fix(codec): Fix flat encoding and decoding of arbitrarily size integers (#378)

This commits fixes the flat encoding and decoding (and consequently,
  the zigzag) for large integers in the following ways:

  - It removes support for encoding and decoding i128 values.

  - It optionally (feature = "num-bigint") introduces encoding and
    decoding of large sized integers through the num-bigint::BigInt
    type.

  Without the feature enabled, it is still possible to encode and decode
  isize values; but the use of i128 is now prohibited (as it would
  overflow on boundaries) in favor of arbitrarily sized integers.

  The commit also introduces a missing property roundtrip for encoding
  and decoding large integers, which was missing and thus, failed to
  identify the overflow problem.

  See related issue: https://github.com/aiken-lang/aiken/issues/796
This commit is contained in:
Matthias Benkort 2024-01-13 14:09:16 +01:00 committed by GitHub
parent 0c026ef4c9
commit 0b1e5f0231
8 changed files with 133 additions and 54 deletions

View file

@ -8,6 +8,37 @@ prop_compose! {
}
}
#[cfg(feature = "num-bigint")]
mod bigint {
use super::arb_big_vec;
use num_bigint::{BigInt, Sign};
use pallas_codec::flat::{decode, encode};
use proptest::prelude::*;
prop_compose! {
fn arb_isize()(i: isize) -> BigInt {
i.into()
}
}
fn arb_bigint() -> impl Strategy<Value = BigInt> {
prop_oneof![
arb_isize(),
arb_big_vec().prop_map(|xs| BigInt::from_bytes_be(Sign::Plus, &xs)),
arb_big_vec().prop_map(|xs| BigInt::from_bytes_be(Sign::Minus, &xs))
]
}
proptest! {
#[test]
fn encode_bigint(x in arb_bigint()) {
let bytes = encode(&x).unwrap();
let decoded: BigInt = decode(&bytes).unwrap();
assert_eq!(decoded, x);
}
}
}
#[test]
fn encode_bool() {
let bytes = encode(&true).unwrap();

View file

@ -1,18 +1,18 @@
use pallas_codec::flat::zigzag::{to_isize, to_usize};
use pallas_codec::flat::zigzag::ZigZag;
use proptest::prelude::*;
proptest! {
#[test]
fn zigzag(i: isize) {
let u = to_usize(i);
let converted_i = to_isize(u);
let u = i.zigzag();
let converted_i = u.zigzag();
assert_eq!(converted_i, i);
}
#[test]
fn zagzig(u: usize) {
let i = to_isize(u);
let converted_u = to_usize(i);
let i = u.zigzag();
let converted_u = i.zigzag();
assert_eq!(converted_u, u);
}
}