rubix-py 0.1.0__py3-none-any.whl

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/__init__.py ADDED
File without changes
rubix/client.py ADDED
@@ -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}")
rubix/crypto/bip39.py ADDED
@@ -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
rubix/did.py ADDED
@@ -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
+
@@ -0,0 +1,79 @@
1
+ from dataclasses import dataclass
2
+
3
+ @dataclass
4
+ class RBTBalance:
5
+ """
6
+ Represents the RBT balance details for a user.
7
+
8
+ Attributes:
9
+ did (str): The user's DID.
10
+ rbt (str): The RBT balance associated with the DID.
11
+ """
12
+ did: str
13
+ rbt: str
14
+
15
+ @dataclass
16
+ class FTBalance:
17
+ """
18
+ Represents the balance details of a fungible token (FT).
19
+
20
+ Attributes:
21
+ ft_name (str): The name of the fungible token.
22
+ ft_count (int): The count of the fungible token.
23
+ creator_did (str): The DID of the creator of the fungible token.
24
+ """
25
+ ft_name: str
26
+ ft_count: int
27
+ creator_did: str
28
+
29
+ @dataclass
30
+ class SmartContractTokenBlock:
31
+ """
32
+ Represents a block of tokens in a smart contract.
33
+
34
+ Attributes:
35
+ BlockNo (int): The block number.
36
+ BlockId (str): The block ID.
37
+ SmartContractData (str): Arbitrary data provided to the smart contract.
38
+ Epoch (int): The epoch number.
39
+ InitiatorSignature (str): The signature of the initiator.
40
+ ExecutorDID (str): The DID of the executor.
41
+ InitiatorSignData (str): The sign data of the initiator.
42
+ """
43
+ BlockNo: int
44
+ BlockId: str
45
+ SmartContractData: str
46
+ Epoch: int
47
+ InitiatorSignature: str
48
+ ExecutorDID: str
49
+ InitiatorSignData: str
50
+
51
+ @dataclass
52
+ class NFTTokenBlock:
53
+ """
54
+ Represents a block of NFT token
55
+
56
+ Attributes:
57
+ BlockNo (int): The block number.
58
+ BlockId (str): The block ID.
59
+ NFTData (str): Arbitrary data provided to the NFT.
60
+ NFTOwner (str): The owner of the NFT.
61
+ NFTValue (float): The value of the NFT.
62
+ Epoch (int): Block Epoch.
63
+ TransactionID (str): The transaction ID associated with the NFT.
64
+ """
65
+ BlockNo: int
66
+ BlockId: str
67
+ NFTData: str
68
+ NFTOwner: str
69
+ NFTValue: float
70
+ Epoch: int
71
+ TransactionID: str
72
+
73
+ @dataclass
74
+ class NFTInfo:
75
+ nft: str
76
+ owner_did: str
77
+ nft_value: float
78
+ nft_metadata: str
79
+ nft_file_name: str
rubix/models/result.py ADDED
@@ -0,0 +1,16 @@
1
+ from dataclasses import dataclass
2
+
3
+ @dataclass
4
+ class Response:
5
+ """
6
+ Standard Response structure of Rubix Core
7
+
8
+ Attributes:
9
+ status (bool): The status of the response.
10
+ message (str): A message providing additional information about the response.
11
+ result (str | dict | None): The result data of the response, which can be a string, a dictionary, or None.
12
+ """
13
+ status: bool
14
+ message: str
15
+ result: str | dict | None
16
+