Removed old chain code

This commit is contained in:
obscuren 2014-08-22 10:58:14 +02:00
parent 740081e2f7
commit 93008e279d
3 changed files with 5 additions and 209 deletions

@ -2,12 +2,10 @@ package ethchain
import ( import (
"bytes" "bytes"
"math"
"math/big" "math/big"
"github.com/ethereum/eth-go/ethlog" "github.com/ethereum/eth-go/ethlog"
"github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethutil"
"github.com/ethereum/eth-go/ethwire"
) )
var chainlogger = ethlog.NewLogger("CHAIN") var chainlogger = ethlog.NewLogger("CHAIN")
@ -110,99 +108,6 @@ func (bc *BlockChain) CalculateBlockTD(block *Block) *big.Int {
return blockDiff 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 { func (bc *BlockChain) GenesisBlock() *Block {
return bc.genesisBlock return bc.genesisBlock
@ -228,66 +133,6 @@ func (self *BlockChain) GetChainHashesFromHash(hash []byte, max uint64) (chain [
return 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) { func AddTestNetFunds(block *Block) {
for _, addr := range []string{ for _, addr := range []string{
"51ba59315b3a95761d0863b05ccc7a7f54703d99", "51ba59315b3a95761d0863b05ccc7a7f54703d99",

@ -140,7 +140,7 @@ func (self *StateTransition) preCheck() (err error) {
} }
func (self *StateTransition) TransitionState() (err error) { func (self *StateTransition) TransitionState() (err error) {
statelogger.Infof("(~) %x\n", self.tx.Hash()) statelogger.Debugf("(~) %x\n", self.tx.Hash())
/* /*
defer func() { defer func() {

57
peer.go

@ -474,7 +474,7 @@ func (p *Peer) HandleInbound() {
for it.Next() { for it.Next() {
block := ethchain.NewBlockFromRlpValue(it.Value()) block := ethchain.NewBlockFromRlpValue(it.Value())
blockPool.SetBlock(block) blockPool.SetBlock(block, p)
p.lastBlockReceived = time.Now() p.lastBlockReceived = time.Now()
} }
@ -507,6 +507,7 @@ func (self *Peer) FetchHashes() {
if self.td.Cmp(blockPool.td) >= 0 { if self.td.Cmp(blockPool.td) >= 0 {
peerlogger.Debugf("Requesting hashes from %x\n", self.lastReceivedHash) peerlogger.Debugf("Requesting hashes from %x\n", self.lastReceivedHash)
blockPool.td = self.td
if !blockPool.HasLatestHash() { if !blockPool.HasLatestHash() {
self.QueueMessage(ethwire.NewMessage(ethwire.MsgGetBlockHashesTy, []interface{}{self.lastReceivedHash, uint32(200)})) self.QueueMessage(ethwire.NewMessage(ethwire.MsgGetBlockHashesTy, []interface{}{self.lastReceivedHash, uint32(200)}))
@ -625,7 +626,6 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) {
usedPub := 0 usedPub := 0
// This peer is already added to the peerlist so we expect to find a double pubkey at least once // 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) { eachPeer(p.ethereum.Peers(), func(peer *Peer, e *list.Element) {
if bytes.Compare(p.pubkey, peer.pubkey) == 0 { if bytes.Compare(p.pubkey, peer.pubkey) == 0 {
usedPub++ usedPub++
@ -644,7 +644,6 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) {
return return
} }
// [PROTOCOL_VERSION, NETWORK_ID, CLIENT_ID, CAPS, PORT, PUBKEY]
p.versionKnown = true p.versionKnown = true
// If this is an inbound connection send an ack back // 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) 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)
/* // Compare the total TD with the blockchain TD. If remote is higher
// Catch up with the connected peer // fetch hashes from highest TD node.
if !p.ethereum.IsUpToDate() {
peerlogger.Debugln("Already syncing up with a peer; sleeping")
time.Sleep(10 * time.Second)
}
*/
//p.SyncWithPeerToLastKnown()
if p.td.Cmp(p.ethereum.BlockChain().TD) > 0 { if p.td.Cmp(p.ethereum.BlockChain().TD) > 0 {
p.ethereum.blockPool.AddHash(p.lastReceivedHash) p.ethereum.blockPool.AddHash(p.lastReceivedHash)
p.FetchHashes() 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) 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{} { func (p *Peer) RlpData() []interface{} {
return []interface{}{p.host, p.port, p.pubkey} return []interface{}{p.host, p.port, p.pubkey}