Skip to content

Commit

Permalink
Merge pull request #1047 from onajifortune/main
Browse files Browse the repository at this point in the history
Zchat by qdev
  • Loading branch information
zksquirrel authored Oct 11, 2024
2 parents 9a478ff + fb5c60d commit b232da7
Show file tree
Hide file tree
Showing 684 changed files with 60,247 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Hackathon/zchat/Zchat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
Zchat MessagingApp: ZecHub 2024 Hackathon

Introduction

This project is a Zchat messaging app that accepts and processes funds in Zcash ($ZEC) while sending messages to loved ones. The app is a proof of concept (PoC) created for the ZecHub 2024 Hackathon, demonstrating interoperability with Zcash through fast payments processing directly from the blockchain and its integration to an everyday messaging platform.

Zcash Interoperability

Wallet Connect Feature

The app allows players to connect their Zcash shielded wallet in order to use the messaging ap. The process for connecting the wallet is as follows:

• The user creates an account and a shielded Zcash address is created for that particular user

Sending Messages and Processing Payments

• Sending Messages: Players can send messages by selecting their preferred user to chat with from the list of users. Each message is cryptographically encrypted and it is end to end. On the backend, it is also cryptographically encrypted hence a different message hash is stored in the database so if it is leaked, it will useless as another layer of encryption is present. As messeges are sent it is updated in real time with the help of websocketsthachat transaction includes a memo field with a specially crafted JSON payload. The memo format helps the backend system process and verify the bet.

• Processing Payments: Payments are initiated with two options: Request and Send. On Request, users can scan a QR Code to quickly transfer the payment details to their wallet address. On send, users can send funds only requiring and amount input and then quickly processes it as soon as transactions enter the mempool, without waiting for full confirmations.


Known Bugs

Please note that this project is a PoC and not intended for production use. Below are some known bugs and issues.

• Message List User Animation: Not all the parts of the message page updates when messages or transactions are updated.

• Zcash Service: Zcash can sometimes fail temporarily or unexpectedly stop which renders transaction and registration logic inactive.

• No Refunds: If the backend fails to parse the memo field correctly or if the message transaction is outside the valid range, there are no refunds.

• Further Issues: This is a proof of concept, so there may be additional bugs or limitations.


Financing
To continue its trajectory toward full-scale implementation, the developer is seeking additional funding to enhance and expand Zchat's features. The focus will be on scaling infrastructure to support more users, conducting extensive security audits, and refining the user interface. Future development plans include the introduction of group chat capabilities, multi-device synchronization, and support for additional cryptocurrencies. While the initial development has been a success, external financing is crucial to move beyond the proof-of-concept stage and bring Zchat to a broader audience. With the right financial backing, Zchat can evolve into a fully functional, secure, and scalable application, ready to take its place at the forefront of decentralized communication and cryptocurrency integration.
1 change: 1 addition & 0 deletions Hackathon/zchat/zchat-backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vercel
Binary file added Hackathon/zchat/zchat-backend/README.md
Binary file not shown.
116 changes: 116 additions & 0 deletions Hackathon/zchat/zchat-backend/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = ./scripts

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to ./scripts/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:./scripts/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = sqlite:///./zcash_db_new_new.sqlite3


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
20 changes: 20 additions & 0 deletions Hackathon/zchat/zchat-backend/app/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from fastapi import status
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext

# Secret key for JWT
SECRET_KEY = "my_secret_keys_and_yours_are_here"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

# Password hashing context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# OAuth2 password bearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")

def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
return pwd_context.hash(password)
41 changes: 41 additions & 0 deletions Hackathon/zchat/zchat-backend/app/cleaners.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from fastapi import Depends, FastAPI, HTTPException, status, Query
import eth_utils
from . import crud, schemas

import re

def og_validate_email(email):
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(pattern, email) is not None

def og_validate_password(password):
# Regex pattern to ensure at least one lowercase, one uppercase, one digit, one special character, and no whitespace
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'

# Check if the password matches the pattern
return re.match(pattern, password) is not None

def validate_eth_address(address: str):
credentials_exception = HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid wallet address",
)
if not eth_utils.is_checksum_address(address):
raise credentials_exception

def validate_email(db, email: str):
if og_validate_email(email=email):
db_user = crud.get_user_by_email(db, email=email)
if db_user:
raise HTTPException(status_code=400, detail="Email already exists")
else:
raise HTTPException(status_code=400, detail="Email format is invalid")

def validate_username(db, username: str):
db_user = crud.get_user_by_username(db, username=username)
if db_user:
raise HTTPException(status_code=400, detail="Username already exists")

def validate_password(db, password: str):
if not og_validate_password(password):
raise HTTPException(status_code=400, detail="Password must be at least 8 characters containing Uppercase and special characters")
167 changes: 167 additions & 0 deletions Hackathon/zchat/zchat-backend/app/crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import os
from fastapi import HTTPException
import hashlib
from datetime import datetime
from typing import List
from cryptography.fernet import Fernet

from sqlalchemy.orm import Session

from . import auth, models, schemas, cleaners
from .zcash_mod import zcash_utils, zcash_wallet

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
key_dir = os.path.join(BASE_DIR, 'key')
key_file_path = os.path.join(key_dir, 'fernet_key.key')

def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()

def get_user_by_email(db: Session, email: str):
return db.query(models.User).filter(models.User.email == email).first()

def get_user_by_username(db: Session, username: str):
return db.query(models.User).filter(models.User.username == username).first()

def get_user_by_zcash_address(db: Session, zcash_address: str):
return db.query(models.User).filter(models.User.zcash_address == zcash_address).first()

def get_users(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.User).offset(skip).limit(limit).all()

def get_some_users(db: Session, current_user_id: int, skip: int = 0, limit: int = 100):
return db.query(models.User).filter(models.User.id != current_user_id).offset(skip).limit(limit).all()


def create_user(db: Session, user: schemas.UserCreate):
hashed_password = auth.get_password_hash(user.password)
# cleaners.validate_eth_address(user.wallet_address)
# zcash_utils.validate_zcash_address(user.wallet_address)
# zcash_utils.validate_zcash_address('address')
# zcash_wallet.send_to_address('address', 0.1)
# try:
zcash_account = zcash_wallet.z_get_new_account()
zcash_address = zcash_wallet.z_getaddressforaccount(zcash_account)
zcash_transparent_address = zcash_wallet.z_listunifiedreceivers(zcash_address, 'p2pkh')
zcash_transparent_balance = str(zcash_wallet.get_transparent_address_balance(zcash_transparent_address))
db_user = models.User(email=user.email.lower(), username=user.username.lower(), zcash_account=zcash_account, zcash_address=zcash_address, zcash_transparent_address=zcash_transparent_address, hashed_password=hashed_password, balance=zcash_transparent_balance)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user

def get_user_id_from_username(db: Session, username: str):
id = db.query(models.User.id).filter(models.User.username == username).scalar()
return id

def get_p2p_chat_history(db: Session, sender_id: int, receiver_id: int):
chat_history = db.query(models.Message).filter(
(models.Message.sender_id == sender_id) & (models.Message.receiver_id == receiver_id) |
(models.Message.sender_id == receiver_id) & (models.Message.receiver_id == sender_id)
).order_by(models.Message.timestamp).all()

return chat_history

def send_zec_funds(db:Session, message_data: schemas.MessageCreate):
user:models.User = get_user_by_username(db=db, username=message_data.receiver)
try:
zcash_wallet.send_to_address(address=user.zcash_transparent_address, amount=message_data.transaction)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

def send_transaction():
pass

def get_latest_message_with_user(db: Session, current_user_id: int, other_user_id: int):
# Fetch chat history between current user and other user
chat_history = db.query(models.Message).filter(
((models.Message.sender_id == current_user_id) & (models.Message.receiver_id == other_user_id)) |
((models.Message.sender_id == other_user_id) & (models.Message.receiver_id == current_user_id))
).order_by(models.Message.timestamp.desc()).all() # Order by timestamp descending

return chat_history[0] if chat_history else None # Return the latest message or None

# Generate or load the encryption key (for demonstration, this key is generated once)
# key = Fernet.generate_key()

# Read the key from the file
with open(key_file_path, "rb") as key_file:
key = key_file.read()

cipher = Fernet(key)

# Proceed with encryption and decryption as before


def encrypt_message(message: str|None) -> str:
if message:
encrypted_message = cipher.encrypt(message.encode('utf-8'))
return encrypted_message.decode('utf-8')
return None

def decrypt_message(encrypted_message: str|None) -> str:
if encrypted_message:
decrypted_message = cipher.decrypt(encrypted_message.encode('utf-8'))
return decrypted_message.decode('utf-8')
return None

def hash_message(message: str|None) -> str:
# Convert the message to bytes and generate a SHA-256 hash
if message:
return hashlib.sha256(message.encode('utf-8')).hexdigest()
return None

def verify_hash(message: str, hash_value: str) -> bool:
"""Verify the hash of the decrypted message."""
return hash_message(message) == hash_value

def decrypt_chat_history(chat_history: List[dict]) -> List[dict]:
decrypted_history = []
# decrypted_message = decrypt_message("4c59ce35aee1dc138819828669e5e024d4a1af156eadb734a7ab014ca7d96c18")

for message in chat_history:
# Decrypt only if the message content is encrypted
decrypted_message = decrypt_message(message.message)
if not verify_hash(message=decrypted_message, hash_value=message.message_hash):
decrypted_message = f"{decrypted_message} (integrity compromised)"

decrypted_history.append({
'id': message.id,
'sender_id': message.sender_id,
'receiver_id': message.receiver_id,
'message': decrypted_message,
'transaction': message.transaction,
'timestamp': message.timestamp.strftime("%H:%M")
})

# return decrypted_history
return decrypted_history

def create_message(db: Session, sender_id: int, receiver_id: int, message: str|None, transaction: int|float|None):
encrypted_message = encrypt_message(message=message)
message_hash = hash_message(message=message)
new_message = models.Message(sender_id=sender_id, receiver_id=receiver_id, message= encrypted_message, message_hash=message_hash, transaction=transaction)
db.add(new_message)
db.commit()

return new_message


# def create_message(db: Session, user: schemas.MessageCreate):
# hashed_password = auth.get_password_hash(user.password)
# # cleaners.validate_eth_address(user.wallet_address)
# db_user = models.User(email=user.email.lower(), username=user.username.lower(), wallet_address=user.wallet_address, hashed_password=hashed_password)
# db.add(db_user)
# db.commit()
# db.refresh(db_user)
# return db_user

# def get_items(db: Session, skip: int = 0, limit: int = 100):
# return db.query(models.Item).offset(skip).limit(limit).all()

# def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int):
# db_item = models.Item(**item.model_dump(), owner_id=user_id)
# db.add(db_item)
# db.commit()
# db.refresh(db_item)
# return db_item
Loading

0 comments on commit b232da7

Please sign in to comment.