def all_rlp_fields_to_dict_camel_case( rlp_object: Union[rlp.Serializable, List, Tuple] ) -> Union[Dict[str, any], List[any]]: #It is either rlp.Serializable or a list if isinstance(rlp_object, rlp.Serializable): dict_to_return = {} # add all of the fields in camelcase for i in range(len(rlp_object._meta.field_names)): field_name = rlp_object._meta.field_names[i] key = underscore_to_camel_case(field_name) raw_val = getattr(rlp_object, field_name) if isinstance(raw_val, rlp.Serializable) or isinstance( raw_val, list) or isinstance(raw_val, tuple): val = all_rlp_fields_to_dict_camel_case(raw_val) else: val = to_hex(raw_val) dict_to_return[key] = val return dict_to_return else: list_to_return = [] for i in range(len(rlp_object)): raw_val = rlp_object[i] if isinstance(raw_val, rlp.Serializable) or isinstance( raw_val, list) or isinstance(raw_val, tuple): val = all_rlp_fields_to_dict_camel_case(raw_val) else: val = to_hex(raw_val) list_to_return.append(val) return list_to_return
async def handle_get_block_bodies(self, peer: ETHPeer, block_hashes: Sequence[Hash32]) -> None: if not peer.is_operational: return self.logger.debug2("%s requested bodies for %d blocks", peer, len(block_hashes)) bodies = [] # Only serve up to MAX_BODIES_FETCH items in every request. for block_hash in block_hashes[:MAX_BODIES_FETCH]: try: header = await self.wait( self.db.coro_get_block_header_by_hash(block_hash)) except HeaderNotFound: self.logger.debug("%s asked for a block we don't have: %s", peer, to_hex(block_hash)) continue try: transactions = await self.wait( self.db.coro_get_block_transactions( header, BaseTransactionFields)) except MissingTrieNode as exc: self.logger.debug( "%s asked for block transactions we don't have: %s, " "due to %r", peer, to_hex(block_hash), exc, ) continue uncles = await self.wait( self.db.coro_get_block_uncles(header.uncles_hash)) bodies.append(BlockBody(transactions, uncles)) self.logger.debug2("Replying to %s with %d block bodies", peer, len(bodies)) peer.sub_proto.send_block_bodies(bodies)
def initiate_payment( self, registry_address: typing.PaymentNetworkID, token_address: typing.TokenAddress, target_address: typing.Address, amount: typing.TokenAmount, identifier: typing.PaymentID, ): log.debug( 'Initiating payment', node=pex(self.raiden_api.address), registry_address=to_checksum_address(registry_address), token_address=to_checksum_address(token_address), target_address=to_checksum_address(target_address), amount=amount, payment_identifier=identifier, ) if identifier is None: identifier = create_default_identifier() try: payment_status = self.raiden_api.transfer( registry_address=registry_address, token_address=token_address, target=target_address, amount=amount, identifier=identifier, ) except (InvalidAmount, InvalidAddress, PaymentConflict, UnknownTokenAddress) as e: return api_error( errors=str(e), status_code=HTTPStatus.CONFLICT, ) except InsufficientFunds as e: return api_error( errors=str(e), status_code=HTTPStatus.PAYMENT_REQUIRED, ) if payment_status.payment_done is False: return api_error( errors="Payment couldn't be completed " "(insufficient funds, no route to target or target offline).", status_code=HTTPStatus.CONFLICT, ) payment = { 'initiator_address': self.raiden_api.address, 'registry_address': registry_address, 'token_address': token_address, 'target_address': target_address, 'amount': amount, 'identifier': identifier, 'secret': to_hex(payment_status.secret), 'secret_hash': to_hex(payment_status.secret_hash), } result = self.payment_schema.dump(payment) return api_response(result=result.data)
async def handle_get_receipts(self, peer: ETHPeer, block_hashes: Sequence[Hash32]) -> None: if not peer.is_operational: return self.logger.debug2("%s requested receipts for %d blocks", peer, len(block_hashes)) receipts = [] # Only serve up to MAX_RECEIPTS_FETCH items in every request. for block_hash in block_hashes[:MAX_RECEIPTS_FETCH]: try: header = await self.wait( self.db.coro_get_block_header_by_hash(block_hash)) except HeaderNotFound: self.logger.debug( "%s asked receipts for a block we don't have: %s", peer, to_hex(block_hash)) continue try: block_receipts = await self.wait( self.db.coro_get_receipts(header, Receipt)) except MissingTrieNode as exc: self.logger.debug( "%s asked for block receipts we don't have: %s, " "due to %r", peer, to_hex(block_hash), exc, ) continue receipts.append(block_receipts) self.logger.debug2("Replying to %s with receipts for %d blocks", peer, len(receipts)) peer.sub_proto.send_receipts(receipts)
async def handle_get_receipts(self, peer: ETHProxyPeer, command: GetReceiptsV65) -> None: block_hashes = command.payload self.logger.debug2("%s requested receipts for %d blocks", peer, len(block_hashes)) receipts = [] # Only serve up to MAX_RECEIPTS_FETCH items in every request. for block_hash in block_hashes[:MAX_RECEIPTS_FETCH]: try: header = await self.db.coro_get_block_header_by_hash(block_hash) except HeaderNotFound: self.logger.debug( "%s asked receipts for a block we don't have: %s", peer, to_hex(block_hash) ) continue vm_class = self._chain_class.get_vm_class_for_block_number(header.block_number) try: block_receipts = await self.db.coro_get_receipts( header, vm_class.get_receipt_builder(), ) except MissingTrieNode as exc: self.logger.debug( "%s asked for block receipts we don't have: %s, " "due to %r", peer, to_hex(block_hash), exc, ) continue receipts.append(block_receipts) self.logger.debug2("Replying to %s with receipts for %d blocks", peer, len(receipts)) peer.eth_api.send_receipts(receipts)
def update_iou( iou: typing.Dict[str, typing.Any], privkey: bytes, added_amount: typing.TokenAmount = 0, expiration_block: typing.Optional[typing.BlockNumber] = None, ) -> typing.Dict[str, typing.Any]: expected_signature = to_hex( sign_one_to_n_iou( privatekey=to_hex(privkey), expiration=iou['expiration_block'], sender=iou['sender'], receiver=iou['receiver'], amount=iou['amount'], )) if iou.get('signature') != expected_signature: raise ServiceRequestFailed( 'Last IOU as given by the pathfinding service is invalid (signature does not match)', ) iou['amount'] += added_amount if expiration_block: iou['expiration_block'] = expiration_block iou['signature'] = sign_one_to_n_iou( privatekey=to_hex(privkey), expiration=iou['expiration_block'], sender=iou['sender'], receiver=iou['receiver'], amount=iou['amount'], ) return iou
def create_latest_block_uri(w3: Web3, tx_receipt: TxReceipt) -> URI: """ Creates a new block uri from data in w3 and provided tx_receipt. """ chain_id = to_hex(get_genesis_block_hash(w3)) block_hash = to_hex(tx_receipt.blockHash) return create_block_uri(chain_id, block_hash)
async def retrieve_block(w3: Web3, block_number: int) -> Block: block_data = await trio.to_thread.run_sync(w3.eth.getBlock, block_number, True) transactions_data = cast(Sequence[TxData], block_data["transactions"]) transaction_hashes = tuple(to_hex(tx_data["hash"]) for tx_data in transactions_data) receipts_data = await gather( *( (trio.to_thread.run_sync, w3.eth.getTransactionReceipt, transaction_hash) for transaction_hash in transaction_hashes ) ) uncles_data = await gather( *( ( trio.to_thread.run_sync, w3.eth.getUncleByBlock, to_hex(block_data["hash"]), idx, ) for idx in range(len(block_data["uncles"])) ) ) return extract_block( block_data, transactions_data=transactions_data, uncles_data=uncles_data, receipts_data=receipts_data, )
def check_addresses(backers): result = [] for backer in backers: if not is_hex(backer): to_hex(backer) result.append(backer) return result
def update_iou( iou: Dict[str, Any], privkey: bytes, added_amount: TokenAmount = ZERO_TOKENS, expiration_block: Optional[BlockNumber] = None, ) -> Dict[str, Any]: expected_signature = to_hex( sign_one_to_n_iou( privatekey=to_hex(privkey), expiration=iou["expiration_block"], sender=iou["sender"], receiver=iou["receiver"], amount=iou["amount"], )) if iou.get("signature") != expected_signature: raise ServiceRequestFailed( "Last IOU as given by the pathfinding service is invalid (signature does not match)" ) iou["amount"] += added_amount if expiration_block: iou["expiration_block"] = expiration_block iou["signature"] = to_hex( sign_one_to_n_iou( privatekey=to_hex(privkey), expiration=iou["expiration_block"], sender=iou["sender"], receiver=iou["receiver"], amount=iou["amount"], )) return iou
def main(): try: # Connect to web3 w3 = connect_to_web3(URL) # Load contracts Ransom = load_contract(w3, os.path.join(PATH, 'Ransom.json')) Escrow = load_contract(w3, os.path.join(PATH, 'Escrow.json')) Registry = load_contract(w3, os.path.join(PATH, 'Escrow.json')) escrow_contract = Escrow(address=w3.toChecksumAddress(ESCROW_ADDRESS)) registry_contract = Registry( address=w3.toChecksumAddress(REGISTRY_ADDRESS)) ransom_contract = Ransom(address=w3.toChecksumAddress(RANSOM_ADDRESS)) victims = [] with open('victims.txt') as v: for line in v: victims.append(line.strip()) with open('payed_accounts.txt') as p: for line in p: m = w3.eth.getBalance(w3.toChecksumAddress(line.strip())) print(w3.fromWei(m, 'ether')) pos = str(7).rjust(64, '0') storage_key = to_hex(w3.sha3(hexstr=pos)) user = w3.toHex( w3.eth.getStorageAt(w3.toChecksumAddress(ESCROW_ADDRESS), storage_key)) print("User Address:", user) print(w3.toHex(w3.eth.getBalance( w3.toChecksumAddress(ESCROW_ADDRESS)))) x = w3.eth.getBalance(w3.toChecksumAddress(MYRANSOM_ADDRESS)) print("My Ransom Balance:", w3.fromWei(x, 'ether')) for v in victims: print("Victim:", v) key = remove_0x_prefix(v).rjust(64, '0').lower() pos = str(3).rjust(64, '0') storage_key = to_hex(w3.sha3(hexstr=key + pos)) print( w3.toHex( w3.eth.getStorageAt(w3.toChecksumAddress(ESCROW_ADDRESS), storage_key))) ''' for x in range(0, 20): pos = str(1).rjust(64, '0') storage_key = hex(int(to_hex(w3.sha3(hexstr=pos)),16) + x) print(w3.toHex(w3.eth.getStorageAt(w3.toChecksumAddress(ESCROWADDRESS), storage_key))) ''' except requests.exceptions.HTTPError as http_err: LOG.error("web3 connection failure: {0}".format(http_err)) return 2 except Exception as e: LOG.error("Caught exception: {0}".format(e)) return 3 return 0
def transaction(simple_contract_address): function_selector = function_signature_to_4byte_selector('getMeaningOfLife()') return { 'from': '0x' + 'ff' * 20, # unfunded address 'to': to_hex(simple_contract_address), 'gasPrice': to_hex(0), 'data': to_hex(function_selector), }
def ProcessEpoch(block_num): blk = rpc.eth.getBlock(to_hex(block_num)) #blk = api.models.block.Block.objects.get(id=block_id) slashedNode = [] epoch = blk.number // settings.BLOCKS_PER_EPOCH log.info('\tProcessing epoch at block {0}.'.format(block_num)) if epoch > 0: end_block = blk.number - 1 start_block = end_block - settings.BLOCKS_PER_EPOCH + 1 s_b = rpc.eth.getBlock(to_hex(start_block)) e,created = api.models.epoch.Epoch.objects.get_or_create( epoch = epoch, defaults = { 'epoch':epoch, 'startTime': pytz.utc.localize(datetime.fromtimestamp(float(s_b.timestamp))), 'endTime': pytz.utc.localize(datetime.fromtimestamp(float(blk.timestamp))), 'startBlock': start_block, 'endBlock': end_block, 'isActive': False, }, ) e.startTime= pytz.utc.localize(datetime.fromtimestamp(float(s_b.timestamp))) e.isActive = False ne,necreated = api.models.epoch.Epoch.objects.get_or_create( epoch = epoch + 1, defaults = { 'epoch':epoch + 1, 'startTime':pytz.utc.localize(datetime.fromtimestamp(float(s_b.timestamp))), 'endTime':pytz.utc.localize(datetime.fromtimestamp(float(s_b.timestamp))), 'startBlock': blk.number, 'endBlock': blk.number + settings.BLOCKS_PER_EPOCH - 1, 'isActive': True, }, ) e.save() ne.save() if (blk.penalties != "0x"): for addr in zip(islice(blk.penalties[2:], 0, None, 20)): if addr.len() > 0: slashedNode.append(addr) if (slashedNode.len() > 0): for i in range(0,4): nextEpoch = epoch + 1 + i e,created = api.models.epoch.Epoch.objects.get_or_create( epoch = nextEpoch, defaults = { 'epoch':nextEpoch, 'startTime':pytz.utc.localize(datetime.fromtimestamp(float(s_b.timestamp))), 'startBlock': ((nextEpoch - 1) * settings.BLOCKS_PER_EPOCH), 'endBlock': (nextEpoch * settings.BLOCKS_PER_EPOCH) - 1, 'isActive': False, 'slashedNode': str(slashedNode) }, ) if not created: e.slashedNode = str(ast.literal_eval(e.slashedNode).extend(slashedNode)) e.save()
def create_finalization_values(sk, balance, index, party): sigma_E_msg = "updated|" + str(index) sigma_E = w3.eth.account.sign_message(encode_defunct(text=sigma_E_msg), private_key=sk) msg = str(index) + "|" + str(balance) + "|0x" + str.upper(party[2:]) sigma_i = to_hex( w3.eth.account.sign_message(encode_defunct(text=msg), private_key=sk).signature) return sigma_E_msg, to_hex(sigma_E.signature), msg, sigma_i
def get_keys_from_file(keyfile_path, keyfile_password): with open(keyfile_path) as keyfile: encrypted_key = keyfile.read() private_key = w3.eth.account.decrypt(encrypted_key, keyfile_password) pk = keys.PrivateKey(private_key) private_key_hex = to_hex(private_key) # hex string public_key_hex = to_hex(pk.public_key._raw_key) # hex string return public_key_hex, private_key_hex
def main(): try: # Connect to web3 w3 = connect_to_web3(URL) # Load contracts Ransom = load_contract(w3, os.path.join(PATH, 'Ransom.json')) Escrow = load_contract(w3, os.path.join(PATH, 'Escrow.json')) escrow_contract = Escrow(address=(ESCROW_ADDRESS)) ransom_address = [] victim_id = [] fulfilled = [] # Get all ransom addresses that the escrow is in charge of for x in range(0, 10): pos = str(9).rjust(64, '0') storage_key = hex(int(to_hex(w3.sha3(hexstr=pos)), 16) + x) ransom_address.append( w3.toHex( w3.eth.getStorageAt(escrow_contract.address, storage_key))) #print("Ransom Address {0}".format(x), ransom_address[x]) # Get victim IDs from the ransom addresses for x in range(0, 10): pos = str(6).rjust(64, '0') key = remove_0x_prefix(ransom_address[x]).rjust(64, "0").lower() storage_key = to_hex(w3.sha3(hexstr=key + pos)) victim_id.append( w3.toHex( w3.eth.getStorageAt(escrow_contract.address, storage_key))) #print("Victim ID {0}".format(x), victim_id[x]) # Get contract fulfillment status for x in range(0, 10): address = remove_0x_prefix(ransom_address[x]) #print(address[24:]) ransom_contract = Ransom( address=w3.toChecksumAddress(address[24:])) result = ransom_contract.functions.isFulFilled().call() if result == True: fulfilled.append(victim_id[x]) #print(result) for victim in victim_id: print(victim) except requests.exceptions.HTTPError as http_err: LOG.error("web3 connection failure: {0}".format(http_err)) return 2 except Exception as e: LOG.error("Caught exception: {0}".format(e)) return 3 return 0
def test_insert_deployment(escrow_deployer): w3 = escrow_deployer.package.w3 escrow_package = escrow_deployer.package init_deployment_data = { "contract_type": "Escrow", "address": "0x", "transaction": "0x", "block": "0x", } new_deployment_data = { "contract_type": "Escrow", "address": "0x123", "transaction": "0x123", "block": "0x123", } genesis_hash = to_hex(get_genesis_block_hash(w3)) w3.testing.mine(1) init_block_hash = to_hex(w3.eth.getBlock("latest")["hash"]) init_block_uri = create_block_uri(genesis_hash, init_block_hash) alt_block_uri = init_block_uri[:15] + "yxz123" + init_block_uri[21:] init_block_deployment_data = { init_block_uri: { "Other": { "x": "x" }, "Escrow": init_deployment_data }, alt_block_uri: { "alt": { "x": "x" } }, } w3.testing.mine(1) new_block_hash = to_hex(w3.eth.getBlock("latest")["hash"]) new_block_uri = create_block_uri(genesis_hash, new_block_hash) escrow_package.manifest = assoc(escrow_package.manifest, "deployments", init_block_deployment_data) updated_manifest = insert_deployment(escrow_package, "Escrow", new_deployment_data, new_block_uri) expected_deployments_data = { new_block_uri: { "Other": { "x": "x" }, "Escrow": new_deployment_data }, alt_block_uri: { "alt": { "x": "x" } }, } assert updated_manifest["deployments"] == expected_deployments_data
def create_deployment_data( contract_name: ContractName, new_address: Address, tx_receipt: TxReceipt, link_refs: List[Dict[str, Any]] = None, ) -> Iterable[Tuple[str, Any]]: yield "contract_type", contract_name yield "address", new_address yield "transaction", to_hex(tx_receipt["transactionHash"]) yield "block", to_hex(tx_receipt["blockHash"]) if link_refs: yield "runtime_bytecode", {"link_dependencies": create_link_dep(link_refs)}
def reward_type_2_to_dict(reward_type_2: StakeRewardType2) -> Dict[str, str]: dict_to_return = {} dict_to_return['amount'] = to_hex(reward_type_2.amount) dict_to_return['proof'] = [] for proof in reward_type_2.proof: proof_dict = all_rlp_fields_to_dict_camel_case(proof) proof_dict['sender'] = to_hex(proof.sender) dict_to_return['proof'].append(proof_dict) return dict_to_return
def _maybe_run_callbacks(self, latest_block: BlockData) -> None: """Run the callbacks if there is at least one new block. The callbacks are executed only if there is a new block, otherwise the filters may try to poll for an inexisting block number and the Ethereum client can return an JSON-RPC error. """ latest_block_number = latest_block["number"] # First run, set the block and run the callbacks if self.known_block_number is None: self.known_block_number = latest_block_number missed_blocks = 1 else: missed_blocks = latest_block_number - self.known_block_number if missed_blocks < 0: log.critical( "Block number decreased", chain_id=self.rpc_client.chain_id, known_block_number=self.known_block_number, old_block_number=latest_block["number"], old_gas_limit=latest_block["gasLimit"], old_block_hash=to_hex(latest_block["hash"]), node=to_checksum_address(self.rpc_client.address), ) elif missed_blocks > 0: log_details = dict( known_block_number=self.known_block_number, latest_block_number=latest_block_number, latest_block_hash=to_hex(latest_block["hash"]), latest_block_gas_limit=latest_block["gasLimit"], node=to_checksum_address(self.rpc_client.address), ) if missed_blocks > 1: log_details["num_missed_blocks"] = missed_blocks - 1 log.debug("Received new block", **log_details) remove = list() for callback in self.callbacks: result = callback(latest_block) if result is REMOVE_CALLBACK: remove.append(callback) for callback in remove: self.callbacks.remove(callback) self.known_block_number = latest_block_number
async def test_eth_call_with_contract_on_ipc(chain, jsonrpc_ipc_pipe_path, simple_contract_address, signature, gas_price, event_loop, ipc_server, expected): function_selector = function_signature_to_4byte_selector(signature) transaction = { 'from': '0x' + 'ff' * 20, # unfunded address 'to': to_hex(simple_contract_address), 'gasPrice': to_hex(gas_price), 'data': to_hex(function_selector), } request_msg = build_request('eth_call', params=[transaction, 'latest']) result = await get_ipc_response(jsonrpc_ipc_pipe_path, request_msg, event_loop) assert result == expected
def get_state_change_with_transfer_by_secrethash( storage: SerializedSQLiteStorage, secrethash: SecretHash) -> Optional[StateChangeRecord]: filters = [ { "from_transfer.lock.secrethash": to_hex(secrethash) }, { "transfer.lock.secrethash": to_hex(secrethash) }, ] query = FilteredDBQuery(filters=filters, main_operator=Operator.OR, inner_operator=Operator.NONE) return storage.get_latest_state_change_by_data_field(query)
def prep_chain_tx_send_data(tx): write_data = { "hash": to_hex(tx["hash"]), "blockHash": to_hex(tx["blockHash"]), "nonce": tx["nonce"], "gasPrice": tx["gasPrice"], "gas": tx["gas"], "to": tx["to"], "value": tx["value"], "input": tx["input"], "v": tx["v"], "r": Web3.toInt(tx["r"]), "s": Web3.toInt(tx["s"]) } return write_data
def hex_encode_abi_type(abi_type: TypeStr, value: Any, force_size: int = None) -> HexStr: """ Encodes value into a hex string in format of abi_type """ validate_abi_type(abi_type) validate_abi_value(abi_type, value) data_size = force_size or size_of_type(abi_type) if is_array_type(abi_type): sub_type = sub_type_of_array_type(abi_type) return HexStr("".join([ remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value ])) elif is_bool_type(abi_type): return to_hex_with_size(value, data_size) elif is_uint_type(abi_type): return to_hex_with_size(value, data_size) elif is_int_type(abi_type): return to_hex_twos_compliment(value, data_size) elif is_address_type(abi_type): return pad_hex(value, data_size) elif is_bytes_type(abi_type): if is_bytes(value): return encode_hex(value) else: return value elif is_string_type(abi_type): return to_hex(text=value) else: raise ValueError("Unsupported ABI type: {0}".format(abi_type))
def __init__(self, abi, address, block_height="latest"): self.abi = abi self.address = address if block_height != "latest": self.block_height = to_hex(block_height) else: self.block_height = block_height
def hex_encode_abi_type(abi_type, value, force_size=None): """ Encodes value into a hex string in format of abi_type """ validate_abi_type(abi_type) validate_abi_value(abi_type, value) data_size = force_size or size_of_type(abi_type) if is_array_type(abi_type): sub_type = sub_type_of_array_type(abi_type) return "".join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value]) elif is_bool_type(abi_type): return to_hex_with_size(value, data_size) elif is_uint_type(abi_type): return to_hex_with_size(value, data_size) elif is_int_type(abi_type): return to_hex_twos_compliment(value, data_size) elif is_address_type(abi_type): return pad_hex(value, data_size) elif is_bytes_type(abi_type): if is_bytes(value): return encode_hex(value) else: return value elif is_string_type(abi_type): return to_hex(text=value) else: raise ValueError( "Unsupported ABI type: {0}".format(abi_type) )
def build_etherscan_manifest(uri: URI, package_name: str, version: str) -> Iterable[Tuple[str, Any]]: address, chain_id = parse.urlparse(uri).netloc.split(":") network = get_etherscan_network(chain_id) body = make_etherscan_request(address, network) contract_type = body["ContractName"] w3 = setup_w3(to_int(text=chain_id)) block_uri = create_latest_block_uri(w3) runtime_bytecode = to_hex( w3.eth.getCode(ChecksumAddress(HexAddress(HexStr(address))))) yield "package_name", package_name yield "version", version yield "manifest_version", "2" yield "sources", {f"./{contract_type}.sol": body["SourceCode"]} yield "contract_types", { contract_type: { "abi": json.loads(body["ABI"]), "runtime_bytecode": { "bytecode": runtime_bytecode }, "compiler": generate_compiler_info(body), } } yield "deployments", { block_uri: { contract_type: { "contract_type": contract_type, "address": address } } }
def update_iou( iou: IOU, privkey: bytes, added_amount: TokenAmount = ZERO_TOKENS, expiration_block: Optional[BlockNumber] = None, ) -> IOU: expected_signature = Signature( sign_one_to_n_iou( privatekey=to_hex(privkey), sender=to_checksum_address(iou.sender), receiver=to_checksum_address(iou.receiver), amount=iou.amount, expiration_block=iou.expiration_block, one_to_n_address=to_checksum_address(iou.one_to_n_address), chain_id=iou.chain_id, )) if iou.signature != expected_signature: raise ServiceRequestFailed( "Last IOU as given by the Pathfinding Service is invalid (signature does not match)" ) iou.amount = TokenAmount(iou.amount + added_amount) if expiration_block: iou.expiration_block = expiration_block iou.sign(privkey) return iou
def getstorageatindex(contractaddress, i, k, provider='http://127.0.0.1:8545'): web3 = Web3(Web3.HTTPProvider(provider, request_kwargs={'timeout': 60})) pos = str(remove_0x_prefix(i)).rjust(64, '0') key = remove_0x_prefix(k).rjust(64, '0').lower() storage_key = to_hex(web3.sha3(hexstr=key + pos)) return storage_key, to_int( web3.eth.getStorageAt(contractaddress, storage_key))
def getstoragepos(i, k): #pos = str(i).rjust(64, '0') pos = getstoragekey(i, k) #print(pos) key = str(remove_0x_prefix(pos)).rjust(64, '0').lower() storage_key = to_hex(Web3auto.sha3(hexstr=key)) return storage_key
def create_account_console(logger: Logger, network: str): """Creates an Ethereum account and echoes the details to console.""" acc = Account.create() private_key = to_hex(acc.privateKey) if private_key.startswith("0x"): # Looks like this behaves differently in different versions, # we assume no 0x prefix for private key to distinguish it from addresses # and hashes private_key = private_key[2:] logger.info("Account address: %s", acc.address) logger.info("Account private key: %s", private_key) config = CONFIG_FILE_TEMPLATE.format(private_key=private_key, network=network, address=acc.address) config_file_name = "myconfig.ini" print() print("Create a file {}{}{} and paste in the following content: {}{}{}". format(colorama.Fore.LIGHTBLUE_EX, config_file_name, colorama.Fore.RESET, colorama.Fore.LIGHTBLACK_EX, config, colorama.Fore.RESET)) print() print("After this you can run {}sto --config-file={} diagnose{}".format( colorama.Fore.LIGHTBLUE_EX, config_file_name, colorama.Fore.RESET))
def _maybe_run_callbacks(self, latest_block): """ Run the callbacks if there is at least one new block. The callbacks are executed only if there is a new block, otherwise the filters may try to poll for an inexisting block number and the Ethereum client can return an JSON-RPC error. """ assert self.known_block_number is not None, 'known_block_number not set' latest_block_number = latest_block['number'] missed_blocks = latest_block_number - self.known_block_number if missed_blocks < 0: log.critical( 'Block number decreased', chain_id=self.chain_id, known_block_number=self.known_block_number, old_block_number=latest_block['number'], old_gas_limit=latest_block['gasLimit'], old_block_hash=to_hex(latest_block['hash']), ) elif missed_blocks > 0: log_details = dict( known_block_number=self.known_block_number, latest_block_number=latest_block_number, latest_block_hash=to_hex(latest_block['hash']), latest_block_gas_limit=latest_block['gasLimit'], ) if missed_blocks > 1: log_details['num_missed_blocks'] = missed_blocks - 1 log.debug( 'Received new block', **log_details, ) remove = list() for callback in self.callbacks: result = callback(latest_block) if result is REMOVE_CALLBACK: remove.append(callback) for callback in remove: self.callbacks.remove(callback) self.known_block_number = latest_block_number
def to_bytes(primitive=None, hexstr=None, text=None): assert_one_val(primitive, hexstr=hexstr, text=text) if is_boolean(primitive): return b'\x01' if primitive else b'\x00' elif isinstance(primitive, bytes): return primitive elif is_integer(primitive): return to_bytes(hexstr=to_hex(primitive)) elif hexstr is not None: if len(hexstr) % 2: hexstr = '0x0' + remove_0x_prefix(hexstr) return decode_hex(hexstr) elif text is not None: return text.encode('utf-8') raise TypeError("expected an int in first arg, or keyword of hexstr or text")
def first_run(self, known_block_number): """ Blocking call to update the local state, if necessary. """ assert self.callbacks, 'callbacks not set' chain_id = self.chain.network_id latest_block = self.chain.get_block(block_identifier='latest') log.debug( 'Alarm task first run', known_block_number=known_block_number, latest_block_number=latest_block['number'], latest_gas_limit=latest_block['gasLimit'], latest_block_hash=to_hex(latest_block['hash']), ) self.known_block_number = known_block_number self.chain_id = chain_id self._maybe_run_callbacks(latest_block)
def topics(self): arg_topics = tuple(arg.match_values for arg in self.indexed_args) return normalize_topic_list(cons(to_hex(self.event_topic), arg_topics))
def _encode(self, value): if is_dynamic_sized_type(self.arg_type): return to_hex(keccak(encode_single_packed(self.arg_type, value))) else: return to_hex(encode_single(self.arg_type, value))
def handle_contract_send_channelsettle( self, raiden: RaidenService, channel_settle_event: ContractSendChannelSettle, ): chain_id = raiden.chain.network_id token_network_identifier = channel_settle_event.token_network_identifier channel_identifier = channel_settle_event.channel_identifier payment_channel: PaymentChannel = raiden.chain.payment_channel( token_network_address=channel_settle_event.token_network_identifier, channel_id=channel_settle_event.channel_identifier, ) token_network_proxy: TokenNetwork = payment_channel.token_network participants_details = token_network_proxy.detail_participants( participant1=payment_channel.participant1, participant2=payment_channel.participant2, channel_identifier=channel_settle_event.channel_identifier, ) our_details = participants_details.our_details partner_details = participants_details.partner_details log_details = { 'chain_id': chain_id, 'token_network_identifier': token_network_identifier, 'channel_identifier': channel_identifier, 'node': pex(raiden.address), 'partner': to_checksum_address(partner_details.address), 'our_deposit': our_details.deposit, 'our_withdrawn': our_details.withdrawn, 'our_is_closer': our_details.is_closer, 'our_balance_hash': to_hex(our_details.balance_hash), 'our_nonce': our_details.nonce, 'our_locksroot': to_hex(our_details.locksroot), 'our_locked_amount': our_details.locked_amount, 'partner_deposit': partner_details.deposit, 'partner_withdrawn': partner_details.withdrawn, 'partner_is_closer': partner_details.is_closer, 'partner_balance_hash': to_hex(partner_details.balance_hash), 'partner_nonce': partner_details.nonce, 'partner_locksroot': to_hex(partner_details.locksroot), 'partner_locked_amount': partner_details.locked_amount, } if our_details.balance_hash != EMPTY_HASH: event_record = get_event_with_balance_proof_by_balance_hash( storage=raiden.wal.storage, chain_id=chain_id, token_network_identifier=token_network_identifier, channel_identifier=channel_identifier, balance_hash=our_details.balance_hash, ) if event_record.data is None: log.critical( 'our balance proof not found', **log_details, ) raise RaidenUnrecoverableError( 'Our balance proof could not be found in the database', ) our_balance_proof = event_record.data.balance_proof our_transferred_amount = our_balance_proof.transferred_amount our_locked_amount = our_balance_proof.locked_amount our_locksroot = our_balance_proof.locksroot else: our_transferred_amount = 0 our_locked_amount = 0 our_locksroot = EMPTY_HASH if partner_details.balance_hash != EMPTY_HASH: state_change_record = get_state_change_with_balance_proof_by_balance_hash( storage=raiden.wal.storage, chain_id=chain_id, token_network_identifier=token_network_identifier, channel_identifier=channel_identifier, balance_hash=partner_details.balance_hash, sender=participants_details.partner_details.address, ) if state_change_record.data is None: log.critical( 'partner balance proof not found', **log_details, ) raise RaidenUnrecoverableError( 'Partner balance proof could not be found in the database', ) partner_balance_proof = state_change_record.data.balance_proof partner_transferred_amount = partner_balance_proof.transferred_amount partner_locked_amount = partner_balance_proof.locked_amount partner_locksroot = partner_balance_proof.locksroot else: partner_transferred_amount = 0 partner_locked_amount = 0 partner_locksroot = EMPTY_HASH payment_channel.settle( our_transferred_amount, our_locked_amount, our_locksroot, partner_transferred_amount, partner_locked_amount, partner_locksroot, )
from eth_utils import denoms, to_hex from raiden.constants import Environment INITIAL_PORT = 38647 CACHE_TTL = 60 GAS_LIMIT = 10 * 10**6 GAS_LIMIT_HEX = to_hex(GAS_LIMIT) GAS_PRICE = denoms.shannon * 20 # pylint: disable=no-member DEFAULT_TRANSPORT_RETRIES_BEFORE_BACKOFF = 5 DEFAULT_TRANSPORT_THROTTLE_CAPACITY = 10. DEFAULT_TRANSPORT_THROTTLE_FILL_RATE = 10. DEFAULT_TRANSPORT_UDP_RETRY_INTERVAL = 1. # matrix gets spammed with the default retry-interval of 1s, wait a little more DEFAULT_TRANSPORT_MATRIX_RETRY_INTERVAL = 5. DEFAULT_MATRIX_KNOWN_SERVERS = { Environment.PRODUCTION: ( "https://raw.githubusercontent.com/raiden-network/raiden-transport" "/master/known_servers.main.yaml" ), Environment.DEVELOPMENT: ( "https://raw.githubusercontent.com/raiden-network/raiden-transport" "/master/known_servers.test.yaml" ), } DEFAULT_REVEAL_TIMEOUT = 50 DEFAULT_SETTLE_TIMEOUT = 500 DEFAULT_RETRY_TIMEOUT = 0.5
def to_hex_with_size(value, bit_size): """ Converts a value to hex with given bit_size: """ return pad_hex(to_hex(value), bit_size)