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.

322 lines
7.6 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/assert"
  11. "github.com/stretchr/testify/require"
  12. "github.com/tendermint/tendermint/internal/p2p"
  13. "github.com/tendermint/tendermint/internal/test/factory"
  14. ssproto "github.com/tendermint/tendermint/proto/tendermint/statesync"
  15. "github.com/tendermint/tendermint/types"
  16. )
  17. type channelInternal struct {
  18. In chan p2p.Envelope
  19. Out chan p2p.Envelope
  20. Error chan p2p.PeerError
  21. }
  22. func testChannel(size int) (*channelInternal, *p2p.Channel) {
  23. in := &channelInternal{
  24. In: make(chan p2p.Envelope, size),
  25. Out: make(chan p2p.Envelope, size),
  26. Error: make(chan p2p.PeerError, size),
  27. }
  28. return in, p2p.NewChannel(0, nil, in.In, in.Out, in.Error)
  29. }
  30. func TestDispatcherBasic(t *testing.T) {
  31. t.Cleanup(leaktest.Check(t))
  32. const numPeers = 5
  33. ctx, cancel := context.WithCancel(context.Background())
  34. defer cancel()
  35. chans, ch := testChannel(100)
  36. d := NewDispatcher(ch)
  37. go handleRequests(ctx, t, d, chans.Out)
  38. peers := createPeerSet(numPeers)
  39. wg := sync.WaitGroup{}
  40. // make a bunch of async requests and require that the correct responses are
  41. // given
  42. for i := 0; i < numPeers; i++ {
  43. wg.Add(1)
  44. go func(height int64) {
  45. defer wg.Done()
  46. lb, err := d.LightBlock(context.Background(), height, peers[height-1])
  47. require.NoError(t, err)
  48. require.NotNil(t, lb)
  49. require.Equal(t, lb.Height, height)
  50. }(int64(i + 1))
  51. }
  52. wg.Wait()
  53. // assert that all calls were responded to
  54. assert.Empty(t, d.calls)
  55. }
  56. func TestDispatcherReturnsNoBlock(t *testing.T) {
  57. t.Cleanup(leaktest.Check(t))
  58. ctx, cancel := context.WithCancel(context.Background())
  59. defer cancel()
  60. chans, ch := testChannel(100)
  61. d := NewDispatcher(ch)
  62. peer := factory.NodeID("a")
  63. go func() {
  64. <-chans.Out
  65. require.NoError(t, d.Respond(nil, peer))
  66. cancel()
  67. }()
  68. lb, err := d.LightBlock(ctx, 1, peer)
  69. <-ctx.Done()
  70. require.Nil(t, lb)
  71. require.Nil(t, err)
  72. }
  73. func TestDispatcherTimeOutWaitingOnLightBlock(t *testing.T) {
  74. t.Cleanup(leaktest.Check(t))
  75. ctx, cancel := context.WithCancel(context.Background())
  76. defer cancel()
  77. _, ch := testChannel(100)
  78. d := NewDispatcher(ch)
  79. peer := factory.NodeID("a")
  80. ctx, cancelFunc := context.WithTimeout(ctx, 10*time.Millisecond)
  81. defer cancelFunc()
  82. lb, err := d.LightBlock(ctx, 1, peer)
  83. require.Error(t, err)
  84. require.Equal(t, context.DeadlineExceeded, err)
  85. require.Nil(t, lb)
  86. }
  87. func TestDispatcherProviders(t *testing.T) {
  88. t.Cleanup(leaktest.Check(t))
  89. chainID := "test-chain"
  90. ctx, cancel := context.WithCancel(context.Background())
  91. defer cancel()
  92. chans, ch := testChannel(100)
  93. d := NewDispatcher(ch)
  94. go handleRequests(ctx, t, d, chans.Out)
  95. peers := createPeerSet(5)
  96. providers := make([]*BlockProvider, len(peers))
  97. for idx, peer := range peers {
  98. providers[idx] = NewBlockProvider(peer, chainID, d)
  99. }
  100. require.Len(t, providers, 5)
  101. for i, p := range providers {
  102. assert.Equal(t, string(peers[i]), p.String(), i)
  103. lb, err := p.LightBlock(context.Background(), 10)
  104. assert.NoError(t, err)
  105. assert.NotNil(t, lb)
  106. }
  107. }
  108. func TestPeerListBasic(t *testing.T) {
  109. t.Cleanup(leaktest.Check(t))
  110. ctx, cancel := context.WithCancel(context.Background())
  111. defer cancel()
  112. peerList := newPeerList()
  113. assert.Zero(t, peerList.Len())
  114. numPeers := 10
  115. peerSet := createPeerSet(numPeers)
  116. for _, peer := range peerSet {
  117. peerList.Append(peer)
  118. }
  119. for idx, peer := range peerList.All() {
  120. assert.Equal(t, peer, peerSet[idx])
  121. }
  122. assert.Equal(t, numPeers, peerList.Len())
  123. half := numPeers / 2
  124. for i := 0; i < half; i++ {
  125. assert.Equal(t, peerSet[i], peerList.Pop(ctx))
  126. }
  127. assert.Equal(t, half, peerList.Len())
  128. // removing a peer that doesn't exist should not change the list
  129. peerList.Remove(types.NodeID("lp"))
  130. assert.Equal(t, half, peerList.Len())
  131. // removing a peer that exists should decrease the list size by one
  132. peerList.Remove(peerSet[half])
  133. assert.Equal(t, numPeers-half-1, peerList.Len())
  134. // popping the next peer should work as expected
  135. assert.Equal(t, peerSet[half+1], peerList.Pop(ctx))
  136. assert.Equal(t, numPeers-half-2, peerList.Len())
  137. // append the two peers back
  138. peerList.Append(peerSet[half])
  139. peerList.Append(peerSet[half+1])
  140. assert.Equal(t, half, peerList.Len())
  141. }
  142. func TestPeerListBlocksWhenEmpty(t *testing.T) {
  143. t.Cleanup(leaktest.Check(t))
  144. peerList := newPeerList()
  145. require.Zero(t, peerList.Len())
  146. doneCh := make(chan struct{})
  147. ctx, cancel := context.WithCancel(context.Background())
  148. defer cancel()
  149. go func() {
  150. peerList.Pop(ctx)
  151. close(doneCh)
  152. }()
  153. select {
  154. case <-doneCh:
  155. t.Error("empty peer list should not have returned result")
  156. case <-time.After(100 * time.Millisecond):
  157. }
  158. }
  159. func TestEmptyPeerListReturnsWhenContextCanceled(t *testing.T) {
  160. t.Cleanup(leaktest.Check(t))
  161. peerList := newPeerList()
  162. require.Zero(t, peerList.Len())
  163. doneCh := make(chan struct{})
  164. ctx := context.Background()
  165. wrapped, cancel := context.WithCancel(ctx)
  166. go func() {
  167. peerList.Pop(wrapped)
  168. close(doneCh)
  169. }()
  170. select {
  171. case <-doneCh:
  172. t.Error("empty peer list should not have returned result")
  173. case <-time.After(100 * time.Millisecond):
  174. }
  175. cancel()
  176. select {
  177. case <-doneCh:
  178. case <-time.After(100 * time.Millisecond):
  179. t.Error("peer list should have returned after context canceled")
  180. }
  181. }
  182. func TestPeerListConcurrent(t *testing.T) {
  183. t.Cleanup(leaktest.Check(t))
  184. ctx, cancel := context.WithCancel(context.Background())
  185. defer cancel()
  186. peerList := newPeerList()
  187. numPeers := 10
  188. wg := sync.WaitGroup{}
  189. // we run a set of goroutines requesting the next peer in the list. As the
  190. // peer list hasn't been populated each these go routines should block
  191. for i := 0; i < numPeers/2; i++ {
  192. go func() {
  193. _ = peerList.Pop(ctx)
  194. wg.Done()
  195. }()
  196. }
  197. // now we add the peers to the list, this should allow the previously
  198. // blocked go routines to unblock
  199. for _, peer := range createPeerSet(numPeers) {
  200. wg.Add(1)
  201. peerList.Append(peer)
  202. }
  203. // we request the second half of the peer set
  204. for i := 0; i < numPeers/2; i++ {
  205. go func() {
  206. _ = peerList.Pop(ctx)
  207. wg.Done()
  208. }()
  209. }
  210. // we use a context with cancel and a separate go routine to wait for all
  211. // the other goroutines to close.
  212. go func() { wg.Wait(); cancel() }()
  213. select {
  214. case <-time.After(time.Second):
  215. // not all of the blocked go routines waiting on peers have closed after
  216. // one second. This likely means the list got blocked.
  217. t.Failed()
  218. case <-ctx.Done():
  219. // there should be no peers remaining
  220. require.Equal(t, 0, peerList.Len())
  221. }
  222. }
  223. func TestPeerListRemove(t *testing.T) {
  224. peerList := newPeerList()
  225. numPeers := 10
  226. peerSet := createPeerSet(numPeers)
  227. for _, peer := range peerSet {
  228. peerList.Append(peer)
  229. }
  230. for _, peer := range peerSet {
  231. peerList.Remove(peer)
  232. for _, p := range peerList.All() {
  233. require.NotEqual(t, p, peer)
  234. }
  235. numPeers--
  236. require.Equal(t, numPeers, peerList.Len())
  237. }
  238. }
  239. // handleRequests is a helper function usually run in a separate go routine to
  240. // imitate the expected responses of the reactor wired to the dispatcher
  241. func handleRequests(ctx context.Context, t *testing.T, d *Dispatcher, ch chan p2p.Envelope) {
  242. t.Helper()
  243. for {
  244. select {
  245. case request := <-ch:
  246. height := request.Message.(*ssproto.LightBlockRequest).Height
  247. peer := request.To
  248. resp := mockLBResp(t, peer, int64(height), time.Now())
  249. block, _ := resp.block.ToProto()
  250. require.NoError(t, d.Respond(block, resp.peer))
  251. case <-ctx.Done():
  252. return
  253. }
  254. }
  255. }
  256. func createPeerSet(num int) []types.NodeID {
  257. peers := make([]types.NodeID, num)
  258. for i := 0; i < num; i++ {
  259. peers[i], _ = types.NewNodeID(strings.Repeat(fmt.Sprintf("%d", i), 2*types.NodeIDByteLength))
  260. }
  261. return peers
  262. }