Esempio n. 1
0
def test_api_get_block_transaction_count_by_height():
    client = EpochClient()
    previous_height = client.get_height() - 1
    transaction_count = client.get_block_transaction_count_by_height(
        previous_height)
    print(transaction_count.count)
    assert transaction_count.count >= 0
Esempio n. 2
0
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})
Esempio n. 3
0
def test_api_get_block_by_hash():
    client = EpochClient()
    latest_block = client.get_latest_block()
    block = client.get_block_by_hash(latest_block.hash)
    # TODO: The following check should not fail. I feel that's a problem with
    # TODO: the current state of the api  --devsnd
    # assert block.hash == latest_block.hash
    assert block.height == latest_block.height
Esempio n. 4
0
def test_api_get_genesis_block():
    client = EpochClient()
    genesis_block = client.get_genesis_block()
    zero_height_block = client.get_key_block_by_height(
        0)  # these should be equivalent
    # assert type(genesis_block) == BlockWithTx
    # assert type(zero_height_block) == BlockWithTx
    assert genesis_block.height == 0
    assert zero_height_block.height == 0
def test_name_revocation():
    domain = random_domain()
    name = AEName(domain)
    name.full_claim_blocking(keypair, name_ttl=10)
    EpochClient().wait_for_next_block()
    name.revoke(keypair=keypair)
    assert name.status == AEName.Status.REVOKED
    EpochClient().wait_for_next_block()
    assert AEName(domain).is_available()
Esempio n. 6
0
def test_api_get_block_transaction_count_by_hash():
    client = EpochClient()
    # get the latest block
    block = client.get_latest_block()
    print(block)
    assert block.hash is not None
    # get the transaction count that should be a number >= 0
    txs_count = client.get_block_transaction_count_by_hash(block.hash)
    print(txs_count)
    assert txs_count.count >= 0
Esempio n. 7
0
    def __init__(self,
                 source_code,
                 bytecode=None,
                 address=None,
                 abi=SOPHIA,
                 client=None):
        """
        Initialize a contract object

        if bytecode is not provided it will be computed using the compile command.

        :param source_code: the source code of the contract
        :param bytecode: the bytecode of the contract
        :param address: the address of the contract
        :param abi: the abi, default 'sofia'
        :param client: the epoch client to use
        """
        if client is None:
            client = EpochClient()
        self.client = client
        self.abi = abi
        self.source_code = source_code
        self.bytecode = bytecode
        self.address = address
        if self.bytecode is None:
            self.bytecode = self.compile(self.source_code)
def test_name_status_unavailable():
    # claim a domain
    domain = random_domain()
    occupy_name = AEName(domain)
    occupy_name.full_claim_blocking(keypair, name_ttl=70)
    # wait for the state to propagate in the block chain
    EpochClient().wait_for_next_block()
    same_name = AEName(domain)
    assert not same_name.is_available()
Esempio n. 9
0
def test_cli_inspect_block_by_hash():
    height = EpochClient().get_height()
    output = call_aecli('--quiet', 'inspect', 'height', str(height))
    lines = output.split('\n')
    # retrieve the block hash
    block_hash = lines[0]
    output = call_aecli('--quiet', 'inspect', 'block', block_hash)
    blines = output.split('\n')
    assert lines[0] == blines[0]
    assert lines[1] == blines[1]
    assert lines[2] == blines[2]
    assert lines[3] == blines[3]
Esempio n. 10
0
def _epoch_cli():
    try:
        ctx = click.get_current_context()
        # set the default configuration
        Config.set_defaults(
            Config(external_url=ctx.obj.get(CTX_EPOCH_URL),
                   internal_url=ctx.obj.get(CTX_EPOCH_URL_INTERNAL),
                   websocket_url=ctx.obj.get(CTX_EPOCH_URL_WEBSOCKET)))
    except ConfigException as e:
        print("Configuration error: ", e)
        exit(1)
    # load the epoch client
    return EpochClient()
Esempio n. 11
0
def test_oracle_query_received():
    client = EpochClient()
    weather_oracle = WeatherOracle(
        query_format="{'city': str}",
        response_format="{'temp_c': int}",
        default_query_fee=0,
        default_fee=10,
        default_ttl=50,
        default_query_ttl=2,
        default_response_ttl=2,
    )
    client.register_oracle(weather_oracle)
    client.listen_until(weather_oracle.is_ready, timeout=5)
    weather_query = WeatherQuery(
        oracle_pubkey=weather_oracle.oracle_id,
        query_fee=0,
        fee=10,
        query_ttl=2,
        response_ttl=2,
    )
    client.mount(weather_query)
    weather_query.query("{'city': 'Berlin'}")
    client.listen_until(lambda: weather_query.response_received, timeout=5)
Esempio n. 12
0
    def __init__(self, domain, client=None):
        if client is None:
            client = EpochClient()
        self.__class__.validate_name(domain)

        self.client = client
        self.domain = domain.lower()
        self.status = NameStatus.UNKNOWN
        # set after preclaimed:
        self.preclaimed_block_height = None
        self.preclaimed_commitment_hash = None
        self.preclaim_salt = None
        # set after claimed
        self.name_ttl = 0
        self.pointers = []
Esempio n. 13
0
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
Esempio n. 14
0
def test_oracle_registration():
    client = EpochClient()
    weather_oracle = WeatherOracle(
        query_format="{'city': str}",
        response_format="{'temp_c': int}",
        default_query_fee=0,
        default_fee=10,
        default_ttl=50,
        default_query_ttl=2,
        default_response_ttl=2,
    )
    client.register_oracle(weather_oracle)
    client.listen_until(weather_oracle.is_ready, timeout=5)
    assert weather_oracle.oracle_id is not None
Esempio n. 15
0
def _epoch_cli():
    try:
        ctx = click.get_current_context()
        # set the default configuration
        url = ctx.obj.get(CTX_EPOCH_URL)
        url_i = ctx.obj.get(CTX_EPOCH_URL_DEBUG)
        url_i = url_i if url_i is not None else url
        config.Config.set_defaults(
            config.Config(
                external_url=url,
                internal_url=url_i,
                force_compatibility=ctx.obj.get(CTX_FORCE_COMPATIBILITY)))
    except config.ConfigException as e:
        print("Configuration error: ", e)
        exit(1)
    except config.UnsupportedEpochVersion as e:
        print(e)
        exit(1)

    # load the epoch client
    return EpochClient(blocking_mode=ctx.obj.get(CTX_BLOCKING_MODE))
Esempio n. 16
0
def test_name_update():
    client = EpochClient()
    # claim a domain
    domain = random_domain()
    print(f"domain is {domain}")
    name = AEName(domain)
    print("Claim name ", domain)
    name.full_claim_blocking(keypair, name_ttl=70)
    print("got next block")
    client.wait_n_blocks(2)
    print("got next block")
    assert not AEName(domain).is_available(), 'The name should be claimed now'
    name.update_status()
    client.wait_n_blocks(2)
    name.update_status()
    print("claimed name", name)
    assert name.pointers != [], 'Pointers should not be empty'
    assert name.pointers['account_pubkey'] == keypair.get_address()
Esempio n. 17
0
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
Esempio n. 18
0
def test_api_get_info():
    client = EpochClient()
    info = client.get_info()
    assert info.last_30_blocks_time[0].time_delta_to_parent > 0
Esempio n. 19
0
def test_api_get_latest_block():
    client = EpochClient()
    block = client.get_latest_block()
    # assert type(block) == BlockWithTx
    assert block.height > 0
Esempio n. 20
0
def test_cli_inspect_block_by_height():
    height = EpochClient().get_height()
    output = call_aecli('--quiet', 'inspect', 'height', str(height))
    lines = output.split('\n')
    assert lines[0].startswith("bh$")
    assert lines[1] == str(height)
Esempio n. 21
0
def test_api_get_version():
    client = EpochClient()
    assert client.get_version() == EPOCH_VERSION
Esempio n. 22
0
def test_api_get_balance():
    client = EpochClient()
    assert client.get_balance(account_pubkey=PUBLIC_KEY) > 0
Esempio n. 23
0
def test_name_transfer_ownership():
    client = EpochClient()
    name = AEName(random_domain())
    name.full_claim_blocking(keypair, name_ttl=70)
    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=new_key_pair.get_address(), name_ttl=10)
    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()
Esempio n. 24
0
def rest_faucet(recipient_address):
    """top up an account"""
    amount = int(os.environ.get('TOPUP_AMOUNT', 250))
    ttl = int(os.environ.get('TX_TTL', 100))
    try:
        # validate the address
        logging.info(f"Top up request for {recipient_address}")
        if not is_valid_hash(recipient_address, prefix='ak'):
            return jsonify({"message":
                            "The provided account is not valid"}), 400

        # genesys key
        bank_wallet_key = os.environ.get('FAUCET_ACCOUNT_PRIV_KEY')
        kp = Account.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"),
                internal_url=os.environ.get('EPOCH_URL_DEBUG',
                                            "https://sdk-testnet.aepps.com"),
                network_id=os.environ.get('NETWORK_ID', "ae_devnet"),
            ))
        # payload
        payload = os.environ.get('TX_PAYLOAD', "Faucet Tx")
        # execute the spend transaction
        client = EpochClient()
        _, _, _, tx = client.spend(kp,
                                   recipient_address,
                                   amount,
                                   payload=payload,
                                   tx_ttl=ttl)
        balance = client.get_account_by_pubkey(
            pubkey=recipient_address).balance
        logging.info(
            f"Top up accont {recipient_address} of {amount} tx_ttl: {ttl} tx_hash: {tx} completed"
        )

        # telegram bot notifications
        enable_telegaram = os.environ.get('TELEGRAM_API_TOKEN', False)
        if enable_telegaram:
            token = os.environ.get('TELEGRAM_API_TOKEN', None)
            chat_id = os.environ.get('TELEGRAM_CHAT_ID', None)
            node = os.environ.get('EPOCH_URL',
                                  "https://sdk-testnet.aepps.com").replace(
                                      "https://", "")
            if token is None or chat_id is None:
                logging.warning(
                    f"missing chat_id ({chat_id}) or token {token} for telegram integration"
                )
            bot = telegram.Bot(token=token)
            bot.send_message(
                chat_id=chat_id,
                text=
                f"Account `{recipient_address}` credited with {amount} tokens on `{node}`. (tx hash: `{tx}`)",
                parse_mode=telegram.ParseMode.MARKDOWN)
        return jsonify({"tx_hash": tx, "balance": balance})
    except OpenAPIClientException as e:
        logging.error(
            f"Api error: top up accont {recipient_address} of {amount} failed with error",
            e)
        return jsonify({
            "message":
            "The node is temporarily unavailable, contact aepp-dev[at]aeternity.com"
        }), 503
    except Exception as e:
        logging.error(
            f"Generic error: top up accont {recipient_address} of {amount} failed with error",
            e)
        return jsonify({
            "message":
            "Unknow error, please contact contact aepp-dev[at]aeternity.com"
        }), 500
Esempio n. 25
0
def test_api_get_block_by_heigt():
    client = EpochClient()
    height = client.get_height()
    block = client.get_key_block_by_height(height)
    # assert type(block) == BlockWithTx
    assert block.height > 0
Esempio n. 26
0
from aeternity.epoch import EpochClient
from aeternity.config import Config

import sys

Config.set_defaults(Config(external_host=3013, internal_host=3113, websocket_host=3114))

recipient, amount = sys.argv[1:3]

amount = int(amount)

epoch = EpochClient()

epoch.spend(recipient, amount)
Esempio n. 27
0
 def __init__(self, code, abi, client=None):
     if client is None:
         client = EpochClient()
     self.client = client
     self.code = code
     self.abi = abi