rpc_blockchain.rs 16 KB

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