You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.3 KiB

10 years ago
10 years ago
  1. /*
  2. Mempool receives new transactions and applies them to the latest committed state.
  3. If the transaction is acceptable, then it broadcasts the tx to peers.
  4. When this node happens to be the next proposer, it simply takes the recently
  5. modified state (and the associated transactions) and use that as the proposal.
  6. */
  7. package mempool
  8. import (
  9. "sync"
  10. . "github.com/tendermint/tendermint/binary"
  11. . "github.com/tendermint/tendermint/blocks"
  12. . "github.com/tendermint/tendermint/state"
  13. )
  14. type Mempool struct {
  15. mtx sync.Mutex
  16. lastBlock *Block
  17. state *State
  18. txs []Tx
  19. }
  20. func NewMempool(lastBlock *Block, state *State) *Mempool {
  21. return &Mempool{
  22. lastBlock: lastBlock,
  23. state: state,
  24. }
  25. }
  26. // Apply tx to the state and remember it.
  27. func (mem *Mempool) AddTx(tx Tx) (err error) {
  28. mem.mtx.Lock()
  29. defer mem.mtx.Unlock()
  30. err = mem.state.CommitTx(tx)
  31. if err != nil {
  32. return err
  33. } else {
  34. mem.txs = append(mem.txs, tx)
  35. return nil
  36. }
  37. }
  38. // Returns a new block from the current state and associated transactions.
  39. // The block's Validation is empty, and some parts of the header too.
  40. func (mem *Mempool) MakeProposalBlock() (*Block, *State) {
  41. mem.mtx.Lock()
  42. defer mem.mtx.Unlock()
  43. nextBlock := mem.lastBlock.MakeNextBlock()
  44. nextBlock.Data.Txs = mem.txs
  45. return nextBlock, mem.state
  46. }
  47. // Txs that are present in block are discarded from mempool.
  48. // Txs that have become invalid in the new state are also discarded.
  49. func (mem *Mempool) ResetForBlockAndState(block *Block, state *State) {
  50. mem.mtx.Lock()
  51. defer mem.mtx.Unlock()
  52. mem.lastBlock = block
  53. mem.state = state.Copy()
  54. // First, create a lookup map of txns in new block.
  55. blockTxsMap := make(map[string]struct{})
  56. for _, tx := range block.Data.Txs {
  57. txHash := BinaryHash(tx)
  58. blockTxsMap[string(txHash)] = struct{}{}
  59. }
  60. // Next, filter all txs from mem.txs that are in blockTxsMap
  61. txs := []Tx{}
  62. for _, tx := range mem.txs {
  63. txHash := BinaryHash(tx)
  64. if _, ok := blockTxsMap[string(txHash)]; ok {
  65. continue
  66. } else {
  67. txs = append(txs, tx)
  68. }
  69. }
  70. // Next, filter all txs that aren't valid given new state.
  71. validTxs := []Tx{}
  72. for _, tx := range txs {
  73. err := mem.state.CommitTx(tx)
  74. if err != nil {
  75. validTxs = append(validTxs, tx)
  76. } else {
  77. // tx is no longer valid.
  78. }
  79. }
  80. // We're done!
  81. mem.txs = validTxs
  82. }