block_processor.go 11.7 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 24 25 26
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)
	BlockChainVersion = 1
)

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
// 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.
155
func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, logs state.Logs, err error) {
obscuren's avatar
obscuren committed
156
	// Processing a blocks may never happen simultaneously
157 158
	sm.mutex.Lock()
	defer sm.mutex.Unlock()
obscuren's avatar
obscuren committed
159

160 161
	header := block.Header()
	if sm.bc.HasBlock(header.Hash()) {
162
		return nil, nil, &KnownBlockError{header.Number, header.Hash()}
obscuren's avatar
obscuren committed
163 164
	}

165
	if !sm.bc.HasBlock(header.ParentHash) {
166
		return nil, nil, ParentError(header.ParentHash)
obscuren's avatar
obscuren committed
167
	}
168
	parent := sm.bc.GetBlock(header.ParentHash)
169

170
	return sm.processWithParent(block, parent)
171
}
obscuren's avatar
obscuren committed
172

173
func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (td *big.Int, logs state.Logs, err error) {
obscuren's avatar
obscuren committed
174 175
	sm.lastAttemptedBlock = block

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

179
	// Block validation
obscuren's avatar
obscuren committed
180
	if err = sm.ValidateHeader(block.Header(), parent.Header()); err != nil {
obscuren's avatar
obscuren committed
181
		return
182 183
	}

obscuren's avatar
obscuren committed
184 185
	// There can be at most two uncles
	if len(block.Uncles()) > 2 {
186
		return nil, nil, ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
obscuren's avatar
obscuren committed
187 188
	}

189
	receipts, err := sm.TransitionState(state, parent, block, false)
190
	if err != nil {
191
		return
192 193
	}

194 195
	header := block.Header()

196 197
	// Validate the received block's bloom with the one derived from the generated receipts.
	// For valid blocks this should always validate to true.
198
	rbloom := types.CreateBloom(receipts)
obscuren's avatar
obscuren committed
199
	if rbloom != header.Bloom {
200 201 202 203
		err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
		return
	}

204
	// The transactions Trie's root (R = (Tr [[i, RLP(T1)], [i, RLP(T2)], ... [n, RLP(Tn)]]))
205
	// can be used by light clients to make sure they've received the correct Txs
206
	txSha := types.DeriveSha(block.Transactions())
obscuren's avatar
obscuren committed
207
	if txSha != header.TxHash {
208
		err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
obscuren's avatar
obscuren committed
209 210
		return
	}
obscuren's avatar
obscuren committed
211

212
	// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
213
	receiptSha := types.DeriveSha(receipts)
obscuren's avatar
obscuren committed
214
	if receiptSha != header.ReceiptHash {
215
		err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
216 217
		return
	}
obscuren's avatar
obscuren committed
218

obscuren's avatar
obscuren committed
219 220
	// Verify uncles
	if err = sm.VerifyUncles(state, block, parent); err != nil {
221
		return
obscuren's avatar
obscuren committed
222
	}
obscuren's avatar
obscuren committed
223 224
	// Accumulate static rewards; block reward, uncle's and uncle inclusion.
	AccumulateRewards(state, block)
obscuren's avatar
obscuren committed
225

226 227
	// Commit state objects/accounts to a temporary trie (does not save)
	// used to calculate the state root.
obscuren's avatar
obscuren committed
228
	state.Update()
obscuren's avatar
obscuren committed
229
	if header.Root != state.Root() {
230
		err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
231
		return
obscuren's avatar
obscuren committed
232 233
	}

234 235
	// Calculate the td for this block
	td = CalculateTD(block, parent)
obscuren's avatar
obscuren committed
236
	// Sync the current block's state to the database
237
	state.Sync()
obscuren's avatar
obscuren committed
238

obscuren's avatar
obscuren committed
239 240
	// Remove transactions from the pool
	sm.txpool.RemoveSet(block.Transactions())
obscuren's avatar
obscuren committed
241

242 243
	// This puts transactions in a extra db for rpc
	for i, tx := range block.Transactions() {
244
		putTx(sm.extraDb, tx, block, uint64(i))
245 246
	}

247
	return td, state.Logs(), nil
obscuren's avatar
obscuren committed
248 249 250 251 252
}

// 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
253
func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
254
	if big.NewInt(int64(len(block.Extra))).Cmp(params.MaximumExtraDataSize) == 1 {
obscuren's avatar
obscuren committed
255
		return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
obscuren's avatar
obscuren committed
256 257
	}

258
	expd := CalcDifficulty(block, parent)
obscuren's avatar
obscuren committed
259 260
	if expd.Cmp(block.Difficulty) != 0 {
		return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
261 262
	}

263
	// block.gasLimit - parent.gasLimit <= parent.gasLimit / GasLimitBoundDivisor
obscuren's avatar
obscuren committed
264
	a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
265
	a.Abs(a)
266 267
	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
268
		return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
Matthew Wampler-Doty's avatar
Matthew Wampler-Doty committed
269 270
	}

obscuren's avatar
obscuren committed
271
	// Allow future blocks up to 10 seconds
272
	if int64(block.Time) > time.Now().Unix()+4 {
273 274 275
		return BlockFutureErr
	}

obscuren's avatar
obscuren committed
276
	if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
277
		return BlockNumberErr
obscuren's avatar
obscuren committed
278 279
	}

obscuren's avatar
obscuren committed
280 281 282 283
	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
284
	// Verify the nonce of the block. Return an error if it's not valid
obscuren's avatar
obscuren committed
285 286
	if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
		return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
obscuren's avatar
obscuren committed
287 288 289 290 291
	}

	return nil
}

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

obscuren's avatar
obscuren committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
	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 {
313
	ancestors := set.New()
obscuren's avatar
obscuren committed
314
	uncles := set.New()
obscuren's avatar
obscuren committed
315
	ancestorHeaders := make(map[common.Hash]*types.Header)
obscuren's avatar
obscuren committed
316
	for _, ancestor := range sm.bc.GetAncestors(block, 7) {
obscuren's avatar
obscuren committed
317 318
		ancestorHeaders[ancestor.Hash()] = ancestor.Header()
		ancestors.Add(ancestor.Hash())
obscuren's avatar
obscuren committed
319 320
		// Include ancestors uncles in the uncle set. Uncles must be unique.
		for _, uncle := range ancestor.Uncles() {
obscuren's avatar
obscuren committed
321
			uncles.Add(uncle.Hash())
obscuren's avatar
obscuren committed
322
		}
323 324
	}

obscuren's avatar
obscuren committed
325
	uncles.Add(block.Hash())
326
	for i, uncle := range block.Uncles() {
obscuren's avatar
obscuren committed
327
		if uncles.Has(uncle.Hash()) {
obscuren's avatar
obscuren committed
328 329 330
			// Error not unique
			return UncleError("Uncle not unique")
		}
obscuren's avatar
obscuren committed
331

obscuren's avatar
obscuren committed
332
		uncles.Add(uncle.Hash())
obscuren's avatar
obscuren committed
333

obscuren's avatar
obscuren committed
334
		if ancestors.Has(uncle.Hash()) {
obscuren's avatar
obscuren committed
335 336 337
			return UncleError("Uncle is ancestor")
		}

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

342
		if err := sm.ValidateHeader(uncle, ancestorHeaders[uncle.ParentHash]); err != nil {
343
			return ValidationError(fmt.Sprintf("uncle[%d](%x) header invalid: %v", i, uncle.Hash().Bytes()[:4], err))
obscuren's avatar
obscuren committed
344
		}
obscuren's avatar
obscuren committed
345
	}
obscuren's avatar
obscuren committed
346 347 348 349

	return nil
}

obscuren's avatar
obscuren committed
350 351 352 353 354 355 356 357 358
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)
359
		state  = state.New(parent.Root(), sm.db)
obscuren's avatar
obscuren committed
360 361
	)

362
	sm.TransitionState(state, parent, block, true)
obscuren's avatar
obscuren committed
363 364 365

	return state.Logs(), nil
}
366

367
func putTx(db common.Database, tx *types.Transaction, block *types.Block, i uint64) {
368 369
	rlpEnc, err := rlp.EncodeToBytes(tx)
	if err != nil {
obscuren's avatar
obscuren committed
370
		glog.V(logger.Debug).Infoln("Failed encoding tx", err)
371 372
		return
	}
obscuren's avatar
obscuren committed
373
	db.Put(tx.Hash().Bytes(), rlpEnc)
374

375 376 377 378
	var txExtra struct {
		BlockHash  common.Hash
		BlockIndex uint64
		Index      uint64
379
	}
380 381 382 383
	txExtra.BlockHash = block.Hash()
	txExtra.BlockIndex = block.NumberU64()
	txExtra.Index = i
	rlpMeta, err := rlp.EncodeToBytes(txExtra)
384
	if err != nil {
obscuren's avatar
obscuren committed
385
		glog.V(logger.Debug).Infoln("Failed encoding tx meta data", err)
386 387
		return
	}
388
	db.Put(append(tx.Hash().Bytes(), 0x0001), rlpMeta)
389
}