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))
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()
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')
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
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")
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
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
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
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
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
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)
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)
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)
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
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()}
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()
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)
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:]
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
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')
def deploy(self, _from, file_path, bytecode, sourcecode, libraries, value, params, label, abi): # replace library placeholders if libraries: for library_name, library_address in libraries.iteritems(): self.references[library_name] = self.replace_references( self.strip_0x(library_address)) if file_path: if self.contract_dir: file_path = '{}/{}'.format(self.contract_dir, file_path) bytecode, abi = self.compile_code(path=file_path) if not label: label = file_path.split("/")[-1].split(".")[0] if sourcecode: # compile code bytecode, abi = self.compile_code(code=sourcecode) if params: translator = ContractTranslator(abi) # replace constructor placeholders params = [self.replace_references(p) for p in params] bytecode += translator.encode_constructor_arguments(params).hex() # deploy contract self.log('Deployment transaction for {} sent'.format( label if label else 'unknown')) tx_response = None tx = { 'from': self._from, 'value': value, 'data': self.add_0x(bytecode), 'gas': self.gas, 'gas_price': self.gas_price } if self.private_key: tx = Transaction(tx) nonce = self.web3.eth.getTransactionCount(self._from) tx['nonce'] = nonce tx.sign(self.private_key) raw_tx = rlp.encode(tx) while tx_response is None or 'error' in tx_response: if tx_response and 'error' in tx_response: self.log('Deploy failed with error {}'.format( tx_response['error']['message'])) time.sleep(5) self.web3.eth.sendRawTransaction(raw_tx) tx_response = self.web3.eth.sendRawTransaction(raw_tx) else: while tx_response is None or 'error' in tx_response: if tx_response and 'error' in tx_response: self.log('Deploy failed with error {}'.format( tx_response['error']['message'])) time.sleep(5) tx_response = self.web3.eth.sendTransaction(tx) transaction_receipt = self.web3.eth.getTransactionReceipt(tx_response) contract_address = transaction_receipt['contractAddress'] self.references[label] = contract_address self.abis[contract_address] = abi self.log('Contract {} created at address {}'.format( label if label else 'unknown', self.add_0x(contract_address))) self.log_transaction_receipt(transaction_receipt)
def test_send_transaction(self): client = self.client addr = '\xff' * 20 priv = '\xee' * 32 tx = Transaction(1, 20 * 10**9, 21000, to=addr, value=0, data=b'') tx.sign(priv) with self.assertRaisesRegexp(ValueError, "[Ii]nsufficient funds"): client.send(tx)
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.
def make_transaction(key, nonce, value, to): gasprice = 20 * 10**9 startgas = 500 * 1000 v, r, s = 0, 0, 0 data = "foo" tx = Transaction(nonce, gasprice, startgas, to, value, data, v, r, s) tx.sign(key) return tx
def faucet_send(o, to, value): value = int(value * denoms.ether) to = normalize_address(to) tx = Transaction(o.faucet_nonce, 1, 21000, to, value, '') tx.sign(Faucet.PRIVKEY) r = o.eth.send(tx) print "Transaction sent:", r gevent.sleep(10)
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)
def send_transaction(self, sender, to, value=0, data='', startgas=0, gasprice=10 * denoms.szabo, nonce=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 and not sender: sender = privtoaddr(self.privkey) if nonce is None: nonce = self.nonce(sender) elif self.privkey: if sender != privtoaddr(self.privkey): 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: # add the fields v, r and s tx.sign(self.privkey) tx_dict = tx.to_dict() # rename the fields to match the eth_sendTransaction signature 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 res.encode('hex')
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)
def run(self): w3 = Web3(HTTPProvider(self.ETH_RPC, request_kwargs={'timeout': 120})) nonce = w3.eth.getTransactionCount(self.CREATE_ADDRESS), nonce = nonce[0] FirstAuctionTimeStamp = int( time.mktime( time.strptime(self.FirstAuctionTime, '%Y-%m-%d %H:%M:%S'))) with open('resource.json', 'r') as resource_definition: resource_json = json.load(resource_definition) with open('land.abi', 'r') as land_definition: land_abi = json.load(land_definition) nonceAdd = 0 ignoreCoord = self.ignore_coord() for index, land in enumerate(resource_json): x = -112 + index % 45 y = 22 - int(index / 45) coord = str(x) + "," + str(y) if land["isSpecial"] == 1 or land[ "isSpecial"] == 2 or coord in ignoreCoord: # Reserved land print(coord) continue land_contract = w3.eth.contract(address=self.Land_ADDRESS, abi=land_abi) try: landTokenId = land_contract.call().encodeTokenId(x, y) except: print("have error ", index, coord) break else: startingPriceInToken = Web3.toWei(6000, 'ether') endingPriceInToken = int(startingPriceInToken / 5) duration = 3600 * 6 startAt = FirstAuctionTimeStamp + 3600 * index execute_transaction = "0x6e3630a8" + \ self.u256ToInput(landTokenId) + \ self.u256ToInput(startingPriceInToken) + \ self.u256ToInput(endingPriceInToken) + \ self.u256ToInput(duration) + \ self.u256ToInput(startAt) + \ self.pandding(self.ringTokenAddress) tx = Transaction( nonce=nonce + nonceAdd, gasprice=2000000000, startgas=1000000, to=self.Genesis_HOLDER, value=0, data=w3.toBytes(hexstr=execute_transaction), ) tx.sign(self.CREATE_PRI_KEY) raw_tx = rlp.encode(tx) raw_tx_hex = w3.toHex(raw_tx) tx = w3.eth.sendRawTransaction(raw_tx_hex) nonceAdd += 1 print(tx)
def _get_signed_transaction( self, transaction_signing_request: TransactionSigningRequest ) -> Union[SignedTransaction, TransactionRejected]: """ This function verifies if data in received TransactionSigningRequest can be used to correctly instantiate Ethereum Transaction object, signs this transaction, and handles related errors. Returns Golem messages SignedTransaction if transaction was signed correctly, otherwise TransactionRejected. """ assert isinstance(transaction_signing_request, TransactionSigningRequest) try: transaction = Transaction( nonce = transaction_signing_request.nonce, gasprice = transaction_signing_request.gasprice, startgas = transaction_signing_request.startgas, to = transaction_signing_request.to, value = transaction_signing_request.value, data = transaction_signing_request.data, ) except (InvalidTransaction, TypeError): # Is it possible to load the transaction using the library we're using to sign it? # If not, rejection reason is InvalidTransaction return TransactionRejected( reason=TransactionRejected.REASON.InvalidTransaction, nonce=transaction_signing_request.nonce, ) # If transaction is correct, sign it. try: transaction.sign(self.ethereum_private_key) except (InvalidTransaction, TypeError): # Does the transaction execute a function from the contract that the service has the private key for? # If not, rejection reason is UnauthorizedAccount. return TransactionRejected( reason=TransactionRejected.REASON.UnauthorizedAccount, nonce=transaction_signing_request.nonce, ) assert transaction.v is not None assert transaction.r is not None assert transaction.s is not None # Respond with SignedTransaction. return SignedTransaction( nonce = transaction_signing_request.nonce, gasprice = transaction_signing_request.gasprice, startgas = transaction_signing_request.startgas, to = transaction_signing_request.to, value = transaction_signing_request.value, data = transaction_signing_request.data, v = transaction.v, r = transaction.r, s = transaction.s, )
async def faucet(self, to, value, *, from_private_key=FAUCET_PRIVATE_KEY, startgas=None, gasprice=DEFAULT_GASPRICE, nonce=None, data=b"", wait_on_confirmation=True): if isinstance(from_private_key, str): from_private_key = data_decoder(from_private_key) from_address = private_key_to_address(from_private_key) ethclient = JsonRPCClient(config['ethereum']['url']) to = data_decoder(to) if len(to) not in (20, 0): raise Exception( 'Addresses must be 20 or 0 bytes long (len was {})'.format( len(to))) if nonce is None: nonce = await ethclient.eth_getTransactionCount(from_address) balance = await ethclient.eth_getBalance(from_address) if startgas is None: startgas = await ethclient.eth_estimateGas(from_address, to, data=data, nonce=nonce, value=value, gasprice=gasprice) tx = Transaction(nonce, gasprice, startgas, to, value, data, 0, 0, 0) if balance < (tx.value + (tx.startgas * tx.gasprice)): raise Exception("Faucet doesn't have enough funds") tx.sign(from_private_key) tx_encoded = data_encoder(rlp.encode(tx, Transaction)) tx_hash = await ethclient.eth_sendRawTransaction(tx_encoded) while wait_on_confirmation: resp = await ethclient.eth_getTransactionByHash(tx_hash) if resp is None or resp['blockNumber'] is None: await asyncio.sleep(0.1) else: break if to == b'': print("contract address: {}".format(data_encoder(tx.creates))) return tx_hash
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 """ def get_nonce(): """Eventually syncing nonce counter. This will keep a local nonce counter that is only syncing against the remote every `UPDATE_INTERVAL`. If the remote counter is lower than the current local counter, it will wait for the remote to catch up. """ with client.nonce_lock: UPDATE_INTERVAL = 5. query_time = now() needs_update = abs(query_time - client.last_nonce_update) > UPDATE_INTERVAL not_initialized = client.current_nonce is None if needs_update or not_initialized: nonce = _query_nonce() # we may have hammered the server and not all tx are # registered as `pending` yet while nonce < client.current_nonce: log.debug( "nonce on server too low; retrying", server=nonce, local=client.current_nonce ) nonce = _query_nonce() query_time = now() client.current_nonce = nonce client.last_nonce_update = query_time else: client.current_nonce += 1 return client.current_nonce def _query_nonce(): pending_transactions_hex = client.call( 'eth_getTransactionCount', address_encoder(sender), 'pending', ) pending_transactions = int(pending_transactions_hex, 16) nonce = pending_transactions + nonce_offset return nonce nonce = get_nonce() 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:]
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
def gimme_money(ethnode, addr, value): nonce = ethnode.get_transaction_count('0x' + 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( value / denoms.ether, '0x' + addr.encode('hex'), h)) h = h[2:].decode('hex') return h
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')
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
def send_transaction(sender, to, value=0, data='', startgas=3141592, 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 """ nonce = int(client.call('eth_getTransactionCount', encode_hex(sender), 'pending'), 16) + 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:]
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]
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)
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
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)
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")
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')
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
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
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)) signature = app.signImmediate(bytearray(decode_hex(args.keyfile)), rawhash)
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