types

package
v1.0.11 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2020 License: GPL-3.0 Imports: 17 Imported by: 3

Documentation

Overview

Package types define the key data structures for the chain

Package vm is used as the vm call chain

Index

Constants

View Source
const (
	TVMExecutedError     = 1001
	TVMGasNotEnoughError = 1002
	TVMCheckABIError     = 1003
	TVMCallMaxDeepError  = 1004
	TVMNoCodeError       = 1005
)
View Source
const (
	TransactionTypeTransfer       = 0
	TransactionTypeContractCreate = 1
	TransactionTypeContractCall   = 2

	// Miner operation related type
	TransactionTypeStakeAdd            = 3
	TransactionTypeMinerAbort          = 4
	TransactionTypeStakeReduce         = 5
	TransactionTypeStakeRefund         = 6
	TransactionTypeApplyGuardMiner     = 7 // apply guard node
	TransactionTypeVoteMinerPool       = 8 // vote to miner pool
	TransactionTypeChangeFundGuardMode = 9 // in half of year,can choose 6+5 or 6+6

	TransactionTypeBlacklistUpdate = 10

	// Group operation related type
	TransactionTypeGroupPiece       = SystemTransactionOffset + 1 //group member upload his encrypted share piece
	TransactionTypeGroupMpk         = SystemTransactionOffset + 2 //group member upload his mpk
	TransactionTypeGroupOriginPiece = SystemTransactionOffset + 3 //group member upload origin share piece
	TransactionTypeReward           = SystemTransactionOffset + 4
)

Supported transaction types

View Source
const (
	EpochLength           = 240 // blocks per epoch
	GroupLiveEpochs       = 25  // epochs one group can live
	GroupActivateEpochGap = 1   // The epoch gap after the group created can start working
)
View Source
const (
	MinerStatusPrepare MinerStatus = 0 // Miner prepare status, maybe abort or not enough stake or without pks,cannot participated any mining process
	MinerStatusActive              = 1 // Miner is activated, can participated in mining
	MinerStatusFrozen              = 2 // Miner frozen by system, cannot participated any mining process
)
View Source
const (
	MinerNormal      NodeIdentity = 0 // this is normal miner node,cannot be stake by others and stake to others
	MinerGuard                    = 1 // this miner is gurad miner node,cannot be stake by others
	MinerPool                     = 2 // this is miner pool node,can stake by others
	InValidMinerPool              = 3 // this is invalid miner pool.only can be reduce before meeting the minimum number of votes
)
View Source
const (
	BloomByteLength = 256
)
View Source
const PayloadVersion = 1
View Source
const SystemTransactionOffset = 100

Variables

View Source
var (
	DefaultPVFunc      PvFunc
	DefaultStakeGetter StakeGetter
)
View Source
var Bloom9 = bloom9
View Source
var MiddleWareLogger *logrus.Logger

MiddleWareLogger is middleware module system

View Source
var ZeroBigInt = new(BigInt).SetInt64(0)

ZeroBigInt indicate zero value

Functions

func AdminAddr added in v1.0.11

func AdminAddr() common.Address

func BlockToPb

func BlockToPb(b *Block) *tas_middleware_pb.Block

func BloomLookup

func BloomLookup(bin Bloom, topic bytesBacked) bool

func BusinessFoundationAddr added in v1.0.11

func BusinessFoundationAddr() common.Address

func CirculatesAddr added in v1.0.11

func CirculatesAddr() common.Address

func DaemonNodeAddress added in v1.0.11

func DaemonNodeAddress() common.Address

func EncodeBlackOperator added in v1.0.8

func EncodeBlackOperator(b *BlackOperator) ([]byte, error)

func EncodePayload

func EncodePayload(pks *MinerPks) ([]byte, error)

EncodePayload encodes pk and vrf pk into byte array storing in transaction data field

func GenBlackOperateSignData added in v1.0.8

func GenBlackOperateSignData(operator common.Address, nonce uint64, opType byte, addrs []common.Address) []byte

func GenesisDefaultGroupInfo added in v1.0.11

func GenesisDefaultGroupInfo() string

func GuardAddress added in v1.0.11

func GuardAddress() []common.Address

func InitMiddleware

func InitMiddleware()

func IsNormalChain

func IsNormalChain() bool

func IsProposalRole

func IsProposalRole(typ MinerType) bool

func IsVerifyRole

func IsVerifyRole(typ MinerType) bool

func LogsBloom

func LogsBloom(logs []*Log) *big.Int

func MarshalBlock

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

MarshalBlock serialize *Block

func MarshalBlockHeader

func MarshalBlockHeader(b *BlockHeader) ([]byte, error)

MarshalBlockHeader Serialize *BlockHeader

func MarshalTransactions

func MarshalTransactions(txs []*RawTransaction) ([]byte, error)

MarshalTransactions serialize []*Transaction

func StakePlatformAddr added in v1.0.11

func StakePlatformAddr() common.Address

func TeamFoundationAddr added in v1.0.11

func TeamFoundationAddr() common.Address

func TransactionsToPb

func TransactionsToPb(txs []*RawTransaction) []*tas_middleware_pb.RawTransaction

func UserNodeAddress added in v1.0.11

func UserNodeAddress() common.Address

Types

type Account

type Account interface {
	MinerSk() string
}

type AccountDB

type AccountDB interface {
	CreateAccount(common.Address)

	SubBalance(common.Address, *big.Int)
	AddBalance(common.Address, *big.Int)
	GetBalance(common.Address) *big.Int

	GetNonce(common.Address) uint64
	SetNonce(common.Address, uint64)

	GetCodeHash(common.Address) common.Hash
	GetCode(common.Address) []byte
	SetCode(common.Address, []byte)
	GetCodeSize(common.Address) int

	AddRefund(uint64)
	GetRefund() uint64

	GetStateObject(common.Address) account.AccAccesser
	GetData(common.Address, []byte) []byte
	SetData(common.Address, []byte, []byte)
	RemoveData(common.Address, []byte)
	DataIterator(common.Address, []byte) *trie.Iterator

	Suicide(common.Address) bool
	HasSuicided(common.Address) bool

	Exist(common.Address) bool
	Empty(common.Address) bool

	RevertToSnapshot(int)
	Snapshot() int

	Transfer(common.Address, common.Address, *big.Int)
	CanTransfer(common.Address, *big.Int) bool

	Database() account.AccountDatabase
}

type AccountRepository

type AccountRepository interface {
	// GetBalance return the balance of specified address
	GetBalance(address common.Address) *big.Int

	// GetBalance returns the nonce of specified address
	GetNonce(address common.Address) uint64
}

AccountRepository contains account query interface

type AddBlockOnChainSituation

type AddBlockOnChainSituation string

type AddBlockResult

type AddBlockResult int8

AddBlockResult is the result of the add-block operation

const (
	AddBlockFailed              AddBlockResult = -1 // Means the operations is fail
	AddBlockConsensusFailed     AddBlockResult = -2 // Means the consensus is fail
	AddBlockExisted             AddBlockResult = 1  // Means the block already added before
	AddBlockLessWeightThanLocal AddBlockResult = 2  // Weight consideration
	AddBlockSucc                AddBlockResult = 3  // Means success
)

defines all possible result of the add-block operation

type BigInt

type BigInt struct {
	big.Int
}

BigUint used as big.Int. Inheritance is for the implementation of Marshaler/Unmarshaler interface in msgpack framework

func NewBigInt

func NewBigInt(v uint64) *BigInt

func (*BigInt) GetBytesWithSign

func (b *BigInt) GetBytesWithSign() []byte

GetBytesWithSign returns a byte array of the number with the first byte representing its sign. It must be success

func (*BigInt) IsNegative

func (b *BigInt) IsNegative() bool

IsNegative check if the number is negative

func (*BigInt) MarshalMsgpack

func (b *BigInt) MarshalMsgpack() ([]byte, error)

MarshalMsgpack implements interface Marshaler

func (*BigInt) SetBytesWithSign

func (b *BigInt) SetBytesWithSign(bs []byte) *BigInt

SetBytesWithSign set the given bytes with the first byte representing its sign to the BigInt. It must be success

func (*BigInt) UnmarshalMsgpack

func (b *BigInt) UnmarshalMsgpack(bs []byte) error

UnmarshalMsgpack implements interface Unmarshaler

func (*BigInt) Value

func (b *BigInt) Value() *big.Int

type BlackOperator added in v1.0.8

type BlackOperator struct {
	Addrs  []common.Address
	OpType byte
	Signs  [][]byte // sign of guard nodes
}

func DecodeBlackOperator added in v1.0.8

func DecodeBlackOperator(bs []byte) (*BlackOperator, error)

type Block

type Block struct {
	Header       *BlockHeader
	Transactions []*RawTransaction
}

Block is the block data structure consists of the header and transactions as body

func PbToBlock

func PbToBlock(b *tas_middleware_pb.Block) *Block

func UnMarshalBlock

func UnMarshalBlock(bytes []byte) (*Block, error)

UnMarshalBlock deserialize from []byte to *Block

type BlockChain

type BlockChain interface {
	ChainReader
	AccountRepository

	// CastBlock cast a block, current casters synchronization operation in the group
	CastBlock(height uint64, proveValue []byte, qn uint64, castor []byte, groupSeed common.Hash) *Block

	// AddBlockOnChain add a block on blockchain, there are five cases of return value:
	// 0, successfully add block on blockchain
	// -1, verification failed
	// 1, the block already exist on the blockchain, then we should discard it
	// 2, the same height block with a larger QN value on the chain, then we should discard it
	// 3, need adjust the blockchain, there will be a fork
	AddBlockOnChain(source string, b *Block) AddBlockResult

	// TotalQN of chain
	TotalQN() uint64

	// LatestAccountDB returns chain's last account database
	LatestAccountDB() (AccountDB, error)

	// QueryBlockByHash query the block by hash
	QueryBlockByHash(hash common.Hash) *Block

	// QueryBlockByHeight query the block by height
	QueryBlockByHeight(height uint64) *Block

	// QueryBlockCeil query first block whose height >= height
	QueryBlockCeil(height uint64) *Block

	// QueryBlockHeaderCeil query first block header whose height >= height
	QueryBlockHeaderCeil(height uint64) *BlockHeader

	// QueryBlockFloor query first block whose height <= height
	QueryBlockFloor(height uint64) *Block

	// QueryBlockHeaderFloor query first block header whose height <= height
	QueryBlockHeaderFloor(height uint64) *BlockHeader

	// BatchGetBlocksAfterHeight query blocks after the specified height
	BatchGetBlocksAfterHeight(height uint64, limit int) []*Block

	// GetTransactionByHash get a transaction by hash
	GetTransactionByHash(onlyReward bool, h common.Hash) *Transaction

	// GetTransactionPool return the transaction pool waiting for the block
	GetTransactionPool() TransactionPool

	// IsAdjusting means whether need to adjust blockchain, which means there may be a fork
	IsAdjusting() bool

	// Remove removes the block and blocks after it from the chain. Only used in a debug file, should be removed later
	Remove(block *Block) bool

	// Clear clear blockchain all data
	Clear() error

	// Close the open levelDb files
	Close()

	// GetRewardManager returns the reward manager
	GetRewardManager() RewardManager

	// GetAccountDBByHash returns account database with specified block hash
	GetAccountDBByHash(hash common.Hash) (AccountDB, error)

	// AccountDBAt returns account database with specified block height
	AccountDBAt(height uint64) (AccountDB, error)

	// GetConsensusHelper returns consensus helper reference
	GetConsensusHelper() ConsensusHelper

	// Version of chain Id
	Version() int

	// ResetTop reset the current top block with parameter bh
	ResetTop(bh *BlockHeader) error

	// countBlocksInRange returns the count of block in a range of block height. the block with startHeight and endHeight
	// will be included
	CountBlocksInRange(startHeight uint64, endHeight uint64) uint64

	// returns latest checkpoint of the chain
	LatestCheckPoint() *BlockHeader

	IsSyncing() bool
}

BlockChain is a interface, encapsulates some methods for manipulating the blockchain

type BlockHeader

type BlockHeader struct {
	Hash        common.Hash    // The hash of this block
	Height      uint64         // The height of this block
	PreHash     common.Hash    // The hash of previous block
	Elapsed     int32          // The length of milliseconds from the last block
	ProveValue  []byte         // Vrf prove
	TotalQN     uint64         // QN of the entire chain
	CurTime     time.TimeStamp // Current block time
	Castor      []byte         // Proposer ID
	Group       common.Hash    // Verify group hash,hash of the seed block
	Signature   []byte         // Group signature from consensus
	Nonce       int32          // Salt
	TxTree      common.Hash    // Transaction Merkel root hash
	ReceiptTree common.Hash    // Receipte Merkel root hash
	StateTree   common.Hash    // State db Merkel root hash
	ExtraData   []byte
	Random      []byte // Random number generated during the consensus process
	GasFee      uint64 // gas fee of transaction executed in block
}

BlockHeader is block header structure

func UnMarshalBlockHeader

func UnMarshalBlockHeader(bytes []byte) (*BlockHeader, error)

UnMarshalBlockHeader deserialize from []byte to *BlockHeader

func (*BlockHeader) GenHash

func (bh *BlockHeader) GenHash() common.Hash

GenHash calculates the hash of the block

func (*BlockHeader) HasTransactions

func (bh *BlockHeader) HasTransactions() bool

func (*BlockHeader) PreTime

func (bh *BlockHeader) PreTime() time.TimeStamp

type BlockWeight

type BlockWeight struct {
	Proposer common.Address
	Height   uint64
	Hash     common.Hash
	TotalQN  uint64   // Same as TotalQN field of BlockHeader
	PV       *big.Int // Converted from ProveValue field of BlockHeader
	// contains filtered or unexported fields
}

BlockWeight denotes the weight of one block

func NewBlockWeight

func NewBlockWeight(bh *BlockHeader) *BlockWeight

func (*BlockWeight) Cmp

func (bw *BlockWeight) Cmp(bw2 *BlockWeight) int

Cmp compares the weight between current block and the given one. 1 returns if current block is more weight 0 returns if equal otherwise -1 is returned

func (*BlockWeight) MoreWeight

func (bw *BlockWeight) MoreWeight(bw2 *BlockWeight) bool

MoreWeight checks the current block is more weight than the given one

func (BlockWeight) String

func (bw BlockWeight) String() string

type Bloom

type Bloom [BloomByteLength]byte

func BytesToBloom

func BytesToBloom(b []byte) Bloom

BytesToBloom converts a byte slice to a bloom filter. It panics if b is not of suitable size.

func CreateBloom

func CreateBloom(receipts Receipts) Bloom

func (*Bloom) Add

func (b *Bloom) Add(d *big.Int)

Add adds d to the filter. Future calls of Test(d) will return true.

func (Bloom) Big

func (b Bloom) Big() *big.Int

Big converts b to a big integer.

func (Bloom) Bytes

func (b Bloom) Bytes() []byte

func (*Bloom) SetBytes

func (b *Bloom) SetBytes(d []byte)

func (Bloom) Test

func (b Bloom) Test(test *big.Int) bool

func (Bloom) TestBytes

func (b Bloom) TestBytes(test []byte) bool

type CandidateBlockHeader

type CandidateBlockHeader struct {
	BW *BlockWeight
	BH *BlockHeader
}

func NewCandidateBlockHeader

func NewCandidateBlockHeader(bh *BlockHeader) *CandidateBlockHeader

type CastRewardShare

type CastRewardShare struct {
	ForBlockProposal   uint64
	ForBlockVerify     uint64
	ForRewardTxPacking uint64
	FeeForProposer     uint64
	FeeForVerifier     uint64
}

CastRewardShare represents for the block generation reward

func (*CastRewardShare) TotalForVerifier

func (crs *CastRewardShare) TotalForVerifier() uint64

type ChainReader

type ChainReader interface {
	Height() uint64
	QueryTopBlock() *BlockHeader
	QueryBlockHeaderByHash(hash common.Hash) *BlockHeader
	QueryBlockHeaderByHeight(height uint64) *BlockHeader
	HasBlock(hash common.Hash) bool
	HasHeight(height uint64) bool
}

type CheckerContext

type CheckerContext interface {
	Height() uint64
}

type ConsensusHelper

type ConsensusHelper interface {

	// generate genesis group and pk info of members
	GenerateGenesisInfo() *GenesisInfo

	// convert the vrf prove to big int
	VRFProve2Value(prove []byte) *big.Int

	// calculate the blockheader's qn
	// it needs to be equal to the blockheader's totalQN - preHeader's totalQN
	CalculateQN(bh *BlockHeader) uint64

	// check the prove root hash for weight node when add block on chain
	CheckProveRoot(bh *BlockHeader) (bool, error)

	// check the new block
	// mainly verify the cast legality and the group signature
	VerifyNewBlock(bh *BlockHeader, preBH *BlockHeader) (bool, error)

	// verify the blockheader: mainly verify the group signature
	VerifyBlockSign(bh *BlockHeader) (bool, error)

	// verify reward transaction
	VerifyRewardTransaction(tx *Transaction) (bool, error)

	// estimate pre block's height
	EstimatePreHeight(bh *BlockHeader) uint64

	// VerifyBlockHeaders checks if the group is legal and the group signature is correct
	VerifyBlockHeaders(pre, bh *BlockHeader) (ok bool, err error)

	GroupSkipCountsBetween(preBH *BlockHeader, h uint64) map[common.Hash]uint16

	// return the min elapsed second for blocks
	GetBlockMinElapse(height uint64) int32
}

ConsensusHelper are consensus interface collection

type CreateResult

type CreateResult interface {
	SeedI
	Code() CreateResultCode // Seen in the CreateResultCode enum above
	GroupInfo() GroupI      // Return new groupInfo if create success
	FrozenMiners() [][]byte // Determines miners to be froze
	Err() error             // Error occurs
}

CreateResult is the group-create result presentation

type CreateResultCode

type CreateResultCode int
const (
	CreateResultSuccess  CreateResultCode = 1 // Group create success
	CreateResultMarkEvil CreateResultCode = 2 // Someone cheat, and mark the origin pieces required
	CreateResultFail     CreateResultCode = 3 // Error occurs
	CreateResultIdle     CreateResultCode = 4 // Idle round, won't start group-create routine
)

type EncryptedSharePiecePacket

type EncryptedSharePiecePacket interface {
	SharePiecePacket
	Pubkey0() []byte // Initial Pubkey
}

EncryptedSharePiecePacket is encrypted share piece data and only the corresponding receiver can decrypt it

type Epoch

type Epoch interface {
	Start() uint64
	End() uint64
	Next() Epoch
	Prev() Epoch
	Add(delta int) Epoch
	Equal(e Epoch) bool
}

func ActivateEpochOfGroupsCreatedAt

func ActivateEpochOfGroupsCreatedAt(h uint64) Epoch

ActivateEpochOfGroupsCreatedAt returns the active epoch of the groups created at the given height

func CreateEpochsOfActivatedGroupsAt

func CreateEpochsOfActivatedGroupsAt(h uint64) (start, end Epoch)

CreateEpochsOfActivatedGroupsAt returns the group-creating epoch ranges of the groups activated at the given height

func DismissEpochOfGroupsCreatedAt

func DismissEpochOfGroupsCreatedAt(h uint64) Epoch

DismissEpochOfGroupsCreatedAt returns the dismiss epoch of the groups created at the given height

func EpochAt

func EpochAt(h uint64) Epoch

EpochAt returns the Epoch of the given height

type ExecutedTransaction

type ExecutedTransaction struct {
	Receipt     *Receipt
	Transaction *Transaction
}

ExecutedTransaction contains the transaction and its receipt

type GenesisInfo

type GenesisInfo struct {
	Group  GroupI
	VrfPKs [][]byte
	Pks    [][]byte
}

GenesisInfo define genesis group info

type GroupCreateChecker

type GroupCreateChecker interface {
	// CheckEncryptedPiecePacket checks the encrypted share piece packet
	CheckEncryptedPiecePacket(packet EncryptedSharePiecePacket, ctx CheckerContext) error

	// CheckMpkPacket checks if the mpk packet legal
	CheckMpkPacket(packet MpkPacket, ctx CheckerContext) error

	// CheckGroupCreateResult checks if the group-create is success
	CheckGroupCreateResult(ctx CheckerContext) CreateResult

	// CheckOriginPiecePacket checks the origin share pieces packet is legal
	CheckOriginPiecePacket(packet OriginSharePiecePacket, ctx CheckerContext) error

	// CheckGroupCreatePunishment determines miners to be punished or rewarded
	CheckGroupCreatePunishment(ctx CheckerContext) (PunishmentMsg, error)
}

GroupCreateChecker provides function to check if the group-create related packets are legal

type GroupHeaderI

type GroupHeaderI interface {
	SeedI
	WorkHeight() uint64
	DismissHeight() uint64
	PublicKey() []byte
	Threshold() uint32
	GroupHeight() uint64
}

GroupHeaderI is the group header info interface

type GroupI

type GroupI interface {
	Header() GroupHeaderI
	Members() []MemberI
}

GroupI is the group info interface

type GroupInfoI

type GroupInfoI interface {
}

GroupInfoI is a group management interface

type GroupPacketSender

type GroupPacketSender interface {
	// SendEncryptedPiecePacket sends the encrypted packet to the pool
	SendEncryptedPiecePacket(packet EncryptedSharePiecePacket) error

	// SendMpkPacket sends the mpk packet to the pool
	SendMpkPacket(packet MpkPacket) error

	// SendOriginPiecePacket sends the origin packet to the pool
	SendOriginPiecePacket(packet OriginSharePiecePacket) error
}

GroupPacketSender provides functions for sending packets

type GroupStoreReader

type GroupStoreReader interface {
	// GetEncryptedPiecePackets Get the encrypted share packet of the given seed
	GetEncryptedPiecePackets(seed SeedI) ([]EncryptedSharePiecePacket, error)

	// HasSentEncryptedPiecePacket checks if the given sender has sent the packet yet
	HasSentEncryptedPiecePacket(sender []byte, seed SeedI) bool

	// HasSentMpkPacket checks if the given sender has sent the packet yet
	HasSentMpkPacket(sender []byte, seed SeedI) bool

	// GetMpkPackets Get the mpk packet of the given seed
	GetMpkPackets(seed SeedI) ([]MpkPacket, error)

	// IsOriginPieceRequired check if origin piece is required of the given seed
	IsOriginPieceRequired(seed SeedI) bool

	// GetOriginPiecePackets returns the origin share piece data of the given seed
	GetOriginPiecePackets(seed SeedI) ([]OriginSharePiecePacket, error)

	// HasSentOriginPiecePacket checks if the given sender has sent the packet yet
	HasSentOriginPiecePacket(sender []byte, seed SeedI) bool
}

GroupStoreReader provides function to access the data generated during the routine or group info

type Log

type Log struct {
	// Consensus fields:
	// address of the contract that generated the event
	Address common.Address `json:"address" gencodec:"required"`
	// list of topics provided by the contract.
	Topic common.Hash `json:"topic" gencodec:"required"`
	// supplied by the contract, usually ABI-encoded
	Data []byte `json:"data" gencodec:"required"`

	// Derived fields. These fields are filled in by the node
	// but not secured by consensus.
	// block in which the transaction was included
	BlockNumber uint64 `json:"block_number"`
	// hash of the transaction
	TxHash common.Hash `json:"transaction_hash" gencodec:"required"`
	// index of the transaction in the block
	TxIndex uint `json:"transaction_index" gencodec:"required"`
	// index of the log in the receipt
	Index uint `json:"log_index" gencodec:"required"`

	// The Removed field is true if this log was reverted due to a chain reorganisation.
	// You must pay attention to this field if you receive logs through a filter query.
	Removed bool `json:"removed"`
}

Log represents a contract log event. These events are generated by the LOG opcode and stored/indexed by the node.

func (*Log) String

func (l *Log) String() string

type MemberI

type MemberI interface {
	ID() []byte
	PK() []byte
}

MemberI is the group member interface

type Miner

type Miner struct {
	ID                   []byte
	PublicKey            []byte
	VrfPublicKey         []byte
	ApplyHeight          uint64
	Stake                uint64
	StatusUpdateHeight   uint64
	Type                 MinerType
	Status               MinerStatus
	Identity             NodeIdentity
	IdentityUpdateHeight uint64
}

Miner is the miner info including public keys and pledges

func (*Miner) IsActive

func (m *Miner) IsActive() bool

func (*Miner) IsFrozen

func (m *Miner) IsFrozen() bool

func (*Miner) IsGuard

func (m *Miner) IsGuard() bool

func (*Miner) IsInvalidMinerPool

func (m *Miner) IsInvalidMinerPool() bool

func (*Miner) IsMinerPool

func (m *Miner) IsMinerPool() bool

func (*Miner) IsNormal

func (m *Miner) IsNormal() bool

func (*Miner) IsPrepare

func (m *Miner) IsPrepare() bool

func (*Miner) IsProposalRole

func (m *Miner) IsProposalRole() bool

func (*Miner) IsVerifyRole

func (m *Miner) IsVerifyRole() bool

func (*Miner) PksCompleted

func (m *Miner) PksCompleted() bool

func (*Miner) UpdateIdentity

func (m *Miner) UpdateIdentity(identity NodeIdentity, height uint64)

func (*Miner) UpdateStatus

func (m *Miner) UpdateStatus(status MinerStatus, height uint64)

type MinerPks

type MinerPks struct {
	MType MinerType
	Pk    []byte
	VrfPk []byte
}

func DecodePayload

func DecodePayload(bs []byte) (*MinerPks, error)

DecodePayload decodes the data field of the miner related transaction

type MinerStatus

type MinerStatus byte

type MinerType

type MinerType byte
const (
	MinerTypeVerify   MinerType = iota // Proposal role
	MinerTypeProposal                  // Verify role
)

defines the miner role type

type MpkPacket

type MpkPacket interface {
	SeedI
	SenderI
	Mpk() []byte  // Pubkey aggregated
	Sign() []byte // Signature to the seed signed by the Mpk
}

MpkPacket contains the signature pubkey of the group which is aggregated from the share pieces received

type NodeIdentity

type NodeIdentity byte

type OriginSharePiecePacket

type OriginSharePiecePacket interface {
	SharePiecePacket
	EncSeckey() []byte
}

OriginSharePiecePacket is the origin share piece data which is not encrypted

type PunishmentMsg

type PunishmentMsg interface {
	PenaltyTarget() [][]byte // Determines miners to be punished
	RewardTarget() [][]byte  // Determines miners to be rewarded
}

PunishmentMsg is the punishment message when someone cheats

type PvFunc

type PvFunc func(pvBytes []byte) *big.Int

type RawTransaction

type RawTransaction struct {
	Data   []byte          `msgpack:"dt,omitempty"` // Data of the transaction, cost gas
	Value  *BigInt         `msgpack:"v"`            // The value the sender suppose to transfer
	Nonce  uint64          `msgpack:"nc"`           // The nonce indicates the transaction sequence related to sender
	Target *common.Address `msgpack:"tg,omitempty"` // The receiver address
	Type   int8            `msgpack:"tp"`           // Transaction type

	GasLimit *BigInt `msgpack:"gl"`
	GasPrice *BigInt `msgpack:"gp"`

	ExtraData []byte          `msgpack:"ed"`
	Sign      []byte          `msgpack:"si"`            // The Sign of the sender
	Source    *common.Address `msgpack:"src,omitempty"` // Sender address, recovered from sign
}

RawTransaction denotes one raw transaction infos used for network transmission and storage system

func PbToTransactions

func PbToTransactions(txs []*tas_middleware_pb.RawTransaction) []*RawTransaction

func UnMarshalTransactions

func UnMarshalTransactions(b []byte) ([]*RawTransaction, error)

UnMarshalTransactions deserialize from []byte to *Transaction

func (*RawTransaction) GenHash

func (tx *RawTransaction) GenHash() common.Hash

GenHash generate unique hash of the transaction. source,sign is out of the hash calculation range

func (RawTransaction) GetData

func (tx RawTransaction) GetData() []byte

func (*RawTransaction) GetExtraData

func (tx *RawTransaction) GetExtraData() []byte

func (RawTransaction) GetGasLimit

func (tx RawTransaction) GetGasLimit() uint64

func (RawTransaction) GetGasLimitOriginal

func (tx RawTransaction) GetGasLimitOriginal() *big.Int

func (*RawTransaction) GetNonce

func (tx *RawTransaction) GetNonce() uint64

func (*RawTransaction) GetSign

func (tx *RawTransaction) GetSign() []byte

func (RawTransaction) GetSource

func (tx RawTransaction) GetSource() *common.Address

func (RawTransaction) GetTarget

func (tx RawTransaction) GetTarget() *common.Address

func (*RawTransaction) GetType

func (tx *RawTransaction) GetType() int8

func (RawTransaction) GetValue

func (tx RawTransaction) GetValue() uint64

func (*RawTransaction) HexSign

func (tx *RawTransaction) HexSign() string

func (*RawTransaction) IsReward

func (tx *RawTransaction) IsReward() bool

func (*RawTransaction) Size

func (tx *RawTransaction) Size() int

type Receipt

type Receipt struct {
	PostState         []byte        `json:"-"`
	Status            ReceiptStatus `json:"status"`
	CumulativeGasUsed uint64        `json:"cumulativeGasUsed"`
	Bloom             Bloom         `json:"-"`
	Logs              []*Log        `json:"logs"`

	TxHash          common.Hash    `json:"transactionHash" gencodec:"required"`
	ContractAddress common.Address `json:"contractAddress"`
	Height          uint64         `json:"height"`
	TxIndex         uint16         `json:"tx_index"`
}

func NewReceipt

func NewReceipt(root []byte, status ReceiptStatus, cumulativeGasUsed uint64) *Receipt

func (*Receipt) Size

func (r *Receipt) Size() common.StorageSize

func (*Receipt) String

func (r *Receipt) String() string

func (*Receipt) Success

func (r *Receipt) Success() bool

type ReceiptStatus

type ReceiptStatus int
const (
	RSSuccess ReceiptStatus = iota
	RSFail
	RSBalanceNotEnough
	RSAbiError
	RSTvmError
	RSGasNotEnoughError
	RSNoCodeError
	RSParseFail
	RSMinerStakeFrozen
	RSMinerStakeOverLimit
	RSMinerStakeLessThanReduce
	RSMinerVerifyLowerStake
	RSMinerVerifyInGroup
	RSMinerReduceHeightNotEnough
	RSVoteNotInRound
	RSMinerUnSupportOp
	RSMinerNotFullStake
	RSMinerMaxApplyGuard
	RSMinerChangeModeExpired
	RSMinerAbortHasPrepared
	RSMinerRefundHeightNotEnougn
	RSMinerNotExists
)

type Receipts

type Receipts []*Receipt

func (Receipts) Len

func (r Receipts) Len() int

type Reward

type Reward struct {
	TxHash     common.Hash
	TargetIds  []int32
	BlockHash  common.Hash
	Group      common.Hash
	Sign       []byte
	TotalValue uint64
	PackFee    uint64
}

Reward is the reward transaction raw data

type RewardManager

type RewardManager interface {
	GetRewardTransactionByBlockHash(blockHash common.Hash) *Transaction
	GenerateReward(targetIds []int32, blockHash common.Hash, gSeed common.Hash, totalValue uint64, packFee uint64) (*Reward, *Transaction, error)
	ParseRewardTransaction(msg TxMessage) (gSeed common.Hash, targets [][]byte, blockHash common.Hash, packFee *big.Int, err error)
	CalculateCastRewardShare(height uint64, gasFee uint64) *CastRewardShare
	HasRewardedOfBlock(blockHash common.Hash, accountdb AccountDB) bool
	MarkBlockRewarded(blockHash common.Hash, transactionHash common.Hash, accountdb AccountDB)
}

type SeedI

type SeedI interface {
	Seed() common.Hash
}

SeedI is the seed block which the group-create routine based on

type SenderI

type SenderI interface {
	Sender() []byte
}

type SharePiecePacket

type SharePiecePacket interface {
	SeedI
	SenderI
	Pieces() []byte // Encrypted pieces data
}

SharePiecePacket contains share piece data generated during the group-create routine

type StakeDetail

type StakeDetail struct {
	Source        common.Address
	Target        common.Address
	Value         uint64
	Status        StakeStatus
	UpdateHeight  uint64
	MType         MinerType
	DisMissHeight uint64
}

StakeDetail expresses the stake detail

type StakeGetter

type StakeGetter func(addr common.Address, height uint64) uint64

Function for getting stake of the given proposer at the given block

type StakeStatus

type StakeStatus = byte

StakeStatus indicates the stake status

const (
	Staked          StakeStatus = iota // Normal status
	StakeFrozen                        // Frozen status
	StakePunishment                    // Punishment status, can't never refund
)

type SyncingPeerTop

type SyncingPeerTop struct {
	Top           *CandidateBlockHeader
	SyncingHeight uint64
}

type Transaction

type Transaction struct {
	*RawTransaction
	Hash common.Hash `msgpack:"-"` // Generated by GenHash and doesn't serialize
}

Transaction denotes one transaction infos

func NewTransaction

func NewTransaction(raw *RawTransaction, hash common.Hash) *Transaction

func (*Transaction) Amount

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

func (Transaction) GetHash

func (tx Transaction) GetHash() common.Hash

func (*Transaction) OpTarget

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

func (*Transaction) OpType

func (tx *Transaction) OpType() int8

func (*Transaction) Operator

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

func (*Transaction) Payload

func (tx *Transaction) Payload() []byte

type TransactionError

type TransactionError struct {
	Code    int
	Message string
}

func NewTransactionError

func NewTransactionError(code int, msg string) *TransactionError

type TransactionPool

type TransactionPool interface {
	// PackForCast returns a list of transactions for casting a block
	PackForCast() []*Transaction

	// AddTransaction adds new transaction to the transaction pool which will be broadcast
	AddTransaction(tx *Transaction) (bool, error)

	// AsyncAddTransaction adds transaction to the transaction pool which won't be broadcast
	AsyncAddTransaction(tx *Transaction) error

	// GetTransaction trys to find a transaction from pool by hash and return it
	GetTransaction(reward bool, hash common.Hash) *Transaction

	// GetReceipt returns the transaction's recipe by hash
	GetReceipt(hash common.Hash) *Receipt

	// GetReceived returns the received transactions in the pool with a limited size
	GetReceived() []*Transaction

	// GetAllTxs returns the all received transactions(including pending and queue) in the pool with a limited size
	GetAllTxs() []*Transaction

	// GetRewardTxs returns all the reward transactions in the pool
	GetRewardTxs() []*Transaction

	// TxNum returns the number of transactions in the pool
	TxNum() uint64

	// TxNum returns the number of transactions in the queue
	TxQueueNum() uint64

	// RemoveFromPool removes the transactions from pool by hash
	RemoveFromPool(txs []common.Hash)

	// BackToPool will put the transactions back to pool
	BackToPool(txs []*Transaction)

	// RecoverAndValidateTx recovers the sender of the transaction and also validates the transaction
	RecoverAndValidateTx(tx *Transaction) error

	SaveReceipts(blockHash common.Hash, receipts Receipts) error

	DeleteReceipts(txs []common.Hash) error

	//check transaction hash exist in local
	IsTransactionExisted(hash common.Hash) (exists bool, where int)
}

type TxMessage

type TxMessage interface {
	OpType() int8
	Operator() *common.Address
	OpTarget() *common.Address
	Amount() *big.Int // Operated value
	Payload() []byte  // Data transfer by the message
	GetExtraData() []byte
	GetGasLimit() uint64
	GetHash() common.Hash
	GetValue() uint64
	GetNonce() uint64
	GetGasLimitOriginal() *big.Int
}

TxMessage generated when operate miner stake info

type VMExecutor

type VMExecutor interface {
	Execute(statedb AccountDB, block *Block) (Receipts, *common.Hash, uint64, error)
}

VMExecutor is a VM executor

Jump to

Keyboard shortcuts

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