def redeem(self, secret: str) -> EthereumTokenTransaction: if self.balance == 0: raise ValueError("Balance of this contract is 0.") contract = self.contract redeem_func = contract.functions.redeem(secret) tx_dict = { 'nonce': self.network.web3.eth.getTransactionCount(self.recipient_address), 'value': 0, 'gas': ETH_REDEEM_GAS_LIMIT, } tx_dict = redeem_func.buildTransaction(tx_dict) transaction = EthereumTokenTransaction(network=self.network) transaction.tx = Transaction( nonce=tx_dict['nonce'], gasprice=tx_dict['gasPrice'], startgas=tx_dict['gas'], to=tx_dict['to'], value=tx_dict['value'], data=Web3.toBytes(hexstr=tx_dict['data']), ) transaction.value = self.value transaction.token = self.token transaction.recipient_address = self.recipient_address return transaction
def main(): erc20_data = make_data(to='0x56e5782c908f69bd46b7e77338349f961fbe55b1', value=Decimal('2019.08281809') * (10**18)) print("erc20_data:{}".format(erc20_data)) tx = Transaction( nonce=120, gasprice=10 * (10**9), startgas=210000, to='0x130fc2749d35fe026f32427f60dd3f2ecb6c2f33', value=0, # data=b'' data=erc20_data.decode('hex')) tx.sender = '0x954d1a58c7abd4ac8ebe05f59191cf718eb0cb89' # print(tx.hash) signed_tx = tx.sign( key='DBBAD2A5682517E4FF095F948F721563231282CA4179AE0DFEA1C76143BA9607', 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
def set_contract(self): self.contract = self.network.web3.eth.contract( address=self.contract_address, abi=self.abi) initiate_func = self.contract.functions.initiate( self.locktime_unix, self.secret_hash, self.recipient_address, self.token_address, bool(self.token), self.token_value_base_units, ) tx_dict = { 'nonce': self.network.web3.eth.getTransactionCount(self.sender_address), 'from': self.sender_address, 'value': self.value_base_units, } tx_dict = initiate_func.buildTransaction(tx_dict) self.gas_limit = initiate_func.estimateGas({ key: value for key, value in tx_dict.items() if key not in ('to', 'data') }) self.tx = Transaction( nonce=tx_dict['nonce'], gasprice=tx_dict['gasPrice'], startgas=self.gas_limit, to=tx_dict['to'], value=tx_dict['value'], data=Web3.toBytes(hexstr=tx_dict['data']), )
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
def refund(self): contract = self.network.web3.eth.contract(address=self.contract_address, abi=self.network.abi) if self.locktime > datetime.utcnow(): locktime_string = self.locktime.strftime('%Y-%m-%d %H:%M:%S') logger.warning(f"This contract is still valid! It can't be refunded until {locktime_string} UTC.") raise RuntimeError(f"This contract is still valid! It can't be refunded until {locktime_string} UTC.") refund_func = contract.functions.refund(self.secret_hash, self.recipient_address) tx_dict = { 'nonce': self.network.web3.eth.getTransactionCount(self.refund_address), 'value': 0, 'gas': ETH_REFUND_GAS_LIMIT, } tx_dict = refund_func.buildTransaction(tx_dict) transaction = EthereumTokenTransaction(network=self.network) transaction.tx = Transaction( nonce=tx_dict['nonce'], gasprice=tx_dict['gasPrice'], startgas=tx_dict['gas'], to=tx_dict['to'], value=tx_dict['value'], data=Web3.toBytes(hexstr=tx_dict['data']), ) transaction.value = self.value transaction.token = self.token transaction.recipient_address = self.refund_address logger.debug('Transaction refunded') return transaction
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 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 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
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
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
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 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 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 make_test_tx(s=100000, g=50, data='', nonce=0): from ethereum.transactions import Transaction return Transaction(nonce=nonce, startgas=s, gasprice=g, value=0, data=data, to=b'\x35' * 20)
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 test_sign(account, password): tx = Transaction(1, 0, 0, account.address, 0, '') account.sign_tx(tx) assert tx.sender == account.address account.lock() with pytest.raises(ValueError): account.sign_tx(tx) account.unlock(password)
def create_transaction(self, func_name, args, nonce_offset=0, value=0): data = self.create_transaction_data(func_name, args) nonce = self.web3.eth.getTransactionCount(self.caller_address, 'pending') + nonce_offset tx = Transaction(nonce, self.gas_price, self.gas_limit, self.address, value, data) # v = CHAIN_ID according to EIP 155. tx.v = self.web3.version.network tx.sender = decode_hex(self.caller_address) return tx
def tx(self, sender=k0, to=b'\x00' * 20, value=0, data=b'', startgas=STARTGAS, gasprice=GASPRICE): sender_addr = privtoaddr(sender) self.last_sender = sender transaction = Transaction(self.head_state.get_nonce(sender_addr), gasprice, startgas, to, value, data).sign(sender) output = self.direct_tx(transaction) return output
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 deposit(self, gasprice=20 * 10**9): assert value * 10**18 >= self.chain.state.get_balance( self.address) + gasprice * 1000000 tx = Transaction( self.chain.state.get_nonce(self.address) * 10**18, gasprice, 1000000, casper_config['CASPER_ADDR'], value * 10**18, ct.encode('deposit', [self.validation_code, self.randao.get(9999)]))
def _generateAddressBInternal(addressA, addressC, sendAmount, dappData, gasPrice, gasLimit, nonce=0, V=27): ''' Main function Generates the Reveal Transaction, commit and generates addressB :param addressA: Sender's Address :param addressC: Smart Contracts Address :param sendAmount: Send Amount (in Wei) :param data: Data for smart contract C :param gasPrice: Gas Price :param gasLimit: Gas Limit :param nonce: default 0 :param V: default 27 --> no replay protection. :return: tx obj, addressB, commit, randw tx object --> reveal transaction (addressB to addressC), includes commit in data addressB : Commit transaction receiver commit : commit message randw: w (witness) random number ''' commit, randw, R, S = _generateRS(addressA, addressC, sendAmount, dappData, gasPrice, gasLimit) submarineData = unlockFunctionSelector + commit # assert(len(commit) == 36) tx = Transaction(nonce, gasPrice, gasLimit, addressC, sendAmount, data=submarineData, v=V, r=R, s=S) try: addressB = tx.to_dict().get("sender") log.info("Unlock TX Dict: {}".format(tx.to_dict())) return tx, addressB, commit, randw except (ValueError, InvalidTransaction) as e: if isinstance(e, ValueError) and "VRS" not in str(e): raise log.info("Address no good (%s), retrying" % e) return _generateAddressBInternal(addressA, addressC, sendAmount, dappData, gasPrice, gasLimit, nonce, V)
def send_transaction( self, sender, to, value=0, data='', startgas=0, gasprice=GAS_PRICE, 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: 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')
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 _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, )
def tx(self, sender=k0, to=b'\x00' * 20, value=0, data=b'', startgas=STARTGAS, gasprice=GASPRICE): sender_addr = privtoaddr(sender) transaction = Transaction(self.state.get_nonce(sender_addr), gasprice, startgas, to, value, data).sign(sender) success, output = apply_transaction(self.state, transaction) if not success: raise TransactionFailed() return output
def get_contract_code(init_code): s = State(env=Env(config=casper_config)) s.gas_limit = 10**9 apply_transaction(s, Transaction(0, 0, 10**8, '', 0, init_code)) addr = utils.mk_metropolis_contract_address( casper_config['METROPOLIS_ENTRY_POINT'], init_code) o = s.get_code(addr) assert o return o
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 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 withdraw(self, gasprice=20 * 10**9): sigdata = make_withdrawal_signature(self.key) txdata = casper_ct.encode('startWithdrawal', [self.vchash, sigdata]) tx = Transaction(self.chain.state.get_nonce(self.address), gasprice, 650000, self.chain.config['CASPER_ADDR'], 0, txdata).sign(self.key) self.txqueue.add_transaction(tx, force=True) self.network.broadcast(self, tx) print 'Withdrawing!'