block_processor.go 12.3 KB
Newer Older
obscuren's avatar
obscuren committed
1
package core
obscuren's avatar
obscuren committed
2 3

import (
obscuren's avatar
obscuren committed
4
	"fmt"
obscuren's avatar
obscuren committed
5 6
	"math/big"
	"sync"
obscuren's avatar
obscuren committed
7
	"time"
obscuren's avatar
obscuren committed
8

obscuren's avatar
obscuren committed
9
	"github.com/ethereum/go-ethereum/common"
obscuren's avatar
obscuren committed
10
	"github.com/ethereum/go-ethereum/core/state"
obscuren's avatar
obscuren committed
11
	"github.com/ethereum/go-ethereum/core/types"
12
	"github.com/ethereum/go-ethereum/event"
obscuren's avatar
obscuren committed
13
	"github.com/ethereum/go-ethereum/logger"
obscuren's avatar
obscuren committed
14
	"github.com/ethereum/go-ethereum/logger/glog"
15
	"github.com/ethereum/go-ethereum/params"
obscuren's avatar
obscuren committed
16
	"github.com/ethereum/go-ethereum/pow"
17
	"github.com/ethereum/go-ethereum/rlp"
18
	"gopkg.in/fatih/set.v0"
obscuren's avatar
obscuren committed
19 20
)

21 22 23
const (
	// must be bumped when consensus algorithm is changed, this forces the upgradedb
	// command to be run (forces the blocks to be imported again using the new algorithm)
24
	BlockChainVersion = 2
25 26
)

obscuren's avatar
obscuren committed
27
var statelogger = logger.NewLogger("BLOCK")
zelig's avatar
zelig committed
28

29
type BlockProcessor struct {
obscuren's avatar
obscuren committed
30 31
	db      common.Database
	extraDb common.Database
obscuren's avatar
obscuren committed
32 33
	// Mutex for locking the block processor. Blocks can only be handled one at a time
	mutex sync.Mutex
34
	// Canonical block chain
35
	bc *ChainManager
obscuren's avatar
obscuren committed
36 37
	// non-persistent key/value memory storage
	mem map[string]*big.Int
obscuren's avatar
obscuren committed
38
	// Proof of work used for validating
obscuren's avatar
obscuren committed
39
	Pow pow.PoW
40 41

	txpool *TxPool
obscuren's avatar
obscuren committed
42 43 44 45

	// The last attempted block is mainly used for debugging purposes
	// This does not have to be a valid block and will be set during
	// 'Process' & canonical validation.
46
	lastAttemptedBlock *types.Block
47

48
	events event.Subscription
obscuren's avatar
obscuren committed
49 50

	eventMux *event.TypeMux
obscuren's avatar
obscuren committed
51 52
}

obscuren's avatar
obscuren committed
53
func NewBlockProcessor(db, extra common.Database, pow pow.PoW, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
54
	sm := &BlockProcessor{
obscuren's avatar
obscuren committed
55
		db:       db,
56
		extraDb:  extra,
obscuren's avatar
obscuren committed
57
		mem:      make(map[string]*big.Int),
obscuren's avatar
obscuren committed
58
		Pow:      pow,
59 60 61
		bc:       chainManager,
		eventMux: eventMux,
		txpool:   txpool,
obscuren's avatar
obscuren committed
62
	}
63

64
	return sm
obscuren's avatar
obscuren committed
65 66
}

67
func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block *types.Block, transientProcess bool) (receipts types.Receipts, err error) {
68
	coinbase := statedb.GetOrNewStateObject(block.Header().Coinbase)
69
	coinbase.SetGasPool(block.Header().GasLimit)
obscuren's avatar
obscuren committed
70

71
	// Process the transactions on to parent state
72
	receipts, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
obscuren's avatar
obscuren committed
73 74 75 76 77 78 79
	if err != nil {
		return nil, err
	}

	return receipts, nil
}

80
func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
obscuren's avatar
obscuren committed
81
	// If we are mining this block and validating we want to set the logs back to 0
82
	//statedb.EmptyLogs()
obscuren's avatar
obscuren committed
83

84
	cb := statedb.GetStateObject(coinbase.Address())
85
	_, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, block), tx, cb)
86
	if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
obscuren's avatar
obscuren committed
87
		// If the account is managed, remove the invalid nonce.
88 89
		//from, _ := tx.From()
		//self.bc.TxState().RemoveNonce(from, tx.Nonce())
90 91
		return nil, nil, err
	}
obscuren's avatar
obscuren committed
92 93

	// Update the state with pending changes
obscuren's avatar
obscuren committed
94
	statedb.Update()
obscuren's avatar
obscuren committed
95

96
	cumulative := new(big.Int).Set(usedGas.Add(usedGas, gas))
obscuren's avatar
obscuren committed
97
	receipt := types.NewReceipt(statedb.Root().Bytes(), cumulative)
98 99 100

	logs := statedb.GetLogs(tx.Hash())
	receipt.SetLogs(logs)
obscuren's avatar
obscuren committed
101
	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
obscuren's avatar
obscuren committed
102 103

	glog.V(logger.Debug).Infoln(receipt)
obscuren's avatar
obscuren committed
104 105 106 107

	// Notify all subscribers
	if !transientProcess {
		go self.eventMux.Post(TxPostEvent{tx})
obscuren's avatar
obscuren committed
108
		go self.eventMux.Post(logs)
obscuren's avatar
obscuren committed
109 110
	}

111
	return receipt, gas, err
obscuren's avatar
obscuren committed
112
}
113 114 115
func (self *BlockProcessor) ChainManager() *ChainManager {
	return self.bc
}
obscuren's avatar
obscuren committed
116

117
func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
118
	var (
119 120 121 122
		receipts      types.Receipts
		totalUsedGas  = big.NewInt(0)
		err           error
		cumulativeSum = new(big.Int)
123 124
	)

125 126 127
	for i, tx := range txs {
		statedb.StartRecord(tx.Hash(), block.Hash(), i)

128
		receipt, txGas, err := self.ApplyTransaction(coinbase, statedb, block, tx, totalUsedGas, transientProcess)
129
		if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
130
			return nil, err
131 132
		}

obscuren's avatar
obscuren committed
133
		if err != nil {
obscuren's avatar
obscuren committed
134
			glog.V(logger.Core).Infoln("TX err:", err)
obscuren's avatar
obscuren committed
135 136
		}
		receipts = append(receipts, receipt)
137

obscuren's avatar
obscuren committed
138
		cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
obscuren's avatar
obscuren committed
139
	}
obscuren's avatar
obscuren committed
140

141 142 143
	if block.GasUsed().Cmp(totalUsedGas) != 0 {
		return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
	}
Maran's avatar
Maran committed
144

obscuren's avatar
obscuren committed
145
	if transientProcess {
146
		go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
obscuren's avatar
obscuren committed
147 148
	}

149
	return receipts, err
obscuren's avatar
obscuren committed
150 151
}

152 153 154 155 156 157 158 159 160 161 162 163 164 165
func (sm *BlockProcessor) RetryProcess(block *types.Block) (logs state.Logs, err error) {
	// Processing a blocks may never happen simultaneously
	sm.mutex.Lock()
	defer sm.mutex.Unlock()

	header := block.Header()
	if !sm.bc.HasBlock(header.ParentHash) {
		return nil, ParentError(header.ParentHash)
	}
	parent := sm.bc.GetBlock(header.ParentHash)

	return sm.processWithParent(block, parent)
}

166 167 168
// Process block will attempt to process the given block's transactions and applies them
// on top of the block's parent state (given it exists) and will return wether it was
// successful or not.
169
func (sm *BlockProcessor) Process(block *types.Block) (logs state.Logs, err error) {
obscuren's avatar
obscuren committed
170
	// Processing a blocks may never happen simultaneously
171 172
	sm.mutex.Lock()
	defer sm.mutex.Unlock()
obscuren's avatar
obscuren committed
173

174 175
	header := block.Header()
	if sm.bc.HasBlock(header.Hash()) {
176
		return nil, &KnownBlockError{header.Number, header.Hash()}
obscuren's avatar
obscuren committed
177 178
	}

179
	if !sm.bc.HasBlock(header.ParentHash) {
180
		return nil, ParentError(header.ParentHash)
obscuren's avatar
obscuren committed
181
	}
182
	parent := sm.bc.GetBlock(header.ParentHash)
183

184
	return sm.processWithParent(block, parent)
185
}
obscuren's avatar
obscuren committed
186

187
func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (logs state.Logs, err error) {
obscuren's avatar
obscuren committed
188 189
	sm.lastAttemptedBlock = block

190
	// Create a new state based on the parent's root (e.g., create copy)
191
	state := state.New(parent.Root(), sm.db)
obscuren's avatar
obscuren committed
192

193
	// Block validation
obscuren's avatar
obscuren committed
194
	if err = sm.ValidateHeader(block.Header(), parent.Header()); err != nil {
obscuren's avatar
obscuren committed
195
		return
196 197
	}

obscuren's avatar
obscuren committed
198 199
	// There can be at most two uncles
	if len(block.Uncles()) > 2 {
200
		return nil, ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
obscuren's avatar
obscuren committed
201 202
	}

203
	receipts, err := sm.TransitionState(state, parent, block, false)
204
	if err != nil {
205
		return
206 207
	}

208 209
	header := block.Header()

210 211
	// Validate the received block's bloom with the one derived from the generated receipts.
	// For valid blocks this should always validate to true.
212
	rbloom := types.CreateBloom(receipts)
obscuren's avatar
obscuren committed
213
	if rbloom != header.Bloom {
214 215 216 217
		err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
		return
	}

218
	// The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
219
	// can be used by light clients to make sure they've received the correct Txs
220
	txSha := types.DeriveSha(block.Transactions())
obscuren's avatar
obscuren committed
221
	if txSha != header.TxHash {
222
		err = fmt.Errorf("invalid transaction root hash. received=%x calculated=%x", header.TxHash, txSha)
obscuren's avatar
obscuren committed
223 224
		return
	}
obscuren's avatar
obscuren committed
225

226
	// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
227
	receiptSha := types.DeriveSha(receipts)
obscuren's avatar
obscuren committed
228
	if receiptSha != header.ReceiptHash {
229 230 231 232 233 234 235 236
		err = fmt.Errorf("invalid receipt root hash. received=%x calculated=%x", header.ReceiptHash, receiptSha)
		return
	}

	// Verify UncleHash before running other uncle validations
	unclesSha := block.CalculateUnclesHash()
	if unclesSha != header.UncleHash {
		err = fmt.Errorf("invalid uncles root hash. received=%x calculated=%x", header.UncleHash, unclesSha)
237 238
		return
	}
obscuren's avatar
obscuren committed
239

obscuren's avatar
obscuren committed
240 241
	// Verify uncles
	if err = sm.VerifyUncles(state, block, parent); err != nil {
242
		return
obscuren's avatar
obscuren committed
243
	}
obscuren's avatar
obscuren committed
244 245
	// Accumulate static rewards; block reward, uncle's and uncle inclusion.
	AccumulateRewards(state, block)
obscuren's avatar
obscuren committed
246

247 248
	// Commit state objects/accounts to a temporary trie (does not save)
	// used to calculate the state root.
obscuren's avatar
obscuren committed
249
	state.Update()
obscuren's avatar
obscuren committed
250
	if header.Root != state.Root() {
251
		err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
252
		return
obscuren's avatar
obscuren committed
253 254
	}

255
	// Calculate the td for this block
256
	//td = CalculateTD(block, parent)
obscuren's avatar
obscuren committed
257
	// Sync the current block's state to the database
258
	state.Sync()
obscuren's avatar
obscuren committed
259

obscuren's avatar
obscuren committed
260
	// Remove transactions from the pool
261
	sm.txpool.RemoveTransactions(block.Transactions())
obscuren's avatar
obscuren committed
262

263 264
	// This puts transactions in a extra db for rpc
	for i, tx := range block.Transactions() {
265
		putTx(sm.extraDb, tx, block, uint64(i))
266 267
	}

268
	return state.Logs(), nil
obscuren's avatar
obscuren committed
269 270 271 272 273
}

// Validates the current block. Returns an error if the block was invalid,
// an uncle or anything that isn't on the current block chain.
// Validation validates easy over difficult (dagger takes longer time = difficult)
obscuren's avatar
obscuren committed
274
func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
275
	if big.NewInt(int64(len(block.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
obscuren's avatar
obscuren committed
276
		return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
obscuren's avatar
obscuren committed
277 278
	}

279
	expd := CalcDifficulty(block, parent)
obscuren's avatar
obscuren committed
280 281
	if expd.Cmp(block.Difficulty) != 0 {
		return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
282 283
	}

284
	// block.gasLimit - parent.gasLimit <= parent.gasLimit / GasLimitBoundDivisor
obscuren's avatar
obscuren committed
285
	a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
286
	a.Abs(a)
287 288
	b := new(big.Int).Div(parent.GasLimit, params.GasLimitBoundDivisor)
	if !(a.Cmp(b) < 0) || (block.GasLimit.Cmp(params.MinGasLimit) == -1) {
obscuren's avatar
obscuren committed
289
		return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
Matthew Wampler-Doty's avatar
Matthew Wampler-Doty committed
290 291
	}

obscuren's avatar
obscuren committed
292
	// Allow future blocks up to 10 seconds
293
	if int64(block.Time) > time.Now().Unix()+4 {
294 295 296
		return BlockFutureErr
	}

obscuren's avatar
obscuren committed
297
	if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
298
		return BlockNumberErr
obscuren's avatar
obscuren committed
299 300
	}

obscuren's avatar
obscuren committed
301 302 303 304
	if block.Time <= parent.Time {
		return BlockEqualTSErr //ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
	}

obscuren's avatar
obscuren committed
305
	// Verify the nonce of the block. Return an error if it's not valid
obscuren's avatar
obscuren committed
306 307
	if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
		return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
obscuren's avatar
obscuren committed
308 309 310 311 312
	}

	return nil
}

obscuren's avatar
obscuren committed
313
func AccumulateRewards(statedb *state.StateDB, block *types.Block) {
314
	reward := new(big.Int).Set(BlockReward)
obscuren's avatar
obscuren committed
315

obscuren's avatar
obscuren committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	for _, uncle := range block.Uncles() {
		num := new(big.Int).Add(big.NewInt(8), uncle.Number)
		num.Sub(num, block.Number())

		r := new(big.Int)
		r.Mul(BlockReward, num)
		r.Div(r, big.NewInt(8))

		statedb.AddBalance(uncle.Coinbase, r)

		reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
	}

	// Get the account associated with the coinbase
	statedb.AddBalance(block.Header().Coinbase, reward)
}

func (sm *BlockProcessor) VerifyUncles(statedb *state.StateDB, block, parent *types.Block) error {
334
	ancestors := set.New()
obscuren's avatar
obscuren committed
335
	uncles := set.New()
obscuren's avatar
obscuren committed
336
	ancestorHeaders := make(map[common.Hash]*types.Header)
obscuren's avatar
obscuren committed
337
	for _, ancestor := range sm.bc.GetAncestors(block, 7) {
obscuren's avatar
obscuren committed
338 339
		ancestorHeaders[ancestor.Hash()] = ancestor.Header()
		ancestors.Add(ancestor.Hash())
obscuren's avatar
obscuren committed
340 341
		// Include ancestors uncles in the uncle set. Uncles must be unique.
		for _, uncle := range ancestor.Uncles() {
obscuren's avatar
obscuren committed
342
			uncles.Add(uncle.Hash())
obscuren's avatar
obscuren committed
343
		}
344 345
	}

obscuren's avatar
obscuren committed
346
	uncles.Add(block.Hash())
347
	for i, uncle := range block.Uncles() {
obscuren's avatar
obscuren committed
348
		if uncles.Has(uncle.Hash()) {
obscuren's avatar
obscuren committed
349 350 351
			// Error not unique
			return UncleError("Uncle not unique")
		}
obscuren's avatar
obscuren committed
352

obscuren's avatar
obscuren committed
353
		uncles.Add(uncle.Hash())
obscuren's avatar
obscuren committed
354

obscuren's avatar
obscuren committed
355
		if ancestors.Has(uncle.Hash()) {
obscuren's avatar
obscuren committed
356 357 358
			return UncleError("Uncle is ancestor")
		}

obscuren's avatar
obscuren committed
359
		if !ancestors.Has(uncle.ParentHash) {
360
			return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
obscuren's avatar
obscuren committed
361
		}
obscuren's avatar
obscuren committed
362

363
		if err := sm.ValidateHeader(uncle, ancestorHeaders[uncle.ParentHash]); err != nil {
364
			return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, uncle.Hash().Bytes()[:4], err))
obscuren's avatar
obscuren committed
365
		}
obscuren's avatar
obscuren committed
366
	}
obscuren's avatar
obscuren committed
367 368 369 370

	return nil
}

obscuren's avatar
obscuren committed
371 372 373 374 375 376 377 378 379
func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err error) {
	if !sm.bc.HasBlock(block.Header().ParentHash) {
		return nil, ParentError(block.Header().ParentHash)
	}

	sm.lastAttemptedBlock = block

	var (
		parent = sm.bc.GetBlock(block.Header().ParentHash)
380
		state  = state.New(parent.Root(), sm.db)
obscuren's avatar
obscuren committed
381 382
	)

383
	sm.TransitionState(state, parent, block, true)
obscuren's avatar
obscuren committed
384 385 386

	return state.Logs(), nil
}
387

388
func putTx(db common.Database, tx *types.Transaction, block *types.Block, i uint64) {
389 390
	rlpEnc, err := rlp.EncodeToBytes(tx)
	if err != nil {
obscuren's avatar
obscuren committed
391
		glog.V(logger.Debug).Infoln("Failed encoding tx", err)
392 393
		return
	}
obscuren's avatar
obscuren committed
394
	db.Put(tx.Hash().Bytes(), rlpEnc)
395

396 397 398 399
	var txExtra struct {
		BlockHash  common.Hash
		BlockIndex uint64
		Index      uint64
400
	}
401 402 403 404
	txExtra.BlockHash = block.Hash()
	txExtra.BlockIndex = block.NumberU64()
	txExtra.Index = i
	rlpMeta, err := rlp.EncodeToBytes(txExtra)
405
	if err != nil {
obscuren's avatar
obscuren committed
406
		glog.V(logger.Debug).Infoln("Failed encoding tx meta data", err)
407 408
		return
	}
409
	db.Put(append(tx.Hash().Bytes(), 0x0001), rlpMeta)
410
}