[Pkg-privacy-commits] [onionbalance] 01/02: Imported Upstream version 0.1.2

Donncha O'Cearbahill donncha-guest at moszumanska.debian.org
Thu Oct 8 16:27:29 UTC 2015


This is an automated email from the git hooks/post-receive script.

donncha-guest pushed a commit to branch master
in repository onionbalance.

commit 04f2576c3b824eeba736a200bf045e63e55fdf89
Author: Donncha O'Cearbhaill <donncha at donncha.is>
Date:   Thu Oct 8 17:28:07 2015 +0200

    Imported Upstream version 0.1.2
---
 .gitignore                                        |  58 ++
 .travis.yml                                       |  15 +
 CHANGES.rst                                       |  20 +
 COPYING                                           | 675 ++++++++++++++++++++++
 MANIFEST.in                                       |   6 +
 README.rst                                        | 142 +++++
 docs/Makefile                                     | 192 ++++++
 docs/conf.py                                      | 380 ++++++++++++
 docs/design.rst                                   | 263 +++++++++
 docs/index.rst                                    |  32 +
 docs/make.bat                                     | 263 +++++++++
 docs/modules.rst                                  |   7 +
 docs/onionbalance.config.rst                      |   7 +
 docs/onionbalance.descriptor.rst                  |   7 +
 docs/onionbalance.eventhandler.rst                |   7 +
 docs/onionbalance.instance.rst                    |   7 +
 docs/onionbalance.log.rst                         |   7 +
 docs/onionbalance.manager.rst                     |   7 +
 docs/onionbalance.rst                             |  26 +
 docs/onionbalance.schedule.rst                    |   7 +
 docs/onionbalance.service.rst                     |   7 +
 docs/onionbalance.settings.rst                    |   7 +
 docs/onionbalance.util.rst                        |   7 +
 onionbalance.py                                   |   9 +
 onionbalance/__init__.py                          |   7 +
 onionbalance/__main__.py                          |   7 +
 onionbalance/config.py                            |  18 +
 onionbalance/data/config.example.yaml             |  16 +
 onionbalance/data/torrc-instance                  |  17 +
 onionbalance/data/torrc-server                    |  13 +
 onionbalance/descriptor.py                        | 290 ++++++++++
 onionbalance/eventhandler.py                      |  47 ++
 onionbalance/instance.py                          | 114 ++++
 onionbalance/log.py                               |  31 +
 onionbalance/manager.py                           | 125 ++++
 onionbalance/schedule.py                          | 416 +++++++++++++
 onionbalance/service.py                           | 196 +++++++
 onionbalance/settings.py                          | 370 ++++++++++++
 onionbalance/util.py                              | 145 +++++
 requirements.txt                                  |   4 +
 scripts/rend-connection-stats.py                  | 146 +++++
 setup.cfg                                         |   5 +
 setup.py                                          |  60 ++
 test-requirements.txt                             |   4 +
 test/__init__.py                                  |   0
 test/functional/test_onionbalance_config.py       | 154 +++++
 test/functional/test_publish_master_descriptor.py | 144 +++++
 test/scripts/install-chutney.sh                   |  31 +
 test/scripts/install-tor.sh                       |   6 +
 test/test_descriptor.py                           | 342 +++++++++++
 test/test_settings.py                             |  50 ++
 test/test_util.py                                 | 267 +++++++++
 test/util.py                                      |  12 +
 tox.ini                                           |  29 +
 54 files changed, 5224 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f58e4c3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,58 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+env/
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.cache
+nosetests.xml
+coverage.xml
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Config files and keys
+*.yaml
+*.key
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..7cc16aa
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,15 @@
+language: python
+env:
+  - TOXENV=py27 TEST=functional
+  - TOXENV=py34 TEST=functional
+  - TOXENV=style
+  - TOXENV=docs
+before_install:
+  # Install tor and chutney if doing functional tests
+  - if [[ $TEST == 'functional' ]]; then ./test/scripts/install-tor.sh; fi
+  - if [[ $TEST == 'functional' ]]; then export PATH=$PATH:$PWD/tor/src/tools:$PWD/tor/src/or; fi
+  - if [[ $TEST == 'functional' ]]; then source test/scripts/install-chutney.sh; fi
+install:
+  - pip install tox
+script:
+  - tox
diff --git a/CHANGES.rst b/CHANGES.rst
new file mode 100644
index 0000000..66da11f
--- /dev/null
+++ b/CHANGES.rst
@@ -0,0 +1,20 @@
+0.1.2
+-----
+
+- Remove dependency on the schedule package to prepare for packaging
+  OnionBalance in Debian. The schedule code is now included directly in
+  onionbalance/schedule.py.
+- Fix the executable path in the help messages for onionbalance and
+  onionbalance-config.
+
+0.1.1
+-----
+
+- Patch to resolve issue when saving generated torrc files from
+  onionbalance-config in Python 2.
+
+
+0.1.0
+-----
+
+-  Initial release
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..10926e8
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,675 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..f6e5dc0
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,6 @@
+include README.rst
+include COPYING
+include requirements.txt
+include tox.ini
+recursive-include docs *.rst
+recursive-include onionbalance/data *
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..a140a7e
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,142 @@
+OnionBalance
+============
+
+Introduction
+------------
+
+The OnionBalance software allows for Tor hidden service requests to be distributed across multiple backend Tor instances. OnionBalance provides load-balancing while also making onion services more resilient and reliable by eliminating single points-of-failure.
+
+* `Documentation <https://onionbalance.readthedocs.org>`_
+* `Code <https://github.com/DonnchaC/onionbalance/>`_
+* `Bug Tracker <https://github.com/DonnchaC/onionbalance/issues>`_
+
+|build-status| |docs|
+
+Getting Started
+---------------
+
+OnionBalance requires a system which runs the OnionBalance management server and up to 10 backend servers which run onion services that serve the desired content (web site, IRC server etc.).
+
+Installing OnionBalance
+~~~~~~~~~~~~~~~~~~~~~~~
+
+::
+
+    $ pip install onionbalance
+
+or
+
+::
+
+    $ git clone https://github.com/DonnchaC/onionbalance.git
+    $ cd onionbalance
+    $ python setup.py install
+
+The management server does not need to be installed on the same systems that host the backend onion service instances.
+
+
+Configuring the OnionBalance management server
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The bundled ``onionbalance-config`` tool is the fastest way to generate the necessary keys and config files to get your onion service up and running.
+
+::
+
+    $ onionbalance-config
+
+The config generator runs in an interactive mode when called without any arguments. The ``master`` directory should be stored on the management server while the other instance directories should be transferred to the respective backend servers.
+
+
+Configuring Tor on the management server
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+OnionBalance requires that a recent version of Tor (>= 0.2.7.1-alpha) is installed on the management server system. This versions of Tor is not yet available from the Tor repositories yet and must be compiled from source.
+
+::
+
+    $ wget https://www.torproject.org/dist/tor-0.2.7.1-alpha.tar.gz
+    $ tar -xzvf tor-0.2.7.1-alpha.tar.gz && cd tor-0.2.7.1-alpha
+    $ ./configure --disable-asciidoc && sudo make install
+
+The Tor config file at ``onionbalance/data/torrc-server`` can be used for the management server. The ``onionbalance-config`` tool also outputs a suitable Tor config file as ``master/torrc-server``.
+
+::
+
+    $ tor -f torrc-server
+
+Configuring the backend onion service instances
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Each backend instance should be run a standard onion service which serves your website or other content. More information about configuring onion services is available in the Tor Project's `hidden service configuration guide <https://www.torproject.org/docs/tor-hidden-service.html.en>`_.
+
+If you have used the ``onionbalance-config`` tool you should transfer the generated instance config files and keys to the respective backend servers. You can then start the onion service instance by simply running:
+
+::
+
+    $ tor -f instance_torrc
+
+OnionBalance config file
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+The OnionBalance management server must have access to the private key for the master onion service. This master private key determines the address that users will use to access your onion service. This private key must be kept secure.
+
+The location of the private key must be specified as relative or absolute path under ``key`` in the config file. Each backend Tor onion service instance is listed by it's unique onion address in the ``instances`` list.
+
+An example config file is provided in `config.example.yaml <onionbalance/data/config.example.yaml>`_. If you have used the ``onionbalance-config`` tool you can simply use the generated config file at ``master/config.yaml``.
+
+Running
+~~~~~~~
+
+
+You can start the management server once your backend onion service instances are running. The management server must be left running to publish descriptors for your onion service.
+
+::
+
+    $ onionbalance -c config.yaml
+
+Multiple OnionBalance management servers can be run to make your service more resilient and remove a single point of failure. Each redundant server should be run with the same private key and config file.
+
+Use Cases
+---------
+
+- A popular onion service with an overloaded web server or Tor process
+
+  A service such as Facebook which gets a large number of users would like to distribute client requests across multiple servers as the load is too much for a single Tor instance to handle. They would also like to balance between instances when the 'encrypted services' proposal is implemented [2555].
+
+- Redundancy and automatic failover
+
+  A political activist would like to keep their web service accessible and secure in the event that the secret police seize some of their servers. Clients should ideally automatically fail-over to another online instances with minimal service disruption.
+
+- 'Shared Hosting' scenarios
+
+  A hosting provider wishes to allow their customers to access their shared hosting control panel over an encrypted onion service. Rather than creating an individual onion service (with corresponding overhead) for thousands of customers, the host could instead run one onion service. Multiple service descriptors could then be published under unique customer onion addresses which would then be routed to that users control panel. This could also enable a low-resourced OnionFlare-type implem [...]
+
+- Secure Onion Service Key storage
+
+  An onion service operator would like to compartmentalize their permanent onion key in a secure location separate to their Tor process and other services. With this proposal permanent keys could be stored on an independent, isolated system.
+
+Contact
+-------
+
+This software is under active development and likely contains many bugs. Please open bugs on Github if you discover any issues with the software or documentation.
+
+I can also be contacted by PGP email or on IRC at ``#onionbalance`` on the OFTC network.
+
+::
+
+    pub   4096R/0x3B0D706A7FBFED86 2013-06-27 [expires: 2016-07-11]
+          Key fingerprint = 7EFB DDE8 FD21 11AE A7BE  1AA6 3B0D 706A 7FBF ED86
+    uid                 [ultimate] Donncha O'Cearbhaill <donncha at donncha.is>
+    sub   3072R/0xD60D64E73458F285 2013-06-27 [expires: 2016-07-11]
+    sub   3072R/0x7D49FC2C759AA659 2013-06-27 [expires: 2016-07-11]
+    sub   3072R/0x2C9C6F4ABBFCF7DD 2013-06-27 [expires: 2016-07-11]
+
+.. |build-status| image:: https://img.shields.io/travis/DonnchaC/onionbalance.svg?style=flat
+    :alt: build status
+    :scale: 100%
+    :target: https://travis-ci.org/DonnchaC/onionbalance
+
+.. |docs| image:: https://readthedocs.org/projects/onionbalance/badge/?version=latest
+    :alt: Documentation Status
+    :scale: 100%
+    :target: https://onionbalance.readthedocs.org/en/latest/
diff --git a/docs/Makefile b/docs/Makefile
new file mode 100644
index 0000000..a7806c1
--- /dev/null
+++ b/docs/Makefile
@@ -0,0 +1,192 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS    =
+SPHINXBUILD   = sphinx-build
+PAPER         =
+BUILDDIR      = _build
+
+# User-friendly check for sphinx-build
+ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
+$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
+endif
+
+# Internal variables.
+PAPEROPT_a4     = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
+
+help:
+	@echo "Please use \`make <target>' where <target> is one of"
+	@echo "  html       to make standalone HTML files"
+	@echo "  dirhtml    to make HTML files named index.html in directories"
+	@echo "  singlehtml to make a single large HTML file"
+	@echo "  pickle     to make pickle files"
+	@echo "  json       to make JSON files"
+	@echo "  htmlhelp   to make HTML files and a HTML help project"
+	@echo "  qthelp     to make HTML files and a qthelp project"
+	@echo "  applehelp  to make an Apple Help Book"
+	@echo "  devhelp    to make HTML files and a Devhelp project"
+	@echo "  epub       to make an epub"
+	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
+	@echo "  latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
+	@echo "  text       to make text files"
+	@echo "  man        to make manual pages"
+	@echo "  texinfo    to make Texinfo files"
+	@echo "  info       to make Texinfo files and run them through makeinfo"
+	@echo "  gettext    to make PO message catalogs"
+	@echo "  changes    to make an overview of all changed/added/deprecated items"
+	@echo "  xml        to make Docutils-native XML files"
+	@echo "  pseudoxml  to make pseudoxml-XML files for display purposes"
+	@echo "  linkcheck  to check all external links for integrity"
+	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"
+	@echo "  coverage   to run coverage check of the documentation (if enabled)"
+
+clean:
+	rm -rf $(BUILDDIR)/*
+
+html:
+	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+	@echo
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+	@echo
+	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+	@echo
+	@echo "Build finished; now you can process the pickle files."
+
+json:
+	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+	@echo
+	@echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+	@echo
+	@echo "Build finished; now you can run HTML Help Workshop with the" \
+	      ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+	@echo
+	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
+	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/onionbalance.qhcp"
+	@echo "To view the help file:"
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/onionbalance.qhc"
+
+applehelp:
+	$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
+	@echo
+	@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
+	@echo "N.B. You won't be able to view it unless you put it in" \
+	      "~/Library/Documentation/Help or install it in your application" \
+	      "bundle."
+
+devhelp:
+	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+	@echo
+	@echo "Build finished."
+	@echo "To view the help file:"
+	@echo "# mkdir -p $$HOME/.local/share/devhelp/onionbalance"
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/onionbalance"
+	@echo "# devhelp"
+
+epub:
+	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+	@echo
+	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo
+	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+	@echo "Run \`make' in that directory to run these through (pdf)latex" \
+	      "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo "Running LaTeX files through pdflatex..."
+	$(MAKE) -C $(BUILDDIR)/latex all-pdf
+	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+latexpdfja:
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+	@echo "Running LaTeX files through platex and dvipdfmx..."
+	$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
+	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+	@echo
+	@echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+	@echo
+	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+texinfo:
+	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+	@echo
+	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
+	@echo "Run \`make' in that directory to run these through makeinfo" \
+	      "(use \`make info' here to do that automatically)."
+
+info:
+	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+	@echo "Running Texinfo files through makeinfo..."
+	make -C $(BUILDDIR)/texinfo info
+	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
+
+gettext:
+	$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
+	@echo
+	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
+
+changes:
+	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+	@echo
+	@echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+	@echo
+	@echo "Link check complete; look for any errors in the above output " \
+	      "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+	@echo "Testing of doctests in the sources finished, look at the " \
+	      "results in $(BUILDDIR)/doctest/output.txt."
+
+coverage:
+	$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
+	@echo "Testing of coverage in the sources finished, look at the " \
+	      "results in $(BUILDDIR)/coverage/python.txt."
+
+xml:
+	$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
+	@echo
+	@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
+
+pseudoxml:
+	$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
+	@echo
+	@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000..c1c26a2
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,380 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+#
+# onionbalance documentation build configuration file, created by
+# sphinx-quickstart on Wed Jun 10 13:54:42 2015.
+#
+# This file is execfile()d with the current directory set to its
+# containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys
+import os
+import datetime
+
+import sphinx.environment
+from docutils.utils import get_source_line
+
+# Documentation configuration
+__version__ = '0.1.2'
+__author__ = "Donncha O'Cearbhaill"
+__contact__ = "donncha at donncha.is"
+
+# Ignore the 'dev' version suffix.
+if __version__.endswith('dev'):
+    __version__ = __version__[:-4]
+
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+sys.path.insert(0, os.path.abspath('..'))
+
+# -- General configuration ------------------------------------------------
+
+
+# Don't give warning for external images
+def _warn_node(self, msg, node):
+    if not msg.startswith('nonlocal image URI found:'):
+        self._warnfunc(msg, '%s:%s' % get_source_line(node))
+sphinx.environment.BuildEnvironment.warn_node = _warn_node
+
+# If your documentation needs a minimal Sphinx version, state it here.
+needs_sphinx = '1.1'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+    'sphinx.ext.autodoc',
+    'sphinx.ext.todo',
+    'sphinx.ext.viewcode',
+    'sphinx.ext.doctest',
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+# source_suffix = ['.rst', '.md']
+source_suffix = '.rst'
+
+# The encoding of source files.
+source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = 'OnionBalance'
+copyright = '{}, {}'.format(datetime.datetime.now().year, __author__)
+author = __author__
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = __version__[:__version__.rfind(".")]
+# The full version, including alpha/beta/rc tags.
+release = __version__
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = 'en'
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build', 'modules.rst']
+
+# The reST default role (used for this markup: `text`) to use for all
+# documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+# If true, keep warnings as "system message" paragraphs in the built documents.
+#keep_warnings = False
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = True
+
+
+# -- Options for HTML output ----------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  See the documentation for
+# a list of builtin themes.
+html_theme = 'alabaster'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further.  For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar.  Default is the same as html_title.
+html_short_title = "OnionBalance Docs"
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = []
+
+# Add any extra paths that contain custom files (such as robots.txt or
+# .htaccess) here, relative to this directory. These files are copied
+# directly to the root of the documentation.
+#html_extra_path = []
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+html_show_sphinx = False
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it.  The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Language to be used for generating the HTML full-text search index.
+# Sphinx supports the following languages:
+#   'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
+#   'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
+#html_search_language = 'en'
+
+# A dictionary with options for the search language support, empty by default.
+# Now only 'ja' uses this config value
+#html_search_options = {'type': 'default'}
+
+# The name of a javascript file (relative to the configuration directory) that
+# implements a search results scorer. If empty, the default will be used.
+#html_search_scorer = 'scorer.js'
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'onionbalancedoc'
+
+# -- Options for LaTeX output ---------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+
+# Latex figure (float) alignment
+#'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+#  author, documentclass [howto, manual, or own class]).
+latex_documents = [
+  (master_doc, 'onionbalance.tex', 'OnionBalance Documentation',
+   [author], 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output ---------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+    (master_doc, 'OnionBalance', 'OnionBalance Documentation',
+     ['%s (%s)' % (__author__, __contact__)], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output -------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+#  dir menu entry, description, category)
+texinfo_documents = [
+  (master_doc, 'OnionBalance', 'OnionBalance Documentation',
+   author, 'OnionBalance', 'Tool for distributing Tor onion services '
+   'connections to multiple backend Tor instances', 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
+
+# If true, do not generate a @detailmenu in the "Top" node's menu.
+#texinfo_no_detailmenu = False
+
+
+# -- Options for Epub output ----------------------------------------------
+
+# Bibliographic Dublin Core info.
+epub_title = project
+epub_author = author
+epub_publisher = author
+epub_copyright = copyright
+
+# The basename for the epub file. It defaults to the project name.
+#epub_basename = project
+
+# The HTML theme for the epub output. Since the default themes are not optimized
+# for small screen space, using the same theme for HTML and epub output is
+# usually not wise. This defaults to 'epub', a theme designed to save visual
+# space.
+#epub_theme = 'epub'
+
+# The language of the text. It defaults to the language option
+# or 'en' if the language is not set.
+#epub_language = ''
+
+# The scheme of the identifier. Typical schemes are ISBN or URL.
+#epub_scheme = ''
+
+# The unique identifier of the text. This can be a ISBN number
+# or the project homepage.
+#epub_identifier = ''
+
+# A unique identification for the text.
+#epub_uid = ''
+
+# A tuple containing the cover image and cover page html template filenames.
+#epub_cover = ()
+
+# A sequence of (type, uri, title) tuples for the guide element of content.opf.
+#epub_guide = ()
+
+# HTML files that should be inserted before the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_pre_files = []
+
+# HTML files shat should be inserted after the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_post_files = []
+
+# A list of files that should not be packed into the epub file.
+epub_exclude_files = ['search.html']
+
+# The depth of the table of contents in toc.ncx.
+#epub_tocdepth = 3
+
+# Allow duplicate toc entries.
+#epub_tocdup = True
+
+# Choose between 'default' and 'includehidden'.
+#epub_tocscope = 'default'
+
+# Fix unsupported image types using the Pillow.
+#epub_fix_images = False
+
+# Scale large images.
+#epub_max_image_width = 0
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#epub_show_urls = 'inline'
+
+# If false, no index is generated.
+#epub_use_index = True
diff --git a/docs/design.rst b/docs/design.rst
new file mode 100644
index 0000000..0cb6321
--- /dev/null
+++ b/docs/design.rst
@@ -0,0 +1,263 @@
+Design Document
+===============
+
+This tool is designed to allow requests to Tor onion service to be
+directed to multiple back-end Tor instances, thereby increasing
+availability and reliability. The design involves collating the set of
+introduction points created by one or more independent Tor onion service
+instances into a single 'master' descriptor.
+
+Overview
+--------
+
+This tool is designed to allow requests to Tor onion service to be
+directed to multiple back-end Tor instances, thereby increasing
+availability and reliability. The design involves collating the set of
+introduction points created by one or more independent Tor onion service
+instances into a single 'master' onion service descriptor.
+
+The master descriptor is signed by the onion service permanent key and
+published to the HSDir system as normal.
+
+Clients who wish to access the onion service would then retrieve the
+*master* service descriptor and try to connect to introduction points
+from the descriptor in a random order. If a client successfully
+establishes an introduction circuit, they can begin communicating with
+one of the onion services instances with the normal onion service
+protocol defined in rend-spec.txt
+
+Instance
+  A load-balancing node running an individual onion service.
+Introduction Point
+  A Tor relay chosen by an onion service instance as a medium-term
+  *meeting-place* for initial client connections.
+Master Descriptor
+  An onion service descriptor published with the desired onion address
+  containing introduction points for each instance.
+Management Server
+  Server running OnionBalance which collates introduction points and
+  publishes a master descriptor.
+Metadata Channel
+  A direct connection from an instance to a management server which can
+  be used for instance descriptor upload and transfer of other data.
+
+Retrieving Introduction Point Data
+----------------------------------
+
+The core functionality of the OnionBalance service is the collation of
+introduction point data from multiple onion service instances by the
+management server.
+
+Basic Mode
+~~~~~~~~~~
+
+In the 'Basic mode` of operation, the introduction point information is
+transferred from the onion service instances to the management server
+via the HSDir system. Each instance runs an onion service with an
+instance specific permanent key. The instance publishes a descriptor to
+the DHT at regularly intervals or when its introduction point set
+changes.
+
+On initial startup the management server will load the previously
+published master descriptor from the DHT if it exists. The master
+descriptor is used to prepopulate the introduction point set. The
+management server regularly polls the HSDir system for a descriptor for
+each of its instances. Currently polling occurs every 10 minutes. This
+polling period can be tuned for hidden services with shorter or longer
+lasting introduction points.
+
+When the management server receives a new descriptor from the HSDir
+system, it should before a number of checks to ensure that it is valid:
+
+-  Confirm that the descriptor has a valid signature and that the public
+   key matches the instance that was requested.
+-  Confirm that the descriptor timestamp is equal or newer than the
+   previously received descriptor for that hidden service instance. This
+   reduces the ability of a HSDir to replay older descriptors for an
+   instance which may contain expired introduction points.
+-  Confirm that the descriptor timestamp is not more than 4 hours in the
+   past. An older descriptor indicates that the instance may no longer
+   be online and publishing descriptors. The instance should not be
+   included in the master descriptor.
+
+It should be possible for two or more independent management servers to
+publish descriptors for a single onion service. The servers would
+publish independent descriptors which will replace each other on the
+HSDir system.. Any difference in introduction point selection between
+descriptors should not impact the end user.
+
+Limitations
+'''''''''''
+
+-  A malicious HSDir could replay old instance descriptors in an attempt
+   to include expired introduction points in the master descriptor.
+   When an attacker does not control all of the responsible HSDirs this
+   attack can be mitigated by not accepting descriptors with a timestamp
+   older than the most recently retrieved descriptor.
+
+-  The management server may also retrieve an old instance descriptor as
+   a result of churn in the DHT. The management server may attempt to
+   fetch the instance descriptor from a different set of HSDirs than the
+   instance published to.
+
+-  An onion service instance may rapidly rotate its introduction point
+   circuits when subjected to a Denial of Service attack. An
+   introduction point circuit is closed by the onion service when it has
+   received ``max_introductions`` for that circuit. During DoS this
+   circuit rotating may occur faster than the management server polls
+   the HSDir system for new descriptors. As a result clients may
+   retrieve master descriptors which contain no currently valid
+   introduction points.
+
+-  It is trivial for a HSDir to determine that a onion service is using
+   OnionBalance when in Basic mode. OnionBalance will try poll for
+   instance descriptors on a regular basis. A HSDir which connects to
+   onion services published to it would find that a backend instance is
+   serving the same content as the master service. This allows a HSDir
+   to trivially determine the onion addresses for a service's backend
+   instances.
+
+
+Basic mode allows for scaling across multiple onion service
+instances with no additional software or Tor modifications necessary
+on the onion service instance. Basic mode does not hide that a
+service is using OnionBalance. It also does not significantly
+protect a service from introduction point denial of service or
+actively malicious HSDirs.
+
+Complex Mode
+~~~~~~~~~~~~
+
+In Complex mode, introduction point information is uploaded directly from
+each instance to the management server via an onion service. The onion
+service instance does not publishing it's onion service descriptor to the
+HSDir system.
+
+A descriptor is uploaded from an instance to it's management servers
+each time Tor generates a new onion service descriptor. A simple daemon
+running on the onion service instance listens for the event emitted on
+the Tor control port when a onion service descriptor is generated. The
+daemon should retrieve the descriptor from the service's local
+descriptor cache and upload it to one or more management servers
+configured for that onion service. The protocol for the metadata channel
+is not yet defined.
+
+The metadata channel should authorize connecting instance clients using
+``basic`` or ``stealth`` authorization.
+
+Multiple management servers for the same onion service may communicate
+with each other via a hidden service channel. This extra channel can be
+used to signal when any of the management servers becomes unavailable. A
+slave management server may begin publishing service descriptors if it's
+master management server is no longer available.
+
+Complex mode requires additional software to be run on the service
+instances. It also requires more complicated communication via a
+metadata channel. In practice, this metadata channel may be less
+reliable than the HSDir system.
+
+.. note ::
+    The management server communication channel is not implemented yet. The
+    Complex Mode design may be revised significantly before implementation.
+
+Complex mode minimizes the information transmitted via the HSDir
+system and may make it more difficult for a HSDir to determine that
+a service is using OnionBalance. It also makes it more difficult for
+an active malicious HSDir to carry out descriptor replay attacks or
+otherwise interfere with the transfer of introduction point
+information. The management server is notified about new
+introduction points shortly after they are created which will result
+in more recent descriptor data during very high load or
+denial-of-service situations.
+
+Choice of Introduction Points
+-----------------------------
+
+Tor onion service descriptors can include a maximum of 10 introduction
+points. OnionBalance should select introduction points so as to
+uniformly distribute load across the available backend instances.
+
+-  **1 instance** - 3 IPs
+-  **2 instance** - 6 IPs (3 IPs from each instance)
+-  **3 instance** - 9 IPs (3 IPs from each instance)
+-  **4 instance** - 10 IPs (3 IPs from one instance, 2 from each other
+   instance)
+-  **5 instance** - 10 IPs (2 IPs from each instance)
+-  **6-9 instances** - 10 IPs (selection from all instances)
+-  **10 or more instances** - 1 IP from a random selection of 10
+   instances.
+
+If running in Complex mode, introduction points can be selected so as to
+obscure that a service is using OnionBalance. Always attempting to
+choose 3 introduction points per descriptor may make it more difficult
+for a passive observer to confirm that a service is running
+OnionBalance. However behavioral characteristics such as the rate of
+introduction point rotation may still allow a passive observer to
+distinguish an OnionBalance service from a standard Tor onion service.
+Selecting a smaller set of introduction points may impact on performance
+or reliability of the service.
+
+-  **1 instance**  - 3 IPs
+-  **2 instances** - 3 IPs (2 IPs from one instance, 1 IP from the other
+   instance)
+-  **3 instances** - 3 IPs (1 IP from each instance)
+-  **more than 3 instances** - Select the maximum set of introduction
+   points as outlined previously.
+
+It may be advantageous to select introduction points in a non-random
+manner. The longest-lived introduction points published by a backend
+instance are likely to be stable. Conversely selecting more recently
+created introduction points may more evenly distribute client
+introductions across an instances introduction point circuits. Further
+investigation of these options should indicate if there is significant
+advantages to any of these approaches.
+
+Generation and Publication of Master Descriptor
+-----------------------------------------------
+
+The management server should generate a onion service descriptor
+containing the selected introduction points. This master descriptor is
+then signed by the actual onion service permanent key. The signed master
+descriptor should be published to the responsible HSDirs as normal.
+
+Clients who wish to access the onion service would then retrieve the
+'master' service descriptor and begin connect to introduction points at
+random from the introduction point list. After successful introduction
+the client will have created an onion service circuit to one of the
+available onion services instances and can then begin communicating as
+normally along that circuit.
+
+Next-Generation Onion Services (Prop 224) Compatibility
+-------------------------------------------------------
+
+In the next-generation onion service proposal (Prop224), introduction
+point keys will no longer be independent of the instance/descriptor
+permanent key. The proposal specifies that each introduction point
+authentication key cross-certifies the descriptor's blinded public key.
+Each instance must know the master descriptor blinded public key during
+descriptor generation.
+
+One solution is to operate in the Complex mode described previously.
+Each instance is provided with the descriptor signing key derived from
+the same master identity key. Each introduction point authentication key
+will then cross-certify the same blinded public key. The generated
+service descriptors are not uploaded to the HSDir system. Instead the
+descriptors are passed to the management server where introduction
+points are selected and a master descriptor is published.
+
+Alternatively a Tor control port command could be implemented to allow a
+controller to request a onion service descriptor which has each
+introduction point authentication key cross-certify a blinded public key
+provided in the control port command. This would remove the need to
+provide any master service private keys to backend instances.
+
+The descriptor signing keys specified in Prop224 are valid for a limited
+period of time. As a result the compromise of a descriptor signing key
+does not lead to permanent compromise of the onion service
+
+.. TODO: Tidy up this section
+
+Implementation
+-------------------------------------------------------
+
+**TODO**
diff --git a/docs/index.rst b/docs/index.rst
new file mode 100644
index 0000000..239d974
--- /dev/null
+++ b/docs/index.rst
@@ -0,0 +1,32 @@
+.. onionbalance documentation master file, created by
+   sphinx-quickstart on Wed Jun 10 13:54:42 2015.
+   You can adapt this file completely to your liking, but it should at least
+   contain the root `toctree` directive.
+
+.. include:: ../README.rst
+
+----
+
+
+Contents
+========
+
+.. toctree::
+   :maxdepth: 2
+
+   onionbalance
+   design
+
+Todo List
+=========
+
+.. todolist::
+
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
diff --git a/docs/make.bat b/docs/make.bat
new file mode 100644
index 0000000..32b6264
--- /dev/null
+++ b/docs/make.bat
@@ -0,0 +1,263 @@
+ at ECHO OFF
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+	set SPHINXBUILD=sphinx-build
+)
+set BUILDDIR=_build
+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
+set I18NSPHINXOPTS=%SPHINXOPTS% .
+if NOT "%PAPER%" == "" (
+	set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
+	set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
+)
+
+if "%1" == "" goto help
+
+if "%1" == "help" (
+	:help
+	echo.Please use `make ^<target^>` where ^<target^> is one of
+	echo.  html       to make standalone HTML files
+	echo.  dirhtml    to make HTML files named index.html in directories
+	echo.  singlehtml to make a single large HTML file
+	echo.  pickle     to make pickle files
+	echo.  json       to make JSON files
+	echo.  htmlhelp   to make HTML files and a HTML help project
+	echo.  qthelp     to make HTML files and a qthelp project
+	echo.  devhelp    to make HTML files and a Devhelp project
+	echo.  epub       to make an epub
+	echo.  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter
+	echo.  text       to make text files
+	echo.  man        to make manual pages
+	echo.  texinfo    to make Texinfo files
+	echo.  gettext    to make PO message catalogs
+	echo.  changes    to make an overview over all changed/added/deprecated items
+	echo.  xml        to make Docutils-native XML files
+	echo.  pseudoxml  to make pseudoxml-XML files for display purposes
+	echo.  linkcheck  to check all external links for integrity
+	echo.  doctest    to run all doctests embedded in the documentation if enabled
+	echo.  coverage   to run coverage check of the documentation if enabled
+	goto end
+)
+
+if "%1" == "clean" (
+	for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
+	del /q /s %BUILDDIR%\*
+	goto end
+)
+
+
+REM Check if sphinx-build is available and fallback to Python version if any
+%SPHINXBUILD% 2> nul
+if errorlevel 9009 goto sphinx_python
+goto sphinx_ok
+
+:sphinx_python
+
+set SPHINXBUILD=python -m sphinx.__init__
+%SPHINXBUILD% 2> nul
+if errorlevel 9009 (
+	echo.
+	echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+	echo.installed, then set the SPHINXBUILD environment variable to point
+	echo.to the full path of the 'sphinx-build' executable. Alternatively you
+	echo.may add the Sphinx directory to PATH.
+	echo.
+	echo.If you don't have Sphinx installed, grab it from
+	echo.http://sphinx-doc.org/
+	exit /b 1
+)
+
+:sphinx_ok
+
+
+if "%1" == "html" (
+	%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The HTML pages are in %BUILDDIR%/html.
+	goto end
+)
+
+if "%1" == "dirhtml" (
+	%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
+	goto end
+)
+
+if "%1" == "singlehtml" (
+	%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
+	goto end
+)
+
+if "%1" == "pickle" (
+	%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished; now you can process the pickle files.
+	goto end
+)
+
+if "%1" == "json" (
+	%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished; now you can process the JSON files.
+	goto end
+)
+
+if "%1" == "htmlhelp" (
+	%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished; now you can run HTML Help Workshop with the ^
+.hhp project file in %BUILDDIR%/htmlhelp.
+	goto end
+)
+
+if "%1" == "qthelp" (
+	%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished; now you can run "qcollectiongenerator" with the ^
+.qhcp project file in %BUILDDIR%/qthelp, like this:
+	echo.^> qcollectiongenerator %BUILDDIR%\qthelp\onionbalance.qhcp
+	echo.To view the help file:
+	echo.^> assistant -collectionFile %BUILDDIR%\qthelp\onionbalance.ghc
+	goto end
+)
+
+if "%1" == "devhelp" (
+	%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished.
+	goto end
+)
+
+if "%1" == "epub" (
+	%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The epub file is in %BUILDDIR%/epub.
+	goto end
+)
+
+if "%1" == "latex" (
+	%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
+	goto end
+)
+
+if "%1" == "latexpdf" (
+	%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+	cd %BUILDDIR%/latex
+	make all-pdf
+	cd %~dp0
+	echo.
+	echo.Build finished; the PDF files are in %BUILDDIR%/latex.
+	goto end
+)
+
+if "%1" == "latexpdfja" (
+	%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+	cd %BUILDDIR%/latex
+	make all-pdf-ja
+	cd %~dp0
+	echo.
+	echo.Build finished; the PDF files are in %BUILDDIR%/latex.
+	goto end
+)
+
+if "%1" == "text" (
+	%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The text files are in %BUILDDIR%/text.
+	goto end
+)
+
+if "%1" == "man" (
+	%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The manual pages are in %BUILDDIR%/man.
+	goto end
+)
+
+if "%1" == "texinfo" (
+	%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
+	goto end
+)
+
+if "%1" == "gettext" (
+	%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
+	goto end
+)
+
+if "%1" == "changes" (
+	%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.The overview file is in %BUILDDIR%/changes.
+	goto end
+)
+
+if "%1" == "linkcheck" (
+	%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Link check complete; look for any errors in the above output ^
+or in %BUILDDIR%/linkcheck/output.txt.
+	goto end
+)
+
+if "%1" == "doctest" (
+	%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Testing of doctests in the sources finished, look at the ^
+results in %BUILDDIR%/doctest/output.txt.
+	goto end
+)
+
+if "%1" == "coverage" (
+	%SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Testing of coverage in the sources finished, look at the ^
+results in %BUILDDIR%/coverage/python.txt.
+	goto end
+)
+
+if "%1" == "xml" (
+	%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The XML files are in %BUILDDIR%/xml.
+	goto end
+)
+
+if "%1" == "pseudoxml" (
+	%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
+	if errorlevel 1 exit /b 1
+	echo.
+	echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
+	goto end
+)
+
+:end
diff --git a/docs/modules.rst b/docs/modules.rst
new file mode 100644
index 0000000..3b162c7
--- /dev/null
+++ b/docs/modules.rst
@@ -0,0 +1,7 @@
+onionbalance
+============
+
+.. toctree::
+   :maxdepth: 4
+
+   onionbalance
diff --git a/docs/onionbalance.config.rst b/docs/onionbalance.config.rst
new file mode 100644
index 0000000..bf11771
--- /dev/null
+++ b/docs/onionbalance.config.rst
@@ -0,0 +1,7 @@
+onionbalance.config module
+==========================
+
+.. automodule:: onionbalance.config
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.descriptor.rst b/docs/onionbalance.descriptor.rst
new file mode 100644
index 0000000..9e8b911
--- /dev/null
+++ b/docs/onionbalance.descriptor.rst
@@ -0,0 +1,7 @@
+onionbalance.descriptor module
+==============================
+
+.. automodule:: onionbalance.descriptor
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.eventhandler.rst b/docs/onionbalance.eventhandler.rst
new file mode 100644
index 0000000..41007bb
--- /dev/null
+++ b/docs/onionbalance.eventhandler.rst
@@ -0,0 +1,7 @@
+onionbalance.eventhandler module
+================================
+
+.. automodule:: onionbalance.eventhandler
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.instance.rst b/docs/onionbalance.instance.rst
new file mode 100644
index 0000000..37c5cbd
--- /dev/null
+++ b/docs/onionbalance.instance.rst
@@ -0,0 +1,7 @@
+onionbalance.instance module
+============================
+
+.. automodule:: onionbalance.instance
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.log.rst b/docs/onionbalance.log.rst
new file mode 100644
index 0000000..852f459
--- /dev/null
+++ b/docs/onionbalance.log.rst
@@ -0,0 +1,7 @@
+onionbalance.log module
+=======================
+
+.. automodule:: onionbalance.log
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.manager.rst b/docs/onionbalance.manager.rst
new file mode 100644
index 0000000..a75460e
--- /dev/null
+++ b/docs/onionbalance.manager.rst
@@ -0,0 +1,7 @@
+onionbalance.manager module
+===========================
+
+.. automodule:: onionbalance.manager
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.rst b/docs/onionbalance.rst
new file mode 100644
index 0000000..40e9053
--- /dev/null
+++ b/docs/onionbalance.rst
@@ -0,0 +1,26 @@
+onionbalance package
+====================
+
+Submodules
+----------
+
+.. toctree::
+
+   onionbalance.config
+   onionbalance.descriptor
+   onionbalance.eventhandler
+   onionbalance.instance
+   onionbalance.log
+   onionbalance.manager
+   onionbalance.schedule
+   onionbalance.service
+   onionbalance.settings
+   onionbalance.util
+
+Module contents
+---------------
+
+.. automodule:: onionbalance
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.schedule.rst b/docs/onionbalance.schedule.rst
new file mode 100644
index 0000000..51da931
--- /dev/null
+++ b/docs/onionbalance.schedule.rst
@@ -0,0 +1,7 @@
+onionbalance.schedule module
+============================
+
+.. automodule:: onionbalance.schedule
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.service.rst b/docs/onionbalance.service.rst
new file mode 100644
index 0000000..2265722
--- /dev/null
+++ b/docs/onionbalance.service.rst
@@ -0,0 +1,7 @@
+onionbalance.service module
+===========================
+
+.. automodule:: onionbalance.service
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.settings.rst b/docs/onionbalance.settings.rst
new file mode 100644
index 0000000..f84ef35
--- /dev/null
+++ b/docs/onionbalance.settings.rst
@@ -0,0 +1,7 @@
+onionbalance.settings module
+============================
+
+.. automodule:: onionbalance.settings
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/docs/onionbalance.util.rst b/docs/onionbalance.util.rst
new file mode 100644
index 0000000..0a96ca4
--- /dev/null
+++ b/docs/onionbalance.util.rst
@@ -0,0 +1,7 @@
+onionbalance.util module
+========================
+
+.. automodule:: onionbalance.util
+    :members:
+    :undoc-members:
+    :show-inheritance:
diff --git a/onionbalance.py b/onionbalance.py
new file mode 100755
index 0000000..e4e2109
--- /dev/null
+++ b/onionbalance.py
@@ -0,0 +1,9 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""Convenience wrapper for running OnionBalance directly from source tree."""
+
+from onionbalance.manager import main
+
+if __name__ == '__main__':
+    main()
diff --git a/onionbalance/__init__.py b/onionbalance/__init__.py
new file mode 100644
index 0000000..62d2014
--- /dev/null
+++ b/onionbalance/__init__.py
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+
+__version__ = "0.1.2"
+__author__ = "Donncha O'Cearbhaill"
+__contact__ = "donncha at donncha.is"
+__url__ = "https://github.com/DonnchaC/onionbalance"
+__license__ = "GPL"
diff --git a/onionbalance/__main__.py b/onionbalance/__main__.py
new file mode 100644
index 0000000..120122b
--- /dev/null
+++ b/onionbalance/__main__.py
@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+
+from onionbalance.manager import main
+
+
+if __name__ == "__main__":
+    main()
diff --git a/onionbalance/config.py b/onionbalance/config.py
new file mode 100644
index 0000000..458f502
--- /dev/null
+++ b/onionbalance/config.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+
+"""
+Define default config options for the management server
+"""
+
+# Set default configuration options for the management server
+
+REPLICAS = 2
+MAX_INTRO_POINTS = 10
+DESCRIPTOR_VALIDITY_PERIOD = 24 * 60 * 60
+DESCRIPTOR_OVERLAP_PERIOD = 60 * 60
+DESCRIPTOR_UPLOAD_PERIOD = 60 * 60  # Re-upload descriptor every hour
+REFRESH_INTERVAL = 10 * 60
+PUBLISH_CHECK_INTERVAL = 5 * 60
+
+# Store global data about onion services and their instance nodes.
+services = []
diff --git a/onionbalance/data/config.example.yaml b/onionbalance/data/config.example.yaml
new file mode 100644
index 0000000..fc2905b
--- /dev/null
+++ b/onionbalance/data/config.example.yaml
@@ -0,0 +1,16 @@
+# Onion Load Balancer Config File
+# ---
+# Each hidden service key line should be followed be followed by a list of 0
+# or more instances which contain the onion address of the load balancing
+# HS and any authentication data needed to access that HS.
+
+REFRESH_INTERVAL: 600 # How often to poll for updated descriptors
+services:
+    - key: /path/to/private_key # 7s4hxwwifcslrus2.onion
+      instances:
+        - address: o6ff73vmigi4oxka # srv1
+        - address: nkz23ai6qesuwqhc # srv2
+          auth: dCmx3qIvArbil8A0KM4KgQ== # Hidden service authentication key
+    - key: /path/to/private_key.enc # dpkdeys3apjtqydk.onion
+      instances:
+        - address: htbzowpp5cn7wj2u # srv3
diff --git a/onionbalance/data/torrc-instance b/onionbalance/data/torrc-instance
new file mode 100644
index 0000000..a861853
--- /dev/null
+++ b/onionbalance/data/torrc-instance
@@ -0,0 +1,17 @@
+# Tor config for the onion service instance servers
+# ---
+# The instance servers run standard onion services. In Basic mode the
+# control port does not need to be enabled.
+
+DataDirectory tor-data
+
+# ControlPort 9051
+# CookieAuthentication 1
+SocksPort 0
+
+# RunAsDaemon 1
+
+# Configure each onion service instance with a unique permanent key.
+# HiddenServiceDir tor-data/hidden_service/
+# HiddenServicePort 80 127.0.0.1:80
+
diff --git a/onionbalance/data/torrc-server b/onionbalance/data/torrc-server
new file mode 100644
index 0000000..d25edfc
--- /dev/null
+++ b/onionbalance/data/torrc-server
@@ -0,0 +1,13 @@
+# Tor config for the management server
+# ---
+# The management server must be able to access the Tor control port.
+# Alternatively the control port can be enabled on the system Tor process.
+
+DataDirectory tor-data
+
+ControlPort 9051
+CookieAuthentication 1
+SocksPort 0
+
+# RunAsDaemon 1
+
diff --git a/onionbalance/descriptor.py b/onionbalance/descriptor.py
new file mode 100644
index 0000000..b24460f
--- /dev/null
+++ b/onionbalance/descriptor.py
@@ -0,0 +1,290 @@
+# -*- coding: utf-8 -*-
+import hashlib
+import base64
+import textwrap
+import datetime
+import random
+
+import Crypto.Util.number
+import stem
+
+from onionbalance import util
+from onionbalance import log
+from onionbalance import config
+
+logger = log.get_logger()
+
+
+def choose_introduction_point_set(available_introduction_points):
+    """
+    Select a set introduction points to included in a HS descriptor.
+
+    Provided with a list of available introduction points for each
+    backend instance for an onionbalance service.
+
+    Introduciton points are selected to try and achieve the greatest
+    distribution of introduction points across all of the available backend
+    instances.
+
+    Return a list of IntroductionPoints.
+    """
+
+    # Shuffle the instance order before beginning to pick intro points
+    random.shuffle(available_introduction_points)
+
+    num_active_instances = len(available_introduction_points)
+    ips_per_instance = [len(ips) for ips in available_introduction_points]
+    num_intro_points = sum(ips_per_instance)
+
+    # Choose up to `MAX_INTRO_POINTS` IPs from the service instances. If less
+    # than `MAX_INTRO_POINTS` IPs are available, we should pick all available
+    # IP's
+    max_introduction_points = min(num_intro_points,
+                                  config.MAX_INTRO_POINTS)
+
+    # Determine the maximum number of IP's which can be selected from
+    # each instance to give the widest distribution of introduction
+    # point
+    pos = 0
+    intro_selection = [0] * num_active_instances
+
+    # Keep looping until we have selected enough introduction points
+    while sum(intro_selection) < max_introduction_points:
+        # Check if the current instance has more IPs available
+        if(ips_per_instance[pos] - intro_selection[pos] > 0):
+            intro_selection[pos] += 1
+        # Increment and wrap the pointer to the current instance
+        pos = ((pos + 1) % num_active_instances)
+
+    # intro_selection now lists the count/number of IPs to select from each
+    # instance. We now sample the determined number of IPs from the IPs
+    # available for each instance.
+    choosen_intro_points = []
+    for count, intros in zip(intro_selection, available_introduction_points):
+        choosen_intro_points.extend(random.sample(intros, count))
+
+    # Shuffle choosen IP's to try reveal less information about which
+    # instances are online and have introduction points included.
+    random.shuffle(choosen_intro_points)
+
+    return choosen_intro_points
+
+
+def generate_service_descriptor(permanent_key, introduction_point_list=None,
+                                replica=0, timestamp=None, deviation=0):
+    """
+    High-level interface for generating a signed HS descriptor
+    """
+
+    if not timestamp:
+        timestamp = datetime.datetime.utcnow()
+    unix_timestamp = int(timestamp.strftime("%s"))
+
+    permanent_key_block = make_public_key_block(permanent_key)
+    permanent_id = util.calc_permanent_id(permanent_key)
+
+    # Calculate the current secret-id-part for this hidden service
+    # Deviation allows the generation of a descriptor for a different time
+    # period.
+    time_period = (util.get_time_period(unix_timestamp, permanent_id)
+                   + int(deviation))
+
+    secret_id_part = util.calc_secret_id_part(time_period, None, replica)
+    descriptor_id = util.calc_descriptor_id(permanent_id, secret_id_part)
+
+    if not introduction_point_list:
+        onion_address = util.calc_onion_address(permanent_key)
+        raise ValueError("No introduction points for service %s.onion." %
+                         onion_address)
+
+    # Generate the introduction point section of the descriptor
+    intro_section = make_introduction_points_part(
+        introduction_point_list
+    )
+
+    unsigned_descriptor = generate_hs_descriptor_raw(
+        desc_id_base32=util.base32_encode_str(descriptor_id),
+        permanent_key_block=permanent_key_block,
+        secret_id_part_base32=util.base32_encode_str(secret_id_part),
+        publication_time=util.rounded_timestamp(timestamp),
+        introduction_points_part=intro_section
+    )
+
+    signed_descriptor = sign_descriptor(unsigned_descriptor, permanent_key)
+    return signed_descriptor
+
+
+def generate_hs_descriptor_raw(desc_id_base32, permanent_key_block,
+                               secret_id_part_base32, publication_time,
+                               introduction_points_part):
+    """
+    Generate hidden service descriptor string
+    """
+    doc = [
+        "rendezvous-service-descriptor {}".format(desc_id_base32),
+        "version 2",
+        "permanent-key",
+        permanent_key_block,
+        "secret-id-part {}".format(secret_id_part_base32),
+        "publication-time {}".format(publication_time),
+        "protocol-versions 2,3",
+        "introduction-points",
+        introduction_points_part,
+        "signature\n",
+    ]
+
+    unsigned_descriptor = '\n'.join(doc)
+    return unsigned_descriptor
+
+
+def make_introduction_points_part(introduction_point_list=None):
+    """
+    Make introduction point block from list of IntroductionPoint objects
+    """
+
+    # If no intro points were specified, we should create an empty list
+    if not introduction_point_list:
+        introduction_point_list = []
+
+    intro = []
+    for intro_point in introduction_point_list:
+        intro.append("introduction-point {}".format(intro_point.identifier))
+        intro.append("ip-address {}".format(intro_point.address))
+        intro.append("onion-port {}".format(intro_point.port))
+        intro.append("onion-key")
+        intro.append(intro_point.onion_key)
+        intro.append("service-key")
+        intro.append(intro_point.service_key)
+
+    intro_section = '\n'.join(intro).encode('utf-8')
+    intro_section_base64 = base64.b64encode(intro_section).decode('utf-8')
+    intro_section_base64 = textwrap.fill(intro_section_base64, 64)
+
+    # Add the header and footer:
+    intro_points_with_headers = '\n'.join([
+        '-----BEGIN MESSAGE-----',
+        intro_section_base64,
+        '-----END MESSAGE-----'])
+    return intro_points_with_headers
+
+
+def make_public_key_block(key):
+    """
+    Get ASN.1 representation of public key, base64 and add headers
+    """
+    asn1_pub = util.get_asn1_sequence(key)
+    pub_base64 = base64.b64encode(asn1_pub).decode('utf-8')
+    pub_base64 = textwrap.fill(pub_base64, 64)
+
+    # Add the header and footer:
+    pub_with_headers = '\n'.join([
+        '-----BEGIN RSA PUBLIC KEY-----',
+        pub_base64,
+        '-----END RSA PUBLIC KEY-----'])
+    return pub_with_headers
+
+
+def sign_digest(digest, private_key):
+    """
+    Sign, base64 encode, wrap and add Tor signature headers
+
+    The message digest is PKCS1 padded without the optional
+    algorithmIdentifier section.
+    """
+
+    digest = util.add_pkcs1_padding(digest)
+    (signature_long, ) = private_key.sign(digest, None)
+    signature_bytes = Crypto.Util.number.long_to_bytes(signature_long, 128)
+    signature_base64 = base64.b64encode(signature_bytes).decode('utf-8')
+    signature_base64 = textwrap.fill(signature_base64, 64)
+
+    # Add the header and footer:
+    signature_with_headers = '\n'.join([
+        '-----BEGIN SIGNATURE-----',
+        signature_base64,
+        '-----END SIGNATURE-----'])
+    return signature_with_headers
+
+
+def sign_descriptor(descriptor, service_key):
+    """
+    Sign or resign a provided hidden service descriptor
+    """
+    token_descriptor_signature = '\nsignature\n'
+
+    # Remove signature block if it exists
+    if token_descriptor_signature in descriptor:
+        descriptor = descriptor[:descriptor.find(token_descriptor_signature)
+                                + len(token_descriptor_signature)]
+    else:
+        descriptor = descriptor.strip() + token_descriptor_signature
+
+    descriptor_digest = hashlib.sha1(descriptor.encode('utf-8')).digest()
+    signature_with_headers = sign_digest(descriptor_digest, service_key)
+    return descriptor + signature_with_headers
+
+
+def descriptor_received(descriptor_content):
+    """
+    Process onion service descriptors retrieved from the HSDir system or
+    received directly over the metadata channel.
+    """
+
+    try:
+        parsed_descriptor = stem.descriptor.hidden_service_descriptor.\
+            HiddenServiceDescriptor(descriptor_content, validate=True)
+    except ValueError:
+        logger.exception("Received an invalid service descriptor.")
+        return None
+
+    # Ensure the received descriptor matches the requested descriptor
+    permanent_key = Crypto.PublicKey.RSA.importKey(
+        parsed_descriptor.permanent_key)
+    descriptor_onion_address = util.calc_onion_address(permanent_key)
+
+    # Find the HS instance for this descriptor
+    for service in config.services:
+        for instance in service.instances:
+            if instance.onion_address == descriptor_onion_address:
+                # Update the descriptor and exit
+                instance.update_descriptor(parsed_descriptor)
+                return None
+
+    # No matching service instance was found for the descriptor
+    logger.debug("Received a descriptor for an unknown service:\n%s",
+                 descriptor_content.decode('utf-8'))
+    logger.warning("Received a descriptor with address %s.onion that "
+                   "did not match any configured service instances.",
+                   descriptor_onion_address)
+
+    return None
+
+
+def upload_descriptor(controller, signed_descriptor, hsdirs=None):
+    """
+    Upload descriptor via the Tor control port
+
+    If no HSDir's are specified, Tor will upload to what it thinks are the
+    responsible directories
+    """
+    logger.debug("Beginning service descriptor upload.")
+
+    # Provide server fingerprints to control command if HSDirs are specified.
+    if hsdirs:
+        server_args = ' '.join([("SERVER={}".format(hsdir))
+                                for hsdir in hsdirs])
+    else:
+        server_args = ""
+
+    # Stem will insert the leading + and trailing '\r\n.\r\n'
+    response = controller.msg("HSPOST%s\n%s" %
+                              (server_args, signed_descriptor))
+
+    (response_code, divider, response_content) = response.content()[0]
+    if not response.is_ok():
+        if response_code == "552":
+            raise stem.InvalidRequest(response_code, response_content)
+        else:
+            raise stem.ProtocolError("HSPOST returned unexpected response "
+                                     "code: %s\n%s" % (response_code,
+                                                       response_content))
diff --git a/onionbalance/eventhandler.py b/onionbalance/eventhandler.py
new file mode 100644
index 0000000..dc049de
--- /dev/null
+++ b/onionbalance/eventhandler.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+from builtins import str, object
+
+from onionbalance import log
+from onionbalance import descriptor
+
+logger = log.get_logger()
+
+
+class EventHandler(object):
+
+    """
+    Handles asynchronous Tor events.
+    """
+
+    @staticmethod
+    def new_desc(desc_event):
+        """
+        Parse HS_DESC response events
+        """
+        logger.debug("Received new HS_DESC event: %s", str(desc_event))
+
+    @staticmethod
+    def new_desc_content(desc_content_event):
+        """
+        Parse HS_DESC_CONTENT response events for descriptor content
+
+        Update the HS instance object with the data from the new descriptor.
+        """
+        logger.debug("Received new HS_DESC_CONTENT event for %s.onion",
+                     desc_content_event.address)
+
+        #  Check that the HSDir returned a descriptor that is not empty
+        descriptor_text = str(desc_content_event.descriptor).encode('utf-8')
+
+        # HSDir's provide a HS_DESC_CONTENT response with either one or two
+        # CRLF lines when they do not have a matching descriptor. Using
+        # len() < 5 should ensure all empty HS_DESC_CONTENT events are matched.
+        if len(descriptor_text) < 5:
+            logger.debug("Empty descriptor received for %s.onion",
+                         desc_content_event.address)
+            return None
+
+        # Send content to callback function which will process the descriptor
+        descriptor.descriptor_received(descriptor_text)
+
+        return None
diff --git a/onionbalance/instance.py b/onionbalance/instance.py
new file mode 100644
index 0000000..ba6f2ff
--- /dev/null
+++ b/onionbalance/instance.py
@@ -0,0 +1,114 @@
+# -*- coding: utf-8 -*-
+import datetime
+import time
+
+import stem.control
+
+from onionbalance import log
+from onionbalance import config
+
+logger = log.get_logger()
+
+
+def fetch_instance_descriptors(controller):
+    """
+    Try fetch fresh descriptors for all HS instances
+    """
+    logger.info("Initiating fetch of descriptors for all service instances.")
+
+    # Clear Tor descriptor cache before making fetches by sending NEWNYM
+    # pylint: disable=no-member
+    controller.signal(stem.control.Signal.NEWNYM)
+    time.sleep(5)
+
+    for service in config.services:
+        for instance in service.instances:
+            instance.fetch_descriptor()
+
+
+class Instance(object):
+    """
+    Instance represents a back-end load balancing hidden service.
+    """
+
+    def __init__(self, controller, onion_address, authentication_cookie=None):
+        """
+        Initialise an Instance object.
+        """
+        self.controller = controller
+
+        # Onion address for the service instance.
+        self.onion_address = onion_address
+        self.authentication_cookie = authentication_cookie
+
+        # Store the latest set of introduction points for this instance
+        self.introduction_points = []
+
+        # Timestamp when last received a descriptor for this instance
+        self.received = None
+
+        # Timestamp of the currently loaded descriptor
+        self.timestamp = None
+
+        # Flag this instance with it's introduction points change. A new
+        # master descriptor will then be published as the introduction
+        # points have changed.
+        self.changed_since_published = False
+
+    def fetch_descriptor(self):
+        """
+        Try fetch a fresh descriptor for this service instance from the HSDirs
+        """
+        logger.debug("Trying to fetch a descriptor for instance %s.onion.",
+                     self.onion_address)
+        try:
+            self.controller.get_hidden_service_descriptor(self.onion_address,
+                                                          await_result=False)
+        except stem.DescriptorUnavailable:
+            # Could not find the descriptor on the HSDir
+            self.received = None
+            logger.warning("No descriptor received for instance %s.onion, "
+                           "the instance may be offline.", self.onion_address)
+
+    def update_descriptor(self, parsed_descriptor):
+        """
+        Update introduction points when a new HS descriptor is received
+
+        Parse the descriptor content and update the set of introduction
+        points for this HS instance.
+        """
+
+        self.received = datetime.datetime.utcnow()
+
+        logger.debug("Received a descriptor for instance %s.onion.",
+                     self.onion_address)
+
+        # Reject descriptor if its timestamp is older than the current
+        # descriptor. Prevent's HSDir's replaying old, expired descriptors.
+        if self.timestamp and parsed_descriptor.published < self.timestamp:
+            logger.error("Received descriptor for instance %s.onion with "
+                         "publication timestamp older than the latest "
+                         "descriptor. Ignoring the descriptor.",
+                         self.onion_address)
+            return
+        else:
+            self.timestamp = parsed_descriptor.published
+
+        # Parse the introduction point list, decrypting if necessary
+        introduction_points = parsed_descriptor.introduction_points(
+            authentication_cookie=self.authentication_cookie
+        )
+
+        # If the new introduction points are different, flag this instance
+        # as modified. Compare the set of introduction point identifiers
+        # (fingerprint of the per IP circuit service key).
+        if (set(ip.identifier for ip in introduction_points) !=
+                set(ip.identifier for ip in self.introduction_points)):
+            logger.info("The introduction point set has changed for instance "
+                        "%s.onion.", self.onion_address)
+            self.changed_since_published = True
+            self.introduction_points = introduction_points
+
+        else:
+            logger.debug("Introduction points for instance %s.onion matched "
+                         "the cached set.", self.onion_address)
diff --git a/onionbalance/log.py b/onionbalance/log.py
new file mode 100644
index 0000000..f498eac
--- /dev/null
+++ b/onionbalance/log.py
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+import logging
+
+handler = logging.StreamHandler()
+handler.setFormatter(logging.Formatter(fmt="%(asctime)s [%(levelname)s]: "
+                                           "%(message)s"))
+
+logger = logging.getLogger("onionbalance")
+logger.addHandler(handler)
+logger.setLevel(logging.DEBUG)
+
+
+def get_logger():
+    """
+    Returns a logger.
+    """
+    return logger
+
+
+def get_config_generator_logger():
+    """
+    Simplified logger for interactive config generator CLI
+    """
+    handler = logging.StreamHandler()
+    handler.setFormatter(logging.Formatter(fmt="[%(levelname)s]: "
+                                               "%(message)s"))
+
+    logger = logging.getLogger("onionbalance-config")
+    logger.addHandler(handler)
+    logger.setLevel(logging.INFO)
+    return logger
diff --git a/onionbalance/manager.py b/onionbalance/manager.py
new file mode 100644
index 0000000..7b7f66e
--- /dev/null
+++ b/onionbalance/manager.py
@@ -0,0 +1,125 @@
+# -*- coding: utf-8 -*-
+"""
+Load balance a hidden service across multiple (remote) Tor instances by
+create a hidden service descriptor containing introduction points from
+each instance.
+"""
+import sys
+import argparse
+import time
+import logging
+
+# import Crypto.PublicKey
+import stem
+from stem.control import Controller, EventType
+
+from onionbalance import log
+from onionbalance import settings
+from onionbalance import config
+from onionbalance import eventhandler
+from onionbalance import schedule
+
+import onionbalance.service
+import onionbalance.instance
+
+logger = log.get_logger()
+
+
+def parse_cmd_args():
+    """
+    Parses and returns command line arguments.
+    """
+
+    parser = argparse.ArgumentParser(
+        description="onionbalance distributes the requests for a Tor hidden "
+        "services across multiple Tor instances.")
+
+    parser.add_argument("-i", "--ip", type=str, default="127.0.0.1",
+                        help="Tor controller IP address")
+
+    parser.add_argument("-p", "--port", type=int, default=9051,
+                        help="Tor controller port")
+
+    parser.add_argument("-c", "--config", type=str,
+                        default="config.yaml", help="Config file location")
+
+    parser.add_argument("-v", "--verbosity", type=str, default="info",
+                        help="Minimum verbosity level for logging.  Available "
+                             "in ascending order: debug, info, warning, "
+                             "error, critical).  The default is info.")
+
+    return parser.parse_args()
+
+
+def main():
+    """
+    Entry point when invoked over the command line.
+    """
+    args = parse_cmd_args()
+    config_file_options = settings.parse_config_file(args.config)
+
+    # Update global configuration with options specified in the config file
+    for setting in dir(config):
+        if setting.isupper() and config_file_options.get(setting):
+            setattr(config, setting, config_file_options.get(setting))
+
+    logger.setLevel(logging.__dict__[args.verbosity.upper()])
+
+    # Create a connection to the Tor control port
+    try:
+        controller = Controller.from_port(address=args.ip, port=args.port)
+    except stem.SocketError as exc:
+        logger.error("Unable to connect to Tor control port: %s", exc)
+        sys.exit(1)
+    else:
+        logger.debug("Successfully connected to the Tor control port.")
+
+    try:
+        controller.authenticate()
+    except stem.connection.AuthenticationFailure as exc:
+        logger.error("Unable to authenticate to Tor control port: %s", exc)
+        sys.exit(1)
+    else:
+        logger.debug("Successfully authenticated to the Tor control port.")
+
+    # Disable no-member due to bug with "Instance of 'Enum' has no * member"
+    # pylint: disable=no-member
+
+    # Check that the Tor client supports the HSPOST control port command
+    if not controller.get_version() >= stem.version.Requirement.HSPOST:
+        logger.error("A Tor version >= %s is required. You may need to "
+                     "compile Tor from source or install a package from "
+                     "the experimental Tor repository.",
+                     stem.version.Requirement.HSPOST)
+        sys.exit(1)
+
+    # Load the keys and config for each onion service
+    settings.initialize_services(controller,
+                                 config_file_options.get('services'))
+
+    # Finished parsing all the config file.
+
+    handler = eventhandler.EventHandler()
+    controller.add_event_listener(handler.new_desc,
+                                  EventType.HS_DESC)
+    controller.add_event_listener(handler.new_desc_content,
+                                  EventType.HS_DESC_CONTENT)
+
+    # Schedule descriptor fetch and upload events
+    schedule.every(config.REFRESH_INTERVAL).seconds.do(
+        onionbalance.instance.fetch_instance_descriptors, controller)
+    schedule.every(config.PUBLISH_CHECK_INTERVAL).seconds.do(
+        onionbalance.service.publish_all_descriptors)
+
+    try:
+        # Run initial fetch of HS instance descriptors
+        schedule.run_all(delay_seconds=30)
+
+        # Begin main loop to poll for HS descriptors
+        while True:
+            schedule.run_pending()
+            time.sleep(1)
+    except KeyboardInterrupt:
+        logger.info("Keyboard interrupt received. Stopping the "
+                    "management server.")
+    return 0
diff --git a/onionbalance/schedule.py b/onionbalance/schedule.py
new file mode 100644
index 0000000..5b9e66d
--- /dev/null
+++ b/onionbalance/schedule.py
@@ -0,0 +1,416 @@
+# -*- coding: utf-8 -*-
+"""
+Python job scheduling for humans.
+
+An in-process scheduler for periodic jobs that uses the builder pattern
+for configuration. Schedule lets you run Python functions (or any other
+callable) periodically at pre-determined intervals using a simple,
+human-friendly syntax.
+
+Inspired by Addam Wiggins' article "Rethinking Cron" [1] and the
+"clockwork" Ruby module [2][3].
+
+Features:
+    - A simple to use API for scheduling jobs.
+    - Very lightweight and no external dependencies.
+    - Excellent test coverage.
+    - Works with Python 2.7 and 3.3
+
+Usage:
+    >>> import schedule
+    >>> import time
+
+    >>> def job(message='stuff'):
+    >>>     print("I'm working on:", message)
+
+    >>> schedule.every(10).minutes.do(job)
+    >>> schedule.every().hour.do(job, message='things')
+    >>> schedule.every().day.at("10:30").do(job)
+
+    >>> while True:
+    >>>     schedule.run_pending()
+    >>>     time.sleep(1)
+
+Copyright (c) 2013 Daniel Bader (http://dbader.org)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+[1] http://adam.heroku.com/past/2010/4/13/rethinking_cron/
+[2] https://github.com/tomykaira/clockwork
+[3] http://adam.heroku.com/past/2010/6/30/replace_cron_with_clockwork/
+"""
+import datetime
+import functools
+import logging
+import time
+
+logger = logging.getLogger('schedule')
+
+
+class CancelJob(object):
+    pass
+
+
+class Scheduler(object):
+    def __init__(self):
+        self.jobs = []
+
+    def run_pending(self):
+        """Run all jobs that are scheduled to run.
+
+        Please note that it is *intended behavior that tick() does not
+        run missed jobs*. For example, if you've registered a job that
+        should run every minute and you only call tick() in one hour
+        increments then your job won't be run 60 times in between but
+        only once.
+        """
+        runnable_jobs = (job for job in self.jobs if job.should_run)
+        for job in sorted(runnable_jobs):
+            self._run_job(job)
+
+    def run_all(self, delay_seconds=0):
+        """Run all jobs regardless if they are scheduled to run or not.
+
+        A delay of `delay` seconds is added between each job. This helps
+        distribute system load generated by the jobs more evenly
+        over time."""
+        logger.info('Running *all* %i jobs with %is delay inbetween',
+                    len(self.jobs), delay_seconds)
+        for job in self.jobs:
+            self._run_job(job)
+            time.sleep(delay_seconds)
+
+    def clear(self):
+        """Deletes all scheduled jobs."""
+        del self.jobs[:]
+
+    def cancel_job(self, job):
+        """Delete a scheduled job."""
+        try:
+            self.jobs.remove(job)
+        except ValueError:
+            pass
+
+    def every(self, interval=1):
+        """Schedule a new periodic job."""
+        job = Job(interval)
+        self.jobs.append(job)
+        return job
+
+    def _run_job(self, job):
+        ret = job.run()
+        if isinstance(ret, CancelJob) or ret is CancelJob:
+            self.cancel_job(job)
+
+    @property
+    def next_run(self):
+        """Datetime when the next job should run."""
+        if not self.jobs:
+            return None
+        return min(self.jobs).next_run
+
+    @property
+    def idle_seconds(self):
+        """Number of seconds until `next_run`."""
+        return (self.next_run - datetime.datetime.now()).total_seconds()
+
+
+class Job(object):
+    """A periodic job as used by `Scheduler`."""
+    def __init__(self, interval):
+        self.interval = interval  # pause interval * unit between runs
+        self.job_func = None  # the job job_func to run
+        self.unit = None  # time units, e.g. 'minutes', 'hours', ...
+        self.at_time = None  # optional time at which this job runs
+        self.last_run = None  # datetime of the last run
+        self.next_run = None  # datetime of the next run
+        self.period = None  # timedelta between runs, only valid for
+        self.start_day = None  # Specific day of the week to start on
+
+    def __lt__(self, other):
+        """PeriodicJobs are sortable based on the scheduled time
+        they run next."""
+        return self.next_run < other.next_run
+
+    def __repr__(self):
+        def format_time(t):
+            return t.strftime('%Y-%m-%d %H:%M:%S') if t else '[never]'
+
+        timestats = '(last run: %s, next run: %s)' % (
+                    format_time(self.last_run), format_time(self.next_run))
+
+        if hasattr(self.job_func, '__name__'):
+            job_func_name = self.job_func.__name__
+        else:
+            job_func_name = repr(self.job_func)
+        args = [repr(x) for x in self.job_func.args]
+        kwargs = ['%s=%s' % (k, repr(v))
+                  for k, v in self.job_func.keywords.items()]
+        call_repr = job_func_name + '(' + ', '.join(args + kwargs) + ')'
+
+        if self.at_time is not None:
+            return 'Every %s %s at %s do %s %s' % (
+                   self.interval,
+                   self.unit[:-1] if self.interval == 1 else self.unit,
+                   self.at_time, call_repr, timestats)
+        else:
+            return 'Every %s %s do %s %s' % (
+                   self.interval,
+                   self.unit[:-1] if self.interval == 1 else self.unit,
+                   call_repr, timestats)
+
+    @property
+    def second(self):
+        assert self.interval == 1
+        return self.seconds
+
+    @property
+    def seconds(self):
+        self.unit = 'seconds'
+        return self
+
+    @property
+    def minute(self):
+        assert self.interval == 1
+        return self.minutes
+
+    @property
+    def minutes(self):
+        self.unit = 'minutes'
+        return self
+
+    @property
+    def hour(self):
+        assert self.interval == 1
+        return self.hours
+
+    @property
+    def hours(self):
+        self.unit = 'hours'
+        return self
+
+    @property
+    def day(self):
+        assert self.interval == 1
+        return self.days
+
+    @property
+    def days(self):
+        self.unit = 'days'
+        return self
+
+    @property
+    def week(self):
+        assert self.interval == 1
+        return self.weeks
+
+    @property
+    def monday(self):
+        assert self.interval == 1
+        self.start_day = 'monday'
+        return self.weeks
+
+    @property
+    def tuesday(self):
+        assert self.interval == 1
+        self.start_day = 'tuesday'
+        return self.weeks
+
+    @property
+    def wednesday(self):
+        assert self.interval == 1
+        self.start_day = 'wednesday'
+        return self.weeks
+
+    @property
+    def thursday(self):
+        assert self.interval == 1
+        self.start_day = 'thursday'
+        return self.weeks
+
+    @property
+    def friday(self):
+        assert self.interval == 1
+        self.start_day = 'friday'
+        return self.weeks
+
+    @property
+    def saturday(self):
+        assert self.interval == 1
+        self.start_day = 'saturday'
+        return self.weeks
+
+    @property
+    def sunday(self):
+        assert self.interval == 1
+        self.start_day = 'sunday'
+        return self.weeks
+
+    @property
+    def weeks(self):
+        self.unit = 'weeks'
+        return self
+
+    def at(self, time_str):
+        """Schedule the job every day at a specific time.
+
+        Calling this is only valid for jobs scheduled to run every
+        N day(s).
+        """
+        assert self.unit in ('days', 'hours') or self.start_day
+        hour, minute = [t for t in time_str.split(':')]
+        minute = int(minute)
+        if self.unit == 'days' or self.start_day:
+            hour = int(hour)
+            assert 0 <= hour <= 23
+        elif self.unit == 'hours':
+            hour = 0
+        assert 0 <= minute <= 59
+        self.at_time = datetime.time(hour, minute)
+        return self
+
+    def do(self, job_func, *args, **kwargs):
+        """Specifies the job_func that should be called every time the
+        job runs.
+
+        Any additional arguments are passed on to job_func when
+        the job runs.
+        """
+        self.job_func = functools.partial(job_func, *args, **kwargs)
+        try:
+            functools.update_wrapper(self.job_func, job_func)
+        except AttributeError:
+            # job_funcs already wrapped by functools.partial won't have
+            # __name__, __module__ or __doc__ and the update_wrapper()
+            # call will fail.
+            pass
+        self._schedule_next_run()
+        return self
+
+    @property
+    def should_run(self):
+        """True if the job should be run now."""
+        return datetime.datetime.now() >= self.next_run
+
+    def run(self):
+        """Run the job and immediately reschedule it."""
+        logger.info('Running job %s', self)
+        ret = self.job_func()
+        self.last_run = datetime.datetime.now()
+        self._schedule_next_run()
+        return ret
+
+    def _schedule_next_run(self):
+        """Compute the instant when this job should run next."""
+        # Allow *, ** magic temporarily:
+        assert self.unit in ('seconds', 'minutes', 'hours', 'days', 'weeks')
+        self.period = datetime.timedelta(**{self.unit: self.interval})
+        self.next_run = datetime.datetime.now() + self.period
+        if self.start_day is not None:
+            assert self.unit == 'weeks'
+            weekdays = (
+                'monday',
+                'tuesday',
+                'wednesday',
+                'thursday',
+                'friday',
+                'saturday',
+                'sunday'
+            )
+            assert self.start_day in weekdays
+            weekday = weekdays.index(self.start_day)
+            days_ahead = weekday - self.next_run.weekday()
+            if days_ahead <= 0:  # Target day already happened this week
+                days_ahead += 7
+            self.next_run += datetime.timedelta(days_ahead) - self.period
+        if self.at_time is not None:
+            assert self.unit in ('days', 'hours') or self.start_day is not None
+            kwargs = {
+                'minute': self.at_time.minute,
+                'second': self.at_time.second,
+                'microsecond': 0
+            }
+            if self.unit == 'days' or self.start_day is not None:
+                kwargs['hour'] = self.at_time.hour
+            self.next_run = self.next_run.replace(**kwargs)
+            # If we are running for the first time, make sure we run
+            # at the specified time *today* (or *this hour*) as well
+            if not self.last_run:
+                now = datetime.datetime.now()
+                if (self.unit == 'days' and self.at_time > now.time() and
+                        self.interval == 1):
+                    self.next_run = self.next_run - datetime.timedelta(days=1)
+                elif self.unit == 'hours' and self.at_time.minute > now.minute:
+                    self.next_run = self.next_run - datetime.timedelta(hours=1)
+        if self.start_day is not None and self.at_time is not None:
+            # Let's see if we will still make that time we specified today
+            if (self.next_run - datetime.datetime.now()).days >= 7:
+                self.next_run -= self.period
+
+# The following methods are shortcuts for not having to
+# create a Scheduler instance:
+
+default_scheduler = Scheduler()
+jobs = default_scheduler.jobs  # todo: should this be a copy, e.g. jobs()?
+
+
+def every(interval=1):
+    """Schedule a new periodic job."""
+    return default_scheduler.every(interval)
+
+
+def run_pending():
+    """Run all jobs that are scheduled to run.
+
+    Please note that it is *intended behavior that run_pending()
+    does not run missed jobs*. For example, if you've registered a job
+    that should run every minute and you only call run_pending()
+    in one hour increments then your job won't be run 60 times in
+    between but only once.
+    """
+    default_scheduler.run_pending()
+
+
+def run_all(delay_seconds=0):
+    """Run all jobs regardless if they are scheduled to run or not.
+
+    A delay of `delay` seconds is added between each job. This can help
+    to distribute the system load generated by the jobs more evenly over
+    time."""
+    default_scheduler.run_all(delay_seconds=delay_seconds)
+
+
+def clear():
+    """Deletes all scheduled jobs."""
+    default_scheduler.clear()
+
+
+def cancel_job(job):
+    """Delete a scheduled job."""
+    default_scheduler.cancel_job(job)
+
+
+def next_run():
+    """Datetime when the next job should run."""
+    return default_scheduler.next_run
+
+
+def idle_seconds():
+    """Number of seconds until `next_run`."""
+    return default_scheduler.idle_seconds
diff --git a/onionbalance/service.py b/onionbalance/service.py
new file mode 100644
index 0000000..77e73de
--- /dev/null
+++ b/onionbalance/service.py
@@ -0,0 +1,196 @@
+# -*- coding: utf-8 -*-
+import datetime
+import time
+import base64
+
+import Crypto.PublicKey.RSA
+import stem
+
+from onionbalance import descriptor
+from onionbalance import util
+from onionbalance import log
+from onionbalance import config
+
+logger = log.get_logger()
+
+
+def publish_all_descriptors():
+    """
+    Called periodically to upload new super-descriptors if needed
+
+    .. todo:: Publishing descriptors for different services at the same time
+              will leak that they are related. Descriptors should
+              be published individually at a random interval to avoid
+              correlation.
+    """
+    logger.debug("Checking if any master descriptors should be published.")
+    for service in config.services:
+        service.descriptor_publish()
+
+
+class Service(object):
+    """
+    Service represents a front-facing hidden service which should
+    be load-balanced.
+    """
+
+    def __init__(self, controller, service_key=None, instances=None):
+        """
+        Initialise a HiddenService object.
+        """
+        self.controller = controller
+
+        # Service key must be a valid PyCrypto RSA key object
+        if isinstance(service_key, Crypto.PublicKey.RSA._RSAobj):
+            self.service_key = service_key
+        else:
+            raise ValueError("Service key is not a valid RSA object.")
+
+        # List of instances for this onion service
+        if not instances:
+            instances = []
+        self.instances = instances
+
+        # Calculate the onion address for this service
+        self.onion_address = util.calc_onion_address(self.service_key)
+
+        # Timestamp when this descriptor was last attempted
+        self.uploaded = None
+
+    def _intro_points_modified(self):
+        """
+        Check if the introduction point set has changed since last
+        publish.
+        """
+        return any(instance.changed_since_published
+                   for instance in self.instances)
+
+    def _descriptor_not_uploaded_recently(self):
+        """
+        Check if the master descriptor hasn't been uploaded recently
+        """
+        if not self.uploaded:
+            # Descriptor never uploaded
+            return True
+
+        descriptor_age = (datetime.datetime.utcnow() - self.uploaded)
+        if (descriptor_age.total_seconds() > config.DESCRIPTOR_UPLOAD_PERIOD):
+            return True
+        else:
+            return False
+
+    def _descriptor_id_changing_soon(self):
+        """
+        If the descriptor ID will change soon, upload under both descriptor IDs
+        """
+        permanent_id = base64.b32decode(self.onion_address, 1)
+        seconds_valid = util.get_seconds_valid(time.time(), permanent_id)
+
+        # Check if descriptor ID will be changing within the overlap period.
+        if seconds_valid < config.DESCRIPTOR_OVERLAP_PERIOD:
+            return True
+        else:
+            return False
+
+    def _select_introduction_points(self):
+        """
+        Choose set of introduction points from all fresh descriptors
+        """
+        available_intro_points = []
+
+        # Loop through each instance and determine fresh intro points
+        for instance in self.instances:
+            if not instance.received:
+                logger.info("No descriptor received for instance %s.onion "
+                            "yet.", instance.onion_address)
+                continue
+
+            # The instance may be offline if no descriptor has been received
+            # for it recently or if the received descriptor's timestamp is
+            # too old
+            received_age = datetime.datetime.utcnow() - instance.received
+            timestamp_age = datetime.datetime.utcnow() - instance.timestamp
+            received_age = received_age.total_seconds()
+            timestamp_age = timestamp_age.total_seconds()
+
+            if (received_age > config.DESCRIPTOR_UPLOAD_PERIOD or
+                    timestamp_age > (4 * 60 * 60)):
+                logger.info("Our descriptor for instance %s.onion is too old. "
+                            "The instance may be offline. It's introduction "
+                            "points will not be included in the master "
+                            "descriptor.", instance.onion_address)
+                continue
+            else:
+                # Include this instance's introduction points
+                instance.changed_since_published = False
+                available_intro_points.append(instance.introduction_points)
+
+        num_intro_points = sum(len(ips) for ips in available_intro_points)
+        choosen_intro_points = descriptor.choose_introduction_point_set(
+            available_intro_points)
+
+        logger.debug("Selected %d IPs of %d for service %s.onion.",
+                     len(choosen_intro_points), num_intro_points,
+                     self.onion_address)
+
+        return choosen_intro_points
+
+    def _publish_descriptor(self, deviation=0):
+        """
+        Create, sign and uploads a master descriptor for this service
+        """
+        introduction_points = self._select_introduction_points()
+        for replica in range(0, config.REPLICAS):
+            try:
+                signed_descriptor = descriptor.generate_service_descriptor(
+                    self.service_key,
+                    introduction_point_list=introduction_points,
+                    replica=replica,
+                    deviation=deviation
+                )
+            except ValueError as exc:
+                logger.warning("Error generating master descriptor: %s", exc)
+            else:
+                # Signed descriptor was generated successfully, upload it
+                try:
+                    descriptor.upload_descriptor(self.controller,
+                                                 signed_descriptor)
+                except stem.ControllerError:
+                    logger.exception("Error uploading descriptor for service "
+                                     "%s.onion.", self.onion_address)
+                else:
+                    logger.info("Published a descriptor for service "
+                                "%s.onion under replica %d.",
+                                self.onion_address, replica)
+
+        # It would be better to set last_uploaded when an upload succeeds and
+        # not when an upload is just attempted. Unfortunately the HS_DESC #
+        # UPLOADED event does not provide information about the service and
+        # so it can't be used to determine when descriptor upload succeeds
+        self.uploaded = datetime.datetime.utcnow()
+
+    def descriptor_publish(self, force_publish=False):
+        """
+        Publish descriptor if have new IP's or if descriptor has expired
+        """
+
+        # A descriptor should be published if any of the following conditions
+        # are True
+        if any([self._intro_points_modified(),  # If any IPs have changed
+                self._descriptor_not_uploaded_recently(),
+                force_publish]):
+
+            logger.debug("Publishing a descriptor for service %s.onion.",
+                         self.onion_address)
+            self._publish_descriptor()
+
+            # If the descriptor ID will change soon, need to upload under
+            # the new ID too.
+            if self._descriptor_id_changing_soon():
+                logger.info("Publishing a descriptor for service %s.onion "
+                            "under next descriptor ID.", self.onion_address)
+                self._publish_descriptor(deviation=1)
+
+        else:
+            logger.debug("Not publishing a new descriptor for service "
+                         "%s.onion.", self.onion_address)
diff --git a/onionbalance/settings.py b/onionbalance/settings.py
new file mode 100644
index 0000000..e39bbb0
--- /dev/null
+++ b/onionbalance/settings.py
@@ -0,0 +1,370 @@
+# -*- coding: utf-8 -*-
+
+"""
+Implements the generation and loading of configuration files.
+"""
+from builtins import input, range
+import os
+import sys
+import errno
+import argparse
+import getpass
+import logging
+import pkg_resources
+
+import yaml
+import Crypto.PublicKey
+
+from onionbalance import config
+from onionbalance import util
+from onionbalance import log
+
+import onionbalance.service
+import onionbalance.instance
+
+logger = log.get_logger()
+
+
+def parse_config_file(config_file):
+    """
+    Parse config file containing service information
+    """
+    config_path = os.path.abspath(config_file)
+    if os.path.exists(config_path):
+        with open(config_file, 'r') as handle:
+            config_data = yaml.load(handle.read())
+            logger.info("Loaded the config file '%s'.", config_path)
+    else:
+        logger.error("The specified config file '%s' does not exist. The "
+                     "onionbalance-config tool can generate the required "
+                     "keys and config files.", config_path)
+        sys.exit(1)
+
+    # Rewrite relative paths in the config to be relative to the config
+    # file directory
+    config_directory = os.path.dirname(config_path)
+    for service in config_data.get('services'):
+        if not os.path.isabs(service.get('key')):
+            service['key'] = os.path.join(config_directory, service['key'])
+
+    return config_data
+
+
+def initialize_services(controller, services_config):
+    """
+    Load keys for services listed in the config
+    """
+
+    # Load the keys and config for each onion service
+    for service in services_config:
+        try:
+            service_key = util.key_decrypt_prompt(service.get("key"))
+        except OSError as e:
+            if e.errno == errno.ENOENT:
+                logger.error("Private key file %s could not be found. "
+                             "Relative paths in the config file are loaded "
+                             "relative to the config file directory.",
+                             service.get("key"))
+                sys.exit(1)
+            else:
+                raise
+        # Key file was read but a valid private key was not found.
+        if not service_key:
+            logger.error("Private key %s could not be loaded. It is a not "
+                         "valid 1024 bit PEM encoded RSA private key",
+                         service.get("key"))
+            sys.exit(1)
+        else:
+            # Successfully imported the private key
+            onion_address = util.calc_onion_address(service_key)
+            logger.debug("Loaded private key for service %s.onion.",
+                         onion_address)
+
+        # Load all instances for the current onion service
+        instance_config = service.get("instances", [])
+        if not instance_config:
+            logger.error("Could not load and instances for service "
+                         "%s.onion.", onion_address)
+            sys.exit(1)
+        else:
+            instances = []
+            for instance in instance_config:
+                instances.append(onionbalance.instance.Instance(
+                    controller=controller,
+                    onion_address=instance.get("address"),
+                    authentication_cookie=instance.get("auth")
+                ))
+
+            logger.info("Loaded %d instances for service %s.onion.",
+                        len(instances), onion_address)
+
+        # Store service configuration in config.services global
+        config.services.append(onionbalance.service.Service(
+            controller=controller,
+            service_key=service_key,
+            instances=instances
+        ))
+
+
+def parse_cmd_args():
+    """
+    Parses and returns command line arguments for config generator
+    """
+
+    parser = argparse.ArgumentParser(
+        description="onionbalance-config generates config files and keys for "
+        "OnionBalance instances and management servers. Calling without any "
+        "options will initiate an interactive mode.")
+
+    parser.add_argument("--key", type=str, default=None,
+                        help="RSA private key for the master onion service.")
+
+    parser.add_argument("-p", "--password", type=str, default=None,
+                        help="Optional password which can be used to encrypt"
+                        "the master service private key.")
+
+    parser.add_argument("-n", type=int, default=2, dest="num_instances",
+                        help="Number of instances to generate (default: "
+                        "%(default)s).")
+
+    parser.add_argument("-t", "--tag", type=str, default='srv',
+                        help="Prefix name for the service instances "
+                        "(default: %(default)s).")
+
+    parser.add_argument("--output", type=str, default='config/',
+                        help="Directory to store generate config files. "
+                        "The directory will be created if it does not "
+                        "already exist.")
+
+    parser.add_argument("--no-interactive", action='store_true',
+                        help="Try to run automatically without prompting for"
+                        "user input.")
+
+    parser.add_argument("-v", type=str, default="info", dest='verbosity',
+                        help="Minimum verbosity level for logging. Available "
+                        "in ascending order: debug, info, warning, error, "
+                        "critical).  The default is info.")
+
+    parser.add_argument("--service-virtual-port", type=str,
+                        default="80",
+                        help="Onion service port for external client "
+                        "connections (default: %(default)s).")
+
+    # TODO: Add validator to check if the target host:port line makes sense.
+    parser.add_argument("--service-target", type=str,
+                        default="127.0.0.1:80",
+                        help="Target IP and port where your service is "
+                        "listening (default: %(default)s).")
+
+    # .. todo:: Add option to specify HS host and port for instance torrc
+
+    return parser.parse_args()
+
+
+def generate_config():
+    """
+    Entry point for interactive config file generation.
+    """
+
+    # Simplify the logging output for the command line tool
+    logger = log.get_config_generator_logger()
+
+    logger.info("Beginning OnionBalance config generation.")
+
+    # Parse initial command line options
+    args = parse_cmd_args()
+
+    # If CLI options have been provided, don't enter interactive mode
+    # Crude check to see if any options beside --verbosity are set.
+    verbose = True if '-v' in sys.argv else False
+
+    if ((len(sys.argv) > 1 and not verbose) or len(sys.argv) > 3 or
+            args.no_interactive):
+        interactive = False
+        logger.info("Entering non-interactive mode.")
+    else:
+        interactive = True
+        logger.info("No command line arguments found, entering interactive "
+                    "mode.")
+
+    logger.setLevel(logging.__dict__[args.verbosity.upper()])
+
+    # Check if output directory exists, if not try create it
+    output_path = None
+    if interactive:
+        output_path = input("Enter path to store generated config "
+                            "[{}]: ".format(os.path.abspath(args.output)))
+    output_path = output_path or args.output
+    try:
+        util.try_make_dir(output_path)
+    except OSError:
+        logger.exception("Problem encountered when trying to create the "
+                         "output directory %s.", os.path.abspath(output_path))
+    else:
+        logger.debug("Created the output directory '%s'.",
+                     os.path.abspath(output_path))
+
+    # The output directory should be empty to avoid having conflict keys
+    # or config files.
+    if not util.is_directory_empty(output_path):
+        logger.error("The specified output directory is not empty. Please "
+                     "delete any files and folders or specify another output "
+                     "directory.")
+        sys.exit(1)
+
+    # Load master key if specified
+    key_path = None
+    if interactive:
+        # Read key path from user
+        key_path = input("Enter path to master service private key "
+                         "(Leave empty to generate a key): ")
+    key_path = args.key or key_path
+    if key_path:
+        if not os.path.isfile(key_path):
+            logger.error("The specified master service private key '%s' "
+                         "could not be found. Please confirm the path and "
+                         "file permissions are correct.", key_path)
+            sys.exit(1)
+        else:
+            # Try load the specified private key file
+            master_key = util.key_decrypt_prompt(key_path)
+            if not master_key:
+                logger.error("The specified master private key %s could not "
+                             "be loaded.", os.path.abspath(master_key))
+                sys.exit(1)
+            else:
+                master_onion_address = util.calc_onion_address(master_key)
+                logger.info("Successfully loaded a master key for service "
+                            "%s.onion.", master_onion_address)
+
+    else:
+        # No key specified, begin generating a new one.
+        master_key = Crypto.PublicKey.RSA.generate(1024)
+        master_onion_address = util.calc_onion_address(master_key)
+        logger.debug("Created a new master key for service %s.onion.",
+                     master_onion_address)
+
+    # Finished loading/generating master key, now try generate keys for
+    # each service instance
+    num_instances = None
+    if interactive:
+        num_instances = input("Number of instance services to create "
+                              "[{}]: ".format(args.num_instances))
+        # Cast to int if a number was specified
+        try:
+            num_instances = int(num_instances)
+        except ValueError:
+            num_instances = None
+    num_instances = num_instances or args.num_instances
+    logger.debug("Creating %d service instances.", num_instances)
+
+    tag = None
+    if interactive:
+        tag = input("Provide a tag name to group these instances "
+                    "[{}]: ".format(args.tag))
+    tag = tag or args.tag
+
+    # Create HiddenServicePort line for instance torrc file
+    service_virtual_port = None
+    if interactive:
+        service_virtual_port = input("Specify the service virtual port (for "
+                                     "client connections) [{}]: ".format(
+                                         args.service_virtual_port))
+    service_virtual_port = service_virtual_port or args.service_virtual_port
+
+    service_target = None
+    if interactive:
+        # In interactive mode, change default target to match the specified
+        # virtual port
+        default_service_target = u'127.0.0.1:{}'.format(service_virtual_port)
+        service_target = input("Specify the service target IP and port (where "
+                               "your service is listening) [{}]: ".format(
+                                   default_service_target))
+        service_target = service_target or default_service_target
+    service_target = service_target or args.service_target
+    torrc_port_line = u'HiddenServicePort {} {}'.format(service_virtual_port,
+                                                        service_target)
+
+    instances = []
+    for i in range(0, num_instances):
+        instance_key = Crypto.PublicKey.RSA.generate(1024)
+        instance_address = util.calc_onion_address(instance_key)
+        logger.debug("Created a key for instance %s.onion.",
+                     instance_address)
+        instances.append((instance_address, instance_key))
+
+    # Write master service key to directory
+    master_passphrase = None
+    if interactive:
+        master_passphrase = getpass.getpass(
+            "Provide an optional password to encrypt the master private "
+            "key (Not encrypted if no password is specified): ")
+    master_passphrase = master_passphrase or args.password
+
+    # Finished reading input, starting to write config files.
+    master_dir = os.path.join(output_path, 'master')
+    util.try_make_dir(master_dir)
+    master_key_file = os.path.join(master_dir,
+                                   '{}.key'.format(master_onion_address))
+    with open(master_key_file, "wb") as key_file:
+        os.chmod(master_key_file, 384)  # chmod 0600 in decimal
+        key_file.write(master_key.exportKey(passphrase=master_passphrase))
+        logger.debug("Successfully wrote master key to file %s.",
+                     os.path.abspath(master_key_file))
+
+    # Create YAML OnionBalance settings file for these instances
+    service_data = {'key': '{}.key'.format(master_onion_address)}
+    service_data['instances'] = [{'address': address,
+                                  'name': '{}{}'.format(tag, i+1)} for
+                                 i, (address, _) in enumerate(instances)]
+    settings_data = {'services': [service_data]}
+    config_yaml = yaml.dump(settings_data, default_flow_style=False)
+
+    config_file_path = os.path.join(master_dir, 'config.yaml')
+    with open(config_file_path, "w") as config_file:
+        config_file.write(u"# OnionBalance Config File\n")
+        config_file.write(config_yaml)
+        logger.info("Wrote master service config file '%s'.",
+                    os.path.abspath(config_file_path))
+
+    # Write master service torrc
+    master_torrc_path = os.path.join(master_dir, 'torrc-server')
+    master_torrc_template = pkg_resources.resource_string(__name__,
+                                                          'data/torrc-server')
+    with open(master_torrc_path, "w") as master_torrc_file:
+        master_torrc_file.write(master_torrc_template.decode('utf-8'))
+
+    # Try generate config files for each service instance
+    for i, (instance_address, instance_key) in enumerate(instances):
+        # Create a numbered directory for instance
+        instance_dir = os.path.join(output_path, '{}{}'.format(tag, i+1))
+        instance_key_dir = os.path.join(instance_dir, instance_address)
+        util.try_make_dir(instance_key_dir)
+        os.chmod(instance_key_dir, 1472)  # chmod 2700 in decimal
+
+        instance_key_file = os.path.join(instance_key_dir, 'private_key')
+        with open(instance_key_file, "wb") as key_file:
+            os.chmod(instance_key_file, 384)  # chmod 0600 in decimal
+            key_file.write(instance_key.exportKey())
+            logger.debug("Successfully wrote key for instance %s.onion to "
+                         "file.", instance_address)
+
+        # Write torrc file for each instance
+        instance_torrc = os.path.join(instance_dir, 'instance_torrc')
+        instance_torrc_template = pkg_resources.resource_string(
+            __name__, 'data/torrc-instance')
+        with open(instance_torrc, "w") as torrc_file:
+            torrc_file.write(instance_torrc_template.decode('utf-8'))
+            # The ./ relative path prevents Tor from raising relative
+            # path warnings. The relative path may need to be edited manual
+            # to work on Windows systems.
+            torrc_file.write(u"HiddenServiceDir {}\n".format(
+                instance_address))
+            torrc_file.write(u"{}\n".format(torrc_port_line))
+
+    # Output final status message
+    logger.info("Done! Successfully generated an OnionBalance config and %d "
+                "instance keys for service %s.onion.",
+                num_instances, master_onion_address)
+
+    sys.exit(0)
diff --git a/onionbalance/util.py b/onionbalance/util.py
new file mode 100644
index 0000000..650e364
--- /dev/null
+++ b/onionbalance/util.py
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-
+import hashlib
+import struct
+import datetime
+import getpass
+import base64
+import binascii
+import os
+
+# import Crypto.Util
+import Crypto.PublicKey
+
+
+def add_pkcs1_padding(message):
+    """Add PKCS#1 padding to **message**."""
+    padding = b''
+    typeinfo = b'\x00\x01'
+    separator = b'\x00'
+    padding = b'\xFF' * (125 - len(message))
+    padded_message = typeinfo + padding + separator + message
+    assert len(padded_message) == 128
+    return padded_message
+
+
+def get_asn1_sequence(rsa_key):
+    seq = Crypto.Util.asn1.DerSequence()
+    seq.append(rsa_key.n)
+    seq.append(rsa_key.e)
+    asn1_seq = seq.encode()
+    return asn1_seq
+
+
+def calc_key_digest(rsa_key):
+    """Calculate the SHA1 digest of an RSA key"""
+    return hashlib.sha1(get_asn1_sequence(rsa_key)).digest()
+
+
+def calc_permanent_id(rsa_key):
+    return calc_key_digest(rsa_key)[:10]
+
+
+def calc_onion_address(rsa_key):
+    return base64.b32encode(calc_permanent_id(rsa_key)).decode().lower()
+
+
+def calc_descriptor_id(permanent_id, secret_id_part):
+    return hashlib.sha1(permanent_id + secret_id_part).digest()
+
+
+def get_time_period(time, permanent_id):
+    """
+    time-period = (current-time + permanent-id-byte * 86400 / 256) / 86400
+    """
+    permanent_id_byte = int(struct.unpack('B', permanent_id[0:1])[0])
+    return int((int(time) + permanent_id_byte * 86400 / 256) / 86400)
+
+
+def get_seconds_valid(time, permanent_id):
+    """
+    Calculate seconds until the descriptor ID changes
+    """
+    permanent_id_byte = int(struct.unpack('B', permanent_id[0:1])[0])
+    return 86400 - int((int(time) + permanent_id_byte * 86400 / 256) % 86400)
+
+
+def calc_secret_id_part(time_period, descriptor_cookie, replica):
+    """
+    secret-id-part = H(time-period | descriptor-cookie | replica)
+    """
+    secret_id_part = hashlib.sha1()
+    secret_id_part.update(struct.pack('>I', time_period)[:4])
+    if descriptor_cookie:
+        secret_id_part.update(descriptor_cookie)
+    secret_id_part.update(binascii.unhexlify('{0:02X}'.format(replica)))
+    return secret_id_part.digest()
+
+
+def rounded_timestamp(timestamp=None):
+    """
+    Create timestamp rounded down to the nearest hour
+    """
+    if not timestamp:
+        timestamp = datetime.datetime.utcnow()
+    timestamp = timestamp.replace(minute=0, second=0, microsecond=0)
+    return timestamp.strftime('%Y-%m-%d %H:%M:%S')
+
+
+def base32_encode_str(byte_str):
+    """
+    Encode bytes as lowercase base32 string
+    """
+    return base64.b32encode(byte_str).lower().decode('utf-8')
+
+
+def key_decrypt_prompt(key_file, retries=3):
+    """
+    Try open an PEM encrypted private key, prompting the user for a
+    passphrase if required.
+    """
+
+    key_passphrase = None
+    with open(key_file, 'rt') as handle:
+        pem_key = handle.read()
+
+        for retries in range(0, retries):
+            if "Proc-Type: 4,ENCRYPTED" in pem_key:  # Key looks encrypted
+                key_passphrase = getpass.getpass(
+                    "Enter the password for the private key (%s): " % key_file)
+            try:
+                rsa_key = Crypto.PublicKey.RSA.importKey(
+                    pem_key, passphrase=key_passphrase)
+            except ValueError:
+                # Key not decrypted correctly, prompt for passphrase again
+                continue
+            else:
+                # .. todo:: Check the loaded key size in a more reasonable way.
+                if rsa_key.has_private() and rsa_key.size() == (1023 or 1024):
+                    return rsa_key
+                else:
+                    raise ValueError("The specified key was not a 1024 bit "
+                                     "private key.")
+
+    # No private key was imported
+    raise ValueError("Could not import RSA key.")
+
+
+def try_make_dir(path):
+    """
+    Try to create a directory (including any parent directories)
+    """
+    try:
+        os.makedirs(path)
+    except OSError:
+        if not os.path.isdir(path):
+            raise
+
+
+def is_directory_empty(path):
+    """
+    Check if a directory contains any files or directories.
+    """
+    if os.listdir(path):
+        return False
+    else:
+        return True
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..5313a02
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,4 @@
+stem==1.4.1b
+PyYAML==3.11
+pycrypto==2.6.1
+future==0.14.3
diff --git a/scripts/rend-connection-stats.py b/scripts/rend-connection-stats.py
new file mode 100755
index 0000000..a8613ec
--- /dev/null
+++ b/scripts/rend-connection-stats.py
@@ -0,0 +1,146 @@
+# -*- coding: utf-8 -*-
+"""
+Log information about the number and rate of rendezvous connections to a HS.
+"""
+
+import sys
+import time
+import argparse
+import logging
+import logging.handlers
+import threading
+
+import stem
+from stem.control import Controller
+import schedule
+
+handler = logging.StreamHandler()
+formatter = logging.Formatter(fmt="%(asctime)s [%(levelname)s]: %(message)s")
+handler.setFormatter(formatter)
+
+logger = logging.getLogger("onionbalance")
+logger.addHandler(handler)
+logger.setLevel(logging.DEBUG)
+
+lock = threading.RLock()
+
+# Track circuits established in current time period.
+new_rend_circuits_established = 0
+rend_circuits_closed = 0
+
+
+def circ_event_handler(event):
+    """
+    Handle the event received when Tor emits an event related the a rendezvous
+    circuit
+    """
+    global new_rend_circuits_established, rend_circuits_closed
+
+    if event.purpose == "HS_SERVICE_REND" and event.hs_state == "HSSR_JOINED":
+        if event.type == "CIRC_MINOR":
+            # Log when a new rendezvous circuit is successfully established.
+            # A CIRC_MINOR event is emitted when the rendezvous circuit moves
+            # from HS_STATE=HSSR_CONNECTING to HS_STATE=HSSR_JOINED
+            logger.debug("New rendezvous circuit established (CircID: %s)",
+                         event.id)
+            new_rend_circuits_established += 1
+
+        elif event.type == "CIRC" and event.status == "CLOSED":
+            logger.debug("Rendezvous circuit closed (CircID: %s)", event.id)
+            rend_circuits_closed += 1
+    return
+
+
+def output_status(controller):
+    """
+    Output the current counts every tick period.
+    """
+    global new_rend_circuits_established, rend_circuits_closed
+
+    # Count number of currently established rendezvous circuits for this HS.
+    rend_circ_count = len([circ for circ in controller.get_circuits()
+                           if circ.purpose == "HS_SERVICE_REND"
+                           and circ.hs_state == "HSSR_JOINED"])
+
+    with lock:
+        logger.info("New rend circuits: %d - Closed rend circuits: %d - "
+                    "Established rend circuits: %d",
+                    new_rend_circuits_established,
+                    rend_circuits_closed,
+                    rend_circ_count)
+        new_rend_circuits_established = 0
+        rend_circuits_closed = 0
+
+    return None
+
+
+def parse_cmd_args():
+    """
+    Parses and returns command line arguments.
+    """
+
+    parser = argparse.ArgumentParser(
+        description="%s logs stats about Tor rendezvous circuits" %
+        sys.argv[0])
+
+    parser.add_argument("-i", "--ip", type=str, default="127.0.0.1",
+                        help="Tor controller IP address")
+
+    parser.add_argument("-p", "--port", type=int, default=9051,
+                        help="Tor controller port")
+
+    parser.add_argument("-t", "--tick", type=int, default=60,
+                        help="Output total every tick seconds "
+                        "(default: %(default)s)")
+
+    parser.add_argument("--log-file", type=str, default="rendezvous.log",
+                        help="Location to log the rendezvous connection"
+                        "data.")
+
+    parser.add_argument("-v", "--verbosity", type=str, default="info",
+                        help="Minimum verbosity level for logging.  Available "
+                             "in ascending order: debug, info, warning, "
+                             "error, critical).  The default is info.")
+
+    return parser.parse_args()
+
+
+def main():
+
+    args = parse_cmd_args()
+    logger.setLevel(logging.__dict__[args.verbosity.upper()])
+
+    if args.log_file:
+        file_handler = logging.handlers.TimedRotatingFileHandler(
+            args.log_file, when='D')
+        file_handler.setFormatter(formatter)
+        logger.addHandler(file_handler)
+
+    logger.info("Beginning rendezvous circuit monitoring."
+                "Status output every %d seconds", args.tick)
+
+    with Controller.from_port(port=args.port) as controller:
+        # Create a connection to the Tor control port
+        controller.authenticate()
+
+        # Add event listeners for HS_DESC and HS_DESC_CONTENT
+        controller.add_event_listener(circ_event_handler,
+                                      stem.control.EventType.CIRC)
+        controller.add_event_listener(circ_event_handler,
+                                      stem.control.EventType.CIRC_MINOR)
+
+        # Schedule rendezvous status output.
+        schedule.every(args.tick).seconds.do(output_status, controller)
+        schedule.run_all()
+
+        try:
+            while True:
+                schedule.run_pending()
+                time.sleep(1)
+        except KeyboardInterrupt:
+            logger.info("Stopping rendezvous circuit monitoring.")
+
+    sys.exit(0)
+
+if __name__ == '__main__':
+    main()
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..4562916
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,5 @@
+[pytest]
+norecursedirs = .tox _build tor chutney
+
+[bdist_wheel]
+universal=1
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..bc254fe
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,60 @@
+# -*- coding: utf-8 -*-
+
+"""setup.py: setuptools control."""
+
+import io
+import os
+
+from setuptools import setup
+
+# Read version and other info from package's __init.py file
+module_info = {}
+init_path = os.path.join(os.path.dirname(__file__), 'onionbalance',
+                         '__init__.py')
+with open(init_path) as init_file:
+    exec(init_file.read(), module_info)
+
+
+def read(*names, **kwargs):
+    return io.open(
+        os.path.join(os.path.dirname(__file__), *names),
+        encoding=kwargs.get("encoding", "utf8")
+    ).read()
+
+setup(
+    name="OnionBalance",
+    packages=["onionbalance"],
+    entry_points={
+        "console_scripts": [
+            'onionbalance = onionbalance.manager:main',
+            'onionbalance-config = onionbalance.settings:generate_config',
+        ]},
+    description="OnionBalance provides load-balancing and redundancy for Tor "
+                "hidden services by distributing requests to multiple backend "
+                "Tor instances.",
+    long_description=read('README.rst'),
+    version=module_info.get('__version__'),
+    author=module_info.get('__author__'),
+    author_email=module_info.get('__contact__'),
+    url=module_info.get('__url__'),
+    license=module_info.get('__license__'),
+    keywords='tor',
+    install_requires=[
+        'setuptools',
+        'stem>=1.4.0-dev',
+        'PyYAML>=3.11',
+        'pycrypto>=2.6.1',
+        'future>=0.14.0',
+        ],
+    tests_require=['tox', 'pytest-mock', 'pytest', 'mock', 'pexpect'],
+    package_data={'onionbalance': ['data/*']},
+    include_package_data=True,
+    classifiers=[
+        'Development Status :: 3 - Alpha',
+        'License :: OSI Approved :: GNU General Public License (GPL)',
+        'Programming Language :: Python :: 2',
+        'Programming Language :: Python :: 2.7',
+        'Programming Language :: Python :: 3',
+        'Programming Language :: Python :: 3.4',
+    ]
+)
diff --git a/test-requirements.txt b/test-requirements.txt
new file mode 100644
index 0000000..53d243a
--- /dev/null
+++ b/test-requirements.txt
@@ -0,0 +1,4 @@
+pytest
+mock
+pytest-mock
+pexpect
diff --git a/test/__init__.py b/test/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/test/functional/test_onionbalance_config.py b/test/functional/test_onionbalance_config.py
new file mode 100644
index 0000000..00a1729
--- /dev/null
+++ b/test/functional/test_onionbalance_config.py
@@ -0,0 +1,154 @@
+# -*- coding: utf-8 -*-
+"""
+Functional tests which run the onionbalance-config tool and check
+the created output files.
+"""
+import sys
+
+import pexpect
+import Crypto.PublicKey.RSA
+
+import onionbalance.util
+
+
+def onionbalance_config_interact(cli, cli_input):
+    """
+    Send each input line to the onionbalance-config CLI interface
+    """
+    cli.expect(u"store generated config")
+    cli.send("{}\n".format(cli_input.get('config_dir', u'')))
+
+    cli.expect(u"path to master service private key")
+    cli.send(u"{}\n".format(cli_input.get('private_key_path', u'')))
+
+    cli.expect(u"Number of instance services")
+    cli.send(u"{}\n".format(cli_input.get('num_instances', u'')))
+
+    cli.expect(u"Provide a tag name")
+    cli.send(u"{}\n".format(cli_input.get('tag_name', u'')))
+
+    cli.expect(u"service virtual port")
+    cli.send(u"{}\n".format(cli_input.get('virtual_port', u'')))
+
+    cli.expect(u"service target IP and port")
+    cli.send(u"{}\n".format(cli_input.get('target_ip', u'')))
+
+    cli.expect(u"optional password")
+    cli.send(u"{}\n".format(cli_input.get('password', u'')))
+
+    return None
+
+
+def check_basic_config_output(config_dir):
+    """
+    Run basic tests on the generated config files and keys to check
+    that they look reasonable.
+    """
+
+    assert len(config_dir.listdir()) == 1 + 2
+
+    # Find generated instance addresses
+    instance_addresses = []
+    for directory in config_dir.listdir():
+        if directory.basename != 'master':
+            instance_addresses.extend(
+                [str(name.basename) for name in directory.listdir()
+                 if 'torrc' not in name.basename])
+
+    # Correct number of directories created
+    assert len(config_dir.listdir()) == 1 + 2
+
+    assert config_dir.join('master', 'torrc-server').check()
+    assert config_dir.join('master', 'config.yaml').check()
+
+    config_file = config_dir.join('master', 'config.yaml').read_text('utf-8')
+    assert all(address in config_file for address in instance_addresses)
+
+    return True
+
+
+def test_onionbalance_config_interactive(tmpdir):
+    """
+    Functional test to run onion-balance config in interactive mode.
+    """
+    # Start onionbalance-config in interactive mode (no command line arguments)
+    cli = pexpect.spawnu("onionbalance-config", logfile=sys.stdout)
+    cli.expect(u"entering interactive mode")
+
+    # Interact with the running onionbalance-config process
+    onionbalance_config_interact(
+        cli, cli_input={'config_dir': str(tmpdir.join(u"configdir"))})
+    cli.expect(u"Done! Successfully generated")
+
+    check_basic_config_output(tmpdir.join(u"configdir"))
+
+
+def test_onionbalance_config_automatic(tmpdir):
+    """
+    Functional test to run onion-balance config in automatic mode.
+    """
+    # Start onionbalance-config in automatic mode
+    cli = pexpect.spawnu("onionbalance-config", logfile=sys.stdout,
+                         args=[
+                             '--output', str(tmpdir.join(u"configdir")),
+                         ])
+    cli.expect(u"Done! Successfully generated")
+
+    check_basic_config_output(tmpdir.join(u"configdir"))
+
+
+def test_onionbalance_config_automatic_custom_ports(tmpdir):
+    """
+    Run onionbalance-config in interactive mode, providing a custom port line.
+    """
+    cli = pexpect.spawnu("onionbalance-config", logfile=sys.stdout,
+                         args=[
+                             '--output', str(tmpdir.join(u"configdir")),
+                             '--service-virtual-port', u'443',
+                             '--service-target', u'127.0.0.1:8443',
+                         ])
+    cli.expect(u"Done! Successfully generated")
+
+    # Read one of the generated torrc files
+    for directory in tmpdir.join(u"configdir").listdir():
+        if directory.basename != 'master':
+            torrc_file = [name for name in directory.listdir()
+                          if name.basename == 'instance_torrc'][0]
+            break
+    assert torrc_file.check()
+
+    # Check torrc line contains the correct HiddenServicePort line
+    torrc_contents = torrc_file.read_text('utf-8')
+    assert u'HiddenServicePort 443 127.0.0.1:8443' in torrc_contents
+
+
+def test_onionbalance_config_automatic_key_with_password(tmpdir, mocker):
+    """
+    Run onionbalance-config with an existing key, export as password protected
+    key.
+    """
+
+    # Create input private_key
+    private_key = Crypto.PublicKey.RSA.generate(1024)
+    key_path = tmpdir.join('private_key')
+    key_path.write(private_key.exportKey())
+
+    # Start onionbalance-config in automatic mode
+    cli = pexpect.spawnu("onionbalance-config", logfile=sys.stdout,
+                         args=[
+                             '--output', str(tmpdir.join(u"configdir")),
+                             '--key', str(key_path),
+                             '--password', 'testpassword',
+                         ])
+    cli.expect(u"Done! Successfully generated")
+
+    # Check master config was generated with password protected key.
+    master_dir = tmpdir.join('configdir', 'master')
+    output_key_path = [fpath for fpath in master_dir.listdir()
+                       if fpath.ext == '.key'][0]
+    assert output_key_path.check()
+
+    # Check key decrypts and is valid
+    mocker.patch('getpass.getpass', lambda *_: 'testpassword')
+    output_key = onionbalance.util.key_decrypt_prompt(str(output_key_path))
+    assert isinstance(output_key, Crypto.PublicKey.RSA._RSAobj)
diff --git a/test/functional/test_publish_master_descriptor.py b/test/functional/test_publish_master_descriptor.py
new file mode 100644
index 0000000..075e06b
--- /dev/null
+++ b/test/functional/test_publish_master_descriptor.py
@@ -0,0 +1,144 @@
+# -*- coding: utf-8 -*-
+import os
+import sys
+import socket
+import time
+
+import pytest
+import Crypto.PublicKey.RSA
+import yaml
+import pexpect
+import stem.control
+
+import onionbalance.util
+
+# Skip functional tests if Chutney environment is not running.
+pytestmark = pytest.mark.skipif(
+    "os.environ.get('CHUTNEY_ONION_ADDRESS') is None",
+    reason="Skipping functional test, no Chutney environment detected")
+
+
+def parse_chutney_enviroment():
+    """
+    Read environment variables and determine chutney instance and
+    client addresses.
+    """
+
+    tor_client = os.environ.get('CHUTNEY_CLIENT_PORT')
+    assert tor_client
+
+    # Calculate the address and port of clients control port
+    client_address, client_socks_port = tor_client.split(':')
+    client_ip = socket.gethostbyname(client_address)
+
+    tor_client_number = int(client_socks_port) - 9000
+    # Control port in the 8000-8999 range, offset by Tor client number
+    control_port = 8000 + tor_client_number
+    assert control_port
+
+    # Retrieve instance onion address exported during chutney setup
+    instance_address = os.environ.get('CHUTNEY_ONION_ADDRESS')
+    assert instance_address  # Need at least 1 instance address for test
+
+    if '.onion' in instance_address:
+        instance_address = instance_address[:16]
+
+    return {
+        'client_ip': client_ip,
+        'control_port': control_port,
+        'instances': [instance_address],
+    }
+
+
+def create_test_config_file(tmppath, private_key=None, instances=None):
+    """
+    Setup function to create a temp directory with master key and config file.
+    Returns a path to the temporary config file.
+
+    .. todo:: Refactor settings.py config creation to avoid code duplication
+              in integration tests.
+    """
+
+    if not private_key:
+        private_key = Crypto.PublicKey.RSA.generate(1024)
+
+    # Write private key file
+    key_path = tmppath.join('private_key')
+    key_path.write(private_key.exportKey())
+    assert key_path.check()
+
+    # Create YAML OnionBalance settings file for these instances
+    service_data = {'key': str(key_path)}
+    service_data['instances'] = [{'address': addr} for addr in instances]
+    settings_data = {'services': [service_data]}
+    config_yaml = yaml.dump(settings_data, default_flow_style=False)
+
+    config_path = tmppath.join('config.yaml')
+    config_path.write_binary(config_yaml.encode('utf-8'))
+    assert config_path.check()
+
+    return str(config_path)
+
+
+def test_master_descriptor_publication(tmpdir):
+    """
+    Functional test to run OnionBalance, publish a master descriptor and
+    check that it can be retrieved from the DHT.
+    """
+
+    chutney_config = parse_chutney_enviroment()
+    private_key = Crypto.PublicKey.RSA.generate(1024)
+    master_onion_address = onionbalance.util.calc_onion_address(private_key)
+
+    config_file_path = create_test_config_file(
+        tmppath=tmpdir,
+        private_key=private_key,
+        instances=chutney_config.get('instances', []),
+    )
+    assert config_file_path
+
+    # Start an OnionBalance server and monitor for correct output with pexpect
+    server = pexpect.spawnu("onionbalance",
+                            args=[
+                                '-i', chutney_config.get('client_ip'),
+                                '-p', str(chutney_config.get('control_port')),
+                                '-c', config_file_path,
+                                '-v', 'debug',
+                            ], logfile=sys.stdout, timeout=15)
+
+    # Check for expected output from OnionBalance
+    server.expect(u"Loaded the config file")
+    server.expect(u"introduction point set has changed")
+    server.expect(u"Published a descriptor", timeout=120)
+
+    # Check Tor control port gave an uploaded event.
+
+    server.expect(u"HS_DESC UPLOADED")
+    # Eek, sleep to wait for descriptor upload to all replicas to finish
+    time.sleep(10)
+
+    # .. todo:: Also need to check and raise for any warnings or errors
+    #           that are emitted
+
+    # Try fetch and validate the descriptor with stem
+    with stem.control.Controller.from_port(
+        address=chutney_config.get('client_ip'),
+        port=chutney_config.get('control_port')
+    ) as controller:
+        controller.authenticate()
+
+        # get_hidden_service_descriptor() will raise exceptions if it
+        # cannot find the descriptors
+        master_descriptor = controller.get_hidden_service_descriptor(
+            master_onion_address)
+        master_ips = master_descriptor.introduction_points()
+
+        # Try retrieve a descriptor for each instance
+        for instance_address in chutney_config.get('instances'):
+            instance_descriptor = controller.get_hidden_service_descriptor(
+                instance_address)
+            instance_ips = instance_descriptor.introduction_points()
+
+            # Check if all instance IPs were included in the master descriptor
+            assert (set(ip.identifier for ip in instance_ips) ==
+                    set(ip.identifier for ip in master_ips))
diff --git a/test/scripts/install-chutney.sh b/test/scripts/install-chutney.sh
new file mode 100755
index 0000000..2a5167f
--- /dev/null
+++ b/test/scripts/install-chutney.sh
@@ -0,0 +1,31 @@
+#!/bin/bash
+# Script to install Chutney, configure a Tor network and wait for the hidden
+# service system to be available.
+git clone https://github.com/DonnchaC/chutney.git
+cd chutney
+# Stop chutney network if it is already running
+./chutney stop networks/hs
+./chutney configure networks/hs
+./chutney start networks/hs
+./chutney status networks/hs
+
+# Retry verify until hidden service subsystem is working
+n=0
+until [ $n -ge 20 ]
+do
+  output=$(./chutney verify networks/hs)
+  # Check if chutney output included 'Transmission: Success'.
+  if [[ $output == *"Transmission: Success"* ]]; then
+    hs_address=$(echo $output | grep -Po "([a-z2-7]{16}.onion:\d{2,5})")
+    client_address=$(echo $output | grep -Po -m 1 "(localhost:\d{2,5})" | head -n1)
+    echo "HS system running with service available at $hs_address"
+    export CHUTNEY_ONION_ADDRESS="$hs_address"
+    export CHUTNEY_CLIENT_PORT="$client_address"
+    break
+  else
+    echo "HS system not running yet. Sleeping 15 seconds"
+    n=$[$n+1]
+    sleep 15
+  fi
+done
+cd ..
diff --git a/test/scripts/install-tor.sh b/test/scripts/install-tor.sh
new file mode 100755
index 0000000..5aee64a
--- /dev/null
+++ b/test/scripts/install-tor.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Script to install Tor
+set -ex
+wget https://www.torproject.org/dist/tor-0.2.7.1-alpha.tar.gz
+tar -xzvf tor-0.2.7.1-alpha.tar.gz && mv tor-0.2.7.1-alpha tor
+cd tor && ./configure --disable-asciidoc && make
diff --git a/test/test_descriptor.py b/test/test_descriptor.py
new file mode 100644
index 0000000..baba067
--- /dev/null
+++ b/test/test_descriptor.py
@@ -0,0 +1,342 @@
+# -*- coding: utf-8 -*-
+import datetime
+
+import pytest
+import Crypto.PublicKey.RSA
+import stem.descriptor
+import hashlib
+from binascii import unhexlify
+
+from onionbalance import descriptor
+
+PEM_PRIVATE_KEY = u'\n'.join([
+    '-----BEGIN RSA PRIVATE KEY-----',
+    'MIICWwIBAAKBgQDXzP6HGtjPSy7uF9OlY7ZmefTVKcFLsq0mSEzQrW5wSiNuYc+d',
+    'oSV2OWxPg+1fVe19ES43AUkq/bS/gjAMLOunP6u9FbPDojyh1Vs/6TVqftS3sPkl',
+    'Q0ItrrZwAwhtHC0WaEyrwYJNOSCBq3wpupdQhpRyWJFqMwm9+iBCG1QcJQIDAQAB',
+    'AoGAegc2Sqm4vgdyozof+R8Ybnw6ISu6XRbNaJ9rqHjZwW9695khsK4GJAM2pwQf',
+    '/0/0ukszyfDVMhVC1yREDS59lgzNecItd6nQZWbwr9TFxIoa9ouTqk8PcAoNixTb',
+    'wafjPcMmWGakizXeAHiOfazPBH4x2keDQCulxfYxXZxTpyECQQDqZu61kd1S3U7T',
+    'BT2NQBd3tHX0Hvonx+IkOKXwpHFY0Mo4d32Bi+MxRuEnd3tO44AaMvlkl13QMTF2',
+    'kHFSC70dAkEA669LZavGjW67+rO+f+xyDVby9pD5GJQBb78xRCf93Zcu2KW4NSp3',
+    'XC4p4eWfLgff1VuXL7g0VdFm4wUUHqYUqQJAZLmqpjdyBeO3tZIw6vu5meTgMvEE',
+    'ygdos+vr0sa3NlUyMKWYNwznqgstQYpkYHf+WkPBS2qIE6iv+qUDLSCCOQJAESSk',
+    'CFYxUBJQ7BBs9+Mb/Kppa9Ppuobxf85ZaAq8pYScrLeJKZzYJ8VX2I2aQX/jISLT',
+    'YW41qFRd9n9lEkGkWQJAcxPmNI+2r5zJG+K148LLmWCIDTVZ4nxOcxffHka/3tCJ',
+    'lDGUw4p2wU6pVRDpNfKrF5Nc9ZKO8NAtC17ZvDyVkQ==',
+    '-----END RSA PRIVATE KEY-----',
+])
+
+INTRODUCTION_POINT_PART = u'\n'.join([
+    '-----BEGIN MESSAGE-----',
+    'AgEdbps604RR6lqeyoZBzOb6+HvlL2cDt63w8vBtyRaLirq5ZD5GDnr+R0ePj71C',
+    'nC7qmRWuwBmzSdSd0lOTaSApBvIifbJksHUeT/rq03dpnnRHdHSVqSvig6bukcWJ',
+    'LgJmrRd3ES13LXVHenD3C6AZMHuL9TG+MjLO2PIHu0mFO18aAHVnWY32Dmt144IY',
+    'c2eTVZbsKobjjwCYvDf0PBZI+B6H0PZWkDX/ykYjArpLDwydeZyp+Zwj4+k0+nRr',
+    'RPlzbHYoBY9pFYDUXDXWdL+vTsgFTG0EngLGlgUWSY5U1T1Db5HfOqc7hbqklgs/',
+    'ULG8NUY1k41Wb+dleJI28/+ZOM9zOpHcegNx4Cn8UGbw/Yv3Tj+yki+TMeOtJyhK',
+    'PQP8NWq8zThiVhBrfpmVjMYkNeVNyVNoxRwS6rxCQjoLWSJit2Mpf57zY1AOvT1S',
+    'EqqFbsX+slD2Uk67imALh4pMtjX29VLIujpum3drLhoTHDszBRhIH61A2eAZqdJy',
+    '7JkJd1x/8x7U0l8xNWhnj/bhUHdt3OrCvlN+n8x6BwmMNoLF8JIsskTuGHOaAKSQ',
+    'WK3z0rHjgIrEjkQeuQtfmptiIgRB9LnNr+YahRnRR6XIOJGaIoVLVM2Uo2RG4MS1',
+    '2KC3DRJ87WdMv2yNWha3w+lWt/mOALahYrvuNMU8wEuNXSi5yCo1OKirv+d5viGe',
+    'hAgVZjRymBQF+vd30zMdOG9qXNoQFUN49JfS8z5FjWmdHRt2MHlqD2isxoeabERY',
+    'T4Q50fFH8XHkRRomKBEbCwy/4t2DiqcTOSLGOSbTtf7qlUACp2bRth/g0ySAW8X/',
+    'CaWVm53z1vdgF2+t6j1CnuIqf0dUygZ07HEAHgu3rMW0YTk04QkvR3jiKAKijvGH',
+    '3YcMJz1aJ7psWSsgiwn8a8Cs4fAcLNJcdTrnyxhQI4PMST/QLfp8nPYrhKEeifTc',
+    'vYkC4CtGuEFkWyRifIGbeD7FcjkL1zqVNu31vgo3EIVbHzylERgpgTIYBRv7aV7W',
+    'X7XAbrrgXL0zgpI0orOyPkr2KRs6CcoEqcc2MLyB6gJ5fYAm69Ige+6gWtRT6qvZ',
+    'tJXagfKZivLj73dRD6sUqTCX4tmgo7Q8WFSeNscDAVm/p4dVsw6SOoFcRgaH20yX',
+    'MBa3oLNTUNAaGbScUPx2Ja3MQS0UITwk0TFTF7hL++NhTvTp6IdgQW4DG+/bVJ3M',
+    'BRR+hsvSz5BSQQj2FUIAsJ+WoVK9ImbgsBbYxSH60jCvxTIdeh2IeUzS2T1bU9AU',
+    'jOLzcJZmNh95Nj2Qdrc8/0gin9KpgPmuPQ6CyH3TPFy88lf19v9jHUMO4SKEr7am',
+    'DAjbX3D7APKgHyZ61CkuoB3gylIRb8rRJD2ote38M6A1+04yJL/jG+PCL1UnMWdL',
+    'yJ4f4LzI9c4ksnGyl9neq0IHnA0Nlky6dmgmE+vLi6OCbEEs2v132wc5PIxRY+TW',
+    '8JWu+3wUA4tj5uQvQRqU9/lmoHG/Jxubx/HwdD9Ri17G+qX8re5sySmmq7rcZEGJ',
+    'LVrlFuvA0NdoTM4AZY23iR6trJ/Ba2Q4pQk4SfOEMSoZJmf0UbxIP0Ez6Fb+Dxzk',
+    'WKXfI+D0ScuVjzV0bs8iXTrCcynztRKndNbtpd39hGAR0rNqvnHyQGYV75bWm5dS',
+    '0S0PQ6DOzicLxjNXZFicQvwfieg9VyJikWLFLu4zAbzHnuoRk6b2KbSU4UCG/BCz',
+    'mHqz4y6GfsncsNkmFmsD5Gn9UrloWcEWgIDL05yIikL+L9DPLnNlSYtehDfxlhvh',
+    'xHzY/Rad4Nzxe62yXhSxhROLTXIolllyOFJgqZ4hBlXybBqJH7sZUll6PUpDwZdu',
+    'BK14pzMIpfxq2eYp8jI7fh4lU9YrkuSUM0Ewa7HfrltAgxMhHyaFjfINt61P9OlO',
+    's3nuBY17+KokaSWjACkCimVLH13H5DRhfX8OBRT4LeRMUspX3cyKbccwpOmoBf4y',
+    'WPM9QXw7nQy2hwnuX6NiK5QfeCGfY64M06J2tBGcCDmjPSIcJgMcyY7jfH9yPlDt',
+    'SKyyXpZnFOJplS2v28A/1csPSGy9kk/uGN0hfFULH4VvyAgNDYzmeOd8FvrbfHH2',
+    '8BUTI/Tq2pckxwCYBWHcjSdXRAj5moCNSxCUMtK3kWFdxLFYzoiKuiZwq171qb5L',
+    'yCHMwNDIWEMeC75XSMswHaBsK6ON0UUg5oedQkOK+II9L/DVyTs3UYJOsWDfM67E',
+    '312O9/bmsoHvr+rofF7HEc74dtUAcaDGJNyNiB+O4UmWbtEpCfuLmq2vaZa9J7Y0',
+    'hXlD2pcibC9CWpKR58cRL+dyYHZGJ4VKg6OHlJlF+JBPeLzObNDz/zQuEt9aL9Ae',
+    'QByamqGDGcaVMVZ/A80fRoUUgHbh3bLoAmxLCvMbJ0YMtRujdtGm8ZD0WvLXQA/U',
+    'dNmQ6tsP6pyVorWVa/Ma5CR7Em5q7M6639T8WPcu7ETTO19MnWud2lPJ5A==',
+    '-----END MESSAGE-----',
+])
+
+UNSIGNED_DESCRIPTOR = u'\n'.join([
+    'rendezvous-service-descriptor 6wgohrr64y2od75psnrfdkbc74ddqx2v',
+    'version 2',
+    'permanent-key',
+    '-----BEGIN RSA PUBLIC KEY-----',
+    'MIGJAoGBANfM/oca2M9LLu4X06VjtmZ59NUpwUuyrSZITNCtbnBKI25hz52hJXY5',
+    'bE+D7V9V7X0RLjcBSSr9tL+CMAws66c/q70Vs8OiPKHVWz/pNWp+1Lew+SVDQi2u',
+    'tnADCG0cLRZoTKvBgk05IIGrfCm6l1CGlHJYkWozCb36IEIbVBwlAgMBAAE=',
+    '-----END RSA PUBLIC KEY-----',
+    'secret-id-part udmoj3e2ykfp73kpvauoq4t4p7kkwsjq',
+    'publication-time 2015-06-25 11:00:00',
+    'protocol-versions 2,3',
+    'introduction-points',
+    '-----BEGIN MESSAGE-----',
+    'AgEdbps604RR6lqeyoZBzOb6+HvlL2cDt63w8vBtyRaLirq5ZD5GDnr+R0ePj71C',
+    'nC7qmRWuwBmzSdSd0lOTaSApBvIifbJksHUeT/rq03dpnnRHdHSVqSvig6bukcWJ',
+    'LgJmrRd3ES13LXVHenD3C6AZMHuL9TG+MjLO2PIHu0mFO18aAHVnWY32Dmt144IY',
+    'c2eTVZbsKobjjwCYvDf0PBZI+B6H0PZWkDX/ykYjArpLDwydeZyp+Zwj4+k0+nRr',
+    'RPlzbHYoBY9pFYDUXDXWdL+vTsgFTG0EngLGlgUWSY5U1T1Db5HfOqc7hbqklgs/',
+    'ULG8NUY1k41Wb+dleJI28/+ZOM9zOpHcegNx4Cn8UGbw/Yv3Tj+yki+TMeOtJyhK',
+    'PQP8NWq8zThiVhBrfpmVjMYkNeVNyVNoxRwS6rxCQjoLWSJit2Mpf57zY1AOvT1S',
+    'EqqFbsX+slD2Uk67imALh4pMtjX29VLIujpum3drLhoTHDszBRhIH61A2eAZqdJy',
+    '7JkJd1x/8x7U0l8xNWhnj/bhUHdt3OrCvlN+n8x6BwmMNoLF8JIsskTuGHOaAKSQ',
+    'WK3z0rHjgIrEjkQeuQtfmptiIgRB9LnNr+YahRnRR6XIOJGaIoVLVM2Uo2RG4MS1',
+    '2KC3DRJ87WdMv2yNWha3w+lWt/mOALahYrvuNMU8wEuNXSi5yCo1OKirv+d5viGe',
+    'hAgVZjRymBQF+vd30zMdOG9qXNoQFUN49JfS8z5FjWmdHRt2MHlqD2isxoeabERY',
+    'T4Q50fFH8XHkRRomKBEbCwy/4t2DiqcTOSLGOSbTtf7qlUACp2bRth/g0ySAW8X/',
+    'CaWVm53z1vdgF2+t6j1CnuIqf0dUygZ07HEAHgu3rMW0YTk04QkvR3jiKAKijvGH',
+    '3YcMJz1aJ7psWSsgiwn8a8Cs4fAcLNJcdTrnyxhQI4PMST/QLfp8nPYrhKEeifTc',
+    'vYkC4CtGuEFkWyRifIGbeD7FcjkL1zqVNu31vgo3EIVbHzylERgpgTIYBRv7aV7W',
+    'X7XAbrrgXL0zgpI0orOyPkr2KRs6CcoEqcc2MLyB6gJ5fYAm69Ige+6gWtRT6qvZ',
+    'tJXagfKZivLj73dRD6sUqTCX4tmgo7Q8WFSeNscDAVm/p4dVsw6SOoFcRgaH20yX',
+    'MBa3oLNTUNAaGbScUPx2Ja3MQS0UITwk0TFTF7hL++NhTvTp6IdgQW4DG+/bVJ3M',
+    'BRR+hsvSz5BSQQj2FUIAsJ+WoVK9ImbgsBbYxSH60jCvxTIdeh2IeUzS2T1bU9AU',
+    'jOLzcJZmNh95Nj2Qdrc8/0gin9KpgPmuPQ6CyH3TPFy88lf19v9jHUMO4SKEr7am',
+    'DAjbX3D7APKgHyZ61CkuoB3gylIRb8rRJD2ote38M6A1+04yJL/jG+PCL1UnMWdL',
+    'yJ4f4LzI9c4ksnGyl9neq0IHnA0Nlky6dmgmE+vLi6OCbEEs2v132wc5PIxRY+TW',
+    '8JWu+3wUA4tj5uQvQRqU9/lmoHG/Jxubx/HwdD9Ri17G+qX8re5sySmmq7rcZEGJ',
+    'LVrlFuvA0NdoTM4AZY23iR6trJ/Ba2Q4pQk4SfOEMSoZJmf0UbxIP0Ez6Fb+Dxzk',
+    'WKXfI+D0ScuVjzV0bs8iXTrCcynztRKndNbtpd39hGAR0rNqvnHyQGYV75bWm5dS',
+    '0S0PQ6DOzicLxjNXZFicQvwfieg9VyJikWLFLu4zAbzHnuoRk6b2KbSU4UCG/BCz',
+    'mHqz4y6GfsncsNkmFmsD5Gn9UrloWcEWgIDL05yIikL+L9DPLnNlSYtehDfxlhvh',
+    'xHzY/Rad4Nzxe62yXhSxhROLTXIolllyOFJgqZ4hBlXybBqJH7sZUll6PUpDwZdu',
+    'BK14pzMIpfxq2eYp8jI7fh4lU9YrkuSUM0Ewa7HfrltAgxMhHyaFjfINt61P9OlO',
+    's3nuBY17+KokaSWjACkCimVLH13H5DRhfX8OBRT4LeRMUspX3cyKbccwpOmoBf4y',
+    'WPM9QXw7nQy2hwnuX6NiK5QfeCGfY64M06J2tBGcCDmjPSIcJgMcyY7jfH9yPlDt',
+    'SKyyXpZnFOJplS2v28A/1csPSGy9kk/uGN0hfFULH4VvyAgNDYzmeOd8FvrbfHH2',
+    '8BUTI/Tq2pckxwCYBWHcjSdXRAj5moCNSxCUMtK3kWFdxLFYzoiKuiZwq171qb5L',
+    'yCHMwNDIWEMeC75XSMswHaBsK6ON0UUg5oedQkOK+II9L/DVyTs3UYJOsWDfM67E',
+    '312O9/bmsoHvr+rofF7HEc74dtUAcaDGJNyNiB+O4UmWbtEpCfuLmq2vaZa9J7Y0',
+    'hXlD2pcibC9CWpKR58cRL+dyYHZGJ4VKg6OHlJlF+JBPeLzObNDz/zQuEt9aL9Ae',
+    'QByamqGDGcaVMVZ/A80fRoUUgHbh3bLoAmxLCvMbJ0YMtRujdtGm8ZD0WvLXQA/U',
+    'dNmQ6tsP6pyVorWVa/Ma5CR7Em5q7M6639T8WPcu7ETTO19MnWud2lPJ5A==',
+    '-----END MESSAGE-----',
+    'signature',
+    '-----BEGIN SIGNATURE-----',
+    'VX4GC6s6zmY84mKsh+YdAqyZqDevJwGYr9yJntBNms4XRQHlgiW/JCspJzCqvrQG',
+    'N4Fh8XNTodQFnxz/kz8K3SBFlLnJHzKxSBTSZTLd8hRp84F/XxDcPaIPda8UJZuF',
+    'pOT8V0hfhgo8WxLpOyUzxrYugPB2GRkWYLhHaKhxkJY=',
+    '-----END SIGNATURE-----',
+])
+
+SIGNED_DESCRIPTOR = u'\n'.join([
+    'rendezvous-service-descriptor 6wgohrr64y2od75psnrfdkbc74ddqx2v',
+    'version 2',
+    'permanent-key',
+    '-----BEGIN RSA PUBLIC KEY-----',
+    'MIGJAoGBANfM/oca2M9LLu4X06VjtmZ59NUpwUuyrSZITNCtbnBKI25hz52hJXY5',
+    'bE+D7V9V7X0RLjcBSSr9tL+CMAws66c/q70Vs8OiPKHVWz/pNWp+1Lew+SVDQi2u',
+    'tnADCG0cLRZoTKvBgk05IIGrfCm6l1CGlHJYkWozCb36IEIbVBwlAgMBAAE=',
+    '-----END RSA PUBLIC KEY-----',
+    'secret-id-part udmoj3e2ykfp73kpvauoq4t4p7kkwsjq',
+    'publication-time 2015-06-25 11:00:00',
+    'protocol-versions 2,3',
+    'introduction-points',
+    '-----BEGIN MESSAGE-----',
+    'AgEdbps604RR6lqeyoZBzOb6+HvlL2cDt63w8vBtyRaLirq5ZD5GDnr+R0ePj71C',
+    'nC7qmRWuwBmzSdSd0lOTaSApBvIifbJksHUeT/rq03dpnnRHdHSVqSvig6bukcWJ',
+    'LgJmrRd3ES13LXVHenD3C6AZMHuL9TG+MjLO2PIHu0mFO18aAHVnWY32Dmt144IY',
+    'c2eTVZbsKobjjwCYvDf0PBZI+B6H0PZWkDX/ykYjArpLDwydeZyp+Zwj4+k0+nRr',
+    'RPlzbHYoBY9pFYDUXDXWdL+vTsgFTG0EngLGlgUWSY5U1T1Db5HfOqc7hbqklgs/',
+    'ULG8NUY1k41Wb+dleJI28/+ZOM9zOpHcegNx4Cn8UGbw/Yv3Tj+yki+TMeOtJyhK',
+    'PQP8NWq8zThiVhBrfpmVjMYkNeVNyVNoxRwS6rxCQjoLWSJit2Mpf57zY1AOvT1S',
+    'EqqFbsX+slD2Uk67imALh4pMtjX29VLIujpum3drLhoTHDszBRhIH61A2eAZqdJy',
+    '7JkJd1x/8x7U0l8xNWhnj/bhUHdt3OrCvlN+n8x6BwmMNoLF8JIsskTuGHOaAKSQ',
+    'WK3z0rHjgIrEjkQeuQtfmptiIgRB9LnNr+YahRnRR6XIOJGaIoVLVM2Uo2RG4MS1',
+    '2KC3DRJ87WdMv2yNWha3w+lWt/mOALahYrvuNMU8wEuNXSi5yCo1OKirv+d5viGe',
+    'hAgVZjRymBQF+vd30zMdOG9qXNoQFUN49JfS8z5FjWmdHRt2MHlqD2isxoeabERY',
+    'T4Q50fFH8XHkRRomKBEbCwy/4t2DiqcTOSLGOSbTtf7qlUACp2bRth/g0ySAW8X/',
+    'CaWVm53z1vdgF2+t6j1CnuIqf0dUygZ07HEAHgu3rMW0YTk04QkvR3jiKAKijvGH',
+    '3YcMJz1aJ7psWSsgiwn8a8Cs4fAcLNJcdTrnyxhQI4PMST/QLfp8nPYrhKEeifTc',
+    'vYkC4CtGuEFkWyRifIGbeD7FcjkL1zqVNu31vgo3EIVbHzylERgpgTIYBRv7aV7W',
+    'X7XAbrrgXL0zgpI0orOyPkr2KRs6CcoEqcc2MLyB6gJ5fYAm69Ige+6gWtRT6qvZ',
+    'tJXagfKZivLj73dRD6sUqTCX4tmgo7Q8WFSeNscDAVm/p4dVsw6SOoFcRgaH20yX',
+    'MBa3oLNTUNAaGbScUPx2Ja3MQS0UITwk0TFTF7hL++NhTvTp6IdgQW4DG+/bVJ3M',
+    'BRR+hsvSz5BSQQj2FUIAsJ+WoVK9ImbgsBbYxSH60jCvxTIdeh2IeUzS2T1bU9AU',
+    'jOLzcJZmNh95Nj2Qdrc8/0gin9KpgPmuPQ6CyH3TPFy88lf19v9jHUMO4SKEr7am',
+    'DAjbX3D7APKgHyZ61CkuoB3gylIRb8rRJD2ote38M6A1+04yJL/jG+PCL1UnMWdL',
+    'yJ4f4LzI9c4ksnGyl9neq0IHnA0Nlky6dmgmE+vLi6OCbEEs2v132wc5PIxRY+TW',
+    '8JWu+3wUA4tj5uQvQRqU9/lmoHG/Jxubx/HwdD9Ri17G+qX8re5sySmmq7rcZEGJ',
+    'LVrlFuvA0NdoTM4AZY23iR6trJ/Ba2Q4pQk4SfOEMSoZJmf0UbxIP0Ez6Fb+Dxzk',
+    'WKXfI+D0ScuVjzV0bs8iXTrCcynztRKndNbtpd39hGAR0rNqvnHyQGYV75bWm5dS',
+    '0S0PQ6DOzicLxjNXZFicQvwfieg9VyJikWLFLu4zAbzHnuoRk6b2KbSU4UCG/BCz',
+    'mHqz4y6GfsncsNkmFmsD5Gn9UrloWcEWgIDL05yIikL+L9DPLnNlSYtehDfxlhvh',
+    'xHzY/Rad4Nzxe62yXhSxhROLTXIolllyOFJgqZ4hBlXybBqJH7sZUll6PUpDwZdu',
+    'BK14pzMIpfxq2eYp8jI7fh4lU9YrkuSUM0Ewa7HfrltAgxMhHyaFjfINt61P9OlO',
+    's3nuBY17+KokaSWjACkCimVLH13H5DRhfX8OBRT4LeRMUspX3cyKbccwpOmoBf4y',
+    'WPM9QXw7nQy2hwnuX6NiK5QfeCGfY64M06J2tBGcCDmjPSIcJgMcyY7jfH9yPlDt',
+    'SKyyXpZnFOJplS2v28A/1csPSGy9kk/uGN0hfFULH4VvyAgNDYzmeOd8FvrbfHH2',
+    '8BUTI/Tq2pckxwCYBWHcjSdXRAj5moCNSxCUMtK3kWFdxLFYzoiKuiZwq171qb5L',
+    'yCHMwNDIWEMeC75XSMswHaBsK6ON0UUg5oedQkOK+II9L/DVyTs3UYJOsWDfM67E',
+    '312O9/bmsoHvr+rofF7HEc74dtUAcaDGJNyNiB+O4UmWbtEpCfuLmq2vaZa9J7Y0',
+    'hXlD2pcibC9CWpKR58cRL+dyYHZGJ4VKg6OHlJlF+JBPeLzObNDz/zQuEt9aL9Ae',
+    'QByamqGDGcaVMVZ/A80fRoUUgHbh3bLoAmxLCvMbJ0YMtRujdtGm8ZD0WvLXQA/U',
+    'dNmQ6tsP6pyVorWVa/Ma5CR7Em5q7M6639T8WPcu7ETTO19MnWud2lPJ5A==',
+    '-----END MESSAGE-----',
+    'signature',
+    '-----BEGIN SIGNATURE-----',
+    'VX4GC6s6zmY84mKsh+YdAqyZqDevJwGYr9yJntBNms4XRQHlgiW/JCspJzCqvrQG',
+    'N4Fh8XNTodQFnxz/kz8K3SBFlLnJHzKxSBTSZTLd8hRp84F/XxDcPaIPda8UJZuF',
+    'pOT8V0hfhgo8WxLpOyUzxrYugPB2GRkWYLhHaKhxkJY=',
+    '-----END SIGNATURE-----',
+])
+
+PRIVATE_KEY = Crypto.PublicKey.RSA.importKey(PEM_PRIVATE_KEY)
+UNIX_TIMESTAMP = 1435233021
+
+
+def setup_introduction_point_lists(desired_intro_points):
+    '''
+    Create a list of lists of IntroductionPoint instances for unit
+    tests
+    '''
+
+
+ at pytest.mark.parametrize('intro_point_distribution, selected_count', [
+    ([3], 3),
+    ([3, 3], 6),
+    ([0], 0),
+    ([10, 10], 10),
+    ([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], 10),
+    pytest.mark.xfail(([0, 3, 3], 9)),
+])
+def test_choose_introduction_point_set(intro_point_distribution,
+                                       selected_count):
+    '''
+    Basic test case to check that the correct number of IPs are selected.
+    '''
+
+    # Create Mock list of instances and respective introduction points.
+    available_intro_points = [['IP'] * count for count
+                              in intro_point_distribution]
+
+    selected_introduction_points = descriptor.choose_introduction_point_set(
+        available_intro_points)
+
+    assert len(selected_introduction_points) == selected_count
+
+
+def test_generate_service_descriptor(monkeypatch, mocker):
+    '''
+    Test creation of a fully signed hidden service descriptor
+    '''
+    # Mock the datetime function to return a constant timestamp
+    class frozen_datetime(datetime.datetime):
+        @classmethod
+        def utcnow(cls):
+            return datetime.datetime.utcfromtimestamp(UNIX_TIMESTAMP)
+    monkeypatch.setattr(datetime, 'datetime', frozen_datetime)
+
+    # Patch make_introduction_points_part to return the test introduction
+    # point section
+    mocker.patch('onionbalance.descriptor.make_introduction_points_part',
+                 lambda *_: INTRODUCTION_POINT_PART)
+
+    # Test basic descriptor generation.
+    signed_descriptor = descriptor.generate_service_descriptor(
+        PRIVATE_KEY,
+        introduction_point_list=['mocked-ip-list'],
+    ).encode('utf-8')
+    stem.descriptor.hidden_service_descriptor.\
+        HiddenServiceDescriptor(signed_descriptor, validate=True)
+    assert (hashlib.sha1(signed_descriptor).hexdigest() ==
+            'df4f4a7a15492205f073c32cbcfc4eb9511e4ad8')
+
+    # Test descriptor generation with specified timestamp
+    signed_descriptor = descriptor.generate_service_descriptor(
+        PRIVATE_KEY,
+        introduction_point_list=['mocked-ip-list'],
+        timestamp=datetime.datetime.utcfromtimestamp(UNIX_TIMESTAMP),
+    ).encode('utf-8')
+    stem.descriptor.hidden_service_descriptor.\
+        HiddenServiceDescriptor(signed_descriptor, validate=True)
+    assert (hashlib.sha1(signed_descriptor).hexdigest() ==
+            'df4f4a7a15492205f073c32cbcfc4eb9511e4ad8')
+
+    # Test descriptor for deviation and replica 1
+    signed_descriptor = descriptor.generate_service_descriptor(
+        PRIVATE_KEY,
+        introduction_point_list=['mocked-ip-list'],
+        replica=1,
+        deviation=24*60*60,
+    ).encode('utf-8')
+    stem.descriptor.hidden_service_descriptor.\
+        HiddenServiceDescriptor(signed_descriptor, validate=True)
+    assert (hashlib.sha1(signed_descriptor).hexdigest() ==
+            'd828140cdccb1165dbc5a4b39622fcb45e6438fb')
+
+
+def test_generate_service_descriptor_no_intros():
+    with pytest.raises(ValueError):
+        descriptor.generate_service_descriptor(
+            PRIVATE_KEY,
+            introduction_point_list=[],
+        )
+
+
+def test_make_public_key_block():
+    """
+    Test generation of ASN.1 representation of public key
+    """
+    public_key_block = descriptor.make_public_key_block(PRIVATE_KEY)
+    assert (hashlib.sha1(public_key_block.encode('utf-8')).hexdigest() ==
+            '2cf75da5e1a198ca7cb3db7b0baa6708feaf26e8')
+
+
+def test_sign_digest():
+    """
+    Test signing a SHA1 digest
+    """
+    test_digest = unhexlify('2a447f044d2f8d8127e8133b2d545450bc58760e')
+    signature = descriptor.sign_digest(test_digest, PRIVATE_KEY)
+    assert (hashlib.sha1(signature.encode('utf-8')).hexdigest() ==
+            '27bee071a7e0f0af26a1c176f0c0af00854c05c1')
+
+
+def test_sign_descriptor():
+    """
+    Test signing a descriptor
+    """
+
+    # Test signing an unsigned descriptor
+    signed_descriptor = descriptor.sign_descriptor(
+        UNSIGNED_DESCRIPTOR, PRIVATE_KEY).encode('utf-8')
+    stem.descriptor.hidden_service_descriptor.\
+        HiddenServiceDescriptor(signed_descriptor, validate=True)
+    assert (hashlib.sha1(signed_descriptor).hexdigest() ==
+            'df4f4a7a15492205f073c32cbcfc4eb9511e4ad8')
+
+    # Test resigning a previously signed descriptor
+    signed_descriptor = descriptor.sign_descriptor(
+        SIGNED_DESCRIPTOR, PRIVATE_KEY).encode('utf-8')
+    stem.descriptor.hidden_service_descriptor.\
+        HiddenServiceDescriptor(signed_descriptor, validate=True)
+    assert (hashlib.sha1(signed_descriptor).hexdigest() ==
+            'df4f4a7a15492205f073c32cbcfc4eb9511e4ad8')
+
+
+def test_descriptor_received_invalid_descriptor(mocker):
+    """
+    Test invalid descriptor content received from the HSDir
+    """
+    mocker.patch("onionbalance.descriptor.logger.exception",
+                 side_effect=ValueError('InvalidDescriptorException'))
+
+    # Check that the invalid descriptor error is logged.
+    with pytest.raises(ValueError):
+        descriptor.descriptor_received(u'not-a-valid-descriptor-input')
+    assert descriptor.logger.exception.call_count == 1
diff --git a/test/test_settings.py b/test/test_settings.py
new file mode 100644
index 0000000..f987803
--- /dev/null
+++ b/test/test_settings.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+import io
+import os
+
+import pytest
+
+from onionbalance import settings
+from .util import builtin
+
+CONFIG_FILE_VALID = u'\n'.join([
+    "services:",
+    "    - key: private.key",
+    "      instances:",
+    "        - address: fqyw6ojo2voercr7",
+    "        - address: facebookcorewwwi",
+])
+
+CONFIG_FILE_ABSOLUTE = u'\n'.join([
+    "services:",
+    "    - key: /absdir/private.key",
+    "      instances:",
+    "        - address: fqyw6ojo2voercr7",
+    "        - address: facebookcorewwwi",
+])
+
+
+def test_parse_config_file_valid(mocker):
+    # Patch config file read
+    mocker.patch('os.path.exists', return_value=True)
+    mocker.patch(builtin('open'),
+                 lambda *_: io.StringIO(CONFIG_FILE_VALID))
+
+    parsed_config = settings.parse_config_file('/configdir/config_rel.yaml')
+
+    assert len(parsed_config['services']) == 1
+    assert len(parsed_config['services'][0]['instances']) == 2
+
+    # Test key with absolute path
+    assert os.path.dirname(parsed_config['services'][0]['key']) == '/configdir'
+
+    # Test key with absolute path
+    mocker.patch(builtin('open'),
+                 lambda *_: io.StringIO(CONFIG_FILE_ABSOLUTE))
+    parsed_config = settings.parse_config_file('/configdir/config_abs.yaml')
+    assert os.path.dirname(parsed_config['services'][0]['key']) == '/absdir'
+
+
+def test_parse_config_file_does_not_exist(mocker):
+    with pytest.raises(SystemExit):
+        settings.parse_config_file('doesnotexist/config.yaml')
diff --git a/test/test_util.py b/test/test_util.py
new file mode 100644
index 0000000..c9e4cc7
--- /dev/null
+++ b/test/test_util.py
@@ -0,0 +1,267 @@
+# -*- coding: utf-8 -*-
+from binascii import hexlify, unhexlify
+import base64
+import datetime
+import io
+import sys
+
+import Crypto.PublicKey.RSA
+
+import pytest
+from .util import builtin
+
+from onionbalance.util import *
+
+
+PEM_PRIVATE_KEY = u'\n'.join([
+    "-----BEGIN RSA PRIVATE KEY-----",
+    "MIICWwIBAAKBgQDXzP6HGtjPSy7uF9OlY7ZmefTVKcFLsq0mSEzQrW5wSiNuYc+d",
+    "oSV2OWxPg+1fVe19ES43AUkq/bS/gjAMLOunP6u9FbPDojyh1Vs/6TVqftS3sPkl",
+    "Q0ItrrZwAwhtHC0WaEyrwYJNOSCBq3wpupdQhpRyWJFqMwm9+iBCG1QcJQIDAQAB",
+    "AoGAegc2Sqm4vgdyozof+R8Ybnw6ISu6XRbNaJ9rqHjZwW9695khsK4GJAM2pwQf",
+    "/0/0ukszyfDVMhVC1yREDS59lgzNecItd6nQZWbwr9TFxIoa9ouTqk8PcAoNixTb",
+    "wafjPcMmWGakizXeAHiOfazPBH4x2keDQCulxfYxXZxTpyECQQDqZu61kd1S3U7T",
+    "BT2NQBd3tHX0Hvonx+IkOKXwpHFY0Mo4d32Bi+MxRuEnd3tO44AaMvlkl13QMTF2",
+    "kHFSC70dAkEA669LZavGjW67+rO+f+xyDVby9pD5GJQBb78xRCf93Zcu2KW4NSp3",
+    "XC4p4eWfLgff1VuXL7g0VdFm4wUUHqYUqQJAZLmqpjdyBeO3tZIw6vu5meTgMvEE",
+    "ygdos+vr0sa3NlUyMKWYNwznqgstQYpkYHf+WkPBS2qIE6iv+qUDLSCCOQJAESSk",
+    "CFYxUBJQ7BBs9+Mb/Kppa9Ppuobxf85ZaAq8pYScrLeJKZzYJ8VX2I2aQX/jISLT",
+    "YW41qFRd9n9lEkGkWQJAcxPmNI+2r5zJG+K148LLmWCIDTVZ4nxOcxffHka/3tCJ",
+    "lDGUw4p2wU6pVRDpNfKrF5Nc9ZKO8NAtC17ZvDyVkQ==",
+    "-----END RSA PRIVATE KEY-----",
+])
+
+PEM_INVALID_KEY = u'\n'.join([
+    "-----BEGIN RSA PRIVATE KEY-----",
+    "MIICWwIBAAKBgQDXzP6HGtjPSy7uF9OlY7ZmefTVKcFLsq0mSEzQrW5wSiNuYc+d",
+    "oSV2OWxPg+1fVe19ES43AUkq/bS/gjAMLOunP6u9FbPDojyh1Vs/6TVqftS3sPkl",
+    "Q0ItrrZwAwhtHC0WaEyrwYJNOSCBq3wpupdQhpRyWJFqMwm9+iBCG1QcJQIDAQAB",
+    "AoGAegc2Sqm4vgdyozof+R8Ybnw6ISu6XRbNaJ9rqHjZwW9695khsK4GJAM2pwQf",
+    "/0/0ukszyfDVMhVC1yREDS59lgzNecItd6nQZWbwr9TFxIoa9ouTqk8PcAoNixTb",
+    "wafjPcMmWGakizXeAHiOfazPBH4x2keDQCulxfYxXZxTpyECQQDqZu61kd1S3U7T",
+    "BT2NQBd3t          This is an invalid key             lkl13QMTF2",
+    "kHFSC70dAkEA669LZavGjW67+rO+f+xyDVby9pD5GJQBb78xRCf93Zcu2KW4NSp3",
+    "XC4p4eWfLgff1VuXL7g0VdFm4wUUHqYUqQJAZLmqpjdyBeO3tZIw6vu5meTgMvEE",
+    "ygdos+vr0sa3NlUyMKWYNwznqgstQYpkYHf+WkPBS2qIE6iv+qUDLSCCOQJAESSk",
+    "CFYxUBJQ7BBs9+Mb/Kppa9Ppuobxf85ZaAq8pYScrLeJKZzYJ8VX2I2aQX/jISLT",
+    "YW41qFRd9n9lEkGkWQJAcxPmNI+2r5zJG+K148LLmWCIDTVZ4nxOcxffHka/3tCJ",
+    "lDGUw4p2wU6pVRDpNfKrF5Nc9ZKO8NAtC17ZvDyVkQ==",
+    "-----END RSA PRIVATE KEY-----",
+])
+
+# Private key encrypted with the password 'password'
+PEM_ENCRYPTED = u'\n'.join([
+    "-----BEGIN RSA PRIVATE KEY-----",
+    "Proc-Type: 4,ENCRYPTED",
+    "DEK-Info: DES-EDE3-CBC,7CB7069233655F1A",
+    "",
+    "EpKWFhHefxQLlKS1M6fPXLUVW0gcrHwYNd2q/0J4emhrHmO50KTC6/nVGTvYS1VC",
+    "XQwzlla04Ed7kAuP7nkbvT+/6fS72iZmIO/kuhihjaMmRV+peznjEroErndRzWko",
+    "LCpe70/yMrHhULGR1lLINe+dZddESfYRoGEM1IYhPEEchXZBdqThvaThgeyVmoAV",
+    "A5qhBOP4QFPSV4J0Jd28wTy+uPmGgCjvfvXjx4JZ2LAfPnLXOoKotRqb/cOtMapp",
+    "9EmsvjRZH3OLreeQm1BmVzcXGgHLIZWmybGNAW/M0seqeD+NRPXEACOBahXZsSwd",
+    "krnWALTkcfLw4NXgaHKdsogDV7gWlwkXr05CrSim0+zvg+hQpVp6Phg9qrT3Jh8g",
+    "988v4Fx/rlVdEpfEeXAmLUpXH3jjeyU1ZOyi8c91Vobxe1dJ9G9P8YBBqnZo1xDa",
+    "q89FR852v2DKR3xv+GRpzFM43NlWLck9DcNcqIUpbrGd0qRA1k87ZwYSiUPhBvtJ",
+    "dix6XfeqbqVMYiH0K4sEyuXxJ98UqFzNY3bBi9oqvoQWpo0qrRYAzHrmDg/hJbO6",
+    "aw8yhe922zw8W9+IQIy2j+ZKkaHSMKqjkIwFxmig5EA+mHNDIP4HwlCxA2e2w6HG",
+    "ykLE01aHMeS72qRdLVwjib4q2iTEXZVnuyFg/wVprLmLY512iWr03kbj2CVN836b",
+    "vEpVIvSj5W6oNXjm+hkKA1AMcHVK96y8Ms3BtarDe4tQDh7GjipkoSXrv+2lIl0o",
+    "XjumCv4Gs63Fv3kUr+jo9N3P0SGe1GggX6MOYIcZF0I=",
+    "-----END RSA PRIVATE KEY-----",
+])
+
+PRIVATE_KEY = Crypto.PublicKey.RSA.importKey(PEM_PRIVATE_KEY)
+UNIX_TIMESTAMP = 1435229421
+
+
+def test_add_pkcs1_padding():
+    message = unhexlify(b'f42687f4c3c017ce1e14eceb2ff153ff2d0a9e96')
+    padded_message = add_pkcs1_padding(message)
+
+    assert len(padded_message) == 128
+    assert (padded_message == unhexlify(
+        b'0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
+        b'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
+        b'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
+        b'ffffffffffffffffffffff00f42687f4c3c017ce1e14eceb2ff153ff2d0a9e96'
+    ))
+
+
+def test_get_asn1_sequence():
+    asn1_sequence = get_asn1_sequence(PRIVATE_KEY)
+    assert (asn1_sequence == unhexlify(
+        b'30818902818100d7ccfe871ad8cf4b2eee17d3a563b66679f4d529c14bb2ad26'
+        b'484cd0ad6e704a236e61cf9da12576396c4f83ed5f55ed7d112e3701492afdb4'
+        b'bf82300c2ceba73fabbd15b3c3a23ca1d55b3fe9356a7ed4b7b0f92543422dae'
+        b'b67003086d1c2d16684cabc1824d392081ab7c29ba975086947258916a3309bd'
+        b'fa20421b541c250203010001'
+    ))
+
+
+def test_calc_key_digest():
+    key_digest = calc_key_digest(PRIVATE_KEY)
+    assert hexlify(key_digest) == b'4e2a58768ccb6aa06f95e11646e187879d07fb66'
+
+
+def test_calc_public_key_digest():
+    public_key = PRIVATE_KEY.publickey()
+    key_digest = calc_key_digest(public_key)
+    assert hexlify(key_digest) == b'4e2a58768ccb6aa06f95e11646e187879d07fb66'
+
+
+def test_calc_permanent_id():
+    assert hexlify(calc_permanent_id(PRIVATE_KEY)) == b'4e2a58768ccb6aa06f95'
+
+
+def test_calc_onion_address():
+    assert calc_onion_address(PRIVATE_KEY) == u'jyvfq5umznvka34v'
+
+
+def test_get_time_period():
+    time_period = get_time_period(
+        time=UNIX_TIMESTAMP,
+        permanent_id=unhexlify(b'4e2a58768ccb6aa06f95'),
+    )
+    assert time_period == 16611
+
+
+def test_get_seconds_valid():
+    seconds_valid = get_seconds_valid(
+        time=UNIX_TIMESTAMP,
+        permanent_id=unhexlify(b'4e2a58768ccb6aa06f95'),
+    )
+    assert seconds_valid == 21054
+
+
+def test_calc_secret_id_part():
+    secret_id_part = calc_secret_id_part(
+        time_period=16611,
+        descriptor_cookie=None,
+        replica=0,
+    )
+    assert (hexlify(secret_id_part) ==
+            b'a0d8e4ec9ac28affed4fa828e8727c7fd4ab4930')
+
+
+def test_calc_secret_id_part_descriptor_cookie():
+    secret_id_part = calc_secret_id_part(
+        time_period=16611,
+        descriptor_cookie=base64.b64decode('dCmx3qIvArbil8A0KM4KgQ=='),
+        replica=0,
+    )
+    assert (hexlify(secret_id_part) ==
+            b'ea4e24b1a832f1da687f874b40fa9ecfe5221dd9')
+
+
+def test_calc_descriptor_id():
+    descriptor_id = calc_descriptor_id(
+        permanent_id=b'N*Xv\x8c\xcbj\xa0o\x95',
+        secret_id_part=unhexlify(b'a0d8e4ec9ac28affed4fa828e8727c7fd4ab4930'),
+    )
+    assert (hexlify(descriptor_id) ==
+            b'f58ce3c63ee634e1ffaf936251a822ff06385f55')
+
+
+def test_rounded_timestamp():
+    timestamp = datetime.datetime(2015, 6, 25, 13, 13, 25)
+    assert rounded_timestamp(timestamp) == u'2015-06-25 13:00:00'
+
+
+def test_rounded_timestamp_none_specified(monkeypatch):
+    # Freeze datetime returned from datetime.datetime.utcnow()
+    class frozen_datetime(datetime.datetime):
+        @classmethod
+        def utcnow(cls):
+            return datetime.datetime(2015, 6, 25, 13, 13, 25)
+    monkeypatch.setattr(datetime, 'datetime', frozen_datetime)
+    assert rounded_timestamp(timestamp=None) == u'2015-06-25 13:00:00'
+
+
+def test_base32_encode_str():
+    assert base32_encode_str(byte_str=b'byte input') == u'mj4xizjanfxha5lu'
+
+
+ at pytest.mark.skipif(sys.version_info < (3, 0), reason="python3 only")
+def test_base32_encode_str_not_byte_string():
+    with pytest.raises(TypeError):
+        base32_encode_str(byte_str=u'not a byte string')
+
+
+def test_key_decrypt_prompt(mocker):
+    # Valid private PEM key
+    mocker.patch(builtin('open'), lambda *_: io.StringIO(PEM_PRIVATE_KEY))
+    key = key_decrypt_prompt('private.key')
+    assert isinstance(key, Crypto.PublicKey.RSA._RSAobj)
+    assert key.has_private()
+
+
+def test_key_decrypt_prompt_public_key(mocker):
+    # Valid public PEM key
+    private_key = Crypto.PublicKey.RSA.importKey(PEM_PRIVATE_KEY)
+    pem_public_key = private_key.publickey().exportKey().decode('utf-8')
+    mocker.patch(builtin('open'), lambda *_: io.StringIO(pem_public_key))
+
+    with pytest.raises(ValueError):
+        key_decrypt_prompt('public.key')
+
+
+def test_key_decrypt_prompt_malformed_key(mocker):
+    mocker.patch(builtin('open'), lambda *_: io.StringIO(PEM_INVALID_KEY))
+    with pytest.raises(ValueError):
+        key_decrypt_prompt('private.key')
+
+
+def test_key_decrypt_prompt_incorrect_size(mocker):
+    # Key which is not 1024 bits
+    private_key_1280 = Crypto.PublicKey.RSA.generate(1280)
+    pem_key_1280 = private_key_1280.exportKey().decode('utf-8')
+    mocker.patch(builtin('open'), lambda *_: io.StringIO(pem_key_1280))
+    with pytest.raises(ValueError):
+        key_decrypt_prompt('512-bit-private.key')
+
+
+def test_key_decrypt_prompt_encrypted(mocker):
+    mocker.patch(builtin('open'), lambda *_: io.StringIO(PEM_ENCRYPTED))
+
+    # Load with correct password
+    mocker.patch('getpass.getpass', lambda *_: u'password')
+    key = key_decrypt_prompt('encrypted_private.key')
+    assert isinstance(key, Crypto.PublicKey.RSA._RSAobj)
+
+    # Load with incorrect password
+    mocker.patch('getpass.getpass', lambda *_: u'incorrect password')
+    with pytest.raises(ValueError):
+        key_decrypt_prompt('encrypted_private.key')
+
+
+def test_try_make_dir_makedirs(mocker):
+    mocker.patch('os.makedirs')
+    try_make_dir('dir')
+    os.makedirs.assert_called_once_with('dir')
+
+
+def test_try_make_dir_makedirs_dir_already_exists(mocker):
+    mocker.patch('os.makedirs', side_effect=OSError)
+    mocker.patch('os.path.isdir', return_value=True)
+    try_make_dir('dir')
+    os.path.isdir.assert_called_once_with('dir')
+
+
+def test_try_make_dir_makedirs_dir_other_error(mocker):
+    mocker.patch('os.makedirs', side_effect=OSError)
+    mocker.patch('os.path.isdir', return_value=False)
+    with pytest.raises(OSError):
+        try_make_dir('dir')
+
+
+def test_is_directory_empty_empty(mocker):
+    # Directory is empty
+    mocker.patch('os.listdir', return_value=[])
+    assert is_directory_empty('dir_empty/')
+
+
+def test_is_directory_empty_not_empty(mocker):
+    # Directory is empty
+    mocker.patch('os.listdir', return_value=['filename'])
+    assert not is_directory_empty('dir_not_empty/')
diff --git a/test/util.py b/test/util.py
new file mode 100644
index 0000000..ec61837
--- /dev/null
+++ b/test/util.py
@@ -0,0 +1,12 @@
+# -*- coding: utf-8 -*-
+import sys
+
+
+def builtin(name):
+    """
+    Provide the correct import name for builtins on Python 2 or Python 3
+    """
+    if sys.version_info >= (3,):
+        return 'builtins.{}'.format(name)
+    else:
+        return '__builtin__.{}'.format(name)
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..af6e48a
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,29 @@
+# Tox (http://tox.testrun.org/) is a tool for running tests
+# in multiple virtualenvs. This configuration file will run the
+# test suite on all supported python versions. To use it, "pip install tox"
+# and then run "tox" from this directory.
+
+[tox]
+envlist = style, py27, py34, docs
+
+[testenv]
+deps = -rrequirements.txt
+       -rtest-requirements.txt
+# Pass Chutney enviroment variables into tox virtual enviroments.
+passenv = CHUTNEY_ONION_ADDRESS CHUTNEY_CLIENT_PORT
+commands = py.test
+
+[testenv:docs]
+basepython=python
+changedir=docs
+deps=sphinx
+commands=
+    sphinx-apidoc -e -f -o . ../onionbalance/
+    sphinx-build -W -b html -d {envtmpdir}/docs . {envtmpdir}/html
+
+[testenv:style]
+basepython=python
+deps=pylint
+     flake8
+commands=pylint onionbalance {posargs: -E}
+         flake8 onionbalance

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-privacy/packages/onionbalance.git



More information about the Pkg-privacy-commits mailing list