async def send_and_get_transaction(client, data, sender_pk):
    if not data.get('nonce'):
        data['nonce'] = await client.eth_getTransactionCount(
            get_address(sender_pk), 'pending')

    tx = MTransaction(**data)
    signed_tx = tx.sign(sender_pk)

    tx_id = await client.eth_sendRawTransaction(to_hex(signed_tx.raw))

    print("Transaction hash: %s" % tx_id)

    assert tx_id == to_hex(signed_tx.hash), 'Hashes are not equal'

    tx_data = await client.eth_getTransactionByHash(tx_id)
    print("Transaction data:")
    pprint.pprint(tx_data)

    print("Waiting until mined..")
    tx_data = await get_tx_until_mined(client, tx_id)

    print("Transaction data mined:")
    pprint.pprint(tx_data)

    return tx_data
Beispiel #2
0
    def parse_directive_to_list(self, raw_asm_line: str):
        directive = Directive(raw_instruction=raw_asm_line)
        if directive.type in ('.word', '.byte'):
            directive.value = to_hex(directive.value, num_bits=16)
            return [directive]
        elif directive.type == '.asciiz':
            ascii_str = directive.value
            ascii_str = self._undo_escape(ascii_str)
            # Partitions string every 2 characters. I.e. '12345' => '12', '34', '5'
            ascii_split_16bit = tuple(ascii_str[i: i + self._BYTES_PER_WORD]
                                      for i in range(0, len(ascii_str), self._BYTES_PER_WORD))
            directives_split_16bit = []
            # Stores a list of directives, each storing 2 chars
            # Converts each string into its hexadecimal ascii encoded format.
            for ascii_word in ascii_split_16bit:
                next_ascii_word = deepcopy(directive)
                next_ascii_word.content = f"\"{ascii_word}\""
                first_char = to_hex(ord(ascii_word[0]), num_bits=8)
                second_char = to_hex(ord(ascii_word[-1]), num_bits=8)
                next_ascii_word.value = second_char + first_char
                directives_split_16bit.append(next_ascii_word)

            # Padding null terminator.
            # Create new if string len is even, pad at end if odd.
            if len(ascii_str) % 2 == 0:
                null_directive = deepcopy(directive)
                null_directive.value = '0000'
                null_directive.content = r'"\0\0"'
                directives_split_16bit.append(null_directive)
            else:
                last_ascii = directives_split_16bit[-1]
                ascii_encoded = last_ascii.value
                len_half = len(ascii_encoded) // 2

                # For debugging
                error_msg = "Due to implementation, " \
                            "last directive should have stored two copies of same string"
                assert ascii_encoded[:len_half] == ascii_encoded[len_half:], error_msg

                # FIXME: Too convoluted and unintuitive
                ascii_char = ascii_encoded[:len_half]
                null_terminator = '00'
                last_ascii.value = null_terminator + ascii_char
                # Recovers original letter from hex encoding
                last_ascii.content = "\"" + chr(int(ascii_char, 16)) + r'\0' + "\""

            return directives_split_16bit

        else:
            raise SyntaxError(f"Expected .word or .byte of .asciiz, but got {directive.content}")
Beispiel #3
0
def main(args):
    parser = bibtex.Parser()
    bib_data = parser.parse_file(args.inp)

    def sort_by_year(x):
        return int(x[1].fields['year'])

    bib_sorted = sorted(bib_data.entries.items(), key=sort_by_year)
    papers = []
    tags = {}
    for key, value in bib_sorted:
        print(key, value.fields['title'])
        papers.append(value.fields['title'])
        taglist = value.fields['swy'].split('.')
        taglist = [TAGS[tag] for tag in taglist]
        tags[value.fields['title']] = taglist

    with open(args.out, 'w') as f:
        f.writelines('var color = {\n')
        for i, human in enumerate(TAGS.values()):
            f.writelines("    '{}': \"{}\",\n".format(human, to_hex(rgb[i])))
        f.writelines("};\n")
        # write edges:
        f.writelines('var data = [\n')
        for i, human in enumerate(papers):
            for val in tags[human]:
                f.writelines("    ['{}', \"{}\", {}],\n".format(
                    val, human, width))
        f.writelines("];\n")
def low_level_parse_logs(ct, tx_result, events=None):
    if events is None:
        events = ['Error(bytes32)', 'Success(bytes32)']

    sha3_events = {to_hex(utils.sha3(event)): re.search('.*?(?=\()', event).group(0).encode('utf-8')
                   for event in events}
    for log in tx_result['logs']:
        if log['topics'][0] in sha3_events:
            yield sha3_events[log['topics'][0]], utils.remove_0x_head(log['data']).rstrip('0')
Beispiel #5
0
    def _sb_execute(self, r1: int, base: int, offset: int, comment: str):
        base_addr = self._register[base]
        target_addr = base_addr + offset

        r1_value = self._register[r1]
        val_as_hex = to_hex(value=r1_value, num_bits=16, debug_comment=comment)
        one_byte = 2
        low_byte = val_as_hex[one_byte:]
        self._memory[target_addr] = low_byte
Beispiel #6
0
 def to_string(self):
     address = hex(self.address)[:-1]
     raw_opc = to_hex_spaced(self.opc_bytes)
     concs = ""
     concs += "" if self.libcall is None else " Call:" + self.libcall.func_name
     concs += "" if self.syscall is None else " " + str(self.syscall.id)
     concs += "" if self.comment is None else " Comment:" + self.comment
     for r_w, reg, value in self.registers:
         val = hex(value) if isinstance(value, int) else to_hex(value)
         concs += " " + r_w + "[" + reg + "]=" + val
     for r_w, addr, value in self.memories:
         concs += " " + r_w + "@[" + hex(addr) + "]=" + to_hex(value)
     concs += " Next:" + hex(
         self.nextaddr) if self.nextaddr is not None else ""
     padding1 = " " * (25 - len(raw_opc))
     padding2 = " " * (16 - len(self.opcode) + len(padding1) + len(raw_opc))
     th = self.thread
     return "%s t[%d] %s%s%s%s %s" % (address, th, raw_opc, padding1,
                                      self.opcode, padding2, concs)
Beispiel #7
0
	def deserialize_currency(self):
		currency = self.get_bytes(20)

		if currency == ALL_ZEROES:
			currency = self.native_currency
		elif _is_iso(currency):
			currency = currency[12:15]
		else:
			currency = utils.to_hex(currency)
		return currency
Beispiel #8
0
 def to_string_generator(self):
     for i in xrange(self.trace_index):
         if i in self.metas:
             for m in self.metas[i]:
                 name_id, arg1, arg2 = m
                 if name_id == "invalid":
                     print name_id
                 elif name_id == "exception":
                     print "Exception, type:" + str(
                         arg1) + " handler:" + to_hex(arg2)
                 elif name_id == "wave":
                     print "====================== Wave " + str(
                         arg1) + "======================"
         yield "%d %s" % (i, self.instrs[i].to_string())
Beispiel #9
0
    def __init__(self, wb, game):
        self.game = game
        self.sheet = wb['sheet1']
        # 初始化
        self.sheet.append(Config.title_top)
        self.sheet.append(Config.title)
        if self.game.team_colors is None:
            Config.team_colors[self.game.team_names['left']] = utils.to_hex([255, 255, 255])
            Config.team_colors[self.game.team_names['right']] = utils.to_hex([70, 70, 70])
        Config.team_colors[self.game.team_names['left']] = utils.to_hex(self.game.team_colors['left'])
        Config.team_colors[self.game.team_names['right']] = utils.to_hex(self.game.team_colors['right'])

        # 上一帧所有玩家的大招状况
        self.ultimate_status = {i: False for i in range(1, 13)}

        # 上一帧所有玩家的 chara
        self.previous_chara = [player.chara for player in self.game.frames[0].players]
        # 下一帧所有玩家的 chara
        self.next_chara = [player.chara for player in self.game.frames[1].players]

        # 当前所有玩家的 玩家名以及信息, 如[(player, chara), ...]
        self.player_and_chara = []

        self.data = []
async def call_contract_method(client,
                               ct,
                               contract_address,
                               method,
                               args=None,
                               *,
                               sender_pk):
    if args is None:
        args = []

    response = await client.eth_call(get_address(sender_pk),
                                     contract_address,
                                     data=to_hex(
                                         ct.encode_function_call(method,
                                                                 args)))

    try:
        result = ct.decode_function_result(method, response)[0]
    except IndexError:
        raise ValueError('Incorrect result for decoding')
    print("Method '%s' result: %s" % (method, result))
    return result
Beispiel #11
0
	def deserialize_int64(self):
		return utils.to_hex(self.get_bytes(8))
Beispiel #12
0
    def encode(self, instruction):
        if instruction.instruct_type == 'comment':
            return instruction.comment

        elif instruction.instruct_type == 'directive':
            encoded = str(instruction.value)
        else:
            assert instruction.instruct_type == 'instruction', \
                "Instruction type should be a comment, directive, or instruction"

            # Label assignment begin
            if instruction.rd in self._symbol_table.keys():
                instruction.rd = self._symbol_table[instruction.rd]
            if instruction.rs in self._symbol_table.keys():
                instruction.rs = self._symbol_table[instruction.rs]
            if instruction.immediate in self._symbol_table.keys():
                instruction.immediate = self._symbol_table[instruction.immediate]
            if instruction.branch_addr in self._symbol_table.keys():
                instruction.branch_addr = self._symbol_table[instruction.branch_addr]
            if instruction.jump_addr in self._symbol_table.keys():
                instruction.jump_addr = self._symbol_table[instruction.jump_addr]
            # Label assignment end

            encoded = ''
            encoded += to_hex(instruction.opcode, debug_instruction=instruction)

            # alu-type instructions all have 4-bit operands
            if instruction.optype == 'alu':
                for operand in (instruction.rd, instruction.rs, instruction.funct_code):
                    operand = self.return_if_int(operand, instruction=instruction)
                    encoded += to_hex(operand, num_bits=4)

            # immediate instruction should have 4-bit registers, and 8 bit immediates
            elif instruction.optype == 'alui':
                instruction.rd = self.return_if_int(instruction.rd,
                                                    instruction=instruction)
                instruction.immediate = self.return_if_int(instruction.immediate,
                                                           instruction=instruction)

                encoded += to_hex(instruction.rd, num_bits=4)
                encoded += to_hex(instruction.immediate, num_bits=8, debug_instruction=instruction)
            # All fields of mem instructions have 4 bits
            elif instruction.optype == 'mem':
                for operand in (instruction.rd, instruction.rs, instruction.mem_offset):
                    operand = self.return_if_int(operand,
                                                 instruction=instruction)
                    encoded += to_hex(operand, num_bits=4)

            # Branch offsets are calculated by target address - next pc address,
            # then shifted right one bit
            elif instruction.optype == 'branch':
                instruction.rd = self.return_if_int(instruction.rd,
                                                    instruction=instruction)
                instruction.branch_addr = self.return_if_int(instruction.branch_addr,
                                                             instruction=instruction)
                encoded += to_hex(instruction.rd, num_bits=4)

                # Calculation of branch offset
                next_pc_addr = instruction.addr + self._BYTES_PER_WORD
                branch_offset = instruction.branch_addr - next_pc_addr
                branch_offset = branch_offset >> 1

                encoded += to_hex(branch_offset, num_bits=8)

            # Jump field should be 12 bits long.
            # Jump addresses are also shifted left one bit.
            elif instruction.opname in ('j', 'jal'):
                instruction.jump_addr = self.return_if_int(instruction.jump_addr,
                                                           instruction=instruction)
                if instruction.jump_addr < 0:
                    raise MemoryError(f"Expected memory value, got {instruction.jump_addr}\n"
                                      f"Instruction: {instruction.content}")

                # Calculation of jump addr
                jump_addr = instruction.jump_addr >> 1
                encoded += zero_extend(jump_addr, num_bits=12)

            elif instruction.opname == 'jr':
                instruction.jump_addr = self.return_if_int(instruction.jump_addr,
                                                           instruction=instruction)
                encoded += zero_extend(instruction.jump_addr, num_bits=4)
                encoded += '00'

            # Parses li pseudoinstruction.
            elif instruction.optype == 'pseudo':
                assert 'li' in instruction.opname, "Only pseudoinstruction is li"
                instruction.rd = self.return_if_int(instruction.rd,
                                                    instruction=instruction)
                encoded += to_hex(instruction.rd, num_bits=4)

                # Depending on lui or ori, takes the first two or last two hex digits.
                if instruction.opname == 'li_lui':
                    instruction.immediate = self.return_if_int(instruction.immediate,
                                                               instruction=instruction)
                    immediate = to_twos_complement(instruction.immediate, num_bits=16)
                    encoded += to_hex(immediate, num_bits=16)[:2]
                elif instruction.opname == 'li_ori':
                    instruction.immediate = self.return_if_int(instruction.immediate,
                                                               instruction=instruction)
                    immediate = to_twos_complement(instruction.immediate, num_bits=16)
                    encoded += to_hex(immediate, num_bits=16)[2:]
                else:
                    print(f"Expected li instruction, got {instruction.opname}\n"
                          f"Instruction: {instruction.content}")

            else:
                raise SyntaxError(f"Expected proper optype, got {instruction.optype}\n"
                                  f"Instruction: {instruction.content}")

            # instructions in hex, so 4 * 4 = 16-bit words
            assert len(encoded) == 4, f"Expected hex length 4, got {encoded}\n" \
                                      f"Instruction: {instruction.content}"

        # Comments and assembly code
        encoded += '; -- ' + repr(instruction.content)
        if instruction.comment:
            encoded += instruction.comment
        assert instruction.addr % 2 == 0, f"Expected word-aligned instruction, got {instruction.content}"
        mif_index = zero_extend(instruction.addr // 2, num_bits=16)
        encoded = mif_index + ' : ' + encoded

        return encoded
Beispiel #13
0
	def deserialize_hash256(self):
		return utils.to_hex(self.get_bytes(32))
Beispiel #14
0
	def deserialize_hash128(self):
		return utils.to_hex(self.get_bytes(16))
Beispiel #15
0
import leveldb
import sys

from utils import to_hex

if __name__ == '__main__':
    server_id = sys.argv[1]
    idx_ETH = sys.argv[2]
    idx_TOK = sys.argv[3]
    masked_amt_ETH = to_hex(sys.argv[4])
    masked_amt_TOK = to_hex(sys.argv[5])

    file = f"Scripts/hbswap/data/Pool-P{server_id}.data"
    pool_ETH, pool_TOK = 0, 0
    with open(file, 'rb') as f:
        pool_ETH = f.read(16)
        pool_TOK = f.read(16)

    db = leveldb.LevelDB(f"Scripts/hbswap/db/server{server_id}")
    mask_share_ETH = bytes(db.Get(idx_ETH.encode()))
    mask_share_TOK = bytes(db.Get(idx_TOK.encode()))

    file = f"Persistence/Transactions-P{server_id}.data"
    with open(file, 'wb') as f:
        f.write(pool_ETH + pool_TOK + mask_share_ETH + mask_share_TOK +
                masked_amt_ETH + masked_amt_TOK)
Beispiel #16
0
from utils import to_bin, to_hex, is_palindrome

with open("dane/dane.txt") as f:
    lines = [int(line.strip()) for line in f.readlines()]

bin_palindrome_count = 0
hex_palindrome_count = 0
for num in lines:
    num_bin = to_bin(num)
    num_hex = to_hex(num)

    if is_palindrome(str(num_bin)):
        bin_palindrome_count += 1

    if is_palindrome(str(num_hex)):
        hex_palindrome_count += 1

print(f"{bin_palindrome_count=}, {hex_palindrome_count=}")
Beispiel #17
0
	def deserialize_hash160(self):
		return utils.to_hex(self.get_bytes(20))
Beispiel #18
0
def parse_flow(flow):
    # parse flow fields
    # hex(int(mask, 16) & int(data, 16))
    if flow['cookie']:
        utils.to_hex(flow, 'cookie')
    # parse instructions
    for instruction in flow['instructions'].get('instruction', []):
        if 'write-metadata' in instruction:
            utils.to_hex(instruction['write-metadata'], 'metadata')
            utils.to_hex(instruction['write-metadata'], 'metadata-mask')
        if 'apply-actions' in instruction:
            for action in instruction['apply-actions'].get('action', []):
                if 'openflowplugin-extension-nicira-action:nx-reg-load' in action:
                    utils.to_hex(
                        action[
                            'openflowplugin-extension-nicira-action:nx-reg-load'],
                        'value')
    # parse matches
    if 'metadata' in flow['match']:
        metadata = flow['match']['metadata']
        utils.to_hex(metadata, 'metadata')
        utils.to_hex(metadata, 'metadata-mask')

    for ofex in flow['match'].get(
            'openflowplugin-extension-general:extension-list', []):
        if ofex['extension-key'] == 'openflowplugin-extension-nicira-match:nxm-nx-reg6-key':
            utils.to_hex(
                ofex['extension']
                ['openflowplugin-extension-nicira-match:nxm-nx-reg'], 'value')

    return flow
Beispiel #19
0
	def deserialize_vl(self):
		length = self.deserialize_vl_length()
		bytes  = self.get_bytes(length)
		return utils.to_hex(bytes).upper()