github.com/myafeier/go-ethereum@v1.6.8-0.20170719123245-3e0dbe0eaa72/light/txpool.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // 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/>.
    16  
    17  package light
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"sync"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/core"
    27  	"github.com/ethereum/go-ethereum/core/state"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/ethdb"
    30  	"github.com/ethereum/go-ethereum/event"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/params"
    33  	"github.com/ethereum/go-ethereum/rlp"
    34  )
    35  
    36  // txPermanent is the number of mined blocks after a mined transaction is
    37  // considered permanent and no rollback is expected
    38  var txPermanent = uint64(500)
    39  
    40  // TxPool implements the transaction pool for light clients, which keeps track
    41  // of the status of locally created transactions, detecting if they are included
    42  // in a block (mined) or rolled back. There are no queued transactions since we
    43  // always receive all locally signed transactions in the same order as they are
    44  // created.
    45  type TxPool struct {
    46  	config   *params.ChainConfig
    47  	signer   types.Signer
    48  	quit     chan bool
    49  	eventMux *event.TypeMux
    50  	events   *event.TypeMuxSubscription
    51  	mu       sync.RWMutex
    52  	chain    *LightChain
    53  	odr      OdrBackend
    54  	chainDb  ethdb.Database
    55  	relay    TxRelayBackend
    56  	head     common.Hash
    57  	nonce    map[common.Address]uint64            // "pending" nonce
    58  	pending  map[common.Hash]*types.Transaction   // pending transactions by tx hash
    59  	mined    map[common.Hash][]*types.Transaction // mined transactions by block hash
    60  	clearIdx uint64                               // earliest block nr that can contain mined tx info
    61  
    62  	homestead bool
    63  }
    64  
    65  // TxRelayBackend provides an interface to the mechanism that forwards transacions
    66  // to the ETH network. The implementations of the functions should be non-blocking.
    67  //
    68  // Send instructs backend to forward new transactions
    69  // NewHead notifies backend about a new head after processed by the tx pool,
    70  //  including  mined and rolled back transactions since the last event
    71  // Discard notifies backend about transactions that should be discarded either
    72  //  because they have been replaced by a re-send or because they have been mined
    73  //  long ago and no rollback is expected
    74  type TxRelayBackend interface {
    75  	Send(txs types.Transactions)
    76  	NewHead(head common.Hash, mined []common.Hash, rollback []common.Hash)
    77  	Discard(hashes []common.Hash)
    78  }
    79  
    80  // NewTxPool creates a new light transaction pool
    81  func NewTxPool(config *params.ChainConfig, eventMux *event.TypeMux, chain *LightChain, relay TxRelayBackend) *TxPool {
    82  	pool := &TxPool{
    83  		config:   config,
    84  		signer:   types.HomesteadSigner{},
    85  		nonce:    make(map[common.Address]uint64),
    86  		pending:  make(map[common.Hash]*types.Transaction),
    87  		mined:    make(map[common.Hash][]*types.Transaction),
    88  		quit:     make(chan bool),
    89  		eventMux: eventMux,
    90  		events:   eventMux.Subscribe(core.ChainHeadEvent{}),
    91  		chain:    chain,
    92  		relay:    relay,
    93  		odr:      chain.Odr(),
    94  		chainDb:  chain.Odr().Database(),
    95  		head:     chain.CurrentHeader().Hash(),
    96  		clearIdx: chain.CurrentHeader().Number.Uint64(),
    97  	}
    98  	go pool.eventLoop()
    99  
   100  	return pool
   101  }
   102  
   103  // currentState returns the light state of the current head header
   104  func (pool *TxPool) currentState(ctx context.Context) *state.StateDB {
   105  	return NewState(ctx, pool.chain.CurrentHeader(), pool.odr)
   106  }
   107  
   108  // GetNonce returns the "pending" nonce of a given address. It always queries
   109  // the nonce belonging to the latest header too in order to detect if another
   110  // client using the same key sent a transaction.
   111  func (pool *TxPool) GetNonce(ctx context.Context, addr common.Address) (uint64, error) {
   112  	state := pool.currentState(ctx)
   113  	nonce := state.GetNonce(addr)
   114  	if state.Error() != nil {
   115  		return 0, state.Error()
   116  	}
   117  	sn, ok := pool.nonce[addr]
   118  	if ok && sn > nonce {
   119  		nonce = sn
   120  	}
   121  	if !ok || sn < nonce {
   122  		pool.nonce[addr] = nonce
   123  	}
   124  	return nonce, nil
   125  }
   126  
   127  type txBlockData struct {
   128  	BlockHash  common.Hash
   129  	BlockIndex uint64
   130  	Index      uint64
   131  }
   132  
   133  // txStateChanges stores the recent changes between pending/mined states of
   134  // transactions. True means mined, false means rolled back, no entry means no change
   135  type txStateChanges map[common.Hash]bool
   136  
   137  // setState sets the status of a tx to either recently mined or recently rolled back
   138  func (txc txStateChanges) setState(txHash common.Hash, mined bool) {
   139  	val, ent := txc[txHash]
   140  	if ent && (val != mined) {
   141  		delete(txc, txHash)
   142  	} else {
   143  		txc[txHash] = mined
   144  	}
   145  }
   146  
   147  // getLists creates lists of mined and rolled back tx hashes
   148  func (txc txStateChanges) getLists() (mined []common.Hash, rollback []common.Hash) {
   149  	for hash, val := range txc {
   150  		if val {
   151  			mined = append(mined, hash)
   152  		} else {
   153  			rollback = append(rollback, hash)
   154  		}
   155  	}
   156  	return
   157  }
   158  
   159  // checkMinedTxs checks newly added blocks for the currently pending transactions
   160  // and marks them as mined if necessary. It also stores block position in the db
   161  // and adds them to the received txStateChanges map.
   162  func (pool *TxPool) checkMinedTxs(ctx context.Context, hash common.Hash, number uint64, txc txStateChanges) error {
   163  	// If no transactions are pending, we don't care about anything
   164  	if len(pool.pending) == 0 {
   165  		return nil
   166  	}
   167  	block, err := GetBlock(ctx, pool.odr, hash, number)
   168  	if err != nil {
   169  		return err
   170  	}
   171  	// Gather all the local transaction mined in this block
   172  	list := pool.mined[hash]
   173  	for _, tx := range block.Transactions() {
   174  		if _, ok := pool.pending[tx.Hash()]; ok {
   175  			list = append(list, tx)
   176  		}
   177  	}
   178  	// If some transactions have been mined, write the needed data to disk and update
   179  	if list != nil {
   180  		// Retrieve all the receipts belonging to this block and write the loopup table
   181  		if _, err := GetBlockReceipts(ctx, pool.odr, hash, number); err != nil { // ODR caches, ignore results
   182  			return err
   183  		}
   184  		if err := core.WriteTxLookupEntries(pool.chainDb, block); err != nil {
   185  			return err
   186  		}
   187  		// Update the transaction pool's state
   188  		for _, tx := range list {
   189  			delete(pool.pending, tx.Hash())
   190  			txc.setState(tx.Hash(), true)
   191  		}
   192  		pool.mined[hash] = list
   193  	}
   194  	return nil
   195  }
   196  
   197  // rollbackTxs marks the transactions contained in recently rolled back blocks
   198  // as rolled back. It also removes any positional lookup entries.
   199  func (pool *TxPool) rollbackTxs(hash common.Hash, txc txStateChanges) {
   200  	if list, ok := pool.mined[hash]; ok {
   201  		for _, tx := range list {
   202  			txHash := tx.Hash()
   203  			core.DeleteTxLookupEntry(pool.chainDb, txHash)
   204  			pool.pending[txHash] = tx
   205  			txc.setState(txHash, false)
   206  		}
   207  		delete(pool.mined, hash)
   208  	}
   209  }
   210  
   211  // reorgOnNewHead sets a new head header, processing (and rolling back if necessary)
   212  // the blocks since the last known head and returns a txStateChanges map containing
   213  // the recently mined and rolled back transaction hashes. If an error (context
   214  // timeout) occurs during checking new blocks, it leaves the locally known head
   215  // at the latest checked block and still returns a valid txStateChanges, making it
   216  // possible to continue checking the missing blocks at the next chain head event
   217  func (pool *TxPool) reorgOnNewHead(ctx context.Context, newHeader *types.Header) (txStateChanges, error) {
   218  	txc := make(txStateChanges)
   219  	oldh := pool.chain.GetHeaderByHash(pool.head)
   220  	newh := newHeader
   221  	// find common ancestor, create list of rolled back and new block hashes
   222  	var oldHashes, newHashes []common.Hash
   223  	for oldh.Hash() != newh.Hash() {
   224  		if oldh.Number.Uint64() >= newh.Number.Uint64() {
   225  			oldHashes = append(oldHashes, oldh.Hash())
   226  			oldh = pool.chain.GetHeader(oldh.ParentHash, oldh.Number.Uint64()-1)
   227  		}
   228  		if oldh.Number.Uint64() < newh.Number.Uint64() {
   229  			newHashes = append(newHashes, newh.Hash())
   230  			newh = pool.chain.GetHeader(newh.ParentHash, newh.Number.Uint64()-1)
   231  			if newh == nil {
   232  				// happens when CHT syncing, nothing to do
   233  				newh = oldh
   234  			}
   235  		}
   236  	}
   237  	if oldh.Number.Uint64() < pool.clearIdx {
   238  		pool.clearIdx = oldh.Number.Uint64()
   239  	}
   240  	// roll back old blocks
   241  	for _, hash := range oldHashes {
   242  		pool.rollbackTxs(hash, txc)
   243  	}
   244  	pool.head = oldh.Hash()
   245  	// check mined txs of new blocks (array is in reversed order)
   246  	for i := len(newHashes) - 1; i >= 0; i-- {
   247  		hash := newHashes[i]
   248  		if err := pool.checkMinedTxs(ctx, hash, newHeader.Number.Uint64()-uint64(i), txc); err != nil {
   249  			return txc, err
   250  		}
   251  		pool.head = hash
   252  	}
   253  
   254  	// clear old mined tx entries of old blocks
   255  	if idx := newHeader.Number.Uint64(); idx > pool.clearIdx+txPermanent {
   256  		idx2 := idx - txPermanent
   257  		if len(pool.mined) > 0 {
   258  			for i := pool.clearIdx; i < idx2; i++ {
   259  				hash := core.GetCanonicalHash(pool.chainDb, i)
   260  				if list, ok := pool.mined[hash]; ok {
   261  					hashes := make([]common.Hash, len(list))
   262  					for i, tx := range list {
   263  						hashes[i] = tx.Hash()
   264  					}
   265  					pool.relay.Discard(hashes)
   266  					delete(pool.mined, hash)
   267  				}
   268  			}
   269  		}
   270  		pool.clearIdx = idx2
   271  	}
   272  
   273  	return txc, nil
   274  }
   275  
   276  // blockCheckTimeout is the time limit for checking new blocks for mined
   277  // transactions. Checking resumes at the next chain head event if timed out.
   278  const blockCheckTimeout = time.Second * 3
   279  
   280  // eventLoop processes chain head events and also notifies the tx relay backend
   281  // about the new head hash and tx state changes
   282  func (pool *TxPool) eventLoop() {
   283  	for ev := range pool.events.Chan() {
   284  		switch ev.Data.(type) {
   285  		case core.ChainHeadEvent:
   286  			pool.setNewHead(ev.Data.(core.ChainHeadEvent).Block.Header())
   287  			// hack in order to avoid hogging the lock; this part will
   288  			// be replaced by a subsequent PR.
   289  			time.Sleep(time.Millisecond)
   290  		}
   291  	}
   292  }
   293  
   294  func (pool *TxPool) setNewHead(head *types.Header) {
   295  	pool.mu.Lock()
   296  	defer pool.mu.Unlock()
   297  
   298  	ctx, cancel := context.WithTimeout(context.Background(), blockCheckTimeout)
   299  	defer cancel()
   300  
   301  	txc, _ := pool.reorgOnNewHead(ctx, head)
   302  	m, r := txc.getLists()
   303  	pool.relay.NewHead(pool.head, m, r)
   304  	pool.homestead = pool.config.IsHomestead(head.Number)
   305  	pool.signer = types.MakeSigner(pool.config, head.Number)
   306  }
   307  
   308  // Stop stops the light transaction pool
   309  func (pool *TxPool) Stop() {
   310  	close(pool.quit)
   311  	pool.events.Unsubscribe()
   312  	log.Info("Transaction pool stopped")
   313  }
   314  
   315  // Stats returns the number of currently pending (locally created) transactions
   316  func (pool *TxPool) Stats() (pending int) {
   317  	pool.mu.RLock()
   318  	defer pool.mu.RUnlock()
   319  
   320  	pending = len(pool.pending)
   321  	return
   322  }
   323  
   324  // validateTx checks whether a transaction is valid according to the consensus rules.
   325  func (pool *TxPool) validateTx(ctx context.Context, tx *types.Transaction) error {
   326  	// Validate sender
   327  	var (
   328  		from common.Address
   329  		err  error
   330  	)
   331  
   332  	// Validate the transaction sender and it's sig. Throw
   333  	// if the from fields is invalid.
   334  	if from, err = types.Sender(pool.signer, tx); err != nil {
   335  		return core.ErrInvalidSender
   336  	}
   337  	// Last but not least check for nonce errors
   338  	currentState := pool.currentState(ctx)
   339  	if n := currentState.GetNonce(from); n > tx.Nonce() {
   340  		return core.ErrNonceTooLow
   341  	}
   342  
   343  	// Check the transaction doesn't exceed the current
   344  	// block limit gas.
   345  	header := pool.chain.GetHeaderByHash(pool.head)
   346  	if header.GasLimit.Cmp(tx.Gas()) < 0 {
   347  		return core.ErrGasLimit
   348  	}
   349  
   350  	// Transactions can't be negative. This may never happen
   351  	// using RLP decoded transactions but may occur if you create
   352  	// a transaction using the RPC for example.
   353  	if tx.Value().Sign() < 0 {
   354  		return core.ErrNegativeValue
   355  	}
   356  
   357  	// Transactor should have enough funds to cover the costs
   358  	// cost == V + GP * GL
   359  	if b := currentState.GetBalance(from); b.Cmp(tx.Cost()) < 0 {
   360  		return core.ErrInsufficientFunds
   361  	}
   362  
   363  	// Should supply enough intrinsic gas
   364  	if tx.Gas().Cmp(core.IntrinsicGas(tx.Data(), tx.To() == nil, pool.homestead)) < 0 {
   365  		return core.ErrIntrinsicGas
   366  	}
   367  
   368  	return currentState.Error()
   369  }
   370  
   371  // add validates a new transaction and sets its state pending if processable.
   372  // It also updates the locally stored nonce if necessary.
   373  func (self *TxPool) add(ctx context.Context, tx *types.Transaction) error {
   374  	hash := tx.Hash()
   375  
   376  	if self.pending[hash] != nil {
   377  		return fmt.Errorf("Known transaction (%x)", hash[:4])
   378  	}
   379  	err := self.validateTx(ctx, tx)
   380  	if err != nil {
   381  		return err
   382  	}
   383  
   384  	if _, ok := self.pending[hash]; !ok {
   385  		self.pending[hash] = tx
   386  
   387  		nonce := tx.Nonce() + 1
   388  
   389  		addr, _ := types.Sender(self.signer, tx)
   390  		if nonce > self.nonce[addr] {
   391  			self.nonce[addr] = nonce
   392  		}
   393  
   394  		// Notify the subscribers. This event is posted in a goroutine
   395  		// because it's possible that somewhere during the post "Remove transaction"
   396  		// gets called which will then wait for the global tx pool lock and deadlock.
   397  		go self.eventMux.Post(core.TxPreEvent{Tx: tx})
   398  	}
   399  
   400  	// Print a log message if low enough level is set
   401  	log.Debug("Pooled new transaction", "hash", hash, "from", log.Lazy{Fn: func() common.Address { from, _ := types.Sender(self.signer, tx); return from }}, "to", tx.To())
   402  	return nil
   403  }
   404  
   405  // Add adds a transaction to the pool if valid and passes it to the tx relay
   406  // backend
   407  func (self *TxPool) Add(ctx context.Context, tx *types.Transaction) error {
   408  	self.mu.Lock()
   409  	defer self.mu.Unlock()
   410  
   411  	data, err := rlp.EncodeToBytes(tx)
   412  	if err != nil {
   413  		return err
   414  	}
   415  
   416  	if err := self.add(ctx, tx); err != nil {
   417  		return err
   418  	}
   419  	//fmt.Println("Send", tx.Hash())
   420  	self.relay.Send(types.Transactions{tx})
   421  
   422  	self.chainDb.Put(tx.Hash().Bytes(), data)
   423  	return nil
   424  }
   425  
   426  // AddTransactions adds all valid transactions to the pool and passes them to
   427  // the tx relay backend
   428  func (self *TxPool) AddBatch(ctx context.Context, txs []*types.Transaction) {
   429  	self.mu.Lock()
   430  	defer self.mu.Unlock()
   431  	var sendTx types.Transactions
   432  
   433  	for _, tx := range txs {
   434  		if err := self.add(ctx, tx); err == nil {
   435  			sendTx = append(sendTx, tx)
   436  		}
   437  	}
   438  	if len(sendTx) > 0 {
   439  		self.relay.Send(sendTx)
   440  	}
   441  }
   442  
   443  // GetTransaction returns a transaction if it is contained in the pool
   444  // and nil otherwise.
   445  func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
   446  	// check the txs first
   447  	if tx, ok := tp.pending[hash]; ok {
   448  		return tx
   449  	}
   450  	return nil
   451  }
   452  
   453  // GetTransactions returns all currently processable transactions.
   454  // The returned slice may be modified by the caller.
   455  func (self *TxPool) GetTransactions() (txs types.Transactions, err error) {
   456  	self.mu.RLock()
   457  	defer self.mu.RUnlock()
   458  
   459  	txs = make(types.Transactions, len(self.pending))
   460  	i := 0
   461  	for _, tx := range self.pending {
   462  		txs[i] = tx
   463  		i++
   464  	}
   465  	return txs, nil
   466  }
   467  
   468  // Content retrieves the data content of the transaction pool, returning all the
   469  // pending as well as queued transactions, grouped by account and nonce.
   470  func (self *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
   471  	self.mu.RLock()
   472  	defer self.mu.RUnlock()
   473  
   474  	// Retrieve all the pending transactions and sort by account and by nonce
   475  	pending := make(map[common.Address]types.Transactions)
   476  	for _, tx := range self.pending {
   477  		account, _ := types.Sender(self.signer, tx)
   478  		pending[account] = append(pending[account], tx)
   479  	}
   480  	// There are no queued transactions in a light pool, just return an empty map
   481  	queued := make(map[common.Address]types.Transactions)
   482  	return pending, queued
   483  }
   484  
   485  // RemoveTransactions removes all given transactions from the pool.
   486  func (self *TxPool) RemoveTransactions(txs types.Transactions) {
   487  	self.mu.Lock()
   488  	defer self.mu.Unlock()
   489  	var hashes []common.Hash
   490  	for _, tx := range txs {
   491  		//self.RemoveTx(tx.Hash())
   492  		hash := tx.Hash()
   493  		delete(self.pending, hash)
   494  		self.chainDb.Delete(hash[:])
   495  		hashes = append(hashes, hash)
   496  	}
   497  	self.relay.Discard(hashes)
   498  }
   499  
   500  // RemoveTx removes the transaction with the given hash from the pool.
   501  func (pool *TxPool) RemoveTx(hash common.Hash) {
   502  	pool.mu.Lock()
   503  	defer pool.mu.Unlock()
   504  	// delete from pending pool
   505  	delete(pool.pending, hash)
   506  	pool.chainDb.Delete(hash[:])
   507  	pool.relay.Discard([]common.Hash{hash})
   508  }