python-trezor/tests/test_entropy.py

32 lines
872 B
Python
Raw Normal View History

2014-01-29 10:09:24 -08:00
import unittest
import common
import math
import trezorlib.messages_pb2 as proto
import trezorlib.types_pb2 as proto_types
2014-01-29 10:09:24 -08:00
def entropy(data):
2014-02-05 15:34:58 -08:00
counts = {}
for c in data:
if c in counts:
counts[c] += 1
else:
counts[c] = 1
2014-01-29 10:09:24 -08:00
e = 0
2014-02-15 11:31:34 -08:00
for _, v in counts.iteritems():
2014-02-05 15:34:58 -08:00
p = 1.0 * v / len(data)
2014-01-29 10:09:24 -08:00
e -= p * math.log(p, 256)
return e
class TestEntropy(common.TrezorTest):
def test_entropy(self):
for l in [0, 1, 2, 3, 4, 5, 8, 9, 16, 17, 32, 33, 64, 65, 128, 129, 256, 257, 512, 513, 1024]:
self.client.set_expected_responses([proto.ButtonRequest(code=proto_types.ButtonRequest_Other), proto.Entropy()])
2014-01-29 10:09:24 -08:00
ent = self.client.get_entropy(l)
self.assertTrue(len(ent) >= l)
print 'entropy = ', entropy(ent)
if __name__ == '__main__':
unittest.main()