Ticket #18116: bug18116_stem.py

File bug18116_stem.py, 1.3 KB (added by teor, 4 years ago)

Minimal example that triggers the bug

Line 
1import random
2import sys
3import time
4import stem.control
5
6# Check both 9050 and 9151: "default"
7CONTROL_PORT = int(sys.argv[1]) if len(sys.argv) >= 2 else "default"
8N_ATTEMPTS = 3
9CIRCUIT_INVALID = "no_circuit_id"
10
11n = 0
12
13def scan(controller, path):
14  """
15  Build a circuit through the given path of relays, and return the circuit_id.
16  """
17  global n
18  try:
19    circuit_id = CIRCUIT_INVALID
20    # purpose = "controller" means these circuits won't be used for anything
21    circuit_id = controller.new_circuit(path, purpose = "controller",
22                                        await_build = True)
23    return circuit_id
24  finally:
25    if circuit_id != CIRCUIT_INVALID:
26      controller.close_circuit(circuit_id)
27    n = n + 1
28    if n >= N_ATTEMPTS - 1:
29      print("Please kill tor now.")
30      time.sleep(10)
31
32with stem.control.Controller.from_port(port = CONTROL_PORT) as controller:
33  controller.authenticate()
34  # Pick some guards
35  relay_fingerprints = [desc.fingerprint for desc in controller.get_network_statuses() if "Guard" in desc.flags]
36  for guard in random.sample(relay_fingerprints, N_ATTEMPTS):
37    try:
38      circuit_id = scan(controller, [guard])
39      print("Circuit %s connected to %s" % (guard, circuit_id))
40    except Exception as exc:
41      print("Error connecting to %s: %s" % (guard, exc))