cn

package
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2021 License: GPL-3.0 Imports: 58 Imported by: 12

Documentation

Overview

Package cn implements components related to network management and message handling. CN implements the Klaytn consensus node service. ProtocolManager handles the messages from the peer nodes and manages its peers. Peer is the interface used for peer nodes and has two different kinds of implementation depending on single or multi channel usage.

Source Files

  • api.go : provides private debug API related to block and state
  • api_backend.go : implements CNAPIBackend which is a wrapper of CN to serve API requests
  • api_tracer.go : provides private debug API related to trace chain, block and state
  • backend.go : implements CN struct used for the Klaytn consensus node service
  • bloombits.go : implements BloomIndexer, an indexer built with bloom bits for fast filtering
  • channel_manager.go : implements ChannelManager struct, which is used to manage channel for each message
  • config.go : defines the configuration used by CN struct
  • gen_config.go : is automatically generated from config.go
  • handler.go : implements ProtocolManager which handles the message and manages network peers
  • metrics.go : includes statistics used in cn package
  • peer.go : provides the interface and implementation of Peer interface
  • peer_set.go : provides the interface and implementation of PeerSet interface
  • protocol.go : defines the protocol version of Klaytn network and includes errors in cn package
  • sync.go : includes syncing features of ProtocolManager

Index

Constants

View Source
const (
	BlockChannel uint = iota
	TxChannel
	ConsensusChannel
	MiscChannel
	MaxChannel
)
View Source
const (

	// DefaultMaxResendTxCount is the number of resending transactions to peer in order to prevent the txs from missing.
	DefaultMaxResendTxCount = 1000

	// DefaultTxResendInterval is the second of resending transactions period.
	DefaultTxResendInterval = 4
)
View Source
const (
	// Protocol messages belonging to klay/62
	StatusMsg                   = 0x00
	NewBlockHashesMsg           = 0x01
	BlockHeaderFetchRequestMsg  = 0x02
	BlockHeaderFetchResponseMsg = 0x03
	BlockBodiesFetchRequestMsg  = 0x04
	BlockBodiesFetchResponseMsg = 0x05
	TxMsg                       = 0x06
	BlockHeadersRequestMsg      = 0x07
	BlockHeadersMsg             = 0x08
	BlockBodiesRequestMsg       = 0x09
	BlockBodiesMsg              = 0x0a
	NewBlockMsg                 = 0x0b

	// Protocol messages belonging to klay/63
	NodeDataRequestMsg = 0x0c
	NodeDataMsg        = 0x0d
	ReceiptsRequestMsg = 0x0e
	ReceiptsMsg        = 0x0f

	MsgCodeEnd = 0x10
)

Klaytn protocol message codes TODO-Klaytn-Issue751 Protocol message should be refactored. Present code is not used.

View Source
const (
	ErrMsgTooLarge = iota
	ErrDecode
	ErrInvalidMsgCode
	ErrProtocolVersionMismatch
	ErrNetworkIdMismatch
	ErrGenesisBlockMismatch
	ErrChainIDMismatch
	ErrNoStatusMsg
	ErrExtraStatusMsg
	ErrSuspendedPeer
	ErrUnexpectedTxType
	ErrFailedToGetStateDB
)
View Source
const ProtocolMaxMsgSize = 10 * 1024 * 1024 // Maximum cap on the size of a protocol message

Variables

View Source
var ChannelOfMessage = map[uint64]int{
	StatusMsg:                   p2p.ConnDefault,
	NewBlockHashesMsg:           p2p.ConnDefault,
	BlockHeaderFetchRequestMsg:  p2p.ConnDefault,
	BlockHeaderFetchResponseMsg: p2p.ConnDefault,
	BlockBodiesFetchRequestMsg:  p2p.ConnDefault,
	BlockBodiesFetchResponseMsg: p2p.ConnDefault,
	TxMsg:                       p2p.ConnTxMsg,
	BlockHeadersRequestMsg:      p2p.ConnDefault,
	BlockHeadersMsg:             p2p.ConnDefault,
	BlockBodiesRequestMsg:       p2p.ConnDefault,
	BlockBodiesMsg:              p2p.ConnDefault,
	NewBlockMsg:                 p2p.ConnDefault,

	NodeDataRequestMsg: p2p.ConnDefault,
	NodeDataMsg:        p2p.ConnDefault,
	ReceiptsRequestMsg: p2p.ConnDefault,
	ReceiptsMsg:        p2p.ConnDefault,
}

ChannelOfMessage is a map with the index of the channel per message

View Source
var ConcurrentOfChannel = []int{
	p2p.ConnDefault: 1,
	p2p.ConnTxMsg:   3,
}
View Source
var ProtocolLengths = []uint64{17, 8}

ProtocolLengths are the number of implemented message corresponding to different protocol versions.

View Source
var ProtocolName = "klay"

ProtocolName is the official short name of the protocol used during capability negotiation.

View Source
var ProtocolVersions = []uint{klay63, klay62}

ProtocolVersions are the upported versions of the klay protocol (first is primary).

Functions

func CreateConsensusEngine

func CreateConsensusEngine(ctx *node.ServiceContext, config *Config, chainConfig *params.ChainConfig, db database.DBManager, gov *governance.Governance, nodetype common.ConnType) consensus.Engine

CreateConsensusEngine creates the required type of consensus engine instance for a Klaytn service

func CreateDB

func CreateDB(ctx *node.ServiceContext, config *Config, name string) database.DBManager

CreateDB creates the chain database.

func NewBloomIndexer

func NewBloomIndexer(db database.DBManager, size uint64) *blockchain.ChainIndexer

NewBloomIndexer returns a chain indexer that generates bloom bits data for the canonical chain for fast logs filtering.

Types

type BackendProtocolManager added in v1.3.0

type BackendProtocolManager interface {
	Downloader() ProtocolManagerDownloader
	SetWsEndPoint(wsep string)
	GetSubProtocols() []p2p.Protocol
	ProtocolVersion() int
	ReBroadcastTxs(transactions types.Transactions)
	SetAcceptTxs()
	SetRewardbase(addr common.Address)
	SetRewardbaseWallet(wallet accounts.Wallet)
	NodeType() common.ConnType
	Start(maxPeers int)
	Stop()
}

BackendProtocolManager is an interface of cn.ProtocolManager used from cn.CN and cn.ServiceChain.

type BloomIndexer

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

BloomIndexer implements a blockchain.ChainIndexer, building up a rotated bloom bits index for the Klaytn header bloom filters, permitting blazing fast filtering.

func (*BloomIndexer) Commit

func (b *BloomIndexer) Commit() error

Commit implements blockchain.ChainIndexerBackend, finalizing the bloom section and writing it out into the database.

func (*BloomIndexer) Process

func (b *BloomIndexer) Process(header *types.Header)

Process implements blockchain.ChainIndexerBackend, adding a new header's bloom into the index.

func (*BloomIndexer) Reset

func (b *BloomIndexer) Reset(section uint64, lastSectionHead common.Hash) error

Reset implements blockchain.ChainIndexerBackend, starting a new bloombits index section.

type ByPassValidator

type ByPassValidator struct{}

func (ByPassValidator) ValidatePeerType

func (v ByPassValidator) ValidatePeerType(addr common.Address) error

type CN

type CN struct {
	APIBackend *CNAPIBackend
	// contains filtered or unexported fields
}

CN implements the Klaytn consensus node service.

func New

func New(ctx *node.ServiceContext, config *Config) (*CN, error)

New creates a new CN object (including the initialisation of the common CN object)

func (*CN) APIs

func (s *CN) APIs() []rpc.API

APIs returns the collection of RPC services the ethereum package offers. NOTE, some of these services probably need to be moved to somewhere else.

func (*CN) AccountManager

func (s *CN) AccountManager() accounts.AccountManager

func (*CN) AddLesServer

func (s *CN) AddLesServer(ls LesServer)

func (*CN) BlockChain

func (s *CN) BlockChain() work.BlockChain

func (*CN) ChainDB

func (s *CN) ChainDB() database.DBManager

func (*CN) Components

func (s *CN) Components() []interface{}

func (*CN) Engine

func (s *CN) Engine() consensus.Engine

func (*CN) EventMux

func (s *CN) EventMux() *event.TypeMux

func (*CN) IsListening

func (s *CN) IsListening() bool

func (*CN) IsMining

func (s *CN) IsMining() bool

func (*CN) Miner

func (s *CN) Miner() Miner

func (*CN) NetVersion

func (s *CN) NetVersion() uint64

func (*CN) Progress added in v1.1.0

func (s *CN) Progress() klaytn.SyncProgress

func (*CN) ProtocolVersion

func (s *CN) ProtocolVersion() int

func (*CN) Protocols

func (s *CN) Protocols() []p2p.Protocol

Protocols implements node.Service, returning all the currently configured network protocols to start.

func (*CN) ReBroadcastTxs

func (s *CN) ReBroadcastTxs(transactions types.Transactions)

func (*CN) ResetWithGenesisBlock

func (s *CN) ResetWithGenesisBlock(gb *types.Block)

func (*CN) Rewardbase

func (s *CN) Rewardbase() (eb common.Address, err error)

func (*CN) RewardbaseWallet

func (s *CN) RewardbaseWallet() (accounts.Wallet, error)

func (*CN) SetComponents

func (s *CN) SetComponents(component []interface{})

func (*CN) SetRewardbase

func (s *CN) SetRewardbase(rewardbase common.Address)

func (*CN) Start

func (s *CN) Start(srvr p2p.Server) error

Start implements node.Service, starting all internal goroutines needed by the Klaytn protocol implementation.

func (*CN) StartMining

func (s *CN) StartMining(local bool) error

func (*CN) Stop

func (s *CN) Stop() error

Stop implements node.Service, terminating all internal goroutines used by the Klaytn protocol.

func (*CN) StopMining

func (s *CN) StopMining()

func (*CN) TxPool

func (s *CN) TxPool() work.TxPool

type CNAPIBackend

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

CNAPIBackend implements api.Backend for full nodes

func (*CNAPIBackend) AccountManager

func (b *CNAPIBackend) AccountManager() accounts.AccountManager

func (*CNAPIBackend) BlockByNumber

func (b *CNAPIBackend) BlockByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Block, error)

func (*CNAPIBackend) BloomStatus

func (b *CNAPIBackend) BloomStatus() (uint64, uint64)

func (*CNAPIBackend) ChainConfig

func (b *CNAPIBackend) ChainConfig() *params.ChainConfig

func (*CNAPIBackend) ChainDB

func (b *CNAPIBackend) ChainDB() database.DBManager

func (*CNAPIBackend) CurrentBlock

func (b *CNAPIBackend) CurrentBlock() *types.Block

func (*CNAPIBackend) EventMux

func (b *CNAPIBackend) EventMux() *event.TypeMux

func (*CNAPIBackend) GetBlock

func (b *CNAPIBackend) GetBlock(ctx context.Context, hash common.Hash) (*types.Block, error)

func (*CNAPIBackend) GetBlockReceipts

func (b *CNAPIBackend) GetBlockReceipts(ctx context.Context, hash common.Hash) types.Receipts

GetBlockReceipts retrieves the receipts for all transactions with given block hash.

func (*CNAPIBackend) GetBlockReceiptsInCache

func (b *CNAPIBackend) GetBlockReceiptsInCache(blockHash common.Hash) types.Receipts

GetBlockReceiptsInCache retrieves receipts for a given block hash in cache.

func (*CNAPIBackend) GetEVM

func (b *CNAPIBackend) GetEVM(ctx context.Context, msg blockchain.Message, state *state.StateDB, header *types.Header, vmCfg vm.Config) (*vm.EVM, func() error, error)

func (*CNAPIBackend) GetLogs

func (b *CNAPIBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error)

func (*CNAPIBackend) GetPoolNonce

func (b *CNAPIBackend) GetPoolNonce(ctx context.Context, addr common.Address) uint64

func (*CNAPIBackend) GetPoolTransaction

func (b *CNAPIBackend) GetPoolTransaction(hash common.Hash) *types.Transaction

func (*CNAPIBackend) GetPoolTransactions

func (b *CNAPIBackend) GetPoolTransactions() (types.Transactions, error)

func (*CNAPIBackend) GetTd

func (b *CNAPIBackend) GetTd(blockHash common.Hash) *big.Int

func (*CNAPIBackend) GetTxAndLookupInfo

func (b *CNAPIBackend) GetTxAndLookupInfo(hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64)

GetTxAndLookupInfo retrieves a tx and lookup info for a given transaction hash.

func (*CNAPIBackend) GetTxAndLookupInfoInCache

func (b *CNAPIBackend) GetTxAndLookupInfoInCache(txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64)

GetTxAndLookupInfoInCache retrieves a tx and lookup info for a given transaction hash in cache.

func (*CNAPIBackend) GetTxLookupInfoAndReceipt

func (b *CNAPIBackend) GetTxLookupInfoAndReceipt(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, *types.Receipt)

GetTxLookupInfoAndReceipt retrieves a tx and lookup info and receipt for a given transaction hash.

func (*CNAPIBackend) GetTxLookupInfoAndReceiptInCache

func (b *CNAPIBackend) GetTxLookupInfoAndReceiptInCache(txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, *types.Receipt)

GetTxLookupInfoAndReceiptInCache retrieves a tx and lookup info and receipt for a given transaction hash in cache.

func (*CNAPIBackend) HeaderByNumber

func (b *CNAPIBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error)

func (*CNAPIBackend) IsParallelDBWrite

func (b *CNAPIBackend) IsParallelDBWrite() bool

func (*CNAPIBackend) IsSenderTxHashIndexingEnabled

func (b *CNAPIBackend) IsSenderTxHashIndexingEnabled() bool

func (*CNAPIBackend) Progress added in v1.1.0

func (b *CNAPIBackend) Progress() klaytn.SyncProgress

func (*CNAPIBackend) ProtocolVersion

func (b *CNAPIBackend) ProtocolVersion() int

func (*CNAPIBackend) RPCGasCap added in v1.6.0

func (b *CNAPIBackend) RPCGasCap() *big.Int

func (*CNAPIBackend) SendTx

func (b *CNAPIBackend) SendTx(ctx context.Context, signedTx *types.Transaction) error

func (*CNAPIBackend) ServiceFilter

func (b *CNAPIBackend) ServiceFilter(ctx context.Context, session *bloombits.MatcherSession)

func (*CNAPIBackend) SetHead

func (b *CNAPIBackend) SetHead(number uint64)

func (*CNAPIBackend) StateAndHeaderByNumber

func (b *CNAPIBackend) StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*state.StateDB, *types.Header, error)

func (*CNAPIBackend) Stats

func (b *CNAPIBackend) Stats() (pending int, queued int)

func (*CNAPIBackend) SubscribeChainEvent

func (b *CNAPIBackend) SubscribeChainEvent(ch chan<- blockchain.ChainEvent) event.Subscription

func (*CNAPIBackend) SubscribeChainHeadEvent

func (b *CNAPIBackend) SubscribeChainHeadEvent(ch chan<- blockchain.ChainHeadEvent) event.Subscription

func (*CNAPIBackend) SubscribeChainSideEvent

func (b *CNAPIBackend) SubscribeChainSideEvent(ch chan<- blockchain.ChainSideEvent) event.Subscription

func (*CNAPIBackend) SubscribeLogsEvent

func (b *CNAPIBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription

func (*CNAPIBackend) SubscribeNewTxsEvent

func (b *CNAPIBackend) SubscribeNewTxsEvent(ch chan<- blockchain.NewTxsEvent) event.Subscription

func (*CNAPIBackend) SubscribeRemovedLogsEvent

func (b *CNAPIBackend) SubscribeRemovedLogsEvent(ch chan<- blockchain.RemovedLogsEvent) event.Subscription

func (*CNAPIBackend) SuggestPrice

func (b *CNAPIBackend) SuggestPrice(ctx context.Context) (*big.Int, error)

func (*CNAPIBackend) TxPoolContent

type ChannelManager

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

func NewChannelManager

func NewChannelManager(channelSize int) *ChannelManager

NewChannelManager returns a new ChannelManager. The ChannelManager manages the channel for the msg code.

func (*ChannelManager) GetChannelWithMsgCode

func (cm *ChannelManager) GetChannelWithMsgCode(idx int, msgCode uint64) (chan p2p.Msg, error)

GetChannelWithMsgCode returns the channel corresponding to msgCode.

func (*ChannelManager) RegisterChannelWithIndex

func (cm *ChannelManager) RegisterChannelWithIndex(idx int, channelId uint, channel chan p2p.Msg)

RegisterChannelWithIndex registers the channel corresponding to network and channel ID.

func (*ChannelManager) RegisterMsgCode

func (cm *ChannelManager) RegisterMsgCode(channelId uint, msgCode uint64)

RegisterMsgCode registers the channel id corresponding to msgCode.

type Config

type Config struct {
	// The genesis block, which is inserted if the database is empty.
	// If nil, the Klaytn main net block is used.
	Genesis *blockchain.Genesis `toml:",omitempty"`

	// Protocol options
	NetworkId     uint64 // Network ID to use for selecting peers to connect to
	SyncMode      downloader.SyncMode
	NoPruning     bool
	WorkerDisable bool // disables worker and does not start istanbul

	// KES options
	DownloaderDisable bool
	FetcherDisable    bool

	// Service chain options
	ParentOperatorAddr *common.Address `toml:",omitempty"` // A hex account address in the parent chain used to sign a child chain transaction.
	AnchoringPeriod    uint64          // Period when child chain sends an anchoring transaction to the parent chain. Default value is 1.
	SentChainTxsLimit  uint64          // Number of chain transactions stored for resending. Default value is 1000.

	OverwriteGenesis bool
	StartBlockNumber uint64

	// Database options
	DBType               database.DBType
	SkipBcVersionCheck   bool `toml:"-"`
	SingleDB             bool
	NumStateTrieShards   uint
	EnableDBPerfMetrics  bool
	LevelDBCompression   database.LevelDBCompressionType
	LevelDBBufferPool    bool
	LevelDBCacheSize     int
	DynamoDBConfig       database.DynamoDBConfig
	TrieCacheSize        int
	TrieTimeout          time.Duration
	TrieBlockInterval    uint
	TriesInMemory        uint64
	SenderTxHashIndexing bool
	ParallelDBWrite      bool
	TrieNodeCacheConfig  statedb.TrieNodeCacheConfig

	// Mining-related options
	ServiceChainSigner common.Address `toml:",omitempty"`
	ExtraData          []byte         `toml:",omitempty"`
	GasPrice           *big.Int

	// Reward
	Rewardbase common.Address `toml:",omitempty"`

	// Transaction pool options
	TxPool blockchain.TxPoolConfig

	// Gas Price Oracle options
	GPO gasprice.Config

	// Enables tracking of SHA3 preimages in the VM
	EnablePreimageRecording bool
	// Enables collecting internal transaction data during processing a block
	EnableInternalTxTracing bool
	// Istanbul options
	Istanbul istanbul.Config

	// Miscellaneous options
	DocRoot string `toml:"-"`

	WsEndpoint string `toml:",omitempty"`

	// Tx Resending options
	TxResendInterval  uint64
	TxResendCount     int
	TxResendUseLegacy bool

	// Service Chain
	NoAccountCreation bool

	// use separate network different from baobab or cypress
	IsPrivate bool

	// Restart
	AutoRestartFlag    bool
	RestartTimeOutFlag time.Duration
	DaemonPathFlag     string

	// RPCGasCap is the global gas cap for eth-call variants.
	RPCGasCap *big.Int `toml:",omitempty"`
}

func GetDefaultConfig added in v1.5.0

func GetDefaultConfig() *Config

GetDefaultConfig returns default settings for use on the Klaytn main net.

func (Config) MarshalTOML

func (c Config) MarshalTOML() (interface{}, error)

MarshalTOML marshals as TOML.

func (*Config) UnmarshalTOML

func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error

UnmarshalTOML unmarshals from TOML.

type DumpStateTrieResult added in v1.5.0

type DumpStateTrieResult struct {
	Root  string `json:"root"`
	Tries []Trie `json:"tries"`
}

type LesServer

type LesServer interface {
	Start(srvr p2p.Server)
	Stop()
	Protocols() []p2p.Protocol
	SetBloomBitsIndexer(bbIndexer *blockchain.ChainIndexer)
}

type Miner added in v1.3.0

type Miner interface {
	Start()
	Stop()
	Register(agent work.Agent)
	Mining() bool
	HashRate() (tot int64)
	SetExtra(extra []byte) error
	Pending() (*types.Block, *state.StateDB)
	PendingBlock() *types.Block
}

Miner is an interface of work.Miner used by ServiceChain.

type NodeInfo

type NodeInfo struct {
	// TODO-Klaytn describe predefined network ID below
	Network    uint64              `json:"network"`    // Klaytn network ID
	BlockScore *big.Int            `json:"blockscore"` // Total blockscore of the host's blockchain
	Genesis    common.Hash         `json:"genesis"`    // SHA3 hash of the host's genesis block
	Config     *params.ChainConfig `json:"config"`     // Chain configuration for the fork rules
	Head       common.Hash         `json:"head"`       // SHA3 hash of the host's best owned block
}

NodeInfo represents a short summary of the Klaytn sub-protocol metadata known about the host peer.

type Peer

type Peer interface {
	// Broadcast is a write loop that multiplexes block propagations, announcements
	// and transaction broadcasts into the remote peer. The goal is to have an async
	// writer that does not lock up node internals.
	Broadcast()

	// Close signals the broadcast goroutine to terminate.
	Close()

	// Info gathers and returns a collection of metadata known about a peer.
	Info() *PeerInfo

	// SetHead updates the head hash and total blockscore of the peer.
	SetHead(hash common.Hash, td *big.Int)

	// AddToKnownBlocks adds a block hash to knownBlocksCache for the peer, ensuring that the block will
	// never be propagated to this particular peer.
	AddToKnownBlocks(hash common.Hash)

	// AddToKnownTxs adds a transaction hash to knownTxsCache for the peer, ensuring that it
	// will never be propagated to this particular peer.
	AddToKnownTxs(hash common.Hash)

	// Send writes an RLP-encoded message with the given code.
	// data should have been encoded as an RLP list.
	Send(msgcode uint64, data interface{}) error

	// SendTransactions sends transactions to the peer and includes the hashes
	// in its transaction hash set for future reference.
	SendTransactions(txs types.Transactions) error

	// ReSendTransactions sends txs to a peer in order to prevent the txs from missing.
	ReSendTransactions(txs types.Transactions) error

	// AsyncSendTransactions sends transactions asynchronously to the peer.
	AsyncSendTransactions(txs types.Transactions)

	// SendNewBlockHashes announces the availability of a number of blocks through
	// a hash notification.
	SendNewBlockHashes(hashes []common.Hash, numbers []uint64) error

	// AsyncSendNewBlockHash queues the availability of a block for propagation to a
	// remote peer. If the peer's broadcast queue is full, the event is silently
	// dropped.
	AsyncSendNewBlockHash(block *types.Block)

	// SendNewBlock propagates an entire block to a remote peer.
	SendNewBlock(block *types.Block, td *big.Int) error

	// AsyncSendNewBlock queues an entire block for propagation to a remote peer. If
	// the peer's broadcast queue is full, the event is silently dropped.
	AsyncSendNewBlock(block *types.Block, td *big.Int)

	// SendBlockHeaders sends a batch of block headers to the remote peer.
	SendBlockHeaders(headers []*types.Header) error

	// SendFetchedBlockHeader sends a block header to the remote peer, requested by fetcher.
	SendFetchedBlockHeader(header *types.Header) error

	// SendBlockBodies sends a batch of block contents to the remote peer.
	SendBlockBodies(bodies []*blockBody) error

	// SendBlockBodiesRLP sends a batch of block contents to the remote peer from
	// an already RLP encoded format.
	SendBlockBodiesRLP(bodies []rlp.RawValue) error

	// SendFetchedBlockBodiesRLP sends a batch of block contents to the remote peer from
	// an already RLP encoded format, requested by fetcher.
	SendFetchedBlockBodiesRLP(bodies []rlp.RawValue) error

	// SendNodeDataRLP sends a batch of arbitrary internal data, corresponding to the
	// hashes requested.
	SendNodeData(data [][]byte) error

	// SendReceiptsRLP sends a batch of transaction receipts, corresponding to the
	// ones requested from an already RLP encoded format.
	SendReceiptsRLP(receipts []rlp.RawValue) error

	// FetchBlockHeader is a wrapper around the header query functions to fetch a
	// single header. It is used solely by the fetcher.
	FetchBlockHeader(hash common.Hash) error

	// FetchBlockBodies fetches a batch of blocks' bodies corresponding to the hashes
	// specified. If uses different message type from RequestBodies.
	// It is used solely by the fetcher.
	FetchBlockBodies(hashes []common.Hash) error

	// Handshake executes the Klaytn protocol handshake, negotiating version number,
	// network IDs, difficulties, head, and genesis blocks and returning error.
	Handshake(network uint64, chainID, td *big.Int, head common.Hash, genesis common.Hash) error

	// ConnType returns the conntype of the peer.
	ConnType() common.ConnType

	// GetID returns the id of the peer.
	GetID() string

	// GetP2PPeerID returns the id of the p2p.Peer.
	GetP2PPeerID() discover.NodeID

	// GetChainID returns the chain id of the peer.
	GetChainID() *big.Int

	// GetAddr returns the address of the peer.
	GetAddr() common.Address

	// SetAddr sets the address of the peer.
	SetAddr(addr common.Address)

	// GetVersion returns the version of the peer.
	GetVersion() int

	// KnowsBlock returns if the peer is known to have the block, based on knownBlocksCache.
	KnowsBlock(hash common.Hash) bool

	// KnowsTx returns if the peer is known to have the transaction, based on knownTxsCache.
	KnowsTx(hash common.Hash) bool

	// GetP2PPeer returns the p2p.
	GetP2PPeer() *p2p.Peer

	// DisconnectP2PPeer disconnects the p2p peer with the given reason.
	DisconnectP2PPeer(discReason p2p.DiscReason)

	// GetRW returns the MsgReadWriter of the peer.
	GetRW() p2p.MsgReadWriter

	// Handle is the callback invoked to manage the life cycle of a Klaytn Peer. When
	// this function terminates, the Peer is disconnected.
	Handle(pm *ProtocolManager) error

	// UpdateRWImplementationVersion updates the version of the implementation of RW.
	UpdateRWImplementationVersion()

	// Peer encapsulates the methods required to synchronise with a remote full peer.
	downloader.Peer

	// RegisterConsensusMsgCode registers the channel of consensus msg.
	RegisterConsensusMsgCode(msgCode uint64) error
}

type PeerInfo

type PeerInfo struct {
	Version    int      `json:"version"`    // Klaytn protocol version negotiated
	BlockScore *big.Int `json:"blockscore"` // Total blockscore of the peer's blockchain
	Head       string   `json:"head"`       // SHA3 hash of the peer's best owned block
}

PeerInfo represents a short summary of the Klaytn sub-protocol metadata known about a connected peer.

type PeerSet added in v1.2.0

type PeerSet interface {
	Register(p Peer) error
	Unregister(id string) error

	Peers() map[string]Peer
	CNPeers() map[common.Address]Peer
	ENPeers() map[common.Address]Peer
	PNPeers() map[common.Address]Peer
	Peer(id string) Peer
	Len() int

	PeersWithoutBlock(hash common.Hash) []Peer

	SamplePeersToSendBlock(block *types.Block, nodeType common.ConnType) []Peer
	SampleResendPeersByType(nodeType common.ConnType) []Peer

	PeersWithoutTx(hash common.Hash) []Peer
	TypePeersWithoutTx(hash common.Hash, nodetype common.ConnType) []Peer
	CNWithoutTx(hash common.Hash) []Peer
	UpdateTypePeersWithoutTxs(tx *types.Transaction, nodeType common.ConnType, peersWithoutTxsMap map[Peer]types.Transactions)

	BestPeer() Peer
	RegisterValidator(connType common.ConnType, validator p2p.PeerTypeValidator)
	Close()
}

type PrivateAdminAPI

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

PrivateAdminAPI is the collection of CN full node-related APIs exposed over the private admin endpoint.

func NewPrivateAdminAPI

func NewPrivateAdminAPI(cn *CN) *PrivateAdminAPI

NewPrivateAdminAPI creates a new API definition for the full node private admin methods of the CN service.

func (*PrivateAdminAPI) ExportChain

func (api *PrivateAdminAPI) ExportChain(file string) (bool, error)

ExportChain exports the current blockchain into a local file.

func (*PrivateAdminAPI) ImportChain

func (api *PrivateAdminAPI) ImportChain(file string) (bool, error)

ImportChain imports a blockchain from a local file.

func (*PrivateAdminAPI) ImportChainFromString added in v1.5.0

func (api *PrivateAdminAPI) ImportChainFromString(blockRlp string) (bool, error)

func (*PrivateAdminAPI) SaveTrieNodeCacheToDisk added in v1.5.3

func (api *PrivateAdminAPI) SaveTrieNodeCacheToDisk() error

func (*PrivateAdminAPI) StartStateMigration added in v1.5.0

func (api *PrivateAdminAPI) StartStateMigration() error

StartStateMigration starts state migration.

func (*PrivateAdminAPI) StateMigrationStatus added in v1.5.0

func (api *PrivateAdminAPI) StateMigrationStatus() map[string]interface{}

StateMigrationStatus returns the status information of state trie migration.

func (*PrivateAdminAPI) StopStateMigration added in v1.5.0

func (api *PrivateAdminAPI) StopStateMigration() error

StopStateMigration stops state migration and removes stateMigrationDB.

type PrivateDebugAPI

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

PrivateDebugAPI is the collection of CN full node APIs exposed over the private debugging endpoint.

func NewPrivateDebugAPI

func NewPrivateDebugAPI(config *params.ChainConfig, cn *CN) *PrivateDebugAPI

NewPrivateDebugAPI creates a new API definition for the full node-related private debug methods of the CN service.

func (*PrivateDebugAPI) GetBadBlocks

func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]blockchain.BadBlockArgs, error)

GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network and returns them as a JSON list of block-hashes

func (*PrivateDebugAPI) GetModifiedAccountsByHash

func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error)

GetModifiedAccountsByHash returns all accounts that have changed between the two blocks specified. A change is defined as a difference in nonce, balance, code hash, or storage hash.

With one parameter, returns the list of accounts modified in the specified block.

func (*PrivateDebugAPI) GetModifiedAccountsByNumber

func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error)

GetModifiedAccountsByNumber returns all accounts that have changed between the two blocks specified. A change is defined as a difference in nonce, balance, code hash, or storage hash.

With one parameter, returns the list of accounts modified in the specified block.

func (*PrivateDebugAPI) GetModifiedStorageNodesByNumber added in v1.6.0

func (api *PrivateDebugAPI) GetModifiedStorageNodesByNumber(contractAddr common.Address, startNum uint64, endNum *uint64, printDetail *bool) (int, error)

GetModifiedStorageNodesByNumber returns the number of storage nodes of a contract account that have been changed between the two blocks specified.

With the first two parameters, it returns the number of storage trie nodes modified in the specified block.

func (*PrivateDebugAPI) Preimage

func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error)

Preimage is a debug API function that returns the preimage for a sha3 hash, if known.

func (*PrivateDebugAPI) StandardTraceBadBlockToFile

func (api *PrivateDebugAPI) StandardTraceBadBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error)

StandardTraceBadBlockToFile dumps the structured logs created during the execution of EVM against a block pulled from the pool of bad ones to the local file system and returns a list of files to the caller.

func (*PrivateDebugAPI) StandardTraceBlockToFile

func (api *PrivateDebugAPI) StandardTraceBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error)

StandardTraceBlockToFile dumps the structured logs created during the execution of EVM to the local file system and returns a list of files to the caller.

func (*PrivateDebugAPI) TraceBadBlock

func (api *PrivateDebugAPI) TraceBadBlock(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error)

TraceBadBlock returns the structured logs created during the execution of EVM against a block pulled from the pool of bad ones and returns them as a JSON object.

func (*PrivateDebugAPI) TraceBlock

func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob hexutil.Bytes, config *TraceConfig) ([]*txTraceResult, error)

TraceBlock returns the structured logs created during the execution of EVM and returns them as a JSON object.

func (*PrivateDebugAPI) TraceBlockByHash

func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error)

TraceBlockByHash returns the structured logs created during the execution of EVM and returns them as a JSON object.

func (*PrivateDebugAPI) TraceBlockByNumber

func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error)

TraceBlockByNumber returns the structured logs created during the execution of EVM and returns them as a JSON object.

func (*PrivateDebugAPI) TraceBlockFromFile

func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error)

TraceBlockFromFile returns the structured logs created during the execution of EVM and returns them as a JSON object.

func (*PrivateDebugAPI) TraceChain

func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error)

TraceChain returns the structured logs created during the execution of EVM between two blocks (excluding start) and returns them as a JSON object.

func (*PrivateDebugAPI) TraceTransaction

func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error)

TraceTransaction returns the structured logs created during the execution of EVM and returns them as a JSON object.

type ProtocolManager

type ProtocolManager struct {
	SubProtocols []p2p.Protocol
	// contains filtered or unexported fields
}

func NewProtocolManager

func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkId uint64, mux *event.TypeMux,
	txpool work.TxPool, engine consensus.Engine, blockchain work.BlockChain, chainDB database.DBManager, cacheLimit int,
	nodetype common.ConnType, cnconfig *Config) (*ProtocolManager, error)

NewProtocolManager returns a new Klaytn sub protocol manager. The Klaytn sub protocol manages peers capable with the Klaytn network.

func (*ProtocolManager) BroadcastBlock

func (pm *ProtocolManager) BroadcastBlock(block *types.Block)

BroadcastBlock will propagate a block to a subset of its peers. If current node is CN, it will send block to all PN peers + sampled CN peers without block. However, if there are more than 5 PN peers, it will sample 5 PN peers. If current node is not CN, it will send block to sampled peers except CNs.

func (*ProtocolManager) BroadcastBlockHash

func (pm *ProtocolManager) BroadcastBlockHash(block *types.Block)

BroadcastBlockHash will propagate a blockHash to a subset of its peers.

func (*ProtocolManager) BroadcastTxs

func (pm *ProtocolManager) BroadcastTxs(txs types.Transactions)

BroadcastTxs propagates a batch of transactions to its peers which are not known to already have the given transaction.

func (*ProtocolManager) Downloader added in v1.3.0

func (pm *ProtocolManager) Downloader() ProtocolManagerDownloader

func (*ProtocolManager) Enqueue

func (pm *ProtocolManager) Enqueue(id string, block *types.Block)

Below functions are used in Istanbul BFT consensus. Enqueue wraps fetcher's Enqueue function to insert the given block.

func (*ProtocolManager) FindCNPeers

func (pm *ProtocolManager) FindCNPeers(targets map[common.Address]bool) map[common.Address]consensus.Peer

func (*ProtocolManager) FindPeers

func (pm *ProtocolManager) FindPeers(targets map[common.Address]bool) map[common.Address]consensus.Peer

func (*ProtocolManager) GetCNPeers

func (pm *ProtocolManager) GetCNPeers() map[common.Address]consensus.Peer

func (*ProtocolManager) GetENPeers

func (pm *ProtocolManager) GetENPeers() map[common.Address]consensus.Peer

func (*ProtocolManager) GetPeers

func (pm *ProtocolManager) GetPeers() []common.Address

func (*ProtocolManager) GetSubProtocols added in v1.3.0

func (pm *ProtocolManager) GetSubProtocols() []p2p.Protocol

func (*ProtocolManager) NodeInfo

func (pm *ProtocolManager) NodeInfo() *NodeInfo

NodeInfo retrieves some protocol metadata about the running host node.

func (*ProtocolManager) NodeType added in v1.3.0

func (pm *ProtocolManager) NodeType() common.ConnType

func (*ProtocolManager) ProtocolVersion added in v1.3.0

func (pm *ProtocolManager) ProtocolVersion() int

func (*ProtocolManager) ReBroadcastTxs

func (pm *ProtocolManager) ReBroadcastTxs(txs types.Transactions)

ReBroadcastTxs sends transactions, not considering whether the peer has the transaction or not. Only PN and EN rebroadcast transactions to its peers, a CN does not rebroadcast transactions.

func (*ProtocolManager) RegisterValidator

func (pm *ProtocolManager) RegisterValidator(connType common.ConnType, validator p2p.PeerTypeValidator)

istanbul BFT

func (*ProtocolManager) SetAcceptTxs added in v1.3.0

func (pm *ProtocolManager) SetAcceptTxs()

func (*ProtocolManager) SetRewardbase

func (pm *ProtocolManager) SetRewardbase(addr common.Address)

func (*ProtocolManager) SetRewardbaseWallet

func (pm *ProtocolManager) SetRewardbaseWallet(wallet accounts.Wallet)

func (*ProtocolManager) SetWsEndPoint added in v1.3.0

func (pm *ProtocolManager) SetWsEndPoint(wsep string)

func (*ProtocolManager) Start

func (pm *ProtocolManager) Start(maxPeers int)

func (*ProtocolManager) Stop

func (pm *ProtocolManager) Stop()

type ProtocolManagerDownloader added in v1.3.0

type ProtocolManagerDownloader interface {
	RegisterPeer(id string, version int, peer downloader.Peer) error
	UnregisterPeer(id string) error

	DeliverBodies(id string, transactions [][]*types.Transaction) error
	DeliverHeaders(id string, headers []*types.Header) error
	DeliverNodeData(id string, data [][]byte) error
	DeliverReceipts(id string, receipts [][]*types.Receipt) error

	Terminate()
	Synchronise(id string, head common.Hash, td *big.Int, mode downloader.SyncMode) error
	Progress() klaytn.SyncProgress
}

ProtocolManagerDownloader is an interface of downloader.Downloader used by ProtocolManager.

type ProtocolManagerFetcher added in v1.2.0

type ProtocolManagerFetcher interface {
	Enqueue(peer string, block *types.Block) error
	FilterBodies(peer string, transactions [][]*types.Transaction, time time.Time) [][]*types.Transaction
	FilterHeaders(peer string, headers []*types.Header, time time.Time) []*types.Header
	Notify(peer string, hash common.Hash, number uint64, time time.Time, headerFetcher fetcher.HeaderRequesterFn, bodyFetcher fetcher.BodyRequesterFn) error
	Start()
	Stop()
}

ProtocolManagerFetcher is an interface of fetcher.Fetcher used by ProtocolManager.

type PublicDebugAPI

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

PublicDebugAPI is the collection of Klaytn full node APIs exposed over the public debugging endpoint.

func NewPublicDebugAPI

func NewPublicDebugAPI(cn *CN) *PublicDebugAPI

NewPublicDebugAPI creates a new API definition for the full node- related public debug methods of the Klaytn service.

func (*PublicDebugAPI) DumpBlock

func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error)

DumpBlock retrieves the entire state of the database at a given block.

func (*PublicDebugAPI) DumpStateTrie added in v1.5.0

func (api *PublicDebugAPI) DumpStateTrie(blockNr uint64) (DumpStateTrieResult, error)

DumpStateTrie retrieves all state/storage tries of the given state root.

func (*PublicDebugAPI) StartCollectingTrieStats added in v1.6.0

func (api *PublicDebugAPI) StartCollectingTrieStats(contractAddr common.Address) error

StartCollectingTrieStats collects state/storage trie statistics and print in the log.

func (*PublicDebugAPI) StartContractWarmUp added in v1.6.0

func (api *PublicDebugAPI) StartContractWarmUp(contractAddr common.Address) error

StartContractWarmUp retrieves a storage trie of the latest state root and caches the trie corresponding to the given contract address.

func (*PublicDebugAPI) StartWarmUp added in v1.5.0

func (api *PublicDebugAPI) StartWarmUp() error

StartWarmUp retrieves all state/storage tries of the latest committed state root and caches the tries.

func (*PublicDebugAPI) StopWarmUp added in v1.5.0

func (api *PublicDebugAPI) StopWarmUp() error

StopWarmUp stops the warming up process.

type PublicKlayAPI

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

PublicKlayAPI provides an API to access Klaytn CN-related information.

func NewPublicKlayAPI

func NewPublicKlayAPI(e *CN) *PublicKlayAPI

NewPublicKlayAPI creates a new Klaytn protocol API for full nodes.

func (*PublicKlayAPI) Rewardbase

func (api *PublicKlayAPI) Rewardbase() (common.Address, error)

Rewardbase is the address that consensus rewards will be send to

type StdTraceConfig

type StdTraceConfig struct {
	*vm.LogConfig
	Reexec *uint64
	TxHash common.Hash
}

StdTraceConfig holds extra parameters to standard-json trace functions.

type StorageRangeResult

type StorageRangeResult struct {
	Storage storageMap   `json:"storage"`
	NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the statedb.
}

StorageRangeResult is the result of a debug_storageRangeAt API call.

type TraceConfig

type TraceConfig struct {
	*vm.LogConfig
	Tracer  *string
	Timeout *string
	Reexec  *uint64
}

TraceConfig holds extra parameters to trace functions.

type Trie added in v1.5.0

type Trie struct {
	Type   string `json:"type"`
	Hash   string `json:"hash"`
	Parent string `json:"parent"`
	Path   string `json:"path"`
}

Directories

Path Synopsis
Package filters implements a Klaytn filtering system for blocks, transactions and log events.
Package filters implements a Klaytn filtering system for blocks, transactions and log events.
mock
Package cn is a generated GoMock package.
Package cn is a generated GoMock package.
Package gasprice contains Oracle type which recommends gas prices based on recent blocks.
Package gasprice contains Oracle type which recommends gas prices based on recent blocks.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package tracers provides implementation of Tracer that evaluates a Javascript function for each VM execution step.
Package tracers provides implementation of Tracer that evaluates a Javascript function for each VM execution step.
internal/tracers
Package tracers contains the actual JavaScript tracer assets.
Package tracers contains the actual JavaScript tracer assets.

Jump to

Keyboard shortcuts

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