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.

646 lines
24 KiB

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