network.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #!/usr/bin/env python3
  2. import random
  3. class NetAddr:
  4. """A class representing a network address"""
  5. nextaddr = 1
  6. def __init__(self):
  7. """Generate a fresh network address"""
  8. self.addr = NetAddr.nextaddr
  9. NetAddr.nextaddr += 1
  10. def __eq__(self, other):
  11. return (isinstance(other, self.__class__)
  12. and self.__dict__ == other.__dict__)
  13. def __hash__(self):
  14. return hash(self.addr)
  15. def __str__(self):
  16. return self.addr.__str__()
  17. class Network:
  18. """A class representing a simulated network. Servers can bind()
  19. to the network, yielding a NetAddr (network address), and clients
  20. can connect() to a NetAddr yielding a Connection."""
  21. def __init__(self):
  22. self.servers = dict()
  23. self.epoch = 1
  24. self.epochcallbacks = []
  25. self.epochendingcallbacks = []
  26. self.dirauthkeylist = []
  27. self.fallbackrelays = []
  28. def printservers(self):
  29. """Print the list of NetAddrs bound to something."""
  30. print("Servers:")
  31. for a in self.servers.keys():
  32. print(a)
  33. def setdirauthkey(self, index, vk):
  34. """Set the public verification key for dirauth number index to
  35. vk."""
  36. if index >= len(self.dirauthkeylist):
  37. self.dirauthkeylist.extend([None] * (index+1-len(self.dirauthkeylist)))
  38. self.dirauthkeylist[index] = vk
  39. def dirauthkeys(self):
  40. """Return the list of dirauth public verification keys."""
  41. return self.dirauthkeylist
  42. def getepoch(self):
  43. """Return the current epoch."""
  44. return self.epoch
  45. def nextepoch(self):
  46. """Increment the current epoch, and return it."""
  47. for c in self.epochendingcallbacks:
  48. c.epoch_ending(self.epoch)
  49. self.epoch += 1
  50. for c in self.epochcallbacks:
  51. c.newepoch(self.epoch)
  52. return self.epoch
  53. def wantepochticks(self, callback, want, end=False):
  54. """Register or deregister an object from receiving epoch change
  55. callbacks. If want is True, the callback object's newepoch()
  56. method will be called at each epoch change, with an argument of
  57. the new epoch. If want if False, the callback object will be
  58. deregistered. If end is True, the callback object's
  59. epoch_ending() method will be called instead at the end of the
  60. epoch, just _before_ the epoch number change."""
  61. if end:
  62. if want:
  63. self.epochendingcallbacks.append(callback)
  64. else:
  65. self.epochendingcallbacks.remove(callback)
  66. else:
  67. if want:
  68. self.epochcallbacks.append(callback)
  69. else:
  70. self.epochcallbacks.remove(callback)
  71. def bind(self, server):
  72. """Bind a server to a newly generated NetAddr, returning the
  73. NetAddr. The server's bound() callback will also be invoked."""
  74. addr = NetAddr()
  75. self.servers[addr] = server
  76. server.bound(addr, lambda: self.servers.pop(addr))
  77. return addr
  78. def connect(self, client, srvaddr):
  79. """Connect the given client to the server bound to addr. Throw
  80. an exception if there is no server bound to that address."""
  81. server = self.servers[srvaddr]
  82. return server.connected(client)
  83. def setfallbackrelays(self, fallbackrelays):
  84. """Set the list of globally known fallback relays. Clients use
  85. these to bootstrap when they know no other relays."""
  86. self.fallbackrelays = fallbackrelays
  87. def getfallbackrelays(self):
  88. """Get the list of globally known fallback relays. Clients use
  89. these to bootstrap when they know no other relays."""
  90. return self.fallbackrelays
  91. # The singleton instance of Network
  92. thenetwork = Network()
  93. # Initialize the (non-cryptographic) random seed
  94. random.seed(1)
  95. class NetMsg:
  96. """The parent class of network messages. Subclass this class to
  97. implement specific kinds of network messages."""
  98. class StringNetMsg(NetMsg):
  99. """Send an arbitratry string as a NetMsg."""
  100. def __init__(self, str):
  101. self.data = str
  102. def __str__(self):
  103. return self.data.__str__()
  104. class Connection:
  105. def __init__(self, peer = None):
  106. """Create a Connection object with the given peer."""
  107. self.peer = peer
  108. def closed(self):
  109. print("connection closed with", self.peer)
  110. self.peer = None
  111. def close(self):
  112. print("closing connection with", self.peer)
  113. self.peer.closed()
  114. self.peer = None
  115. class ClientConnection(Connection):
  116. """The parent class of client-side network connections. Subclass
  117. this class to do anything more elaborate than just passing arbitrary
  118. NetMsgs, which then get ignored. Use subclasses of this class when
  119. the server required no per-connection state, such as just fetching
  120. consensus documents."""
  121. def __init__(self, peer):
  122. """Create a ClientConnection object with the given peer. The
  123. peer must have a received(client, msg) method."""
  124. self.peer = peer
  125. def sendmsg(self, netmsg):
  126. assert(isinstance(netmsg, NetMsg))
  127. self.peer.received(self, netmsg)
  128. def reply(self, netmsg):
  129. assert(isinstance(netmsg, NetMsg))
  130. self.receivedfromserver(netmsg)
  131. def received(self, netmsg):
  132. print("received", netmsg, "from server")
  133. class ServerConnection(Connection):
  134. """The parent class of server-side network connections."""
  135. def __init__(self):
  136. self.peer = None
  137. def sendmsg(self, netmsg):
  138. assert(isinstance(netmsg, NetMsg))
  139. self.peer.received(netmsg)
  140. def received(self, client, netmsg):
  141. print("received", netmsg, "from client", client)
  142. class Server:
  143. """The parent class of network servers. Subclass this class to
  144. implement servers of different kinds. You will probably only need
  145. to override the implementation of connected()."""
  146. def __init__(self, name):
  147. self.name = name
  148. def __str__(self):
  149. return self.name.__str__()
  150. def bound(self, netaddr, closer):
  151. """Callback invoked when the server is successfully bound to a
  152. NetAddr. The parameters are the netaddr to which the server is
  153. bound and closer (as in a thing that causes something to close)
  154. is a callback function that should be used when the server
  155. wishes to stop listening for new connections."""
  156. self.closer = closer
  157. def close(self):
  158. """Stop listening for new connections."""
  159. self.closer()
  160. def connected(self, client):
  161. """Callback invoked when a client connects to this server.
  162. This callback must create the Connection object that will be
  163. returned to the client."""
  164. print("server", self, "conected to client", client)
  165. serverconnection = ServerConnection()
  166. clientconnection = ClientConnection(serverconnection)
  167. serverconnection.peer = clientconnection
  168. return clientconnection
  169. if __name__ == '__main__':
  170. n1 = NetAddr()
  171. n2 = NetAddr()
  172. assert(n1 == n1)
  173. assert(not (n1 == n2))
  174. assert(n1 != n2)
  175. print(n1, n2)
  176. srv = Server("hello world server")
  177. thenetwork.printservers()
  178. a = thenetwork.bind(srv)
  179. thenetwork.printservers()
  180. print("in main", a)
  181. conn = thenetwork.connect("hello world client", a)
  182. conn.sendmsg(StringNetMsg("hi"))
  183. conn.close()
  184. srv.close()
  185. thenetwork.printservers()