network.py 16 KB

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