Python ethereum.transactions.Transaction() Examples

The following are 29 code examples of ethereum.transactions.Transaction(). 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.transactions , or try the search function .
Example #1
Source File: utils.py    From airdrop with Apache License 2.0 6 votes vote down vote up
def _check_transaction(self, transaction, unsigned):
        """
        Checks a single (external) transaction against its expected unsigned (local) counterpart
        """
        decoded = rlp.decode(self.web3.toAscii(transaction['signedRaw']), Transaction)

        decoded_tx = dict(
            nonce=self.web3.toHex(decoded.nonce),
            gasPrice=self.web3.toHex(decoded.gasprice),
            gas=self.web3.toHex(decoded.startgas),
            to=self.web3.toHex(decoded.to),
            value=self.web3.toHex(decoded.value),
            data=self.web3.toHex(decoded.data)
        )

        unsigned['tx'].pop('from')

        if unsigned['tx'] != decoded_tx:
            logging.error("mismatch! signed tx: {}, local tx: {}".format(decoded_tx, unsigned['tx']))
            raise AirdropException("transaction mismatch for {}".format(unsigned['tx']['nonce'])) 
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: base.py    From clove with GNU General Public License v3.0 6 votes vote down vote up
def publish(self, transaction: Union[str, Transaction]) -> Optional[str]:
        '''
        Method to publish transaction

        Args:
            transaction (str, `ethereum.transactions.Transaction`): signed transaction

        Returns:
            str, None: transaction hash or None if something goes wrong

        Example:
            >>> from clove.network import EthereumTestnet
            >>> network = EthereumTestnet()
            >>> signed_transaction = '0xf901318201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a90920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001ca0d1c5b984ef2629eeb7c96f48a645566b2caf4130b0f3d7060ad5225946eee9e99f9928c5dfe868b45efbb9f8ae7d64d6162591c78961439c49e836947842e178'  # noqa: E501
            >>> network.publish(signed_transaction)
            '0x4fd41289b816f6122e59a0759bd10441ead75d550562f4b3aad2fddc56eb3274'
        '''
        raw_transaction = transaction if isinstance(transaction, str) else self.get_raw_transaction(transaction)
        try:
            published_transaction = self.web3.eth.sendRawTransaction(raw_transaction).hex()
            logger.debug(f'Transaction {published_transaction} published successful')
            return published_transaction
        except ValueError:
            logger.warning(f'Unable to publish transaction {raw_transaction}')
            return 
Example #4
Source File: contract.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def redeem(self, secret: str) -> EthereumTokenTransaction:
        '''
        Creates transaction that can redeem a contract.

        Args:
            secret (str): transaction secret that should match the contract secret hash (after hashing)

        Returns:
            EthereumTokenTransaction: unsigned transaction object with redeem transaction

        Raises:
            ValueError: if contract balance is 0
        '''
        if self.balance == 0:
            raise ValueError("Balance of this contract is 0.")
        contract = self.contract
        redeem_func = contract.functions.redeem(secret)
        tx_dict = {
            'nonce': self.network.web3.eth.getTransactionCount(self.recipient_address),
            'value': 0,
            'gas': ETH_REDEEM_GAS_LIMIT,
        }

        tx_dict = redeem_func.buildTransaction(tx_dict)

        transaction = EthereumTokenTransaction(network=self.network)
        transaction.tx = Transaction(
            nonce=tx_dict['nonce'],
            gasprice=tx_dict['gasPrice'],
            startgas=tx_dict['gas'],
            to=tx_dict['to'],
            value=tx_dict['value'],
            data=Web3.toBytes(hexstr=tx_dict['data']),
        )
        transaction.value = self.value
        transaction.token = self.token
        transaction.recipient_address = self.recipient_address
        return transaction 
Example #5
Source File: simple_casper_tester.py    From research with MIT License 5 votes vote down vote up
def inject_tx(txhex):
    tx = rlp.decode(utils.decode_hex(txhex[2:]), transactions.Transaction)
    s.state.set_balance(tx.sender, tx.startgas * tx.gasprice)
    state_transition.apply_transaction(s.state, tx)
    contract_address = utils.mk_contract_address(tx.sender, 0)
    assert s.state.get_code(contract_address)
    return contract_address 
Example #6
Source File: utils.py    From airdrop with Apache License 2.0 5 votes vote down vote up
def _get_receipt(self, transaction):
        decoded = rlp.decode(self.web3.toAscii(transaction['signedRaw']), Transaction)
        receipt = self.web3.eth.getTransactionReceipt(self.web3.toHex(decoded.hash))
        return receipt 
Example #7
Source File: test_send_raw_transaction.py    From eth-testrpc with MIT License 5 votes vote down vote up
def test_eth_sendRawTransaction(hex_accounts, client):
    tx = Transaction(0, tester.gas_price, tester.gas_limit, tester.accounts[1], 1234, '')
    tx.sign(tester.keys[0])

    raw_tx = rlp.encode(tx)
    raw_tx_hex = encode_data(raw_tx)

    tx_hash = client.send_raw_transaction(raw_tx_hex)
    assert tx_hash

    tx_data = client.get_transaction_by_hash(tx_hash)

    assert tx_data['hash'] == tx_hash
    assert tx_data['from'] == hex_accounts[0]
    assert tx_data['to'] == hex_accounts[1] 
Example #8
Source File: test_eth_sendRawTransaction.py    From eth-testrpc with MIT License 5 votes vote down vote up
def test_eth_sendRawTransaction(accounts, rpc_client):
    tx = Transaction(0, tester.gas_price, tester.gas_limit, accounts[1], 1234, '')
    tx.sign(tester.keys[0])

    raw_tx = rlp.encode(tx)
    raw_tx_hex = encode_data(raw_tx)

    result = rpc_client('eth_sendRawTransaction', params=[raw_tx_hex])
    assert len(result) == 66 
Example #9
Source File: client.py    From eth-testrpc with MIT License 5 votes vote down vote up
def send_raw_transaction(self, raw_tx):
        tx = rlp.decode(decode_hex(strip_0x(raw_tx)), transactions.Transaction)

        to = encode_address(tx.to) if tx.to else b''
        _from = encode_address(tx.sender)
        data = encode_data(tx.data)

        return self.send_transaction(
            _from=_from,
            to=to,
            gas_price=tx.gasprice,
            gas=tx.startgas,
            value=tx.value,
            data=data,
        ) 
Example #10
Source File: client.py    From eth-testrpc with MIT License 5 votes vote down vote up
def _get_transaction_by_hash(self, txn_hash):
        txn_hash = strip_0x(txn_hash)
        if len(txn_hash) == 64:
            txn_hash = decode_hex(txn_hash)
        for block in reversed(self.evm.blocks):
            txn_hashes = block.get_transaction_hashes()

            if txn_hash in txn_hashes:
                txn_index = txn_hashes.index(txn_hash)
                txn = block.transaction_list[txn_index]
                break
        else:
            raise ValueError("Transaction not found")
        return block, txn, txn_index 
Example #11
Source File: signer.py    From cert-issuer with MIT License 5 votes vote down vote up
def sign_transaction(self, wif, transaction_to_sign):
        ##try to sign the transaction.

        if isinstance(transaction_to_sign, transactions.Transaction):
            try:
                raw_tx = rlp.encode(transaction_to_sign.sign(wif, self.netcode))
                raw_tx_hex = encode_hex(raw_tx)
                return raw_tx_hex
            except Exception as msg:
                return {'error': True, 'message': msg}
        else:
            raise UnableToSignTxError('You are trying to sign a non transaction type') 
Example #12
Source File: tx_utils.py    From cert-issuer with MIT License 5 votes vote down vote up
def create_ethereum_trx(issuing_address, nonce, to_address, blockchain_bytes, gasprice, gaslimit):
    # the actual value transfer is 0 in the Ethereum implementation
    from ethereum.transactions import Transaction
    value = 0
    tx = Transaction(nonce=nonce, gasprice=gasprice, startgas=gaslimit, to=to_address, value=value,
                     data=blockchain_bytes)
    return tx 
Example #13
Source File: trace_statetests.py    From evmlab with GNU General Public License v3.0 5 votes vote down vote up
def getTxSender(test_tx):
    tx = transactions.Transaction(
        nonce=parse_int_or_hex(test_tx['nonce'] or b"0"),
        gasprice=parse_int_or_hex(test_tx['gasPrice'] or b"0"),
        startgas=parse_int_or_hex(test_tx['gasLimit'] or b"0"),
        to=decode_hex(remove_0x_head(test_tx['to'])),
        value=parse_int_or_hex(test_tx['value'] or b"0"),
        data=decode_hex(remove_0x_head(test_tx['data'])))
    if 'secretKey' in test_tx:
        tx.sign(decode_hex(remove_0x_head(test_tx['secretKey'])))
    return encode_hex(tx.sender) 
Example #14
Source File: trace_statetests.py    From evmlab with GNU General Public License v3.0 5 votes vote down vote up
def getIntrinsicGas(test_tx):
    tx = transactions.Transaction(
        nonce=parse_int_or_hex(test_tx['nonce'] or b"0"),
        gasprice=parse_int_or_hex(test_tx['gasPrice'] or b"0"),
        startgas=parse_int_or_hex(test_tx['gasLimit'] or b"0"),
        to=decode_hex(remove_0x_head(test_tx['to'])),
        value=parse_int_or_hex(test_tx['value'] or b"0"),
        data=decode_hex(remove_0x_head(test_tx['data'])))

    return tx.intrinsic_gas_used 
Example #15
Source File: run_statetest.py    From evmlab with GNU General Public License v3.0 5 votes vote down vote up
def compute_state_test_unit(state, txdata, konfig):
    state.env.config = konfig
    s = state.snapshot()
    try:
        # Create the transaction
        tx = transactions.Transaction(
            nonce=parse_int_or_hex(txdata['nonce'] or b"0"),
            gasprice=parse_int_or_hex(txdata['gasPrice'] or b"0"),
            startgas=parse_int_or_hex(txdata['gasLimit'] or b"0"),
            to=decode_hex(remove_0x_head(txdata['to'])),
            value=parse_int_or_hex(txdata['value'] or b"0"),
            data=decode_hex(remove_0x_head(txdata['data'])))
        if 'secretKey' in txdata:
            tx.sign(decode_hex(remove_0x_head(txdata['secretKey'])))
        else:
            tx.v = parse_int_or_hex(txdata['v'])
        # Run it
        prev = state.to_dict()
        print("calling apply_transaction")
        success, output = apply_transaction(state, tx)
        print("Applied tx")
    except InvalidTransaction as e:
        print("Exception: %r" % e)
        success, output = False, b''
    state.commit()
    post = state.to_dict()
    output_decl = {
        "hash": '0x' + encode_hex(state.trie.root_hash),
        #"indexes": indices,
        #"diff": mk_state_diff(prev, post)
    }
    stateRoot = encode_hex(state.trie.root_hash)
    print("{{\"stateRoot\": \"{}\"}}".format(stateRoot))
    state.revert(s)
    return output_decl 
Example #16
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 #17
Source File: base.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def deserialize_raw_transaction(raw_transaction: str) -> Transaction:
        '''
        Deserializing raw transaction and returning Transaction object

        Args:
            raw_transaction (str): raw transaction hex string

        Returns:
            `ethereum.transactions.Transaction`: Ethereum transaction object

        Raises:
            ImpossibleDeserialization: if the raw transaction was not deserializable

        Example:
            >>> from clove.network import EthereumTestnet
            >>> network = EthereumTestnet()
            >>> transaction = network.deserialize_raw_transaction('0xf8f28201f4843b9aca008302251694ce07ab9477bc20790b88b398a2a9e0f626c7d26387b1a2bc2ec50000b8c47337c993000000000000000000000000000000000000000000000000000000005bd564819d3e84874c199ca4656d434060ec1a393750ab74000000000000000000000000000000000000000000000000d867f293ba129629a9f9355fa285b8d3711a9092000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000808080')  # noqa: E501
            <Transaction(821b)>
        '''
        try:
            transaction = rlp.hex_decode(raw_transaction, Transaction)
            logger.debug('Deserialization succeed')
        except (ValueError, RLPException):
            logger.warning(f'Deserialization with {raw_transaction} failed')
            raise ImpossibleDeserialization()

        transaction._cached_rlp = None
        transaction.make_mutable()

        return transaction 
Example #18
Source File: base.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def sign(transaction: Transaction, private_key: str) -> Transaction:
        '''
        Signing the transaction.

        Args:
            transaction (Transaction): Ethereum unsigned transaction object
            private_key (str): private key

        Returns:
            Transaction: Ethereum signed transaction object
        '''
        transaction.sign(private_key)
        logger.info('Transaction signed')
        return transaction 
Example #19
Source File: transaction.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def set_contract(self):
        self.contract = self.network.web3.eth.contract(address=self.contract_address, abi=self.abi)

        initiate_func = self.contract.functions.initiate(
            self.locktime_unix,
            self.secret_hash,
            self.recipient_address,
            self.token_address,
            bool(self.token),
            self.token_value_base_units,
        )

        tx_dict = {
            'nonce': self.network.web3.eth.getTransactionCount(self.sender_address),
            'from': self.sender_address,
            'value': self.value_base_units,
        }

        tx_dict = initiate_func.buildTransaction(tx_dict)

        self.gas_limit = initiate_func.estimateGas({
            key: value for key, value in tx_dict.items() if key not in ('to', 'data')
        })

        self.tx = Transaction(
            nonce=tx_dict['nonce'],
            gasprice=tx_dict['gasPrice'],
            startgas=self.gas_limit,
            to=tx_dict['to'],
            value=tx_dict['value'],
            data=Web3.toBytes(hexstr=tx_dict['data']),
        ) 
Example #20
Source File: eth_service.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def broadcast_transaction(self, tx, origin=None):
        assert isinstance(tx, Transaction)
        if self.broadcast_filter.known(tx.hash):
            log.debug('already broadcasted tx')
        else:
            log.debug('broadcasting tx', origin=origin)
            bcast = self.app.services.peermanager.broadcast
            bcast(eth_protocol.ETHProtocol, 'transactions', args=(tx,),
                  exclude_peers=[origin.peer] if origin else [])

    # wire protocol receivers ########### 
Example #21
Source File: rpc_client.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def signed_tx_example():
    from ethereum.transactions import Transaction
    from pyethapp.accounts import mk_privkey, privtoaddr
    secret_seed = 'wow'
    privkey = mk_privkey(secret_seed)
    sender = privtoaddr(privkey)
    # fetch nonce
    nonce = quantity_decoder(
        JSONRPCClient().call('eth_getTransactionCount', address_encoder(sender), 'pending'))
    # create transaction
    tx = Transaction(nonce, default_gasprice, default_startgas, to=z_address, value=100, data='')
    tx.sign(privkey)
    tx_dict = tx.to_dict()
    tx_dict.pop('hash')
    res = JSONRPCClient().eth_sendTransaction(**tx_dict)
    if len(res) == 20:
        print 'contract created @', res.encode('hex')
    else:
        assert len(res) == 32
        print 'tx hash', res.encode('hex') 
Example #22
Source File: jsonrpc.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_trace(self, txhash):
        try:  # index
            test_blk, tx, i = self._get_block_before_tx(txhash)
        except (KeyError, TypeError):
            raise Exception('Unknown Transaction  %s' % txhash)

        # collect debug output FIXME set loglevel trace???
        recorder = LogRecorder()
        # apply tx (thread? we don't want logs from other invocations)
        self.app.services.chain.add_transaction_lock.acquire()
        processblock.apply_transaction(test_blk, tx)  # FIXME deactivate tx context switch or lock
        self.app.services.chain.add_transaction_lock.release()
        return dict(tx=txhash, trace=recorder.pop_records()) 
Example #23
Source File: jsonrpc.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tx_hash_decoder(data):
    """Decode a transaction hash."""
    decoded = data_decoder(data)
    if len(decoded) != 32:
        raise BadRequestError('Transaction hashes must be 32 bytes long')
    return decoded 
Example #24
Source File: contract.py    From clove with GNU General Public License v3.0 4 votes vote down vote up
def refund(self) -> EthereumTokenTransaction:
        '''
        Creates transaction that can refund a contract.

        Returns:
            EthereumTokenTransaction: unsigned transaction object with refund transaction

        Raises:
            RuntimeError: if contract is still valid
            ValueError: if contract balance is 0
        '''
        if self.balance == 0:
            raise ValueError("Balance of this contract is 0.")
        contract = self.contract

        if self.locktime > datetime.utcnow():
            locktime_string = self.locktime.strftime('%Y-%m-%d %H:%M:%S')
            logger.warning(f"This contract is still valid! It can't be refunded until {locktime_string} UTC.")
            raise RuntimeError(f"This contract is still valid! It can't be refunded until {locktime_string} UTC.")

        refund_func = contract.functions.refund(self.secret_hash, self.recipient_address)
        tx_dict = {
            'nonce': self.network.web3.eth.getTransactionCount(self.refund_address),
            'value': 0,
            'gas': ETH_REFUND_GAS_LIMIT,
        }

        tx_dict = refund_func.buildTransaction(tx_dict)

        transaction = EthereumTokenTransaction(network=self.network)
        transaction.tx = Transaction(
            nonce=tx_dict['nonce'],
            gasprice=tx_dict['gasPrice'],
            startgas=tx_dict['gas'],
            to=tx_dict['to'],
            value=tx_dict['value'],
            data=Web3.toBytes(hexstr=tx_dict['data']),
        )
        transaction.value = self.value
        transaction.token = self.token
        transaction.recipient_address = self.refund_address
        logger.debug('Transaction refunded')
        return transaction 
Example #25
Source File: transaction.py    From clove with GNU General Public License v3.0 4 votes vote down vote up
def __init__(
        self,
        network,
        sender_address: str,
        value: Decimal,
        token=None,
    ):
        super().__init__(network)

        self.sender_address = self.network.unify_address(sender_address)
        self.value = value
        self.token = token
        self.value_base_units = self.token.value_to_base_units(self.value)
        self.token_address = self.token.token_address
        self.symbol = self.token.symbol

        self.contract = self.network.web3.eth.contract(address=self.token_address, abi=self.token.approve_abi)

        approve_func = self.contract.functions.approve(
            self.network.contract_address,
            self.value_base_units,
        )

        tx_dict = {
            'nonce': self.network.web3.eth.getTransactionCount(self.sender_address),
            'from': self.sender_address,
        }

        tx_dict = approve_func.buildTransaction(tx_dict)

        self.gas_limit = approve_func.estimateGas({
            key: value for key, value in tx_dict.items() if key not in ('to', 'data')
        })

        self.tx = Transaction(
            nonce=tx_dict['nonce'],
            gasprice=tx_dict['gasPrice'],
            startgas=self.gas_limit,
            to=tx_dict['to'],
            value=tx_dict['value'],
            data=Web3.toBytes(hexstr=tx_dict['data']),
        ) 
Example #26
Source File: sdk.py    From erc20token-sdk-python with GNU General Public License v2.0 4 votes vote down vote up
def send_transaction(self, address, amount, data=b''):
        """Send transaction with retry.
        Submitting a raw transaction can result in a nonce collision error. In this case, the submission is
        retried with a new nonce.

        :param str address: the target address.

        :param Decimal amount: the amount of Ether to send.

        :param data: binary data to put into transaction data field.

        :returns: transaction id (hash)
        :rtype: str
        """
        with self.lock:
            attempts = 0
            while True:
                try:
                    remote_nonce = self.web3.eth.getTransactionCount(self.address, 'pending')
                    nonce = max(self.local_nonce, remote_nonce)
                    value = self.web3.toWei(amount, 'ether')
                    tx = Transaction(
                        nonce=nonce,
                        gasprice=self.gas_price,
                        startgas=self.estimate_tx_gas({'to': address, 'from': self.address, 'value': value, 'data': data}),
                        to=address,
                        value=value,
                        data=data,
                    )
                    signed_tx = tx.sign(self.private_key)
                    raw_tx_hex = self.web3.toHex(rlp.encode(signed_tx))
                    tx_id = self.web3.eth.sendRawTransaction(raw_tx_hex)
                    # send successful, increment nonce.
                    self.local_nonce = nonce + 1
                    return tx_id
                except ValueError as ve:
                    if 'message' in ve.args[0]:
                        err_msg = ve.args[0]['message']
                        if ('nonce too low' in err_msg
                            or 'another transaction with same nonce' in err_msg
                            or "the tx doesn't have the correct nonce" in err_msg) \
                                and attempts < RETRY_ATTEMPTS:
                            logging.warning('transaction nonce error, retrying')
                            attempts += 1
                            sleep(RETRY_DELAY)  # TODO: exponential backoff, configurable retry?
                            continue
                    raise 
Example #27
Source File: jsonrpc.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def call(self, data, block_id=None):
        block = self.json_rpc_server.get_block(block_id)
        state_root_before = block.state_root

        # rebuild block state before finalization
        if block.has_parent():
            parent = block.get_parent()
            test_block = block.init_from_parent(parent, block.coinbase,
                                                timestamp=block.timestamp)
            for tx in block.get_transactions():
                success, output = processblock.apply_transaction(test_block, tx)
                assert success
        else:
            original = block.snapshot()
            original['journal'] = deepcopy(original['journal'])  # do not alter original journal
            test_block = ethereum.blocks.genesis(block.db)
            test_block.revert(original)

        # validate transaction
        if not isinstance(data, dict):
            raise BadRequestError('Transaction must be an object')
        to = address_decoder(data['to'])
        try:
            startgas = quantity_decoder(data['gas'])
        except KeyError:
            startgas = block.gas_limit - block.gas_used
        try:
            gasprice = quantity_decoder(data['gasPrice'])
        except KeyError:
            gasprice = 0
        try:
            value = quantity_decoder(data['value'])
        except KeyError:
            value = 0
        try:
            data_ = data_decoder(data['data'])
        except KeyError:
            data_ = b''
        try:
            sender = address_decoder(data['from'])
        except KeyError:
            sender = '\x00' * 20

        # apply transaction
        nonce = test_block.get_nonce(sender)
        tx = Transaction(nonce, gasprice, startgas, to, value, data_)
        tx.sender = sender

        try:
            success, output = processblock.apply_transaction(test_block, tx)
        except processblock.InvalidTransaction as e:
            success = False
        assert block.state_root == state_root_before

        if success:
            return output
        else:
            return False 
Example #28
Source File: jsonrpc.py    From pyethapp with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def sendTransaction(self, data):
        """
        extend spec to support v,r,s signed transactions
        """
        if not isinstance(data, dict):
            raise BadRequestError('Transaction must be an object')

        def get_data_default(key, decoder, default=None):
            if key in data:
                return decoder(data[key])
            return default

        to = get_data_default('to', address_decoder, b'')
        startgas = get_data_default('gas', quantity_decoder, default_startgas)
        gasprice = get_data_default('gasPrice', quantity_decoder, default_gasprice)
        value = get_data_default('value', quantity_decoder, 0)
        data_ = get_data_default('data', data_decoder, b'')
        v = signed = get_data_default('v', quantity_decoder, 0)
        r = get_data_default('r', quantity_decoder, 0)
        s = get_data_default('s', quantity_decoder, 0)
        nonce = get_data_default('nonce', quantity_decoder, None)
        sender = get_data_default('from', address_decoder, self.app.services.accounts.coinbase)

        # create transaction
        if signed:
            assert nonce is not None, 'signed but no nonce provided'
            assert v and r and s
        else:
            nonce = self.app.services.chain.chain.head_candidate.get_nonce(sender)

        tx = Transaction(nonce, gasprice, startgas, to, value, data_, v, r, s)
        if not signed:
            assert sender in self.app.services.accounts, 'no account for sender'
            self.app.services.accounts.sign_tx(sender, tx)
        self.app.services.chain.add_transaction(tx, origin=None)

        log.debug('decoded tx', tx=tx.to_dict())

        if to == b'':  # create
            return address_encoder(processblock.mk_contract_address(tx.sender, nonce))
        else:
            return data_encoder(tx.hash) 
Example #29
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