rpc.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 finalized 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 finalized block height
  56. let (last_finalized_height, _) = self.get_last_finalized_block().await?;
  57. // Handle genesis(0) block
  58. if last_finalized_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 finalized block again
  66. let (last_finalized_height, last_finalized_hash) = self.get_last_finalized_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_finalized_height != last_scanned_height || last_finalized_hash != last_scanned_hash
  78. {
  79. eprintln!("Warning: Last scanned block is not the last finalized 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. // TODO: Fully test this once darkfid broadcasts reorg sequences
  145. // Check if a reorg block was received, to reset to its previous
  146. if block.header.height <= last_scanned_height {
  147. if let Err(e) =
  148. self.reset_to_height(block.header.height.saturating_sub(1)).await
  149. {
  150. return Err(Error::DatabaseError(format!(
  151. "[subscribe_blocks] Wallet state reset failed: {e:?}"
  152. )))
  153. }
  154. }
  155. if let Err(e) = self.scan_block(&block).await {
  156. return Err(Error::DatabaseError(format!(
  157. "[subscribe_blocks] Scanning block failed: {e:?}"
  158. )))
  159. }
  160. // Set new last scanned block height
  161. last_scanned_height = block.header.height;
  162. }
  163. }
  164. JsonResult::Error(e) => {
  165. // Some error happened in the transmission
  166. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  167. }
  168. x => {
  169. // And this is weird
  170. break Error::UnexpectedJsonRpc(format!(
  171. "Got unexpected data from JSON-RPC: {x:?}"
  172. ))
  173. }
  174. }
  175. };
  176. Err(e)
  177. }
  178. /// `scan_block` will go over over transactions in a block and handle their calls
  179. /// based on the called contract. Additionally, will update `last_scanned_block` to
  180. /// the provided block height and will store its height, hash and inverse query.
  181. async fn scan_block(&self, block: &BlockInfo) -> Result<()> {
  182. // Reset wallet inverse cache state
  183. self.reset_inverse_cache().await?;
  184. // Keep track of our wallet transactions
  185. let mut wallet_txs = vec![];
  186. println!("=======================================");
  187. println!("{}", block.header);
  188. println!("=======================================");
  189. println!("[scan_block] Iterating over {} transactions", block.txs.len());
  190. for tx in block.txs.iter() {
  191. let tx_hash = tx.hash().to_string();
  192. let mut wallet_tx = false;
  193. println!("[scan_block] Processing transaction: {tx_hash}");
  194. for (i, call) in tx.calls.iter().enumerate() {
  195. if call.data.contract_id == *MONEY_CONTRACT_ID {
  196. println!("[scan_block] Found Money contract in call {i}");
  197. if self.apply_tx_money_data(i, &tx.calls, &tx_hash).await? {
  198. wallet_tx = true;
  199. };
  200. continue
  201. }
  202. if call.data.contract_id == *DAO_CONTRACT_ID {
  203. println!("[scan_block] Found DAO contract in call {i}");
  204. if self
  205. .apply_tx_dao_data(
  206. &call.data.data,
  207. TransactionHash::new(
  208. *blake3::hash(&serialize_async(tx).await).as_bytes(),
  209. ),
  210. i as u8,
  211. )
  212. .await?
  213. {
  214. wallet_tx = true;
  215. };
  216. continue
  217. }
  218. if call.data.contract_id == *DEPLOYOOOR_CONTRACT_ID {
  219. println!("[scan_block] Found DeployoOor contract in call {i}");
  220. // TODO: implement
  221. continue
  222. }
  223. // TODO: For now we skip non-native contract calls
  224. println!("[scan_block] Found non-native contract in call {i}, skipping.");
  225. }
  226. // If this is our wallet tx we mark it for update
  227. if wallet_tx {
  228. wallet_txs.push(tx);
  229. }
  230. }
  231. // Update wallet transactions records
  232. if let Err(e) = self.put_tx_history_records(&wallet_txs, "Finalized").await {
  233. return Err(Error::DatabaseError(format!(
  234. "[scan_block] Inserting transaction history records failed: {e:?}"
  235. )))
  236. }
  237. // Store this block rollback query
  238. self.store_inverse_cache(block.header.height, &block.hash().to_string())?;
  239. Ok(())
  240. }
  241. /// Scans the blockchain for wallet relevant transactions,
  242. /// starting from the last scanned block. If a reorg has happened,
  243. /// we revert to its previous height and then scan from there.
  244. pub async fn scan_blocks(&self) -> WalletDbResult<()> {
  245. // Grab last scanned block height
  246. let (mut height, hash) = self.get_last_scanned_block()?;
  247. // Grab our last scanned block from darkfid
  248. let block = match self.get_block_by_height(height).await {
  249. Ok(b) => Some(b),
  250. // Check if block was found
  251. Err(Error::JsonRpcError((-32121, _))) => None,
  252. Err(e) => {
  253. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  254. return Err(WalletDbError::GenericError)
  255. }
  256. };
  257. // Check if a reorg has happened
  258. if block.is_none() || hash != block.unwrap().hash().to_string() {
  259. // Find the exact block height the reorg happened
  260. println!("A reorg has happened, finding last known common block...");
  261. height = height.saturating_sub(1);
  262. while height != 0 {
  263. // Grab our scanned block hash for that height
  264. let (_, scanned_block_hash, _) = self.get_scanned_block_record(height)?;
  265. // Grab the block from darkfid for that height
  266. let block = match self.get_block_by_height(height).await {
  267. Ok(b) => Some(b),
  268. // Check if block was found
  269. Err(Error::JsonRpcError((-32121, _))) => None,
  270. Err(e) => {
  271. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  272. return Err(WalletDbError::GenericError)
  273. }
  274. };
  275. // Continue to previous one if they don't match
  276. if block.is_none() || scanned_block_hash != block.unwrap().hash().to_string() {
  277. height = height.saturating_sub(1);
  278. continue
  279. }
  280. // Reset to its height
  281. println!("Last common block found: {height} - {scanned_block_hash}");
  282. self.reset_to_height(height).await?;
  283. break
  284. }
  285. }
  286. // If last scanned block is genesis(0) we reset,
  287. // otherwise continue with the next block height.
  288. if height == 0 {
  289. self.reset().await?;
  290. } else {
  291. height += 1;
  292. }
  293. loop {
  294. // Grab last finalized block
  295. println!("Requested to scan from block number: {height}");
  296. let (last_height, last_hash) = match self.get_last_finalized_block().await {
  297. Ok(last) => last,
  298. Err(e) => {
  299. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  300. return Err(WalletDbError::GenericError)
  301. }
  302. };
  303. println!("Last finalized block reported by darkfid: {last_height} - {last_hash}");
  304. // Already scanned last finalized block
  305. if height > last_height {
  306. return Ok(())
  307. }
  308. while height <= last_height {
  309. println!("Requesting block {height}...");
  310. let block = match self.get_block_by_height(height).await {
  311. Ok(b) => b,
  312. Err(e) => {
  313. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  314. return Err(WalletDbError::GenericError)
  315. }
  316. };
  317. println!("Block {height} received! Scanning block...");
  318. if let Err(e) = self.scan_block(&block).await {
  319. eprintln!("[scan_blocks] Scan block failed: {e:?}");
  320. return Err(WalletDbError::GenericError)
  321. };
  322. height += 1;
  323. }
  324. }
  325. }
  326. // Queries darkfid for last finalized block.
  327. async fn get_last_finalized_block(&self) -> Result<(u32, String)> {
  328. let rep = self
  329. .darkfid_daemon_request("blockchain.last_finalized_block", &JsonValue::Array(vec![]))
  330. .await?;
  331. let params = rep.get::<Vec<JsonValue>>().unwrap();
  332. let height = *params[0].get::<f64>().unwrap() as u32;
  333. let hash = params[1].get::<String>().unwrap().clone();
  334. Ok((height, hash))
  335. }
  336. // Queries darkfid for a block with given height.
  337. async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  338. let params = self
  339. .darkfid_daemon_request(
  340. "blockchain.get_block",
  341. &JsonValue::Array(vec![JsonValue::String(height.to_string())]),
  342. )
  343. .await?;
  344. let param = params.get::<String>().unwrap();
  345. let bytes = base64::decode(param).unwrap();
  346. let block = deserialize_async(&bytes).await?;
  347. Ok(block)
  348. }
  349. /// Broadcast a given transaction to darkfid and forward onto the network.
  350. /// Returns the transaction ID upon success.
  351. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  352. println!("Broadcasting transaction...");
  353. let params =
  354. JsonValue::Array(vec![JsonValue::String(base64::encode(&serialize_async(tx).await))]);
  355. let rep = self.darkfid_daemon_request("tx.broadcast", &params).await?;
  356. let txid = rep.get::<String>().unwrap().clone();
  357. // Store transactions history record
  358. if let Err(e) = self.put_tx_history_record(tx, "Broadcasted").await {
  359. return Err(Error::DatabaseError(format!(
  360. "[broadcast_tx] Inserting transaction history record failed: {e:?}"
  361. )))
  362. }
  363. Ok(txid)
  364. }
  365. /// Queries darkfid for a tx with given hash.
  366. pub async fn get_tx(&self, tx_hash: &TransactionHash) -> Result<Option<Transaction>> {
  367. let tx_hash_str = tx_hash.to_string();
  368. match self
  369. .darkfid_daemon_request(
  370. "blockchain.get_tx",
  371. &JsonValue::Array(vec![JsonValue::String(tx_hash_str)]),
  372. )
  373. .await
  374. {
  375. Ok(param) => {
  376. let tx_bytes = base64::decode(param.get::<String>().unwrap()).unwrap();
  377. let tx = deserialize_async(&tx_bytes).await?;
  378. Ok(Some(tx))
  379. }
  380. Err(_) => Ok(None),
  381. }
  382. }
  383. /// Simulate the transaction with the state machine.
  384. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  385. let tx_str = base64::encode(&serialize_async(tx).await);
  386. let rep = self
  387. .darkfid_daemon_request(
  388. "tx.simulate",
  389. &JsonValue::Array(vec![JsonValue::String(tx_str)]),
  390. )
  391. .await?;
  392. let is_valid = *rep.get::<bool>().unwrap();
  393. Ok(is_valid)
  394. }
  395. /// Try to fetch zkas bincodes for the given `ContractId`.
  396. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  397. let params = JsonValue::Array(vec![JsonValue::String(format!("{contract_id}"))]);
  398. let rep = self.darkfid_daemon_request("blockchain.lookup_zkas", &params).await?;
  399. let params = rep.get::<Vec<JsonValue>>().unwrap();
  400. let mut ret = Vec::with_capacity(params.len());
  401. for param in params {
  402. let zkas_ns = param[0].get::<String>().unwrap().clone();
  403. let zkas_bincode_bytes = base64::decode(param[1].get::<String>().unwrap()).unwrap();
  404. ret.push((zkas_ns, zkas_bincode_bytes));
  405. }
  406. Ok(ret)
  407. }
  408. /// Queries darkfid for given transaction's gas.
  409. pub async fn get_tx_gas(&self, tx: &Transaction, include_fee: bool) -> Result<u64> {
  410. let params = JsonValue::Array(vec![
  411. JsonValue::String(base64::encode(&serialize_async(tx).await)),
  412. JsonValue::Boolean(include_fee),
  413. ]);
  414. let rep = self.darkfid_daemon_request("tx.calculate_gas", &params).await?;
  415. let gas = *rep.get::<f64>().unwrap() as u64;
  416. Ok(gas)
  417. }
  418. /// Queries darkfid for current best fork next height.
  419. pub async fn get_next_block_height(&self) -> Result<u32> {
  420. let rep = self
  421. .darkfid_daemon_request(
  422. "blockchain.best_fork_next_block_height",
  423. &JsonValue::Array(vec![]),
  424. )
  425. .await?;
  426. let next_height = *rep.get::<f64>().unwrap() as u32;
  427. Ok(next_height)
  428. }
  429. /// Queries darkfid for currently configured block target time.
  430. pub async fn get_block_target(&self) -> Result<u32> {
  431. let rep = self
  432. .darkfid_daemon_request("blockchain.block_target", &JsonValue::Array(vec![]))
  433. .await?;
  434. let next_height = *rep.get::<f64>().unwrap() as u32;
  435. Ok(next_height)
  436. }
  437. /// Auxiliary function to ping configured darkfid daemon for liveness.
  438. pub async fn ping(&self) -> Result<()> {
  439. println!("Executing ping request to darkfid...");
  440. let latency = Instant::now();
  441. let rep = self.darkfid_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  442. let latency = latency.elapsed();
  443. println!("Got reply: {rep:?}");
  444. println!("Latency: {latency:?}");
  445. Ok(())
  446. }
  447. /// Auxiliary function to execute a request towards the configured darkfid daemon JSON-RPC endpoint.
  448. pub async fn darkfid_daemon_request(
  449. &self,
  450. method: &str,
  451. params: &JsonValue,
  452. ) -> Result<JsonValue> {
  453. let Some(ref rpc_client) = self.rpc_client else { return Err(Error::RpcClientStopped) };
  454. let req = JsonRequest::new(method, params.clone());
  455. let rep = rpc_client.request(req).await?;
  456. Ok(rep)
  457. }
  458. /// Auxiliary function to stop current JSON-RPC client, if its initialized.
  459. pub async fn stop_rpc_client(&self) -> Result<()> {
  460. if let Some(ref rpc_client) = self.rpc_client {
  461. rpc_client.stop().await;
  462. };
  463. Ok(())
  464. }
  465. }