Skip to content

Commit

Permalink
fix: Add arbitrary for coinbase
Browse files Browse the repository at this point in the history
Function `NeptuneCoins::arbitrary_coinbase` returns an arbitrary
`Option<NeptuneCoins>` with a small, non-negative amount (if set).

This fixes failing test cases in `time_lock.rs`.

Co-authored-by: Alan Szepieniec <[email protected]>
  • Loading branch information
Sword-Smith and aszepieniec committed Dec 19, 2024
1 parent 9813c6b commit 1a30205
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ pub(crate) struct CoinbaseAmount;

const ILLEGAL_COINBASE_AMOUNT_ERROR: i128 = 1_000_200;

/// Map a pointer to a coinbase object to its amount (if some) or (if none)
/// zero.
impl BasicSnippet for CoinbaseAmount {
fn inputs(&self) -> Vec<(DataType, String)> {
vec![(DataType::VoidPointer, "*coinbase".to_owned())]
Expand Down Expand Up @@ -197,7 +199,10 @@ mod test {
let new_seed: [u8; 32] = rng.gen();

let mut u = Unstructured::new(&new_seed);
let coinbase: Option<NeptuneCoins> = u.arbitrary().unwrap();
let coinbase: Option<NeptuneCoins> = u
.arbitrary::<Option<NeptuneCoins>>()
.unwrap()
.map(|c| c.abs());
let coinbase_ptr: BFieldElement = rng.gen();

let mut memory = HashMap::default();
Expand Down
10 changes: 10 additions & 0 deletions src/models/blockchain/type_scripts/neptune_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,8 @@ impl Display for NeptuneCoins {
}

impl<'a> Arbitrary<'a> for NeptuneCoins {
/// Generate an arbitrary amount of NeptuneCoins that is small in absolute
/// value but can be negative.
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let nau: u128 = u.arbitrary()?;
Ok(NeptuneCoins((nau as i128) >> 10))
Expand All @@ -511,6 +513,14 @@ impl NeptuneCoins {
.prop_map(|uint| NeptuneCoins((uint >> 10) as i128))
.boxed()
}

/// Generate a strategy for an Option of NeptuneCoins, which if set will be
/// a small non-negative amount.
pub(crate) fn arbitrary_coinbase() -> BoxedStrategy<Option<Self>> {
arb::<Option<NeptuneCoins>>()
.prop_map(|coinbase| coinbase.map(|c| c.abs()))
.boxed()
}
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion src/models/blockchain/type_scripts/time_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,7 @@ impl Arbitrary for TimeLockWitness {
vec(arb::<Digest>(), num_outputs),
vec(NeptuneCoins::arbitrary_non_negative(), num_outputs),
vec(arb::<PublicAnnouncement>(), num_public_announcements),
arb::<Option<NeptuneCoins>>(),
NeptuneCoins::arbitrary_coinbase(),
NeptuneCoins::arbitrary_non_negative(),
)
.prop_flat_map(
Expand Down

0 comments on commit 1a30205

Please sign in to comment.