Skip to content

Commit

Permalink
avoid duplicate randomly generated keys/peer-ids
Browse files Browse the repository at this point in the history
This implements #4 from #43.

fixes #43
  • Loading branch information
Stebalien committed Jul 22, 2019
1 parent cfafedb commit 1df1ff7
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 13 deletions.
10 changes: 3 additions & 7 deletions core/test/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,16 @@ package test
import (
"math/rand"
"sync/atomic"
"time"

ci "github.com/libp2p/go-libp2p-core/crypto"
)

var generatedPairs int64 = 0
var globalSeed int64

func RandTestKeyPair(typ, bits int) (ci.PrivKey, ci.PubKey, error) {
seed := time.Now().UnixNano()

// workaround for low time resolution
seed += atomic.AddInt64(&generatedPairs, 1) << 32

return SeededTestKeyPair(typ, bits, time.Now().UnixNano())
seed := atomic.AddInt64(&globalSeed, 1)
return SeededTestKeyPair(typ, bits, seed)
}

func SeededTestKeyPair(typ, bits int, seed int64) (ci.PrivKey, ci.PubKey, error) {
Expand Down
7 changes: 1 addition & 6 deletions core/test/peer.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
package test

import (
"io"
"math/rand"
"testing"
"time"

"github.com/libp2p/go-libp2p-core/peer"

mh "github.com/multiformats/go-multihash"
)

func RandPeerID() (peer.ID, error) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
buf := make([]byte, 16)
if _, err := io.ReadFull(r, buf); err != nil {
return "", err
}
rand.Read(buf)
h, _ := mh.Sum(buf, mh.SHA2_256, -1)
return peer.ID(h), nil
}
Expand Down

0 comments on commit 1df1ff7

Please sign in to comment.