network.py 6.6 KB

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