Browse Source

avoid duplicate randomly generated keys/peer-ids

This implements #4 from #43.

fixes #43
pull/1683/head
Steven Allen 5 years ago
parent
commit
1df1ff755d
  1. 10
      core/test/crypto.go
  2. 7
      core/test/peer.go

10
core/test/crypto.go

@ -3,20 +3,16 @@ package test
import ( import (
"math/rand" "math/rand"
"sync/atomic" "sync/atomic"
"time"
ci "github.com/libp2p/go-libp2p-core/crypto" 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) { func RandTestKeyPair(typ, bits int) (ci.PrivKey, ci.PubKey, error) {
seed := time.Now().UnixNano()
// workaround for low time resolution // workaround for low time resolution
seed += atomic.AddInt64(&generatedPairs, 1) << 32 seed := atomic.AddInt64(&globalSeed, 1)
return SeededTestKeyPair(typ, bits, seed)
return SeededTestKeyPair(typ, bits, time.Now().UnixNano())
} }
func SeededTestKeyPair(typ, bits int, seed int64) (ci.PrivKey, ci.PubKey, error) { func SeededTestKeyPair(typ, bits int, seed int64) (ci.PrivKey, ci.PubKey, error) {

7
core/test/peer.go

@ -1,10 +1,8 @@
package test package test
import ( import (
"io"
"math/rand" "math/rand"
"testing" "testing"
"time"
"github.com/libp2p/go-libp2p-core/peer" "github.com/libp2p/go-libp2p-core/peer"
@ -12,11 +10,8 @@ import (
) )
func RandPeerID() (peer.ID, error) { func RandPeerID() (peer.ID, error) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
buf := make([]byte, 16) buf := make([]byte, 16)
if _, err := io.ReadFull(r, buf); err != nil { rand.Read(buf)
return "", err
}
h, _ := mh.Sum(buf, mh.SHA2_256, -1) h, _ := mh.Sum(buf, mh.SHA2_256, -1)
return peer.ID(h), nil return peer.ID(h), nil
} }

Loading…
Cancel
Save