rpc.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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::{
  19. collections::{BTreeMap, HashMap},
  20. sync::Arc,
  21. time::Instant,
  22. };
  23. use smol::channel::Sender;
  24. use url::Url;
  25. use darkfi::{
  26. blockchain::BlockInfo,
  27. rpc::{
  28. client::RpcClient,
  29. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResult},
  30. util::JsonValue,
  31. },
  32. system::{ExecutorPtr, Publisher, StoppableTaskPtr},
  33. tx::Transaction,
  34. util::encoding::base64,
  35. Error, Result,
  36. };
  37. use darkfi_dao_contract::model::{DaoBulla, DaoProposalBulla};
  38. use darkfi_money_contract::model::TokenId;
  39. use darkfi_sdk::{
  40. bridgetree::Position,
  41. crypto::{
  42. smt::{PoseidonFp, EMPTY_NODES_FP},
  43. ContractId, MerkleTree, SecretKey, DAO_CONTRACT_ID, DEPLOYOOOR_CONTRACT_ID,
  44. MONEY_CONTRACT_ID,
  45. },
  46. tx::TransactionHash,
  47. };
  48. use darkfi_serial::{deserialize_async, serialize_async};
  49. use crate::{
  50. cache::{CacheOverlay, CacheSmt, CacheSmtStorage, KVDB_MONEY_SMT_TREE},
  51. cli_util::append_or_print,
  52. dao::{KVDB_MERKLE_TREES_DAO_DAOS, KVDB_MERKLE_TREES_DAO_PROPOSALS},
  53. error::{WalletDbError, WalletDbResult},
  54. money::KVDB_MERKLE_TREES_MONEY,
  55. Drk, DrkPtr,
  56. };
  57. /// Structure to hold a JSON-RPC client and its config,
  58. /// so we can recreate it in case of an error.
  59. pub struct DarkfidRpcClient {
  60. endpoint: Url,
  61. ex: ExecutorPtr,
  62. client: Option<RpcClient>,
  63. }
  64. impl DarkfidRpcClient {
  65. pub async fn new(endpoint: Url, ex: ExecutorPtr) -> Self {
  66. let client = RpcClient::new(endpoint.clone(), ex.clone()).await.ok();
  67. Self { endpoint, ex, client }
  68. }
  69. /// Stop the client.
  70. pub async fn stop(&self) {
  71. if let Some(ref client) = self.client {
  72. client.stop().await
  73. }
  74. }
  75. }
  76. /// Auxiliary structure holding various in memory caches to use during scan
  77. pub struct ScanCache {
  78. /// The Money Merkle tree containing coins
  79. pub money_tree: MerkleTree,
  80. /// The Money Sparse Merkle tree containing coins nullifiers
  81. pub money_smt: CacheSmt,
  82. /// All our known secrets to decrypt coin notes
  83. pub notes_secrets: Vec<SecretKey>,
  84. /// Our own coins nullifiers and their leaf positions
  85. pub owncoins_nullifiers: BTreeMap<[u8; 32], ([u8; 32], Position)>,
  86. /// Our own tokens to track freezes
  87. pub own_tokens: Vec<TokenId>,
  88. /// The DAO Merkle tree containing DAO bullas
  89. pub dao_daos_tree: MerkleTree,
  90. /// The DAO Merkle tree containing proposals bullas
  91. pub dao_proposals_tree: MerkleTree,
  92. /// Our own DAOs with their proposals and votes keys
  93. pub own_daos: HashMap<DaoBulla, (Option<SecretKey>, Option<SecretKey>)>,
  94. /// Our own DAOs proposals with their corresponding DAO reference
  95. pub own_proposals: HashMap<DaoProposalBulla, DaoBulla>,
  96. /// Our own deploy authorities
  97. pub own_deploy_auths: HashMap<[u8; 32], SecretKey>,
  98. /// Optional messages buffer for better downstream prints handling
  99. pub messages_buffer: Option<Vec<String>>,
  100. }
  101. impl ScanCache {
  102. /// Auxiliary function to consume the messages buffer.
  103. pub fn flush_messages(&mut self) -> Vec<String> {
  104. self.messages_buffer.as_mut().map_or(vec![], std::mem::take)
  105. }
  106. }
  107. /// Guard to push a message into the provided [`ScanCache`] optional
  108. /// messages buffer. The format arguments are only evaluated when the
  109. /// buffer is enabled, so no string formatting happens when logging
  110. /// is disabled.
  111. #[macro_export]
  112. macro_rules! scan_cache_log {
  113. ($cache:expr, $($arg:tt)*) => {
  114. if let Some(ref mut buffer) = $cache.messages_buffer {
  115. buffer.push(format!($($arg)*));
  116. }
  117. };
  118. }
  119. impl Drk {
  120. /// Auxiliary function to generate a new [`ScanCache`] for the
  121. /// wallet. The provided flag controls whether the messages
  122. /// buffer is enabled.
  123. pub async fn scan_cache(&self, verbose: bool) -> Result<ScanCache> {
  124. let money_tree = self.get_money_tree().await?;
  125. let smt_store = CacheSmtStorage::new(CacheOverlay::new(&self.cache)?, KVDB_MONEY_SMT_TREE);
  126. let money_smt = CacheSmt::new(smt_store, PoseidonFp::new(), &EMPTY_NODES_FP);
  127. let mut notes_secrets = self.get_money_secrets().await?;
  128. let mut owncoins_nullifiers = BTreeMap::new();
  129. for coin in self.get_coins(true).await? {
  130. owncoins_nullifiers.insert(
  131. coin.0.nullifier().to_bytes(),
  132. (coin.0.coin.to_bytes(), coin.0.leaf_position),
  133. );
  134. }
  135. let mint_authorities = self.get_mint_authorities().await?;
  136. let mut own_tokens = Vec::with_capacity(mint_authorities.len());
  137. for (token, _, _, _, _) in mint_authorities {
  138. own_tokens.push(token);
  139. }
  140. let (dao_daos_tree, dao_proposals_tree) = self.get_dao_trees().await?;
  141. let mut own_daos = HashMap::new();
  142. for dao in self.get_daos().await? {
  143. own_daos.insert(
  144. dao.bulla(),
  145. (dao.params.proposals_secret_key, dao.params.votes_secret_key),
  146. );
  147. if let Some(secret_key) = dao.params.notes_secret_key {
  148. notes_secrets.push(secret_key);
  149. }
  150. }
  151. let mut own_proposals = HashMap::new();
  152. for proposal in self.get_proposals().await? {
  153. own_proposals.insert(proposal.bulla(), proposal.proposal.dao_bulla);
  154. }
  155. let own_deploy_auths = self.get_deploy_auths_keys_map().await?;
  156. let messages_buffer = if verbose { Some(vec![]) } else { None };
  157. Ok(ScanCache {
  158. money_tree,
  159. money_smt,
  160. notes_secrets,
  161. owncoins_nullifiers,
  162. own_tokens,
  163. dao_daos_tree,
  164. dao_proposals_tree,
  165. own_daos,
  166. own_proposals,
  167. own_deploy_auths,
  168. messages_buffer,
  169. })
  170. }
  171. /// `scan_block` will go over over transactions in a block and handle their calls
  172. /// based on the called contract.
  173. pub async fn scan_block(&self, scan_cache: &mut ScanCache, block: &BlockInfo) -> Result<()> {
  174. // Keep track of our wallet transactions.
  175. let mut wallet_txs = vec![];
  176. // Checkpoint the merkle trees
  177. scan_cache.money_tree.checkpoint(block.header.height as usize);
  178. scan_cache.dao_daos_tree.checkpoint(block.header.height as usize);
  179. scan_cache.dao_proposals_tree.checkpoint(block.header.height as usize);
  180. // Scan the block
  181. scan_cache_log!(scan_cache, "=======================================");
  182. scan_cache_log!(scan_cache, "{}", block.header);
  183. scan_cache_log!(scan_cache, "=======================================");
  184. scan_cache_log!(scan_cache, "[scan_block] Iterating over {} transactions", block.txs.len());
  185. let mut block_signing_key = None;
  186. for tx in block.txs.iter() {
  187. let tx_hash = tx.hash();
  188. let tx_hash_string = tx_hash.to_string();
  189. let mut wallet_tx = false;
  190. scan_cache_log!(scan_cache, "[scan_block] Processing transaction: {tx_hash_string}");
  191. for (i, call) in tx.calls.iter().enumerate() {
  192. if call.data.contract_id == *MONEY_CONTRACT_ID {
  193. scan_cache_log!(scan_cache, "[scan_block] Found Money contract in call {i}");
  194. let (is_wallet_tx, signing_key) = self
  195. .apply_tx_money_data(
  196. scan_cache,
  197. &i,
  198. &tx.calls,
  199. &tx_hash_string,
  200. &block.header.height,
  201. )
  202. .await?;
  203. if is_wallet_tx {
  204. wallet_tx = true;
  205. // Only one block signing key exists per block
  206. if signing_key.is_some() {
  207. block_signing_key = signing_key;
  208. }
  209. }
  210. continue
  211. }
  212. if call.data.contract_id == *DAO_CONTRACT_ID {
  213. scan_cache_log!(scan_cache, "[scan_block] Found DAO contract in call {i}");
  214. if self
  215. .apply_tx_dao_data(
  216. scan_cache,
  217. &call.data.data,
  218. &tx_hash,
  219. &(i as u8),
  220. &block.header.height,
  221. )
  222. .await?
  223. {
  224. wallet_tx = true;
  225. }
  226. continue
  227. }
  228. if call.data.contract_id == *DEPLOYOOOR_CONTRACT_ID {
  229. scan_cache_log!(
  230. scan_cache,
  231. "[scan_block] Found DeployoOor contract in call {i}"
  232. );
  233. if self
  234. .apply_tx_deploy_data(
  235. scan_cache,
  236. &call.data.data,
  237. &tx_hash,
  238. &block.header.height,
  239. )
  240. .await?
  241. {
  242. wallet_tx = true;
  243. }
  244. continue
  245. }
  246. // TODO: For now we skip non-native contract calls
  247. scan_cache_log!(
  248. scan_cache,
  249. "[scan_block] Found non-native contract in call {i}, skipping."
  250. );
  251. }
  252. // If this is our wallet tx we mark it for update
  253. if wallet_tx {
  254. wallet_txs.push(tx);
  255. }
  256. }
  257. // Insert the block record
  258. scan_cache.money_smt.store.overlay.insert_scanned_block(
  259. &block.header.height,
  260. &block.header.hash(),
  261. &block_signing_key,
  262. )?;
  263. // Grab the overlay current diff
  264. let diff = scan_cache.money_smt.store.overlay.0.diff(&[])?;
  265. // Apply the overlay current changes
  266. scan_cache.money_smt.store.overlay.0.apply_diff(&diff)?;
  267. // Insert the state inverse diff record
  268. self.cache.insert_state_inverse_diff(&block.header.height, &diff.inverse())?;
  269. // Update the merkle trees
  270. self.cache.insert_merkle_trees(&[
  271. (KVDB_MERKLE_TREES_MONEY, &scan_cache.money_tree),
  272. (KVDB_MERKLE_TREES_DAO_DAOS, &scan_cache.dao_daos_tree),
  273. (KVDB_MERKLE_TREES_DAO_PROPOSALS, &scan_cache.dao_proposals_tree),
  274. ])?;
  275. // Flush kvdb
  276. self.cache.kvdb.flush_default_mode()?;
  277. // Update wallet transactions records
  278. if let Err(e) =
  279. self.put_tx_history_records(&wallet_txs, "Confirmed", Some(block.header.height)).await
  280. {
  281. return Err(Error::DatabaseError(format!(
  282. "[scan_block] Inserting transaction history records failed: {e}"
  283. )))
  284. }
  285. Ok(())
  286. }
  287. /// Scans the blockchain for wallet relevant transactions,
  288. /// starting from the last scanned block. If a reorg has happened,
  289. /// we revert to its previous height and then scan from there.
  290. pub async fn scan_blocks(
  291. &self,
  292. output: &mut Vec<String>,
  293. sender: Option<&Sender<Vec<String>>>,
  294. print: &bool,
  295. ) -> WalletDbResult<()> {
  296. // Grab last scanned block height
  297. let (mut height, hash) = self.get_last_scanned_block()?;
  298. // Grab our last scanned block from darkfid
  299. let block = match self.get_block_by_height(height).await {
  300. Ok(b) => Some(b),
  301. // Check if block was found
  302. Err(Error::JsonRpcError((-32121, _))) => None,
  303. Err(e) => {
  304. append_or_print(
  305. output,
  306. sender,
  307. print,
  308. vec![format!("[scan_blocks] RPC client request failed: {e}")],
  309. )
  310. .await;
  311. return Err(WalletDbError::GenericError)
  312. }
  313. };
  314. // Check if a reorg has happened
  315. if block.is_none() || hash != block.unwrap().hash().to_string() {
  316. // Find the exact block height the reorg happened
  317. let mut buf =
  318. vec![String::from("A reorg has happened, finding last known common block...")];
  319. height = height.saturating_sub(1);
  320. while height != 0 {
  321. // Grab our scanned block hash for that height
  322. let (scanned_block_hash, _) = self.get_scanned_block(&height)?;
  323. // Grab the block from darkfid for that height
  324. let block = match self.get_block_by_height(height).await {
  325. Ok(b) => Some(b),
  326. // Check if block was found
  327. Err(Error::JsonRpcError((-32121, _))) => None,
  328. Err(e) => {
  329. buf.push(format!("[scan_blocks] RPC client request failed: {e}"));
  330. append_or_print(output, sender, print, buf).await;
  331. return Err(WalletDbError::GenericError)
  332. }
  333. };
  334. // Continue to previous one if they don't match
  335. if block.is_none() || scanned_block_hash != block.unwrap().hash().to_string() {
  336. height = height.saturating_sub(1);
  337. continue
  338. }
  339. // Reset to its height
  340. buf.push(format!("Last common block found: {height} - {scanned_block_hash}"));
  341. self.reset_to_height(height, &mut buf).await?;
  342. append_or_print(output, sender, print, buf).await;
  343. break
  344. }
  345. }
  346. // If last scanned block is genesis(0) we reset,
  347. // otherwise continue with the next block height.
  348. if height == 0 {
  349. let mut buf = vec![];
  350. self.reset(&mut buf).await?;
  351. append_or_print(output, sender, print, buf).await;
  352. } else {
  353. height += 1;
  354. }
  355. // Generate a new scan cache
  356. let mut scan_cache = match self.scan_cache(true).await {
  357. Ok(c) => c,
  358. Err(e) => {
  359. append_or_print(
  360. output,
  361. sender,
  362. print,
  363. vec![format!("[scan_blocks] Generating scan cache failed: {e}")],
  364. )
  365. .await;
  366. return Err(WalletDbError::GenericError)
  367. }
  368. };
  369. loop {
  370. // Grab last confirmed block
  371. let mut buf = vec![format!("Requested to scan from block number: {height}")];
  372. let (last_height, last_hash) = match self.get_last_confirmed_block().await {
  373. Ok(last) => last,
  374. Err(e) => {
  375. buf.push(format!("[scan_blocks] RPC client request failed: {e}"));
  376. append_or_print(output, sender, print, buf).await;
  377. return Err(WalletDbError::GenericError)
  378. }
  379. };
  380. buf.push(format!(
  381. "Last confirmed block reported by darkfid: {last_height} - {last_hash}"
  382. ));
  383. append_or_print(output, sender, print, buf).await;
  384. // Already scanned last confirmed block
  385. if height > last_height {
  386. return Ok(())
  387. }
  388. while height <= last_height {
  389. let mut buf = vec![format!("Requesting block {height}...")];
  390. let block = match self.get_block_by_height(height).await {
  391. Ok(b) => b,
  392. Err(e) => {
  393. buf.push(format!("[scan_blocks] RPC client request failed: {e}"));
  394. append_or_print(output, sender, print, buf).await;
  395. return Err(WalletDbError::GenericError)
  396. }
  397. };
  398. buf.push(format!("Block {height} received! Scanning block..."));
  399. if let Err(e) = self.scan_block(&mut scan_cache, &block).await {
  400. buf.push(format!("[scan_blocks] Scan block failed: {e}"));
  401. append_or_print(output, sender, print, buf).await;
  402. return Err(WalletDbError::GenericError)
  403. };
  404. for msg in scan_cache.flush_messages() {
  405. buf.push(msg);
  406. }
  407. append_or_print(output, sender, print, buf).await;
  408. height += 1;
  409. }
  410. }
  411. }
  412. // Queries darkfid for last confirmed block.
  413. pub async fn get_last_confirmed_block(&self) -> Result<(u32, String)> {
  414. let rep = self
  415. .darkfid_daemon_request("blockchain.last_confirmed_block", &JsonValue::Array(vec![]))
  416. .await?;
  417. let params = rep.get::<Vec<JsonValue>>().unwrap();
  418. let height = *params[0].get::<f64>().unwrap() as u32;
  419. let hash = params[1].get::<String>().unwrap().clone();
  420. Ok((height, hash))
  421. }
  422. // Queries darkfid for a block with given height.
  423. pub async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  424. let params = self
  425. .darkfid_daemon_request(
  426. "blockchain.get_block",
  427. &JsonValue::Array(vec![JsonValue::Number(height as f64)]),
  428. )
  429. .await?;
  430. let param = params.get::<String>().unwrap();
  431. let bytes = base64::decode(param).unwrap();
  432. let block = deserialize_async(&bytes).await?;
  433. Ok(block)
  434. }
  435. /// Broadcast a given transaction to darkfid and forward onto the network.
  436. /// Returns the transaction ID upon success.
  437. pub async fn broadcast_tx(&self, tx: &Transaction, output: &mut Vec<String>) -> Result<String> {
  438. output.push(String::from("Broadcasting transaction..."));
  439. let params =
  440. JsonValue::Array(vec![JsonValue::String(base64::encode(&serialize_async(tx).await))]);
  441. let rep = self.darkfid_daemon_request("tx.broadcast", &params).await?;
  442. let txid = rep.get::<String>().unwrap().clone();
  443. // Store transactions history record
  444. if let Err(e) = self.put_tx_history_record(tx, "Broadcasted", None).await {
  445. return Err(Error::DatabaseError(format!(
  446. "[broadcast_tx] Inserting transaction history record failed: {e}"
  447. )))
  448. }
  449. Ok(txid)
  450. }
  451. /// Queries darkfid for a tx with given hash.
  452. pub async fn get_tx(&self, tx_hash: &TransactionHash) -> Result<Option<Transaction>> {
  453. let tx_hash_str = tx_hash.to_string();
  454. match self
  455. .darkfid_daemon_request(
  456. "blockchain.get_tx",
  457. &JsonValue::Array(vec![JsonValue::String(tx_hash_str)]),
  458. )
  459. .await
  460. {
  461. Ok(param) => {
  462. let tx_bytes = base64::decode(param.get::<String>().unwrap()).unwrap();
  463. let tx = deserialize_async(&tx_bytes).await?;
  464. Ok(Some(tx))
  465. }
  466. Err(_) => Ok(None),
  467. }
  468. }
  469. /// Simulate the transaction with the state machine.
  470. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  471. let tx_str = base64::encode(&serialize_async(tx).await);
  472. let rep = self
  473. .darkfid_daemon_request(
  474. "tx.simulate",
  475. &JsonValue::Array(vec![JsonValue::String(tx_str)]),
  476. )
  477. .await?;
  478. let is_valid = *rep.get::<bool>().unwrap();
  479. Ok(is_valid)
  480. }
  481. /// Try to fetch zkas bincodes for the given `ContractId`.
  482. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  483. let params = JsonValue::Array(vec![JsonValue::String(format!("{contract_id}"))]);
  484. let rep = self.darkfid_daemon_request("blockchain.lookup_zkas", &params).await?;
  485. let params = rep.get::<Vec<JsonValue>>().unwrap();
  486. let mut ret = Vec::with_capacity(params.len());
  487. for param in params {
  488. let zkas_ns = param[0].get::<String>().unwrap().clone();
  489. let zkas_bincode_bytes = base64::decode(param[1].get::<String>().unwrap()).unwrap();
  490. ret.push((zkas_ns, zkas_bincode_bytes));
  491. }
  492. Ok(ret)
  493. }
  494. /// Queries darkfid for given transaction's required fee.
  495. pub async fn get_tx_fee(&self, tx: &Transaction, include_fee: bool) -> Result<u64> {
  496. let params = JsonValue::Array(vec![
  497. JsonValue::String(base64::encode(&serialize_async(tx).await)),
  498. JsonValue::Boolean(include_fee),
  499. ]);
  500. let rep = self.darkfid_daemon_request("tx.calculate_fee", &params).await?;
  501. let fee = *rep.get::<f64>().unwrap() as u64;
  502. Ok(fee)
  503. }
  504. /// Queries darkfid for current best fork next height.
  505. pub async fn get_next_block_height(&self) -> Result<u32> {
  506. let rep = self
  507. .darkfid_daemon_request(
  508. "blockchain.best_fork_next_block_height",
  509. &JsonValue::Array(vec![]),
  510. )
  511. .await?;
  512. let next_height = *rep.get::<f64>().unwrap() as u32;
  513. Ok(next_height)
  514. }
  515. /// Queries darkfid for currently configured block target time.
  516. pub async fn get_block_target(&self) -> Result<u32> {
  517. let rep = self
  518. .darkfid_daemon_request("blockchain.block_target", &JsonValue::Array(vec![]))
  519. .await?;
  520. let next_height = *rep.get::<f64>().unwrap() as u32;
  521. Ok(next_height)
  522. }
  523. /// Auxiliary function to ping configured darkfid daemon for liveness.
  524. pub async fn ping(&self, output: &mut Vec<String>) -> Result<()> {
  525. output.push(String::from("Executing ping request to darkfid..."));
  526. let latency = Instant::now();
  527. let rep = self.darkfid_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  528. let latency = latency.elapsed();
  529. output.push(format!("Got reply: {rep:?}"));
  530. output.push(format!("Latency: {latency:?}"));
  531. Ok(())
  532. }
  533. /// Auxiliary function to execute a request towards the configured darkfid daemon JSON-RPC endpoint.
  534. pub async fn darkfid_daemon_request(
  535. &self,
  536. method: &str,
  537. params: &JsonValue,
  538. ) -> Result<JsonValue> {
  539. let Some(ref rpc_client) = self.rpc_client else { return Err(Error::RpcClientStopped) };
  540. let mut lock = rpc_client.write().await;
  541. let req = JsonRequest::new(method, params.clone());
  542. // Check the client is initialized
  543. if let Some(ref client) = lock.client {
  544. // Execute request
  545. if let Ok(rep) = client.request(req.clone()).await {
  546. drop(lock);
  547. return Ok(rep);
  548. }
  549. }
  550. // Reset the rpc client in case of an error and try again
  551. let client = RpcClient::new(lock.endpoint.clone(), lock.ex.clone()).await?;
  552. let rep = client.request(req).await?;
  553. lock.client = Some(client);
  554. drop(lock);
  555. Ok(rep)
  556. }
  557. /// Auxiliary function to stop current JSON-RPC client, if its initialized.
  558. pub async fn stop_rpc_client(&self) -> Result<()> {
  559. if let Some(ref rpc_client) = self.rpc_client {
  560. rpc_client.read().await.stop().await;
  561. };
  562. Ok(())
  563. }
  564. }
  565. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  566. /// new confirmed blocks. Upon receiving them, all the transactions are
  567. /// scanned and we check if any of them call the money contract, and if
  568. /// the payments are intended for us. If so, we decrypt them and append
  569. /// the metadata to our wallet. If a reorg block is received, we revert
  570. /// to its previous height and then scan it. We assume that the blocks
  571. /// up to that point are unchanged, since darkfid will just broadcast
  572. /// the sequence after the reorg.
  573. pub async fn subscribe_blocks(
  574. drk: &DrkPtr,
  575. rpc_task: StoppableTaskPtr,
  576. shell_sender: Sender<Vec<String>>,
  577. endpoint: Url,
  578. ex: &ExecutorPtr,
  579. ) -> Result<()> {
  580. // First we do a clean scan
  581. let lock = drk.read().await;
  582. if let Err(e) = lock.scan_blocks(&mut vec![], Some(&shell_sender), &false).await {
  583. let err_msg = format!("Failed during scanning: {e}");
  584. shell_sender.send(vec![err_msg.clone()]).await?;
  585. return Err(Error::Custom(err_msg))
  586. }
  587. shell_sender.send(vec![String::from("Finished scanning blockchain")]).await?;
  588. // Grab last confirmed block height
  589. let (last_confirmed_height, _) = lock.get_last_confirmed_block().await?;
  590. // Handle genesis(0) block
  591. if last_confirmed_height == 0 {
  592. if let Err(e) = lock.scan_blocks(&mut vec![], Some(&shell_sender), &false).await {
  593. let err_msg = format!("[subscribe_blocks] Scanning from genesis block failed: {e}");
  594. shell_sender.send(vec![err_msg.clone()]).await?;
  595. return Err(Error::Custom(err_msg))
  596. }
  597. }
  598. // Grab last confirmed block again
  599. let (last_confirmed_height, last_confirmed_hash) = lock.get_last_confirmed_block().await?;
  600. // Grab last scanned block
  601. let (mut last_scanned_height, last_scanned_hash) = match lock.get_last_scanned_block() {
  602. Ok(last) => last,
  603. Err(e) => {
  604. let err_msg = format!("[subscribe_blocks] Retrieving last scanned block failed: {e}");
  605. shell_sender.send(vec![err_msg.clone()]).await?;
  606. return Err(Error::Custom(err_msg))
  607. }
  608. };
  609. drop(lock);
  610. // Check if other blocks have been created
  611. if last_confirmed_height != last_scanned_height || last_confirmed_hash != last_scanned_hash {
  612. let err_msg = String::from("[subscribe_blocks] Blockchain not fully scanned");
  613. shell_sender
  614. .send(vec![
  615. String::from("Warning: Last scanned block is not the last confirmed block."),
  616. String::from("You should first fully scan the blockchain, and then subscribe"),
  617. err_msg.clone(),
  618. ])
  619. .await?;
  620. return Err(Error::Custom(err_msg))
  621. }
  622. let mut shell_message =
  623. vec![String::from("Subscribing to receive notifications of incoming blocks")];
  624. let publisher = Publisher::new();
  625. let subscription = publisher.clone().subscribe().await;
  626. let _publisher = publisher.clone();
  627. let rpc_client = Arc::new(RpcClient::new(endpoint, ex.clone()).await?);
  628. let rpc_client_ = rpc_client.clone();
  629. rpc_task.start(
  630. // Weird hack to prevent lifetimes hell
  631. async move {
  632. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  633. rpc_client_.subscribe(req, _publisher).await
  634. },
  635. |res| async move {
  636. rpc_client.stop().await;
  637. match res {
  638. Ok(()) | Err(Error::DetachedTaskStopped) | Err(Error::RpcServerStopped) => { /* Do nothing */ }
  639. Err(e) => {
  640. eprintln!("[subscribe_blocks] JSON-RPC server error: {e}");
  641. publisher
  642. .notify(JsonResult::Error(JsonError::new(
  643. ErrorCode::InternalError,
  644. None,
  645. 0,
  646. )))
  647. .await;
  648. }
  649. }
  650. },
  651. Error::RpcServerStopped,
  652. ex.clone(),
  653. );
  654. shell_message.push(String::from("Detached subscription to background"));
  655. shell_message.push(String::from("All is good. Waiting for block notifications..."));
  656. shell_sender.send(shell_message).await?;
  657. let e = 'outer: loop {
  658. match subscription.receive().await {
  659. JsonResult::Notification(n) => {
  660. let mut shell_message =
  661. vec![String::from("Got Block notification from darkfid subscription")];
  662. if n.method != "blockchain.subscribe_blocks" {
  663. shell_sender.send(shell_message).await?;
  664. break Error::UnexpectedJsonRpc(format!(
  665. "Got foreign notification from darkfid: {}",
  666. n.method
  667. ))
  668. }
  669. // Verify parameters
  670. if !n.params.is_array() {
  671. shell_sender.send(shell_message).await?;
  672. break Error::UnexpectedJsonRpc(
  673. "Received notification params are not an array".to_string(),
  674. )
  675. }
  676. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  677. if params.is_empty() {
  678. shell_sender.send(shell_message).await?;
  679. break Error::UnexpectedJsonRpc("Notification parameters are empty".to_string())
  680. }
  681. for param in params {
  682. let param = param.get::<String>().unwrap();
  683. let bytes = base64::decode(param).unwrap();
  684. let block: BlockInfo = deserialize_async(&bytes).await?;
  685. shell_message
  686. .push(String::from("Deserialized successfully. Scanning block..."));
  687. // Check if a reorg block was received, to reset to its previous
  688. let lock = drk.read().await;
  689. if block.header.height <= last_scanned_height {
  690. let reset_height = block.header.height.saturating_sub(1);
  691. if let Err(e) = lock.reset_to_height(reset_height, &mut shell_message).await
  692. {
  693. shell_sender.send(shell_message).await?;
  694. break 'outer Error::Custom(format!(
  695. "[subscribe_blocks] Wallet state reset failed: {e}"
  696. ))
  697. }
  698. // Scan genesis again if needed
  699. if reset_height == 0 {
  700. let genesis = match lock.get_block_by_height(reset_height).await {
  701. Ok(b) => b,
  702. Err(e) => {
  703. shell_sender.send(shell_message).await?;
  704. break 'outer Error::Custom(format!(
  705. "[subscribe_blocks] RPC client request failed: {e}"
  706. ))
  707. }
  708. };
  709. let mut scan_cache = lock.scan_cache(true).await?;
  710. if let Err(e) = lock.scan_block(&mut scan_cache, &genesis).await {
  711. shell_sender.send(shell_message).await?;
  712. break 'outer Error::Custom(format!(
  713. "[subscribe_blocks] Scanning block failed: {e}"
  714. ))
  715. };
  716. for msg in scan_cache.flush_messages() {
  717. shell_message.push(msg);
  718. }
  719. }
  720. }
  721. let mut scan_cache = lock.scan_cache(true).await?;
  722. if let Err(e) = lock.scan_block(&mut scan_cache, &block).await {
  723. shell_sender.send(shell_message).await?;
  724. break 'outer Error::Custom(format!(
  725. "[subscribe_blocks] Scanning block failed: {e}"
  726. ))
  727. }
  728. for msg in scan_cache.flush_messages() {
  729. shell_message.push(msg);
  730. }
  731. shell_sender.send(shell_message.clone()).await?;
  732. // Set new last scanned block height
  733. last_scanned_height = block.header.height;
  734. }
  735. }
  736. JsonResult::Error(e) => {
  737. // Some error happened in the transmission
  738. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  739. }
  740. x => {
  741. // And this is weird
  742. break Error::UnexpectedJsonRpc(format!("Got unexpected data from JSON-RPC: {x:?}"))
  743. }
  744. }
  745. };
  746. shell_sender.send(vec![format!("[subscribe_blocks] Subscription loop break: {e}")]).await?;
  747. Err(e)
  748. }