rpc_blockchain.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. let mf = MoneyFunction::Transfer as u8;
  110. // TODO: FIXME: This shouldn't be hardcoded here obviously.
  111. let contract_id = ContractId::from(pallas::Base::from(u64::MAX - 420));
  112. for (i, tx) in block.txs.iter().enumerate() {
  113. for (j, call) in tx.calls.iter().enumerate() {
  114. if call.contract_id == contract_id && call.data[0] == mf {
  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. }
  121. }
  122. }
  123. // Fetch our secret keys from the wallet
  124. eprintln!("Fetching secret keys from wallet");
  125. let secrets = self.wallet_secrets().await?;
  126. if secrets.is_empty() {
  127. eprintln!("Warning: No secrets found in wallet");
  128. }
  129. eprintln!("Fetching Merkle tree from wallet");
  130. let mut tree = self.wallet_tree().await?;
  131. let mut owncoins = vec![];
  132. for output in outputs {
  133. // Append the new coin to the Merkle tree. Every coin has to be added.
  134. let coin = output.coin;
  135. tree.append(&MerkleNode::from(coin));
  136. // Attempt to decrypt the note
  137. let enc_note =
  138. EncryptedNote { ciphertext: output.ciphertext, ephem_public: output.ephem_public };
  139. for secret in &secrets {
  140. if let Ok(note) = enc_note.decrypt(secret) {
  141. eprintln!("Successfully decrypted a note");
  142. eprintln!("Witnessing coin in Merkle tree");
  143. let leaf_position = tree.witness().unwrap();
  144. let owncoin = OwnCoin {
  145. coin: Coin::from(coin),
  146. note: note.clone(),
  147. secret: *secret,
  148. nullifier: Nullifier::from(poseidon_hash([secret.inner(), note.serial])),
  149. leaf_position,
  150. };
  151. owncoins.push(owncoin);
  152. }
  153. }
  154. }
  155. eprintln!("Serializing the Merkle tree into the wallet");
  156. self.put_tree(&tree).await?;
  157. eprintln!("Merkle tree written successfully");
  158. // This is the SQL query we'll be executing to insert coins into the wallet
  159. let query = format!(
  160. "INSERT INTO {} ({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12);",
  161. MONEY_COINS_TABLE,
  162. MONEY_COINS_COL_COIN,
  163. MONEY_COINS_COL_IS_SPENT,
  164. MONEY_COINS_COL_SERIAL,
  165. MONEY_COINS_COL_VALUE,
  166. MONEY_COINS_COL_TOKEN_ID,
  167. MONEY_COINS_COL_COIN_BLIND,
  168. MONEY_COINS_COL_VALUE_BLIND,
  169. MONEY_COINS_COL_TOKEN_BLIND,
  170. MONEY_COINS_COL_SECRET,
  171. MONEY_COINS_COL_NULLIFIER,
  172. MONEY_COINS_COL_LEAF_POSITION,
  173. MONEY_COINS_COL_MEMO,
  174. );
  175. eprintln!("Found {} OwnCoin(s) in block", owncoins.len());
  176. for owncoin in owncoins {
  177. let params = json!([
  178. query,
  179. QueryType::Blob as u8,
  180. serialize(&owncoin.coin),
  181. QueryType::Integer as u8,
  182. 0, // <-- is_spent
  183. QueryType::Blob as u8,
  184. serialize(&owncoin.note.serial),
  185. QueryType::Blob as u8,
  186. serialize(&owncoin.note.value),
  187. QueryType::Blob as u8,
  188. serialize(&owncoin.note.token_id),
  189. QueryType::Blob as u8,
  190. serialize(&owncoin.note.coin_blind),
  191. QueryType::Blob as u8,
  192. serialize(&owncoin.note.value_blind),
  193. QueryType::Blob as u8,
  194. serialize(&owncoin.note.token_blind),
  195. QueryType::Blob as u8,
  196. serialize(&owncoin.secret),
  197. QueryType::Blob as u8,
  198. serialize(&owncoin.nullifier),
  199. QueryType::Blob as u8,
  200. serialize(&owncoin.leaf_position),
  201. QueryType::Blob as u8,
  202. serialize(&owncoin.note.memo),
  203. ]);
  204. eprintln!("Executing JSON-RPC request to add OwnCoin to wallet");
  205. let req = JsonRequest::new("wallet.exec_sql", params);
  206. self.rpc_client.request(req).await?;
  207. eprintln!("Coin added successfully");
  208. }
  209. Ok(())
  210. }
  211. /// Try to fetch zkas bincodes for the given `ContractId`.
  212. pub async fn lookup_zkas(&self, contract_id: &ContractId) -> Result<Vec<(String, Vec<u8>)>> {
  213. eprintln!("Querying zkas bincode for {}", contract_id);
  214. let params = json!([format!("{}", contract_id)]);
  215. let req = JsonRequest::new("blockchain.lookup_zkas", params);
  216. let rep = self.rpc_client.request(req).await?;
  217. let ret = serde_json::from_value(rep)?;
  218. Ok(ret)
  219. }
  220. /// Broadcast a given transaction to darkfid and forward onto the network.
  221. /// Returns the transaction ID upon success
  222. pub async fn broadcast_tx(&self, tx: &Transaction) -> Result<String> {
  223. eprintln!("Broadcasting transaction...");
  224. let params = json!([bs58::encode(&serialize(tx)).into_string()]);
  225. let req = JsonRequest::new("tx.broadcast", params);
  226. let rep = self.rpc_client.request(req).await?;
  227. let txid = serde_json::from_value(rep)?;
  228. Ok(txid)
  229. }
  230. /// Queries darkfid for a block with given slot
  231. async fn get_block_by_slot(&self, slot: u64) -> Result<Option<BlockInfo>> {
  232. let req = JsonRequest::new("blockchain.get_slot", json!([slot]));
  233. // This API is weird, we need some way of telling it's an empty slot and
  234. // not an error
  235. match self.rpc_client.request(req).await {
  236. Ok(v) => {
  237. let block_bytes: Vec<u8> = serde_json::from_value(v)?;
  238. let block = deserialize(&block_bytes)?;
  239. Ok(Some(block))
  240. }
  241. Err(_) => Ok(None),
  242. }
  243. }
  244. /// Scans the blockchain optionally starting from the given slot for relevant
  245. /// money transfer transactions. Alternatively it looks for a checkpoint in the
  246. /// wallet to start scanning from.
  247. pub async fn scan_blocks(&self, slot: Option<u64>) -> Result<()> {
  248. let mut sl = if let Some(sl) = slot { sl } else { self.wallet_last_scanned_slot().await? };
  249. let req = JsonRequest::new("blockchain.last_known_slot", json!([]));
  250. let rep = self.rpc_client.request(req).await?;
  251. let last: u64 = serde_json::from_value(rep)?;
  252. eprintln!("Requested to scan from slot number: {}", sl);
  253. eprintln!("Last known slot number reported by darkfid: {}", last);
  254. // We set this up to handle an interrupt
  255. let mut signals = Signals::new(&[SIGTERM, SIGINT, SIGQUIT])?;
  256. let handle = signals.handle();
  257. let (term_tx, _term_rx) = smol::channel::bounded::<()>(1);
  258. let term_tx_ = term_tx.clone();
  259. let signals_task = task::spawn(async move {
  260. while let Some(signal) = signals.next().await {
  261. match signal {
  262. SIGTERM | SIGINT | SIGQUIT => term_tx_.close(),
  263. _ => unreachable!(),
  264. };
  265. }
  266. });
  267. while !term_tx.is_closed() {
  268. if sl == last {
  269. term_tx.close();
  270. break
  271. }
  272. sl += 1;
  273. eprint!("Requesting slot {}... ", sl);
  274. if let Some(block) = self.get_block_by_slot(sl).await? {
  275. eprintln!("Found");
  276. self.scan_block(&block).await?;
  277. } else {
  278. eprintln!("Not found");
  279. }
  280. // Write down the slot number into back to the wallet
  281. // TODO: Why doesn't it work?
  282. let query = format!(
  283. "INSERT INTO {} ({}) VALUES (?1);",
  284. MONEY_INFO_TABLE, MONEY_INFO_COL_LAST_SCANNED_SLOT
  285. );
  286. let params = json!([query, QueryType::Integer as u8, sl]);
  287. let req = JsonRequest::new("wallet.exec_sql", params);
  288. let _ = self.rpc_client.request(req).await?;
  289. }
  290. handle.close();
  291. signals_task.await;
  292. Ok(())
  293. }
  294. }