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