rpc_blockchain.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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).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. let e = loop {
  62. match subscription.receive().await {
  63. JsonResult::Notification(n) => {
  64. eprintln!("Got Block notification from darkfid subscription");
  65. if n.method != "blockchain.subscribe_blocks" {
  66. break anyhow!("Got foreign notification from darkfid: {}", n.method)
  67. }
  68. let Some(params) = n.params.as_array() else {
  69. break anyhow!("Received notification params are not an array")
  70. };
  71. if params.len() != 1 {
  72. break anyhow!("Notification parameters are not len 1")
  73. }
  74. let params = n.params.as_array().unwrap()[0].as_str().unwrap();
  75. let bytes = bs58::decode(params).into_vec()?;
  76. let block_data: BlockInfo = deserialize(&bytes)?;
  77. eprintln!("=======================================");
  78. eprintln!("Block header:\n{:#?}", block_data.header);
  79. eprintln!("=======================================");
  80. eprintln!("Deserialized successfully. Scanning block...");
  81. self.scan_block_money(&block_data).await?;
  82. self.scan_block_dao(&block_data).await?;
  83. }
  84. JsonResult::Error(e) => {
  85. // Some error happened in the transmission
  86. break anyhow!("Got error from JSON-RPC: {:?}", e)
  87. }
  88. x => {
  89. // And this is weird
  90. break anyhow!("Got unexpected data from JSON-RPC: {:?}", x)
  91. }
  92. }
  93. };
  94. Err(e)
  95. }
  96. /// `scan_block_dao` will go over transactions in a block and fetch the ones dealing
  97. /// with the dao contract. Then over all of them, try to see if any are related
  98. /// to us. If any are found, the metadata is extracted and placed into the wallet
  99. /// for future use.
  100. async fn scan_block_dao(&self, block: &BlockInfo) -> Result<()> {
  101. eprintln!("[DAO] Iterating over {} transactions", block.txs.len());
  102. for tx in block.txs.iter() {
  103. // Verify transaction is not in the erroneous set
  104. if self.is_erroneous_tx(tx).await? {
  105. continue
  106. }
  107. self.apply_tx_dao_data(tx, true).await?;
  108. }
  109. Ok(())
  110. }
  111. /// `scan_block_money` will go over transactions in a block and fetch the ones dealing
  112. /// with the money contract. Then over all of them, try to see if any are related
  113. /// to us. If any are found, the metadata is extracted and placed into the wallet
  114. /// for future use.
  115. async fn scan_block_money(&self, block: &BlockInfo) -> Result<()> {
  116. eprintln!("[Money] Iterating over {} transactions", block.txs.len());
  117. for tx in block.txs.iter() {
  118. // Verify transaction is not in the erroneous set
  119. if self.is_erroneous_tx(tx).await? {
  120. continue
  121. }
  122. self.apply_tx_money_data(tx, true).await?;
  123. }
  124. // Write this slot into `last_scanned_slot`
  125. let query =
  126. format!("UPDATE {} SET {} = ?1;", MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT);
  127. let params = json!([query, QueryType::Integer as u8, block.header.slot]);
  128. let req = JsonRequest::new("wallet.exec_sql", params);
  129. let _ = self.rpc_client.request(req).await?;
  130. Ok(())
  131. }
  132. /// Try to fetch zkas bincodes for the given `ContractId`.
  133. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  134. eprintln!("Querying zkas bincode for {}", contract_id);
  135. let params = json!([format!("{}", contract_id)]);
  136. let req = JsonRequest::new("blockchain.lookup_zkas", params);
  137. let rep = self.rpc_client.request(req).await?;
  138. let ret = serde_json::from_value(rep)?;
  139. Ok(ret)
  140. }
  141. /// Broadcast a given transaction to darkfid and forward onto the network.
  142. /// Returns the transaction ID upon success
  143. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  144. eprintln!("Broadcasting transaction...");
  145. let params = json!([bs58::encode(&serialize(tx)).into_string()]);
  146. let req = JsonRequest::new("tx.broadcast", params);
  147. let rep = self.rpc_client.request(req).await?;
  148. let txid = serde_json::from_value(rep)?;
  149. // At this point the tx is successfully broadcasted. We can add the
  150. // temp data into the wallet. Once scanned, it should mean that the
  151. // transaction was finalized, so at that point we actually add the
  152. // missing data. For now it'll be in an "unconfirmed" state.
  153. // TODO: Do the same for Money::*
  154. //self.wallet_apply_unconfirmed_dao_data(tx).await?;
  155. //self.wallet_apply_unconfirmed_money_data(tx).await?;
  156. Ok(txid)
  157. }
  158. /// Queries darkfid for a block with given slot
  159. async fn get_block_by_slot(&self, slot: u64) -> Result<Option<BlockInfo>> {
  160. let req = JsonRequest::new("blockchain.get_slot", json!([slot]));
  161. // This API is weird, we need some way of telling it's an empty slot and
  162. // not an error
  163. match self.rpc_client.request(req).await {
  164. Ok(v) => {
  165. let block_bytes: Vec<u8> = serde_json::from_value(v)?;
  166. let block = deserialize(&block_bytes)?;
  167. Ok(Some(block))
  168. }
  169. Err(_) => Ok(None),
  170. }
  171. }
  172. /// Scans the blockchain starting from the last scanned slot, for relevant
  173. /// money transfer transactions. If reset flag is provided, Merkle tree state
  174. /// and coins are reset, and start scanning from beginning. Alternatively,
  175. /// it looks for a checkpoint in the wallet to reset and start scanning from.
  176. pub async fn scan_blocks(&self, reset: bool) -> Result<()> {
  177. let mut sl = if reset {
  178. self.reset_money_tree().await?;
  179. self.reset_money_coins().await?;
  180. self.reset_dao_trees().await?;
  181. self.reset_daos().await?;
  182. self.reset_dao_proposals().await?;
  183. self.reset_dao_votes().await?;
  184. 0
  185. } else {
  186. self.last_scanned_slot().await?
  187. };
  188. let req = JsonRequest::new("blockchain.last_known_slot", json!([]));
  189. let rep = self.rpc_client.request(req).await?;
  190. let last: u64 = serde_json::from_value(rep)?;
  191. eprintln!("Requested to scan from slot number: {}", sl);
  192. eprintln!("Last known slot number reported by darkfid: {}", last);
  193. // Already scanned last known slot
  194. if sl == last {
  195. return Ok(())
  196. }
  197. // We set this up to handle an interrupt
  198. let mut signals = Signals::new([SIGTERM, SIGINT, SIGQUIT])?;
  199. let handle = signals.handle();
  200. let (term_tx, _term_rx) = smol::channel::bounded::<()>(1);
  201. let term_tx_ = term_tx.clone();
  202. let signals_task = task::spawn(async move {
  203. while let Some(signal) = signals.next().await {
  204. match signal {
  205. SIGTERM | SIGINT | SIGQUIT => term_tx_.close(),
  206. _ => unreachable!(),
  207. };
  208. }
  209. });
  210. while !term_tx.is_closed() {
  211. sl += 1;
  212. if sl > last {
  213. term_tx.close();
  214. break
  215. }
  216. eprint!("Requesting slot {}... ", sl);
  217. if let Some(block) = self.get_block_by_slot(sl).await? {
  218. eprintln!("Found");
  219. self.scan_block_money(&block).await?;
  220. self.scan_block_dao(&block).await?;
  221. } else {
  222. eprintln!("Not found");
  223. // Write down the slot number into back to the wallet
  224. // This might be a bit intense, but we accept it for now.
  225. let query = format!(
  226. "UPDATE {} SET {} = ?1;",
  227. MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT
  228. );
  229. let params = json!([query, QueryType::Integer as u8, sl]);
  230. let req = JsonRequest::new("wallet.exec_sql", params);
  231. let _ = self.rpc_client.request(req).await?;
  232. }
  233. }
  234. handle.close();
  235. signals_task.await;
  236. Ok(())
  237. }
  238. /// Queries darkfid to check if transaction is in the erroneous set
  239. async fn is_erroneous_tx(&self, tx: &Transaction) -> Result<bool> {
  240. let serialized = serialize(tx);
  241. let tx_hash = blake3::hash(&serialized);
  242. let req = JsonRequest::new("blockchain.is_erroneous_tx", json!([tx_hash.as_bytes()]));
  243. match self.rpc_client.request(req).await {
  244. Ok(v) => Ok(serde_json::from_value(v)?),
  245. Err(_) => Ok(false),
  246. }
  247. }
  248. }