network.py 16 KB

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