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.

581 lines
17 KiB

  1. package evidence_test
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "math/rand"
  6. "sync"
  7. "testing"
  8. "time"
  9. "github.com/fortytw2/leaktest"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/mock"
  12. "github.com/stretchr/testify/require"
  13. dbm "github.com/tendermint/tm-db"
  14. "github.com/tendermint/tendermint/crypto"
  15. "github.com/tendermint/tendermint/crypto/tmhash"
  16. "github.com/tendermint/tendermint/internal/evidence"
  17. "github.com/tendermint/tendermint/internal/evidence/mocks"
  18. "github.com/tendermint/tendermint/internal/p2p"
  19. "github.com/tendermint/tendermint/internal/p2p/p2ptest"
  20. sm "github.com/tendermint/tendermint/internal/state"
  21. "github.com/tendermint/tendermint/libs/log"
  22. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  23. "github.com/tendermint/tendermint/types"
  24. )
  25. var (
  26. numEvidence = 10
  27. rng = rand.New(rand.NewSource(time.Now().UnixNano()))
  28. )
  29. type reactorTestSuite struct {
  30. network *p2ptest.Network
  31. logger log.Logger
  32. reactors map[types.NodeID]*evidence.Reactor
  33. pools map[types.NodeID]*evidence.Pool
  34. evidenceChannels map[types.NodeID]*p2p.Channel
  35. peerUpdates map[types.NodeID]*p2p.PeerUpdates
  36. peerChans map[types.NodeID]chan p2p.PeerUpdate
  37. nodes []*p2ptest.Node
  38. numStateStores int
  39. }
  40. func setup(ctx context.Context, t *testing.T, stateStores []sm.Store, chBuf uint) *reactorTestSuite {
  41. t.Helper()
  42. pID := make([]byte, 16)
  43. _, err := rng.Read(pID)
  44. require.NoError(t, err)
  45. numStateStores := len(stateStores)
  46. rts := &reactorTestSuite{
  47. numStateStores: numStateStores,
  48. logger: log.TestingLogger().With("testCase", t.Name()),
  49. network: p2ptest.MakeNetwork(ctx, t, p2ptest.NetworkOptions{NumNodes: numStateStores}),
  50. reactors: make(map[types.NodeID]*evidence.Reactor, numStateStores),
  51. pools: make(map[types.NodeID]*evidence.Pool, numStateStores),
  52. peerUpdates: make(map[types.NodeID]*p2p.PeerUpdates, numStateStores),
  53. peerChans: make(map[types.NodeID]chan p2p.PeerUpdate, numStateStores),
  54. }
  55. chDesc := &p2p.ChannelDescriptor{ID: evidence.EvidenceChannel, MessageType: new(tmproto.EvidenceList)}
  56. rts.evidenceChannels = rts.network.MakeChannelsNoCleanup(t, chDesc)
  57. require.Len(t, rts.network.RandomNode().PeerManager.Peers(), 0)
  58. idx := 0
  59. evidenceTime := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
  60. for nodeID := range rts.network.Nodes {
  61. logger := rts.logger.With("validator", idx)
  62. evidenceDB := dbm.NewMemDB()
  63. blockStore := &mocks.BlockStore{}
  64. state, _ := stateStores[idx].Load()
  65. blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(func(h int64) *types.BlockMeta {
  66. if h <= state.LastBlockHeight {
  67. return &types.BlockMeta{Header: types.Header{Time: evidenceTime}}
  68. }
  69. return nil
  70. })
  71. rts.pools[nodeID], err = evidence.NewPool(logger, evidenceDB, stateStores[idx], blockStore)
  72. require.NoError(t, err)
  73. rts.peerChans[nodeID] = make(chan p2p.PeerUpdate)
  74. rts.peerUpdates[nodeID] = p2p.NewPeerUpdates(rts.peerChans[nodeID], 1)
  75. rts.network.Nodes[nodeID].PeerManager.Register(rts.peerUpdates[nodeID])
  76. rts.nodes = append(rts.nodes, rts.network.Nodes[nodeID])
  77. rts.reactors[nodeID] = evidence.NewReactor(logger,
  78. rts.evidenceChannels[nodeID],
  79. rts.peerUpdates[nodeID],
  80. rts.pools[nodeID])
  81. require.NoError(t, rts.reactors[nodeID].Start(ctx))
  82. require.True(t, rts.reactors[nodeID].IsRunning())
  83. idx++
  84. }
  85. t.Cleanup(func() {
  86. for _, r := range rts.reactors {
  87. if r.IsRunning() {
  88. require.NoError(t, r.Stop())
  89. require.False(t, r.IsRunning())
  90. }
  91. }
  92. leaktest.Check(t)
  93. })
  94. return rts
  95. }
  96. func (rts *reactorTestSuite) start(t *testing.T) {
  97. rts.network.Start(t)
  98. require.Len(t,
  99. rts.network.RandomNode().PeerManager.Peers(),
  100. rts.numStateStores-1,
  101. "network does not have expected number of nodes")
  102. }
  103. func (rts *reactorTestSuite) waitForEvidence(t *testing.T, evList types.EvidenceList, ids ...types.NodeID) {
  104. t.Helper()
  105. fn := func(pool *evidence.Pool) {
  106. var (
  107. localEvList []types.Evidence
  108. size int64
  109. loops int
  110. )
  111. // wait till we have at least the amount of evidence
  112. // that we expect. if there's more local evidence then
  113. // it doesn't make sense to wait longer and a
  114. // different assertion should catch the resulting error
  115. for len(localEvList) < len(evList) {
  116. // each evidence should not be more than 500 bytes
  117. localEvList, size = pool.PendingEvidence(int64(len(evList) * 500))
  118. if loops == 100 {
  119. t.Log("current wait status:", "|",
  120. "local", len(localEvList), "|",
  121. "waitlist", len(evList), "|",
  122. "size", size)
  123. }
  124. loops++
  125. }
  126. // put the reaped evidence in a map so we can quickly check we got everything
  127. evMap := make(map[string]types.Evidence)
  128. for _, e := range localEvList {
  129. evMap[string(e.Hash())] = e
  130. }
  131. for i, expectedEv := range evList {
  132. gotEv := evMap[string(expectedEv.Hash())]
  133. require.Equalf(
  134. t,
  135. expectedEv,
  136. gotEv,
  137. "evidence for pool %d in pool does not match; got: %v, expected: %v", i, gotEv, expectedEv,
  138. )
  139. }
  140. }
  141. if len(ids) == 1 {
  142. // special case waiting once, just to avoid the extra
  143. // goroutine, in the case that this hits a timeout,
  144. // the stack will be clearer.
  145. fn(rts.pools[ids[0]])
  146. return
  147. }
  148. wg := sync.WaitGroup{}
  149. for id := range rts.pools {
  150. if len(ids) > 0 && !p2ptest.NodeInSlice(id, ids) {
  151. // if an ID list is specified, then we only
  152. // want to wait for those pools that are
  153. // specified in the list, otherwise, wait for
  154. // all pools.
  155. continue
  156. }
  157. wg.Add(1)
  158. go func(id types.NodeID) { defer wg.Done(); fn(rts.pools[id]) }(id)
  159. }
  160. wg.Wait()
  161. }
  162. func (rts *reactorTestSuite) assertEvidenceChannelsEmpty(t *testing.T) {
  163. t.Helper()
  164. for id, r := range rts.reactors {
  165. require.NoError(t, r.Stop(), "stopping reactor #%s", id)
  166. r.Wait()
  167. require.False(t, r.IsRunning(), "reactor #%d did not stop", id)
  168. }
  169. for id, ech := range rts.evidenceChannels {
  170. require.Empty(t, ech.Out, "checking channel #%q", id)
  171. }
  172. }
  173. func createEvidenceList(
  174. t *testing.T,
  175. pool *evidence.Pool,
  176. val types.PrivValidator,
  177. numEvidence int,
  178. ) types.EvidenceList {
  179. t.Helper()
  180. evList := make([]types.Evidence, numEvidence)
  181. for i := 0; i < numEvidence; i++ {
  182. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  183. int64(i+1),
  184. time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC),
  185. val,
  186. evidenceChainID,
  187. )
  188. require.NoError(t, pool.AddEvidence(ev),
  189. "adding evidence it#%d of %d to pool with height %d",
  190. i, numEvidence, pool.State().LastBlockHeight)
  191. evList[i] = ev
  192. }
  193. return evList
  194. }
  195. func TestReactorMultiDisconnect(t *testing.T) {
  196. ctx, cancel := context.WithCancel(context.Background())
  197. defer cancel()
  198. val := types.NewMockPV()
  199. height := int64(numEvidence) + 10
  200. stateDB1 := initializeValidatorState(t, val, height)
  201. stateDB2 := initializeValidatorState(t, val, height)
  202. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 20)
  203. primary := rts.nodes[0]
  204. secondary := rts.nodes[1]
  205. _ = createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  206. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  207. rts.start(t)
  208. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusUp)
  209. // Ensure "disconnecting" the secondary peer from the primary more than once
  210. // is handled gracefully.
  211. primary.PeerManager.Disconnected(secondary.NodeID)
  212. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  213. _, err := primary.PeerManager.TryEvictNext()
  214. require.NoError(t, err)
  215. primary.PeerManager.Disconnected(secondary.NodeID)
  216. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  217. require.Equal(t, secondary.PeerManager.Status(primary.NodeID), p2p.PeerStatusUp)
  218. }
  219. // TestReactorBroadcastEvidence creates an environment of multiple peers that
  220. // are all at the same height. One peer, designated as a primary, gossips all
  221. // evidence to the remaining peers.
  222. func TestReactorBroadcastEvidence(t *testing.T) {
  223. numPeers := 7
  224. // create a stateDB for all test suites (nodes)
  225. stateDBs := make([]sm.Store, numPeers)
  226. val := types.NewMockPV()
  227. // We need all validators saved for heights at least as high as we have
  228. // evidence for.
  229. height := int64(numEvidence) + 10
  230. for i := 0; i < numPeers; i++ {
  231. stateDBs[i] = initializeValidatorState(t, val, height)
  232. }
  233. ctx, cancel := context.WithCancel(context.Background())
  234. defer cancel()
  235. rts := setup(ctx, t, stateDBs, 0)
  236. rts.start(t)
  237. // Create a series of fixtures where each suite contains a reactor and
  238. // evidence pool. In addition, we mark a primary suite and the rest are
  239. // secondaries where each secondary is added as a peer via a PeerUpdate to the
  240. // primary. As a result, the primary will gossip all evidence to each secondary.
  241. primary := rts.network.RandomNode()
  242. secondaries := make([]*p2ptest.Node, 0, len(rts.network.NodeIDs())-1)
  243. secondaryIDs := make([]types.NodeID, 0, cap(secondaries))
  244. for id := range rts.network.Nodes {
  245. if id == primary.NodeID {
  246. continue
  247. }
  248. secondaries = append(secondaries, rts.network.Nodes[id])
  249. secondaryIDs = append(secondaryIDs, id)
  250. }
  251. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  252. // Add each secondary suite (node) as a peer to the primary suite (node). This
  253. // will cause the primary to gossip all evidence to the secondaries.
  254. for _, suite := range secondaries {
  255. rts.peerChans[primary.NodeID] <- p2p.PeerUpdate{
  256. Status: p2p.PeerStatusUp,
  257. NodeID: suite.NodeID,
  258. }
  259. }
  260. // Wait till all secondary suites (reactor) received all evidence from the
  261. // primary suite (node).
  262. rts.waitForEvidence(t, evList, secondaryIDs...)
  263. for _, pool := range rts.pools {
  264. require.Equal(t, numEvidence, int(pool.Size()))
  265. }
  266. rts.assertEvidenceChannelsEmpty(t)
  267. }
  268. // TestReactorSelectiveBroadcast tests a context where we have two reactors
  269. // connected to one another but are at different heights. Reactor 1 which is
  270. // ahead receives a list of evidence.
  271. func TestReactorBroadcastEvidence_Lagging(t *testing.T) {
  272. val := types.NewMockPV()
  273. height1 := int64(numEvidence) + 10
  274. height2 := int64(numEvidence) / 2
  275. // stateDB1 is ahead of stateDB2, where stateDB1 has all heights (1-20) and
  276. // stateDB2 only has heights 1-5.
  277. stateDB1 := initializeValidatorState(t, val, height1)
  278. stateDB2 := initializeValidatorState(t, val, height2)
  279. ctx, cancel := context.WithCancel(context.Background())
  280. defer cancel()
  281. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 100)
  282. rts.start(t)
  283. primary := rts.nodes[0]
  284. secondary := rts.nodes[1]
  285. // Send a list of valid evidence to the first reactor's, the one that is ahead,
  286. // evidence pool.
  287. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  288. // Add each secondary suite (node) as a peer to the primary suite (node). This
  289. // will cause the primary to gossip all evidence to the secondaries.
  290. rts.peerChans[primary.NodeID] <- p2p.PeerUpdate{
  291. Status: p2p.PeerStatusUp,
  292. NodeID: secondary.NodeID,
  293. }
  294. // only ones less than the peers height should make it through
  295. rts.waitForEvidence(t, evList[:height2], secondary.NodeID)
  296. require.Equal(t, numEvidence, int(rts.pools[primary.NodeID].Size()))
  297. require.Equal(t, int(height2), int(rts.pools[secondary.NodeID].Size()))
  298. rts.assertEvidenceChannelsEmpty(t)
  299. }
  300. func TestReactorBroadcastEvidence_Pending(t *testing.T) {
  301. val := types.NewMockPV()
  302. height := int64(10)
  303. stateDB1 := initializeValidatorState(t, val, height)
  304. stateDB2 := initializeValidatorState(t, val, height)
  305. ctx, cancel := context.WithCancel(context.Background())
  306. defer cancel()
  307. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 100)
  308. primary := rts.nodes[0]
  309. secondary := rts.nodes[1]
  310. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  311. // Manually add half the evidence to the secondary which will mark them as
  312. // pending.
  313. for i := 0; i < numEvidence/2; i++ {
  314. require.NoError(t, rts.pools[secondary.NodeID].AddEvidence(evList[i]))
  315. }
  316. // the secondary should have half the evidence as pending
  317. require.Equal(t, numEvidence/2, int(rts.pools[secondary.NodeID].Size()))
  318. rts.start(t)
  319. // The secondary reactor should have received all the evidence ignoring the
  320. // already pending evidence.
  321. rts.waitForEvidence(t, evList, secondary.NodeID)
  322. // check to make sure that all of the evidence has
  323. // propogated
  324. require.Len(t, rts.pools, 2)
  325. assert.EqualValues(t, numEvidence, rts.pools[primary.NodeID].Size(),
  326. "primary node should have all the evidence")
  327. assert.EqualValues(t, numEvidence, rts.pools[secondary.NodeID].Size(),
  328. "secondary nodes should have caught up")
  329. }
  330. func TestReactorBroadcastEvidence_Committed(t *testing.T) {
  331. val := types.NewMockPV()
  332. height := int64(10)
  333. stateDB1 := initializeValidatorState(t, val, height)
  334. stateDB2 := initializeValidatorState(t, val, height)
  335. ctx, cancel := context.WithCancel(context.Background())
  336. defer cancel()
  337. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 0)
  338. primary := rts.nodes[0]
  339. secondary := rts.nodes[1]
  340. // add all evidence to the primary reactor
  341. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  342. // Manually add half the evidence to the secondary which will mark them as
  343. // pending.
  344. for i := 0; i < numEvidence/2; i++ {
  345. require.NoError(t, rts.pools[secondary.NodeID].AddEvidence(evList[i]))
  346. }
  347. // the secondary should have half the evidence as pending
  348. require.Equal(t, numEvidence/2, int(rts.pools[secondary.NodeID].Size()))
  349. state, err := stateDB2.Load()
  350. require.NoError(t, err)
  351. // update the secondary's pool such that all pending evidence is committed
  352. state.LastBlockHeight++
  353. rts.pools[secondary.NodeID].Update(state, evList[:numEvidence/2])
  354. // the secondary should have half the evidence as committed
  355. require.Equal(t, 0, int(rts.pools[secondary.NodeID].Size()))
  356. // start the network and ensure it's configured
  357. rts.start(t)
  358. // The secondary reactor should have received all the evidence ignoring the
  359. // already committed evidence.
  360. rts.waitForEvidence(t, evList[numEvidence/2:], secondary.NodeID)
  361. require.Len(t, rts.pools, 2)
  362. assert.EqualValues(t, numEvidence, rts.pools[primary.NodeID].Size(),
  363. "primary node should have all the evidence")
  364. assert.EqualValues(t, numEvidence/2, rts.pools[secondary.NodeID].Size(),
  365. "secondary nodes should have caught up")
  366. }
  367. func TestReactorBroadcastEvidence_FullyConnected(t *testing.T) {
  368. numPeers := 7
  369. // create a stateDB for all test suites (nodes)
  370. stateDBs := make([]sm.Store, numPeers)
  371. val := types.NewMockPV()
  372. // We need all validators saved for heights at least as high as we have
  373. // evidence for.
  374. height := int64(numEvidence) + 10
  375. for i := 0; i < numPeers; i++ {
  376. stateDBs[i] = initializeValidatorState(t, val, height)
  377. }
  378. ctx, cancel := context.WithCancel(context.Background())
  379. defer cancel()
  380. rts := setup(ctx, t, stateDBs, 0)
  381. rts.start(t)
  382. evList := createEvidenceList(t, rts.pools[rts.network.RandomNode().NodeID], val, numEvidence)
  383. // every suite (reactor) connects to every other suite (reactor)
  384. for outerID, outerChan := range rts.peerChans {
  385. for innerID := range rts.peerChans {
  386. if outerID != innerID {
  387. outerChan <- p2p.PeerUpdate{
  388. Status: p2p.PeerStatusUp,
  389. NodeID: innerID,
  390. }
  391. }
  392. }
  393. }
  394. // wait till all suites (reactors) received all evidence from other suites (reactors)
  395. rts.waitForEvidence(t, evList)
  396. for _, pool := range rts.pools {
  397. require.Equal(t, numEvidence, int(pool.Size()))
  398. // commit state so we do not continue to repeat gossiping the same evidence
  399. state := pool.State()
  400. state.LastBlockHeight++
  401. pool.Update(state, evList)
  402. }
  403. }
  404. // nolint:lll
  405. func TestEvidenceListSerialization(t *testing.T) {
  406. exampleVote := func(msgType byte) *types.Vote {
  407. var stamp, err = time.Parse(types.TimeFormat, "2017-12-25T03:00:01.234Z")
  408. require.NoError(t, err)
  409. return &types.Vote{
  410. Type: tmproto.SignedMsgType(msgType),
  411. Height: 3,
  412. Round: 2,
  413. Timestamp: stamp,
  414. BlockID: types.BlockID{
  415. Hash: tmhash.Sum([]byte("blockID_hash")),
  416. PartSetHeader: types.PartSetHeader{
  417. Total: 1000000,
  418. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  419. },
  420. },
  421. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  422. ValidatorIndex: 56789,
  423. }
  424. }
  425. val := &types.Validator{
  426. Address: crypto.AddressHash([]byte("validator_address")),
  427. VotingPower: 10,
  428. }
  429. valSet := types.NewValidatorSet([]*types.Validator{val})
  430. dupl, err := types.NewDuplicateVoteEvidence(
  431. exampleVote(1),
  432. exampleVote(2),
  433. defaultEvidenceTime,
  434. valSet,
  435. )
  436. require.NoError(t, err)
  437. testCases := map[string]struct {
  438. evidenceList []types.Evidence
  439. expBytes string
  440. }{
  441. "DuplicateVoteEvidence": {
  442. []types.Evidence{dupl},
  443. "0a85020a82020a79080210031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb031279080110031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb03180a200a2a060880dbaae105",
  444. },
  445. }
  446. for name, tc := range testCases {
  447. tc := tc
  448. t.Run(name, func(t *testing.T) {
  449. protoEv := make([]tmproto.Evidence, len(tc.evidenceList))
  450. for i := 0; i < len(tc.evidenceList); i++ {
  451. ev, err := types.EvidenceToProto(tc.evidenceList[i])
  452. require.NoError(t, err)
  453. protoEv[i] = *ev
  454. }
  455. epl := tmproto.EvidenceList{
  456. Evidence: protoEv,
  457. }
  458. bz, err := epl.Marshal()
  459. require.NoError(t, err)
  460. require.Equal(t, tc.expBytes, hex.EncodeToString(bz))
  461. })
  462. }
  463. }