rpc_blocks.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 log::{error, info, warn};
  20. use tinyjson::JsonValue;
  21. use url::Url;
  22. use darkfi::{
  23. blockchain::BlockInfo,
  24. rpc::{
  25. client::RpcClient,
  26. jsonrpc::{
  27. ErrorCode::{InternalError, InvalidParams, ParseError},
  28. JsonError, JsonRequest, JsonResponse, JsonResult,
  29. },
  30. },
  31. system::{Publisher, StoppableTask, StoppableTaskPtr},
  32. util::encoding::base64,
  33. Error, Result,
  34. };
  35. use darkfi_serial::deserialize_async;
  36. use drk::error::{WalletDbError, WalletDbResult};
  37. use crate::BlockchainExplorer;
  38. impl BlockchainExplorer {
  39. // Queries darkfid for a block with given height.
  40. async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  41. let params = self
  42. .darkfid_daemon_request(
  43. "blockchain.get_block",
  44. &JsonValue::Array(vec![JsonValue::String(height.to_string())]),
  45. )
  46. .await?;
  47. let param = params.get::<String>().unwrap();
  48. let bytes = base64::decode(param).unwrap();
  49. let block = deserialize_async(&bytes).await?;
  50. Ok(block)
  51. }
  52. /// Syncs the blockchain starting from the last synced block.
  53. /// If reset flag is provided, all tables are reset, and start syncing from beginning.
  54. pub async fn sync_blocks(&self, reset: bool) -> WalletDbResult<()> {
  55. // Grab last synced block height
  56. let (mut height, _) = self.last_block().await?;
  57. // If last synced block is genesis (0) or reset flag
  58. // has been provided we reset, otherwise continue with
  59. // the next block height
  60. if height == 0 || reset {
  61. self.reset_blocks()?;
  62. height = 0;
  63. } else {
  64. height += 1;
  65. };
  66. loop {
  67. let rep = match self
  68. .darkfid_daemon_request("blockchain.last_known_block", &JsonValue::Array(vec![]))
  69. .await
  70. {
  71. Ok(r) => r,
  72. Err(e) => {
  73. error!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "[sync_blocks] RPC client request failed: {e:?}");
  74. return Err(WalletDbError::GenericError)
  75. }
  76. };
  77. let last = *rep.get::<f64>().unwrap() as u32;
  78. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Requested to sync from block number: {height}");
  79. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Last known block number reported by darkfid: {last}");
  80. // Already synced last known block
  81. if height > last {
  82. return Ok(())
  83. }
  84. while height <= last {
  85. info!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "Requesting block {height}... ");
  86. let block = match self.get_block_by_height(height).await {
  87. Ok(r) => r,
  88. Err(e) => {
  89. error!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "[sync_blocks] RPC client request failed: {e:?}");
  90. return Err(WalletDbError::GenericError)
  91. }
  92. };
  93. if let Err(e) = self.put_block(&(&block).into()).await {
  94. error!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "[sync_blocks] Insert block failed: {e:?}");
  95. return Err(WalletDbError::GenericError)
  96. };
  97. let block_hash = block.hash().to_string();
  98. for transaction in block.txs {
  99. if let Err(e) = self.put_transaction(&(&block_hash, &transaction).into()).await
  100. {
  101. error!(target: "blockchain-explorer::rpc_blocks::sync_blocks", "[sync_blocks] Insert block transaction failed: {e:?}");
  102. return Err(WalletDbError::GenericError)
  103. };
  104. }
  105. height += 1;
  106. }
  107. }
  108. }
  109. // RPCAPI:
  110. // Queries the database to retrieve last N blocks.
  111. // Returns an array of readable blocks upon success.
  112. //
  113. // **Params:**
  114. // * `array[0]`: `u16` Number of blocks to retrieve (as string)
  115. //
  116. // **Returns:**
  117. // * Array of `BlockRecord` encoded into a JSON.
  118. //
  119. // --> {"jsonrpc": "2.0", "method": "blocks.get_last_n_blocks", "params": ["10"], "id": 1}
  120. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  121. pub async fn blocks_get_last_n_blocks(&self, id: u16, params: JsonValue) -> JsonResult {
  122. let params = params.get::<Vec<JsonValue>>().unwrap();
  123. if params.len() != 1 || !params[0].is_string() {
  124. return JsonError::new(InvalidParams, None, id).into()
  125. }
  126. let n = match params[0].get::<String>().unwrap().parse::<u16>() {
  127. Ok(v) => v,
  128. Err(_) => return JsonError::new(ParseError, None, id).into(),
  129. };
  130. let blocks = match self.get_last_n_blocks(n) {
  131. Ok(v) => v,
  132. Err(e) => {
  133. error!(target: "blockchain-explorer::rpc_blocks::blocks_get_last_n_blocks", "Failed fetching blocks: {}", e);
  134. return JsonError::new(InternalError, None, id).into()
  135. }
  136. };
  137. let mut ret = vec![];
  138. for block in blocks {
  139. ret.push(block.to_json_array());
  140. }
  141. JsonResponse::new(JsonValue::Array(ret), id).into()
  142. }
  143. // RPCAPI:
  144. // Queries the database to retrieve blocks in provided heights range.
  145. // Returns an array of readable blocks upon success.
  146. //
  147. // **Params:**
  148. // * `array[0]`: `u32` Starting height (as string)
  149. // * `array[1]`: `u32` Ending height range (as string)
  150. //
  151. // **Returns:**
  152. // * Array of `BlockRecord` encoded into a JSON.
  153. //
  154. // --> {"jsonrpc": "2.0", "method": "blocks.get_blocks_in_heights_range", "params": ["10", "15"], "id": 1}
  155. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  156. pub async fn blocks_get_blocks_in_heights_range(
  157. &self,
  158. id: u16,
  159. params: JsonValue,
  160. ) -> JsonResult {
  161. let params = params.get::<Vec<JsonValue>>().unwrap();
  162. if params.len() != 2 || !params[0].is_string() || !params[1].is_string() {
  163. return JsonError::new(InvalidParams, None, id).into()
  164. }
  165. let start = match params[0].get::<String>().unwrap().parse::<u32>() {
  166. Ok(v) => v,
  167. Err(_) => return JsonError::new(ParseError, None, id).into(),
  168. };
  169. let end = match params[1].get::<String>().unwrap().parse::<u32>() {
  170. Ok(v) => v,
  171. Err(_) => return JsonError::new(ParseError, None, id).into(),
  172. };
  173. if start > end {
  174. return JsonError::new(ParseError, None, id).into()
  175. }
  176. let blocks = match self.get_blocks_in_heights_range(start, end) {
  177. Ok(v) => v,
  178. Err(e) => {
  179. error!(target: "blockchain-explorer::rpc_blocks::blocks_get_blocks_in_height_range", "Failed fetching blocks: {}", e);
  180. return JsonError::new(InternalError, None, id).into()
  181. }
  182. };
  183. let mut ret = vec![];
  184. for block in blocks {
  185. ret.push(block.to_json_array());
  186. }
  187. JsonResponse::new(JsonValue::Array(ret), id).into()
  188. }
  189. // RPCAPI:
  190. // Queries the database to retrieve the block corresponding to the provided hash.
  191. // Returns the readable block upon success.
  192. //
  193. // **Params:**
  194. // * `array[0]`: `String` Block header hash
  195. //
  196. // **Returns:**
  197. // * `BlockRecord` encoded into a JSON.
  198. //
  199. // --> {"jsonrpc": "2.0", "method": "blocks.get_block_by_hash", "params": ["5cc...2f9"], "id": 1}
  200. // <-- {"jsonrpc": "2.0", "result": {...}, "id": 1}
  201. pub async fn blocks_get_block_by_hash(&self, id: u16, params: JsonValue) -> JsonResult {
  202. let params = params.get::<Vec<JsonValue>>().unwrap();
  203. if params.len() != 1 || !params[0].is_string() {
  204. return JsonError::new(InvalidParams, None, id).into()
  205. }
  206. let header_hash = params[0].get::<String>().unwrap();
  207. let block = match self.get_block_by_hash(header_hash) {
  208. Ok(v) => v,
  209. Err(e) => {
  210. error!(target: "blockchain-explorer::rpc_blocks::blocks_get_get_block_by_hash", "Failed fetching block: {}", e);
  211. return JsonError::new(InternalError, None, id).into()
  212. }
  213. };
  214. JsonResponse::new(block.to_json_array(), id).into()
  215. }
  216. }
  217. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  218. /// new finalized blocks. Upon receiving them, store them to the database.
  219. pub async fn subscribe_blocks(
  220. explorer: Arc<BlockchainExplorer>,
  221. endpoint: Url,
  222. ex: Arc<smol::Executor<'static>>,
  223. ) -> Result<(StoppableTaskPtr, StoppableTaskPtr)> {
  224. let rep = explorer
  225. .darkfid_daemon_request("blockchain.last_known_block", &JsonValue::Array(vec![]))
  226. .await?;
  227. let last_known = *rep.get::<f64>().unwrap() as u32;
  228. let (last_synced, _) = match explorer.last_block().await {
  229. Ok(l) => l,
  230. Err(e) => {
  231. return Err(Error::RusqliteError(format!(
  232. "[subscribe_blocks] Retrieving last synced block failed: {e:?}"
  233. )))
  234. }
  235. };
  236. if last_known != last_synced {
  237. warn!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Warning: Last synced block is not the last known block.");
  238. warn!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "You should first fully sync the blockchain, and then subscribe");
  239. return Err(Error::RusqliteError(
  240. "[subscribe_blocks] Blockchain not fully synced".to_string(),
  241. ))
  242. }
  243. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Subscribing to receive notifications of incoming blocks");
  244. let publisher = Publisher::new();
  245. let subscription = publisher.clone().subscribe().await;
  246. let _ex = ex.clone();
  247. let subscriber_task = StoppableTask::new();
  248. subscriber_task.clone().start(
  249. // Weird hack to prevent lifetimes hell
  250. async move {
  251. let ex = _ex.clone();
  252. let rpc_client = RpcClient::new(endpoint, ex).await?;
  253. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  254. rpc_client.subscribe(req, publisher).await
  255. },
  256. |res| async move {
  257. match res {
  258. Ok(()) => { /* Do nothing */ }
  259. Err(e) => error!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  260. }
  261. },
  262. Error::RpcServerStopped,
  263. ex.clone(),
  264. );
  265. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Detached subscription to background");
  266. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "All is good. Waiting for block notifications...");
  267. let listener_task = StoppableTask::new();
  268. listener_task.clone().start(
  269. // Weird hack to prevent lifetimes hell
  270. async move {
  271. loop {
  272. match subscription.receive().await {
  273. JsonResult::Notification(n) => {
  274. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Got Block notification from darkfid subscription");
  275. if n.method != "blockchain.subscribe_blocks" {
  276. return Err(Error::UnexpectedJsonRpc(format!(
  277. "Got foreign notification from darkfid: {}",
  278. n.method
  279. )))
  280. }
  281. // Verify parameters
  282. if !n.params.is_array() {
  283. return Err(Error::UnexpectedJsonRpc(
  284. "Received notification params are not an array".to_string(),
  285. ))
  286. }
  287. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  288. if params.is_empty() {
  289. return Err(Error::UnexpectedJsonRpc(
  290. "Notification parameters are empty".to_string(),
  291. ))
  292. }
  293. for param in params {
  294. let param = param.get::<String>().unwrap();
  295. let bytes = base64::decode(param).unwrap();
  296. let block_data: BlockInfo = match deserialize_async(&bytes).await {
  297. Ok(b) => b,
  298. Err(e) => {
  299. return Err(Error::UnexpectedJsonRpc(format!(
  300. "[subscribe_blocks] Deserializing block failed: {e:?}"
  301. )))
  302. },
  303. };
  304. let header_hash = block_data.hash().to_string();
  305. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "=======================================");
  306. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Block header: {header_hash}");
  307. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "=======================================");
  308. info!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "Deserialized successfully. Storring block...");
  309. if let Err(e) = explorer.put_block(&(&block_data).into()).await {
  310. return Err(Error::RusqliteError(format!(
  311. "[subscribe_blocks] Insert block failed: {e:?}"
  312. )))
  313. }
  314. let block_hash = block_data.hash().to_string();
  315. for transaction in block_data.txs {
  316. if let Err(e) = explorer.put_transaction(&(&block_hash, &transaction).into()).await {
  317. return Err(Error::RusqliteError(format!(
  318. "[subscribe_blocks] Insert block transaction failed: {e:?}"
  319. )))
  320. };
  321. }
  322. }
  323. }
  324. JsonResult::Error(e) => {
  325. // Some error happened in the transmission
  326. return Err(Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}")))
  327. }
  328. x => {
  329. // And this is weird
  330. return Err(Error::UnexpectedJsonRpc(format!(
  331. "Got unexpected data from JSON-RPC: {x:?}"
  332. )))
  333. }
  334. }
  335. };
  336. },
  337. |res| async move {
  338. match res {
  339. Ok(()) => { /* Do nothing */ }
  340. Err(e) => error!(target: "blockchain-explorer::rpc_blocks::subscribe_blocks", "[subscribe_blocks] JSON-RPC server error: {e:?}"),
  341. }
  342. },
  343. Error::RpcServerStopped,
  344. ex,
  345. );
  346. Ok((subscriber_task, listener_task))
  347. }