blockchain

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2018 License: Apache-2.0 Imports: 37 Imported by: 30

Documentation

Index

Constants

View Source
const (
	// FailureStatus is the status that contract execution failed
	FailureStatus = uint64(0)
	// SuccessStatus is the status that contract execution success
	SuccessStatus = uint64(1)
)
View Source
const (
	// Rau is the smallest non-fungible token unit
	Rau int64 = 1
	// KRau is 1000 Rau
	KRau = Rau * 1000
	// MRau is 1000 KRau
	MRau = KRau * 1000
	// GRau is 1000 MRau
	GRau = MRau * 1000
	// Qev is 1000 GRau
	Qev = GRau * 1000
	// Jin is 1000 Qev
	Jin = Qev * 1000
	// Iotx is 1000 Jin, which should be fit into int64
	Iotx = Jin * 1000
)
View Source
const GasLimit = uint64(1000000000)

GasLimit is the total gas limit could be consumed in a block

View Source
const RecoveryHeightKey key = "recoveryHeight"

RecoveryHeightKey indicates the recovery height key used by context

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 action")
	// 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")
	// ErrDKGSecretProposal indicates the error of DKG secret proposal
	ErrDKGSecretProposal = errors.New("invalid DKG secret proposal")
)
View Source
var ErrInconsistentNonce = errors.New("Nonce is not identical to executor nonce")

ErrInconsistentNonce is the error that the nonce is different from executor's nonce

View Source
var Gen = &Genesis{
	TotalSupply:         ConvertIotxToRau(10000000000),
	BlockReward:         ConvertIotxToRau(5),
	Timestamp:           uint64(1524676419),
	ParentHash:          hash.Hash32B{},
	GenesisCoinbaseData: "Connecting the physical world, block by block",
}

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 ConvertIotxToRau added in v0.4.0

func ConvertIotxToRau(iotx int64) *big.Int

ConvertIotxToRau converts an Iotx to Rau

func ExecuteContracts added in v0.3.0

func ExecuteContracts(blk *Block, ws state.WorkingSet, bc Blockchain, gasLimit *uint64, enableGasCharge bool)

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 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
	Actions         []action.Action
	SecretProposals []*action.SecretProposal
	SecretWitness   *action.SecretWitness

	Footer *BlockFooter
	// contains filtered or unexported fields
}

Block defines the struct of block

func NewBlock

func NewBlock(
	chainID uint32,
	height uint64,
	prevBlockHash hash.Hash32B,
	timestamp uint64,
	producer keypair.PublicKey,
	actions []action.Action,
) *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 NewSecretBlock added in v0.4.0

func NewSecretBlock(
	chainID uint32,
	height uint64,
	prevBlockHash hash.Hash32B,
	timestamp uint64,
	producer keypair.PublicKey,
	secretProposals []*action.SecretProposal,
	secretWitness *action.SecretWitness,
) *Block

NewSecretBlock returns a new DKG secret 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) CalculateTxRoot added in v0.4.0

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

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

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) PrevHash

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

PrevHash returns the hash of prev block

func (*Block) ProducerAddress added in v0.4.0

func (b *Block) ProducerAddress() string

ProducerAddress returns the address of producer

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) StateRoot added in v0.4.0

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

StateRoot returns the state root after apply this block.

func (*Block) TxRoot added in v0.2.0

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

TxRoot returns the hash of all actions in this block.

func (*Block) VerifySignature added in v0.4.0

func (b *Block) VerifySignature() bool

VerifySignature verifies the signature saved in block header

func (*Block) VerifyStateRoot added in v0.4.0

func (b *Block) VerifyStateRoot(root hash.Hash32B) error

VerifyStateRoot verifies the state root in header

type BlockFooter added in v0.4.0

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

BlockFooter defines a set of proof of 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 account with initial balance to the factory
	CreateState(addr string, init *big.Int) (*state.Account, error)
	// 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)
	// GetTotalActions returns the total number of actions
	GetTotalActions() (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) (*action.Receipt, error)
	// GetActionsFromAddress returns actions from address
	GetActionsFromAddress(address string) ([]hash.Hash32B, error)
	// GetActionsToAddress returns actions to address
	GetActionsToAddress(address string) ([]hash.Hash32B, error)
	// GetActionByActionHash returns action by action hash
	GetActionByActionHash(h hash.Hash32B) (action.Action, error)
	// GetBlockHashByActionHash returns Block hash by action hash
	GetBlockHashByActionHash(h hash.Hash32B) (hash.Hash32B, error)
	// GetFactory returns the state factory
	GetFactory() state.Factory
	// GetChainID returns the chain ID
	ChainID() uint32
	// ChainAddress returns chain address on parent chain, the root chain return empty.
	ChainAddress() string
	// TipHash returns tip block's hash
	TipHash() hash.Hash32B
	// TipHeight returns tip block's height
	TipHeight() uint64
	// StateByAddr returns account of a given address
	StateByAddr(address string) (*state.Account, error)

	// For block operations
	// MintNewBlock creates a new block with given actions and dkg keys
	// Note: the coinbase transfer will be added to the given transfers when minting a new block
	MintNewBlock(
		actions []action.Action,
		producer *iotxaddress.Address,
		dkgAddress *iotxaddress.DKGAddress,
		seed []byte,
		data string,
	) (*Block, error)
	// MintNewSecretBlock creates a new DKG secret block with given DKG secrets and witness
	MintNewSecretBlock(secretProposals []*action.SecretProposal, secretWitness *action.SecretWitness,
		producer *iotxaddress.Address) (*Block, error)
	// 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, containCoinbase bool) 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)

	// SubscribeBlockCreation make you listen to every single produced block
	SubscribeBlockCreation(ch chan *Block) error

	// UnsubscribeBlockCreation make you listen to every single produced block
	UnsubscribeBlockCreation(ch chan *Block) 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 Creator added in v0.4.0

type Creator struct {
	PubKey string `yaml:"pubKey"`
	PriKey string `yaml:"priKey"`
}

Creator is the Creator of the genesis block

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, ws state.WorkingSet, 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 existence 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() []*action.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 {
	TotalSupply         *big.Int
	BlockReward         *big.Int
	Timestamp           uint64
	ParentHash          hash.Hash32B
	GenesisCoinbaseData string
	CreatorPubKey       string
	CreatorPrivKey      string
}

Genesis defines the Genesis default settings

func (*Genesis) CreatorAddr added in v0.2.0

func (g *Genesis) CreatorAddr(chainID uint32) string

CreatorAddr returns the creator address on a particular chain

func (*Genesis) CreatorPKHash added in v0.4.0

func (g *Genesis) CreatorPKHash() hash.PKHash

CreatorPKHash returns the creator public key hash

type GenesisAction added in v0.2.0

type GenesisAction struct {
	Creation       Creator     `yaml:"creator"`
	SelfNominators []Nominator `yaml:"selfNominators"`
	Transfers      []Transfer  `yaml:"transfers"`
	SubChains      []SubChain  `yaml:"subChains"`
}

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

type Nominator added in v0.2.0

type Nominator struct {
	PubKey string `yaml:"pubKey"`
	PriKey string `yaml:"priKey"`
}

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 SubChain added in v0.4.0

type SubChain struct {
	ChainID            uint32 `yaml:"chainID"`
	SecurityDeposit    int64  `yaml:"securityDeposit"`
	OperationDeposit   int64  `yaml:"operationDeposit"`
	StartHeight        uint64 `yaml:"startHeight"`
	ParentHeightOffset uint64 `yaml:"parentHeightOffset"`
}

SubChain is the SubChain struct

type Transfer added in v0.2.0

type Transfer struct {
	Amount      int64  `yaml:"amount"`
	RecipientPK string `yaml:"recipientPK"`
}

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, containCoinbase bool) error
}

Validator is the interface of validator

Jump to

Keyboard shortcuts

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