chain_manager.go 6.8 KB
Newer Older
O
obscuren 已提交
1 2 3 4
package ethchain

import (
	"bytes"
O
obscuren 已提交
5
	"fmt"
6 7
	"math/big"

8 9
	"github.com/ethereum/go-ethereum/ethlog"
	"github.com/ethereum/go-ethereum/ethutil"
O
obscuren 已提交
10 11
)

Z
zelig 已提交
12 13
var chainlogger = ethlog.NewLogger("CHAIN")

O
obscuren 已提交
14
type ChainManager struct {
15
	Ethereum EthManager
O
obscuren 已提交
16 17 18 19 20 21 22 23 24 25 26
	// The famous, the fabulous Mister GENESIIIIIIS (block)
	genesisBlock *Block
	// Last known total difficulty
	TD *big.Int

	LastBlockNumber uint64

	CurrentBlock  *Block
	LastBlockHash []byte
}

O
obscuren 已提交
27 28
func NewChainManager(ethereum EthManager) *ChainManager {
	bc := &ChainManager{}
M
Maran 已提交
29
	bc.genesisBlock = NewBlockFromBytes(ethutil.Encode(Genesis))
M
Maran 已提交
30
	bc.Ethereum = ethereum
O
obscuren 已提交
31 32 33 34 35 36

	bc.setLastBlock()

	return bc
}

O
obscuren 已提交
37
func (bc *ChainManager) Genesis() *Block {
O
obscuren 已提交
38 39 40
	return bc.genesisBlock
}

O
obscuren 已提交
41
func (bc *ChainManager) NewBlock(coinbase []byte) *Block {
O
obscuren 已提交
42 43 44 45
	var root interface{}
	hash := ZeroHash256

	if bc.CurrentBlock != nil {
O
obscuren 已提交
46
		root = bc.CurrentBlock.state.Trie.Root
O
obscuren 已提交
47 48
		hash = bc.LastBlockHash
	}
49

O
obscuren 已提交
50 51 52 53 54 55
	block := CreateBlock(
		root,
		hash,
		coinbase,
		ethutil.BigPow(2, 32),
		nil,
O
obscuren 已提交
56
		"")
O
obscuren 已提交
57

O
obscuren 已提交
58 59
	block.MinGasPrice = big.NewInt(10000000000000)

O
obscuren 已提交
60 61
	parent := bc.CurrentBlock
	if parent != nil {
62
		block.Difficulty = CalcDifficulty(block, parent)
O
obscuren 已提交
63
		block.Number = new(big.Int).Add(bc.CurrentBlock.Number, ethutil.Big1)
M
Maran 已提交
64
		block.GasLimit = block.CalcGasLimit(bc.CurrentBlock)
O
obscuren 已提交
65

O
obscuren 已提交
66 67 68 69 70
	}

	return block
}

71 72 73 74 75 76 77 78 79 80 81 82 83
func CalcDifficulty(block, parent *Block) *big.Int {
	diff := new(big.Int)

	adjust := new(big.Int).Rsh(parent.Difficulty, 10)
	if block.Time >= parent.Time+5 {
		diff.Sub(parent.Difficulty, adjust)
	} else {
		diff.Add(parent.Difficulty, adjust)
	}

	return diff
}

O
obscuren 已提交
84
func (bc *ChainManager) Reset() {
O
obscuren 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97
	AddTestNetFunds(bc.genesisBlock)

	bc.genesisBlock.state.Trie.Sync()
	// Prepare the genesis block
	bc.Add(bc.genesisBlock)
	bc.CurrentBlock = bc.genesisBlock

	bc.SetTotalDifficulty(ethutil.Big("0"))

	// Set the last know difficulty (might be 0x0 as initial value, Genesis)
	bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD())
}

O
obscuren 已提交
98
func (bc *ChainManager) HasBlock(hash []byte) bool {
O
obscuren 已提交
99 100 101 102
	data, _ := ethutil.Config.Db.Get(hash)
	return len(data) != 0
}

M
Maran 已提交
103
// TODO: At one point we might want to save a block by prevHash in the db to optimise this...
O
obscuren 已提交
104
func (bc *ChainManager) HasBlockWithPrevHash(hash []byte) bool {
M
Maran 已提交
105 106 107 108 109 110 111 112 113 114
	block := bc.CurrentBlock

	for ; block != nil; block = bc.GetBlock(block.PrevHash) {
		if bytes.Compare(hash, block.PrevHash) == 0 {
			return true
		}
	}
	return false
}

O
obscuren 已提交
115
func (bc *ChainManager) CalculateBlockTD(block *Block) *big.Int {
M
Maran 已提交
116 117 118 119 120 121 122 123 124 125
	blockDiff := new(big.Int)

	for _, uncle := range block.Uncles {
		blockDiff = blockDiff.Add(blockDiff, uncle.Difficulty)
	}
	blockDiff = blockDiff.Add(blockDiff, block.Difficulty)

	return blockDiff
}

O
obscuren 已提交
126
func (bc *ChainManager) GenesisBlock() *Block {
O
obscuren 已提交
127 128 129
	return bc.genesisBlock
}

O
obscuren 已提交
130
func (self *ChainManager) GetChainHashesFromHash(hash []byte, max uint64) (chain [][]byte) {
O
obscuren 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
	block := self.GetBlock(hash)
	if block == nil {
		return
	}

	// XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
	for i := uint64(0); i < max; i++ {
		chain = append(chain, block.Hash())

		if block.Number.Cmp(ethutil.Big0) <= 0 {
			break
		}

		block = self.GetBlock(block.PrevHash)
	}

	return
}

150 151
func AddTestNetFunds(block *Block) {
	for _, addr := range []string{
O
obscuren 已提交
152
		"51ba59315b3a95761d0863b05ccc7a7f54703d99",
O
obscuren 已提交
153
		"e4157b34ea9615cfbde6b4fda419828124b70c78",
O
Up  
obscuren 已提交
154
		"b9c015918bdaba24b4ff057a92a3873d6eb201be",
O
obscuren 已提交
155 156 157 158 159
		"6c386a4b26f73c802f34673f7248bb118f97424a",
		"cd2a3d9f938e13cd947ec05abc7fe734df8dd826",
		"2ef47100e0787b915105fd5e3f4ff6752079d5cb",
		"e6716f9544a56c530d868e4bfbacb172315bdead",
		"1a26338f0d905e295fccb71fa9ea849ffa12aaf4",
160
	} {
161
		codedAddr := ethutil.Hex2Bytes(addr)
162
		account := block.state.GetAccount(codedAddr)
O
obscuren 已提交
163
		account.SetBalance(ethutil.Big("1606938044258990275541962092341162602522202993782792835301376")) //ethutil.BigPow(2, 200)
164
		block.state.UpdateStateObject(account)
165 166 167
	}
}

O
obscuren 已提交
168
func (bc *ChainManager) setLastBlock() {
O
obscuren 已提交
169 170
	data, _ := ethutil.Config.Db.Get([]byte("LastBlock"))
	if len(data) != 0 {
O
obscuren 已提交
171 172 173
		// Prep genesis
		AddTestNetFunds(bc.genesisBlock)

O
obscuren 已提交
174 175 176
		block := NewBlockFromBytes(data)
		bc.CurrentBlock = block
		bc.LastBlockHash = block.Hash()
O
obscuren 已提交
177
		bc.LastBlockNumber = block.Number.Uint64()
O
obscuren 已提交
178

O
obscuren 已提交
179 180
		// Set the last know difficulty (might be 0x0 as initial value, Genesis)
		bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD())
181
	} else {
O
obscuren 已提交
182
		bc.Reset()
O
obscuren 已提交
183 184
	}

O
obscuren 已提交
185
	chainlogger.Infof("Last block (#%d) %x\n", bc.LastBlockNumber, bc.CurrentBlock.Hash())
O
obscuren 已提交
186 187
}

O
obscuren 已提交
188
func (bc *ChainManager) SetTotalDifficulty(td *big.Int) {
O
obscuren 已提交
189
	ethutil.Config.Db.Put([]byte("LTD"), td.Bytes())
O
obscuren 已提交
190 191 192 193
	bc.TD = td
}

// Add a block to the chain and record addition information
O
obscuren 已提交
194
func (bc *ChainManager) Add(block *Block) {
O
obscuren 已提交
195 196
	bc.writeBlockInfo(block)
	// Prepare the genesis block
M
Maran 已提交
197

O
obscuren 已提交
198 199 200
	bc.CurrentBlock = block
	bc.LastBlockHash = block.Hash()

O
obscuren 已提交
201 202 203
	encodedBlock := block.RlpEncode()
	ethutil.Config.Db.Put(block.Hash(), encodedBlock)
	ethutil.Config.Db.Put([]byte("LastBlock"), encodedBlock)
O
obscuren 已提交
204 205
}

O
obscuren 已提交
206
func (self *ChainManager) CalcTotalDiff(block *Block) (*big.Int, error) {
O
obscuren 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
	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
}

O
obscuren 已提交
226
func (bc *ChainManager) GetBlock(hash []byte) *Block {
O
obscuren 已提交
227
	data, _ := ethutil.Config.Db.Get(hash)
O
obscuren 已提交
228 229 230
	if len(data) == 0 {
		return nil
	}
O
obscuren 已提交
231

M
Maran 已提交
232
	return NewBlockFromBytes(data)
O
obscuren 已提交
233 234
}

O
obscuren 已提交
235
func (self *ChainManager) GetBlockByNumber(num uint64) *Block {
O
obscuren 已提交
236
	block := self.CurrentBlock
O
obscuren 已提交
237 238 239 240
	for ; block != nil; block = self.GetBlock(block.PrevHash) {
		if block.Number.Uint64() == num {
			break
		}
O
obscuren 已提交
241 242
	}

O
obscuren 已提交
243
	if block != nil && block.Number.Uint64() == 0 && num != 0 {
O
obscuren 已提交
244 245 246 247 248 249
		return nil
	}

	return block
}

O
obscuren 已提交
250
func (self *ChainManager) GetBlockBack(num uint64) *Block {
O
obscuren 已提交
251 252 253 254 255 256 257 258 259
	block := self.CurrentBlock

	for ; num != 0 && block != nil; num-- {
		block = self.GetBlock(block.PrevHash)
	}

	return block
}

O
obscuren 已提交
260
func (bc *ChainManager) BlockInfoByHash(hash []byte) BlockInfo {
O
obscuren 已提交
261 262 263 264 265 266 267
	bi := BlockInfo{}
	data, _ := ethutil.Config.Db.Get(append(hash, []byte("Info")...))
	bi.RlpDecode(data)

	return bi
}

O
obscuren 已提交
268
func (bc *ChainManager) BlockInfo(block *Block) BlockInfo {
O
obscuren 已提交
269 270 271 272 273 274 275 276
	bi := BlockInfo{}
	data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...))
	bi.RlpDecode(data)

	return bi
}

// Unexported method for writing extra non-essential block info to the db
O
obscuren 已提交
277
func (bc *ChainManager) writeBlockInfo(block *Block) {
O
obscuren 已提交
278
	bc.LastBlockNumber++
O
obscuren 已提交
279
	bi := BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash, TD: bc.TD}
O
obscuren 已提交
280 281 282 283 284

	// 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())
}

O
obscuren 已提交
285
func (bc *ChainManager) Stop() {
O
obscuren 已提交
286
	if bc.CurrentBlock != nil {
Z
zelig 已提交
287
		chainlogger.Infoln("Stopped")
O
obscuren 已提交
288 289
	}
}