rpc.rs 32 KB

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