Files
chains/zkvm/nullifier_db_test.go
zeekay 6919ac8229 zkvm: a transaction's identity is its content, and one predicate decides
The proof cache was keyed on tx.ID as read off the wire, plus the proof
type, the proof and its public inputs — all four the sender's to choose.
Copy an accepted transaction's four onto a transaction spending entirely
different notes and the key matched; the hit returned nil from the cache,
ahead of verifyPublicInputs, which is the only thing tying those inputs to
what the transaction spends. Shielded value, backed by a proof that
attests to nothing about it.

The id is no longer on the wire. parseTransaction derives it, the cache is
keyed on ComputeID(), and a block's id folds in ComputeID() rather than
whatever id arrived — which also ends the block and vertex id malleability
that one flipped byte bought.

Every block and vertex id, and the first public input of every proof, now
open with sha256(ChainID ‖ NetworkID). It is not on the wire, so a block
from another chain has no parent here and its proofs do not verify, rather
than passing a check someone can forget to write.

Also on the consensus surface:

  Verify required height == parent+1 and nothing more, so a block whose
  parent was a long-accepted ancestor verified, and accepting it rewound
  the tip and left the height index naming an orphan to every peer that
  bootstraps from it. Verify now requires the parent to be the tip or a
  block above it, and Accept re-checks against the tip, which moves
  between the two.

  Vertex.Verify checked its transactions and nothing else — no parent, no
  height — so a vertex naming no parent at height 1<<40 verified, and
  accepting it set the store's height to 1<<40 and left the chain unable
  to propose again. Its decoder also ignored trailing bytes, so one
  logical vertex had unboundedly many encodings under one id, each of
  which the store writes to disk.

  BuildBlock skipped the ValidateBasic that Verify runs, so a transaction
  with an out-of-range Type — read straight off the wire — was assembled
  into every block and refused by every node including the proposer, and
  nothing evicted it. admit is now that one predicate, assembly drops what
  it cannot build, and a transaction names an expiry so a bounded pool
  drains.

  BuildBlock stamped an unclamped time.Now(), which is below a parent
  legally up to maxClockSkew ahead — a block its own Verify refuses.

  ParseBlock never tracked what it parsed and SetPreference discarded it,
  so a follower could verify the first block of a run and not the second.

  A genesis naming no timestamp was stamped with the wall clock, hashed
  into the genesis id: one genesis file, a different chain per node and
  per restart.

  VerifyBlockProof took a GPU path on accel.Available() — a second, inline
  copy of the Groth16 checks that consulted neither the cache nor the
  dummy-key refusal — so whether a block was accepted turned on whether
  the node had an accelerator.

Reads that failed were reported as absence: the spent set answered "not
spent" for a set it could not read, which is the whole double-spend gate;
the state root answered "empty" at boot AND on rollback, where it also
returned nil; the UTXO store answered "not found". Each now reports the
failure.

Deleted, none of it reachable: a node-side wallet holding plaintext
spending keys behind an HTTP endpoint, with a loadAddresses that returned
nil so the keys were unusable anyway; note construction and the package's
only panic; an FHE processor whose verifier tested len(proof) >= 128 and
whose "encryption" wrote the plaintext into the first eight bytes; a
zwitness carrying a TODO; a 256-level sparse Merkle tree that computed no
root and wrote its cache under a read lock; six endpoints answering "Not
implemented"; a Signature field nothing verified; and eight config knobs
nothing read. The endpoints that remain answer at the path the node mounts
them on, rather than behind a mux that dispatches on a path it never sees.

Coverage 58.9% -> 76.7% on a denominator 539 statements smaller.
2026-08-28 15:02:32 -07:00

169 lines
5.6 KiB
Go

// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package zkvm
import (
"errors"
"sync"
"testing"
"github.com/luxfi/database"
"github.com/luxfi/database/memdb"
"github.com/luxfi/log"
"github.com/stretchr/testify/require"
)
// spentOf asks the spent set, and fails the test on a read that FAILED rather
// than reading it as "not spent" — which is the shape the production code had
// and the shape that reopens a double spend.
func spentOf(t *testing.T, ndb *NullifierDB, nullifier []byte) bool {
t.Helper()
_, spent, err := ndb.Spent(nullifier)
require.NoError(t, err)
return spent
}
// brokenDB fails every read with something that is NOT ErrNotFound.
type brokenDB struct {
database.Database
err error
}
func (d *brokenDB) Get([]byte) ([]byte, error) { return nil, d.err }
// TestSpentCountIsReadOffTheRecords pins that the count describes the records
// and cannot drift from them. It starts from the state a total kept alongside
// would disagree with: a record on disk with no counter beside it.
func TestSpentCountIsReadOffTheRecords(t *testing.T) {
db := memdb.New()
// The record landed; a counter write, had there been one, did not.
require.NoError(t, db.Put(makeNullifierKey([]byte("orphan")), make([]byte, 8)))
ndb, err := NewNullifierDB(db, log.NoLog{})
require.NoError(t, err)
require.True(t, spentOf(t, ndb, []byte("orphan")), "the set is rebuilt from the records")
require.Equal(t, uint64(1), ndb.GetNullifierCount(),
"the count is read off the records, so it cannot disagree with the set it describes")
}
// The count follows ordinary spending, and a nullifier is spent once.
func TestSpentCountFollowsTheSet(t *testing.T) {
ndb, err := NewNullifierDB(memdb.New(), log.NoLog{})
require.NoError(t, err)
require.Zero(t, ndb.GetNullifierCount())
require.NoError(t, ndb.MarkNullifierSpent([]byte("a"), 1))
require.NoError(t, ndb.MarkNullifierSpent([]byte("b"), 2))
require.Equal(t, uint64(2), ndb.GetNullifierCount())
// The set is permanent: spending the same note again is refused, and there
// is no removal path that could make room for it.
require.ErrorIs(t, ndb.MarkNullifierSpent([]byte("a"), 3), errNullifierSpent)
require.Equal(t, uint64(2), ndb.GetNullifierCount())
height, spent, err := ndb.Spent([]byte("b"))
require.NoError(t, err)
require.True(t, spent)
require.Equal(t, uint64(2), height, "the set records which block spent the note")
_, spent, err = ndb.Spent([]byte("never"))
require.NoError(t, err)
require.False(t, spent)
}
// A read that FAILED is not "not spent". The old IsNullifierSpent ended
// `_, err := Get(key); return err == nil`, so an unreadable set answered "this
// note is unspent" for every note in it — and verifyTransaction, whose only
// double-spend gate that is, admitted the spend.
func TestFailedReadIsNotAnUnspentNote(t *testing.T) {
boom := errors.New("disk gone")
ndb, err := NewNullifierDB(memdb.New(), log.NoLog{})
require.NoError(t, err)
ndb.db = &brokenDB{Database: ndb.db, err: boom}
_, spent, err := ndb.Spent([]byte("n"))
require.ErrorIs(t, err, boom)
require.False(t, spent)
}
// TestNullifierReadDoesNotWriteTheSet. Spent must not memoise what it loaded
// while holding only the read lock: a read lock promises every other reader
// that nothing is changing, so two callers missing at once would write the same
// map at the same time, which is a runtime throw that takes the process down
// rather than an error anyone can handle. Consensus and RPC both sit here.
func TestNullifierReadDoesNotWriteTheSet(t *testing.T) {
ndb, err := NewNullifierDB(memdb.New(), log.NoLog{})
require.NoError(t, err)
require.NoError(t, ndb.MarkNullifierSpent([]byte("n"), 4))
// A record on disk that the in-memory set does not know about is what a
// memoising read would fill in.
ndb.spent = map[string]uint64{}
var readers sync.WaitGroup
for i := 0; i < 8; i++ {
readers.Add(1)
go func() {
defer readers.Done()
height, spent, err := ndb.Spent([]byte("n"))
switch {
case err != nil:
t.Errorf("read failed: %v", err)
case !spent:
t.Error("record on disk read as unspent")
case height != 4:
t.Errorf("read height %d, want 4", height)
}
}()
}
readers.Wait()
require.Empty(t, ndb.spent, "a read must not change the set it reads")
}
// TestShortRecordIsNotAHeight. Blocks are stored in the same database under
// their raw id, so the nullifier prefix can turn up over a value that is not a
// height. load already passes over anything that is not eight bytes; the read
// path has to agree with it, or reading one of those is a panic where a miss
// was meant.
func TestShortRecordIsNotAHeight(t *testing.T) {
db := memdb.New()
require.NoError(t, db.Put(makeNullifierKey([]byte("n")), []byte{1}))
ndb, err := NewNullifierDB(db, log.NoLog{})
require.NoError(t, err)
require.Zero(t, ndb.GetNullifierCount())
_, _, err = ndb.Spent([]byte("n"))
require.ErrorContains(t, err, "not a height")
}
// A set that cannot be read at startup is not an empty set.
func TestUnreadableSetDoesNotOpen(t *testing.T) {
boom := errors.New("iterator gone")
_, err := NewNullifierDB(&failIterDB{Database: memdb.New(), err: boom}, log.NoLog{})
require.ErrorIs(t, err, boom)
}
type failIterDB struct {
database.Database
err error
}
func (d *failIterDB) NewIteratorWithPrefix([]byte) database.Iterator {
return &brokenIter{err: d.err}
}
type brokenIter struct {
database.Iterator
err error
}
func (i *brokenIter) Next() bool { return false }
func (i *brokenIter) Error() error { return i.err }
func (i *brokenIter) Release() {}
func (i *brokenIter) Key() []byte { return nil }
func (i *brokenIter) Value() []byte { return nil }