rpc.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{sync::Arc, time::Instant};
  19. use url::Url;
  20. use darkfi::{
  21. blockchain::BlockInfo,
  22. rpc::{
  23. client::RpcClient,
  24. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResult},
  25. util::JsonValue,
  26. },
  27. system::{Publisher, StoppableTask},
  28. tx::Transaction,
  29. util::encoding::base64,
  30. Error, Result,
  31. };
  32. use darkfi_sdk::{
  33. crypto::{ContractId, DAO_CONTRACT_ID, DEPLOYOOOR_CONTRACT_ID, MONEY_CONTRACT_ID},
  34. tx::TransactionHash,
  35. };
  36. use darkfi_serial::{deserialize_async, serialize_async};
  37. use crate::{
  38. error::{WalletDbError, WalletDbResult},
  39. Drk,
  40. };
  41. impl Drk {
  42. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  43. /// new confirmed blocks. Upon receiving them, all the transactions are
  44. /// scanned and we check if any of them call the money contract, and if
  45. /// the payments are intended for us. If so, we decrypt them and append
  46. /// the metadata to our wallet. If a reorg block is received, we revert
  47. /// to its previous height and then scan it. We assume that the blocks
  48. /// up to that point are unchanged, since darkfid will just broadcast
  49. /// the sequence after the reorg.
  50. pub async fn subscribe_blocks(
  51. &self,
  52. endpoint: Url,
  53. ex: Arc<smol::Executor<'static>>,
  54. ) -> Result<()> {
  55. // Grab last confirmed block height
  56. let (last_confirmed_height, _) = self.get_last_confirmed_block().await?;
  57. // Handle genesis(0) block
  58. if last_confirmed_height == 0 {
  59. if let Err(e) = self.scan_blocks().await {
  60. return Err(Error::DatabaseError(format!(
  61. "[subscribe_blocks] Scanning from genesis block failed: {e:?}"
  62. )))
  63. }
  64. }
  65. // Grab last confirmed block again
  66. let (last_confirmed_height, last_confirmed_hash) = self.get_last_confirmed_block().await?;
  67. // Grab last scanned block
  68. let (mut last_scanned_height, last_scanned_hash) = match self.get_last_scanned_block() {
  69. Ok(last) => last,
  70. Err(e) => {
  71. return Err(Error::DatabaseError(format!(
  72. "[subscribe_blocks] Retrieving last scanned block failed: {e:?}"
  73. )))
  74. }
  75. };
  76. // Check if other blocks have been created
  77. if last_confirmed_height != last_scanned_height || last_confirmed_hash != last_scanned_hash
  78. {
  79. eprintln!("Warning: Last scanned block is not the last confirmed block.");
  80. eprintln!("You should first fully scan the blockchain, and then subscribe");
  81. return Err(Error::DatabaseError(
  82. "[subscribe_blocks] Blockchain not fully scanned".to_string(),
  83. ))
  84. }
  85. println!("Subscribing to receive notifications of incoming blocks");
  86. let publisher = Publisher::new();
  87. let subscription = publisher.clone().subscribe().await;
  88. let _publisher = publisher.clone();
  89. let _ex = ex.clone();
  90. StoppableTask::new().start(
  91. // Weird hack to prevent lifetimes hell
  92. async move {
  93. let rpc_client = RpcClient::new(endpoint, _ex).await?;
  94. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  95. rpc_client.subscribe(req, _publisher).await
  96. },
  97. |res| async move {
  98. match res {
  99. Ok(()) => { /* Do nothing */ }
  100. Err(e) => {
  101. eprintln!("[subscribe_blocks] JSON-RPC server error: {e:?}");
  102. publisher
  103. .notify(JsonResult::Error(JsonError::new(
  104. ErrorCode::InternalError,
  105. None,
  106. 0,
  107. )))
  108. .await;
  109. }
  110. }
  111. },
  112. Error::RpcServerStopped,
  113. ex,
  114. );
  115. println!("Detached subscription to background");
  116. println!("All is good. Waiting for block notifications...");
  117. let e = loop {
  118. match subscription.receive().await {
  119. JsonResult::Notification(n) => {
  120. println!("Got Block notification from darkfid subscription");
  121. if n.method != "blockchain.subscribe_blocks" {
  122. break Error::UnexpectedJsonRpc(format!(
  123. "Got foreign notification from darkfid: {}",
  124. n.method
  125. ))
  126. }
  127. // Verify parameters
  128. if !n.params.is_array() {
  129. break Error::UnexpectedJsonRpc(
  130. "Received notification params are not an array".to_string(),
  131. )
  132. }
  133. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  134. if params.is_empty() {
  135. break Error::UnexpectedJsonRpc(
  136. "Notification parameters are empty".to_string(),
  137. )
  138. }
  139. for param in params {
  140. let param = param.get::<String>().unwrap();
  141. let bytes = base64::decode(param).unwrap();
  142. let block: BlockInfo = deserialize_async(&bytes).await?;
  143. println!("Deserialized successfully. Scanning block...");
  144. // Check if a reorg block was received, to reset to its previous
  145. if block.header.height <= last_scanned_height {
  146. let reset_height = block.header.height.saturating_sub(1);
  147. if let Err(e) = self.reset_to_height(reset_height).await {
  148. return Err(Error::DatabaseError(format!(
  149. "[subscribe_blocks] Wallet state reset failed: {e:?}"
  150. )))
  151. }
  152. // Scan genesis again if needed
  153. if reset_height == 0 {
  154. let genesis = match self.get_block_by_height(reset_height).await {
  155. Ok(b) => b,
  156. Err(e) => {
  157. return Err(Error::Custom(format!(
  158. "[subscribe_blocks] RPC client request failed: {e:?}"
  159. )))
  160. }
  161. };
  162. if let Err(e) = self.scan_block(&genesis).await {
  163. return Err(Error::DatabaseError(format!(
  164. "[subscribe_blocks] Scanning block failed: {e:?}"
  165. )))
  166. };
  167. }
  168. }
  169. if let Err(e) = self.scan_block(&block).await {
  170. return Err(Error::DatabaseError(format!(
  171. "[subscribe_blocks] Scanning block failed: {e:?}"
  172. )))
  173. }
  174. // Set new last scanned block height
  175. last_scanned_height = block.header.height;
  176. }
  177. }
  178. JsonResult::Error(e) => {
  179. // Some error happened in the transmission
  180. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  181. }
  182. x => {
  183. // And this is weird
  184. break Error::UnexpectedJsonRpc(format!(
  185. "Got unexpected data from JSON-RPC: {x:?}"
  186. ))
  187. }
  188. }
  189. };
  190. Err(e)
  191. }
  192. /// `scan_block` will go over over transactions in a block and handle their calls
  193. /// based on the called contract. Additionally, will update `last_scanned_block` to
  194. /// the provided block height and will store its height, hash and inverse query.
  195. async fn scan_block(&self, block: &BlockInfo) -> Result<()> {
  196. // Reset wallet inverse cache state
  197. self.reset_inverse_cache().await?;
  198. // Keep track of our wallet transactions
  199. let mut wallet_txs = vec![];
  200. println!("=======================================");
  201. println!("{}", block.header);
  202. println!("=======================================");
  203. println!("[scan_block] Iterating over {} transactions", block.txs.len());
  204. for tx in block.txs.iter() {
  205. let tx_hash = tx.hash().to_string();
  206. let mut wallet_tx = false;
  207. println!("[scan_block] Processing transaction: {tx_hash}");
  208. for (i, call) in tx.calls.iter().enumerate() {
  209. if call.data.contract_id == *MONEY_CONTRACT_ID {
  210. println!("[scan_block] Found Money contract in call {i}");
  211. if self.apply_tx_money_data(i, &tx.calls, &tx_hash).await? {
  212. wallet_tx = true;
  213. };
  214. continue
  215. }
  216. if call.data.contract_id == *DAO_CONTRACT_ID {
  217. println!("[scan_block] Found DAO contract in call {i}");
  218. if self
  219. .apply_tx_dao_data(
  220. &call.data.data,
  221. TransactionHash::new(
  222. *blake3::hash(&serialize_async(tx).await).as_bytes(),
  223. ),
  224. i as u8,
  225. )
  226. .await?
  227. {
  228. wallet_tx = true;
  229. };
  230. continue
  231. }
  232. if call.data.contract_id == *DEPLOYOOOR_CONTRACT_ID {
  233. println!("[scan_block] Found DeployoOor contract in call {i}");
  234. // TODO: implement
  235. continue
  236. }
  237. // TODO: For now we skip non-native contract calls
  238. println!("[scan_block] Found non-native contract in call {i}, skipping.");
  239. }
  240. // If this is our wallet tx we mark it for update
  241. if wallet_tx {
  242. wallet_txs.push(tx);
  243. }
  244. }
  245. // Update wallet transactions records
  246. if let Err(e) = self.put_tx_history_records(&wallet_txs, "Confirmed").await {
  247. return Err(Error::DatabaseError(format!(
  248. "[scan_block] Inserting transaction history records failed: {e:?}"
  249. )))
  250. }
  251. // Store this block rollback query
  252. self.store_inverse_cache(block.header.height, &block.hash().to_string())?;
  253. Ok(())
  254. }
  255. /// Scans the blockchain for wallet relevant transactions,
  256. /// starting from the last scanned block. If a reorg has happened,
  257. /// we revert to its previous height and then scan from there.
  258. pub async fn scan_blocks(&self) -> WalletDbResult<()> {
  259. // Grab last scanned block height
  260. let (mut height, hash) = self.get_last_scanned_block()?;
  261. // Grab our last scanned block from darkfid
  262. let block = match self.get_block_by_height(height).await {
  263. Ok(b) => Some(b),
  264. // Check if block was found
  265. Err(Error::JsonRpcError((-32121, _))) => None,
  266. Err(e) => {
  267. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  268. return Err(WalletDbError::GenericError)
  269. }
  270. };
  271. // Check if a reorg has happened
  272. if block.is_none() || hash != block.unwrap().hash().to_string() {
  273. // Find the exact block height the reorg happened
  274. println!("A reorg has happened, finding last known common block...");
  275. height = height.saturating_sub(1);
  276. while height != 0 {
  277. // Grab our scanned block hash for that height
  278. let (_, scanned_block_hash, _) = self.get_scanned_block_record(height)?;
  279. // Grab the block from darkfid for that height
  280. let block = match self.get_block_by_height(height).await {
  281. Ok(b) => Some(b),
  282. // Check if block was found
  283. Err(Error::JsonRpcError((-32121, _))) => None,
  284. Err(e) => {
  285. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  286. return Err(WalletDbError::GenericError)
  287. }
  288. };
  289. // Continue to previous one if they don't match
  290. if block.is_none() || scanned_block_hash != block.unwrap().hash().to_string() {
  291. height = height.saturating_sub(1);
  292. continue
  293. }
  294. // Reset to its height
  295. println!("Last common block found: {height} - {scanned_block_hash}");
  296. self.reset_to_height(height).await?;
  297. break
  298. }
  299. }
  300. // If last scanned block is genesis(0) we reset,
  301. // otherwise continue with the next block height.
  302. if height == 0 {
  303. self.reset().await?;
  304. } else {
  305. height += 1;
  306. }
  307. loop {
  308. // Grab last confirmed block
  309. println!("Requested to scan from block number: {height}");
  310. let (last_height, last_hash) = match self.get_last_confirmed_block().await {
  311. Ok(last) => last,
  312. Err(e) => {
  313. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  314. return Err(WalletDbError::GenericError)
  315. }
  316. };
  317. println!("Last confirmed block reported by darkfid: {last_height} - {last_hash}");
  318. // Already scanned last confirmed block
  319. if height > last_height {
  320. return Ok(())
  321. }
  322. while height <= last_height {
  323. println!("Requesting block {height}...");
  324. let block = match self.get_block_by_height(height).await {
  325. Ok(b) => b,
  326. Err(e) => {
  327. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  328. return Err(WalletDbError::GenericError)
  329. }
  330. };
  331. println!("Block {height} received! Scanning block...");
  332. if let Err(e) = self.scan_block(&block).await {
  333. eprintln!("[scan_blocks] Scan block failed: {e:?}");
  334. return Err(WalletDbError::GenericError)
  335. };
  336. height += 1;
  337. }
  338. }
  339. }
  340. // Queries darkfid for last confirmed block.
  341. async fn get_last_confirmed_block(&self) -> Result<(u32, String)> {
  342. let rep = self
  343. .darkfid_daemon_request("blockchain.last_confirmed_block", &JsonValue::Array(vec![]))
  344. .await?;
  345. let params = rep.get::<Vec<JsonValue>>().unwrap();
  346. let height = *params[0].get::<f64>().unwrap() as u32;
  347. let hash = params[1].get::<String>().unwrap().clone();
  348. Ok((height, hash))
  349. }
  350. // Queries darkfid for a block with given height.
  351. async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  352. let params = self
  353. .darkfid_daemon_request(
  354. "blockchain.get_block",
  355. &JsonValue::Array(vec![JsonValue::String(height.to_string())]),
  356. )
  357. .await?;
  358. let param = params.get::<String>().unwrap();
  359. let bytes = base64::decode(param).unwrap();
  360. let block = deserialize_async(&bytes).await?;
  361. Ok(block)
  362. }
  363. /// Broadcast a given transaction to darkfid and forward onto the network.
  364. /// Returns the transaction ID upon success.
  365. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  366. println!("Broadcasting transaction...");
  367. let params =
  368. JsonValue::Array(vec![JsonValue::String(base64::encode(&serialize_async(tx).await))]);
  369. let rep = self.darkfid_daemon_request("tx.broadcast", &params).await?;
  370. let txid = rep.get::<String>().unwrap().clone();
  371. // Store transactions history record
  372. if let Err(e) = self.put_tx_history_record(tx, "Broadcasted").await {
  373. return Err(Error::DatabaseError(format!(
  374. "[broadcast_tx] Inserting transaction history record failed: {e:?}"
  375. )))
  376. }
  377. Ok(txid)
  378. }
  379. /// Queries darkfid for a tx with given hash.
  380. pub async fn get_tx(&self, tx_hash: &TransactionHash) -> Result<Option<Transaction>> {
  381. let tx_hash_str = tx_hash.to_string();
  382. match self
  383. .darkfid_daemon_request(
  384. "blockchain.get_tx",
  385. &JsonValue::Array(vec![JsonValue::String(tx_hash_str)]),
  386. )
  387. .await
  388. {
  389. Ok(param) => {
  390. let tx_bytes = base64::decode(param.get::<String>().unwrap()).unwrap();
  391. let tx = deserialize_async(&tx_bytes).await?;
  392. Ok(Some(tx))
  393. }
  394. Err(_) => Ok(None),
  395. }
  396. }
  397. /// Simulate the transaction with the state machine.
  398. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  399. let tx_str = base64::encode(&serialize_async(tx).await);
  400. let rep = self
  401. .darkfid_daemon_request(
  402. "tx.simulate",
  403. &JsonValue::Array(vec![JsonValue::String(tx_str)]),
  404. )
  405. .await?;
  406. let is_valid = *rep.get::<bool>().unwrap();
  407. Ok(is_valid)
  408. }
  409. /// Try to fetch zkas bincodes for the given `ContractId`.
  410. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  411. let params = JsonValue::Array(vec![JsonValue::String(format!("{contract_id}"))]);
  412. let rep = self.darkfid_daemon_request("blockchain.lookup_zkas", &params).await?;
  413. let params = rep.get::<Vec<JsonValue>>().unwrap();
  414. let mut ret = Vec::with_capacity(params.len());
  415. for param in params {
  416. let zkas_ns = param[0].get::<String>().unwrap().clone();
  417. let zkas_bincode_bytes = base64::decode(param[1].get::<String>().unwrap()).unwrap();
  418. ret.push((zkas_ns, zkas_bincode_bytes));
  419. }
  420. Ok(ret)
  421. }
  422. /// Queries darkfid for given transaction's gas.
  423. pub async fn get_tx_gas(&self, tx: &Transaction, include_fee: bool) -> Result<u64> {
  424. let params = JsonValue::Array(vec![
  425. JsonValue::String(base64::encode(&serialize_async(tx).await)),
  426. JsonValue::Boolean(include_fee),
  427. ]);
  428. let rep = self.darkfid_daemon_request("tx.calculate_gas", &params).await?;
  429. let gas = *rep.get::<f64>().unwrap() as u64;
  430. Ok(gas)
  431. }
  432. /// Queries darkfid for current best fork next height.
  433. pub async fn get_next_block_height(&self) -> Result<u32> {
  434. let rep = self
  435. .darkfid_daemon_request(
  436. "blockchain.best_fork_next_block_height",
  437. &JsonValue::Array(vec![]),
  438. )
  439. .await?;
  440. let next_height = *rep.get::<f64>().unwrap() as u32;
  441. Ok(next_height)
  442. }
  443. /// Queries darkfid for currently configured block target time.
  444. pub async fn get_block_target(&self) -> Result<u32> {
  445. let rep = self
  446. .darkfid_daemon_request("blockchain.block_target", &JsonValue::Array(vec![]))
  447. .await?;
  448. let next_height = *rep.get::<f64>().unwrap() as u32;
  449. Ok(next_height)
  450. }
  451. /// Auxiliary function to ping configured darkfid daemon for liveness.
  452. pub async fn ping(&self) -> Result<()> {
  453. println!("Executing ping request to darkfid...");
  454. let latency = Instant::now();
  455. let rep = self.darkfid_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  456. let latency = latency.elapsed();
  457. println!("Got reply: {rep:?}");
  458. println!("Latency: {latency:?}");
  459. Ok(())
  460. }
  461. /// Auxiliary function to execute a request towards the configured darkfid daemon JSON-RPC endpoint.
  462. pub async fn darkfid_daemon_request(
  463. &self,
  464. method: &str,
  465. params: &JsonValue,
  466. ) -> Result<JsonValue> {
  467. let Some(ref rpc_client) = self.rpc_client else { return Err(Error::RpcClientStopped) };
  468. let req = JsonRequest::new(method, params.clone());
  469. let rep = rpc_client.request(req).await?;
  470. Ok(rep)
  471. }
  472. /// Auxiliary function to stop current JSON-RPC client, if its initialized.
  473. pub async fn stop_rpc_client(&self) -> Result<()> {
  474. if let Some(ref rpc_client) = self.rpc_client {
  475. rpc_client.stop().await;
  476. };
  477. Ok(())
  478. }
  479. }