2023-11-13 12:34:43 +00:00
|
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
#
|
|
|
|
# Copyright (c) 2017 PySSB contributors (see AUTHORS for more details)
|
|
|
|
#
|
|
|
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
|
|
# of this software and associated documentation files (the "Software"), to deal
|
|
|
|
# in the Software without restriction, including without limitation the rights
|
|
|
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
|
|
# copies of the Software, and to permit persons to whom the Software is
|
|
|
|
# furnished to do so, subject to the following conditions:
|
|
|
|
#
|
|
|
|
# The above copyright notice and this permission notice shall be included in all
|
|
|
|
# copies or substantial portions of the Software.
|
|
|
|
#
|
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
|
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
|
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
|
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
|
|
# SOFTWARE.
|
|
|
|
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Feed models"""
|
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
from base64 import b64encode
|
2023-11-14 04:00:03 +00:00
|
|
|
from collections import OrderedDict, namedtuple
|
2023-11-14 17:47:17 +00:00
|
|
|
from datetime import datetime
|
2017-05-25 10:47:01 +00:00
|
|
|
from hashlib import sha256
|
2023-11-01 06:22:29 +00:00
|
|
|
from typing import Any, Dict, Optional
|
2017-05-25 10:47:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
from nacl.signing import SigningKey, VerifyKey
|
2017-05-25 10:47:01 +00:00
|
|
|
from simplejson import dumps, loads
|
2023-11-01 06:22:29 +00:00
|
|
|
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
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
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):
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Exception to raise when a private key is not available"""
|
2017-08-05 16:21:14 +00:00
|
|
|
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def to_ordered(data: Dict[str, Any]) -> OrderedDict[str, Any]:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Convert a dictionary to an ``OrderedDict``"""
|
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
smsg = OrderedMsg(**data)
|
2023-11-01 05:03:06 +00:00
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
return OrderedDict((k, getattr(smsg, k)) for k in smsg._fields)
|
|
|
|
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def get_millis_1970() -> int:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Get the UNIX timestamp in milliseconds"""
|
|
|
|
|
2023-11-14 17:47:17 +00:00
|
|
|
return int(datetime.utcnow().timestamp() * 1000)
|
2018-02-04 21:17:38 +00:00
|
|
|
|
|
|
|
|
2023-11-01 05:03:06 +00:00
|
|
|
class Feed:
|
|
|
|
"""Base class for feeds"""
|
|
|
|
|
2023-11-18 06:03:02 +00:00
|
|
|
def __init__(self, public_key: VerifyKey):
|
2017-08-05 16:21:14 +00:00
|
|
|
self.public_key = public_key
|
|
|
|
|
|
|
|
@property
|
2023-11-01 06:22:29 +00:00
|
|
|
def id(self) -> str:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""The identifier of the feed"""
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
return tag(self.public_key).decode("ascii")
|
2017-08-05 16:21:14 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def sign(self, msg: bytes) -> bytes:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Sign a message"""
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
raise NoPrivateKeyException("Cannot use remote identity to sign (no private key!)")
|
2017-08-05 16:21:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LocalFeed(Feed):
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Class representing a local feed"""
|
|
|
|
|
2023-11-18 06:03:02 +00:00
|
|
|
def __init__(self, private_key: SigningKey): # pylint: disable=super-init-not-called
|
2017-08-05 16:21:14 +00:00
|
|
|
self.private_key = private_key
|
|
|
|
|
|
|
|
@property
|
2023-11-01 06:22:29 +00:00
|
|
|
def public_key(self) -> VerifyKey:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""The public key of the feed"""
|
|
|
|
|
2017-08-05 16:21:14 +00:00
|
|
|
return self.private_key.verify_key
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
@public_key.setter
|
|
|
|
def public_key(self, key: VerifyKey) -> None:
|
|
|
|
raise TypeError("Can not set only the public key for a local feed")
|
|
|
|
|
|
|
|
def sign(self, msg: bytes) -> bytes:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Sign a message for this feed"""
|
|
|
|
|
2017-08-05 16:21:14 +00:00
|
|
|
return self.private_key.sign(msg).signature
|
|
|
|
|
|
|
|
|
2023-11-01 05:03:06 +00:00
|
|
|
class Message:
|
|
|
|
"""Base class for SSB messages"""
|
|
|
|
|
|
|
|
def __init__( # pylint: disable=too-many-arguments
|
2023-11-01 06:22:29 +00:00
|
|
|
self,
|
|
|
|
feed: Feed,
|
|
|
|
content: Dict[str, Any],
|
|
|
|
signature: Optional[str] = None,
|
|
|
|
sequence: int = 1,
|
|
|
|
timestamp: Optional[int] = None,
|
|
|
|
previous: Optional["Message"] = None,
|
2023-11-01 05:03:06 +00:00
|
|
|
):
|
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 16:21:14 +00:00
|
|
|
self.signature = signature
|
2017-05-25 10:47:01 +00:00
|
|
|
self.previous = previous
|
2023-11-01 06:22:29 +00:00
|
|
|
self.timestamp = get_millis_1970() if timestamp is None else timestamp
|
|
|
|
|
2017-08-05 16:21:14 +00:00
|
|
|
if self.previous:
|
2023-11-01 06:22:29 +00:00
|
|
|
self.sequence: int = self.previous.sequence + 1
|
2017-08-05 16:21:14 +00:00
|
|
|
else:
|
|
|
|
self.sequence = sequence
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
self._check_signature()
|
|
|
|
|
|
|
|
def _check_signature(self) -> None:
|
|
|
|
if self.signature is None:
|
|
|
|
raise ValueError("signature can't be None")
|
2017-05-25 10:47:01 +00:00
|
|
|
|
|
|
|
@classmethod
|
2023-11-01 06:22:29 +00:00
|
|
|
def parse(cls, data: bytes, feed: Feed) -> Self:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Parse raw message data"""
|
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
obj = loads(data, object_pairs_hook=OrderedDict)
|
2023-11-01 04:04:43 +00:00
|
|
|
msg = cls(feed, obj["content"], timestamp=obj["timestamp"])
|
2023-11-01 05:03:06 +00:00
|
|
|
|
2017-08-06 10:16:22 +00:00
|
|
|
return msg
|
2017-05-25 10:47:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def serialize(self, add_signature: bool = True) -> bytes:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Serialize the message"""
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
return dumps(self.to_dict(add_signature=add_signature), indent=2).encode("utf-8")
|
2017-08-05 18:01:17 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def to_dict(self, add_signature: bool = True) -> OrderedDict[str, Any]:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Convert the message to a dictionary"""
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
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:
|
2023-11-01 04:04:43 +00:00
|
|
|
obj["signature"] = self.signature
|
2023-11-01 05:03:06 +00:00
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
return obj
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def verify(self, signature: str) -> bool:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Verify the signature of the message"""
|
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
return self.signature == signature
|
|
|
|
|
|
|
|
@property
|
2023-11-01 06:22:29 +00:00
|
|
|
def hash(self) -> str:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""The cryptographic hash of the message"""
|
|
|
|
|
|
|
|
hash_ = sha256(self.serialize()).digest()
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2023-11-01 05:03:06 +00:00
|
|
|
return b64encode(hash_).decode("ascii") + ".sha256"
|
2017-05-25 10:47:01 +00:00
|
|
|
|
|
|
|
@property
|
2023-11-01 06:22:29 +00:00
|
|
|
def key(self) -> str:
|
2023-11-01 05:03:06 +00:00
|
|
|
"""The key of the message"""
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
return "%" + self.hash
|
2017-08-05 16:21:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LocalMessage(Message):
|
2023-11-01 05:03:06 +00:00
|
|
|
"""Class representing a local message"""
|
|
|
|
|
|
|
|
def __init__( # pylint: disable=too-many-arguments,super-init-not-called
|
2023-11-01 06:22:29 +00:00
|
|
|
self,
|
|
|
|
feed: LocalFeed,
|
|
|
|
content: Dict[str, Any],
|
|
|
|
signature: Optional[str] = None,
|
|
|
|
sequence: int = 1,
|
|
|
|
timestamp: Optional[int] = None,
|
|
|
|
previous: Optional["LocalMessage"] = None,
|
2023-11-01 05:03:06 +00:00
|
|
|
):
|
2023-11-01 06:22:29 +00:00
|
|
|
super().__init__(feed, content, signature=signature, sequence=sequence, timestamp=timestamp, previous=previous)
|
2017-08-05 17:32:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def _check_signature(self) -> None:
|
|
|
|
if self.signature is None:
|
2017-08-05 17:32:01 +00:00
|
|
|
self.signature = self._sign()
|
2017-08-05 16:21:14 +00:00
|
|
|
|
2023-11-01 06:22:29 +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)
|
2023-11-18 05:50:51 +00:00
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
return (b64encode(bytes(self.feed.sign(data))) + b".sig.ed25519").decode("ascii")
|