Skip to content

Commit

Permalink
- Added eth-hash module
Browse files Browse the repository at this point in the history
- Added list user function to cli
- Added method to generate user address
- Added address to user.surql
- Added address to auth.surql
  • Loading branch information
Satti-Gowtham committed Jan 2, 2025
1 parent 378743b commit 3c0071f
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 27 deletions.
1 change: 1 addition & 0 deletions node/storage/hub/data_structures/auth.surql
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ DEFINE SCOPE user SESSION 7d
username: $username,
password: crypto::argon2::generate($password),
public_key: $public_key,
address: $address,
id: $public_key
}
)
Expand Down
2 changes: 2 additions & 0 deletions node/storage/hub/data_structures/user.surql
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ DEFINE FIELD password ON user TYPE string PERMISSIONS FOR select NONE
PERMISSIONS
FOR select, update, delete WHERE id = $auth.id;
DEFINE FIELD public_key ON user TYPE string;
DEFINE FIELD address ON user TYPE string;

DEFINE FIELD created ON user
VALUE $before OR time::now()
Expand All @@ -23,6 +24,7 @@ DEFINE FIELD updated ON user

DEFINE INDEX unique_username ON user FIELDS username UNIQUE;
DEFINE INDEX unique_public_key ON user FIELDS public_key UNIQUE;
DEFINE INDEX unique_address ON user FIELDS address UNIQUE;

DEFINE EVENT removal ON user WHEN $event = "DELETE" THEN {
DELETE job WHERE consumer_id = $before.id;
Expand Down
21 changes: 21 additions & 0 deletions node/storage/hub/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from node.utils import AsyncMixin
from node.config import HUB_DB, HUB_NS, LOCAL_HUB_URL, LOCAL_HUB, PUBLIC_HUB_URL
from node.schemas import Module, NodeConfig, NodeServer
from node.user import generate_address
import os
from surrealdb import Surreal
import traceback
Expand Down Expand Up @@ -64,6 +65,7 @@ async def signin(
self.user_id = self._decode_token(user)
self.token = user
self.is_authenticated = True
await self.check_and_update_address(self.user_id)
return True, user, self.user_id
except Exception as e:
logger.error(f"Sign in failed: {e}")
Expand All @@ -82,12 +84,31 @@ async def signup(
"username": username,
"password": password,
"public_key": public_key,
"address": generate_address(bytes.fromhex(public_key))
}
)
if not user:
return False, None, None
self.user_id = self._decode_token(user)
return True, user, self.user_id

async def check_and_update_address(self, user_id: str) -> None:
user = await self.get_user(user_id)

# Check if the address is empty or None
if not user.get("address"):
logger.info("User address not found")
logger.info("Updating address....")

# Generate the address and update the record
user["address"] = generate_address(bytes.fromhex(user["public_key"]))
try:
await self.surrealdb.update(user.pop('id'), user)
logger.info("Address updated successfully")
except Exception as e:
logger.error(f"Failed to update address: {e}")
else:
logger.info("User address found, moving on.....")

async def get_user(self, user_id: str) -> Optional[Dict]:
return await self.surrealdb.select(user_id)
Expand Down
12 changes: 9 additions & 3 deletions node/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from ecdsa import SigningKey, SECP256k1
from node.storage.db.db import DB
from typing import Dict, Tuple
from eth_hash.auto import keccak

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -41,18 +42,23 @@ async def check_user(user_input: Dict) -> Tuple[bool, Dict]:
user_data["is_registered"] = False
return False, user_data


def get_public_key(private_key_hex):
private_key = SigningKey.from_string(
bytes.fromhex(private_key_hex), curve=SECP256k1
)
public_key = private_key.get_verifying_key()
return public_key.to_string().hex()


def generate_user():
private_key = SigningKey.generate(curve=SECP256k1).to_string().hex()
public_key = get_public_key(private_key)
return public_key, private_key


def generate_address(public_key: bytes) -> str:
if len(public_key) not in [64, 33]:
print(public_key)
raise ValueError("Public key must be either 33 or 64 bytes long.")

hash = keccak(public_key)
address = hash[-20:]
return "0x" + address.hex()
108 changes: 84 additions & 24 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ psycopg2-binary = "^2.9.9"
alembic = "^1.13.3"
aiohttp = "^3.11.9"

[tool.poetry.dependencies.eth-hash]
extras = [ "pycryptodome",]
version = "^0.7.0"

[tool.poetry.group.dev.dependencies]
ruff = "^0.1.11"
ipykernel = "^6.29.2"

0 comments on commit 3c0071f

Please sign in to comment.