Merge pull request #776 from fjl/win32-build-fixes

Win32 build fixes
pull/747/merge
Jeffrey Wilcke 10 years ago
commit 35595560f0
  1. 25
      cmd/geth/admin.go
  2. 255
      cmd/geth/js_test.go
  3. 11
      common/bytes.go
  4. 14
      common/bytes_test.go
  5. 23
      miner/worker.go
  6. 7
      p2p/server.go

@ -3,7 +3,6 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"os"
"time" "time"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
@ -318,7 +317,7 @@ func (js *jsre) newAccount(call otto.FunctionCall) otto.Value {
fmt.Printf("Could not create the account: %v", err) fmt.Printf("Could not create the account: %v", err)
return otto.UndefinedValue() return otto.UndefinedValue()
} }
return js.re.ToVal(common.Bytes2Hex(acct.Address)) return js.re.ToVal("0x" + common.Bytes2Hex(acct.Address))
} }
func (js *jsre) nodeInfo(call otto.FunctionCall) otto.Value { func (js *jsre) nodeInfo(call otto.FunctionCall) otto.Value {
@ -334,33 +333,15 @@ func (js *jsre) importChain(call otto.FunctionCall) otto.Value {
fmt.Println("err: require file name") fmt.Println("err: require file name")
return otto.FalseValue() return otto.FalseValue()
} }
fn, err := call.Argument(0).ToString() fn, err := call.Argument(0).ToString()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
return otto.FalseValue() return otto.FalseValue()
} }
if err := utils.ImportChain(js.ethereum.ChainManager(), fn); err != nil {
var fh *os.File fmt.Println("Import error: ", err)
fh, err = os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
if err != nil {
fmt.Println(err)
return otto.FalseValue() return otto.FalseValue()
} }
defer fh.Close()
var blocks types.Blocks
if err = rlp.Decode(fh, &blocks); err != nil {
fmt.Println(err)
return otto.FalseValue()
}
js.ethereum.ChainManager().Reset()
if err = js.ethereum.ChainManager().InsertChain(blocks); err != nil {
fmt.Println(err)
return otto.FalseValue()
}
return otto.TrueValue() return otto.TrueValue()
} }

@ -3,260 +3,141 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"path/filepath"
"os" "os"
"path" "path"
"testing" "testing"
"github.com/robertkrimen/otto"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth"
"runtime"
"regexp"
"strconv"
) )
var port = 30300 var port = 30300
func testJEthRE(t *testing.T) (repl *jsre, ethereum *eth.Ethereum, err error) { func testJEthRE(t *testing.T) (*jsre, *eth.Ethereum) {
os.RemoveAll("/tmp/eth/") tmp, err := ioutil.TempDir("", "geth-test")
err = os.MkdirAll("/tmp/eth/keys/e273f01c99144c438695e10f24926dc1f9fbf62d/", os.ModePerm)
if err != nil {
t.Errorf("%v", err)
return
}
err = os.MkdirAll("/tmp/eth/data", os.ModePerm)
if err != nil { if err != nil {
t.Errorf("%v", err) t.Fatal(err)
return
} }
// FIXME: this does not work ATM defer os.RemoveAll(tmp)
ks := crypto.NewKeyStorePlain("/tmp/eth/keys")
ioutil.WriteFile("/tmp/eth/keys/e273f01c99144c438695e10f24926dc1f9fbf62d/e273f01c99144c438695e10f24926dc1f9fbf62d",
[]byte(`{"Id":"RhRXD+fNRKS4jx+7ZfEsNA==","Address":"4nPwHJkUTEOGleEPJJJtwfn79i0=","PrivateKey":"h4ACVpe74uIvi5Cg/2tX/Yrm2xdr3J7QoMbMtNX2CNc="}`), os.ModePerm)
port++ ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keys"))
ethereum, err = eth.New(&eth.Config{ ethereum, err := eth.New(&eth.Config{
DataDir: "/tmp/eth", DataDir: tmp,
AccountManager: accounts.NewManager(ks), AccountManager: accounts.NewManager(ks),
Port: fmt.Sprintf("%d", port), MaxPeers: 0,
MaxPeers: 10,
Name: "test", Name: "test",
}) })
if err != nil { if err != nil {
t.Errorf("%v", err) t.Fatal("%v", err)
return
} }
assetPath := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext") assetPath := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
repl = newJSRE(ethereum, assetPath, false) repl := newJSRE(ethereum, assetPath, false)
return return repl, ethereum
} }
func TestNodeInfo(t *testing.T) { func TestNodeInfo(t *testing.T) {
repl, ethereum, err := testJEthRE(t) repl, ethereum := testJEthRE(t)
if err != nil { if err := ethereum.Start(); err != nil {
t.Errorf("error creating jsre, got %v", err) t.Fatalf("error starting ethereum: %v", err)
return
}
err = ethereum.Start()
if err != nil {
t.Errorf("error starting ethereum: %v", err)
return
} }
defer ethereum.Stop() defer ethereum.Stop()
val, err := repl.re.Run("admin.nodeInfo()") want := `{"DiscPort":0,"IP":"0.0.0.0","ListenAddr":"","Name":"test","NodeID":"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","NodeUrl":"enode://00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000@0.0.0.0:0","TCPPort":0,"Td":"0"}`
if err != nil { checkEvalJSON(t, repl, `admin.nodeInfo()`, want)
t.Errorf("expected no error, got %v", err)
}
exp, err := val.Export()
if err != nil {
t.Errorf("expected no error, got %v", err)
}
nodeInfo, ok := exp.(*eth.NodeInfo)
if !ok {
t.Errorf("expected nodeInfo, got %v", err)
}
exp = "test"
got := nodeInfo.Name
if exp != got {
t.Errorf("expected %v, got %v", exp, got)
}
exp = 30301
port := nodeInfo.DiscPort
if exp != port {
t.Errorf("expected %v, got %v", exp, port)
}
exp = 30301
port = nodeInfo.TCPPort
if exp != port {
t.Errorf("expected %v, got %v", exp, port)
}
} }
func TestAccounts(t *testing.T) { func TestAccounts(t *testing.T) {
repl, ethereum, err := testJEthRE(t) repl, ethereum := testJEthRE(t)
if err != nil { if err := ethereum.Start(); err != nil {
t.Errorf("error creating jsre, got %v", err) t.Fatalf("error starting ethereum: %v", err)
return
}
err = ethereum.Start()
if err != nil {
t.Errorf("error starting ethereum: %v", err)
return
} }
defer ethereum.Stop() defer ethereum.Stop()
val, err := repl.re.Run("eth.coinbase") checkEvalJSON(t, repl, `eth.accounts`, `[]`)
if err != nil { checkEvalJSON(t, repl, `eth.coinbase`, `"0x"`)
t.Errorf("expected no error, got %v", err)
}
pp, err := repl.re.PrettyPrint(val)
if err != nil {
t.Errorf("%v", err)
}
if !val.IsString() {
t.Errorf("incorrect type, expected string, got %v: %v", val, pp)
}
strVal, _ := val.ToString()
expected := "0xe273f01c99144c438695e10f24926dc1f9fbf62d"
if strVal != expected {
t.Errorf("incorrect result, expected %s, got %v", expected, strVal)
}
val, err = repl.re.Run(`admin.newAccount("password")`) val, err := repl.re.Run(`admin.newAccount("password")`)
if err != nil { if err != nil {
t.Errorf("expected no error, got %v", err) t.Errorf("expected no error, got %v", err)
} }
addr, err := val.ToString() addr := val.String()
if err != nil { if !regexp.MustCompile(`0x[0-9a-f]{40}`).MatchString(addr) {
t.Errorf("expected string, got %v", err) t.Errorf("address not hex: %q", addr)
}
val, err = repl.re.Run("eth.accounts")
if err != nil {
t.Errorf("expected no error, got %v", err)
}
exp, err := val.Export()
if err != nil {
t.Errorf("expected no error, got %v", err)
}
interfaceAddr, ok := exp.([]interface{})
if !ok {
t.Errorf("expected []string, got %T", exp)
}
addrs := make([]string, len(interfaceAddr))
for i, addr := range interfaceAddr {
var ok bool
if addrs[i], ok = addr.(string); !ok {
t.Errorf("expected addrs[%d] to be string. Got %T instead", i, addr)
}
}
if len(addrs) != 2 || (addr != addrs[0][2:] && addr != addrs[1][2:]) {
t.Errorf("expected addrs == [<default>, <new>], got %v (%v)", addrs, addr)
} }
checkEvalJSON(t, repl, `eth.accounts`, `["` + addr + `"]`)
checkEvalJSON(t, repl, `eth.coinbase`, `"` + addr + `"`)
} }
func TestBlockChain(t *testing.T) { func TestBlockChain(t *testing.T) {
repl, ethereum, err := testJEthRE(t) repl, ethereum := testJEthRE(t)
if err != nil { if err := ethereum.Start(); err != nil {
t.Errorf("error creating jsre, got %v", err) t.Fatalf("error starting ethereum: %v", err)
return
}
err = ethereum.Start()
if err != nil {
t.Errorf("error starting ethereum: %v", err)
return
} }
defer ethereum.Stop() defer ethereum.Stop()
// should get current block // get current block dump before export/import.
val0, err := repl.re.Run("admin.debug.dumpBlock()") val, err := repl.re.Run("JSON.stringify(admin.debug.dumpBlock())")
if err != nil { if err != nil {
t.Errorf("expected no error, got %v", err) t.Errorf("expected no error, got %v", err)
} }
beforeExport := val.String()
fn := "/tmp/eth/data/blockchain.0" // do the export
_, err = repl.re.Run("admin.export(\"" + fn + "\")") tmp, err := ioutil.TempDir("", "geth-test-export")
if err != nil { if err != nil {
t.Errorf("expected no error, got %v", err) t.Fatal(err)
}
if _, err = os.Stat(fn); err != nil {
t.Errorf("expected no error on file, got %v", err)
} }
defer os.RemoveAll(tmp)
tmpfile := filepath.Join(tmp, "export.chain")
tmpfileq := strconv.Quote(tmpfile)
_, err = repl.re.Run("admin.import(\"" + fn + "\")") checkEvalJSON(t, repl, `admin.export(` + tmpfileq + `)`, `true`)
if err != nil { if _, err := os.Stat(tmpfile); err != nil {
t.Errorf("expected no error, got %v", err) t.Fatal(err)
} }
var val1 otto.Value // check import, verify that dumpBlock gives the same result.
checkEvalJSON(t, repl, `admin.import(` + tmpfileq + `)`, `true`)
// should get current block checkEvalJSON(t, repl, `admin.debug.dumpBlock()`, beforeExport)
val1, err = repl.re.Run("admin.debug.dumpBlock()")
if err != nil {
t.Errorf("expected no error, got %v", err)
}
// FIXME: neither != , nor reflect.DeepEqual works, doing string comparison
v0 := fmt.Sprintf("%v", val0)
v1 := fmt.Sprintf("%v", val1)
if v0 != v1 {
t.Errorf("expected same head after export-import, got %v (!=%v)", v1, v0)
}
} }
func TestMining(t *testing.T) { func TestMining(t *testing.T) {
repl, ethereum, err := testJEthRE(t) repl, ethereum := testJEthRE(t)
if err != nil { if err := ethereum.Start(); err != nil {
t.Errorf("error creating jsre, got %v", err) t.Fatalf("error starting ethereum: %v", err)
return
}
err = ethereum.Start()
if err != nil {
t.Errorf("error starting ethereum: %v", err)
return
} }
defer ethereum.Stop() defer ethereum.Stop()
val, err := repl.re.Run("eth.mining") checkEvalJSON(t, repl, `eth.mining`, `false`)
if err != nil {
t.Errorf("expected no error, got %v", err)
}
var mining bool
mining, err = val.ToBoolean()
if err != nil {
t.Errorf("expected boolean, got %v", err)
}
if mining {
t.Errorf("expected false (not mining), got true")
}
} }
func TestRPC(t *testing.T) { func TestRPC(t *testing.T) {
repl, ethereum, err := testJEthRE(t) repl, ethereum := testJEthRE(t)
if err != nil { if err := ethereum.Start(); err != nil {
t.Errorf("error creating jsre, got %v", err)
return
}
err = ethereum.Start()
if err != nil {
t.Errorf("error starting ethereum: %v", err) t.Errorf("error starting ethereum: %v", err)
return return
} }
defer ethereum.Stop() defer ethereum.Stop()
val, err := repl.re.Run(`admin.startRPC("127.0.0.1", 5004)`) checkEvalJSON(t, repl, `admin.startRPC("127.0.0.1", 5004)`, `true`)
if err != nil { }
t.Errorf("expected no error, got %v", err)
func checkEvalJSON(t *testing.T, re *jsre, expr, want string) error {
val, err := re.re.Run("JSON.stringify("+ expr + ")")
if err == nil && val.String() != want {
err = fmt.Errorf("Output mismatch for `%s`:\ngot: %s\nwant: %s", expr, val.String(), want)
} }
success, _ := val.ToBoolean() if err != nil {
if !success { _, file, line, _ := runtime.Caller(1)
t.Errorf("expected true (started), got false") file = path.Base(file)
fmt.Printf("\t%s:%d: %v\n", file, line, err)
t.Fail()
} }
return err
} }

@ -106,17 +106,6 @@ func ReadVarInt(buff []byte) (ret uint64) {
return return
} }
// Binary length
//
// Returns the true binary length of the given number
func BinaryLength(num int) int {
if num == 0 {
return 0
}
return 1 + BinaryLength(num>>8)
}
// Copy bytes // Copy bytes
// //
// Returns an exact copy of the provided bytes // Returns an exact copy of the provided bytes

@ -79,20 +79,6 @@ func (s *BytesSuite) TestReadVarInt(c *checker.C) {
c.Assert(res1, checker.Equals, exp1) c.Assert(res1, checker.Equals, exp1)
} }
func (s *BytesSuite) TestBinaryLength(c *checker.C) {
data1 := 0
data2 := 920987656789
exp1 := 0
exp2 := 5
res1 := BinaryLength(data1)
res2 := BinaryLength(data2)
c.Assert(res1, checker.Equals, exp1)
c.Assert(res2, checker.Equals, exp2)
}
func (s *BytesSuite) TestCopyBytes(c *checker.C) { func (s *BytesSuite) TestCopyBytes(c *checker.C) {
data1 := []byte{1, 2, 3, 4} data1 := []byte{1, 2, 3, 4}
exp1 := []byte{1, 2, 3, 4} exp1 := []byte{1, 2, 3, 4}

@ -66,7 +66,6 @@ type worker struct {
mux *event.TypeMux mux *event.TypeMux
quit chan struct{} quit chan struct{}
pow pow.PoW pow pow.PoW
atWork int64
eth core.Backend eth core.Backend
chain *core.ChainManager chain *core.ChainManager
@ -84,7 +83,9 @@ type worker struct {
txQueueMu sync.Mutex txQueueMu sync.Mutex
txQueue map[common.Hash]*types.Transaction txQueue map[common.Hash]*types.Transaction
mining int64 // atomic status counters
mining int32
atWork int32
} }
func newWorker(coinbase common.Address, eth core.Backend) *worker { func newWorker(coinbase common.Address, eth core.Backend) *worker {
@ -127,19 +128,19 @@ func (self *worker) start() {
agent.Start() agent.Start()
} }
atomic.StoreInt64(&self.mining, 1) atomic.StoreInt32(&self.mining, 1)
} }
func (self *worker) stop() { func (self *worker) stop() {
if atomic.LoadInt64(&self.mining) == 1 { if atomic.LoadInt32(&self.mining) == 1 {
// stop all agents // stop all agents
for _, agent := range self.agents { for _, agent := range self.agents {
agent.Stop() agent.Stop()
} }
} }
atomic.StoreInt64(&self.mining, 0) atomic.StoreInt32(&self.mining, 0)
atomic.StoreInt64(&self.atWork, 0) atomic.StoreInt32(&self.atWork, 0)
} }
func (self *worker) register(agent Agent) { func (self *worker) register(agent Agent) {
@ -162,7 +163,7 @@ out:
self.possibleUncles[ev.Block.Hash()] = ev.Block self.possibleUncles[ev.Block.Hash()] = ev.Block
self.uncleMu.Unlock() self.uncleMu.Unlock()
case core.TxPreEvent: case core.TxPreEvent:
if atomic.LoadInt64(&self.mining) == 0 { if atomic.LoadInt32(&self.mining) == 0 {
self.commitNewWork() self.commitNewWork()
} }
} }
@ -177,7 +178,7 @@ out:
func (self *worker) wait() { func (self *worker) wait() {
for { for {
for block := range self.recv { for block := range self.recv {
atomic.AddInt64(&self.atWork, -1) atomic.AddInt32(&self.atWork, -1)
if block == nil { if block == nil {
continue continue
@ -205,13 +206,13 @@ func (self *worker) wait() {
} }
func (self *worker) push() { func (self *worker) push() {
if atomic.LoadInt64(&self.mining) == 1 { if atomic.LoadInt32(&self.mining) == 1 {
self.current.block.Header().GasUsed = self.current.totalUsedGas self.current.block.Header().GasUsed = self.current.totalUsedGas
self.current.block.SetRoot(self.current.state.Root()) self.current.block.SetRoot(self.current.state.Root())
// push new work to agents // push new work to agents
for _, agent := range self.agents { for _, agent := range self.agents {
atomic.AddInt64(&self.atWork, 1) atomic.AddInt32(&self.atWork, 1)
if agent.Work() != nil { if agent.Work() != nil {
agent.Work() <- self.current.block.Copy() agent.Work() <- self.current.block.Copy()
@ -320,7 +321,7 @@ func (self *worker) commitNewWork() {
} }
// We only care about logging if we're actually mining // We only care about logging if we're actually mining
if atomic.LoadInt64(&self.mining) == 1 { if atomic.LoadInt32(&self.mining) == 1 {
glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles\n", self.current.block.Number(), tcount, len(uncles)) glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles\n", self.current.block.Number(), tcount, len(uncles))
} }

@ -283,6 +283,11 @@ func (srv *Server) Stop() {
// Self returns the local node's endpoint information. // Self returns the local node's endpoint information.
func (srv *Server) Self() *discover.Node { func (srv *Server) Self() *discover.Node {
srv.lock.RLock()
defer srv.lock.RUnlock()
if !srv.running {
return &discover.Node{IP: net.ParseIP("0.0.0.0")}
}
return srv.ntab.Self() return srv.ntab.Self()
} }
@ -471,7 +476,7 @@ func (srv *Server) checkPeer(id discover.NodeID) (bool, DiscReason) {
return false, DiscTooManyPeers return false, DiscTooManyPeers
case srv.peers[id] != nil: case srv.peers[id] != nil:
return false, DiscAlreadyConnected return false, DiscAlreadyConnected
case id == srv.Self().ID: case id == srv.ntab.Self().ID:
return false, DiscSelf return false, DiscSelf
default: default:
return true, 0 return true, 0

Loading…
Cancel
Save