Python web3.Web3.toHex() Examples

The following are 13 code examples of web3.Web3.toHex(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module web3.Web3 , or try the search function .
Example #1
Source File: blockchain_address.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, type, blockchain_address=None):

        if type not in self.allowed_types():
            raise Exception("type {} not one of {}".format(type, self.allowed_types()))

        self.type = type

        if blockchain_address:
            self.address = blockchain_address

        if self.type == "TRANSFER_ACCOUNT" and not blockchain_address:

            hex_private_key = Web3.toHex(keccak(os.urandom(4096)))

            self.encoded_private_key = self.encrypt_private_key(hex_private_key)

            self.calculate_address(hex_private_key) 
Example #2
Source File: base.py    From clove with GNU General Public License v3.0 6 votes vote down vote up
def get_raw_transaction(transaction: Transaction) -> str:
        '''
        Get raw_transaction by encoding Transaction object

        Args:
            transaction (`ethereum.transactions.Transaction`): Ethereum transaction object

        Returns:
            str: raw transaction hex string

        Example:
            >>> from clove.network import EthereumTestnet
            >>> network = EthereumTestnet()
            >>> transaction = network.deserialize_raw_transaction('0xf8f28201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a9092000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000808080')  # noqa: E501
            >>> network.get_raw_transaction(transaction)
            '0xf8f28201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a9092000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000808080'  # noqa: E501
        '''
        return Web3.toHex(rlp.encode(transaction)) 
Example #3
Source File: models.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, private_key=None, wei_target_balance=None, wei_topup_threshold=None):

        if private_key:
            self.private_key = private_key
        else:
            self.private_key = Web3.toHex(keccak(os.urandom(4096)))

        self.wei_target_balance = wei_target_balance
        self.wei_topup_threshold = wei_topup_threshold

# https://stackoverflow.com/questions/20830118/creating-a-self-referencing-m2m-relationship-in-sqlalchemy-flask 
Example #4
Source File: transaction.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def raw_transaction(self) -> str:
        '''Returns raw transaction serialized to hex.'''
        return Web3.toHex(rlp.encode(self.tx)) 
Example #5
Source File: test_logs.py    From casper with The Unlicense 5 votes vote down vote up
def test_epoch_insta_finalize_logs(tester,
                                   concise_casper,
                                   casper_epoch_filter,
                                   new_epoch):
    start_epoch = concise_casper.START_EPOCH()
    new_epoch()
    new_epoch()
    logs = casper_epoch_filter.get_new_entries()
    assert len(logs) == 4
    log_old = logs[-2]['args']
    log_new = logs[-1]['args']

    log_fields = {
        '_number',
        '_checkpoint_hash',
        '_is_justified',
        '_is_finalized'
    }
    assert log_fields == log_old.keys()

    # New epoch log
    assert log_new['_number'] == start_epoch + 2
    init_block_number = tester.get_block_by_number('latest')['number'] - 1
    # block before epoch init == checkpoint hash
    assert Web3.toHex(log_new['_checkpoint_hash']) == \
        tester.get_block_by_number(init_block_number - 1)['hash']
    assert log_new['_is_justified'] is False
    assert log_new['_is_finalized'] is False

    # Insta-finalized previous epoch
    assert log_old['_number'] == start_epoch + 1
    # block before previous epoch init == checkpoint hash
    prev_epoch_block_number = init_block_number - concise_casper.EPOCH_LENGTH()
    assert Web3.toHex(log_old['_checkpoint_hash']) == \
        tester.get_block_by_number(prev_epoch_block_number - 1)['hash']
    assert log_old['_is_justified'] is True
    assert log_old['_is_finalized'] is True 
Example #6
Source File: context.py    From evmlab with GNU General Public License v3.0 5 votes vote down vote up
def findContractForBytecode(contracts, bytecode):
    if type(bytecode) is HexBytes:
        bytecode = Web3.toHex(bytecode)

    if  bytecode.startswith('0x'):
        bytecode = bytecode[2:]

    for c in contracts:
        # ignore last 34 bytes which is just metadata
        if c.bin and c.bin[:-68] == bytecode[:-68] or c.binRuntime and c.binRuntime[:-68] == bytecode[:-68]:
            return c

    return None 
Example #7
Source File: test_get_registry.py    From web3.py with MIT License 5 votes vote down vote up
def test_labelhash(ens, label, expected_hash):
    if isinstance(expected_hash, type):
        with pytest.raises(expected_hash):
            ens.labelhash(label)
    else:
        labelhash = ens.labelhash(label)
        assert isinstance(labelhash, bytes)
        hash_hex = Web3.toHex(labelhash)
        assert hash_hex == expected_hash 
Example #8
Source File: test_conversions.py    From web3.py with MIT License 5 votes vote down vote up
def test_to_hex(val, expected):
    assert Web3.toHex(val) == expected 
Example #9
Source File: test_conversions.py    From web3.py with MIT License 5 votes vote down vote up
def test_to_hex_text(val, expected):
    assert Web3.toHex(text=val) == expected 
Example #10
Source File: test_conversions.py    From web3.py with MIT License 5 votes vote down vote up
def test_to_hex_cleanup_only(val, expected):
    assert Web3.toHex(hexstr=val) == expected 
Example #11
Source File: test_logs.py    From casper with The Unlicense 4 votes vote down vote up
def test_epoch_with_validator_logs(tester,
                                   casper,
                                   concise_casper,
                                   casper_epoch_filter,
                                   new_epoch,
                                   induct_validator,
                                   funded_account,
                                   validation_key,
                                   deposit_amount,
                                   send_vote,
                                   mk_suggested_vote):
    validator_index = induct_validator(funded_account, validation_key, deposit_amount)

    last_block_number = tester.get_block_by_number('latest')['number'] - 1

    send_vote(mk_suggested_vote(validator_index, validation_key))

    logs = casper_epoch_filter.get_new_entries()
    last_epoch_hash = tester.get_block_by_number(last_block_number - 1)['hash']
    last_epoch_log = [
        log for log in logs
        if Web3.toHex(log['args']['_checkpoint_hash']) == last_epoch_hash
    ][-1]['args']
    assert last_epoch_log['_is_justified'] is True
    assert last_epoch_log['_is_finalized'] is False

    new_epoch()
    last_block_number = tester.get_block_by_number('latest')['number'] - 1
    send_vote(mk_suggested_vote(validator_index, validation_key))

    logs = casper_epoch_filter.get_new_entries()
    last_epoch_hash = tester.get_block_by_number(last_block_number - 1)['hash']
    last_epoch_log = [
        log for log in logs
        if Web3.toHex(log['args']['_checkpoint_hash']) == last_epoch_hash
    ][-1]['args']
    prev_epoch_hash = tester.get_block_by_number(
        last_block_number - concise_casper.EPOCH_LENGTH() - 1
    )['hash']
    prev_epoch_log = [
        log for log in logs
        if Web3.toHex(log['args']['_checkpoint_hash']) == prev_epoch_hash
    ][-1]['args']

    assert prev_epoch_log['_is_justified'] is True
    assert prev_epoch_log['_is_finalized'] is True

    assert last_epoch_log['_is_justified'] is True
    assert last_epoch_log['_is_finalized'] is False 
Example #12
Source File: marketplace.py    From catalyst with Apache License 2.0 4 votes vote down vote up
def publish(self, dataset, datadir, watch):
        dataset = dataset.lower()
        provider_info = self.mkt_contract.functions.getDataProviderInfo(
            Web3.toHex(dataset.encode())
        ).call()

        if not provider_info[4]:
            raise MarketplaceDatasetNotFound(dataset=dataset)

        match = next(
            (l for l in self.addresses if l['pubAddr'] == provider_info[0]),
            None
        )
        if not match:
            raise MarketplaceNoAddressMatch(
                dataset=dataset,
                address=provider_info[0])

        print('Using address: {} to publish this dataset.'.format(
            provider_info[0]))

        if 'key' in match:
            key = match['key']
            secret = match['secret']
        else:
            key, secret = get_key_secret(provider_info[0], match['wallet'])

        filenames = glob.glob(os.path.join(datadir, '*.csv'))

        if not filenames:
            raise MarketplaceNoCSVFiles(datadir=datadir)

        def read_file(pathname):
            with open(pathname, 'rb') as f:
                return f.read()

        files = []
        for idx, file in enumerate(filenames):
            log.info('Uploading file {} of {}: {}'.format(
                idx + 1, len(filenames), file))
            files.append(('file', (os.path.basename(file), read_file(file))))

        headers = get_signed_headers(dataset, key, secret)
        r = requests.post('{}/marketplace/publish'.format(AUTH_SERVER),
                          files=files,
                          headers=headers)

        if r.status_code != 200:
            raise MarketplaceHTTPRequest(request='upload file',
                                         error=r.status_code)

        if 'error' in r.json():
            raise MarketplaceHTTPRequest(request='upload file',
                                         error=r.json()['error'])

        log.info('File processed successfully.')

        print('\nDataset {} uploaded and processed successfully.'.format(
            dataset)) 
Example #13
Source File: marketplace.py    From catalyst with Apache License 2.0 4 votes vote down vote up
def get_withdraw_amount(self, dataset=None):

        if dataset is None:

            df_sets = self._list()
            if df_sets.empty:
                print('There are no datasets available yet.')
                return

            set_print_settings()
            while True:
                print(df_sets)
                dataset_num = input('Choose the dataset you want to '
                                    'get the withdraw amount for '
                                    '[0..{}]: '.format(df_sets.size - 1))
                try:
                    dataset_num = int(dataset_num)
                except ValueError:
                    print('Enter a number between 0 and {}'.format(
                        df_sets.size - 1))
                else:
                    if dataset_num not in range(0, df_sets.size):
                        print('Enter a number between 0 and {}'.format(
                            df_sets.size - 1))
                    else:
                        dataset = df_sets.iloc[dataset_num]['dataset']
                        break

        dataset = dataset.lower()

        # address = self.choose_pubaddr()[0]
        provider_info = self.mkt_contract.functions.getDataProviderInfo(
            Web3.toHex(dataset.encode())
        ).call()

        if not provider_info[4]:
            print('The requested "{}" dataset is not registered in '
                  'the Data Marketplace.'.format(dataset))
            return

        withdraw_amount = from_grains(
            self.mkt_contract.functions.getWithdrawAmount(
                Web3.toHex(dataset.encode())).call())
        print('{} ENG'.format(withdraw_amount))