rpc_blockchain.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 anyhow::{anyhow, Result};
  19. use async_std::{stream::StreamExt, task};
  20. use darkfi::{
  21. consensus::BlockInfo,
  22. rpc::{
  23. client::RpcClient,
  24. jsonrpc::{JsonRequest, JsonResult},
  25. },
  26. system::Subscriber,
  27. tx::Transaction,
  28. wallet::walletdb::QueryType,
  29. };
  30. use darkfi_money_contract::{
  31. client::{
  32. Coin, EncryptedNote, OwnCoin, MONEY_COINS_COL_COIN, MONEY_COINS_COL_COIN_BLIND,
  33. MONEY_COINS_COL_IS_SPENT, MONEY_COINS_COL_LEAF_POSITION, MONEY_COINS_COL_MEMO,
  34. MONEY_COINS_COL_NULLIFIER, MONEY_COINS_COL_SECRET, MONEY_COINS_COL_SERIAL,
  35. MONEY_COINS_COL_TOKEN_BLIND, MONEY_COINS_COL_TOKEN_ID, MONEY_COINS_COL_VALUE,
  36. MONEY_COINS_COL_VALUE_BLIND, MONEY_COINS_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT,
  37. MONEY_INFO_TABLE,
  38. },
  39. state::{MoneyTransferParams, Output},
  40. MoneyFunction,
  41. };
  42. use darkfi_sdk::{
  43. crypto::{contract_id::MONEY_CONTRACT_ID, poseidon_hash, ContractId, MerkleNode, Nullifier},
  44. incrementalmerkletree::Tree,
  45. };
  46. use darkfi_serial::{deserialize, serialize};
  47. use serde_json::json;
  48. use signal_hook::consts::{SIGINT, SIGQUIT, SIGTERM};
  49. use signal_hook_async_std::Signals;
  50. use url::Url;
  51. use super::Drk;
  52. use crate::cli_util::kaching;
  53. impl Drk {
  54. /// Subscribes to darkfid's JSON-RPC notification endpoint that serves
  55. /// new finalized blocks. Upon receiving them, all the transactions are
  56. /// scanned and we check if any of them call the money contract, and if
  57. /// the payments are intended for us. If so, we decrypt them and append
  58. /// the metadata to our wallet.
  59. pub async fn subscribe_blocks(&self, endpoint: Url) -> Result<()> {
  60. let req = JsonRequest::new("blockchain.last_known_slot", json!([]));
  61. let rep = self.rpc_client.request(req).await?;
  62. let last_known: u64 = serde_json::from_value(rep)?;
  63. let last_scanned = self.wallet_last_scanned_slot().await?;
  64. if last_known != last_scanned {
  65. eprintln!("Warning: Last scanned slot is not the last known slot.");
  66. eprintln!("You should first fully scan the blockchain, and then subscribe");
  67. return Err(anyhow!("Blockchain not fully scanned"))
  68. }
  69. eprintln!("Subscribing to receive notifications of incoming blocks");
  70. let subscriber = Subscriber::new();
  71. let subscription = subscriber.clone().subscribe().await;
  72. let rpc_client = RpcClient::new(endpoint).await?;
  73. let req = JsonRequest::new("blockchain.subscribe_blocks", json!([]));
  74. task::spawn(async move { rpc_client.subscribe(req, subscriber).await.unwrap() });
  75. eprintln!("Detached subscription to background");
  76. let e = loop {
  77. match subscription.receive().await {
  78. JsonResult::Notification(n) => {
  79. eprintln!("Got Block notification from darkfid subscription");
  80. if n.method != "blockchain.subscribe_blocks" {
  81. break anyhow!("Got foreign notification from darkfid: {}", n.method)
  82. }
  83. let Some(params) = n.params.as_array() else {
  84. break anyhow!("Received notification params are not an array")
  85. };
  86. if params.len() != 1 {
  87. break anyhow!("Notification parameters are not len 1")
  88. }
  89. let params = n.params.as_array().unwrap()[0].as_str().unwrap();
  90. let bytes = bs58::decode(params).into_vec()?;
  91. let block_data: BlockInfo = deserialize(&bytes)?;
  92. eprintln!("=======================================");
  93. eprintln!("Block header:\n{:#?}", block_data.header);
  94. eprintln!("=======================================");
  95. eprintln!("Deserialized successfully. Scanning block...");
  96. self.scan_block(&block_data).await?;
  97. }
  98. JsonResult::Error(e) => {
  99. // Some error happened in the transmission
  100. break anyhow!("Got error from JSON-RPC: {:?}", e)
  101. }
  102. x => {
  103. // And this is weird
  104. break anyhow!("Got unexpected data from JSON-RPC: {:?}", x)
  105. }
  106. }
  107. };
  108. Err(e)
  109. }
  110. /// `scan_block` will go over transactions in a block and fetch the ones dealing
  111. /// with the money contract. Then over all of them, try to see if any are related
  112. /// to us. If any are found, the metadata is extracted and placed into the wallet
  113. /// for future use.
  114. async fn scan_block(&self, block: &BlockInfo) -> Result<()> {
  115. eprintln!("Iterating over {} transactions", block.txs.len());
  116. let mut nullifiers: Vec<Nullifier> = vec![];
  117. let mut outputs: Vec<Output> = vec![];
  118. let contract_id = *MONEY_CONTRACT_ID;
  119. for (i, tx) in block.txs.iter().enumerate() {
  120. for (j, call) in tx.calls.iter().enumerate() {
  121. if call.contract_id == contract_id && call.data[0] == MoneyFunction::Transfer as u8
  122. {
  123. eprintln!("Found Money::Transfer in call {} in tx {}", j, i);
  124. let params: MoneyTransferParams = deserialize(&call.data[1..])?;
  125. for input in params.inputs {
  126. nullifiers.push(input.nullifier);
  127. }
  128. for output in params.outputs {
  129. outputs.push(output);
  130. }
  131. continue
  132. }
  133. if call.contract_id == contract_id && call.data[0] == MoneyFunction::OtcSwap as u8 {
  134. eprintln!("Found Money::OtcSwap in call {} in tx {}", j, i);
  135. let params: MoneyTransferParams = deserialize(&call.data[1..])?;
  136. for input in params.inputs {
  137. nullifiers.push(input.nullifier);
  138. }
  139. for output in params.outputs {
  140. outputs.push(output);
  141. }
  142. continue
  143. }
  144. }
  145. }
  146. // Fetch our secret keys from the wallet
  147. eprintln!("Fetching secret keys from wallet");
  148. let secrets = self.wallet_secrets().await?;
  149. if secrets.is_empty() {
  150. eprintln!("Warning: No secrets found in wallet");
  151. }
  152. eprintln!("Fetching Merkle tree from wallet");
  153. let mut tree = self.wallet_tree().await?;
  154. let mut owncoins = vec![];
  155. for output in outputs {
  156. let coin = output.coin;
  157. // Append the new coin to the Merkle tree. Every coin has to be added.
  158. tree.append(&MerkleNode::from(coin));
  159. // Attempt to decrypt the note
  160. let enc_note =
  161. EncryptedNote { ciphertext: output.ciphertext, ephem_public: output.ephem_public };
  162. for secret in &secrets {
  163. if let Ok(note) = enc_note.decrypt(secret) {
  164. eprintln!("Successfully decrypted a note");
  165. eprintln!("Witnessing coin in Merkle tree");
  166. let leaf_position = tree.witness().unwrap();
  167. let owncoin = OwnCoin {
  168. coin: Coin::from(coin),
  169. note: note.clone(),
  170. secret: *secret,
  171. nullifier: Nullifier::from(poseidon_hash([secret.inner(), note.serial])),
  172. leaf_position,
  173. };
  174. owncoins.push(owncoin);
  175. }
  176. }
  177. }
  178. eprintln!("Serializing the Merkle tree into the wallet");
  179. self.put_tree(&tree).await?;
  180. eprintln!("Merkle tree written successfully");
  181. if !nullifiers.is_empty() {
  182. eprintln!("Found {} spent coins, marking as spent", nullifiers.len());
  183. self.mark_spent_coins(nullifiers).await?;
  184. eprintln!("Spent coins marked successfully");
  185. }
  186. // This is the SQL query we'll be executing to insert coins into the wallet
  187. let query = format!(
  188. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12);",
  189. MONEY_COINS_TABLE,
  190. MONEY_COINS_COL_COIN,
  191. MONEY_COINS_COL_IS_SPENT,
  192. MONEY_COINS_COL_SERIAL,
  193. MONEY_COINS_COL_VALUE,
  194. MONEY_COINS_COL_TOKEN_ID,
  195. MONEY_COINS_COL_COIN_BLIND,
  196. MONEY_COINS_COL_VALUE_BLIND,
  197. MONEY_COINS_COL_TOKEN_BLIND,
  198. MONEY_COINS_COL_SECRET,
  199. MONEY_COINS_COL_NULLIFIER,
  200. MONEY_COINS_COL_LEAF_POSITION,
  201. MONEY_COINS_COL_MEMO,
  202. );
  203. eprintln!("Found {} OwnCoin(s) in block", owncoins.len());
  204. for owncoin in &owncoins {
  205. eprintln!("Owncoin: {:?}", owncoin.coin);
  206. let params = json!([
  207. query,
  208. QueryType::Blob as u8,
  209. serialize(&owncoin.coin),
  210. QueryType::Integer as u8,
  211. 0, // <-- is_spent
  212. QueryType::Blob as u8,
  213. serialize(&owncoin.note.serial),
  214. QueryType::Blob as u8,
  215. serialize(&owncoin.note.value),
  216. QueryType::Blob as u8,
  217. serialize(&owncoin.note.token_id),
  218. QueryType::Blob as u8,
  219. serialize(&owncoin.note.coin_blind),
  220. QueryType::Blob as u8,
  221. serialize(&owncoin.note.value_blind),
  222. QueryType::Blob as u8,
  223. serialize(&owncoin.note.token_blind),
  224. QueryType::Blob as u8,
  225. serialize(&owncoin.secret),
  226. QueryType::Blob as u8,
  227. serialize(&owncoin.nullifier),
  228. QueryType::Blob as u8,
  229. serialize(&owncoin.leaf_position),
  230. QueryType::Blob as u8,
  231. serialize(&owncoin.note.memo),
  232. ]);
  233. eprintln!("Executing JSON-RPC request to add OwnCoin to wallet");
  234. let req = JsonRequest::new("wallet.exec_sql", params);
  235. self.rpc_client.request(req).await?;
  236. eprintln!("Coin added successfully");
  237. }
  238. // Write this slot into `last_scanned_slot`
  239. let query =
  240. format!("UPDATE {} SET {} = ?1;", MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT);
  241. let params = json!([query, QueryType::Integer as u8, block.header.slot]);
  242. let req = JsonRequest::new("wallet.exec_sql", params);
  243. let _ = self.rpc_client.request(req).await?;
  244. if !owncoins.is_empty() {
  245. if let Err(_) = kaching().await {
  246. return Ok(())
  247. }
  248. }
  249. Ok(())
  250. }
  251. /// Try to fetch zkas bincodes for the given `ContractId`.
  252. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  253. eprintln!("Querying zkas bincode for {}", contract_id);
  254. let params = json!([format!("{}", contract_id)]);
  255. let req = JsonRequest::new("blockchain.lookup_zkas", params);
  256. let rep = self.rpc_client.request(req).await?;
  257. let ret = serde_json::from_value(rep)?;
  258. Ok(ret)
  259. }
  260. /// Broadcast a given transaction to darkfid and forward onto the network.
  261. /// Returns the transaction ID upon success
  262. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  263. eprintln!("Broadcasting transaction...");
  264. let params = json!([bs58::encode(&serialize(tx)).into_string()]);
  265. let req = JsonRequest::new("tx.broadcast", params);
  266. let rep = self.rpc_client.request(req).await?;
  267. let txid = serde_json::from_value(rep)?;
  268. Ok(txid)
  269. }
  270. /// Queries darkfid for a block with given slot
  271. async fn get_block_by_slot(&self, slot: u64) -> Result<Option<BlockInfo>> {
  272. let req = JsonRequest::new("blockchain.get_slot", json!([slot]));
  273. // This API is weird, we need some way of telling it's an empty slot and
  274. // not an error
  275. match self.rpc_client.request(req).await {
  276. Ok(v) => {
  277. let block_bytes: Vec<u8> = serde_json::from_value(v)?;
  278. let block = deserialize(&block_bytes)?;
  279. Ok(Some(block))
  280. }
  281. Err(_) => Ok(None),
  282. }
  283. }
  284. /// Scans the blockchain starting from the last scanned slot, for relevant
  285. /// money transfer transactions. If reset flag is provided, Merkle tree state
  286. /// and coins are reset, and start scanning from beginning. Alternatively,
  287. /// it looks for a checkpoint in the wallet to reset and start scanning from.
  288. pub async fn scan_blocks(&self, reset: bool) -> Result<()> {
  289. let mut sl = if reset {
  290. self.reset_tree().await?;
  291. 0
  292. } else {
  293. self.wallet_last_scanned_slot().await?
  294. };
  295. let req = JsonRequest::new("blockchain.last_known_slot", json!([]));
  296. let rep = self.rpc_client.request(req).await?;
  297. let last: u64 = serde_json::from_value(rep)?;
  298. eprintln!("Requested to scan from slot number: {}", sl);
  299. eprintln!("Last known slot number reported by darkfid: {}", last);
  300. // Already scanned last known slot
  301. if sl == last {
  302. return Ok(())
  303. }
  304. // We set this up to handle an interrupt
  305. let mut signals = Signals::new([SIGTERM, SIGINT, SIGQUIT])?;
  306. let handle = signals.handle();
  307. let (term_tx, _term_rx) = smol::channel::bounded::<()>(1);
  308. let term_tx_ = term_tx.clone();
  309. let signals_task = task::spawn(async move {
  310. while let Some(signal) = signals.next().await {
  311. match signal {
  312. SIGTERM | SIGINT | SIGQUIT => term_tx_.close(),
  313. _ => unreachable!(),
  314. };
  315. }
  316. });
  317. while !term_tx.is_closed() {
  318. sl += 1;
  319. if sl > last {
  320. term_tx.close();
  321. break
  322. }
  323. eprint!("Requesting slot {}... ", sl);
  324. if let Some(block) = self.get_block_by_slot(sl).await? {
  325. eprintln!("Found");
  326. self.scan_block(&block).await?;
  327. } else {
  328. eprintln!("Not found");
  329. // Write down the slot number into back to the wallet
  330. // This might be a bit intense, but we accept it for now.
  331. let query = format!(
  332. "UPDATE {} SET {} = ?1;",
  333. MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT
  334. );
  335. let params = json!([query, QueryType::Integer as u8, sl]);
  336. let req = JsonRequest::new("wallet.exec_sql", params);
  337. let _ = self.rpc_client.request(req).await?;
  338. }
  339. }
  340. handle.close();
  341. signals_task.await;
  342. Ok(())
  343. }
  344. }