ethereum

package module
v0.0.0-...-cd7b9ce Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2019 License: Apache-2.0 Imports: 5 Imported by: 0

README

Go DX

Welcome to the official Go implementation of DxChain protocol!

CircleCI Go Report Card Coverage Golang release License Open Source Love

gdx program is built on top of the DxChain protocol. DxChain is a blockchain based P2P network for data storage. The core feature is that user can upload data to the network as storage client or provide data storage service for other peers in the network as a storage host. In addition, DxChain also contains features that are supported by other blockchain, such as distributed ledger and smart contracts.

Table of contents:

Section 1. Getting Started

1.1. Prerequisites

NOTE: currently, we only support MacOS and Linux. Windows is not supported yet.

1.1.1. Golang

To build the program from the source code, Golang 1.11 is required. Please follow this link to install Golang on your computer. To check if the program is installed successfully, use the following command:

$ go version
1.1.2. Xcode (for macOS only)

Xcode can be installed from the App Store

1.1.3. Go Vendor

Go Vendor is a package management tool used for this project. It can be installed via:

$ go get -u -v github.com/kardianos/govendor
1.1.4. Docker (Optional)

The installation of Docker is optional. Docker is used for cross-platform build meaning if you want to build linux version of gdx on your MacBook, you have to install Docker. Please follow the following installation guide:

Docker Installation Guide for Mac

Docker Installation Guide for Linux

1.2. Build from source

1.2.1. Clone Project
$ mkdir -p $GOPATH/src/github.com/DxChainNetwork
$ cd $GOPATH/src/github.com/DxChainNetwork
$ git clone git@github.com:DxChainNetwork/godx.git

NOTE: please checkout to the latest release branch by using the following command:

$ git checkout release0.8.0
1.2.2. Packages Installation

Required packages can be installed via go vendor,

$ cd $GOPATH/src/github.com/DxChainNetwork/godx
$ govendor sync -v

All packages saved in the godx/vendor/vendor.json will be downloaded. Please wait for download to finish.

1.2.3. Build

Build for your operating system

$ make gdx
1.2.4. Add gdx to path

Add gdx executable to your path by going through the following commands:

$ cd $GOPATH/src/github.com/DxChainNetwork/godx/build/bin
$ export PATH=$PATH:$(pwd)

For each terminal you open, you have to run the above commands. For more advanced users, you can add the export statement in the shell init file like ~/.bash_profile or ~/.zshrc

Section 2. Running gdx

A node in the DxChain Network can become the following three roles

  • Storage Client
  • Storage Host
  • Miner

NOTE: each node can become a miner regardless of its role

To run the node that is capable of performing all operations, use the following command:

$ gdx

2.1. Run as miner

If you do not intend to become neither a storage client nor a storage host, you can start the program by running the following command in the terminal

$ gdx --role miner

2.2. Run as storage client

By paying DX tokens to storage hosts, storage client is able to rent storage space and store files in the DX network safely and securely. When needed, storage client can download those files from the network.

If you intend to become a storage client only, run the following command in the terminal

$ gdx --role client

2.3. Run as storage host

Storage host serves as a storage service provider, gaining profit for storing data uploaded by the storage client.

If you intend to become a storage host only, run the following command in the terminal

$ gdx --role host

Section 3. Tutorial

The basic tutorial can be found here

Section 4. Basic Console Commands

Once the gdx program is up and running, you can use the following command to open the gdx console to perform different operations, such as mining, creating storage contract, uploading files, and etc.

$ gdx attach

4.1. Account

4.1.1. personal.newAccount
Usage Description
personal.newAccount() Generate a new account

Example:

> personal.newAccount()
Passphrase:
Repeat passphrase:
"0x1ec76840382bfde5ec6a03dadd71947d842577e3"
4.1.2. eth.accounts
Usage Description
eth.accounts Retrieve all accounts

Example

> eth.accounts
["0x1ec76840382bfde5ec6a03dadd71947d842577e3"]
4.1.3. personal.unlockAccount
Usage Description
personal.unlockAccount(address, passphrase, duration) Unlock the account

NOTE: To send transactions, the account must be unlocked. To use storage services, the account must be unlocked permanently because the transactions are made automatically.

The duration is measured in terms of seconds with 300 seconds as its default value. To make an account be permanently unlocked, set the duration to 0.

Example:

> personal.unlockAccount(eth.accounts[0], "", 0)
true

which is equivalent to

> personal.unlockAccount("0x1ec76840382bfde5ec6a03dadd71947d842577e3", "", 0)
true
4.1.4. eth.getBalance
Usage Description
eth.getBalance(address) Check the account balance

Example:

> eth.getBalance(eth.accounts[0])
0

4.2. Mining

4.2.1. miner.start
Usage Description
miner.start() Start mining

Example:

> miner.start()
null
4.2.2. miner.stop
Usage Description
miner.stop() Stop mining

Example:

> miner.stop()
null
4.2.3. eth.mining
Usage Description
eth.mining Check if the node is mining

Example:

> eth.mining
false

4.3. Node

4.3.1. eth.blockHeight
Usage Description
eth.blockNumber Current block height

Example:

> eth.blockNumber
12
4.3.2. admin.peers
Usage Description
admin.peers Number of nodes connected

Example:

> admin.peers
[{
    caps: ["eth/63", "eth/64"],
    enode: "enode://fdac7145904eba296b91b21dbc2fb75c114ab3a4e2cf5076ea95ae278e142d9b40da8b7c061beb179523781b8d4207de69266862090ac7b24e3afa62e5bb9629@35.164.203.139:36000",
    id: "578c262796d0c566e968cef804e502bbf16b8ae27af2bf8ac3b7cc10cfbd04ea",
    name: "gdx/v0.7.0-unstable-b710fae7/linux-amd64/go1.11.1",
    network: {
      inbound: false,
      localAddress: "192.168.0.109:50855",
      remoteAddress: "35.164.203.139:36000",
      static: true,
      trusted: false
    },
    protocols: {
      eth: {
        difficulty: 1048576,
        head: "0xfc27079037c07c16646518b7f5067ae5e07df0657c2e949ed84e0d6e2e4f7577",
        version: 64
      }
    }
}]
4.3.3. admin.nodeInfo
Usage Description
admin.nodeInfo Detailed local node information

Example:

> admin.nodeInfo
{
  enode: "enode://72c61072be163425f780ce1c54bf62835116bf471e8c6551dfb5bdb16128ab546c3bab8fc0f820e090d5cb523ca3ad2bc1d88435e6ce3b1e095c9893ff5ac4a9@192.168.7.99:36000",
  enr: "0xf89cb8403553c1046074ce413afdcd70e42429df7570c8c45855666b8f0a06af071503036e25b748834d8e7b3718dd50d02128a041b6fc1ad84b165019724d92e78a47220483636170ccc5836574683fc5836574684082696482763482697084c0a8076389736563703235366b31a10372c61072be163425f780ce1c54bf62835116bf471e8c6551dfb5bdb16128ab5483746370828ca083756470828ca0",
  id: "6ae04b801cf80310b48a10b55fbb478bfb977e159e96ea3b0a9d0a52ae8164ec",
  ip: "192.168.7.99",
  listenAddr: "[::]:36000",
  name: "gdx/v0.7.0-unstable-9437f7c7/darwin-amd64/go1.11.12",
  ports: {
    discovery: 36000,
    listener: 36000
  },
  protocols: {
    eth: {
      config: {
        byzantiumBlock: 0,
        chainId: 1,
        eip150Block: 0,
        eip150Hash: "0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d",
        eip155Block: 0,
        eip158Block: 0,
        ethash: {},
        homesteadBlock: 0
      },
      difficulty: 13055408,
      genesis: "0xfc27079037c07c16646518b7f5067ae5e07df0657c2e949ed84e0d6e2e4f7577",
      head: "0x14eaa4d7901af0b65fb815ee8623c0ffd11f762a39f73a6b887284480c2ce6c5",
      network: 1
    }
  }
}

4.4. StorageClient

NOTE: To be able to use the following commands, the storage client module must be enabled when you start the gdx program. Otherwise, error will be returned.

4.4.1. sclient.host.ls
Usage Description
sclient.host.ls Retrieve the available storage hosts

Example:

> sclient.host.ls
[{
    acceptingContracts: true,
    baseRPCPrice: 100000000000,
    contractPrice: 50000000000000000,
    deposit: 1000,
    downloadBandwidthPrice: 100000000,
    enodeid: "578c262796d0c566e968cef804e502bbf16b8ae27af2bf8ac3b7cc10cfbd04ea",
    enodeurl: "enode://fdac7145904eba296b91b21dbc2fb75c114ab3a4e2cf5076ea95ae278e142d9b40da8b7c061beb179523781b8d4207de69266862090ac7b24e3afa62e5bb9629@35.164.203.139:36000",
    filtered: false,
    firstseen: 15,
    historicdowntime: 0,
    historicfailedinteractions: 0,
    historicsuccessfulinteractions: 0,
    historicuptime: 0,
    ip: "35.164.203.139",
    ipnetwork: "35.164.203.0/24",
    lasthistoricupdate: 0,
    lastipnetworkchange: "2019-08-01T11:17:24.527496-07:00",
    maxDeposit: 9000000000000000000,
    maxDownloadBatchSize: 17825792,
    maxDuration: 172800,
    maxReviseBatchSize: 17825792,
    nodepubkey: "BP2scUWQTropa5GyHbwvt1wRSrOk4s9QduqVrieOFC2bQNqLfAYb6xeVI3gbjUIH3mkmaGIJCseyTjr6YuW7lik=",
    paymentAddress: "0x3c15440003892ad2a755459a66ccb3197234d7e2",
    recentfailedinteractions: 0,
    recentsuccessfulinteractions: 1,
    remainingStorage: 0,
    scanrecords: [{
        success: true,
        timestamp: "2019-08-01T11:07:24.576446-07:00"
    }, {
        success: true,
        timestamp: "2019-08-01T11:17:24.576447-07:00"
    }],
    sectorAccessPrice: 10000000000000,
    sectorSize: 4194304,
    storagePrice: 1000,
    totalStorage: 0,
    uploadBandwidthPrice: 10000000,
    version: "1.0.1",
    windowSize: 1200
}]

NOTE: length can be attach to the end of the command to get number of storage hosts that the client learnt from the network. If error returned, meaning that there are no hosts available.

> sclient.host.ls.length
1
4.4.2. sclient.paymentAddr
Usage Description
sclient.paymentAddr Retrieve the account used for storage service

NOTE: By default, the first account user generated will be used as the storage service payment address. All the storage cost will be spent from this account.

Example:

> sclient.paymentAddr
"0x792e6b278ef8ec562b9530bf5df70064a55c3744"
4.4.3. sclient.setPaymentAddr
Usage Description
sclient.setPaymentAddr(address) Register the account address to be used for the storage service

Example:

> sclient.setPaymentAddr(eth.accounts[1])
true
4.4.4. sclient.setConfig
Usage Description
sclient.setConfig(config) Configure the client settings used for contract creation and etc.

The following is a list of supported configuration:

Config Type Description
period Duration file storage duration
hosts Number number of storage hosts that the client want to sign contract with
renew Duration time that the contract will automatically be renewed
fund Currency amount of money the client wants to be used for the storage service within one period

NOTE: units must be included when config the storage client configuration, please refer to Units for available units

Before setting the client config, please make sure that you have enough balance in your payment account. Please refer to 4.1.4. eth.getBalance to check balance.

In addition, the payment account must be permanently unlocked first. To unlock the account, please refer to 4.1.3. personal.unlockAccount

Example:

> sclient.setConfig({"fund":"1dx", "hosts":"3", "period":"2d", "renew":"36h"})
"Successfully set the storage client setting"

the following command uses the default settings

> sclient.setConfig({})
"Successfully set the storage client setting"

Default Setting:

Fund:   1 DX
Hosts:  3 Hosts
Renew:  36 Hours
Period: 2 Days

NOTE: once the client configuration is settled, the contracts will be automatically created.

4.4.5. sclient.config
Usage Description
sclient.config Current storage client settings used for the storage service

Example:

> sclient.config
{
  IP Violation Check Status: "Disabled: storage client can sign contract with storage hosts from the same network",
  Max Download Speed: "Unlimited",
  Max Upload Speed: "Unlimited",
  RentPayment Setting: {
    Expected Download: "578703 B/block",
    Expected Redundancy: "2 Copies",
    Expected Storage: "976562500 KiB",
    Expected Upload: "1157407 B/block",
    Fund: "1 DX",
    Number of Storage Hosts: "3 Hosts",
    Renew Time: "12 Hour(s)",
    Storage Time: "3 Day(s)"
  }
}
4.4.6. sclient.contracts
Usage Description
sclient.contracts Active storage contracts signed by the storage client

Example:

> sclient.contracts
[{
    AbleToRenew: true,
    AbleToUpload: true,
    Canceled: false,
    ContractID: "0x527924bc4e7316382601662527dbc327a7854918bed725522a633bd383257df0",
    HostID: "578c262796d0c566e968cef804e502bbf16b8ae27af2bf8ac3b7cc10cfbd04ea"
}]

to get the number of contracts that the storage client signed

> sclient.contracts.length
1
4.4.7 sclient.contract
Usage Description
sclient.contract(contractID) Detailed contract information based on the provided contract ID

Example:

> sclient.contract("0x527924bc4e7316382601662527dbc327a7854918bed725522a633bd383257df0")
{
  Canceled: "the contract is still active",
  ContractBalance: "0.06111111111111111 DX",
  ContractFee: "0.05 DX",
  DownloadCost: "0 Camel",
  EndHeight: "17843 b",
  EnodeID: "578c262796d0c566e968cef804e502bbf16b8ae27af2bf8ac3b7cc10cfbd04ea",
  GasCost: "0 Camel",
  ID: "0x527924bc4e7316382601662527dbc327a7854918bed725522a633bd383257df0",
  LatestContractRevision: {
    Signatures: ["BUl14sSzxbciCt4Wg/9ouy80qygRRQIKbDwGOfG/MxtnDh5m2b+ENR+hqCglInyTDdsO6/vqwoaimFves2jUMgA=", "Seh6lPZTnp8yI0bjc3x44gIgnu+dcgj4aonMV6gF0Ap21qCMMhqino2ueghtVbZyILANAkhdbwW36TgggL0g1gA="],
    newfilemerkleroot: "0x0000000000000000000000000000000000000000000000000000000000000000",
    newfilesize: 0,
    newmissedproofoutputs: [{
        Address: "0x792e6b278ef8ec562b9530bf5df70064a55c3744",
        Value: 61111111111111110
    }, {
        Address: "0x3c15440003892ad2a755459a66ccb3197234d7e2",
        Value: 111111111111111000
    }],
    newrevisionnumber: 1,
    newunlockhash: "0x2f58aa5ab70e1d6844d829948070b34b5f4bcf93cdc66dac72bf8e3b6ae56f26",
    newvalidproofoutputs: [{
        Address: "0x792e6b278ef8ec562b9530bf5df70064a55c3744",
        Value: 61111111111111110
    }, {
        Address: "0x3c15440003892ad2a755459a66ccb3197234d7e2",
        Value: 111111111111111000
    }],
    newwindowend: 19043,
    newwindowstart: 17843,
    parentid: "0x527924bc4e7316382601662527dbc327a7854918bed725522a633bd383257df0",
    unlockconditions: {
      paymentaddress: ["0x792e6b278ef8ec562b9530bf5df70064a55c3744", "0x3c15440003892ad2a755459a66ccb3197234d7e2"],
      signaturesrequired: 2
    }
  },
  RenewAbility: "the contract can be used for data downloading",
  StartHeight: "563 b",
  StorageCost: "0 Camel",
  TotalCost: "0.1111111111111111 DX",
  UploadAbility: "the contract can be used for data uploading",
  UploadCost: "0 Camel"
}
4.4.8 sclient.upload
Usage Description
sclient.upload(source, destination) Upload the file specified by the storage client to storage hosts

NOTE: both source and destination path must be absolute path

Example:

> sclient.upload("/Users/mzhang/upload1.file", "download.file")
"success"
4.4.9 sclient.download
Usage Description
sclient.download(source, destination) Download the file specified by the client to the local machine

NOTE: both source and destination path must be absolute path

Example:

> sclient.download("download.file", "download.file")
"File downloaded successfully"
4.4.10 sclient.file.ls
Usage Description
sclient.file.ls Files uploaded by the storage client

Example:

> sclient.file.ls
[{
    dxpath: "download.file",
    status: "healthy",
    uploadProgress: 100
}]
4.4.11 sclient.file.rename
Usage Description
sclient.file.rename(oldName, newName) Rename the file uploaded

Example:

> sclient.file.rename("download.file", "newfile.file")
"File download.file renamed to newfile.file"
4.4.12 sclient.file.delete
Usage Description
sclient.file.delete(file) Delete the file

Example:

> sclient.file.delete("newfile.file")
"File newfile.file deleted"

4.5. StorageHost

NOTE: To be able to use the following commands, the storage host module must be enabled when you start the gdx program. Otherwise, error will be returned.

4.5.1. shost.config
Usage Description
shost.config Storage host configurations used for storage service

NOTE: if the configuration is not set, default configuration will be used.

Example:

> shost.config
{
  acceptingContracts: "false",
  baseRPCPrice: "100 Gcamel",
  contractPrice: "0.05 DX/contract",
  deposit: "1000 Camel/byte/block",
  depositBudget: "10000 DX/contract",
  downloadBandwidthPrice: "0.1 Gcamel/byte",
  maxDeposit: "100 DX",
  maxDownloadBatchSize: "17 MiB/block",
  maxDuration: "1 Month(s)",
  maxReviseBatchSize: "17 MiB/block",
  paymentAddress: "0x0000000000000000000000000000000000000000",
  sectorAccessPrice: "10000 Gcamel/sector",
  storagePrice: "1000 Camel/byte/block",
  uploadBandwidthPrice: "0.01 Gcamel/byte",
  windowSize: "5 Hour(s)"
}
4.5.2. shost.setConfig
Usage Description
shost.setConfig(config) Set the storage host configurations

The following is a list of available configurations:

Config Type Description
acceptingContracts Boolean whether the host accepts new contracts
maxDuration Duration max duration for a storage contract
deposit Currency deposit price per block per byte
contractPrice Currency price that client must be paid when creating contract
downloadPrice Currency download bandwidth price per byte
uploadPrice Currency upload bandwidth price per byte
storagePrice Currency storage price per block per byte
depositBudget Currency the maximum deposit for all contracts
maxDeposit Currency the max deposit for a single storage contract
paymentAddress Address account address used for the storage service

NOTE for available units, please refer to Units

Example:

> shost.setConfig({"acceptingContracts":"true", "deposit":"2gcamel"})
"Successfully set the host config"
4.5.3. shost.paymentAddr
Usage Description
shost.paymentAddr Retrieve the account used for storage service

NOTE: By default, the first account user generated will be used as the storage service payment address. All the storage cost will be spent from this account. All the profit will be saved in this account as well

Example:

> shost.paymentAddr
"0x792e6b278ef8ec562b9530bf5df70064a55c3744"
4.5.4. shost.announce
Usage Description
shost.announce Announce the node as storage host node

NOTE: there is no limitation on number of announcements. However, each announcement will cost a small amount of transaction fee. Before making announcement, please make sure that you have enough balance in your payment account. Please refer to 4.1.4. eth.getBalance to check balance.

In addition, the payment account must be permanently unlocked first. To unlock the account, please refer to 4.1.3. personal.unlockAccount

Example:

> shost.announce()
"Announcement transaction: 0x3e3466bab9476d997ab4fc8a8a68c0893ecd373646e6bbc98137cd343b169881"

to check the transaction detail, use the following command

> eth.getTransaction("0x3e3466bab9476d997ab4fc8a8a68c0893ecd373646e6bbc98137cd343b169881")
{
  blockHash: "0xcd3f13a85c129ebc4d77d4b3c65db7a37921e3c16d40e816daf0cacb32e6191f",
  blockNumber: 1745,
  from: "0x792e6b278ef8ec562b9530bf5df70064a55c3744",
  gas: 90000,
  gasPrice: 1000000000,
  hash: "0x3e3466bab9476d997ab4fc8a8a68c0893ecd373646e6bbc98137cd343b169881",
  input: "0xf8e0b89b656e6f64653a2f2f3936333438326236643764353433623335316439396464633833373031336166336239646438363230346465623930313165306663363561656163383039666137353833663061633063323261366262633364383861343262346430346266373262326265373635653039653164643763313664396237646432623563336166403139322e3136382e372e39393a3336303030b8415978fcb1e3d366450f1dfde82a8aab4e1dc5c8675f79314dc0a6f13ebfe007bd73e5e16c92323f32d073e09404889ad8939c3b0e35b3bfa536b80a3d93dc645a00",
  nonce: 2,
  r: "0xc579aa9e6bbcbf7e466c39d8d077a5b9d5c1de73f9a4a598689c88eb6869ae74",
  s: "0xf980116eb2a47fc7f18054fd87bcdbef8dc8f67b7eb2b17a283d744e2704951",
  to: "0x0000000000000000000000000000000000000009",
  transactionIndex: 0,
  v: "0x25",
  value: 0
}
4.5.5. shost.folder.add
Usage Description
shost.folder.add(path, size) Allocate disk space for saving data uploaded by the storage client

NOTE: for supported storage size unit, please refer to Units

Example:

> shost.folder.add("~/temp", "1gb")
"successfully added the storage folder"
4.5.6. shost.folder.ls
Usage Description
shost.folder.ls Information of folders created for storing data uploaded by client

Example:

> shost.folder.ls
[{
    path: "/Users/mzhang/temp",
    totalSectors: 238,
    usedSectors: 0
}]
4.5.7. shost.folder.resize
Usage Description
shost.folder.resize(folder, size) Resize the disk space allocated for saving data uploaded by the storage client

Example:

> shost.folder.resize("/Users/mzhang/temp", "500mb")
"successfully resize the storage folder"
4.5.8. shost.folder.delete
Usage Description
shost.folder.delete(folder) Free up the disk space used for saving data uploaded by the storage client

NOTE: this command will not delete the directory created on your local machine

Example:

> shost.folder.delete("/Users/mzhang/temp")
"successfully delete the storage folder"

License

GoDx is released under the Apache 2.0 License. See LICENSE for more information.

Appendix

Units

Duration:

Duration/Time Representation
b block
h hour
d day
w week
m month
y year

Currency:

Currency Transfer Rate
camel smallest currency unit
Gcamel 1e9 camel
DX 1e18 camel

Storage Size:

Storage Size Representation
kb 1e3 bytes
mb 1e6 bytes
gb 1e9 bytes
tb 1e12 bytes
kib 1 << 10 bytes
mib 1 << 20 bytes
gib 1 << 30 bytes
tib 1 << 40 bytes

Contact

Thank you so much for your support and your confidence in this project. If you have any question, please do not hesitated to contact us via support@dxchain.com

Documentation

Overview

Package ethereum defines interfaces for interacting with Ethereum.

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      uint64          // if 0, 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 {
	BlockHash *common.Hash     // used by eth_getLogs, return logs only from block with this hash
	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) (uint64, 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 Ethereum 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 Ethereum account management.
Package accounts implements high level Ethereum account management.
keystore
Package keystore implements encrypted storage of secp256k1 private keys.
Package keystore implements encrypted storage of secp256k1 private keys.
cmd
gdx command
geth is the official command-line client for Ethereum.
geth is the official command-line client for Ethereum.
internal/browser
Package browser provides utilities for interacting with users' browsers.
Package browser provides utilities for interacting with users' browsers.
utils
Package utils contains internal helper functions for go-ethereum commands.
Package utils contains internal helper functions for go-ethereum 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.
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
threadmanager
Package ThreadManager provides a utility for performing organized clean shutdown and quick shutdown of long running groups of threads, such as networking threads, background threads, or resources like databases.
Package ThreadManager provides a utility for performing organized clean shutdown and quick shutdown of long running groups of threads, such as networking threads, background threads, or resources like databases.
Package consensus implements different Ethereum consensus engines.
Package consensus implements different Ethereum consensus engines.
clique
Package clique implements the proof-of-authority consensus engine.
Package clique implements the proof-of-authority consensus engine.
ethash
Package ethash implements the ethash proof-of-work consensus engine.
Package ethash implements the ethash proof-of-work consensus engine.
Package core implements the Ethereum consensus protocol.
Package core implements the Ethereum consensus protocol.
bloombits
Package bloombits implements bloom filtering on batches of data.
Package bloombits implements bloom filtering on batches of data.
rawdb
Package rawdb contains a collection of low level database accessors.
Package rawdb contains a collection of low level database accessors.
state
Package state provides a caching layer atop the Ethereum state trie.
Package state provides a caching layer atop the Ethereum state trie.
types
Package types contains data types related to Ethereum consensus.
Package types contains data types related to Ethereum 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 the Optimal Ate pairing over a 256-bit Barreto-Naehrig curve.
Package bn256 implements the Optimal Ate pairing over a 256-bit Barreto-Naehrig curve.
bn256/cloudflare
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.
bn256/google
Package bn256 implements a particular bilinear group.
Package bn256 implements a particular bilinear group.
ed25519
Package ed25519 implements the Ed25519 signature algorithm.
Package ed25519 implements the Ed25519 signature algorithm.
secp256k1
Package secp256k1 wraps the bitcoin secp256k1 C library.
Package secp256k1 wraps the bitcoin secp256k1 C library.
eth
Package eth implements the Ethereum protocol.
Package eth implements the Ethereum 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.
tracers
Package tracers is a collection of JavaScript transaction tracers.
Package tracers is a collection of JavaScript transaction tracers.
tracers/internal/tracers
Package tracers contains the actual JavaScript tracer assets.
Package tracers contains the actual JavaScript tracer assets.
Package ethclient provides a client for the Ethereum RPC API.
Package ethclient provides a client for the Ethereum RPC API.
Package ethstats implements the network stats reporting service.
Package ethstats implements the network stats reporting service.
Package event deals with subscriptions to real-time events.
Package event deals with subscriptions to real-time events.
internal
debug
Package debug interfaces Go runtime debugging facilities.
Package debug interfaces Go runtime debugging facilities.
ethapi
Package ethapi implements the general Ethereum API functions.
Package ethapi implements the general Ethereum API functions.
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.
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 geth specific web3.js extensions.
package web3ext contains geth specific web3.js extensions.
les
Package les implements the Light Ethereum Subprotocol.
Package les implements the Light Ethereum Subprotocol.
flowcontrol
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 Ethereum Light Client.
Package light implements on-demand retrieval capable state and chain objects for the Ethereum Light Client.
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.
Go port of Coda Hale's Metrics library
Go port of Coda Hale's Metrics library
exp
Hook go-metrics into expvar on any /debug/metrics request, load all vars from the registry into expvar, and execute regular expvar handler
Hook go-metrics into expvar on any /debug/metrics request, load all vars from the registry into expvar, and execute regular expvar handler
Package miner implements Ethereum block creation and mining.
Package miner implements Ethereum block creation and mining.
Package node sets up multi-protocol Ethereum nodes.
Package node sets up multi-protocol Ethereum nodes.
p2p
Package p2p implements the Ethereum p2p network protocols.
Package p2p implements the Ethereum 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.
enr
Package enr implements Ethereum Node Records as defined in EIP-778.
Package enr implements Ethereum Node Records as defined in EIP-778.
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.
protocols
Package protocols is an extension to p2p.
Package protocols is an extension to p2p.
simulations
Package simulations simulates p2p networks.
Package simulations simulates p2p networks.
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.
storageclient/memorymanager
Package memorymanager implements the storage client memory management methods
Package memorymanager implements the storage client memory management methods

Jump to

Keyboard shortcuts

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