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.

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