network.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #!/usr/bin/env python3
  2. import random
  3. import pickle
  4. import logging
  5. from enum import Enum
  6. # Set this to True if you want the bytes sent and received to be added
  7. # symbolically, in terms of the numbers of each type of network message.
  8. # You will need sympy installed for this to work.
  9. symbolic_byte_counters = False
  10. if symbolic_byte_counters:
  11. import sympy
  12. # Network parameters
  13. # On average, how large is a consensus diff as compared to a full
  14. # consensus?
  15. P_Delta = 0.019
  16. class WOMode(Enum):
  17. """The different Walking Onion modes"""
  18. VANILLA = 0 # No Walking Onions
  19. TELESCOPING = 1 # Telescoping Walking Onions
  20. SINGLEPASS = 2 # Single-Pass Walking Onions
  21. def string_to_type(type_input):
  22. reprs = {'vanilla': WOMode.VANILLA, 'telescoping': WOMode.TELESCOPING,
  23. 'single-pass': WOMode.SINGLEPASS }
  24. if type_input in reprs.keys():
  25. return reprs[type_input]
  26. return -1
  27. class SNIPAuthMode(Enum):
  28. """The different styles of SNIP authentication"""
  29. NONE = 0 # No SNIPs; only used for WOMode = VANILLA
  30. MERKLE = 1 # Merkle trees
  31. THRESHSIG = 2 # Threshold signatures
  32. # We only need to differentiate between merkle and telescoping on the
  33. # command line input, Vanilla always takes a NONE type but nothing else
  34. # does.
  35. def string_to_type(type_input):
  36. reprs = {'merkle': SNIPAuthMode.MERKLE,
  37. 'telesocping': SNIPAuthMode.THRESHSIG }
  38. if type_input in reprs.keys():
  39. return reprs[type_input]
  40. return -1
  41. class EntType(Enum):
  42. """The different types of entities in the system."""
  43. NONE = 0
  44. DIRAUTH = 1
  45. RELAY = 2
  46. CLIENT = 3
  47. class PerfStats:
  48. """A class to store performance statistics for a relay or client.
  49. We keep track of bytes sent, bytes received, and counts of
  50. public-key operations of various types. We will reset these every
  51. epoch."""
  52. def __init__(self, ent_type):
  53. # Which type of entity is this for (DIRAUTH, RELAY, CLIENT)
  54. self.ent_type = ent_type
  55. # A printable name for the entity
  56. self.name = None
  57. self.reset()
  58. def __str__(self):
  59. return "%s: type=%s boot=%s sent=%s recv=%s keygen=%d sig=%d verif=%d dh=%d" % \
  60. (self.name, self.ent_type.name, self.is_bootstrapping, \
  61. self.bytes_sent, self.bytes_received, self.keygens, \
  62. self.sigs, self.verifs, self.dhs)
  63. def reset(self):
  64. """Reset the counters, typically at the beginning of each
  65. epoch."""
  66. # True if bootstrapping this epoch
  67. self.is_bootstrapping = False
  68. # Bytes sent and received
  69. self.bytes_sent = 0
  70. self.bytes_received = 0
  71. # Public-key operations: key generation, signing, verification,
  72. # Diffie-Hellman
  73. self.keygens = 0
  74. self.sigs = 0
  75. self.verifs = 0
  76. self.dhs = 0
  77. class NetAddr:
  78. """A class representing a network address"""
  79. nextaddr = 1
  80. def __init__(self):
  81. """Generate a fresh network address"""
  82. self.addr = NetAddr.nextaddr
  83. NetAddr.nextaddr += 1
  84. def __eq__(self, other):
  85. return (isinstance(other, self.__class__)
  86. and self.__dict__ == other.__dict__)
  87. def __hash__(self):
  88. return hash(self.addr)
  89. def __str__(self):
  90. return self.addr.__str__()
  91. class NetNoServer(Exception):
  92. """No server is listening on the address someone tried to connect
  93. to."""
  94. class Network:
  95. """A class representing a simulated network. Servers can bind()
  96. to the network, yielding a NetAddr (network address), and clients
  97. can connect() to a NetAddr yielding a Connection."""
  98. def __init__(self):
  99. self.servers = dict()
  100. self.epoch = 1
  101. self.epochcallbacks = []
  102. self.epochendingcallbacks = []
  103. self.dirauthkeylist = []
  104. self.fallbackrelays = []
  105. self.womode = WOMode.VANILLA
  106. self.snipauthmode = SNIPAuthMode.NONE
  107. def printservers(self):
  108. """Print the list of NetAddrs bound to something."""
  109. print("Servers:")
  110. for a in self.servers.keys():
  111. print(a)
  112. def setdirauthkey(self, index, vk):
  113. """Set the public verification key for dirauth number index to
  114. vk."""
  115. if index >= len(self.dirauthkeylist):
  116. self.dirauthkeylist.extend([None] * (index+1-len(self.dirauthkeylist)))
  117. self.dirauthkeylist[index] = vk
  118. def dirauthkeys(self):
  119. """Return the list of dirauth public verification keys."""
  120. return self.dirauthkeylist
  121. def getepoch(self):
  122. """Return the current epoch."""
  123. return self.epoch
  124. def nextepoch(self):
  125. """Increment the current epoch, and return it."""
  126. logging.info("Ending epoch %s", self.epoch)
  127. for c in self.epochendingcallbacks:
  128. c.epoch_ending(self.epoch)
  129. self.epoch += 1
  130. logging.info("Starting epoch %s", self.epoch)
  131. totcallbacks = len(self.epochcallbacks)
  132. lastroundpercent = -1
  133. for i, c in enumerate(self.epochcallbacks):
  134. c.newepoch(self.epoch)
  135. roundpercent = int(100*(i+1)/totcallbacks)
  136. if roundpercent != lastroundpercent:
  137. logging.info("%d%% complete", roundpercent)
  138. lastroundpercent = roundpercent
  139. logging.info("Epoch %s started", self.epoch)
  140. return self.epoch
  141. def wantepochticks(self, callback, want, end=False):
  142. """Register or deregister an object from receiving epoch change
  143. callbacks. If want is True, the callback object's newepoch()
  144. method will be called at each epoch change, with an argument of
  145. the new epoch. If want if False, the callback object will be
  146. deregistered. If end is True, the callback object's
  147. epoch_ending() method will be called instead at the end of the
  148. epoch, just _before_ the epoch number change."""
  149. if end:
  150. if want:
  151. self.epochendingcallbacks.append(callback)
  152. else:
  153. self.epochendingcallbacks.remove(callback)
  154. else:
  155. if want:
  156. self.epochcallbacks.append(callback)
  157. else:
  158. self.epochcallbacks.remove(callback)
  159. def bind(self, server):
  160. """Bind a server to a newly generated NetAddr, returning the
  161. NetAddr. The server's bound() callback will also be invoked."""
  162. addr = NetAddr()
  163. self.servers[addr] = server
  164. server.bound(addr, lambda: self.servers.pop(addr))
  165. return addr
  166. def connect(self, client, srvaddr, perfstats):
  167. """Connect the given client to the server bound to addr. Throw
  168. an exception if there is no server bound to that address."""
  169. try:
  170. server = self.servers[srvaddr]
  171. except KeyError:
  172. raise NetNoServer()
  173. conn = server.connected(client)
  174. conn.perfstats = perfstats
  175. return conn
  176. def setfallbackrelays(self, fallbackrelays):
  177. """Set the list of globally known fallback relays. Clients use
  178. these to bootstrap when they know no other relays."""
  179. self.fallbackrelays = fallbackrelays
  180. def getfallbackrelays(self):
  181. """Get the list of globally known fallback relays. Clients use
  182. these to bootstrap when they know no other relays."""
  183. return self.fallbackrelays
  184. def set_wo_style(self, womode, snipauthmode):
  185. """Set the Walking Onions mode and the SNIP authenticate mode
  186. for the network."""
  187. if ((womode == WOMode.VANILLA) \
  188. and (snipauthmode != SNIPAuthMode.NONE)) or \
  189. ((womode != WOMode.VANILLA) and \
  190. (snipauthmode == SNIPAuthMode.NONE)):
  191. # Incompatible settings
  192. raise ValueError("Bad argument combination")
  193. self.womode = womode
  194. self.snipauthmode = snipauthmode
  195. # The singleton instance of Network
  196. thenetwork = Network()
  197. class NetMsg:
  198. """The parent class of network messages. Subclass this class to
  199. implement specific kinds of network messages."""
  200. def size(self):
  201. """Return the size of this network message. For now, just
  202. pickle it and return the length of that. There's some
  203. unnecessary overhead in this method; if you want specific
  204. messages to have more accurate sizes, override this method in
  205. the subclass. Alternately, if symbolic_byte_counters is set,
  206. return a symbolic representation of the message size instead, so
  207. that the total byte counts will clearly show how many of each
  208. message type were sent and received."""
  209. if symbolic_byte_counters:
  210. sz = sympy.symbols(type(self).__name__)
  211. else:
  212. sz = len(pickle.dumps(self))
  213. return sz
  214. class StringNetMsg(NetMsg):
  215. """Send an arbitratry string as a NetMsg."""
  216. def __init__(self, data):
  217. self.data = data
  218. def __str__(self):
  219. return self.data.__str__()
  220. class Connection:
  221. def __init__(self, peer = None):
  222. """Create a Connection object with the given peer."""
  223. self.peer = peer
  224. def closed(self):
  225. logging.debug("connection closed with %s", self.peer)
  226. self.peer = None
  227. def close(self):
  228. logging.debug("closing connection with %s", self.peer)
  229. self.peer.closed()
  230. self.peer = None
  231. class ClientConnection(Connection):
  232. """The parent class of client-side network connections. Subclass
  233. this class to do anything more elaborate than just passing arbitrary
  234. NetMsgs, which then get ignored. Use subclasses of this class when
  235. the server required no per-connection state, such as just fetching
  236. consensus documents."""
  237. def __init__(self, peer):
  238. """Create a ClientConnection object with the given peer. The
  239. peer must have a received(client, msg) method."""
  240. self.peer = peer
  241. self.perfstats = None
  242. def sendmsg(self, netmsg):
  243. assert(isinstance(netmsg, NetMsg))
  244. msgsize = netmsg.size()
  245. self.perfstats.bytes_sent += msgsize
  246. self.peer.received(self, netmsg)
  247. def reply(self, netmsg):
  248. assert(isinstance(netmsg, NetMsg))
  249. msgsize = netmsg.size()
  250. self.perfstats.bytes_received += msgsize
  251. self.receivedfromserver(netmsg)
  252. class ServerConnection(Connection):
  253. """The parent class of server-side network connections."""
  254. def __init__(self):
  255. self.peer = None
  256. def sendmsg(self, netmsg):
  257. assert(isinstance(netmsg, NetMsg))
  258. self.peer.received(netmsg)
  259. def received(self, client, netmsg):
  260. logging.debug("received %s from client %s", netmsg, client)
  261. class Server:
  262. """The parent class of network servers. Subclass this class to
  263. implement servers of different kinds. You will probably only need
  264. to override the implementation of connected()."""
  265. def __init__(self, name):
  266. self.name = name
  267. def __str__(self):
  268. return self.name.__str__()
  269. def bound(self, netaddr, closer):
  270. """Callback invoked when the server is successfully bound to a
  271. NetAddr. The parameters are the netaddr to which the server is
  272. bound and closer (as in a thing that causes something to close)
  273. is a callback function that should be used when the server
  274. wishes to stop listening for new connections."""
  275. self.closer = closer
  276. def close(self):
  277. """Stop listening for new connections."""
  278. self.closer()
  279. def connected(self, client):
  280. """Callback invoked when a client connects to this server.
  281. This callback must create the Connection object that will be
  282. returned to the client."""
  283. logging.debug("server %s connected to client %s", self, client)
  284. serverconnection = ServerConnection()
  285. clientconnection = ClientConnection(serverconnection)
  286. serverconnection.peer = clientconnection
  287. return clientconnection
  288. if __name__ == '__main__':
  289. n1 = NetAddr()
  290. n2 = NetAddr()
  291. assert(n1 == n1)
  292. assert(not (n1 == n2))
  293. assert(n1 != n2)
  294. print(n1, n2)
  295. # Initialize the (non-cryptographic) random seed
  296. random.seed(1)
  297. srv = Server("hello world server")
  298. thenetwork.printservers()
  299. a = thenetwork.bind(srv)
  300. thenetwork.printservers()
  301. print("in main", a)
  302. perfstats = PerfStats(EntType.NONE)
  303. conn = thenetwork.connect("hello world client", a, perfstats)
  304. conn.sendmsg(StringNetMsg("hi"))
  305. conn.close()
  306. srv.close()
  307. thenetwork.printservers()