rubix-py 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rubix_py-0.1.0/LICENSE +21 -0
- rubix_py-0.1.0/PKG-INFO +105 -0
- rubix_py-0.1.0/README.md +0 -0
- rubix_py-0.1.0/docs/readme.rst +83 -0
- rubix_py-0.1.0/pyproject.toml +31 -0
- rubix_py-0.1.0/rubix/__init__.py +0 -0
- rubix_py-0.1.0/rubix/client.py +166 -0
- rubix_py-0.1.0/rubix/crypto/bip39.py +31 -0
- rubix_py-0.1.0/rubix/crypto/secp256k1.py +79 -0
- rubix_py-0.1.0/rubix/did.py +138 -0
- rubix_py-0.1.0/rubix/models/querier.py +79 -0
- rubix_py-0.1.0/rubix/models/result.py +16 -0
- rubix_py-0.1.0/rubix/querier.py +219 -0
- rubix_py-0.1.0/rubix/signer.py +551 -0
- rubix_py-0.1.0/rubix/utils/validate.py +41 -0
- rubix_py-0.1.0/rubix_py.egg-info/PKG-INFO +105 -0
- rubix_py-0.1.0/rubix_py.egg-info/SOURCES.txt +20 -0
- rubix_py-0.1.0/rubix_py.egg-info/dependency_links.txt +1 -0
- rubix_py-0.1.0/rubix_py.egg-info/requires.txt +6 -0
- rubix_py-0.1.0/rubix_py.egg-info/top_level.txt +1 -0
- rubix_py-0.1.0/setup.cfg +4 -0
- rubix_py-0.1.0/tests/test_client.py +10 -0
rubix_py-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Rubix
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
rubix_py-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rubix-py
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Rubix Client SDK for Python
|
|
5
|
+
Author-email: Arnab Ghose <arnab.g@rubix.net>
|
|
6
|
+
Maintainer-email: Arnab Ghose <arnab.g@rubix.net>
|
|
7
|
+
License: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/rubixchain/rubix-sdk-py
|
|
9
|
+
Project-URL: Repository, https://github.com/rubixchain/rubix-sdk-py
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/rubixchain/rubix-sdk-py/issues
|
|
11
|
+
Keywords: blockchain,web3,sdk,cryptography,nft
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/x-rst
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: requests>=2.31.0
|
|
16
|
+
Requires-Dist: ecdsa>=0.19.1
|
|
17
|
+
Requires-Dist: bip32utils>=0.3.post4
|
|
18
|
+
Requires-Dist: mnemonic>=0.21
|
|
19
|
+
Requires-Dist: ECPy>=1.2.5
|
|
20
|
+
Requires-Dist: py-cid>=0.3.1
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
Rubix Client SDK for Python
|
|
24
|
+
============================
|
|
25
|
+
|
|
26
|
+
``rubix-py`` is a lightweight client for the Rubix Blockchain Node, providing complete node interaction with minimal overhead.
|
|
27
|
+
|
|
28
|
+
⚠️ This project is currently under **active development**. API changes and method signature updates may occur between releases. Please review the **Release Notes** before upgrading.
|
|
29
|
+
|
|
30
|
+
Installation
|
|
31
|
+
============
|
|
32
|
+
|
|
33
|
+
Run the following to install ``rubix-py``
|
|
34
|
+
|
|
35
|
+
.. code-block:: shell
|
|
36
|
+
|
|
37
|
+
pip install rubix-py
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
Architecture
|
|
41
|
+
============
|
|
42
|
+
|
|
43
|
+
The architecture of ``rubix-py`` is pretty straightforward. It consists of the following classes:
|
|
44
|
+
|
|
45
|
+
- ``RubixClient``: Responsible for connection to Rubix Blockchain Node
|
|
46
|
+
- ``Signer``: Signs and performs Blockchain transactions and manages user's crypto keys.
|
|
47
|
+
- ``Querier``: Queries information such as Token Balances, Smart Contract and NFT token chains, etc.
|
|
48
|
+
|
|
49
|
+
``RubixClient`` has a set of internal methods to make API requests to the node. Both ``Signer`` and ``Querier`` consumes an instance of ``RubixClient`` which helps them to achieve their respective operations with the Blockchain node.
|
|
50
|
+
|
|
51
|
+
Let's have a look at a simple example of fetching RBT balance and transferring them:
|
|
52
|
+
|
|
53
|
+
.. code-block:: python
|
|
54
|
+
|
|
55
|
+
from rubix.client import RubixClient
|
|
56
|
+
from rubix.signer import Signer
|
|
57
|
+
from rubix.querier import Querier
|
|
58
|
+
|
|
59
|
+
# Define the RubixClient by specifying the target Rubix node address
|
|
60
|
+
# and optionally providing timeout in seconds
|
|
61
|
+
client = RubixClient(node_url="http://localhost:20000", timeout=300)
|
|
62
|
+
|
|
63
|
+
# Define the Signer
|
|
64
|
+
# If you already have a BIP-39 24-word mnemonic, you can pass it to the Signer
|
|
65
|
+
# Else, a random mnemonic will be used
|
|
66
|
+
signer = Signer(
|
|
67
|
+
rubixClient=client,
|
|
68
|
+
mnemonic="<Enter 24-word long BIP-39 mnemonic>" # This can be left empty
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
# Internally, a call is made to Rubix Node to create and register your DID
|
|
72
|
+
user_did = signer.did
|
|
73
|
+
|
|
74
|
+
# Retrieve the keypair which can be used for signing arbitrary message
|
|
75
|
+
keypair = signer.get_keypair()
|
|
76
|
+
|
|
77
|
+
# Retrieve the mnemonic
|
|
78
|
+
mnemonic = signer.get_mnemonic()
|
|
79
|
+
|
|
80
|
+
# Define the Querier
|
|
81
|
+
queryClient = Querier(
|
|
82
|
+
rubixClient=client
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# Check RBT balance
|
|
86
|
+
balance_info = queryClient.get_rbt_balance(user_did)
|
|
87
|
+
balance = balance_info["rbt"]
|
|
88
|
+
|
|
89
|
+
# Perform RBT Transfer
|
|
90
|
+
tx_response = signer.send_rbt_tokens(
|
|
91
|
+
receiver_did="<Enter recipient DID>",
|
|
92
|
+
rbt_amount=0.001,
|
|
93
|
+
comment="Test RBT Transfer"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
if tx_response["status"] is True:
|
|
97
|
+
print("RBT Transfer Successful!")
|
|
98
|
+
else:
|
|
99
|
+
print("RBT Transfer Failed!: ", tx_response.get("message", ""))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
Usage
|
|
103
|
+
=====
|
|
104
|
+
|
|
105
|
+
Refer `examples <https://github.com/your-org/rubix-py/tree/main/examples>`_ for more usecases
|
rubix_py-0.1.0/README.md
ADDED
|
Binary file
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Rubix Client SDK for Python
|
|
2
|
+
============================
|
|
3
|
+
|
|
4
|
+
``rubix-py`` is a lightweight client for the Rubix Blockchain Node, providing complete node interaction with minimal overhead.
|
|
5
|
+
|
|
6
|
+
⚠️ This project is currently under **active development**. API changes and method signature updates may occur between releases. Please review the **Release Notes** before upgrading.
|
|
7
|
+
|
|
8
|
+
Installation
|
|
9
|
+
============
|
|
10
|
+
|
|
11
|
+
Run the following to install ``rubix-py``
|
|
12
|
+
|
|
13
|
+
.. code-block:: shell
|
|
14
|
+
|
|
15
|
+
pip install rubix-py
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
Architecture
|
|
19
|
+
============
|
|
20
|
+
|
|
21
|
+
The architecture of ``rubix-py`` is pretty straightforward. It consists of the following classes:
|
|
22
|
+
|
|
23
|
+
- ``RubixClient``: Responsible for connection to Rubix Blockchain Node
|
|
24
|
+
- ``Signer``: Signs and performs Blockchain transactions and manages user's crypto keys.
|
|
25
|
+
- ``Querier``: Queries information such as Token Balances, Smart Contract and NFT token chains, etc.
|
|
26
|
+
|
|
27
|
+
``RubixClient`` has a set of internal methods to make API requests to the node. Both ``Signer`` and ``Querier`` consumes an instance of ``RubixClient`` which helps them to achieve their respective operations with the Blockchain node.
|
|
28
|
+
|
|
29
|
+
Let's have a look at a simple example of fetching RBT balance and transferring them:
|
|
30
|
+
|
|
31
|
+
.. code-block:: python
|
|
32
|
+
|
|
33
|
+
from rubix.client import RubixClient
|
|
34
|
+
from rubix.signer import Signer
|
|
35
|
+
from rubix.querier import Querier
|
|
36
|
+
|
|
37
|
+
# Define the RubixClient by specifying the target Rubix node address
|
|
38
|
+
# and optionally providing timeout in seconds
|
|
39
|
+
client = RubixClient(node_url="http://localhost:20000", timeout=300)
|
|
40
|
+
|
|
41
|
+
# Define the Signer
|
|
42
|
+
# If you already have a BIP-39 24-word mnemonic, you can pass it to the Signer
|
|
43
|
+
# Else, a random mnemonic will be used
|
|
44
|
+
signer = Signer(
|
|
45
|
+
rubixClient=client,
|
|
46
|
+
mnemonic="<Enter 24-word long BIP-39 mnemonic>" # This can be left empty
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
# Internally, a call is made to Rubix Node to create and register your DID
|
|
50
|
+
user_did = signer.did
|
|
51
|
+
|
|
52
|
+
# Retrieve the keypair which can be used for signing arbitrary message
|
|
53
|
+
keypair = signer.get_keypair()
|
|
54
|
+
|
|
55
|
+
# Retrieve the mnemonic
|
|
56
|
+
mnemonic = signer.get_mnemonic()
|
|
57
|
+
|
|
58
|
+
# Define the Querier
|
|
59
|
+
queryClient = Querier(
|
|
60
|
+
rubixClient=client
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# Check RBT balance
|
|
64
|
+
balance_info = queryClient.get_rbt_balance(user_did)
|
|
65
|
+
balance = balance_info["rbt"]
|
|
66
|
+
|
|
67
|
+
# Perform RBT Transfer
|
|
68
|
+
tx_response = signer.send_rbt_tokens(
|
|
69
|
+
receiver_did="<Enter recipient DID>",
|
|
70
|
+
rbt_amount=0.001,
|
|
71
|
+
comment="Test RBT Transfer"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
if tx_response["status"] is True:
|
|
75
|
+
print("RBT Transfer Successful!")
|
|
76
|
+
else:
|
|
77
|
+
print("RBT Transfer Failed!: ", tx_response.get("message", ""))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
Usage
|
|
81
|
+
=====
|
|
82
|
+
|
|
83
|
+
Refer `examples <https://github.com/your-org/rubix-py/tree/main/examples>`_ for more usecases
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools >= 64.0.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rubix-py"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Rubix Client SDK for Python"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
readme = "docs/readme.rst"
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Arnab Ghose", email = "arnab.g@rubix.net" }
|
|
14
|
+
]
|
|
15
|
+
maintainers = [
|
|
16
|
+
{ name = "Arnab Ghose", email = "arnab.g@rubix.net" }
|
|
17
|
+
]
|
|
18
|
+
keywords = ["blockchain", "web3", "sdk", "cryptography", "nft"]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"requests>=2.31.0",
|
|
21
|
+
"ecdsa>=0.19.1",
|
|
22
|
+
"bip32utils>=0.3.post4",
|
|
23
|
+
"mnemonic>=0.21",
|
|
24
|
+
"ECPy>=1.2.5",
|
|
25
|
+
"py-cid>=0.3.1"
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/rubixchain/rubix-sdk-py"
|
|
30
|
+
Repository = "https://github.com/rubixchain/rubix-sdk-py"
|
|
31
|
+
"Bug Tracker" = "https://github.com/rubixchain/rubix-sdk-py/issues"
|
|
File without changes
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
from typing import Dict, Any, Optional
|
|
3
|
+
from urllib.parse import urljoin
|
|
4
|
+
|
|
5
|
+
class RubixClient:
|
|
6
|
+
def __init__(self, node_url: str, timeout: int = 300):
|
|
7
|
+
"""
|
|
8
|
+
Initialize Rubix client.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
node_url: Base URL of the Rubix node
|
|
12
|
+
timeout: Request timeout in seconds (default: 300)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
self.node_url = node_url.rstrip('/') # Remove trailing slash
|
|
16
|
+
self._timeout = timeout
|
|
17
|
+
|
|
18
|
+
def _make_get_request(
|
|
19
|
+
self,
|
|
20
|
+
endpoint: str,
|
|
21
|
+
params: Optional[Dict[str, Any]] = None
|
|
22
|
+
) -> Any:
|
|
23
|
+
"""
|
|
24
|
+
Protected method to make GET request to Rubix node.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
endpoint: API endpoint path
|
|
28
|
+
params: Optional query parameters as dictionary
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
JSON response as dictionary
|
|
32
|
+
|
|
33
|
+
Raises:
|
|
34
|
+
requests.exceptions.RequestException: If request fails
|
|
35
|
+
ValueError: If response is not valid JSON
|
|
36
|
+
"""
|
|
37
|
+
# Build full URL
|
|
38
|
+
url = urljoin(self.node_url, endpoint)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
response = requests.get(
|
|
42
|
+
url,
|
|
43
|
+
params=params,
|
|
44
|
+
timeout=self._timeout
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# Raise for HTTP errors (4xx, 5xx)
|
|
48
|
+
response.raise_for_status()
|
|
49
|
+
|
|
50
|
+
# Parse and return JSON
|
|
51
|
+
return response.json()
|
|
52
|
+
|
|
53
|
+
except requests.exceptions.Timeout:
|
|
54
|
+
raise requests.exceptions.RequestException(
|
|
55
|
+
f"GET request to {url} timed out after {self._timeout}s"
|
|
56
|
+
)
|
|
57
|
+
except requests.exceptions.ConnectionError:
|
|
58
|
+
raise requests.exceptions.RequestException(
|
|
59
|
+
f"Failed to connect to Rubix node at {url}"
|
|
60
|
+
)
|
|
61
|
+
except ValueError as e:
|
|
62
|
+
raise ValueError(f"Invalid JSON response from {url}: {e}")
|
|
63
|
+
|
|
64
|
+
def _make_post_request(
|
|
65
|
+
self,
|
|
66
|
+
endpoint: str,
|
|
67
|
+
json_data: Optional[Dict[str, Any]] = None,
|
|
68
|
+
params: Optional[Dict[str, Any]] = None
|
|
69
|
+
) -> Any:
|
|
70
|
+
"""
|
|
71
|
+
Protected method to make POST request to Rubix node.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
endpoint: API endpoint path (e.g., "/api/request-did-for-pubkey")
|
|
75
|
+
json_data: Optional JSON body data as dictionary
|
|
76
|
+
params: Optional query parameters as dictionary
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
JSON response as dictionary
|
|
80
|
+
|
|
81
|
+
Raises:
|
|
82
|
+
requests.exceptions.RequestException: If request fails
|
|
83
|
+
ValueError: If response is not valid JSON
|
|
84
|
+
"""
|
|
85
|
+
# Build full URL
|
|
86
|
+
url = urljoin(self.node_url, endpoint)
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
response = requests.post(
|
|
90
|
+
url,
|
|
91
|
+
json=json_data,
|
|
92
|
+
params=params,
|
|
93
|
+
timeout=self._timeout
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Raise for HTTP errors (4xx, 5xx)
|
|
97
|
+
response.raise_for_status()
|
|
98
|
+
|
|
99
|
+
# Parse and return JSON
|
|
100
|
+
return response.json()
|
|
101
|
+
|
|
102
|
+
except requests.exceptions.Timeout:
|
|
103
|
+
raise requests.exceptions.RequestException(
|
|
104
|
+
f"POST request to {url} timed out after {self._timeout}s"
|
|
105
|
+
)
|
|
106
|
+
except requests.exceptions.ConnectionError:
|
|
107
|
+
raise requests.exceptions.RequestException(
|
|
108
|
+
f"Failed to connect to Rubix node at {url}"
|
|
109
|
+
)
|
|
110
|
+
except ValueError as e:
|
|
111
|
+
raise ValueError(f"Invalid JSON response from {url}: {e}")
|
|
112
|
+
|
|
113
|
+
def _make_form_data_request(
|
|
114
|
+
self,
|
|
115
|
+
endpoint: str,
|
|
116
|
+
files: Any = None,
|
|
117
|
+
data: Any = None,
|
|
118
|
+
params: Any = None
|
|
119
|
+
) -> Any:
|
|
120
|
+
"""
|
|
121
|
+
Protected method to make multipart/form-data POST request to Rubix node.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
endpoint: API endpoint path (e.g., "/api/upload")
|
|
125
|
+
files: Dictionary of files to upload. Can be:
|
|
126
|
+
- {'field_name': file_object}
|
|
127
|
+
- {'field_name': ('filename', file_object)}
|
|
128
|
+
- {'field_name': ('filename', file_object, 'content_type')}
|
|
129
|
+
data: Dictionary of form fields (non-file data)
|
|
130
|
+
params: Optional query parameters as dictionary
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
JSON response as dictionary
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
requests.exceptions.RequestException: If request fails
|
|
137
|
+
ValueError: If response is not valid JSON
|
|
138
|
+
"""
|
|
139
|
+
# Build full URL
|
|
140
|
+
url = urljoin(self.node_url, endpoint)
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
response = requests.post(
|
|
144
|
+
url,
|
|
145
|
+
files=files,
|
|
146
|
+
data=data,
|
|
147
|
+
params=params,
|
|
148
|
+
timeout=self._timeout
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
# Raise for HTTP errors (4xx, 5xx)
|
|
152
|
+
response.raise_for_status()
|
|
153
|
+
|
|
154
|
+
# Parse and return JSON
|
|
155
|
+
return response.json()
|
|
156
|
+
|
|
157
|
+
except requests.exceptions.Timeout:
|
|
158
|
+
raise requests.exceptions.RequestException(
|
|
159
|
+
f"Form-data POST request to {url} timed out after {self._timeout}s"
|
|
160
|
+
)
|
|
161
|
+
except requests.exceptions.ConnectionError:
|
|
162
|
+
raise requests.exceptions.RequestException(
|
|
163
|
+
f"Failed to connect to Rubix node at {url}"
|
|
164
|
+
)
|
|
165
|
+
except ValueError as e:
|
|
166
|
+
raise ValueError(f"Invalid JSON response from {url}: {e}")
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from mnemonic import Mnemonic
|
|
2
|
+
|
|
3
|
+
def generate_bip39_mnemonic() -> str:
|
|
4
|
+
"""Generate a 24-word BIP39 mnemonic phrase.
|
|
5
|
+
|
|
6
|
+
Returns:
|
|
7
|
+
str: The generated BIP39 24-word mnemonic phrase.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
return Mnemonic("english").generate(strength=256)
|
|
11
|
+
|
|
12
|
+
def get_seed_from_mnemonic(mnemonic_phrase: str, passphrase: str = "") -> bytes:
|
|
13
|
+
"""Derive a seed from a BIP39 mnemonic phrase.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
mnemonic (str): The BIP39 mnemonic phrase.
|
|
17
|
+
passphrase (str): An optional passphrase to enhance security. Default is an empty string.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
bytes: The derived seed in bytes.
|
|
21
|
+
"""
|
|
22
|
+
if mnemonic_phrase is None or mnemonic_phrase.strip() == "":
|
|
23
|
+
raise ValueError("Mnemonic phrase cannot be empty.")
|
|
24
|
+
|
|
25
|
+
if not Mnemonic("english").check(mnemonic_phrase):
|
|
26
|
+
raise ValueError(f"Invalid mnemonic phrase: {mnemonic_phrase}")
|
|
27
|
+
|
|
28
|
+
if len(mnemonic_phrase.split()) != 24:
|
|
29
|
+
raise ValueError(f"Mnemonic phrase must be 24 words long, got {len(mnemonic_phrase.split())}.")
|
|
30
|
+
|
|
31
|
+
return Mnemonic("english").to_seed(mnemonic_phrase, passphrase=passphrase)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import bip32utils
|
|
2
|
+
import hashlib
|
|
3
|
+
import base64
|
|
4
|
+
|
|
5
|
+
from ecpy.curves import Curve
|
|
6
|
+
from ecpy.keys import ECPrivateKey
|
|
7
|
+
from ecpy.ecdsa import ECDSA
|
|
8
|
+
from ecdsa import SigningKey, SECP256k1, util
|
|
9
|
+
|
|
10
|
+
class Secp256k1Keypair:
|
|
11
|
+
def __init__(self, private_key: str, public_key: str):
|
|
12
|
+
self.__private_key: str = private_key
|
|
13
|
+
self.__public_key: str = public_key
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
def from_mnemonic_seed(mnemonic_seed: bytes) -> 'Secp256k1Keypair':
|
|
17
|
+
"""Generates a Secp256k1Keypair from a mnemonic seed.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
mnemonic_seed (bytes): The mnemonic seed used to derive the keypair.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
Secp256k1Keypair: The generated Secp256k1 keypair.
|
|
24
|
+
"""
|
|
25
|
+
bip32_root_key = bip32utils.BIP32Key.fromEntropy(mnemonic_seed)
|
|
26
|
+
bip32_child_key = bip32_root_key.ChildKey(0)
|
|
27
|
+
|
|
28
|
+
if not bip32_child_key:
|
|
29
|
+
raise ValueError("Failed to derive child key from mnemonic seed.")
|
|
30
|
+
|
|
31
|
+
private_key = bip32_child_key.PrivateKey()
|
|
32
|
+
|
|
33
|
+
return Secp256k1Keypair.from_private_key(private_key)
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def from_private_key(private_key: bytes) -> 'Secp256k1Keypair':
|
|
37
|
+
"""Generates a Secp256k1Keypair from a private key.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
private_key (bytes): The private key used to derive the keypair.
|
|
41
|
+
Returns:
|
|
42
|
+
Secp256k1Keypair: The generated Secp256k1 keypair.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
signing_key = SigningKey.from_string(private_key, curve=SECP256k1)
|
|
46
|
+
private_key_hex = signing_key.to_string().hex()
|
|
47
|
+
|
|
48
|
+
public_key = signing_key.get_verifying_key()
|
|
49
|
+
if not public_key:
|
|
50
|
+
raise ValueError("Failed to derive public key from private key.")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
public_key_hex = public_key.to_string("compressed").hex()
|
|
54
|
+
|
|
55
|
+
return Secp256k1Keypair(private_key_hex, public_key_hex)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def public_key(self) -> str:
|
|
59
|
+
"""Returns the public key in hexadecimal format."""
|
|
60
|
+
return self.__public_key
|
|
61
|
+
|
|
62
|
+
def sign(self, message: bytes) -> bytes:
|
|
63
|
+
"""Signs a message using the private key.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
message (bytes): The message to sign.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
str: The hexadecimal signature.
|
|
70
|
+
"""
|
|
71
|
+
cv = Curve.get_curve('secp256k1')
|
|
72
|
+
pv_key = ECPrivateKey(int(self.__private_key, 16), cv)
|
|
73
|
+
signer = ECDSA()
|
|
74
|
+
|
|
75
|
+
sig = signer.sign(message, pv_key)
|
|
76
|
+
if sig is None:
|
|
77
|
+
raise ValueError("Failed to sign the message.")
|
|
78
|
+
|
|
79
|
+
return sig
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import requests
|
|
3
|
+
|
|
4
|
+
from .crypto.secp256k1 import Secp256k1Keypair
|
|
5
|
+
from urllib.parse import urlparse, urljoin
|
|
6
|
+
|
|
7
|
+
class DIDCreationError(Exception):
|
|
8
|
+
"""Raised when DID creation fails."""
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
class DIDRegistrationError(Exception):
|
|
12
|
+
"""Raised when DID registration fails."""
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
class signatureResponseError(Exception):
|
|
16
|
+
"""Raised when signature response fails."""
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
# TODO: To be deprecated once the creation of DID is implemented on the
|
|
20
|
+
# 0x address scheme is implemented on RubixCore
|
|
21
|
+
# Creation of DID will become a method of Signer class
|
|
22
|
+
def create_did(keypair: Secp256k1Keypair, rubixNodeBaseUrl: str) -> None:
|
|
23
|
+
request_did_api_url = urlparse(rubixNodeBaseUrl)
|
|
24
|
+
if all([request_did_api_url.scheme, request_did_api_url.netloc]):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
# Create IPFS based DID
|
|
28
|
+
request_did_api_url = urljoin(rubixNodeBaseUrl, "/api/request-did-for-pubkey")
|
|
29
|
+
|
|
30
|
+
public_key = keypair.public_key
|
|
31
|
+
if public_key is None or public_key.strip() == "":
|
|
32
|
+
raise ValueError("Public key is required to create DID")
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
response = requests.post(
|
|
36
|
+
request_did_api_url,
|
|
37
|
+
json={"public_key": public_key},
|
|
38
|
+
timeout=300
|
|
39
|
+
)
|
|
40
|
+
response.raise_for_status()
|
|
41
|
+
|
|
42
|
+
except requests.exceptions.Timeout:
|
|
43
|
+
raise DIDCreationError("Request to Rubix node timed out")
|
|
44
|
+
except requests.exceptions.ConnectionError:
|
|
45
|
+
raise DIDCreationError(f"Failed to connect to Rubix node at {rubixNodeBaseUrl}")
|
|
46
|
+
except requests.exceptions.HTTPError as e:
|
|
47
|
+
raise DIDCreationError(f"HTTP error from Rubix node: {e}")
|
|
48
|
+
except requests.exceptions.RequestException as e:
|
|
49
|
+
raise DIDCreationError(f"Request failed: {e}")
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
response_body = response.json()
|
|
53
|
+
except ValueError:
|
|
54
|
+
raise DIDCreationError("Invalid JSON response from Rubix node")
|
|
55
|
+
|
|
56
|
+
if "status" in response_body and response_body["status"] is False:
|
|
57
|
+
raise DIDCreationError(f"DID creation failed: {response_body['message']}")
|
|
58
|
+
|
|
59
|
+
user_did = response_body["did"]
|
|
60
|
+
|
|
61
|
+
# Register the newly created DID
|
|
62
|
+
register_did_url = urljoin(rubixNodeBaseUrl, "/api/register-did")
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
response = requests.post(
|
|
66
|
+
register_did_url,
|
|
67
|
+
json={"did": user_did},
|
|
68
|
+
timeout=300
|
|
69
|
+
)
|
|
70
|
+
response.raise_for_status()
|
|
71
|
+
|
|
72
|
+
except requests.exceptions.Timeout:
|
|
73
|
+
raise DIDRegistrationError("Request to Rubix node timed out")
|
|
74
|
+
except requests.exceptions.ConnectionError:
|
|
75
|
+
raise DIDRegistrationError(f"Failed to connect to Rubix node at {rubixNodeBaseUrl}")
|
|
76
|
+
except requests.exceptions.HTTPError as e:
|
|
77
|
+
raise DIDRegistrationError(f"HTTP error from Rubix node: {e}")
|
|
78
|
+
except requests.exceptions.RequestException as e:
|
|
79
|
+
raise DIDRegistrationError(f"Request failed: {e}")
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
response_body = response.json()
|
|
83
|
+
except ValueError:
|
|
84
|
+
raise DIDRegistrationError("Invalid JSON response from Rubix node")
|
|
85
|
+
|
|
86
|
+
if "status" in response_body and response_body["status"] is False:
|
|
87
|
+
raise DIDRegistrationError(f"DID registeration failed: {response_body['message']}")
|
|
88
|
+
|
|
89
|
+
# Retrieve the message from response and sign
|
|
90
|
+
message = response_body["result"]["hash"]
|
|
91
|
+
|
|
92
|
+
if message is None or message.strip() == "":
|
|
93
|
+
raise DIDRegistrationError("No message to sign for DID registration")
|
|
94
|
+
|
|
95
|
+
# Decode and sign the message
|
|
96
|
+
message_bytes = base64.b64decode(message)
|
|
97
|
+
|
|
98
|
+
signature_bytes = keypair.sign(message_bytes)
|
|
99
|
+
|
|
100
|
+
# Send the signature-response request
|
|
101
|
+
signature_response_url = urljoin(rubixNodeBaseUrl, "/api/signature-response")
|
|
102
|
+
req_id = response_body["result"]["id"]
|
|
103
|
+
|
|
104
|
+
signature_response_body = {
|
|
105
|
+
"id": req_id,
|
|
106
|
+
"Signature": {
|
|
107
|
+
"Signature": list(map(int, signature_bytes))
|
|
108
|
+
},
|
|
109
|
+
"mode": 4
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
response = requests.post(
|
|
114
|
+
signature_response_url,
|
|
115
|
+
json=signature_response_body,
|
|
116
|
+
timeout=300
|
|
117
|
+
)
|
|
118
|
+
response.raise_for_status()
|
|
119
|
+
|
|
120
|
+
except requests.exceptions.Timeout:
|
|
121
|
+
raise signatureResponseError("Request to Rubix node timed out")
|
|
122
|
+
except requests.exceptions.ConnectionError:
|
|
123
|
+
raise signatureResponseError(f"Failed to connect to Rubix node at {rubixNodeBaseUrl}")
|
|
124
|
+
except requests.exceptions.HTTPError as e:
|
|
125
|
+
raise signatureResponseError(f"HTTP error from Rubix node: {e}")
|
|
126
|
+
except requests.exceptions.RequestException as e:
|
|
127
|
+
raise signatureResponseError(f"Request failed: {e}")
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
response_body = response.json()
|
|
131
|
+
except ValueError:
|
|
132
|
+
raise signatureResponseError("Invalid JSON response from Rubix node")
|
|
133
|
+
|
|
134
|
+
if response_body.get("status") is False:
|
|
135
|
+
raise signatureResponseError(f"Signature response failed: {response_body['message']}")
|
|
136
|
+
|
|
137
|
+
return user_did
|
|
138
|
+
|