database

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

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

Go to latest
Published: Apr 19, 2023 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

• Adding new transactions to Mempool • Validating transactions against the current State (sufficient sender balance) • Changing the state • Persisting transactions to disk • Calculating accounts balances by replaying all transactions since Genesis in a sequence

Index

Constants

View Source
const (
	// HashLength is the expected length of the hash
	HashLength = 32
	// AddressLength is the expected length of the address
	AddressLength = 20

	A0 string = "0x0000000000000000000000000000000000000009"
	A1 string = "0x0000000000000000000000000000000000000001"
	A2 string = "0x0000000000000000000000000000000000000002"
	A3 string = "0x0000000000000000000000000000000000000003"
)

Lengths of hashes and addresses in bytes.

View Source
const BlockReward = 100
View Source
const TxFee = uint(50)
View Source
const TxGas = 21
View Source
const TxGasPriceDefault = 1

Variables

This section is empty.

Functions

func ApplySimpleTx

func ApplySimpleTx(tx SimpleTx, s *State) error

func ApplyTx

func ApplyTx(tx SignedTx, s *State) error

func InitDataDirIfNotExists

func InitDataDirIfNotExists(dataDir string, genesis []byte) error

func IsBlockHashValid

func IsBlockHashValid(hash Hash, miningDifficulty uint) bool

func NewAccount

func NewAccount(value string) common.Address

func ValidateSimpleTx

func ValidateSimpleTx(tx SimpleTx, s *State) error

func ValidateTx

func ValidateTx(tx SignedTx, s *State) error

Types

type Address

type Address [AddressLength]byte

func ToAddress

func ToAddress(hex string) Address

func (Address) Hex

func (a Address) Hex() string

Hex returns an EIP55-compliant hex string representation of the address.

func (Address) MarshalText

func (a Address) MarshalText() ([]byte, error)

func (Address) String

func (a Address) String() string

String implements fmt.Stringer.

func (*Address) UnmarshalJSON

func (a *Address) UnmarshalJSON(input []byte) error

UnmarshalJSON parses a hash in hex syntax.

func (*Address) UnmarshalText

func (v *Address) UnmarshalText(input []byte) error

type Block

type Block struct {
	Header BlockHeader `json:"header"`  // metadata (parent block hash + time)
	TXs    []SignedTx  `json:"payload"` // new transactions only (payload)
}

func GetBlocksAfter

func GetBlocksAfter(blockHash Hash, dataDir string) ([]Block, error)

func NewBlock

func NewBlock(parent Hash, number uint64, miner Address, txs []SignedTx) Block

func (Block) GasReward

func (b Block) GasReward() uint

func (Block) Hash

func (b Block) Hash() (Hash, error)

type BlockFS

type BlockFS struct {
	Key   Hash  `json:"hash"`
	Value Block `json:"block"`
}

func GetBlockByHeightOrHash

func GetBlockByHeightOrHash(state *State, height uint64, hash, dataDir string) (BlockFS, error)

GetBlockByHeightOrHash returns the requested block by hash or height. It uses cached data in the State struct (HashCache / HeightCache)

type BlockHeader

type BlockHeader struct {
	Parent Hash    `json:"parent"` // parent block reference
	Number uint64  `json:"number"`
	Nonce  uint32  `json:"nonce"`
	Time   uint64  `json:"time"`
	Miner  Address `json:"miner"`
}

type Genesis

type Genesis struct {
	//Time     uint64           `json:"time"`
	Symbol   string           `json:"symbol"`
	Balances map[Address]uint `json:"balances"`
	ForkTIP1 uint64           `json:"fork_tip_1"`
}

type Hash

type Hash [HashLength]byte

func (Hash) Hex

func (h Hash) Hex() string

func (Hash) IsEmpty

func (h Hash) IsEmpty() bool

func (Hash) MarshalText

func (h Hash) MarshalText() ([]byte, error)

func (*Hash) UnmarshalText

func (h *Hash) UnmarshalText(data []byte) error

type SignedTx

type SignedTx struct {
	Tx
	Sig []byte `json:"signature"`
}

func NewSignedTx

func NewSignedTx(tx Tx, sig []byte) SignedTx

func (SignedTx) Hash

func (t SignedTx) Hash() (Hash, error)

func (SignedTx) IsAuthentic

func (t SignedTx) IsAuthentic() (bool, error)

func (SignedTx) MarshalJSON

func (t SignedTx) MarshalJSON() ([]byte, error)

MarshalJSON is the main source of truth for encoding a TX for hash calculation (backwards compatible for TIPs).

The logic is bit ugly and hacky but prevents infinite marshaling loops of embedded objects and allows the structure to change with new TIPs.

type SimpleBlock

type SimpleBlock struct {
	Header BlockHeader `json:"header"`
	TXs    []SimpleTx  `json:"payload"` // new transactions only (payload)
}

func NewSimpleBlock

func NewSimpleBlock(parent Hash, number uint64, miner Address, txs []SimpleTx) SimpleBlock

func (SimpleBlock) GasReward

func (b SimpleBlock) GasReward() uint

func (SimpleBlock) Hash

func (b SimpleBlock) Hash() (Hash, error)

type SimpleBlockFS

type SimpleBlockFS struct {
	Key   Hash        `json:"hash"`
	Value SimpleBlock `json:"block"`
}

type SimpleTx

type SimpleTx struct {
	From  Address `json:"from"`
	To    Address `json:"to"`
	Value uint    `json:"value"`
	Nonce uint    `json:"nonce"`
	Data  string  `json:"data"`
	Time  uint64  `json:"time"`
}

func NewSimpleTx

func NewSimpleTx(from, to Address, value uint, data string) SimpleTx

func NewSimpleTxStringAddress

func NewSimpleTxStringAddress(from, to string, value uint, data string) SimpleTx

func (SimpleTx) Cost

func (t SimpleTx) Cost(isTip1Fork bool) uint

func (SimpleTx) GasCost

func (t SimpleTx) GasCost() uint

func (SimpleTx) IsAuthentic

func (t SimpleTx) IsAuthentic() (bool, error)

func (SimpleTx) IsMint

func (t SimpleTx) IsMint() bool

type State

type State struct {
	Balances      map[Address]uint
	Account2Nonce map[Address]uint

	HashCache   map[string]int64
	HeightCache map[uint64]int64
	// contains filtered or unexported fields
}

func NewStateFromDisk

func NewStateFromDisk(dataDir string, miningDifficulty uint) (*State, error)

func (*State) AddSimpleBlock

func (s *State) AddSimpleBlock(b SimpleBlock) error
func (s *State) AddBlocks(blocks []Block) error {
	for _, b := range blocks {
		_, err := s.AddBlock(b)
		if err != nil {
			return err
		}
	}

	return nil
}
func (s *State) AddBlock(b Block) (Hash, error) {
	pendingState := s.Copy()

	err := applyBlock(b, &pendingState)
	if err != nil {
		return Hash{}, err
	}

	blockHash, err := b.Hash()
	if err != nil {
		return Hash{}, err
	}

	blockFs := BlockFS{blockHash, b}

	blockFsJson, err := json.Marshal(blockFs)
	if err != nil {
		return Hash{}, err
	}

	fmt.Printf("\nPersisting new Block to disk:\n")
	fmt.Printf("\t%s\n", blockFsJson)

	// get file pos for cache
	fs, _ := s.dbFile.Stat()
	filePos := fs.Size() + 1

	_, err = s.dbFile.Write(append(blockFsJson, '\n'))
	if err != nil {
		return Hash{}, err
	}

	// set search caches
	s.HashCache[blockFs.Key.Hex()] = filePos
	s.HeightCache[blockFs.Value.Header.Number] = filePos

	s.Balances = pendingState.Balances
	s.Account2Nonce = pendingState.Account2Nonce
	s.latestBlockHash = blockHash
	s.latestBlock = b
	s.hasGenesisBlock = true
	s.miningDifficulty = pendingState.miningDifficulty

	return blockHash, nil
}

func (*State) AddSimpleTx

func (s *State) AddSimpleTx(tx SimpleTx) error

func (*State) ChangeMiningDifficulty

func (s *State) ChangeMiningDifficulty(newDifficulty uint)

func (*State) Close

func (s *State) Close() error

func (*State) Copy

func (s *State) Copy() State

func (*State) GetNextAccountNonce

func (s *State) GetNextAccountNonce(account Address) uint

func (*State) IsTIP1Fork

func (s *State) IsTIP1Fork() bool

func (*State) LatestBlock

func (s *State) LatestBlock() SimpleBlock

func (*State) LatestBlockHash

func (s *State) LatestBlockHash() Hash

func (*State) NextBlockNumber

func (s *State) NextBlockNumber() uint64

func (*State) Persist

func (s *State) Persist() (Hash, error)

type Tx

type Tx struct {
	From     Address `json:"from"`
	To       Address `json:"to"`
	Gas      uint    `json:"gas"`
	GasPrice uint    `json:"gasPrice"`
	Value    uint    `json:"value"`
	Nonce    uint    `json:"nonce"`
	Data     string  `json:"data"`
	Time     uint64  `json:"time"`
}

func NewBaseTx

func NewBaseTx(from, to Address, value, nonce uint, data string) Tx

func NewTx

func NewTx(from, to Address, gas uint, gasPrice uint, value, nonce uint, data string) Tx

func (Tx) Cost

func (t Tx) Cost(isTip1Fork bool) uint

func (Tx) Encode

func (t Tx) Encode() ([]byte, error)

func (Tx) GasCost

func (t Tx) GasCost() uint

func (Tx) Hash

func (t Tx) Hash() (Hash, error)

func (Tx) IsMint

func (t Tx) IsMint() bool

func (Tx) MarshalJSON

func (t Tx) MarshalJSON() ([]byte, error)

MarshalJSON is the main source of truth for encoding a TX for hash calculation from expected attributes.

The logic is bit ugly and hacky but prevents infinite marshaling loops of embedded objects and allows the structure to change with new TIPs.

Jump to

Keyboard shortcuts

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