txpool.go 17 KB

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