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