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.

698 lines
24 KiB

  1. package statesync
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/stretchr/testify/mock"
  10. "github.com/stretchr/testify/require"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. tmsync "github.com/tendermint/tendermint/libs/sync"
  13. "github.com/tendermint/tendermint/p2p"
  14. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  15. "github.com/tendermint/tendermint/proxy"
  16. proxymocks "github.com/tendermint/tendermint/proxy/mocks"
  17. sm "github.com/tendermint/tendermint/state"
  18. "github.com/tendermint/tendermint/statesync/mocks"
  19. "github.com/tendermint/tendermint/types"
  20. "github.com/tendermint/tendermint/version"
  21. )
  22. var ctx = context.Background()
  23. func TestSyncer_SyncAny(t *testing.T) {
  24. state := sm.State{
  25. ChainID: "chain",
  26. Version: sm.Version{
  27. Consensus: version.Consensus{
  28. Block: version.BlockProtocol,
  29. App: 0,
  30. },
  31. Software: version.TMCoreSemVer,
  32. },
  33. LastBlockHeight: 1,
  34. LastBlockID: types.BlockID{Hash: []byte("blockhash")},
  35. LastBlockTime: time.Now(),
  36. LastResultsHash: []byte("last_results_hash"),
  37. AppHash: []byte("app_hash"),
  38. LastValidators: &types.ValidatorSet{Proposer: &types.Validator{Address: []byte("val1")}},
  39. Validators: &types.ValidatorSet{Proposer: &types.Validator{Address: []byte("val2")}},
  40. NextValidators: &types.ValidatorSet{Proposer: &types.Validator{Address: []byte("val3")}},
  41. ConsensusParams: *types.DefaultConsensusParams(),
  42. LastHeightConsensusParamsChanged: 1,
  43. }
  44. commit := &types.Commit{BlockID: types.BlockID{Hash: []byte("blockhash")}}
  45. chunks := []*chunk{
  46. {Height: 1, Format: 1, Index: 0, Chunk: []byte{1, 1, 0}},
  47. {Height: 1, Format: 1, Index: 1, Chunk: []byte{1, 1, 1}},
  48. {Height: 1, Format: 1, Index: 2, Chunk: []byte{1, 1, 2}},
  49. }
  50. s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  51. stateProvider := &mocks.StateProvider{}
  52. stateProvider.On("AppHash", mock.Anything, uint64(1)).Return(state.AppHash, nil)
  53. stateProvider.On("AppHash", mock.Anything, uint64(2)).Return([]byte("app_hash_2"), nil)
  54. stateProvider.On("Commit", mock.Anything, uint64(1)).Return(commit, nil)
  55. stateProvider.On("State", mock.Anything, uint64(1)).Return(state, nil)
  56. connSnapshot := &proxymocks.AppConnSnapshot{}
  57. connQuery := &proxymocks.AppConnQuery{}
  58. peerAID := p2p.NodeID("aa")
  59. peerBID := p2p.NodeID("bb")
  60. rts := setup(t, connSnapshot, connQuery, stateProvider, 3)
  61. // Adding a chunk should error when no sync is in progress
  62. _, err := rts.syncer.AddChunk(&chunk{Height: 1, Format: 1, Index: 0, Chunk: []byte{1}})
  63. require.Error(t, err)
  64. // Adding a couple of peers should trigger snapshot discovery messages
  65. rts.syncer.AddPeer(peerAID)
  66. e := <-rts.snapshotOutCh
  67. require.Equal(t, &ssproto.SnapshotsRequest{}, e.Message)
  68. require.Equal(t, peerAID, e.To)
  69. rts.syncer.AddPeer(peerBID)
  70. e = <-rts.snapshotOutCh
  71. require.Equal(t, &ssproto.SnapshotsRequest{}, e.Message)
  72. require.Equal(t, peerBID, e.To)
  73. // Both peers report back with snapshots. One of them also returns a snapshot we don't want, in
  74. // format 2, which will be rejected by the ABCI application.
  75. new, err := rts.syncer.AddSnapshot(peerAID, s)
  76. require.NoError(t, err)
  77. require.True(t, new)
  78. new, err = rts.syncer.AddSnapshot(peerBID, s)
  79. require.NoError(t, err)
  80. require.False(t, new)
  81. new, err = rts.syncer.AddSnapshot(peerBID, &snapshot{Height: 2, Format: 2, Chunks: 3, Hash: []byte{1}})
  82. require.NoError(t, err)
  83. require.True(t, new)
  84. // We start a sync, with peers sending back chunks when requested. We first reject the snapshot
  85. // with height 2 format 2, and accept the snapshot at height 1.
  86. connSnapshot.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  87. Snapshot: &abci.Snapshot{
  88. Height: 2,
  89. Format: 2,
  90. Chunks: 3,
  91. Hash: []byte{1},
  92. },
  93. AppHash: []byte("app_hash_2"),
  94. }).Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT_FORMAT}, nil)
  95. connSnapshot.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  96. Snapshot: &abci.Snapshot{
  97. Height: s.Height,
  98. Format: s.Format,
  99. Chunks: s.Chunks,
  100. Hash: s.Hash,
  101. Metadata: s.Metadata,
  102. },
  103. AppHash: []byte("app_hash"),
  104. }).Times(2).Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ACCEPT}, nil)
  105. chunkRequests := make(map[uint32]int)
  106. chunkRequestsMtx := tmsync.Mutex{}
  107. var wg sync.WaitGroup
  108. wg.Add(4)
  109. go func() {
  110. for e := range rts.chunkOutCh {
  111. msg, ok := e.Message.(*ssproto.ChunkRequest)
  112. assert.True(t, ok)
  113. assert.EqualValues(t, 1, msg.Height)
  114. assert.EqualValues(t, 1, msg.Format)
  115. assert.LessOrEqual(t, msg.Index, uint32(len(chunks)))
  116. added, err := rts.syncer.AddChunk(chunks[msg.Index])
  117. assert.NoError(t, err)
  118. assert.True(t, added)
  119. chunkRequestsMtx.Lock()
  120. chunkRequests[msg.Index]++
  121. chunkRequestsMtx.Unlock()
  122. wg.Done()
  123. }
  124. }()
  125. // The first time we're applying chunk 2 we tell it to retry the snapshot and discard chunk 1,
  126. // which should cause it to keep the existing chunk 0 and 2, and restart restoration from
  127. // beginning. We also wait for a little while, to exercise the retry logic in fetchChunks().
  128. connSnapshot.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  129. Index: 2, Chunk: []byte{1, 1, 2},
  130. }).Once().Run(func(args mock.Arguments) { time.Sleep(2 * time.Second) }).Return(
  131. &abci.ResponseApplySnapshotChunk{
  132. Result: abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT,
  133. RefetchChunks: []uint32{1},
  134. }, nil)
  135. connSnapshot.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  136. Index: 0, Chunk: []byte{1, 1, 0},
  137. }).Times(2).Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  138. connSnapshot.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  139. Index: 1, Chunk: []byte{1, 1, 1},
  140. }).Times(2).Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  141. connSnapshot.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  142. Index: 2, Chunk: []byte{1, 1, 2},
  143. }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  144. connQuery.On("InfoSync", ctx, proxy.RequestInfo).Return(&abci.ResponseInfo{
  145. AppVersion: 9,
  146. LastBlockHeight: 1,
  147. LastBlockAppHash: []byte("app_hash"),
  148. }, nil)
  149. newState, lastCommit, err := rts.syncer.SyncAny(0)
  150. require.NoError(t, err)
  151. wg.Wait()
  152. chunkRequestsMtx.Lock()
  153. require.Equal(t, map[uint32]int{0: 1, 1: 2, 2: 1}, chunkRequests)
  154. chunkRequestsMtx.Unlock()
  155. // The syncer should have updated the state app version from the ABCI info response.
  156. expectState := state
  157. expectState.Version.Consensus.App = 9
  158. require.Equal(t, expectState, newState)
  159. require.Equal(t, commit, lastCommit)
  160. connSnapshot.AssertExpectations(t)
  161. connQuery.AssertExpectations(t)
  162. }
  163. func TestSyncer_SyncAny_noSnapshots(t *testing.T) {
  164. stateProvider := &mocks.StateProvider{}
  165. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  166. rts := setup(t, nil, nil, stateProvider, 2)
  167. _, _, err := rts.syncer.SyncAny(0)
  168. require.Equal(t, errNoSnapshots, err)
  169. }
  170. func TestSyncer_SyncAny_abort(t *testing.T) {
  171. stateProvider := &mocks.StateProvider{}
  172. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  173. rts := setup(t, nil, nil, stateProvider, 2)
  174. s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  175. peerID := p2p.NodeID("aa")
  176. _, err := rts.syncer.AddSnapshot(peerID, s)
  177. require.NoError(t, err)
  178. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  179. Snapshot: toABCI(s), AppHash: []byte("app_hash"),
  180. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ABORT}, nil)
  181. _, _, err = rts.syncer.SyncAny(0)
  182. require.Equal(t, errAbort, err)
  183. rts.conn.AssertExpectations(t)
  184. }
  185. func TestSyncer_SyncAny_reject(t *testing.T) {
  186. stateProvider := &mocks.StateProvider{}
  187. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  188. rts := setup(t, nil, nil, stateProvider, 2)
  189. // s22 is tried first, then s12, then s11, then errNoSnapshots
  190. s22 := &snapshot{Height: 2, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}}
  191. s12 := &snapshot{Height: 1, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}}
  192. s11 := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  193. peerID := p2p.NodeID("aa")
  194. _, err := rts.syncer.AddSnapshot(peerID, s22)
  195. require.NoError(t, err)
  196. _, err = rts.syncer.AddSnapshot(peerID, s12)
  197. require.NoError(t, err)
  198. _, err = rts.syncer.AddSnapshot(peerID, s11)
  199. require.NoError(t, err)
  200. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  201. Snapshot: toABCI(s22), AppHash: []byte("app_hash"),
  202. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil)
  203. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  204. Snapshot: toABCI(s12), AppHash: []byte("app_hash"),
  205. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil)
  206. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  207. Snapshot: toABCI(s11), AppHash: []byte("app_hash"),
  208. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil)
  209. _, _, err = rts.syncer.SyncAny(0)
  210. require.Equal(t, errNoSnapshots, err)
  211. rts.conn.AssertExpectations(t)
  212. }
  213. func TestSyncer_SyncAny_reject_format(t *testing.T) {
  214. stateProvider := &mocks.StateProvider{}
  215. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  216. rts := setup(t, nil, nil, stateProvider, 2)
  217. // s22 is tried first, which reject s22 and s12, then s11 will abort.
  218. s22 := &snapshot{Height: 2, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}}
  219. s12 := &snapshot{Height: 1, Format: 2, Chunks: 3, Hash: []byte{1, 2, 3}}
  220. s11 := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  221. peerID := p2p.NodeID("aa")
  222. _, err := rts.syncer.AddSnapshot(peerID, s22)
  223. require.NoError(t, err)
  224. _, err = rts.syncer.AddSnapshot(peerID, s12)
  225. require.NoError(t, err)
  226. _, err = rts.syncer.AddSnapshot(peerID, s11)
  227. require.NoError(t, err)
  228. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  229. Snapshot: toABCI(s22), AppHash: []byte("app_hash"),
  230. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT_FORMAT}, nil)
  231. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  232. Snapshot: toABCI(s11), AppHash: []byte("app_hash"),
  233. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_ABORT}, nil)
  234. _, _, err = rts.syncer.SyncAny(0)
  235. require.Equal(t, errAbort, err)
  236. rts.conn.AssertExpectations(t)
  237. }
  238. func TestSyncer_SyncAny_reject_sender(t *testing.T) {
  239. stateProvider := &mocks.StateProvider{}
  240. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  241. rts := setup(t, nil, nil, stateProvider, 2)
  242. peerAID := p2p.NodeID("aa")
  243. peerBID := p2p.NodeID("bb")
  244. peerCID := p2p.NodeID("cc")
  245. // sbc will be offered first, which will be rejected with reject_sender, causing all snapshots
  246. // submitted by both b and c (i.e. sb, sc, sbc) to be rejected. Finally, sa will reject and
  247. // errNoSnapshots is returned.
  248. sa := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  249. sb := &snapshot{Height: 2, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  250. sc := &snapshot{Height: 3, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  251. sbc := &snapshot{Height: 4, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  252. _, err := rts.syncer.AddSnapshot(peerAID, sa)
  253. require.NoError(t, err)
  254. _, err = rts.syncer.AddSnapshot(peerBID, sb)
  255. require.NoError(t, err)
  256. _, err = rts.syncer.AddSnapshot(peerCID, sc)
  257. require.NoError(t, err)
  258. _, err = rts.syncer.AddSnapshot(peerBID, sbc)
  259. require.NoError(t, err)
  260. _, err = rts.syncer.AddSnapshot(peerCID, sbc)
  261. require.NoError(t, err)
  262. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  263. Snapshot: toABCI(sbc), AppHash: []byte("app_hash"),
  264. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT_SENDER}, nil)
  265. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  266. Snapshot: toABCI(sa), AppHash: []byte("app_hash"),
  267. }).Once().Return(&abci.ResponseOfferSnapshot{Result: abci.ResponseOfferSnapshot_REJECT}, nil)
  268. _, _, err = rts.syncer.SyncAny(0)
  269. require.Equal(t, errNoSnapshots, err)
  270. rts.conn.AssertExpectations(t)
  271. }
  272. func TestSyncer_SyncAny_abciError(t *testing.T) {
  273. stateProvider := &mocks.StateProvider{}
  274. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  275. rts := setup(t, nil, nil, stateProvider, 2)
  276. errBoom := errors.New("boom")
  277. s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}}
  278. peerID := p2p.NodeID("aa")
  279. _, err := rts.syncer.AddSnapshot(peerID, s)
  280. require.NoError(t, err)
  281. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  282. Snapshot: toABCI(s), AppHash: []byte("app_hash"),
  283. }).Once().Return(nil, errBoom)
  284. _, _, err = rts.syncer.SyncAny(0)
  285. require.True(t, errors.Is(err, errBoom))
  286. rts.conn.AssertExpectations(t)
  287. }
  288. func TestSyncer_offerSnapshot(t *testing.T) {
  289. unknownErr := errors.New("unknown error")
  290. boom := errors.New("boom")
  291. testcases := map[string]struct {
  292. result abci.ResponseOfferSnapshot_Result
  293. err error
  294. expectErr error
  295. }{
  296. "accept": {abci.ResponseOfferSnapshot_ACCEPT, nil, nil},
  297. "abort": {abci.ResponseOfferSnapshot_ABORT, nil, errAbort},
  298. "reject": {abci.ResponseOfferSnapshot_REJECT, nil, errRejectSnapshot},
  299. "reject_format": {abci.ResponseOfferSnapshot_REJECT_FORMAT, nil, errRejectFormat},
  300. "reject_sender": {abci.ResponseOfferSnapshot_REJECT_SENDER, nil, errRejectSender},
  301. "unknown": {abci.ResponseOfferSnapshot_UNKNOWN, nil, unknownErr},
  302. "error": {0, boom, boom},
  303. "unknown non-zero": {9, nil, unknownErr},
  304. }
  305. for name, tc := range testcases {
  306. tc := tc
  307. t.Run(name, func(t *testing.T) {
  308. stateProvider := &mocks.StateProvider{}
  309. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  310. rts := setup(t, nil, nil, stateProvider, 2)
  311. s := &snapshot{Height: 1, Format: 1, Chunks: 3, Hash: []byte{1, 2, 3}, trustedAppHash: []byte("app_hash")}
  312. rts.conn.On("OfferSnapshotSync", ctx, abci.RequestOfferSnapshot{
  313. Snapshot: toABCI(s),
  314. AppHash: []byte("app_hash"),
  315. }).Return(&abci.ResponseOfferSnapshot{Result: tc.result}, tc.err)
  316. err := rts.syncer.offerSnapshot(s)
  317. if tc.expectErr == unknownErr {
  318. require.Error(t, err)
  319. } else {
  320. unwrapped := errors.Unwrap(err)
  321. if unwrapped != nil {
  322. err = unwrapped
  323. }
  324. require.Equal(t, tc.expectErr, err)
  325. }
  326. })
  327. }
  328. }
  329. func TestSyncer_applyChunks_Results(t *testing.T) {
  330. unknownErr := errors.New("unknown error")
  331. boom := errors.New("boom")
  332. testcases := map[string]struct {
  333. result abci.ResponseApplySnapshotChunk_Result
  334. err error
  335. expectErr error
  336. }{
  337. "accept": {abci.ResponseApplySnapshotChunk_ACCEPT, nil, nil},
  338. "abort": {abci.ResponseApplySnapshotChunk_ABORT, nil, errAbort},
  339. "retry": {abci.ResponseApplySnapshotChunk_RETRY, nil, nil},
  340. "retry_snapshot": {abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT, nil, errRetrySnapshot},
  341. "reject_snapshot": {abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT, nil, errRejectSnapshot},
  342. "unknown": {abci.ResponseApplySnapshotChunk_UNKNOWN, nil, unknownErr},
  343. "error": {0, boom, boom},
  344. "unknown non-zero": {9, nil, unknownErr},
  345. }
  346. for name, tc := range testcases {
  347. tc := tc
  348. t.Run(name, func(t *testing.T) {
  349. stateProvider := &mocks.StateProvider{}
  350. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  351. rts := setup(t, nil, nil, stateProvider, 2)
  352. body := []byte{1, 2, 3}
  353. chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 1}, "")
  354. require.NoError(t, err)
  355. _, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 0, Chunk: body})
  356. require.NoError(t, err)
  357. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  358. Index: 0, Chunk: body,
  359. }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: tc.result}, tc.err)
  360. if tc.result == abci.ResponseApplySnapshotChunk_RETRY {
  361. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  362. Index: 0, Chunk: body,
  363. }).Once().Return(&abci.ResponseApplySnapshotChunk{
  364. Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  365. }
  366. err = rts.syncer.applyChunks(chunks)
  367. if tc.expectErr == unknownErr {
  368. require.Error(t, err)
  369. } else {
  370. unwrapped := errors.Unwrap(err)
  371. if unwrapped != nil {
  372. err = unwrapped
  373. }
  374. require.Equal(t, tc.expectErr, err)
  375. }
  376. rts.conn.AssertExpectations(t)
  377. })
  378. }
  379. }
  380. func TestSyncer_applyChunks_RefetchChunks(t *testing.T) {
  381. // Discarding chunks via refetch_chunks should work the same for all results
  382. testcases := map[string]struct {
  383. result abci.ResponseApplySnapshotChunk_Result
  384. }{
  385. "accept": {abci.ResponseApplySnapshotChunk_ACCEPT},
  386. "abort": {abci.ResponseApplySnapshotChunk_ABORT},
  387. "retry": {abci.ResponseApplySnapshotChunk_RETRY},
  388. "retry_snapshot": {abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT},
  389. "reject_snapshot": {abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT},
  390. }
  391. for name, tc := range testcases {
  392. tc := tc
  393. t.Run(name, func(t *testing.T) {
  394. stateProvider := &mocks.StateProvider{}
  395. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  396. rts := setup(t, nil, nil, stateProvider, 2)
  397. chunks, err := newChunkQueue(&snapshot{Height: 1, Format: 1, Chunks: 3}, "")
  398. require.NoError(t, err)
  399. added, err := chunks.Add(&chunk{Height: 1, Format: 1, Index: 0, Chunk: []byte{0}})
  400. require.True(t, added)
  401. require.NoError(t, err)
  402. added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 1, Chunk: []byte{1}})
  403. require.True(t, added)
  404. require.NoError(t, err)
  405. added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 2, Chunk: []byte{2}})
  406. require.True(t, added)
  407. require.NoError(t, err)
  408. // The first two chunks are accepted, before the last one asks for 1 to be refetched
  409. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  410. Index: 0, Chunk: []byte{0},
  411. }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  412. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  413. Index: 1, Chunk: []byte{1},
  414. }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  415. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  416. Index: 2, Chunk: []byte{2},
  417. }).Once().Return(&abci.ResponseApplySnapshotChunk{
  418. Result: tc.result,
  419. RefetchChunks: []uint32{1},
  420. }, nil)
  421. // Since removing the chunk will cause Next() to block, we spawn a goroutine, then
  422. // check the queue contents, and finally close the queue to end the goroutine.
  423. // We don't really care about the result of applyChunks, since it has separate test.
  424. go func() {
  425. rts.syncer.applyChunks(chunks) //nolint:errcheck // purposefully ignore error
  426. }()
  427. time.Sleep(50 * time.Millisecond)
  428. require.True(t, chunks.Has(0))
  429. require.False(t, chunks.Has(1))
  430. require.True(t, chunks.Has(2))
  431. require.NoError(t, chunks.Close())
  432. })
  433. }
  434. }
  435. func TestSyncer_applyChunks_RejectSenders(t *testing.T) {
  436. // Banning chunks senders via ban_chunk_senders should work the same for all results
  437. testcases := map[string]struct {
  438. result abci.ResponseApplySnapshotChunk_Result
  439. }{
  440. "accept": {abci.ResponseApplySnapshotChunk_ACCEPT},
  441. "abort": {abci.ResponseApplySnapshotChunk_ABORT},
  442. "retry": {abci.ResponseApplySnapshotChunk_RETRY},
  443. "retry_snapshot": {abci.ResponseApplySnapshotChunk_RETRY_SNAPSHOT},
  444. "reject_snapshot": {abci.ResponseApplySnapshotChunk_REJECT_SNAPSHOT},
  445. }
  446. for name, tc := range testcases {
  447. tc := tc
  448. t.Run(name, func(t *testing.T) {
  449. stateProvider := &mocks.StateProvider{}
  450. stateProvider.On("AppHash", mock.Anything, mock.Anything).Return([]byte("app_hash"), nil)
  451. rts := setup(t, nil, nil, stateProvider, 2)
  452. // Set up three peers across two snapshots, and ask for one of them to be banned.
  453. // It should be banned from all snapshots.
  454. peerAID := p2p.NodeID("aa")
  455. peerBID := p2p.NodeID("bb")
  456. peerCID := p2p.NodeID("cc")
  457. s1 := &snapshot{Height: 1, Format: 1, Chunks: 3}
  458. s2 := &snapshot{Height: 2, Format: 1, Chunks: 3}
  459. _, err := rts.syncer.AddSnapshot(peerAID, s1)
  460. require.NoError(t, err)
  461. _, err = rts.syncer.AddSnapshot(peerAID, s2)
  462. require.NoError(t, err)
  463. _, err = rts.syncer.AddSnapshot(peerBID, s1)
  464. require.NoError(t, err)
  465. _, err = rts.syncer.AddSnapshot(peerBID, s2)
  466. require.NoError(t, err)
  467. _, err = rts.syncer.AddSnapshot(peerCID, s1)
  468. require.NoError(t, err)
  469. _, err = rts.syncer.AddSnapshot(peerCID, s2)
  470. require.NoError(t, err)
  471. chunks, err := newChunkQueue(s1, "")
  472. require.NoError(t, err)
  473. added, err := chunks.Add(&chunk{Height: 1, Format: 1, Index: 0, Chunk: []byte{0}, Sender: peerAID})
  474. require.True(t, added)
  475. require.NoError(t, err)
  476. added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 1, Chunk: []byte{1}, Sender: peerBID})
  477. require.True(t, added)
  478. require.NoError(t, err)
  479. added, err = chunks.Add(&chunk{Height: 1, Format: 1, Index: 2, Chunk: []byte{2}, Sender: peerCID})
  480. require.True(t, added)
  481. require.NoError(t, err)
  482. // The first two chunks are accepted, before the last one asks for b sender to be rejected
  483. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  484. Index: 0, Chunk: []byte{0}, Sender: "aa",
  485. }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  486. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  487. Index: 1, Chunk: []byte{1}, Sender: "bb",
  488. }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  489. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  490. Index: 2, Chunk: []byte{2}, Sender: "cc",
  491. }).Once().Return(&abci.ResponseApplySnapshotChunk{
  492. Result: tc.result,
  493. RejectSenders: []string{string(peerBID)},
  494. }, nil)
  495. // On retry, the last chunk will be tried again, so we just accept it then.
  496. if tc.result == abci.ResponseApplySnapshotChunk_RETRY {
  497. rts.conn.On("ApplySnapshotChunkSync", ctx, abci.RequestApplySnapshotChunk{
  498. Index: 2, Chunk: []byte{2}, Sender: "cc",
  499. }).Once().Return(&abci.ResponseApplySnapshotChunk{Result: abci.ResponseApplySnapshotChunk_ACCEPT}, nil)
  500. }
  501. // We don't really care about the result of applyChunks, since it has separate test.
  502. // However, it will block on e.g. retry result, so we spawn a goroutine that will
  503. // be shut down when the chunk queue closes.
  504. go func() {
  505. rts.syncer.applyChunks(chunks) //nolint:errcheck // purposefully ignore error
  506. }()
  507. time.Sleep(50 * time.Millisecond)
  508. s1peers := rts.syncer.snapshots.GetPeers(s1)
  509. require.Len(t, s1peers, 2)
  510. require.EqualValues(t, "aa", s1peers[0])
  511. require.EqualValues(t, "cc", s1peers[1])
  512. rts.syncer.snapshots.GetPeers(s1)
  513. require.Len(t, s1peers, 2)
  514. require.EqualValues(t, "aa", s1peers[0])
  515. require.EqualValues(t, "cc", s1peers[1])
  516. require.NoError(t, chunks.Close())
  517. })
  518. }
  519. }
  520. func TestSyncer_verifyApp(t *testing.T) {
  521. boom := errors.New("boom")
  522. s := &snapshot{Height: 3, Format: 1, Chunks: 5, Hash: []byte{1, 2, 3}, trustedAppHash: []byte("app_hash")}
  523. testcases := map[string]struct {
  524. response *abci.ResponseInfo
  525. err error
  526. expectErr error
  527. }{
  528. "verified": {&abci.ResponseInfo{
  529. LastBlockHeight: 3,
  530. LastBlockAppHash: []byte("app_hash"),
  531. AppVersion: 9,
  532. }, nil, nil},
  533. "invalid height": {&abci.ResponseInfo{
  534. LastBlockHeight: 5,
  535. LastBlockAppHash: []byte("app_hash"),
  536. AppVersion: 9,
  537. }, nil, errVerifyFailed},
  538. "invalid hash": {&abci.ResponseInfo{
  539. LastBlockHeight: 3,
  540. LastBlockAppHash: []byte("xxx"),
  541. AppVersion: 9,
  542. }, nil, errVerifyFailed},
  543. "error": {nil, boom, boom},
  544. }
  545. for name, tc := range testcases {
  546. tc := tc
  547. t.Run(name, func(t *testing.T) {
  548. rts := setup(t, nil, nil, nil, 2)
  549. rts.connQuery.On("InfoSync", ctx, proxy.RequestInfo).Return(tc.response, tc.err)
  550. version, err := rts.syncer.verifyApp(s)
  551. unwrapped := errors.Unwrap(err)
  552. if unwrapped != nil {
  553. err = unwrapped
  554. }
  555. require.Equal(t, tc.expectErr, err)
  556. if err == nil {
  557. require.Equal(t, tc.response.AppVersion, version)
  558. }
  559. })
  560. }
  561. }
  562. func toABCI(s *snapshot) *abci.Snapshot {
  563. return &abci.Snapshot{
  564. Height: s.Height,
  565. Format: s.Format,
  566. Chunks: s.Chunks,
  567. Hash: s.Hash,
  568. Metadata: s.Metadata,
  569. }
  570. }