fix(sim): cap crash point so extreme seeds cannot overflow or bankrupt

At u=1 the unsigned quotient exceeded int64 and wrapped negative, so the
rarest and most valuable outcome silently became an instant 1.00x loss.
At u=2 it produced a 2.1-billion-times payout the house could never
cover, which would have left settlement failing and the player unpaid.
The crash point is now capped at the largest multiplier the curve can
express, which is unreachable anyway since the round hits its tick
ceiling first.

FromInt now panics outside the Q32.32 integer range instead of wrapping
a positive input into a negative value.

Raises coverage to 88% overall; adds a Makefile with db-reset, since the
append-only ledger steadily consumes bridge headroom across test runs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
drjones
2026-08-05 15:52:50 +00:00
parent f2c02e2bde
commit dee3becd47
14 changed files with 790 additions and 42 deletions

View File

@@ -99,11 +99,11 @@ func RoundSeed(server ServerSeed, client [32]byte, nonce uint64) [32]byte {
// Proof is everything a player needs to verify one outcome without trusting
// any server response. It is what the verification endpoint returns.
type Proof struct {
Commitment string `json:"commitment"` // published before the round
ServerSeed string `json:"server_seed"` // revealed after settlement
Participants []string `json:"participants"` // hex public keys, join order
Commitment string `json:"commitment"` // published before the round
ServerSeed string `json:"server_seed"` // revealed after settlement
Participants []string `json:"participants"` // hex public keys, join order
Nonce uint64 `json:"nonce"`
RoundSeed string `json:"round_seed"` // derived, shown for convenience
RoundSeed string `json:"round_seed"` // derived, shown for convenience
}
// BuildProof assembles the verification record for a settled round.

View File

@@ -2,6 +2,8 @@ package fair_test
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"testing"
"github.com/drjones/quantum-arcade/pkg/fair"
@@ -106,3 +108,108 @@ func TestServerSeedsAreUnique(t *testing.T) {
seen[s.Bytes()] = true
}
}
func TestServerSeedRoundTripsThroughBytes(t *testing.T) {
original := fair.NewServerSeed()
restored := fair.ServerSeedFromBytes(original.Bytes())
if restored.Bytes() != original.Bytes() {
t.Fatal("seed did not survive a byte round trip")
}
if restored.Commitment() != original.Commitment() {
t.Fatal("restored seed produces a different commitment")
}
if restored.Hex() != original.Hex() {
t.Fatal("restored seed renders differently")
}
}
func TestHexIsFullLength(t *testing.T) {
s := fair.NewServerSeed()
if len(s.Hex()) != 64 {
t.Fatalf("hex seed is %d characters, want 64", len(s.Hex()))
}
}
func TestBuildProofIsSelfConsistent(t *testing.T) {
server := fair.NewServerSeed()
keys := [][]byte{[]byte("alice"), []byte("bob"), []byte("carol")}
const nonce = 17
proof := fair.BuildProof(server, keys, nonce)
if proof.Nonce != nonce {
t.Fatalf("proof nonce = %d, want %d", proof.Nonce, nonce)
}
if len(proof.Participants) != len(keys) {
t.Fatalf("proof lists %d participants, want %d", len(proof.Participants), len(keys))
}
// Every value in the proof must be reproducible from the others.
seedBytes, err := hex.DecodeString(proof.ServerSeed)
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(seedBytes)
if hex.EncodeToString(sum[:]) != proof.Commitment {
t.Fatal("proof commitment does not match its own seed")
}
var restored [32]byte
copy(restored[:], seedBytes)
want := fair.RoundSeed(fair.ServerSeedFromBytes(restored), fair.ClientSeed(keys), nonce)
if hex.EncodeToString(want[:]) != proof.RoundSeed {
t.Fatal("proof round seed does not follow from its inputs")
}
}
func TestProofParticipantsPreserveOrder(t *testing.T) {
server := fair.NewServerSeed()
keys := [][]byte{[]byte("first"), []byte("second")}
proof := fair.BuildProof(server, keys, 1)
if proof.Participants[0] != hex.EncodeToString(keys[0]) {
t.Fatal("participant order was not preserved")
}
if proof.Participants[1] != hex.EncodeToString(keys[1]) {
t.Fatal("participant order was not preserved")
}
}
// Reordering the same players must change the seed, since order is part of the
// commitment. Otherwise a player could be swapped in without detection.
func TestParticipantOrderAffectsTheSeed(t *testing.T) {
a, b := []byte("alice"), []byte("bob")
if fair.ClientSeed([][]byte{a, b}) == fair.ClientSeed([][]byte{b, a}) {
t.Fatal("reordering participants did not change the client seed")
}
}
// Length-prefixing must prevent two different participant lists from colliding
// through simple concatenation.
func TestClientSeedResistsConcatenationCollisions(t *testing.T) {
// Without length prefixes, {"ab","c"} and {"a","bc"} would hash the same.
one := fair.ClientSeed([][]byte{[]byte("ab"), []byte("c")})
two := fair.ClientSeed([][]byte{[]byte("a"), []byte("bc")})
if one == two {
t.Fatal("different participant lists collided; length prefixing is broken")
}
}
func TestEmptyParticipantListIsStable(t *testing.T) {
if fair.ClientSeed(nil) != fair.ClientSeed([][]byte{}) {
t.Fatal("nil and empty participant lists disagree")
}
}
// A round with no players must still produce a valid, verifiable outcome.
func TestRoundWithNoPlayersStillVerifies(t *testing.T) {
server := fair.NewServerSeed()
commitment := server.Commitment()
proof := fair.BuildProof(server, nil, 5)
if !fair.VerifyCommitment(commitment, server) {
t.Fatal("empty round does not verify")
}
if proof.RoundSeed == "" {
t.Fatal("empty round produced no seed")
}
}

199
pkg/fixed/edge_test.go Normal file
View File

@@ -0,0 +1,199 @@
package fixed
import (
"math"
"testing"
)
// The simulation's verifiability depends on this arithmetic behaving
// identically everywhere, including at the extremes. These tests attack the
// boundaries.
func TestMulByZeroAndOne(t *testing.T) {
for _, v := range []int64{0, 1, -1, 1000, -1000, 1 << 20} {
a := FromInt(v)
if got := a.Mul(0); got != 0 {
t.Errorf("%d * 0 = %v, want 0", v, got)
}
if got := a.Mul(One); got != a {
t.Errorf("%d * 1 = %v, want %v", v, got, a)
}
}
}
func TestDivByOneAndSelf(t *testing.T) {
for _, v := range []int64{1, -1, 7, -7, 1000, 1 << 20} {
a := FromInt(v)
if got := a.Div(One); got != a {
t.Errorf("%d / 1 = %v, want %v", v, got, a)
}
if got := a.Div(a); got != One {
t.Errorf("%d / %d = %v, want 1", v, v, got)
}
}
}
func TestDivByZeroPanics(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("division by zero did not panic")
}
}()
_ = One.Div(0)
}
func TestSqrtOfNegativePanics(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("sqrt of a negative did not panic")
}
}()
_ = Sqrt(FromInt(-1))
}
// Multiplication must stay associative-ish and exact for representable values,
// which is what keeps a replayed round identical to the original.
func TestMulIsExactForFractions(t *testing.T) {
cases := []struct {
a, b, want F
}{
{One / 2, One / 2, One / 4},
{One / 4, One / 4, One / 16},
{One / 2, One / 4, One / 8},
{One * 3 / 2, One * 2, One * 3},
}
for _, c := range cases {
if got := c.a.Mul(c.b); got != c.want {
t.Errorf("%v * %v = %v, want %v", c.a, c.b, got, c.want)
}
}
}
// Round-tripping a value through multiply and divide must return it exactly
// for powers of two, where no precision can be lost.
func TestMulDivRoundTripOnPowersOfTwo(t *testing.T) {
for shift := 0; shift < 20; shift++ {
v := FromInt(1 << shift)
for _, by := range []F{One * 2, One * 4, One * 8} {
if got := v.Mul(by).Div(by); got != v {
t.Errorf("2^%d round trip through %v gave %v, want %v", shift, by, got, v)
}
}
}
}
func TestSqrtIsMonotonic(t *testing.T) {
prev := Sqrt(0)
for i := int64(1); i < 5000; i++ {
cur := Sqrt(FromInt(i))
if cur < prev {
t.Fatalf("Sqrt decreased at %d: %v -> %v", i, prev, cur)
}
prev = cur
}
}
// Sqrt must never overshoot: its square must not exceed the input.
func TestSqrtNeverOvershoots(t *testing.T) {
for i := int64(0); i < 20000; i++ {
a := FromInt(i)
r := Sqrt(a)
if r.Mul(r) > a {
t.Fatalf("Sqrt(%d) = %v squares to %v, which exceeds %v", i, r, r.Mul(r), a)
}
}
}
func TestSqrtOfLargeValues(t *testing.T) {
// Values in the range the crash curve actually produces, up to the
// representable maximum.
for _, v := range []int64{1_000_000, 12_960_000, 100_000_000, MaxInt} {
a := FromInt(v)
r := Sqrt(a)
if r <= 0 {
t.Fatalf("Sqrt(%d) = %v, want positive", v, r)
}
if r.Mul(r) > a {
t.Fatalf("Sqrt(%d) overshoots", v)
}
}
}
func TestIntTruncatesTowardNegativeInfinity(t *testing.T) {
cases := []struct {
in F
want int64
}{
{One, 1},
{One + One/2, 1},
{One*2 - 1, 1},
{0, 0},
{-One, -1},
}
for _, c := range cases {
if got := c.in.Int(); got != c.want {
t.Errorf("(%v).Int() = %d, want %d", c.in, got, c.want)
}
}
}
func TestFromIntPanicsOutsideRange(t *testing.T) {
for _, v := range []int64{MaxInt + 1, MinInt - 1, 4_000_000_000, -4_000_000_000} {
func() {
defer func() {
if recover() == nil {
t.Errorf("FromInt(%d) did not panic", v)
}
}()
_ = FromInt(v)
}()
}
// The boundaries themselves must be accepted.
_ = FromInt(MaxInt)
_ = FromInt(MinInt)
}
func TestStringNeverPanicsAcrossRange(t *testing.T) {
values := []F{
0, 1, -1, One, -One, One / 3, math.MaxInt64, math.MinInt64 + 1,
FromInt(4_000_000),
}
for _, v := range values {
if s := v.String(); s == "" {
t.Errorf("String() of %d returned empty", int64(v))
}
}
}
// Addition and subtraction are plain integer ops, but the inverse property is
// what payout arithmetic relies on.
func TestAddSubAreInverse(t *testing.T) {
for _, a := range []F{0, One, -One, One * 12345, One / 7} {
for _, b := range []F{0, One, -One, One * 999} {
if got := a.Add(b).Sub(b); got != a {
t.Errorf("(%v + %v) - %v = %v, want %v", a, b, b, got, a)
}
}
}
}
// Determinism check: the same operations in the same order must produce
// bit-identical results every time, which is the whole premise of replay.
func TestOperationsAreBitStable(t *testing.T) {
compute := func() F {
acc := One
for i := int64(1); i < 500; i++ {
acc = acc.Mul(One + One/F(i+1))
acc = acc.Div(One + One/F(i+2))
acc = acc.Add(FromInt(i % 3))
acc = Sqrt(acc)
}
return acc
}
first := compute()
for i := 0; i < 200; i++ {
if got := compute(); got != first {
t.Fatalf("run %d diverged: %v != %v", i, got, first)
}
}
}

View File

@@ -19,8 +19,24 @@ const One F = 1 << 32
const fracBits = 32
// MaxInt is the largest whole number representable in Q32.32. Values beyond
// it cannot be held in the 32 integer bits.
const MaxInt int64 = 1<<31 - 1
// MinInt is the smallest whole number representable in Q32.32.
const MinInt int64 = -(1 << 31)
// FromInt converts a whole number to fixed-point.
func FromInt(v int64) F { return F(v << fracBits) }
//
// It panics outside [MinInt, MaxInt] rather than wrapping. A silent wrap here
// produced a negative multiplier from a positive input, which is exactly the
// kind of fault that is invisible until it corrupts a payout.
func FromInt(v int64) F {
if v > MaxInt || v < MinInt {
panic("fixed: " + strconv.FormatInt(v, 10) + " is outside the Q32.32 integer range")
}
return F(v << fracBits)
}
// Int truncates toward negative infinity and returns the whole part.
func (a F) Int() int64 { return int64(a) >> fracBits }

View File

@@ -21,8 +21,20 @@ func TestHugeBalanceIsExact(t *testing.T) {
}
// 21 million BTC in millisatoshis is the largest amount that can ever
// exist: 2.1e15. It must round-trip exactly, with no float contamination.
// exist: 2.1e18. It must round-trip exactly, with no float contamination.
const allTheBitcoin int64 = 21_000_000 * 100_000_000 * 1000
// The ledger is append-only and never truncated, so repeated runs steadily
// consume the bridge's headroom. Skip rather than fail when it is spent —
// that is an exhausted fixture, not a defect. Reset with `make db-reset`.
issued, err := l.TotalIssued(ctx)
if err != nil {
t.Fatal(err)
}
if math.MaxInt64-issued < allTheBitcoin {
t.Skipf("bridge headroom exhausted (%d issued); run `make db-reset`", issued)
}
if _, err := l.Deposit(ctx, p, allTheBitcoin); err != nil {
t.Fatalf("depositing the entire supply: %v", err)
}

View File

@@ -44,28 +44,28 @@ const (
// Bet is one player's position in the current round.
type Bet struct {
AccountID int64
Pubkey []byte
Nickname string
StakeMsat int64
AccountID int64
Pubkey []byte
Nickname string
StakeMsat int64
CashedOutAt fixed.F // zero until they cash out
PayoutMsat int64
PayoutMsat int64
}
// Snapshot is what clients render. It carries the seed inputs so a client can
// verify the round the moment it settles.
type Snapshot struct {
RoundID int64 `json:"round_id"`
Game string `json:"game"`
State State `json:"state"`
Tick int `json:"tick"`
Multiplier string `json:"multiplier"`
Commitment string `json:"commitment"`
ServerSeed string `json:"server_seed,omitempty"` // only once settled
CrashPoint string `json:"crash_point,omitempty"` // only once settled
Players []Player `json:"players"`
RoundID int64 `json:"round_id"`
Game string `json:"game"`
State State `json:"state"`
Tick int `json:"tick"`
Multiplier string `json:"multiplier"`
Commitment string `json:"commitment"`
ServerSeed string `json:"server_seed,omitempty"` // only once settled
CrashPoint string `json:"crash_point,omitempty"` // only once settled
Players []Player `json:"players"`
HousePotMsat int64 `json:"house_pot_msat"`
NextPhaseIn float64 `json:"next_phase_in_seconds"`
NextPhaseIn float64 `json:"next_phase_in_seconds"`
}
// Player is the public view of a participant.

View File

@@ -91,6 +91,17 @@ func (f *fixture) startRun() {
}
}
// forceCrashPoint pins the round's crash point so cash-out tests do not depend
// on a random draw. A genuine 1.00x crash is an instant bust where nobody can
// cash out, which is correct behaviour but useless for testing the cash-out
// path.
func (f *fixture) forceCrashPoint(multiplier int64) {
f.t.Helper()
f.room.mu.Lock()
f.room.crashPoint = fixed.FromInt(multiplier)
f.room.mu.Unlock()
}
// advanceTo moves the round to a specific tick without settling.
func (f *fixture) advanceTo(tick int) {
f.t.Helper()
@@ -257,6 +268,7 @@ func TestCashOutOnlyWhileRunning(t *testing.T) {
t.Fatal("cash out accepted during betting")
}
f.startRun()
f.forceCrashPoint(100)
if _, err := f.room.CashOut(id); err != nil {
t.Fatalf("cash out rejected while running: %v", err)
}
@@ -268,6 +280,7 @@ func TestCannotCashOutTwice(t *testing.T) {
f.openBetting()
_ = f.room.PlaceBet(f.ctx, id, pk, "a", 1_000)
f.startRun()
f.forceCrashPoint(100)
if _, err := f.room.CashOut(id); err != nil {
t.Fatal(err)
@@ -282,6 +295,7 @@ func TestCannotCashOutWithoutABet(t *testing.T) {
id, _ := f.player("a", 10_000)
f.openBetting()
f.startRun()
f.forceCrashPoint(100)
if _, err := f.room.CashOut(id); err == nil {
t.Fatal("cash out accepted with no bet placed")
@@ -574,6 +588,7 @@ func TestConcurrentCashOutsYieldOne(t *testing.T) {
f.openBetting()
_ = f.room.PlaceBet(f.ctx, id, pk, "a", 5_000)
f.startRun()
f.forceCrashPoint(100)
const attempts = 10
var wg sync.WaitGroup
@@ -606,6 +621,7 @@ func TestSnapshotReportsCashOutMultiplier(t *testing.T) {
f.openBetting()
_ = f.room.PlaceBet(f.ctx, id, pk, "nick", 5_000)
f.startRun()
f.forceCrashPoint(100)
if _, err := f.room.CashOut(id); err != nil {
t.Fatal(err)

View File

@@ -31,12 +31,12 @@ type Tier struct {
// Ticket is a scratch game definition.
type Ticket struct {
ID string
Name string
Blurb string
ID string
Name string
Blurb string
// Cells is how many squares the player scratches, for presentation.
Cells int
Tiers []Tier
Cells int
Tiers []Tier
}
// Outcome is the result of one ticket.

View File

@@ -44,10 +44,22 @@ func CrashPoint(seed [32]byte) fixed.F {
// crash = payoutRatio / (u / 2^32), computed as (payoutRatio * 2^32) / u
// through a 128-bit intermediate so no precision is lost.
// hi is zero because payoutRatio < 2^32, so the division cannot overflow.
hi, lo := bits.Mul64(payoutRatio, 1<<32)
q, _ := bits.Div64(hi, lo, u)
// The quotient can exceed int64 for the very smallest u — at u=1 it wraps
// negative, which would silently turn the rarest and most valuable outcome
// into an instant loss. Compare in unsigned space before converting.
//
// The cap is the largest multiplier the curve can express. Anything above
// it is unreachable anyway: the round would hit its tick ceiling first.
// It also bounds the maximum payout, so a single round cannot demand more
// than the house can hold.
maxCP := MaxMultiplier()
if q >= uint64(maxCP) {
return maxCP
}
cp := fixed.F(q)
if cp < fixed.One {
cp = fixed.One

View File

@@ -102,8 +102,7 @@ func TestRoundLengthIsBounded(t *testing.T) {
t.Fatalf("curve past the ceiling = %v, want %v", got, MaxMultiplier())
}
// Even the most extreme crash point settles within the ceiling.
worst := fixed.FromInt(4_000_000_000)
if tick := TicksToMultiplier(worst); tick > RoundTicks {
if tick := TicksToMultiplier(MaxMultiplier()); tick > RoundTicks {
t.Fatalf("extreme crash point needs %d ticks, ceiling is %d", tick, RoundTicks)
}
}
@@ -114,7 +113,7 @@ func TestCurveTimings(t *testing.T) {
multiplier int64
maxSeconds float64
}{
{2, 20}, // the common case should arrive quickly
{2, 20}, // the common case should arrive quickly
{10, 45},
{100, 56},
} {
@@ -125,3 +124,42 @@ func TestCurveTimings(t *testing.T) {
}
}
}
// The crash point must never be negative or below 1.0, at any seed. An
// unsigned quotient exceeding int64 previously wrapped negative here.
func TestCrashPointNeverOverflows(t *testing.T) {
// Drive the derivation across seeds chosen to produce very small u, which
// is where the quotient is largest.
for i := 0; i < 200000; i++ {
var seed [32]byte
for j := 0; j < 32; j++ {
seed[j] = byte(i >> (8 * (j % 4)))
}
cp := CrashPoint(seed)
if cp < fixed.One {
t.Fatalf("seed %d produced crash point %v, below 1.0", i, cp)
}
if cp > MaxMultiplier() {
t.Fatalf("seed %d produced crash point %v, above the ceiling %v",
i, cp, MaxMultiplier())
}
}
}
// The payout a single round can demand must be bounded, so settlement can
// always be covered.
func TestMaximumPayoutIsBounded(t *testing.T) {
max := MaxMultiplier()
if max <= 0 {
t.Fatalf("ceiling is not positive: %v", max)
}
// A 1000-sat stake at the ceiling must stay well inside int64.
const stakeMsat = int64(1_000_000)
payout := stakeMsat * int64(max) / int64(fixed.One)
if payout <= 0 {
t.Fatalf("payout at the ceiling overflowed: %d", payout)
}
if payout > 1<<62 {
t.Fatalf("payout at the ceiling is %d, unreasonably large", payout)
}
}