Example #1
0
def _public_get_address_balance(ctx, address):
    address = address[1:]
    stub = qrl_pb2_grpc.PublicAPIStub(ctx.obj.channel_public)
    getAddressStateReq = qrl_pb2.GetAddressStateReq(
        address=bytes(hstr2bin(address)))
    getAddressStateResp = stub.GetAddressState(getAddressStateReq, timeout=1)
    return getAddressStateResp.state.balance
Example #2
0
def collect(ctx, msg_id):
    """
    Collects and returns the list of encrypted ephemeral message corresponding to msg_id
    :param ctx:
    :param msg_id:
    :return:
    """
    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    stub = qrl_pb2_grpc.PublicAPIStub(ctx.obj.channel_public)

    try:
        collectEphemeralMessageReq = qrl_pb2.CollectEphemeralMessageReq(
            msg_id=bytes(hstr2bin(msg_id)))
        collectEphemeralMessageResp = stub.CollectEphemeralMessage(
            collectEphemeralMessageReq, timeout=5)

        print(
            len(collectEphemeralMessageResp.ephemeral_metadata.
                encrypted_ephemeral_message_list))
        for message in collectEphemeralMessageResp.ephemeral_metadata.encrypted_ephemeral_message_list:
            print('%s' % (message.payload, ))
    except Exception as e:
        print("Error {}".format(str(e)))
Example #3
0
def main():
    args = parse_arguments()

    qrl_dir_post_fix = ''
    copy_files = []
    if args.network_type == 'testnet':
        qrl_dir_post_fix = '-testnet'
        package_directory = os.path.dirname(os.path.abspath(__file__))
        copy_files.append(
            os.path.join(package_directory, 'network/testnet/genesis.yml'))
        copy_files.append(
            os.path.join(package_directory, 'network/testnet/config.yml'))

    config.user.qrl_dir = os.path.expanduser(
        os.path.normpath(args.qrl_dir) + qrl_dir_post_fix)
    config.create_path(config.user.qrl_dir, copy_files)
    config.user.load_yaml(config.user.config_path)

    global payment_slaves, payment_xmss
    global mining_stub, public_stub
    mining_stub = qrlmining_pb2_grpc.MiningAPIStub(
        grpc.insecure_channel('{0}:{1}'.format(config.user.mining_api_host,
                                               config.user.mining_api_port)))
    public_stub = qrl_pb2_grpc.PublicAPIStub(
        grpc.insecure_channel('{0}:{1}'.format(config.user.public_api_host,
                                               config.user.public_api_port),
                              options=[('grpc.max_receive_message_length',
                                        10485760)]))
    payment_xmss = None
    payment_slaves = read_slaves(config.user.mining_pool_payment_wallet_path)
    app.run(host=config.user.grpc_proxy_host,
            port=config.user.grpc_proxy_port,
            threaded=False)
Example #4
0
def send_eph_message(ctx, msg_id, ttl, ttr, enc_aes256_symkey, nonce, payload):
    """
    Creates & Push Ephemeral Message
    :param ctx:
    :param msg_id:
    :param ttl:
    :param ttr:
    :param enc_aes256_symkey:
    :param nonce:
    :param payload:
    :return:
    """
    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    stub = qrl_pb2_grpc.PublicAPIStub(ctx.obj.channel_public)

    if len(enc_aes256_symkey):
        enc_aes256_symkey = enc_aes256_symkey.encode()

    payload = payload.encode()

    encrypted_ephemeral_msg = EncryptedEphemeralMessage.create(
        bytes(hstr2bin(msg_id)), ttl, ttr, nonce, payload, enc_aes256_symkey)

    try:
        ephemeralMessageReq = qrl_pb2.PushEphemeralMessageReq(
            ephemeral_message=encrypted_ephemeral_msg.pbdata)
        ephemeralMessageResp = stub.PushEphemeralMessage(ephemeralMessageReq,
                                                         timeout=5)

        print(ephemeralMessageResp.error_code)
    except Exception as e:
        print("Error {}".format(str(e)))
Example #5
0
def api_proxy(api_method_name):
    """
    Proxy JSON RPC requests to the gRPC server as well as converts back gRPC response
    to JSON.
    :param api_method_name:
    :return:
    """
    stub = qrl_pb2_grpc.PublicAPIStub(
        grpc.insecure_channel('{}:{}'.format(config.user.public_api_host,
                                             config.user.public_api_port)))
    public_api = qrl_pb2.DESCRIPTOR.services_by_name['PublicAPI']
    api_method = public_api.FindMethodByName(api_method_name)
    api_request = getattr(qrl_pb2, api_method.input_type.name)()

    for arg in request.args:
        if arg not in api_method.input_type.fields_by_name:
            raise Exception('Invalid args %s', arg)
        data_type = type(getattr(api_request, arg))
        if data_type == bool and request.args[arg].lower() == 'false':
            continue
        value = data_type(request.args.get(arg, type=data_type))
        setattr(api_request, arg, value)

    resp = getattr(stub, api_method_name)(api_request, timeout=10)
    return Response(response=MessageToJson(resp, sort_keys=True),
                    status=200,
                    mimetype='application/json')
Example #6
0
def slave_tx_generate(ctx, src, addr_from, number_of_slaves, access_type, fee, pk, otsidx):
    """
    Generates Slave Transaction for the wallet
    """
    try:
        address_src, src_xmss = _select_wallet(ctx, src)
        src_xmss.set_ots_index(otsidx)
        if len(addr_from.strip()) == 0:
            addr_from = address_src
        if src_xmss:
            address_src_pk = src_xmss.pk
        else:
            address_src_pk = pk.encode()

        fee_shor = int(fee * 1.e9)
    except Exception as e:
        click.echo("Error validating arguments")
        quit(1)

    slave_xmss = []
    slave_pks = []
    access_types = []
    slave_xmss_seed = []
    if number_of_slaves > 100:
        click.echo("Error: Max Limit for the number of slaves is 100")
        quit(1)

    for i in range(number_of_slaves):
        print("Generating Slave #" + str(i + 1))
        xmss = XMSS.from_height(config.dev.xmss_tree_height)
        slave_xmss.append(xmss)
        slave_xmss_seed.append(xmss.extended_seed)
        slave_pks.append(xmss.pk)
        access_types.append(access_type)
        print("Successfully Generated Slave %s/%s" % (str(i + 1), number_of_slaves))

    channel = grpc.insecure_channel(ctx.obj.node_public_address)
    stub = qrl_pb2_grpc.PublicAPIStub(channel)
    # FIXME: This could be problematic. Check
    slaveTxnReq = qrl_pb2.SlaveTxnReq(address_from=addr_from,
                                      slave_pks=slave_pks,
                                      access_types=access_types,
                                      fee=fee_shor,
                                      xmss_pk=address_src_pk, )

    try:
        slaveTxnResp = stub.GetSlaveTxn(slaveTxnReq, timeout=5)
        tx = Transaction.from_pbdata(slaveTxnResp.transaction_unsigned)
        tx.sign(src_xmss)
        with open('slaves.json', 'w') as f:
            json.dump([bin2hstr(src_xmss.address), slave_xmss_seed, tx.to_json()], f)
        click.echo('Successfully created slaves.json')
        click.echo('Move slaves.json file from current directory to the mining node inside ~/.qrl/')
    except grpc.RpcError as e:
        click.echo(e.details())
        quit(1)
    except Exception as e:
        click.echo("Unhandled error: {}".format(str(e)))
        quit(1)
Example #7
0
def tx_token(ctx, src, symbol, name, owner, decimals, fee, ots_key_index):
    """
    Create Token Transaction, that results into the formation of new token if accepted.
    """

    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    initial_balances = []

    while True:
        address = click.prompt('Address ', default='')
        if address == '':
            break
        amount = int(click.prompt('Amount ')) * (10**int(decimals))
        initial_balances.append(
            qrl_pb2.AddressAmount(address=address.encode(), amount=amount))

    try:
        address_src, src_xmss = _select_wallet(ctx, src)
        if not src_xmss:
            click.echo("A local wallet is required to sign the transaction")
            quit(1)

        address_src_pk = src_xmss.pk()
        src_xmss.set_index(int(ots_key_index))
        address_src_otsidx = src_xmss.get_index()
        address_owner = owner.encode()
        # FIXME: This could be problematic. Check
        fee_shor = int(fee * 1.e8)
    except KeyboardInterrupt as e:
        click.echo("Error validating arguments")
        quit(1)

    try:
        channel = grpc.insecure_channel(ctx.obj.node_public_address)
        stub = qrl_pb2_grpc.PublicAPIStub(channel)

        tx = TokenTransaction.create(addr_from=address_src,
                                     symbol=symbol.encode(),
                                     name=name.encode(),
                                     owner=address_owner,
                                     decimals=decimals,
                                     initial_balances=initial_balances,
                                     fee=fee_shor,
                                     xmss_pk=address_src_pk,
                                     xmss_ots_index=address_src_otsidx)

        tx.sign(src_xmss)

        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)
        pushTransactionResp = stub.PushTransaction(pushTransactionReq,
                                                   timeout=5)

        print(pushTransactionResp.some_response)
    except Exception as e:
        print("Error {}".format(str(e)))
Example #8
0
def connect_client(address):
    """ Connect to the remote client """
    channel = grpc.insecure_channel(address,
                                    options=[
                                        ('grpc.max_receive_message_length',
                                         4194304 * 8)
                                    ])
    return qrl_pb2_grpc.PublicAPIStub(channel)
Example #9
0
 def __init__(self):
     self._wallet_path = os.path.join(config.user.wallet_dir,
                                      'walletd.json')
     self._public_stub = qrl_pb2_grpc.PublicAPIStub(
         grpc.insecure_channel(config.user.public_api_server))
     self._wallet = None
     self._passphrase = None
     self.load_wallet()
Example #10
0
def main():
    global payment_slaves, payment_xmss
    global mining_stub, public_stub
    mining_stub = qrlmining_pb2_grpc.MiningAPIStub(
        grpc.insecure_channel('{0}:{1}'.format(config.user.mining_api_host,
                                               config.user.mining_api_port)))
    public_stub = qrl_pb2_grpc.PublicAPIStub(
        grpc.insecure_channel('{0}:{1}'.format(config.user.public_api_host,
                                               config.user.public_api_port)))
    payment_xmss = None
    payment_slaves = read_slaves(config.user.mining_pool_payment_wallet_path)
    app.run(host=config.user.grpc_proxy_host, port=config.user.grpc_proxy_port)
Example #11
0
def tx_transfertoken(ctx, src, master, token_txhash, dst, amounts, decimals,
                     fee, ots_key_index):
    """
    Create Token Transaction, that results into the formation of new token if accepted.
    """

    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    try:
        _, src_xmss = _select_wallet(ctx, src)
        if not src_xmss:
            click.echo("A local wallet is required to sign the transaction")
            quit(1)

        address_src_pk = src_xmss.pk
        src_xmss.set_ots_index(int(ots_key_index))
        addresses_dst = []
        for addr in dst.split(' '):
            addresses_dst.append(bytes(hstr2bin(addr[1:])))

        shor_amounts = []
        for amount in amounts.split(' '):
            shor_amounts.append(int(float(amount) * (10**int(decimals))))

        bin_token_txhash = bytes(hstr2bin(token_txhash))
        # FIXME: This could be problematic. Check
        fee_shor = int(fee * 1.e9)
    except KeyboardInterrupt as e:
        click.echo("Error validating arguments")
        quit(1)

    try:
        channel = grpc.insecure_channel(ctx.obj.node_public_address)
        stub = qrl_pb2_grpc.PublicAPIStub(channel)

        tx = TransferTokenTransaction.create(token_txhash=bin_token_txhash,
                                             addrs_to=addresses_dst,
                                             amounts=amounts,
                                             fee=fee_shor,
                                             xmss_pk=address_src_pk,
                                             master_addr=master.encode())
        tx.sign(src_xmss)

        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)
        pushTransactionResp = stub.PushTransaction(pushTransactionReq,
                                                   timeout=5)

        print(pushTransactionResp.error_code)
    except Exception as e:
        print("Error {}".format(str(e)))
Example #12
0
def tx_transfer(ctx, src, master, dst, amounts, fee, ots_key_index):
    """
    Transfer coins from src to dst
    """
    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    try:
        _, src_xmss = _select_wallet(ctx, src)
        if not src_xmss:
            click.echo("A local wallet is required to sign the transaction")
            quit(1)

        address_src_pk = src_xmss.pk
        src_xmss.set_ots_index(ots_key_index)
        addresses_dst = []
        for addr in dst.split(' '):
            addresses_dst.append(bytes(hstr2bin(addr[1:])))

        shor_amounts = []
        for amount in amounts.split(' '):
            shor_amounts.append(int(float(amount) * 1.e9))

        fee_shor = int(fee * 1.e9)
    except Exception:
        click.echo("Error validating arguments")
        quit(1)

    try:
        channel = grpc.insecure_channel(ctx.obj.node_public_address)
        stub = qrl_pb2_grpc.PublicAPIStub(channel)
        transferCoinsReq = qrl_pb2.TransferCoinsReq(
            addresses_to=addresses_dst,
            amounts=shor_amounts,
            fee=fee_shor,
            xmss_pk=address_src_pk,
            master_addr=master.encode())

        transferCoinsResp = stub.TransferCoins(transferCoinsReq, timeout=5)

        tx = Transaction.from_pbdata(
            transferCoinsResp.extended_transaction_unsigned.tx)
        tx.sign(src_xmss)

        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)
        pushTransactionResp = stub.PushTransaction(pushTransactionReq,
                                                   timeout=5)

        print(pushTransactionResp)
    except Exception as e:
        print("Error {}".format(str(e)))
        def func_monitor_log():
            node_tracker = NodeLogTracker(mocknet)

            while mocknet.uptime < 30:
                node_tracker.track()
                time.sleep(0.01)

            if node_tracker.synced_count() < mocknet.node_count:
                raise Exception("Nodes did not sync")

            protobuf_strategies = modules_to_strategies(qrl_pb2)
            publicapi = qrl_pb2._PUBLICAPI

            self.assertTrue(publicapi.methods, "methods is empty")
            req_attrs = []
            for m in publicapi.methods:
                req_attrs.append(ReqAttrNames(m.name, m.input_type.name))

            stubs = [
                qrl_pb2_grpc.PublicAPIStub(
                    grpc.insecure_channel("127.0.0.1:10002"))
            ]

            while mocknet.uptime < 180:
                try:
                    node_tracker.track()
                    if node_tracker.synced_count() == mocknet.node_count:
                        rand_stub = choice(stubs)
                        rand_req = choice(req_attrs)
                        req_strategy = protobuf_strategies[getattr(
                            qrl_pb2, rand_req.arg)]
                        req_arg = req_strategy.example()
                        req_method = getattr(rand_stub, rand_req.method)

                        try:
                            resp = req_method(req_arg)
                        except grpc.RpcError as err:
                            print('*******************************')
                            print("Time    : %s" % mocknet.uptime)
                            print("Method  : %s" % rand_req.method)
                            print("error   : %s" % err)
                            print("code    : %s" % err.code())
                            print("details : %s" % err.details())
                            print('*******************************\n')
                            if err.code() == grpc.StatusCode.UNKNOWN:
                                raise
                        except Exception as e:
                            pass
                        time.sleep(1)

                except Empty:
                    pass
Example #14
0
def state(ctx):
    """
    Shows Information about a Node's State
    """
    channel = grpc.insecure_channel(ctx.obj.node_public_address)
    stub = qrl_pb2_grpc.PublicAPIStub(channel)

    nodeStateResp = stub.GetNodeState(qrl_pb2.GetNodeStateReq())

    if ctx.obj.json:
        click.echo(MessageToJson(nodeStateResp))
    else:
        click.echo(nodeStateResp)
Example #15
0
def tx_transfertoken(ctx, src, token_txhash, dst, amount, decimals, fee,
                     ots_key_index):
    """
    Create Token Transaction, that results into the formation of new token if accepted.
    """

    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    try:
        address_src, src_xmss = _select_wallet(ctx, src)
        if not src_xmss:
            click.echo("A local wallet is required to sign the transaction")
            quit(1)

        address_src_pk = src_xmss.pk()
        src_xmss.set_index(int(ots_key_index))
        address_src_otsidx = src_xmss.get_index()
        address_dst = dst.encode()
        bin_token_txhash = bytes(hstr2bin(token_txhash))
        # FIXME: This could be problematic. Check
        amount = int(amount * (10**int(decimals)))
        fee_shor = int(fee * 1.e8)
    except KeyboardInterrupt as e:
        click.echo("Error validating arguments")
        quit(1)

    try:
        channel = grpc.insecure_channel(ctx.obj.node_public_address)
        stub = qrl_pb2_grpc.PublicAPIStub(channel)

        tx = TransferTokenTransaction.create(addr_from=address_src,
                                             token_txhash=bin_token_txhash,
                                             addr_to=address_dst,
                                             amount=amount,
                                             fee=fee_shor,
                                             xmss_pk=address_src_pk,
                                             xmss_ots_index=address_src_otsidx)
        tx.sign(src_xmss)

        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)
        pushTransactionResp = stub.PushTransaction(pushTransactionReq,
                                                   timeout=5)

        print(pushTransactionResp.some_response)
    except Exception as e:
        print("Error {}".format(str(e)))
Example #16
0
def tx_transfer(ctx, src, dst, amount, fee):
    """
    Transfer coins from src to dst
    """
    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    try:
        address_src, src_xmss = _select_wallet(ctx, src)
        if not src_xmss:
            click.echo("A local wallet is required to sign the transaction")
            quit(1)

        address_src_pk = src_xmss.pk()
        address_src_otsidx = src_xmss.get_index()
        address_dst = dst.encode()
        # FIXME: This could be problematic. Check
        amount_shor = int(amount * 1.e8)
        fee_shor = int(fee * 1.e8)
    except Exception as e:
        click.echo("Error validating arguments")
        quit(1)

    try:
        channel = grpc.insecure_channel(ctx.obj.node_public_address)
        stub = qrl_pb2_grpc.PublicAPIStub(channel)
        transferCoinsReq = qrl_pb2.TransferCoinsReq(
            address_from=address_src,
            address_to=address_dst,
            amount=amount_shor,
            fee=fee_shor,
            xmss_pk=address_src_pk,
            xmss_ots_index=address_src_otsidx)

        transferCoinsResp = stub.TransferCoins(transferCoinsReq, timeout=5)

        tx = Transaction.from_pbdata(transferCoinsResp.transaction_unsigned)
        tx.sign(src_xmss.xmss)

        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)
        pushTransactionResp = stub.PushTransaction(pushTransactionReq,
                                                   timeout=5)

        print(pushTransactionResp.some_response)
    except Exception as e:
        print("Error {}".format(str(e)))
Example #17
0
def tx_prepare(ctx, src, master, dst, amounts, fee, pk):
    """
    Request a tx blob (unsigned) to transfer from src to dst (uses local wallet)
    """
    try:
        _, src_xmss = _select_wallet(ctx, src)
        if src_xmss:
            address_src_pk = src_xmss.pk
        else:
            address_src_pk = pk.encode()

        addresses_dst = []
        for addr in dst.split(' '):
            addresses_dst.append(bytes(hstr2bin(addr[1:])))

        shor_amounts = []
        for amount in amounts.split(' '):
            shor_amounts.append(int(float(amount) * 1.e9))
        fee_shor = int(fee * 1.e9)
    except Exception as e:
        click.echo("Error validating arguments")
        quit(1)

    channel = grpc.insecure_channel(ctx.obj.node_public_address)
    stub = qrl_pb2_grpc.PublicAPIStub(channel)
    # FIXME: This could be problematic. Check
    transferCoinsReq = qrl_pb2.TransferCoinsReq(addresses_to=addresses_dst,
                                                amounts=shor_amounts,
                                                fee=fee_shor,
                                                xmss_pk=address_src_pk,
                                                master_addr=master.encode())

    try:
        transferCoinsResp = stub.TransferCoins(transferCoinsReq, timeout=5)
    except grpc.RpcError as e:
        click.echo(e.details())
        quit(1)
    except Exception as e:
        click.echo("Unhandled error: {}".format(str(e)))
        quit(1)

    txblob = bin2hstr(
        transferCoinsResp.extended_transaction_unsigned.tx.SerializeToString())
    print(txblob)
Example #18
0
def send():
    """
    Transfer coins
    """
    channel = get_channel()
    stub = qrl_pb2_grpc.PublicAPIStub(channel)

    walletObj = get_wallet_obj()
    print_wallet_list(walletObj)
    selected_wallet = select_wallet(walletObj)
    if not selected_wallet:
        return

    address_to = click.prompt('Enter Address To', type=str)
    amount = click.prompt('Enter Amount', type=float)
    fee = click.prompt('Fee', type=float)

    address_to = address_to.encode()
    int_amount = int(amount * 10**8)
    int_fee = int(fee * 10**8)

    try:
        transferCoinsReq = qrl_pb2.TransferCoinsReq(
            address_from=selected_wallet.address,
            address_to=address_to,
            amount=int_amount,
            fee=int_fee,
            xmss_pk=selected_wallet.xmss.pk(),
            xmss_ots_index=selected_wallet.xmss.get_index())

        f = stub.TransferCoins.future(transferCoinsReq, timeout=5)
        transferCoinsResp = f.result(timeout=5)

        tx = Transaction.from_pbdata(transferCoinsResp.transaction_unsigned)
        tx.sign(selected_wallet.xmss)
        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)

        f = stub.PushTransaction.future(pushTransactionReq, timeout=5)
        pushTransactionResp = f.result(timeout=5)

        print('%s' % (pushTransactionResp.some_response, ))
    except Exception as e:
        print("Error {}".format(str(e)))
Example #19
0
def tx_prepare(ctx, src, dst, amount, fee, pk, otsidx):
    """
    Request a tx blob (unsigned) to transfer from src to dst (uses local wallet)
    """
    try:
        address_src, src_xmss = _select_wallet(ctx, src)
        if src_xmss:
            address_src_pk = src_xmss.pk()
            address_src_otsidx = src_xmss.get_index()
        else:
            address_src_pk = pk.encode()
            address_src_otsidx = int(otsidx)

        address_dst = dst.encode()
        amount_shor = int(amount * 1.e8)
        fee_shor = int(fee * 1.e8)
    except Exception as e:
        click.echo("Error validating arguments")
        quit(1)

    channel = grpc.insecure_channel(ctx.obj.node_public_address)
    stub = qrl_pb2_grpc.PublicAPIStub(channel)
    # FIXME: This could be problematic. Check
    transferCoinsReq = qrl_pb2.TransferCoinsReq(
        address_from=address_src,
        address_to=address_dst,
        amount=amount_shor,
        fee=fee_shor,
        xmss_pk=address_src_pk,
        xmss_ots_index=address_src_otsidx)

    try:
        transferCoinsResp = stub.TransferCoins(transferCoinsReq, timeout=5)
    except grpc.RpcError as e:
        click.echo(e.details())
        quit(1)
    except Exception as e:
        click.echo("Unhandled error: {}".format(str(e)))
        quit(1)

    txblob = bin2hstr(
        transferCoinsResp.transaction_unsigned.SerializeToString())
    print(txblob)
Example #20
0
def tx_latticepk(ctx, src, master, kyber_pk, dilithium_pk, fee, ots_key_index):
    """
    Create Lattice Public Keys Transaction
    """
    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    stub = qrl_pb2_grpc.PublicAPIStub(ctx.obj.channel_public)

    try:
        _, src_xmss = _select_wallet(ctx, src)
        if not src_xmss:
            click.echo("A local wallet is required to sign the transaction")
            quit(1)

        address_src_pk = src_xmss.pk
        src_xmss.set_ots_index(ots_key_index)
        kyber_pk = kyber_pk.encode()
        dilithium_pk = dilithium_pk.encode()
        # FIXME: This could be problematic. Check
        fee_shor = int(fee * 1.e9)
    except Exception:
        click.echo("Error validating arguments")
        quit(1)

    try:
        tx = LatticePublicKey.create(fee=fee_shor,
                                     kyber_pk=kyber_pk,
                                     dilithium_pk=dilithium_pk,
                                     xmss_pk=address_src_pk,
                                     master_addr=master.encode())
        tx.sign(src_xmss)

        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)
        pushTransactionResp = stub.PushTransaction(pushTransactionReq,
                                                   timeout=5)

        print(pushTransactionResp.error_code)
    except Exception as e:
        print("Error {}".format(str(e)))
Example #21
0
        def state_check():
            public_api_addresses = mocknet.public_addresses
            for public_api_address in public_api_addresses:
                channel_public = grpc.insecure_channel(public_api_address)
                stub = qrl_pb2_grpc.PublicAPIStub(channel_public)

                # TODO: Check coins emitted, coins total supply, epoch, block_last_reward
                # response = stub.GetStats(request=qrl_pb2.GetStatsReq())

                response = stub.GetNodeState(request=qrl_pb2.GetNodeStateReq())
                if response.info.block_height != LAST_BLOCK_NUMBER:
                    raise Exception('Expected Blockheight %s \n Found blockheight %s',
                                    LAST_BLOCK_NUMBER,
                                    response.info.block_height)

                if response.info.block_last_hash != bytes(hstr2bin(LAST_BLOCK_HEADERHASH)):
                    raise Exception('Last Block Headerhash mismatch\n'
                                    'Expected : %s\n', bin2hstr(response.info.block_last_hash),
                                    'Found : %s ', LAST_BLOCK_HEADERHASH)

            return True
Example #22
0
def token_list(ctx, owner):
    """
    Create Token Transaction, that results into the formation of new token if accepted.
    """

    if not ctx.obj.remote:
        click.echo('This command is unsupported for local wallets')
        return

    try:

        channel = grpc.insecure_channel(ctx.obj.node_public_address)
        stub = qrl_pb2_grpc.PublicAPIStub(channel)
        addressStateReq = qrl_pb2.GetAddressStateReq(address=owner.encode())
        addressStateResp = stub.GetAddressState(addressStateReq, timeout=5)

        for token_hash in addressStateResp.state.tokens:
            click.echo('Hash: %s' % (token_hash,))
            click.echo('Balance: %s' % (addressStateResp.state.tokens[token_hash],))
    except Exception as e:
        print("Error {}".format(str(e)))
Example #23
0
def tx_push(ctx, txblob):
    tx = None
    try:
        txbin = bytes(hstr2bin(txblob))
        pbdata = qrl_pb2.Transaction()
        pbdata.ParseFromString(txbin)
        tx = Transaction.from_pbdata(pbdata)
    except Exception as e:
        click.echo("tx blob is not valid")
        quit(1)

    tmp_json = tx.to_json()
    # FIXME: binary fields are represented in base64. Improve output
    print(tmp_json)
    if len(tx.signature) == 0:
        click.echo('Signature missing')
        quit(1)

    channel = grpc.insecure_channel(ctx.obj.node_public_address)
    stub = qrl_pb2_grpc.PublicAPIStub(channel)
    pushTransactionReq = qrl_pb2.PushTransactionReq(transaction_signed=tx.pbdata)
    pushTransactionResp = stub.PushTransaction(pushTransactionReq, timeout=5)
    print(pushTransactionResp.error_code)
Example #24
0
def lattice():
    channel = get_channel()
    stub = qrl_pb2_grpc.PublicAPIStub(channel)

    walletObj = get_wallet_obj()
    print_wallet_list(walletObj)
    selected_wallet = select_wallet(walletObj)
    if not selected_wallet:
        return

    lattice_public_key = click.prompt('Enter Lattice Public Key', type=str)

    lattice_public_key = lattice_public_key.encode()

    try:
        latticePublicKeyTxnReq = qrl_pb2.LatticePublicKeyTxnReq(
            address_from=selected_wallet.address,
            kyber_pk=lattice_public_key,
            tesla_pk=lattice_public_key,
            xmss_pk=selected_wallet.xmss.pk(),
            xmss_ots_index=selected_wallet.xmss.get_index())

        f = stub.GetLatticePublicKeyTxn.future(latticePublicKeyTxnReq,
                                               timeout=5)
        latticePublicKeyResp = f.result(timeout=5)

        tx = Transaction.from_pbdata(latticePublicKeyResp.transaction_unsigned)
        tx.sign(selected_wallet.xmss)
        pushTransactionReq = qrl_pb2.PushTransactionReq(
            transaction_signed=tx.pbdata)

        f = stub.PushTransaction.future(pushTransactionReq, timeout=5)
        pushTransactionResp = f.result(timeout=5)

        print('%s' % (pushTransactionResp.some_response, ))
    except Exception as e:
        print("Error {}".format(str(e)))
Example #25
0
        return None

    tx = TransferTransaction.create(addrs_to=addrs_to,
                                    amounts=amounts,
                                    fee=fee,
                                    xmss_pk=xmss.pk,
                                    master_addr=payment_slaves[0])

    tx.sign(xmss)

    response = stub.PushTransaction(request=qrl_pb2.PushTransactionReq(transaction_signed=tx.pbdata))

    if response.error_code != 3:
        return None

    response = {'tx_hash': bin2hstr(tx.txhash)}

    return response


app.add_url_rule('/json_rpc', 'api', api.as_view(), methods=['POST'])

if __name__ == '__main__':
    global payment_slaves
    global payment_xmss
    mining_stub = qrlmining_pb2_grpc.MiningAPIStub(grpc.insecure_channel('127.0.0.1:9007'))
    public_stub = qrl_pb2_grpc.PublicAPIStub(grpc.insecure_channel('127.0.0.1:9009'))
    payment_xmss = None
    payment_slaves = read_slaves(config.user.mining_pool_payment_wallet_path)
    app.run(host='127.0.0.1', port=18081)
Example #26
0
    description='Compare the blockchain across two servers.')
parser.add_argument('--hostA',
                    default='127.0.0.1',
                    help='ip address of the node')
parser.add_argument('--portA', default='19009', help='port of the node')
parser.add_argument('--hostB',
                    default='127.0.0.1',
                    help='ip address of the node')
parser.add_argument('--portB', default='19009', help='port of the node')
parser.add_argument('--startBlock', default='0', help='starting block')
parser.add_argument('--endBlock', default='100000', help='ending block')
args = parser.parse_args()

addressA = '{}:{}'.format(args.hostA, args.portA)
channelA = grpc.insecure_channel(addressA)
qrlClientA = qrl_pb2_grpc.PublicAPIStub(channelA)
logging.info('Connected to {}'.format(addressA))

addressB = '{}:{}'.format(args.hostB, args.portB)
channelB = grpc.insecure_channel(addressB)
qrlClientB = qrl_pb2_grpc.PublicAPIStub(channelB)
logging.info('Connected to {}'.format(addressB))

# load the blocks for addressA & addressB
start = time.monotonic()
for blockNum in range(int(args.startBlock), int(args.endBlock) + 1):
    request = qrl_pb2.GetObjectReq(query=str(blockNum).encode(
        encoding='ascii'))
    responseA = qrlClientA.GetObject(request)
    responseB = qrlClientB.GetObject(request)
    if not responseA.HasField('block_extended') or not responseB.HasField(
Example #27
0
def get_public_stub():
    stub = qrl_pb2_grpc.PublicAPIStub(grpc.insecure_channel('127.0.0.1:9009'))
    return stub
Example #28
0
                    help='ip address of the node')
parser.add_argument('--port', default='19009', help='port of the node')
parser.add_argument('--show_request',
                    action='store_true',
                    default=False,
                    help='display outgoing query message')
parser.add_argument(
    'object',
    help='what to query, such as [block number], [txhash], [Q-address], stats')
args = parser.parse_args()

address = '{}:{}'.format(args.host, args.port)
channel = grpc.insecure_channel(address,
                                options=[('grpc.max_receive_message_length',
                                          4194304 * 2)])
qrl_client = qrl_pb2_grpc.PublicAPIStub(channel)
logging.info('Connected to {}'.format(address))

# Determine if we are querying something sensible
if len(args.object) == 79 and args.object.startswith('Q'):
    logging.info('Query of address detected')
    query_addr(qrl_client, args.object)
elif len(args.object) == 64:
    logging.info('Query of tx detected')
    query_txn(qrl_client, args.object)
elif args.object.isnumeric():
    logging.info('Query of block number detected')
    query_block(qrl_client, int(args.object))
elif args.object == 'stats':
    query_stats(qrl_client)
else:
Example #29
0
 def get_stub_public_api(self):
     node_public_address = '{}:{}'.format(self.host, self.port_public)
     channel = grpc.insecure_channel(node_public_address)
     return qrl_pb2_grpc.PublicAPIStub(channel)
Example #30
0
 def get_stub_public_api(self):
     return qrl_pb2_grpc.PublicAPIStub(self.channel_public)