database

package
v0.0.0-...-297edb8 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2024 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package database handles all lower level support for maintaining the blockchain database. This includes the management of an in-memory database of account information.

Index

Constants

This section is empty.

Variables

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

ErrChainForked is returned from validateNextBlock if another node's chain is two or more blocks ahead of ours.

Functions

This section is empty.

Types

type Account

type Account struct {
	AccountID AccountID
	Nonce     uint64
	Balance   uint64
}

Account represents an account on the blockchain.

type AccountID

type AccountID string

AccountID represents an account ID that is used to sign transactions. It is associated with transactions on the blockchain. This is the last 20 bytes of the hash of the public key.

func PublicKeyToAccountID

func PublicKeyToAccountID(publicKey ecdsa.PublicKey) AccountID

PublicKeyToAccountID converts a public key to an account ID.

func ToAccountID

func ToAccountID(hex string) (AccountID, error)

ToAccountID converts a hex-encoded string to an account ID and validates the string is formatted correctly.

func (AccountID) IsAccountID

func (a AccountID) IsAccountID() bool

IsAccountID returns true if the account ID is valid.

type Block

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

Block represents a group of transactions bundled together.

func POW

func POW(ctx context.Context, args POWArgs) (Block, error)

POW constructs a new Block and performs the work to find a nonce that solves the cryptographic hash puzzle.

func ToBlock

func ToBlock(blockData BlockData) (Block, error)

ToBlock converts a storage block into a database block.

func (Block) Hash

func (b Block) Hash() string

Hash returns the unique hash for the Block.

func (Block) ValidateBlock

func (b Block) ValidateBlock(previousBlock Block, stateRoot string, evHandler func(v string, args ...any)) error

ValidateBlock takes a block and validates it to be included into the blockchain.

type BlockData

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

BlockData represents what can be serialized to disk and over the network.

func NewBlockData

func NewBlockData(block Block) BlockData

NewBlockData creates a new block data.

type BlockHeader

type BlockHeader struct {
	Number        uint64    `json:"number"`          // Ethereum: Block number in the chain.
	PrevBlockHash string    `json:"prev_block_hash"` // Bitcoin: Hash of the previous block.
	TimeStamp     uint64    `json:"timestamp"`       // Bitcoin: Time the block was mined.
	BeneficiaryID AccountID `json:"beneficiary"`     // Ethereum: The account who is receiving fees and tips.
	Difficulty    uint16    `json:"difficulty"`      // Ethereum: The number of 0's needed to solve the hash solution.
	MiningReward  uint64    `json:"mining_reward"`   // Ethereum: The reward for mining this block.
	StateRoot     string    `json:"state_root"`      // Ethereum: Represents the hash of the accounts and their balances.
	TransRoot     string    `json:"trans_root"`      // Both: Represents the merkle root hash for the transactions.
	Nonce         uint64    `json:"nonce"`           // Both: Value identified to solve the hash solution.
}

BlockHeader represents common information required for each block.

type BlockTx

type BlockTx struct {
	SignedTx
	TimeStamp uint64 `json:"timestamp"` // Ethereum: The timestamp of the block.
	GasPrice  uint64 `json:"gas_price"` // Ethereum: The gas price in the block.
	GasUnits  uint64 `json:"gas_units"` // Ethereum: The gas units in the block.
}

BlockTx represents a transaction in a block, which includes the timestamp and gas fees.

func NewBlockTx

func NewBlockTx(tx SignedTx, gasPrice, gasUnits uint64) BlockTx

NewBlockTx creates a new block transaction.

func (BlockTx) Equals

func (tx BlockTx) Equals(otherTx BlockTx) bool

Equals implements the merkle Hashable interface to compare two block transactions. If the nonce and signatures are the same, the two blocks are the same.

func (BlockTx) Hash

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

Hash implements the merkle Hashable interface to hash a block transaction.

type Database

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

Database manages data related to accounts who have transacted on the blockchain.

func New

func New(genesis genesis.Genesis, storage Storage, evHandler func(v string, args ...any)) (*Database, error)

New constructs a new database and applies account genesis information. It reads/writes the blockchain database on disk if a dbPath is provided.

func (*Database) ApplyMiningReward

func (db *Database) ApplyMiningReward(block Block)

ApplyMiningReward gives the specified account the mining reward.

func (*Database) ApplyTransaction

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

ApplyTransaction performs the business logic for applying a transaction to the database.

func (*Database) Copy

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

Copy makes a copy of the current accounts in the database.

func (*Database) ForEach

func (db *Database) ForEach() DatabaseIterator

ForEach returns an iterator to walk through all the blocks starting from the genesis block.

func (*Database) GetBlock

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

GetBlock searches the blockchain on disk to locate and return the contents of the specified block by number.

func (*Database) HashState

func (db *Database) HashState() string

HashState returns a hash based on the contents of the accounts and their balances. This is added to each block and checked by peers.

func (*Database) LatestBlock

func (db *Database) LatestBlock() Block

LatestBlock returns the latest block.

func (*Database) Query

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

Query returns a queried account from the database.

func (*Database) Remove

func (db *Database) Remove(accountID AccountID)

Remove removes an account from the database.

func (*Database) UpdateLatestBlock

func (db *Database) UpdateLatestBlock(block Block)

UpdateLatestBlock provides safe access to update the latest block.

func (*Database) Write

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

Write adds a new block to the chain.

type DatabaseIterator

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

DatabaseIterator provides support for iterating over the blocks in the blockchain database using the configured storage option.

func (*DatabaseIterator) Done

func (di *DatabaseIterator) Done() bool

Done returns the end of the chain value.

func (*DatabaseIterator) Next

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

Next retrieves the next block from disk.

type Iterator

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

Iterator interface represents the behavior required to be implemented by any package providing support to iterate over the blocks.

type POWArgs

type POWArgs struct {
	BeneficiaryID AccountID
	Difficulty    uint16
	MiningReward  uint64
	PrevBlock     Block
	StateRoot     string
	Trans         []BlockTx
	EvHandler     func(v string, args ...any)
}

POWArgs represents the arguments required to solve the proof of work.

type SignedTx

type SignedTx struct {
	Tx
	V *big.Int `json:"v"` // Ethereum: The recovery ID.
	R *big.Int `json:"r"` // Ethereum: The first 32 bytes of the ECDSA signature.
	S *big.Int `json:"s"` // Ethereum: The second 32 bytes of the ECDSA signature.
}

SignedTx represents a signed transaction.

func (SignedTx) SignatureString

func (tx SignedTx) SignatureString() string

SignatureString returns the signature as a string.

func (SignedTx) String

func (tx SignedTx) String() string

String implements the Stringer interface.

func (SignedTx) Validate

func (tx SignedTx) Validate(chainID uint16) error

Validate verifies the transaction has a proper signature conforming to the standards. It checks that the from field matches the account that signed the transaction. It checks the format of the from and to fields.

type Storage

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

Storage interface represents the behavior required to be implemented by any package providing support for reading and writing the blockchain.

type Tx

type Tx struct {
	ChainID uint16    `json:"chain_id"` // Ethereum: The chain ID in the genesis file.
	FromID  AccountID `json:"from_id"`  // Ethereum: The transaction sender.
	ToID    AccountID `json:"to_id"`    // Ethereum: The transaction recipient.
	Value   uint64    `json:"value"`    // Ethereum: The unit amount to transfer.
	Nonce   uint64    `json:"nonce"`    // Ethereum: Unique number for the transaction.
	Tip     uint64    `json:"tip"`      // Ethereum: The unit amount to tip the miner.
	Data    []byte    `json:"data"`     // Ethereum: The input data for the transaction.
}

Tx represents a transaction.

func NewTx

func NewTx(chainID uint16, fromID, toID AccountID, value, nonce, tip uint64, data []byte) (Tx, error)

NewTx creates a new transaction.

func (Tx) Sign

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

Sign signs the transaction.

Jump to

Keyboard shortcuts

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