Пример #1
0
def _normalize_account(raw_account: RawAccountDetails) -> Account:
    return Account(
        balance=to_int(hexstr=raw_account.get('balance', '0x0')),
        nonce=to_int(hexstr=raw_account.get('nonce', '0x0')),
        code=decode_hex(raw_account.get('code', '')),
        storage=_normalize_storage(raw_account.get('storage', {})),
    )
Пример #2
0
 def __init__(self):
     self.result = {
         "hash32": test_block_hash.lower(),
         "address": test_address.lower(),
         "hexaddress": test_address.lower(),
         "checksumaddress": test_address,
         "hexstring": test_hexstring.lower(),
         "data": test_hexstring.lower(),
         "blocknumber": hex(56333),
         "integer": hex(9000),
         "data_list": test_data_list,
         "anyaddress": test_any_address.lower(),
         "blockid": test_block_num,
     }
     self.result_expect = {
         "hash32": to_bytes(None, self.result["hash32"]),
         "address": to_bytes(None, self.result["address"]),
         "hexaddress": to_normalized_address(self.result["hexaddress"]),
         "checksumaddress":
         to_checksum_address(self.result["checksumaddress"]),
         "anyaddress": to_bytes(None, self.result["anyaddress"]),
         "hexstring": to_text(None, self.result["hexstring"]),
         "data": to_text(None, self.result["data"]),
         "data_list":
         list(map(lambda z: to_text(z), self.result["data_list"])),
         "blocknumber": to_int(None, self.result["blocknumber"]),
         "integer": to_int(None, self.result["integer"]),
         "blockid": to_int(None, self.result["blockid"]),
     }
Пример #3
0
    def discard(self, checkpoint: JournalDBCheckpoint) -> None:
        self.logger.debug2('discard checkpoint %r', checkpoint)
        latest_clear_count = to_int(self._clear_count[CLEAR_COUNT_KEY_NAME])

        if self._journal_storage.has_checkpoint(checkpoint):
            self._journal_storage.discard(checkpoint)
            self._clear_count.discard(checkpoint)
        else:
            # if the checkpoint comes before this account started tracking,
            #    then simply reset to the beginning
            self._journal_storage.reset()
            self._clear_count.reset()
        self._storage_cache.reset_cache()

        reverted_clear_count = to_int(self._clear_count[CLEAR_COUNT_KEY_NAME])

        if reverted_clear_count == latest_clear_count - 1:
            # This revert rewinds past a trie deletion, so roll back to the trie at
            #   that point. We use the clear count as an index to get back to the
            #   old base trie.
            self._storage_lookup.rollback_trie(reverted_clear_count)
        elif reverted_clear_count == latest_clear_count:
            # No change in the base trie, take no action
            pass
        else:
            # Although CREATE2 permits multiple creates and deletes in a single block,
            #   you can still only revert across a single delete. That's because delete
            #   is only triggered at the end of the transaction.
            raise ValidationError(
                f"This revert has changed the clear count in an invalid way, from"
                f" {latest_clear_count} to {reverted_clear_count}, in 0x{self._address.hex()}"
            )
Пример #4
0
def get_chain_id() -> int:
    question = f"On what chain ID is your deployment located? {list(SUPPORTED_CHAIN_IDS.keys())} "
    chain_id = to_int(text=input(question))
    while chain_id not in SUPPORTED_CHAIN_IDS.keys():
        cli_logger.info(f"{chain_id} is not a supported chain id. ")
        chain_id = to_int(text=input(question))
    return chain_id
Пример #5
0
def extract_blake2b_parameters(input_bytes: bytes) -> TFCompressArgs:
    num_bytes = len(input_bytes)
    if num_bytes != 213:
        raise ValidationError(
            f"input length for Blake2 F precompile should be exactly 213 bytes, got: {num_bytes}"
        )

    rounds = to_int(input_bytes[:4])

    h_state = cast(TMessageBlock,
                   _get_64_bit_little_endian_words(input_bytes[4:68]))

    message = cast(TMessage,
                   _get_64_bit_little_endian_words(input_bytes[68:196]))

    t_offset_counters = cast(
        Tuple[int, int], _get_64_bit_little_endian_words(input_bytes[196:212]))

    final_block_int = to_int(input_bytes[212])
    if final_block_int == 0:
        final_block_flag = False
    elif final_block_int == 1:
        final_block_flag = True
    else:
        raise ValidationError(
            f"incorrect final block indicator flag, needed 0 or 1, got: {final_block_int}"
        )

    return rounds, h_state, message, t_offset_counters, final_block_flag
Пример #6
0
def coerce_type(solidity_type: str,
                value: bytes) -> Union[int, bool, str, ChecksumAddress, hex]:
    """
    Converts input to the indicated type.
    Args:
        solidity_type (str): String representation of type.
        value (bytes): The value to be converted.
    Returns:
        (Union[int, bool, str, ChecksumAddress, hex]): The type representation of the value.
    """
    if "int" in solidity_type:
        converted_value = to_int(value)
    elif "bool" in solidity_type:
        converted_value = bool(to_int(value))
    elif "string" in solidity_type:
        # length * 2 is stored in lower end bits
        # TODO handle bytes and strings greater than 32 bytes
        length = int(int.from_bytes(value[-2:], "big") / 2)
        converted_value = to_text(value[:length])

    elif "address" in solidity_type:
        converted_value = to_checksum_address(value)
    else:
        converted_value = value.hex()

    return converted_value
Пример #7
0
def test_payment_channel():
    contracts_code = prepare_contracts(["PaymentChannel.sol"])
    # print(contracts_code)
    fib = constructor.construct_contract(contracts_code["Fibonacci"])
    channel = constructor.construct_contract(contracts_code["PaymentChannel"],
                                             fib["address"])
    raw_contracts = constructor.generate_code([fib, channel])
    contracts = [ArbContract(raw) for raw in raw_contracts]
    fib = contracts[0]
    channel = contracts[1]
    vm = create_evm_vm(contracts)

    person_a = '0x1000000000000000000000000000000000000000'
    person_b = '0x2222222222222222222222222222222222222222'
    person_a_int = eth_utils.to_int(hexstr=person_a)
    person_b_int = eth_utils.to_int(hexstr=person_b)

    vm.env.send_message([channel.deposit(), person_a_int, 10000, 0, 0])
    vm.env.send_message([channel.getBalance(person_a), 0, 0, 0, 0])
    vm.env.send_message([channel.getBalance(person_b), 0, 0, 0, 0])
    vm.env.deliver_pending()
    run_until_halt(vm)
    vm.env.send_message(
        [channel.transferFib(person_b, 14), person_a_int, 0, 0, 0])
    vm.env.send_message([channel.getBalance(person_a), 0, 0, 0, 0])
    vm.env.send_message([channel.getBalance(person_b), 0, 0, 0, 0])
    vm.env.deliver_pending()
    run_until_halt(vm)
    vm.env.send_message([channel.withdraw(10), person_b_int, 0, 0, 0])
    vm.env.send_message([channel.getBalance(person_a), 0, 0, 0, 0])
    vm.env.send_message([channel.getBalance(person_b), 0, 0, 0, 0])
    vm.env.deliver_pending()
    run_until_halt(vm)
    print("Contract sent messages:", vm.sent_messages)
Пример #8
0
def get_pair_code(pair_id):
    """
    Get pair code from pair id
    """
    sub_symbol = pair_id.split("_")
    cash_code = TOKEN_CODE_DICT[sub_symbol[0]]
    stock_code = TOKEN_CODE_DICT[sub_symbol[1]]
    return eth_utils.to_int(cash_code) << 16 | eth_utils.to_int(stock_code)
Пример #9
0
def derive_child_key(
    parent_key: bytes,
    parent_chain_code: bytes,
    node: Node,
) -> Tuple[bytes, bytes]:
    """
    Compute a derivitive key from the parent key.

    From BIP32:

    The function CKDpriv((k_par, c_par), i) → (k_i, c_i) computes a child extended
    private key from the parent extended private key:

    1. Check whether the child is a hardened key (i ≥ 2**31). If the child is a hardened key,
       let I = HMAC-SHA512(Key = c_par, Data = 0x00 || ser_256(k_par) || ser_32(i)).
       (Note: The 0x00 pads the private key to make it 33 bytes long.)
       If it is not a hardened key, then
       let I = HMAC-SHA512(Key = c_par, Data = ser_P(point(k_par)) || ser_32(i)).
    2. Split I into two 32-byte sequences, I_L and I_R.
    3. The returned child key k_i is parse_256(I_L) + k_par (mod n).
    4. The returned chain code c_i is I_R.
    5. In case parse_256(I_L) ≥ n or k_i = 0, the resulting key is invalid,
       and one should proceed with the next value for i.
       (Note: this has probability lower than 1 in 2**127.)

    """
    assert len(parent_chain_code) == 32
    if isinstance(node, HardNode):
        # NOTE Empty byte is added to align to SoftNode case
        assert len(
            parent_key) == 32  # Should be guaranteed here in return statment
        child = hmac_sha512(parent_chain_code,
                            b"\x00" + parent_key + node.serialize())

    elif isinstance(node, SoftNode):
        assert len(ec_point(
            parent_key)) == 33  # Should be guaranteed by Account class
        child = hmac_sha512(parent_chain_code,
                            ec_point(parent_key) + node.serialize())

    else:
        raise ValidationError(f"Cannot process: {node}")

    assert len(child) == 64

    if to_int(child[:32]) >= SECP256K1_N:
        # Invalid key, compute using next node (< 2**-127 probability)
        return derive_child_key(parent_key, parent_chain_code, node + 1)

    child_key = (to_int(child[:32]) + to_int(parent_key)) % SECP256K1_N
    if child_key == 0:
        # Invalid key, compute using next node (< 2**-127 probability)
        return derive_child_key(parent_key, parent_chain_code, node + 1)

    child_key_bytes = child_key.to_bytes(32, byteorder="big")
    child_chain_code = child[32:]
    return child_key_bytes, child_chain_code
Пример #10
0
 def addHome(self, adr, area, cost):
     self.nonce = self.w3.eth.getTransactionCount(self.account_address)
     transaction = self.contract.functions.AddHome(adr, to_int(text=area), to_int(text=cost)).buildTransaction({
         'gas': 3000000,
         'gasPrice': self.w3.toWei('1', 'gwei'),
         'from': self.account_address,
         'nonce': self.nonce
     })
     self.sendTransaction(transaction)
     return "Операция прошла успешно."
Пример #11
0
 def __init__(self, contractInfo):
     self.address_string = contractInfo["address"]
     self.address = eth_utils.to_int(hexstr=self.address_string)
     self.code = bytes.fromhex(contractInfo["code"][2:])
     self.storage = {}
     if "storage" in contractInfo:
         raw_storage = contractInfo["storage"]
         for item in raw_storage:
             key = eth_utils.to_int(hexstr=item)
             self.storage[key] = eth_utils.to_int(hexstr=raw_storage[item])
Пример #12
0
def main():
    if len(sys.argv) != 2:
        raise Exception("Call as truffle_runner.py [compiled.json]")

    with open(sys.argv[1]) as json_file:
        raw_contracts = json.load(json_file)

    contracts = [ContractABI(contract) for contract in raw_contracts]
    vm = create_evm_vm(contracts)
    output_handler = create_output_handler(contracts)
    with open("code.txt", "w") as f:
        for instr in vm.code:
            f.write("{} {}".format(instr, instr.path))
            f.write("\n")
    contract = contracts[0]

    person_a = "0x1111111122222222000000000000000000000000"
    person_b = "0x2222222222222222222222222222222222222222"
    person_a_int = eth_utils.to_int(hexstr=person_a)
    person_b_int = eth_utils.to_int(hexstr=person_b)
    print("person_a_int", person_a_int)
    print("person_b_int", person_b_int)
    erc20_address = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"
    erc721_address = "0x06012c8cf97BEaD5deAe237070F9587f8E7A266d"

    vm.env.send_message([
        make_msg_val(contract.deposit(10)),
        person_a_int,
        10000000,
        eth_utils.to_int(hexstr=erc20_address + "00"),
    ])

    vm.env.send_message([
        make_msg_val(contract.sendERC20(12, erc20_address, 5432)),
        person_a_int, 0, 0
    ])

    vm.env.send_message([
        make_msg_val(contract.deposit(10)),
        person_a_int,
        10000000,
        eth_utils.to_int(hexstr=erc721_address + "01"),
    ])

    vm.env.send_message([
        make_msg_val(contract.sendERC721(12, erc721_address, 10000000)),
        person_a_int,
        0,
        0,
    ])

    vm.env.deliver_pending()
    logs = run_until_halt(vm)
    for log in logs:
        print(output_handler(log))
Пример #13
0
def _extract_vm_config(vm_config: Dict[str, str]) -> Iterable[VMFork]:
    if 'frontierForkBlock' in vm_config.keys():
        yield to_int(hexstr=vm_config['frontierForkBlock']), FrontierVM
    if 'homesteadForkBlock' in vm_config.keys():
        homestead_fork_block = to_int(hexstr=vm_config['homesteadForkBlock'])
        if 'DAOForkBlock' in vm_config:
            dao_fork_block_number = to_int(hexstr=vm_config['DAOForkBlock'])

            HomesteadVM = MainnetDAOValidatorVM.configure(
                _dao_fork_block_number=dao_fork_block_number, )
            yield homestead_fork_block, HomesteadVM
        else:
            yield homestead_fork_block, BaseHomesteadVM
    if 'EIP150ForkBlock' in vm_config.keys():
        yield to_int(hexstr=vm_config['EIP150ForkBlock']), TangerineWhistleVM
    if 'EIP158ForkBlock' in vm_config.keys():
        yield to_int(hexstr=vm_config['EIP158ForkBlock']), SpuriousDragonVM
    if 'byzantiumForkBlock' in vm_config.keys():
        yield to_int(hexstr=vm_config['byzantiumForkBlock']), ByzantiumVM
    if 'constantinopleForkBlock' in vm_config.keys():
        yield to_int(
            hexstr=vm_config['constantinopleForkBlock']), ConstantinopleVM
    if 'petersburgForkBlock' in vm_config.keys():
        yield to_int(hexstr=vm_config['petersburgForkBlock']), PetersburgVM
    if 'istanbulForkBlock' in vm_config.keys():
        yield to_int(hexstr=vm_config['istanbulForkBlock']), IstanbulVM
Пример #14
0
def etherscan_query_with_retries(url, sleep, retries=3):
    for _ in range(retries - 1):
        try:
            etherscan_block = to_int(hexstr=requests.get(url).json()['result'])
        except (RequestException, ValueError, KeyError):
            gevent.sleep(sleep)
        else:
            return etherscan_block

    etherscan_block = to_int(hexstr=requests.get(url).json()['result'])
    return etherscan_block
Пример #15
0
 def encode(self) -> bytes:
     data = self.as_dict()
     unsigned_txn = serializable_unsigned_transaction_from_dict(data)
     return encode_transaction(
         unsigned_txn,
         (
             to_int(self.signature[:1]),
             to_int(self.signature[1:33]),
             to_int(self.signature[33:65]),
         ),
     )
Пример #16
0
def extract_genesis_params(genesis_config: RawEIP1085Dict) -> GenesisParams:
    raw_params = genesis_config['genesis']

    return GenesisParams(
        nonce=decode_hex(raw_params['nonce']),
        difficulty=to_int(hexstr=raw_params['difficulty']),
        extra_data=Hash32(decode_hex(raw_params['extraData'])),
        gas_limit=to_int(hexstr=raw_params['gasLimit']),
        coinbase=Address(decode_hex(raw_params['author'])),
        timestamp=to_int(hexstr=raw_params['timestamp']),
    )
Пример #17
0
 def addRequest(self, type, adr, area, cost, adrNewOwner):
     if not self.w3.isAddress(adrNewOwner):
         return "Ошибка ввода данных."
     self.nonce = self.w3.eth.getTransactionCount(self.account_address)
     transaction = self.contract.functions.AddRequest(to_int(text=type), adr, to_int(text=area), to_int(text=cost), adrNewOwner).buildTransaction({
         'gas': 3000000,
         'gasPrice': self.w3.toWei('1', 'gwei'),
         'from': self.account_address,
         'nonce': self.nonce,
         'value': self.w3.toWei('1', 'gwei')
     })
     self.sendTransaction(transaction)
     return "Операция прошла успешно."
Пример #18
0
 def parse_obj(cls: Type[eth_models.T], data: Dict):
     data["hash32"] = to_bytes(hexstr=data["hash32"])
     data["address"] = to_bytes(None, data["address"])
     data["hexaddress"] = to_normalized_address(data["hexaddress"])
     data["checksumaddress"] = data["checksumaddress"]
     data["anyaddress"] = to_bytes(None, data["anyaddress"])
     data["hexstring"] = to_text(None, data["hexstring"])
     data["data"] = to_text(None, data["data"])
     data["data_list"] = list(map(lambda z: to_text(z), data["data_list"]))
     data["blocknumber"] = to_int(None, data["blocknumber"])
     data["integer"] = to_int(None, data["integer"])
     data["blockid"] = to_int(None, data["blockid"])
     return cls(**data)
Пример #19
0
def etherscan_query_with_retries(url: str,
                                 sleep: float,
                                 retries: int = 3) -> int:
    for _ in range(retries - 1):
        try:
            etherscan_block = to_int(hexstr=requests.get(url).json()["result"])
        except (RequestException, ValueError, KeyError):
            gevent.sleep(sleep)
        else:
            return etherscan_block

    etherscan_block = to_int(hexstr=requests.get(url).json()["result"])
    return etherscan_block
Пример #20
0
def etherscan_query_with_retries(
        url: str,
        sleep: float,
        retries: int = 3,
) -> int:
    for _ in range(retries - 1):
        try:
            etherscan_block = to_int(hexstr=requests.get(url).json()['result'])
        except (RequestException, ValueError, KeyError):
            gevent.sleep(sleep)
        else:
            return etherscan_block

    etherscan_block = to_int(hexstr=requests.get(url).json()['result'])
    return etherscan_block
Пример #21
0
def etherscan_query_with_retries(url: str, sleep: float, retries: int = 3) -> int:
    def get_result():
        response = requests.get(url)
        return json.loads(response.content)["result"]

    for _ in range(retries - 1):
        try:
            etherscan_block = to_int(hexstr=get_result())
        except (RequestException, ValueError, KeyError):
            gevent.sleep(sleep)
        else:
            return etherscan_block

    etherscan_block = to_int(hexstr=get_result())
    return etherscan_block
Пример #22
0
def _rpc_request_to_filter_params(raw_params: RawFilterParams) -> FilterParams:
    address: Union[None, Address, Tuple[Address, ...]]

    if "address" not in raw_params:
        address = None
    elif raw_params["address"] is None:
        address = None
    elif is_address(raw_params["address"]):
        address = to_canonical_address(raw_params["address"])  # type: ignore
    elif isinstance(raw_params["address"], list):
        address = tuple(
            to_canonical_address(sub_address)
            for sub_address in raw_params["address"])
    else:
        raise TypeError(f"Unsupported address: {raw_params['address']!r}")

    topics: FilterTopics

    if "topics" not in raw_params:
        topics = ()
    elif raw_params["topics"] is None:
        topics = ()
    elif isinstance(raw_params["topics"], Sequence):
        topics = _normalize_topics(raw_params["topics"])  # type: ignore
    else:
        raise TypeError(f"Unsupported topics: {raw_params['topics']!r}")

    from_block: Optional[BlockNumber]
    if "fromBlock" not in raw_params:
        from_block = None
    elif raw_params["fromBlock"] is None:
        from_block = None
    elif isinstance(raw_params["fromBlock"], str):
        from_block = BlockNumber(to_int(hexstr=raw_params["fromBlock"]))
    else:
        raise TypeError(f"Unsupported fromBlock: {raw_params['fromBlock']!r}")

    to_block: Optional[BlockNumber]
    if "toBlock" not in raw_params:
        to_block = None
    elif raw_params["toBlock"] is None:
        to_block = None
    elif isinstance(raw_params["toBlock"], str):
        to_block = BlockNumber(to_int(hexstr=raw_params["toBlock"]))
    else:
        raise TypeError(f"Unsupported toBlock: {raw_params['toBlock']!r}")

    return FilterParams(from_block, to_block, address, topics)
Пример #23
0
def build_etherscan_manifest(uri: URI, package_name: str,
                             version: str) -> Iterable[Tuple[str, Any]]:
    address, chain_id = parse.urlparse(uri).netloc.split(":")
    network = get_etherscan_network(chain_id)
    body = make_etherscan_request(address, network)
    contract_type = body["ContractName"]
    w3 = setup_w3(to_int(text=chain_id))
    block_uri = create_latest_block_uri(w3)
    runtime_bytecode = to_hex(
        w3.eth.getCode(ChecksumAddress(HexAddress(HexStr(address)))))

    yield "package_name", package_name
    yield "version", version
    yield "manifest_version", "2"
    yield "sources", {f"./{contract_type}.sol": body["SourceCode"]}
    yield "contract_types", {
        contract_type: {
            "abi": json.loads(body["ABI"]),
            "runtime_bytecode": {
                "bytecode": runtime_bytecode
            },
            "compiler": generate_compiler_info(body),
        }
    }
    yield "deployments", {
        block_uri: {
            contract_type: {
                "contract_type": contract_type,
                "address": address
            }
        }
    }
Пример #24
0
def getstorageatindex(contractaddress, i, k, provider='http://127.0.0.1:8545'):
    web3 = Web3(Web3.HTTPProvider(provider, request_kwargs={'timeout': 60}))
    pos = str(remove_0x_prefix(i)).rjust(64, '0')
    key = remove_0x_prefix(k).rjust(64, '0').lower()
    storage_key = to_hex(web3.sha3(hexstr=key + pos))
    return storage_key, to_int(
        web3.eth.getStorageAt(contractaddress, storage_key))
Пример #25
0
def parse_byetherscan_uri(parsed: urllib.parse.ParseResult,
                          network_id: int) -> Checkpoint:

    try:
        network = Network(network_id)
    except ValueError:
        raise ValidationError(
            f"Can not resolve checkpoint through Etherscan API"
            f"for network {network_id}. Network not supported")

    try:
        etherscan_api_key = os.environ['TRINITY_ETHERSCAN_API_KEY']
    except KeyError:
        raise RuntimeError(
            "Etherscan API key missing. Assign your Etherscan API key "
            "to the TRINITY_ETHERSCAN_API_KEY environment variable.")

    etherscan_api = Etherscan(etherscan_api_key)

    latest_block_number = etherscan_api.get_latest_block(network)
    checkpoint_block_number = latest_block_number - BLOCKS_FROM_TIP
    checkpoint_block_response = etherscan_api.get_block_by_number(
        checkpoint_block_number, network)
    checkpoint_score = to_int(
        hexstr=checkpoint_block_response['totalDifficulty'])
    checkpoint_hash = checkpoint_block_response['hash']

    return Checkpoint(Hash32(decode_hex(checkpoint_hash)), checkpoint_score)
def test_get_clique_checkpoint_block_number(network_id, epoch_length):
    try:
        block = get_checkpoint_block_byetherscan(network_id)
    except EtherscanAPIError as e:
        warnings.warn(UserWarning(f'Etherscan API issue: "{e}"'))
    else:
        assert to_int(hexstr=block.get('number')) % epoch_length == 0
Пример #27
0
def ecies_decrypt(priv_key, message_parts):
    sender_public_key_obj = ec.EllipticCurvePublicKey.from_encoded_point(
        ec.SECP256K1(), message_parts["ephemPublicKey"])
    private_key_obj = ec.derive_private_key(eth_utils.to_int(priv_key),
                                            ec.SECP256K1(), default_backend())
    aes_shared_key = private_key_obj.exchange(ec.ECDH(), sender_public_key_obj)
    # Now let's do AES-CBC with this, including the hmac matching (modeled after eccrypto code).
    aes_keyhash = hashlib.sha512(aes_shared_key).digest()
    hmac_key = aes_keyhash[32:]
    test_hmac = hmac.new(
        hmac_key, message_parts["iv"] + message_parts["ephemPublicKey"] +
        message_parts["ciphertext"], hashlib.sha256).digest()
    if test_hmac != message_parts["mac"]:
        raise Exception("Mac does not match")
    aes_key = aes_keyhash[:32]
    # Actual decrypt is modeled after ecies.utils.aes_decrypt() - but with CBC mode to match eccrypto.
    aes_cipher = AES.new(aes_key, AES.MODE_CBC, iv=message_parts["iv"])
    try:
        decrypted_bytes = aes_cipher.decrypt(message_parts["ciphertext"])
        # Padding characters (unprintable) may be at the end to fit AES block size, so strip them.
        unprintable_chars = bytes(
            ''.join(map(chr, range(0, 32))).join(map(chr, range(127, 160))),
            'utf-8')
        decrypted_string = decrypted_bytes.rstrip(unprintable_chars).decode(
            "utf-8")
        return decrypted_string
    except:
        raise Exception("Could not decode ciphertext")
Пример #28
0
def get_side_token(
    *,
    web3: Web3,
    bridge_contract: Contract,
    main_token_address,
):
    is_main_token = bridge_contract.functions.knownTokens(
        address(main_token_address)).call()
    if is_main_token:
        logger.info('Token %s is main token', main_token_address)
        return None

    side_token_address = bridge_contract.functions.mappedTokens(
        address(main_token_address)).call()
    if to_int(hexstr=side_token_address) == 0:
        logger.error('side token not found for %s', main_token_address)
        return None

    side_token_contract = get_erc20_contract(
        web3=web3,
        token_address=side_token_address,
    )
    side_token_symbol = side_token_contract.functions.symbol().call()
    side_token_decimals = side_token_contract.functions.decimals().call()
    return SideToken(
        address=side_token_address.lower(),
        symbol=side_token_symbol,
        decimals=side_token_decimals,
        contract=side_token_contract,
    )
Пример #29
0
    def set(self, key, value):
        """
        Returns all updated hashes in root->leaf order
        """
        validate_is_bytes(key)
        validate_length(key, 20)
        validate_is_bytes(value)

        path = to_int(key)
        branch = self.branch(key)
        node = value
        proof_update = []

        target_bit = 1
        # branch is in root->leaf order, so flip
        for sibling in reversed(branch):
            # Set
            node_hash = keccak(node)
            proof_update.append(node_hash)
            self.db[node_hash] = node

            # Update
            if (path & target_bit):
                node = sibling + node_hash
            else:
                node = node_hash + sibling

            target_bit <<= 1

        self.root_hash = keccak(node)
        self.db[self.root_hash] = node
        # updates need to be in root->leaf order, so flip back
        return list(reversed(proof_update))
Пример #30
0
    def decode(cls, encoded: bytes) -> ReceiptAPI:
        type_id = to_int(encoded[0])
        payload = encoded[1:]

        payload_codec = cls.get_payload_codec(type_id)
        inner_receipt = payload_codec.decode(payload)
        return cls(type_id, inner_receipt)
Пример #31
0
    def decode(cls, encoded: bytes) -> SignedTransactionAPI:
        type_id = to_int(encoded[0])
        payload = encoded[1:]

        payload_codec = cls.get_payload_codec(type_id)
        inner_transaction = payload_codec.decode(payload)
        return cls(type_id, inner_transaction)