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