| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
from typing import NamedTuple, cast |
| 5 |
|
| 6 |
import xeddsa |
| 7 |
|
| 8 |
from .migrations import parse_signed_pre_key_pair_model |
| 9 |
from .models import SignedPreKeyPairModel |
| 10 |
from .types import JSONObject |
| 11 |
|
| 12 |
|
| 13 |
__all__ = [ |
| 14 |
"SignedPreKeyPair" |
| 15 |
] |
| 16 |
|
| 17 |
|
| 18 |
class SignedPreKeyPair(NamedTuple): |
| 19 |
""" |
| 20 |
A signed pre key, i.e. a pre key whose public key was encoded using an application-specific encoding |
| 21 |
format, then signed by the identity key, and stored together with a generation timestamp for periodic |
| 22 |
rotation. |
| 23 |
""" |
| 24 |
|
| 25 |
priv: bytes |
| 26 |
sig: bytes |
| 27 |
timestamp: int |
| 28 |
|
| 29 |
@property |
| 30 |
def pub(self) -> bytes: |
| 31 |
""" |
| 32 |
Returns: |
| 33 |
The public key of this signed pre key. |
| 34 |
""" |
| 35 |
|
| 36 |
return xeddsa.priv_to_curve25519_pub(self.priv) |
| 37 |
|
| 38 |
@property |
| 39 |
def model(self) -> SignedPreKeyPairModel: |
| 40 |
""" |
| 41 |
Returns: |
| 42 |
The internal state of this :class:`SignedPreKeyPair` as a pydantic model. |
| 43 |
""" |
| 44 |
|
| 45 |
return SignedPreKeyPairModel(priv=self.priv, sig=self.sig, timestamp=self.timestamp) |
| 46 |
|
| 47 |
@property |
| 48 |
def json(self) -> JSONObject: |
| 49 |
""" |
| 50 |
Returns: |
| 51 |
The internal state of this :class:`SignedPreKeyPair` as a JSON-serializable Python object. |
| 52 |
""" |
| 53 |
|
| 54 |
return cast(JSONObject, json.loads(self.model.json())) |
| 55 |
|
| 56 |
@staticmethod |
| 57 |
def from_model(model: SignedPreKeyPairModel) -> "SignedPreKeyPair": |
| 58 |
""" |
| 59 |
Args: |
| 60 |
model: The pydantic model holding the internal state of a :class:`SignedPreKeyPair`, as produced |
| 61 |
by :attr:`model`. |
| 62 |
|
| 63 |
Returns: |
| 64 |
A configured instance of :class:`SignedPreKeyPair`, with internal state restored from the model. |
| 65 |
|
| 66 |
Warning: |
| 67 |
Migrations are not provided via the :attr:`model`/:meth:`from_model` API. Use |
| 68 |
:attr:`json`/:meth:`from_json` instead. Refer to :ref:`serialization_and_migration` in the |
| 69 |
documentation for details. |
| 70 |
""" |
| 71 |
|
| 72 |
return SignedPreKeyPair(priv=model.priv, sig=model.sig, timestamp=model.timestamp) |
| 73 |
|
| 74 |
@staticmethod |
| 75 |
def from_json(serialized: JSONObject) -> "SignedPreKeyPair": |
| 76 |
""" |
| 77 |
Args: |
| 78 |
serialized: A JSON-serializable Python object holding the internal state of a |
| 79 |
:class:`SignedPreKeyPair`, as produced by :attr:`json`. |
| 80 |
|
| 81 |
Returns: |
| 82 |
A configured instance of :class:`SignedPreKeyPair`, with internal state restored from the |
| 83 |
serialized data. |
| 84 |
""" |
| 85 |
|
| 86 |
return SignedPreKeyPair.from_model(parse_signed_pre_key_pair_model(serialized)) |