pyssb/ssb/feed/models.py

191 lines
5.1 KiB
Python
Raw Normal View History

"""Feed models"""
2017-05-25 10:47:01 +00:00
from base64 import b64encode
from collections import OrderedDict, namedtuple
import datetime
2017-05-25 10:47:01 +00:00
from hashlib import sha256
from typing import Any, Dict, Optional
2017-05-25 10:47:01 +00:00
from nacl.signing import SigningKey, VerifyKey
2017-05-25 10:47:01 +00:00
from simplejson import dumps, loads
from typing_extensions import Self
2017-05-25 10:47:01 +00:00
2017-08-05 16:21:14 +00:00
from ssb.util import tag
OrderedMsg = namedtuple("OrderedMsg", ("previous", "author", "sequence", "timestamp", "hash", "content"))
2017-05-25 10:47:01 +00:00
2017-08-05 16:21:14 +00:00
class NoPrivateKeyException(Exception):
"""Exception to raise when a private key is not available"""
2017-08-05 16:21:14 +00:00
def to_ordered(data: Dict[str, Any]) -> OrderedDict[str, Any]:
"""Convert a dictionary to an ``OrderedDict``"""
2017-05-25 10:47:01 +00:00
smsg = OrderedMsg(**data)
2017-05-25 10:47:01 +00:00
return OrderedDict((k, getattr(smsg, k)) for k in smsg._fields)
def get_millis_1970() -> int:
"""Get the UNIX timestamp in milliseconds"""
return int(datetime.datetime.utcnow().timestamp() * 1000)
class Feed:
"""Base class for feeds"""
def __init__(self, public_key: VerifyKey):
2017-08-05 16:21:14 +00:00
self.public_key = public_key
@property
def id(self) -> str:
"""The identifier of the feed"""
return tag(self.public_key).decode("ascii")
2017-08-05 16:21:14 +00:00
def sign(self, msg: "Message") -> bytes:
"""Sign a message"""
raise NoPrivateKeyException("Cannot use remote identity to sign (no private key!)")
2017-08-05 16:21:14 +00:00
class LocalFeed(Feed):
"""Class representing a local feed"""
def __init__(self, private_key: SigningKey): # pylint: disable=super-init-not-called
self.private_key: SigningKey = private_key
2017-08-05 16:21:14 +00:00
@property
def public_key(self) -> VerifyKey:
"""The public key of the feed"""
2017-08-05 16:21:14 +00:00
return self.private_key.verify_key
@public_key.setter
def public_key(self, _: VerifyKey) -> None:
raise TypeError("Cannot set just the public key of a local feed")
def sign(self, msg: "Message") -> bytes:
"""Sign a message for this feed"""
2017-08-05 16:21:14 +00:00
return self.private_key.sign(msg).signature
class Message:
"""Base class for SSB messages"""
def __init__( # pylint: disable=too-many-arguments
self,
feed: Feed,
content: Dict[str, Any],
signature: Optional[str] = None,
sequence: int = 1,
timestamp: Optional[int] = None,
previous: Optional["Message"] = None,
):
2017-08-05 16:21:14 +00:00
self.feed = feed
2017-05-25 10:47:01 +00:00
self.content = content
2017-08-05 17:32:01 +00:00
if signature is None:
raise ValueError("signature can't be None")
2017-08-05 16:21:14 +00:00
self.signature = signature
2017-05-25 10:47:01 +00:00
self.previous = previous
2017-08-05 16:21:14 +00:00
if self.previous:
self.sequence: int = self.previous.sequence + 1
2017-08-05 16:21:14 +00:00
else:
self.sequence = sequence
self.timestamp = get_millis_1970() if timestamp is None else timestamp
2017-05-25 10:47:01 +00:00
@classmethod
def parse(cls, data: bytes, feed: Feed) -> Self:
"""Parse raw message data"""
2017-05-25 10:47:01 +00:00
obj = loads(data, object_pairs_hook=OrderedDict)
msg = cls(feed, obj["content"], timestamp=obj["timestamp"])
2017-08-06 10:16:22 +00:00
return msg
2017-05-25 10:47:01 +00:00
def serialize(self, add_signature: bool = True) -> bytes:
"""Serialize the message"""
return dumps(self.to_dict(add_signature=add_signature), indent=2).encode("utf-8")
2017-08-05 18:01:17 +00:00
def to_dict(self, add_signature: bool = True) -> OrderedDict[str, Any]:
"""Convert the message to a dictionary"""
obj = to_ordered(
{
"previous": self.previous.key if self.previous else None,
"author": self.feed.id,
"sequence": self.sequence,
"timestamp": self.timestamp,
"hash": "sha256",
"content": self.content,
}
)
2017-05-25 10:47:01 +00:00
if add_signature:
obj["signature"] = self.signature
2017-05-25 10:47:01 +00:00
return obj
def verify(self, signature: str) -> bool:
"""Verify the signature of the message"""
2017-05-25 10:47:01 +00:00
return self.signature == signature
@property
def hash(self) -> str:
"""The cryptographic hash of the message"""
hash_ = sha256(self.serialize()).digest()
return b64encode(hash_).decode("ascii") + ".sha256"
2017-05-25 10:47:01 +00:00
@property
def key(self) -> str:
"""The key of the message"""
return "%" + self.hash
2017-08-05 16:21:14 +00:00
class LocalMessage(Message):
"""Class representing a local message"""
def __init__( # pylint: disable=too-many-arguments,super-init-not-called
self,
feed: Feed,
content: Dict[str, Any],
signature: Optional[str] = None,
sequence: int = 1,
timestamp: Optional[int] = None,
previous: Optional[Message] = None,
):
2017-08-05 17:32:01 +00:00
self.feed = feed
self.content = content
self.previous = previous
if self.previous:
self.sequence = self.previous.sequence + 1
else:
self.sequence = sequence
self.timestamp = get_millis_1970() if timestamp is None else timestamp
2017-08-05 17:32:01 +00:00
2017-08-05 16:21:14 +00:00
if signature is None:
2017-08-05 17:32:01 +00:00
self.signature = self._sign()
else:
self.signature = signature
2017-08-05 16:21:14 +00:00
def _sign(self) -> str:
2017-08-05 16:21:14 +00:00
# ensure ordering of keys and indentation of 2 characters, like ssb-keys
2017-08-05 18:01:17 +00:00
data = self.serialize(add_signature=False)
return (b64encode(bytes(self.feed.sign(data))) + b".sig.ed25519").decode("ascii")