diff --git a/LICENSE b/LICENSE
--- a/LICENSE
+++ b/LICENSE
@@ -1,674 +1,7 @@
-              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.
+Copyright (c) 2016 Serokell
 
-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".
+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:
 
-  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 above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
-  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>.
+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.
diff --git a/bench/Network/Common/Bench/Network/Commons.hs b/bench/Network/Common/Bench/Network/Commons.hs
new file mode 100644
--- /dev/null
+++ b/bench/Network/Common/Bench/Network/Commons.hs
@@ -0,0 +1,186 @@
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DeriveGeneric  #-}
+
+module Bench.Network.Commons
+    ( MsgId
+    , Ping (..)
+    , Pong (..)
+    , Payload (..)
+    , curTimeMcs
+    , logMeasure
+
+    , loadLogConfig
+
+    , Timestamp
+    , MeasureEvent (..)
+    , MeasureInfo (..)
+    , LogMessage (..)
+    , measureInfoParser
+    , logMessageParser
+    ) where
+
+import           Control.Applicative   ((<|>))
+import           Control.Monad         (join)
+import           Control.Monad.Trans   (MonadIO (..))
+import           Data.Binary           (Binary)
+import           Data.Binary           (Binary (..))
+import qualified Data.ByteString.Lazy  as BL
+import           Data.Data             (Data)
+import           Data.Default          (def)
+import           Data.Functor          (($>))
+import qualified Data.HashMap.Strict   as M
+import           Data.Int              (Int64)
+import           Data.Monoid           ((<>))
+import           Data.Text.Buildable   (Buildable, build)
+import           Data.Time.Clock.POSIX (getPOSIXTime)
+import qualified Formatting            as F
+import           GHC.Generics          (Generic)
+import           Prelude               hiding (takeWhile)
+
+import           Data.Attoparsec.Text  (Parser, char, decimal, string, takeWhile)
+
+import           Control.TimeWarp.Rpc  (Message (formatMessage), messageName')
+import           System.Wlog           (LoggerConfig (..), Severity (..), WithLogger,
+                                        logInfo, parseLoggerConfig, traverseLoggerConfig)
+
+
+-- * Transfered data types
+
+type MsgId = Int
+
+-- | Serializes into message of (given size + const)
+data Payload = Payload
+    { getPayload :: Int64
+    } deriving (Generic, Data)
+
+data Ping = Ping MsgId Payload
+    deriving (Generic, Data, Binary)
+
+data Pong = Pong MsgId Payload
+    deriving (Generic, Data, Binary)
+
+instance Message Ping where
+    formatMessage = messageName'
+
+instance Message Pong where
+    formatMessage = messageName'
+
+instance Binary Payload where
+    get = Payload . BL.length <$> get
+    put (Payload l) = put $ BL.replicate l 42
+
+
+-- * Util
+
+type Timestamp = Integer
+
+curTimeMcs :: MonadIO m => m Timestamp
+curTimeMcs = liftIO $ round . ( * 1000000) <$> getPOSIXTime
+
+logMeasure :: (MonadIO m, WithLogger m) => MeasureEvent -> MsgId -> Payload -> m ()
+logMeasure miEvent miId miPayload = do
+    miTime <- curTimeMcs
+    logInfo $ F.sformat F.build $ LogMessage MeasureInfo{..}
+
+defaultLogConfig :: LoggerConfig
+defaultLogConfig = def
+    { lcSeverity   = Just Warning
+    , lcSubloggers = M.fromList
+        [ withName "sender" def
+            { lcSeverity = Just Info
+            , lcSubloggers = M.fromList
+                [ withName "comm" def
+                    { lcSeverity = Just Error
+                    }
+                ]
+            }
+        , withName "receiver" def
+            { lcSeverity = Just Info
+            , lcSubloggers = M.fromList
+                [ withName "comm" def
+                    { lcSeverity = Just Error
+                    }
+                ]
+            }
+        ]
+    }
+  where
+    withName = (,)
+
+loadLogConfig :: MonadIO m => Maybe FilePath -> Maybe FilePath -> m ()
+loadLogConfig logsPrefix configFile = do
+    loggerConfig <- maybe (return defaultLogConfig) parseLoggerConfig configFile
+    traverseLoggerConfig id loggerConfig logsPrefix
+
+
+-- * Logging & parsing
+
+-- ** Measure event
+
+-- | Type of event in measurement.
+data MeasureEvent
+    = PingSent
+    | PingReceived
+    | PongSent
+    | PongReceived
+    deriving (Show, Eq, Ord, Enum, Bounded)
+
+instance Buildable MeasureEvent where
+    build PingSent     = "• → "
+    build PingReceived = " → •"
+    build PongSent     = " ← •"
+    build PongReceived = "• ← "
+
+measureEventParser :: Parser MeasureEvent
+measureEventParser = string "• → " $> PingSent
+                 <|> string " → •" $> PingReceived
+                 <|> string " ← •" $> PongSent
+                 <|> string "• ← " $> PongReceived
+
+
+-- ** Measure info
+
+-- | Single event in measurement.
+data MeasureInfo = MeasureInfo
+    { miId      :: MsgId
+    , miEvent   :: MeasureEvent
+    , miTime    :: Timestamp
+    , miPayload :: Payload
+    }
+
+instance Buildable MeasureInfo where
+    build MeasureInfo{..} = mconcat
+        [ build miId
+        , " "
+        , build miEvent
+        , " ("
+        , build $ getPayload miPayload
+        , ") "
+        , build miTime
+        ]
+
+measureInfoParser :: Parser MeasureInfo
+measureInfoParser = do
+    miId <- decimal
+    _ <- string " "
+    miEvent <- measureEventParser
+    _ <- string " ("
+    miPayload <- Payload <$> decimal
+    _ <- string ") "
+    miTime <- decimal
+    return MeasureInfo{..}
+
+
+-- ** Log message
+
+-- | Allows to extract bare message content from logs.
+-- Just inserts separator at beginning.
+data LogMessage a = LogMessage a
+
+instance Buildable a => Buildable (LogMessage a) where
+    build (LogMessage a) = "#" <> build a
+
+logMessageParser :: Parser a -> Parser (Maybe (LogMessage a))
+logMessageParser p = (takeWhile (/= '#') >>) . join $ do
+        (char '#' *> pure (Just . LogMessage <$> p))
+    <|> pure (pure Nothing)
diff --git a/bench/Network/LogReader/LogReaderOptions.hs b/bench/Network/LogReader/LogReaderOptions.hs
new file mode 100644
--- /dev/null
+++ b/bench/Network/LogReader/LogReaderOptions.hs
@@ -0,0 +1,35 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- | Command line options of pos-node.
+
+module LogReaderOptions
+       ( Args (..)
+       , argsParser
+       ) where
+
+import           Data.Monoid                ((<>))
+import           Options.Applicative.Simple (Parser, help, long, metavar, short,
+                                             showDefault, some, strOption, value)
+
+data Args = Args
+    { inputFiles :: ![FilePath]
+    , resultFile :: !FilePath
+    } deriving Show
+
+argsParser :: Parser Args
+argsParser =
+    Args <$>
+    some
+        (strOption $
+            short 'i'
+              <> long "input"
+              <> metavar "FILEPATH" <>
+             help "Files to get data from")
+    <*>
+    strOption
+        (short 'o'
+          <> long "output"
+          <> metavar "FILEPATH"
+          <> value "measures.csv"
+          <> showDefault <>
+         help "File to write results in csv form")
diff --git a/bench/Network/LogReader/Main.hs b/bench/Network/LogReader/Main.hs
new file mode 100644
--- /dev/null
+++ b/bench/Network/LogReader/Main.hs
@@ -0,0 +1,135 @@
+{-# LANGUAGE TypeApplications #-}
+
+import           Control.Applicative          (empty, (<|>))
+import           Control.Exception            (Exception)
+import           Control.Lens                 (at, (%=), (^.), _2,
+                                               _Just)
+import           Control.Monad                (forM_)
+import           Control.Monad.Catch          (handle)
+import           Control.Monad.State          (StateT (..), evalStateT, execStateT, get,
+                                               modify)
+import           Control.Monad.Trans          (lift, liftIO)
+import           Control.Monad.Trans.Resource (runResourceT)
+import           Data.Conduit                 (Source, yield, ($$), (=$=))
+import           Data.Conduit.Binary          (sinkFile, sourceFile)
+import qualified Data.Conduit.Binary          as CB
+import qualified Data.Conduit.List            as CL
+import           Data.Conduit.Text            (decode, encode, utf8)
+import           Data.List                    (intersperse)
+import qualified Data.Map                     as M
+import           Data.Text                    (Text)
+import           Data.Text.Buildable          (Buildable (..))
+import           Data.Typeable                (Typeable)
+import           Formatting                   (bprint, int, right, sformat, (%))
+import qualified Formatting                   as F
+import           System.IO                    (FilePath)
+
+import           Data.Attoparsec.Text         (parseOnly)
+import           Options.Applicative.Simple   (simpleOptions)
+
+import           Bench.Network.Commons        (LogMessage (..), MeasureEvent (..),
+                                               MeasureInfo (..), MsgId, Payload (..),
+                                               Timestamp, logMessageParser,
+                                               measureInfoParser)
+import           LogReaderOptions             (Args (..), argsParser)
+import           System.Wlog                  (LoggerNameBox, Severity (Info),
+                                               initLogging, logError, logWarning,
+                                               usingLoggerName, usingLoggerName)
+
+
+type Measures = M.Map MsgId (Payload, [(MeasureEvent, Timestamp)])
+
+newtype MeasureInfoDuplicateError = MeasureInfoDuplicateError (Timestamp, MeasureInfo)
+    deriving (Typeable)
+
+instance Show MeasureInfoDuplicateError where
+    show = F.formatToString F.build . build
+
+instance Buildable MeasureInfoDuplicateError where
+    build (MeasureInfoDuplicateError (was, new)) = mconcat
+        ["Duplicate measure: was "
+        , build was
+        , " but meet "
+        , build new
+        ]
+
+instance Exception MeasureInfoDuplicateError
+
+
+type RowId = Int
+
+analyze :: FilePath -> StateT Measures (LoggerNameBox IO) ()
+analyze file =
+    catchE . flip evalStateT 0 . runResourceT $
+        sourceFile file =$= CB.lines =$= CL.iterM (const $ modify succ)
+            =$= decode utf8 $$ CL.mapM_ (lift . saveMeasure)
+  where
+    saveMeasure :: Text -> StateT RowId (StateT Measures (LoggerNameBox IO)) ()
+    saveMeasure row = do
+        case parseOnly (logMessageParser measureInfoParser) row of
+            Left err -> do
+                rowNo <- get
+                logWarning $
+                    sformat ("Parse error at file "%F.build%" (line "%F.int%"): "%F.build)
+                    file rowNo err
+            Right (Just (LogMessage MeasureInfo{..})) -> lift $ do
+                at miId %= (<|> Just (miPayload, mempty))
+                at miId . _Just . _2 %= ((miEvent, miTime):)
+                --mwas <- singular (at miId . _Just . _2) . at miEvent <<.= Just miTime
+                --forM_ mwas $ \was -> throwM $ MeasureInfoDuplicateError (was, mi)
+            Right _ -> return ()
+
+    catchE = handle @_ @MeasureInfoDuplicateError $ logError . sformat F.build
+
+
+printMeasures :: FilePath -> Measures -> LoggerNameBox IO ()
+printMeasures file measures = runResourceT $
+    source $$ encode utf8 =$= sinkFile file
+  where
+    source = printHeader >> mapM_ printMeasure (M.toList measures)
+
+    printHeader = printRow $ "MsgId" : "Size" : map (sformat F.build) eventsUniverse
+
+    printMeasure :: Monad m
+                 => (MsgId, (Payload, [(MeasureEvent, Timestamp)])) -> Source m Text
+    printMeasure (mid, (Payload p, mm)) = do
+        case uniqMap mm of
+            Just mm' -> printRow $ sformat int mid
+                          : sformat int p
+                          : [ maybe "-" (sformat int) $ mm' ^. at ev | ev <- eventsUniverse ]
+            _ -> return ()
+
+    printRow :: Monad m => [Text] -> Source m Text
+    printRow = yield
+             . sformat (F.build%"\n")
+             . mconcat
+             . intersperse ","
+             . alignColumns
+
+    uniqMap = foldl upd (Just mempty)
+      where
+        upd m (ev, ts) = m >>= \m' ->
+            case ev `M.lookup` m' of
+              Nothing -> return $ M.insert ev ts m'
+              _       -> fail ""
+
+    alignColumns = map (\(s, m) -> bprint (right s ' ') m)
+                  . zip (7 : 7 : (18 <$ eventsUniverse))
+
+    eventsUniverse = [minBound .. maxBound]
+
+getOptions :: IO Args
+getOptions = (\(a, ()) -> a) <$> simpleOptions
+    "bench-log-reader"
+    "Utility to extract measures from logs into csv file"
+    "Use it!"
+    argsParser
+    empty
+
+main :: IO ()
+main = usingLoggerName mempty $ do
+    initLogging Info
+    Args{..} <- liftIO getOptions
+    measures <- flip execStateT M.empty $
+        forM_ inputFiles analyze
+    printMeasures resultFile measures
diff --git a/bench/Network/Receiver/Main.hs b/bench/Network/Receiver/Main.hs
new file mode 100644
--- /dev/null
+++ b/bench/Network/Receiver/Main.hs
@@ -0,0 +1,45 @@
+module Main where
+
+import           Control.Applicative        (empty)
+import           Control.Monad              (when)
+import           Control.Monad.Trans        (liftIO)
+import           GHC.IO.Encoding            (setLocaleEncoding, utf8)
+
+import           Bench.Network.Commons      (MeasureEvent (..), Ping (..), Pong (..),
+                                             loadLogConfig, logMeasure)
+import           Control.TimeWarp.Rpc       (Binding (AtPort), Listener (..), listen,
+                                             plainBinaryP, reply, runDialog, runTransfer)
+import           Control.TimeWarp.Timed     (for, runTimedIO, sec, wait)
+import           Options.Applicative.Simple (simpleOptions)
+import           System.Wlog                (usingLoggerName)
+
+import           ReceiverOptions            (Args (..), argsParser)
+
+main :: IO ()
+main = do
+    (Args {..}, ()) <-
+        simpleOptions
+            "bench-receiver"
+            "Server utility for benches"
+            "Use it!"
+            argsParser
+            empty
+
+    runNode "receiver" $ do
+        loadLogConfig logsPrefix logConfig
+        liftIO $ setLocaleEncoding utf8
+
+        stopper <- listen (AtPort port)
+            [ Listener $
+                \(Ping mid payload) -> do
+                    logMeasure PingReceived mid payload
+                    when (not noPong) $ do
+                        logMeasure PongSent mid payload
+                        reply $ Pong mid payload
+            ]
+        wait (for duration sec)
+        stopper
+
+  where
+    runNode name = runTimedIO . usingLoggerName name
+                 . runTransfer (pure ()) . runDialog plainBinaryP
diff --git a/bench/Network/Receiver/ReceiverOptions.hs b/bench/Network/Receiver/ReceiverOptions.hs
new file mode 100644
--- /dev/null
+++ b/bench/Network/Receiver/ReceiverOptions.hs
@@ -0,0 +1,60 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- | Command line options of pos-node.
+
+module ReceiverOptions
+       ( Args (..)
+       , argsParser
+       ) where
+
+import           Data.Monoid                ((<>))
+import           Data.Word                  (Word16)
+import           Options.Applicative.Simple (Parser, auto, help, long, metavar, option,
+                                             optional, short, showDefault, strOption,
+                                             switch, value)
+
+data Args = Args
+    { logConfig  :: !(Maybe FilePath)
+    , logsPrefix :: !(Maybe FilePath)
+    , port       :: !Word16
+    , noPong     :: !Bool
+    , duration   :: !Int
+    }
+  deriving Show
+
+--TODO introduce subcommands
+argsParser :: Parser Args
+argsParser =
+    Args <$>
+    optional
+        (strOption
+            (long "log-config"
+              <> metavar "FILEPATH" <>
+             help "Path to logger configuration")
+        )
+    <*>
+    optional
+        (strOption $
+         long "logs-prefix" <> metavar "FILEPATH" <> help "Prefix to logger output path")
+    <*>
+    option
+        auto
+        (short 'p'
+          <> long "port"
+          <> metavar "INTEGER"
+          <> value 3000
+          <> showDefault <>
+         help "Port to work on")
+    <*>
+    switch
+        (long "no-pong" <>
+         help "Don't send pong")
+    <*>
+    option
+        auto
+        (short 'd'
+          <> long "duration"
+          <> metavar "INTEGER"
+          <> value 10
+          <> showDefault <>
+         help "Time to run before stopping, seconds")
diff --git a/bench/Network/Sender/Main.hs b/bench/Network/Sender/Main.hs
new file mode 100644
--- /dev/null
+++ b/bench/Network/Sender/Main.hs
@@ -0,0 +1,68 @@
+{-# LANGUAGE FlexibleContexts #-}
+
+module Main where
+
+import           Control.Applicative         (empty)
+import           Control.Concurrent.Async    (forConcurrently)
+import           Control.Monad               (forM, mzero, void, when)
+import           Control.Monad.Trans         (lift, liftIO)
+import           Control.Monad.Trans.Control (liftBaseWith)
+import           Control.Monad.Trans.Maybe   (runMaybeT)
+import           GHC.IO.Encoding             (setLocaleEncoding, utf8)
+import           System.Random               (randomRIO)
+
+import           Bench.Network.Commons       (MeasureEvent (..), Payload (..), Ping (..),
+                                              Pong (..), loadLogConfig, logMeasure)
+import           Control.TimeWarp.Rpc        (Binding (AtConnTo), Listener (..), listen,
+                                              plainBinaryP, runDialog, runTransfer, send)
+import           Control.TimeWarp.Timed      (Microsecond, for, interval, mcs, runTimedIO,
+                                              runTimedIO, sec, startTimer, wait)
+import           Options.Applicative.Simple  (simpleOptions)
+import           SenderOptions               (Args (..), argsParser)
+import           System.Wlog                 (usingLoggerName)
+
+main :: IO ()
+main = do
+    (Args {..}, ()) <-
+        simpleOptions
+            "bench-sender"
+            "Sender utility for benches"
+            "Use it!"
+            argsParser
+            empty
+
+    runNode "sender" $ do
+        loadLogConfig logsPrefix logConfig
+        liftIO $ setLocaleEncoding utf8
+
+        let sendDelay :: Microsecond
+            sendDelay = maybe 0 (\r -> interval ((1000000 :: Int) `div` r) mcs) msgRate
+        let tasksIds  = [[tid, tid + threadNum .. msgNum] | tid <- [1..threadNum]]
+        runConcurrently tasksIds $
+            \msgIds -> runNetworking $ do
+                closeConns <- forM recipients $
+                    \addr -> listen (AtConnTo addr)
+                        [ Listener $
+                            \(Pong mid payload) -> logMeasure PongReceived mid payload
+                        ]
+                workTimer <- startTimer
+                void . runMaybeT . forM msgIds $
+                    \msgId -> do
+                        lift $ wait (for sendDelay)
+                        working <- lift workTimer
+                        when (working > interval duration sec) mzero
+
+                        lift $ runConcurrently (zip [0..] recipients) $
+                            \(no, addr) -> do
+                                let sMsgId  = no * msgNum + msgId
+                                payload <- liftIO $
+                                    Payload <$> randomRIO (0, payloadBound)
+                                logMeasure PingSent sMsgId payload
+                                send addr $ Ping sMsgId payload
+                -- wait for responses
+                wait (for 1 sec)
+                sequence_ closeConns
+  where
+    runNode name = runTimedIO . usingLoggerName name
+    runNetworking = runTransfer (pure ()) . runDialog plainBinaryP
+    runConcurrently l f = liftBaseWith $ \run -> void $ forConcurrently l (run . f)
diff --git a/bench/Network/Sender/SenderOptions.hs b/bench/Network/Sender/SenderOptions.hs
new file mode 100644
--- /dev/null
+++ b/bench/Network/Sender/SenderOptions.hs
@@ -0,0 +1,99 @@
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- | Command line options of pos-node.
+
+module SenderOptions
+       ( Args (..)
+       , argsParser
+       ) where
+
+import           Control.TimeWarp.Rpc       (NetworkAddress)
+import           Data.Int                   (Int64)
+import           Data.Monoid                ((<>))
+import           Data.String                (fromString)
+import           Options.Applicative.Simple (Parser, auto, help, long, metavar, option,
+                                             optional, short, showDefault, some,
+                                             strOption, value)
+import           Serokell.Util.OptParse     (fromParsec)
+import           Serokell.Util.Parse        (connection)
+
+data Args = Args
+    { logConfig    :: !(Maybe FilePath)
+    , logsPrefix   :: !(Maybe FilePath)
+    , recipients   :: ![NetworkAddress]
+    , threadNum    :: !Int
+    , msgNum       :: !Int
+    , msgRate      :: !(Maybe Int)
+    , duration     :: !Int
+    , payloadBound :: !Int64
+    }
+  deriving Show
+
+--TODO introduce subcommands
+argsParser :: Parser Args
+argsParser =
+    Args <$>
+    optional
+        (strOption
+            (long "log-config"
+              <> metavar "FILEPATH" <>
+             help "Path to logger configuration")
+        )
+    <*>
+    optional
+        (strOption $
+         long "logs-prefix" <> metavar "FILEPATH" <> help "Prefix to logger output path")
+    <*>
+    some
+        (option (fromParsec recipient) $
+         long "peer" <> metavar "HOST:PORT" <> help "Recipient's ip:port")
+    <*>
+    option
+        auto
+        (short 't'
+          <> long "thread-num"
+          <> metavar "INTEGER"
+          <> value 5
+          <> showDefault <>
+         help "Number of threads to use")
+    <*>
+    option
+        auto
+        (short 'm'
+          <> long "msg-num"
+          <> metavar "INTEGER"
+          <> value 1000
+          <> showDefault <>
+         help "Number of messages to send")
+    <*>
+    optional
+        (option
+            auto
+            (short 'r'
+              <> long "msg-rate"
+              <> metavar "INTEGER" <>
+             help "Number of messages to send per second")
+        )
+    <*>
+    option
+        auto
+        (short 'd'
+          <> long "duration"
+          <> metavar "INTEGER"
+          <> value 10
+          <> showDefault <>
+         help "Time to run before stopping, seconds")
+     <*>
+    option
+        auto
+        (short 'p'
+          <> long "payload"
+          <> metavar "INTEGER"
+          <> value 0
+          <> showDefault <>
+         help "Defines upper bound on sent message size")
+  where
+    recipient = connection >>= \(h, mp) ->
+        case mp of
+            Just p -> return (fromString h, p)
+            _      -> fail $ "No port specified for host " <> h
diff --git a/examples/ping-pong/Main.hs b/examples/ping-pong/Main.hs
new file mode 100644
--- /dev/null
+++ b/examples/ping-pong/Main.hs
@@ -0,0 +1,79 @@
+{-# LANGUAGE DeriveAnyClass  #-}
+{-# LANGUAGE OverloadedLists #-}
+
+-- | Example of simple ping-pong network application.
+
+module Main where
+
+import           Control.Concurrent       (forkIO)
+import           Control.Monad            (void)
+import           Control.Monad.IO.Class   (MonadIO (liftIO))
+
+import           Data.Binary              (Binary)
+import           Data.Data                (Data)
+import           Data.Default             (def)
+import           Data.Time.Clock          (getCurrentTime)
+
+import           Formatting               (sformat, shown, (%))
+import           GHC.Generics             (Generic)
+import           Serokell.Util.Concurrent (threadDelay)
+import           System.Wlog              (LoggerConfig (..), LoggerName, Severity (Info),
+                                           logInfo, traverseLoggerConfig, usingLoggerName)
+
+import           Control.TimeWarp.Rpc     (BinaryP, Binding (AtPort), Dialog,
+                                           Listener (..), Message (..), Transfer, listen,
+                                           localhost, messageName', plainBinaryP,
+                                           runDialog, runTransfer, send)
+import           Control.TimeWarp.Timed   (for, runTimedIO, sec, wait)
+
+runNode :: LoggerName -> Dialog (BinaryP ()) (Transfer ()) () -> IO ()
+runNode name = void . forkIO . runTimedIO . usingLoggerName name . runTransfer (pure ())
+             . runDialog plainBinaryP
+
+ppLoggerConfig :: LoggerConfig
+ppLoggerConfig = def { lcSubloggers = [("ping", infoConf), ("pong", infoConf)] }
+  where
+    infoConf = def { lcSeverity = Just Info }
+
+initLogging :: MonadIO m => m ()
+initLogging = traverseLoggerConfig id ppLoggerConfig Nothing
+
+data Ping = Ping
+    deriving (Generic, Binary, Data)
+
+data Pong = Pong
+    deriving (Generic, Binary, Data)
+
+instance Message Ping where
+    formatMessage = messageName'
+
+instance Message Pong where
+    formatMessage = messageName'
+
+main :: IO ()
+main = do
+    initLogging
+
+    runNode "ping" $ do
+        logInfo "Running..."
+
+        wait (for 2 sec)
+        send (localhost, 5555) Ping
+
+        void $ listen (AtPort 4444)
+            [ Listener $ \Pong -> do
+                curTime <- liftIO getCurrentTime
+                logInfo $ sformat ("Get Pong at "%shown) curTime
+            ]
+
+    runNode "pong" $ do
+        logInfo "Running..."
+
+        void $ listen (AtPort 5555)
+            [ Listener $ \Ping -> do
+                curTime <- liftIO getCurrentTime
+                logInfo $ sformat ("Get Ping at "%shown) curTime
+                send (localhost, 4444) Pong
+            ]
+
+    threadDelay $ sec 5
diff --git a/examples/playground/Main.hs b/examples/playground/Main.hs
new file mode 100644
--- /dev/null
+++ b/examples/playground/Main.hs
@@ -0,0 +1,386 @@
+{-# LANGUAGE DeriveAnyClass        #-}
+{-# LANGUAGE DeriveGeneric         #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE TupleSections         #-}
+{-# LANGUAGE TypeFamilies          #-}
+
+module Main
+    ( main
+    , yohohoScenario
+--    , rpcScenario
+    , transferScenario
+    , proxyScenario
+    , slowpokeScenario
+    , closingServerScenario
+    , pendingForkStrategy
+--    , runEmulation
+--    , runReal
+    ) where
+
+import           Control.Concurrent.MVar           (newEmptyMVar, putMVar, takeMVar)
+import           Control.Concurrent.STM.TVar       (modifyTVar, newTVar, readTVar)
+import           Control.Monad                     (forM_, replicateM_, when)
+import           Control.Monad.STM                 (atomically)
+import           Control.Monad.Trans               (MonadIO (liftIO))
+import           Data.Binary                       (Binary, Get, Put, get, put)
+import           Data.Conduit                      (yield, (=$=))
+import qualified Data.Conduit.List                 as CL
+import           Data.Conduit.Serialization.Binary (conduitGet, conduitPut)
+import           Data.Data                         (Data)
+import           Data.Default                      (def)
+import           Data.MessagePack                  (MessagePack (..))
+import           Data.Monoid                       ((<>))
+import           Data.Text.Buildable               (Buildable (..))
+import           Data.Word                         (Word16)
+import           Formatting                        (sformat, shown, string, (%))
+import           GHC.Generics                      (Generic)
+
+import           System.Wlog                       (LoggerName, Severity (Debug),
+                                                    initLogging, logDebug, logInfo,
+                                                    usingLoggerName)
+
+import           Control.TimeWarp.Rpc              (BinaryP (..), Binding (..),
+                                                    ForkStrategy (..), Listener (..),
+                                                    ListenerH (..), Message,
+                                                    MonadTransfer (..), NetworkAddress,
+                                                    Port, listen, listenH, listenR,
+                                                    localhost, messageName', plainBinaryP,
+                                                    reconnectPolicy, reply, replyRaw,
+                                                    runDialog, runTransfer, runTransferS,
+                                                    send, sendH, sendR, setForkStrategy)
+import           Control.TimeWarp.Timed            (MonadTimed (wait), Second, after, for,
+                                                    fork_, interval, ms, runTimedIO,
+                                                    schedule, sec, sec', till)
+
+-- use ghci; this is only for logger debugging
+main :: IO ()
+main = return ()
+
+{-
+runReal :: MsgPackRpc a -> IO a
+runReal = runMsgPackRpc
+
+runEmulation :: PureRpc IO a -> IO a
+runEmulation scenario = do
+    gen <- newStdGen
+    runPureRpc delays gen scenario
+  where
+    delays :: Microsecond
+    delays = interval 50 ms
+-}
+
+-- * data types
+
+data Ping = Ping
+    deriving (Generic, Data, Binary, MessagePack, Message)
+
+instance Buildable Ping where
+    build _ = "Ping"
+
+data Pong = Pong
+    deriving (Generic, Data, Binary, MessagePack, Message)
+
+instance Buildable Pong where
+    build _ = "Pong"
+
+data EpicRequest = EpicRequest
+    { num :: Int
+    , msg :: String
+    } deriving (Generic, Data, Binary, MessagePack)
+
+instance Buildable EpicRequest where
+    build EpicRequest{..} = "EpicRequest " <> build num <> " " <> build msg
+
+instance Message EpicRequest
+
+-- * scenarios
+
+-- | Examples management info.
+narrator :: LoggerName
+narrator = "*"
+
+-- Emulates dialog of two guys, maybe several times, in parallel:
+-- 1: Ping
+-- 2: Pong
+-- 1: EpicRequest ...
+-- 2: <prints result>
+yohohoScenario :: IO ()
+yohohoScenario = runTimedIO $ do
+    initLogging Debug
+    (saveWorker, killWorkers) <- newNode narrator workersManager
+
+    -- guy 1
+    newNode "guy.1" . fork_ $ do
+        saveWorker $ listen (AtPort $ guysPort 1)
+            [ Listener $ \Pong ->
+              do logDebug "Got Pong!"
+                 reply $ EpicRequest 14 " men on the dead man's chest"
+            ]
+        -- guy 1 initiates dialog
+        wait (for 100 ms)
+        replicateM_ 2 $ do
+            send (guy 2) Ping
+            logInfo "Sent"
+
+
+    -- guy 2
+    newNode "guy.2" . fork_ $ do
+        saveWorker $ listen (AtPort $ guysPort 2)
+            [ Listener $ \Ping ->
+              do logDebug "Got Ping!"
+                 send (guy 1) Pong
+            ]
+        saveWorker $ listen (AtConnTo $ guy 1)
+            [ Listener $ \EpicRequest{..} ->
+              do logDebug "Got EpicRequest!"
+                 wait (for 0.1 sec')
+                 logInfo $ sformat (shown%string) (num + 1) msg
+            ]
+
+    wait (till finish)
+    newNode narrator killWorkers
+    wait (for 100 ms)
+  where
+    finish :: Second
+    finish = 5
+
+    newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
+
+    guy :: Word16 -> NetworkAddress
+    guy = (localhost, ) . guysPort
+
+    guysPort :: Word16 -> Port
+    guysPort = (+10000)
+
+
+-- | Example of `Transfer` usage
+transferScenario :: IO ()
+transferScenario = runTimedIO $ do
+    initLogging Debug
+    (saveWorker, killWorkers) <- newNode narrator workersManager
+
+    newNode "node.server" $
+        let listener req = do
+                logInfo $ sformat ("Got "%shown) req
+                replyRaw $ yield (put $ sformat "Ok!") =$= conduitPut
+        in  saveWorker $ listenRaw (AtPort 1234) $
+                conduitGet decoder =$= CL.mapM_ listener
+
+    wait (for 100 ms)
+
+    newNode "node.client-1" $
+        schedule (after 200 ms) $ do
+            saveWorker $ listenRaw (AtConnTo (localhost, 1234)) $
+                    conduitGet get =$= CL.mapM_ logInfo
+            forM_ ([1..5] :: [Int]) $ \i ->
+                sendRaw (localhost, 1234) $ yield i
+                                         =$= CL.map Left
+                                         =$= CL.map encoder
+                                         =$= conduitPut
+--                                     =$= awaitForever (\m -> yield "trash" >> yield m)
+
+    newNode "node.client-2" $
+        schedule (after 200 ms) $ do
+            sendRaw (localhost, 1234) $  CL.sourceList ([1..5] :: [Int])
+                                     =$= CL.map (, -1)
+                                     =$= CL.map Right
+                                     =$= CL.map encoder
+                                     =$= conduitPut
+            saveWorker $ listenRaw (AtConnTo (localhost, 1234)) $
+                conduitGet get =$= CL.mapM_ logInfo
+
+    wait (for 1000 ms)
+    newNode narrator killWorkers
+    wait (for 100 ms)
+  where
+    decoder :: Get (Either Int (Int, Int))
+    decoder = do
+        magic <- get
+        when (magic /= magicVal) $
+            fail "Missed magic constant!"
+        get
+
+    encoder :: Either Int (Int, Int) -> Put
+    encoder d = put magicVal >> put d
+
+    magicVal :: Int
+    magicVal = 234
+
+    newNode name = usingLoggerName name . runTransfer (pure ())
+
+{-
+rpcScenario :: IO ()
+rpcScenario = runTimedIO $ do
+    liftIO $ initLogging ["server", "cli"] Debug
+    usingLoggerName "server" . runTransfer . runBinaryDialog . runRpc $
+        work (till finish) $
+            serve 1234
+                [ Method $ \Ping -> do
+                  do logInfo "Got Ping! Wait a sec..."
+                     wait (for 1000 ms)
+                     logInfo "Replying"
+                     return Pong
+                ]
+
+    wait (for 100 ms)
+    usingLoggerName "client" . runTransfer . runBinaryDialog . runRpc $ do
+        Pong <- call (localhost, 1234) Ping
+        logInfo "Got Pong!"
+    return ()
+  where
+    finish :: Second
+    finish = 5
+
+-}
+
+-- * Blind proxy scenario, illustrates work with headers and raw data.
+proxyScenario :: IO ()
+proxyScenario = runTimedIO $ do
+    liftIO $ initLogging Debug
+    (saveWorker, killWorkers) <- newNode narrator workersManager
+
+    lock <- liftIO newEmptyMVar
+    let sync act = liftIO (putMVar lock ()) >> act >> liftIO (takeMVar lock)
+
+    -- server
+    newNode "server" . fork_ $
+        saveWorker $ listenH (AtPort 5678)
+            [ ListenerH $ \(h, EpicRequest{..}) -> sync . logInfo $
+                sformat ("Got request!: "%shown%" "%shown%"; h = "%shown)
+                num msg (int h)
+            ]
+
+    -- proxy
+    newNode "proxy" . fork_ $
+        saveWorker $ listenR (AtPort 1234)
+            [ ListenerH $ \(h, EpicRequest _ _) -> sync . logInfo $
+                sformat ("Proxy! h = "%shown) h
+            ]
+            $ \(h, raw) -> do
+                when (h < 5) $ do
+                    sendR (localhost, 5678) h raw
+                    sync $ logInfo $ sformat ("Resend "%shown) h
+                return $ even (int h)
+
+
+    wait (for 100 ms)
+
+    -- client
+    newNode "client" . fork_  $
+        forM_ [1..10] $
+            \i -> sendH (localhost, 1234) (int i) $ EpicRequest 34 "lol"
+
+    wait (till finish)
+    newNode narrator killWorkers
+    wait (for 100 ms)
+  where
+    finish :: Second
+    finish = 1
+
+    newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog packing
+
+    packing :: BinaryP Int
+    packing = BinaryP
+
+    int :: Int -> Int
+    int = id
+
+-- | Slowpoke server scenario
+slowpokeScenario :: IO ()
+slowpokeScenario = runTimedIO $ do
+    initLogging Debug
+    (saveWorker, killWorkers) <- newNode narrator workersManager
+
+    newNode "server" . fork_ $ do
+        wait (for 3 sec)
+        saveWorker $ listen (AtPort 1234)
+            [ Listener $ \Ping -> logDebug "Got Ping!"
+            ]
+
+    newNode "client" . fork_ $ do
+        wait (for 100 ms)
+        replicateM_ 3 $ send (localhost, 1234) Ping
+
+    wait (till finish)
+    newNode narrator killWorkers
+    wait (for 100 ms)
+  where
+    finish :: Second
+    finish = 5
+
+    newNode name = usingLoggerName name . runTransferS settings (pure ())
+                 . runDialog plainBinaryP
+
+    settings = def
+        { reconnectPolicy = \failsInRow -> return $
+            if failsInRow < 5 then Just (interval 1 sec) else Nothing
+        }
+
+closingServerScenario :: IO ()
+closingServerScenario = runTimedIO $ do
+    initLogging Debug
+    (saveWorker, killWorkers) <- newNode narrator workersManager
+
+    newNode "server" . fork_ $
+        saveWorker $ listen (AtPort 1234) []
+
+    wait (for 100 ms)
+
+    newNode "client" $
+        replicateM_ 3 $ do
+            closer <- listen (AtConnTo (localhost, 1234)) []
+            wait (for 500 ms)
+            closer
+
+    wait (till finish)
+    newNode narrator killWorkers
+    wait (for 100 ms)
+  where
+    finish :: Second
+    finish = 3
+
+    newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
+
+pendingForkStrategy :: IO ()
+pendingForkStrategy = runTimedIO $ do
+    initLogging Debug
+    (saveWorker, killWorkers) <- newNode narrator workersManager
+
+    newNode "server" . fork_ $
+        saveWorker $ setForkStrategy forkStrategy $
+            listen (AtPort 1234)
+                [ Listener $ \Ping -> do
+                    logInfo "Got Ping, wait 1 sec"
+                    wait (for 1 sec)
+                ]
+
+    wait (for 100 ms)
+
+    newNode "client" . fork_ $ do
+        wait (for 100 ms)
+        replicateM_ 5 $ send (localhost, 1234) Ping
+
+    wait (till finish)
+    newNode narrator killWorkers
+    wait (for 100 ms)
+  where
+    finish :: Second
+    finish = 6
+
+    forkStrategy = ForkStrategy $ \msgName act ->
+        if msgName == messageName' Ping
+        then act        -- execute in-place
+        else fork_ act  -- execute in another thread
+
+    newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
+
+workersManager :: MonadIO m => m (m (m ()) -> m (), m ())
+workersManager = do
+    t <- liftIO . atomically $ newTVar []
+    let saveWorker action = do
+            closer <- action
+            liftIO . atomically $ modifyTVar t (closer:)
+        killWorkers = sequence_ =<< liftIO (atomically $ readTVar t)
+
+    return (saveWorker, killWorkers)
diff --git a/examples/socket-state/Main.hs b/examples/socket-state/Main.hs
new file mode 100644
--- /dev/null
+++ b/examples/socket-state/Main.hs
@@ -0,0 +1,96 @@
+{-# LANGUAGE DeriveAnyClass  #-}
+{-# LANGUAGE OverloadedLists #-}
+
+-- | Example of simple ping-pong network application.
+
+module Main where
+
+import           Control.Concurrent       (forkIO)
+import           Control.Concurrent.STM   (TVar, atomically, newTVar)
+import           Control.Lens             ((<+=))
+import           Control.Monad            (forM_, void)
+import           Control.Monad.IO.Class   (MonadIO (liftIO))
+import           Control.Monad.Loops      (whileM)
+import           Data.Binary              (Binary)
+import           Data.Data                (Data)
+import           Data.Default             (def)
+import           Data.Monoid              ((<>))
+import           Data.String              (fromString)
+import           Data.Time.Clock          (getCurrentTime)
+import           Formatting               (sformat, shown, (%))
+import           GHC.Generics             (Generic)
+import           Serokell.Util.Concurrent (modifyTVarS, threadDelay)
+import           System.Random
+import           System.Wlog              (LoggerConfig (..), LoggerName, Severity (Info),
+                                           logInfo, traverseLoggerConfig, usingLoggerName)
+
+import           Control.TimeWarp.Rpc     (BinaryP, Binding (AtPort), Dialog,
+                                           Listener (..), Message (..), Transfer, close,
+                                           listen, localhost, messageName', plainBinaryP,
+                                           runDialog, runTransfer, send, userStateR)
+import           Control.TimeWarp.Timed   (after, for, invoke, runTimedIO, sec, wait)
+
+type RequestsCounter = TVar Int
+
+runNode :: LoggerName -> Dialog (BinaryP ()) (Transfer RequestsCounter) () -> IO ()
+runNode name = void . forkIO . runTimedIO . usingLoggerName name . runTransfer mkState
+             . runDialog plainBinaryP
+    where
+        mkState = atomically $ newTVar 0
+
+ppLoggerConfig :: LoggerConfig
+ppLoggerConfig = def { lcSubloggers = [("server", infoConf), ("client", infoConf)] }
+  where
+    infoConf = def { lcSeverity = Just Info }
+
+initLogging :: MonadIO m => m ()
+initLogging = traverseLoggerConfig id ppLoggerConfig Nothing
+
+data Ping = Ping Int
+    deriving (Generic, Binary, Data)
+
+instance Message Ping where
+    formatMessage = messageName'
+
+-- | This example runs:
+-- * server node which counts requests from each client separatelly
+-- * 3 clients which send few messages, one per second
+main :: IO ()
+main = do
+    initLogging
+
+    runNode "server" $ do
+        logInfo "Running..."
+
+        stop <- listen (AtPort 4444)
+            [ Listener $ \(Ping cid) -> do
+                curTime <- liftIO getCurrentTime
+
+                -- increment counter by 1, and return new value
+                reqNo <- counterTic
+
+                logInfo $ sformat ("Got Ping #"%shown%" from client #"%shown%" at "%shown)
+                            reqNo cid curTime
+            ]
+
+        invoke (after 10 sec) stop
+
+    forM_ ([1..3] :: [Int]) $
+        \cid -> runNode ("client" <> fromString (show cid)) $ do
+            logInfo "Running..."
+
+            void $ whileM ruskaRuletka $ do
+                 wait (for 1 sec)
+                 send (localhost, 4444) $ Ping cid
+
+            logInfo "Done"
+            close (localhost, 4444)
+
+    threadDelay $ sec 12
+  where
+    counterTic = do
+        counter <- userStateR
+        liftIO . atomically $ modifyTVarS counter $ id <+= 1
+
+    -- | True with probability 2/3
+    ruskaRuletka = liftIO $ ( > 0) <$> randomRIO (0, 2 :: Int)
diff --git a/examples/token-ring/Main.hs b/examples/token-ring/Main.hs
deleted file mode 100644
--- a/examples/token-ring/Main.hs
+++ /dev/null
@@ -1,211 +0,0 @@
-{-# LANGUAGE FlexibleInstances    #-}
-{-# LANGUAGE TupleSections        #-}
-{-# LANGUAGE UndecidableInstances #-}
-{-# LANGUAGE ConstraintKinds      #-}
-
-import           Control.Exception          (Exception)
-import           Control.Monad              (forever, when, forM_, unless, join)
-import           Control.Monad.Catch        (MonadCatch, catch)
-import           Control.Monad.Random       (StdGen, mkStdGen)
-import qualified Control.Concurrent.STM.TVar as T
-import           Control.Concurrent.STM     (atomically)
-import           Control.Monad.Trans        (MonadIO (..), lift)
-import           Control.Lens               (Iso', iso, (^.))
-import           Formatting                 (sformat, shown, (%))
-import           Data.Monoid                ((<>))
-import           Data.Typeable              (Typeable)
-
-import           Control.TimeWarp.Logging   (WithNamedLogger (..), usingLoggerName,
-                                             logInfo, initLogging, setLoggerName,
-                                             Severity (..),
-                                             LoggerName (..),
-                                             logDebug, logError, LoggerNameBox)
-import           Control.TimeWarp.Timed     (MonadTimed (..), schedule, ThreadId,
-                                             killThread, at, for, sleepForever,
-                                             Microsecond, sec, ms,
-                                             interval, invoke, after, fork_)
-import           Control.TimeWarp.Rpc       (MonadRpc (..), Port, NetworkAddress,
-                                             Client, ServerT, call, method, runPureRpc,
-                                             runMsgPackRpc, DelaysSpecifier,
-                                             serverTypeRestriction1, MsgPackRpc,
-                                             PureRpc, getRandomTR, Delays (..),
-                                             ConnectionOutcome (..))
-
--- * Launch parameters.
-
-launchDuration :: Microsecond
-launchDuration = interval 20 sec
-
-tokenPassingDelay :: Microsecond
-tokenPassingDelay = interval 3 sec
-
-nodeNumber :: Int
-nodeNumber = 3
-
-allowedProgressDelay :: Microsecond
-allowedProgressDelay = interval 5 sec
-
-networkDelay :: (Microsecond, Microsecond)
-networkDelay = (interval 1 ms, interval 5 ms)
-
-emulationMode :: Bool
-emulationMode = True
-
--- * Starter
-
-main :: IO ()
-main = do
-    initLogging ["node", "observer"] Info
-    if emulationMode
-        then runEmulationMode delays (mkStdGen 0) scenario
-        else runRealMode scenario
-  where
-    scenario :: WorkMode m => m ()
-    scenario = do
-        setLoggerName "node" $ do
-            forM_ [1 .. nodeNumber] $
-                \no -> modifyLoggerName (<> LoggerName (show no)) $
-                    fork $ launchNode no
-
-        setLoggerName ("observer" <> "progress") $
-            fork_ $
-                launchObserver
-    delays = Delays $
-                \dest _ -> 
-                    if dest == (observerPort ^. fullAddr)
-                    then return $ ConnectedIn 0
-                    else ConnectedIn <$> getRandomTR networkDelay
-
-runRealMode :: LoggerNameBox MsgPackRpc () -> IO ()
-runRealMode = runMsgPackRpc . usingLoggerName mempty
-
-runEmulationMode
-    :: DelaysSpecifier delays
-    => delays -> StdGen -> PureRpc IO () -> IO ()
-runEmulationMode delays gen = runPureRpc gen delays
-
-nodePort :: Iso' Int Port
-nodePort = iso (+2000) (subtract 2000)
-
-fullAddr :: Iso' Port NetworkAddress
-fullAddr = iso ("127.0.0.1", ) snd
-
-type WorkMode m
-    = ( MonadTimed m
-      , MonadRpc m
-      , WithNamedLogger m
-      , MonadIO m
-      , MonadCatch m)
-
--- * Nodes
-
-type TokenValue = Int
-
-launchNode :: WorkMode m => Int -> m ()
-launchNode no = do
-    logDebug $ sformat ("Launching node " % shown) no
-
-    -- worker thread, which waits for signal from server thread
-    -- to process token
-    wtid <- modifyLoggerName (<> "worker") $
-        fork $
-            forever $ catch sleepForever onValueReceived
-
-    -- server thread, which waits for token from other node and
-    -- sends a signal to worker
-    stid <- modifyLoggerName (<> "server") $
-        fork $ do
-            idr <- serverTypeRestriction1
-            logDebug $ sformat ("Server up at " % shown) $ no ^. nodePort
-            serve (no ^. nodePort)
-                [ method "token" $ idr $ acceptToken wtid
-                ]
-
-    -- kill all when testing finishes
-    modifyLoggerName (<> "killer") $
-        schedule (at launchDuration) $ do
-            mapM_ killThread [wtid, stid]
-
-    logInfo "Launched"
-
-    -- initiate first token passing
-    when (no == 1) $
-        invoke (after 1 sec) $ do
-            logInfo "Creating token"
-            initPassingToken 1
-  where
-    onValueReceived (ValueReceived v) = do
-        logInfo $ sformat ("Got token with value " % shown) v
-        execClient ("127.0.0.1", observerPort) $ noteTokenCall v
-        wait (for tokenPassingDelay)
-        initPassingToken $ v + 1
-
-    initPassingToken v = do
-        let targetNode = no `mod` nodeNumber + 1
-            targetAddr = targetNode ^. nodePort . fullAddr
-        logDebug "Passing token"
-        execClient targetAddr $ passToken v
-
-    passToken :: TokenValue -> Client ()
-    passToken = call "token"
-
-    acceptToken :: WorkMode m => ThreadId m -> TokenValue -> ServerT m ()
-    acceptToken tid value = do
-        lift . throwTo tid $ ValueReceived value
-
-data SignalException = ValueReceived Int
-    deriving (Show, Typeable)
-
-instance Exception SignalException
-
--- * Observer, checks for global predicates.
-
-observerPort :: Int
-observerPort = 5000
-
-launchObserver :: WorkMode m => m ()
-launchObserver = do
-    lastProgress <- liftIO $ T.newTVarIO (0, 0)
-
-    -- server which listens whether token value was changed
-    stid <- modifyLoggerName (<> "server") $
-        fork $ do
-            idr <- serverTypeRestriction1
-            serve observerPort
-                [method "noteToken" $ idr $ noteTokenMethod lastProgress
-                ]
-
-    -- periodically checks for progress
-    ctid <- modifyLoggerName (<> "checker") $
-        fork . forever $ do
-            wait (for 1 sec)
-            (lastTime, value) <- liftIO $ T.readTVarIO lastProgress
-            time <- virtualTime
-            when (time - lastTime > allowedProgressDelay) $
-                logError $
-                    sformat ("Token value (" % shown % ") hasn't changed " %
-                             "since " % shown % shown) value lastTime time
-
-    logInfo "Launched"
-
-    -- kill all when testing finishes
-    modifyLoggerName (<> "killer") $
-        schedule (at launchDuration) $ do
-            mapM_ killThread [stid, ctid]
-
-
-noteTokenMethod
-    :: WorkMode m
-    => T.TVar (Microsecond, TokenValue) -> TokenValue -> ServerT m ()
-noteTokenMethod progressBox value = lift $ do
-    time <- virtualTime
-    join . liftIO . atomically $ do
-        (_, wasValue) <- T.readTVar progressBox
-        T.writeTVar progressBox (time, value)
-        return $
-            unless (value == wasValue + 1) $
-                logError $ sformat ("Wrong token value: expected " % shown %
-                                    " but got " % shown) (wasValue + 1) value
-
-noteTokenCall :: TokenValue -> Client ()
-noteTokenCall = call "noteToken"
diff --git a/src/Control/TimeWarp/Logging.hs b/src/Control/TimeWarp/Logging.hs
deleted file mode 100644
--- a/src/Control/TimeWarp/Logging.hs
+++ /dev/null
@@ -1,216 +0,0 @@
-{-# LANGUAGE DeriveDataTypeable    #-}
-{-# LANGUAGE DeriveGeneric         #-}
-{-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE TemplateHaskell       #-}
-{-# LANGUAGE UndecidableInstances  #-}
-{-# LANGUAGE ViewPatterns          #-}
-
--- |
--- Module      : Control.TimeWarp.Logging
--- Copyright   : (c) Serokell, 2016
--- License     : GPL-3 (see the file LICENSE)
--- Maintainer  : Serokell <hi@serokell.io>
--- Stability   : experimental
--- Portability : POSIX, GHC
---
--- Logging functionality. This module is wrapper over
--- <http://hackage.haskell.org/package/hslogger hslogger>,
--- which allows to keep logger name in monadic context.
--- Messages are colored depending on used serverity.
-
-module Control.TimeWarp.Logging
-       ( Severity (..)
-       , initLogging
-       , initLoggerByName
-
-       , LoggerName (..)
-
-         -- * Remove boilerplate
-       , WithNamedLogger (..)
-       , setLoggerName
-       , LoggerNameBox (..)
-       , usingLoggerName
-
-         -- * Logging functions
-       , logDebug
-       , logError
-       , logInfo
-       , logWarning
-       , logMessage
-       ) where
-
-import           Control.Monad.Catch       (MonadCatch, MonadMask, MonadThrow)
-import           Control.Monad.Except      (ExceptT (..), runExceptT)
-import           Control.Monad.Reader      (MonadReader (..), ReaderT, runReaderT)
-import           Control.Monad.State       (MonadState (get), StateT, evalStateT)
-import           Control.Monad.Trans       (MonadIO (liftIO), MonadTrans, lift)
-import           Control.Monad.Trans.Cont  (ContT, mapContT)
-
-import           Data.String               (IsString)
-import qualified Data.Text                 as T
-import           Data.Typeable             (Typeable)
-import           GHC.Generics              (Generic)
-
-import           System.Console.ANSI       (Color (Blue, Green, Red, Yellow),
-                                            ColorIntensity (Vivid),
-                                            ConsoleLayer (Foreground),
-                                            SGR (Reset, SetColor), setSGRCode)
-import           System.IO                 (stderr, stdout)
-import           System.Log.Formatter      (simpleLogFormatter)
-import           System.Log.Handler        (setFormatter)
-import           System.Log.Handler.Simple (streamHandler)
-import           System.Log.Logger         (Priority (DEBUG, ERROR, INFO, WARNING), logM,
-                                            removeHandler, rootLoggerName, setHandlers,
-                                            setLevel, updateGlobalLogger)
-
--- | This type is intended to be used as command line option
--- which specifies which messages to print.
-data Severity
-    = Debug
-    | Info
-    | Warning
-    | Error
-    deriving (Generic, Typeable, Show, Read, Eq)
-
--- | Logger name to keep in context.
-newtype LoggerName = LoggerName
-    { loggerName :: String
-    } deriving (Show, IsString)
-
--- | Defined such that @n1@ is parent for @(n1 <> n2)@
--- (see <http://hackage.haskell.org/package/hslogger-1.2.10/docs/System-Log-Logger.html hslogger description>).
-instance Monoid LoggerName where
-    mempty = ""
-
-    LoggerName base `mappend` LoggerName suffix
-        | null base = LoggerName suffix
-        | otherwise = LoggerName $ base ++ "." ++ suffix
-
-convertSeverity :: Severity -> Priority
-convertSeverity Debug   = DEBUG
-convertSeverity Info    = INFO
-convertSeverity Warning = WARNING
-convertSeverity Error   = ERROR
-
--- | Initiates specified loggers, and sets severity of root logger's handler to
--- `Debug`
-initLogging :: [LoggerName] -> Severity -> IO ()
-initLogging predefinedLoggers sev = do
-    updateGlobalLogger rootLoggerName removeHandler
-    updateGlobalLogger rootLoggerName $ setLevel DEBUG
-    mapM_ (initLoggerByName sev) predefinedLoggers
-
--- | Turns logger with specified name on.
--- All messages are printed to /stdout/, moreover messages with at least
--- `Error` severity are printed to /stderr/.
-initLoggerByName :: Severity -> LoggerName -> IO ()
-initLoggerByName (convertSeverity -> s) LoggerName{..} = do
-    stdoutHandler <-
-        (flip setFormatter) stdoutFormatter <$> streamHandler stdout s
-    stderrHandler <-
-        (flip setFormatter) stderrFormatter <$> streamHandler stderr ERROR
-    updateGlobalLogger loggerName $ setHandlers [stdoutHandler, stderrHandler]
-  where
-    stderrFormatter = simpleLogFormatter
-        ("[$time] " ++ colorizer ERROR "[$loggername:$prio]: " ++ "$msg")
-    stdoutFormatter h r@(pr, _) n =
-        simpleLogFormatter (colorizer pr "[$loggername:$prio] " ++ "$msg") h r n
-
--- | Defines pre- and post-printed characters for printing colorized text.
-table :: Priority -> (String, String)
-table priority = case priority of
-    ERROR   -> (setColor Red   , reset)
-    DEBUG   -> (setColor Green , reset)
-    WARNING -> (setColor Yellow, reset)
-    INFO    -> (setColor Blue  , reset)
-    _       -> ("", "")
-  where
-    setColor color = setSGRCode [SetColor Foreground Vivid color]
-    reset = setSGRCode [Reset]
-
--- | Colorizes text.
-colorizer :: Priority -> String -> String
-colorizer pr s = before ++ s ++ after
-  where
-    (before, after) = table pr
-
--- | This type class exists to remove boilerplate logging
--- by adding the logger's name to the context in each module.
-class WithNamedLogger m where
-    -- | Extract logger name from context
-    getLoggerName :: m LoggerName
-
-    -- | Change logger name in context
-    modifyLoggerName :: (LoggerName -> LoggerName) -> m a -> m a
-
--- | Set logger name in context.
-setLoggerName :: WithNamedLogger m => LoggerName -> m a -> m a
-setLoggerName = modifyLoggerName . const
-
-instance (Monad m, WithNamedLogger m) =>
-         WithNamedLogger (ReaderT a m) where
-    getLoggerName = lift getLoggerName
-
-    modifyLoggerName how m =
-        ask >>= lift . modifyLoggerName how . runReaderT m
-
-instance (Monad m, WithNamedLogger m) =>
-         WithNamedLogger (StateT a m) where
-    getLoggerName = lift getLoggerName
-
-    modifyLoggerName how m =
-        get >>= lift . modifyLoggerName how . evalStateT m
-
-instance (Monad m, WithNamedLogger m) =>
-         WithNamedLogger (ExceptT e m) where
-    getLoggerName = lift getLoggerName
-
-    modifyLoggerName how = ExceptT . modifyLoggerName how . runExceptT
-
-instance (Monad m, WithNamedLogger m) =>
-         WithNamedLogger (ContT r m) where
-    getLoggerName = lift getLoggerName
-
-    modifyLoggerName = mapContT . modifyLoggerName
-
-
--- | Default implementation of `WithNamedLogger`.
-newtype LoggerNameBox m a = LoggerNameBox
-    { loggerNameBoxEntry :: ReaderT LoggerName m a
-    } deriving (Functor, Applicative, Monad, MonadIO, MonadTrans,
-                MonadThrow, MonadCatch, MonadMask, MonadState s)
-
-
-instance MonadReader r m => MonadReader r (LoggerNameBox m) where
-    ask = lift ask
-    reader = lift . reader
-    local f (LoggerNameBox m) = getLoggerName >>= lift . local f . runReaderT m
-
--- | Runs a `LoggerNameBox` with specified initial `LoggerName`.
-usingLoggerName :: LoggerName -> LoggerNameBox m a -> m a
-usingLoggerName name = flip runReaderT name . loggerNameBoxEntry
-
-instance Monad m =>
-         WithNamedLogger (LoggerNameBox m) where
-    getLoggerName = LoggerNameBox ask
-
-    modifyLoggerName how = LoggerNameBox . local how . loggerNameBoxEntry
-
--- | Shortcut for `logMessage` to use according severity.
-logDebug, logInfo, logWarning, logError
-    :: (WithNamedLogger m, MonadIO m)
-    => T.Text -> m ()
-logDebug   = logMessage Debug
-logInfo    = logMessage Info
-logWarning = logMessage Warning
-logError   = logMessage Error
-
--- | Logs message with specified severity using logger name in context.
-logMessage
-    :: (WithNamedLogger m, MonadIO m)
-    => Severity -> T.Text -> m ()
-logMessage severity t = do
-    LoggerName{..} <- getLoggerName
-    liftIO . logM loggerName (convertSeverity severity) $ T.unpack t
diff --git a/src/Control/TimeWarp/Manager.hs b/src/Control/TimeWarp/Manager.hs
new file mode 100644
--- /dev/null
+++ b/src/Control/TimeWarp/Manager.hs
@@ -0,0 +1,7 @@
+-- | Reexports all @Manager@ utilities.
+
+module Control.TimeWarp.Manager
+       ( module Control.TimeWarp.Manager.Job
+       ) where
+
+import           Control.TimeWarp.Manager.Job
diff --git a/src/Control/TimeWarp/Manager/Job.hs b/src/Control/TimeWarp/Manager/Job.hs
new file mode 100644
--- /dev/null
+++ b/src/Control/TimeWarp/Manager/Job.hs
@@ -0,0 +1,199 @@
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE TemplateHaskell       #-}
+{-# LANGUAGE ViewPatterns          #-}
+
+-- | This module provides abstractions for parallel job processing.
+
+module Control.TimeWarp.Manager.Job
+       ( -- * Job data types
+         InterruptType (..)
+       , JobCurator    (..)
+
+         -- * 'JobsState' lenses
+       , jcCounter
+       , jcIsClosed
+       , jcJobs
+
+         -- * Manager utilities
+       , addManagerAsJob
+       , addSafeThreadJob
+       , addThreadJob
+       , interruptAllJobs
+       , isInterrupted
+       , mkJobCurator
+       , stopAllJobs
+       , unlessInterrupted
+       ) where
+
+import           Control.Concurrent          (forkIO)
+import           Control.Concurrent.STM      (atomically, check)
+import           Control.Concurrent.STM.TVar (TVar, newTVarIO, readTVar, readTVarIO,
+                                              writeTVar)
+import           Control.Lens                (at, makeLenses, use, view, (&), (.=), (.~),
+                                              (<<+=), (<<.=), (?=), (^.))
+import           Control.Monad               (mapM_, unless, void)
+import           Control.Monad.Catch         (MonadMask (mask), finally)
+import           Control.Monad.Extra         ((&&^))
+import           Control.Monad.Trans         (MonadIO (liftIO))
+import           Control.Monad.Trans.Control (MonadBaseControl (..))
+
+import           Data.Hashable               (Hashable)
+import           Data.HashMap.Strict         (HashMap)
+import qualified Data.HashMap.Strict         as HM hiding (HashMap)
+import           Serokell.Util.Base          (inCurrentContext)
+import           Serokell.Util.Concurrent    (modifyTVarS, threadDelay)
+import           System.Wlog                 (CanLog)
+
+import           Control.TimeWarp.Timed      (Microsecond, MonadTimed, fork_, killThread,
+                                              myThreadId)
+
+-- | Unique identifier of job.
+newtype JobId = JobId Word
+    deriving (Show, Eq, Num, Hashable)
+
+-- | Job killer.
+newtype JobInterrupter = JobInterrupter
+    { runJobInterrupter :: IO ()
+    }
+
+-- | Action to mark job as finished
+newtype MarkJobFinished = MarkJobFinished
+    { runMarker :: IO ()
+    }
+
+data JobCuratorState = JobCuratorState
+    { -- | @True@ if interrupt had been invoked. Also, when @True@, no job could be added
+      _jcIsClosed :: !Bool
+
+      -- | 'Map' with currently active jobs
+    , _jcJobs     :: !(HashMap JobId JobInterrupter)
+
+      -- | Total number of allocated jobs ever
+    , _jcCounter  :: !JobId
+    }
+
+makeLenses ''JobCuratorState
+
+-- | Keeps set of jobs. Allows to stop jobs and wait till all of them finish.
+newtype JobCurator = JobCurator
+    { getJobCurator :: TVar JobCuratorState
+    }
+
+-- | Defines way to interrupt all jobs in curator.
+data InterruptType
+    = Plain
+    -- ^ Just interrupt all jobs
+    | Force
+    -- ^ Interrupt all jobs, and treat them all as completed
+    | WithTimeout !Microsecond !(IO ())
+    -- ^ Interrupt all jobs in `Plain` was, but if some jobs fail to complete in time,
+    -- interrupt `Force`ly and execute given action.
+
+mkJobCurator :: MonadIO m => m JobCurator
+mkJobCurator = JobCurator <$> (liftIO $ newTVarIO
+    JobCuratorState
+    { _jcIsClosed = False
+    , _jcJobs     = mempty
+    , _jcCounter  = 0
+    })
+
+
+-- | Remembers and starts given action.
+-- Once `interruptAllJobs` called on this manager, if job is not completed yet,
+-- `JobInterrupter` is invoked.
+--
+-- Given job *must* invoke given `MarkJobFinished` upon finishing, even if it was
+-- interrupted.
+--
+-- If curator is already interrupted, action would not start, and `JobInterrupter`
+-- would be invoked.
+addJob :: MonadIO m
+       => JobCurator
+       -> JobInterrupter
+       -> (MarkJobFinished -> m ())
+       -> m ()
+addJob
+       (getJobCurator     -> curator)
+    ji@(runJobInterrupter -> interrupter)
+    action
+  = do
+    jidm <- liftIO . atomically $ do
+        st <- readTVar curator
+        let closed = st ^. jcIsClosed
+        if closed
+            then return Nothing
+            else modifyTVarS curator $ do
+                    no <- jcCounter <<+= 1
+                    jcJobs . at no ?= ji
+                    return $ Just no
+    maybe (liftIO interrupter) (action . markReady) jidm
+  where
+    markReady jid = MarkJobFinished $ atomically $ do
+        st <- readTVar curator
+        writeTVar curator $ st & jcJobs . at jid .~ Nothing
+
+-- | Invokes `JobInterrupter`s for all incompleted jobs.
+-- Has no effect on second call.
+interruptAllJobs :: MonadIO m => JobCurator -> InterruptType -> m ()
+interruptAllJobs (getJobCurator -> curator) Plain = do
+    jobs <- liftIO . atomically $ modifyTVarS curator $ do
+        wasClosed <- jcIsClosed <<.= True
+        if wasClosed
+            then return mempty
+            else use jcJobs
+    liftIO $ mapM_ runJobInterrupter jobs
+interruptAllJobs c@(getJobCurator -> curator) Force = do
+    interruptAllJobs c Plain
+    liftIO . atomically $ modifyTVarS curator $ jcJobs .= mempty
+interruptAllJobs c@(getJobCurator -> curator) (WithTimeout delay onTimeout) = do
+    interruptAllJobs c Plain
+    void $ liftIO . forkIO $ do
+        threadDelay delay
+        done <- HM.null . view jcJobs <$> readTVarIO curator
+        unless done $ liftIO onTimeout >> interruptAllJobs c Force
+
+-- | Waits for this manager to get closed and all registered jobs to invoke
+-- `MaskForJobFinished`.
+awaitAllJobs :: MonadIO m => JobCurator -> m ()
+awaitAllJobs (getJobCurator -> jc) =
+    liftIO . atomically $
+        check =<< (view jcIsClosed &&^ (HM.null . view jcJobs)) <$> readTVar jc
+
+-- | Interrupts and then awaits for all jobs to complete.
+stopAllJobs :: MonadIO m => JobCurator -> m ()
+stopAllJobs c = interruptAllJobs c Plain >> awaitAllJobs c
+
+-- | Add second manager as a job to first manager.
+addManagerAsJob :: (MonadIO m, MonadTimed m, MonadBaseControl IO m)
+                => JobCurator -> InterruptType -> JobCurator -> m ()
+addManagerAsJob curator intType managerJob = do
+    interrupter <- inCurrentContext $ interruptAllJobs managerJob intType
+    addJob curator (JobInterrupter interrupter) $
+        \(runMarker -> ready) -> fork_ $ awaitAllJobs managerJob >> liftIO ready
+
+-- | Adds job executing in another thread, where interrupting kills the thread.
+addThreadJob :: (CanLog m, MonadIO m,  MonadMask m, MonadTimed m, MonadBaseControl IO m)
+             => JobCurator -> m () -> m ()
+addThreadJob curator action =
+    mask $
+        \unmask -> fork_ $ do
+            tid <- myThreadId
+            killer <- inCurrentContext $ killThread tid
+            addJob curator (JobInterrupter killer) $
+                \(runMarker -> markReady) -> unmask action `finally` liftIO markReady
+
+-- | Adds job executing in another thread, interrupting does nothing.
+-- Usefull then work stops itself on interrupt, and we just need to wait till it fully
+-- stops.
+addSafeThreadJob :: (MonadIO m,  MonadMask m, MonadTimed m) => JobCurator -> m () -> m ()
+addSafeThreadJob curator action =
+    mask $
+        \unmask -> fork_ $ addJob curator (JobInterrupter $ return ()) $
+            \(runMarker -> markReady) -> unmask action `finally` liftIO markReady
+
+isInterrupted :: MonadIO m => JobCurator -> m Bool
+isInterrupted = liftIO . atomically . fmap (view jcIsClosed) . readTVar . getJobCurator
+
+unlessInterrupted :: MonadIO m => JobCurator -> m () -> m ()
+unlessInterrupted c a = isInterrupted c >>= flip unless a
diff --git a/src/Control/TimeWarp/Rpc.hs b/src/Control/TimeWarp/Rpc.hs
--- a/src/Control/TimeWarp/Rpc.hs
+++ b/src/Control/TimeWarp/Rpc.hs
@@ -6,56 +6,24 @@
 -- Stability   : experimental
 -- Portability : POSIX, GHC
 --
--- This module provides RPC capabilities. It allows to write scenarios over
--- distributed systems, which can then be launched as either real program or
--- emulation with network nastiness manually controlled.
---
--- Usage example:
---
--- @
--- sumMethod :: Monad m => Int -> Int -> ServerT m Int
--- sumMethod a b = return $ a + b
---
--- callSum :: Int -> Int -> Client Int
--- callSum = call "sum"
---
--- exampleLaunch :: (MonadRpc m, MonadTimed m, MonadIO m) => m ()
--- exampleLaunch = do
---     -- launch server
---     work (for 1 minute) $ do
---         idr <- serverTypeRestriction2
---         serve 1234 [method "sum" $ idr sumMethod]
---     -- make 3 requests with delay
---     fork_ $
---         forM_ [1..3] $
---             \\i -> do
---                 wait (for 3 sec)
---                 res <- execClient ("127.0.0.1", 1234) $ callSum (-1) i
---                 liftIO $ timestamp $ "Answer is " ++ show res
--- @
---
--- This scenario then can be launched as real program:
---
--- >>> runTimedIO . runMsgPackRpc $ exampleLaunch
--- [3000012µs] Answer is 0
--- [6000013µs] Answer is 1
--- [9000015µs] Answer is 2
---
--- Or as emulation, which works immediately:
---
--- >>> runTimedT . runPureRpc (mkStdGen 23423) (10 :: Microsecond, 50 :: Microsecond) $ exampleLaunch
--- [3000023µs] Answer is 0
--- [6000072µs] Answer is 1
--- [90000102µs] Answer is 2
+-- This module provides networking capabilities.
+-- Name `RPC` is outdated and is subject to change; this module does *not* provide
+-- RPC interface.
 
 module Control.TimeWarp.Rpc
-       ( module Control.TimeWarp.Rpc.MonadRpc
-       , module Control.TimeWarp.Rpc.MsgPackRpc
-       , module Control.TimeWarp.Rpc.Restriction
-       , module Control.TimeWarp.Rpc.PureRpc
+       ( module Control.TimeWarp.Rpc.Message
+       , module Control.TimeWarp.Rpc.MonadDialog
+--       , module Control.TimeWarp.Rpc.MonadRpc
+       , module Control.TimeWarp.Rpc.MonadTransfer
+--       , module Control.TimeWarp.Rpc.Rpc
+       , module Control.TimeWarp.Rpc.Transfer
+--       , module Control.TimeWarp.Rpc.TH
        ) where
 
-import           Control.TimeWarp.Rpc.MonadRpc
-import           Control.TimeWarp.Rpc.MsgPackRpc
-import           Control.TimeWarp.Rpc.PureRpc
-import           Control.TimeWarp.Rpc.Restriction
+import           Control.TimeWarp.Rpc.Message
+import           Control.TimeWarp.Rpc.MonadDialog
+--import           Control.TimeWarp.Rpc.MonadRpc
+import           Control.TimeWarp.Rpc.MonadTransfer
+--import           Control.TimeWarp.Rpc.Rpc
+import           Control.TimeWarp.Rpc.Transfer
+--import           Control.TimeWarp.Rpc.TH
diff --git a/src/Control/TimeWarp/Rpc/Message.hs b/src/Control/TimeWarp/Rpc/Message.hs
new file mode 100644
--- /dev/null
+++ b/src/Control/TimeWarp/Rpc/Message.hs
@@ -0,0 +1,202 @@
+{-# LANGUAGE ConstraintKinds       #-}
+{-# LANGUAGE DefaultSignatures     #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE Rank2Types            #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE TypeOperators         #-}
+{-# LANGUAGE UndecidableInstances  #-}
+
+-- |
+-- Module      : Control.TimeWarp.Rpc.Message
+-- Copyright   : (c) Serokell, 2016
+-- License     : GPL-3 (see the file LICENSE)
+-- Maintainer  : Serokell <hi@serokell.io>
+-- Stability   : experimental
+-- Portability : POSIX, GHC
+--
+-- This module defines typeclasses which allow to abstragate from concrete serialization
+-- strategy, and also `Message` type, which binds a name to request.
+--
+-- UPGRADE-NOTE: currently only `Binary` serialization is supported,
+-- need to add support for /MessagePack/, /aeson/, /cereal/ e.t.c.
+
+module Control.TimeWarp.Rpc.Message
+       (
+       -- * Message
+         MessageName
+       , Message (..)
+
+       -- * Serialization and deserialization
+       , PackingType (..)
+       , Packable (..)
+       , Unpackable (..)
+
+       -- * Basic packing types
+       , BinaryP (..)
+       , plainBinaryP
+
+       -- * Parts of message
+       -- $message-parts
+       , ContentData (..)
+       , NameData (..)
+       , RawData (..)
+       , WithHeaderData (..)
+
+       -- * Util
+       , messageName'
+       , runGetOrThrow
+       ) where
+
+import           Control.Monad.Catch               (MonadThrow (..))
+import           Control.Monad.Extra               (unlessM)
+import           Data.Binary                       (Binary (..))
+import           Data.Binary.Get                   (Get, isEmpty, label, runGetOrFail)
+import           Data.Binary.Put                   (runPut)
+import           Data.ByteString                   (ByteString)
+import qualified Data.ByteString.Lazy              as BL
+import           Data.Conduit                      (Conduit, (=$=))
+import qualified Data.Conduit.List                 as CL
+import           Data.Conduit.Serialization.Binary (ParseError (..), conduitGet,
+                                                    conduitPut)
+import           Data.Data                         (Data, dataTypeName, dataTypeOf)
+import           Data.Proxy                        (Proxy (..), asProxyTypeOf)
+import qualified Data.Text                         as T
+import           Data.Text.Buildable               (Buildable)
+import           Data.Typeable                     (Typeable)
+import qualified Formatting                        as F
+
+
+-- * Message
+
+-- | Message name, which is expected to uniquely define type of message.
+type MessageName = T.Text
+
+-- | Defines type with it's own `MessageName`.
+class Typeable m => Message m where
+    -- | Uniquely identifies this type
+    messageName :: Proxy m -> MessageName
+    default messageName :: Data m => Proxy m -> MessageName
+    messageName proxy =
+         T.pack . dataTypeName . dataTypeOf $ undefined `asProxyTypeOf` proxy
+
+    -- | Description of message, for debug purposes
+    formatMessage :: m -> T.Text
+    default formatMessage :: Buildable m => m -> T.Text
+    formatMessage = F.sformat F.build
+
+
+-- * Parts of message.
+-- $message-parts
+-- This part describes different parts of message. which are enought for serializing
+-- message / could be extracted on deserializing.
+--
+-- | Message's content.
+data ContentData r = ContentData r
+
+-- | Designates data given from incoming message, but not deserialized to any specified
+-- object.
+data RawData = RawData ByteString
+
+-- | Message's name.
+data NameData = NameData MessageName
+
+-- | Message's header & something else
+data WithHeaderData h r = WithHeaderData h r
+
+
+-- * Util
+
+-- | As `messageName`, but accepts message itself, may be more convinient is most cases.
+messageName' :: Message m => m -> MessageName
+messageName' = messageName . proxyOf
+  where
+    proxyOf :: a -> Proxy a
+    proxyOf _ = Proxy
+
+-- | Parses given bytestring, throwing `ParseError` on fail.
+runGetOrThrow :: MonadThrow m => Get a -> BL.ByteString -> m a
+runGetOrThrow p s =
+    either (\(bs, off, err) -> throwM $ ParseError (BL.toStrict bs) off err)
+           (\(_, _, a) -> return a)
+        $ runGetOrFail p s
+
+-- * Serialization and deserialization
+
+-- | Defines a serialization / deserialization strategy.
+-- Deserealization is assumed to be performed in two phases:
+--
+-- * byte stream -> intermediate form
+--
+-- * intermediate form -> any part of message (or their combination)
+class PackingType p where
+    -- | Defines intermediate form
+    type IntermediateForm p :: *
+
+    -- | Way of unpacking raw bytes to intermediate form.
+    unpackMsg :: MonadThrow m => p -> Conduit ByteString m (IntermediateForm p)
+
+-- | Defines a way to serialize object @r@ with given packing type @p@.
+class PackingType p => Packable p r where
+    -- | Way of packing data to raw bytes.
+    packMsg :: MonadThrow m => p -> Conduit r m ByteString
+
+-- | Defines a way to deserealize data with given packing type @p@ and extract object @r@.
+class PackingType p => Unpackable p r where
+    -- | Way to extract message part from intermediate form.
+    extractMsgPart :: MonadThrow m => p -> IntermediateForm p -> m r
+
+
+-- * Basic packing types
+
+-- ** Binary
+
+-- | Defines way to encode `Binary` instances into message of format
+-- (header, [[name], content]), where [x] = (length of x, x).
+-- /P/ here denotes to "packing".
+data BinaryP header = BinaryP
+
+plainBinaryP :: BinaryP ()
+plainBinaryP = BinaryP
+
+instance Binary h => PackingType (BinaryP h) where
+    type IntermediateForm (BinaryP h) = WithHeaderData h RawData
+    unpackMsg _ = conduitGet $ WithHeaderData <$> get <*> (RawData <$> get)
+
+instance (Binary h, Binary r, Message r)
+       => Packable (BinaryP h) (WithHeaderData h (ContentData r)) where
+    packMsg p = CL.map packToRaw =$= packMsg p
+      where
+        packToRaw (WithHeaderData h (ContentData r)) =
+            WithHeaderData h . RawData . BL.toStrict . runPut $ do
+                put $ messageName' r
+                put r
+
+instance Binary h
+      => Packable (BinaryP h) (WithHeaderData h RawData) where
+    packMsg _ = CL.map doPut =$= conduitPut
+      where
+        doPut (WithHeaderData h (RawData r)) = put h >> put r
+
+
+instance Binary h
+      => Unpackable (BinaryP h) (WithHeaderData h RawData) where
+    extractMsgPart _ = return
+
+instance Binary h
+      => Unpackable (BinaryP h) NameData where
+    extractMsgPart _ (WithHeaderData _ (RawData raw)) =
+        runGetOrThrow (NameData <$> label lname get) $ BL.fromStrict raw
+      where
+        lname = "(in parseNameData)"
+
+instance (Binary h, Binary r)
+      => Unpackable (BinaryP h) (ContentData r) where
+    extractMsgPart _ (WithHeaderData _ (RawData raw)) =
+        runGetOrThrow parser $ BL.fromStrict raw
+      where
+        parser = label lname $ checkAllConsumed $
+            (get :: Get MessageName) *> (ContentData <$> get)
+        checkAllConsumed p = p <* unlessM isEmpty (fail "unconsumed input")
+        lname = "(in parseNameNContentData)"
diff --git a/src/Control/TimeWarp/Rpc/MonadDialog.hs b/src/Control/TimeWarp/Rpc/MonadDialog.hs
new file mode 100644
--- /dev/null
+++ b/src/Control/TimeWarp/Rpc/MonadDialog.hs
@@ -0,0 +1,355 @@
+{-# LANGUAGE ConstraintKinds           #-}
+{-# LANGUAGE ExistentialQuantification #-}
+{-# LANGUAGE FlexibleContexts          #-}
+{-# LANGUAGE FlexibleInstances         #-}
+{-# LANGUAGE FunctionalDependencies    #-}
+{-# LANGUAGE GADTs                     #-}
+{-# LANGUAGE LambdaCase                #-}
+{-# LANGUAGE MultiParamTypeClasses     #-}
+{-# LANGUAGE Rank2Types                #-}
+{-# LANGUAGE StandaloneDeriving        #-}
+{-# LANGUAGE TupleSections             #-}
+{-# LANGUAGE TypeFamilies              #-}
+{-# LANGUAGE UndecidableInstances      #-}
+
+-- |
+-- Module      : Control.TimeWarp.Rpc.MonadDialog
+-- Copyright   : (c) Serokell, 2016
+-- License     : GPL-3 (see the file LICENSE)
+-- Maintainer  : Serokell <hi@serokell.io>
+-- Stability   : experimental
+-- Portability : POSIX, GHC
+--
+-- This module defines `Dialog` monad, which is add-on over `Transfer` and allows to
+-- send/receive whole messages, where serialization strategy could be defined in
+-- arbitrary way.
+--
+-- For `Dialog`, `send` function is trivial; `listen` function infinitelly captures
+-- messages from input stream, processing them in separate thread then.
+--
+--
+-- Mainly, following structure of message is currently supported:
+-- [header, name, content]
+-- where /name/ uniquely defines type of message.
+--
+-- Given message could be deserealized as sum of header and raw data;
+-- then user can just send the message further, or deserialize and process
+-- message's content.
+
+module Control.TimeWarp.Rpc.MonadDialog
+       (
+       -- * MonadDialog
+         MonadDialog (..)
+
+       -- * Dialog
+       , Dialog (..)
+       , runDialog
+
+       -- * ForkStrategy
+       , ForkStrategy (..)
+
+       -- * Communication methods
+       -- $monad-dialog-funcs
+       , send
+       , sendH
+       , sendR
+       , listen
+       , listenH
+       , listenR
+       , reply
+       , replyH
+       , replyR
+
+       -- * Listeners
+       , Listener (..)
+       , ListenerH (..)
+       , ListenerR
+       , getListenerName
+       , getListenerNameH
+
+       -- * Misc
+       , MonadListener
+       ) where
+
+import           Control.Lens                       (at, iso, (.~), (^.), _2)
+import           Control.Monad                      (void, when)
+import           Control.Monad.Base                 (MonadBase (..))
+import           Control.Monad.Catch                (MonadCatch, MonadMask, MonadThrow,
+                                                     handleAll)
+import           Control.Monad.Morph                (hoist)
+import           Control.Monad.Reader               (MonadReader (ask, local),
+                                                     ReaderT (..))
+import           Control.Monad.State                (MonadState)
+import           Control.Monad.Trans                (MonadIO, MonadTrans (..))
+import           Control.Monad.Trans.Control        (ComposeSt, MonadBaseControl (..),
+                                                     MonadTransControl (..), StM,
+                                                     defaultLiftBaseWith, defaultLiftWith,
+                                                     defaultRestoreM, defaultRestoreT)
+import           Data.ByteString                    (ByteString)
+import           Data.Conduit                       (Conduit, yield, (=$=))
+import qualified Data.Conduit.List                  as CL
+import           Data.Map                           as M
+import           Data.Proxy                         (Proxy (..))
+import           Formatting                         (sformat, shown, stext, (%))
+import           System.Wlog                        (CanLog, HasLoggerName,
+                                                     LoggerNameBox (..), WithLogger,
+                                                     logDebug, logError, logWarning)
+
+import           Serokell.Util.Lens                 (WrappedM (..))
+
+import           Control.TimeWarp.Rpc.Message       (ContentData (..), Message (..),
+                                                     MessageName, NameData (..),
+                                                     Packable (..), RawData (..),
+                                                     Unpackable (..), WithHeaderData (..),
+                                                     unpackMsg)
+import           Control.TimeWarp.Rpc.MonadTransfer (Binding,
+                                                     MonadResponse (peerAddr, replyRaw),
+                                                     MonadTransfer (..), NetworkAddress,
+                                                     ResponseT (..), commLog)
+import           Control.TimeWarp.Timed             (MonadTimed, ThreadId, fork_)
+
+
+-- * Related datatypes
+
+data ForkStrategy s = ForkStrategy
+    { withForkStrategy :: forall m . (MonadIO m, MonadTimed m)
+                       => s -> m () -> m ()
+    }
+
+
+-- * MonadDialog
+
+-- | Defines communication based on messages.
+-- It allows to specify service data (/header/) for use by overlying protocols.
+class MonadTransfer s m => MonadDialog s p m | m -> p, m -> s where
+    packingType     :: m p
+    forkStrategy    :: m (ForkStrategy MessageName)
+    setForkStrategy :: ForkStrategy MessageName -> m a -> m a
+
+-- * Communication methods
+
+-- ** Helpers
+
+packMsg' :: (Packable p r, MonadDialog s p m, MonadThrow m) => Conduit r m ByteString
+packMsg' = lift packingType >>= packMsg
+
+
+-- $monad-dialog-funcs
+-- Functions differ by suffix, meanings are following:
+--
+--  * /No suffix/ - operates with plain message (TODO: weaken `Packable` constraints)
+--
+--  * H - operates with message with header
+--
+--  * R - operates with message in raw form with header
+
+-- ** Send functions
+
+-- | Send message of arbitrary structure
+doSend :: (Packable p r, MonadDialog s p m, MonadThrow m)
+       => NetworkAddress -> r -> m ()
+doSend addr r = sendRaw addr $ yield r =$= packMsg'
+
+-- | Send plain message
+send :: (Packable p (WithHeaderData () (ContentData r)), MonadDialog s p m, MonadThrow m)
+     => NetworkAddress -> r -> m ()
+send addr msg = doSend addr $ WithHeaderData () (ContentData msg)
+
+-- | Send message with header
+sendH :: (Packable p (WithHeaderData h (ContentData r)), MonadDialog s p m, MonadThrow m)
+      => NetworkAddress -> h -> r -> m ()
+sendH addr h msg = doSend addr $ WithHeaderData h (ContentData msg)
+
+-- | Send message given in raw form
+sendR :: (Packable p (WithHeaderData h RawData), MonadDialog s p m, MonadThrow m)
+      => NetworkAddress -> h -> RawData -> m ()
+sendR addr h raw = doSend addr $ WithHeaderData h raw
+
+
+-- ** Reply functions
+
+-- | Reply to peer node with message of arbitrary structure
+doReply :: (Packable p r, MonadDialog s p m, MonadResponse s m, MonadThrow m)
+        => r -> m ()
+doReply r = replyRaw $ yield r =$= packMsg'
+
+-- | Sends message to peer node.
+reply :: (Packable p (WithHeaderData () (ContentData r)), MonadDialog s p m,
+          MonadResponse s m, MonadThrow m)
+      => r -> m ()
+reply msg = doReply $ WithHeaderData () (ContentData msg)
+
+-- | Sends message with given header to peer node.
+replyH :: (Packable p (WithHeaderData h (ContentData r)), MonadDialog s p m,
+           MonadResponse s m, MonadThrow m)
+       => h -> r -> m ()
+replyH h msg = doReply $ WithHeaderData h (ContentData msg)
+
+-- | Sends message with given header and message content in raw form to peer node.
+replyR :: (Packable p (WithHeaderData h RawData), MonadDialog s p m,
+           MonadResponse s m, MonadThrow m)
+       => h -> RawData -> m ()
+replyR h raw = doReply $ WithHeaderData h raw
+
+-- Those @m@ looks like waterfall :3
+type MonadListener  s m =
+    ( MonadIO       m
+    , MonadMask     m
+    , MonadTimed    m
+    , MonadTransfer s m
+    , WithLogger    m
+    )
+
+-- | Starts server with given set of listeners.
+listen :: (Unpackable p (WithHeaderData () RawData),Unpackable p NameData,
+           MonadListener s m, MonadDialog s p m)
+       => Binding -> [Listener s p m] -> m (m ())
+listen binding listeners = listenH binding $ convert <$> listeners
+  where
+    convert :: Listener s p m -> ListenerH s p () m
+    convert (Listener f) = ListenerH $ f . second
+    second ((), r) = r
+
+-- | Starts server with given set of listeners, which allow to read both header and
+-- content of received message.
+listenH :: (Unpackable p (WithHeaderData h RawData), Unpackable p NameData,
+            MonadListener s m, MonadDialog s p m)
+        => Binding -> [ListenerH s p h m] -> m (m ())
+listenH binding listeners =
+    listenR binding listeners (const $ return True)
+
+-- | Starts server with given /raw listener/ and set of /typed listeners/.
+-- First, raw listener is applied, it allows to read header and content in raw form of
+-- received message.
+-- If raw listener returned `True`, then processing continues with given typed listeners
+-- in the way defined in `listenH`.
+listenR :: (Unpackable p (WithHeaderData h RawData),Unpackable p NameData,
+            MonadListener s m, MonadDialog s p m)
+        => Binding -> [ListenerH s p h m] -> ListenerR s h m -> m (m ())
+listenR binding listeners rawListener = do
+    packing <- packingType
+    forking <- forkStrategy
+    listenRaw binding $ handleAll handleE $
+        unpackMsg packing =$= CL.mapM  (processContent packing)
+                          =$= CL.mapM_ (uncurry $ withForkStrategy forking)
+  where
+    processContent packing msg = do
+        WithHeaderData header raw <- extractMsgPart packing msg
+        NameData name             <- extractMsgPart packing msg
+
+        case listenersMap ^. at name of
+            Nothing -> do
+                commLog . logWarning $
+                    sformat ("No listener with name "%stext%" defined") name
+                putDownstream name . void $
+                    invokeRawListenerSafe $ rawListener (header, raw)
+
+            Just (ListenerH f) -> do
+                ContentData r <- extractMsgPart packing msg
+                putDownstream name $ do
+                    cont <- invokeRawListenerSafe $ rawListener (header, raw)
+                    peer <- peerAddr
+                    when cont $ do
+                        commLog . logDebug $
+                            sformat ("Got message from "%stext%": "%stext)
+                            peer (formatMessage r)
+                        invokeListenerSafe name $ f (header, r)
+
+    handleE e = lift . commLog . logWarning $
+                    sformat ("Error parsing message: " % shown) e
+
+    -- TODO: check for duplicates
+    listenersMap = M.fromList [(getListenerNameH li, li) | li <- listeners]
+
+    invokeRawListenerSafe = handleAll $ \e -> do
+        commLog . logError $ sformat ("Uncaught error in raw listener: "%shown) e
+        return False
+
+    invokeListenerSafe name = handleAll $
+        commLog . logError . sformat ("Uncaught error in listener "%shown%": "%shown) name
+
+    putDownstream = curry return
+
+-- * Listeners
+
+-- | Creates plain listener which accepts message.
+data Listener s p m =
+    forall r . (Unpackable p (ContentData r), Message r)
+             => Listener (r -> ResponseT s m ())
+
+-- | Creates listener which accepts header and message.
+data ListenerH s p h m =
+    forall r . (Unpackable p (ContentData r), Message r)
+             => ListenerH ((h, r) -> ResponseT s m ())
+
+-- | Creates listener which accepts header and raw data.
+-- Returns, whether message souhld then be deserialized and passed to typed listener.
+type ListenerR s h m = (h, RawData) -> ResponseT s m Bool
+
+-- | Gets name of message type, acceptable by this listener.
+getListenerName :: Listener s p m -> MessageName
+getListenerName (Listener f) = messageName $ proxyOfArg f
+  where
+    proxyOfArg :: (a -> b) -> Proxy a
+    proxyOfArg _ = Proxy
+
+-- | Gets name of message type, acceptable by this listener.
+getListenerNameH :: ListenerH s p h m -> MessageName
+getListenerNameH (ListenerH f) = messageName $ proxyOfArg f
+  where
+    proxyOfArg :: ((h, a) -> b) -> Proxy a
+    proxyOfArg _ = Proxy
+
+
+-- * Default instance of MonadDialog
+
+-- | Default implementation of `MonadDialog`.
+-- Keeps packing type in context, allowing to use the same serialization strategy
+-- all over the code without extra boilerplate.
+newtype Dialog p m a = Dialog
+    { getDialog :: ReaderT (p, ForkStrategy MessageName) m a
+    } deriving (Functor, Applicative, Monad, MonadIO, MonadTrans,
+                MonadThrow, MonadCatch, MonadMask,
+                MonadState s, CanLog, HasLoggerName, MonadTimed)
+
+-- | Runs given `Dialog`.
+runDialog :: p -> Dialog p m a -> m a
+runDialog p = flip runReaderT (p, ForkStrategy $ const fork_) . getDialog
+
+instance MonadBase IO m => MonadBase IO (Dialog p m) where
+    liftBase = lift . liftBase
+
+instance MonadTransControl (Dialog p) where
+    type StT (Dialog p) a = StT (ReaderT p) a
+    liftWith = defaultLiftWith Dialog getDialog
+    restoreT = defaultRestoreT Dialog
+
+instance MonadBaseControl IO m => MonadBaseControl IO (Dialog p m) where
+    type StM (Dialog p m) a = ComposeSt (Dialog p) m a
+    liftBaseWith     = defaultLiftBaseWith
+    restoreM         = defaultRestoreM
+
+type instance ThreadId (Dialog p m) = ThreadId m
+
+instance Monad m => WrappedM (Dialog p m) where
+    type UnwrappedM (Dialog p m) = ReaderT (p, ForkStrategy MessageName) m
+    _WrappedM = iso getDialog Dialog
+
+instance MonadTransfer s m => MonadTransfer s (Dialog p m) where
+
+instance MonadTransfer s m => MonadDialog s p (Dialog p m) where
+    packingType = fst <$> Dialog ask
+    forkStrategy = snd <$> Dialog ask
+    setForkStrategy fs = Dialog . local (_2 .~ fs) . getDialog
+
+
+-- * Instances
+
+instance MonadDialog s p m => MonadDialog s p (ReaderT r m) where
+    packingType = lift packingType
+    forkStrategy = lift forkStrategy
+    setForkStrategy fs = hoist $ setForkStrategy fs
+
+deriving instance MonadDialog s p m => MonadDialog s p (LoggerNameBox m)
+
+deriving instance MonadDialog s p m => MonadDialog s p (ResponseT s0 m)
diff --git a/src/Control/TimeWarp/Rpc/MonadRpc.hs b/src/Control/TimeWarp/Rpc/MonadRpc.hs
deleted file mode 100644
--- a/src/Control/TimeWarp/Rpc/MonadRpc.hs
+++ /dev/null
@@ -1,140 +0,0 @@
-{-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE GADTs                 #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE StandaloneDeriving    #-}
-{-# LANGUAGE TypeFamilies          #-}
-{-# LANGUAGE ViewPatterns          #-}
-
--- |
--- Module      : Control.TimeWarp.Rpc.MonadRpc
--- Copyright   : (c) Serokell, 2016
--- License     : GPL-3 (see the file LICENSE)
--- Maintainer  : Serokell <hi@serokell.io>
--- Stability   : experimental
--- Portability : POSIX, GHC
---
--- This module contains `MonadRpc` typeclass which abstracts over
--- RPC communication.
-
-module Control.TimeWarp.Rpc.MonadRpc
-       ( Port
-       , Host
-       , NetworkAddress
-
-       , MonadRpc (serve, execClient)
-       , RpcType()
-       , execClientTimeout
-       , Method(..)
-       , Client(..)
-       , method
-       , call
-       , S.Server
-       , S.ServerT
-       , S.MethodType
-       , C.RpcError(..)
-       ) where
-
-import           Control.Monad.Catch        (MonadCatch (catch),
-                                             MonadThrow (throwM))
-import           Control.Monad.Reader       (ReaderT (..))
-import           Control.Monad.Trans        (lift)
-import           Data.ByteString            (ByteString)
-
-import           Data.MessagePack           (MessagePack, toObject, Object)
-import           Data.Time.Units            (TimeUnit)
-
-import qualified Network.MessagePack.Client as C
-import qualified Network.MessagePack.Server as S
-
-import           Control.TimeWarp.Logging   (WithNamedLogger, LoggerNameBox (..))
-import           Control.TimeWarp.Timed     (MonadTimed (timeout))
-
--- | Port number.
-type Port = Int
-
--- | Host address.
-type Host = ByteString
-
--- | Full node address.
-type NetworkAddress = (Host, Port)
-
-
-deriving instance WithNamedLogger m => WithNamedLogger (S.ServerT m)
-
--- | Defines protocol of RPC layer.
-class MonadThrow r => MonadRpc r where
-    -- | Executes remote method call.
-    execClient :: MessagePack a => NetworkAddress -> Client a -> r a
-
-    -- | Starts RPC server with a set of RPC methods.
-    serve :: Port -> [Method r] -> r ()
-
--- | Same as `execClient`, but allows to set up timeout for a call (see
--- `Control.TimeWarp.Timed.MonadTimed.timeout`).
-execClientTimeout
-    :: (MonadTimed m, MonadRpc m, MessagePack a, TimeUnit t)
-    => t -> NetworkAddress -> Client a -> m a
-execClientTimeout t addr = timeout t . execClient addr
-
--- * Client part
-
--- | Creates a function call. It accepts function name and arguments.
-call :: RpcType t => String -> t
-call name = rpcc name []
-
--- | Collects function name and arguments
--- (it's <https://hackage.haskell.org/package/msgpack-rpc-1.0.0/docs/Network-MessagePack-Client.html#v:call msgpack-rpc> implementation is hidden, need our own).
-class RpcType t where
-    rpcc :: String -> [Object] -> t
-
-instance (RpcType t, MessagePack p) => RpcType (p -> t) where
-    rpcc name objs p = rpcc name $ toObject p : objs
-
--- | Keeps function name and arguments.
-data Client a where
-    Client :: MessagePack a => String -> [Object] -> Client a
-
-instance MessagePack o => RpcType (Client o) where
-    rpcc name args = Client name (reverse args)
-
--- * Server part
-
--- | Keeps method definition.
-data Method m = Method
-    { methodName :: String
-    , methodBody :: [Object] -> m Object
-    }
-
--- | Creates method available for RPC-requests.
---   It accepts method name (which would be refered by clients)
---   and it's body.
-method :: S.MethodType m f => String -> f -> Method m
-method name f = Method
-    { methodName = name
-    , methodBody = S.toBody f
-    }
-
-instance Monad m => S.MethodType m Object where
-    toBody res [] = return res
-    toBody _   _  = error "Too many arguments!"
-
-instance MonadThrow m => MonadThrow (S.ServerT m) where
-    throwM = lift . throwM
-
-instance MonadCatch m =>
-         MonadCatch (S.ServerT m) where
-    catch (S.ServerT action) handler =
-        S.ServerT $ action `catch` (S.runServerT . handler)
-
-instance MonadRpc m => MonadRpc (ReaderT r m) where
-    execClient addr cli = lift $ execClient addr cli
-
-    serve port methods = ReaderT $
-                            \r -> serve port (convert r <$> methods)
-      where
-        convert :: r -> Method (ReaderT r m) -> Method m
-        convert r Method {..} =
-            Method methodName (flip runReaderT r . methodBody)
-
-deriving instance MonadRpc m => MonadRpc (LoggerNameBox m)
diff --git a/src/Control/TimeWarp/Rpc/MonadTransfer.hs b/src/Control/TimeWarp/Rpc/MonadTransfer.hs
new file mode 100644
--- /dev/null
+++ b/src/Control/TimeWarp/Rpc/MonadTransfer.hs
@@ -0,0 +1,246 @@
+{-# LANGUAGE AllowAmbiguousTypes       #-}
+{-# LANGUAGE DefaultSignatures         #-}
+{-# LANGUAGE ExistentialQuantification #-}
+{-# LANGUAGE FlexibleContexts          #-}
+{-# LANGUAGE FlexibleInstances         #-}
+{-# LANGUAGE FunctionalDependencies    #-}
+{-# LANGUAGE GADTs                     #-}
+{-# LANGUAGE MultiParamTypeClasses     #-}
+{-# LANGUAGE Rank2Types                #-}
+{-# LANGUAGE TypeFamilies              #-}
+{-# LANGUAGE UndecidableInstances      #-}
+
+-- |
+-- Module      : Control.TimeWarp.Rpc.MonadTransfer
+-- Copyright   : (c) Serokell, 2016
+-- License     : GPL-3 (see the file LICENSE)
+-- Maintainer  : Serokell <hi@serokell.io>
+-- Stability   : experimental
+-- Portability : POSIX, GHC
+--
+-- This module defines monad, which serves for sending and receiving raw byte streams.
+--
+-- UPGRAGE-NOTE (TW-47):
+-- We'd like to have another interface for `listenRaw` function.
+-- Currently it allows only single listener for given connection.
+-- It makes difficult to define, for example, a listener for all outbound connections,
+-- which is likely to have.
+-- There is a proposal to have subscriptions-based interface:
+--
+--   * `listenRaw` is in some sense automatically applied when connection is created
+--
+--   * At `Dialog` layer, add `subscribe` function which allows to listen for messages at
+--       specified port / specified outbound connection / sum of them.
+
+module Control.TimeWarp.Rpc.MonadTransfer
+       ( -- * Related datatypes
+         Port
+       , Host
+       , NetworkAddress
+       , Binding (..)
+       , localhost
+       , commLoggerName
+       , commLog
+
+       -- * MonadTransfer
+       , MonadTransfer (..)
+
+       -- * MonadResponse
+       , MonadResponse (..)
+       , ResponseContext (..)
+       , ResponseT (..)
+       , runResponseT
+       , mapResponseT
+       , hoistRespCond
+       ) where
+
+import           Control.Lens                (iso, view)
+import           Control.Monad.Catch         (MonadCatch, MonadMask, MonadThrow)
+import           Control.Monad.Morph         (hoist)
+import           Control.Monad.Reader        (MonadReader (..), ReaderT (..), mapReaderT)
+import           Control.Monad.State         (MonadState)
+import           Control.Monad.Trans         (MonadIO (..), MonadTrans (..))
+import           Control.Monad.Trans.Control (MonadTransControl (..))
+import           Data.ByteString             (ByteString)
+import           Data.Conduit                (ConduitM, Producer, Sink, Source)
+import           Data.Monoid                 ((<>))
+import           Data.Text                   (Text)
+import           Data.Word                   (Word16)
+import           System.Wlog                 (CanLog, HasLoggerName, LoggerName,
+                                              LoggerNameBox (..), WithLogger,
+                                              modifyLoggerName)
+
+import           Serokell.Util.Lens          (WrappedM (..), _UnwrappedM)
+
+import           Control.TimeWarp.Timed      (MonadTimed, ThreadId)
+
+
+-- * Related datatypes
+
+-- | Port number.
+type Port = Word16
+
+-- | Host address.
+type Host = ByteString
+
+-- | @"127.0.0.1"@.
+localhost :: Host
+localhost = "127.0.0.1"
+
+-- | Full node address.
+type NetworkAddress = (Host, Port)
+
+-- | Name of logger responsible for communication events - @comm@.
+-- TODO: Make non-hardcoded.
+commLoggerName :: LoggerName
+commLoggerName = "comm"
+
+-- | Appends `commLoggerName` as suffix to current logger name.
+commLog :: HasLoggerName m => m a -> m a
+commLog = modifyLoggerName (<> commLoggerName)
+
+-- | Specifies type of `listen` binding.
+--
+-- UPGRADE-NOTE: adding /Loopback/ binding may be useful.
+data Binding
+    = AtPort Port              -- ^ Listen at port
+    | AtConnTo NetworkAddress  -- ^ Listen at connection established earlier
+    deriving (Eq, Ord, Show)
+
+
+-- * MonadTransfer
+
+-- | Allows to send/receive raw byte sequences.
+class Monad m => MonadTransfer s m | m -> s where
+    -- | Sends raw data.
+    -- When invoked several times for same address, this function is expected to
+    -- use same connection kept under hood.
+    -- Byte sequence, produced by given source, will be transmitted as a whole;
+    sendRaw :: NetworkAddress       -- ^ Destination address
+            -> Source m ByteString  -- ^ Data to send
+            -> m ()
+    default sendRaw :: (WrappedM m, MonadTransfer s (UnwrappedM m))
+                    => NetworkAddress -> Source m ByteString -> m ()
+    sendRaw addr req = view _UnwrappedM $
+        sendRaw addr $ view _WrappedM `hoist` req
+
+    -- | Listens at specified input or output connection.
+    -- Returns server stopper, which blocks current thread until server is actually
+    -- stopped.
+    -- Calling this function in case there is defined listener already for this
+    -- connection should lead to error.
+    listenRaw :: Binding                             -- ^ Port/address to listen to
+              -> Sink ByteString (ResponseT s m) ()  -- ^ Parser for input byte stream
+              -> m (m ())                            -- ^ Server stopper
+    default listenRaw :: (WrappedM m, MonadTransfer s (UnwrappedM m))
+                      => Binding -> Sink ByteString (ResponseT s m) () -> m (m ())
+    listenRaw binding sink = view _UnwrappedM $ fmap (view _UnwrappedM) $
+            listenRaw binding $ view _WrappedM `hoistRespCond` sink
+
+    -- | Closes outbound connection to specified node, if exists.
+    -- To close inbound connections, use `closeR`.
+    close :: NetworkAddress -> m ()
+    default close :: (WrappedM m, MonadTransfer s (UnwrappedM m))
+                  => NetworkAddress -> m ()
+    close = view _UnwrappedM . close
+
+    -- | Gets state, attached to related socket.
+    -- If such connection doesn't exist, it would be created.
+    userState :: NetworkAddress -> m s
+    default userState :: (WrappedM m, MonadTransfer s (UnwrappedM m))
+                      => NetworkAddress -> m s
+    userState = view _UnwrappedM . userState
+
+
+-- * MonadResponse
+
+-- | Provides operations related to /peer/ node. Peer is a node, which this node is
+-- currently communicating with.
+class Monad m => MonadResponse s m | m -> s where
+    -- | Sends data to peer.
+    replyRaw :: Producer m ByteString -> m ()
+
+    -- | Closes connection with peer.
+    closeR :: m ()
+
+    -- | Gets address of peer, for debugging purposes only.
+    peerAddr :: m Text
+
+    -- | Get state attached to socket.
+    userStateR :: m s
+    default userStateR :: (MonadTrans t, t n ~ m, MonadResponse s n) => t n s
+    userStateR = lift userStateR
+
+
+-- | Keeps information about peer.
+data ResponseContext s = ResponseContext
+    { respSend      :: forall m . (MonadIO m, MonadMask m, WithLogger m)
+                    => Source m ByteString -> m ()
+    , respClose     :: IO ()
+    , respPeerAddr  :: Text
+    , respUserState :: s
+    }
+
+-- | Default implementation of `MonadResponse`.
+newtype ResponseT s m a = ResponseT
+    { getResponseT :: ReaderT (ResponseContext s) m a
+    } deriving (Functor, Applicative, Monad, MonadIO, MonadTrans,
+                MonadThrow, MonadCatch, MonadMask,
+                MonadState ss, CanLog,
+                HasLoggerName, MonadTimed)
+
+-- | Unwrappes `ResponseT`.
+runResponseT :: ResponseT s m a -> ResponseContext s -> m a
+runResponseT = runReaderT . getResponseT
+
+instance Monad m => WrappedM (ResponseT s m) where
+    type UnwrappedM (ResponseT s m) = ReaderT (ResponseContext s) m
+    _WrappedM = iso getResponseT ResponseT
+
+type instance ThreadId (ResponseT s m) = ThreadId m
+
+instance MonadReader r m => MonadReader r (ResponseT s m) where
+    ask = lift ask
+    reader f = lift $ reader f
+    local = mapResponseT . local
+
+instance MonadTransfer s m => MonadTransfer s (ResponseT s0 m) where
+
+instance (MonadIO m, MonadMask m, WithLogger m)
+         => MonadResponse s (ResponseT s m) where
+    replyRaw dat = ResponseT ask >>= \ctx -> respSend ctx dat
+
+    closeR = ResponseT $ ask >>= liftIO . respClose
+
+    peerAddr = respPeerAddr <$> ResponseT ask
+
+    userStateR = respUserState <$> ResponseT ask
+
+-- | Maps entry of `ResponseT`.
+-- TODO: implement `hoist` instead, it should be enough.
+mapResponseT :: (m a -> n b) -> ResponseT s m a -> ResponseT s n b
+mapResponseT how = ResponseT . mapReaderT how . getResponseT
+
+
+-- * Instances
+
+-- | Allows to modify entry of @Conduit i o (ResponseT m) r@.
+hoistRespCond :: Monad m
+              => (forall a . m a -> n a)
+              -> ConduitM i o (ResponseT s m) r
+              -> ConduitM i o (ResponseT s n) r
+hoistRespCond how = hoist $ mapResponseT how
+
+instance MonadTransfer s m => MonadTransfer s (ReaderT r m) where
+    sendRaw addr req = ask >>= \ctx -> lift $ sendRaw addr (hoist (`runReaderT` ctx) req)
+    listenRaw binding sink =
+        fmap lift $ liftWith $ \run -> listenRaw binding $ hoistRespCond run sink
+    close = lift . close
+    userState = lift . userState
+
+instance MonadTransfer s m => MonadTransfer s (LoggerNameBox m) where
+
+instance MonadResponse s m => MonadResponse s (ReaderT r m) where
+    replyRaw dat = ask >>= \ctx -> lift $ replyRaw (hoist (`runReaderT` ctx) dat)
+    closeR = lift closeR
+    peerAddr = lift peerAddr
diff --git a/src/Control/TimeWarp/Rpc/MsgPackRpc.hs b/src/Control/TimeWarp/Rpc/MsgPackRpc.hs
deleted file mode 100644
--- a/src/Control/TimeWarp/Rpc/MsgPackRpc.hs
+++ /dev/null
@@ -1,79 +0,0 @@
-{-# LANGUAGE FlexibleContexts      #-}
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE GADTs                 #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE TypeFamilies          #-}
-
--- |
--- Module      : Control.TimeWarp.Rpc.MsgPackRpc
--- Copyright   : (c) Serokell, 2016
--- License     : GPL-3 (see the file LICENSE)
--- Maintainer  : Serokell <hi@serokell.io>
--- Stability   : experimental
--- Portability : POSIX, GHC
---
--- This module contains implementation of `MonadRpc` for real mode
--- (network, time- and thread-management capabilities provided by OS are used).
-
-module Control.TimeWarp.Rpc.MsgPackRpc
-       ( MsgPackRpc
-       , runMsgPackRpc
-       ) where
-
-import qualified Control.Concurrent            as C
-import           Control.Monad.Base            (MonadBase)
-import           Control.Monad.Catch           (MonadCatch, MonadMask,
-                                                MonadThrow)
-import           Control.Monad.Trans           (MonadIO (..))
-import           Control.Monad.Trans.Control   (MonadBaseControl, StM,
-                                                liftBaseWith, restoreM)
-
-import           Data.IORef                    (newIORef, readIORef, writeIORef)
-import           Data.Maybe                    (fromMaybe)
-
-import qualified Network.MessagePack.Client    as C
-import qualified Network.MessagePack.Server    as S
-
-import           Control.TimeWarp.Rpc.MonadRpc (Client (..), Method (..),
-                                                MonadRpc (..))
-import           Control.TimeWarp.Timed        (MonadTimed (..), TimedIO, ThreadId,
-                                                runTimedIO)
-
--- | Wrapper over `Control.TimeWarp.Timed.TimedIO`, which implements `MonadRpc`
--- using <https://hackage.haskell.org/package/msgpack-rpc-1.0.0 msgpack-rpc>.
-newtype MsgPackRpc a = MsgPackRpc
-    { -- | Launches distributed scenario using real network, threads and time.
-      unwrapMsgPackRpc :: TimedIO a
-    } deriving (Functor, Applicative, Monad, MonadIO, MonadBase IO,
-                MonadThrow, MonadCatch, MonadMask, MonadTimed)
-
-runMsgPackRpc :: MsgPackRpc a -> IO a
-runMsgPackRpc = runTimedIO . unwrapMsgPackRpc
-
-type instance ThreadId MsgPackRpc = C.ThreadId
-
-instance MonadBaseControl IO MsgPackRpc where
-    type StM MsgPackRpc a = a
-
-    liftBaseWith f = MsgPackRpc $ liftBaseWith $ \g -> f $ g . unwrapMsgPackRpc
-
-    restoreM = MsgPackRpc . restoreM
-
-instance MonadRpc MsgPackRpc where
-    execClient (addr, port) (Client name args) = liftIO $ do
-        box <- newIORef Nothing
-        C.execClient addr port $ do
-            -- note, underlying rpc accepts a single argument - [Object]
-            res <- C.call name args
-            liftIO . writeIORef box $ Just res
-        fromMaybe (error "execClient didn't return a value!")
-            <$> readIORef box
-
-    serve port methods = S.serve port $ convertMethod <$> methods
-      where
-        convertMethod :: Method MsgPackRpc -> S.Method MsgPackRpc
-        convertMethod Method{..} = S.method methodName methodBody
-
-instance S.MethodType MsgPackRpc f => S.MethodType MsgPackRpc (MsgPackRpc f)
-   where
-    toBody res args = res >>= flip S.toBody args
diff --git a/src/Control/TimeWarp/Rpc/PureRpc.hs b/src/Control/TimeWarp/Rpc/PureRpc.hs
deleted file mode 100644
--- a/src/Control/TimeWarp/Rpc/PureRpc.hs
+++ /dev/null
@@ -1,246 +0,0 @@
-{-# LANGUAGE ExplicitForAll        #-}
-{-# LANGUAGE FlexibleInstances     #-}
-{-# LANGUAGE MultiParamTypeClasses #-}
-{-# LANGUAGE StandaloneDeriving    #-}
-{-# LANGUAGE TemplateHaskell       #-}
-{-# LANGUAGE TypeFamilies          #-}
-{-# LANGUAGE UndecidableInstances  #-}
-{-# LANGUAGE ViewPatterns          #-}
-
--- |
--- Module      : Control.TimeWarp.Rpc.PureRpc
--- Copyright   : (c) Serokell, 2016
--- License     : GPL-3 (see the file LICENSE)
--- Maintainer  : Serokell <hi@serokell.io>
--- Stability   : experimental
--- Portability : POSIX, GHC
---
--- Defines network-emulated implementation of `MonadRpc`. Threads and time are
--- also emulated via `Control.TimeWarp.Timed.TimedT`.
-module Control.TimeWarp.Rpc.PureRpc
-       ( PureRpc
-       , runPureRpc
-       , DelaysSpecifier (..)
-       , Delays (..)
-       , ConnectionOutcome (..)
-       , getRandomTR
-       ) where
-
-import           Control.Exception.Base        (Exception)
-import           Control.Lens                  (both, makeLenses, to, use, (%%=),
-                                                (%~), at, (?=))
-import           Control.Monad                 (forM_, when)
-import           Control.Monad.Catch           (MonadCatch, MonadMask, MonadThrow, throwM)
-import           Control.Monad.Random          (MonadRandom (getRandomR), Rand, runRand)
-import           Control.Monad.State           (MonadState (get, put, state), StateT,
-                                                evalStateT)
-import           Control.Monad.Trans           (MonadIO, MonadTrans, lift)
-import           Data.Default                  (Default, def)
-import           Data.Map                      as Map
-import           Data.Time.Units               (fromMicroseconds, toMicroseconds)
-import           Data.Typeable                 (Typeable)
-import           System.Random                 (StdGen)
-
-import           Data.MessagePack              (Object, MessagePack (..))
-
-import           Control.TimeWarp.Logging      (WithNamedLogger)
-import           Control.TimeWarp.Rpc.MonadRpc (Client (..), Host, Method (..),
-                                                MonadRpc (execClient, serve),
-                                                Port, RpcError (..), methodBody,
-                                                methodName, NetworkAddress)
-import           Control.TimeWarp.Timed        (Microsecond, MonadTimed (..),
-                                                PureThreadId, TimedT, for,
-                                                virtualTime, runTimedT, sleepForever,
-                                                wait, ThreadId)
-
-localhost :: Host
-localhost = "127.0.0.1"
-
--- | Describes obstructions occured on executing RPC request.
-data ConnectionOutcome
-    -- | Connection established in specified amout of time.
-    = ConnectedIn Microsecond
-    -- | Connection would be never established, client hangs.
-    | NeverConnected
-
--- | Allows to describe most complicated behaviour of network.
---
--- Examples:
---
--- * Always 1 second delay:
---
--- @
--- Delays $ \\_ _ -> return $ ConnectedIn (interval 1 sec)
--- @
---
--- * Delay varies between 1 and 5 seconds (with granularity of 1 mcs):
---
--- @
--- Delays $ \\_ _ -> ConnectedIn \<$\> getRandomTR (interval 1 sec, interval 5 sec)
--- @
---
--- * For first 10 seconds after scenario start connection is established
--- with probability of 1/6:
---
--- @
--- Delays $ \\_ time -> do
---     p <- getRandomR (0, 5)
---     if (p == 0) && (time <= interval 10 sec)
---         then return $ ConnectedIn 0
---         else return NeverConnected
--- @
---
--- * Node with address `isolatedAddr` is not accessible:
---
--- @
--- Delays $ \\serverAddr _ ->
---     return if serverAddr == isolatedAddr
---            then NeverConnected
---            else ConnectedIn 0
--- @
-
-newtype Delays = Delays
-    { -- | Basing on current virtual time, rpc method server's
-      -- address, returns delay after which server receives RPC request.
-      evalDelay :: NetworkAddress
-                -> Microsecond
-                -> Rand StdGen ConnectionOutcome
-    }
-
--- | Describes network nastiness.
-class DelaysSpecifier d where
-    toDelays :: d -> Delays
-
--- | Detailed description of network nastiness.
-instance DelaysSpecifier Delays where
-    toDelays = id
-
--- | Connection is never established.
-instance DelaysSpecifier () where
-    toDelays = const . Delays . const . const . return $ NeverConnected
-
--- | Specifies permanent connection delay.
-instance DelaysSpecifier Microsecond where
-    toDelays = Delays . const . const . return . ConnectedIn
-
--- | Connection delay varies is specified range.
-instance DelaysSpecifier (Microsecond, Microsecond) where
-    toDelays = Delays . const . const . fmap ConnectedIn . getRandomTR
-
--- This is needed for QC.
-instance Show Delays where
-    show _ = "Delays"
-
--- | Describes reliable network.
-instance Default Delays where
-    def = Delays . const . const . return . ConnectedIn $ 0
-
--- | Return a randomly-selected time value in specified range.
-getRandomTR :: MonadRandom m => (Microsecond, Microsecond) -> m Microsecond
-getRandomTR = fmap fromMicroseconds . getRandomR . (both %~ toMicroseconds)
-
--- | Keeps servers' methods.
-type Listeners m = Map.Map (Port, String) ([Object] -> m Object)
-
--- | Keeps global network information.
-data NetInfo m = NetInfo
-    { _listeners :: Listeners m
-    , _randSeed  :: StdGen
-    , _delays    :: Delays
-    }
-
-$(makeLenses ''NetInfo)
-
--- | Implementation of RPC protocol for emulation, allows to manually define
--- network nastiness via `Delays` datatype. TCP model is used.
---
--- List of known issues:
---
---     * Method, once being declared in net, can't be removed.
--- Even `throwTo` won't help.
---
---     * In implementation, remote method is actually inlined at call position,
--- so @instance WithNamedLogger@ would refer to caller's logger name, not
--- server's one.
-newtype PureRpc m a = PureRpc
-    { unwrapPureRpc :: TimedT (StateT (NetInfo (PureRpc m)) m) a
-    } deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch,
-                MonadMask, WithNamedLogger)
-
-type instance ThreadId (PureRpc m) = PureThreadId
-
-deriving instance (MonadIO m, MonadCatch m) => MonadTimed (PureRpc m)
-
-instance MonadTrans PureRpc where
-    lift = PureRpc . lift . lift
-
-instance MonadState s m => MonadState s (PureRpc m) where
-    get = lift get
-    put = lift . put
-    state = lift . state
-
--- | Launches distributed scenario, emulating work of network.
-runPureRpc
-    :: (MonadIO m, MonadCatch m, DelaysSpecifier delays)
-    => StdGen -> delays -> PureRpc m a -> m a
-runPureRpc _randSeed (toDelays -> _delays) rpc =
-    evalStateT (runTimedT $ unwrapPureRpc rpc) net
-  where
-    net        = NetInfo{..}
-    _listeners = Map.empty
-
-request :: (MonadThrow m, MessagePack a)
-        => Client a
-        -> Listeners (PureRpc m)
-        -> Port
-        -> PureRpc m a
-request (Client name args) listeners' port =
-    case Map.lookup (port, name) listeners' of
-        Nothing -> throwM $ ServerError $ toObject $ mconcat
-            ["method \"", name, "\" not found at port ", show port]
-        Just f  -> do
-            res <- f args
-            case fromObject res of
-                Nothing -> throwM $ ResultTypeError "type mismatch" res
-                Just r  -> return r
-
-
-instance (MonadIO m, MonadCatch m) =>
-         MonadRpc (PureRpc m) where
-    execClient addr@(host, port) cli =
-        if host /= localhost
-            then
-                error "Can't emulate for host /= localhost"
-            else do
-                waitDelay addr
-                ls <- PureRpc $ use listeners
-                request cli ls port
-    serve port methods =
-        PureRpc $
-        do lift $
-               forM_ methods $
-               \Method {..} -> do
-                    let methodRef = (port, methodName)
-                    defined <- use $ listeners . to (Map.member methodRef)
-                    when defined $ return ()
-                    -- TODO:
-                    --    throwM $ PortAlreadyBindedError port
-                    listeners . at (port, methodName) ?= methodBody
-           sleepForever
-
-waitDelay
-    :: (MonadThrow m, MonadIO m, MonadCatch m)
-    => NetworkAddress -> PureRpc m ()
-waitDelay addr =
-    PureRpc $
-    do delays' <- use delays
-       time    <- virtualTime
-       delay   <- randSeed %%= runRand (evalDelay delays' addr time)
-       case delay of
-           ConnectedIn connDelay -> wait (for connDelay)
-           NeverConnected        -> sleepForever
-
-data PortAlreadyBindedError = PortAlreadyBindedError Port
-    deriving (Show, Typeable)
-
-instance Exception PortAlreadyBindedError
diff --git a/src/Control/TimeWarp/Rpc/Restriction.hs b/src/Control/TimeWarp/Rpc/Restriction.hs
deleted file mode 100644
--- a/src/Control/TimeWarp/Rpc/Restriction.hs
+++ /dev/null
@@ -1,69 +0,0 @@
-{-# LANGUAGE Rank2Types #-}
-
--- |
--- Module      : Control.TimeWarp.Rpc.Restriction
--- Copyright   : (c) Serokell, 2016
--- License     : GPL-3 (see the file LICENSE)
--- Maintainer  : Serokell <hi@serokell.io>
--- Stability   : experimental
--- Portability : POSIX, GHC
---
--- This module helps abstragate from concrete instance of
--- `Control.TimeWarp.Rpc.MonadRpc`.
---
--- Consider such example:
---
--- @
--- sumMethod :: MonadRpc m => Int -> Int -> ServerT m Int
--- sumMethod a b = return $ a + b
---
--- startServer :: MonadRpc m => m ()
--- startServer = serve 1234 [method "sum" sumMethod]
--- @
---
--- This code won't compile, because compiler doesn't know that type @m@
--- in @sumMethod@ is the same @m@ as in @startServer@, so it can't apply
--- 'Control.TimeWarp.Rpc.MonadRpc.method' to @sumMethod@
--- (`Network.MessagePack.Server.MethodType` won't be deduced).
---
--- Functions @restrictServerType/N/@, where /N/ is method's arguments number,
--- help to bound the type. They are all defined like @return id@.
---
--- So the error above can be fixed in following way:
---
--- @
--- startServer :: MonadRpc m => m ()
--- startServer = do
---    idr <- restrictServerType2
---    serve 1234 [method "sum" $ idr sumMethod]
--- @
-
-module Control.TimeWarp.Rpc.Restriction where
-
-import Control.TimeWarp.Rpc.MonadRpc (ServerT)
-
-type ServerRestriction m t = m (t -> t)
-
-serverTypeRestriction0 ::
-    Monad m => ServerRestriction m (ServerT m a)
-serverTypeRestriction0 = return id
-
-serverTypeRestriction1 ::
-    Monad m => ServerRestriction m (b -> ServerT m a)
-serverTypeRestriction1 = return id
-
-serverTypeRestriction2 ::
-    Monad m => ServerRestriction m (c -> b -> ServerT m a)
-serverTypeRestriction2 = return id
-
-serverTypeRestriction3 ::
-    Monad m => ServerRestriction m (d -> c -> b -> ServerT m a)
-serverTypeRestriction3 = return id
-
-serverTypeRestriction4 ::
-    Monad m => ServerRestriction m (e -> d -> c -> b -> ServerT m a)
-serverTypeRestriction4 = return id
-
-serverTypeRestriction5 ::
-    Monad m => ServerRestriction m (f -> e -> d -> c -> b -> ServerT m a)
-serverTypeRestriction5 = return id
diff --git a/src/Control/TimeWarp/Rpc/Transfer.hs b/src/Control/TimeWarp/Rpc/Transfer.hs
new file mode 100644
--- /dev/null
+++ b/src/Control/TimeWarp/Rpc/Transfer.hs
@@ -0,0 +1,622 @@
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+{-# LANGUAGE Rank2Types            #-}
+{-# LANGUAGE ScopedTypeVariables   #-}
+{-# LANGUAGE TemplateHaskell       #-}
+{-# LANGUAGE TupleSections         #-}
+{-# LANGUAGE TypeFamilies          #-}
+{-# LANGUAGE UndecidableInstances  #-}
+{-# LANGUAGE ViewPatterns          #-}
+
+-- |
+-- Module      : Control.TimeWarp.Rpc.Transfer
+-- Copyright   : (c) Serokell, 2016
+-- License     : GPL-3 (see the file LICENSE)
+-- Maintainer  : Serokell <hi@serokell.io>
+-- Stability   : experimental
+-- Portability : POSIX, GHC
+--
+-- This module provides implementation of `MonadTransfer`.
+--
+-- It operates with so called /lively sockets/, so that, if error occured while sending
+-- or receiving, it would try to restore connection before reporting error.
+--
+-- When some data is sent for first time to given address, connection with single
+-- lively-socket is created; it would be reused for further sends until closed.
+--
+-- Then server is getting up at some port, it creates single thread to handle incoming
+-- connections, then for each input connection lively-socket is created.
+--
+-- TODO [TW-67]: close all connections upon quiting `Transfer` monad.
+--
+--
+-- About lively sockets:
+--
+-- Lively socket keeps queue of byte chunks inside.
+-- For given lively-socket, @send@ function just pushes chunks to send-queue, whenever
+-- @receive@ infinitelly acquires chunks from receive-queue.
+-- Those queues are connected to plain socket behind the scene.
+--
+-- Let's say lively socket to be /active/ if it successfully sends and receives
+-- required data at the moment.
+-- Upon becoming active, lively socket spawns `processing-observer` thread, which itself
+-- spawns 3 threads: one pushes chunks from send-queue to socket, another one
+-- pulls chunks from socket to receive-queue, and the last tracks whether socket was
+-- closed.
+-- Processor thread finishes in one of the following cases:
+--
+--    * One of it's children threads threw an error
+--
+--    * Socket was closed
+--
+-- If some error occures, lively socket goes to exceptional state (which is not expressed
+-- in code, however), where it could be closed or provided with newly created plain socket
+-- to continue work with and thus become active again.
+--
+-- UPGRADE-NOTE [TW-59]:
+-- Currently, if an error in listener occures (parse error), socket gets closed.
+-- Need to make it reconnect, if possible.
+
+
+module Control.TimeWarp.Rpc.Transfer
+       (
+       -- * Transfer
+         Transfer (..)
+       , TransferException (..)
+       , runTransfer
+       , runTransferS
+
+       -- * Settings
+       , FailsInRow
+       , Settings (..)
+       ) where
+
+import qualified Control.Concurrent                 as C
+import           Control.Concurrent.STM             (STM, atomically, check)
+import qualified Control.Concurrent.STM.TBMChan     as TBM
+import qualified Control.Concurrent.STM.TChan       as TC
+import qualified Control.Concurrent.STM.TVar        as TV
+import           Control.Lens                       (at, at, each, makeLenses, use, view,
+                                                     (.=), (?=), (^..))
+import           Control.Monad                      (forM_, forever, guard, unless, when)
+import           Control.Monad.Base                 (MonadBase)
+import           Control.Monad.Catch                (Exception, MonadCatch,
+                                                     MonadMask (mask), MonadThrow (..),
+                                                     bracket, bracketOnError, catchAll,
+                                                     finally, handleAll, onException,
+                                                     throwM)
+import           Control.Monad.Morph                (hoist)
+import           Control.Monad.Reader               (MonadReader (ask), ReaderT (..))
+import           Control.Monad.State                (StateT (..))
+import           Control.Monad.Trans                (MonadIO (..), lift)
+import           Control.Monad.Trans.Control        (MonadBaseControl (..))
+
+import           Control.Monad.Extra                (whenM)
+import qualified Data.ByteString                    as BS
+import qualified Data.ByteString.Lazy               as BL
+import           Data.Conduit                       (Sink, Source, ($$))
+import           Data.Conduit.Binary                (sinkLbs, sourceLbs)
+import           Data.Conduit.Network               (sinkSocket, sourceSocket)
+import           Data.Conduit.TMChan                (sinkTBMChan, sourceTBMChan)
+import           Data.Default                       (Default (..))
+import           Data.HashMap.Strict                (HashMap)
+import qualified Data.IORef                         as IR
+import           Data.List                          (intersperse)
+import           Data.Streaming.Network             (acceptSafe, bindPortTCP,
+                                                     getSocketFamilyTCP)
+import           Data.Text                          (Text)
+import           Data.Text.Buildable                (Buildable (build), build)
+import           Data.Text.Encoding                 (decodeUtf8)
+import           Data.Typeable                      (Typeable)
+import           Formatting                         (bprint, builder, int, sformat, shown,
+                                                     stext, string, (%))
+import qualified Network.Socket                     as NS
+import           Serokell.Util.Base                 (inCurrentContext)
+import           Serokell.Util.Concurrent           (modifyTVarS)
+import           System.Wlog                        (CanLog, HasLoggerName, LoggerNameBox,
+                                                     Severity (..), WithLogger, logDebug,
+                                                     logInfo, logMessage, logWarning)
+
+import           Control.TimeWarp.Manager           (InterruptType (..), JobCurator (..),
+                                                     addManagerAsJob, addSafeThreadJob,
+                                                     addThreadJob, interruptAllJobs,
+                                                     isInterrupted, jcIsClosed,
+                                                     mkJobCurator, stopAllJobs,
+                                                     unlessInterrupted)
+import           Control.TimeWarp.Rpc.MonadTransfer (Binding (..), MonadTransfer (..),
+                                                     NetworkAddress, Port,
+                                                     ResponseContext (..), ResponseT,
+                                                     commLog, runResponseT, runResponseT,
+                                                     sendRaw)
+import           Control.TimeWarp.Timed             (Microsecond, MonadTimed, ThreadId,
+                                                     TimedIO, for, fork, fork_, interval,
+                                                     killThread, sec, wait)
+
+-- * Util
+
+logSeverityUnlessClosed :: (WithLogger m, MonadIO m)
+                        => Severity -> JobCurator -> Text -> m ()
+logSeverityUnlessClosed severityIfNotClosed jm msg = do
+    closed <- isInterrupted jm
+    let severity = if closed then severityIfNotClosed else Debug
+    logMessage severity msg
+
+
+-- * Related datatypes
+
+-- ** Exceptions
+
+-- | Error thrown if attempt to listen at already being listened connection is performed.
+data TransferException = AlreadyListeningOutbound Text
+    deriving (Show, Typeable)
+
+instance Exception TransferException
+
+instance Buildable TransferException where
+    build (AlreadyListeningOutbound addr) =
+        bprint ("Already listening at outbound connection to "%stext) addr
+
+-- | Error thrown if peer was detected to close connection.
+data PeerClosedConnection = PeerClosedConnection
+    deriving (Show, Typeable)
+
+instance Exception PeerClosedConnection
+
+instance Buildable PeerClosedConnection where
+    build _ = "Peer closed connection"
+
+-- ** Connections
+
+-- | Textual representation of peer node. For debugging purposes only.
+type PeerAddr = Text
+
+data OutputConnection s = OutputConnection
+    { outConnSend       :: forall m . (MonadIO m, MonadMask m, WithLogger m)
+                        => Source m BS.ByteString -> m ()
+      -- ^ Function to send all data produced by source
+    , outConnRec        :: forall m . (MonadIO m, MonadMask m, MonadTimed m,
+                                       MonadBaseControl IO m, WithLogger m)
+                        => Sink BS.ByteString (ResponseT s m) () -> m ()
+      -- ^ Function to stark sink-listener, returns synchronous closer
+    , outConnJobCurator :: JobCurator
+      -- ^ Job manager for this connection
+    , outConnAddr       :: PeerAddr
+      -- ^ Address of socket on other side of net
+    , outConnUserState  :: s
+      -- ^ State binded to socket
+    }
+
+
+-- ** Settings
+
+-- | Number of consequent fails while trying to establish connection.
+type FailsInRow = Int
+
+data Settings = Settings
+    { queueSize       :: Int
+    , reconnectPolicy :: forall m . (HasLoggerName m, MonadIO m)
+                      => FailsInRow -> m (Maybe Microsecond)
+    }
+
+-- | Default settings, you can use it like @transferSettings { queueSize = 1 }@
+instance Default Settings where
+    def = Settings
+        { queueSize = 100
+        , reconnectPolicy =
+            \failsInRow -> return $ guard (failsInRow < 3) >> Just (interval 3 sec)
+        }
+
+
+-- ** ConnectionPool
+
+newtype ConnectionPool s = ConnectionPool
+    { _outputConn :: HashMap NetworkAddress (OutputConnection s)
+    }
+
+makeLenses ''ConnectionPool
+
+initConnectionPool :: ConnectionPool s
+initConnectionPool =
+    ConnectionPool
+    { _outputConn = mempty
+    }
+
+-- ** SocketFrame
+
+-- | Keeps data required to implement so-called /lively socket/.
+data SocketFrame s = SocketFrame
+    { sfPeerAddr   :: PeerAddr
+    -- ^ Peer address, for debuging purposes only
+    , sfInBusy     :: TV.TVar Bool
+    -- ^ Whether someone already listens on this socket
+    , sfInChan     :: TBM.TBMChan BS.ByteString
+    -- ^ For incoming packs of bytes
+    , sfOutChan    :: TBM.TBMChan (BL.ByteString, IO ())
+    -- ^ For (packs of bytes to send, notification when bytes passed to socket)
+    , sfJobCurator :: JobCurator
+    -- ^ Job manager, tracks whether lively-socket wasn't closed.
+    , sfUserState  :: s
+    }
+
+mkSocketFrame :: MonadIO m
+              => Settings -> IO s -> PeerAddr -> m (SocketFrame s)
+mkSocketFrame settings mkUserState sfPeerAddr = liftIO $ do
+    sfInBusy     <- TV.newTVarIO False
+    sfInChan     <- TBM.newTBMChanIO (queueSize settings)
+    sfOutChan    <- TBM.newTBMChanIO (queueSize settings)
+    sfJobCurator <- mkJobCurator
+    sfUserState  <- mkUserState
+    return SocketFrame{..}
+
+-- | Makes sender function in terms of @MonadTransfer@ for given `SocketFrame`.
+-- This first extracts ready `Lazy.ByteString` from given source, and then passes it to
+-- sending queue.
+sfSend :: (MonadIO m, WithLogger m)
+       => SocketFrame s -> Source m BS.ByteString -> m ()
+sfSend SocketFrame{..} src = do
+    lbs <- src $$ sinkLbs
+    logQueueState
+    (notifier, awaiter) <- mkMonitor
+    liftIO . atomically . TBM.writeTBMChan sfOutChan $ (lbs, atomically notifier)
+
+    -- wait till data get consumed by socket, but immediatelly quit on socket
+    -- get closed.
+    liftIO . atomically $ do
+        let jm = getJobCurator sfJobCurator
+        closed <- view jcIsClosed <$> TV.readTVar jm
+        unless closed awaiter
+  where
+    -- creates pair (@notifier@, @awaiter@), where @awaiter@ blocks thread
+    -- until @notifier@ is called.
+    mkMonitor = do
+        t <- liftIO $ TV.newTVarIO False
+        return ( TV.writeTVar t True
+               , check =<< TV.readTVar t
+               )
+
+    logQueueState = do
+        whenM (liftIO . atomically $ TBM.isFullTBMChan sfOutChan) $
+            commLog . logWarning $
+                sformat ("Send channel for "%shown%" is full") sfPeerAddr
+        whenM (liftIO . atomically $ TBM.isClosedTBMChan sfOutChan) $
+            commLog . logWarning $
+                sformat ("Send channel for "%shown%" is closed, message wouldn't be sent")
+                    sfPeerAddr
+
+-- | Constructs function which allows to infinitelly listen on given `SocketFrame`
+-- in terms of `MonadTransfer`.
+-- Attempt to use this function twice will end with `AlreadyListeningOutbound` error.
+sfReceive :: (MonadIO m, MonadMask m, MonadTimed m, WithLogger m,
+              MonadBaseControl IO m)
+          => SocketFrame s -> Sink BS.ByteString (ResponseT s m) () -> m ()
+sfReceive sf@SocketFrame{..} sink = do
+    busy <- liftIO . atomically $ TV.swapTVar sfInBusy True
+    when busy $ throwM $ AlreadyListeningOutbound sfPeerAddr
+
+    liManager <- mkJobCurator
+    onTimeout <- inCurrentContext logOnInterruptTimeout
+    let interruptType = WithTimeout (interval 3 sec) onTimeout
+    mask $ \unmask -> do
+        addManagerAsJob sfJobCurator interruptType liManager
+        addThreadJob liManager $ unmask $ logOnErr $ do  -- TODO: reconnect on error?
+            (sourceTBMChan sfInChan $$ sink) `runResponseT` sfMkResponseCtx sf
+            logListeningHappilyStopped
+  where
+    logOnErr = handleAll $ \e ->
+        unlessInterrupted sfJobCurator $ do
+            commLog . logWarning $ sformat ("Server error: "%shown) e
+            interruptAllJobs sfJobCurator Plain
+
+    logOnInterruptTimeout = commLog . logDebug $
+        sformat ("While closing socket to "%stext%" listener "%
+                 "worked for too long, closing with no regard to it") sfPeerAddr
+
+    logListeningHappilyStopped =
+        commLog . logDebug $
+            sformat ("Listening on socket to "%stext%" happily stopped") sfPeerAddr
+
+sfClose :: SocketFrame s -> IO ()
+sfClose SocketFrame{..} = do
+    interruptAllJobs sfJobCurator Plain
+    atomically $ do
+        TBM.closeTBMChan sfInChan
+        TBM.closeTBMChan sfOutChan
+        clearInChan
+  where
+    clearInChan = TBM.tryReadTBMChan sfInChan >>= maybe (return ()) (const clearInChan)
+
+sfMkOutputConn :: SocketFrame s -> OutputConnection s
+sfMkOutputConn sf =
+    OutputConnection
+    { outConnSend       = sfSend sf
+    , outConnRec        = sfReceive sf
+    , outConnJobCurator = sfJobCurator sf
+    , outConnAddr       = sfPeerAddr sf
+    , outConnUserState  = sfUserState sf
+    }
+
+sfMkResponseCtx :: SocketFrame s -> ResponseContext s
+sfMkResponseCtx sf =
+    ResponseContext
+    { respSend      = sfSend sf
+    , respClose     = sfClose sf
+    , respPeerAddr  = sfPeerAddr sf
+    , respUserState = sfUserState sf
+    }
+
+-- | Starts workers, which connect channels in `SocketFrame` with real `NS.Socket`.
+-- If error in any worker occurs, it's propagated.
+sfProcessSocket :: (MonadIO m, MonadMask m, MonadTimed m, WithLogger m)
+                => SocketFrame s -> NS.Socket -> m ()
+sfProcessSocket SocketFrame{..} sock = do
+    -- TODO: rewrite to async when MonadTimed supports it
+    -- create channel to notify about error
+    eventChan  <- liftIO TC.newTChanIO
+    -- create worker threads
+    stid <- fork $ reportErrors eventChan foreverSend $
+        sformat ("foreverSend on "%stext) sfPeerAddr
+    rtid <- fork $ reportErrors eventChan foreverRec $
+        sformat ("foreverRec on "%stext) sfPeerAddr
+    commLog . logDebug $ sformat ("Start processing of socket to "%stext) sfPeerAddr
+    -- check whether @isClosed@ keeps @True@
+    ctid <- fork $ do
+        let jm = getJobCurator sfJobCurator
+        liftIO . atomically $ check . view jcIsClosed =<< TV.readTVar jm
+        liftIO . atomically $
+            TC.writeTChan eventChan $ Right ()
+        mapM_ killThread [stid, rtid]
+    -- wait for error messages
+    let onError e = do
+            mapM_ killThread [stid, rtid, ctid]
+            throwM e
+    event <- liftIO . atomically $ TC.readTChan eventChan
+    commLog . logDebug $ sformat ("Stop processing socket to "%stext) sfPeerAddr
+    -- Left - worker error, Right - get closed
+    either onError return event
+    -- at this point workers are stopped
+  where
+    foreverSend =
+        mask $ \unmask -> do
+            datm <- liftIO . atomically $ TBM.readTBMChan sfOutChan
+            forM_ datm $
+                \dat@(bs, notif) -> do
+                    let pushback = liftIO . atomically $ TBM.unGetTBMChan sfOutChan dat
+                    unmask (sourceLbs bs $$ sinkSocket sock) `onException` pushback
+                    -- TODO: if get async exception here   ^, will send msg twice
+                    liftIO notif
+                    unmask foreverSend
+
+    foreverRec = do
+        hoist liftIO (sourceSocket sock) $$ sinkTBMChan sfInChan False
+        unlessInterrupted sfJobCurator $
+            throwM PeerClosedConnection
+
+    reportErrors eventChan action desc =
+        action `catchAll` \e -> do
+            commLog . logDebug $ sformat ("Caught error on "%stext%": " % shown) desc e
+            liftIO . atomically . TC.writeTChan eventChan . Left $ e
+
+
+-- * Transfer
+
+newtype Transfer s a = Transfer
+    { getTransfer :: ReaderT Settings
+                        (ReaderT (TV.TVar (ConnectionPool s))
+                            (ReaderT (IO s)
+                                (LoggerNameBox
+                                    TimedIO
+                                )
+                            )
+                        ) a
+    } deriving (Functor, Applicative, Monad, MonadIO, MonadBase IO,
+                MonadThrow, MonadCatch, MonadMask, MonadTimed, CanLog, HasLoggerName)
+
+type instance ThreadId (Transfer s) = C.ThreadId
+
+-- | Run with specified settings.
+runTransferS :: Settings -> IO s -> Transfer s a -> LoggerNameBox TimedIO a
+runTransferS s us t = do
+    m <- liftIO (TV.newTVarIO initConnectionPool)
+    flip runReaderT us $ flip runReaderT m $ flip runReaderT s $
+        getTransfer t
+
+-- | Run `Transfer`, with a way to create initial state for socket.
+runTransfer :: IO s -> Transfer s a -> LoggerNameBox TimedIO a
+runTransfer = runTransferS def
+
+modifyManager :: StateT (ConnectionPool s) STM a -> Transfer s a
+modifyManager how = Transfer . lift $
+    ask >>= liftIO . atomically . flip modifyTVarS how
+
+
+-- * Logic
+
+buildSockAddr :: NS.SockAddr -> PeerAddr
+buildSockAddr (NS.SockAddrInet port host) =
+    let buildHost = mconcat . intersperse "."
+                  . map build . (^.. each) . NS.hostAddressToTuple
+    in  sformat (builder%":"%int) (buildHost host) port
+
+buildSockAddr (NS.SockAddrInet6 port _ host _) =
+    let buildHost6 = mconcat . intersperse "."
+                   . map build . (^.. each) . NS.hostAddress6ToTuple
+    in  sformat (builder%":"%int) (buildHost6 host) port
+
+buildSockAddr (NS.SockAddrUnix addr) = sformat string addr
+
+buildSockAddr (NS.SockAddrCan addr) = sformat ("can:"%int) addr
+
+buildNetworkAddress :: NetworkAddress -> PeerAddr
+buildNetworkAddress (host, port) = sformat (stext%":"%int) (decodeUtf8 host) port
+
+listenInbound :: Port
+              -> Sink BS.ByteString (ResponseT s (Transfer s)) ()
+              -> Transfer s (Transfer s ())
+listenInbound (fromIntegral -> port) sink = do
+    serverJobCurator <- mkJobCurator
+    -- launch server
+    bracketOnError (liftIO $ bindPortTCP port "*") (liftIO . NS.close) $
+        \lsocket -> mask $
+            \unmask -> addThreadJob serverJobCurator $
+                flip finally (liftIO $ NS.close lsocket) . unmask $
+                    handleAll (logOnServerError serverJobCurator) $
+                        serve lsocket serverJobCurator
+    -- return closer
+    inCurrentContext $ do
+        commLog . logDebug $ sformat ("Stopping server at "%int) port
+        stopAllJobs serverJobCurator
+        commLog . logDebug $ sformat ("Server at "%int%" fully stopped") port
+  where
+    serve lsocket serverJobCurator = forever $
+        bracketOnError (liftIO $ acceptSafe lsocket) (liftIO . NS.close . fst) $
+            \(sock, addr) -> mask $
+                \unmask -> fork_ $ do
+                    settings <- Transfer ask
+                    us <- Transfer . lift . lift $ ask
+                    sf@SocketFrame{..} <- mkSocketFrame settings us $ buildSockAddr addr
+                    addManagerAsJob serverJobCurator Plain sfJobCurator
+
+                    logNewInputConnection sfPeerAddr
+                    unmask (processSocket sock sf serverJobCurator)
+                        `finally` liftIO (NS.close sock)
+
+    -- makes socket work, finishes once it's fully shutdown
+    processSocket sock sf@SocketFrame{..} jc = do
+        liftIO $ NS.setSocketOption sock NS.ReuseAddr 1
+
+        sfReceive sf sink
+        unlessInterrupted jc $
+            handleAll (logErrorOnServerSocketProcessing jc sfPeerAddr) $ do
+                sfProcessSocket sf sock
+                logInputConnHappilyClosed sfPeerAddr
+
+    -- * Logs
+
+    logNewInputConnection addr =
+        commLog . logDebug $
+            sformat ("New input connection: "%int%" <- "%stext)
+            port addr
+
+    logErrorOnServerSocketProcessing jm addr e =
+        logSeverityUnlessClosed Warning jm $
+            sformat ("Error in server socket "%int%" connected with "%stext%": "%shown)
+            port addr e
+
+    logOnServerError jm e =
+        logSeverityUnlessClosed Error jm $
+            sformat ("Server at port "%int%" stopped with error "%shown) port e
+
+    logInputConnHappilyClosed addr =
+        commLog . logInfo $
+            sformat ("Happily closing input connection "%int%" <- "%stext)
+            port addr
+
+
+-- | Listens for incoming bytes on outbound connection.
+-- This thread doesn't block current thread. Use returned function to close relevant
+-- connection.
+listenOutbound :: NetworkAddress
+               -> Sink BS.ByteString (ResponseT s (Transfer s)) ()
+               -> Transfer s (Transfer s ())
+listenOutbound addr sink = do
+    conn <- getOutConnOrOpen addr
+    outConnRec conn sink
+    return $ stopAllJobs $ outConnJobCurator conn
+
+
+getOutConnOrOpen :: NetworkAddress -> Transfer s (OutputConnection s)
+getOutConnOrOpen addr@(host, fromIntegral -> port) =
+    mask $
+        \unmask -> do
+            (conn, sfm) <- ensureConnExist
+            forM_ sfm $
+                \sf -> addSafeThreadJob (sfJobCurator sf) $
+                    unmask (startWorker sf) `finally` releaseConn sf
+            return conn
+  where
+    addrName = buildNetworkAddress addr
+
+    ensureConnExist = do
+        settings <- Transfer ask
+        let getOr m act = maybe act (return . (, Nothing)) m
+
+        -- two-phase connection creation
+        -- 1. check whether connection already exists: if doesn't, make `SocketFrame`.
+        -- 2. check again, if still absent push connection to pool
+        mconn <- modifyManager $ use $ outputConn . at addr
+        getOr mconn $ do
+            us <- Transfer . lift . lift $ ask
+            sf <- mkSocketFrame settings us addrName
+            let conn = sfMkOutputConn sf
+            modifyManager $ do
+                mres <- use $ outputConn . at addr
+                getOr mres $ do
+                    outputConn . at addr ?= conn
+                    return (conn, Just sf)
+
+    startWorker sf = do
+        failsInRow <- liftIO $ IR.newIORef 0
+        commLog . logDebug $ sformat ("Lively socket to "%stext%" created, processing")
+            (sfPeerAddr sf)
+        withRecovery sf failsInRow $
+            bracket (liftIO $ fst <$> getSocketFamilyTCP host port NS.AF_UNSPEC)
+                    (liftIO . NS.close) $
+                    \sock -> do
+                        liftIO $ IR.writeIORef failsInRow 0
+                        commLog . logDebug $
+                            sformat ("Established connection to "%stext) (sfPeerAddr sf)
+                        sfProcessSocket sf sock
+
+    withRecovery sf failsInRow action = catchAll action $ \e -> do
+        closed <- isInterrupted (sfJobCurator sf)
+        unless closed $ do
+            commLog . logWarning $
+                sformat ("Error while working with socket to "%stext%": "%shown)
+                    addrName e
+            reconnect <- reconnectPolicy <$> Transfer ask
+            fails <- liftIO $ succ <$> IR.readIORef failsInRow
+            liftIO $ IR.writeIORef failsInRow fails
+            maybeReconnect <- reconnect fails
+            case maybeReconnect of
+                Nothing ->
+                    commLog . logWarning $
+                        sformat ("Can't connect to "%shown%", closing connection") addr
+                Just delay -> do
+                    commLog . logWarning $
+                        sformat ("Reconnect in "%shown) delay
+                    wait (for delay)
+                    withRecovery sf failsInRow action
+
+    releaseConn sf = do
+        interruptAllJobs (sfJobCurator sf) Plain
+        modifyManager $ outputConn . at addr .= Nothing
+        commLog . logDebug $
+            sformat ("Socket to "%stext%" closed") addrName
+
+
+instance MonadTransfer s (Transfer s) where
+    sendRaw addr src = do
+        conn <- getOutConnOrOpen addr
+        outConnSend conn src
+
+    listenRaw (AtPort   port) = listenInbound port
+    listenRaw (AtConnTo addr) = listenOutbound addr
+
+    -- closes asynchronuosly
+    close addr = do
+        maybeConn <- modifyManager . use $ outputConn . at addr
+        forM_ maybeConn $
+            \conn -> interruptAllJobs (outConnJobCurator conn) Plain
+
+    userState addr =
+        outConnUserState <$> getOutConnOrOpen addr
+
+
+-- * Instances
+
+instance MonadBaseControl IO (Transfer s) where
+    type StM (Transfer s) a = StM (LoggerNameBox TimedIO) a
+    liftBaseWith io =
+        Transfer $ liftBaseWith $ \runInBase -> io $ runInBase . getTransfer
+    restoreM = Transfer . restoreM
diff --git a/src/Control/TimeWarp/Timed/MonadTimed.hs b/src/Control/TimeWarp/Timed/MonadTimed.hs
--- a/src/Control/TimeWarp/Timed/MonadTimed.hs
+++ b/src/Control/TimeWarp/Timed/MonadTimed.hs
@@ -4,7 +4,6 @@
 {-# LANGUAGE StandaloneDeriving    #-}
 {-# LANGUAGE TemplateHaskell       #-}
 {-# LANGUAGE TypeFamilies          #-}
-{-# LANGUAGE ViewPatterns          #-}
 
 -- |
 -- Module      : Control.TimeWarp.Timed.MonadTimed
@@ -48,21 +47,20 @@
     , MonadTimedError (..)
     ) where
 
-import           Control.Exception        (AsyncException (ThreadKilled), Exception (..))
-import           Control.Monad            (void)
-import           Control.Monad.Catch      (MonadThrow)
-import           Control.Monad.Reader     (ReaderT (..), ask, runReaderT)
-import           Control.Monad.State      (StateT, evalStateT, get)
-import           Control.Monad.Trans      (MonadIO, lift, liftIO)
-
-import           Data.Monoid              ((<>))
-import           Data.Text                (Text)
-import           Data.Text.Buildable      (Buildable (build))
-import           Data.Time.Units          (Microsecond, Millisecond, Minute, Second,
-                                           TimeUnit (..), convertUnit)
-import           Data.Typeable            (Typeable)
+import           Control.Exception    (AsyncException (ThreadKilled), Exception (..))
+import           Control.Monad        (void)
+import           Control.Monad.Catch  (MonadThrow)
+import           Control.Monad.Reader (ReaderT (..), ask, runReaderT)
+import           Control.Monad.State  (StateT, evalStateT, get)
+import           Control.Monad.Trans  (MonadIO, lift, liftIO)
 
-import           Control.TimeWarp.Logging (LoggerNameBox (..))
+import           Data.Monoid          ((<>))
+import           Data.Text            (Text)
+import           Data.Text.Buildable  (Buildable (build))
+import           Data.Time.Units      (Microsecond, Millisecond, Minute, Second,
+                                       TimeUnit (..), convertUnit)
+import           Data.Typeable        (Typeable)
+import           System.Wlog          (LoggerNameBox (..))
 
 -- | Defines some time point basing on current virtual time.
 type RelativeToNow = Microsecond -> Microsecond
@@ -110,6 +108,9 @@
     -- | Acquires virtual time.
     virtualTime :: m Microsecond
 
+    -- | Acquires (pseudo-)real time.
+    currentTime :: m Microsecond
+
     -- | Waits for specified amount of time.
     --
     -- Use `for` to specify relative virtual time (counting from now),
@@ -136,6 +137,9 @@
     -- if running action exceeds specified time.
     timeout :: TimeUnit t => t -> m a -> m a
 
+    -- | From `slave-thread` library.
+    forkSlave :: m () -> m (ThreadId m)
+
 -- | Type of thread identifier.
 type family ThreadId (m :: * -> *) :: *
 
@@ -206,6 +210,8 @@
 instance MonadTimed m => MonadTimed (ReaderT r m) where
     virtualTime = lift virtualTime
 
+    currentTime = lift currentTime
+
     wait = lift . wait
 
     fork m = lift . fork . runReaderT m =<< ask
@@ -216,11 +222,16 @@
 
     timeout t m = lift . timeout t . runReaderT m =<< ask
 
+    forkSlave m = lift . forkSlave . runReaderT m =<< ask
+
+
 type instance ThreadId (StateT s m) = ThreadId m
 
 instance MonadTimed m => MonadTimed (StateT s m) where
     virtualTime = lift virtualTime
 
+    currentTime = lift currentTime
+
     wait = lift . wait
 
     fork m = lift . fork . evalStateT m =<< get
@@ -231,9 +242,12 @@
 
     timeout t m = lift . timeout t . evalStateT m =<< get
 
-type instance ThreadId (LoggerNameBox m) = ThreadId m
+    forkSlave m = lift . forkSlave . evalStateT m =<< get
 
+
 deriving instance MonadTimed m => MonadTimed (LoggerNameBox m)
+
+type instance ThreadId (LoggerNameBox m) = ThreadId m
 
 -- | Converts a specified time to `Microsecond`.
 mcs, ms, sec, minute, hour :: Int -> Microsecond
diff --git a/src/Control/TimeWarp/Timed/TimedIO.hs b/src/Control/TimeWarp/Timed/TimedIO.hs
--- a/src/Control/TimeWarp/Timed/TimedIO.hs
+++ b/src/Control/TimeWarp/Timed/TimedIO.hs
@@ -23,32 +23,29 @@
 
 import qualified Control.Concurrent                as C
 import           Control.Monad.Base                (MonadBase)
-import           Control.Monad.Catch               (MonadCatch, MonadMask,
-                                                    MonadThrow, throwM)
-import           Control.Monad.Reader              (ReaderT (..), ask,
-                                                    runReaderT)
+import           Control.Monad.Catch               (MonadCatch, MonadMask, MonadThrow,
+                                                    throwM)
+import           Control.Monad.Reader              (ReaderT (..), ask, runReaderT)
 import           Control.Monad.Trans               (MonadIO, lift, liftIO)
-import           Control.Monad.Trans.Control       (MonadBaseControl, StM,
-                                                    liftBaseWith, restoreM)
+import           Control.Monad.Trans.Control       (MonadBaseControl, StM, liftBaseWith,
+                                                    restoreM)
 import           Data.Time.Clock.POSIX             (getPOSIXTime)
 import           Data.Time.Units                   (toMicroseconds)
+import           SlaveThread                       as ST
 import qualified System.Timeout                    as T
+import           System.Wlog                       (CanLog)
 
-import           Control.TimeWarp.Timed.MonadTimed (Microsecond,
-                                                    MonadTimed (..),
-                                                    ThreadId,
-                                                    MonadTimedError
-                                                    (MTTimeoutError))
+import           Control.TimeWarp.Timed.MonadTimed (Microsecond, MonadTimed (..),
+                                                    MonadTimedError (MTTimeoutError),
+                                                    ThreadId)
 
 -- | Default implementation for `IO`, i.e. real mode.
 -- `wait` refers to `Control.Concurrent.threadDelay`,
 -- `fork` refers to `Control.Concurrent.forkIO`, and so on.
 newtype TimedIO a = TimedIO
-    { -- Reader's environment stores the /origin/ point and logger name for
-      -- `WithNamedLogger` instance.
-      getTimedIO :: ReaderT Microsecond IO a
+    { getTimedIO :: ReaderT Microsecond IO a
     } deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch,
-               MonadBase IO, MonadMask)
+               MonadBase IO, MonadMask, CanLog)
 
 instance MonadBaseControl IO TimedIO where
     type StM TimedIO a = a
@@ -62,6 +59,8 @@
 instance MonadTimed TimedIO where
     virtualTime = TimedIO $ (-) <$> lift curTime <*> ask
 
+    currentTime = TimedIO $ lift curTime
+
     wait relativeToNow = do
         cur <- virtualTime
         liftIO $ C.threadDelay $ fromIntegral $ relativeToNow cur - cur
@@ -75,6 +74,8 @@
     timeout (toMicroseconds -> t) (TimedIO action) = TimedIO $ do
         res <- liftIO . T.timeout (fromIntegral t) . runReaderT action =<< ask
         maybe (throwM $ MTTimeoutError "Timeout has exceeded") return res
+
+    forkSlave (TimedIO a) = TimedIO $ lift . ST.fork . runReaderT a =<< ask
 
 -- | Launches scenario using real time and threads.
 runTimedIO :: TimedIO a -> IO a
diff --git a/src/Control/TimeWarp/Timed/TimedT.hs b/src/Control/TimeWarp/Timed/TimedT.hs
--- a/src/Control/TimeWarp/Timed/TimedT.hs
+++ b/src/Control/TimeWarp/Timed/TimedT.hs
@@ -7,7 +7,6 @@
 {-# LANGUAGE TemplateHaskell           #-}
 {-# LANGUAGE TypeFamilies              #-}
 {-# LANGUAGE UndecidableInstances      #-}
-{-# LANGUAGE ViewPatterns              #-}
 
 -- |
 -- Module      : Control.TimeWarp.Timed.TimedT
@@ -30,17 +29,17 @@
                                                     Exception (fromException),
                                                     SomeException (..))
 
-import           Control.Lens                      (makeLenses, use, view, (%=), (%~),
-                                                    (&), (.=), (<&>), (^.), at, (<<.=),
-                                                    (<<+=), (.~))
-import           Control.Monad                     (void, unless)
+import           Control.Lens                      (at, makeLenses, use, view, (%=), (%~),
+                                                    (&), (.=), (.~), (<&>), (<<+=),
+                                                    (<<.=), (^.))
+import           Control.Monad                     (unless, void)
 import           Control.Monad.Catch               (Handler (..), MonadCatch, MonadMask,
                                                     MonadThrow, catch, catchAll, catches,
-                                                    mask, throwM, try, finally,
+                                                    finally, mask, throwM, try,
                                                     uninterruptibleMask)
 import           Control.Monad.Cont                (ContT (..), runContT)
 import           Control.Monad.Loops               (whileM_)
-import           Control.Monad.Reader              (ReaderT (..), ask, runReaderT, local)
+import           Control.Monad.Reader              (ReaderT (..), ask, local, runReaderT)
 import           Control.Monad.State               (MonadState (get, put, state), StateT,
                                                     evalStateT)
 import           Control.Monad.Trans               (MonadIO, MonadTrans, lift, liftIO)
@@ -53,14 +52,14 @@
 import qualified Data.Map                          as M
 import qualified Data.PQueue.Min                   as PQ
 import           Safe                              (fromJustNote)
+import           System.Wlog                       (CanLog, HasLoggerName (..),
+                                                    LoggerName, WithLogger, logDebug,
+                                                    logWarning)
 
-import           Control.TimeWarp.Logging          (WithNamedLogger (..), LoggerName,
-                                                    logDebug, logWarning)
-import           Control.TimeWarp.Timed.MonadTimed (Microsecond,
-                                                    MonadTimed (..),
-                                                    MonadTimedError (MTTimeoutError), for,
-                                                    virtualTime, mcs,
-                                                    timeout, ThreadId, schedule, after)
+import           Control.TimeWarp.Timed.MonadTimed (Microsecond, MonadTimed (..),
+                                                    MonadTimedError (MTTimeoutError),
+                                                    ThreadId, after, for, mcs, schedule,
+                                                    timeout, virtualTime)
 
 -- Summary, `TimedT` (implementation of emulation mode) consists of several
 -- layers (from outer to inner):
@@ -169,17 +168,19 @@
     put = lift . put
     state = lift . state
 
-instance WithNamedLogger (TimedT m) where
+instance HasLoggerName (TimedT m) where
     getLoggerName = TimedT $ view loggerName
 
     modifyLoggerName how = TimedT . local (loggerName %~ how) . unwrapTimedT
 
+instance CanLog m => CanLog (TimedT m) where
+
 newtype ContException = ContException SomeException
     deriving (Show)
 
 instance Exception ContException
 
-instance MonadCatch m => MonadCatch (TimedT m) where
+instance (MonadCatch m) => MonadCatch (TimedT m) where
     catch m handler =
         TimedT $
         ReaderT $
@@ -306,7 +307,7 @@
 isThreadKilled = maybe False (== ThreadKilled) . fromException
 
 threadKilledNotifier
-    :: (MonadIO m, WithNamedLogger m)
+    :: WithLogger m
     => SomeException -> m ()
 threadKilledNotifier e
     | isThreadKilled e = logDebug msg
@@ -316,9 +317,10 @@
 
 type instance ThreadId (TimedT m) = PureThreadId
 
-instance (MonadIO m, MonadThrow m, MonadCatch m) =>
+instance (CanLog m, MonadIO m, MonadThrow m, MonadCatch m) =>
          MonadTimed (TimedT m) where
     virtualTime = TimedT $ use curTime
+    currentTime = virtualTime
     -- | Take note, created thread may be killed by async exception
     --   only when it calls "wait"
     fork act
@@ -330,10 +332,7 @@
         let _threadCtx =
                 ThreadCtx
                 { _threadId   = tid
-                , _handlers   = []
-                   --   [( Handler threadKilledNotifier
-                   --    , contHandler
-                   --    )]
+                , _handlers   = []   -- top-level exceptions are caught below
                 , _loggerName = logName
                 }
             _action = act `catch` threadKilledNotifier
@@ -375,6 +374,7 @@
             (liftIO (readIORef done) >>=) . flip unless $
                 throwTo pid $ MTTimeoutError "Timeout exceeded"
         action' `finally` liftIO (writeIORef done True)
+    forkSlave = undefined
 
 -- | Name which is used by logger (see `WithNamedLogger`) if no other one was specified.
 defaultLoggerName :: LoggerName
diff --git a/test/Test/Control/TimeWarp/Common.hs b/test/Test/Control/TimeWarp/Common.hs
--- a/test/Test/Control/TimeWarp/Common.hs
+++ b/test/Test/Control/TimeWarp/Common.hs
@@ -6,14 +6,14 @@
 
 import           Data.Time.Units                   (TimeUnit, convertUnit,
                                                     fromMicroseconds)
-import           Test.QuickCheck                   (Arbitrary (arbitrary), choose)
 import           System.Random                     (StdGen, mkStdGen)
+import           System.Wlog                       (HasLoggerName (..))
+import           Test.QuickCheck                   (Arbitrary (arbitrary), choose)
 
-import           Control.TimeWarp.Logging          (WithNamedLogger (..))
 import qualified Control.TimeWarp.Timed.MonadTimed as T
 
 
-instance WithNamedLogger IO where
+instance HasLoggerName IO where
     getLoggerName = pure "TimeWarp tests"
 
     modifyLoggerName = const id
diff --git a/test/Test/Control/TimeWarp/Rpc/MonadRpcSpec.hs b/test/Test/Control/TimeWarp/Rpc/MonadRpcSpec.hs
deleted file mode 100644
--- a/test/Test/Control/TimeWarp/Rpc/MonadRpcSpec.hs
+++ /dev/null
@@ -1,143 +0,0 @@
-{-# LANGUAGE ViewPatterns #-}
-
--- | RSCoin.Test.MonadRpc specification
-
-module Test.Control.TimeWarp.Rpc.MonadRpcSpec
-       ( spec
-       ) where
-
-import           Control.Monad.State          (StateT, execStateT, modify)
-import           Network.MessagePack.Server   (ServerT)
-import           Test.Hspec                   (Spec, describe, runIO)
-import           Test.Hspec.QuickCheck        (prop)
-import           Test.QuickCheck              (Property, Testable (property),
-                                               ioProperty)
-import           Test.QuickCheck.Monadic      (PropertyM, assert, monadic, run)
-
-import           Control.TimeWarp.Rpc         (Client (..), Host, MonadRpc (..),
-                                               MsgPackRpc, NetworkAddress,
-                                               Port, PureRpc, call, method,
-                                               runMsgPackRpc, runPureRpc)
-import           Control.TimeWarp.Timed       (for, fork, fork_, killThread, ms,
-                                               wait, Microsecond)
-
-import           Test.Control.TimeWarp.Common ()
-
-spec :: Spec
-spec =
-    describe "MonadRpc" $ do
-        describe "MsgPackRpc" $
-            describe "msgpack-rpc based implementation of RPC layer" $ do
-                runIO $ runMsgPackRpc (fork_ server)
-                prop "client should be able to execute server method" $
-                    runMsgPackRpcProp serverMethodShouldExecuteSimpleSpec
-        describe "PureRpc" $
-            describe "pure implementation of RPC layer" $
-                prop "client should be able to execute server method" $
-                    runPureRpcProp serverMethodShouldExecuteSimplePureSpec
-
-type MsgPackRpcProp = PropertyM MsgPackRpc
-type PureRpcProp = PureRpc (StateT Bool IO)
-
-assertPure :: Bool -> PureRpcProp ()
-assertPure b = modify (b &&)
-
-runMsgPackRpcProp :: MsgPackRpcProp () -> Property
-runMsgPackRpcProp = monadic $ ioProperty . runMsgPackRpc
-
-runPureRpcProp :: PureRpcProp () -> Property
-runPureRpcProp test =
-    property $
-    \gen ->
-         ioProperty $ execStateT (runPureRpc gen delays test) True
-  where
-    delays :: (Microsecond, Microsecond)
-    delays = (0, 1000)
-
--- TODO: it would be useful to create an instance of Function for Client and Method;
--- see here https://hackage.haskell.org/package/QuickCheck-2.8.2/docs/Test-QuickCheck-Function.html#t:Function
-
-port :: Port
-port = 5000
-
-host :: Host
-host = "127.0.0.1"
-
-addr :: NetworkAddress
-addr = (host, port)
-
-serverMethodShouldExecuteSimpleSpec :: PropertyM MsgPackRpc ()
-serverMethodShouldExecuteSimpleSpec = client
-
-serverMethodShouldExecuteSimplePureSpec
-    :: PureRpcProp ()
-serverMethodShouldExecuteSimplePureSpec = do
-    serverThread <- fork server
-    clientPure
-    killThread serverThread
-
-server :: MonadRpc m => m ()
-server = do
-    let respAdd = add
-        respEcho = echo
-    restrict $ respAdd 0 0
-    restrict $ respEcho ""
-    serve port [method "add" respAdd, method "echo" respEcho]
-  where
-    add
-        :: Monad m
-        => Int -> Int -> ServerT m Int
-    add x y = return $ x + y
-    echo
-        :: Monad m
-        => String -> ServerT m String
-    echo s = return $ "***" ++ s ++ "***"
-
-restrict :: Monad m => ServerT m a -> m ()
-restrict _  =  return ()
-
-client :: PropertyM MsgPackRpc ()
-client = do
-    run $ wait $ for 50 ms
-    r1 <- run $ execClient addr $ addC 123 456
-    assert $ r1 == 123 + 456
-    r2 <- run $ execClient addr $ echoC "hello"
-    assert $ r2 == "***hello***"
-
-clientPure :: PureRpcProp ()
-clientPure = do
-    wait $ for 50 ms
-    r1 <- execClient addr $ addC 123 456
-    assertPure $ r1 == 123 + 456
-    r2 <- execClient addr $ echoC "hello"
-    assertPure $ r2 == "***hello***"
-
-addC :: Int -> Int -> Client Int
-addC = call "add"
-
-echoC :: String -> Client String
-echoC = call "echo"
-
--- TODO: this method triggers some msgpack exceptions
--- | Method should execute if called correctly
--- serverMethodShouldExecuteSpec
---     :: (MonadTimed m, MonadRpc m)
---     => NonEmptyList (NonEmptyList Char)
---     -> PropertyM m ()
--- serverMethodShouldExecuteSpec (getNonEmpty -> methodNames') = do
---     mtds <- createMethods methodNames
---     let methodMap = createMethodMap mtds
---     run . fork $ serve port mtds
---     run . wait $ for 500 ms
---     name <- pick $ elements methodNames
---     res <- run . execClient addr $ call name
---     shouldBe <- run $ fromJust $ M.lookup name methodMap <*> pure []
---     assert $ shouldBe == res
---   where methodNames = nub $ map getNonEmpty methodNames'
---         -- TODO: we wouldn't need to do this if Function was defined
---         createMethods :: Monad m => [String] -> PropertyM m [Method m]
---         createMethods = mapM $ \name -> do
---             res <- toObject <$> pick (arbitrary :: Gen Int)
---             return . Method name . const $ return res
---         createMethodMap :: Monad m => [Method m] -> M.Map String ([Object] -> m Object)
---         createMethodMap = M.fromList . map (\m -> (methodName m, methodBody m))
diff --git a/test/Test/Control/TimeWarp/Timed/ExceptionSpec.hs b/test/Test/Control/TimeWarp/Timed/ExceptionSpec.hs
--- a/test/Test/Control/TimeWarp/Timed/ExceptionSpec.hs
+++ b/test/Test/Control/TimeWarp/Timed/ExceptionSpec.hs
@@ -6,31 +6,30 @@
        ) where
 
 import           Control.Concurrent.STM       (atomically)
-import           Control.Concurrent.STM.TVar  (TVar, modifyTVar, newTVarIO,
-                                               readTVarIO)
+import           Control.Concurrent.STM.TVar  (TVar, modifyTVar, newTVarIO, readTVarIO)
 import           Control.Exception.Base       (ArithException (Overflow),
                                                AsyncException (ThreadKilled),
                                                SomeException (..))
 import           Control.Monad.Catch          (catch, catchAll, throwM)
 import           Control.Monad.IO.Class       (liftIO)
 import           Control.Monad.Trans          (MonadIO)
+import           System.Wlog                  (Severity (Error), initLogging)
 import           Test.Hspec                   (Spec, before, describe)
 import           Test.Hspec.QuickCheck        (prop)
 import           Test.QuickCheck              (NonNegative (..), Property)
 import           Test.QuickCheck.Monadic      (monadicIO)
-import           Test.QuickCheck.Property     (Result (reason), failed,
-                                               ioProperty, succeeded)
+import           Test.QuickCheck.Property     (Result (reason), failed, ioProperty,
+                                               succeeded)
 
-import           Control.TimeWarp.Logging     (Severity (Error), initLogging)
-import           Control.TimeWarp.Timed       (Microsecond, TimedT, after,
-                                               fork_, fork, invoke, runTimedT,
-                                               sec, wait, for, throwTo)
+import           Control.TimeWarp.Timed       (Microsecond, TimedT, after, for, fork,
+                                               fork_, invoke, runTimedT, sec, throwTo,
+                                               wait)
 
 import           Test.Control.TimeWarp.Common ()
 
 spec :: Spec
 spec =
-    before (initLogging ["dunno"] Error) $
+    before (initLogging Error) $
     describe "WorkMode" $ do
         describe "error" $ do
             prop "should abort the execution"
diff --git a/test/Test/Control/TimeWarp/Timed/MonadTimedSpec.hs b/test/Test/Control/TimeWarp/Timed/MonadTimedSpec.hs
--- a/test/Test/Control/TimeWarp/Timed/MonadTimedSpec.hs
+++ b/test/Test/Control/TimeWarp/Timed/MonadTimedSpec.hs
@@ -141,7 +141,7 @@
 -- TimedIO tests
 
 timeoutProp
-    :: (MonadTimed m, MonadIO m, MonadCatch m)
+    :: (MonadTimed m, MonadCatch m)
     => NonNegative Microsecond
     -> NonNegative Microsecond
     -> PropertyM m ()
diff --git a/time-warp.cabal b/time-warp.cabal
--- a/time-warp.cabal
+++ b/time-warp.cabal
@@ -1,9 +1,8 @@
 name:                time-warp
-version:             0.1.1.2
-synopsis:            distributed systems execution emulation
+version:             1.1.1.0
 homepage:            https://github.com/serokell/time-warp
 bug-reports:         https://github.com/serokell/time-warp/issues
-license:             GPL-3
+license:             MIT
 license-file:        LICENSE
 author:              Serokell
 maintainer:          Serokell <hi@serokell.io>
@@ -17,43 +16,65 @@
                      fast emulation without need to wait for delays and with
                      network nastiness manually controlled.
 
+flag build-executables
+  description:       Build executables
+  default:           False
+  manual:            True
+
 library
-  exposed-modules:     Control.TimeWarp.Logging
+  exposed-modules:     Control.TimeWarp.Manager
+                       Control.TimeWarp.Manager.Job
 
-                     , Control.TimeWarp.Rpc
-                     , Control.TimeWarp.Rpc.MonadRpc
-                     , Control.TimeWarp.Rpc.MsgPackRpc
-                     , Control.TimeWarp.Rpc.PureRpc
-                     , Control.TimeWarp.Rpc.Restriction
+                       Control.TimeWarp.Rpc
+                       Control.TimeWarp.Rpc.Message
+                       Control.TimeWarp.Rpc.MonadDialog
+                       Control.TimeWarp.Rpc.MonadTransfer
+                       Control.TimeWarp.Rpc.Transfer
 
-                     , Control.TimeWarp.Timed
-                     , Control.TimeWarp.Timed.MonadTimed
-                     , Control.TimeWarp.Timed.Misc
-                     , Control.TimeWarp.Timed.TimedIO
-                     , Control.TimeWarp.Timed.TimedT
+                       Control.TimeWarp.Timed
+                       Control.TimeWarp.Timed.MonadTimed
+                       Control.TimeWarp.Timed.Misc
+                       Control.TimeWarp.Timed.TimedIO
+                       Control.TimeWarp.Timed.TimedT
+
   build-depends:       ansi-terminal
+                     , array
+                     , attoparsec >= 0.13
                      , base >= 4.8 && < 5
+                     , binary >= 0.8.3
+                     , binary-conduit >= 1.2.4.1
                      , bytestring >= 0.10.6.0
+                     , conduit >= 1.2.6
+                     , conduit-extra >= 1.1
                      , containers
                      , data-default
                      , data-msgpack >= 0.0.8
+                     , deepseq >= 1.4.1
                      , exceptions
+                     , extra
                      , formatting
-                     , hslogger
+                     , hashable
                      , lens
                      , lifted-base >= 0.2.3
+                     , log-warper  >= 0.2.0
                      , mtl
                      , MonadRandom
                      , monad-loops
                      , monad-control
-                     , network-msgpack-rpc == 0.0.1
+                     , mmorph >= 1.0
+                     , network >= 2.6
                      , pqueue
                      , QuickCheck >= 2.8.1
                      , quickcheck-instances
                      , random >= 1.1
                      , safe
                      , serokell-util >= 0.1.1.1
+                     , semigroups
+                     , slave-thread >= 1.0
                      , stm >= 2.4.4
+                     , stm-chans >= 3.0.0
+                     , stm-conduit >= 3.0
+                     , streaming-commons >= 0.1.15
                      , template-haskell
                      , text >= 1.2.2.0
                      , text-format
@@ -61,19 +82,20 @@
                      , time-units >= 1.0.0
                      , transformers >= 0.4.2.0
                      , transformers-base
+                     , unordered-containers >= 0.2.7
+
   hs-source-dirs:      src
   default-language:    Haskell2010
   ghc-options:         -Wall -fno-warn-orphans
   default-extensions:  RecordWildCards
-                     , OverloadedStrings
-                     , DeriveDataTypeable
-                     , GeneralizedNewtypeDeriving
+                       OverloadedStrings
+                       DeriveDataTypeable
+                       DeriveGeneric
+                       GeneralizedNewtypeDeriving
 
 test-suite time-warp-test
   main-is:             Test.hs
-  other-modules:       Test.Control.TimeWarp.Rpc.MonadRpcSpec
-
-                     , Test.Control.TimeWarp.Timed.ExceptionSpec
+  other-modules:       Test.Control.TimeWarp.Timed.ExceptionSpec
                      , Test.Control.TimeWarp.Timed.MonadTimedSpec
 
                      , Test.Control.TimeWarp.Common
@@ -83,12 +105,12 @@
   build-depends:       async >= 2.0.1
                      , base >= 4.8 && < 5
                      , data-default
-                     , data-msgpack >= 0.0.8
                      , exceptions >= 0.8.2.1
                      , hspec >= 2.1.10
                      , lens >= 4.13
+                     , log-warper >= 0.2.0
+                     , data-msgpack >= 0.0.8
                      , mtl
-                     , network-msgpack-rpc == 0.0.1
                      , QuickCheck >= 2.8.1
                      , serokell-util >= 0.1.1.1
                      , stm >= 2.4.4.1
@@ -106,18 +128,79 @@
                      , DeriveDataTypeable
                      , GeneralizedNewtypeDeriving
 
-executable token-ring
+executable ping-pong
   main-is:             Main.hs
+  build-depends:       base          >= 4.8 && < 5
+                     , binary
+                     , data-default
+                     , exceptions    >= 0.8.2.1
+                     , formatting
+                     , log-warper    >= 0.2.0
+                     , mtl
+                     , serokell-util >= 0.1.1.1
+                     , stm           >= 2.4.4.1
+                     , text          >= 1.2.2.0
+                     , time-warp
+                     , time
+  hs-source-dirs:      examples/ping-pong
+  if flag(build-executables)
+    buildable:         True
+  else
+    buildable:         False
+  default-language:    Haskell2010
+  ghc-options:         -threaded -Wall -fno-warn-orphans
+  default-extensions:  DeriveGeneric
+                       DeriveDataTypeable
+                       GeneralizedNewtypeDeriving
+                       OverloadedStrings
+                       RecordWildCards
+
+executable socket-state
+  main-is:             Main.hs
+  build-depends:       base          >= 4.8 && < 5
+                     , binary
+                     , data-default
+                     , exceptions    >= 0.8.2.1
+                     , formatting
+                     , lens          >= 4.14
+                     , log-warper    >= 0.2.0
+                     , monad-loops   >= 0.4.3
+                     , mtl
+                     , random        >= 1.1
+                     , serokell-util >= 0.1.1.1
+                     , stm           >= 2.4.4.1
+                     , text          >= 1.2.2.0
+                     , time-warp
+                     , time
+  hs-source-dirs:      examples/socket-state
+  if flag(build-executables)
+    buildable:         True
+  else
+    buildable:         False
+  default-language:    Haskell2010
+  ghc-options:         -threaded -Wall -fno-warn-orphans
+  default-extensions:  DeriveGeneric
+                       DeriveDataTypeable
+                       GeneralizedNewtypeDeriving
+                       OverloadedStrings
+                       RecordWildCards
+
+
+executable net-playground
+  main-is:             Main.hs
   build-depends:       async >= 2.0.1
                      , base >= 4.8 && < 5
+                     , binary >= 0.8.3
+                     , binary-conduit >= 1.2.4.1
+                     , conduit >= 1.2.6
                      , data-default
-                     , data-msgpack >= 0.0.8
                      , exceptions >= 0.8.2.1
                      , formatting
                      , hspec >= 2.1.10
                      , lens >= 4.13
-                     , network-msgpack-rpc == 0.0.1
+                     , log-warper >= 0.2.0
                      , MonadRandom
+                     , data-msgpack >= 0.0.8
                      , mtl
                      , QuickCheck >= 2.8.1
                      , serokell-util >= 0.1.1.1
@@ -128,9 +211,127 @@
                      , time-warp
                      , transformers >= 0.4.2.0
                      , random >= 1.1
-  hs-source-dirs:      examples/token-ring
-  default-language:    Haskell2010  
+  hs-source-dirs:      examples/playground
+  default-language:    Haskell2010
   ghc-options:         -threaded -Wall -fno-warn-orphans
+  default-extensions:  OverloadedStrings
+                     , RecordWildCards
+                     , DeriveDataTypeable
+                     , GeneralizedNewtypeDeriving
+
+executable bench-sender
+  main-is:             Main.hs
+  other-modules:       Bench.Network.Commons
+                       SenderOptions
+  build-depends:       async >= 2.1
+                     , attoparsec >= 0.13.1
+                     , base == 4.*
+                     , binary >= 0.8.3
+                     , bytestring >= 0.10.6.0
+                     , data-default >= 0.7
+                     , data-msgpack >= 0.0.8
+                     , directory >= 1.2.6
+                     , exceptions >= 0.8.2.1
+                     , extra >= 1.4
+                     , formatting
+                     , hslogger
+                     , log-warper >= 0.2.0
+                     , monad-control >= 1.0.1
+                     , mtl
+                     , optparse-simple >= 0.0.3
+                     , serokell-util
+                     , random >= 1.1
+                     , text-format >= 0.3.1
+                     , time >= 1.6
+                     , time-units >= 1.0.0
+                     , time-warp
+                     , transformers >= 0.5.2
+                     , unordered-containers >= 0.2.7
+  hs-source-dirs:      bench/Network/Sender
+                     , bench/Network/Common
+  if flag(build-executables)
+    buildable:         True
+  else
+    buildable:         False
+  default-language:    Haskell2010
+  ghc-options:         -threaded -rtsopts -with-rtsopts=-N -Wall
+  default-extensions:  OverloadedStrings
+                     , RecordWildCards
+                     , DeriveDataTypeable
+                     , GeneralizedNewtypeDeriving
+
+executable bench-receiver
+  main-is:             Main.hs
+  other-modules:       Bench.Network.Commons
+                       ReceiverOptions
+  build-depends:       attoparsec >= 0.13.1
+                     , base == 4.*
+                     , binary >= 0.8.3
+                     , bytestring >= 0.10.6.0
+                     , data-default >= 0.7
+                     , data-msgpack >= 0.0.8
+                     , directory >= 1.2.6
+                     , exceptions >= 0.8.2.1
+                     , formatting
+                     , hslogger
+                     , log-warper >= 0.2.0
+                     , mtl
+                     , optparse-simple >= 0.0.3
+                     , serokell-util
+                     , text-format >= 0.3.1
+                     , time >= 1.6
+                     , time-units >= 1.0.0
+                     , time-warp
+                     , unordered-containers >= 0.2.7
+  hs-source-dirs:      bench/Network/Receiver
+                     , bench/Network/Common
+  if flag(build-executables)
+    buildable:         True
+  else
+    buildable:         False
+  default-language:    Haskell2010
+  ghc-options:         -threaded -rtsopts -with-rtsopts=-N -Wall
+  default-extensions:  OverloadedStrings
+                     , RecordWildCards
+                     , DeriveDataTypeable
+                     , GeneralizedNewtypeDeriving
+
+executable bench-log-reader
+  main-is:             Main.hs
+  other-modules:       Bench.Network.Commons
+                       LogReaderOptions
+  build-depends:       attoparsec >= 0.13.1
+                     , base == 4.*
+                     , binary >= 0.8.3
+                     , bytestring >= 0.10.6.0
+                     , conduit >= 1.2.7
+                     , conduit-extra >= 1.1.13
+                     , containers >= 0.5.7
+                     , data-default >= 0.7
+                     , data-msgpack >= 0.0.8
+                     , directory >= 1.2.6
+                     , exceptions >= 0.8.2.1
+                     , formatting
+                     , hslogger
+                     , log-warper >= 0.2.0
+                     , lens >= 4.14
+                     , mtl
+                     , optparse-simple >= 0.0.3
+                     , resourcet >= 1.1.7
+                     , text >= 1.2.2
+                     , text-format >= 0.3.1
+                     , time >= 1.6
+                     , time-units >= 1.0.0
+                     , time-warp
+                     , unordered-containers >= 0.2.7
+  hs-source-dirs:      bench/Network/LogReader
+                     , bench/Network/Common
+  if flag(build-executables)
+    buildable:         True
+  else
+    buildable:         False
+  default-language:    Haskell2010
+  ghc-options:         -threaded -Wall
   default-extensions:  OverloadedStrings
                      , RecordWildCards
                      , DeriveDataTypeable
