rpc_airdrop.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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 darkfi::rpc::{client::RpcClient, jsonrpc::JsonRequest};
  20. use darkfi_sdk::{
  21. crypto::{mimc_vdf, PublicKey},
  22. num_bigint::BigUint,
  23. num_traits::Num,
  24. };
  25. use serde_json::json;
  26. use url::Url;
  27. use super::Drk;
  28. impl Drk {
  29. /// Request an airdrop of `amount` `token_id` tokens from a faucet.
  30. /// Returns a transaction ID on success.
  31. pub async fn request_airdrop(
  32. &self,
  33. faucet_endpoint: Url,
  34. amount: f64,
  35. address: PublicKey,
  36. ) -> Result<String> {
  37. let rpc_client = RpcClient::new(faucet_endpoint).await?;
  38. // First we request a VDF challenge from the faucet
  39. let params = json!([format!("{}", address)]);
  40. let req = JsonRequest::new("challenge", params);
  41. let rep = rpc_client.request(req).await?;
  42. let Some(rep) = rep.as_array() else {
  43. return Err(anyhow!("Invalid challenge response from faucet: {:?}", rep))
  44. };
  45. if rep.len() != 2 || !rep[0].is_string() || !rep[1].is_u64() {
  46. return Err(anyhow!("Invalid challenge response from faucet: {:?}", rep))
  47. }
  48. // Retrieve VDF challenge
  49. let challenge = BigUint::from_str_radix(rep[0].as_str().unwrap(), 16)?;
  50. let n_steps = rep[1].as_u64().unwrap();
  51. // Then evaluate the VDF
  52. eprintln!("Evaluating VDF with n_steps={} ... (this could take about a minute)", n_steps);
  53. let witness = mimc_vdf::eval(&challenge, n_steps);
  54. eprintln!("Done! Sending airdrop request...");
  55. // And finally request airdrop with the VDF evaluation witness
  56. let params = json!([format!("{}", address), amount, witness.to_str_radix(16)]);
  57. let req = JsonRequest::new("airdrop", params);
  58. let rep = rpc_client.oneshot_request(req).await?;
  59. let txid = serde_json::from_value(rep)?;
  60. Ok(txid)
  61. }
  62. }