rpc.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. money::{MONEY_INFO_COL_LAST_SCANNED_BLOCK, MONEY_INFO_TABLE},
  40. Drk,
  41. };
  42. impl Drk {
  43. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  44. /// new finalized blocks. Upon receiving them, all the transactions are
  45. /// scanned and we check if any of them call the money contract, and if
  46. /// the payments are intended for us. If so, we decrypt them and append
  47. /// the metadata to our wallet.
  48. pub async fn subscribe_blocks(
  49. &self,
  50. endpoint: Url,
  51. ex: Arc<smol::Executor<'static>>,
  52. ) -> Result<()> {
  53. let rep = self
  54. .darkfid_daemon_request("blockchain.last_known_block", &JsonValue::Array(vec![]))
  55. .await?;
  56. let last_known = *rep.get::<f64>().unwrap() as u32;
  57. let last_scanned = match self.last_scanned_block() {
  58. Ok(l) => l,
  59. Err(e) => {
  60. return Err(Error::DatabaseError(format!(
  61. "[subscribe_blocks] Retrieving last scanned block failed: {e:?}"
  62. )))
  63. }
  64. };
  65. if last_known != last_scanned {
  66. eprintln!("Warning: Last scanned block is not the last known block.");
  67. eprintln!("You should first fully scan the blockchain, and then subscribe");
  68. return Err(Error::DatabaseError(
  69. "[subscribe_blocks] Blockchain not fully scanned".to_string(),
  70. ))
  71. }
  72. println!("Subscribing to receive notifications of incoming blocks");
  73. let publisher = Publisher::new();
  74. let subscription = publisher.clone().subscribe().await;
  75. let _publisher = publisher.clone();
  76. let _ex = ex.clone();
  77. StoppableTask::new().start(
  78. // Weird hack to prevent lifetimes hell
  79. async move {
  80. let rpc_client = RpcClient::new(endpoint, _ex).await?;
  81. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  82. rpc_client.subscribe(req, _publisher).await
  83. },
  84. |res| async move {
  85. match res {
  86. Ok(()) => { /* Do nothing */ }
  87. Err(e) => {
  88. eprintln!("[subscribe_blocks] JSON-RPC server error: {e:?}");
  89. publisher
  90. .notify(JsonResult::Error(JsonError::new(
  91. ErrorCode::InternalError,
  92. None,
  93. 0,
  94. )))
  95. .await;
  96. }
  97. }
  98. },
  99. Error::RpcServerStopped,
  100. ex,
  101. );
  102. println!("Detached subscription to background");
  103. println!("All is good. Waiting for block notifications...");
  104. let e = loop {
  105. match subscription.receive().await {
  106. JsonResult::Notification(n) => {
  107. println!("Got Block notification from darkfid subscription");
  108. if n.method != "blockchain.subscribe_blocks" {
  109. break Error::UnexpectedJsonRpc(format!(
  110. "Got foreign notification from darkfid: {}",
  111. n.method
  112. ))
  113. }
  114. // Verify parameters
  115. if !n.params.is_array() {
  116. break Error::UnexpectedJsonRpc(
  117. "Received notification params are not an array".to_string(),
  118. )
  119. }
  120. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  121. if params.is_empty() {
  122. break Error::UnexpectedJsonRpc(
  123. "Notification parameters are empty".to_string(),
  124. )
  125. }
  126. for param in params {
  127. let param = param.get::<String>().unwrap();
  128. let bytes = base64::decode(param).unwrap();
  129. let block_data: BlockInfo = deserialize_async(&bytes).await?;
  130. println!("Deserialized successfully. Scanning block...");
  131. if let Err(e) = self.scan_block(&block_data).await {
  132. return Err(Error::DatabaseError(format!(
  133. "[subscribe_blocks] Scanning block failed: {e:?}"
  134. )))
  135. }
  136. let txs_hashes = match self.insert_tx_history_records(&block_data.txs).await {
  137. Ok(hashes) => hashes,
  138. Err(e) => {
  139. return Err(Error::DatabaseError(format!(
  140. "[subscribe_blocks] Inserting transaction history records failed: {e:?}"
  141. )))
  142. },
  143. };
  144. if let Err(e) =
  145. self.update_tx_history_records_status(&txs_hashes, "Finalized")
  146. {
  147. return Err(Error::DatabaseError(format!(
  148. "[subscribe_blocks] Update transaction history record status failed: {e:?}"
  149. )))
  150. }
  151. }
  152. }
  153. JsonResult::Error(e) => {
  154. // Some error happened in the transmission
  155. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  156. }
  157. x => {
  158. // And this is weird
  159. break Error::UnexpectedJsonRpc(format!(
  160. "Got unexpected data from JSON-RPC: {x:?}"
  161. ))
  162. }
  163. }
  164. };
  165. Err(e)
  166. }
  167. /// `scan_block` will go over over transactions in a block and handle their calls
  168. /// based on the called contract. Additionally, will update `last_scanned_block` to
  169. /// the probided block height.
  170. async fn scan_block(&self, block: &BlockInfo) -> Result<()> {
  171. println!("=======================================");
  172. println!("{}", block.header);
  173. println!("=======================================");
  174. println!("[scan_block] Iterating over {} transactions", block.txs.len());
  175. for tx in block.txs.iter() {
  176. let tx_hash = tx.hash().to_string();
  177. println!("[scan_block] Processing transaction: {tx_hash}");
  178. for (i, call) in tx.calls.iter().enumerate() {
  179. if call.data.contract_id == *MONEY_CONTRACT_ID {
  180. println!("[scan_block] Found Money contract in call {i}");
  181. self.apply_tx_money_data(i, &tx.calls, &tx_hash).await?;
  182. continue
  183. }
  184. if call.data.contract_id == *DAO_CONTRACT_ID {
  185. println!("[scan_block] Found DAO contract in call {i}");
  186. self.apply_tx_dao_data(
  187. &call.data.data,
  188. TransactionHash::new(*blake3::hash(&serialize_async(tx).await).as_bytes()),
  189. i as u8,
  190. )
  191. .await?;
  192. continue
  193. }
  194. if call.data.contract_id == *DEPLOYOOOR_CONTRACT_ID {
  195. println!("[scan_block] Found DeployoOor contract in call {i}");
  196. // TODO: implement
  197. continue
  198. }
  199. // TODO: For now we skip non-native contract calls
  200. println!("[scan_block] Found non-native contract in call {i}, skipping.");
  201. }
  202. }
  203. // Write this block height into `last_scanned_block`
  204. let query =
  205. format!("UPDATE {} SET {} = ?1;", *MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_BLOCK);
  206. if let Err(e) = self.wallet.exec_sql(&query, rusqlite::params![block.header.height]) {
  207. return Err(Error::DatabaseError(format!(
  208. "[scan_block] Update last scanned block failed: {e:?}"
  209. )))
  210. }
  211. Ok(())
  212. }
  213. /// Scans the blockchain starting from the last scanned block, for relevant
  214. /// money transfer transactions. If reset flag is provided, Merkle tree state
  215. /// and coins are reset, and start scanning from beginning. Alternatively,
  216. /// it looks for a checkpoint in the wallet to reset and start scanning from.
  217. pub async fn scan_blocks(&self, reset: bool) -> WalletDbResult<()> {
  218. // Grab last scanned block height
  219. let mut height = self.last_scanned_block()?;
  220. // If last scanned block is genesis (0) or reset flag
  221. // has been provided we reset, otherwise continue with
  222. // the next block height
  223. if height == 0 || reset {
  224. self.reset_money_tree().await?;
  225. self.reset_money_smt()?;
  226. self.reset_money_coins()?;
  227. self.reset_dao_trees().await?;
  228. self.reset_daos().await?;
  229. self.reset_dao_proposals().await?;
  230. self.reset_dao_votes()?;
  231. self.update_all_tx_history_records_status("Rejected")?;
  232. height = 0;
  233. } else {
  234. height += 1;
  235. };
  236. loop {
  237. let rep = match self
  238. .darkfid_daemon_request("blockchain.last_known_block", &JsonValue::Array(vec![]))
  239. .await
  240. {
  241. Ok(r) => r,
  242. Err(e) => {
  243. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  244. return Err(WalletDbError::GenericError)
  245. }
  246. };
  247. let last = *rep.get::<f64>().unwrap() as u32;
  248. println!("Requested to scan from block number: {height}");
  249. println!("Last known block number reported by darkfid: {last}");
  250. // Already scanned last known block
  251. if height > last {
  252. return Ok(())
  253. }
  254. while height <= last {
  255. println!("Requesting block {height}...");
  256. let block = match self.get_block_by_height(height).await {
  257. Ok(r) => r,
  258. Err(e) => {
  259. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  260. return Err(WalletDbError::GenericError)
  261. }
  262. };
  263. println!("Block {height} received! Scanning block...");
  264. if let Err(e) = self.scan_block(&block).await {
  265. eprintln!("[scan_blocks] Scan block failed: {e:?}");
  266. return Err(WalletDbError::GenericError)
  267. };
  268. let txs_hashes = self.insert_tx_history_records(&block.txs).await?;
  269. self.update_tx_history_records_status(&txs_hashes, "Finalized")?;
  270. height += 1;
  271. }
  272. }
  273. }
  274. // Queries darkfid for a block with given height.
  275. async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  276. let params = self
  277. .darkfid_daemon_request(
  278. "blockchain.get_block",
  279. &JsonValue::Array(vec![JsonValue::String(height.to_string())]),
  280. )
  281. .await?;
  282. let param = params.get::<String>().unwrap();
  283. let bytes = base64::decode(param).unwrap();
  284. let block = deserialize_async(&bytes).await?;
  285. Ok(block)
  286. }
  287. /// Broadcast a given transaction to darkfid and forward onto the network.
  288. /// Returns the transaction ID upon success.
  289. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  290. println!("Broadcasting transaction...");
  291. let params =
  292. JsonValue::Array(vec![JsonValue::String(base64::encode(&serialize_async(tx).await))]);
  293. let rep = self.darkfid_daemon_request("tx.broadcast", &params).await?;
  294. let txid = rep.get::<String>().unwrap().clone();
  295. // Store transactions history record
  296. if let Err(e) = self.insert_tx_history_record(tx).await {
  297. return Err(Error::DatabaseError(format!(
  298. "[broadcast_tx] Inserting transaction history record failed: {e:?}"
  299. )))
  300. }
  301. Ok(txid)
  302. }
  303. /// Queries darkfid for a tx with given hash.
  304. pub async fn get_tx(&self, tx_hash: &TransactionHash) -> Result<Option<Transaction>> {
  305. let tx_hash_str = tx_hash.to_string();
  306. match self
  307. .darkfid_daemon_request(
  308. "blockchain.get_tx",
  309. &JsonValue::Array(vec![JsonValue::String(tx_hash_str)]),
  310. )
  311. .await
  312. {
  313. Ok(param) => {
  314. let tx_bytes = base64::decode(param.get::<String>().unwrap()).unwrap();
  315. let tx = deserialize_async(&tx_bytes).await?;
  316. Ok(Some(tx))
  317. }
  318. Err(_) => Ok(None),
  319. }
  320. }
  321. /// Simulate the transaction with the state machine.
  322. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  323. let tx_str = base64::encode(&serialize_async(tx).await);
  324. let rep = self
  325. .darkfid_daemon_request(
  326. "tx.simulate",
  327. &JsonValue::Array(vec![JsonValue::String(tx_str)]),
  328. )
  329. .await?;
  330. let is_valid = *rep.get::<bool>().unwrap();
  331. Ok(is_valid)
  332. }
  333. /// Try to fetch zkas bincodes for the given `ContractId`.
  334. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  335. let params = JsonValue::Array(vec![JsonValue::String(format!("{contract_id}"))]);
  336. let rep = self.darkfid_daemon_request("blockchain.lookup_zkas", &params).await?;
  337. let params = rep.get::<Vec<JsonValue>>().unwrap();
  338. let mut ret = Vec::with_capacity(params.len());
  339. for param in params {
  340. let zkas_ns = param[0].get::<String>().unwrap().clone();
  341. let zkas_bincode_bytes = base64::decode(param[1].get::<String>().unwrap()).unwrap();
  342. ret.push((zkas_ns, zkas_bincode_bytes));
  343. }
  344. Ok(ret)
  345. }
  346. /// Queries darkfid for given transaction's gas.
  347. pub async fn get_tx_gas(&self, tx: &Transaction, include_fee: bool) -> Result<u64> {
  348. let params = JsonValue::Array(vec![
  349. JsonValue::String(base64::encode(&serialize_async(tx).await)),
  350. JsonValue::Boolean(include_fee),
  351. ]);
  352. let rep = self.darkfid_daemon_request("tx.calculate_gas", &params).await?;
  353. let gas = *rep.get::<f64>().unwrap() as u64;
  354. Ok(gas)
  355. }
  356. /// Queries darkfid for current best fork next height.
  357. pub async fn get_next_block_height(&self) -> Result<u32> {
  358. let rep = self
  359. .darkfid_daemon_request(
  360. "blockchain.best_fork_next_block_height",
  361. &JsonValue::Array(vec![]),
  362. )
  363. .await?;
  364. let next_height = *rep.get::<f64>().unwrap() as u32;
  365. Ok(next_height)
  366. }
  367. /// Queries darkfid for currently configured block target time.
  368. pub async fn get_block_target(&self) -> Result<u32> {
  369. let rep = self
  370. .darkfid_daemon_request("blockchain.block_target", &JsonValue::Array(vec![]))
  371. .await?;
  372. let next_height = *rep.get::<f64>().unwrap() as u32;
  373. Ok(next_height)
  374. }
  375. /// Auxiliary function to ping configured darkfid daemon for liveness.
  376. pub async fn ping(&self) -> Result<()> {
  377. println!("Executing ping request to darkfid...");
  378. let latency = Instant::now();
  379. let rep = self.darkfid_daemon_request("ping", &JsonValue::Array(vec![])).await?;
  380. let latency = latency.elapsed();
  381. println!("Got reply: {rep:?}");
  382. println!("Latency: {latency:?}");
  383. Ok(())
  384. }
  385. /// Auxiliary function to execute a request towards the configured darkfid daemon JSON-RPC endpoint.
  386. pub async fn darkfid_daemon_request(
  387. &self,
  388. method: &str,
  389. params: &JsonValue,
  390. ) -> Result<JsonValue> {
  391. let Some(ref rpc_client) = self.rpc_client else { return Err(Error::RpcClientStopped) };
  392. let req = JsonRequest::new(method, params.clone());
  393. let rep = rpc_client.request(req).await?;
  394. Ok(rep)
  395. }
  396. /// Auxiliary function to stop current JSON-RPC client, if its initialized.
  397. pub async fn stop_rpc_client(&self) -> Result<()> {
  398. if let Some(ref rpc_client) = self.rpc_client {
  399. rpc_client.stop().await;
  400. };
  401. Ok(())
  402. }
  403. }