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.

90 lines
2.1 KiB

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. state *state.State
  17. txs []Tx
  18. }
  19. func NewMempool(state *state.State) *Mempool {
  20. return &Mempool{
  21. state: state,
  22. }
  23. }
  24. // Apply tx to the state and remember it.
  25. func (mem *Mempool) AddTx(tx Tx) (err error) {
  26. mem.mtx.Lock()
  27. defer mem.mtx.Unlock()
  28. err = mem.state.ExecTx(tx)
  29. if err != nil {
  30. return err
  31. } else {
  32. mem.txs = append(mem.txs, tx)
  33. return nil
  34. }
  35. }
  36. func (mem *Mempool) GetProposalTxs() ([]Tx, *state.State) {
  37. mem.mtx.Lock()
  38. defer mem.mtx.Unlock()
  39. return mem.txs, mem.state
  40. }
  41. // "block" is the new block being committed.
  42. // "state" is the result of state.AppendBlock("block").
  43. // Txs that are present in "block" are discarded from mempool.
  44. // Txs that have become invalid in the new "state" are also discarded.
  45. func (mem *Mempool) ResetForBlockAndState(block *Block, state *state.State) {
  46. mem.mtx.Lock()
  47. defer mem.mtx.Unlock()
  48. mem.state = state.Copy()
  49. // First, create a lookup map of txns in new block.
  50. blockTxsMap := make(map[string]struct{})
  51. for _, tx := range block.Data.Txs {
  52. txHash := BinaryHash(tx)
  53. blockTxsMap[string(txHash)] = struct{}{}
  54. }
  55. // Next, filter all txs from mem.txs that are in blockTxsMap
  56. txs := []Tx{}
  57. for _, tx := range mem.txs {
  58. txHash := BinaryHash(tx)
  59. if _, ok := blockTxsMap[string(txHash)]; ok {
  60. continue
  61. } else {
  62. txs = append(txs, tx)
  63. }
  64. }
  65. // Next, filter all txs that aren't valid given new state.
  66. validTxs := []Tx{}
  67. for _, tx := range txs {
  68. err := mem.state.ExecTx(tx)
  69. if err != nil {
  70. validTxs = append(validTxs, tx)
  71. } else {
  72. // tx is no longer valid.
  73. }
  74. }
  75. // We're done!
  76. mem.txs = validTxs
  77. }