diff options
-rw-r--r-- | README.md | 2 | ||||
-rw-r--r-- | block_pool.go | 24 | ||||
-rw-r--r-- | ethchain/block_chain.go | 157 | ||||
-rw-r--r-- | ethchain/state_transition.go | 2 | ||||
-rw-r--r-- | ethdb/database.go | 13 | ||||
-rw-r--r-- | ethereum.go | 12 | ||||
-rw-r--r-- | ethpipe/js_pipe.go | 3 | ||||
-rw-r--r-- | ethreact/reactor.go | 5 | ||||
-rw-r--r-- | ethstate/state.go | 2 | ||||
-rw-r--r-- | ethutil/value.go | 2 | ||||
-rw-r--r-- | ethvm/vm.go | 4 | ||||
-rw-r--r-- | peer.go | 57 |
12 files changed, 48 insertions, 235 deletions
@@ -6,7 +6,7 @@ Ethereum Ethereum Go Development package (C) Jeffrey Wilcke Ethereum is currently in its testing phase. The current state is "Proof -of Concept 0.6.4". For build instructions see the [Wiki](https://github.com/ethereum/go-ethereum/wiki/Building-Ethereum(Go)). +of Concept 0.6.5". For build instructions see the [Wiki](https://github.com/ethereum/go-ethereum/wiki/Building-Ethereum(Go)). Ethereum Go is split up in several sub packages Please refer to each individual package for more information. diff --git a/block_pool.go b/block_pool.go index 3225bdff2..25627eb5c 100644 --- a/block_pool.go +++ b/block_pool.go @@ -49,11 +49,11 @@ func (self *BlockPool) AddHash(hash []byte) { } } -func (self *BlockPool) SetBlock(b *ethchain.Block) { +func (self *BlockPool) SetBlock(b *ethchain.Block, peer *Peer) { hash := string(b.Hash()) - if self.pool[string(hash)] == nil { - self.pool[hash] = &block{nil, nil} + if self.pool[hash] == nil { + self.pool[hash] = &block{peer, nil} } self.pool[hash].block = b @@ -65,6 +65,10 @@ func (self *BlockPool) CheckLinkAndProcess(f func(block *ethchain.Block)) bool { if self.IsLinked() { for i, hash := range self.hashPool { + if self.pool[string(hash)] == nil { + continue + } + block := self.pool[string(hash)].block if block != nil { f(block) @@ -88,9 +92,15 @@ func (self *BlockPool) IsLinked() bool { return false } - block := self.pool[string(self.hashPool[0])].block - if block != nil { - return self.eth.BlockChain().HasBlock(block.PrevHash) + for i := 0; i < len(self.hashPool); i++ { + item := self.pool[string(self.hashPool[i])] + if item != nil && item.block != nil { + if self.eth.BlockChain().HasBlock(item.block.PrevHash) { + self.hashPool = self.hashPool[i:] + + return true + } + } } return false @@ -104,7 +114,7 @@ func (self *BlockPool) Take(amount int, peer *Peer) (hashes [][]byte) { j := 0 for i := 0; i < len(self.hashPool) && j < num; i++ { hash := string(self.hashPool[i]) - if self.pool[hash].peer == nil || self.pool[hash].peer == peer { + if self.pool[hash] != nil && (self.pool[hash].peer == nil || self.pool[hash].peer == peer) && self.pool[hash].block == nil { self.pool[hash].peer = peer hashes = append(hashes, self.hashPool[i]) diff --git a/ethchain/block_chain.go b/ethchain/block_chain.go index 3445bbb87..74f47aa90 100644 --- a/ethchain/block_chain.go +++ b/ethchain/block_chain.go @@ -2,12 +2,10 @@ package ethchain import ( "bytes" - "math" "math/big" "github.com/ethereum/eth-go/ethlog" "github.com/ethereum/eth-go/ethutil" - "github.com/ethereum/eth-go/ethwire" ) var chainlogger = ethlog.NewLogger("CHAIN") @@ -110,99 +108,6 @@ func (bc *BlockChain) CalculateBlockTD(block *Block) *big.Int { return blockDiff } -func (bc *BlockChain) FindCanonicalChainFromMsg(msg *ethwire.Msg, commonBlockHash []byte) bool { - var blocks []*Block - for i := 0; i < (msg.Data.Len() - 1); i++ { - block := NewBlockFromRlpValue(msg.Data.Get(i)) - blocks = append(blocks, block) - } - return bc.FindCanonicalChain(blocks, commonBlockHash) -} - -// Is tasked by finding the CanonicalChain and resetting the chain if we are not the Conical one -// Return true if we are the using the canonical chain false if not -func (bc *BlockChain) FindCanonicalChain(blocks []*Block, commonBlockHash []byte) bool { - // 1. Calculate TD of the current chain - // 2. Calculate TD of the new chain - // Reset state to the correct one - - chainDifficulty := new(big.Int) - - // Calculate the entire chain until the block we both have - // Start with the newest block we got, all the way back to the common block we both know - for _, block := range blocks { - if bytes.Compare(block.Hash(), commonBlockHash) == 0 { - chainlogger.Infoln("We have found the common parent block, breaking") - break - } - chainDifficulty.Add(chainDifficulty, bc.CalculateBlockTD(block)) - } - - chainlogger.Infoln("Incoming chain difficulty:", chainDifficulty) - - curChainDifficulty := new(big.Int) - block := bc.CurrentBlock - for i := 0; block != nil; block = bc.GetBlock(block.PrevHash) { - i++ - if bytes.Compare(block.Hash(), commonBlockHash) == 0 { - chainlogger.Infoln("Found the common parent block") - break - } - anOtherBlock := bc.GetBlock(block.PrevHash) - if anOtherBlock == nil { - // We do not want to count the genesis block for difficulty since that's not being sent - chainlogger.Infoln("Found genesis block. Stop") - break - } - curChainDifficulty.Add(curChainDifficulty, bc.CalculateBlockTD(block)) - } - - chainlogger.Infoln("Current chain difficulty:", curChainDifficulty) - if chainDifficulty.Cmp(curChainDifficulty) == 1 { - chainlogger.Infof("Resetting to block %x. Changing chain.") - bc.ResetTillBlockHash(commonBlockHash) - return false - } else { - chainlogger.Infoln("Current chain is longest chain. Ignoring incoming chain.") - return true - } -} -func (bc *BlockChain) ResetTillBlockHash(hash []byte) error { - lastBlock := bc.CurrentBlock - var returnTo *Block - // Reset to Genesis if that's all the origin there is. - if bytes.Compare(hash, bc.genesisBlock.Hash()) == 0 { - returnTo = bc.genesisBlock - bc.CurrentBlock = bc.genesisBlock - bc.LastBlockHash = bc.genesisBlock.Hash() - bc.LastBlockNumber = 1 - } else { - returnTo = bc.GetBlock(hash) - bc.CurrentBlock = returnTo - bc.LastBlockHash = returnTo.Hash() - bc.LastBlockNumber = returnTo.Number.Uint64() - } - - // Manually reset the last sync block - err := ethutil.Config.Db.Delete(lastBlock.Hash()) - if err != nil { - return err - } - - var block *Block - for ; block != nil; block = bc.GetBlock(block.PrevHash) { - if bytes.Compare(block.Hash(), hash) == 0 { - chainlogger.Infoln("We have arrived at the the common parent block, breaking") - break - } - err = ethutil.Config.Db.Delete(block.Hash()) - if err != nil { - return err - } - } - chainlogger.Infoln("Split chain deleted and reverted to common parent block.") - return nil -} func (bc *BlockChain) GenesisBlock() *Block { return bc.genesisBlock @@ -228,66 +133,6 @@ func (self *BlockChain) GetChainHashesFromHash(hash []byte, max uint64) (chain [ return } -// Get chain return blocks from hash up to max in RLP format -func (bc *BlockChain) GetChainFromHash(hash []byte, max uint64) []interface{} { - var chain []interface{} - // Get the current hash to start with - currentHash := bc.CurrentBlock.Hash() - // Get the last number on the block chain - lastNumber := bc.CurrentBlock.Number.Uint64() - // Get the parents number - parentNumber := bc.GetBlock(hash).Number.Uint64() - // Get the min amount. We might not have max amount of blocks - count := uint64(math.Min(float64(lastNumber-parentNumber), float64(max))) - startNumber := parentNumber + count - - num := lastNumber - for num > startNumber { - num-- - - block := bc.GetBlock(currentHash) - if block == nil { - break - } - currentHash = block.PrevHash - } - - for i := uint64(0); bytes.Compare(currentHash, hash) != 0 && num >= parentNumber && i < count; i++ { - // Get the block of the chain - block := bc.GetBlock(currentHash) - if block == nil { - chainlogger.Debugf("Unexpected error during GetChainFromHash: Unable to find %x\n", currentHash) - break - } - - currentHash = block.PrevHash - - chain = append(chain, block.Value().Val) - - num-- - } - - return chain -} - -func (bc *BlockChain) GetChain(hash []byte, amount int) []*Block { - genHash := bc.genesisBlock.Hash() - - block := bc.GetBlock(hash) - var blocks []*Block - - for i := 0; i < amount && block != nil; block = bc.GetBlock(block.PrevHash) { - blocks = append([]*Block{block}, blocks...) - - if bytes.Compare(genHash, block.Hash()) == 0 { - break - } - i++ - } - - return blocks -} - func AddTestNetFunds(block *Block) { for _, addr := range []string{ "51ba59315b3a95761d0863b05ccc7a7f54703d99", @@ -331,7 +176,7 @@ func (bc *BlockChain) setLastBlock() { } func (bc *BlockChain) SetTotalDifficulty(td *big.Int) { - ethutil.Config.Db.Put([]byte("LastKnownTotalDifficulty"), td.Bytes()) + ethutil.Config.Db.Put([]byte("LTD"), td.Bytes()) bc.TD = td } diff --git a/ethchain/state_transition.go b/ethchain/state_transition.go index 9fbc160a5..80f9fda5e 100644 --- a/ethchain/state_transition.go +++ b/ethchain/state_transition.go @@ -140,7 +140,7 @@ func (self *StateTransition) preCheck() (err error) { } func (self *StateTransition) TransitionState() (err error) { - statelogger.Infof("(~) %x\n", self.tx.Hash()) + statelogger.Debugf("(~) %x\n", self.tx.Hash()) /* defer func() { diff --git a/ethdb/database.go b/ethdb/database.go index 09e9d8c7d..e4b069930 100644 --- a/ethdb/database.go +++ b/ethdb/database.go @@ -2,9 +2,10 @@ package ethdb import ( "fmt" + "path" + "github.com/ethereum/eth-go/ethutil" "github.com/syndtr/goleveldb/leveldb" - "path" ) type LDBDatabase struct { @@ -45,7 +46,7 @@ func (db *LDBDatabase) Db() *leveldb.DB { } func (db *LDBDatabase) LastKnownTD() []byte { - data, _ := db.db.Get([]byte("LastKnownTotalDifficulty"), nil) + data, _ := db.db.Get([]byte("LTD"), nil) if len(data) == 0 { data = []byte{0x0} @@ -54,14 +55,6 @@ func (db *LDBDatabase) LastKnownTD() []byte { return data } -/* -func (db *LDBDatabase) GetKeys() []*ethutil.Key { - data, _ := db.Get([]byte("KeyRing")) - - return []*ethutil.Key{ethutil.NewKeyFromBytes(data)} -} -*/ - func (db *LDBDatabase) Close() { // Close the leveldb database db.db.Close() diff --git a/ethereum.go b/ethereum.go index 1e1891589..4c5e13b6d 100644 --- a/ethereum.go +++ b/ethereum.go @@ -90,7 +90,6 @@ type Ethereum struct { } func New(db ethutil.Database, clientIdentity ethwire.ClientIdentity, keyManager *ethcrypto.KeyManager, caps Caps, usePnp bool) (*Ethereum, error) { - var err error var nat NAT @@ -101,6 +100,8 @@ func New(db ethutil.Database, clientIdentity ethwire.ClientIdentity, keyManager } } + bootstrapDb(db) + ethutil.Config.Db = db nonce, _ := ethutil.RandomUint64() @@ -534,3 +535,12 @@ out: } } } + +func bootstrapDb(db ethutil.Database) { + d, _ := db.Get([]byte("ProtocolVersion")) + protov := ethutil.NewValue(d).Uint() + + if protov == 0 { + db.Put([]byte("ProtocolVersion"), ethutil.NewValue(ProtocolVersion).Bytes()) + } +} diff --git a/ethpipe/js_pipe.go b/ethpipe/js_pipe.go index b32e94a10..eeece5179 100644 --- a/ethpipe/js_pipe.go +++ b/ethpipe/js_pipe.go @@ -99,7 +99,8 @@ func (self *JSPipe) NumberToHuman(balance string) string { func (self *JSPipe) StorageAt(addr, storageAddr string) string { storage := self.World().SafeGet(ethutil.Hex2Bytes(addr)).Storage(ethutil.Hex2Bytes(storageAddr)) - return storage.BigInt().String() + + return ethutil.Bytes2Hex(storage.Bytes()) } func (self *JSPipe) TxCountAt(address string) int { diff --git a/ethreact/reactor.go b/ethreact/reactor.go index 7fe2356db..2edcbbbd9 100644 --- a/ethreact/reactor.go +++ b/ethreact/reactor.go @@ -1,8 +1,9 @@ package ethreact import ( - "github.com/ethereum/eth-go/ethlog" "sync" + + "github.com/ethereum/eth-go/ethlog" ) var logger = ethlog.NewLogger("REACTOR") @@ -32,7 +33,7 @@ func (e *EventHandler) Post(event Event) { select { case ch <- event: default: - logger.Warnf("subscribing channel %d to event %s blocked. skipping\n", i, event.Name) + logger.Debugf("subscribing channel %d to event %s blocked. skipping\n", i, event.Name) } } } diff --git a/ethstate/state.go b/ethstate/state.go index cf060e795..2f7f00a32 100644 --- a/ethstate/state.go +++ b/ethstate/state.go @@ -103,7 +103,7 @@ func (self *State) GetOrNewStateObject(addr []byte) *StateObject { func (self *State) NewStateObject(addr []byte) *StateObject { addr = ethutil.Address(addr) - statelogger.Infof("(+) %x\n", addr) + statelogger.Debugf("(+) %x\n", addr) stateObject := NewStateObject(addr) self.stateObjects[string(addr)] = stateObject diff --git a/ethutil/value.go b/ethutil/value.go index 608d332ba..b336345ca 100644 --- a/ethutil/value.go +++ b/ethutil/value.go @@ -141,6 +141,8 @@ func (val *Value) Bytes() []byte { return []byte(s) } else if s, ok := val.Val.(*big.Int); ok { return s.Bytes() + } else { + return big.NewInt(val.Int()).Bytes() } return []byte{} diff --git a/ethvm/vm.go b/ethvm/vm.go index 873a80c44..347ebcfe6 100644 --- a/ethvm/vm.go +++ b/ethvm/vm.go @@ -631,12 +631,12 @@ func (self *Vm) RunClosure(closure *Closure) (ret []byte, err error) { require(1) stack.Pop() case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16: - n := int(op - DUP1 + 1) + n := int(op - DUP1) stack.Dupn(n) self.Printf(" => [%d] 0x%x", n, stack.Peek().Bytes()) case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16: - n := int(op - SWAP1 + 1) + n := int(op - SWAP1) x, y := stack.Swapn(n) self.Printf(" => [%d] %x [0] %x", n, x.Bytes(), y.Bytes()) @@ -474,7 +474,7 @@ func (p *Peer) HandleInbound() { for it.Next() { block := ethchain.NewBlockFromRlpValue(it.Value()) - blockPool.SetBlock(block) + blockPool.SetBlock(block, p) p.lastBlockReceived = time.Now() } @@ -507,6 +507,7 @@ func (self *Peer) FetchHashes() { if self.td.Cmp(blockPool.td) >= 0 { peerlogger.Debugf("Requesting hashes from %x\n", self.lastReceivedHash) + blockPool.td = self.td if !blockPool.HasLatestHash() { self.QueueMessage(ethwire.NewMessage(ethwire.MsgGetBlockHashesTy, []interface{}{self.lastReceivedHash, uint32(200)})) @@ -625,7 +626,6 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) { usedPub := 0 // This peer is already added to the peerlist so we expect to find a double pubkey at least once - eachPeer(p.ethereum.Peers(), func(peer *Peer, e *list.Element) { if bytes.Compare(p.pubkey, peer.pubkey) == 0 { usedPub++ @@ -644,7 +644,6 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) { return } - // [PROTOCOL_VERSION, NETWORK_ID, CLIENT_ID, CAPS, PORT, PUBKEY] p.versionKnown = true // If this is an inbound connection send an ack back @@ -680,15 +679,8 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) { ethlogger.Infof("Added peer (%s) %d / %d (TD = %v ~ %x)\n", p.conn.RemoteAddr(), p.ethereum.Peers().Len(), p.ethereum.MaxPeers, p.td, p.bestHash) - /* - // Catch up with the connected peer - if !p.ethereum.IsUpToDate() { - peerlogger.Debugln("Already syncing up with a peer; sleeping") - time.Sleep(10 * time.Second) - } - */ - //p.SyncWithPeerToLastKnown() - + // Compare the total TD with the blockchain TD. If remote is higher + // fetch hashes from highest TD node. if p.td.Cmp(p.ethereum.BlockChain().TD) > 0 { p.ethereum.blockPool.AddHash(p.lastReceivedHash) p.FetchHashes() @@ -714,47 +706,6 @@ func (p *Peer) String() string { return fmt.Sprintf("[%s] (%s) %v %s [%s]", strConnectType, strBoundType, p.conn.RemoteAddr(), p.version, p.caps) } -func (p *Peer) SyncWithPeerToLastKnown() { - p.catchingUp = false - p.CatchupWithPeer(p.ethereum.BlockChain().CurrentBlock.Hash()) -} - -func (p *Peer) FindCommonParentBlock() { - if p.catchingUp { - return - } - - p.catchingUp = true - if p.blocksRequested == 0 { - p.blocksRequested = 20 - } - blocks := p.ethereum.BlockChain().GetChain(p.ethereum.BlockChain().CurrentBlock.Hash(), p.blocksRequested) - - var hashes []interface{} - for _, block := range blocks { - hashes = append(hashes, block.Hash()) - } - - msgInfo := append(hashes, uint64(len(hashes))) - - peerlogger.DebugDetailf("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) - p.QueueMessage(msg) -} -func (p *Peer) CatchupWithPeer(blockHash []byte) { - if !p.catchingUp { - // Make sure nobody else is catching up when you want to do this - p.catchingUp = true - msg := ethwire.NewMessage(ethwire.MsgGetChainTy, []interface{}{blockHash, uint64(100)}) - p.QueueMessage(msg) - - peerlogger.DebugDetailf("Requesting blockchain %x... from peer %s\n", p.ethereum.BlockChain().CurrentBlock.Hash()[:4], p.conn.RemoteAddr()) - - msg = ethwire.NewMessage(ethwire.MsgGetTxsTy, []interface{}{}) - p.QueueMessage(msg) - } -} func (p *Peer) RlpData() []interface{} { return []interface{}{p.host, p.port, p.pubkey} |