def test_multi_send_safe_tx(self): owners = [Account.create() for _ in range(2)] owner_addresses = [owner.address for owner in owners] threshold = 1 safe = self.deploy_test_safe( owners=owner_addresses, threshold=threshold, initial_funding_wei=self.w3.toWei(0.1, "ether"), ) safe_contract = safe.get_contract() to = self.multi_send_contract.address value = 0 safe_tx_gas = 600000 base_gas = 200000 # Atomic swap the owner of a Safe new_owner = Account.create() owner_to_remove = owners[-1] prev_owner = owners[-2] owners_expected = [x.address for x in owners[:-1]] + [new_owner.address] new_threshold = threshold + 1 data = HexBytes( safe_contract.functions.addOwnerWithThreshold( new_owner.address, new_threshold).buildTransaction({"gas": 0})["data"]) data_2 = HexBytes( safe_contract.functions.removeOwner( prev_owner.address, owner_to_remove.address, new_threshold).buildTransaction({"gas": 0})["data"]) multisend_txs = [ MultiSendTx(MultiSendOperation.CALL, safe.address, value, d) for d in (data, data_2) ] safe_multisend_data = self.multi_send.build_tx_data(multisend_txs) safe_tx = SafeTx( self.ethereum_client, safe.address, to, 0, safe_multisend_data, SafeOperation.DELEGATE_CALL.value, safe_tx_gas, base_gas, self.gas_price, None, None, safe_nonce=0, ) safe_tx.sign(owners[0].key) self.assertEqual( safe_tx.call(tx_sender_address=self.ethereum_test_account.address), 1) tx_hash, _ = safe_tx.execute( tx_sender_private_key=self.ethereum_test_account.key) self.ethereum_client.get_transaction_receipt(tx_hash, timeout=60) self.assertEqual(safe.retrieve_nonce(), 1) self.assertEqual(safe.retrieve_threshold(), new_threshold) self.assertCountEqual(safe.retrieve_owners(), owners_expected)
def decrypt_file(file_path, password): with open(file_path, 'r') as f: encrypted = f.read() secured_value = Account.decrypt(encrypted, password) return secured_value.decode()
def save_wallet(acct: Account, password: str) -> Account: encrypted: Dict = Account.encrypt(acct.privateKey, password) file_path: str = "%s%s%s%s" % (get_key_file_path(), KEYFILE_PREFIX, acct.address, KEYFILE_POSTFIX) with open(file_path, 'w+') as f: f.write(json.dumps(encrypted)) return acct
def test_notifications_devices_create_with_signatures_view(self): safe_address = Account.create().address safe_contract = SafeContractFactory(address=safe_address) owner_account = Account.create() owner_account_2 = Account.create() self.assertEqual(FirebaseDevice.objects.count(), 0) unique_id = uuid.uuid4() timestamp = int(time.time()) cloud_messaging_token = 'A' * 163 safes = [safe_address] hash_to_sign = calculate_device_registration_hash( timestamp, unique_id, cloud_messaging_token, safes) signatures = [owner_account.signHash(hash_to_sign)['signature'].hex()] data = { 'uuid': unique_id, 'safes': [safe_address], 'cloudMessagingToken': cloud_messaging_token, 'buildNumber': 0, 'bundle': 'company.package.app', 'deviceType': 'WEB', 'version': '2.0.1', 'timestamp': timestamp, 'signatures': signatures, } response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertIn('is not an owner of any of the safes', str(response.data['non_field_errors'])) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) with mock.patch( 'safe_transaction_service.notifications.serializers.get_safe_owners', return_value=[owner_account.address]): response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['uuid'], str(unique_id)) self.assertEqual(FirebaseDevice.objects.count(), 1) self.assertEqual(FirebaseDeviceOwner.objects.count(), 1) self.assertEqual(FirebaseDeviceOwner.objects.first().owner, owner_account.address) # Add another signature signatures.append( owner_account_2.signHash(hash_to_sign)['signature'].hex()) response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertIn('is not an owner of any of the safes', str(response.data['non_field_errors'])) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) with mock.patch( 'safe_transaction_service.notifications.serializers.get_safe_owners', return_value=[owner_account.address, owner_account_2.address]): response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(FirebaseDevice.objects.count(), 1) self.assertCountEqual( FirebaseDeviceOwner.objects.values_list('owner', flat=True), [owner_account.address, owner_account_2.address])
default=LAST_PROXY_FACTORY_CONTRACT, type=check_ethereum_address) parser.add_argument( '--callback-handler', help= 'Use a custom fallback handler. It is not required for Safe Master Copies ' 'with version < 1.1.0', default=LAST_DEFAULT_CALLBACK_HANDLER, type=check_ethereum_address) if __name__ == '__main__': print_formatted_text( pyfiglet.figlet_format('Gnosis Safe Creator')) # Print fancy text args = parser.parse_args() node_url: URI = args.node_url account: LocalAccount = Account.from_key(args.private_key) owners: List[str] = list(set( args.owners)) if args.owners else [account.address] threshold: int = args.threshold if len(owners) < threshold: print_formatted_text( 'Threshold cannot be bigger than the number of unique owners') sys.exit(1) safe_contract_address = args.safe_contract proxy_factory_address = args.proxy_factory callback_handler_address = args.callback_handler ethereum_client = EthereumClient(node_url) account_balance: int = ethereum_client.get_balance(account.address) if not account_balance:
class Eth(Module): account = Account() _default_account: Union[ChecksumAddress, Empty] = empty _default_block: BlockIdentifier = "latest" defaultContractFactory: Type[ Union[Contract, ConciseContract, ContractCaller]] = Contract # noqa: E704,E501 iban = Iban gasPriceStrategy = None def namereg(self) -> NoReturn: raise NotImplementedError() def icapNamereg(self) -> NoReturn: raise NotImplementedError() _protocol_version: Method[Callable[[], str]] = Method( RPC.eth_protocolVersion, mungers=None, ) @property def protocol_version(self) -> str: warnings.warn( "This method has been deprecated in some clients.", category=DeprecationWarning, ) return self._protocol_version() @property def protocolVersion(self) -> str: warnings.warn( 'protocolVersion is deprecated in favor of protocol_version', category=DeprecationWarning, ) return self.protocol_version is_syncing: Method[Callable[[], Union[SyncStatus, bool]]] = Method( RPC.eth_syncing, mungers=None, ) @property def syncing(self) -> Union[SyncStatus, bool]: return self.is_syncing() get_coinbase: Method[Callable[[], ChecksumAddress]] = Method( RPC.eth_coinbase, mungers=None, ) @property def coinbase(self) -> ChecksumAddress: return self.get_coinbase() is_mining: Method[Callable[[], bool]] = Method( RPC.eth_mining, mungers=None, ) @property def mining(self) -> bool: return self.is_mining() get_hashrate: Method[Callable[[], int]] = Method( RPC.eth_hashrate, mungers=None, ) @property def hashrate(self) -> int: return self.get_hashrate() _gas_price: Method[Callable[[], Wei]] = Method( RPC.eth_gasPrice, mungers=None, ) @property def gas_price(self) -> Wei: return self._gas_price() @property def gasPrice(self) -> Wei: warnings.warn( 'gasPrice is deprecated in favor of gas_price', category=DeprecationWarning, ) return self.gas_price get_accounts: Method[Callable[[], Tuple[ChecksumAddress]]] = Method( RPC.eth_accounts, mungers=None, ) @property def accounts(self) -> Tuple[ChecksumAddress]: return self.get_accounts() get_block_number: Method[Callable[[], BlockNumber]] = Method( RPC.eth_blockNumber, mungers=None, ) @property def block_number(self) -> BlockNumber: return self.get_block_number() @property def blockNumber(self) -> BlockNumber: warnings.warn( 'blockNumber is deprecated in favor of block_number', category=DeprecationWarning, ) return self.block_number _chain_id: Method[Callable[[], int]] = Method( RPC.eth_chainId, mungers=None, ) @property def chain_id(self) -> int: return self._chain_id() @property def chainId(self) -> int: warnings.warn( 'chainId is deprecated in favor of chain_id', category=DeprecationWarning, ) return self.chain_id """ property default_account """ @property def default_account(self) -> Union[ChecksumAddress, Empty]: return self._default_account @default_account.setter def default_account(self, account: Union[ChecksumAddress, Empty]) -> None: self._default_account = account @property def defaultAccount(self) -> Union[ChecksumAddress, Empty]: warnings.warn( 'defaultAccount is deprecated in favor of default_account', category=DeprecationWarning, ) return self._default_account @defaultAccount.setter def defaultAccount(self, account: Union[ChecksumAddress, Empty]) -> None: warnings.warn( 'defaultAccount is deprecated in favor of default_account', category=DeprecationWarning, ) self._default_account = account """ property default_block """ @property def default_block(self) -> BlockIdentifier: return self._default_block @default_block.setter def default_block(self, value: BlockIdentifier) -> None: self._default_block = value @property def defaultBlock(self) -> BlockIdentifier: warnings.warn( 'defaultBlock is deprecated in favor of default_block', category=DeprecationWarning, ) return self._default_block @defaultBlock.setter def defaultBlock(self, value: BlockIdentifier) -> None: warnings.warn( 'defaultBlock is deprecated in favor of default_block', category=DeprecationWarning, ) self._default_block = value def block_id_munger( self, account: Union[Address, ChecksumAddress, ENS], block_identifier: Optional[BlockIdentifier] = None ) -> Tuple[Union[Address, ChecksumAddress, ENS], BlockIdentifier]: if block_identifier is None: block_identifier = self.default_block return (account, block_identifier) get_balance: Method[Callable[..., Wei]] = Method( RPC.eth_getBalance, mungers=[block_id_munger], ) def get_storage_at_munger( self, account: Union[Address, ChecksumAddress, ENS], position: int, block_identifier: Optional[BlockIdentifier] = None ) -> Tuple[Union[Address, ChecksumAddress, ENS], int, BlockIdentifier]: if block_identifier is None: block_identifier = self.default_block return (account, position, block_identifier) get_storage_at: Method[Callable[..., HexBytes]] = Method( RPC.eth_getStorageAt, mungers=[get_storage_at_munger], ) def get_proof_munger( self, account: Union[Address, ChecksumAddress, ENS], positions: Sequence[int], block_identifier: Optional[BlockIdentifier] = None ) -> Tuple[Union[Address, ChecksumAddress, ENS], Sequence[int], Optional[BlockIdentifier]]: if block_identifier is None: block_identifier = self.default_block return (account, positions, block_identifier) get_proof: Method[Callable[[ Tuple[Union[Address, ChecksumAddress, ENS], Sequence[int], Optional[BlockIdentifier]] ], MerkleProof]] = Method( RPC.eth_getProof, mungers=[get_proof_munger], ) get_code: Method[Callable[..., HexBytes]] = Method(RPC.eth_getCode, mungers=[block_id_munger]) def get_block_munger( self, block_identifier: BlockIdentifier, full_transactions: bool = False) -> Tuple[BlockIdentifier, bool]: return (block_identifier, full_transactions) """ `eth_getBlockByHash` `eth_getBlockByNumber` """ get_block: Method[Callable[..., BlockData]] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getBlockByNumber, if_hash=RPC.eth_getBlockByHash, if_number=RPC.eth_getBlockByNumber, ), mungers=[get_block_munger], ) """ `eth_getBlockTransactionCountByHash` `eth_getBlockTransactionCountByNumber` """ get_block_transaction_count: Method[Callable[ [BlockIdentifier], int]] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getBlockTransactionCountByNumber, if_hash=RPC.eth_getBlockTransactionCountByHash, if_number=RPC.eth_getBlockTransactionCountByNumber, ), mungers=[default_root_munger]) """ `eth_getUncleCountByBlockHash` `eth_getUncleCountByBlockNumber` """ get_uncle_count: Method[Callable[[BlockIdentifier], int]] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getUncleCountByBlockNumber, if_hash=RPC.eth_getUncleCountByBlockHash, if_number=RPC.eth_getUncleCountByBlockNumber, ), mungers=[default_root_munger]) """ `eth_getUncleByBlockHashAndIndex` `eth_getUncleByBlockNumberAndIndex` """ get_uncle_by_block: Method[Callable[ [BlockIdentifier, int], Uncle]] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getUncleByBlockNumberAndIndex, if_hash=RPC.eth_getUncleByBlockHashAndIndex, if_number=RPC.eth_getUncleByBlockNumberAndIndex, ), mungers=[default_root_munger]) get_transaction: Method[Callable[[_Hash32], TxData]] = Method( RPC.eth_getTransactionByHash, mungers=[default_root_munger]) def getTransactionFromBlock(self, block_identifier: BlockIdentifier, transaction_index: int) -> NoReturn: """ Alias for the method getTransactionByBlock Deprecated to maintain naming consistency with the json-rpc API """ raise DeprecationWarning( "This method has been deprecated as of EIP 1474.") get_transaction_by_block: Method[Callable[ [BlockIdentifier, int], TxData]] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getTransactionByBlockNumberAndIndex, if_hash=RPC.eth_getTransactionByBlockHashAndIndex, if_number=RPC.eth_getTransactionByBlockNumberAndIndex, ), mungers=[default_root_munger]) @deprecated_for("wait_for_transaction_receipt") def waitForTransactionReceipt(self, transaction_hash: _Hash32, timeout: int = 120, poll_latency: float = 0.1) -> TxReceipt: return self.wait_for_transaction_receipt(transaction_hash, timeout, poll_latency) def wait_for_transaction_receipt(self, transaction_hash: _Hash32, timeout: int = 120, poll_latency: float = 0.1) -> TxReceipt: try: return wait_for_transaction_receipt(self.web3, transaction_hash, timeout, poll_latency) except Timeout: raise TimeExhausted( "Transaction {} is not in the chain, after {} seconds".format( to_hex(transaction_hash), timeout, )) get_transaction_receipt: Method[Callable[[_Hash32], TxReceipt]] = Method( RPC.eth_getTransactionReceipt, mungers=[default_root_munger]) get_transaction_count: Method[Callable[..., Nonce]] = Method( RPC.eth_getTransactionCount, mungers=[block_id_munger], ) @deprecated_for("replace_transaction") def replaceTransaction(self, transaction_hash: _Hash32, new_transaction: TxParams) -> HexBytes: return self.replace_transaction(transaction_hash, new_transaction) def replace_transaction(self, transaction_hash: _Hash32, new_transaction: TxParams) -> HexBytes: current_transaction = get_required_transaction(self.web3, transaction_hash) return replace_transaction(self.web3, current_transaction, new_transaction) # todo: Update Any to stricter kwarg checking with TxParams # https://github.com/python/mypy/issues/4441 @deprecated_for("modify_transaction") def modifyTransaction(self, transaction_hash: _Hash32, **transaction_params: Any) -> HexBytes: return self.modify_transaction(transaction_hash, **transaction_params) def modify_transaction(self, transaction_hash: _Hash32, **transaction_params: Any) -> HexBytes: assert_valid_transaction_params(cast(TxParams, transaction_params)) current_transaction = get_required_transaction(self.web3, transaction_hash) current_transaction_params = extract_valid_transaction_params( current_transaction) new_transaction = merge(current_transaction_params, transaction_params) return replace_transaction(self.web3, current_transaction, new_transaction) def send_transaction_munger(self, transaction: TxParams) -> Tuple[TxParams]: # TODO: move to middleware if 'from' not in transaction and is_checksum_address( self.default_account): transaction = assoc(transaction, 'from', self.default_account) # TODO: move gas estimation in middleware if 'gas' not in transaction: transaction = assoc( transaction, 'gas', get_buffered_gas_estimate(self.web3, transaction), ) return (transaction, ) send_transaction: Method[Callable[[TxParams], HexBytes]] = Method( RPC.eth_sendTransaction, mungers=[send_transaction_munger]) send_raw_transaction: Method[Callable[[Union[HexStr, bytes]], HexBytes]] = Method( RPC.eth_sendRawTransaction, mungers=[default_root_munger], ) def sign_munger( self, account: Union[Address, ChecksumAddress, ENS], data: Union[int, bytes] = None, hexstr: HexStr = None, text: str = None ) -> Tuple[Union[Address, ChecksumAddress, ENS], HexStr]: message_hex = to_hex(data, hexstr=hexstr, text=text) return (account, message_hex) sign: Method[Callable[..., HexStr]] = Method( RPC.eth_sign, mungers=[sign_munger], ) sign_transaction: Method[Callable[[TxParams], SignedTx]] = Method( RPC.eth_signTransaction, mungers=[default_root_munger], ) sign_typed_data: Method[Callable[..., HexStr]] = Method( RPC.eth_signTypedData, mungers=[default_root_munger], ) def call_munger( self, transaction: TxParams, block_identifier: Optional[BlockIdentifier] = None, state_override: Optional[CallOverrideParams] = None, ) -> Union[Tuple[TxParams, BlockIdentifier], Tuple[ TxParams, BlockIdentifier, CallOverrideParams]]: # noqa-E501 # TODO: move to middleware if 'from' not in transaction and is_checksum_address( self.default_account): transaction = assoc(transaction, 'from', self.default_account) # TODO: move to middleware if block_identifier is None: block_identifier = self.default_block if state_override is None: return (transaction, block_identifier) else: return (transaction, block_identifier, state_override) call: Method[Callable[..., Union[bytes, bytearray]]] = Method(RPC.eth_call, mungers=[call_munger]) def estimate_gas_munger( self, transaction: TxParams, block_identifier: Optional[BlockIdentifier] = None ) -> Sequence[Union[TxParams, BlockIdentifier]]: if 'from' not in transaction and is_checksum_address( self.default_account): transaction = assoc(transaction, 'from', self.default_account) if block_identifier is None: params: Sequence[Union[TxParams, BlockIdentifier]] = [transaction] else: params = [transaction, block_identifier] return params estimate_gas: Method[Callable[..., Wei]] = Method(RPC.eth_estimateGas, mungers=[estimate_gas_munger]) def filter_munger( self, filter_params: Optional[Union[str, FilterParams]] = None, filter_id: Optional[HexStr] = None ) -> Union[List[FilterParams], List[HexStr], List[str]]: if filter_id and filter_params: raise TypeError( "Ambiguous invocation: provide either a `filter_params` or a `filter_id` argument. " "Both were supplied.") if isinstance(filter_params, dict): return [filter_params] elif is_string(filter_params): if filter_params in ['latest', 'pending']: return [filter_params] else: raise ValueError( "The filter API only accepts the values of `pending` or " "`latest` for string based filters") elif filter_id and not filter_params: return [filter_id] else: raise TypeError( "Must provide either filter_params as a string or " "a valid filter object, or a filter_id as a string " "or hex.") filter: Method[Callable[..., Any]] = Method( method_choice_depends_on_args=select_filter_method( if_new_block_filter=RPC.eth_newBlockFilter, if_new_pending_transaction_filter=RPC. eth_newPendingTransactionFilter, if_new_filter=RPC.eth_newFilter, ), mungers=[filter_munger], ) get_filter_changes: Method[Callable[[HexStr], List[LogReceipt]]] = Method( RPC.eth_getFilterChanges, mungers=[default_root_munger]) get_filter_logs: Method[Callable[[HexStr], List[LogReceipt]]] = Method( RPC.eth_getFilterLogs, mungers=[default_root_munger]) get_logs: Method[Callable[[FilterParams], List[LogReceipt]]] = Method( RPC.eth_getLogs, mungers=[default_root_munger]) submit_hashrate: Method[Callable[[int, _Hash32], bool]] = Method( RPC.eth_submitHashrate, mungers=[default_root_munger], ) submit_work: Method[Callable[[int, _Hash32, _Hash32], bool]] = Method( RPC.eth_submitWork, mungers=[default_root_munger], ) uninstall_filter: Method[Callable[[HexStr], bool]] = Method( RPC.eth_uninstallFilter, mungers=[default_root_munger], ) @overload def contract(self, address: None = None, **kwargs: Any) -> Type[Contract]: ... # noqa: E704,E501 @overload # noqa: F811 def contract(self, address: Union[Address, ChecksumAddress, ENS], **kwargs: Any) -> Contract: ... # noqa: E704,E501 def contract( # noqa: F811 self, address: Optional[Union[Address, ChecksumAddress, ENS]] = None, **kwargs: Any) -> Union[Type[Contract], Contract]: ContractFactoryClass = kwargs.pop('ContractFactoryClass', self.defaultContractFactory) ContractFactory = ContractFactoryClass.factory(self.web3, **kwargs) if address: return ContractFactory(address) else: return ContractFactory @deprecated_for("set_contract_factory") def setContractFactory( self, contractFactory: Type[Union[Contract, ConciseContract, ContractCaller]] ) -> None: return self.set_contract_factory(contractFactory) def set_contract_factory( self, contractFactory: Type[Union[Contract, ConciseContract, ContractCaller]] ) -> None: self.defaultContractFactory = contractFactory def getCompilers(self) -> NoReturn: raise DeprecationWarning( "This method has been deprecated as of EIP 1474.") get_work: Method[Callable[[], List[HexBytes]]] = Method( RPC.eth_getWork, mungers=None, ) @deprecated_for("generate_gas_price") def generateGasPrice( self, transaction_params: Optional[TxParams] = None) -> Optional[Wei]: return self.generate_gas_price(transaction_params) def generate_gas_price( self, transaction_params: Optional[TxParams] = None) -> Optional[Wei]: if self.gasPriceStrategy: return self.gasPriceStrategy(self.web3, transaction_params) return None @deprecated_for("set_gas_price_strategy") def setGasPriceStrategy(self, gas_price_strategy: GasPriceStrategy) -> None: return self.set_gas_price_strategy(gas_price_strategy) def set_gas_price_strategy(self, gas_price_strategy: GasPriceStrategy) -> None: self.gasPriceStrategy = gas_price_strategy # Deprecated Methods getBalance = DeprecatedMethod(get_balance, 'getBalance', 'get_balance') getStorageAt = DeprecatedMethod(get_storage_at, 'getStorageAt', 'get_storage_at') getBlock = DeprecatedMethod(get_block, 'getBlock', 'get_block') getBlockTransactionCount = DeprecatedMethod(get_block_transaction_count, 'getBlockTransactionCount', 'get_block_transaction_count') getCode = DeprecatedMethod(get_code, 'getCode', 'get_code') getProof = DeprecatedMethod(get_proof, 'getProof', 'get_proof') getTransaction = DeprecatedMethod(get_transaction, 'getTransaction', 'get_transaction') getTransactionByBlock = DeprecatedMethod(get_transaction_by_block, 'getTransactionByBlock', 'get_transaction_by_block') getTransactionCount = DeprecatedMethod(get_transaction_count, 'getTransactionCount', 'get_transaction_count') getUncleByBlock = DeprecatedMethod(get_uncle_by_block, 'getUncleByBlock', 'get_uncle_by_block') getUncleCount = DeprecatedMethod(get_uncle_count, 'getUncleCount', 'get_uncle_count') sendTransaction = DeprecatedMethod(send_transaction, 'sendTransaction', 'send_transaction') signTransaction = DeprecatedMethod(sign_transaction, 'signTransaction', 'sign_transaction') signTypedData = DeprecatedMethod(sign_typed_data, 'signTypedData', 'sign_typed_data') submitHashrate = DeprecatedMethod(submit_hashrate, 'submitHashrate', 'submit_hashrate') submitWork = DeprecatedMethod(submit_work, 'submitWork', 'submit_work') getLogs = DeprecatedMethod(get_logs, 'getLogs', 'get_logs') estimateGas = DeprecatedMethod(estimate_gas, 'estimateGas', 'estimate_gas') sendRawTransaction = DeprecatedMethod(send_raw_transaction, 'sendRawTransaction', 'send_raw_transaction') getTransactionReceipt = DeprecatedMethod(get_transaction_receipt, 'getTransactionReceipt', 'get_transaction_receipt') uninstallFilter = DeprecatedMethod(uninstall_filter, 'uninstallFilter', 'uninstall_filter') getFilterLogs = DeprecatedMethod(get_filter_logs, 'getFilterLogs', 'get_filter_logs') getFilterChanges = DeprecatedMethod(get_filter_changes, 'getFilterChanges', 'get_filter_changes') getWork = DeprecatedMethod(get_work, 'getWork', 'get_work')
def test_create_or_update_from_tx_hashes_existing(self): index_service: IndexService = IndexServiceProvider() self.assertListEqual( index_service.txs_create_or_update_from_tx_hashes([]), []) tx_hashes = [ '0x52fcb05f2ad209d53d84b0a9a7ce6474ab415db88bc364c088758d70c8b5b0ef' ] with self.assertRaisesMessage(TransactionNotFoundException, tx_hashes[0]): index_service.txs_create_or_update_from_tx_hashes(tx_hashes) # Test with database txs. Use block_number > current_block_number to prevent storing blocks with wrong # hashes that will be indexed by next tests current_block_number = self.ethereum_client.current_block_number ethereum_txs = [ EthereumTxFactory(block__number=current_block_number + 100 + i) for i in range(4) ] tx_hashes = [ethereum_tx.tx_hash for ethereum_tx in ethereum_txs] db_txs = index_service.txs_create_or_update_from_tx_hashes(tx_hashes) self.assertEqual(len(db_txs), len(tx_hashes)) for db_tx in db_txs: self.assertIsNotNone(db_tx) # Test with real txs value = 6 real_tx_hashes = [ self.send_ether(Account.create().address, value) for _ in range(2) ] ethereum_txs = index_service.txs_create_or_update_from_tx_hashes( real_tx_hashes) self.assertEqual(len(ethereum_txs), len(ethereum_txs)) for ethereum_tx in ethereum_txs: self.assertEqual(ethereum_tx.value, value) # Remove blocks and try again EthereumTx.objects.filter(tx_hash__in=real_tx_hashes).update( block=None) ethereum_txs = index_service.txs_create_or_update_from_tx_hashes( real_tx_hashes) for ethereum_tx in ethereum_txs: self.assertIsNotNone(ethereum_tx.block) # Test mixed tx_hashes = tx_hashes + real_tx_hashes mixed_txs = index_service.txs_create_or_update_from_tx_hashes( tx_hashes) self.assertEqual(len(mixed_txs), len(tx_hashes)) for mixed_tx in mixed_txs: self.assertIsNotNone(mixed_tx) # Test block hash changes ethereum_tx = ethereum_txs[0] ethereum_tx.block.block_hash = Web3.keccak(text='aloha') ethereum_tx.block.save(update_fields=['block_hash']) tx_hash = ethereum_tx.tx_hash # Uses database index_service.txs_create_or_update_from_tx_hashes([tx_hash]) ethereum_tx.delete() # Try to fetch again with self.assertRaises(EthereumBlockHashMismatch): index_service.txs_create_or_update_from_tx_hashes([tx_hash])
def sign_hash(message_hash, private_key): if not is_hex(message_hash): raise ValueError('Invalid message_hash provided') return ETHAccount.signHash(message_hash, private_key)
def Import_From_Private(secret, password1): print("this is imported private key", secret) acct = Account.privateKeyToAccount(secret) public_key = acct.address encrypted = Account.encrypt(secret, password1) return (1, public_key, json.dumps(encrypted))
def get_key(address, key_type, mode, address_caller=None) : """ main function to get key from server storage """ if not mode.w3.isAddress(address) or address == '0x0000000000000000000000000000000000000000' : logging.error('incorrect address = %s', address) return None if key_type == 'P-256' : try : fp = open(mode.P256_path + address + '.P256', 'r') except : logging.error('P256 key not found in privatekey.py') return None key = jwk.JWK.from_pem(fp.read().encode(), password=mode.password.encode()) return key.export_private() if key_type == 'Ed25519' : try : fp = open(mode.Ed25519_path + address + '.Ed25519', 'r') except : logging.error('Ed25519 key not found in privatekey.py') return None key = jwk.JWK.from_pem(fp.read().encode(), password=mode.password.encode()) return key.export_private() if key_type == 'secp256k1' : try : fp = open(mode.keystore_path + address[2:] + '.json', 'r') except : logging.error('private key not found in privatekey.py') return None pvk = Account.decrypt(fp.read(), mode.password).hex() return helpers.ethereum_to_jwk(pvk, mode) if key_type == 'private_key' : try : fp = open(mode.keystore_path + address[2:] + '.json', 'r') except : logging.error('private key not found in privatekey.py') return None return Account.decrypt(fp.read(), mode.password).hex() # first we try to find a the new rsa file with .pem workspace_contract = ownersToContracts(address, mode) previous_filename = "./RSA_key/" + mode.BLOCKCHAIN + '/' + address + "_TalaoAsymetricEncryptionPrivateKeyAlgorithm1.txt" new_filename = "./RSA_key/" + mode.BLOCKCHAIN + '/did:talao:' + mode.BLOCKCHAIN + ':' + workspace_contract[2:] + ".pem" try : fp_new = open(new_filename,'r') except IOError : try : fp_prev = open(previous_filename,'r') except IOError : logging.warning('RSA key not found') rsa_key = None else : rsa_key = fp_prev.read() os.rename(previous_filename, new_filename) else : rsa_key = fp_new.read() if key_type in ['rsa_key', 'RSA'] : return rsa_key # get data for AES keys from workspace contract contract = mode.w3.eth.contract(workspace_contract,abi = constante.workspace_ABI) data = contract.functions.identityInformation().call() if key_type in ['aes_key', 'private'] and rsa_key : key = RSA.importKey(rsa_key) cipher = PKCS1_OAEP.new(key) return cipher.decrypt(data[5]) elif key_type in ['secret_key', 'secret'] and rsa_key : key = RSA.importKey(rsa_key) cipher = PKCS1_OAEP.new(key) return cipher.decrypt(data[6]) elif key_type in ['aes_key', 'private'] and address_caller : # look for partnership data #recuperer les cle AES cryptée du user sur son partnership de l identité (caller) workspace_contract_caller = ownersToContracts(address_caller, mode) contract = mode.w3.eth.contract(workspace_contract_caller, abi = constante.workspace_ABI) private_key_caller = get_key(address_caller, 'private_key', mode) try : acct = Account.from_key(private_key_caller) except : return None mode.w3.eth.defaultAccount = acct.address try : partnership_data = contract.functions.getPartnership(workspace_contract).call() except : logging.error('problem with getPartnership') return None # one tests if the user is in partnershipg with identity (pending or authorized) and if his aes_key exist (status rejected ?) if partnership_data[1] in [1, 2] and partnership_data[4] != b'': aes_encrypted = partnership_data[4] else : # no partnership logging.info('no partnership with Identity') return None rsa_key_caller = get_key(address_caller, 'rsa_key', mode) key = RSA.importKey(rsa_key_caller) cipher = PKCS1_OAEP.new(key) logging.info('private key decrypted with partnership data = %s', cipher.decrypt(aes_encrypted)) return cipher.decrypt(aes_encrypted) else : logging.error('no key decrypted %s', key_type) return None
def recover_executive_address(self, proposal: Proposal) -> str: signing_account = Account.recoverHash(message_hash=proposal.digest, signature=self.serialize()) return signing_account
def priv_key_to_address(private_key): from eth_account import Account acc = Account.privateKeyToAccount(private_key) return acc.address
def test_personal_importRawKey(rpc_client): account_manager = Account() private_key = account_manager.create().privateKey new_account = rpc_client('personal_importRawKey', [encode_hex(private_key), 'a-password']) assert rpc_client('personal_unlockAccount', [new_account, 'a-password']) is True
def send(endpoint, message): w3 = Web3(Web3.HTTPProvider(endpoint)) account = Account() private_key = os.environ["ETH_MSG_PRIVATE_KEY"] address = account.privateKeyToAccount(private_key).address contract_source_code = ''' pragma solidity ^0.4.21; contract Message { string public text; function Message() public { text = '$message'; } function getText() public returns(string) { return text; } } ''' contract_source_code = Template(contract_source_code).substitute( {'message': message}) compiled_sol = compile_source(contract_source_code) contract_interface = compiled_sol['<stdin>:Message'] nonce = w3.eth.getTransactionCount(address, 'pending') Message = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) text_file = open("/tmp/fin.json", "w") text_file.write("%s" % json.dumps(contract_interface['abi'])) text_file.close() tx = Message.constructor().buildTransaction({ 'from': address, 'gas': w3.eth.estimateGas(Message.constructor().buildTransaction( {'from': address})), 'nonce': nonce, 'gasPrice': w3.eth.gasPrice }) signed_txn = w3.eth.account.signTransaction(tx, private_key=private_key) tx_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) receipt = w3.eth.waitForTransactionReceipt(tx_hash, 10000) receipt_data = w3.eth.getTransactionReceipt(tx_hash) print("Message saved to contract:") print(receipt_data['contractAddress']) print("Transaction hash:") print(tx_hash.hex())
from http.server import BaseHTTPRequestHandler, HTTPServer import socketserver import json import cgi import hashlib import time from web3 import Web3 from eth_account import Account from solc import compile_source from web3.contract import ConciseContract from web3.gas_strategies.time_based import medium_gas_price_strategy w3 = Web3( Web3.WebsocketProvider( 'wss://ropsten.infura.io/ws/v3/8290d422df13434f8133c29fd2138734')) acct = Account.privateKeyToAccount( 'BAD62390F4D3F53E67C70E3A4961D4724B7FF1BF66B2EF5486FFCC45A76F1806') key = acct.privateKey abi = ''' [ { "constant": true, "inputs": [], "name": "nextIDSource", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false,
def test_safe_creation(self): salt_nonce = generate_salt_nonce() owners = [Account.create().address for _ in range(2)] data = { 'saltNonce': salt_nonce, 'owners': owners, 'threshold': len(owners) } response = self.client.post(reverse('v3:safe-creation'), data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) response_json = response.json() safe_address = response_json['safe'] self.assertTrue(check_checksum(safe_address)) self.assertTrue(check_checksum(response_json['paymentReceiver'])) self.assertEqual(response_json['paymentToken'], NULL_ADDRESS) self.assertEqual( int(response_json['payment']), int(response_json['gasEstimated']) * int(response_json['gasPriceEstimated'])) self.assertGreater(int(response_json['gasEstimated']), 0) self.assertGreater(int(response_json['gasPriceEstimated']), 0) self.assertGreater(len(response_json['setupData']), 2) self.assertEqual(response_json['masterCopy'], settings.SAFE_CONTRACT_ADDRESS) self.assertTrue(SafeContract.objects.filter(address=safe_address)) self.assertTrue( SafeCreation2.objects.filter(owners__contains=[owners[0]])) safe_creation = SafeCreation2.objects.get(safe=safe_address) self.assertEqual(safe_creation.payment_token, None) # Payment includes deployment gas + gas to send eth to the deployer self.assertEqual(safe_creation.payment, safe_creation.wei_estimated_deploy_cost()) # Deploy the Safe to check it self.send_ether(safe_address, int(response_json['payment'])) safe_creation2 = SafeCreationServiceProvider().deploy_create2_safe_tx( safe_address) self.ethereum_client.get_transaction_receipt(safe_creation2.tx_hash, timeout=20) safe = Safe(safe_address, self.ethereum_client) self.assertEqual(safe.retrieve_master_copy_address(), response_json['masterCopy']) self.assertEqual(safe.retrieve_owners(), owners) # Test exception when same Safe is created response = self.client.post(reverse('v3:safe-creation'), data, format='json') self.assertEqual(response.status_code, status.HTTP_422_UNPROCESSABLE_ENTITY) self.assertIn('SafeAlreadyExistsException', response.json()['exception']) data = {'salt_nonce': -1, 'owners': owners, 'threshold': 2} response = self.client.post(reverse('v3:safe-creation'), data, format='json') self.assertEqual(response.status_code, status.HTTP_422_UNPROCESSABLE_ENTITY)
def mock_key(): test_key = Account.create(extra_entropy='M*A*S*H* DIWOKNECNECENOE#@!') return test_key
def recover_hash(message_hash, signature): if not is_hex(message_hash): raise ValueError('Invalid message_hash provided') return ETHAccount.recoverHash(message_hash, signature=signature)
def mock_account(mock_key): account = Account.from_key(private_key=mock_key.key) return account
def enable_unaudited_features(self): self._account = Account()
def unknown_address(): address = Account.create().address return address
def import_and_save_wallet(password: str, private_key: str) -> Account: acct: Account = Account.privateKeyToAccount(private_key) return save_wallet(acct, password)
def get_goerli_test_account(): return Account.from_key(os.getenv('PRIVATE_KEY'))
from eth_account import Account acct = Account.create('test') pk = acct.privateKey new_pk = pk.hex() print("privateKey: " + new_pk) print("address: " + acct.address)
super().__init__(parties, db) self.background_tasks = background_tasks self.token_contract = token_contract async def create( self, user: UserInDb, obj: PartyCreate, create_blockchain_account: bool = True, token_id: int = 0, initial_amount: int = 1_000_000_00, token_owner: LocalAccount = None, tx: bool = True ): account = None if create_blockchain_account: account = Account.create() elif obj.blockchain_account_key is not None: # noinspection PyCallByClass account = Account.from_key( obj.blockchain_account_key.get_secret_value() ) if account is not None: obj.blockchain_account_address = account.address self.save_blockchain_account(account) obj_data = self._to_dict(obj) obj_data.pop('blockchain_account_key', '') result = await self._insert(obj_data, tx=tx) if initial_amount > 0 and obj.blockchain_account_address is not None: if token_owner is None: qadmin_name = get_settings().qadmin_name qadmin = await self.get_one_by_name(user, qadmin_name)
def test_notifications_devices_create_view(self): response = self.client.post(reverse('v1:notifications-devices')) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) safe_address = Account.create().address safe_contract = SafeContractFactory(address=safe_address) self.assertEqual(FirebaseDevice.objects.count(), 0) data = { 'safes': [safe_address], 'cloudMessagingToken': 'A' * 163, 'buildNumber': 0, 'bundle': 'company.package.app', 'deviceType': 'WEB', 'version': '2.0.1', } response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(FirebaseDevice.objects.count(), 1) device_uuid = response.data['uuid'] self.assertTrue(uuid.UUID(device_uuid)) # Same request should return a 400 because a new device with same push token cannot be created response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # Request with `uuid` should not create a new object data['uuid'] = device_uuid response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(FirebaseDevice.objects.count(), 1) # Changing the token and using the uuid will change the cloud messaging token data['cloudMessagingToken'] = 'B' * 163 response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(FirebaseDevice.objects.count(), 1) self.assertEqual(FirebaseDevice.objects.first().cloud_messaging_token, data['cloudMessagingToken']) # Add the same FirebaseDevice to another Safe safe_contract_2 = SafeContractFactory() data['safes'].append(safe_contract_2.address) response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(safe_contract.firebase_devices.count(), 1) self.assertEqual(safe_contract_2.firebase_devices.count(), 1) self.assertEqual(FirebaseDevice.objects.count(), 1) self.assertEqual(FirebaseDevice.objects.first().safes.count(), 2) # Use not valid deviceType previous_device_type = data['deviceType'] data['deviceType'] = 'RANGER-MORPHER' response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertIn('is not a valid choice', response.content.decode()) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(safe_contract.firebase_devices.count(), 1) data['deviceType'] = previous_device_type # Use not valid version previous_version = data['version'] data['version'] = 'Megazord' response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertIn('Semantic version was expected', response.content.decode()) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(safe_contract.firebase_devices.count(), 1) data['version'] = previous_version # Remove one of the Safes data['safes'] = [safe_contract_2.address] response = self.client.post(reverse('v1:notifications-devices'), format='json', data=data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(safe_contract.firebase_devices.count(), 0) self.assertEqual(safe_contract_2.firebase_devices.count(), 1)
def priv_key_to_account(priv_key, coin): if coin == BTCTEST: return PrivateKeyTestnet(str(priv_key)) elif coin == ETH: return Account.from_key(str(priv_key))
""" this python script was created by Simon Schuler ([email protected]) for the Workshop "Supply-Blockchain management" at NConf 2019 """ from eth_account import Account # choose a random String, acts as a seed for wallet generation # this just increases the entropy, executing this script twice with the same # random_string dose not produce the same wallet! random_string = "put something randome here" # create a new Account account = Account().create(extra_entropy=random_string) # save the private key in a file with open("wallet/private.key", "wb") as key_file: key_file.write(account.privateKey) # print all information on the screen print("Address:", account.address) # let the user know it succeded print("Your key can be found in the file \"wallet/private.key\"")
def priv_key_to_account(coin, priv_key): if coin == ETH: return Account.privateKeyToAccount(priv_key) if coin == BTCTEST: return PrivateKeyTestnet(priv_key)
from hypothesis import ( given, settings, strategies as st, ) import pytest import subprocess from eth_account import ( Account, ) from eth_account.hdaccount.mnemonic import ( VALID_ENTROPY_SIZES, Mnemonic, ) Account.enable_unaudited_hdwallet_features() language_st = st.sampled_from(Mnemonic.list_languages()) seed_st = st.binary(min_size=min(VALID_ENTROPY_SIZES), max_size=max(VALID_ENTROPY_SIZES)) \ .filter(lambda x: len(x) in VALID_ENTROPY_SIZES) \ .filter(lambda s: int.from_bytes(s, byteorder="big") != 0) node_st = st.tuples(st.integers(min_value=0, max_value=2**31 - 1), st.booleans()) path_st = st.lists(node_st, min_size=0, max_size=10) \ .map(lambda nodes: list(str(n[0]) + ('' if n[1] else "'") for n in nodes)) \ .map(lambda nodes: 'm' + ('/' + '/'.join(nodes) if nodes else '')) @given(seed=seed_st, language=language_st, account_path=path_st)
def private_key_to_account(val): normalized_key = key_normalizer(val) return Account.privateKeyToAccount(normalized_key)