network.py 16 KB

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