rpc_blockchain.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 anyhow::{anyhow, Result};
  19. use async_std::{stream::StreamExt, task};
  20. use darkfi::{
  21. consensus::BlockInfo,
  22. rpc::{
  23. client::RpcClient,
  24. jsonrpc::{JsonRequest, JsonResult},
  25. },
  26. system::Subscriber,
  27. tx::Transaction,
  28. wallet::walletdb::QueryType,
  29. };
  30. use darkfi_money_contract::client::{MONEY_INFO_COL_LAST_SCANNED_SLOT, MONEY_INFO_TABLE};
  31. use darkfi_sdk::crypto::ContractId;
  32. use darkfi_serial::{deserialize, serialize};
  33. use serde_json::json;
  34. use signal_hook::consts::{SIGINT, SIGQUIT, SIGTERM};
  35. use signal_hook_async_std::Signals;
  36. use url::Url;
  37. use super::Drk;
  38. impl Drk {
  39. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  40. /// new finalized blocks. Upon receiving them, all the transactions are
  41. /// scanned and we check if any of them call the money contract, and if
  42. /// the payments are intended for us. If so, we decrypt them and append
  43. /// the metadata to our wallet.
  44. pub async fn subscribe_blocks(&self, endpoint: Url) -> Result<()> {
  45. let req = JsonRequest::new("blockchain.last_known_slot", json!([]));
  46. let rep = self.rpc_client.request(req).await?;
  47. let last_known: u64 = serde_json::from_value(rep)?;
  48. let last_scanned = self.last_scanned_slot().await?;
  49. if last_known != last_scanned {
  50. eprintln!("Warning: Last scanned slot is not the last known slot.");
  51. eprintln!("You should first fully scan the blockchain, and then subscribe");
  52. return Err(anyhow!("Blockchain not fully scanned"))
  53. }
  54. eprintln!("Subscribing to receive notifications of incoming blocks");
  55. let subscriber = Subscriber::new();
  56. let subscription = subscriber.clone().subscribe().await;
  57. let rpc_client = RpcClient::new(endpoint, None).await?;
  58. let req = JsonRequest::new("blockchain.subscribe_blocks", json!([]));
  59. task::spawn(async move { rpc_client.subscribe(req, subscriber).await.unwrap() });
  60. eprintln!("Detached subscription to background");
  61. eprintln!("All is good. Waiting for block notifications...");
  62. let e = loop {
  63. match subscription.receive().await {
  64. JsonResult::Notification(n) => {
  65. eprintln!("Got Block notification from darkfid subscription");
  66. if n.method != "blockchain.subscribe_blocks" {
  67. break anyhow!("Got foreign notification from darkfid: {}", n.method)
  68. }
  69. let Some(params) = n.params.as_array() else {
  70. break anyhow!("Received notification params are not an array")
  71. };
  72. if params.len() != 1 {
  73. break anyhow!("Notification parameters are not len 1")
  74. }
  75. let params = n.params.as_array().unwrap()[0].as_str().unwrap();
  76. let bytes = bs58::decode(params).into_vec()?;
  77. let block_data: BlockInfo = deserialize(&bytes)?;
  78. eprintln!("=======================================");
  79. eprintln!("Block header:\n{:#?}", block_data.header);
  80. eprintln!("=======================================");
  81. eprintln!("Deserialized successfully. Scanning block...");
  82. self.scan_block_money(&block_data).await?;
  83. self.scan_block_dao(&block_data).await?;
  84. self.update_tx_history_records_status(&block_data.txs, "Finalized").await?;
  85. }
  86. JsonResult::Error(e) => {
  87. // Some error happened in the transmission
  88. break anyhow!("Got error from JSON-RPC: {:?}", e)
  89. }
  90. x => {
  91. // And this is weird
  92. break anyhow!("Got unexpected data from JSON-RPC: {:?}", x)
  93. }
  94. }
  95. };
  96. Err(e)
  97. }
  98. /// `scan_block_dao` will go over transactions in a block and fetch the ones dealing
  99. /// with the dao contract. Then over all of them, try to see if any are related
  100. /// to us. If any are found, the metadata is extracted and placed into the wallet
  101. /// for future use.
  102. async fn scan_block_dao(&self, block: &BlockInfo) -> Result<()> {
  103. eprintln!("[DAO] Iterating over {} transactions", block.txs.len());
  104. for tx in block.txs.iter() {
  105. self.apply_tx_dao_data(tx, true).await?;
  106. }
  107. Ok(())
  108. }
  109. /// `scan_block_money` will go over transactions in a block and fetch the ones dealing
  110. /// with the money contract. Then over all of them, try to see if any are related
  111. /// to us. If any are found, the metadata is extracted and placed into the wallet
  112. /// for future use.
  113. async fn scan_block_money(&self, block: &BlockInfo) -> Result<()> {
  114. eprintln!("[Money] Iterating over {} transactions", block.txs.len());
  115. for tx in block.txs.iter() {
  116. self.apply_tx_money_data(tx, true).await?;
  117. }
  118. // Write this slot into `last_scanned_slot`
  119. let query =
  120. format!("UPDATE {} SET {} = ?1;", MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT);
  121. let params = json!([query, QueryType::Integer as u8, block.header.slot]);
  122. let req = JsonRequest::new("wallet.exec_sql", params);
  123. let _ = self.rpc_client.request(req).await?;
  124. Ok(())
  125. }
  126. /// Try to fetch zkas bincodes for the given `ContractId`.
  127. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  128. eprintln!("Querying zkas bincode for {}", contract_id);
  129. let params = json!([format!("{}", contract_id)]);
  130. let req = JsonRequest::new("blockchain.lookup_zkas", params);
  131. let rep = self.rpc_client.request(req).await?;
  132. let ret = serde_json::from_value(rep)?;
  133. Ok(ret)
  134. }
  135. /// Broadcast a given transaction to darkfid and forward onto the network.
  136. /// Returns the transaction ID upon success
  137. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  138. eprintln!("Broadcasting transaction...");
  139. let params = json!([bs58::encode(&serialize(tx)).into_string()]);
  140. let req = JsonRequest::new("tx.broadcast", params);
  141. let rep = self.rpc_client.request(req).await?;
  142. let txid = serde_json::from_value(rep)?;
  143. // Store transactions history record
  144. self.insert_tx_history_record(tx).await?;
  145. Ok(txid)
  146. }
  147. /// Simulate the transaction with the state machine
  148. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  149. let params = json!([bs58::encode(&serialize(tx)).into_string()]);
  150. let req = JsonRequest::new("tx.simulate", params);
  151. let rep = self.rpc_client.request(req).await?;
  152. let is_valid = serde_json::from_value(rep)?;
  153. Ok(is_valid)
  154. }
  155. /// Queries darkfid for a block with given slot
  156. async fn get_block_by_slot(&self, slot: u64) -> Result<Option<BlockInfo>> {
  157. let req = JsonRequest::new("blockchain.get_slot", json!([slot]));
  158. // This API is weird, we need some way of telling it's an empty slot and
  159. // not an error
  160. match self.rpc_client.request(req).await {
  161. Ok(v) => {
  162. let block_bytes: Vec<u8> = serde_json::from_value(v)?;
  163. let block = deserialize(&block_bytes)?;
  164. Ok(Some(block))
  165. }
  166. Err(_) => Ok(None),
  167. }
  168. }
  169. /// Queries darkfid for a tx with given hash
  170. pub async fn get_tx(&self, tx_hash: &blake3::Hash) -> Result<Option<Transaction>> {
  171. let tx_hash_str: &str = &tx_hash.to_hex();
  172. let req = JsonRequest::new("blockchain.get_tx", json!([tx_hash_str]));
  173. match self.rpc_client.request(req).await {
  174. Ok(v) => {
  175. let tx_bytes: Vec<u8> = serde_json::from_value(v)?;
  176. let tx = deserialize(&tx_bytes)?;
  177. Ok(Some(tx))
  178. }
  179. Err(_) => Ok(None),
  180. }
  181. }
  182. /// Scans the blockchain starting from the last scanned slot, for relevant
  183. /// money transfer transactions. If reset flag is provided, Merkle tree state
  184. /// and coins are reset, and start scanning from beginning. Alternatively,
  185. /// it looks for a checkpoint in the wallet to reset and start scanning from.
  186. pub async fn scan_blocks(&self, reset: bool) -> Result<()> {
  187. let mut sl = if reset {
  188. self.reset_money_tree().await?;
  189. self.reset_money_coins().await?;
  190. self.reset_dao_trees().await?;
  191. self.reset_daos().await?;
  192. self.reset_dao_proposals().await?;
  193. self.reset_dao_votes().await?;
  194. self.update_all_tx_history_records_status("Rejected").await?;
  195. 0
  196. } else {
  197. self.last_scanned_slot().await?
  198. };
  199. let req = JsonRequest::new("blockchain.last_known_slot", json!([]));
  200. let rep = self.rpc_client.request(req).await?;
  201. let last: u64 = serde_json::from_value(rep)?;
  202. eprintln!("Requested to scan from slot number: {}", sl);
  203. eprintln!("Last known slot number reported by darkfid: {}", last);
  204. // Already scanned last known slot
  205. if sl == last {
  206. return Ok(())
  207. }
  208. // We set this up to handle an interrupt
  209. let mut signals = Signals::new([SIGTERM, SIGINT, SIGQUIT])?;
  210. let handle = signals.handle();
  211. let (term_tx, _term_rx) = smol::channel::bounded::<()>(1);
  212. let term_tx_ = term_tx.clone();
  213. let signals_task = task::spawn(async move {
  214. while let Some(signal) = signals.next().await {
  215. match signal {
  216. SIGTERM | SIGINT | SIGQUIT => term_tx_.close(),
  217. _ => unreachable!(),
  218. };
  219. }
  220. });
  221. while !term_tx.is_closed() {
  222. sl += 1;
  223. if sl > last {
  224. term_tx.close();
  225. break
  226. }
  227. eprint!("Requesting slot {}... ", sl);
  228. if let Some(block) = self.get_block_by_slot(sl).await? {
  229. eprintln!("Found");
  230. self.scan_block_money(&block).await?;
  231. self.scan_block_dao(&block).await?;
  232. self.update_tx_history_records_status(&block.txs, "Finalized").await?;
  233. } else {
  234. eprintln!("Not found");
  235. // Write down the slot number into back to the wallet
  236. // This might be a bit intense, but we accept it for now.
  237. let query = format!(
  238. "UPDATE {} SET {} = ?1;",
  239. MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT
  240. );
  241. let params = json!([query, QueryType::Integer as u8, sl]);
  242. let req = JsonRequest::new("wallet.exec_sql", params);
  243. let _ = self.rpc_client.request(req).await?;
  244. }
  245. }
  246. handle.close();
  247. signals_task.await;
  248. Ok(())
  249. }
  250. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  251. /// erroneous transactions rejections.
  252. pub async fn subscribe_err_txs(&self, endpoint: Url) -> Result<()> {
  253. eprintln!("Subscribing to receive notifications of erroneous transactions");
  254. let subscriber = Subscriber::new();
  255. let subscription = subscriber.clone().subscribe().await;
  256. let rpc_client = RpcClient::new(endpoint, None).await?;
  257. let req = JsonRequest::new("blockchain.subscribe_err_txs", json!([]));
  258. task::spawn(async move { rpc_client.subscribe(req, subscriber).await.unwrap() });
  259. eprintln!("Detached subscription to background");
  260. eprintln!("All is good. Waiting for erroneous transactions notifications...");
  261. let e = loop {
  262. match subscription.receive().await {
  263. JsonResult::Notification(n) => {
  264. eprintln!("Got erroneous transaction notification from darkfid subscription");
  265. if n.method != "blockchain.subscribe_err_txs" {
  266. break anyhow!("Got foreign notification from darkfid: {}", n.method)
  267. }
  268. let Some(params) = n.params.as_array() else {
  269. break anyhow!("Received notification params are not an array")
  270. };
  271. if params.len() != 1 {
  272. break anyhow!("Notification parameters are not len 1")
  273. }
  274. let params = n.params.as_array().unwrap()[0].as_str().unwrap();
  275. let bytes = bs58::decode(params).into_vec()?;
  276. let tx_hash: String = deserialize(&bytes)?;
  277. eprintln!("===================================");
  278. eprintln!("Erroneous transaction: {}", tx_hash);
  279. eprintln!("===================================");
  280. self.update_tx_history_record_status(&tx_hash, "Rejected").await?;
  281. }
  282. JsonResult::Error(e) => {
  283. // Some error happened in the transmission
  284. break anyhow!("Got error from JSON-RPC: {:?}", e)
  285. }
  286. x => {
  287. // And this is weird
  288. break anyhow!("Got unexpected data from JSON-RPC: {:?}", x)
  289. }
  290. }
  291. };
  292. Err(e)
  293. }
  294. }