modified logging API

- package vars for tagged loggers
- weed out spurious fmt.PrintX and log.PrintX logging
- tried to second guess loglevel for some :)
This commit is contained in:
zelig 2014-06-23 12:54:10 +01:00
parent 8e9cc36979
commit b9e8a3e024
13 changed files with 132 additions and 111 deletions

View File

@ -4,11 +4,13 @@ import (
"bytes" "bytes"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethwire" "github.com/ethereum/eth-go/ethwire"
"log" "github.com/ethereum/eth-go/ethlog"
"math" "math"
"math/big" "math/big"
) )
var chainlogger = ethlog.NewLogger("CHAIN")
type BlockChain struct { type BlockChain struct {
Ethereum EthManager Ethereum EthManager
// The famous, the fabulous Mister GENESIIIIIIS (block) // The famous, the fabulous Mister GENESIIIIIIS (block)
@ -129,38 +131,38 @@ func (bc *BlockChain) FindCanonicalChain(blocks []*Block, commonBlockHash []byte
// Start with the newest block we got, all the way back to the common block we both know // Start with the newest block we got, all the way back to the common block we both know
for _, block := range blocks { for _, block := range blocks {
if bytes.Compare(block.Hash(), commonBlockHash) == 0 { if bytes.Compare(block.Hash(), commonBlockHash) == 0 {
log.Println("[CHAIN] We have found the common parent block, breaking") chainlogger.Infoln("[CHAIN] We have found the common parent block, breaking")
break break
} }
chainDifficulty.Add(chainDifficulty, bc.CalculateBlockTD(block)) chainDifficulty.Add(chainDifficulty, bc.CalculateBlockTD(block))
} }
log.Println("[CHAIN] Incoming chain difficulty:", chainDifficulty) chainlogger.Infoln("Incoming chain difficulty:", chainDifficulty)
curChainDifficulty := new(big.Int) curChainDifficulty := new(big.Int)
block := bc.CurrentBlock block := bc.CurrentBlock
for i := 0; block != nil; block = bc.GetBlock(block.PrevHash) { for i := 0; block != nil; block = bc.GetBlock(block.PrevHash) {
i++ i++
if bytes.Compare(block.Hash(), commonBlockHash) == 0 { if bytes.Compare(block.Hash(), commonBlockHash) == 0 {
log.Println("[CHAIN] We have found the common parent block, breaking") chainlogger.Infoln("We have found the common parent block, breaking")
break break
} }
anOtherBlock := bc.GetBlock(block.PrevHash) anOtherBlock := bc.GetBlock(block.PrevHash)
if anOtherBlock == nil { if anOtherBlock == nil {
// We do not want to count the genesis block for difficulty since that's not being sent // We do not want to count the genesis block for difficulty since that's not being sent
log.Println("[CHAIN] At genesis block, breaking") chainlogger.Infoln("At genesis block, breaking")
break break
} }
curChainDifficulty.Add(curChainDifficulty, bc.CalculateBlockTD(block)) curChainDifficulty.Add(curChainDifficulty, bc.CalculateBlockTD(block))
} }
log.Println("[CHAIN] Current chain difficulty:", curChainDifficulty) chainlogger.Infoln("Current chain difficulty:", curChainDifficulty)
if chainDifficulty.Cmp(curChainDifficulty) == 1 { if chainDifficulty.Cmp(curChainDifficulty) == 1 {
log.Printf("[CHAIN] The incoming Chain beat our asses, resetting to block: %x", commonBlockHash) chainlogger.Infof("The incoming Chain beat our asses, resetting to block: %x", commonBlockHash)
bc.ResetTillBlockHash(commonBlockHash) bc.ResetTillBlockHash(commonBlockHash)
return false return false
} else { } else {
log.Println("[CHAIN] Our chain showed the incoming chain who is boss. Ignoring.") chainlogger.Infoln("Our chain showed the incoming chain who is boss. Ignoring.")
return true return true
} }
} }
@ -195,7 +197,7 @@ func (bc *BlockChain) ResetTillBlockHash(hash []byte) error {
var block *Block var block *Block
for ; block != nil; block = bc.GetBlock(block.PrevHash) { for ; block != nil; block = bc.GetBlock(block.PrevHash) {
if bytes.Compare(block.Hash(), hash) == 0 { if bytes.Compare(block.Hash(), hash) == 0 {
log.Println("[CHAIN] We have arrived at the the common parent block, breaking") chainlogger.Infoln("We have arrived at the the common parent block, breaking")
break break
} }
err = ethutil.Config.Db.Delete(block.Hash()) err = ethutil.Config.Db.Delete(block.Hash())
@ -203,7 +205,7 @@ func (bc *BlockChain) ResetTillBlockHash(hash []byte) error {
return err return err
} }
} }
log.Println("[CHAIN] Split chain deleted and reverted to common parent block.") chainlogger.Infoln("Split chain deleted and reverted to common parent block.")
return nil return nil
} }
@ -286,7 +288,7 @@ func (bc *BlockChain) setLastBlock() {
bc.LastBlockHash = block.Hash() bc.LastBlockHash = block.Hash()
bc.LastBlockNumber = block.Number.Uint64() bc.LastBlockNumber = block.Number.Uint64()
ethutil.Config.Log.Infof("[CHAIN] Last known block height #%d\n", bc.LastBlockNumber) chainlogger.Infof("Last known block height #%d\n", bc.LastBlockNumber)
} else { } else {
AddTestNetFunds(bc.genesisBlock) AddTestNetFunds(bc.genesisBlock)
@ -294,14 +296,14 @@ func (bc *BlockChain) setLastBlock() {
// Prepare the genesis block // Prepare the genesis block
bc.Add(bc.genesisBlock) bc.Add(bc.genesisBlock)
//log.Printf("root %x\n", bm.bc.genesisBlock.State().Root) //chainlogger.Infof("root %x\n", bm.bc.genesisBlock.State().Root)
//bm.bc.genesisBlock.PrintHash() //bm.bc.genesisBlock.PrintHash()
} }
// Set the last know difficulty (might be 0x0 as initial value, Genesis) // Set the last know difficulty (might be 0x0 as initial value, Genesis)
bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD()) bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD())
ethutil.Config.Log.Infof("Last block: %x\n", bc.CurrentBlock.Hash()) chainlogger.Infof("Last block: %x\n", bc.CurrentBlock.Hash())
} }
func (bc *BlockChain) SetTotalDifficulty(td *big.Int) { func (bc *BlockChain) SetTotalDifficulty(td *big.Int) {
@ -358,6 +360,6 @@ func (bc *BlockChain) writeBlockInfo(block *Block) {
func (bc *BlockChain) Stop() { func (bc *BlockChain) Stop() {
if bc.CurrentBlock != nil { if bc.CurrentBlock != nil {
log.Println("[CHAIN] Stopped") chainlogger.Infoln("Stopped")
} }
} }

View File

@ -2,14 +2,16 @@ package ethchain
import ( import (
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethlog"
"github.com/obscuren/sha3" "github.com/obscuren/sha3"
"hash" "hash"
"log"
"math/big" "math/big"
"math/rand" "math/rand"
"time" "time"
) )
var powlogger = ethlog.NewLogger("POW")
type PoW interface { type PoW interface {
Search(block *Block, reactChan chan ethutil.React) []byte Search(block *Block, reactChan chan ethutil.React) []byte
Verify(hash []byte, diff *big.Int, nonce []byte) bool Verify(hash []byte, diff *big.Int, nonce []byte) bool
@ -29,14 +31,14 @@ func (pow *EasyPow) Search(block *Block, reactChan chan ethutil.React) []byte {
for { for {
select { select {
case <-reactChan: case <-reactChan:
//ethutil.Config.Log.Infoln("[POW] Received reactor event; breaking out.") //powlogger.Infoln("Received reactor event; breaking out.")
return nil return nil
default: default:
i++ i++
if i%1234567 == 0 { if i%1234567 == 0 {
elapsed := time.Now().UnixNano() - start elapsed := time.Now().UnixNano() - start
hashes := ((float64(1e9) / float64(elapsed)) * float64(i)) / 1000 hashes := ((float64(1e9) / float64(elapsed)) * float64(i)) / 1000
ethutil.Config.Log.Infoln("[POW] Hashing @", int64(hashes), "khash") powlogger.Infoln("Hashing @", int64(hashes), "khash")
} }
sha := ethutil.Sha3Bin(big.NewInt(r.Int63()).Bytes()) sha := ethutil.Sha3Bin(big.NewInt(r.Int63()).Bytes())
@ -81,7 +83,7 @@ func (dag *Dagger) Find(obj *big.Int, resChan chan int64) {
rnd := r.Int63() rnd := r.Int63()
res := dag.Eval(big.NewInt(rnd)) res := dag.Eval(big.NewInt(rnd))
log.Printf("rnd %v\nres %v\nobj %v\n", rnd, res, obj) powlogger.Infof("rnd %v\nres %v\nobj %v\n", rnd, res, obj)
if res.Cmp(obj) < 0 { if res.Cmp(obj) < 0 {
// Post back result on the channel // Post back result on the channel
resChan <- rnd resChan <- rnd

View File

@ -125,7 +125,7 @@ func (self *State) GetOrNewStateObject(addr []byte) *StateObject {
} }
func (self *State) NewStateObject(addr []byte) *StateObject { func (self *State) NewStateObject(addr []byte) *StateObject {
ethutil.Config.Log.Printf(ethutil.LogLevelInfo, "(+) %x\n", addr) statelogger.Infof("(+) %x\n", addr)
stateObject := NewStateObject(addr) stateObject := NewStateObject(addr)
self.stateObjects[string(addr)] = stateObject self.stateObjects[string(addr)] = stateObject

View File

@ -3,14 +3,16 @@ package ethchain
import ( import (
"bytes" "bytes"
"container/list" "container/list"
"fmt"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethwire" "github.com/ethereum/eth-go/ethwire"
"github.com/ethereum/eth-go/ethlog"
"math/big" "math/big"
"sync" "sync"
"time" "time"
) )
var statelogger = ethlog.NewLogger("STATE")
type BlockProcessor interface { type BlockProcessor interface {
ProcessBlock(block *Block) ProcessBlock(block *Block)
} }
@ -120,7 +122,7 @@ done:
break done break done
default: default:
ethutil.Config.Log.Infoln(err) statelogger.Infoln(err)
} }
} }
@ -186,29 +188,29 @@ func (sm *StateManager) ProcessBlock(state *State, parent, block *Block, dontRea
if err != nil { if err != nil {
if len(receipts) == len(block.Receipts()) { if len(receipts) == len(block.Receipts()) {
for i, receipt := range block.Receipts() { for i, receipt := range block.Receipts() {
ethutil.Config.Log.Debugf("diff (r) %v ~ %x <=> (c) %v ~ %x (%x)\n", receipt.CumulativeGasUsed, receipt.PostState[0:4], receipts[i].CumulativeGasUsed, receipts[i].PostState[0:4], receipt.Tx.Hash()) statelogger.Debugf("diff (r) %v ~ %x <=> (c) %v ~ %x (%x)\n", receipt.CumulativeGasUsed, receipt.PostState[0:4], receipts[i].CumulativeGasUsed, receipts[i].PostState[0:4], receipt.Tx.Hash())
} }
} else { } else {
ethutil.Config.Log.Debugln("Unable to print receipt diff. Length didn't match", len(receipts), "for", len(block.Receipts())) statelogger.Warnln("Unable to print receipt diff. Length didn't match", len(receipts), "for", len(block.Receipts()))
} }
} }
}() }()
// Block validation // Block validation
if err = sm.ValidateBlock(block); err != nil { if err = sm.ValidateBlock(block); err != nil {
fmt.Println("[SM] Error validating block:", err) statelogger.Errorln("Error validating block:", err)
return err return err
} }
// I'm not sure, but I don't know if there should be thrown // I'm not sure, but I don't know if there should be thrown
// any errors at this time. // any errors at this time.
if err = sm.AccumelateRewards(state, block); err != nil { if err = sm.AccumelateRewards(state, block); err != nil {
fmt.Println("[SM] Error accumulating reward", err) statelogger.Errorln("Error accumulating reward", err)
return err return err
} }
if !block.State().Cmp(state) { if !block.State().Cmp(state) {
err = fmt.Errorf("Invalid merkle root.\nrec: %x\nis: %x", block.State().trie.Root, state.trie.Root) statelogger.Errorf("Invalid merkle root.\nrec: %x\nis: %x", block.State().trie.Root, state.trie.Root)
return return
} }
@ -221,7 +223,7 @@ func (sm *StateManager) ProcessBlock(state *State, parent, block *Block, dontRea
sm.bc.Add(block) sm.bc.Add(block)
sm.notifyChanges(state) sm.notifyChanges(state)
ethutil.Config.Log.Infof("[STATE] Added block #%d (%x)\n", block.Number, block.Hash()) statelogger.Infof("Added block #%d (%x)\n", block.Number, block.Hash())
if dontReact == false { if dontReact == false {
sm.Ethereum.Reactor().Post("newBlock", block) sm.Ethereum.Reactor().Post("newBlock", block)
@ -232,7 +234,7 @@ func (sm *StateManager) ProcessBlock(state *State, parent, block *Block, dontRea
sm.Ethereum.TxPool().RemoveInvalid(state) sm.Ethereum.TxPool().RemoveInvalid(state)
} else { } else {
fmt.Println("total diff failed") statelogger.Errorln("total diff failed")
} }
return nil return nil

View File

@ -124,13 +124,13 @@ func (c *StateObject) ReturnGas(gas, price *big.Int, state *State) {
func (c *StateObject) AddAmount(amount *big.Int) { func (c *StateObject) AddAmount(amount *big.Int) {
c.SetAmount(new(big.Int).Add(c.Amount, amount)) c.SetAmount(new(big.Int).Add(c.Amount, amount))
ethutil.Config.Log.Printf(ethutil.LogLevelInfo, "%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.Amount, amount) statelogger.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.Amount, amount)
} }
func (c *StateObject) SubAmount(amount *big.Int) { func (c *StateObject) SubAmount(amount *big.Int) {
c.SetAmount(new(big.Int).Sub(c.Amount, amount)) c.SetAmount(new(big.Int).Sub(c.Amount, amount))
ethutil.Config.Log.Printf(ethutil.LogLevelInfo, "%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.Amount, amount) statelogger.Infof("%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.Amount, amount)
} }
func (c *StateObject) SetAmount(amount *big.Int) { func (c *StateObject) SetAmount(amount *big.Int) {
@ -151,7 +151,7 @@ func (c *StateObject) ConvertGas(gas, price *big.Int) error {
func (self *StateObject) SetGasPool(gasLimit *big.Int) { func (self *StateObject) SetGasPool(gasLimit *big.Int) {
self.gasPool = new(big.Int).Set(gasLimit) self.gasPool = new(big.Int).Set(gasLimit)
ethutil.Config.Log.Printf(ethutil.LogLevelSystem, "%x: fuel (+ %v)", self.Address(), self.gasPool) statelogger.Infof("%x: fuel (+ %v)", self.Address(), self.gasPool)
} }
func (self *StateObject) BuyGas(gas, price *big.Int) error { func (self *StateObject) BuyGas(gas, price *big.Int) error {

View File

@ -2,7 +2,6 @@ package ethchain
import ( import (
"fmt" "fmt"
"github.com/ethereum/eth-go/ethutil"
"math/big" "math/big"
) )
@ -135,12 +134,12 @@ func (self *StateTransition) preCheck() (err error) {
} }
func (self *StateTransition) TransitionState() (err error) { func (self *StateTransition) TransitionState() (err error) {
ethutil.Config.Log.Printf(ethutil.LogLevelInfo, "(~) %x\n", self.tx.Hash()) statelogger.Infof("(~) %x\n", self.tx.Hash())
/* /*
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
ethutil.Config.Log.Infoln(r) logger.Infoln(r)
err = fmt.Errorf("state transition err %v", r) err = fmt.Errorf("state transition err %v", r)
} }
}() }()
@ -231,7 +230,7 @@ func (self *StateTransition) transferValue(sender, receiver *StateObject) error
// Add the amount to receivers account which should conclude this transaction // Add the amount to receivers account which should conclude this transaction
receiver.AddAmount(self.value) receiver.AddAmount(self.value)
//ethutil.Config.Log.Debugf("%x => %x (%v)\n", sender.Address()[:4], receiver.Address()[:4], self.value) //statelogger.Debugf("%x => %x (%v)\n", sender.Address()[:4], receiver.Address()[:4], self.value)
//} //}
return nil return nil

View File

@ -3,15 +3,15 @@ package ethchain
import ( import (
"bytes" "bytes"
"container/list" "container/list"
"errors"
"fmt" "fmt"
"github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethwire" "github.com/ethereum/eth-go/ethwire"
"log" "github.com/ethereum/eth-go/ethlog"
"math/big" "math/big"
"sync" "sync"
) )
var txplogger = ethlog.NewLogger("TXP")
const ( const (
txPoolQueueSize = 50 txPoolQueueSize = 50
) )
@ -97,7 +97,7 @@ func (pool *TxPool) ProcessTransaction(tx *Transaction, state *State, toContract
fmt.Printf("state root before update %x\n", state.Root()) fmt.Printf("state root before update %x\n", state.Root())
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
ethutil.Config.Log.Infoln(r) txplogger.Infoln(r)
err = fmt.Errorf("%v", r) err = fmt.Errorf("%v", r)
} }
}() }()
@ -156,7 +156,7 @@ func (pool *TxPool) ProcessTransaction(tx *Transaction, state *State, toContract
fmt.Printf("state root after receiver update %x\n", state.Root()) fmt.Printf("state root after receiver update %x\n", state.Root())
} }
ethutil.Config.Log.Infof("[TXPL] Processed Tx %x\n", tx.Hash()) txplogger.Infof("[TXPL] Processed Tx %x\n", tx.Hash())
return return
} }
@ -168,7 +168,7 @@ func (pool *TxPool) ValidateTransaction(tx *Transaction) error {
block := pool.Ethereum.BlockChain().CurrentBlock block := pool.Ethereum.BlockChain().CurrentBlock
// Something has gone horribly wrong if this happens // Something has gone horribly wrong if this happens
if block == nil { if block == nil {
return errors.New("[TXPL] No last block on the block chain") return fmt.Errorf("[TXPL] No last block on the block chain")
} }
if len(tx.Recipient) != 20 { if len(tx.Recipient) != 20 {
@ -188,7 +188,7 @@ func (pool *TxPool) ValidateTransaction(tx *Transaction) error {
if tx.IsContract() { if tx.IsContract() {
if tx.GasPrice.Cmp(big.NewInt(minGasPrice)) < 0 { if tx.GasPrice.Cmp(big.NewInt(minGasPrice)) < 0 {
return fmt.Errorf("[TXPL] Gasprice to low, %s given should be at least %d.", tx.GasPrice, minGasPrice) return fmt.Errorf("[TXPL] Gasprice too low, %s given should be at least %d.", tx.GasPrice, minGasPrice)
} }
} }
@ -215,12 +215,12 @@ out:
// Validate the transaction // Validate the transaction
err := pool.ValidateTransaction(tx) err := pool.ValidateTransaction(tx)
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("Validating Tx failed", err) txplogger.Debugln("Validating Tx failed", err)
} else { } else {
// Call blocking version. // Call blocking version.
pool.addTransaction(tx) pool.addTransaction(tx)
ethutil.Config.Log.Debugf("(t) %x => %x (%v) %x\n", tx.Sender()[:4], tx.Recipient[:4], tx.Value, tx.Hash()) txplogger.Debugf("(t) %x => %x (%v) %x\n", tx.Sender()[:4], tx.Recipient[:4], tx.Value, tx.Hash())
// Notify the subscribers // Notify the subscribers
pool.Ethereum.Reactor().Post("newTx:pre", tx) pool.Ethereum.Reactor().Post("newTx:pre", tx)
@ -282,5 +282,5 @@ func (pool *TxPool) Stop() {
pool.Flush() pool.Flush()
log.Println("[TXP] Stopped") txplogger.Infoln("Stopped")
} }

View File

@ -3,10 +3,13 @@ package ethchain
import ( import (
"fmt" "fmt"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethlog"
"math" "math"
"math/big" "math/big"
) )
var vmlogger = ethlog.NewLogger("VM")
var ( var (
GasStep = big.NewInt(1) GasStep = big.NewInt(1)
GasSha = big.NewInt(20) GasSha = big.NewInt(20)
@ -72,7 +75,7 @@ func (self *Vm) Printf(format string, v ...interface{}) *Vm {
func (self *Vm) Endl() *Vm { func (self *Vm) Endl() *Vm {
if self.Verbose { if self.Verbose {
ethutil.Config.Log.Infoln(self.logStr) vmlogger.Infoln(self.logStr)
self.logStr = "" self.logStr = ""
} }
@ -93,11 +96,11 @@ func (vm *Vm) RunClosure(closure *Closure, hook DebugHook) (ret []byte, err erro
if r := recover(); r != nil { if r := recover(); r != nil {
ret = closure.Return(nil) ret = closure.Return(nil)
err = fmt.Errorf("%v", r) err = fmt.Errorf("%v", r)
fmt.Println("vm err", err) vmlogger.Errorln("vm err", err)
} }
}() }()
ethutil.Config.Log.Debugf("[VM] (~) %x gas: %v (d) %x\n", closure.object.Address(), closure.Gas, closure.Args) vmlogger.Debugf("(~) %x gas: %v (d) %x\n", closure.object.Address(), closure.Gas, closure.Args)
// Memory for the current closure // Memory for the current closure
mem := &Memory{} mem := &Memory{}
@ -638,7 +641,7 @@ func (vm *Vm) RunClosure(closure *Closure, hook DebugHook) (ret []byte, err erro
args := mem.Get(inOffset.Int64(), inSize.Int64()) args := mem.Get(inOffset.Int64(), inSize.Int64())
if closure.object.Amount.Cmp(value) < 0 { if closure.object.Amount.Cmp(value) < 0 {
ethutil.Config.Log.Debugf("Insufficient funds to transfer value. Req %v, has %v", value, closure.object.Amount) vmlogger.Debugf("Insufficient funds to transfer value. Req %v, has %v", value, closure.object.Amount)
stack.Push(ethutil.BigFalse) stack.Push(ethutil.BigFalse)
} else { } else {
@ -657,7 +660,7 @@ func (vm *Vm) RunClosure(closure *Closure, hook DebugHook) (ret []byte, err erro
if err != nil { if err != nil {
stack.Push(ethutil.BigFalse) stack.Push(ethutil.BigFalse)
ethutil.Config.Log.Debugf("Closure execution failed. %v\n", err) vmlogger.Debugf("Closure execution failed. %v\n", err)
vm.err = err vm.err = err
vm.state.Set(snapshot) vm.state.Set(snapshot)
@ -692,7 +695,7 @@ func (vm *Vm) RunClosure(closure *Closure, hook DebugHook) (ret []byte, err erro
return closure.Return(nil), nil return closure.Return(nil), nil
default: default:
ethutil.Config.Log.Debugf("Invalid opcode %x\n", op) vmlogger.Debugf("Invalid opcode %x\n", op)
return closure.Return(nil), fmt.Errorf("Invalid opcode %x", op) return closure.Return(nil), fmt.Errorf("Invalid opcode %x", op)
} }

View File

@ -8,8 +8,8 @@ import (
"github.com/ethereum/eth-go/ethrpc" "github.com/ethereum/eth-go/ethrpc"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethwire" "github.com/ethereum/eth-go/ethwire"
"github.com/ethereum/eth-go/ethlog"
"io/ioutil" "io/ioutil"
"log"
"math/rand" "math/rand"
"net" "net"
"net/http" "net/http"
@ -20,6 +20,8 @@ import (
"time" "time"
) )
var ethlogger = ethlog.NewLogger("SERV")
func eachPeer(peers *list.List, callback func(*Peer, *list.Element)) { func eachPeer(peers *list.List, callback func(*Peer, *list.Element)) {
// Loop thru the peers and close them (if we had them) // Loop thru the peers and close them (if we had them)
for e := peers.Front(); e != nil; e = e.Next() { for e := peers.Front(); e != nil; e = e.Next() {
@ -85,7 +87,7 @@ func New(caps Caps, usePnp bool) (*Ethereum, error) {
if usePnp { if usePnp {
nat, err = Discover() nat, err = Discover()
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("UPnP failed", err) ethlogger.Debugln("UPnP failed", err)
} }
} }
@ -163,7 +165,7 @@ func (s *Ethereum) AddPeer(conn net.Conn) {
if s.peers.Len() < s.MaxPeers { if s.peers.Len() < s.MaxPeers {
peer.Start() peer.Start()
} else { } else {
ethutil.Config.Log.Debugf("[SERV] Max connected peers reached. Not adding incoming peer.") ethlogger.Debugf("Max connected peers reached. Not adding incoming peer.")
} }
} }
} }
@ -223,7 +225,7 @@ func (s *Ethereum) ConnectToPeer(addr string) error {
if phost == chost { if phost == chost {
alreadyConnected = true alreadyConnected = true
//ethutil.Config.Log.Debugf("[SERV] Peer %s already added.\n", chost) //ethlogger.Debugf("Peer %s already added.\n", chost)
return return
} }
}) })
@ -340,12 +342,12 @@ func (s *Ethereum) Start(seed bool) {
// Bind to addr and port // Bind to addr and port
ln, err := net.Listen("tcp", ":"+s.Port) ln, err := net.Listen("tcp", ":"+s.Port)
if err != nil { if err != nil {
log.Println("Connection listening disabled. Acting as client") ethlogger.Warnln("Connection listening disabled. Acting as client")
s.listening = false s.listening = false
} else { } else {
s.listening = true s.listening = true
// Starting accepting connections // Starting accepting connections
ethutil.Config.Log.Infoln("Ready and accepting connections") ethlogger.Infoln("Ready and accepting connections")
// Start the peer handler // Start the peer handler
go s.peerHandler(ln) go s.peerHandler(ln)
} }
@ -363,7 +365,7 @@ func (s *Ethereum) Start(seed bool) {
} }
func (s *Ethereum) Seed() { func (s *Ethereum) Seed() {
ethutil.Config.Log.Debugln("[SERV] Retrieving seed nodes") ethlogger.Debugln("Retrieving seed nodes")
// Eth-Go Bootstrapping // Eth-Go Bootstrapping
ips, er := net.LookupIP("seed.bysh.me") ips, er := net.LookupIP("seed.bysh.me")
@ -371,7 +373,7 @@ func (s *Ethereum) Seed() {
peers := []string{} peers := []string{}
for _, ip := range ips { for _, ip := range ips {
node := fmt.Sprintf("%s:%d", ip.String(), 30303) node := fmt.Sprintf("%s:%d", ip.String(), 30303)
ethutil.Config.Log.Debugln("[SERV] Found DNS Go Peer:", node) ethlogger.Debugln("Found DNS Go Peer:", node)
peers = append(peers, node) peers = append(peers, node)
} }
s.ProcessPeerList(peers) s.ProcessPeerList(peers)
@ -391,11 +393,11 @@ func (s *Ethereum) Seed() {
for _, a := range addr { for _, a := range addr {
// Build string out of SRV port and Resolved IP // Build string out of SRV port and Resolved IP
peer := net.JoinHostPort(a, port) peer := net.JoinHostPort(a, port)
ethutil.Config.Log.Debugln("[SERV] Found DNS Bootstrap Peer:", peer) ethlogger.Debugln("Found DNS Bootstrap Peer:", peer)
peers = append(peers, peer) peers = append(peers, peer)
} }
} else { } else {
ethutil.Config.Log.Debugln("[SERV} Couldn't resolve :", target) ethlogger.Debugln("Couldn't resolve :", target)
} }
} }
// Connect to Peer list // Connect to Peer list
@ -404,13 +406,13 @@ func (s *Ethereum) Seed() {
// Fallback to servers.poc3.txt // Fallback to servers.poc3.txt
resp, err := http.Get("http://www.ethereum.org/servers.poc3.txt") resp, err := http.Get("http://www.ethereum.org/servers.poc3.txt")
if err != nil { if err != nil {
log.Println("Fetching seed failed:", err) ethlogger.Warnln("Fetching seed failed:", err)
return return
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
log.Println("Reading seed failed:", err) ethlogger.Warnln("Reading seed failed:", err)
return return
} }
@ -422,7 +424,7 @@ func (s *Ethereum) peerHandler(listener net.Listener) {
for { for {
conn, err := listener.Accept() conn, err := listener.Accept()
if err != nil { if err != nil {
ethutil.Config.Log.Debugln(err) ethlogger.Debugln(err)
continue continue
} }
@ -468,13 +470,13 @@ out:
var err error var err error
_, err = s.nat.AddPortMapping("TCP", int(lport), int(lport), "eth listen port", 20*60) _, err = s.nat.AddPortMapping("TCP", int(lport), int(lport), "eth listen port", 20*60)
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("can't add UPnP port mapping:", err) ethlogger.Debugln("can't add UPnP port mapping:", err)
break out break out
} }
if first && err == nil { if first && err == nil {
_, err = s.nat.GetExternalAddress() _, err = s.nat.GetExternalAddress()
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("UPnP can't get external address:", err) ethlogger.Debugln("UPnP can't get external address:", err)
continue out continue out
} }
first = false first = false
@ -488,8 +490,8 @@ out:
timer.Stop() timer.Stop()
if err := s.nat.DeletePortMapping("TCP", int(lport), int(lport)); err != nil { if err := s.nat.DeletePortMapping("TCP", int(lport), int(lport)); err != nil {
ethutil.Config.Log.Debugln("unable to remove UPnP port mapping:", err) ethlogger.Debugln("unable to remove UPnP port mapping:", err)
} else { } else {
ethutil.Config.Log.Debugln("succesfully disestablished UPnP port mapping") ethlogger.Debugln("succesfully disestablished UPnP port mapping")
} }
} }

View File

@ -5,9 +5,12 @@ import (
"github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethchain"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethwire" "github.com/ethereum/eth-go/ethwire"
"github.com/ethereum/eth-go/ethlog"
"sort" "sort"
) )
var logger = ethlog.NewLogger("MINER")
type Miner struct { type Miner struct {
pow ethchain.PoW pow ethchain.PoW
ethereum ethchain.EthManager ethereum ethchain.EthManager
@ -67,10 +70,10 @@ out:
break out break out
case chanMessage := <-miner.reactChan: case chanMessage := <-miner.reactChan:
if block, ok := chanMessage.Resource.(*ethchain.Block); ok { if block, ok := chanMessage.Resource.(*ethchain.Block); ok {
//ethutil.Config.Log.Infoln("[MINER] Got new block via Reactor") //logger.Infoln("Got new block via Reactor")
if bytes.Compare(miner.ethereum.BlockChain().CurrentBlock.Hash(), block.Hash()) == 0 { if bytes.Compare(miner.ethereum.BlockChain().CurrentBlock.Hash(), block.Hash()) == 0 {
// TODO: Perhaps continue mining to get some uncle rewards // TODO: Perhaps continue mining to get some uncle rewards
//ethutil.Config.Log.Infoln("[MINER] New top block found resetting state") //logger.Infoln("New top block found resetting state")
// Filter out which Transactions we have that were not in this block // Filter out which Transactions we have that were not in this block
var newtxs []*ethchain.Transaction var newtxs []*ethchain.Transaction
@ -92,7 +95,7 @@ out:
} else { } else {
if bytes.Compare(block.PrevHash, miner.ethereum.BlockChain().CurrentBlock.PrevHash) == 0 { if bytes.Compare(block.PrevHash, miner.ethereum.BlockChain().CurrentBlock.PrevHash) == 0 {
ethutil.Config.Log.Infoln("[MINER] Adding uncle block") logger.Infoln("Adding uncle block")
miner.uncles = append(miner.uncles, block) miner.uncles = append(miner.uncles, block)
} }
} }
@ -137,14 +140,14 @@ func (self *Miner) mineNewBlock() {
// Sort the transactions by nonce in case of odd network propagation // Sort the transactions by nonce in case of odd network propagation
sort.Sort(ethchain.TxByNonce{self.txs}) sort.Sort(ethchain.TxByNonce{self.txs})
// Accumulate all valid transaction and apply them to the new state // Accumulate all valid transactions and apply them to the new state
// Error may be ignored. It's not important during mining // Error may be ignored. It's not important during mining
parent := self.ethereum.BlockChain().GetBlock(self.block.PrevHash) parent := self.ethereum.BlockChain().GetBlock(self.block.PrevHash)
coinbase := self.block.State().GetOrNewStateObject(self.block.Coinbase) coinbase := self.block.State().GetOrNewStateObject(self.block.Coinbase)
coinbase.SetGasPool(self.block.CalcGasLimit(parent)) coinbase.SetGasPool(self.block.CalcGasLimit(parent))
receipts, txs, unhandledTxs, err := stateManager.ProcessTransactions(coinbase, self.block.State(), self.block, self.block, self.txs) receipts, txs, unhandledTxs, err := stateManager.ProcessTransactions(coinbase, self.block.State(), self.block, self.block, self.txs)
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("[MINER]", err) logger.Debugln(err)
} }
self.txs = append(txs, unhandledTxs...) self.txs = append(txs, unhandledTxs...)
@ -156,18 +159,18 @@ func (self *Miner) mineNewBlock() {
self.block.State().Update() self.block.State().Update()
ethutil.Config.Log.Infoln("[MINER] Mining on block. Includes", len(self.txs), "transactions") logger.Infoln("Mining on block. Includes", len(self.txs), "transactions")
// Find a valid nonce // Find a valid nonce
self.block.Nonce = self.pow.Search(self.block, self.powQuitChan) self.block.Nonce = self.pow.Search(self.block, self.powQuitChan)
if self.block.Nonce != nil { if self.block.Nonce != nil {
err := self.ethereum.StateManager().Process(self.block, false) err := self.ethereum.StateManager().Process(self.block, false)
if err != nil { if err != nil {
ethutil.Config.Log.Infoln(err) logger.Infoln(err)
} else { } else {
self.ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{self.block.Value().Val}) self.ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{self.block.Value().Val})
ethutil.Config.Log.Infof("[MINER] 🔨 Mined block %x\n", self.block.Hash()) logger.Infof("🔨 Mined block %x\n", self.block.Hash())
ethutil.Config.Log.Infoln(self.block) logger.Infoln(self.block)
// Gather the new batch of transactions currently in the tx pool // Gather the new batch of transactions currently in the tx pool
self.txs = self.ethereum.TxPool().CurrentTransactions() self.txs = self.ethereum.TxPool().CurrentTransactions()
} }

View File

@ -4,11 +4,14 @@ import (
"encoding/hex" "encoding/hex"
"github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethchain"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethlog"
"math/big" "math/big"
"strings" "strings"
"sync/atomic" "sync/atomic"
) )
var logger = ethlog.NewLogger("PUB")
type PEthereum struct { type PEthereum struct {
manager ethchain.EthManager manager ethchain.EthManager
stateManager *ethchain.StateManager stateManager *ethchain.StateManager
@ -191,7 +194,7 @@ func (lib *PEthereum) createTx(key, recipient, valueStr, gasStr, gasPriceStr, sc
lib.txPool.QueueTransaction(tx) lib.txPool.QueueTransaction(tx)
if contractCreation { if contractCreation {
ethutil.Config.Log.Infof("Contract addr %x", tx.CreationAddress()) logger.Infof("Contract addr %x", tx.CreationAddress())
} }
return NewPReciept(contractCreation, tx.CreationAddress(), tx.Hash(), keyPair.Address()), nil return NewPReciept(contractCreation, tx.CreationAddress(), tx.Hash(), keyPair.Address()), nil

View File

@ -3,12 +3,14 @@ package ethrpc
import ( import (
"fmt" "fmt"
"github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethpub"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethlog"
"net" "net"
"net/rpc" "net/rpc"
"net/rpc/jsonrpc" "net/rpc/jsonrpc"
) )
var logger = ethlog.NewLogger("JSON")
type JsonRpcServer struct { type JsonRpcServer struct {
quit chan bool quit chan bool
listener net.Listener listener net.Listener
@ -25,7 +27,7 @@ out:
} }
} }
ethutil.Config.Log.Infoln("[JSON] Shutdown JSON-RPC server") logger.Infoln("Shutdown JSON-RPC server")
} }
func (s *JsonRpcServer) Stop() { func (s *JsonRpcServer) Stop() {
@ -33,7 +35,7 @@ func (s *JsonRpcServer) Stop() {
} }
func (s *JsonRpcServer) Start() { func (s *JsonRpcServer) Start() {
ethutil.Config.Log.Infoln("[JSON] Starting JSON-RPC server") logger.Infoln("Starting JSON-RPC server")
go s.exitHandler() go s.exitHandler()
rpc.Register(&EthereumApi{ethp: s.ethp}) rpc.Register(&EthereumApi{ethp: s.ethp})
rpc.HandleHTTP() rpc.HandleHTTP()
@ -41,10 +43,10 @@ func (s *JsonRpcServer) Start() {
for { for {
conn, err := s.listener.Accept() conn, err := s.listener.Accept()
if err != nil { if err != nil {
ethutil.Config.Log.Infoln("[JSON] Error starting JSON-RPC:", err) logger.Infoln("Error starting JSON-RPC:", err)
break break
} }
ethutil.Config.Log.Debugln("[JSON] Incoming request.") logger.Debugln("Incoming request.")
go jsonrpc.ServeConn(conn) go jsonrpc.ServeConn(conn)
} }
} }

59
peer.go
View File

@ -7,6 +7,7 @@ import (
"github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethchain"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethwire" "github.com/ethereum/eth-go/ethwire"
"github.com/ethereum/eth-go/ethlog"
"net" "net"
"strconv" "strconv"
"strings" "strings"
@ -14,6 +15,8 @@ import (
"time" "time"
) )
var peerlogger = ethlog.NewLogger("PEER")
const ( const (
// The size of the output buffer for writing messages // The size of the output buffer for writing messages
outputBufferSize = 50 outputBufferSize = 50
@ -176,7 +179,7 @@ func NewOutboundPeer(addr string, ethereum *Ethereum, caps Caps) *Peer {
conn, err := net.DialTimeout("tcp", addr, 10*time.Second) conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("Connection to peer failed", err) peerlogger.Debugln("Connection to peer failed", err)
p.Stop() p.Stop()
return return
} }
@ -245,11 +248,11 @@ func (p *Peer) writeMessage(msg *ethwire.Msg) {
} }
} }
ethutil.Config.Log.Println(ethutil.LogLevelSystem, "<=", msg.Type, msg.Data) peerlogger.Infoln("<=", msg.Type, msg.Data)
err := ethwire.WriteMessage(p.conn, msg) err := ethwire.WriteMessage(p.conn, msg)
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("[PEER] Can't send message:", err) peerlogger.Debugln(" Can't send message:", err)
// Stop the client if there was an error writing to it // Stop the client if there was an error writing to it
p.Stop() p.Stop()
return return
@ -274,7 +277,7 @@ out:
case <-pingTimer.C: case <-pingTimer.C:
timeSince := time.Since(time.Unix(p.lastPong, 0)) timeSince := time.Since(time.Unix(p.lastPong, 0))
if !p.pingStartTime.IsZero() && p.lastPong != 0 && timeSince > (pingPongTimer+30*time.Second) { if !p.pingStartTime.IsZero() && p.lastPong != 0 && timeSince > (pingPongTimer+30*time.Second) {
ethutil.Config.Log.Infof("[PEER] Peer did not respond to latest pong fast enough, it took %s, disconnecting.\n", timeSince) peerlogger.Infof("Peer did not respond to latest pong fast enough, it took %s, disconnecting.\n", timeSince)
p.Stop() p.Stop()
return return
} }
@ -316,10 +319,10 @@ func (p *Peer) HandleInbound() {
// Wait for a message from the peer // Wait for a message from the peer
msgs, err := ethwire.ReadMessages(p.conn) msgs, err := ethwire.ReadMessages(p.conn)
if err != nil { if err != nil {
ethutil.Config.Log.Debugln(err) peerlogger.Debugln(err)
} }
for _, msg := range msgs { for _, msg := range msgs {
ethutil.Config.Log.Println(ethutil.LogLevelSystem, "=>", msg.Type, msg.Data) peerlogger.Infoln("=>", msg.Type, msg.Data)
switch msg.Type { switch msg.Type {
case ethwire.MsgHandshakeTy: case ethwire.MsgHandshakeTy:
@ -331,7 +334,7 @@ func (p *Peer) HandleInbound() {
} }
case ethwire.MsgDiscTy: case ethwire.MsgDiscTy:
p.Stop() p.Stop()
ethutil.Config.Log.Infoln("Disconnect peer:", DiscReason(msg.Data.Get(0).Uint())) peerlogger.Infoln("Disconnect peer:", DiscReason(msg.Data.Get(0).Uint()))
case ethwire.MsgPingTy: case ethwire.MsgPingTy:
// Respond back with pong // Respond back with pong
p.QueueMessage(ethwire.NewMessage(ethwire.MsgPongTy, "")) p.QueueMessage(ethwire.NewMessage(ethwire.MsgPongTy, ""))
@ -351,7 +354,7 @@ func (p *Peer) HandleInbound() {
// We requested blocks and now we need to make sure we have a common ancestor somewhere in these blocks so we can find // We requested blocks and now we need to make sure we have a common ancestor somewhere in these blocks so we can find
// common ground to start syncing from // common ground to start syncing from
lastBlock = ethchain.NewBlockFromRlpValue(msg.Data.Get(msg.Data.Len() - 1)) lastBlock = ethchain.NewBlockFromRlpValue(msg.Data.Get(msg.Data.Len() - 1))
ethutil.Config.Log.Infof("[PEER] Last block: %x. Checking if we have it locally.\n", lastBlock.Hash()) peerlogger.Infof("Last block: %x. Checking if we have it locally.\n", lastBlock.Hash())
for i := msg.Data.Len() - 1; i >= 0; i-- { for i := msg.Data.Len() - 1; i >= 0; i-- {
block = ethchain.NewBlockFromRlpValue(msg.Data.Get(i)) block = ethchain.NewBlockFromRlpValue(msg.Data.Get(i))
// Do we have this block on our chain? If so we can continue // Do we have this block on our chain? If so we can continue
@ -372,7 +375,7 @@ func (p *Peer) HandleInbound() {
// we just keep increasing the amount of blocks. // we just keep increasing the amount of blocks.
p.blocksRequested = p.blocksRequested * 2 p.blocksRequested = p.blocksRequested * 2
ethutil.Config.Log.Infof("[PEER] No common ancestor found, requesting %d more blocks.\n", p.blocksRequested) peerlogger.Infof("No common ancestor found, requesting %d more blocks.\n", p.blocksRequested)
p.catchingUp = false p.catchingUp = false
p.FindCommonParentBlock() p.FindCommonParentBlock()
break break
@ -388,9 +391,9 @@ func (p *Peer) HandleInbound() {
if err != nil { if err != nil {
if ethutil.Config.Debug { if ethutil.Config.Debug {
ethutil.Config.Log.Infof("[PEER] Block %x failed\n", block.Hash()) peerlogger.Infof("Block %x failed\n", block.Hash())
ethutil.Config.Log.Infof("[PEER] %v\n", err) peerlogger.Infof("%v\n", err)
ethutil.Config.Log.Debugln(block) peerlogger.Debugln(block)
} }
break break
} else { } else {
@ -407,7 +410,7 @@ func (p *Peer) HandleInbound() {
if err != nil { if err != nil {
// If the parent is unknown try to catch up with this peer // If the parent is unknown try to catch up with this peer
if ethchain.IsParentErr(err) { if ethchain.IsParentErr(err) {
ethutil.Config.Log.Infoln("Attempting to catch. Parent known") peerlogger.Infoln("Attempting to catch. Parent known")
p.catchingUp = false p.catchingUp = false
p.CatchupWithPeer(p.ethereum.BlockChain().CurrentBlock.Hash()) p.CatchupWithPeer(p.ethereum.BlockChain().CurrentBlock.Hash())
} else if ethchain.IsValidationErr(err) { } else if ethchain.IsValidationErr(err) {
@ -419,7 +422,7 @@ func (p *Peer) HandleInbound() {
if p.catchingUp && msg.Data.Len() > 1 { if p.catchingUp && msg.Data.Len() > 1 {
if lastBlock != nil { if lastBlock != nil {
blockInfo := lastBlock.BlockInfo() blockInfo := lastBlock.BlockInfo()
ethutil.Config.Log.Printf(ethutil.LogLevelSystem, "Synced chain to #%d %x %x\n", blockInfo.Number, lastBlock.Hash(), blockInfo.Hash) peerlogger.Infof("Synced chain to #%d %x %x\n", blockInfo.Number, lastBlock.Hash(), blockInfo.Hash)
} }
p.catchingUp = false p.catchingUp = false
@ -486,17 +489,17 @@ func (p *Peer) HandleInbound() {
// If a parent is found send back a reply // If a parent is found send back a reply
if parent != nil { if parent != nil {
ethutil.Config.Log.Printf(ethutil.LogLevelSystem, "[PEER] Found canonical block, returning chain from: %x ", parent.Hash()) peerlogger.Infof("Found canonical block, returning chain from: %x ", parent.Hash())
chain := p.ethereum.BlockChain().GetChainFromHash(parent.Hash(), amountOfBlocks) chain := p.ethereum.BlockChain().GetChainFromHash(parent.Hash(), amountOfBlocks)
if len(chain) > 0 { if len(chain) > 0 {
//ethutil.Config.Log.Debugf("[PEER] Returning %d blocks: %x ", len(chain), parent.Hash()) //peerlogger.Debugf("Returning %d blocks: %x ", len(chain), parent.Hash())
p.QueueMessage(ethwire.NewMessage(ethwire.MsgBlockTy, chain)) p.QueueMessage(ethwire.NewMessage(ethwire.MsgBlockTy, chain))
} else { } else {
p.QueueMessage(ethwire.NewMessage(ethwire.MsgBlockTy, []interface{}{})) p.QueueMessage(ethwire.NewMessage(ethwire.MsgBlockTy, []interface{}{}))
} }
} else { } else {
//ethutil.Config.Log.Debugf("[PEER] Could not find a similar block") //peerlogger.Debugf("Could not find a similar block")
// If no blocks are found we send back a reply with msg not in chain // If no blocks are found we send back a reply with msg not in chain
// and the last hash from get chain // and the last hash from get chain
if l > 0 { if l > 0 {
@ -506,7 +509,7 @@ func (p *Peer) HandleInbound() {
} }
} }
case ethwire.MsgNotInChainTy: case ethwire.MsgNotInChainTy:
ethutil.Config.Log.Printf(ethutil.LogLevelSystem, "Not in chain: %x\n", msg.Data.Get(0).Bytes()) peerlogger.Infof("Not in chain: %x\n", msg.Data.Get(0).Bytes())
if p.diverted == true { if p.diverted == true {
// If were already looking for a common parent and we get here again we need to go deeper // If were already looking for a common parent and we get here again we need to go deeper
p.blocksRequested = p.blocksRequested * 2 p.blocksRequested = p.blocksRequested * 2
@ -527,7 +530,7 @@ func (p *Peer) HandleInbound() {
// Unofficial but fun nonetheless // Unofficial but fun nonetheless
case ethwire.MsgTalkTy: case ethwire.MsgTalkTy:
ethutil.Config.Log.Infoln("%v says: %s\n", p.conn.RemoteAddr(), msg.Data.Str()) peerlogger.Infoln("%v says: %s\n", p.conn.RemoteAddr(), msg.Data.Str())
} }
} }
} }
@ -546,7 +549,7 @@ func (p *Peer) Start() {
err := p.pushHandshake() err := p.pushHandshake()
if err != nil { if err != nil {
ethutil.Config.Log.Debugln("Peer can't send outbound version ack", err) peerlogger.Debugln("Peer can't send outbound version ack", err)
p.Stop() p.Stop()
@ -620,7 +623,7 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) {
p.pubkey = c.Get(5).Bytes() p.pubkey = c.Get(5).Bytes()
if p.pubkey == nil { if p.pubkey == nil {
//ethutil.Config.Log.Debugln("Pubkey required, not supplied in handshake.") peerlogger.Warnln("Pubkey required, not supplied in handshake.")
p.Stop() p.Stop()
return return
} }
@ -635,13 +638,13 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) {
}) })
if usedPub > 0 { if usedPub > 0 {
//ethutil.Config.Log.Debugf("Pubkey %x found more then once. Already connected to client.", p.pubkey) peerlogger.Debugf("Pubkey %x found more then once. Already connected to client.", p.pubkey)
p.Stop() p.Stop()
return return
} }
if c.Get(0).Uint() != ProtocolVersion { if c.Get(0).Uint() != ProtocolVersion {
ethutil.Config.Log.Debugf("Invalid peer version. Require protocol: %d. Received: %d\n", ProtocolVersion, c.Get(0).Uint()) peerlogger.Debugf("Invalid peer version. Require protocol: %d. Received: %d\n", ProtocolVersion, c.Get(0).Uint())
p.Stop() p.Stop()
return return
} }
@ -675,16 +678,16 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) {
p.ethereum.PushPeer(p) p.ethereum.PushPeer(p)
p.ethereum.reactor.Post("peerList", p.ethereum.Peers()) p.ethereum.reactor.Post("peerList", p.ethereum.Peers())
ethutil.Config.Log.Infof("[SERV] Added peer (%s) %d / %d\n", p.conn.RemoteAddr(), p.ethereum.Peers().Len(), p.ethereum.MaxPeers) ethlogger.Infof("Added peer (%s) %d / %d\n", p.conn.RemoteAddr(), p.ethereum.Peers().Len(), p.ethereum.MaxPeers)
// Catch up with the connected peer // Catch up with the connected peer
if !p.ethereum.IsUpToDate() { if !p.ethereum.IsUpToDate() {
ethutil.Config.Log.Debugln("Already syncing up with a peer; sleeping") peerlogger.Debugln("Already syncing up with a peer; sleeping")
time.Sleep(10 * time.Second) time.Sleep(10 * time.Second)
} }
p.SyncWithPeerToLastKnown() p.SyncWithPeerToLastKnown()
ethutil.Config.Log.Debugln("[PEER]", p) peerlogger.Debugln(p)
} }
func (p *Peer) String() string { func (p *Peer) String() string {
@ -727,7 +730,7 @@ func (p *Peer) FindCommonParentBlock() {
msgInfo := append(hashes, uint64(len(hashes))) msgInfo := append(hashes, uint64(len(hashes)))
ethutil.Config.Log.Printf(ethutil.LogLevelSystem, "Asking for block from %x (%d total) from %s\n", p.ethereum.BlockChain().CurrentBlock.Hash(), len(hashes), p.conn.RemoteAddr().String()) peerlogger.Infof("Asking for block from %x (%d total) from %s\n", p.ethereum.BlockChain().CurrentBlock.Hash(), len(hashes), p.conn.RemoteAddr().String())
msg := ethwire.NewMessage(ethwire.MsgGetChainTy, msgInfo) msg := ethwire.NewMessage(ethwire.MsgGetChainTy, msgInfo)
p.QueueMessage(msg) p.QueueMessage(msg)
@ -739,7 +742,7 @@ func (p *Peer) CatchupWithPeer(blockHash []byte) {
msg := ethwire.NewMessage(ethwire.MsgGetChainTy, []interface{}{blockHash, uint64(50)}) msg := ethwire.NewMessage(ethwire.MsgGetChainTy, []interface{}{blockHash, uint64(50)})
p.QueueMessage(msg) p.QueueMessage(msg)
ethutil.Config.Log.Printf(ethutil.LogLevelSystem, "Requesting blockchain %x... from peer %s\n", p.ethereum.BlockChain().CurrentBlock.Hash()[:4], p.conn.RemoteAddr()) peerlogger.Infof("Requesting blockchain %x... from peer %s\n", p.ethereum.BlockChain().CurrentBlock.Hash()[:4], p.conn.RemoteAddr())
msg = ethwire.NewMessage(ethwire.MsgGetTxsTy, []interface{}{}) msg = ethwire.NewMessage(ethwire.MsgGetTxsTy, []interface{}{})
p.QueueMessage(msg) p.QueueMessage(msg)