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.

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