Files
ark/asp/internal/infrastructure/db/badger/vtxo_repo.go
Pietralberto Mazza 3985bd4e14 Cleanup & Add config and launcher (#57)
* Fixes

* Fixes to domain layer:
* Add Leaf bool field to know to fix the returned list of leaves
* Add non-persisted UnsignedForfeitTxs to RoundFinalizationStarted
* Store only error msg when round fails instead of full error

* Fix wallet interface:
* Add Close() to close conn with wallet
* Add GetAsset() to fix missing asset err when calling Transfer()

* Fix gocron scheduler to correctly run/build the project

* Fix badger repo implementation:
* Fix datadirs of projection stores
* Return error if current round not found
* Fix round event deserialization

* Fix TxBuilder interface & dummy impl:
* Pass asp pubkey as arg of the defined functions
* Fix connectorsToInputArgs to return the right number of ins
* Fix getTxid() to return the id of an hex encoded tx too
* Fix createConnectors() to return a tx if there's only 1 connector
* Add leaf bool field to psetWithLevel in case a leaf is not in the last level
* Fix node's isLeaf() check
* Move to hex encoded pubkeys instead of ark encoded

* Fix app layer:
* Add Start() and Stop() to the interface & Expect raw pubkeys instead of strings as args
* Source & cache pubkey from wallet at startup
* Drop usage of scheduler and schedule next task based on occurred round events
* Increase verbosity
* Use hex instead of ark encoding to store receveirs' pubkeys
* Lower faucet amount from 100k to 10k sats in total
* Fix finalizeRound() to persist round events even if it failed
* Add view() to forfeitTxMap to enrich RoundFinalizationEvent with unsigned forfeit txs

* Add app config

* Fix interface layer:
* Remove repo manager from handler factory
* Fix GetEventStream to forward events to stream once they arrive from app layer
* Return missing unsigned forfeit txs in RoundFinalizationEvent
* Fix extracting user pubkey from address
* Add log interceptors
* Add config struct
* Add factory
* Clean interface

* Add config and launcher

* Tidy deps & Set defaut round interval to 30secs for dev mode
2023-12-12 14:55:22 +01:00

158 lines
3.5 KiB
Go

package badgerdb
import (
"context"
"fmt"
"path/filepath"
"github.com/ark-network/ark/internal/core/domain"
dbtypes "github.com/ark-network/ark/internal/infrastructure/db/types"
"github.com/dgraph-io/badger/v4"
"github.com/timshannon/badgerhold/v4"
)
const vtxoStoreDir = "vtxos"
type vtxoRepository struct {
store *badgerhold.Store
}
func NewVtxoRepository(config ...interface{}) (dbtypes.VtxoStore, error) {
if len(config) != 2 {
return nil, fmt.Errorf("invalid config")
}
baseDir, ok := config[0].(string)
if !ok {
return nil, fmt.Errorf("invalid base directory")
}
var logger badger.Logger
if config[1] != nil {
logger, ok = config[1].(badger.Logger)
if !ok {
return nil, fmt.Errorf("invalid logger")
}
}
var dir string
if len(baseDir) > 0 {
dir = filepath.Join(baseDir, vtxoStoreDir)
}
store, err := createDB(dir, logger)
if err != nil {
return nil, fmt.Errorf("failed to open round events store: %s", err)
}
return &vtxoRepository{store}, nil
}
func (r *vtxoRepository) AddVtxos(
ctx context.Context, vtxos []domain.Vtxo,
) error {
return r.addVtxos(ctx, vtxos)
}
func (r *vtxoRepository) SpendVtxos(
ctx context.Context, vtxoKeys []domain.VtxoKey,
) error {
for _, vtxoKey := range vtxoKeys {
if err := r.spendVtxo(ctx, vtxoKey); err != nil {
return err
}
}
return nil
}
func (r *vtxoRepository) GetVtxos(
ctx context.Context, vtxoKeys []domain.VtxoKey,
) ([]domain.Vtxo, error) {
vtxos := make([]domain.Vtxo, 0, len(vtxoKeys))
for _, vtxoKey := range vtxoKeys {
vtxo, err := r.getVtxo(ctx, vtxoKey)
if err != nil {
return nil, err
}
vtxos = append(vtxos, *vtxo)
}
return vtxos, nil
}
func (r *vtxoRepository) GetSpendableVtxosWithPubkey(
ctx context.Context, pubkey string,
) ([]domain.Vtxo, error) {
query := badgerhold.Where("Pubkey").Eq(pubkey).And("Spent").Eq(false)
return r.findVtxos(ctx, query)
}
func (r *vtxoRepository) Close() {
r.store.Close()
}
func (r *vtxoRepository) addVtxos(
ctx context.Context, vtxos []domain.Vtxo,
) (err error) {
for _, vtxo := range vtxos {
vtxoKey := vtxo.VtxoKey.Hash()
if ctx.Value("tx") != nil {
tx := ctx.Value("tx").(*badger.Txn)
err = r.store.TxInsert(tx, vtxoKey, vtxo)
} else {
err = r.store.Insert(vtxoKey, vtxo)
}
}
if err != nil && err == badgerhold.ErrKeyExists {
err = nil
}
return
}
func (r *vtxoRepository) getVtxo(
ctx context.Context, vtxoKey domain.VtxoKey,
) (*domain.Vtxo, error) {
var vtxo domain.Vtxo
var err error
if ctx.Value("tx") != nil {
tx := ctx.Value("tx").(*badger.Txn)
err = r.store.TxGet(tx, vtxoKey.Hash(), &vtxo)
} else {
err = r.store.Get(vtxoKey.Hash(), &vtxo)
}
if err != nil && err == badgerhold.ErrNotFound {
return nil, fmt.Errorf("vtxo %s:%d not found", vtxoKey.Txid, vtxoKey.VOut)
}
return &vtxo, nil
}
func (r *vtxoRepository) spendVtxo(ctx context.Context, vtxoKey domain.VtxoKey) error {
vtxo, err := r.getVtxo(ctx, vtxoKey)
if err != nil {
return err
}
if vtxo.Spent {
return nil
}
vtxo.Spent = true
if ctx.Value("tx") != nil {
tx := ctx.Value("tx").(*badger.Txn)
err = r.store.TxUpdate(tx, vtxoKey.Hash(), *vtxo)
} else {
err = r.store.Update(vtxoKey.Hash(), *vtxo)
}
return err
}
func (r *vtxoRepository) findVtxos(ctx context.Context, query *badgerhold.Query) ([]domain.Vtxo, error) {
var vtxos []domain.Vtxo
var err error
if ctx.Value("tx") != nil {
tx := ctx.Value("tx").(*badger.Txn)
err = r.store.TxFind(tx, &vtxos, query)
} else {
err = r.store.Find(&vtxos, query)
}
return vtxos, err
}