network.py 16 KB

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