network.py 6.9 KB

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