Beispiel #1
0
async def create_resource(request):
    """Creates a new Resource in state"""
    required_fields = ['name']
    common.validate_fields(required_fields, request.json)

    signer = await common.get_signer(request)
    resource = _create_resource_dict(request.json,
                                     signer.get_public_key().as_hex())

    batches, batch_id = transaction_creation.create_resource(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        name=resource.get('name'),
        description=resource.get('description'),
        rules=resource.get('rules'))

    await messaging.send(request.app.config.VAL_CONN,
                         request.app.config.TIMEOUT, batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    if resource.get('rules'):
        resource['rules'] = request.json['rules']

    return response.json(resource)
async def create_asset(request):
    """Creates a new Asset in state"""
    required_fields = ['name']
    common.validate_fields(required_fields, request.json)

    signer = await common.get_signer(request)
    asset = _create_asset_dict(request.json, signer.get_public_key().as_hex())

    batches, batch_id = transaction_creation.create_asset(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        name=asset.get('name'),
        description=asset.get('description'),
        rules=asset.get('rules'))

    await messaging.send(
        request.app.config.VAL_CONN,
        request.app.config.TIMEOUT,
        batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    if asset.get('rules'):
        asset['rules'] = request.json['rules']

    return response.json(asset)
async def create_account(request):
    """Creates a new Account and corresponding authorization token"""
    required_fields = ['email', 'password']
    common.validate_fields(required_fields, request.json)

    private_key = request.app.config.CONTEXT.new_random_private_key()
    signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key)
    public_key = signer.get_public_key().as_hex()

    auth_entry = _create_auth_dict(request, public_key, private_key.as_hex())
    await auth_query.create_auth_entry(request.app.config.DB_CONN, auth_entry)

    account = _create_account_dict(request.json, public_key)

    batches, batch_id = transaction_creation.create_account(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        label=account.get('label'),
        description=account.get('description'))

    await messaging.send(request.app.config.VAL_CONN,
                         request.app.config.TIMEOUT, batches)

    try:
        await messaging.check_batch_status(request.app.config.VAL_CONN,
                                           batch_id)
    except (ApiBadRequest, ApiInternalError) as err:
        await auth_query.remove_auth_entry(request.app.config.DB_CONN,
                                           request.json.get('email'))
        raise err

    token = common.generate_auth_token(request.app.config.SECRET_KEY,
                                       account.get('email'), public_key)

    return response.json({'authorization': token, 'account': account})
async def create_offer(request):
    """Creates a new Offer in state"""
    required_fields = ['source', 'sourceQuantity']
    common.validate_fields(required_fields, request.json)

    signer = await common.get_signer(request)

    await asyncio.sleep(2.0)  # Mitigate race condition
    offer = _create_offer_dict(request.json, signer.get_public_key().as_hex())

    offer_assets = await _create_assets_dict(request.app.config.DB_CONN, offer)

    source, target = _create_marketplace_assets(offer, offer_assets)

    batches, batch_id = transaction_creation.create_offer(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        identifier=offer['id'],
        label=offer.get('label'),
        description=offer.get('description'),
        source=source,
        target=target,
        rules=offer.get('rules'))

    await messaging.send(request.app.config.VAL_CONN,
                         request.app.config.TIMEOUT, batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    if offer.get('rules'):
        offer['rules'] = request.json['rules']

    return response.json(offer)
async def accept_offer(request, offer_id):
    """Request for authorized Account to accept Offer"""
    required_fields = ['count', 'target']
    common.validate_fields(required_fields, request.json)

    offer = await offers_query.fetch_offer_resource(request.app.config.DB_CONN,
                                                    offer_id)

    offer_assets = await _create_assets_dict(request.app.config.DB_CONN, offer)

    offerer, receiver = _create_offer_participants(request.json, offer,
                                                   offer_assets)

    signer = await common.get_signer(request)
    batches, batch_id = transaction_creation.accept_offer(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        identifier=offer_id,
        offerer=offerer,
        receiver=receiver,
        count=request.json['count'])

    await messaging.send(request.app.config.VAL_CONN,
                         request.app.config.TIMEOUT, batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    return response.json('')
async def accept_offer(request, offer_id):
    """Request for authorized Account to accept Offer"""
    required_fields = ['count', 'target']
    common.validate_fields(required_fields, request.json)

    offer = await offers_query.fetch_offer_resource(
        request.app.config.DB_CONN, offer_id)

    offer_holdings = await _create_holdings_dict(
        request.app.config.DB_CONN, offer)

    offerer, receiver = _create_offer_participants(
        request.json, offer, offer_holdings)

    signer = await common.get_signer(request)
    batches, batch_id = transaction_creation.accept_offer(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        identifier=offer_id,
        offerer=offerer,
        receiver=receiver,
        count=request.json['count'])

    await messaging.send(
        request.app.config.VAL_CONN,
        request.app.config.TIMEOUT,
        batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    return response.json('')
Beispiel #7
0
async def create_holding(request):
    """Creates a new Holding for the authorized Account"""
    required_fields = ['asset']
    common.validate_fields(required_fields, request.json)

    holding = _create_holding_dict(request)
    signer = await common.get_signer(request)

    batches, batch_id = transaction_creation.create_holding(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        identifier=holding['id'],
        label=holding.get('label'),
        description=holding.get('description'),
        asset=holding['asset'],
        quantity=holding['quantity'])

    await messaging.send(
        request.app.config.VAL_CONN,
        request.app.config.TIMEOUT,
        batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    return response.json(holding)
async def transfer_asset(request):
    """Creates a new Asset for the authorized Account"""

    required_fields = ['label', 'source', 'target', 'amount', 'resource']
    common.validate_fields(required_fields, request.json)

    transfer = _create_transfer_dict(request)
    sender = _create_transfer_participant(request.json, transfer)
    signer = await common.get_signer(request)

    # print("transfer =======> ", transfer)
    # print("sender =========> ", sender)

    batches, batch_id = transaction_creation.transfer_asset(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        identifier=transfer['id'],
        label=transfer.get('label'),
        sender=sender,
        amount=transfer['amount'])

    # print("batches =========> ", batches)

    await messaging.send(request.app.config.VAL_CONN,
                         request.app.config.TIMEOUT, batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    return response.json({"transfer": "asad"})
Beispiel #9
0
async def create_asset(request):

    required_fields = [
        "user_id", "password", "file_name", "file_hash", "base64_file_bytes"
    ]

    common.validate_fields(required_fields, request.json)

    file_exist = await asset_query.fetch_info_by_filehash(
        request.app.config.DB_CONN, request.json["file_hash"])

    if file_exist:
        raise ApiInternalError("file already exist. Try again later")

    file_bytes = base64.b64decode(request.json["base64_file_bytes"])

    mnemonic, address, account = await accounts_utils.get_account_details(
        request)

    childkey_index = common.gen_childkey_index()

    child_private_key, child_public_key = await remote_api.get_child_key(
        mnemonic, childkey_index)

    private_hex_key, public_hex_key = await remote_api.get_child_key(
        mnemonic, request.app.config.ROOT_KEY_INDEX)

    private_key = Secp256k1PrivateKey.from_hex(private_hex_key)

    signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key)
    public_key = signer.get_public_key().as_hex()

    aes_key = encryption.generate_aes_key(16)

    ciphertext, tag, nonce = encryption.aes_encrypt(aes_key, file_bytes)

    ciphertext = b"".join([tag, ciphertext, nonce])

    secrets = binascii.hexlify(ciphertext)

    struct = {
        "file_hash": request.json["file_hash"],
        "file_name": request.json["file_name"],
        "file_cipher_hex": secrets.decode()
    }

    s3_key = amazon_s3.generate_s3_key(request.json["user_id"],
                                       request.json["file_name"])
    s3_url = amazon_s3.store_s3(request, s3_key, request.json["user_id"],
                                struct)
Beispiel #10
0
async def generate_asset_address(request):

    required_fields = ["user_id", "password"]

    common.validate_fields(required_fields, request.json)

    mnemonic, address, account = await accounts_utils.get_account_details(
        request)
    # print(type(account))
    childkey_index = common.gen_childkey_index()

    if "keys" in account.keys():
        while childkey_index in account["keys"]:
            childkey_index = common.gen_childkey_index()

    else:
        childkey_index = common.gen_childkey_index()

    child_private_key, child_public_key = await remote_api.get_child_key(
        mnemonic, childkey_index)

    private_hex_key, public_hex_key = await remote_api.get_child_key(
        mnemonic, request.app.config.ROOT_KEY_INDEX)

    private_key = Secp256k1PrivateKey.from_hex(private_hex_key)
    # private_key = request.app.config.CONTEXT.new_random_private_key()
    signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key)
    public_key = signer.get_public_key().as_hex()

    batches, batch_id, batch_list_bytes = transaction_creation.create_empty_asset(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        key_index=childkey_index,
        child_public_key=child_public_key,
        is_empty_asset=True)

    # print(batch_list_bytes)

    data = await messaging.send(batch_list_bytes, request)

    try:
        await messaging.wait_for_status(batch_id, 300, request)
    except (ApiBadRequest, ApiInternalError) as err:
        raise err

    token = common.generate_auth_token(request.app.config.SECRET_KEY,
                                       child_private_key, public_key)
    # print(token)
    return response.json({'authorization': token, 'key_index': childkey_index})
async def authorize(request):
    """Requests an authorization token for a registered Account"""
    required_fields = ['email', 'password']
    common.validate_fields(required_fields, request.json)
    password = bytes(request.json.get('password'), 'utf-8')
    auth_info = await auth_query.fetch_info_by_email(
        request.app.config.DB_CONN, request.json.get('email'))
    if auth_info is None:
        raise ApiUnauthorized("No user with that email exists")
    hashed_password = auth_info.get('hashed_password')
    if not bcrypt.checkpw(password, hashed_password):
        raise ApiUnauthorized("Incorrect email or password")
    token = common.generate_auth_token(request.app.config.SECRET_KEY,
                                       auth_info.get('email'),
                                       auth_info.get('public_key'))
    return json({'authorization': token})
async def create_account(request):
    """Creates a new Account and corresponding authorization token"""
    required_fields = ['email', 'password']
    common.validate_fields(required_fields, request.json)

    private_key = request.app.config.CONTEXT.new_random_private_key()
    signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key)
    public_key = signer.get_public_key().as_hex()

    auth_entry = _create_auth_dict(
        request, public_key, private_key.as_hex())
    await auth_query.create_auth_entry(request.app.config.DB_CONN, auth_entry)

    account = _create_account_dict(request.json, public_key)

    batches, batch_id = transaction_creation.create_account(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        label=account.get('label'),
        description=account.get('description'))

    await messaging.send(
        request.app.config.VAL_CONN,
        request.app.config.TIMEOUT,
        batches)

    try:
        await messaging.check_batch_status(
            request.app.config.VAL_CONN, batch_id)
    except (ApiBadRequest, ApiInternalError) as err:
        await auth_query.remove_auth_entry(
            request.app.config.DB_CONN, request.json.get('email'))
        raise err

    token = common.generate_auth_token(
        request.app.config.SECRET_KEY,
        account.get('email'),
        public_key)

    return response.json(
        {
            'authorization': token,
            'account': account
        })
Beispiel #13
0
async def transfer_asset(request):
    """Updates auth information for the authorized account"""
    token = common.deserialize_auth_token(
        request.app.config.SECRET_KEY, request.token)

    signer = await common.get_signer(request)
    await asyncio.sleep(2.0)  # Mitigate race condition


    required_fields = ['targetID', 'assetName', 'amount']
    common.validate_fields(required_fields, request.json)


    targetID = request.json.get('targetID')
    assetName = request.json.get('assetName')
    amount = request.json.get('amount')


    return send_payment(request ,signer.get_public_key().as_hex(), targetID, assetName, amount)
async def authorize(request):
    """Requests an authorization token for a registered Account"""
    required_fields = ['email', 'password']
    common.validate_fields(required_fields, request.json)
    password = bytes(request.json.get('password'), 'utf-8')
    auth_info = await auth_query.fetch_info_by_email(
        request.app.config.DB_CONN, request.json.get('email'))
    if auth_info is None:
        raise ApiUnauthorized("No user with that email exists")
    hashed_password = auth_info.get('hashed_password')
    if not bcrypt.checkpw(password, hashed_password):
        raise ApiUnauthorized("Incorrect email or password")
    token = common.generate_auth_token(
        request.app.config.SECRET_KEY,
        auth_info.get('email'),
        auth_info.get('public_key'))
    return json(
        {
            'authorization': token
        })
async def create_feedback(request):
    """Creates a new Feedbacks in state"""
    required_fields = ['asset', 'rating']
    common.validate_fields(required_fields, request.json)

    feedback = _create_feedback_dict(request)
    signer = await common.get_signer(request)

    batches, batch_id = transaction_creation.create_feedback(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        identifier=feedback['id'],
        asset=feedback.get('asset'),
        text=feedback.get('text'),
        rating=feedback.get('rating'))

    await messaging.send(request.app.config.VAL_CONN,
                         request.app.config.TIMEOUT, batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    return response.json(feedback)
Beispiel #16
0
async def create_offer(request):
    """Creates a new Offer in state"""
    required_fields = ['source', 'sourceQuantity']
    common.validate_fields(required_fields, request.json)

    signer = await common.get_signer(request)

    await asyncio.sleep(2.0)  # Mitigate race condition
    offer = _create_offer_dict(request.json, signer.get_public_key().as_hex())

    offer_holdings = await _create_holdings_dict(
        request.app.config.DB_CONN, offer)

    source, target = _create_marketplace_holdings(offer, offer_holdings)

    batches, batch_id = transaction_creation.create_offer(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        identifier=offer['id'],
        label=offer.get('label'),
        description=offer.get('description'),
        source=source,
        target=target,
        rules=offer.get('rules'))

    await messaging.send(
        request.app.config.VAL_CONN,
        request.app.config.TIMEOUT,
        batches)

    await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id)

    if offer.get('rules'):
        offer['rules'] = request.json['rules']

    return response.json(offer)
Beispiel #17
0
async def create_account(request):

    # print(request.app.config)
    # print(request.json)
    required_fields = [
        'email', 'phone_number', "adhaar", "pancard", "first_name",
        "last_name", "user_type"
    ]
    # print(request.json)

    common.validate_fields(required_fields, request.json)

    user_id, password, secrets = await remote_api.registration(request)
    # print(secrets)
    print(user_id)
    print(password)
    mnemonic = encryption.recover_mnemonic(password, secrets)

    # print(mnemonic)

    private_hex_key, public_hex_key = await remote_api.get_child_key(
        mnemonic, request.app.config.ROOT_KEY_INDEX)

    private_key = Secp256k1PrivateKey.from_hex(private_hex_key)
    # private_key = request.app.config.CONTEXT.new_random_private_key()
    signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key)
    public_key = signer.get_public_key().as_hex()
    # print(public_key)

    # return json({"main":1})
    auth_entry = _create_auth_dict(request, public_key, private_key.as_hex(),
                                   secrets, user_id)
    # print(auth_entry)
    # print(request.app.config.DB_CONN)
    database_entry = await auth_query.create_auth_entry(
        request.app.config.DB_CONN, auth_entry)
    # details = await auth_query.fetch_info_by_email(request.app.config.DB_CONN,user_id)
    # print(request.app.config.DB_CONN)
    # print(details)

    # type(email_details)
    account = _create_account_dict(request.json, public_key, user_id)

    # print(account)
    batches, batch_id, batch_list_bytes = transaction_creation.create_account(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        email=account['email'],
        phone_number=account["phone_number"],
        adhaar=account["adhaar"],
        pancard=account["pancard"],
        first_name=account["first_name"],
        last_name=account["last_name"],
        user_type=account["user_type"],
        user_id=account["user_id"],
        keys=[])
    # print(batch_list_bytes)
    # print(batches)
    # print(type(batch_list_bytes))
    # print(type(batch_id))
    # print(batches)
    # await messaging.send(
    #     request.app.config.VAL_CONN,
    #     request.app.config.TIMEOUT,
    #     batches)

    data = await messaging.send(batch_list_bytes, request)
    # print(data)
    # try:
    #     await messaging.check_batch_status(
    #         request.app.config.VAL_CONN, batch_id)
    # except (ApiBadRequest, ApiInternalError) as err:
    #     await auth_query.remove_auth_entry(
    #         request.app.config.DB_CONN, request.json.get('email'))
    #     raise err
    try:
        await messaging.wait_for_status(batch_id, 300, request)
    except (ApiBadRequest, ApiInternalError) as err:
        raise err

    token = common.generate_auth_token(request.app.config.SECRET_KEY,
                                       account.get('email'), public_key)
    # print(token)
    return response.json({'authorization': token, 'account': account})