network.py 7.9 KB

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