diff --git a/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/nil.go b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/nil.go
new file mode 100644
index 000000000..54b222f1f
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/nil.go
@@ -0,0 +1,57 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package backends
+
+import (
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/accounts/abi/bind"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core/types"
+ "golang.org/x/net/context"
+)
+
+// This nil assignment ensures compile time that nilBackend implements bind.ContractBackend.
+var _ bind.ContractBackend = (*nilBackend)(nil)
+
+// nilBackend implements bind.ContractBackend, but panics on any method call.
+// Its sole purpose is to support the binding tests to construct the generated
+// wrappers without calling any methods on them.
+type nilBackend struct{}
+
+func (*nilBackend) ContractCall(context.Context, common.Address, []byte, bool) ([]byte, error) {
+ panic("not implemented")
+}
+func (*nilBackend) EstimateGasLimit(context.Context, common.Address, *common.Address, *big.Int, []byte) (*big.Int, error) {
+ panic("not implemented")
+}
+func (*nilBackend) HasCode(context.Context, common.Address, bool) (bool, error) {
+ panic("not implemented")
+}
+func (*nilBackend) SuggestGasPrice(context.Context) (*big.Int, error) { panic("not implemented") }
+func (*nilBackend) PendingAccountNonce(context.Context, common.Address) (uint64, error) {
+ panic("not implemented")
+}
+func (*nilBackend) SendTransaction(context.Context, *types.Transaction) error {
+ panic("not implemented")
+}
+
+// NewNilBackend creates a new binding backend that can be used for instantiation
+// but will panic on any invocation. Its sole purpose is to help testing.
+func NewNilBackend() bind.ContractBackend {
+ return new(nilBackend)
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/remote.go b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/remote.go
new file mode 100644
index 000000000..4793143e4
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/remote.go
@@ -0,0 +1,260 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package backends
+
+import (
+ "encoding/json"
+ "fmt"
+ "math/big"
+ "sync"
+ "sync/atomic"
+
+ "github.com/ethereum/go-ethereum/accounts/abi/bind"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core/types"
+ "github.com/ethereum/go-ethereum/rlp"
+ "github.com/ethereum/go-ethereum/rpc"
+ "golang.org/x/net/context"
+)
+
+// This nil assignment ensures compile time that rpcBackend implements bind.ContractBackend.
+var _ bind.ContractBackend = (*rpcBackend)(nil)
+
+// rpcBackend implements bind.ContractBackend, and acts as the data provider to
+// Ethereum contracts bound to Go structs. It uses an RPC connection to delegate
+// all its functionality.
+//
+// Note: The current implementation is a blocking one. This should be replaced
+// by a proper async version when a real RPC client is created.
+type rpcBackend struct {
+ client rpc.Client // RPC client connection to interact with an API server
+ autoid uint32 // ID number to use for the next API request
+ lock sync.Mutex // Singleton access until we get to request multiplexing
+}
+
+// NewRPCBackend creates a new binding backend to an RPC provider that can be
+// used to interact with remote contracts.
+func NewRPCBackend(client rpc.Client) bind.ContractBackend {
+ return &rpcBackend{
+ client: client,
+ }
+}
+
+// request is a JSON RPC request package assembled internally from the client
+// method calls.
+type request struct {
+ JSONRPC string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
+ ID int `json:"id"` // Auto incrementing ID number for this request
+ Method string `json:"method"` // Remote procedure name to invoke on the server
+ Params []interface{} `json:"params"` // List of parameters to pass through (keep types simple)
+}
+
+// response is a JSON RPC response package sent back from the API server.
+type response struct {
+ JSONRPC string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
+ ID int `json:"id"` // Auto incrementing ID number for this request
+ Error *failure `json:"error"` // Any error returned by the remote side
+ Result json.RawMessage `json:"result"` // Whatever the remote side sends us in reply
+}
+
+// failure is a JSON RPC response error field sent back from the API server.
+type failure struct {
+ Code int `json:"code"` // JSON RPC error code associated with the failure
+ Message string `json:"message"` // Specific error message of the failure
+}
+
+// request forwards an API request to the RPC server, and parses the response.
+//
+// This is currently painfully non-concurrent, but it will have to do until we
+// find the time for niceties like this :P
+func (b *rpcBackend) request(ctx context.Context, method string, params []interface{}) (json.RawMessage, error) {
+ b.lock.Lock()
+ defer b.lock.Unlock()
+
+ if ctx == nil {
+ ctx = context.Background()
+ }
+
+ // Ugly hack to serialize an empty list properly
+ if params == nil {
+ params = []interface{}{}
+ }
+ // Assemble the request object
+ reqID := int(atomic.AddUint32(&b.autoid, 1))
+ req := &request{
+ JSONRPC: "2.0",
+ ID: reqID,
+ Method: method,
+ Params: params,
+ }
+ if err := b.client.Send(req); err != nil {
+ return nil, err
+ }
+ res := new(response)
+ errc := make(chan error, 1)
+ go func() {
+ errc <- b.client.Recv(res)
+ }()
+ select {
+ case err := <-errc:
+ if err != nil {
+ return nil, err
+ }
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ if res.Error != nil {
+ if res.Error.Message == bind.ErrNoCode.Error() {
+ return nil, bind.ErrNoCode
+ }
+ return nil, fmt.Errorf("remote error: %s", res.Error.Message)
+ }
+ return res.Result, nil
+}
+
+// HasCode implements ContractVerifier.HasCode by retrieving any code associated
+// with the contract from the remote node, and checking its size.
+func (b *rpcBackend) HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error) {
+ // Execute the RPC code retrieval
+ block := "latest"
+ if pending {
+ block = "pending"
+ }
+ res, err := b.request(ctx, "eth_getCode", []interface{}{contract.Hex(), block})
+ if err != nil {
+ return false, err
+ }
+ var hex string
+ if err := json.Unmarshal(res, &hex); err != nil {
+ return false, err
+ }
+ // Convert the response back to a Go byte slice and return
+ return len(common.FromHex(hex)) > 0, nil
+}
+
+// ContractCall implements ContractCaller.ContractCall, delegating the execution of
+// a contract call to the remote node, returning the reply to for local processing.
+func (b *rpcBackend) ContractCall(ctx context.Context, contract common.Address, data []byte, pending bool) ([]byte, error) {
+ // Pack up the request into an RPC argument
+ args := struct {
+ To common.Address `json:"to"`
+ Data string `json:"data"`
+ }{
+ To: contract,
+ Data: common.ToHex(data),
+ }
+ // Execute the RPC call and retrieve the response
+ block := "latest"
+ if pending {
+ block = "pending"
+ }
+ res, err := b.request(ctx, "eth_call", []interface{}{args, block})
+ if err != nil {
+ return nil, err
+ }
+ var hex string
+ if err := json.Unmarshal(res, &hex); err != nil {
+ return nil, err
+ }
+ // Convert the response back to a Go byte slice and return
+ return common.FromHex(hex), nil
+}
+
+// PendingAccountNonce implements ContractTransactor.PendingAccountNonce, delegating
+// the current account nonce retrieval to the remote node.
+func (b *rpcBackend) PendingAccountNonce(ctx context.Context, account common.Address) (uint64, error) {
+ res, err := b.request(ctx, "eth_getTransactionCount", []interface{}{account.Hex(), "pending"})
+ if err != nil {
+ return 0, err
+ }
+ var hex string
+ if err := json.Unmarshal(res, &hex); err != nil {
+ return 0, err
+ }
+ nonce, ok := new(big.Int).SetString(hex, 0)
+ if !ok {
+ return 0, fmt.Errorf("invalid nonce hex: %s", hex)
+ }
+ return nonce.Uint64(), nil
+}
+
+// SuggestGasPrice implements ContractTransactor.SuggestGasPrice, delegating the
+// gas price oracle request to the remote node.
+func (b *rpcBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
+ res, err := b.request(ctx, "eth_gasPrice", nil)
+ if err != nil {
+ return nil, err
+ }
+ var hex string
+ if err := json.Unmarshal(res, &hex); err != nil {
+ return nil, err
+ }
+ price, ok := new(big.Int).SetString(hex, 0)
+ if !ok {
+ return nil, fmt.Errorf("invalid price hex: %s", hex)
+ }
+ return price, nil
+}
+
+// EstimateGasLimit implements ContractTransactor.EstimateGasLimit, delegating
+// the gas estimation to the remote node.
+func (b *rpcBackend) EstimateGasLimit(ctx context.Context, sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
+ // Pack up the request into an RPC argument
+ args := struct {
+ From common.Address `json:"from"`
+ To *common.Address `json:"to"`
+ Value *rpc.HexNumber `json:"value"`
+ Data string `json:"data"`
+ }{
+ From: sender,
+ To: contract,
+ Data: common.ToHex(data),
+ Value: rpc.NewHexNumber(value),
+ }
+ // Execute the RPC call and retrieve the response
+ res, err := b.request(ctx, "eth_estimateGas", []interface{}{args})
+ if err != nil {
+ return nil, err
+ }
+ var hex string
+ if err := json.Unmarshal(res, &hex); err != nil {
+ return nil, err
+ }
+ estimate, ok := new(big.Int).SetString(hex, 0)
+ if !ok {
+ return nil, fmt.Errorf("invalid estimate hex: %s", hex)
+ }
+ return estimate, nil
+}
+
+// SendTransaction implements ContractTransactor.SendTransaction, delegating the
+// raw transaction injection to the remote node.
+func (b *rpcBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
+ data, err := rlp.EncodeToBytes(tx)
+ if err != nil {
+ return err
+ }
+ res, err := b.request(ctx, "eth_sendRawTransaction", []interface{}{common.ToHex(data)})
+ if err != nil {
+ return err
+ }
+ var hex string
+ if err := json.Unmarshal(res, &hex); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/simulated.go b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/simulated.go
new file mode 100644
index 000000000..687a31bf1
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/bind/backends/simulated.go
@@ -0,0 +1,212 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package backends
+
+import (
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/accounts/abi/bind"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/core/state"
+ "github.com/ethereum/go-ethereum/core/types"
+ "github.com/ethereum/go-ethereum/core/vm"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/event"
+ "golang.org/x/net/context"
+)
+
+// Default chain configuration which sets homestead phase at block 0 (i.e. no frontier)
+var chainConfig = &core.ChainConfig{HomesteadBlock: big.NewInt(0)}
+
+// This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
+var _ bind.ContractBackend = (*SimulatedBackend)(nil)
+
+// SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
+// the background. Its main purpose is to allow easily testing contract bindings.
+type SimulatedBackend struct {
+ database ethdb.Database // In memory database to store our testing data
+ blockchain *core.BlockChain // Ethereum blockchain to handle the consensus
+
+ pendingBlock *types.Block // Currently pending block that will be imported on request
+ pendingState *state.StateDB // Currently pending state that will be the active on on request
+}
+
+// NewSimulatedBackend creates a new binding backend using a simulated blockchain
+// for testing purposes.
+func NewSimulatedBackend(accounts ...core.GenesisAccount) *SimulatedBackend {
+ database, _ := ethdb.NewMemDatabase()
+ core.WriteGenesisBlockForTesting(database, accounts...)
+ blockchain, _ := core.NewBlockChain(database, chainConfig, new(core.FakePow), new(event.TypeMux))
+
+ backend := &SimulatedBackend{
+ database: database,
+ blockchain: blockchain,
+ }
+ backend.Rollback()
+
+ return backend
+}
+
+// Commit imports all the pending transactions as a single block and starts a
+// fresh new state.
+func (b *SimulatedBackend) Commit() {
+ if _, err := b.blockchain.InsertChain([]*types.Block{b.pendingBlock}); err != nil {
+ panic(err) // This cannot happen unless the simulator is wrong, fail in that case
+ }
+ b.Rollback()
+}
+
+// Rollback aborts all pending transactions, reverting to the last committed state.
+func (b *SimulatedBackend) Rollback() {
+ blocks, _ := core.GenerateChain(nil, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {})
+
+ b.pendingBlock = blocks[0]
+ b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
+}
+
+// HasCode implements ContractVerifier.HasCode, checking whether there is any
+// code associated with a certain account in the blockchain.
+func (b *SimulatedBackend) HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error) {
+ if pending {
+ return len(b.pendingState.GetCode(contract)) > 0, nil
+ }
+ statedb, _ := b.blockchain.State()
+ return len(statedb.GetCode(contract)) > 0, nil
+}
+
+// ContractCall implements ContractCaller.ContractCall, executing the specified
+// contract with the given input data.
+func (b *SimulatedBackend) ContractCall(ctx context.Context, contract common.Address, data []byte, pending bool) ([]byte, error) {
+ // Create a copy of the current state db to screw around with
+ var (
+ block *types.Block
+ statedb *state.StateDB
+ )
+ if pending {
+ block, statedb = b.pendingBlock, b.pendingState.Copy()
+ } else {
+ block = b.blockchain.CurrentBlock()
+ statedb, _ = b.blockchain.State()
+ }
+ // If there's no code to interact with, respond with an appropriate error
+ if code := statedb.GetCode(contract); len(code) == 0 {
+ return nil, bind.ErrNoCode
+ }
+ // Set infinite balance to the a fake caller account
+ from := statedb.GetOrNewStateObject(common.Address{})
+ from.SetBalance(common.MaxBig)
+
+ // Assemble the call invocation to measure the gas usage
+ msg := callmsg{
+ from: from,
+ to: &contract,
+ gasPrice: new(big.Int),
+ gasLimit: common.MaxBig,
+ value: new(big.Int),
+ data: data,
+ }
+ // Execute the call and return
+ vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
+ gaspool := new(core.GasPool).AddGas(common.MaxBig)
+
+ out, _, err := core.ApplyMessage(vmenv, msg, gaspool)
+ return out, err
+}
+
+// PendingAccountNonce implements ContractTransactor.PendingAccountNonce, retrieving
+// the nonce currently pending for the account.
+func (b *SimulatedBackend) PendingAccountNonce(ctx context.Context, account common.Address) (uint64, error) {
+ return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
+}
+
+// SuggestGasPrice implements ContractTransactor.SuggestGasPrice. Since the simulated
+// chain doens't have miners, we just return a gas price of 1 for any call.
+func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
+ return big.NewInt(1), nil
+}
+
+// EstimateGasLimit implements ContractTransactor.EstimateGasLimit, executing the
+// requested code against the currently pending block/state and returning the used
+// gas.
+func (b *SimulatedBackend) EstimateGasLimit(ctx context.Context, sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
+ // Create a copy of the currently pending state db to screw around with
+ var (
+ block = b.pendingBlock
+ statedb = b.pendingState.Copy()
+ )
+ // If there's no code to interact with, respond with an appropriate error
+ if contract != nil {
+ if code := statedb.GetCode(*contract); len(code) == 0 {
+ return nil, bind.ErrNoCode
+ }
+ }
+ // Set infinite balance to the a fake caller account
+ from := statedb.GetOrNewStateObject(sender)
+ from.SetBalance(common.MaxBig)
+
+ // Assemble the call invocation to measure the gas usage
+ msg := callmsg{
+ from: from,
+ to: contract,
+ gasPrice: new(big.Int),
+ gasLimit: common.MaxBig,
+ value: value,
+ data: data,
+ }
+ // Execute the call and return
+ vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
+ gaspool := new(core.GasPool).AddGas(common.MaxBig)
+
+ _, gas, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
+ return gas, err
+}
+
+// SendTransaction implements ContractTransactor.SendTransaction, delegating the raw
+// transaction injection to the remote node.
+func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
+ blocks, _ := core.GenerateChain(nil, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
+ for _, tx := range b.pendingBlock.Transactions() {
+ block.AddTx(tx)
+ }
+ block.AddTx(tx)
+ })
+ b.pendingBlock = blocks[0]
+ b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
+
+ return nil
+}
+
+// callmsg implements core.Message to allow passing it as a transaction simulator.
+type callmsg struct {
+ from *state.StateObject
+ to *common.Address
+ gasLimit *big.Int
+ gasPrice *big.Int
+ value *big.Int
+ data []byte
+}
+
+func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
+func (m callmsg) FromFrontier() (common.Address, error) { return m.from.Address(), nil }
+func (m callmsg) Nonce() uint64 { return 0 }
+func (m callmsg) CheckNonce() bool { return false }
+func (m callmsg) To() *common.Address { return m.to }
+func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
+func (m callmsg) Gas() *big.Int { return m.gasLimit }
+func (m callmsg) Value() *big.Int { return m.value }
+func (m callmsg) Data() []byte { return m.data }
diff --git a/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/numbers.go b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/numbers.go
index 06c4422f9..3d5842292 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/numbers.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/accounts/abi/numbers.go
@@ -56,27 +56,21 @@ var (
big_ts = reflect.TypeOf([]*big.Int(nil))
)
-// U256 will ensure unsigned 256bit on big nums
+// U256 converts a big Int into a 256bit EVM number.
func U256(n *big.Int) []byte {
return common.LeftPadBytes(common.U256(n).Bytes(), 32)
}
-// S256 will ensure signed 256bit on big nums
-func U2U256(n uint64) []byte {
- return U256(big.NewInt(int64(n)))
-}
-
// packNum packs the given number (using the reflect value) and will cast it to appropriate number representation
func packNum(value reflect.Value) []byte {
switch kind := value.Kind(); kind {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return U2U256(value.Uint())
+ return U256(new(big.Int).SetUint64(value.Uint()))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return U2U256(uint64(value.Int()))
+ return U256(big.NewInt(value.Int()))
case reflect.Ptr:
return U256(value.Interface().(*big.Int))
}
-
return nil
}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/accounts/account_manager.go b/src/vendor/github.com/ethereum/go-ethereum/accounts/account_manager.go
index 1aba7d235..4aa873fe7 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/accounts/account_manager.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/accounts/account_manager.go
@@ -192,6 +192,7 @@ func (am *Manager) Lock(addr common.Address) error {
// shortens the active unlock timeout. If the address was previously unlocked
// indefinitely the timeout is not altered.
func (am *Manager) TimedUnlock(a Account, passphrase string, timeout time.Duration) error {
+
a, key, err := am.getDecryptedKey(a, passphrase)
if err != nil {
return err
@@ -231,7 +232,6 @@ func (am *Manager) TimedUnlock(a Account, passphrase string, timeout time.Durati
}
func (am *Manager) syncAccounts(a string, key *Key) error {
-
for _, service := range *am.sync {
if whisperInstance, ok := service.(*whisper.Whisper); ok && key.WhisperEnabled {
err := whisperInstance.InjectIdentity(key.PrivateKey)
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/abigen/main.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/abigen/main.go
new file mode 100644
index 000000000..f36391351
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/abigen/main.go
@@ -0,0 +1,136 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+package main
+
+import (
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "strings"
+
+ "github.com/ethereum/go-ethereum/accounts/abi/bind"
+ "github.com/ethereum/go-ethereum/common/compiler"
+)
+
+var (
+ abiFlag = flag.String("abi", "", "Path to the Ethereum contract ABI json to bind")
+ binFlag = flag.String("bin", "", "Path to the Ethereum contract bytecode (generate deploy method)")
+ typFlag = flag.String("type", "", "Go struct name for the binding (default = package name)")
+
+ solFlag = flag.String("sol", "", "Path to the Ethereum contract Solidity source to build and bind")
+ solcFlag = flag.String("solc", "solc", "Solidity compiler to use if source builds are requested")
+ excFlag = flag.String("exc", "", "Comma separated types to exclude from binding")
+
+ pkgFlag = flag.String("pkg", "", "Go package name to generate the binding into")
+ outFlag = flag.String("out", "", "Output file for the generated binding (default = stdout)")
+)
+
+func main() {
+ // Parse and ensure all needed inputs are specified
+ flag.Parse()
+
+ if *abiFlag == "" && *solFlag == "" {
+ fmt.Printf("No contract ABI (--abi) or Solidity source (--sol) specified\n")
+ os.Exit(-1)
+ } else if (*abiFlag != "" || *binFlag != "" || *typFlag != "") && *solFlag != "" {
+ fmt.Printf("Contract ABI (--abi), bytecode (--bin) and type (--type) flags are mutually exclusive with the Solidity source (--sol) flag\n")
+ os.Exit(-1)
+ }
+ if *pkgFlag == "" {
+ fmt.Printf("No destination Go package specified (--pkg)\n")
+ os.Exit(-1)
+ }
+ // If the entire solidity code was specified, build and bind based on that
+ var (
+ abis []string
+ bins []string
+ types []string
+ )
+ if *solFlag != "" {
+ // Generate the list of types to exclude from binding
+ exclude := make(map[string]bool)
+ for _, kind := range strings.Split(*excFlag, ",") {
+ exclude[strings.ToLower(kind)] = true
+ }
+ // Build the Solidity source into bindable components
+ solc, err := compiler.New(*solcFlag)
+ if err != nil {
+ fmt.Printf("Failed to locate Solidity compiler: %v\n", err)
+ os.Exit(-1)
+ }
+ source, err := ioutil.ReadFile(*solFlag)
+ if err != nil {
+ fmt.Printf("Failed to read Soldity source code: %v\n", err)
+ os.Exit(-1)
+ }
+ contracts, err := solc.Compile(string(source))
+ if err != nil {
+ fmt.Printf("Failed to build Solidity contract: %v\n", err)
+ os.Exit(-1)
+ }
+ // Gather all non-excluded contract for binding
+ for name, contract := range contracts {
+ if exclude[strings.ToLower(name)] {
+ continue
+ }
+ abi, _ := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse
+ abis = append(abis, string(abi))
+ bins = append(bins, contract.Code)
+ types = append(types, name)
+ }
+ } else {
+ // Otherwise load up the ABI, optional bytecode and type name from the parameters
+ abi, err := ioutil.ReadFile(*abiFlag)
+ if err != nil {
+ fmt.Printf("Failed to read input ABI: %v\n", err)
+ os.Exit(-1)
+ }
+ abis = append(abis, string(abi))
+
+ bin := []byte{}
+ if *binFlag != "" {
+ if bin, err = ioutil.ReadFile(*binFlag); err != nil {
+ fmt.Printf("Failed to read input bytecode: %v\n", err)
+ os.Exit(-1)
+ }
+ }
+ bins = append(bins, string(bin))
+
+ kind := *typFlag
+ if kind == "" {
+ kind = *pkgFlag
+ }
+ types = append(types, kind)
+ }
+ // Generate the contract binding
+ code, err := bind.Bind(types, abis, bins, *pkgFlag)
+ if err != nil {
+ fmt.Printf("Failed to generate ABI binding: %v\n", err)
+ os.Exit(-1)
+ }
+ // Either flush it out to a file or display on the standard output
+ if *outFlag == "" {
+ fmt.Printf("%s\n", code)
+ return
+ }
+ if err := ioutil.WriteFile(*outFlag, []byte(code), 0600); err != nil {
+ fmt.Printf("Failed to write ABI binding: %v\n", err)
+ os.Exit(-1)
+ }
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/bootnode/main.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/bootnode/main.go
new file mode 100644
index 000000000..7d3f9fdb3
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/bootnode/main.go
@@ -0,0 +1,82 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// bootnode runs a bootstrap node for the Ethereum Discovery Protocol.
+package main
+
+import (
+ "crypto/ecdsa"
+ "flag"
+ "os"
+
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/logger/glog"
+ "github.com/ethereum/go-ethereum/p2p/discover"
+ "github.com/ethereum/go-ethereum/p2p/nat"
+)
+
+func main() {
+ var (
+ listenAddr = flag.String("addr", ":30301", "listen address")
+ genKey = flag.String("genkey", "", "generate a node key and quit")
+ nodeKeyFile = flag.String("nodekey", "", "private key filename")
+ nodeKeyHex = flag.String("nodekeyhex", "", "private key as hex (for testing)")
+ natdesc = flag.String("nat", "none", "port mapping mechanism (any|none|upnp|pmp|extip:)")
+
+ nodeKey *ecdsa.PrivateKey
+ err error
+ )
+ flag.Var(glog.GetVerbosity(), "verbosity", "log verbosity (0-9)")
+ flag.Var(glog.GetVModule(), "vmodule", "log verbosity pattern")
+ glog.SetToStderr(true)
+ flag.Parse()
+
+ if *genKey != "" {
+ key, err := crypto.GenerateKey()
+ if err != nil {
+ utils.Fatalf("could not generate key: %v", err)
+ }
+ if err := crypto.SaveECDSA(*genKey, key); err != nil {
+ utils.Fatalf("%v", err)
+ }
+ os.Exit(0)
+ }
+
+ natm, err := nat.Parse(*natdesc)
+ if err != nil {
+ utils.Fatalf("-nat: %v", err)
+ }
+ switch {
+ case *nodeKeyFile == "" && *nodeKeyHex == "":
+ utils.Fatalf("Use -nodekey or -nodekeyhex to specify a private key")
+ case *nodeKeyFile != "" && *nodeKeyHex != "":
+ utils.Fatalf("Options -nodekey and -nodekeyhex are mutually exclusive")
+ case *nodeKeyFile != "":
+ if nodeKey, err = crypto.LoadECDSA(*nodeKeyFile); err != nil {
+ utils.Fatalf("-nodekey: %v", err)
+ }
+ case *nodeKeyHex != "":
+ if nodeKey, err = crypto.HexToECDSA(*nodeKeyHex); err != nil {
+ utils.Fatalf("-nodekeyhex: %v", err)
+ }
+ }
+
+ if _, err := discover.ListenUDP(nodeKey, *listenAddr, natm, ""); err != nil {
+ utils.Fatalf("%v", err)
+ }
+ select {}
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/disasm/main.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/disasm/main.go
new file mode 100644
index 000000000..ba1295ba1
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/disasm/main.go
@@ -0,0 +1,51 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// disasm is a pretty-printer for EVM bytecode.
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+ "os"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core/vm"
+)
+
+func main() {
+ code, err := ioutil.ReadAll(os.Stdin)
+ if err != nil {
+ fmt.Println(err)
+ os.Exit(1)
+ }
+ code = common.Hex2Bytes(string(code[:len(code)-1]))
+ fmt.Printf("%x\n", code)
+
+ for pc := uint64(0); pc < uint64(len(code)); pc++ {
+ op := vm.OpCode(code[pc])
+ fmt.Printf("%-5d %v", pc, op)
+
+ switch op {
+ case vm.PUSH1, vm.PUSH2, vm.PUSH3, vm.PUSH4, vm.PUSH5, vm.PUSH6, vm.PUSH7, vm.PUSH8, vm.PUSH9, vm.PUSH10, vm.PUSH11, vm.PUSH12, vm.PUSH13, vm.PUSH14, vm.PUSH15, vm.PUSH16, vm.PUSH17, vm.PUSH18, vm.PUSH19, vm.PUSH20, vm.PUSH21, vm.PUSH22, vm.PUSH23, vm.PUSH24, vm.PUSH25, vm.PUSH26, vm.PUSH27, vm.PUSH28, vm.PUSH29, vm.PUSH30, vm.PUSH31, vm.PUSH32:
+ a := uint64(op) - uint64(vm.PUSH1) + 1
+ fmt.Printf(" => %x", code[pc+1:pc+1+a])
+
+ pc += a
+ }
+ fmt.Println()
+ }
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/code.txt b/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/code.txt
new file mode 100644
index 000000000..a964ad9d2
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/code.txt
@@ -0,0 +1 @@
+60006102ff5360003560001a60008114156103395760013560405260216040516020025990590160009052606052604051602002816060513760405160200281019050506002604051121561005957604051602002606051f35b604051602002599059016000905260a052600060c052604051602002599059016000905260e0526000610100526001610120525b604051610120511215610109576060515161012051602002606051015112156100d8576101205160200260605101516101005160200260e051015260016101005101610100526100f9565b61012051602002606051015160c05160200260a0510152600160c0510160c0525b600161012051016101205261008d565b60216020599059016000905260c051808252806020028301925050602082015990590160009052600081538151600182015260218101825160200260a0518260005b8381101561016657808301518186015260208101905061014b565b50505050825160200281019050604059905901600090526102405281610240515283602061024051015261024051905090509050905060c05160200280599059016000905281816020850151855160003060195a03f1508090509050905060a05260216020599059016000905261010051808252806020028301925050602082015990590160009052600081538151600182015260218101825160200260e0518260005b8381101561022557808301518186015260208101905061020a565b50505050825160200281019050604059905901600090526102c052816102c051528360206102c05101526102c05190509050905090506101005160200280599059016000905281816020850151855160003060195a03f1508090509050905060e05260405160200259905901600090526102e0526000610120525b610100516101205112156102d7576101205160200260e0510151610120516020026102e051015260016101205101610120526102a0565b60605151610100516020026102e05101526000610120525b60c05161012051121561032d576101205160200260a05101516101205160016101005101016020026102e051015260016101205101610120526102ef565b6040516020026102e051f35b50
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/input.txt b/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/input.txt
new file mode 100644
index 000000000..1b6857ab9
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/input.txt
@@ -0,0 +1 @@
+0000000000000000000000000000000000000000000000000000000000000000c80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000700000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000009000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000d000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000f0000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001100000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000013000000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000150000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001700000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000000000000001b000000000000000000000000000000000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000001d000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000000000000001f0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002100000000000000000000000000000000000000000000000000000000000000220000000000000000000000000000000000000000000000000000000000000023000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000250000000000000000000000000000000000000000000000000000000000000026000000000000000000000000000000000000000000000000000000000000002700000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000029000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000002b000000000000000000000000000000000000000000000000000000000000002c000000000000000000000000000000000000000000000000000000000000002d000000000000000000000000000000000000000000000000000000000000002e000000000000000000000000000000000000000000000000000000000000002f0000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000003100000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000033000000000000000000000000000000000000000000000000000000000000003400000000000000000000000000000000000000000000000000000000000000350000000000000000000000000000000000000000000000000000000000000036000000000000000000000000000000000000000000000000000000000000003700000000000000000000000000000000000000000000000000000000000000380000000000000000000000000000000000000000000000000000000000000039000000000000000000000000000000000000000000000000000000000000003a000000000000000000000000000000000000000000000000000000000000003b000000000000000000000000000000000000000000000000000000000000003c000000000000000000000000000000000000000000000000000000000000003d000000000000000000000000000000000000000000000000000000000000003e000000000000000000000000000000000000000000000000000000000000003f0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000004100000000000000000000000000000000000000000000000000000000000000420000000000000000000000000000000000000000000000000000000000000043000000000000000000000000000000000000000000000000000000000000004400000000000000000000000000000000000000000000000000000000000000450000000000000000000000000000000000000000000000000000000000000046000000000000000000000000000000000000000000000000000000000000004700000000000000000000000000000000000000000000000000000000000000480000000000000000000000000000000000000000000000000000000000000049000000000000000000000000000000000000000000000000000000000000004a000000000000000000000000000000000000000000000000000000000000004b000000000000000000000000000000000000000000000000000000000000004c000000000000000000000000000000000000000000000000000000000000004d000000000000000000000000000000000000000000000000000000000000004e000000000000000000000000000000000000000000000000000000000000004f0000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000005100000000000000000000000000000000000000000000000000000000000000520000000000000000000000000000000000000000000000000000000000000053000000000000000000000000000000000000000000000000000000000000005400000000000000000000000000000000000000000000000000000000000000550000000000000000000000000000000000000000000000000000000000000056000000000000000000000000000000000000000000000000000000000000005700000000000000000000000000000000000000000000000000000000000000580000000000000000000000000000000000000000000000000000000000000059000000000000000000000000000000000000000000000000000000000000005a000000000000000000000000000000000000000000000000000000000000005b000000000000000000000000000000000000000000000000000000000000005c000000000000000000000000000000000000000000000000000000000000005d000000000000000000000000000000000000000000000000000000000000005e000000000000000000000000000000000000000000000000000000000000005f0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000006100000000000000000000000000000000000000000000000000000000000000620000000000000000000000000000000000000000000000000000000000000063000000000000000000000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000650000000000000000000000000000000000000000000000000000000000000066000000000000000000000000000000000000000000000000000000000000006700000000000000000000000000000000000000000000000000000000000000680000000000000000000000000000000000000000000000000000000000000069000000000000000000000000000000000000000000000000000000000000006a000000000000000000000000000000000000000000000000000000000000006b000000000000000000000000000000000000000000000000000000000000006c000000000000000000000000000000000000000000000000000000000000006d000000000000000000000000000000000000000000000000000000000000006e000000000000000000000000000000000000000000000000000000000000006f0000000000000000000000000000000000000000000000000000000000000070000000000000000000000000000000000000000000000000000000000000007100000000000000000000000000000000000000000000000000000000000000720000000000000000000000000000000000000000000000000000000000000073000000000000000000000000000000000000000000000000000000000000007400000000000000000000000000000000000000000000000000000000000000750000000000000000000000000000000000000000000000000000000000000076000000000000000000000000000000000000000000000000000000000000007700000000000000000000000000000000000000000000000000000000000000780000000000000000000000000000000000000000000000000000000000000079000000000000000000000000000000000000000000000000000000000000007a000000000000000000000000000000000000000000000000000000000000007b000000000000000000000000000000000000000000000000000000000000007c000000000000000000000000000000000000000000000000000000000000007d000000000000000000000000000000000000000000000000000000000000007e000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000008100000000000000000000000000000000000000000000000000000000000000820000000000000000000000000000000000000000000000000000000000000083000000000000000000000000000000000000000000000000000000000000008400000000000000000000000000000000000000000000000000000000000000850000000000000000000000000000000000000000000000000000000000000086000000000000000000000000000000000000000000000000000000000000008700000000000000000000000000000000000000000000000000000000000000880000000000000000000000000000000000000000000000000000000000000089000000000000000000000000000000000000000000000000000000000000008a000000000000000000000000000000000000000000000000000000000000008b000000000000000000000000000000000000000000000000000000000000008c000000000000000000000000000000000000000000000000000000000000008d000000000000000000000000000000000000000000000000000000000000008e000000000000000000000000000000000000000000000000000000000000008f0000000000000000000000000000000000000000000000000000000000000090000000000000000000000000000000000000000000000000000000000000009100000000000000000000000000000000000000000000000000000000000000920000000000000000000000000000000000000000000000000000000000000093000000000000000000000000000000000000000000000000000000000000009400000000000000000000000000000000000000000000000000000000000000950000000000000000000000000000000000000000000000000000000000000096000000000000000000000000000000000000000000000000000000000000009700000000000000000000000000000000000000000000000000000000000000980000000000000000000000000000000000000000000000000000000000000099000000000000000000000000000000000000000000000000000000000000009a000000000000000000000000000000000000000000000000000000000000009b000000000000000000000000000000000000000000000000000000000000009c000000000000000000000000000000000000000000000000000000000000009d000000000000000000000000000000000000000000000000000000000000009e000000000000000000000000000000000000000000000000000000000000009f00000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000a100000000000000000000000000000000000000000000000000000000000000a200000000000000000000000000000000000000000000000000000000000000a300000000000000000000000000000000000000000000000000000000000000a400000000000000000000000000000000000000000000000000000000000000a500000000000000000000000000000000000000000000000000000000000000a600000000000000000000000000000000000000000000000000000000000000a700000000000000000000000000000000000000000000000000000000000000a800000000000000000000000000000000000000000000000000000000000000a900000000000000000000000000000000000000000000000000000000000000aa00000000000000000000000000000000000000000000000000000000000000ab00000000000000000000000000000000000000000000000000000000000000ac00000000000000000000000000000000000000000000000000000000000000ad00000000000000000000000000000000000000000000000000000000000000ae00000000000000000000000000000000000000000000000000000000000000af00000000000000000000000000000000000000000000000000000000000000b000000000000000000000000000000000000000000000000000000000000000b100000000000000000000000000000000000000000000000000000000000000b200000000000000000000000000000000000000000000000000000000000000b300000000000000000000000000000000000000000000000000000000000000b400000000000000000000000000000000000000000000000000000000000000b500000000000000000000000000000000000000000000000000000000000000b600000000000000000000000000000000000000000000000000000000000000b700000000000000000000000000000000000000000000000000000000000000b800000000000000000000000000000000000000000000000000000000000000b900000000000000000000000000000000000000000000000000000000000000ba00000000000000000000000000000000000000000000000000000000000000bb00000000000000000000000000000000000000000000000000000000000000bc00000000000000000000000000000000000000000000000000000000000000bd00000000000000000000000000000000000000000000000000000000000000be00000000000000000000000000000000000000000000000000000000000000bf00000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000c100000000000000000000000000000000000000000000000000000000000000c200000000000000000000000000000000000000000000000000000000000000c300000000000000000000000000000000000000000000000000000000000000c400000000000000000000000000000000000000000000000000000000000000c500000000000000000000000000000000000000000000000000000000000000c600000000000000000000000000000000000000000000000000000000000000c7
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/main.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/main.go
new file mode 100644
index 000000000..aa48f6ede
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/evm/main.go
@@ -0,0 +1,276 @@
+// Copyright 2014 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// evm executes EVM code snippets.
+package main
+
+import (
+ "fmt"
+ "math/big"
+ "os"
+ "runtime"
+ "time"
+
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/core/state"
+ "github.com/ethereum/go-ethereum/core/types"
+ "github.com/ethereum/go-ethereum/core/vm"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/logger/glog"
+ "gopkg.in/urfave/cli.v1"
+)
+
+var (
+ app *cli.App
+ DebugFlag = cli.BoolFlag{
+ Name: "debug",
+ Usage: "output full trace logs",
+ }
+ ForceJitFlag = cli.BoolFlag{
+ Name: "forcejit",
+ Usage: "forces jit compilation",
+ }
+ DisableJitFlag = cli.BoolFlag{
+ Name: "nojit",
+ Usage: "disabled jit compilation",
+ }
+ CodeFlag = cli.StringFlag{
+ Name: "code",
+ Usage: "EVM code",
+ }
+ GasFlag = cli.StringFlag{
+ Name: "gas",
+ Usage: "gas limit for the evm",
+ Value: "10000000000",
+ }
+ PriceFlag = cli.StringFlag{
+ Name: "price",
+ Usage: "price set for the evm",
+ Value: "0",
+ }
+ ValueFlag = cli.StringFlag{
+ Name: "value",
+ Usage: "value set for the evm",
+ Value: "0",
+ }
+ DumpFlag = cli.BoolFlag{
+ Name: "dump",
+ Usage: "dumps the state after the run",
+ }
+ InputFlag = cli.StringFlag{
+ Name: "input",
+ Usage: "input for the EVM",
+ }
+ SysStatFlag = cli.BoolFlag{
+ Name: "sysstat",
+ Usage: "display system stats",
+ }
+ VerbosityFlag = cli.IntFlag{
+ Name: "verbosity",
+ Usage: "sets the verbosity level",
+ }
+ CreateFlag = cli.BoolFlag{
+ Name: "create",
+ Usage: "indicates the action should be create rather than call",
+ }
+)
+
+func init() {
+ app = utils.NewApp("0.2", "the evm command line interface")
+ app.Flags = []cli.Flag{
+ CreateFlag,
+ DebugFlag,
+ VerbosityFlag,
+ ForceJitFlag,
+ DisableJitFlag,
+ SysStatFlag,
+ CodeFlag,
+ GasFlag,
+ PriceFlag,
+ ValueFlag,
+ DumpFlag,
+ InputFlag,
+ }
+ app.Action = run
+}
+
+func run(ctx *cli.Context) error {
+ glog.SetToStderr(true)
+ glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
+
+ db, _ := ethdb.NewMemDatabase()
+ statedb, _ := state.New(common.Hash{}, db)
+ sender := statedb.CreateAccount(common.StringToAddress("sender"))
+
+ vmenv := NewEnv(statedb, common.StringToAddress("evmuser"), common.Big(ctx.GlobalString(ValueFlag.Name)), vm.Config{
+ Debug: ctx.GlobalBool(DebugFlag.Name),
+ ForceJit: ctx.GlobalBool(ForceJitFlag.Name),
+ EnableJit: !ctx.GlobalBool(DisableJitFlag.Name),
+ })
+
+ tstart := time.Now()
+
+ var (
+ ret []byte
+ err error
+ )
+
+ if ctx.GlobalBool(CreateFlag.Name) {
+ input := append(common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name)), common.Hex2Bytes(ctx.GlobalString(InputFlag.Name))...)
+ ret, _, err = vmenv.Create(
+ sender,
+ input,
+ common.Big(ctx.GlobalString(GasFlag.Name)),
+ common.Big(ctx.GlobalString(PriceFlag.Name)),
+ common.Big(ctx.GlobalString(ValueFlag.Name)),
+ )
+ } else {
+ receiver := statedb.CreateAccount(common.StringToAddress("receiver"))
+ receiver.SetCode(common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name)))
+ ret, err = vmenv.Call(
+ sender,
+ receiver.Address(),
+ common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)),
+ common.Big(ctx.GlobalString(GasFlag.Name)),
+ common.Big(ctx.GlobalString(PriceFlag.Name)),
+ common.Big(ctx.GlobalString(ValueFlag.Name)),
+ )
+ }
+ vmdone := time.Since(tstart)
+
+ if ctx.GlobalBool(DumpFlag.Name) {
+ statedb.Commit()
+ fmt.Println(string(statedb.Dump()))
+ }
+ vm.StdErrFormat(vmenv.StructLogs())
+
+ if ctx.GlobalBool(SysStatFlag.Name) {
+ var mem runtime.MemStats
+ runtime.ReadMemStats(&mem)
+ fmt.Printf("vm took %v\n", vmdone)
+ fmt.Printf(`alloc: %d
+tot alloc: %d
+no. malloc: %d
+heap alloc: %d
+heap objs: %d
+num gc: %d
+`, mem.Alloc, mem.TotalAlloc, mem.Mallocs, mem.HeapAlloc, mem.HeapObjects, mem.NumGC)
+ }
+
+ fmt.Printf("OUT: 0x%x", ret)
+ if err != nil {
+ fmt.Printf(" error: %v", err)
+ }
+ fmt.Println()
+ return nil
+}
+
+func main() {
+ if err := app.Run(os.Args); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+type VMEnv struct {
+ state *state.StateDB
+ block *types.Block
+
+ transactor *common.Address
+ value *big.Int
+
+ depth int
+ Gas *big.Int
+ time *big.Int
+ logs []vm.StructLog
+
+ evm *vm.EVM
+}
+
+func NewEnv(state *state.StateDB, transactor common.Address, value *big.Int, cfg vm.Config) *VMEnv {
+ env := &VMEnv{
+ state: state,
+ transactor: &transactor,
+ value: value,
+ time: big.NewInt(time.Now().Unix()),
+ }
+ cfg.Logger.Collector = env
+
+ env.evm = vm.New(env, cfg)
+ return env
+}
+
+// ruleSet implements vm.RuleSet and will always default to the homestead rule set.
+type ruleSet struct{}
+
+func (ruleSet) IsHomestead(*big.Int) bool { return true }
+
+func (self *VMEnv) RuleSet() vm.RuleSet { return ruleSet{} }
+func (self *VMEnv) Vm() vm.Vm { return self.evm }
+func (self *VMEnv) Db() vm.Database { return self.state }
+func (self *VMEnv) MakeSnapshot() vm.Database { return self.state.Copy() }
+func (self *VMEnv) SetSnapshot(db vm.Database) { self.state.Set(db.(*state.StateDB)) }
+func (self *VMEnv) Origin() common.Address { return *self.transactor }
+func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 }
+func (self *VMEnv) Coinbase() common.Address { return *self.transactor }
+func (self *VMEnv) Time() *big.Int { return self.time }
+func (self *VMEnv) Difficulty() *big.Int { return common.Big1 }
+func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
+func (self *VMEnv) Value() *big.Int { return self.value }
+func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
+func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
+func (self *VMEnv) Depth() int { return 0 }
+func (self *VMEnv) SetDepth(i int) { self.depth = i }
+func (self *VMEnv) GetHash(n uint64) common.Hash {
+ if self.block.Number().Cmp(big.NewInt(int64(n))) == 0 {
+ return self.block.Hash()
+ }
+ return common.Hash{}
+}
+func (self *VMEnv) AddStructLog(log vm.StructLog) {
+ self.logs = append(self.logs, log)
+}
+func (self *VMEnv) StructLogs() []vm.StructLog {
+ return self.logs
+}
+func (self *VMEnv) AddLog(log *vm.Log) {
+ self.state.AddLog(log)
+}
+func (self *VMEnv) CanTransfer(from common.Address, balance *big.Int) bool {
+ return self.state.GetBalance(from).Cmp(balance) >= 0
+}
+func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) {
+ core.Transfer(from, to, amount)
+}
+
+func (self *VMEnv) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
+ self.Gas = gas
+ return core.Call(self, caller, addr, data, gas, price, value)
+}
+
+func (self *VMEnv) CallCode(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
+ return core.CallCode(self, caller, addr, data, gas, price, value)
+}
+
+func (self *VMEnv) DelegateCall(caller vm.ContractRef, addr common.Address, data []byte, gas, price *big.Int) ([]byte, error) {
+ return core.DelegateCall(self, caller, addr, data, gas, price)
+}
+
+func (self *VMEnv) Create(caller vm.ContractRef, data []byte, gas, price, value *big.Int) ([]byte, common.Address, error) {
+ return core.Create(self, caller, data, gas, price, value)
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/accountcmd.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/accountcmd.go
new file mode 100644
index 000000000..5e2895636
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/accountcmd.go
@@ -0,0 +1,354 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+package main
+
+import (
+ "fmt"
+ "io/ioutil"
+
+ "github.com/ethereum/go-ethereum/accounts"
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/console"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
+ "gopkg.in/urfave/cli.v1"
+ "github.com/ethereum/go-ethereum/node"
+)
+
+var (
+ walletCommand = cli.Command{
+ Name: "wallet",
+ Usage: "ethereum presale wallet",
+ Subcommands: []cli.Command{
+ {
+ Action: importWallet,
+ Name: "import",
+ Usage: "import ethereum presale wallet",
+ },
+ },
+ Description: `
+
+ get wallet import /path/to/my/presale.wallet
+
+will prompt for your password and imports your ether presale account.
+It can be used non-interactively with the --password option taking a
+passwordfile as argument containing the wallet password in plaintext.
+
+`}
+ accountCommand = cli.Command{
+ Action: accountList,
+ Name: "account",
+ Usage: "manage accounts",
+ Description: `
+
+Manage accounts lets you create new accounts, list all existing accounts,
+import a private key into a new account.
+
+' help' shows a list of subcommands or help for one subcommand.
+
+It supports interactive mode, when you are prompted for password as well as
+non-interactive mode where passwords are supplied via a given password file.
+Non-interactive mode is only meant for scripted use on test networks or known
+safe environments.
+
+Make sure you remember the password you gave when creating a new account (with
+either new or import). Without it you are not able to unlock your account.
+
+Note that exporting your key in unencrypted format is NOT supported.
+
+Keys are stored under /keystore.
+It is safe to transfer the entire directory or the individual keys therein
+between ethereum nodes by simply copying.
+Make sure you backup your keys regularly.
+
+In order to use your account to send transactions, you need to unlock them using
+the '--unlock' option. The argument is a space separated list of addresses or
+indexes. If used non-interactively with a passwordfile, the file should contain
+the respective passwords one per line. If you unlock n accounts and the password
+file contains less than n entries, then the last password is meant to apply to
+all remaining accounts.
+
+And finally. DO NOT FORGET YOUR PASSWORD.
+`,
+ Subcommands: []cli.Command{
+ {
+ Action: accountList,
+ Name: "list",
+ Usage: "print account addresses",
+ },
+ {
+ Action: accountCreate,
+ Name: "new",
+ Usage: "create a new account",
+ Description: `
+
+ ethereum account new
+
+Creates a new account. Prints the address.
+
+The account is saved in encrypted format, you are prompted for a passphrase.
+
+You must remember this passphrase to unlock your account in the future.
+
+For non-interactive use the passphrase can be specified with the --password flag:
+
+ ethereum --password account new
+
+Note, this is meant to be used for testing only, it is a bad idea to save your
+password to file or expose in any other way.
+ `,
+ },
+ {
+ Action: accountUpdate,
+ Name: "update",
+ Usage: "update an existing account",
+ Description: `
+
+ ethereum account update
+
+Update an existing account.
+
+The account is saved in the newest version in encrypted format, you are prompted
+for a passphrase to unlock the account and another to save the updated file.
+
+This same command can therefore be used to migrate an account of a deprecated
+format to the newest format or change the password for an account.
+
+For non-interactive use the passphrase can be specified with the --password flag:
+
+ ethereum --password account update
+
+Since only one password can be given, only format update can be performed,
+changing your password is only possible interactively.
+ `,
+ },
+ {
+ Action: accountImport,
+ Name: "import",
+ Usage: "import a private key into a new account",
+ Description: `
+
+ ethereum account import
+
+Imports an unencrypted private key from and creates a new account.
+Prints the address.
+
+The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
+
+The account is saved in encrypted format, you are prompted for a passphrase.
+
+You must remember this passphrase to unlock your account in the future.
+
+For non-interactive use the passphrase can be specified with the -password flag:
+
+ ethereum --password account import
+
+Note:
+As you can directly copy your encrypted accounts to another ethereum instance,
+this import mechanism is not needed when you transfer an account between
+nodes.
+ `,
+ },
+ },
+ }
+)
+
+func accountList(ctx *cli.Context) error {
+ var sync *[]node.Service
+ accman := utils.MakeAccountManager(ctx, sync)
+ for i, acct := range accman.Accounts() {
+ fmt.Printf("Account #%d: {%x} %s\n", i, acct.Address, acct.File)
+ }
+ return nil
+}
+
+// tries unlocking the specified account a few times.
+func unlockAccount(ctx *cli.Context, accman *accounts.Manager, address string, i int, passwords []string) (accounts.Account, string) {
+ account, err := utils.MakeAddress(accman, address)
+ if err != nil {
+ utils.Fatalf("Could not list accounts: %v", err)
+ }
+ for trials := 0; trials < 3; trials++ {
+ prompt := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", address, trials+1, 3)
+ password := getPassPhrase(prompt, false, i, passwords)
+ err = accman.Unlock(account, password)
+ if err == nil {
+ glog.V(logger.Info).Infof("Unlocked account %x", account.Address)
+ return account, password
+ }
+ if err, ok := err.(*accounts.AmbiguousAddrError); ok {
+ glog.V(logger.Info).Infof("Unlocked account %x", account.Address)
+ return ambiguousAddrRecovery(accman, err, password), password
+ }
+ if err != accounts.ErrDecrypt {
+ // No need to prompt again if the error is not decryption-related.
+ break
+ }
+ }
+ // All trials expended to unlock account, bail out
+ utils.Fatalf("Failed to unlock account %s (%v)", address, err)
+ return accounts.Account{}, ""
+}
+
+// getPassPhrase retrieves the password associated with an account, either fetched
+// from a list of preloaded passphrases, or requested interactively from the user.
+func getPassPhrase(prompt string, confirmation bool, i int, passwords []string) string {
+ // If a list of passwords was supplied, retrieve from them
+ if len(passwords) > 0 {
+ if i < len(passwords) {
+ return passwords[i]
+ }
+ return passwords[len(passwords)-1]
+ }
+ // Otherwise prompt the user for the password
+ if prompt != "" {
+ fmt.Println(prompt)
+ }
+ password, err := console.Stdin.PromptPassword("Passphrase: ")
+ if err != nil {
+ utils.Fatalf("Failed to read passphrase: %v", err)
+ }
+ if confirmation {
+ confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ")
+ if err != nil {
+ utils.Fatalf("Failed to read passphrase confirmation: %v", err)
+ }
+ if password != confirm {
+ utils.Fatalf("Passphrases do not match")
+ }
+ }
+ return password
+}
+
+// getWhisperYesNo retrieves an indication of whether or not the user wants the created
+// account to also be enabled as a whisper identity
+func getWhisperYesNo(prompt string) bool {
+
+ // prompt the user for the whisper preference
+ if prompt != "" {
+ fmt.Println(prompt)
+ }
+
+ shhRes, err := console.Stdin.PromptConfirm("Enable the new account as a Whisper Identity?")
+ if err != nil {
+ utils.Fatalf("Failed to read response: %v", err)
+ }
+
+ return shhRes
+}
+
+func ambiguousAddrRecovery(am *accounts.Manager, err *accounts.AmbiguousAddrError, auth string) accounts.Account {
+ fmt.Printf("Multiple key files exist for address %x:\n", err.Addr)
+ for _, a := range err.Matches {
+ fmt.Println(" ", a.File)
+ }
+ fmt.Println("Testing your passphrase against all of them...")
+ var match *accounts.Account
+ for _, a := range err.Matches {
+ if err := am.Unlock(a, auth); err == nil {
+ match = &a
+ break
+ }
+ }
+ if match == nil {
+ utils.Fatalf("None of the listed files could be unlocked.")
+ }
+ fmt.Printf("Your passphrase unlocked %s\n", match.File)
+ fmt.Println("In order to avoid this warning, you need to remove the following duplicate key files:")
+ for _, a := range err.Matches {
+ if a != *match {
+ fmt.Println(" ", a.File)
+ }
+ }
+ return *match
+}
+
+// accountCreate creates a new account into the keystore defined by the CLI flags.
+func accountCreate(ctx *cli.Context) error {
+ var sync *[]node.Service
+ accman := utils.MakeAccountManager(ctx, sync)
+ password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
+ whisper := getWhisperYesNo("You can also choose to enable your new account as a Whisper identity.")
+
+ account, err := accman.NewAccount(password, whisper)
+ if err != nil {
+ utils.Fatalf("Failed to create account: %v", err)
+ }
+
+ fmt.Printf("Address: {%x}\n", account.Address)
+ return nil
+}
+
+// accountUpdate transitions an account from a previous format to the current
+// one, also providing the possibility to change the pass-phrase.
+func accountUpdate(ctx *cli.Context) error {
+ if len(ctx.Args()) == 0 {
+ utils.Fatalf("No accounts specified to update")
+ }
+ var sync *[]node.Service
+ accman := utils.MakeAccountManager(ctx, sync)
+
+ account, oldPassword := unlockAccount(ctx, accman, ctx.Args().First(), 0, nil)
+ newPassword := getPassPhrase("Please give a new password. Do not forget this password.", true, 0, nil)
+ if err := accman.Update(account, oldPassword, newPassword); err != nil {
+ utils.Fatalf("Could not update the account: %v", err)
+ }
+ return nil
+}
+
+func importWallet(ctx *cli.Context) error {
+ keyfile := ctx.Args().First()
+ if len(keyfile) == 0 {
+ utils.Fatalf("keyfile must be given as argument")
+ }
+ keyJson, err := ioutil.ReadFile(keyfile)
+ if err != nil {
+ utils.Fatalf("Could not read wallet file: %v", err)
+ }
+
+ var sync *[]node.Service
+ accman := utils.MakeAccountManager(ctx, sync)
+ passphrase := getPassPhrase("", false, 0, utils.MakePasswordList(ctx))
+
+ acct, err := accman.ImportPreSaleKey(keyJson, passphrase)
+ if err != nil {
+ utils.Fatalf("%v", err)
+ }
+ fmt.Printf("Address: {%x}\n", acct.Address)
+ return nil
+}
+
+func accountImport(ctx *cli.Context) error {
+ keyfile := ctx.Args().First()
+ if len(keyfile) == 0 {
+ utils.Fatalf("keyfile must be given as argument")
+ }
+ key, err := crypto.LoadECDSA(keyfile)
+ if err != nil {
+ utils.Fatalf("Failed to load the private key: %v", err)
+ }
+ var sync *[]node.Service
+ accman := utils.MakeAccountManager(ctx, sync)
+ passphrase := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
+ acct, err := accman.ImportECDSA(key, passphrase)
+ if err != nil {
+ utils.Fatalf("Could not create the account: %v", err)
+ }
+ fmt.Printf("Address: {%x}\n", acct.Address)
+ return nil
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/chaincmd.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/chaincmd.go
new file mode 100644
index 000000000..fe63dfcca
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/chaincmd.go
@@ -0,0 +1,207 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+package main
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "time"
+
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/console"
+ "github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/core/state"
+ "github.com/ethereum/go-ethereum/core/types"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/logger/glog"
+ "gopkg.in/urfave/cli.v1"
+)
+
+var (
+ importCommand = cli.Command{
+ Action: importChain,
+ Name: "import",
+ Usage: `import a blockchain file`,
+ }
+ exportCommand = cli.Command{
+ Action: exportChain,
+ Name: "export",
+ Usage: `export blockchain into file`,
+ Description: `
+Requires a first argument of the file to write to.
+Optional second and third arguments control the first and
+last block to write. In this mode, the file will be appended
+if already existing.
+ `,
+ }
+ upgradedbCommand = cli.Command{
+ Action: upgradeDB,
+ Name: "upgradedb",
+ Usage: "upgrade chainblock database",
+ }
+ removedbCommand = cli.Command{
+ Action: removeDB,
+ Name: "removedb",
+ Usage: "Remove blockchain and state databases",
+ }
+ dumpCommand = cli.Command{
+ Action: dump,
+ Name: "dump",
+ Usage: `dump a specific block from storage`,
+ Description: `
+The arguments are interpreted as block numbers or hashes.
+Use "ethereum dump 0" to dump the genesis block.
+`,
+ }
+)
+
+func importChain(ctx *cli.Context) error {
+ if len(ctx.Args()) != 1 {
+ utils.Fatalf("This command requires an argument.")
+ }
+ chain, chainDb := utils.MakeChain(ctx)
+ start := time.Now()
+ err := utils.ImportChain(chain, ctx.Args().First())
+ chainDb.Close()
+ if err != nil {
+ utils.Fatalf("Import error: %v", err)
+ }
+ fmt.Printf("Import done in %v", time.Since(start))
+ return nil
+}
+
+func exportChain(ctx *cli.Context) error {
+ if len(ctx.Args()) < 1 {
+ utils.Fatalf("This command requires an argument.")
+ }
+ chain, _ := utils.MakeChain(ctx)
+ start := time.Now()
+
+ var err error
+ fp := ctx.Args().First()
+ if len(ctx.Args()) < 3 {
+ err = utils.ExportChain(chain, fp)
+ } else {
+ // This can be improved to allow for numbers larger than 9223372036854775807
+ first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
+ last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
+ if ferr != nil || lerr != nil {
+ utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
+ }
+ if first < 0 || last < 0 {
+ utils.Fatalf("Export error: block number must be greater than 0\n")
+ }
+ err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
+ }
+
+ if err != nil {
+ utils.Fatalf("Export error: %v\n", err)
+ }
+ fmt.Printf("Export done in %v", time.Since(start))
+ return nil
+}
+
+func removeDB(ctx *cli.Context) error {
+ confirm, err := console.Stdin.PromptConfirm("Remove local database?")
+ if err != nil {
+ utils.Fatalf("%v", err)
+ }
+
+ if confirm {
+ fmt.Println("Removing chaindata...")
+ start := time.Now()
+
+ os.RemoveAll(filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), utils.ChainDbName(ctx)))
+
+ fmt.Printf("Removed in %v\n", time.Since(start))
+ } else {
+ fmt.Println("Operation aborted")
+ }
+ return nil
+}
+
+func upgradeDB(ctx *cli.Context) error {
+ glog.Infoln("Upgrading blockchain database")
+
+ chain, chainDb := utils.MakeChain(ctx)
+ bcVersion := core.GetBlockChainVersion(chainDb)
+ if bcVersion == 0 {
+ bcVersion = core.BlockChainVersion
+ }
+
+ // Export the current chain.
+ filename := fmt.Sprintf("blockchain_%d_%s.chain", bcVersion, time.Now().Format("20060102_150405"))
+ exportFile := filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), filename)
+ if err := utils.ExportChain(chain, exportFile); err != nil {
+ utils.Fatalf("Unable to export chain for reimport %s", err)
+ }
+ chainDb.Close()
+ os.RemoveAll(filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), utils.ChainDbName(ctx)))
+
+ // Import the chain file.
+ chain, chainDb = utils.MakeChain(ctx)
+ core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
+ err := utils.ImportChain(chain, exportFile)
+ chainDb.Close()
+ if err != nil {
+ utils.Fatalf("Import error %v (a backup is made in %s, use the import command to import it)", err, exportFile)
+ } else {
+ os.Remove(exportFile)
+ glog.Infoln("Import finished")
+ }
+ return nil
+}
+
+func dump(ctx *cli.Context) error {
+ chain, chainDb := utils.MakeChain(ctx)
+ for _, arg := range ctx.Args() {
+ var block *types.Block
+ if hashish(arg) {
+ block = chain.GetBlockByHash(common.HexToHash(arg))
+ } else {
+ num, _ := strconv.Atoi(arg)
+ block = chain.GetBlockByNumber(uint64(num))
+ }
+ if block == nil {
+ fmt.Println("{}")
+ utils.Fatalf("block not found")
+ } else {
+ state, err := state.New(block.Root(), chainDb)
+ if err != nil {
+ utils.Fatalf("could not create new state: %v", err)
+ }
+ fmt.Printf("%s\n", state.Dump())
+ }
+ }
+ chainDb.Close()
+ return nil
+}
+
+// hashish returns true for strings that look like hashes.
+func hashish(x string) bool {
+ _, err := strconv.Atoi(x)
+ return err != nil
+}
+
+func closeAll(dbs ...ethdb.Database) {
+ for _, db := range dbs {
+ db.Close()
+ }
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/consolecmd.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/consolecmd.go
new file mode 100644
index 000000000..f16d0a594
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/consolecmd.go
@@ -0,0 +1,185 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+package main
+
+import (
+ "os"
+ "os/signal"
+
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/console"
+ "github.com/ethereum/go-ethereum/rpc"
+ "gopkg.in/urfave/cli.v1"
+)
+
+var (
+ consoleCommand = cli.Command{
+ Action: localConsole,
+ Name: "console",
+ Usage: `Geth Console: interactive JavaScript environment`,
+ Description: `
+The Geth console is an interactive shell for the JavaScript runtime environment
+which exposes a node admin interface as well as the Ðapp JavaScript API.
+See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
+`,
+ }
+ attachCommand = cli.Command{
+ Action: remoteConsole,
+ Name: "attach",
+ Usage: `Geth Console: interactive JavaScript environment (connect to node)`,
+ Description: `
+The Geth console is an interactive shell for the JavaScript runtime environment
+which exposes a node admin interface as well as the Ðapp JavaScript API.
+See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console.
+This command allows to open a console on a running geth node.
+ `,
+ }
+ javascriptCommand = cli.Command{
+ Action: ephemeralConsole,
+ Name: "js",
+ Usage: `executes the given JavaScript files in the Geth JavaScript VM`,
+ Description: `
+The JavaScript VM exposes a node admin interface as well as the Ðapp
+JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
+`,
+ }
+)
+
+// localConsole starts a new geth node, attaching a JavaScript console to it at the
+// same time.
+func localConsole(ctx *cli.Context) error {
+ // Create and start the node based on the CLI flags
+ node, _ := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx)
+ startNode(ctx, node)
+ defer node.Stop()
+
+ // Attach to the newly started node and start the JavaScript console
+ client := rpc.NewClientRestartWrapper(func() rpc.Client {
+ client, err := node.Attach()
+ if err != nil {
+ utils.Fatalf("Failed to attach to the inproc geth: %v", err)
+ }
+ return client
+ })
+ config := console.Config{
+ DataDir: node.DataDir(),
+ DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
+ Client: client,
+ Preload: utils.MakeConsolePreloads(ctx),
+ }
+ console, err := console.New(config)
+ if err != nil {
+ utils.Fatalf("Failed to start the JavaScript console: %v", err)
+ }
+ defer console.Stop(false)
+
+ // If only a short execution was requested, evaluate and return
+ if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
+ console.Evaluate(script)
+ return nil
+ }
+ // Otherwise print the welcome screen and enter interactive mode
+ console.Welcome()
+ console.Interactive()
+
+ return nil
+}
+
+// remoteConsole will connect to a remote geth instance, attaching a JavaScript
+// console to it.
+func remoteConsole(ctx *cli.Context) error {
+ // Attach to a remotely running geth instance and start the JavaScript console
+ client := rpc.NewClientRestartWrapper(func() rpc.Client {
+ client, err := utils.NewRemoteRPCClient(ctx)
+ if err != nil {
+ utils.Fatalf("Unable to attach to remote geth: %v", err)
+ }
+ return client
+ })
+
+ config := console.Config{
+ DataDir: utils.MustMakeDataDir(ctx),
+ DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
+ Client: client,
+ Preload: utils.MakeConsolePreloads(ctx),
+ }
+ console, err := console.New(config)
+ if err != nil {
+ utils.Fatalf("Failed to start the JavaScript console: %v", err)
+ }
+ defer console.Stop(false)
+
+ // If only a short execution was requested, evaluate and return
+ if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
+ console.Evaluate(script)
+ return nil
+ }
+ // Otherwise print the welcome screen and enter interactive mode
+ console.Welcome()
+ console.Interactive()
+
+ return nil
+}
+
+// ephemeralConsole starts a new geth node, attaches an ephemeral JavaScript
+// console to it, and each of the files specified as arguments and tears the
+// everything down.
+func ephemeralConsole(ctx *cli.Context) error {
+ // Create and start the node based on the CLI flags
+ node, _ := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx)
+ startNode(ctx, node)
+ defer node.Stop()
+
+ // Attach to the newly started node and start the JavaScript console
+ client := rpc.NewClientRestartWrapper(func() rpc.Client {
+ client, err := node.Attach()
+ if err != nil {
+ utils.Fatalf("Failed to attach to the inproc geth: %v", err)
+ }
+ return client
+ })
+
+ config := console.Config{
+ DataDir: node.DataDir(),
+ DocRoot: ctx.GlobalString(utils.JSpathFlag.Name),
+ Client: client,
+ Preload: utils.MakeConsolePreloads(ctx),
+ }
+ console, err := console.New(config)
+ if err != nil {
+ utils.Fatalf("Failed to start the JavaScript console: %v", err)
+ }
+ defer console.Stop(false)
+
+ // Evaluate each of the specified JavaScript files
+ for _, file := range ctx.Args() {
+ if err = console.Execute(file); err != nil {
+ utils.Fatalf("Failed to execute %s: %v", file, err)
+ }
+ }
+ // Wait for pending callbacks, but stop for Ctrl-C.
+ abort := make(chan os.Signal, 1)
+ signal.Notify(abort, os.Interrupt)
+
+ go func() {
+ <-abort
+ os.Exit(0)
+ }()
+ console.Stop(true)
+
+ return nil
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/info_test.json b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/info_test.json
new file mode 100644
index 000000000..63f2163a9
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/info_test.json
@@ -0,0 +1 @@
+{"code":"0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056","info":{"abiDefinition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}],"compilerVersion":"0.9.23","developerDoc":{"methods":{}},"language":"Solidity","languageVersion":"0","source":"contract test {\n /// @notice Will multiply `a` by 7.\n function multiply(uint a) returns(uint d) {\n return a * 7;\n }\n}\n","userDoc":{"methods":{"multiply(uint256)":{"notice":"Will multiply `a` by 7."}}}}}
\ No newline at end of file
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library.c b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library.c
new file mode 100644
index 000000000..f738621a8
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library.c
@@ -0,0 +1,24 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// Simple wrapper to translate the API exposed methods and types to inthernal
+// Go versions of the same types.
+
+#include "_cgo_export.h"
+
+int run(const char* args) {
+ return doRun((char*)args);
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library.go
new file mode 100644
index 000000000..b8ffaaed7
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library.go
@@ -0,0 +1,46 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// Contains a simple library definition to allow creating a Geth instance from
+// straight C code.
+
+package main
+
+// #ifdef __cplusplus
+// extern "C" {
+// #endif
+//
+// extern int run(const char*);
+//
+// #ifdef __cplusplus
+// }
+// #endif
+import "C"
+import (
+ "fmt"
+ "os"
+ "strings"
+)
+
+//export doRun
+func doRun(args *C.char) C.int {
+ // This is equivalent to geth.main, just modified to handle the function arg passing
+ if err := app.Run(strings.Split("geth "+C.GoString(args), " ")); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return -1
+ }
+ return 0
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library_android.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library_android.go
new file mode 100644
index 000000000..fb021bfe0
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/library_android.go
@@ -0,0 +1,56 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// Contains specialized code for running Geth on Android.
+
+package main
+
+// #include
+// #cgo LDFLAGS: -llog
+import "C"
+import (
+ "bufio"
+ "os"
+)
+
+func init() {
+ // Redirect the standard output and error to logcat
+ oldStdout, oldStderr := os.Stdout, os.Stderr
+
+ outRead, outWrite, _ := os.Pipe()
+ errRead, errWrite, _ := os.Pipe()
+
+ os.Stdout = outWrite
+ os.Stderr = errWrite
+
+ go func() {
+ scanner := bufio.NewScanner(outRead)
+ for scanner.Scan() {
+ line := scanner.Text()
+ C.__android_log_write(C.ANDROID_LOG_INFO, C.CString("Stdout"), C.CString(line))
+ oldStdout.WriteString(line + "\n")
+ }
+ }()
+
+ go func() {
+ scanner := bufio.NewScanner(errRead)
+ for scanner.Scan() {
+ line := scanner.Text()
+ C.__android_log_write(C.ANDROID_LOG_INFO, C.CString("Stderr"), C.CString(line))
+ oldStderr.WriteString(line + "\n")
+ }
+ }()
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/main.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/main.go
new file mode 100644
index 000000000..d35671da9
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/main.go
@@ -0,0 +1,425 @@
+// Copyright 2014 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// geth is the official command-line client for Ethereum.
+package main
+
+import (
+ "encoding/hex"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/ethereum/ethash"
+ "github.com/ethereum/go-ethereum/accounts"
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/console"
+ "github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/eth"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/internal/debug"
+ "github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
+ "github.com/ethereum/go-ethereum/metrics"
+ "github.com/ethereum/go-ethereum/node"
+ "github.com/ethereum/go-ethereum/p2p/discover"
+ "github.com/ethereum/go-ethereum/params"
+ "github.com/ethereum/go-ethereum/release"
+ "github.com/ethereum/go-ethereum/rlp"
+ "gopkg.in/urfave/cli.v1"
+)
+
+const (
+ clientIdentifier = "Geth" // Client identifier to advertise over the network
+ versionMajor = 1 // Major version component of the current release
+ versionMinor = 5 // Minor version component of the current release
+ versionPatch = 0 // Patch version component of the current release
+ versionMeta = "unstable" // Version metadata to append to the version string
+
+ versionOracle = "0xfa7b9770ca4cb04296cac84f37736d4041251cdf" // Ethereum address of the Geth release oracle
+)
+
+var (
+ gitCommit string // Git SHA1 commit hash of the release (set via linker flags)
+ verString string // Combined textual representation of all the version components
+ relConfig release.Config // Structured version information and release oracle config
+ app *cli.App
+)
+
+func init() {
+ // Construct the textual version string from the individual components
+ verString = fmt.Sprintf("%d.%d.%d", versionMajor, versionMinor, versionPatch)
+ if versionMeta != "" {
+ verString += "-" + versionMeta
+ }
+ if gitCommit != "" {
+ verString += "-" + gitCommit[:8]
+ }
+ // Construct the version release oracle configuration
+ relConfig.Oracle = common.HexToAddress(versionOracle)
+
+ relConfig.Major = uint32(versionMajor)
+ relConfig.Minor = uint32(versionMinor)
+ relConfig.Patch = uint32(versionPatch)
+
+ commit, _ := hex.DecodeString(gitCommit)
+ copy(relConfig.Commit[:], commit)
+
+ // Initialize the CLI app and start Geth
+ app = utils.NewApp(verString, "the go-ethereum command line interface")
+ app.Action = geth
+ app.HideVersion = true // we have a command to print the version
+ app.Commands = []cli.Command{
+ importCommand,
+ exportCommand,
+ upgradedbCommand,
+ removedbCommand,
+ dumpCommand,
+ monitorCommand,
+ accountCommand,
+ walletCommand,
+ consoleCommand,
+ attachCommand,
+ javascriptCommand,
+ {
+ Action: makedag,
+ Name: "makedag",
+ Usage: "generate ethash dag (for testing)",
+ Description: `
+The makedag command generates an ethash DAG in /tmp/dag.
+
+This command exists to support the system testing project.
+Regular users do not need to execute it.
+`,
+ },
+ {
+ Action: gpuinfo,
+ Name: "gpuinfo",
+ Usage: "gpuinfo",
+ Description: `
+Prints OpenCL device info for all found GPUs.
+`,
+ },
+ {
+ Action: gpubench,
+ Name: "gpubench",
+ Usage: "benchmark GPU",
+ Description: `
+Runs quick benchmark on first GPU found.
+`,
+ },
+ {
+ Action: version,
+ Name: "version",
+ Usage: "print ethereum version numbers",
+ Description: `
+The output of this command is supposed to be machine-readable.
+`,
+ },
+ {
+ Action: initGenesis,
+ Name: "init",
+ Usage: "bootstraps and initialises a new genesis block (JSON)",
+ Description: `
+The init command initialises a new genesis block and definition for the network.
+This is a destructive action and changes the network in which you will be
+participating.
+`,
+ },
+ }
+
+ app.Flags = []cli.Flag{
+ utils.IdentityFlag,
+ utils.UnlockedAccountFlag,
+ utils.PasswordFileFlag,
+ utils.BootnodesFlag,
+ utils.DataDirFlag,
+ utils.KeyStoreDirFlag,
+ utils.BlockchainVersionFlag,
+ utils.OlympicFlag,
+ utils.FastSyncFlag,
+ utils.LightModeFlag,
+ utils.NoDefSrvFlag,
+ utils.LightServFlag,
+ utils.LightPeersFlag,
+ utils.CacheFlag,
+ utils.LightKDFFlag,
+ utils.JSpathFlag,
+ utils.ListenPortFlag,
+ utils.MaxPeersFlag,
+ utils.MaxPendingPeersFlag,
+ utils.EtherbaseFlag,
+ utils.GasPriceFlag,
+ utils.SupportDAOFork,
+ utils.OpposeDAOFork,
+ utils.MinerThreadsFlag,
+ utils.MiningEnabledFlag,
+ utils.MiningGPUFlag,
+ utils.AutoDAGFlag,
+ utils.TargetGasLimitFlag,
+ utils.NATFlag,
+ utils.NatspecEnabledFlag,
+ utils.NoDiscoverFlag,
+ utils.NoEthFlag,
+ utils.NodeKeyFileFlag,
+ utils.NodeKeyHexFlag,
+ utils.RPCEnabledFlag,
+ utils.RPCListenAddrFlag,
+ utils.RPCPortFlag,
+ utils.RPCApiFlag,
+ utils.WSEnabledFlag,
+ utils.WSListenAddrFlag,
+ utils.WSPortFlag,
+ utils.WSApiFlag,
+ utils.WSAllowedOriginsFlag,
+ utils.IPCDisabledFlag,
+ utils.IPCApiFlag,
+ utils.IPCPathFlag,
+ utils.ExecFlag,
+ utils.PreloadJSFlag,
+ utils.WhisperEnabledFlag,
+ utils.DevModeFlag,
+ utils.TestNetFlag,
+ utils.VMForceJitFlag,
+ utils.VMJitCacheFlag,
+ utils.VMEnableJitFlag,
+ utils.NetworkIdFlag,
+ utils.RPCCORSDomainFlag,
+ utils.MetricsEnabledFlag,
+ utils.FakePoWFlag,
+ utils.SolcPathFlag,
+ utils.GpoMinGasPriceFlag,
+ utils.GpoMaxGasPriceFlag,
+ utils.GpoFullBlockRatioFlag,
+ utils.GpobaseStepDownFlag,
+ utils.GpobaseStepUpFlag,
+ utils.GpobaseCorrectionFactorFlag,
+ utils.ExtraDataFlag,
+ }
+ app.Flags = append(app.Flags, debug.Flags...)
+
+ app.Before = func(ctx *cli.Context) error {
+ runtime.GOMAXPROCS(runtime.NumCPU())
+ if err := debug.Setup(ctx); err != nil {
+ return err
+ }
+ // Start system runtime metrics collection
+ go metrics.CollectProcessMetrics(3 * time.Second)
+
+ // This should be the only place where reporting is enabled
+ // because it is not intended to run while testing.
+ // In addition to this check, bad block reports are sent only
+ // for chains with the main network genesis block and network id 1.
+ eth.EnableBadBlockReporting = true
+
+ utils.SetupNetwork(ctx)
+ return nil
+ }
+
+ app.After = func(ctx *cli.Context) error {
+ logger.Flush()
+ debug.Exit()
+ console.Stdin.Close() // Resets terminal mode.
+ return nil
+ }
+}
+
+func main() {
+ if err := app.Run(os.Args); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func makeDefaultExtra() []byte {
+ var clientInfo = struct {
+ Version uint
+ Name string
+ GoVersion string
+ Os string
+ }{uint(versionMajor<<16 | versionMinor<<8 | versionPatch), clientIdentifier, runtime.Version(), runtime.GOOS}
+ extra, err := rlp.EncodeToBytes(clientInfo)
+ if err != nil {
+ glog.V(logger.Warn).Infoln("error setting canonical miner information:", err)
+ }
+
+ if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
+ glog.V(logger.Warn).Infoln("error setting canonical miner information: extra exceeds", params.MaximumExtraDataSize)
+ glog.V(logger.Debug).Infof("extra: %x\n", extra)
+ return nil
+ }
+ return extra
+}
+
+// geth is the main entry point into the system if no special subcommand is ran.
+// It creates a default node based on the command line arguments and runs it in
+// blocking mode, waiting for it to be shut down.
+func geth(ctx *cli.Context) error {
+ node, _ := utils.MakeSystemNode(clientIdentifier, verString, relConfig, makeDefaultExtra(), ctx)
+ startNode(ctx, node)
+ node.Wait()
+
+ return nil
+}
+
+// initGenesis will initialise the given JSON format genesis file and writes it as
+// the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
+func initGenesis(ctx *cli.Context) error {
+ genesisPath := ctx.Args().First()
+ if len(genesisPath) == 0 {
+ utils.Fatalf("must supply path to genesis JSON file")
+ }
+
+ chainDb, err := ethdb.NewLDBDatabase(filepath.Join(utils.MustMakeDataDir(ctx), utils.ChainDbName(ctx)), 0, 0)
+ if err != nil {
+ utils.Fatalf("could not open database: %v", err)
+ }
+
+ genesisFile, err := os.Open(genesisPath)
+ if err != nil {
+ utils.Fatalf("failed to read genesis file: %v", err)
+ }
+
+ block, err := core.WriteGenesisBlock(chainDb, genesisFile)
+ if err != nil {
+ utils.Fatalf("failed to write genesis block: %v", err)
+ }
+ glog.V(logger.Info).Infof("successfully wrote genesis block and/or chain rule set: %x", block.Hash())
+ return nil
+}
+
+// startNode boots up the system node and all registered protocols, after which
+// it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
+// miner.
+func startNode(ctx *cli.Context, stack *node.Node) {
+ // Report geth version
+ glog.V(logger.Info).Infof("instance: Geth/%s/%s/%s\n", verString, runtime.Version(), runtime.GOOS)
+ // Start up the node itself
+ utils.StartNode(stack)
+
+ if !ctx.GlobalBool(utils.NoEthFlag.Name) {
+ if ctx.GlobalBool(utils.LightModeFlag.Name) && !ctx.GlobalBool(utils.NoDefSrvFlag.Name) {
+ // add default light server; test phase only
+ url := "enode://201aa667e0b75462c8837708dbc3c91b43f84d233efda2f4e2c5ae0ea237d646db656375b394fb35d841cf8ea2814e3629af4821d3b0204508f7eb8cea8e7f31@40.118.3.223:30303"
+ if ctx.GlobalBool(utils.TestNetFlag.Name) {
+ url = "enode://2737bebb1e70cf682553c974d9551b74a917cb4f61292150abc10d2c122c8d369c82cb2b71ff107120ea2547419d2d9e998c637d45a6ff57bb01e83cfc1d5115@40.118.3.223:30304"
+ //url = "enode://2737bebb1e70cf682553c974d9551b74a917cb4f61292150abc10d2c122c8d369c82cb2b71ff107120ea2547419d2d9e998c637d45a6ff57bb01e83cfc1d5115@[::]:30303"
+ }
+ node, err := discover.ParseNode(url)
+ if err == nil {
+ stack.Server().AddPeer(node)
+ }
+ }
+
+ // Unlock any account specifically requested
+ var accman *accounts.Manager
+ if err := stack.Service(&accman); err != nil {
+ utils.Fatalf("ethereum service not running: %v", err)
+ }
+ passwords := utils.MakePasswordList(ctx)
+
+ accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
+ for i, account := range accounts {
+ if trimmed := strings.TrimSpace(account); trimmed != "" {
+ unlockAccount(ctx, accman, trimmed, i, passwords)
+ }
+ }
+ // Start auxiliary services if enabled
+ if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
+ var ethereum *eth.Ethereum
+ if err := stack.Service(ðereum); err != nil {
+ utils.Fatalf("ethereum service not running: %v", err)
+ }
+ if err := ethereum.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name), ctx.GlobalString(utils.MiningGPUFlag.Name)); err != nil {
+ utils.Fatalf("Failed to start mining: %v", err)
+ }
+ }
+ }
+}
+
+func makedag(ctx *cli.Context) error {
+ args := ctx.Args()
+ wrongArgs := func() {
+ utils.Fatalf(`Usage: geth makedag `)
+ }
+ switch {
+ case len(args) == 2:
+ blockNum, err := strconv.ParseUint(args[0], 0, 64)
+ dir := args[1]
+ if err != nil {
+ wrongArgs()
+ } else {
+ dir = filepath.Clean(dir)
+ // seems to require a trailing slash
+ if !strings.HasSuffix(dir, "/") {
+ dir = dir + "/"
+ }
+ _, err = ioutil.ReadDir(dir)
+ if err != nil {
+ utils.Fatalf("Can't find dir")
+ }
+ fmt.Println("making DAG, this could take awhile...")
+ ethash.MakeDAG(blockNum, dir)
+ }
+ default:
+ wrongArgs()
+ }
+ return nil
+}
+
+func gpuinfo(ctx *cli.Context) error {
+ eth.PrintOpenCLDevices()
+ return nil
+}
+
+func gpubench(ctx *cli.Context) error {
+ args := ctx.Args()
+ wrongArgs := func() {
+ utils.Fatalf(`Usage: geth gpubench `)
+ }
+ switch {
+ case len(args) == 1:
+ n, err := strconv.ParseUint(args[0], 0, 64)
+ if err != nil {
+ wrongArgs()
+ }
+ eth.GPUBench(n)
+ case len(args) == 0:
+ eth.GPUBench(0)
+ default:
+ wrongArgs()
+ }
+ return nil
+}
+
+func version(c *cli.Context) error {
+ fmt.Println(clientIdentifier)
+ fmt.Println("Version:", verString)
+ fmt.Println("Protocol Versions:", eth.ProtocolVersions)
+ fmt.Println("Network Id:", c.GlobalInt(utils.NetworkIdFlag.Name))
+ fmt.Println("Go Version:", runtime.Version())
+ fmt.Println("OS:", runtime.GOOS)
+ fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
+ fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
+
+ return nil
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/monitorcmd.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/monitorcmd.go
new file mode 100644
index 000000000..11fdca89c
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/monitorcmd.go
@@ -0,0 +1,369 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+package main
+
+import (
+ "fmt"
+ "math"
+ "reflect"
+ "runtime"
+ "strings"
+ "time"
+
+ "sort"
+
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/node"
+ "github.com/ethereum/go-ethereum/rpc"
+ "github.com/gizak/termui"
+ "gopkg.in/urfave/cli.v1"
+)
+
+var (
+ monitorCommandAttachFlag = cli.StringFlag{
+ Name: "attach",
+ Value: "ipc:" + node.DefaultIPCEndpoint(),
+ Usage: "API endpoint to attach to",
+ }
+ monitorCommandRowsFlag = cli.IntFlag{
+ Name: "rows",
+ Value: 5,
+ Usage: "Maximum rows in the chart grid",
+ }
+ monitorCommandRefreshFlag = cli.IntFlag{
+ Name: "refresh",
+ Value: 3,
+ Usage: "Refresh interval in seconds",
+ }
+ monitorCommand = cli.Command{
+ Action: monitor,
+ Name: "monitor",
+ Usage: `Geth Monitor: node metrics monitoring and visualization`,
+ Description: `
+The Geth monitor is a tool to collect and visualize various internal metrics
+gathered by the node, supporting different chart types as well as the capacity
+to display multiple metrics simultaneously.
+`,
+ Flags: []cli.Flag{
+ monitorCommandAttachFlag,
+ monitorCommandRowsFlag,
+ monitorCommandRefreshFlag,
+ },
+ }
+)
+
+// monitor starts a terminal UI based monitoring tool for the requested metrics.
+func monitor(ctx *cli.Context) error {
+ var (
+ client rpc.Client
+ err error
+ )
+ // Attach to an Ethereum node over IPC or RPC
+ endpoint := ctx.String(monitorCommandAttachFlag.Name)
+ if client, err = utils.NewRemoteRPCClientFromString(endpoint); err != nil {
+ utils.Fatalf("Unable to attach to geth node: %v", err)
+ }
+ defer client.Close()
+
+ // Retrieve all the available metrics and resolve the user pattens
+ metrics, err := retrieveMetrics(client)
+ if err != nil {
+ utils.Fatalf("Failed to retrieve system metrics: %v", err)
+ }
+ monitored := resolveMetrics(metrics, ctx.Args())
+ if len(monitored) == 0 {
+ list := expandMetrics(metrics, "")
+ sort.Strings(list)
+
+ if len(list) > 0 {
+ utils.Fatalf("No metrics specified.\n\nAvailable:\n - %s", strings.Join(list, "\n - "))
+ } else {
+ utils.Fatalf("No metrics collected by geth (--%s).\n", utils.MetricsEnabledFlag.Name)
+ }
+ }
+ sort.Strings(monitored)
+ if cols := len(monitored) / ctx.Int(monitorCommandRowsFlag.Name); cols > 6 {
+ utils.Fatalf("Requested metrics (%d) spans more that 6 columns:\n - %s", len(monitored), strings.Join(monitored, "\n - "))
+ }
+ // Create and configure the chart UI defaults
+ if err := termui.Init(); err != nil {
+ utils.Fatalf("Unable to initialize terminal UI: %v", err)
+ }
+ defer termui.Close()
+
+ rows := len(monitored)
+ if max := ctx.Int(monitorCommandRowsFlag.Name); rows > max {
+ rows = max
+ }
+ cols := (len(monitored) + rows - 1) / rows
+ for i := 0; i < rows; i++ {
+ termui.Body.AddRows(termui.NewRow())
+ }
+ // Create each individual data chart
+ footer := termui.NewPar("")
+ footer.Block.Border = true
+ footer.Height = 3
+
+ charts := make([]*termui.LineChart, len(monitored))
+ units := make([]int, len(monitored))
+ data := make([][]float64, len(monitored))
+ for i := 0; i < len(monitored); i++ {
+ charts[i] = createChart((termui.TermHeight() - footer.Height) / rows)
+ row := termui.Body.Rows[i%rows]
+ row.Cols = append(row.Cols, termui.NewCol(12/cols, 0, charts[i]))
+ }
+ termui.Body.AddRows(termui.NewRow(termui.NewCol(12, 0, footer)))
+
+ refreshCharts(client, monitored, data, units, charts, ctx, footer)
+ termui.Body.Align()
+ termui.Render(termui.Body)
+
+ // Watch for various system events, and periodically refresh the charts
+ termui.Handle("/sys/kbd/C-c", func(termui.Event) {
+ termui.StopLoop()
+ })
+ termui.Handle("/sys/wnd/resize", func(termui.Event) {
+ termui.Body.Width = termui.TermWidth()
+ for _, chart := range charts {
+ chart.Height = (termui.TermHeight() - footer.Height) / rows
+ }
+ termui.Body.Align()
+ termui.Render(termui.Body)
+ })
+ go func() {
+ tick := time.NewTicker(time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second)
+ for range tick.C {
+ if refreshCharts(client, monitored, data, units, charts, ctx, footer) {
+ termui.Body.Align()
+ }
+ termui.Render(termui.Body)
+ }
+ }()
+ termui.Loop()
+ return nil
+}
+
+// retrieveMetrics contacts the attached geth node and retrieves the entire set
+// of collected system metrics.
+func retrieveMetrics(client rpc.Client) (map[string]interface{}, error) {
+ req := map[string]interface{}{
+ "id": new(int64),
+ "method": "debug_metrics",
+ "jsonrpc": "2.0",
+ "params": []interface{}{true},
+ }
+
+ if err := client.Send(req); err != nil {
+ return nil, err
+ }
+
+ var res rpc.JSONSuccessResponse
+ if err := client.Recv(&res); err != nil {
+ return nil, err
+ }
+
+ if res.Result != nil {
+ if mets, ok := res.Result.(map[string]interface{}); ok {
+ return mets, nil
+ }
+ }
+
+ return nil, fmt.Errorf("unable to retrieve metrics")
+}
+
+// resolveMetrics takes a list of input metric patterns, and resolves each to one
+// or more canonical metric names.
+func resolveMetrics(metrics map[string]interface{}, patterns []string) []string {
+ res := []string{}
+ for _, pattern := range patterns {
+ res = append(res, resolveMetric(metrics, pattern, "")...)
+ }
+ return res
+}
+
+// resolveMetrics takes a single of input metric pattern, and resolves it to one
+// or more canonical metric names.
+func resolveMetric(metrics map[string]interface{}, pattern string, path string) []string {
+ results := []string{}
+
+ // If a nested metric was requested, recurse optionally branching (via comma)
+ parts := strings.SplitN(pattern, "/", 2)
+ if len(parts) > 1 {
+ for _, variation := range strings.Split(parts[0], ",") {
+ if submetrics, ok := metrics[variation].(map[string]interface{}); !ok {
+ utils.Fatalf("Failed to retrieve system metrics: %s", path+variation)
+ return nil
+ } else {
+ results = append(results, resolveMetric(submetrics, parts[1], path+variation+"/")...)
+ }
+ }
+ return results
+ }
+ // Depending what the last link is, return or expand
+ for _, variation := range strings.Split(pattern, ",") {
+ switch metric := metrics[variation].(type) {
+ case float64:
+ // Final metric value found, return as singleton
+ results = append(results, path+variation)
+
+ case map[string]interface{}:
+ results = append(results, expandMetrics(metric, path+variation+"/")...)
+
+ default:
+ utils.Fatalf("Metric pattern resolved to unexpected type: %v", reflect.TypeOf(metric))
+ return nil
+ }
+ }
+ return results
+}
+
+// expandMetrics expands the entire tree of metrics into a flat list of paths.
+func expandMetrics(metrics map[string]interface{}, path string) []string {
+ // Iterate over all fields and expand individually
+ list := []string{}
+ for name, metric := range metrics {
+ switch metric := metric.(type) {
+ case float64:
+ // Final metric value found, append to list
+ list = append(list, path+name)
+
+ case map[string]interface{}:
+ // Tree of metrics found, expand recursively
+ list = append(list, expandMetrics(metric, path+name+"/")...)
+
+ default:
+ utils.Fatalf("Metric pattern %s resolved to unexpected type: %v", path+name, reflect.TypeOf(metric))
+ return nil
+ }
+ }
+ return list
+}
+
+// fetchMetric iterates over the metrics map and retrieves a specific one.
+func fetchMetric(metrics map[string]interface{}, metric string) float64 {
+ parts, found := strings.Split(metric, "/"), true
+ for _, part := range parts[:len(parts)-1] {
+ metrics, found = metrics[part].(map[string]interface{})
+ if !found {
+ return 0
+ }
+ }
+ if v, ok := metrics[parts[len(parts)-1]].(float64); ok {
+ return v
+ }
+ return 0
+}
+
+// refreshCharts retrieves a next batch of metrics, and inserts all the new
+// values into the active datasets and charts
+func refreshCharts(client rpc.Client, metrics []string, data [][]float64, units []int, charts []*termui.LineChart, ctx *cli.Context, footer *termui.Par) (realign bool) {
+ values, err := retrieveMetrics(client)
+ for i, metric := range metrics {
+ if len(data) < 512 {
+ data[i] = append([]float64{fetchMetric(values, metric)}, data[i]...)
+ } else {
+ data[i] = append([]float64{fetchMetric(values, metric)}, data[i][:len(data[i])-1]...)
+ }
+ if updateChart(metric, data[i], &units[i], charts[i], err) {
+ realign = true
+ }
+ }
+ updateFooter(ctx, err, footer)
+ return
+}
+
+// updateChart inserts a dataset into a line chart, scaling appropriately as to
+// not display weird labels, also updating the chart label accordingly.
+func updateChart(metric string, data []float64, base *int, chart *termui.LineChart, err error) (realign bool) {
+ dataUnits := []string{"", "K", "M", "G", "T", "E"}
+ timeUnits := []string{"ns", "µs", "ms", "s", "ks", "ms"}
+ colors := []termui.Attribute{termui.ColorBlue, termui.ColorCyan, termui.ColorGreen, termui.ColorYellow, termui.ColorRed, termui.ColorRed}
+
+ // Extract only part of the data that's actually visible
+ if chart.Width*2 < len(data) {
+ data = data[:chart.Width*2]
+ }
+ // Find the maximum value and scale under 1K
+ high := 0.0
+ if len(data) > 0 {
+ high = data[0]
+ for _, value := range data[1:] {
+ high = math.Max(high, value)
+ }
+ }
+ unit, scale := 0, 1.0
+ for high >= 1000 && unit+1 < len(dataUnits) {
+ high, unit, scale = high/1000, unit+1, scale*1000
+ }
+ // If the unit changes, re-create the chart (hack to set max height...)
+ if unit != *base {
+ realign, *base, *chart = true, unit, *createChart(chart.Height)
+ }
+ // Update the chart's data points with the scaled values
+ if cap(chart.Data) < len(data) {
+ chart.Data = make([]float64, len(data))
+ }
+ chart.Data = chart.Data[:len(data)]
+ for i, value := range data {
+ chart.Data[i] = value / scale
+ }
+ // Update the chart's label with the scale units
+ units := dataUnits
+ if strings.Contains(metric, "/Percentiles/") || strings.Contains(metric, "/pauses/") || strings.Contains(metric, "/time/") {
+ units = timeUnits
+ }
+ chart.BorderLabel = metric
+ if len(units[unit]) > 0 {
+ chart.BorderLabel += " [" + units[unit] + "]"
+ }
+ chart.LineColor = colors[unit] | termui.AttrBold
+ if err != nil {
+ chart.LineColor = termui.ColorRed | termui.AttrBold
+ }
+ return
+}
+
+// createChart creates an empty line chart with the default configs.
+func createChart(height int) *termui.LineChart {
+ chart := termui.NewLineChart()
+ if runtime.GOOS == "windows" {
+ chart.Mode = "dot"
+ }
+ chart.DataLabels = []string{""}
+ chart.Height = height
+ chart.AxesColor = termui.ColorWhite
+ chart.PaddingBottom = -2
+
+ chart.BorderLabelFg = chart.BorderFg | termui.AttrBold
+ chart.BorderFg = chart.BorderBg
+
+ return chart
+}
+
+// updateFooter updates the footer contents based on any encountered errors.
+func updateFooter(ctx *cli.Context, err error, footer *termui.Par) {
+ // Generate the basic footer
+ refresh := time.Duration(ctx.Int(monitorCommandRefreshFlag.Name)) * time.Second
+ footer.Text = fmt.Sprintf("Press Ctrl+C to quit. Refresh interval: %v.", refresh)
+ footer.TextFgColor = termui.ThemeAttr("par.fg") | termui.AttrBold
+
+ // Append any encountered errors
+ if err != nil {
+ footer.Text = fmt.Sprintf("Error: %v.", err)
+ footer.TextFgColor = termui.ColorRed | termui.AttrBold
+ }
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/usage.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/usage.go
new file mode 100644
index 000000000..9d1b5c19a
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/geth/usage.go
@@ -0,0 +1,220 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// Contains the geth command usage template and generator.
+
+package main
+
+import (
+ "io"
+
+ "github.com/ethereum/go-ethereum/cmd/utils"
+ "github.com/ethereum/go-ethereum/internal/debug"
+ "gopkg.in/urfave/cli.v1"
+)
+
+// AppHelpTemplate is the test template for the default, global app help topic.
+var AppHelpTemplate = `NAME:
+ {{.App.Name}} - {{.App.Usage}}
+
+USAGE:
+ {{.App.HelpName}} [options]{{if .App.Commands}} command [command options]{{end}} {{if .App.ArgsUsage}}{{.App.ArgsUsage}}{{else}}[arguments...]{{end}}
+ {{if .App.Version}}
+VERSION:
+ {{.App.Version}}
+ {{end}}{{if len .App.Authors}}
+AUTHOR(S):
+ {{range .App.Authors}}{{ . }}{{end}}
+ {{end}}{{if .App.Commands}}
+COMMANDS:
+ {{range .App.Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
+ {{end}}{{end}}{{if .FlagGroups}}
+{{range .FlagGroups}}{{.Name}} OPTIONS:
+ {{range .Flags}}{{.}}
+ {{end}}
+{{end}}{{end}}{{if .App.Copyright }}
+COPYRIGHT:
+ {{.App.Copyright}}
+ {{end}}
+`
+
+// flagGroup is a collection of flags belonging to a single topic.
+type flagGroup struct {
+ Name string
+ Flags []cli.Flag
+}
+
+// AppHelpFlagGroups is the application flags, grouped by functionality.
+var AppHelpFlagGroups = []flagGroup{
+ {
+ Name: "ETHEREUM",
+ Flags: []cli.Flag{
+ utils.DataDirFlag,
+ utils.KeyStoreDirFlag,
+ utils.NetworkIdFlag,
+ utils.OlympicFlag,
+ utils.TestNetFlag,
+ utils.DevModeFlag,
+ utils.IdentityFlag,
+ utils.FastSyncFlag,
+ utils.LightModeFlag,
+ utils.NoDefSrvFlag,
+ utils.LightServFlag,
+ utils.LightPeersFlag,
+ utils.LightKDFFlag,
+ utils.CacheFlag,
+ utils.BlockchainVersionFlag,
+ },
+ },
+ {
+ Name: "ACCOUNT",
+ Flags: []cli.Flag{
+ utils.UnlockedAccountFlag,
+ utils.PasswordFileFlag,
+ },
+ },
+ {
+ Name: "API AND CONSOLE",
+ Flags: []cli.Flag{
+ utils.RPCEnabledFlag,
+ utils.RPCListenAddrFlag,
+ utils.RPCPortFlag,
+ utils.RPCApiFlag,
+ utils.WSEnabledFlag,
+ utils.WSListenAddrFlag,
+ utils.WSPortFlag,
+ utils.WSApiFlag,
+ utils.WSAllowedOriginsFlag,
+ utils.IPCDisabledFlag,
+ utils.IPCApiFlag,
+ utils.IPCPathFlag,
+ utils.RPCCORSDomainFlag,
+ utils.JSpathFlag,
+ utils.ExecFlag,
+ utils.PreloadJSFlag,
+ },
+ },
+ {
+ Name: "NETWORKING",
+ Flags: []cli.Flag{
+ utils.BootnodesFlag,
+ utils.ListenPortFlag,
+ utils.MaxPeersFlag,
+ utils.MaxPendingPeersFlag,
+ utils.NATFlag,
+ utils.NoDiscoverFlag,
+ utils.NodeKeyFileFlag,
+ utils.NodeKeyHexFlag,
+ },
+ },
+ {
+ Name: "MINER",
+ Flags: []cli.Flag{
+ utils.MiningEnabledFlag,
+ utils.MinerThreadsFlag,
+ utils.MiningGPUFlag,
+ utils.AutoDAGFlag,
+ utils.EtherbaseFlag,
+ utils.TargetGasLimitFlag,
+ utils.GasPriceFlag,
+ utils.ExtraDataFlag,
+ },
+ },
+ {
+ Name: "GAS PRICE ORACLE",
+ Flags: []cli.Flag{
+ utils.GpoMinGasPriceFlag,
+ utils.GpoMaxGasPriceFlag,
+ utils.GpoFullBlockRatioFlag,
+ utils.GpobaseStepDownFlag,
+ utils.GpobaseStepUpFlag,
+ utils.GpobaseCorrectionFactorFlag,
+ },
+ },
+ {
+ Name: "VIRTUAL MACHINE",
+ Flags: []cli.Flag{
+ utils.VMEnableJitFlag,
+ utils.VMForceJitFlag,
+ utils.VMJitCacheFlag,
+ },
+ },
+ {
+ Name: "LOGGING AND DEBUGGING",
+ Flags: append([]cli.Flag{
+ utils.MetricsEnabledFlag,
+ utils.FakePoWFlag,
+ }, debug.Flags...),
+ },
+ {
+ Name: "EXPERIMENTAL",
+ Flags: []cli.Flag{
+ utils.WhisperEnabledFlag,
+ utils.NatspecEnabledFlag,
+ utils.NoEthFlag,
+ },
+ },
+ {
+ Name: "MISCELLANEOUS",
+ Flags: []cli.Flag{
+ utils.SolcPathFlag,
+ },
+ },
+}
+
+func init() {
+ // Override the default app help template
+ cli.AppHelpTemplate = AppHelpTemplate
+
+ // Define a one shot struct to pass to the usage template
+ type helpData struct {
+ App interface{}
+ FlagGroups []flagGroup
+ }
+ // Override the default app help printer, but only for the global app help
+ originalHelpPrinter := cli.HelpPrinter
+ cli.HelpPrinter = func(w io.Writer, tmpl string, data interface{}) {
+ if tmpl == AppHelpTemplate {
+ // Iterate over all the flags and add any uncategorized ones
+ categorized := make(map[string]struct{})
+ for _, group := range AppHelpFlagGroups {
+ for _, flag := range group.Flags {
+ categorized[flag.String()] = struct{}{}
+ }
+ }
+ uncategorized := []cli.Flag{}
+ for _, flag := range data.(*cli.App).Flags {
+ if _, ok := categorized[flag.String()]; !ok {
+ uncategorized = append(uncategorized, flag)
+ }
+ }
+ if len(uncategorized) > 0 {
+ // Append all ungategorized options to the misc group
+ miscs := len(AppHelpFlagGroups[len(AppHelpFlagGroups)-1].Flags)
+ AppHelpFlagGroups[len(AppHelpFlagGroups)-1].Flags = append(AppHelpFlagGroups[len(AppHelpFlagGroups)-1].Flags, uncategorized...)
+
+ // Make sure they are removed afterwards
+ defer func() {
+ AppHelpFlagGroups[len(AppHelpFlagGroups)-1].Flags = AppHelpFlagGroups[len(AppHelpFlagGroups)-1].Flags[:miscs]
+ }()
+ }
+ // Render out custom usage screen
+ originalHelpPrinter(w, tmpl, helpData{data, AppHelpFlagGroups})
+ } else {
+ originalHelpPrinter(w, tmpl, data)
+ }
+ }
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/gethrpctest/main.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/gethrpctest/main.go
new file mode 100644
index 000000000..2e07e9426
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/gethrpctest/main.go
@@ -0,0 +1,170 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// gethrpctest is a command to run the external RPC tests.
+package main
+
+import (
+ "flag"
+ "io/ioutil"
+ "log"
+ "os"
+ "os/signal"
+
+ "github.com/ethereum/go-ethereum/accounts"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/eth"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/logger/glog"
+ "github.com/ethereum/go-ethereum/node"
+ "github.com/ethereum/go-ethereum/params"
+ "github.com/ethereum/go-ethereum/tests"
+ "github.com/ethereum/go-ethereum/whisper"
+)
+
+const defaultTestKey = "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"
+
+var (
+ testFile = flag.String("json", "", "Path to the .json test file to load")
+ testName = flag.String("test", "", "Name of the test from the .json file to run")
+ testKey = flag.String("key", defaultTestKey, "Private key of a test account to inject")
+)
+
+func main() {
+ flag.Parse()
+
+ // Enable logging errors, we really do want to see those
+ glog.SetV(2)
+ glog.SetToStderr(true)
+
+ // Load the test suite to run the RPC against
+ tests, err := tests.LoadBlockTests(*testFile)
+ if err != nil {
+ log.Fatalf("Failed to load test suite: %v", err)
+ }
+ test, found := tests[*testName]
+ if !found {
+ log.Fatalf("Requested test (%s) not found within suite", *testName)
+ }
+ // Create the protocol stack to run the test with
+ keydir, err := ioutil.TempDir("", "")
+ if err != nil {
+ log.Fatalf("Failed to create temporary keystore directory: %v", err)
+ }
+ defer os.RemoveAll(keydir)
+
+ stack, err := MakeSystemNode(keydir, *testKey, test)
+ if err != nil {
+ log.Fatalf("Failed to assemble test stack: %v", err)
+ }
+ if err := stack.Start(); err != nil {
+ log.Fatalf("Failed to start test node: %v", err)
+ }
+ defer stack.Stop()
+
+ log.Println("Test node started...")
+
+ // Make sure the tests contained within the suite pass
+ if err := RunTest(stack, test); err != nil {
+ log.Fatalf("Failed to run the pre-configured test: %v", err)
+ }
+ log.Println("Initial test suite passed...")
+
+ quit := make(chan os.Signal, 1)
+ signal.Notify(quit, os.Interrupt)
+ <-quit
+}
+
+// MakeSystemNode configures a protocol stack for the RPC tests based on a given
+// keystore path and initial pre-state.
+func MakeSystemNode(keydir string, privkey string, test *tests.BlockTest) (*node.Node, error) {
+ // Create a networkless protocol stack
+ stack, err := node.New(&node.Config{
+ IPCPath: node.DefaultIPCEndpoint(),
+ HTTPHost: common.DefaultHTTPHost,
+ HTTPPort: common.DefaultHTTPPort,
+ HTTPModules: []string{"admin", "db", "eth", "debug", "miner", "net", "shh", "txpool", "personal", "web3"},
+ WSHost: common.DefaultWSHost,
+ WSPort: common.DefaultWSPort,
+ WSModules: []string{"admin", "db", "eth", "debug", "miner", "net", "shh", "txpool", "personal", "web3"},
+ NoDiscovery: true,
+ })
+ if err != nil {
+ return nil, err
+ }
+ // Create the keystore and inject an unlocked account if requested
+ accman := accounts.NewPlaintextManager(keydir)
+ if len(privkey) > 0 {
+ key, err := crypto.HexToECDSA(privkey)
+ if err != nil {
+ return nil, err
+ }
+ a, err := accman.ImportECDSA(key, "")
+ if err != nil {
+ return nil, err
+ }
+ if err := accman.Unlock(a, ""); err != nil {
+ return nil, err
+ }
+ }
+ // Initialize and register the Ethereum protocol
+ db, _ := ethdb.NewMemDatabase()
+ if _, err := test.InsertPreState(db); err != nil {
+ return nil, err
+ }
+ ethConf := ð.Config{
+ TestGenesisState: db,
+ TestGenesisBlock: test.Genesis,
+ ChainConfig: &core.ChainConfig{HomesteadBlock: params.MainNetHomesteadBlock},
+ AccountManager: accman,
+ }
+ if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
+ return nil, err
+ }
+ // Initialize and register the Whisper protocol
+ if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
+ return nil, err
+ }
+ return stack, nil
+}
+
+// RunTest executes the specified test against an already pre-configured protocol
+// stack to ensure basic checks pass before running RPC tests.
+func RunTest(stack *node.Node, test *tests.BlockTest) error {
+ var ethereum *eth.Ethereum
+ stack.Service(ðereum)
+ blockchain := ethereum.BlockChain()
+
+ // Process the blocks and verify the imported headers
+ blocks, err := test.TryBlocksInsert(blockchain)
+ if err != nil {
+ return err
+ }
+ if err := test.ValidateImportedHeaders(blockchain, blocks); err != nil {
+ return err
+ }
+ // Retrieve the assembled state and validate it
+ stateDb, err := blockchain.State()
+ if err != nil {
+ return err
+ }
+ if err := test.ValidatePostState(stateDb); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/rlpdump/main.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/rlpdump/main.go
new file mode 100644
index 000000000..10eea1fde
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/rlpdump/main.go
@@ -0,0 +1,143 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of go-ethereum.
+//
+// go-ethereum is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// go-ethereum is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with go-ethereum. If not, see .
+
+// rlpdump is a pretty-printer for RLP data.
+package main
+
+import (
+ "bytes"
+ "encoding/hex"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/ethereum/go-ethereum/rlp"
+)
+
+var (
+ hexMode = flag.String("hex", "", "dump given hex data")
+ noASCII = flag.Bool("noascii", false, "don't print ASCII strings readably")
+)
+
+func init() {
+ flag.Usage = func() {
+ fmt.Fprintln(os.Stderr, "Usage:", os.Args[0], "[-noascii] [-hex ] [filename]")
+ flag.PrintDefaults()
+ fmt.Fprintln(os.Stderr, `
+Dumps RLP data from the given file in readable form.
+If the filename is omitted, data is read from stdin.`)
+ }
+}
+
+func main() {
+ flag.Parse()
+
+ var r io.Reader
+ switch {
+ case *hexMode != "":
+ data, err := hex.DecodeString(*hexMode)
+ if err != nil {
+ die(err)
+ }
+ r = bytes.NewReader(data)
+
+ case flag.NArg() == 0:
+ r = os.Stdin
+
+ case flag.NArg() == 1:
+ fd, err := os.Open(flag.Arg(0))
+ if err != nil {
+ die(err)
+ }
+ defer fd.Close()
+ r = fd
+
+ default:
+ fmt.Fprintln(os.Stderr, "Error: too many arguments")
+ flag.Usage()
+ os.Exit(2)
+ }
+
+ s := rlp.NewStream(r, 0)
+ for {
+ if err := dump(s, 0); err != nil {
+ if err != io.EOF {
+ die(err)
+ }
+ break
+ }
+ fmt.Println()
+ }
+}
+
+func dump(s *rlp.Stream, depth int) error {
+ kind, size, err := s.Kind()
+ if err != nil {
+ return err
+ }
+ switch kind {
+ case rlp.Byte, rlp.String:
+ str, err := s.Bytes()
+ if err != nil {
+ return err
+ }
+ if len(str) == 0 || !*noASCII && isASCII(str) {
+ fmt.Printf("%s%q", ws(depth), str)
+ } else {
+ fmt.Printf("%s%x", ws(depth), str)
+ }
+ case rlp.List:
+ s.List()
+ defer s.ListEnd()
+ if size == 0 {
+ fmt.Print(ws(depth) + "[]")
+ } else {
+ fmt.Println(ws(depth) + "[")
+ for i := 0; ; i++ {
+ if i > 0 {
+ fmt.Print(",\n")
+ }
+ if err := dump(s, depth+1); err == rlp.EOL {
+ break
+ } else if err != nil {
+ return err
+ }
+ }
+ fmt.Print(ws(depth) + "]")
+ }
+ }
+ return nil
+}
+
+func isASCII(b []byte) bool {
+ for _, c := range b {
+ if c < 32 || c > 126 {
+ return false
+ }
+ }
+ return true
+}
+
+func ws(n int) string {
+ return strings.Repeat(" ", n)
+}
+
+func die(args ...interface{}) {
+ fmt.Fprintln(os.Stderr, args...)
+ os.Exit(1)
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/cmd.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/cmd.go
index 9e2b14f56..3b521a0e1 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/cmd.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/cmd.go
@@ -120,7 +120,7 @@ func ImportChain(chain *core.BlockChain, fn string) error {
}
}
- glog.Infoln("Importing blockchain", fn)
+ glog.Infoln("Importing blockchain ", fn)
fh, err := os.Open(fn)
if err != nil {
return err
@@ -182,7 +182,7 @@ func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
}
func ExportChain(blockchain *core.BlockChain, fn string) error {
- glog.Infoln("Exporting blockchain to", fn)
+ glog.Infoln("Exporting blockchain to ", fn)
fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
if err != nil {
return err
@@ -191,12 +191,12 @@ func ExportChain(blockchain *core.BlockChain, fn string) error {
if err := blockchain.Export(fh); err != nil {
return err
}
- glog.Infoln("Exported blockchain to", fn)
+ glog.Infoln("Exported blockchain to ", fn)
return nil
}
func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, last uint64) error {
- glog.Infoln("Exporting blockchain to", fn)
+ glog.Infoln("Exporting blockchain to ", fn)
// TODO verify mode perms
fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil {
@@ -206,6 +206,6 @@ func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, las
if err := blockchain.ExportN(fh, first, last); err != nil {
return err
}
- glog.Infoln("Exported blockchain to", fn)
+ glog.Infoln("Exported blockchain to ", fn)
return nil
}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/flags.go b/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/flags.go
index 378baad21..82a2fceed 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/flags.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/cmd/utils/flags.go
@@ -129,10 +129,6 @@ var (
Name: "dev",
Usage: "Developer mode: pre-configured private network with several debugging flags",
}
- GenesisFileFlag = cli.StringFlag{
- Name: "genesis",
- Usage: "Insert/overwrite the genesis block (JSON format)",
- }
IdentityFlag = cli.StringFlag{
Name: "identity",
Usage: "Custom node name",
@@ -164,6 +160,10 @@ var (
Name: "light",
Usage: "Enable light client mode",
}
+ NoDefSrvFlag = cli.BoolFlag{
+ Name: "nodefsrv",
+ Usage: "Don't add default LES server (only for test version)",
+ }
LightServFlag = cli.IntFlag{
Name: "lightserv",
Usage: "Maximum percentage of time allowed for serving LES requests (0-90)",
@@ -178,6 +178,15 @@ var (
Name: "lightkdf",
Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
}
+ // Fork settings
+ SupportDAOFork = cli.BoolFlag{
+ Name: "support-dao-fork",
+ Usage: "Updates the chain rules to support the DAO hard-fork",
+ }
+ OpposeDAOFork = cli.BoolFlag{
+ Name: "oppose-dao-fork",
+ Usage: "Updates the chain rules to oppose the DAO hard-fork",
+ }
// Miner settings
// TODO: refactor CPU vs GPU mining flags
MiningEnabledFlag = cli.BoolFlag{
@@ -562,20 +571,6 @@ func MakeWSRpcHost(ctx *cli.Context) string {
return ctx.GlobalString(WSListenAddrFlag.Name)
}
-// MakeGenesisBlock loads up a genesis block from an input file specified in the
-// command line, or returns the empty string if none set.
-func MakeGenesisBlock(ctx *cli.Context) string {
- genesis := ctx.GlobalString(GenesisFileFlag.Name)
- if genesis == "" {
- return ""
- }
- data, err := ioutil.ReadFile(genesis)
- if err != nil {
- Fatalf("Failed to load custom genesis file: %v", err)
- }
- return string(data)
-}
-
// MakeDatabaseHandles raises out the number of allowed file handles per process
// for Geth and returns half of the allowance to assign to the database.
func MakeDatabaseHandles() int {
@@ -718,9 +713,9 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
ethConf := ð.Config{
ChainConfig: MustMakeChainConfig(ctx),
- Genesis: MakeGenesisBlock(ctx),
FastSync: ctx.GlobalBool(FastSyncFlag.Name),
LightMode: ctx.GlobalBool(LightModeFlag.Name),
+ NoDefSrv: ctx.GlobalBool(NoDefSrvFlag.Name),
LightServ: ctx.GlobalInt(LightServFlag.Name),
LightPeers: ctx.GlobalInt(LightPeersFlag.Name),
BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
@@ -745,6 +740,7 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
SolcPath: ctx.GlobalString(SolcPathFlag.Name),
AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
}
+
// Configure the Whisper service
shhEnable := ctx.GlobalBool(WhisperEnabledFlag.Name)
@@ -757,17 +753,13 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
ethConf.NetworkId = 1
}
- if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
- ethConf.Genesis = core.OlympicGenesisBlock()
- }
+ ethConf.Genesis = core.OlympicGenesisBlock()
case ctx.GlobalBool(TestNetFlag.Name):
if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
ethConf.NetworkId = 2
}
- if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
- ethConf.Genesis = core.TestNetGenesisBlock()
- }
+ ethConf.Genesis = core.TestNetGenesisBlock()
state.StartingNonce = 1048576 // (2**20)
light.StartingNonce = 1048576 // (2**20)
@@ -783,9 +775,7 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
stackConf.ListenAddr = ":0"
}
// Override the Ethereum protocol configs
- if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
- ethConf.Genesis = core.OlympicGenesisBlock()
- }
+ ethConf.Genesis = core.OlympicGenesisBlock()
if !ctx.GlobalIsSet(GasPriceFlag.Name) {
ethConf.GasPrice = new(big.Int)
}
@@ -872,24 +862,62 @@ func MustMakeChainConfig(ctx *cli.Context) *core.ChainConfig {
// MustMakeChainConfigFromDb reads the chain configuration from the given database.
func MustMakeChainConfigFromDb(ctx *cli.Context, db ethdb.Database) *core.ChainConfig {
- genesis := core.GetBlock(db, core.GetCanonicalHash(db, 0), 0)
+ // If the chain is already initialized, use any existing chain configs
+ config := new(core.ChainConfig)
+ genesis := core.GetBlock(db, core.GetCanonicalHash(db, 0), 0)
if genesis != nil {
- // Existing genesis block, use stored config if available.
storedConfig, err := core.GetChainConfig(db, genesis.Hash())
- if err == nil {
- return storedConfig
- } else if err != core.ChainConfigNotFoundErr {
+ switch err {
+ case nil:
+ config = storedConfig
+ case core.ChainConfigNotFoundErr:
+ // No configs found, use empty, will populate below
+ default:
Fatalf("Could not make chain configuration: %v", err)
}
}
- var homesteadBlockNo *big.Int
- if ctx.GlobalBool(TestNetFlag.Name) {
- homesteadBlockNo = params.TestNetHomesteadBlock
- } else {
- homesteadBlockNo = params.MainNetHomesteadBlock
+ // Set any missing fields due to them being unset or system upgrade
+ if config.HomesteadBlock == nil {
+ if ctx.GlobalBool(TestNetFlag.Name) {
+ config.HomesteadBlock = params.TestNetHomesteadBlock
+ } else {
+ config.HomesteadBlock = params.MainNetHomesteadBlock
+ }
}
- return &core.ChainConfig{HomesteadBlock: homesteadBlockNo}
+ if config.DAOForkBlock == nil {
+ if ctx.GlobalBool(TestNetFlag.Name) {
+ config.DAOForkBlock = params.TestNetDAOForkBlock
+ } else {
+ config.DAOForkBlock = params.MainNetDAOForkBlock
+ }
+ config.DAOForkSupport = true
+ }
+ // Force override any existing configs if explicitly requested
+ switch {
+ case ctx.GlobalBool(SupportDAOFork.Name):
+ config.DAOForkSupport = true
+ case ctx.GlobalBool(OpposeDAOFork.Name):
+ config.DAOForkSupport = false
+ }
+ // Temporarilly display a proper message so the user knows which fork its on
+ if !ctx.GlobalBool(TestNetFlag.Name) && (genesis == nil || genesis.Hash() == common.HexToHash("0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3")) {
+ choice := "SUPPORT"
+ if !config.DAOForkSupport {
+ choice = "OPPOSE"
+ }
+ current := fmt.Sprintf("Geth is currently configured to %s the DAO hard-fork!", choice)
+ howtoswap := fmt.Sprintf("You can change your choice prior to block #%v with --support-dao-fork or --oppose-dao-fork.", config.DAOForkBlock)
+ howtosync := fmt.Sprintf("After the hard-fork block #%v passed, changing chains requires a resync from scratch!", config.DAOForkBlock)
+ separator := strings.Repeat("-", len(howtoswap))
+
+ glog.V(logger.Warn).Info(separator)
+ glog.V(logger.Warn).Info(current)
+ glog.V(logger.Warn).Info(howtoswap)
+ glog.V(logger.Warn).Info(howtosync)
+ glog.V(logger.Warn).Info(separator)
+ }
+ return config
}
func ChainDbName(ctx *cli.Context) string {
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/.gitignore b/src/vendor/github.com/ethereum/go-ethereum/common/.gitignore
deleted file mode 100644
index f725d58d1..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/common/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-# See http://help.github.com/ignore-files/ for more about ignoring files.
-#
-# If you find yourself ignoring temporary files generated by your text editor
-# or operating system, you probably want to add a global ignore instead:
-# git config --global core.excludesfile ~/.gitignore_global
-
-/tmp
-*/**/*un~
-*un~
-.DS_Store
-*/**/.DS_Store
-
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/.travis.yml b/src/vendor/github.com/ethereum/go-ethereum/common/.travis.yml
deleted file mode 100644
index 69359072d..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/common/.travis.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-language: go
-go:
- - 1.2
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/README.md b/src/vendor/github.com/ethereum/go-ethereum/common/README.md
deleted file mode 100644
index adea022b7..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/common/README.md
+++ /dev/null
@@ -1,140 +0,0 @@
-# common
-
-[![Build
-Status](https://travis-ci.org/ethereum/go-ethereum.png?branch=master)](https://travis-ci.org/ethereum/go-ethereum)
-
-The common package contains the ethereum utility library.
-
-# Installation
-
-As a subdirectory the main go-ethereum repository, you get it with
-`go get github.com/ethereum/go-ethereum`.
-
-# Usage
-
-## RLP (Recursive Linear Prefix) Encoding
-
-RLP Encoding is an encoding scheme used by the Ethereum project. It
-encodes any native value or list to a string.
-
-More in depth information about the encoding scheme see the
-[Wiki](http://wiki.ethereum.org/index.php/RLP) article.
-
-```go
-rlp := common.Encode("doge")
-fmt.Printf("%q\n", rlp) // => "\0x83dog"
-
-rlp = common.Encode([]interface{}{"dog", "cat"})
-fmt.Printf("%q\n", rlp) // => "\0xc8\0x83dog\0x83cat"
-decoded := common.Decode(rlp)
-fmt.Println(decoded) // => ["dog" "cat"]
-```
-
-## Patricia Trie
-
-Patricie Tree is a merkle trie used by the Ethereum project.
-
-More in depth information about the (modified) Patricia Trie can be
-found on the [Wiki](http://wiki.ethereum.org/index.php/Patricia_Tree).
-
-The patricia trie uses a db as backend and could be anything as long as
-it satisfies the Database interface found in `common/db.go`.
-
-```go
-db := NewDatabase()
-
-// db, root
-trie := common.NewTrie(db, "")
-
-trie.Put("puppy", "dog")
-trie.Put("horse", "stallion")
-trie.Put("do", "verb")
-trie.Put("doge", "coin")
-
-// Look up the key "do" in the trie
-out := trie.Get("do")
-fmt.Println(out) // => verb
-
-trie.Delete("puppy")
-```
-
-The patricia trie, in combination with RLP, provides a robust,
-cryptographically authenticated data structure that can be used to store
-all (key, value) bindings.
-
-```go
-// ... Create db/trie
-
-// Note that RLP uses interface slices as list
-value := common.Encode([]interface{}{"one", 2, "three", []interface{}{42}})
-// Store the RLP encoded value of the list
-trie.Put("mykey", value)
-```
-
-## Value
-
-Value is a Generic Value which is used in combination with RLP data or
-`([])interface{}` structures. It may serve as a bridge between RLP data
-and actual real values and takes care of all the type checking and
-casting. Unlike Go's `reflect.Value` it does not panic if it's unable to
-cast to the requested value. It simple returns the base value of that
-type (e.g. `Slice()` returns []interface{}, `Uint()` return 0, etc).
-
-### Creating a new Value
-
-`NewEmptyValue()` returns a new \*Value with it's initial value set to a
-`[]interface{}`
-
-`AppendList()` appends a list to the current value.
-
-`Append(v)` appends the value (v) to the current value/list.
-
-```go
-val := common.NewEmptyValue().Append(1).Append("2")
-val.AppendList().Append(3)
-```
-
-### Retrieving values
-
-`Get(i)` returns the `i` item in the list.
-
-`Uint()` returns the value as an unsigned int64.
-
-`Slice()` returns the value as a interface slice.
-
-`Str()` returns the value as a string.
-
-`Bytes()` returns the value as a byte slice.
-
-`Len()` assumes current to be a slice and returns its length.
-
-`Byte()` returns the value as a single byte.
-
-```go
-val := common.NewValue([]interface{}{1,"2",[]interface{}{3}})
-val.Get(0).Uint() // => 1
-val.Get(1).Str() // => "2"
-s := val.Get(2) // => Value([]interface{}{3})
-s.Get(0).Uint() // => 3
-```
-
-## Decoding
-
-Decoding streams of RLP data is simplified
-
-```go
-val := common.NewValueFromBytes(rlpData)
-val.Get(0).Uint()
-```
-
-## Encoding
-
-Encoding from Value to RLP is done with the `Encode` method. The
-underlying value can be anything RLP can encode (int, str, lists, bytes)
-
-```go
-val := common.NewValue([]interface{}{1,"2",[]interface{}{3}})
-rlp := val.Encode()
-// Store the rlp data
-Store(rlp)
-```
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/math/dist.go b/src/vendor/github.com/ethereum/go-ethereum/common/math/dist.go
new file mode 100644
index 000000000..913fbfbd4
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/common/math/dist.go
@@ -0,0 +1,96 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package math
+
+import (
+ "math/big"
+ "sort"
+
+ "github.com/ethereum/go-ethereum/common"
+)
+
+type Summer interface {
+ Sum(i int) *big.Int
+ Len() int
+}
+
+func Sum(slice Summer) (sum *big.Int) {
+ sum = new(big.Int)
+
+ for i := 0; i < slice.Len(); i++ {
+ sum.Add(sum, slice.Sum(i))
+ }
+ return
+}
+
+type Vector struct {
+ Gas, Price *big.Int
+}
+
+type VectorsBy func(v1, v2 Vector) bool
+
+func (self VectorsBy) Sort(vectors []Vector) {
+ bs := vectorSorter{
+ vectors: vectors,
+ by: self,
+ }
+ sort.Sort(bs)
+}
+
+type vectorSorter struct {
+ vectors []Vector
+ by func(v1, v2 Vector) bool
+}
+
+func (v vectorSorter) Len() int { return len(v.vectors) }
+func (v vectorSorter) Less(i, j int) bool { return v.by(v.vectors[i], v.vectors[j]) }
+func (v vectorSorter) Swap(i, j int) { v.vectors[i], v.vectors[j] = v.vectors[j], v.vectors[i] }
+
+func PriceSort(v1, v2 Vector) bool { return v1.Price.Cmp(v2.Price) < 0 }
+func GasSort(v1, v2 Vector) bool { return v1.Gas.Cmp(v2.Gas) < 0 }
+
+type vectorSummer struct {
+ vectors []Vector
+ by func(v Vector) *big.Int
+}
+
+type VectorSum func(v Vector) *big.Int
+
+func (v VectorSum) Sum(vectors []Vector) *big.Int {
+ vs := vectorSummer{
+ vectors: vectors,
+ by: v,
+ }
+ return Sum(vs)
+}
+
+func (v vectorSummer) Len() int { return len(v.vectors) }
+func (v vectorSummer) Sum(i int) *big.Int { return v.by(v.vectors[i]) }
+
+func GasSum(v Vector) *big.Int { return v.Gas }
+
+var etherInWei = new(big.Rat).SetInt(common.String2Big("1000000000000000000"))
+
+func GasPrice(bp, gl, ep *big.Int) *big.Int {
+ BP := new(big.Rat).SetInt(bp)
+ GL := new(big.Rat).SetInt(gl)
+ EP := new(big.Rat).SetInt(ep)
+ GP := new(big.Rat).Quo(BP, GL)
+ GP = GP.Quo(GP, EP)
+
+ return GP.Mul(GP, etherInWei).Num()
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/natspec/natspec.go b/src/vendor/github.com/ethereum/go-ethereum/common/natspec/natspec.go
new file mode 100644
index 000000000..4521ff7a1
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/common/natspec/natspec.go
@@ -0,0 +1,262 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+// +build ignore
+
+package natspec
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/common/httpclient"
+ "github.com/ethereum/go-ethereum/common/registrar"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/xeth"
+ "github.com/robertkrimen/otto"
+)
+
+type abi2method map[[8]byte]*method
+
+type NatSpec struct {
+ jsvm *otto.Otto
+ abiDocJson []byte
+ userDoc userDoc
+ tx, data string
+}
+
+// main entry point for to get natspec notice for a transaction
+// the implementation is frontend friendly in that it always gives back
+// a notice that is safe to display
+// :FIXME: the second return value is an error, which can be used to fine-tune bahaviour
+func GetNotice(xeth *xeth.XEth, tx string, http *httpclient.HTTPClient) (notice string) {
+ ns, err := New(xeth, tx, http)
+ if err != nil {
+ if ns == nil {
+ return getFallbackNotice(fmt.Sprintf("no NatSpec info found for contract: %v", err), tx)
+ } else {
+ return getFallbackNotice(fmt.Sprintf("invalid NatSpec info: %v", err), tx)
+ }
+ }
+
+ notice, err = ns.Notice()
+ if err != nil {
+ return getFallbackNotice(fmt.Sprintf("NatSpec notice error: %v", err), tx)
+ }
+
+ return
+}
+
+func getFallbackNotice(comment, tx string) string {
+ return fmt.Sprintf("About to submit transaction (%s): %s", comment, tx)
+}
+
+type transaction struct {
+ To string `json:"to"`
+ Data string `json:"data"`
+}
+
+type jsonTx struct {
+ Params []transaction `json:"params"`
+}
+
+type contractInfo struct {
+ Source string `json:"source"`
+ Language string `json:"language"`
+ Version string `json:"compilerVersion"`
+ AbiDefinition json.RawMessage `json:"abiDefinition"`
+ UserDoc userDoc `json:"userDoc"`
+ DeveloperDoc json.RawMessage `json:"developerDoc"`
+}
+
+func New(xeth *xeth.XEth, jsontx string, http *httpclient.HTTPClient) (self *NatSpec, err error) {
+
+ // extract contract address from tx
+ var tx jsonTx
+ err = json.Unmarshal([]byte(jsontx), &tx)
+ if err != nil {
+ return
+ }
+ t := tx.Params[0]
+ contractAddress := t.To
+
+ content, err := FetchDocsForContract(contractAddress, xeth, http)
+ if err != nil {
+ return
+ }
+
+ self, err = NewWithDocs(content, jsontx, t.Data)
+ return
+}
+
+// also called by admin.contractInfo.get
+func FetchDocsForContract(contractAddress string, xeth *xeth.XEth, client *httpclient.HTTPClient) (content []byte, err error) {
+ // retrieve contract hash from state
+ codehex := xeth.CodeAt(contractAddress)
+ codeb := xeth.CodeAtBytes(contractAddress)
+
+ if codehex == "0x" {
+ err = fmt.Errorf("contract (%v) not found", contractAddress)
+ return
+ }
+ codehash := common.BytesToHash(crypto.Keccak256(codeb))
+ // set up nameresolver with natspecreg + urlhint contract addresses
+ reg := registrar.New(xeth)
+
+ // resolve host via HashReg/UrlHint Resolver
+ hash, err := reg.HashToHash(codehash)
+ if err != nil {
+ return
+ }
+ if client.HasScheme("bzz") {
+ content, err = client.Get("bzz://"+hash.Hex()[2:], "")
+ if err == nil { // non-fatal
+ return
+ }
+ err = nil
+ //falling back to urlhint
+ }
+
+ uri, err := reg.HashToUrl(hash)
+ if err != nil {
+ return
+ }
+
+ // get content via http client and authenticate content using hash
+ content, err = client.GetAuthContent(uri, hash)
+ if err != nil {
+ return
+ }
+ return
+}
+
+func NewWithDocs(infoDoc []byte, tx string, data string) (self *NatSpec, err error) {
+
+ var contract contractInfo
+ err = json.Unmarshal(infoDoc, &contract)
+ if err != nil {
+ return
+ }
+
+ self = &NatSpec{
+ jsvm: otto.New(),
+ abiDocJson: []byte(contract.AbiDefinition),
+ userDoc: contract.UserDoc,
+ tx: tx,
+ data: data,
+ }
+
+ // load and require natspec js (but it is meant to be protected environment)
+ _, err = self.jsvm.Run(natspecJS)
+ if err != nil {
+ return
+ }
+ _, err = self.jsvm.Run("var natspec = require('natspec');")
+ return
+}
+
+// type abiDoc []method
+
+// type method struct {
+// Name string `json:name`
+// Inputs []input `json:inputs`
+// abiKey [8]byte
+// }
+
+// type input struct {
+// Name string `json:name`
+// Type string `json:type`
+// }
+
+// json skeleton for abi doc (contract method definitions)
+type method struct {
+ Notice string `json:notice`
+ name string
+}
+
+type userDoc struct {
+ Methods map[string]*method `json:methods`
+}
+
+func (self *NatSpec) makeAbi2method(abiKey [8]byte) (meth *method) {
+ for signature, m := range self.userDoc.Methods {
+ name := strings.Split(signature, "(")[0]
+ hash := []byte(common.Bytes2Hex(crypto.Keccak256([]byte(signature))))
+ var key [8]byte
+ copy(key[:], hash[:8])
+ if bytes.Equal(key[:], abiKey[:]) {
+ meth = m
+ meth.name = name
+ return
+ }
+ }
+ return
+}
+
+func (self *NatSpec) Notice() (notice string, err error) {
+ var abiKey [8]byte
+ if len(self.data) < 10 {
+ err = fmt.Errorf("Invalid transaction data")
+ return
+ }
+ copy(abiKey[:], self.data[2:10])
+ meth := self.makeAbi2method(abiKey)
+
+ if meth == nil {
+ err = fmt.Errorf("abi key does not match any method")
+ return
+ }
+ notice, err = self.noticeForMethod(self.tx, meth.name, meth.Notice)
+ return
+}
+
+func (self *NatSpec) noticeForMethod(tx string, name, expression string) (notice string, err error) {
+
+ if _, err = self.jsvm.Run("var transaction = " + tx + ";"); err != nil {
+ return "", fmt.Errorf("natspec.js error setting transaction: %v", err)
+ }
+
+ if _, err = self.jsvm.Run("var abi = " + string(self.abiDocJson) + ";"); err != nil {
+ return "", fmt.Errorf("natspec.js error setting abi: %v", err)
+ }
+
+ if _, err = self.jsvm.Run("var method = '" + name + "';"); err != nil {
+ return "", fmt.Errorf("natspec.js error setting method: %v", err)
+ }
+
+ if _, err = self.jsvm.Run("var expression = \"" + expression + "\";"); err != nil {
+ return "", fmt.Errorf("natspec.js error setting expression: %v", err)
+ }
+
+ self.jsvm.Run("var call = {method: method,abi: abi,transaction: transaction};")
+ value, err := self.jsvm.Run("natspec.evaluateExpression(expression, call);")
+ if err != nil {
+ return "", fmt.Errorf("natspec.js error evaluating expression: %v", err)
+ }
+ evalError := "Natspec evaluation failed, wrong input params"
+ if value.String() == evalError {
+ return "", fmt.Errorf("natspec.js error evaluating expression: wrong input params in expression '%s'", expression)
+ }
+ if len(value.String()) == 0 {
+ return "", fmt.Errorf("natspec.js error evaluating expression")
+ }
+
+ return value.String(), nil
+
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/natspec/natspec_js.go b/src/vendor/github.com/ethereum/go-ethereum/common/natspec/natspec_js.go
new file mode 100644
index 000000000..2b30d31d3
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/common/natspec/natspec_js.go
@@ -0,0 +1,4060 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package natspec
+
+const natspecJS = //`require=function t(e,n,r){function i(f,u){if(!n[f]){if(!e[f]){var s="function"==typeof require&&require;if(!u&&s)return s(f,!0);if(o)return o(f,!0);var c=new Error("Cannot find module '"+f+"'");throw c.code="MODULE_NOT_FOUND",c}var a=n[f]={exports:{}};e[f][0].call(a.exports,function(t){var n=e[f][1][t];return i(n?n:t)},a,a.exports,t,e,n,r)}return n[f].exports}for(var o="function"==typeof require&&require,f=0;fv;v++)d.push(g(e.slice(0,s))),e=e.slice(s);n.push(d)}else r.prefixedType("string")(t[c].type)?(a=a.slice(s),n.push(g(e.slice(0,s))),e=e.slice(s)):(n.push(g(e.slice(0,s))),e=e.slice(s))}),n},g=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),i=n.extractTypeName(t.name),o=function(){var e=Array.prototype.slice.call(arguments);return a(t.inputs,e)};void 0===e[r]&&(e[r]=o),e[r][i]=o}),e},m=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),i=n.extractTypeName(t.name),o=function(e){return h(t.outputs,e)};void 0===e[r]&&(e[r]=o),e[r][i]=o}),e};e.exports={inputParser:g,outputParser:m,formatInput:a,formatOutput:h}},{"./const":4,"./formatters":5,"./types":6,"./utils":7}],4:[function(t,e){(function(n){if("build"!==n.env.NODE_ENV)var r=t("bignumber.js");var i=["wei","Kwei","Mwei","Gwei","szabo","finney","ether","grand","Mether","Gether","Tether","Pether","Eether","Zether","Yether","Nether","Dether","Vether","Uether"];e.exports={ETH_PADDING:32,ETH_SIGNATURE_LENGTH:4,ETH_UNITS:i,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:r.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3}}).call(this,t("_process"))},{_process:2,"bignumber.js":8}],5:[function(t,e){(function(n){if("build"!==n.env.NODE_ENV)var r=t("bignumber.js");var i=t("./utils"),o=t("./const"),f=function(t,e,n){return new Array(e-t.length+1).join(n?n:"0")+t},u=function(t){var e=2*o.ETH_PADDING;return t instanceof r||"number"==typeof t?("number"==typeof t&&(t=new r(t)),r.config(o.ETH_BIGNUMBER_ROUNDING_MODE),t=t.round(),t.lessThan(0)&&(t=new r("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16).plus(t).plus(1)),t=t.toString(16)):t=0===t.indexOf("0x")?t.substr(2):"string"==typeof t?u(new r(t)):(+t).toString(16),f(t,e)},s=function(t){return i.fromAscii(t,o.ETH_PADDING).substr(2)},c=function(t){return"000000000000000000000000000000000000000000000000000000000000000"+(t?"1":"0")},a=function(t){return u(new r(t).times(new r(2).pow(128)))},l=function(t){return"1"===new r(t.substr(0,1),16).toString(2).substr(0,1)},p=function(t){return t=t||"0",l(t)?new r(t,16).minus(new r("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new r(t,16)},h=function(t){return t=t||"0",new r(t,16)},g=function(t){return p(t).dividedBy(new r(2).pow(128))},m=function(t){return h(t).dividedBy(new r(2).pow(128))},d=function(t){return"0x"+t},v=function(t){return"0000000000000000000000000000000000000000000000000000000000000001"===t?!0:!1},w=function(t){return i.toAscii(t)},y=function(t){return"0x"+t.slice(t.length-40,t.length)};e.exports={formatInputInt:u,formatInputString:s,formatInputBool:c,formatInputReal:a,formatOutputInt:p,formatOutputUInt:h,formatOutputReal:g,formatOutputUReal:m,formatOutputHash:d,formatOutputBool:v,formatOutputString:w,formatOutputAddress:y}}).call(this,t("_process"))},{"./const":4,"./utils":7,_process:2,"bignumber.js":8}],6:[function(t,e){var n=t("./formatters"),r=function(t){return function(e){return 0===e.indexOf(t)}},i=function(t){return function(e){return t===e}},o=function(){return[{type:r("uint"),format:n.formatInputInt},{type:r("int"),format:n.formatInputInt},{type:r("hash"),format:n.formatInputInt},{type:r("string"),format:n.formatInputString},{type:r("real"),format:n.formatInputReal},{type:r("ureal"),format:n.formatInputReal},{type:i("address"),format:n.formatInputInt},{type:i("bool"),format:n.formatInputBool}]},f=function(){return[{type:r("uint"),format:n.formatOutputUInt},{type:r("int"),format:n.formatOutputInt},{type:r("hash"),format:n.formatOutputHash},{type:r("string"),format:n.formatOutputString},{type:r("real"),format:n.formatOutputReal},{type:r("ureal"),format:n.formatOutputUReal},{type:i("address"),format:n.formatOutputAddress},{type:i("bool"),format:n.formatOutputBool}]};e.exports={prefixedType:r,namedType:i,inputTypes:o,outputTypes:f}},{"./formatters":5}],7:[function(t,e){var n=t("./const"),r=function(t,e){for(var n=!1,r=0;rn;n+=2){var i=parseInt(t.substr(n,2),16);if(0===i)break;e+=String.fromCharCode(i)}return e},o=function(t){for(var e="",n=0;n3e3&&rr?"i":"").test(c))return m(a,c,u,r);u?(a.s=0>1/t?(c=c.slice(1),-1):1,$&&c.replace(/^0\.0*|\./,"").length>15&&U(L,O,t),u=!1):a.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1,c=n(c,10,r,a.s)}else{if(t instanceof e)return a.s=t.s,a.e=t.e,a.c=(t=t.c)?t.slice():t,void(L=0);if((u="number"==typeof t)&&0*t==0){if(a.s=0>1/t?(t=-t,-1):1,t===~~t){for(o=0,f=t;f>=10;f/=10,o++);return a.e=o,a.c=[t],void(L=0)}c=t+""}else{if(!d.test(c=t+""))return m(a,c,u);a.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1}}for((o=c.indexOf("."))>-1&&(c=c.replace(".","")),(f=c.search(/e/i))>0?(0>o&&(o=f),o+=+c.slice(f+1),c=c.substring(0,f)):0>o&&(o=c.length),f=0;48===c.charCodeAt(f);f++);for(s=c.length;48===c.charCodeAt(--s););if(c=c.slice(f,s+1))if(s=c.length,u&&$&&s>15&&U(L,O,a.s*t),o=o-f-1,o>q)a.c=a.e=null;else if(k>o)a.c=[a.e=0];else{if(a.e=o,a.c=[],f=(o+1)%I,0>o&&(f+=I),s>f){for(f&&a.c.push(+c.slice(0,f)),s-=I;s>f;)a.c.push(+c.slice(f,f+=I));c=c.slice(f),f=I-c.length}else f-=s;for(;f--;c+="0");a.c.push(+c)}else a.c=[a.e=0];L=0}function n(t,n,r,i){var f,u,s,a,p,h,g,m=t.indexOf("."),d=B,v=H;for(37>r&&(t=t.toLowerCase()),m>=0&&(s=Y,Y=0,t=t.replace(".",""),g=new e(r),p=g.pow(t.length-m),Y=s,g.c=c(l(o(p.c),p.e),10,n),g.e=g.c.length),h=c(t,r,n),u=s=h.length;0==h[--s];h.pop());if(!h[0])return"0";if(0>m?--u:(p.c=h,p.e=u,p.s=i,p=G(p,g,d,v,n),h=p.c,a=p.r,u=p.e),f=u+d+1,m=h[f],s=n/2,a=a||0>f||null!=h[f+1],a=4>v?(null!=m||a)&&(0==v||v==(p.s<0?3:2)):m>s||m==s&&(4==v||a||6==v&&1&h[f-1]||v==(p.s<0?8:7)),1>f||!h[0])t=a?l("1",-d):"0";else{if(h.length=f,a)for(--n;++h[--f]>n;)h[f]=0,f||(++u,h.unshift(1));for(s=h.length;!h[--s];);for(m=0,t="";s>=m;t+=N.charAt(h[m++]));t=l(t,u)}return t}function h(t,n,r,i){var f,u,s,c,p;if(r=null!=r&&z(r,0,8,i,b)?0|r:H,!t.c)return t.toString();if(f=t.c[0],s=t.e,null==n)p=o(t.c),p=19==i||24==i&&C>=s?a(p,s):l(p,s);else if(t=F(new e(t),n,r),u=t.e,p=o(t.c),c=p.length,19==i||24==i&&(u>=n||C>=u)){for(;n>c;p+="0",c++);p=a(p,u)}else if(n-=s,p=l(p,u),u+1>c){if(--n>0)for(p+=".";n--;p+="0");}else if(n+=u-c,n>0)for(u+1==c&&(p+=".");n--;p+="0");return t.s<0&&f?"-"+p:p}function S(t,n){var r,i,o=0;for(s(t[0])&&(t=t[0]),r=new e(t[0]);++ot||t>n||t!=p(t))&&U(r,(i||"decimal places")+(e>t||t>n?" out of range":" not an integer"),t),!0}function R(t,e,n){for(var r=1,i=e.length;!e[--i];e.pop());for(i=e[0];i>=10;i/=10,r++);return(n=r+n*I-1)>q?t.c=t.e=null:k>n?t.c=[t.e=0]:(t.e=n,t.c=e),t}function U(t,e,n){var r=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][t]+"() "+e+": "+n);throw r.name="BigNumber Error",L=0,r}function F(t,e,n,r){var i,o,f,u,s,c,a,l=t.c,p=_;if(l){t:{for(i=1,u=l[0];u>=10;u/=10,i++);if(o=e-i,0>o)o+=I,f=e,s=l[c=0],a=s/p[i-f-1]%10|0;else if(c=v((o+1)/I),c>=l.length){if(!r)break t;for(;l.length<=c;l.push(0));s=a=0,i=1,o%=I,f=o-I+1}else{for(s=u=l[c],i=1;u>=10;u/=10,i++);o%=I,f=o-I+i,a=0>f?0:s/p[i-f-1]%10|0}if(r=r||0>e||null!=l[c+1]||(0>f?s:s%p[i-f-1]),r=4>n?(a||r)&&(0==n||n==(t.s<0?3:2)):a>5||5==a&&(4==n||r||6==n&&(o>0?f>0?s/p[i-f]:0:l[c-1])%10&1||n==(t.s<0?8:7)),1>e||!l[0])return l.length=0,r?(e-=t.e+1,l[0]=p[e%I],t.e=-e||0):l[0]=t.e=0,t;if(0==o?(l.length=c,u=1,c--):(l.length=c+1,u=p[I-o],l[c]=f>0?w(s/p[i-f]%p[f])*u:0),r)for(;;){if(0==c){for(o=1,f=l[0];f>=10;f/=10,o++);for(f=l[0]+=u,u=1;f>=10;f/=10,u++);o!=u&&(t.e++,l[0]==E&&(l[0]=1));break}if(l[c]+=u,l[c]!=E)break;l[c--]=0,u=1}for(o=l.length;0===l[--o];l.pop());}t.e>q?t.c=t.e=null:t.en?null!=(t=i[n++]):void 0};return f(e="DECIMAL_PLACES")&&z(t,0,D,2,e)&&(B=0|t),r[e]=B,f(e="ROUNDING_MODE")&&z(t,0,8,2,e)&&(H=0|t),r[e]=H,f(e="EXPONENTIAL_AT")&&(s(t)?z(t[0],-D,0,2,e)&&z(t[1],0,D,2,e)&&(C=0|t[0],j=0|t[1]):z(t,-D,D,2,e)&&(C=-(j=0|(0>t?-t:t)))),r[e]=[C,j],f(e="RANGE")&&(s(t)?z(t[0],-D,-1,2,e)&&z(t[1],1,D,2,e)&&(k=0|t[0],q=0|t[1]):z(t,-D,D,2,e)&&(0|t?k=-(q=0|(0>t?-t:t)):$&&U(2,e+" cannot be zero",t))),r[e]=[k,q],f(e="ERRORS")&&(t===!!t||1===t||0===t?(L=0,z=($=!!t)?A:u):$&&U(2,e+y,t)),r[e]=$,f(e="CRYPTO")&&(t===!!t||1===t||0===t?(V=!(!t||!g||"object"!=typeof g),t&&!V&&$&&U(2,"crypto unavailable",g)):$&&U(2,e+y,t)),r[e]=V,f(e="MODULO_MODE")&&z(t,0,9,2,e)&&(W=0|t),r[e]=W,f(e="POW_PRECISION")&&z(t,0,D,2,e)&&(Y=0|t),r[e]=Y,f(e="FORMAT")&&("object"==typeof t?Z=t:$&&U(2,e+" not an object",t)),r[e]=Z,r},e.max=function(){return S(arguments,M.lt)},e.min=function(){return S(arguments,M.gt)},e.random=function(){var t=9007199254740992,n=Math.random()*t&2097151?function(){return w(Math.random()*t)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(t){var r,i,o,f,u,s=0,c=[],a=new e(P);if(t=null!=t&&z(t,0,D,14)?0|t:B,f=v(t/I),V)if(g&&g.getRandomValues){for(r=g.getRandomValues(new Uint32Array(f*=2));f>s;)u=131072*r[s]+(r[s+1]>>>11),u>=9e15?(i=g.getRandomValues(new Uint32Array(2)),r[s]=i[0],r[s+1]=i[1]):(c.push(u%1e14),s+=2);s=f/2}else if(g&&g.randomBytes){for(r=g.randomBytes(f*=7);f>s;)u=281474976710656*(31&r[s])+1099511627776*r[s+1]+4294967296*r[s+2]+16777216*r[s+3]+(r[s+4]<<16)+(r[s+5]<<8)+r[s+6],u>=9e15?g.randomBytes(7).copy(r,s):(c.push(u%1e14),s+=7);s=f/7}else $&&U(14,"crypto unavailable",g);if(!s)for(;f>s;)u=n(),9e15>u&&(c[s++]=u%1e14);for(f=c[--s],t%=I,f&&t&&(u=_[I-t],c[s]=w(f/u)*u);0===c[s];c.pop(),s--);if(0>s)c=[o=0];else{for(o=-1;0===c[0];c.shift(),o-=I);for(s=1,u=c[0];u>=10;u/=10,s++);I>s&&(o-=I-s)}return a.e=o,a.c=c,a}}(),G=function(){function t(t,e,n){var r,i,o,f,u=0,s=t.length,c=e%T,a=e/T|0;for(t=t.slice();s--;)o=t[s]%T,f=t[s]/T|0,r=a*o+f*c,i=c*o+r%T*T+u,u=(i/n|0)+(r/T|0)+a*f,t[s]=i%n;return u&&t.unshift(u),t}function n(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;n>i;i++)if(t[i]!=e[i]){o=t[i]>e[i]?1:-1;break}return o}function r(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.shift());}return function(o,f,u,s,c){var a,l,p,h,g,m,d,v,y,b,O,N,x,_,T,D,S,A=o.s==f.s?1:-1,R=o.c,U=f.c;if(!(R&&R[0]&&U&&U[0]))return new e(o.s&&f.s&&(R?!U||R[0]!=U[0]:U)?R&&0==R[0]||!U?0*A:A/0:0/0);for(v=new e(A),y=v.c=[],l=o.e-f.e,A=u+l+1,c||(c=E,l=i(o.e/I)-i(f.e/I),A=A/I|0),p=0;U[p]==(R[p]||0);p++);if(U[p]>(R[p]||0)&&l--,0>A)y.push(1),h=!0;else{for(_=R.length,D=U.length,p=0,A+=2,g=w(c/(U[0]+1)),g>1&&(U=t(U,g,c),R=t(R,g,c),D=U.length,_=R.length),x=D,b=R.slice(0,D),O=b.length;D>O;b[O++]=0);S=U.slice(),S.unshift(0),T=U[0],U[1]>=c/2&&T++;do g=0,a=n(U,b,D,O),0>a?(N=b[0],D!=O&&(N=N*c+(b[1]||0)),g=w(N/T),g>1?(g>=c&&(g=c-1),m=t(U,g,c),d=m.length,O=b.length,a=n(m,b,d,O),1==a&&(g--,r(m,d>D?S:U,d,c))):(0==g&&(a=g=1),m=U.slice()),d=m.length,O>d&&m.unshift(0),r(b,m,O,c),-1==a&&(O=b.length,a=n(U,b,D,O),1>a&&(g++,r(b,O>D?S:U,O,c))),O=b.length):0===a&&(g++,b=[0]),y[p++]=g,a&&b[0]?b[O++]=R[x]||0:(b=[R[x]],O=1);while((x++<_||null!=b[0])&&A--);h=null!=b[0],y[0]||y.shift()}if(c==E){for(p=1,A=y[0];A>=10;A/=10,p++);F(v,u+(v.e=p+l*I-1)+1,s,h)}else v.e=l,v.r=+h;return v}}(),m==function(){var t=/^(-?)0([xbo])(\w[\w.]*$)/i,n=/^([^.]+)\.$/,r=/^\.([^.]+)$/,i=/^-?(Infinity|NaN)$/,o=/^\s*\+([\w.])|^\s+|\s+$/g;return function(f,u,s,c){var a,l=s?u:u.replace(o,"$1");if(i.test(l))f.s=isNaN(l)?null:0>l?-1:1;else{if(!s&&(l=l.replace(t,function(t,e,n){return a="x"==(n=n.toLowerCase())?16:"b"==n?2:8,c&&c!=a?t:e}),c&&(a=c,l=l.replace(n,"$1").replace(r,"0.$1")),u!=l))return new e(l,a);$&&U(L,"not a"+(c?" base "+c:"")+" number",u),f.s=null}f.c=f.e=null,L=0}}(),M.absoluteValue=M.abs=function(){var t=new e(this);return t.s<0&&(t.s=1),t},M.ceil=function(){return F(new e(this),this.e+1,2)},M.comparedTo=M.cmp=function(t,n){return L=1,f(this,new e(t,n))},M.decimalPlaces=M.dp=function(){var t,e,n=this.c;if(!n)return null;if(t=((e=n.length-1)-i(this.e/I))*I,e=n[e])for(;e%10==0;e/=10,t--);return 0>t&&(t=0),t},M.dividedBy=M.div=function(t,n){return L=3,G(this,new e(t,n),B,H)},M.dividedToIntegerBy=M.divToInt=function(t,n){return L=4,G(this,new e(t,n),0,1)},M.equals=M.eq=function(t,n){return L=5,0===f(this,new e(t,n))},M.floor=function(){return F(new e(this),this.e+1,3)},M.greaterThan=M.gt=function(t,n){return L=6,f(this,new e(t,n))>0},M.greaterThanOrEqualTo=M.gte=function(t,n){return L=7,1===(n=f(this,new e(t,n)))||0===n},M.isFinite=function(){return!!this.c},M.isInteger=M.isInt=function(){return!!this.c&&i(this.e/I)>this.c.length-2},M.isNaN=function(){return!this.s},M.isNegative=M.isNeg=function(){return this.s<0},M.isZero=function(){return!!this.c&&0==this.c[0]},M.lessThan=M.lt=function(t,n){return L=8,f(this,new e(t,n))<0},M.lessThanOrEqualTo=M.lte=function(t,n){return L=9,-1===(n=f(this,new e(t,n)))||0===n},M.minus=M.sub=function(t,n){var r,o,f,u,s=this,c=s.s;if(L=10,t=new e(t,n),n=t.s,!c||!n)return new e(0/0);if(c!=n)return t.s=-n,s.plus(t);var a=s.e/I,l=t.e/I,p=s.c,h=t.c;if(!a||!l){if(!p||!h)return p?(t.s=-n,t):new e(h?s:0/0);if(!p[0]||!h[0])return h[0]?(t.s=-n,t):new e(p[0]?s:3==H?-0:0)}if(a=i(a),l=i(l),p=p.slice(),c=a-l){for((u=0>c)?(c=-c,f=p):(l=a,f=h),f.reverse(),n=c;n--;f.push(0));f.reverse()}else for(o=(u=(c=p.length)<(n=h.length))?c:n,c=n=0;o>n;n++)if(p[n]!=h[n]){u=p[n]0)for(;n--;p[r++]=0);for(n=E-1;o>c;){if(p[--o]0?(s=u,r=a):(f=-f,r=c),r.reverse();f--;r.push(0));r.reverse()}for(f=c.length,n=a.length,0>f-n&&(r=a,a=c,c=r,n=f),f=0;n;)f=(c[--n]=c[n]+a[n]+f)/E|0,c[n]%=E;return f&&(c.unshift(f),++s),R(t,c,s)},M.precision=M.sd=function(t){var e,n,r=this,i=r.c;if(null!=t&&t!==!!t&&1!==t&&0!==t&&($&&U(13,"argument"+y,t),t!=!!t&&(t=null)),!i)return null;if(n=i.length-1,e=n*I+1,n=i[n]){for(;n%10==0;n/=10,e--);for(n=i[0];n>=10;n/=10,e++);}return t&&r.e+1>e&&(e=r.e+1),e},M.round=function(t,n){var r=new e(this);return(null==t||z(t,0,D,15))&&F(r,~~t+this.e+1,null!=n&&z(n,0,8,15,b)?0|n:H),r},M.shift=function(t){var n=this;return z(t,-x,x,16,"argument")?n.times("1e"+p(t)):new e(n.c&&n.c[0]&&(-x>t||t>x)?n.s*(0>t?0:1/0):n)},M.squareRoot=M.sqrt=function(){var t,n,r,f,u,s=this,c=s.c,a=s.s,l=s.e,p=B+4,h=new e("0.5");if(1!==a||!c||!c[0])return new e(!a||0>a&&(!c||c[0])?0/0:c?s:1/0);if(a=Math.sqrt(+s),0==a||a==1/0?(n=o(c),(n.length+l)%2==0&&(n+="0"),a=Math.sqrt(n),l=i((l+1)/2)-(0>l||l%2),a==1/0?n="1e"+l:(n=a.toExponential(),n=n.slice(0,n.indexOf("e")+1)+l),r=new e(n)):r=new e(a+""),r.c[0])for(l=r.e,a=l+p,3>a&&(a=0);;)if(u=r,r=h.times(u.plus(G(s,u,p,1))),o(u.c).slice(0,a)===(n=o(r.c)).slice(0,a)){if(r.ea&&(d=b,b=O,O=d,f=a,a=h,h=f),f=a+h,d=[];f--;d.push(0));for(v=E,w=T,f=h;--f>=0;){for(r=0,g=O[f]%w,m=O[f]/w|0,s=a,u=f+s;u>f;)l=b[--s]%w,p=b[s]/w|0,c=m*l+p*g,l=g*l+c%w*w+d[u]+r,r=(l/v|0)+(c/w|0)+m*p,d[u--]=l%v;d[u]=r}return r?++o:d.shift(),R(t,d,o)},M.toDigits=function(t,n){var r=new e(this);return t=null!=t&&z(t,1,D,18,"precision")?0|t:null,n=null!=n&&z(n,0,8,18,b)?0|n:H,t?F(r,t,n):r},M.toExponential=function(t,e){return h(this,null!=t&&z(t,0,D,19)?~~t+1:null,e,19)},M.toFixed=function(t,e){return h(this,null!=t&&z(t,0,D,20)?~~t+this.e+1:null,e,20)},M.toFormat=function(t,e){var n=h(this,null!=t&&z(t,0,D,21)?~~t+this.e+1:null,e,21);if(this.c){var r,i=n.split("."),o=+Z.groupSize,f=+Z.secondaryGroupSize,u=Z.groupSeparator,s=i[0],c=i[1],a=this.s<0,l=a?s.slice(1):s,p=l.length;if(f&&(r=o,o=f,f=r,p-=r),o>0&&p>0){for(r=p%o||o,s=l.substr(0,r);p>r;r+=o)s+=u+l.substr(r,o);f>0&&(s+=u+l.slice(r)),a&&(s="-"+s)}n=c?s+Z.decimalSeparator+((f=+Z.fractionGroupSize)?c.replace(new RegExp("\\d{"+f+"}\\B","g"),"$&"+Z.fractionGroupSeparator):c):s}return n},M.toFraction=function(t){var n,r,i,f,u,s,c,a,l,p=$,h=this,g=h.c,m=new e(P),d=r=new e(P),v=c=new e(P);if(null!=t&&($=!1,s=new e(t),$=p,(!(p=s.isInt())||s.lt(P))&&($&&U(22,"max denominator "+(p?"out of range":"not an integer"),t),t=!p&&s.c&&F(s,s.e+1,1).gte(P)?s:null)),!g)return h.toString();for(l=o(g),f=m.e=l.length-h.e-1,m.c[0]=_[(u=f%I)<0?I+u:u],t=!t||s.cmp(m)>0?f>0?m:d:s,u=q,q=1/0,s=new e(l),c.c[0]=0;a=G(s,m,0,1),i=r.plus(a.times(v)),1!=i.cmp(t);)r=v,v=i,d=c.plus(a.times(i=d)),c=i,m=s.minus(a.times(i=m)),s=i;return i=G(t.minus(r),v,0,1),c=c.plus(i.times(d)),r=r.plus(i.times(v)),c.s=d.s=h.s,f*=2,n=G(d,v,f,H).minus(h).abs().cmp(G(c,r,f,H).minus(h).abs())<1?[d.toString(),v.toString()]:[c.toString(),r.toString()],q=u,n},M.toNumber=function(){var t=this;return+t||(t.s?0*t.s:0/0)},M.toPower=M.pow=function(t){var n,r,i=w(0>t?-t:+t),o=this;if(!z(t,-x,x,23,"exponent")&&(!isFinite(t)||i>x&&(t/=0)||parseFloat(t)!=t&&!(t=0/0)))return new e(Math.pow(+o,t));for(n=Y?v(Y/I+2):0,r=new e(P);;){if(i%2){if(r=r.times(o),!r.c)break;n&&r.c.length>n&&(r.c.length=n)}if(i=w(i/2),!i)break;o=o.times(o),n&&o.c&&o.c.length>n&&(o.c.length=n)}return 0>t&&(r=P.div(r)),n?F(r,Y,H):r},M.toPrecision=function(t,e){return h(this,null!=t&&z(t,1,D,24,"precision")?0|t:null,e,24)},M.toString=function(t){var e,r=this,i=r.s,f=r.e;return null===f?i?(e="Infinity",0>i&&(e="-"+e)):e="NaN":(e=o(r.c),e=null!=t&&z(t,2,64,25,"base")?n(l(e,f),0|t,10,i):C>=f||f>=j?a(e,f):l(e,f),0>i&&r.c[0]&&(e="-"+e)),e},M.truncated=M.trunc=function(){return F(new e(this),this.e+1,1)},M.valueOf=M.toJSON=function(){return this.toString()},null!=t&&e.config(t),e}function i(t){var e=0|t;return t>0||t===e?e:e-1}function o(t){for(var e,n,r=1,i=t.length,o=t[0]+"";i>r;){for(e=t[r++]+"",n=I-e.length;n--;e="0"+e);o+=e}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function f(t,e){var n,r,i=t.c,o=e.c,f=t.s,u=e.s,s=t.e,c=e.e;if(!f||!u)return null;if(n=i&&!i[0],r=o&&!o[0],n||r)return n?r?0:-u:f;if(f!=u)return f;if(n=0>f,r=s==c,!i||!o)return r?0:!i^n?1:-1;if(!r)return s>c^n?1:-1;for(u=(s=i.length)<(c=o.length)?s:c,f=0;u>f;f++)if(i[f]!=o[f])return i[f]>o[f]^n?1:-1;return s==c?0:s>c^n?1:-1}function u(t,e,n){return(t=p(t))>=e&&n>=t}function s(t){return"[object Array]"==Object.prototype.toString.call(t)}function c(t,e,n){for(var r,i,o=[0],f=0,u=t.length;u>f;){for(i=o.length;i--;o[i]*=e);for(o[r=0]+=N.indexOf(t.charAt(f++));rn-1&&(null==o[r+1]&&(o[r+1]=0),o[r+1]+=o[r]/n|0,o[r]%=n)}return o.reverse()}function a(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(0>e?"e":"e+")+e}function l(t,e){var n,r;if(0>e){for(r="0.";++e;r+="0");t=r+t}else if(n=t.length,++e>n){for(r="0",e-=n;--e;r+="0");t+=r}else n>e&&(t=t.slice(0,e)+"."+t.slice(e));return t}function p(t){return t=parseFloat(t),0>t?v(t):w(t)}var h,g,m,d=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,v=Math.ceil,w=Math.floor,y=" not a boolean or binary digit",b="rounding mode",O="number type has more than 15 significant digits",N="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",E=1e14,I=14,x=9007199254740991,_=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],T=1e7,D=1e9;if(h=r(),"function"==typeof define&&define.amd)define(function(){return h});else if("undefined"!=typeof e&&e.exports){if(e.exports=h,!g)try{g=t("crypto")}catch(S){}}else n.BigNumber=h}(this)},{crypto:1}],natspec:[function(t,e){var n=t("./node_modules/ethereum.js/lib/abi.js"),r=function(){var t=function(t,e){Object.keys(t).forEach(function(n){e[n]=t[n]})},e=function(t){return Object.keys(t).reduce(function(t,e){return t+"var "+e+" = context['"+e+"'];\n"},"")},r=function(t,e){return t.filter(function(t){return t.name===e})[0]},i=function(t,e){var r=n.formatOutput(t.inputs,"0x"+e.params[0].data.slice(10));return t.inputs.reduce(function(t,e,n){return t[e.name]=r[n],t},{})},o=function(t,e){var n,r="",i=/\` + "`" + `(?:\\.|[^` + "`" + `\\])*\` + "`" + `/gim,o=0;try{for(;null!==(n=i.exec(t));){var f=i.lastIndex-n[0].length,u=n[0].slice(1,n[0].length-1);r+=t.slice(o,f);var s=e(u);r+=s,o=i.lastIndex}r+=t.slice(o)}catch(c){throw new Error("Natspec evaluation failed, wrong input params")}return r},f=function(n,f){var u={};if(f)try{var s=r(f.abi,f.method),c=i(s,f.transaction);t(c,u)}catch(a){throw new Error("Natspec evaluation failed, method does not exist")}var l=e(u),p=o(n,function(t){var e=new Function("context",l+"return "+t+";");return e(u).toString()});return p},u=function(t,e){try{return f(t,e)}catch(n){return n.message}};return{evaluateExpression:f,evaluateExpressionSafe:u}}();e.exports=r},{"./node_modules/ethereum.js/lib/abi.js":3}]},{},[]);
+`
+require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o.
+*/
+/**
+ * @file abi.js
+ * @author Marek Kotewicz
+ * @author Gav Wood
+ * @date 2014
+ */
+
+var utils = require('../utils/utils');
+var c = require('../utils/config');
+var types = require('./types');
+var f = require('./formatters');
+var solUtils = require('./utils');
+
+/**
+ * throw incorrect type error
+ *
+ * @method throwTypeError
+ * @param {String} type
+ * @throws incorrect type error
+ */
+var throwTypeError = function (type) {
+ throw new Error('parser does not support type: ' + type);
+};
+
+/** This method should be called if we want to check if givent type is an array type
+ *
+ * @method isArrayType
+ * @param {String} type name
+ * @returns {Boolean} true if it is, otherwise false
+ */
+var isArrayType = function (type) {
+ return type.slice(-2) === '[]';
+};
+
+/**
+ * This method should be called to return dynamic type length in hex
+ *
+ * @method dynamicTypeBytes
+ * @param {String} type
+ * @param {String|Array} dynamic type
+ * @return {String} length of dynamic type in hex or empty string if type is not dynamic
+ */
+var dynamicTypeBytes = function (type, value) {
+ // TODO: decide what to do with array of strings
+ if (isArrayType(type) || type === 'bytes')
+ return f.formatInputInt(value.length);
+ return "";
+};
+
+var inputTypes = types.inputTypes();
+
+/**
+ * Formats input params to bytes
+ *
+ * @method formatInput
+ * @param {Array} abi inputs of method
+ * @param {Array} params that will be formatted to bytes
+ * @returns bytes representation of input params
+ */
+var formatInput = function (inputs, params) {
+ var bytes = "";
+ var toAppendConstant = "";
+ var toAppendArrayContent = "";
+
+ /// first we iterate in search for dynamic
+ inputs.forEach(function (input, index) {
+ bytes += dynamicTypeBytes(input.type, params[index]);
+ });
+
+ inputs.forEach(function (input, i) {
+ /*jshint maxcomplexity:5 */
+ var typeMatch = false;
+ for (var j = 0; j < inputTypes.length && !typeMatch; j++) {
+ typeMatch = inputTypes[j].type(inputs[i].type, params[i]);
+ }
+ if (!typeMatch) {
+ throwTypeError(inputs[i].type);
+ }
+
+ var formatter = inputTypes[j - 1].format;
+
+ if (isArrayType(inputs[i].type))
+ toAppendArrayContent += params[i].reduce(function (acc, curr) {
+ return acc + formatter(curr);
+ }, "");
+ else if (inputs[i].type === 'bytes')
+ toAppendArrayContent += formatter(params[i]);
+ else
+ toAppendConstant += formatter(params[i]);
+ });
+
+ bytes += toAppendConstant + toAppendArrayContent;
+
+ return bytes;
+};
+
+/**
+ * This method should be called to predict the length of dynamic type
+ *
+ * @method dynamicBytesLength
+ * @param {String} type
+ * @returns {Number} length of dynamic type, 0 or multiplication of ETH_PADDING (32)
+ */
+var dynamicBytesLength = function (type) {
+ if (isArrayType(type) || type === 'bytes')
+ return c.ETH_PADDING * 2;
+ return 0;
+};
+
+var outputTypes = types.outputTypes();
+
+/**
+ * Formats output bytes back to param list
+ *
+ * @method formatOutput
+ * @param {Array} abi outputs of method
+ * @param {String} bytes represention of output
+ * @returns {Array} output params
+ */
+var formatOutput = function (outs, output) {
+
+ output = output.slice(2);
+ var result = [];
+ var padding = c.ETH_PADDING * 2;
+
+ var dynamicPartLength = outs.reduce(function (acc, curr) {
+ return acc + dynamicBytesLength(curr.type);
+ }, 0);
+
+ var dynamicPart = output.slice(0, dynamicPartLength);
+ output = output.slice(dynamicPartLength);
+
+ outs.forEach(function (out, i) {
+ /*jshint maxcomplexity:6 */
+ var typeMatch = false;
+ for (var j = 0; j < outputTypes.length && !typeMatch; j++) {
+ typeMatch = outputTypes[j].type(outs[i].type);
+ }
+
+ if (!typeMatch) {
+ throwTypeError(outs[i].type);
+ }
+
+ var formatter = outputTypes[j - 1].format;
+ if (isArrayType(outs[i].type)) {
+ var size = f.formatOutputUInt(dynamicPart.slice(0, padding));
+ dynamicPart = dynamicPart.slice(padding);
+ var array = [];
+ for (var k = 0; k < size; k++) {
+ array.push(formatter(output.slice(0, padding)));
+ output = output.slice(padding);
+ }
+ result.push(array);
+ }
+ else if (types.prefixedType('bytes')(outs[i].type)) {
+ dynamicPart = dynamicPart.slice(padding);
+ result.push(formatter(output.slice(0, padding)));
+ output = output.slice(padding);
+ } else {
+ result.push(formatter(output.slice(0, padding)));
+ output = output.slice(padding);
+ }
+ });
+
+ return result;
+};
+
+/**
+ * Should be called to create input parser for contract with given abi
+ *
+ * @method inputParser
+ * @param {Array} contract abi
+ * @returns {Object} input parser object for given json abi
+ * TODO: refactor creating the parser, do not double logic from contract
+ */
+var inputParser = function (json) {
+ var parser = {};
+ json.forEach(function (method) {
+ var displayName = utils.extractDisplayName(method.name);
+ var typeName = utils.extractTypeName(method.name);
+
+ var impl = function () {
+ var params = Array.prototype.slice.call(arguments);
+ return formatInput(method.inputs, params);
+ };
+
+ if (parser[displayName] === undefined) {
+ parser[displayName] = impl;
+ }
+
+ parser[displayName][typeName] = impl;
+ });
+
+ return parser;
+};
+
+/**
+ * Should be called to create output parser for contract with given abi
+ *
+ * @method outputParser
+ * @param {Array} contract abi
+ * @returns {Object} output parser for given json abi
+ */
+var outputParser = function (json) {
+ var parser = {};
+ json.forEach(function (method) {
+
+ var displayName = utils.extractDisplayName(method.name);
+ var typeName = utils.extractTypeName(method.name);
+
+ var impl = function (output) {
+ return formatOutput(method.outputs, output);
+ };
+
+ if (parser[displayName] === undefined) {
+ parser[displayName] = impl;
+ }
+
+ parser[displayName][typeName] = impl;
+ });
+
+ return parser;
+};
+
+var formatConstructorParams = function (abi, params) {
+ var constructor = solUtils.getConstructor(abi, params.length);
+ if (!constructor) {
+ if (params.length > 0) {
+ console.warn("didn't found matching constructor, using default one");
+ }
+ return '';
+ }
+ return formatInput(constructor.inputs, params);
+};
+
+module.exports = {
+ inputParser: inputParser,
+ outputParser: outputParser,
+ formatInput: formatInput,
+ formatOutput: formatOutput,
+ formatConstructorParams: formatConstructorParams
+};
+
+},{"../utils/config":6,"../utils/utils":7,"./formatters":3,"./types":4,"./utils":5}],3:[function(require,module,exports){
+/*
+ This file is part of ethereum.js.
+
+ ethereum.js is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ ethereum.js is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with ethereum.js. If not, see .
+*/
+/** @file formatters.js
+ * @authors:
+ * Marek Kotewicz
+ * @date 2015
+ */
+
+var BigNumber = require('bignumber.js');
+var utils = require('../utils/utils');
+var c = require('../utils/config');
+
+/**
+ * Formats input value to byte representation of int
+ * If value is negative, return it's two's complement
+ * If the value is floating point, round it down
+ *
+ * @method formatInputInt
+ * @param {String|Number|BigNumber} value that needs to be formatted
+ * @returns {String} right-aligned byte representation of int
+ */
+var formatInputInt = function (value) {
+ var padding = c.ETH_PADDING * 2;
+ BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
+ return utils.padLeft(utils.toTwosComplement(value).round().toString(16), padding);
+};
+
+/**
+ * Formats input value to byte representation of string
+ *
+ * @method formatInputString
+ * @param {String}
+ * @returns {String} left-algined byte representation of string
+ */
+var formatInputString = function (value) {
+ return utils.fromAscii(value, c.ETH_PADDING).substr(2);
+};
+
+/**
+ * Formats input value to byte representation of bool
+ *
+ * @method formatInputBool
+ * @param {Boolean}
+ * @returns {String} right-aligned byte representation bool
+ */
+var formatInputBool = function (value) {
+ return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
+};
+
+/**
+ * Formats input value to byte representation of real
+ * Values are multiplied by 2^m and encoded as integers
+ *
+ * @method formatInputReal
+ * @param {String|Number|BigNumber}
+ * @returns {String} byte representation of real
+ */
+var formatInputReal = function (value) {
+ return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
+};
+
+/**
+ * Check if input value is negative
+ *
+ * @method signedIsNegative
+ * @param {String} value is hex format
+ * @returns {Boolean} true if it is negative, otherwise false
+ */
+var signedIsNegative = function (value) {
+ return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
+};
+
+/**
+ * Formats right-aligned output bytes to int
+ *
+ * @method formatOutputInt
+ * @param {String} bytes
+ * @returns {BigNumber} right-aligned output bytes formatted to big number
+ */
+var formatOutputInt = function (value) {
+
+ value = value || "0";
+
+ // check if it's negative number
+ // it it is, return two's complement
+ if (signedIsNegative(value)) {
+ return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
+ }
+ return new BigNumber(value, 16);
+};
+
+/**
+ * Formats right-aligned output bytes to uint
+ *
+ * @method formatOutputUInt
+ * @param {String} bytes
+ * @returns {BigNumeber} right-aligned output bytes formatted to uint
+ */
+var formatOutputUInt = function (value) {
+ value = value || "0";
+ return new BigNumber(value, 16);
+};
+
+/**
+ * Formats right-aligned output bytes to real
+ *
+ * @method formatOutputReal
+ * @param {String}
+ * @returns {BigNumber} input bytes formatted to real
+ */
+var formatOutputReal = function (value) {
+ return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128));
+};
+
+/**
+ * Formats right-aligned output bytes to ureal
+ *
+ * @method formatOutputUReal
+ * @param {String}
+ * @returns {BigNumber} input bytes formatted to ureal
+ */
+var formatOutputUReal = function (value) {
+ return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128));
+};
+
+/**
+ * Should be used to format output hash
+ *
+ * @method formatOutputHash
+ * @param {String}
+ * @returns {String} right-aligned output bytes formatted to hex
+ */
+var formatOutputHash = function (value) {
+ return "0x" + value;
+};
+
+/**
+ * Should be used to format output bool
+ *
+ * @method formatOutputBool
+ * @param {String}
+ * @returns {Boolean} right-aligned input bytes formatted to bool
+ */
+var formatOutputBool = function (value) {
+ return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
+};
+
+/**
+ * Should be used to format output string
+ *
+ * @method formatOutputString
+ * @param {Sttring} left-aligned hex representation of string
+ * @returns {String} ascii string
+ */
+var formatOutputString = function (value) {
+ return utils.toAscii(value);
+};
+
+/**
+ * Should be used to format output address
+ *
+ * @method formatOutputAddress
+ * @param {String} right-aligned input bytes
+ * @returns {String} address
+ */
+var formatOutputAddress = function (value) {
+ return "0x" + value.slice(value.length - 40, value.length);
+};
+
+module.exports = {
+ formatInputInt: formatInputInt,
+ formatInputString: formatInputString,
+ formatInputBool: formatInputBool,
+ formatInputReal: formatInputReal,
+ formatOutputInt: formatOutputInt,
+ formatOutputUInt: formatOutputUInt,
+ formatOutputReal: formatOutputReal,
+ formatOutputUReal: formatOutputUReal,
+ formatOutputHash: formatOutputHash,
+ formatOutputBool: formatOutputBool,
+ formatOutputString: formatOutputString,
+ formatOutputAddress: formatOutputAddress
+};
+
+
+},{"../utils/config":6,"../utils/utils":7,"bignumber.js":8}],4:[function(require,module,exports){
+/*
+ This file is part of ethereum.js.
+
+ ethereum.js is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ ethereum.js is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with ethereum.js. If not, see .
+*/
+/** @file types.js
+ * @authors:
+ * Marek Kotewicz
+ * @date 2015
+ */
+
+var f = require('./formatters');
+
+/// @param expected type prefix (string)
+/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false
+var prefixedType = function (prefix) {
+ return function (type) {
+ return type.indexOf(prefix) === 0;
+ };
+};
+
+/// @param expected type name (string)
+/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false
+var namedType = function (name) {
+ return function (type) {
+ return name === type;
+ };
+};
+
+/// Setups input formatters for solidity types
+/// @returns an array of input formatters
+var inputTypes = function () {
+
+ return [
+ { type: prefixedType('uint'), format: f.formatInputInt },
+ { type: prefixedType('int'), format: f.formatInputInt },
+ { type: prefixedType('bytes'), format: f.formatInputString },
+ { type: prefixedType('real'), format: f.formatInputReal },
+ { type: prefixedType('ureal'), format: f.formatInputReal },
+ { type: namedType('address'), format: f.formatInputInt },
+ { type: namedType('bool'), format: f.formatInputBool }
+ ];
+};
+
+/// Setups output formaters for solidity types
+/// @returns an array of output formatters
+var outputTypes = function () {
+
+ return [
+ { type: prefixedType('uint'), format: f.formatOutputUInt },
+ { type: prefixedType('int'), format: f.formatOutputInt },
+ { type: prefixedType('bytes'), format: f.formatOutputString },
+ { type: prefixedType('real'), format: f.formatOutputReal },
+ { type: prefixedType('ureal'), format: f.formatOutputUReal },
+ { type: namedType('address'), format: f.formatOutputAddress },
+ { type: namedType('bool'), format: f.formatOutputBool }
+ ];
+};
+
+module.exports = {
+ prefixedType: prefixedType,
+ namedType: namedType,
+ inputTypes: inputTypes,
+ outputTypes: outputTypes
+};
+
+
+},{"./formatters":3}],5:[function(require,module,exports){
+/*
+ This file is part of ethereum.js.
+
+ ethereum.js is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ ethereum.js is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with ethereum.js. If not, see .
+*/
+/**
+ * @file utils.js
+ * @author Marek Kotewicz
+ * @date 2015
+ */
+
+/**
+ * Returns the contstructor with matching number of arguments
+ *
+ * @method getConstructor
+ * @param {Array} abi
+ * @param {Number} numberOfArgs
+ * @returns {Object} constructor function abi
+ */
+var getConstructor = function (abi, numberOfArgs) {
+ return abi.filter(function (f) {
+ return f.type === 'constructor' && f.inputs.length === numberOfArgs;
+ })[0];
+};
+
+/**
+ * Filters all functions from input abi
+ *
+ * @method filterFunctions
+ * @param {Array} abi
+ * @returns {Array} abi array with filtered objects of type 'function'
+ */
+var filterFunctions = function (json) {
+ return json.filter(function (current) {
+ return current.type === 'function';
+ });
+};
+
+/**
+ * Filters all events from input abi
+ *
+ * @method filterEvents
+ * @param {Array} abi
+ * @returns {Array} abi array with filtered objects of type 'event'
+ */
+var filterEvents = function (json) {
+ return json.filter(function (current) {
+ return current.type === 'event';
+ });
+};
+
+module.exports = {
+ getConstructor: getConstructor,
+ filterFunctions: filterFunctions,
+ filterEvents: filterEvents
+};
+
+
+},{}],6:[function(require,module,exports){
+/*
+ This file is part of ethereum.js.
+
+ ethereum.js is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ ethereum.js is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with ethereum.js. If not, see .
+*/
+/** @file config.js
+ * @authors:
+ * Marek Kotewicz
+ * @date 2015
+ */
+
+/**
+ * Utils
+ *
+ * @module utils
+ */
+
+/**
+ * Utility functions
+ *
+ * @class [utils] config
+ * @constructor
+ */
+
+/// required to define ETH_BIGNUMBER_ROUNDING_MODE
+var BigNumber = require('bignumber.js');
+
+var ETH_UNITS = [
+ 'wei',
+ 'Kwei',
+ 'Mwei',
+ 'Gwei',
+ 'szabo',
+ 'finney',
+ 'ether',
+ 'grand',
+ 'Mether',
+ 'Gether',
+ 'Tether',
+ 'Pether',
+ 'Eether',
+ 'Zether',
+ 'Yether',
+ 'Nether',
+ 'Dether',
+ 'Vether',
+ 'Uether'
+];
+
+module.exports = {
+ ETH_PADDING: 32,
+ ETH_SIGNATURE_LENGTH: 4,
+ ETH_UNITS: ETH_UNITS,
+ ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },
+ ETH_POLLING_TIMEOUT: 1000,
+ ETH_DEFAULTBLOCK: 'latest'
+};
+
+
+},{"bignumber.js":8}],7:[function(require,module,exports){
+/*
+ This file is part of ethereum.js.
+
+ ethereum.js is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ ethereum.js is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with ethereum.js. If not, see .
+*/
+/** @file utils.js
+ * @authors:
+ * Marek Kotewicz
+ * @date 2015
+ */
+
+/**
+ * Utils
+ *
+ * @module utils
+ */
+
+/**
+ * Utility functions
+ *
+ * @class [utils] utils
+ * @constructor
+ */
+
+var BigNumber = require('bignumber.js');
+
+var unitMap = {
+ 'wei': '1',
+ 'kwei': '1000',
+ 'ada': '1000',
+ 'mwei': '1000000',
+ 'babbage': '1000000',
+ 'gwei': '1000000000',
+ 'shannon': '1000000000',
+ 'szabo': '1000000000000',
+ 'finney': '1000000000000000',
+ 'ether': '1000000000000000000',
+ 'kether': '1000000000000000000000',
+ 'grand': '1000000000000000000000',
+ 'einstein': '1000000000000000000000',
+ 'mether': '1000000000000000000000000',
+ 'gether': '1000000000000000000000000000',
+ 'tether': '1000000000000000000000000000000'
+};
+
+/**
+ * Should be called to pad string to expected length
+ *
+ * @method padLeft
+ * @param {String} string to be padded
+ * @param {Number} characters that result string should have
+ * @param {String} sign, by default 0
+ * @returns {String} right aligned string
+ */
+var padLeft = function (string, chars, sign) {
+ return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
+};
+
+/** Finds first index of array element matching pattern
+ *
+ * @method findIndex
+ * @param {Array}
+ * @param {Function} pattern
+ * @returns {Number} index of element
+ */
+var findIndex = function (array, callback) {
+ var end = false;
+ var i = 0;
+ for (; i < array.length && !end; i++) {
+ end = callback(array[i]);
+ }
+ return end ? i - 1 : -1;
+};
+
+/**
+ * Should be called to get sting from it's hex representation
+ *
+ * @method toAscii
+ * @param {String} string in hex
+ * @returns {String} ascii string representation of hex value
+ */
+var toAscii = function(hex) {
+// Find termination
+ var str = "";
+ var i = 0, l = hex.length;
+ if (hex.substring(0, 2) === '0x') {
+ i = 2;
+ }
+ for (; i < l; i+=2) {
+ var code = parseInt(hex.substr(i, 2), 16);
+ if (code === 0) {
+ break;
+ }
+
+ str += String.fromCharCode(code);
+ }
+
+ return str;
+};
+
+/**
+ * Shold be called to get hex representation (prefixed by 0x) of ascii string
+ *
+ * @method fromAscii
+ * @param {String} string
+ * @returns {String} hex representation of input string
+ */
+var toHexNative = function(str) {
+ var hex = "";
+ for(var i = 0; i < str.length; i++) {
+ var n = str.charCodeAt(i).toString(16);
+ hex += n.length < 2 ? '0' + n : n;
+ }
+
+ return hex;
+};
+
+/**
+ * Shold be called to get hex representation (prefixed by 0x) of ascii string
+ *
+ * @method fromAscii
+ * @param {String} string
+ * @param {Number} optional padding
+ * @returns {String} hex representation of input string
+ */
+var fromAscii = function(str, pad) {
+ pad = pad === undefined ? 0 : pad;
+ var hex = toHexNative(str);
+ while (hex.length < pad*2)
+ hex += "00";
+ return "0x" + hex;
+};
+
+/**
+ * Should be called to get display name of contract function
+ *
+ * @method extractDisplayName
+ * @param {String} name of function/event
+ * @returns {String} display name for function/event eg. multiply(uint256) -> multiply
+ */
+var extractDisplayName = function (name) {
+ var length = name.indexOf('(');
+ return length !== -1 ? name.substr(0, length) : name;
+};
+
+/// @returns overloaded part of function/event name
+var extractTypeName = function (name) {
+ /// TODO: make it invulnerable
+ var length = name.indexOf('(');
+ return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
+};
+
+/**
+ * Converts value to it's decimal representation in string
+ *
+ * @method toDecimal
+ * @param {String|Number|BigNumber}
+ * @return {String}
+ */
+var toDecimal = function (value) {
+ return toBigNumber(value).toNumber();
+};
+
+/**
+ * Converts value to it's hex representation
+ *
+ * @method fromDecimal
+ * @param {String|Number|BigNumber}
+ * @return {String}
+ */
+var fromDecimal = function (value) {
+ var number = toBigNumber(value);
+ var result = number.toString(16);
+
+ return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result;
+};
+
+/**
+ * Auto converts any given value into it's hex representation.
+ *
+ * And even stringifys objects before.
+ *
+ * @method toHex
+ * @param {String|Number|BigNumber|Object}
+ * @return {String}
+ */
+var toHex = function (val) {
+ /*jshint maxcomplexity:7 */
+
+ if (isBoolean(val))
+ return fromDecimal(+val);
+
+ if (isBigNumber(val))
+ return fromDecimal(val);
+
+ if (isObject(val))
+ return fromAscii(JSON.stringify(val));
+
+ // if its a negative number, pass it through fromDecimal
+ if (isString(val)) {
+ if (val.indexOf('-0x') === 0)
+ return fromDecimal(val);
+ else if (!isFinite(val))
+ return fromAscii(val);
+ }
+
+ return fromDecimal(val);
+};
+
+/**
+ * Returns value of unit in Wei
+ *
+ * @method getValueOfUnit
+ * @param {String} unit the unit to convert to, default ether
+ * @returns {BigNumber} value of the unit (in Wei)
+ * @throws error if the unit is not correct:w
+ */
+var getValueOfUnit = function (unit) {
+ unit = unit ? unit.toLowerCase() : 'ether';
+ var unitValue = unitMap[unit];
+ if (unitValue === undefined) {
+ throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2));
+ }
+ return new BigNumber(unitValue, 10);
+};
+
+/**
+ * Takes a number of wei and converts it to any other ether unit.
+ *
+ * Possible units are:
+ * - kwei/ada
+ * - mwei/babbage
+ * - gwei/shannon
+ * - szabo
+ * - finney
+ * - ether
+ * - kether/grand/einstein
+ * - mether
+ * - gether
+ * - tether
+ *
+ * @method fromWei
+ * @param {Number|String} number can be a number, number string or a HEX of a decimal
+ * @param {String} unit the unit to convert to, default ether
+ * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
+*/
+var fromWei = function(number, unit) {
+ var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit));
+
+ return isBigNumber(number) ? returnValue : returnValue.toString(10);
+};
+
+/**
+ * Takes a number of a unit and converts it to wei.
+ *
+ * Possible units are:
+ * - kwei/ada
+ * - mwei/babbage
+ * - gwei/shannon
+ * - szabo
+ * - finney
+ * - ether
+ * - kether/grand/einstein
+ * - mether
+ * - gether
+ * - tether
+ *
+ * @method toWei
+ * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal
+ * @param {String} unit the unit to convert from, default ether
+ * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
+*/
+var toWei = function(number, unit) {
+ var returnValue = toBigNumber(number).times(getValueOfUnit(unit));
+
+ return isBigNumber(number) ? returnValue : returnValue.toString(10);
+};
+
+/**
+ * Takes an input and transforms it into an bignumber
+ *
+ * @method toBigNumber
+ * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber
+ * @return {BigNumber} BigNumber
+*/
+var toBigNumber = function(number) {
+ /*jshint maxcomplexity:5 */
+ number = number || 0;
+ if (isBigNumber(number))
+ return number;
+
+ if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) {
+ return new BigNumber(number.replace('0x',''), 16);
+ }
+
+ return new BigNumber(number.toString(10), 10);
+};
+
+/**
+ * Takes and input transforms it into bignumber and if it is negative value, into two's complement
+ *
+ * @method toTwosComplement
+ * @param {Number|String|BigNumber}
+ * @return {BigNumber}
+ */
+var toTwosComplement = function (number) {
+ var bigNumber = toBigNumber(number);
+ if (bigNumber.lessThan(0)) {
+ return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1);
+ }
+ return bigNumber;
+};
+
+/**
+ * Checks if the given string is strictly an address
+ *
+ * @method isStrictAddress
+ * @param {String} address the given HEX adress
+ * @return {Boolean}
+*/
+var isStrictAddress = function (address) {
+ return /^0x[0-9a-f]{40}$/.test(address);
+};
+
+/**
+ * Checks if the given string is an address
+ *
+ * @method isAddress
+ * @param {String} address the given HEX adress
+ * @return {Boolean}
+*/
+var isAddress = function (address) {
+ return /^(0x)?[0-9a-f]{40}$/.test(address);
+};
+
+/**
+ * Transforms given string to valid 20 bytes-length addres with 0x prefix
+ *
+ * @method toAddress
+ * @param {String} address
+ * @return {String} formatted address
+ */
+var toAddress = function (address) {
+ if (isStrictAddress(address)) {
+ return address;
+ }
+
+ if (/^[0-9a-f]{40}$/.test(address)) {
+ return '0x' + address;
+ }
+
+ return '0x' + padLeft(toHex(address).substr(2), 40);
+};
+
+/**
+ * Returns true if object is BigNumber, otherwise false
+ *
+ * @method isBigNumber
+ * @param {Object}
+ * @return {Boolean}
+ */
+var isBigNumber = function (object) {
+ return object instanceof BigNumber ||
+ (object && object.constructor && object.constructor.name === 'BigNumber');
+};
+
+/**
+ * Returns true if object is string, otherwise false
+ *
+ * @method isString
+ * @param {Object}
+ * @return {Boolean}
+ */
+var isString = function (object) {
+ return typeof object === 'string' ||
+ (object && object.constructor && object.constructor.name === 'String');
+};
+
+/**
+ * Returns true if object is function, otherwise false
+ *
+ * @method isFunction
+ * @param {Object}
+ * @return {Boolean}
+ */
+var isFunction = function (object) {
+ return typeof object === 'function';
+};
+
+/**
+ * Returns true if object is Objet, otherwise false
+ *
+ * @method isObject
+ * @param {Object}
+ * @return {Boolean}
+ */
+var isObject = function (object) {
+ return typeof object === 'object';
+};
+
+/**
+ * Returns true if object is boolean, otherwise false
+ *
+ * @method isBoolean
+ * @param {Object}
+ * @return {Boolean}
+ */
+var isBoolean = function (object) {
+ return typeof object === 'boolean';
+};
+
+/**
+ * Returns true if object is array, otherwise false
+ *
+ * @method isArray
+ * @param {Object}
+ * @return {Boolean}
+ */
+var isArray = function (object) {
+ return object instanceof Array;
+};
+
+/**
+ * Returns true if given string is valid json object
+ *
+ * @method isJson
+ * @param {String}
+ * @return {Boolean}
+ */
+var isJson = function (str) {
+ try {
+ return !!JSON.parse(str);
+ } catch (e) {
+ return false;
+ }
+};
+
+module.exports = {
+ padLeft: padLeft,
+ findIndex: findIndex,
+ toHex: toHex,
+ toDecimal: toDecimal,
+ fromDecimal: fromDecimal,
+ toAscii: toAscii,
+ fromAscii: fromAscii,
+ extractDisplayName: extractDisplayName,
+ extractTypeName: extractTypeName,
+ toWei: toWei,
+ fromWei: fromWei,
+ toBigNumber: toBigNumber,
+ toTwosComplement: toTwosComplement,
+ toAddress: toAddress,
+ isBigNumber: isBigNumber,
+ isStrictAddress: isStrictAddress,
+ isAddress: isAddress,
+ isFunction: isFunction,
+ isString: isString,
+ isObject: isObject,
+ isBoolean: isBoolean,
+ isArray: isArray,
+ isJson: isJson
+};
+
+
+},{"bignumber.js":8}],8:[function(require,module,exports){
+/*! bignumber.js v2.0.7 https://github.com/MikeMcl/bignumber.js/LICENCE */
+
+;(function (global) {
+ 'use strict';
+
+ /*
+ bignumber.js v2.0.7
+ A JavaScript library for arbitrary-precision arithmetic.
+ https://github.com/MikeMcl/bignumber.js
+ Copyright (c) 2015 Michael Mclaughlin
+ MIT Expat Licence
+ */
+
+
+ var BigNumber, crypto, parseNumeric,
+ isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
+ mathceil = Math.ceil,
+ mathfloor = Math.floor,
+ notBool = ' not a boolean or binary digit',
+ roundingMode = 'rounding mode',
+ tooManyDigits = 'number type has more than 15 significant digits',
+ ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
+ BASE = 1e14,
+ LOG_BASE = 14,
+ MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
+ // MAX_INT32 = 0x7fffffff, // 2^31 - 1
+ POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
+ SQRT_BASE = 1e7,
+
+ /*
+ * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
+ * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
+ * exception is thrown (if ERRORS is true).
+ */
+ MAX = 1E9; // 0 to MAX_INT32
+
+
+ /*
+ * Create and return a BigNumber constructor.
+ */
+ function another(configObj) {
+ var div,
+
+ // id tracks the caller function, so its name can be included in error messages.
+ id = 0,
+ P = BigNumber.prototype,
+ ONE = new BigNumber(1),
+
+
+ /********************************* EDITABLE DEFAULTS **********************************/
+
+
+ /*
+ * The default values below must be integers within the inclusive ranges stated.
+ * The values can also be changed at run-time using BigNumber.config.
+ */
+
+ // The maximum number of decimal places for operations involving division.
+ DECIMAL_PLACES = 20, // 0 to MAX
+
+ /*
+ * The rounding mode used when rounding to the above decimal places, and when using
+ * toExponential, toFixed, toFormat and toPrecision, and round (default value).
+ * UP 0 Away from zero.
+ * DOWN 1 Towards zero.
+ * CEIL 2 Towards +Infinity.
+ * FLOOR 3 Towards -Infinity.
+ * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
+ * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
+ * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
+ * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
+ * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
+ */
+ ROUNDING_MODE = 4, // 0 to 8
+
+ // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
+
+ // The exponent value at and beneath which toString returns exponential notation.
+ // Number type: -7
+ TO_EXP_NEG = -7, // 0 to -MAX
+
+ // The exponent value at and above which toString returns exponential notation.
+ // Number type: 21
+ TO_EXP_POS = 21, // 0 to MAX
+
+ // RANGE : [MIN_EXP, MAX_EXP]
+
+ // The minimum exponent value, beneath which underflow to zero occurs.
+ // Number type: -324 (5e-324)
+ MIN_EXP = -1e7, // -1 to -MAX
+
+ // The maximum exponent value, above which overflow to Infinity occurs.
+ // Number type: 308 (1.7976931348623157e+308)
+ // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
+ MAX_EXP = 1e7, // 1 to MAX
+
+ // Whether BigNumber Errors are ever thrown.
+ ERRORS = true, // true or false
+
+ // Change to intValidatorNoErrors if ERRORS is false.
+ isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
+
+ // Whether to use cryptographically-secure random number generation, if available.
+ CRYPTO = false, // true or false
+
+ /*
+ * The modulo mode used when calculating the modulus: a mod n.
+ * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
+ * The remainder (r) is calculated as: r = a - n * q.
+ *
+ * UP 0 The remainder is positive if the dividend is negative, else is negative.
+ * DOWN 1 The remainder has the same sign as the dividend.
+ * This modulo mode is commonly known as 'truncated division' and is
+ * equivalent to (a % n) in JavaScript.
+ * FLOOR 3 The remainder has the same sign as the divisor (Python %).
+ * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
+ * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
+ * The remainder is always positive.
+ *
+ * The truncated division, floored division, Euclidian division and IEEE 754 remainder
+ * modes are commonly used for the modulus operation.
+ * Although the other rounding modes can also be used, they may not give useful results.
+ */
+ MODULO_MODE = 1, // 0 to 9
+
+ // The maximum number of significant digits of the result of the toPower operation.
+ // If POW_PRECISION is 0, there will be unlimited significant digits.
+ POW_PRECISION = 100, // 0 to MAX
+
+ // The format specification used by the BigNumber.prototype.toFormat method.
+ FORMAT = {
+ decimalSeparator: '.',
+ groupSeparator: ',',
+ groupSize: 3,
+ secondaryGroupSize: 0,
+ fractionGroupSeparator: '\xA0', // non-breaking space
+ fractionGroupSize: 0
+ };
+
+
+ /******************************************************************************************/
+
+
+ // CONSTRUCTOR
+
+
+ /*
+ * The BigNumber constructor and exported function.
+ * Create and return a new instance of a BigNumber object.
+ *
+ * n {number|string|BigNumber} A numeric value.
+ * [b] {number} The base of n. Integer, 2 to 64 inclusive.
+ */
+ function BigNumber( n, b ) {
+ var c, e, i, num, len, str,
+ x = this;
+
+ // Enable constructor usage without new.
+ if ( !( x instanceof BigNumber ) ) {
+
+ // 'BigNumber() constructor call without new: {n}'
+ if (ERRORS) raise( 26, 'constructor call without new', n );
+ return new BigNumber( n, b );
+ }
+
+ // 'new BigNumber() base not an integer: {b}'
+ // 'new BigNumber() base out of range: {b}'
+ if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
+
+ // Duplicate.
+ if ( n instanceof BigNumber ) {
+ x.s = n.s;
+ x.e = n.e;
+ x.c = ( n = n.c ) ? n.slice() : n;
+ id = 0;
+ return;
+ }
+
+ if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
+ x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
+
+ // Fast path for integers.
+ if ( n === ~~n ) {
+ for ( e = 0, i = n; i >= 10; i /= 10, e++ );
+ x.e = e;
+ x.c = [n];
+ id = 0;
+ return;
+ }
+
+ str = n + '';
+ } else {
+ if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
+ x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
+ }
+ } else {
+ b = b | 0;
+ str = n + '';
+
+ // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
+ // Allow exponential notation to be used with base 10 argument.
+ if ( b == 10 ) {
+ x = new BigNumber( n instanceof BigNumber ? n : str );
+ return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
+ }
+
+ // Avoid potential interpretation of Infinity and NaN as base 44+ values.
+ // Any number in exponential form will fail due to the [Ee][+-].
+ if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
+ !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
+ '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
+ return parseNumeric( x, str, num, b );
+ }
+
+ if (num) {
+ x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
+
+ if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
+
+ // 'new BigNumber() number type has more than 15 significant digits: {n}'
+ raise( id, tooManyDigits, n );
+ }
+
+ // Prevent later check for length on converted number.
+ num = false;
+ } else {
+ x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
+ }
+
+ str = convertBase( str, 10, b, x.s );
+ }
+
+ // Decimal point?
+ if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
+
+ // Exponential form?
+ if ( ( i = str.search( /e/i ) ) > 0 ) {
+
+ // Determine exponent.
+ if ( e < 0 ) e = i;
+ e += +str.slice( i + 1 );
+ str = str.substring( 0, i );
+ } else if ( e < 0 ) {
+
+ // Integer.
+ e = str.length;
+ }
+
+ // Determine leading zeros.
+ for ( i = 0; str.charCodeAt(i) === 48; i++ );
+
+ // Determine trailing zeros.
+ for ( len = str.length; str.charCodeAt(--len) === 48; );
+ str = str.slice( i, len + 1 );
+
+ if (str) {
+ len = str.length;
+
+ // Disallow numbers with over 15 significant digits if number type.
+ // 'new BigNumber() number type has more than 15 significant digits: {n}'
+ if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n );
+
+ e = e - i - 1;
+
+ // Overflow?
+ if ( e > MAX_EXP ) {
+
+ // Infinity.
+ x.c = x.e = null;
+
+ // Underflow?
+ } else if ( e < MIN_EXP ) {
+
+ // Zero.
+ x.c = [ x.e = 0 ];
+ } else {
+ x.e = e;
+ x.c = [];
+
+ // Transform base
+
+ // e is the base 10 exponent.
+ // i is where to slice str to get the first element of the coefficient array.
+ i = ( e + 1 ) % LOG_BASE;
+ if ( e < 0 ) i += LOG_BASE;
+
+ if ( i < len ) {
+ if (i) x.c.push( +str.slice( 0, i ) );
+
+ for ( len -= LOG_BASE; i < len; ) {
+ x.c.push( +str.slice( i, i += LOG_BASE ) );
+ }
+
+ str = str.slice(i);
+ i = LOG_BASE - str.length;
+ } else {
+ i -= len;
+ }
+
+ for ( ; i--; str += '0' );
+ x.c.push( +str );
+ }
+ } else {
+
+ // Zero.
+ x.c = [ x.e = 0 ];
+ }
+
+ id = 0;
+ }
+
+
+ // CONSTRUCTOR PROPERTIES
+
+
+ BigNumber.another = another;
+
+ BigNumber.ROUND_UP = 0;
+ BigNumber.ROUND_DOWN = 1;
+ BigNumber.ROUND_CEIL = 2;
+ BigNumber.ROUND_FLOOR = 3;
+ BigNumber.ROUND_HALF_UP = 4;
+ BigNumber.ROUND_HALF_DOWN = 5;
+ BigNumber.ROUND_HALF_EVEN = 6;
+ BigNumber.ROUND_HALF_CEIL = 7;
+ BigNumber.ROUND_HALF_FLOOR = 8;
+ BigNumber.EUCLID = 9;
+
+
+ /*
+ * Configure infrequently-changing library-wide settings.
+ *
+ * Accept an object or an argument list, with one or many of the following properties or
+ * parameters respectively:
+ *
+ * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
+ * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
+ * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
+ * [integer -MAX to 0 incl., 0 to MAX incl.]
+ * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
+ * [integer -MAX to -1 incl., integer 1 to MAX incl.]
+ * ERRORS {boolean|number} true, false, 1 or 0
+ * CRYPTO {boolean|number} true, false, 1 or 0
+ * MODULO_MODE {number} 0 to 9 inclusive
+ * POW_PRECISION {number} 0 to MAX inclusive
+ * FORMAT {object} See BigNumber.prototype.toFormat
+ * decimalSeparator {string}
+ * groupSeparator {string}
+ * groupSize {number}
+ * secondaryGroupSize {number}
+ * fractionGroupSeparator {string}
+ * fractionGroupSize {number}
+ *
+ * (The values assigned to the above FORMAT object properties are not checked for validity.)
+ *
+ * E.g.
+ * BigNumber.config(20, 4) is equivalent to
+ * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
+ *
+ * Ignore properties/parameters set to null or undefined.
+ * Return an object with the properties current values.
+ */
+ BigNumber.config = function () {
+ var v, p,
+ i = 0,
+ r = {},
+ a = arguments,
+ o = a[0],
+ has = o && typeof o == 'object'
+ ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
+ : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
+
+ // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
+ // 'config() DECIMAL_PLACES not an integer: {v}'
+ // 'config() DECIMAL_PLACES out of range: {v}'
+ if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
+ DECIMAL_PLACES = v | 0;
+ }
+ r[p] = DECIMAL_PLACES;
+
+ // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
+ // 'config() ROUNDING_MODE not an integer: {v}'
+ // 'config() ROUNDING_MODE out of range: {v}'
+ if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
+ ROUNDING_MODE = v | 0;
+ }
+ r[p] = ROUNDING_MODE;
+
+ // EXPONENTIAL_AT {number|number[]}
+ // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
+ // 'config() EXPONENTIAL_AT not an integer: {v}'
+ // 'config() EXPONENTIAL_AT out of range: {v}'
+ if ( has( p = 'EXPONENTIAL_AT' ) ) {
+
+ if ( isArray(v) ) {
+ if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
+ TO_EXP_NEG = v[0] | 0;
+ TO_EXP_POS = v[1] | 0;
+ }
+ } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
+ TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
+ }
+ }
+ r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
+
+ // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
+ // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
+ // 'config() RANGE not an integer: {v}'
+ // 'config() RANGE cannot be zero: {v}'
+ // 'config() RANGE out of range: {v}'
+ if ( has( p = 'RANGE' ) ) {
+
+ if ( isArray(v) ) {
+ if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
+ MIN_EXP = v[0] | 0;
+ MAX_EXP = v[1] | 0;
+ }
+ } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
+ if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
+ else if (ERRORS) raise( 2, p + ' cannot be zero', v );
+ }
+ }
+ r[p] = [ MIN_EXP, MAX_EXP ];
+
+ // ERRORS {boolean|number} true, false, 1 or 0.
+ // 'config() ERRORS not a boolean or binary digit: {v}'
+ if ( has( p = 'ERRORS' ) ) {
+
+ if ( v === !!v || v === 1 || v === 0 ) {
+ id = 0;
+ isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
+ } else if (ERRORS) {
+ raise( 2, p + notBool, v );
+ }
+ }
+ r[p] = ERRORS;
+
+ // CRYPTO {boolean|number} true, false, 1 or 0.
+ // 'config() CRYPTO not a boolean or binary digit: {v}'
+ // 'config() crypto unavailable: {crypto}'
+ if ( has( p = 'CRYPTO' ) ) {
+
+ if ( v === !!v || v === 1 || v === 0 ) {
+ CRYPTO = !!( v && crypto && typeof crypto == 'object' );
+ if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto );
+ } else if (ERRORS) {
+ raise( 2, p + notBool, v );
+ }
+ }
+ r[p] = CRYPTO;
+
+ // MODULO_MODE {number} Integer, 0 to 9 inclusive.
+ // 'config() MODULO_MODE not an integer: {v}'
+ // 'config() MODULO_MODE out of range: {v}'
+ if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
+ MODULO_MODE = v | 0;
+ }
+ r[p] = MODULO_MODE;
+
+ // POW_PRECISION {number} Integer, 0 to MAX inclusive.
+ // 'config() POW_PRECISION not an integer: {v}'
+ // 'config() POW_PRECISION out of range: {v}'
+ if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
+ POW_PRECISION = v | 0;
+ }
+ r[p] = POW_PRECISION;
+
+ // FORMAT {object}
+ // 'config() FORMAT not an object: {v}'
+ if ( has( p = 'FORMAT' ) ) {
+
+ if ( typeof v == 'object' ) {
+ FORMAT = v;
+ } else if (ERRORS) {
+ raise( 2, p + ' not an object', v );
+ }
+ }
+ r[p] = FORMAT;
+
+ return r;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the maximum of the arguments.
+ *
+ * arguments {number|string|BigNumber}
+ */
+ BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
+
+
+ /*
+ * Return a new BigNumber whose value is the minimum of the arguments.
+ *
+ * arguments {number|string|BigNumber}
+ */
+ BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
+
+
+ /*
+ * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
+ * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
+ * zeros are produced).
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ *
+ * 'random() decimal places not an integer: {dp}'
+ * 'random() decimal places out of range: {dp}'
+ * 'random() crypto unavailable: {crypto}'
+ */
+ BigNumber.random = (function () {
+ var pow2_53 = 0x20000000000000;
+
+ // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
+ // Check if Math.random() produces more than 32 bits of randomness.
+ // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
+ // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
+ var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
+ ? function () { return mathfloor( Math.random() * pow2_53 ); }
+ : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
+ (Math.random() * 0x800000 | 0); };
+
+ return function (dp) {
+ var a, b, e, k, v,
+ i = 0,
+ c = [],
+ rand = new BigNumber(ONE);
+
+ dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
+ k = mathceil( dp / LOG_BASE );
+
+ if (CRYPTO) {
+
+ // Browsers supporting crypto.getRandomValues.
+ if ( crypto && crypto.getRandomValues ) {
+
+ a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
+
+ for ( ; i < k; ) {
+
+ // 53 bits:
+ // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
+ // 11111 11111111 11111111 11111111 11100000 00000000 00000000
+ // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
+ // 11111 11111111 11111111
+ // 0x20000 is 2^21.
+ v = a[i] * 0x20000 + (a[i + 1] >>> 11);
+
+ // Rejection sampling:
+ // 0 <= v < 9007199254740992
+ // Probability that v >= 9e15, is
+ // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
+ if ( v >= 9e15 ) {
+ b = crypto.getRandomValues( new Uint32Array(2) );
+ a[i] = b[0];
+ a[i + 1] = b[1];
+ } else {
+
+ // 0 <= v <= 8999999999999999
+ // 0 <= (v % 1e14) <= 99999999999999
+ c.push( v % 1e14 );
+ i += 2;
+ }
+ }
+ i = k / 2;
+
+ // Node.js supporting crypto.randomBytes.
+ } else if ( crypto && crypto.randomBytes ) {
+
+ // buffer
+ a = crypto.randomBytes( k *= 7 );
+
+ for ( ; i < k; ) {
+
+ // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
+ // 0x100000000 is 2^32, 0x1000000 is 2^24
+ // 11111 11111111 11111111 11111111 11111111 11111111 11111111
+ // 0 <= v < 9007199254740992
+ v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
+ ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
+ ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
+
+ if ( v >= 9e15 ) {
+ crypto.randomBytes(7).copy( a, i );
+ } else {
+
+ // 0 <= (v % 1e14) <= 99999999999999
+ c.push( v % 1e14 );
+ i += 7;
+ }
+ }
+ i = k / 7;
+ } else if (ERRORS) {
+ raise( 14, 'crypto unavailable', crypto );
+ }
+ }
+
+ // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false.
+ if (!i) {
+
+ for ( ; i < k; ) {
+ v = random53bitInt();
+ if ( v < 9e15 ) c[i++] = v % 1e14;
+ }
+ }
+
+ k = c[--i];
+ dp %= LOG_BASE;
+
+ // Convert trailing digits to zeros according to dp.
+ if ( k && dp ) {
+ v = POWS_TEN[LOG_BASE - dp];
+ c[i] = mathfloor( k / v ) * v;
+ }
+
+ // Remove trailing elements which are zero.
+ for ( ; c[i] === 0; c.pop(), i-- );
+
+ // Zero?
+ if ( i < 0 ) {
+ c = [ e = 0 ];
+ } else {
+
+ // Remove leading elements which are zero and adjust exponent accordingly.
+ for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE);
+
+ // Count the digits of the first element of c to determine leading zeros, and...
+ for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
+
+ // adjust the exponent accordingly.
+ if ( i < LOG_BASE ) e -= LOG_BASE - i;
+ }
+
+ rand.e = e;
+ rand.c = c;
+ return rand;
+ };
+ })();
+
+
+ // PRIVATE FUNCTIONS
+
+
+ // Convert a numeric string of baseIn to a numeric string of baseOut.
+ function convertBase( str, baseOut, baseIn, sign ) {
+ var d, e, k, r, x, xc, y,
+ i = str.indexOf( '.' ),
+ dp = DECIMAL_PLACES,
+ rm = ROUNDING_MODE;
+
+ if ( baseIn < 37 ) str = str.toLowerCase();
+
+ // Non-integer.
+ if ( i >= 0 ) {
+ k = POW_PRECISION;
+
+ // Unlimited precision.
+ POW_PRECISION = 0;
+ str = str.replace( '.', '' );
+ y = new BigNumber(baseIn);
+ x = y.pow( str.length - i );
+ POW_PRECISION = k;
+
+ // Convert str as if an integer, then restore the fraction part by dividing the
+ // result by its base raised to a power.
+ y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
+ y.e = y.c.length;
+ }
+
+ // Convert the number as integer.
+ xc = toBaseOut( str, baseIn, baseOut );
+ e = k = xc.length;
+
+ // Remove trailing zeros.
+ for ( ; xc[--k] == 0; xc.pop() );
+ if ( !xc[0] ) return '0';
+
+ if ( i < 0 ) {
+ --e;
+ } else {
+ x.c = xc;
+ x.e = e;
+
+ // sign is needed for correct rounding.
+ x.s = sign;
+ x = div( x, y, dp, rm, baseOut );
+ xc = x.c;
+ r = x.r;
+ e = x.e;
+ }
+
+ d = e + dp + 1;
+
+ // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
+ i = xc[d];
+ k = baseOut / 2;
+ r = r || d < 0 || xc[d + 1] != null;
+
+ r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
+ : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
+ rm == ( x.s < 0 ? 8 : 7 ) );
+
+ if ( d < 1 || !xc[0] ) {
+
+ // 1^-dp or 0.
+ str = r ? toFixedPoint( '1', -dp ) : '0';
+ } else {
+ xc.length = d;
+
+ if (r) {
+
+ // Rounding up may mean the previous digit has to be rounded up and so on.
+ for ( --baseOut; ++xc[--d] > baseOut; ) {
+ xc[d] = 0;
+
+ if ( !d ) {
+ ++e;
+ xc.unshift(1);
+ }
+ }
+ }
+
+ // Determine trailing zeros.
+ for ( k = xc.length; !xc[--k]; );
+
+ // E.g. [4, 11, 15] becomes 4bf.
+ for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
+ str = toFixedPoint( str, e );
+ }
+
+ // The caller will add the sign.
+ return str;
+ }
+
+
+ // Perform division in the specified base. Called by div and convertBase.
+ div = (function () {
+
+ // Assume non-zero x and k.
+ function multiply( x, k, base ) {
+ var m, temp, xlo, xhi,
+ carry = 0,
+ i = x.length,
+ klo = k % SQRT_BASE,
+ khi = k / SQRT_BASE | 0;
+
+ for ( x = x.slice(); i--; ) {
+ xlo = x[i] % SQRT_BASE;
+ xhi = x[i] / SQRT_BASE | 0;
+ m = khi * xlo + xhi * klo;
+ temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
+ carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
+ x[i] = temp % base;
+ }
+
+ if (carry) x.unshift(carry);
+
+ return x;
+ }
+
+ function compare( a, b, aL, bL ) {
+ var i, cmp;
+
+ if ( aL != bL ) {
+ cmp = aL > bL ? 1 : -1;
+ } else {
+
+ for ( i = cmp = 0; i < aL; i++ ) {
+
+ if ( a[i] != b[i] ) {
+ cmp = a[i] > b[i] ? 1 : -1;
+ break;
+ }
+ }
+ }
+ return cmp;
+ }
+
+ function subtract( a, b, aL, base ) {
+ var i = 0;
+
+ // Subtract b from a.
+ for ( ; aL--; ) {
+ a[aL] -= i;
+ i = a[aL] < b[aL] ? 1 : 0;
+ a[aL] = i * base + a[aL] - b[aL];
+ }
+
+ // Remove leading zeros.
+ for ( ; !a[0] && a.length > 1; a.shift() );
+ }
+
+ // x: dividend, y: divisor.
+ return function ( x, y, dp, rm, base ) {
+ var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
+ yL, yz,
+ s = x.s == y.s ? 1 : -1,
+ xc = x.c,
+ yc = y.c;
+
+ // Either NaN, Infinity or 0?
+ if ( !xc || !xc[0] || !yc || !yc[0] ) {
+
+ return new BigNumber(
+
+ // Return NaN if either NaN, or both Infinity or 0.
+ !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
+
+ // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
+ xc && xc[0] == 0 || !yc ? s * 0 : s / 0
+ );
+ }
+
+ q = new BigNumber(s);
+ qc = q.c = [];
+ e = x.e - y.e;
+ s = dp + e + 1;
+
+ if ( !base ) {
+ base = BASE;
+ e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
+ s = s / LOG_BASE | 0;
+ }
+
+ // Result exponent may be one less then the current value of e.
+ // The coefficients of the BigNumbers from convertBase may have trailing zeros.
+ for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
+ if ( yc[i] > ( xc[i] || 0 ) ) e--;
+
+ if ( s < 0 ) {
+ qc.push(1);
+ more = true;
+ } else {
+ xL = xc.length;
+ yL = yc.length;
+ i = 0;
+ s += 2;
+
+ // Normalise xc and yc so highest order digit of yc is >= base / 2.
+
+ n = mathfloor( base / ( yc[0] + 1 ) );
+
+ // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
+ // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
+ if ( n > 1 ) {
+ yc = multiply( yc, n, base );
+ xc = multiply( xc, n, base );
+ yL = yc.length;
+ xL = xc.length;
+ }
+
+ xi = yL;
+ rem = xc.slice( 0, yL );
+ remL = rem.length;
+
+ // Add zeros to make remainder as long as divisor.
+ for ( ; remL < yL; rem[remL++] = 0 );
+ yz = yc.slice();
+ yz.unshift(0);
+ yc0 = yc[0];
+ if ( yc[1] >= base / 2 ) yc0++;
+ // Not necessary, but to prevent trial digit n > base, when using base 3.
+ // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
+
+ do {
+ n = 0;
+
+ // Compare divisor and remainder.
+ cmp = compare( yc, rem, yL, remL );
+
+ // If divisor < remainder.
+ if ( cmp < 0 ) {
+
+ // Calculate trial digit, n.
+
+ rem0 = rem[0];
+ if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
+
+ // n is how many times the divisor goes into the current remainder.
+ n = mathfloor( rem0 / yc0 );
+
+ // Algorithm:
+ // 1. product = divisor * trial digit (n)
+ // 2. if product > remainder: product -= divisor, n--
+ // 3. remainder -= product
+ // 4. if product was < remainder at 2:
+ // 5. compare new remainder and divisor
+ // 6. If remainder > divisor: remainder -= divisor, n++
+
+ if ( n > 1 ) {
+
+ // n may be > base only when base is 3.
+ if (n >= base) n = base - 1;
+
+ // product = divisor * trial digit.
+ prod = multiply( yc, n, base );
+ prodL = prod.length;
+ remL = rem.length;
+
+ // Compare product and remainder.
+ // If product > remainder.
+ // Trial digit n too high.
+ // n is 1 too high about 5% of the time, and is not known to have
+ // ever been more than 1 too high.
+ while ( compare( prod, rem, prodL, remL ) == 1 ) {
+ n--;
+
+ // Subtract divisor from product.
+ subtract( prod, yL < prodL ? yz : yc, prodL, base );
+ prodL = prod.length;
+ cmp = 1;
+ }
+ } else {
+
+ // n is 0 or 1, cmp is -1.
+ // If n is 0, there is no need to compare yc and rem again below,
+ // so change cmp to 1 to avoid it.
+ // If n is 1, leave cmp as -1, so yc and rem are compared again.
+ if ( n == 0 ) {
+
+ // divisor < remainder, so n must be at least 1.
+ cmp = n = 1;
+ }
+
+ // product = divisor
+ prod = yc.slice();
+ prodL = prod.length;
+ }
+
+ if ( prodL < remL ) prod.unshift(0);
+
+ // Subtract product from remainder.
+ subtract( rem, prod, remL, base );
+ remL = rem.length;
+
+ // If product was < remainder.
+ if ( cmp == -1 ) {
+
+ // Compare divisor and new remainder.
+ // If divisor < new remainder, subtract divisor from remainder.
+ // Trial digit n too low.
+ // n is 1 too low about 5% of the time, and very rarely 2 too low.
+ while ( compare( yc, rem, yL, remL ) < 1 ) {
+ n++;
+
+ // Subtract divisor from remainder.
+ subtract( rem, yL < remL ? yz : yc, remL, base );
+ remL = rem.length;
+ }
+ }
+ } else if ( cmp === 0 ) {
+ n++;
+ rem = [0];
+ } // else cmp === 1 and n will be 0
+
+ // Add the next digit, n, to the result array.
+ qc[i++] = n;
+
+ // Update the remainder.
+ if ( rem[0] ) {
+ rem[remL++] = xc[xi] || 0;
+ } else {
+ rem = [ xc[xi] ];
+ remL = 1;
+ }
+ } while ( ( xi++ < xL || rem[0] != null ) && s-- );
+
+ more = rem[0] != null;
+
+ // Leading zero?
+ if ( !qc[0] ) qc.shift();
+ }
+
+ if ( base == BASE ) {
+
+ // To calculate q.e, first get the number of digits of qc[0].
+ for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
+ round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
+
+ // Caller is convertBase.
+ } else {
+ q.e = e;
+ q.r = +more;
+ }
+
+ return q;
+ };
+ })();
+
+
+ /*
+ * Return a string representing the value of BigNumber n in fixed-point or exponential
+ * notation rounded to the specified decimal places or significant digits.
+ *
+ * n is a BigNumber.
+ * i is the index of the last digit required (i.e. the digit that may be rounded up).
+ * rm is the rounding mode.
+ * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
+ */
+ function format( n, i, rm, caller ) {
+ var c0, e, ne, len, str;
+
+ rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
+ ? rm | 0 : ROUNDING_MODE;
+
+ if ( !n.c ) return n.toString();
+ c0 = n.c[0];
+ ne = n.e;
+
+ if ( i == null ) {
+ str = coeffToString( n.c );
+ str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
+ ? toExponential( str, ne )
+ : toFixedPoint( str, ne );
+ } else {
+ n = round( new BigNumber(n), i, rm );
+
+ // n.e may have changed if the value was rounded up.
+ e = n.e;
+
+ str = coeffToString( n.c );
+ len = str.length;
+
+ // toPrecision returns exponential notation if the number of significant digits
+ // specified is less than the number of digits necessary to represent the integer
+ // part of the value in fixed-point notation.
+
+ // Exponential notation.
+ if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
+
+ // Append zeros?
+ for ( ; len < i; str += '0', len++ );
+ str = toExponential( str, e );
+
+ // Fixed-point notation.
+ } else {
+ i -= ne;
+ str = toFixedPoint( str, e );
+
+ // Append zeros?
+ if ( e + 1 > len ) {
+ if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
+ } else {
+ i += e - len;
+ if ( i > 0 ) {
+ if ( e + 1 == len ) str += '.';
+ for ( ; i--; str += '0' );
+ }
+ }
+ }
+ }
+
+ return n.s < 0 && c0 ? '-' + str : str;
+ }
+
+
+ // Handle BigNumber.max and BigNumber.min.
+ function maxOrMin( args, method ) {
+ var m, n,
+ i = 0;
+
+ if ( isArray( args[0] ) ) args = args[0];
+ m = new BigNumber( args[0] );
+
+ for ( ; ++i < args.length; ) {
+ n = new BigNumber( args[i] );
+
+ // If any number is NaN, return NaN.
+ if ( !n.s ) {
+ m = n;
+ break;
+ } else if ( method.call( m, n ) ) {
+ m = n;
+ }
+ }
+
+ return m;
+ }
+
+
+ /*
+ * Return true if n is an integer in range, otherwise throw.
+ * Use for argument validation when ERRORS is true.
+ */
+ function intValidatorWithErrors( n, min, max, caller, name ) {
+ if ( n < min || n > max || n != truncate(n) ) {
+ raise( caller, ( name || 'decimal places' ) +
+ ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
+ }
+
+ return true;
+ }
+
+
+ /*
+ * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
+ * Called by minus, plus and times.
+ */
+ function normalise( n, c, e ) {
+ var i = 1,
+ j = c.length;
+
+ // Remove trailing zeros.
+ for ( ; !c[--j]; c.pop() );
+
+ // Calculate the base 10 exponent. First get the number of digits of c[0].
+ for ( j = c[0]; j >= 10; j /= 10, i++ );
+
+ // Overflow?
+ if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
+
+ // Infinity.
+ n.c = n.e = null;
+
+ // Underflow?
+ } else if ( e < MIN_EXP ) {
+
+ // Zero.
+ n.c = [ n.e = 0 ];
+ } else {
+ n.e = e;
+ n.c = c;
+ }
+
+ return n;
+ }
+
+
+ // Handle values that fail the validity test in BigNumber.
+ parseNumeric = (function () {
+ var basePrefix=/^(-?)0([xbo])/i,
+ dotAfter=/^([^.]+)\.$/,
+ dotBefore=/^\.([^.]+)$/,
+ isInfinityOrNaN=/^-?(Infinity|NaN)$/,
+ whitespaceOrPlus=/^\s*\+|^\s+|\s+$/g;
+
+ return function ( x, str, num, b ) {
+ var base,
+ s = num ? str : str.replace( whitespaceOrPlus, '' );
+
+ // No exception on ±Infinity or NaN.
+ if ( isInfinityOrNaN.test(s) ) {
+ x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
+ } else {
+ if ( !num ) {
+
+ // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
+ s = s.replace( basePrefix, function ( m, p1, p2 ) {
+ base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
+ return !b || b == base ? p1 : m;
+ });
+
+ if (b) {
+ base = b;
+
+ // E.g. '1.' to '1', '.1' to '0.1'
+ s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
+ }
+
+ if ( str != s ) return new BigNumber( s, base );
+ }
+
+ // 'new BigNumber() not a number: {n}'
+ // 'new BigNumber() not a base {b} number: {n}'
+ if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
+ x.s = null;
+ }
+
+ x.c = x.e = null;
+ id = 0;
+ }
+ })();
+
+
+ // Throw a BigNumber Error.
+ function raise( caller, msg, val ) {
+ var error = new Error( [
+ 'new BigNumber', // 0
+ 'cmp', // 1
+ 'config', // 2
+ 'div', // 3
+ 'divToInt', // 4
+ 'eq', // 5
+ 'gt', // 6
+ 'gte', // 7
+ 'lt', // 8
+ 'lte', // 9
+ 'minus', // 10
+ 'mod', // 11
+ 'plus', // 12
+ 'precision', // 13
+ 'random', // 14
+ 'round', // 15
+ 'shift', // 16
+ 'times', // 17
+ 'toDigits', // 18
+ 'toExponential', // 19
+ 'toFixed', // 20
+ 'toFormat', // 21
+ 'toFraction', // 22
+ 'pow', // 23
+ 'toPrecision', // 24
+ 'toString', // 25
+ 'BigNumber' // 26
+ ][caller] + '() ' + msg + ': ' + val );
+
+ error.name = 'BigNumber Error';
+ id = 0;
+ throw error;
+ }
+
+
+ /*
+ * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
+ * If r is truthy, it is known that there are more digits after the rounding digit.
+ */
+ function round( x, sd, rm, r ) {
+ var d, i, j, k, n, ni, rd,
+ xc = x.c,
+ pows10 = POWS_TEN;
+
+ // if x is not Infinity or NaN...
+ if (xc) {
+
+ // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
+ // n is a base 1e14 number, the value of the element of array x.c containing rd.
+ // ni is the index of n within x.c.
+ // d is the number of digits of n.
+ // i is the index of rd within n including leading zeros.
+ // j is the actual index of rd within n (if < 0, rd is a leading zero).
+ out: {
+
+ // Get the number of digits of the first element of xc.
+ for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
+ i = sd - d;
+
+ // If the rounding digit is in the first element of xc...
+ if ( i < 0 ) {
+ i += LOG_BASE;
+ j = sd;
+ n = xc[ ni = 0 ];
+
+ // Get the rounding digit at index j of n.
+ rd = n / pows10[ d - j - 1 ] % 10 | 0;
+ } else {
+ ni = mathceil( ( i + 1 ) / LOG_BASE );
+
+ if ( ni >= xc.length ) {
+
+ if (r) {
+
+ // Needed by sqrt.
+ for ( ; xc.length <= ni; xc.push(0) );
+ n = rd = 0;
+ d = 1;
+ i %= LOG_BASE;
+ j = i - LOG_BASE + 1;
+ } else {
+ break out;
+ }
+ } else {
+ n = k = xc[ni];
+
+ // Get the number of digits of n.
+ for ( d = 1; k >= 10; k /= 10, d++ );
+
+ // Get the index of rd within n.
+ i %= LOG_BASE;
+
+ // Get the index of rd within n, adjusted for leading zeros.
+ // The number of leading zeros of n is given by LOG_BASE - d.
+ j = i - LOG_BASE + d;
+
+ // Get the rounding digit at index j of n.
+ rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
+ }
+ }
+
+ r = r || sd < 0 ||
+
+ // Are there any non-zero digits after the rounding digit?
+ // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
+ // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
+ xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
+
+ r = rm < 4
+ ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
+ : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
+
+ // Check whether the digit to the left of the rounding digit is odd.
+ ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
+ rm == ( x.s < 0 ? 8 : 7 ) );
+
+ if ( sd < 1 || !xc[0] ) {
+ xc.length = 0;
+
+ if (r) {
+
+ // Convert sd to decimal places.
+ sd -= x.e + 1;
+
+ // 1, 0.1, 0.01, 0.001, 0.0001 etc.
+ xc[0] = pows10[ sd % LOG_BASE ];
+ x.e = -sd || 0;
+ } else {
+
+ // Zero.
+ xc[0] = x.e = 0;
+ }
+
+ return x;
+ }
+
+ // Remove excess digits.
+ if ( i == 0 ) {
+ xc.length = ni;
+ k = 1;
+ ni--;
+ } else {
+ xc.length = ni + 1;
+ k = pows10[ LOG_BASE - i ];
+
+ // E.g. 56700 becomes 56000 if 7 is the rounding digit.
+ // j > 0 means i > number of leading zeros of n.
+ xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
+ }
+
+ // Round up?
+ if (r) {
+
+ for ( ; ; ) {
+
+ // If the digit to be rounded up is in the first element of xc...
+ if ( ni == 0 ) {
+
+ // i will be the length of xc[0] before k is added.
+ for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
+ j = xc[0] += k;
+ for ( k = 1; j >= 10; j /= 10, k++ );
+
+ // if i != k the length has increased.
+ if ( i != k ) {
+ x.e++;
+ if ( xc[0] == BASE ) xc[0] = 1;
+ }
+
+ break;
+ } else {
+ xc[ni] += k;
+ if ( xc[ni] != BASE ) break;
+ xc[ni--] = 0;
+ k = 1;
+ }
+ }
+ }
+
+ // Remove trailing zeros.
+ for ( i = xc.length; xc[--i] === 0; xc.pop() );
+ }
+
+ // Overflow? Infinity.
+ if ( x.e > MAX_EXP ) {
+ x.c = x.e = null;
+
+ // Underflow? Zero.
+ } else if ( x.e < MIN_EXP ) {
+ x.c = [ x.e = 0 ];
+ }
+ }
+
+ return x;
+ }
+
+
+ // PROTOTYPE/INSTANCE METHODS
+
+
+ /*
+ * Return a new BigNumber whose value is the absolute value of this BigNumber.
+ */
+ P.absoluteValue = P.abs = function () {
+ var x = new BigNumber(this);
+ if ( x.s < 0 ) x.s = 1;
+ return x;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
+ * number in the direction of Infinity.
+ */
+ P.ceil = function () {
+ return round( new BigNumber(this), this.e + 1, 2 );
+ };
+
+
+ /*
+ * Return
+ * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
+ * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
+ * 0 if they have the same value,
+ * or null if the value of either is NaN.
+ */
+ P.comparedTo = P.cmp = function ( y, b ) {
+ id = 1;
+ return compare( this, new BigNumber( y, b ) );
+ };
+
+
+ /*
+ * Return the number of decimal places of the value of this BigNumber, or null if the value
+ * of this BigNumber is ±Infinity or NaN.
+ */
+ P.decimalPlaces = P.dp = function () {
+ var n, v,
+ c = this.c;
+
+ if ( !c ) return null;
+ n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
+
+ // Subtract the number of trailing zeros of the last number.
+ if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
+ if ( n < 0 ) n = 0;
+
+ return n;
+ };
+
+
+ /*
+ * n / 0 = I
+ * n / N = N
+ * n / I = 0
+ * 0 / n = 0
+ * 0 / 0 = N
+ * 0 / N = N
+ * 0 / I = 0
+ * N / n = N
+ * N / 0 = N
+ * N / N = N
+ * N / I = N
+ * I / n = I
+ * I / 0 = I
+ * I / N = N
+ * I / I = N
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
+ * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
+ */
+ P.dividedBy = P.div = function ( y, b ) {
+ id = 3;
+ return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the integer part of dividing the value of this
+ * BigNumber by the value of BigNumber(y, b).
+ */
+ P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
+ id = 4;
+ return div( this, new BigNumber( y, b ), 0, 1 );
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
+ * otherwise returns false.
+ */
+ P.equals = P.eq = function ( y, b ) {
+ id = 5;
+ return compare( this, new BigNumber( y, b ) ) === 0;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
+ * number in the direction of -Infinity.
+ */
+ P.floor = function () {
+ return round( new BigNumber(this), this.e + 1, 3 );
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
+ * otherwise returns false.
+ */
+ P.greaterThan = P.gt = function ( y, b ) {
+ id = 6;
+ return compare( this, new BigNumber( y, b ) ) > 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is greater than or equal to the value of
+ * BigNumber(y, b), otherwise returns false.
+ */
+ P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
+ id = 7;
+ return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
+
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is a finite number, otherwise returns false.
+ */
+ P.isFinite = function () {
+ return !!this.c;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is an integer, otherwise return false.
+ */
+ P.isInteger = P.isInt = function () {
+ return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is NaN, otherwise returns false.
+ */
+ P.isNaN = function () {
+ return !this.s;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is negative, otherwise returns false.
+ */
+ P.isNegative = P.isNeg = function () {
+ return this.s < 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
+ */
+ P.isZero = function () {
+ return !!this.c && this.c[0] == 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
+ * otherwise returns false.
+ */
+ P.lessThan = P.lt = function ( y, b ) {
+ id = 8;
+ return compare( this, new BigNumber( y, b ) ) < 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is less than or equal to the value of
+ * BigNumber(y, b), otherwise returns false.
+ */
+ P.lessThanOrEqualTo = P.lte = function ( y, b ) {
+ id = 9;
+ return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
+ };
+
+
+ /*
+ * n - 0 = n
+ * n - N = N
+ * n - I = -I
+ * 0 - n = -n
+ * 0 - 0 = 0
+ * 0 - N = N
+ * 0 - I = -I
+ * N - n = N
+ * N - 0 = N
+ * N - N = N
+ * N - I = N
+ * I - n = I
+ * I - 0 = I
+ * I - N = N
+ * I - I = N
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber minus the value of
+ * BigNumber(y, b).
+ */
+ P.minus = P.sub = function ( y, b ) {
+ var i, j, t, xLTy,
+ x = this,
+ a = x.s;
+
+ id = 10;
+ y = new BigNumber( y, b );
+ b = y.s;
+
+ // Either NaN?
+ if ( !a || !b ) return new BigNumber(NaN);
+
+ // Signs differ?
+ if ( a != b ) {
+ y.s = -b;
+ return x.plus(y);
+ }
+
+ var xe = x.e / LOG_BASE,
+ ye = y.e / LOG_BASE,
+ xc = x.c,
+ yc = y.c;
+
+ if ( !xe || !ye ) {
+
+ // Either Infinity?
+ if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
+
+ // Either zero?
+ if ( !xc[0] || !yc[0] ) {
+
+ // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
+ return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
+
+ // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
+ ROUNDING_MODE == 3 ? -0 : 0 );
+ }
+ }
+
+ xe = bitFloor(xe);
+ ye = bitFloor(ye);
+ xc = xc.slice();
+
+ // Determine which is the bigger number.
+ if ( a = xe - ye ) {
+
+ if ( xLTy = a < 0 ) {
+ a = -a;
+ t = xc;
+ } else {
+ ye = xe;
+ t = yc;
+ }
+
+ t.reverse();
+
+ // Prepend zeros to equalise exponents.
+ for ( b = a; b--; t.push(0) );
+ t.reverse();
+ } else {
+
+ // Exponents equal. Check digit by digit.
+ j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
+
+ for ( a = b = 0; b < j; b++ ) {
+
+ if ( xc[b] != yc[b] ) {
+ xLTy = xc[b] < yc[b];
+ break;
+ }
+ }
+ }
+
+ // x < y? Point xc to the array of the bigger number.
+ if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
+
+ b = ( j = yc.length ) - ( i = xc.length );
+
+ // Append zeros to xc if shorter.
+ // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
+ if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
+ b = BASE - 1;
+
+ // Subtract yc from xc.
+ for ( ; j > a; ) {
+
+ if ( xc[--j] < yc[j] ) {
+ for ( i = j; i && !xc[--i]; xc[i] = b );
+ --xc[i];
+ xc[j] += BASE;
+ }
+
+ xc[j] -= yc[j];
+ }
+
+ // Remove leading zeros and adjust exponent accordingly.
+ for ( ; xc[0] == 0; xc.shift(), --ye );
+
+ // Zero?
+ if ( !xc[0] ) {
+
+ // Following IEEE 754 (2008) 6.3,
+ // n - n = +0 but n - n = -0 when rounding towards -Infinity.
+ y.s = ROUNDING_MODE == 3 ? -1 : 1;
+ y.c = [ y.e = 0 ];
+ return y;
+ }
+
+ // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
+ // for finite x and y.
+ return normalise( y, xc, ye );
+ };
+
+
+ /*
+ * n % 0 = N
+ * n % N = N
+ * n % I = n
+ * 0 % n = 0
+ * -0 % n = -0
+ * 0 % 0 = N
+ * 0 % N = N
+ * 0 % I = 0
+ * N % n = N
+ * N % 0 = N
+ * N % N = N
+ * N % I = N
+ * I % n = N
+ * I % 0 = N
+ * I % N = N
+ * I % I = N
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
+ * BigNumber(y, b). The result depends on the value of MODULO_MODE.
+ */
+ P.modulo = P.mod = function ( y, b ) {
+ var q, s,
+ x = this;
+
+ id = 11;
+ y = new BigNumber( y, b );
+
+ // Return NaN if x is Infinity or NaN, or y is NaN or zero.
+ if ( !x.c || !y.s || y.c && !y.c[0] ) {
+ return new BigNumber(NaN);
+
+ // Return x if y is Infinity or x is zero.
+ } else if ( !y.c || x.c && !x.c[0] ) {
+ return new BigNumber(x);
+ }
+
+ if ( MODULO_MODE == 9 ) {
+
+ // Euclidian division: q = sign(y) * floor(x / abs(y))
+ // r = x - qy where 0 <= r < abs(y)
+ s = y.s;
+ y.s = 1;
+ q = div( x, y, 0, 3 );
+ y.s = s;
+ q.s *= s;
+ } else {
+ q = div( x, y, 0, MODULO_MODE );
+ }
+
+ return x.minus( q.times(y) );
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber negated,
+ * i.e. multiplied by -1.
+ */
+ P.negated = P.neg = function () {
+ var x = new BigNumber(this);
+ x.s = -x.s || null;
+ return x;
+ };
+
+
+ /*
+ * n + 0 = n
+ * n + N = N
+ * n + I = I
+ * 0 + n = n
+ * 0 + 0 = 0
+ * 0 + N = N
+ * 0 + I = I
+ * N + n = N
+ * N + 0 = N
+ * N + N = N
+ * N + I = N
+ * I + n = I
+ * I + 0 = I
+ * I + N = N
+ * I + I = I
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber plus the value of
+ * BigNumber(y, b).
+ */
+ P.plus = P.add = function ( y, b ) {
+ var t,
+ x = this,
+ a = x.s;
+
+ id = 12;
+ y = new BigNumber( y, b );
+ b = y.s;
+
+ // Either NaN?
+ if ( !a || !b ) return new BigNumber(NaN);
+
+ // Signs differ?
+ if ( a != b ) {
+ y.s = -b;
+ return x.minus(y);
+ }
+
+ var xe = x.e / LOG_BASE,
+ ye = y.e / LOG_BASE,
+ xc = x.c,
+ yc = y.c;
+
+ if ( !xe || !ye ) {
+
+ // Return ±Infinity if either ±Infinity.
+ if ( !xc || !yc ) return new BigNumber( a / 0 );
+
+ // Either zero?
+ // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
+ if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
+ }
+
+ xe = bitFloor(xe);
+ ye = bitFloor(ye);
+ xc = xc.slice();
+
+ // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
+ if ( a = xe - ye ) {
+ if ( a > 0 ) {
+ ye = xe;
+ t = yc;
+ } else {
+ a = -a;
+ t = xc;
+ }
+
+ t.reverse();
+ for ( ; a--; t.push(0) );
+ t.reverse();
+ }
+
+ a = xc.length;
+ b = yc.length;
+
+ // Point xc to the longer array, and b to the shorter length.
+ if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
+
+ // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
+ for ( a = 0; b; ) {
+ a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
+ xc[b] %= BASE;
+ }
+
+ if (a) {
+ xc.unshift(a);
+ ++ye;
+ }
+
+ // No need to check for zero, as +x + +y != 0 && -x + -y != 0
+ // ye = MAX_EXP + 1 possible
+ return normalise( y, xc, ye );
+ };
+
+
+ /*
+ * Return the number of significant digits of the value of this BigNumber.
+ *
+ * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
+ */
+ P.precision = P.sd = function (z) {
+ var n, v,
+ x = this,
+ c = x.c;
+
+ // 'precision() argument not a boolean or binary digit: {z}'
+ if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
+ if (ERRORS) raise( 13, 'argument' + notBool, z );
+ if ( z != !!z ) z = null;
+ }
+
+ if ( !c ) return null;
+ v = c.length - 1;
+ n = v * LOG_BASE + 1;
+
+ if ( v = c[v] ) {
+
+ // Subtract the number of trailing zeros of the last element.
+ for ( ; v % 10 == 0; v /= 10, n-- );
+
+ // Add the number of digits of the first element.
+ for ( v = c[0]; v >= 10; v /= 10, n++ );
+ }
+
+ if ( z && x.e + 1 > n ) n = x.e + 1;
+
+ return n;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
+ * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
+ * omitted.
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * 'round() decimal places out of range: {dp}'
+ * 'round() decimal places not an integer: {dp}'
+ * 'round() rounding mode not an integer: {rm}'
+ * 'round() rounding mode out of range: {rm}'
+ */
+ P.round = function ( dp, rm ) {
+ var n = new BigNumber(this);
+
+ if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
+ round( n, ~~dp + this.e + 1, rm == null ||
+ !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
+ }
+
+ return n;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
+ * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
+ *
+ * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
+ *
+ * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
+ * otherwise.
+ *
+ * 'shift() argument not an integer: {k}'
+ * 'shift() argument out of range: {k}'
+ */
+ P.shift = function (k) {
+ var n = this;
+ return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
+
+ // k < 1e+21, or truncate(k) will produce exponential notation.
+ ? n.times( '1e' + truncate(k) )
+ : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
+ ? n.s * ( k < 0 ? 0 : 1 / 0 )
+ : n );
+ };
+
+
+ /*
+ * sqrt(-n) = N
+ * sqrt( N) = N
+ * sqrt(-I) = N
+ * sqrt( I) = I
+ * sqrt( 0) = 0
+ * sqrt(-0) = -0
+ *
+ * Return a new BigNumber whose value is the square root of the value of this BigNumber,
+ * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
+ */
+ P.squareRoot = P.sqrt = function () {
+ var m, n, r, rep, t,
+ x = this,
+ c = x.c,
+ s = x.s,
+ e = x.e,
+ dp = DECIMAL_PLACES + 4,
+ half = new BigNumber('0.5');
+
+ // Negative/NaN/Infinity/zero?
+ if ( s !== 1 || !c || !c[0] ) {
+ return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
+ }
+
+ // Initial estimate.
+ s = Math.sqrt( +x );
+
+ // Math.sqrt underflow/overflow?
+ // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
+ if ( s == 0 || s == 1 / 0 ) {
+ n = coeffToString(c);
+ if ( ( n.length + e ) % 2 == 0 ) n += '0';
+ s = Math.sqrt(n);
+ e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
+
+ if ( s == 1 / 0 ) {
+ n = '1e' + e;
+ } else {
+ n = s.toExponential();
+ n = n.slice( 0, n.indexOf('e') + 1 ) + e;
+ }
+
+ r = new BigNumber(n);
+ } else {
+ r = new BigNumber( s + '' );
+ }
+
+ // Check for zero.
+ // r could be zero if MIN_EXP is changed after the this value was created.
+ // This would cause a division by zero (x/t) and hence Infinity below, which would cause
+ // coeffToString to throw.
+ if ( r.c[0] ) {
+ e = r.e;
+ s = e + dp;
+ if ( s < 3 ) s = 0;
+
+ // Newton-Raphson iteration.
+ for ( ; ; ) {
+ t = r;
+ r = half.times( t.plus( div( x, t, dp, 1 ) ) );
+
+ if ( coeffToString( t.c ).slice( 0, s ) === ( n =
+ coeffToString( r.c ) ).slice( 0, s ) ) {
+
+ // The exponent of r may here be one less than the final result exponent,
+ // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
+ // are indexed correctly.
+ if ( r.e < e ) --s;
+ n = n.slice( s - 3, s + 1 );
+
+ // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
+ // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
+ // iteration.
+ if ( n == '9999' || !rep && n == '4999' ) {
+
+ // On the first iteration only, check to see if rounding up gives the
+ // exact result as the nines may infinitely repeat.
+ if ( !rep ) {
+ round( t, t.e + DECIMAL_PLACES + 2, 0 );
+
+ if ( t.times(t).eq(x) ) {
+ r = t;
+ break;
+ }
+ }
+
+ dp += 4;
+ s += 4;
+ rep = 1;
+ } else {
+
+ // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
+ // result. If not, then there are further digits and m will be truthy.
+ if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
+
+ // Truncate to the first rounding digit.
+ round( r, r.e + DECIMAL_PLACES + 2, 1 );
+ m = !r.times(r).eq(x);
+ }
+
+ break;
+ }
+ }
+ }
+ }
+
+ return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
+ };
+
+
+ /*
+ * n * 0 = 0
+ * n * N = N
+ * n * I = I
+ * 0 * n = 0
+ * 0 * 0 = 0
+ * 0 * N = N
+ * 0 * I = N
+ * N * n = N
+ * N * 0 = N
+ * N * N = N
+ * N * I = N
+ * I * n = I
+ * I * 0 = N
+ * I * N = N
+ * I * I = I
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber times the value of
+ * BigNumber(y, b).
+ */
+ P.times = P.mul = function ( y, b ) {
+ var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
+ base, sqrtBase,
+ x = this,
+ xc = x.c,
+ yc = ( id = 17, y = new BigNumber( y, b ) ).c;
+
+ // Either NaN, ±Infinity or ±0?
+ if ( !xc || !yc || !xc[0] || !yc[0] ) {
+
+ // Return NaN if either is NaN, or one is 0 and the other is Infinity.
+ if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
+ y.c = y.e = y.s = null;
+ } else {
+ y.s *= x.s;
+
+ // Return ±Infinity if either is ±Infinity.
+ if ( !xc || !yc ) {
+ y.c = y.e = null;
+
+ // Return ±0 if either is ±0.
+ } else {
+ y.c = [0];
+ y.e = 0;
+ }
+ }
+
+ return y;
+ }
+
+ e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
+ y.s *= x.s;
+ xcL = xc.length;
+ ycL = yc.length;
+
+ // Ensure xc points to longer array and xcL to its length.
+ if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
+
+ // Initialise the result array with zeros.
+ for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
+
+ base = BASE;
+ sqrtBase = SQRT_BASE;
+
+ for ( i = ycL; --i >= 0; ) {
+ c = 0;
+ ylo = yc[i] % sqrtBase;
+ yhi = yc[i] / sqrtBase | 0;
+
+ for ( k = xcL, j = i + k; j > i; ) {
+ xlo = xc[--k] % sqrtBase;
+ xhi = xc[k] / sqrtBase | 0;
+ m = yhi * xlo + xhi * ylo;
+ xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
+ c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
+ zc[j--] = xlo % base;
+ }
+
+ zc[j] = c;
+ }
+
+ if (c) {
+ ++e;
+ } else {
+ zc.shift();
+ }
+
+ return normalise( y, zc, e );
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
+ * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
+ *
+ * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * 'toDigits() precision out of range: {sd}'
+ * 'toDigits() precision not an integer: {sd}'
+ * 'toDigits() rounding mode not an integer: {rm}'
+ * 'toDigits() rounding mode out of range: {rm}'
+ */
+ P.toDigits = function ( sd, rm ) {
+ var n = new BigNumber(this);
+ sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
+ rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
+ return sd ? round( n, sd, rm ) : n;
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in exponential notation and
+ * rounded using ROUNDING_MODE to dp fixed decimal places.
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * 'toExponential() decimal places not an integer: {dp}'
+ * 'toExponential() decimal places out of range: {dp}'
+ * 'toExponential() rounding mode not an integer: {rm}'
+ * 'toExponential() rounding mode out of range: {rm}'
+ */
+ P.toExponential = function ( dp, rm ) {
+ return format( this,
+ dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in fixed-point notation rounding
+ * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
+ *
+ * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
+ * but e.g. (-0.00001).toFixed(0) is '-0'.
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * 'toFixed() decimal places not an integer: {dp}'
+ * 'toFixed() decimal places out of range: {dp}'
+ * 'toFixed() rounding mode not an integer: {rm}'
+ * 'toFixed() rounding mode out of range: {rm}'
+ */
+ P.toFixed = function ( dp, rm ) {
+ return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
+ ? ~~dp + this.e + 1 : null, rm, 20 );
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in fixed-point notation rounded
+ * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
+ * of the FORMAT object (see BigNumber.config).
+ *
+ * FORMAT = {
+ * decimalSeparator : '.',
+ * groupSeparator : ',',
+ * groupSize : 3,
+ * secondaryGroupSize : 0,
+ * fractionGroupSeparator : '\xA0', // non-breaking space
+ * fractionGroupSize : 0
+ * };
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * 'toFormat() decimal places not an integer: {dp}'
+ * 'toFormat() decimal places out of range: {dp}'
+ * 'toFormat() rounding mode not an integer: {rm}'
+ * 'toFormat() rounding mode out of range: {rm}'
+ */
+ P.toFormat = function ( dp, rm ) {
+ var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
+ ? ~~dp + this.e + 1 : null, rm, 21 );
+
+ if ( this.c ) {
+ var i,
+ arr = str.split('.'),
+ g1 = +FORMAT.groupSize,
+ g2 = +FORMAT.secondaryGroupSize,
+ groupSeparator = FORMAT.groupSeparator,
+ intPart = arr[0],
+ fractionPart = arr[1],
+ isNeg = this.s < 0,
+ intDigits = isNeg ? intPart.slice(1) : intPart,
+ len = intDigits.length;
+
+ if (g2) i = g1, g1 = g2, g2 = i, len -= i;
+
+ if ( g1 > 0 && len > 0 ) {
+ i = len % g1 || g1;
+ intPart = intDigits.substr( 0, i );
+
+ for ( ; i < len; i += g1 ) {
+ intPart += groupSeparator + intDigits.substr( i, g1 );
+ }
+
+ if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
+ if (isNeg) intPart = '-' + intPart;
+ }
+
+ str = fractionPart
+ ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
+ ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
+ '$&' + FORMAT.fractionGroupSeparator )
+ : fractionPart )
+ : intPart;
+ }
+
+ return str;
+ };
+
+
+ /*
+ * Return a string array representing the value of this BigNumber as a simple fraction with
+ * an integer numerator and an integer denominator. The denominator will be a positive
+ * non-zero value less than or equal to the specified maximum denominator. If a maximum
+ * denominator is not specified, the denominator will be the lowest value necessary to
+ * represent the number exactly.
+ *
+ * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
+ *
+ * 'toFraction() max denominator not an integer: {md}'
+ * 'toFraction() max denominator out of range: {md}'
+ */
+ P.toFraction = function (md) {
+ var arr, d0, d2, e, exp, n, n0, q, s,
+ k = ERRORS,
+ x = this,
+ xc = x.c,
+ d = new BigNumber(ONE),
+ n1 = d0 = new BigNumber(ONE),
+ d1 = n0 = new BigNumber(ONE);
+
+ if ( md != null ) {
+ ERRORS = false;
+ n = new BigNumber(md);
+ ERRORS = k;
+
+ if ( !( k = n.isInt() ) || n.lt(ONE) ) {
+
+ if (ERRORS) {
+ raise( 22,
+ 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
+ }
+
+ // ERRORS is false:
+ // If md is a finite non-integer >= 1, round it to an integer and use it.
+ md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
+ }
+ }
+
+ if ( !xc ) return x.toString();
+ s = coeffToString(xc);
+
+ // Determine initial denominator.
+ // d is a power of 10 and the minimum max denominator that specifies the value exactly.
+ e = d.e = s.length - x.e - 1;
+ d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
+ md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
+
+ exp = MAX_EXP;
+ MAX_EXP = 1 / 0;
+ n = new BigNumber(s);
+
+ // n0 = d1 = 0
+ n0.c[0] = 0;
+
+ for ( ; ; ) {
+ q = div( n, d, 0, 1 );
+ d2 = d0.plus( q.times(d1) );
+ if ( d2.cmp(md) == 1 ) break;
+ d0 = d1;
+ d1 = d2;
+ n1 = n0.plus( q.times( d2 = n1 ) );
+ n0 = d2;
+ d = n.minus( q.times( d2 = d ) );
+ n = d2;
+ }
+
+ d2 = div( md.minus(d0), d1, 0, 1 );
+ n0 = n0.plus( d2.times(n1) );
+ d0 = d0.plus( d2.times(d1) );
+ n0.s = n1.s = x.s;
+ e *= 2;
+
+ // Determine which fraction is closer to x, n0/d0 or n1/d1
+ arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
+ div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
+ ? [ n1.toString(), d1.toString() ]
+ : [ n0.toString(), d0.toString() ];
+
+ MAX_EXP = exp;
+ return arr;
+ };
+
+
+ /*
+ * Return the value of this BigNumber converted to a number primitive.
+ */
+ P.toNumber = function () {
+ var x = this;
+
+ // Ensure zero has correct sign.
+ return +x || ( x.s ? x.s * 0 : NaN );
+ };
+
+
+ /*
+ * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
+ * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
+ * If POW_PRECISION is not 0, round to POW_PRECISION using ROUNDING_MODE.
+ *
+ * n {number} Integer, -9007199254740992 to 9007199254740992 inclusive.
+ * (Performs 54 loop iterations for n of 9007199254740992.)
+ *
+ * 'pow() exponent not an integer: {n}'
+ * 'pow() exponent out of range: {n}'
+ */
+ P.toPower = P.pow = function (n) {
+ var k, y,
+ i = mathfloor( n < 0 ? -n : +n ),
+ x = this;
+
+ // Pass ±Infinity to Math.pow if exponent is out of range.
+ if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
+ ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
+ parseFloat(n) != n && !( n = NaN ) ) ) {
+ return new BigNumber( Math.pow( +x, n ) );
+ }
+
+ // Truncating each coefficient array to a length of k after each multiplication equates
+ // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a
+ // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.)
+ k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0;
+ y = new BigNumber(ONE);
+
+ for ( ; ; ) {
+
+ if ( i % 2 ) {
+ y = y.times(x);
+ if ( !y.c ) break;
+ if ( k && y.c.length > k ) y.c.length = k;
+ }
+
+ i = mathfloor( i / 2 );
+ if ( !i ) break;
+
+ x = x.times(x);
+ if ( k && x.c && x.c.length > k ) x.c.length = k;
+ }
+
+ if ( n < 0 ) y = ONE.div(y);
+ return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber rounded to sd significant digits
+ * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
+ * necessary to represent the integer part of the value in fixed-point notation, then use
+ * exponential notation.
+ *
+ * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * 'toPrecision() precision not an integer: {sd}'
+ * 'toPrecision() precision out of range: {sd}'
+ * 'toPrecision() rounding mode not an integer: {rm}'
+ * 'toPrecision() rounding mode out of range: {rm}'
+ */
+ P.toPrecision = function ( sd, rm ) {
+ return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
+ ? sd | 0 : null, rm, 24 );
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in base b, or base 10 if b is
+ * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
+ * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
+ * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
+ * TO_EXP_NEG, return exponential notation.
+ *
+ * [b] {number} Integer, 2 to 64 inclusive.
+ *
+ * 'toString() base not an integer: {b}'
+ * 'toString() base out of range: {b}'
+ */
+ P.toString = function (b) {
+ var str,
+ n = this,
+ s = n.s,
+ e = n.e;
+
+ // Infinity or NaN?
+ if ( e === null ) {
+
+ if (s) {
+ str = 'Infinity';
+ if ( s < 0 ) str = '-' + str;
+ } else {
+ str = 'NaN';
+ }
+ } else {
+ str = coeffToString( n.c );
+
+ if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
+ str = e <= TO_EXP_NEG || e >= TO_EXP_POS
+ ? toExponential( str, e )
+ : toFixedPoint( str, e );
+ } else {
+ str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
+ }
+
+ if ( s < 0 && n.c[0] ) str = '-' + str;
+ }
+
+ return str;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
+ * number.
+ */
+ P.truncated = P.trunc = function () {
+ return round( new BigNumber(this), this.e + 1, 1 );
+ };
+
+
+
+ /*
+ * Return as toString, but do not accept a base argument.
+ */
+ P.valueOf = P.toJSON = function () {
+ return this.toString();
+ };
+
+
+ // Aliases for BigDecimal methods.
+ //P.add = P.plus; // P.add included above
+ //P.subtract = P.minus; // P.sub included above
+ //P.multiply = P.times; // P.mul included above
+ //P.divide = P.div;
+ //P.remainder = P.mod;
+ //P.compareTo = P.cmp;
+ //P.negate = P.neg;
+
+
+ if ( configObj != null ) BigNumber.config(configObj);
+
+ return BigNumber;
+ }
+
+
+ // PRIVATE HELPER FUNCTIONS
+
+
+ function bitFloor(n) {
+ var i = n | 0;
+ return n > 0 || n === i ? i : i - 1;
+ }
+
+
+ // Return a coefficient array as a string of base 10 digits.
+ function coeffToString(a) {
+ var s, z,
+ i = 1,
+ j = a.length,
+ r = a[0] + '';
+
+ for ( ; i < j; ) {
+ s = a[i++] + '';
+ z = LOG_BASE - s.length;
+ for ( ; z--; s = '0' + s );
+ r += s;
+ }
+
+ // Determine trailing zeros.
+ for ( j = r.length; r.charCodeAt(--j) === 48; );
+ return r.slice( 0, j + 1 || 1 );
+ }
+
+
+ // Compare the value of BigNumbers x and y.
+ function compare( x, y ) {
+ var a, b,
+ xc = x.c,
+ yc = y.c,
+ i = x.s,
+ j = y.s,
+ k = x.e,
+ l = y.e;
+
+ // Either NaN?
+ if ( !i || !j ) return null;
+
+ a = xc && !xc[0];
+ b = yc && !yc[0];
+
+ // Either zero?
+ if ( a || b ) return a ? b ? 0 : -j : i;
+
+ // Signs differ?
+ if ( i != j ) return i;
+
+ a = i < 0;
+ b = k == l;
+
+ // Either Infinity?
+ if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
+
+ // Compare exponents.
+ if ( !b ) return k > l ^ a ? 1 : -1;
+
+ j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
+
+ // Compare digit by digit.
+ for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
+
+ // Compare lengths.
+ return k == l ? 0 : k > l ^ a ? 1 : -1;
+ }
+
+
+ /*
+ * Return true if n is a valid number in range, otherwise false.
+ * Use for argument validation when ERRORS is false.
+ * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
+ */
+ function intValidatorNoErrors( n, min, max ) {
+ return ( n = truncate(n) ) >= min && n <= max;
+ }
+
+
+ function isArray(obj) {
+ return Object.prototype.toString.call(obj) == '[object Array]';
+ }
+
+
+ /*
+ * Convert string of baseIn to an array of numbers of baseOut.
+ * Eg. convertBase('255', 10, 16) returns [15, 15].
+ * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
+ */
+ function toBaseOut( str, baseIn, baseOut ) {
+ var j,
+ arr = [0],
+ arrL,
+ i = 0,
+ len = str.length;
+
+ for ( ; i < len; ) {
+ for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
+ arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
+
+ for ( ; j < arr.length; j++ ) {
+
+ if ( arr[j] > baseOut - 1 ) {
+ if ( arr[j + 1] == null ) arr[j + 1] = 0;
+ arr[j + 1] += arr[j] / baseOut | 0;
+ arr[j] %= baseOut;
+ }
+ }
+ }
+
+ return arr.reverse();
+ }
+
+
+ function toExponential( str, e ) {
+ return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
+ ( e < 0 ? 'e' : 'e+' ) + e;
+ }
+
+
+ function toFixedPoint( str, e ) {
+ var len, z;
+
+ // Negative exponent?
+ if ( e < 0 ) {
+
+ // Prepend zeros.
+ for ( z = '0.'; ++e; z += '0' );
+ str = z + str;
+
+ // Positive exponent
+ } else {
+ len = str.length;
+
+ // Append zeros.
+ if ( ++e > len ) {
+ for ( z = '0', e -= len; --e; z += '0' );
+ str += z;
+ } else if ( e < len ) {
+ str = str.slice( 0, e ) + '.' + str.slice(e);
+ }
+ }
+
+ return str;
+ }
+
+
+ function truncate(n) {
+ n = parseFloat(n);
+ return n < 0 ? mathceil(n) : mathfloor(n);
+ }
+
+
+ // EXPORT
+
+
+ BigNumber = another();
+
+ // AMD.
+ if ( typeof define == 'function' && define.amd ) {
+ define( function () { return BigNumber; } );
+
+ // Node and other environments that support module.exports.
+ } else if ( typeof module != 'undefined' && module.exports ) {
+ module.exports = BigNumber;
+ if ( !crypto ) try { crypto = require('crypto'); } catch (e) {}
+
+ // Browser.
+ } else {
+ global.BigNumber = BigNumber;
+ }
+})(this);
+
+},{"crypto":1}],"natspec":[function(require,module,exports){
+/*
+ This file is part of natspec.js.
+
+ natspec.js is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ natspec.js is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with natspec.js. If not, see .
+*/
+/** @file natspec.js
+ * @authors:
+ * Marek Kotewicz
+ * @date 2015
+ */
+
+var abi = require('./node_modules/web3/lib/solidity/abi.js');
+
+/**
+ * This object should be used to evaluate natspec expression
+ * It has one method evaluateExpression which shoul be used
+ */
+var natspec = (function () {
+ /**
+ * Helper method
+ * Should be called to copy values from object to global context
+ *
+ * @method copyToContext
+ * @param {Object} object from which we want to copy properties
+ * @param {Object} object to which we copy
+ */
+ var copyToContext = function (obj, context) {
+ Object.keys(obj).forEach(function (key) {
+ context[key] = obj[key];
+ });
+ }
+
+ /**
+ * Should be used to generate codes, which will be evaluated
+ *
+ * @method generateCode
+ * @param {Object} object from which code will be generated
+ * @return {String} javascript code which is used to initalized variables
+ */
+ var generateCode = function (obj) {
+ return Object.keys(obj).reduce(function (acc, key) {
+ return acc + "var " + key + " = context['" + key + "'];\n";
+ }, "");
+ };
+
+ /**
+ * Helper method
+ * Should be called to get method with given name from the abi
+ *
+ * @method getMethodWithName
+ * @param {Array} contract's abi
+ * @param {String} name of the method that we are looking for
+ * @return {Object} abi for method with name
+ */
+ var getMethodWithName = function(abi, name) {
+ return abi.filter(function (method) {
+ return method.name === name;
+ })[0];
+ };
+
+ /**
+ * Should be used to get all contract method input variables
+ *
+ * @method getMethodInputParams
+ * @param {Object} abi for certain method
+ * @param {Object} transaction object
+ * @return {Object} object with all contract's method input variables
+ */
+ var getMethodInputParams = function (method, transaction) {
+ // do it with output formatter (cause we have to decode)
+ var params = abi.formatOutput(method.inputs, '0x' + transaction.params[0].data.slice(10));
+
+ return method.inputs.reduce(function (acc, current, index) {
+ acc[current.name] = params[index];
+ return acc;
+ }, {});
+ };
+
+ /**
+ * Should be called when we want to evaluate natspec expression
+ * Replaces all natspec 'subexpressions' with evaluated value
+ *
+ * @method mapExpressionToEvaluate
+ * @param {String} expression to evaluate
+ * @param {Function} callback which is called to evaluate te expression
+ * @return {String} evaluated expression
+ */
+ var mapExpressionsToEvaluate = function (expression, cb) {
+ var evaluatedExpression = "";
+
+ // match everything in quotes
+ var pattern = /\` + "`" + `(?:\\.|[^` + "`" + `\\])*\` + "`" + `/gim
+ var match;
+ var lastIndex = 0;
+ try {
+ while ((match = pattern.exec(expression)) !== null) {
+ var startIndex = pattern.lastIndex - match[0].length;
+ var toEval = match[0].slice(1, match[0].length - 1);
+ evaluatedExpression += expression.slice(lastIndex, startIndex);
+ var evaluatedPart = cb(toEval);
+ evaluatedExpression += evaluatedPart;
+ lastIndex = pattern.lastIndex;
+ }
+
+ evaluatedExpression += expression.slice(lastIndex);
+ }
+ catch (err) {
+ throw new Error("Natspec evaluation failed, wrong input params");
+ }
+
+ return evaluatedExpression;
+ };
+
+ /**
+ * Should be called to evaluate single expression
+ * Is internally using javascript's 'eval' method
+ *
+ * @method evaluateExpression
+ * @param {String} expression which should be evaluated
+ * @param {Object} [call] object containing contract abi, transaction, called method
+ * @return {String} evaluated expression
+ * @throws exception if method is not found or we are trying to evaluate input params that does not exists
+ */
+
+ var utils = require('../utils/utils');
+
+ var evaluateExpression = function (expression, call) {
+ //var self = this;
+ var context = {};
+
+ if (!!call) {
+ try {
+ var method = getMethodWithName(call.abi, call.method);
+ var params = getMethodInputParams(method, call.transaction);
+ copyToContext(params, context);
+ }
+ catch (err) {
+ throw new Error("Natspec evaluation failed, method does not exist");
+ }
+ }
+
+ var code = generateCode(context);
+
+ var evaluatedExpression = mapExpressionsToEvaluate(expression, function (toEval) {
+ //var fn = new Function("context", "toHex", code + "return " + toEval + ";");
+ //return fn(context, toHex).toString();
+ var fn = new Function("context", "utils", code + "return " + toEval + ";");
+ return fn(context, utils).toString();
+ });
+
+ return evaluatedExpression;
+ };
+
+ /**
+ * Safe version of evaluateExpression
+ * Instead of throwing an exception it returns it as a string
+ *
+ * @method evaluateExpressionSafe
+ * @param {String} expression which should be evaluated
+ * @param {Object} [call] object containing contract abi, transaction, called method
+ * @return {String} evaluated expression
+ */
+ var evaluateExpressionSafe = function (expression, call) {
+ try {
+ return evaluateExpression(expression, call);
+ }
+ catch (err) {
+ return err.message;
+ }
+ };
+
+ return {
+ evaluateExpression: evaluateExpression,
+ evaluateExpressionSafe: evaluateExpressionSafe
+ };
+
+})();
+
+module.exports = natspec;
+
+
+},{"./node_modules/web3/lib/solidity/abi.js":2,"../utils/utils":7}]},{},[]);
+`
+
+//# sourceMappingURL=natspec.js.map`
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/number/int.go b/src/vendor/github.com/ethereum/go-ethereum/common/number/int.go
new file mode 100644
index 000000000..6dab2436d
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/common/number/int.go
@@ -0,0 +1,197 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package number
+
+import (
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/common"
+)
+
+var tt256 = new(big.Int).Lsh(big.NewInt(1), 256)
+var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1))
+var tt255 = new(big.Int).Lsh(big.NewInt(1), 255)
+
+func limitUnsigned256(x *Number) *Number {
+ x.num.And(x.num, tt256m1)
+ return x
+}
+
+func limitSigned256(x *Number) *Number {
+ if x.num.Cmp(tt255) < 0 {
+ return x
+ } else {
+ x.num.Sub(x.num, tt256)
+ return x
+ }
+}
+
+// Number function
+type Initialiser func(n int64) *Number
+
+// A Number represents a generic integer with a bounding function limiter. Limit is called after each operations
+// to give "fake" bounded integers. New types of Number can be created through NewInitialiser returning a lambda
+// with the new Initialiser.
+type Number struct {
+ num *big.Int
+ limit func(n *Number) *Number
+}
+
+// Returns a new initialiser for a new *Number without having to expose certain fields
+func NewInitialiser(limiter func(*Number) *Number) Initialiser {
+ return func(n int64) *Number {
+ return &Number{big.NewInt(n), limiter}
+ }
+}
+
+// Return a Number with a UNSIGNED limiter up to 256 bits
+func Uint256(n int64) *Number {
+ return &Number{big.NewInt(n), limitUnsigned256}
+}
+
+// Return a Number with a SIGNED limiter up to 256 bits
+func Int256(n int64) *Number {
+ return &Number{big.NewInt(n), limitSigned256}
+}
+
+// Returns a Number with a SIGNED unlimited size
+func Big(n int64) *Number {
+ return &Number{big.NewInt(n), func(x *Number) *Number { return x }}
+}
+
+// Sets i to sum of x+y
+func (i *Number) Add(x, y *Number) *Number {
+ i.num.Add(x.num, y.num)
+ return i.limit(i)
+}
+
+// Sets i to difference of x-y
+func (i *Number) Sub(x, y *Number) *Number {
+ i.num.Sub(x.num, y.num)
+ return i.limit(i)
+}
+
+// Sets i to product of x*y
+func (i *Number) Mul(x, y *Number) *Number {
+ i.num.Mul(x.num, y.num)
+ return i.limit(i)
+}
+
+// Sets i to the quotient prodject of x/y
+func (i *Number) Div(x, y *Number) *Number {
+ i.num.Div(x.num, y.num)
+ return i.limit(i)
+}
+
+// Sets i to x % y
+func (i *Number) Mod(x, y *Number) *Number {
+ i.num.Mod(x.num, y.num)
+ return i.limit(i)
+}
+
+// Sets i to x << s
+func (i *Number) Lsh(x *Number, s uint) *Number {
+ i.num.Lsh(x.num, s)
+ return i.limit(i)
+}
+
+// Sets i to x^y
+func (i *Number) Pow(x, y *Number) *Number {
+ i.num.Exp(x.num, y.num, big.NewInt(0))
+ return i.limit(i)
+}
+
+// Setters
+
+// Set x to i
+func (i *Number) Set(x *Number) *Number {
+ i.num.Set(x.num)
+ return i.limit(i)
+}
+
+// Set x bytes to i
+func (i *Number) SetBytes(x []byte) *Number {
+ i.num.SetBytes(x)
+ return i.limit(i)
+}
+
+// Cmp compares x and y and returns:
+//
+// -1 if x < y
+// 0 if x == y
+// +1 if x > y
+func (i *Number) Cmp(x *Number) int {
+ return i.num.Cmp(x.num)
+}
+
+// Getters
+
+// Returns the string representation of i
+func (i *Number) String() string {
+ return i.num.String()
+}
+
+// Returns the byte representation of i
+func (i *Number) Bytes() []byte {
+ return i.num.Bytes()
+}
+
+// Uint64 returns the Uint64 representation of x. If x cannot be represented in an int64, the result is undefined.
+func (i *Number) Uint64() uint64 {
+ return i.num.Uint64()
+}
+
+// Int64 returns the int64 representation of x. If x cannot be represented in an int64, the result is undefined.
+func (i *Number) Int64() int64 {
+ return i.num.Int64()
+}
+
+// Returns the signed version of i
+func (i *Number) Int256() *Number {
+ return Int(0).Set(i)
+}
+
+// Returns the unsigned version of i
+func (i *Number) Uint256() *Number {
+ return Uint(0).Set(i)
+}
+
+// Returns the index of the first bit that's set to 1
+func (i *Number) FirstBitSet() int {
+ for j := 0; j < i.num.BitLen(); j++ {
+ if i.num.Bit(j) > 0 {
+ return j
+ }
+ }
+
+ return i.num.BitLen()
+}
+
+// Variables
+
+var (
+ Zero = Uint(0)
+ One = Uint(1)
+ Two = Uint(2)
+ MaxUint256 = Uint(0).SetBytes(common.Hex2Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"))
+
+ MinOne = Int(-1)
+
+ // "typedefs"
+ Uint = Uint256
+ Int = Int256
+)
diff --git a/src/vendor/github.com/ethereum/go-ethereum/common/registrar/ethreg/api.go b/src/vendor/github.com/ethereum/go-ethereum/common/registrar/ethreg/api.go
index 6d77a9385..6dd0ef46f 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/common/registrar/ethreg/api.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/common/registrar/ethreg/api.go
@@ -128,7 +128,10 @@ func (m callmsg) FromFrontier() (common.Address, error) {
return m.from.Address(), nil
}
func (m callmsg) Nonce() uint64 {
- return m.from.Nonce()
+ return 0
+}
+func (m callmsg) CheckNonce() bool {
+ return false
}
func (m callmsg) To() *common.Address {
return m.to
diff --git a/src/vendor/github.com/ethereum/go-ethereum/compression/rle/read_write.go b/src/vendor/github.com/ethereum/go-ethereum/compression/rle/read_write.go
new file mode 100644
index 000000000..03dffd607
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/compression/rle/read_write.go
@@ -0,0 +1,101 @@
+// Copyright 2014 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+// Package rle implements the run-length encoding used for Ethereum data.
+package rle
+
+import (
+ "bytes"
+ "errors"
+
+ "github.com/ethereum/go-ethereum/crypto"
+)
+
+const (
+ token byte = 0xfe
+ emptyShaToken = 0xfd
+ emptyListShaToken = 0xfe
+ tokenToken = 0xff
+)
+
+var empty = crypto.Keccak256([]byte(""))
+var emptyList = crypto.Keccak256([]byte{0x80})
+
+func Decompress(dat []byte) ([]byte, error) {
+ buf := new(bytes.Buffer)
+
+ for i := 0; i < len(dat); i++ {
+ if dat[i] == token {
+ if i+1 < len(dat) {
+ switch dat[i+1] {
+ case emptyShaToken:
+ buf.Write(empty)
+ case emptyListShaToken:
+ buf.Write(emptyList)
+ case tokenToken:
+ buf.WriteByte(token)
+ default:
+ buf.Write(make([]byte, int(dat[i+1]-2)))
+ }
+ i++
+ } else {
+ return nil, errors.New("error reading bytes. token encountered without proceeding bytes")
+ }
+ } else {
+ buf.WriteByte(dat[i])
+ }
+ }
+
+ return buf.Bytes(), nil
+}
+
+func compressChunk(dat []byte) (ret []byte, n int) {
+ switch {
+ case dat[0] == token:
+ return []byte{token, tokenToken}, 1
+ case len(dat) > 1 && dat[0] == 0x0 && dat[1] == 0x0:
+ j := 0
+ for j <= 254 && j < len(dat) {
+ if dat[j] != 0 {
+ break
+ }
+ j++
+ }
+ return []byte{token, byte(j + 2)}, j
+ case len(dat) >= 32:
+ if dat[0] == empty[0] && bytes.Compare(dat[:32], empty) == 0 {
+ return []byte{token, emptyShaToken}, 32
+ } else if dat[0] == emptyList[0] && bytes.Compare(dat[:32], emptyList) == 0 {
+ return []byte{token, emptyListShaToken}, 32
+ }
+ fallthrough
+ default:
+ return dat[:1], 1
+ }
+}
+
+func Compress(dat []byte) []byte {
+ buf := new(bytes.Buffer)
+
+ i := 0
+ for i < len(dat) {
+ b, n := compressChunk(dat[i:])
+ buf.Write(b)
+ i += n
+ }
+
+ return buf.Bytes()
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/console/bridge.go b/src/vendor/github.com/ethereum/go-ethereum/console/bridge.go
new file mode 100644
index 000000000..65f2541b0
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/console/bridge.go
@@ -0,0 +1,341 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package console
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "time"
+
+ "github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
+ "github.com/ethereum/go-ethereum/rpc"
+ "github.com/robertkrimen/otto"
+ "golang.org/x/net/context"
+)
+
+// bridge is a collection of JavaScript utility methods to bride the .js runtime
+// environment and the Go RPC connection backing the remote method calls.
+type bridge struct {
+ client *rpc.ClientRestartWrapper // RPC client to execute Ethereum requests through
+ prompter UserPrompter // Input prompter to allow interactive user feedback
+ printer io.Writer // Output writer to serialize any display strings to
+ ctx context.Context
+}
+
+// newBridge creates a new JavaScript wrapper around an RPC client.
+func newBridge(client *rpc.ClientRestartWrapper, prompter UserPrompter, printer io.Writer) *bridge {
+ return &bridge{
+ client: client,
+ prompter: prompter,
+ printer: printer,
+ }
+}
+
+func (b *bridge) setContext(ctx context.Context) {
+ b.ctx = ctx
+}
+
+// NewAccount is a wrapper around the personal.newAccount RPC method that uses a
+// non-echoing password prompt to aquire the passphrase and executes the original
+// RPC method (saved in jeth.newAccount) with it to actually execute the RPC call.
+func (b *bridge) NewAccount(call otto.FunctionCall) (response otto.Value) {
+ var (
+ password string
+ confirm string
+ err error
+ )
+ switch {
+ // No password was specified, prompt the user for it
+ case len(call.ArgumentList) == 0:
+ if password, err = b.prompter.PromptPassword("Passphrase: "); err != nil {
+ throwJSException(err.Error())
+ }
+ if confirm, err = b.prompter.PromptPassword("Repeat passphrase: "); err != nil {
+ throwJSException(err.Error())
+ }
+ if password != confirm {
+ throwJSException("passphrases don't match!")
+ }
+
+ // A single string password was specified, use that
+ case len(call.ArgumentList) == 1 && call.Argument(0).IsString():
+ password, _ = call.Argument(0).ToString()
+
+ // Otherwise fail with some error
+ default:
+ throwJSException("expected 0 or 1 string argument")
+ }
+ // Password aquired, execute the call and return
+ ret, err := call.Otto.Call("jeth.newAccount", nil, password)
+ if err != nil {
+ throwJSException(err.Error())
+ }
+ return ret
+}
+
+// UnlockAccount is a wrapper around the personal.unlockAccount RPC method that
+// uses a non-echoing password prompt to aquire the passphrase and executes the
+// original RPC method (saved in jeth.unlockAccount) with it to actually execute
+// the RPC call.
+func (b *bridge) UnlockAccount(call otto.FunctionCall) (response otto.Value) {
+ // Make sure we have an account specified to unlock
+ if !call.Argument(0).IsString() {
+ throwJSException("first argument must be the account to unlock")
+ }
+ account := call.Argument(0)
+
+ // If password is not given or is the null value, prompt the user for it
+ var passwd otto.Value
+
+ if call.Argument(1).IsUndefined() || call.Argument(1).IsNull() {
+ fmt.Fprintf(b.printer, "Unlock account %s\n", account)
+ if input, err := b.prompter.PromptPassword("Passphrase: "); err != nil {
+ throwJSException(err.Error())
+ } else {
+ passwd, _ = otto.ToValue(input)
+ }
+ } else {
+ if !call.Argument(1).IsString() {
+ throwJSException("password must be a string")
+ }
+ passwd = call.Argument(1)
+ }
+ // Third argument is the duration how long the account must be unlocked.
+ duration := otto.NullValue()
+ if call.Argument(2).IsDefined() && !call.Argument(2).IsNull() {
+ if !call.Argument(2).IsNumber() {
+ throwJSException("unlock duration must be a number")
+ }
+ duration = call.Argument(2)
+ }
+ // Send the request to the backend and return
+ val, err := call.Otto.Call("jeth.unlockAccount", nil, account, passwd, duration)
+ if err != nil {
+ throwJSException(err.Error())
+ }
+ return val
+}
+
+// Sleep will block the console for the specified number of seconds.
+func (b *bridge) Sleep(call otto.FunctionCall) (response otto.Value) {
+ if call.Argument(0).IsNumber() {
+ sleep, _ := call.Argument(0).ToInteger()
+ time.Sleep(time.Duration(sleep) * time.Second)
+ return otto.TrueValue()
+ }
+ return throwJSException("usage: sleep()")
+}
+
+// SleepBlocks will block the console for a specified number of new blocks optionally
+// until the given timeout is reached.
+func (b *bridge) SleepBlocks(call otto.FunctionCall) (response otto.Value) {
+ var (
+ blocks = int64(0)
+ sleep = int64(9999999999999999) // indefinitely
+ )
+ // Parse the input parameters for the sleep
+ nArgs := len(call.ArgumentList)
+ if nArgs == 0 {
+ throwJSException("usage: sleepBlocks([, max sleep in seconds])")
+ }
+ if nArgs >= 1 {
+ if call.Argument(0).IsNumber() {
+ blocks, _ = call.Argument(0).ToInteger()
+ } else {
+ throwJSException("expected number as first argument")
+ }
+ }
+ if nArgs >= 2 {
+ if call.Argument(1).IsNumber() {
+ sleep, _ = call.Argument(1).ToInteger()
+ } else {
+ throwJSException("expected number as second argument")
+ }
+ }
+ // go through the console, this will allow web3 to call the appropriate
+ // callbacks if a delayed response or notification is received.
+ blockNumber := func() int64 {
+ result, err := call.Otto.Run("eth.blockNumber")
+ if err != nil {
+ throwJSException(err.Error())
+ }
+ block, err := result.ToInteger()
+ if err != nil {
+ throwJSException(err.Error())
+ }
+ return block
+ }
+ // Poll the current block number until either it ot a timeout is reached
+ targetBlockNr := blockNumber() + blocks
+ deadline := time.Now().Add(time.Duration(sleep) * time.Second)
+
+ for time.Now().Before(deadline) {
+ if blockNumber() >= targetBlockNr {
+ return otto.TrueValue()
+ }
+ time.Sleep(time.Second)
+ }
+ return otto.FalseValue()
+}
+
+// Send will serialize the first argument, send it to the node and returns the response.
+func (b *bridge) Send(call otto.FunctionCall) (response otto.Value) {
+ // Ensure that we've got a batch request (array) or a single request (object)
+ arg := call.Argument(0).Object()
+ if arg == nil || (arg.Class() != "Array" && arg.Class() != "Object") {
+ throwJSException("request must be an object or array")
+ }
+ // Convert the otto VM arguments to Go values
+ data, err := call.Otto.Call("JSON.stringify", nil, arg)
+ if err != nil {
+ throwJSException(err.Error())
+ }
+ reqjson, err := data.ToString()
+ if err != nil {
+ throwJSException(err.Error())
+ }
+
+ var (
+ reqs []rpc.JSONRequest
+ batch = true
+ )
+ if err = json.Unmarshal([]byte(reqjson), &reqs); err != nil {
+ // single request?
+ reqs = make([]rpc.JSONRequest, 1)
+ if err = json.Unmarshal([]byte(reqjson), &reqs[0]); err != nil {
+ throwJSException("invalid request")
+ }
+ batch = false
+ }
+ // Iteratively execute the requests
+ call.Otto.Set("response_len", len(reqs))
+ call.Otto.Run("var ret_response = new Array(response_len);")
+
+ for i, req := range reqs {
+ // Execute the RPC request and parse the reply
+ client := b.client.Client()
+ if err = client.Send(&req); err != nil {
+ return newErrorResponse(call, -32603, err.Error(), req.Id)
+ }
+ errc := make(chan error, 1)
+ errc2 := make(chan error)
+ go func(){
+ if b.ctx != nil {
+ select {
+ case <-b.ctx.Done():
+ b.client.Restart()
+ errc2 <- b.ctx.Err()
+ case err := <-errc:
+ errc2 <- err
+ }
+ } else {
+ errc2 <- <-errc
+ }
+ }()
+ result := make(map[string]interface{})
+ errc <- client.Recv(&result)
+ err := <-errc2
+ if err != nil {
+ return newErrorResponse(call, -32603, err.Error(), req.Id)
+ }
+ // Feed the reply back into the JavaScript runtime environment
+ id, _ := result["id"]
+ jsonver, _ := result["jsonrpc"]
+
+ call.Otto.Set("ret_id", id)
+ call.Otto.Set("ret_jsonrpc", jsonver)
+ call.Otto.Set("response_idx", i)
+
+ if res, ok := result["result"]; ok {
+ payload, _ := json.Marshal(res)
+ call.Otto.Set("ret_result", string(payload))
+ response, err = call.Otto.Run(`
+ ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, result: JSON.parse(ret_result) };
+ `)
+ continue
+ }
+ if res, ok := result["error"]; ok {
+ payload, _ := json.Marshal(res)
+ call.Otto.Set("ret_result", string(payload))
+ response, err = call.Otto.Run(`
+ ret_response[response_idx] = { jsonrpc: ret_jsonrpc, id: ret_id, error: JSON.parse(ret_result) };
+ `)
+ continue
+ }
+ return newErrorResponse(call, -32603, fmt.Sprintf("Invalid response"), new(int64))
+ }
+ // Convert single requests back from batch ones
+ if !batch {
+ call.Otto.Run("ret_response = ret_response[0];")
+ }
+ // Execute any registered callbacks
+ if call.Argument(1).IsObject() {
+ call.Otto.Set("callback", call.Argument(1))
+ call.Otto.Run(`
+ if (Object.prototype.toString.call(callback) == '[object Function]') {
+ callback(null, ret_response);
+ }
+ `)
+ }
+ return
+}
+
+// throwJSException panics on an otto.Value. The Otto VM will recover from the
+// Go panic and throw msg as a JavaScript error.
+func throwJSException(msg interface{}) otto.Value {
+ val, err := otto.ToValue(msg)
+ if err != nil {
+ glog.V(logger.Error).Infof("Failed to serialize JavaScript exception %v: %v", msg, err)
+ }
+ panic(val)
+}
+
+// newErrorResponse creates a JSON RPC error response for a specific request id,
+// containing the specified error code and error message. Beside returning the
+// error to the caller, it also sets the ret_error and ret_response JavaScript
+// variables.
+func newErrorResponse(call otto.FunctionCall, code int, msg string, id interface{}) (response otto.Value) {
+ // Bundle the error into a JSON RPC call response
+ res := rpc.JSONErrResponse{
+ Version: rpc.JSONRPCVersion,
+ Id: id,
+ Error: rpc.JSONError{
+ Code: code,
+ Message: msg,
+ },
+ }
+ // Serialize the error response into JavaScript variables
+ errObj, err := json.Marshal(res.Error)
+ if err != nil {
+ glog.V(logger.Error).Infof("Failed to serialize JSON RPC error: %v", err)
+ }
+ resObj, err := json.Marshal(res)
+ if err != nil {
+ glog.V(logger.Error).Infof("Failed to serialize JSON RPC error response: %v", err)
+ }
+
+ if _, err = call.Otto.Run("ret_error = " + string(errObj)); err != nil {
+ glog.V(logger.Error).Infof("Failed to set `ret_error` to the occurred error: %v", err)
+ }
+ resVal, err := call.Otto.Run("ret_response = " + string(resObj))
+ if err != nil {
+ glog.V(logger.Error).Infof("Failed to set `ret_response` to the JSON RPC response: %v", err)
+ }
+ return resVal
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/console/console.go b/src/vendor/github.com/ethereum/go-ethereum/console/console.go
new file mode 100644
index 000000000..449deeaf3
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/console/console.go
@@ -0,0 +1,424 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package console
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "regexp"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/ethereum/go-ethereum/internal/jsre"
+ "github.com/ethereum/go-ethereum/internal/web3ext"
+ "github.com/ethereum/go-ethereum/rpc"
+ "github.com/mattn/go-colorable"
+ "github.com/peterh/liner"
+ "github.com/robertkrimen/otto"
+ "golang.org/x/net/context"
+)
+
+var (
+ passwordRegexp = regexp.MustCompile("personal.[nus]")
+ onlyWhitespace = regexp.MustCompile("^\\s*$")
+ exit = regexp.MustCompile("^\\s*exit\\s*;*\\s*$")
+)
+
+// HistoryFile is the file within the data directory to store input scrollback.
+const HistoryFile = "history"
+
+// DefaultPrompt is the default prompt line prefix to use for user input querying.
+const DefaultPrompt = "> "
+
+// Config is te collection of configurations to fine tune the behavior of the
+// JavaScript console.
+type Config struct {
+ DataDir string // Data directory to store the console history at
+ DocRoot string // Filesystem path from where to load JavaScript files from
+ Client *rpc.ClientRestartWrapper // RPC client to execute Ethereum requests through
+ Prompt string // Input prompt prefix string (defaults to DefaultPrompt)
+ Prompter UserPrompter // Input prompter to allow interactive user feedback (defaults to TerminalPrompter)
+ Printer io.Writer // Output writer to serialize any display strings to (defaults to os.Stdout)
+ Preload []string // Absolute paths to JavaScript files to preload
+}
+
+// Console is a JavaScript interpreted runtime environment. It is a fully fleged
+// JavaScript console attached to a running node via an external or in-process RPC
+// client.
+type Console struct {
+ client *rpc.ClientRestartWrapper // RPC client to execute Ethereum requests through
+ jsre *jsre.JSRE // JavaScript runtime environment running the interpreter
+ prompt string // Input prompt prefix string
+ prompter UserPrompter // Input prompter to allow interactive user feedback
+ histPath string // Absolute path to the console scrollback history
+ history []string // Scroll history maintained by the console
+ printer io.Writer // Output writer to serialize any display strings to
+ setContext func(context.Context)
+}
+
+func New(config Config) (*Console, error) {
+ // Handle unset config values gracefully
+ if config.Prompter == nil {
+ config.Prompter = Stdin
+ }
+ if config.Prompt == "" {
+ config.Prompt = DefaultPrompt
+ }
+ if config.Printer == nil {
+ config.Printer = colorable.NewColorableStdout()
+ }
+ // Initialize the console and return
+ console := &Console{
+ client: config.Client,
+ jsre: jsre.New(config.DocRoot, config.Printer),
+ prompt: config.Prompt,
+ prompter: config.Prompter,
+ printer: config.Printer,
+ histPath: filepath.Join(config.DataDir, HistoryFile),
+ }
+ if err := console.init(config.Preload); err != nil {
+ return nil, err
+ }
+ return console, nil
+}
+
+// init retrieves the available APIs from the remote RPC provider and initializes
+// the console's JavaScript namespaces based on the exposed modules.
+func (c *Console) init(preload []string) error {
+ // Initialize the JavaScript <-> Go RPC bridge
+ bridge := newBridge(c.client, c.prompter, c.printer)
+ c.setContext = bridge.setContext
+ c.jsre.Set("jeth", struct{}{})
+
+ jethObj, _ := c.jsre.Get("jeth")
+ jethObj.Object().Set("send", bridge.Send)
+ jethObj.Object().Set("sendAsync", bridge.Send)
+
+ consoleObj, _ := c.jsre.Get("console")
+ consoleObj.Object().Set("log", c.consoleOutput)
+ consoleObj.Object().Set("error", c.consoleOutput)
+
+ // Load all the internal utility JavaScript libraries
+ if err := c.jsre.Compile("bignumber.js", jsre.BigNumber_JS); err != nil {
+ return fmt.Errorf("bignumber.js: %v", err)
+ }
+ if err := c.jsre.Compile("web3.js", jsre.Web3_JS); err != nil {
+ return fmt.Errorf("web3.js: %v", err)
+ }
+ if _, err := c.jsre.Run("var Web3 = require('web3');"); err != nil {
+ return fmt.Errorf("web3 require: %v", err)
+ }
+ if _, err := c.jsre.Run("var web3 = new Web3(jeth);"); err != nil {
+ return fmt.Errorf("web3 provider: %v", err)
+ }
+ // Load the supported APIs into the JavaScript runtime environment
+ apis, err := c.client.Client().SupportedModules()
+ if err != nil {
+ return fmt.Errorf("api modules: %v", err)
+ }
+ flatten := "var eth = web3.eth; var personal = web3.personal; "
+ for api := range apis {
+ if api == "web3" {
+ continue // manually mapped or ignore
+ }
+ if file, ok := web3ext.Modules[api]; ok {
+ if err = c.jsre.Compile(fmt.Sprintf("%s.js", api), file); err != nil {
+ return fmt.Errorf("%s.js: %v", api, err)
+ }
+ flatten += fmt.Sprintf("var %s = web3.%s; ", api, api)
+ }
+ }
+ if _, err = c.jsre.Run(flatten); err != nil {
+ return fmt.Errorf("namespace flattening: %v", err)
+ }
+ // Initialize the global name register (disabled for now)
+ //c.jsre.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `); registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`)
+
+ // If the console is in interactive mode, instrument password related methods to query the user
+ if c.prompter != nil {
+ // Retrieve the account management object to instrument
+ personal, err := c.jsre.Get("personal")
+ if err != nil {
+ return err
+ }
+ // Override the unlockAccount and newAccount methods since these require user interaction.
+ // Assign the jeth.unlockAccount and jeth.newAccount in the Console the original web3 callbacks.
+ // These will be called by the jeth.* methods after they got the password from the user and send
+ // the original web3 request to the backend.
+ if obj := personal.Object(); obj != nil { // make sure the personal api is enabled over the interface
+ if _, err = c.jsre.Run(`jeth.unlockAccount = personal.unlockAccount;`); err != nil {
+ return fmt.Errorf("personal.unlockAccount: %v", err)
+ }
+ if _, err = c.jsre.Run(`jeth.newAccount = personal.newAccount;`); err != nil {
+ return fmt.Errorf("personal.newAccount: %v", err)
+ }
+ obj.Set("unlockAccount", bridge.UnlockAccount)
+ obj.Set("newAccount", bridge.NewAccount)
+ }
+ }
+ // The admin.sleep and admin.sleepBlocks are offered by the console and not by the RPC layer.
+ admin, err := c.jsre.Get("admin")
+ if err != nil {
+ return err
+ }
+ if obj := admin.Object(); obj != nil { // make sure the admin api is enabled over the interface
+ obj.Set("sleepBlocks", bridge.SleepBlocks)
+ obj.Set("sleep", bridge.Sleep)
+ }
+ // Preload any JavaScript files before starting the console
+ for _, path := range preload {
+ if err := c.jsre.Exec(path); err != nil {
+ failure := err.Error()
+ if ottoErr, ok := err.(*otto.Error); ok {
+ failure = ottoErr.String()
+ }
+ return fmt.Errorf("%s: %v", path, failure)
+ }
+ }
+ // Configure the console's input prompter for scrollback and tab completion
+ if c.prompter != nil {
+ if content, err := ioutil.ReadFile(c.histPath); err != nil {
+ c.prompter.SetHistory(nil)
+ } else {
+ c.history = strings.Split(string(content), "\n")
+ c.prompter.SetHistory(c.history)
+ }
+ c.prompter.SetWordCompleter(c.AutoCompleteInput)
+ }
+ return nil
+}
+
+// consoleOutput is an override for the console.log and console.error methods to
+// stream the output into the configured output stream instead of stdout.
+func (c *Console) consoleOutput(call otto.FunctionCall) otto.Value {
+ output := []string{}
+ for _, argument := range call.ArgumentList {
+ output = append(output, fmt.Sprintf("%v", argument))
+ }
+ fmt.Fprintln(c.printer, strings.Join(output, " "))
+ return otto.Value{}
+}
+
+// AutoCompleteInput is a pre-assembled word completer to be used by the user
+// input prompter to provide hints to the user about the methods available.
+func (c *Console) AutoCompleteInput(line string, pos int) (string, []string, string) {
+ // No completions can be provided for empty inputs
+ if len(line) == 0 || pos == 0 {
+ return "", nil, ""
+ }
+ // Chunck data to relevant part for autocompletion
+ // E.g. in case of nested lines eth.getBalance(eth.coinb
+ start := 0
+ for start = pos - 1; start > 0; start-- {
+ // Skip all methods and namespaces (i.e. including te dot)
+ if line[start] == '.' || (line[start] >= 'a' && line[start] <= 'z') || (line[start] >= 'A' && line[start] <= 'Z') {
+ continue
+ }
+ // Handle web3 in a special way (i.e. other numbers aren't auto completed)
+ if start >= 3 && line[start-3:start] == "web3" {
+ start -= 3
+ continue
+ }
+ // We've hit an unexpected character, autocomplete form here
+ start++
+ break
+ }
+ return line[:start], c.jsre.CompleteKeywords(line[start:pos]), line[pos:]
+}
+
+// Welcome show summary of current Geth instance and some metadata about the
+// console's available modules.
+func (c *Console) Welcome() {
+ // Print some generic Geth metadata
+ fmt.Fprintf(c.printer, "Welcome to the Geth JavaScript console!\n\n")
+ c.jsre.Run(`
+ console.log("instance: " + web3.version.node);
+ console.log("coinbase: " + eth.coinbase);
+ console.log("at block: " + eth.blockNumber + " (" + new Date(1000 * eth.getBlock(eth.blockNumber).timestamp) + ")");
+ console.log(" datadir: " + admin.datadir);
+ `)
+ // List all the supported modules for the user to call
+ if apis, err := c.client.Client().SupportedModules(); err == nil {
+ modules := make([]string, 0, len(apis))
+ for api, version := range apis {
+ modules = append(modules, fmt.Sprintf("%s:%s", api, version))
+ }
+ sort.Strings(modules)
+ fmt.Fprintln(c.printer, " modules:", strings.Join(modules, " "))
+ }
+ fmt.Fprintln(c.printer)
+}
+
+// Evaluate executes code and pretty prints the result to the specified output
+// stream.
+func (c *Console) Evaluate(statement string) error {
+ defer func() {
+ if r := recover(); r != nil {
+ fmt.Fprintf(c.printer, "[native] error: %v\n", r)
+ }
+ }()
+ if err := c.jsre.Evaluate(statement, c.printer); err != nil {
+ return err
+ }
+ return nil
+}
+
+// Interactive starts an interactive user session, where input is propted from
+// the configured user prompter.
+func (c *Console) Interactive() {
+ var (
+ prompt = c.prompt // Current prompt line (used for multi-line inputs)
+ indents = 0 // Current number of input indents (used for multi-line inputs)
+ input = "" // Current user input
+ scheduler = make(chan string) // Channel to send the next prompt on and receive the input
+ )
+ // Start a goroutine to listen for promt requests and send back inputs
+ go func() {
+ for {
+ // Read the next user input
+ line, err := c.prompter.PromptInput(<-scheduler)
+ if err != nil {
+ // In case of an error, either clear the prompt or fail
+ if err == liner.ErrPromptAborted { // ctrl-C
+ prompt, indents, input = c.prompt, 0, ""
+ scheduler <- ""
+ continue
+ }
+ close(scheduler)
+ return
+ }
+ // User input retrieved, send for interpretation and loop
+ scheduler <- line
+ }
+ }()
+ // Monitor Ctrl-C too in case the input is empty and we need to bail
+ abort := make(chan os.Signal, 1)
+ signal.Notify(abort, os.Interrupt)
+
+ // Start sending prompts to the user and reading back inputs
+ for {
+ // Send the next prompt, triggering an input read and process the result
+ scheduler <- prompt
+ select {
+ case <-abort:
+ // User forcefully quite the console
+ fmt.Fprintln(c.printer, "caught interrupt, exiting")
+ return
+
+ case line, ok := <-scheduler:
+ // User input was returned by the prompter, handle special cases
+ if !ok || (indents <= 0 && exit.MatchString(line)) {
+ return
+ }
+ if onlyWhitespace.MatchString(line) {
+ continue
+ }
+ // Append the line to the input and check for multi-line interpretation
+ input += line + "\n"
+
+ indents = countIndents(input)
+ if indents <= 0 {
+ prompt = c.prompt
+ } else {
+ prompt = strings.Repeat(".", indents*3) + " "
+ }
+ // If all the needed lines are present, save the command and run
+ if indents <= 0 {
+ if len(input) > 0 && input[0] != ' ' && !passwordRegexp.MatchString(input) {
+ if command := strings.TrimSpace(input); len(c.history) == 0 || command != c.history[len(c.history)-1] {
+ c.history = append(c.history, command)
+ if c.prompter != nil {
+ c.prompter.AppendHistory(command)
+ }
+ }
+ }
+ done := make(chan struct{})
+ ctx, _ := context.WithTimeout(context.Background(), time.Second*5)
+ c.setContext(ctx)
+ c.Evaluate(input)
+ c.setContext(nil)
+ close(done)
+ input = ""
+ }
+ }
+ }
+}
+
+// countIndents returns the number of identations for the given input.
+// In case of invalid input such as var a = } the result can be negative.
+func countIndents(input string) int {
+ var (
+ indents = 0
+ inString = false
+ strOpenChar = ' ' // keep track of the string open char to allow var str = "I'm ....";
+ charEscaped = false // keep track if the previous char was the '\' char, allow var str = "abc\"def";
+ )
+
+ for _, c := range input {
+ switch c {
+ case '\\':
+ // indicate next char as escaped when in string and previous char isn't escaping this backslash
+ if !charEscaped && inString {
+ charEscaped = true
+ }
+ case '\'', '"':
+ if inString && !charEscaped && strOpenChar == c { // end string
+ inString = false
+ } else if !inString && !charEscaped { // begin string
+ inString = true
+ strOpenChar = c
+ }
+ charEscaped = false
+ case '{', '(':
+ if !inString { // ignore brackets when in string, allow var str = "a{"; without indenting
+ indents++
+ }
+ charEscaped = false
+ case '}', ')':
+ if !inString {
+ indents--
+ }
+ charEscaped = false
+ default:
+ charEscaped = false
+ }
+ }
+
+ return indents
+}
+
+// Execute runs the JavaScript file specified as the argument.
+func (c *Console) Execute(path string) error {
+ return c.jsre.Exec(path)
+}
+
+// Stop cleans up the console and terminates the runtime envorinment.
+func (c *Console) Stop(graceful bool) error {
+ if err := ioutil.WriteFile(c.histPath, []byte(strings.Join(c.history, "\n")), 0600); err != nil {
+ return err
+ }
+ if err := os.Chmod(c.histPath, 0600); err != nil { // Force 0600, even if it was different previously
+ return err
+ }
+ c.jsre.Stop(graceful)
+ return nil
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/console/prompter.go b/src/vendor/github.com/ethereum/go-ethereum/console/prompter.go
new file mode 100644
index 000000000..0e4a8a53e
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/console/prompter.go
@@ -0,0 +1,165 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package console
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/peterh/liner"
+)
+
+// Stdin holds the stdin line reader (also using stdout for printing prompts).
+// Only this reader may be used for input because it keeps an internal buffer.
+var Stdin = newTerminalPrompter()
+
+// UserPrompter defines the methods needed by the console to promt the user for
+// various types of inputs.
+type UserPrompter interface {
+ // PromptInput displays the given prompt to the user and requests some textual
+ // data to be entered, returning the input of the user.
+ PromptInput(prompt string) (string, error)
+
+ // PromptPassword displays the given prompt to the user and requests some textual
+ // data to be entered, but one which must not be echoed out into the terminal.
+ // The method returns the input provided by the user.
+ PromptPassword(prompt string) (string, error)
+
+ // PromptConfirm displays the given prompt to the user and requests a boolean
+ // choice to be made, returning that choice.
+ PromptConfirm(prompt string) (bool, error)
+
+ // SetHistory sets the the input scrollback history that the prompter will allow
+ // the user to scoll back to.
+ SetHistory(history []string)
+
+ // AppendHistory appends an entry to the scrollback history. It should be called
+ // if and only if the prompt to append was a valid command.
+ AppendHistory(command string)
+
+ // SetWordCompleter sets the completion function that the prompter will call to
+ // fetch completion candidates when the user presses tab.
+ SetWordCompleter(completer WordCompleter)
+}
+
+// WordCompleter takes the currently edited line with the cursor position and
+// returns the completion candidates for the partial word to be completed. If
+// the line is "Hello, wo!!!" and the cursor is before the first '!', ("Hello,
+// wo!!!", 9) is passed to the completer which may returns ("Hello, ", {"world",
+// "Word"}, "!!!") to have "Hello, world!!!".
+type WordCompleter func(line string, pos int) (string, []string, string)
+
+// terminalPrompter is a UserPrompter backed by the liner package. It supports
+// prompting the user for various input, among others for non-echoing password
+// input.
+type terminalPrompter struct {
+ *liner.State
+ warned bool
+ supported bool
+ normalMode liner.ModeApplier
+ rawMode liner.ModeApplier
+}
+
+// newTerminalPrompter creates a liner based user input prompter working off the
+// standard input and output streams.
+func newTerminalPrompter() *terminalPrompter {
+ p := new(terminalPrompter)
+ // Get the original mode before calling NewLiner.
+ // This is usually regular "cooked" mode where characters echo.
+ normalMode, _ := liner.TerminalMode()
+ // Turn on liner. It switches to raw mode.
+ p.State = liner.NewLiner()
+ rawMode, err := liner.TerminalMode()
+ if err != nil || !liner.TerminalSupported() {
+ p.supported = false
+ } else {
+ p.supported = true
+ p.normalMode = normalMode
+ p.rawMode = rawMode
+ // Switch back to normal mode while we're not prompting.
+ normalMode.ApplyMode()
+ }
+ p.SetCtrlCAborts(true)
+ p.SetTabCompletionStyle(liner.TabPrints)
+
+ return p
+}
+
+// PromptInput displays the given prompt to the user and requests some textual
+// data to be entered, returning the input of the user.
+func (p *terminalPrompter) PromptInput(prompt string) (string, error) {
+ if p.supported {
+ p.rawMode.ApplyMode()
+ defer p.normalMode.ApplyMode()
+ } else {
+ // liner tries to be smart about printing the prompt
+ // and doesn't print anything if input is redirected.
+ // Un-smart it by printing the prompt always.
+ fmt.Print(prompt)
+ prompt = ""
+ defer fmt.Println()
+ }
+ return p.State.Prompt(prompt)
+}
+
+// PromptPassword displays the given prompt to the user and requests some textual
+// data to be entered, but one which must not be echoed out into the terminal.
+// The method returns the input provided by the user.
+func (p *terminalPrompter) PromptPassword(prompt string) (passwd string, err error) {
+ if p.supported {
+ p.rawMode.ApplyMode()
+ defer p.normalMode.ApplyMode()
+ return p.State.PasswordPrompt(prompt)
+ }
+ if !p.warned {
+ fmt.Println("!! Unsupported terminal, password will be echoed.")
+ p.warned = true
+ }
+ // Just as in Prompt, handle printing the prompt here instead of relying on liner.
+ fmt.Print(prompt)
+ passwd, err = p.State.Prompt("")
+ fmt.Println()
+ return passwd, err
+}
+
+// PromptConfirm displays the given prompt to the user and requests a boolean
+// choice to be made, returning that choice.
+func (p *terminalPrompter) PromptConfirm(prompt string) (bool, error) {
+ input, err := p.Prompt(prompt + " [y/N] ")
+ if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
+ return true, nil
+ }
+ return false, err
+}
+
+// SetHistory sets the the input scrollback history that the prompter will allow
+// the user to scoll back to.
+func (p *terminalPrompter) SetHistory(history []string) {
+ p.State.ReadHistory(strings.NewReader(strings.Join(history, "\n")))
+}
+
+// AppendHistory appends an entry to the scrollback history. It should be called
+// if and only if the prompt to append was a valid command.
+func (p *terminalPrompter) AppendHistory(command string) {
+ p.State.AppendHistory(command)
+}
+
+// SetWordCompleter sets the completion function that the prompter will call to
+// fetch completion candidates when the user presses tab.
+func (p *terminalPrompter) SetWordCompleter(completer WordCompleter) {
+ p.State.SetWordCompleter(liner.WordCompleter(completer))
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/.gitignore b/src/vendor/github.com/ethereum/go-ethereum/core/.gitignore
deleted file mode 100644
index f725d58d1..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/core/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-# See http://help.github.com/ignore-files/ for more about ignoring files.
-#
-# If you find yourself ignoring temporary files generated by your text editor
-# or operating system, you probably want to add a global ignore instead:
-# git config --global core.excludesfile ~/.gitignore_global
-
-/tmp
-*/**/*un~
-*un~
-.DS_Store
-*/**/.DS_Store
-
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/block_validator.go b/src/vendor/github.com/ethereum/go-ethereum/core/block_validator.go
index f777b9f23..e5bc6178b 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/block_validator.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/block_validator.go
@@ -64,7 +64,7 @@ func NewBlockValidator(config *ChainConfig, blockchain *BlockChain, pow pow.PoW)
//
// ValidateBlock also validates and makes sure that any previous state (or present)
// state that might or might not be present is checked to make sure that fast
-// sync has done it's job proper. This prevents the block validator form accepting
+// sync has done it's job proper. This prevents the block validator from accepting
// false positives where a header is present but the state is not.
func (v *BlockValidator) ValidateBlock(block *types.Block) error {
if v.bc.HasBlock(block.Hash()) {
@@ -139,7 +139,7 @@ func (v *BlockValidator) ValidateState(block, parent *types.Block, statedb *stat
// error if any of the included uncle headers were invalid. It returns an error
// if the validation failed.
func (v *BlockValidator) VerifyUncles(block, parent *types.Block) error {
- // validate that there at most 2 uncles included in this block
+ // validate that there are at most 2 uncles included in this block
if len(block.Uncles()) > 2 {
return ValidationError("Block can only contain maximum 2 uncles (contained %v)", len(block.Uncles()))
}
@@ -193,7 +193,7 @@ func (v *BlockValidator) ValidateHeader(header, parent *types.Header, checkPow b
if parent == nil {
return ParentError(header.ParentHash)
}
- // Short circuit if the header's already known or its parent missing
+ // Short circuit if the header's already known or its parent is missing
if v.bc.HasHeader(header.Hash()) {
return nil
}
@@ -247,7 +247,8 @@ func ValidateHeader(config *ChainConfig, pow pow.PoW, header *types.Header, pare
return &BlockNonceErr{header.Number, header.Hash(), header.Nonce.Uint64()}
}
}
- return nil
+ // If all checks passed, validate the extra-data field for hard forks
+ return ValidateDAOHeaderExtraData(config, header)
}
// CalcDifficulty is the difficulty adjustment algorithm. It returns
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/blockchain.go b/src/vendor/github.com/ethereum/go-ethereum/core/blockchain.go
index 62ebecaf1..fb77106cd 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/blockchain.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/blockchain.go
@@ -777,14 +777,13 @@ func (self *BlockChain) WriteBlock(block *types.Block) (status WriteStatus, err
if ptd == nil {
return NonStatTy, ParentError(block.ParentHash())
}
-
- localTd := self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64())
- externTd := new(big.Int).Add(block.Difficulty(), ptd)
-
// Make sure no inconsistent state is leaked during insertion
self.mu.Lock()
defer self.mu.Unlock()
+ localTd := self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64())
+ externTd := new(big.Int).Add(block.Difficulty(), ptd)
+
// If the total difficulty is higher than our known, add it to the canonical chain
// Second clause in the if statement reduces the vulnerability to selfish mining.
// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/chain_makers.go b/src/vendor/github.com/ethereum/go-ethereum/core/chain_makers.go
index ef0ac66d1..0b9a5f75d 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/chain_makers.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/chain_makers.go
@@ -26,6 +26,7 @@ import (
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
+ "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow"
)
@@ -35,7 +36,11 @@ import (
// MakeChainConfig returns a new ChainConfig with the ethereum default chain settings.
func MakeChainConfig() *ChainConfig {
- return &ChainConfig{HomesteadBlock: big.NewInt(0)}
+ return &ChainConfig{
+ HomesteadBlock: big.NewInt(0),
+ DAOForkBlock: nil,
+ DAOForkSupport: true,
+ }
}
// FakePow is a non-validating proof of work implementation.
@@ -173,10 +178,27 @@ func (b *BlockGen) OffsetTime(seconds int64) {
// Blocks created by GenerateChain do not contain valid proof of work
// values. Inserting them into BlockChain requires use of FakePow or
// a similar non-validating proof of work implementation.
-func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
+func GenerateChain(config *ChainConfig, parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
genblock := func(i int, h *types.Header, statedb *state.StateDB) (*types.Block, types.Receipts) {
b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}
+
+ // Mutate the state and block according to any hard-fork specs
+ if config == nil {
+ config = MakeChainConfig()
+ }
+ if daoBlock := config.DAOForkBlock; daoBlock != nil {
+ limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
+ if h.Number.Cmp(daoBlock) >= 0 && h.Number.Cmp(limit) < 0 {
+ if config.DAOForkSupport {
+ h.Extra = common.CopyBytes(params.DAOForkBlockExtra)
+ }
+ }
+ }
+ if config.DAOForkSupport && config.DAOForkBlock != nil && config.DAOForkBlock.Cmp(h.Number) == 0 {
+ ApplyDAOHardFork(statedb)
+ }
+ // Execute any user modifications to the block and finalize it
if gen != nil {
gen(i, b)
}
@@ -261,7 +283,7 @@ func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) [
// makeBlockChain creates a deterministic chain of blocks rooted at parent.
func makeBlockChain(parent *types.Block, n int, db ethdb.Database, seed int) []*types.Block {
- blocks, _ := GenerateChain(parent, db, n, func(i int, b *BlockGen) {
+ blocks, _ := GenerateChain(nil, parent, db, n, func(i int, b *BlockGen) {
b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
})
return blocks
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/config.go b/src/vendor/github.com/ethereum/go-ethereum/core/config.go
index 81ca76aa3..c0d065a57 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/config.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/config.go
@@ -31,16 +31,17 @@ var ChainConfigNotFoundErr = errors.New("ChainConfig not found") // general conf
// that any network, identified by its genesis block, can have its own
// set of configuration options.
type ChainConfig struct {
- HomesteadBlock *big.Int // homestead switch block
+ HomesteadBlock *big.Int `json:"homesteadBlock"` // Homestead switch block (nil = no fork, 0 = already homestead)
+ DAOForkBlock *big.Int `json:"daoForkBlock"` // TheDAO hard-fork switch block (nil = no fork)
+ DAOForkSupport bool `json:"daoForkSupport"` // Whether the nodes supports or opposes the DAO hard-fork
VmConfig vm.Config `json:"-"`
}
// IsHomestead returns whether num is either equal to the homestead block or greater.
func (c *ChainConfig) IsHomestead(num *big.Int) bool {
- if num == nil {
+ if c.HomesteadBlock == nil || num == nil {
return false
}
-
return num.Cmp(c.HomesteadBlock) >= 0
}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/dao.go b/src/vendor/github.com/ethereum/go-ethereum/core/dao.go
new file mode 100644
index 000000000..e315c9884
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/dao.go
@@ -0,0 +1,74 @@
+// Copyright 2016 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package core
+
+import (
+ "bytes"
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/core/state"
+ "github.com/ethereum/go-ethereum/core/types"
+ "github.com/ethereum/go-ethereum/params"
+)
+
+// ValidateDAOHeaderExtraData validates the extra-data field of a block header to
+// ensure it conforms to DAO hard-fork rules.
+//
+// DAO hard-fork extension to the header validity:
+// a) if the node is no-fork, do not accept blocks in the [fork, fork+10) range
+// with the fork specific extra-data set
+// b) if the node is pro-fork, require blocks in the specific range to have the
+// unique extra-data set.
+func ValidateDAOHeaderExtraData(config *ChainConfig, header *types.Header) error {
+ // Short circuit validation if the node doesn't care about the DAO fork
+ if config.DAOForkBlock == nil {
+ return nil
+ }
+ // Make sure the block is within the fork's modified extra-data range
+ limit := new(big.Int).Add(config.DAOForkBlock, params.DAOForkExtraRange)
+ if header.Number.Cmp(config.DAOForkBlock) < 0 || header.Number.Cmp(limit) >= 0 {
+ return nil
+ }
+ // Depending whether we support or oppose the fork, validate the extra-data contents
+ if config.DAOForkSupport {
+ if bytes.Compare(header.Extra, params.DAOForkBlockExtra) != 0 {
+ return ValidationError("DAO pro-fork bad block extra-data: 0x%x", header.Extra)
+ }
+ } else {
+ if bytes.Compare(header.Extra, params.DAOForkBlockExtra) == 0 {
+ return ValidationError("DAO no-fork bad block extra-data: 0x%x", header.Extra)
+ }
+ }
+ // All ok, header has the same extra-data we expect
+ return nil
+}
+
+// ApplyDAOHardFork modifies the state database according to the DAO hard-fork
+// rules, transferring all balances of a set of DAO accounts to a single refund
+// contract.
+func ApplyDAOHardFork(statedb *state.StateDB) {
+ // Retrieve the contract to refund balances into
+ refund := statedb.GetOrNewStateObject(params.DAORefundContract)
+
+ // Move every DAO account and extra-balance account funds into the refund contract
+ for _, addr := range params.DAODrainList {
+ if account := statedb.GetStateObject(addr); account != nil {
+ refund.AddBalance(account.Balance())
+ account.SetBalance(new(big.Int))
+ }
+ }
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/database_util.go b/src/vendor/github.com/ethereum/go-ethereum/core/database_util.go
index 7456d32dd..bbb99d10c 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/database_util.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/database_util.go
@@ -625,3 +625,30 @@ func GetChainConfig(db ethdb.Database, hash common.Hash) (*ChainConfig, error) {
return &config, nil
}
+
+// FindCommonAncestor returns the last common ancestor of two block headers
+func FindCommonAncestor(db ethdb.Database, a, b *types.Header) *types.Header {
+ for a.GetNumberU64() > b.GetNumberU64() {
+ a = GetHeader(db, a.ParentHash, a.GetNumberU64()-1)
+ if a == nil {
+ return nil
+ }
+ }
+ for a.GetNumberU64() < b.GetNumberU64() {
+ b = GetHeader(db, b.ParentHash, b.GetNumberU64()-1)
+ if b == nil {
+ return nil
+ }
+ }
+ for a.Hash() != b.Hash() {
+ a = GetHeader(db, a.ParentHash, a.GetNumberU64()-1)
+ if a == nil {
+ return nil
+ }
+ b = GetHeader(db, b.ParentHash, b.GetNumberU64()-1)
+ if b == nil {
+ return nil
+ }
+ }
+ return a
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/state/statedb.go b/src/vendor/github.com/ethereum/go-ethereum/core/state/statedb.go
index 70673799e..3e25e0c16 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/state/statedb.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/state/statedb.go
@@ -370,6 +370,27 @@ func (s *StateDB) IntermediateRoot() common.Hash {
return s.trie.Hash()
}
+// DeleteSuicides flags the suicided objects for deletion so that it
+// won't be referenced again when called / queried up on.
+//
+// DeleteSuicides should not be used for consensus related updates
+// under any circumstances.
+func (s *StateDB) DeleteSuicides() {
+ // Reset refund so that any used-gas calculations can use
+ // this method.
+ s.refund = new(big.Int)
+ for _, stateObject := range s.stateObjects {
+ if stateObject.dirty {
+ // If the object has been removed by a suicide
+ // flag the object as deleted.
+ if stateObject.remove {
+ stateObject.deleted = true
+ }
+ stateObject.dirty = false
+ }
+ }
+}
+
// Commit commits all state changes to the database.
func (s *StateDB) Commit() (root common.Hash, err error) {
root, batch := s.CommitBatch()
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/state_processor.go b/src/vendor/github.com/ethereum/go-ethereum/core/state_processor.go
index 95b3057bb..fd8e9762e 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/state_processor.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/state_processor.go
@@ -65,7 +65,11 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
allLogs vm.Logs
gp = new(GasPool).AddGas(block.GasLimit())
)
-
+ // Mutate the the block and state according to any hard-fork specs
+ if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
+ ApplyDAOHardFork(statedb)
+ }
+ // Iterate over and process the individual transactions
for i, tx := range block.Transactions() {
statedb.StartRecord(tx.Hash(), block.Hash(), i)
receipt, logs, _, err := ApplyTransaction(p.config, p.bc, gp, statedb, header, tx, totalUsedGas, cfg)
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/state_transition.go b/src/vendor/github.com/ethereum/go-ethereum/core/state_transition.go
index c8160424b..9e6b2f567 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/state_transition.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/state_transition.go
@@ -71,6 +71,7 @@ type Message interface {
Value() *big.Int
Nonce() uint64
+ CheckNonce() bool
Data() []byte
}
@@ -208,8 +209,10 @@ func (self *StateTransition) preCheck() (err error) {
}
// Make sure this transaction's nonce is correct
- if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
- return NonceError(msg.Nonce(), n)
+ if msg.CheckNonce() {
+ if n := self.state.GetNonce(sender.Address()); n != msg.Nonce() {
+ return NonceError(msg.Nonce(), n)
+ }
}
// Pre-pay gas
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go b/src/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go
index b99d3a716..c71c98aa7 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/types/transaction.go
@@ -113,6 +113,7 @@ func (tx *Transaction) Gas() *big.Int { return new(big.Int).Set(tx.data.Gas
func (tx *Transaction) GasPrice() *big.Int { return new(big.Int).Set(tx.data.Price) }
func (tx *Transaction) Value() *big.Int { return new(big.Int).Set(tx.data.Amount) }
func (tx *Transaction) Nonce() uint64 { return tx.data.AccountNonce }
+func (tx *Transaction) CheckNonce() bool { return true }
func (tx *Transaction) To() *common.Address {
if tx.data.Recipient == nil {
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/vm/jit.go b/src/vendor/github.com/ethereum/go-ethereum/core/vm/jit.go
index f56d7c1af..e2374df42 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/vm/jit.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/vm/jit.go
@@ -421,7 +421,7 @@ func jitCalculateGasAndSize(env Environment, contract *Contract, instr instructi
g = params.SstoreClearGas
} else {
- g = params.SstoreClearGas
+ g = params.SstoreResetGas
}
gas.Set(g)
case SUICIDE:
diff --git a/src/vendor/github.com/ethereum/go-ethereum/light/events.go b/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/doc.go
similarity index 65%
rename from src/vendor/github.com/ethereum/go-ethereum/light/events.go
rename to src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/doc.go
index 28d91e31d..a3b464a7d 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/light/events.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/doc.go
@@ -1,4 +1,4 @@
-// Copyright 2015 The go-ethereum Authors
+// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
@@ -14,20 +14,5 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see .
-package light
-
-import (
- "github.com/ethereum/go-ethereum/common"
- "github.com/ethereum/go-ethereum/core/types"
-)
-
-type LightChainSplitEvent struct{ Header *types.Header }
-
-type LightChainEvent struct {
- Header *types.Header
- Hash common.Hash
-}
-
-type LightChainSideEvent struct{ Header *types.Header }
-
-type LightChainHeadEvent struct{ Header *types.Header }
+// Package runtime provides a basic execution model for executing EVM code.
+package runtime
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/env.go b/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/env.go
new file mode 100644
index 000000000..d8c98e545
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/env.go
@@ -0,0 +1,127 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package runtime
+
+import (
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/core/state"
+ "github.com/ethereum/go-ethereum/core/vm"
+)
+
+// Env is a basic runtime environment required for running the EVM.
+type Env struct {
+ ruleSet vm.RuleSet
+ depth int
+ state *state.StateDB
+
+ origin common.Address
+ coinbase common.Address
+
+ number *big.Int
+ time *big.Int
+ difficulty *big.Int
+ gasLimit *big.Int
+
+ logs []vm.StructLog
+
+ getHashFn func(uint64) common.Hash
+
+ evm *vm.EVM
+}
+
+// NewEnv returns a new vm.Environment
+func NewEnv(cfg *Config, state *state.StateDB) vm.Environment {
+ env := &Env{
+ ruleSet: cfg.RuleSet,
+ state: state,
+ origin: cfg.Origin,
+ coinbase: cfg.Coinbase,
+ number: cfg.BlockNumber,
+ time: cfg.Time,
+ difficulty: cfg.Difficulty,
+ gasLimit: cfg.GasLimit,
+ }
+ env.evm = vm.New(env, vm.Config{
+ Debug: cfg.Debug,
+ EnableJit: !cfg.DisableJit,
+ ForceJit: !cfg.DisableJit,
+
+ Logger: vm.LogConfig{
+ Collector: env,
+ },
+ })
+
+ return env
+}
+
+func (self *Env) StructLogs() []vm.StructLog {
+ return self.logs
+}
+
+func (self *Env) AddStructLog(log vm.StructLog) {
+ self.logs = append(self.logs, log)
+}
+
+func (self *Env) RuleSet() vm.RuleSet { return self.ruleSet }
+func (self *Env) Vm() vm.Vm { return self.evm }
+func (self *Env) Origin() common.Address { return self.origin }
+func (self *Env) BlockNumber() *big.Int { return self.number }
+func (self *Env) Coinbase() common.Address { return self.coinbase }
+func (self *Env) Time() *big.Int { return self.time }
+func (self *Env) Difficulty() *big.Int { return self.difficulty }
+func (self *Env) Db() vm.Database { return self.state }
+func (self *Env) GasLimit() *big.Int { return self.gasLimit }
+func (self *Env) VmType() vm.Type { return vm.StdVmTy }
+func (self *Env) GetHash(n uint64) common.Hash {
+ return self.getHashFn(n)
+}
+func (self *Env) AddLog(log *vm.Log) {
+ self.state.AddLog(log)
+}
+func (self *Env) Depth() int { return self.depth }
+func (self *Env) SetDepth(i int) { self.depth = i }
+func (self *Env) CanTransfer(from common.Address, balance *big.Int) bool {
+ return self.state.GetBalance(from).Cmp(balance) >= 0
+}
+func (self *Env) MakeSnapshot() vm.Database {
+ return self.state.Copy()
+}
+func (self *Env) SetSnapshot(copy vm.Database) {
+ self.state.Set(copy.(*state.StateDB))
+}
+
+func (self *Env) Transfer(from, to vm.Account, amount *big.Int) {
+ core.Transfer(from, to, amount)
+}
+
+func (self *Env) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
+ return core.Call(self, caller, addr, data, gas, price, value)
+}
+func (self *Env) CallCode(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
+ return core.CallCode(self, caller, addr, data, gas, price, value)
+}
+
+func (self *Env) DelegateCall(me vm.ContractRef, addr common.Address, data []byte, gas, price *big.Int) ([]byte, error) {
+ return core.DelegateCall(self, me, addr, data, gas, price)
+}
+
+func (self *Env) Create(caller vm.ContractRef, data []byte, gas, price, value *big.Int) ([]byte, common.Address, error) {
+ return core.Create(self, caller, data, gas, price, value)
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/runtime.go b/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/runtime.go
new file mode 100644
index 000000000..309d508c3
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/vm/runtime/runtime.go
@@ -0,0 +1,144 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package runtime
+
+import (
+ "math/big"
+ "time"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core/state"
+ "github.com/ethereum/go-ethereum/core/vm"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/ethdb"
+)
+
+// The default, always homestead, rule set for the vm env
+type ruleSet struct{}
+
+func (ruleSet) IsHomestead(*big.Int) bool { return true }
+
+// Config is a basic type specifying certain configuration flags for running
+// the EVM.
+type Config struct {
+ RuleSet vm.RuleSet
+ Difficulty *big.Int
+ Origin common.Address
+ Coinbase common.Address
+ BlockNumber *big.Int
+ Time *big.Int
+ GasLimit *big.Int
+ GasPrice *big.Int
+ Value *big.Int
+ DisableJit bool // "disable" so it's enabled by default
+ Debug bool
+
+ State *state.StateDB
+ GetHashFn func(n uint64) common.Hash
+}
+
+// sets defaults on the config
+func setDefaults(cfg *Config) {
+ if cfg.RuleSet == nil {
+ cfg.RuleSet = ruleSet{}
+ }
+
+ if cfg.Difficulty == nil {
+ cfg.Difficulty = new(big.Int)
+ }
+ if cfg.Time == nil {
+ cfg.Time = big.NewInt(time.Now().Unix())
+ }
+ if cfg.GasLimit == nil {
+ cfg.GasLimit = new(big.Int).Set(common.MaxBig)
+ }
+ if cfg.GasPrice == nil {
+ cfg.GasPrice = new(big.Int)
+ }
+ if cfg.Value == nil {
+ cfg.Value = new(big.Int)
+ }
+ if cfg.BlockNumber == nil {
+ cfg.BlockNumber = new(big.Int)
+ }
+ if cfg.GetHashFn == nil {
+ cfg.GetHashFn = func(n uint64) common.Hash {
+ return common.BytesToHash(crypto.Keccak256([]byte(new(big.Int).SetUint64(n).String())))
+ }
+ }
+}
+
+// Execute executes the code using the input as call data during the execution.
+// It returns the EVM's return value, the new state and an error if it failed.
+//
+// Executes sets up a in memory, temporarily, environment for the execution of
+// the given code. It enabled the JIT by default and make sure that it's restored
+// to it's original state afterwards.
+func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) {
+ if cfg == nil {
+ cfg = new(Config)
+ }
+ setDefaults(cfg)
+
+ if cfg.State == nil {
+ db, _ := ethdb.NewMemDatabase()
+ cfg.State, _ = state.New(common.Hash{}, db)
+ }
+ var (
+ vmenv = NewEnv(cfg, cfg.State)
+ sender = cfg.State.CreateAccount(cfg.Origin)
+ receiver = cfg.State.CreateAccount(common.StringToAddress("contract"))
+ )
+ // set the receiver's (the executing contract) code for execution.
+ receiver.SetCode(code)
+
+ // Call the code with the given configuration.
+ ret, err := vmenv.Call(
+ sender,
+ receiver.Address(),
+ input,
+ cfg.GasLimit,
+ cfg.GasPrice,
+ cfg.Value,
+ )
+
+ return ret, cfg.State, err
+}
+
+// Call executes the code given by the contract's address. It will return the
+// EVM's return value or an error if it failed.
+//
+// Call, unlike Execute, requires a config and also requires the State field to
+// be set.
+func Call(address common.Address, input []byte, cfg *Config) ([]byte, error) {
+ setDefaults(cfg)
+
+ vmenv := NewEnv(cfg, cfg.State)
+
+ sender := cfg.State.GetOrNewStateObject(cfg.Origin)
+ // Call the code with the given configuration.
+ ret, err := vmenv.Call(
+ sender,
+ address,
+ input,
+ cfg.GasLimit,
+ cfg.GasPrice,
+ cfg.Value,
+ )
+
+ return ret, err
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/core/vm/vm.go b/src/vendor/github.com/ethereum/go-ethereum/core/vm/vm.go
index 0f93715d6..52e782b23 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/core/vm/vm.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/core/vm/vm.go
@@ -306,7 +306,7 @@ func calculateGasAndSize(env Environment, contract *Contract, caller ContractRef
g = params.SstoreClearGas
} else {
// non 0 => non 0 (or 0 => 0)
- g = params.SstoreClearGas
+ g = params.SstoreResetGas
}
gas.Set(g)
case SUICIDE:
diff --git a/src/vendor/github.com/ethereum/go-ethereum/crypto/ecies/.gitignore b/src/vendor/github.com/ethereum/go-ethereum/crypto/ecies/.gitignore
deleted file mode 100644
index 802b6744a..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/crypto/ecies/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-
-*~
diff --git a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/.gitignore b/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/.gitignore
deleted file mode 100644
index 802b6744a..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-
-*~
diff --git a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/.gitignore b/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/.gitignore
deleted file mode 100644
index e0b7b7a48..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/.gitignore
+++ /dev/null
@@ -1,41 +0,0 @@
-bench_inv
-bench_ecdh
-bench_sign
-bench_verify
-bench_schnorr_verify
-bench_recover
-bench_internal
-tests
-gen_context
-*.exe
-*.so
-*.a
-!.gitignore
-
-Makefile
-configure
-.libs/
-Makefile.in
-aclocal.m4
-autom4te.cache/
-config.log
-config.status
-*.tar.gz
-*.la
-libtool
-.deps/
-.dirstamp
-build-aux/
-*.lo
-*.o
-*~
-src/libsecp256k1-config.h
-src/libsecp256k1-config.h.in
-src/ecmult_static_context.h
-m4/libtool.m4
-m4/ltoptions.m4
-m4/ltsugar.m4
-m4/ltversion.m4
-m4/lt~obsolete.m4
-src/stamp-h1
-libsecp256k1.pc
diff --git a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/.travis.yml b/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/.travis.yml
deleted file mode 100644
index fba0892dd..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/.travis.yml
+++ /dev/null
@@ -1,62 +0,0 @@
-language: c
-sudo: false
-addons:
- apt:
- packages: libgmp-dev
-compiler:
- - clang
- - gcc
-env:
- global:
- - FIELD=auto BIGNUM=auto SCALAR=auto ENDOMORPHISM=no STATICPRECOMPUTATION=yes ASM=no BUILD=check EXTRAFLAGS= HOST= ECDH=no schnorr=NO RECOVERY=NO
- matrix:
- - SCALAR=32bit RECOVERY=yes
- - SCALAR=32bit FIELD=32bit ECDH=yes
- - SCALAR=64bit
- - FIELD=64bit RECOVERY=yes
- - FIELD=64bit ENDOMORPHISM=yes
- - FIELD=64bit ENDOMORPHISM=yes ECDH=yes
- - FIELD=64bit ASM=x86_64
- - FIELD=64bit ENDOMORPHISM=yes ASM=x86_64
- - FIELD=32bit SCHNORR=yes
- - FIELD=32bit ENDOMORPHISM=yes
- - BIGNUM=no
- - BIGNUM=no ENDOMORPHISM=yes SCHNORR=yes RECOVERY=yes
- - BIGNUM=no STATICPRECOMPUTATION=no
- - BUILD=distcheck
- - EXTRAFLAGS=CFLAGS=-DDETERMINISTIC
-matrix:
- fast_finish: true
- include:
- - compiler: clang
- env: HOST=i686-linux-gnu ENDOMORPHISM=yes
- addons:
- apt:
- packages:
- - gcc-multilib
- - libgmp-dev:i386
- - compiler: clang
- env: HOST=i686-linux-gnu
- addons:
- apt:
- packages:
- - gcc-multilib
- - compiler: gcc
- env: HOST=i686-linux-gnu ENDOMORPHISM=yes
- addons:
- apt:
- packages:
- - gcc-multilib
- - compiler: gcc
- env: HOST=i686-linux-gnu
- addons:
- apt:
- packages:
- - gcc-multilib
- - libgmp-dev:i386
-before_script: ./autogen.sh
-script:
- - if [ -n "$HOST" ]; then export USE_HOST="--host=$HOST"; fi
- - if [ "x$HOST" = "xi686-linux-gnu" ]; then export CC="$CC -m32"; fi
- - ./configure --enable-endomorphism=$ENDOMORPHISM --with-field=$FIELD --with-bignum=$BIGNUM --with-scalar=$SCALAR --enable-ecmult-static-precomputation=$STATICPRECOMPUTATION --enable-module-ecdh=$ECDH --enable-module-schnorr=$SCHNORR $EXTRAFLAGS $USE_HOST && make -j2 $BUILD
-os: linux
diff --git a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/README.md b/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/README.md
deleted file mode 100644
index 6095db422..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/README.md
+++ /dev/null
@@ -1,61 +0,0 @@
-libsecp256k1
-============
-
-[![Build Status](https://travis-ci.org/bitcoin/secp256k1.svg?branch=master)](https://travis-ci.org/bitcoin/secp256k1)
-
-Optimized C library for EC operations on curve secp256k1.
-
-This library is a work in progress and is being used to research best practices. Use at your own risk.
-
-Features:
-* secp256k1 ECDSA signing/verification and key generation.
-* Adding/multiplying private/public keys.
-* Serialization/parsing of private keys, public keys, signatures.
-* Constant time, constant memory access signing and pubkey generation.
-* Derandomized DSA (via RFC6979 or with a caller provided function.)
-* Very efficient implementation.
-
-Implementation details
-----------------------
-
-* General
- * No runtime heap allocation.
- * Extensive testing infrastructure.
- * Structured to facilitate review and analysis.
- * Intended to be portable to any system with a C89 compiler and uint64_t support.
- * Expose only higher level interfaces to minimize the API surface and improve application security. ("Be difficult to use insecurely.")
-* Field operations
- * Optimized implementation of arithmetic modulo the curve's field size (2^256 - 0x1000003D1).
- * Using 5 52-bit limbs (including hand-optimized assembly for x86_64, by Diederik Huys).
- * Using 10 26-bit limbs.
- * Field inverses and square roots using a sliding window over blocks of 1s (by Peter Dettman).
-* Scalar operations
- * Optimized implementation without data-dependent branches of arithmetic modulo the curve's order.
- * Using 4 64-bit limbs (relying on __int128 support in the compiler).
- * Using 8 32-bit limbs.
-* Group operations
- * Point addition formula specifically simplified for the curve equation (y^2 = x^3 + 7).
- * Use addition between points in Jacobian and affine coordinates where possible.
- * Use a unified addition/doubling formula where necessary to avoid data-dependent branches.
- * Point/x comparison without a field inversion by comparison in the Jacobian coordinate space.
-* Point multiplication for verification (a*P + b*G).
- * Use wNAF notation for point multiplicands.
- * Use a much larger window for multiples of G, using precomputed multiples.
- * Use Shamir's trick to do the multiplication with the public key and the generator simultaneously.
- * Optionally (off by default) use secp256k1's efficiently-computable endomorphism to split the P multiplicand into 2 half-sized ones.
-* Point multiplication for signing
- * Use a precomputed table of multiples of powers of 16 multiplied with the generator, so general multiplication becomes a series of additions.
- * Access the table with branch-free conditional moves so memory access is uniform.
- * No data-dependent branches
- * The precomputed tables add and eventually subtract points for which no known scalar (private key) is known, preventing even an attacker with control over the private key used to control the data internally.
-
-Build steps
------------
-
-libsecp256k1 is built using autotools:
-
- $ ./autogen.sh
- $ ./configure
- $ make
- $ ./tests
- $ sudo make install # optional
diff --git a/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/obj/.gitignore b/src/vendor/github.com/ethereum/go-ethereum/crypto/secp256k1/libsecp256k1/obj/.gitignore
deleted file mode 100644
index e69de29bb..000000000
diff --git a/src/vendor/github.com/ethereum/go-ethereum/errs/errors.go b/src/vendor/github.com/ethereum/go-ethereum/errs/errors.go
new file mode 100644
index 000000000..675649efa
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/errs/errors.go
@@ -0,0 +1,110 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+package errs
+
+import (
+ "fmt"
+
+ "github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
+)
+
+/*
+Errors implements an error handler providing standardised errors for a package.
+Fields:
+
+ Errors:
+ a map from error codes to description
+
+ Package:
+ name of the package/component
+
+ Level:
+ a function mapping error code to logger.LogLevel (severity)
+ if not given, errors default to logger.InfoLevel
+*/
+type Errors struct {
+ Errors map[int]string
+ Package string
+ Level func(code int) logger.LogLevel
+}
+
+/*
+Error implements the standard go error interface.
+
+ errors.New(code, format, params ...interface{})
+
+Prints as:
+
+ [package] description: details
+
+where details is fmt.Sprintf(self.format, self.params...)
+*/
+type Error struct {
+ Code int
+ Name string
+ Package string
+ level logger.LogLevel
+ message string
+ format string
+ params []interface{}
+}
+
+func (self *Errors) New(code int, format string, params ...interface{}) *Error {
+ name, ok := self.Errors[code]
+ if !ok {
+ panic("invalid error code")
+ }
+ level := logger.InfoLevel
+ if self.Level != nil {
+ level = self.Level(code)
+ }
+ return &Error{
+ Code: code,
+ Name: name,
+ Package: self.Package,
+ level: level,
+ format: format,
+ params: params,
+ }
+}
+
+func (self Error) Error() (message string) {
+ if len(message) == 0 {
+ self.message = fmt.Sprintf("[%s] ERROR: %s", self.Package, self.Name)
+ if self.format != "" {
+ self.message += ": " + fmt.Sprintf(self.format, self.params...)
+ }
+ }
+ return self.message
+}
+
+func (self Error) Log(v glog.Verbose) {
+ if v {
+ v.Infoln(self)
+ }
+}
+
+/*
+err.Fatal() is true if err's severity level is 0 or 1 (logger.ErrorLevel or logger.Silence)
+*/
+func (self *Error) Fatal() (fatal bool) {
+ if self.level < logger.WarnLevel {
+ fatal = true
+ }
+ return
+}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/api.go b/src/vendor/github.com/ethereum/go-ethereum/eth/api.go
index 8fd759a21..3b7abb69a 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/api.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/api.go
@@ -40,41 +40,41 @@ import (
"github.com/ethereum/go-ethereum/rpc"
)
-// PublicFullEthereumAPI provides an API to access Ethereum full node-related
+// PublicEthereumAPI provides an API to access Ethereum full node-related
// information.
-type PublicFullEthereumAPI struct {
- e *FullNodeService
+type PublicEthereumAPI struct {
+ e *Ethereum
}
-// NewPublicFullEthereumAPI creates a new Etheruem protocol API for full nodes.
-func NewPublicFullEthereumAPI(e *FullNodeService) *PublicFullEthereumAPI {
- return &PublicFullEthereumAPI{e}
+// NewPublicEthereumAPI creates a new Etheruem protocol API for full nodes.
+func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
+ return &PublicEthereumAPI{e}
}
// Etherbase is the address that mining rewards will be send to
-func (s *PublicFullEthereumAPI) Etherbase() (common.Address, error) {
+func (s *PublicEthereumAPI) Etherbase() (common.Address, error) {
return s.e.Etherbase()
}
// Coinbase is the address that mining rewards will be send to (alias for Etherbase)
-func (s *PublicFullEthereumAPI) Coinbase() (common.Address, error) {
+func (s *PublicEthereumAPI) Coinbase() (common.Address, error) {
return s.Etherbase()
}
// Hashrate returns the POW hashrate
-func (s *PublicFullEthereumAPI) Hashrate() *rpc.HexNumber {
+func (s *PublicEthereumAPI) Hashrate() *rpc.HexNumber {
return rpc.NewHexNumber(s.e.Miner().HashRate())
}
// PublicMinerAPI provides an API to control the miner.
// It offers only methods that operate on data that pose no security risk when it is publicly accessible.
type PublicMinerAPI struct {
- e *FullNodeService
+ e *Ethereum
agent *miner.RemoteAgent
}
// NewPublicMinerAPI create a new PublicMinerAPI instance.
-func NewPublicMinerAPI(e *FullNodeService) *PublicMinerAPI {
+func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
agent := miner.NewRemoteAgent()
e.Miner().Register(agent)
@@ -120,11 +120,11 @@ func (s *PublicMinerAPI) SubmitHashrate(hashrate rpc.HexNumber, id common.Hash)
// PrivateMinerAPI provides private RPC methods to control the miner.
// These methods can be abused by external users and must be considered insecure for use by untrusted users.
type PrivateMinerAPI struct {
- e *FullNodeService
+ e *Ethereum
}
// NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
-func NewPrivateMinerAPI(e *FullNodeService) *PrivateMinerAPI {
+func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
return &PrivateMinerAPI{e: e}
}
@@ -191,20 +191,20 @@ func (s *PrivateMinerAPI) MakeDAG(blockNr rpc.BlockNumber) (bool, error) {
return true, nil
}
-// PrivateFullAdminAPI is the collection of Etheruem full node-related APIs
+// PrivateAdminAPI is the collection of Etheruem full node-related APIs
// exposed over the private admin endpoint.
-type PrivateFullAdminAPI struct {
- eth *FullNodeService
+type PrivateAdminAPI struct {
+ eth *Ethereum
}
// NewPrivateAdminAPI creates a new API definition for the full node private
// admin methods of the Ethereum service.
-func NewPrivateFullAdminAPI(eth *FullNodeService) *PrivateFullAdminAPI {
- return &PrivateFullAdminAPI{eth: eth}
+func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
+ return &PrivateAdminAPI{eth: eth}
}
// ExportChain exports the current blockchain into a local file.
-func (api *PrivateFullAdminAPI) ExportChain(file string) (bool, error) {
+func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
// Make sure we can create the file to export into
out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
if err != nil {
@@ -230,7 +230,7 @@ func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
}
// ImportChain imports a blockchain from a local file.
-func (api *PrivateFullAdminAPI) ImportChain(file string) (bool, error) {
+func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
// Make sure the can access the file to import
in, err := os.Open(file)
if err != nil {
@@ -271,20 +271,20 @@ func (api *PrivateFullAdminAPI) ImportChain(file string) (bool, error) {
return true, nil
}
-// PublicFullDebugAPI is the collection of Etheruem full node APIs exposed
+// PublicDebugAPI is the collection of Etheruem full node APIs exposed
// over the public debugging endpoint.
-type PublicFullDebugAPI struct {
- eth *FullNodeService
+type PublicDebugAPI struct {
+ eth *Ethereum
}
-// NewPublicFullDebugAPI creates a new API definition for the full node-
+// NewPublicDebugAPI creates a new API definition for the full node-
// related public debug methods of the Ethereum service.
-func NewPublicFullDebugAPI(eth *FullNodeService) *PublicFullDebugAPI {
- return &PublicFullDebugAPI{eth: eth}
+func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
+ return &PublicDebugAPI{eth: eth}
}
// DumpBlock retrieves the entire state of the database at a given block.
-func (api *PublicFullDebugAPI) DumpBlock(number uint64) (state.World, error) {
+func (api *PublicDebugAPI) DumpBlock(number uint64) (state.World, error) {
block := api.eth.BlockChain().GetBlockByNumber(number)
if block == nil {
return state.World{}, fmt.Errorf("block #%d not found", number)
@@ -296,17 +296,17 @@ func (api *PublicFullDebugAPI) DumpBlock(number uint64) (state.World, error) {
return stateDb.RawDump(), nil
}
-// PrivateFullDebugAPI is the collection of Etheruem full node APIs exposed over
+// PrivateDebugAPI is the collection of Etheruem full node APIs exposed over
// the private debugging endpoint.
-type PrivateFullDebugAPI struct {
+type PrivateDebugAPI struct {
config *core.ChainConfig
- eth *FullNodeService
+ eth *Ethereum
}
-// NewPrivateFullDebugAPI creates a new API definition for the full node-related
+// NewPrivateDebugAPI creates a new API definition for the full node-related
// private debug methods of the Ethereum service.
-func NewPrivateFullDebugAPI(config *core.ChainConfig, eth *FullNodeService) *PrivateFullDebugAPI {
- return &PrivateFullDebugAPI{config: config, eth: eth}
+func NewPrivateDebugAPI(config *core.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
+ return &PrivateDebugAPI{config: config, eth: eth}
}
// BlockTraceResult is the returned value when replaying a block to check for
@@ -319,7 +319,7 @@ type BlockTraceResult struct {
// TraceBlock processes the given block's RLP but does not import the block in to
// the chain.
-func (api *PrivateFullDebugAPI) TraceBlock(blockRlp []byte, config *vm.Config) BlockTraceResult {
+func (api *PrivateDebugAPI) TraceBlock(blockRlp []byte, config *vm.Config) BlockTraceResult {
var block types.Block
err := rlp.Decode(bytes.NewReader(blockRlp), &block)
if err != nil {
@@ -336,7 +336,7 @@ func (api *PrivateFullDebugAPI) TraceBlock(blockRlp []byte, config *vm.Config) B
// TraceBlockFromFile loads the block's RLP from the given file name and attempts to
// process it but does not import the block in to the chain.
-func (api *PrivateFullDebugAPI) TraceBlockFromFile(file string, config *vm.Config) BlockTraceResult {
+func (api *PrivateDebugAPI) TraceBlockFromFile(file string, config *vm.Config) BlockTraceResult {
blockRlp, err := ioutil.ReadFile(file)
if err != nil {
return BlockTraceResult{Error: fmt.Sprintf("could not read file: %v", err)}
@@ -345,7 +345,7 @@ func (api *PrivateFullDebugAPI) TraceBlockFromFile(file string, config *vm.Confi
}
// TraceBlockByNumber processes the block by canonical block number.
-func (api *PrivateFullDebugAPI) TraceBlockByNumber(number uint64, config *vm.Config) BlockTraceResult {
+func (api *PrivateDebugAPI) TraceBlockByNumber(number uint64, config *vm.Config) BlockTraceResult {
// Fetch the block that we aim to reprocess
block := api.eth.BlockChain().GetBlockByNumber(number)
if block == nil {
@@ -361,7 +361,7 @@ func (api *PrivateFullDebugAPI) TraceBlockByNumber(number uint64, config *vm.Con
}
// TraceBlockByHash processes the block by hash.
-func (api *PrivateFullDebugAPI) TraceBlockByHash(hash common.Hash, config *vm.Config) BlockTraceResult {
+func (api *PrivateDebugAPI) TraceBlockByHash(hash common.Hash, config *vm.Config) BlockTraceResult {
// Fetch the block that we aim to reprocess
block := api.eth.BlockChain().GetBlockByHash(hash)
if block == nil {
@@ -389,7 +389,7 @@ func (t *TraceCollector) AddStructLog(slog vm.StructLog) {
}
// traceBlock processes the given block but does not save the state.
-func (api *PrivateFullDebugAPI) traceBlock(block *types.Block, config *vm.Config) (bool, []vm.StructLog, error) {
+func (api *PrivateDebugAPI) traceBlock(block *types.Block, config *vm.Config) (bool, []vm.StructLog, error) {
// Validate and reprocess the block
var (
blockchain = api.eth.BlockChain()
@@ -424,7 +424,6 @@ func (api *PrivateFullDebugAPI) traceBlock(block *types.Block, config *vm.Config
// callmsg is the message type used for call transations.
type callmsg struct {
addr common.Address
- nonce uint64
to *common.Address
gas, gasPrice *big.Int
value *big.Int
@@ -434,7 +433,8 @@ type callmsg struct {
// accessor boilerplate to implement core.Message
func (m callmsg) From() (common.Address, error) { return m.addr, nil }
func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil }
-func (m callmsg) Nonce() uint64 { return m.nonce }
+func (m callmsg) Nonce() uint64 { return 0 }
+func (m callmsg) CheckNonce() bool { return false }
func (m callmsg) To() *common.Address { return m.to }
func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
func (m callmsg) Gas() *big.Int { return m.gas }
@@ -452,7 +452,7 @@ func formatError(err error) string {
// TraceTransaction returns the structured logs created during the execution of EVM
// and returns them as a JSON object.
-func (api *PrivateFullDebugAPI) TraceTransaction(txHash common.Hash, logger *vm.LogConfig) (*ethapi.ExecutionResult, error) {
+func (api *PrivateDebugAPI) TraceTransaction(txHash common.Hash, logger *vm.LogConfig) (*ethapi.ExecutionResult, error) {
if logger == nil {
logger = new(vm.LogConfig)
}
@@ -496,6 +496,7 @@ func (api *PrivateFullDebugAPI) TraceTransaction(txHash common.Hash, logger *vm.
if err != nil {
return nil, fmt.Errorf("mutation failed: %v", err)
}
+ stateDb.DeleteSuicides()
continue
}
// Otherwise trace the transaction and return
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/api_backend.go b/src/vendor/github.com/ethereum/go-ethereum/eth/api_backend.go
index 9dbebb226..aa4c75e20 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/api_backend.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/api_backend.go
@@ -36,7 +36,7 @@ import (
// EthApiBackend implements ethapi.Backend for full nodes
type EthApiBackend struct {
- eth *FullNodeService
+ eth *Ethereum
gpo *gasprice.GasPriceOracle
}
@@ -44,17 +44,17 @@ func (b *EthApiBackend) SetHead(number uint64) {
b.eth.blockchain.SetHead(number)
}
-func (b *EthApiBackend) HeaderByNumber(blockNr rpc.BlockNumber) *types.Header {
+func (b *EthApiBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) {
// Pending block is only known by the miner
if blockNr == rpc.PendingBlockNumber {
block, _ := b.eth.miner.Pending()
- return block.Header()
+ return block.Header(), nil
}
// Otherwise resolve and return the block
if blockNr == rpc.LatestBlockNumber {
- return b.eth.blockchain.CurrentBlock().Header()
+ return b.eth.blockchain.CurrentBlock().Header(), nil
}
- return b.eth.blockchain.GetHeaderByNumber(uint64(blockNr))
+ return b.eth.blockchain.GetHeaderByNumber(uint64(blockNr)), nil
}
func (b *EthApiBackend) BlockByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Block, error) {
@@ -70,16 +70,16 @@ func (b *EthApiBackend) BlockByNumber(ctx context.Context, blockNr rpc.BlockNumb
return b.eth.blockchain.GetBlockByNumber(uint64(blockNr)), nil
}
-func (b *EthApiBackend) StateAndHeaderByNumber(blockNr rpc.BlockNumber) (ethapi.State, *types.Header, error) {
+func (b *EthApiBackend) StateAndHeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (ethapi.State, *types.Header, error) {
// Pending state is only known by the miner
if blockNr == rpc.PendingBlockNumber {
block, state := b.eth.miner.Pending()
return EthApiState{state}, block.Header(), nil
}
// Otherwise resolve the block number and return its state
- header := b.HeaderByNumber(blockNr)
- if header == nil {
- return nil, nil, nil
+ header, err := b.HeaderByNumber(ctx, blockNr)
+ if header == nil || err != nil {
+ return nil, nil, err
}
stateDb, err := state.New(header.Root, b.eth.chainDb)
return EthApiState{stateDb}, header, err
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/backend.go b/src/vendor/github.com/ethereum/go-ethereum/eth/backend.go
index 360acacfc..ea8cc4a0d 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/backend.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/backend.go
@@ -71,6 +71,7 @@ type Config struct {
Genesis string // Genesis JSON to seed the chain database with
FastSync bool // Enables the state download based fast synchronisation algorithm
LightMode bool // Running in light client mode
+ NoDefSrv bool // No default LES server
LightServ int // Maximum percentage of time allowed for serving LES requests
LightPeers int // Maximum number of LES client peers
@@ -112,8 +113,8 @@ type LesServer interface {
Protocols() []p2p.Protocol
}
-// FullNodeService implements the Ethereum full node service.
-type FullNodeService struct {
+// Ethereum implements the Ethereum full node service.
+type Ethereum struct {
chainConfig *core.ChainConfig
// Channel for shutting down the service
shutdownChan chan bool // Channel for shutting down the ethereum
@@ -150,13 +151,13 @@ type FullNodeService struct {
netRPCService *ethapi.PublicNetAPI
}
-func (s *FullNodeService) AddLesServer(ls LesServer) {
+func (s *Ethereum) AddLesServer(ls LesServer) {
s.ls = ls
}
-// New creates a new FullNodeService object (including the
+// New creates a new Ethereum object (including the
// initialisation of the common Ethereum object)
-func New(ctx *node.ServiceContext, config *Config) (*FullNodeService, error) {
+func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
chainDb, dappDb, err := CreateDBs(ctx, config, "chaindata")
if err != nil {
return nil, err
@@ -170,7 +171,7 @@ func New(ctx *node.ServiceContext, config *Config) (*FullNodeService, error) {
return nil, err
}
- eth := &FullNodeService{
+ eth := &Ethereum{
chainDb: chainDb,
dappDb: dappDb,
eventMux: ctx.EventMux,
@@ -219,6 +220,8 @@ func New(ctx *node.ServiceContext, config *Config) (*FullNodeService, error) {
if config.ChainConfig == nil {
return nil, errors.New("missing chain config")
}
+ core.WriteChainConfig(chainDb, genesis.Hash(), config.ChainConfig)
+
eth.chainConfig = config.ChainConfig
eth.chainConfig.VmConfig = vm.Config{
EnableJit: config.EnableJit,
@@ -317,12 +320,12 @@ func CreatePoW(config *Config) (*ethash.Ethash, error) {
// APIs returns the collection of RPC services the ethereum package offers.
// NOTE, some of these services probably need to be moved to somewhere else.
-func (s *FullNodeService) APIs() []rpc.API {
+func (s *Ethereum) APIs() []rpc.API {
return append(ethapi.GetAPIs(s.ApiBackend, &s.solcPath, &s.solc), []rpc.API{
{
Namespace: "eth",
Version: "1.0",
- Service: NewPublicFullEthereumAPI(s),
+ Service: NewPublicEthereumAPI(s),
Public: true,
}, {
Namespace: "eth",
@@ -347,16 +350,16 @@ func (s *FullNodeService) APIs() []rpc.API {
}, {
Namespace: "admin",
Version: "1.0",
- Service: NewPrivateFullAdminAPI(s),
+ Service: NewPrivateAdminAPI(s),
}, {
Namespace: "debug",
Version: "1.0",
- Service: NewPublicFullDebugAPI(s),
+ Service: NewPublicDebugAPI(s),
Public: true,
}, {
Namespace: "debug",
Version: "1.0",
- Service: NewPrivateFullDebugAPI(s.chainConfig, s),
+ Service: NewPrivateDebugAPI(s.chainConfig, s),
}, {
Namespace: "net",
Version: "1.0",
@@ -370,11 +373,11 @@ func (s *FullNodeService) APIs() []rpc.API {
}...)
}
-func (s *FullNodeService) ResetWithGenesisBlock(gb *types.Block) {
+func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
s.blockchain.ResetWithGenesisBlock(gb)
}
-func (s *FullNodeService) Etherbase() (eb common.Address, err error) {
+func (s *Ethereum) Etherbase() (eb common.Address, err error) {
eb = s.etherbase
if (eb == common.Address{}) {
firstAccount, err := s.AccountManager().AccountByIndex(0)
@@ -387,30 +390,30 @@ func (s *FullNodeService) Etherbase() (eb common.Address, err error) {
}
// set in js console via admin interface or wrapper from cli flags
-func (self *FullNodeService) SetEtherbase(etherbase common.Address) {
+func (self *Ethereum) SetEtherbase(etherbase common.Address) {
self.etherbase = etherbase
self.miner.SetEtherbase(etherbase)
}
-func (s *FullNodeService) StopMining() { s.miner.Stop() }
-func (s *FullNodeService) IsMining() bool { return s.miner.Mining() }
-func (s *FullNodeService) Miner() *miner.Miner { return s.miner }
+func (s *Ethereum) StopMining() { s.miner.Stop() }
+func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
+func (s *Ethereum) Miner() *miner.Miner { return s.miner }
-func (s *FullNodeService) AccountManager() *accounts.Manager { return s.accountManager }
-func (s *FullNodeService) BlockChain() *core.BlockChain { return s.blockchain }
-func (s *FullNodeService) TxPool() *core.TxPool { return s.txPool }
-func (s *FullNodeService) EventMux() *event.TypeMux { return s.eventMux }
-func (s *FullNodeService) Pow() *ethash.Ethash { return s.pow }
-func (s *FullNodeService) ChainDb() ethdb.Database { return s.chainDb }
-func (s *FullNodeService) DappDb() ethdb.Database { return s.dappDb }
-func (s *FullNodeService) IsListening() bool { return true } // Always listening
-func (s *FullNodeService) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
-func (s *FullNodeService) NetVersion() int { return s.netVersionId }
-func (s *FullNodeService) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
+func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
+func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
+func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
+func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
+func (s *Ethereum) Pow() *ethash.Ethash { return s.pow }
+func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
+func (s *Ethereum) DappDb() ethdb.Database { return s.dappDb }
+func (s *Ethereum) IsListening() bool { return true } // Always listening
+func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
+func (s *Ethereum) NetVersion() int { return s.netVersionId }
+func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
// Protocols implements node.Service, returning all the currently configured
// network protocols to start.
-func (s *FullNodeService) Protocols() []p2p.Protocol {
+func (s *Ethereum) Protocols() []p2p.Protocol {
if s.ls == nil {
return s.protocolManager.SubProtocols
} else {
@@ -419,8 +422,8 @@ func (s *FullNodeService) Protocols() []p2p.Protocol {
}
// Start implements node.Service, starting all internal goroutines needed by the
-// FullNodeService protocol implementation.
-func (s *FullNodeService) Start(srvr *p2p.Server) error {
+// Ethereum protocol implementation.
+func (s *Ethereum) Start(srvr *p2p.Server) error {
s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
if s.AutoDAG {
s.StartAutoDAG()
@@ -434,7 +437,7 @@ func (s *FullNodeService) Start(srvr *p2p.Server) error {
// Stop implements node.Service, terminating all internal goroutines used by the
// Ethereum protocol.
-func (s *FullNodeService) Stop() error {
+func (s *Ethereum) Stop() error {
if s.stopDbUpgrade != nil {
s.stopDbUpgrade()
}
@@ -457,7 +460,7 @@ func (s *FullNodeService) Stop() error {
}
// This function will wait for a shutdown and resumes main thread execution
-func (s *FullNodeService) WaitForShutdown() {
+func (s *Ethereum) WaitForShutdown() {
<-s.shutdownChan
}
@@ -470,7 +473,7 @@ func (s *FullNodeService) WaitForShutdown() {
// stop any number of times.
// For any more sophisticated pattern of DAG generation, use CLI subcommand
// makedag
-func (self *FullNodeService) StartAutoDAG() {
+func (self *Ethereum) StartAutoDAG() {
if self.autodagquit != nil {
return // already started
}
@@ -516,7 +519,7 @@ func (self *FullNodeService) StartAutoDAG() {
}
// stopAutoDAG stops automatic DAG pregeneration by quitting the loop
-func (self *FullNodeService) StopAutoDAG() {
+func (self *Ethereum) StopAutoDAG() {
if self.autodagquit != nil {
close(self.autodagquit)
self.autodagquit = nil
@@ -526,7 +529,7 @@ func (self *FullNodeService) StopAutoDAG() {
// HTTPClient returns the light http client used for fetching offchain docs
// (natspec, source for verification)
-func (self *FullNodeService) HTTPClient() *httpclient.HTTPClient {
+func (self *Ethereum) HTTPClient() *httpclient.HTTPClient {
return self.httpclient
}
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/cpu_mining.go b/src/vendor/github.com/ethereum/go-ethereum/eth/cpu_mining.go
index 143b9c98a..3469d394e 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/cpu_mining.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/cpu_mining.go
@@ -28,7 +28,7 @@ import (
const disabledInfo = "Set GO_OPENCL and re-build to enable."
-func (s *FullNodeService) StartMining(threads int, gpus string) error {
+func (s *Ethereum) StartMining(threads int, gpus string) error {
eb, err := s.Etherbase()
if err != nil {
err = fmt.Errorf("Cannot start mining without etherbase address: %v", err)
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/downloader/downloader.go b/src/vendor/github.com/ethereum/go-ethereum/eth/downloader/downloader.go
index 6e2680c32..baf6688a6 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/downloader/downloader.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/downloader/downloader.go
@@ -1874,7 +1874,7 @@ func (d *Downloader) processContent() error {
}
if err != nil {
glog.V(logger.Debug).Infof("Result #%d [%x…] processing failed: %v", results[index].Header.Number, results[index].Header.Hash().Bytes()[:4], err)
- return err
+ return errInvalidChain
}
// Shift the results to the next batch
results = results[items:]
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/filters/filter.go b/src/vendor/github.com/ethereum/go-ethereum/eth/filters/filter.go
index b781c6545..f44484e26 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/filters/filter.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/filters/filter.go
@@ -80,7 +80,8 @@ func (self *Filter) SetTopics(topics [][]common.Hash) {
// Run filters logs with the current parameters set
func (self *Filter) Find(ctx context.Context) (vm.Logs, error) {
- headBlockNumber := self.apiBackend.HeaderByNumber(rpc.LatestBlockNumber).Number.Uint64()
+ head, _ := self.apiBackend.HeaderByNumber(ctx, rpc.LatestBlockNumber)
+ headBlockNumber := head.Number.Uint64()
var beginBlockNo uint64 = uint64(self.begin)
if self.begin == -1 {
@@ -132,9 +133,9 @@ func (self *Filter) Find(ctx context.Context) (vm.Logs, error) {
func (self *Filter) getLogs(ctx context.Context, start, end uint64) (logs vm.Logs, err error) {
for i := start; i <= end; i++ {
- header := self.apiBackend.HeaderByNumber(rpc.BlockNumber(i))
- if header == nil {
- return logs, nil
+ header, err := self.apiBackend.HeaderByNumber(ctx, rpc.BlockNumber(i))
+ if header == nil || err != nil {
+ return logs, err
}
// Use bloom filtering to see if this block is interesting given the
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/gasprice/lightprice.go b/src/vendor/github.com/ethereum/go-ethereum/eth/gasprice/lightprice.go
index 5b420bc9d..ce075ff4e 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/gasprice/lightprice.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/gasprice/lightprice.go
@@ -60,7 +60,7 @@ func (self *LightPriceOracle) SuggestPrice(ctx context.Context) (*big.Int, error
lastPrice := self.lastPrice
self.cacheLock.RUnlock()
- head := self.backend.HeaderByNumber(rpc.LatestBlockNumber)
+ head, _ := self.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber)
headHash := head.Hash()
if headHash == lastHead {
return lastPrice, nil
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/gpu_mining.go b/src/vendor/github.com/ethereum/go-ethereum/eth/gpu_mining.go
index 0208bba80..12fa74601 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/gpu_mining.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/gpu_mining.go
@@ -33,7 +33,7 @@ import (
"github.com/ethereum/go-ethereum/miner"
)
-func (s *FullNodeService) StartMining(threads int, gpus string) error {
+func (s *Ethereum) StartMining(threads int, gpus string) error {
eb, err := s.Etherbase()
if err != nil {
err = fmt.Errorf("Cannot start mining without etherbase address: %v", err)
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/handler.go b/src/vendor/github.com/ethereum/go-ethereum/eth/handler.go
index 2caa2ab7d..cbc6dd228 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/handler.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/handler.go
@@ -45,6 +45,10 @@ const (
estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header
)
+var (
+ daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge
+)
+
// errIncompatibleConfig is returned if the requested protocols and configs are
// not compatible (low protocol version restrictions and high requirements).
var errIncompatibleConfig = errors.New("incompatible configuration")
@@ -62,9 +66,10 @@ type ProtocolManager struct {
fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks)
synced uint32 // Flag whether we're considered synchronised (enables transaction processing)
- txpool txPool
- blockchain *core.BlockChain
- chaindb ethdb.Database
+ txpool txPool
+ blockchain *core.BlockChain
+ chaindb ethdb.Database
+ chainconfig *core.ChainConfig
downloader *downloader.Downloader
fetcher *fetcher.Fetcher
@@ -99,6 +104,7 @@ func NewProtocolManager(config *core.ChainConfig, fastSync bool, networkId int,
txpool: txpool,
blockchain: blockchain,
chaindb: chaindb,
+ chainconfig: config,
peers: newPeerSet(),
newPeerCh: make(chan *peer),
noMorePeers: make(chan struct{}),
@@ -251,8 +257,8 @@ func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *p
func (pm *ProtocolManager) handle(p *peer) error {
if pm.peers.Len() >= 20 {
return p2p.DiscTooManyPeers
- }
-
+ }
+
glog.V(logger.Debug).Infof("%v: peer connected [%s]", p, p.Name())
// Execute the Ethereum handshake
@@ -282,6 +288,18 @@ func (pm *ProtocolManager) handle(p *peer) error {
// after this will be sent via broadcasts.
pm.syncTransactions(p)
+ // If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork
+ if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil {
+ // Request the peer's DAO fork header for extra-data validation
+ if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil {
+ return err
+ }
+ // Start a timer to disconnect if the peer doesn't reply in time
+ p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() {
+ glog.V(logger.Warn).Infof("%v: timed out DAO fork-check, dropping", p)
+ pm.removePeer(p.id)
+ })
+ }
// main loop. handle incoming messages.
for {
if err := pm.handleMsg(p); err != nil {
@@ -485,9 +503,43 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
if err := msg.Decode(&headers); err != nil {
return errResp(ErrDecode, "msg %v: %v", msg, err)
}
+ // If no headers were received, but we're expending a DAO fork check, maybe it's that
+ if len(headers) == 0 && p.forkDrop != nil {
+ // Possibly an empty reply to the fork header checks, sanity check TDs
+ verifyDAO := true
+
+ // If we already have a DAO header, we can check the peer's TD against it. If
+ // the peer's ahead of this, it too must have a reply to the DAO check
+ if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil {
+ if p.Td().Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 {
+ verifyDAO = false
+ }
+ }
+ // If we're seemingly on the same chain, disable the drop timer
+ if verifyDAO {
+ glog.V(logger.Debug).Infof("%v: seems to be on the same side of the DAO fork", p)
+ p.forkDrop.Stop()
+ p.forkDrop = nil
+ return nil
+ }
+ }
// Filter out any explicitly requested headers, deliver the rest to the downloader
filter := len(headers) == 1
if filter {
+ // If it's a potential DAO fork check, validate against the rules
+ if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 {
+ // Disable the fork drop timer
+ p.forkDrop.Stop()
+ p.forkDrop = nil
+
+ // Validate the header and either drop the peer or continue
+ if err := core.ValidateDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil {
+ glog.V(logger.Debug).Infof("%v: verified to be on the other side of the DAO fork, dropping", p)
+ return err
+ }
+ glog.V(logger.Debug).Infof("%v: verified to be on the same side of the DAO fork", p)
+ }
+ // Irrelevant of the fork checks, send the header to the fetcher just in case
headers = pm.fetcher.FilterHeaders(headers, time.Now())
}
if len(headers) > 0 || !filter {
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/peer.go b/src/vendor/github.com/ethereum/go-ethereum/eth/peer.go
index 8eb41b0f9..b97825c69 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/peer.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/peer.go
@@ -59,10 +59,12 @@ type peer struct {
*p2p.Peer
rw p2p.MsgReadWriter
- version int // Protocol version negotiated
- head common.Hash
- td *big.Int
- lock sync.RWMutex
+ version int // Protocol version negotiated
+ forkDrop *time.Timer // Timed connection dropper if forks aren't validated in time
+
+ head common.Hash
+ td *big.Int
+ lock sync.RWMutex
knownTxs *set.Set // Set of transaction hashes known to be known by this peer
knownBlocks *set.Set // Set of block hashes known to be known by this peer
diff --git a/src/vendor/github.com/ethereum/go-ethereum/eth/protocol.go b/src/vendor/github.com/ethereum/go-ethereum/eth/protocol.go
index 808ac0601..7de0cb020 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/eth/protocol.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/eth/protocol.go
@@ -37,10 +37,10 @@ const (
var ProtocolName = "eth"
// Supported versions of the eth protocol (first is primary).
-var ProtocolVersions = []uint{eth63, eth62, eth61}
+var ProtocolVersions = []uint{eth63, eth62}
// Number of implemented message corresponding to different protocol versions.
-var ProtocolLengths = []uint64{17, 8, 9}
+var ProtocolLengths = []uint64{17, 8}
const (
NetworkId = 1
diff --git a/src/vendor/github.com/ethereum/go-ethereum/ethdb/.gitignore b/src/vendor/github.com/ethereum/go-ethereum/ethdb/.gitignore
deleted file mode 100644
index f725d58d1..000000000
--- a/src/vendor/github.com/ethereum/go-ethereum/ethdb/.gitignore
+++ /dev/null
@@ -1,12 +0,0 @@
-# See http://help.github.com/ignore-files/ for more about ignoring files.
-#
-# If you find yourself ignoring temporary files generated by your text editor
-# or operating system, you probably want to add a global ignore instead:
-# git config --global core.excludesfile ~/.gitignore_global
-
-/tmp
-*/**/*un~
-*un~
-.DS_Store
-*/**/.DS_Store
-
diff --git a/src/vendor/github.com/ethereum/go-ethereum/ethdb/database.go b/src/vendor/github.com/ethereum/go-ethereum/ethdb/database.go
index 83b689631..a8c02b731 100644
--- a/src/vendor/github.com/ethereum/go-ethereum/ethdb/database.go
+++ b/src/vendor/github.com/ethereum/go-ethereum/ethdb/database.go
@@ -36,7 +36,7 @@ import (
var OpenFileLimit = 64
-// cacheRatio specifies how the total alloted cache is distributed between the
+// cacheRatio specifies how the total allotted cache is distributed between the
// various system databases.
var cacheRatio = map[string]float64{
"dapp": 0.0,
@@ -44,7 +44,7 @@ var cacheRatio = map[string]float64{
"lightchaindata": 1.0,
}
-// handleRatio specifies how the total alloted file descriptors is distributed
+// handleRatio specifies how the total allotted file descriptors is distributed
// between the various system databases.
var handleRatio = map[string]float64{
"dapp": 0.0,
@@ -81,7 +81,7 @@ func NewLDBDatabase(file string, cache int, handles int) (*LDBDatabase, error) {
if handles < 16 {
handles = 16
}
- glog.V(logger.Info).Infof("Alloted %dMB cache and %d file handles to %s", cache, handles, file)
+ glog.V(logger.Info).Infof("Allotted %dMB cache and %d file handles to %s", cache, handles, file)
// Open the db and recover any potential corruptions
db, err := leveldb.OpenFile(file, &opt.Options{
diff --git a/src/vendor/github.com/ethereum/go-ethereum/flags.dif b/src/vendor/github.com/ethereum/go-ethereum/flags.dif
new file mode 100644
index 000000000..7912b1a4c
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/flags.dif
@@ -0,0 +1,44 @@
+diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go
+index fc58447..e9d9ef1 100644
+--- a/cmd/utils/flags.go
++++ b/cmd/utils/flags.go
+@@ -39,6 +39,7 @@ import (
+ "github.com/ethereum/go-ethereum/eth"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/event"
++ "github.com/ethereum/go-ethereum/internal/debug"
+ "github.com/ethereum/go-ethereum/les"
+ "github.com/ethereum/go-ethereum/light"
+ "github.com/ethereum/go-ethereum/logger"
+@@ -160,7 +161,7 @@ var (
+ Usage: "Enable light client mode",
+ }
+ NoDefSrvFlag = cli.BoolFlag{
+- Name: "nodefsrv",
++ Name: "nodefsrv",
+ Usage: "Don't add default LES server (only for test version)",
+ }
+ LightServFlag = cli.IntFlag{
+@@ -419,6 +420,13 @@ var (
+ }
+ )
+
++// DebugSetup sets up the debugging parameters such that logs can be retrieved when a
++// node is started via importing go-ethereum packages, as opposed to starting via CLI
++func DebugSetup(ctx *cli.Context) error {
++ err := debug.Setup(ctx)
++ return err
++}
++
+ // MustMakeDataDir retrieves the currently requested data directory, terminating
+ // if none (or the empty string) is specified. If the node is starting a testnet,
+ // the a subdirectory of the specified datadir will be used.
+@@ -669,7 +677,7 @@ func MakeSystemNode(name, version string, relconf release.Config, extra []byte,
+ DataDir: MustMakeDataDir(ctx),
+ PrivateKey: MakeNodeKey(ctx),
+ Name: MakeNodeName(name, version, ctx),
+- NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name), // light client hack
++ NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name) || ctx.GlobalBool(LightModeFlag.Name), // light client hack
+ BootstrapNodes: MakeBootstrapNodes(ctx),
+ ListenAddr: MakeListenAddress(ctx),
+ NAT: MakeNAT(ctx),
diff --git a/src/vendor/github.com/ethereum/go-ethereum/generators/defaults.go b/src/vendor/github.com/ethereum/go-ethereum/generators/defaults.go
new file mode 100644
index 000000000..107e13e67
--- /dev/null
+++ b/src/vendor/github.com/ethereum/go-ethereum/generators/defaults.go
@@ -0,0 +1,81 @@
+// Copyright 2015 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// The go-ethereum library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public License
+// along with the go-ethereum library. If not, see .
+
+//go:generate go run defaults.go default.json defs.go
+
+package main //build !none
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+func fatalf(str string, v ...interface{}) {
+ fmt.Fprintf(os.Stderr, str, v...)
+ os.Exit(1)
+}
+
+type setting struct {
+ Value int64 `json:"v"`
+ Comment string `json:"d"`
+}
+
+func main() {
+ if len(os.Args) < 3 {
+ fatalf("usage %s