txpool.go 17 KB

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