rpc.rs 27 KB

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