utils.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. use crate::consensus::ouroboros::types::Float10;
  2. use dashu::integer::{IBig, Sign};
  3. use log::{debug, info};
  4. use pasta_curves::pallas;
  5. //use pasta_curves::{group::ff::PrimeField};
  6. //use dashu::integer::{UBig};
  7. pub(crate) fn fbig2ibig(f: Float10) -> IBig {
  8. let rad = IBig::try_from(10).unwrap();
  9. let sig = f.repr().significand();
  10. let exp = f.repr().exponent();
  11. let val: IBig = if exp >= 0 { sig.clone() * rad.pow(exp as usize) } else { sig.clone() };
  12. debug!("fbig2ibig (f): {}", f);
  13. debug!("fbig2ibig (i): {}", val);
  14. val
  15. }
  16. /*
  17. pub(crate) fn base2ibig(base: pallas::Base) -> IBig {
  18. //
  19. let byts: [u8; 32] = base.to_repr();
  20. let words: [u64; 4] = [
  21. u64::from_le_bytes(byts[0..8].try_into().expect("")),
  22. u64::from_le_bytes(byts[8..16].try_into().expect("")),
  23. u64::from_le_bytes(byts[16..24].try_into().expect("")),
  24. u64::from_le_bytes(byts[24..32].try_into().expect("")),
  25. ];
  26. let uparts = UBig::from_words(&words);
  27. //TODO both y, and t are positive, but workout the sign for general use
  28. let ibig = IBig::from_parts(Sign::Positive, uparts);
  29. ibig
  30. }
  31. */
  32. pub(crate) fn fbig2base(f: Float10) -> pallas::Base {
  33. info!("fbig -> base (f): {}", f);
  34. let val: IBig = fbig2ibig(f);
  35. let (sign, word) = val.as_sign_words();
  36. //TODO (res) set pallas base sign, i.e sigma1 is negative.
  37. let mut words: [u64; 4] = [0, 0, 0, 0];
  38. for i in 0..word.len() {
  39. words[i] = word[i];
  40. }
  41. let base = match sign {
  42. Sign::Positive => pallas::Base::from_raw(words),
  43. Sign::Negative => pallas::Base::from_raw(words).neg(),
  44. };
  45. base
  46. }
  47. #[cfg(test)]
  48. mod tests {
  49. use dashu::integer::IBig;
  50. use pasta_curves::pallas;
  51. use crate::consensus::ouroboros::{
  52. consts::RADIX_BITS,
  53. types::Float10,
  54. utils::{base2ibig, fbig2base, fbig2ibig},
  55. };
  56. #[test]
  57. fn dashu_fbig2ibig() {
  58. let f =
  59. Float10::from_str_native("234234223.000").unwrap().with_precision(RADIX_BITS).value();
  60. let i: IBig = fbig2ibig(f);
  61. let sig = IBig::from(234234223);
  62. assert_eq!(i, sig);
  63. }
  64. /*
  65. #[test]
  66. fn dashu_test_base2ibig() {
  67. //
  68. let fbig: Float10 = Float10::from_str_native(
  69. "28948022309329048855892746252171976963363056481941560715954676764349967630337",
  70. )
  71. .unwrap()
  72. .with_precision(RADIX_BITS)
  73. .value();
  74. let ibig = fbig2ibig(fbig.clone());
  75. let res_base: pallas::Base = fbig2base(fbig.clone());
  76. let res_ibig: IBig = base2ibig(res_base);
  77. assert_eq!(res_ibig, ibig);
  78. }
  79. */
  80. }