github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/p2p/key_test.go (about)

     1  package p2p
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"path/filepath"
     7  	"testing"
     8  
     9  	"github.com/gnolang/gno/tm2/pkg/random"
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestLoadOrGenNodeKey(t *testing.T) {
    14  	t.Parallel()
    15  
    16  	filePath := filepath.Join(os.TempDir(), random.RandStr(12)+"_peer_id.json")
    17  
    18  	nodeKey, err := LoadOrGenNodeKey(filePath)
    19  	assert.Nil(t, err)
    20  
    21  	nodeKey2, err := LoadOrGenNodeKey(filePath)
    22  	assert.Nil(t, err)
    23  
    24  	assert.Equal(t, nodeKey, nodeKey2)
    25  }
    26  
    27  // ----------------------------------------------------------
    28  
    29  func padBytes(bz []byte, targetBytes int) []byte {
    30  	return append(bz, bytes.Repeat([]byte{0xFF}, targetBytes-len(bz))...)
    31  }
    32  
    33  func TestPoWTarget(t *testing.T) {
    34  	t.Parallel()
    35  
    36  	targetBytes := 20
    37  	cases := []struct {
    38  		difficulty uint
    39  		target     []byte
    40  	}{
    41  		{0, padBytes([]byte{}, targetBytes)},
    42  		{1, padBytes([]byte{127}, targetBytes)},
    43  		{8, padBytes([]byte{0}, targetBytes)},
    44  		{9, padBytes([]byte{0, 127}, targetBytes)},
    45  		{10, padBytes([]byte{0, 63}, targetBytes)},
    46  		{16, padBytes([]byte{0, 0}, targetBytes)},
    47  		{17, padBytes([]byte{0, 0, 127}, targetBytes)},
    48  	}
    49  
    50  	for _, c := range cases {
    51  		assert.Equal(t, MakePoWTarget(c.difficulty, 20*8), c.target)
    52  	}
    53  }