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.

81 lines
2.2 KiB

  1. package p2p
  2. import (
  3. "strings"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/require"
  7. "github.com/tendermint/tendermint/crypto/ed25519"
  8. "github.com/tendermint/tendermint/types"
  9. dbm "github.com/tendermint/tm-db"
  10. )
  11. func TestPeerScoring(t *testing.T) {
  12. // coppied from p2p_test shared variables
  13. selfKey := ed25519.GenPrivKeyFromSecret([]byte{0xf9, 0x1b, 0x08, 0xaa, 0x38, 0xee, 0x34, 0xdd})
  14. selfID := types.NodeIDFromPubKey(selfKey.PubKey())
  15. // create a mock peer manager
  16. db := dbm.NewMemDB()
  17. peerManager, err := NewPeerManager(selfID, db, PeerManagerOptions{})
  18. require.NoError(t, err)
  19. defer peerManager.Close()
  20. // create a fake node
  21. id := types.NodeID(strings.Repeat("a1", 20))
  22. added, err := peerManager.Add(NodeAddress{NodeID: id, Protocol: "memory"})
  23. require.NoError(t, err)
  24. require.True(t, added)
  25. t.Run("Synchronous", func(t *testing.T) {
  26. // update the manager and make sure it's correct
  27. require.EqualValues(t, 0, peerManager.Scores()[id])
  28. // add a bunch of good status updates and watch things increase.
  29. for i := 1; i < 10; i++ {
  30. peerManager.processPeerEvent(PeerUpdate{
  31. NodeID: id,
  32. Status: PeerStatusGood,
  33. })
  34. require.EqualValues(t, i, peerManager.Scores()[id])
  35. }
  36. // watch the corresponding decreases respond to update
  37. for i := 10; i == 0; i-- {
  38. peerManager.processPeerEvent(PeerUpdate{
  39. NodeID: id,
  40. Status: PeerStatusBad,
  41. })
  42. require.EqualValues(t, i, peerManager.Scores()[id])
  43. }
  44. })
  45. t.Run("AsynchronousIncrement", func(t *testing.T) {
  46. start := peerManager.Scores()[id]
  47. pu := peerManager.Subscribe()
  48. defer pu.Close()
  49. pu.SendUpdate(PeerUpdate{
  50. NodeID: id,
  51. Status: PeerStatusGood,
  52. })
  53. require.Eventually(t,
  54. func() bool { return start+1 == peerManager.Scores()[id] },
  55. time.Second,
  56. time.Millisecond,
  57. "startAt=%d score=%d", start, peerManager.Scores()[id])
  58. })
  59. t.Run("AsynchronousDecrement", func(t *testing.T) {
  60. start := peerManager.Scores()[id]
  61. pu := peerManager.Subscribe()
  62. defer pu.Close()
  63. pu.SendUpdate(PeerUpdate{
  64. NodeID: id,
  65. Status: PeerStatusBad,
  66. })
  67. require.Eventually(t,
  68. func() bool { return start-1 == peerManager.Scores()[id] },
  69. time.Second,
  70. time.Millisecond,
  71. "startAt=%d score=%d", start, peerManager.Scores()[id])
  72. })
  73. }