librats 3.0.5.dev2__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- librats-3.0.5.dev2.dist-info/METADATA +309 -0
- librats-3.0.5.dev2.dist-info/RECORD +21 -0
- librats-3.0.5.dev2.dist-info/WHEEL +5 -0
- librats-3.0.5.dev2.dist-info/licenses/LICENSE +21 -0
- librats-3.0.5.dev2.dist-info/top_level.txt +1 -0
- librats_py/__init__.py +48 -0
- librats_py/callbacks.py +52 -0
- librats_py/core.py +743 -0
- librats_py/ctypes_wrapper.py +274 -0
- librats_py/enums.py +181 -0
- librats_py/examples/__init__.py +3 -0
- librats_py/examples/basic_client.py +92 -0
- librats_py/examples/file_transfer.py +122 -0
- librats_py/examples/gossipsub_chat.py +125 -0
- librats_py/exceptions.py +85 -0
- librats_py/rats.dll +0 -0
- librats_py/tests/__init__.py +3 -0
- librats_py/tests/conftest.py +31 -0
- librats_py/tests/test_abi_layout.py +90 -0
- librats_py/tests/test_client.py +173 -0
- librats_py/tests/test_integration.py +181 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
GossipSub chat room example using librats.
|
|
4
|
+
|
|
5
|
+
Demonstrates the pub/sub subsystem. The subsystem must be enabled and topics
|
|
6
|
+
subscribed before ``start()``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
|
|
13
|
+
from librats_py import RatsNode, RatsError, LogLevel, set_log_level
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GossipSubChat:
|
|
17
|
+
def __init__(self, listen_port: int, username: str, topic: str):
|
|
18
|
+
self.listen_port = listen_port
|
|
19
|
+
self.username = username
|
|
20
|
+
self.topic = topic
|
|
21
|
+
self.node = RatsNode(listen_port)
|
|
22
|
+
|
|
23
|
+
# Enable + subscribe BEFORE start().
|
|
24
|
+
self.node.on_peer_connected(lambda pid: self._print(f"+ {pid[:16]}… joined"))
|
|
25
|
+
self.node.on_peer_disconnected(
|
|
26
|
+
lambda pid, why: self._print(f"- {pid[:16]}… left ({why.name})"))
|
|
27
|
+
self.node.enable_pubsub()
|
|
28
|
+
self.node.subscribe(topic, self.on_topic_message)
|
|
29
|
+
|
|
30
|
+
def _print(self, line):
|
|
31
|
+
print(f"\n{line}")
|
|
32
|
+
print(f"[{self.topic}]> ", end="", flush=True)
|
|
33
|
+
|
|
34
|
+
def on_topic_message(self, peer_id, topic, data):
|
|
35
|
+
if peer_id == self.node.local_id:
|
|
36
|
+
return # publish() also delivers to our own subscription
|
|
37
|
+
try:
|
|
38
|
+
msg = json.loads(data.decode('utf-8'))
|
|
39
|
+
who = msg.get('username', '?')
|
|
40
|
+
kind = msg.get('type')
|
|
41
|
+
if kind == 'chat':
|
|
42
|
+
self._print(f"{who}: {msg.get('content', '')}")
|
|
43
|
+
return
|
|
44
|
+
if kind in ('join', 'leave'):
|
|
45
|
+
self._print(f"* {who} {'joined' if kind == 'join' else 'left'}")
|
|
46
|
+
return
|
|
47
|
+
except (json.JSONDecodeError, UnicodeDecodeError, AttributeError):
|
|
48
|
+
pass
|
|
49
|
+
self._print(f"{peer_id[:16]}…: {data!r}")
|
|
50
|
+
|
|
51
|
+
def start(self):
|
|
52
|
+
self.node.start()
|
|
53
|
+
print(f"GossipSub chat on port {self.listen_port}")
|
|
54
|
+
print(f"Local peer id: {self.node.local_id}")
|
|
55
|
+
print(f"Username: {self.username} Topic: {self.topic}")
|
|
56
|
+
self._publish('join', '')
|
|
57
|
+
|
|
58
|
+
def stop(self):
|
|
59
|
+
try:
|
|
60
|
+
self._publish('leave', '')
|
|
61
|
+
except RatsError:
|
|
62
|
+
pass
|
|
63
|
+
self.node.stop()
|
|
64
|
+
|
|
65
|
+
def _publish(self, kind, content):
|
|
66
|
+
payload = {
|
|
67
|
+
'type': kind,
|
|
68
|
+
'username': self.username,
|
|
69
|
+
'content': content,
|
|
70
|
+
'timestamp': datetime.now().isoformat(),
|
|
71
|
+
}
|
|
72
|
+
self.node.publish(self.topic, json.dumps(payload).encode('utf-8'))
|
|
73
|
+
|
|
74
|
+
def run(self):
|
|
75
|
+
print("\nCommands: connect <host> <port> | peers | quit | <message>\n")
|
|
76
|
+
while True:
|
|
77
|
+
try:
|
|
78
|
+
line = input(f"[{self.topic}]> ").strip()
|
|
79
|
+
except (EOFError, KeyboardInterrupt):
|
|
80
|
+
break
|
|
81
|
+
if not line:
|
|
82
|
+
continue
|
|
83
|
+
parts = line.split()
|
|
84
|
+
cmd = parts[0].lower()
|
|
85
|
+
try:
|
|
86
|
+
if cmd in ("quit", "exit"):
|
|
87
|
+
break
|
|
88
|
+
elif cmd == "connect" and len(parts) == 3:
|
|
89
|
+
self.node.connect(parts[1], int(parts[2]))
|
|
90
|
+
print(f"Dialing {parts[1]}:{parts[2]}…")
|
|
91
|
+
elif cmd == "peers":
|
|
92
|
+
for pid in self.node.peer_ids:
|
|
93
|
+
print(f" - {pid}")
|
|
94
|
+
else:
|
|
95
|
+
self._publish('chat', line)
|
|
96
|
+
except RatsError as e:
|
|
97
|
+
print(f"Error: {e}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def main():
|
|
101
|
+
if len(sys.argv) < 3:
|
|
102
|
+
print("Usage: python gossipsub_chat.py <listen_port> <username> [topic]")
|
|
103
|
+
sys.exit(1)
|
|
104
|
+
try:
|
|
105
|
+
listen_port = int(sys.argv[1])
|
|
106
|
+
except ValueError:
|
|
107
|
+
print("Error: Port must be a number")
|
|
108
|
+
sys.exit(1)
|
|
109
|
+
username = sys.argv[2].strip()
|
|
110
|
+
topic = sys.argv[3] if len(sys.argv) > 3 else "general"
|
|
111
|
+
if not username:
|
|
112
|
+
print("Error: Username cannot be empty")
|
|
113
|
+
sys.exit(1)
|
|
114
|
+
|
|
115
|
+
set_log_level(LogLevel.INFO)
|
|
116
|
+
chat = GossipSubChat(listen_port, username, topic)
|
|
117
|
+
try:
|
|
118
|
+
chat.start()
|
|
119
|
+
chat.run()
|
|
120
|
+
finally:
|
|
121
|
+
chat.stop()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
if __name__ == "__main__":
|
|
125
|
+
main()
|
librats_py/exceptions.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Exceptions of the librats Python bindings, one per ``rats_error_t`` code.
|
|
3
|
+
|
|
4
|
+
:func:`check_error` turns a returned code into the matching exception.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .enums import RatsError as ErrorCode
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RatsError(Exception):
|
|
11
|
+
"""Base of every librats exception; ``error_code`` is the ``rats_error_t``."""
|
|
12
|
+
|
|
13
|
+
code = ErrorCode.INTERNAL # what a subclass raised without an explicit code carries
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, error_code: ErrorCode = None):
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.error_code = self.code if error_code is None else error_code
|
|
18
|
+
self.message = message
|
|
19
|
+
|
|
20
|
+
def __str__(self):
|
|
21
|
+
return f"{self.message} ({self.error_code.name})"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RatsInvalidArgError(RatsError):
|
|
25
|
+
"""A NULL or malformed argument: bad peer id, bad JSON, impossible config."""
|
|
26
|
+
code = ErrorCode.INVALID_ARG
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RatsNotStartedError(RatsError):
|
|
30
|
+
"""The call needs a started node."""
|
|
31
|
+
code = ErrorCode.NOT_STARTED
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RatsAlreadyStartedError(RatsError):
|
|
35
|
+
"""The call is only allowed before start()."""
|
|
36
|
+
code = ErrorCode.ALREADY_STARTED
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RatsNotEnabledError(RatsError):
|
|
40
|
+
"""The subsystem was not enabled with its enable_*()."""
|
|
41
|
+
code = ErrorCode.NOT_ENABLED
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class RatsNoSuchPeerError(RatsError):
|
|
45
|
+
"""The peer is not connected."""
|
|
46
|
+
code = ErrorCode.NO_SUCH_PEER
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class RatsNotFoundError(RatsError):
|
|
50
|
+
"""No such transfer."""
|
|
51
|
+
code = ErrorCode.NOT_FOUND
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class RatsDeclinedError(RatsError):
|
|
55
|
+
"""Nothing to do or nothing to try with: the peer is already connected, an
|
|
56
|
+
attempt is running or cooling down, or no peer can help."""
|
|
57
|
+
code = ErrorCode.DECLINED
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class RatsBindError(RatsError):
|
|
61
|
+
"""start() could not open its sockets (the listen port is taken)."""
|
|
62
|
+
code = ErrorCode.BIND
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_ERROR_MAP = {
|
|
66
|
+
ErrorCode.INVALID_ARG: RatsInvalidArgError,
|
|
67
|
+
ErrorCode.NOT_STARTED: RatsNotStartedError,
|
|
68
|
+
ErrorCode.ALREADY_STARTED: RatsAlreadyStartedError,
|
|
69
|
+
ErrorCode.NOT_ENABLED: RatsNotEnabledError,
|
|
70
|
+
ErrorCode.NO_SUCH_PEER: RatsNoSuchPeerError,
|
|
71
|
+
ErrorCode.NOT_FOUND: RatsNotFoundError,
|
|
72
|
+
ErrorCode.DECLINED: RatsDeclinedError,
|
|
73
|
+
ErrorCode.BIND: RatsBindError,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def check_error(error_code: int, operation: str) -> None:
|
|
78
|
+
"""Raise the exception matching a non-OK ``rats_error_t``."""
|
|
79
|
+
if error_code == ErrorCode.OK:
|
|
80
|
+
return
|
|
81
|
+
try:
|
|
82
|
+
code = ErrorCode(error_code)
|
|
83
|
+
except ValueError:
|
|
84
|
+
raise RatsError(f"{operation} failed (unknown error {error_code})")
|
|
85
|
+
raise _ERROR_MAP.get(code, RatsError)(f"{operation} failed", code)
|
librats_py/rats.dll
ADDED
|
Binary file
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Pytest configuration for the librats Python bindings.
|
|
3
|
+
|
|
4
|
+
Tests marked ``native`` need the librats shared library; when it cannot be
|
|
5
|
+
loaded they are skipped, not failed. Point ``LIBRATS_LIBRARY_PATH`` at the
|
|
6
|
+
directory holding it if it is neither next to the package nor in ``build/``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
import pytest
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
|
15
|
+
|
|
16
|
+
from librats_py.ctypes_wrapper import LibratsNotFoundError, get_librats # noqa: E402
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
get_librats()
|
|
20
|
+
LIBRATS_AVAILABLE = True
|
|
21
|
+
except LibratsNotFoundError:
|
|
22
|
+
LIBRATS_AVAILABLE = False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def pytest_collection_modifyitems(config, items):
|
|
26
|
+
if LIBRATS_AVAILABLE:
|
|
27
|
+
return
|
|
28
|
+
skip = pytest.mark.skip(reason="librats shared library not available")
|
|
29
|
+
for item in items:
|
|
30
|
+
if "native" in item.keywords:
|
|
31
|
+
item.add_marker(skip)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""The ctypes structs against the C header they mirror.
|
|
2
|
+
|
|
3
|
+
ctypes cannot see rats.h, so a field added there and not here still loads and
|
|
4
|
+
runs: on 64-bit it may even land in padding and look fine, while on 32-bit every
|
|
5
|
+
later field shifts. This reads the struct definitions out of the header and
|
|
6
|
+
compares field order and types, so such a change fails here instead.
|
|
7
|
+
|
|
8
|
+
Needs the source tree (the header is not shipped with the package); skipped
|
|
9
|
+
without it. Does not need the shared library.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from ctypes import c_char, c_char_p, c_double, c_int, c_size_t, c_uint16, c_uint32, c_uint64
|
|
15
|
+
|
|
16
|
+
import pytest
|
|
17
|
+
|
|
18
|
+
from librats_py.ctypes_wrapper import (
|
|
19
|
+
RatsBtConfig, RatsConfig, RatsFileProgress, RatsPathStats, RatsPeerInfo,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
HEADER = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
23
|
+
"..", "..", "..", "src", "librats", "bindings", "rats.h")
|
|
24
|
+
|
|
25
|
+
STRUCTS = {
|
|
26
|
+
"rats_config_t": RatsConfig,
|
|
27
|
+
"rats_peer_info_t": RatsPeerInfo,
|
|
28
|
+
"rats_path_stats_t": RatsPathStats,
|
|
29
|
+
"rats_file_progress_t": RatsFileProgress,
|
|
30
|
+
"rats_bt_config_t": RatsBtConfig,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
SCALARS = {
|
|
34
|
+
"uint16_t": c_uint16,
|
|
35
|
+
"uint32_t": c_uint32,
|
|
36
|
+
"uint64_t": c_uint64,
|
|
37
|
+
"size_t": c_size_t,
|
|
38
|
+
"int": c_int,
|
|
39
|
+
"double": c_double,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _c_structs(text):
|
|
44
|
+
"""{name: [(c_type, field, array_len or None)]} for every typedef'd struct."""
|
|
45
|
+
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
|
|
46
|
+
text = re.sub(r"//[^\n]*", "", text)
|
|
47
|
+
out = {}
|
|
48
|
+
for body, name in re.findall(r"typedef\s+struct\s*\{(.*?)\}\s*(\w+)\s*;", text, flags=re.S):
|
|
49
|
+
fields = []
|
|
50
|
+
for decl in body.split(";"):
|
|
51
|
+
decl = " ".join(decl.split())
|
|
52
|
+
if not decl:
|
|
53
|
+
continue
|
|
54
|
+
m = re.fullmatch(r"(.+?)\s*\b(\w+)\s*(?:\[(\d+)\])?", decl)
|
|
55
|
+
assert m, f"{name}: cannot parse {decl!r}"
|
|
56
|
+
fields.append((m.group(1).strip(), m.group(2), int(m.group(3)) if m.group(3) else None))
|
|
57
|
+
out[name] = fields
|
|
58
|
+
return out
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _expected_ctype(c_type, array_len):
|
|
62
|
+
if array_len is not None:
|
|
63
|
+
assert c_type == "char", f"only char arrays are mirrored, got {c_type}[]"
|
|
64
|
+
return c_char * array_len
|
|
65
|
+
if c_type.replace(" ", "") == "constchar*":
|
|
66
|
+
return c_char_p
|
|
67
|
+
if c_type in SCALARS:
|
|
68
|
+
return SCALARS[c_type]
|
|
69
|
+
if re.fullmatch(r"rats_\w+_t", c_type):
|
|
70
|
+
return c_int # an enum: int-sized in C, int-based in C++
|
|
71
|
+
raise AssertionError(f"no ctypes mapping for C type {c_type!r}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@pytest.mark.skipif(not os.path.exists(HEADER), reason="rats.h not found (not a source tree)")
|
|
75
|
+
@pytest.mark.parametrize("c_name", sorted(STRUCTS))
|
|
76
|
+
def test_struct_matches_header(c_name):
|
|
77
|
+
with open(HEADER, encoding="utf-8") as f:
|
|
78
|
+
c_structs = _c_structs(f.read())
|
|
79
|
+
assert c_name in c_structs, f"{c_name} not found in rats.h"
|
|
80
|
+
|
|
81
|
+
want = [(field, _expected_ctype(t, n)) for t, field, n in c_structs[c_name]]
|
|
82
|
+
have = list(STRUCTS[c_name]._fields_)
|
|
83
|
+
|
|
84
|
+
assert [f for f, _ in have] == [f for f, _ in want], f"{c_name}: field names or order differ"
|
|
85
|
+
for (field, got), (_, expected) in zip(have, want):
|
|
86
|
+
if hasattr(expected, "_length_"): # a char array: ctypes makes a new type per call
|
|
87
|
+
ok = getattr(got, "_type_", None) is c_char and getattr(got, "_length_", None) == expected._length_
|
|
88
|
+
else:
|
|
89
|
+
ok = got is expected
|
|
90
|
+
assert ok, f"{c_name}.{field}: ctypes {got.__name__}, C wants {expected.__name__}"
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Single-node tests of RatsNode against the librats shared library."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from librats_py import (
|
|
6
|
+
RatsNode, RatsError, RatsInvalidArgError, RatsNotEnabledError, RatsNotStartedError,
|
|
7
|
+
RatsAlreadyStartedError, RatsNotFoundError, RatsDeclinedError, ErrorCode, LogLevel,
|
|
8
|
+
Security, Transport, TransportMask, NatMapping, CloseReason, Direction,
|
|
9
|
+
FALLBACK_NEVER, version, version_info, abi, git_describe, error_str, set_log_level,
|
|
10
|
+
set_log_file,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
native = pytest.mark.native
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.fixture
|
|
17
|
+
def node():
|
|
18
|
+
n = RatsNode(bind_address="127.0.0.1")
|
|
19
|
+
yield n
|
|
20
|
+
n.destroy()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@native
|
|
24
|
+
def test_defaults(node):
|
|
25
|
+
assert len(node.local_id) == 64
|
|
26
|
+
int(node.local_id, 16)
|
|
27
|
+
assert node.protocol == "librats/1.0"
|
|
28
|
+
assert node.transports == TransportMask.NONE
|
|
29
|
+
assert node.listen_port == 0
|
|
30
|
+
node.start()
|
|
31
|
+
assert node.running
|
|
32
|
+
assert node.listen_port != 0
|
|
33
|
+
assert node.transports == TransportMask.TCP | TransportMask.UDP
|
|
34
|
+
assert node.peer_count == 0 and node.peer_ids == []
|
|
35
|
+
assert node.nat_mapping == NatMapping.UNKNOWN
|
|
36
|
+
assert node.observed_addresses == []
|
|
37
|
+
node.stop()
|
|
38
|
+
node.stop()
|
|
39
|
+
assert not node.running
|
|
40
|
+
assert node.transports == TransportMask.NONE
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@native
|
|
44
|
+
def test_config_keywords_reach_the_node():
|
|
45
|
+
with RatsNode(security=Security.PLAINTEXT, protocol="myapp/2.0", max_peers=10,
|
|
46
|
+
transports=TransportMask.TCP, transport_fallback_ms=FALLBACK_NEVER,
|
|
47
|
+
udp_offload=False, udp_idle_timeout_ms=5000, reactor_threads=2,
|
|
48
|
+
network_monitor=False) as n:
|
|
49
|
+
assert n.protocol == "myapp/2.0"
|
|
50
|
+
assert n.max_peers == 10
|
|
51
|
+
n.start()
|
|
52
|
+
assert n.transports == TransportMask.TCP
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@native
|
|
56
|
+
def test_impossible_config_is_refused():
|
|
57
|
+
with pytest.raises(RatsInvalidArgError):
|
|
58
|
+
RatsNode(transports=TransportMask.UDP, preferred_transport=Transport.TCP)
|
|
59
|
+
with pytest.raises(RatsInvalidArgError):
|
|
60
|
+
RatsNode(preferred_transport=Transport.RELAY)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@native
|
|
64
|
+
def test_destroyed_node_is_inert():
|
|
65
|
+
with RatsNode() as n:
|
|
66
|
+
n.start()
|
|
67
|
+
with pytest.raises(RatsError):
|
|
68
|
+
n.local_id
|
|
69
|
+
n.destroy() # idempotent
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@native
|
|
73
|
+
def test_lifecycle_rules(node):
|
|
74
|
+
with pytest.raises(RatsNotStartedError):
|
|
75
|
+
node.connect("127.0.0.1", 1)
|
|
76
|
+
node.start()
|
|
77
|
+
with pytest.raises(RatsAlreadyStartedError):
|
|
78
|
+
node.start()
|
|
79
|
+
with pytest.raises(RatsAlreadyStartedError):
|
|
80
|
+
node.enable_pubsub()
|
|
81
|
+
with pytest.raises(RatsAlreadyStartedError):
|
|
82
|
+
node.on_peer_connected(lambda peer: None)
|
|
83
|
+
with pytest.raises(RatsNotEnabledError):
|
|
84
|
+
node.publish("topic", b"data")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@native
|
|
88
|
+
def test_unknown_peer(node):
|
|
89
|
+
node.start()
|
|
90
|
+
other = "0" * 64
|
|
91
|
+
assert node.peer_info(other) is None
|
|
92
|
+
assert node.path_stats(other) is None
|
|
93
|
+
assert node.peer_writable(other) is False
|
|
94
|
+
assert node.peer_rtt_ms(other) is None
|
|
95
|
+
with pytest.raises(RatsInvalidArgError):
|
|
96
|
+
node.peer_info("not-hex")
|
|
97
|
+
with pytest.raises(RatsError) as e:
|
|
98
|
+
node.send(other, "chat", b"x")
|
|
99
|
+
assert e.value.error_code == ErrorCode.NO_SUCH_PEER
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@native
|
|
103
|
+
def test_every_subsystem_enables_before_start(node):
|
|
104
|
+
node.enable_dht()
|
|
105
|
+
node.enable_mdns()
|
|
106
|
+
node.enable_peer_exchange()
|
|
107
|
+
node.enable_port_mapping(upnp=False, natpmp=False)
|
|
108
|
+
node.enable_hole_punch()
|
|
109
|
+
node.enable_relay()
|
|
110
|
+
node.enable_pubsub()
|
|
111
|
+
node.enable_json()
|
|
112
|
+
node.enable_file_transfer()
|
|
113
|
+
node.enable_ping()
|
|
114
|
+
node.enable_reconnect()
|
|
115
|
+
node.enable_pubsub() # idempotent
|
|
116
|
+
node.start()
|
|
117
|
+
with pytest.raises(RatsDeclinedError):
|
|
118
|
+
node.punch_peer("0" * 64)
|
|
119
|
+
with pytest.raises(RatsNotFoundError):
|
|
120
|
+
node.cancel_file(node.local_id, 999999)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@native
|
|
124
|
+
def test_dht_keys_can_be_set(node):
|
|
125
|
+
with pytest.raises(RatsNotEnabledError):
|
|
126
|
+
node.dht_set_keys(["room/a"])
|
|
127
|
+
node.enable_dht()
|
|
128
|
+
node.dht_set_keys(["room/a", "room/b"])
|
|
129
|
+
node.dht_set_keys([]) # none: found by nobody over the DHT
|
|
130
|
+
with pytest.raises(RatsInvalidArgError):
|
|
131
|
+
node.dht_set_keys([""])
|
|
132
|
+
with pytest.raises(TypeError):
|
|
133
|
+
node.dht_set_keys("room/a") # one string is not a list of keys
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@native
|
|
137
|
+
def test_reconnect_lost_enables_before_start_only(node):
|
|
138
|
+
node.enable_reconnect_lost(30000)
|
|
139
|
+
node.add_reconnect("127.0.0.1", 1)
|
|
140
|
+
node.start()
|
|
141
|
+
with pytest.raises(RatsAlreadyStartedError):
|
|
142
|
+
node.enable_reconnect_lost(30000)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@native
|
|
146
|
+
def test_max_peers_is_settable(node):
|
|
147
|
+
node.max_peers = 20
|
|
148
|
+
assert node.max_peers == 20
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@native
|
|
152
|
+
def test_library_info_and_logging():
|
|
153
|
+
assert version()
|
|
154
|
+
assert isinstance(git_describe(), str)
|
|
155
|
+
info = version_info()
|
|
156
|
+
assert abi() == (info.major << 16) | (info.minor << 8) | info.patch
|
|
157
|
+
assert error_str(ErrorCode.DECLINED) == "RATS_ERR_DECLINED"
|
|
158
|
+
set_log_level(LogLevel.WARN)
|
|
159
|
+
set_log_file(None)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def test_enums_mirror_the_c_abi():
|
|
163
|
+
assert (Transport.UDP, Transport.TCP, Transport.RELAY) == (0, 1, 2)
|
|
164
|
+
assert (TransportMask.TCP, TransportMask.UDP) == (0x1, 0x2)
|
|
165
|
+
assert (Direction.OUTBOUND, Direction.INBOUND) == (0, 1)
|
|
166
|
+
assert CloseReason.SLOW_CONSUMER == 6 and CloseReason.DIAL_SUPERSEDED == 11
|
|
167
|
+
assert (ErrorCode.NOT_FOUND, ErrorCode.DECLINED, ErrorCode.BIND, ErrorCode.INTERNAL) == (6, 7, 8, 9)
|
|
168
|
+
assert NatMapping.ENDPOINT_DEPENDENT == 3
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def test_exception_carries_its_code():
|
|
172
|
+
assert RatsNotFoundError("x").error_code == ErrorCode.NOT_FOUND
|
|
173
|
+
assert "INVALID_ARG" in str(RatsError("boom", ErrorCode.INVALID_ARG))
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Two and three live nodes over loopback."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from librats_py import (
|
|
10
|
+
RatsNode, RatsNoSuchPeerError, CloseReason, Direction, FileTransferStatus, Transport,
|
|
11
|
+
TransportMask,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
pytestmark = pytest.mark.native
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def wait_for(pred, timeout=10.0):
|
|
18
|
+
deadline = time.monotonic() + timeout
|
|
19
|
+
while time.monotonic() < deadline:
|
|
20
|
+
if pred():
|
|
21
|
+
return True
|
|
22
|
+
time.sleep(0.01)
|
|
23
|
+
return pred()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.fixture
|
|
27
|
+
def nodes():
|
|
28
|
+
made = []
|
|
29
|
+
|
|
30
|
+
def make(**kw):
|
|
31
|
+
kw.setdefault("bind_address", "127.0.0.1")
|
|
32
|
+
n = RatsNode(**kw)
|
|
33
|
+
made.append(n)
|
|
34
|
+
return n
|
|
35
|
+
|
|
36
|
+
yield make
|
|
37
|
+
for n in made:
|
|
38
|
+
n.destroy()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def link(client, server):
|
|
42
|
+
server.start()
|
|
43
|
+
client.start()
|
|
44
|
+
client.connect("127.0.0.1", server.listen_port)
|
|
45
|
+
assert wait_for(lambda: client.peer_count == 1 and server.peer_count == 1)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_channel_message_info_and_disconnect(nodes):
|
|
49
|
+
server, client = nodes(), nodes(dial_only=True)
|
|
50
|
+
got, gone = [], []
|
|
51
|
+
server.on("chat", lambda peer, data: got.append((peer, data)))
|
|
52
|
+
server.on_peer_disconnected(lambda peer, why: gone.append(why))
|
|
53
|
+
link(client, server)
|
|
54
|
+
|
|
55
|
+
sid, cid = server.local_id, client.local_id
|
|
56
|
+
assert client.peer_ids == [sid]
|
|
57
|
+
client.send(sid, "chat", b"hello\x00world")
|
|
58
|
+
assert wait_for(lambda: got == [(cid, b"hello\x00world")])
|
|
59
|
+
|
|
60
|
+
info = client.peer_info(sid)
|
|
61
|
+
assert info.direction == Direction.OUTBOUND
|
|
62
|
+
assert info.transport == Transport.UDP
|
|
63
|
+
assert info.address.endswith(f":{server.listen_port}")
|
|
64
|
+
assert wait_for(lambda: client.peer_info(sid).transports
|
|
65
|
+
== TransportMask.TCP | TransportMask.UDP)
|
|
66
|
+
assert server.peer_info(cid).direction == Direction.INBOUND
|
|
67
|
+
|
|
68
|
+
client.disconnect(sid)
|
|
69
|
+
assert wait_for(lambda: client.peer_count == 0 and gone)
|
|
70
|
+
assert isinstance(gone[0], CloseReason) and gone[0] != CloseReason.SLOW_CONSUMER
|
|
71
|
+
with pytest.raises(RatsNoSuchPeerError):
|
|
72
|
+
client.disconnect(sid)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_live_message_and_path_stats(nodes):
|
|
76
|
+
server, client = nodes(), nodes(dial_only=True)
|
|
77
|
+
got, samples = [], []
|
|
78
|
+
server.on("video", lambda peer, data: got.append(data))
|
|
79
|
+
client.on_peer_path(lambda peer, stats: samples.append(stats))
|
|
80
|
+
link(client, server)
|
|
81
|
+
|
|
82
|
+
frame = b"k" * 20000
|
|
83
|
+
client.send(server.local_id, "video", frame, lifetime_ms=500)
|
|
84
|
+
assert wait_for(lambda: got == [frame])
|
|
85
|
+
|
|
86
|
+
def counted():
|
|
87
|
+
stats = client.path_stats(server.local_id)
|
|
88
|
+
return stats is not None and stats.live_sent == 1
|
|
89
|
+
assert wait_for(counted)
|
|
90
|
+
assert wait_for(lambda: len(samples) >= 2)
|
|
91
|
+
assert samples[-1].srtt_us > 0
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def test_dial_failed_names_the_address(nodes):
|
|
95
|
+
closed = nodes()
|
|
96
|
+
closed.start()
|
|
97
|
+
port = closed.listen_port
|
|
98
|
+
closed.destroy()
|
|
99
|
+
|
|
100
|
+
client = nodes(dial_only=True)
|
|
101
|
+
failed = []
|
|
102
|
+
client.on_dial_failed(failed.append)
|
|
103
|
+
client.start()
|
|
104
|
+
client.connect("127.0.0.1", port)
|
|
105
|
+
assert wait_for(lambda: failed, timeout=15)
|
|
106
|
+
assert failed[0] == f"127.0.0.1:{port}"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_pubsub_and_json(nodes):
|
|
110
|
+
a, b = nodes(), nodes()
|
|
111
|
+
received, values = [], []
|
|
112
|
+
for n in (a, b):
|
|
113
|
+
n.enable_pubsub()
|
|
114
|
+
n.enable_json()
|
|
115
|
+
a.subscribe("room", lambda peer, topic, data: received.append((topic, data)))
|
|
116
|
+
b.subscribe("room", lambda peer, topic, data: None)
|
|
117
|
+
a.on_json("greeting", lambda peer, value: values.append(value))
|
|
118
|
+
link(b, a)
|
|
119
|
+
|
|
120
|
+
def published():
|
|
121
|
+
b.publish("room", b"payload")
|
|
122
|
+
return ("room", b"payload") in received
|
|
123
|
+
assert wait_for(published)
|
|
124
|
+
|
|
125
|
+
b.broadcast_json("greeting", {"hi": "there", "n": 7})
|
|
126
|
+
assert wait_for(lambda: {"hi": "there", "n": 7} in values)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_file_transfer(nodes):
|
|
130
|
+
a, b = nodes(), nodes()
|
|
131
|
+
for n in (a, b):
|
|
132
|
+
n.enable_file_transfer()
|
|
133
|
+
dest_dir = tempfile.mkdtemp()
|
|
134
|
+
done, progress = [], []
|
|
135
|
+
|
|
136
|
+
a.on_file_offer(lambda peer, tid, name, size, is_dir:
|
|
137
|
+
a.accept_file(peer, tid, os.path.join(dest_dir, name)))
|
|
138
|
+
a.on_file_progress(progress.append)
|
|
139
|
+
a.on_file_complete(lambda peer, tid, ok, path: done.append((peer, tid, ok, path)))
|
|
140
|
+
link(b, a)
|
|
141
|
+
|
|
142
|
+
with tempfile.NamedTemporaryFile("wb", delete=False, suffix=".bin") as f:
|
|
143
|
+
f.write(b"payload" * 1000)
|
|
144
|
+
src = f.name
|
|
145
|
+
try:
|
|
146
|
+
tid = b.send_file(a.local_id, src)
|
|
147
|
+
assert wait_for(lambda: done)
|
|
148
|
+
peer, got_tid, ok, path = done[0]
|
|
149
|
+
assert (peer, got_tid, ok) == (b.local_id, tid, True)
|
|
150
|
+
with open(path, "rb") as f:
|
|
151
|
+
assert f.read() == b"payload" * 1000
|
|
152
|
+
assert any(p.direction == Direction.INBOUND and p.transfer_id == tid for p in progress)
|
|
153
|
+
assert all(isinstance(p.status, FileTransferStatus) for p in progress)
|
|
154
|
+
finally:
|
|
155
|
+
os.unlink(src)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_peer_exchange_introduces_peers(nodes):
|
|
159
|
+
hub, a, b = nodes(), nodes(), nodes()
|
|
160
|
+
for n in (hub, a, b):
|
|
161
|
+
n.enable_peer_exchange()
|
|
162
|
+
n.start()
|
|
163
|
+
a.connect("127.0.0.1", hub.listen_port)
|
|
164
|
+
assert wait_for(lambda: hub.peer_count == 1)
|
|
165
|
+
b.connect("127.0.0.1", hub.listen_port)
|
|
166
|
+
assert wait_for(lambda: a.peer_count == 2 and b.peer_count == 2, timeout=15)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def test_relay(nodes):
|
|
170
|
+
hub, a, b = nodes(), nodes(), nodes()
|
|
171
|
+
hub.enable_relay(serve=True)
|
|
172
|
+
a.enable_relay()
|
|
173
|
+
b.enable_relay()
|
|
174
|
+
for n in (hub, a, b):
|
|
175
|
+
n.start()
|
|
176
|
+
a.connect("127.0.0.1", hub.listen_port)
|
|
177
|
+
b.connect("127.0.0.1", hub.listen_port)
|
|
178
|
+
assert wait_for(lambda: hub.peer_count == 2)
|
|
179
|
+
a.connect_via_relay(b.local_id)
|
|
180
|
+
assert wait_for(lambda: a.peer_count == 2 and b.peer_count == 2, timeout=20)
|
|
181
|
+
assert a.peer_info(b.local_id).transport == Transport.RELAY
|