Struct cardano_serialization_lib::utils::BigInt
source · pub struct BigInt(_);
Implementations§
source§impl BigInt
impl BigInt
pub fn from_bytes(bytes: Vec<u8>) -> Result<BigInt, DeserializeError>
source§impl BigInt
impl BigInt
sourcepub fn is_zero(&self) -> bool
pub fn is_zero(&self) -> bool
Examples found in repository?
More examples
src/fees.rs (line 56)
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
fn sum(a: &Ratio, b: &Ratio) -> Ratio {
// Ratio Addition: a/x + b/y = ((a*y) + (b*x))/(x*y)
let (a_num, a_denum) = &a;
let (b_num, b_denum) = &b;
if a_num.is_zero() {
return b.clone();
}
if b_num.is_zero() {
return a.clone();
}
let a_num_fixed = &a_num.mul(b_denum);
let b_num_fixed = &b_num.mul(a_denum);
let a_b_num_sum = a_num_fixed.add(b_num_fixed);
let common_denum = a_denum.mul(b_denum);
(a_b_num_sum, common_denum)
}
sourcepub fn as_u64(&self) -> Option<BigNum>
pub fn as_u64(&self) -> Option<BigNum>
Examples found in repository?
src/fees.rs (line 71)
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
pub fn calculate_ex_units_ceil_cost(
ex_units: &ExUnits,
ex_unit_prices: &ExUnitPrices,
) -> Result<Coin, JsError> {
type Ratio = (BigInt, BigInt);
fn mult(sc: &SubCoin, x: &BigNum) -> Result<Ratio, JsError> {
let n: BigInt = BigInt::from_str(&sc.numerator.to_str())?;
let d: BigInt = BigInt::from_str(&sc.denominator.to_str())?;
let m: BigInt = BigInt::from_str(&x.to_str())?;
Ok((n.mul(&m), d))
}
fn sum(a: &Ratio, b: &Ratio) -> Ratio {
// Ratio Addition: a/x + b/y = ((a*y) + (b*x))/(x*y)
let (a_num, a_denum) = &a;
let (b_num, b_denum) = &b;
if a_num.is_zero() {
return b.clone();
}
if b_num.is_zero() {
return a.clone();
}
let a_num_fixed = &a_num.mul(b_denum);
let b_num_fixed = &b_num.mul(a_denum);
let a_b_num_sum = a_num_fixed.add(b_num_fixed);
let common_denum = a_denum.mul(b_denum);
(a_b_num_sum, common_denum)
}
let mem_ratio: Ratio = mult(&ex_unit_prices.mem_price(), &ex_units.mem())?;
let steps_ratio: Ratio = mult(&ex_unit_prices.step_price(), &ex_units.steps())?;
let (total_num, total_denum) = sum(&mem_ratio, &steps_ratio);
match total_num.div_ceil(&total_denum).as_u64() {
Some(coin) => Ok(coin),
_ => Err(JsError::from_str(&format!(
"Failed to calculate ceil from ratio {}/{}",
total_num.to_str(),
total_denum.to_str(),
))),
}
}
sourcepub fn as_int(&self) -> Option<Int>
pub fn as_int(&self) -> Option<Int>
Examples found in repository?
src/plutus.rs (line 1256)
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
pub fn decode_plutus_datum_to_json_value(
datum: &PlutusData,
schema: PlutusDatumSchema,
) -> Result<serde_json::Value, JsError> {
use serde_json::Value;
let (type_tag, json_value) = match &datum.datum {
PlutusDataEnum::ConstrPlutusData(constr) => {
let mut obj = serde_json::map::Map::with_capacity(2);
obj.insert(
String::from("constructor"),
Value::from(from_bignum(&constr.alternative))
);
let mut fields = Vec::new();
for field in constr.data.elems.iter() {
fields.push(decode_plutus_datum_to_json_value(field, schema)?);
}
obj.insert(
String::from("fields"),
Value::from(fields)
);
(None, Value::from(obj))
},
PlutusDataEnum::Map(map) => match schema {
PlutusDatumSchema::BasicConversions => (None, Value::from(map.0.iter().map(|(key, value)| {
let json_key: String = match &key.datum {
PlutusDataEnum::ConstrPlutusData(_) => Err(JsError::from_str("plutus data constructors are not allowed as keys in this schema. Use DetailedSchema.")),
PlutusDataEnum::Map(_) => Err(JsError::from_str("plutus maps are not allowed as keys in this schema. Use DetailedSchema.")),
PlutusDataEnum::List(_) => Err(JsError::from_str("plutus lists are not allowed as keys in this schema. Use DetailedSchema.")),
PlutusDataEnum::Integer(x) => Ok(x.to_str()),
PlutusDataEnum::Bytes(bytes) => String::from_utf8(bytes.clone()).or_else(|_err| Ok(format!("0x{}", hex::encode(bytes))))
}?;
let json_value = decode_plutus_datum_to_json_value(value, schema)?;
Ok((json_key, Value::from(json_value)))
}).collect::<Result<serde_json::map::Map<String, Value>, JsError>>()?)),
PlutusDatumSchema::DetailedSchema => (Some("map"), Value::from(map.0.iter().map(|(key, value)| {
let k = decode_plutus_datum_to_json_value(key, schema)?;
let v = decode_plutus_datum_to_json_value(value, schema)?;
let mut kv_obj = serde_json::map::Map::with_capacity(2);
kv_obj.insert(String::from("k"), k);
kv_obj.insert(String::from("v"), v);
Ok(Value::from(kv_obj))
}).collect::<Result<Vec<_>, JsError>>()?)),
},
PlutusDataEnum::List(list) => {
let mut elems = Vec::new();
for elem in list.elems.iter() {
elems.push(decode_plutus_datum_to_json_value(elem, schema)?);
}
(Some("list"), Value::from(elems))
},
PlutusDataEnum::Integer(bigint) => (
Some("int"),
bigint
.as_int()
.as_ref()
.map(|int| if int.0 >= 0 { Value::from(int.0 as u64) } else { Value::from(int.0 as i64) })
.ok_or_else(|| JsError::from_str(&format!("Integer {} too big for our JSON support", bigint.to_str())))?
),
PlutusDataEnum::Bytes(bytes) => (Some("bytes"), Value::from(match schema {
PlutusDatumSchema::BasicConversions => {
// cardano-cli converts to a string only if bytes are utf8 and all characters are printable
String::from_utf8(bytes.clone())
.ok()
.filter(|utf8| utf8.chars().all(|c| !c.is_control()))
// otherwise we hex-encode the bytes with a 0x prefix
.unwrap_or_else(|| format!("0x{}", hex::encode(bytes)))
},
PlutusDatumSchema::DetailedSchema => hex::encode(bytes),
})),
};
if type_tag.is_none() || schema != PlutusDatumSchema::DetailedSchema {
Ok(json_value)
} else {
let mut wrapper = serde_json::map::Map::with_capacity(1);
wrapper.insert(String::from(type_tag.unwrap()), json_value);
Ok(Value::from(wrapper))
}
}
sourcepub fn from_str(text: &str) -> Result<BigInt, JsError>
pub fn from_str(text: &str) -> Result<BigInt, JsError>
Examples found in repository?
src/utils.rs (line 355)
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
pub fn to_bigint(val: u64) -> BigInt {
BigInt::from_str(&val.to_string()).unwrap()
}
// Specifies an amount of ADA in terms of lovelace
pub type Coin = BigNum;
#[wasm_bindgen]
#[derive(
Clone,
Debug,
Eq,
/*Hash,*/ Ord,
PartialEq,
serde::Serialize,
serde::Deserialize,
JsonSchema,
)]
pub struct Value {
pub(crate) coin: Coin,
pub(crate) multiasset: Option<MultiAsset>,
}
impl_to_from!(Value);
#[wasm_bindgen]
impl Value {
pub fn new(coin: &Coin) -> Value {
Self {
coin: coin.clone(),
multiasset: None,
}
}
pub fn new_from_assets(multiasset: &MultiAsset) -> Value {
Value::new_with_assets(&Coin::zero(), multiasset)
}
pub fn new_with_assets(coin: &Coin, multiasset: &MultiAsset) -> Value {
match multiasset.0.is_empty() {
true => Value::new(coin),
false => Self {
coin: coin.clone(),
multiasset: Some(multiasset.clone()),
},
}
}
pub fn zero() -> Value {
Value::new(&Coin::zero())
}
pub fn is_zero(&self) -> bool {
self.coin.is_zero()
&& self
.multiasset
.as_ref()
.map(|m| m.len() == 0)
.unwrap_or(true)
}
pub fn coin(&self) -> Coin {
self.coin
}
pub fn set_coin(&mut self, coin: &Coin) {
self.coin = coin.clone();
}
pub fn multiasset(&self) -> Option<MultiAsset> {
self.multiasset.clone()
}
pub fn set_multiasset(&mut self, multiasset: &MultiAsset) {
self.multiasset = Some(multiasset.clone());
}
pub fn checked_add(&self, rhs: &Value) -> Result<Value, JsError> {
use std::collections::btree_map::Entry;
let coin = self.coin.checked_add(&rhs.coin)?;
let multiasset = match (&self.multiasset, &rhs.multiasset) {
(Some(lhs_multiasset), Some(rhs_multiasset)) => {
let mut multiasset = MultiAsset::new();
for ma in &[lhs_multiasset, rhs_multiasset] {
for (policy, assets) in &ma.0 {
for (asset_name, amount) in &assets.0 {
match multiasset.0.entry(policy.clone()) {
Entry::Occupied(mut assets) => {
match assets.get_mut().0.entry(asset_name.clone()) {
Entry::Occupied(mut assets) => {
let current = assets.get_mut();
*current = current.checked_add(&amount)?;
}
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(amount.clone());
}
}
}
Entry::Vacant(entry) => {
let mut assets = Assets::new();
assets.0.insert(asset_name.clone(), amount.clone());
entry.insert(assets);
}
}
}
}
}
Some(multiasset)
}
(None, None) => None,
(Some(ma), None) => Some(ma.clone()),
(None, Some(ma)) => Some(ma.clone()),
};
Ok(Value { coin, multiasset })
}
pub fn checked_sub(&self, rhs_value: &Value) -> Result<Value, JsError> {
let coin = self.coin.checked_sub(&rhs_value.coin)?;
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Ok(Value { coin, multiasset })
}
pub fn clamped_sub(&self, rhs_value: &Value) -> Value {
let coin = self.coin.clamped_sub(&rhs_value.coin);
let multiasset = match (&self.multiasset, &rhs_value.multiasset) {
(Some(lhs_ma), Some(rhs_ma)) => match lhs_ma.sub(rhs_ma).len() {
0 => None,
_ => Some(lhs_ma.sub(rhs_ma)),
},
(Some(lhs_ma), None) => Some(lhs_ma.clone()),
(None, Some(_rhs_ma)) => None,
(None, None) => None,
};
Value { coin, multiasset }
}
/// note: values are only partially comparable
pub fn compare(&self, rhs_value: &Value) -> Option<i8> {
match self.partial_cmp(&rhs_value) {
None => None,
Some(std::cmp::Ordering::Equal) => Some(0),
Some(std::cmp::Ordering::Less) => Some(-1),
Some(std::cmp::Ordering::Greater) => Some(1),
}
}
}
impl PartialOrd for Value {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
use std::cmp::Ordering::*;
fn compare_assets(
lhs: &Option<MultiAsset>,
rhs: &Option<MultiAsset>,
) -> Option<std::cmp::Ordering> {
match (lhs, rhs) {
(None, None) => Some(Equal),
(None, Some(rhs_assets)) => MultiAsset::new().partial_cmp(&rhs_assets),
(Some(lhs_assets), None) => lhs_assets.partial_cmp(&MultiAsset::new()),
(Some(lhs_assets), Some(rhs_assets)) => lhs_assets.partial_cmp(&rhs_assets),
}
}
compare_assets(&self.multiasset(), &other.multiasset()).and_then(|assets_match| {
let coin_cmp = self.coin.cmp(&other.coin);
match (coin_cmp, assets_match) {
(coin_order, Equal) => Some(coin_order),
(Equal, Less) => Some(Less),
(Less, Less) => Some(Less),
(Equal, Greater) => Some(Greater),
(Greater, Greater) => Some(Greater),
(_, _) => None,
}
})
}
}
impl cbor_event::se::Serialize for Value {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
match &self.multiasset {
Some(multiasset) => {
serializer.write_array(cbor_event::Len::Len(2))?;
self.coin.serialize(serializer)?;
multiasset.serialize(serializer)
}
None => self.coin.serialize(serializer),
}
}
}
impl Deserialize for Value {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
match raw.cbor_type()? {
cbor_event::Type::UnsignedInteger => Ok(Value::new(&Coin::deserialize(raw)?)),
cbor_event::Type::Array => {
let len = raw.array()?;
let coin =
(|| -> Result<_, DeserializeError> { Ok(Coin::deserialize(raw)?) })()
.map_err(|e| e.annotate("coin"))?;
let multiasset =
(|| -> Result<_, DeserializeError> { Ok(MultiAsset::deserialize(raw)?) })()
.map_err(|e| e.annotate("multiasset"))?;
let ret = Ok(Self {
coin,
multiasset: Some(multiasset),
});
match len {
cbor_event::Len::Len(n) => match n {
2 =>
/* it's ok */
{
()
}
n => {
return Err(
DeserializeFailure::DefiniteLenMismatch(n, Some(2)).into()
);
}
},
cbor_event::Len::Indefinite => match raw.special()? {
CBORSpecial::Break =>
/* it's ok */
{
()
}
_ => return Err(DeserializeFailure::EndingBreakMissing.into()),
},
}
ret
}
_ => Err(DeserializeFailure::NoVariantMatched.into()),
}
})()
.map_err(|e| e.annotate("Value"))
}
}
// CBOR has int = uint / nint
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Int(pub(crate) i128);
impl_to_from!(Int);
#[wasm_bindgen]
impl Int {
pub fn new(x: &BigNum) -> Self {
Self(x.0 as i128)
}
pub fn new_negative(x: &BigNum) -> Self {
Self(-(x.0 as i128))
}
pub fn new_i32(x: i32) -> Self {
Self(x as i128)
}
pub fn is_positive(&self) -> bool {
return self.0 >= 0;
}
/// BigNum can only contain unsigned u64 values
///
/// This function will return the BigNum representation
/// only in case the underlying i128 value is positive.
///
/// Otherwise nothing will be returned (undefined).
pub fn as_positive(&self) -> Option<BigNum> {
if self.is_positive() {
Some(to_bignum(self.0 as u64))
} else {
None
}
}
/// BigNum can only contain unsigned u64 values
///
/// This function will return the *absolute* BigNum representation
/// only in case the underlying i128 value is negative.
///
/// Otherwise nothing will be returned (undefined).
pub fn as_negative(&self) -> Option<BigNum> {
if !self.is_positive() {
Some(to_bignum((-self.0) as u64))
} else {
None
}
}
/// !!! DEPRECATED !!!
/// Returns an i32 value in case the underlying original i128 value is within the limits.
/// Otherwise will just return an empty value (undefined).
#[deprecated(
since = "10.0.0",
note = "Unsafe ignoring of possible boundary error and it's not clear from the function name. Use `as_i32_or_nothing`, `as_i32_or_fail`, or `to_str`"
)]
pub fn as_i32(&self) -> Option<i32> {
self.as_i32_or_nothing()
}
/// Returns the underlying value converted to i32 if possible (within limits)
/// Otherwise will just return an empty value (undefined).
pub fn as_i32_or_nothing(&self) -> Option<i32> {
use std::convert::TryFrom;
i32::try_from(self.0).ok()
}
/// Returns the underlying value converted to i32 if possible (within limits)
/// JsError in case of out of boundary overflow
pub fn as_i32_or_fail(&self) -> Result<i32, JsError> {
use std::convert::TryFrom;
i32::try_from(self.0).map_err(|e| JsError::from_str(&format!("{}", e)))
}
/// Returns string representation of the underlying i128 value directly.
/// Might contain the minus sign (-) in case of negative value.
pub fn to_str(&self) -> String {
format!("{}", self.0)
}
// Create an Int from a standard rust string representation
pub fn from_str(string: &str) -> Result<Int, JsError> {
let x = string
.parse::<i128>()
.map_err(|e| JsError::from_str(&format! {"{:?}", e}))?;
if x.abs() > u64::MAX as i128 {
return Err(JsError::from_str(&format!(
"{} out of bounds. Value (without sign) must fit within 4 bytes limit of {}",
x,
u64::MAX
)));
}
Ok(Self(x))
}
}
impl cbor_event::se::Serialize for Int {
fn serialize<'se, W: Write>(
&self,
serializer: &'se mut Serializer<W>,
) -> cbor_event::Result<&'se mut Serializer<W>> {
if self.0 < 0 {
serializer.write_negative_integer(self.0 as i64)
} else {
serializer.write_unsigned_integer(self.0 as u64)
}
}
}
impl Deserialize for Int {
fn deserialize<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<Self, DeserializeError> {
(|| -> Result<_, DeserializeError> {
match raw.cbor_type()? {
cbor_event::Type::UnsignedInteger => Ok(Self(raw.unsigned_integer()? as i128)),
cbor_event::Type::NegativeInteger => Ok(Self(read_nint(raw)?)),
_ => Err(DeserializeFailure::NoVariantMatched.into()),
}
})()
.map_err(|e| e.annotate("Int"))
}
}
impl serde::Serialize for Int {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_str())
}
}
impl<'de> serde::de::Deserialize<'de> for Int {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = <String as serde::de::Deserialize>::deserialize(deserializer)?;
Self::from_str(&s).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"string rep of a number",
)
})
}
}
impl JsonSchema for Int {
fn schema_name() -> String {
String::from("Int")
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
String::json_schema(gen)
}
fn is_referenceable() -> bool {
String::is_referenceable()
}
}
/// TODO: this function can be removed in case `cbor_event` library ever gets a fix on their side
/// See https://github.com/Emurgo/cardano-serialization-lib/pull/392
fn read_nint<R: BufRead + Seek>(raw: &mut Deserializer<R>) -> Result<i128, DeserializeError> {
let found = raw.cbor_type()?;
if found != cbor_event::Type::NegativeInteger {
return Err(cbor_event::Error::Expected(cbor_event::Type::NegativeInteger, found).into());
}
let (len, len_sz) = raw.cbor_len()?;
match len {
cbor_event::Len::Indefinite => Err(cbor_event::Error::IndefiniteLenNotSupported(
cbor_event::Type::NegativeInteger,
)
.into()),
cbor_event::Len::Len(v) => {
raw.advance(1 + len_sz)?;
Ok(-(v as i128) - 1)
}
}
}
const BOUNDED_BYTES_CHUNK_SIZE: usize = 64;
pub(crate) fn write_bounded_bytes<'se, W: Write>(
serializer: &'se mut Serializer<W>,
bytes: &[u8],
) -> cbor_event::Result<&'se mut Serializer<W>> {
if bytes.len() <= BOUNDED_BYTES_CHUNK_SIZE {
serializer.write_bytes(bytes)
} else {
// to get around not having access from outside the library we just write the raw CBOR indefinite byte string code here
serializer.write_raw_bytes(&[0x5f])?;
for chunk in bytes.chunks(BOUNDED_BYTES_CHUNK_SIZE) {
serializer.write_bytes(chunk)?;
}
serializer.write_special(CBORSpecial::Break)
}
}
pub(crate) fn read_bounded_bytes<R: BufRead + Seek>(
raw: &mut Deserializer<R>,
) -> Result<Vec<u8>, DeserializeError> {
use std::io::Read;
let t = raw.cbor_type()?;
if t != CBORType::Bytes {
return Err(cbor_event::Error::Expected(CBORType::Bytes, t).into());
}
let (len, len_sz) = raw.cbor_len()?;
match len {
cbor_event::Len::Len(_) => {
let bytes = raw.bytes()?;
if bytes.len() > BOUNDED_BYTES_CHUNK_SIZE {
return Err(DeserializeFailure::OutOfRange {
min: 0,
max: BOUNDED_BYTES_CHUNK_SIZE,
found: bytes.len(),
}
.into());
}
Ok(bytes)
}
cbor_event::Len::Indefinite => {
// this is CBOR indefinite encoding, but we must check that each chunk
// is at most 64 big so we can't just use cbor_event's implementation
// and check after the fact.
// This is a slightly adopted version of what I made internally in cbor_event
// but with the extra checks and not having access to non-pub methods.
let mut bytes = Vec::new();
raw.advance(1 + len_sz)?;
// TODO: also change this + check at end of loop to the following after we update cbor_event
//while raw.cbor_type()? != CBORType::Special || !raw.special_break()? {
while raw.cbor_type()? != CBORType::Special {
let chunk_t = raw.cbor_type()?;
if chunk_t != CBORType::Bytes {
return Err(cbor_event::Error::Expected(CBORType::Bytes, chunk_t).into());
}
let (chunk_len, chunk_len_sz) = raw.cbor_len()?;
match chunk_len {
// TODO: use this error instead once that PR is merged into cbor_event
//cbor_event::Len::Indefinite => return Err(cbor_event::Error::InvalidIndefiniteString.into()),
cbor_event::Len::Indefinite => {
return Err(cbor_event::Error::CustomError(String::from(
"Illegal CBOR: Indefinite string found inside indefinite string",
))
.into());
}
cbor_event::Len::Len(len) => {
if chunk_len_sz > BOUNDED_BYTES_CHUNK_SIZE {
return Err(DeserializeFailure::OutOfRange {
min: 0,
max: BOUNDED_BYTES_CHUNK_SIZE,
found: chunk_len_sz,
}
.into());
}
raw.advance(1 + chunk_len_sz)?;
raw.as_mut_ref()
.by_ref()
.take(len)
.read_to_end(&mut bytes)
.map_err(|e| cbor_event::Error::IoError(e))?;
}
}
}
if raw.special()? != CBORSpecial::Break {
return Err(DeserializeFailure::EndingBreakMissing.into());
}
Ok(bytes)
}
}
}
#[wasm_bindgen]
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct BigInt(num_bigint::BigInt);
impl_to_from!(BigInt);
impl serde::Serialize for BigInt {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_str())
}
}
impl<'de> serde::de::Deserialize<'de> for BigInt {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let s = <String as serde::de::Deserialize>::deserialize(deserializer)?;
BigInt::from_str(&s).map_err(|_e| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Str(&s),
&"string rep of a big int",
)
})
}
More examples
src/plutus.rs (line 1069)
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
fn encode_string(
s: &str,
schema: PlutusDatumSchema,
is_key: bool,
) -> Result<PlutusData, JsError> {
if schema == PlutusDatumSchema::BasicConversions {
if s.starts_with("0x") {
// this must be a valid hex bytestring after
hex::decode(&s[2..])
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|err| JsError::from_str(&format!("Error decoding {}: {}", s, err)))
} else if is_key {
// try as an integer
BigInt::from_str(s)
.map(|x| PlutusData::new_integer(&x))
// if not, we use the utf8 bytes of the string instead directly
.or_else(|_err| Ok(PlutusData::new_bytes(s.as_bytes().to_vec())))
} else {
// can only be UTF bytes if not in a key and not prefixed by 0x
Ok(PlutusData::new_bytes(s.as_bytes().to_vec()))
}
} else {
if s.starts_with("0x") {
Err(JsError::from_str("Hex byte strings in detailed schema should NOT start with 0x and should just contain the hex characters"))
} else {
hex::decode(s)
.map(|bytes| PlutusData::new_bytes(bytes))
.map_err(|e| JsError::from_str(&e.to_string()))
}
}
}
sourcepub fn to_str(&self) -> String
pub fn to_str(&self) -> String
Examples found in repository?
More examples
src/fees.rs (line 75)
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
pub fn calculate_ex_units_ceil_cost(
ex_units: &ExUnits,
ex_unit_prices: &ExUnitPrices,
) -> Result<Coin, JsError> {
type Ratio = (BigInt, BigInt);
fn mult(sc: &SubCoin, x: &BigNum) -> Result<Ratio, JsError> {
let n: BigInt = BigInt::from_str(&sc.numerator.to_str())?;
let d: BigInt = BigInt::from_str(&sc.denominator.to_str())?;
let m: BigInt = BigInt::from_str(&x.to_str())?;
Ok((n.mul(&m), d))
}
fn sum(a: &Ratio, b: &Ratio) -> Ratio {
// Ratio Addition: a/x + b/y = ((a*y) + (b*x))/(x*y)
let (a_num, a_denum) = &a;
let (b_num, b_denum) = &b;
if a_num.is_zero() {
return b.clone();
}
if b_num.is_zero() {
return a.clone();
}
let a_num_fixed = &a_num.mul(b_denum);
let b_num_fixed = &b_num.mul(a_denum);
let a_b_num_sum = a_num_fixed.add(b_num_fixed);
let common_denum = a_denum.mul(b_denum);
(a_b_num_sum, common_denum)
}
let mem_ratio: Ratio = mult(&ex_unit_prices.mem_price(), &ex_units.mem())?;
let steps_ratio: Ratio = mult(&ex_unit_prices.step_price(), &ex_units.steps())?;
let (total_num, total_denum) = sum(&mem_ratio, &steps_ratio);
match total_num.div_ceil(&total_denum).as_u64() {
Some(coin) => Ok(coin),
_ => Err(JsError::from_str(&format!(
"Failed to calculate ceil from ratio {}/{}",
total_num.to_str(),
total_denum.to_str(),
))),
}
}
src/plutus.rs (line 1231)
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
pub fn decode_plutus_datum_to_json_value(
datum: &PlutusData,
schema: PlutusDatumSchema,
) -> Result<serde_json::Value, JsError> {
use serde_json::Value;
let (type_tag, json_value) = match &datum.datum {
PlutusDataEnum::ConstrPlutusData(constr) => {
let mut obj = serde_json::map::Map::with_capacity(2);
obj.insert(
String::from("constructor"),
Value::from(from_bignum(&constr.alternative))
);
let mut fields = Vec::new();
for field in constr.data.elems.iter() {
fields.push(decode_plutus_datum_to_json_value(field, schema)?);
}
obj.insert(
String::from("fields"),
Value::from(fields)
);
(None, Value::from(obj))
},
PlutusDataEnum::Map(map) => match schema {
PlutusDatumSchema::BasicConversions => (None, Value::from(map.0.iter().map(|(key, value)| {
let json_key: String = match &key.datum {
PlutusDataEnum::ConstrPlutusData(_) => Err(JsError::from_str("plutus data constructors are not allowed as keys in this schema. Use DetailedSchema.")),
PlutusDataEnum::Map(_) => Err(JsError::from_str("plutus maps are not allowed as keys in this schema. Use DetailedSchema.")),
PlutusDataEnum::List(_) => Err(JsError::from_str("plutus lists are not allowed as keys in this schema. Use DetailedSchema.")),
PlutusDataEnum::Integer(x) => Ok(x.to_str()),
PlutusDataEnum::Bytes(bytes) => String::from_utf8(bytes.clone()).or_else(|_err| Ok(format!("0x{}", hex::encode(bytes))))
}?;
let json_value = decode_plutus_datum_to_json_value(value, schema)?;
Ok((json_key, Value::from(json_value)))
}).collect::<Result<serde_json::map::Map<String, Value>, JsError>>()?)),
PlutusDatumSchema::DetailedSchema => (Some("map"), Value::from(map.0.iter().map(|(key, value)| {
let k = decode_plutus_datum_to_json_value(key, schema)?;
let v = decode_plutus_datum_to_json_value(value, schema)?;
let mut kv_obj = serde_json::map::Map::with_capacity(2);
kv_obj.insert(String::from("k"), k);
kv_obj.insert(String::from("v"), v);
Ok(Value::from(kv_obj))
}).collect::<Result<Vec<_>, JsError>>()?)),
},
PlutusDataEnum::List(list) => {
let mut elems = Vec::new();
for elem in list.elems.iter() {
elems.push(decode_plutus_datum_to_json_value(elem, schema)?);
}
(Some("list"), Value::from(elems))
},
PlutusDataEnum::Integer(bigint) => (
Some("int"),
bigint
.as_int()
.as_ref()
.map(|int| if int.0 >= 0 { Value::from(int.0 as u64) } else { Value::from(int.0 as i64) })
.ok_or_else(|| JsError::from_str(&format!("Integer {} too big for our JSON support", bigint.to_str())))?
),
PlutusDataEnum::Bytes(bytes) => (Some("bytes"), Value::from(match schema {
PlutusDatumSchema::BasicConversions => {
// cardano-cli converts to a string only if bytes are utf8 and all characters are printable
String::from_utf8(bytes.clone())
.ok()
.filter(|utf8| utf8.chars().all(|c| !c.is_control()))
// otherwise we hex-encode the bytes with a 0x prefix
.unwrap_or_else(|| format!("0x{}", hex::encode(bytes)))
},
PlutusDatumSchema::DetailedSchema => hex::encode(bytes),
})),
};
if type_tag.is_none() || schema != PlutusDatumSchema::DetailedSchema {
Ok(json_value)
} else {
let mut wrapper = serde_json::map::Map::with_capacity(1);
wrapper.insert(String::from(type_tag.unwrap()), json_value);
Ok(Value::from(wrapper))
}
}
sourcepub fn add(&self, other: &BigInt) -> BigInt
pub fn add(&self, other: &BigInt) -> BigInt
Examples found in repository?
More examples
src/fees.rs (line 64)
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
fn sum(a: &Ratio, b: &Ratio) -> Ratio {
// Ratio Addition: a/x + b/y = ((a*y) + (b*x))/(x*y)
let (a_num, a_denum) = &a;
let (b_num, b_denum) = &b;
if a_num.is_zero() {
return b.clone();
}
if b_num.is_zero() {
return a.clone();
}
let a_num_fixed = &a_num.mul(b_denum);
let b_num_fixed = &b_num.mul(a_denum);
let a_b_num_sum = a_num_fixed.add(b_num_fixed);
let common_denum = a_denum.mul(b_denum);
(a_b_num_sum, common_denum)
}
sourcepub fn mul(&self, other: &BigInt) -> BigInt
pub fn mul(&self, other: &BigInt) -> BigInt
Examples found in repository?
src/fees.rs (line 50)
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
fn mult(sc: &SubCoin, x: &BigNum) -> Result<Ratio, JsError> {
let n: BigInt = BigInt::from_str(&sc.numerator.to_str())?;
let d: BigInt = BigInt::from_str(&sc.denominator.to_str())?;
let m: BigInt = BigInt::from_str(&x.to_str())?;
Ok((n.mul(&m), d))
}
fn sum(a: &Ratio, b: &Ratio) -> Ratio {
// Ratio Addition: a/x + b/y = ((a*y) + (b*x))/(x*y)
let (a_num, a_denum) = &a;
let (b_num, b_denum) = &b;
if a_num.is_zero() {
return b.clone();
}
if b_num.is_zero() {
return a.clone();
}
let a_num_fixed = &a_num.mul(b_denum);
let b_num_fixed = &b_num.mul(a_denum);
let a_b_num_sum = a_num_fixed.add(b_num_fixed);
let common_denum = a_denum.mul(b_denum);
(a_b_num_sum, common_denum)
}
sourcepub fn div_ceil(&self, other: &BigInt) -> BigInt
pub fn div_ceil(&self, other: &BigInt) -> BigInt
Examples found in repository?
src/fees.rs (line 71)
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
pub fn calculate_ex_units_ceil_cost(
ex_units: &ExUnits,
ex_unit_prices: &ExUnitPrices,
) -> Result<Coin, JsError> {
type Ratio = (BigInt, BigInt);
fn mult(sc: &SubCoin, x: &BigNum) -> Result<Ratio, JsError> {
let n: BigInt = BigInt::from_str(&sc.numerator.to_str())?;
let d: BigInt = BigInt::from_str(&sc.denominator.to_str())?;
let m: BigInt = BigInt::from_str(&x.to_str())?;
Ok((n.mul(&m), d))
}
fn sum(a: &Ratio, b: &Ratio) -> Ratio {
// Ratio Addition: a/x + b/y = ((a*y) + (b*x))/(x*y)
let (a_num, a_denum) = &a;
let (b_num, b_denum) = &b;
if a_num.is_zero() {
return b.clone();
}
if b_num.is_zero() {
return a.clone();
}
let a_num_fixed = &a_num.mul(b_denum);
let b_num_fixed = &b_num.mul(a_denum);
let a_b_num_sum = a_num_fixed.add(b_num_fixed);
let common_denum = a_denum.mul(b_denum);
(a_b_num_sum, common_denum)
}
let mem_ratio: Ratio = mult(&ex_unit_prices.mem_price(), &ex_units.mem())?;
let steps_ratio: Ratio = mult(&ex_unit_prices.step_price(), &ex_units.steps())?;
let (total_num, total_denum) = sum(&mem_ratio, &steps_ratio);
match total_num.div_ceil(&total_denum).as_u64() {
Some(coin) => Ok(coin),
_ => Err(JsError::from_str(&format!(
"Failed to calculate ceil from ratio {}/{}",
total_num.to_str(),
total_denum.to_str(),
))),
}
}
Trait Implementations§
source§impl<'de> Deserialize<'de> for BigInt
impl<'de> Deserialize<'de> for BigInt
source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl Deserialize for BigInt
impl Deserialize for BigInt
fn deserialize<R: BufRead + Seek>(
raw: &mut Deserializer<R>
) -> Result<Self, DeserializeError>
source§impl JsonSchema for BigInt
impl JsonSchema for BigInt
source§fn schema_name() -> String
fn schema_name() -> String
The name of the generated JSON Schema. Read more
source§fn json_schema(gen: &mut SchemaGenerator) -> Schema
fn json_schema(gen: &mut SchemaGenerator) -> Schema
Generates a JSON Schema for this type. Read more
source§fn is_referenceable() -> bool
fn is_referenceable() -> bool
Whether JSON Schemas generated for this type should be re-used where possible using the
$ref
keyword. Read moresource§impl Ord for BigInt
impl Ord for BigInt
source§impl PartialEq<BigInt> for BigInt
impl PartialEq<BigInt> for BigInt
source§impl PartialOrd<BigInt> for BigInt
impl PartialOrd<BigInt> for BigInt
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read more