rpc_blocks.rs 16 KB

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