-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinv_message.py
50 lines (36 loc) · 1.4 KB
/
inv_message.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import struct
from io import BytesIO
from typing import List, Iterable
from serialize import read_var_int
class InvVector:
FORMAT = '<I32s'
def __init__(self, type_id: int, hash_bytes: bytes) -> None:
self._type_id = type_id
self._hash_bytes = hash_bytes
def type_id(self) -> int:
return self._type_id
def hash_bytes(self) -> bytes:
return self._hash_bytes
@classmethod
def deserialize(cls, payload: bytes) -> 'InvVector':
return InvVector(*struct.unpack(cls.FORMAT, payload))
def serialize(self) -> bytes:
return struct.pack(self.FORMAT, self._type_id, self._hash_bytes)
def __repr__(self) -> str:
return f'InvVector(type_id={self._type_id}, hash_bytes={self._hash_bytes})'
class InvMessage:
def __init__(self, inventory: List[InvVector]) -> None:
self._inventory = inventory
@classmethod
def deserialize(cls, payload: bytes) -> 'InvMessage':
b = BytesIO(payload)
inv_count = read_var_int(b)
inventory = []
for _ in range(inv_count):
inv_vector_bytes = b.read(struct.calcsize(InvVector.FORMAT))
inventory.append(InvVector.deserialize(inv_vector_bytes))
return InvMessage(inventory)
def inventory(self) -> Iterable[InvVector]:
return iter(self._inventory)
def __repr__(self) -> str:
return f'InvMessage({self._inventory})'