rpc.rs 14 KB

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