Files
zeekayandHanzo Dev 938b06d485 Stop requiring the node this module is imported by
proto required luxfi/node and luxfi/node required proto, with no replace
directive on either side. The cycle was not load-bearing: most of it was proto
reaching into the node for packages proto already owns — p/warp, p/txs,
p/signer, p/stakeable, p/security, x/txs — which now name themselves.

Two were real. The UTXO components moved here, where the chains that use them
already live, and the node is the only other caller, so that dependency now
runs one way. And p/config held the node's chain manager to queue a chain the
P-Chain had accepted a CreateChainTx for; it calls one method, so it declares
one method. A P-Chain that imports the node to describe QueueChainCreation is
what made two modules require each other.

Dropping the requirement dropped a registration with it: lux.ParseUTXO is a
registry filled by an init, which the node used to link in on proto's behalf.
The packages that call it now say so themselves.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-06 12:49:55 -07:00

298 lines
6.4 KiB
Go

// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package lux
import (
"errors"
"github.com/luxfi/database"
"github.com/luxfi/database/linkeddb"
"github.com/luxfi/database/prefixdb"
"github.com/luxfi/ids"
"github.com/luxfi/metric"
"github.com/luxfi/cache"
"github.com/luxfi/cache/metercacher"
)
const (
utxoCacheSize = 8192
indexCacheSize = 64
)
var (
utxoPrefix = []byte("utxo")
indexPrefix = []byte("index")
)
// UTXOState is a thin wrapper around a database to provide, caching,
// serialization, and de-serialization for UTXOs.
type UTXOState interface {
UTXOReader
UTXOWriter
// Checksum returns the current UTXOChecksum.
Checksum() ids.ID
}
// UTXOReader is a thin wrapper around a database to provide fetching of UTXOs.
type UTXOReader interface {
UTXOGetter
// UTXOIDs returns the slice of IDs associated with [addr], starting after
// [previous].
// If [previous] is not in the list, starts at beginning.
// Returns at most [limit] IDs.
UTXOIDs(addr []byte, previous ids.ID, limit int) ([]ids.ID, error)
}
// UTXOGetter is a thin wrapper around a database to provide fetching of a UTXO.
type UTXOGetter interface {
// GetUTXO attempts to load a utxo.
GetUTXO(utxoID ids.ID) (*UTXO, error)
}
type UTXOAdder interface {
AddUTXO(utxo *UTXO)
}
type UTXODeleter interface {
DeleteUTXO(utxoID ids.ID)
}
// UTXOWriter is a thin wrapper around a database to provide storage and
// deletion of UTXOs.
type UTXOWriter interface {
// PutUTXO saves the provided utxo to storage.
PutUTXO(utxo *UTXO) error
// DeleteUTXO deletes the provided utxo.
DeleteUTXO(utxoID ids.ID) error
}
type utxoState struct {
// UTXO ID -> *UTXO. If the *UTXO is nil the UTXO doesn't exist
utxoCache cache.Cacher[ids.ID, *UTXO]
utxoDB database.Database
indexDB database.Database
indexCache cache.Cacher[string, linkeddb.LinkedDB]
trackChecksum bool
checksum ids.ID
}
// NewUTXOState returns a UTXOState backed by ZAP-native wire bytes (no
// codec.Manager): UTXO.Marshal on write, UTXO.Unmarshal on read. The
// fx-aware output dispatch that reconstructs the polymorphic Out is wired
// via this package's init() (utxo_parser.go) plus the stakeable
// LockedOutputHandler registration.
func NewUTXOState(
db database.Database,
trackChecksum bool,
) (UTXOState, error) {
s := &utxoState{
utxoCache: &cache.LRU[ids.ID, *UTXO]{Size: utxoCacheSize},
utxoDB: prefixdb.New(utxoPrefix, db),
indexDB: prefixdb.New(indexPrefix, db),
indexCache: &cache.LRU[string, linkeddb.LinkedDB]{Size: indexCacheSize},
trackChecksum: trackChecksum,
}
return s, s.initChecksum()
}
func NewMeteredUTXOState(
db database.Database,
metrics metric.Registerer,
trackChecksum bool,
) (UTXOState, error) {
registry, ok := metrics.(metric.Registry)
if !ok {
return nil, errors.New("metrics must be a Registry")
}
utxoCache, err := metercacher.New[ids.ID, *UTXO](
"utxo_cache",
registry,
&cache.LRU[ids.ID, *UTXO]{Size: utxoCacheSize},
)
if err != nil {
return nil, err
}
indexCache, err := metercacher.New[string, linkeddb.LinkedDB](
"index_cache",
registry,
&cache.LRU[string, linkeddb.LinkedDB]{
Size: indexCacheSize,
},
)
if err != nil {
return nil, err
}
s := &utxoState{
utxoCache: utxoCache,
utxoDB: prefixdb.New(utxoPrefix, db),
indexDB: prefixdb.New(indexPrefix, db),
indexCache: indexCache,
trackChecksum: trackChecksum,
}
return s, s.initChecksum()
}
func (s *utxoState) GetUTXO(utxoID ids.ID) (*UTXO, error) {
if utxo, found := s.utxoCache.Get(utxoID); found {
if utxo == nil {
return nil, database.ErrNotFound
}
return utxo, nil
}
bytes, err := s.utxoDB.Get(utxoID[:])
if err == database.ErrNotFound {
s.utxoCache.Put(utxoID, nil)
return nil, database.ErrNotFound
}
if err != nil {
return nil, err
}
// The key was in the database — ZAP-native decode (fx-aware Out dispatch).
utxo := &UTXO{}
if err := utxo.Unmarshal(bytes); err != nil {
return nil, err
}
s.utxoCache.Put(utxoID, utxo)
return utxo, nil
}
func (s *utxoState) PutUTXO(utxo *UTXO) error {
// ZAP-native: the same wire bytes flow to disk and across chains. No
// separate codec.Marshal step.
utxoBytes, err := utxo.Marshal()
if err != nil {
return err
}
utxoID := utxo.InputID()
s.updateChecksum(utxoID)
s.utxoCache.Put(utxoID, utxo)
if err := s.utxoDB.Put(utxoID[:], utxoBytes); err != nil {
return err
}
addressable, ok := utxo.Out.(Addressable)
if !ok {
return nil
}
addresses := addressable.Addresses()
for _, addr := range addresses {
indexList := s.getIndexDB(addr)
if err := indexList.Put(utxoID[:], nil); err != nil {
return err
}
}
return nil
}
func (s *utxoState) DeleteUTXO(utxoID ids.ID) error {
utxo, err := s.GetUTXO(utxoID)
if err == database.ErrNotFound {
return nil
}
if err != nil {
return err
}
s.updateChecksum(utxoID)
s.utxoCache.Put(utxoID, nil)
if err := s.utxoDB.Delete(utxoID[:]); err != nil {
return err
}
addressable, ok := utxo.Out.(Addressable)
if !ok {
return nil
}
addresses := addressable.Addresses()
for _, addr := range addresses {
indexList := s.getIndexDB(addr)
if err := indexList.Delete(utxoID[:]); err != nil {
return err
}
}
return nil
}
func (s *utxoState) UTXOIDs(addr []byte, start ids.ID, limit int) ([]ids.ID, error) {
indexList := s.getIndexDB(addr)
iter := indexList.NewIteratorWithStart(start[:])
defer iter.Release()
utxoIDs := []ids.ID(nil)
for len(utxoIDs) < limit && iter.Next() {
utxoID, err := ids.ToID(iter.Key())
if err != nil {
return nil, err
}
if utxoID == start {
continue
}
start = ids.Empty
utxoIDs = append(utxoIDs, utxoID)
}
return utxoIDs, iter.Error()
}
func (s *utxoState) Checksum() ids.ID {
return s.checksum
}
func (s *utxoState) getIndexDB(addr []byte) linkeddb.LinkedDB {
addrStr := string(addr)
if indexList, exists := s.indexCache.Get(addrStr); exists {
return indexList
}
indexDB := prefixdb.NewNested(addr, s.indexDB)
indexList := linkeddb.NewDefault(indexDB)
s.indexCache.Put(addrStr, indexList)
return indexList
}
func (s *utxoState) initChecksum() error {
if !s.trackChecksum {
return nil
}
it := s.utxoDB.NewIterator()
defer it.Release()
for it.Next() {
utxoID, err := ids.ToID(it.Key())
if err != nil {
return err
}
s.updateChecksum(utxoID)
}
return it.Error()
}
func (s *utxoState) updateChecksum(modifiedID ids.ID) {
if !s.trackChecksum {
return
}
s.checksum = s.checksum.XOR(modifiedID)
}