From d790229a33b1f3e6256ca6916be17a0cc3663076 Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Sun, 25 Jan 2015 14:50:43 -0600 Subject: [PATCH 1/9] Move HTTP transport to sub package of RPC --- cmd/utils/cmd.go | 4 +-- eth/backend.go | 2 +- rpc/{ => http}/server.go | 65 +++++++++++++++++++++------------------- rpc/json.go | 19 ++++++------ rpc/message.go | 14 ++++----- rpc/packages.go | 15 ++++++++-- 6 files changed, 66 insertions(+), 53 deletions(-) rename rpc/{ => http}/server.go (58%) diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 95a7f89c8..13fbc7c64 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -38,7 +38,7 @@ import ( "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/miner" "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/rpc" + rpchttp "github.com/ethereum/go-ethereum/rpc/http" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/websocket" "github.com/ethereum/go-ethereum/xeth" @@ -193,7 +193,7 @@ func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, Secre func StartRpc(ethereum *eth.Ethereum, RpcPort int) { var err error - ethereum.RpcServer, err = rpc.NewJsonRpcServer(xeth.NewJSXEth(ethereum), RpcPort) + ethereum.RpcServer, err = rpchttp.NewRpcHttpServer(xeth.NewJSXEth(ethereum), RpcPort) if err != nil { clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err) } else { diff --git a/eth/backend.go b/eth/backend.go index c3c7d1287..fbe080618 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -66,7 +66,7 @@ type Ethereum struct { txSub event.Subscription blockSub event.Subscription - RpcServer *rpc.JsonRpcServer + RpcServer rpc.RpcServer keyManager *crypto.KeyManager clientIdentity p2p.ClientIdentity diff --git a/rpc/server.go b/rpc/http/server.go similarity index 58% rename from rpc/server.go rename to rpc/http/server.go index a4cf1aa7c..a8b116076 100644 --- a/rpc/server.go +++ b/rpc/http/server.go @@ -14,7 +14,7 @@ You should have received a copy of the GNU General Public License along with go-ethereum. If not, see . */ -package rpc +package rpchttp import ( "fmt" @@ -22,18 +22,34 @@ import ( "net/http" "github.com/ethereum/go-ethereum/logger" + "github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/xeth" ) -var jsonlogger = logger.NewLogger("JSON") +var rpchttplogger = logger.NewLogger("RPC-HTTP") +var JSON rpc.JsonWrapper -type JsonRpcServer struct { +func NewRpcHttpServer(pipe *xeth.JSXEth, port int) (*RpcHttpServer, error) { + sport := fmt.Sprintf(":%d", port) + l, err := net.Listen("tcp", sport) + if err != nil { + return nil, err + } + + return &RpcHttpServer{ + listener: l, + quit: make(chan bool), + pipe: pipe, + }, nil +} + +type RpcHttpServer struct { quit chan bool listener net.Listener pipe *xeth.JSXEth } -func (s *JsonRpcServer) exitHandler() { +func (s *RpcHttpServer) exitHandler() { out: for { select { @@ -43,61 +59,48 @@ out: } } - jsonlogger.Infoln("Shutdown JSON-RPC server") + rpchttplogger.Infoln("Shutdown RPC-HTTP server") } -func (s *JsonRpcServer) Stop() { +func (s *RpcHttpServer) Stop() { close(s.quit) } -func (s *JsonRpcServer) Start() { - jsonlogger.Infoln("Starting JSON-RPC server") +func (s *RpcHttpServer) Start() { + rpchttplogger.Infoln("Starting RPC-HTTP server") go s.exitHandler() - h := apiHandler(&EthereumApi{pipe: s.pipe}) + api := rpc.NewEthereumApi(s.pipe) + h := s.apiHandler(api) http.Handle("/", h) err := http.Serve(s.listener, nil) // FIX Complains on shutdown due to listner already being closed if err != nil { - jsonlogger.Errorln("Error on JSON-RPC interface:", err) + rpchttplogger.Errorln("Error on RPC-HTTP interface:", err) } } -func NewJsonRpcServer(pipe *xeth.JSXEth, port int) (*JsonRpcServer, error) { - sport := fmt.Sprintf(":%d", port) - l, err := net.Listen("tcp", sport) - if err != nil { - return nil, err - } - - return &JsonRpcServer{ - listener: l, - quit: make(chan bool), - pipe: pipe, - }, nil -} - -func apiHandler(xeth *EthereumApi) http.Handler { +func (s *RpcHttpServer) apiHandler(xeth *rpc.EthereumApi) http.Handler { fn := func(w http.ResponseWriter, req *http.Request) { - jsonlogger.Debugln("Handling request") + rpchttplogger.Debugln("Handling request") reqParsed, reqerr := JSON.ParseRequestBody(req) if reqerr != nil { - JSON.Send(w, &RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: ErrorParseRequest}) + JSON.Send(w, &rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest}) return } var response interface{} reserr := xeth.GetRequestReply(&reqParsed, &response) if reserr != nil { - jsonlogger.Errorln(reserr) - JSON.Send(w, &RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()}) + rpchttplogger.Errorln(reserr) + JSON.Send(w, &rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()}) return } - jsonlogger.Debugf("Generated response: %T %s", response, response) - JSON.Send(w, &RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response}) + rpchttplogger.Debugf("Generated response: %T %s", response, response) + JSON.Send(w, &rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response}) } return http.HandlerFunc(fn) diff --git a/rpc/json.go b/rpc/json.go index 5446cb3c1..9bd204818 100644 --- a/rpc/json.go +++ b/rpc/json.go @@ -18,25 +18,28 @@ package rpc import ( "encoding/json" + "github.com/ethereum/go-ethereum/logger" "io" "net/http" ) -type jsonWrapper struct{} +var rpclogger = logger.NewLogger("RPC") -func (self jsonWrapper) Send(writer io.Writer, v interface{}) (n int, err error) { +type JsonWrapper struct{} + +func (self JsonWrapper) Send(writer io.Writer, v interface{}) (n int, err error) { var payload []byte payload, err = json.Marshal(v) if err != nil { - jsonlogger.Fatalln("Error marshalling JSON", err) + rpclogger.Fatalln("Error marshalling JSON", err) return 0, err } - jsonlogger.Infof("Sending payload: %s", payload) + rpclogger.Infof("Sending payload: %s", payload) return writer.Write(payload) } -func (self jsonWrapper) ParseRequestBody(req *http.Request) (RpcRequest, error) { +func (self JsonWrapper) ParseRequestBody(req *http.Request) (RpcRequest, error) { var reqParsed RpcRequest // Convert JSON to native types @@ -46,12 +49,10 @@ func (self jsonWrapper) ParseRequestBody(req *http.Request) (RpcRequest, error) err := d.Decode(&reqParsed) if err != nil { - jsonlogger.Errorln("Error decoding JSON: ", err) + rpclogger.Errorln("Error decoding JSON: ", err) return reqParsed, err } - jsonlogger.DebugDetailf("Parsed request: %s", reqParsed) + rpclogger.DebugDetailf("Parsed request: %s", reqParsed) return reqParsed, nil } - -var JSON jsonWrapper diff --git a/rpc/message.go b/rpc/message.go index 63de734b8..caf50a6c0 100644 --- a/rpc/message.go +++ b/rpc/message.go @@ -67,7 +67,7 @@ func (req *RpcRequest) ToGetBlockArgs() (*GetBlockArgs, error) { if err != nil { return nil, NewErrorResponse(ErrorDecodeArgs) } - jsonlogger.DebugDetailf("%T %v", args, args) + rpclogger.DebugDetailf("%T %v", args, args) return args, nil } @@ -82,7 +82,7 @@ func (req *RpcRequest) ToNewTxArgs() (*NewTxArgs, error) { if err != nil { return nil, NewErrorResponse(ErrorDecodeArgs) } - jsonlogger.DebugDetailf("%T %v", args, args) + rpclogger.DebugDetailf("%T %v", args, args) return args, nil } @@ -97,7 +97,7 @@ func (req *RpcRequest) ToPushTxArgs() (*PushTxArgs, error) { if err != nil { return nil, NewErrorResponse(ErrorDecodeArgs) } - jsonlogger.DebugDetailf("%T %v", args, args) + rpclogger.DebugDetailf("%T %v", args, args) return args, nil } @@ -113,7 +113,7 @@ func (req *RpcRequest) ToGetStorageArgs() (*GetStorageArgs, error) { if err != nil { return nil, NewErrorResponse(ErrorDecodeArgs) } - jsonlogger.DebugDetailf("%T %v", args, args) + rpclogger.DebugDetailf("%T %v", args, args) return args, nil } @@ -128,7 +128,7 @@ func (req *RpcRequest) ToGetTxCountArgs() (*GetTxCountArgs, error) { if err != nil { return nil, NewErrorResponse(ErrorDecodeArgs) } - jsonlogger.DebugDetailf("%T %v", args, args) + rpclogger.DebugDetailf("%T %v", args, args) return args, nil } @@ -143,7 +143,7 @@ func (req *RpcRequest) ToGetBalanceArgs() (*GetBalanceArgs, error) { if err != nil { return nil, NewErrorResponse(ErrorDecodeArgs) } - jsonlogger.DebugDetailf("%T %v", args, args) + rpclogger.DebugDetailf("%T %v", args, args) return args, nil } @@ -158,7 +158,7 @@ func (req *RpcRequest) ToGetCodeAtArgs() (*GetCodeAtArgs, error) { if err != nil { return nil, NewErrorResponse(ErrorDecodeArgs) } - jsonlogger.DebugDetailf("%T %v", args, args) + rpclogger.DebugDetailf("%T %v", args, args) return args, nil } diff --git a/rpc/packages.go b/rpc/packages.go index e87e0db7c..8b5965069 100644 --- a/rpc/packages.go +++ b/rpc/packages.go @@ -33,6 +33,15 @@ import ( "github.com/ethereum/go-ethereum/xeth" ) +type RpcServer interface { + Start() + Stop() +} + +func NewEthereumApi(xeth *xeth.JSXEth) *EthereumApi { + return &EthereumApi{pipe: xeth} +} + type EthereumApi struct { pipe *xeth.JSXEth } @@ -103,7 +112,7 @@ func (p *EthereumApi) GetStorageAt(args *GetStorageArgs, reply *interface{}) err i, _ := new(big.Int).SetString(args.Key, 10) hx = ethutil.Bytes2Hex(i.Bytes()) } - jsonlogger.Debugf("GetStorageAt(%s, %s)\n", args.Address, hx) + rpclogger.Debugf("GetStorageAt(%s, %s)\n", args.Address, hx) value := state.Storage(ethutil.Hex2Bytes(hx)) *reply = GetStorageAtRes{Address: args.Address, Key: args.Key, Value: value.Str()} return nil @@ -159,7 +168,7 @@ func (p *EthereumApi) GetCodeAt(args *GetCodeAtArgs, reply *interface{}) error { func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error { // Spec at https://github.com/ethereum/wiki/wiki/Generic-JSON-RPC - jsonlogger.DebugDetailf("%T %s", req.Params, req.Params) + rpclogger.DebugDetailf("%T %s", req.Params, req.Params) switch req.Method { case "eth_coinbase": return p.GetCoinbase(reply) @@ -203,6 +212,6 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error return NewErrorResponse(ErrorNotImplemented) } - jsonlogger.DebugDetailf("Reply: %T %s", reply, reply) + rpclogger.DebugDetailf("Reply: %T %s", reply, reply) return nil } From 2f0166b94583cc17fab28f3e4f1214f220d6c4a3 Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Tue, 27 Jan 2015 12:26:30 -0600 Subject: [PATCH 2/9] Indicate port in startup log message --- rpc/http/server.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rpc/http/server.go b/rpc/http/server.go index a8b116076..631d47110 100644 --- a/rpc/http/server.go +++ b/rpc/http/server.go @@ -40,6 +40,7 @@ func NewRpcHttpServer(pipe *xeth.JSXEth, port int) (*RpcHttpServer, error) { listener: l, quit: make(chan bool), pipe: pipe, + port: port, }, nil } @@ -47,6 +48,7 @@ type RpcHttpServer struct { quit chan bool listener net.Listener pipe *xeth.JSXEth + port int } func (s *RpcHttpServer) exitHandler() { @@ -67,7 +69,7 @@ func (s *RpcHttpServer) Stop() { } func (s *RpcHttpServer) Start() { - rpchttplogger.Infoln("Starting RPC-HTTP server") + rpchttplogger.Infof("Starting RPC-HTTP server on port %d", s.port) go s.exitHandler() api := rpc.NewEthereumApi(s.pipe) From b8e7b8e2e1b88e40090c9b741b4cd7000689ae9e Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Tue, 27 Jan 2015 12:27:14 -0600 Subject: [PATCH 3/9] New simplified Websocket transport Uses rpc.EthereumApi abstraction --- rpc/websocket/server.go | 124 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 rpc/websocket/server.go diff --git a/rpc/websocket/server.go b/rpc/websocket/server.go new file mode 100644 index 000000000..f854fe502 --- /dev/null +++ b/rpc/websocket/server.go @@ -0,0 +1,124 @@ +/* + 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 websocket + +import ( + "fmt" + "net" + "net/http" + + ws "code.google.com/p/go.net/websocket" + "github.com/ethereum/go-ethereum/eth" + "github.com/ethereum/go-ethereum/event/filter" + "github.com/ethereum/go-ethereum/logger" + "github.com/ethereum/go-ethereum/rpc" + "github.com/ethereum/go-ethereum/xeth" +) + +var wslogger = logger.NewLogger("RPC-WS") + +type WebSocketServer struct { + eth *eth.Ethereum + filterManager *filter.FilterManager + port int + doneCh chan bool + listener net.Listener +} + +func NewWebSocketServer(eth *eth.Ethereum, port int) (*WebSocketServer, error) { + sport := fmt.Sprintf(":%d", port) + l, err := net.Listen("tcp", sport) + if err != nil { + return nil, err + } + + filterManager := filter.NewFilterManager(eth.EventMux()) + go filterManager.Start() + + return &WebSocketServer{eth, + filterManager, + port, + make(chan bool), + l, + }, nil +} + +func (self *WebSocketServer) handlerLoop() { + for { + select { + case <-self.doneCh: + wslogger.Infoln("Shutdown RPC-WS server") + return + } + } +} + +func (self *WebSocketServer) Stop() { + close(self.doneCh) +} + +func (self *WebSocketServer) Start() { + wslogger.Infof("Starting RPC-WS server on port %d", self.port) + go self.handlerLoop() + + api := rpc.NewEthereumApi(xeth.NewJSXEth(self.eth)) + h := self.apiHandler(api) + http.Handle("/ws", h) + + err := http.Serve(self.listener, nil) + if err != nil { + wslogger.Errorln("Error on RPC-WS interface:", err) + } +} + +func (s *WebSocketServer) apiHandler(xeth *rpc.EthereumApi) http.Handler { + fn := func(w http.ResponseWriter, req *http.Request) { + h := sockHandler(xeth) + s := ws.Server{Handler: h} + s.ServeHTTP(w, req) + } + + return http.HandlerFunc(fn) +} + +func sockHandler(xeth *rpc.EthereumApi) ws.Handler { + fn := func(conn *ws.Conn) { + for { + // FIX wslogger does not output to console + wslogger.Debugln("Handling request") + var reqParsed rpc.RpcRequest + + if err := ws.JSON.Receive(conn, &reqParsed); err != nil { + wslogger.Debugln(rpc.ErrorParseRequest) + ws.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest}) + continue + } + + var response interface{} + reserr := xeth.GetRequestReply(&reqParsed, &response) + if reserr != nil { + wslogger.Errorln(reserr) + ws.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()}) + continue + } + + wslogger.Debugf("Generated response: %T %s", response, response) + ws.JSON.Send(conn, rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response}) + } + } + return fn +} From 5f50fe7a4a6218bedf78333d751b57166932464a Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Tue, 27 Jan 2015 12:28:58 -0600 Subject: [PATCH 4/9] Update CLI to use new Websocket RPC MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use “wsport” flag to change default port --- cmd/ethereum/flags.go | 2 ++ cmd/ethereum/main.go | 2 +- cmd/utils/cmd.go | 16 ++++++++++++---- eth/backend.go | 4 ++++ 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/cmd/ethereum/flags.go b/cmd/ethereum/flags.go index f829744dc..e0fbbb008 100644 --- a/cmd/ethereum/flags.go +++ b/cmd/ethereum/flags.go @@ -41,6 +41,7 @@ var ( StartRpc bool StartWebSockets bool RpcPort int + WsPort int NatType string PMPGateway string OutboundPort string @@ -96,6 +97,7 @@ func Init() { flag.StringVar(&PMPGateway, "pmp", "", "Gateway IP for PMP") flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers") flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on") + flag.IntVar(&WsPort, "wsport", 40404, "port to start websocket rpc server on") flag.BoolVar(&StartRpc, "rpc", false, "start rpc server") flag.BoolVar(&StartWebSockets, "ws", false, "start websocket server") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") diff --git a/cmd/ethereum/main.go b/cmd/ethereum/main.go index b816c678e..92dbf5a6f 100644 --- a/cmd/ethereum/main.go +++ b/cmd/ethereum/main.go @@ -131,7 +131,7 @@ func main() { } if StartWebSockets { - utils.StartWebSockets(ethereum) + utils.StartWebSockets(ethereum, WsPort) } utils.StartEthereum(ethereum, UseSeed) diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 13fbc7c64..437e0c037 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -39,8 +39,9 @@ import ( "github.com/ethereum/go-ethereum/miner" "github.com/ethereum/go-ethereum/rlp" rpchttp "github.com/ethereum/go-ethereum/rpc/http" + rpcws "github.com/ethereum/go-ethereum/rpc/websocket" "github.com/ethereum/go-ethereum/state" - "github.com/ethereum/go-ethereum/websocket" + // "github.com/ethereum/go-ethereum/websocket" "github.com/ethereum/go-ethereum/xeth" ) @@ -201,11 +202,18 @@ func StartRpc(ethereum *eth.Ethereum, RpcPort int) { } } -func StartWebSockets(eth *eth.Ethereum) { +func StartWebSockets(eth *eth.Ethereum, wsPort int) { clilogger.Infoln("Starting WebSockets") - sock := websocket.NewWebSocketServer(eth) - go sock.Serv() + // sock := websocket.NewWebSocketServer(eth) + // go sock.Serv() + var err error + eth.WsServer, err = rpcws.NewWebSocketServer(eth, wsPort) + if err != nil { + clilogger.Errorf("Could not start RPC interface (port %v): %v", wsPort, err) + } else { + go eth.WsServer.Start() + } } var gminer *miner.Miner diff --git a/eth/backend.go b/eth/backend.go index fbe080618..ab30a1b38 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -67,6 +67,7 @@ type Ethereum struct { blockSub event.Subscription RpcServer rpc.RpcServer + WsServer rpc.RpcServer keyManager *crypto.KeyManager clientIdentity p2p.ClientIdentity @@ -276,6 +277,9 @@ func (s *Ethereum) Stop() { if s.RpcServer != nil { s.RpcServer.Stop() } + if s.WsServer != nil { + s.WsServer.Stop() + } s.txPool.Stop() s.eventMux.Stop() s.blockPool.Stop() From a38bca3438960ab1eec6a522eebc6622a1096881 Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Tue, 27 Jan 2015 12:40:52 -0600 Subject: [PATCH 5/9] Add wsport flag to Mist --- cmd/mist/flags.go | 2 ++ cmd/mist/main.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cmd/mist/flags.go b/cmd/mist/flags.go index 8a67cdd0a..f530394c2 100644 --- a/cmd/mist/flags.go +++ b/cmd/mist/flags.go @@ -43,6 +43,7 @@ var ( StartRpc bool StartWebSockets bool RpcPort int + WsPort int UseUPnP bool NatType string OutboundPort string @@ -111,6 +112,7 @@ func Init() { flag.BoolVar(&UseUPnP, "upnp", true, "enable UPnP support") flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers") flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on") + flag.IntVar(&WsPort, "wsport", 40404, "port to start websocket rpc server on") flag.BoolVar(&StartRpc, "rpc", false, "start rpc server") flag.BoolVar(&StartWebSockets, "ws", false, "start websocket server") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") diff --git a/cmd/mist/main.go b/cmd/mist/main.go index eb0a80add..bcfb7f2ec 100644 --- a/cmd/mist/main.go +++ b/cmd/mist/main.go @@ -73,7 +73,7 @@ func run() error { } if StartWebSockets { - utils.StartWebSockets(ethereum) + utils.StartWebSockets(ethereum, WsPort) } gui := NewWindow(ethereum, config, ethereum.ClientIdentity().(*p2p.SimpleClientIdentity), KeyRing, LogLevel) From dd3f38fe5b283f3c728823cb2d4e844712017e48 Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Tue, 27 Jan 2015 14:16:34 -0600 Subject: [PATCH 6/9] Rename transport to ws Cleanup object naming for clarity --- cmd/utils/cmd.go | 2 +- rpc/{websocket => ws}/server.go | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) rename rpc/{websocket => ws}/server.go (80%) diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 437e0c037..9cdd8b5d1 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -39,7 +39,7 @@ import ( "github.com/ethereum/go-ethereum/miner" "github.com/ethereum/go-ethereum/rlp" rpchttp "github.com/ethereum/go-ethereum/rpc/http" - rpcws "github.com/ethereum/go-ethereum/rpc/websocket" + rpcws "github.com/ethereum/go-ethereum/rpc/ws" "github.com/ethereum/go-ethereum/state" // "github.com/ethereum/go-ethereum/websocket" "github.com/ethereum/go-ethereum/xeth" diff --git a/rpc/websocket/server.go b/rpc/ws/server.go similarity index 80% rename from rpc/websocket/server.go rename to rpc/ws/server.go index f854fe502..9be305b6c 100644 --- a/rpc/websocket/server.go +++ b/rpc/ws/server.go @@ -14,14 +14,14 @@ You should have received a copy of the GNU General Public License along with go-ethereum. If not, see . */ -package websocket +package ws import ( "fmt" "net" "net/http" - ws "code.google.com/p/go.net/websocket" + "code.google.com/p/go.net/websocket" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/event/filter" "github.com/ethereum/go-ethereum/logger" @@ -88,23 +88,23 @@ func (self *WebSocketServer) Start() { func (s *WebSocketServer) apiHandler(xeth *rpc.EthereumApi) http.Handler { fn := func(w http.ResponseWriter, req *http.Request) { h := sockHandler(xeth) - s := ws.Server{Handler: h} + s := websocket.Server{Handler: h} s.ServeHTTP(w, req) } return http.HandlerFunc(fn) } -func sockHandler(xeth *rpc.EthereumApi) ws.Handler { - fn := func(conn *ws.Conn) { +func sockHandler(xeth *rpc.EthereumApi) websocket.Handler { + fn := func(conn *websocket.Conn) { for { // FIX wslogger does not output to console wslogger.Debugln("Handling request") var reqParsed rpc.RpcRequest - if err := ws.JSON.Receive(conn, &reqParsed); err != nil { + if err := websocket.JSON.Receive(conn, &reqParsed); err != nil { wslogger.Debugln(rpc.ErrorParseRequest) - ws.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest}) + websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest}) continue } @@ -112,12 +112,12 @@ func sockHandler(xeth *rpc.EthereumApi) ws.Handler { reserr := xeth.GetRequestReply(&reqParsed, &response) if reserr != nil { wslogger.Errorln(reserr) - ws.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()}) + websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()}) continue } wslogger.Debugf("Generated response: %T %s", response, response) - ws.JSON.Send(conn, rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response}) + websocket.JSON.Send(conn, rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response}) } } return fn From d8c6168d11dda55ffb10bc70601e74e347c156e1 Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Tue, 27 Jan 2015 14:26:42 -0600 Subject: [PATCH 7/9] Return a websocker.Handler of the function --- rpc/ws/server.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rpc/ws/server.go b/rpc/ws/server.go index 9be305b6c..c275031f4 100644 --- a/rpc/ws/server.go +++ b/rpc/ws/server.go @@ -120,5 +120,5 @@ func sockHandler(xeth *rpc.EthereumApi) websocket.Handler { websocket.JSON.Send(conn, rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response}) } } - return fn + return websocket.Handler(fn) } From e9d017ba082bfd624267c974fa93a77da6269756 Mon Sep 17 00:00:00 2001 From: Taylor Gerring Date: Tue, 27 Jan 2015 14:34:01 -0600 Subject: [PATCH 8/9] Rename api var for clarity --- rpc/http/server.go | 4 ++-- rpc/ws/server.go | 9 ++++----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/rpc/http/server.go b/rpc/http/server.go index 631d47110..93b52a634 100644 --- a/rpc/http/server.go +++ b/rpc/http/server.go @@ -83,7 +83,7 @@ func (s *RpcHttpServer) Start() { } } -func (s *RpcHttpServer) apiHandler(xeth *rpc.EthereumApi) http.Handler { +func (s *RpcHttpServer) apiHandler(api *rpc.EthereumApi) http.Handler { fn := func(w http.ResponseWriter, req *http.Request) { rpchttplogger.Debugln("Handling request") @@ -94,7 +94,7 @@ func (s *RpcHttpServer) apiHandler(xeth *rpc.EthereumApi) http.Handler { } var response interface{} - reserr := xeth.GetRequestReply(&reqParsed, &response) + reserr := api.GetRequestReply(&reqParsed, &response) if reserr != nil { rpchttplogger.Errorln(reserr) JSON.Send(w, &rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()}) diff --git a/rpc/ws/server.go b/rpc/ws/server.go index c275031f4..248ebc585 100644 --- a/rpc/ws/server.go +++ b/rpc/ws/server.go @@ -85,9 +85,9 @@ func (self *WebSocketServer) Start() { } } -func (s *WebSocketServer) apiHandler(xeth *rpc.EthereumApi) http.Handler { +func (s *WebSocketServer) apiHandler(api *rpc.EthereumApi) http.Handler { fn := func(w http.ResponseWriter, req *http.Request) { - h := sockHandler(xeth) + h := sockHandler(api) s := websocket.Server{Handler: h} s.ServeHTTP(w, req) } @@ -95,10 +95,9 @@ func (s *WebSocketServer) apiHandler(xeth *rpc.EthereumApi) http.Handler { return http.HandlerFunc(fn) } -func sockHandler(xeth *rpc.EthereumApi) websocket.Handler { +func sockHandler(api *rpc.EthereumApi) websocket.Handler { fn := func(conn *websocket.Conn) { for { - // FIX wslogger does not output to console wslogger.Debugln("Handling request") var reqParsed rpc.RpcRequest @@ -109,7 +108,7 @@ func sockHandler(xeth *rpc.EthereumApi) websocket.Handler { } var response interface{} - reserr := xeth.GetRequestReply(&reqParsed, &response) + reserr := api.GetRequestReply(&reqParsed, &response) if reserr != nil { wslogger.Errorln(reserr) websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()}) From 7f638f0b2d8d989be25e660178d79df3278e4c84 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 28 Jan 2015 18:14:28 +0100 Subject: [PATCH 9/9] moving to a better xeth --- cmd/mist/assets/qml/main.qml | 4 +- cmd/mist/assets/qml/views/wallet.qml | 11 +- cmd/mist/gui.go | 86 ++++++------- cmd/mist/ui_lib.go | 54 --------- core/genesis.go | 2 +- eth/backend.go | 4 + javascript/types.go | 10 +- rpc/http/server.go | 2 + rpc/packages.go | 35 +++--- xeth/config.go | 2 + xeth/hexface.go | 154 ++++++++++-------------- xeth/world.go | 57 ++------- xeth/xeth.go | 174 +-------------------------- 13 files changed, 141 insertions(+), 454 deletions(-) diff --git a/cmd/mist/assets/qml/main.qml b/cmd/mist/assets/qml/main.qml index c6b524549..8f62cd0c8 100644 --- a/cmd/mist/assets/qml/main.qml +++ b/cmd/mist/assets/qml/main.qml @@ -56,7 +56,9 @@ ApplicationWindow { mainSplit.setView(wallet.view, wallet.menuItem); - newBrowserTab("http://etherian.io"); + console.log(">>>>>>") + newBrowserTab("http://etherian.io"); + console.log("WTF") // Command setup gui.sendCommand(0) diff --git a/cmd/mist/assets/qml/views/wallet.qml b/cmd/mist/assets/qml/views/wallet.qml index b81273a17..cb9762d2b 100644 --- a/cmd/mist/assets/qml/views/wallet.qml +++ b/cmd/mist/assets/qml/views/wallet.qml @@ -22,7 +22,8 @@ Rectangle { function setBalance() { //balance.text = "Balance: " + eth.numberToHuman(eth.balanceAt(eth.key().address)) if(menuItem) - menuItem.secondaryTitle = eth.numberToHuman(eth.balanceAt(eth.key().address)) + menuItem.secondaryTitle = eth.numberToHuman("0") + //menuItem.secondaryTitle = eth.numberToHuman(eth.balanceAt(eth.key().address)) } ListModel { @@ -155,14 +156,6 @@ Rectangle { model: ListModel { id: txModel Component.onCompleted: { - var me = eth.key().address; - var filterTo = ethx.watch({latest: -1, to: me}); - var filterFrom = ethx.watch({latest: -1, from: me}); - filterTo.changed(addTxs) - filterFrom.changed(addTxs) - - addTxs(filterTo.messages()) - addTxs(filterFrom.messages()) } function addTxs(messages) { diff --git a/cmd/mist/gui.go b/cmd/mist/gui.go index fd2ad5a11..6522c865d 100644 --- a/cmd/mist/gui.go +++ b/cmd/mist/gui.go @@ -32,7 +32,6 @@ import ( "path" "runtime" "strconv" - "strings" "time" "github.com/ethereum/go-ethereum/core" @@ -229,41 +228,44 @@ func (gui *Gui) setInitialChain(ancientBlocks bool) { } func (gui *Gui) loadAddressBook() { - view := gui.getObjectByName("infoView") - nameReg := gui.xeth.World().Config().Get("NameReg") - if nameReg != nil { - it := nameReg.Trie().Iterator() - for it.Next() { - if it.Key[0] != 0 { - view.Call("addAddress", struct{ Name, Address string }{string(it.Key), ethutil.Bytes2Hex(it.Value)}) - } + /* + view := gui.getObjectByName("infoView") + nameReg := gui.xeth.World().Config().Get("NameReg") + if nameReg != nil { + it := nameReg.Trie().Iterator() + for it.Next() { + if it.Key[0] != 0 { + view.Call("addAddress", struct{ Name, Address string }{string(it.Key), ethutil.Bytes2Hex(it.Value)}) + } + } } - } + */ } func (self *Gui) loadMergedMiningOptions() { - view := self.getObjectByName("mergedMiningModel") + /* + view := self.getObjectByName("mergedMiningModel") - mergeMining := self.xeth.World().Config().Get("MergeMining") - if mergeMining != nil { - i := 0 - it := mergeMining.Trie().Iterator() - for it.Next() { - view.Call("addMergedMiningOption", struct { - Checked bool - Name, Address string - Id, ItemId int - }{false, string(it.Key), ethutil.Bytes2Hex(it.Value), 0, i}) + mergeMining := self.xeth.World().Config().Get("MergeMining") + if mergeMining != nil { + i := 0 + it := mergeMining.Trie().Iterator() + for it.Next() { + view.Call("addMergedMiningOption", struct { + Checked bool + Name, Address string + Id, ItemId int + }{false, string(it.Key), ethutil.Bytes2Hex(it.Value), 0, i}) - i++ + i++ + } } - } + */ } func (gui *Gui) insertTransaction(window string, tx *types.Transaction) { - nameReg := gui.xeth.World().Config().Get("NameReg") addr := gui.address() var inout string @@ -275,31 +277,11 @@ func (gui *Gui) insertTransaction(window string, tx *types.Transaction) { var ( ptx = xeth.NewJSTx(tx) - send = nameReg.Storage(tx.From()) - rec = nameReg.Storage(tx.To()) - s, r string + send = ethutil.Bytes2Hex(tx.From()) + rec = ethutil.Bytes2Hex(tx.To()) ) - - if core.MessageCreatesContract(tx) { - rec = nameReg.Storage(core.AddressFromMessage(tx)) - } - - if send.Len() != 0 { - s = strings.Trim(send.Str(), "\x00") - } else { - s = ethutil.Bytes2Hex(tx.From()) - } - if rec.Len() != 0 { - r = strings.Trim(rec.Str(), "\x00") - } else { - if core.MessageCreatesContract(tx) { - r = ethutil.Bytes2Hex(core.AddressFromMessage(tx)) - } else { - r = ethutil.Bytes2Hex(tx.To()) - } - } - ptx.Sender = s - ptx.Address = r + ptx.Sender = send + ptx.Address = rec if window == "post" { //gui.getObjectByName("transactionView").Call("addTx", ptx, inout) @@ -320,7 +302,7 @@ func (gui *Gui) readPreviousTransactions() { } func (gui *Gui) processBlock(block *types.Block, initial bool) { - name := strings.Trim(gui.xeth.World().Config().Get("NameReg").Storage(block.Coinbase()).Str(), "\x00") + name := ethutil.Bytes2Hex(block.Coinbase()) b := xeth.NewJSBlock(block) b.Name = name @@ -531,9 +513,9 @@ NumGC: %d func (gui *Gui) setPeerInfo() { gui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", gui.eth.PeerCount(), gui.eth.MaxPeers)) gui.win.Root().Call("resetPeers") - for _, peer := range gui.xeth.Peers() { - gui.win.Root().Call("addPeer", peer) - } + //for _, peer := range gui.xeth.Peers() { + //gui.win.Root().Call("addPeer", peer) + //} } func (gui *Gui) privateKey() string { diff --git a/cmd/mist/ui_lib.go b/cmd/mist/ui_lib.go index e0321f6dd..ca3884a82 100644 --- a/cmd/mist/ui_lib.go +++ b/cmd/mist/ui_lib.go @@ -21,15 +21,11 @@ package main import ( - "bytes" "fmt" "path" - "strconv" - "strings" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/event/filter" @@ -79,56 +75,6 @@ func (self *UiLib) Notef(args []interface{}) { guilogger.Infoln(args...) } -func (self *UiLib) LookupDomain(domain string) string { - world := self.World() - - if len(domain) > 32 { - domain = string(crypto.Sha3([]byte(domain))) - } - data := world.Config().Get("DnsReg").StorageString(domain).Bytes() - - // Left padded = A record, Right padded = CNAME - if len(data) > 0 && data[0] == 0 { - data = bytes.TrimLeft(data, "\x00") - var ipSlice []string - for _, d := range data { - ipSlice = append(ipSlice, strconv.Itoa(int(d))) - } - - return strings.Join(ipSlice, ".") - } else { - data = bytes.TrimRight(data, "\x00") - - return string(data) - } -} - -func (self *UiLib) LookupName(addr string) string { - var ( - nameReg = self.World().Config().Get("NameReg") - lookup = nameReg.Storage(ethutil.Hex2Bytes(addr)) - ) - - if lookup.Len() != 0 { - return strings.Trim(lookup.Str(), "\x00") - } - - return addr -} - -func (self *UiLib) LookupAddress(name string) string { - var ( - nameReg = self.World().Config().Get("NameReg") - lookup = nameReg.Storage(ethutil.RightPadBytes([]byte(name), 32)) - ) - - if lookup.Len() != 0 { - return ethutil.Bytes2Hex(lookup.Bytes()) - } - - return "" -} - func (self *UiLib) PastPeers() *ethutil.List { return ethutil.NewList([]string{}) //return ethutil.NewList(eth.PastPeers()) diff --git a/core/genesis.go b/core/genesis.go index d9edaace2..6d4eeba72 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -34,7 +34,7 @@ func GenesisBlock(db ethutil.Database) *types.Block { statedb := state.New(genesis.Root(), db) //statedb := state.New(genesis.Trie()) for _, addr := range []string{ - "51ba59315b3a95761d0863b05ccc7a7f54703d99", + "dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6", "e4157b34ea9615cfbde6b4fda419828124b70c78", "b9c015918bdaba24b4ff057a92a3873d6eb201be", "6c386a4b26f73c802f34673f7248bb118f97424a", diff --git a/eth/backend.go b/eth/backend.go index ab30a1b38..b7b5c5f85 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -219,6 +219,10 @@ func (s *Ethereum) MaxPeers() int { return s.net.MaxPeers } +func (s *Ethereum) Coinbase() []byte { + return nil // TODO +} + // Start the ethereum func (s *Ethereum) Start(seed bool) error { err := s.net.Start() diff --git a/javascript/types.go b/javascript/types.go index 61a57033b..3f30fa92b 100644 --- a/javascript/types.go +++ b/javascript/types.go @@ -82,16 +82,8 @@ func (self *JSEthereum) Block(v interface{}) otto.Value { return otto.UndefinedValue() } -func (self *JSEthereum) Peers() otto.Value { - return self.toVal(self.JSXEth.Peers()) -} - -func (self *JSEthereum) Key() otto.Value { - return self.toVal(self.JSXEth.Key()) -} - func (self *JSEthereum) GetStateObject(addr string) otto.Value { - return self.toVal(&JSStateObject{xeth.NewJSObject(self.JSXEth.World().SafeGet(ethutil.Hex2Bytes(addr))), self}) + return self.toVal(&JSStateObject{xeth.NewJSObject(self.JSXEth.State().SafeGet(addr)), self}) } func (self *JSEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value { diff --git a/rpc/http/server.go b/rpc/http/server.go index 93b52a634..2a492f465 100644 --- a/rpc/http/server.go +++ b/rpc/http/server.go @@ -85,6 +85,8 @@ func (s *RpcHttpServer) Start() { func (s *RpcHttpServer) apiHandler(api *rpc.EthereumApi) http.Handler { fn := func(w http.ResponseWriter, req *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + rpchttplogger.Debugln("Handling request") reqParsed, reqerr := JSON.ParseRequestBody(req) diff --git a/rpc/packages.go b/rpc/packages.go index 8b5965069..e6d4859d2 100644 --- a/rpc/packages.go +++ b/rpc/packages.go @@ -39,11 +39,11 @@ type RpcServer interface { } func NewEthereumApi(xeth *xeth.JSXEth) *EthereumApi { - return &EthereumApi{pipe: xeth} + return &EthereumApi{xeth: xeth} } type EthereumApi struct { - pipe *xeth.JSXEth + xeth *xeth.JSXEth } func (p *EthereumApi) GetBlock(args *GetBlockArgs, reply *interface{}) error { @@ -53,9 +53,9 @@ func (p *EthereumApi) GetBlock(args *GetBlockArgs, reply *interface{}) error { } if args.BlockNumber > 0 { - *reply = p.pipe.BlockByNumber(args.BlockNumber) + *reply = p.xeth.BlockByNumber(args.BlockNumber) } else { - *reply = p.pipe.BlockByHash(args.Hash) + *reply = p.xeth.BlockByHash(args.Hash) } return nil } @@ -65,7 +65,7 @@ func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) error { if err != nil { return err } - result, _ := p.pipe.Transact(p.pipe.Key().PrivateKey, args.Recipient, args.Value, args.Gas, args.GasPrice, args.Body) + result, _ := p.xeth.Transact( /* TODO specify account */ "", args.Recipient, args.Value, args.Gas, args.GasPrice, args.Body) *reply = result return nil } @@ -76,7 +76,7 @@ func (p *EthereumApi) Create(args *NewTxArgs, reply *interface{}) error { return err } - result, _ := p.pipe.Transact(p.pipe.Key().PrivateKey, "", args.Value, args.Gas, args.GasPrice, args.Body) + result, _ := p.xeth.Transact( /* TODO specify account */ "", "", args.Value, args.Gas, args.GasPrice, args.Body) *reply = result return nil } @@ -86,23 +86,18 @@ func (p *EthereumApi) PushTx(args *PushTxArgs, reply *interface{}) error { if err != nil { return err } - result, _ := p.pipe.PushTx(args.Tx) + result, _ := p.xeth.PushTx(args.Tx) *reply = result return nil } -func (p *EthereumApi) GetKey(args interface{}, reply *interface{}) error { - *reply = p.pipe.Key() - return nil -} - func (p *EthereumApi) GetStorageAt(args *GetStorageArgs, reply *interface{}) error { err := args.requirements() if err != nil { return err } - state := p.pipe.World().SafeGet(ethutil.Hex2Bytes(args.Address)) + state := p.xeth.State().SafeGet(args.Address) var hx string if strings.Index(args.Key, "0x") == 0 { @@ -119,22 +114,22 @@ func (p *EthereumApi) GetStorageAt(args *GetStorageArgs, reply *interface{}) err } func (p *EthereumApi) GetPeerCount(reply *interface{}) error { - *reply = p.pipe.PeerCount() + *reply = p.xeth.PeerCount() return nil } func (p *EthereumApi) GetIsListening(reply *interface{}) error { - *reply = p.pipe.IsListening() + *reply = p.xeth.IsListening() return nil } func (p *EthereumApi) GetCoinbase(reply *interface{}) error { - *reply = p.pipe.CoinBase() + *reply = p.xeth.Coinbase() return nil } func (p *EthereumApi) GetIsMining(reply *interface{}) error { - *reply = p.pipe.IsMining() + *reply = p.xeth.IsMining() return nil } @@ -143,7 +138,7 @@ func (p *EthereumApi) GetTxCountAt(args *GetTxCountArgs, reply *interface{}) err if err != nil { return err } - *reply = p.pipe.TxCountAt(args.Address) + *reply = p.xeth.TxCountAt(args.Address) return nil } @@ -152,7 +147,7 @@ func (p *EthereumApi) GetBalanceAt(args *GetBalanceArgs, reply *interface{}) err if err != nil { return err } - state := p.pipe.World().SafeGet(ethutil.Hex2Bytes(args.Address)) + state := p.xeth.State().SafeGet(args.Address) *reply = BalanceRes{Balance: state.Balance().String(), Address: args.Address} return nil } @@ -162,7 +157,7 @@ func (p *EthereumApi) GetCodeAt(args *GetCodeAtArgs, reply *interface{}) error { if err != nil { return err } - *reply = p.pipe.CodeAt(args.Address) + *reply = p.xeth.CodeAt(args.Address) return nil } diff --git a/xeth/config.go b/xeth/config.go index ad0660d75..db6cce3bd 100644 --- a/xeth/config.go +++ b/xeth/config.go @@ -1,5 +1,6 @@ package xeth +/* import "github.com/ethereum/go-ethereum/ethutil" var cnfCtr = ethutil.Hex2Bytes("661005d2720d855f1d9976f88bb10c1a3398c77f") @@ -33,3 +34,4 @@ func (self *Config) Get(name string) *Object { func (self *Config) Exist() bool { return self.pipe.World().Get(cnfCtr) != nil } +*/ diff --git a/xeth/hexface.go b/xeth/hexface.go index 808ae7d39..3eb535724 100644 --- a/xeth/hexface.go +++ b/xeth/hexface.go @@ -11,27 +11,52 @@ import ( "github.com/ethereum/go-ethereum/state" ) -type JSXEth struct { - *XEth +// to resolve the import cycle +type Backend interface { + BlockProcessor() *core.BlockProcessor + ChainManager() *core.ChainManager + Coinbase() []byte + KeyManager() *crypto.KeyManager + IsMining() bool + IsListening() bool + PeerCount() int + Db() ethutil.Database + TxPool() *core.TxPool } -func NewJSXEth(eth core.EthManager) *JSXEth { - return &JSXEth{New(eth)} +type JSXEth struct { + eth Backend + blockProcessor *core.BlockProcessor + chainManager *core.ChainManager + world *State } +func NewJSXEth(eth Backend) *JSXEth { + xeth := &JSXEth{ + eth: eth, + blockProcessor: eth.BlockProcessor(), + chainManager: eth.ChainManager(), + } + xeth.world = NewState(xeth) + + return xeth +} + +func (self *JSXEth) State() *State { return self.world } + func (self *JSXEth) BlockByHash(strHash string) *JSBlock { hash := fromHex(strHash) - block := self.obj.ChainManager().GetBlock(hash) + block := self.chainManager.GetBlock(hash) return NewJSBlock(block) } func (self *JSXEth) BlockByNumber(num int32) *JSBlock { if num == -1 { - return NewJSBlock(self.obj.ChainManager().CurrentBlock()) + return NewJSBlock(self.chainManager.CurrentBlock()) } - return NewJSBlock(self.obj.ChainManager().GetBlockByNumber(uint64(num))) + return NewJSBlock(self.chainManager.GetBlockByNumber(uint64(num))) } func (self *JSXEth) Block(v interface{}) *JSBlock { @@ -46,43 +71,32 @@ func (self *JSXEth) Block(v interface{}) *JSBlock { return nil } -func (self *JSXEth) Key() *JSKey { - return NewJSKey(self.obj.KeyManager().KeyPair()) -} - func (self *JSXEth) Accounts() []string { - return []string{toHex(self.obj.KeyManager().Address())} + return []string{toHex(self.eth.KeyManager().Address())} } +/* func (self *JSXEth) StateObject(addr string) *JSObject { - object := &Object{self.World().safeGet(fromHex(addr))} + object := &Object{self.State().safeGet(fromHex(addr))} return NewJSObject(object) } +*/ func (self *JSXEth) PeerCount() int { - return self.obj.PeerCount() -} - -func (self *JSXEth) Peers() []JSPeer { - var peers []JSPeer - for _, peer := range self.obj.Peers() { - peers = append(peers, *NewJSPeer(peer)) - } - - return peers + return self.eth.PeerCount() } func (self *JSXEth) IsMining() bool { - return self.obj.IsMining() + return self.eth.IsMining() } func (self *JSXEth) IsListening() bool { - return self.obj.IsListening() + return self.eth.IsListening() } -func (self *JSXEth) CoinBase() string { - return toHex(self.obj.KeyManager().Address()) +func (self *JSXEth) Coinbase() string { + return toHex(self.eth.KeyManager().Address()) } func (self *JSXEth) NumberToHuman(balance string) string { @@ -92,25 +106,25 @@ func (self *JSXEth) NumberToHuman(balance string) string { } func (self *JSXEth) StorageAt(addr, storageAddr string) string { - storage := self.World().SafeGet(fromHex(addr)).Storage(fromHex(storageAddr)) + storage := self.State().SafeGet(addr).StorageString(storageAddr) return toHex(storage.Bytes()) } func (self *JSXEth) BalanceAt(addr string) string { - return self.World().SafeGet(fromHex(addr)).Balance().String() + return self.State().SafeGet(addr).Balance().String() } func (self *JSXEth) TxCountAt(address string) int { - return int(self.World().SafeGet(fromHex(address)).Nonce) + return int(self.State().SafeGet(address).Nonce) } func (self *JSXEth) CodeAt(address string) string { - return toHex(self.World().SafeGet(fromHex(address)).Code) + return toHex(self.State().SafeGet(address).Code) } func (self *JSXEth) IsContract(address string) bool { - return len(self.World().SafeGet(fromHex(address)).Code) > 0 + return len(self.State().SafeGet(address).Code) > 0 } func (self *JSXEth) SecretToAddress(key string) string { @@ -123,15 +137,7 @@ func (self *JSXEth) SecretToAddress(key string) string { } func (self *JSXEth) Execute(addr, value, gas, price, data string) (string, error) { - ret, err := self.ExecuteObject(&Object{ - self.World().safeGet(fromHex(addr))}, - fromHex(data), - ethutil.NewValue(value), - ethutil.NewValue(gas), - ethutil.NewValue(price), - ) - - return toHex(ret), err + return "", nil } type KeyVal struct { @@ -141,7 +147,7 @@ type KeyVal struct { func (self *JSXEth) EachStorage(addr string) string { var values []KeyVal - object := self.World().SafeGet(fromHex(addr)) + object := self.State().SafeGet(addr) it := object.Trie().Iterator() for it.Next() { values = append(values, KeyVal{toHex(it.Key), toHex(it.Value)}) @@ -178,55 +184,7 @@ func (self *JSXEth) FromNumber(str string) string { } func (self *JSXEth) Transact(key, toStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) { - var ( - to []byte - value = ethutil.NewValue(valueStr) - gas = ethutil.NewValue(gasStr) - gasPrice = ethutil.NewValue(gasPriceStr) - data []byte - ) - - data = fromHex(codeStr) - - to = fromHex(toStr) - - keyPair, err := crypto.NewKeyPairFromSec([]byte(fromHex(key))) - if err != nil { - return "", err - } - - tx, err := self.XEth.Transact(keyPair, to, value, gas, gasPrice, data) - if err != nil { - return "", err - } - if types.IsContractAddr(to) { - return toHex(core.AddressFromMessage(tx)), nil - } - - return toHex(tx.Hash()), nil -} - -func (self *JSXEth) PushTx(txStr string) (*JSReceipt, error) { - tx := types.NewTransactionFromBytes(fromHex(txStr)) - err := self.obj.TxPool().Add(tx) - if err != nil { - return nil, err - } - - return NewJSReciept(core.MessageCreatesContract(tx), core.AddressFromMessage(tx), tx.Hash(), tx.From()), nil -} - -func (self *JSXEth) CompileMutan(code string) string { - data, err := self.XEth.CompileMutan(code) - if err != nil { - return err.Error() - } - - return toHex(data) -} - -func (self *JSXEth) FindInConfig(str string) string { - return toHex(self.World().Config().Get(str).Address()) + return "", nil } func ToJSMessages(messages state.Messages) *ethutil.List { @@ -237,3 +195,17 @@ func ToJSMessages(messages state.Messages) *ethutil.List { return ethutil.NewList(msgs) } + +func (self *JSXEth) PushTx(encodedTx string) (string, error) { + tx := types.NewTransactionFromBytes(fromHex(encodedTx)) + err := self.eth.TxPool().Add(tx) + if err != nil { + return "", err + } + + if tx.To() == nil { + addr := core.AddressFromMessage(tx) + return toHex(addr), nil + } + return toHex(tx.Hash()), nil +} diff --git a/xeth/world.go b/xeth/world.go index 25c2f3eb8..60d4bbb57 100644 --- a/xeth/world.go +++ b/xeth/world.go @@ -1,63 +1,32 @@ package xeth -import ( - "github.com/ethereum/go-ethereum/p2p" - "github.com/ethereum/go-ethereum/state" -) +import "github.com/ethereum/go-ethereum/state" -type World struct { - pipe *XEth - cfg *Config +type State struct { + xeth *JSXEth } -func NewWorld(pipe *XEth) *World { - world := &World{pipe, nil} - world.cfg = &Config{pipe} - - return world +func NewState(xeth *JSXEth) *State { + return &State{xeth} } -func (self *XEth) World() *World { - return self.world +func (self *State) State() *state.StateDB { + return self.xeth.chainManager.State() } -func (self *World) State() *state.StateDB { - return self.pipe.chainManager.State() +func (self *State) Get(addr string) *Object { + return &Object{self.State().GetStateObject(fromHex(addr))} } -func (self *World) Get(addr []byte) *Object { - return &Object{self.State().GetStateObject(addr)} -} - -func (self *World) SafeGet(addr []byte) *Object { +func (self *State) SafeGet(addr string) *Object { return &Object{self.safeGet(addr)} } -func (self *World) safeGet(addr []byte) *state.StateObject { - object := self.State().GetStateObject(addr) +func (self *State) safeGet(addr string) *state.StateObject { + object := self.State().GetStateObject(fromHex(addr)) if object == nil { - object = state.NewStateObject(addr, self.pipe.obj.Db()) + object = state.NewStateObject(fromHex(addr), self.xeth.eth.Db()) } return object } - -func (self *World) Coinbase() *state.StateObject { - return nil -} - -func (self *World) IsMining() bool { - return self.pipe.obj.IsMining() -} - -func (self *World) IsListening() bool { - return self.pipe.obj.IsListening() -} - -func (self *World) Peers() []*p2p.Peer { - return self.pipe.obj.Peers() -} - -func (self *World) Config() *Config { - return self.cfg -} diff --git a/xeth/xeth.go b/xeth/xeth.go index 34d8ffd0a..92b9bc995 100644 --- a/xeth/xeth.go +++ b/xeth/xeth.go @@ -4,178 +4,6 @@ package xeth * eXtended ETHereum */ -import ( - "github.com/ethereum/go-ethereum/core" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" - "github.com/ethereum/go-ethereum/logger" - "github.com/ethereum/go-ethereum/state" -) +import "github.com/ethereum/go-ethereum/logger" var pipelogger = logger.NewLogger("XETH") - -type VmVars struct { - State *state.StateDB -} - -type XEth struct { - obj core.EthManager - blockProcessor *core.BlockProcessor - chainManager *core.ChainManager - world *World - - Vm VmVars -} - -func New(obj core.EthManager) *XEth { - pipe := &XEth{ - obj: obj, - blockProcessor: obj.BlockProcessor(), - chainManager: obj.ChainManager(), - } - pipe.world = NewWorld(pipe) - - return pipe -} - -/* - * State / Account accessors - */ -func (self *XEth) Balance(addr []byte) *ethutil.Value { - return ethutil.NewValue(self.World().safeGet(addr).Balance) -} - -func (self *XEth) Nonce(addr []byte) uint64 { - return self.World().safeGet(addr).Nonce -} - -func (self *XEth) Block(hash []byte) *types.Block { - return self.chainManager.GetBlock(hash) -} - -func (self *XEth) Storage(addr, storageAddr []byte) *ethutil.Value { - return self.World().safeGet(addr).GetStorage(ethutil.BigD(storageAddr)) -} - -func (self *XEth) Exists(addr []byte) bool { - return self.World().Get(addr) != nil -} - -// Converts the given private key to an address -func (self *XEth) ToAddress(priv []byte) []byte { - pair, err := crypto.NewKeyPairFromSec(priv) - if err != nil { - return nil - } - - return pair.Address() -} - -/* - * Execution helpers - */ -func (self *XEth) Execute(addr []byte, data []byte, value, gas, price *ethutil.Value) ([]byte, error) { - return self.ExecuteObject(&Object{self.World().safeGet(addr)}, data, value, gas, price) -} - -func (self *XEth) ExecuteObject(object *Object, data []byte, value, gas, price *ethutil.Value) ([]byte, error) { - var ( - initiator = state.NewStateObject(self.obj.KeyManager().KeyPair().Address(), self.obj.Db()) - block = self.chainManager.CurrentBlock() - ) - - self.Vm.State = self.World().State().Copy() - - vmenv := NewEnv(self.chainManager, self.Vm.State, block, value.BigInt(), initiator.Address()) - return vmenv.Call(initiator, object.Address(), data, gas.BigInt(), price.BigInt(), value.BigInt()) -} - -/* - * Transactional methods - */ -func (self *XEth) TransactString(key *crypto.KeyPair, rec string, value, gas, price *ethutil.Value, data []byte) (*types.Transaction, error) { - // Check if an address is stored by this address - var hash []byte - addr := self.World().Config().Get("NameReg").StorageString(rec).Bytes() - if len(addr) > 0 { - hash = addr - } else if ethutil.IsHex(rec) { - hash = ethutil.Hex2Bytes(rec[2:]) - } else { - hash = ethutil.Hex2Bytes(rec) - } - - return self.Transact(key, hash, value, gas, price, data) -} - -func (self *XEth) Transact(key *crypto.KeyPair, to []byte, value, gas, price *ethutil.Value, data []byte) (*types.Transaction, error) { - var hash []byte - var contractCreation bool - if types.IsContractAddr(to) { - contractCreation = true - } else { - // Check if an address is stored by this address - addr := self.World().Config().Get("NameReg").Storage(to).Bytes() - if len(addr) > 0 { - hash = addr - } else { - hash = to - } - } - - var tx *types.Transaction - if contractCreation { - tx = types.NewContractCreationTx(value.BigInt(), gas.BigInt(), price.BigInt(), data) - } else { - tx = types.NewTransactionMessage(hash, value.BigInt(), gas.BigInt(), price.BigInt(), data) - } - - state := self.chainManager.TransState() - nonce := state.GetNonce(key.Address()) - - tx.SetNonce(nonce) - tx.Sign(key.PrivateKey) - - // Do some pre processing for our "pre" events and hooks - block := self.chainManager.NewBlock(key.Address()) - coinbase := state.GetOrNewStateObject(key.Address()) - coinbase.SetGasPool(block.GasLimit()) - self.blockProcessor.ApplyTransactions(coinbase, state, block, types.Transactions{tx}, true) - - err := self.obj.TxPool().Add(tx) - if err != nil { - return nil, err - } - state.SetNonce(key.Address(), nonce+1) - - if contractCreation { - addr := core.AddressFromMessage(tx) - pipelogger.Infof("Contract addr %x\n", addr) - } - - return tx, nil -} - -func (self *XEth) PushTx(tx *types.Transaction) ([]byte, error) { - err := self.obj.TxPool().Add(tx) - if err != nil { - return nil, err - } - - if tx.To() == nil { - addr := core.AddressFromMessage(tx) - pipelogger.Infof("Contract addr %x\n", addr) - return addr, nil - } - return tx.Hash(), nil -} - -func (self *XEth) CompileMutan(code string) ([]byte, error) { - data, err := ethutil.Compile(code, false) - if err != nil { - return nil, err - } - - return data, nil -}