コード例 #1
0
    def pay(self, address_to_send, amount, fee=get_network_fee(),
            number_gas=NB_GAS_FOR_TRANSACTION):
        """
        Function to send ether to an address, you can choose the fees

        """
        assert self.web3.isConnected()
        nonce_address = self.web3.eth.getTransactionCount(self.address)
        assert self.web3.isAddress(address_to_send)

        amount_in_wei = self.web3.toWei(amount, "ether")
        fee_in_wei = self.web3.toWei(fee, "gwei")  # 1 Gwei = 1 billion wei

        if (self.web3.eth.getBalance(self.address) >= amount_in_wei + fee_in_wei):
            tx = Transaction(
                nonce=nonce_address,
                gasprice=fee_in_wei,
                startgas=number_gas,
                to=address_to_send,
                value=amount_in_wei,
                data=b"",  # no need of additional data
            )
            tx.sign(self.key)
            raw_tx = rlp.encode(tx)
            raw_tx_hex = self.web3.toHex(raw_tx)
            tx_hash = self.web3.eth.sendRawTransaction(raw_tx_hex)
            return tx_hash
        else:
            print("No enough ether on your account")
コード例 #2
0
ファイル: rpc_client.py プロジェクト: hdiedrich/pyethapp
    def send_transaction(self, sender, to, value=0, data='', startgas=0, gasprice=10 * denoms.szabo):
        "can send a locally signed transaction if privkey is given"
        assert self.privkey or sender
        if self.privkey:
            _sender = sender
            sender = privtoaddr(self.privkey)
            assert sender == _sender
        assert sender
        # fetch nonce
        nonce = self.nonce(sender)
        if not startgas:
            startgas = quantity_decoder(self.call('eth_gasLimit')) - 1

        # create transaction
        tx = Transaction(nonce, gasprice, startgas, to=to, value=value, data=data)
        if self.privkey:
            tx.sign(self.privkey)
        tx_dict = tx.to_dict()
        tx_dict.pop('hash')
        for k, v in dict(gasprice='gasPrice', startgas='gas').items():
            tx_dict[v] = tx_dict.pop(k)
        tx_dict['sender'] = sender
        res = self.eth_sendTransaction(**tx_dict)
        assert len(res) in (20, 32)
        return res.encode('hex')
コード例 #3
0
def do_transaction(json_rpc, coinbase, contract, name, params, gas, gas_price,
                   private_key):
    contract_address = addresses[
        contract] if contract in addresses else contract
    contract_abi = abis[contract]
    translator = ContractTranslator(contract_abi)
    data = translator.encode(name, [
        addresses[param] if param in addresses else param for param in params
    ]).encode("hex")
    print 'Try to send {} transaction to contract {}.'.format(name, contract)
    if private_key:
        address = privtoaddr(private_key.decode('hex'))
        nonce = int(
            json_rpc.eth_getTransactionCount('0x' + address.encode('hex'))
            ["result"][2:], 16)
        tx = Transaction(nonce, gas_price, gas, contract_address, 0,
                         data.decode('hex'))
        tx.sign(private_key.decode('hex'))
        raw_tx = rlp.encode(tx).encode('hex')
        transaction_hash = json_rpc.eth_sendRawTransaction("0x" +
                                                           raw_tx)["result"]
    else:
        transaction_hash = json_rpc.eth_sendTransaction(
            coinbase,
            to_address=contract_address,
            data=data,
            gas=gas,
            gas_price=gas_price)["result"]
    wait_for_transaction_receipt(json_rpc, transaction_hash)
    print 'Transaction {} for contract {} completed.'.format(name, contract)
コード例 #4
0
ファイル: blockchainjob.py プロジェクト: bar9/bernhackt
def store_hash_in_blockchain(hash, web3):
    print 'Storing hash: {}'.format(hash)
    print 'Current block height: {}'.format(web3.eth.blockNumber)

    address_from = '0x4f7696940Cfe0C75c830da07435e65e5ebb610B0'  # our sending account
    address_to = '0x85043213AFbA0eccd37F29DE0BB760b42EBd5d58'  # our receving account
    private_key = '0c6ae2768077764b1c1ed3e6b52a2df64f01fd465a450b0a1a989ffbbbaecaac'  # sending accounts private key
    data = ' '.join(format(x, 'b') for x in bytearray(hash))

    print 'Current balance: {}'.format(web3.eth.getBalance(address_from))

    tx = Transaction(
        nonce=web3.eth.getTransactionCount(address_from),
        gasprice=web3.eth.gasPrice,
        startgas=1000000,
        to=address_to,
        value=12345,
        data=data,
    )
    tx.sign(private_key)
    raw_tx = rlp.encode(tx)
    raw_tx_hex = web3.toHex(raw_tx)

    result = None
    try:
        result = web3.eth.sendRawTransaction(raw_tx_hex)
    except:
        # TODO proper error handling
        print "Something went wrong."

    print 'Transaction: {} -> Hash stored in blockchain'.format(result)

    return result
コード例 #5
0
ファイル: vpn_contract.py プロジェクト: zhou0/sentinel
 def add_vpn_usage(self, from_addr, to_addr, sent_bytes, session_duration,
                   amount, timestamp, session_id):
     from ..helpers import nonce_manager
     try:
         nonce = nonce_manager.get_nonce(COINBASE_ADDRESS, self.net.chain)
         tx = Transaction(
             nonce=nonce,
             gasprice=self.net.web3.eth.gasPrice,
             startgas=1000000,
             to=self.address,
             value=0,
             data=self.net.web3.toBytes(hexstr=self.contract.encodeABI(
                 fn_name='addVpnUsage',
                 args=[
                     from_addr, to_addr, sent_bytes, session_duration,
                     amount, timestamp, session_id
                 ])))
         tx.sign(COINBASE_PRIVATE_KEY)
         raw_tx = self.net.web3.toHex(rlp.encode(tx))
         tx_hash = self.net.web3.eth.sendRawTransaction(raw_tx)
         nonce_manager.set_nonce(COINBASE_ADDRESS, self.net.chain,
                                 nonce + 1)
     except Exception as err:
         nonce_manager.set_nonce(COINBASE_ADDRESS, self.net.chain)
         return {'code': 307, 'error': str(err)}, None
     return None, tx_hash
コード例 #6
0
            def call(this, to, value=0, data='', sender=None,
                     startgas=25000, gasprice=60 * denoms.shannon):
                sender = normalize_address(sender or this.coinbase)
                to = normalize_address(to, allow_blank=True)
                block = this.head_candidate
                state_root_before = block.state_root
                assert block.has_parent()
                # rebuild block state before finalization
                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

                # 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 InvalidTransaction:
                    success = False

                assert block.state_root == state_root_before

                if success:
                    return output
                else:
                    return False
コード例 #7
0
ファイル: native_contracts.py プロジェクト: 1600/hydrachain
def test_call(block, sender, to, data='', gasprice=0, value=0):
    state_root_before = block.state_root
    assert block.has_parent()
    # rebuild block state before finalization
    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
    # apply transaction
    startgas = block.gas_limit - block.gas_used
    gasprice = 0
    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:
        log.debug('test_call failed', error=e)
        return None
コード例 #8
0
def main2():

    erc20_data = make_data(to='0xdf88522B56B85d4F0Bb08a7494b97E017BC6CB31',
                           value=Decimal('656340.20627410') * (10**18))
    print("erc20_data:{}".format(erc20_data))

    tx = Transaction(
        nonce=51,
        gasprice=10 * (10**9),
        startgas=210000,
        to='0x130fc2749d35fe026f32427f60dd3f2ecb6c2f33',
        value=1 * (10**16),
        # data=b''
        data=erc20_data.decode('hex'))
    tx.sender = '0x56e5782c908f69bd46b7e77338349f961fbe55b1'

    # print(tx.hash)
    signed_tx = tx.sign(
        key='63C08FABC252B53B9471E520CE8199971DB8884B5B569CBBBD17BC714E6BB39F',
        network_id=Rinkeby)  # 4:Rinkeby
    print(signed_tx.hash.encode('hex'))
    rlp_data = rlp.encode(rlp.infer_sedes(tx).serialize(tx))
    print(rlp_data.encode('hex'))
    # print(signed_tx)

    pass
コード例 #9
0
ファイル: rpc_client.py プロジェクト: youzg/pyethapp
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')
コード例 #10
0
ファイル: distributeTokens.py プロジェクト: illuzen/JoiCoin
def writeChain(contractAddr, funcSig, args=[]):
    encoding = getFunctionEncoding(funcSig, args)
    data = encoding
    #data = codecs.decode(encoding[2:], 'hex')
    nonce = web3.eth.getTransactionCount(fromAddr)
    tx = Transaction(nonce=nonce,
                     gasprice=gasPrice,
                     startgas=int(2e5),
                     to=contractAddr,
                     value=0,
                     data=data)
    tx.sign(priv)

    raw_tx = web3.toHex(rlp.encode(tx))
    txHash = web3.eth.sendRawTransaction(raw_tx)
    print('Broadcasting', txHash)
    rcpt = web3.eth.getTransactionReceipt(txHash)
    while rcpt == None:
        try:
            rcpt = web3.eth.getTransactionReceipt(txHash)
            time.sleep(7)
        except requests.exceptions.ReadTimeout:
            print('timeout, trying again')
            pass
    if rcpt.status != 1:
        print('Tx failed', rcpt)
        return False, txHash
    print('Successful tx', txHash)
    return True, txHash
コード例 #11
0
ファイル: ethClient.py プロジェクト: wjlu/trinity-eth
    def construct_erc20_tx(self,addressFrom,addressTo,value,gasPrice=None):
        '''
        构造eth未签名交易
        '''
        contract_instance=self.get_contract_instance(CONTRACT_ADDRESS, CONTRACT_ABI)
        tx_dict = contract_instance.functions.transfer(
            checksum_encode(addressTo),
            int(value*(10**8))
        ).buildTransaction({
            'from': addressFrom,
            'nonce': self.web3.eth.getTransactionCount(addressFrom),
        })

        tx = Transaction(
            nonce=tx_dict.get("nonce"),
            gasprice=tx_dict.get("gasPrice") if not gasPrice else gasPrice,
            startgas=tx_dict.get("gas"),
            to=tx_dict.get("to"),
            value=tx_dict.get("value"),
            data=binascii.unhexlify(tx_dict.get("data")[2:]))

        UnsignedTransaction = Transaction.exclude(['v', 'r', 's'])
        unsigned_tx = rlp.encode(tx, UnsignedTransaction)
        before_hash = utils.sha3(unsigned_tx)
        return binascii.hexlify(unsigned_tx).decode(),binascii.hexlify(before_hash).decode()
コード例 #12
0
ファイル: console_service.py プロジェクト: Arachnid/pyethapp
            def call(this, to, value=0, data='',  sender=None,
                     startgas=25000, gasprice=10*denoms.szabo):
                sender = address20(sender or this.coinbase)
                to = address20(to)
                block = this.head_candidate
                state_root_before = block.state_root
                assert block.has_parent()
                # rebuild block state before finalization
                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

                # 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
コード例 #13
0
ファイル: eth_rpc.py プロジェクト: trinity-project/EthNode
    def transfer_eth(self,
                     addressFrom,
                     addressTo,
                     value,
                     privtKey,
                     nounce=None):
        '''
        eth转账
        '''
        dict_tx = {
            "from": addressFrom,
            "to": addressTo,
            "value": int(value),
            "data": b''
        }
        gas_limit = self.estimate_gas(dict_tx)
        nounce = nounce if nounce else self.web3.eth.getTransactionCount(
            addressFrom)
        tx = Transaction(nonce=nounce,
                         gasprice=self.web3.eth.gasPrice,
                         startgas=gas_limit,
                         to=addressTo,
                         value=int(value),
                         data=b'')

        tx.sign(privtKey)
        raw_tx = self.web3.toHex(rlp.encode(tx))
        tx_id = self.web3.eth.sendRawTransaction(raw_tx)
        return binascii.hexlify(tx_id).decode()
コード例 #14
0
ファイル: ethClient.py プロジェクト: trinity-project/EthNode
    def write_contract(self, invoker, contractAddress, method, args,gasPrice=None):
        '''
        调用合约里实现的方法
        '''
        invoker = checksum_encode(invoker)
        contractAddress = checksum_encode(contractAddress)
        contract_instance = self.get_contract_instance(contractAddress)
        if not contract_instance:
            return None
        tx_dict = contract_instance.functions[method](*args).buildTransaction({
            'gasPrice': self.web3.eth.gasPrice if not gasPrice else gasPrice,
            'from':invoker,
            'nonce': self.web3.eth.getTransactionCount(invoker),
        })

        tx = Transaction(
            nonce=tx_dict.get("nonce"),
            gasprice=tx_dict.get("gasPrice"),
            startgas=tx_dict.get("gas"),
            to=tx_dict.get("to"),
            value=tx_dict.get("value"),
            data=binascii.unhexlify(tx_dict.get("data")[2:]))

        UnsignedTransaction = Transaction.exclude(['v', 'r', 's'])
        unsigned_tx = rlp.encode(tx, UnsignedTransaction)

        return binascii.hexlify(unsigned_tx).decode()
    def signTransaction(from_addr, nonce, gas_price, start_gas,
                        smart_contract_name, function_name, function_params,
                        private_key):

        to_addr = TransactionSigner._getToAddress(smart_contract_name)
        data = TransactionSigner._getTransactionData(from_addr,
                                                     smart_contract_name,
                                                     function_name,
                                                     function_params)

        if None in [to_addr, data]:
            return False, None

        transaction = Transaction(nonce=nonce,
                                  gasprice=gas_price,
                                  startgas=start_gas,
                                  to=to_addr,
                                  value=0,
                                  data=data)

        transaction.sign(private_key)
        raw_transaction = rlp.encode(transaction)
        hex_transaction = raw_transaction.hex()

        return True, hex_transaction
コード例 #16
0
    def send_transaction(self,
                         sender: address,
                         to: address,
                         value: int = 0,
                         data: bytes = b'',
                         startgas: int = None,
                         nonce: int = None):
        """ Helper to send signed messages.

        This method will use the `privkey` provided in the constructor to
        locally sign the transaction. This requires an extended server
        implementation that accepts the variables v, r, and s.
        """

        if not self.privkey and not sender:
            raise ValueError('Either privkey or sender needs to be supplied.')

        if self.privkey:
            privkey_address = privatekey_to_address(self.privkey)
            sender = sender or privkey_address

            if sender != privkey_address:
                raise ValueError('sender for a different privkey.')

            if nonce is None:
                nonce = self.nonce(sender)
        else:
            if nonce is None:
                nonce = 0

        startgas = self.check_startgas(startgas)

        tx = Transaction(nonce,
                         self.gasprice(),
                         startgas,
                         to=to,
                         value=value,
                         data=data)

        if self.privkey:
            tx.sign(self.privkey)
            result = self.call(
                'eth_sendRawTransaction',
                data_encoder(rlp.encode(tx)),
            )
            return result[2 if result.startswith('0x') else 0:]

        else:

            # rename the fields to match the eth_sendTransaction signature
            tx_dict = tx.to_dict()
            tx_dict.pop('hash')
            tx_dict['sender'] = sender
            tx_dict['gasPrice'] = tx_dict.pop('gasprice')
            tx_dict['gas'] = tx_dict.pop('startgas')

            res = self.eth_sendTransaction(**tx_dict)

        assert len(res) in (20, 32)
        return hexlify(res)
コード例 #17
0
ファイル: client.py プロジェクト: tomaaron/raiden
    def send_transaction(sender,
                         to,
                         value=0,
                         data='',
                         startgas=GAS_LIMIT,
                         gasprice=GAS_PRICE,
                         nonce=None):
        """Custom implementation for `pyethapp.rpc_client.JSONRPCClient.send_transaction`.
        This is necessary to support other remotes that don't support pyethapp's extended specs.
        @see https://github.com/ethereum/pyethapp/blob/develop/pyethapp/rpc_client.py#L359
        """
        pending_transactions_hex = client.call(
            'eth_getTransactionCount',
            address_encoder(sender),
            'pending',
        )
        pending_transactions = int(pending_transactions_hex, 16)
        nonce = pending_transactions + nonce_offset

        tx = Transaction(nonce, gasprice, startgas, to, value, data)
        assert hasattr(client, 'privkey') and client.privkey
        tx.sign(client.privkey)
        result = client.call(
            'eth_sendRawTransaction',
            data_encoder(rlp.encode(tx)),
        )
        return result[2 if result.startswith('0x') else 0:]
コード例 #18
0
ファイル: vpn_contract.py プロジェクト: cryptogrey/sentinel
 def add_vpn_usage(self, from_addr, to_addr, sent_bytes, session_duration,
                   amount, timestamp, session_id, nonce):
     count, tx_hash = 0, None
     while count < MAX_TX_TRY:
         try:
             tx = Transaction(
                 nonce=nonce + count,
                 gasprice=rinkeby.web3.eth.gasPrice,
                 startgas=1000000,
                 to=VPNSERVICE_ADDRESS,
                 value=0,
                 data=rinkeby.web3.toBytes(hexstr=self.contract.encodeABI(
                     fn_name='addVpnUsage',
                     args=[
                         from_addr, to_addr, sent_bytes, session_duration,
                         amount, timestamp, session_id
                     ])))
             tx.sign(COINBASE_PRIVATE_KEY)
             raw_tx = rinkeby.web3.toHex(rlp.encode(tx))
             tx_hash = rinkeby.web3.eth.sendRawTransaction(raw_tx)
             if len(tx_hash) > 0:
                 break
         except Exception as err:
             err = str(err)
             if '-32000' in err:
                 count = count + 1
             if (count >= MAX_TX_TRY) or ('-32000' not in err):
                 return {'code': 307, 'error': err}, None
     return None, tx_hash
コード例 #19
0
ファイル: ethClient.py プロジェクト: trinity-project/nft-shop
    def transfer_eth(self, addressFrom, addressTo, value, privtKey, data=b''):
        '''
        eth转账
        '''
        dict_tx = {
            "from": addressFrom,
            "to": addressTo,
            "value": int(value * (10**18)),
            "data": data
        }
        if not self.nonce_dict.get(addressFrom):
            self.nonce_dict[addressFrom] = self.web3.eth.getTransactionCount(
                checksum_encode(addressFrom))
        print(self.nonce_dict[addressFrom])
        gas_limit = self.estimate_gas(dict_tx) * 2
        print(gas_limit)
        tx = Transaction(nonce=self.nonce_dict[addressFrom],
                         gasprice=self.web3.eth.gasPrice,
                         startgas=gas_limit,
                         to=addressTo,
                         value=int(value * (10**18)),
                         data=data)

        tx.sign(privtKey)
        raw_tx = self.web3.toHex(rlp.encode(tx))
        tx_id = self.web3.eth.sendRawTransaction(raw_tx)
        self.nonce_dict[addressFrom] = self.nonce_dict[addressFrom] + 1
        return {"txId": "0x" + binascii.hexlify(tx_id).decode()}
コード例 #20
0
ファイル: tx.py プロジェクト: B0bbyB0livia/mmgen
	def do_sign(self,d,wif,tx_num_str):

		d_in = {'to':       d['to'].decode('hex'),
				'startgas': d['startGas'].toWei(),
				'gasprice': d['gasPrice'].toWei(),
				'value':    d['amt'].toWei() if d['amt'] else 0,
				'nonce':    d['nonce'],
				'data':     d['data'].decode('hex')}

		msg_r('Signing transaction{}...'.format(tx_num_str))

		try:
			from ethereum.transactions import Transaction
			etx = Transaction(**d_in)
			etx.sign(wif,d['chainId'])
			import rlp
			self.hex = rlp.encode(etx).encode('hex')
			self.coin_txid = CoinTxID(etx.hash.encode('hex'))
			msg('OK')
			if d['data']:
				self.token_addr = TokenAddr(etx.creates.encode('hex'))
		except Exception as e:
			m = "{!r}: transaction signing failed!"
			msg(m.format(e.message))
			return False

		return self.check_sigs()
コード例 #21
0
def main3():

    erc20_data = make_data(to='0x401bf316182c792048c75e52ce18cb12ec3c4273',
                           value=Decimal('65.20627410') * (10**18))
    print("erc20_data:{}".format(erc20_data))

    tx = Transaction(
        nonce=58,
        gasprice=10 * (10**9),
        startgas=210000,
        to='0xee8e2882e07f89685430c27e2f77636b08df3c81',
        value=1,
        # data=b''
        data=erc20_data.decode('hex'))
    tx.sender = '0x56e5782c908f69bd46b7e77338349f961fbe55b1'

    # print(tx.hash)
    signed_tx = tx.sign(
        key='63C08FABC252B53B9471E520CE8199971DB8884B5B569CBBBD17BC714E6BB39F',
        network_id=Rinkeby)  # 4:Rinkeby
    print(signed_tx.hash.encode('hex'))
    rlp_data = rlp.encode(rlp.infer_sedes(tx).serialize(tx))
    print(rlp_data.encode('hex'))
    # print(signed_tx)

    pass
コード例 #22
0
    def deliver(self, enc_num, to):
        # nonce = number of transactions already sent by that account
        head = self.app.services.chain.chain.head
        nonce = head.get_nonce(self.my_addr)

        # Took from buterin example:
        # https://blog.ethereum.org/2014/04/10/pyethereum-and-serpent-programming-guide/
        gasprice = 10**12

        # Took from buterin example:
        # https://blog.ethereum.org/2014/04/10/pyethereum-and-serpent-programming-guide/
        startgas = 10000
        value = 0  # It's just a message, don't need to send any value (TODO: confirm that info)

        # data is a json formatted message but has to be 'binary'
        unix_now = int(round(time()))
        payload = {}
        payload['when'] = unix_now
        payload['number'] = enc_num
        payload['publish_on'] = unix_now + 86400  # in 24 hours
        payload['published_at'] = 'http://www.example.com/foo'
        data = json.dumps(payload)

        deliver_tx = Transaction(nonce, gasprice, startgas, to, value, data)
        signed_deliver_tx = deliver_tx.sign(self.privkey_hex)
        success, output = apply_transaction(head, signed_deliver_tx)
コード例 #23
0
ファイル: vpn_contract.py プロジェクト: cryptogrey/sentinel
 def set_initial_payment(self, account_addr, nonce, is_paid=True):
     count, tx_hash = 0, None
     while count < MAX_TX_TRY:
         try:
             tx = Transaction(
                 nonce=nonce + count,
                 gasprice=rinkeby.web3.eth.gasPrice,
                 startgas=1000000,
                 to=VPNSERVICE_ADDRESS,
                 value=0,
                 data=rinkeby.web3.toBytes(hexstr=self.contract.encodeABI(
                     fn_name='setInitialPaymentStatusOf',
                     args=[account_addr, is_paid])))
             tx.sign(COINBASE_PRIVATE_KEY)
             raw_tx = rinkeby.web3.toHex(rlp.encode(tx))
             tx_hash = rinkeby.web3.eth.sendRawTransaction(raw_tx)
             if len(tx_hash) > 0:
                 break
         except Exception as err:
             err = str(err)
             if '-32000' in err:
                 count = count + 1
             if (count >= MAX_TX_TRY) or ('-32000' not in err):
                 return {'code': 302, 'error': err}, None
     return None, tx_hash
コード例 #24
0
def test_call(block, sender, to, data='', gasprice=0, value=0):
    state_root_before = block.state_root
    assert block.has_parent()
    # rebuild block state before finalization
    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
    # apply transaction
    startgas = block.gas_limit - block.gas_used
    gasprice = 0
    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:
        log.debug('test_call failed', error=e)
        return None
コード例 #25
0
def mk_initializers(config, sender_privkey, starting_nonce=0):
    o = []
    nonce = starting_nonce
    # Create transactions for instantiating RLP decoder, sig hasher and purity checker, plus transactions for feeding the
    # one-time accounts that generate those transactions
    for tx in (viper_rlp_decoder_tx, sig_hasher_tx, purity_checker_tx):
        o.append(
            Transaction(nonce, gasprice, 90000, tx.sender,
                        tx.startgas * tx.gasprice + tx.value,
                        '').sign(sender_privkey))
        o.append(tx)
        nonce += 1
    # Casper initialization transaction
    casper_tx = Transaction(nonce, gasprice, 5000000, b'', 0,
                            casper_bytecode).sign(sender_privkey)
    # Casper initiate call (separate from initialization to save gas)
    initiate_args = casper_ct.encode('initiate', [
        config["EPOCH_LENGTH"], config["WITHDRAWAL_DELAY"], config["OWNER"],
        sig_hasher_address, purity_checker_address,
        config["BASE_INTEREST_FACTOR"], config["BASE_PENALTY_FACTOR"]
    ])
    casper_initiate_tx = Transaction(nonce + 1, gasprice, 1000000,
                                     casper_tx.creates, 0,
                                     initiate_args).sign(sender_privkey)
    # Return list of transactions and Casper address
    return o + [casper_tx, casper_initiate_tx], casper_tx.creates
コード例 #26
0
ファイル: rno_service.py プロジェクト: AFDudley/rn_service
    def deliver(self, enc_num, to):
        # nonce = number of transactions already sent by that account
        head = self.app.services.chain.chain.head
        nonce = head.get_nonce(self.my_addr)

        # Took from buterin example:
        # https://blog.ethereum.org/2014/04/10/pyethereum-and-serpent-programming-guide/
        gasprice = 10**12

        # Took from buterin example:
        # https://blog.ethereum.org/2014/04/10/pyethereum-and-serpent-programming-guide/
        startgas = 10000
        value = 0  # It's just a message, don't need to send any value (TODO: confirm that info)

        # data is a json formatted message but has to be 'binary'
        unix_now = int(round(time()))
        payload = {}
        payload['when'] = unix_now
        payload['number'] = enc_num
        payload['publish_on'] = unix_now + 86400  # in 24 hours
        payload['published_at'] = 'http://www.example.com/foo'
        data = json.dumps(payload)

        deliver_tx = Transaction(nonce, gasprice, startgas, to, value, data)
        signed_deliver_tx = deliver_tx.sign(self.privkey_hex)
        success, output = apply_transaction(head, signed_deliver_tx)
コード例 #27
0
def create_transaction(*,
                       nonce,
                       gasprice,
                       startgas,
                       to,
                       value,
                       data=b'',
                       v=None,
                       r=None,
                       s=None,
                       network_id=None):

    if to:
        to = address_decoder(to)
    else:
        to = b''

    if network_id is not None:
        if r is not None or s is not None:
            raise Exception(
                "cannot set network id at the same time as r and s values")
        v = network_id

    tx = Transaction(nonce, gasprice, startgas, to, value, data, v or 0, r
                     or 0, s or 0)
    tx._sender = None

    return tx
コード例 #28
0
ファイル: tt.py プロジェクト: csfl/Dasdaq-api
def playGame(s):
    '''
    :param sk: 私钥
    :param contract:合约账号
    :param nonce: nonce,如果连续完的话,每次+1
    :param value: 转账的金额
    :param gasprice:
    :param startgas: gaslimit
    :param funname: 要调用的方法
    :param params: 要调用的参数
    :return: tx
    '''
    # to EIP address
    address = '0x92c4557c83b59007C3A758992326a204b3F8D257'
    sk = '6e2f03c1e089a46f1679d5734cb24747d122a2d7c8156b16dad717d5825b0fc0'
    address = w3.toChecksumAddress(address)

    _data = w3.toBytes(hexstr=w3.toHex(text=s))
    nonce = getnonce(address)
    startgas = 1000000
    tx = Transaction(nonce=nonce,
                     gasprice=10000000000,
                     startgas=startgas,
                     to=address,
                     value=0,
                     data=_data)
    tx.sign(sk)
    raw_tx = rlp.encode(tx)
    raw_tx_hex = w3.toHex(raw_tx)
    tx = w3.eth.sendRawTransaction(raw_tx_hex)
    return (Web3.toHex(tx))
コード例 #29
0
def mk_initializers(config, sender_privkey, starting_nonce=0):
    o = []
    nonce = starting_nonce
    # Create transactions for instantiating RLP decoder, sig hasher and purity checker, plus transactions for feeding the
    # one-time accounts that generate those transactions
    for tx in (viper_rlp_decoder_tx, sig_hasher_tx, purity_checker_tx):
        o.append(
            Transaction(nonce, gasprice, 90000, tx.sender,
                        tx.startgas * tx.gasprice + tx.value,
                        '').sign(sender_privkey))
        o.append(tx)
        nonce += 1
    # Casper initialization transaction
    casper_tx = Transaction(nonce, gasprice, 5000000, b'', 0,
                            casper_bytecode).sign(sender_privkey)
    # Casper initiate call (separate from initialization to save gas)
    initiate_args = casper_ct.encode('initiate', [
        config["epoch_length"], config["withdrawal_delay"], config["owner"],
        sig_hasher_address, purity_checker_address,
        config["base_interest_factor"], config["base_penalty_factor"]
    ])
    casper_initiate_tx = Transaction(nonce + 1, gasprice, 1000000,
                                     casper_tx.creates, 0,
                                     initiate_args).sign(sender_privkey)
    # Return list of transactions and Casper address
    return o + [casper_tx, casper_initiate_tx], casper_tx.creates
コード例 #30
0
def test_transfer_ERC20_USDT():

    #rinkeby 合约地址:  0x0f38e3426de0f7afdf7e641633b287f462f346f2

    erc20_data = make_data(
        to='0xC4d2e23807d176441221248fCbC03170e40B37d1',  #代币接收地址
        value=Decimal('1000001.123456') * (10**6))

    print("erc20_data:{}".format(erc20_data))

    tx = Transaction(
        nonce=420,
        gasprice=20 * (10**9),
        startgas=210000,
        to='0xeca059f3d6de135e520e789cdfeecbf5ceca3770',  #合约地址
        value=0,
        # data=b''
        data=unhexlify(erc20_data))

    tx.sender = '0x954d1a58c7abd4ac8ebe05f59191Cf718eb0cB89'  #源地址
    signed_tx = tx.sign(
        key=
        'DBBAD2A5682517E4FF095F948F721563231282CA4179AE0DFEA1C76143BA9607',  #源地址的私钥
        network_id=None)  # 4:Rinkeby

    rlp_data = rlp.encode(rlp.infer_sedes(signed_tx).serialize(signed_tx))

    print(hexlify(rlp_data))  #交易数据

    pass
コード例 #31
0
ファイル: ethClient.py プロジェクト: trinity-project/nft-shop
    def invoke_contract(self,
                        invoker,
                        contract,
                        method,
                        args,
                        gasLimit=800000):
        tx_dict = contract.functions[method](*args).buildTransaction({
            "gas":
            gasLimit,
            'gasPrice':
            self.web3.eth.gasPrice,
            'nonce':
            self.web3.eth.getTransactionCount(checksum_encode(invoker)),
        })
        tx = Transaction(nonce=tx_dict.get("nonce"),
                         gasprice=tx_dict.get("gasPrice"),
                         startgas=tx_dict.get("gas"),
                         to=tx_dict.get("to"),
                         value=tx_dict.get("value"),
                         data=binascii.unhexlify(tx_dict.get("data")[2:]))

        UnsignedTransaction = Transaction.exclude(['v', 'r', 's'])
        unsigned_tx = rlp.encode(tx, UnsignedTransaction)

        return binascii.hexlify(unsigned_tx).decode()
コード例 #32
0
    def test_add_signature_to_transaction_with_netowrk_id(self):

        for network_id in [1, 2, 66, 100]:

            sender_private_key = "0x0164f7c7399f4bb1eafeaae699ebbb12050bc6a50b2836b9ca766068a9d000c0"
            sender_address = "0xde3d2d9dd52ea80f7799ef4791063a5458d13913"
            to_address = "0x056db290f8ba3250ca64a45d16284d04bc6f5fbf"
            value = 10000000000
            nonce = 1048576
            data = b''
            gasprice = DEFAULT_GASPRICE
            startgas = DEFAULT_STARTGAS
            network_id = 1

            tx1 = Transaction(nonce, gasprice, startgas, to_address, value,
                              data, network_id, 0, 0)
            tx = encode_transaction(tx1)
            tx1.sign(data_decoder(sender_private_key), network_id=network_id)
            expected_signed_tx = encode_transaction(tx1)
            sig = data_encoder(signature_from_transaction(tx1))

            signed_tx = add_signature_to_transaction(tx, sig)

            self.assertEqual(signed_tx, expected_signed_tx)

            tx_obj = decode_transaction(tx)

            add_signature_to_transaction(tx_obj, sig)

            self.assertEqual(tx_obj.network_id, network_id)
            self.assertEqual(data_encoder(tx_obj.sender), sender_address)

            self.assertEqual(encode_transaction(tx_obj), expected_signed_tx)
コード例 #33
0
def playGame(s, nonce=None):
    '''
    :param sk: 私钥
    :param contract:合约账号
    :param nonce: nonce,如果连续完的话,每次+1
    :param value: 转账的金额
    :param gasprice:
    :param startgas: gaslimit
    :param funname: 要调用的方法
    :param params: 要调用的参数
    :return: tx
    '''
    # to EIP address
    address = '0xxxxxxxxxxxxxxxxxxxx'
    sk = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    address = w3.toChecksumAddress(address)

    _data = w3.toBytes(hexstr=w3.toHex(text=s))
    if not nonce:
        nonce = getnonce(address)
    startgas = 4000000
    tx = Transaction(nonce=nonce,
                     gasprice=100000000000,
                     startgas=startgas,
                     to=address,
                     value=0,
                     data=_data)
    tx.sign(sk)
    raw_tx = rlp.encode(tx)
    raw_tx_hex = w3.toHex(raw_tx)
    tx = w3.eth.sendRawTransaction(raw_tx_hex)
    print(tx)
    inredis(nonce)
    return tx
コード例 #34
0
ファイル: web3test.py プロジェクト: yaozaiwind/web3eth
    def sendRawTransaction(
            self,
            from_add='0x8aA4c17EA21804f7c27E2f0BB1444C7941171319',
            pri_key=None,
            target=None,
            value=None):
        # python3.6  不能用
        import rlp
        from ethereum.transactions import Transaction

        tx = Transaction(
            nonce=wp3.eth.getTransactionCount(from_add),
            gasprice=wp3.eth.gasPrice,
            startgas=100000,
            to=target,
            value=value,
            data=b'',
        )

        tx.sign(pri_key)
        print('生成tx ', tx)
        rawtx = rlp.encode(tx)
        print(rawtx)
        rawtx_hex = Web3.toHex(rawtx)
        print(rawtx_hex)
        a = wp3.eth.sendRawTransaction(rawtx_hex)
        return wp3.toHex(a)
コード例 #35
0
    def sendout(self):
        log.debug("Sendout ping")
        if not self.__awaiting:
            return

        payments = self.__awaiting  # FIXME: Should this list be synchronized?
        self.__awaiting = []
        addr = keys.privtoaddr(self.__privkey)  # TODO: Should be done once?
        nonce = self.__client.get_transaction_count(addr.encode('hex'))
        p, value = _encode_payments(payments)
        data = bank_contract.encode('transfer', [p])
        gas = 21000 + len(p) * 30000
        tx = Transaction(nonce, self.GAS_PRICE, gas, to=self.BANK_ADDR,
                         value=value, data=data)
        tx.sign(self.__privkey)
        h = tx.hash
        log.info("Batch payments: {}".format(h.encode('hex')))

        # Firstly write transaction hash to database. We need the hash to be
        # remembered before sending the transaction to the Ethereum node in
        # case communication with the node is interrupted and it will be not
        # known if the transaction has been sent or not.
        with Payment._meta.database.transaction():
            for payment in payments:
                assert payment.status == PaymentStatus.awaiting
                payment.status = PaymentStatus.sent
                payment.details['tx'] = h.encode('hex')
                payment.save()

            tx_hash = self.__client.send(tx)
            assert tx_hash[2:].decode('hex') == h  # FIXME: Improve Client.

            self.__inprogress[h] = payments
コード例 #36
0
ファイル: crypto.py プロジェクト: AlphaX-IBS/microraiden
def sign_transaction(tx: Transaction, privkey: str, network_id: int):
    # Implementing EIP 155.
    tx.v = network_id
    sig = sign(privkey, keccak256(rlp.encode(tx)), v=35 + 2 * network_id)
    v, r, s = sig[-1], sig[0:32], sig[32:-1]
    tx.v = v
    tx.r = int.from_bytes(r, byteorder='big')
    tx.s = int.from_bytes(s, byteorder='big')
コード例 #37
0
ファイル: jsonrpc.py プロジェクト: ychaim/pyethapp
    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
コード例 #38
0
    def send_transaction(
            self,
            sender: address,
            to: address,
            value: int = 0,
            data: bytes = b'',
            startgas: int = 0,
            gasprice: int = GAS_PRICE,
            nonce: Optional[int] = None):
        """ Helper to send signed messages.

        This method will use the `privkey` provided in the constructor to
        locally sign the transaction. This requires an extended server
        implementation that accepts the variables v, r, and s.
        """

        if not self.privkey and not sender:
            raise ValueError('Either privkey or sender needs to be supplied.')

        if self.privkey:
            privkey_address = privatekey_to_address(self.privkey)
            sender = sender or privkey_address

            if sender != privkey_address:
                raise ValueError('sender for a different privkey.')

            if nonce is None:
                nonce = self.nonce(sender)
        else:
            if nonce is None:
                nonce = 0

        if not startgas:
            startgas = self.gaslimit() - 1

        tx = Transaction(nonce, gasprice, startgas, to=to, value=value, data=data)

        if self.privkey:
            tx.sign(self.privkey)
            result = self.call(
                'eth_sendRawTransaction',
                data_encoder(rlp.encode(tx)),
            )
            return result[2 if result.startswith('0x') else 0:]

        else:

            # rename the fields to match the eth_sendTransaction signature
            tx_dict = tx.to_dict()
            tx_dict.pop('hash')
            tx_dict['sender'] = sender
            tx_dict['gasPrice'] = tx_dict.pop('gasprice')
            tx_dict['gas'] = tx_dict.pop('startgas')

            res = self.eth_sendTransaction(**tx_dict)

        assert len(res) in (20, 32)
        return hexlify(res)
コード例 #39
0
ファイル: eth.py プロジェクト: imapp-pl/ethereum-payments
def faucet_send(o, to, value):
    value = int(value * denoms.ether)
    nonce = o.eth.get_transaction_count(Faucet.ADDR.encode('hex'))
    to = normalize_address(to)
    tx = Transaction(nonce, 1, 21000, to, value, '')
    tx.sign(Faucet.PRIVKEY)
    r = o.eth.send(tx)
    print "Transaction sent:", r
    gevent.sleep(10)
コード例 #40
0
ファイル: eth.py プロジェクト: imapp-pl/ethereum-payments
def direct(o, recipient, value):
    nonce = o.eth.get_transaction_count(o.me.address.encode('hex'))
    print "NONCE", nonce
    print "VALUE", value
    tx = Transaction(nonce, 1, 21000, to=recipient, value=value,
                     data='')
    tx.sign(o.me.priv)
    print o.eth.send(tx)
    gevent.sleep(1)  # FIXME: Wait for confirmed transaction receipt.
コード例 #41
0
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
コード例 #42
0
ファイル: node.py プロジェクト: imapp-pl/ethereum-payments
 def gimme_money(ethnode, addr, value):
     nonce = ethnode.get_transaction_count(Faucet.ADDR.encode('hex'))
     addr = normalize_address(addr)
     tx = Transaction(nonce, 1, 21000, addr, value, '')
     tx.sign(Faucet.PRIVKEY)
     h = ethnode.send(tx)
     log.info("Faucet --({} ETH)--> {} ({})".format(float(value) / 10**18,
                                                    addr.encode('hex'), h))
     h = h[2:].decode('hex')
     assert h == tx.hash
     return h
コード例 #43
0
ファイル: eth.py プロジェクト: imapp-pl/ethereum-payments
def faucet(o):
    nonce = o.eth.get_transaction_count(Faucet.ADDR.encode('hex'))
    print "NONCE", nonce
    if nonce == 0:  # Deploy Bank of Deposit contract
        tx = Transaction(nonce, 1, 3141592, to='', value=0,
                         data=BankOfDeposit.INIT_HEX.decode('hex'))
        tx.sign(Faucet.PRIVKEY)
        o.eth.send(tx)
        addr = tx.creates
        assert addr == "cfdc7367e9ece2588afe4f530a9adaa69d5eaedb".decode('hex')
        print "ADDR", addr.encode('hex')
コード例 #44
0
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]
コード例 #45
0
ファイル: contract.py プロジェクト: AlphaX-IBS/microraiden
def create_transaction(
        web3: Web3,
        from_: str,
        to: str,
        data: bytes = b'',
        nonce_offset: int = 0,
        value: int = 0,
        gas_price: Union[int, None] = None,
        gas_limit: int = NETWORK_CFG.POT_GAS_LIMIT
) -> Transaction:
    if gas_price is None:
        gas_price = NETWORK_CFG.GAS_PRICE
    nonce = web3.eth.getTransactionCount(from_, 'pending') + nonce_offset
    tx = Transaction(nonce, gas_price, gas_limit, to, value, data)
    tx.sender = decode_hex(from_)
    return tx
コード例 #46
0
    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
コード例 #47
0
ファイル: jsonrpc.py プロジェクト: danielnovy/test
    def call(self, data, block_id=None):
        block = self.json_rpc_server.get_block(block_id)
        # rebuild block state before finalization
        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

        # 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
        # initialize transaction
        nonce = block.get_nonce(sender)
        tx = Transaction(nonce, gasprice, startgas, to, value, data_)
        tx.sender = sender
        # apply transaction
        try:
            success, output = processblock.apply_transaction(test_block, tx)
        except processblock.InvalidTransaction:
            success = False
        if success:
            return output
        else:
            return False
コード例 #48
0
ファイル: jsonrpc.py プロジェクト: hdiedrich/pyethapp
    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'')
        gas_key = 'gas' if 'gas' in data else 'startgas'
        startgas = get_data_default(gas_key, quantity_decoder, default_startgas)
        gasprice_key = 'gasPrice' if 'gasPrice' in data else 'gasprice'
        gasprice = get_data_default(gasprice_key, 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)
        assert len(sender) == 20

        # 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)
        tx._sender = None
        print tx.log_dict()
        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.log_dict())

        if to == b'':  # create
            return address_encoder(processblock.mk_contract_address(tx.sender, nonce))
        else:
            return data_encoder(tx.hash)
コード例 #49
0
ファイル: eth_protocol.py プロジェクト: danielnovy/test
 def decode_payload(cls, rlp_data):
     # convert to dict
     txs = []
     for i, tx in enumerate(rlp.decode_lazy(rlp_data)):
         txs.append(Transaction.deserialize(tx))
         if not i % 10:
             gevent.sleep(0.0001)
     return txs
コード例 #50
0
ファイル: client.py プロジェクト: raiden-network/raiden
    def send_transaction(sender, to, value=0, data='', startgas=GAS_LIMIT,
                         gasprice=GAS_PRICE, nonce=None):
        """Custom implementation for `pyethapp.rpc_client.JSONRPCClient.send_transaction`.
        This is necessary to support other remotes that don't support pyethapp's extended specs.
        @see https://github.com/ethereum/pyethapp/blob/develop/pyethapp/rpc_client.py#L359
        """
        pending_transactions_hex = client.call(
            'eth_getTransactionCount',
            encode_hex(sender),
            'pending',
        )
        pending_transactions = int(pending_transactions_hex, 16)
        nonce = pending_transactions + nonce_offset

        tx = Transaction(nonce, gasprice, startgas, to, value, data)
        assert hasattr(client, 'privkey') and client.privkey
        tx.sign(client.privkey)
        result = client.call('eth_sendRawTransaction', rlp.encode(tx).encode('hex'))
        return result[2 if result.startswith('0x') else 0:]
コード例 #51
0
def test_create_gnt(chain):
    owner_addr, receiver_addr, gnt, gntb, cdep = mysetup(chain)
    faucet, _ = chain.provider.get_or_deploy_contract('Faucet',
                                                      deploy_args=[gnt.address])

    assert gnt.call().balanceOf(faucet.address) == 0
    chain.wait.for_receipt(gnt.transact({'from': encode_hex(ethereum.tester.a0)}).transfer(
        faucet.address, 1000 * utils.denoms.ether ))
    assert gnt.call().balanceOf(faucet.address) == 1000 * utils.denoms.ether
    key = sha3(to_string(11))
    account = privtoaddr(key)

    ethereum.tester.accounts.append(account)
    ethereum.tester.keys.append(key)

    assert chain.web3.eth.getBalance(encode_hex(account)) == 0
    previousA0 = chain.web3.eth.getBalance(encode_hex(ethereum.tester.a0))
    assert previousA0 > utils.denoms.ether

    tx = Transaction(
        nonce=chain.web3.eth.getTransactionCount(ethereum.tester.a0),
        gasprice=chain.web3.eth.gasPrice,
        startgas=100000,
        to=encode_hex(account),
        value=utils.denoms.ether,
        data=b'',
    )

    tx.sign(ethereum.tester.k0)
    raw_tx = rlp.encode(tx)
    raw_tx_hex = chain.web3.toHex(raw_tx)
    chain.web3.eth.sendRawTransaction(raw_tx_hex)

    assert gnt.call().balanceOf(faucet.address) == 1000 * utils.denoms.ether

    assert chain.web3.eth.getBalance(encode_hex(account)) == utils.denoms.ether

    assert gnt.call().decimals() == 18
    assert gnt.call().balanceOf(encode_hex(account)) == 0
    tx = chain.wait.for_receipt(
        faucet.transact({'from': encode_hex(account)}).create())
    assert gnt.call().balanceOf(encode_hex(account)) == 1000 * utils.denoms.ether
    assert gnt.call().balanceOf(faucet.address) == 0
コード例 #52
0
ファイル: rpc_client.py プロジェクト: ezdac/pyethapp
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")
コード例 #53
0
ファイル: rpc_client.py プロジェクト: ychaim/pyethapp
def signed_tx_example(to=z_address, value=100):
    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=value, 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')
コード例 #54
0
ファイル: eth.py プロジェクト: imapp-pl/ethereum-payments
def multi(o, payments):
    print "multi payment"
    data = ''
    encp = []
    value = 0
    for p in payments:
        p = p.split(':')
        print "->", p[0], p[1]
        encp.append(encode_payment(p[0], p[1]))
        value += long(p[1])

    nonce = o.eth.get_transaction_count(o.me.address.encode('hex'))
    translator = abi.ContractTranslator(BankOfDeposit.ABI)
    data = translator.encode('transfer', [encp])
    print "DATA: ", data.encode('hex')

    gas = 21000 + len(encp) * 30000
    tx = Transaction(nonce, 1, gas, to=BANK_ADDR, value=value, data=data)
    tx.sign(o.me.priv)
    print o.eth.send(tx)
コード例 #55
0
def test_eth_sendRawTransaction(web3, wait_for_transaction, extra_accounts):
    private_key = mk_random_privkey()
    address = encode_address(privtoaddr(private_key))

    funding_txn_hash = web3.eth.sendTransaction({
        "from": web3.eth.coinbase,
        "to": address,
        "value": 10000000000000000,
    })
    wait_for_transaction(web3, funding_txn_hash)

    if isinstance(web3.currentProvider, TestRPCProvider):
        # ethereum-tester-client doesn't quite implement the
        # `sendRawTransaction` correctly because of how the underlying tester
        # evm works.  It needs to know about the address for this to work.
        web3.personal.importRawKey(private_key, "password")
        web3.personal.unlockAccount(address, "password")

    initial_balance = web3.eth.getBalance(extra_accounts[1])

    tx = Transaction(
        web3.eth.getTransactionCount(address),
        web3.eth.gasPrice,
        100000,
        extra_accounts[1],
        1234,
        '',
    )
    tx.sign(private_key)

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

    txn_hash = web3.eth.sendRawTransaction(raw_tx_hex)
    wait_for_transaction(web3, txn_hash)
    txn_receipt = web3.eth.getTransactionReceipt(txn_hash)

    after_balance = web3.eth.getBalance(extra_accounts[1])

    assert after_balance - initial_balance == 1234
コード例 #56
0
ファイル: node.py プロジェクト: imapp-pl/ethereum-payments
 def deploy_contract(ethnode, init_code):
     nonce = ethnode.get_transaction_count(Faucet.ADDR.encode('hex'))
     tx = Transaction(nonce, 0, 3141592, to='', value=0, data=init_code)
     tx.sign(Faucet.PRIVKEY)
     ethnode.send(tx)
     return tx.creates
コード例 #57
0
ファイル: fork_tester.py プロジェクト: ethereum/research
state.log_listeners.append(lambda x: sys.stdout.write(str(withdrawer_ct.listen(x))+'\n'))

print 'State created'

# Check pre-balance

pre_balance = state.get_balance(my_account)
pre_dao_tokens = get_dao_balance(state, my_account)
pre_withdrawer_balance = state.get_balance(withdrawer)

print 'Pre ETH (wei) balance: %d' % pre_balance
print 'Pre DAO (base unit) balance: %d' % pre_dao_tokens

# Attempt to claim the ETH without approving (should fail)

tx0 = Transaction(state.get_nonce(my_account), 0, 1000000, withdrawer, 0, withdrawer_ct.encode('withdraw', [])).sign('\x33' * 32)
tx0._sender = normalize_address(my_account)
apply_transaction(state, tx0)

med_balance = state.get_balance(my_account)
med_dao_tokens = get_dao_balance(state, my_account)
med_withdrawer_balance = state.get_balance(withdrawer)

assert med_balance == pre_balance
assert med_dao_tokens == pre_dao_tokens
assert med_withdrawer_balance == pre_withdrawer_balance > 0

print 'ETH claim without approving failed, as expected'

# Approve the withdrawal
コード例 #58
0
ファイル: tx_sign.py プロジェクト: bargst/pyethoff
print('                 From Nonce: ' + str(tx.nonce))
print('                 To Address: ' + web3.toHex(tx.to))
print('           Transaction Data: ' + web3.toHex(tx.data))
print('======================================================')

# Using file wallet to sign transaction
if args.keytype == 'file':
    json = json.loads(open(args.keyfile).read())
    print("Enter password of keyfile or ctrl+c to cancel")
    pw = getpass()
    print("Applying hard key derivation function. Wait a little")
    k = decode_keystore_json(json, pw)

    # Prepare a new transaction (decoded transaction seems immutable...)
    tx = Transaction(
        tx.nonce, tx.gasprice, tx.startgas, tx.to, tx.value, tx.data
    )
    tx.sign(k)

# Using Ledger HW1 in DEV mode (SIGNVERIFY_IMMEDIATE)
if args.keytype == 'dongle':
    from btchip.btchip import getDongle, btchip
    from bitcoin import decode_sig as bitcoin_decode_sig
    dongle = getDongle(True)
    app = btchip(dongle)
    print("Enter pin of dongle or ctrl+c to cancel")
    pin = getpass('Pin:')
    app.verifyPin(pin)

    # Sign with dongle
    rawhash = sha3(encode(tx, UnsignedTransaction))