client.py 28 KB

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