Merge branch 'develop' into rpcargs

pull/579/head
Taylor Gerring 10 years ago
commit 0ac346f707
  1. 12
      README.md
  2. 8
      accounts/account_manager.go
  3. 5
      cmd/geth/admin.go
  4. 3
      cmd/geth/js.go
  5. 8
      cmd/geth/main.go
  6. 11
      cmd/utils/flags.go
  7. 27
      eth/backend.go
  8. 23
      rpc/api.go
  9. 69
      rpc/api_test.go
  10. 4
      rpc/http.go
  11. 137
      rpc/responses.go
  12. 123
      rpc/responses_test.go
  13. 14
      xeth/xeth.go

@ -20,7 +20,7 @@ Mist (GUI):
`go get github.com/ethereum/go-ethereum/cmd/mist` `go get github.com/ethereum/go-ethereum/cmd/mist`
Ethereum (CLI): Geth (CLI):
`go get github.com/ethereum/go-ethereum/cmd/ethereum` `go get github.com/ethereum/go-ethereum/cmd/ethereum`
@ -32,10 +32,10 @@ Mist (GUI):
godep go build -v ./cmd/mist godep go build -v ./cmd/mist
``` ```
Ethereum (CLI): Geth (CLI):
``` ```
godep go build -v ./cmd/ethereum godep go build -v ./cmd/geth
``` ```
Instead of `build`, you can use `install` which will also install the resulting binary. Instead of `build`, you can use `install` which will also install the resulting binary.
@ -61,7 +61,7 @@ Go Ethereum comes with several wrappers/executables found in
[the `cmd` directory](https://github.com/ethereum/go-ethereum/tree/develop/cmd): [the `cmd` directory](https://github.com/ethereum/go-ethereum/tree/develop/cmd):
* `mist` Official Ethereum Browser (ethereum GUI client) * `mist` Official Ethereum Browser (ethereum GUI client)
* `ethereum` Ethereum CLI (ethereum command line interface client) * `geth` Ethereum CLI (ethereum command line interface client)
* `bootnode` runs a bootstrap node for the Discovery Protocol * `bootnode` runs a bootstrap node for the Discovery Protocol
* `ethtest` test tool which runs with the [tests](https://github.com/ethereum/testes) suite: * `ethtest` test tool which runs with the [tests](https://github.com/ethereum/testes) suite:
`cat file | ethtest`. `cat file | ethtest`.
@ -73,12 +73,12 @@ Go Ethereum comes with several wrappers/executables found in
Command line options Command line options
============================ ============================
Both `mist` and `ethereum` can be configured via command line options, environment variables and config files. Both `mist` and `geth` can be configured via command line options, environment variables and config files.
To get the options available: To get the options available:
``` ```
ethereum -help geth -help
``` ```
For further details on options, see the [wiki](https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options) For further details on options, see the [wiki](https://github.com/ethereum/go-ethereum/wiki/Command-Line-Options)

@ -81,13 +81,7 @@ func (am *Manager) HasAccount(addr []byte) bool {
return false return false
} }
// Coinbase returns the account address that mining rewards are sent to. func (am *Manager) Primary() (addr []byte, err error) {
func (am *Manager) Coinbase() (addr []byte, err error) {
// TODO: persist coinbase address on disk
return am.firstAddr()
}
func (am *Manager) firstAddr() ([]byte, error) {
addrs, err := am.keyStore.GetKeyAddresses() addrs, err := am.keyStore.GetKeyAddresses()
if os.IsNotExist(err) { if os.IsNotExist(err) {
return nil, ErrNoKeys return nil, ErrNoKeys

@ -9,10 +9,10 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/xeth" "github.com/ethereum/go-ethereum/xeth"
"github.com/robertkrimen/otto" "github.com/robertkrimen/otto"
) )
@ -69,14 +69,13 @@ func (js *jsre) startRPC(call otto.FunctionCall) otto.Value {
fmt.Println(err) fmt.Println(err)
return otto.FalseValue() return otto.FalseValue()
} }
dataDir := js.ethereum.DataDir
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port)) l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port))
if err != nil { if err != nil {
fmt.Printf("Can't listen on %s:%d: %v", addr, port, err) fmt.Printf("Can't listen on %s:%d: %v", addr, port, err)
return otto.FalseValue() return otto.FalseValue()
} }
go http.Serve(l, rpc.JSONRPC(xeth.New(js.ethereum, nil), dataDir)) go http.Serve(l, rpc.JSONRPC(xeth.New(js.ethereum, nil)))
return otto.TrueValue() return otto.TrueValue()
} }

@ -91,8 +91,7 @@ func newJSRE(ethereum *eth.Ethereum, libPath string, interactive bool) *jsre {
func (js *jsre) apiBindings() { func (js *jsre) apiBindings() {
ethApi := rpc.NewEthereumApi(js.xeth, js.ethereum.DataDir) ethApi := rpc.NewEthereumApi(js.xeth)
ethApi.Close()
//js.re.Bind("jeth", rpc.NewJeth(ethApi, js.re.ToVal)) //js.re.Bind("jeth", rpc.NewJeth(ethApi, js.re.ToVal))
jeth := rpc.NewJeth(ethApi, js.re.ToVal, js.re) jeth := rpc.NewJeth(ethApi, js.re.ToVal, js.re)

@ -221,6 +221,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
utils.LogJSONFlag, utils.LogJSONFlag,
utils.LogLevelFlag, utils.LogLevelFlag,
utils.MaxPeersFlag, utils.MaxPeersFlag,
utils.EtherbaseFlag,
utils.MinerThreadsFlag, utils.MinerThreadsFlag,
utils.MiningEnabledFlag, utils.MiningEnabledFlag,
utils.NATFlag, utils.NATFlag,
@ -322,10 +323,10 @@ func startEth(ctx *cli.Context, eth *eth.Ethereum) {
account := ctx.GlobalString(utils.UnlockedAccountFlag.Name) account := ctx.GlobalString(utils.UnlockedAccountFlag.Name)
if len(account) > 0 { if len(account) > 0 {
if account == "coinbase" { if account == "primary" {
accbytes, err := am.Coinbase() accbytes, err := am.Primary()
if err != nil { if err != nil {
utils.Fatalf("no coinbase account: %v", err) utils.Fatalf("no primary account: %v", err)
} }
account = common.ToHex(accbytes) account = common.ToHex(accbytes)
} }
@ -468,7 +469,6 @@ func dump(ctx *cli.Context) {
} else { } else {
statedb := state.New(block.Root(), stateDb) statedb := state.New(block.Root(), stateDb)
fmt.Printf("%s\n", statedb.Dump()) fmt.Printf("%s\n", statedb.Dump())
// fmt.Println(block)
} }
} }
} }

@ -96,10 +96,15 @@ var (
Name: "mine", Name: "mine",
Usage: "Enable mining", Usage: "Enable mining",
} }
EtherbaseFlag = cli.StringFlag{
Name: "etherbase",
Usage: "public address for block mining rewards. By default the address of your primary account is used",
Value: "primary",
}
UnlockedAccountFlag = cli.StringFlag{ UnlockedAccountFlag = cli.StringFlag{
Name: "unlock", Name: "unlock",
Usage: "unlock the account given until this program exits (prompts for password). '--unlock coinbase' unlocks the primary (coinbase) account", Usage: "unlock the account given until this program exits (prompts for password). '--unlock primary' unlocks the primary account",
Value: "", Value: "",
} }
PasswordFileFlag = cli.StringFlag{ PasswordFileFlag = cli.StringFlag{
@ -215,6 +220,7 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
LogFile: ctx.GlobalString(LogFileFlag.Name), LogFile: ctx.GlobalString(LogFileFlag.Name),
LogLevel: ctx.GlobalInt(LogLevelFlag.Name), LogLevel: ctx.GlobalInt(LogLevelFlag.Name),
LogJSON: ctx.GlobalString(LogJSONFlag.Name), LogJSON: ctx.GlobalString(LogJSONFlag.Name),
Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name), MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
AccountManager: GetAccountManager(ctx), AccountManager: GetAccountManager(ctx),
VmDebug: ctx.GlobalBool(VMDebugFlag.Name), VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
@ -251,11 +257,10 @@ func GetAccountManager(ctx *cli.Context) *accounts.Manager {
func StartRPC(eth *eth.Ethereum, ctx *cli.Context) { func StartRPC(eth *eth.Ethereum, ctx *cli.Context) {
addr := ctx.GlobalString(RPCListenAddrFlag.Name) addr := ctx.GlobalString(RPCListenAddrFlag.Name)
port := ctx.GlobalInt(RPCPortFlag.Name) port := ctx.GlobalInt(RPCPortFlag.Name)
dataDir := ctx.GlobalString(DataDirFlag.Name)
fmt.Println("Starting RPC on port: ", port) fmt.Println("Starting RPC on port: ", port)
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port)) l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port))
if err != nil { if err != nil {
Fatalf("Can't listen on %s:%d: %v", addr, port, err) Fatalf("Can't listen on %s:%d: %v", addr, port, err)
} }
go http.Serve(l, rpc.JSONRPC(xeth.New(eth, nil), dataDir)) go http.Serve(l, rpc.JSONRPC(xeth.New(eth, nil)))
} }

@ -63,6 +63,7 @@ type Config struct {
Shh bool Shh bool
Dial bool Dial bool
Etherbase string
MinerThreads int MinerThreads int
AccountManager *accounts.Manager AccountManager *accounts.Manager
@ -140,6 +141,7 @@ type Ethereum struct {
Mining bool Mining bool
DataDir string DataDir string
etherbase common.Address
clientVersion string clientVersion string
ethVersionId int ethVersionId int
netVersionId int netVersionId int
@ -185,6 +187,7 @@ func New(config *Config) (*Ethereum, error) {
eventMux: &event.TypeMux{}, eventMux: &event.TypeMux{},
accountManager: config.AccountManager, accountManager: config.AccountManager,
DataDir: config.DataDir, DataDir: config.DataDir,
etherbase: common.HexToAddress(config.Etherbase),
clientVersion: config.Name, // TODO should separate from Name clientVersion: config.Name, // TODO should separate from Name
ethVersionId: config.ProtocolVersion, ethVersionId: config.ProtocolVersion,
netVersionId: config.NetworkId, netVersionId: config.NetworkId,
@ -297,15 +300,31 @@ func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
} }
func (s *Ethereum) StartMining() error { func (s *Ethereum) StartMining() error {
cb, err := s.accountManager.Coinbase() eb, err := s.Etherbase()
if err != nil { if err != nil {
servlogger.Errorf("Cannot start mining without coinbase: %v\n", err) err = fmt.Errorf("Cannot start mining without etherbase address: %v", err)
return fmt.Errorf("no coinbase: %v", err) servlogger.Errorln(err)
return err
} }
s.miner.Start(common.BytesToAddress(cb))
s.miner.Start(eb)
return nil return nil
} }
func (s *Ethereum) Etherbase() (eb common.Address, err error) {
eb = s.etherbase
if (eb == common.Address{}) {
var ebbytes []byte
ebbytes, err = s.accountManager.Primary()
eb = common.BytesToAddress(ebbytes)
if (eb == common.Address{}) {
err = fmt.Errorf("no accounts found")
}
}
return
}
func (s *Ethereum) StopMining() { s.miner.Stop() } func (s *Ethereum) StopMining() { s.miner.Stop() }
func (s *Ethereum) IsMining() bool { return s.miner.Mining() } func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
func (s *Ethereum) Miner() *miner.Miner { return s.miner } func (s *Ethereum) Miner() *miner.Miner { return s.miner }

@ -3,13 +3,11 @@ package rpc
import ( import (
"encoding/json" "encoding/json"
"math/big" "math/big"
"path"
"sync" "sync"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/xeth" "github.com/ethereum/go-ethereum/xeth"
) )
@ -19,15 +17,9 @@ type EthereumApi struct {
db common.Database db common.Database
} }
func NewEthereumApi(xeth *xeth.XEth, dataDir string) *EthereumApi { func NewEthereumApi(xeth *xeth.XEth) *EthereumApi {
// What about when dataDir is empty?
db, err := ethdb.NewLDBDatabase(path.Join(dataDir, "dapps"))
if err != nil {
panic(err)
}
api := &EthereumApi{ api := &EthereumApi{
eth: xeth, eth: xeth,
db: db,
} }
return api return api
@ -44,10 +36,6 @@ func (api *EthereumApi) xethAtStateNum(num int64) *xeth.XEth {
return api.xeth().AtStateNum(num) return api.xeth().AtStateNum(num)
} }
func (api *EthereumApi) Close() {
api.db.Close()
}
func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error { func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error {
// Spec at https://github.com/ethereum/wiki/wiki/JSON-RPC // Spec at https://github.com/ethereum/wiki/wiki/JSON-RPC
rpclogger.Debugf("%s %s", req.Method, req.Params) rpclogger.Debugf("%s %s", req.Method, req.Params)
@ -343,7 +331,8 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
return err return err
} }
api.db.Put([]byte(args.Database+args.Key), args.Value) api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
*reply = true *reply = true
case "db_getString": case "db_getString":
args := new(DbArgs) args := new(DbArgs)
@ -355,7 +344,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
return err return err
} }
res, _ := api.db.Get([]byte(args.Database + args.Key)) res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
*reply = string(res) *reply = string(res)
case "db_putHex": case "db_putHex":
args := new(DbHexArgs) args := new(DbHexArgs)
@ -367,7 +356,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
return err return err
} }
api.db.Put([]byte(args.Database+args.Key), args.Value) api.xeth().DbPut([]byte(args.Database+args.Key), args.Value)
*reply = true *reply = true
case "db_getHex": case "db_getHex":
args := new(DbHexArgs) args := new(DbHexArgs)
@ -379,7 +368,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
return err return err
} }
res, _ := api.db.Get([]byte(args.Database + args.Key)) res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
*reply = common.ToHex(res) *reply = common.ToHex(res)
case "shh_version": case "shh_version":
*reply = api.xeth().WhisperVersion() *reply = api.xeth().WhisperVersion()

@ -6,7 +6,7 @@ import (
"testing" "testing"
// "time" // "time"
"github.com/ethereum/go-ethereum/xeth" // "github.com/ethereum/go-ethereum/xeth"
) )
func TestWeb3Sha3(t *testing.T) { func TestWeb3Sha3(t *testing.T) {
@ -26,49 +26,48 @@ func TestWeb3Sha3(t *testing.T) {
} }
} }
func TestDbStr(t *testing.T) { // func TestDbStr(t *testing.T) {
jsonput := `{"jsonrpc":"2.0","method":"db_putString","params":["testDB","myKey","myString"],"id":64}` // jsonput := `{"jsonrpc":"2.0","method":"db_putString","params":["testDB","myKey","myString"],"id":64}`
jsonget := `{"jsonrpc":"2.0","method":"db_getString","params":["testDB","myKey"],"id":64}` // jsonget := `{"jsonrpc":"2.0","method":"db_getString","params":["testDB","myKey"],"id":64}`
expected := "myString" // expected := "myString"
xeth := &xeth.XEth{} // xeth := &xeth.XEth{}
api := NewEthereumApi(xeth, "") // api := NewEthereumApi(xeth)
defer api.db.Close() // var response interface{}
var response interface{}
var req RpcRequest // var req RpcRequest
json.Unmarshal([]byte(jsonput), &req) // json.Unmarshal([]byte(jsonput), &req)
_ = api.GetRequestReply(&req, &response) // _ = api.GetRequestReply(&req, &response)
json.Unmarshal([]byte(jsonget), &req) // json.Unmarshal([]byte(jsonget), &req)
_ = api.GetRequestReply(&req, &response) // _ = api.GetRequestReply(&req, &response)
if response.(string) != expected { // if response.(string) != expected {
t.Errorf("Expected %s got %s", expected, response) // t.Errorf("Expected %s got %s", expected, response)
} // }
} // }
func TestDbHexStr(t *testing.T) { // func TestDbHexStr(t *testing.T) {
jsonput := `{"jsonrpc":"2.0","method":"db_putHex","params":["testDB","beefKey","0xbeef"],"id":64}` // jsonput := `{"jsonrpc":"2.0","method":"db_putHex","params":["testDB","beefKey","0xbeef"],"id":64}`
jsonget := `{"jsonrpc":"2.0","method":"db_getHex","params":["testDB","beefKey"],"id":64}` // jsonget := `{"jsonrpc":"2.0","method":"db_getHex","params":["testDB","beefKey"],"id":64}`
expected := "0xbeef" // expected := "0xbeef"
xeth := &xeth.XEth{} // xeth := &xeth.XEth{}
api := NewEthereumApi(xeth, "") // api := NewEthereumApi(xeth)
defer api.db.Close() // defer api.db.Close()
var response interface{} // var response interface{}
var req RpcRequest // var req RpcRequest
json.Unmarshal([]byte(jsonput), &req) // json.Unmarshal([]byte(jsonput), &req)
_ = api.GetRequestReply(&req, &response) // _ = api.GetRequestReply(&req, &response)
json.Unmarshal([]byte(jsonget), &req) // json.Unmarshal([]byte(jsonget), &req)
_ = api.GetRequestReply(&req, &response) // _ = api.GetRequestReply(&req, &response)
if response.(string) != expected { // if response.(string) != expected {
t.Errorf("Expected %s got %s", expected, response) // t.Errorf("Expected %s got %s", expected, response)
} // }
} // }
// func TestFilterClose(t *testing.T) { // func TestFilterClose(t *testing.T) {
// t.Skip() // t.Skip()

@ -18,8 +18,8 @@ const (
) )
// JSONRPC returns a handler that implements the Ethereum JSON-RPC API. // JSONRPC returns a handler that implements the Ethereum JSON-RPC API.
func JSONRPC(pipe *xeth.XEth, dataDir string) http.Handler { func JSONRPC(pipe *xeth.XEth) http.Handler {
api := NewEthereumApi(pipe, dataDir) api := NewEthereumApi(pipe)
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// TODO this needs to be configurable // TODO this needs to be configurable

@ -6,14 +6,14 @@ import (
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
) )
type BlockRes struct { type BlockRes struct {
fullTx bool fullTx bool
BlockNumber int64 `json:"number"` BlockNumber *big.Int `json:"number"`
BlockHash common.Hash `json:"hash"` BlockHash common.Hash `json:"hash"`
ParentHash common.Hash `json:"parentHash"` ParentHash common.Hash `json:"parentHash"`
Nonce [8]byte `json:"nonce"` Nonce [8]byte `json:"nonce"`
@ -22,13 +22,13 @@ type BlockRes struct {
TransactionRoot common.Hash `json:"transactionRoot"` TransactionRoot common.Hash `json:"transactionRoot"`
StateRoot common.Hash `json:"stateRoot"` StateRoot common.Hash `json:"stateRoot"`
Miner common.Address `json:"miner"` Miner common.Address `json:"miner"`
Difficulty int64 `json:"difficulty"` Difficulty *big.Int `json:"difficulty"`
TotalDifficulty int64 `json:"totalDifficulty"` TotalDifficulty *big.Int `json:"totalDifficulty"`
Size int64 `json:"size"` Size *big.Int `json:"size"`
ExtraData []byte `json:"extraData"` ExtraData []byte `json:"extraData"`
GasLimit int64 `json:"gasLimit"` GasLimit *big.Int `json:"gasLimit"`
MinGasPrice int64 `json:"minGasPrice"` MinGasPrice int64 `json:"minGasPrice"`
GasUsed int64 `json:"gasUsed"` GasUsed *big.Int `json:"gasUsed"`
UnixTimestamp int64 `json:"timestamp"` UnixTimestamp int64 `json:"timestamp"`
Transactions []*TransactionRes `json:"transactions"` Transactions []*TransactionRes `json:"transactions"`
Uncles []common.Hash `json:"uncles"` Uncles []common.Hash `json:"uncles"`
@ -58,7 +58,7 @@ func (b *BlockRes) MarshalJSON() ([]byte, error) {
} }
// convert strict types to hexified strings // convert strict types to hexified strings
ext.BlockNumber = common.ToHex(big.NewInt(b.BlockNumber).Bytes()) ext.BlockNumber = common.ToHex(b.BlockNumber.Bytes())
ext.BlockHash = b.BlockHash.Hex() ext.BlockHash = b.BlockHash.Hex()
ext.ParentHash = b.ParentHash.Hex() ext.ParentHash = b.ParentHash.Hex()
ext.Nonce = common.ToHex(b.Nonce[:]) ext.Nonce = common.ToHex(b.Nonce[:])
@ -67,13 +67,13 @@ func (b *BlockRes) MarshalJSON() ([]byte, error) {
ext.TransactionRoot = b.TransactionRoot.Hex() ext.TransactionRoot = b.TransactionRoot.Hex()
ext.StateRoot = b.StateRoot.Hex() ext.StateRoot = b.StateRoot.Hex()
ext.Miner = b.Miner.Hex() ext.Miner = b.Miner.Hex()
ext.Difficulty = common.ToHex(big.NewInt(b.Difficulty).Bytes()) ext.Difficulty = common.ToHex(b.Difficulty.Bytes())
ext.TotalDifficulty = common.ToHex(big.NewInt(b.TotalDifficulty).Bytes()) ext.TotalDifficulty = common.ToHex(b.TotalDifficulty.Bytes())
ext.Size = common.ToHex(big.NewInt(b.Size).Bytes()) ext.Size = common.ToHex(b.Size.Bytes())
// ext.ExtraData = common.ToHex(b.ExtraData) // ext.ExtraData = common.ToHex(b.ExtraData)
ext.GasLimit = common.ToHex(big.NewInt(b.GasLimit).Bytes()) ext.GasLimit = common.ToHex(b.GasLimit.Bytes())
// ext.MinGasPrice = common.ToHex(big.NewInt(b.MinGasPrice).Bytes()) // ext.MinGasPrice = common.ToHex(big.NewInt(b.MinGasPrice).Bytes())
ext.GasUsed = common.ToHex(big.NewInt(b.GasUsed).Bytes()) ext.GasUsed = common.ToHex(b.GasUsed.Bytes())
ext.UnixTimestamp = common.ToHex(big.NewInt(b.UnixTimestamp).Bytes()) ext.UnixTimestamp = common.ToHex(big.NewInt(b.UnixTimestamp).Bytes())
ext.Transactions = make([]interface{}, len(b.Transactions)) ext.Transactions = make([]interface{}, len(b.Transactions))
if b.fullTx { if b.fullTx {
@ -99,7 +99,7 @@ func NewBlockRes(block *types.Block) *BlockRes {
} }
res := new(BlockRes) res := new(BlockRes)
res.BlockNumber = block.Number().Int64() res.BlockNumber = block.Number()
res.BlockHash = block.Hash() res.BlockHash = block.Hash()
res.ParentHash = block.ParentHash() res.ParentHash = block.ParentHash()
res.Nonce = block.Header().Nonce res.Nonce = block.Header().Nonce
@ -108,15 +108,13 @@ func NewBlockRes(block *types.Block) *BlockRes {
res.TransactionRoot = block.Header().TxHash res.TransactionRoot = block.Header().TxHash
res.StateRoot = block.Root() res.StateRoot = block.Root()
res.Miner = block.Header().Coinbase res.Miner = block.Header().Coinbase
res.Difficulty = block.Difficulty().Int64() res.Difficulty = block.Difficulty()
if block.Td != nil { res.TotalDifficulty = block.Td
res.TotalDifficulty = block.Td.Int64() res.Size = big.NewInt(int64(block.Size()))
}
res.Size = int64(block.Size())
// res.ExtraData = // res.ExtraData =
res.GasLimit = block.GasLimit().Int64() res.GasLimit = block.GasLimit()
// res.MinGasPrice = // res.MinGasPrice =
res.GasUsed = block.GasUsed().Int64() res.GasUsed = block.GasUsed()
res.UnixTimestamp = block.Time() res.UnixTimestamp = block.Time()
res.Transactions = make([]*TransactionRes, len(block.Transactions())) res.Transactions = make([]*TransactionRes, len(block.Transactions()))
for i, tx := range block.Transactions() { for i, tx := range block.Transactions() {
@ -135,47 +133,47 @@ func NewBlockRes(block *types.Block) *BlockRes {
type TransactionRes struct { type TransactionRes struct {
Hash common.Hash `json:"hash"` Hash common.Hash `json:"hash"`
Nonce int64 `json:"nonce"` Nonce uint64 `json:"nonce"`
BlockHash common.Hash `json:"blockHash,omitempty"` BlockHash common.Hash `json:"blockHash,omitempty"`
BlockNumber int64 `json:"blockNumber,omitempty"` BlockNumber int64 `json:"blockNumber,omitempty"`
TxIndex int64 `json:"transactionIndex,omitempty"` TxIndex int64 `json:"transactionIndex,omitempty"`
From common.Address `json:"from"` From common.Address `json:"from"`
To *common.Address `json:"to"` To *common.Address `json:"to"`
Value int64 `json:"value"` Value *big.Int `json:"value"`
Gas int64 `json:"gas"` Gas *big.Int `json:"gas"`
GasPrice int64 `json:"gasPrice"` GasPrice *big.Int `json:"gasPrice"`
Input []byte `json:"input"` Input []byte `json:"input"`
} }
func (t *TransactionRes) MarshalJSON() ([]byte, error) { func (t *TransactionRes) MarshalJSON() ([]byte, error) {
var ext struct { var ext struct {
Hash string `json:"hash"` Hash string `json:"hash"`
Nonce string `json:"nonce"` Nonce string `json:"nonce"`
BlockHash string `json:"blockHash,omitempty"` BlockHash string `json:"blockHash,omitempty"`
BlockNumber string `json:"blockNumber,omitempty"` BlockNumber string `json:"blockNumber,omitempty"`
TxIndex string `json:"transactionIndex,omitempty"` TxIndex string `json:"transactionIndex,omitempty"`
From string `json:"from"` From string `json:"from"`
To string `json:"to"` To interface{} `json:"to"`
Value string `json:"value"` Value string `json:"value"`
Gas string `json:"gas"` Gas string `json:"gas"`
GasPrice string `json:"gasPrice"` GasPrice string `json:"gasPrice"`
Input string `json:"input"` Input string `json:"input"`
} }
ext.Hash = t.Hash.Hex() ext.Hash = t.Hash.Hex()
ext.Nonce = common.ToHex(big.NewInt(t.Nonce).Bytes()) ext.Nonce = common.ToHex(big.NewInt(int64(t.Nonce)).Bytes())
ext.BlockHash = t.BlockHash.Hex() ext.BlockHash = t.BlockHash.Hex()
ext.BlockNumber = common.ToHex(big.NewInt(t.BlockNumber).Bytes()) ext.BlockNumber = common.ToHex(big.NewInt(t.BlockNumber).Bytes())
ext.TxIndex = common.ToHex(big.NewInt(t.TxIndex).Bytes()) ext.TxIndex = common.ToHex(big.NewInt(t.TxIndex).Bytes())
ext.From = t.From.Hex() ext.From = t.From.Hex()
if t.To == nil { if t.To == nil {
ext.To = "0x00" ext.To = nil
} else { } else {
ext.To = t.To.Hex() ext.To = t.To.Hex()
} }
ext.Value = common.ToHex(big.NewInt(t.Value).Bytes()) ext.Value = common.ToHex(t.Value.Bytes())
ext.Gas = common.ToHex(big.NewInt(t.Gas).Bytes()) ext.Gas = common.ToHex(t.Gas.Bytes())
ext.GasPrice = common.ToHex(big.NewInt(t.GasPrice).Bytes()) ext.GasPrice = common.ToHex(t.GasPrice.Bytes())
ext.Input = common.ToHex(t.Input) ext.Input = common.ToHex(t.Input)
return json.Marshal(ext) return json.Marshal(ext)
@ -184,12 +182,12 @@ func (t *TransactionRes) MarshalJSON() ([]byte, error) {
func NewTransactionRes(tx *types.Transaction) *TransactionRes { func NewTransactionRes(tx *types.Transaction) *TransactionRes {
var v = new(TransactionRes) var v = new(TransactionRes)
v.Hash = tx.Hash() v.Hash = tx.Hash()
v.Nonce = int64(tx.Nonce()) v.Nonce = tx.Nonce()
v.From, _ = tx.From() v.From, _ = tx.From()
v.To = tx.To() v.To = tx.To()
v.Value = tx.Value().Int64() v.Value = tx.Value()
v.Gas = tx.Gas().Int64() v.Gas = tx.Gas()
v.GasPrice = tx.GasPrice().Int64() v.GasPrice = tx.GasPrice()
v.Input = tx.Data() v.Input = tx.Data()
return v return v
} }
@ -218,25 +216,48 @@ type FilterWhisperRes struct {
} }
type LogRes struct { type LogRes struct {
Address string `json:"address"` Address common.Address `json:"address"`
Topics []string `json:"topics"` Topics []common.Hash `json:"topics"`
Data string `json:"data"` Data []byte `json:"data"`
Number uint64 `json:"number"` Number uint64 `json:"number"`
}
func NewLogRes(log state.Log) LogRes {
var l LogRes
l.Topics = make([]common.Hash, len(log.Topics()))
l.Address = log.Address()
l.Data = log.Data()
l.Number = log.Number()
for j, topic := range log.Topics() {
l.Topics[j] = topic
}
return l
}
func (l *LogRes) MarshalJSON() ([]byte, error) {
var ext struct {
Address string `json:"address"`
Topics []string `json:"topics"`
Data string `json:"data"`
Number string `json:"number"`
}
ext.Address = l.Address.Hex()
ext.Data = common.Bytes2Hex(l.Data)
ext.Number = common.Bytes2Hex(big.NewInt(int64(l.Number)).Bytes())
ext.Topics = make([]string, len(l.Topics))
for i, v := range l.Topics {
ext.Topics[i] = v.Hex()
}
return json.Marshal(ext)
} }
func NewLogsRes(logs state.Logs) (ls []LogRes) { func NewLogsRes(logs state.Logs) (ls []LogRes) {
ls = make([]LogRes, len(logs)) ls = make([]LogRes, len(logs))
for i, log := range logs { for i, log := range logs {
var l LogRes ls[i] = NewLogRes(log)
l.Topics = make([]string, len(log.Topics()))
l.Address = log.Address().Hex()
l.Data = common.ToHex(log.Data())
l.Number = log.Number()
for j, topic := range log.Topics() {
l.Topics[j] = topic.Hex()
}
ls[i] = l
} }
return return

@ -0,0 +1,123 @@
package rpc
import (
"encoding/json"
"math/big"
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
)
func TestNewBlockRes(t *testing.T) {
parentHash := common.HexToHash("0x01")
coinbase := common.HexToAddress("0x01")
root := common.HexToHash("0x01")
difficulty := common.Big1
nonce := uint64(1)
extra := ""
block := types.NewBlock(parentHash, coinbase, root, difficulty, nonce, extra)
_ = NewBlockRes(block)
}
func TestBlockRes(t *testing.T) {
v := &BlockRes{
BlockNumber: big.NewInt(0),
BlockHash: common.HexToHash("0x0"),
ParentHash: common.HexToHash("0x0"),
Nonce: [8]byte{0, 0, 0, 0, 0, 0, 0, 0},
Sha3Uncles: common.HexToHash("0x0"),
LogsBloom: types.BytesToBloom([]byte{0}),
TransactionRoot: common.HexToHash("0x0"),
StateRoot: common.HexToHash("0x0"),
Miner: common.HexToAddress("0x0"),
Difficulty: big.NewInt(0),
TotalDifficulty: big.NewInt(0),
Size: big.NewInt(0),
ExtraData: []byte{},
GasLimit: big.NewInt(0),
MinGasPrice: int64(0),
GasUsed: big.NewInt(0),
UnixTimestamp: int64(0),
// Transactions []*TransactionRes `json:"transactions"`
// Uncles []common.Hash `json:"uncles"`
}
_, _ = json.Marshal(v)
// fmt.Println(string(j))
}
func TestTransactionRes(t *testing.T) {
a := common.HexToAddress("0x0")
v := &TransactionRes{
Hash: common.HexToHash("0x0"),
Nonce: uint64(0),
BlockHash: common.HexToHash("0x0"),
BlockNumber: int64(0),
TxIndex: int64(0),
From: common.HexToAddress("0x0"),
To: &a,
Value: big.NewInt(0),
Gas: big.NewInt(0),
GasPrice: big.NewInt(0),
Input: []byte{0},
}
_, _ = json.Marshal(v)
}
func TestNewTransactionRes(t *testing.T) {
to := common.HexToAddress("0x02")
amount := big.NewInt(1)
gasAmount := big.NewInt(1)
gasPrice := big.NewInt(1)
data := []byte{1, 2, 3}
tx := types.NewTransactionMessage(to, amount, gasAmount, gasPrice, data)
_ = NewTransactionRes(tx)
}
func TestLogRes(t *testing.T) {
topics := make([]common.Hash, 3)
topics = append(topics, common.HexToHash("0x00"))
topics = append(topics, common.HexToHash("0x10"))
topics = append(topics, common.HexToHash("0x20"))
v := &LogRes{
Topics: topics,
Address: common.HexToAddress("0x0"),
Data: []byte{1, 2, 3},
Number: uint64(5),
}
_, _ = json.Marshal(v)
}
func MakeStateLog(num int) state.Log {
address := common.HexToAddress("0x0")
data := []byte{1, 2, 3}
number := uint64(num)
topics := make([]common.Hash, 3)
topics = append(topics, common.HexToHash("0x00"))
topics = append(topics, common.HexToHash("0x10"))
topics = append(topics, common.HexToHash("0x20"))
log := state.NewLog(address, topics, data, number)
return log
}
func TestNewLogRes(t *testing.T) {
log := MakeStateLog(0)
_ = NewLogRes(log)
}
func TestNewLogsRes(t *testing.T) {
logs := make([]state.Log, 3)
logs[0] = MakeStateLog(1)
logs[1] = MakeStateLog(2)
logs[2] = MakeStateLog(3)
_ = NewLogsRes(logs)
}

@ -209,6 +209,16 @@ func (self *XEth) Accounts() []string {
return accountAddresses return accountAddresses
} }
func (self *XEth) DbPut(key, val []byte) bool {
self.backend.ExtraDb().Put(key, val)
return true
}
func (self *XEth) DbGet(key []byte) ([]byte, error) {
val, err := self.backend.ExtraDb().Get(key)
return val, err
}
func (self *XEth) PeerCount() int { func (self *XEth) PeerCount() int {
return self.backend.PeerCount() return self.backend.PeerCount()
} }
@ -250,8 +260,8 @@ func (self *XEth) IsListening() bool {
} }
func (self *XEth) Coinbase() string { func (self *XEth) Coinbase() string {
cb, _ := self.backend.AccountManager().Coinbase() eb, _ := self.backend.Etherbase()
return common.ToHex(cb) return eb.Hex()
} }
func (self *XEth) NumberToHuman(balance string) string { func (self *XEth) NumberToHuman(balance string) string {

Loading…
Cancel
Save