Added TD for each block

This commit is contained in:
obscuren
2014-09-24 11:39:17 +02:00
parent 615d20598a
commit 57dc435f9b
4 changed files with 44 additions and 2 deletions
+3 -1
View File
@@ -18,6 +18,7 @@ type BlockInfo struct {
Number uint64
Hash []byte
Parent []byte
TD *big.Int
}
func (bi *BlockInfo) RlpDecode(data []byte) {
@@ -26,10 +27,11 @@ func (bi *BlockInfo) RlpDecode(data []byte) {
bi.Number = decoder.Get(0).Uint()
bi.Hash = decoder.Get(1).Bytes()
bi.Parent = decoder.Get(2).Bytes()
bi.TD = decoder.Get(3).BigInt()
}
func (bi *BlockInfo) RlpEncode() []byte {
return ethutil.Encode([]interface{}{bi.Number, bi.Hash, bi.Parent})
return ethutil.Encode([]interface{}{bi.Number, bi.Hash, bi.Parent, bi.TD})
}
type Blocks []*Block
+22 -1
View File
@@ -2,6 +2,7 @@ package ethchain
import (
"bytes"
"fmt"
"math/big"
"github.com/ethereum/eth-go/ethlog"
@@ -191,6 +192,26 @@ func (bc *BlockChain) Add(block *Block) {
ethutil.Config.Db.Put([]byte("LastBlock"), encodedBlock)
}
func (self *BlockChain) CalcTotalDiff(block *Block) (*big.Int, error) {
parent := self.GetBlock(block.PrevHash)
if parent == nil {
return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.PrevHash)
}
parentTd := parent.BlockInfo().TD
uncleDiff := new(big.Int)
for _, uncle := range block.Uncles {
uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)
}
td := new(big.Int)
td = td.Add(parentTd, uncleDiff)
td = td.Add(td, block.Difficulty)
return td, nil
}
func (bc *BlockChain) GetBlock(hash []byte) *Block {
data, _ := ethutil.Config.Db.Get(hash)
if len(data) == 0 {
@@ -234,7 +255,7 @@ func (bc *BlockChain) BlockInfo(block *Block) BlockInfo {
// Unexported method for writing extra non-essential block info to the db
func (bc *BlockChain) writeBlockInfo(block *Block) {
bc.LastBlockNumber++
bi := BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash}
bi := BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash, TD: bc.TD}
// For now we use the block hash with the words "info" appended as key
ethutil.Config.Db.Put(append(block.Hash(), []byte("Info")...), bi.RlpEncode())