blockchain

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2018 License: Apache-2.0 Imports: 35 Imported by: 30

Documentation

Index

Constants

View Source
const (
	// ExecutionDataGas represents the execution data gas per uint
	ExecutionDataGas = uint64(100)
	// BaseIntrinsicGas represents the base intrinsic gas for execution
	BaseIntrinsicGas = uint64(10000)
	// FailureStatus is the status that contract execution failed
	FailureStatus = uint64(0)
	// SuccessStatus is the status that contract execution success
	SuccessStatus = uint64(1)
	// GasLimit is the total gas limit to be consumed in a block
	GasLimit = uint64(1000000000)
)

Variables

View Source
var (
	// ErrInvalidTipHeight is the error returned when the block height is not valid
	ErrInvalidTipHeight = errors.New("invalid tip height")
	// ErrInvalidBlock is the error returned when the block is not valid
	ErrInvalidBlock = errors.New("failed to validate the block")
	// ErrActionNonce is the error when the nonce of the action is wrong
	ErrActionNonce = errors.New("invalid action nonce")
	// ErrGasHigherThanLimit indicates the error of gas value
	ErrGasHigherThanLimit = errors.New("invalid gas for execution")
	// ErrInsufficientGas indicates the error of insufficient gas value for data storage
	ErrInsufficientGas = errors.New("insufficient intrinsic gas value")
	// ErrBalance indicates the error of balance
	ErrBalance = errors.New("invalid balance")
)
View Source
var (
	// ErrHitGasLimit is the error when hit gas limit
	ErrHitGasLimit = errors.New("Hit Gas Limit")
	// ErrInsufficientBalanceForGas is the error that the balance in executor account is lower than gas
	ErrInsufficientBalanceForGas = errors.New("Insufficient balance for gas")
	// ErrInconsistentNonce is the error that the nonce is different from executor's nonce
	ErrInconsistentNonce = errors.New("Nonce is not identical to executor nonce")
	// ErrOutOfGas is the error when running out of gas
	ErrOutOfGas = errors.New("Out of gas")
)
View Source
var Gen = &Genesis{
	ChainID:             uint32(1),
	TotalSupply:         uint64(10000000000),
	BlockReward:         uint64(5),
	Timestamp:           uint64(1524676419),
	ParentHash:          hash.Hash32B{},
	GenesisCoinbaseData: "Connecting the physical world, block by block",
	CreatorAddr:         "io1qyqsyqcy222ggazmccgf7dsx9m9vfqtadw82ygwhjnxtmx",
	CreatorPubKey:       "d01164c3afe47406728d3e17861a3251dcff39e62bdc2b93ccb69a02785a175e195b5605517fd647eb7dd095b3d862dffb087f35eacf10c6859d04a100dbfb7358eeca9d5c37c904",
}

Gen hardcodes genesis default settings

Functions

func CanTransfer added in v0.3.0

func CanTransfer(db vm.StateDB, fromHash common.Address, balance *big.Int) bool

CanTransfer checks whether the from account has enough balance

func ExecuteContracts added in v0.3.0

func ExecuteContracts(blk *Block, bc Blockchain)

ExecuteContracts process the contracts in a block

func GetHashFn added in v0.3.0

func GetHashFn(stateDB *EVMStateDBAdapter) func(n uint64) common.Hash

GetHashFn returns a GetHashFunc which retrieves hashes by number

func IntrinsicGas added in v0.3.0

func IntrinsicGas(data []byte) (uint64, error)

IntrinsicGas returns the intrinsic gas of an execution

func MakeTransfer added in v0.3.0

func MakeTransfer(db vm.StateDB, fromHash, toHash common.Address, amount *big.Int)

MakeTransfer transfers account

Types

type Block

type Block struct {
	Header     *BlockHeader
	Transfers  []*action.Transfer
	Votes      []*action.Vote
	Executions []*action.Execution
	// contains filtered or unexported fields
}

Block defines the struct of block

func NewBlock

func NewBlock(
	chainID uint32,
	height uint64,
	prevBlockHash hash.Hash32B,
	c clock.Clock,
	tsf []*action.Transfer,
	vote []*action.Vote,
	executions []*action.Execution) *Block

NewBlock returns a new block

func NewGenesisBlock added in v0.2.0

func NewGenesisBlock(cfg *config.Config) *Block

NewGenesisBlock creates a new genesis block

func (*Block) ByteStream

func (b *Block) ByteStream() []byte

ByteStream returns a byte stream of the block

func (*Block) ByteStreamHeader added in v0.2.0

func (b *Block) ByteStreamHeader() []byte

ByteStreamHeader returns a byte stream of the block header

func (*Block) ConvertFromBlockHeaderPb

func (b *Block) ConvertFromBlockHeaderPb(pbBlock *iproto.BlockPb)

ConvertFromBlockHeaderPb converts BlockHeaderPb to BlockHeader

func (*Block) ConvertFromBlockPb

func (b *Block) ConvertFromBlockPb(pbBlock *iproto.BlockPb)

ConvertFromBlockPb converts BlockPb to Block

func (*Block) ConvertToBlockHeaderPb

func (b *Block) ConvertToBlockHeaderPb() *iproto.BlockHeaderPb

ConvertToBlockHeaderPb converts BlockHeader to BlockHeaderPb

func (*Block) ConvertToBlockPb

func (b *Block) ConvertToBlockPb() *iproto.BlockPb

ConvertToBlockPb converts Block to BlockPb

func (*Block) Deserialize

func (b *Block) Deserialize(buf []byte) error

Deserialize parses the byte stream into a Block

func (*Block) HashBlock

func (b *Block) HashBlock() hash.Hash32B

HashBlock return the hash of this block (actually hash of block header)

func (*Block) Height

func (b *Block) Height() uint64

Height returns the height of this block

func (*Block) IsDummyBlock added in v0.3.0

func (b *Block) IsDummyBlock() bool

IsDummyBlock checks whether block is a dummy block

func (*Block) PrevHash

func (b *Block) PrevHash() hash.Hash32B

PrevHash returns the hash of prev block

func (*Block) Serialize

func (b *Block) Serialize() ([]byte, error)

Serialize returns the serialized byte stream of the block

func (*Block) SignBlock added in v0.2.0

func (b *Block) SignBlock(signer *iotxaddress.Address) error

SignBlock allows signer to sign the block b

func (*Block) TxRoot added in v0.2.0

func (b *Block) TxRoot() hash.Hash32B

TxRoot returns the Merkle root of all txs and actions in this block.

type BlockHeader

type BlockHeader struct {
	Pubkey      keypair.PublicKey // block producer's public key
	DKGID       []byte            // dkg ID of producer
	DKGPubkey   []byte            // dkg public key of producer
	DKGBlockSig []byte            // dkg signature of producer
	// contains filtered or unexported fields
}

BlockHeader defines the struct of block header make sure the variable type and order of this struct is same as "BlockHeaderPb" in blockchain.pb.go

func (*BlockHeader) Timestamp added in v0.3.0

func (bh *BlockHeader) Timestamp() time.Time

Timestamp returns the timestamp in the block header

type Blockchain

type Blockchain interface {
	lifecycle.StartStopper

	// Balance returns balance of an account
	Balance(addr string) (*big.Int, error)
	// Nonce returns the nonce if the account exists
	Nonce(addr string) (uint64, error)
	// CreateState adds a new State with initial balance to the factory
	CreateState(addr string, init uint64) (*state.State, error)
	// CommitStateChanges updates a State from the given actions
	CommitStateChanges(chainHeight uint64, tsf []*action.Transfer, vote []*action.Vote, executions []*action.Execution) error
	// Candidates returns the candidate list
	Candidates() (uint64, []*state.Candidate)
	// CandidatesByHeight returns the candidate list by a given height
	CandidatesByHeight(height uint64) ([]*state.Candidate, error)
	// For exposing blockchain states
	// GetHeightByHash returns Block's height by hash
	GetHeightByHash(h hash.Hash32B) (uint64, error)
	// GetHashByHeight returns Block's hash by height
	GetHashByHeight(height uint64) (hash.Hash32B, error)
	// GetBlockByHeight returns Block by height
	GetBlockByHeight(height uint64) (*Block, error)
	// GetBlockByHash returns Block by hash
	GetBlockByHash(h hash.Hash32B) (*Block, error)
	// GetTotalTransfers returns the total number of transfers
	GetTotalTransfers() (uint64, error)
	// GetTotalVotes returns the total number of votes
	GetTotalVotes() (uint64, error)
	// GetTotalExecutions returns the total number of executions
	GetTotalExecutions() (uint64, error)
	// GetTransfersFromAddress returns transaction from address
	GetTransfersFromAddress(address string) ([]hash.Hash32B, error)
	// GetTransfersToAddress returns transaction to address
	GetTransfersToAddress(address string) ([]hash.Hash32B, error)
	// GetTransfersByTransferHash returns transfer by transfer hash
	GetTransferByTransferHash(h hash.Hash32B) (*action.Transfer, error)
	// GetBlockHashByTransferHash returns Block hash by transfer hash
	GetBlockHashByTransferHash(h hash.Hash32B) (hash.Hash32B, error)
	// GetVoteFromAddress returns vote from address
	GetVotesFromAddress(address string) ([]hash.Hash32B, error)
	// GetVoteToAddress returns vote to address
	GetVotesToAddress(address string) ([]hash.Hash32B, error)
	// GetVotesByVoteHash returns vote by vote hash
	GetVoteByVoteHash(h hash.Hash32B) (*action.Vote, error)
	// GetBlockHashByVoteHash returns Block hash by vote hash
	GetBlockHashByVoteHash(h hash.Hash32B) (hash.Hash32B, error)
	// GetExecutionsFromAddress returns executions from address
	GetExecutionsFromAddress(address string) ([]hash.Hash32B, error)
	// GetExecutionsToAddress returns executions to address
	GetExecutionsToAddress(address string) ([]hash.Hash32B, error)
	// GetExecutionByExecutionHash returns execution by execution hash
	GetExecutionByExecutionHash(h hash.Hash32B) (*action.Execution, error)
	// GetBlockHashByExecutionHash returns Block hash by execution hash
	GetBlockHashByExecutionHash(h hash.Hash32B) (hash.Hash32B, error)
	// GetReceiptByExecutionHash returns the receipt by execution hash
	GetReceiptByExecutionHash(h hash.Hash32B) (*Receipt, error)
	// GetFactory returns the State Factory
	GetFactory() state.Factory
	// TipHash returns tip block's hash
	TipHash() (hash.Hash32B, error)
	// TipHeight returns tip block's height
	TipHeight() (uint64, error)
	// StateByAddr returns state of a given address
	StateByAddr(address string) (*state.State, error)

	// For block operations
	// MintNewBlock creates a new block with given actions
	// Note: the coinbase transfer will be added to the given transfers when minting a new block
	MintNewBlock(tsf []*action.Transfer, vote []*action.Vote, executions []*action.Execution, address *iotxaddress.Address, data string) (*Block, error)
	// TODO: Merge the MintNewDKGBlock into MintNewBlock
	// MintNewDKGBlock creates a new block with given actions and dkg keys
	MintNewDKGBlock(tsf []*action.Transfer, vote []*action.Vote, executions []*action.Execution,
		producer *iotxaddress.Address, dkgAddress *iotxaddress.DKGAddress, seed []byte, data string) (*Block, error)
	// MintDummyNewBlock creates a new dummy block, used for unreached consensus
	MintNewDummyBlock() *Block
	// CommitBlock validates and appends a block to the chain
	CommitBlock(blk *Block) error
	// ValidateBlock validates a new block before adding it to the blockchain
	ValidateBlock(blk *Block) error

	// For action operations
	// Validator returns the current validator object
	Validator() Validator
	// SetValidator sets the current validator object
	SetValidator(val Validator)

	// For smart contract operations
	// ExecuteContractRead runs a read-only smart contract operation, this is done off the network since it does not
	// cause any state change
	ExecuteContractRead(*action.Execution) ([]byte, error)
}

Blockchain represents the blockchain data structure and hosts the APIs to access it

func NewBlockchain

func NewBlockchain(cfg *config.Config, opts ...Option) Blockchain

NewBlockchain creates a new blockchain and DB instance

type EVMParams added in v0.3.0

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

EVMParams is the context and parameters

func NewEVMParams added in v0.3.0

func NewEVMParams(blk *Block, execution *action.Execution, stateDB *EVMStateDBAdapter) (*EVMParams, error)

NewEVMParams creates a new context for use in the EVM.

type EVMStateDBAdapter added in v0.3.0

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

EVMStateDBAdapter represents the state db adapter for evm to access iotx blockchain

func NewEVMStateDBAdapter added in v0.3.0

func NewEVMStateDBAdapter(bc Blockchain, blockHeight uint64, blockHash hash.Hash32B, executionIndex uint, executionHash hash.Hash32B) *EVMStateDBAdapter

NewEVMStateDBAdapter creates a new state db with iotx blockchain

func (*EVMStateDBAdapter) AddBalance added in v0.3.0

func (stateDB *EVMStateDBAdapter) AddBalance(evmAddr common.Address, amount *big.Int)

AddBalance adds balance to account

func (*EVMStateDBAdapter) AddLog added in v0.3.0

func (stateDB *EVMStateDBAdapter) AddLog(evmLog *types.Log)

AddLog adds log

func (*EVMStateDBAdapter) AddPreimage added in v0.3.0

func (stateDB *EVMStateDBAdapter) AddPreimage(common.Hash, []byte)

AddPreimage adds the preimage

func (*EVMStateDBAdapter) AddRefund added in v0.3.0

func (stateDB *EVMStateDBAdapter) AddRefund(uint64)

AddRefund adds refund

func (*EVMStateDBAdapter) CreateAccount added in v0.3.0

func (stateDB *EVMStateDBAdapter) CreateAccount(evmAddr common.Address)

CreateAccount creates an account in iotx blockchain

func (*EVMStateDBAdapter) Empty added in v0.3.0

func (stateDB *EVMStateDBAdapter) Empty(common.Address) bool

Empty empties the contract

func (*EVMStateDBAdapter) Error added in v0.3.0

func (stateDB *EVMStateDBAdapter) Error() error

Error returns the first stored error during evm contract execution

func (*EVMStateDBAdapter) Exist added in v0.3.0

func (stateDB *EVMStateDBAdapter) Exist(evmAddr common.Address) bool

Exist checks the existance of an address

func (*EVMStateDBAdapter) ForEachStorage added in v0.3.0

func (stateDB *EVMStateDBAdapter) ForEachStorage(common.Address, func(common.Hash, common.Hash) bool)

ForEachStorage loops each storage

func (*EVMStateDBAdapter) GetBalance added in v0.3.0

func (stateDB *EVMStateDBAdapter) GetBalance(evmAddr common.Address) *big.Int

GetBalance gets the balance of account

func (*EVMStateDBAdapter) GetCode added in v0.3.0

func (stateDB *EVMStateDBAdapter) GetCode(evmAddr common.Address) []byte

GetCode gets the code saved in hash

func (*EVMStateDBAdapter) GetCodeHash added in v0.3.0

func (stateDB *EVMStateDBAdapter) GetCodeHash(evmAddr common.Address) common.Hash

GetCodeHash gets the code hash of account

func (*EVMStateDBAdapter) GetCodeSize added in v0.3.0

func (stateDB *EVMStateDBAdapter) GetCodeSize(evmAddr common.Address) int

GetCodeSize gets the code size saved in hash

func (*EVMStateDBAdapter) GetNonce added in v0.3.0

func (stateDB *EVMStateDBAdapter) GetNonce(evmAddr common.Address) uint64

GetNonce gets the nonce of account

func (*EVMStateDBAdapter) GetRefund added in v0.3.0

func (stateDB *EVMStateDBAdapter) GetRefund() uint64

GetRefund gets refund

func (*EVMStateDBAdapter) GetState added in v0.3.0

func (stateDB *EVMStateDBAdapter) GetState(evmAddr common.Address, k common.Hash) common.Hash

GetState gets state

func (*EVMStateDBAdapter) HasSuicided added in v0.3.0

func (stateDB *EVMStateDBAdapter) HasSuicided(common.Address) bool

HasSuicided returns whether the contract has been killed

func (*EVMStateDBAdapter) Logs added in v0.3.0

func (stateDB *EVMStateDBAdapter) Logs() []*Log

Logs returns the logs

func (*EVMStateDBAdapter) RevertToSnapshot added in v0.3.0

func (stateDB *EVMStateDBAdapter) RevertToSnapshot(int)

RevertToSnapshot reverts the state factory to snapshot

func (*EVMStateDBAdapter) SetCode added in v0.3.0

func (stateDB *EVMStateDBAdapter) SetCode(evmAddr common.Address, code []byte)

SetCode sets the code saved in hash

func (*EVMStateDBAdapter) SetNonce added in v0.3.0

func (stateDB *EVMStateDBAdapter) SetNonce(common.Address, uint64)

SetNonce sets the nonce of account

func (*EVMStateDBAdapter) SetState added in v0.3.0

func (stateDB *EVMStateDBAdapter) SetState(evmAddr common.Address, k, v common.Hash)

SetState sets state

func (*EVMStateDBAdapter) Snapshot added in v0.3.0

func (stateDB *EVMStateDBAdapter) Snapshot() int

Snapshot returns the snapshot id

func (*EVMStateDBAdapter) SubBalance added in v0.3.0

func (stateDB *EVMStateDBAdapter) SubBalance(evmAddr common.Address, amount *big.Int)

SubBalance subtracts balance from account

func (*EVMStateDBAdapter) Suicide added in v0.3.0

func (stateDB *EVMStateDBAdapter) Suicide(common.Address) bool

Suicide kills the contract

type Genesis added in v0.2.0

type Genesis struct {
	ChainID             uint32
	TotalSupply         uint64
	BlockReward         uint64
	Timestamp           uint64
	ParentHash          hash.Hash32B
	GenesisCoinbaseData string
	CreatorAddr         string
	CreatorPubKey       string
}

Genesis defines the Genesis default settings

type GenesisAction added in v0.2.0

type GenesisAction struct {
	SelfNominators []Nominator `yaml:"selfNominators"`
	Transfers      []Transfer  `yaml:"transfers"`
}

GenesisAction is the root action struct, each package's action should be put as its sub struct

type Log added in v0.3.0

type Log struct {
	Address     string
	Topics      []hash.Hash32B
	Data        []byte
	BlockNumber uint64
	TxnHash     hash.Hash32B
	BlockHash   hash.Hash32B
	Index       uint
}

Log stores an evm contract event

func (*Log) ConvertFromLogPb added in v0.3.0

func (log *Log) ConvertFromLogPb(pbLog *iproto.LogPb)

ConvertFromLogPb converts a protobuf's LogPb to Log

func (*Log) ConvertToLogPb added in v0.3.0

func (log *Log) ConvertToLogPb() *iproto.LogPb

ConvertToLogPb converts a Log to protobuf's LogPb

func (*Log) Deserialize added in v0.3.0

func (log *Log) Deserialize(buf []byte) error

Deserialize parse the byte stream into Log

func (*Log) Serialize added in v0.3.0

func (log *Log) Serialize() ([]byte, error)

Serialize returns a serialized byte stream for the Log

type Nominator added in v0.2.0

type Nominator struct {
	PubKey    string `yaml:"pubKey"`
	Address   string `yaml:"address"`
	Signature string `yaml:"signature"`
}

Nominator is the Nominator struct for vote struct

type Option added in v0.3.0

type Option func(*blockchain, *config.Config) error

Option sets blockchain construction parameter

func BoltDBDaoOption added in v0.3.0

func BoltDBDaoOption() Option

BoltDBDaoOption sets blockchain's dao with BoltDB from config.Chain.ChainDBPath

func ClockOption added in v0.3.0

func ClockOption(clk clock.Clock) Option

ClockOption overrides the default clock

func DefaultStateFactoryOption added in v0.3.0

func DefaultStateFactoryOption() Option

DefaultStateFactoryOption sets blockchain's sf from config

func InMemDaoOption added in v0.3.0

func InMemDaoOption() Option

InMemDaoOption sets blockchain's dao with MemKVStore

func InMemStateFactoryOption added in v0.3.0

func InMemStateFactoryOption() Option

InMemStateFactoryOption sets blockchain's state.Factory as in memory sf

func PrecreatedDaoOption added in v0.3.0

func PrecreatedDaoOption(dao *blockDAO) Option

PrecreatedDaoOption sets blockchain's dao

func PrecreatedStateFactoryOption added in v0.3.0

func PrecreatedStateFactoryOption(sf state.Factory) Option

PrecreatedStateFactoryOption sets blockchain's state.Factory to sf

type Payee

type Payee struct {
	Address string
	Amount  uint64
}

Payee defines the struct of payee

type Receipt added in v0.3.0

type Receipt struct {
	ReturnValue     []byte
	Status          uint64
	Hash            hash.Hash32B
	GasConsumed     uint64
	ContractAddress string
	Logs            []*Log
}

Receipt represents the result of a contract

func (*Receipt) ConvertFromReceiptPb added in v0.3.0

func (receipt *Receipt) ConvertFromReceiptPb(pbReceipt *iproto.ReceiptPb)

ConvertFromReceiptPb converts a protobuf's ReceiptPb to Receipt

func (*Receipt) ConvertToReceiptPb added in v0.3.0

func (receipt *Receipt) ConvertToReceiptPb() *iproto.ReceiptPb

ConvertToReceiptPb converts a Receipt to protobuf's ReceiptPb

func (*Receipt) Deserialize added in v0.3.0

func (receipt *Receipt) Deserialize(buf []byte) error

Deserialize parse the byte stream into Receipt

func (*Receipt) Serialize added in v0.3.0

func (receipt *Receipt) Serialize() ([]byte, error)

Serialize returns a serialized byte stream for the Receipt

type Transfer added in v0.2.0

type Transfer struct {
	Amount    int64  `yaml:"amount"`
	Recipient string `yaml:"recipient"`
	Signature string `yaml:"signature"`
}

Transfer is the Transfer struct

type Validator added in v0.2.0

type Validator interface {
	// Validate validates the given block's content
	Validate(block *Block, tipHeight uint64, tipHash hash.Hash32B) error
}

Validator is the interface of validator

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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