2018-06-21 14:28:34 +00:00
|
|
|
# This file is part of the Trezor project.
|
2017-12-12 15:40:11 +00:00
|
|
|
#
|
2019-05-29 16:44:09 +00:00
|
|
|
# Copyright (C) 2012-2019 SatoshiLabs and contributors
|
2017-12-12 15:40:11 +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-12-12 15:40:11 +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>.
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
"""
|
|
|
|
Extremely minimal streaming codec for a subset of protobuf.
|
|
|
|
Supports uint32, bytes, string, embedded message and repeated fields.
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
For de-serializing (loading) protobuf types, object with `Reader` interface is required.
|
|
|
|
For serializing (dumping) protobuf types, object with `Writer` interface is required.
|
|
|
|
"""
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
import logging
|
2017-12-12 15:40:11 +00:00
|
|
|
from io import BytesIO
|
2019-08-22 14:44:23 +00:00
|
|
|
from typing import (
|
|
|
|
Any,
|
|
|
|
Callable,
|
|
|
|
Dict,
|
|
|
|
Iterable,
|
|
|
|
Iterator,
|
|
|
|
List,
|
|
|
|
Optional,
|
|
|
|
Tuple,
|
|
|
|
Type,
|
|
|
|
TypeVar,
|
|
|
|
Union,
|
|
|
|
)
|
|
|
|
|
|
|
|
from typing_extensions import Protocol
|
|
|
|
|
|
|
|
FieldType = Union[
|
|
|
|
"EnumType",
|
|
|
|
Type["MessageType"],
|
|
|
|
Type["UVarintType"],
|
|
|
|
Type["SVarintType"],
|
|
|
|
Type["BoolType"],
|
|
|
|
Type["UnicodeType"],
|
|
|
|
Type["BytesType"],
|
|
|
|
]
|
|
|
|
FieldInfo = Tuple[str, FieldType, int]
|
|
|
|
MT = TypeVar("MT", bound="MessageType")
|
|
|
|
|
|
|
|
|
|
|
|
class Reader(Protocol):
|
|
|
|
def readinto(self, buffer: bytearray) -> int:
|
|
|
|
"""
|
|
|
|
Reads exactly `len(buffer)` bytes into `buffer`. Returns number of bytes read,
|
|
|
|
or 0 if it cannot read that much.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
class Writer(Protocol):
|
|
|
|
def write(self, buffer: bytes) -> int:
|
|
|
|
"""
|
|
|
|
Writes all bytes from `buffer`, or raises `EOFError`
|
|
|
|
"""
|
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
|
|
|
|
_UVARINT_BUFFER = bytearray(1)
|
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def load_uvarint(reader: Reader) -> int:
|
2017-12-12 15:40:11 +00:00
|
|
|
buffer = _UVARINT_BUFFER
|
|
|
|
result = 0
|
|
|
|
shift = 0
|
|
|
|
byte = 0x80
|
2019-08-22 14:44:23 +00:00
|
|
|
bytes_read = 0
|
2017-12-12 15:40:11 +00:00
|
|
|
while byte & 0x80:
|
|
|
|
if reader.readinto(buffer) == 0:
|
2019-08-22 14:44:23 +00:00
|
|
|
if bytes_read > 0:
|
|
|
|
raise IOError("Interrupted UVarint")
|
|
|
|
else:
|
|
|
|
raise EOFError
|
|
|
|
bytes_read += 1
|
2017-12-12 15:40:11 +00:00
|
|
|
byte = buffer[0]
|
|
|
|
result += (byte & 0x7F) << shift
|
|
|
|
shift += 7
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def dump_uvarint(writer: Writer, n: int) -> None:
|
2018-04-11 09:15:38 +00:00
|
|
|
if n < 0:
|
|
|
|
raise ValueError("Cannot dump signed value, convert it to unsigned first.")
|
2017-12-12 15:40:11 +00:00
|
|
|
buffer = _UVARINT_BUFFER
|
2019-08-22 14:44:23 +00:00
|
|
|
shifted = 1
|
2017-12-12 15:40:11 +00:00
|
|
|
while shifted:
|
|
|
|
shifted = n >> 7
|
|
|
|
buffer[0] = (n & 0x7F) | (0x80 if shifted else 0x00)
|
|
|
|
writer.write(buffer)
|
|
|
|
n = shifted
|
|
|
|
|
|
|
|
|
2018-04-11 09:15:38 +00:00
|
|
|
# protobuf interleaved signed encoding:
|
|
|
|
# https://developers.google.com/protocol-buffers/docs/encoding#structure
|
|
|
|
# the idea is to save the sign in LSbit instead of twos-complement.
|
|
|
|
# so counting up, you go: 0, -1, 1, -2, 2, ... (as the first bit changes, sign flips)
|
|
|
|
#
|
|
|
|
# To achieve this with a twos-complement number:
|
|
|
|
# 1. shift left by 1, leaving LSbit free
|
2018-05-07 12:09:56 +00:00
|
|
|
# 2. if the number is negative, do bitwise negation.
|
2018-04-11 09:15:38 +00:00
|
|
|
# This keeps positive number the same, and converts negative from twos-complement
|
2018-05-07 12:09:56 +00:00
|
|
|
# to the appropriate value, while setting the sign bit.
|
2018-04-11 09:15:38 +00:00
|
|
|
#
|
|
|
|
# The original algorithm makes use of the fact that arithmetic (signed) shift
|
2018-05-07 12:09:56 +00:00
|
|
|
# keeps the sign bits, so for a n-bit number, (x >> n) gets us "all sign bits".
|
|
|
|
# Then you can take "number XOR all-sign-bits", which is XOR 0 (identity) for positive
|
|
|
|
# and XOR 1 (bitwise negation) for negative. Cute and efficient.
|
2018-04-11 09:15:38 +00:00
|
|
|
#
|
2018-05-07 12:09:56 +00:00
|
|
|
# But this is harder in Python because we don't natively know the bit size of the number.
|
|
|
|
# So we have to branch on whether the number is negative.
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2018-08-13 16:21:24 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def sint_to_uint(sint: int) -> int:
|
2018-04-11 09:15:38 +00:00
|
|
|
res = sint << 1
|
|
|
|
if sint < 0:
|
|
|
|
res = ~res
|
|
|
|
return res
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2018-04-11 09:15:38 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def uint_to_sint(uint: int) -> int:
|
2018-04-11 09:15:38 +00:00
|
|
|
sign = uint & 1
|
|
|
|
res = uint >> 1
|
|
|
|
if sign:
|
|
|
|
res = ~res
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
|
|
|
class UVarintType:
|
2017-12-12 15:40:11 +00:00
|
|
|
WIRE_TYPE = 0
|
|
|
|
|
|
|
|
|
2018-04-11 09:15:38 +00:00
|
|
|
class SVarintType:
|
2018-01-30 14:04:24 +00:00
|
|
|
WIRE_TYPE = 0
|
|
|
|
|
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
class BoolType:
|
|
|
|
WIRE_TYPE = 0
|
|
|
|
|
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
class EnumType:
|
|
|
|
WIRE_TYPE = 0
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def __init__(self, enum_name: str, enum_values: Iterable[int]) -> None:
|
2019-08-02 17:06:01 +00:00
|
|
|
self.enum_name = enum_name
|
|
|
|
self.enum_values = enum_values
|
|
|
|
|
|
|
|
def validate(self, fvalue: int) -> int:
|
|
|
|
if fvalue not in self.enum_values:
|
|
|
|
# raise TypeError("Invalid enum value")
|
2020-02-13 14:08:22 +00:00
|
|
|
LOG.info("Value {} unknown for type {}".format(fvalue, self.enum_name))
|
2019-08-02 17:06:01 +00:00
|
|
|
return fvalue
|
|
|
|
|
|
|
|
def to_str(self, fvalue: int) -> str:
|
|
|
|
from . import messages
|
|
|
|
|
|
|
|
module = getattr(messages, self.enum_name)
|
|
|
|
for name in dir(module):
|
|
|
|
if name.startswith("__"):
|
|
|
|
continue
|
|
|
|
if getattr(module, name) == fvalue:
|
|
|
|
return name
|
|
|
|
else:
|
|
|
|
raise TypeError("Invalid enum value")
|
|
|
|
|
|
|
|
def from_str(self, fstr: str) -> int:
|
|
|
|
try:
|
|
|
|
from . import messages
|
|
|
|
|
|
|
|
module = getattr(messages, self.enum_name)
|
|
|
|
ivalue = getattr(module, fstr)
|
|
|
|
if isinstance(ivalue, int):
|
|
|
|
return ivalue
|
|
|
|
else:
|
|
|
|
raise TypeError("Invalid enum value")
|
|
|
|
except AttributeError:
|
|
|
|
raise TypeError("Invalid enum value") from None
|
|
|
|
|
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
class BytesType:
|
|
|
|
WIRE_TYPE = 2
|
|
|
|
|
|
|
|
|
|
|
|
class UnicodeType:
|
|
|
|
WIRE_TYPE = 2
|
|
|
|
|
|
|
|
|
|
|
|
class MessageType:
|
|
|
|
WIRE_TYPE = 2
|
2018-09-20 11:53:21 +00:00
|
|
|
|
|
|
|
@classmethod
|
2019-08-22 14:44:23 +00:00
|
|
|
def get_fields(cls) -> Dict[int, FieldInfo]:
|
2018-09-20 11:53:21 +00:00
|
|
|
return {}
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-11-14 14:36:33 +00:00
|
|
|
@classmethod
|
|
|
|
def get_field_type(cls, name: str) -> Optional[FieldType]:
|
|
|
|
for fname, ftype, flags in cls.get_fields().values():
|
|
|
|
if fname == name:
|
|
|
|
return ftype
|
|
|
|
return None
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def __init__(self, **kwargs: Any) -> None:
|
2017-12-12 15:40:11 +00:00
|
|
|
for kw in kwargs:
|
|
|
|
setattr(self, kw, kwargs[kw])
|
2017-12-19 09:21:31 +00:00
|
|
|
self._fill_missing()
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def __eq__(self, rhs: Any) -> bool:
|
2018-08-13 16:21:24 +00:00
|
|
|
return self.__class__ is rhs.__class__ and self.__dict__ == rhs.__dict__
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def __repr__(self) -> str:
|
2018-01-07 17:07:13 +00:00
|
|
|
d = {}
|
|
|
|
for key, value in self.__dict__.items():
|
|
|
|
if value is None or value == []:
|
|
|
|
continue
|
|
|
|
d[key] = value
|
2018-08-13 16:21:24 +00:00
|
|
|
return "<%s: %s>" % (self.__class__.__name__, d)
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def __iter__(self) -> Iterator[str]:
|
2018-11-02 16:06:04 +00:00
|
|
|
return iter(self.keys())
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def keys(self) -> Iterator[str]:
|
2018-10-30 13:57:17 +00:00
|
|
|
return (name for name, _, _ in self.get_fields().values())
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def __getitem__(self, key: str) -> Any:
|
2018-10-30 13:57:17 +00:00
|
|
|
return getattr(self, key)
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def _fill_missing(self) -> None:
|
2017-12-12 15:40:11 +00:00
|
|
|
# fill missing fields
|
2018-09-20 11:53:21 +00:00
|
|
|
for fname, ftype, fflags in self.get_fields().values():
|
2017-12-19 09:21:31 +00:00
|
|
|
if not hasattr(self, fname):
|
|
|
|
if fflags & FLAG_REPEATED:
|
|
|
|
setattr(self, fname, [])
|
|
|
|
else:
|
|
|
|
setattr(self, fname, None)
|
2017-12-12 15:40:11 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def ByteSize(self) -> int:
|
2017-12-12 15:40:11 +00:00
|
|
|
data = BytesIO()
|
|
|
|
dump_message(data, self)
|
|
|
|
return len(data.getvalue())
|
|
|
|
|
|
|
|
|
|
|
|
class LimitedReader:
|
2019-08-22 14:44:23 +00:00
|
|
|
def __init__(self, reader: Reader, limit: int) -> None:
|
2017-12-12 15:40:11 +00:00
|
|
|
self.reader = reader
|
|
|
|
self.limit = limit
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def readinto(self, buf: bytearray) -> int:
|
2017-12-12 15:40:11 +00:00
|
|
|
if self.limit < len(buf):
|
2019-08-22 14:44:23 +00:00
|
|
|
return 0
|
2017-12-12 15:40:11 +00:00
|
|
|
else:
|
|
|
|
nread = self.reader.readinto(buf)
|
|
|
|
self.limit -= nread
|
|
|
|
return nread
|
|
|
|
|
|
|
|
|
|
|
|
class CountingWriter:
|
2019-08-22 14:44:23 +00:00
|
|
|
def __init__(self) -> None:
|
2017-12-12 15:40:11 +00:00
|
|
|
self.size = 0
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def write(self, buf: bytes) -> int:
|
2017-12-12 15:40:11 +00:00
|
|
|
nwritten = len(buf)
|
|
|
|
self.size += nwritten
|
|
|
|
return nwritten
|
|
|
|
|
|
|
|
|
|
|
|
FLAG_REPEATED = 1
|
|
|
|
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def decode_packed_array_field(ftype: FieldType, reader: Reader) -> List[Any]:
|
|
|
|
length = load_uvarint(reader)
|
|
|
|
packed_reader = LimitedReader(reader, length)
|
|
|
|
values = []
|
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
values.append(decode_varint_field(ftype, packed_reader))
|
|
|
|
except EOFError:
|
|
|
|
pass
|
|
|
|
return values
|
|
|
|
|
|
|
|
|
|
|
|
def decode_varint_field(ftype: FieldType, reader: Reader) -> Union[int, bool]:
|
|
|
|
value = load_uvarint(reader)
|
|
|
|
if ftype is UVarintType:
|
|
|
|
return value
|
|
|
|
elif ftype is SVarintType:
|
|
|
|
return uint_to_sint(value)
|
|
|
|
elif ftype is BoolType:
|
|
|
|
return bool(value)
|
|
|
|
elif isinstance(ftype, EnumType):
|
|
|
|
return ftype.validate(value)
|
|
|
|
else:
|
|
|
|
raise TypeError # not a varint field or unknown type
|
|
|
|
|
|
|
|
|
|
|
|
def decode_length_delimited_field(
|
|
|
|
ftype: FieldType, reader: Reader
|
|
|
|
) -> Union[bytes, str, MessageType]:
|
|
|
|
value = load_uvarint(reader)
|
|
|
|
if ftype is BytesType:
|
|
|
|
buf = bytearray(value)
|
|
|
|
reader.readinto(buf)
|
|
|
|
return bytes(buf)
|
|
|
|
elif ftype is UnicodeType:
|
|
|
|
buf = bytearray(value)
|
|
|
|
reader.readinto(buf)
|
|
|
|
return buf.decode()
|
|
|
|
elif isinstance(ftype, type) and issubclass(ftype, MessageType):
|
|
|
|
return load_message(LimitedReader(reader, value), ftype)
|
|
|
|
else:
|
|
|
|
raise TypeError # field type is unknown
|
|
|
|
|
|
|
|
|
|
|
|
def load_message(reader: Reader, msg_type: Type[MT]) -> MT:
|
2018-09-20 11:53:21 +00:00
|
|
|
fields = msg_type.get_fields()
|
2017-12-12 15:40:11 +00:00
|
|
|
msg = msg_type()
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
fkey = load_uvarint(reader)
|
|
|
|
except EOFError:
|
|
|
|
break # no more fields to load
|
|
|
|
|
|
|
|
ftag = fkey >> 3
|
|
|
|
wtype = fkey & 7
|
|
|
|
|
|
|
|
field = fields.get(ftag, None)
|
|
|
|
|
|
|
|
if field is None: # unknown field, skip it
|
|
|
|
if wtype == 0:
|
|
|
|
load_uvarint(reader)
|
|
|
|
elif wtype == 2:
|
|
|
|
ivalue = load_uvarint(reader)
|
|
|
|
reader.readinto(bytearray(ivalue))
|
|
|
|
else:
|
|
|
|
raise ValueError
|
|
|
|
continue
|
|
|
|
|
|
|
|
fname, ftype, fflags = field
|
2019-08-22 14:44:23 +00:00
|
|
|
|
|
|
|
if wtype == 2 and ftype.WIRE_TYPE == 0 and fflags & FLAG_REPEATED:
|
|
|
|
# packed array
|
|
|
|
fvalues = decode_packed_array_field(ftype, reader)
|
|
|
|
|
|
|
|
elif wtype != ftype.WIRE_TYPE:
|
2017-12-12 15:40:11 +00:00
|
|
|
raise TypeError # parsed wire type differs from the schema
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
elif wtype == 2:
|
|
|
|
fvalues = [decode_length_delimited_field(ftype, reader)]
|
|
|
|
|
|
|
|
elif wtype == 0:
|
|
|
|
fvalues = [decode_varint_field(ftype, reader)]
|
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
else:
|
2019-08-22 14:44:23 +00:00
|
|
|
raise TypeError # unknown wire type
|
2017-12-12 15:40:11 +00:00
|
|
|
|
|
|
|
if fflags & FLAG_REPEATED:
|
2017-12-19 09:21:31 +00:00
|
|
|
pvalue = getattr(msg, fname)
|
2019-08-22 14:44:23 +00:00
|
|
|
pvalue.extend(fvalues)
|
2017-12-12 15:40:11 +00:00
|
|
|
fvalue = pvalue
|
2019-08-22 14:44:23 +00:00
|
|
|
elif len(fvalues) != 1:
|
|
|
|
raise ValueError("Unexpected multiple values in non-repeating field")
|
|
|
|
else:
|
|
|
|
fvalue = fvalues[0]
|
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
setattr(msg, fname, fvalue)
|
|
|
|
|
|
|
|
return msg
|
|
|
|
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def dump_message(writer: Writer, msg: MessageType) -> None:
|
2017-12-12 15:40:11 +00:00
|
|
|
repvalue = [0]
|
|
|
|
mtype = msg.__class__
|
2018-09-20 11:53:21 +00:00
|
|
|
fields = mtype.get_fields()
|
2017-12-12 15:40:11 +00:00
|
|
|
|
|
|
|
for ftag in fields:
|
2018-03-20 12:00:36 +00:00
|
|
|
fname, ftype, fflags = fields[ftag]
|
2017-12-12 15:40:11 +00:00
|
|
|
|
|
|
|
fvalue = getattr(msg, fname, None)
|
|
|
|
if fvalue is None:
|
|
|
|
continue
|
|
|
|
|
|
|
|
fkey = (ftag << 3) | ftype.WIRE_TYPE
|
|
|
|
|
|
|
|
if not fflags & FLAG_REPEATED:
|
|
|
|
repvalue[0] = fvalue
|
|
|
|
fvalue = repvalue
|
|
|
|
|
|
|
|
for svalue in fvalue:
|
|
|
|
dump_uvarint(writer, fkey)
|
|
|
|
|
|
|
|
if ftype is UVarintType:
|
|
|
|
dump_uvarint(writer, svalue)
|
|
|
|
|
2018-04-11 09:15:38 +00:00
|
|
|
elif ftype is SVarintType:
|
|
|
|
dump_uvarint(writer, sint_to_uint(svalue))
|
2018-01-30 14:04:24 +00:00
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
elif ftype is BoolType:
|
|
|
|
dump_uvarint(writer, int(svalue))
|
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
elif isinstance(ftype, EnumType):
|
|
|
|
dump_uvarint(writer, ftype.validate(svalue))
|
|
|
|
|
2017-12-12 15:40:11 +00:00
|
|
|
elif ftype is BytesType:
|
|
|
|
dump_uvarint(writer, len(svalue))
|
|
|
|
writer.write(svalue)
|
|
|
|
|
|
|
|
elif ftype is UnicodeType:
|
2019-08-29 11:56:09 +00:00
|
|
|
svalue_bytes = svalue.encode()
|
|
|
|
dump_uvarint(writer, len(svalue_bytes))
|
|
|
|
writer.write(svalue_bytes)
|
2017-12-12 15:40:11 +00:00
|
|
|
|
|
|
|
elif issubclass(ftype, MessageType):
|
|
|
|
counter = CountingWriter()
|
|
|
|
dump_message(counter, svalue)
|
|
|
|
dump_uvarint(writer, counter.size)
|
|
|
|
dump_message(writer, svalue)
|
|
|
|
|
|
|
|
else:
|
|
|
|
raise TypeError
|
2018-04-20 13:52:47 +00:00
|
|
|
|
|
|
|
|
2018-08-13 16:21:24 +00:00
|
|
|
def format_message(
|
|
|
|
pb: MessageType,
|
|
|
|
indent: int = 0,
|
|
|
|
sep: str = " " * 4,
|
|
|
|
truncate_after: Optional[int] = 256,
|
|
|
|
truncate_to: Optional[int] = 64,
|
|
|
|
) -> str:
|
2019-08-22 14:44:23 +00:00
|
|
|
def mostly_printable(bytes: bytes) -> bool:
|
2018-05-09 16:01:51 +00:00
|
|
|
if not bytes:
|
|
|
|
return True
|
2018-10-01 12:01:33 +00:00
|
|
|
printable = sum(1 for byte in bytes if 0x20 <= byte <= 0x7E)
|
2018-05-09 16:01:51 +00:00
|
|
|
return printable / len(bytes) > 0.8
|
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
def pformat(name: str, value: Any, indent: int) -> str:
|
2018-04-20 13:52:47 +00:00
|
|
|
level = sep * indent
|
|
|
|
leadin = sep * (indent + 1)
|
2019-11-14 14:36:33 +00:00
|
|
|
ftype = pb.get_field_type(name)
|
2019-08-02 17:06:01 +00:00
|
|
|
|
2018-04-20 13:52:47 +00:00
|
|
|
if isinstance(value, MessageType):
|
|
|
|
return format_message(value, indent, sep)
|
2019-08-02 17:06:01 +00:00
|
|
|
|
2018-04-20 13:52:47 +00:00
|
|
|
if isinstance(value, list):
|
2018-05-09 16:01:51 +00:00
|
|
|
# short list of simple values
|
2019-08-22 14:44:23 +00:00
|
|
|
if not value or isinstance(value, (UVarintType, SVarintType, BoolType)):
|
2018-05-09 16:01:51 +00:00
|
|
|
return repr(value)
|
|
|
|
|
|
|
|
# long list, one line per entry
|
2018-08-13 16:21:24 +00:00
|
|
|
lines = ["[", level + "]"]
|
2019-08-02 17:06:01 +00:00
|
|
|
lines[1:1] = [leadin + pformat(name, x, indent + 1) + "," for x in value]
|
2018-08-13 16:21:24 +00:00
|
|
|
return "\n".join(lines)
|
2019-08-02 17:06:01 +00:00
|
|
|
|
2018-04-20 13:52:47 +00:00
|
|
|
if isinstance(value, dict):
|
2018-08-13 16:21:24 +00:00
|
|
|
lines = ["{"]
|
2018-04-20 13:52:47 +00:00
|
|
|
for key, val in sorted(value.items()):
|
|
|
|
if val is None or val == []:
|
|
|
|
continue
|
2019-08-02 17:06:01 +00:00
|
|
|
lines.append(leadin + key + ": " + pformat(key, val, indent + 1) + ",")
|
2018-08-13 16:21:24 +00:00
|
|
|
lines.append(level + "}")
|
|
|
|
return "\n".join(lines)
|
2019-08-02 17:06:01 +00:00
|
|
|
|
2018-05-09 16:01:51 +00:00
|
|
|
if isinstance(value, (bytes, bytearray)):
|
|
|
|
length = len(value)
|
2018-08-13 16:21:24 +00:00
|
|
|
suffix = ""
|
2018-05-09 16:01:51 +00:00
|
|
|
if truncate_after and length > truncate_after:
|
2018-08-13 16:21:24 +00:00
|
|
|
suffix = "..."
|
|
|
|
value = value[: truncate_to or 0]
|
2018-05-09 16:01:51 +00:00
|
|
|
if mostly_printable(value):
|
|
|
|
output = repr(value)
|
|
|
|
else:
|
2018-09-12 22:44:08 +00:00
|
|
|
output = "0x" + value.hex()
|
2018-08-13 16:21:24 +00:00
|
|
|
return "{} bytes {}{}".format(length, output, suffix)
|
2018-04-20 13:52:47 +00:00
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
if isinstance(value, int) and isinstance(ftype, EnumType):
|
2020-02-13 14:08:22 +00:00
|
|
|
try:
|
|
|
|
return "{} ({})".format(ftype.to_str(value), value)
|
|
|
|
except TypeError:
|
|
|
|
return str(value)
|
2019-08-02 17:06:01 +00:00
|
|
|
|
2018-04-20 13:52:47 +00:00
|
|
|
return repr(value)
|
|
|
|
|
2018-08-13 16:21:24 +00:00
|
|
|
return "{name} ({size} bytes) {content}".format(
|
2018-04-23 10:58:30 +00:00
|
|
|
name=pb.__class__.__name__,
|
|
|
|
size=pb.ByteSize(),
|
2019-08-02 17:06:01 +00:00
|
|
|
content=pformat("", pb.__dict__, indent),
|
2018-04-23 10:58:30 +00:00
|
|
|
)
|
2018-08-21 13:58:26 +00:00
|
|
|
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def value_to_proto(ftype: FieldType, value: Any) -> Any:
|
2019-08-02 17:06:01 +00:00
|
|
|
if isinstance(ftype, type) and issubclass(ftype, MessageType):
|
2018-08-21 13:58:26 +00:00
|
|
|
raise TypeError("value_to_proto only converts simple values")
|
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
if isinstance(ftype, EnumType):
|
|
|
|
if isinstance(value, str):
|
|
|
|
return ftype.from_str(value)
|
2019-05-06 11:26:23 +00:00
|
|
|
else:
|
|
|
|
return int(value)
|
2018-08-21 13:58:26 +00:00
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
if ftype in (UVarintType, SVarintType):
|
|
|
|
return int(value)
|
|
|
|
|
2018-08-21 13:58:26 +00:00
|
|
|
if ftype is BoolType:
|
|
|
|
return bool(value)
|
|
|
|
|
|
|
|
if ftype is UnicodeType:
|
|
|
|
return str(value)
|
|
|
|
|
|
|
|
if ftype is BytesType:
|
|
|
|
if isinstance(value, str):
|
2018-09-12 22:44:08 +00:00
|
|
|
return bytes.fromhex(value)
|
2018-08-21 13:58:26 +00:00
|
|
|
elif isinstance(value, bytes):
|
|
|
|
return value
|
|
|
|
else:
|
|
|
|
raise TypeError("can't convert {} value to bytes".format(type(value)))
|
|
|
|
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def dict_to_proto(message_type: Type[MT], d: Dict[str, Any]) -> MT:
|
2018-08-21 13:58:26 +00:00
|
|
|
params = {}
|
2018-09-20 11:53:21 +00:00
|
|
|
for fname, ftype, fflags in message_type.get_fields().values():
|
2018-08-21 13:58:26 +00:00
|
|
|
repeated = fflags & FLAG_REPEATED
|
|
|
|
value = d.get(fname)
|
|
|
|
if value is None:
|
|
|
|
continue
|
|
|
|
|
|
|
|
if not repeated:
|
|
|
|
value = [value]
|
|
|
|
|
2019-08-02 17:06:01 +00:00
|
|
|
if isinstance(ftype, type) and issubclass(ftype, MessageType):
|
2019-08-22 14:44:23 +00:00
|
|
|
function = dict_to_proto # type: Callable[[Any, Any], Any]
|
2018-08-21 13:58:26 +00:00
|
|
|
else:
|
|
|
|
function = value_to_proto
|
|
|
|
|
|
|
|
newvalue = [function(ftype, v) for v in value]
|
|
|
|
|
|
|
|
if not repeated:
|
|
|
|
newvalue = newvalue[0]
|
|
|
|
|
|
|
|
params[fname] = newvalue
|
|
|
|
return message_type(**params)
|
2018-11-02 16:06:04 +00:00
|
|
|
|
|
|
|
|
2019-08-22 14:44:23 +00:00
|
|
|
def to_dict(msg: MessageType, hexlify_bytes: bool = True) -> Dict[str, Any]:
|
2019-11-14 14:36:33 +00:00
|
|
|
def convert_value(ftype: FieldType, value: Any) -> Any:
|
2019-02-19 16:14:12 +00:00
|
|
|
if hexlify_bytes and isinstance(value, bytes):
|
|
|
|
return value.hex()
|
|
|
|
elif isinstance(value, MessageType):
|
|
|
|
return to_dict(value, hexlify_bytes)
|
|
|
|
elif isinstance(value, list):
|
2019-11-14 14:36:33 +00:00
|
|
|
return [convert_value(ftype, v) for v in value]
|
|
|
|
elif isinstance(value, int) and isinstance(ftype, EnumType):
|
2020-02-13 14:08:22 +00:00
|
|
|
try:
|
|
|
|
return ftype.to_str(value)
|
|
|
|
except TypeError:
|
|
|
|
return value
|
2019-02-19 16:14:12 +00:00
|
|
|
else:
|
|
|
|
return value
|
|
|
|
|
2018-11-02 16:06:04 +00:00
|
|
|
res = {}
|
|
|
|
for key, value in msg.__dict__.items():
|
|
|
|
if value is None or value == []:
|
|
|
|
continue
|
2019-11-14 14:36:33 +00:00
|
|
|
res[key] = convert_value(msg.get_field_type(key), value)
|
2019-02-19 16:14:12 +00:00
|
|
|
|
2018-11-02 16:06:04 +00:00
|
|
|
return res
|