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. "github.com/ethereum/go-ethereum/rlp"
  33. )
  34. const (
  35. // chainHeadChanSize is the size of channel listening to ChainHeadEvent.
  36. chainHeadChanSize = 10
  37. )
  38. // txPermanent is the number of mined blocks after a mined transaction is
  39. // considered permanent and no rollback is expected
  40. var txPermanent = uint64(500)
  41. // TxPool implements the transaction pool for light clients, which keeps track
  42. // of the status of locally created transactions, detecting if they are included
  43. // in a block (mined) or rolled back. There are no queued transactions since we
  44. // always receive all locally signed transactions in the same order as they are
  45. // created.
  46. type TxPool struct {
  47. config *params.ChainConfig
  48. signer types.Signer
  49. quit chan bool
  50. txFeed event.Feed
  51. scope event.SubscriptionScope
  52. chainHeadCh chan core.ChainHeadEvent
  53. chainHeadSub event.Subscription
  54. mu sync.RWMutex
  55. chain *LightChain
  56. odr OdrBackend
  57. chainDb ethdb.Database
  58. relay TxRelayBackend
  59. head common.Hash
  60. nonce map[common.Address]uint64 // "pending" nonce
  61. pending map[common.Hash]*types.Transaction // pending transactions by tx hash
  62. mined map[common.Hash][]*types.Transaction // mined transactions by block hash
  63. clearIdx uint64 // earliest block nr that can contain mined tx info
  64. istanbul bool // Fork indicator whether we are in the istanbul 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.NewEIP155Signer(config.ChainID),
  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. }
  290. // Stop stops the light transaction pool
  291. func (pool *TxPool) Stop() {
  292. // Unsubscribe all subscriptions registered from txpool
  293. pool.scope.Close()
  294. // Unsubscribe subscriptions registered from blockchain
  295. pool.chainHeadSub.Unsubscribe()
  296. close(pool.quit)
  297. log.Info("Transaction pool stopped")
  298. }
  299. // SubscribeNewTxsEvent registers a subscription of core.NewTxsEvent and
  300. // starts sending event to the given channel.
  301. func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
  302. return pool.scope.Track(pool.txFeed.Subscribe(ch))
  303. }
  304. // Stats returns the number of currently pending (locally created) transactions
  305. func (pool *TxPool) Stats() (pending int) {
  306. pool.mu.RLock()
  307. defer pool.mu.RUnlock()
  308. pending = len(pool.pending)
  309. return
  310. }
  311. // validateTx checks whether a transaction is valid according to the consensus rules.
  312. func (pool *TxPool) validateTx(ctx context.Context, tx *types.Transaction) error {
  313. // Validate sender
  314. var (
  315. from common.Address
  316. err error
  317. )
  318. // Validate the transaction sender and it's sig. Throw
  319. // if the from fields is invalid.
  320. if from, err = types.Sender(pool.signer, tx); err != nil {
  321. return core.ErrInvalidSender
  322. }
  323. // Last but not least check for nonce errors
  324. currentState := pool.currentState(ctx)
  325. if n := currentState.GetNonce(from); n > tx.Nonce() {
  326. return core.ErrNonceTooLow
  327. }
  328. // Check the transaction doesn't exceed the current
  329. // block limit gas.
  330. header := pool.chain.GetHeaderByHash(pool.head)
  331. if header.GasLimit < tx.Gas() {
  332. return core.ErrGasLimit
  333. }
  334. // Transactions can't be negative. This may never happen
  335. // using RLP decoded transactions but may occur if you create
  336. // a transaction using the RPC for example.
  337. if tx.Value().Sign() < 0 {
  338. return core.ErrNegativeValue
  339. }
  340. // Transactor should have enough funds to cover the costs
  341. // cost == V + GP * GL
  342. if b := currentState.GetBalance(from); b.Cmp(tx.Cost()) < 0 {
  343. return core.ErrInsufficientFunds
  344. }
  345. // Should supply enough intrinsic gas
  346. gas, err := core.IntrinsicGas(tx.Data(), tx.To() == nil, true, pool.istanbul)
  347. if err != nil {
  348. return err
  349. }
  350. if tx.Gas() < gas {
  351. return core.ErrIntrinsicGas
  352. }
  353. return currentState.Error()
  354. }
  355. // add validates a new transaction and sets its state pending if processable.
  356. // It also updates the locally stored nonce if necessary.
  357. func (pool *TxPool) add(ctx context.Context, tx *types.Transaction) error {
  358. hash := tx.Hash()
  359. if pool.pending[hash] != nil {
  360. return fmt.Errorf("Known transaction (%x)", hash[:4])
  361. }
  362. err := pool.validateTx(ctx, tx)
  363. if err != nil {
  364. return err
  365. }
  366. if _, ok := pool.pending[hash]; !ok {
  367. pool.pending[hash] = tx
  368. nonce := tx.Nonce() + 1
  369. addr, _ := types.Sender(pool.signer, tx)
  370. if nonce > pool.nonce[addr] {
  371. pool.nonce[addr] = nonce
  372. }
  373. // Notify the subscribers. This event is posted in a goroutine
  374. // because it's possible that somewhere during the post "Remove transaction"
  375. // gets called which will then wait for the global tx pool lock and deadlock.
  376. go pool.txFeed.Send(core.NewTxsEvent{Txs: types.Transactions{tx}})
  377. }
  378. // Print a log message if low enough level is set
  379. 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())
  380. return nil
  381. }
  382. // Add adds a transaction to the pool if valid and passes it to the tx relay
  383. // backend
  384. func (pool *TxPool) Add(ctx context.Context, tx *types.Transaction) error {
  385. pool.mu.Lock()
  386. defer pool.mu.Unlock()
  387. data, err := rlp.EncodeToBytes(tx)
  388. if err != nil {
  389. return err
  390. }
  391. if err := pool.add(ctx, tx); err != nil {
  392. return err
  393. }
  394. //fmt.Println("Send", tx.Hash())
  395. pool.relay.Send(types.Transactions{tx})
  396. pool.chainDb.Put(tx.Hash().Bytes(), data)
  397. return nil
  398. }
  399. // AddTransactions adds all valid transactions to the pool and passes them to
  400. // the tx relay backend
  401. func (pool *TxPool) AddBatch(ctx context.Context, txs []*types.Transaction) {
  402. pool.mu.Lock()
  403. defer pool.mu.Unlock()
  404. var sendTx types.Transactions
  405. for _, tx := range txs {
  406. if err := pool.add(ctx, tx); err == nil {
  407. sendTx = append(sendTx, tx)
  408. }
  409. }
  410. if len(sendTx) > 0 {
  411. pool.relay.Send(sendTx)
  412. }
  413. }
  414. // GetTransaction returns a transaction if it is contained in the pool
  415. // and nil otherwise.
  416. func (pool *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
  417. // check the txs first
  418. if tx, ok := pool.pending[hash]; ok {
  419. return tx
  420. }
  421. return nil
  422. }
  423. // GetTransactions returns all currently processable transactions.
  424. // The returned slice may be modified by the caller.
  425. func (pool *TxPool) GetTransactions() (txs types.Transactions, err error) {
  426. pool.mu.RLock()
  427. defer pool.mu.RUnlock()
  428. txs = make(types.Transactions, len(pool.pending))
  429. i := 0
  430. for _, tx := range pool.pending {
  431. txs[i] = tx
  432. i++
  433. }
  434. return txs, nil
  435. }
  436. // Content retrieves the data content of the transaction pool, returning all the
  437. // pending as well as queued transactions, grouped by account and nonce.
  438. func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
  439. pool.mu.RLock()
  440. defer pool.mu.RUnlock()
  441. // Retrieve all the pending transactions and sort by account and by nonce
  442. pending := make(map[common.Address]types.Transactions)
  443. for _, tx := range pool.pending {
  444. account, _ := types.Sender(pool.signer, tx)
  445. pending[account] = append(pending[account], tx)
  446. }
  447. // There are no queued transactions in a light pool, just return an empty map
  448. queued := make(map[common.Address]types.Transactions)
  449. return pending, queued
  450. }
  451. // RemoveTransactions removes all given transactions from the pool.
  452. func (pool *TxPool) RemoveTransactions(txs types.Transactions) {
  453. pool.mu.Lock()
  454. defer pool.mu.Unlock()
  455. var hashes []common.Hash
  456. batch := pool.chainDb.NewBatch()
  457. for _, tx := range txs {
  458. hash := tx.Hash()
  459. delete(pool.pending, hash)
  460. batch.Delete(hash.Bytes())
  461. hashes = append(hashes, hash)
  462. }
  463. batch.Write()
  464. pool.relay.Discard(hashes)
  465. }
  466. // RemoveTx removes the transaction with the given hash from the pool.
  467. func (pool *TxPool) RemoveTx(hash common.Hash) {
  468. pool.mu.Lock()
  469. defer pool.mu.Unlock()
  470. // delete from pending pool
  471. delete(pool.pending, hash)
  472. pool.chainDb.Delete(hash[:])
  473. pool.relay.Discard([]common.Hash{hash})
  474. }