Beispiel #1
0
 def _EOSImageFormat(self):
     return Struct(
         'Entries' / PrefixedArray(
             self._UInt32,
             Struct(
                 'Bytes' / self._UInt32,
                 PrefixedArray(lambda ctx: ctx.Bytes / 4, Byte),
                 'Type' / Enum(
                     self._UInt32,
                     default=Pass,
                     JPG=1,
                     RAW=1,
                 ),
                 'Size' / Enum(
                     self._UInt32,
                     default=Pass,
                     L=0x00,
                     M=0x01,
                     S=0x02,
                     S1=0x0E,
                     S2=0x0f,
                     S3=0x10,
                 ),
                 'Compression' / Enum(
                     self._UInt32,
                     default=Pass,
                     Standard=0x02,
                     Fine=0x03,
                     Lossless=0x04,
                 ),
             )), )
Beispiel #2
0
def sign_transaction(path: Derivation, tx: Transaction):
    INS = 0x04
    P2 = 0x00

    path_construct = PrefixedArray(Byte, Int32ub)
    path_apdu = path_construct.build(path.to_list())

    data = path_apdu + rlp.encode(tx)

    class DeviceResponse(NamedTuple):
        v: int
        r: int
        s: int

    def f(client: LedgerClient) -> DeviceResponse:
        raw_response = bytes()

        for idx, each in enumerate(chunk(data, 255)):
            P1 = 0x00 if idx == 0 else 0x80
            raw_response = client.apdu_exchange(INS, each, P1, P2)

        response_template = Struct(
            v=BytesInteger(1),
            r=BytesInteger(32),
            s=BytesInteger(32),
        )
        parsed_response = response_template.parse(raw_response)

        return DeviceResponse(
            v=parsed_response.v,
            r=parsed_response.r,
            s=parsed_response.s,
        )

    return f
Beispiel #3
0
 def _EOSDeviceInfo(self):
     return Struct(
         'EventsSupported' /
         PrefixedArray(self._UInt32, self._EOSEventCode),
         'DevicePropertiesSupported' /
         PrefixedArray(self._UInt32, self._EOSPropertyCode),
         'TODO' / PrefixedArray(self._UInt32, self._UInt32),
     )
Beispiel #4
0
def numa_topology():
    return PrefixedArray(Struct("node",
                                UNInt32("nodenr"),
                                UNInt64("mem_total"),
                                UNInt64("mem_free"),
                                str_with_len("cpus")),
                         UNInt32("nr"))
Beispiel #5
0
 def _NikonEvent(self):
     return PrefixedArray(
         self._UInt16,
         Struct(
             'EventCode' / self._EventCode,
             'Parameter' / self._UInt32,
         ))
Beispiel #6
0
def get_wallet_public_key(path: Derivation, opts: GetWalletPublicKeyOpts):
    # TODO: support user-validation token

    if opts.scheme is not None and not Scheme.is_member(opts.scheme):
        raise ValueError(f"unrecognized Scheme value: {opts.scheme}")

    INS = 0x40
    P1 = 0x01 if opts.display_address else 0x00
    P2 = opts.scheme.value if opts.scheme is not None else Scheme.P2PKH

    if opts.display_address and path.depth != 5:
        raise ValueError(
            f"cannot derive address at BIP-32 path {path}: invalid depth {path.depth}"
        )

    if opts.scheme is not None and path.depth != 5:
        raise ValueError(
            f"scheme not expected at BIP-32 path {path}: {opts.scheme.name}")

    path_construct = PrefixedArray(Byte, Int32ub)
    path_apdu = path_construct.build(path.to_list())

    data = path_apdu

    class DeviceResponse(NamedTuple):
        public_key: bytes
        address: str
        chain_code: bytes

    def f(client: LedgerClient) -> DeviceResponse:
        response = client.apdu_exchange(INS, data, P1, P2)

        response_template = Struct(
            public_key=Prefixed(Int8ub, GreedyBytes),
            address=PascalString(Int8ub, "ascii"),
            chain_code=Bytes(32),
        )

        parsed_response = response_template.parse(response)
        return DeviceResponse(
            public_key=parsed_response.public_key,
            address=parsed_response.address,
            chain_code=parsed_response.chain_code,
        )

    return f
Beispiel #7
0
def string_list(name, extra = Pass):
    return PrefixedArray(Struct(name,
                               UNInt32("len"),
                               Anchor("start"),
                               CString(name),
                               Anchor("offset"),
                               pad(),
                               extra), UNInt32("nr"))
class InstantSoupData(object):

    # common
    server = Struct("server", CString("server_id"),
                    PrefixedArray(CString('channels'), UBInt8("num_channels")))

    # structures from rfc
    opt_client_nick = CString('nickname')

    opt_client_membership = PrefixedArray(server, UBInt8("num_servers"))

    opt_server = Struct("opt_server", UBInt16("port"))

    opt_server_channels = Struct(
        "opt_server_channels",
        PrefixedArray(CString("channels"), UBInt8("num_channels")))

    opt_server_invite = Struct(
        "opt_server_invite", CString("channel_id"),
        PrefixedArray(CString("client_id"), UBInt8("num_clients")))

    # option fields
    option = Struct(
        "option",
        Enum(UBInt8("option_id"),
             CLIENT_NICK_OPTION=0x01,
             CLIENT_MEMBERSHIP_OPTION=0x02,
             SERVER_OPTION=0x10,
             SERVER_CHANNELS_OPTION=0x11,
             SERVER_INVITE_OPTION=0x12),
        Switch(
            "option_data", lambda ctx: ctx["option_id"], {
                "CLIENT_NICK_OPTION": opt_client_nick,
                "CLIENT_MEMBERSHIP_OPTION": opt_client_membership,
                "SERVER_OPTION": opt_server,
                "SERVER_CHANNELS_OPTION": opt_server_channels,
                "SERVER_INVITE_OPTION": opt_server_invite
            }))

    # the peer pdu itself
    peer_pdu = Struct("peer_pdu", CString('id'), OptionalGreedyRange(option))

    command = PascalString("command",
                           length_field=UBInt32("length"),
                           encoding='utf8')
Beispiel #9
0
 def _PTPString(self):
     '''Returns a PTP String constructor'''
     return ExprAdapter(
         PrefixedArray(self._UInt8, self._UInt16),
         encoder=lambda obj, ctx: []
         if len(obj) == 0 else [ord(c) for c in six.text_type(obj)] + [0],
         decoder=lambda obj, ctx: u''.join([six.unichr(o)
                                            for o in obj]).split('\x00')[0],
     )
Beispiel #10
0
def Vec(subcon: Construct) -> Array:  # noqa: N802
    """Dynamic sized array.

    Args:
        subcon (Construct): the type of the array members.

    Returns:
        Array: a Construct PrefixedArray.
    """
    return PrefixedArray(U32, subcon)
Beispiel #11
0
 def _EOSImageFormat(self):
     return PrefixedArray(
         self._UInt32,
         Struct(
             'Bytes' / self._UInt32,
             'Type' / self._EOSImageType,
             'Size' / self._EOSImageSize,
             'Compression' / self._EOSImageCompression,
         )
     )
Beispiel #12
0
def get_eth_public_address(path: Derivation, opts: GetEthPublicAddressOpts):
    INS = 0x02
    P1 = 0x01 if opts.display_address else 0x00
    P2 = 0x01 if opts.return_chain_code else 0x00

    path_construct = PrefixedArray(Byte, Int32ub)
    path_apdu = path_construct.build(path.to_list())

    data = path_apdu

    class DeviceResponse(NamedTuple):
        public_key: bytes
        address: str
        chain_code: Optional[bytes]

    def f(client: LedgerClient) -> DeviceResponse:
        response = client.apdu_exchange(INS, data, P1, P2)

        struct_kwargs = dict(
            public_key=Prefixed(Int8ub, GreedyBytes),
            address=PascalString(Int8ub, "ascii"),
        )
        if opts.return_chain_code:
            struct_kwargs["chain_code"] = Bytes(32)

        response_template = Struct(**struct_kwargs)

        parsed_response = response_template.parse(response)
        return DeviceResponse(
            public_key=parsed_response.public_key,
            address=parsed_response.address,
            chain_code=parsed_response.chain_code
            if opts.return_chain_code else None,
        )

    return f
Beispiel #13
0
requirement_type_map = {
    "resource": ConstructResourceRequirement,
    "template": CString("utf8"),
}

ConstructRequirement = Struct(type=construct.Enum(Byte,
                                                  resource=0,
                                                  **{
                                                      "and": 1,
                                                      "or": 2
                                                  },
                                                  template=3),
                              data=Switch(lambda this: this.type,
                                          requirement_type_map))
requirement_type_map["and"] = PrefixedArray(VarInt, ConstructRequirement)
requirement_type_map["or"] = PrefixedArray(VarInt, ConstructRequirement)

ConstructDockWeakness = Struct(
    index=VarInt,
    name=CString("utf8"),
    is_blast_door=Flag,
    requirement=ConstructRequirement,
)

ConstructResourceDatabase = Struct(
    items=PrefixedArray(VarInt, ConstructItemResourceInfo),
    events=PrefixedArray(VarInt, ConstructResourceInfo),
    tricks=PrefixedArray(VarInt, ConstructTrickResourceInfo),
    damage=PrefixedArray(
        VarInt,
Beispiel #14
0
DebugV2Parameter = SwitchStruct(
    "data_type" / EnumAdapter(Int8ul, DebugV2DataTypes), "parameter" / Switch(
        this.data_type, {
            DebugV2DataTypes.UINT8: Int8ul,
            DebugV2DataTypes.UINT16: Int16ul,
            DebugV2DataTypes.UINT32: Int32ul,
            DebugV2DataTypes.UINT64: Int64ul,
            DebugV2DataTypes.INT8: Int8sl,
            DebugV2DataTypes.INT16: Int16sl,
            DebugV2DataTypes.INT32: Int32sl,
            DebugV2DataTypes.INT64: Int64sl,
            DebugV2DataTypes.FLOAT: Float32l,
            DebugV2DataTypes.DOUBLE: Float64l,
            DebugV2DataTypes.ENUM: Int8ul,
            DebugV2DataTypes.STRING: PascalString(Int8ul, "utf-8"),
            DebugV2DataTypes.ARRAY: PrefixedArray(Int8ul, Int8ul),
            DebugV2DataTypes.INVALID: Struct()
        }))

DebugV2SubMessage = Struct("subopcode" / EnumAdapter(Int8ul, DebugV2SubOpcode),
                           "parameter_type" / Int8ul, "page_number" / Int8ul,
                           "payload" / GreedyRange(DebugV2Parameter))

DebugV2Message = SwitchStruct(
    "opcode" / Opcode(DebugV2Opcode),
    "params" / Switch(this.opcode, {
        DebugV2Opcode.SILVAIR_DEBUG_V2: DebugV2SubMessage,
    }))

# fmt: on
Beispiel #15
0
        return "/".join(out)

    def _encode(self, obj, context, path):
        out = list()
        elements = obj.split("/")
        if elements[0] == "m":
            elements = elements[1:]
        for element in elements:
            if element.endswith("'"):
                out.append(0x80000000 | int(element[:-1]))
            else:
                out.append(int(element))
        return out


Bip32Path = Bip32PathAdapter(PrefixedArray(Byte, Int32ub))

PrefixedString = PascalString(Asn1Length, "utf8")

AppName = PrefixedString
Version = PrefixedString
Icon = Prefixed(Asn1Length, GreedyBytes)

CURVE_SEPCK256K1 = 1
CURVE_PRIME256R1 = 2
CURVE_ED25519 = 4

Curve = FlagsEnum(
    Byte, secp256k1=CURVE_SEPCK256K1, prime256r1=CURVE_PRIME256R1, ed25519=CURVE_ED25519
)
Beispiel #16
0
def array(struct):
    """Standard prefixed arrays."""
    return PrefixedArray(struct, ULInt32('count'))
Beispiel #17
0
 def _SonyAllPropDesc(self):
     return PrefixedArray(self._UInt64, self._SonyPropDesc)
Beispiel #18
0
 def _EnumerationForm(self, element):
     return PrefixedArray(self._UInt16, element)
Beispiel #19
0
ConstructNodeIdentifier = construct.Struct(
    world_name=String,
    area_name=String,
    node_name=String,
)

ConstructResourceInfo = _build_resource_info()

ConstructItemResourceInfo = _build_resource_info(max_capacity=Int32ub, )

ConstructTrickResourceInfo = _build_resource_info(description=String, )

ConstructDamageReductions = Struct(name=String,
                                   reductions=PrefixedArray(
                                       VarInt,
                                       Struct(
                                           name=String,
                                           multiplier=Float32b,
                                       )))

ConstructResourceType = construct.Enum(Byte,
                                       items=0,
                                       events=1,
                                       tricks=2,
                                       damage=3,
                                       versions=4,
                                       misc=5,
                                       pickup_index=7,
                                       gate_index=8,
                                       logbook_index=9,
                                       ship_node=10)
Beispiel #20
0
                RuntimeError, "events offset is not like header size."),
    CheckCustom(lambda this:
                0 != this.events_offset and 0 != this.events_offsets_array_offset and 0 != this.process_table_offset and
                0 != this.strings_table_offset and 0 != this.hosts_and_ports_tables_offset and 0 != this.unknown_table_offset,
                RuntimeError, "Procmon was probably not closed properly.")
)

StringsTable = """
The table of all the strings needed for the logs.
""" * Struct(
    "table_offset" / Tell,
    "strings" / PrefixedArray(
        Int32ul,
        Struct(
            "offset" / Int32ul,
            "string" / Pointer(
                lambda this: this._._.table_offset + this.offset,
                FixedNullTerminatedUTF16String
            )
        )
    )
)

RawProcessStruct = """
Struct that describes a process.
""" * Struct(
    "strings_table" / Computed(lambda ctx: ctx._.strings_table),  # keep the reference to the strings table
    "process_index" / Int32ul,
    "process_id" / Int32ul,
    "parent_process_id" / Int32ul,
    "reserved1" / Int32ul * "!!Unknown field!!",
    "authentication_id" / Int32ul,
Beispiel #21
0
def pmu_mappings():
    return PrefixedArray(Struct("pmu", UNInt32("type"), str_with_len("name")),
                         UNInt32("nr"))
Beispiel #22
0
def ConstructDict(subcon):
    return DictAdapter(
        PrefixedArray(VarInt, Struct(
            key=String,
            value=subcon,
        )))
Beispiel #23
0
from construct import PrefixedArray, VarInt, Struct, CString, Flag

from randovania.lib.construct_lib import OptionalValue

BinStr = CString("utf-8")

OldBinaryInventory = PrefixedArray(
    VarInt,
    Struct(
        index=VarInt,
        amount=VarInt,
        capacity=VarInt,
    )
)


BinaryInventory = PrefixedArray(
    VarInt,
    Struct(
        name=BinStr,
        amount=VarInt,
        capacity=VarInt,
    )
)

BinaryPlayerSessionEntry = Struct(
    id=VarInt,
    name=BinStr,
    row=OptionalValue(VarInt),
    admin=Flag,
    connection_state=BinStr,
Beispiel #24
0
object_types[0x03] = Struct(
    "red_" / Int8ul,
    "blue_" / Int8ul,
    "value" / PascalString(Int8ul, "latin-1"),
)

KeyValuePair = Struct(
    "bloom_" / Int8ul,
    "key" / PascalString(Int8ul, "latin-1"),
    "value" / SerializedObject,
)

# mapping
object_types[0x05] = Struct(
    "monkey_" / Int8ul,  # Usually 0
    "items" / PrefixedArray(Int32ul, KeyValuePair),
)

Version = Struct(
    "major" / Int16ul,
    "minor" / Int16ul,
    "patch" / Int16ul,
    "even_" / Int16ul,  # Sometimes 1
    "odd_" / Int8ul,  # Usually 0
)

OldScriptDat = Struct(
    "_type" / Computed(lambda this: "script"),
    "version" / Version,
    "data" / PrefixedArray(
        Int32ul,
Beispiel #25
0
 def _PTPArray(self, element):
     return PrefixedArray(self._UInt32, element)
Beispiel #26
0
AnlzTagPath = Struct(
    "payload_size" / Int32ub,  # is 0 for some tag types
    "path" / String(this.payload_size - 2, encoding="utf-16-be"),
    Padding(2))

AnlzTagVbr = Struct(Padding(4), "idx" / Array(400, Int32ub),
                    "unknown" / Int32ub)

AnlzQuantizeTick = Struct(
    "beat" / Int16ub,
    "bpm_100" / Int16ub,
    "time" / Int32ub  # in ms from start
)

AnlzTagQuantize = Struct(Padding(4), "unknown" / Const(0x80000, Int32ub),
                         "entries" / PrefixedArray(Int32ub, AnlzQuantizeTick))

AnlzTagQuantize2 = Struct(
    Padding(4),
    "u1" /
    Const(0x01000002,
          Int32ub),  # maybe this encodes the count of "bpm" objects below
    Padding(4),
    "bpm" / Array(2, AnlzQuantizeTick),
    "entry_count" / Int32ub,  # 680
    "u3" / Int32ub,
    "u4" / Int32ub,
    "u5" / Int32ub,
    "u6" / Int32ub,
    Padding(8))
Beispiel #27
0
 def _VendorExtensionMapArray(self):
     '''Return desired endianness for VendorExtensionMapArray'''
     return PrefixedArray(
         self._UInt64,
         self._VendorExtensionMap,
     )
Beispiel #28
0
 def __init__(self, key_subcon: Construct, value_subcon: Construct) -> None:
     super().__init__(
         PrefixedArray(U32, TupleStruct(key_subcon, value_subcon)),
     )  # type: ignore
Beispiel #29
0
    START_STREAM = 0x10
    REQUEST_KEYFRAMES = 0x20
    LAST_DISPLAYED_FRAME_RENDERED = 0x80
    SMOOTH_RENDERING_SETTINGS_SENT = 0x1000


video_format = Struct(
)


video_server_handshake = Struct(
    'protocol_version' / Int32ul,
    'screen_width' / Int32ul,
    'screen_height' / Int32ul,
    'reference_timestamp' / Int64ul,
    'formats' / PrefixedArray(Int32ul, video_format)
)


video_client_handshake = Struct(
    'initial_frame_id' / Int32ul,
    'requested_format' / video_format
)


video_control = Struct(
    'flags' / Int32ul,  # see VideoControlFlags
    'last_displayed_frame' / Int32ul,  # if(flags << 31)
    'last_displayed_frame_rendered' / Int32ul,  # if(flags & 0x80)
    'lost_frames' / Array(2, Int32ul),  # if (flags & 2)
    'queue_depth' / Int32ul,  # if(flags & 4)
Beispiel #30
0
 def __init__(self, subcon: Construct) -> None:
     super().__init__(PrefixedArray(U32, subcon))  # type: ignore