rpc_blockchain.rs 12 KB

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