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