Extract out stream() method

This commit is contained in:
Pedro Ferreira 2017-08-05 20:01:17 +02:00
parent a5ce920440
commit 73dccb8b15
2 changed files with 31 additions and 4 deletions

View File

@ -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')

View File

@ -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"
}"""