walletdb.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. use crate::client::ClientFailed;
  2. use crate::crypto::{
  3. coin::Coin, merkle::IncrementalWitness, merkle_node::MerkleNode, note::Note, OwnCoins,
  4. };
  5. use crate::serial;
  6. use crate::serial::{deserialize, serialize, Decodable, Encodable};
  7. use crate::{Error, Result};
  8. use async_std::sync::{Arc, Mutex};
  9. use ff::Field;
  10. use log::*;
  11. use rand::rngs::OsRng;
  12. use rusqlite::{named_params, params, Connection};
  13. use std::path::PathBuf;
  14. pub type WalletPtr = Arc<WalletDb>;
  15. pub struct WalletDb {
  16. pub path: PathBuf,
  17. pub secrets: Vec<jubjub::Fr>,
  18. pub cashier_secrets: Vec<jubjub::Fr>,
  19. pub coins: Mutex<Vec<Coin>>,
  20. pub notes: Mutex<Vec<Note>>,
  21. pub witnesses: Mutex<Vec<IncrementalWitness<MerkleNode>>>,
  22. pub cashier_public: jubjub::SubgroupPoint,
  23. pub public: jubjub::SubgroupPoint,
  24. pub password: String,
  25. }
  26. impl WalletDb {
  27. pub fn new(path: &std::path::PathBuf, password: String) -> Result<Self> {
  28. debug!(target: "walletdb", "new() Constructor called");
  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: path.to_owned(),
  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::from(ClientFailed::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 put_keypair(&self, key_public: Vec<u8>, key_private: Vec<u8>) -> Result<()> {
  169. let conn = Connection::open(&self.path)?;
  170. conn.pragma_update(None, "key", &self.password)?;
  171. conn.execute(
  172. "INSERT INTO keys(key_public, key_private) VALUES (?1, ?2)",
  173. params![key_public, key_private],
  174. )?;
  175. Ok(())
  176. }
  177. pub fn put_cashier_pub(&self, key_public: Vec<u8>) -> Result<()> {
  178. debug!(target: "save_cash_key", "Save cashier keys...");
  179. let conn = Connection::open(&self.path)?;
  180. conn.pragma_update(None, "key", &self.password)?;
  181. conn.execute(
  182. "INSERT INTO cashier(key_public) VALUES (?1)",
  183. params![key_public],
  184. )?;
  185. Ok(())
  186. }
  187. pub fn get_public(&self) -> Result<jubjub::SubgroupPoint> {
  188. debug!(target: "get", "Returning keys...");
  189. let conn = Connection::open(&self.path)?;
  190. conn.pragma_update(None, "key", &self.password)?;
  191. let mut stmt = conn.prepare("SELECT key_public FROM keys")?;
  192. // this just gets the first key. maybe we should randomize this
  193. let key_iter = stmt.query_map([], |row| row.get(0))?;
  194. let mut pub_keys = Vec::new();
  195. for key in key_iter {
  196. pub_keys.push(key?);
  197. }
  198. let public: jubjub::SubgroupPoint = self.get_value_deserialized(
  199. pub_keys
  200. .pop()
  201. .expect("unable to load public_key from walletdb"),
  202. )?;
  203. Ok(public)
  204. }
  205. pub fn get_cashier_public(&self) -> Result<jubjub::SubgroupPoint> {
  206. debug!(target: "get_cashier_public", "Returning keys...");
  207. let conn = Connection::open(&self.path)?;
  208. conn.pragma_update(None, "key", &self.password)?;
  209. let mut stmt = conn.prepare("SELECT key_public FROM cashier")?;
  210. let key_iter = stmt.query_map([], |row| row.get(0))?;
  211. let mut pub_keys = Vec::new();
  212. for key in key_iter {
  213. pub_keys.push(key?);
  214. }
  215. let public: jubjub::SubgroupPoint = self.get_value_deserialized(
  216. pub_keys
  217. .pop()
  218. .expect("unable to load cashier public_key from walletdb"),
  219. )?;
  220. Ok(public)
  221. }
  222. pub fn get_private(&self) -> Result<jubjub::Fr> {
  223. debug!(target: "get", "Returning keys...");
  224. let conn = Connection::open(&self.path)?;
  225. conn.pragma_update(None, "key", &self.password)?;
  226. let mut stmt = conn.prepare("SELECT key_private FROM keys")?;
  227. let key_iter = stmt.query_map([], |row| row.get(0))?;
  228. let mut keys = Vec::new();
  229. for key in key_iter {
  230. keys.push(key?);
  231. }
  232. let private: jubjub::Fr = self.get_value_deserialized(
  233. keys.pop()
  234. .expect("unable to load private key from walletdb"),
  235. )?;
  236. Ok(private)
  237. }
  238. pub fn test_wallet(&self) -> Result<()> {
  239. let conn = Connection::open(&self.path)?;
  240. conn.pragma_update(None, "key", &self.password)?;
  241. let mut stmt = conn.prepare("SELECT * FROM keys")?;
  242. let _rows = stmt.query([])?;
  243. Ok(())
  244. }
  245. fn get_tables_name(&self) -> Result<Vec<String>> {
  246. let conn = Connection::open(&self.path)?;
  247. conn.pragma_update(None, "key", &self.password)?;
  248. let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table'")?;
  249. let table_iter = stmt.query_map::<String, _, _>([], |row| row.get(0))?;
  250. let mut tables = Vec::new();
  251. for table in table_iter {
  252. tables.push(table?);
  253. }
  254. Ok(tables)
  255. }
  256. pub fn destory(&self) -> Result<()> {
  257. let conn = Connection::open(&self.path)?;
  258. conn.pragma_update(None, "key", &self.password)?;
  259. for table in self.get_tables_name()?.iter() {
  260. let drop_stmt = format!("DROP TABLE IF EXISTS {}", table);
  261. let drop_stmt = drop_stmt.as_str();
  262. conn.execute(drop_stmt, [])?;
  263. }
  264. Ok(())
  265. }
  266. pub fn get_value_serialized<T: Encodable>(&self, data: &T) -> Result<Vec<u8>> {
  267. let v = serialize(data);
  268. Ok(v)
  269. }
  270. pub fn get_value_deserialized<D: Decodable>(&self, key: Vec<u8>) -> Result<D> {
  271. let v: D = deserialize(&key)?;
  272. Ok(v)
  273. }
  274. }
  275. #[cfg(test)]
  276. mod tests {
  277. use super::*;
  278. use crate::util::join_config_path;
  279. use ff::PrimeField;
  280. #[test]
  281. pub fn test_save_and_load_keypair() -> Result<()> {
  282. let walletdb_path = join_config_path(&PathBuf::from("test_wallet.db"))?;
  283. let wallet = WalletDb::new(&walletdb_path, "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 public2 = wallet.get_public()?;
  291. let secret2 = wallet.get_private()?;
  292. assert_eq!(public, public2);
  293. assert_eq!(secret, secret2);
  294. wallet.destory()?;
  295. Ok(())
  296. }
  297. #[test]
  298. pub fn test_put_and_get_own_coins() -> Result<()> {
  299. let walletdb_path = join_config_path(&PathBuf::from("test2_wallet.db"))?;
  300. let wallet = WalletDb::new(&walletdb_path, "darkfi".into())?;
  301. wallet.init_db()?;
  302. let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
  303. let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  304. let key_public = serial::serialize(&public);
  305. let key_private = serial::serialize(&secret);
  306. wallet.put_keypair(key_public, key_private)?;
  307. let note = Note {
  308. serial: jubjub::Fr::random(&mut OsRng),
  309. value: 110,
  310. asset_id: 1,
  311. coin_blind: jubjub::Fr::random(&mut OsRng),
  312. valcom_blind: jubjub::Fr::random(&mut OsRng),
  313. };
  314. let coin = Coin::new(bls12_381::Scalar::random(&mut OsRng).to_repr());
  315. let mut tree = crate::crypto::merkle::CommitmentTree::empty();
  316. tree.append(MerkleNode::from_coin(&coin))?;
  317. let witness = IncrementalWitness::from_tree(&tree);
  318. wallet.put_own_coins(coin.clone(), note.clone(), witness.clone(), secret)?;
  319. let own_coin = wallet.get_own_coins()?[0].clone();
  320. assert_eq!(&own_coin.1.valcom_blind, &note.valcom_blind);
  321. assert_eq!(&own_coin.1.coin_blind, &note.coin_blind);
  322. assert_eq!(own_coin.2, secret);
  323. assert_eq!(own_coin.3.root(), witness.root());
  324. assert_eq!(own_coin.3.path(), witness.path());
  325. wallet.destory()?;
  326. Ok(())
  327. }
  328. }