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.

561 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(ctx, 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(ctx, 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. })
  93. t.Cleanup(leaktest.Check(t))
  94. return rts
  95. }
  96. func (rts *reactorTestSuite) start(ctx context.Context, t *testing.T) {
  97. rts.network.Start(ctx, 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 createEvidenceList(
  163. t *testing.T,
  164. pool *evidence.Pool,
  165. val types.PrivValidator,
  166. numEvidence int,
  167. ) types.EvidenceList {
  168. t.Helper()
  169. evList := make([]types.Evidence, numEvidence)
  170. for i := 0; i < numEvidence; i++ {
  171. ev := types.NewMockDuplicateVoteEvidenceWithValidator(
  172. int64(i+1),
  173. time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC),
  174. val,
  175. evidenceChainID,
  176. )
  177. require.NoError(t, pool.AddEvidence(ev),
  178. "adding evidence it#%d of %d to pool with height %d",
  179. i, numEvidence, pool.State().LastBlockHeight)
  180. evList[i] = ev
  181. }
  182. return evList
  183. }
  184. func TestReactorMultiDisconnect(t *testing.T) {
  185. ctx, cancel := context.WithCancel(context.Background())
  186. defer cancel()
  187. val := types.NewMockPV()
  188. height := int64(numEvidence) + 10
  189. stateDB1 := initializeValidatorState(t, val, height)
  190. stateDB2 := initializeValidatorState(t, val, height)
  191. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 20)
  192. primary := rts.nodes[0]
  193. secondary := rts.nodes[1]
  194. _ = createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  195. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  196. rts.start(ctx, t)
  197. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusUp)
  198. // Ensure "disconnecting" the secondary peer from the primary more than once
  199. // is handled gracefully.
  200. primary.PeerManager.Disconnected(ctx, secondary.NodeID)
  201. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  202. _, err := primary.PeerManager.TryEvictNext()
  203. require.NoError(t, err)
  204. primary.PeerManager.Disconnected(ctx, secondary.NodeID)
  205. require.Equal(t, primary.PeerManager.Status(secondary.NodeID), p2p.PeerStatusDown)
  206. require.Equal(t, secondary.PeerManager.Status(primary.NodeID), p2p.PeerStatusUp)
  207. }
  208. // TestReactorBroadcastEvidence creates an environment of multiple peers that
  209. // are all at the same height. One peer, designated as a primary, gossips all
  210. // evidence to the remaining peers.
  211. func TestReactorBroadcastEvidence(t *testing.T) {
  212. numPeers := 7
  213. // create a stateDB for all test suites (nodes)
  214. stateDBs := make([]sm.Store, numPeers)
  215. val := types.NewMockPV()
  216. // We need all validators saved for heights at least as high as we have
  217. // evidence for.
  218. height := int64(numEvidence) + 10
  219. for i := 0; i < numPeers; i++ {
  220. stateDBs[i] = initializeValidatorState(t, val, height)
  221. }
  222. ctx, cancel := context.WithCancel(context.Background())
  223. defer cancel()
  224. rts := setup(ctx, t, stateDBs, 0)
  225. rts.start(ctx, t)
  226. // Create a series of fixtures where each suite contains a reactor and
  227. // evidence pool. In addition, we mark a primary suite and the rest are
  228. // secondaries where each secondary is added as a peer via a PeerUpdate to the
  229. // primary. As a result, the primary will gossip all evidence to each secondary.
  230. primary := rts.network.RandomNode()
  231. secondaries := make([]*p2ptest.Node, 0, len(rts.network.NodeIDs())-1)
  232. secondaryIDs := make([]types.NodeID, 0, cap(secondaries))
  233. for id := range rts.network.Nodes {
  234. if id == primary.NodeID {
  235. continue
  236. }
  237. secondaries = append(secondaries, rts.network.Nodes[id])
  238. secondaryIDs = append(secondaryIDs, id)
  239. }
  240. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  241. // Add each secondary suite (node) as a peer to the primary suite (node). This
  242. // will cause the primary to gossip all evidence to the secondaries.
  243. for _, suite := range secondaries {
  244. rts.peerChans[primary.NodeID] <- p2p.PeerUpdate{
  245. Status: p2p.PeerStatusUp,
  246. NodeID: suite.NodeID,
  247. }
  248. }
  249. // Wait till all secondary suites (reactor) received all evidence from the
  250. // primary suite (node).
  251. rts.waitForEvidence(t, evList, secondaryIDs...)
  252. for _, pool := range rts.pools {
  253. require.Equal(t, numEvidence, int(pool.Size()))
  254. }
  255. }
  256. // TestReactorSelectiveBroadcast tests a context where we have two reactors
  257. // connected to one another but are at different heights. Reactor 1 which is
  258. // ahead receives a list of evidence.
  259. func TestReactorBroadcastEvidence_Lagging(t *testing.T) {
  260. val := types.NewMockPV()
  261. height1 := int64(numEvidence) + 10
  262. height2 := int64(numEvidence) / 2
  263. // stateDB1 is ahead of stateDB2, where stateDB1 has all heights (1-20) and
  264. // stateDB2 only has heights 1-5.
  265. stateDB1 := initializeValidatorState(t, val, height1)
  266. stateDB2 := initializeValidatorState(t, val, height2)
  267. ctx, cancel := context.WithCancel(context.Background())
  268. defer cancel()
  269. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 100)
  270. rts.start(ctx, t)
  271. primary := rts.nodes[0]
  272. secondary := rts.nodes[1]
  273. // Send a list of valid evidence to the first reactor's, the one that is ahead,
  274. // evidence pool.
  275. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  276. // Add each secondary suite (node) as a peer to the primary suite (node). This
  277. // will cause the primary to gossip all evidence to the secondaries.
  278. rts.peerChans[primary.NodeID] <- p2p.PeerUpdate{
  279. Status: p2p.PeerStatusUp,
  280. NodeID: secondary.NodeID,
  281. }
  282. // only ones less than the peers height should make it through
  283. rts.waitForEvidence(t, evList[:height2], secondary.NodeID)
  284. require.Equal(t, numEvidence, int(rts.pools[primary.NodeID].Size()))
  285. require.Equal(t, int(height2), int(rts.pools[secondary.NodeID].Size()))
  286. }
  287. func TestReactorBroadcastEvidence_Pending(t *testing.T) {
  288. val := types.NewMockPV()
  289. height := int64(10)
  290. stateDB1 := initializeValidatorState(t, val, height)
  291. stateDB2 := initializeValidatorState(t, val, height)
  292. ctx, cancel := context.WithCancel(context.Background())
  293. defer cancel()
  294. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 100)
  295. primary := rts.nodes[0]
  296. secondary := rts.nodes[1]
  297. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  298. // Manually add half the evidence to the secondary which will mark them as
  299. // pending.
  300. for i := 0; i < numEvidence/2; i++ {
  301. require.NoError(t, rts.pools[secondary.NodeID].AddEvidence(evList[i]))
  302. }
  303. // the secondary should have half the evidence as pending
  304. require.Equal(t, numEvidence/2, int(rts.pools[secondary.NodeID].Size()))
  305. rts.start(ctx, t)
  306. // The secondary reactor should have received all the evidence ignoring the
  307. // already pending evidence.
  308. rts.waitForEvidence(t, evList, secondary.NodeID)
  309. // check to make sure that all of the evidence has
  310. // propogated
  311. require.Len(t, rts.pools, 2)
  312. assert.EqualValues(t, numEvidence, rts.pools[primary.NodeID].Size(),
  313. "primary node should have all the evidence")
  314. assert.EqualValues(t, numEvidence, rts.pools[secondary.NodeID].Size(),
  315. "secondary nodes should have caught up")
  316. }
  317. func TestReactorBroadcastEvidence_Committed(t *testing.T) {
  318. val := types.NewMockPV()
  319. height := int64(10)
  320. stateDB1 := initializeValidatorState(t, val, height)
  321. stateDB2 := initializeValidatorState(t, val, height)
  322. ctx, cancel := context.WithCancel(context.Background())
  323. defer cancel()
  324. rts := setup(ctx, t, []sm.Store{stateDB1, stateDB2}, 0)
  325. primary := rts.nodes[0]
  326. secondary := rts.nodes[1]
  327. // add all evidence to the primary reactor
  328. evList := createEvidenceList(t, rts.pools[primary.NodeID], val, numEvidence)
  329. // Manually add half the evidence to the secondary which will mark them as
  330. // pending.
  331. for i := 0; i < numEvidence/2; i++ {
  332. require.NoError(t, rts.pools[secondary.NodeID].AddEvidence(evList[i]))
  333. }
  334. // the secondary should have half the evidence as pending
  335. require.Equal(t, numEvidence/2, int(rts.pools[secondary.NodeID].Size()))
  336. state, err := stateDB2.Load()
  337. require.NoError(t, err)
  338. // update the secondary's pool such that all pending evidence is committed
  339. state.LastBlockHeight++
  340. rts.pools[secondary.NodeID].Update(state, evList[:numEvidence/2])
  341. // the secondary should have half the evidence as committed
  342. require.Equal(t, 0, int(rts.pools[secondary.NodeID].Size()))
  343. // start the network and ensure it's configured
  344. rts.start(ctx, t)
  345. // The secondary reactor should have received all the evidence ignoring the
  346. // already committed evidence.
  347. rts.waitForEvidence(t, evList[numEvidence/2:], secondary.NodeID)
  348. require.Len(t, rts.pools, 2)
  349. assert.EqualValues(t, numEvidence, rts.pools[primary.NodeID].Size(),
  350. "primary node should have all the evidence")
  351. assert.EqualValues(t, numEvidence/2, rts.pools[secondary.NodeID].Size(),
  352. "secondary nodes should have caught up")
  353. }
  354. func TestReactorBroadcastEvidence_FullyConnected(t *testing.T) {
  355. numPeers := 7
  356. // create a stateDB for all test suites (nodes)
  357. stateDBs := make([]sm.Store, numPeers)
  358. val := types.NewMockPV()
  359. // We need all validators saved for heights at least as high as we have
  360. // evidence for.
  361. height := int64(numEvidence) + 10
  362. for i := 0; i < numPeers; i++ {
  363. stateDBs[i] = initializeValidatorState(t, val, height)
  364. }
  365. ctx, cancel := context.WithCancel(context.Background())
  366. defer cancel()
  367. rts := setup(ctx, t, stateDBs, 0)
  368. rts.start(ctx, t)
  369. evList := createEvidenceList(t, rts.pools[rts.network.RandomNode().NodeID], val, numEvidence)
  370. // every suite (reactor) connects to every other suite (reactor)
  371. for outerID, outerChan := range rts.peerChans {
  372. for innerID := range rts.peerChans {
  373. if outerID != innerID {
  374. outerChan <- p2p.PeerUpdate{
  375. Status: p2p.PeerStatusUp,
  376. NodeID: innerID,
  377. }
  378. }
  379. }
  380. }
  381. // wait till all suites (reactors) received all evidence from other suites (reactors)
  382. rts.waitForEvidence(t, evList)
  383. for _, pool := range rts.pools {
  384. require.Equal(t, numEvidence, int(pool.Size()))
  385. // commit state so we do not continue to repeat gossiping the same evidence
  386. state := pool.State()
  387. state.LastBlockHeight++
  388. pool.Update(state, evList)
  389. }
  390. }
  391. func TestEvidenceListSerialization(t *testing.T) {
  392. exampleVote := func(msgType byte) *types.Vote {
  393. var stamp, err = time.Parse(types.TimeFormat, "2017-12-25T03:00:01.234Z")
  394. require.NoError(t, err)
  395. return &types.Vote{
  396. Type: tmproto.SignedMsgType(msgType),
  397. Height: 3,
  398. Round: 2,
  399. Timestamp: stamp,
  400. BlockID: types.BlockID{
  401. Hash: tmhash.Sum([]byte("blockID_hash")),
  402. PartSetHeader: types.PartSetHeader{
  403. Total: 1000000,
  404. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  405. },
  406. },
  407. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  408. ValidatorIndex: 56789,
  409. }
  410. }
  411. val := &types.Validator{
  412. Address: crypto.AddressHash([]byte("validator_address")),
  413. VotingPower: 10,
  414. }
  415. valSet := types.NewValidatorSet([]*types.Validator{val})
  416. dupl, err := types.NewDuplicateVoteEvidence(
  417. exampleVote(1),
  418. exampleVote(2),
  419. defaultEvidenceTime,
  420. valSet,
  421. )
  422. require.NoError(t, err)
  423. testCases := map[string]struct {
  424. evidenceList []types.Evidence
  425. expBytes string
  426. }{
  427. "DuplicateVoteEvidence": {
  428. []types.Evidence{dupl},
  429. "0a85020a82020a79080210031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb031279080110031802224a0a208b01023386c371778ecb6368573e539afc3cc860ec3a2f614e54fe5652f4fc80122608c0843d122072db3d959635dff1bb567bedaa70573392c5159666a3f8caf11e413aac52207a2a0b08b1d381d20510809dca6f32146af1f4111082efb388211bc72c55bcd61e9ac3d538d5bb03180a200a2a060880dbaae105",
  430. },
  431. }
  432. for name, tc := range testCases {
  433. tc := tc
  434. t.Run(name, func(t *testing.T) {
  435. protoEv := make([]tmproto.Evidence, len(tc.evidenceList))
  436. for i := 0; i < len(tc.evidenceList); i++ {
  437. ev, err := types.EvidenceToProto(tc.evidenceList[i])
  438. require.NoError(t, err)
  439. protoEv[i] = *ev
  440. }
  441. epl := tmproto.EvidenceList{
  442. Evidence: protoEv,
  443. }
  444. bz, err := epl.Marshal()
  445. require.NoError(t, err)
  446. require.Equal(t, tc.expBytes, hex.EncodeToString(bz))
  447. })
  448. }
  449. }