transaction_pool.go 9.0 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

47
	mu    sync.RWMutex
48
	txs   map[common.Hash]*types.Transaction // processable transactions
49
	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 54 55 56 57 58 59
	return &TxPool{
		txs:          make(map[common.Hash]*types.Transaction),
		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() {
65 66 67 68 69 70 71 72 73
	pool.events = pool.eventMux.Subscribe(ChainEvent{})
	for _ = range pool.events.Chan() {
		pool.mu.Lock()
		pool.state = state.ManageState(pool.currentState())

		for _, tx := range pool.txs {
			if addr, err := tx.From(); err == nil {
				pool.state.SetNonce(addr, tx.Nonce())
			}
74
		}
75 76 77

		pool.checkQueue()
		pool.mu.Unlock()
78
	}
O
obscuren 已提交
79 80
}

81 82 83 84 85 86 87 88 89 90 91 92 93 94
func (pool *TxPool) Stop() {
	pool.txs = make(map[common.Hash]*types.Transaction)
	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
}

95 96 97
// validateTx checks whether a transaction is valid according
// to the consensus rules.
func (pool *TxPool) validateTx(tx *types.Transaction) error {
98
	// Validate sender
O
obscuren 已提交
99 100 101 102 103 104
	var (
		from common.Address
		err  error
	)

	if from, err = tx.From(); err != nil {
F
Felix Lange 已提交
105
		return ErrInvalidSender
O
obscuren 已提交
106
	}
O
obscuren 已提交
107 108 109

	if !pool.currentState().HasAccount(from) {
		return ErrNonExistentAccount
110
	}
O
obscuren 已提交
111

112 113 114 115
	if pool.gasLimit().Cmp(tx.GasLimit) < 0 {
		return ErrGasLimit
	}

116 117 118 119
	if tx.Amount.Cmp(common.Big0) < 0 {
		return ErrNegativeValue
	}

120 121 122
	total := new(big.Int).Mul(tx.Price, tx.GasLimit)
	total.Add(total, tx.Value())
	if pool.currentState().GetBalance(from).Cmp(total) < 0 {
O
obscuren 已提交
123 124 125 126 127 128 129 130
		return ErrInsufficientFunds
	}

	if tx.GasLimit.Cmp(IntrinsicGas(tx)) < 0 {
		return ErrIntrinsicGas
	}

	if pool.currentState().GetNonce(from) > tx.Nonce() {
131
		return ErrNonce
O
obscuren 已提交
132 133 134
	}

	return nil
O
obscuren 已提交
135 136
}

137
func (self *TxPool) add(tx *types.Transaction) error {
138
	hash := tx.Hash()
139

O
obscuren 已提交
140 141
	/* XXX I'm unsure about this. This is extremely dangerous and may result
	 in total black listing of certain transactions
142 143 144
	if self.invalidHashes.Has(hash) {
		return fmt.Errorf("Invalid transaction (%x)", hash[:4])
	}
O
obscuren 已提交
145
	*/
146
	if self.txs[hash] != nil {
147
		return fmt.Errorf("Known transaction (%x)", hash[:4])
148
	}
149
	err := self.validateTx(tx)
150 151 152
	if err != nil {
		return err
	}
153
	self.queueTx(hash, tx)
O
obscuren 已提交
154 155

	if glog.V(logger.Debug) {
156 157 158 159 160 161 162 163 164 165 166
		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 已提交
167
	}
168

169 170 171
	// check and validate the queueue
	self.checkQueue()

172 173 174
	return nil
}

175
// Add queues a single transaction in the pool if it is valid.
176 177 178
func (self *TxPool) Add(tx *types.Transaction) error {
	self.mu.Lock()
	defer self.mu.Unlock()
179

180 181
	return self.add(tx)
}
182

183
// AddTransactions attempts to queue all valid transactions in txs.
Z
zelig 已提交
184
func (self *TxPool) AddTransactions(txs []*types.Transaction) {
185 186 187
	self.mu.Lock()
	defer self.mu.Unlock()

Z
zelig 已提交
188
	for _, tx := range txs {
189
		if err := self.add(tx); err != nil {
190
			glog.V(logger.Debug).Infoln("tx error:", err)
Z
zelig 已提交
191
		} else {
192
			h := tx.Hash()
O
obscuren 已提交
193
			glog.V(logger.Debug).Infof("tx %x\n", h[:4])
Z
zelig 已提交
194 195 196 197
		}
	}
}

198 199
// GetTransaction returns a transaction if it is contained in the pool
// and nil otherwise.
200 201 202 203 204 205 206
func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
	// check the txs first
	if tx, ok := tp.txs[hash]; ok {
		return tx
	}
	// check queue
	for _, txs := range tp.queue {
207 208
		if tx, ok := txs[hash]; ok {
			return tx
209 210 211 212 213
		}
	}
	return nil
}

214
// GetTransactions returns all currently processable transactions.
O
Merge  
obscuren 已提交
215
func (self *TxPool) GetTransactions() (txs types.Transactions) {
216 217 218 219 220 221 222
	self.mu.Lock()
	defer self.mu.Unlock()

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

224
	txs = make(types.Transactions, len(self.txs))
O
obscuren 已提交
225
	i := 0
O
Merge  
obscuren 已提交
226 227
	for _, tx := range self.txs {
		txs[i] = tx
O
obscuren 已提交
228
		i++
O
Merge  
obscuren 已提交
229
	}
230
	return txs
231 232
}

233
// GetQueuedTransactions returns all non-processable transactions.
234 235 236 237
func (self *TxPool) GetQueuedTransactions() types.Transactions {
	self.mu.RLock()
	defer self.mu.RUnlock()

238 239 240 241 242
	var ret types.Transactions
	for _, txs := range self.queue {
		for _, tx := range txs {
			ret = append(ret, tx)
		}
243
	}
244 245
	sort.Sort(types.TxByNonce{ret})
	return ret
246 247
}

248
// RemoveTransactions removes all given transactions from the pool.
249
func (self *TxPool) RemoveTransactions(txs types.Transactions) {
250 251
	self.mu.Lock()
	defer self.mu.Unlock()
252
	for _, tx := range txs {
O
obscuren 已提交
253
		self.removeTx(tx.Hash())
254 255 256
	}
}

257
func (self *TxPool) queueTx(hash common.Hash, tx *types.Transaction) {
258
	from, _ := tx.From() // already validated
259 260 261 262
	if self.queue[from] == nil {
		self.queue[from] = make(map[common.Hash]*types.Transaction)
	}
	self.queue[from][hash] = tx
263 264
}

265
func (pool *TxPool) addTx(hash common.Hash, addr common.Address, tx *types.Transaction) {
266 267
	if _, ok := pool.txs[hash]; !ok {
		pool.txs[hash] = tx
268 269

		pool.state.SetNonce(addr, tx.AccountNonce)
270 271 272 273
		// 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})
274 275 276
	}
}

277
// checkQueue moves transactions that have become processable to main pool.
278
func (pool *TxPool) checkQueue() {
279
	state := pool.state
280

281
	var addq txQueue
282
	for address, txs := range pool.queue {
283
		curnonce := state.GetNonce(address)
284 285 286 287 288 289 290 291
		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.
292
				addq = append(addq, txQueueEntry{hash, address, tx})
293 294
			}
		}
295 296 297 298
		// Find the next consecutive nonce range starting at the
		// current account nonce.
		sort.Sort(addq)
		for _, e := range addq {
299
			if e.AccountNonce > curnonce+1 {
300 301
				break
			}
302
			delete(txs, e.hash)
303
			pool.addTx(e.hash, address, e.Transaction)
304
		}
305 306
		// Delete the entire queue entry if it became empty.
		if len(txs) == 0 {
307 308 309 310
			delete(pool.queue, address)
		}
	}
}
311

312 313 314 315 316
func (pool *TxPool) removeTx(hash common.Hash) {
	// delete from pending pool
	delete(pool.txs, hash)
	// delete from queue
	for address, txs := range pool.queue {
317 318 319 320 321 322
		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)
323
			}
324
			break
325 326 327 328
		}
	}
}

329
// validatePool removes invalid and processed transactions from the main pool.
330 331
func (pool *TxPool) validatePool() {
	for hash, tx := range pool.txs {
332
		if err := pool.validateTx(tx); err != nil {
333 334
			if glog.V(logger.Info) {
				glog.Infof("removed tx (%x) from pool: %v\n", hash[:4], err)
335
			}
336
			delete(pool.txs, hash)
337 338 339
		}
	}
}
340 341 342 343 344

type txQueue []txQueueEntry

type txQueueEntry struct {
	hash common.Hash
345
	addr common.Address
346 347 348 349 350 351
	*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 }