rpc_blocks.rs 16 KB

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