money.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{collections::HashMap, str::FromStr};
  19. use lazy_static::lazy_static;
  20. use rand::rngs::OsRng;
  21. use rusqlite::types::Value;
  22. use darkfi::{tx::Transaction, zk::halo2::Field, Error, Result};
  23. use darkfi_money_contract::{
  24. client::{MoneyNote, OwnCoin},
  25. model::{
  26. Coin, MoneyPoWRewardParamsV1, MoneyTokenFreezeParamsV1, MoneyTokenMintParamsV1,
  27. MoneyTransferParamsV1, Nullifier, TokenId, DARK_TOKEN_ID,
  28. },
  29. MoneyFunction,
  30. };
  31. use darkfi_sdk::{
  32. bridgetree,
  33. crypto::{
  34. note::AeadEncryptedNote, BaseBlind, FuncId, Keypair, MerkleNode, MerkleTree, PublicKey,
  35. ScalarBlind, SecretKey, MONEY_CONTRACT_ID,
  36. },
  37. pasta::pallas,
  38. };
  39. use darkfi_serial::{deserialize, serialize};
  40. use crate::{
  41. convert_named_params,
  42. error::{WalletDbError, WalletDbResult},
  43. kaching, Drk,
  44. };
  45. // Wallet SQL table constant names. These have to represent the `wallet.sql`
  46. // SQL schema. Table names are prefixed with the contract ID to avoid collisions.
  47. lazy_static! {
  48. pub static ref MONEY_INFO_TABLE: String =
  49. format!("{}_money_info", MONEY_CONTRACT_ID.to_string());
  50. pub static ref MONEY_TREE_TABLE: String =
  51. format!("{}_money_tree", MONEY_CONTRACT_ID.to_string());
  52. pub static ref MONEY_KEYS_TABLE: String =
  53. format!("{}_money_keys", MONEY_CONTRACT_ID.to_string());
  54. pub static ref MONEY_COINS_TABLE: String =
  55. format!("{}_money_coins", MONEY_CONTRACT_ID.to_string());
  56. pub static ref MONEY_TOKENS_TABLE: String =
  57. format!("{}_money_tokens", MONEY_CONTRACT_ID.to_string());
  58. pub static ref MONEY_ALIASES_TABLE: String =
  59. format!("{}_money_aliases", MONEY_CONTRACT_ID.to_string());
  60. }
  61. // MONEY_INFO_TABLE
  62. pub const MONEY_INFO_COL_LAST_SCANNED_BLOCK: &str = "last_scanned_block";
  63. // MONEY_TREE_TABLE
  64. pub const MONEY_TREE_COL_TREE: &str = "tree";
  65. // MONEY_KEYS_TABLE
  66. pub const MONEY_KEYS_COL_KEY_ID: &str = "key_id";
  67. pub const MONEY_KEYS_COL_IS_DEFAULT: &str = "is_default";
  68. pub const MONEY_KEYS_COL_PUBLIC: &str = "public";
  69. pub const MONEY_KEYS_COL_SECRET: &str = "secret";
  70. // MONEY_COINS_TABLE
  71. pub const MONEY_COINS_COL_COIN: &str = "coin";
  72. pub const MONEY_COINS_COL_IS_SPENT: &str = "is_spent";
  73. pub const MONEY_COINS_COL_VALUE: &str = "value";
  74. pub const MONEY_COINS_COL_TOKEN_ID: &str = "token_id";
  75. pub const MONEY_COINS_COL_SPEND_HOOK: &str = "spend_hook";
  76. pub const MONEY_COINS_COL_USER_DATA: &str = "user_data";
  77. pub const MONEY_COINS_COL_COIN_BLIND: &str = "coin_blind";
  78. pub const MONEY_COINS_COL_VALUE_BLIND: &str = "value_blind";
  79. pub const MONEY_COINS_COL_TOKEN_BLIND: &str = "token_blind";
  80. pub const MONEY_COINS_COL_SECRET: &str = "secret";
  81. pub const MONEY_COINS_COL_NULLIFIER: &str = "nullifier";
  82. pub const MONEY_COINS_COL_LEAF_POSITION: &str = "leaf_position";
  83. pub const MONEY_COINS_COL_MEMO: &str = "memo";
  84. // MONEY_TOKENS_TABLE
  85. pub const MONEY_TOKENS_COL_MINT_AUTHORITY: &str = "mint_authority";
  86. pub const MONEY_TOKENS_COL_TOKEN_ID: &str = "token_id";
  87. pub const MONEY_TOKENS_COL_IS_FROZEN: &str = "is_frozen";
  88. // MONEY_ALIASES_TABLE
  89. pub const MONEY_ALIASES_COL_ALIAS: &str = "alias";
  90. pub const MONEY_ALIASES_COL_TOKEN_ID: &str = "token_id";
  91. pub const BALANCE_BASE10_DECIMALS: usize = 8;
  92. impl Drk {
  93. /// Initialize wallet with tables for the Money contract.
  94. pub async fn initialize_money(&self) -> WalletDbResult<()> {
  95. // Initialize Money wallet schema
  96. let wallet_schema = include_str!("../money.sql");
  97. self.wallet.exec_batch_sql(wallet_schema).await?;
  98. // Check if we have to initialize the Merkle tree.
  99. // We check if we find a row in the tree table, and if not, we create a
  100. // new tree and push it into the table.
  101. // For now, on success, we don't care what's returned, but in the future
  102. // we should actually check it.
  103. if self.get_money_tree().await.is_err() {
  104. println!("Initializing Money Merkle tree");
  105. let mut tree = MerkleTree::new(100);
  106. tree.append(MerkleNode::from(pallas::Base::ZERO));
  107. let _ = tree.mark().unwrap();
  108. self.put_money_tree(&tree).await?;
  109. println!("Successfully initialized Merkle tree for the Money contract");
  110. }
  111. // We maintain the last scanned block as part of the Money contract,
  112. // but at this moment it is also somewhat applicable to DAO scans.
  113. if self.last_scanned_block().await.is_err() {
  114. let query = format!(
  115. "INSERT INTO {} ({}) VALUES (?1);",
  116. *MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_BLOCK
  117. );
  118. self.wallet.exec_sql(&query, rusqlite::params![0]).await?;
  119. }
  120. // Insert DRK alias
  121. self.add_alias("DRK".to_string(), *DARK_TOKEN_ID).await?;
  122. Ok(())
  123. }
  124. /// Generate a new keypair and place it into the wallet.
  125. pub async fn money_keygen(&self) -> WalletDbResult<()> {
  126. println!("Generating a new keypair");
  127. // TODO: We might want to have hierarchical deterministic key derivation.
  128. let keypair = Keypair::random(&mut OsRng);
  129. let is_default = 0;
  130. let query = format!(
  131. "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3);",
  132. *MONEY_KEYS_TABLE,
  133. MONEY_KEYS_COL_IS_DEFAULT,
  134. MONEY_KEYS_COL_PUBLIC,
  135. MONEY_KEYS_COL_SECRET
  136. );
  137. self.wallet
  138. .exec_sql(
  139. &query,
  140. rusqlite::params![
  141. is_default,
  142. serialize(&keypair.public),
  143. serialize(&keypair.secret)
  144. ],
  145. )
  146. .await?;
  147. println!("New address:");
  148. println!("{}", keypair.public);
  149. Ok(())
  150. }
  151. /// Fetch default secret key from the wallet.
  152. pub async fn default_secret(&self) -> Result<SecretKey> {
  153. let row = match self
  154. .wallet
  155. .query_single(
  156. &MONEY_KEYS_TABLE,
  157. &[MONEY_KEYS_COL_SECRET],
  158. convert_named_params! {(MONEY_KEYS_COL_IS_DEFAULT, 1)},
  159. )
  160. .await
  161. {
  162. Ok(r) => r,
  163. Err(e) => {
  164. return Err(Error::RusqliteError(format!(
  165. "[default_secret] Default secret key retrieval failed: {e:?}"
  166. )))
  167. }
  168. };
  169. let Value::Blob(ref key_bytes) = row[0] else {
  170. return Err(Error::ParseFailed("[default_secret] Key bytes parsing failed"))
  171. };
  172. let secret_key: SecretKey = deserialize(key_bytes)?;
  173. Ok(secret_key)
  174. }
  175. /// Fetch default pubkey from the wallet.
  176. pub async fn default_address(&self) -> Result<PublicKey> {
  177. let row = match self
  178. .wallet
  179. .query_single(
  180. &MONEY_KEYS_TABLE,
  181. &[MONEY_KEYS_COL_PUBLIC],
  182. convert_named_params! {(MONEY_KEYS_COL_IS_DEFAULT, 1)},
  183. )
  184. .await
  185. {
  186. Ok(r) => r,
  187. Err(e) => {
  188. return Err(Error::RusqliteError(format!(
  189. "[default_address] Default address retrieval failed: {e:?}"
  190. )))
  191. }
  192. };
  193. let Value::Blob(ref key_bytes) = row[0] else {
  194. return Err(Error::ParseFailed("[default_address] Key bytes parsing failed"))
  195. };
  196. let public_key: PublicKey = deserialize(key_bytes)?;
  197. Ok(public_key)
  198. }
  199. /// Set provided index address as default in the wallet.
  200. pub async fn set_default_address(&self, idx: usize) -> WalletDbResult<()> {
  201. // First we update previous default record
  202. let is_default = 0;
  203. let query = format!("UPDATE {} SET {} = ?1", *MONEY_KEYS_TABLE, MONEY_KEYS_COL_IS_DEFAULT,);
  204. self.wallet.exec_sql(&query, rusqlite::params![is_default]).await?;
  205. // and then we set the new one
  206. let is_default = 1;
  207. let query = format!(
  208. "UPDATE {} SET {} = ?1 WHERE {} = ?2",
  209. *MONEY_KEYS_TABLE, MONEY_KEYS_COL_IS_DEFAULT, MONEY_KEYS_COL_KEY_ID,
  210. );
  211. self.wallet.exec_sql(&query, rusqlite::params![is_default, idx]).await
  212. }
  213. /// Fetch all pukeys from the wallet.
  214. pub async fn addresses(&self) -> Result<Vec<(u64, PublicKey, SecretKey, u64)>> {
  215. let rows = match self.wallet.query_multiple(&MONEY_KEYS_TABLE, &[], &[]).await {
  216. Ok(r) => r,
  217. Err(e) => {
  218. return Err(Error::RusqliteError(format!(
  219. "[addresses] Addresses retrieval failed: {e:?}"
  220. )))
  221. }
  222. };
  223. let mut vec = Vec::with_capacity(rows.len());
  224. for row in rows {
  225. let Value::Integer(key_id) = row[0] else {
  226. return Err(Error::ParseFailed("[addresses] Key ID parsing failed"))
  227. };
  228. let Ok(key_id) = u64::try_from(key_id) else {
  229. return Err(Error::ParseFailed("[addresses] Key ID parsing failed"))
  230. };
  231. let Value::Integer(is_default) = row[1] else {
  232. return Err(Error::ParseFailed("[addresses] Is default parsing failed"))
  233. };
  234. let Ok(is_default) = u64::try_from(is_default) else {
  235. return Err(Error::ParseFailed("[addresses] Is default parsing failed"))
  236. };
  237. let Value::Blob(ref key_bytes) = row[2] else {
  238. return Err(Error::ParseFailed("[addresses] Public key bytes parsing failed"))
  239. };
  240. let public_key: PublicKey = deserialize(key_bytes)?;
  241. let Value::Blob(ref key_bytes) = row[3] else {
  242. return Err(Error::ParseFailed("[addresses] Secret key bytes parsing failed"))
  243. };
  244. let secret_key: SecretKey = deserialize(key_bytes)?;
  245. vec.push((key_id, public_key, secret_key, is_default));
  246. }
  247. Ok(vec)
  248. }
  249. /// Fetch all secret keys from the wallet.
  250. pub async fn get_money_secrets(&self) -> Result<Vec<SecretKey>> {
  251. let rows = match self
  252. .wallet
  253. .query_multiple(&MONEY_KEYS_TABLE, &[MONEY_KEYS_COL_SECRET], &[])
  254. .await
  255. {
  256. Ok(r) => r,
  257. Err(e) => {
  258. return Err(Error::RusqliteError(format!(
  259. "[get_money_secrets] Secret keys retrieval failed: {e:?}"
  260. )))
  261. }
  262. };
  263. let mut secrets = Vec::with_capacity(rows.len());
  264. // Let's scan through the rows and see if we got anything.
  265. for row in rows {
  266. let Value::Blob(ref key_bytes) = row[0] else {
  267. return Err(Error::ParseFailed(
  268. "[get_money_secrets] Secret key bytes parsing failed",
  269. ))
  270. };
  271. let secret_key: SecretKey = deserialize(key_bytes)?;
  272. secrets.push(secret_key);
  273. }
  274. Ok(secrets)
  275. }
  276. /// Import given secret keys into the wallet.
  277. /// If the key already exists, it will be skipped.
  278. /// Returns the respective PublicKey objects for the imported keys.
  279. pub async fn import_money_secrets(&self, secrets: Vec<SecretKey>) -> Result<Vec<PublicKey>> {
  280. let existing_secrets = self.get_money_secrets().await?;
  281. let mut ret = Vec::with_capacity(secrets.len());
  282. for secret in secrets {
  283. // Check if secret already exists
  284. if existing_secrets.contains(&secret) {
  285. println!("Existing key found: {secret}");
  286. continue
  287. }
  288. ret.push(PublicKey::from_secret(secret));
  289. let is_default = 0;
  290. let public = serialize(&PublicKey::from_secret(secret));
  291. let secret = serialize(&secret);
  292. let query = format!(
  293. "INSERT INTO {} ({}, {}, {}) VALUES (?1, ?2, ?3);",
  294. *MONEY_KEYS_TABLE,
  295. MONEY_KEYS_COL_IS_DEFAULT,
  296. MONEY_KEYS_COL_PUBLIC,
  297. MONEY_KEYS_COL_SECRET
  298. );
  299. if let Err(e) =
  300. self.wallet.exec_sql(&query, rusqlite::params![is_default, public, secret]).await
  301. {
  302. return Err(Error::RusqliteError(format!(
  303. "[import_money_secrets] Inserting new address failed: {e:?}"
  304. )))
  305. }
  306. }
  307. Ok(ret)
  308. }
  309. /// Fetch known unspent balances from the wallet and return them as a hashmap.
  310. pub async fn money_balance(&self) -> Result<HashMap<String, u64>> {
  311. let mut coins = self.get_coins(false).await?;
  312. coins.retain(|x| x.0.note.spend_hook == FuncId::none());
  313. // Fill this map with balances
  314. let mut balmap: HashMap<String, u64> = HashMap::new();
  315. for coin in coins {
  316. let mut value = coin.0.note.value;
  317. if let Some(prev) = balmap.get(&coin.0.note.token_id.to_string()) {
  318. value += prev;
  319. }
  320. balmap.insert(coin.0.note.token_id.to_string(), value);
  321. }
  322. Ok(balmap)
  323. }
  324. /// Fetch all coins and their metadata related to the Money contract from the wallet.
  325. /// Optionally also fetch spent ones.
  326. /// The boolean in the returned tuple notes if the coin was marked as spent.
  327. pub async fn get_coins(&self, fetch_spent: bool) -> Result<Vec<(OwnCoin, bool)>> {
  328. let query = if fetch_spent {
  329. self.wallet.query_multiple(&MONEY_COINS_TABLE, &[], &[]).await
  330. } else {
  331. self.wallet
  332. .query_multiple(
  333. &MONEY_COINS_TABLE,
  334. &[],
  335. convert_named_params! {(MONEY_COINS_COL_IS_SPENT, false)},
  336. )
  337. .await
  338. };
  339. let rows = match query {
  340. Ok(r) => r,
  341. Err(e) => {
  342. return Err(Error::RusqliteError(format!(
  343. "[get_coins] Coins retrieval failed: {e:?}"
  344. )))
  345. }
  346. };
  347. let mut owncoins = Vec::with_capacity(rows.len());
  348. for row in rows {
  349. let Value::Blob(ref coin_bytes) = row[0] else {
  350. return Err(Error::ParseFailed("[get_coins] Coin bytes parsing failed"))
  351. };
  352. let coin: Coin = deserialize(coin_bytes)?;
  353. let Value::Integer(is_spent) = row[1] else {
  354. return Err(Error::ParseFailed("[get_coins] Is spent parsing failed"))
  355. };
  356. let Ok(is_spent) = u64::try_from(is_spent) else {
  357. return Err(Error::ParseFailed("[get_coins] Is spent parsing failed"))
  358. };
  359. let is_spent = is_spent > 0;
  360. let Value::Blob(ref value_bytes) = row[2] else {
  361. return Err(Error::ParseFailed("[get_coins] Value bytes parsing failed"))
  362. };
  363. let value: u64 = deserialize(value_bytes)?;
  364. let Value::Blob(ref token_id_bytes) = row[3] else {
  365. return Err(Error::ParseFailed("[get_coins] Token ID bytes parsing failed"))
  366. };
  367. let token_id: TokenId = deserialize(token_id_bytes)?;
  368. let Value::Blob(ref spend_hook_bytes) = row[4] else {
  369. return Err(Error::ParseFailed("[get_coins] Spend hook bytes parsing failed"))
  370. };
  371. let spend_hook: pallas::Base = deserialize(spend_hook_bytes)?;
  372. let Value::Blob(ref user_data_bytes) = row[5] else {
  373. return Err(Error::ParseFailed("[get_coins] User data bytes parsing failed"))
  374. };
  375. let user_data: pallas::Base = deserialize(user_data_bytes)?;
  376. let Value::Blob(ref coin_blind_bytes) = row[6] else {
  377. return Err(Error::ParseFailed("[get_coins] Coin blind bytes parsing failed"))
  378. };
  379. let coin_blind: BaseBlind = deserialize(coin_blind_bytes)?;
  380. let Value::Blob(ref value_blind_bytes) = row[7] else {
  381. return Err(Error::ParseFailed("[get_coins] Value blind bytes parsing failed"))
  382. };
  383. let value_blind: ScalarBlind = deserialize(value_blind_bytes)?;
  384. let Value::Blob(ref token_blind_bytes) = row[8] else {
  385. return Err(Error::ParseFailed("[get_coins] Token blind bytes parsing failed"))
  386. };
  387. let token_blind: BaseBlind = deserialize(token_blind_bytes)?;
  388. let Value::Blob(ref secret_bytes) = row[9] else {
  389. return Err(Error::ParseFailed("[get_coins] Secret bytes parsing failed"))
  390. };
  391. let secret: SecretKey = deserialize(secret_bytes)?;
  392. // TODO: Remove from SQL store, can be derived ondemand
  393. let Value::Blob(ref nullifier_bytes) = row[10] else {
  394. return Err(Error::ParseFailed("[get_coins] Nullifier bytes parsing failed"))
  395. };
  396. let _nullifier: Nullifier = deserialize(nullifier_bytes)?;
  397. let Value::Blob(ref leaf_position_bytes) = row[11] else {
  398. return Err(Error::ParseFailed("[get_coins] Leaf position bytes parsing failed"))
  399. };
  400. let leaf_position: bridgetree::Position = deserialize(leaf_position_bytes)?;
  401. let Value::Blob(ref memo) = row[12] else {
  402. return Err(Error::ParseFailed("[get_coins] Memo parsing failed"))
  403. };
  404. let note = MoneyNote {
  405. value,
  406. token_id,
  407. spend_hook: spend_hook.into(),
  408. user_data,
  409. coin_blind,
  410. value_blind,
  411. token_blind,
  412. memo: memo.clone(),
  413. };
  414. let owncoin = OwnCoin { coin, note, secret, leaf_position };
  415. owncoins.push((owncoin, is_spent))
  416. }
  417. Ok(owncoins)
  418. }
  419. /// Create an alias record for provided Token ID.
  420. pub async fn add_alias(&self, alias: String, token_id: TokenId) -> WalletDbResult<()> {
  421. println!("Generating alias {alias} for Token: {token_id}");
  422. let query = format!(
  423. "INSERT OR REPLACE INTO {} ({}, {}) VALUES (?1, ?2);",
  424. *MONEY_ALIASES_TABLE, MONEY_ALIASES_COL_ALIAS, MONEY_ALIASES_COL_TOKEN_ID,
  425. );
  426. self.wallet
  427. .exec_sql(&query, rusqlite::params![serialize(&alias), serialize(&token_id)])
  428. .await
  429. }
  430. /// Fetch all aliases from the wallet.
  431. /// Optionally filter using alias name and/or token id.
  432. pub async fn get_aliases(
  433. &self,
  434. alias_filter: Option<String>,
  435. token_id_filter: Option<TokenId>,
  436. ) -> Result<HashMap<String, TokenId>> {
  437. let rows = match self.wallet.query_multiple(&MONEY_ALIASES_TABLE, &[], &[]).await {
  438. Ok(r) => r,
  439. Err(e) => {
  440. return Err(Error::RusqliteError(format!(
  441. "[get_aliases] Aliases retrieval failed: {e:?}"
  442. )))
  443. }
  444. };
  445. // Fill this map with aliases
  446. let mut map: HashMap<String, TokenId> = HashMap::new();
  447. for row in rows {
  448. let Value::Blob(ref alias_bytes) = row[0] else {
  449. return Err(Error::ParseFailed("[get_aliases] Alias bytes parsing failed"))
  450. };
  451. let alias: String = deserialize(alias_bytes)?;
  452. if alias_filter.is_some() && alias_filter.as_ref().unwrap() != &alias {
  453. continue
  454. }
  455. let Value::Blob(ref token_id_bytes) = row[1] else {
  456. return Err(Error::ParseFailed("[get_aliases] TokenId bytes parsing failed"))
  457. };
  458. let token_id: TokenId = deserialize(token_id_bytes)?;
  459. if token_id_filter.is_some() && token_id_filter.as_ref().unwrap() != &token_id {
  460. continue
  461. }
  462. map.insert(alias, token_id);
  463. }
  464. Ok(map)
  465. }
  466. /// Fetch all aliases from the wallet, mapped by token id.
  467. pub async fn get_aliases_mapped_by_token(&self) -> Result<HashMap<String, String>> {
  468. let aliases = self.get_aliases(None, None).await?;
  469. let mut map: HashMap<String, String> = HashMap::new();
  470. for (alias, token_id) in aliases {
  471. let aliases_string = if let Some(prev) = map.get(&token_id.to_string()) {
  472. format!("{}, {}", prev, alias)
  473. } else {
  474. alias
  475. };
  476. map.insert(token_id.to_string(), aliases_string);
  477. }
  478. Ok(map)
  479. }
  480. /// Remove provided alias record from the wallet database.
  481. pub async fn remove_alias(&self, alias: String) -> WalletDbResult<()> {
  482. println!("Removing alias: {alias}");
  483. let query = format!(
  484. "DELETE FROM {} WHERE {} = ?1;",
  485. *MONEY_ALIASES_TABLE, MONEY_ALIASES_COL_ALIAS,
  486. );
  487. self.wallet.exec_sql(&query, rusqlite::params![serialize(&alias)]).await
  488. }
  489. /// Mark a given coin in the wallet as unspent.
  490. pub async fn unspend_coin(&self, coin: &Coin) -> WalletDbResult<()> {
  491. let is_spend = 0;
  492. let query = format!(
  493. "UPDATE {} SET {} = ?1 WHERE {} = ?2",
  494. *MONEY_COINS_TABLE, MONEY_COINS_COL_IS_SPENT, MONEY_COINS_COL_COIN,
  495. );
  496. self.wallet.exec_sql(&query, rusqlite::params![is_spend, serialize(&coin.inner())]).await
  497. }
  498. /// Replace the Money Merkle tree in the wallet.
  499. pub async fn put_money_tree(&self, tree: &MerkleTree) -> WalletDbResult<()> {
  500. // First we remove old record
  501. let query = format!("DELETE FROM {};", *MONEY_TREE_TABLE);
  502. self.wallet.exec_sql(&query, &[]).await?;
  503. // then we insert the new one
  504. let query =
  505. format!("INSERT INTO {} ({}) VALUES (?1);", *MONEY_TREE_TABLE, MONEY_TREE_COL_TREE,);
  506. self.wallet.exec_sql(&query, rusqlite::params![serialize(tree)]).await
  507. }
  508. /// Fetch the Money Merkle tree from the wallet.
  509. pub async fn get_money_tree(&self) -> Result<MerkleTree> {
  510. let row =
  511. match self.wallet.query_single(&MONEY_TREE_TABLE, &[MONEY_TREE_COL_TREE], &[]).await {
  512. Ok(r) => r,
  513. Err(e) => {
  514. return Err(Error::RusqliteError(format!(
  515. "[get_money_tree] Tree retrieval failed: {e:?}"
  516. )))
  517. }
  518. };
  519. let Value::Blob(ref tree_bytes) = row[0] else {
  520. return Err(Error::ParseFailed("[get_money_tree] Tree bytes parsing failed"))
  521. };
  522. let tree = deserialize(tree_bytes)?;
  523. Ok(tree)
  524. }
  525. /// Get the last scanned block height from the wallet.
  526. pub async fn last_scanned_block(&self) -> WalletDbResult<u64> {
  527. let ret = self
  528. .wallet
  529. .query_single(&MONEY_INFO_TABLE, &[MONEY_INFO_COL_LAST_SCANNED_BLOCK], &[])
  530. .await?;
  531. let Value::Integer(height) = ret[0] else {
  532. return Err(WalletDbError::ParseColumnValueError);
  533. };
  534. let Ok(height) = u64::try_from(height) else {
  535. return Err(WalletDbError::ParseColumnValueError);
  536. };
  537. Ok(height)
  538. }
  539. /// Append data related to Money contract transactions into the wallet database.
  540. pub async fn apply_tx_money_data(&self, tx: &Transaction, _confirm: bool) -> Result<()> {
  541. let cid = *MONEY_CONTRACT_ID;
  542. let mut nullifiers: Vec<Nullifier> = vec![];
  543. let mut coins: Vec<Coin> = vec![];
  544. let mut notes: Vec<AeadEncryptedNote> = vec![];
  545. let mut freezes: Vec<TokenId> = vec![];
  546. for (i, call) in tx.calls.iter().enumerate() {
  547. if call.data.contract_id == cid && call.data.data[0] == MoneyFunction::PoWRewardV1 as u8
  548. {
  549. println!("Found Money::PoWRewardV1 in call {i}");
  550. let params: MoneyPoWRewardParamsV1 = deserialize(&call.data.data[1..])?;
  551. coins.push(params.output.coin);
  552. notes.push(params.output.note);
  553. continue
  554. }
  555. if call.data.contract_id == cid && call.data.data[0] == MoneyFunction::TransferV1 as u8
  556. {
  557. println!("Found Money::TransferV1 in call {i}");
  558. let params: MoneyTransferParamsV1 = deserialize(&call.data.data[1..])?;
  559. for input in params.inputs {
  560. nullifiers.push(input.nullifier);
  561. }
  562. for output in params.outputs {
  563. coins.push(output.coin);
  564. notes.push(output.note);
  565. }
  566. continue
  567. }
  568. if call.data.contract_id == cid && call.data.data[0] == MoneyFunction::OtcSwapV1 as u8 {
  569. println!("Found Money::OtcSwapV1 in call {i}");
  570. let params: MoneyTransferParamsV1 = deserialize(&call.data.data[1..])?;
  571. for input in params.inputs {
  572. nullifiers.push(input.nullifier);
  573. }
  574. for output in params.outputs {
  575. coins.push(output.coin);
  576. notes.push(output.note);
  577. }
  578. continue
  579. }
  580. if call.data.contract_id == cid && call.data.data[0] == MoneyFunction::TokenMintV1 as u8
  581. {
  582. println!("Found Money::MintV1 in call {i}");
  583. let params: MoneyTokenMintParamsV1 = deserialize(&call.data.data[1..])?;
  584. coins.push(params.coin);
  585. //notes.push(output.note);
  586. continue
  587. }
  588. if call.data.contract_id == cid &&
  589. call.data.data[0] == MoneyFunction::TokenFreezeV1 as u8
  590. {
  591. println!("Found Money::FreezeV1 in call {i}");
  592. let params: MoneyTokenFreezeParamsV1 = deserialize(&call.data.data[1..])?;
  593. let token_id = TokenId::derive_public(params.mint_public);
  594. freezes.push(token_id);
  595. }
  596. }
  597. let secrets = self.get_money_secrets().await?;
  598. let dao_secrets = self.get_dao_secrets().await?;
  599. let mut tree = self.get_money_tree().await?;
  600. let mut owncoins = vec![];
  601. for (coin, note) in coins.iter().zip(notes.iter()) {
  602. // Append the new coin to the Merkle tree. Every coin has to be added.
  603. tree.append(MerkleNode::from(coin.inner()));
  604. // Attempt to decrypt the note
  605. for secret in secrets.iter().chain(dao_secrets.iter()) {
  606. if let Ok(note) = note.decrypt::<MoneyNote>(secret) {
  607. println!("Successfully decrypted a Money Note");
  608. println!("Witnessing coin in Merkle tree");
  609. let leaf_position = tree.mark().unwrap();
  610. let owncoin =
  611. OwnCoin { coin: *coin, note: note.clone(), secret: *secret, leaf_position };
  612. owncoins.push(owncoin);
  613. }
  614. }
  615. }
  616. if let Err(e) = self.put_money_tree(&tree).await {
  617. return Err(Error::RusqliteError(format!(
  618. "[apply_tx_money_data] Put Money tree failed: {e:?}"
  619. )))
  620. }
  621. if !nullifiers.is_empty() {
  622. self.mark_spent_coins(&nullifiers).await?;
  623. }
  624. // This is the SQL query we'll be executing to insert new coins
  625. // into the wallet
  626. let query = format!(
  627. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13);",
  628. *MONEY_COINS_TABLE,
  629. MONEY_COINS_COL_COIN,
  630. MONEY_COINS_COL_IS_SPENT,
  631. MONEY_COINS_COL_VALUE,
  632. MONEY_COINS_COL_TOKEN_ID,
  633. MONEY_COINS_COL_SPEND_HOOK,
  634. MONEY_COINS_COL_USER_DATA,
  635. MONEY_COINS_COL_COIN_BLIND,
  636. MONEY_COINS_COL_VALUE_BLIND,
  637. MONEY_COINS_COL_TOKEN_BLIND,
  638. MONEY_COINS_COL_SECRET,
  639. MONEY_COINS_COL_NULLIFIER,
  640. MONEY_COINS_COL_LEAF_POSITION,
  641. MONEY_COINS_COL_MEMO,
  642. );
  643. println!("Found {} OwnCoin(s) in transaction", owncoins.len());
  644. for owncoin in &owncoins {
  645. println!("OwnCoin: {:?}", owncoin.coin);
  646. let params = rusqlite::params![
  647. serialize(&owncoin.coin),
  648. 0, // <-- is_spent
  649. serialize(&owncoin.note.value),
  650. serialize(&owncoin.note.token_id),
  651. serialize(&owncoin.note.spend_hook),
  652. serialize(&owncoin.note.user_data),
  653. serialize(&owncoin.note.coin_blind),
  654. serialize(&owncoin.note.value_blind),
  655. serialize(&owncoin.note.token_blind),
  656. serialize(&owncoin.secret),
  657. serialize(&owncoin.nullifier()),
  658. serialize(&owncoin.leaf_position),
  659. serialize(&owncoin.note.memo),
  660. ];
  661. if let Err(e) = self.wallet.exec_sql(&query, params).await {
  662. return Err(Error::RusqliteError(format!(
  663. "[apply_tx_money_data] Inserting Money coin failed: {e:?}"
  664. )))
  665. }
  666. }
  667. for token_id in freezes {
  668. let query = format!(
  669. "UPDATE {} SET {} = 1 WHERE {} = ?1;",
  670. *MONEY_TOKENS_TABLE, MONEY_TOKENS_COL_IS_FROZEN, MONEY_TOKENS_COL_TOKEN_ID,
  671. );
  672. if let Err(e) =
  673. self.wallet.exec_sql(&query, rusqlite::params![serialize(&token_id)]).await
  674. {
  675. return Err(Error::RusqliteError(format!(
  676. "[apply_tx_money_data] Inserting Money coin failed: {e:?}"
  677. )))
  678. }
  679. }
  680. if !owncoins.is_empty() {
  681. kaching().await;
  682. }
  683. Ok(())
  684. }
  685. /// Mark a coin in the wallet as spent
  686. pub async fn mark_spent_coin(&self, coin: &Coin) -> WalletDbResult<()> {
  687. let query = format!(
  688. "UPDATE {} SET {} = ?1 WHERE {} = ?2;",
  689. *MONEY_COINS_TABLE, MONEY_COINS_COL_IS_SPENT, MONEY_COINS_COL_COIN
  690. );
  691. let is_spent = 1;
  692. self.wallet.exec_sql(&query, rusqlite::params![is_spent, serialize(&coin.inner())]).await
  693. }
  694. /// Marks all coins in the wallet as spent, if their nullifier is in the given set
  695. pub async fn mark_spent_coins(&self, nullifiers: &[Nullifier]) -> Result<()> {
  696. if nullifiers.is_empty() {
  697. return Ok(())
  698. }
  699. for (coin, _) in self.get_coins(false).await? {
  700. if nullifiers.contains(&coin.nullifier()) {
  701. if let Err(e) = self.mark_spent_coin(&coin.coin).await {
  702. return Err(Error::RusqliteError(format!(
  703. "[mark_spent_coins] Marking spent coin failed: {e:?}"
  704. )))
  705. }
  706. }
  707. }
  708. Ok(())
  709. }
  710. /// Reset the Money Merkle tree in the wallet
  711. pub async fn reset_money_tree(&self) -> WalletDbResult<()> {
  712. println!("Resetting Money Merkle tree");
  713. let mut tree = MerkleTree::new(100);
  714. tree.append(MerkleNode::from(pallas::Base::ZERO));
  715. let _ = tree.mark().unwrap();
  716. self.put_money_tree(&tree).await?;
  717. println!("Successfully reset Money Merkle tree");
  718. Ok(())
  719. }
  720. /// Reset the Money coins in the wallet
  721. pub async fn reset_money_coins(&self) -> WalletDbResult<()> {
  722. println!("Resetting coins");
  723. let query = format!("DELETE FROM {};", *MONEY_COINS_TABLE);
  724. self.wallet.exec_sql(&query, &[]).await?;
  725. println!("Successfully reset coins");
  726. Ok(())
  727. }
  728. /// Retrieve token by provided string.
  729. /// Input string represents either an alias or a token id.
  730. pub async fn get_token(&self, input: String) -> Result<TokenId> {
  731. // Check if input is an alias(max 5 characters)
  732. if input.chars().count() <= 5 {
  733. let aliases = self.get_aliases(Some(input.clone()), None).await?;
  734. if let Some(token_id) = aliases.get(&input) {
  735. return Ok(*token_id)
  736. }
  737. }
  738. // Else parse input
  739. Ok(TokenId::from_str(input.as_str())?)
  740. }
  741. }