database

package
v0.0.0-...-8b83558 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package database contains blockchain models and database interfaces.

Index

Constants

This section is empty.

Variables

View Source
var ErrChainForked = errors.New("blockchain forked, start resync")

ErrChainForked signals a fork when another chain is 2+ blocks ahead.

Functions

This section is empty.

Types

type Account

type Account struct {
	ID      AccountID
	Nonce   uint64
	Balance uint64
}

Account represents an account/wallet on the blockchain.

type AccountID

type AccountID string

AccountID represents an account/wallet identifier on the blockchain. The ID is hex-encoded string of the last 20 bytes of the account public key.

func AccountIDFromHex

func AccountIDFromHex(hex string) (AccountID, error)

AccountIDFromHex takes a hex-encoded account ID, validates it and returns an AccountID.

func AccountIDFromPubKey

func AccountIDFromPubKey(pk ecdsa.PublicKey) AccountID

AccountIDFromPubKey converts the public key to AccountID.

func (AccountID) Verify

func (account AccountID) Verify() error

Verify verifies whether the underlying data represents a valid hex-encoded account format.

type Block

type Block struct {
	Header     BlockHeader
	MerkleTree *merkle.Tree[BlockTx]
}

Block represents a blockchain block.

func NewBlock

func NewBlock(blockData BlockData) (Block, error)

NewBlock converts BlockData to a Block.

func POW

func POW(
	ctx context.Context,
	beneficiaryID AccountID,
	difficulty uint16,
	miningReward uint64,
	prevBlock Block,
	stateRoot string,
	txs []BlockTx,
) (
	Block,
	error,
)

POW mines a block by finding a valid solution.

func (Block) Hex

func (b Block) Hex() (string, error)

Hex returns the block's unique hex-encoded hash.

func (Block) ValidateBlock

func (b Block) ValidateBlock(previousBlock Block, stateRoot string) error

ValidateBlock checks the block's integrity against the previous block and state.

type BlockData

type BlockData struct {
	Hash   string      `json:"hash"`
	Header BlockHeader `json:"block"`
	Trans  []BlockTx   `json:"trans"`
}

BlockData is a serializable block for network/disk.

func NewBlockData

func NewBlockData(block Block) (BlockData, error)

NewBlockData builds BlockData from a Block.

type BlockHeader

type BlockHeader struct {
	Number        uint64    `json:"number"`          // Block number.
	PrevBlockHash string    `json:"prev_block_hash"` // Previous block hash.
	Timestamp     uint64    `json:"timestamp"`       // Block timestamp.
	BeneficiaryID AccountID `json:"beneficiary"`     // Fee/tip recipient.
	Difficulty    uint16    `json:"difficulty"`      // Mining difficulty.
	MiningReward  uint64    `json:"mining_reward"`   // Mining reward.
	StateRoot     string    `json:"state_root"`      // Accounts state Merkle root.
	TransRoot     string    `json:"trans_root"`      // Transactions Merkle root.
	Solution      uint64    `json:"solution"`        // The mined block solution.
}

BlockHeader holds block metadata.

type BlockTx

type BlockTx struct {
	SignedTx

	// The timestamp of when the transaction was received.
	// Format: Unix timestamp in milliseconds.
	Timestamp uint64 `json:"timestamp"`

	// The price of one unit of gas.
	GasPrice uint64 `json:"gas_price"`

	// The number of units used in this transaction.
	GasUnits uint64 `json:"gas_units"`
}

BlockTx represents a transaction inside a block.

func NewBlockTx

func NewBlockTx(signedTx SignedTx, gasPrice uint64, unitsOfGas uint64) BlockTx

NewBlockTx constructs a new block transaction.

func (BlockTx) Equals

func (tx BlockTx) Equals(otherTx BlockTx) bool

Equals implements the Merkle Hashable interface. It provides an equality check between two block transactions.

func (BlockTx) Hash

func (tx BlockTx) Hash() ([]byte, error)

Hash implements the Merkle Hashable interface. It does so by hashing the entire block transaction data.

func (BlockTx) Hex

func (tx BlockTx) Hex() (string, error)

Hex returns a hex-encoded string representation of the block transaction hash.

type Database

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

Database manages the blockchain state.

func New

func New(genesis genesis.Genesis, storage Storage) (*Database, error)

New creates a new Database using the provided genesis configuration.

func (*Database) ApplyMiningReward

func (db *Database) ApplyMiningReward(block Block)

ApplyMiningReward credits the beneficiary with the mining reward.

func (*Database) ApplyTransaction

func (db *Database) ApplyTransaction(block Block, tx BlockTx) error

ApplyTransaction applies a transaction to the database and does the accounting.

func (*Database) Close

func (db *Database) Close()

Close closes the database storage.

func (*Database) Copy

func (db *Database) Copy() map[AccountID]Account

Copy returns a copy of the accounts map.

func (*Database) ForEach

func (db *Database) ForEach() DatabaseIterator

ForEach returns an iterator that walks over the database blockchain starting from the first entry.

func (*Database) GetBlock

func (db *Database) GetBlock(num uint64) (Block, error)

GetBlock retrieves a block from the database by block number.

func (*Database) HashState

func (db *Database) HashState() (string, error)

HashState returns a hash of the current accounts state. The hash is computed from a sorted JSON representation of accounts.

func (*Database) LatestBlock

func (db *Database) LatestBlock() Block

LatestBlock returns the latest block.

func (*Database) Query

func (db *Database) Query(accountID AccountID) Account

Query returns the account for the given accountID. Returns an empty account if not found.

func (*Database) Remove

func (db *Database) Remove(accountID AccountID)

Remove deletes the account from the database.

func (*Database) Reset

func (db *Database) Reset() error

Reset re-initializes the database back to the genesis state.

func (*Database) Update

func (db *Database) Update(account Account)

Update sets the account state.

func (*Database) UpdateLatestBlock

func (db *Database) UpdateLatestBlock(block Block)

UpdateLatestBlock safely updates the latest block.

func (*Database) Write

func (db *Database) Write(block Block) error

Write adds a new block to the blockchain database.

type DatabaseIterator

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

DatabaseIterator provides support for iterating over the blockchain.

func (*DatabaseIterator) Done

func (dbIter *DatabaseIterator) Done() bool

Done returns true if the iterator has reached the end of the blockchain.

func (*DatabaseIterator) Next

func (dbIter *DatabaseIterator) Next() (Block, error)

Next returns the next block in the blockchain.

type Iterator

type Iterator interface {
	Next() (BlockData, error)
	Done() bool
}

Iterator represents a storage block iterator, it provides support to iterate over the blockchain blocks.

type SignedTx

type SignedTx struct {
	Tx
	Sig signature.Sig
}

SignedTx is a signed transaction. This is the required format for clients and wallets to submit a transaction to the blockchain.

func (SignedTx) Verify

func (tx SignedTx) Verify(chainID uint16) error

Verify verifies the transaction complies with our protocol specification.

type Storage

type Storage interface {
	WriteBlock(blockData BlockData) error
	GetBlock(num uint64) (BlockData, error)
	ForEach() Iterator
	Close() error
	Reset() error
}

Storage represents a blockchain database storage interface.

type Tx

type Tx struct {
	// ChainID represents a unique identifier for this blockchain.
	// It is used to run multiple blockchains in parallel
	// without conflicting with each other.
	//
	// Current SPEC:
	// ChainID 0: Development
	// ChainID 1: Production
	ChainID uint16 `json:"chain_id"`

	// Nonce represents a unique identifier for this transaction.
	// Currently it's an incremental number representing the transaction number.
	Nonce uint64 `json:"nonce"`

	From   AccountID `json:"from"`
	To     AccountID `json:"to"`
	Amount uint64    `json:"amount"`

	// Tip is offered by the sender as an incentive to mine this transaction.
	Tip uint64 `json:"tip"`

	// Optional data attached to this transaction.
	Data []byte `json:"data"`
}

Tx represents a transaction between two parties.

func NewTx

func NewTx(
	chainID uint16,
	nonce uint64,
	from AccountID,
	to AccountID,
	amount uint64,
	tip uint64,
	data []byte,
) (
	Tx,
	error,
)

NewTx constructs a new transaction.

func (Tx) Bytes

func (tx Tx) Bytes() ([]byte, error)

Bytes returns a byte array representation of the transaction.

func (Tx) Sign

func (tx Tx) Sign(privKey *ecdsa.PrivateKey) (SignedTx, error)

Sign takes a private key and uses it to sign the transaction.

Jump to

Keyboard shortcuts

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