Files
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

136 lines
3.8 KiB
Go

// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package zkvm
import (
"errors"
"fmt"
"sync"
"crypto/sha256"
"github.com/luxfi/log"
"github.com/luxfi/database"
)
// rootKey holds the committed state root.
var rootKey = []byte("state_root")
// Root is the committed state root and the fold that produces the next one.
//
// It was a "sparse Merkle tree": 256 levels, a node cache, GetMerkleProof and
// VerifyMerkleProof. None of it was reachable — the root is the SHA-256 fold
// below and always was — and the unreachable half held a map written under a
// READ lock, which in Go is a fatal throw rather than a bug you get to debug.
// A type named for a structure it does not have costs exactly that.
type Root struct {
db database.Database
log log.Logger
committed []byte
mu sync.RWMutex
}
// NewRoot opens the committed state root.
func NewRoot(db database.Database, log log.Logger) (*Root, error) {
r := &Root{db: db, log: log, committed: make([]byte, 32)}
if err := r.reload(); err != nil {
return nil, err
}
return r, nil
}
// After returns the state root that results from applying txs on top of the
// committed root, as SHA-256 over
//
// committed ‖ every output commitment (tx order) ‖ every nullifier (tx order)
//
// It is PURE: nothing is mutated, so computing a root is safe inside
// Block.Verify. Verifying the same block twice, or verifying a block that is
// later rejected and then verifying its competitor, all yield the root that
// block's proposer computed. Only Finalize advances the committed root, and
// only Accept calls Finalize.
//
// There is exactly ONE root function. A hardware-conditional digest (a GPU
// Poseidon path with a SHA-256 fallback) would make the consensus-committed
// root depend on whether the node has an accelerator, so validators with and
// without one would reject each other's blocks.
func (r *Root) After(txs []*Transaction) []byte {
r.mu.RLock()
defer r.mu.RUnlock()
h := sha256.New()
h.Write(r.committed)
for _, tx := range txs {
for _, output := range tx.Outputs {
h.Write(output.Commitment)
}
}
for _, tx := range txs {
for _, nullifier := range tx.Nullifiers {
h.Write(nullifier)
}
}
return h.Sum(nil)
}
// Finalize advances the committed root. It is the only mutation, and Accept is
// its only caller.
func (r *Root) Finalize(next []byte) error {
r.mu.Lock()
defer r.mu.Unlock()
// The record first: a root held in memory that is not in the database is a
// root this node alone believes.
if err := r.db.Put(rootKey, next); err != nil {
return err
}
r.committed = next
r.log.Debug("State root finalized", log.String("root", fmt.Sprintf("%x", next[:8])))
return nil
}
// Get returns the committed state root.
func (r *Root) Get() []byte {
r.mu.RLock()
defer r.mu.RUnlock()
return r.committed
}
// reload puts the committed root back, discarding an advance that belonged to
// a block whose writes were discarded.
//
// A read that FAILED is not an absent root. Both the constructor and this
// rollback path used to answer any error with the empty root and report
// success — so an unreadable database booted the node believing the shielded
// state was empty, and it then disagreed with the network on every block it
// saw, permanently. Only database.ErrNotFound means a chain with no root yet.
func (r *Root) reload() error {
r.mu.Lock()
defer r.mu.Unlock()
raw, err := r.db.Get(rootKey)
switch {
case errors.Is(err, database.ErrNotFound):
r.committed = make([]byte, 32)
return nil
case err != nil:
return fmt.Errorf("zkvm: read state root: %w", err)
case len(raw) != 32:
return fmt.Errorf("zkvm: state root is %d bytes, want 32", len(raw))
}
r.committed = raw
return nil
}
// Close releases the root.
func (r *Root) Close() {
r.mu.Lock()
defer r.mu.Unlock()
r.committed = nil
}