Skip to content

Instantly share code, notes, and snippets.

@viraptor
Last active December 22, 2016 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viraptor/049b76f4ad8af007b20ee296d97e5894 to your computer and use it in GitHub Desktop.
Save viraptor/049b76f4ad8af007b20ee296d97e5894 to your computer and use it in GitHub Desktop.
def close_all_circuits(ctrl):
circuits = ctrl.get_circuits()
for c in circuits:
ctrl.close_circuit(c.id)
def initialize(ctrl):
# don't create circuits automatically
ctrl.set_conf('__DisablePredictedCircuits', '1')
# close all existing circuits
close_all_circuits(ctrl)
# find a valid first hop
initial_hop = None
guards = ctrl.get_info('entry-guards')
for guard in guards.splitlines():
guard = guard.strip()
parts = guard.split()
if len(parts) < 2:
continue
if parts[1] != 'up':
continue
initial_hop = parts[0].split('~')[0]
break
if not initial_hop:
sys.exit("cannot find valid first hop")
return initial_hop
def use_exit(ctrl, initial_hop, ex):
try:
close_all_circuits(ctrl)
except:
pass
try:
ex_ns = ctrl.get_network_status(ex)
except stem.DescriptorUnavailable:
raise # handle offline node
fp = ex_ns.fingerprint
if stem.Flag.RUNNING not in ex_ns.flags:
return # handle offline node
if stem.Flag.EXIT not in ex_ns.flags:
return # node's not exit anymore
circ_id = ctrl.new_circuit([initial_hop, fp])
# use the circuit
try:
ctrl.close_circuit(circ_id)
except:
raise # handle issues
first_hop = initialize(ctrl)
use_exit(ctrl, first_hop, chosen_exit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment