From 73dccb8b15e1a3016f01f58e5e29bc8b7b8b876c Mon Sep 17 00:00:00 2001 From: Pedro Ferreira Date: Sat, 5 Aug 2017 20:01:17 +0200 Subject: [PATCH] Extract out stream() method --- ssb/feed.py | 9 ++++++--- ssb/tests/test_feed.py | 26 +++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/ssb/feed.py b/ssb/feed.py index aacf686..667f33a 100644 --- a/ssb/feed.py +++ b/ssb/feed.py @@ -67,6 +67,9 @@ class Message(object): msg = cls(feed, obj['content'], timestamp=obj['timestamp']) return msg, obj['signature'] + def serialize(self, add_signature=True): + return dumps(self.to_dict(add_signature=add_signature), indent=2).encode('utf-8') + def to_dict(self, add_signature=True): obj = to_ordered({ 'previous': self.previous.key if self.previous else None, @@ -86,7 +89,7 @@ class Message(object): @property def hash(self): - hash = sha256(dumps(self.to_dict(), indent=2).encode('ascii')).digest() + hash = sha256(self.serialize()).digest() return b64encode(hash).decode('ascii') + '.sha256' @property @@ -114,5 +117,5 @@ class LocalMessage(Message): def _sign(self): # ensure ordering of keys and indentation of 2 characters, like ssb-keys - data = dumps(self.to_dict(add_signature=False), indent=2) - return (b64encode(bytes(self.feed.sign(data.encode('ascii')))) + b'.sig.ed25519').decode('ascii') + data = self.serialize(add_signature=False) + return (b64encode(bytes(self.feed.sign(data))) + b'.sig.ed25519').decode('ascii') diff --git a/ssb/tests/test_feed.py b/ssb/tests/test_feed.py index 41037f8..c24dbb1 100644 --- a/ssb/tests/test_feed.py +++ b/ssb/tests/test_feed.py @@ -4,7 +4,7 @@ from collections import OrderedDict import pytest from nacl.signing import SigningKey, VerifyKey -from ssb.feed import LocalMessage, LocalFeed, Feed, Message, NoPrivateKeyException +from ssb.feed import LocalMessage, LocalFeed, Feed, Message @pytest.fixture() @@ -99,3 +99,27 @@ def test_remote_no_signature(remote_feed): ('name', 'neo'), ('description', 'The Chosen One') ]), None, timestamp=1495706260190) + + +def test_serialize(local_feed): + m1 = LocalMessage(local_feed, OrderedDict([ + ('type', 'about'), + ('about', local_feed.id), + ('name', 'neo'), + ('description', 'The Chosen One') + ]), timestamp=1495706260190) + + assert m1.serialize() == b"""{ + "previous": null, + "author": "@I/4cyN/jPBbDsikbHzAEvmaYlaJK33lW3UhWjNXjyrU=.ed25519", + "sequence": 1, + "timestamp": 1495706260190, + "hash": "sha256", + "content": { + "type": "about", + "about": "@I/4cyN/jPBbDsikbHzAEvmaYlaJK33lW3UhWjNXjyrU=.ed25519", + "name": "neo", + "description": "The Chosen One" + }, + "signature": "lPsQ9P10OgeyH6u0unFgiI2wV/RQ7Q2x2ebxnXYCzsJ055TBMXphRADTKhOMS2EkUxXQ9k3amj5fnWPudGxwBQ==.sig.ed25519" +}"""