Skip to content

randomUtxo / randomToken / randomNFT draw from only 10,000 values, so larger test setups get colliding outpoints and token categories #471

Open

Description

@mr-zwets

Summary

randomUtxo, randomToken and randomNFT draw their txids, token categories and NFT commitments from only 10,000 values. All three hash randomInt(), which is BigInt(Math.floor(Math.random() * 10000)).

That's plenty for a test with a handful of UTXOs. It isn't enough for larger test setups that hold many random UTXOs at once, such as a transaction with a hundred or more inputs, or a MockNetworkProvider filled with a whole protocol's state.

How often

  • Outpoints: 10,000 txids × a random vout from 0 to 9 gives 100,000 outpoints. With n random UTXOs, the chance that two share an outpoint is about 1 − e^(−n²/200,000):

    random UTXOs chance of a shared outpoint
    8 0.03%
    50 1.2%
    400 55%

    A shared outpoint fails the transaction with "the transaction attempts to spend the same outpoint in multiple inputs". MockNetworkProvider.addUtxo keeps both entries, so a spend can also be matched to the wrong one.

  • Token categories: only 10,000 values, with no vout to spread them, so ≈ 1 − e^(−n²/20,000): 2% for 20 random tokens, 12% for 50, 39% for 100. Two tokens meant to be different then share a category, which can make token-balance assertions wrong instead of failing clearly.

  • NFT commitments: the same 10,000 values, truncated to 4 bytes.

What we ran into

Our tests for a multi-contract protocol create many random UTXOs per test:

  • A test with eight random UTXOs failed intermittently, when one landed on another input's outpoint.
  • Merge tests with up to ~390 inputs failed the same way.
  • We had to write our own helper to avoid it.

Possible fix

Draw txids and categories from 32 random bytes, and commitments from 4, using crypto.getRandomValues. It's global in Node 19+ and browsers, and libauth's generateRandomBytesUnchecked already relies on it. The API stays the same, and satoshi and token amounts can keep using randomInt().

const randomBytesHex = (length: number): string => binToHex(crypto.getRandomValues(new Uint8Array(length)));

export const randomUtxo = <T extends Partial<Utxo>>(defaults?: T): Utxo & T => ({
  txid: randomBytesHex(32),
  vout: Math.floor(Math.random() * 10),
  satoshis: 100_000n + randomInt(),
  ...defaults,
} as Utxo & T);

randomToken and randomNFT would take category: randomBytesHex(32), and randomNFT would take commitment: randomBytesHex(4).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions