txpool.go 17 KB

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