moving to a better xeth

This commit is contained in:
obscuren 2015-01-28 18:14:28 +01:00
parent b46e1ca97e
commit 7f638f0b2d
13 changed files with 141 additions and 454 deletions

View File

@ -56,7 +56,9 @@ ApplicationWindow {
mainSplit.setView(wallet.view, wallet.menuItem); mainSplit.setView(wallet.view, wallet.menuItem);
newBrowserTab("http://etherian.io"); console.log(">>>>>>")
newBrowserTab("http://etherian.io");
console.log("WTF")
// Command setup // Command setup
gui.sendCommand(0) gui.sendCommand(0)

View File

@ -22,7 +22,8 @@ Rectangle {
function setBalance() { function setBalance() {
//balance.text = "<b>Balance</b>: " + eth.numberToHuman(eth.balanceAt(eth.key().address)) //balance.text = "<b>Balance</b>: " + eth.numberToHuman(eth.balanceAt(eth.key().address))
if(menuItem) 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 { ListModel {
@ -155,14 +156,6 @@ Rectangle {
model: ListModel { model: ListModel {
id: txModel id: txModel
Component.onCompleted: { 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) { function addTxs(messages) {

View File

@ -32,7 +32,6 @@ import (
"path" "path"
"runtime" "runtime"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
@ -229,41 +228,44 @@ func (gui *Gui) setInitialChain(ancientBlocks bool) {
} }
func (gui *Gui) loadAddressBook() { func (gui *Gui) loadAddressBook() {
view := gui.getObjectByName("infoView") /*
nameReg := gui.xeth.World().Config().Get("NameReg") view := gui.getObjectByName("infoView")
if nameReg != nil { nameReg := gui.xeth.World().Config().Get("NameReg")
it := nameReg.Trie().Iterator() if nameReg != nil {
for it.Next() { it := nameReg.Trie().Iterator()
if it.Key[0] != 0 { for it.Next() {
view.Call("addAddress", struct{ Name, Address string }{string(it.Key), ethutil.Bytes2Hex(it.Value)}) if it.Key[0] != 0 {
} view.Call("addAddress", struct{ Name, Address string }{string(it.Key), ethutil.Bytes2Hex(it.Value)})
}
}
} }
} */
} }
func (self *Gui) loadMergedMiningOptions() { func (self *Gui) loadMergedMiningOptions() {
view := self.getObjectByName("mergedMiningModel") /*
view := self.getObjectByName("mergedMiningModel")
mergeMining := self.xeth.World().Config().Get("MergeMining") mergeMining := self.xeth.World().Config().Get("MergeMining")
if mergeMining != nil { if mergeMining != nil {
i := 0 i := 0
it := mergeMining.Trie().Iterator() it := mergeMining.Trie().Iterator()
for it.Next() { for it.Next() {
view.Call("addMergedMiningOption", struct { view.Call("addMergedMiningOption", struct {
Checked bool Checked bool
Name, Address string Name, Address string
Id, ItemId int Id, ItemId int
}{false, string(it.Key), ethutil.Bytes2Hex(it.Value), 0, i}) }{false, string(it.Key), ethutil.Bytes2Hex(it.Value), 0, i})
i++ i++
}
} }
} */
} }
func (gui *Gui) insertTransaction(window string, tx *types.Transaction) { func (gui *Gui) insertTransaction(window string, tx *types.Transaction) {
nameReg := gui.xeth.World().Config().Get("NameReg")
addr := gui.address() addr := gui.address()
var inout string var inout string
@ -275,31 +277,11 @@ func (gui *Gui) insertTransaction(window string, tx *types.Transaction) {
var ( var (
ptx = xeth.NewJSTx(tx) ptx = xeth.NewJSTx(tx)
send = nameReg.Storage(tx.From()) send = ethutil.Bytes2Hex(tx.From())
rec = nameReg.Storage(tx.To()) rec = ethutil.Bytes2Hex(tx.To())
s, r string
) )
ptx.Sender = send
if core.MessageCreatesContract(tx) { ptx.Address = rec
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
if window == "post" { if window == "post" {
//gui.getObjectByName("transactionView").Call("addTx", ptx, inout) //gui.getObjectByName("transactionView").Call("addTx", ptx, inout)
@ -320,7 +302,7 @@ func (gui *Gui) readPreviousTransactions() {
} }
func (gui *Gui) processBlock(block *types.Block, initial bool) { 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 := xeth.NewJSBlock(block)
b.Name = name b.Name = name
@ -531,9 +513,9 @@ NumGC: %d
func (gui *Gui) setPeerInfo() { func (gui *Gui) setPeerInfo() {
gui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", gui.eth.PeerCount(), gui.eth.MaxPeers)) gui.win.Root().Call("setPeers", fmt.Sprintf("%d / %d", gui.eth.PeerCount(), gui.eth.MaxPeers))
gui.win.Root().Call("resetPeers") gui.win.Root().Call("resetPeers")
for _, peer := range gui.xeth.Peers() { //for _, peer := range gui.xeth.Peers() {
gui.win.Root().Call("addPeer", peer) //gui.win.Root().Call("addPeer", peer)
} //}
} }
func (gui *Gui) privateKey() string { func (gui *Gui) privateKey() string {

View File

@ -21,15 +21,11 @@
package main package main
import ( import (
"bytes"
"fmt" "fmt"
"path" "path"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/event/filter" "github.com/ethereum/go-ethereum/event/filter"
@ -79,56 +75,6 @@ func (self *UiLib) Notef(args []interface{}) {
guilogger.Infoln(args...) 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 { func (self *UiLib) PastPeers() *ethutil.List {
return ethutil.NewList([]string{}) return ethutil.NewList([]string{})
//return ethutil.NewList(eth.PastPeers()) //return ethutil.NewList(eth.PastPeers())

View File

@ -34,7 +34,7 @@ func GenesisBlock(db ethutil.Database) *types.Block {
statedb := state.New(genesis.Root(), db) statedb := state.New(genesis.Root(), db)
//statedb := state.New(genesis.Trie()) //statedb := state.New(genesis.Trie())
for _, addr := range []string{ for _, addr := range []string{
"51ba59315b3a95761d0863b05ccc7a7f54703d99", "dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6",
"e4157b34ea9615cfbde6b4fda419828124b70c78", "e4157b34ea9615cfbde6b4fda419828124b70c78",
"b9c015918bdaba24b4ff057a92a3873d6eb201be", "b9c015918bdaba24b4ff057a92a3873d6eb201be",
"6c386a4b26f73c802f34673f7248bb118f97424a", "6c386a4b26f73c802f34673f7248bb118f97424a",

View File

@ -219,6 +219,10 @@ func (s *Ethereum) MaxPeers() int {
return s.net.MaxPeers return s.net.MaxPeers
} }
func (s *Ethereum) Coinbase() []byte {
return nil // TODO
}
// Start the ethereum // Start the ethereum
func (s *Ethereum) Start(seed bool) error { func (s *Ethereum) Start(seed bool) error {
err := s.net.Start() err := s.net.Start()

View File

@ -82,16 +82,8 @@ func (self *JSEthereum) Block(v interface{}) otto.Value {
return otto.UndefinedValue() 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 { 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 { func (self *JSEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value {

View File

@ -85,6 +85,8 @@ func (s *RpcHttpServer) Start() {
func (s *RpcHttpServer) apiHandler(api *rpc.EthereumApi) http.Handler { func (s *RpcHttpServer) apiHandler(api *rpc.EthereumApi) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) { fn := func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
rpchttplogger.Debugln("Handling request") rpchttplogger.Debugln("Handling request")
reqParsed, reqerr := JSON.ParseRequestBody(req) reqParsed, reqerr := JSON.ParseRequestBody(req)

View File

@ -39,11 +39,11 @@ type RpcServer interface {
} }
func NewEthereumApi(xeth *xeth.JSXEth) *EthereumApi { func NewEthereumApi(xeth *xeth.JSXEth) *EthereumApi {
return &EthereumApi{pipe: xeth} return &EthereumApi{xeth: xeth}
} }
type EthereumApi struct { type EthereumApi struct {
pipe *xeth.JSXEth xeth *xeth.JSXEth
} }
func (p *EthereumApi) GetBlock(args *GetBlockArgs, reply *interface{}) error { 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 { if args.BlockNumber > 0 {
*reply = p.pipe.BlockByNumber(args.BlockNumber) *reply = p.xeth.BlockByNumber(args.BlockNumber)
} else { } else {
*reply = p.pipe.BlockByHash(args.Hash) *reply = p.xeth.BlockByHash(args.Hash)
} }
return nil return nil
} }
@ -65,7 +65,7 @@ func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) error {
if err != nil { if err != nil {
return err 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 *reply = result
return nil return nil
} }
@ -76,7 +76,7 @@ func (p *EthereumApi) Create(args *NewTxArgs, reply *interface{}) error {
return err 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 *reply = result
return nil return nil
} }
@ -86,23 +86,18 @@ func (p *EthereumApi) PushTx(args *PushTxArgs, reply *interface{}) error {
if err != nil { if err != nil {
return err return err
} }
result, _ := p.pipe.PushTx(args.Tx) result, _ := p.xeth.PushTx(args.Tx)
*reply = result *reply = result
return nil 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 { func (p *EthereumApi) GetStorageAt(args *GetStorageArgs, reply *interface{}) error {
err := args.requirements() err := args.requirements()
if err != nil { if err != nil {
return err return err
} }
state := p.pipe.World().SafeGet(ethutil.Hex2Bytes(args.Address)) state := p.xeth.State().SafeGet(args.Address)
var hx string var hx string
if strings.Index(args.Key, "0x") == 0 { 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 { func (p *EthereumApi) GetPeerCount(reply *interface{}) error {
*reply = p.pipe.PeerCount() *reply = p.xeth.PeerCount()
return nil return nil
} }
func (p *EthereumApi) GetIsListening(reply *interface{}) error { func (p *EthereumApi) GetIsListening(reply *interface{}) error {
*reply = p.pipe.IsListening() *reply = p.xeth.IsListening()
return nil return nil
} }
func (p *EthereumApi) GetCoinbase(reply *interface{}) error { func (p *EthereumApi) GetCoinbase(reply *interface{}) error {
*reply = p.pipe.CoinBase() *reply = p.xeth.Coinbase()
return nil return nil
} }
func (p *EthereumApi) GetIsMining(reply *interface{}) error { func (p *EthereumApi) GetIsMining(reply *interface{}) error {
*reply = p.pipe.IsMining() *reply = p.xeth.IsMining()
return nil return nil
} }
@ -143,7 +138,7 @@ func (p *EthereumApi) GetTxCountAt(args *GetTxCountArgs, reply *interface{}) err
if err != nil { if err != nil {
return err return err
} }
*reply = p.pipe.TxCountAt(args.Address) *reply = p.xeth.TxCountAt(args.Address)
return nil return nil
} }
@ -152,7 +147,7 @@ func (p *EthereumApi) GetBalanceAt(args *GetBalanceArgs, reply *interface{}) err
if err != nil { if err != nil {
return err 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} *reply = BalanceRes{Balance: state.Balance().String(), Address: args.Address}
return nil return nil
} }
@ -162,7 +157,7 @@ func (p *EthereumApi) GetCodeAt(args *GetCodeAtArgs, reply *interface{}) error {
if err != nil { if err != nil {
return err return err
} }
*reply = p.pipe.CodeAt(args.Address) *reply = p.xeth.CodeAt(args.Address)
return nil return nil
} }

View File

@ -1,5 +1,6 @@
package xeth package xeth
/*
import "github.com/ethereum/go-ethereum/ethutil" import "github.com/ethereum/go-ethereum/ethutil"
var cnfCtr = ethutil.Hex2Bytes("661005d2720d855f1d9976f88bb10c1a3398c77f") var cnfCtr = ethutil.Hex2Bytes("661005d2720d855f1d9976f88bb10c1a3398c77f")
@ -33,3 +34,4 @@ func (self *Config) Get(name string) *Object {
func (self *Config) Exist() bool { func (self *Config) Exist() bool {
return self.pipe.World().Get(cnfCtr) != nil return self.pipe.World().Get(cnfCtr) != nil
} }
*/

View File

@ -11,27 +11,52 @@ import (
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
) )
type JSXEth struct { // to resolve the import cycle
*XEth 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 { type JSXEth struct {
return &JSXEth{New(eth)} 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 { func (self *JSXEth) BlockByHash(strHash string) *JSBlock {
hash := fromHex(strHash) hash := fromHex(strHash)
block := self.obj.ChainManager().GetBlock(hash) block := self.chainManager.GetBlock(hash)
return NewJSBlock(block) return NewJSBlock(block)
} }
func (self *JSXEth) BlockByNumber(num int32) *JSBlock { func (self *JSXEth) BlockByNumber(num int32) *JSBlock {
if num == -1 { 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 { func (self *JSXEth) Block(v interface{}) *JSBlock {
@ -46,43 +71,32 @@ func (self *JSXEth) Block(v interface{}) *JSBlock {
return nil return nil
} }
func (self *JSXEth) Key() *JSKey {
return NewJSKey(self.obj.KeyManager().KeyPair())
}
func (self *JSXEth) Accounts() []string { 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 { func (self *JSXEth) StateObject(addr string) *JSObject {
object := &Object{self.World().safeGet(fromHex(addr))} object := &Object{self.State().safeGet(fromHex(addr))}
return NewJSObject(object) return NewJSObject(object)
} }
*/
func (self *JSXEth) PeerCount() int { func (self *JSXEth) PeerCount() int {
return self.obj.PeerCount() return self.eth.PeerCount()
}
func (self *JSXEth) Peers() []JSPeer {
var peers []JSPeer
for _, peer := range self.obj.Peers() {
peers = append(peers, *NewJSPeer(peer))
}
return peers
} }
func (self *JSXEth) IsMining() bool { func (self *JSXEth) IsMining() bool {
return self.obj.IsMining() return self.eth.IsMining()
} }
func (self *JSXEth) IsListening() bool { func (self *JSXEth) IsListening() bool {
return self.obj.IsListening() return self.eth.IsListening()
} }
func (self *JSXEth) CoinBase() string { func (self *JSXEth) Coinbase() string {
return toHex(self.obj.KeyManager().Address()) return toHex(self.eth.KeyManager().Address())
} }
func (self *JSXEth) NumberToHuman(balance string) string { 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 { 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()) return toHex(storage.Bytes())
} }
func (self *JSXEth) BalanceAt(addr string) string { 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 { 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 { 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 { 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 { 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) { func (self *JSXEth) Execute(addr, value, gas, price, data string) (string, error) {
ret, err := self.ExecuteObject(&Object{ return "", nil
self.World().safeGet(fromHex(addr))},
fromHex(data),
ethutil.NewValue(value),
ethutil.NewValue(gas),
ethutil.NewValue(price),
)
return toHex(ret), err
} }
type KeyVal struct { type KeyVal struct {
@ -141,7 +147,7 @@ type KeyVal struct {
func (self *JSXEth) EachStorage(addr string) string { func (self *JSXEth) EachStorage(addr string) string {
var values []KeyVal var values []KeyVal
object := self.World().SafeGet(fromHex(addr)) object := self.State().SafeGet(addr)
it := object.Trie().Iterator() it := object.Trie().Iterator()
for it.Next() { for it.Next() {
values = append(values, KeyVal{toHex(it.Key), toHex(it.Value)}) 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) { func (self *JSXEth) Transact(key, toStr, valueStr, gasStr, gasPriceStr, codeStr string) (string, error) {
var ( return "", nil
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())
} }
func ToJSMessages(messages state.Messages) *ethutil.List { func ToJSMessages(messages state.Messages) *ethutil.List {
@ -237,3 +195,17 @@ func ToJSMessages(messages state.Messages) *ethutil.List {
return ethutil.NewList(msgs) 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
}

View File

@ -1,63 +1,32 @@
package xeth package xeth
import ( import "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/state"
)
type World struct { type State struct {
pipe *XEth xeth *JSXEth
cfg *Config
} }
func NewWorld(pipe *XEth) *World { func NewState(xeth *JSXEth) *State {
world := &World{pipe, nil} return &State{xeth}
world.cfg = &Config{pipe}
return world
} }
func (self *XEth) World() *World { func (self *State) State() *state.StateDB {
return self.world return self.xeth.chainManager.State()
} }
func (self *World) State() *state.StateDB { func (self *State) Get(addr string) *Object {
return self.pipe.chainManager.State() return &Object{self.State().GetStateObject(fromHex(addr))}
} }
func (self *World) Get(addr []byte) *Object { func (self *State) SafeGet(addr string) *Object {
return &Object{self.State().GetStateObject(addr)}
}
func (self *World) SafeGet(addr []byte) *Object {
return &Object{self.safeGet(addr)} return &Object{self.safeGet(addr)}
} }
func (self *World) safeGet(addr []byte) *state.StateObject { func (self *State) safeGet(addr string) *state.StateObject {
object := self.State().GetStateObject(addr) object := self.State().GetStateObject(fromHex(addr))
if object == nil { if object == nil {
object = state.NewStateObject(addr, self.pipe.obj.Db()) object = state.NewStateObject(fromHex(addr), self.xeth.eth.Db())
} }
return object 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
}

View File

@ -4,178 +4,6 @@ package xeth
* eXtended ETHereum * eXtended ETHereum
*/ */
import ( import "github.com/ethereum/go-ethereum/logger"
"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"
)
var pipelogger = logger.NewLogger("XETH") 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
}