relay.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. #!/usr/bin/env python3
  2. import random # For simulation, not cryptography!
  3. import math
  4. import nacl.utils
  5. import nacl.signing
  6. import nacl.public
  7. import nacl.hash
  8. import network
  9. import dirauth
  10. class RelayNetMsg(network.NetMsg):
  11. """The subclass of NetMsg for messages between relays and either
  12. relays or clients."""
  13. class RelayGetConsensusMsg(RelayNetMsg):
  14. """The subclass of RelayNetMsg for fetching the consensus."""
  15. class RelayConsensusMsg(RelayNetMsg):
  16. """The subclass of RelayNetMsg for returning the consensus."""
  17. def __init__(self, consensus):
  18. self.consensus = consensus
  19. class RelayRandomHopMsg(RelayNetMsg):
  20. """A message used for testing, that hops from relay to relay
  21. randomly until its TTL expires."""
  22. def __init__(self, ttl):
  23. self.ttl = ttl
  24. def __str__(self):
  25. return "RandomHop TTL=%d" % self.ttl
  26. class CircuitCellMsg(RelayNetMsg):
  27. """Send a message tagged with a circuit id."""
  28. def __init__(self, circuitid, cell):
  29. self.circid = circuitid
  30. self.cell = cell
  31. def __str__(self):
  32. return "C%d:%s" % (self.circid, self.cell)
  33. def size(self):
  34. # circuitids are 4 bytes
  35. return 4 + self.cell.size()
  36. class RelayCell(RelayNetMsg):
  37. """All cells (which are sent inside a CircuitCellMsg, and so do not
  38. need their own circuitid) should be a subclass of this class."""
  39. class VanillaCreateCircuitMsg(RelayNetMsg):
  40. """The message for requesting circuit creation in Vanilla Onion
  41. Routing."""
  42. def __init__(self, circid, ntor_request):
  43. self.circid = circid
  44. self.ntor_request = ntor_request
  45. class VanillaCreatedCircuitCell(RelayCell):
  46. """The message for responding to circuit creation in Vanilla Onion
  47. Routing."""
  48. def __init__(self, ntor_reply):
  49. self.ntor_reply = ntor_reply
  50. class VanillaExtendCircuitCell(RelayCell):
  51. """The message for requesting circuit creation in Vanilla Onion
  52. Routing."""
  53. def __init__(self, hopaddr, ntor_request):
  54. self.hopaddr = hopaddr
  55. self.ntor_request = ntor_request
  56. class VanillaExtendedCircuitCell(RelayCell):
  57. """The message for responding to circuit creation in Vanilla Onion
  58. Routing."""
  59. def __init__(self, ntor_reply):
  60. self.ntor_reply = ntor_reply
  61. class EncryptedCell(RelayCell):
  62. """Send a message encrypted with a symmetric key. In this
  63. implementation, the encryption is not really done. A hash of the
  64. key is stored with the message so that it can be checked at
  65. decryption time."""
  66. def __init__(self, key, msg):
  67. self.keyhash = nacl.hash.sha256(key)
  68. self.plaintext = msg
  69. def decrypt(self, key):
  70. keyhash = nacl.hash.sha256(key)
  71. if keyhash != self.keyhash:
  72. raise ValueError("EncryptedCell key mismatch")
  73. return self.plaintext
  74. class RelayFallbackTerminationError(Exception):
  75. """An exception raised when someone tries to terminate a fallback
  76. relay."""
  77. class NTor:
  78. """A class implementing the ntor one-way authenticated key agreement
  79. scheme. The details are not exactly the same as either the ntor
  80. paper or Tor's implementation, but it will agree on keys and have
  81. the same number of public key operations."""
  82. def __init__(self, perfstats):
  83. self.perfstats = perfstats
  84. def request(self):
  85. """Create the ntor request message: X = g^x."""
  86. self.client_ephem_key = nacl.public.PrivateKey.generate()
  87. self.perfstats.keygens += 1
  88. return self.client_ephem_key.public_key
  89. @staticmethod
  90. def reply(onion_privkey, idpubkey, client_pubkey, perfstats):
  91. """The server calls this static method to produce the ntor reply
  92. message: (Y = g^y, B = g^b, A = H(M, "verify")) and the shared
  93. secret S = H(M, "secret") for M = (X^y,X^b,ID,B,X,Y)."""
  94. server_ephem_key = nacl.public.PrivateKey.generate()
  95. perfstats.keygens += 1
  96. xykey = nacl.public.Box(server_ephem_key, client_pubkey).shared_key()
  97. xbkey = nacl.public.Box(onion_privkey, client_pubkey).shared_key()
  98. perfstats.dhs += 2
  99. M = xykey + xbkey + \
  100. idpubkey.encode(encoder=nacl.encoding.RawEncoder) + \
  101. onion_privkey.public_key.encode(encoder=nacl.encoding.RawEncoder) + \
  102. server_ephem_key.public_key.encode(encoder=nacl.encoding.RawEncoder)
  103. A = nacl.hash.sha256(M + b'verify', encoder=nacl.encoding.RawEncoder)
  104. S = nacl.hash.sha256(M + b'secret', encoder=nacl.encoding.RawEncoder)
  105. return ((server_ephem_key.public_key, onion_privkey.public_key, A), \
  106. S)
  107. def verify(self, reply, onion_pubkey, idpubkey):
  108. """The client calls this method to verify the ntor reply
  109. message, passing the onion and id public keys for the server
  110. it's expecting to be talking to . Returns the shared secret on
  111. success, or raises ValueError on failure."""
  112. server_ephem_pubkey, server_onion_pubkey, authtag = reply
  113. if onion_pubkey != server_onion_pubkey:
  114. raise ValueError("NTor onion pubkey mismatch")
  115. xykey = nacl.public.Box(self.client_ephem_key, server_ephem_pubkey).shared_key()
  116. xbkey = nacl.public.Box(self.client_ephem_key, onion_pubkey).shared_key()
  117. self.perfstats.dhs += 2
  118. M = xykey + xbkey + \
  119. idpubkey.encode(encoder=nacl.encoding.RawEncoder) + \
  120. onion_pubkey.encode(encoder=nacl.encoding.RawEncoder) + \
  121. server_ephem_pubkey.encode(encoder=nacl.encoding.RawEncoder)
  122. Acheck = nacl.hash.sha256(M + b'verify', encoder=nacl.encoding.RawEncoder)
  123. S = nacl.hash.sha256(M + b'secret', encoder=nacl.encoding.RawEncoder)
  124. if Acheck != authtag:
  125. raise ValueError("NTor auth mismatch")
  126. return S
  127. class CircuitHandler:
  128. """A class for managing sending and receiving encrypted cells on a
  129. particular circuit."""
  130. class NoCryptLayer:
  131. def encrypt_msg(self, msg): return msg
  132. def decrypt_msg(self, msg): return msg
  133. class CryptLayer:
  134. def __init__(self, enckey, deckey, next_layer):
  135. self.enckey = enckey
  136. self.deckey = deckey
  137. self.next_layer = next_layer
  138. def encrypt_msg(self, msg):
  139. return self.next_layer.encrypt_msg(EncryptedCell(self.enckey, msg))
  140. def decrypt_msg(self, msg):
  141. return self.next_layer.decrypt_msg(msg).decrypt(self.deckey)
  142. def __init__(self, channel, circid):
  143. self.channel = channel
  144. self.circid = circid
  145. # The list of relay descriptors that form the circuit so far
  146. # (client side only)
  147. self.circuit_descs = []
  148. # The dispatch table is indexed by type, and the values are
  149. # objects with received_cell(circhandler, cell) methods.
  150. self.cell_dispatch_table = dict()
  151. # The topmost crypt layer. This is an object with
  152. # encrypt_msg(msg) and decrypt_msg(msg) methods that returns the
  153. # en/decrypted messages respectively. Messages are encrypted
  154. # starting with the last layer that was added (the keys for the
  155. # furthest away relay in the circuit) and are decrypted starting
  156. # with the first layer that was added (the keys for the guard).
  157. self.crypt_layer = self.NoCryptLayer()
  158. def send_cell(self, cell):
  159. """Send a cell on this circuit, encrypting as needed."""
  160. self.channel_send_cell(self.crypt_layer.encrypt_msg(cell))
  161. def channel_send_cell(self, cell):
  162. """Send a cell on this circuit directly without encrypting it
  163. first."""
  164. self.channel.send_msg(CircuitCellMsg(self.circid, cell))
  165. def received_cell(self, cell):
  166. """A cell has been received on this circuit. Dispatch it
  167. according to its type."""
  168. if isinstance(cell, EncryptedCell):
  169. cell = self.crypt_layer.decrypt_msg(cell)
  170. print("CircuitHandler: %s received cell %s on circuit %d from %s" % (self.channel.cellhandler.myaddr, cell, self.circid, self.channel.peer.cellhandler.myaddr))
  171. celltype = type(cell)
  172. if celltype in self.cell_dispatch_table:
  173. self.cell_dispatch_table[celltype].received_cell(self, cell)
  174. def add_crypt_layer(self, enckey, deckey):
  175. """Add a processing layer to this CircuitHandler so that cells
  176. we send will get encrypted with the first given key, and cells
  177. we receive will be decrypted with the other given key."""
  178. current_crypt_layer = self.crypt_layer
  179. self.crypt_layer = self.CryptLayer(enckey, deckey, current_crypt_layer)
  180. class Channel(network.Connection):
  181. """A class representing a channel between a relay and either a
  182. client or a relay, transporting cells from various circuits."""
  183. def __init__(self):
  184. super().__init__()
  185. # The CellRelay managing this Channel
  186. self.cellhandler = None
  187. # The Channel at the other end
  188. self.peer = None
  189. # The function to call when the connection closes
  190. self.closer = lambda: 0
  191. # The next circuit id to use on this channel. The party that
  192. # opened the channel uses even numbers; the receiving party uses
  193. # odd numbers.
  194. self.next_circid = None
  195. # A map for CircuitHandlers to use for each open circuit on the
  196. # channel
  197. self.circuithandlers = dict()
  198. def closed(self):
  199. self.closer()
  200. self.peer = None
  201. def close(self):
  202. if self.peer is not None and self.peer is not self:
  203. self.peer.closed()
  204. self.closed()
  205. def new_circuit(self):
  206. """Allocate a new circuit on this channel, returning the new
  207. circuit's id and the new CircuitHandler."""
  208. circid = self.next_circid
  209. self.next_circid += 2
  210. circuithandler = CircuitHandler(self, circid)
  211. self.circuithandlers[circid] = circuithandler
  212. return circid, circuithandler
  213. def new_circuit_with_circid(self, circid):
  214. """Allocate a new circuit on this channel, with the circuit id
  215. received from our peer. Return the new CircuitHandler"""
  216. circuithandler = CircuitHandler(self, circid)
  217. self.circuithandlers[circid] = circuithandler
  218. return circuithandler
  219. def send_cell(self, circid, cell):
  220. """Send the given message on the given circuit, encrypting or
  221. decrypting as needed."""
  222. self.circuithandlers[circid].send_cell(cell)
  223. def send_raw_cell(self, circid, cell):
  224. """Send the given message, tagged for the given circuit id. No
  225. encryption or decryption is done."""
  226. self.send_msg(CircuitCellMsg(self.circid, self.cell))
  227. def send_msg(self, msg):
  228. """Send the given NetMsg on the channel."""
  229. self.cellhandler.perfstats.bytes_sent += msg.size()
  230. self.peer.received(self.cellhandler.myaddr, msg)
  231. def received(self, peeraddr, msg):
  232. """Callback when a message is received from the network."""
  233. print('Channel: %s received %s from %s' % (self.cellhandler.myaddr, msg, peeraddr))
  234. self.cellhandler.perfstats.bytes_received += msg.size()
  235. if isinstance(msg, CircuitCellMsg):
  236. circid, cell = msg.circid, msg.cell
  237. self.circuithandlers[circid].received_cell(cell)
  238. else:
  239. self.cellhandler.received_msg(msg, peeraddr, self)
  240. class CellHandler:
  241. """The class that manages the channels to other relays and clients.
  242. Relays and clients both use subclasses of this class to both create
  243. on-demand channels to relays, to gracefully handle the closing of
  244. channels, and to handle commands received over the channels."""
  245. def __init__(self, myaddr, dirauthaddrs, perfstats):
  246. # A dictionary of Channels to other hosts, indexed by NetAddr
  247. self.channels = dict()
  248. self.myaddr = myaddr
  249. self.dirauthaddrs = dirauthaddrs
  250. self.consensus = None
  251. self.perfstats = perfstats
  252. def terminate(self):
  253. """Close all connections we're managing."""
  254. while self.channels:
  255. channelitems = iter(self.channels.items())
  256. addr, channel = next(channelitems)
  257. print('closing channel', addr, channel)
  258. channel.close()
  259. def add_channel(self, channel, peeraddr):
  260. """Add the given channel to the list of channels we are
  261. managing. If we are already managing a channel to the same
  262. peer, close it first."""
  263. if peeraddr in self.channels:
  264. self.channels[peeraddr].close()
  265. channel.cellhandler = self
  266. self.channels[peeraddr] = channel
  267. channel.closer = lambda: self.channels.pop(peeraddr)
  268. def get_channel_to(self, addr):
  269. """Get the Channel connected to the given NetAddr, creating one
  270. if none exists right now."""
  271. if addr in self.channels:
  272. return self.channels[addr]
  273. # Create the new channel
  274. newchannel = network.thenetwork.connect(self.myaddr, addr, \
  275. self.perfstats)
  276. self.channels[addr] = newchannel
  277. newchannel.closer = lambda: self.channels.pop(addr)
  278. newchannel.cellhandler = self
  279. return newchannel
  280. def received_msg(self, msg, peeraddr, channel):
  281. """Callback when a NetMsg not specific to a circuit is
  282. received."""
  283. print("CellHandler: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  284. def received_cell(self, circid, cell, peeraddr, channel):
  285. """Callback with a circuit-specific cell is received."""
  286. print("CellHandler: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  287. def send_msg(self, msg, peeraddr):
  288. """Send a message to the peer with the given address."""
  289. channel = self.get_channel_to(peeraddr)
  290. channel.send_msg(msg)
  291. def send_cell(self, circid, cell, peeraddr):
  292. """Send a cell on the given circuit to the peer with the given
  293. address."""
  294. channel = self.get_channel_to(peeraddr)
  295. channel.send_cell(circid, cell)
  296. class CellRelay(CellHandler):
  297. """The subclass of CellHandler for relays."""
  298. def __init__(self, myaddr, dirauthaddrs, onionprivkey, idpubkey, perfstats):
  299. super().__init__(myaddr, dirauthaddrs, perfstats)
  300. self.onionkey = onionprivkey
  301. self.idpubkey = idpubkey
  302. def get_consensus(self):
  303. """Download a fresh consensus from a random dirauth."""
  304. a = random.choice(self.dirauthaddrs)
  305. c = network.thenetwork.connect(self, a, self.perfstats)
  306. self.consensus = c.getconsensus()
  307. dirauth.Consensus.verify(self.consensus, \
  308. network.thenetwork.dirauthkeys(), self.perfstats)
  309. c.close()
  310. def received_msg(self, msg, peeraddr, channel):
  311. """Callback when a NetMsg not specific to a circuit is
  312. received."""
  313. print("CellRelay: Node %s received msg %s from %s" % (self.myaddr, msg, peeraddr))
  314. if isinstance(msg, RelayRandomHopMsg):
  315. if msg.ttl > 0:
  316. # Pick a random next hop from the consensus
  317. nexthop = random.choice(self.consensus.consdict['relays'])
  318. nextaddr = nexthop.descdict['addr']
  319. self.send_msg(RelayRandomHopMsg(msg.ttl-1), nextaddr)
  320. elif isinstance(msg, RelayGetConsensusMsg):
  321. self.send_msg(RelayConsensusMsg(self.consensus), peeraddr)
  322. elif isinstance(msg, VanillaCreateCircuitMsg):
  323. # A new circuit has arrived
  324. circhandler = channel.new_circuit_with_circid(msg.circid)
  325. # Create the ntor reply
  326. reply, secret = NTor.reply(self.onionkey, self.idpubkey, \
  327. msg.ntor_request, self.perfstats)
  328. # Set up the circuit to use the shared secret
  329. enckey = nacl.hash.sha256(secret + b'downstream')
  330. deckey = nacl.hash.sha256(secret + b'upstream')
  331. circhandler.add_crypt_layer(enckey, deckey)
  332. # Send the ntor reply
  333. self.send_msg(CircuitCellMsg(msg.circid, \
  334. VanillaCreatedCircuitCell(reply)), peeraddr)
  335. else:
  336. return super().received_msg(msg, peeraddr, channel)
  337. def received_cell(self, circid, cell, peeraddr, channel):
  338. """Callback with a circuit-specific cell is received."""
  339. print("CellRelay: Node %s received cell on circ %d: %s from %s" % (self.myaddr, circid, cell, peeraddr))
  340. return super().received_cell(circid, cell, peeraddr, channel)
  341. class Relay(network.Server):
  342. """The class representing an onion relay."""
  343. def __init__(self, dirauthaddrs, bw, flags):
  344. # Gather performance statistics
  345. self.perfstats = network.PerfStats(network.EntType.RELAY)
  346. self.perfstats.is_bootstrapping = True
  347. # Create the identity and onion keys
  348. self.idkey = nacl.signing.SigningKey.generate()
  349. self.onionkey = nacl.public.PrivateKey.generate()
  350. self.perfstats.keygens += 2
  351. self.name = self.idkey.verify_key.encode(encoder=nacl.encoding.HexEncoder).decode("ascii")
  352. # Bind to the network to get a network address
  353. self.netaddr = network.thenetwork.bind(self)
  354. self.perfstats.name = "Relay at %s" % self.netaddr
  355. # Our bandwidth and flags
  356. self.bw = bw
  357. self.flags = flags
  358. # Register for epoch change notification
  359. network.thenetwork.wantepochticks(self, True, end=True)
  360. network.thenetwork.wantepochticks(self, True)
  361. # Create the CellRelay connection manager
  362. self.cellhandler = CellRelay(self.netaddr, dirauthaddrs, \
  363. self.onionkey, self.idkey.verify_key, self.perfstats)
  364. # Initially, we're not a fallback relay
  365. self.is_fallbackrelay = False
  366. self.uploaddesc()
  367. def terminate(self):
  368. """Stop this relay."""
  369. if self.is_fallbackrelay:
  370. # Fallback relays must not (for now) terminate
  371. raise RelayFallbackTerminationError(self)
  372. # Stop listening for epoch ticks
  373. network.thenetwork.wantepochticks(self, False, end=True)
  374. network.thenetwork.wantepochticks(self, False)
  375. # Tell the dirauths we're going away
  376. self.uploaddesc(False)
  377. # Close connections to other relays
  378. self.cellhandler.terminate()
  379. # Stop listening to our own bound port
  380. self.close()
  381. def set_is_fallbackrelay(self, isfallback = True):
  382. """Set this relay to be a fallback relay (or unset if passed
  383. False)."""
  384. self.is_fallbackrelay = isfallback
  385. def epoch_ending(self, epoch):
  386. # Download the new consensus, which will have been created
  387. # already since the dirauths' epoch_ending callbacks happened
  388. # before the relays'.
  389. self.cellhandler.get_consensus()
  390. def newepoch(self, epoch):
  391. self.uploaddesc()
  392. def uploaddesc(self, upload=True):
  393. # Upload the descriptor for the epoch to come, or delete a
  394. # previous upload if upload=False
  395. descdict = dict();
  396. descdict["epoch"] = network.thenetwork.getepoch() + 1
  397. descdict["idkey"] = self.idkey.verify_key
  398. descdict["onionkey"] = self.onionkey.public_key
  399. descdict["addr"] = self.netaddr
  400. descdict["bw"] = self.bw
  401. descdict["flags"] = self.flags
  402. desc = dirauth.RelayDescriptor(descdict)
  403. desc.sign(self.idkey, self.perfstats)
  404. dirauth.RelayDescriptor.verify(desc, self.perfstats)
  405. if upload:
  406. descmsg = dirauth.DirAuthUploadDescMsg(desc)
  407. else:
  408. # Note that this relies on signatures being deterministic;
  409. # otherwise we'd need to save the descriptor we uploaded
  410. # before so we could tell the airauths to delete the exact
  411. # one
  412. descmsg = dirauth.DirAuthDelDescMsg(desc)
  413. # Upload them
  414. for a in self.cellhandler.dirauthaddrs:
  415. c = network.thenetwork.connect(self, a, self.perfstats)
  416. c.sendmsg(descmsg)
  417. c.close()
  418. def connected(self, peer):
  419. """Callback invoked when someone (client or relay) connects to
  420. us. Create a pair of linked Channels and return the peer half
  421. to the peer."""
  422. # Create the linked pair
  423. if peer is self.netaddr:
  424. # A self-loop? We'll allow it.
  425. peerchannel = Channel()
  426. peerchannel.peer = peerchannel
  427. peerchannel.next_circid = 2
  428. return peerchannel
  429. peerchannel = Channel()
  430. ourchannel = Channel()
  431. peerchannel.peer = ourchannel
  432. peerchannel.next_circid = 2
  433. ourchannel.peer = peerchannel
  434. ourchannel.next_circid = 1
  435. # Add our channel to the CellRelay
  436. self.cellhandler.add_channel(ourchannel, peer)
  437. return peerchannel
  438. if __name__ == '__main__':
  439. perfstats = network.PerfStats(network.EntType.NONE)
  440. # Start some dirauths
  441. numdirauths = 9
  442. dirauthaddrs = []
  443. for i in range(numdirauths):
  444. dira = dirauth.DirAuth(i, numdirauths)
  445. dirauthaddrs.append(dira.netaddr)
  446. # Start some relays
  447. numrelays = 10
  448. relays = []
  449. for i in range(numrelays):
  450. # Relay bandwidths (at least the ones fast enough to get used)
  451. # in the live Tor network (as of Dec 2019) are well approximated
  452. # by (200000-(200000-25000)/3*log10(x)) where x is a
  453. # uniform integer in [1,2500]
  454. x = random.randint(1,2500)
  455. bw = int(200000-(200000-25000)/3*math.log10(x))
  456. relays.append(Relay(dirauthaddrs, bw, 0))
  457. # The fallback relays are a hardcoded list of about 5% of the
  458. # relays, used by clients for bootstrapping
  459. numfallbackrelays = int(numrelays * 0.05) + 1
  460. fallbackrelays = random.sample(relays, numfallbackrelays)
  461. for r in fallbackrelays:
  462. r.set_is_fallbackrelay()
  463. network.thenetwork.setfallbackrelays(fallbackrelays)
  464. # Tick the epoch
  465. network.thenetwork.nextepoch()
  466. dirauth.Consensus.verify(dirauth.DirAuth.consensus, \
  467. network.thenetwork.dirauthkeys(), perfstats)
  468. print('ticked; epoch=', network.thenetwork.getepoch())
  469. relays[3].cellhandler.send_msg(RelayRandomHopMsg(30), relays[5].netaddr)
  470. # See what channels exist and do a consistency check
  471. for r in relays:
  472. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  473. raddr = r.netaddr
  474. for ad, ch in r.cellhandler.channels.items():
  475. if ch.peer.cellhandler.myaddr != ad:
  476. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  477. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  478. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  479. # Stop some relays
  480. relays[3].terminate()
  481. del relays[3]
  482. relays[5].terminate()
  483. del relays[5]
  484. relays[7].terminate()
  485. del relays[7]
  486. # Tick the epoch
  487. network.thenetwork.nextepoch()
  488. print(dirauth.DirAuth.consensus)
  489. # See what channels exist and do a consistency check
  490. for r in relays:
  491. print("%s: %s" % (r.netaddr, [ str(k) for k in r.cellhandler.channels.keys()]))
  492. raddr = r.netaddr
  493. for ad, ch in r.cellhandler.channels.items():
  494. if ch.peer.cellhandler.myaddr != ad:
  495. print('address mismatch:', raddr, ad, ch.peer.cellhandler.myaddr)
  496. if ch.peer.cellhandler.channels[raddr].peer is not ch:
  497. print('asymmetry:', raddr, ad, ch, ch.peer.cellhandler.channels[raddr].peer)
  498. channel = relays[3].cellhandler.get_channel_to(relays[5].netaddr)
  499. circid, circhandler = channel.new_circuit()
  500. peerchannel = relays[5].cellhandler.get_channel_to(relays[3].netaddr)
  501. peerchannel.new_circuit_with_circid(circid)
  502. relays[3].cellhandler.send_cell(circid, network.StringNetMsg("test"), relays[5].netaddr)
  503. idpubkey = dirauth.DirAuth.consensus.consdict["relays"][1].descdict["idkey"]
  504. onionpubkey = dirauth.DirAuth.consensus.consdict["relays"][1].descdict["onionkey"]
  505. nt = NTor(perfstats)
  506. req = nt.request()
  507. R, S = NTor.reply(relays[1].onionkey, idpubkey, req, perfstats)
  508. S2 = nt.verify(R, onionpubkey, idpubkey)
  509. print(S == S2)