Python ethereum.utils.privtoaddr() Examples

The following are 17 code examples of ethereum.utils.privtoaddr(). 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 ethereum.utils , or try the search function .
Example #1
Source File: post_contract_ui.py    From smart_contracts with MIT License 6 votes vote down vote up
def call_const_function( priv_key, value, contract_hash, contract_abi, function_name, args ):
    src_address = b2h( utils.privtoaddr(priv_key) )    
    translator = ContractTranslator(contract_abi)
    call = translator.encode_function_call(function_name, args)  
    nonce = get_num_transactions( src_address )
    gas_price = get_gas_price_in_wei()
    
    start_gas = eval_startgas( src_address, contract_hash, value, b2h(call), gas_price )    
    nonce = int( nonce, 16 )
    gas_price = int( gas_price, 16 )
    start_gas = int( start_gas, 16 ) + 100000
    
    params = { "from" : "0x" + src_address,
               "to"   : "0x" + contract_hash,
               "gas"  : "0x" + str(start_gas),
               "gasPrice" : "0x" + str(gas_price),
               "value" : str(value),
               "data" : "0x" + b2h(call) }
    
    return_value = json_call( "eth_call", [params])
    return_value = h2b(return_value[2:]) # remove 0x
    return translator.decode(function_name, return_value) 
Example #2
Source File: test_gnt.py    From golem-crowdfunding with GNU General Public License v3.0 6 votes vote down vote up
def test_gas_for_set_migration_agent_and_master(self):
        factory_key = urandom(32)
        addr, _ = self.deploy_contract(privtoaddr(factory_key), 1, 2)
        self.state.mine(1)
        for i, k in enumerate(tester.keys):
            v = random.randrange(15000 * denoms.ether, 82000 * denoms.ether)
            self.c.create(sender=k, value=v)
        self.state.mine(2)
        self.c.finalize()
        m_addr, _ = self.deploy_migration_contract(addr)
        self.state.mine()

        lg = self.state.block.gas_used
        self.c.setMigrationAgent(m_addr, sender=factory_key)
        g = self.state.block.gas_used - lg
        assert g == 44169

        lg = self.state.block.gas_used
        self.c.setMigrationMaster(m_addr, sender=factory_key)
        g = self.state.block.gas_used - lg
        assert g == 28570 
Example #3
Source File: ethereum_processor.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 contract_address,
                 contract_abi_string,
                 ethereum_chain_id,
                 http_provider,
                 websocket_provider,
                 gas_price_gwei,
                 gas_limit,
                 contract_owner_private_key):

        super(MintableERC20Processor, self).__init__(contract_address,
                                                     contract_abi_string,
                                                     ethereum_chain_id,
                                                     http_provider,
                                                     websocket_provider,
                                                     gas_price_gwei,
                                                     gas_limit)

        self.master_wallet_private_key = contract_owner_private_key
        self.master_wallet_address = Web3.toChecksumAddress(utils.privtoaddr(self.master_wallet_private_key)) 
Example #4
Source File: test_gnt.py    From golem-crowdfunding with GNU General Public License v3.0 6 votes vote down vote up
def test_gas_for_migrate_half(self):
        factory_key = urandom(32)
        addr, _ = self.deploy_contract(privtoaddr(factory_key), 1, 2)
        self.state.mine(1)
        for i, k in enumerate(tester.keys):
            v = random.randrange(15000 * denoms.ether, 82000 * denoms.ether)
            self.c.create(sender=k, value=v)
        self.state.mine(2)
        self.c.finalize()
        m_addr, _ = self.deploy_migration_contract(addr)
        t_addr, _ = self.deploy_target_contract(m_addr)
        self.c.setMigrationAgent(m_addr, sender=factory_key)
        self.m.setTargetToken(t_addr, sender=tester.k9)
        self.state.mine()
        self.state.block.coinbase = urandom(20)
        costs = []
        for i, k in enumerate(tester.keys):
            b = self.c.balanceOf(tester.accounts[i])
            m = self.monitor(i)
            self.c.migrate(b / 2, sender=k)
            costs.append(m.gas())
        print(costs)
        assert max(costs) <= 114304
        assert min(costs) >= 71037 
Example #5
Source File: test_gnt.py    From golem-crowdfunding with GNU General Public License v3.0 6 votes vote down vote up
def test_gas_for_migrate_all(self):
        factory_key = urandom(32)
        addr, _ = self.deploy_contract(privtoaddr(factory_key), 1, 2)
        self.state.mine(1)
        for i, k in enumerate(tester.keys):
            v = random.randrange(15000 * denoms.ether, 82000 * denoms.ether)
            self.c.create(sender=k, value=v)
        self.state.mine(2)
        self.c.finalize()
        m_addr, _ = self.deploy_migration_contract(addr)
        t_addr, _ = self.deploy_target_contract(m_addr)
        self.c.setMigrationAgent(m_addr, sender=factory_key)
        self.m.setTargetToken(t_addr, sender=tester.k9)
        self.state.mine()
        self.state.block.coinbase = urandom(20)
        costs = []
        for i, k in enumerate(tester.keys):
            b = self.c.balanceOf(tester.accounts[i])
            m = self.monitor(i)
            self.c.migrate(b, sender=k)
            costs.append(m.gas())
        print(costs)
        assert max(costs) <= 99304
        assert min(costs) >= 56037 
Example #6
Source File: create_multiple_safes.py    From safe-relay-service with MIT License 6 votes vote down vote up
def deploy_safes(number, owners, private_key):
    safes = []
    funding_public_key = checksum_encode(privtoaddr(private_key))
    funding_nonce = w3.eth.getTransactionCount(funding_public_key, 'pending')
    for _ in range(number):
        payload_json = generate_payload(owners)
        r = requests.post(SAFES_URL, json=payload_json)
        assert r.ok
        safe_created = r.json()
        safe_address = safe_created['safe']
        payment = int(safe_created['payment'])

        logging.info('Created safe=%s, need payment=%d', safe_address, payment)
        send_eth(private_key, safe_address, payment, funding_nonce)
        logging.info('Sent payment=%s to safe=%s', payment, safe_address)
        r = requests.put(get_safes_notify_url(safe_address))
        assert r.ok
        funding_nonce += 1
        safes.append(safe_address)

    with open('safes.txt', mode='a') as safes_file:
        safes_file.write('\n'.join(safes))


# notify_safes() 
Example #7
Source File: conftest.py    From eth-testrpc with MIT License 5 votes vote down vote up
def account_public_key(account_private_key):
    from ethereum.utils import privtoaddr
    from testrpc.client.utils import encode_address
    return encode_address(privtoaddr(account_private_key)) 
Example #8
Source File: post_contract_ui.py    From smart_contracts with MIT License 5 votes vote down vote up
def make_transaction( src_priv_key, dst_address, value, data ):
    src_address = b2h( utils.privtoaddr(src_priv_key) )
    nonce = get_num_transactions( src_address )
    gas_price = get_gas_price_in_wei()
    data_as_string = b2h(data)
    start_gas = eval_startgas( src_address, dst_address, value, data_as_string, gas_price )
    
    nonce = int( nonce, 16 )
    gas_price = int( gas_price, 16 )
    start_gas = int( start_gas, 16 ) + 100000
    
    tx = transactions.Transaction( nonce,
                                   gas_price,
                                   start_gas,
                                   dst_address,
                                   value,
                                   data ).sign(src_priv_key)
    
    
                                   
    tx_hex  = b2h(rlp.encode(tx))
    tx_hash = b2h( tx.hash )
    if use_ether_scan:
        params = [{"hex" : "0x" + tx_hex }]
    else:
        params = ["0x" + tx_hex]
    return_value = json_call( "eth_sendRawTransaction", params )                       
    if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000":
        print "Transaction failed"
        return False
    wait_for_confirmation(tx_hash)
    return return_value 
Example #9
Source File: wallet.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, private_key=None):
        self.private_key = private_key
        if private_key is None:
            self.private_key = SigningKey.generate(curve=SECP256k1).to_string().hex()
        self._raw_address = utils.privtoaddr(self.private_key)
        self.address = utils.checksum_encode(self._raw_address) 
Example #10
Source File: accounts.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def address(self):
        a = privtoaddr(self.privkey)
        assert len(a) == 20
        assert isinstance(a, bytes)
        return a 
Example #11
Source File: web3_interface.py    From exchange-simulator with MIT License 5 votes vote down vote up
def call_const_function(priv_key, value, contract_hash, contract_abi, function_name, args):
    # src_address = b2h(utils.privtoaddr(priv_key))
    translator = ContractTranslator(json.loads(contract_abi))
    call = translator.encode_function_call(function_name, args)
    # nonce = get_num_transactions(src_address)
    # gas_price = get_gas_price_in_wei()

    # start_gas = eval_startgas(
    # src_address, contract_hash, value, b2h(call), gas_price)
    # nonce = int(nonce, 16)
    # gas_price = int(gas_price, 16)
    # start_gas = int(start_gas, 16) + 100000
    # start_gas = 7612288

    params = {
        # "from": "0x" + src_address,
        "to": "0x" + contract_hash,
        #   "gas": "0x" + "%x" % start_gas,
        #   "gasPrice": "0x" + "%x" % gas_price,
        #   "value": "0x" + str(value),
        "data": "0x" + b2h(call)
    }

    return_value = json_call("eth_call", [params, "latest"])
    # print return_value
    return_value = h2b(return_value[2:])  # remove 0x
    return translator.decode_function_result(function_name, return_value)

# 
Example #12
Source File: ethereum_processor.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 contract_address,
                 contract_abi_string,
                 ethereum_chain_id,
                 http_provider,
                 websocket_provider,
                 gas_price_gwei,
                 gas_limit,
                 master_wallet_private_key,
                 force_eth_disbursement_amount=None,
                 withdraw_to_address = None):

        super(UnmintableERC20Processor, self).__init__(contract_address,
                                                       contract_abi_string,
                                                       ethereum_chain_id,
                                                       http_provider,
                                                       websocket_provider,
                                                       gas_price_gwei,
                                                       gas_limit)

        self.master_wallet_private_key = master_wallet_private_key
        self.master_wallet_address = Web3.toChecksumAddress(utils.privtoaddr(self.master_wallet_private_key))
        print('master wallet address: ' + self.master_wallet_address)

        self.websocket_contract = self.wsw3.eth.contract(address=self.contract_address, abi=self.abi_dict)

        self.force_eth_disbursement_amount = force_eth_disbursement_amount

        self.withdraw_to_address = withdraw_to_address 
Example #13
Source File: ethereum_processor.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def construct_master_wallet_approval_tasks(self, account_to_approve_encoded_pk, credit_transfer_id):

        private_key = self.decode_private_key(account_to_approve_encoded_pk)

        address = Web3.toChecksumAddress(utils.privtoaddr(private_key))

        gas_required, gas_price = self.estimate_load_ether_gas_and_price()

        return [
            celery_tasks.load_ether.si(address, gas_required, gas_price),
            celery_tasks.create_transaction_response.s(credit_transfer_id),
            celery_tasks.approve_master_for_transfers.si(account_to_approve_encoded_pk, gas_required, gas_price),
            celery_tasks.create_transaction_response.s(credit_transfer_id)
        ] 
Example #14
Source File: post_contract_ui.py    From smart_contracts with MIT License 5 votes vote down vote up
def get_account_balance( key ):
    url = "https://testnet.etherscan.io/api"
    payload = {"module" : "account",
               "action" : "balance",
               "tag" : "latest",
               "address" : "0x" + b2h( utils.privtoaddr(key) ), 
               "apikey" : ether_scan_api_key }
    response = requests.post( url, params=payload )
    balance = response.json()[ 'result' ]
    if balance is None:
        return 0
    return int(balance) 
Example #15
Source File: web3_interface.py    From exchange-simulator with MIT License 4 votes vote down vote up
def make_transaction(src_priv_key, dst_address, value, data):
    # global global_nonce

    src_address = b2h(utils.privtoaddr(src_priv_key))
    nonce = get_num_transactions(src_address)
    gas_price = get_gas_price_in_wei()
    data_as_string = b2h(data)
    # print len(data_as_string)
    # if len(data) > 0:
    #    data_as_string = "0x" + data_as_string
    # start_gas = eval_startgas(src_address, dst_address, value,
    # data_as_string, gas_price)
    start_gas = "0xF4240"

    nonce = int(nonce, 16)
    # if(global_nonce < 0):
    # global_nonce = nonce

    # nonce = global_nonce
    # global_nonce += 1

    # print(nonce)

    gas_price = int(gas_price, 16)
    # int(gas_price, 16)/20
    start_gas = int(start_gas, 16) + 100000

    tx = transactions.Transaction(nonce,
                                  gas_price,
                                  start_gas,
                                  dst_address,
                                  value,
                                  data).sign(src_priv_key)

    tx_hex = b2h(rlp.encode(tx))
    tx_hash = b2h(tx.hash)

    params = ["0x" + tx_hex]
    return_value = json_call("eth_sendRawTransaction", params)
    if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000":
        print("Transaction failed")
        return return_value

    return return_value 
Example #16
Source File: test_gnt.py    From golem-crowdfunding with GNU General Public License v3.0 4 votes vote down vote up
def deploy_contract_and_accounts(state, n_devs, start=1, end=2, deploy_contract=True):
    dev_keys = []
    dev_accounts = []

    milestone = int(math.log10(n_devs))
    notify_step = milestone - 2
    notify_value = 10 ** notify_step if notify_step > 0 else 1

    # create developer accounts and keys in fashion of testers
    for account_number in range(n_devs):
        if account_number % notify_value == 0:
            print "Account", account_number + 1, "out of", n_devs

        dev_keys.append(sha3('dev' + to_string(account_number)))
        dev_accounts.append(privtoaddr(dev_keys[-1]))

    # developer balances
    block = state.block

    for i in range(n_devs):
        if i % notify_value == 0:
            print "Balance", i + 1, "out of", n_devs

        addr, data = dev_accounts[i], {'wei': 10 ** 24}
        if len(addr) == 40:
            addr = decode_hex(addr)
        assert len(addr) == 20
        block.set_balance(addr, parse_int_or_hex(data['wei']))

    block.commit_state()
    block.state.db.commit()

    dev_addresses = [ContractHelper.dev_address(a) for a in dev_accounts]

    # deploy the gnt contract with updated developer accounts
    if deploy_contract:
        contract, _, _ = deploy_gnt(state, tester.accounts[9], start, end,
                                    replacements=[(dev_addresses, DEV_ADDR_REGEX)])
        alloc_addr = mk_contract_address(contract.address, 0)
        allocation = tester.ABIContract(state, ALLOC_ABI, alloc_addr)
    else:
        contract, allocation = None, None

    return contract, allocation, dev_keys, dev_accounts 
Example #17
Source File: ethereum_processor.py    From SempoBlockchain with GNU General Public License v3.0 4 votes vote down vote up
def process_transaction(self,
                            signing_private_key,
                            credit_transfer_id=None,
                            unbuilt_transaction=None,
                            partial_txn_dict={},
                            transaction_type=None,
                            gas_limit_override=None,
                            gas_price_override=None):

        signing_address = Web3.toChecksumAddress(utils.privtoaddr(signing_private_key))

        network_nonce = self.w3.eth.getTransactionCount(signing_address, block_identifier='pending')

        nonce, transaction_id = self.claim_transaction_spot(signing_address, network_nonce)


        print('@@@@@@@@@@@@@@ using nonce @@@@@@@@@@@@@@: {}'.format(nonce))


        txn = {
            'chainId': self.ethereum_chain_id,
            'gas': gas_limit_override or self.gas_limit,
            'gasPrice': gas_price_override or self.get_gas_price(),
            'nonce': nonce
        }

        if unbuilt_transaction:
            txn = unbuilt_transaction.buildTransaction(txn)
        else:
            txn = {**txn, **partial_txn_dict}

        signed_txn = self.w3.eth.account.signTransaction(txn, private_key=signing_private_key)

        transaction_data = {
            'transaction_hash': signed_txn.hash.hex(),
            'transaction_nonce': nonce,
            'transaction_type': transaction_type,
            'signing_address': signing_address,
            'submitted_date': str(datetime.datetime.utcnow()),
            'credit_transfer_id': credit_transfer_id,
            'transaction_id': transaction_id
        }

        self.send_blockchain_result_to_app(transaction_data)

        try:
            result = self.w3.eth.sendRawTransaction(signed_txn.rawTransaction)

        except ValueError as e:

            transaction_data['status'] = 'FAILED'
            transaction_data['message'] = str(e)

            raise PreBlockchainError(transaction_data)

        print('*****************transaction_data:*****************')
        print(transaction_data)

        return transaction_data