p2p

package
v0.0.0-...-457eeb3 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2018 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Overview

Package ethapi implements the general Ethereum API functions.

Package p2p implements the Ethereum p2p network protocols.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrPipeClosed = errors.New("p2p: read or write on closed message pipe")

ErrPipeClosed is returned from pipe operations after the pipe has been closed.

Functions

func ExpectMsg

func ExpectMsg(r MsgReader, code uint64, content interface{}) error

ExpectMsg reads a message from r and verifies that its code and encoded RLP content match the provided values. If content is nil, the payload is discarded and not verified.

func GetAPIs

func GetAPIs(apiBackend Backend) []rpc.API

func MsgPipe

func MsgPipe() (*MsgPipeRW, *MsgPipeRW)

MsgPipe creates a message pipe. Reads on one end are matched with writes on the other. The pipe is full-duplex, both ends implement MsgReadWriter.

Example
rw1, rw2 := MsgPipe()
go func() {
	Send(rw1, 8, [][]byte{{0, 0}})
	Send(rw1, 5, [][]byte{{1, 1}})
	rw1.Close()
}()

for {
	msg, err := rw2.ReadMsg()
	if err != nil {
		break
	}
	var data [][]byte
	msg.Decode(&data)
	fmt.Printf("msg: %d, %x\n", msg.Code, data[0])
}
Output:

msg: 8, 0000
msg: 5, 0101

func Send

func Send(w MsgWriter, msgcode uint64, data interface{}) error

Send writes an RLP-encoded message with the given code. data should encode as an RLP list.

func SendItems

func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error

SendItems writes an RLP with the given code and data elements. For a call such as:

SendItems(w, code, e1, e2, e3)

the message payload will be an RLP list containing the items:

[e1, e2, e3]

Types

type AddrLocker

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

func (*AddrLocker) LockAddr

func (l *AddrLocker) LockAddr(address common.Address)

LockAddr locks an account's mutex. This is used to prevent another tx getting the same nonce until the lock is released. The mutex prevents the (an identical nonce) from being read again during the time that the first transaction is being signed.

func (*AddrLocker) UnlockAddr

func (l *AddrLocker) UnlockAddr(address common.Address)

UnlockAddr unlocks the mutex of the given account.

type Backend

type Backend interface {
	// general Ethereum API
	Downloader() *downloader.Downloader
	ProtocolVersion() int
	SuggestPrice(ctx context.Context) (*big.Int, error)
	ChainDb() store.Database
	EventMux() *event.TypeMux
	AccountManager() *account.Manager
	// BlockChain API
	SetHead(number uint64)
	HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error)
	BlockByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Block, error)
	StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*state.StateDB, *types.Header, error)
	GetBlock(ctx context.Context, blockHash common.Hash) (*types.Block, error)
	GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
	GetTd(blockHash common.Hash) *big.Int
	GetEVM(ctx context.Context, msg core.Message, state *state.StateDB, header *types.Header, vmCfg vm.Config) (*vm.EVM, func() error, error)
	SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
	SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
	SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription

	// TxPool API
	SendTx(ctx context.Context, signedTx *types.Transaction) error
	GetPoolTransactions() (types.Transactions, error)
	GetPoolTransaction(txHash common.Hash) *types.Transaction
	GetPoolNonce(ctx context.Context, addr common.Address) (uint64, error)
	Stats() (pending int, queued int)
	TxPoolContent() (map[common.Address]types.Transactions, map[common.Address]types.Transactions)
	SubscribeTxPreEvent(chan<- core.TxPreEvent) event.Subscription

	ChainConfig() *config.ChainConfig
	CurrentBlock() *types.Block
}

Backend interface provides the common API services (that are provided by both full and light clients) with access to necessary functions.

type CallArgs

type CallArgs struct {
	DAppID   common.Hash     `json:"dappid"`
	From     common.Address  `json:"from"`
	To       *common.Address `json:"to"`
	Gas      hexutil.Uint64  `json:"gas"`
	GasPrice hexutil.Big     `json:"gasPrice"`
	Value    hexutil.Big     `json:"value"`
	Data     hexutil.Bytes   `json:"data"`
}

CallArgs represents the arguments for a call.

type Cap

type Cap struct {
	Name    string
	Version uint
}

Cap is the structure of a peer capability.

func (Cap) RlpData

func (cap Cap) RlpData() interface{}

func (Cap) String

func (cap Cap) String() string

type Config

type Config struct {
	// This field must be set to a valid secp256k1 private key.
	PrivateKey *ecdsa.PrivateKey `toml:"-"`

	// MaxPeers is the maximum number of peers that can be
	// connected. It must be greater than zero.
	MaxPeers int

	// MaxPendingPeers is the maximum number of peers that can be pending in the
	// handshake phase, counted separately for inbound and outbound connections.
	// Zero defaults to preset values.
	MaxPendingPeers int `toml:",omitempty"`

	// DialRatio controls the ratio of inbound to dialed connections.
	// Example: a DialRatio of 2 allows 1/2 of connections to be dialed.
	// Setting DialRatio to zero defaults it to 3.
	DialRatio int `toml:",omitempty"`

	// NoDiscovery can be used to disable the peer discovery mechanism.
	// Disabling is useful for protocol debugging (manual topology).
	NoDiscovery bool

	// Name sets the node name of this server.
	// Use common.MakeName to create a name that follows existing conventions.
	Name string `toml:"-"`

	// BootstrapNodes are used to establish connectivity
	// with the rest of the network.
	BootstrapNodes []*discover.Node

	// Static nodes are used as pre-configured connections which are always
	// maintained and re-connected on disconnects.
	StaticNodes []*discover.Node

	// Trusted nodes are used as pre-configured connections which are always
	// allowed to connect, even above the peer limit.
	TrustedNodes []*discover.Node

	// Connectivity can be restricted to certain IP networks.
	// If this option is set to a non-nil value, only hosts which match one of the
	// IP networks contained in the list are considered.
	NetRestrict *netutil.Netlist `toml:",omitempty"`

	// NodeDatabase is the path to the database containing the previously seen
	// live nodes in the network.
	NodeDatabase string `toml:",omitempty"`

	// Protocols should contain the protocols supported
	// by the server. Matching protocols are launched for
	// each peer.
	Protocols []Protocol `toml:"-"`

	// If ListenAddr is set to a non-nil address, the server
	// will listen for incoming connections.
	//
	// If the port is zero, the operating system will pick a port. The
	// ListenAddr field will be updated with the actual address when
	// the server is started.
	ListenAddr string

	// If set to a non-nil value, the given NAT port mapper
	// is used to make the listening port available to the
	// Internet.
	NAT nat.Interface `toml:",omitempty"`

	// If Dialer is set to a non-nil value, the given Dialer
	// is used to dial outbound peer connections.
	Dialer NodeDialer `toml:"-"`

	// If NoDial is true, the server will not dial any peers.
	NoDial bool `toml:",omitempty"`

	// If EnableMsgEvents is set then the server will emit PeerEvents
	// whenever a message is sent to or received from a peer
	EnableMsgEvents bool

	// Logger is a custom logger to use with the p2p.Server.
	Logger log.Logger `toml:",omitempty"`
}

Config holds Server options.

type DiscReason

type DiscReason uint
const (
	DiscRequested DiscReason = iota
	DiscNetworkError
	DiscProtocolError
	DiscUselessPeer
	DiscTooManyPeers
	DiscAlreadyConnected
	DiscIncompatibleVersion
	DiscInvalidIdentity
	DiscQuitting
	DiscUnexpectedIdentity
	DiscSelf
	DiscReadTimeout
	DiscSubprotocolError = 0x10
)

func (DiscReason) Error

func (d DiscReason) Error() string

func (DiscReason) String

func (d DiscReason) String() string

type ExecutionResult

type ExecutionResult struct {
	Gas         uint64         `json:"gas"`
	Failed      bool           `json:"failed"`
	ReturnValue string         `json:"returnValue"`
	StructLogs  []StructLogRes `json:"structLogs"`
}

ExecutionResult groups all structured logs emitted by the EVM while replaying a transaction in debug mode as well as transaction execution status, the amount of gas used and the return value

type JavascriptTracer

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

JavascriptTracer provides an implementation of Tracer that evaluates a Javascript function for each VM execution step.

func NewJavascriptTracer

func NewJavascriptTracer(code string) (*JavascriptTracer, error)

NewJavascriptTracer instantiates a new JavascriptTracer instance. code specifies a Javascript snippet, which must evaluate to an expression returning an object with 'step' and 'result' functions.

func (*JavascriptTracer) CaptureEnd

func (jst *JavascriptTracer) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error

CaptureEnd is called after the call finishes

func (*JavascriptTracer) CaptureState

func (jst *JavascriptTracer) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) error

CaptureState implements the Tracer interface to trace a single step of VM execution

func (*JavascriptTracer) GetResult

func (jst *JavascriptTracer) GetResult() (result interface{}, err error)

GetResult calls the Javascript 'result' function and returns its value, or any accumulated error

func (*JavascriptTracer) Stop

func (jst *JavascriptTracer) Stop(err error)

Stop terminates execution of any JavaScript

type Msg

type Msg struct {
	Code       uint64
	Size       uint32 // size of the paylod
	Payload    io.Reader
	ReceivedAt time.Time
}

Msg defines the structure of a p2p message.

Note that a Msg can only be sent once since the Payload reader is consumed during sending. It is not possible to create a Msg and send it any number of times. If you want to reuse an encoded structure, encode the payload into a byte array and create a separate Msg with a bytes.Reader as Payload for each send.

func (Msg) Decode

func (msg Msg) Decode(val interface{}) error

Decode parses the RLP content of a message into the given value, which must be a pointer.

For the decoding rules, please see package rlp.

func (Msg) Discard

func (msg Msg) Discard() error

Discard reads any remaining payload data into a black hole.

func (Msg) String

func (msg Msg) String() string

type MsgPipeRW

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

MsgPipeRW is an endpoint of a MsgReadWriter pipe.

func (*MsgPipeRW) Close

func (p *MsgPipeRW) Close() error

Close unblocks any pending ReadMsg and WriteMsg calls on both ends of the pipe. They will return ErrPipeClosed. Close also interrupts any reads from a message payload.

func (*MsgPipeRW) ReadMsg

func (p *MsgPipeRW) ReadMsg() (Msg, error)

ReadMsg returns a message sent on the other end of the pipe.

func (*MsgPipeRW) WriteMsg

func (p *MsgPipeRW) WriteMsg(msg Msg) error

WriteMsg sends a messsage on the pipe. It blocks until the receiver has consumed the message payload.

type MsgReadWriter

type MsgReadWriter interface {
	MsgReader
	MsgWriter
}

MsgReadWriter provides reading and writing of encoded messages. Implementations should ensure that ReadMsg and WriteMsg can be called simultaneously from multiple goroutines.

type MsgReader

type MsgReader interface {
	ReadMsg() (Msg, error)
}

type MsgWriter

type MsgWriter interface {
	// WriteMsg sends a message. It will block until the message's
	// Payload has been consumed by the other end.
	//
	// Note that messages can be sent only once because their
	// payload reader is drained.
	WriteMsg(Msg) error
}

type NodeDialer

type NodeDialer interface {
	Dial(*discover.Node) (net.Conn, error)
}

NodeDialer is used to connect to nodes in the network, typically by using an underlying net.Dialer but also using net.Pipe in tests

type NodeInfo

type NodeInfo struct {
	ID    string `json:"id"`    // Unique node identifier (also the encryption key)
	Name  string `json:"name"`  // Name of the node, including client type, version, OS, custom data
	Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
	IP    string `json:"ip"`    // IP address of the node
	Ports struct {
		Discovery int `json:"discovery"` // UDP listening port for discovery protocol
		Listener  int `json:"listener"`  // TCP listening port for RLPx
	} `json:"ports"`
	ListenAddr string                 `json:"listenAddr"`
	Protocols  map[string]interface{} `json:"protocols"`
}

NodeInfo represents a short summary of the information known about the host.

type Peer

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

Peer represents a connected remote node.

func NewPeer

func NewPeer(id discover.NodeID, name string, caps []Cap) *Peer

NewPeer returns a peer for testing purposes.

func (*Peer) Caps

func (p *Peer) Caps() []Cap

Caps returns the capabilities (supported subprotocols) of the remote peer.

func (*Peer) Disconnect

func (p *Peer) Disconnect(reason DiscReason)

Disconnect terminates the peer connection with the given reason. It returns immediately and does not wait until the connection is closed.

func (*Peer) ID

func (p *Peer) ID() discover.NodeID

ID returns the node's public key.

func (*Peer) Inbound

func (p *Peer) Inbound() bool

Inbound returns true if the peer is an inbound connection

func (*Peer) Info

func (p *Peer) Info() *PeerInfo

Info gathers and returns a collection of metadata known about a peer.

func (*Peer) LocalAddr

func (p *Peer) LocalAddr() net.Addr

LocalAddr returns the local address of the network connection.

func (*Peer) Log

func (p *Peer) Log() log.Logger

func (*Peer) Name

func (p *Peer) Name() string

Name returns the node name that the remote node advertised.

func (*Peer) RemoteAddr

func (p *Peer) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the network connection.

func (*Peer) String

func (p *Peer) String() string

String implements fmt.Stringer.

type PeerEvent

type PeerEvent struct {
	Type     PeerEventType   `json:"type"`
	Peer     discover.NodeID `json:"peer"`
	Error    string          `json:"error,omitempty"`
	Protocol string          `json:"protocol,omitempty"`
	MsgCode  *uint64         `json:"msg_code,omitempty"`
	MsgSize  *uint32         `json:"msg_size,omitempty"`
}

PeerEvent is an event emitted when peers are either added or dropped from a p2p.Server or when a message is sent or received on a peer connection

type PeerEventType

type PeerEventType string

PeerEventType is the type of peer events emitted by a p2p.Server

const (
	// PeerEventTypeAdd is the type of event emitted when a peer is added
	// to a p2p.Server
	PeerEventTypeAdd PeerEventType = "add"

	// PeerEventTypeDrop is the type of event emitted when a peer is
	// dropped from a p2p.Server
	PeerEventTypeDrop PeerEventType = "drop"

	// PeerEventTypeMsgSend is the type of event emitted when a
	// message is successfully sent to a peer
	PeerEventTypeMsgSend PeerEventType = "msgsend"

	// PeerEventTypeMsgRecv is the type of event emitted when a
	// message is received from a peer
	PeerEventTypeMsgRecv PeerEventType = "msgrecv"
)

type PeerInfo

type PeerInfo struct {
	ID      string   `json:"id"`   // Unique node identifier (also the encryption key)
	Name    string   `json:"name"` // Name of the node, including client type, version, OS, custom data
	Caps    []string `json:"caps"` // Sum-protocols advertised by this particular peer
	Network struct {
		LocalAddress  string `json:"localAddress"`  // Local endpoint of the TCP data connection
		RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection
		Inbound       bool   `json:"inbound"`
		Trusted       bool   `json:"trusted"`
		Static        bool   `json:"static"`
	} `json:"network"`
	Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields
}

PeerInfo represents a short summary of the information known about a connected peer. Sub-protocol independent fields are contained and initialized here, with protocol specifics delegated to all connected sub-protocols.

type PrivateAccountAPI

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

PrivateAccountAPI provides an API to access accounts managed by this node. It offers methods to create, (un)lock en list accounts. Some methods accept passwords and are therefore considered private by default.

func NewPrivateAccountAPI

func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI

NewPrivateAccountAPI create a new PrivateAccountAPI.

func (*PrivateAccountAPI) DeriveAccount

func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (account.Account, error)

DeriveAccount requests a HD wallet to derive a new account, optionally pinning it for later reuse.

func (*PrivateAccountAPI) EcRecover

func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error)

EcRecover returns the address for the account that was used to create the signature. Note, this function is compatible with eth_sign and personal_sign. As such it recovers the address of: hash = keccak256("\x19Juchain Signed Message:\n"${message length}${message}) addr = ecrecover(hash, signature)

Note, the signature must conform to the secp256k1 curve R, S and V values, where the V value must be be 27 or 28 for legacy reasons.

https://github.com/juchain/go-juchain/wiki/Management-APIs#personal_ecRecover

func (*PrivateAccountAPI) HashDApp

func (s *PrivateAccountAPI) HashDApp(dappId *common.Address) bool

func (*PrivateAccountAPI) ImportDAppRawKey

func (s *PrivateAccountAPI) ImportDAppRawKey(privkey string, password string) (common.Address, error)

func (*PrivateAccountAPI) ImportRawKey

func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error)

ImportRawKey stores the given hex encoded ECDSA key into the key directory, encrypting it with the passphrase.

func (*PrivateAccountAPI) ListAccounts

func (s *PrivateAccountAPI) ListAccounts() []common.Address

ListAccounts will return a list of addresses for accounts this node manages.

func (*PrivateAccountAPI) ListAllDAppIds

func (s *PrivateAccountAPI) ListAllDAppIds(offset uint8) ([]common.Address, error)

func (*PrivateAccountAPI) ListDAppContracts

func (s *PrivateAccountAPI) ListDAppContracts(dappId common.Address) error

func (*PrivateAccountAPI) ListDAppStorageNodeInfo

func (s *PrivateAccountAPI) ListDAppStorageNodeInfo(dappId common.Address, password string) ([]string, error)

func (*PrivateAccountAPI) ListWallets

func (s *PrivateAccountAPI) ListWallets() []rawWallet

ListWallets will return a list of wallets this node manages.

func (*PrivateAccountAPI) LockAccount

func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool

LockAccount will lock the account associated with the given address when it's unlocked.

func (*PrivateAccountAPI) NewAccount

func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error)

NewAccount will create a new account and returns the address for the new account.

func (*PrivateAccountAPI) NewDAppAccount

func (s *PrivateAccountAPI) NewDAppAccount(dappName string, orgName string, orgDescription,
	nationalityCode int, password string) (common.Address, error)

NewDAppAccount will create a new account and returns the address for the new Dapp user.

func (*PrivateAccountAPI) OpenWallet

func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error

OpenWallet initiates a hardware wallet opening procedure, establishing a USB connection and attempting to authenticate via the provided passphrase. Note, the method may return an extra challenge requiring a second open (e.g. the Trezor PIN matrix challenge).

func (*PrivateAccountAPI) SendTransaction

func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error)

SendTransaction will create a transaction from the given arguments and tries to sign it with the key associated with args.To. If the given passwd isn't able to decrypt the key it fails.

func (*PrivateAccountAPI) Sign

func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error)

Sign calculates an Juchain ECDSA signature for: keccack256("\x19Juchain Signed Message:\n" + len(message) + message))

Note, the produced signature conforms to the secp256k1 curve R, S and V values, where the V value will be 27 or 28 for legacy reasons.

The key used to calculate the signature is decrypted with the given password.

https://github.com/juchain/go-juchain/wiki/Management-APIs#personal_sign

func (*PrivateAccountAPI) SignAndSendTransaction

func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error)

SignAndSendTransaction was renamed to SendTransaction. This method is deprecated and will be removed in the future. It primary goal is to give clients time to update.

func (*PrivateAccountAPI) SignTransaction

func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error)

SignTransaction will create a transaction from the given arguments and tries to sign it with the key associated with args.To. If the given passwd isn't able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast to other nodes

func (*PrivateAccountAPI) TotalDApps

func (s *PrivateAccountAPI) TotalDApps() (int, error)

func (*PrivateAccountAPI) UnlockAccount

func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64) (bool, error)

UnlockAccount will unlock the account associated with the given address with the given password for duration seconds. If duration is nil it will use a default of 300 seconds. It returns an indication if the account was unlocked.

func (*PrivateAccountAPI) UpdateDAppStorageNode

func (s *PrivateAccountAPI) UpdateDAppStorageNode(dappId common.Address, password string, nodes []string) error

type PrivateDebugAPI

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

PrivateDebugAPI is the collection of Juchain APIs exposed over the private debugging endpoint.

func NewPrivateDebugAPI

func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI

NewPrivateDebugAPI creates a new API definition for the private debug methods of the Juchain service.

func (*PrivateDebugAPI) ChaindbCompact

func (api *PrivateDebugAPI) ChaindbCompact() error

func (*PrivateDebugAPI) ChaindbProperty

func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error)

ChaindbProperty returns leveldb properties of the chain database.

func (*PrivateDebugAPI) SetHead

func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64)

SetHead rewinds the head of the blockchain to a previous block.

type Protocol

type Protocol struct {
	// Name should contain the official protocol name,
	// often a three-letter word.
	Name string

	// Version should contain the version number of the protocol.
	Version uint

	// Length should contain the number of message codes used
	// by the protocol.
	Length uint64

	// Run is called in a new groutine when the protocol has been
	// negotiated with a peer. It should read and write messages from
	// rw. The Payload for each message must be fully consumed.
	//
	// The peer connection is closed when Start returns. It should return
	// any protocol-level error (such as an I/O error) that is
	// encountered.
	Run func(peer *Peer, rw MsgReadWriter) error

	// NodeInfo is an optional helper method to retrieve protocol specific metadata
	// about the host node.
	NodeInfo func() interface{}

	// PeerInfo is an optional helper method to retrieve protocol specific metadata
	// about a certain peer in the network. If an info retrieval function is set,
	// but returns nil, it is assumed that the protocol handshake is still running.
	PeerInfo func(id discover.NodeID) interface{}
}

Protocol represents a P2P subprotocol implementation.

type PublicAccountAPI

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

PublicAccountAPI provides an API to access accounts managed by this node. It offers only methods that can retrieve accounts.

func NewPublicAccountAPI

func NewPublicAccountAPI(am *account.Manager) *PublicAccountAPI

NewPublicAccountAPI creates a new PublicAccountAPI.

func (*PublicAccountAPI) Accounts

func (s *PublicAccountAPI) Accounts() []common.Address

Accounts returns the collection of accounts this node manages

type PublicBlockChainAPI

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

PublicBlockChainAPI provides an API to access the Juchain blockchain. It offers only methods that operate on public data that is freely available to anyone.

func NewPublicBlockChainAPI

func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI

NewPublicBlockChainAPI creates a new Juchain blockchain API.

func (*PublicBlockChainAPI) BlockNumber

func (s *PublicBlockChainAPI) BlockNumber() *big.Int

rpc.BlockNumber returns the block number of the chain head.

func (*PublicBlockChainAPI) Call

func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error)

Call executes the given transaction on the state for the given block number. It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.

func (*PublicBlockChainAPI) EstimateGas

func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error)

EstimateGas returns an estimate of the amount of gas needed to execute the given transaction against the current pending block.

func (*PublicBlockChainAPI) GetBalance

func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error)

GetBalance returns the amount of wei for the given address in the state of the given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block numbers are also allowed.

func (*PublicBlockChainAPI) GetBlockByHash

func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error)

GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.

func (*PublicBlockChainAPI) GetBlockByNumber

func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error)

GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.

func (*PublicBlockChainAPI) GetCode

func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Bytes, error)

GetCode returns the code stored at the given address in the state for the given block number.

func (*PublicBlockChainAPI) GetStorageAt

func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (hexutil.Bytes, error)

GetStorageAt returns the storage from the state at the given address, key and block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block numbers are also allowed.

func (*PublicBlockChainAPI) GetUncleByBlockHashAndIndex

func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error)

GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.

func (*PublicBlockChainAPI) GetUncleByBlockNumberAndIndex

func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error)

GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.

func (*PublicBlockChainAPI) GetUncleCountByBlockHash

func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint

GetUncleCountByBlockHash returns number of uncles in the block for the given block hash

func (*PublicBlockChainAPI) GetUncleCountByBlockNumber

func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint

GetUncleCountByBlockNumber returns number of uncles in the block for the given block number

type PublicDebugAPI

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

PublicDebugAPI is the collection of Juchain APIs exposed over the public debugging endpoint.

func NewPublicDebugAPI

func NewPublicDebugAPI(b Backend) *PublicDebugAPI

NewPublicDebugAPI creates a new API definition for the public debug methods of the Juchain service.

func (*PublicDebugAPI) GetBlockRlp

func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error)

GetBlockRlp retrieves the RLP encoded for of a single block.

func (*PublicDebugAPI) PrintBlock

func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error)

PrintBlock retrieves a block and returns its pretty printed form.

func (*PublicDebugAPI) SeedHash

func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error)

SeedHash retrieves the seed hash of a block.

type PublicJuchainAPI

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

PublicJuchainAPI provides an API to access Juchain related information. It offers only methods that operate on public data that is freely available to anyone.

func NewPublicJuchainAPI

func NewPublicJuchainAPI(b Backend) *PublicJuchainAPI

NewPublicJuchainAPI creates a new Juchain protocol API.

func (*PublicJuchainAPI) GasPrice

func (s *PublicJuchainAPI) GasPrice(ctx context.Context) (*big.Int, error)

GasPrice returns a suggestion for a gas price.

func (*PublicJuchainAPI) ProtocolVersion

func (s *PublicJuchainAPI) ProtocolVersion() hexutil.Uint

ProtocolVersion returns the current Juchain protocol version this node supports

func (*PublicJuchainAPI) Syncing

func (s *PublicJuchainAPI) Syncing() (interface{}, error)

Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not yet received the latest block headers from its pears. In case it is synchronizing: - startingBlock: block number this node started to synchronise from - currentBlock: block number this node is currently importing - highestBlock: block number of the highest block header this node has received from peers - pulledStates: number of state entries processed until now - knownStates: number of known state entries that still need to be pulled

type PublicNetAPI

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

PublicNetAPI offers network related RPC methods

func NewPublicNetAPI

func NewPublicNetAPI(net *Server, networkVersion uint64) *PublicNetAPI

NewPublicNetAPI creates a new net API instance.

func (*PublicNetAPI) Listening

func (s *PublicNetAPI) Listening() bool

Listening returns an indication if the node is listening for network connections.

func (*PublicNetAPI) PeerCount

func (s *PublicNetAPI) PeerCount() hexutil.Uint

PeerCount returns the number of connected peers

func (*PublicNetAPI) Version

func (s *PublicNetAPI) Version() string

Version returns the current ethereum protocol version.

type PublicTransactionPoolAPI

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

PublicTransactionPoolAPI exposes methods for the RPC interface

func NewPublicTransactionPoolAPI

func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI

NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.

func (*PublicTransactionPoolAPI) GetBlockTransactionCountByHash

func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint

GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.

func (*PublicTransactionPoolAPI) GetBlockTransactionCountByNumber

func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint

GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.

func (*PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex

func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes

GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.

func (*PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex

func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes

GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.

func (*PublicTransactionPoolAPI) GetRawTransactionByHash

func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error)

GetRawTransactionByHash returns the bytes of the transaction for the given hash.

func (*PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex

func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction

GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.

func (*PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex

func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction

GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.

func (*PublicTransactionPoolAPI) GetTransactionByHash

func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) *RPCTransaction

GetTransactionByHash returns the transaction for the given hash

func (*PublicTransactionPoolAPI) GetTransactionCount

func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error)

GetTransactionCount returns the number of transactions the given address has sent for the given block number

func (*PublicTransactionPoolAPI) GetTransactionReceipt

func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error)

GetTransactionReceipt returns the transaction receipt for the given transaction hash.

func (*PublicTransactionPoolAPI) PendingTransactions

func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error)

PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of the accounts this node manages.

func (*PublicTransactionPoolAPI) Resend

func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error)

Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the pool and reinsert it with the new gas price and limit.

func (*PublicTransactionPoolAPI) SendRawTransaction

func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error)

SendRawTransaction will add the signed transaction to the transaction pool. The sender is responsible for signing the transaction and using the correct nonce.

func (*PublicTransactionPoolAPI) SendTransaction

func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error)

SendTransaction creates a transaction for the given argument, sign it and submit it to the transaction pool.

func (*PublicTransactionPoolAPI) Sign

Sign calculates an ECDSA signature for: keccack256("\x19Juchain Signed Message:\n" + len(message) + message).

Note, the produced signature conforms to the secp256k1 curve R, S and V values, where the V value will be 27 or 28 for legacy reasons.

The account associated with addr must be unlocked.

https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign

func (*PublicTransactionPoolAPI) SignTransaction

SignTransaction will sign the given transaction with the from account. The node needs to have the private key of the account corresponding with the given from address and it needs to be unlocked.

type PublicTxPoolAPI

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

PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.

func NewPublicTxPoolAPI

func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI

NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.

func (*PublicTxPoolAPI) Content

func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction

Content returns the transactions contained within the transaction pool.

func (*PublicTxPoolAPI) Inspect

func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string

Inspect retrieves the content of the transaction pool and flattens it into an easily inspectable list.

func (*PublicTxPoolAPI) Status

func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint

Status returns the number of pending and queued transaction in the pool.

type RPCTransaction

type RPCTransaction struct {
	BlockHash        common.Hash     `json:"blockHash"`
	BlockNumber      *hexutil.Big    `json:"blockNumber"`
	From             common.Address  `json:"from"`
	Gas              hexutil.Uint64  `json:"gas"`
	GasPrice         *hexutil.Big    `json:"gasPrice"`
	Hash             common.Hash     `json:"hash"`
	Input            hexutil.Bytes   `json:"input"`
	Nonce            hexutil.Uint64  `json:"nonce"`
	To               *common.Address `json:"to"`
	TransactionIndex hexutil.Uint    `json:"transactionIndex"`
	Value            *hexutil.Big    `json:"value"`
	V                *hexutil.Big    `json:"v"`
	R                *hexutil.Big    `json:"r"`
	S                *hexutil.Big    `json:"s"`
}

RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction

type SendTxArgs

type SendTxArgs struct {
	DAppID   *common.Address `json:"dappid"`
	From     common.Address  `json:"from"`
	To       *common.Address `json:"to"`
	Gas      *hexutil.Uint64 `json:"gas"`
	GasPrice *hexutil.Big    `json:"gasPrice"`
	Value    *hexutil.Big    `json:"value"`
	Nonce    *hexutil.Uint64 `json:"nonce"`
	// We accept "data" and "input" for backwards-compatibility reasons. "input" is the
	// newer name and should be preferred by clients.
	Data  *hexutil.Bytes `json:"data"`
	Input *hexutil.Bytes `json:"input"`
}

SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.

type Server

type Server struct {
	// Config fields may not be modified while the server is running.
	Config
	// contains filtered or unexported fields
}

Server manages all peer connections.

func (*Server) AddPeer

func (srv *Server) AddPeer(node *discover.Node)

AddPeer connects to the given node and maintains the connection until the server is shut down. If the connection fails for any reason, the server will attempt to reconnect the peer.

func (*Server) NodeInfo

func (srv *Server) NodeInfo() *NodeInfo

NodeInfo gathers and returns a collection of metadata known about the host.

func (*Server) PeerCount

func (srv *Server) PeerCount() int

PeerCount returns the number of connected peers.

func (*Server) Peers

func (srv *Server) Peers() []*Peer

Peers returns all connected peers.

func (*Server) PeersInfo

func (srv *Server) PeersInfo() []*PeerInfo

PeersInfo returns an array of metadata objects describing connected peers.

func (*Server) RemovePeer

func (srv *Server) RemovePeer(node *discover.Node)

RemovePeer disconnects from the given node

func (*Server) Self

func (srv *Server) Self() *discover.Node

Self returns the local node's endpoint information.

func (*Server) SetupConn

func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *discover.Node)

SetupConn runs the handshakes and attempts to add the connection as a peer. It returns when the connection has been added as a peer or the handshakes have failed.

func (*Server) Start

func (srv *Server) Start() (err error)

Start starts running the server. Servers can not be re-used after stopping.

func (*Server) Stop

func (srv *Server) Stop()

Stop terminates the server and all active peer connections. It blocks until all active connections have been closed.

func (*Server) SubscribeEvents

func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription

SubscribePeers subscribes the given channel to peer events

type SignTransactionResult

type SignTransactionResult struct {
	Raw hexutil.Bytes      `json:"raw"`
	Tx  *types.Transaction `json:"tx"`
}

SignTransactionResult represents a RLP encoded signed transaction.

type StructLogRes

type StructLogRes struct {
	Pc      uint64             `json:"pc"`
	Op      string             `json:"op"`
	Gas     uint64             `json:"gas"`
	GasCost uint64             `json:"gasCost"`
	Depth   int                `json:"depth"`
	Error   error              `json:"error,omitempty"`
	Stack   *[]string          `json:"stack,omitempty"`
	Memory  *[]string          `json:"memory,omitempty"`
	Storage *map[string]string `json:"storage,omitempty"`
}

StructLogRes stores a structured log emitted by the EVM while replaying a transaction in debug mode

func FormatLogs

func FormatLogs(logs []vm.StructLog) []StructLogRes

formatLogs formats EVM returned structured logs for json output

type TCPDialer

type TCPDialer struct {
	*net.Dialer
}

TCPDialer implements the NodeDialer interface by using a net.Dialer to create TCP connections to nodes in the network

func (TCPDialer) Dial

func (t TCPDialer) Dial(dest *discover.Node) (net.Conn, error)

Dial creates a TCP connection to the node

Directories

Path Synopsis
Package discover implements the Node Discovery Protocol.
Package discover implements the Node Discovery Protocol.
Package nat provides access to common network port mapping protocols.
Package nat provides access to common network port mapping protocols.
Package netutil contains extensions to the net package.
Package netutil contains extensions to the net package.
Package node sets up multi-protocol Ethereum nodes.
Package node sets up multi-protocol Ethereum nodes.
Package eth implements the Infinet protocol.
Package eth implements the Infinet protocol.
downloader
Package downloader contains the manual full chain synchronisation.
Package downloader contains the manual full chain synchronisation.
fetcher
Package fetcher contains the block announcement based synchronisation.
Package fetcher contains the block announcement based synchronisation.
filters
Package filters implements an ethereum filtering system for block, transactions and log events.
Package filters implements an ethereum filtering system for block, transactions and log events.

Jump to

Keyboard shortcuts

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