Skip to content

feature: kavach generate key implemented and tested #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/lighthouseweb3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import os
import io
from typing import Dict

from .functions.encryption import generate as generateKey

from .functions import (
upload as d,
deal_status,
Expand Down Expand Up @@ -224,3 +228,19 @@ def getTagged(self, tag: str):
except Exception as e:
raise e

class Kavach:
@staticmethod
def generate(threshold: int = 3, key_count: int = 5) -> Dict[str, any]:
"""
Generates a set of master secret keys and corresponding key shards using BLS (Boneh-Lynn-Shacham)
threshold cryptography.

:param threshold: int, The minimum number of key shards required to reconstruct the master key.
:param key_count: int, The total number of key shards to generate.
:return: Dict[str, any], A dictionary containing the master key and a list of key shards.
"""

try:
return generateKey.generate(threshold, key_count)
except Exception as e:
raise e
36 changes: 36 additions & 0 deletions src/lighthouseweb3/functions/encryption/generate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from py_ecc.bls import G2ProofOfPossession as BLS
from py_ecc.optimized_bls12_381 import curve_order
import random
from typing import Dict, List

def int_to_bytes(x: int) -> bytes:
return x.to_bytes(32, byteorder="big")

def eval_poly(poly: List[int], x: int) -> int:
"""Evaluate polynomial at a given point x."""
result = 0
for i, coeff in enumerate(poly):
result = (result + coeff * pow(x, i, curve_order)) % curve_order
return result

def generate(threshold: int = 3, key_count: int = 5) -> Dict[str, any]:
if threshold > key_count:
raise ValueError("threshold must be less than or equal to key_count")

# Generate random polynomial coefficients (secret is constant term)
poly = [random.randint(1, curve_order - 1) for _ in range(threshold)]
master_sk = poly[0] # constant term is master key

shares = []
for i in range(1, key_count + 1):
x = i
y = eval_poly(poly, x)
shares.append({
"index": x,
"key": int_to_bytes(y).hex()
})

return {
"masterKey": int_to_bytes(master_sk).hex(),
"keyShards": shares
}
18 changes: 18 additions & 0 deletions tests/test_encryption/test_generate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import unittest
from src.lighthouseweb3 import Kavach
from unittest.mock import patch

class TestGenerateKey(unittest.TestCase):
def test_generate_key_success(self):
result = Kavach.generate()
self.assertIsInstance(result["masterKey"], str, "masterKey should be a string")
self.assertEqual(len(result["keyShards"]), 5, "keyShards should have length 5")

def test_threshold_greater_than_key_count(self):
with self.assertRaises(ValueError) as context:
Kavach.generate(threshold=6, key_count=5)
self.assertEqual(
str(context.exception),
"threshold must be less than or equal to key_count",
"Expected ValueError for threshold > key_count"
)