ionchain

package module
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2020 License: MIT Imports: 5 Imported by: 0

README

ionchain-core

本项目是ionchain协议golang版本的实现

在这篇博客中IPOS共识算法设计,详细说明了ionchain的共识算法的设计详情。

源码编译

在编译之前,你现需要安装golang(版本大于等于1.10)和C编译器

clone项目到你指定的目录中:

git clone https://github.com/ionchain/ionchain-core

使用以下命令编译ionc

cd ionchain-core

make ionc

或者可以通过以下命令编译其他平台的ionc版本(Linuxwindows

make all

在ionchain主网上运行全节点

用户在ionchain是最多的使用场景就是:创建账号,转移资产,部署、调用合约。为了满足这个特定的场景,可以使用快速同步方法来启动网络,执行以下命令:

$ ionc console

上面这个命令将产生以下两个操作:

  • 在快速同步模式下,启动ionc节点,在快速同步模式下,节点将会下载所有的状态数据,而不是执行所有ionchain网络上的所有交易.
  • 开启一个内置的javascript console控制台,在控制台中用户可以与ionchain网络进行交互。
使用Docker快速启动节点

启动ionchain网络最快速的方式就是在本地启动一个Docker

docker run -d --name ionchain-node -v /Users/alice/ionchain:/root \
           -p 8545:8545 -p 30303:30303 \
           ionchain/go-ionchain

docker会在/Users/alice/ionchain本地目录中映射一个持久的volume用来存储区块,同时也会映射默认端口。如果你想从其他容器或主机通过RPC方式访问运行的节点,需要加上--rpcaddr 0.0.0.0参数。默认情况下,ionc绑定的本地接口与RPC端点是不能从外部访问的。

以编程的方式与IONC节点交互

作为一个开发人员想通过自己的程序与ionchain网络进行交互,而不是通过JavaScript console的方式,为了满足这种需求,ionc有一个内置JSON-RPC API,这些API通过HTTPWebSocketsIPC方式暴露出去。其中IPC端口是默认开启的,HTTPWS端口需要手动开启,同时为了安全方面的考虑,这两个端口只会暴露部分API。

基于HTTP的JSON-RPC API 选项:

  • --rpc 开启 HTTP-RPC 服务
  • --rpcaddr HTTP-RPC 服务监听地址 (默认: "localhost")
  • --rpcport HTTP-RPC 服务监听端口 (默认: 8545)
  • --rpcapi 通过HTTP暴露出可用的API
  • --rpccorsdomain 逗号分隔的一系列域,通过这些域接收跨域请求

基于WebSocket的 JSON-RPC API选项:

  • --ws 开启 WS-RPC 服务
  • --wsaddr WS-RPC 服务监听地址(默认: "localhost")
  • --wsport WS-RPC 服务监听端口 (默认: 8546)
  • --wsapi 通过WS-PRC暴露出可用的API

基于IPC的JSON-RPC AP选项

  • --ipcdisable 禁用 IPC-RPC 服务
  • --ipcapi 通过IPC-PRC暴露出可用的API

注意:在使用http/ws接口之前,你需要了解相关的安全知识,在公网上,黑客会利用节点在公网上暴露的接口进行破坏式的攻击

创建一个私有链

创建一个自己的私有链会有一点复杂,因为你需要手动修改很多官方创建文件的配置。

定义私有链创世块

首先,为你的私有网络创建一个创始状态,这个创始状态需要你的私有网络中的所有节点都知晓,并达成共识。genesis.json以JSON格式组成:

{
		  "config": {
			"chainId":
		  },
		  "alloc": {},
			"0x0000000000000000000000000000000000000100": {
			  "code": "编译后的保证金合约二进制代码",
			  "storage": {
				"0x0000000000000000000000000000000000000000000000000000000000000000": "0x0a",
				"0x33d4e30ad2c3b9f507062560fe978acc29929f1ee5c2c33abe6d050171fd8c93": "0x0de0b6b3a7640000",
				"0xe0811e07d38b83ef44191e63c263ef79eeed21f1260fd00fef00a37495c1accc": "0xd9a7c07f349d4ac7640000"
			  },
			  "balance": ""
			}
		  },
		  "coinbase": "0x0000000000000000000000000000000000000000",
		  "difficulty": "0x01",
		  "extraData": "0x777573686f756865",
		  "gasLimit": "0x47e7c4",
		  "nonce": "0x0000000000000001",
		  "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
		  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
		  "timestamp": "0x00",
		  "baseTarget": "0x1bc4fd6588",
		  "blockSignature": "0x00",
		  "generationSignature": "0x00"
		}

以上关于保证金合约是如何创建、编译的将在另外一个项目中做详细说明,我们建议你修改nonce值为一个随机数,这样可以防止未知的远程节点连接到你的网络中。如果你需要给某些账户预设一些资金,可以使用修改alloc值:

"alloc": {
  "0x0000000000000000000000000000000000000001": {"balance": "111111111"},
  "0x0000000000000000000000000000000000000002": {"balance": "222222222"}
}

genesis.json文件创建完成时,你需要在所有的ionc节点执行初始化操作。

$ ionc init path/to/genesis.json
创建bootnode节点

当所有的节点都完成初始化时,你需要启动一个bootstrap节点,通过bootstrap节点可以帮助其他的节点之间进行相互发现,这样他们就可以通过网络连接在一起。

$ bootnode --genkey=boot.key
$ bootnode --nodekey=boot.key
启动节点

bootnode启动后,通过telnet <ip> <port>命令测试一下是否可以从外部访问bootnode,现在启动所有的ionc节点,在启动时加上--bootnodes选项。同时为了保存你的私有链上的数据,你需要创建一个datadir目录,并通过--datadir选项设置。

$ ionc --datadir=path/to/custom/data/folder --bootnodes=<bootnode-enode-url-from-above>

注意:从现在开始你的节点已经完全从主链网络上断开,现在你可以配置miner来处理交易,并创建新的区块

运行私有链miner

ionc网络中miner的算力是通过在保证金合约的保证金数量决定的,启动一个实例用于挖矿:

$ ionc <usual-flags> --mine --etherbase=0x0000000000000000000000000000000000000000

其中—etherbase设置为miner的账号地址,miner可以通过--targetgaslimit调整区块的gas limit--gasprice设置接受交易的gas price

Documentation

Overview

Package ionchain defines interfaces for interacting with ionchain.

Index

Constants

This section is empty.

Variables

View Source
var NotFound = errors.New("not found")

NotFound is returned by API methods if the requested item does not exist.

Functions

This section is empty.

Types

type CallMsg

type CallMsg struct {
	From     common.Address  // the sender of the 'transaction'
	To       *common.Address // the destination contract (nil for contract creation)
	Gas      *big.Int        // if nil, the call executes with near-infinite gas
	GasPrice *big.Int        // wei <-> gas exchange ratio
	Value    *big.Int        // amount of wei sent along with the call
	Data     []byte          // input data, usually an ABI-encoded contract method invocation
}

CallMsg contains parameters for contract calls.

type ChainReader

type ChainReader interface {
	BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
	BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
	HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error)
	HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
	TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error)
	TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error)

	// This method subscribes to notifications about changes of the head block of
	// the canonical chain.
	SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (Subscription, error)
}

ChainReader provides access to the blockchain. The methods in this interface access raw data from either the canonical chain (when requesting by block number) or any blockchain fork that was previously downloaded and processed by the node. The block number argument can be nil to select the latest canonical block. Reading block headers should be preferred over full blocks whenever possible.

The returned error is NotFound if the requested item does not exist.

type ChainStateReader

type ChainStateReader interface {
	BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error)
	StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error)
	CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error)
	NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error)
}

ChainStateReader wraps access to the state trie of the canonical blockchain. Note that implementations of the interface may be unable to return state values for old blocks. In many cases, using CallContract can be preferable to reading raw contract storage.

type ChainSyncReader

type ChainSyncReader interface {
	SyncProgress(ctx context.Context) (*SyncProgress, error)
}

ChainSyncReader wraps access to the node's current sync status. If there's no sync currently running, it returns nil.

type ContractCaller

type ContractCaller interface {
	CallContract(ctx context.Context, call CallMsg, blockNumber *big.Int) ([]byte, error)
}

A ContractCaller provides contract calls, essentially transactions that are executed by the EVM but not mined into the blockchain. ContractCall is a low-level method to execute such calls. For applications which are structured around specific contracts, the abigen tool provides a nicer, properly typed way to perform calls.

type FilterQuery

type FilterQuery struct {
	FromBlock *big.Int         // beginning of the queried range, nil means genesis block
	ToBlock   *big.Int         // end of the range, nil means latest block
	Addresses []common.Address // restricts matches to events created by specific contracts

	// The Topic list restricts matches to particular event topics. Each event has a list
	// of topics. Topics matches a prefix of that list. An empty element slice matches any
	// topic. Non-empty elements represent an alternative that matches any of the
	// contained topics.
	//
	// Examples:
	// {} or nil          matches any topic list
	// {{A}}              matches topic A in first position
	// {{}, {B}}          matches any topic in first position, B in second position
	// {{A}}, {B}}        matches topic A in first position, B in second position
	// {{A, B}}, {C, D}}  matches topic (A OR B) in first position, (C OR D) in second position
	Topics [][]common.Hash
}

FilterQuery contains options for contract log filtering.

type GasEstimator

type GasEstimator interface {
	EstimateGas(ctx context.Context, call CallMsg) (usedGas *big.Int, err error)
}

GasEstimator wraps EstimateGas, which tries to estimate the gas needed to execute a specific transaction based on the pending state. There is no guarantee that this is the true gas limit requirement as other transactions may be added or removed by miners, but it should provide a basis for setting a reasonable default.

type GasPricer

type GasPricer interface {
	SuggestGasPrice(ctx context.Context) (*big.Int, error)
}

GasPricer wraps the gas price oracle, which monitors the blockchain to determine the optimal gas price given current fee market conditions.

type LogFilterer

type LogFilterer interface {
	FilterLogs(ctx context.Context, q FilterQuery) ([]types.Log, error)
	SubscribeFilterLogs(ctx context.Context, q FilterQuery, ch chan<- types.Log) (Subscription, error)
}

LogFilterer provides access to contract log events using a one-off query or continuous event subscription.

Logs received through a streaming query subscription may have Removed set to true, indicating that the log was reverted due to a chain reorganisation.

type PendingContractCaller

type PendingContractCaller interface {
	PendingCallContract(ctx context.Context, call CallMsg) ([]byte, error)
}

PendingContractCaller can be used to perform calls against the pending state.

type PendingStateEventer

type PendingStateEventer interface {
	SubscribePendingTransactions(ctx context.Context, ch chan<- *types.Transaction) (Subscription, error)
}

A PendingStateEventer provides access to real time notifications about changes to the pending state.

type PendingStateReader

type PendingStateReader interface {
	PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error)
	PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error)
	PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
	PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
	PendingTransactionCount(ctx context.Context) (uint, error)
}

A PendingStateReader provides access to the pending state, which is the result of all known executable transactions which have not yet been included in the blockchain. It is commonly used to display the result of ’unconfirmed’ actions (e.g. wallet value transfers) initiated by the user. The PendingNonceAt operation is a good way to retrieve the next available transaction nonce for a specific account.

type Subscription

type Subscription interface {
	// Unsubscribe cancels the sending of events to the data channel
	// and closes the error channel.
	Unsubscribe()
	// Err returns the subscription error channel. The error channel receives
	// a value if there is an issue with the subscription (e.g. the network connection
	// delivering the events has been closed). Only one value will ever be sent.
	// The error channel is closed by Unsubscribe.
	Err() <-chan error
}

Subscription represents an event subscription where events are delivered on a data channel.

type SyncProgress

type SyncProgress struct {
	StartingBlock uint64 // Block number where sync began
	CurrentBlock  uint64 // Current block number where sync is at
	HighestBlock  uint64 // Highest alleged block number in the chain
	PulledStates  uint64 // Number of state trie entries already downloaded
	KnownStates   uint64 // Total number of state trie entries known about
}

SyncProgress gives progress indications when the node is synchronising with the ionchain network.

type TransactionReader

type TransactionReader interface {
	// TransactionByHash checks the pool of pending transactions in addition to the
	// blockchain. The isPending return value indicates whether the transaction has been
	// mined yet. Note that the transaction may not be part of the canonical chain even if
	// it's not pending.
	TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, isPending bool, err error)
	// TransactionReceipt returns the receipt of a mined transaction. Note that the
	// transaction may not be included in the current canonical chain even if a receipt
	// exists.
	TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
}

TransactionReader provides access to past transactions and their receipts. Implementations may impose arbitrary restrictions on the transactions and receipts that can be retrieved. Historic transactions may not be available.

Avoid relying on this interface if possible. Contract logs (through the LogFilterer interface) are more reliable and usually safer in the presence of chain reorganisations.

The returned error is NotFound if the requested item does not exist.

type TransactionSender

type TransactionSender interface {
	SendTransaction(ctx context.Context, tx *types.Transaction) error
}

TransactionSender wraps transaction sending. The SendTransaction method injects a signed transaction into the pending transaction pool for execution. If the transaction was a contract creation, the TransactionReceipt method can be used to retrieve the contract address after the transaction has been mined.

The transaction must be signed and have a valid nonce to be included. Consumers of the API can use package accounts to maintain local private keys and need can retrieve the next available nonce using PendingNonceAt.

Directories

Path Synopsis
Package accounts implements high level ionchain account management.
Package accounts implements high level ionchain account management.
abi
Package abi implements the ionchain ABI (Application Binary Interface).
Package abi implements the ionchain ABI (Application Binary Interface).
abi/bind
Package bind generates ionchain contract Go bindings.
Package bind generates ionchain contract Go bindings.
keystore
Package keystore implements encrypted storage of secp256k1 private keys.
Package keystore implements encrypted storage of secp256k1 private keys.
Package bmt provides a binary merkle tree implementation simple nonconcurrent reference implementation for hashsize segment based Binary Merkle tree hash on arbitrary but fixed maximum chunksize This implementation does not take advantage of any paralellisms and uses far more memory than necessary, but it is easy to see that it is correct.
Package bmt provides a binary merkle tree implementation simple nonconcurrent reference implementation for hashsize segment based Binary Merkle tree hash on arbitrary but fixed maximum chunksize This implementation does not take advantage of any paralellisms and uses far more memory than necessary, but it is easy to see that it is correct.
cmd
bootnode
bootnode runs a bootstrap node for the ionchain Discovery Protocol.
bootnode runs a bootstrap node for the ionchain Discovery Protocol.
evm
evm executes EVM code snippets.
evm executes EVM code snippets.
internal/browser
Package browser provides utilities for interacting with users' browsers.
Package browser provides utilities for interacting with users' browsers.
ionc
ionc is the official command-line client for ionchain.
ionc is the official command-line client for ionchain.
p2psim
p2psim provides a command-line client for a simulation HTTP API.
p2psim provides a command-line client for a simulation HTTP API.
rlpdump
rlpdump is a pretty-printer for RLP data.
rlpdump is a pretty-printer for RLP data.
utils
Package utils contains internal helper functions for go-ionchain commands.
Package utils contains internal helper functions for go-ionchain commands.
Package common contains various helper functions.
Package common contains various helper functions.
bitutil
Package bitutil implements fast bitwise operations.
Package bitutil implements fast bitwise operations.
compiler
Package compiler wraps the Solidity compiler executable (solc).
Package compiler wraps the Solidity compiler executable (solc).
hexutil
Package hexutil implements hex encoding with 0x prefix.
Package hexutil implements hex encoding with 0x prefix.
math
Package math provides integer math utilities.
Package math provides integer math utilities.
mclock
package mclock is a wrapper for a monotonic clock source
package mclock is a wrapper for a monotonic clock source
compression
rle
Package rle implements the run-length encoding used for ionchain data.
Package rle implements the run-length encoding used for ionchain data.
Package consensus implements different ionchain consensus engines.
Package consensus implements different ionchain consensus engines.
Package core implements the ionchain consensus protocol.
Package core implements the ionchain consensus protocol.
asm
Provides support for dealing with EVM assembly instructions (e.g., disassembling them).
Provides support for dealing with EVM assembly instructions (e.g., disassembling them).
bloombits
Package bloombits implements bloom filtering on batches of data.
Package bloombits implements bloom filtering on batches of data.
state
Package state provides a caching layer atop the ionchain state trie.
Package state provides a caching layer atop the ionchain state trie.
types
Package types contains data types related to ionchain consensus.
Package types contains data types related to ionchain consensus.
vm
Package vm implements the Ethereum Virtual Machine.
Package vm implements the Ethereum Virtual Machine.
vm/runtime
Package runtime provides a basic execution model for executing EVM code.
Package runtime provides a basic execution model for executing EVM code.
bn256
Package bn256 implements a particular bilinear group at the 128-bit security level.
Package bn256 implements a particular bilinear group at the 128-bit security level.
secp256k1
Package secp256k1 wraps the bitcoin secp256k1 C library.
Package secp256k1 wraps the bitcoin secp256k1 C library.
sha3
Package sha3 implements the SHA-3 fixed-output-length hash functions and the SHAKE variable-output-length hash functions defined by FIPS-202.
Package sha3 implements the SHA-3 fixed-output-length hash functions and the SHAKE variable-output-length hash functions defined by FIPS-202.
Package event deals with subscriptions to real-time events.
Package event deals with subscriptions to real-time events.
filter
Package filter implements event filters.
Package filter implements event filters.
internal
debug
Package debug interfaces Go runtime debugging facilities.
Package debug interfaces Go runtime debugging facilities.
guide
Package guide is a small test suite to ensure snippets in the dev guide work.
Package guide is a small test suite to ensure snippets in the dev guide work.
ioncapi
Package ethapi implements the general ionchain API functions.
Package ethapi implements the general ionchain API functions.
jsre
Package jsre provides execution environment for JavaScript.
Package jsre provides execution environment for JavaScript.
jsre/deps
Package deps contains the console JavaScript dependencies Go embedded.
Package deps contains the console JavaScript dependencies Go embedded.
web3ext
package web3ext contains ionc specific web3.js extensions.
package web3ext contains ionc specific web3.js extensions.
Package ionc implements the ionchain protocol.
Package ionc implements the ionchain 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 ionchain filtering system for block, transactions and log events.
Package filters implements an ionchain filtering system for block, transactions and log events.
Package ioncclient provides a client for the ionchain RPC API.
Package ioncclient provides a client for the ionchain RPC API.
Package ioncstats implements the network stats reporting service.
Package ioncstats implements the network stats reporting service.
les
Package les implements the Light ionchain Subprotocol.
Package les implements the Light ionchain Subprotocol.
flowcontrol
Package flowcontrol implements a client side flow control mechanism Package flowcontrol implements a client side flow control mechanism
Package flowcontrol implements a client side flow control mechanism Package flowcontrol implements a client side flow control mechanism
Package light implements on-demand retrieval capable state and chain objects for the ionchain Light Client.
Package light implements on-demand retrieval capable state and chain objects for the ionchain Light Client.
log
Package log15 provides an opinionated, simple toolkit for best-practice logging that is both human and machine readable.
Package log15 provides an opinionated, simple toolkit for best-practice logging that is both human and machine readable.
Package metrics provides general system and process level metrics collection.
Package metrics provides general system and process level metrics collection.
Package miner implements ionchain block creation and mining.
Package miner implements ionchain block creation and mining.
Package ionc contains the simplified mobile APIs to go-ionchain.
Package ionc contains the simplified mobile APIs to go-ionchain.
Package node sets up multi-protocol ionchain nodes.
Package node sets up multi-protocol ionchain nodes.
p2p
Package p2p implements the ionchain p2p network protocols.
Package p2p implements the ionchain p2p network protocols.
discover
Package discover implements the Node Discovery Protocol.
Package discover implements the Node Discovery Protocol.
discv5
Package discv5 implements the RLPx v5 Topic Discovery Protocol.
Package discv5 implements the RLPx v5 Topic Discovery Protocol.
nat
Package nat provides access to common network port mapping protocols.
Package nat provides access to common network port mapping protocols.
netutil
Package netutil contains extensions to the net package.
Package netutil contains extensions to the net package.
Package rlp implements the RLP serialization format.
Package rlp implements the RLP serialization format.
Package rpc provides access to the exported methods of an object across a network or other I/O connection.
Package rpc provides access to the exported methods of an object across a network or other I/O connection.
Package trie implements Merkle Patricia Tries.
Package trie implements Merkle Patricia Tries.
whisper
whisperv2
Package whisper implements the Whisper PoC-1.
Package whisper implements the Whisper PoC-1.
whisperv5
Package whisper implements the Whisper protocol (version 5).
Package whisper implements the Whisper protocol (version 5).
whisperv6
Package whisper implements the Whisper protocol (version 6).
Package whisper implements the Whisper protocol (version 6).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳