Module diem.jsonrpc

This package provides a client for connecting to Diem JSON-RPC Service API

Create a client connect to Diem Testnet and calls get_metadata API:


>>> from diem import jsonrpc, testnet
>>> client = jsonrpc.Client(testnet.JSON_RPC_URL)
>>> client.get_metadata()
version: 3300304
timestamp: 1601492912847973
chain_id: 2

See Diem JSON-RPC API SPEC for more details

Expand source code
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0

""" This package provides a client for connecting to Diem JSON-RPC Service API

Create a client connect to Diem Testnet and calls get_metadata API:

```python3

>>> from diem import jsonrpc, testnet
>>> client = jsonrpc.Client(testnet.JSON_RPC_URL)
>>> client.get_metadata()
version: 3300304
timestamp: 1601492912847973
chain_id: 2

```

See [Diem JSON-RPC API SPEC](https://github.com/diem/diem/blob/master/json-rpc/json-rpc-spec.md) for more details

"""

from .client import (
    Client,
    State,
    Retry,
    RequestStrategy,
    RequestWithBackups,
    # Exceptions
    JsonRpcError,
    NetworkError,
    InvalidServerResponse,
    StaleResponseError,
    TransactionHashMismatchError,
    TransactionExecutionFailed,
    TransactionExpired,
    WaitForTransactionTimeout,
    AccountNotFoundError,
)
from .jsonrpc_pb2 import (
    Amount,
    Metadata,
    CurrencyInfo,
    Account,
    AccountRole,
    Transaction,
    TransactionData,
    Script,
    Event,
    EventData,
    VMStatus,
    StateProof,
    AccountStateWithProof,
    AccountStateProof,
)
from .constants import (
    # AccountRole#type field values
    ACCOUNT_ROLE_UNKNOWN,
    ACCOUNT_ROLE_CHILD_VASP,
    ACCOUNT_ROLE_PARENT_VASP,
    ACCOUNT_ROLE_DESIGNATED_DEALER,
    # EventData#type field values
    EVENT_DATA_UNKNOWN,
    EVENT_DATA_BURN,
    EVENT_DATA_CANCEL_BURN,
    EVENT_DATA_MINT,
    EVENT_DATA_TO_XDX_EXCHANGE_RATE_UPDATE,
    EVENT_DATA_PREBURN,
    EVENT_DATA_RECEIVED_PAYMENT,
    EVENT_DATA_SENT_PAYMENT,
    EVENT_DATA_NEW_EPOCH,
    EVENT_DATA_NEW_BLOCK,
    EVENT_DATA_RECEIVED_MINT,
    EVENT_DATA_COMPLIANCE_KEY_ROTATION,
    EVENT_DATA_BASE_URL_ROTATION,
    EVENT_DATA_CREATE_ACCOUNT,
    EVENT_DATA_ADMIN_TRANSACTION,
    # VMStatus#type field values
    VM_STATUS_EXECUTED,
    VM_STATUS_OUT_OF_GAS,
    VM_STATUS_MOVE_ABORT,
    VM_STATUS_EXECUTION_FAILURE,
    VM_STATUS_MISC_ERROR,
    # TransactionData#type field values
    TRANSACTION_DATA_BLOCK_METADATA,
    TRANSACTION_DATA_WRITE_SET,
    TRANSACTION_DATA_USER,
    TRANSACTION_DATA_UNKNOWN,
    # Script#type field values, only set unknown type here,
    # other types, plese see https://github.com/diem/diem/blob/master/language/stdlib/transaction_scripts/doc/transaction_script_documentation.md for all available script names.
    SCRIPT_UNKNOWN,
)

Sub-modules

diem.jsonrpc.client
diem.jsonrpc.constants

Defines constants for enum type values …

diem.jsonrpc.jsonrpc_pb2

Generated protocol buffer code.

Classes

class Account (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var ADDRESS_FIELD_NUMBER
var AUTHENTICATION_KEY_FIELD_NUMBER
var BALANCES_FIELD_NUMBER
var DELEGATED_KEY_ROTATION_CAPABILITY_FIELD_NUMBER
var DELEGATED_WITHDRAWAL_CAPABILITY_FIELD_NUMBER
var DESCRIPTOR
var IS_FROZEN_FIELD_NUMBER
var RECEIVED_EVENTS_KEY_FIELD_NUMBER
var ROLE_FIELD_NUMBER
var SENT_EVENTS_KEY_FIELD_NUMBER
var SEQUENCE_NUMBER_FIELD_NUMBER
var VERSION_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var address

Getter for address.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var authentication_key

Getter for authentication_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var balances

Getter for balances.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var delegated_key_rotation_capability

Getter for delegated_key_rotation_capability.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var delegated_withdrawal_capability

Getter for delegated_withdrawal_capability.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var is_frozen

Getter for is_frozen.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var received_events_key

Getter for received_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var role

Getter for role.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var sent_events_key

Getter for sent_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var sequence_number

Getter for sequence_number.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var version

Getter for version.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class AccountRole (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var BASE_URL_FIELD_NUMBER
var BASE_URL_ROTATION_EVENTS_KEY_FIELD_NUMBER
var COMPLIANCE_KEY_FIELD_NUMBER
var COMPLIANCE_KEY_ROTATION_EVENTS_KEY_FIELD_NUMBER
var DESCRIPTOR
var EXPIRATION_TIME_FIELD_NUMBER
var HUMAN_NAME_FIELD_NUMBER
var NUM_CHILDREN_FIELD_NUMBER
var PARENT_VASP_ADDRESS_FIELD_NUMBER
var PREBURN_BALANCES_FIELD_NUMBER
var PREBURN_QUEUES_FIELD_NUMBER
var RECEIVED_MINT_EVENTS_KEY_FIELD_NUMBER
var TYPE_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var base_url

Getter for base_url.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var base_url_rotation_events_key

Getter for base_url_rotation_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var compliance_key

Getter for compliance_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var compliance_key_rotation_events_key

Getter for compliance_key_rotation_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var expiration_time

Getter for expiration_time.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var human_name

Getter for human_name.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var num_children

Getter for num_children.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var parent_vasp_address

Getter for parent_vasp_address.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var preburn_balances

Getter for preburn_balances.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var preburn_queues

Getter for preburn_queues.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var received_mint_events_key

Getter for received_mint_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var type

Getter for type.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class AccountStateProof (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var DESCRIPTOR
var LEDGER_INFO_TO_TRANSACTION_INFO_PROOF_FIELD_NUMBER
var TRANSACTION_INFO_FIELD_NUMBER
var TRANSACTION_INFO_TO_ACCOUNT_PROOF_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var ledger_info_to_transaction_info_proof

Getter for ledger_info_to_transaction_info_proof.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var transaction_info

Getter for transaction_info.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var transaction_info_to_account_proof

Getter for transaction_info_to_account_proof.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class AccountStateWithProof (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var BLOB_FIELD_NUMBER
var DESCRIPTOR
var PROOF_FIELD_NUMBER
var VERSION_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var blob

Getter for blob.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var proof

Getter for proof.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var version

Getter for version.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class Amount (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var AMOUNT_FIELD_NUMBER
var CURRENCY_FIELD_NUMBER
var DESCRIPTOR

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var amount

Getter for amount.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var currency

Getter for currency.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class CurrencyInfo (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var BURN_EVENTS_KEY_FIELD_NUMBER
var CANCEL_BURN_EVENTS_KEY_FIELD_NUMBER
var CODE_FIELD_NUMBER
var DESCRIPTOR
var EXCHANGE_RATE_UPDATE_EVENTS_KEY_FIELD_NUMBER
var FRACTIONAL_PART_FIELD_NUMBER
var MINT_EVENTS_KEY_FIELD_NUMBER
var PREBURN_EVENTS_KEY_FIELD_NUMBER
var SCALING_FACTOR_FIELD_NUMBER
var TO_XDX_EXCHANGE_RATE_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var burn_events_key

Getter for burn_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var cancel_burn_events_key

Getter for cancel_burn_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var code

Getter for code.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var exchange_rate_update_events_key

Getter for exchange_rate_update_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var fractional_part

Getter for fractional_part.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var mint_events_key

Getter for mint_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var preburn_events_key

Getter for preburn_events_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var scaling_factor

Getter for scaling_factor.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var to_xdx_exchange_rate

Getter for to_xdx_exchange_rate.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class Event (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var DATA_FIELD_NUMBER
var DESCRIPTOR
var KEY_FIELD_NUMBER
var SEQUENCE_NUMBER_FIELD_NUMBER
var TRANSACTION_VERSION_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var data

Getter for data.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var key

Getter for key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var sequence_number

Getter for sequence_number.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var transaction_version

Getter for transaction_version.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class EventData (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var AMOUNT_FIELD_NUMBER
var BYTES_FIELD_NUMBER
var COMMITTED_TIMESTAMP_SECS_FIELD_NUMBER
var CREATED_ADDRESS_FIELD_NUMBER
var CURRENCY_CODE_FIELD_NUMBER
var DESCRIPTOR
var DESTINATION_ADDRESS_FIELD_NUMBER
var EPOCH_FIELD_NUMBER
var METADATA_FIELD_NUMBER
var NEW_BASE_URL_FIELD_NUMBER
var NEW_COMPLIANCE_PUBLIC_KEY_FIELD_NUMBER
var NEW_TO_XDX_EXCHANGE_RATE_FIELD_NUMBER
var PREBURN_ADDRESS_FIELD_NUMBER
var PROPOSED_TIME_FIELD_NUMBER
var PROPOSER_FIELD_NUMBER
var RECEIVER_FIELD_NUMBER
var ROLE_ID_FIELD_NUMBER
var ROUND_FIELD_NUMBER
var SENDER_FIELD_NUMBER
var TIME_ROTATED_SECONDS_FIELD_NUMBER
var TYPE_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var amount

Getter for amount.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var bytes

Getter for bytes.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var committed_timestamp_secs

Getter for committed_timestamp_secs.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var created_address

Getter for created_address.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var currency_code

Getter for currency_code.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var destination_address

Getter for destination_address.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var epoch

Getter for epoch.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var metadata

Getter for metadata.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var new_base_url

Getter for new_base_url.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var new_compliance_public_key

Getter for new_compliance_public_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var new_to_xdx_exchange_rate

Getter for new_to_xdx_exchange_rate.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var preburn_address

Getter for preburn_address.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var proposed_time

Getter for proposed_time.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var proposer

Getter for proposer.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var receiver

Getter for receiver.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var role_id

Getter for role_id.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var round

Getter for round.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var sender

Getter for sender.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var time_rotated_seconds

Getter for time_rotated_seconds.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var type

Getter for type.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class Metadata (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var ACCUMULATOR_ROOT_HASH_FIELD_NUMBER
var CHAIN_ID_FIELD_NUMBER
var DESCRIPTOR
var DIEM_VERSION_FIELD_NUMBER
var DUAL_ATTESTATION_LIMIT_FIELD_NUMBER
var MODULE_PUBLISHING_ALLOWED_FIELD_NUMBER
var SCRIPT_HASH_ALLOW_LIST_FIELD_NUMBER
var TIMESTAMP_FIELD_NUMBER
var VERSION_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var accumulator_root_hash

Getter for accumulator_root_hash.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var chain_id

Getter for chain_id.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var diem_version

Getter for diem_version.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var dual_attestation_limit

Getter for dual_attestation_limit.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var module_publishing_allowed

Getter for module_publishing_allowed.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var script_hash_allow_list

Getter for script_hash_allow_list.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var timestamp

Getter for timestamp.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var version

Getter for version.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class Script (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var AMOUNT_FIELD_NUMBER
var ARGUMENTS_BCS_FIELD_NUMBER
var ARGUMENTS_FIELD_NUMBER
var CODE_FIELD_NUMBER
var CURRENCY_FIELD_NUMBER
var DESCRIPTOR
var FUNCTION_NAME_FIELD_NUMBER
var METADATA_FIELD_NUMBER
var METADATA_SIGNATURE_FIELD_NUMBER
var MODULE_ADDRESS_FIELD_NUMBER
var MODULE_NAME_FIELD_NUMBER
var RECEIVER_FIELD_NUMBER
var TYPE_ARGUMENTS_FIELD_NUMBER
var TYPE_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var amount

Getter for amount.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var arguments

Getter for arguments.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var arguments_bcs

Getter for arguments_bcs.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var code

Getter for code.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var currency

Getter for currency.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var function_name

Getter for function_name.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var metadata

Getter for metadata.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var metadata_signature

Getter for metadata_signature.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var module_address

Getter for module_address.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var module_name

Getter for module_name.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var receiver

Getter for receiver.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var type

Getter for type.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var type_arguments

Getter for type_arguments.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class StateProof (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var DESCRIPTOR
var EPOCH_CHANGE_PROOF_FIELD_NUMBER
var LEDGER_CONSISTENCY_PROOF_FIELD_NUMBER
var LEDGER_INFO_WITH_SIGNATURES_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var epoch_change_proof

Getter for epoch_change_proof.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var ledger_consistency_proof

Getter for ledger_consistency_proof.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var ledger_info_with_signatures

Getter for ledger_info_with_signatures.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class Transaction (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var BYTES_FIELD_NUMBER
var DESCRIPTOR
var EVENTS_FIELD_NUMBER
var GAS_USED_FIELD_NUMBER
var HASH_FIELD_NUMBER
var TRANSACTION_FIELD_NUMBER
var VERSION_FIELD_NUMBER
var VM_STATUS_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var bytes

Getter for bytes.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var events

Getter for events.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var gas_used

Getter for gas_used.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var hash

Getter for hash.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var transaction

Getter for transaction.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var version

Getter for version.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var vm_status

Getter for vm_status.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class TransactionData (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var CHAIN_ID_FIELD_NUMBER
var DESCRIPTOR
var EXPIRATION_TIMESTAMP_SECS_FIELD_NUMBER
var GAS_CURRENCY_FIELD_NUMBER
var GAS_UNIT_PRICE_FIELD_NUMBER
var MAX_GAS_AMOUNT_FIELD_NUMBER
var PUBLIC_KEY_FIELD_NUMBER
var SCRIPT_BYTES_FIELD_NUMBER
var SCRIPT_FIELD_NUMBER
var SCRIPT_HASH_FIELD_NUMBER
var SENDER_FIELD_NUMBER
var SEQUENCE_NUMBER_FIELD_NUMBER
var SIGNATURE_FIELD_NUMBER
var SIGNATURE_SCHEME_FIELD_NUMBER
var TIMESTAMP_USECS_FIELD_NUMBER
var TYPE_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var chain_id

Getter for chain_id.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var expiration_timestamp_secs

Getter for expiration_timestamp_secs.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var gas_currency

Getter for gas_currency.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var gas_unit_price

Getter for gas_unit_price.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var max_gas_amount

Getter for max_gas_amount.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var public_key

Getter for public_key.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var script

Getter for script.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var script_bytes

Getter for script_bytes.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var script_hash

Getter for script_hash.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var sender

Getter for sender.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var sequence_number

Getter for sequence_number.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var signature

Getter for signature.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var signature_scheme

Getter for signature_scheme.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var timestamp_usecs

Getter for timestamp_usecs.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var type

Getter for type.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None
class VMStatus (**kwargs)

Abstract base class for protocol messages.

Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below.

Ancestors

  • google.protobuf.message.Message

Class variables

var ABORT_CODE_FIELD_NUMBER
var CODE_OFFSET_FIELD_NUMBER
var DESCRIPTOR
var EXPLANATION_FIELD_NUMBER
var FUNCTION_INDEX_FIELD_NUMBER
var LOCATION_FIELD_NUMBER
var TYPE_FIELD_NUMBER

Static methods

def FromString(s)
Expand source code
def FromString(s):
  message = cls()
  message.MergeFromString(s)
  return message
def RegisterExtension(extension_handle)
Expand source code
def RegisterExtension(extension_handle):
  extension_handle.containing_type = cls.DESCRIPTOR
  # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available.
  # pylint: disable=protected-access
  cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(extension_handle)
  _AttachFieldHelpers(cls, extension_handle)

Instance variables

var abort_code

Getter for abort_code.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var code_offset

Getter for code_offset.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var explanation

Getter for explanation.

Expand source code
def getter(self):
  field_value = self._fields.get(field)
  if field_value is None:
    # Construct a new object to represent this field.
    field_value = field._default_constructor(self)

    # Atomically check if another thread has preempted us and, if not, swap
    # in the new object we just created.  If someone has preempted us, we
    # take that object and discard ours.
    # WARNING:  We are relying on setdefault() being atomic.  This is true
    #   in CPython but we haven't investigated others.  This warning appears
    #   in several other locations in this file.
    field_value = self._fields.setdefault(field, field_value)
  return field_value
var function_index

Getter for function_index.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var location

Getter for location.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)
var type

Getter for type.

Expand source code
def getter(self):
  # TODO(protobuf-team): This may be broken since there may not be
  # default_value.  Combine with has_default_value somehow.
  return self._fields.get(field, default_value)

Methods

def ByteSize(self)
Expand source code
def ByteSize(self):
  if not self._cached_byte_size_dirty:
    return self._cached_byte_size

  size = 0
  descriptor = self.DESCRIPTOR
  if descriptor.GetOptions().map_entry:
    # Fields of map entry should always be serialized.
    size = descriptor.fields_by_name['key']._sizer(self.key)
    size += descriptor.fields_by_name['value']._sizer(self.value)
  else:
    for field_descriptor, field_value in self.ListFields():
      size += field_descriptor._sizer(field_value)
    for tag_bytes, value_bytes in self._unknown_fields:
      size += len(tag_bytes) + len(value_bytes)

  self._cached_byte_size = size
  self._cached_byte_size_dirty = False
  self._listener_for_children.dirty = False
  return size
def Clear(self)
Expand source code
def _Clear(self):
  # Clear fields.
  self._fields = {}
  self._unknown_fields = ()
  # pylint: disable=protected-access
  if self._unknown_field_set is not None:
    self._unknown_field_set._clear()
    self._unknown_field_set = None

  self._oneofs = {}
  self._Modified()
def ClearField(self, field_name)
Expand source code
def ClearField(self, field_name):
  try:
    field = message_descriptor.fields_by_name[field_name]
  except KeyError:
    try:
      field = message_descriptor.oneofs_by_name[field_name]
      if field in self._oneofs:
        field = self._oneofs[field]
      else:
        return
    except KeyError:
      raise ValueError('Protocol message %s has no "%s" field.' %
                       (message_descriptor.name, field_name))

  if field in self._fields:
    # To match the C++ implementation, we need to invalidate iterators
    # for map fields when ClearField() happens.
    if hasattr(self._fields[field], 'InvalidateIterators'):
      self._fields[field].InvalidateIterators()

    # Note:  If the field is a sub-message, its listener will still point
    #   at us.  That's fine, because the worst than can happen is that it
    #   will call _Modified() and invalidate our byte size.  Big deal.
    del self._fields[field]

    if self._oneofs.get(field.containing_oneof, None) is field:
      del self._oneofs[field.containing_oneof]

  # Always call _Modified() -- even if nothing was changed, this is
  # a mutating method, and thus calling it should cause the field to become
  # present in the parent message.
  self._Modified()
def DiscardUnknownFields(self)
Expand source code
def _DiscardUnknownFields(self):
  self._unknown_fields = []
  self._unknown_field_set = None      # pylint: disable=protected-access
  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            value[key].DiscardUnknownFields()
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for sub_message in value:
          sub_message.DiscardUnknownFields()
      else:
        value.DiscardUnknownFields()
def FindInitializationErrors(self)

Finds required fields which are not initialized.

Returns

A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz".

Expand source code
def FindInitializationErrors(self):
  """Finds required fields which are not initialized.

  Returns:
    A list of strings.  Each string is a path to an uninitialized field from
    the top-level message, e.g. "foo.bar[5].baz".
  """

  errors = []  # simplify things

  for field in required_fields:
    if not self.HasField(field.name):
      errors.append(field.name)

  for field, value in self.ListFields():
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.is_extension:
        name = '(%s)' % field.full_name
      else:
        name = field.name

      if _IsMapField(field):
        if _IsMessageMapField(field):
          for key in value:
            element = value[key]
            prefix = '%s[%s].' % (name, key)
            sub_errors = element.FindInitializationErrors()
            errors += [prefix + error for error in sub_errors]
        else:
          # ScalarMaps can't have any initialization errors.
          pass
      elif field.label == _FieldDescriptor.LABEL_REPEATED:
        for i in range(len(value)):
          element = value[i]
          prefix = '%s[%d].' % (name, i)
          sub_errors = element.FindInitializationErrors()
          errors += [prefix + error for error in sub_errors]
      else:
        prefix = name + '.'
        sub_errors = value.FindInitializationErrors()
        errors += [prefix + error for error in sub_errors]

  return errors
def HasField(self, field_name)
Expand source code
def HasField(self, field_name):
  try:
    field = hassable_fields[field_name]
  except KeyError:
    raise ValueError(error_msg % (message_descriptor.full_name, field_name))

  if isinstance(field, descriptor_mod.OneofDescriptor):
    try:
      return HasField(self, self._oneofs[field].name)
    except KeyError:
      return False
  else:
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      value = self._fields.get(field)
      return value is not None and value._is_present_in_parent
    else:
      return field in self._fields
def IsInitialized(self, errors=None)

Checks if all required fields of a message are set.

Args

errors
A list which, if provided, will be populated with the field paths of all missing required fields.

Returns

True iff the specified message has all required fields set.

Expand source code
def IsInitialized(self, errors=None):
  """Checks if all required fields of a message are set.

  Args:
    errors:  A list which, if provided, will be populated with the field
             paths of all missing required fields.

  Returns:
    True iff the specified message has all required fields set.
  """

  # Performance is critical so we avoid HasField() and ListFields().

  for field in required_fields:
    if (field not in self._fields or
        (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and
         not self._fields[field]._is_present_in_parent)):
      if errors is not None:
        errors.extend(self.FindInitializationErrors())
      return False

  for field, value in list(self._fields.items()):  # dict can change size!
    if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
      if field.label == _FieldDescriptor.LABEL_REPEATED:
        if (field.message_type.has_options and
            field.message_type.GetOptions().map_entry):
          continue
        for element in value:
          if not element.IsInitialized():
            if errors is not None:
              errors.extend(self.FindInitializationErrors())
            return False
      elif value._is_present_in_parent and not value.IsInitialized():
        if errors is not None:
          errors.extend(self.FindInitializationErrors())
        return False

  return True
def ListFields(self)
Expand source code
def ListFields(self):
  all_fields = [item for item in self._fields.items() if _IsPresent(item)]
  all_fields.sort(key = lambda item: item[0].number)
  return all_fields
def MergeFrom(self, msg)
Expand source code
def MergeFrom(self, msg):
  if not isinstance(msg, cls):
    raise TypeError(
        'Parameter to MergeFrom() must be instance of same class: '
        'expected %s got %s.' % (cls.__name__, msg.__class__.__name__))

  assert msg is not self
  self._Modified()

  fields = self._fields

  for field, value in msg._fields.items():
    if field.label == LABEL_REPEATED:
      field_value = fields.get(field)
      if field_value is None:
        # Construct a new object to represent this field.
        field_value = field._default_constructor(self)
        fields[field] = field_value
      field_value.MergeFrom(value)
    elif field.cpp_type == CPPTYPE_MESSAGE:
      if value._is_present_in_parent:
        field_value = fields.get(field)
        if field_value is None:
          # Construct a new object to represent this field.
          field_value = field._default_constructor(self)
          fields[field] = field_value
        field_value.MergeFrom(value)
    else:
      self._fields[field] = value
      if field.containing_oneof:
        self._UpdateOneofState(field)

  if msg._unknown_fields:
    if not self._unknown_fields:
      self._unknown_fields = []
    self._unknown_fields.extend(msg._unknown_fields)
    # pylint: disable=protected-access
    if self._unknown_field_set is None:
      self._unknown_field_set = containers.UnknownFieldSet()
    self._unknown_field_set._extend(msg._unknown_field_set)
def MergeFromString(self, serialized)
Expand source code
def MergeFromString(self, serialized):
  if isinstance(serialized, memoryview) and six.PY2:
    raise TypeError(
        'memoryview not supported in Python 2 with the pure Python proto '
        'implementation: this is to maintain compatibility with the C++ '
        'implementation')

  serialized = memoryview(serialized)
  length = len(serialized)
  try:
    if self._InternalParse(serialized, 0, length) != length:
      # The only reason _InternalParse would return early is if it
      # encountered an end-group tag.
      raise message_mod.DecodeError('Unexpected end-group tag.')
  except (IndexError, TypeError):
    # Now ord(buf[p:p+1]) == ord('') gets TypeError.
    raise message_mod.DecodeError('Truncated message.')
  except struct.error as e:
    raise message_mod.DecodeError(e)
  return length   # Return this for legacy reasons.
def SerializePartialToString(self, **kwargs)
Expand source code
def SerializePartialToString(self, **kwargs):
  out = BytesIO()
  self._InternalSerialize(out.write, **kwargs)
  return out.getvalue()
def SerializeToString(self, **kwargs)
Expand source code
def SerializeToString(self, **kwargs):
  # Check if the message has all of its required fields set.
  if not self.IsInitialized():
    raise message_mod.EncodeError(
        'Message %s is missing required fields: %s' % (
        self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors())))
  return self.SerializePartialToString(**kwargs)
def SetInParent(self)

Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change.

Expand source code
def Modified(self):
  """Sets the _cached_byte_size_dirty bit to true,
  and propagates this to our listener iff this was a state change.
  """

  # Note:  Some callers check _cached_byte_size_dirty before calling
  #   _Modified() as an extra optimization.  So, if this method is ever
  #   changed such that it does stuff even when _cached_byte_size_dirty is
  #   already true, the callers need to be updated.
  if not self._cached_byte_size_dirty:
    self._cached_byte_size_dirty = True
    self._listener_for_children.dirty = True
    self._is_present_in_parent = True
    self._listener.Modified()
def UnknownFields(self)
Expand source code
def _UnknownFields(self):
  if self._unknown_field_set is None:  # pylint: disable=protected-access
    # pylint: disable=protected-access
    self._unknown_field_set = containers.UnknownFieldSet()
  return self._unknown_field_set    # pylint: disable=protected-access
def WhichOneof(self, oneof_name)

Returns the name of the currently set field inside a oneof, or None.

Expand source code
def WhichOneof(self, oneof_name):
  """Returns the name of the currently set field inside a oneof, or None."""
  try:
    field = message_descriptor.oneofs_by_name[oneof_name]
  except KeyError:
    raise ValueError(
        'Protocol message has no oneof "%s" field.' % oneof_name)

  nested_field = self._oneofs.get(field, None)
  if nested_field is not None and self.HasField(nested_field.name):
    return nested_field.name
  else:
    return None