database

package
v0.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2021 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const AddrIndexKeySize = ripemd160.Size + 1

AddrIndexKeySize is the number of bytes used by keys into the BlockAddrIndex.

Variables

View Source
var (
	ErrAddrIndexDoesNotNeedInit = errors.New("address index has been initialized")
	ErrAddrIndexDoesNotExist    = errors.New("address index hasn't been built or is an older version")
	ErrAddrIndexVersionNotFound = errors.New("address index version not found")
	ErrAddrIndexInvalidVersion  = errors.New("address index version is not allowed")
	ErrUnsupportedAddressType   = errors.New("address type is not supported by the address-index")
	ErrTxShaMissing             = errors.New("requested transaction does not exist")
	ErrBlockShaMissing          = errors.New("requested block does not exist")
	ErrDuplicateSha             = errors.New("duplicate insert attempted")
	ErrDbDoesNotExist           = errors.New("non-existent database")
	ErrDbUnknownType            = errors.New("non-existent database type")
	ErrNotImplemented           = errors.New("method has not yet been implemented")
	ErrInvalidBlockStorageMeta  = errors.New("invalid block storage meta")
	ErrInvalidAddrIndexMeta     = errors.New("invalid addr index meta")
	ErrDeleteNonNewestBlock     = errors.New("delete block that is not newest")
)

Errors that the various database functions may return.

Functions

func AddDBDriver

func AddDBDriver(instance DriverDB)

AddDBDriver adds a back end database driver to available interfaces.

func SupportedDBs

func SupportedDBs() []string

SupportedDBs returns a slice of strings that represent the database drivers that have been registered and are therefore supported.

Types

type AddrIndexData

type AddrIndexData struct {
	TxIndex             TxAddrIndex
	BindingTxIndex      BindingTxAddrIndex
	BindingTxSpentIndex BindingTxSpentAddrIndex
}

type AddrIndexOutPoint

type AddrIndexOutPoint struct {
	TxLoc *wire.TxLoc
	Index uint32
}

type BLHeight

type BLHeight struct {
	BitLength int
	BlkHeight uint64
}

type BindingTxAddrIndex

type BindingTxAddrIndex map[[ripemd160.Size]byte][]*AddrIndexOutPoint

type BindingTxReply

type BindingTxReply struct {
	Height     uint64
	TxSha      *wire.Hash
	IsCoinbase bool
	Value      int64
	Index      uint32
}

type BindingTxSpent

type BindingTxSpent struct {
	SpentTxLoc   *wire.TxLoc
	BTxBlkHeight uint64
	BTxLoc       *wire.TxLoc
	BTxIndex     uint32
}

type BindingTxSpentAddrIndex

type BindingTxSpentAddrIndex map[[ripemd160.Size]byte][]*BindingTxSpent

type BlockAddrIndex

type BlockAddrIndex map[[AddrIndexKeySize]byte][]*AddrIndexOutPoint

BlockAddrIndex represents the indexing structure for addresses. It maps a hash160 to a list of transaction locations within a block that either pays to or spends from the passed UTXO for the hash160.

type BlockLoc

type BlockLoc struct {
	Height uint64
	Hash   wire.Hash
	File   uint32
	Offset uint64
	Length uint64
}

type Db

type Db interface {
	// Close cleanly shuts down the database and syncs all data.
	Close() (err error)

	// RollbackClose discards the recent database changes to the previously
	// saved data at last Sync and closes the database.
	RollbackClose() (err error)
	Rollback()

	// Sync verifies that the database is coherent on disk and no
	// outstanding transactions are in flight.
	Sync() (err error)

	// Commit commits batches in a single transaction
	Commit(hash wire.Hash) error

	// InitByGenesisBlock init database by setting genesis block
	InitByGenesisBlock(block *massutil.Block) (err error)

	// SubmitBlock inserts raw block and transaction data from a block
	// into the database.  The first block inserted into the database
	// will be treated as the genesis block.  Every subsequent block insert
	// requires the referenced parent block to already exist.
	SubmitBlock(block *massutil.Block) (err error)

	// DeleteBlock will remove any blocks from the database after
	// the given block.  It terminates any existing transaction and performs
	// its operations in an atomic transaction which is committed before
	// the function returns.
	DeleteBlock(hash *wire.Hash) (err error)

	// ExistsSha returns whether or not the given block hash is present in
	// the database.
	ExistsSha(sha *wire.Hash) (exists bool, err error)

	// FetchBlockBySha returns a massutil Block.  The implementation may
	// cache the underlying data if desired.
	FetchBlockBySha(sha *wire.Hash) (blk *massutil.Block, err error)

	// FetchBlockHeightBySha returns the block height for the given hash.
	FetchBlockHeightBySha(sha *wire.Hash) (height uint64, err error)

	// FetchBlockHeaderBySha returns a wire.BlockHeader for the given
	// sha.  The implementation may cache the underlying data if desired.
	FetchBlockHeaderBySha(sha *wire.Hash) (bh *wire.BlockHeader, err error)

	// FetchBlockShaByHeight returns a block hash based on its height in the
	// block chain.
	FetchBlockShaByHeight(height uint64) (sha *wire.Hash, err error)

	FetchBlockLocByHeight(height uint64) (*BlockLoc, error)

	// ExistsTxSha returns whether or not the given tx hash is present in
	// the database
	ExistsTxSha(sha *wire.Hash) (exists bool, err error)

	FetchTxByLoc(blkHeight uint64, txOff int, txLen int) (*wire.MsgTx, error)

	// FetchTxByFileLoc returns transactions saved in file, including
	// those revoked with chain reorganization, for file is in APPEND mode.
	FetchTxByFileLoc(blkLoc *BlockLoc, txLoc *wire.TxLoc) (*wire.MsgTx, error)

	// FetchTxBySha returns some data for the given transaction hash. The
	// implementation may cache the underlying data if desired.
	FetchTxBySha(txsha *wire.Hash) ([]*TxReply, error)

	// GetTxData returns the block height, txOffset, txLen for the given transaction hash,
	// including unspent and fully spent transaction
	GetUnspentTxData(txsha *wire.Hash) (uint64, int, int, error)

	// FetchTxByShaList returns a TxReply given an array of transaction
	// hashes.  The implementation may cache the underlying data if desired.
	// This differs from FetchUnSpentTxByShaList in that it will return
	// the most recent known Tx, if it is fully spent or not.
	//
	// NOTE: This function does not return an error directly since it MUST
	// return at least one TxReply instance for each requested
	// transaction.  Each TxReply instance then contains an Err field
	// which can be used to detect errors.
	FetchTxByShaList(txShaList []*wire.Hash) []*TxReply

	// Returns database.ErrTxShaMissing if no transaction found
	FetchLastFullySpentTxBeforeHeight(txsha *wire.Hash, height uint64) (tx *wire.MsgTx, blkheight uint64, blksha *wire.Hash, err error)

	// FetchUnSpentTxByShaList returns a TxReply given an array of
	// transaction hashes.  The implementation may cache the underlying
	// data if desired. Fully spent transactions will not normally not
	// be returned in this operation.
	//
	// NOTE: This function does not return an error directly since it MUST
	// return at least one TxReply instance for each requested
	// transaction.  Each TxReply instance then contains an Err field
	// which can be used to detect errors.
	FetchUnSpentTxByShaList(txShaList []*wire.Hash) []*TxReply

	// FetchUnexpiredStakingRank returns only currently unexpired staking rank at
	// target height. This function is for mining and validating block.
	FetchUnexpiredStakingRank(height uint64, onlyOnList bool) ([]Rank, error)

	// FetchStakingRank returns staking rank at any height. This
	// function may be slow.
	FetchStakingRank(height uint64, onlyOnList bool) ([]Rank, error)

	// fetch a map of all staking transactions in database
	FetchStakingTxMap() (StakingNodes, error)

	FetchExpiredStakingTxListByHeight(height uint64) (StakingNodes, error)

	FetchHeightRange(startHeight, endHeight uint64) ([]wire.Hash, error)

	// NewestSha returns the hash and block height of the most recent (end)
	// block of the block chain.  It will return the zero hash, -1 for
	// the block height, and no error (nil) if there are not any blocks in
	// the database yet.
	NewestSha() (sha *wire.Hash, height uint64, err error)

	// FetchFaultPkBySha returns the FaultPubKey by Hash of that PubKey.
	// Hash = DoubleHashB(PubKey.SerializeUnCompressed()).
	// It will return ErrNotFound if this PubKey is not banned.
	FetchFaultPkBySha(sha *wire.Hash) (fpk *wire.FaultPubKey, height uint64, err error)

	FetchAllFaultPks() ([]*wire.FaultPubKey, []uint64, error)

	// FetchFaultPkListByHeight returns the newly added FaultPubKey List
	// on given height. It will return ErrNotFound if this height has not
	// mined. And will return empty slice if there aren't any new banned Pks.
	FetchFaultPkListByHeight(blkHeight uint64) ([]*wire.FaultPubKey, error)

	// ExistsFaultPk returns whether or not the given FaultPubKey hash is present in
	// the database.
	ExistsFaultPk(sha *wire.Hash) (bool, error)

	// FetchAllPunishment returns all faultPubKey stored in db, with random order.
	FetchAllPunishment() ([]*wire.FaultPubKey, error)

	// ExistsPunishment returns whether or not the given PoC PublicKey is present in
	// the database.
	ExistsPunishment(pk interfaces.PublicKey) (bool, error)

	// InsertPunishment insert a fpk into punishment storage instantly.
	InsertPunishment(fpk *wire.FaultPubKey) error

	FetchMinedBlocks(pubKey interfaces.PublicKey) ([]uint64, error)

	// FetchAddrIndexTip returns the hash and block height of the most recent
	// block which has had its address index populated. It will return
	// ErrAddrIndexDoesNotExist along with a zero hash, and math.MaxUint64 if
	// it hasn't yet been built up.
	FetchAddrIndexTip() (sha *wire.Hash, height uint64, err error)

	SubmitAddrIndex(hash *wire.Hash, height uint64, addrIndexData *AddrIndexData) (err error)

	DeleteAddrIndex(hash *wire.Hash, height uint64) (err error)

	// FetchScriptHashRelatedTx  returns all relevant txhash mapped by block height
	FetchScriptHashRelatedTx(scriptHashes [][]byte, startBlock, stopBlock uint64) (map[uint64][]*wire.TxLoc, error)

	CheckScriptHashUsed(scriptHash []byte) (bool, error)

	// pubkeyHash is hash of MASS plot pubkey
	FetchOldBinding(pubkeyHash []byte) ([]*BindingTxReply, error)

	// For testing purpose
	TestExportDbEntries() map[string][]byte
}

Db defines a generic interface that is used to request and insert data into the mass block chain. This interface is intended to be agnostic to actual mechanism used for backend data storage. The AddDBDriver function can be used to add a new backend data storage method.

Example (NewestSha)

This example demonstrates querying the database for the most recent best block height and hash.

package main

import (
	"fmt"

	"github.com/gnc-project/mass-core/config"
	"github.com/gnc-project/mass-core/database"
	"github.com/gnc-project/mass-core/database/memdb"
	"github.com/gnc-project/mass-core/massutil"
)

// exampleLoadDB is used in the example to elide the setup code.
func exampleLoadDB() (database.Db, error) {
	db, err := memdb.NewMemDb()
	if err != nil {
		return nil, err
	}

	genesis := massutil.NewBlock(config.ChainParams.GenesisBlock)
	err = db.InitByGenesisBlock(genesis)
	if err != nil {
		return nil, err
	}

	return db, err
}

func main() {
	// Load a database for the purposes of this example and schedule it to
	// be closed on exit.  See the CreateDB example for more details on what
	// this step is doing.
	db, err := exampleLoadDB()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	latestHash, latestHeight, err := db.NewestSha()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Latest hash:", latestHash)
	fmt.Println("Latest height:", latestHeight)

}
Output:

Latest hash: ee26300e0f068114a680a772e080507c0f9c0ca4335c382c42b78e2eafbebaa3
Latest height: 0

func CreateDB

func CreateDB(dbtype string, args ...interface{}) (pbdb Db, err error)

CreateDB intializes and opens a database.

Example

This example demonstrates creating a new database and inserting the genesis block into it.

package main

import (
	"fmt"

	"github.com/gnc-project/mass-core/config"
	"github.com/gnc-project/mass-core/database/memdb"
	"github.com/gnc-project/mass-core/massutil"
)

func main() {
	// Notice in these example imports that the memdb driver is loaded.
	// Ordinarily this would be whatever driver(s) your application
	// requires.

	// Create a database and schedule it to be closed on exit.  This example
	// uses a memory-only database to avoid needing to write anything to
	// the disk.  Typically, you would specify a persistent database driver
	// such as "leveldb" and give it a database name as the second
	// parameter.
	db, err := memdb.NewMemDb()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	// Insert the main network genesis block.
	genesis := massutil.NewBlock(config.ChainParams.GenesisBlock)
	err = db.InitByGenesisBlock(genesis)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("New height:", genesis.Height())

}
Output:

New height: 0

func OpenDB

func OpenDB(dbtype, path string, readonly bool, args ...interface{}) (pbdb Db, err error)

OpenDB opens an existing database.

type DriverDB

type DriverDB struct {
	DbType   string
	CreateDB func(args ...interface{}) (pbdb Db, err error)
	OpenDB   func(path string, readonly bool, args ...interface{}) (pbdb Db, err error)
}

DriverDB defines a structure for backend drivers to use when they registered themselves as a backend which implements the Db interface.

type Pair

type Pair struct {
	Key    [sha256.Size]byte
	Value  int64
	Weight *safetype.Uint128
}

type PairList

type PairList struct {
	// contains filtered or unexported fields
}

func (PairList) Len

func (pl PairList) Len() int

func (PairList) Less

func (pl PairList) Less(i, j int) bool

func (PairList) Swap

func (pl PairList) Swap(i, j int)

type Pairs

type Pairs []Pair

func SortMap

func SortMap(m map[[sha256.Size]byte][]StakingTxInfo, newestHeight uint64, isOnlyReward bool) (Pairs, error)

func (Pairs) Len

func (p Pairs) Len() int

func (Pairs) Less

func (p Pairs) Less(i, j int) bool

func (Pairs) Swap

func (p Pairs) Swap(i, j int)

type Rank

type Rank struct {
	Rank       int32
	Value      int64
	ScriptHash [sha256.Size]byte
	Weight     *safetype.Uint128
	StakingTx  []StakingTxInfo
}

func (Rank) GetValue

func (r Rank) GetValue() int64

func (Rank) GetWeight

func (r Rank) GetWeight() *safetype.Uint128

type StakingNodes

type StakingNodes map[[sha256.Size]byte]StakingTxOutAtHeight

func (StakingNodes) Delete

func (nodes StakingNodes) Delete(key [sha256.Size]byte, blkHeight uint64, op wire.OutPoint) bool

func (StakingNodes) Get

func (StakingNodes) IsEmpty

func (nodes StakingNodes) IsEmpty(key [sha256.Size]byte) bool

type StakingTxInfo

type StakingTxInfo struct {
	Value        uint64
	FrozenPeriod uint64
	BlkHeight    uint64
}

func (StakingTxInfo) GetBlockHeight

func (s StakingTxInfo) GetBlockHeight() uint64

func (StakingTxInfo) GetFrozenPeriod

func (s StakingTxInfo) GetFrozenPeriod() uint64

type StakingTxOutAtHeight

type StakingTxOutAtHeight map[uint64]map[wire.OutPoint]StakingTxInfo

func (StakingTxOutAtHeight) Put

func (sh StakingTxOutAtHeight) Put(op wire.OutPoint, stk StakingTxInfo) (success bool)

Returns false if already exists

type TxAddrIndex

type TxAddrIndex map[[sha256.Size]byte][]*wire.TxLoc

BlockTxAddrIndex represents the indexing structure for txs

type TxReply

type TxReply struct {
	Sha     *wire.Hash
	Tx      *wire.MsgTx
	BlkSha  *wire.Hash
	Height  uint64
	TxSpent []bool
	Err     error
}

TxReply is used to return individual transaction information when data about multiple transactions is requested in a single call.

type UtxoReply

type UtxoReply struct {
	TxSha    *wire.Hash
	Height   uint64
	Coinbase bool
	Index    uint32
	Value    massutil.Amount
}

Directories

Path Synopsis
ldb
This file is only used to check data correctness for 1.1.0
This file is only used to check data correctness for 1.1.0
Package memdb implements an instance of the database package that uses memory for the block storage.
Package memdb implements an instance of the database package that uses memory for the block storage.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL