def queue_answer_swap_challenge(self, challenge: Challenge, token_pair, balance_at_start_of_eon, tx_trail, allotment_chain, membership_chain, values, l_r, deltas, tx_set_root, tx_chain, passive_checksum, passive_amount, passive_marker): return self.queue_transaction_by_owner( transaction=self.contract.functions. answerSwapChallengeWithProofOfExclusiveBalanceAllotment( [add_0x_prefix(token_pair[0]), add_0x_prefix(token_pair[1])], add_0x_prefix(challenge.wallet.address), tx_trail, allotment_chain, membership_chain, tx_chain, values, [l_r, deltas, [passive_amount, passive_marker]], balance_at_start_of_eon, [ tx_set_root, passive_checksum, crypto.uint256(0) # always zero ]), tag=challenge.tag(tx_trail))
def fulfill_access_secret_store_condition(event, agreement_id, did, service_agreement, consumer_address, publisher_account): """ Fulfill the access condition. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param consumer_address: ethereum account address of consumer, hex str :param publisher_account: Account instance of the publisher """ logger.debug(f"release reward after event {event}.") name_to_parameter = { param.name: param for param in service_agreement.condition_by_name['accessSecretStore'].parameters } document_id = add_0x_prefix(name_to_parameter['_documentId'].value) asset_id = add_0x_prefix(did_to_id(did)) assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.' try: tx_hash = Keeper.get_instance().access_secret_store_condition.fulfill( agreement_id, document_id, consumer_address, publisher_account) process_tx_receipt( tx_hash, Keeper.get_instance().access_secret_store_condition. FULFILLED_EVENT, 'AccessSecretStoreCondition.Fulfilled') except Exception as e: # logger.error(f'Error when calling grantAccess condition function: {e}') raise e
def check_proof_of_transition_agreement(self, token_address, holder, trail_identifier, eon_number, tx_set_root, deltas, attester, r, s, v, block_identifier='latest'): return self.contract\ .functions\ .verifyProofOfActiveStateUpdateAgreement( add_0x_prefix(token_address), add_0x_prefix(holder), trail_identifier, eon_number, tx_set_root, deltas, add_0x_prefix(attester), r, s, v)\ .call(block_identifier=block_identifier)
def issue_delivery_challenge(self, token_address, wallet, sender, nonce, sender_tx_recipient_trails, chain, tx_set_root, deltas, amount, r, s, v): wallet = add_0x_prefix(wallet) sender = add_0x_prefix(sender) method = self.contract\ .functions\ .challengeTransferDeliveryWithProofOfActiveStateUpdateAgreement( add_0x_prefix(token_address), [sender, wallet], [nonce, amount], sender_tx_recipient_trails, chain, deltas, [ r, s, tx_set_root, ], v) gas_cost = method.estimateGas({ 'from': wallet, 'value': self.get_challenge_min_gas_cost() * 10000000 }) return method.transact({ 'from': wallet, 'value': self.get_challenge_min_gas_cost() * gas_cost, 'gasPrice': self.get_challenge_min_gas_cost() })
def parse_BIP122_uri(blockchain_uri: URI) -> Tuple[str, str, str]: match = re.match(BIP122_URL_REGEX, blockchain_uri) if match is None: raise ValueError(f"Invalid URI format: '{blockchain_uri}'") chain_id, resource_type, resource_hash = match.groups() return (add_0x_prefix(chain_id), resource_type, add_0x_prefix(resource_hash))
def issue_state_update_challenge_empty(self, token_address, wallet, trail_identifier, tx_set_root, deltas, r, s, v): method = self.contract\ .functions\ .challengeStateUpdateWithProofOfActiveStateUpdateAgreement( add_0x_prefix(token_address), tx_set_root, trail_identifier, deltas, r, s, v) gas_cost = method.estimateGas({ 'from': add_0x_prefix(wallet), 'value': self.get_challenge_min_gas_cost() * 10000000 }) return method.transact({ 'from': add_0x_prefix(wallet), 'value': self.get_challenge_min_gas_cost() * (gas_cost + 25), 'gasPrice': self.get_challenge_min_gas_cost() })
def to_representation(self, wallet): return { 'authorization': None, 'address': add_0x_prefix(wallet.address), 'token': add_0x_prefix(wallet.token.address), 'tos_signature': None, }
def withdraw(self, token_address, wallet, active_state_checksum, trail, allotment_chain, membership_chain, values, exclusive_allotment_interval, withdrawal_amount, passive_checksum, passive_amount, passive_marker): return self.contract\ .functions\ .requestWithdrawal( add_0x_prefix(token_address), [ active_state_checksum, passive_checksum ], trail, allotment_chain, membership_chain, values, [ exclusive_allotment_interval, [passive_amount, passive_marker] ], withdrawal_amount )\ .transact({ 'from': add_0x_prefix(wallet), 'value': 100100 * self.get_challenge_min_gas_cost(), 'gasPrice': self.get_challenge_min_gas_cost()})
def test_eth_sign(web3, skip_if_testrpc): skip_if_testrpc(web3) private_key_hex = '0x5e95384d8050109aab08c1922d3c230739bc16976553c317e5d0b87b59371f2a' private_key = decode_hex(private_key_hex) # This imports the private key into the running geth instance and unlocks # the account so that it can sign things. # `0xa5df35f30ba0ce878b1061ae086289adff3ba1e0` address = web3.personal.importRawKey(private_key, "password") web3.personal.unlockAccount(address, "password") assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address) assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0' # the data to be signed data = b'1234567890abcdefghijklmnopqrstuvwxyz' # the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3` data_hash = web3.sha3(data, encoding=None) data_hash_bytes = decode_hex(data_hash) assert force_bytes(data_hash) == sha3(data) priv_key = PrivateKey(flags=ALL_FLAGS) priv_key.set_raw_privkey(private_key) # sanit check the extract_ecdsa_signer function works as expected. vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=sha3_256) vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig) vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id)) vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full)) assert vector_address == address # Now have geth sign some data. signature_hex = web3.eth.sign(address, data) signature_bytes = decode_hex(signature_hex) actual_signer = extract_ecdsa_signer(data_hash_bytes, signature_bytes) assert actual_signer == address # Verify the signature against the public key derived from the # original private key. It fails. rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) recoverable_signature = priv_key.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ) signature = priv_key.ecdsa_recoverable_convert(recoverable_signature) is_valid = priv_key.pubkey.ecdsa_verify( msg=data, raw_sig=signature, digest=sha3_256, ) assert is_valid
def generate_nft_holder_condition_id(self, keeper, agreement_id, asset_id, holder_address, number_nfts): _hash = add_0x_prefix( keeper.nft_holder_condition.hash_values(asset_id, holder_address, number_nfts).hex()) return add_0x_prefix( keeper.nft_holder_condition.contract.functions.generateId( agreement_id, _hash).call().hex())
def generate_compute_condition_id(self, keeper, agreement_id, asset_id, consumer_address): _hash = add_0x_prefix( keeper.compute_execution_condition.hash_values( asset_id, consumer_address).hex()) return add_0x_prefix( keeper.compute_execution_condition.contract.functions.generateId( agreement_id, _hash).call().hex())
def queue_slash_withdrawal(self, token_address, wallet_address, eon_number, available, r, s, v, tag): return self.queue_transaction_by_owner( transaction=self.contract.functions. slashWithdrawalWithProofOfMinimumAvailableBalance( add_0x_prefix(token_address), add_0x_prefix(wallet_address), [eon_number, available], [r, s], v), tag=tag)
def generate_transfer_did_condition_id(self, keeper, agreement_id, asset_id, receiver_address): _hash = add_0x_prefix( keeper.transfer_did_condition.hash_values(asset_id, receiver_address).hex()) return add_0x_prefix( keeper.transfer_did_condition.contract.functions.generateId( agreement_id, _hash).call().hex())
def get_client_contract_state_variables(self, token_address, member, block_identifier='latest'): return self.contract\ .functions\ .getClientContractStateVariables(add_0x_prefix(token_address), add_0x_prefix(member))\ .call(block_identifier=block_identifier)
def post(self, redis_conn=None): """ Creates a new form application """ eth_address = api.payload['ethAddress'] eth_address = eth_utils.to_normalized_address(eth_address) if not eth_address: return {}, 400 try: user_details = json.loads( redis_conn.hget('adabdha:users', eth_address)) except json.JSONDecodeError: return {}, 404 if not user_details: return user_details, 404 if not api.payload['formData']: return {}, 400 _form_data = json.loads(api.payload['formData']) serialized_form_data = json.dumps(_form_data, separators=(',', ':')) _form_data.update({ 'uuid': api.payload['uuid'] }) # because we want to store the UUID information in local cache _form_data.update({ 'status': -1 }) # because we want to store the UUID information in local cache _form_data.update({'userEthAddress': eth_address}) hashed_formdata = eth_utils.keccak(text=serialized_form_data).hex() hashed_formdata = eth_utils.add_0x_prefix(hashed_formdata) hashed_uuid = eth_utils.add_0x_prefix( eth_utils.keccak(text=api.payload['uuid']).hex()) redis_conn.hset( 'adabdha:forms', hashed_uuid, json.dumps(_form_data, separators=(',', ':')).encode('utf-8')) # Add to main contract update_formdata_params = dict(uuidHash=hashed_uuid, ethAddress=eth_address, formdataHash=hashed_formdata) try: tx = main_contract_instance.submitFormData( **update_formdata_params) print('Updated user form data on contract with tx: ', tx[0]['txHash']) except Exception as e: print('Exception trying to update user form data on Contract ', update_formdata_params, e) return {}, 400 else: redis_conn.zadd(f'adabdha:pendingUserForms:{eth_address}', {hashed_uuid: int(time.time())}) return_struct = { 'txHash': tx[0]['txHash'], 'contractAddress': settings['MAIN_CONTRACT'], 'methodName': 'submitFormData' } return return_struct, 201
def parse_BIP122_uri(blockchain_uri): match = re.match(BIP122_URL_REGEX, blockchain_uri) if match is None: raise ValueError("Invalid URI format: '{0}'".format(blockchain_uri)) chain_id, resource_type, resource_hash = match.groups() return ( add_0x_prefix(chain_id), resource_type, add_0x_prefix(resource_hash), )
def generate_lock_condition_id(self, keeper, agreement_id, asset_id, escrow_condition_address, token_address, amounts, receivers): _hash = add_0x_prefix( keeper.lock_payment_condition.hash_values( asset_id, escrow_condition_address, token_address, amounts, receivers).hex()) return add_0x_prefix( keeper.lock_payment_condition.contract.functions.generateId( agreement_id, _hash).call().hex())
def get_challenge_record(self, token_address, recipient, sender, block_identifier='latest') -> ChallengeEntry: on_chain_record = self.contract\ .functions\ .getChallenge(add_0x_prefix(token_address), add_0x_prefix(sender), add_0x_prefix(recipient))\ .call(block_identifier=block_identifier) return ChallengeEntry(on_chain_record)
def convert_to_bytes(did): if isinstance(did, str): if re.match('^[0x]?[0-9A-Za-z]+$', did): return Web3.toBytes(hexstr=add_0x_prefix(did)) else: return Web3.toBytes(hexstr=add_0x_prefix(did_to_id(did))) elif isinstance(did, bytes): return did else: raise ValueError(f'The id {did} is not in a valid format.')
def generate_access_proof_condition_id(self, keeper, agreement_id, asset_id, consumer_address): keyhash = self.get_key_hash() provider_address = self.get_provider_babyjub_key() _hash = add_0x_prefix( keeper.access_proof_condition.hash_values(keyhash, consumer_address, provider_address).hex()) return add_0x_prefix( keeper.access_proof_condition.contract.functions.generateId( agreement_id, _hash).call().hex())
def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account, publisher_address, condition_ids, escrow_condition_id): """ Refund the reward to the publisher address. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the consumer :param publisher_address: ethereum account address of publisher, hex str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :param escrow_condition_id: hex str the id of escrow reward condition at this `agreement_id` """ logger.debug( f"trigger refund (agreement {agreement_id}) after event {event}.") if Keeper.get_instance().condition_manager.get_condition_state( escrow_condition_id) > 1: logger.debug( f'escrow payment condition already fulfilled/aborted: ' f'agreementId={agreement_id}, escrow reward conditionId={escrow_condition_id},' f' publisher={publisher_address}') return access_id, lock_id = condition_ids[:2] name_to_parameter = { param.name: param for param in service_agreement.condition_by_name['escrowPayment'].parameters } document_id = add_0x_prefix(name_to_parameter['_documentId'].value) asset_id = add_0x_prefix(did_to_id(did)) did_owner = Keeper.get_instance( ).agreement_manager.get_agreement_did_owner(agreement_id) assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.' assert price == service_agreement.get_price(), 'price mismatch.' try: escrow_condition = Keeper.get_instance().escrow_payment_condition tx_hash = escrow_condition.fulfill( agreement_id, price, Web3Provider.get_web3().toChecksumAddress(did_owner), consumer_account.address, lock_id, access_id, consumer_account) process_tx_receipt( tx_hash, getattr(escrow_condition.contract.events, escrow_condition.FULFILLED_EVENT)(), 'EscrowReward.Fulfilled') except Exception as e: logger.error( f'Error when doing escrow_payment_condition.fulfills (agreementId {agreement_id}): {e}', exc_info=1) raise e
def get_confirmed_withdrawable_amount(self, token_address, wallet_address, block_identifier='latest'): amount = self.contract \ .functions \ .confirmWithdrawal( add_0x_prefix(token_address), add_0x_prefix(wallet_address) ) \ .call(block_identifier=block_identifier) return amount
def confirm_withdrawals(self, token_address, wallet_address): txid = self.contract \ .functions \ .confirmWithdrawal( add_0x_prefix(token_address), add_0x_prefix(wallet_address) ) \ .transact({ 'from': add_0x_prefix(wallet_address), 'gasPrice': self.get_challenge_min_gas_cost()}) return txid
def generate_transfer_nft_condition_id(self, keeper, agreement_id, asset_id, nft_holder, receiver_address, number_nfts, lock_cond_id): _hash = add_0x_prefix( keeper.transfer_nft_condition.hash_values(asset_id, nft_holder, receiver_address, number_nfts, lock_cond_id).hex()) return add_0x_prefix( keeper.transfer_nft_condition.contract.functions.generateId( agreement_id, _hash).call().hex())
def _normalize_combined_json_contract_data(contract_data): if 'metadata' in contract_data: yield 'metadata', _normalize_contract_metadata(contract_data['metadata']) if 'bin' in contract_data: yield 'bytecode', add_0x_prefix(contract_data['bin']) if 'bin-runtime' in contract_data: yield 'bytecode_runtime', add_0x_prefix(contract_data['bin-runtime']) if 'abi' in contract_data: yield 'abi', _load_json_if_string(contract_data['abi']) if 'userdoc' in contract_data: yield 'userdoc', _load_json_if_string(contract_data['userdoc']) if 'devdoc' in contract_data: yield 'devdoc', _load_json_if_string(contract_data['devdoc'])
def normalize_combined_json_contract_data(contract_data): if 'metadata' in contract_data: yield 'metadata', normalize_contract_metadata(contract_data['metadata']) if 'bin' in contract_data: yield 'bytecode', add_0x_prefix(contract_data['bin']) if 'bin-runtime' in contract_data: yield 'bytecode_runtime', add_0x_prefix(contract_data['bin-runtime']) if 'abi' in contract_data: yield 'abi', load_json_if_string(contract_data['abi']) if 'userdoc' in contract_data: yield 'userdoc', load_json_if_string(contract_data['userdoc']) if 'devdoc' in contract_data: yield 'devdoc', load_json_if_string(contract_data['devdoc'])
def queue_answer_state_update_challenge(self, challenge: Challenge, allotment_chain, membership_chain, values, l_r, tx_set_root, deltas, r, s, v, passive_checksum, passive_amount, passive_marker): return self.queue_transaction_by_owner( transaction=self.contract.functions.answerStateUpdateChallenge( add_0x_prefix(challenge.wallet.token.address), add_0x_prefix(challenge.wallet.address), allotment_chain, membership_chain, values, [l_r, deltas, [passive_amount, passive_marker]], [r[0], s[0], r[1], s[1], tx_set_root, passive_checksum], v), tag=challenge.tag(0))
def queue_answer_delivery_challenge(self, challenge: Challenge, tx_trail, allotment_chain, membership_chain, values, l_r, deltas, tx_set_root, tx_chain, passive_checksum, passive_amount, passive_marker): return self.queue_transaction_by_owner( transaction=self.contract.functions. answerTransferDeliveryChallengeWithProofOfActiveStateUpdateAgreement( add_0x_prefix(challenge.wallet.token.address), [ add_0x_prefix(challenge.wallet.address), add_0x_prefix(challenge.recipient.address) ], tx_trail, allotment_chain, membership_chain, values, [l_r, deltas, [passive_amount, passive_marker]], [tx_set_root, passive_checksum], tx_chain), tag=challenge.tag(tx_trail))
def to_hex(value=None, hexstr=None, text=None): """ Auto converts any supported value into it's hex representation. Trims leading zeros, as defined in: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding """ assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return add_0x_prefix(hexstr.lower()) if text is not None: return encode_hex(text.encode('utf-8')) if is_boolean(value): return "0x1" if value else "0x0" if is_dict(value): return encode_hex(json.dumps(value, sort_keys=True)) if isinstance(value, bytes): return encode_hex(value) elif is_string(value): return to_hex(text=value) if is_integer(value): return hex(value) raise TypeError( "Unsupported type: '{0}'. Must be one of Boolean, Dictionary, String, " "or Integer.".format(repr(type(value))) )
def sign_for_delivery_as_owner(self, transaction: EthereumTransaction, gas_price: int): transaction_dictionary = { 'chainId': transaction.chain_id, 'from': add_0x_prefix(transaction.from_address), 'to': add_0x_prefix(transaction.to_address), 'gas': 2 * transaction.gas, 'gasPrice': gas_price, 'data': add_0x_prefix(transaction.data), 'value': int(transaction.value), 'nonce': transaction.nonce } logger.info('Signing TX Dict: {}'.format(transaction_dictionary)) return self.web3.eth.account.signTransaction( transaction_dict=transaction_dictionary, private_key=settings.HUB_OWNER_ACCOUNT_KEY)
def address_in_keystore(self, address: Optional[AddressHex]) -> bool: if address is None: return False address = add_0x_prefix(address) return address.lower() in self.accounts
def get_privkey(self, address: AddressHex, password: str = None) -> str: """Find the keystore file for an account, unlock it and get the private key Args: address(str): The Ethereum address for which to find the keyfile in the system password(str): Mostly for testing purposes. A password can be provided as the function argument here. If it's not then the user is interactively queried for one. Returns str: The private key associated with the address """ address = add_0x_prefix(address).lower() if not self.address_in_keystore(address): raise ValueError('Keystore file not found for %s' % address) with open(self.accounts[address]) as data_file: data = json.load(data_file) # Since file was found prompt for a password if not already given if password is None: password = getpass.getpass( f'Enter the password to unlock {to_checksum_address(address)}: ', ) acc = Account(data, password, self.accounts[address]) return acc.privkey
def _encode_abi(cls, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), ) ) try: encoded_arguments = encode_abi( argument_types, force_obj_to_bytes(arguments), ) except EncodingError as e: raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type: {0}".format(str(e)) ) if data: return add_0x_prefix( force_bytes(remove_0x_prefix(data)) + force_bytes(remove_0x_prefix(encode_hex(encoded_arguments))) ) else: return encode_hex(encoded_arguments)
def to_hex(value=None, hexstr=None, text=None): """ Auto converts any supported value into it's hex representation. Trims leading zeros, as defined in: https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding """ assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return add_0x_prefix(hexstr.lower()) if text is not None: return encode_hex(text.encode('utf-8')) if is_boolean(value): return "0x1" if value else "0x0" if is_dict(value): return encode_hex(json.dumps(value, sort_keys=True)) if isinstance(value, bytes): return encode_hex(value) elif is_string(value): return to_hex(text=value) if is_integer(value): return hex(value) raise TypeError( "Unsupported type: '{0}'. Must be one of Boolean, Dictionary, String, " "or Integer.".format(repr(type(value))))
def _encode_abi(cls, abi, arguments, data=None): argument_types = get_abi_input_types(abi) if not check_if_arguments_can_be_encoded(abi, arguments, {}): raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type. Expected types are: {0}".format( ', '.join(argument_types), )) try: encoded_arguments = encode_abi( argument_types, force_obj_to_bytes(arguments), ) except EncodingError as e: raise TypeError( "One or more arguments could not be encoded to the necessary " "ABI type: {0}".format(str(e))) if data: return add_0x_prefix( force_bytes(remove_0x_prefix(data)) + force_bytes(remove_0x_prefix(encode_hex(encoded_arguments)))) else: return encode_hex(encoded_arguments)
def encode_transaction_data(w3: "Web3", fn_identifier: Union[str, Type[FallbackFn], Type[ReceiveFn]], contract_abi: Optional[ABI] = None, fn_abi: Optional[ABIFunction] = None, args: Optional[Sequence[Any]] = None, kwargs: Optional[Any] = None) -> HexStr: if fn_identifier is FallbackFn: fn_abi, fn_selector, fn_arguments = get_fallback_function_info( contract_abi, fn_abi) elif fn_identifier is ReceiveFn: fn_abi, fn_selector, fn_arguments = get_receive_function_info( contract_abi, fn_abi) elif is_text(fn_identifier): fn_abi, fn_selector, fn_arguments = get_function_info( # type ignored b/c fn_id here is always str b/c FallbackFn is handled above fn_identifier, w3.codec, contract_abi, fn_abi, args, kwargs, # type: ignore ) else: raise TypeError("Unsupported function identifier") return add_0x_prefix(encode_abi(w3, fn_abi, fn_arguments, fn_selector))
def test_trace_replay_block_with_transactions(self, web3, block_with_txn, parity_fixture_data): trace = web3.parity.traceReplayBlockTransactions(block_with_txn['number']) assert len(trace) > 0 trace_0_action = trace[0]['trace'][0]['action'] assert trace_0_action['from'] == add_0x_prefix(parity_fixture_data['coinbase'])
def input_address_formatter(addr): iban = Iban(addr) if iban.isValid() and iban.isDirect(): return add_0x_prefix(iban.address()) elif is_address(addr): return to_normalized_address(addr) raise ValueError("invalid address")
def _encode_constructor_data(cls, args=None, kwargs=None): constructor_abi = get_constructor_abi(cls.abi) if constructor_abi: if args is None: args = tuple() if kwargs is None: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) deploy_data = add_0x_prefix( cls._encode_abi(constructor_abi, arguments, data=cls.bytecode) ) else: deploy_data = add_0x_prefix(cls.bytecode) return deploy_data
def test_get_chain_definition(web3): block_0 = web3.eth.getBlock(0) chain_definition = get_chain_definition(web3) assert remove_0x_prefix(block_0['hash']) in chain_definition assert '0x' not in chain_definition _, _, anchor_block_hash = chain_definition.rpartition('/') anchor_block = web3.eth.getBlock(anchor_block_hash) assert anchor_block['hash'] == add_0x_prefix(anchor_block_hash)
def encode_transaction_data(abi, web3, fn_identifier, args=None, kwargs=None): if fn_identifier is FallbackFn: fn_abi, fn_selector, fn_arguments = get_fallback_function_info(abi) elif is_text(fn_identifier): fn_abi, fn_selector, fn_arguments = get_function_info( abi, fn_identifier, args, kwargs ) else: raise TypeError("Unsupported function identifier") return add_0x_prefix(encode_abi(web3, fn_abi, fn_arguments, fn_selector))
def normalize_return_type(data_type, data_value): try: base, sub, arrlist = data_type except ValueError: base, sub, arrlist = process_type(data_type) if arrlist: sub_type = (base, sub, arrlist[:-1]) return [normalize_return_type(sub_type, sub_value) for sub_value in data_value] elif base == 'address': return add_0x_prefix(data_value) else: return data_value
def address(self): """ Should be called to get client direct address @method address @returns {String} client direct address """ if self.isDirect(): base36 = self._iban[4:] asInt = int(base36, 36) return add_0x_prefix(pad_left_hex(baseN(asInt, 16), 20)) return ""
def get_constructor_arguments(contract: Contract, args: Optional[list]=None, kwargs: Optional[dict]=None): """Get constructor arguments for Etherscan verify. https://etherscanio.freshdesk.com/support/solutions/articles/16000053599-contract-verification-constructor-arguments """ constructor_abi = get_constructor_abi(contract.abi) if args is not None: return contract._encode_abi(constructor_abi, args)[2:] # No 0x else: constructor_abi = get_constructor_abi(contract.abi) arguments = merge_args_and_kwargs(constructor_abi, [], kwargs) deploy_data = add_0x_prefix( contract._encode_abi(constructor_abi, arguments) ) return deploy_data
def _encode_data_in_transaction(self, *args, **kwargs): constructor_abi = get_constructor_abi(self.abi) if constructor_abi: if not args: args = tuple() if not kwargs: kwargs = {} arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) data = add_0x_prefix( encode_abi(self.web3, constructor_abi, arguments, data=self.bytecode) ) else: data = to_hex(self.bytecode) return data
def extract_ecdsa_signer(msg_hash, signature): msg_hash_bytes = decode_hex(msg_hash) if msg_hash.startswith(b'0x') else msg_hash signature_bytes = decode_hex(signature) if signature.startswith(b'0x') else signature pk = PublicKey(flags=ALL_FLAGS) rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) pk.public_key = pk.ecdsa_recover( msg_hash_bytes, pk.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ), raw=True, ) pk_serialized = pk.serialize(compressed=False) address = add_0x_prefix(sha3(encode_pubkey(pk_serialized, 'bin')[1:])[-40:]) return address
def __init__(self, keystore_path: str = None): self.keystore_path = keystore_path self.accounts = {} if self.keystore_path is None: self.keystore_path = _find_keystoredir() if self.keystore_path is not None: try: files = os.listdir(self.keystore_path) except OSError as ex: msg = 'Unable to list the specified directory' log.error('OsError', msg=msg, path=self.keystore_path, ex=ex) return for f in files: fullpath = os.path.join(self.keystore_path, f) if os.path.isfile(fullpath): try: with open(fullpath) as data_file: data = json.load(data_file) address = add_0x_prefix(str(data['address']).lower()) self.accounts[address] = str(fullpath) except ( IOError, json.JSONDecodeError, KeyError, OSError, UnicodeDecodeError, ) as ex: # Invalid file - skip if f.startswith('UTC--'): # Should be a valid account file - warn user msg = 'Invalid account file' if isinstance(ex, IOError) or isinstance(ex, OSError): msg = 'Can not read account file (errno=%s)' % ex.errno if isinstance(ex, json.decoder.JSONDecodeError): msg = 'The account file is not valid JSON format' log.warning(msg, path=fullpath, ex=ex)
def soliditySha3(cls, abi_types, values): """ Executes sha3 (keccak256) exactly as Solidity does. Takes list of abi_types as inputs -- `[uint24, int8[], bool]` and list of corresponding values -- `[20, [-1, 5, 0], True]` """ if len(abi_types) != len(values): raise ValueError( "Length mismatch between provided abi types and values. Got " "{0} types and {1} values.".format(len(abi_types), len(values)) ) if isinstance(cls, type): w3 = None else: w3 = cls normalized_values = map_abi_data([abi_ens_resolver(w3)], abi_types, values) hex_string = add_0x_prefix(''.join( remove_0x_prefix(hex_encode_abi_type(abi_type, value)) for abi_type, value in zip(abi_types, normalized_values) )) return cls.sha3(hexstr=hex_string)
def test_trace_replay_transaction(self, web3, parity_fixture_data): trace = web3.parity.traceReplayTransaction(parity_fixture_data['mined_txn_hash']) assert trace['stateDiff'] is None assert trace['vmTrace'] is None assert trace['trace'][0]['action']['from'] == add_0x_prefix(parity_fixture_data['coinbase'])
def test_trace_transaction(self, web3, parity_fixture_data): trace = web3.parity.traceTransaction(parity_fixture_data['mined_txn_hash']) assert trace[0]['action']['from'] == add_0x_prefix(parity_fixture_data['coinbase'])
def test_trace_filter(self, web3, txn_filter_params, parity_fixture_data): trace = web3.parity.traceFilter(txn_filter_params) assert isinstance(trace, list) assert trace[0]['action']['from'] == add_0x_prefix(parity_fixture_data['coinbase'])
def data_encoder(data: bytes, length: int = 0) -> str: data = remove_0x_prefix(encode_hex(data)) return add_0x_prefix( data.rjust(length * 2, b'0').decode(), )
def encode_transaction_data(abi, web3, fn_name, args=None, kwargs=None): fn_abi, fn_selector, fn_arguments = get_function_info( abi, fn_name, args, kwargs, ) return add_0x_prefix(encode_abi(web3, fn_abi, fn_arguments, fn_selector))
def insert_link_value(bytecode, value, offset): return add_0x_prefix(''.join(( remove_0x_prefix(bytecode)[:offset], remove_0x_prefix(value), remove_0x_prefix(bytecode)[offset + len(remove_0x_prefix(value)):] )))
def pad_hex(value, bit_size): """ Pads a hex string up to the given bit_size """ value = remove_0x_prefix(value) return add_0x_prefix(value.zfill(int(bit_size / 4)))
def _encode_transaction_data(cls): return add_0x_prefix(encode_abi(cls.web3, cls.abi, cls.arguments, cls.selector))
def _encode_transaction_data(cls, fn_name, args=None, kwargs=None): fn_abi, fn_selector, fn_arguments = cls._get_function_info( fn_name, args, kwargs, ) return add_0x_prefix(cls._encode_abi(fn_abi, fn_arguments, fn_selector))