rpc.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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, PublisherPtr, 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. progress_pub: Option<PublisherPtr<(u32, u32)>>,
  281. ) -> WalletDbResult<()> {
  282. // Grab last scanned block height
  283. let (mut height, hash) = self.get_last_scanned_block()?;
  284. // Grab our last scanned block from darkfid
  285. let block = match self.get_block_by_height(height).await {
  286. Ok(b) => Some(b),
  287. // Check if block was found
  288. Err(Error::JsonRpcError((-32121, _))) => None,
  289. Err(e) => {
  290. append_or_print(
  291. output,
  292. sender,
  293. print,
  294. vec![format!("[scan_blocks] RPC client request failed: {e}")],
  295. )
  296. .await;
  297. return Err(WalletDbError::GenericError)
  298. }
  299. };
  300. // Check if a reorg has happened
  301. if block.is_none() || hash != block.unwrap().hash().to_string() {
  302. // Find the exact block height the reorg happened
  303. let mut buf =
  304. vec![String::from("A reorg has happened, finding last known common block...")];
  305. height = height.saturating_sub(1);
  306. while height != 0 {
  307. // Grab our scanned block hash for that height
  308. let (scanned_block_hash, _) = self.get_scanned_block(&height)?;
  309. // Grab the block from darkfid for that height
  310. let block = match self.get_block_by_height(height).await {
  311. Ok(b) => Some(b),
  312. // Check if block was found
  313. Err(Error::JsonRpcError((-32121, _))) => None,
  314. Err(e) => {
  315. buf.push(format!("[scan_blocks] RPC client request failed: {e}"));
  316. append_or_print(output, sender, print, buf).await;
  317. return Err(WalletDbError::GenericError)
  318. }
  319. };
  320. // Continue to previous one if they don't match
  321. if block.is_none() || scanned_block_hash != block.unwrap().hash().to_string() {
  322. height = height.saturating_sub(1);
  323. continue
  324. }
  325. // Reset to its height
  326. buf.push(format!("Last common block found: {height} - {scanned_block_hash}"));
  327. self.reset_to_height(height, &mut buf).await?;
  328. append_or_print(output, sender, print, buf).await;
  329. break
  330. }
  331. }
  332. // If last scanned block is genesis(0) we reset,
  333. // otherwise continue with the next block height.
  334. if height == 0 {
  335. let mut buf = vec![];
  336. self.reset(&mut buf).await?;
  337. append_or_print(output, sender, print, buf).await;
  338. } else {
  339. height += 1;
  340. }
  341. // Generate a new scan cache
  342. let mut scan_cache = match self.scan_cache().await {
  343. Ok(c) => c,
  344. Err(e) => {
  345. append_or_print(
  346. output,
  347. sender,
  348. print,
  349. vec![format!("[scan_blocks] Generating scan cache failed: {e}")],
  350. )
  351. .await;
  352. return Err(WalletDbError::GenericError)
  353. }
  354. };
  355. loop {
  356. // Grab last confirmed block
  357. let mut buf = vec![format!("Requested to scan from block number: {height}")];
  358. let (last_height, last_hash) = match self.get_last_confirmed_block().await {
  359. Ok(last) => last,
  360. Err(e) => {
  361. buf.push(format!("[scan_blocks] RPC client request failed: {e}"));
  362. append_or_print(output, sender, print, buf).await;
  363. return Err(WalletDbError::GenericError)
  364. }
  365. };
  366. buf.push(format!(
  367. "Last confirmed block reported by darkfid: {last_height} - {last_hash}"
  368. ));
  369. append_or_print(output, sender, print, buf).await;
  370. // Already scanned last confirmed block
  371. if height > last_height {
  372. return Ok(())
  373. }
  374. while height <= last_height {
  375. let mut buf = vec![format!("Requesting block {height}...")];
  376. let block = match self.get_block_by_height(height).await {
  377. Ok(b) => b,
  378. Err(e) => {
  379. buf.push(format!("[scan_blocks] RPC client request failed: {e}"));
  380. append_or_print(output, sender, print, buf).await;
  381. return Err(WalletDbError::GenericError)
  382. }
  383. };
  384. buf.push(format!("Block {height} received! Scanning block..."));
  385. if let Err(e) = self.scan_block(&mut scan_cache, &block).await {
  386. buf.push(format!("[scan_blocks] Scan block failed: {e}"));
  387. append_or_print(output, sender, print, buf).await;
  388. return Err(WalletDbError::GenericError)
  389. };
  390. for msg in scan_cache.flush_messages() {
  391. buf.push(msg);
  392. }
  393. append_or_print(output, sender, print, buf).await;
  394. if let Some(ref progress) = progress_pub {
  395. progress.notify((height, last_height)).await;
  396. }
  397. height += 1;
  398. }
  399. }
  400. }
  401. // Queries darkfid for last confirmed block.
  402. pub async fn get_last_confirmed_block(&self) -> Result<(u32, String)> {
  403. let rep = self
  404. .darkfid_daemon_request("blockchain.last_confirmed_block", &JsonValue::Array(vec![]))
  405. .await?;
  406. let params = rep.get::<Vec<JsonValue>>().unwrap();
  407. let height = *params[0].get::<f64>().unwrap() as u32;
  408. let hash = params[1].get::<String>().unwrap().clone();
  409. Ok((height, hash))
  410. }
  411. // Queries darkfid for a block with given height.
  412. pub async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  413. let params = self
  414. .darkfid_daemon_request(
  415. "blockchain.get_block",
  416. &JsonValue::Array(vec![JsonValue::Number(height as f64)]),
  417. )
  418. .await?;
  419. let param = params.get::<String>().unwrap();
  420. let bytes = base64::decode(param).unwrap();
  421. let block = deserialize_async(&bytes).await?;
  422. Ok(block)
  423. }
  424. /// Broadcast a given transaction to darkfid and forward onto the network.
  425. /// Returns the transaction ID upon success.
  426. pub async fn broadcast_tx(&self, tx: &Transaction, output: &mut Vec<String>) -> Result<String> {
  427. output.push(String::from("Broadcasting transaction..."));
  428. let params =
  429. JsonValue::Array(vec![JsonValue::String(base64::encode(&serialize_async(tx).await))]);
  430. let rep = self.darkfid_daemon_request("tx.broadcast", &params).await?;
  431. let txid = rep.get::<String>().unwrap().clone();
  432. // Store transactions history record
  433. if let Err(e) = self.put_tx_history_record(tx, "Broadcasted", None).await {
  434. return Err(Error::DatabaseError(format!(
  435. "[broadcast_tx] Inserting transaction history record failed: {e}"
  436. )))
  437. }
  438. Ok(txid)
  439. }
  440. /// Queries darkfid for a tx with given hash.
  441. pub async fn get_tx(&self, tx_hash: &TransactionHash) -> Result<Option<Transaction>> {
  442. let tx_hash_str = tx_hash.to_string();
  443. match self
  444. .darkfid_daemon_request(
  445. "blockchain.get_tx",
  446. &JsonValue::Array(vec![JsonValue::String(tx_hash_str)]),
  447. )
  448. .await
  449. {
  450. Ok(param) => {
  451. let tx_bytes = base64::decode(param.get::<String>().unwrap()).unwrap();
  452. let tx = deserialize_async(&tx_bytes).await?;
  453. Ok(Some(tx))
  454. }
  455. Err(_) => Ok(None),
  456. }
  457. }
  458. /// Simulate the transaction with the state machine.
  459. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  460. let tx_str = base64::encode(&serialize_async(tx).await);
  461. let rep = self
  462. .darkfid_daemon_request(
  463. "tx.simulate",
  464. &JsonValue::Array(vec![JsonValue::String(tx_str)]),
  465. )
  466. .await?;
  467. let is_valid = *rep.get::<bool>().unwrap();
  468. Ok(is_valid)
  469. }
  470. /// Try to fetch zkas bincodes for the given `ContractId`.
  471. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  472. let params = JsonValue::Array(vec![JsonValue::String(format!("{contract_id}"))]);
  473. let rep = self.darkfid_daemon_request("blockchain.lookup_zkas", &params).await?;
  474. let params = rep.get::<Vec<JsonValue>>().unwrap();
  475. let mut ret = Vec::with_capacity(params.len());
  476. for param in params {
  477. let zkas_ns = param[0].get::<String>().unwrap().clone();
  478. let zkas_bincode_bytes = base64::decode(param[1].get::<String>().unwrap()).unwrap();
  479. ret.push((zkas_ns, zkas_bincode_bytes));
  480. }
  481. Ok(ret)
  482. }
  483. /// Queries darkfid for given transaction's required fee.
  484. pub async fn get_tx_fee(&self, tx: &Transaction, include_fee: bool) -> Result<u64> {
  485. let params = JsonValue::Array(vec![
  486. JsonValue::String(base64::encode(&serialize_async(tx).await)),
  487. JsonValue::Boolean(include_fee),
  488. ]);
  489. let rep = self.darkfid_daemon_request("tx.calculate_fee", &params).await?;
  490. let fee = *rep.get::<f64>().unwrap() as u64;
  491. Ok(fee)
  492. }
  493. /// Queries darkfid for current best fork next height.
  494. pub async fn get_next_block_height(&self) -> Result<u32> {
  495. let rep = self
  496. .darkfid_daemon_request(
  497. "blockchain.best_fork_next_block_height",
  498. &JsonValue::Array(vec![]),
  499. )
  500. .await?;
  501. let next_height = *rep.get::<f64>().unwrap() as u32;
  502. Ok(next_height)
  503. }
  504. /// Queries darkfid for currently configured block target time.
  505. pub async fn get_block_target(&self) -> Result<u32> {
  506. let rep = self
  507. .darkfid_daemon_request("blockchain.block_target", &JsonValue::Array(vec![]))
  508. .await?;
  509. let next_height = *rep.get::<f64>().unwrap() as u32;
  510. Ok(next_height)
  511. }
  512. /// Auxiliary function to ping configured darkfid daemon for liveness.
  513. pub async fn ping(&self, output: &mut Vec<String>) -> Result<()> {
  514. output.push(String::from("Executing ping request to darkfid..."));
  515. let latency = Instant::now();
  516. let rep = self.darkfid_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  517. let latency = latency.elapsed();
  518. output.push(format!("Got reply: {rep:?}"));
  519. output.push(format!("Latency: {latency:?}"));
  520. Ok(())
  521. }
  522. /// Auxiliary function to execute a request towards the configured darkfid daemon JSON-RPC endpoint.
  523. pub async fn darkfid_daemon_request(
  524. &self,
  525. method: &str,
  526. params: &JsonValue,
  527. ) -> Result<JsonValue> {
  528. let Some(ref rpc_client) = self.rpc_client else { return Err(Error::RpcClientStopped) };
  529. let mut lock = rpc_client.write().await;
  530. let req = JsonRequest::new(method, params.clone());
  531. // Check the client is initialized
  532. if let Some(ref client) = lock.client {
  533. // Execute request
  534. if let Ok(rep) = client.request(req.clone()).await {
  535. drop(lock);
  536. return Ok(rep);
  537. }
  538. }
  539. // Reset the rpc client in case of an error and try again
  540. let client = RpcClient::new(lock.endpoint.clone(), lock.ex.clone()).await?;
  541. let rep = client.request(req).await?;
  542. lock.client = Some(client);
  543. drop(lock);
  544. Ok(rep)
  545. }
  546. /// Auxiliary function to stop current JSON-RPC client, if its initialized.
  547. pub async fn stop_rpc_client(&self) -> Result<()> {
  548. if let Some(ref rpc_client) = self.rpc_client {
  549. rpc_client.read().await.stop().await;
  550. };
  551. Ok(())
  552. }
  553. }
  554. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  555. /// new confirmed blocks. Upon receiving them, all the transactions are
  556. /// scanned and we check if any of them call the money contract, and if
  557. /// the payments are intended for us. If so, we decrypt them and append
  558. /// the metadata to our wallet. If a reorg block is received, we revert
  559. /// to its previous height and then scan it. We assume that the blocks
  560. /// up to that point are unchanged, since darkfid will just broadcast
  561. /// the sequence after the reorg.
  562. pub async fn subscribe_blocks(
  563. drk: &DrkPtr,
  564. rpc_task: StoppableTaskPtr,
  565. shell_sender: Sender<Vec<String>>,
  566. endpoint: Url,
  567. ex: &ExecutorPtr,
  568. ) -> Result<()> {
  569. // First we do a clean scan
  570. let lock = drk.read().await;
  571. if let Err(e) = lock.scan_blocks(&mut vec![], Some(&shell_sender), &false, None).await {
  572. let err_msg = format!("Failed during scanning: {e}");
  573. shell_sender.send(vec![err_msg.clone()]).await?;
  574. return Err(Error::Custom(err_msg))
  575. }
  576. shell_sender.send(vec![String::from("Finished scanning blockchain")]).await?;
  577. // Grab last confirmed block height
  578. let (last_confirmed_height, _) = lock.get_last_confirmed_block().await?;
  579. // Handle genesis(0) block
  580. if last_confirmed_height == 0 {
  581. if let Err(e) = lock.scan_blocks(&mut vec![], Some(&shell_sender), &false, None).await {
  582. let err_msg = format!("[subscribe_blocks] Scanning from genesis block failed: {e}");
  583. shell_sender.send(vec![err_msg.clone()]).await?;
  584. return Err(Error::Custom(err_msg))
  585. }
  586. }
  587. // Grab last confirmed block again
  588. let (last_confirmed_height, last_confirmed_hash) = lock.get_last_confirmed_block().await?;
  589. // Grab last scanned block
  590. let (mut last_scanned_height, last_scanned_hash) = match lock.get_last_scanned_block() {
  591. Ok(last) => last,
  592. Err(e) => {
  593. let err_msg = format!("[subscribe_blocks] Retrieving last scanned block failed: {e}");
  594. shell_sender.send(vec![err_msg.clone()]).await?;
  595. return Err(Error::Custom(err_msg))
  596. }
  597. };
  598. drop(lock);
  599. // Check if other blocks have been created
  600. if last_confirmed_height != last_scanned_height || last_confirmed_hash != last_scanned_hash {
  601. let err_msg = String::from("[subscribe_blocks] Blockchain not fully scanned");
  602. shell_sender
  603. .send(vec![
  604. String::from("Warning: Last scanned block is not the last confirmed block."),
  605. String::from("You should first fully scan the blockchain, and then subscribe"),
  606. err_msg.clone(),
  607. ])
  608. .await?;
  609. return Err(Error::Custom(err_msg))
  610. }
  611. let mut shell_message =
  612. vec![String::from("Subscribing to receive notifications of incoming blocks")];
  613. let publisher = Publisher::new();
  614. let subscription = publisher.clone().subscribe().await;
  615. let _publisher = publisher.clone();
  616. let rpc_client = Arc::new(RpcClient::new(endpoint, ex.clone()).await?);
  617. let rpc_client_ = rpc_client.clone();
  618. rpc_task.start(
  619. // Weird hack to prevent lifetimes hell
  620. async move {
  621. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  622. rpc_client_.subscribe(req, _publisher).await
  623. },
  624. |res| async move {
  625. rpc_client.stop().await;
  626. match res {
  627. Ok(()) | Err(Error::DetachedTaskStopped) | Err(Error::RpcServerStopped) => { /* Do nothing */ }
  628. Err(e) => {
  629. eprintln!("[subscribe_blocks] JSON-RPC server error: {e}");
  630. publisher
  631. .notify(JsonResult::Error(JsonError::new(
  632. ErrorCode::InternalError,
  633. None,
  634. 0,
  635. )))
  636. .await;
  637. }
  638. }
  639. },
  640. Error::RpcServerStopped,
  641. ex.clone(),
  642. );
  643. shell_message.push(String::from("Detached subscription to background"));
  644. shell_message.push(String::from("All is good. Waiting for block notifications..."));
  645. shell_sender.send(shell_message).await?;
  646. let e = 'outer: loop {
  647. match subscription.receive().await {
  648. JsonResult::Notification(n) => {
  649. let mut shell_message =
  650. vec![String::from("Got Block notification from darkfid subscription")];
  651. if n.method != "blockchain.subscribe_blocks" {
  652. shell_sender.send(shell_message).await?;
  653. break Error::UnexpectedJsonRpc(format!(
  654. "Got foreign notification from darkfid: {}",
  655. n.method
  656. ))
  657. }
  658. // Verify parameters
  659. if !n.params.is_array() {
  660. shell_sender.send(shell_message).await?;
  661. break Error::UnexpectedJsonRpc(
  662. "Received notification params are not an array".to_string(),
  663. )
  664. }
  665. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  666. if params.is_empty() {
  667. shell_sender.send(shell_message).await?;
  668. break Error::UnexpectedJsonRpc("Notification parameters are empty".to_string())
  669. }
  670. for param in params {
  671. let param = param.get::<String>().unwrap();
  672. let bytes = base64::decode(param).unwrap();
  673. let block: BlockInfo = deserialize_async(&bytes).await?;
  674. shell_message
  675. .push(String::from("Deserialized successfully. Scanning block..."));
  676. // Check if a reorg block was received, to reset to its previous
  677. let lock = drk.read().await;
  678. if block.header.height <= last_scanned_height {
  679. let reset_height = block.header.height.saturating_sub(1);
  680. if let Err(e) = lock.reset_to_height(reset_height, &mut shell_message).await
  681. {
  682. shell_sender.send(shell_message).await?;
  683. break 'outer Error::Custom(format!(
  684. "[subscribe_blocks] Wallet state reset failed: {e}"
  685. ))
  686. }
  687. // Scan genesis again if needed
  688. if reset_height == 0 {
  689. let genesis = match lock.get_block_by_height(reset_height).await {
  690. Ok(b) => b,
  691. Err(e) => {
  692. shell_sender.send(shell_message).await?;
  693. break 'outer Error::Custom(format!(
  694. "[subscribe_blocks] RPC client request failed: {e}"
  695. ))
  696. }
  697. };
  698. let mut scan_cache = lock.scan_cache().await?;
  699. if let Err(e) = lock.scan_block(&mut scan_cache, &genesis).await {
  700. shell_sender.send(shell_message).await?;
  701. break 'outer Error::Custom(format!(
  702. "[subscribe_blocks] Scanning block failed: {e}"
  703. ))
  704. };
  705. for msg in scan_cache.flush_messages() {
  706. shell_message.push(msg);
  707. }
  708. }
  709. }
  710. let mut scan_cache = lock.scan_cache().await?;
  711. if let Err(e) = lock.scan_block(&mut scan_cache, &block).await {
  712. shell_sender.send(shell_message).await?;
  713. break 'outer Error::Custom(format!(
  714. "[subscribe_blocks] Scanning block failed: {e}"
  715. ))
  716. }
  717. for msg in scan_cache.flush_messages() {
  718. shell_message.push(msg);
  719. }
  720. shell_sender.send(shell_message.clone()).await?;
  721. // Set new last scanned block height
  722. last_scanned_height = block.header.height;
  723. }
  724. }
  725. JsonResult::Error(e) => {
  726. // Some error happened in the transmission
  727. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  728. }
  729. x => {
  730. // And this is weird
  731. break Error::UnexpectedJsonRpc(format!("Got unexpected data from JSON-RPC: {x:?}"))
  732. }
  733. }
  734. };
  735. shell_sender.send(vec![format!("[subscribe_blocks] Subscription loop break: {e}")]).await?;
  736. Err(e)
  737. }