rpc.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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::{Publisher, StoppableTask},
  28. tx::Transaction,
  29. util::encoding::base64,
  30. Error, Result,
  31. };
  32. use darkfi_sdk::{
  33. crypto::{ContractId, DAO_CONTRACT_ID, DEPLOYOOOR_CONTRACT_ID, MONEY_CONTRACT_ID},
  34. tx::TransactionHash,
  35. };
  36. use darkfi_serial::{deserialize_async, serialize_async};
  37. use crate::{
  38. error::{WalletDbError, WalletDbResult},
  39. money::{MONEY_INFO_COL_LAST_SCANNED_BLOCK, MONEY_INFO_TABLE},
  40. Drk,
  41. };
  42. impl Drk {
  43. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  44. /// new finalized blocks. Upon receiving them, all the transactions are
  45. /// scanned and we check if any of them call the money contract, and if
  46. /// the payments are intended for us. If so, we decrypt them and append
  47. /// the metadata to our wallet.
  48. pub async fn subscribe_blocks(
  49. &self,
  50. endpoint: Url,
  51. ex: Arc<smol::Executor<'static>>,
  52. ) -> Result<()> {
  53. let req = JsonRequest::new("blockchain.last_known_block", JsonValue::Array(vec![]));
  54. let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
  55. let last_known = *rep.get::<f64>().unwrap() as u32;
  56. let last_scanned = match self.last_scanned_block() {
  57. Ok(l) => l,
  58. Err(e) => {
  59. return Err(Error::RusqliteError(format!(
  60. "[subscribe_blocks] Retrieving last scanned block failed: {e:?}"
  61. )))
  62. }
  63. };
  64. if last_known != last_scanned {
  65. eprintln!("Warning: Last scanned block is not the last known block.");
  66. eprintln!("You should first fully scan the blockchain, and then subscribe");
  67. return Err(Error::RusqliteError(
  68. "[subscribe_blocks] Blockchain not fully scanned".to_string(),
  69. ))
  70. }
  71. println!("Subscribing to receive notifications of incoming blocks");
  72. let publisher = Publisher::new();
  73. let subscription = publisher.clone().subscribe().await;
  74. let _ex = ex.clone();
  75. StoppableTask::new().start(
  76. // Weird hack to prevent lifetimes hell
  77. async move {
  78. let ex = _ex.clone();
  79. let rpc_client = RpcClient::new(endpoint, ex).await?;
  80. let req = JsonRequest::new("blockchain.subscribe_blocks", JsonValue::Array(vec![]));
  81. rpc_client.subscribe(req, publisher).await
  82. },
  83. |res| async move {
  84. match res {
  85. Ok(()) => {
  86. eprintln!("wtf");
  87. }
  88. Err(e) => eprintln!("[subscribe_blocks] JSON-RPC server error: {e:?}"),
  89. }
  90. },
  91. Error::RpcServerStopped,
  92. ex,
  93. );
  94. println!("Detached subscription to background");
  95. println!("All is good. Waiting for block notifications...");
  96. let e = loop {
  97. match subscription.receive().await {
  98. JsonResult::Notification(n) => {
  99. println!("Got Block notification from darkfid subscription");
  100. if n.method != "blockchain.subscribe_blocks" {
  101. break Error::UnexpectedJsonRpc(format!(
  102. "Got foreign notification from darkfid: {}",
  103. n.method
  104. ))
  105. }
  106. // Verify parameters
  107. if !n.params.is_array() {
  108. break Error::UnexpectedJsonRpc(
  109. "Received notification params are not an array".to_string(),
  110. )
  111. }
  112. let params = n.params.get::<Vec<JsonValue>>().unwrap();
  113. if params.is_empty() {
  114. break Error::UnexpectedJsonRpc(
  115. "Notification parameters are empty".to_string(),
  116. )
  117. }
  118. for param in params {
  119. let param = param.get::<String>().unwrap();
  120. let bytes = base64::decode(param).unwrap();
  121. let block_data: BlockInfo = deserialize_async(&bytes).await?;
  122. println!("=======================================");
  123. println!("Block header:\n{:#?}", block_data.header);
  124. println!("=======================================");
  125. println!("Deserialized successfully. Scanning block...");
  126. if let Err(e) = self.scan_block(&block_data).await {
  127. return Err(Error::RusqliteError(format!(
  128. "[subscribe_blocks] Scanning block failed: {e:?}"
  129. )))
  130. }
  131. let txs_hashes = match self.insert_tx_history_records(&block_data.txs).await {
  132. Ok(hashes) => hashes,
  133. Err(e) => {
  134. return Err(Error::RusqliteError(format!(
  135. "[subscribe_blocks] Inserting transaction history records failed: {e:?}"
  136. )))
  137. },
  138. };
  139. if let Err(e) =
  140. self.update_tx_history_records_status(&txs_hashes, "Finalized")
  141. {
  142. return Err(Error::RusqliteError(format!(
  143. "[subscribe_blocks] Update transaction history record status failed: {e:?}"
  144. )))
  145. }
  146. }
  147. }
  148. JsonResult::Error(e) => {
  149. // Some error happened in the transmission
  150. break Error::UnexpectedJsonRpc(format!("Got error from JSON-RPC: {e:?}"))
  151. }
  152. x => {
  153. // And this is weird
  154. break Error::UnexpectedJsonRpc(format!(
  155. "Got unexpected data from JSON-RPC: {x:?}"
  156. ))
  157. }
  158. }
  159. };
  160. Err(e)
  161. }
  162. /// `scan_block` will go over over transactions in a block and handle their calls
  163. /// based on the called contract. Additionally, will update `last_scanned_block` to
  164. /// the probided block height.
  165. async fn scan_block(&self, block: &BlockInfo) -> Result<()> {
  166. println!("[scan_block] Iterating over {} transactions", block.txs.len());
  167. for tx in block.txs.iter() {
  168. let tx_hash = tx.hash().to_string();
  169. println!("[scan_block] Processing transaction: {tx_hash}");
  170. for (i, call) in tx.calls.iter().enumerate() {
  171. if call.data.contract_id == *MONEY_CONTRACT_ID {
  172. println!("[scan_block] Found Money contract in call {i}");
  173. self.apply_tx_money_data(i, &tx.calls, &tx_hash).await?;
  174. continue
  175. }
  176. if call.data.contract_id == *DAO_CONTRACT_ID {
  177. println!("[scan_block] Found DAO contract in call {i}");
  178. self.apply_tx_dao_data(
  179. &call.data.data,
  180. TransactionHash::new(*blake3::hash(&serialize_async(tx).await).as_bytes()),
  181. i as u8,
  182. )
  183. .await?;
  184. continue
  185. }
  186. if call.data.contract_id == *DEPLOYOOOR_CONTRACT_ID {
  187. println!("[scan_block] Found DeployoOor contract in call {i}");
  188. // TODO: implement
  189. continue
  190. }
  191. // TODO: For now we skip non-native contract calls
  192. println!("[scan_block] Found non-native contract in call {i}, skipping.");
  193. }
  194. }
  195. // Write this block height into `last_scanned_block`
  196. let query =
  197. format!("UPDATE {} SET {} = ?1;", *MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_BLOCK);
  198. if let Err(e) = self.wallet.exec_sql(&query, rusqlite::params![block.header.height]) {
  199. return Err(Error::RusqliteError(format!(
  200. "[scan_block] Update last scanned block failed: {e:?}"
  201. )))
  202. }
  203. Ok(())
  204. }
  205. /// Scans the blockchain starting from the last scanned block, for relevant
  206. /// money transfer transactions. If reset flag is provided, Merkle tree state
  207. /// and coins are reset, and start scanning from beginning. Alternatively,
  208. /// it looks for a checkpoint in the wallet to reset and start scanning from.
  209. pub async fn scan_blocks(&self, reset: bool) -> WalletDbResult<()> {
  210. // Grab last scanned block height
  211. let mut height = self.last_scanned_block()?;
  212. // If last scanned block is genesis (0) or reset flag
  213. // has been provided we reset, otherwise continue with
  214. // the next block height
  215. if height == 0 || reset {
  216. self.reset_money_tree().await?;
  217. self.reset_money_smt()?;
  218. self.reset_money_coins()?;
  219. self.reset_dao_trees().await?;
  220. self.reset_daos().await?;
  221. self.reset_dao_proposals().await?;
  222. self.reset_dao_votes()?;
  223. self.update_all_tx_history_records_status("Rejected")?;
  224. height = 0;
  225. } else {
  226. height += 1;
  227. };
  228. loop {
  229. let req = JsonRequest::new("blockchain.last_known_block", JsonValue::Array(vec![]));
  230. let rep = match self.rpc_client.as_ref().unwrap().request(req).await {
  231. Ok(r) => r,
  232. Err(e) => {
  233. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  234. return Err(WalletDbError::GenericError)
  235. }
  236. };
  237. let last = *rep.get::<f64>().unwrap() as u32;
  238. println!("Requested to scan from block number: {height}");
  239. println!("Last known block number reported by darkfid: {last}");
  240. // Already scanned last known block
  241. if height > last {
  242. return Ok(())
  243. }
  244. while height <= last {
  245. println!("Requesting block {}... ", height);
  246. let block = match self.get_block_by_height(height).await {
  247. Ok(r) => r,
  248. Err(e) => {
  249. eprintln!("[scan_blocks] RPC client request failed: {e:?}");
  250. return Err(WalletDbError::GenericError)
  251. }
  252. };
  253. if let Err(e) = self.scan_block(&block).await {
  254. eprintln!("[scan_blocks] Scan block failed: {e:?}");
  255. return Err(WalletDbError::GenericError)
  256. };
  257. let txs_hashes = self.insert_tx_history_records(&block.txs).await?;
  258. self.update_tx_history_records_status(&txs_hashes, "Finalized")?;
  259. height += 1;
  260. }
  261. }
  262. }
  263. // Queries darkfid for a block with given height.
  264. async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
  265. let req = JsonRequest::new(
  266. "blockchain.get_block",
  267. JsonValue::Array(vec![JsonValue::String(height.to_string())]),
  268. );
  269. let params = self.rpc_client.as_ref().unwrap().request(req).await?;
  270. let param = params.get::<String>().unwrap();
  271. let bytes = base64::decode(param).unwrap();
  272. let block = deserialize_async(&bytes).await?;
  273. Ok(block)
  274. }
  275. /// Broadcast a given transaction to darkfid and forward onto the network.
  276. /// Returns the transaction ID upon success.
  277. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  278. println!("Broadcasting transaction...");
  279. let params =
  280. JsonValue::Array(vec![JsonValue::String(base64::encode(&serialize_async(tx).await))]);
  281. let req = JsonRequest::new("tx.broadcast", params);
  282. let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
  283. let txid = rep.get::<String>().unwrap().clone();
  284. // Store transactions history record
  285. if let Err(e) = self.insert_tx_history_record(tx).await {
  286. return Err(Error::RusqliteError(format!(
  287. "[broadcast_tx] Inserting transaction history record failed: {e:?}"
  288. )))
  289. }
  290. Ok(txid)
  291. }
  292. /// Queries darkfid for a tx with given hash.
  293. pub async fn get_tx(&self, tx_hash: &TransactionHash) -> Result<Option<Transaction>> {
  294. let tx_hash_str = tx_hash.to_string();
  295. let req = JsonRequest::new(
  296. "blockchain.get_tx",
  297. JsonValue::Array(vec![JsonValue::String(tx_hash_str)]),
  298. );
  299. match self.rpc_client.as_ref().unwrap().request(req).await {
  300. Ok(param) => {
  301. let tx_bytes = base64::decode(param.get::<String>().unwrap()).unwrap();
  302. let tx = deserialize_async(&tx_bytes).await?;
  303. Ok(Some(tx))
  304. }
  305. Err(_) => Ok(None),
  306. }
  307. }
  308. /// Simulate the transaction with the state machine.
  309. pub async fn simulate_tx(&self, tx: &Transaction) -> Result<bool> {
  310. let tx_str = base64::encode(&serialize_async(tx).await);
  311. let req =
  312. JsonRequest::new("tx.simulate", JsonValue::Array(vec![JsonValue::String(tx_str)]));
  313. let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
  314. let is_valid = *rep.get::<bool>().unwrap();
  315. Ok(is_valid)
  316. }
  317. /// Try to fetch zkas bincodes for the given `ContractId`.
  318. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  319. let params = JsonValue::Array(vec![JsonValue::String(format!("{contract_id}"))]);
  320. let req = JsonRequest::new("blockchain.lookup_zkas", params);
  321. let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
  322. let params = rep.get::<Vec<JsonValue>>().unwrap();
  323. let mut ret = Vec::with_capacity(params.len());
  324. for param in params {
  325. let zkas_ns = param[0].get::<String>().unwrap().clone();
  326. let zkas_bincode_bytes = base64::decode(param[1].get::<String>().unwrap()).unwrap();
  327. ret.push((zkas_ns, zkas_bincode_bytes));
  328. }
  329. Ok(ret)
  330. }
  331. /// Queries darkfid for given transaction's gas.
  332. pub async fn get_tx_gas(&self, tx: &Transaction, include_fee: bool) -> Result<u64> {
  333. let params = JsonValue::Array(vec![
  334. JsonValue::String(base64::encode(&serialize_async(tx).await)),
  335. JsonValue::Boolean(include_fee),
  336. ]);
  337. let req = JsonRequest::new("tx.calculate_gas", params);
  338. let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
  339. let gas = *rep.get::<f64>().unwrap() as u64;
  340. Ok(gas)
  341. }
  342. /// Queries darkfid for current best fork next height.
  343. pub async fn get_next_block_height(&self) -> Result<u32> {
  344. let req =
  345. JsonRequest::new("blockchain.best_fork_next_block_height", JsonValue::Array(vec![]));
  346. let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
  347. let next_height = *rep.get::<f64>().unwrap() as u32;
  348. Ok(next_height)
  349. }
  350. /// Queries darkfid for currently configured block target time.
  351. pub async fn get_block_target(&self) -> Result<u32> {
  352. let req = JsonRequest::new("blockchain.block_target", JsonValue::Array(vec![]));
  353. let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
  354. let next_height = *rep.get::<f64>().unwrap() as u32;
  355. Ok(next_height)
  356. }
  357. }