diff --git a/include/opendht/infohash.h b/include/opendht/infohash.h index 4a98a231..acc7a335 100644 --- a/include/opendht/infohash.h +++ b/include/opendht/infohash.h @@ -188,6 +188,8 @@ public: */ static InfoHash get(const uint8_t* data, size_t data_len); + static InfoHash getRandom(); + friend std::ostream& operator<< (std::ostream& s, const InfoHash& h); std::string toString() const; diff --git a/python/opendht.pyx b/python/opendht.pyx index 265c3baa..f93384d2 100644 --- a/python/opendht.pyx +++ b/python/opendht.pyx @@ -70,6 +70,8 @@ cdef extern from "opendht/infohash.h" namespace "dht": unsigned commonBits(InfoHash a, InfoHash b) @staticmethod InfoHash get(string s) + @staticmethod + InfoHash getRandom() cdef extern from "opendht/value.h" namespace "dht": cdef cppclass Value: @@ -183,6 +185,11 @@ cdef class PyInfoHash(_WithID): h = PyInfoHash() h._infohash = InfoHash.get(key.encode()) return h + @staticmethod + def getRandom(): + h = PyInfoHash() + h._infohash = InfoHash.getRandom() + return h cdef class PyNode(_WithID): cdef shared_ptr[Node] _node diff --git a/python/tools/benchmark.py b/python/tools/benchmark.py index 1d592fcd..147bf68e 100755 --- a/python/tools/benchmark.py +++ b/python/tools/benchmark.py @@ -12,7 +12,7 @@ sys.path.append('..') from opendht import * def random_hash(): - return PyInfoHash(''.join(random.SystemRandom().choice(string.hexdigits) for _ in range(40)).encode()) + return PyInfoHash.getRandom() def start_cluster(i): global procs diff --git a/src/infohash.cpp b/src/infohash.cpp index 14cbdfb3..7835c8b3 100644 --- a/src/infohash.cpp +++ b/src/infohash.cpp @@ -29,11 +29,13 @@ */ #include "infohash.h" +#include "rng.h" extern "C" { #include } +#include #include #include @@ -69,6 +71,16 @@ InfoHash::get(const uint8_t* data, size_t data_len) throw std::string("Error while hashing"); } +InfoHash +InfoHash::getRandom() +{ + InfoHash h; + crypto::random_device rdev; + std::uniform_int_distribution rand_byte; + std::generate(h.begin(), h.end(), std::bind(rand_byte, std::ref(rdev))); + return h; +} + std::string InfoHash::toString() const {