Răsfoiți Sursa

Remove num-bigint usage from crates, revert to u64.

parazyd 4 ani în urmă
părinte
comite
0d01be2f4e

+ 2 - 19
Cargo.lock

@@ -1208,7 +1208,6 @@ dependencies = [
  "libsqlite3-sys",
  "libsqlite3-sys",
  "log",
  "log",
  "native-tls",
  "native-tls",
- "num-bigint",
  "pasta_curves",
  "pasta_curves",
  "plotters",
  "plotters",
  "rand",
  "rand",
@@ -1274,7 +1273,6 @@ dependencies = [
  "incrementalmerkletree",
  "incrementalmerkletree",
  "lazy-init",
  "lazy-init",
  "log",
  "log",
- "num-bigint",
  "pasta_curves",
  "pasta_curves",
  "rand",
  "rand",
  "serde",
  "serde",
@@ -1297,7 +1295,6 @@ dependencies = [
  "darkfi",
  "darkfi",
  "halo2_gadgets",
  "halo2_gadgets",
  "halo2_proofs",
  "halo2_proofs",
- "num-bigint",
  "rand",
  "rand",
  "serde_json",
  "serde_json",
  "termion",
  "termion",
@@ -1564,7 +1561,6 @@ dependencies = [
  "clap 3.2.16",
  "clap 3.2.16",
  "darkfi",
  "darkfi",
  "log",
  "log",
- "num-bigint",
  "prettytable-rs",
  "prettytable-rs",
  "serde_json",
  "serde_json",
  "simplelog",
  "simplelog",
@@ -1748,7 +1744,6 @@ dependencies = [
  "hex",
  "hex",
  "lazy-init",
  "lazy-init",
  "log",
  "log",
- "num-bigint",
  "rand",
  "rand",
  "serde",
  "serde",
  "serde_derive",
  "serde_derive",
@@ -1969,9 +1964,9 @@ dependencies = [
 
 
 [[package]]
 [[package]]
 name = "futures-rustls"
 name = "futures-rustls"
-version = "0.22.1"
+version = "0.22.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e01fe9932a224b72b45336d96040aa86386d674a31d0af27d800ea7bc8ca97fe"
+checksum = "d2411eed028cdf8c8034eaf21f9915f956b6c3abec4d4c7949ee67f0721127bd"
 dependencies = [
 dependencies = [
  "futures-io",
  "futures-io",
  "rustls",
  "rustls",
@@ -2601,18 +2596,6 @@ dependencies = [
  "minimal-lexical",
  "minimal-lexical",
 ]
 ]
 
 
-[[package]]
-name = "num-bigint"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f"
-dependencies = [
- "autocfg",
- "num-integer",
- "num-traits",
- "serde",
-]
-
 [[package]]
 [[package]]
 name = "num-integer"
 name = "num-integer"
 version = "0.1.45"
 version = "0.1.45"

+ 0 - 2
Cargo.toml

@@ -75,7 +75,6 @@ bs58 = {version = "0.4.0", optional = true}
 toml = {version = "0.5.9", optional = true}
 toml = {version = "0.5.9", optional = true}
 bytes = {version = "1.2.1", optional = true}
 bytes = {version = "1.2.1", optional = true}
 bincode = {version = "2.0.0-rc.1", features = ["serde"], optional = true}
 bincode = {version = "2.0.0-rc.1", features = ["serde"], optional = true}
-num-bigint = {version = "0.4.3", features = ["serde"], optional = true}
 serde_json = {version = "1.0.83", optional = true}
 serde_json = {version = "1.0.83", optional = true}
 serde = {version = "1.0.142", features = ["derive"], optional = true}
 serde = {version = "1.0.142", features = ["derive"], optional = true}
 structopt = {version= "0.3.26", optional = true}
 structopt = {version= "0.3.26", optional = true}
@@ -176,7 +175,6 @@ util = [
 	"simplelog",
 	"simplelog",
 	"serde_json",
 	"serde_json",
 	"dirs",
 	"dirs",
-	"num-bigint",
 	"fxhash",
 	"fxhash",
 	"chrono",
 	"chrono",
 	"indicatif",
 	"indicatif",

+ 0 - 1
bin/darkfid/Cargo.toml

@@ -24,7 +24,6 @@ fxhash = "0.2.1"
 incrementalmerkletree = "0.3.0"
 incrementalmerkletree = "0.3.0"
 lazy-init = "0.5.1"
 lazy-init = "0.5.1"
 log = "0.4.17"
 log = "0.4.17"
-num-bigint = {version = "0.4.3", features = ["serde"]}
 pasta_curves = "0.4.0"
 pasta_curves = "0.4.0"
 rand = "0.8.5"
 rand = "0.8.5"
 serde_json = "1.0.83"
 serde_json = "1.0.83"

+ 0 - 1
bin/darkotc/Cargo.toml

@@ -15,7 +15,6 @@ clap = {version = "3.2.16", features = ["derive"]}
 darkfi = {path = "../../", features = ["crypto", "rpc", "util"]}
 darkfi = {path = "../../", features = ["crypto", "rpc", "util"]}
 halo2_proofs = "0.2.0"
 halo2_proofs = "0.2.0"
 halo2_gadgets = "0.2.0"
 halo2_gadgets = "0.2.0"
-num-bigint = {version = "0.4.3", features = ["serde"]}
 rand = "0.8.5"
 rand = "0.8.5"
 serde_json = "1.0.83"
 serde_json = "1.0.83"
 termion = "1.5.6"
 termion = "1.5.6"

+ 1 - 3
bin/darkotc/src/cli_util.rs

@@ -1,10 +1,8 @@
 use std::process::exit;
 use std::process::exit;
 
 
-use num_bigint::BigUint;
-
 use darkfi::{util::decode_base10, Result};
 use darkfi::{util::decode_base10, Result};
 
 
-pub fn parse_value_pair(s: &str) -> Result<(BigUint, BigUint)> {
+pub fn parse_value_pair(s: &str) -> Result<(u64, u64)> {
     let v: Vec<&str> = s.split(':').collect();
     let v: Vec<&str> = s.split(':').collect();
     if v.len() != 2 {
     if v.len() != 2 {
         eprintln!("Invalid value pair. Use a pair such as '13.37:11.0'.");
         eprintln!("Invalid value pair. Use a pair such as '13.37:11.0'.");

+ 5 - 11
bin/darkotc/src/main.rs

@@ -7,7 +7,6 @@ use std::{
 use clap::{Parser, Subcommand};
 use clap::{Parser, Subcommand};
 use darkfi::crypto::proof::VerifyingKey;
 use darkfi::crypto::proof::VerifyingKey;
 use halo2_proofs::{arithmetic::Field, pasta::group::ff::PrimeField};
 use halo2_proofs::{arithmetic::Field, pasta::group::ff::PrimeField};
-use num_bigint::BigUint;
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
 use serde_json::json;
 use serde_json::json;
 use termion::color;
 use termion::color;
@@ -201,13 +200,12 @@ impl Rpc {
 async fn init_swap(
 async fn init_swap(
     endpoint: Url,
     endpoint: Url,
     token_pair: (String, String),
     token_pair: (String, String),
-    value_pair: (BigUint, BigUint),
+    value_pair: (u64, u64),
 ) -> Result<()> {
 ) -> Result<()> {
     let rpc_client = RpcClient::new(endpoint).await?;
     let rpc_client = RpcClient::new(endpoint).await?;
     let rpc = Rpc { rpc_client };
     let rpc = Rpc { rpc_client };
 
 
-    // TODO: Rethink the use of BigUint throughout the codebase. Can we just use u64?
-    // TODO: Think about decimals as well, there has to be some metadata to keep track.
+    // TODO: Think about decimals, there has to be some metadata to keep track.
     let tp = (token_id::parse_b58(&token_pair.0)?, token_id::parse_b58(&token_pair.1)?);
     let tp = (token_id::parse_b58(&token_pair.0)?, token_id::parse_b58(&token_pair.1)?);
     let vp: (u64, u64) =
     let vp: (u64, u64) =
         (value_pair.0.clone().try_into().unwrap(), value_pair.1.clone().try_into().unwrap());
         (value_pair.0.clone().try_into().unwrap(), value_pair.1.clone().try_into().unwrap());
@@ -219,11 +217,7 @@ async fn init_swap(
             "Error: There is not enough balance for token \"{}\" in your wallet.",
             "Error: There is not enough balance for token \"{}\" in your wallet.",
             token_pair.0
             token_pair.0
         );
         );
-        eprintln!(
-            "Available balance is {} ({})",
-            encode_base10(BigUint::from(balance), 8),
-            balance
-        );
+        eprintln!("Available balance is {} ({})", encode_base10(balance, 8), balance);
         exit(1);
         exit(1);
     }
     }
 
 
@@ -460,12 +454,12 @@ fn inspect(data: &str) -> Result<()> {
 
 
     eprintln!(
     eprintln!(
         "Mint: {} {}",
         "Mint: {} {}",
-        encode_base10(BigUint::from(sd.mint_value), 8),
+        encode_base10(sd.mint_value, 8),
         bs58::encode(sd.mint_token.to_repr()).into_string()
         bs58::encode(sd.mint_token.to_repr()).into_string()
     );
     );
     eprintln!(
     eprintln!(
         "Burn: {} {}",
         "Burn: {} {}",
-        encode_base10(BigUint::from(sd.burn_value), 8),
+        encode_base10(sd.burn_value, 8),
         bs58::encode(sd.burn_token.to_repr()).into_string()
         bs58::encode(sd.burn_token.to_repr()).into_string()
     );
     );
 
 

+ 0 - 1
bin/drk/Cargo.toml

@@ -13,7 +13,6 @@ async-std = {version = "1.12.0", features = ["attributes"]}
 clap = {version = "3.2.16", features = ["derive"]}
 clap = {version = "3.2.16", features = ["derive"]}
 darkfi = {path = "../../", features = ["crypto", "util", "rpc"]}
 darkfi = {path = "../../", features = ["crypto", "util", "rpc"]}
 log = "0.4.17"
 log = "0.4.17"
-num-bigint = {version = "0.4.3", features = ["serde"]}
 prettytable-rs = "0.8.0"
 prettytable-rs = "0.8.0"
 serde_json = "1.0.83"
 serde_json = "1.0.83"
 simplelog = "0.12.0"
 simplelog = "0.12.0"

+ 1 - 2
bin/drk/src/main.rs

@@ -1,7 +1,6 @@
 use std::{process::exit, str::FromStr, time::Instant};
 use std::{process::exit, str::FromStr, time::Instant};
 
 
 use clap::{Parser, Subcommand};
 use clap::{Parser, Subcommand};
-use num_bigint::BigUint;
 use prettytable::{cell, format, row, Table};
 use prettytable::{cell, format, row, Table};
 
 
 use serde_json::json;
 use serde_json::json;
@@ -176,7 +175,7 @@ impl Drk {
 
 
         for i in rep.as_object().unwrap().keys() {
         for i in rep.as_object().unwrap().keys() {
             if let Some(balance) = rep[i].as_u64() {
             if let Some(balance) = rep[i].as_u64() {
-                table.add_row(row![i, encode_base10(BigUint::from(balance), 8)]);
+                table.add_row(row![i, encode_base10(balance, 8)]);
                 continue
                 continue
             }
             }
 
 

+ 0 - 1
bin/faucetd/Cargo.toml

@@ -23,7 +23,6 @@ futures-lite = "1.12.0"
 hex = "0.4.3"
 hex = "0.4.3"
 lazy-init = "0.5.1"
 lazy-init = "0.5.1"
 log = "0.4.17"
 log = "0.4.17"
-num-bigint = {version = "0.4.3", features = ["serde"]}
 rand = "0.8.5"
 rand = "0.8.5"
 serde_json = "1.0.83"
 serde_json = "1.0.83"
 simplelog = "0.12.0"
 simplelog = "0.12.0"

+ 4 - 13
bin/faucetd/src/main.rs

@@ -6,7 +6,6 @@ use async_trait::async_trait;
 use chrono::Utc;
 use chrono::Utc;
 use futures_lite::future;
 use futures_lite::future;
 use log::{debug, error, info};
 use log::{debug, error, info};
-use num_bigint::BigUint;
 use serde_derive::Deserialize;
 use serde_derive::Deserialize;
 use serde_json::{json, Value};
 use serde_json::{json, Value};
 use structopt::StructOpt;
 use structopt::StructOpt;
@@ -111,7 +110,7 @@ struct Args {
 
 
     #[structopt(long, default_value = "10")]
     #[structopt(long, default_value = "10")]
     /// Airdrop amount limit
     /// Airdrop amount limit
-    airdrop_limit: String, // We convert this to biguint with decode_base10
+    airdrop_limit: String, // We convert this to u64 with decode_base10
 
 
     #[structopt(short, parse(from_occurrences))]
     #[structopt(short, parse(from_occurrences))]
     /// Increase verbosity (-vvv supported)
     /// Increase verbosity (-vvv supported)
@@ -124,7 +123,7 @@ pub struct Faucetd {
     client: Arc<Client>,
     client: Arc<Client>,
     validator_state: ValidatorStatePtr,
     validator_state: ValidatorStatePtr,
     airdrop_timeout: i64,
     airdrop_timeout: i64,
-    airdrop_limit: BigUint,
+    airdrop_limit: u64,
     airdrop_map: Arc<Mutex<HashMap<Address, i64>>>,
     airdrop_map: Arc<Mutex<HashMap<Address, i64>>>,
 }
 }
 
 
@@ -149,7 +148,7 @@ impl Faucetd {
         validator_state: ValidatorStatePtr,
         validator_state: ValidatorStatePtr,
         sync_p2p: P2pPtr,
         sync_p2p: P2pPtr,
         timeout: i64,
         timeout: i64,
-        limit: BigUint,
+        limit: u64,
     ) -> Result<Self> {
     ) -> Result<Self> {
         let client = validator_state.read().await.client.clone();
         let client = validator_state.read().await.client.clone();
 
 
@@ -232,19 +231,11 @@ impl Faucetd {
         };
         };
         drop(map);
         drop(map);
 
 
-        let amnt: u64 = match amount.try_into() {
-            Ok(v) => v,
-            Err(e) => {
-                error!("airdrop(): Failed converting biguint to u64: {}", e);
-                return JsonError::new(InternalError, None, id).into()
-            }
-        };
-
         let tx = match self
         let tx = match self
             .client
             .client
             .build_transaction(
             .build_transaction(
                 pubkey,
                 pubkey,
-                amnt,
+                amount,
                 token_id,
                 token_id,
                 true,
                 true,
                 self.validator_state.read().await.state_machine.clone(),
                 self.validator_state.read().await.state_machine.clone(),

+ 0 - 8
src/error.rs

@@ -25,14 +25,6 @@ pub enum Error {
     #[error(transparent)]
     #[error(transparent)]
     ParseFloatError(#[from] std::num::ParseFloatError),
     ParseFloatError(#[from] std::num::ParseFloatError),
 
 
-    #[cfg(feature = "num-bigint")]
-    #[error(transparent)]
-    ParseBigIntError(#[from] num_bigint::ParseBigIntError),
-
-    #[cfg(feature = "num-bigint")]
-    #[error(transparent)]
-    TryFromBigIntError(#[from] num_bigint::TryFromBigIntError<num_bigint::BigUint>),
-
     #[cfg(feature = "url")]
     #[cfg(feature = "url")]
     #[error(transparent)]
     #[error(transparent)]
     UrlParseError(#[from] url::ParseError),
     UrlParseError(#[from] url::ParseError),

+ 6 - 6
src/lib.rs

@@ -10,21 +10,18 @@ pub mod consensus;
 #[cfg(feature = "crypto")]
 #[cfg(feature = "crypto")]
 pub mod crypto;
 pub mod crypto;
 
 
-#[cfg(feature = "dht")]
-pub mod dht;
-
 #[cfg(feature = "crypto")]
 #[cfg(feature = "crypto")]
 pub mod zk;
 pub mod zk;
 
 
+#[cfg(feature = "dht")]
+pub mod dht;
+
 #[cfg(feature = "net")]
 #[cfg(feature = "net")]
 pub mod net;
 pub mod net;
 
 
 #[cfg(feature = "node")]
 #[cfg(feature = "node")]
 pub mod node;
 pub mod node;
 
 
-//#[cfg(feature = "wasm-runtime")]
-//pub mod runtime;
-
 #[cfg(feature = "raft")]
 #[cfg(feature = "raft")]
 pub mod raft;
 pub mod raft;
 
 
@@ -43,5 +40,8 @@ pub mod util;
 #[cfg(feature = "wallet")]
 #[cfg(feature = "wallet")]
 pub mod wallet;
 pub mod wallet;
 
 
+//#[cfg(feature = "wasm-runtime")]
+//pub mod runtime;
+
 #[cfg(feature = "zkas")]
 #[cfg(feature = "zkas")]
 pub mod zkas;
 pub mod zkas;

+ 13 - 18
src/util/parse.rs

@@ -1,7 +1,5 @@
 use std::{iter::FromIterator, str::FromStr};
 use std::{iter::FromIterator, str::FromStr};
 
 
-use num_bigint::BigUint;
-
 use crate::{Error, Result};
 use crate::{Error, Result};
 
 
 fn is_digit(c: char) -> bool {
 fn is_digit(c: char) -> bool {
@@ -12,7 +10,7 @@ fn char_eq(a: char, b: char) -> bool {
     a == b
     a == b
 }
 }
 
 
-pub fn decode_base10(amount: &str, decimal_places: usize, strict: bool) -> Result<BigUint> {
+pub fn decode_base10(amount: &str, decimal_places: usize, strict: bool) -> Result<u64> {
     let mut s: Vec<char> = amount.to_string().chars().collect();
     let mut s: Vec<char> = amount.to_string().chars().collect();
 
 
     // Get rid of the decimal point:
     // Get rid of the decimal point:
@@ -54,19 +52,17 @@ pub fn decode_base10(amount: &str, decimal_places: usize, strict: bool) -> Resul
     }
     }
 
 
     // Convert to an integer
     // Convert to an integer
-    let number = BigUint::from_str(&String::from_iter(&s))?;
+    let number = u64::from_str(&String::from_iter(&s))?;
 
 
     // Round and return
     // Round and return
-    /*
     if round && number == u64::MAX {
     if round && number == u64::MAX {
-    return Err(Error::ParseFailed("u64 overflow"));
+        return Err(Error::ParseFailed("u64 overflow"))
     }
     }
-    */
 
 
     Ok(number + round as u64)
     Ok(number + round as u64)
 }
 }
 
 
-pub fn encode_base10(amount: BigUint, decimal_places: usize) -> String {
+pub fn encode_base10(amount: u64, decimal_places: usize) -> String {
     let mut s: Vec<char> =
     let mut s: Vec<char> =
         format!("{:0width$}", amount, width = 1 + decimal_places).chars().collect();
         format!("{:0width$}", amount, width = 1 + decimal_places).chars().collect();
     s.insert(s.len() - decimal_places, '.');
     s.insert(s.len() - decimal_places, '.');
@@ -95,24 +91,23 @@ pub fn truncate(amount: u64, decimals: u16, token_decimals: u16) -> Result<u64>
 #[cfg(test)]
 #[cfg(test)]
 mod tests {
 mod tests {
     use super::{decode_base10, encode_base10, truncate};
     use super::{decode_base10, encode_base10, truncate};
-    use num_bigint::ToBigUint;
 
 
     #[test]
     #[test]
     fn test_decode_base10() {
     fn test_decode_base10() {
-        assert_eq!(124.to_biguint().unwrap(), decode_base10("12.33", 1, false).unwrap());
-        assert_eq!(1233000.to_biguint().unwrap(), decode_base10("12.33", 5, false).unwrap());
-        assert_eq!(1200000.to_biguint().unwrap(), decode_base10("12.", 5, false).unwrap());
-        assert_eq!(1200000.to_biguint().unwrap(), decode_base10("12", 5, false).unwrap());
+        assert_eq!(124, decode_base10("12.33", 1, false).unwrap());
+        assert_eq!(1233000, decode_base10("12.33", 5, false).unwrap());
+        assert_eq!(1200000, decode_base10("12.", 5, false).unwrap());
+        assert_eq!(1200000, decode_base10("12", 5, false).unwrap());
         assert!(decode_base10("12.33", 1, true).is_err());
         assert!(decode_base10("12.33", 1, true).is_err());
     }
     }
 
 
     #[test]
     #[test]
     fn test_encode_base10() {
     fn test_encode_base10() {
-        assert_eq!("23.4321111", &encode_base10(234321111_u64.to_biguint().unwrap(), 7));
-        assert_eq!("23432111.1", &encode_base10(234321111_u64.to_biguint().unwrap(), 1));
-        assert_eq!("234321.1", &encode_base10(2343211_u64.to_biguint().unwrap(), 1));
-        assert_eq!("2343211", &encode_base10(2343211_u64.to_biguint().unwrap(), 0));
-        assert_eq!("0.00002343", &encode_base10(2343_u64.to_biguint().unwrap(), 8));
+        assert_eq!("23.4321111", &encode_base10(234321111, 7));
+        assert_eq!("23432111.1", &encode_base10(234321111, 1));
+        assert_eq!("234321.1", &encode_base10(2343211, 1));
+        assert_eq!("2343211", &encode_base10(2343211, 0));
+        assert_eq!("0.00002343", &encode_base10(2343, 8));
     }
     }
 
 
     #[test]
     #[test]

+ 0 - 17
src/util/serial.rs

@@ -8,7 +8,6 @@ use std::{
     str::FromStr,
     str::FromStr,
 };
 };
 
 
-use num_bigint::BigUint;
 use url::Url;
 use url::Url;
 
 
 pub use darkfi_derive::{SerialDecodable, SerialEncodable};
 pub use darkfi_derive::{SerialDecodable, SerialEncodable};
@@ -631,22 +630,6 @@ impl Decodable for Box<[u8]> {
     }
     }
 }
 }
 
 
-impl Encodable for BigUint {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        let bytes = self.to_bytes_le();
-        s.write_slice(&bytes)?;
-        Ok(bytes.len())
-    }
-}
-
-impl Decodable for BigUint {
-    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
-        let mut bytes = vec![];
-        d.read_slice(&mut bytes)?;
-        Ok(BigUint::from_bytes_le(&bytes))
-    }
-}
-
 impl Encodable for blake3::Hash {
 impl Encodable for blake3::Hash {
     fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
     fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
         s.write_slice(self.as_bytes())?;
         s.write_slice(self.as_bytes())?;