-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path__init__.py
440 lines (353 loc) · 12.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import datetime
import json
from copy import copy
from hashlib import sha256
from json import JSONDecodeError
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Type, TypeVar, Union, cast
from pydantic import BaseModel, Extra, Field, validator
from typing_extensions import TypeAlias
from .abstract import BaseContent, HashableModel
from .base import Chain, HashType, MessageType
from .execution.base import MachineType, Payment, PaymentType
from .execution.instance import InstanceContent
from .execution.program import ProgramContent
from .item_hash import ItemHash, ItemType
__all__ = [
"AggregateContent",
"AggregateMessage",
"AlephMessage",
"AlephMessageType",
"Chain",
"ChainRef",
"ExecutableContent",
"ExecutableMessage",
"ForgetContent",
"ForgetMessage",
"HashType",
"InstanceContent",
"InstanceMessage",
"ItemHash",
"ItemType",
"HashableModel",
"MachineType",
"MessageConfirmation",
"MessageConfirmationHash",
"MessageType",
"Payment",
"PaymentType",
"PostContent",
"PostMessage",
"BaseContent",
"ProgramContent",
"ProgramMessage",
"StoreContent",
"StoreMessage",
]
class MongodbId(BaseModel):
"""PyAleph returns an internal MongoDB id"""
oid: str = Field(alias="$oid")
class Config:
extra = Extra.forbid
class ChainRef(BaseModel):
"""Some POST messages have a 'ref' field referencing other content"""
chain: Chain
channel: Optional[str] = None
item_content: str
item_hash: ItemHash
item_type: ItemType
sender: str
signature: str
time: float
type: Literal["POST"] = "POST"
class MessageConfirmationHash(BaseModel):
binary: str = Field(alias="$binary")
type: str = Field(alias="$type")
class Config:
extra = Extra.forbid
class MessageConfirmation(BaseModel):
"""Format of the result when a message has been confirmed on a blockchain"""
chain: Chain
height: int
hash: Union[str, MessageConfirmationHash]
# These two optional fields are introduced in recent versions of CCNs. They should
# remain optional until the corresponding CCN upload (0.4.0) is widely uploaded.
time: Optional[float] = None
publisher: Optional[str] = Field(
default=None, description="The address that published the transaction."
)
class Config:
extra = Extra.forbid
class AggregateContentKey(BaseModel):
name: str
class Config:
extra = Extra.forbid
class PostContent(BaseContent):
"""Content of a POST message"""
content: Optional[Any] = Field(
default=None, description="User-generated content of a POST message"
)
ref: Optional[Union[str, ChainRef]] = Field(
default=None,
description="Other message referenced by this one",
)
type: str = Field(description="User-generated 'content-type' of a POST message")
@validator("type")
def check_type(cls, v, values):
if v == "amend":
ref = values.get("ref")
if not ref:
raise ValueError("A 'ref' is required for POST type 'amend'")
return v
class Config:
extra = Extra.forbid
class AggregateContent(BaseContent):
"""Content of an AGGREGATE message"""
key: Union[str, AggregateContentKey] = Field(
description="The aggregate key can be either a string of a dict containing the key in field 'name'"
)
content: Dict = Field(description="The content of an aggregate must be a dict")
class Config:
extra = Extra.forbid
class StoreContent(BaseContent):
"""Content of a STORE message"""
item_type: ItemType
item_hash: ItemHash
size: Optional[int] = None # Generated by the node on storage
content_type: Optional[str] = None # Generated by the node on storage
ref: Optional[str] = None
metadata: Optional[Dict[str, Any]] = Field(description="Metadata of the VM")
class Config:
extra = Extra.allow
class ForgetContent(BaseContent):
"""Content of a FORGET message"""
hashes: List[ItemHash]
aggregates: List[ItemHash] = Field(default_factory=list)
reason: Optional[str] = None
def __hash__(self):
# Convert List to Tuple for hashing
values = copy(self.__dict__)
values["hashes"] = tuple(values["hashes"])
return hash(self.__class__) + hash(values.values())
class BaseMessage(BaseModel):
"""Base template for all messages"""
id_: Optional[MongodbId] = Field(
alias="_id",
default=None,
description="MongoDB metadata",
exclude=True,
)
chain: Chain = Field(description="Blockchain used for this message")
sender: str = Field(description="Address of the sender")
type: MessageType = Field(description="Type of message (POST, AGGREGATE or STORE)")
channel: Optional[str] = Field(
default=None,
description="Channel of the message, one application ideally has one channel",
)
confirmations: Optional[List[MessageConfirmation]] = Field(
default=None, description="Blockchain confirmations of the message"
)
confirmed: Optional[bool] = Field(
default=None,
description="Indicates that the message has been confirmed on a blockchain",
)
signature: Optional[str] = Field(
description="Cryptographic signature of the message by the sender"
)
size: Optional[int] = Field(
default=None, description="Size of the content"
) # Almost always present
time: datetime.datetime = Field(
description="Unix timestamp or datetime when the message was published"
)
item_type: ItemType = Field(description="Storage method used for the content")
item_content: Optional[str] = Field(
default=None,
description="JSON serialization of the message when 'item_type' is 'inline'",
)
hash_type: Optional[HashType] = Field(
default=None, description="Hashing algorithm used to compute 'item_hash'"
)
item_hash: ItemHash = Field(description="Hash of the content (sha256 by default)")
content: BaseContent = Field(description="Content of the message, ready to be used")
forgotten_by: Optional[List[str]]
@validator("item_content")
def check_item_content(cls, v: Optional[str], values) -> Optional[str]:
item_type = values["item_type"]
if v is None:
return None
elif item_type == ItemType.inline:
try:
json.loads(v)
except JSONDecodeError:
raise ValueError(
"Field 'item_content' does not appear to be valid JSON"
)
else:
raise ValueError(
f"Field 'item_content' cannot be defined when 'item_type' == '{item_type}'"
)
return v
@validator("item_hash")
def check_item_hash(cls, v: ItemHash, values) -> ItemHash:
item_type = values["item_type"]
if item_type == ItemType.inline:
item_content: str = values["item_content"]
# Double check that the hash function is supported
hash_type = values["hash_type"] or HashType.sha256
assert hash_type.value == HashType.sha256
computed_hash: str = sha256(item_content.encode()).hexdigest()
if v != computed_hash:
raise ValueError(
f"'item_hash' do not match 'sha256(item_content)'"
f", expecting {computed_hash}"
)
elif item_type == ItemType.ipfs:
# TODO: CHeck that the hash looks like an IPFS multihash
pass
else:
assert item_type == ItemType.storage
return v
@validator("confirmed")
def check_confirmed(cls, v, values):
confirmations = values["confirmations"]
if v is True and not bool(confirmations):
raise ValueError("Message cannot be 'confirmed' without 'confirmations'")
return v
@validator("time")
def convert_float_to_datetime(cls, v, values):
if isinstance(v, float):
v = datetime.datetime.fromtimestamp(v)
assert isinstance(v, datetime.datetime)
return v
class Config:
extra = Extra.forbid
exclude = {"id_", "_id"}
class PostMessage(BaseMessage):
"""Unique data posts (unique data points, events, ...)"""
type: Literal[MessageType.post]
content: PostContent
class AggregateMessage(BaseMessage):
"""A key-value storage specific to an address"""
type: Literal[MessageType.aggregate]
content: AggregateContent
class StoreMessage(BaseMessage):
type: Literal[MessageType.store]
content: StoreContent
class ForgetMessage(BaseMessage):
type: Literal[MessageType.forget]
content: ForgetContent
@validator("forgotten_by")
def cannot_be_forgotten(cls, v: Optional[List[str]], values) -> Optional[List[str]]:
assert values
if v:
raise ValueError("This type of message may not be forgotten")
return v
class ProgramMessage(BaseMessage):
type: Literal[MessageType.program]
content: ProgramContent
@validator("content")
def check_content(cls, v, values):
item_type = values["item_type"]
if item_type == ItemType.inline:
item_content = json.loads(values["item_content"])
if v.dict(exclude_none=True) != item_content:
# Print differences
vdict = v.dict(exclude_none=True)
for key, value in item_content.items():
if vdict[key] != value:
print(f"{key}: {vdict[key]} != {value}")
raise ValueError("Content and item_content differ")
return v
class InstanceMessage(BaseMessage):
type: Literal[MessageType.instance]
content: InstanceContent
AlephMessage: TypeAlias = Union[
PostMessage,
AggregateMessage,
StoreMessage,
ProgramMessage,
InstanceMessage,
ForgetMessage,
]
T = TypeVar("T", bound=AlephMessage)
AlephMessageType: TypeAlias = Type[T]
message_classes: List[AlephMessageType] = [
PostMessage,
AggregateMessage,
StoreMessage,
ProgramMessage,
InstanceMessage,
ForgetMessage,
]
ExecutableContent: TypeAlias = Union[InstanceContent, ProgramContent]
ExecutableMessage: TypeAlias = Union[InstanceMessage, ProgramMessage]
def parse_message(message_dict: Dict) -> AlephMessage:
"""Returns the message class corresponding to the type of message."""
for message_class in message_classes:
message_type: MessageType = MessageType(
message_class.__annotations__["type"].__args__[0]
)
if message_dict["type"] == message_type:
return message_class.parse_obj(message_dict)
else:
raise ValueError(f"Unknown message type {message_dict['type']}")
def add_item_content_and_hash(message_dict: Dict, inplace: bool = False):
if not inplace:
message_dict = copy(message_dict)
message_dict["item_content"] = json.dumps(
message_dict["content"], separators=(",", ":")
)
message_dict["item_hash"] = sha256(
message_dict["item_content"].encode()
).hexdigest()
return message_dict
def create_new_message(
message_dict: Dict,
factory: Optional[Type[T]] = None,
) -> T:
"""Create a new message from a dict.
Computes the 'item_content' and 'item_hash' fields.
"""
message_content = add_item_content_and_hash(message_dict)
if factory:
return cast(T, factory.parse_obj(message_content))
else:
return cast(T, parse_message(message_content))
def create_message_from_json(
json_data: str,
factory: Optional[AlephMessageType] = None,
) -> AlephMessage:
"""Create a new message from a JSON encoded string.
Computes the 'item_content' and 'item_hash' fields.
"""
message_dict = json.loads(json_data)
message_content = add_item_content_and_hash(message_dict, inplace=True)
if factory:
return factory.parse_obj(message_content)
else:
return parse_message(message_content)
def create_message_from_file(
filepath: Path, factory: Optional[AlephMessageType] = None, decoder=json
) -> AlephMessage:
"""Create a new message from an encoded file.
Expects json by default, but allows other decoders with a method `.load()`
that takes a file descriptor.
Computes the 'item_content' and 'item_hash' fields.
"""
with open(filepath) as fd:
message_dict = decoder.load(fd)
message_content = add_item_content_and_hash(message_dict, inplace=True)
if factory:
return factory.parse_obj(message_content)
else:
return parse_message(message_content)
class MessagesResponse(BaseModel):
"""Response from an Aleph node API."""
messages: List[AlephMessage]
pagination_page: int
pagination_total: int
pagination_per_page: int
pagination_item: str
class Config:
extra = Extra.forbid