module

package
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2021 License: Apache-2.0 Imports: 8 Imported by: 5

Documentation

Index

Constants

View Source
const (
	BlockVersion0 = iota
	BlockVersion1
	BlockVersion2
)
View Source
const (
	TransactionVersion2 = 2
	TransactionVersion3 = 3
)
View Source
const (
	FinalizeNormalTransaction = 1 << iota
	FinalizePatchTransaction
	FinalizeResult

	// TODO It's only necessary if storing receipt index is determined by
	// block manager. The current service manager determines by itself according
	// to version, so it doesn't use it.
	FinalizeWriteReceiptIndex
)

Options for finalize

View Source
const (
	ImportByForce = 0x1
)

ImportXXX is used as flag value of BlockManager.Import and BlockManager.ImportBlock.

View Source
const (
	PatchTypeSkipTransaction = "skip_txs"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type APIInfo

type APIInfo interface {
	ToJSON(JSONVersion) (interface{}, error)
}

type Address

type Address interface {
	String() string
	Bytes() []byte
	ID() []byte
	IsContract() bool
	Equal(Address) bool
}

type Block

type Block interface {
	BlockData
	NextValidators() ValidatorList
}

type BlockCandidate

type BlockCandidate interface {
	Block
	Dup() BlockCandidate
	Dispose()
}

type BlockData

type BlockData interface {
	Version() int
	ID() []byte
	Height() int64
	PrevID() []byte
	NextValidatorsHash() []byte
	// voters are subset of previous previous block's next validators
	Votes() CommitVoteSet
	NormalTransactions() TransactionList
	PatchTransactions() TransactionList
	Timestamp() int64
	Proposer() Address // can be nil. e.g. in genesis block.
	LogsBloom() LogsBloom
	Result() []byte

	MarshalHeader(w io.Writer) error
	MarshalBody(w io.Writer) error
	Marshal(w io.Writer) error

	ToJSON(version JSONVersion) (interface{}, error)
	NewBlock(vl ValidatorList) Block
}

type BlockInfo

type BlockInfo interface {
	Height() int64
	Timestamp() int64
}

Block information used by service manager.

type BlockManager

type BlockManager interface {
	GetBlockByHeight(height int64) (Block, error)
	GetLastBlock() (Block, error)
	GetBlock(id []byte) (Block, error)

	// WaitForBlock returns a channel that receives the block with the given
	// height.
	WaitForBlock(height int64) (<-chan Block, error)

	//  NewBlockDataFromReader creates a BlockData from reader. The returned block
	//	shall be imported by ImportBlock before it is Committed or Finalized.
	NewBlockDataFromReader(r io.Reader) (BlockData, error)

	//	Propose proposes a Block following the parent Block.
	//	The result is asynchronously notified by cb. canceler cancels the
	//	operation. canceler returns true and cb is not called if the
	//	cancellation was successful. Proposed block can be Commited or
	// 	Finalized.
	Propose(parentID []byte, votes CommitVoteSet, cb func(BlockCandidate, error)) (canceler Canceler, err error)

	//	Import creates a Block from blockBytes and verifies the block.
	//	The result is asynchronously notified by cb. canceler cancels the
	//	operation. canceler returns true and cb is not called if the
	//	cancellation was successful. Imported block can be Commited or
	//	Finalized.
	Import(r io.Reader, flags int, cb func(BlockCandidate, error)) (canceler Canceler, err error)
	ImportBlock(blk BlockData, flags int, cb func(BlockCandidate, error)) (canceler Canceler, err error)

	Commit(BlockCandidate) error

	//	Finalize updates world state according to BlockCandidate and removes non-finalized committed blocks with the same height as block from persistent storage.
	Finalize(BlockCandidate) error

	GetTransactionInfo(id []byte) (TransactionInfo, error)
	Term()

	// WaitTransaction waits for a transaction with timestamp between
	// bi.Timestamp() - TimestampThreshold and current time +
	// TimestampThreshold. If such a transaction is available now, the function
	// returns false and callback cb is not called.
	WaitForTransaction(parentID []byte, cb func()) bool

	// SendAndWaitTransaction sends a transaction, and get a channel to
	// to wait for the result of it.
	SendTransactionAndWait(txi interface{}) (tid []byte, rc <-chan interface{}, err error)

	// WaitTransactionResult check whether it knows about the transaction
	// and wait for the result.
	WaitTransactionResult(id []byte) (rc <-chan interface{}, err error)

	// ExportBlock exports blocks assuring specified block ranges.
	ExportBlocks(from, to int64, dst db.Database, on func(height int64) error) error

	// ExportGenesis exports genesis to the writer based on the block.
	ExportGenesis(blk Block, writer GenesisStorageWriter) error

	// GetGenesisVotes returns available votes from genesis storage.
	// They are available only when it starts from genesis.
	GetGenesisData() (Block, CommitVoteSet, error)
}

type BroadcastType

type BroadcastType byte
const (
	BROADCAST_ALL BroadcastType = iota
	BROADCAST_NEIGHBOR
	BROADCAST_CHILDREN
)

func (BroadcastType) ForceSend

func (b BroadcastType) ForceSend() bool

func (BroadcastType) TTL

func (b BroadcastType) TTL() byte

type Canceler

type Canceler interface {
	Cancel() bool
}

type Chain

type Chain interface {
	Database() db.Database
	Wallet() Wallet
	NID() int
	CID() int
	NetID() int
	Channel() string
	ConcurrencyLevel() int
	NormalTxPoolSize() int
	PatchTxPoolSize() int
	MaxBlockTxBytes() int
	DefaultWaitTimeout() time.Duration
	MaxWaitTimeout() time.Duration
	TransactionTimeout() time.Duration
	Genesis() []byte
	GenesisStorage() GenesisStorage
	CommitVoteSetDecoder() CommitVoteSetDecoder
	PatchDecoder() PatchDecoder

	BlockManager() BlockManager
	Consensus() Consensus
	ServiceManager() ServiceManager
	NetworkManager() NetworkManager
	Regulator() Regulator

	Init() error
	Start() error
	Stop() error
	Import(src string, height int64) error
	Prune(gs string, dbt string, height int64) error
	Backup(file string, extra []string) error
	RunTask(task string, params json.RawMessage) error
	Term() error
	State() (string, int64, error)
	IsStarted() bool
	IsStopped() bool

	Reset() error
	Verify() error

	MetricContext() context.Context
	Logger() log.Logger
}

type CommitVoteSet

type CommitVoteSet interface {
	Verify(block BlockData, validators ValidatorList) ([]bool, error)
	Bytes() []byte
	Hash() []byte
	Timestamp() int64
}

type CommitVoteSetDecoder

type CommitVoteSetDecoder func([]byte) CommitVoteSet

type Consensus

type Consensus interface {
	Start() error
	Term()
	GetStatus() *ConsensusStatus
	GetVotesByHeight(height int64) (CommitVoteSet, error)
}

type ConsensusInfo added in v0.9.4

type ConsensusInfo interface {
	Proposer() Address
	Voters() ValidatorList
	Voted() []bool
}

type ConsensusStatus

type ConsensusStatus struct {
	Height   int64
	Round    int32
	Proposer bool
}

type EventLog

type EventLog interface {
	Address() Address
	Indexed() [][]byte
	Data() [][]byte
}

type EventLogIterator

type EventLogIterator interface {
	Has() bool
	Next() error
	Get() (EventLog, error)
}

type FeePayment added in v0.9.6

type FeePayment interface {
	Payer() Address
	Amount() *big.Int
}

type FeePaymentIterator added in v0.9.6

type FeePaymentIterator interface {
	Has() bool
	Next() error
	Get() (FeePayment, error)
}

type GenesisStorage

type GenesisStorage interface {
	CID() (int, error)
	NID() (int, error)
	Height() int64
	Type() (GenesisType, error)
	Genesis() []byte
	Get(key []byte) ([]byte, error)
}

type GenesisStorageWriter

type GenesisStorageWriter interface {
	WriteGenesis(gtx []byte) error
	WriteData(value []byte) ([]byte, error)
	Close() error
}

type GenesisType

type GenesisType int
const (
	GenesisUnknown GenesisType = iota
	GenesisNormal
	GenesisPruned
)

type JSONVersion

type JSONVersion int
const (
	JSONVersion2 JSONVersion = iota
	JSONVersion3
	JSONVersion3Raw
	JSONVersionLast = JSONVersion3Raw
)

type LogsBloom

type LogsBloom interface {
	String() string
	Bytes() []byte
	CompressedBytes() []byte
	LogBytes() []byte
	Contain(lb2 LogsBloom) bool
	Merge(lb2 LogsBloom)
	Equal(lb2 LogsBloom) bool
}

type MemberIterator

type MemberIterator interface {
	Has() bool
	Next() error
	Get() (Address, error)
}

type MemberList

type MemberList interface {
	IsEmpty() bool
	Equal(MemberList) bool
	Iterator() MemberIterator
}

type NetworkError

type NetworkError interface {
	error
	Temporary() bool // Is the error temporary?
}

TODO remove interface and implement network.IsTemporaryError(error) bool

type NetworkManager

type NetworkManager interface {
	Start() error
	Term()

	GetPeers() []PeerID

	RegisterReactor(name string, pi ProtocolInfo, reactor Reactor, piList []ProtocolInfo, priority uint8) (ProtocolHandler, error)
	RegisterReactorForStreams(name string, pi ProtocolInfo, reactor Reactor, piList []ProtocolInfo, priority uint8) (ProtocolHandler, error)
	UnregisterReactor(reactor Reactor) error

	SetRole(version int64, role Role, peers ...PeerID)
	GetPeersByRole(role Role) []PeerID
	AddRole(role Role, peers ...PeerID)
	RemoveRole(role Role, peers ...PeerID)
	HasRole(role Role, id PeerID) bool
	Roles(id PeerID) []Role

	SetTrustSeeds(seeds string)
	SetInitialRoles(roles ...Role)
}

type NetworkTransport

type NetworkTransport interface {
	Listen() error
	Close() error
	Dial(address string, channel string) error
	PeerID() PeerID
	Address() string
	SetListenAddress(address string) error
	GetListenAddress() string
	SetSecureSuites(channel string, secureSuites string) error
	GetSecureSuites(channel string) string
	SetSecureAeads(channel string, secureAeads string) error
	GetSecureAeads(channel string) string
}

type Patch

type Patch interface {
	Type() string
	Data() []byte
}

type PatchDecoder

type PatchDecoder func(t string, bs []byte) (Patch, error)

type PeerID

type PeerID interface {
	Bytes() []byte
	Equal(PeerID) bool
	String() string
}

type ProtocolHandler

type ProtocolHandler interface {
	Broadcast(pi ProtocolInfo, b []byte, bt BroadcastType) error
	Multicast(pi ProtocolInfo, b []byte, role Role) error
	Unicast(pi ProtocolInfo, b []byte, id PeerID) error
}

type ProtocolInfo

type ProtocolInfo uint16
const (
	ProtoUnknown ProtocolInfo = iota << 8
	ProtoStateSync
	ProtoTransaction
	ProtoConsensus
	ProtoFastSync
	ProtoConsensusSync
)

func NewProtocolInfo

func NewProtocolInfo(id byte, version byte) ProtocolInfo

func (ProtocolInfo) ID

func (pi ProtocolInfo) ID() byte

func (ProtocolInfo) String

func (pi ProtocolInfo) String() string

func (ProtocolInfo) Uint16

func (pi ProtocolInfo) Uint16() uint16

func (ProtocolInfo) Version

func (pi ProtocolInfo) Version() byte

type Reactor

type Reactor interface {
	//case broadcast and multicast, if return (true,nil) then rebroadcast
	OnReceive(pi ProtocolInfo, b []byte, id PeerID) (bool, error)
	OnFailure(err error, pi ProtocolInfo, b []byte)
	OnJoin(id PeerID)
	OnLeave(id PeerID)
}

type Receipt

type Receipt interface {
	Bytes() []byte
	To() Address
	CumulativeStepUsed() *big.Int
	StepPrice() *big.Int
	StepUsed() *big.Int
	Status() Status
	SCOREAddress() Address
	Check(r Receipt) error
	ToJSON(version JSONVersion) (interface{}, error)
	LogsBloom() LogsBloom
	EventLogIterator() EventLogIterator
	FeePaymentIterator() FeePaymentIterator
	LogsBloomDisabled() bool
	GetProofOfEvent(int) ([][]byte, error)
}

type ReceiptIterator

type ReceiptIterator interface {
	Has() bool
	Next() error
	Get() (Receipt, error)
}

type ReceiptList

type ReceiptList interface {
	Get(int) (Receipt, error)
	GetProof(n int) ([][]byte, error)
	Iterator() ReceiptIterator
	Hash() []byte
	Flush() error
}

type Regulator

type Regulator interface {
	MaxTxCount() int
	OnPropose(now time.Time)
	CommitTimeout() time.Duration
	MinCommitTimeout() time.Duration
	OnTxExecution(count int, ed time.Duration, fd time.Duration)
	SetBlockInterval(i time.Duration, d time.Duration)
}

type Revision added in v0.9.1

type Revision int64
const (
	InputCostingWithJSON Revision = 1 << (8 + iota)
	ExpandErrorCode
	UseChainID
	UseMPTOnEvents
	UseCompactAPIInfo
	AutoAcceptGovernance
	ResetStepOnFailure
	LegacyFallbackCheck
	LegacyContentCount
	LegacyBalanceCheck
	LegacyInputJSON
	LegacyNoTimeout
	LastRevisionBit
)

func (Revision) AutoAcceptGovernance added in v0.9.6

func (r Revision) AutoAcceptGovernance() bool

func (Revision) ExpandErrorCode added in v0.9.1

func (r Revision) ExpandErrorCode() bool

func (Revision) Has added in v0.9.6

func (r Revision) Has(flag Revision) bool

func (Revision) InputCostingWithJSON added in v0.9.1

func (r Revision) InputCostingWithJSON() bool

func (Revision) LegacyBalanceCheck added in v0.9.6

func (r Revision) LegacyBalanceCheck() bool

func (Revision) LegacyContentCount added in v0.9.6

func (r Revision) LegacyContentCount() bool

func (Revision) LegacyFallbackCheck added in v0.9.6

func (r Revision) LegacyFallbackCheck() bool

func (Revision) ResetStepOnFailure added in v0.9.6

func (r Revision) ResetStepOnFailure() bool

func (Revision) UseChainID added in v0.9.1

func (r Revision) UseChainID() bool

func (Revision) UseCompactAPIInfo added in v0.9.1

func (r Revision) UseCompactAPIInfo() bool

func (Revision) UseMPTOnEvents added in v0.9.1

func (r Revision) UseMPTOnEvents() bool

func (Revision) Value added in v0.9.1

func (r Revision) Value() int

type Role

type Role string
const (
	ROLE_VALIDATOR Role = "validator"
	ROLE_SEED      Role = "seed"
	ROLE_NORMAL    Role = "normal"
)

type ServiceManager

type ServiceManager interface {
	TransitionManager

	// Start starts service module.
	Start()
	// Term terminates serviceManager instance.
	Term()

	// TransactionFromBytes returns a Transaction instance from bytes.
	TransactionFromBytes(b []byte, blockVersion int) (Transaction, error)

	// GenesisTransactionFromBytes returns a Genesis Transaction instance from bytes.
	GenesisTransactionFromBytes(b []byte, blockVersion int) (Transaction, error)

	// TransactionListFromHash returns a TransactionList instance from
	// the hash of transactions or nil when no transactions exist.
	// It assumes it's called only by new version block, so it doesn't receive
	// version value.
	TransactionListFromHash(hash []byte) TransactionList

	// TransactionListFromSlice returns list of transactions.
	TransactionListFromSlice(txs []Transaction, version int) TransactionList

	// ReceiptListFromResult returns list of receipts from result.
	ReceiptListFromResult(result []byte, g TransactionGroup) (ReceiptList, error)

	// SendTransaction adds transaction to a transaction pool.
	SendTransaction(tx interface{}) ([]byte, error)

	// SendPatch sends a patch
	SendPatch(patch Patch) error

	// Call handles read-only contract API call.
	Call(result []byte, vl ValidatorList, js []byte, bi BlockInfo) (interface{}, error)

	// ValidatorListFromHash returns ValidatorList from hash.
	ValidatorListFromHash(hash []byte) ValidatorList

	// GetBalance returns balance of the account
	GetBalance(result []byte, addr Address) (*big.Int, error)

	// GetTotalSupply returns total supplied coin
	GetTotalSupply(result []byte) (*big.Int, error)

	// GetNetworkID returns network ID of the state
	GetNetworkID(result []byte) (int64, error)

	// GetChainID returns chain ID of the state
	GetChainID(result []byte) (int64, error)

	// GetAPIInfo returns API info of the contract
	GetAPIInfo(result []byte, addr Address) (APIInfo, error)

	// GetMembers returns network member list
	GetMembers(result []byte) (MemberList, error)

	// GetRoundLimit returns round limit
	GetRoundLimit(result []byte, vl int) int64

	// GetMinimizeEmptyBlock returns minimize empty block generation flag
	GetMinimizeBlockGen(result []byte) bool

	// HasTransaction returns whether it has specified transaction in the pool
	HasTransaction(id []byte) bool

	// SendTransactionAndWait send transaction and return channel for result
	SendTransactionAndWait(tx interface{}) ([]byte, <-chan interface{}, error)

	// WaitTransactionResult return channel for result.
	WaitTransactionResult(id []byte) (<-chan interface{}, error)

	// ExportResult exports all related entries related with the result
	// should be exported to the database
	ExportResult(result []byte, vh []byte, dst db.Database) error

	// ImportResult imports all related entries related with the result
	// should be imported from the database
	ImportResult(result []byte, vh []byte, src db.Database) error

	// ExecuteTransaction executes the transaction on the specified state.
	// Then it returns the expected result of the transaction.
	// It ignores supplied step limit.
	ExecuteTransaction(result []byte, vh []byte, js []byte, bi BlockInfo) (Receipt, error)
}

type SkipTransactionPatch

type SkipTransactionPatch interface {
	Patch
	Height() int64 // height of the block to skip execution of

	// Verify check internal data is correct
	Verify(vl ValidatorList, roundLimit int64, nid int) error
}

type Status

type Status int
const (
	StatusSuccess Status = iota
	StatusUnknownFailure
	StatusContractNotFound
	StatusMethodNotFound
	StatusMethodNotPayable
	StatusIllegalFormat
	StatusInvalidParameter
	StatusInvalidInstance
	StatusInvalidContainerAccess
	StatusAccessDenied
	StatusOutOfStep
	StatusOutOfBalance
	StatusTimeout
	StatusStackOverflow
	StatusSkipTransaction
	StatusInvalidPackage
	StatusReverted Status = 32

	StatusLimitRev5 Status = 99
	StatusLimit     Status = 999
)

func (Status) String

func (s Status) String() string

type Timestamper

type Timestamper interface {
	GetVoteTimestamp(h, ts int64) int64
	GetBlockTimestamp(h, ts int64) int64
}

type TraceCallback

type TraceCallback interface {
	OnLog(level TraceLevel, msg string)
	OnEnd(e error)
}

type TraceInfo

type TraceInfo struct {
	Group    TransactionGroup
	Index    int
	Callback TraceCallback
}

type TraceLevel

type TraceLevel int
const (
	TDebugLevel TraceLevel = iota
	TTraceLevel
	TSystemLevel
)

type Transaction

type Transaction interface {
	Group() TransactionGroup
	ID() []byte
	From() Address
	Bytes() []byte
	Hash() []byte
	Verify() error
	Version() int
	ToJSON(version JSONVersion) (interface{}, error)
	ValidateNetwork(nid int) bool
}

type TransactionGroup

type TransactionGroup int
const (
	TransactionGroupPatch TransactionGroup = iota
	TransactionGroupNormal
)

type TransactionInfo

type TransactionInfo interface {
	Block() Block
	Index() int
	Group() TransactionGroup
	Transaction() Transaction
	GetReceipt() (Receipt, error)
}

type TransactionIterator

type TransactionIterator interface {
	Has() bool
	Next() error
	Get() (Transaction, int, error)
}

type TransactionList

type TransactionList interface {
	Get(int) (Transaction, error)
	Iterator() TransactionIterator

	// length if Hash() is 0 iff empty
	Hash() []byte

	Equal(TransactionList) bool
	Flush() error
}

type Transition

type Transition interface {
	PatchTransactions() TransactionList
	NormalTransactions() TransactionList

	PatchReceipts() ReceiptList
	NormalReceipts() ReceiptList
	// Execute executes this transition.
	// The result is asynchronously notified by cb. canceler can be used
	// to cancel it after calling Execute. After canceler returns true,
	// all succeeding cb functions may not be called back.
	// REMARK: It is assumed to be called once. Any additional call returns
	// error.
	Execute(cb TransitionCallback) (canceler func() bool, err error)

	// ExecuteForTrace executes this transition until it executes the transaction
	// at offset `n` of normal transactions. If it fails, then OnValidate or
	// OnExecute will be called with an error.
	ExecuteForTrace(ti TraceInfo) (canceler func() bool, err error)

	// Result returns service manager defined result bytes.
	// For example, it can be "[world_state_hash][patch_tx_hash][normal_tx_hash]".
	Result() []byte

	// NextValidators returns the addresses of validators as a result of
	// transaction processing.
	// It may return nil before cb.OnExecute is called back by Execute.
	NextValidators() ValidatorList

	// LogsBloom returns log bloom filter for this transition.
	// It may return nil before cb.OnExecute is called back by Execute.
	LogsBloom() LogsBloom

	// BlockInfo returns block information for the normal transaction.
	BlockInfo() BlockInfo

	// Equal check equality of inputs of transition.
	Equal(Transition) bool
}

type TransitionCallback

type TransitionCallback interface {
	// Called if validation is done.
	OnValidate(Transition, error)

	// Called if execution is done.
	OnExecute(Transition, error)
}

TransitionCallback provides transition change notifications. All functions are called back with the same Transition instance for the convenience.

type TransitionManager

type TransitionManager interface {
	// ProposeTransition proposes a Transition following the parent Transition.
	// Returned Transition always passes validation.
	ProposeTransition(parent Transition, bi BlockInfo, csi ConsensusInfo) (Transition, error)
	// CreateInitialTransition creates an initial Transition.
	CreateInitialTransition(result []byte, nextValidators ValidatorList) (Transition, error)
	// CreateTransition creates a Transition following parent Transition.
	CreateTransition(parent Transition, txs TransactionList, bi BlockInfo, csi ConsensusInfo) (Transition, error)
	// GetPatches returns all patch transactions based on the parent transition.
	// bi is the block info of the block that will contain the patches
	GetPatches(parent Transition, bi BlockInfo) TransactionList
	// PatchTransition creates a Transition by overwriting patches on the transition.
	// bi is the block info of the block that contains the patches,
	// or nil if the patches are already prevalidated.
	PatchTransition(transition Transition, patches TransactionList, bi BlockInfo) Transition
	CreateSyncTransition(transition Transition, result []byte, vlHash []byte) Transition
	// Finalize finalizes data related to the transition. It usually stores
	// data to a persistent storage. opt indicates which data are finalized.
	// It should be called for every transition.
	Finalize(transition Transition, opt int) error
	// WaitTransaction waits for a transaction with timestamp between
	// bi.Timestamp() - TimestampThreshold and current time +
	// TimestampThreshold. If such a transaction is available now, the function
	// returns false and callback cb is not called.
	WaitForTransaction(parent Transition, bi BlockInfo, cb func()) bool
}

TransitionManager provides Transition APIs. For a block proposal, it is usually called as follows:

  1. GetPatches
  2. if any changes of patches exist from GetPatches 2.1 PatchTransaction 2.2 Transition.Execute
  3. ProposeTransition
  4. Transition.Execute

For a block validation,

  1. if any changes of patches are detected from a new block 1.1 PatchTransition 1.2 Transition.Execute
  2. create Transaction instances by TransactionFromBytes
  3. CreateTransition with TransactionList
  4. Transition.Execute

type Validator

type Validator interface {
	Address() Address

	// PublicKey returns public key of the validator.
	// If it doesn't have, then it return nil
	PublicKey() []byte

	Bytes() []byte
}

type ValidatorList

type ValidatorList interface {
	Hash() []byte
	Bytes() []byte
	Flush() error
	IndexOf(Address) int
	Len() int
	Get(i int) (Validator, bool)
}

type Wallet

type Wallet interface {
	Address() Address
	Sign(data []byte) ([]byte, error)
	PublicKey() []byte
}

Jump to

Keyboard shortcuts

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