| 1 |
from typing import Any, FrozenSet, Optional |
| 2 |
|
| 3 |
from pydantic import BaseModel |
| 4 |
from pydantic.functional_serializers import PlainSerializer |
| 5 |
from pydantic.functional_validators import PlainValidator |
| 6 |
from typing_extensions import Annotated |
| 7 |
|
| 8 |
from .types import SecretType |
| 9 |
|
| 10 |
|
| 11 |
__all__ = [ |
| 12 |
"BaseStateModel", |
| 13 |
"IdentityKeyPairModel", |
| 14 |
"SignedPreKeyPairModel" |
| 15 |
] |
| 16 |
|
| 17 |
|
| 18 |
def _json_bytes_decoder(val: Any) -> bytes: |
| 19 |
""" |
| 20 |
Decode bytes from a string according to the JSON specification. See |
| 21 |
https://github.com/samuelcolvin/pydantic/issues/3756 for details. |
| 22 |
|
| 23 |
Args: |
| 24 |
val: The value to type check and decode. |
| 25 |
|
| 26 |
Returns: |
| 27 |
The value decoded to bytes. If the value is bytes already, it is returned unmodified. |
| 28 |
|
| 29 |
Raises: |
| 30 |
ValueError: if the value is not correctly encoded. |
| 31 |
""" |
| 32 |
|
| 33 |
if isinstance(val, bytes): |
| 34 |
return val |
| 35 |
if isinstance(val, str): |
| 36 |
return bytes(map(ord, val)) |
| 37 |
raise ValueError("bytes fields must be encoded as bytes or str.") |
| 38 |
|
| 39 |
|
| 40 |
def _json_bytes_encoder(val: bytes) -> str: |
| 41 |
""" |
| 42 |
Encode bytes as a string according to the JSON specification. See |
| 43 |
https://github.com/samuelcolvin/pydantic/issues/3756 for details. |
| 44 |
|
| 45 |
Args: |
| 46 |
val: The bytes to encode. |
| 47 |
|
| 48 |
Returns: |
| 49 |
The encoded bytes. |
| 50 |
""" |
| 51 |
|
| 52 |
return "".join(map(chr, val)) |
| 53 |
|
| 54 |
|
| 55 |
JsonBytes = Annotated[bytes, PlainValidator(_json_bytes_decoder), PlainSerializer(_json_bytes_encoder)] |
| 56 |
|
| 57 |
|
| 58 |
class IdentityKeyPairModel(BaseModel): |
| 59 |
""" |
| 60 |
The model representing the internal state of an :class:`~x3dh.identity_key_pair.IdentityKeyPair`. |
| 61 |
""" |
| 62 |
|
| 63 |
version: str = "1.0.0" |
| 64 |
secret: JsonBytes |
| 65 |
secret_type: SecretType |
| 66 |
|
| 67 |
|
| 68 |
class SignedPreKeyPairModel(BaseModel): |
| 69 |
""" |
| 70 |
The model representing the internal state of a :class:`~x3dh.signed_pre_key_pair.SignedPreKeyPair`. |
| 71 |
""" |
| 72 |
|
| 73 |
version: str = "1.0.0" |
| 74 |
priv: JsonBytes |
| 75 |
sig: JsonBytes |
| 76 |
timestamp: int |
| 77 |
|
| 78 |
|
| 79 |
class BaseStateModel(BaseModel): |
| 80 |
""" |
| 81 |
The model representing the internal state of a :class:`~x3dh.base_state.BaseState`. |
| 82 |
""" |
| 83 |
|
| 84 |
version: str = "1.0.0" |
| 85 |
identity_key: IdentityKeyPairModel |
| 86 |
signed_pre_key: SignedPreKeyPairModel |
| 87 |
old_signed_pre_key: Optional[SignedPreKeyPairModel] |
| 88 |
pre_keys: FrozenSet[JsonBytes] |