def rest_faucet(recipient_address): """top up an account""" # recipient_address = request.form.get("account") # validate the address if len(recipient_address.strip()) < 3 or not is_valid_hash( recipient_address, prefix='ak'): return jsonify({"message": "bad request"}), 400 # genesys key bank_wallet_key = os.environ.get('BANK_WALLET_KEY') kp = KeyPair.from_private_key_string(bank_wallet_key) # target node Config.set_defaults( Config(external_url=os.environ.get('EPOCH_URL', "https://sdk-testnet.aepps.com"))) # amount amount = int(os.environ.get('TOPUP_AMOUNT', 250)) ttl = int(os.environ.get('TX_TTL', 100)) client = EpochClient() tx = client.spend(kp, recipient_address, amount, tx_ttl=ttl) balance = client.get_balance(account_pubkey=recipient_address) logging.info( f"top up accont {recipient_address} of {amount} tx_ttl:{ttl} tx_hash: {tx}" ) return jsonify({"tx_hash": tx, "balance": balance})
def read_keypair(wallet_path): if not os.path.exists(wallet_path): stderr(f'Path to wallet "{wallet_path}" does not exist!') sys.exit(1) password = getpass('Wallet password: ') keypair = KeyPair.read_from_dir(wallet_path, password) return keypair
def test_create_transaction_signing(): client = EpochClient() new_keypair = KeyPair.generate() receiver_address = new_keypair.get_address() keypair = KeyPair.read_from_dir('/home/tom/data/aeternity/epoch/_build/dev1/rel/epoch/data/aecore/keys/', 'secret') transaction = client.create_spend_transaction(receiver_address, 10) signed_transaction, b58signature = keypair.sign_transaction(transaction) result = client.send_signed_transaction(signed_transaction) assert result == {} current_block = client.get_latest_block() # make sure this works for very short block times client.wait_for_next_block(polling_interval=0.01) next_block = client.get_latest_block() # find the transaction that is the spend transaction we just submitted spend_tx = next(tx for tx in next_block.transactions if type(tx.tx) == SpendTx) assert spend_tx.signatures[0] == b58signature
def post_transaction(self, keypair, transaction): """ post a transaction to the chain :return: the signed_transaction """ signed_transaction, b58signature = keypair.sign_transaction(transaction) #b58 signiture is an unused variable tx_hash = KeyPair.compute_tx_hash(signed_transaction) signed_transaction_reply = self.send_signed_transaction(signed_transaction) if signed_transaction_reply.tx_hash != tx_hash: raise TransactionHashMismatch(f"Transaction hash doesn't match, expected {tx_hash} got {signed_transaction_reply.tx_hash}") return signed_transaction_reply
def wallet_create(ctx, password, force): kp = KeyPair.generate() kf = ctx.obj.get(CTX_KEY_PATH) if not force and os.path.exists(kf): click.confirm(f'Key file {kf} already exists, overwrite?', abort=True) if password is None: password = click.prompt("Enter the wallet password", default='', hide_input=True) kp.save_to_file(kf, password) _pp([('Wallet address', kp.get_address()), ('Wallet path', os.path.abspath(kf))], title='Wallet created')
def test_create_transaction_signing(): client = EpochClient() # generate a new keypair new_keypair = KeyPair.generate() receiver_address = new_keypair.get_address() # get the test keypair keypair = KeyPair.from_public_private_key_strings(PUBLIC_KEY, PRIVATE_KEY) # create a spend transaction transaction = client.create_spend_transaction(PUBLIC_KEY, receiver_address, 321) signed_transaction, b58signature = keypair.sign_transaction(transaction) # post the transaction result = client.send_signed_transaction(signed_transaction) assert result is not None assert result.tx_hash is not None print(result) # make sure this works for very short block times client.wait_for_next_block(polling_interval=0.01) spend_tx = client.get_transaction_by_transaction_hash(result.tx_hash, tx_encoding='json') assert spend_tx.transaction['signatures'][0] == b58signature
def wallet_save(ctx, private_key): try: kp = KeyPair.from_private_key_string(private_key) kf = ctx.obj.get(CTX_KEY_PATH) if os.path.exists(kf): click.confirm(f'Key file {kf} already exists, overwrite?', abort=True) password = click.prompt("Enter the wallet password", default='', hide_input=True) kp.save_to_file(kf, password) _pp([('Wallet address', kp.get_address()), ('Wallet path', os.path.abspath(kf))], title='Wallet saved') except Exception as e: _ppe(e)
def get_aeternity(): """get the epoch client and the genesis keypair from config""" # configure epoch client in case we need it epoch = EpochClient(configs=Config(external_host=epoch_node, internal_host=f"{epoch_node}/internal", secure_connection=True)) logging.info(f"using node at {epoch_node}") # load the genesis keypair gp = bar_wallet_address gk = bar_wallet_private main_wallet = KeyPair.from_public_private_key_strings(gp, gk) return epoch, main_wallet
def create(self, request, **kwargs): pub_key = request.data.get('key') amount = request.data.get('amount', 100) with redis.lock(f'get_faucet_{pub_key}', timeout=5): free_coins = FaucetTransaction.receivable_tokens(pub_key) actual_coins = min(amount, free_coins) if actual_coins > 0: epoch_host = settings.EPOCH_HOST config = Config( external_host=f'{epoch_host}:3013', internal_host=f'{epoch_host}:3113', websocket_host=f'{epoch_host}:3114' ) # connect with the Epoch node client = EpochClient(configs=config) key_pair = KeyPair.read_from_dir( settings.EPOCH_KEYS, settings.EPOCH_PASSWORD ) try: # check balance balance = client.get_balance() if balance < actual_coins: raise ParseError('Faucet is out of cash') except AException: raise ParseError('Faucet has no account') try: client.spend(pub_key, int(actual_coins), key_pair) except AException: raise ParseError(f'Spend TX failed Amount {actual_coins}') FaucetTransaction.objects.create( public_key=pub_key, amount=actual_coins ) elif amount > 0: raise ParseError('Your hourly/daily rate has been reached') return JsonResponse({'spent': actual_coins})
def _keypair(password=None): """ utility function to get the keypair from the click context :return: (keypair, keypath) """ ctx = click.get_current_context() kf = ctx.obj.get(CTX_KEY_PATH) if not os.path.exists(kf): print(f'Key file {kf} does not exits.') exit(1) try: if password is None: password = click.prompt("Enter the wallet password", default='', hide_input=True) return KeyPair.read_from_private_key(kf, password), os.path.abspath(kf) except Exception: print("Invalid password") exit(1)
def test_transfer_ownership(): client = EpochClient() name = AEName(random_domain()) name.full_claim_blocking(keypair) assert name.status == AEName.Status.CLAIMED client.wait_for_next_block() new_key_pair = KeyPair.generate() # put some coins into the account so the account is in the state tree # otherwise it couldn't become the owner of an address. client.spend(keypair, new_key_pair.get_address(), 1) client.wait_for_next_block() # now transfer the name to the other account name.transfer_ownership(keypair, new_key_pair.get_address()) assert name.status == AEName.Status.TRANSFERRED client.wait_for_next_block() # try changing the target using that new keypair name.update_status() name.update(new_key_pair, target=keypair.get_address()) client.wait_for_next_block() name.update_status() assert name.pointers != [], 'Pointers should not be empty' assert name.pointers['account_pubkey'] == new_key_pair.get_address()
def spend(amount, receipient, keypair_folder, password): keypair = KeyPair.read_from_dir(keypair_folder, password) EpochClient().spend(receipient, amount, keypair)
elif main_arg == 'oracle': oracle(args, force=force) elif main_arg == 'balance': balance(args) elif main_arg == 'height': height() elif main_arg == 'spend': if len(args) != 4: print( 'You must specify <amount>, <receipient> and <wallet-path>. ' 'Tip: escape the receipient address in single quotes to make ' 'sure that your shell does not get confused with the dollar-sign') sys.exit(1) password = getpass('Wallet password: '******'Transaction sent. Your balance will change once it was included in ' 'the blockchain.') sys.exit(1) elif main_arg == 'generate': # generate wallet keypair = KeyPair.generate() try: path = popargs(args, '--path') except ValueError: print('You must specify the --path argument') sys.exit(1) keypair.save_to_folder(path) address = keypair.get_address() print('You wallet has been generated:')
def _get_burn_key(cls): keypair = KeyPair.generate() keypair.signing_key
import logging import os from aeternity.config import Config from aeternity.signing import KeyPair logging.getLogger("requests").setLevel(logging.DEBUG) logging.getLogger("urllib3").setLevel(logging.DEBUG) PUBLIC_KEY = os.environ.get('WALLET_PUB') PRIVATE_KEY = os.environ.get('WALLET_PRIV') NODE_URL = os.environ.get('TEST_URL') NODE_URL_INTERNAL = os.environ.get('TEST_INTERNAL_URL') EPOCH_VERSION = '0.18.0' # set the key folder as environment variables KEYPAIR = KeyPair.from_public_private_key_strings(PUBLIC_KEY, PRIVATE_KEY) Config.set_defaults( Config(external_url=NODE_URL, internal_url=NODE_URL_INTERNAL))
# to run this test in other environments set the env vars as specified in the # config.py from aeternity.formatter import pretty_block from aeternity.signing import KeyPair try: # if there are no env vars set for the config, this call will fail Config() except ConfigException: # in this case we create a default config that should work on the dev # machines. Config.set_defaults( Config(external_host=3013, internal_host=3113, websocket_host=3114)) keypair = KeyPair.read_from_dir( '/home/tom/data/aeternity/epoch/_build/dev1/rel/epoch/data/aecore/keys/', 'secret') def random_domain(length=10): rand_str = ''.join( random.choice(string.ascii_letters) for _ in range(length)) return rand_str + '.aet' def test_name_validation_fails(): with raises(ValueError): AEName('test.lol') def test_name_validation_succeeds():