def contract_deposit(self, deposit_amount, sender_pkey, partner_pkey): sender_address = private_key_to_address(sender_pkey.to_hex()) partner_address = private_key_to_address(partner_pkey.to_hex()) token_balance = self.token.functions.balanceOf(sender_address).call() # Sampling private keys could choose the pair # from the same item. # skip as getChannelInfo fails for the sender==receiver if sender_address == partner_address: return (channel_identifier, _, channel_state) = self.token_network.functions.getChannelInfo( participant1=sender_address, participant2=partner_address).call() (existing_deposit, _, _, _, _) = self.token_network.functions.getChannelParticipantInfo( participant=sender_address, partner=partner_address).call() deposit_amount += existing_deposit if not self.is_participant(sender_address): with transaction_must_fail( "deposit from non-participant didnt fail"): self.token_network.functions.setTotalDeposit( sender_address, deposit_amount, partner_address).transact({"from": sender_address}) elif channel_state != 1: with transaction_must_fail( "deposit with closed channel didnt fail"): self.token_network.functions.setTotalDeposit( sender_address, deposit_amount, partner_address).transact({"from": sender_address}) elif token_balance < deposit_amount: with transaction_must_fail( "having insufficient funds for a deposit didnt fail"): self.token_network.functions.setTotalDeposit( sender_address, deposit_amount, partner_address).transact({"from": sender_address}) else: self.token.functions.approve(self.token_network.address, deposit_amount).transact( {"from": sender_address}) self.token_network.functions.setTotalDeposit( sender_address, deposit_amount, partner_address).transact({"from": sender_address})
def __init__( self, web3: Web3, private_key: str, gas_limit: int, gas_price: int = 1, wait: int = 10, contracts_version: Optional[str] = None, ): # pylint: disable=E1101 super(ContractDeployer, self).__init__(web3=web3, contracts_version=contracts_version) self.wait = wait self.owner = private_key_to_address(private_key) self.transaction = {"from": self.owner, "gas": gas_limit} if gas_price != 0: self.transaction["gasPrice"] = gas_price * int(units["gwei"]) self.web3.middleware_stack.add(construct_sign_and_send_raw_middleware(private_key)) # Check that the precompiled data matches the source code # Only for current version, because this is the only one with source code if self.contracts_version in [None, CONTRACTS_VERSION]: contract_manager_source = ContractSourceManager(contracts_source_path()) contract_manager_source.checksum_contracts() contract_manager_source.verify_precompiled_checksums(self.precompiled_path) else: LOG.info("Skipped checks against the source code because it is not available.")
def __init__( self, web3: Web3, private_key: str, gas_limit: int, gas_price: int=1, wait: int=10, contracts_version: Optional[str]=None, ): self.web3 = web3 self.wait = wait self.owner = private_key_to_address(private_key) self.transaction = {'from': self.owner, 'gas': gas_limit} if gas_price != 0: self.transaction['gasPrice'] = gas_price * denoms.gwei self.contracts_version = contracts_version self.precompiled_path = contracts_precompiled_path(self.contracts_version) self.contract_manager = ContractManager(self.precompiled_path) self.web3.middleware_stack.add( construct_sign_and_send_raw_middleware(private_key), ) # Check that the precompiled data matches the source code # Only for current version, because this is the only one with source code if self.contracts_version in [None, CONTRACTS_VERSION]: contract_manager_source = ContractManager(contracts_source_path()) contract_manager_source.checksum_contracts() contract_manager_source.verify_precompiled_checksums(self.precompiled_path) else: log.info('Skipped checks against the source code because it is not available.')
def deploy_contract(web3, contracts_manager, contract_name, deployer_key, args=None): deployer_address = private_key_to_address(deployer_key.to_hex()) json_contract = contracts_manager.get_contract(contract_name) contract = web3.eth.contract(abi=json_contract["abi"], bytecode=json_contract["bin"]) tx_hash = contract.constructor(*args).call_and_transact({"from": deployer_address}) contract_address = web3.eth.getTransactionReceipt(tx_hash).contractAddress return contract(contract_address)
def __init__( self, rpc_url: URI, private_key: Path, password: Optional[Path] = None, wait: int = 10 ): self.web3 = Web3(HTTPProvider(rpc_url)) self.private_key = get_private_key(private_key, password) assert self.private_key is not None self.owner = private_key_to_address(self.private_key) self.wait = wait self.web3.middleware_onion.add(construct_sign_and_send_raw_middleware(self.private_key)) self.web3.eth.defaultAccount = self.owner # type: ignore self.web3.middleware_onion.inject(geth_poa_middleware, layer=0)
def deploy_contract(web3, contracts_manager, contract_name, deployer_key, libs=None, args=None): deployer_address = private_key_to_address(deployer_key.to_hex()) json_contract = contracts_manager.get_contract(contract_name) contract = web3.eth.contract( abi=json_contract['abi'], bytecode=json_contract['bin'], ) tx_hash = contract.constructor(*args).transact({ 'from': deployer_address, }) contract_address = web3.eth.getTransactionReceipt(tx_hash).contractAddress return contract(contract_address)
def deploy_contract( web3: Web3, contracts_manager: ContractManager, contract_name: str, deployer_key: CCPrivateKey, args: List[Any], ) -> Contract: deployer_address = private_key_to_address(deployer_key.to_hex()) json_contract = contracts_manager.get_contract(contract_name) contract = web3.eth.contract(abi=json_contract["abi"], bytecode=json_contract["bin"]) tx_hash = contract.constructor(*args).transact(TxParams({"from": deployer_address})) contract_address = web3.eth.get_transaction_receipt(tx_hash)["contractAddress"] return contract(contract_address)
def get(): privkey = get_random_privkey() address = private_key_to_address(privkey) ethereum_tester.add_account(privkey) for faucet in web3.eth.accounts[:10]: try: web3.eth.sendTransaction({ 'from': faucet, 'to': address, 'value': 1 * denoms.finney, }) break except TransactionFailed: continue return address
def main(rpc_url: URI, private_key: Path, token_address: ChecksumAddress, amount: int) -> None: web3 = Web3(HTTPProvider(rpc_url)) privkey = get_private_key(private_key) assert privkey is not None owner = private_key_to_address(privkey) web3.middleware_onion.add(construct_sign_and_send_raw_middleware(privkey)) token_code = web3.eth.get_code(token_address, "latest") assert token_code != HexBytes("") token_contract = ContractManager(contracts_precompiled_path()).get_contract( CONTRACT_CUSTOM_TOKEN ) token_proxy = web3.eth.contract(address=token_address, abi=token_contract["abi"]) tx_hash = token_proxy.functions.mint(amount).transact({"from": owner}) print(f"Minting tokens for address {owner}") print(f"Transaction hash {encode_hex(tx_hash)}") balance = token_proxy.functions.balanceOf(owner).call() print(f"Balance of {owner}: {balance}")
def get_web3(eth_tester, deployer_key): """Returns an initialized Web3 instance""" provider = EthereumTesterProvider(eth_tester) web3 = Web3(provider) # add faucet account to tester eth_tester.add_account(deployer_key.to_hex()) # make faucet rich eth_tester.send_transaction({ 'from': eth_tester.get_accounts()[0], 'to': private_key_to_address(deployer_key.to_hex()), 'gas': 21000, 'value': FAUCET_ALLOWANCE, }) return web3
def get(privkey: Optional[str] = None) -> HexAddress: if not privkey: privkey = get_random_privkey() address = private_key_to_address(privkey) if not any((is_same_address(address, x) for x in ethereum_tester.get_accounts())): # account has not been added to ethereum_tester, yet ethereum_tester.add_account(privkey) for faucet in web3.eth.accounts[:10]: try: web3.eth.sendTransaction( {"from": faucet, "to": address, "value": 1 * int(units["finney"])} ) break except TransactionFailed: continue return address
def setup_ctx( ctx: click.Context, private_key: str, password_file: Optional[Path], rpc_provider: URI, wait: int, gas_price: int, gas_limit: int, contracts_version: Optional[str] = None, ) -> None: """Set up deployment context according to common options (shared among all subcommands). """ logging.basicConfig(level=logging.DEBUG) logging.getLogger("web3").setLevel(logging.INFO) logging.getLogger("urllib3").setLevel(logging.INFO) web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={"timeout": 60})) web3.middleware_onion.inject(geth_poa_middleware, layer=0) print("Web3 provider is", web3.provider) private_key_string = get_private_key( Path(private_key).expanduser(), password_file) if not private_key_string: raise RuntimeError("Could not access the private key.") owner = private_key_to_address(private_key_string) # pylint: disable=E1101 if web3.eth.get_balance(owner) == 0: raise RuntimeError("Account with insufficient funds.") deployer = ContractDeployer( web3=web3, private_key=private_key_string, gas_limit=gas_limit, gas_price=gas_price, wait=wait, contracts_version=contracts_version, ) ctx.obj = { "deployer": deployer, "deployed_contracts": {}, "token_type": "CustomToken", "wait": wait, }
def get_web3(eth_tester: EthereumTester, deployer_key: CCPrivateKey) -> Web3: """Returns an initialized Web3 instance""" provider = EthereumTesterProvider(eth_tester) web3 = Web3(provider) # add faucet account to tester eth_tester.add_account(deployer_key.to_hex()) # make faucet rich eth_tester.send_transaction( { "from": eth_tester.get_accounts()[0], "to": private_key_to_address(deployer_key.to_hex()), "gas": 21000, "value": FAUCET_ALLOWANCE, } ) return web3
def setup_ctx( ctx: click.Context, private_key: str, rpc_provider: str, wait: int, gas_price: int, gas_limit: int, contracts_version: None = None, ): """Set up deployment context according to common options (shared among all subcommands). """ if private_key is None: return logging.basicConfig(level=logging.DEBUG) logging.getLogger('web3').setLevel(logging.INFO) logging.getLogger('urllib3').setLevel(logging.INFO) web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60})) web3.middleware_stack.inject(geth_poa_middleware, layer=0) print('Web3 provider is', web3.providers[0]) private_key = get_private_key(private_key) assert private_key is not None owner = private_key_to_address(private_key) # pylint: disable=E1101 assert web3.eth.getBalance(owner) > 0, 'Account with insuficient funds.' deployer = ContractDeployer( web3=web3, private_key=private_key, gas_limit=gas_limit, gas_price=gas_price, wait=wait, contracts_version=contracts_version, ) ctx.obj = {} ctx.obj['deployer'] = deployer ctx.obj['deployed_contracts'] = {} ctx.obj['token_type'] = 'CustomToken' ctx.obj['wait'] = wait
def __init__(self): super().__init__() self.log = list() self.settle_timeout = 10 deployer_key = PrivateKey(secret=b'deploy_key') pyevm_main.GENESIS_GAS_LIMIT = 6 * 10**6 self.tester_chain = ethereum_tester() self.web3 = get_web3(self.tester_chain, deployer_key) self.tokens = [ deploy_custom_token( self.web3, deployer_key, ), deploy_custom_token( self.web3, deployer_key, ), ] self.token = self.tokens[0] self.token_addresses = [token.address for token in self.tokens] self.private_keys = [ PrivateKey(secret=b'p1'), PrivateKey(secret=b'p2'), PrivateKey(secret=b'p3'), ] # Create and fund accounts with Ether and CustomToken self.addresses = [] token_amount = 100000 for private_key in self.private_keys: self.tester_chain.add_account(private_key.to_hex()) address = private_key_to_address(private_key.to_hex()) self.tester_chain.send_transaction({ 'from': self.tester_chain.get_accounts()[0], 'to': address, 'gas': 21000, 'value': self.web3.toWei(100, 'ether'), }) self.token.functions.transfer( address, token_amount, ).transact({ 'from': private_key_to_address(deployer_key.to_hex()), }) self.addresses.append(address) self.secret_registry = deploy_contract( self.web3, CONTRACT_SECRET_REGISTRY, deployer_key, [], # No Libs [], # No Args ) self.token_network_registry = deploy_contract( self.web3, CONTRACT_TOKEN_NETWORK_REGISTRY, deployer_key, [], [ self.secret_registry.address, 1, TEST_SETTLE_TIMEOUT_MIN, TEST_SETTLE_TIMEOUT_MAX, ], ) self.token_network_registry.functions.createERC20TokenNetwork( self.token.address, MAX_ETH_CHANNEL_PARTICIPANT, MAX_ETH_TOKEN_NETWORK, ).transact() token_network_address = self.token_network_registry.functions.token_to_token_networks( self.token.address, ).call() self.token_network = get_token_network( self.web3, to_checksum_address(token_network_address), ) channel_identifier = self.open_channel() self.closing_address = None self.update_transfer_called = False self.participant_addresses = { self.addresses[0], self.addresses[1], } self.channel_addresses = [ channel_identifier, make_address(), ]
def contract_update_transfer(self, transfer, sender_pkey, partner_pkey): sender_signature = transfer.sign( sender_pkey, private_key_to_address(sender_pkey.to_hex()), ) receiver_signature = transfer.sign( partner_pkey, private_key_to_address(partner_pkey.to_hex()), ) sender_address = private_key_to_address(sender_pkey.to_hex()) partner_address = private_key_to_address(partner_pkey.to_hex()) transfer_data = transfer.to_bytes() transfer_hash = Web3.sha3(hexstr=encode_hex(transfer_data[:-65]), ) # Sampling private keys could choose the pair # from the same item. # skip as getChannelInfo fails for the sender==receiver if sender_address == partner_address: return (_, settle_block_number, channel_state) = self.token_network.functions.getChannelInfo( sender_address, partner_address, ).call({ 'from': self.web3.eth.accounts[0], 'gas': GAS_LIMIT, }) is_closed = channel_state == 2 block_number = self.tester_chain.get_block_by_number( 'latest')['number'] is_settlement_period_over = is_closed and settle_block_number < block_number if not self.is_participant(transfer.sender): msg = 'updateTransfer with transfer data from a non participant didnt fail' with transaction_must_fail(msg): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() elif transfer.sender == sender_address: with transaction_must_fail( 'updateTransfer with self signed transfer didnt fail'): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() elif self.update_transfer_called: with transaction_must_fail( 'updateTransfer called twice didnt fail'): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() elif not self.is_participant(sender_address): with transaction_must_fail( 'updateTransfer called by a non participant didnt fail'): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() elif transfer.channel != self.channel_addresses[0]: msg = 'updateTransfer called with a transfer for a different channel didnt fail' with transaction_must_fail(msg): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() elif not is_closed: with transaction_must_fail( 'updateTransfer called on an open channel and didnt fail'): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() elif is_settlement_period_over: msg = 'updateTransfer called after end of the settlement period and didnt fail' with transaction_must_fail(msg): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() elif sender_address == self.closing_address: with transaction_must_fail( 'updateTransfer called by the closer and it didnt fail'): self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() else: self.token_network.functions.updateNonClosingBalanceProof( sender_address, partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, sender_signature, receiver_signature, ).transact() self.update_transfer_called = True
def contract_close(self, transfer, closer_pkey, partner_pkey): closer_signature = transfer.sign( closer_pkey, private_key_to_address(closer_pkey.to_hex()), ) closer_address = private_key_to_address(closer_pkey.to_hex()) partner_address = private_key_to_address(partner_pkey.to_hex()) transfer_data = transfer.to_bytes() transfer_hash = Web3.sha3(hexstr=encode_hex(transfer_data[:-65]), ) if closer_address == partner_address: return (_, _, channel_state) = self.token_network.functions.getChannelInfo( participant1=closer_address, participant2=partner_address, ).call() if not self.is_participant(transfer.sender): msg = 'close with transfer data from a non participant didnt fail' with transaction_must_fail(msg): self.token_network.functions.closeChannel( partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, closer_signature, ).transact() elif transfer.sender == closer_address: with transaction_must_fail( 'close with self signed transfer didnt fail'): self.token_network.functions.closeChannel( partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, closer_signature, ).transact() elif channel_state == 2: with transaction_must_fail('close called twice didnt fail'): self.token_network.functions.closeChannel( partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, closer_signature, ).transact() elif not self.is_participant(closer_address): with transaction_must_fail( 'close called by a non participant didnt fail'): self.token_network.functions.closeChannel( partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, closer_signature, ).transact() elif transfer.channel != to_canonical_address( self.token_network.address): msg = 'close called with a transfer for a different channe didnt fail' with transaction_must_fail(msg): self.token_network.functions.closeChannel( partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, closer_signature, ).transact() else: self.token_network.functions.closeChannel( partner_address, transfer.balance_hash(), transfer.nonce, transfer_hash, closer_signature, ).transact() self.closing_address = closer_address
from enum import IntEnum from eth_utils.units import units from raiden_contracts.utils.signature import private_key_to_address UINT256_MAX = 2**256 - 1 NOT_ADDRESS = "0xaaa" FAKE_ADDRESS = "0x00112233445566778899aabbccddeeff00112233" EMPTY_BALANCE_HASH = b"\x00" * 32 EMPTY_ADDITIONAL_HASH = b"\x00" * 32 EMPTY_SIGNATURE = b"\x00" * 65 passphrase = "0" FAUCET_PRIVATE_KEY = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" FAUCET_ADDRESS = private_key_to_address(FAUCET_PRIVATE_KEY) FAUCET_ALLOWANCE = 100 * int(units["ether"]) CONTRACT_DEPLOYER_ADDRESS = FAUCET_ADDRESS NONEXISTENT_LOCKSROOT = b"\x00" * 32 SECONDS_PER_DAY = 60 * 60 * 24 # Constants for ServiceRegistry testing SERVICE_DEPOSIT = 5000 * (10**18) DEFAULT_BUMP_NUMERATOR = 6 DEFAULT_BUMP_DENOMINATOR = 5 DEFAULT_DECAY_CONSTANT = 200 * SECONDS_PER_DAY DEFAULT_REGISTRATION_DURATION = 180 * SECONDS_PER_DAY DEFAULT_MIN_PRICE = 1000 class TestLockIndex(IntEnum): EXPIRATION = 0
def faucet_address(faucet_private_key): """Returns address of a faucet used in tests""" return private_key_to_address(faucet_private_key)
def get_random_address() -> str: """Returns a random valid ethereum address""" return private_key_to_address(get_random_privkey())
def f(): return private_key_to_address(get_random_privkey())