Files
chains/zkvm/nullifier_db.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

170 lines
5.1 KiB
Go

// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package zkvm
import (
"encoding/binary"
"errors"
"sync"
"github.com/luxfi/log"
"github.com/luxfi/database"
)
// nullifierPrefix keys the spent set. A nullifier record is the height of the
// block that spent it.
const nullifierPrefix = 0x20
var errNullifierSpent = errors.New("zkvm: nullifier already spent")
// NullifierDB is the spent set: the whole of what stops a shielded note being
// spent twice.
type NullifierDB struct {
db database.Database
log log.Logger
// spent is the entire set, loaded at startup and never pruned — which is
// why the count is read off it rather than kept beside it and reconciled.
spent map[string]uint64 // nullifier -> height when spent
mu sync.RWMutex
}
// NewNullifierDB creates a new nullifier database
func NewNullifierDB(db database.Database, log log.Logger) (*NullifierDB, error) {
ndb := &NullifierDB{
db: db,
log: log,
spent: make(map[string]uint64),
}
if err := ndb.load(); err != nil {
return nil, err
}
return ndb, nil
}
// MarkNullifierSpent records a spend.
func (ndb *NullifierDB) MarkNullifierSpent(nullifier []byte, height uint64) error {
ndb.mu.Lock()
defer ndb.mu.Unlock()
key := string(nullifier)
if _, exists := ndb.spent[key]; exists {
return errNullifierSpent
}
heightBytes := make([]byte, 8)
binary.BigEndian.PutUint64(heightBytes, height)
if err := ndb.db.Put(makeNullifierKey(nullifier), heightBytes); err != nil {
return err
}
ndb.spent[key] = height
ndb.log.Debug("Marked nullifier as spent",
log.Uint64("height", height),
log.Int("nullifiers", len(ndb.spent)),
)
return nil
}
// Spent reports whether a nullifier has been spent and at what height.
//
// It is ONE question with one answer, because the two it used to be —
// IsNullifierSpent returning a bool and GetNullifierHeight returning a height —
// could not report a failed read at all. `_, err := Get(key); return err == nil`
// answers "not spent" for a set that could not be read, and that answer is what
// lets an already-spent note be spent again. A read that failed is an error
// here, and verifyTransaction refuses the transaction rather than admitting it.
//
// A miss falls through to the records and returns what it finds without
// memoising it. Memoising would be a write on a path that holds only the read
// lock, and a read lock promises every other reader that nothing is changing:
// two callers missing at once would write the same map at the same time, which
// is a runtime throw, not a returned error. The write lock is not the answer
// either — it would serialise every reader of a path consensus and RPC both sit
// on, to save a lookup the set already answers.
func (ndb *NullifierDB) Spent(nullifier []byte) (uint64, bool, error) {
ndb.mu.RLock()
defer ndb.mu.RUnlock()
if height, exists := ndb.spent[string(nullifier)]; exists {
return height, true, nil
}
raw, err := ndb.db.Get(makeNullifierKey(nullifier))
switch {
case errors.Is(err, database.ErrNotFound):
return 0, false, nil
case err != nil:
return 0, false, err
case len(raw) != 8:
return 0, false, errors.New("zkvm: nullifier record is not a height")
}
return binary.BigEndian.Uint64(raw), true, nil
}
// GetNullifierCount returns the number of spent nullifiers, counted off the set
// itself. Every record is loaded at startup and nullifiers are never pruned, so
// the set is the whole of them; a total kept alongside would be a second write
// that has to agree with the first, and this cannot disagree with what it
// describes.
func (ndb *NullifierDB) GetNullifierCount() uint64 {
ndb.mu.RLock()
defer ndb.mu.RUnlock()
return uint64(len(ndb.spent))
}
// Nullifiers are permanent and MUST NOT be pruned or removed. Deleting a spent
// nullifier lets a previously spent note be spent again, so there is no
// removal path here — not for reorg, not for compaction. If storage becomes a
// concern, a Merkle accumulator is the compaction.
// load reads the whole set from the database.
func (ndb *NullifierDB) load() error {
it := ndb.db.NewIteratorWithPrefix([]byte{nullifierPrefix})
defer it.Release()
for it.Next() {
key, val := it.Key(), it.Value()
if len(key) < 2 || len(val) != 8 {
continue
}
ndb.spent[string(key[1:])] = binary.BigEndian.Uint64(val)
}
return it.Error()
}
// reload rebuilds the set from what the database now says. A block whose
// writes were discarded has had its nullifiers discarded with them, so a set
// that already recorded them must stop claiming those notes are spent —
// otherwise the block can never be applied again.
func (ndb *NullifierDB) reload() error {
ndb.mu.Lock()
defer ndb.mu.Unlock()
ndb.spent = make(map[string]uint64)
return ndb.load()
}
// makeNullifierKey creates a database key for a nullifier
func makeNullifierKey(nullifier []byte) []byte {
key := make([]byte, 1+len(nullifier))
key[0] = nullifierPrefix
copy(key[1:], nullifier)
return key
}
// Close closes the nullifier database
func (ndb *NullifierDB) Close() {
ndb.mu.Lock()
defer ndb.mu.Unlock()
ndb.spent = nil
}