database

package
v0.0.0-...-c97bdb9 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2022 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package database handles all the lower level support for maintaining the blockchain in storage and maintaining an in-memory databse 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 information stored in the database for an individual account.

type AccountID

type AccountID string

AccountID represents an account id that is used to sign transactions and is associated with transactions on the blockchain. This will be the last 20 bytes of the public key.

func PublicKeyToAccountID

func PublicKeyToAccountID(pk ecdsa.PublicKey) AccountID

PublicKeyToAccountID converts the public key to an account value.

func ToAccountID

func ToAccountID(hex string) (AccountID, error)

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

func (AccountID) IsAccountID

func (a AccountID) IsAccountID() bool

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

type Block

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

Block represents a group of transactions batched 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 POW puzzel.

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 constructs block data from a block.

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 in the chain.
	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: 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 a hash of the accounts and their balances.
	TransRoot     string    `json:"trans_root"`      // Both: Represents the merkle tree root hash for the transactions in this block.
	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 time the transaction was received.
	GasPrice  uint64 `json:"gas_price"` // Ethereum: The price of one unit of gas to be paid for fees.
	GasUnits  uint64 `json:"gas_units"` // Ethereum: The number of units of gas used for this transaction.
}

BlockTx represents the transaction as it's recorded inside a block. This includes a timestamp and gas fees.

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 for providing an equality check between 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 for providing a hash of 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 and reads/writes the blockchain database on disk if a dbPath is provided.

func (*Database) ApplyMiningReward

func (db *Database) ApplyMiningReward(block Block)

ApplyMiningReward gives the specififed 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) Close

func (db *Database) Close()

Close closes the open blocks 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 with block number 1.

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 retrieves an account from the database.

func (*Database) Remove

func (db *Database) Remove(accountID AccountID)

Remove deletes an account from the database.

func (*Database) Reset

func (db *Database) Reset() error

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

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 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 set of arguments required to run POW.

type SignedTx

type SignedTx struct {
	Tx
	V *big.Int `json:"v"` // Ethereum: Recovery identifier, either 29 or 30 with ardanID.
	R *big.Int `json:"r"` // Ethereum: First coordinate of the ECDSA signature.
	S *big.Int `json:"s"` // Ethereum: Second coordinate of the ECDSA signature.
}

SignedTx is a signed version of the transaction. This is how clients like a wallet provide transactions for inclusion into the blockchain.

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 for logging.

func (SignedTx) Validate

func (tx SignedTx) Validate(chainID uint16) error

Validate verifies the transaction has a proper signature that conforms to our standards. It also checks the from field matches the account that signed the transaction. Last 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 that is listed in the genesis file.
	Nonce   uint64    `json:"nonce"`    // Ethereum: Unique id for the transaction supplied by the user.
	FromID  AccountID `json:"from"`     // Ethereum: Account sending the transaction. Will be checked against signature.
	ToID    AccountID `json:"to"`       // Ethereum: Account receiving the benefit of the transaction.
	Value   uint64    `json:"value"`    // Ethereum: Monetary value received from this transaction.
	Tip     uint64    `json:"tip"`      // Ethereum: Tip offered by the sender as an incentive to mine this transaction.
	Data    []byte    `json:"data"`     // Ethereum: Extra data related to the transaction.
}

Tx is the transactional information between two parties.

func NewTx

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

NewTx constructs a new transaction.

func (Tx) Sign

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

Sign uses the specified private key to sign the transaction.

Jump to

Keyboard shortcuts

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