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.

396 lines
12 KiB

8 years ago
8 years ago
8 years ago
  1. package mempool
  2. import (
  3. "crypto/md5"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. "github.com/tendermint/tendermint/abci/example/counter"
  15. "github.com/tendermint/tendermint/abci/example/kvstore"
  16. abci "github.com/tendermint/tendermint/abci/types"
  17. cfg "github.com/tendermint/tendermint/config"
  18. "github.com/tendermint/tendermint/libs/log"
  19. "github.com/tendermint/tendermint/proxy"
  20. "github.com/tendermint/tendermint/types"
  21. )
  22. func newMempoolWithApp(cc proxy.ClientCreator) *Mempool {
  23. config := cfg.ResetTestRoot("mempool_test")
  24. appConnMem, _ := cc.NewABCIClient()
  25. appConnMem.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "mempool"))
  26. err := appConnMem.Start()
  27. if err != nil {
  28. panic(err)
  29. }
  30. mempool := NewMempool(config.Mempool, appConnMem, 0)
  31. mempool.SetLogger(log.TestingLogger())
  32. return mempool
  33. }
  34. func ensureNoFire(t *testing.T, ch <-chan struct{}, timeoutMS int) {
  35. timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond)
  36. select {
  37. case <-ch:
  38. t.Fatal("Expected not to fire")
  39. case <-timer.C:
  40. }
  41. }
  42. func ensureFire(t *testing.T, ch <-chan struct{}, timeoutMS int) {
  43. timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond)
  44. select {
  45. case <-ch:
  46. case <-timer.C:
  47. t.Fatal("Expected to fire")
  48. }
  49. }
  50. func checkTxs(t *testing.T, mempool *Mempool, count int) types.Txs {
  51. txs := make(types.Txs, count)
  52. for i := 0; i < count; i++ {
  53. txBytes := make([]byte, 20)
  54. txs[i] = txBytes
  55. _, err := rand.Read(txBytes)
  56. if err != nil {
  57. t.Error(err)
  58. }
  59. if err := mempool.CheckTx(txBytes, nil); err != nil {
  60. // Skip invalid txs.
  61. // TestMempoolFilters will fail otherwise. It asserts a number of txs
  62. // returned.
  63. if IsPreCheckError(err) {
  64. continue
  65. }
  66. t.Fatalf("CheckTx failed: %v while checking #%d tx", err, i)
  67. }
  68. }
  69. return txs
  70. }
  71. func TestReapMaxBytesMaxGas(t *testing.T) {
  72. app := kvstore.NewKVStoreApplication()
  73. cc := proxy.NewLocalClientCreator(app)
  74. mempool := newMempoolWithApp(cc)
  75. // Ensure gas calculation behaves as expected
  76. checkTxs(t, mempool, 1)
  77. tx0 := mempool.TxsFront().Value.(*mempoolTx)
  78. // assert that kv store has gas wanted = 1.
  79. require.Equal(t, app.CheckTx(tx0.tx).GasWanted, int64(1), "KVStore had a gas value neq to 1")
  80. require.Equal(t, tx0.gasWanted, int64(1), "transactions gas was set incorrectly")
  81. // ensure each tx is 20 bytes long
  82. require.Equal(t, len(tx0.tx), 20, "Tx is longer than 20 bytes")
  83. mempool.Flush()
  84. // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs.
  85. // each tx has 20 bytes + amino overhead = 21 bytes, 1 gas
  86. tests := []struct {
  87. numTxsToCreate int
  88. maxBytes int64
  89. maxGas int64
  90. expectedNumTxs int
  91. }{
  92. {20, -1, -1, 20},
  93. {20, -1, 0, 0},
  94. {20, -1, 10, 10},
  95. {20, -1, 30, 20},
  96. {20, 0, -1, 0},
  97. {20, 0, 10, 0},
  98. {20, 10, 10, 0},
  99. {20, 22, 10, 1},
  100. {20, 220, -1, 10},
  101. {20, 220, 5, 5},
  102. {20, 220, 10, 10},
  103. {20, 220, 15, 10},
  104. {20, 20000, -1, 20},
  105. {20, 20000, 5, 5},
  106. {20, 20000, 30, 20},
  107. }
  108. for tcIndex, tt := range tests {
  109. checkTxs(t, mempool, tt.numTxsToCreate)
  110. got := mempool.ReapMaxBytesMaxGas(tt.maxBytes, tt.maxGas)
  111. assert.Equal(t, tt.expectedNumTxs, len(got), "Got %d txs, expected %d, tc #%d",
  112. len(got), tt.expectedNumTxs, tcIndex)
  113. mempool.Flush()
  114. }
  115. }
  116. func TestMempoolFilters(t *testing.T) {
  117. app := kvstore.NewKVStoreApplication()
  118. cc := proxy.NewLocalClientCreator(app)
  119. mempool := newMempoolWithApp(cc)
  120. emptyTxArr := []types.Tx{[]byte{}}
  121. nopPreFilter := func(tx types.Tx) error { return nil }
  122. nopPostFilter := func(tx types.Tx, res *abci.ResponseCheckTx) error { return nil }
  123. // each table driven test creates numTxsToCreate txs with checkTx, and at the end clears all remaining txs.
  124. // each tx has 20 bytes + amino overhead = 21 bytes, 1 gas
  125. tests := []struct {
  126. numTxsToCreate int
  127. preFilter PreCheckFunc
  128. postFilter PostCheckFunc
  129. expectedNumTxs int
  130. }{
  131. {10, nopPreFilter, nopPostFilter, 10},
  132. {10, PreCheckAminoMaxBytes(10), nopPostFilter, 0},
  133. {10, PreCheckAminoMaxBytes(20), nopPostFilter, 0},
  134. {10, PreCheckAminoMaxBytes(22), nopPostFilter, 10},
  135. {10, nopPreFilter, PostCheckMaxGas(-1), 10},
  136. {10, nopPreFilter, PostCheckMaxGas(0), 0},
  137. {10, nopPreFilter, PostCheckMaxGas(1), 10},
  138. {10, nopPreFilter, PostCheckMaxGas(3000), 10},
  139. {10, PreCheckAminoMaxBytes(10), PostCheckMaxGas(20), 0},
  140. {10, PreCheckAminoMaxBytes(30), PostCheckMaxGas(20), 10},
  141. {10, PreCheckAminoMaxBytes(22), PostCheckMaxGas(1), 10},
  142. {10, PreCheckAminoMaxBytes(22), PostCheckMaxGas(0), 0},
  143. }
  144. for tcIndex, tt := range tests {
  145. mempool.Update(1, emptyTxArr, tt.preFilter, tt.postFilter)
  146. checkTxs(t, mempool, tt.numTxsToCreate)
  147. require.Equal(t, tt.expectedNumTxs, mempool.Size(), "mempool had the incorrect size, on test case %d", tcIndex)
  148. mempool.Flush()
  149. }
  150. }
  151. func TestTxsAvailable(t *testing.T) {
  152. app := kvstore.NewKVStoreApplication()
  153. cc := proxy.NewLocalClientCreator(app)
  154. mempool := newMempoolWithApp(cc)
  155. mempool.EnableTxsAvailable()
  156. timeoutMS := 500
  157. // with no txs, it shouldnt fire
  158. ensureNoFire(t, mempool.TxsAvailable(), timeoutMS)
  159. // send a bunch of txs, it should only fire once
  160. txs := checkTxs(t, mempool, 100)
  161. ensureFire(t, mempool.TxsAvailable(), timeoutMS)
  162. ensureNoFire(t, mempool.TxsAvailable(), timeoutMS)
  163. // call update with half the txs.
  164. // it should fire once now for the new height
  165. // since there are still txs left
  166. committedTxs, txs := txs[:50], txs[50:]
  167. if err := mempool.Update(1, committedTxs, nil, nil); err != nil {
  168. t.Error(err)
  169. }
  170. ensureFire(t, mempool.TxsAvailable(), timeoutMS)
  171. ensureNoFire(t, mempool.TxsAvailable(), timeoutMS)
  172. // send a bunch more txs. we already fired for this height so it shouldnt fire again
  173. moreTxs := checkTxs(t, mempool, 50)
  174. ensureNoFire(t, mempool.TxsAvailable(), timeoutMS)
  175. // now call update with all the txs. it should not fire as there are no txs left
  176. committedTxs = append(txs, moreTxs...)
  177. if err := mempool.Update(2, committedTxs, nil, nil); err != nil {
  178. t.Error(err)
  179. }
  180. ensureNoFire(t, mempool.TxsAvailable(), timeoutMS)
  181. // send a bunch more txs, it should only fire once
  182. checkTxs(t, mempool, 100)
  183. ensureFire(t, mempool.TxsAvailable(), timeoutMS)
  184. ensureNoFire(t, mempool.TxsAvailable(), timeoutMS)
  185. }
  186. func TestSerialReap(t *testing.T) {
  187. app := counter.NewCounterApplication(true)
  188. app.SetOption(abci.RequestSetOption{Key: "serial", Value: "on"})
  189. cc := proxy.NewLocalClientCreator(app)
  190. mempool := newMempoolWithApp(cc)
  191. appConnCon, _ := cc.NewABCIClient()
  192. appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus"))
  193. err := appConnCon.Start()
  194. require.Nil(t, err)
  195. cacheMap := make(map[string]struct{})
  196. deliverTxsRange := func(start, end int) {
  197. // Deliver some txs.
  198. for i := start; i < end; i++ {
  199. // This will succeed
  200. txBytes := make([]byte, 8)
  201. binary.BigEndian.PutUint64(txBytes, uint64(i))
  202. err := mempool.CheckTx(txBytes, nil)
  203. _, cached := cacheMap[string(txBytes)]
  204. if cached {
  205. require.NotNil(t, err, "expected error for cached tx")
  206. } else {
  207. require.Nil(t, err, "expected no err for uncached tx")
  208. }
  209. cacheMap[string(txBytes)] = struct{}{}
  210. // Duplicates are cached and should return error
  211. err = mempool.CheckTx(txBytes, nil)
  212. require.NotNil(t, err, "Expected error after CheckTx on duplicated tx")
  213. }
  214. }
  215. reapCheck := func(exp int) {
  216. txs := mempool.ReapMaxBytesMaxGas(-1, -1)
  217. require.Equal(t, len(txs), exp, fmt.Sprintf("Expected to reap %v txs but got %v", exp, len(txs)))
  218. }
  219. updateRange := func(start, end int) {
  220. txs := make([]types.Tx, 0)
  221. for i := start; i < end; i++ {
  222. txBytes := make([]byte, 8)
  223. binary.BigEndian.PutUint64(txBytes, uint64(i))
  224. txs = append(txs, txBytes)
  225. }
  226. if err := mempool.Update(0, txs, nil, nil); err != nil {
  227. t.Error(err)
  228. }
  229. }
  230. commitRange := func(start, end int) {
  231. // Deliver some txs.
  232. for i := start; i < end; i++ {
  233. txBytes := make([]byte, 8)
  234. binary.BigEndian.PutUint64(txBytes, uint64(i))
  235. res, err := appConnCon.DeliverTxSync(txBytes)
  236. if err != nil {
  237. t.Errorf("Client error committing tx: %v", err)
  238. }
  239. if res.IsErr() {
  240. t.Errorf("Error committing tx. Code:%v result:%X log:%v",
  241. res.Code, res.Data, res.Log)
  242. }
  243. }
  244. res, err := appConnCon.CommitSync()
  245. if err != nil {
  246. t.Errorf("Client error committing: %v", err)
  247. }
  248. if len(res.Data) != 8 {
  249. t.Errorf("Error committing. Hash:%X", res.Data)
  250. }
  251. }
  252. //----------------------------------------
  253. // Deliver some txs.
  254. deliverTxsRange(0, 100)
  255. // Reap the txs.
  256. reapCheck(100)
  257. // Reap again. We should get the same amount
  258. reapCheck(100)
  259. // Deliver 0 to 999, we should reap 900 new txs
  260. // because 100 were already counted.
  261. deliverTxsRange(0, 1000)
  262. // Reap the txs.
  263. reapCheck(1000)
  264. // Reap again. We should get the same amount
  265. reapCheck(1000)
  266. // Commit from the conensus AppConn
  267. commitRange(0, 500)
  268. updateRange(0, 500)
  269. // We should have 500 left.
  270. reapCheck(500)
  271. // Deliver 100 invalid txs and 100 valid txs
  272. deliverTxsRange(900, 1100)
  273. // We should have 600 now.
  274. reapCheck(600)
  275. }
  276. func TestCacheRemove(t *testing.T) {
  277. cache := newMapTxCache(100)
  278. numTxs := 10
  279. txs := make([][]byte, numTxs)
  280. for i := 0; i < numTxs; i++ {
  281. // probability of collision is 2**-256
  282. txBytes := make([]byte, 32)
  283. rand.Read(txBytes)
  284. txs[i] = txBytes
  285. cache.Push(txBytes)
  286. // make sure its added to both the linked list and the map
  287. require.Equal(t, i+1, len(cache.map_))
  288. require.Equal(t, i+1, cache.list.Len())
  289. }
  290. for i := 0; i < numTxs; i++ {
  291. cache.Remove(txs[i])
  292. // make sure its removed from both the map and the linked list
  293. require.Equal(t, numTxs-(i+1), len(cache.map_))
  294. require.Equal(t, numTxs-(i+1), cache.list.Len())
  295. }
  296. }
  297. func TestMempoolCloseWAL(t *testing.T) {
  298. // 1. Create the temporary directory for mempool and WAL testing.
  299. rootDir, err := ioutil.TempDir("", "mempool-test")
  300. require.Nil(t, err, "expecting successful tmpdir creation")
  301. defer os.RemoveAll(rootDir)
  302. // 2. Ensure that it doesn't contain any elements -- Sanity check
  303. m1, err := filepath.Glob(filepath.Join(rootDir, "*"))
  304. require.Nil(t, err, "successful globbing expected")
  305. require.Equal(t, 0, len(m1), "no matches yet")
  306. // 3. Create the mempool
  307. wcfg := cfg.DefaultMempoolConfig()
  308. wcfg.RootDir = rootDir
  309. app := kvstore.NewKVStoreApplication()
  310. cc := proxy.NewLocalClientCreator(app)
  311. appConnMem, _ := cc.NewABCIClient()
  312. mempool := NewMempool(wcfg, appConnMem, 10)
  313. mempool.InitWAL()
  314. // 4. Ensure that the directory contains the WAL file
  315. m2, err := filepath.Glob(filepath.Join(rootDir, "*"))
  316. require.Nil(t, err, "successful globbing expected")
  317. require.Equal(t, 1, len(m2), "expecting the wal match in")
  318. // 5. Write some contents to the WAL
  319. mempool.CheckTx(types.Tx([]byte("foo")), nil)
  320. walFilepath := mempool.wal.Path
  321. sum1 := checksumFile(walFilepath, t)
  322. // 6. Sanity check to ensure that the written TX matches the expectation.
  323. require.Equal(t, sum1, checksumIt([]byte("foo\n")), "foo with a newline should be written")
  324. // 7. Invoke CloseWAL() and ensure it discards the
  325. // WAL thus any other write won't go through.
  326. mempool.CloseWAL()
  327. mempool.CheckTx(types.Tx([]byte("bar")), nil)
  328. sum2 := checksumFile(walFilepath, t)
  329. require.Equal(t, sum1, sum2, "expected no change to the WAL after invoking CloseWAL() since it was discarded")
  330. // 8. Sanity check to ensure that the WAL file still exists
  331. m3, err := filepath.Glob(filepath.Join(rootDir, "*"))
  332. require.Nil(t, err, "successful globbing expected")
  333. require.Equal(t, 1, len(m3), "expecting the wal match in")
  334. }
  335. func checksumIt(data []byte) string {
  336. h := md5.New()
  337. h.Write(data)
  338. return fmt.Sprintf("%x", h.Sum(nil))
  339. }
  340. func checksumFile(p string, t *testing.T) string {
  341. data, err := ioutil.ReadFile(p)
  342. require.Nil(t, err, "expecting successful read of %q", p)
  343. return checksumIt(data)
  344. }