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

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

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

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

40 41
var jsonlogger = logger.NewJsonLogger()

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

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

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

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

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

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

	createdAt time.Time
}

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

91
// worker is the main object which takes care of applying messages to the new state
O
obscuren 已提交
92
type worker struct {
93 94
	config *core.ChainConfig

O
obscuren 已提交
95 96
	mu sync.Mutex

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

103
	eth     core.Backend
104
	chain   *core.BlockChain
105
	proc    core.Validator
106
	chainDb ethdb.Database
107

O
obscuren 已提交
108
	coinbase common.Address
109
	gasPrice *big.Int
110
	extra    []byte
O
obscuren 已提交
111

O
obscuren 已提交
112
	currentMu sync.Mutex
J
Jeffrey Wilcke 已提交
113
	current   *Work
114

O
obscuren 已提交
115 116 117
	uncleMu        sync.Mutex
	possibleUncles map[common.Hash]*types.Block

O
obscuren 已提交
118 119 120
	txQueueMu sync.Mutex
	txQueue   map[common.Hash]*types.Transaction

F
Felix Lange 已提交
121 122 123
	// atomic status counters
	mining int32
	atWork int32
J
Jeffrey Wilcke 已提交
124 125

	fullValidation bool
O
obscuren 已提交
126 127
}

128
func newWorker(config *core.ChainConfig, coinbase common.Address, eth core.Backend) *worker {
O
obscuren 已提交
129
	worker := &worker{
130
		config:         config,
O
obscuren 已提交
131 132
		eth:            eth,
		mux:            eth.EventMux(),
133
		chainDb:        eth.ChainDb(),
J
Jeffrey Wilcke 已提交
134
		recv:           make(chan *Result, resultQueueSize),
135
		gasPrice:       new(big.Int),
136
		chain:          eth.BlockChain(),
137
		proc:           eth.BlockChain().Validator(),
O
obscuren 已提交
138 139
		possibleUncles: make(map[common.Hash]*types.Block),
		coinbase:       coinbase,
O
obscuren 已提交
140
		txQueue:        make(map[common.Hash]*types.Transaction),
O
obscuren 已提交
141
		quit:           make(chan struct{}),
142
		agents:         make(map[Agent]struct{}),
J
Jeffrey Wilcke 已提交
143
		fullValidation: false,
O
obscuren 已提交
144
	}
O
obscuren 已提交
145 146 147 148 149 150
	go worker.update()
	go worker.wait()

	worker.commitNewWork()

	return worker
O
obscuren 已提交
151 152
}

J
Jeffrey Wilcke 已提交
153 154 155 156 157 158
func (self *worker) setEtherbase(addr common.Address) {
	self.mu.Lock()
	defer self.mu.Unlock()
	self.coinbase = addr
}

159
func (self *worker) pending() (*types.Block, *state.StateDB) {
O
obscuren 已提交
160 161
	self.currentMu.Lock()
	defer self.currentMu.Unlock()
162

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

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

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

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

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

F
Felix Lange 已提交
190
	if atomic.LoadInt32(&self.mining) == 1 {
191 192
		// Stop all agents.
		for agent := range self.agents {
O
obscuren 已提交
193
			agent.Stop()
194 195 196
			// Remove CPU agents.
			if _, ok := agent.(*CpuAgent); ok {
				delete(self.agents, agent)
197
			}
O
obscuren 已提交
198 199
		}
	}
200

F
Felix Lange 已提交
201 202
	atomic.StoreInt32(&self.mining, 0)
	atomic.StoreInt32(&self.atWork, 0)
O
obscuren 已提交
203 204 205
}

func (self *worker) register(agent Agent) {
206 207
	self.mu.Lock()
	defer self.mu.Unlock()
208
	self.agents[agent] = struct{}{}
O
obscuren 已提交
209
	agent.SetReturnCh(self.recv)
O
obscuren 已提交
210 211
}

212 213 214 215 216 217 218
func (self *worker) unregister(agent Agent) {
	self.mu.Lock()
	defer self.mu.Unlock()
	delete(self.agents, agent)
	agent.Stop()
}

O
obscuren 已提交
219
func (self *worker) update() {
220 221
	eventSub := self.mux.Subscribe(core.ChainHeadEvent{}, core.ChainSideEvent{}, core.TxPreEvent{})
	defer eventSub.Unsubscribe()
O
obscuren 已提交
222

223
	eventCh := eventSub.Chan()
O
obscuren 已提交
224 225
	for {
		select {
226 227 228 229 230 231 232 233
		case event, ok := <-eventCh:
			if !ok {
				// Event subscription closed, set the channel to nil to stop spinning
				eventCh = nil
				continue
			}
			// A real event arrived, process interesting content
			switch ev := event.Data.(type) {
234
			case core.ChainHeadEvent:
O
obscuren 已提交
235
				self.commitNewWork()
O
obscuren 已提交
236
			case core.ChainSideEvent:
O
obscuren 已提交
237 238 239
				self.uncleMu.Lock()
				self.possibleUncles[ev.Block.Hash()] = ev.Block
				self.uncleMu.Unlock()
O
obscuren 已提交
240
			case core.TxPreEvent:
241
				// Apply transaction to the pending state if we're not mining
F
Felix Lange 已提交
242
				if atomic.LoadInt32(&self.mining) == 0 {
243
					self.currentMu.Lock()
244
					self.current.commitTransactions(self.mux, types.Transactions{ev.Tx}, self.gasPrice, self.chain)
245
					self.currentMu.Unlock()
O
obscuren 已提交
246
				}
O
obscuren 已提交
247 248
			}
		case <-self.quit:
249
			return
O
obscuren 已提交
250 251 252 253
		}
	}
}

J
Jason Carver 已提交
254
func newLocalMinedBlock(blockNumber uint64, prevMinedBlocks *uint64RingBuffer) (minedBlocks *uint64RingBuffer) {
255
	if prevMinedBlocks == nil {
256
		minedBlocks = &uint64RingBuffer{next: 0, ints: make([]uint64, miningLogAtDepth+1)}
257 258 259 260 261 262 263 264 265
	} else {
		minedBlocks = prevMinedBlocks
	}

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

O
obscuren 已提交
266 267
func (self *worker) wait() {
	for {
J
Jeffrey Wilcke 已提交
268
		for result := range self.recv {
F
Felix Lange 已提交
269
			atomic.AddInt32(&self.atWork, -1)
O
obscuren 已提交
270

J
Jeffrey Wilcke 已提交
271
			if result == nil {
O
obscuren 已提交
272 273
				continue
			}
J
Jeffrey Wilcke 已提交
274
			block := result.Block
275
			work := result.Work
O
obscuren 已提交
276

J
Jeffrey Wilcke 已提交
277 278 279 280 281
			if self.fullValidation {
				if _, err := self.chain.InsertChain(types.Blocks{block}); err != nil {
					glog.V(logger.Error).Infoln("mining err", err)
					continue
				}
F
Felix Lange 已提交
282
				go self.mux.Post(core.NewMinedBlockEvent{Block: block})
J
Jeffrey Wilcke 已提交
283
			} else {
284
				work.state.Commit()
J
Jeffrey Wilcke 已提交
285 286 287 288 289
				parent := self.chain.GetBlock(block.ParentHash())
				if parent == nil {
					glog.V(logger.Error).Infoln("Invalid block found during mining")
					continue
				}
290 291

				auxValidator := self.eth.BlockChain().AuxValidator()
292
				if err := core.ValidateHeader(self.config, auxValidator, block.Header(), parent.Header(), true, false); err != nil && err != core.BlockFutureErr {
J
Jeffrey Wilcke 已提交
293 294 295
					glog.V(logger.Error).Infoln("Invalid header on mined block:", err)
					continue
				}
296

297
				stat, err := self.chain.WriteBlock(block)
J
Jeffrey Wilcke 已提交
298 299 300 301
				if err != nil {
					glog.V(logger.Error).Infoln("error writing block to chain", err)
					continue
				}
302 303 304 305 306 307 308 309 310 311 312

				// update block hash since it is now available and not when the receipt/log of individual transactions were created
				for _, r := range work.receipts {
					for _, l := range r.Logs {
						l.BlockHash = block.Hash()
					}
				}
				for _, log := range work.state.Logs() {
					log.BlockHash = block.Hash()
				}

J
Jeffrey Wilcke 已提交
313 314 315
				// check if canon block and write transactions
				if stat == core.CanonStatTy {
					// This puts transactions in a extra db for rpc
316
					core.WriteTransactions(self.chainDb, block)
J
Jeffrey Wilcke 已提交
317
					// store the receipts
318
					core.WriteReceipts(self.chainDb, work.receipts)
319 320
					// Write map map bloom filters
					core.WriteMipmapBloom(self.chainDb, block.NumberU64(), work.receipts)
J
Jeffrey Wilcke 已提交
321 322 323
				}

				// broadcast before waiting for validation
324
				go func(block *types.Block, logs vm.Logs, receipts []*types.Receipt) {
F
Felix Lange 已提交
325 326
					self.mux.Post(core.NewMinedBlockEvent{Block: block})
					self.mux.Post(core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
327

J
Jeffrey Wilcke 已提交
328
					if stat == core.CanonStatTy {
F
Felix Lange 已提交
329
						self.mux.Post(core.ChainHeadEvent{Block: block})
J
Jeffrey Wilcke 已提交
330 331
						self.mux.Post(logs)
					}
332
					if err := core.WriteBlockReceipts(self.chainDb, block.Hash(), receipts); err != nil {
333 334 335
						glog.V(logger.Warn).Infoln("error writing block receipts:", err)
					}
				}(block, work.state.Logs(), work.receipts)
336
			}
O
obscuren 已提交
337

338 339 340 341 342
			// 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 已提交
343
			} else {
344
				confirm = "Wait 5 blocks for confirmation"
345
				work.localMinedBlocks = newLocalMinedBlock(block.Number().Uint64(), work.localMinedBlocks)
346
			}
347 348 349
			glog.V(logger.Info).Infof("🔨  Mined %sblock (#%v / %x). %s", stale, block.Number(), block.Hash().Bytes()[:4], confirm)

			self.commitNewWork()
O
obscuren 已提交
350 351 352 353
		}
	}
}

354
// push sends a new work task to currently live miner agents.
355
func (self *worker) push(work *Work) {
356 357 358 359 360 361 362
	if atomic.LoadInt32(&self.mining) != 1 {
		return
	}
	for agent := range self.agents {
		atomic.AddInt32(&self.atWork, 1)
		if ch := agent.Work(); ch != nil {
			ch <- work
363
		}
O
obscuren 已提交
364 365 366
	}
}

F
Felix Lange 已提交
367
// makeCurrent creates a new environment for the current cycle.
368 369 370 371 372
func (self *worker) makeCurrent(parent *types.Block, header *types.Header) error {
	state, err := state.New(parent.Root(), self.eth.ChainDb())
	if err != nil {
		return err
	}
373
	work := &Work{
374
		config:    self.config,
F
Felix Lange 已提交
375 376 377 378 379
		state:     state,
		ancestors: set.New(),
		family:    set.New(),
		uncles:    set.New(),
		header:    header,
J
Jeffrey Wilcke 已提交
380
		createdAt: time.Now(),
381
	}
382

Z
zelig 已提交
383
	// when 08 is processed ancestors contain 07 (quick block)
F
Felix Lange 已提交
384
	for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
385
		for _, uncle := range ancestor.Uncles() {
386
			work.family.Add(uncle.Hash())
387
		}
388 389
		work.family.Add(ancestor.Hash())
		work.ancestors.Add(ancestor.Hash())
O
obscuren 已提交
390
	}
F
Felix Lange 已提交
391
	accounts := self.eth.AccountManager().Accounts()
F
Felix Lange 已提交
392

393
	// Keep track of transactions which return errors so they can be removed
394 395 396 397 398
	work.remove = set.New()
	work.tcount = 0
	work.ignoredTransactors = set.New()
	work.lowGasTransactors = set.New()
	work.ownedAccounts = accountAddressesSet(accounts)
399
	if self.current != nil {
400
		work.localMinedBlocks = self.current.localMinedBlocks
401
	}
402
	self.current = work
403
	return nil
O
obscuren 已提交
404 405
}

406 407 408
func (w *worker) setGasPrice(p *big.Int) {
	w.mu.Lock()
	defer w.mu.Unlock()
409 410 411 412 413

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

F
Felix Lange 已提交
414
	w.mux.Post(core.GasPriceChanged{Price: w.gasPrice})
415 416
}

417
func (self *worker) isBlockLocallyMined(current *Work, deepBlockNum uint64) bool {
418 419
	//Did this instance mine a block at {deepBlockNum} ?
	var isLocal = false
420
	for idx, blockNum := range current.localMinedBlocks.ints {
421 422
		if deepBlockNum == blockNum {
			isLocal = true
423
			current.localMinedBlocks.ints[idx] = 0 //prevent showing duplicate logs
424 425 426 427 428 429 430 431 432 433
			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 已提交
434
	return block != nil && block.Coinbase() == self.coinbase
435 436
}

437 438 439
func (self *worker) logLocalMinedBlocks(current, previous *Work) {
	if previous != nil && current.localMinedBlocks != nil {
		nextBlockNum := current.Block.NumberU64()
J
Jeffrey Wilcke 已提交
440
		for checkBlockNum := previous.Block.NumberU64(); checkBlockNum < nextBlockNum; checkBlockNum++ {
441
			inspectBlockNum := checkBlockNum - miningLogAtDepth
442
			if self.isBlockLocallyMined(current, inspectBlockNum) {
443
				glog.V(logger.Info).Infof("🔨 🔗  Mined %d blocks back: block #%v", miningLogAtDepth, inspectBlockNum)
444 445 446 447 448
			}
		}
	}
}

O
obscuren 已提交
449 450 451 452 453 454 455 456
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()

457
	tstart := time.Now()
F
Felix Lange 已提交
458 459
	parent := self.chain.CurrentBlock()
	tstamp := tstart.Unix()
C
Christoph Jentzsch 已提交
460
	if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 {
461
		tstamp = parent.Time().Int64() + 1
F
Felix Lange 已提交
462
	}
463 464 465 466 467 468 469
	// 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 已提交
470 471 472 473
	num := parent.Number()
	header := &types.Header{
		ParentHash: parent.Hash(),
		Number:     num.Add(num, common.Big1),
474
		Difficulty: core.CalcDifficulty(self.config, uint64(tstamp), parent.Time().Uint64(), parent.Number(), parent.Difficulty()),
F
Felix Lange 已提交
475 476 477 478
		GasLimit:   core.CalcGasLimit(parent),
		GasUsed:    new(big.Int),
		Coinbase:   self.coinbase,
		Extra:      self.extra,
479
		Time:       big.NewInt(tstamp),
F
Felix Lange 已提交
480
	}
481

482
	previous := self.current
483 484 485 486 487 488
	// Could potentially happen if starting to mine in an odd state.
	err := self.makeCurrent(parent, header)
	if err != nil {
		glog.V(logger.Info).Infoln("Could not create new env for mining, retrying on next block.")
		return
	}
489
	work := self.current
O
obscuren 已提交
490

491
	/* //approach 1
O
obscuren 已提交
492
	transactions := self.eth.TxPool().GetTransactions()
493
	sort.Sort(types.TxByNonce(transactions))
494 495 496 497
	*/

	//approach 2
	transactions := self.eth.TxPool().GetTransactions()
498
	types.SortByPriceAndNonce(transactions)
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

	/* // approach 3
	// commit transactions for this run.
	txPerOwner := make(map[common.Address]types.Transactions)
	// Sort transactions by owner
	for _, tx := range self.eth.TxPool().GetTransactions() {
		from, _ := tx.From() // we can ignore the sender error
		txPerOwner[from] = append(txPerOwner[from], tx)
	}
	var (
		singleTxOwner types.Transactions
		multiTxOwner  types.Transactions
	)
	// Categorise transactions by
	// 1. 1 owner tx per block
	// 2. multi txs owner per block
	for _, txs := range txPerOwner {
		if len(txs) == 1 {
			singleTxOwner = append(singleTxOwner, txs[0])
		} else {
			multiTxOwner = append(multiTxOwner, txs...)
		}
	}
522 523
	sort.Sort(types.TxByPrice(singleTxOwner))
	sort.Sort(types.TxByNonce(multiTxOwner))
524 525 526
	transactions := append(singleTxOwner, multiTxOwner...)
	*/

527
	work.commitTransactions(self.mux, transactions, self.gasPrice, self.chain)
528
	self.eth.TxPool().RemoveTransactions(work.lowGasTxs)
O
obscuren 已提交
529

F
Felix Lange 已提交
530
	// compute uncles for the new block.
O
obscuren 已提交
531 532 533 534
	var (
		uncles    []*types.Header
		badUncles []common.Hash
	)
O
obscuren 已提交
535
	for hash, uncle := range self.possibleUncles {
O
obscuren 已提交
536
		if len(uncles) == 2 {
O
obscuren 已提交
537 538
			break
		}
539
		if err := self.commitUncle(work, uncle.Header()); err != nil {
540 541 542 543
			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 已提交
544
			badUncles = append(badUncles, hash)
O
obscuren 已提交
545
		} else {
O
obscuren 已提交
546
			glog.V(logger.Debug).Infof("commiting %x as uncle\n", hash[:4])
O
obscuren 已提交
547
			uncles = append(uncles, uncle.Header())
O
obscuren 已提交
548 549
		}
	}
O
obscuren 已提交
550 551 552
	for _, hash := range badUncles {
		delete(self.possibleUncles, hash)
	}
553

554 555
	if atomic.LoadInt32(&self.mining) == 1 {
		// commit state root after all state transitions.
556
		core.AccumulateRewards(work.state, header, uncles)
557
		header.Root = work.state.IntermediateRoot()
558
	}
O
obscuren 已提交
559

F
Felix Lange 已提交
560
	// create the new block whose nonce will be mined.
561
	work.Block = types.NewBlock(header, work.txs, uncles, work.receipts)
O
obscuren 已提交
562

F
Felix Lange 已提交
563 564
	// We only care about logging if we're actually mining.
	if atomic.LoadInt32(&self.mining) == 1 {
565 566
		glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles. Took %v\n", work.Block.Number(), work.tcount, len(uncles), time.Since(tstart))
		self.logLocalMinedBlocks(work, previous)
F
Felix Lange 已提交
567
	}
568
	self.push(work)
O
obscuren 已提交
569 570
}

571
func (self *worker) commitUncle(work *Work, uncle *types.Header) error {
F
Felix Lange 已提交
572
	hash := uncle.Hash()
573
	if work.uncles.Has(hash) {
O
obscuren 已提交
574 575
		return core.UncleError("Uncle not unique")
	}
576
	if !work.ancestors.Has(uncle.ParentHash) {
O
obscuren 已提交
577 578
		return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
	}
579
	if work.family.Has(hash) {
F
Felix Lange 已提交
580
		return core.UncleError(fmt.Sprintf("Uncle already in family (%x)", hash))
O
obscuren 已提交
581
	}
582
	work.uncles.Add(uncle.Hash())
O
obscuren 已提交
583 584 585
	return nil
}

586
func (env *Work) commitTransactions(mux *event.TypeMux, transactions types.Transactions, gasPrice *big.Int, bc *core.BlockChain) {
587
	gp := new(core.GasPool).AddGas(env.header.GasLimit)
588 589

	var coalescedLogs vm.Logs
590
	for _, tx := range transactions {
591 592
		// Error may be ignored here. The error has already been checked
		// during transaction acceptance is the transaction pool.
593 594
		from, _ := tx.From()

595
		// Check if it falls within margin. Txs from owned accounts are always processed.
F
Felix Lange 已提交
596
		if tx.GasPrice().Cmp(gasPrice) < 0 && !env.ownedAccounts.Has(from) {
597 598 599
			// 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 已提交
600
			env.lowGasTransactors.Add(from)
601

F
Felix Lange 已提交
602
			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])
603 604 605 606 607
		}

		// 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 已提交
608
		if env.lowGasTransactors.Has(from) {
609 610
			// add tx to the low gas set. This will be removed at the end of the run
			// owned accounts are ignored
F
Felix Lange 已提交
611 612
			if !env.ownedAccounts.Has(from) {
				env.lowGasTxs = append(env.lowGasTxs, tx)
613 614 615 616 617 618 619 620 621
			}
			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 已提交
622
		if env.ignoredTransactors.Has(from) {
623 624 625
			continue
		}

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

628
		err, logs := env.commitTransaction(tx, bc, gp)
629
		switch {
630
		case core.IsGasLimitErr(err):
631 632
			// 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 已提交
633
			env.ignoredTransactors.Add(from)
634 635

			glog.V(logger.Detail).Infof("Gas limit reached for (%x) in this block. Continue to try smaller txs\n", from[:4])
636 637 638 639 640 641
		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)
			}
642
		default:
F
Felix Lange 已提交
643
			env.tcount++
644
			coalescedLogs = append(coalescedLogs, logs...)
645 646
		}
	}
647 648 649 650 651 652 653 654 655
	if len(coalescedLogs) > 0 || env.tcount > 0 {
		go func(logs vm.Logs, tcount int) {
			if len(logs) > 0 {
				mux.Post(core.PendingLogsEvent{Logs: logs})
			}
			if tcount > 0 {
				mux.Post(core.PendingStateEvent{})
			}
		}(coalescedLogs, env.tcount)
656
	}
657 658
}

659
func (env *Work) commitTransaction(tx *types.Transaction, bc *core.BlockChain, gp *core.GasPool) (error, vm.Logs) {
F
Felix Lange 已提交
660
	snap := env.state.Copy()
661 662 663 664 665 666 667 668 669

	// this is a bit of a hack to force jit for the miners
	config := env.config.VmConfig
	if !(config.EnableJit && config.ForceJit) {
		config.EnableJit = false
	}
	config.ForceJit = false // disable forcing jit

	receipt, logs, _, err := core.ApplyTransaction(env.config, bc, gp, env.state, env.header, tx, env.header.GasUsed, config)
670
	if err != nil {
F
Felix Lange 已提交
671
		env.state.Set(snap)
672
		return err, nil
O
obscuren 已提交
673
	}
F
Felix Lange 已提交
674 675
	env.txs = append(env.txs, tx)
	env.receipts = append(env.receipts, receipt)
676 677

	return nil, logs
O
obscuren 已提交
678
}
O
obscuren 已提交
679

680
// TODO: remove or use
O
obscuren 已提交
681
func (self *worker) HashRate() int64 {
682
	return 0
O
obscuren 已提交
683
}
O
obscuren 已提交
684 685 686 687 688 689 690 691 692

// 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
}
693 694 695 696

func accountAddressesSet(accounts []accounts.Account) *set.Set {
	accountSet := set.New()
	for _, account := range accounts {
697
		accountSet.Add(account.Address)
698 699 700
	}
	return accountSet
}