diff options
author | obscuren <geffobscura@gmail.com> | 2015-01-29 01:22:53 +0800 |
---|---|---|
committer | obscuren <geffobscura@gmail.com> | 2015-01-29 01:22:53 +0800 |
commit | 45e15f62f594d6f5191e60a54aead33602838e98 (patch) | |
tree | 5b82273df6a23c219d1e97dbb86b4bdcb620374a | |
parent | fb7c03ff4dc759f7dd2fc5cee65b46111cbb7375 (diff) | |
parent | 7f638f0b2d8d989be25e660178d79df3278e4c84 (diff) | |
download | dexon-45e15f62f594d6f5191e60a54aead33602838e98.tar.gz dexon-45e15f62f594d6f5191e60a54aead33602838e98.tar.zst dexon-45e15f62f594d6f5191e60a54aead33602838e98.zip |
merge jsonrpc
-rw-r--r-- | cmd/ethereum/flags.go | 2 | ||||
-rw-r--r-- | cmd/ethereum/main.go | 2 | ||||
-rw-r--r-- | cmd/mist/assets/qml/main.qml | 1 | ||||
-rw-r--r-- | cmd/mist/assets/qml/views/info.qml | 2 | ||||
-rw-r--r-- | cmd/mist/assets/qml/views/wallet.qml | 13 | ||||
-rw-r--r-- | cmd/mist/flags.go | 2 | ||||
-rw-r--r-- | cmd/mist/gui.go | 90 | ||||
-rw-r--r-- | cmd/mist/main.go | 2 | ||||
-rw-r--r-- | cmd/mist/ui_lib.go | 54 | ||||
-rw-r--r-- | cmd/utils/cmd.go | 20 | ||||
-rw-r--r-- | core/genesis.go | 2 | ||||
-rw-r--r-- | eth/backend.go | 10 | ||||
-rw-r--r-- | javascript/types.go | 10 | ||||
-rw-r--r-- | rpc/http/server.go (renamed from rpc/server.go) | 69 | ||||
-rw-r--r-- | rpc/json.go | 19 | ||||
-rw-r--r-- | rpc/message.go | 14 | ||||
-rw-r--r-- | rpc/packages.go | 48 | ||||
-rw-r--r-- | rpc/ws/server.go | 123 | ||||
-rw-r--r-- | xeth/config.go | 2 | ||||
-rw-r--r-- | xeth/hexface.go | 150 | ||||
-rw-r--r-- | xeth/world.go | 57 | ||||
-rw-r--r-- | xeth/xeth.go | 174 |
22 files changed, 350 insertions, 516 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/mist/assets/qml/main.qml b/cmd/mist/assets/qml/main.qml index c88873795..bc579ddfa 100644 --- a/cmd/mist/assets/qml/main.qml +++ b/cmd/mist/assets/qml/main.qml @@ -47,7 +47,6 @@ ApplicationWindow { console.log("starting browser") newBrowserTab("http://etherian.io"); - console.log("done") // Command setup gui.sendCommand(0) diff --git a/cmd/mist/assets/qml/views/info.qml b/cmd/mist/assets/qml/views/info.qml index 3ff551b05..f694f1e7a 100644 --- a/cmd/mist/assets/qml/views/info.qml +++ b/cmd/mist/assets/qml/views/info.qml @@ -28,7 +28,7 @@ Rectangle { text: "Address" } TextField { - text: eth.key().address + text: ""//eth.key().address width: 500 } diff --git a/cmd/mist/assets/qml/views/wallet.qml b/cmd/mist/assets/qml/views/wallet.qml index 23f32378d..d6160740d 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 = "<b>Balance</b>: " + 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,16 +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/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/gui.go b/cmd/mist/gui.go index 4a090a1a2..f78cb7c49 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") - - 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++ + /* + 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}) + + 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 @@ -523,9 +505,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/main.go b/cmd/mist/main.go index 376a52576..6732d5aaa 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) diff --git a/cmd/mist/ui_lib.go b/cmd/mist/ui_lib.go index 484fe6289..9fa368a4d 100644 --- a/cmd/mist/ui_lib.go +++ b/cmd/mist/ui_lib.go @@ -21,15 +21,11 @@ package main import ( - "bytes" "fmt" "io/ioutil" "path" - "strconv" - "strings" "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" @@ -77,56 +73,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/cmd/utils/cmd.go b/cmd/utils/cmd.go index 95a7f89c8..9cdd8b5d1 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -38,9 +38,10 @@ 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" + 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/websocket" "github.com/ethereum/go-ethereum/xeth" ) @@ -193,7 +194,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 { @@ -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/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 c3c7d1287..b7b5c5f85 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -66,7 +66,8 @@ type Ethereum struct { txSub event.Subscription blockSub event.Subscription - RpcServer *rpc.JsonRpcServer + RpcServer rpc.RpcServer + WsServer rpc.RpcServer keyManager *crypto.KeyManager clientIdentity p2p.ClientIdentity @@ -218,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() @@ -276,6 +281,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() diff --git a/javascript/types.go b/javascript/types.go index d85e24c88..2da4a76f8 100644 --- a/javascript/types.go +++ b/javascript/types.go @@ -70,16 +70,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/server.go b/rpc/http/server.go index 9061c33ef..2a492f465 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 <http://www.gnu.org/licenses/>. */ -package rpc +package rpchttp import ( "fmt" @@ -22,18 +22,36 @@ 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, + port: port, + }, nil +} + +type RpcHttpServer struct { quit chan bool listener net.Listener pipe *xeth.JSXEth + port int } -func (s *JsonRpcServer) exitHandler() { +func (s *RpcHttpServer) exitHandler() { out: for { select { @@ -43,63 +61,50 @@ 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.Infof("Starting RPC-HTTP server on port %d", s.port) 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(api *rpc.EthereumApi) http.Handler { fn := func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") - 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) + reserr := api.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..e6d4859d2 100644 --- a/rpc/packages.go +++ b/rpc/packages.go @@ -33,8 +33,17 @@ import ( "github.com/ethereum/go-ethereum/xeth" ) +type RpcServer interface { + Start() + Stop() +} + +func NewEthereumApi(xeth *xeth.JSXEth) *EthereumApi { + return &EthereumApi{xeth: xeth} +} + type EthereumApi struct { - pipe *xeth.JSXEth + xeth *xeth.JSXEth } func (p *EthereumApi) GetBlock(args *GetBlockArgs, reply *interface{}) error { @@ -44,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 } @@ -56,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 } @@ -67,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 } @@ -77,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 { @@ -103,29 +107,29 @@ 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 } 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 } @@ -134,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 } @@ -143,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 } @@ -153,13 +157,13 @@ 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 } 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 +207,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 } diff --git a/rpc/ws/server.go b/rpc/ws/server.go new file mode 100644 index 000000000..248ebc585 --- /dev/null +++ b/rpc/ws/server.go @@ -0,0 +1,123 @@ +/* + 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 <http://www.gnu.org/licenses/>. +*/ +package ws + +import ( + "fmt" + "net" + "net/http" + + "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(api *rpc.EthereumApi) http.Handler { + fn := func(w http.ResponseWriter, req *http.Request) { + h := sockHandler(api) + s := websocket.Server{Handler: h} + s.ServeHTTP(w, req) + } + + return http.HandlerFunc(fn) +} + +func sockHandler(api *rpc.EthereumApi) websocket.Handler { + fn := func(conn *websocket.Conn) { + for { + wslogger.Debugln("Handling request") + var reqParsed rpc.RpcRequest + + if err := websocket.JSON.Receive(conn, &reqParsed); err != nil { + wslogger.Debugln(rpc.ErrorParseRequest) + websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest}) + continue + } + + var response interface{} + 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()}) + continue + } + + wslogger.Debugf("Generated response: %T %s", response, response) + websocket.JSON.Send(conn, rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response}) + } + } + return websocket.Handler(fn) +} 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" ) +// 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 +} + type JSXEth struct { - *XEth + eth Backend + blockProcessor *core.BlockProcessor + chainManager *core.ChainManager + world *State } -func NewJSXEth(eth core.EthManager) *JSXEth { - return &JSXEth{New(eth)} +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,62 +184,28 @@ 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 + return "", 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 +func ToJSMessages(messages state.Messages) *ethutil.List { + var msgs []JSMessage + for _, m := range messages { + msgs = append(msgs, NewJSMessage(m)) } - return NewJSReciept(core.MessageCreatesContract(tx), core.AddressFromMessage(tx), tx.Hash(), tx.From()), nil + return ethutil.NewList(msgs) } -func (self *JSXEth) CompileMutan(code string) string { - data, err := self.XEth.CompileMutan(code) +func (self *JSXEth) PushTx(encodedTx string) (string, error) { + tx := types.NewTransactionFromBytes(fromHex(encodedTx)) + err := self.eth.TxPool().Add(tx) if err != nil { - return err.Error() + return "", err } - return toHex(data) -} - -func (self *JSXEth) FindInConfig(str string) string { - return toHex(self.World().Config().Get(str).Address()) -} - -func ToJSMessages(messages state.Messages) *ethutil.List { - var msgs []JSMessage - for _, m := range messages { - msgs = append(msgs, NewJSMessage(m)) + if tx.To() == nil { + addr := core.AddressFromMessage(tx) + return toHex(addr), nil } - - return ethutil.NewList(msgs) + 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" -) - -type World struct { - pipe *XEth - cfg *Config -} - -func NewWorld(pipe *XEth) *World { - world := &World{pipe, nil} - world.cfg = &Config{pipe} +import "github.com/ethereum/go-ethereum/state" - return world +type State struct { + xeth *JSXEth } -func (self *XEth) World() *World { - return self.world +func NewState(xeth *JSXEth) *State { + return &State{xeth} } -func (self *World) State() *state.StateDB { - return self.pipe.chainManager.State() +func (self *State) State() *state.StateDB { + return self.xeth.chainManager.State() } -func (self *World) Get(addr []byte) *Object { - return &Object{self.State().GetStateObject(addr)} +func (self *State) Get(addr string) *Object { + return &Object{self.State().GetStateObject(fromHex(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 -} |