darkfid.rs 12 KB

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