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.

838 lines
24 KiB

  1. package statesync
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "sync"
  7. "testing"
  8. "time"
  9. "github.com/fortytw2/leaktest"
  10. "github.com/stretchr/testify/mock"
  11. "github.com/stretchr/testify/require"
  12. dbm "github.com/tendermint/tm-db"
  13. abci "github.com/tendermint/tendermint/abci/types"
  14. "github.com/tendermint/tendermint/config"
  15. "github.com/tendermint/tendermint/internal/p2p"
  16. "github.com/tendermint/tendermint/internal/proxy"
  17. proxymocks "github.com/tendermint/tendermint/internal/proxy/mocks"
  18. "github.com/tendermint/tendermint/internal/statesync/mocks"
  19. "github.com/tendermint/tendermint/internal/test/factory"
  20. "github.com/tendermint/tendermint/libs/log"
  21. "github.com/tendermint/tendermint/light/provider"
  22. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  23. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  24. smmocks "github.com/tendermint/tendermint/state/mocks"
  25. "github.com/tendermint/tendermint/store"
  26. "github.com/tendermint/tendermint/types"
  27. )
  28. var (
  29. m = PrometheusMetrics(config.TestConfig().Instrumentation.Namespace)
  30. )
  31. type reactorTestSuite struct {
  32. reactor *Reactor
  33. syncer *syncer
  34. conn *proxymocks.AppConnSnapshot
  35. connQuery *proxymocks.AppConnQuery
  36. stateProvider *mocks.StateProvider
  37. snapshotChannel *p2p.Channel
  38. snapshotInCh chan p2p.Envelope
  39. snapshotOutCh chan p2p.Envelope
  40. snapshotPeerErrCh chan p2p.PeerError
  41. chunkChannel *p2p.Channel
  42. chunkInCh chan p2p.Envelope
  43. chunkOutCh chan p2p.Envelope
  44. chunkPeerErrCh chan p2p.PeerError
  45. blockChannel *p2p.Channel
  46. blockInCh chan p2p.Envelope
  47. blockOutCh chan p2p.Envelope
  48. blockPeerErrCh chan p2p.PeerError
  49. paramsChannel *p2p.Channel
  50. paramsInCh chan p2p.Envelope
  51. paramsOutCh chan p2p.Envelope
  52. paramsPeerErrCh chan p2p.PeerError
  53. peerUpdateCh chan p2p.PeerUpdate
  54. peerUpdates *p2p.PeerUpdates
  55. stateStore *smmocks.Store
  56. blockStore *store.BlockStore
  57. }
  58. func setup(
  59. t *testing.T,
  60. conn *proxymocks.AppConnSnapshot,
  61. connQuery *proxymocks.AppConnQuery,
  62. stateProvider *mocks.StateProvider,
  63. chBuf uint,
  64. ) *reactorTestSuite {
  65. t.Helper()
  66. if conn == nil {
  67. conn = &proxymocks.AppConnSnapshot{}
  68. }
  69. if connQuery == nil {
  70. connQuery = &proxymocks.AppConnQuery{}
  71. }
  72. if stateProvider == nil {
  73. stateProvider = &mocks.StateProvider{}
  74. }
  75. rts := &reactorTestSuite{
  76. snapshotInCh: make(chan p2p.Envelope, chBuf),
  77. snapshotOutCh: make(chan p2p.Envelope, chBuf),
  78. snapshotPeerErrCh: make(chan p2p.PeerError, chBuf),
  79. chunkInCh: make(chan p2p.Envelope, chBuf),
  80. chunkOutCh: make(chan p2p.Envelope, chBuf),
  81. chunkPeerErrCh: make(chan p2p.PeerError, chBuf),
  82. blockInCh: make(chan p2p.Envelope, chBuf),
  83. blockOutCh: make(chan p2p.Envelope, chBuf),
  84. blockPeerErrCh: make(chan p2p.PeerError, chBuf),
  85. paramsInCh: make(chan p2p.Envelope, chBuf),
  86. paramsOutCh: make(chan p2p.Envelope, chBuf),
  87. paramsPeerErrCh: make(chan p2p.PeerError, chBuf),
  88. conn: conn,
  89. connQuery: connQuery,
  90. stateProvider: stateProvider,
  91. }
  92. rts.peerUpdateCh = make(chan p2p.PeerUpdate, chBuf)
  93. rts.peerUpdates = p2p.NewPeerUpdates(rts.peerUpdateCh, int(chBuf))
  94. rts.snapshotChannel = p2p.NewChannel(
  95. SnapshotChannel,
  96. new(ssproto.Message),
  97. rts.snapshotInCh,
  98. rts.snapshotOutCh,
  99. rts.snapshotPeerErrCh,
  100. )
  101. rts.chunkChannel = p2p.NewChannel(
  102. ChunkChannel,
  103. new(ssproto.Message),
  104. rts.chunkInCh,
  105. rts.chunkOutCh,
  106. rts.chunkPeerErrCh,
  107. )
  108. rts.blockChannel = p2p.NewChannel(
  109. LightBlockChannel,
  110. new(ssproto.Message),
  111. rts.blockInCh,
  112. rts.blockOutCh,
  113. rts.blockPeerErrCh,
  114. )
  115. rts.paramsChannel = p2p.NewChannel(
  116. ParamsChannel,
  117. new(ssproto.Message),
  118. rts.paramsInCh,
  119. rts.paramsOutCh,
  120. rts.paramsPeerErrCh,
  121. )
  122. rts.stateStore = &smmocks.Store{}
  123. rts.blockStore = store.NewBlockStore(dbm.NewMemDB())
  124. cfg := config.DefaultStateSyncConfig()
  125. rts.reactor = NewReactor(
  126. factory.DefaultTestChainID,
  127. 1,
  128. *cfg,
  129. log.TestingLogger(),
  130. conn,
  131. connQuery,
  132. rts.snapshotChannel,
  133. rts.chunkChannel,
  134. rts.blockChannel,
  135. rts.paramsChannel,
  136. rts.peerUpdates,
  137. rts.stateStore,
  138. rts.blockStore,
  139. "",
  140. m,
  141. )
  142. rts.syncer = newSyncer(
  143. *cfg,
  144. log.NewNopLogger(),
  145. conn,
  146. connQuery,
  147. stateProvider,
  148. rts.snapshotOutCh,
  149. rts.chunkOutCh,
  150. "",
  151. rts.reactor.metrics,
  152. )
  153. require.NoError(t, rts.reactor.Start())
  154. require.True(t, rts.reactor.IsRunning())
  155. t.Cleanup(func() {
  156. require.NoError(t, rts.reactor.Stop())
  157. require.False(t, rts.reactor.IsRunning())
  158. })
  159. return rts
  160. }
  161. func TestReactor_Sync(t *testing.T) {
  162. const snapshotHeight = 7
  163. rts := setup(t, nil, nil, nil, 2)
  164. chain := buildLightBlockChain(t, 1, 10, time.Now())
  165. // app accepts any snapshot
  166. rts.conn.On("OfferSnapshotSync", ctx, mock.AnythingOfType("types.RequestOfferSnapshot")).
  167. Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ACCEPT}, nil)
  168. // app accepts every chunk
  169. rts.conn.On("ApplySnapshotChunkSync", ctx, mock.AnythingOfType("types.RequestApplySnapshotChunk")).
  170. Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  171. // app query returns valid state app hash
  172. rts.connQuery.On("InfoSync", ctx, proxy.RequestInfo).Return(&abci.ResponseInfo{
  173. AppVersion: 9,
  174. LastBlockHeight: snapshotHeight,
  175. LastBlockAppHash: chain[snapshotHeight+1].AppHash,
  176. }, nil)
  177. // store accepts state and validator sets
  178. rts.stateStore.On("Bootstrap", mock.AnythingOfType("state.State")).Return(nil)
  179. rts.stateStore.On("SaveValidatorSets", mock.AnythingOfType("int64"), mock.AnythingOfType("int64"),
  180. mock.AnythingOfType("*types.ValidatorSet")).Return(nil)
  181. closeCh := make(chan struct{})
  182. defer close(closeCh)
  183. go handleLightBlockRequests(t, chain, rts.blockOutCh,
  184. rts.blockInCh, closeCh, 0)
  185. go graduallyAddPeers(rts.peerUpdateCh, closeCh, 1*time.Second)
  186. go handleSnapshotRequests(t, rts.snapshotOutCh, rts.snapshotInCh, closeCh, []snapshot{
  187. {
  188. Height: uint64(snapshotHeight),
  189. Format: 1,
  190. Chunks: 1,
  191. },
  192. })
  193. go handleChunkRequests(t, rts.chunkOutCh, rts.chunkInCh, closeCh, []byte("abc"))
  194. go handleConsensusParamsRequest(t, rts.paramsOutCh, rts.paramsInCh, closeCh)
  195. // update the config to use the p2p provider
  196. rts.reactor.cfg.UseP2P = true
  197. rts.reactor.cfg.TrustHeight = 1
  198. rts.reactor.cfg.TrustHash = fmt.Sprintf("%X", chain[1].Hash())
  199. rts.reactor.cfg.DiscoveryTime = 1 * time.Second
  200. // Run state sync
  201. _, err := rts.reactor.Sync(context.Background())
  202. require.NoError(t, err)
  203. }
  204. func TestReactor_ChunkRequest_InvalidRequest(t *testing.T) {
  205. rts := setup(t, nil, nil, nil, 2)
  206. rts.chunkInCh <- p2p.Envelope{
  207. From: types.NodeID("aa"),
  208. Message: &ssproto.SnapshotsRequest{},
  209. }
  210. response := <-rts.chunkPeerErrCh
  211. require.Error(t, response.Err)
  212. require.Empty(t, rts.chunkOutCh)
  213. require.Contains(t, response.Err.Error(), "received unknown message")
  214. require.Equal(t, types.NodeID("aa"), response.NodeID)
  215. }
  216. func TestReactor_ChunkRequest(t *testing.T) {
  217. testcases := map[string]struct {
  218. request *ssproto.ChunkRequest
  219. chunk []byte
  220. expectResponse *ssproto.ChunkResponse
  221. }{
  222. "chunk is returned": {
  223. &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1},
  224. []byte{1, 2, 3},
  225. &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{1, 2, 3}},
  226. },
  227. "empty chunk is returned, as empty": {
  228. &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1},
  229. []byte{},
  230. &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Chunk: []byte{}},
  231. },
  232. "nil (missing) chunk is returned as missing": {
  233. &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1},
  234. nil,
  235. &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true},
  236. },
  237. "invalid request": {
  238. &ssproto.ChunkRequest{Height: 1, Format: 1, Index: 1},
  239. nil,
  240. &ssproto.ChunkResponse{Height: 1, Format: 1, Index: 1, Missing: true},
  241. },
  242. }
  243. for name, tc := range testcases {
  244. tc := tc
  245. t.Run(name, func(t *testing.T) {
  246. // mock ABCI connection to return local snapshots
  247. conn := &proxymocks.AppConnSnapshot{}
  248. conn.On("LoadSnapshotChunkSync", context.Background(), abci.RequestLoadSnapshotChunk{
  249. Height: tc.request.Height,
  250. Format: tc.request.Format,
  251. Chunk: tc.request.Index,
  252. }).Return(&abci.ResponseLoadSnapshotChunk{Chunk: tc.chunk}, nil)
  253. rts := setup(t, conn, nil, nil, 2)
  254. rts.chunkInCh <- p2p.Envelope{
  255. From: types.NodeID("aa"),
  256. Message: tc.request,
  257. }
  258. response := <-rts.chunkOutCh
  259. require.Equal(t, tc.expectResponse, response.Message)
  260. require.Empty(t, rts.chunkOutCh)
  261. conn.AssertExpectations(t)
  262. })
  263. }
  264. }
  265. func TestReactor_SnapshotsRequest_InvalidRequest(t *testing.T) {
  266. rts := setup(t, nil, nil, nil, 2)
  267. rts.snapshotInCh <- p2p.Envelope{
  268. From: types.NodeID("aa"),
  269. Message: &ssproto.ChunkRequest{},
  270. }
  271. response := <-rts.snapshotPeerErrCh
  272. require.Error(t, response.Err)
  273. require.Empty(t, rts.snapshotOutCh)
  274. require.Contains(t, response.Err.Error(), "received unknown message")
  275. require.Equal(t, types.NodeID("aa"), response.NodeID)
  276. }
  277. func TestReactor_SnapshotsRequest(t *testing.T) {
  278. testcases := map[string]struct {
  279. snapshots []*abci.Snapshot
  280. expectResponses []*ssproto.SnapshotsResponse
  281. }{
  282. "no snapshots": {nil, []*ssproto.SnapshotsResponse{}},
  283. ">10 unordered snapshots": {
  284. []*abci.Snapshot{
  285. {Height: 1, Format: 2, Chunks: 7, Hash: []byte{1, 2}, Metadata: []byte{1}},
  286. {Height: 2, Format: 2, Chunks: 7, Hash: []byte{2, 2}, Metadata: []byte{2}},
  287. {Height: 3, Format: 2, Chunks: 7, Hash: []byte{3, 2}, Metadata: []byte{3}},
  288. {Height: 1, Format: 1, Chunks: 7, Hash: []byte{1, 1}, Metadata: []byte{4}},
  289. {Height: 2, Format: 1, Chunks: 7, Hash: []byte{2, 1}, Metadata: []byte{5}},
  290. {Height: 3, Format: 1, Chunks: 7, Hash: []byte{3, 1}, Metadata: []byte{6}},
  291. {Height: 1, Format: 4, Chunks: 7, Hash: []byte{1, 4}, Metadata: []byte{7}},
  292. {Height: 2, Format: 4, Chunks: 7, Hash: []byte{2, 4}, Metadata: []byte{8}},
  293. {Height: 3, Format: 4, Chunks: 7, Hash: []byte{3, 4}, Metadata: []byte{9}},
  294. {Height: 1, Format: 3, Chunks: 7, Hash: []byte{1, 3}, Metadata: []byte{10}},
  295. {Height: 2, Format: 3, Chunks: 7, Hash: []byte{2, 3}, Metadata: []byte{11}},
  296. {Height: 3, Format: 3, Chunks: 7, Hash: []byte{3, 3}, Metadata: []byte{12}},
  297. },
  298. []*ssproto.SnapshotsResponse{
  299. {Height: 3, Format: 4, Chunks: 7, Hash: []byte{3, 4}, Metadata: []byte{9}},
  300. {Height: 3, Format: 3, Chunks: 7, Hash: []byte{3, 3}, Metadata: []byte{12}},
  301. {Height: 3, Format: 2, Chunks: 7, Hash: []byte{3, 2}, Metadata: []byte{3}},
  302. {Height: 3, Format: 1, Chunks: 7, Hash: []byte{3, 1}, Metadata: []byte{6}},
  303. {Height: 2, Format: 4, Chunks: 7, Hash: []byte{2, 4}, Metadata: []byte{8}},
  304. {Height: 2, Format: 3, Chunks: 7, Hash: []byte{2, 3}, Metadata: []byte{11}},
  305. {Height: 2, Format: 2, Chunks: 7, Hash: []byte{2, 2}, Metadata: []byte{2}},
  306. {Height: 2, Format: 1, Chunks: 7, Hash: []byte{2, 1}, Metadata: []byte{5}},
  307. {Height: 1, Format: 4, Chunks: 7, Hash: []byte{1, 4}, Metadata: []byte{7}},
  308. {Height: 1, Format: 3, Chunks: 7, Hash: []byte{1, 3}, Metadata: []byte{10}},
  309. },
  310. },
  311. }
  312. for name, tc := range testcases {
  313. tc := tc
  314. t.Run(name, func(t *testing.T) {
  315. // mock ABCI connection to return local snapshots
  316. conn := &proxymocks.AppConnSnapshot{}
  317. conn.On("ListSnapshotsSync", context.Background(), abci.RequestListSnapshots{}).Return(&abci.ResponseListSnapshots{
  318. Snapshots: tc.snapshots,
  319. }, nil)
  320. rts := setup(t, conn, nil, nil, 100)
  321. rts.snapshotInCh <- p2p.Envelope{
  322. From: types.NodeID("aa"),
  323. Message: &ssproto.SnapshotsRequest{},
  324. }
  325. if len(tc.expectResponses) > 0 {
  326. retryUntil(t, func() bool { return len(rts.snapshotOutCh) == len(tc.expectResponses) }, time.Second)
  327. }
  328. responses := make([]*ssproto.SnapshotsResponse, len(tc.expectResponses))
  329. for i := 0; i < len(tc.expectResponses); i++ {
  330. e := <-rts.snapshotOutCh
  331. responses[i] = e.Message.(*ssproto.SnapshotsResponse)
  332. }
  333. require.Equal(t, tc.expectResponses, responses)
  334. require.Empty(t, rts.snapshotOutCh)
  335. })
  336. }
  337. }
  338. func TestReactor_LightBlockResponse(t *testing.T) {
  339. rts := setup(t, nil, nil, nil, 2)
  340. var height int64 = 10
  341. h := factory.MakeRandomHeader()
  342. h.Height = height
  343. blockID := factory.MakeBlockIDWithHash(h.Hash())
  344. vals, pv := factory.RandValidatorSet(1, 10)
  345. vote, err := factory.MakeVote(pv[0], h.ChainID, 0, h.Height, 0, 2,
  346. blockID, factory.DefaultTestTime)
  347. require.NoError(t, err)
  348. sh := &types.SignedHeader{
  349. Header: h,
  350. Commit: &types.Commit{
  351. Height: h.Height,
  352. BlockID: blockID,
  353. Signatures: []types.CommitSig{
  354. vote.CommitSig(),
  355. },
  356. },
  357. }
  358. lb := &types.LightBlock{
  359. SignedHeader: sh,
  360. ValidatorSet: vals,
  361. }
  362. require.NoError(t, rts.blockStore.SaveSignedHeader(sh, blockID))
  363. rts.stateStore.On("LoadValidators", height).Return(vals, nil)
  364. rts.blockInCh <- p2p.Envelope{
  365. From: types.NodeID("aa"),
  366. Message: &ssproto.LightBlockRequest{
  367. Height: 10,
  368. },
  369. }
  370. require.Empty(t, rts.blockPeerErrCh)
  371. select {
  372. case response := <-rts.blockOutCh:
  373. require.Equal(t, types.NodeID("aa"), response.To)
  374. res, ok := response.Message.(*ssproto.LightBlockResponse)
  375. require.True(t, ok)
  376. receivedLB, err := types.LightBlockFromProto(res.LightBlock)
  377. require.NoError(t, err)
  378. require.Equal(t, lb, receivedLB)
  379. case <-time.After(1 * time.Second):
  380. t.Fatal("expected light block response")
  381. }
  382. }
  383. func TestReactor_BlockProviders(t *testing.T) {
  384. rts := setup(t, nil, nil, nil, 2)
  385. rts.peerUpdateCh <- p2p.PeerUpdate{
  386. NodeID: types.NodeID("aa"),
  387. Status: p2p.PeerStatusUp,
  388. }
  389. rts.peerUpdateCh <- p2p.PeerUpdate{
  390. NodeID: types.NodeID("bb"),
  391. Status: p2p.PeerStatusUp,
  392. }
  393. closeCh := make(chan struct{})
  394. defer close(closeCh)
  395. chain := buildLightBlockChain(t, 1, 10, time.Now())
  396. go handleLightBlockRequests(t, chain, rts.blockOutCh, rts.blockInCh, closeCh, 0)
  397. peers := rts.reactor.peers.All()
  398. require.Len(t, peers, 2)
  399. providers := make([]provider.Provider, len(peers))
  400. for idx, peer := range peers {
  401. providers[idx] = NewBlockProvider(peer, factory.DefaultTestChainID, rts.reactor.dispatcher)
  402. }
  403. wg := sync.WaitGroup{}
  404. for _, p := range providers {
  405. wg.Add(1)
  406. go func(t *testing.T, p provider.Provider) {
  407. defer wg.Done()
  408. for height := 2; height < 10; height++ {
  409. lb, err := p.LightBlock(context.Background(), int64(height))
  410. require.NoError(t, err)
  411. require.NotNil(t, lb)
  412. require.Equal(t, height, int(lb.Height))
  413. }
  414. }(t, p)
  415. }
  416. ctx, cancel := context.WithCancel(context.Background())
  417. go func() { wg.Wait(); cancel() }()
  418. select {
  419. case <-time.After(time.Second):
  420. // not all of the requests to the dispatcher were responded to
  421. // within the timeout
  422. t.Fail()
  423. case <-ctx.Done():
  424. }
  425. }
  426. func TestReactor_StateProviderP2P(t *testing.T) {
  427. rts := setup(t, nil, nil, nil, 2)
  428. // make syncer non nil else test won't think we are state syncing
  429. rts.reactor.syncer = rts.syncer
  430. peerA := types.NodeID(strings.Repeat("a", 2*types.NodeIDByteLength))
  431. peerB := types.NodeID(strings.Repeat("b", 2*types.NodeIDByteLength))
  432. rts.peerUpdateCh <- p2p.PeerUpdate{
  433. NodeID: peerA,
  434. Status: p2p.PeerStatusUp,
  435. }
  436. rts.peerUpdateCh <- p2p.PeerUpdate{
  437. NodeID: peerB,
  438. Status: p2p.PeerStatusUp,
  439. }
  440. closeCh := make(chan struct{})
  441. defer close(closeCh)
  442. chain := buildLightBlockChain(t, 1, 10, time.Now())
  443. go handleLightBlockRequests(t, chain, rts.blockOutCh, rts.blockInCh, closeCh, 0)
  444. go handleConsensusParamsRequest(t, rts.paramsOutCh, rts.paramsInCh, closeCh)
  445. rts.reactor.cfg.UseP2P = true
  446. rts.reactor.cfg.TrustHeight = 1
  447. rts.reactor.cfg.TrustHash = fmt.Sprintf("%X", chain[1].Hash())
  448. ctx := context.Background()
  449. rts.reactor.mtx.Lock()
  450. err := rts.reactor.initStateProvider(ctx, factory.DefaultTestChainID, 1)
  451. rts.reactor.mtx.Unlock()
  452. require.NoError(t, err)
  453. rts.reactor.syncer.stateProvider = rts.reactor.stateProvider
  454. appHash, err := rts.reactor.stateProvider.AppHash(ctx, 5)
  455. require.NoError(t, err)
  456. require.Len(t, appHash, 32)
  457. state, err := rts.reactor.stateProvider.State(ctx, 5)
  458. require.NoError(t, err)
  459. require.Equal(t, appHash, state.AppHash)
  460. require.Equal(t, types.DefaultConsensusParams(), &state.ConsensusParams)
  461. commit, err := rts.reactor.stateProvider.Commit(ctx, 5)
  462. require.NoError(t, err)
  463. require.Equal(t, commit.BlockID, state.LastBlockID)
  464. added, err := rts.reactor.syncer.AddSnapshot(peerA, &snapshot{
  465. Height: 1, Format: 2, Chunks: 7, Hash: []byte{1, 2}, Metadata: []byte{1},
  466. })
  467. require.NoError(t, err)
  468. require.True(t, added)
  469. }
  470. func TestReactor_Backfill(t *testing.T) {
  471. // test backfill algorithm with varying failure rates [0, 10]
  472. failureRates := []int{0, 2, 9}
  473. for _, failureRate := range failureRates {
  474. failureRate := failureRate
  475. t.Run(fmt.Sprintf("failure rate: %d", failureRate), func(t *testing.T) {
  476. t.Cleanup(leaktest.CheckTimeout(t, 1*time.Minute))
  477. rts := setup(t, nil, nil, nil, 21)
  478. var (
  479. startHeight int64 = 20
  480. stopHeight int64 = 10
  481. stopTime = time.Date(2020, 1, 1, 0, 100, 0, 0, time.UTC)
  482. )
  483. peers := []string{"a", "b", "c", "d"}
  484. for _, peer := range peers {
  485. rts.peerUpdateCh <- p2p.PeerUpdate{
  486. NodeID: types.NodeID(peer),
  487. Status: p2p.PeerStatusUp,
  488. }
  489. }
  490. trackingHeight := startHeight
  491. rts.stateStore.On("SaveValidatorSets", mock.AnythingOfType("int64"), mock.AnythingOfType("int64"),
  492. mock.AnythingOfType("*types.ValidatorSet")).Return(func(lh, uh int64, vals *types.ValidatorSet) error {
  493. require.Equal(t, trackingHeight, lh)
  494. require.Equal(t, lh, uh)
  495. require.GreaterOrEqual(t, lh, stopHeight)
  496. trackingHeight--
  497. return nil
  498. })
  499. chain := buildLightBlockChain(t, stopHeight-1, startHeight+1, stopTime)
  500. closeCh := make(chan struct{})
  501. defer close(closeCh)
  502. go handleLightBlockRequests(t, chain, rts.blockOutCh,
  503. rts.blockInCh, closeCh, failureRate)
  504. err := rts.reactor.backfill(
  505. context.Background(),
  506. factory.DefaultTestChainID,
  507. startHeight,
  508. stopHeight,
  509. 1,
  510. factory.MakeBlockIDWithHash(chain[startHeight].Header.Hash()),
  511. stopTime,
  512. )
  513. if failureRate > 3 {
  514. require.Error(t, err)
  515. require.NotEqual(t, rts.reactor.backfilledBlocks, rts.reactor.backfillBlockTotal)
  516. require.Equal(t, startHeight-stopHeight+1, rts.reactor.backfillBlockTotal)
  517. } else {
  518. require.NoError(t, err)
  519. for height := startHeight; height <= stopHeight; height++ {
  520. blockMeta := rts.blockStore.LoadBlockMeta(height)
  521. require.NotNil(t, blockMeta)
  522. }
  523. require.Nil(t, rts.blockStore.LoadBlockMeta(stopHeight-1))
  524. require.Nil(t, rts.blockStore.LoadBlockMeta(startHeight+1))
  525. require.Equal(t, startHeight-stopHeight+1, rts.reactor.backfilledBlocks)
  526. require.Equal(t, startHeight-stopHeight+1, rts.reactor.backfillBlockTotal)
  527. }
  528. require.Equal(t, rts.reactor.backfilledBlocks, rts.reactor.BackFilledBlocks())
  529. require.Equal(t, rts.reactor.backfillBlockTotal, rts.reactor.BackFillBlocksTotal())
  530. })
  531. }
  532. }
  533. // retryUntil will continue to evaluate fn and will return successfully when true
  534. // or fail when the timeout is reached.
  535. func retryUntil(t *testing.T, fn func() bool, timeout time.Duration) {
  536. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  537. defer cancel()
  538. for {
  539. if fn() {
  540. return
  541. }
  542. require.NoError(t, ctx.Err())
  543. }
  544. }
  545. func handleLightBlockRequests(t *testing.T,
  546. chain map[int64]*types.LightBlock,
  547. receiving chan p2p.Envelope,
  548. sending chan p2p.Envelope,
  549. close chan struct{},
  550. failureRate int) {
  551. requests := 0
  552. errorCount := 0
  553. for {
  554. select {
  555. case envelope := <-receiving:
  556. if msg, ok := envelope.Message.(*ssproto.LightBlockRequest); ok {
  557. if requests%10 >= failureRate {
  558. lb, err := chain[int64(msg.Height)].ToProto()
  559. require.NoError(t, err)
  560. sending <- p2p.Envelope{
  561. From: envelope.To,
  562. Message: &ssproto.LightBlockResponse{
  563. LightBlock: lb,
  564. },
  565. }
  566. } else {
  567. switch errorCount % 3 {
  568. case 0: // send a different block
  569. vals, pv := factory.RandValidatorSet(3, 10)
  570. _, _, lb := mockLB(t, int64(msg.Height), factory.DefaultTestTime, factory.MakeBlockID(), vals, pv)
  571. differntLB, err := lb.ToProto()
  572. require.NoError(t, err)
  573. sending <- p2p.Envelope{
  574. From: envelope.To,
  575. Message: &ssproto.LightBlockResponse{
  576. LightBlock: differntLB,
  577. },
  578. }
  579. case 1: // send nil block i.e. pretend we don't have it
  580. sending <- p2p.Envelope{
  581. From: envelope.To,
  582. Message: &ssproto.LightBlockResponse{
  583. LightBlock: nil,
  584. },
  585. }
  586. case 2: // don't do anything
  587. }
  588. errorCount++
  589. }
  590. }
  591. case <-close:
  592. return
  593. }
  594. requests++
  595. }
  596. }
  597. func handleConsensusParamsRequest(t *testing.T, receiving, sending chan p2p.Envelope, closeCh chan struct{}) {
  598. t.Helper()
  599. params := types.DefaultConsensusParams()
  600. paramsProto := params.ToProto()
  601. for {
  602. select {
  603. case envelope := <-receiving:
  604. t.Log("received consensus params request")
  605. msg, ok := envelope.Message.(*ssproto.ParamsRequest)
  606. require.True(t, ok)
  607. sending <- p2p.Envelope{
  608. From: envelope.To,
  609. Message: &ssproto.ParamsResponse{
  610. Height: msg.Height,
  611. ConsensusParams: paramsProto,
  612. },
  613. }
  614. case <-closeCh:
  615. return
  616. }
  617. }
  618. }
  619. func buildLightBlockChain(t *testing.T, fromHeight, toHeight int64, startTime time.Time) map[int64]*types.LightBlock {
  620. chain := make(map[int64]*types.LightBlock, toHeight-fromHeight)
  621. lastBlockID := factory.MakeBlockID()
  622. blockTime := startTime.Add(time.Duration(fromHeight-toHeight) * time.Minute)
  623. vals, pv := factory.RandValidatorSet(3, 10)
  624. for height := fromHeight; height < toHeight; height++ {
  625. vals, pv, chain[height] = mockLB(t, height, blockTime, lastBlockID, vals, pv)
  626. lastBlockID = factory.MakeBlockIDWithHash(chain[height].Header.Hash())
  627. blockTime = blockTime.Add(1 * time.Minute)
  628. }
  629. return chain
  630. }
  631. func mockLB(t *testing.T, height int64, time time.Time, lastBlockID types.BlockID,
  632. currentVals *types.ValidatorSet, currentPrivVals []types.PrivValidator,
  633. ) (*types.ValidatorSet, []types.PrivValidator, *types.LightBlock) {
  634. header, err := factory.MakeHeader(&types.Header{
  635. Height: height,
  636. LastBlockID: lastBlockID,
  637. Time: time,
  638. })
  639. require.NoError(t, err)
  640. nextVals, nextPrivVals := factory.RandValidatorSet(3, 10)
  641. header.ValidatorsHash = currentVals.Hash()
  642. header.NextValidatorsHash = nextVals.Hash()
  643. header.ConsensusHash = types.DefaultConsensusParams().HashConsensusParams()
  644. lastBlockID = factory.MakeBlockIDWithHash(header.Hash())
  645. voteSet := types.NewVoteSet(factory.DefaultTestChainID, height, 0, tmproto.PrecommitType, currentVals)
  646. commit, err := factory.MakeCommit(lastBlockID, height, 0, voteSet, currentPrivVals, time)
  647. require.NoError(t, err)
  648. return nextVals, nextPrivVals, &types.LightBlock{
  649. SignedHeader: &types.SignedHeader{
  650. Header: header,
  651. Commit: commit,
  652. },
  653. ValidatorSet: currentVals,
  654. }
  655. }
  656. // graduallyAddPeers delivers a new randomly-generated peer update on peerUpdateCh once
  657. // per interval, until closeCh is closed. Each peer update is assigned a random node ID.
  658. func graduallyAddPeers(
  659. peerUpdateCh chan p2p.PeerUpdate,
  660. closeCh chan struct{},
  661. interval time.Duration,
  662. ) {
  663. ticker := time.NewTicker(interval)
  664. for {
  665. select {
  666. case <-ticker.C:
  667. peerUpdateCh <- p2p.PeerUpdate{
  668. NodeID: factory.RandomNodeID(),
  669. Status: p2p.PeerStatusUp,
  670. }
  671. case <-closeCh:
  672. return
  673. }
  674. }
  675. }
  676. func handleSnapshotRequests(
  677. t *testing.T,
  678. receivingCh chan p2p.Envelope,
  679. sendingCh chan p2p.Envelope,
  680. closeCh chan struct{},
  681. snapshots []snapshot,
  682. ) {
  683. t.Helper()
  684. for {
  685. select {
  686. case envelope := <-receivingCh:
  687. _, ok := envelope.Message.(*ssproto.SnapshotsRequest)
  688. require.True(t, ok)
  689. for _, snapshot := range snapshots {
  690. sendingCh <- p2p.Envelope{
  691. From: envelope.To,
  692. Message: &ssproto.SnapshotsResponse{
  693. Height: snapshot.Height,
  694. Format: snapshot.Format,
  695. Chunks: snapshot.Chunks,
  696. Hash: snapshot.Hash,
  697. Metadata: snapshot.Metadata,
  698. },
  699. }
  700. }
  701. case <-closeCh:
  702. return
  703. }
  704. }
  705. }
  706. func handleChunkRequests(
  707. t *testing.T,
  708. receivingCh chan p2p.Envelope,
  709. sendingCh chan p2p.Envelope,
  710. closeCh chan struct{},
  711. chunk []byte,
  712. ) {
  713. t.Helper()
  714. for {
  715. select {
  716. case envelope := <-receivingCh:
  717. msg, ok := envelope.Message.(*ssproto.ChunkRequest)
  718. require.True(t, ok)
  719. sendingCh <- p2p.Envelope{
  720. From: envelope.To,
  721. Message: &ssproto.ChunkResponse{
  722. Height: msg.Height,
  723. Format: msg.Format,
  724. Index: msg.Index,
  725. Chunk: chunk,
  726. Missing: false,
  727. },
  728. }
  729. case <-closeCh:
  730. return
  731. }
  732. }
  733. }