Compare commits
3 Commits
483ba9f2a2
...
8045e37c16
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8045e37c16 | ||
|
|
8fccbb2a9a | ||
|
|
9413537251 |
31
docker-compose.yml
Normal file
31
docker-compose.yml
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: arcade
|
||||||
|
POSTGRES_PASSWORD: arcade_dev
|
||||||
|
POSTGRES_DB: arcade
|
||||||
|
ports: ["5432:5432"]
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
- ./migrations:/docker-entrypoint-initdb.d:ro
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U arcade"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
ports: ["6379:6379"]
|
||||||
|
volumes:
|
||||||
|
- redisdata:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
|
redisdata:
|
||||||
1081
docs/superpowers/plans/2026-08-05-foundation.md
Normal file
1081
docs/superpowers/plans/2026-08-05-foundation.md
Normal file
File diff suppressed because it is too large
Load Diff
13
go.mod
Normal file
13
go.mod
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
module github.com/drjones/quantum-arcade
|
||||||
|
|
||||||
|
go 1.26.5
|
||||||
|
|
||||||
|
require github.com/jackc/pgx/v5 v5.10.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
golang.org/x/sync v0.17.0 // indirect
|
||||||
|
golang.org/x/text v0.29.0 // indirect
|
||||||
|
)
|
||||||
26
go.sum
Normal file
26
go.sum
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||||
|
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||||
|
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||||
|
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
96
migrations/0001_ledger.sql
Normal file
96
migrations/0001_ledger.sql
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
-- Quantum Arcade ledger: append-only double-entry accounting.
|
||||||
|
--
|
||||||
|
-- Amounts are millisatoshis stored as BIGINT. No UPDATE or DELETE is ever
|
||||||
|
-- issued against these tables; corrections are compensating transactions.
|
||||||
|
-- The constraints below restate the application's invariants so that a bug in
|
||||||
|
-- the Go layer cannot corrupt the books.
|
||||||
|
|
||||||
|
CREATE TYPE account_kind AS ENUM ('player', 'house', 'lightning_bridge');
|
||||||
|
|
||||||
|
CREATE TABLE accounts (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
kind account_kind NOT NULL,
|
||||||
|
-- Player accounts key on the ed25519 public key; system accounts use a
|
||||||
|
-- stable name. Exactly one of these is set.
|
||||||
|
pubkey BYTEA UNIQUE,
|
||||||
|
name TEXT UNIQUE,
|
||||||
|
nickname TEXT,
|
||||||
|
-- The Lightning bridge is the boundary with the outside world: its balance
|
||||||
|
-- goes negative by exactly the amount owed to players inside the system.
|
||||||
|
-- Every other account is strictly non-negative.
|
||||||
|
allow_negative BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT account_identity CHECK (
|
||||||
|
(kind = 'player' AND pubkey IS NOT NULL AND name IS NULL) OR
|
||||||
|
(kind <> 'player' AND pubkey IS NULL AND name IS NOT NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE transactions (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
kind TEXT NOT NULL, -- 'bet', 'payout', 'deposit', ...
|
||||||
|
round_id BIGINT, -- NULL for non-game transactions
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE postings (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
transaction_id BIGINT NOT NULL REFERENCES transactions(id),
|
||||||
|
account_id BIGINT NOT NULL REFERENCES accounts(id),
|
||||||
|
-- Positive credits the account, negative debits it.
|
||||||
|
amount_msat BIGINT NOT NULL,
|
||||||
|
balance_before BIGINT NOT NULL,
|
||||||
|
balance_after BIGINT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT amount_nonzero CHECK (amount_msat <> 0),
|
||||||
|
CONSTRAINT balance_arithmetic CHECK (balance_after = balance_before + amount_msat)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- A CHECK constraint cannot consult another table, so the non-negative rule is
|
||||||
|
-- a trigger. It is the last line of defence behind the application's own check.
|
||||||
|
CREATE OR REPLACE FUNCTION enforce_balance_floor() RETURNS TRIGGER AS $$
|
||||||
|
DECLARE
|
||||||
|
permitted BOOLEAN;
|
||||||
|
BEGIN
|
||||||
|
SELECT allow_negative INTO permitted FROM accounts WHERE id = NEW.account_id;
|
||||||
|
IF NOT permitted AND NEW.balance_after < 0 THEN
|
||||||
|
RAISE EXCEPTION 'account % may not go negative (balance would be %)',
|
||||||
|
NEW.account_id, NEW.balance_after;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
CREATE TRIGGER postings_balance_floor
|
||||||
|
BEFORE INSERT ON postings
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION enforce_balance_floor();
|
||||||
|
|
||||||
|
CREATE INDEX postings_account_idx ON postings (account_id, id DESC);
|
||||||
|
CREATE INDEX postings_transaction_idx ON postings (transaction_id);
|
||||||
|
CREATE INDEX transactions_round_idx ON transactions (round_id) WHERE round_id IS NOT NULL;
|
||||||
|
|
||||||
|
-- Current balance is the most recent posting's balance_after.
|
||||||
|
CREATE VIEW account_balances AS
|
||||||
|
SELECT DISTINCT ON (account_id)
|
||||||
|
account_id, balance_after AS balance_msat
|
||||||
|
FROM postings
|
||||||
|
ORDER BY account_id, id DESC;
|
||||||
|
|
||||||
|
-- Enforce append-only at the database level, not just by convention.
|
||||||
|
CREATE OR REPLACE FUNCTION reject_mutation() RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
RAISE EXCEPTION 'ledger tables are append-only';
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
CREATE TRIGGER postings_append_only
|
||||||
|
BEFORE UPDATE OR DELETE ON postings
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION reject_mutation();
|
||||||
|
|
||||||
|
CREATE TRIGGER transactions_append_only
|
||||||
|
BEFORE UPDATE OR DELETE ON transactions
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION reject_mutation();
|
||||||
|
|
||||||
|
INSERT INTO accounts (kind, name, allow_negative) VALUES
|
||||||
|
('house', 'house_pot', false),
|
||||||
|
('lightning_bridge', 'lightning_bridge', true);
|
||||||
122
pkg/fixed/fixed.go
Normal file
122
pkg/fixed/fixed.go
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
// Package fixed provides deterministic Q32.32 fixed-point arithmetic.
|
||||||
|
//
|
||||||
|
// No floating-point operation appears anywhere in this package. Results must be
|
||||||
|
// bit-identical across architectures and between native and WASM builds, which
|
||||||
|
// is what allows a player's browser to independently replay a round and reach
|
||||||
|
// exactly the same outcome as the server.
|
||||||
|
package fixed
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/bits"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
// F is a Q32.32 fixed-point number: an int64 with 32 fractional bits.
|
||||||
|
type F int64
|
||||||
|
|
||||||
|
// One is the fixed-point representation of 1.0.
|
||||||
|
const One F = 1 << 32
|
||||||
|
|
||||||
|
const fracBits = 32
|
||||||
|
|
||||||
|
// FromInt converts a whole number to fixed-point.
|
||||||
|
func FromInt(v int64) F { return F(v << fracBits) }
|
||||||
|
|
||||||
|
// Int truncates toward negative infinity and returns the whole part.
|
||||||
|
func (a F) Int() int64 { return int64(a) >> fracBits }
|
||||||
|
|
||||||
|
func (a F) Add(b F) F { return a + b }
|
||||||
|
func (a F) Sub(b F) F { return a - b }
|
||||||
|
|
||||||
|
// Mul multiplies via a 128-bit intermediate so no precision is lost before the
|
||||||
|
// shift back down. A naive (a*b)>>32 overflows for operands above roughly 2^15.
|
||||||
|
func (a F) Mul(b F) F {
|
||||||
|
neg := false
|
||||||
|
x, y := int64(a), int64(b)
|
||||||
|
if x < 0 {
|
||||||
|
x, neg = -x, !neg
|
||||||
|
}
|
||||||
|
if y < 0 {
|
||||||
|
y, neg = -y, !neg
|
||||||
|
}
|
||||||
|
hi, lo := bits.Mul64(uint64(x), uint64(y))
|
||||||
|
res := int64(lo>>fracBits | hi<<(64-fracBits))
|
||||||
|
if neg {
|
||||||
|
res = -res
|
||||||
|
}
|
||||||
|
return F(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Div divides via a 128-bit intermediate for the same reason as Mul.
|
||||||
|
func (a F) Div(b F) F {
|
||||||
|
if b == 0 {
|
||||||
|
panic("fixed: division by zero")
|
||||||
|
}
|
||||||
|
neg := false
|
||||||
|
x, y := int64(a), int64(b)
|
||||||
|
if x < 0 {
|
||||||
|
x, neg = -x, !neg
|
||||||
|
}
|
||||||
|
if y < 0 {
|
||||||
|
y, neg = -y, !neg
|
||||||
|
}
|
||||||
|
hi := uint64(x) >> (64 - fracBits)
|
||||||
|
lo := uint64(x) << fracBits
|
||||||
|
q, _ := bits.Div64(hi, lo, uint64(y))
|
||||||
|
res := int64(q)
|
||||||
|
if neg {
|
||||||
|
res = -res
|
||||||
|
}
|
||||||
|
return F(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sqrt returns the fixed-point square root using integer Newton iteration.
|
||||||
|
// It converges in well under the iteration cap for the full int64 range.
|
||||||
|
func Sqrt(a F) F {
|
||||||
|
if a < 0 {
|
||||||
|
panic("fixed: sqrt of negative")
|
||||||
|
}
|
||||||
|
if a == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
// Initial guess: half the bit length puts us within a factor of two.
|
||||||
|
shift := uint(bits.Len64(uint64(a))+fracBits) / 2
|
||||||
|
x := F(1) << shift
|
||||||
|
for i := 0; i < 64; i++ {
|
||||||
|
next := (x + a.Div(x)) / 2
|
||||||
|
if next == x || next == x-1 {
|
||||||
|
x = next
|
||||||
|
break
|
||||||
|
}
|
||||||
|
x = next
|
||||||
|
}
|
||||||
|
// Newton can land one ulp high; step down while the square exceeds the input.
|
||||||
|
for x > 0 && x.Mul(x) > a {
|
||||||
|
x--
|
||||||
|
}
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
// String renders the value with six fractional digits, using integer math only.
|
||||||
|
func (a F) String() string {
|
||||||
|
neg := a < 0
|
||||||
|
if neg {
|
||||||
|
a = -a
|
||||||
|
}
|
||||||
|
whole := int64(a) >> fracBits
|
||||||
|
frac := int64(a) & (int64(One) - 1)
|
||||||
|
micros := (frac * 1_000_000) >> fracBits
|
||||||
|
s := strconv.FormatInt(whole, 10) + "." + pad6(micros)
|
||||||
|
if neg {
|
||||||
|
return "-" + s
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func pad6(v int64) string {
|
||||||
|
s := strconv.FormatInt(v, 10)
|
||||||
|
for len(s) < 6 {
|
||||||
|
s = "0" + s
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
67
pkg/fixed/fixed_test.go
Normal file
67
pkg/fixed/fixed_test.go
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package fixed
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestFromIntAndBack(t *testing.T) {
|
||||||
|
if got := FromInt(7).Int(); got != 7 {
|
||||||
|
t.Fatalf("FromInt(7).Int() = %d, want 7", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMulIsExact(t *testing.T) {
|
||||||
|
half := One / 2
|
||||||
|
if got := half.Mul(half); got != One/4 {
|
||||||
|
t.Fatalf("0.5*0.5 = %d, want %d", got, One/4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMulDoesNotOverflowAtScale(t *testing.T) {
|
||||||
|
// A naive (a*b)>>32 overflows well below this. The 128-bit intermediate
|
||||||
|
// must handle it exactly.
|
||||||
|
a := FromInt(100000)
|
||||||
|
if got := a.Mul(FromInt(2)); got != FromInt(200000) {
|
||||||
|
t.Fatalf("100000*2 = %v, want 200000", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDivIsExact(t *testing.T) {
|
||||||
|
if got := FromInt(1).Div(FromInt(4)); got != One/4 {
|
||||||
|
t.Fatalf("1/4 = %d, want %d", got, One/4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNegativeMulAndDiv(t *testing.T) {
|
||||||
|
if got := FromInt(-3).Mul(FromInt(4)); got != FromInt(-12) {
|
||||||
|
t.Fatalf("-3*4 = %v, want -12", got)
|
||||||
|
}
|
||||||
|
if got := FromInt(-12).Div(FromInt(4)); got != FromInt(-3) {
|
||||||
|
t.Fatalf("-12/4 = %v, want -3", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSqrt(t *testing.T) {
|
||||||
|
for _, n := range []int64{0, 1, 4, 9, 16, 100, 10000} {
|
||||||
|
want := FromInt(isqrt(n))
|
||||||
|
got := Sqrt(FromInt(n))
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("Sqrt(%d) = %v, want %v", n, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isqrt(n int64) int64 {
|
||||||
|
var r int64
|
||||||
|
for r*r <= n {
|
||||||
|
r++
|
||||||
|
}
|
||||||
|
return r - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestString(t *testing.T) {
|
||||||
|
if got := (One + One/2).String(); got != "1.500000" {
|
||||||
|
t.Fatalf("1.5.String() = %q", got)
|
||||||
|
}
|
||||||
|
if got := FromInt(-2).String(); got != "-2.000000" {
|
||||||
|
t.Fatalf("-2.String() = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
52
pkg/fixed/nofloat_test.go
Normal file
52
pkg/fixed/nofloat_test.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
package fixed_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Determinism depends on there being no floating-point arithmetic anywhere in
|
||||||
|
// the simulation path: floats drift between architectures and between native
|
||||||
|
// and WASM builds, which would silently break round verification. This test
|
||||||
|
// fails the build if a float type is ever introduced.
|
||||||
|
//
|
||||||
|
// Test files are exempt, since statistical assertions legitimately use floats.
|
||||||
|
func TestNoFloatingPointInDeterministicPackages(t *testing.T) {
|
||||||
|
for _, dir := range []string{".", "../sim"} {
|
||||||
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
pkgs, err := parser.ParseDir(fset, dir, nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse %s: %v", dir, err)
|
||||||
|
}
|
||||||
|
for _, pkg := range pkgs {
|
||||||
|
for name, file := range pkg.Files {
|
||||||
|
if strings.HasSuffix(name, "_test.go") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ast.Inspect(file, func(n ast.Node) bool {
|
||||||
|
switch node := n.(type) {
|
||||||
|
case *ast.Ident:
|
||||||
|
if node.Name == "float32" || node.Name == "float64" {
|
||||||
|
t.Errorf("%s: forbidden float type %q in deterministic package",
|
||||||
|
filepath.Base(name), node.Name)
|
||||||
|
}
|
||||||
|
case *ast.BasicLit:
|
||||||
|
if node.Kind == token.FLOAT {
|
||||||
|
t.Errorf("%s: forbidden float literal %s",
|
||||||
|
filepath.Base(name), node.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
247
pkg/ledger/ledger.go
Normal file
247
pkg/ledger/ledger.go
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
// Package ledger implements append-only double-entry accounting.
|
||||||
|
//
|
||||||
|
// Invariants, enforced here and again by database constraints and triggers:
|
||||||
|
// - every transaction's postings sum to exactly zero
|
||||||
|
// - no account balance may go negative
|
||||||
|
// - rows are never updated or deleted; corrections are compensating entries
|
||||||
|
//
|
||||||
|
// Every balance change is explained by a posting that records what happened,
|
||||||
|
// when, which round it belonged to, and the balance either side of it.
|
||||||
|
package ledger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUnbalanced = errors.New("ledger: postings do not sum to zero")
|
||||||
|
ErrInsufficientFunds = errors.New("ledger: insufficient funds")
|
||||||
|
ErrEmptyTransaction = errors.New("ledger: transaction has no postings")
|
||||||
|
ErrNonPositiveAmount = errors.New("ledger: amount must be positive")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Posting is a single leg of a transaction. Positive credits, negative debits.
|
||||||
|
type Posting struct {
|
||||||
|
AccountID int64
|
||||||
|
AmountMsat int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry is a posting as seen from one account's history.
|
||||||
|
type Entry struct {
|
||||||
|
TransactionID int64
|
||||||
|
Kind string
|
||||||
|
RoundID *int64
|
||||||
|
AmountMsat int64
|
||||||
|
BalanceBefore int64
|
||||||
|
BalanceAfter int64
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Ledger struct{ pool *pgxpool.Pool }
|
||||||
|
|
||||||
|
func New(pool *pgxpool.Pool) *Ledger { return &Ledger{pool: pool} }
|
||||||
|
|
||||||
|
// Post writes one balanced transaction atomically.
|
||||||
|
//
|
||||||
|
// Accounts are locked in ascending id order so that concurrent transactions
|
||||||
|
// touching the same accounts cannot deadlock, and so a balance read cannot be
|
||||||
|
// stale by the time the posting is written.
|
||||||
|
func (l *Ledger) Post(ctx context.Context, kind string, roundID *int64, postings []Posting) (int64, error) {
|
||||||
|
if len(postings) == 0 {
|
||||||
|
return 0, ErrEmptyTransaction
|
||||||
|
}
|
||||||
|
var sum int64
|
||||||
|
for _, p := range postings {
|
||||||
|
sum += p.AmountMsat
|
||||||
|
}
|
||||||
|
if sum != 0 {
|
||||||
|
return 0, fmt.Errorf("%w: sum is %d", ErrUnbalanced, sum)
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := l.pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
var txID int64
|
||||||
|
if err := tx.QueryRow(ctx,
|
||||||
|
`INSERT INTO transactions (kind, round_id) VALUES ($1, $2) RETURNING id`,
|
||||||
|
kind, roundID).Scan(&txID); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ordered := append([]Posting(nil), postings...)
|
||||||
|
sort.Slice(ordered, func(i, j int) bool {
|
||||||
|
return ordered[i].AccountID < ordered[j].AccountID
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, p := range ordered {
|
||||||
|
// Lock the account row first, then read its latest balance. Taking the
|
||||||
|
// lock before the read is what serializes concurrent spends.
|
||||||
|
var allowNegative bool
|
||||||
|
if err := tx.QueryRow(ctx,
|
||||||
|
`SELECT allow_negative FROM accounts WHERE id = $1 FOR UPDATE`,
|
||||||
|
p.AccountID).Scan(&allowNegative); err != nil {
|
||||||
|
return 0, fmt.Errorf("locking account %d: %w", p.AccountID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var before int64
|
||||||
|
if err := tx.QueryRow(ctx,
|
||||||
|
`SELECT COALESCE(
|
||||||
|
(SELECT balance_after FROM postings
|
||||||
|
WHERE account_id = $1 ORDER BY id DESC LIMIT 1), 0)`,
|
||||||
|
p.AccountID).Scan(&before); err != nil {
|
||||||
|
return 0, fmt.Errorf("reading balance of account %d: %w", p.AccountID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
after := before + p.AmountMsat
|
||||||
|
if after < 0 && !allowNegative {
|
||||||
|
return 0, fmt.Errorf("%w: account %d holds %d, needs %d",
|
||||||
|
ErrInsufficientFunds, p.AccountID, before, -p.AmountMsat)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := tx.Exec(ctx,
|
||||||
|
`INSERT INTO postings
|
||||||
|
(transaction_id, account_id, amount_msat, balance_before, balance_after)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)`,
|
||||||
|
txID, p.AccountID, p.AmountMsat, before, after); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return txID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transfer moves funds between two accounts. This is the peer-to-peer path.
|
||||||
|
func (l *Ledger) Transfer(ctx context.Context, from, to int64, amountMsat int64) (int64, error) {
|
||||||
|
if amountMsat <= 0 {
|
||||||
|
return 0, ErrNonPositiveAmount
|
||||||
|
}
|
||||||
|
return l.Post(ctx, "transfer", nil, []Posting{
|
||||||
|
{AccountID: from, AmountMsat: -amountMsat},
|
||||||
|
{AccountID: to, AmountMsat: amountMsat},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deposit credits a player from the Lightning bridge account.
|
||||||
|
func (l *Ledger) Deposit(ctx context.Context, player int64, amountMsat int64) (int64, error) {
|
||||||
|
if amountMsat <= 0 {
|
||||||
|
return 0, ErrNonPositiveAmount
|
||||||
|
}
|
||||||
|
bridge, err := l.AccountByName(ctx, "lightning_bridge")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return l.Post(ctx, "deposit", nil, []Posting{
|
||||||
|
{AccountID: bridge, AmountMsat: -amountMsat},
|
||||||
|
{AccountID: player, AmountMsat: amountMsat},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Withdraw debits a player back to the Lightning bridge account.
|
||||||
|
func (l *Ledger) Withdraw(ctx context.Context, player int64, amountMsat int64) (int64, error) {
|
||||||
|
if amountMsat <= 0 {
|
||||||
|
return 0, ErrNonPositiveAmount
|
||||||
|
}
|
||||||
|
bridge, err := l.AccountByName(ctx, "lightning_bridge")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return l.Post(ctx, "withdraw", nil, []Posting{
|
||||||
|
{AccountID: player, AmountMsat: -amountMsat},
|
||||||
|
{AccountID: bridge, AmountMsat: amountMsat},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Balance returns the account's current balance in millisatoshis.
|
||||||
|
func (l *Ledger) Balance(ctx context.Context, accountID int64) (int64, error) {
|
||||||
|
var bal int64
|
||||||
|
err := l.pool.QueryRow(ctx,
|
||||||
|
`SELECT COALESCE(
|
||||||
|
(SELECT balance_after FROM postings
|
||||||
|
WHERE account_id = $1 ORDER BY id DESC LIMIT 1), 0)`,
|
||||||
|
accountID).Scan(&bal)
|
||||||
|
return bal, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// History returns an account's postings, newest first.
|
||||||
|
func (l *Ledger) History(ctx context.Context, accountID int64, limit int) ([]Entry, error) {
|
||||||
|
rows, err := l.pool.Query(ctx,
|
||||||
|
`SELECT p.transaction_id, t.kind, t.round_id,
|
||||||
|
p.amount_msat, p.balance_before, p.balance_after, p.created_at
|
||||||
|
FROM postings p
|
||||||
|
JOIN transactions t ON t.id = p.transaction_id
|
||||||
|
WHERE p.account_id = $1
|
||||||
|
ORDER BY p.id DESC
|
||||||
|
LIMIT $2`, accountID, limit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var out []Entry
|
||||||
|
for rows.Next() {
|
||||||
|
var e Entry
|
||||||
|
if err := rows.Scan(&e.TransactionID, &e.Kind, &e.RoundID,
|
||||||
|
&e.AmountMsat, &e.BalanceBefore, &e.BalanceAfter, &e.CreatedAt); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, e)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsurePlayer returns the account id for a public key, creating it if needed.
|
||||||
|
func (l *Ledger) EnsurePlayer(ctx context.Context, pubkey []byte) (int64, error) {
|
||||||
|
var id int64
|
||||||
|
err := l.pool.QueryRow(ctx,
|
||||||
|
`INSERT INTO accounts (kind, pubkey) VALUES ('player', $1)
|
||||||
|
ON CONFLICT (pubkey) DO UPDATE SET pubkey = EXCLUDED.pubkey
|
||||||
|
RETURNING id`, pubkey).Scan(&id)
|
||||||
|
return id, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccountByName resolves a system account such as "house_pot".
|
||||||
|
func (l *Ledger) AccountByName(ctx context.Context, name string) (int64, error) {
|
||||||
|
var id int64
|
||||||
|
err := l.pool.QueryRow(ctx,
|
||||||
|
`SELECT id FROM accounts WHERE name = $1`, name).Scan(&id)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return 0, fmt.Errorf("ledger: no account named %q", name)
|
||||||
|
}
|
||||||
|
return id, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TotalIssued is the value held inside the system by players and the house —
|
||||||
|
// every account except the external Lightning bridge. It changes only when
|
||||||
|
// funds genuinely enter or leave, never through internal play.
|
||||||
|
func (l *Ledger) TotalIssued(ctx context.Context) (int64, error) {
|
||||||
|
var total int64
|
||||||
|
err := l.pool.QueryRow(ctx,
|
||||||
|
`SELECT COALESCE(SUM(b.balance_msat), 0)
|
||||||
|
FROM account_balances b
|
||||||
|
JOIN accounts a ON a.id = b.account_id
|
||||||
|
WHERE NOT a.allow_negative`).Scan(&total)
|
||||||
|
return total, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConservationCheck sums every account including the bridge. Because each
|
||||||
|
// transaction sums to zero, this must always be exactly zero. A non-zero
|
||||||
|
// result means the books are corrupt, and is the top-level audit alarm.
|
||||||
|
func (l *Ledger) ConservationCheck(ctx context.Context) (int64, error) {
|
||||||
|
var total int64
|
||||||
|
err := l.pool.QueryRow(ctx,
|
||||||
|
`SELECT COALESCE(SUM(balance_msat), 0) FROM account_balances`).Scan(&total)
|
||||||
|
return total, err
|
||||||
|
}
|
||||||
229
pkg/ledger/ledger_test.go
Normal file
229
pkg/ledger/ledger_test.go
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
package ledger_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/drjones/quantum-arcade/pkg/ledger"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testPool(t *testing.T) *pgxpool.Pool {
|
||||||
|
t.Helper()
|
||||||
|
dsn := os.Getenv("ARCADE_TEST_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
dsn = "postgres://arcade:arcade_dev@localhost:5432/arcade"
|
||||||
|
}
|
||||||
|
pool, err := pgxpool.New(context.Background(), dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("no database available: %v", err)
|
||||||
|
}
|
||||||
|
if err := pool.Ping(context.Background()); err != nil {
|
||||||
|
t.Skipf("no database available: %v", err)
|
||||||
|
}
|
||||||
|
return pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// runID is fresh for each execution of the test binary. The ledger is
|
||||||
|
// append-only and never truncated, so accounts must not be shared between runs
|
||||||
|
// or balances would accumulate across them.
|
||||||
|
var runID = fmt.Sprintf("%d-%d", time.Now().UnixNano(), rand.Int63())
|
||||||
|
|
||||||
|
// uniqueKey produces an account key unique to this test and this run.
|
||||||
|
func uniqueKey(t *testing.T, label string) []byte {
|
||||||
|
t.Helper()
|
||||||
|
return []byte(fmt.Sprintf("%s-%s-%s", runID, t.Name(), label))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostRejectsUnbalanced(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
a, err := l.EnsurePlayer(ctx, uniqueKey(t, "a"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, err := l.EnsurePlayer(ctx, uniqueKey(t, "b"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = l.Post(ctx, "test", nil, []ledger.Posting{
|
||||||
|
{AccountID: a, AmountMsat: -100},
|
||||||
|
{AccountID: b, AmountMsat: 50},
|
||||||
|
})
|
||||||
|
if !errors.Is(err, ledger.ErrUnbalanced) {
|
||||||
|
t.Fatalf("got %v, want ErrUnbalanced", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPostRejectsOverdraft(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
a, _ := l.EnsurePlayer(ctx, uniqueKey(t, "a"))
|
||||||
|
b, _ := l.EnsurePlayer(ctx, uniqueKey(t, "b"))
|
||||||
|
_, err := l.Post(ctx, "test", nil, []ledger.Posting{
|
||||||
|
{AccountID: a, AmountMsat: -1_000_000},
|
||||||
|
{AccountID: b, AmountMsat: 1_000_000},
|
||||||
|
})
|
||||||
|
if !errors.Is(err, ledger.ErrInsufficientFunds) {
|
||||||
|
t.Fatalf("got %v, want ErrInsufficientFunds", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRejectedTransactionLeavesNoTrace(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
a, _ := l.EnsurePlayer(ctx, uniqueKey(t, "a"))
|
||||||
|
b, _ := l.EnsurePlayer(ctx, uniqueKey(t, "b"))
|
||||||
|
|
||||||
|
before, err := l.Balance(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _ = l.Post(ctx, "test", nil, []ledger.Posting{
|
||||||
|
{AccountID: a, AmountMsat: -500},
|
||||||
|
{AccountID: b, AmountMsat: 500},
|
||||||
|
})
|
||||||
|
after, err := l.Balance(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if before != after {
|
||||||
|
t.Fatalf("failed transaction changed balance: %d -> %d", before, after)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConservationOfValue(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
bridge, err := l.AccountByName(ctx, "lightning_bridge")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p, _ := l.EnsurePlayer(ctx, uniqueKey(t, "player"))
|
||||||
|
|
||||||
|
before, err := l.TotalIssued(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := l.Deposit(ctx, p, 5000); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := l.Withdraw(ctx, p, 5000); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
after, err := l.TotalIssued(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if before != after {
|
||||||
|
t.Fatalf("total value changed: %d -> %d", before, after)
|
||||||
|
}
|
||||||
|
_ = bridge
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBalanceTracksPostings(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
p, _ := l.EnsurePlayer(ctx, uniqueKey(t, "p"))
|
||||||
|
|
||||||
|
if _, err := l.Deposit(ctx, p, 12_345); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
bal, err := l.Balance(ctx, p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if bal != 12_345 {
|
||||||
|
t.Fatalf("balance = %d, want 12345", bal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two concurrent spends of the same funds must not both succeed. The account
|
||||||
|
// row lock is what prevents a double-spend under load.
|
||||||
|
func TestConcurrentSpendsCannotOverdraw(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
from, _ := l.EnsurePlayer(ctx, uniqueKey(t, "from"))
|
||||||
|
to, _ := l.EnsurePlayer(ctx, uniqueKey(t, "to"))
|
||||||
|
|
||||||
|
if _, err := l.Deposit(ctx, from, 1000); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
const workers = 8
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
succeeded := make([]bool, workers)
|
||||||
|
for i := 0; i < workers; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(i int) {
|
||||||
|
defer wg.Done()
|
||||||
|
_, err := l.Transfer(ctx, from, to, 1000)
|
||||||
|
succeeded[i] = err == nil
|
||||||
|
}(i)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
wins := 0
|
||||||
|
for _, ok := range succeeded {
|
||||||
|
if ok {
|
||||||
|
wins++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if wins != 1 {
|
||||||
|
t.Fatalf("%d concurrent spends of the same 1000 msat succeeded, want 1", wins)
|
||||||
|
}
|
||||||
|
bal, _ := l.Balance(ctx, from)
|
||||||
|
if bal != 0 {
|
||||||
|
t.Fatalf("source balance = %d, want 0", bal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAppendOnlyEnforcedByDatabase(t *testing.T) {
|
||||||
|
pool := testPool(t)
|
||||||
|
l := ledger.New(pool)
|
||||||
|
ctx := context.Background()
|
||||||
|
p, _ := l.EnsurePlayer(ctx, uniqueKey(t, "p"))
|
||||||
|
if _, err := l.Deposit(ctx, p, 100); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err := pool.Exec(ctx, `UPDATE postings SET amount_msat = 999 WHERE account_id = $1`, p)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("UPDATE on postings succeeded; append-only trigger is not working")
|
||||||
|
}
|
||||||
|
_, err = pool.Exec(ctx, `DELETE FROM postings WHERE account_id = $1`, p)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("DELETE on postings succeeded; append-only trigger is not working")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHistoryExplainsEveryChange(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
p, _ := l.EnsurePlayer(ctx, uniqueKey(t, "p"))
|
||||||
|
if _, err := l.Deposit(ctx, p, 800); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := l.Withdraw(ctx, p, 300); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
entries, err := l.History(ctx, p, 10)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(entries) != 2 {
|
||||||
|
t.Fatalf("got %d history entries, want 2", len(entries))
|
||||||
|
}
|
||||||
|
// History is newest-first.
|
||||||
|
if entries[0].Kind != "withdraw" || entries[0].AmountMsat != -300 {
|
||||||
|
t.Fatalf("unexpected newest entry: %+v", entries[0])
|
||||||
|
}
|
||||||
|
if entries[0].BalanceAfter != 500 {
|
||||||
|
t.Fatalf("balance after withdraw = %d, want 500", entries[0].BalanceAfter)
|
||||||
|
}
|
||||||
|
}
|
||||||
117
pkg/ledger/property_test.go
Normal file
117
pkg/ledger/property_test.go
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
package ledger_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/drjones/quantum-arcade/pkg/ledger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Across a long run of random transfers, bets, and payouts, total value must
|
||||||
|
// never change and no player balance may go negative. This is the property that
|
||||||
|
// makes end-of-night settlement trustworthy.
|
||||||
|
func TestRandomActivityConservesValue(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
house, err := l.AccountByName(ctx, "house_pot")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
const players = 8
|
||||||
|
ids := make([]int64, players)
|
||||||
|
for i := range ids {
|
||||||
|
id, err := l.EnsurePlayer(ctx, uniqueKey(t, string(rune('a'+i))))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ids[i] = id
|
||||||
|
if _, err := l.Deposit(ctx, id, 100_000); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
before, err := l.TotalIssued(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rng := rand.New(rand.NewSource(1))
|
||||||
|
roundID := int64(0)
|
||||||
|
for i := 0; i < 400; i++ {
|
||||||
|
amt := int64(rng.Intn(5000) + 1)
|
||||||
|
player := ids[rng.Intn(players)]
|
||||||
|
|
||||||
|
var err error
|
||||||
|
switch rng.Intn(3) {
|
||||||
|
case 0: // peer transfer
|
||||||
|
other := ids[rng.Intn(players)]
|
||||||
|
if other == player {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, err = l.Transfer(ctx, player, other, amt)
|
||||||
|
case 1: // bet: player pays the house
|
||||||
|
roundID++
|
||||||
|
r := roundID
|
||||||
|
_, err = l.Post(ctx, "bet", &r, []ledger.Posting{
|
||||||
|
{AccountID: player, AmountMsat: -amt},
|
||||||
|
{AccountID: house, AmountMsat: amt},
|
||||||
|
})
|
||||||
|
case 2: // payout: house pays the player
|
||||||
|
roundID++
|
||||||
|
r := roundID
|
||||||
|
_, err = l.Post(ctx, "payout", &r, []ledger.Posting{
|
||||||
|
{AccountID: house, AmountMsat: -amt},
|
||||||
|
{AccountID: player, AmountMsat: amt},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Running out of funds is a legitimate outcome; nothing else is.
|
||||||
|
if err != nil && !errors.Is(err, ledger.ErrInsufficientFunds) {
|
||||||
|
t.Fatalf("iteration %d: %v", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
after, err := l.TotalIssued(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if before != after {
|
||||||
|
t.Fatalf("value not conserved: %d -> %d", before, after)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, id := range ids {
|
||||||
|
bal, err := l.Balance(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if bal < 0 {
|
||||||
|
t.Fatalf("account %d went negative: %d", id, bal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every transaction sums to zero, so the sum across all accounts including the
|
||||||
|
// external bridge must be exactly zero at all times.
|
||||||
|
func TestBooksAlwaysBalanceToZero(t *testing.T) {
|
||||||
|
l := ledger.New(testPool(t))
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
p, err := l.EnsurePlayer(ctx, uniqueKey(t, "p"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := l.Deposit(ctx, p, 7_777); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
total, err := l.ConservationCheck(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if total != 0 {
|
||||||
|
t.Fatalf("books do not balance: total across all accounts = %d", total)
|
||||||
|
}
|
||||||
|
}
|
||||||
78
pkg/sim/crash.go
Normal file
78
pkg/sim/crash.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package sim
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/bits"
|
||||||
|
|
||||||
|
"github.com/drjones/quantum-arcade/pkg/fixed"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HouseEdgeBP is the house edge in basis points (200 = 2.00%).
|
||||||
|
const HouseEdgeBP int64 = 200
|
||||||
|
|
||||||
|
// TickHz is the simulation rate. Rounds advance in whole ticks only.
|
||||||
|
const TickHz = 60
|
||||||
|
|
||||||
|
// growthPerTickBP is multiplier growth per tick, in basis points of the current
|
||||||
|
// value. At 6bp and 60Hz the multiplier reaches 2x in roughly 19 seconds, which
|
||||||
|
// is long enough to feel the climb and short enough to keep rounds moving.
|
||||||
|
const growthPerTickBP int64 = 6
|
||||||
|
|
||||||
|
// CrashPoint derives the multiplier at which a round ends, as a pure function of
|
||||||
|
// the seed.
|
||||||
|
//
|
||||||
|
// The distribution is the inverse-uniform curve scaled by the house edge:
|
||||||
|
//
|
||||||
|
// crash = (1 - edge) / u, u uniform over (0, 1]
|
||||||
|
//
|
||||||
|
// which yields the same expected return of (1 - edge) at every cash-out target.
|
||||||
|
// No target is smarter than any other, so there is nothing to grind out.
|
||||||
|
func CrashPoint(seed [32]byte) fixed.F {
|
||||||
|
r := NewRNG(seed)
|
||||||
|
|
||||||
|
// u is uniform over [1, 2^32], giving a resolution of one part in 4 billion.
|
||||||
|
u := (r.Uint64() >> 32) + 1
|
||||||
|
|
||||||
|
// payoutRatio is (1 - edge) in Q32.32, e.g. 0.98.
|
||||||
|
payoutRatio := uint64((10000 - HouseEdgeBP) << 32 / 10000)
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
|
||||||
|
cp := fixed.F(q)
|
||||||
|
if cp < fixed.One {
|
||||||
|
cp = fixed.One
|
||||||
|
}
|
||||||
|
return cp
|
||||||
|
}
|
||||||
|
|
||||||
|
// step is the per-tick growth factor, 1 + growthPerTickBP/10000, in Q32.32.
|
||||||
|
func step() fixed.F {
|
||||||
|
return fixed.One + fixed.F(growthPerTickBP<<32/10000)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MultiplierAt returns the multiplier displayed at a given tick of the round,
|
||||||
|
// compounding from 1.0.
|
||||||
|
func MultiplierAt(tick int) fixed.F {
|
||||||
|
m := fixed.One
|
||||||
|
s := step()
|
||||||
|
for i := 0; i < tick; i++ {
|
||||||
|
m = m.Mul(s)
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// TicksToMultiplier returns the first tick at which MultiplierAt reaches m.
|
||||||
|
func TicksToMultiplier(m fixed.F) int {
|
||||||
|
cur := fixed.One
|
||||||
|
s := step()
|
||||||
|
for tick := 0; tick < 1_000_000; tick++ {
|
||||||
|
if cur >= m {
|
||||||
|
return tick
|
||||||
|
}
|
||||||
|
cur = cur.Mul(s)
|
||||||
|
}
|
||||||
|
return 1_000_000
|
||||||
|
}
|
||||||
97
pkg/sim/crash_test.go
Normal file
97
pkg/sim/crash_test.go
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
package sim
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/drjones/quantum-arcade/pkg/fixed"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCrashPointNeverBelowOne(t *testing.T) {
|
||||||
|
for i := 0; i < 20000; i++ {
|
||||||
|
var seed [32]byte
|
||||||
|
seed[0], seed[1] = byte(i), byte(i>>8)
|
||||||
|
if cp := CrashPoint(seed); cp < 1<<32 {
|
||||||
|
t.Fatalf("seed %d: crash point %v below 1.0", i, cp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCrashPointIsDeterministic(t *testing.T) {
|
||||||
|
var seed [32]byte
|
||||||
|
copy(seed[:], "repeatable")
|
||||||
|
first := CrashPoint(seed)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
if got := CrashPoint(seed); got != first {
|
||||||
|
t.Fatalf("run %d: %v != %v", i, got, first)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// With a 2% house edge, a player cashing out at exactly 2.00x should win
|
||||||
|
// slightly under half the time. This pins the payout distribution.
|
||||||
|
func TestHouseEdgeAtTwoX(t *testing.T) {
|
||||||
|
const n = 200000
|
||||||
|
target := int64(2) << 32
|
||||||
|
wins := 0
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
var seed [32]byte
|
||||||
|
seed[0], seed[1], seed[2] = byte(i), byte(i>>8), byte(i>>16)
|
||||||
|
if int64(CrashPoint(seed)) >= target {
|
||||||
|
wins++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pct := float64(wins) * 100 / n
|
||||||
|
if pct < 47.5 || pct > 50.5 {
|
||||||
|
t.Fatalf("win rate at 2.00x = %.2f%%, want ~49%%", pct)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The expected return at any cash-out target should be about 98%.
|
||||||
|
func TestExpectedReturnMatchesEdge(t *testing.T) {
|
||||||
|
const n = 200000
|
||||||
|
for _, targetX := range []int64{2, 3, 5} {
|
||||||
|
target := targetX << 32
|
||||||
|
var returned float64
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
var seed [32]byte
|
||||||
|
seed[0], seed[1], seed[2], seed[3] = byte(i), byte(i>>8), byte(i>>16), byte(targetX)
|
||||||
|
if int64(CrashPoint(seed)) >= target {
|
||||||
|
returned += float64(targetX)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rtp := returned * 100 / n
|
||||||
|
if rtp < 96.0 || rtp > 100.0 {
|
||||||
|
t.Fatalf("RTP at %dx = %.2f%%, want ~98%%", targetX, rtp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMultiplierStartsAtOne(t *testing.T) {
|
||||||
|
if got := MultiplierAt(0); got != 1<<32 {
|
||||||
|
t.Fatalf("MultiplierAt(0) = %v, want 1.0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMultiplierIsMonotonic(t *testing.T) {
|
||||||
|
prev := MultiplierAt(0)
|
||||||
|
for tick := 1; tick < 5000; tick++ {
|
||||||
|
cur := MultiplierAt(tick)
|
||||||
|
if cur < prev {
|
||||||
|
t.Fatalf("tick %d: multiplier decreased %v -> %v", tick, prev, cur)
|
||||||
|
}
|
||||||
|
prev = cur
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTicksToMultiplierRoundTrips(t *testing.T) {
|
||||||
|
for _, m := range []int64{2, 5, 10} {
|
||||||
|
target := fixed.FromInt(m)
|
||||||
|
tick := TicksToMultiplier(target)
|
||||||
|
if MultiplierAt(tick) < target {
|
||||||
|
t.Fatalf("tick %d does not reach %dx", tick, m)
|
||||||
|
}
|
||||||
|
if tick > 0 && MultiplierAt(tick-1) >= target {
|
||||||
|
t.Fatalf("tick %d is not the first to reach %dx", tick, m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
75
pkg/sim/rng.go
Normal file
75
pkg/sim/rng.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
package sim
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
|
||||||
|
"github.com/drjones/quantum-arcade/pkg/fixed"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RNG is a deterministic xoshiro256** generator seeded from 32 bytes.
|
||||||
|
// It uses only integer operations, so a browser replaying a round reproduces
|
||||||
|
// the server's stream exactly.
|
||||||
|
//
|
||||||
|
// This is the expansion function, not the entropy source: the seed itself comes
|
||||||
|
// from the commit-reveal protocol, which is what makes outcomes unriggable.
|
||||||
|
type RNG struct {
|
||||||
|
state [4]uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRNG creates a reproducible generator from a 32-byte seed.
|
||||||
|
//
|
||||||
|
// The seed is run through SplitMix64 rather than copied into the state
|
||||||
|
// directly. Copying directly leaves the first output depending only on
|
||||||
|
// state[1], so seeds differing in other bytes produce identical first draws —
|
||||||
|
// which would make CrashPoint blind to most of its own seed.
|
||||||
|
func NewRNG(seed [32]byte) *RNG {
|
||||||
|
// Fold every seed byte into a single accumulator first, so all 32 bytes
|
||||||
|
// influence all four state words.
|
||||||
|
acc := uint64(0x9E3779B97F4A7C15)
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
acc ^= binary.LittleEndian.Uint64(seed[i*8 : i*8+8])
|
||||||
|
acc = splitMix64(&acc)
|
||||||
|
}
|
||||||
|
r := &RNG{}
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
r.state[i] = splitMix64(&acc)
|
||||||
|
}
|
||||||
|
// An all-zero state is a fixed point of the recurrence. SplitMix64 makes
|
||||||
|
// this vanishingly unlikely, but the guard costs nothing.
|
||||||
|
if r.state[0]|r.state[1]|r.state[2]|r.state[3] == 0 {
|
||||||
|
r.state[0] = 0x9E3779B97F4A7C15
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitMix64 advances x and returns a well-mixed 64-bit value. Every input bit
|
||||||
|
// affects every output bit, which is the property the state expansion needs.
|
||||||
|
func splitMix64(x *uint64) uint64 {
|
||||||
|
*x += 0x9E3779B97F4A7C15
|
||||||
|
z := *x
|
||||||
|
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
|
||||||
|
z = (z ^ (z >> 27)) * 0x94D049BB133111EB
|
||||||
|
return z ^ (z >> 31)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Uint64 returns the next 64 bits of the stream.
|
||||||
|
func (r *RNG) Uint64() uint64 {
|
||||||
|
s := &r.state
|
||||||
|
result := rotl(s[1]*5, 7) * 9
|
||||||
|
t := s[1] << 17
|
||||||
|
s[2] ^= s[0]
|
||||||
|
s[3] ^= s[1]
|
||||||
|
s[1] ^= s[2]
|
||||||
|
s[0] ^= s[3]
|
||||||
|
s[2] ^= t
|
||||||
|
s[3] = rotl(s[3], 45)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func rotl(x uint64, k uint) uint64 { return (x << k) | (x >> (64 - k)) }
|
||||||
|
|
||||||
|
// Unit returns a fixed-point value uniformly distributed over [0, 1).
|
||||||
|
// Taking the top 32 bits places them exactly in the fractional field.
|
||||||
|
func (r *RNG) Unit() fixed.F {
|
||||||
|
return fixed.F(r.Uint64() >> 32)
|
||||||
|
}
|
||||||
51
pkg/sim/rng_test.go
Normal file
51
pkg/sim/rng_test.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package sim
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestRNGIsDeterministic(t *testing.T) {
|
||||||
|
var seed [32]byte
|
||||||
|
copy(seed[:], "quantum-arcade-test-seed")
|
||||||
|
a, b := NewRNG(seed), NewRNG(seed)
|
||||||
|
for i := 0; i < 1000; i++ {
|
||||||
|
if x, y := a.Uint64(), b.Uint64(); x != y {
|
||||||
|
t.Fatalf("iteration %d: %d != %d", i, x, y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDifferentSeedsDiverge(t *testing.T) {
|
||||||
|
var s1, s2 [32]byte
|
||||||
|
copy(s1[:], "seed-one")
|
||||||
|
copy(s2[:], "seed-two")
|
||||||
|
a, b := NewRNG(s1), NewRNG(s2)
|
||||||
|
same := 0
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
if a.Uint64() == b.Uint64() {
|
||||||
|
same++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if same > 1 {
|
||||||
|
t.Fatalf("streams collided %d times in 100 draws", same)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestZeroSeedDoesNotDegenerate(t *testing.T) {
|
||||||
|
var seed [32]byte // all zeros
|
||||||
|
r := NewRNG(seed)
|
||||||
|
first := r.Uint64()
|
||||||
|
if first == 0 && r.Uint64() == 0 {
|
||||||
|
t.Fatal("zero seed produced a degenerate all-zero stream")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnitInRange(t *testing.T) {
|
||||||
|
var seed [32]byte
|
||||||
|
seed[0] = 9
|
||||||
|
r := NewRNG(seed)
|
||||||
|
for i := 0; i < 10000; i++ {
|
||||||
|
u := r.Unit()
|
||||||
|
if u < 0 || u >= 1<<32 {
|
||||||
|
t.Fatalf("Unit() = %v out of [0,1)", u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user