network.py 8.6 KB

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