rpc.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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_money_contract::client::{MONEY_INFO_COL_LAST_SCANNED_SLOT, MONEY_INFO_TABLE};
  33. use darkfi_serial::{deserialize, serialize};
  34. use super::{
  35. error::{WalletDbError, WalletDbResult},
  36. Drk,
  37. };
  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(
  45. &self,
  46. endpoint: Url,
  47. ex: Arc<smol::Executor<'static>>,
  48. ) -> Result<()> {
  49. let req = JsonRequest::new("blockchain.last_known_slot", JsonValue::Array(vec![]));
  50. let rep = self.rpc_client.request(req).await?;
  51. let last_known = *rep.get::<f64>().unwrap() as u64;
  52. let last_scanned = match self.last_scanned_slot().await {
  53. Ok(l) => l,
  54. Err(e) => {
  55. return Err(Error::RusqliteError(format!(
  56. "[subscribe_blocks] Retrieving last scanned slot failed: {e:?}"
  57. )))
  58. }
  59. };
  60. if last_known != last_scanned {
  61. eprintln!("Warning: Last scanned slot is not the last known slot.");
  62. eprintln!("You should first fully scan the blockchain, and then subscribe");
  63. return Err(Error::RusqliteError(
  64. "[subscribe_blocks] Blockchain not fully scanned".to_string(),
  65. ))
  66. }
  67. eprintln!("Subscribing to receive notifications of incoming blocks");
  68. let subscriber = Subscriber::new();
  69. let subscription = subscriber.clone().subscribe().await;
  70. let _ex = ex.clone();
  71. StoppableTask::new().start(
  72. // Weird hack to prevent lifetimes hell
  73. async move {
  74. let ex = _ex.clone();
  75. let rpc_client = RpcClient::new(endpoint, ex).await?;
  76. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  77. rpc_client.subscribe(req, subscriber).await
  78. },
  79. |res| async move {
  80. match res {
  81. Ok(()) => {
  82. eprintln!("wtf");
  83. }
  84. Err(e) => eprintln!("[subscribe_blocks] JSON-RPC server error: {e:?}"),
  85. }
  86. },
  87. Error::RpcServerStopped,
  88. ex,
  89. );
  90. eprintln!("Detached subscription to background");
  91. eprintln!("All is good. Waiting for block notifications...");
  92. let e = loop {
  93. match subscription.receive().await {
  94. JsonResult::Notification(n) => {
  95. eprintln!("Got Block notification from darkfid subscription");
  96. if n.method != "blockchain.subscribe_blocks" {
  97. break Error::UnexpectedJsonRpc(format!(
  98. "Got foreign notification from darkfid: {}",
  99. n.method
  100. ))
  101. }
  102. // Verify parameters
  103. if !n.params.is_array() {
  104. break Error::UnexpectedJsonRpc(
  105. "Received notification params are not an array".to_string(),
  106. )
  107. }
  108. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  109. if params.is_empty() {
  110. break Error::UnexpectedJsonRpc(
  111. "Notification parameters are empty".to_string(),
  112. )
  113. }
  114. for param in params {
  115. let param = param.get::<String>().unwrap();
  116. let bytes = bs58::decode(param).into_vec()?;
  117. let block_data: BlockInfo = deserialize(&bytes)?;
  118. eprintln!("=======================================");
  119. eprintln!("Block header:\n{:#?}", block_data.header);
  120. eprintln!("=======================================");
  121. eprintln!("Deserialized successfully. Scanning block...");
  122. if let Err(e) = self.scan_block_money(&block_data).await {
  123. return Err(Error::RusqliteError(format!(
  124. "[subscribe_blocks] Scaning blocks for Money failed: {e:?}"
  125. )))
  126. }
  127. self.scan_block_dao(&block_data).await?;
  128. if let Err(e) = self
  129. .update_tx_history_records_status(&block_data.txs, "Finalized")
  130. .await
  131. {
  132. return Err(Error::RusqliteError(format!(
  133. "[subscribe_blocks] Update transaction history record status failed: {e:?}"
  134. )))
  135. }
  136. }
  137. }
  138. JsonResult::Error(e) => {
  139. // Some error happened in the transmission
  140. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  141. }
  142. x => {
  143. // And this is weird
  144. break Error::UnexpectedJsonRpc(format!(
  145. "Got unexpected data from JSON-RPC: {x:?}"
  146. ))
  147. }
  148. }
  149. };
  150. Err(e)
  151. }
  152. /// `scan_block_money` will go over transactions in a block and fetch the ones dealing
  153. /// with the money contract. Then over all of them, try to see if any are related
  154. /// to us. If any are found, the metadata is extracted and placed into the wallet
  155. /// for future use.
  156. async fn scan_block_money(&self, block: &BlockInfo) -> Result<()> {
  157. eprintln!("[Money] Iterating over {} transactions", block.txs.len());
  158. for tx in block.txs.iter() {
  159. self.apply_tx_money_data(tx, true).await?;
  160. }
  161. // Write this slot into `last_scanned_slot`
  162. let query =
  163. format!("UPDATE {} SET {} = ?1;", MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT);
  164. if let Err(e) = self.wallet.exec_sql(&query, rusqlite::params![block.header.height]).await {
  165. return Err(Error::RusqliteError(format!(
  166. "[scan_block_money] Update last scanned slot failed: {e:?}"
  167. )))
  168. }
  169. Ok(())
  170. }
  171. /// `scan_block_dao` will go over transactions in a block and fetch the ones dealing
  172. /// with the dao contract. Then over all of them, try to see if any are related
  173. /// to us. If any are found, the metadata is extracted and placed into the wallet
  174. /// for future use.
  175. async fn scan_block_dao(&self, block: &BlockInfo) -> Result<()> {
  176. eprintln!("[DAO] Iterating over {} transactions", block.txs.len());
  177. for tx in block.txs.iter() {
  178. self.apply_tx_dao_data(tx, true).await?;
  179. }
  180. Ok(())
  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) -> WalletDbResult<()> {
  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", JsonValue::Array(vec![]));
  200. let rep = match self.rpc_client.request(req).await {
  201. Ok(r) => r,
  202. Err(e) => {
  203. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  204. return Err(WalletDbError::GenericError)
  205. }
  206. };
  207. let last = *rep.get::<f64>().unwrap() as u64;
  208. eprintln!("Requested to scan from slot number: {sl}");
  209. eprintln!("Last known slot number reported by darkfid: {last}");
  210. // Already scanned last known slot
  211. if sl == last {
  212. return Ok(())
  213. }
  214. while sl <= last {
  215. eprint!("Requesting slot {}... ", sl);
  216. let requested_block = match self.get_block_by_slot(sl).await {
  217. Ok(r) => r,
  218. Err(e) => {
  219. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  220. return Err(WalletDbError::GenericError)
  221. }
  222. };
  223. if let Some(block) = requested_block {
  224. eprintln!("Found");
  225. if let Err(e) = self.scan_block_money(&block).await {
  226. eprintln!("[scan_blocks] Scan block Money failed: {e:?}");
  227. return Err(WalletDbError::GenericError)
  228. };
  229. if let Err(e) = self.scan_block_dao(&block).await {
  230. eprintln!("[scan_blocks] Scan block DAO failed: {e:?}");
  231. return Err(WalletDbError::GenericError)
  232. };
  233. self.update_tx_history_records_status(&block.txs, "Finalized").await?;
  234. } else {
  235. eprintln!("Not found");
  236. // Write down the slot number into back to the wallet
  237. // This might be a bit intense, but we accept it for now.
  238. let query = format!(
  239. "UPDATE {} SET {} = ?1;",
  240. MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT
  241. );
  242. self.wallet.exec_sql(&query, rusqlite::params![sl]).await?;
  243. }
  244. sl += 1;
  245. }
  246. Ok(())
  247. }
  248. // Queries darkfid for a block with given slot
  249. async fn get_block_by_slot(&self, slot: u64) -> Result<Option<BlockInfo>> {
  250. let req = JsonRequest::new(
  251. "blockchain.get_slot",
  252. JsonValue::Array(vec![JsonValue::String(slot.to_string())]),
  253. );
  254. // This API is weird, we need some way of telling it's an empty slot and
  255. // not an error
  256. match self.rpc_client.request(req).await {
  257. Ok(params) => {
  258. let param = params.get::<String>().unwrap();
  259. let bytes = bs58::decode(param).into_vec()?;
  260. let block = deserialize(&bytes)?;
  261. Ok(Some(block))
  262. }
  263. Err(_) => Ok(None),
  264. }
  265. }
  266. /// Broadcast a given transaction to darkfid and forward onto the network.
  267. /// Returns the transaction ID upon success
  268. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  269. eprintln!("Broadcasting transaction...");
  270. let params =
  271. JsonValue::Array(vec![JsonValue::String(bs58::encode(&serialize(tx)).into_string())]);
  272. let req = JsonRequest::new("tx.broadcast", params);
  273. let rep = self.rpc_client.request(req).await?;
  274. let txid = rep.get::<String>().unwrap().clone();
  275. // Store transactions history record
  276. if let Err(e) = self.insert_tx_history_record(tx).await {
  277. return Err(Error::RusqliteError(format!(
  278. "[broadcast_tx] Inserting transaction history record failed: {e:?}"
  279. )))
  280. }
  281. Ok(txid)
  282. }
  283. /// Queries darkfid for a tx with given hash
  284. pub async fn get_tx(&self, tx_hash: &blake3::Hash) -> Result<Option<Transaction>> {
  285. let tx_hash_str = tx_hash.to_hex().to_string();
  286. let req = JsonRequest::new(
  287. "blockchain.get_tx",
  288. JsonValue::Array(vec![JsonValue::String(tx_hash_str)]),
  289. );
  290. match self.rpc_client.request(req).await {
  291. Ok(param) => {
  292. let tx_bytes = base64::decode(param.get::<String>().unwrap()).unwrap();
  293. let tx = deserialize(&tx_bytes)?;
  294. Ok(Some(tx))
  295. }
  296. Err(_) => Ok(None),
  297. }
  298. }
  299. /// Simulate the transaction with the state machine
  300. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  301. let tx_str = bs58::encode(&serialize(tx)).into_string();
  302. let req =
  303. JsonRequest::new("tx.simulate", JsonValue::Array(vec![JsonValue::String(tx_str)]));
  304. let rep = self.rpc_client.request(req).await?;
  305. let is_valid = *rep.get::<bool>().unwrap();
  306. Ok(is_valid)
  307. }
  308. }