This commit is contained in:
Péter Szilágyi 2016-03-18 16:07:16 +00:00
commit d5437ae5a5
12 changed files with 1170 additions and 42 deletions

View file

@ -26,11 +26,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
) )
// Executer is an executer method for performing state executions. It takes one
// argument which is the input data and expects output data to be returned as
// multiple 32 byte word length concatenated slice
type Executer func(datain []byte) []byte
// The ABI holds information about a contract's context and available // The ABI holds information about a contract's context and available
// invokable methods. It will allow you to type check function calls and // invokable methods. It will allow you to type check function calls and
// packs data accordingly. // packs data accordingly.
@ -169,21 +164,6 @@ func toGoType(i int, t Argument, output []byte) (interface{}, error) {
return nil, fmt.Errorf("abi: unknown type %v", t.Type.T) return nil, fmt.Errorf("abi: unknown type %v", t.Type.T)
} }
// Call will unmarshal the output of the call in v. It will return an error if
// invalid type is given or if the output is too short to conform to the ABI
// spec.
//
// Call supports all of the available types and accepts a struct or an interface
// slice if the return is a tuple.
func (abi ABI) Call(executer Executer, v interface{}, name string, args ...interface{}) error {
callData, err := abi.Pack(name, args...)
if err != nil {
return err
}
return abi.unmarshal(v, name, executer(callData))
}
// these variable are used to determine certain types during type assertion for // these variable are used to determine certain types during type assertion for
// assignment. // assignment.
var ( var (
@ -193,8 +173,8 @@ var (
r_byte = reflect.TypeOf(byte(0)) r_byte = reflect.TypeOf(byte(0))
) )
// unmarshal output in v according to the abi specification // Unpack output in v according to the abi specification
func (abi ABI) unmarshal(v interface{}, name string, output []byte) error { func (abi ABI) Unpack(v interface{}, name string, output []byte) error {
var method = abi.Methods[name] var method = abi.Methods[name]
if len(output) == 0 { if len(output) == 0 {

View file

@ -579,7 +579,7 @@ func TestMultiReturnWithStruct(t *testing.T) {
Int *big.Int Int *big.Int
String string String string
} }
err = abi.unmarshal(&inter, "multi", buff.Bytes()) err = abi.Unpack(&inter, "multi", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -597,7 +597,7 @@ func TestMultiReturnWithStruct(t *testing.T) {
Int *big.Int Int *big.Int
} }
err = abi.unmarshal(&reversed, "multi", buff.Bytes()) err = abi.Unpack(&reversed, "multi", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -629,7 +629,7 @@ func TestMultiReturnWithSlice(t *testing.T) {
buff.Write(common.RightPadBytes([]byte(stringOut), 32)) buff.Write(common.RightPadBytes([]byte(stringOut), 32))
var inter []interface{} var inter []interface{}
err = abi.unmarshal(&inter, "multi", buff.Bytes()) err = abi.Unpack(&inter, "multi", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -661,13 +661,13 @@ func TestMarshalArrays(t *testing.T) {
output := common.LeftPadBytes([]byte{1}, 32) output := common.LeftPadBytes([]byte{1}, 32)
var bytes10 [10]byte var bytes10 [10]byte
err = abi.unmarshal(&bytes10, "bytes32", output) err = abi.Unpack(&bytes10, "bytes32", output)
if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" { if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
t.Error("expected error or bytes32 not be assignable to bytes10:", err) t.Error("expected error or bytes32 not be assignable to bytes10:", err)
} }
var bytes32 [32]byte var bytes32 [32]byte
err = abi.unmarshal(&bytes32, "bytes32", output) err = abi.Unpack(&bytes32, "bytes32", output)
if err != nil { if err != nil {
t.Error("didn't expect error:", err) t.Error("didn't expect error:", err)
} }
@ -681,13 +681,13 @@ func TestMarshalArrays(t *testing.T) {
) )
var b10 B10 var b10 B10
err = abi.unmarshal(&b10, "bytes32", output) err = abi.Unpack(&b10, "bytes32", output)
if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" { if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
t.Error("expected error or bytes32 not be assignable to bytes10:", err) t.Error("expected error or bytes32 not be assignable to bytes10:", err)
} }
var b32 B32 var b32 B32
err = abi.unmarshal(&b32, "bytes32", output) err = abi.Unpack(&b32, "bytes32", output)
if err != nil { if err != nil {
t.Error("didn't expect error:", err) t.Error("didn't expect error:", err)
} }
@ -697,7 +697,7 @@ func TestMarshalArrays(t *testing.T) {
output[10] = 1 output[10] = 1
var shortAssignLong [32]byte var shortAssignLong [32]byte
err = abi.unmarshal(&shortAssignLong, "bytes10", output) err = abi.Unpack(&shortAssignLong, "bytes10", output)
if err != nil { if err != nil {
t.Error("didn't expect error:", err) t.Error("didn't expect error:", err)
} }
@ -722,7 +722,7 @@ func TestUnmarshal(t *testing.T) {
// marshal int // marshal int
var Int *big.Int var Int *big.Int
err = abi.unmarshal(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -733,7 +733,7 @@ func TestUnmarshal(t *testing.T) {
// marshal bool // marshal bool
var Bool bool var Bool bool
err = abi.unmarshal(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -750,7 +750,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(bytesOut) buff.Write(bytesOut)
var Bytes []byte var Bytes []byte
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes()) err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -766,7 +766,7 @@ func TestUnmarshal(t *testing.T) {
bytesOut = common.RightPadBytes([]byte("hello"), 64) bytesOut = common.RightPadBytes([]byte("hello"), 64)
buff.Write(bytesOut) buff.Write(bytesOut)
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes()) err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -782,7 +782,7 @@ func TestUnmarshal(t *testing.T) {
bytesOut = common.RightPadBytes([]byte("hello"), 63) bytesOut = common.RightPadBytes([]byte("hello"), 63)
buff.Write(bytesOut) buff.Write(bytesOut)
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes()) err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -792,7 +792,7 @@ func TestUnmarshal(t *testing.T) {
} }
// marshal dynamic bytes output empty // marshal dynamic bytes output empty
err = abi.unmarshal(&Bytes, "bytes", nil) err = abi.Unpack(&Bytes, "bytes", nil)
if err == nil { if err == nil {
t.Error("expected error") t.Error("expected error")
} }
@ -803,7 +803,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
buff.Write(common.RightPadBytes([]byte("hello"), 32)) buff.Write(common.RightPadBytes([]byte("hello"), 32))
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes()) err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -817,7 +817,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(common.RightPadBytes([]byte("hello"), 32)) buff.Write(common.RightPadBytes([]byte("hello"), 32))
var hash common.Hash var hash common.Hash
err = abi.unmarshal(&hash, "fixed", buff.Bytes()) err = abi.Unpack(&hash, "fixed", buff.Bytes())
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -830,12 +830,12 @@ func TestUnmarshal(t *testing.T) {
// marshal error // marshal error
buff.Reset() buff.Reset()
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes()) err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
if err == nil { if err == nil {
t.Error("expected error") t.Error("expected error")
} }
err = abi.unmarshal(&Bytes, "multi", make([]byte, 64)) err = abi.Unpack(&Bytes, "multi", make([]byte, 64))
if err == nil { if err == nil {
t.Error("expected error") t.Error("expected error")
} }
@ -850,7 +850,7 @@ func TestUnmarshal(t *testing.T) {
buff.Write(bytesOut) buff.Write(bytesOut)
var out []interface{} var out []interface{}
err = abi.unmarshal(&out, "mixedBytes", buff.Bytes()) err = abi.Unpack(&out, "mixedBytes", buff.Bytes())
if err != nil { if err != nil {
t.Fatal("didn't expect error:", err) t.Fatal("didn't expect error:", err)
} }

View file

@ -0,0 +1,231 @@
// 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 <http://www.gnu.org/licenses/>.
package bind
import (
"encoding/json"
"fmt"
"math/big"
"sync"
"sync/atomic"
"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"
)
// ContractCaller defines the methods needed to allow operating with contract on a read
// only basis.
type ContractCaller interface {
// ContractCall executes an Ethereum contract call with the specified data as
// the input.
ContractCall(contract common.Address, data []byte) ([]byte, error)
}
// ContractTransactor defines the methods needed to allow operating with contract
// on a write only basis. Beside the transacting method, the remainder are helpers
// used when the user does not provide some needed values, but rather leaves it up
// to the transactor to decide.
type ContractTransactor interface {
// Nonce retrieves the current pending nonce associated with an account.
AccountNonce(account common.Address) (uint64, error)
// GasPrice retrieves the currently suggested gas price to allow a timely execution
// of a transaction.
GasPrice() (*big.Int, error)
// GasLimit tries to estimate the gas needed to execute a specific transaction.
GasLimit(sender, contract common.Address, value *big.Int, data []byte) (*big.Int, error)
// SendTransaction injects the transaction into the pending pool for execution.
SendTransaction(*types.Transaction) error
}
// ContractBackend defines the methods needed to allow operating with contract
// on a read-write basis.
type ContractBackend interface {
ContractCaller
ContractTransactor
}
// 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) 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 json.RawMessage `json:"error"` // Any error returned by the remote side
Result json.RawMessage `json:"result"` // Whatever the remote side sends us in reply
}
// 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 (backend *rpcBackend) request(method string, params []interface{}) (json.RawMessage, error) {
backend.lock.Lock()
defer backend.lock.Unlock()
// Ugly hack to serialize an empty list properly
if params == nil {
params = []interface{}{}
}
// Assemble the request object
req := &request{
JsonRpc: "2.0",
Id: int(atomic.AddUint32(&backend.autoid, 1)),
Method: method,
Params: params,
}
if err := backend.client.Send(req); err != nil {
return nil, err
}
res := new(response)
if err := backend.client.Recv(res); err != nil {
return nil, err
}
if len(res.Error) > 0 {
return nil, fmt.Errorf("remote error: %s", string(res.Error))
}
return res.Result, 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(contract common.Address, data []byte) ([]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
res, err := b.request("eth_call", []interface{}{args, "pending"})
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
}
// AccountNonce implements ContractTransactor.AccountNonce, delegating the
// current account nonce retrieval to the remote node.
func (b *rpcBackend) AccountNonce(account common.Address) (uint64, error) {
res, err := b.request("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
}
return new(big.Int).SetBytes(common.FromHex(hex)).Uint64(), nil
}
// GasPrice implements ContractTransactor.GasPrice, delegating the gas price
// oracle request to the remote node.
func (b *rpcBackend) GasPrice() (*big.Int, error) {
res, err := b.request("eth_gasPrice", nil)
if err != nil {
return nil, err
}
var hex string
if err := json.Unmarshal(res, &hex); err != nil {
return nil, err
}
return new(big.Int).SetBytes(common.FromHex(hex)), nil
}
// GasLimit implements ContractTransactor.GasLimit, delegating the gas estimation
// to the remote node.
func (b *rpcBackend) GasLimit(sender, 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("eth_estimateGas", []interface{}{args, "pending"})
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 new(big.Int).SetBytes(common.FromHex(hex)), nil
}
// Transact implements ContractTransactor.SendTransaction, delegating the raw
// transaction injection to the remote node.
func (b *rpcBackend) SendTransaction(tx *types.Transaction) error {
data, err := rlp.EncodeToBytes(tx)
if err != nil {
return err
}
res, err := b.request("eth_sendRawTransaction", []interface{}{data})
if err != nil {
return err
}
var hex string
if err := json.Unmarshal(res, &hex); err != nil {
return err
}
return nil
}

130
accounts/abi/bind/base.go Normal file
View file

@ -0,0 +1,130 @@
// 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 <http://www.gnu.org/licenses/>.
package bind
import (
"errors"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
// SignerFn is a signer function callback when a contract requires a method to
// sign the transaction before submission.
type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
// AuthOpts is the authorization data required to create a valid Ethereum transaction.
type AuthOpts struct {
Account common.Address // Ethereum account to send the transaction from
Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state)
Signer SignerFn // Method to use for signing the transaction (mandatory)
Value *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds)
GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
GasLimit *big.Int // Gas limit to set for the transaction execution (nil = estimate + 10%)
}
// BoundContract is the base wrapper object that reflects a contract on the
// Ethereum network. It contains a collection of methods that are used by the
// higher level contract bindings to operate.
type BoundContract struct {
address common.Address // Deployment address of the contract on the Ethereum blockchain
abi abi.ABI // Reflect based ABI to access the correct Ethereum methods
caller ContractCaller // Read interface to interact with the blockchain
transactor ContractTransactor // Write interface to interact with the blockchain
}
// NewBoundContract creates a low level contract interface through which calls
// and transactions may be made through.
func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor) *BoundContract {
return &BoundContract{
address: address,
abi: abi,
caller: caller,
transactor: transactor,
}
}
// Call invokes the (constant) contract method with params as input values and
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
func (c *BoundContract) Call(result interface{}, method string, params ...interface{}) error {
input, err := c.abi.Pack(method, params...)
if err != nil {
return err
}
output, err := c.caller.ContractCall(c.address, input)
if err != nil {
return err
}
return c.abi.Unpack(result, method, output)
}
// Transact invokes the (paid) contract method with params as input values and
// value as the fund transfer to the contract.
func (c *BoundContract) Transact(opts *AuthOpts, method string, params ...interface{}) (*types.Transaction, error) {
input, err := c.abi.Pack(method, params...)
if err != nil {
return nil, err
}
// Ensure a valid value field and resolve the account nonce
value := opts.Value
if value == nil {
value = new(big.Int)
}
nonce := uint64(0)
if opts.Nonce == nil {
nonce, err = c.transactor.AccountNonce(opts.Account)
if err != nil {
return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
}
} else {
nonce = opts.Nonce.Uint64()
}
// Figure out the gas allowance and gas price values
gasPrice := opts.GasPrice
if gasPrice == nil {
gasPrice, err = c.transactor.GasPrice()
if err != nil {
return nil, fmt.Errorf("failed to suggest gas price: %v", err)
}
}
gasLimit := opts.GasLimit
if gasLimit == nil {
gasLimit, err = c.transactor.GasLimit(opts.Account, c.address, value, input)
if err != nil {
return nil, fmt.Errorf("failed to exstimate gas needed: %v", err)
}
}
// Create the transaction, sign it and schedule it for execution
rawTx := types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
if opts.Signer == nil {
return nil, errors.New("no signer to authorize the transaction with")
}
signedTx, err := opts.Signer(opts.Account, rawTx)
if err != nil {
return nil, err
}
if err := c.transactor.SendTransaction(signedTx); err != nil {
return nil, err
}
return signedTx, nil
}

318
accounts/abi/bind/bind.go Normal file
View file

@ -0,0 +1,318 @@
// 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 <http://www.gnu.org/licenses/>.
// Package bind generates Ethereum contract Go bindings.
package bind
import (
"bytes"
"fmt"
"sort"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi"
"golang.org/x/tools/imports"
)
// Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant
// to be used as is in client code, but rather as an intermediate struct which
// enforces compile time type safety and naming convention opposed to having to
// manually maintain hard coded strings that break on runtime.
func Bind(jsonABI string, pkg string, kind string) (string, error) {
// Parse the actual ABI to generate the binding for
abi, err := abi.JSON(strings.NewReader(jsonABI))
if err != nil {
return "", err
}
// Generate the contract type, fields and methods
code := new(bytes.Buffer)
kind = strings.ToUpper(kind[:1]) + kind[1:]
fmt.Fprintf(code, "%s\n", bindContract(kind, jsonABI))
methods := make([]string, 0, len(abi.Methods))
for name, _ := range abi.Methods {
methods = append(methods, name)
}
sort.Strings(methods)
for _, method := range methods {
fmt.Fprintf(code, "%s\n", bindMethod(kind, abi.Methods[method]))
}
// Format the code with goimports and return
buffer := new(bytes.Buffer)
fmt.Fprintf(buffer, "package %s\n\n", pkg)
fmt.Fprintf(buffer, "%s\n\n", string(code.Bytes()))
blob, err := imports.Process("", buffer.Bytes(), nil)
if err != nil {
fmt.Println(string(buffer.Bytes()))
return "", err
}
return string(blob), nil
}
// bindContract generates the basic wrapper code for interacting with an Ethereum
// contract via the abi package. All contract methods will call into the generic
// ones generated here.
func bindContract(kind string, abi string) string {
code := ""
// Generate the hard coded ABI used for Ethereum interaction
code += fmt.Sprintf("// Ethereum ABI used to generate the binding from.\nconst %sABI = `%s`\n\n", kind, strings.TrimSpace(abi))
// Generate the Go struct with all the maintenance fields
code += fmt.Sprintf("// %s is an auto generated Go binding around an Ethereum contract.\n", kind)
code += fmt.Sprintf("type %s struct {\n", kind)
code += fmt.Sprintf(" %sCaller // Read-only binding to the contract\n", kind)
code += fmt.Sprintf(" %sTransactor // Write-only binding to the contract\n", kind)
code += fmt.Sprintf("}\n\n")
code += fmt.Sprintf("// %sCaller is an auto generated read-only Go binding around an Ethereum contract.\n", kind)
code += fmt.Sprintf("type %sCaller struct {\n", kind)
code += fmt.Sprintf(" common *common%s // Contract binding common to callers and transactors\n", kind)
code += fmt.Sprintf("}\n\n")
code += fmt.Sprintf("// %sTransactor is an auto generated write-only Go binding around an Ethereum contract.\n", kind)
code += fmt.Sprintf("type %sTransactor struct {\n", kind)
code += fmt.Sprintf(" common *common%s // Contract binding common to callers and transactors\n", kind)
code += fmt.Sprintf("}\n\n")
code += fmt.Sprintf("// common%s is an auto generated Go binding around an Ethereum contract.\n", kind)
code += fmt.Sprintf("type common%s struct {\n", kind)
code += fmt.Sprintf(" contract *bind.BoundContract // Generic contract wrapper for the low level calls\n")
code += fmt.Sprintf("}\n\n")
// Generate the constructor to create a bound contract
code += fmt.Sprintf("// New%s creates a new instance of %s, bound to a specific deployed contract.\n", kind, kind)
code += fmt.Sprintf("func New%s(address common.Address, backend bind.ContractBackend) (*%s, error) {\n", kind, kind)
code += fmt.Sprintf(" common, err := newCommon%s(address, backend.(bind.ContractCaller), backend.(bind.ContractTransactor))\n", kind)
code += fmt.Sprintf(" if err != nil {\n")
code += fmt.Sprintf(" return nil, err\n")
code += fmt.Sprintf(" }\n")
code += fmt.Sprintf(" return &%s{%sCaller: %sCaller{common: common}, %sTransactor: %sTransactor{common: common}}, nil\n", kind, kind, kind, kind, kind)
code += fmt.Sprintf("}\n\n")
code += fmt.Sprintf("// New%sCaller creates a new read-only instance of %s, bound to a specific deployed contract.\n", kind, kind)
code += fmt.Sprintf("func New%sCaller(address common.Address, caller bind.ContractCaller) (*%sCaller, error) {\n", kind, kind)
code += fmt.Sprintf(" common, err := newCommon%s(address, caller, nil)\n", kind)
code += fmt.Sprintf(" if err != nil {\n")
code += fmt.Sprintf(" return nil, err\n")
code += fmt.Sprintf(" }\n")
code += fmt.Sprintf(" return &%sCaller{common: common}, nil\n", kind)
code += fmt.Sprintf("}\n\n")
code += fmt.Sprintf("// New%sTransactor creates a new write-only instance of %s, bound to a specific deployed contract.\n", kind, kind)
code += fmt.Sprintf("func New%sTransactor(address common.Address, transactor bind.ContractTransactor) (*%sTransactor, error) {\n", kind, kind)
code += fmt.Sprintf(" common, err := newCommon%s(address, nil, transactor)\n", kind)
code += fmt.Sprintf(" if err != nil {\n")
code += fmt.Sprintf(" return nil, err\n")
code += fmt.Sprintf(" }\n")
code += fmt.Sprintf(" return &%sTransactor{common: common}, nil\n", kind)
code += fmt.Sprintf("}\n\n")
code += fmt.Sprintf("// newCommon%s creates an internal instance of %s, bound to a specific deployed contract.\n", kind, kind)
code += fmt.Sprintf("func newCommon%s(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor) (*common%s, error) {\n", kind, kind)
code += fmt.Sprintf(" parsed, err := abi.JSON(strings.NewReader(%sABI))\n", kind)
code += fmt.Sprintf(" if err != nil {\n")
code += fmt.Sprintf(" return nil, err\n")
code += fmt.Sprintf(" }\n")
code += fmt.Sprintf(" return &common%s{\n", kind)
code += fmt.Sprintf(" contract: bind.NewBoundContract(address, parsed, caller, transactor),\n")
code += fmt.Sprintf(" }, nil\n")
code += fmt.Sprintf("}")
return code
}
// bindMethod
func bindMethod(kind string, method abi.Method) string {
var (
name = strings.ToUpper(method.Name[:1]) + method.Name[1:]
prologue = new(bytes.Buffer)
)
// Generate the argument and return list for the function
args := make([]string, 0, len(method.Inputs))
for i, arg := range method.Inputs {
param := arg.Name
if param == "" {
param = fmt.Sprintf("arg%d", i)
}
args = append(args, fmt.Sprintf("%s %s", param, bindType(arg.Type)))
}
returns, _ := bindReturn(prologue, name, method.Outputs)
// Generate the docs to help with coding against the binding
callTypeDoc := "free data retrieval call"
if !method.Const {
callTypeDoc = "paid mutator transaction"
}
docs := fmt.Sprintf("// %s is a %s binding the contract method 0x%x.\n", name, callTypeDoc, method.Id())
docs += fmt.Sprintf("// \n")
docs += fmt.Sprintf("// Solidity: %s", strings.TrimPrefix(method.String(), "function "))
// Generate the method itself for both the read/write version and the combo too
code := fmt.Sprintf("%s\n", prologue)
if method.Const {
code += fmt.Sprintf("%s\nfunc (_%s *%sCaller) %s(%s) (%s) {\n%s\n}\n", docs, kind, kind, name, strings.Join(args, ","), strings.Join(returns, ","), bindCallBody(kind, method.Name, args, returns))
} else {
args = append([]string{"auth *bind.AuthOpts"}, args...)
code += fmt.Sprintf("%s\nfunc (_%s *%sTransactor) %s(%s) (*types.Transaction, error) {\n%s\n}\n", docs, kind, kind, name, strings.Join(args, ","), bindTransactionBody(kind, method.Name, args))
}
return code
}
// bindType converts a Solidity type to a Go one. Since there is no clear mapping
// from all Solidity types to Go ones (e.g. uint17), those that cannot be exactly
// mapped will use an upscaled type (e.g. *big.Int).
func bindType(kind abi.Type) string {
stringKind := kind.String()
switch {
case stringKind == "address":
return "common.Address"
case stringKind == "hash":
return "common.Hash"
case strings.HasPrefix(stringKind, "bytes"):
if stringKind == "bytes" {
return "[]byte"
}
return fmt.Sprintf("[%s]byte", stringKind[5:])
case strings.HasPrefix(stringKind, "int"):
switch stringKind[:3] {
case "8", "16", "32", "64":
return stringKind
}
return "*big.Int"
case strings.HasPrefix(stringKind, "uint"):
switch stringKind[:4] {
case "8", "16", "32", "64":
return stringKind
}
return "*big.Int"
default:
return stringKind
}
}
// bindReturn creates the list of return parameters for a method invocation. If
// all the fields of the return type are named, and there is more than one value
// being returned, the returns are wrapped in a result struct.
func bindReturn(prologue *bytes.Buffer, method string, outputs []abi.Argument) ([]string, string) {
// Generate the anonymous return list for when a struct is not needed/possible
var (
returns = make([]string, 0, len(outputs)+1)
anonymous = false
)
for _, ret := range outputs {
returns = append(returns, bindType(ret.Type))
if ret.Name == "" {
anonymous = true
}
}
if anonymous || len(returns) < 2 {
returns = append(returns, "error")
return returns, ""
}
// If the returns are named and numerous, wrap in a result struct
wrapper, impl := bindReturnStruct(method, outputs)
prologue.WriteString(impl + "\n")
return []string{"*" + wrapper, "error"}, wrapper
}
// bindReturnStruct creates a Go structure with the specified fields to be used
// as the return type from a method call.
func bindReturnStruct(method string, returns []abi.Argument) (string, string) {
fields := make([]string, 0, len(returns))
for _, ret := range returns {
fields = append(fields, fmt.Sprintf("%s %s", strings.ToUpper(ret.Name[:1])+ret.Name[1:], bindType(ret.Type)))
}
kind := fmt.Sprintf("%sResult", method)
docs := fmt.Sprintf("// %s is the result of the %s invocation.", kind, method)
return kind, fmt.Sprintf("%s\ntype %s struct {\n%s\n}", docs, kind, strings.Join(fields, "\n"))
}
// bindCallBody creates the Go code to declare a batch of return values, invoke
// an Ethereum method call with the requested parameters, parse the binary output
// into the return values and return them.
func bindCallBody(kind string, method string, params []string, returns []string) string {
body := ""
// Allocate memory for each of the return values
rets := make([]string, 0, len(returns)-1)
if len(returns) > 1 {
body += "var ("
for i, kind := range returns[:len(returns)-1] { // Omit the final error
name := fmt.Sprintf("ret%d", i)
rets = append(rets, name)
body += fmt.Sprintf("%s = new(%s)\n", name, strings.TrimPrefix(kind, "*"))
}
body += ")\n"
}
// Assemble a single collector variable for the result ABI initialization
result := strings.Join(rets, ",")
if len(returns) > 2 {
result = "[]interface{}{" + result + "}"
}
// Extract the parameter list into a flat variable name list
inputs := make([]string, len(params))
for i, param := range params {
inputs[i] = strings.Split(param, " ")[0]
}
input := ""
if len(inputs) > 0 {
input = "," + strings.Join(inputs, ",")
}
// Request executing the contract call and return the results with the errors
body += fmt.Sprintf("err := _%s.common.contract.Call(%s, \"%s\" %s)\n", kind, result, method, input)
outs := make([]string, 0, len(returns))
for i, ret := range returns[:len(returns)-1] { // Handle th final error separately
if strings.HasPrefix(ret, "*") {
outs = append(outs, rets[i])
} else {
outs = append(outs, "*"+rets[i])
}
}
outs = append(outs, "err")
body += fmt.Sprintf("return %s", strings.Join(outs, ","))
return body
}
// bindTransactionBody creates the Go code to invoke an Ethereum transaction call
// with the requested parameters, and return the assembled transaction object.
func bindTransactionBody(kind string, method string, params []string) string {
// Extract the parameter list into a flat variable name list
inputs := make([]string, len(params)-1) // Omit the auth options
for i, param := range params[1:] {
inputs[i] = strings.Split(param, " ")[0]
}
input := ""
if len(inputs) > 0 {
input = "," + strings.Join(inputs, ",")
}
// Request executing the contract call and return the results with the errors
return fmt.Sprintf("return _%s.common.contract.Transact(auth, \"%s\" %s)", kind, method, input)
}

View file

@ -0,0 +1,23 @@
// 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 <http://www.gnu.org/licenses/>.
package bind
/*
// Tests that packages generated by the binder can be successfully compiled.
func TestBindValidity(t *testing.T) {
}*/

71
cmd/abigen/main.go Normal file
View file

@ -0,0 +1,71 @@
// 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 <http://www.gnu.org/licenses/>.
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
)
var (
abiFlag = flag.String("abi", "", "Path to the Ethereum contract ABI json to bind")
pkgFlag = flag.String("pkg", "", "Go package name to generate the binding into")
typFlag = flag.String("type", "", "Go struct name for the binding (default = package name)")
outFlag = flag.String("out", "", "Output path for the generated binding")
)
func main() {
// Parse and validate the command line flags
flag.Parse()
if *abiFlag == "" {
fmt.Printf("No contract ABI path specified (--abi)\n")
os.Exit(-1)
}
if *pkgFlag == "" {
fmt.Printf("No destination Go package specified (--pkg)\n")
os.Exit(-1)
}
// Generate the contract binding
in, err := ioutil.ReadFile(*abiFlag)
if err != nil {
fmt.Printf("Failed to read input ABI: %v\n", err)
os.Exit(-1)
}
kind := *typFlag
if kind == "" {
kind = *pkgFlag
}
code, err := bind.Bind(string(in), *pkgFlag, kind)
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)
}
}

View file

@ -32,6 +32,7 @@ import (
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/versions"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
@ -749,6 +750,12 @@ func MakeSystemNode(name, version string, extra []byte, ctx *cli.Context) *node.
} }
} }
err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
return versions.NewVersionCheck(ctx)
})
if err != nil {
Fatalf("Failed to register the Version Check service: %v", err)
}
return stack return stack
} }

152
common/versions/version.sol Normal file
View file

@ -0,0 +1,152 @@
// 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 <http://www.gnu.org/licenses/>.
// WARNING: WORK IN PROGRESS & UNTESTED
//
// contract tracking versions added by designated signers.
// designed to track versions of geth (go-ethereum) recommended by the
// go-ethereum team. geth client interfaces with contract through ABI by simply
// reading the full state and then deciding on recommended version based on
// some logic (e.g. version date & number of signers).
//
// to keep things simple, the contract does not use FSM for multisig
// but rather allows any designated signer to add a version or vote for an
// existing version. this avoids need to track voting-in-progress states and
// also provides history of all past versions.
//
contract Versions {
struct V {
bytes32 v;
uint64 ts;
address[] signers;
}
address[] public parties; // owners/signers
address[] public deleteAcks; // votes to suicide contract
uint public deleteAcksReq; // number of votes needed
V[] public versions;
modifier canAccess(address addr) {
bool access = false;
for (uint i = 0; i < parties.length; i++) {
if (parties[i] == addr) {
access = true;
break;
}
}
if (access == false) {
throw;
}
_
}
function Versions(address[] addrs) {
if (addrs.length < 2) {
throw;
}
parties = addrs;
deleteAcksReq = (addrs.length / 2) + 1;
}
// TODO: use dynamic array when solidity adds proper support for returning them
function GetVersions() returns (bytes32[10], uint64[10], uint[10]) {
bytes32[10] memory vs;
uint64[10] memory ts;
uint[10] memory ss;
for (uint i = 0; i < versions.length; i++) {
vs[i] = versions[i].v;
ts[i] = versions[i].ts;
ss[i] = versions[i].signers.length;
}
return (vs, ts, ss);
}
// either submit a new version or acknowledge an existing one
function AckVersion(bytes32 ver)
canAccess(msg.sender)
{
for (uint i = 0; i < versions.length; i++) {
if (versions[i].v == ver) {
for (uint j = 0; j < versions[i].signers.length; j++) {
if (versions[i].signers[j] == msg.sender) {
// already signed
throw;
}
}
// add sender as signer of existing version
versions[i].signers.push(msg.sender);
return;
}
}
// version is new, add it
// due to dynamic array, push it first then set values
V memory v;
versions.push(v);
versions[versions.length - 1].v = ver;
// signers is dynamic array; have to extend size manually
versions[versions.length - 1].signers.length++;
versions[versions.length - 1].signers[0] = msg.sender;
versions[versions.length - 1].ts = uint64(block.timestamp);
}
// remove vote for a version, if present
function NackVersion(bytes32 ver)
canAccess(msg.sender)
{
for (uint i = 0; i < versions.length; i++) {
if (versions[i].v == ver) {
for (uint j = 0; j < versions[i].signers.length; j++) {
if (versions[i].signers[j] == msg.sender) {
delete versions[i].signers[j];
}
}
}
}
}
// delete-this-contract vote, suicide if enough votes
function AckDelete()
canAccess(msg.sender)
{
for (uint i = 0; i < deleteAcks.length; i++) {
if (deleteAcks[i] == msg.sender) {
throw; // already acked delete
}
}
deleteAcks.push(msg.sender);
if (deleteAcks.length >= deleteAcksReq) {
suicide(msg.sender);
}
}
// remove sender's delete-this-contract vote, if present
function NackDelete()
canAccess(msg.sender)
{
uint len = deleteAcks.length;
for (uint i = 0; i < len; i++) {
if (deleteAcks[i] == msg.sender) {
if (len > 1) {
deleteAcks[i] = deleteAcks[len-1];
}
deleteAcks.length -= 1;
}
}
}
}

215
common/versions/versions.go Normal file
View file

@ -0,0 +1,215 @@
// 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 <http://www.gnu.org/licenses/>.
package versions
import (
"fmt"
"math/big"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/rpc"
)
var (
jsonlogger = logger.NewJsonLogger()
// TODO: add Frontier address
GlobalVersionsAddr = common.HexToAddress("0x40bebcadbb4456db23fda39f261f3b2509096e9e") // test
dummySender = common.HexToAddress("0x16db48070243bc37a1c59cd5bb977ad7047618be") // test
getVersionsSignature = "GetVersions()"
firstCheckTime = time.Second * 4
continousCheckTime = time.Second * 600
)
type VersionCheck struct {
serverName string
timer *time.Timer
e *eth.Ethereum
stop chan bool
}
// Boilerplate to satisfy node.Service interface
func (v *VersionCheck) Protocols() []p2p.Protocol {
return []p2p.Protocol{}
}
func (v *VersionCheck) APIs() []rpc.API {
return []rpc.API{}
}
func (v *VersionCheck) Start(server *p2p.Server) error {
v.serverName = server.Name
// Check version first time after a few seconds so it shows after
// other startup messages
t := time.NewTimer(firstCheckTime)
v.timer = t
v.stop = make(chan bool)
versionCheck := func() {
for {
select {
case <-v.stop:
close(v.stop)
return
case <-v.timer.C:
_, err := get(v.e, v.serverName)
if err != nil {
glog.V(logger.Error).Infof("Could not query geth version contract: %s", err)
}
v.timer.Reset(continousCheckTime)
}
}
}
go versionCheck()
return nil
}
func (v *VersionCheck) Stop() error {
v.stop <- true
select {
case <-v.stop:
}
return nil
}
func NewVersionCheck(ctx *node.ServiceContext) (node.Service, error) {
var v VersionCheck
var e *eth.Ethereum
// sets e to the Ethereum instance previously started
// expects double pointer
ctx.Service(&e)
v.e = e
return &v, nil
}
// query versions list from the (custom) accessor in the versions contract
func get(e *eth.Ethereum, clientVersion string) (string, error) {
// TODO: move common/registrar abiSignature to some util package
abi := crypto.Sha3([]byte(getVersionsSignature))[:4]
res, _, err := simulateCall(
e,
&dummySender,
&GlobalVersionsAddr,
big.NewInt(3000000), // gasLimit
big.NewInt(1), // gasPrice
big.NewInt(0), // value
abi)
if err != nil {
return "", err
}
// TODO: we use static arrays of size versionCount as workaround
// until solidity has proper support for returning dynamic arrays
versionCount := 10
if len(res) != 2+(64*versionCount*3) { // 0x + three 32-byte fields per version
return "", fmt.Errorf("unexpected result length from GetVersions")
}
// TODO: use ABI (after solidity supports returning arrays of arrays and/or structs)
var versions []string
var timestamps []uint64
var signerCounts []uint64
// trim 0x
res = res[2:]
// parse res
for i := 0; i < versionCount; i++ {
bytes := common.FromHex(res[:64])
versions = append(versions, string(bytes))
res = res[64:]
}
for i := 0; i < versionCount; i++ {
ts, err := strconv.ParseUint(res[:64], 16, 64)
if err != nil {
return "", err
}
timestamps = append(timestamps, ts)
res = res[64:]
}
for i := 0; i < versionCount; i++ {
sc, err := strconv.ParseUint(res[:64], 16, 64)
if err != nil {
return "", err
}
signerCounts = append(signerCounts, sc)
res = res[64:]
}
// TODO: version matching logic (e.g. most votes / most recent)
if versions[0] != clientVersion {
glog.V(logger.Info).Infof("geth version %s does not match recommended version %s", clientVersion, versions[0])
}
return res, nil
}
func simulateCall(e *eth.Ethereum, from0, to *common.Address, gas, gasPrice, value *big.Int, data []byte) (string, *big.Int, error) {
stateCopy, err := e.BlockChain().State()
if err != nil {
return "", nil, err
}
from := stateCopy.GetOrNewStateObject(*from0)
from.SetBalance(common.MaxBig)
msg := callmsg{
from: from,
to: to,
gas: gas,
gasPrice: gasPrice,
value: value,
data: data,
}
// Execute the call and return
vmenv := core.NewEnv(stateCopy, e.BlockChain(), msg, e.BlockChain().CurrentHeader())
gp := new(core.GasPool).AddGas(common.MaxBig)
res, gas, err := core.ApplyMessage(vmenv, msg, gp)
return common.ToHex(res), gas, err
}
// TODO: consider moving to package common or accounts/abi as it's useful for anyone
// simulating EVM CALL
type callmsg struct {
from *state.StateObject
to *common.Address
gas, gasPrice *big.Int
value *big.Int
data []byte
}
// accessor boilerplate to implement core.Message
func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
func (m callmsg) Nonce() uint64 { return m.from.Nonce() }
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 }
func (m callmsg) Value() *big.Int { return m.value }
func (m callmsg) Data() []byte { return m.data }

View file

@ -688,7 +688,7 @@ func (s *PublicBlockChainAPI) Call(args CallArgs, blockNr rpc.BlockNumber) (stri
// EstimateGas returns an estimate of the amount of gas needed to execute the given transaction. // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
func (s *PublicBlockChainAPI) EstimateGas(args CallArgs) (*rpc.HexNumber, error) { func (s *PublicBlockChainAPI) EstimateGas(args CallArgs) (*rpc.HexNumber, error) {
_, gas, err := s.doCall(args, rpc.LatestBlockNumber) _, gas, err := s.doCall(args, rpc.PendingBlockNumber)
return rpc.NewHexNumber(gas), err return rpc.NewHexNumber(gas), err
} }

View file

@ -522,6 +522,7 @@ func (n *Node) Server() *p2p.Server {
} }
// Service retrieves a currently running service registered of a specific type. // Service retrieves a currently running service registered of a specific type.
// NOTE: must be called with double pointer to service
func (n *Node) Service(service interface{}) error { func (n *Node) Service(service interface{}) error {
n.lock.RLock() n.lock.RLock()
defer n.lock.RUnlock() defer n.lock.RUnlock()