types

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2019 License: LGPL-3.0 Imports: 16 Imported by: 175

Documentation

Index

Constants

View Source
const (
	UserDeposit        = iota // deposit
	StartUserExit             // start exit
	EndUserExit               // end exit
	ChallengedUserExit        // challenge result
)
View Source
const DebtSize = 118

DebtSize debt serialized size

View Source
const TestDebtTargetShard = 2
View Source
const TestGenesisShard = 1
View Source
const (

	// TransactionPreSize is the transaction size excluding payload size
	TransactionPreSize = 177
)

Variables

View Source
var (
	// ErrBlockHeaderNil is returned when the block header is nil.
	ErrBlockHeaderNil = errors.New("block header is nil")

	// ErrBlockHashMismatch is returned when the block hash does not match the header hash.
	ErrBlockHashMismatch = errors.New("block header hash mismatch")

	// ErrBlockTxsHashMismatch is returned when the block transactions hash does not match
	// the transaction root hash in the header.
	ErrBlockTxsHashMismatch = errors.New("block transactions root hash mismatch")

	// ErrBlockTxDebtHashMismatch is returned when the calculated tx debts hash of block
	// does not match the debts root hash in block header.
	ErrBlockTxDebtHashMismatch = errors.New("block transaction debts hash mismatch")

	// ErrBlockDebtHashMismatch is returned when the calculated debts hash of block
	// does not match the debts root hash in block header.
	ErrBlockDebtHashMismatch = errors.New("block debts hash mismatch")
)
View Source
var (
	// IstanbulDigest represents a hash of "Istanbul practical byzantine fault tolerance"
	// to identify whether the block is from Istanbul consensus engine
	IstanbulWitness = common.MustHexToHash("0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365").Bytes()

	IstanbulExtraVanity = 32 // Fixed number of extra-data bytes reserved for validator vanity
	IstanbulExtraSeal   = 65 // Fixed number of extra-data bytes reserved for validator seal

	// ErrInvalidIstanbulHeaderExtra is returned if the length of extra-data is less than 32 bytes
	ErrInvalidIstanbulHeaderExtra = errors.New("invalid istanbul header extra-data")
)
View Source
var (
	// ErrAmountNegative is returned when the transaction amount is negative.
	ErrAmountNegative = errors.New("amount is negative")

	// ErrAmountNil is returned when the transaction amount is nil.
	ErrAmountNil = errors.New("amount is null")

	// ErrPriceNegative is returned when the transaction gas price is negative or zero.
	ErrPriceNegative = errors.New("gas price is negative or zero")

	// ErrPriceNil is returned when the transaction gas price is nil.
	ErrPriceNil = errors.New("gas price is nil")

	// ErrIntrinsicGas is returned if the tx gas is too low.
	ErrIntrinsicGas = errors.New("intrinsic gas too low")

	// ErrHashMismatch is returned when the transaction hash and data mismatch.
	ErrHashMismatch = errors.New("hash mismatch")

	// ErrPayloadOversized is returned when the payload size is larger than the MaxPayloadSize.
	ErrPayloadOversized = errors.New("oversized payload")

	// ErrPayloadEmpty is returned when create or call a contract without payload.
	ErrPayloadEmpty = errors.New("empty payload")

	// ErrSigInvalid is returned when the transaction signature is invalid.
	ErrSigInvalid = errors.New("signature is invalid")

	// ErrSigMissing is returned when the transaction signature is missing.
	ErrSigMissing = errors.New("signature missing")

	// MaxPayloadSize limits the payload size to prevent malicious transactions.
	MaxPayloadSize = defaultMaxPayloadSize

	// TransferAmountIntrinsicGas is the intrinsic gas to transfer amount.
	TransferAmountIntrinsicGas = ethIntrinsicGas(nil)

	CrossShardTransactionGas = TransferAmountIntrinsicGas

	DebtGas = 2 * TransferAmountIntrinsicGas

	CrossShardTotalGas = CrossShardTransactionGas + DebtGas
)
View Source
var (
	ErrMsgVerifierFailed = "failed to validate debt via verifier"
)
View Source
var TestGenesisAccount = NewTestAccount(new(big.Int).Mul(big.NewInt(100000), common.SeeleToFan), 0, TestGenesisShard)

genesis account with enough balance (100K seele) for benchmark test

Functions

func BatchValidate

func BatchValidate(handler func(index int) error, len int) error

func BatchValidateDebt

func BatchValidateDebt(debts []*Debt, verifier DebtVerifier) error

func BatchValidateTxs

func BatchValidateTxs(txs []*Transaction) error

BatchValidateTxs validates the state independent fields of specified txs in multiple threads. Because the signature verification is time consuming (see test Benchmark_Transaction_ValidateWithoutState), once a block includes too many txs (e.g. 5000), the txs validation will consume too much time.

func DebtArrayToMap

func DebtArrayToMap(debts []*Debt) [][]*Debt

DebtArrayToMap transfer debt array to debt map

func DebtMerkleRootHash

func DebtMerkleRootHash(debts []*Debt) common.Hash

DebtMerkleRootHash calculates and returns the merkle root hash of the specified debts. If the given receipts are empty, return empty hash.

func GetDebtTrie

func GetDebtTrie(debts []*Debt) *trie.Trie

GetDebtTrie generates a debt trie for the specified debts.

func GetDebtsSize

func GetDebtsSize(debts []*Debt) int

GetDebtsSize is the bytes of debts

func GetReceiptTrie

func GetReceiptTrie(receipts []*Receipt) *trie.Trie

GetReceiptTrie generate trie according the receipts

func GetTransactionsSize

func GetTransactionsSize(txs []*Transaction) int

GetTransactionsSize return the transaction size

func GetTxTrie

func GetTxTrie(txs []*Transaction) *trie.Trie

GetTxTrie generate trie according the txs

func MerkleRootHash

func MerkleRootHash(txs []*Transaction) common.Hash

MerkleRootHash calculates and returns the merkle root hash of the specified transactions. If the given transactions are empty, return empty hash.

func NewDebtMap

func NewDebtMap(txs []*Transaction) [][]*Debt

NewDebtMap new debt map

func NewTestAccount

func NewTestAccount(amount *big.Int, nonce uint64, shard uint) *testAccount

func ReceiptMerkleRootHash

func ReceiptMerkleRootHash(receipts []*Receipt) common.Hash

ReceiptMerkleRootHash calculates and returns the merkle root hash of the specified receipts. If the given receipts are empty, return empty hash.

Types

type Block

type Block struct {
	HeaderHash   common.Hash    // HeaderHash is the hash of the RLP encoded header bytes
	Header       *BlockHeader   // Header is the block header, a block header is about 165byte
	Transactions []*Transaction // Transactions is the block payload
	Debts        []*Debt        // Debts for cross shard transaction
}

Block represents a block in the blockchain.

func NewBlock

func NewBlock(header *BlockHeader, txs []*Transaction, receipts []*Receipt, debts []*Debt) *Block

NewBlock creates a new block. The input header is copied so that any change will not affect the block. The input transaction array is copied, but each transaction is not copied. So any change of the input transaction will affect the block. The input receipt array is the same behavior with transaction array.

func NewBlockWithHeader

func NewBlockWithHeader(header *BlockHeader) *Block

NewBlockWithHeader creates a block with the given header data. The header data is copied, changes to header and to the field values will not affect the block.

func (*Block) FindTransaction

func (block *Block) FindTransaction(txHash common.Hash) *Transaction

FindTransaction returns the transaction of the specified hash if found. Otherwise, it returns nil.

func (*Block) GetExcludeRewardTransactions

func (block *Block) GetExcludeRewardTransactions() []*Transaction

GetExcludeRewardTransactions returns all txs of a block except for the reward transaction

func (*Block) GetShardNumber

func (block *Block) GetShardNumber() uint

GetShardNumber returns the shard number of the block, which means the shard number of the creator.

func (*Block) Hash

func (b *Block) Hash() common.Hash

func (*Block) Height

func (b *Block) Height() uint64

func (*Block) ParentHash

func (b *Block) ParentHash() common.Hash

func (*Block) Time

func (b *Block) Time() *big.Int

func (*Block) Validate

func (block *Block) Validate() error

Validate validates state independent fields in a block.

func (*Block) WithSeal

func (block *Block) WithSeal(header *BlockHeader) *Block

type BlockHeader

type BlockHeader struct {
	PreviousBlockHash common.Hash    // PreviousBlockHash represents the hash of the parent block
	Creator           common.Address // Creator is the coinbase of the miner which mined the block
	StateHash         common.Hash    // StateHash is the root hash of the state trie
	TxHash            common.Hash    // TxHash is the root hash of the transaction merkle tree
	ReceiptHash       common.Hash    // ReceiptHash is the root hash of the receipt merkle tree
	TxDebtHash        common.Hash    // TxDebtHash is the root hash of the tx's debt merkle tree
	DebtHash          common.Hash    // DebtHash is the root hash of the debt merkle tree
	Difficulty        *big.Int       // Difficulty is the difficulty of the block
	Height            uint64         // Height is the number of the block
	CreateTimestamp   *big.Int       // CreateTimestamp is the timestamp when the block is created
	// in pow consensus, witness is the nonce that proof whether the block is validate;
	// in spow consensus, witness and secondWitness are the nonce pair
	// in BFT consensus, witness is used to vote for validator candidates and Creator is the candidate address.
	Witness       []byte
	SecondWitness []byte
	Consensus     ConsensusType
	ExtraData     []byte // ExtraData stores the extra info of block header.
}

BlockHeader represents the header of a block in the blockchain.

func IstanbulFilteredHeader

func IstanbulFilteredHeader(h *BlockHeader, keepSeal bool) *BlockHeader

IstanbulFilteredHeader returns a filtered header which some information (like seal, committed seals) are clean to fulfill the Istanbul hash rules. It returns nil if the extra-data cannot be decoded/encoded by rlp.

func (*BlockHeader) Clone

func (header *BlockHeader) Clone() *BlockHeader

Clone returns a clone of the block header.

func (*BlockHeader) Hash

func (header *BlockHeader) Hash() common.Hash

Hash calculates and returns the hash of the block header.

type ConsensusType

type ConsensusType uint
const (
	PowConsensus ConsensusType = iota
	IstanbulConsensus
)

type Debt

type Debt struct {
	Hash common.Hash // Debt hash of DebtData
	Data DebtData
}

Debt debt class

func NewDebtWithContext

func NewDebtWithContext(tx *Transaction) *Debt

NewDebtWithContext new a debt

func NewDebtWithoutContext

func NewDebtWithoutContext(tx *Transaction) *Debt

NewDebtWithoutContext new debt

func NewDebts

func NewDebts(txs []*Transaction) []*Debt

NewDebts new debts

func NewTestDebt

func NewTestDebt() *Debt

func NewTestDebtDetail

func NewTestDebtDetail(amount int64, price int64) *Debt

func NewTestDebtWithTargetShard

func NewTestDebtWithTargetShard(targeShard uint) *Debt

func (*Debt) Fee

func (d *Debt) Fee() *big.Int

func (*Debt) FromAccount

func (d *Debt) FromAccount() common.Address

func (*Debt) GetHash

func (d *Debt) GetHash() common.Hash

func (*Debt) Nonce

func (d *Debt) Nonce() uint64

func (*Debt) Price

func (d *Debt) Price() *big.Int

func (*Debt) Size

func (d *Debt) Size() int

Size is the bytes of debt

func (*Debt) ToAccount

func (d *Debt) ToAccount() common.Address

func (*Debt) Validate

func (d *Debt) Validate(verifier DebtVerifier, isPool bool, targetShard uint) (recoverable bool, retErr error)

Validate validate debt with verifier If verifier is nil, will skip it. If isPool is true, we don't return error when the error is recoverable

type DebtData

type DebtData struct {
	TxHash  common.Hash // the hash of the executed transaction
	From    common.Address
	Nonce   uint64
	Account common.Address // debt for account
	Amount  *big.Int       // debt amount
	Price   *big.Int       // debt price
	Code    common.Bytes   // debt contract code
}

DebtData debt data

func (*DebtData) Hash

func (data *DebtData) Hash() common.Hash

type DebtIndex

type DebtIndex indexInBlock

DebtIndex debt index

type DebtVerifier

type DebtVerifier interface {
	// ValidateDebt validate debt
	// returns packed whether debt is packed
	// returns confirmed whether debt is confirmed
	// returns retErr error info
	ValidateDebt(debt *Debt) (packed bool, confirmed bool, err error)

	// IfDebtPacked
	// returns packed whether debt is packed
	// returns confirmed whether debt is confirmed
	// returns retErr error info
	IfDebtPacked(debt *Debt) (packed bool, confirmed bool, err error)
}

DebtVerifier interface

type IstanbulExtra

type IstanbulExtra struct {
	Validators    []common.Address
	Seal          []byte
	CommittedSeal [][]byte
}

func ExtractIstanbulExtra

func ExtractIstanbulExtra(h *BlockHeader) (*IstanbulExtra, error)

ExtractIstanbulExtra extracts all values of the IstanbulExtra from the header. It returns an error if the length of the given extra-data is less than 32 bytes or the extra-data can not be decoded.

func (*IstanbulExtra) DecodeRLP

func (ist *IstanbulExtra) DecodeRLP(s *rlp.Stream) error

DecodeRLP implements rlp.Decoder, and load the istanbul fields from a RLP stream.

func (*IstanbulExtra) EncodeRLP

func (ist *IstanbulExtra) EncodeRLP(w io.Writer) error

EncodeRLP serializes ist into the Ethereum RLP format.

type Log

type Log struct {
	// Consensus fields:
	// address of the contract that generated the event
	Address common.Address
	// list of topics provided by the contract.
	Topics []common.Hash
	// supplied by the contract, usually ABI-encoded
	Data []byte
	// Derived fields. These fields are filled in by the node
	// but not secured by consensus.
	// block in which the transaction was included
	BlockNumber uint64
	// index of the transaction in the block
	TxIndex uint
}

Log represents the contract execution log.

func (*Log) MarshalJSON

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

MarshalJSON marshal in hex string instead of base64

type Receipt

type Receipt struct {
	Result          []byte      // the execution result of the tx
	Failed          bool        // indicates if execution failed
	UsedGas         uint64      // tx used gas
	PostState       common.Hash // the root hash of the state trie after the tx is processed.
	Logs            []*Log      // the log objects
	TxHash          common.Hash // the hash of the executed transaction
	ContractAddress []byte      // Used when the tx (nil To address) is to create a contract.
	TotalFee        uint64      // the full cost of the transaction
}

Receipt represents the transaction processing receipt.

type ReceiptIndex

type ReceiptIndex indexInBlock

ReceiptIndex represents an index that used to query block info by tx hash.

type SubTransaction

type SubTransaction struct {
	Hash common.Hash // SubTransaction hash of SubTransactionData
	Data SubTransactionData
}

SubTransaction SubTransaction class

func NewChallengedUserExitSubTransaction

func NewChallengedUserExitSubTransaction(txHash common.Hash, args []interface{}) (*SubTransaction, error)

func NewDepositSubTransaction

func NewDepositSubTransaction(txHash common.Hash, args []interface{}) (*SubTransaction, error)

func NewEndUserExitSubTransaction

func NewEndUserExitSubTransaction(txHash common.Hash, args []interface{}) (*SubTransaction, error)

func NewStartUserExitSubTransaction

func NewStartUserExitSubTransaction(txHash common.Hash, args []interface{}) (*SubTransaction, error)

type SubTransactionData

type SubTransactionData struct {
	TxHash common.Hash // the hash of the executed transaction
	From   common.Address
	To     common.Address
	Nonce  uint64
	Amount *big.Int
	Bond   *big.Int
}

SubTransactionData subchain transaction data

func (*SubTransactionData) Hash

func (data *SubTransactionData) Hash() common.Hash

type TestVerifier

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

func NewTestVerifier

func NewTestVerifier(p bool, c bool, err error) *TestVerifier

func (*TestVerifier) IfDebtPacked

func (v *TestVerifier) IfDebtPacked(debt *Debt) (packed bool, confirmed bool, err error)

func (*TestVerifier) ValidateDebt

func (v *TestVerifier) ValidateDebt(debt *Debt) (packed bool, confirmed bool, err error)

type TestVerifierWithFunc

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

func NewTestVerifierWithFunc

func NewTestVerifierWithFunc(fun func(debt *Debt) (bool, bool, error)) *TestVerifierWithFunc

func (*TestVerifierWithFunc) IfDebtPacked

func (v *TestVerifierWithFunc) IfDebtPacked(debt *Debt) (packed bool, confirmed bool, err error)

func (*TestVerifierWithFunc) ValidateDebt

func (v *TestVerifierWithFunc) ValidateDebt(debt *Debt) (packed bool, confirmed bool, err error)

type Transaction

type Transaction struct {
	Hash      common.Hash      // Hash is the hash of the transaction data
	Data      TransactionData  // Data is the transaction data
	Signature crypto.Signature // Signature is the signature of the transaction
}

Transaction represents a transaction in the blockchain.

func NewContractTransaction

func NewContractTransaction(from common.Address, amount *big.Int, price *big.Int, gasLimit uint64, nonce uint64, code []byte) (*Transaction, error)

NewContractTransaction returns a transaction to create a smart contract.

func NewMessageTransaction

func NewMessageTransaction(from, to common.Address, amount *big.Int, price *big.Int, gasLimit uint64, nonce uint64, msg []byte) (*Transaction, error)

NewMessageTransaction returns a transaction with the specified message.

func NewTestCrossShardTransaction

func NewTestCrossShardTransaction() *Transaction

func NewTestCrossShardTransactionWithNonce

func NewTestCrossShardTransactionWithNonce(nonce uint64) *Transaction

func NewTestTransaction

func NewTestTransaction() *Transaction

func NewTestTransactionWithNonce

func NewTestTransactionWithNonce(nonce uint64) *Transaction

func NewTestTxDetail

func NewTestTxDetail(amount, price, nonce uint64) *Transaction

func NewTransaction

func NewTransaction(from, to common.Address, amount *big.Int, price *big.Int, nonce uint64) (*Transaction, error)

NewTransaction creates a new transaction to transfer asset. The transaction data hash is also calculated.

func (*Transaction) CalculateHash

func (tx *Transaction) CalculateHash() common.Hash

CalculateHash calculates and returns the transaction hash.

func (*Transaction) FromAccount

func (tx *Transaction) FromAccount() common.Address

func (*Transaction) GetHash

func (tx *Transaction) GetHash() common.Hash

func (*Transaction) IntrinsicGas

func (tx *Transaction) IntrinsicGas() uint64

IntrinsicGas computes the 'intrinsic gas' for a tx.

func (*Transaction) IsCrossShardTx

func (tx *Transaction) IsCrossShardTx() bool

IsCrossShardTx indicates whether the tx is to another shard.

func (*Transaction) Nonce

func (tx *Transaction) Nonce() uint64

func (*Transaction) Price

func (tx *Transaction) Price() *big.Int

func (*Transaction) Sign

func (tx *Transaction) Sign(privKey *ecdsa.PrivateKey)

Sign signs the transaction with the specified private key.

func (*Transaction) Size

func (tx *Transaction) Size() int

Size return the transaction size

func (*Transaction) ToAccount

func (tx *Transaction) ToAccount() common.Address

func (*Transaction) Validate

func (tx *Transaction) Validate(statedb stateDB) error

Validate validates all fields in tx.

func (*Transaction) ValidateState

func (tx *Transaction) ValidateState(statedb stateDB) error

ValidateState validates state dependent fields in tx.

func (*Transaction) ValidateWithoutState

func (tx *Transaction) ValidateWithoutState(signNeeded bool, shardNeeded bool) error

ValidateWithoutState validates state independent fields in tx.

type TransactionData

type TransactionData struct {
	Type         TxType         // Transaction type
	From         common.Address // From is the address of the sender
	To           common.Address // To is the receiver address, and empty address is used to create contract
	Amount       *big.Int       // Amount is the amount to be transferred
	AccountNonce uint64         // AccountNonce is the nonce of the sender account
	GasPrice     *big.Int       // Transaction gas price
	GasLimit     uint64         // Maximum gas for contract creation/execution
	Timestamp    uint64         // Timestamp is used for the miner reward transaction, referring to the block timestamp
	Payload      common.Bytes   // Payload is the extra data of the transaction
}

TransactionData wraps the data in a transaction.

type TxIndex

type TxIndex indexInBlock

TxIndex represents an index that used to query block info by tx hash.

type TxType

type TxType byte

TxType represents transaction type

const (
	TxTypeRegular TxType = iota
	TxTypeReward
)

Transaction types

Jump to

Keyboard shortcuts

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