magic-wormhole/src/wormhole/_order.py

69 lines
2.4 KiB
Python
Raw Normal View History

2017-02-24 02:11:07 +00:00
from __future__ import print_function, absolute_import, unicode_literals
from zope.interface import implementer
2017-02-23 00:56:39 +00:00
from attr import attrs, attrib
from attr.validators import provides, instance_of
from automat import MethodicalMachine
from . import _interfaces
2017-02-23 00:56:39 +00:00
@attrs
@implementer(_interfaces.IOrder)
class Order(object):
2017-02-23 00:56:39 +00:00
_side = attrib(validator=instance_of(type(u"")))
_timing = attrib(validator=provides(_interfaces.ITiming))
m = MethodicalMachine()
set_trace = getattr(m, "_setTrace", lambda self, f: None)
2017-02-23 00:56:39 +00:00
2017-02-24 02:11:07 +00:00
def __attrs_post_init__(self):
self._key = None
self._queue = []
def wire(self, key, receive):
self._K = _interfaces.IKey(key)
self._R = _interfaces.IReceive(receive)
@m.state(initial=True)
def S0_no_pake(self): pass # pragma: no cover
@m.state(terminal=True)
def S1_yes_pake(self): pass # pragma: no cover
2017-02-26 12:13:57 +00:00
def got_message(self, side, phase, body):
2017-02-25 02:30:00 +00:00
#print("ORDER[%s].got_message(%s)" % (self._side, phase))
2017-02-26 12:13:57 +00:00
assert isinstance(side, type("")), type(phase)
2017-02-22 20:51:53 +00:00
assert isinstance(phase, type("")), type(phase)
assert isinstance(body, type(b"")), type(body)
if phase == "pake":
2017-02-26 12:13:57 +00:00
self.got_pake(side, phase, body)
else:
2017-02-26 12:13:57 +00:00
self.got_non_pake(side, phase, body)
@m.input()
2017-02-26 12:13:57 +00:00
def got_pake(self, side, phase, body): pass
@m.input()
2017-02-26 12:13:57 +00:00
def got_non_pake(self, side, phase, body): pass
@m.output()
2017-02-26 12:13:57 +00:00
def queue(self, side, phase, body):
assert isinstance(side, type("")), type(phase)
2017-02-22 20:51:53 +00:00
assert isinstance(phase, type("")), type(phase)
assert isinstance(body, type(b"")), type(body)
2017-02-26 12:13:57 +00:00
self._queue.append((side, phase, body))
@m.output()
2017-02-26 12:13:57 +00:00
def notify_key(self, side, phase, body):
2017-02-22 20:51:53 +00:00
self._K.got_pake(body)
@m.output()
2017-02-26 12:13:57 +00:00
def drain(self, side, phase, body):
del phase
2017-02-22 20:51:53 +00:00
del body
2017-02-26 12:13:57 +00:00
for (side, phase, body) in self._queue:
self._deliver(side, phase, body)
self._queue[:] = []
@m.output()
2017-02-26 12:13:57 +00:00
def deliver(self, side, phase, body):
self._deliver(side, phase, body)
2017-02-26 12:13:57 +00:00
def _deliver(self, side, phase, body):
self._R.got_message(side, phase, body)
S0_no_pake.upon(got_non_pake, enter=S0_no_pake, outputs=[queue])
S0_no_pake.upon(got_pake, enter=S1_yes_pake, outputs=[notify_key, drain])
S1_yes_pake.upon(got_non_pake, enter=S1_yes_pake, outputs=[deliver])