Ejemplo n.º 1
0
 async def receive_assets(self):
     receive_asset_idxs, nth_keys = await self.indexes_n_pub_priv_pairs(
         "receive_asset_idxs")
     address_list = []
     for key_index in receive_asset_idxs:
         public_key = nth_keys[str(key_index)]["public_key"]
         receive_asset_address = addresser.receive_asset_address(
             asset_id=public_key, index=key_index)
         address_list.append(receive_asset_address)
     logging.info(f"Asset address list <<{address_list}>>")
     return address_list
def receive_asset(**in_data):
    """
    """
    address = addresser.receive_asset_address(
        asset_id=in_data["txn_key"].get_public_key().as_hex(),
        index=in_data["idx"])

    inputs = [in_data["org_address"], address]
    outputs = [in_data["org_address"], address]
    logging.info(in_data)
    if in_data["child_zero_pub"]:

        child_address = addresser.child_account_address(
            account_id=in_data["child_zero_pub"], index=0)
        logging.info(f"CHILD address is {child_address}")
        inputs.append(child_address)
        outputs.append(child_address)

    if in_data["receive_asset_details"]:
        receive_asset_details = payload_pb2.ReceiveAssetDetails(
            name=in_data["receive_asset_details"]["name"],
            description=in_data["receive_asset_details"]["description"],
        )
    receive_asset = payload_pb2.CreateReceiveAsset(
        _id_=in_data["_id_"],
        time=in_data["time"],
        indiantime=in_data["indiantime"],
        idx=in_data["idx"],
        at_which_asset_expires=in_data["at_which_asset_expires"],
        org_name=in_data["org_name"],
        org_address=in_data["org_address"],
        org_role=in_data["org_role"],
        org_zero_pub=in_data["org_zero_pub"],
        receive_asset_details=receive_asset_details,
        child_zero_pub=in_data["child_zero_pub"],
        signed_nonce=in_data["signed_nonce"],
        nonce=in_data["nonce"],
        nonce_hash=in_data["nonce_hash"],
        unique_code_hash=in_data["unique_code_hash"],
        encrypted_unique_code=in_data["encrypted_unique_code"],
        encrypted_admin_unique_code=in_data["encrypted_admin_unique_code"])

    payload = payload_pb2.TransactionPayload(
        payload_type=payload_pb2.TransactionPayload.RECEIVE_ASSET,
        receive_asset=receive_asset)
    logging.info(payload)
    return make_header_and_batch(payload=payload,
                                 inputs=inputs,
                                 outputs=outputs,
                                 txn_key=in_data["txn_key"],
                                 batch_key=in_data["batch_key"])
    def receive_asset(self, public, org_account, child_address, child_account,
                      payload):

        self.update_receive_index(payload.org_address, org_account,
                                  payload.idx)
        if payload.child_zero_pub:
            self.update_receive_index(child_address, child_account,
                                      payload.idx)

        address = addresser.receive_asset_address(asset_id=public,
                                                  index=payload.idx)
        receive_asset = empty_receive_asset()

        receive_asset._id_ = payload._id_
        receive_asset.time = payload.time
        receive_asset.indiantime = payload.indiantime
        receive_asset.idx = payload.idx
        receive_asset.at_which_asset_expires = payload.at_which_asset_expires
        receive_asset.org_address = payload.org_address
        receive_asset.org_role = payload.org_role
        receive_asset.org_name = payload.org_name
        receive_asset.child_zero_pub = payload.child_zero_pub
        receive_asset.nonce = payload.nonce
        receive_asset.signed_nonce = payload.signed_nonce
        receive_asset.nonce_hash = payload.nonce_hash
        receive_asset.unique_code_hash = payload.unique_code_hash
        receive_asset.encrypted_unique_code = payload.encrypted_unique_code
        receive_asset.encrypted_admin_unique_code = payload.encrypted_admin_unique_code
        receive_asset.public = public

        if payload.receive_asset_details:
            receive_asset.receive_asset_details.name = payload.receive_asset_details.name
            receive_asset.receive_asset_details.description = payload.receive_asset_details.description

        self._context.set_state({address: receive_asset.SerializeToString()},
                                self._timeout)
        return
async def submit_receive_asset(app, requester, _id_, name, description,
                               at_which_asset_expires):
    """
    """
    f = await userapis.SolveAccount(requester, app)
    decrypted_mnemonic = f.decrypted_mnemonic
    logging.info(f"THis is the decrypted mnemonic {decrypted_mnemonic}")
    org_db_entry = f.org_db
    receive_asset_idxs = f.org_state.get("receive_asset_idxs")
    child_user_id = f.child_user_id
    child_zero_pub = f.child_zero_pub
    account_zero_pub = f.zero_pub

    key_index = await ledger_utils.generate_key_index(array=receive_asset_idxs)

    nth_keys = await remote_calls.key_index_keys(app, decrypted_mnemonic,
                                                 [key_index, 0])

    nth_priv, nth_pub = nth_keys[str(key_index)]["private_key"], \
                        nth_keys[str(key_index)]["public_key"]

    org_priv, org_pub = nth_keys[str(0)]["private_key"], \
                        nth_keys[str(0)]["public_key"]

    org_account_address = addresser.create_organization_account_address(
        account_id=account_zero_pub, index=0)

    instance = await userapis.SolveAddress(org_account_address,
                                           app.config.REST_API_URL)
    org_state = instance.data

    ##the transaction will be signed by users nth private key
    create_asset_signer = ledger_utils.create_signer(nth_priv)

    ##we havent included the child_nth_pub in this transaction because it
    ## can be calculated from txn_key on the processor side

    ##for added security we will send a nonce signed by issuer account
    ##private key
    nonce = random.randint(2**20, 2**30)
    nonce_hash = hashlib.sha224(str(nonce).encode()).hexdigest()
    ##nonce signed by zerothprivate key and in hex format
    hex_signatures = signatures.ecdsa_signature(org_priv, nonce)

    receive_asset_address = addresser.receive_asset_address(asset_id=nth_pub,
                                                            index=key_index)

    unique_code = int("".join(map(str, random.choices(list(range(1, 10)),
                                                      k=5))))
    unique_code_hash = hashlib.sha224(str(unique_code).encode()).hexdigest()
    encrypted_unique_code = encryption_utils.encrypt_w_pubkey(
        str(unique_code).encode(), nth_pub)
    encrypted_admin_unique_code = encryption_utils.encrypt_w_pubkey(
        str(unique_code).encode(), app.config.ADMIN_ZERO_PUB)

    transaction_data = {
        "config": app.config,
        "txn_key": create_asset_signer,
        "batch_key": app.config.SIGNER,
        "_id_": _id_,
        "time": int(time.time()),
        "indiantime": upload_utils.indian_time_stamp(),
        "idx": key_index,
        "at_which_asset_expires": at_which_asset_expires,
        "org_name": org_state["org_name"],
        "org_address": org_account_address,
        "org_zero_pub": org_pub,
        "org_role": org_state["role"],
        "receive_asset_details": {
            "name": name,
            "description": description
        },
        "child_zero_pub": child_zero_pub,
        "signed_nonce": hex_signatures,
        "nonce": nonce,
        "nonce_hash": nonce_hash,
        "unique_code_hash": unique_code_hash,
        "encrypted_unique_code": encrypted_unique_code,
        "encrypted_admin_unique_code": encrypted_admin_unique_code
    }

    logging.info(f"THis is the transaction data in receive_asset")
    logging.info(pprint(transaction_data))

    transaction_ids, batch_id = await send_receive_asset(**transaction_data)

    if batch_id:
        [
            transaction_data.pop(field)
            for field in ["config", "txn_key", "batch_key"]
        ]
        signed_nonce = transaction_data["signed_nonce"].decode()

        transaction_data.update({
            "user_id": requester["user_id"],
            "public": nth_pub,
            "transaction_id": transaction_ids[0],
            "batch_id": batch_id,
            "signed_nonce": signed_nonce,
            "unique_code": unique_code
        })

        await receive_assets_query.store_receive_assets(app, transaction_data)
        await accounts_query.update_receive_assets_idxs(
            app, org_db_entry["user_id"], key_index)
        ##if this receive_asset is created by child of the organization
        ##then update the child account receive_asset_idxs array also
        if child_user_id:
            await accounts_query.update_receive_assets_idxs(
                app, child_user_id, key_index)

            #await accounts_query.update_create_asst_idxs_pending(app,
            #requester["user_id"], key_index)

        return nth_pub, key_index, receive_asset_address
    else:
        logging.error("Create asset Faied, GO to hell Dude!!!!,\
         Kabhi kabhi lagta hai ki bhagwan hone ka bhi kya fayda")
    return
async def send_receive_asset(**in_data):
    """
    """
    address = addresser.receive_asset_address(
        asset_id=in_data["txn_key"].get_public_key().as_hex(),
        index=in_data["idx"])

    inputs = [in_data["org_address"], address]
    outputs = [in_data["org_address"], address]
    logging.info(in_data)
    if in_data["child_zero_pub"]:

        child_address = addresser.child_account_address(
            account_id=in_data["child_zero_pub"], index=0)
        logging.info(f"CHILD address is {child_address}")
        inputs.append(child_address)
        outputs.append(child_address)

    if in_data["receive_asset_details"]:
        receive_asset_details = payload_pb2.ReceiveAssetDetails(
            name=in_data["receive_asset_details"]["name"],
            description=in_data["receive_asset_details"]["description"],
        )
    receive_asset = payload_pb2.CreateReceiveAsset(
        _id_=in_data["_id_"],
        time=in_data["time"],
        indiantime=in_data["indiantime"],
        idx=in_data["idx"],
        at_which_asset_expires=in_data["at_which_asset_expires"],
        org_name=in_data["org_name"],
        org_address=in_data["org_address"],
        org_role=in_data["org_role"],
        org_zero_pub=in_data["org_zero_pub"],
        receive_asset_details=receive_asset_details,
        child_zero_pub=in_data["child_zero_pub"],
        signed_nonce=in_data["signed_nonce"],
        nonce=in_data["nonce"],
        nonce_hash=in_data["nonce_hash"],
        unique_code_hash=in_data["unique_code_hash"],
        encrypted_unique_code=in_data["encrypted_unique_code"],
        encrypted_admin_unique_code=in_data["encrypted_admin_unique_code"])

    payload = payload_pb2.TransactionPayload(
        payload_type=payload_pb2.TransactionPayload.RECEIVE_ASSET,
        receive_asset=receive_asset)
    logging.info(payload)
    transaction_ids, batches, batch_id, batch_list_bytes = make_header_and_batch(
        payload=payload,
        inputs=inputs,
        outputs=outputs,
        txn_key=in_data["txn_key"],
        batch_key=in_data["batch_key"])

    logging.info(f"This is the batch_id {batch_id}")

    rest_api_response = await messaging.send(batch_list_bytes,
                                             in_data["config"])

    try:
        result = await messaging.wait_for_status(batch_id, in_data["config"])
    except (ApiBadRequest, ApiInternalError) as err:
        #await auth_query.remove_auth_entry(request.app.config.DB_CONN, request.json.get('email'))
        logging.error(f"Transaction failed with {err}")
        raise ApiInternalError(err)
        #raise err
    return transaction_ids, batch_id