worker.go 17.9 KB
Newer Older
F
Felix Lange 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright 2015 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with go-ethereum.  If not, see <http://www.gnu.org/licenses/>.

O
obscuren 已提交
17 18 19 20 21 22
package miner

import (
	"fmt"
	"math/big"
	"sort"
O
obscuren 已提交
23
	"sync"
O
obscuren 已提交
24
	"sync/atomic"
25
	"time"
O
obscuren 已提交
26

27
	"github.com/ethereum/go-ethereum/accounts"
O
obscuren 已提交
28
	"github.com/ethereum/go-ethereum/common"
O
obscuren 已提交
29
	"github.com/ethereum/go-ethereum/core"
O
obscuren 已提交
30
	"github.com/ethereum/go-ethereum/core/state"
O
obscuren 已提交
31 32
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/event"
33
	"github.com/ethereum/go-ethereum/logger"
O
obscuren 已提交
34
	"github.com/ethereum/go-ethereum/logger/glog"
O
obscuren 已提交
35 36 37 38
	"github.com/ethereum/go-ethereum/pow"
	"gopkg.in/fatih/set.v0"
)

39 40
var jsonlogger = logger.NewJsonLogger()

J
Jeffrey Wilcke 已提交
41 42 43 44
const (
	resultQueueSize  = 10
	miningLogAtDepth = 5
)
45 46 47

// Agent can register themself with the worker
type Agent interface {
J
Jeffrey Wilcke 已提交
48 49
	Work() chan<- *Work
	SetReturnCh(chan<- *Result)
50 51 52 53 54
	Stop()
	Start()
	GetHashRate() int64
}

J
Jason Carver 已提交
55
type uint64RingBuffer struct {
56 57 58 59
	ints []uint64 //array of all integers in buffer
	next int      //where is the next insertion? assert 0 <= next < len(ints)
}

60 61
// environment is the workers current environment and holds
// all of the current state information
J
Jeffrey Wilcke 已提交
62
type Work struct {
63 64
	state              *state.StateDB     // apply state changes here
	coinbase           *state.StateObject // the miner's account
65 66
	ancestors          *set.Set           // ancestor set (used for checking uncle parent validity)
	family             *set.Set           // family set (used for checking uncle invalidity)
67 68 69
	uncles             *set.Set           // uncle set
	remove             *set.Set           // tx which will be removed
	tcount             int                // tx count in cycle
70 71 72 73
	ignoredTransactors *set.Set
	lowGasTransactors  *set.Set
	ownedAccounts      *set.Set
	lowGasTxs          types.Transactions
J
Jason Carver 已提交
74
	localMinedBlocks   *uint64RingBuffer // the most recent block numbers that were mined locally (used to check block inclusion)
O
obscuren 已提交
75

J
Jeffrey Wilcke 已提交
76
	Block *types.Block // the new block
O
obscuren 已提交
77

F
Felix Lange 已提交
78 79 80
	header   *types.Header
	txs      []*types.Transaction
	receipts []*types.Receipt
J
Jeffrey Wilcke 已提交
81 82 83 84 85 86 87

	createdAt time.Time
}

type Result struct {
	Work  *Work
	Block *types.Block
O
obscuren 已提交
88 89
}

90
// worker is the main object which takes care of applying messages to the new state
O
obscuren 已提交
91
type worker struct {
O
obscuren 已提交
92 93
	mu sync.Mutex

O
obscuren 已提交
94
	agents []Agent
J
Jeffrey Wilcke 已提交
95
	recv   chan *Result
O
obscuren 已提交
96 97 98 99
	mux    *event.TypeMux
	quit   chan struct{}
	pow    pow.PoW

100 101 102 103
	eth     core.Backend
	chain   *core.ChainManager
	proc    *core.BlockProcessor
	extraDb common.Database
104

O
obscuren 已提交
105
	coinbase common.Address
106
	gasPrice *big.Int
107
	extra    []byte
O
obscuren 已提交
108

O
obscuren 已提交
109
	currentMu sync.Mutex
J
Jeffrey Wilcke 已提交
110
	current   *Work
111

O
obscuren 已提交
112 113 114
	uncleMu        sync.Mutex
	possibleUncles map[common.Hash]*types.Block

O
obscuren 已提交
115 116 117
	txQueueMu sync.Mutex
	txQueue   map[common.Hash]*types.Transaction

F
Felix Lange 已提交
118 119 120
	// atomic status counters
	mining int32
	atWork int32
J
Jeffrey Wilcke 已提交
121 122

	fullValidation bool
O
obscuren 已提交
123 124
}

O
obscuren 已提交
125
func newWorker(coinbase common.Address, eth core.Backend) *worker {
O
obscuren 已提交
126
	worker := &worker{
O
obscuren 已提交
127 128
		eth:            eth,
		mux:            eth.EventMux(),
129
		extraDb:        eth.ExtraDb(),
J
Jeffrey Wilcke 已提交
130
		recv:           make(chan *Result, resultQueueSize),
131
		gasPrice:       new(big.Int),
O
obscuren 已提交
132 133 134 135
		chain:          eth.ChainManager(),
		proc:           eth.BlockProcessor(),
		possibleUncles: make(map[common.Hash]*types.Block),
		coinbase:       coinbase,
O
obscuren 已提交
136
		txQueue:        make(map[common.Hash]*types.Transaction),
O
obscuren 已提交
137
		quit:           make(chan struct{}),
J
Jeffrey Wilcke 已提交
138
		fullValidation: false,
O
obscuren 已提交
139
	}
O
obscuren 已提交
140 141 142 143 144 145
	go worker.update()
	go worker.wait()

	worker.commitNewWork()

	return worker
O
obscuren 已提交
146 147
}

J
Jeffrey Wilcke 已提交
148 149 150 151 152 153
func (self *worker) setEtherbase(addr common.Address) {
	self.mu.Lock()
	defer self.mu.Unlock()
	self.coinbase = addr
}

O
obscuren 已提交
154 155 156 157 158
func (self *worker) pendingState() *state.StateDB {
	self.currentMu.Lock()
	defer self.currentMu.Unlock()
	return self.current.state
}
159

O
obscuren 已提交
160 161 162
func (self *worker) pendingBlock() *types.Block {
	self.currentMu.Lock()
	defer self.currentMu.Unlock()
163

F
Felix Lange 已提交
164 165 166 167 168 169 170 171
	if atomic.LoadInt32(&self.mining) == 0 {
		return types.NewBlock(
			self.current.header,
			self.current.txs,
			nil,
			self.current.receipts,
		)
	}
J
Jeffrey Wilcke 已提交
172
	return self.current.Block
O
obscuren 已提交
173 174 175
}

func (self *worker) start() {
176 177 178
	self.mu.Lock()
	defer self.mu.Unlock()

179 180
	atomic.StoreInt32(&self.mining, 1)

O
obscuren 已提交
181 182 183 184
	// spin up agents
	for _, agent := range self.agents {
		agent.Start()
	}
O
obscuren 已提交
185 186 187
}

func (self *worker) stop() {
188 189 190
	self.mu.Lock()
	defer self.mu.Unlock()

F
Felix Lange 已提交
191
	if atomic.LoadInt32(&self.mining) == 1 {
192
		var keep []Agent
O
obscuren 已提交
193 194 195
		// stop all agents
		for _, agent := range self.agents {
			agent.Stop()
196 197 198 199
			// keep all that's not a cpu agent
			if _, ok := agent.(*CpuAgent); !ok {
				keep = append(keep, agent)
			}
O
obscuren 已提交
200
		}
201
		self.agents = keep
O
obscuren 已提交
202
	}
203

F
Felix Lange 已提交
204 205
	atomic.StoreInt32(&self.mining, 0)
	atomic.StoreInt32(&self.atWork, 0)
O
obscuren 已提交
206 207 208
}

func (self *worker) register(agent Agent) {
209 210
	self.mu.Lock()
	defer self.mu.Unlock()
O
obscuren 已提交
211
	self.agents = append(self.agents, agent)
O
obscuren 已提交
212
	agent.SetReturnCh(self.recv)
O
obscuren 已提交
213 214 215
}

func (self *worker) update() {
O
obscuren 已提交
216
	events := self.mux.Subscribe(core.ChainHeadEvent{}, core.ChainSideEvent{}, core.TxPreEvent{})
O
obscuren 已提交
217 218 219 220 221

out:
	for {
		select {
		case event := <-events.Chan():
222
			switch ev := event.(type) {
223
			case core.ChainHeadEvent:
O
obscuren 已提交
224
				self.commitNewWork()
O
obscuren 已提交
225
			case core.ChainSideEvent:
O
obscuren 已提交
226 227 228
				self.uncleMu.Lock()
				self.possibleUncles[ev.Block.Hash()] = ev.Block
				self.uncleMu.Unlock()
O
obscuren 已提交
229
			case core.TxPreEvent:
230
				// Apply transaction to the pending state if we're not mining
F
Felix Lange 已提交
231
				if atomic.LoadInt32(&self.mining) == 0 {
232
					self.currentMu.Lock()
F
Felix Lange 已提交
233
					self.current.commitTransactions(types.Transactions{ev.Tx}, self.gasPrice, self.proc)
234
					self.currentMu.Unlock()
O
obscuren 已提交
235
				}
O
obscuren 已提交
236 237 238 239 240
			}
		case <-self.quit:
			break out
		}
	}
241 242

	events.Unsubscribe()
O
obscuren 已提交
243 244
}

J
Jason Carver 已提交
245
func newLocalMinedBlock(blockNumber uint64, prevMinedBlocks *uint64RingBuffer) (minedBlocks *uint64RingBuffer) {
246
	if prevMinedBlocks == nil {
247
		minedBlocks = &uint64RingBuffer{next: 0, ints: make([]uint64, miningLogAtDepth+1)}
248 249 250 251 252 253 254 255 256
	} else {
		minedBlocks = prevMinedBlocks
	}

	minedBlocks.ints[minedBlocks.next] = blockNumber
	minedBlocks.next = (minedBlocks.next + 1) % len(minedBlocks.ints)
	return minedBlocks
}

O
obscuren 已提交
257 258
func (self *worker) wait() {
	for {
J
Jeffrey Wilcke 已提交
259
		for result := range self.recv {
F
Felix Lange 已提交
260
			atomic.AddInt32(&self.atWork, -1)
O
obscuren 已提交
261

J
Jeffrey Wilcke 已提交
262
			if result == nil {
O
obscuren 已提交
263 264
				continue
			}
J
Jeffrey Wilcke 已提交
265
			block := result.Block
O
obscuren 已提交
266

J
Jeffrey Wilcke 已提交
267
			self.current.state.Sync()
J
Jeffrey Wilcke 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
			if self.fullValidation {
				if _, err := self.chain.InsertChain(types.Blocks{block}); err != nil {
					glog.V(logger.Error).Infoln("mining err", err)
					continue
				}
				go self.mux.Post(core.NewMinedBlockEvent{block})
			} else {
				parent := self.chain.GetBlock(block.ParentHash())
				if parent == nil {
					glog.V(logger.Error).Infoln("Invalid block found during mining")
					continue
				}
				if err := core.ValidateHeader(self.eth.BlockProcessor().Pow, block.Header(), parent, true); err != nil && err != core.BlockFutureErr {
					glog.V(logger.Error).Infoln("Invalid header on mined block:", err)
					continue
				}
284

J
Jeffrey Wilcke 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
				stat, err := self.chain.WriteBlock(block, false)
				if err != nil {
					glog.V(logger.Error).Infoln("error writing block to chain", err)
					continue
				}
				// check if canon block and write transactions
				if stat == core.CanonStatTy {
					// This puts transactions in a extra db for rpc
					core.PutTransactions(self.extraDb, block, block.Transactions())
					// store the receipts
					core.PutReceipts(self.extraDb, self.current.receipts)
				}

				// broadcast before waiting for validation
				go func(block *types.Block, logs state.Logs) {
					self.mux.Post(core.NewMinedBlockEvent{block})
					self.mux.Post(core.ChainEvent{block, block.Hash(), logs})
					if stat == core.CanonStatTy {
						self.mux.Post(core.ChainHeadEvent{block})
						self.mux.Post(logs)
					}
				}(block, self.current.state.Logs())
307
			}
O
obscuren 已提交
308

309 310 311 312 313
			// check staleness and display confirmation
			var stale, confirm string
			canonBlock := self.chain.GetBlockByNumber(block.NumberU64())
			if canonBlock != nil && canonBlock.Hash() != block.Hash() {
				stale = "stale "
O
obscuren 已提交
314
			} else {
315 316
				confirm = "Wait 5 blocks for confirmation"
				self.current.localMinedBlocks = newLocalMinedBlock(block.Number().Uint64(), self.current.localMinedBlocks)
317
			}
318 319 320
			glog.V(logger.Info).Infof("🔨  Mined %sblock (#%v / %x). %s", stale, block.Number(), block.Hash().Bytes()[:4], confirm)

			self.commitNewWork()
O
obscuren 已提交
321 322 323 324 325
		}
	}
}

func (self *worker) push() {
F
Felix Lange 已提交
326
	if atomic.LoadInt32(&self.mining) == 1 {
J
Jeffrey Wilcke 已提交
327 328 329 330 331 332
		if core.Canary(self.current.state) {
			glog.Infoln("Toxicity levels rising to deadly levels. Your canary has died. You can go back or continue down the mineshaft --more--")
			glog.Infoln("You turn back and abort mining")
			return
		}

O
obscuren 已提交
333
		// push new work to agents
334
		for _, agent := range self.agents {
F
Felix Lange 已提交
335
			atomic.AddInt32(&self.atWork, 1)
O
obscuren 已提交
336

337
			if agent.Work() != nil {
J
Jeffrey Wilcke 已提交
338
				agent.Work() <- self.current
339
			}
340
		}
O
obscuren 已提交
341 342 343
	}
}

F
Felix Lange 已提交
344 345 346
// makeCurrent creates a new environment for the current cycle.
func (self *worker) makeCurrent(parent *types.Block, header *types.Header) {
	state := state.New(parent.Root(), self.eth.StateDb())
J
Jeffrey Wilcke 已提交
347
	current := &Work{
F
Felix Lange 已提交
348 349 350 351 352 353
		state:     state,
		ancestors: set.New(),
		family:    set.New(),
		uncles:    set.New(),
		header:    header,
		coinbase:  state.GetOrNewStateObject(self.coinbase),
J
Jeffrey Wilcke 已提交
354
		createdAt: time.Now(),
355
	}
356

Z
zelig 已提交
357
	// when 08 is processed ancestors contain 07 (quick block)
F
Felix Lange 已提交
358
	for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
359 360 361
		for _, uncle := range ancestor.Uncles() {
			current.family.Add(uncle.Hash())
		}
362
		current.family.Add(ancestor.Hash())
V
Vitalik Buterin 已提交
363
		current.ancestors.Add(ancestor.Hash())
O
obscuren 已提交
364
	}
365
	accounts, _ := self.eth.AccountManager().Accounts()
F
Felix Lange 已提交
366

367 368 369 370 371 372
	// Keep track of transactions which return errors so they can be removed
	current.remove = set.New()
	current.tcount = 0
	current.ignoredTransactors = set.New()
	current.lowGasTransactors = set.New()
	current.ownedAccounts = accountAddressesSet(accounts)
373 374 375
	if self.current != nil {
		current.localMinedBlocks = self.current.localMinedBlocks
	}
376
	self.current = current
O
obscuren 已提交
377 378
}

379 380 381
func (w *worker) setGasPrice(p *big.Int) {
	w.mu.Lock()
	defer w.mu.Unlock()
382 383 384 385 386 387

	// calculate the minimal gas price the miner accepts when sorting out transactions.
	const pct = int64(90)
	w.gasPrice = gasprice(p, pct)

	w.mux.Post(core.GasPriceChanged{w.gasPrice})
388 389
}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
func (self *worker) isBlockLocallyMined(deepBlockNum uint64) bool {
	//Did this instance mine a block at {deepBlockNum} ?
	var isLocal = false
	for idx, blockNum := range self.current.localMinedBlocks.ints {
		if deepBlockNum == blockNum {
			isLocal = true
			self.current.localMinedBlocks.ints[idx] = 0 //prevent showing duplicate logs
			break
		}
	}
	//Short-circuit on false, because the previous and following tests must both be true
	if !isLocal {
		return false
	}

	//Does the block at {deepBlockNum} send earnings to my coinbase?
	var block = self.chain.GetBlockByNumber(deepBlockNum)
F
Felix Lange 已提交
407
	return block != nil && block.Coinbase() == self.coinbase
408 409
}

J
Jeffrey Wilcke 已提交
410
func (self *worker) logLocalMinedBlocks(previous *Work) {
411
	if previous != nil && self.current.localMinedBlocks != nil {
J
Jeffrey Wilcke 已提交
412 413
		nextBlockNum := self.current.Block.NumberU64()
		for checkBlockNum := previous.Block.NumberU64(); checkBlockNum < nextBlockNum; checkBlockNum++ {
414
			inspectBlockNum := checkBlockNum - miningLogAtDepth
415
			if self.isBlockLocallyMined(inspectBlockNum) {
416
				glog.V(logger.Info).Infof("🔨 🔗  Mined %d blocks back: block #%v", miningLogAtDepth, inspectBlockNum)
417 418 419 420 421
			}
		}
	}
}

O
obscuren 已提交
422 423 424 425 426 427 428 429
func (self *worker) commitNewWork() {
	self.mu.Lock()
	defer self.mu.Unlock()
	self.uncleMu.Lock()
	defer self.uncleMu.Unlock()
	self.currentMu.Lock()
	defer self.currentMu.Unlock()

430
	tstart := time.Now()
F
Felix Lange 已提交
431 432
	parent := self.chain.CurrentBlock()
	tstamp := tstart.Unix()
433 434
	if tstamp <= int64(parent.Time()) {
		tstamp = int64(parent.Time()) + 1
F
Felix Lange 已提交
435
	}
436 437 438 439 440 441 442
	// this will ensure we're not going off too far in the future
	if now := time.Now().Unix(); tstamp > now+4 {
		wait := time.Duration(tstamp-now) * time.Second
		glog.V(logger.Info).Infoln("We are too far in the future. Waiting for", wait)
		time.Sleep(wait)
	}

F
Felix Lange 已提交
443 444 445 446
	num := parent.Number()
	header := &types.Header{
		ParentHash: parent.Hash(),
		Number:     num.Add(num, common.Big1),
447
		Difficulty: core.CalcDifficulty(uint64(tstamp), parent.Time(), parent.Difficulty()),
F
Felix Lange 已提交
448 449 450 451 452 453
		GasLimit:   core.CalcGasLimit(parent),
		GasUsed:    new(big.Int),
		Coinbase:   self.coinbase,
		Extra:      self.extra,
		Time:       uint64(tstamp),
	}
454

455
	previous := self.current
F
Felix Lange 已提交
456
	self.makeCurrent(parent, header)
457
	current := self.current
O
obscuren 已提交
458

F
Felix Lange 已提交
459
	// commit transactions for this run.
O
obscuren 已提交
460 461
	transactions := self.eth.TxPool().GetTransactions()
	sort.Sort(types.TxByNonce{transactions})
F
Felix Lange 已提交
462 463
	current.coinbase.SetGasLimit(header.GasLimit)
	current.commitTransactions(transactions, self.gasPrice, self.proc)
464
	self.eth.TxPool().RemoveTransactions(current.lowGasTxs)
O
obscuren 已提交
465

F
Felix Lange 已提交
466
	// compute uncles for the new block.
O
obscuren 已提交
467 468 469 470
	var (
		uncles    []*types.Header
		badUncles []common.Hash
	)
O
obscuren 已提交
471
	for hash, uncle := range self.possibleUncles {
O
obscuren 已提交
472
		if len(uncles) == 2 {
O
obscuren 已提交
473 474 475
			break
		}
		if err := self.commitUncle(uncle.Header()); err != nil {
476 477 478 479
			if glog.V(logger.Ridiculousness) {
				glog.V(logger.Detail).Infof("Bad uncle found and will be removed (%x)\n", hash[:4])
				glog.V(logger.Detail).Infoln(uncle)
			}
O
obscuren 已提交
480
			badUncles = append(badUncles, hash)
O
obscuren 已提交
481
		} else {
O
obscuren 已提交
482
			glog.V(logger.Debug).Infof("commiting %x as uncle\n", hash[:4])
O
obscuren 已提交
483
			uncles = append(uncles, uncle.Header())
O
obscuren 已提交
484 485
		}
	}
O
obscuren 已提交
486 487 488
	for _, hash := range badUncles {
		delete(self.possibleUncles, hash)
	}
489

490 491 492
	if atomic.LoadInt32(&self.mining) == 1 {
		// commit state root after all state transitions.
		core.AccumulateRewards(self.current.state, header, uncles)
493
		current.state.SyncObjects()
494 495
		header.Root = current.state.Root()
	}
O
obscuren 已提交
496

F
Felix Lange 已提交
497
	// create the new block whose nonce will be mined.
J
Jeffrey Wilcke 已提交
498 499
	current.Block = types.NewBlock(header, current.txs, uncles, current.receipts)
	self.current.Block.Td = new(big.Int).Set(core.CalcTD(self.current.Block, self.chain.GetBlock(self.current.Block.ParentHash())))
O
obscuren 已提交
500

F
Felix Lange 已提交
501 502
	// We only care about logging if we're actually mining.
	if atomic.LoadInt32(&self.mining) == 1 {
J
Jeffrey Wilcke 已提交
503
		glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles. Took %v\n", current.Block.Number(), current.tcount, len(uncles), time.Since(tstart))
F
Felix Lange 已提交
504 505
		self.logLocalMinedBlocks(previous)
	}
O
obscuren 已提交
506

O
obscuren 已提交
507
	self.push()
O
obscuren 已提交
508 509 510
}

func (self *worker) commitUncle(uncle *types.Header) error {
F
Felix Lange 已提交
511 512
	hash := uncle.Hash()
	if self.current.uncles.Has(hash) {
O
obscuren 已提交
513 514
		return core.UncleError("Uncle not unique")
	}
515
	if !self.current.ancestors.Has(uncle.ParentHash) {
O
obscuren 已提交
516 517
		return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
	}
F
Felix Lange 已提交
518 519
	if self.current.family.Has(hash) {
		return core.UncleError(fmt.Sprintf("Uncle already in family (%x)", hash))
O
obscuren 已提交
520
	}
521
	self.current.uncles.Add(uncle.Hash())
O
obscuren 已提交
522 523 524
	return nil
}

J
Jeffrey Wilcke 已提交
525
func (env *Work) commitTransactions(transactions types.Transactions, gasPrice *big.Int, proc *core.BlockProcessor) {
526 527 528 529
	for _, tx := range transactions {
		// We can skip err. It has already been validated in the tx pool
		from, _ := tx.From()

530
		// Check if it falls within margin. Txs from owned accounts are always processed.
F
Felix Lange 已提交
531
		if tx.GasPrice().Cmp(gasPrice) < 0 && !env.ownedAccounts.Has(from) {
532 533 534
			// ignore the transaction and transactor. We ignore the transactor
			// because nonce will fail after ignoring this transaction so there's
			// no point
F
Felix Lange 已提交
535
			env.lowGasTransactors.Add(from)
536

F
Felix Lange 已提交
537
			glog.V(logger.Info).Infof("transaction(%x) below gas price (tx=%v ask=%v). All sequential txs from this address(%x) will be ignored\n", tx.Hash().Bytes()[:4], common.CurrencyToString(tx.GasPrice()), common.CurrencyToString(gasPrice), from[:4])
538 539 540 541 542
		}

		// Continue with the next transaction if the transaction sender is included in
		// the low gas tx set. This will also remove the tx and all sequential transaction
		// from this transactor
F
Felix Lange 已提交
543
		if env.lowGasTransactors.Has(from) {
544 545
			// add tx to the low gas set. This will be removed at the end of the run
			// owned accounts are ignored
F
Felix Lange 已提交
546 547
			if !env.ownedAccounts.Has(from) {
				env.lowGasTxs = append(env.lowGasTxs, tx)
548 549 550 551 552 553 554 555 556
			}
			continue
		}

		// Move on to the next transaction when the transactor is in ignored transactions set
		// This may occur when a transaction hits the gas limit. When a gas limit is hit and
		// the transaction is processed (that could potentially be included in the block) it
		// will throw a nonce error because the previous transaction hasn't been processed.
		// Therefor we need to ignore any transaction after the ignored one.
F
Felix Lange 已提交
557
		if env.ignoredTransactors.Has(from) {
558 559 560
			continue
		}

F
Felix Lange 已提交
561
		env.state.StartRecord(tx.Hash(), common.Hash{}, 0)
562

F
Felix Lange 已提交
563
		err := env.commitTransaction(tx, proc)
564 565 566 567
		switch {
		case state.IsGasLimitErr(err):
			// ignore the transactor so no nonce errors will be thrown for this account
			// next time the worker is run, they'll be picked up again.
F
Felix Lange 已提交
568
			env.ignoredTransactors.Add(from)
569 570

			glog.V(logger.Detail).Infof("Gas limit reached for (%x) in this block. Continue to try smaller txs\n", from[:4])
571 572 573 574 575 576
		case err != nil:
			env.remove.Add(tx.Hash())

			if glog.V(logger.Detail) {
				glog.Infof("TX (%x) failed, will be removed: %v\n", tx.Hash().Bytes()[:4], err)
			}
577
		default:
F
Felix Lange 已提交
578
			env.tcount++
579 580 581 582
		}
	}
}

J
Jeffrey Wilcke 已提交
583
func (env *Work) commitTransaction(tx *types.Transaction, proc *core.BlockProcessor) error {
F
Felix Lange 已提交
584 585
	snap := env.state.Copy()
	receipt, _, err := proc.ApplyTransaction(env.coinbase, env.state, env.header, tx, env.header.GasUsed, true)
586
	if err != nil {
F
Felix Lange 已提交
587
		env.state.Set(snap)
O
obscuren 已提交
588 589
		return err
	}
F
Felix Lange 已提交
590 591
	env.txs = append(env.txs, tx)
	env.receipts = append(env.receipts, receipt)
O
obscuren 已提交
592 593
	return nil
}
O
obscuren 已提交
594

595
// TODO: remove or use
O
obscuren 已提交
596
func (self *worker) HashRate() int64 {
597
	return 0
O
obscuren 已提交
598
}
O
obscuren 已提交
599 600 601 602 603 604 605 606 607

// gasprice calculates a reduced gas price based on the pct
// XXX Use big.Rat?
func gasprice(price *big.Int, pct int64) *big.Int {
	p := new(big.Int).Set(price)
	p.Div(p, big.NewInt(100))
	p.Mul(p, big.NewInt(pct))
	return p
}
608 609 610 611

func accountAddressesSet(accounts []accounts.Account) *set.Set {
	accountSet := set.New()
	for _, account := range accounts {
612
		accountSet.Add(account.Address)
613 614 615
	}
	return accountSet
}