network.py 14 KB

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