darkfid.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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::adapter::RpcAdapter;
  13. use drk::rpc::jsonserver;
  14. use drk::serial::{deserialize, Decodable, Encodable};
  15. use drk::service::{GatewayClient, GatewaySlabsSubscriber};
  16. use drk::state::{state_transition, ProgramState, StateUpdate};
  17. use drk::util::join_config_path;
  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. async fn start(executor: Arc<Executor<'_>>, config: Arc<&DarkfidConfig>) -> Result<()> {
  128. let connect_addr: SocketAddr = config.connect_url.parse()?;
  129. let sub_addr: SocketAddr = config.subscriber_url.parse()?;
  130. let database_path = config.database_path.clone();
  131. let database_path = join_config_path(&PathBuf::from(database_path))?;
  132. let rocks = Rocks::new(&database_path)?;
  133. let rocks2 = rocks.clone();
  134. let slabstore = RocksColumn::<columns::Slabs>::new(rocks2.clone());
  135. // Auto create trusted ceremony parameters if they don't exist
  136. if !Path::new("mint.params").exists() {
  137. let params = setup_mint_prover();
  138. save_params("mint.params", &params)?;
  139. }
  140. if !Path::new("spend.params").exists() {
  141. let params = setup_spend_prover();
  142. save_params("spend.params", &params)?;
  143. }
  144. // Load trusted setup parameters
  145. let (mint_params, mint_pvk) = load_params("mint.params")?;
  146. let (spend_params, spend_pvk) = load_params("spend.params")?;
  147. //let cashier_secret = jubjub::Fr::random(&mut OsRng);
  148. //let cashier_public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * cashier_secret;
  149. // wallet secret key
  150. let secret = jubjub::Fr::random(&mut OsRng);
  151. // wallet public key
  152. let _public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
  153. let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
  154. let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
  155. let wallet = Arc::new(WalletDb::new("wallet.db", config.password.clone())?);
  156. let ex = executor.clone();
  157. let mut state = State {
  158. tree: CommitmentTree::empty(),
  159. merkle_roots,
  160. nullifiers,
  161. mint_pvk,
  162. spend_pvk,
  163. wallet: wallet.clone(),
  164. };
  165. // create gateway client
  166. debug!(target: "Client", "Creating client");
  167. let mut client = GatewayClient::new(connect_addr, slabstore)?;
  168. debug!(target: "Gateway", "Start subscriber");
  169. // start subscribing
  170. let gateway_slabs_sub: GatewaySlabsSubscriber =
  171. client.start_subscriber(sub_addr, executor.clone()).await?;
  172. let (publish_tx_send, publish_tx_recv) = async_channel::unbounded::<TransferParams>();
  173. // start gateway client
  174. debug!(target: "fn::start client", "start() Client started");
  175. client.start().await?;
  176. executor
  177. .spawn(async move {
  178. loop {
  179. futures::select! {
  180. // TODO: using "?" instead of unwrap()
  181. slab = gateway_slabs_sub.recv().fuse() => {
  182. let slab = slab.unwrap();
  183. let tx = tx::Transaction::decode(&slab.get_payload()[..]).unwrap();
  184. let update = state_transition(&state, tx).unwrap();
  185. state.apply(update).await.unwrap();
  186. }
  187. transfer_params = publish_tx_recv.recv().fuse() => {
  188. let transfer_params = transfer_params.unwrap();
  189. let merkle_path = {
  190. let (_coin, _, _, witness) = &mut state.wallet.get_own_coins().unwrap()[0];
  191. let merkle_path = witness.path().unwrap();
  192. merkle_path
  193. };
  194. let address = bs58::decode(transfer_params.pub_key).into_vec().unwrap();
  195. let address: jubjub::SubgroupPoint = deserialize(&address).unwrap();
  196. // Make a spend tx
  197. // Construct a new tx spending the coin
  198. let builder = tx::TransactionBuilder {
  199. clear_inputs: vec![],
  200. inputs: vec![tx::TransactionBuilderInputInfo {
  201. merkle_path,
  202. secret: secret.clone(),
  203. note: state.wallet.get_own_coins().unwrap()[0].1.clone(),
  204. }],
  205. // We can add more outputs to this list.
  206. // The only constraint is that sum(value in) == sum(value out)
  207. outputs: vec![tx::TransactionBuilderOutputInfo {
  208. value: transfer_params.amount,
  209. asset_id: 1,
  210. public: address,
  211. }],
  212. };
  213. // Build the tx
  214. let mut tx_data = vec![];
  215. {
  216. let tx = builder.build(&mint_params, &spend_params);
  217. tx.encode(&mut tx_data).expect("encode tx");
  218. }
  219. let slab = Slab::new(tx_data);
  220. client.put_slab(slab).await.expect("put slab");
  221. }
  222. }
  223. }
  224. })
  225. .detach();
  226. let adapter = RpcAdapter::new(wallet.clone(), config.connect_url.clone(), publish_tx_send)?;
  227. // start the rpc server
  228. jsonserver::start(ex.clone(), config.clone(), adapter).await?;
  229. //subscribe_task.cancel().await;
  230. Ok(())
  231. }
  232. fn main() -> Result<()> {
  233. let options = Arc::new(DarkfidCli::load()?);
  234. let path = join_config_path(&PathBuf::from("darkfid.toml")).unwrap();
  235. let config: DarkfidConfig = if Path::new(&path).exists() {
  236. Config::<DarkfidConfig>::load(path)?
  237. } else {
  238. Config::<DarkfidConfig>::load_default(path)?
  239. };
  240. let config_ptr = Arc::new(&config);
  241. let ex = Arc::new(Executor::new());
  242. let (signal, shutdown) = async_channel::unbounded::<()>();
  243. {
  244. use simplelog::*;
  245. let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
  246. let debug_level = if options.verbose {
  247. LevelFilter::Debug
  248. } else {
  249. LevelFilter::Off
  250. };
  251. let log_path = config.log_path.clone();
  252. CombinedLogger::init(vec![
  253. TermLogger::new(debug_level, logger_config, TerminalMode::Mixed).unwrap(),
  254. WriteLogger::new(
  255. LevelFilter::Debug,
  256. Config::default(),
  257. std::fs::File::create(log_path).unwrap(),
  258. ),
  259. ])
  260. .unwrap();
  261. }
  262. let ex2 = ex.clone();
  263. let (_, result) = Parallel::new()
  264. // Run four executor threads.
  265. .each(0..3, |_| smol::future::block_on(ex.run(shutdown.recv())))
  266. // Run the main future on the current thread.
  267. .finish(|| {
  268. smol::future::block_on(async move {
  269. start(ex2, config_ptr).await?;
  270. drop(signal);
  271. Ok::<(), drk::Error>(())
  272. })
  273. });
  274. result
  275. }