2018-06-21 14:28:34 +00:00
|
|
|
# This file is part of the Trezor project.
|
2017-01-03 18:40:05 +00:00
|
|
|
#
|
2019-05-29 16:44:09 +00:00
|
|
|
# Copyright (C) 2012-2019 SatoshiLabs and contributors
|
2017-01-03 18:40:05 +00:00
|
|
|
#
|
|
|
|
# This library is free software: you can redistribute it and/or modify
|
2018-06-21 14:28:34 +00:00
|
|
|
# it under the terms of the GNU Lesser General Public License version 3
|
|
|
|
# as published by the Free Software Foundation.
|
2017-01-03 18:40:05 +00:00
|
|
|
#
|
|
|
|
# This library is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser General Public License for more details.
|
|
|
|
#
|
2018-06-21 14:28:34 +00:00
|
|
|
# You should have received a copy of the License along with this library.
|
|
|
|
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
|
2016-05-20 20:27:20 +00:00
|
|
|
|
2014-02-21 01:33:23 +00:00
|
|
|
import math
|
|
|
|
|
2018-08-13 13:38:04 +00:00
|
|
|
import pytest
|
|
|
|
|
2023-08-15 15:58:32 +00:00
|
|
|
from trezorlib import messages as m
|
|
|
|
from trezorlib import misc
|
2024-11-15 16:31:22 +00:00
|
|
|
from trezorlib.debuglink import SessionDebugWrapper as Session
|
2018-08-13 13:38:04 +00:00
|
|
|
|
2022-06-21 13:31:47 +00:00
|
|
|
ENTROPY_LENGTHS_POW2 = [2**l for l in range(10)]
|
|
|
|
ENTROPY_LENGTHS_POW2_1 = [2**l + 1 for l in range(10)]
|
2018-08-13 13:38:04 +00:00
|
|
|
|
|
|
|
ENTROPY_LENGTHS = ENTROPY_LENGTHS_POW2 + ENTROPY_LENGTHS_POW2_1
|
2014-02-21 01:33:23 +00:00
|
|
|
|
2017-06-23 19:31:42 +00:00
|
|
|
|
2014-02-21 01:33:23 +00:00
|
|
|
def entropy(data):
|
|
|
|
counts = {}
|
|
|
|
for c in data:
|
2018-08-13 13:38:04 +00:00
|
|
|
counts[c] = counts.get(c, 0) + 1
|
2014-02-21 01:33:23 +00:00
|
|
|
e = 0
|
2018-08-13 13:38:04 +00:00
|
|
|
for v in counts.values():
|
|
|
|
p = v / len(data)
|
2014-02-21 01:33:23 +00:00
|
|
|
e -= p * math.log(p, 256)
|
|
|
|
return e
|
|
|
|
|
2017-06-23 19:31:42 +00:00
|
|
|
|
2018-08-13 13:38:04 +00:00
|
|
|
@pytest.mark.parametrize("entropy_length", ENTROPY_LENGTHS)
|
2024-11-15 16:31:22 +00:00
|
|
|
def test_entropy(session: Session, entropy_length):
|
|
|
|
with session:
|
|
|
|
session.set_expected_responses(
|
2020-09-15 11:06:41 +00:00
|
|
|
[m.ButtonRequest(code=m.ButtonRequestType.ProtectCall), m.Entropy]
|
2018-08-13 13:38:04 +00:00
|
|
|
)
|
2024-11-15 16:31:22 +00:00
|
|
|
ent = misc.get_entropy(session, entropy_length)
|
2018-08-13 13:38:04 +00:00
|
|
|
assert len(ent) == entropy_length
|
2021-09-27 10:13:51 +00:00
|
|
|
print(f"{entropy_length} bytes: entropy = {entropy(ent)}")
|