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
1.9 KiB

  1. package p2p
  2. import (
  3. "bytes"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. "github.com/tendermint/tendermint/crypto/ed25519"
  10. tmrand "github.com/tendermint/tendermint/libs/rand"
  11. )
  12. func TestLoadOrGenNodeKey(t *testing.T) {
  13. filePath := filepath.Join(os.TempDir(), tmrand.Str(12)+"_peer_id.json")
  14. nodeKey, err := LoadOrGenNodeKey(filePath)
  15. assert.Nil(t, err)
  16. nodeKey2, err := LoadOrGenNodeKey(filePath)
  17. assert.Nil(t, err)
  18. assert.Equal(t, nodeKey, nodeKey2)
  19. }
  20. func TestLoadNodeKey(t *testing.T) {
  21. filePath := filepath.Join(os.TempDir(), tmrand.Str(12)+"_peer_id.json")
  22. _, err := LoadNodeKey(filePath)
  23. assert.True(t, os.IsNotExist(err))
  24. _, err = LoadOrGenNodeKey(filePath)
  25. require.NoError(t, err)
  26. nodeKey, err := LoadNodeKey(filePath)
  27. assert.NoError(t, err)
  28. assert.NotNil(t, nodeKey)
  29. }
  30. func TestNodeKeySaveAs(t *testing.T) {
  31. filePath := filepath.Join(os.TempDir(), tmrand.Str(12)+"_peer_id.json")
  32. assert.NoFileExists(t, filePath)
  33. privKey := ed25519.GenPrivKey()
  34. nodeKey := &NodeKey{
  35. PrivKey: privKey,
  36. }
  37. err := nodeKey.SaveAs(filePath)
  38. assert.NoError(t, err)
  39. assert.FileExists(t, filePath)
  40. }
  41. //----------------------------------------------------------
  42. func padBytes(bz []byte, targetBytes int) []byte {
  43. return append(bz, bytes.Repeat([]byte{0xFF}, targetBytes-len(bz))...)
  44. }
  45. func TestPoWTarget(t *testing.T) {
  46. targetBytes := 20
  47. cases := []struct {
  48. difficulty uint
  49. target []byte
  50. }{
  51. {0, padBytes([]byte{}, targetBytes)},
  52. {1, padBytes([]byte{127}, targetBytes)},
  53. {8, padBytes([]byte{0}, targetBytes)},
  54. {9, padBytes([]byte{0, 127}, targetBytes)},
  55. {10, padBytes([]byte{0, 63}, targetBytes)},
  56. {16, padBytes([]byte{0, 0}, targetBytes)},
  57. {17, padBytes([]byte{0, 0, 127}, targetBytes)},
  58. }
  59. for _, c := range cases {
  60. assert.Equal(t, MakePoWTarget(c.difficulty, 20*8), c.target)
  61. }
  62. }