transaction_pool.go 10.4 KB
Newer Older
O
obscuren 已提交
1
package core
O
obscuren 已提交
2 3

import (
4
	"errors"
O
obscuren 已提交
5
	"fmt"
O
obscuren 已提交
6
	"math/big"
7
	"sort"
8
	"sync"
9

O
obscuren 已提交
10
	"github.com/ethereum/go-ethereum/common"
O
obscuren 已提交
11
	"github.com/ethereum/go-ethereum/core/state"
12
	"github.com/ethereum/go-ethereum/core/types"
O
obscuren 已提交
13
	"github.com/ethereum/go-ethereum/event"
O
obscuren 已提交
14
	"github.com/ethereum/go-ethereum/logger"
O
obscuren 已提交
15
	"github.com/ethereum/go-ethereum/logger/glog"
O
obscuren 已提交
16 17
)

18
var (
19
	// Transaction Pool Errors
O
obscuren 已提交
20
	ErrInvalidSender      = errors.New("Invalid sender")
21
	ErrNonce              = errors.New("Nonce too low")
22
	ErrBalance            = errors.New("Insufficient balance")
23
	ErrNonExistentAccount = errors.New("Account does not exist or account balance too low")
24
	ErrInsufficientFunds  = errors.New("Insufficient funds for gas * price + value")
O
obscuren 已提交
25
	ErrIntrinsicGas       = errors.New("Intrinsic gas too low")
26
	ErrGasLimit           = errors.New("Exceeds block gas limit")
27
	ErrNegativeValue      = errors.New("Negative value")
28
)
Z
zelig 已提交
29

30 31
type stateFn func() *state.StateDB

32 33 34 35 36 37 38
// TxPool contains all currently known transactions. Transactions
// enter the pool when they are received from the network or submitted
// locally. They exit the pool when they are included in the blockchain.
//
// The pool separates processable transactions (which can be applied to the
// current state) and future transactions. Transactions move between those
// two states over time as they are received and processed.
O
obscuren 已提交
39
type TxPool struct {
40 41 42
	quit         chan bool // Quiting channel
	currentState stateFn   // The state function which will allow us to do some pre checkes
	state        *state.ManagedState
43 44
	gasLimit     func() *big.Int // The current gas limit function callback
	eventMux     *event.TypeMux
45
	events       event.Subscription
O
obscuren 已提交
46

O
obscuren 已提交
47 48 49
	mu      sync.RWMutex
	pending map[common.Hash]*types.Transaction // processable transactions
	queue   map[common.Address]map[common.Hash]*types.Transaction
O
obscuren 已提交
50 51
}

52
func NewTxPool(eventMux *event.TypeMux, currentStateFn stateFn, gasLimitFn func() *big.Int) *TxPool {
53
	return &TxPool{
O
obscuren 已提交
54
		pending:      make(map[common.Hash]*types.Transaction),
55 56 57 58 59
		queue:        make(map[common.Address]map[common.Hash]*types.Transaction),
		quit:         make(chan bool),
		eventMux:     eventMux,
		currentState: currentStateFn,
		gasLimit:     gasLimitFn,
60
		state:        state.ManageState(currentStateFn()),
O
obscuren 已提交
61
	}
62 63 64
}

func (pool *TxPool) Start() {
O
obscuren 已提交
65 66 67
	// Track chain events. When a chain events occurs (new chain canon block)
	// we need to know the new state. The new state will help us determine
	// the nonces in the managed state
68 69 70 71 72
	pool.events = pool.eventMux.Subscribe(ChainEvent{})
	for _ = range pool.events.Chan() {
		pool.mu.Lock()
		pool.state = state.ManageState(pool.currentState())

O
obscuren 已提交
73 74 75 76 77 78 79 80
		// validate the pool of pending transactions, this will remove
		// any transactions that have been included in the block or
		// have been invalidated because of another transaction (e.g.
		// higher gas price)
		pool.validatePool()

		// Loop over the pending transactions and base the nonce of the new
		// pending transaction set.
O
obscuren 已提交
81
		for _, tx := range pool.pending {
82
			if addr, err := tx.From(); err == nil {
O
obscuren 已提交
83 84 85
				// Set the nonce. Transaction nonce can never be lower
				// than the state nonce; validatePool took care of that.
				pool.state.SetNonce(addr, tx.Nonce())
86
			}
87
		}
88

O
obscuren 已提交
89 90
		// Check the queue and move transactions over to the pending if possible
		// or remove those that have become invalid
91 92
		pool.checkQueue()
		pool.mu.Unlock()
93
	}
O
obscuren 已提交
94 95
}

96
func (pool *TxPool) Stop() {
O
obscuren 已提交
97
	pool.pending = make(map[common.Hash]*types.Transaction)
98 99 100 101 102 103 104 105 106 107 108 109
	close(pool.quit)
	pool.events.Unsubscribe()
	glog.V(logger.Info).Infoln("TX Pool stopped")
}

func (pool *TxPool) State() *state.ManagedState {
	pool.mu.RLock()
	defer pool.mu.RUnlock()

	return pool.state
}

110 111 112
// validateTx checks whether a transaction is valid according
// to the consensus rules.
func (pool *TxPool) validateTx(tx *types.Transaction) error {
113
	// Validate sender
O
obscuren 已提交
114 115 116 117 118
	var (
		from common.Address
		err  error
	)

O
obscuren 已提交
119 120
	// Validate the transaction sender and it's sig. Throw
	// if the from fields is invalid.
O
obscuren 已提交
121
	if from, err = tx.From(); err != nil {
F
Felix Lange 已提交
122
		return ErrInvalidSender
O
obscuren 已提交
123
	}
O
obscuren 已提交
124

O
obscuren 已提交
125 126
	// Make sure the account exist. Non existant accounts
	// haven't got funds and well therefor never pass.
O
obscuren 已提交
127 128
	if !pool.currentState().HasAccount(from) {
		return ErrNonExistentAccount
129
	}
O
obscuren 已提交
130

O
obscuren 已提交
131 132
	// Check the transaction doesn't exceed the current
	// block limit gas.
133 134 135 136
	if pool.gasLimit().Cmp(tx.GasLimit) < 0 {
		return ErrGasLimit
	}

O
obscuren 已提交
137 138 139
	// Transactions can't be negative. This may never happen
	// using RLP decoded transactions but may occur if you create
	// a transaction using the RPC for example.
140 141 142 143
	if tx.Amount.Cmp(common.Big0) < 0 {
		return ErrNegativeValue
	}

O
obscuren 已提交
144 145
	// Transactor should have enough funds to cover the costs
	// cost == V + GP * GL
146 147 148
	total := new(big.Int).Mul(tx.Price, tx.GasLimit)
	total.Add(total, tx.Value())
	if pool.currentState().GetBalance(from).Cmp(total) < 0 {
O
obscuren 已提交
149 150 151
		return ErrInsufficientFunds
	}

O
obscuren 已提交
152
	// Should supply enough intrinsic gas
O
obscuren 已提交
153 154 155 156
	if tx.GasLimit.Cmp(IntrinsicGas(tx)) < 0 {
		return ErrIntrinsicGas
	}

O
obscuren 已提交
157 158
	// Last but not least check for nonce errors (intensive
	// operation, saved for last)
O
obscuren 已提交
159
	if pool.currentState().GetNonce(from) > tx.Nonce() {
160
		return ErrNonce
O
obscuren 已提交
161 162 163
	}

	return nil
O
obscuren 已提交
164 165
}

166
func (self *TxPool) add(tx *types.Transaction) error {
167
	hash := tx.Hash()
168

O
obscuren 已提交
169 170
	/* XXX I'm unsure about this. This is extremely dangerous and may result
	 in total black listing of certain transactions
171 172 173
	if self.invalidHashes.Has(hash) {
		return fmt.Errorf("Invalid transaction (%x)", hash[:4])
	}
O
obscuren 已提交
174
	*/
O
obscuren 已提交
175
	if self.pending[hash] != nil {
176
		return fmt.Errorf("Known transaction (%x)", hash[:4])
177
	}
178
	err := self.validateTx(tx)
179 180 181
	if err != nil {
		return err
	}
182
	self.queueTx(hash, tx)
O
obscuren 已提交
183 184

	if glog.V(logger.Debug) {
185 186 187 188 189 190 191 192 193 194 195
		var toname string
		if to := tx.To(); to != nil {
			toname = common.Bytes2Hex(to[:4])
		} else {
			toname = "[NEW_CONTRACT]"
		}
		// we can ignore the error here because From is
		// verified in ValidateTransaction.
		f, _ := tx.From()
		from := common.Bytes2Hex(f[:4])
		glog.Infof("(t) %x => %s (%v) %x\n", from, toname, tx.Value, hash)
O
obscuren 已提交
196
	}
197

198 199 200
	// check and validate the queueue
	self.checkQueue()

201 202 203
	return nil
}

204
// Add queues a single transaction in the pool if it is valid.
205 206 207
func (self *TxPool) Add(tx *types.Transaction) error {
	self.mu.Lock()
	defer self.mu.Unlock()
208

209 210
	return self.add(tx)
}
211

212
// AddTransactions attempts to queue all valid transactions in txs.
Z
zelig 已提交
213
func (self *TxPool) AddTransactions(txs []*types.Transaction) {
214 215 216
	self.mu.Lock()
	defer self.mu.Unlock()

Z
zelig 已提交
217
	for _, tx := range txs {
218
		if err := self.add(tx); err != nil {
219
			glog.V(logger.Debug).Infoln("tx error:", err)
Z
zelig 已提交
220
		} else {
221
			h := tx.Hash()
O
obscuren 已提交
222
			glog.V(logger.Debug).Infof("tx %x\n", h[:4])
Z
zelig 已提交
223 224 225 226
		}
	}
}

227 228
// GetTransaction returns a transaction if it is contained in the pool
// and nil otherwise.
229 230
func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
	// check the txs first
O
obscuren 已提交
231
	if tx, ok := tp.pending[hash]; ok {
232 233 234 235
		return tx
	}
	// check queue
	for _, txs := range tp.queue {
236 237
		if tx, ok := txs[hash]; ok {
			return tx
238 239 240 241 242
		}
	}
	return nil
}

243
// GetTransactions returns all currently processable transactions.
O
Merge  
obscuren 已提交
244
func (self *TxPool) GetTransactions() (txs types.Transactions) {
245 246 247 248 249 250 251
	self.mu.Lock()
	defer self.mu.Unlock()

	// check queue first
	self.checkQueue()
	// invalidate any txs
	self.validatePool()
252

O
obscuren 已提交
253
	txs = make(types.Transactions, len(self.pending))
O
obscuren 已提交
254
	i := 0
O
obscuren 已提交
255
	for _, tx := range self.pending {
O
Merge  
obscuren 已提交
256
		txs[i] = tx
O
obscuren 已提交
257
		i++
O
Merge  
obscuren 已提交
258
	}
259
	return txs
260 261
}

262
// GetQueuedTransactions returns all non-processable transactions.
263 264 265 266
func (self *TxPool) GetQueuedTransactions() types.Transactions {
	self.mu.RLock()
	defer self.mu.RUnlock()

267 268 269 270 271
	var ret types.Transactions
	for _, txs := range self.queue {
		for _, tx := range txs {
			ret = append(ret, tx)
		}
272
	}
273 274
	sort.Sort(types.TxByNonce{ret})
	return ret
275 276
}

277
// RemoveTransactions removes all given transactions from the pool.
278
func (self *TxPool) RemoveTransactions(txs types.Transactions) {
279 280
	self.mu.Lock()
	defer self.mu.Unlock()
281
	for _, tx := range txs {
O
obscuren 已提交
282
		self.removeTx(tx.Hash())
283 284 285
	}
}

286
func (self *TxPool) queueTx(hash common.Hash, tx *types.Transaction) {
287
	from, _ := tx.From() // already validated
288 289 290 291
	if self.queue[from] == nil {
		self.queue[from] = make(map[common.Hash]*types.Transaction)
	}
	self.queue[from][hash] = tx
292 293
}

294
func (pool *TxPool) addTx(hash common.Hash, addr common.Address, tx *types.Transaction) {
O
obscuren 已提交
295 296
	if _, ok := pool.pending[hash]; !ok {
		pool.pending[hash] = tx
297 298

		pool.state.SetNonce(addr, tx.AccountNonce)
299 300 301 302
		// Notify the subscribers. This event is posted in a goroutine
		// because it's possible that somewhere during the post "Remove transaction"
		// gets called which will then wait for the global tx pool lock and deadlock.
		go pool.eventMux.Post(TxPreEvent{tx})
303 304 305
	}
}

306
// checkQueue moves transactions that have become processable to main pool.
307
func (pool *TxPool) checkQueue() {
308
	state := pool.state
309

310
	var addq txQueue
311
	for address, txs := range pool.queue {
312
		curnonce := state.GetNonce(address)
313 314 315 316 317 318 319 320
		addq := addq[:0]
		for hash, tx := range txs {
			if tx.AccountNonce < curnonce {
				// Drop queued transactions whose nonce is lower than
				// the account nonce because they have been processed.
				delete(txs, hash)
			} else {
				// Collect the remaining transactions for the next pass.
321
				addq = append(addq, txQueueEntry{hash, address, tx})
322 323
			}
		}
324 325 326 327
		// Find the next consecutive nonce range starting at the
		// current account nonce.
		sort.Sort(addq)
		for _, e := range addq {
328
			if e.AccountNonce > curnonce+1 {
329 330
				break
			}
331
			delete(txs, e.hash)
332
			pool.addTx(e.hash, address, e.Transaction)
333
		}
334 335
		// Delete the entire queue entry if it became empty.
		if len(txs) == 0 {
336 337 338 339
			delete(pool.queue, address)
		}
	}
}
340

341 342
func (pool *TxPool) removeTx(hash common.Hash) {
	// delete from pending pool
O
obscuren 已提交
343
	delete(pool.pending, hash)
344 345
	// delete from queue
	for address, txs := range pool.queue {
346 347 348 349 350 351
		if _, ok := txs[hash]; ok {
			if len(txs) == 1 {
				// if only one tx, remove entire address entry.
				delete(pool.queue, address)
			} else {
				delete(txs, hash)
352
			}
353
			break
354 355 356 357
		}
	}
}

358
// validatePool removes invalid and processed transactions from the main pool.
359
func (pool *TxPool) validatePool() {
O
obscuren 已提交
360
	for hash, tx := range pool.pending {
361
		if err := pool.validateTx(tx); err != nil {
O
obscuren 已提交
362
			if glog.V(logger.Core) {
363
				glog.Infof("removed tx (%x) from pool: %v\n", hash[:4], err)
364
			}
O
obscuren 已提交
365
			delete(pool.pending, hash)
366 367 368
		}
	}
}
369 370 371 372 373

type txQueue []txQueueEntry

type txQueueEntry struct {
	hash common.Hash
374
	addr common.Address
375 376 377 378 379 380
	*types.Transaction
}

func (q txQueue) Len() int           { return len(q) }
func (q txQueue) Swap(i, j int)      { q[i], q[j] = q[j], q[i] }
func (q txQueue) Less(i, j int) bool { return q[i].AccountNonce < q[j].AccountNonce }