Skip to content

Commit 6b7c846

Browse files
committed
Merge branch 'main' into feature_ipns_apis
2 parents df000ce + d95c8c0 commit 6b7c846

File tree

11 files changed

+266
-66
lines changed

11 files changed

+266
-66
lines changed

requirements-dev.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ charset-normalizer==3.1.0
44
idna==3.4
55
requests==2.31.0
66
urllib3==2.0.2
7+
web3
8+
eth-accounts

src/lighthouseweb3/__init__.py

Lines changed: 40 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,9 @@
77
deal_status,
88
get_uploads as getUploads,
99
download as _download,
10-
ipns_generate_key as ipnsGenerateKey,
11-
ipns_publish_record as ipnsPublishRecord,
12-
get_ipns_record as getIpnsRecord,
13-
remove_ipns_record as removeIpnsRecord,
10+
get_file_info as getFileInfo,
11+
get_balance as getBalance,
12+
get_api_key as getApiKey
1413
)
1514

1615

@@ -48,51 +47,14 @@ def uploadBlob(self, source: io.BufferedReader, filename: str, tag: str = ''):
4847
except Exception as e:
4948
raise e
5049

51-
def generateKey(self):
50+
def getBalance(self):
5251
"""
53-
Generate a new IPNS key for the authenticated user.
54-
:return: dict, The generated IPNS key information.
52+
Retrieve the balance information of a user from the Lighthouse.
53+
:param publicKey: str, The public key of the user.
54+
:return: dict[str, any], A dictionary containing the data usage and data limit details.
5555
"""
5656
try:
57-
return ipnsGenerateKey.ipns_generate_key(self.token)
58-
except Exception as e:
59-
raise e
60-
61-
def publishRecord(self, cid: str, keyName: str):
62-
"""
63-
Publish an IPNS record for a given CID and key name.
64-
65-
:param cid: str, Content Identifier to publish
66-
:param keyName: str, Name of the IPNS key to use
67-
:return: dict, The published IPNS record information
68-
"""
69-
try:
70-
return ipnsPublishRecord.ipns_publish_record(self.token, cid, keyName)
71-
except Exception as e:
72-
raise e
73-
74-
def getAllKeys(self):
75-
"""
76-
Retrieves all IPNS records associated with the current token.
77-
78-
return: list A list of IPNS records retrieved using the provided token.
79-
"""
80-
81-
try:
82-
return getIpnsRecord.get_ipns_records(self.token)
83-
except Exception as e:
84-
raise e
85-
86-
def removeKey(self, keyName: str):
87-
"""
88-
Remove IPNS record of the given keyName
89-
90-
:param keyName: str, Name of the IPNS key to use
91-
:return: dict, A dict of removed IPNS record.
92-
"""
93-
94-
try:
95-
return removeIpnsRecord.remove_ipns_record(self.token, keyName)
57+
return getBalance.get_balance(self.token)
9658
except Exception as e:
9759
raise e
9860

@@ -125,18 +87,16 @@ def getDealStatus(cid: str):
12587
return deal_status.get_deal_status(cid)
12688
except Exception as e:
12789
raise e
128-
129-
@staticmethod
130-
def getUploads(publicKey: str, pageNo: int = 1):
90+
91+
def getUploads(self, lastKey: str = None):
13192
"""
13293
Get uploads from the Lighthouse.
13394
134-
:param publicKey: str, public key
135-
:param pageNo: int, page number (default: 1)
95+
:param lastKey: To navigate to different pages of results
13696
:return: List[t.DealData], list of deal data
13797
"""
13898
try:
139-
return getUploads.get_uploads(publicKey, pageNo)
99+
return getUploads.get_uploads(self.token, lastKey)
140100
except Exception as e:
141101
raise e
142102

@@ -153,6 +113,34 @@ def download(cid: str):
153113
return _download.get_file(cid)
154114
except Exception as e:
155115
raise e
116+
117+
@staticmethod
118+
def getFileInfo(cid: str):
119+
"""
120+
Retrieves information about a file using its CID (Content Identifier).
121+
:param cid: str, Content Identifier for the data to be downloaded
122+
returns: dict, A dictionary containing file information.
123+
"""
124+
125+
try:
126+
return getFileInfo.get_file_info(cid)
127+
except Exception as e:
128+
raise e
129+
130+
@staticmethod
131+
def getApiKey(publicKey: str, signedMessage: str):
132+
"""
133+
Generates and returns an API key for the given public key and signed message.
134+
:param publicKey: str, The public key associated with the user.
135+
:param signedMessage: str, The message signed by the user's private key.
136+
:return: dict, A dict with generated API key.
137+
"""
138+
139+
140+
try:
141+
return getApiKey.get_api_key(publicKey, signedMessage)
142+
except Exception as e:
143+
raise e
156144

157145
def getTagged(self, tag: str):
158146
"""
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from .config import Config
2+
import requests as req
3+
4+
def get_api_key(publicKey: str, signedMessage: str):
5+
url = f"{Config.lighthouse_api}/api/auth/create_api_key"
6+
7+
data = {
8+
"publicKey": publicKey,
9+
"signedMessage": signedMessage
10+
}
11+
12+
try:
13+
response = req.post(url, data=data)
14+
except Exception as e:
15+
raise Exception("Failed to create api key")
16+
17+
if response.status_code != 200:
18+
return response.json()
19+
20+
apiKey = response.json()
21+
22+
result = {
23+
"data": {
24+
"apiKey" : apiKey
25+
}
26+
}
27+
28+
return result
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from .config import Config
2+
import requests as req
3+
4+
def get_balance(token:str):
5+
headers = {
6+
"Authorization": f"Bearer {token}",
7+
}
8+
url = f"{Config.lighthouse_api}/api/user/user_data_usage"
9+
try:
10+
response = req.get(url, headers=headers)
11+
except Exception as e:
12+
raise Exception("Failed to get account balance")
13+
14+
return response.json()
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from .config import Config
2+
import requests as req
3+
4+
def get_file_info(cid: str):
5+
url = f"{Config.lighthouse_api}/api/lighthouse/file_info?cid={cid}"
6+
try:
7+
response = req.get(url)
8+
except Exception as e:
9+
raise Exception("Failed to get file metadata")
10+
11+
return response.json()

src/lighthouseweb3/functions/get_uploads.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,14 @@ def bytes_to_size(bytes_size):
1111
return f"{round(bytes_size, 2)} {units[index]}"
1212

1313

14-
def get_uploads(publicKey: str, pageNo: int = 1) :
14+
def get_uploads(token: str, lastKey: str = None) :
15+
headers = {
16+
"Authorization": f"Bearer {token}",
17+
}
18+
1519
try:
16-
url = f"{Config.lighthouse_api}/api/user/files_uploaded?publicKey={publicKey}&pageNo={pageNo}"
17-
response = requests.get(url)
20+
url = f"{Config.lighthouse_api}/api/user/files_uploaded?lastKey={lastKey}"
21+
response = requests.get(url, headers=headers)
1822
response.raise_for_status()
1923
return response.json()
2024
except requests.HTTPError as error:

tests/test_deal_status.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def test_deal_status(self):
1515
"QmT9shXpKcn4HRbJhXJ1ZywzwjEo2QWbxAx4SVgW4eYKjG")
1616
self.assertIsInstance(res, list, "data is a list")
1717
self.assertIsInstance(res[0].get(
18-
"dealId"), int, "dealId is Int")
18+
"DealID"), int, "DealID is Int")
1919

2020
def test_deal_status_init(self):
2121
"""test deal_status function"""
@@ -25,4 +25,4 @@ def test_deal_status_init(self):
2525
"QmT9shXpKcn4HRbJhXJ1ZywzwjEo2QWbxAx4SVgW4eYKjG")
2626
self.assertIsInstance(res, list, "data is a list")
2727
self.assertIsInstance(res[0].get(
28-
"dealId"), int, "dealId is Int")
28+
"DealID"), int, "DealID is Int")

tests/test_get_api_key.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import unittest
4+
from src.lighthouseweb3 import Lighthouse
5+
from .setup import parse_env
6+
import requests as req
7+
from src.lighthouseweb3.functions.config import Config
8+
from web3 import Web3
9+
from eth_account.messages import encode_defunct
10+
11+
12+
class TestGetApiKey(unittest.TestCase):
13+
14+
def test_get_api_key(self):
15+
"""test getApiKey using valid signed message and public key"""
16+
parse_env()
17+
publicKey = os.environ.get("PUBLIC_KEY")
18+
response = req.get(
19+
f"{Config.lighthouse_api}/api/auth/get_auth_message?publicKey={publicKey}"
20+
)
21+
22+
if(response.status_code != 200):
23+
raise Exception("Failed to get authentication message")
24+
25+
verificationMessage = response.json()
26+
27+
self.assertIn("Please prove you are the owner", verificationMessage, "Owner response should come")
28+
29+
encodedMessage = encode_defunct(text=verificationMessage)
30+
31+
32+
signedMessage = Web3().eth.account.sign_message(
33+
encodedMessage,
34+
private_key=os.environ.get("PRIVATE_KEY")
35+
).signature.hex()
36+
37+
res = Lighthouse.getApiKey(publicKey, f"0x{signedMessage}")
38+
39+
self.assertIsInstance(res, dict, "res is a dict")
40+
self.assertIsInstance(res.get("data"), dict, "data is a dict")
41+
self.assertIsInstance(res.get('data').get('apiKey'), str, "apiKey is a string")
42+
43+
def test_get_api_key_with_invalid_message(self):
44+
"""test getApiKey using signed invalid message and public key"""
45+
parse_env()
46+
publicKey = os.environ.get("PUBLIC_KEY")
47+
encodedMessage = encode_defunct(text='random_message')
48+
49+
50+
signedMessage = Web3().eth.account.sign_message(
51+
encodedMessage,
52+
private_key=os.environ.get("PRIVATE_KEY")
53+
).signature.hex()
54+
55+
res = Lighthouse.getApiKey(publicKey, f"0x{signedMessage}")
56+
self.assertIsInstance(res, dict, "res is a dict")
57+
self.assertIsInstance(res.get("error"), dict, "data is a dict")
58+
59+
def test_get_api_key_with_random_private_key(self):
60+
"""test getApiKey using signed message with invalid private key and public key"""
61+
62+
parse_env()
63+
publicKey = os.environ.get("PUBLIC_KEY")
64+
response = req.get(
65+
f"{Config.lighthouse_api}/api/auth/get_auth_message?publicKey={publicKey}"
66+
)
67+
68+
if(response.status_code != 200):
69+
raise Exception("Failed to get authentication message")
70+
71+
verificationMessage = response.json()
72+
73+
self.assertIn("Please prove you are the owner", verificationMessage, "Owner response should come")
74+
75+
encodedMessage = encode_defunct(text=verificationMessage)
76+
77+
78+
signedMessage = Web3().eth.account.sign_message(
79+
encodedMessage,
80+
private_key='0x8218aa5dbf4dbec243142286b93e26af521b3e91219583595a06a7765abc9c8b'
81+
).signature.hex()
82+
83+
res = Lighthouse.getApiKey(publicKey, f"0x{signedMessage}")
84+
85+
self.assertIsInstance(res, dict, "res is a dict")
86+
self.assertIsInstance(res.get("error"), dict, "data is a dict")

tests/test_get_balance.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import unittest
4+
from src.lighthouseweb3 import Lighthouse
5+
from .setup import parse_env
6+
7+
8+
class TestGetBalance(unittest.TestCase):
9+
10+
def test_get_balance(self):
11+
"""test get_balance function"""
12+
parse_env()
13+
l = Lighthouse(os.environ.get("LIGHTHOUSE_TOKEN"))
14+
res = l.getBalance()
15+
self.assertIsInstance(res, dict, "data is a dict")
16+
self.assertIsInstance(res.get("dataLimit"), int, "data limit is a integer")
17+
self.assertIsInstance(res.get("dataUsed"), int, "data used is a integer")
18+
19+
def test_get_balance_invalid_token(self):
20+
"""test get_balance function with invalid token"""
21+
parse_env()
22+
l = Lighthouse('invalid_token')
23+
res = l.getBalance()
24+
self.assertIsInstance(res, dict, "res is a dict")
25+
self.assertIn("authentication failed", str(res).lower())
26+

tests/test_get_file_info.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import unittest
4+
from src.lighthouseweb3 import Lighthouse
5+
from .setup import parse_env
6+
7+
8+
class TestGetFileInfo(unittest.TestCase):
9+
10+
def test_get_file_info(self):
11+
"""test get_file_info function"""
12+
parse_env()
13+
l = Lighthouse(os.environ.get("LIGHTHOUSE_TOKEN"))
14+
res = l.getFileInfo("Qmd5MBBScDUV3Ly8qahXtZFqyRRfYSmUwEcxpYcV4hzKfW")
15+
self.assertIsInstance(res, dict, "data is a dict")
16+
self.assertEqual(res.get("cid"),"Qmd5MBBScDUV3Ly8qahXtZFqyRRfYSmUwEcxpYcV4hzKfW", "cid is matching")
17+
18+
def test_get_file_info_invalid_token(self):
19+
"""test get_upload with invalid token"""
20+
with self.assertRaises(Exception) as context:
21+
l = Lighthouse("invalid_token")
22+
l.getFileInfo("Qmd5MBBScDUV3Ly8qahXtZFqyRRfYSmUwEcxpYcV4hzKfW")
23+
self.assertIn("authentication failed", str(context.exception).lower())
24+
25+
def test_get_file_info_invalid_cid(self):
26+
parse_env()
27+
l = Lighthouse(os.environ.get("LIGHTHOUSE_TOKEN"))
28+
res = l.getFileInfo("invalid_cid")
29+
self.assertIsInstance(res, dict, "res is dict")
30+
self.assertIsInstance(res.get('error'), dict, "error is dict")
31+
self.assertEqual(res.get("error").get('message'), 'Not Found', 'cid not found')

0 commit comments

Comments
 (0)