client.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import sys
  5. import logging
  6. import network
  7. import dirauth
  8. import relay
  9. import nacl.hash
  10. class VanillaCreatedExtendedHandler:
  11. """A handler for VanillaCreatedCircuitCell and
  12. VanillaExtendedCircuitCell cells."""
  13. def __init__(self, channelmgr, ntor, expecteddesc):
  14. self.channelmgr = channelmgr
  15. self.ntor = ntor
  16. self.expecteddesc = expecteddesc
  17. self.onionkey = expecteddesc.descdict['onionkey']
  18. self.idkey = expecteddesc.descdict['idkey']
  19. def received_cell(self, circhandler, cell):
  20. secret = self.ntor.verify(cell.ntor_reply, self.onionkey, self.idkey)
  21. enckey = nacl.hash.sha256(secret + b'upstream')
  22. deckey = nacl.hash.sha256(secret + b'downstream')
  23. circhandler.add_crypt_layer(enckey, deckey)
  24. if len(circhandler.circuit_descs) == 0:
  25. # This was a VanillaCreatedCircuitCell
  26. circhandler.replace_celltype_handler(
  27. relay.VanillaCreatedCircuitCell, None)
  28. else:
  29. # This was a VanillaExtendedCircuitCell
  30. circhandler.replace_celltype_handler(
  31. relay.VanillaExtendedCircuitCell, None)
  32. circhandler.circuit_descs.append(self.expecteddesc)
  33. # Are we done building the circuit?
  34. if len(circhandler.circuit_descs) == 3:
  35. # Yes!
  36. return
  37. nexthop = None
  38. while nexthop is None:
  39. nexthop = self.channelmgr.relaypicker.pick_weighted_relay()
  40. if nexthop.descdict['addr'] in \
  41. [ desc.descdict['addr'] \
  42. for desc in circhandler.circuit_descs ]:
  43. nexthop = None
  44. # Construct the VanillaExtendCircuitCell
  45. ntor = relay.NTor(self.channelmgr.perfstats)
  46. ntor_request = ntor.request()
  47. circextendmsg = relay.VanillaExtendCircuitCell(
  48. nexthop.descdict['addr'], ntor_request)
  49. # Set up the reply handler
  50. circhandler.replace_celltype_handler(
  51. relay.VanillaExtendedCircuitCell,
  52. VanillaCreatedExtendedHandler(self.channelmgr, ntor, nexthop))
  53. # Send the cell
  54. circhandler.send_cell(circextendmsg)
  55. class TelescopingCreatedHandler:
  56. """A handler for TelescopingCreatedCircuitCell cells; this will only always
  57. communicate with the client's guard."""
  58. def __init__(self, channelmgr, ntor):
  59. self.channelmgr = channelmgr
  60. self.ntor = ntor
  61. self.onionkey = self.channelmgr.guard.snipdict['onionkey']
  62. self.idkey = self.channelmgr.guard.snipdict['idkey']
  63. def received_cell(self, circhandler, cell):
  64. logging.debug("Received cell in TelescopingCreatedHandler")
  65. secret = self.ntor.verify(cell.ntor_reply, self.onionkey, self.idkey)
  66. enckey = nacl.hash.sha256(secret + b'upstream')
  67. deckey = nacl.hash.sha256(secret + b'downstream')
  68. circhandler.add_crypt_layer(enckey, deckey)
  69. circhandler.replace_celltype_handler(relay.TelescopingCreatedCircuitCell, None)
  70. circhandler.circuit_descs.append(self.channelmgr.guard)
  71. nexthopidx = None
  72. while nexthopidx is None:
  73. nexthopidx = self.channelmgr.relaypicker.pick_weighted_relay_index()
  74. #print("WARNING: Unimplemented! Need to check if this idx is in the list of circhandlers idxs")
  75. # TODO verify we don't need to do the above
  76. # Construct the TelescopingExtendCircuitCell
  77. ntor = relay.NTor(self.channelmgr.perfstats)
  78. ntor_request = ntor.request()
  79. circextendmsg = relay.TelescopingExtendCircuitCell(
  80. nexthopidx, ntor_request)
  81. # Set up the reply handler
  82. circhandler.replace_celltype_handler(
  83. relay.TelescopingExtendedCircuitCell,
  84. TelescopingExtendedHandler(self.channelmgr, ntor))
  85. # Send the cell
  86. circhandler.send_cell(circextendmsg)
  87. class TelescopingExtendedHandler:
  88. """A handler for TelescopingExtendedCircuitCell cells."""
  89. def __init__(self, channelmgr, ntor):
  90. self.channelmgr = channelmgr
  91. self.ntor = ntor
  92. def received_cell(self, circhandler, cell):
  93. logging.debug("Received cell in TelescopingExtendedHandler")
  94. # Validate the SNIP
  95. dirauth.SNIP.verify(cell.snip, self.channelmgr.consensus,
  96. network.thenetwork.dirauthkeys()[0],
  97. self.channelmgr.perfstats)
  98. onionkey = cell.snip.snipdict['onionkey']
  99. idkey = cell.snip.snipdict['idkey']
  100. secret = self.ntor.verify(cell.ntor_reply, onionkey, idkey)
  101. enckey = nacl.hash.sha256(secret + b'upstream')
  102. deckey = nacl.hash.sha256(secret + b'downstream')
  103. circhandler.add_crypt_layer(enckey, deckey)
  104. circhandler.replace_celltype_handler(
  105. relay.TelescopingExtendedCircuitCell, None)
  106. circhandler.circuit_descs.append(cell.snip)
  107. # Are we done building the circuit?
  108. logging.warning("we may need another circhandler structure for snips")
  109. if len(circhandler.circuit_descs) == 3:
  110. logging.debug("Circuit [%s] is long enough; exiting.", [str(x.snipdict['addr']) for x in circhandler.circuit_descs])
  111. # Yes!
  112. return
  113. nexthopidx = None
  114. guardrange = circhandler.circuit_descs[0].snipdict["range"]
  115. while nexthopidx is None:
  116. # Relays make sure that when the extend to a relay, they are not
  117. # extending to themselves. So here, we just need to make sure that
  118. # this ID is not the same as the guard ID, to protect against the
  119. # guard and exit being the same relay
  120. nexthopidx = self.channelmgr.relaypicker.pick_weighted_relay_index()
  121. if guardrange[0] <= nexthopidx and nexthopidx < guardrange[1]:
  122. # We've picked this relay already. Try again.
  123. nexthopidx = None
  124. # Construct the VanillaExtendCircuitCell
  125. ntor = relay.NTor(self.channelmgr.perfstats)
  126. ntor_request = ntor.request()
  127. circextendmsg = relay.TelescopingExtendCircuitCell(
  128. nexthopidx, ntor_request)
  129. # Set up the reply handler
  130. circhandler.replace_celltype_handler(
  131. relay.TelescopingExtendedCircuitCell,
  132. TelescopingExtendedHandler(self.channelmgr, ntor))
  133. # Send the cell
  134. circhandler.send_cell(circextendmsg)
  135. class SinglePassCreatedHandler:
  136. """A handler for SinglePassCreatedCircuitCell cells."""
  137. def __init__(self, channelmgr, ntor, client_key):
  138. self.channelmgr = channelmgr
  139. self.ntor = ntor
  140. self.client_key = client_key
  141. def received_cell(self, circhandler, cell):
  142. logging.debug("Received cell in SinglePassCreatedHandler")
  143. sys.exit("not yet implemented")
  144. class ClientChannelManager(relay.ChannelManager):
  145. """The subclass of ChannelManager for clients."""
  146. def __init__(self, myaddr, dirauthaddrs, perfstats):
  147. super().__init__(myaddr, dirauthaddrs, perfstats)
  148. self.guardaddr = None
  149. self.guard = None
  150. def get_consensus_from_fallbackrelay(self):
  151. """Download a fresh consensus from a random fallbackrelay."""
  152. fb = network.thenetwork.getfallbackrelay()
  153. logging.debug("Chose fallback %s", fb)
  154. if network.thenetwork.womode == network.WOMode.VANILLA:
  155. if self.consensus is not None and \
  156. len(self.consensus.consdict['relays']) > 0:
  157. self.send_msg(relay.RelayGetConsensusDiffMsg(), fb.netaddr)
  158. else:
  159. self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
  160. else:
  161. self.send_msg(relay.RelayGetConsensusMsg(), fb.netaddr)
  162. def ensure_guard_vanilla(self):
  163. """Ensure that we have a channel to a guard (Vanilla Onion
  164. Routing version)."""
  165. while True:
  166. if self.guardaddr is None:
  167. # Pick a guard from the consensus
  168. self.guard = self.relaypicker.pick_weighted_relay()
  169. self.guardaddr = self.guard.descdict['addr']
  170. self.test_guard_connection()
  171. if self.guardaddr is not None:
  172. break
  173. logging.debug('chose guard=%s', self.guardaddr)
  174. def test_guard_connection(self):
  175. # Connect to the guard
  176. try:
  177. self.get_channel_to(self.guardaddr)
  178. except network.NetNoServer:
  179. # Our guard is gone
  180. self.guardaddr = None
  181. self.guard = None
  182. def ensure_guard_walking_onions(self):
  183. """Ensure we have a channel to a guard (Walking Onions version).
  184. For the first implementation, we assume an out-of-band mechanism
  185. that just simply hands us a guard; we don't count the number of
  186. operations or bandwidth as this operation in practice occurs
  187. infrequently."""
  188. while True:
  189. if self.guardaddr is None:
  190. #randomly-sample a guard
  191. logging.warning("Unimplemented! guard should be selected from any relays.")
  192. self.guard = self.relaypicker.pick_weighted_relay()
  193. # here, we have a SNIP instead of a relay descriptor
  194. self.guardaddr = self.guard.snipdict['addr']
  195. self.test_guard_connection()
  196. if self.guardaddr is not None:
  197. break
  198. logging.debug('chose guard=%s', self.guardaddr)
  199. def ensure_guard(self):
  200. """Ensure that we have a channel to a guard."""
  201. if network.thenetwork.womode == network.WOMode.VANILLA:
  202. self.ensure_guard_vanilla()
  203. return
  204. # At this point, we are either in Telescoping or Single-Pass mode
  205. self.ensure_guard_walking_onions()
  206. def new_circuit_vanilla(self):
  207. """Create a new circuit from this client. (Vanilla Onion Routing
  208. version)"""
  209. # Get our channel to the guard
  210. guardchannel = self.get_channel_to(self.guardaddr)
  211. # Allocate a new circuit id on it
  212. circid, circhandler = guardchannel.new_circuit()
  213. # Construct the VanillaCreateCircuitMsg
  214. ntor = relay.NTor(self.perfstats)
  215. ntor_request = ntor.request()
  216. circcreatemsg = relay.VanillaCreateCircuitMsg(circid, ntor_request)
  217. # Set up the reply handler
  218. circhandler.replace_celltype_handler(
  219. relay.VanillaCreatedCircuitCell,
  220. VanillaCreatedExtendedHandler(self, ntor, self.guard))
  221. # Send the message
  222. guardchannel.send_msg(circcreatemsg)
  223. return circhandler
  224. def new_circuit_telescoping(self):
  225. """Create a new circuit from this client (Telescoping Walking Onions
  226. version). If an error occurs and the circuit is deleted from the guard
  227. channel, return None, otherwise, return the circuit handler."""
  228. # Get our channel to the guard
  229. guardchannel = self.get_channel_to(self.guardaddr)
  230. # Allocate a new circuit id on it
  231. circid, circhandler = guardchannel.new_circuit()
  232. # Construct the TelescopingCreateCircuitMsg
  233. ntor = relay.NTor(self.perfstats)
  234. ntor_request = ntor.request()
  235. circcreatemsg = relay.TelescopingCreateCircuitMsg(circid, ntor_request)
  236. # Set up the reply handler
  237. circhandler.replace_celltype_handler(
  238. relay.TelescopingCreatedCircuitCell,
  239. TelescopingCreatedHandler(self, ntor))
  240. # Send the message
  241. guardchannel.send_msg(circcreatemsg)
  242. # Check to make sure the circuit is open before sending it- if there
  243. # was an error when establishing it, the circuit could already be
  244. # closed.
  245. if not guardchannel.is_circuit_open(circid):
  246. logging.debug("Circuit was already closed, not sending bytes. circid: " + str(circid))
  247. return None
  248. # In Telescoping Walking Onions, it should never happen that the
  249. # guard and exit are the same node, as the
  250. # TelescopingExtendedHandler takes care to not pick an index for
  251. # the exit that matches the guard's range. So this test should
  252. # never trigger. In Single-Pass Walking Onions, however, the
  253. # equivalent test is needed here (but should just log a debug,
  254. # not an error, since the client cannot control the index value
  255. # selected for the exit.
  256. if circhandler.circuit_descs[0].snipdict["addr"] == \
  257. circhandler.circuit_descs[2].snipdict["addr"]:
  258. logging.error("CIRCUIT IN A LOOP")
  259. circhandler.close()
  260. circhandler = None
  261. return circhandler
  262. def new_circuit_singlepass(self):
  263. """Create a new circuit from this client (Single-Pass Walking Onions
  264. version). If an error occurs and the circuit is deleted from the guard
  265. channel, return None, otherwise, return the circuit handler."""
  266. # Get our channel to the guard
  267. guardchannel = self.get_channel_to(self.guardaddr)
  268. # Allocate a new circuit id on it
  269. circid, circhandler = guardchannel.new_circuit()
  270. # first, create the path-selection key used for Sphinx
  271. client_pathsel_key = nacl.public.PrivateKey.generate()
  272. self.perfstats.keygens += 1
  273. # Construct the SinglePassCreateCircuitMsg
  274. ntor = relay.NTor(self.perfstats)
  275. ntor_request = ntor.request()
  276. circcreatemsg = relay.SinglePassCreateCircuitMsg(circid, ntor_request,
  277. client_pathsel_key.public_key)
  278. # Set up the reply handler
  279. circhandler.replace_celltype_handler(
  280. relay.SinglePassCreatedCircuitCell,
  281. SinglePassCreatedHandler(self, ntor, client_pathsel_key))
  282. # Send the message
  283. guardchannel.send_msg(circcreatemsg)
  284. # Check to make sure the circuit is open before sending it- if there
  285. # was an error when establishing it, the circuit could already be
  286. # closed.
  287. if not guardchannel.is_circuit_open(circid):
  288. logging.debug("Circuit was already closed, not sending bytes. circid: " + str(circid))
  289. return None
  290. # In Single-Pass Walking Onions, we need to check whether the
  291. # circuit got into a loop (guard equals exit); each node will
  292. # refuse to extend to itself, so this is the only possible loop
  293. # in a circuit of length 3
  294. if circhandler.circuit_descs[0].snipdict["addr"] == \
  295. circhandler.circuit_descs[2].snipdict["addr"]:
  296. logging.debug("circuit in a loop")
  297. circhandler.close()
  298. circhandler = None
  299. return circhandler
  300. def new_circuit(self):
  301. """Create a new circuit from this client."""
  302. circhandler = None
  303. # If an error occured, circhandler will still be None, so we should
  304. # try again.
  305. while circhandler is None:
  306. if network.thenetwork.womode == network.WOMode.VANILLA:
  307. circhandler = self.new_circuit_vanilla()
  308. elif network.thenetwork.womode == network.WOMode.TELESCOPING:
  309. circhandler = self.new_circuit_telescoping()
  310. elif network.thenetwork.womode == network.WOMode.SINGLEPASS:
  311. circhandler = self.new_circuit_singlepass()
  312. return circhandler
  313. def received_msg(self, msg, peeraddr, channel):
  314. """Callback when a NetMsg not specific to a circuit is
  315. received."""
  316. logging.debug("Client %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  317. if isinstance(msg, relay.RelayConsensusMsg) or \
  318. isinstance(msg, relay.RelayConsensusDiffMsg):
  319. self.relaypicker = dirauth.Consensus.verify(msg.consensus,
  320. network.thenetwork.dirauthkeys(), self.perfstats)
  321. self.consensus = msg.consensus
  322. else:
  323. return super().received_msg(msg, peeraddr, channel)
  324. def received_cell(self, circid, cell, peeraddr, channel):
  325. """Callback with a circuit-specific cell is received."""
  326. logging.debug("Client %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  327. if isinstance(msg, relay.CloseCell):
  328. logging.debug("Log: Client received close cell; closing circuit")
  329. # TODO close cell
  330. return super().received_cell(circid, cell, peeraddr, channel)
  331. class Client:
  332. """A class representing a Tor client."""
  333. def __init__(self, dirauthaddrs):
  334. # Get a network address for client-side use only (do not bind it
  335. # to the network)
  336. self.netaddr = network.NetAddr()
  337. self.perfstats = network.PerfStats(network.EntType.CLIENT)
  338. self.perfstats.name = "Client at %s" % self.netaddr
  339. self.perfstats.is_bootstrapping = True
  340. self.channelmgr = ClientChannelManager(self.netaddr, dirauthaddrs,
  341. self.perfstats)
  342. # Register for epoch tick notifications
  343. network.thenetwork.wantepochticks(self, True)
  344. def terminate(self):
  345. """Quit this client."""
  346. # Stop listening for epoch ticks
  347. network.thenetwork.wantepochticks(self, False)
  348. # Close relay connections
  349. self.channelmgr.terminate()
  350. def get_consensus(self):
  351. """Fetch a new consensus."""
  352. # We're going to want a new consensus from our guard. In order
  353. # to get that, we'll need a channel to our guard. In order to
  354. # get that, we'll need a guard address. In order to get that,
  355. # we'll need a consensus (uh, oh; in that case, fetch the
  356. # consensus from a fallback relay).
  357. guardaddr = self.channelmgr.guardaddr
  358. guardchannel = None
  359. if guardaddr is not None:
  360. try:
  361. guardchannel = self.channelmgr.get_channel_to(guardaddr)
  362. except network.NetNoServer:
  363. guardaddr = None
  364. if guardchannel is None:
  365. logging.debug("In bootstrapping mode")
  366. self.channelmgr.get_consensus_from_fallbackrelay()
  367. logging.debug('client consensus=%s', self.channelmgr.consensus)
  368. return
  369. if network.thenetwork.womode == network.WOMode.VANILLA:
  370. if self.channelmgr.consensus is not None and len(self.channelmgr.consensus.consdict['relays']) > 0:
  371. guardchannel.send_msg(relay.RelayGetConsensusDiffMsg())
  372. logging.debug('got consensus diff, client consensus=%s', self.channelmgr.consensus)
  373. return
  374. # At this point, we are in one of the following scenarios:
  375. # 1. This is a walking onions protocol, and the client fetches the
  376. # complete consensus each epoch
  377. # 2. This is Vanilla Onion Routing and the client doesn't have a
  378. # consensus and needs to bootstrap it.
  379. guardchannel.send_msg(relay.RelayGetConsensusMsg())
  380. logging.debug('client consensus=%s', self.channelmgr.consensus)
  381. def newepoch(self, epoch):
  382. """Callback that fires at the start of each epoch"""
  383. # We'll need a new consensus
  384. self.get_consensus()
  385. # If we don't have a guard, pick one and make a channel to it
  386. self.channelmgr.ensure_guard()
  387. if __name__ == '__main__':
  388. perfstats = network.PerfStats(network.EntType.NONE)
  389. totsent = 0
  390. totrecv = 0
  391. dirasent = 0
  392. dirarecv = 0
  393. relaysent = 0
  394. relayrecv = 0
  395. clisent = 0
  396. clirecv = 0
  397. if len(sys.argv) < 3:
  398. print("Must pass in network mode and snip auth mode!")
  399. print("Network options are vanilla, telescoping, or single-pass.")
  400. print("SNIP auth options are merkle or threshold.")
  401. sys.exit(0)
  402. logging.basicConfig(level=logging.DEBUG)
  403. network_mode = network.WOMode.string_to_type(sys.argv[1])
  404. if network_mode == -1:
  405. print("Not a valid network mode: " + network_mode)
  406. sys.exit(0)
  407. snipauth_mode = network.SNIPAuthMode.string_to_type(sys.argv[2])
  408. if network_mode == -1:
  409. print("Not a valid SNIP authentication mode: " + snipauth_mode)
  410. sys.exit(0)
  411. # Initialize the (non-cryptographic) random seed
  412. random.seed(1)
  413. if network_mode == network.WOMode.VANILLA:
  414. network.thenetwork.set_wo_style(network.WOMode.VANILLA,
  415. network.SNIPAuthMode.NONE)
  416. elif network_mode == network.WOMode.TELESCOPING:
  417. if snipauth_mode == network.SNIPAuthMode.MERKLE:
  418. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  419. network.SNIPAuthMode.MERKLE)
  420. else:
  421. network.thenetwork.set_wo_style(network.WOMode.TELESCOPING,
  422. network.SNIPAuthMode.THRESHSIG)
  423. elif network_mode == network.WOMode.SINGLEPASS:
  424. if snipauth_mode == network.SNIPAuthMode.MERKLE:
  425. network.thenetwork.set_wo_style(network.WOMode.SINGLEPASS,
  426. network.SNIPAuthMode.MERKLE)
  427. else:
  428. network.thenetwork.set_wo_style(network.WOMode.SINGLEPASS,
  429. network.SNIPAuthMode.THRESHSIG)
  430. else:
  431. sys.exit("Received unsupported network mode, exiting.")
  432. # Start some dirauths
  433. numdirauths = 9
  434. dirauthaddrs = []
  435. dirauths = []
  436. for i in range(numdirauths):
  437. dira = dirauth.DirAuth(i, numdirauths)
  438. dirauths.append(dira)
  439. dirauthaddrs.append(dira.netaddr)
  440. # Start some relays
  441. numrelays = 10
  442. relays = []
  443. for i in range(numrelays):
  444. # Relay bandwidths (at least the ones fast enough to get used)
  445. # in the live Tor network (as of Dec 2019) are well approximated
  446. # by (200000-(200000-25000)/3*log10(x)) where x is a
  447. # uniform integer in [1,2500]
  448. x = random.randint(1,2500)
  449. bw = int(200000-(200000-25000)/3*math.log10(x))
  450. relays.append(relay.Relay(dirauthaddrs, bw, 0))
  451. # The fallback relays are a hardcoded list of about 5% of the
  452. # relays, used by clients for bootstrapping
  453. numfallbackrelays = int(numrelays * 0.05) + 1
  454. fallbackrelays = random.sample(relays, numfallbackrelays)
  455. for r in fallbackrelays:
  456. r.set_is_fallbackrelay()
  457. network.thenetwork.setfallbackrelays(fallbackrelays)
  458. # Tick the epoch
  459. network.thenetwork.nextepoch()
  460. dirauth.Consensus.verify(dirauth.DirAuth.consensus, network.thenetwork.dirauthkeys(), perfstats)
  461. print('ticked; epoch=', network.thenetwork.getepoch())
  462. relays[3].channelmgr.send_msg(relay.RelayRandomHopMsg(30), relays[5].netaddr)
  463. # See what channels exist and do a consistency check
  464. for r in relays:
  465. print("%s: %s" % (r.netaddr, [ str(k) for k in r.channelmgr.channels.keys()]))
  466. raddr = r.netaddr
  467. for ad, ch in r.channelmgr.channels.items():
  468. if ch.peer.channelmgr.myaddr != ad:
  469. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  470. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  471. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  472. # Start some clients
  473. numclients = 1
  474. clients = []
  475. for i in range(numclients):
  476. clients.append(Client(dirauthaddrs))
  477. # Tick the epoch
  478. network.thenetwork.nextepoch()
  479. # See what channels exist and do a consistency check
  480. for c in clients:
  481. print("%s: %s" % (c.netaddr, [ str(k) for k in c.channelmgr.channels.keys()]))
  482. caddr = c.netaddr
  483. for ad, ch in c.channelmgr.channels.items():
  484. if ch.peer.channelmgr.myaddr != ad:
  485. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  486. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  487. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  488. # Pick a bunch of bw-weighted random relays and look at the
  489. # distribution
  490. for i in range(100):
  491. r = relays[0].channelmgr.relaypicker.pick_weighted_relay()
  492. if network.thenetwork.womode == network.WOMode.VANILLA:
  493. print("relay",r.descdict["addr"])
  494. else:
  495. print("relay",r.snipdict["addr"])
  496. relays[3].terminate()
  497. relaysent += relays[3].perfstats.bytes_sent
  498. relayrecv += relays[3].perfstats.bytes_received
  499. del relays[3]
  500. # Tick the epoch
  501. network.thenetwork.nextepoch()
  502. circs = []
  503. for i in range(20):
  504. circ = clients[0].channelmgr.new_circuit()
  505. if circ is None:
  506. sys.exit("ERR: Client unable to create circuits")
  507. circs.append(circ)
  508. circ.send_cell(relay.StringCell("hello world circuit %d" % i))
  509. # Tick the epoch
  510. network.thenetwork.nextepoch()
  511. # See what channels exist and do a consistency check
  512. for r in relays:
  513. print("%s: %s" % (r.netaddr, [ str(k) + str([ck for ck in r.channelmgr.channels[k].circuithandlers.keys()]) for k in r.channelmgr.channels.keys()]))
  514. raddr = r.netaddr
  515. for ad, ch in r.channelmgr.channels.items():
  516. if ch.peer.channelmgr.myaddr != ad:
  517. print('address mismatch:', raddr, ad, ch.peer.channelmgr.myaddr)
  518. if ch.peer.channelmgr.channels[raddr].peer is not ch:
  519. print('asymmetry:', raddr, ad, ch, ch.peer.channelmgr.channels[raddr].peer)
  520. # See what channels exist and do a consistency check
  521. for c in clients:
  522. print("%s: %s" % (c.netaddr, [ str(k) + str([ck for ck in c.channelmgr.channels[k].circuithandlers.keys()]) for k in c.channelmgr.channels.keys()]))
  523. caddr = c.netaddr
  524. for ad, ch in c.channelmgr.channels.items():
  525. if ch.peer.channelmgr.myaddr != ad:
  526. print('address mismatch:', caddr, ad, ch.peer.channelmgr.myaddr)
  527. if ch.peer.channelmgr.channels[caddr].peer is not ch:
  528. print('asymmetry:', caddr, ad, ch, ch.peer.channelmgr.channels[caddr].peer)
  529. if ch.circuithandlers.keys() != \
  530. ch.peer.channelmgr.channels[caddr].circuithandlers.keys():
  531. print('circuit asymmetry:', caddr, ad, ch.peer.channelmgr.myaddr)
  532. for c in circs:
  533. c.close()
  534. for d in dirauths:
  535. print(d.perfstats)
  536. dirasent += d.perfstats.bytes_sent
  537. dirarecv += d.perfstats.bytes_received
  538. print("DirAuths sent=%s recv=%s" % (dirasent, dirarecv))
  539. totsent += dirasent
  540. totrecv += dirarecv
  541. for r in relays:
  542. print(r.perfstats)
  543. relaysent += r.perfstats.bytes_sent
  544. relayrecv += r.perfstats.bytes_received
  545. print("Relays sent=%s recv=%s" % (relaysent, relayrecv))
  546. totsent += relaysent
  547. totrecv += relayrecv
  548. for c in clients:
  549. print(c.perfstats)
  550. clisent += c.perfstats.bytes_sent
  551. clirecv += c.perfstats.bytes_received
  552. print("Client sent=%s recv=%s" % (clisent, clirecv))
  553. totsent += clisent
  554. totrecv += clirecv
  555. print("Total sent=%s recv=%s" % (totsent, totrecv))