model.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. # This file is part of DarkFi (https://dark.fi)
  2. #
  3. # Copyright (C) 2020-2023 Dyne.org foundation
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import logging, time
  18. import datetime as dt
  19. # -------------------------------------------------------------------
  20. # TODO:
  21. # * on first get_info call, initialize data structure
  22. # * use channel id as key
  23. # * e.g. outbound[id] = [info1, info2, ...]
  24. # * create unique null id if not connected
  25. # -------------------------------------------------------------------
  26. class Model:
  27. def __init__(self):
  28. self.info = Info()
  29. self.nodes = {}
  30. self.channel_lookup = {}
  31. def update_node(self, key, value):
  32. self.nodes[key] = value
  33. def handle_nodes(self, node):
  34. #logging.debug(f"p2p_get_info(): {node}")
  35. name = list(node.keys())[0]
  36. values = list(node.values())[0]
  37. info = values["result"]
  38. channels = info["channels"]
  39. for channel in channels:
  40. id = channel["id"]
  41. self.channel_lookup[id] = channel
  42. for channel in channels:
  43. if channel["session"] != "inbound":
  44. continue
  45. id = channel["id"]
  46. url = self.channel_lookup[id]["url"]
  47. self.info.update_inbound(f"{id}", url)
  48. for i, id in enumerate(info["outbound_slots"]):
  49. if id == 0:
  50. self.info.update_outbound(f"{i}", "none")
  51. continue
  52. assert id in self.channel_lookup
  53. url = self.channel_lookup[id]["url"]
  54. self.info.update_outbound(f"{i}", url)
  55. for channel in channels:
  56. if channel["session"] != "seed":
  57. continue
  58. url = channel["url"]
  59. self.info.update_seed("seed", url)
  60. for channel in channels:
  61. if channel["session"] != "manual":
  62. continue
  63. url = channel["url"]
  64. self.info.update_manual("manual", url)
  65. self.update_node(name, self.info)
  66. def handle_event(self, event):
  67. name = list(event.keys())[0]
  68. values = list(event.values())[0]
  69. params = values.get("params")
  70. event = params[0].get("event")
  71. info = params[0].get("info")
  72. t = time.localtime()
  73. current_time = time.strftime("%H:%M:%S", t)
  74. match event:
  75. case "send":
  76. nano = info.get("time")
  77. cmd = info.get("cmd")
  78. chan = info.get("chan")
  79. addr = chan.get("addr")
  80. t = (dt.datetime
  81. .fromtimestamp(int(nano)/1000000000)
  82. .strftime('%H:%M:%S'))
  83. self.info.update_msg(addr, (t, event, cmd))
  84. case "recv":
  85. nano = info.get("time")
  86. cmd = info.get("cmd")
  87. chan = info.get("chan")
  88. addr = chan.get("addr")
  89. t = (dt.datetime
  90. .fromtimestamp(int(nano)/1000000000)
  91. .strftime('%H:%M:%S'))
  92. self.info.update_msg(addr, (t, event, cmd))
  93. case "inbound_connected":
  94. addr = info["addr"]
  95. id = info.get("channel_id")
  96. self.info.update_inbound(f"{id}", addr)
  97. logging.debug(f"{current_time} inbound (connect): {addr}")
  98. case "inbound_disconnected":
  99. addr = info["addr"]
  100. id = info.get("channel_id")
  101. self.info.remove_inbound(id)
  102. logging.debug(f"{current_time} inbound (disconnect): {addr}")
  103. case "outbound_slot_sleeping":
  104. slot = info["slot"]
  105. self.info.update_event((f"{name}", f"{slot}"), "sleeping")
  106. logging.debug(f"{current_time} slot {slot}: sleeping")
  107. case "outbound_slot_connecting":
  108. slot = info["slot"]
  109. addr = info["addr"]
  110. self.info.update_event((f"{name}", f"{slot}"), f"connecting: addr={addr}")
  111. logging.debug(f"{current_time} slot {slot}: connecting addr={addr}")
  112. case "outbound_slot_connected":
  113. slot = info["slot"]
  114. addr = info["addr"]
  115. channel_id = info["channel_id"]
  116. self.info.update_event((f"{name}", f"{slot}"), f"connected: addr={addr}")
  117. logging.debug(f"{current_time} slot {slot}: connected addr={addr}")
  118. case "outbound_slot_disconnected":
  119. slot = info["slot"]
  120. err = info["err"]
  121. self.info.update_event((f"{name}", f"{slot}"), f"disconnected: {err}")
  122. logging.debug(f"{current_time} slot {slot}: disconnected err='{err}'")
  123. case "outbound_peer_discovery":
  124. attempt = info["attempt"]
  125. state = info["state"]
  126. self.info.update_event((f"{name}", "outbound"), f"peer discovery: {state} (attempt {attempt})")
  127. logging.debug(f"{current_time} peer_discovery: {state} (attempt {attempt})")
  128. def __repr__(self):
  129. return f"{self.nodes}"
  130. class Info:
  131. def __init__(self):
  132. self.outbound = {}
  133. self.inbound = {}
  134. self.manual = {}
  135. self.event = {}
  136. self.seed = {}
  137. self.msgs = {}
  138. def update_outbound(self, key, value):
  139. self.outbound[key] = value
  140. def update_inbound(self, key, value):
  141. self.inbound[key] = value
  142. def remove_inbound(self, key):
  143. if key in self.inbound:
  144. del self.inbound[key]
  145. def update_manual(self, key, value):
  146. self.manual[key] = value
  147. def update_seed(self, key, value):
  148. self.seed[key] = value
  149. def update_event(self, key, value):
  150. self.event[key] = value
  151. def update_msg(self, key, value):
  152. if key in self.msgs:
  153. self.msgs[key] += [value]
  154. else:
  155. self.msgs[key] = [value]
  156. def __repr__(self):
  157. return (f"outbound: {self.outbound}"
  158. f"inbound: {self.inbound}"
  159. f"manual: {self.manual}"
  160. f"seed: {self.seed}"
  161. f"msg: {self.msgs}")