def validate_fields(required_fields, request_json): try: for field in required_fields: if request_json.get(field) is None: raise ApiBadRequest("{} is required".format(field)) except (ValueError, AttributeError): raise ApiBadRequest("Improper JSON format")
async def registration(request): ##request object received from sanic app, It has all the ##paramteres sent by the user. async with aiohttp.ClientSession() as session: try: async with session.post(f"http://{request.app.config.REGISTRATION}/registration", json={'email': request.json["email"], "phone_number": request.json["phone_number"],\ 'adhaar': request.json["adhaar"],'pancard': request.json["pancard"], 'first_name': request.json["first_name"], 'last_name': request.json['last_name'],\ 'user_type': request.json["user_type"] }) as request_response: data = await request_response.read() except Exception as e: logging.error( "Registration api is not working, Please fix it Dude") raise ApiInternalError( "Registration api is not working, Please fix it Dude") request_json = load_json(data) if request_json.get("error"): raise ApiBadRequest(f"User already exists") user_id, password, secrets = request_json["data"]["user_id"],\ request_json["data"]["password"], request_json["data"]["secrets"] return user_id, password, secrets
async def store_share_asset(app, data): ##you need to encode binary data into string try: return await r.table(app.config.DATABASE["share_asset"])\ .insert(data).run(app.config.DB) except ReqlNonExistenceError as e: logging.error(f"Error in inserting {data} which is {e}") raise ApiBadRequest( f"Error in storing asset {e}") return
async def retrieve_assets(user_id, conn): try: cursor= await r.table('assets')\ .filter(r.row["user_id"] == user_id)\ .run(conn) except ReqlNonExistenceError: raise ApiBadRequest(f"No account with this user_id exists {user_id}") assets = [] while (await cursor.fetch_next()): item = await cursor.next() assets.append(item) return assets
async def fetch_info_by_email(email, app): try: cursor = await r.table(app.config.DATABASE["users"])\ .filter({"email": email})\ .run(app.config.DB) except ReqlNonExistenceError: raise ApiBadRequest( f"No account with this email exists {email} or the user havent claimed his/her account" ) except Exception as e: print(e) result = [] while (await cursor.fetch_next()): item = await cursor.next() result.append(item) if not result: raise ApiBadRequest( f"No account with this email exists {email} or the user havent claimed his/her account" ) else: return result[0]
async def store_receive_assets(app, data): if await find_receive_asset(app, data["org_zero_pub"], data["idx"]): logging.error("This transfer_asset transaction is already present in\ the database") raise Exception("This transfer_asset transaction is already present in\ the database") try: return await r.table(app.config.DATABASE["receive_asset"])\ .insert(data).run(app.config.DB) except ReqlNonExistenceError as e: logging.error(f"Error in inserting {data} which is {e}") raise ApiBadRequest(f"Error in storing receive asset {e}") return
async def store_assets(app, data): """ if not await find_on_key("user_id", data["user_id"], app): raise AccountCreationError( message=f"user with user_id={data['user_id']} doesnt exists" ) if await find_user_field(app, data["user_id"], "file_hash") == data["file_hash"]: raise AssetCreationError( message=f"Asset with file_hash=data['file_hash'] already exists" ) """ try: return await r.table(app.config.DATABASE["assets"])\ .insert(data).run(app.config.DB) except ReqlNonExistenceError as e: raise ApiBadRequest(f"Error in storing asset {e}")
async def store_transfer_assets(app, data): logging.info(f"This is the data for store_transfer_assets {data}") if await find_transfer_asset(app, data["issuer_address"], data["receiver_address"]): logging.error("This transfer_asset transaction is already present in\ the database") raise Exception("This transfer_asset transaction is already present in\ the database") try: return await r.table(app.config.DATABASE["transfer_asset"])\ .insert(data).run(app.config.DB) except ReqlNonExistenceError as e: logging.error(f"Error in inserting {data} which is {e}") raise ApiBadRequest(f"Error in storing asset {e}") return
async def check_filehash_assets(file_hash, conn): try: cursor= await r.table('assets')\ .filter(r.row["file_hash"] == file_hash)\ .run(conn) except ReqlNonExistenceError: raise ApiBadRequest(f"No account with this user_id exists {user_id}") assets = [] while (await cursor.fetch_next()): item = await cursor.next() assets.append(item) logging.debug(f"assets found with similar hash are {assets}") if len(assets) > 0: return False return True
async def check_batch_status(conn, batch_id): status_request = client_batch_submit_pb2.ClientBatchStatusRequest( batch_ids=[batch_id], wait=True) validator_response = await conn.send( validator_pb2.Message.CLIENT_BATCH_STATUS_REQUEST, status_request.SerializeToString()) status_response = client_batch_submit_pb2.ClientBatchStatusResponse() status_response.ParseFromString(validator_response.content) batch_status = status_response.batch_statuses[0].status if batch_status == client_batch_submit_pb2.ClientBatchStatus.INVALID: invalid = status_response.batch_statuses[0].invalid_transactions[0] raise ApiBadRequest(invalid.message) elif batch_status == client_batch_submit_pb2.ClientBatchStatus.PENDING: raise ApiInternalError("Transaction submitted but timed out") elif batch_status == client_batch_submit_pb2.ClientBatchStatus.UNKNOWN: raise ApiInternalError("Something went wrong. Try again later")
async def wait_for_status(batch_id, config): '''Wait until transaction status is not PENDING (COMMITTED or error). 'wait' is time to wait for status, in seconds. ''' headers = {'Content-Type': 'application/json'} waited = 0 start_time = time.time() wait = config.TIMEOUT timeout = aiohttp.ClientTimeout(total=config.TIMEOUT) while waited < wait: async with aiohttp.ClientSession(timeout=timeout) as session: async with session.get(f"http://{config.REST_API_URL}/batch_statuses?id={batch_id}", headers=headers) as response: await asyncio.sleep(0.5) data = await response.read() try: data = load_json(data) status = data['data'][0]['status'] except Exception as e: logging.error("Error in wait for status") logging.error(e) status = "" pass waited = time.time() - start_time logging.info(f"Trying again, to check block status BLOCK-STATUS {status}") if status != 'PENDING': break if status == "COMMITTED": logging.info("Transaction successfully submittted") return True elif status == "PENDING": logging.error("Transaction submitted but timed out") raise ApiInternalError("Transaction submitted but timed out") elif status == "UNKNOWN": logging.error("Something went wrong. Try again later") raise ApiInternalError("Something went wrong. Try again later") elif status == "INVALID": logging.error("Transaction submitted to blockchain is invalid") raise ApiInternalError("Transaction submitted to blockchain is invalid") else: logging.error("Error in the transaction {%s}"%data['data'][0]['message']) raise ApiBadRequest("Error in the transaction {%s}"%data['data'][0]['message']) return False
async def wait_for_status(self, batch_id): """ Once the batch is pushed on to the rest api of blockchain, wait for its confirmation, If the status of block sumission is COMMITTED return True else False """ waited = 0 start_time = time.time() while waited < self.wait: async with aiohttp.ClientSession(timeout=self.timeout) as session: async with session.get(f"http://{self.rest_api_url}/batch_statuses?id={batch_id}", headers=self.headers) as response: await asyncio.sleep(0.1) data = await response.read() try: data = self.load_json(data) status = data['data'][0]['status'] except Exception as e: logger.error("Error in wait for status") logger.error(e) status = "" pass waited = time.time() - start_time logger.warning(f"Trying again, to check block status BLOCK-STATUS {status}") if status != 'PENDING': break try: if status == "COMMITTED": logger.success("Transaction successfully submittted") return True else: logger.error("Error in the transaction {%s}"%data['data'][0]['message']) raise ApiBadRequest("Error in the transaction {%s}"%data['data'][0]['message']) except Exception as e: logger.error(data["data"][0]["invalid_transactions"][0]["message"]) return False
def load_json(self, data): try: request_json = json.loads(data.decode()) except Exception as e: raise ApiBadRequest(f"Json cannot be parsed") return request_json
def check_hash(file_bytes, hash): calculated_hash = hashlib.sha224(file_bytes).hexdigest() if calculated_hash != hash: raise ApiBadRequest( "File hash doesnt Match, Please send the right sha224 hash") return True