Преглед изворни кода

consensus/types: Wrap Float10 into our own struct for some code simplification.

parazyd пре 3 година
родитељ
комит
4c4132ce7e
4 измењених фајлова са 126 додато и 38 уклоњено
  1. 16 17
      src/consensus/constants.rs
  2. 7 18
      src/consensus/state.rs
  3. 99 3
      src/consensus/types.rs
  4. 4 0
      src/error.rs

+ 16 - 17
src/consensus/constants.rs

@@ -48,28 +48,27 @@ lazy_static! {
     pub static ref TESTNET_INITIAL_DISTRIBUTION: u64 = 1000;
     pub static ref TESTNET_INITIAL_DISTRIBUTION: u64 = 1000;
 
 
     // Commonly used Float10
     // Commonly used Float10
-    pub static ref FLOAT10_ZERO: Float10 = Float10::from_str_native("0").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref FLOAT10_ONE: Float10 = Float10::from_str_native("1").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref FLOAT10_TWO: Float10 = Float10::from_str_native("2").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref FLOAT10_THREE: Float10 = Float10::from_str_native("3").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref FLOAT10_FIVE: Float10 = Float10::from_str_native("5").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref FLOAT10_NINE: Float10 = Float10::from_str_native("9").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref FLOAT10_TEN: Float10 = Float10::from_str_native("10").unwrap().with_precision(RADIX_BITS).value();
+    pub static ref FLOAT10_ZERO: Float10 = Float10::try_from("0").unwrap();
+    pub static ref FLOAT10_ONE: Float10 = Float10::try_from("1").unwrap();
+    pub static ref FLOAT10_TWO: Float10 = Float10::try_from("2").unwrap();
+    pub static ref FLOAT10_THREE: Float10 = Float10::try_from("3").unwrap();
+    pub static ref FLOAT10_FIVE: Float10 = Float10::try_from("5").unwrap();
+    pub static ref FLOAT10_NINE: Float10 = Float10::try_from("9").unwrap();
+    pub static ref FLOAT10_TEN: Float10 = Float10::try_from("10").unwrap();
 
 
     // Consensus parameters
     // Consensus parameters
-    pub static ref DT: Float10 =  Float10::from_str_native("0.1").unwrap().with_precision(RADIX_BITS).value();
+    pub static ref DT: Float10 =  Float10::try_from("0.1").unwrap();
     pub static ref TI: Float10 = FLOAT10_ONE.clone();
     pub static ref TI: Float10 = FLOAT10_ONE.clone();
     pub static ref TD: Float10 = FLOAT10_ONE.clone();
     pub static ref TD: Float10 = FLOAT10_ONE.clone();
-    pub static ref KP: Float10 = Float10::from_str_native("0.1").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref KI: Float10 = Float10::from_str_native("0.03").unwrap().with_precision(RADIX_BITS).value();
+    pub static ref KP: Float10 = Float10::try_from("0.1").unwrap();
+    pub static ref KI: Float10 = Float10::try_from("0.03").unwrap();
     pub static ref KD: Float10 = FLOAT10_ONE.clone();
     pub static ref KD: Float10 = FLOAT10_ONE.clone();
-    pub static ref PID_OUT_STEP: Float10  = Float10::from_str_native("0.1").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref MAX_DER: Float10 = Float10::from_str_native("0.1").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref MIN_DER: Float10 = Float10::from_str_native("-0.1").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref MAX_F: Float10 = Float10::from_str_native("0.99").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref MIN_F: Float10 = Float10::from_str_native("0.05").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref DEG_RATE: Float10 = Float10::from_str_native("0.9").unwrap().with_precision(RADIX_BITS).value();
-
+    pub static ref PID_OUT_STEP: Float10  = Float10::try_from("0.1").unwrap();
+    pub static ref MAX_DER: Float10 = Float10::try_from("0.1").unwrap();
+    pub static ref MIN_DER: Float10 = Float10::try_from("-0.1").unwrap();
+    pub static ref MAX_F: Float10 = Float10::try_from("0.99").unwrap();
+    pub static ref MIN_F: Float10 = Float10::try_from("0.05").unwrap();
+    pub static ref DEG_RATE: Float10 = Float10::try_from("0.9").unwrap();
 }
 }
 
 
 /// Block version number
 /// Block version number

+ 7 - 18
src/consensus/state.rs

@@ -34,9 +34,7 @@ use super::{
     utils::fbig2base,
     utils::fbig2base,
     Block, BlockProposal, Float10,
     Block, BlockProposal, Float10,
 };
 };
-
 use crate::{blockchain::Blockchain, net, tx::Transaction, util::time::Timestamp, Error, Result};
 use crate::{blockchain::Blockchain, net, tx::Transaction, util::time::Timestamp, Error, Result};
-use dashu::base::Abs;
 
 
 /// This struct represents the information required by the consensus algorithm
 /// This struct represents the information required by the consensus algorithm
 pub struct ConsensusState {
 pub struct ConsensusState {
@@ -241,12 +239,8 @@ impl ConsensusState {
         info!(target: "consensus::state", "sigmas(): stake: {}", total_stake);
         info!(target: "consensus::state", "sigmas(): stake: {}", total_stake);
         let one = constants::FLOAT10_ONE.clone();
         let one = constants::FLOAT10_ONE.clone();
         let two = constants::FLOAT10_TWO.clone();
         let two = constants::FLOAT10_TWO.clone();
-        let field_p = Float10::from_str_native(constants::P)
-            .unwrap()
-            .with_precision(constants::RADIX_BITS)
-            .value();
-        let total_sigma =
-            Float10::try_from(total_stake).unwrap().with_precision(constants::RADIX_BITS).value();
+        let field_p = Float10::try_from(constants::P).unwrap();
+        let total_sigma = Float10::try_from(total_stake).unwrap();
 
 
         let x = one - f;
         let x = one - f;
         let c = x.ln();
         let c = x.ln();
@@ -372,7 +366,7 @@ impl ConsensusState {
         }
         }
         self.leaders_history.push(count);
         self.leaders_history.push(count);
         info!(target: "consensus::state", "extend_leaders_history(): Current leaders history: {:?}", self.leaders_history);
         info!(target: "consensus::state", "extend_leaders_history(): Current leaders history: {:?}", self.leaders_history);
-        Float10::try_from(count as i64).unwrap().with_precision(constants::RADIX_BITS).value()
+        Float10::try_from(count as i64).unwrap()
     }
     }
 
 
     fn pid_error(feedback: Float10) -> Float10 {
     fn pid_error(feedback: Float10) -> Float10 {
@@ -395,7 +389,7 @@ impl ConsensusState {
             }
             }
         }
         }
 
 
-        Float10::try_from(max as i64).unwrap().with_precision(constants::RADIX_BITS).value()
+        Float10::try_from(max as i64).unwrap()
     }
     }
 
 
     fn tuned_kp(&self) -> Float10 {
     fn tuned_kp(&self) -> Float10 {
@@ -408,14 +402,9 @@ impl ConsensusState {
 
 
     fn f_der(&self) -> Float10 {
     fn f_der(&self) -> Float10 {
         let len = self.leaders_history.len();
         let len = self.leaders_history.len();
-        let last = Float10::try_from(self.leaders_history[len - 1] as i64)
-            .unwrap()
-            .with_precision(constants::RADIX_BITS)
-            .value();
-        let second_to_last = Float10::try_from(self.leaders_history[len - 2] as i64)
-            .unwrap()
-            .with_precision(constants::RADIX_BITS)
-            .value();
+        let last = Float10::try_from(self.leaders_history[len - 1] as i64).unwrap();
+        let second_to_last = Float10::try_from(self.leaders_history[len - 2] as i64).unwrap();
+
         let mut der =
         let mut der =
             (Self::pid_error(second_to_last) - Self::pid_error(last)) / constants::DT.clone();
             (Self::pid_error(second_to_last) - Self::pid_error(last)) / constants::DT.clone();
         der = if der > constants::MAX_DER.clone() { constants::MAX_DER.clone() } else { der };
         der = if der > constants::MAX_DER.clone() { constants::MAX_DER.clone() } else { der };

+ 99 - 3
src/consensus/types.rs

@@ -16,7 +16,103 @@
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  */
  */
 
 
-//! Type aliases used in the consensus codevbase.
-use dashu::float::{round::mode::Zero, FBig};
+//! Type aliases used in the consensus codebase.
+use std::ops::{Add, AddAssign, Div, Mul, Sub};
 
 
-pub type Float10 = FBig<Zero, 10>;
+use dashu::{
+    base::Abs,
+    float::{round::mode::Zero, FBig, Repr},
+};
+
+use super::constants::RADIX_BITS;
+
+const B: u64 = 10;
+
+#[derive(Clone, PartialEq, PartialOrd, Debug)]
+pub struct Float10(FBig<Zero, B>);
+
+impl Float10 {
+    pub fn repr(&self) -> &Repr<B> {
+        self.0.repr()
+    }
+
+    pub fn abs(&self) -> Self {
+        Self(self.0.clone().abs())
+    }
+
+    pub fn powf(&self, exp: Self) -> Self {
+        Self(self.0.powf(exp.0))
+    }
+
+    pub fn ln(&self) -> Self {
+        Self(self.0.ln())
+    }
+}
+
+impl Add for Float10 {
+    type Output = Self;
+
+    fn add(self, other: Self) -> Self {
+        Self(self.0 + other.0)
+    }
+}
+
+impl AddAssign for Float10 {
+    fn add_assign(&mut self, other: Self) {
+        *self = Self(self.0.clone() + other.0);
+    }
+}
+
+impl Sub for Float10 {
+    type Output = Self;
+
+    fn sub(self, other: Self) -> Self {
+        Self(self.0 - other.0)
+    }
+}
+
+impl Mul for Float10 {
+    type Output = Self;
+
+    fn mul(self, other: Self) -> Self {
+        Self(self.0 * other.0)
+    }
+}
+
+impl Div for Float10 {
+    type Output = Self;
+
+    fn div(self, other: Self) -> Self {
+        Self(self.0 / other.0)
+    }
+}
+
+impl std::fmt::Display for Float10 {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        write!(f, "{}", self.0)
+    }
+}
+
+impl TryFrom<&str> for Float10 {
+    type Error = crate::Error;
+
+    fn try_from(value: &str) -> Result<Self, Self::Error> {
+        Ok(Self(FBig::from_str_native(value)?.with_precision(RADIX_BITS).value()))
+    }
+}
+
+impl TryFrom<u64> for Float10 {
+    type Error = crate::Error;
+
+    fn try_from(value: u64) -> Result<Self, Self::Error> {
+        Ok(Self(FBig::try_from(value)?))
+    }
+}
+
+impl TryFrom<i64> for Float10 {
+    type Error = crate::Error;
+
+    fn try_from(value: i64) -> Result<Self, Self::Error> {
+        Ok(Self(FBig::try_from(value)?))
+    }
+}

+ 4 - 0
src/error.rs

@@ -59,6 +59,10 @@ pub enum Error {
     #[error(transparent)]
     #[error(transparent)]
     TryFromSliceError(#[from] std::array::TryFromSliceError),
     TryFromSliceError(#[from] std::array::TryFromSliceError),
 
 
+    #[cfg(feature = "dashu")]
+    #[error(transparent)]
+    DashuParseError(#[from] dashu::integer::error::ParseError),
+
     // ===============
     // ===============
     // Encoding errors
     // Encoding errors
     // ===============
     // ===============