block_processor.go 10.8 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/types"
11
	"github.com/ethereum/go-ethereum/event"
obscuren's avatar
obscuren committed
12
	"github.com/ethereum/go-ethereum/logger"
obscuren's avatar
obscuren committed
13
	"github.com/ethereum/go-ethereum/pow"
14
	"github.com/ethereum/go-ethereum/rlp"
obscuren's avatar
obscuren committed
15
	"github.com/ethereum/go-ethereum/state"
16
	"gopkg.in/fatih/set.v0"
obscuren's avatar
obscuren committed
17 18
)

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

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

	txpool *TxPool
obscuren's avatar
obscuren committed
34 35 36 37

	// 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.
38
	lastAttemptedBlock *types.Block
39

40
	events event.Subscription
obscuren's avatar
obscuren committed
41 42

	eventMux *event.TypeMux
obscuren's avatar
obscuren committed
43 44
}

obscuren's avatar
obscuren committed
45
func NewBlockProcessor(db, extra common.Database, pow pow.PoW, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor {
46
	sm := &BlockProcessor{
obscuren's avatar
obscuren committed
47
		db:       db,
48
		extraDb:  extra,
obscuren's avatar
obscuren committed
49
		mem:      make(map[string]*big.Int),
obscuren's avatar
obscuren committed
50
		Pow:      pow,
51 52 53
		bc:       chainManager,
		eventMux: eventMux,
		txpool:   txpool,
obscuren's avatar
obscuren committed
54
	}
55

56
	return sm
obscuren's avatar
obscuren committed
57 58
}

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

63
	// Process the transactions on to parent state
64
	receipts, _, _, _, err = sm.ApplyTransactions(coinbase, statedb, block, block.Transactions(), transientProcess)
obscuren's avatar
obscuren committed
65 66 67 68 69 70 71
	if err != nil {
		return nil, err
	}

	return receipts, nil
}

72
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
73
	// If we are mining this block and validating we want to set the logs back to 0
74
	statedb.EmptyLogs()
obscuren's avatar
obscuren committed
75

76
	cb := statedb.GetStateObject(coinbase.Address())
77
	_, gas, err := ApplyMessage(NewEnv(statedb, self.bc, tx, block), tx, cb)
78
	if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
obscuren's avatar
obscuren committed
79
		// If the account is managed, remove the invalid nonce.
80 81
		from, _ := tx.From()
		self.bc.TxState().RemoveNonce(from, tx.Nonce())
82 83
		return nil, nil, err
	}
obscuren's avatar
obscuren committed
84 85

	// Update the state with pending changes
86
	statedb.Update(nil)
obscuren's avatar
obscuren committed
87

88
	cumulative := new(big.Int).Set(usedGas.Add(usedGas, gas))
obscuren's avatar
obscuren committed
89
	receipt := types.NewReceipt(statedb.Root().Bytes(), cumulative)
90
	receipt.SetLogs(statedb.Logs())
obscuren's avatar
obscuren committed
91 92 93 94 95 96
	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
	chainlogger.Debugln(receipt)

	// Notify all subscribers
	if !transientProcess {
		go self.eventMux.Post(TxPostEvent{tx})
obscuren's avatar
obscuren committed
97 98
		logs := statedb.Logs()
		go self.eventMux.Post(logs)
obscuren's avatar
obscuren committed
99 100
	}

101
	return receipt, gas, err
obscuren's avatar
obscuren committed
102
}
103 104 105
func (self *BlockProcessor) ChainManager() *ChainManager {
	return self.bc
}
obscuren's avatar
obscuren committed
106

107
func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
108
	var (
109 110 111
		receipts           types.Receipts
		handled, unhandled types.Transactions
		erroneous          types.Transactions
112 113
		totalUsedGas       = big.NewInt(0)
		err                error
obscuren's avatar
obscuren committed
114
		cumulativeSum      = new(big.Int)
115 116
	)

117
	for _, tx := range txs {
118
		receipt, txGas, err := self.ApplyTransaction(coinbase, statedb, block, tx, totalUsedGas, transientProcess)
119 120 121 122
		if err != nil && (IsNonceErr(err) || state.IsGasLimitErr(err) || IsInvalidTxErr(err)) {
			return nil, nil, nil, nil, err
		}

obscuren's avatar
obscuren committed
123
		if err != nil {
124
			statelogger.Infoln("TX err:", err)
obscuren's avatar
obscuren committed
125 126
		}
		receipts = append(receipts, receipt)
127
		handled = append(handled, tx)
128

obscuren's avatar
obscuren committed
129
		cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
obscuren's avatar
obscuren committed
130
	}
obscuren's avatar
obscuren committed
131

obscuren's avatar
obscuren committed
132
	block.Reward = cumulativeSum
133
	block.Header().GasUsed = totalUsedGas
Maran's avatar
Maran committed
134

obscuren's avatar
obscuren committed
135
	if transientProcess {
136
		go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
obscuren's avatar
obscuren committed
137 138
	}

139
	return receipts, handled, unhandled, erroneous, err
obscuren's avatar
obscuren committed
140 141
}

142 143 144
// 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.
145
func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, logs state.Logs, err error) {
obscuren's avatar
obscuren committed
146
	// Processing a blocks may never happen simultaneously
147 148
	sm.mutex.Lock()
	defer sm.mutex.Unlock()
obscuren's avatar
obscuren committed
149

150 151
	header := block.Header()
	if sm.bc.HasBlock(header.Hash()) {
152
		return nil, nil, &KnownBlockError{header.Number, header.Hash()}
obscuren's avatar
obscuren committed
153 154
	}

155
	if !sm.bc.HasBlock(header.ParentHash) {
156
		return nil, nil, ParentError(header.ParentHash)
obscuren's avatar
obscuren committed
157
	}
158
	parent := sm.bc.GetBlock(header.ParentHash)
159

160
	return sm.processWithParent(block, parent)
161
}
obscuren's avatar
obscuren committed
162

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

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

169
	// Block validation
obscuren's avatar
obscuren committed
170
	if err = sm.ValidateHeader(block.Header(), parent.Header()); err != nil {
171
		return
172 173
	}

obscuren's avatar
obscuren committed
174 175
	// There can be at most two uncles
	if len(block.Uncles()) > 2 {
176
		return nil, nil, ValidationError("Block can only contain one uncle (contained %v)", len(block.Uncles()))
obscuren's avatar
obscuren committed
177 178
	}

179
	receipts, err := sm.TransitionState(state, parent, block, false)
180
	if err != nil {
181
		return
182 183
	}

184 185
	header := block.Header()

186 187
	// Validate the received block's bloom with the one derived from the generated receipts.
	// For valid blocks this should always validate to true.
188
	rbloom := types.CreateBloom(receipts)
obscuren's avatar
obscuren committed
189
	if rbloom != header.Bloom {
190 191 192 193
		err = fmt.Errorf("unable to replicate block's bloom=%x", rbloom)
		return
	}

194 195
	// The transactions Trie's root (R = (Tr [[H1, T1], [H2, T2], ... [Hn, Tn]]))
	// can be used by light clients to make sure they've received the correct Txs
196
	txSha := types.DeriveSha(block.Transactions())
obscuren's avatar
obscuren committed
197
	if txSha != header.TxHash {
198
		err = fmt.Errorf("validating transaction root. received=%x got=%x", header.TxHash, txSha)
obscuren's avatar
obscuren committed
199 200
		return
	}
obscuren's avatar
obscuren committed
201

202
	// Tre receipt Trie's root (R = (Tr [[H1, R1], ... [Hn, R1]]))
203
	receiptSha := types.DeriveSha(receipts)
obscuren's avatar
obscuren committed
204
	if receiptSha != header.ReceiptHash {
205
		err = fmt.Errorf("validating receipt root. received=%x got=%x", header.ReceiptHash, receiptSha)
206 207
		return
	}
obscuren's avatar
obscuren committed
208

209
	// Accumulate static rewards; block reward, uncle's and uncle inclusion.
210
	if err = sm.AccumulateRewards(state, block, parent); err != nil {
211
		return
obscuren's avatar
obscuren committed
212 213
	}

214 215
	// Commit state objects/accounts to a temporary trie (does not save)
	// used to calculate the state root.
obscuren's avatar
obscuren committed
216
	state.Update(common.Big0)
obscuren's avatar
obscuren committed
217
	if header.Root != state.Root() {
218
		err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root())
219
		return
obscuren's avatar
obscuren committed
220 221
	}

222 223
	// Calculate the td for this block
	td = CalculateTD(block, parent)
obscuren's avatar
obscuren committed
224
	// Sync the current block's state to the database
225 226 227
	state.Sync()
	// Remove transactions from the pool
	sm.txpool.RemoveSet(block.Transactions())
obscuren's avatar
obscuren committed
228

229 230 231 232
	for _, tx := range block.Transactions() {
		putTx(sm.extraDb, tx)
	}

obscuren's avatar
obscuren committed
233
	chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash().Bytes()[0:4])
234

235
	return td, state.Logs(), nil
obscuren's avatar
obscuren committed
236 237 238 239 240
}

// 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
241 242 243
func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
	if len(block.Extra) > 1024 {
		return fmt.Errorf("Block extra data too long (%d)", len(block.Extra))
obscuren's avatar
obscuren committed
244 245
	}

246
	expd := CalcDifficulty(block, parent)
obscuren's avatar
obscuren committed
247 248
	if expd.Cmp(block.Difficulty) != 0 {
		return fmt.Errorf("Difficulty check failed for block %v, %v", block.Difficulty, expd)
249 250
	}

obscuren's avatar
obscuren committed
251
	// block.gasLimit - parent.gasLimit <= parent.gasLimit / 1024
obscuren's avatar
obscuren committed
252 253
	a := new(big.Int).Sub(block.GasLimit, parent.GasLimit)
	b := new(big.Int).Div(parent.GasLimit, big.NewInt(1024))
obscuren's avatar
obscuren committed
254
	if a.Cmp(b) > 0 {
obscuren's avatar
obscuren committed
255
		return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
Matthew Wampler-Doty's avatar
Matthew Wampler-Doty committed
256 257
	}

258
	if block.Time <= parent.Time {
259
		return ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
obscuren's avatar
obscuren committed
260 261
	}

obscuren's avatar
obscuren committed
262
	if int64(block.Time) > time.Now().Unix() {
263 264 265
		return BlockFutureErr
	}

obscuren's avatar
obscuren committed
266
	if new(big.Int).Sub(block.Number, parent.Number).Cmp(big.NewInt(1)) != 0 {
267
		return BlockNumberErr
obscuren's avatar
obscuren committed
268 269 270
	}

	// Verify the nonce of the block. Return an error if it's not valid
obscuren's avatar
obscuren committed
271 272
	if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
		return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
obscuren's avatar
obscuren committed
273 274 275 276 277
	}

	return nil
}

278
func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
279
	reward := new(big.Int).Set(BlockReward)
obscuren's avatar
obscuren committed
280

281
	ancestors := set.New()
obscuren's avatar
obscuren committed
282
	uncles := set.New()
obscuren's avatar
obscuren committed
283
	ancestorHeaders := make(map[common.Hash]*types.Header)
obscuren's avatar
obscuren committed
284
	for _, ancestor := range sm.bc.GetAncestors(block, 7) {
obscuren's avatar
obscuren committed
285 286
		ancestorHeaders[ancestor.Hash()] = ancestor.Header()
		ancestors.Add(ancestor.Hash())
obscuren's avatar
obscuren committed
287 288
		// Include ancestors uncles in the uncle set. Uncles must be unique.
		for _, uncle := range ancestor.Uncles() {
obscuren's avatar
obscuren committed
289
			uncles.Add(uncle.Hash())
obscuren's avatar
obscuren committed
290
		}
291 292
	}

obscuren's avatar
obscuren committed
293
	uncles.Add(block.Hash())
294
	for _, uncle := range block.Uncles() {
obscuren's avatar
obscuren committed
295
		if uncles.Has(uncle.Hash()) {
obscuren's avatar
obscuren committed
296 297 298
			// Error not unique
			return UncleError("Uncle not unique")
		}
obscuren's avatar
obscuren committed
299

obscuren's avatar
obscuren committed
300
		uncles.Add(uncle.Hash())
obscuren's avatar
obscuren committed
301

obscuren's avatar
obscuren committed
302
		if ancestors.Has(uncle.Hash()) {
obscuren's avatar
obscuren committed
303 304 305
			return UncleError("Uncle is ancestor")
		}

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

obscuren's avatar
obscuren committed
310
		if err := sm.ValidateHeader(uncle, ancestorHeaders[uncle.ParentHash]); err != nil {
obscuren's avatar
obscuren committed
311 312 313
			return ValidationError(fmt.Sprintf("%v", err))
		}

obscuren's avatar
obscuren committed
314
		if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
obscuren's avatar
obscuren committed
315
			return ValidationError("Uncle's nonce is invalid (= %x)", uncle.Nonce)
obscuren's avatar
obscuren committed
316 317
		}

obscuren's avatar
obscuren committed
318 319
		r := new(big.Int)
		r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
obscuren's avatar
obscuren committed
320

321
		statedb.AddBalance(uncle.Coinbase, r)
obscuren's avatar
obscuren committed
322

obscuren's avatar
obscuren committed
323
		reward.Add(reward, new(big.Int).Div(BlockReward, big.NewInt(32)))
obscuren's avatar
obscuren committed
324
	}
obscuren's avatar
obscuren committed
325

obscuren's avatar
obscuren committed
326
	// Get the account associated with the coinbase
327
	statedb.AddBalance(block.Header().Coinbase, reward)
obscuren's avatar
obscuren committed
328

obscuren's avatar
obscuren committed
329 330 331
	return nil
}

obscuren's avatar
obscuren committed
332 333 334 335 336 337 338 339 340
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)
341
		state  = state.New(parent.Root(), sm.db)
obscuren's avatar
obscuren committed
342 343
	)

344
	sm.TransitionState(state, parent, block, true)
345
	sm.AccumulateRewards(state, block, parent)
obscuren's avatar
obscuren committed
346 347 348

	return state.Logs(), nil
}
349

obscuren's avatar
obscuren committed
350
func putTx(db common.Database, tx *types.Transaction) {
351 352 353 354 355
	rlpEnc, err := rlp.EncodeToBytes(tx)
	if err != nil {
		statelogger.Infoln("Failed encoding tx", err)
		return
	}
obscuren's avatar
obscuren committed
356
	db.Put(tx.Hash().Bytes(), rlpEnc)
357
}