From 75fe46d067ed0b42a0deafe88a6a1ea2271d2cc8 Mon Sep 17 00:00:00 2001 From: matejcik Date: Mon, 6 May 2019 13:26:23 +0200 Subject: [PATCH] trezorlib: allow text values for enums in dict_to_proto --- python/trezorlib/protobuf.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/python/trezorlib/protobuf.py b/python/trezorlib/protobuf.py index 187a06786..21d49b887 100644 --- a/python/trezorlib/protobuf.py +++ b/python/trezorlib/protobuf.py @@ -364,12 +364,32 @@ def format_message( ) +_ALL_ENUMS = {} + + +def _make_all_enums(): + if not _ALL_ENUMS: + import inspect + from . import messages + + for attr in messages.__dict__.values(): + if not inspect.ismodule(attr): + continue + for name in dir(attr): + value = getattr(attr, name) + if isinstance(value, int): + _ALL_ENUMS[name] = value + + def value_to_proto(ftype, value): if issubclass(ftype, MessageType): raise TypeError("value_to_proto only converts simple values") if ftype in (UVarintType, SVarintType): - return int(value) + if isinstance(value, str) and value in _ALL_ENUMS: + return _ALL_ENUMS[value] + else: + return int(value) if ftype is BoolType: return bool(value) @@ -387,6 +407,8 @@ def value_to_proto(ftype, value): def dict_to_proto(message_type, d): + _make_all_enums() + params = {} for fname, ftype, fflags in message_type.get_fields().values(): repeated = fflags & FLAG_REPEATED