rpc.rs 32 KB

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