Example #1
0
def attach_middlewares(
    server: Server,
    api_token: str = "",
    api_token_header: str = API_TOKEN_HEADER,
    peer_whitelist: List[Union[IPv4Network, IPv6Network]] = [],
):
    if api_token and api_token_header:
        logger.info("api token middleware attached")
    else:
        logger.info("api token middleware NOT attached")

    if peer_whitelist:
        logger.info(f"peer whitelist middleware attached with networks: {peer_whitelist}")
    else:
        logger.info("peer whitelist middleware NOT attached")

    async def recv_request(event: RecvRequest):
        # Middlewares called in reversed order
        if api_token and api_token_header:
            attach_token_auth(event, api_header=api_token_header, api_token=api_token)

        if peer_whitelist:
            attach_check_peer_method(event, address_whitelist=peer_whitelist)

    listen(server, RecvRequest, recv_request)
Example #2
0
    def __init__(self):
        self._host = os.environ.get("LND_HOST")
        self._port = int(os.environ.get("LND_PORT"))
        self._network = os.environ.get("NETWORK")
        self.id_pubkey = None
        self.stub = None

        os.environ["GRPC_SSL_CIPHER_SUITES"] = "HIGH+ECDSA"
        os.environ["SSL_CERT_DIR"] = "/root/.lnd"

        with open(
                f"/root/.lnd/data/chain/bitcoin/{self._network}/admin.macaroon",
                "rb") as macaroon_bytes:
            self._macaroon = macaroon_bytes.read().hex()

        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
        ctx.verify_mode = ssl.CERT_REQUIRED
        ctx.load_verify_locations(cafile="/root/.lnd/tls.cert")
        # can take second arg path the private key str(client_key)
        ctx.load_cert_chain("/root/.lnd/tls.cert", "/root/.lnd/tls.key")
        # ctx.load_verify_locations(str(trusted)) WE TRUST THE CERTIFICATE
        ctx.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
        ctx.set_ciphers("ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20")
        ctx.set_alpn_protocols(["h2"])
        try:
            ctx.set_npn_protocols(["h2"])
        except NotImplementedError:
            pass
        self._channel = Channel(self._host, self._port, ssl=ctx)

        async def attach_metadata(event: SendRequest):
            event.metadata["macaroon"] = self._macaroon

        listen(self._channel, SendRequest, attach_metadata)
Example #3
0
async def main(*, host: str = '127.0.0.1', port: int = 50051) -> None:
    server = Server([Greeter()])
    listen(server, RecvRequest, on_recv_request)
    with graceful_exit([server]):
        await server.start(host, port)
        print(f'Serving on {host}:{port}')
        await server.wait_closed()
Example #4
0
async def test_dispatch():
    class MyEvent(_Event, metaclass=_EventMeta):
        __payload__ = ('a', 'b')
        a: int
        b: str
        c: int
        d: str

    class MyDispatch(_Dispatch, metaclass=_DispatchMeta):
        @_dispatches(MyEvent)
        async def my_event(self, a, b, *, c, d):
            return await self.__dispatch__(MyEvent(a=a, b=b, c=c, d=d))

    class Target:
        __dispatch__ = MyDispatch()

    assert Target.__dispatch__.my_event is _ident
    assert await Target.__dispatch__.my_event(1, 3, c=6, d=9) == (1, 3)

    @mock_callback
    async def callback(event: MyEvent):
        assert event.a == 2
        assert event.b == 4
        assert event.c == 8
        assert event.d == 16

    listen(Target, MyEvent, callback)

    assert Target.__dispatch__.my_event is not _ident
    assert await Target.__dispatch__.my_event(2, 4, c=8, d=16) == (2, 4)
    with patch_event():
        callback.assert_called_once_with(MyEvent(a=2, b=4, c=8, d=16))
Example #5
0
async def main() -> None:
    async with Channel('127.0.0.1', 50051) as channel:
        listen(channel, SendRequest, on_send_request)

        stub = GreeterStub(channel)
        response = await stub.SayHello(HelloRequest(name='World'))
        print(response.message)
Example #6
0
async def main(*, host='127.0.0.1', port=50051):
    loop = asyncio.get_running_loop()
    server = Server([Greeter()], loop=loop)
    listen(server, RecvRequest, recv_request)
    with graceful_exit([server], loop=loop):
        await server.start(host, port)
        print(f'Serving on {host}:{port}')
        await server.wait_closed()
Example #7
0
    def configure(self, value: grpc_pb2.Server):
        assert isinstance(value, grpc_pb2.Server), type(value)
        self._config = value

        handlers = list(self.handlers)
        if not any(isinstance(h, Health) for h in handlers):
            handlers.append(Health())
        handlers = ServerReflection.extend(handlers)

        self.server = Server(handlers)
        listen(self.server, RecvRequest, _recv_request)
        listen(self.server, SendTrailingMetadata, _send_trailing_metadata)
async def _test(event_type):
    service = DummyService()
    events = []

    async def callback(event_):
        events.append(event_)

    async with ChannelFor([service]) as channel:
        listen(channel, event_type, callback)
        stub = DummyServiceStub(channel)
        reply = await stub.UnaryUnary(DummyRequest(value='ping'),
                                      timeout=1,
                                      metadata={'request': 'true'})
        assert reply == DummyReply(value='pong')

    event, = events
    return event
Example #9
0
async def _test(event_type):
    service = DummyService()
    events = []

    async def callback(event_):
        events.append(event_)

    channel_for = ChannelFor([service])
    async with channel_for as channel:
        server = channel_for._server

        listen(server, event_type, callback)
        stub = DummyServiceStub(channel)
        reply = await stub.UnaryUnary(DummyRequest(value='ping'),
                                      timeout=1,
                                      metadata={'foo': 'bar'})
        assert reply == DummyReply(value='pong')

    event, = events
    return event
Example #10
0
async def test_interrupt():
    class MyEvent(_Event, metaclass=_EventMeta):
        payload: int

    class MyDispatch(_Dispatch, metaclass=_DispatchMeta):
        @_dispatches(MyEvent)
        async def my_event(self, *, payload):
            return await self.__dispatch__(MyEvent(payload=payload))

    class Target:
        __dispatch__ = MyDispatch()

    @mock_callback
    async def cb1(_: MyEvent):
        pass

    @mock_callback
    async def cb2(event: MyEvent):
        event.interrupt()

    @mock_callback
    async def cb3(_: MyEvent):
        pass

    listen(Target, MyEvent, cb1)
    listen(Target, MyEvent, cb2)
    listen(Target, MyEvent, cb3)

    assert await Target.__dispatch__.my_event(payload=42) == ()

    cb1.assert_called_once()
    cb2.assert_called_once()
    assert not cb3.called
Example #11
0
    async def _start_grpc_server(self):

        self.grpc_server = Server([AioShadowsocksServicer()], loop=self.loop)
        listen(self.grpc_server, RecvRequest, logging_grpc_request)
        await self.grpc_server.start(self.grpc_host, self.grpc_port)
        logging.info(f"Start grpc Server on {self.grpc_host}:{self.grpc_port}")
Example #12
0
    def configure(self, value: grpc_pb2.Channel):
        assert isinstance(value, grpc_pb2.Channel), type(value)

        self.channel = Channel(value.address.host, value.address.port)
        listen(self.channel, SendRequest, _send_request)
        listen(self.channel, RecvTrailingMetadata, _recv_trailing_metadata)