rpc_blockchain.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. eprintln!("Subscribing to receive notifications of incoming blocks");
  61. let subscriber = Subscriber::new();
  62. let subscription = subscriber.clone().subscribe().await;
  63. let rpc_client = RpcClient::new(endpoint).await?;
  64. let req = JsonRequest::new("blockchain.subscribe_blocks", json!([]));
  65. task::spawn(async move { rpc_client.subscribe(req, subscriber).await.unwrap() });
  66. eprintln!("Detached subscription to background");
  67. let e = loop {
  68. match subscription.receive().await {
  69. JsonResult::Notification(n) => {
  70. eprintln!("Got Block notification from darkfid subscription");
  71. if n.method != "blockchain.subscribe_blocks" {
  72. break anyhow!("Got foreign notification from darkfid: {}", n.method)
  73. }
  74. let Some(params) = n.params.as_array() else {
  75. break anyhow!("Received notification params are not an array")
  76. };
  77. if params.len() != 1 {
  78. break anyhow!("Notification parameters are not len 1")
  79. }
  80. let params = n.params.as_array().unwrap()[0].as_str().unwrap();
  81. let bytes = bs58::decode(params).into_vec()?;
  82. let block_data: BlockInfo = deserialize(&bytes)?;
  83. eprintln!("=======================================");
  84. eprintln!("Block header:\n{:#?}", block_data.header);
  85. eprintln!("=======================================");
  86. // TODO: FIXME: Disallow this if last_scanned_slot is not this-1 or something
  87. eprintln!("Deserialized successfully. Scanning block...");
  88. self.scan_block(&block_data).await?;
  89. }
  90. JsonResult::Error(e) => {
  91. // Some error happened in the transmission
  92. break anyhow!("Got error from JSON-RPC: {:?}", e)
  93. }
  94. x => {
  95. // And this is weird
  96. break anyhow!("Got unexpected data from JSON-RPC: {:?}", x)
  97. }
  98. }
  99. };
  100. Err(e)
  101. }
  102. /// `scan_block` will go over transactions in a block and fetch the ones dealing
  103. /// with the money contract. Then over all of them, try to see if any are related
  104. /// to us. If any are found, the metadata is extracted and placed into the wallet
  105. /// for future use.
  106. async fn scan_block(&self, block: &BlockInfo) -> Result<()> {
  107. eprintln!("Iterating over {} transactions", block.txs.len());
  108. let mut outputs: Vec<Output> = vec![];
  109. // TODO: FIXME: This shouldn't be hardcoded here obviously.
  110. let contract_id = ContractId::from(pallas::Base::from(u64::MAX - 420));
  111. for (i, tx) in block.txs.iter().enumerate() {
  112. for (j, call) in tx.calls.iter().enumerate() {
  113. if call.contract_id == contract_id && call.data[0] == MoneyFunction::Transfer as u8
  114. {
  115. eprintln!("Found Money::Transfer in call {} in tx {}", j, i);
  116. let params: MoneyTransferParams = deserialize(&call.data[1..])?;
  117. for output in params.outputs {
  118. outputs.push(output);
  119. }
  120. continue
  121. }
  122. if call.contract_id == contract_id && call.data[0] == MoneyFunction::OtcSwap as u8 {
  123. eprintln!("Found Money::OtcSwap in call {} in tx {}", j, i);
  124. let params: MoneyTransferParams = deserialize(&call.data[1..])?;
  125. for output in params.outputs {
  126. outputs.push(output);
  127. }
  128. continue
  129. }
  130. }
  131. }
  132. // Fetch our secret keys from the wallet
  133. eprintln!("Fetching secret keys from wallet");
  134. let secrets = self.wallet_secrets().await?;
  135. if secrets.is_empty() {
  136. eprintln!("Warning: No secrets found in wallet");
  137. }
  138. eprintln!("Fetching Merkle tree from wallet");
  139. let mut tree = self.wallet_tree().await?;
  140. let mut owncoins = vec![];
  141. // FIXME: We end up adding duplicate coins that could already be in the tree
  142. for output in outputs {
  143. let coin = output.coin;
  144. // Append the new coin to the Merkle tree. Every coin has to be added.
  145. tree.append(&MerkleNode::from(coin));
  146. // Attempt to decrypt the note
  147. let enc_note =
  148. EncryptedNote { ciphertext: output.ciphertext, ephem_public: output.ephem_public };
  149. for secret in &secrets {
  150. if let Ok(note) = enc_note.decrypt(secret) {
  151. eprintln!("Successfully decrypted a note");
  152. eprintln!("Witnessing coin in Merkle tree");
  153. let leaf_position = tree.witness().unwrap();
  154. let owncoin = OwnCoin {
  155. coin: Coin::from(coin),
  156. note: note.clone(),
  157. secret: *secret,
  158. nullifier: Nullifier::from(poseidon_hash([secret.inner(), note.serial])),
  159. leaf_position,
  160. };
  161. owncoins.push(owncoin);
  162. }
  163. }
  164. }
  165. eprintln!("Serializing the Merkle tree into the wallet");
  166. self.put_tree(&tree).await?;
  167. eprintln!("Merkle tree written successfully");
  168. // This is the SQL query we'll be executing to insert coins into the wallet
  169. let query = format!(
  170. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12);",
  171. MONEY_COINS_TABLE,
  172. MONEY_COINS_COL_COIN,
  173. MONEY_COINS_COL_IS_SPENT,
  174. MONEY_COINS_COL_SERIAL,
  175. MONEY_COINS_COL_VALUE,
  176. MONEY_COINS_COL_TOKEN_ID,
  177. MONEY_COINS_COL_COIN_BLIND,
  178. MONEY_COINS_COL_VALUE_BLIND,
  179. MONEY_COINS_COL_TOKEN_BLIND,
  180. MONEY_COINS_COL_SECRET,
  181. MONEY_COINS_COL_NULLIFIER,
  182. MONEY_COINS_COL_LEAF_POSITION,
  183. MONEY_COINS_COL_MEMO,
  184. );
  185. eprintln!("Found {} OwnCoin(s) in block", owncoins.len());
  186. for owncoin in owncoins {
  187. eprintln!("Owncoin: {:?}", owncoin.coin);
  188. let params = json!([
  189. query,
  190. QueryType::Blob as u8,
  191. serialize(&owncoin.coin),
  192. QueryType::Integer as u8,
  193. 0, // <-- is_spent
  194. QueryType::Blob as u8,
  195. serialize(&owncoin.note.serial),
  196. QueryType::Blob as u8,
  197. serialize(&owncoin.note.value),
  198. QueryType::Blob as u8,
  199. serialize(&owncoin.note.token_id),
  200. QueryType::Blob as u8,
  201. serialize(&owncoin.note.coin_blind),
  202. QueryType::Blob as u8,
  203. serialize(&owncoin.note.value_blind),
  204. QueryType::Blob as u8,
  205. serialize(&owncoin.note.token_blind),
  206. QueryType::Blob as u8,
  207. serialize(&owncoin.secret),
  208. QueryType::Blob as u8,
  209. serialize(&owncoin.nullifier),
  210. QueryType::Blob as u8,
  211. serialize(&owncoin.leaf_position),
  212. QueryType::Blob as u8,
  213. serialize(&owncoin.note.memo),
  214. ]);
  215. eprintln!("Executing JSON-RPC request to add OwnCoin to wallet");
  216. let req = JsonRequest::new("wallet.exec_sql", params);
  217. self.rpc_client.request(req).await?;
  218. eprintln!("Coin added successfully");
  219. }
  220. Ok(())
  221. }
  222. /// Try to fetch zkas bincodes for the given `ContractId`.
  223. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  224. eprintln!("Querying zkas bincode for {}", contract_id);
  225. let params = json!([format!("{}", contract_id)]);
  226. let req = JsonRequest::new("blockchain.lookup_zkas", params);
  227. let rep = self.rpc_client.request(req).await?;
  228. let ret = serde_json::from_value(rep)?;
  229. Ok(ret)
  230. }
  231. /// Broadcast a given transaction to darkfid and forward onto the network.
  232. /// Returns the transaction ID upon success
  233. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  234. eprintln!("Broadcasting transaction...");
  235. let params = json!([bs58::encode(&serialize(tx)).into_string()]);
  236. let req = JsonRequest::new("tx.broadcast", params);
  237. let rep = self.rpc_client.request(req).await?;
  238. let txid = serde_json::from_value(rep)?;
  239. Ok(txid)
  240. }
  241. /// Queries darkfid for a block with given slot
  242. async fn get_block_by_slot(&self, slot: u64) -> Result<Option<BlockInfo>> {
  243. let req = JsonRequest::new("blockchain.get_slot", json!([slot]));
  244. // This API is weird, we need some way of telling it's an empty slot and
  245. // not an error
  246. match self.rpc_client.request(req).await {
  247. Ok(v) => {
  248. let block_bytes: Vec<u8> = serde_json::from_value(v)?;
  249. let block = deserialize(&block_bytes)?;
  250. Ok(Some(block))
  251. }
  252. Err(_) => Ok(None),
  253. }
  254. }
  255. /// Scans the blockchain optionally starting from the given slot for relevant
  256. /// money transfer transactions. Alternatively it looks for a checkpoint in the
  257. /// wallet to start scanning from.
  258. pub async fn scan_blocks(&self, slot: Option<u64>) -> Result<()> {
  259. let mut sl = if let Some(sl) = slot { sl } else { self.wallet_last_scanned_slot().await? };
  260. let req = JsonRequest::new("blockchain.last_known_slot", json!([]));
  261. let rep = self.rpc_client.request(req).await?;
  262. let last: u64 = serde_json::from_value(rep)?;
  263. eprintln!("Requested to scan from slot number: {}", sl);
  264. eprintln!("Last known slot number reported by darkfid: {}", last);
  265. // We set this up to handle an interrupt
  266. let mut signals = Signals::new(&[SIGTERM, SIGINT, SIGQUIT])?;
  267. let handle = signals.handle();
  268. let (term_tx, _term_rx) = smol::channel::bounded::<()>(1);
  269. let term_tx_ = term_tx.clone();
  270. let signals_task = task::spawn(async move {
  271. while let Some(signal) = signals.next().await {
  272. match signal {
  273. SIGTERM | SIGINT | SIGQUIT => term_tx_.close(),
  274. _ => unreachable!(),
  275. };
  276. }
  277. });
  278. while !term_tx.is_closed() {
  279. if sl == last {
  280. term_tx.close();
  281. break
  282. }
  283. sl += 1;
  284. eprint!("Requesting slot {}... ", sl);
  285. if let Some(block) = self.get_block_by_slot(sl).await? {
  286. eprintln!("Found");
  287. self.scan_block(&block).await?;
  288. } else {
  289. eprintln!("Not found");
  290. }
  291. // Write down the slot number into back to the wallet
  292. // TODO: Why doesn't it work?
  293. let query = format!(
  294. "INSERT INTO {} ({}) VALUES (?1);",
  295. MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT
  296. );
  297. let params = json!([query, QueryType::Integer as u8, sl]);
  298. let req = JsonRequest::new("wallet.exec_sql", params);
  299. let _ = self.rpc_client.request(req).await?;
  300. }
  301. handle.close();
  302. signals_task.await;
  303. Ok(())
  304. }
  305. }