koi-net 1.0.0b19__py3-none-any.whl → 1.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.
Potentially problematic release.
This version of koi-net might be problematic. Click here for more details.
- koi_net/actor.py +60 -0
- koi_net/config.py +44 -18
- koi_net/context.py +63 -0
- koi_net/core.py +152 -84
- koi_net/default_actions.py +15 -0
- koi_net/effector.py +139 -0
- koi_net/identity.py +4 -22
- koi_net/lifecycle.py +104 -0
- koi_net/network/__init__.py +0 -1
- koi_net/network/error_handler.py +50 -0
- koi_net/network/event_queue.py +199 -0
- koi_net/network/graph.py +23 -38
- koi_net/network/request_handler.py +129 -66
- koi_net/network/resolver.py +150 -0
- koi_net/network/response_handler.py +15 -6
- koi_net/poller.py +40 -0
- koi_net/processor/__init__.py +0 -1
- koi_net/processor/default_handlers.py +71 -42
- koi_net/processor/handler.py +3 -7
- koi_net/processor/interface.py +15 -214
- koi_net/processor/knowledge_object.py +10 -17
- koi_net/processor/knowledge_pipeline.py +220 -0
- koi_net/protocol/api_models.py +18 -3
- koi_net/protocol/edge.py +26 -1
- koi_net/protocol/envelope.py +58 -0
- koi_net/protocol/errors.py +23 -0
- koi_net/protocol/event.py +0 -3
- koi_net/protocol/node.py +2 -1
- koi_net/protocol/secure.py +160 -0
- koi_net/secure.py +117 -0
- koi_net/server.py +129 -0
- {koi_net-1.0.0b19.dist-info → koi_net-1.1.0.dist-info}/METADATA +5 -4
- koi_net-1.1.0.dist-info/RECORD +38 -0
- koi_net/network/interface.py +0 -276
- koi_net/protocol/helpers.py +0 -25
- koi_net-1.0.0b19.dist-info/RECORD +0 -25
- {koi_net-1.0.0b19.dist-info → koi_net-1.1.0.dist-info}/WHEEL +0 -0
- {koi_net-1.0.0b19.dist-info → koi_net-1.1.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Callable
|
|
3
|
+
from rid_lib.core import RIDType
|
|
4
|
+
from rid_lib.types import KoiNetEdge, KoiNetNode
|
|
5
|
+
from rid_lib.ext import Cache
|
|
6
|
+
from ..protocol.event import EventType
|
|
7
|
+
from ..network.request_handler import RequestHandler
|
|
8
|
+
from ..network.event_queue import NetworkEventQueue
|
|
9
|
+
from ..network.graph import NetworkGraph
|
|
10
|
+
from ..identity import NodeIdentity
|
|
11
|
+
from .handler import (
|
|
12
|
+
KnowledgeHandler,
|
|
13
|
+
HandlerType,
|
|
14
|
+
STOP_CHAIN,
|
|
15
|
+
StopChain
|
|
16
|
+
)
|
|
17
|
+
from .knowledge_object import KnowledgeObject
|
|
18
|
+
|
|
19
|
+
from typing import TYPE_CHECKING
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from ..context import HandlerContext
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class KnowledgePipeline:
|
|
27
|
+
handler_context: "HandlerContext"
|
|
28
|
+
cache: Cache
|
|
29
|
+
identity: NodeIdentity
|
|
30
|
+
request_handler: RequestHandler
|
|
31
|
+
event_queue: NetworkEventQueue
|
|
32
|
+
graph: NetworkGraph
|
|
33
|
+
handlers: list[KnowledgeHandler]
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
handler_context: "HandlerContext",
|
|
38
|
+
cache: Cache,
|
|
39
|
+
request_handler: RequestHandler,
|
|
40
|
+
event_queue: NetworkEventQueue,
|
|
41
|
+
graph: NetworkGraph,
|
|
42
|
+
default_handlers: list[KnowledgeHandler] = []
|
|
43
|
+
):
|
|
44
|
+
self.handler_context = handler_context
|
|
45
|
+
self.cache = cache
|
|
46
|
+
self.request_handler = request_handler
|
|
47
|
+
self.event_queue = event_queue
|
|
48
|
+
self.graph = graph
|
|
49
|
+
self.handlers = default_handlers
|
|
50
|
+
|
|
51
|
+
def add_handler(self, handler: KnowledgeHandler):
|
|
52
|
+
self.handlers.append(handler)
|
|
53
|
+
|
|
54
|
+
def register_handler(
|
|
55
|
+
self,
|
|
56
|
+
handler_type: HandlerType,
|
|
57
|
+
rid_types: list[RIDType] | None = None,
|
|
58
|
+
event_types: list[EventType | None] | None = None
|
|
59
|
+
):
|
|
60
|
+
"""Assigns decorated function as handler for this processor."""
|
|
61
|
+
def decorator(func: Callable) -> Callable:
|
|
62
|
+
handler = KnowledgeHandler(func, handler_type, rid_types, event_types)
|
|
63
|
+
self.add_handler(handler)
|
|
64
|
+
return func
|
|
65
|
+
return decorator
|
|
66
|
+
|
|
67
|
+
def call_handler_chain(
|
|
68
|
+
self,
|
|
69
|
+
handler_type: HandlerType,
|
|
70
|
+
kobj: KnowledgeObject
|
|
71
|
+
) -> KnowledgeObject | StopChain:
|
|
72
|
+
"""Calls handlers of provided type, chaining their inputs and outputs together.
|
|
73
|
+
|
|
74
|
+
The knowledge object provided when this function is called will be passed to the first handler. A handler may return one of three types:
|
|
75
|
+
- `KnowledgeObject` - to modify the knowledge object for the next handler in the chain
|
|
76
|
+
- `None` - to keep the same knowledge object for the next handler in the chain
|
|
77
|
+
- `STOP_CHAIN` - to stop the handler chain and immediately exit the processing pipeline
|
|
78
|
+
|
|
79
|
+
Handlers will only be called in the chain if their handler and RID type match that of the inputted knowledge object.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
for handler in self.handlers:
|
|
83
|
+
if handler_type != handler.handler_type:
|
|
84
|
+
continue
|
|
85
|
+
|
|
86
|
+
if handler.rid_types and type(kobj.rid) not in handler.rid_types:
|
|
87
|
+
continue
|
|
88
|
+
|
|
89
|
+
if handler.event_types and kobj.event_type not in handler.event_types:
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
logger.debug(f"Calling {handler_type} handler '{handler.func.__name__}'")
|
|
93
|
+
|
|
94
|
+
resp = handler.func(
|
|
95
|
+
ctx=self.handler_context,
|
|
96
|
+
kobj=kobj.model_copy()
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# stops handler chain execution
|
|
100
|
+
if resp is STOP_CHAIN:
|
|
101
|
+
logger.debug(f"Handler chain stopped by {handler.func.__name__}")
|
|
102
|
+
return STOP_CHAIN
|
|
103
|
+
# kobj unmodified
|
|
104
|
+
elif resp is None:
|
|
105
|
+
continue
|
|
106
|
+
# kobj modified by handler
|
|
107
|
+
elif isinstance(resp, KnowledgeObject):
|
|
108
|
+
kobj = resp
|
|
109
|
+
logger.debug(f"Knowledge object modified by {handler.func.__name__}")
|
|
110
|
+
else:
|
|
111
|
+
raise ValueError(f"Handler {handler.func.__name__} returned invalid response '{resp}'")
|
|
112
|
+
|
|
113
|
+
return kobj
|
|
114
|
+
|
|
115
|
+
def process(self, kobj: KnowledgeObject):
|
|
116
|
+
"""Sends provided knowledge obejct through knowledge processing pipeline.
|
|
117
|
+
|
|
118
|
+
Handler chains are called in between major events in the pipeline, indicated by their handler type. Each handler type is guaranteed to have access to certain knowledge, and may affect a subsequent action in the pipeline. The five handler types are as follows:
|
|
119
|
+
- RID - provided RID; if event type is `FORGET`, this handler decides whether to delete the knowledge from the cache by setting the normalized event type to `FORGET`, otherwise this handler decides whether to validate the manifest (and fetch it if not provided).
|
|
120
|
+
- Manifest - provided RID, manifest; decides whether to validate the bundle (and fetch it if not provided).
|
|
121
|
+
- Bundle - provided RID, manifest, contents (bundle); decides whether to write knowledge to the cache by setting the normalized event type to `NEW` or `UPDATE`.
|
|
122
|
+
- Network - provided RID, manifest, contents (bundle); decides which nodes (if any) to broadcast an event about this knowledge to. (Note, if event type is `FORGET`, the manifest and contents will be retrieved from the local cache, and indicate the last state of the knowledge before it was deleted.)
|
|
123
|
+
- Final - provided RID, manifests, contents (bundle); final action taken after network broadcast.
|
|
124
|
+
|
|
125
|
+
The pipeline may be stopped by any point by a single handler returning the `STOP_CHAIN` sentinel. In that case, the process will exit immediately. Further handlers of that type and later handler chains will not be called.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
logger.debug(f"Handling {kobj!r}")
|
|
129
|
+
kobj = self.call_handler_chain(HandlerType.RID, kobj)
|
|
130
|
+
if kobj is STOP_CHAIN: return
|
|
131
|
+
|
|
132
|
+
if kobj.event_type == EventType.FORGET:
|
|
133
|
+
bundle = self.cache.read(kobj.rid)
|
|
134
|
+
if not bundle:
|
|
135
|
+
logger.debug("Local bundle not found")
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
# the bundle (to be deleted) attached to kobj for downstream analysis
|
|
139
|
+
logger.debug("Adding local bundle (to be deleted) to knowledge object")
|
|
140
|
+
kobj.manifest = bundle.manifest
|
|
141
|
+
kobj.contents = bundle.contents
|
|
142
|
+
|
|
143
|
+
else:
|
|
144
|
+
# attempt to retrieve manifest
|
|
145
|
+
if not kobj.manifest:
|
|
146
|
+
logger.debug("Manifest not found")
|
|
147
|
+
if not kobj.source:
|
|
148
|
+
return
|
|
149
|
+
|
|
150
|
+
logger.debug("Attempting to fetch remote manifest from source")
|
|
151
|
+
payload = self.request_handler.fetch_manifests(
|
|
152
|
+
node=kobj.source,
|
|
153
|
+
rids=[kobj.rid]
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
if not payload.manifests:
|
|
157
|
+
logger.debug("Failed to find manifest")
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
kobj.manifest = payload.manifests[0]
|
|
161
|
+
|
|
162
|
+
kobj = self.call_handler_chain(HandlerType.Manifest, kobj)
|
|
163
|
+
if kobj is STOP_CHAIN: return
|
|
164
|
+
|
|
165
|
+
# attempt to retrieve bundle
|
|
166
|
+
if not kobj.bundle:
|
|
167
|
+
logger.debug("Bundle not found")
|
|
168
|
+
if kobj.source is None:
|
|
169
|
+
return
|
|
170
|
+
|
|
171
|
+
logger.debug("Attempting to fetch remote bundle from source")
|
|
172
|
+
payload = self.request_handler.fetch_bundles(
|
|
173
|
+
node=kobj.source,
|
|
174
|
+
rids=[kobj.rid]
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
if not payload.bundles:
|
|
178
|
+
logger.debug("Failed to find bundle")
|
|
179
|
+
return
|
|
180
|
+
|
|
181
|
+
bundle = payload.bundles[0]
|
|
182
|
+
|
|
183
|
+
if kobj.manifest != bundle.manifest:
|
|
184
|
+
logger.warning("Retrieved bundle contains a different manifest")
|
|
185
|
+
|
|
186
|
+
kobj.manifest = bundle.manifest
|
|
187
|
+
kobj.contents = bundle.contents
|
|
188
|
+
|
|
189
|
+
kobj = self.call_handler_chain(HandlerType.Bundle, kobj)
|
|
190
|
+
if kobj is STOP_CHAIN: return
|
|
191
|
+
|
|
192
|
+
if kobj.normalized_event_type in (EventType.UPDATE, EventType.NEW):
|
|
193
|
+
logger.info(f"Writing to cache: {kobj!r}")
|
|
194
|
+
self.cache.write(kobj.bundle)
|
|
195
|
+
|
|
196
|
+
elif kobj.normalized_event_type == EventType.FORGET:
|
|
197
|
+
logger.info(f"Deleting from cache: {kobj!r}")
|
|
198
|
+
self.cache.delete(kobj.rid)
|
|
199
|
+
|
|
200
|
+
else:
|
|
201
|
+
logger.debug("Normalized event type was never set, no cache or network operations will occur")
|
|
202
|
+
return
|
|
203
|
+
|
|
204
|
+
if type(kobj.rid) in (KoiNetNode, KoiNetEdge):
|
|
205
|
+
logger.debug("Change to node or edge, regenerating network graph")
|
|
206
|
+
self.graph.generate()
|
|
207
|
+
|
|
208
|
+
kobj = self.call_handler_chain(HandlerType.Network, kobj)
|
|
209
|
+
if kobj is STOP_CHAIN: return
|
|
210
|
+
|
|
211
|
+
if kobj.network_targets:
|
|
212
|
+
logger.debug(f"Broadcasting event to {len(kobj.network_targets)} network target(s)")
|
|
213
|
+
else:
|
|
214
|
+
logger.debug("No network targets set")
|
|
215
|
+
|
|
216
|
+
for node in kobj.network_targets:
|
|
217
|
+
self.event_queue.push_event_to(kobj.normalized_event, node)
|
|
218
|
+
self.event_queue.flush_webhook_queue(node)
|
|
219
|
+
|
|
220
|
+
kobj = self.call_handler_chain(HandlerType.Final, kobj)
|
koi_net/protocol/api_models.py
CHANGED
|
@@ -1,47 +1,62 @@
|
|
|
1
1
|
"""Pydantic models for request and response/payload objects in the KOI-net API."""
|
|
2
2
|
|
|
3
|
-
from
|
|
3
|
+
from typing import Literal
|
|
4
|
+
from pydantic import BaseModel, Field
|
|
4
5
|
from rid_lib import RID, RIDType
|
|
5
6
|
from rid_lib.ext import Bundle, Manifest
|
|
6
7
|
from .event import Event
|
|
8
|
+
from .errors import ErrorType
|
|
7
9
|
|
|
8
10
|
|
|
9
11
|
# REQUEST MODELS
|
|
10
12
|
|
|
11
13
|
class PollEvents(BaseModel):
|
|
12
|
-
|
|
14
|
+
type: Literal["poll_events"] = Field("poll_events")
|
|
13
15
|
limit: int = 0
|
|
14
16
|
|
|
15
17
|
class FetchRids(BaseModel):
|
|
18
|
+
type: Literal["fetch_rids"] = Field("fetch_rids")
|
|
16
19
|
rid_types: list[RIDType] = []
|
|
17
20
|
|
|
18
21
|
class FetchManifests(BaseModel):
|
|
22
|
+
type: Literal["fetch_manifests"] = Field("fetch_manifests")
|
|
19
23
|
rid_types: list[RIDType] = []
|
|
20
24
|
rids: list[RID] = []
|
|
21
25
|
|
|
22
26
|
class FetchBundles(BaseModel):
|
|
27
|
+
type: Literal["fetch_bundles"] = Field("fetch_bundles")
|
|
23
28
|
rids: list[RID]
|
|
24
29
|
|
|
25
30
|
|
|
26
31
|
# RESPONSE/PAYLOAD MODELS
|
|
27
32
|
|
|
28
33
|
class RidsPayload(BaseModel):
|
|
34
|
+
type: Literal["rids_payload"] = Field("rids_payload")
|
|
29
35
|
rids: list[RID]
|
|
30
36
|
|
|
31
37
|
class ManifestsPayload(BaseModel):
|
|
38
|
+
type: Literal["manifests_payload"] = Field("manifests_payload")
|
|
32
39
|
manifests: list[Manifest]
|
|
33
40
|
not_found: list[RID] = []
|
|
34
41
|
|
|
35
42
|
class BundlesPayload(BaseModel):
|
|
43
|
+
type: Literal["bundles_payload"] = Field("bundles_payload")
|
|
36
44
|
bundles: list[Bundle]
|
|
37
45
|
not_found: list[RID] = []
|
|
38
46
|
deferred: list[RID] = []
|
|
39
47
|
|
|
40
48
|
class EventsPayload(BaseModel):
|
|
49
|
+
type: Literal["events_payload"] = Field("events_payload")
|
|
41
50
|
events: list[Event]
|
|
42
51
|
|
|
43
52
|
|
|
53
|
+
# ERROR MODELS
|
|
54
|
+
|
|
55
|
+
class ErrorResponse(BaseModel):
|
|
56
|
+
type: Literal["error_response"] = Field("error_response")
|
|
57
|
+
error: ErrorType
|
|
58
|
+
|
|
44
59
|
# TYPES
|
|
45
60
|
|
|
46
61
|
type RequestModels = EventsPayload | PollEvents | FetchRids | FetchManifests | FetchBundles
|
|
47
|
-
type ResponseModels = RidsPayload | ManifestsPayload | BundlesPayload | EventsPayload
|
|
62
|
+
type ResponseModels = RidsPayload | ManifestsPayload | BundlesPayload | EventsPayload | ErrorResponse
|
koi_net/protocol/edge.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
from enum import StrEnum
|
|
2
2
|
from pydantic import BaseModel
|
|
3
3
|
from rid_lib import RIDType
|
|
4
|
-
from rid_lib.
|
|
4
|
+
from rid_lib.ext.bundle import Bundle
|
|
5
|
+
from rid_lib.ext.utils import sha256_hash
|
|
6
|
+
from rid_lib.types import KoiNetEdge, KoiNetNode
|
|
5
7
|
|
|
6
8
|
|
|
7
9
|
class EdgeStatus(StrEnum):
|
|
@@ -18,3 +20,26 @@ class EdgeProfile(BaseModel):
|
|
|
18
20
|
edge_type: EdgeType
|
|
19
21
|
status: EdgeStatus
|
|
20
22
|
rid_types: list[RIDType]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def generate_edge_bundle(
|
|
26
|
+
source: KoiNetNode,
|
|
27
|
+
target: KoiNetNode,
|
|
28
|
+
rid_types: list[RIDType],
|
|
29
|
+
edge_type: EdgeType
|
|
30
|
+
) -> Bundle:
|
|
31
|
+
edge_rid = KoiNetEdge(sha256_hash(
|
|
32
|
+
str(source) + str(target)
|
|
33
|
+
))
|
|
34
|
+
edge_profile = EdgeProfile(
|
|
35
|
+
source=source,
|
|
36
|
+
target=target,
|
|
37
|
+
rid_types=rid_types,
|
|
38
|
+
edge_type=edge_type,
|
|
39
|
+
status=EdgeStatus.PROPOSED
|
|
40
|
+
)
|
|
41
|
+
edge_bundle = Bundle.generate(
|
|
42
|
+
edge_rid,
|
|
43
|
+
edge_profile.model_dump()
|
|
44
|
+
)
|
|
45
|
+
return edge_bundle
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Generic, TypeVar
|
|
3
|
+
from pydantic import BaseModel, ConfigDict
|
|
4
|
+
from rid_lib.types import KoiNetNode
|
|
5
|
+
|
|
6
|
+
from .secure import PrivateKey, PublicKey
|
|
7
|
+
from .api_models import RequestModels, ResponseModels
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
T = TypeVar("T", bound=RequestModels | ResponseModels)
|
|
14
|
+
|
|
15
|
+
class SignedEnvelope(BaseModel, Generic[T]):
|
|
16
|
+
model_config = ConfigDict(exclude_none=True)
|
|
17
|
+
|
|
18
|
+
payload: T
|
|
19
|
+
source_node: KoiNetNode
|
|
20
|
+
target_node: KoiNetNode
|
|
21
|
+
signature: str
|
|
22
|
+
|
|
23
|
+
def verify_with(self, pub_key: PublicKey):
|
|
24
|
+
# IMPORTANT: calling `model_dump()` loses all typing! when converting between SignedEnvelope and UnsignedEnvelope, use the Pydantic classes, not the dictionary form
|
|
25
|
+
unsigned_envelope = UnsignedEnvelope[T](
|
|
26
|
+
payload=self.payload,
|
|
27
|
+
source_node=self.source_node,
|
|
28
|
+
target_node=self.target_node
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
logger.debug(f"Verifying envelope: {unsigned_envelope.model_dump_json(exclude_none=True)}")
|
|
32
|
+
|
|
33
|
+
pub_key.verify(
|
|
34
|
+
self.signature,
|
|
35
|
+
unsigned_envelope.model_dump_json(exclude_none=True).encode()
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
class UnsignedEnvelope(BaseModel, Generic[T]):
|
|
39
|
+
model_config = ConfigDict(exclude_none=True)
|
|
40
|
+
|
|
41
|
+
payload: T
|
|
42
|
+
source_node: KoiNetNode
|
|
43
|
+
target_node: KoiNetNode
|
|
44
|
+
|
|
45
|
+
def sign_with(self, priv_key: PrivateKey) -> SignedEnvelope[T]:
|
|
46
|
+
logger.debug(f"Signing envelope: {self.model_dump_json(exclude_none=True)}")
|
|
47
|
+
logger.debug(f"Type: [{type(self.payload)}]")
|
|
48
|
+
|
|
49
|
+
signature = priv_key.sign(
|
|
50
|
+
self.model_dump_json(exclude_none=True).encode()
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
return SignedEnvelope(
|
|
54
|
+
payload=self.payload,
|
|
55
|
+
source_node=self.source_node,
|
|
56
|
+
target_node=self.target_node,
|
|
57
|
+
signature=signature
|
|
58
|
+
)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from enum import StrEnum
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ErrorType(StrEnum):
|
|
5
|
+
UnknownNode = "unknown_node"
|
|
6
|
+
InvalidKey = "invalid_key"
|
|
7
|
+
InvalidSignature = "invalid_signature"
|
|
8
|
+
InvalidTarget = "invalid_target"
|
|
9
|
+
|
|
10
|
+
class ProtocolError(Exception):
|
|
11
|
+
error_type: ErrorType
|
|
12
|
+
|
|
13
|
+
class UnknownNodeError(ProtocolError):
|
|
14
|
+
error_type = ErrorType.UnknownNode
|
|
15
|
+
|
|
16
|
+
class InvalidKeyError(ProtocolError):
|
|
17
|
+
error_type = ErrorType.InvalidKey
|
|
18
|
+
|
|
19
|
+
class InvalidSignatureError(ProtocolError):
|
|
20
|
+
error_type = ErrorType.InvalidSignature
|
|
21
|
+
|
|
22
|
+
class InvalidTargetError(ProtocolError):
|
|
23
|
+
error_type = ErrorType.InvalidTarget
|
koi_net/protocol/event.py
CHANGED
koi_net/protocol/node.py
CHANGED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from base64 import b64decode, b64encode
|
|
3
|
+
from cryptography.hazmat.primitives import hashes
|
|
4
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
5
|
+
from cryptography.hazmat.primitives import serialization
|
|
6
|
+
from rid_lib.ext.utils import sha256_hash
|
|
7
|
+
from cryptography.hazmat.primitives.asymmetric.utils import (
|
|
8
|
+
decode_dss_signature,
|
|
9
|
+
encode_dss_signature
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def der_to_raw_signature(der_signature: bytes, curve=ec.SECP256R1()) -> bytes:
|
|
16
|
+
"""Convert a DER-encoded signature to raw r||s format."""
|
|
17
|
+
|
|
18
|
+
# Decode the DER signature to get r and s
|
|
19
|
+
r, s = decode_dss_signature(der_signature)
|
|
20
|
+
|
|
21
|
+
# Determine byte length based on curve bit size
|
|
22
|
+
byte_length = (curve.key_size + 7) // 8
|
|
23
|
+
|
|
24
|
+
# Convert r and s to big-endian byte arrays of fixed length
|
|
25
|
+
r_bytes = r.to_bytes(byte_length, byteorder='big')
|
|
26
|
+
s_bytes = s.to_bytes(byte_length, byteorder='big')
|
|
27
|
+
|
|
28
|
+
# Concatenate r and s
|
|
29
|
+
return r_bytes + s_bytes
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def raw_to_der_signature(raw_signature: bytes, curve=ec.SECP256R1()) -> bytes:
|
|
33
|
+
"""Convert a raw r||s signature to DER format."""
|
|
34
|
+
|
|
35
|
+
# Determine byte length based on curve bit size
|
|
36
|
+
byte_length = (curve.key_size + 7) // 8
|
|
37
|
+
|
|
38
|
+
# Split the raw signature into r and s components
|
|
39
|
+
if len(raw_signature) != 2 * byte_length:
|
|
40
|
+
raise ValueError(f"Raw signature must be {2 * byte_length} bytes for {curve.name}")
|
|
41
|
+
|
|
42
|
+
r_bytes = raw_signature[:byte_length]
|
|
43
|
+
s_bytes = raw_signature[byte_length:]
|
|
44
|
+
|
|
45
|
+
# Convert bytes to integers
|
|
46
|
+
r = int.from_bytes(r_bytes, byteorder='big')
|
|
47
|
+
s = int.from_bytes(s_bytes, byteorder='big')
|
|
48
|
+
|
|
49
|
+
# Encode as DER
|
|
50
|
+
return encode_dss_signature(r, s)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PrivateKey:
|
|
54
|
+
priv_key: ec.EllipticCurvePrivateKey
|
|
55
|
+
|
|
56
|
+
def __init__(self, priv_key):
|
|
57
|
+
self.priv_key = priv_key
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def generate(cls):
|
|
61
|
+
return cls(priv_key=ec.generate_private_key(ec.SECP256R1()))
|
|
62
|
+
|
|
63
|
+
def public_key(self) -> "PublicKey":
|
|
64
|
+
return PublicKey(self.priv_key.public_key())
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def from_pem(cls, priv_key_pem: str, password: str):
|
|
68
|
+
return cls(
|
|
69
|
+
priv_key=serialization.load_pem_private_key(
|
|
70
|
+
data=priv_key_pem.encode(),
|
|
71
|
+
password=password.encode()
|
|
72
|
+
)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def to_pem(self, password: str) -> str:
|
|
76
|
+
return self.priv_key.private_bytes(
|
|
77
|
+
encoding=serialization.Encoding.PEM,
|
|
78
|
+
format=serialization.PrivateFormat.PKCS8,
|
|
79
|
+
encryption_algorithm=serialization.BestAvailableEncryption(password.encode())
|
|
80
|
+
).decode()
|
|
81
|
+
|
|
82
|
+
def sign(self, message: bytes) -> str:
|
|
83
|
+
hashed_message = sha256_hash(message.decode())
|
|
84
|
+
|
|
85
|
+
der_signature_bytes = self.priv_key.sign(
|
|
86
|
+
data=message,
|
|
87
|
+
signature_algorithm=ec.ECDSA(hashes.SHA256())
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
raw_signature_bytes = der_to_raw_signature(der_signature_bytes)
|
|
91
|
+
|
|
92
|
+
signature = b64encode(raw_signature_bytes).decode()
|
|
93
|
+
|
|
94
|
+
logger.debug(f"Signing message with [{self.public_key().to_der()}]")
|
|
95
|
+
logger.debug(f"hash: {hashed_message}")
|
|
96
|
+
logger.debug(f"signature: {signature}")
|
|
97
|
+
|
|
98
|
+
return signature
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class PublicKey:
|
|
102
|
+
pub_key: ec.EllipticCurvePublicKey
|
|
103
|
+
|
|
104
|
+
def __init__(self, pub_key):
|
|
105
|
+
self.pub_key = pub_key
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def from_pem(cls, pub_key_pem: str):
|
|
109
|
+
return cls(
|
|
110
|
+
pub_key=serialization.load_pem_public_key(
|
|
111
|
+
data=pub_key_pem.encode()
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
def to_pem(self) -> str:
|
|
116
|
+
return self.pub_key.public_bytes(
|
|
117
|
+
encoding=serialization.Encoding.PEM,
|
|
118
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
119
|
+
).decode()
|
|
120
|
+
|
|
121
|
+
@classmethod
|
|
122
|
+
def from_der(cls, pub_key_der: str):
|
|
123
|
+
return cls(
|
|
124
|
+
pub_key=serialization.load_der_public_key(
|
|
125
|
+
data=b64decode(pub_key_der)
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def to_der(self) -> str:
|
|
130
|
+
return b64encode(
|
|
131
|
+
self.pub_key.public_bytes(
|
|
132
|
+
encoding=serialization.Encoding.DER,
|
|
133
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
134
|
+
)
|
|
135
|
+
).decode()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def verify(self, signature: str, message: bytes) -> bool:
|
|
139
|
+
# hashed_message = sha256_hash(message.decode())
|
|
140
|
+
|
|
141
|
+
# print(message.hex())
|
|
142
|
+
# print()
|
|
143
|
+
# print(hashed_message)
|
|
144
|
+
# print()
|
|
145
|
+
# print(message.decode())
|
|
146
|
+
|
|
147
|
+
# logger.debug(f"Verifying message with [{self.to_der()}]")
|
|
148
|
+
# logger.debug(f"hash: {hashed_message}")
|
|
149
|
+
# logger.debug(f"signature: {signature}")
|
|
150
|
+
|
|
151
|
+
raw_signature_bytes = b64decode(signature)
|
|
152
|
+
der_signature_bytes = raw_to_der_signature(raw_signature_bytes)
|
|
153
|
+
|
|
154
|
+
# NOTE: throws cryptography.exceptions.InvalidSignature on failure
|
|
155
|
+
|
|
156
|
+
self.pub_key.verify(
|
|
157
|
+
signature=der_signature_bytes,
|
|
158
|
+
data=message,
|
|
159
|
+
signature_algorithm=ec.ECDSA(hashes.SHA256())
|
|
160
|
+
)
|