rpc.rs 31 KB

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