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.

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