darkfid-old.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. use drk::blockchain::{rocks::columns, Rocks, RocksColumn, Slab};
  2. use drk::cli::TransferParams;
  3. use drk::cli::{Config, DarkfidCli, DarkfidConfig};
  4. use drk::crypto::{
  5. load_params,
  6. merkle::{CommitmentTree, IncrementalWitness},
  7. merkle_node::MerkleNode,
  8. note::{EncryptedNote, Note},
  9. nullifier::Nullifier,
  10. save_params, setup_mint_prover, setup_spend_prover,
  11. };
  12. use drk::rpc::adapters::user_adapter::UserAdapter;
  13. use drk::rpc::jsonserver;
  14. use drk::serial::{deserialize, Decodable};
  15. use drk::service::{CashierClient, GatewayClient, GatewaySlabsSubscriber};
  16. use drk::state::{state_transition, ProgramState, StateUpdate};
  17. use drk::util::{join_config_path, prepare_transaction};
  18. use drk::wallet::{WalletDb, WalletPtr};
  19. use drk::{tx, Result};
  20. use async_executor::Executor;
  21. use bellman::groth16;
  22. use bls12_381::Bls12;
  23. use easy_parallel::Parallel;
  24. use ff::Field;
  25. use log::*;
  26. use rand::rngs::OsRng;
  27. use rusqlite::Connection;
  28. use async_std::sync::Arc;
  29. use futures::FutureExt;
  30. use std::net::SocketAddr;
  31. use std::path::Path;
  32. use std::path::PathBuf;
  33. pub struct State {
  34. // The entire merkle tree state
  35. tree: CommitmentTree<MerkleNode>,
  36. // List of all previous and the current merkle roots
  37. // This is the hashed value of all the children.
  38. merkle_roots: RocksColumn<columns::MerkleRoots>,
  39. // Nullifiers prevent double spending
  40. nullifiers: RocksColumn<columns::Nullifiers>,
  41. // Mint verifying key used by ZK
  42. mint_pvk: groth16::PreparedVerifyingKey<Bls12>,
  43. // Spend verifying key used by ZK
  44. spend_pvk: groth16::PreparedVerifyingKey<Bls12>,
  45. // Public key of the cashier
  46. // List of all our secret keys
  47. wallet: WalletPtr,
  48. }
  49. impl ProgramState for State {
  50. fn is_valid_cashier_public_key(&self, _public: &jubjub::SubgroupPoint) -> bool {
  51. let conn = Connection::open(&self.wallet.path).expect("Failed to connect to database");
  52. let mut stmt = conn
  53. .prepare("SELECT key_public FROM cashier WHERE key_public IN (SELECT key_public)")
  54. .expect("Cannot generate statement.");
  55. stmt.exists([1i32]).expect("Failed to read database")
  56. // do actual validity check
  57. }
  58. fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
  59. self.merkle_roots
  60. .key_exist(*merkle_root)
  61. .expect("couldn't check if the merkle_root valid")
  62. }
  63. fn nullifier_exists(&self, nullifier: &Nullifier) -> bool {
  64. self.nullifiers
  65. .key_exist(nullifier.repr)
  66. .expect("couldn't check if nullifier exists")
  67. }
  68. // load from disk
  69. fn mint_pvk(&self) -> &groth16::PreparedVerifyingKey<Bls12> {
  70. &self.mint_pvk
  71. }
  72. fn spend_pvk(&self) -> &groth16::PreparedVerifyingKey<Bls12> {
  73. &self.spend_pvk
  74. }
  75. }
  76. impl State {
  77. async fn apply(&mut self, update: StateUpdate) -> Result<()> {
  78. // Extend our list of nullifiers with the ones from the update
  79. for nullifier in update.nullifiers {
  80. self.nullifiers.put(nullifier, vec![] as Vec<u8>)?;
  81. }
  82. // Update merkle tree and witnesses
  83. for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.into_iter()) {
  84. // Add the new coins to the merkle tree
  85. let node = MerkleNode::from_coin(&coin);
  86. self.tree.append(node).expect("Append to merkle tree");
  87. // Keep track of all merkle roots that have existed
  88. self.merkle_roots.put(self.tree.root(), vec![] as Vec<u8>)?;
  89. // Also update all the coin witnesses
  90. for witness in self.wallet.witnesses.lock().await.iter_mut() {
  91. witness.append(node).expect("append to witness");
  92. }
  93. if let Some((note, secret)) = self.try_decrypt_note(enc_note).await {
  94. // We need to keep track of the witness for this coin.
  95. // This allows us to prove inclusion of the coin in the merkle tree with ZK.
  96. // Just as we update the merkle tree with every new coin, so we do the same with
  97. // the witness.
  98. // Derive the current witness from the current tree.
  99. // This is done right after we add our coin to the tree (but before any other
  100. // coins are added)
  101. // Make a new witness for this coin
  102. let witness = IncrementalWitness::from_tree(&self.tree);
  103. self.wallet
  104. .put_own_coins(coin.clone(), note.clone(), witness.clone(), secret)?;
  105. }
  106. }
  107. Ok(())
  108. }
  109. async fn try_decrypt_note(&self, ciphertext: EncryptedNote) -> Option<(Note, jubjub::Fr)> {
  110. let secret = self.wallet.get_private().ok()?;
  111. match ciphertext.decrypt(&secret) {
  112. Ok(note) => {
  113. // ... and return the decrypted note for this coin.
  114. return Some((note, secret.clone()));
  115. }
  116. Err(_) => {}
  117. }
  118. // We weren't able to decrypt the note with our key.
  119. None
  120. }
  121. }
  122. //pub async fn subscribe(
  123. // gateway_slabs_sub: GatewaySlabsSubscriber,
  124. // mut state: State,
  125. //) -> Result<()> {
  126. //}
  127. pub async fn futures_broker(
  128. client: &mut GatewayClient,
  129. cashier_client: &mut CashierClient,
  130. state: &mut State,
  131. secret: jubjub::Fr,
  132. mint_params: bellman::groth16::Parameters<Bls12>,
  133. spend_params: bellman::groth16::Parameters<Bls12>,
  134. gateway_slabs_sub: async_channel::Receiver<Slab>,
  135. deposit_req: async_channel::Receiver<jubjub::SubgroupPoint>,
  136. deposit_rep: async_channel::Sender<Option<bitcoin::util::address::Address>>,
  137. withdraw_req: async_channel::Receiver<String>,
  138. withdraw_rep: async_channel::Sender<Option<jubjub::SubgroupPoint>>,
  139. publish_tx_recv: async_channel::Receiver<TransferParams>,
  140. ) -> Result<()> {
  141. loop {
  142. futures::select! {
  143. slab = gateway_slabs_sub.recv().fuse() => {
  144. let slab = slab?;
  145. let tx = tx::Transaction::decode(&slab.get_payload()[..])?;
  146. let update = state_transition(state, tx)?;
  147. state.apply(update).await?;
  148. }
  149. deposit_addr = deposit_req.recv().fuse() => {
  150. let btc_public = cashier_client.get_address(deposit_addr?).await?;
  151. deposit_rep.send(btc_public).await?;
  152. }
  153. withdraw_addr = withdraw_req.recv().fuse() => {
  154. let drk_public = cashier_client.withdraw(withdraw_addr?).await?;
  155. withdraw_rep.send(drk_public).await?;
  156. }
  157. transfer_params = publish_tx_recv.recv().fuse() => {
  158. let transfer_params = transfer_params?;
  159. let address = bs58::decode(transfer_params.pub_key).into_vec()?;
  160. let address: jubjub::SubgroupPoint = deserialize(&address)?;
  161. let own_coins = state.wallet.get_own_coins()?;
  162. let slab = prepare_transaction(
  163. state,
  164. secret.clone(),
  165. mint_params.clone(),
  166. spend_params.clone(),
  167. address,
  168. transfer_params.amount,
  169. own_coins
  170. )?;
  171. client.put_slab(slab).await.expect("put slab");
  172. }
  173. }
  174. }
  175. }
  176. async fn start(executor: Arc<Executor<'_>>, config: Arc<DarkfidConfig>) -> Result<()> {
  177. let connect_addr: SocketAddr = config.connect_url.parse()?;
  178. let sub_addr: SocketAddr = config.subscriber_url.parse()?;
  179. let cashier_addr: SocketAddr = config.cashier_url.parse()?;
  180. let database_path = config.database_path.clone();
  181. let walletdb_path = config.walletdb_path.clone();
  182. let database_path = join_config_path(&PathBuf::from(database_path))?;
  183. let walletdb_path = join_config_path(&PathBuf::from(walletdb_path))?;
  184. let rocks = Rocks::new(&database_path)?;
  185. let rocks2 = rocks.clone();
  186. let slabstore = RocksColumn::<columns::Slabs>::new(rocks2.clone());
  187. // Auto create trusted ceremony parameters if they don't exist
  188. if !Path::new("mint.params").exists() {
  189. let params = setup_mint_prover();
  190. save_params("mint.params", &params)?;
  191. }
  192. if !Path::new("spend.params").exists() {
  193. let params = setup_spend_prover();
  194. save_params("spend.params", &params)?;
  195. }
  196. // Load trusted setup parameters
  197. let (mint_params, mint_pvk) = load_params("mint.params")?;
  198. let (spend_params, spend_pvk) = load_params("spend.params")?;
  199. //let cashier_secret = jubjub::Fr::random(&mut OsRng);
  200. //let cashier_public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * cashier_secret;
  201. // wallet secret key
  202. let secret = jubjub::Fr::random(&mut OsRng);
  203. // wallet public key
  204. let _public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  205. let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
  206. let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
  207. let wallet = Arc::new(WalletDb::new(&walletdb_path, config.password.clone())?);
  208. let ex = executor.clone();
  209. let mut state = State {
  210. tree: CommitmentTree::empty(),
  211. merkle_roots,
  212. nullifiers,
  213. mint_pvk,
  214. spend_pvk,
  215. wallet: wallet.clone(),
  216. };
  217. // create gateway client
  218. debug!(target: "Client", "Creating client");
  219. let mut client = GatewayClient::new(connect_addr, sub_addr, slabstore)?;
  220. // create cashier client
  221. debug!(target: "Cashier Client", "Creating cashier client");
  222. let mut cashier_client = CashierClient::new(cashier_addr)?;
  223. debug!(target: "Gateway", "Start subscriber");
  224. // start subscribing
  225. let gateway_slabs_sub: GatewaySlabsSubscriber =
  226. client.start_subscriber(executor.clone()).await?;
  227. // channels to request transfer from adapter
  228. let (publish_tx_send, publish_tx_recv) = async_channel::unbounded::<TransferParams>();
  229. // channels to request deposit from adapter, send DRK key and receive BTC key
  230. let (deposit_req_send, deposit_req_recv) = async_channel::unbounded::<jubjub::SubgroupPoint>();
  231. let (deposit_rep_send, deposit_rep_recv) =
  232. async_channel::unbounded::<Option<bitcoin::util::address::Address>>();
  233. // channel to request withdraw from adapter, send BTC key and receive DRK key
  234. let (withdraw_req_send, withdraw_req_recv) = async_channel::unbounded::<String>();
  235. let (withdraw_rep_send, withdraw_rep_recv) =
  236. async_channel::unbounded::<Option<jubjub::SubgroupPoint>>();
  237. // start gateway client
  238. debug!(target: "fn::start client", "start() Client started");
  239. client.start().await?;
  240. cashier_client.start().await?;
  241. let futures_broker_task = executor.spawn(async move {
  242. futures_broker(
  243. &mut client,
  244. &mut cashier_client,
  245. &mut state,
  246. secret.clone(),
  247. mint_params.clone(),
  248. spend_params.clone(),
  249. gateway_slabs_sub.clone(),
  250. deposit_req_recv.clone(),
  251. deposit_rep_send.clone(),
  252. withdraw_req_recv.clone(),
  253. withdraw_rep_send.clone(),
  254. publish_tx_recv.clone(),
  255. )
  256. .await?;
  257. Ok::<(), drk::Error>(())
  258. });
  259. let adapter = Arc::new(UserAdapter::new(
  260. wallet.clone(),
  261. publish_tx_send,
  262. (deposit_req_send, deposit_rep_recv),
  263. (withdraw_req_send, withdraw_rep_recv),
  264. )?);
  265. let rpc_url: std::net::SocketAddr = config.rpc_url.parse()?;
  266. // start the rpc server
  267. let io = Arc::new(adapter.handle_input()?);
  268. jsonserver::start(ex.clone(), rpc_url, io).await?;
  269. futures_broker_task.cancel().await;
  270. Ok(())
  271. }
  272. fn main() -> Result<()> {
  273. let options = Arc::new(DarkfidCli::load()?);
  274. let config_path: PathBuf;
  275. match options.config.as_ref() {
  276. Some(path) => {
  277. config_path = path.to_owned();
  278. }
  279. None => {
  280. config_path = join_config_path(&PathBuf::from("darkfid.toml"))?;
  281. }
  282. }
  283. let config: DarkfidConfig = if Path::new(&config_path).exists() {
  284. Config::<DarkfidConfig>::load(config_path)?
  285. } else {
  286. Config::<DarkfidConfig>::load_default(config_path)?
  287. };
  288. let config = Arc::new(config);
  289. let ex = Arc::new(Executor::new());
  290. let (signal, shutdown) = async_channel::unbounded::<()>();
  291. {
  292. use simplelog::*;
  293. let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
  294. let debug_level = if options.verbose {
  295. LevelFilter::Debug
  296. } else {
  297. LevelFilter::Off
  298. };
  299. let log_path = config.log_path.clone();
  300. CombinedLogger::init(vec![
  301. TermLogger::new(debug_level, logger_config, TerminalMode::Mixed).unwrap(),
  302. WriteLogger::new(
  303. LevelFilter::Debug,
  304. Config::default(),
  305. std::fs::File::create(log_path).unwrap(),
  306. ),
  307. ])
  308. .unwrap();
  309. }
  310. let ex2 = ex.clone();
  311. let (_, result) = Parallel::new()
  312. // Run four executor threads.
  313. .each(0..3, |_| smol::future::block_on(ex.run(shutdown.recv())))
  314. // Run the main future on the current thread.
  315. .finish(|| {
  316. smol::future::block_on(async move {
  317. start(ex2, config).await?;
  318. drop(signal);
  319. Ok::<(), drk::Error>(())
  320. })
  321. });
  322. result
  323. }