Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.51 KB | None | 0 0
  1. fn cli() -> Result<(), String> {
  2. let matches = App::new("zeroc")
  3. .setting(AppSettings::SubcommandRequiredElseHelp)
  4. .version("0.1.0")
  5. .author("Osuke Sudo")
  6. .about("Zerochain: Privacy-protecting blockchain on top of Substrate.")
  7. .subcommand(SubCommand::with_name("setup")
  8. .about("Performs a trusted setup for a given constraint system")
  9. .arg(Arg::with_name("proving-key-path")
  10. .short("p")
  11. .long("proving-key-path")
  12. .help("Path of the generated proving key file")
  13. .value_name("FILE")
  14. .takes_value(true)
  15. .required(false)
  16. .default_value(PROVING_KEY_PATH)
  17. )
  18. .arg(Arg::with_name("verification-key-path")
  19. .short("v")
  20. .long("verification-key-path")
  21. .help("Path of the generated verification key file")
  22. .value_name("FILE")
  23. .takes_value(true)
  24. .required(false)
  25. .default_value(VERIFICATION_KEY_PATH)
  26. )
  27. )
  28. .subcommand(SubCommand::with_name("wallet-test")
  29. .about("Initialize key components")
  30. )
  31. .subcommand(SubCommand::with_name("wallet-init")
  32. .about("Initialize your wallet")
  33. )
  34. .subcommand(SubCommand::with_name("inspect")
  35. .about("Gets a encryption key and a SS58 address from the provided Secret URI")
  36. .args(Arg::with_name("uri")
  37. .short("u")
  38. .long("uri")
  39. .help("A Key URI to be inspected like a secret seed, SS58 or public URI.")
  40. .required(true)
  41. )
  42. )
  43. .subcommand(SubCommand::with_name("print-tx")
  44. .about("Show transaction components for sending it from a browser")
  45. .arg(Arg::with_name("proving-key-path")
  46. .short("p")
  47. .long("proving-key-path")
  48. .help("Path of the proving key file")
  49. .value_name("FILE")
  50. .takes_value(true)
  51. .required(false)
  52. .default_value(PROVING_KEY_PATH)
  53. )
  54. .arg(Arg::with_name("verification-key-path")
  55. .short("v")
  56. .long("verification-key-path")
  57. .help("Path of the generated verification key file")
  58. .value_name("FILE")
  59. .takes_value(true)
  60. .required(false)
  61. .default_value(VERIFICATION_KEY_PATH)
  62. )
  63. .arg(Arg::with_name("amount")
  64. .short("a")
  65. .long("amount")
  66. .help("The coin amount for the confidential transfer. (default: 10)")
  67. .takes_value(true)
  68. .required(false)
  69. .default_value(DEFAULT_AMOUNT)
  70. )
  71. .arg(Arg::with_name("balance")
  72. .short("b")
  73. .long("balance")
  74. .help("The coin balance for the confidential transfer.")
  75. .takes_value(true)
  76. .required(false)
  77. .default_value(DEFAULT_BALANCE)
  78. )
  79. .arg(Arg::with_name("sender-privatekey")
  80. .short("s")
  81. .long("sender-privatekey")
  82. .help("Sender's private key. (default: Alice)")
  83. .takes_value(true)
  84. .required(false)
  85. .default_value(ALICESEED)
  86. )
  87. .arg(Arg::with_name("recipient-privatekey")
  88. .short("r")
  89. .long("recipient-privatekey")
  90. .help("Recipient's private key. (default: Bob)")
  91. .takes_value(true)
  92. .required(false)
  93. .default_value(BOBSEED)
  94. )
  95. .arg(Arg::with_name("encrypted-balance")
  96. .short("e")
  97. .long("encrypted-balance")
  98. .help("Encrypted balance by sender stored in on-chain")
  99. .takes_value(true)
  100. .required(false)
  101. .default_value(DEFAULT_ENCRYPTED_BALANCE)
  102. )
  103. )
  104. .subcommand(SubCommand::with_name("send")
  105. .about("Submit extrinsic to the substrate nodes")
  106. .arg(Arg::with_name("amount")
  107. .short("a")
  108. .long("amount")
  109. .help("The coin amount for the confidential transfer. (default: 10)")
  110. .takes_value(true)
  111. .required(false)
  112. .default_value(DEFAULT_AMOUNT)
  113. )
  114. .arg(Arg::with_name("sender-seed")
  115. .short("s")
  116. .long("sender-seed")
  117. .help("Sender's seed. (default: Alice)")
  118. .takes_value(true)
  119. .required(false)
  120. .default_value(ALICESEED)
  121. )
  122. .arg(Arg::with_name("recipient-encryption-key")
  123. .short("to")
  124. .long("recipient-encryption-key")
  125. .help("Recipient's encryption key. (default: Bob)")
  126. .takes_value(true)
  127. .required(false)
  128. .default_value(BOBACCOUNTID)
  129. )
  130. // .arg(Arg::with_name("fee")
  131. // .short("f")
  132. // .long("fee")
  133. // .help("The fee for the confidential transfer. (default: 1)")
  134. // .takes_value(true)
  135. // .required(false)
  136. // .default_value(DEFAULT_FEE)
  137. // )
  138. .arg(Arg::with_name("url")
  139. .short("u")
  140. .long("url")
  141. .help("Endpoint to connect zerochain nodes")
  142. .takes_value(true)
  143. .required(false)
  144. )
  145. )
  146. .subcommand(SubCommand::with_name("balance")
  147. .about("Get current balance stored in ConfTransfer module")
  148. .arg(Arg::with_name("decryption-key")
  149. .short("d")
  150. .long("decryption-key")
  151. .help("Your decription key")
  152. .takes_value(true)
  153. .required(true)
  154. .default_value(ALICEDECRYPTIONKEY)
  155. )
  156. )
  157. .get_matches();
  158.  
  159. match matches.subcommand() {
  160. ("setup", Some(sub_matches)) => {
  161. println!("Performing setup...");
  162.  
  163. let pk_path = Path::new(sub_matches.value_of("proving-key-path").unwrap());
  164. let vk_path = Path::new(sub_matches.value_of("verification-key-path").unwrap());
  165.  
  166. let pk_file = File::create(&pk_path)
  167. .map_err(|why| format!("couldn't create {}: {}", pk_path.display(), why))?;
  168. let vk_file = File::create(&vk_path)
  169. .map_err(|why| format!("couldn't create {}: {}", vk_path.display(), why))?;
  170.  
  171. let mut bw_pk = BufWriter::new(pk_file);
  172. let mut bw_vk = BufWriter::new(vk_file);
  173.  
  174. let (proving_key, prepared_vk) = setup();
  175. let mut v_pk = vec![];
  176. let mut v_vk = vec![];
  177.  
  178. proving_key.write(&mut &mut v_pk).unwrap();
  179. prepared_vk.write(&mut &mut v_vk).unwrap();
  180.  
  181. bw_pk.write(&v_pk[..])
  182. .map_err(|_| "Unable to write proving key data to file.".to_string())?;
  183.  
  184. bw_vk.write(&v_vk[..])
  185. .map_err(|_| "Unable to write verification key data to file.".to_string())?;
  186.  
  187. bw_pk.flush()
  188. .map_err(|_| "Unable to flush proving key buffer.".to_string())?;
  189.  
  190. bw_vk.flush()
  191. .map_err(|_| "Unable to flush verification key buffer.".to_string())?;
  192.  
  193. println!("Success! Output >> 'proving.params' and 'verification.params'");
  194. },
  195. ("wallet-init", Some(_)) => {
  196. // create a new randomly generated mnemonic phrase
  197. let mnemonic = Mnemonic::new(MnemonicType::Words12, Language::English);
  198. PrintKeys::print_from_phrase(mnemonic.phrase(), None);
  199. },
  200. ("wallet-test", Some(_)) => {
  201. println!("Initialize key components...");
  202. println!("Accounts of alice and bob are fixed");
  203.  
  204. let alice_seed = seed_to_array(ALICESEED);
  205. let bob_seed = seed_to_array(BOBSEED);
  206.  
  207. let print_keys_alice = PrintKeys::generate_from_seed(alice_seed);
  208. let print_keys_bob = PrintKeys::generate_from_seed(bob_seed);
  209. let print_keys_charlie = PrintKeys::generate();
  210.  
  211. println!(
  212. "
  213. \nSeed
  214. Alice: 0x{}
  215. Bob: 0x{}
  216. Charlie: 0x{}
  217. \nDecryption Key
  218. Alice: 0x{}
  219. Bob: 0x{}
  220. Charlie: 0x{}
  221. \nEncryption Key
  222. Alice: 0x{}
  223. Bob: 0x{}
  224. Charlie: 0x{}
  225. ",
  226. hex::encode(&alice_seed[..]),
  227. hex::encode(&print_keys_bob.seed[..]),
  228. hex::encode(&print_keys_charlie.seed[..]),
  229. hex::encode(&print_keys_alice.decryption_key[..]),
  230. hex::encode(&print_keys_bob.decryption_key[..]),
  231. hex::encode(&print_keys_charlie.decryption_key[..]),
  232. hex::encode(&print_keys_alice.encryption_key[..]),
  233. hex::encode(&print_keys_bob.encryption_key[..]),
  234. hex::encode(&print_keys_charlie.encryption_key[..]),
  235. );
  236. },
  237. ("inspect", Some(sub_matches)) => {
  238. let uri = sub_matches.value_of("uri")
  239. .expect("URI parameter is required; qed");
  240.  
  241.  
  242. },
  243. ("send", Some(sub_matches)) => {
  244. println!("Preparing paramters...");
  245.  
  246. let url = match sub_matches.value_of("url") {
  247. Some(u) => Url::Custom(u.to_string()),
  248. None => Url::Local,
  249. };
  250. let api = Api::init(url);
  251.  
  252. let rng = &mut OsRng::new().expect("should be able to construct RNG");
  253. // let alpha = fs::Fs::rand(rng);
  254. let alpha = fs::Fs::zero(); // TODO
  255.  
  256. let pk_path = Path::new(PROVING_KEY_PATH);
  257. let vk_path = Path::new(VERIFICATION_KEY_PATH);
  258.  
  259. let pk_file = File::open(&pk_path)
  260. .map_err(|why| format!("couldn't open {}: {}", pk_path.display(), why))?;
  261. let vk_file = File::open(&vk_path)
  262. .map_err(|why| format!("couldn't open {}: {}", vk_path.display(), why))?;
  263.  
  264. let mut reader_pk = BufReader::new(pk_file);
  265. let mut reader_vk = BufReader::new(vk_file);
  266.  
  267. let mut buf_pk = vec![];
  268. reader_pk.read_to_end(&mut buf_pk)
  269. .map_err(|why| format!("couldn't read {}: {}", pk_path.display(), why))?;
  270.  
  271. let mut buf_vk = vec![];
  272. reader_vk.read_to_end(&mut buf_vk)
  273. .map_err(|why| format!("couldn't read {}: {}", vk_path.display(), why))?;
  274.  
  275. let proving_key = Parameters::<Bls12>::read(&mut &buf_pk[..], true)
  276. .expect("should be casted to Parameters<Bls12> type.");
  277. let prepared_vk = PreparedVerifyingKey::<Bls12>::read(&mut &buf_vk[..])
  278. .expect("should ne casted to PreparedVerifyingKey<Bls12> type");
  279.  
  280. let seed = hex::decode(sub_matches.value_of("sender-seed")
  281. .expect("Seed parameter is required; qed"))
  282. .expect("should be decoded to hex.");
  283.  
  284. let amount_str = sub_matches.value_of("amount")
  285. .expect("Amount parameter is required; qed");
  286. let amount: u32 = amount_str.parse()
  287. .expect("should be parsed to u32 number; qed");
  288.  
  289. let fee_str = api.get_storage("ConfTransfer", "TransactionBaseFee", None)
  290. .expect("should be fetched TransactionBaseFee from ConfTransfer module of Zerochain.");
  291. let fee = hexstr_to_u64(fee_str) as u32;
  292.  
  293. let origin_key = bytes_to_uniform_fs::<Bls12>(&seed[..]);
  294. let decryption_key = ProofGenerationKey::<Bls12>::from_seed(&seed[..], &PARAMS).bdk();
  295.  
  296. let mut decrypted_key = [0u8; 32];
  297. decryption_key.into_repr().write_le(&mut &mut decrypted_key[..])
  298. .expect("should be casted as bytes-array.");
  299.  
  300. let recipient_encryption_key = hex::decode(sub_matches.value_of("recipient-encryption-key")
  301. .expect("Recipient's encryption key parameter is required; qed")
  302. ).expect("should be decoded to hex.");
  303.  
  304. let (decrypted_balance, encrypted_balance_vec, _) = get_balance_from_decryption_key(&decrypted_key[..] ,api.clone());
  305. let remaining_balance = decrypted_balance - amount - fee;
  306. assert!(decrypted_balance >= amount + fee, "Not enough balance you have");
  307.  
  308. let recipient_account_id = EncryptionKey::<Bls12>::read(&mut &recipient_encryption_key[..], &PARAMS)
  309. .expect("should be casted to EncryptionKey<Bls12> type.");
  310. let encrypted_balance = elgamal::Ciphertext::read(&mut &encrypted_balance_vec[..], &PARAMS as &JubjubBls12)
  311. .expect("should be casted to Ciphertext type.");
  312.  
  313. println!("Computing zk proof...");
  314. let tx = Transaction::gen_tx(
  315. amount,
  316. remaining_balance,
  317. alpha,
  318. &proving_key,
  319. &prepared_vk,
  320. &recipient_account_id,
  321. &origin_key,
  322. encrypted_balance,
  323. rng,
  324. fee
  325. ).expect("fails to generate the tx");
  326.  
  327.  
  328. {
  329. println!("Start submitting a transaction to Zerochain...");
  330.  
  331. let p_g = zFixedGenerators::Diversifier; // 1
  332.  
  333. let mut rsk_repr = zFs::default().into_repr();
  334. rsk_repr.read_le(&mut &tx.rsk[..])
  335. .expect("should be casted to Fs's repr type.");
  336. let rsk = zFs::from_repr(rsk_repr)
  337. .expect("should be casted to Fs type from repr type.");
  338.  
  339. let sig_sk = zPrivateKey::<zBls12>(rsk);
  340. let sig_vk = SigVerificationKey::from_slice(&tx.rvk[..]);
  341.  
  342. let calls = Call::ConfTransfer(ConfTransferCall::confidential_transfer(
  343. Proof::from_slice(&tx.proof[..]),
  344. PkdAddress::from_slice(&tx.address_sender[..]),
  345. PkdAddress::from_slice(&tx.address_recipient[..]),
  346. zCiphertext::from_slice(&tx.enc_val_sender[..]),
  347. zCiphertext::from_slice(&tx.enc_val_recipient[..]),
  348. sig_vk,
  349. zCiphertext::from_slice(&tx.enc_fee[..]),
  350. ));
  351.  
  352. let era = Era::Immortal;
  353. let index = api.get_nonce(&sig_vk).expect("Nonce must be got.");
  354. let checkpoint = api.get_genesis_blockhash()
  355. .expect("should be fetched the genesis block hash from zerochain node.");
  356. let raw_payload = (Compact(index), calls, era, checkpoint);
  357.  
  358. let sig = raw_payload.using_encoded(|payload| {
  359. let msg = blake2_256(payload);
  360. let sig = sig_sk.sign(&msg[..], rng, p_g, &ZPARAMS as &zJubjubBls12);
  361.  
  362. let sig_vk = sig_vk.into_verification_key()
  363. .expect("should be casted to redjubjub::PublicKey<Bls12> type.");
  364. assert!(sig_vk.verify(&msg, &sig, p_g, &ZPARAMS as &zJubjubBls12));
  365.  
  366. sig
  367. });
  368.  
  369. let sig_repr = RedjubjubSignature::from_signature(&sig);
  370. let uxt = UncheckedExtrinsic::new_signed(index, raw_payload.1, sig_vk.into(), sig_repr, era);
  371. let _tx_hash = api.submit_extrinsic(&uxt)
  372. .expect("Faild to submit a extrinsic to zerochain node.");
  373.  
  374. println!("Remaining balance is {}", remaining_balance);
  375. }
  376.  
  377. },
  378. ("balance", Some(sub_matches)) => {
  379. println!("Getting encrypted balance from zerochain");
  380. let api = Api::init(Url::Local);
  381. let decryption_key_vec = hex::decode(sub_matches.value_of("decryption-key")
  382. .expect("Decryption key parameter is required; qed"))
  383. .expect("should be decoded to hex.");
  384.  
  385. let (decrypted_balance, _, encrypted_balance_str) = get_balance_from_decryption_key(&decryption_key_vec[..], api);
  386.  
  387. println!("Decrypted balance: {}", decrypted_balance);
  388. println!("Encrypted balance: {}", encrypted_balance_str);
  389. },
  390. ("print-tx", Some(sub_matches)) => {
  391. println!("Generate transaction...");
  392.  
  393. let sender_seed = hex::decode(sub_matches.value_of("sender-privatekey").unwrap()).unwrap();
  394. let recipient_seed = hex::decode(sub_matches.value_of("recipient-privatekey").unwrap()).unwrap();
  395.  
  396. let sender_address = get_address(&sender_seed[..]);
  397. let recipient_address = get_address(&recipient_seed[..]);
  398.  
  399. println!("Private Key(Sender): 0x{}\nAddress(Sender): 0x{}\n",
  400. HexDisplay::from(&sender_seed),
  401. HexDisplay::from(&sender_address),
  402. );
  403.  
  404. println!("Private Key(Recipient): 0x{}\nAddress(Recipient): 0x{}\n",
  405. HexDisplay::from(&recipient_seed),
  406. HexDisplay::from(&recipient_address),
  407. );
  408.  
  409. let pk_path = Path::new(sub_matches.value_of("proving-key-path").unwrap());
  410. let vk_path = Path::new(sub_matches.value_of("verification-key-path").unwrap());
  411.  
  412. let pk_file = File::open(&pk_path)
  413. .map_err(|why| format!("couldn't open {}: {}", pk_path.display(), why))?;
  414. let vk_file = File::open(&vk_path)
  415. .map_err(|why| format!("couldn't open {}: {}", vk_path.display(), why))?;
  416.  
  417. let mut reader_pk = BufReader::new(pk_file);
  418. let mut reader_vk = BufReader::new(vk_file);
  419.  
  420. let mut buf_pk = vec![];
  421. reader_pk.read_to_end(&mut buf_pk)
  422. .map_err(|why| format!("couldn't read {}: {}", pk_path.display(), why))?;
  423.  
  424. let mut buf_vk = vec![];
  425. reader_vk.read_to_end(&mut buf_vk)
  426. .map_err(|why| format!("couldn't read {}: {}", vk_path.display(), why))?;
  427.  
  428.  
  429. let amount_str = sub_matches.value_of("amount").unwrap();
  430. let amount: u32 = amount_str.parse().unwrap();
  431. let fee = 1 as u32;
  432.  
  433. let balance_str = sub_matches.value_of("balance").unwrap();
  434. let balance: u32 = balance_str.parse().unwrap();
  435.  
  436. println!("Transaction >>");
  437.  
  438. let rng = &mut OsRng::new().expect("should be able to construct RNG");
  439.  
  440. // let alpha = fs::Fs::rand(rng);
  441. let alpha = fs::Fs::zero(); // TODO
  442.  
  443. let proving_key = Parameters::<Bls12>::read(&mut &buf_pk[..], true).unwrap();
  444. let prepared_vk = PreparedVerifyingKey::<Bls12>::read(&mut &buf_vk[..]).unwrap();
  445.  
  446. let origin_key = bytes_to_uniform_fs::<Bls12>(&sender_seed[..]);
  447.  
  448. let address_recipient = EncryptionKey::<Bls12>::from_seed(&recipient_seed[..], &PARAMS);
  449.  
  450. let ciphertext_balance_a = sub_matches.value_of("encrypted-balance").unwrap();
  451. let ciphertext_balance_v = hex::decode(ciphertext_balance_a).unwrap();
  452. let ciphertext_balance = elgamal::Ciphertext::read(&mut &ciphertext_balance_v[..], &PARAMS as &JubjubBls12).unwrap();
  453.  
  454. let remaining_balance = balance - amount - fee;
  455.  
  456. let tx = Transaction::gen_tx(
  457. amount,
  458. remaining_balance,
  459. alpha,
  460. &proving_key,
  461. &prepared_vk,
  462. &address_recipient,
  463. &origin_key,
  464. ciphertext_balance,
  465. rng,
  466. fee
  467. ).expect("fails to generate the tx");
  468.  
  469. // println!(
  470. // "
  471. // \nEncrypted fee by sender: 0x{}
  472. // \nzkProof: 0x{}
  473. // \nEncrypted amount by sender: 0x{}
  474. // \nEncrypted amount by recipient: 0x{}
  475. // ",
  476. // HexDisplay::from(&tx.enc_fee as &AsBytesRef),
  477. // HexDisplay::from(&&tx.proof[..] as &AsBytesRef),
  478. // HexDisplay::from(&tx.enc_val_sender as &AsBytesRef),
  479. // HexDisplay::from(&tx.enc_val_recipient as &AsBytesRef),
  480. // );
  481. println!(
  482. "
  483. \nzkProof(Alice): 0x{}
  484. \naddress_sender(Alice): 0x{}
  485. \naddress_recipient(Alice): 0x{}
  486. \nvalue_sender(Alice): 0x{}
  487. \nvalue_recipient(Alice): 0x{}
  488. \nbalance_sender(Alice): 0x{}
  489. \nrvk(Alice): 0x{}
  490. \nrsk(Alice): 0x{}
  491. \nEncrypted fee by sender: 0x{}
  492. ",
  493. HexDisplay::from(&&tx.proof[..] as &AsBytesRef),
  494. HexDisplay::from(&tx.address_sender as &AsBytesRef),
  495. HexDisplay::from(&tx.address_recipient as &AsBytesRef),
  496. HexDisplay::from(&tx.enc_val_sender as &AsBytesRef),
  497. HexDisplay::from(&tx.enc_val_recipient as &AsBytesRef),
  498. HexDisplay::from(&tx.enc_bal_sender as &AsBytesRef),
  499. HexDisplay::from(&tx.rvk as &AsBytesRef),
  500. HexDisplay::from(&tx.rsk as &AsBytesRef),
  501. HexDisplay::from(&tx.enc_fee as &AsBytesRef),
  502. );
  503. },
  504. _ => unreachable!()
  505. }
  506. Ok(())
  507. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement