--- /dev/null
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
--- /dev/null
+btcspy
+
+GPL v3
+David Llewellyn-Jones
+D.Llewellyn-Jones@ljmu.ac.uk
+david@flypig.co.uk
+http://www.flypig.co.uk
+
+
+To use btcspy as a standalone script, open a command window in the
+btcspy folder (you can do this by Shift-Right-Clicking on the folder
+and selecting "Open command window here" from the menu). Then type the
+following
+
+btcspy.ph
+
+For help type
+
+btcspy.ph --help
+
+To use btcspy within a Python program (or in the Python interpreter)
+you can do the following:
+
+import btcspy
+result = btcspy.history()
+print (result)
+
+Note that for this to work, the contents of the btcspy folder has to be
+in the currently selected directory.
+
+For more information, please feel free to contact David
+D.Llewellyn-Jones@ljmu.ac.uk
--- /dev/null
+#!/usr/bin/env python
+#
+# btcspy - electrum client history outputter
+# Copyright (C) 2011 thomasv@gitorious
+# Copyright (C) 2014 David Llewellyn-Jones (david@flypig.co.uk)
+#
+# 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/>.
+
+from decimal import Decimal
+import json
+import optparse
+import os
+import re
+import ast
+import sys
+import time
+import traceback
+import inspect
+
+# use this if you want to include modules from a subforder
+cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"lib")))
+if cmd_subfolder not in sys.path:
+ sys.path.insert(0, cmd_subfolder)
+
+
+import simple_config, wallet
+from simple_config import *
+from commands import *
+from util import print_msg, print_stderr, print_json, set_verbosity
+from wallet import *
+
+is_local = os.path.dirname(os.path.realpath(__file__)) == os.getcwd()
+is_android = 'ANDROID_DATA' in os.environ
+
+#import __builtin__
+#__builtin__.use_local_modules = is_local or is_android
+
+## load local module as electrum
+#if __builtin__.use_local_modules:
+# import imp
+# #imp.load_module('electrum', *imp.find_module('lib'))
+
+#if is_local:
+sys.path.append('lib')
+
+
+#from electrum import SimpleConfig, Wallet, WalletStorage
+#from electrum.util import print_msg, print_stderr, print_json, set_verbosity
+
+# get password routine
+def prompt_password(prompt, confirm=True):
+ import getpass
+ if sys.stdin.isatty():
+ password = getpass.getpass(prompt)
+ if password and confirm:
+ password2 = getpass.getpass("Confirm: ")
+ if password != password2:
+ sys.exit("Error: Passwords do not match.")
+ else:
+ password = raw_input(prompt)
+ if not password:
+ password = None
+ return password
+
+
+def arg_parser():
+ usage = "btcspy [options] command"
+ details = "Outputs a list of Bitcoin transactions in JSON format taken from the Electrum wallet of the current user. It can also be imported into a Python program using 'import btcspy', after which 'btcspy.history()' will return the history as a structure,"
+ parser = optparse.OptionParser(prog=usage, add_help_option=False, description=details)
+
+ parser.add_option("-h", "--help", action="callback", callback=print_help_cb, help="show this help text")
+ parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="show debugging information")
+ parser.add_option("-W", "--password", dest="password", default=None, help="set password for usage with commands (currently only implemented for create command, do not use it for longrunning gui session since the password is visible in /proc)")
+ parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)")
+ return parser
+
+
+def print_help(parser):
+ parser.print_help()
+ print_msg("Type 'btcspy --help' to see the list of options")
+ run_command(known_commands['help'], None)
+ sys.exit(1)
+
+
+def print_help_cb(self, opt, value, parser):
+ print_help(parser)
+
+
+def run_command(cmd, wallet, password=None, args=[]):
+ network = None
+
+ cmd_runner = Commands(wallet)
+ func = getattr(cmd_runner, cmd.name)
+ cmd_runner.password = password
+ try:
+ result = func(*args[1:])
+ except Exception:
+ traceback.print_exc(file=sys.stdout)
+ sys.exit(1)
+
+ if type(result) == str:
+ print_msg(result)
+ elif result is not None:
+ print_json(result)
+
+def get_command(cmd, wallet, password=None, args=[]):
+ network = None
+
+ cmd_runner = Commands(wallet)
+ func = getattr(cmd_runner, cmd.name)
+ cmd_runner.password = password
+ try:
+ result = func(*args[1:])
+ except Exception:
+ traceback.print_exc(file=sys.stdout)
+ sys.exit(1)
+
+ return result
+
+
+if __name__ == '__main__':
+
+ parser = arg_parser()
+ options, args = parser.parse_args()
+# if options.wallet_path is None:
+# options.electrum_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'electrum_data')
+
+ config_options = eval(str(options))
+ for k, v in config_options.items():
+ if v is None:
+ config_options.pop(k)
+
+ set_verbosity(config_options.get('verbose'))
+
+ config = SimpleConfig(config_options)
+
+ if len(args) == 0:
+ url = None
+ cmd = 'history'
+ else:
+ cmd = args[0]
+
+ if cmd not in known_commands:
+ cmd = 'help'
+
+ cmd = known_commands[cmd]
+
+ # instanciate wallet for command-line
+ storage = WalletStorage(config)
+
+
+ if cmd.requires_wallet and not storage.file_exists:
+ print_msg("Error: Wallet file not found.")
+ sys.exit(0)
+
+
+ wallet = Wallet(storage)
+
+
+ # commands needing password
+ if cmd.requires_password:
+ if wallet.seed == '':
+ seed = ''
+ password = None
+ elif wallet.use_encryption:
+ password = prompt_password('Password:', False)
+ if not password:
+ print_msg("Error: Password required")
+ sys.exit(1)
+ # check password
+ try:
+ seed = wallet.get_seed(password)
+ except Exception:
+ print_msg("Error: This password does not decode this wallet.")
+ sys.exit(1)
+ else:
+ password = None
+ seed = wallet.get_seed(None)
+ else:
+ password = None
+
+ # add missing arguments, do type conversions
+ if cmd.name == 'help':
+ if len(args) < 2:
+ print_help(parser)
+
+ # check the number of arguments
+ argslength = len(args) - 1
+ if argslength < 0:
+ argslength = 0
+
+ if argslength < cmd.min_args:
+ print_msg("Not enough arguments")
+ print_msg("Syntax:", cmd.syntax)
+ sys.exit(1)
+
+ if cmd.max_args >= 0 and argslength > cmd.max_args:
+ print_msg("too many arguments", args)
+ print_msg("Syntax:", cmd.syntax)
+ sys.exit(1)
+
+ if cmd.max_args < 0:
+ if len(args) > cmd.min_args + 1:
+ message = ' '.join(args[cmd.min_args:])
+ print_msg("Warning: Final argument was reconstructed from several arguments:", repr(message))
+ args = args[0:cmd.min_args] + [message]
+
+
+
+ # run the command
+ run_command(cmd, wallet, password, args)
+
+
+ time.sleep(0.1)
+ sys.exit(0)
+
+def history():
+ config = SimpleConfig()
+
+ url = None
+ cmd = 'history'
+
+ cmd = known_commands[cmd]
+
+ # instanciate wallet for command-line
+ storage = WalletStorage(config)
+
+
+ if cmd.requires_wallet and not storage.file_exists:
+ print_msg("Error: Wallet file not found.")
+ sys.exit(0)
+
+
+ wallet = Wallet(storage)
+
+ # commands needing password
+ if cmd.requires_password:
+ if wallet.seed == '':
+ seed = ''
+ password = None
+ elif wallet.use_encryption:
+ password = prompt_password('Password:', False)
+ if not password:
+ print_msg("Error: Password required")
+ sys.exit(1)
+ # check password
+ try:
+ seed = wallet.get_seed(password)
+ except Exception:
+ print_msg("Error: This password does not decode this wallet.")
+ sys.exit(1)
+ else:
+ password = None
+ seed = wallet.get_seed(None)
+ else:
+ password = None
+
+ # run the command
+ return get_command(cmd, wallet, password)
+
+
+
--- /dev/null
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2013 thomasv@gitorious
+#
+# 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/>.
+
+from bitcoin import *
+from i18n import _
+from transaction import Transaction
+
+
+
+class Account(object):
+ def __init__(self, v):
+ self.addresses = v.get('0', [])
+ self.change = v.get('1', [])
+
+ def dump(self):
+ return {'0':self.addresses, '1':self.change}
+
+ def get_addresses(self, for_change):
+ return self.change[:] if for_change else self.addresses[:]
+
+ def create_new_address(self, for_change):
+ addresses = self.change if for_change else self.addresses
+ n = len(addresses)
+ address = self.get_address( for_change, n)
+ addresses.append(address)
+ print address
+ return address
+
+ def get_address(self, for_change, n):
+ pass
+
+ def get_pubkeys(self, sequence):
+ return [ self.get_pubkey( *sequence )]
+
+ def has_change(self):
+ return True
+
+ def get_name(self, k):
+ return _('Main account')
+
+ def get_keyID(self, *sequence):
+ pass
+
+ def redeem_script(self, *sequence):
+ pass
+
+
+class PendingAccount(Account):
+ def __init__(self, v):
+ self.addresses = [ v['pending'] ]
+ self.change = []
+
+ def has_change(self):
+ return False
+
+ def dump(self):
+ return {'pending':self.addresses[0]}
+
+ def get_name(self, k):
+ return _('Pending account')
+
+
+class ImportedAccount(Account):
+ def __init__(self, d):
+ self.keypairs = d['imported']
+
+ def get_addresses(self, for_change):
+ return [] if for_change else sorted(self.keypairs.keys())
+
+ def get_pubkey(self, *sequence):
+ for_change, i = sequence
+ assert for_change == 0
+ addr = self.get_addresses(0)[i]
+ return self.keypairs[addr][0]
+
+ def get_private_key(self, sequence, wallet, password):
+ from wallet import pw_decode
+ for_change, i = sequence
+ assert for_change == 0
+ address = self.get_addresses(0)[i]
+ pk = pw_decode(self.keypairs[address][1], password)
+ # this checks the password
+ assert address == address_from_private_key(pk)
+ return [pk]
+
+ def has_change(self):
+ return False
+
+ def add(self, address, pubkey, privkey, password):
+ from wallet import pw_encode
+ self.keypairs[address] = (pubkey, pw_encode(privkey, password ))
+
+ def remove(self, address):
+ self.keypairs.pop(address)
+
+ def dump(self):
+ return {'imported':self.keypairs}
+
+ def get_name(self, k):
+ return _('Imported keys')
+
+
+# def update_password(self, old_password, new_password):
+# for k, v in self.keypairs.items():
+# pubkey, a = v
+# b = pw_decode(a, old_password)
+# c = pw_encode(b, new_password)
+# self.keypairs[k] = (pubkey, c)
+
+
+class OldAccount(Account):
+ """ Privatekey(type,n) = Master_private_key + H(n|S|type) """
+
+ def __init__(self, v):
+ self.addresses = v.get(0, [])
+ self.change = v.get(1, [])
+ self.mpk = v['mpk'].decode('hex')
+
+ def dump(self):
+ return {0:self.addresses, 1:self.change}
+
+ @classmethod
+ def mpk_from_seed(klass, seed):
+ curve = SECP256k1
+ secexp = klass.stretch_key(seed)
+ master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
+ master_public_key = master_private_key.get_verifying_key().to_string().encode('hex')
+ return master_public_key
+
+ @classmethod
+ def stretch_key(self,seed):
+ oldseed = seed
+ for i in range(100000):
+ seed = hashlib.sha256(seed + oldseed).digest()
+ return string_to_number( seed )
+
+ def get_sequence(self, for_change, n):
+ return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.mpk ) )
+
+ def get_address(self, for_change, n):
+ pubkey = self.get_pubkey(for_change, n)
+ address = public_key_to_bc_address( pubkey.decode('hex') )
+ return address
+
+ def get_pubkey(self, for_change, n):
+ curve = SECP256k1
+ mpk = self.mpk
+ z = self.get_sequence(for_change, n)
+ master_public_key = ecdsa.VerifyingKey.from_string( mpk, curve = SECP256k1 )
+ pubkey_point = master_public_key.pubkey.point + z*curve.generator
+ public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
+ return '04' + public_key2.to_string().encode('hex')
+
+ def get_private_key_from_stretched_exponent(self, for_change, n, secexp):
+ order = generator_secp256k1.order()
+ secexp = ( secexp + self.get_sequence(for_change, n) ) % order
+ pk = number_to_string( secexp, generator_secp256k1.order() )
+ compressed = False
+ return SecretToASecret( pk, compressed )
+
+
+ def get_private_key(self, sequence, wallet, password):
+ seed = wallet.get_seed(password)
+ self.check_seed(seed)
+ for_change, n = sequence
+ secexp = self.stretch_key(seed)
+ pk = self.get_private_key_from_stretched_exponent(for_change, n, secexp)
+ return [pk]
+
+
+ def check_seed(self, seed):
+ curve = SECP256k1
+ secexp = self.stretch_key(seed)
+ master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
+ master_public_key = master_private_key.get_verifying_key().to_string()
+ if master_public_key != self.mpk:
+ print_error('invalid password (mpk)', self.mpk.encode('hex'), master_public_key.encode('hex'))
+ raise Exception('Invalid password')
+ return True
+
+ def redeem_script(self, sequence):
+ return None
+
+ def get_master_pubkeys(self):
+ return [self.mpk.encode('hex')]
+
+ def get_type(self):
+ return _('Old Electrum format')
+
+ def get_keyID(self, sequence):
+ a, b = sequence
+ return 'old(%s,%d,%d)'%(self.mpk.encode('hex'),a,b)
+
+
+
+class BIP32_Account(Account):
+
+ def __init__(self, v):
+ Account.__init__(self, v)
+ self.xpub = v['xpub']
+
+ def dump(self):
+ d = Account.dump(self)
+ d['xpub'] = self.xpub
+ return d
+
+ def get_address(self, for_change, n):
+ pubkey = self.get_pubkey(for_change, n)
+ address = public_key_to_bc_address( pubkey.decode('hex') )
+ return address
+
+ def first_address(self):
+ return self.get_address(0,0)
+
+ def get_master_pubkeys(self):
+ return [self.xpub]
+
+ def get_pubkey_from_x(self, xpub, for_change, n):
+ _, _, _, c, cK = deserialize_xkey(xpub)
+ for i in [for_change, n]:
+ cK, c = CKD_pub(cK, c, i)
+ return cK.encode('hex')
+
+ def get_pubkeys(self, sequence):
+ return sorted(map(lambda x: self.get_pubkey_from_x(x, *sequence), self.get_master_pubkeys()))
+
+ def get_pubkey(self, for_change, n):
+ return self.get_pubkeys((for_change, n))[0]
+
+
+ def get_private_key(self, sequence, wallet, password):
+ out = []
+ xpubs = self.get_master_pubkeys()
+ roots = [k for k, v in wallet.master_public_keys.iteritems() if v in xpubs]
+ for root in roots:
+ xpriv = wallet.get_master_private_key(root, password)
+ if not xpriv:
+ continue
+ _, _, _, c, k = deserialize_xkey(xpriv)
+ pk = bip32_private_key( sequence, k, c )
+ out.append(pk)
+
+ return out
+
+
+ def redeem_script(self, sequence):
+ return None
+
+ def get_type(self):
+ return _('Standard 1 of 1')
+
+ def get_keyID(self, sequence):
+ s = '/' + '/'.join( map(lambda x:str(x), sequence) )
+ return '&'.join( map(lambda x: 'bip32(%s,%s)'%(x, s), self.get_master_pubkeys() ) )
+
+ def get_name(self, k):
+ name = "Unnamed account"
+ m = re.match("m/(\d+)'", k)
+ if m:
+ num = m.group(1)
+ if num == '0':
+ name = "Main account"
+ else:
+ name = "Account %s"%num
+
+ return name
+
+
+
+class BIP32_Account_2of2(BIP32_Account):
+
+ def __init__(self, v):
+ BIP32_Account.__init__(self, v)
+ self.xpub2 = v['xpub2']
+
+ def dump(self):
+ d = BIP32_Account.dump(self)
+ d['xpub2'] = self.xpub2
+ return d
+
+ def redeem_script(self, sequence):
+ pubkeys = self.get_pubkeys(sequence)
+ return Transaction.multisig_script(pubkeys, 2)
+
+ def get_address(self, for_change, n):
+ address = hash_160_to_bc_address(hash_160(self.redeem_script((for_change, n)).decode('hex')), 5)
+ return address
+
+ def get_master_pubkeys(self):
+ return [self.xpub, self.xpub2]
+
+ def get_type(self):
+ return _('Multisig 2 of 2')
+
+
+class BIP32_Account_2of3(BIP32_Account_2of2):
+
+ def __init__(self, v):
+ BIP32_Account_2of2.__init__(self, v)
+ self.xpub3 = v['xpub3']
+
+ def dump(self):
+ d = BIP32_Account_2of2.dump(self)
+ d['xpub3'] = self.xpub3
+ return d
+
+ def get_master_pubkeys(self):
+ return [self.xpub, self.xpub2, self.xpub3]
+
+ def get_type(self):
+ return _('Multisig 2 of 3')
+
+
+
+
--- /dev/null
+# -*- coding: utf-8 -*-
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2011 thomasv@gitorious
+#
+# 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/>.
+
+import hashlib
+import base64
+import re
+import sys
+import hmac
+
+
+try:
+ import ecdsa
+except ImportError:
+ sys.exit("Error: python-ecdsa does not seem to be installed. Try 'sudo pip install ecdsa'")
+
+try:
+ import aes
+except ImportError:
+ sys.exit("Error: AES does not seem to be installed. Try 'sudo pip install slowaes'")
+
+try:
+ import pbkdf2
+except ImportError:
+ sys.exit("Error: pbkdf2 does not seem to be installed. Try 'sudo pip install pbkdf2'")
+
+
+
+from util import print_error
+
+
+
+# AES encryption
+EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s))
+DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e))
+
+def pw_encode(s, password):
+ if password:
+ secret = Hash(password)
+ return EncodeAES(secret, s.encode("utf8"))
+ else:
+ return s
+
+def pw_decode(s, password):
+ if password is not None:
+ secret = Hash(password)
+ try:
+ d = DecodeAES(secret, s).decode("utf8")
+ except Exception:
+ raise Exception('Invalid password')
+ return d
+ else:
+ return s
+
+
+
+
+
+def rev_hex(s):
+ return s.decode('hex')[::-1].encode('hex')
+
+def int_to_hex(i, length=1):
+ s = hex(i)[2:].rstrip('L')
+ s = "0"*(2*length - len(s)) + s
+ return rev_hex(s)
+
+def var_int(i):
+ # https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
+ if i<0xfd:
+ return int_to_hex(i)
+ elif i<=0xffff:
+ return "fd"+int_to_hex(i,2)
+ elif i<=0xffffffff:
+ return "fe"+int_to_hex(i,4)
+ else:
+ return "ff"+int_to_hex(i,8)
+
+def op_push(i):
+ if i<0x4c:
+ return int_to_hex(i)
+ elif i<0xff:
+ return '4c' + int_to_hex(i)
+ elif i<0xffff:
+ return '4d' + int_to_hex(i,2)
+ else:
+ return '4e' + int_to_hex(i,4)
+
+
+
+def sha256(x):
+ return hashlib.sha256(x).digest()
+
+def Hash(x):
+ if type(x) is unicode: x=x.encode('utf-8')
+ return sha256(sha256(x))
+
+hash_encode = lambda x: x[::-1].encode('hex')
+hash_decode = lambda x: x.decode('hex')[::-1]
+hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
+
+def mnemonic_to_seed(mnemonic, passphrase):
+ from pbkdf2 import PBKDF2
+ import hmac
+ PBKDF2_ROUNDS = 2048
+ return PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64)
+
+from version import SEED_PREFIX
+is_new_seed = lambda x: hmac_sha_512("Seed version", x.encode('utf8')).encode('hex')[0:2].startswith(SEED_PREFIX)
+
+def is_old_seed(seed):
+ import mnemonic
+ words = seed.strip().split()
+ try:
+ mnemonic.mn_decode(words)
+ uses_electrum_words = True
+ except Exception:
+ uses_electrum_words = False
+
+ try:
+ seed.decode('hex')
+ is_hex = (len(seed) == 32)
+ except Exception:
+ is_hex = False
+
+ return is_hex or (uses_electrum_words and len(words) == 12)
+
+
+# pywallet openssl private key implementation
+
+def i2d_ECPrivateKey(pkey, compressed=False):
+ if compressed:
+ key = '3081d30201010420' + \
+ '%064x' % pkey.secret + \
+ 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
+ '%064x' % _p + \
+ '3006040100040107042102' + \
+ '%064x' % _Gx + \
+ '022100' + \
+ '%064x' % _r + \
+ '020101a124032200'
+ else:
+ key = '308201130201010420' + \
+ '%064x' % pkey.secret + \
+ 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
+ '%064x' % _p + \
+ '3006040100040107044104' + \
+ '%064x' % _Gx + \
+ '%064x' % _Gy + \
+ '022100' + \
+ '%064x' % _r + \
+ '020101a144034200'
+
+ return key.decode('hex') + i2o_ECPublicKey(pkey.pubkey, compressed)
+
+def i2o_ECPublicKey(pubkey, compressed=False):
+ # public keys are 65 bytes long (520 bits)
+ # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
+ # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
+ # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
+ if compressed:
+ if pubkey.point.y() & 1:
+ key = '03' + '%064x' % pubkey.point.x()
+ else:
+ key = '02' + '%064x' % pubkey.point.x()
+ else:
+ key = '04' + \
+ '%064x' % pubkey.point.x() + \
+ '%064x' % pubkey.point.y()
+
+ return key.decode('hex')
+
+# end pywallet openssl private key implementation
+
+
+
+############ functions from pywallet #####################
+
+def hash_160(public_key):
+ try:
+ md = hashlib.new('ripemd160')
+ md.update(sha256(public_key))
+ return md.digest()
+ except Exception:
+ import ripemd
+ md = ripemd.new(sha256(public_key))
+ return md.digest()
+
+
+def public_key_to_bc_address(public_key):
+ h160 = hash_160(public_key)
+ return hash_160_to_bc_address(h160)
+
+def hash_160_to_bc_address(h160, addrtype = 0):
+ vh160 = chr(addrtype) + h160
+ h = Hash(vh160)
+ addr = vh160 + h[0:4]
+ return b58encode(addr)
+
+def bc_address_to_hash_160(addr):
+ bytes = b58decode(addr, 25)
+ return ord(bytes[0]), bytes[1:21]
+
+
+__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
+__b58base = len(__b58chars)
+
+def b58encode(v):
+ """ encode v, which is a string of bytes, to base58."""
+
+ long_value = 0L
+ for (i, c) in enumerate(v[::-1]):
+ long_value += (256**i) * ord(c)
+
+ result = ''
+ while long_value >= __b58base:
+ div, mod = divmod(long_value, __b58base)
+ result = __b58chars[mod] + result
+ long_value = div
+ result = __b58chars[long_value] + result
+
+ # Bitcoin does a little leading-zero-compression:
+ # leading 0-bytes in the input become leading-1s
+ nPad = 0
+ for c in v:
+ if c == '\0': nPad += 1
+ else: break
+
+ return (__b58chars[0]*nPad) + result
+
+def b58decode(v, length):
+ """ decode v into a string of len bytes."""
+ long_value = 0L
+ for (i, c) in enumerate(v[::-1]):
+ long_value += __b58chars.find(c) * (__b58base**i)
+
+ result = ''
+ while long_value >= 256:
+ div, mod = divmod(long_value, 256)
+ result = chr(mod) + result
+ long_value = div
+ result = chr(long_value) + result
+
+ nPad = 0
+ for c in v:
+ if c == __b58chars[0]: nPad += 1
+ else: break
+
+ result = chr(0)*nPad + result
+ if length is not None and len(result) != length:
+ return None
+
+ return result
+
+
+def EncodeBase58Check(vchIn):
+ hash = Hash(vchIn)
+ return b58encode(vchIn + hash[0:4])
+
+def DecodeBase58Check(psz):
+ vchRet = b58decode(psz, None)
+ key = vchRet[0:-4]
+ csum = vchRet[-4:]
+ hash = Hash(key)
+ cs32 = hash[0:4]
+ if cs32 != csum:
+ return None
+ else:
+ return key
+
+def PrivKeyToSecret(privkey):
+ return privkey[9:9+32]
+
+def SecretToASecret(secret, compressed=False, addrtype=0):
+ vchIn = chr((addrtype+128)&255) + secret
+ if compressed: vchIn += '\01'
+ return EncodeBase58Check(vchIn)
+
+def ASecretToSecret(key, addrtype=0):
+ vch = DecodeBase58Check(key)
+ if vch and vch[0] == chr((addrtype+128)&255):
+ return vch[1:]
+ else:
+ return False
+
+def regenerate_key(sec):
+ b = ASecretToSecret(sec)
+ if not b:
+ return False
+ b = b[0:32]
+ return EC_KEY(b)
+
+def GetPubKey(pubkey, compressed=False):
+ return i2o_ECPublicKey(pubkey, compressed)
+
+def GetPrivKey(pkey, compressed=False):
+ return i2d_ECPrivateKey(pkey, compressed)
+
+def GetSecret(pkey):
+ return ('%064x' % pkey.secret).decode('hex')
+
+def is_compressed(sec):
+ b = ASecretToSecret(sec)
+ return len(b) == 33
+
+
+def public_key_from_private_key(sec):
+ # rebuild public key from private key, compressed or uncompressed
+ pkey = regenerate_key(sec)
+ assert pkey
+ compressed = is_compressed(sec)
+ public_key = GetPubKey(pkey.pubkey, compressed)
+ return public_key.encode('hex')
+
+
+def address_from_private_key(sec):
+ public_key = public_key_from_private_key(sec)
+ address = public_key_to_bc_address(public_key.decode('hex'))
+ return address
+
+
+def is_valid(addr):
+ return is_address(addr)
+
+
+def is_address(addr):
+ ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z')
+ if not ADDRESS_RE.match(addr): return False
+ try:
+ addrtype, h = bc_address_to_hash_160(addr)
+ except Exception:
+ return False
+ return addr == hash_160_to_bc_address(h, addrtype)
+
+
+def is_private_key(key):
+ try:
+ k = ASecretToSecret(key)
+ return k is not False
+ except:
+ return False
+
+
+########### end pywallet functions #######################
+
+try:
+ from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
+except Exception:
+ print "cannot import ecdsa.curve_secp256k1. You probably need to upgrade ecdsa.\nTry: sudo pip install --upgrade ecdsa"
+ exit()
+
+from ecdsa.curves import SECP256k1
+from ecdsa.ellipticcurve import Point
+from ecdsa.util import string_to_number, number_to_string
+
+def msg_magic(message):
+ varint = var_int(len(message))
+ encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
+ return "\x18Bitcoin Signed Message:\n" + encoded_varint + message
+
+
+def verify_message(address, signature, message):
+ try:
+ EC_KEY.verify_message(address, signature, message)
+ return True
+ except Exception as e:
+ print_error("Verification error: {0}".format(e))
+ return False
+
+
+def encrypt_message(message, pubkey):
+ return EC_KEY.encrypt_message(message, pubkey.decode('hex'))
+
+
+def chunks(l, n):
+ return [l[i:i+n] for i in xrange(0, len(l), n)]
+
+
+def ECC_YfromX(x,curved=curve_secp256k1, odd=True):
+ _p = curved.p()
+ _a = curved.a()
+ _b = curved.b()
+ for offset in range(128):
+ Mx = x + offset
+ My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p
+ My = pow(My2, (_p+1)/4, _p )
+
+ if curved.contains_point(Mx,My):
+ if odd == bool(My&1):
+ return [My,offset]
+ return [_p-My,offset]
+ raise Exception('ECC_YfromX: No Y found')
+
+
+def negative_point(P):
+ return Point( P.curve(), P.x(), -P.y(), P.order() )
+
+
+def point_to_ser(P, comp=True ):
+ if comp:
+ return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex')
+ return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
+
+
+def ser_to_point(Aser):
+ curve = curve_secp256k1
+ generator = generator_secp256k1
+ _r = generator.order()
+ assert Aser[0] in ['\x02','\x03','\x04']
+ if Aser[0] == '\x04':
+ return Point( curve, string_to_number(Aser[1:33]), string_to_number(Aser[33:]), _r )
+ Mx = string_to_number(Aser[1:])
+ return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
+
+
+
+class MyVerifyingKey(ecdsa.VerifyingKey):
+ @classmethod
+ def from_signature(klass, sig, recid, h, curve):
+ """ See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 """
+ from ecdsa import util, numbertheory
+ import msqr
+ curveFp = curve.curve
+ G = curve.generator
+ order = G.order()
+ # extract r,s from signature
+ r, s = util.sigdecode_string(sig, order)
+ # 1.1
+ x = r + (recid/2) * order
+ # 1.3
+ alpha = ( x * x * x + curveFp.a() * x + curveFp.b() ) % curveFp.p()
+ beta = msqr.modular_sqrt(alpha, curveFp.p())
+ y = beta if (beta - recid) % 2 == 0 else curveFp.p() - beta
+ # 1.4 the constructor checks that nR is at infinity
+ R = Point(curveFp, x, y, order)
+ # 1.5 compute e from message:
+ e = string_to_number(h)
+ minus_e = -e % order
+ # 1.6 compute Q = r^-1 (sR - eG)
+ inv_r = numbertheory.inverse_mod(r,order)
+ Q = inv_r * ( s * R + minus_e * G )
+ return klass.from_public_point( Q, curve )
+
+
+class EC_KEY(object):
+ def __init__( self, k ):
+ secret = string_to_number(k)
+ self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
+ self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
+ self.secret = secret
+
+ def get_public_key(self, compressed=True):
+ return point_to_ser(self.pubkey.point, compressed).encode('hex')
+
+ def sign_message(self, message, compressed, address):
+ private_key = ecdsa.SigningKey.from_secret_exponent( self.secret, curve = SECP256k1 )
+ public_key = private_key.get_verifying_key()
+ signature = private_key.sign_digest_deterministic( Hash( msg_magic(message) ), hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string )
+ assert public_key.verify_digest( signature, Hash( msg_magic(message) ), sigdecode = ecdsa.util.sigdecode_string)
+ for i in range(4):
+ sig = base64.b64encode( chr(27 + i + (4 if compressed else 0)) + signature )
+ try:
+ self.verify_message( address, sig, message)
+ return sig
+ except Exception:
+ continue
+ else:
+ raise Exception("error: cannot sign message")
+
+
+ @classmethod
+ def verify_message(self, address, signature, message):
+ sig = base64.b64decode(signature)
+ if len(sig) != 65: raise Exception("Wrong encoding")
+
+ nV = ord(sig[0])
+ if nV < 27 or nV >= 35:
+ raise Exception("Bad encoding")
+ if nV >= 31:
+ compressed = True
+ nV -= 4
+ else:
+ compressed = False
+
+ recid = nV - 27
+ h = Hash( msg_magic(message) )
+ public_key = MyVerifyingKey.from_signature( sig[1:], recid, h, curve = SECP256k1 )
+
+ # check public key
+ public_key.verify_digest( sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
+
+ # check that we get the original signing address
+ addr = public_key_to_bc_address( point_to_ser(public_key.pubkey.point, compressed) )
+ if address != addr:
+ raise Exception("Bad signature")
+
+
+ # ecies encryption/decryption methods; aes-256-cbc is used as the cipher; hmac-sha256 is used as the mac
+
+ @classmethod
+ def encrypt_message(self, message, pubkey):
+
+ pk = ser_to_point(pubkey)
+ if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()):
+ raise Exception('invalid pubkey')
+
+ ephemeral_exponent = number_to_string(ecdsa.util.randrange(pow(2,256)), generator_secp256k1.order())
+ ephemeral = EC_KEY(ephemeral_exponent)
+
+ ecdh_key = (pk * ephemeral.privkey.secret_multiplier).x()
+ ecdh_key = ('%064x' % ecdh_key).decode('hex')
+ key = hashlib.sha512(ecdh_key).digest()
+ key_e, key_m = key[:32], key[32:]
+
+ iv_ciphertext = aes.encryptData(key_e, message)
+
+ ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex')
+ encrypted = 'BIE1' + ephemeral_pubkey + iv_ciphertext
+ mac = hmac.new(key_m, encrypted, hashlib.sha256).digest()
+
+ return base64.b64encode(encrypted + mac)
+
+
+ def decrypt_message(self, encrypted):
+
+ encrypted = base64.b64decode(encrypted)
+
+ if len(encrypted) < 85:
+ raise Exception('invalid ciphertext: length')
+
+ magic = encrypted[:4]
+ ephemeral_pubkey = encrypted[4:37]
+ iv_ciphertext = encrypted[37:-32]
+ mac = encrypted[-32:]
+
+ if magic != 'BIE1':
+ raise Exception('invalid ciphertext: invalid magic bytes')
+
+ try:
+ ephemeral_pubkey = ser_to_point(ephemeral_pubkey)
+ except AssertionError, e:
+ raise Exception('invalid ciphertext: invalid ephemeral pubkey')
+
+ if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, ephemeral_pubkey.x(), ephemeral_pubkey.y()):
+ raise Exception('invalid ciphertext: invalid ephemeral pubkey')
+
+ ecdh_key = (ephemeral_pubkey * self.privkey.secret_multiplier).x()
+ ecdh_key = ('%064x' % ecdh_key).decode('hex')
+ key = hashlib.sha512(ecdh_key).digest()
+ key_e, key_m = key[:32], key[32:]
+ if mac != hmac.new(key_m, encrypted[:-32], hashlib.sha256).digest():
+ raise Exception('invalid ciphertext: invalid mac')
+
+ return aes.decryptData(key_e, iv_ciphertext)
+
+
+###################################### BIP32 ##############################
+
+random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
+BIP32_PRIME = 0x80000000
+
+
+def get_pubkeys_from_secret(secret):
+ # public key
+ private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
+ public_key = private_key.get_verifying_key()
+ K = public_key.to_string()
+ K_compressed = GetPubKey(public_key.pubkey,True)
+ return K, K_compressed
+
+
+# Child private key derivation function (from master private key)
+# k = master private key (32 bytes)
+# c = master chain code (extra entropy for key derivation) (32 bytes)
+# n = the index of the key we want to derive. (only 32 bits will be used)
+# If n is negative (i.e. the 32nd bit is set), the resulting private key's
+# corresponding public key can NOT be determined without the master private key.
+# However, if n is positive, the resulting private key's corresponding
+# public key can be determined without the master private key.
+def CKD_priv(k, c, n):
+ is_prime = n & BIP32_PRIME
+ return _CKD_priv(k, c, rev_hex(int_to_hex(n,4)).decode('hex'), is_prime)
+
+def _CKD_priv(k, c, s, is_prime):
+ import hmac
+ from ecdsa.util import string_to_number, number_to_string
+ order = generator_secp256k1.order()
+ keypair = EC_KEY(k)
+ cK = GetPubKey(keypair.pubkey,True)
+ data = chr(0) + k + s if is_prime else cK + s
+ I = hmac.new(c, data, hashlib.sha512).digest()
+ k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
+ c_n = I[32:]
+ return k_n, c_n
+
+# Child public key derivation function (from public key only)
+# K = master public key
+# c = master chain code
+# n = index of key we want to derive
+# This function allows us to find the nth public key, as long as n is
+# non-negative. If n is negative, we need the master private key to find it.
+def CKD_pub(cK, c, n):
+ if n & BIP32_PRIME: raise
+ return _CKD_pub(cK, c, rev_hex(int_to_hex(n,4)).decode('hex'))
+
+# helper function, callable with arbitrary string
+def _CKD_pub(cK, c, s):
+ import hmac
+ from ecdsa.util import string_to_number, number_to_string
+ order = generator_secp256k1.order()
+ I = hmac.new(c, cK + s, hashlib.sha512).digest()
+ curve = SECP256k1
+ pubkey_point = string_to_number(I[0:32])*curve.generator + ser_to_point(cK)
+ public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
+ c_n = I[32:]
+ cK_n = GetPubKey(public_key.pubkey,True)
+ return cK_n, c_n
+
+
+
+def deserialize_xkey(xkey):
+ xkey = DecodeBase58Check(xkey)
+ assert len(xkey) == 78
+ assert xkey[0:4].encode('hex') in ["0488ade4", "0488b21e"]
+ depth = ord(xkey[4])
+ fingerprint = xkey[5:9]
+ child_number = xkey[9:13]
+ c = xkey[13:13+32]
+ if xkey[0:4].encode('hex') == "0488ade4":
+ K_or_k = xkey[13+33:]
+ else:
+ K_or_k = xkey[13+32:]
+ return depth, fingerprint, child_number, c, K_or_k
+
+
+
+def bip32_root(seed):
+ import hmac
+ seed = seed.decode('hex')
+ I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
+ master_k = I[0:32]
+ master_c = I[32:]
+ K, cK = get_pubkeys_from_secret(master_k)
+ xprv = ("0488ADE4" + "00" + "00000000" + "00000000").decode("hex") + master_c + chr(0) + master_k
+ xpub = ("0488B21E" + "00" + "00000000" + "00000000").decode("hex") + master_c + cK
+ return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
+
+
+
+def bip32_private_derivation(xprv, branch, sequence):
+ depth, fingerprint, child_number, c, k = deserialize_xkey(xprv)
+ assert sequence.startswith(branch)
+ sequence = sequence[len(branch):]
+ for n in sequence.split('/'):
+ if n == '': continue
+ i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
+ parent_k = k
+ k, c = CKD_priv(k, c, i)
+ depth += 1
+
+ _, parent_cK = get_pubkeys_from_secret(parent_k)
+ fingerprint = hash_160(parent_cK)[0:4]
+ child_number = ("%08X"%i).decode('hex')
+ K, cK = get_pubkeys_from_secret(k)
+ xprv = "0488ADE4".decode('hex') + chr(depth) + fingerprint + child_number + c + chr(0) + k
+ xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
+ return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
+
+
+
+def bip32_public_derivation(xpub, branch, sequence):
+ depth, fingerprint, child_number, c, cK = deserialize_xkey(xpub)
+ assert sequence.startswith(branch)
+ sequence = sequence[len(branch):]
+ for n in sequence.split('/'):
+ if n == '': continue
+ i = int(n)
+ parent_cK = cK
+ cK, c = CKD_pub(cK, c, i)
+ depth += 1
+
+ fingerprint = hash_160(parent_cK)[0:4]
+ child_number = ("%08X"%i).decode('hex')
+ xpub = "0488B21E".decode('hex') + chr(depth) + fingerprint + child_number + c + cK
+ return EncodeBase58Check(xpub)
+
+
+
+
+def bip32_private_key(sequence, k, chain):
+ for i in sequence:
+ k, chain = CKD_priv(k, chain, i)
+ return SecretToASecret(k, True)
+
+
+
+
+################################## transactions
+
+MIN_RELAY_TX_FEE = 1000
+
+
+
+import unittest
+class Test_bitcoin(unittest.TestCase):
+
+ def test_crypto(self):
+ for message in ["Chancellor on brink of second bailout for banks", chr(255)*512]:
+ self.do_test_crypto(message)
+
+ def do_test_crypto(self, message):
+ G = generator_secp256k1
+ _r = G.order()
+ pvk = ecdsa.util.randrange( pow(2,256) ) %_r
+
+ Pub = pvk*G
+ pubkey_c = point_to_ser(Pub,True)
+ pubkey_u = point_to_ser(Pub,False)
+ addr_c = public_key_to_bc_address(pubkey_c)
+ addr_u = public_key_to_bc_address(pubkey_u)
+
+ #print "Private key ", '%064x'%pvk
+ eck = EC_KEY(number_to_string(pvk,_r))
+
+ #print "Compressed public key ", pubkey_c.encode('hex')
+ enc = EC_KEY.encrypt_message(message, pubkey_c)
+ dec = eck.decrypt_message(enc)
+ assert dec == message
+
+ #print "Uncompressed public key", pubkey_u.encode('hex')
+ enc2 = EC_KEY.encrypt_message(message, pubkey_u)
+ dec2 = eck.decrypt_message(enc)
+ assert dec2 == message
+
+ signature = eck.sign_message(message, True, addr_c)
+ #print signature
+ EC_KEY.verify_message(addr_c, signature, message)
+
+
+
+ def test_bip32(self):
+ # see https://en.bitcoin.it/wiki/BIP_0032_TestVectors
+ xpub, xprv = self.do_test_bip32("000102030405060708090a0b0c0d0e0f", "m/0'/1/2'/2/1000000000")
+ assert xpub == "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy"
+ assert xprv == "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76"
+
+ xpub, xprv = self.do_test_bip32("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542","m/0/2147483647'/1/2147483646'/2")
+ assert xpub == "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt"
+ assert xprv == "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j"
+
+
+ def do_test_bip32(self, seed, sequence):
+ xprv, xpub = bip32_root(seed)
+ assert sequence[0:2] == "m/"
+ path = 'm'
+ sequence = sequence[2:]
+ for n in sequence.split('/'):
+ child_path = path + '/' + n
+ if n[-1] != "'":
+ xpub2 = bip32_public_derivation(xpub, path, child_path)
+ xprv, xpub = bip32_private_derivation(xprv, path, child_path)
+ if n[-1] != "'":
+ assert xpub == xpub2
+ path = child_path
+
+ return xpub, xprv
+
+
+ def test_aes(self):
+ s = u'\u66f4\u7a33\u5b9a\u7684\u4ea4\u6613\u5e73\u53f0'
+ self.do_test_aes(s, s)
+
+ def do_test_aes(self, s, p):
+ enc = pw_encode(s, p)
+ dec = pw_decode(enc, p)
+ assert dec == s
+
+
+if __name__ == "__main__":
+ unittest.main()
--- /dev/null
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2011 thomasv@gitorious
+#
+# 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/>.
+
+import time
+from util import *
+#from bitcoin import *
+from decimal import Decimal
+#import bitcoin
+#from transaction import Transaction
+
+class Command:
+ def __init__(self, name, min_args, max_args, requires_network, requires_wallet, requires_password, description, syntax = '', options_syntax = ''):
+ self.name = name
+ self.min_args=min_args
+ self.max_args = max_args
+ self.requires_network = requires_network
+ self.requires_wallet = requires_wallet
+ self.requires_password = requires_password
+ self.description = description
+ self.syntax = syntax
+ self.options = options_syntax
+
+known_commands = {}
+def register_command(*args):
+ global known_commands
+ name = args[0]
+ known_commands[name] = Command(*args)
+
+
+
+payto_options = ' --fee, -f: set transaction fee\n --fromaddr, -F: send from address -\n --changeaddr, -c: send change to address'
+listaddr_options = " -a: show all addresses, including change addresses\n -l: include labels in results"
+restore_options = " accepts a seed or master public key."
+mksendmany_syntax = 'mksendmanytx <recipient> <amount> [<recipient> <amount> ...]'
+payto_syntax = "payto <recipient> <amount> [label]\n<recipient> can be a bitcoin address or a label"
+paytomany_syntax = "paytomany <recipient> <amount> [<recipient> <amount> ...]\n<recipient> can be a bitcoin address or a label"
+signmessage_syntax = 'signmessage <address> <message>\nIf you want to lead or end a message with spaces, or want double spaces inside the message make sure you quote the string. I.e. " Hello This is a weird String "'
+verifymessage_syntax = 'verifymessage <address> <signature> <message>\nIf you want to lead or end a message with spaces, or want double spaces inside the message make sure you quote the string. I.e. " Hello This is a weird String "'
+
+
+# command
+# requires_network
+# requires_wallet
+# requires_password
+register_command('history', 0, 0, True, True, False, 'Returns the transaction history of your wallet')
+register_command('help', 0, 1, False, False, False, 'Prints this help')
+
+
+
+
+class Commands:
+
+ def __init__(self, wallet, callback = None):
+ self.wallet = wallet
+ #self.network = network
+ self._callback = callback
+ self.password = None
+
+
+ def _run(self, method, args, password_getter):
+ cmd = known_commands[method]
+ if cmd.requires_password and self.wallet.use_encryption:
+ self.password = apply(password_getter,())
+ f = getattr(self, method)
+ result = f(*args)
+ self.password = None
+ if self._callback:
+ apply(self._callback, ())
+ return result
+
+
+ def help(self, cmd=None):
+ if cmd not in known_commands:
+ print_msg("\nList of commands:", ', '.join(sorted(known_commands)))
+ else:
+ cmd = known_commands[cmd]
+ print_msg(cmd.description)
+ if cmd.syntax: print_msg("Syntax: " + cmd.syntax)
+ if cmd.options: print_msg("options:\n" + cmd.options)
+ return None
+
+
+ def history(self):
+ import datetime
+ balance = 0
+ out = []
+ for item in self.wallet.get_tx_history():
+ tx_hash, conf, is_mine, value, fee, balance, timestamp = item
+ try:
+ time_str = datetime.datetime.fromtimestamp( timestamp).isoformat(' ')[:-3]
+ except Exception:
+ time_str = "----"
+
+ label, is_default_label = self.wallet.get_label(tx_hash)
+
+ out.append({'txid':tx_hash, 'date':"%16s"%time_str, 'label':label, 'value':format_satoshis(value)})
+ return out
+
+
+
+
--- /dev/null
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2012 thomasv@gitorious
+#
+# 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/>.
+
+import gettext, os
+
+if os.path.exists('./locale'):
+ LOCALE_DIR = './locale'
+else:
+ LOCALE_DIR = '/usr/share/locale'
+
+language = gettext.translation('electrum', LOCALE_DIR, fallback = True)
+
+def _(x):
+ global language
+ return language.ugettext(x)
+
+def set_language(x):
+ global language
+ if x: language = gettext.translation('electrum', LOCALE_DIR, fallback = True, languages=[x])
+
+
+languages = {
+ '':_('Default'),
+ 'pt_PT':_('Portuguese'),
+ 'pt_BR':_('Brasilian'),
+ 'cs_CZ':_('Czech'),
+ 'de_DE':_('German'),
+ 'eo_UY':_('Esperanto'),
+ 'en_UK':_('English'),
+ 'es_ES':_('Spanish'),
+ 'fr_FR':_('French'),
+ 'it_IT':_('Italian'),
+ 'ja_JP':_('Japanese'),
+ 'lv_LV':_('Latvian'),
+ 'nl_NL':_('Dutch'),
+ 'ru_RU':_('Russian'),
+ 'sl_SI':_('Slovenian'),
+ 'ta_IN':_('Tamil'),
+ 'vi_VN':_('Vietnamese'),
+ 'zh_CN':_('Chinese')
+ }
--- /dev/null
+import json
+import ast
+import threading
+import os
+
+from util import user_dir, print_error, print_msg
+
+
+config = None
+def get_config():
+ global config
+ return config
+
+def set_config(c):
+ global config
+ config = c
+
+
+class SimpleConfig:
+ """
+The SimpleConfig class is responsible for handling operations involving
+configuration files. The constructor reads and stores the system and
+user configurations from electrum.conf into separate dictionaries within
+a SimpleConfig instance then reads the wallet file.
+"""
+ def __init__(self, options={}):
+ self.lock = threading.Lock()
+
+ # system conf, readonly
+ self.system_config = {}
+ if options.get('portable') is not True:
+ self.read_system_config()
+
+ # command-line options
+ self.options_config = options
+
+ # init path
+ self.init_path()
+
+ # user conf, writeable
+ self.user_config = {}
+ self.read_user_config()
+
+ set_config(self)
+
+
+
+ def init_path(self):
+
+ # Read electrum path in the command line configuration
+ self.path = self.options_config.get('electrum_path')
+
+ # Read electrum path in the system configuration
+ if self.path is None:
+ self.path = self.system_config.get('electrum_path')
+
+ # If not set, use the user's default data directory.
+ if self.path is None:
+ self.path = user_dir()
+
+ # Make directory if it does not yet exist.
+ if not os.path.exists(self.path):
+ os.mkdir(self.path)
+
+ print_error( "electrum directory", self.path)
+
+ # portable wallet: use the same directory for wallet and headers file
+ #if options.get('portable'):
+ # self.wallet_config['blockchain_headers_path'] = os.path.dirname(self.path)
+
+ def set_key(self, key, value, save = True):
+ # find where a setting comes from and save it there
+ if self.options_config.get(key) is not None:
+ print "Warning: not changing '%s' because it was passed as a command-line option"%key
+ return
+
+ elif self.system_config.get(key) is not None:
+ if str(self.system_config[key]) != str(value):
+ print "Warning: not changing '%s' because it was set in the system configuration"%key
+
+ else:
+
+ with self.lock:
+ self.user_config[key] = value
+ if save:
+ self.save_user_config()
+
+
+
+ def get(self, key, default=None):
+
+ out = None
+
+ # 1. command-line options always override everything
+ if self.options_config.has_key(key) and self.options_config.get(key) is not None:
+ out = self.options_config.get(key)
+
+ # 2. user configuration
+ elif self.user_config.has_key(key):
+ out = self.user_config.get(key)
+
+ # 2. system configuration
+ elif self.system_config.has_key(key):
+ out = self.system_config.get(key)
+
+ if out is None and default is not None:
+ out = default
+
+ # try to fix the type
+ if default is not None and type(out) != type(default):
+ import ast
+ try:
+ out = ast.literal_eval(out)
+ except Exception:
+ print "type error for '%s': using default value"%key
+ out = default
+
+ return out
+
+
+ def is_modifiable(self, key):
+ """Check if the config file is modifiable."""
+ if self.options_config.has_key(key):
+ return False
+ elif self.user_config.has_key(key):
+ return True
+ elif self.system_config.has_key(key):
+ return False
+ else:
+ return True
+
+
+ def read_system_config(self):
+ """Parse and store the system config settings in electrum.conf into system_config[]."""
+ name = '/etc/electrum.conf'
+ if os.path.exists(name):
+ try:
+ import ConfigParser
+ except ImportError:
+ print "cannot parse electrum.conf. please install ConfigParser"
+ return
+
+ p = ConfigParser.ConfigParser()
+ p.read(name)
+ try:
+ for k, v in p.items('client'):
+ self.system_config[k] = v
+ except ConfigParser.NoSectionError:
+ pass
+
+
+ def read_user_config(self):
+ """Parse and store the user config settings in electrum.conf into user_config[]."""
+ if not self.path: return
+
+ path = os.path.join(self.path, "config")
+ if os.path.exists(path):
+ try:
+ with open(path, "r") as f:
+ data = f.read()
+ except IOError:
+ return
+ try:
+ d = ast.literal_eval( data ) #parse raw data from reading wallet file
+ except Exception:
+ print_msg("Error: Cannot read config file.")
+ return
+
+ self.user_config = d
+
+
+ def save_user_config(self):
+ if not self.path: return
+
+ path = os.path.join(self.path, "config")
+ s = repr(self.user_config)
+ f = open(path,"w")
+ f.write( s )
+ f.close()
+ if self.get('gui') != 'android':
+ import stat
+ os.chmod(path, stat.S_IREAD | stat.S_IWRITE)
--- /dev/null
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2011 thomasv@gitorious
+#
+# 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/>.
+
+
+# Note: The deserialization code originally comes from ABE.
+
+
+from bitcoin import *
+from util import print_error
+import time
+import struct
+
+#
+# Workalike python implementation of Bitcoin's CDataStream class.
+#
+import struct
+import StringIO
+import mmap
+
+class SerializationError(Exception):
+ """ Thrown when there's a problem deserializing or serializing """
+
+class BCDataStream(object):
+ def __init__(self):
+ self.input = None
+ self.read_cursor = 0
+
+ def clear(self):
+ self.input = None
+ self.read_cursor = 0
+
+ def write(self, bytes): # Initialize with string of bytes
+ if self.input is None:
+ self.input = bytes
+ else:
+ self.input += bytes
+
+ def map_file(self, file, start): # Initialize with bytes from file
+ self.input = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
+ self.read_cursor = start
+
+ def seek_file(self, position):
+ self.read_cursor = position
+
+ def close_file(self):
+ self.input.close()
+
+ def read_string(self):
+ # Strings are encoded depending on length:
+ # 0 to 252 : 1-byte-length followed by bytes (if any)
+ # 253 to 65,535 : byte'253' 2-byte-length followed by bytes
+ # 65,536 to 4,294,967,295 : byte '254' 4-byte-length followed by bytes
+ # ... and the Bitcoin client is coded to understand:
+ # greater than 4,294,967,295 : byte '255' 8-byte-length followed by bytes of string
+ # ... but I don't think it actually handles any strings that big.
+ if self.input is None:
+ raise SerializationError("call write(bytes) before trying to deserialize")
+
+ try:
+ length = self.read_compact_size()
+ except IndexError:
+ raise SerializationError("attempt to read past end of buffer")
+
+ return self.read_bytes(length)
+
+ def write_string(self, string):
+ # Length-encoded as with read-string
+ self.write_compact_size(len(string))
+ self.write(string)
+
+ def read_bytes(self, length):
+ try:
+ result = self.input[self.read_cursor:self.read_cursor+length]
+ self.read_cursor += length
+ return result
+ except IndexError:
+ raise SerializationError("attempt to read past end of buffer")
+
+ return ''
+
+ def read_boolean(self): return self.read_bytes(1)[0] != chr(0)
+ def read_int16(self): return self._read_num('<h')
+ def read_uint16(self): return self._read_num('<H')
+ def read_int32(self): return self._read_num('<i')
+ def read_uint32(self): return self._read_num('<I')
+ def read_int64(self): return self._read_num('<q')
+ def read_uint64(self): return self._read_num('<Q')
+
+ def write_boolean(self, val): return self.write(chr(1) if val else chr(0))
+ def write_int16(self, val): return self._write_num('<h', val)
+ def write_uint16(self, val): return self._write_num('<H', val)
+ def write_int32(self, val): return self._write_num('<i', val)
+ def write_uint32(self, val): return self._write_num('<I', val)
+ def write_int64(self, val): return self._write_num('<q', val)
+ def write_uint64(self, val): return self._write_num('<Q', val)
+
+ def read_compact_size(self):
+ size = ord(self.input[self.read_cursor])
+ self.read_cursor += 1
+ if size == 253:
+ size = self._read_num('<H')
+ elif size == 254:
+ size = self._read_num('<I')
+ elif size == 255:
+ size = self._read_num('<Q')
+ return size
+
+ def write_compact_size(self, size):
+ if size < 0:
+ raise SerializationError("attempt to write size < 0")
+ elif size < 253:
+ self.write(chr(size))
+ elif size < 2**16:
+ self.write('\xfd')
+ self._write_num('<H', size)
+ elif size < 2**32:
+ self.write('\xfe')
+ self._write_num('<I', size)
+ elif size < 2**64:
+ self.write('\xff')
+ self._write_num('<Q', size)
+
+ def _read_num(self, format):
+ (i,) = struct.unpack_from(format, self.input, self.read_cursor)
+ self.read_cursor += struct.calcsize(format)
+ return i
+
+ def _write_num(self, format, num):
+ s = struct.pack(format, num)
+ self.write(s)
+
+#
+# enum-like type
+# From the Python Cookbook, downloaded from http://code.activestate.com/recipes/67107/
+#
+import types, string, exceptions
+
+class EnumException(exceptions.Exception):
+ pass
+
+class Enumeration:
+ def __init__(self, name, enumList):
+ self.__doc__ = name
+ lookup = { }
+ reverseLookup = { }
+ i = 0
+ uniqueNames = [ ]
+ uniqueValues = [ ]
+ for x in enumList:
+ if type(x) == types.TupleType:
+ x, i = x
+ if type(x) != types.StringType:
+ raise EnumException, "enum name is not a string: " + x
+ if type(i) != types.IntType:
+ raise EnumException, "enum value is not an integer: " + i
+ if x in uniqueNames:
+ raise EnumException, "enum name is not unique: " + x
+ if i in uniqueValues:
+ raise EnumException, "enum value is not unique for " + x
+ uniqueNames.append(x)
+ uniqueValues.append(i)
+ lookup[x] = i
+ reverseLookup[i] = x
+ i = i + 1
+ self.lookup = lookup
+ self.reverseLookup = reverseLookup
+ def __getattr__(self, attr):
+ if not self.lookup.has_key(attr):
+ raise AttributeError
+ return self.lookup[attr]
+ def whatis(self, value):
+ return self.reverseLookup[value]
+
+
+# This function comes from bitcointools, bct-LICENSE.txt.
+def long_hex(bytes):
+ return bytes.encode('hex_codec')
+
+# This function comes from bitcointools, bct-LICENSE.txt.
+def short_hex(bytes):
+ t = bytes.encode('hex_codec')
+ if len(t) < 11:
+ return t
+ return t[0:4]+"..."+t[-4:]
+
+
+
+
+def parse_redeemScript(bytes):
+ dec = [ x for x in script_GetOp(bytes.decode('hex')) ]
+
+ # 2 of 2
+ match = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2, opcodes.OP_CHECKMULTISIG ]
+ if match_decoded(dec, match):
+ pubkeys = [ dec[1][1].encode('hex'), dec[2][1].encode('hex') ]
+ return 2, pubkeys
+
+ # 2 of 3
+ match = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_3, opcodes.OP_CHECKMULTISIG ]
+ if match_decoded(dec, match):
+ pubkeys = [ dec[1][1].encode('hex'), dec[2][1].encode('hex'), dec[3][1].encode('hex') ]
+ return 2, pubkeys
+
+
+
+opcodes = Enumeration("Opcodes", [
+ ("OP_0", 0), ("OP_PUSHDATA1",76), "OP_PUSHDATA2", "OP_PUSHDATA4", "OP_1NEGATE", "OP_RESERVED",
+ "OP_1", "OP_2", "OP_3", "OP_4", "OP_5", "OP_6", "OP_7",
+ "OP_8", "OP_9", "OP_10", "OP_11", "OP_12", "OP_13", "OP_14", "OP_15", "OP_16",
+ "OP_NOP", "OP_VER", "OP_IF", "OP_NOTIF", "OP_VERIF", "OP_VERNOTIF", "OP_ELSE", "OP_ENDIF", "OP_VERIFY",
+ "OP_RETURN", "OP_TOALTSTACK", "OP_FROMALTSTACK", "OP_2DROP", "OP_2DUP", "OP_3DUP", "OP_2OVER", "OP_2ROT", "OP_2SWAP",
+ "OP_IFDUP", "OP_DEPTH", "OP_DROP", "OP_DUP", "OP_NIP", "OP_OVER", "OP_PICK", "OP_ROLL", "OP_ROT",
+ "OP_SWAP", "OP_TUCK", "OP_CAT", "OP_SUBSTR", "OP_LEFT", "OP_RIGHT", "OP_SIZE", "OP_INVERT", "OP_AND",
+ "OP_OR", "OP_XOR", "OP_EQUAL", "OP_EQUALVERIFY", "OP_RESERVED1", "OP_RESERVED2", "OP_1ADD", "OP_1SUB", "OP_2MUL",
+ "OP_2DIV", "OP_NEGATE", "OP_ABS", "OP_NOT", "OP_0NOTEQUAL", "OP_ADD", "OP_SUB", "OP_MUL", "OP_DIV",
+ "OP_MOD", "OP_LSHIFT", "OP_RSHIFT", "OP_BOOLAND", "OP_BOOLOR",
+ "OP_NUMEQUAL", "OP_NUMEQUALVERIFY", "OP_NUMNOTEQUAL", "OP_LESSTHAN",
+ "OP_GREATERTHAN", "OP_LESSTHANOREQUAL", "OP_GREATERTHANOREQUAL", "OP_MIN", "OP_MAX",
+ "OP_WITHIN", "OP_RIPEMD160", "OP_SHA1", "OP_SHA256", "OP_HASH160",
+ "OP_HASH256", "OP_CODESEPARATOR", "OP_CHECKSIG", "OP_CHECKSIGVERIFY", "OP_CHECKMULTISIG",
+ "OP_CHECKMULTISIGVERIFY",
+ ("OP_SINGLEBYTE_END", 0xF0),
+ ("OP_DOUBLEBYTE_BEGIN", 0xF000),
+ "OP_PUBKEY", "OP_PUBKEYHASH",
+ ("OP_INVALIDOPCODE", 0xFFFF),
+])
+
+
+def script_GetOp(bytes):
+ i = 0
+ while i < len(bytes):
+ vch = None
+ opcode = ord(bytes[i])
+ i += 1
+ if opcode >= opcodes.OP_SINGLEBYTE_END:
+ opcode <<= 8
+ opcode |= ord(bytes[i])
+ i += 1
+
+ if opcode <= opcodes.OP_PUSHDATA4:
+ nSize = opcode
+ if opcode == opcodes.OP_PUSHDATA1:
+ nSize = ord(bytes[i])
+ i += 1
+ elif opcode == opcodes.OP_PUSHDATA2:
+ (nSize,) = struct.unpack_from('<H', bytes, i)
+ i += 2
+ elif opcode == opcodes.OP_PUSHDATA4:
+ (nSize,) = struct.unpack_from('<I', bytes, i)
+ i += 4
+ vch = bytes[i:i+nSize]
+ i += nSize
+
+ yield (opcode, vch, i)
+
+
+def script_GetOpName(opcode):
+ return (opcodes.whatis(opcode)).replace("OP_", "")
+
+
+def decode_script(bytes):
+ result = ''
+ for (opcode, vch, i) in script_GetOp(bytes):
+ if len(result) > 0: result += " "
+ if opcode <= opcodes.OP_PUSHDATA4:
+ result += "%d:"%(opcode,)
+ result += short_hex(vch)
+ else:
+ result += script_GetOpName(opcode)
+ return result
+
+
+def match_decoded(decoded, to_match):
+ if len(decoded) != len(to_match):
+ return False;
+ for i in range(len(decoded)):
+ if to_match[i] == opcodes.OP_PUSHDATA4 and decoded[i][0] <= opcodes.OP_PUSHDATA4 and decoded[i][0]>0:
+ continue # Opcodes below OP_PUSHDATA4 all just push data onto stack, and are equivalent.
+ if to_match[i] != decoded[i][0]:
+ return False
+ return True
+
+def parse_scriptSig(d, bytes):
+ try:
+ decoded = [ x for x in script_GetOp(bytes) ]
+ except Exception:
+ # coinbase transactions raise an exception
+ print_error("cannot find address in input script", bytes.encode('hex'))
+ return
+
+ # payto_pubkey
+ match = [ opcodes.OP_PUSHDATA4 ]
+ if match_decoded(decoded, match):
+ return
+
+ # non-generated TxIn transactions push a signature
+ # (seventy-something bytes) and then their public key
+ # (65 bytes) onto the stack:
+ match = [ opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4 ]
+ if match_decoded(decoded, match):
+ sig = decoded[0][1].encode('hex')
+ pubkey = decoded[1][1].encode('hex')
+ if sig[-2:] == '01':
+ sig = sig[:-2]
+ d['pubkeys'] = [pubkey]
+ d['signatures'] = {pubkey:sig}
+ d['address'] = public_key_to_bc_address(pubkey.decode('hex'))
+ return
+ else:
+ print_error("cannot find address in input script", bytes.encode('hex'))
+ return
+
+ # p2sh transaction, 2 of n
+ match = [ opcodes.OP_0 ]
+ while len(match) < len(decoded):
+ match.append(opcodes.OP_PUSHDATA4)
+
+ if match_decoded(decoded, match):
+ redeemScript = decoded[-1][1]
+ num = len(match) - 2
+ d['signatures'] = map(lambda x:x[1][:-1].encode('hex'), decoded[1:-1])
+ d['address'] = hash_160_to_bc_address(hash_160(redeemScript), 5)
+ d['redeemScript'] = redeemScript.encode('hex')
+ dec2 = [ x for x in script_GetOp(redeemScript) ]
+ match_2of2 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2, opcodes.OP_CHECKMULTISIG ]
+ match_2of3 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_3, opcodes.OP_CHECKMULTISIG ]
+ if match_decoded(dec2, match_2of2):
+ pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex') ]
+ elif match_decoded(dec2, match_2of3):
+ pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex'), dec2[3][1].encode('hex') ]
+ else:
+ return
+ d['pubkeys'] = pubkeys
+ return
+
+ print_error("cannot find address in input script", bytes.encode('hex'))
+
+
+
+
+def get_address_from_output_script(bytes):
+ decoded = [ x for x in script_GetOp(bytes) ]
+
+ # The Genesis Block, self-payments, and pay-by-IP-address payments look like:
+ # 65 BYTES:... CHECKSIG
+ match = [ opcodes.OP_PUSHDATA4, opcodes.OP_CHECKSIG ]
+ if match_decoded(decoded, match):
+ return True, public_key_to_bc_address(decoded[0][1])
+
+ # Pay-by-Bitcoin-address TxOuts look like:
+ # DUP HASH160 20 BYTES:... EQUALVERIFY CHECKSIG
+ match = [ opcodes.OP_DUP, opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUALVERIFY, opcodes.OP_CHECKSIG ]
+ if match_decoded(decoded, match):
+ return False, hash_160_to_bc_address(decoded[2][1])
+
+ # p2sh
+ match = [ opcodes.OP_HASH160, opcodes.OP_PUSHDATA4, opcodes.OP_EQUAL ]
+ if match_decoded(decoded, match):
+ return False, hash_160_to_bc_address(decoded[1][1],5)
+
+ return False, "(None)"
+
+
+class Transaction:
+
+ def __init__(self, raw):
+ self.raw = raw
+ self.deserialize()
+ self.inputs = self.d['inputs']
+ self.outputs = self.d['outputs']
+ self.outputs = map(lambda x: (x['address'],x['value']), self.outputs)
+ self.locktime = self.d['lockTime']
+
+ def __str__(self):
+ return self.raw
+
+ @classmethod
+ def from_io(klass, inputs, outputs):
+ raw = klass.serialize(inputs, outputs, for_sig = None) # for_sig=-1 means do not sign
+ self = klass(raw)
+ self.inputs = inputs
+ self.outputs = outputs
+ return self
+
+ @classmethod
+ def sweep(klass, privkeys, network, to_address, fee):
+ inputs = []
+ for privkey in privkeys:
+ pubkey = public_key_from_private_key(privkey)
+ address = address_from_private_key(privkey)
+ u = network.synchronous_get([ ('blockchain.address.listunspent',[address])])[0]
+ pay_script = klass.pay_script(address)
+ for item in u:
+ item['scriptPubKey'] = pay_script
+ item['redeemPubkey'] = pubkey
+ item['address'] = address
+ item['prevout_hash'] = item['tx_hash']
+ item['prevout_n'] = item['tx_pos']
+ inputs += u
+
+ if not inputs:
+ return
+
+ total = sum( map(lambda x:int(x.get('value')), inputs) ) - fee
+ outputs = [(to_address, total)]
+ self = klass.from_io(inputs, outputs)
+ self.sign({ pubkey:privkey })
+ return self
+
+ @classmethod
+ def multisig_script(klass, public_keys, num=None):
+ n = len(public_keys)
+ if num is None: num = n
+ # supports only "2 of 2", and "2 of 3" transactions
+ assert num <= n and n in [2,3]
+
+ if num==2:
+ s = '52'
+ elif num == 3:
+ s = '53'
+ else:
+ raise
+
+ for k in public_keys:
+ s += var_int(len(k)/2)
+ s += k
+ if n==2:
+ s += '52'
+ elif n==3:
+ s += '53'
+ else:
+ raise
+ s += 'ae'
+
+ return s
+
+
+ @classmethod
+ def pay_script(self, addr):
+ addrtype, hash_160 = bc_address_to_hash_160(addr)
+ if addrtype == 0:
+ script = '76a9' # op_dup, op_hash_160
+ script += '14' # push 0x14 bytes
+ script += hash_160.encode('hex')
+ script += '88ac' # op_equalverify, op_checksig
+ elif addrtype == 5:
+ script = 'a9' # op_hash_160
+ script += '14' # push 0x14 bytes
+ script += hash_160.encode('hex')
+ script += '87' # op_equal
+ else:
+ raise
+ return script
+
+
+ @classmethod
+ def serialize( klass, inputs, outputs, for_sig = None ):
+
+ push_script = lambda x: op_push(len(x)/2) + x
+ s = int_to_hex(1,4) # version
+ s += var_int( len(inputs) ) # number of inputs
+ for i in range(len(inputs)):
+ txin = inputs[i]
+ s += txin['prevout_hash'].decode('hex')[::-1].encode('hex') # prev hash
+ s += int_to_hex(txin['prevout_n'],4) # prev index
+
+ signatures = txin.get('signatures', {})
+ if for_sig is None and not signatures:
+ script = ''
+
+ elif for_sig is None:
+ pubkeys = txin['pubkeys']
+ sig_list = ''
+ for pubkey in pubkeys:
+ sig = signatures.get(pubkey)
+ if not sig:
+ continue
+ sig = sig + '01'
+ sig_list += push_script(sig)
+
+ if not txin.get('redeemScript'):
+ script = sig_list
+ script += push_script(pubkeys[0])
+ else:
+ script = '00' # op_0
+ script += sig_list
+ redeem_script = klass.multisig_script(pubkeys,2)
+ assert redeem_script == txin.get('redeemScript')
+ script += push_script(redeem_script)
+
+ elif for_sig==i:
+ if txin.get('redeemScript'):
+ script = txin['redeemScript'] # p2sh uses the inner script
+ else:
+ script = txin['scriptPubKey'] # scriptsig
+ else:
+ script = ''
+ s += var_int( len(script)/2 ) # script length
+ s += script
+ s += "ffffffff" # sequence
+
+ s += var_int( len(outputs) ) # number of outputs
+ for output in outputs:
+ addr, amount = output
+ s += int_to_hex( amount, 8) # amount
+ script = klass.pay_script(addr)
+ s += var_int( len(script)/2 ) # script length
+ s += script # script
+ s += int_to_hex(0,4) # lock time
+ if for_sig is not None and for_sig != -1:
+ s += int_to_hex(1, 4) # hash type
+ return s
+
+
+ def tx_for_sig(self,i):
+ return self.serialize(self.inputs, self.outputs, for_sig = i)
+
+
+ def hash(self):
+ return Hash(self.raw.decode('hex') )[::-1].encode('hex')
+
+ def add_signature(self, i, pubkey, sig):
+ txin = self.inputs[i]
+ signatures = txin.get("signatures",{})
+ signatures[pubkey] = sig
+ txin["signatures"] = signatures
+ self.inputs[i] = txin
+ print_error("adding signature for", pubkey)
+ self.raw = self.serialize( self.inputs, self.outputs )
+
+
+ def is_complete(self):
+ for i, txin in enumerate(self.inputs):
+ redeem_script = txin.get('redeemScript')
+ num, redeem_pubkeys = parse_redeemScript(redeem_script) if redeem_script else (1, [txin.get('redeemPubkey')])
+ signatures = txin.get("signatures",{})
+ if len(signatures) == num:
+ continue
+ else:
+ return False
+ return True
+
+
+
+ def sign(self, keypairs):
+ print_error("tx.sign(), keypairs:", keypairs)
+
+ for i, txin in enumerate(self.inputs):
+
+ # if the input is multisig, parse redeem script
+ redeem_script = txin.get('redeemScript')
+ num, redeem_pubkeys = parse_redeemScript(redeem_script) if redeem_script else (1, [txin.get('redeemPubkey')])
+
+ # add pubkeys
+ txin["pubkeys"] = redeem_pubkeys
+ # get list of already existing signatures
+ signatures = txin.get("signatures",{})
+ # continue if this txin is complete
+ if len(signatures) == num:
+ continue
+
+ for_sig = Hash(self.tx_for_sig(i).decode('hex'))
+ for pubkey in redeem_pubkeys:
+ if pubkey in keypairs.keys():
+ # add signature
+ sec = keypairs[pubkey]
+ pkey = regenerate_key(sec)
+ secexp = pkey.secret
+ private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
+ public_key = private_key.get_verifying_key()
+ sig = private_key.sign_digest_deterministic( for_sig, hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_der )
+ assert public_key.verify_digest( sig, for_sig, sigdecode = ecdsa.util.sigdecode_der)
+ self.add_signature(i, pubkey, sig.encode('hex'))
+
+
+ print_error("is_complete", self.is_complete())
+ self.raw = self.serialize( self.inputs, self.outputs )
+
+
+
+ def deserialize(self):
+ vds = BCDataStream()
+ vds.write(self.raw.decode('hex'))
+ d = {}
+ start = vds.read_cursor
+ d['version'] = vds.read_int32()
+ n_vin = vds.read_compact_size()
+ d['inputs'] = []
+ for i in xrange(n_vin):
+ d['inputs'].append(self.parse_input(vds))
+ n_vout = vds.read_compact_size()
+ d['outputs'] = []
+ for i in xrange(n_vout):
+ d['outputs'].append(self.parse_output(vds, i))
+ d['lockTime'] = vds.read_uint32()
+ self.d = d
+ return self.d
+
+
+ def parse_input(self, vds):
+ d = {}
+ prevout_hash = hash_encode(vds.read_bytes(32))
+ prevout_n = vds.read_uint32()
+ scriptSig = vds.read_bytes(vds.read_compact_size())
+ sequence = vds.read_uint32()
+
+ if prevout_hash == '00'*32:
+ d['is_coinbase'] = True
+ else:
+ d['is_coinbase'] = False
+ d['prevout_hash'] = prevout_hash
+ d['prevout_n'] = prevout_n
+ d['sequence'] = sequence
+
+ d['pubkeys'] = []
+ d['signatures'] = {}
+ d['address'] = None
+ if scriptSig:
+ parse_scriptSig(d, scriptSig)
+ return d
+
+
+ def parse_output(self, vds, i):
+ d = {}
+ d['value'] = vds.read_int64()
+ scriptPubKey = vds.read_bytes(vds.read_compact_size())
+ is_pubkey, address = get_address_from_output_script(scriptPubKey)
+ d['is_pubkey'] = is_pubkey
+ d['address'] = address
+ d['scriptPubKey'] = scriptPubKey.encode('hex')
+ d['prevout_n'] = i
+ return d
+
+
+ def add_extra_addresses(self, txlist):
+ for i in self.inputs:
+ if i.get("address") == "(pubkey)":
+ prev_tx = txlist.get(i.get('prevout_hash'))
+ if prev_tx:
+ address, value = prev_tx.outputs[i.get('prevout_n')]
+ print_error("found pay-to-pubkey address:", address)
+ i["address"] = address
+
+
+ def has_address(self, addr):
+ found = False
+ for txin in self.inputs:
+ if addr == txin.get('address'):
+ found = True
+ break
+ for txout in self.outputs:
+ if addr == txout[0]:
+ found = True
+ break
+ return found
+
+
+ def get_value(self, addresses, prevout_values):
+ # return the balance for that tx
+ is_relevant = False
+ is_send = False
+ is_pruned = False
+ is_partial = False
+ v_in = v_out = v_out_mine = 0
+
+ for item in self.inputs:
+ addr = item.get('address')
+ if addr in addresses:
+ is_send = True
+ is_relevant = True
+ key = item['prevout_hash'] + ':%d'%item['prevout_n']
+ value = prevout_values.get( key )
+ if value is None:
+ is_pruned = True
+ else:
+ v_in += value
+ else:
+ is_partial = True
+
+ if not is_send: is_partial = False
+
+ for item in self.outputs:
+ addr, value = item
+ v_out += value
+ if addr in addresses:
+ v_out_mine += value
+ is_relevant = True
+
+ if is_pruned:
+ # some inputs are mine:
+ fee = None
+ if is_send:
+ v = v_out_mine - v_out
+ else:
+ # no input is mine
+ v = v_out_mine
+
+ else:
+ v = v_out_mine - v_in
+
+ if is_partial:
+ # some inputs are mine, but not all
+ fee = None
+ is_send = v < 0
+ else:
+ # all inputs are mine
+ fee = v_out - v_in
+
+ return is_relevant, is_send, v, fee
+
+
+ def get_input_info(self):
+ keys = ['prevout_hash', 'prevout_n', 'address', 'KeyID', 'scriptPubKey', 'redeemScript', 'redeemPubkey', 'pubkeys', 'signatures', 'is_coinbase']
+ info = []
+ for i in self.inputs:
+ item = {}
+ for k in keys:
+ v = i.get(k)
+ if v is not None:
+ item[k] = v
+ info.append(item)
+ return info
+
+
+ def as_dict(self):
+ import json
+ out = {
+ "hex":self.raw,
+ "complete":self.is_complete()
+ }
+
+ if not self.is_complete():
+ input_info = self.get_input_info()
+ out['input_info'] = json.dumps(input_info).replace(' ','')
+
+ return out
+
+
+ def requires_fee(self, verifier):
+ # see https://en.bitcoin.it/wiki/Transaction_fees
+ threshold = 57600000
+ size = len(self.raw)/2
+ if size >= 10000:
+ return True
+
+ for o in self.outputs:
+ value = o[1]
+ if value < 1000000:
+ return True
+ sum = 0
+ for i in self.inputs:
+ age = verifier.get_confirmations(i["prevout_hash"])[0]
+ sum += i["value"] * age
+ priority = sum / size
+ print_error(priority, threshold)
+ return priority < threshold
+
+
+
+ def add_input_info(self, input_info):
+ for i, txin in enumerate(self.inputs):
+ item = input_info[i]
+ txin['scriptPubKey'] = item['scriptPubKey']
+ txin['redeemScript'] = item.get('redeemScript')
+ txin['redeemPubkey'] = item.get('redeemPubkey')
+ txin['KeyID'] = item.get('KeyID')
+ txin['signatures'] = item.get('signatures',{})
--- /dev/null
+import os, sys, re, json
+import platform
+import shutil
+from datetime import datetime
+is_verbose = False
+
+
+class MyEncoder(json.JSONEncoder):
+ def default(self, obj):
+ from transaction import Transaction
+ if isinstance(obj, Transaction):
+ return obj.as_dict()
+ return super(MyEncoder, self).default(obj)
+
+
+def set_verbosity(b):
+ global is_verbose
+ is_verbose = b
+
+
+def print_error(*args):
+ if not is_verbose: return
+ print_stderr(*args)
+
+def print_stderr(*args):
+ args = [str(item) for item in args]
+ sys.stderr.write(" ".join(args) + "\n")
+ sys.stderr.flush()
+
+def print_msg(*args):
+ # Stringify args
+ args = [str(item) for item in args]
+ sys.stdout.write(" ".join(args) + "\n")
+ sys.stdout.flush()
+
+def print_json(obj):
+ try:
+ s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
+ except TypeError:
+ s = repr(obj)
+ sys.stdout.write(s + "\n")
+ sys.stdout.flush()
+
+def user_dir():
+ if "HOME" in os.environ:
+ return os.path.join(os.environ["HOME"], ".electrum")
+ elif "APPDATA" in os.environ:
+ return os.path.join(os.environ["APPDATA"], "Electrum")
+ elif "LOCALAPPDATA" in os.environ:
+ return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
+ elif 'ANDROID_DATA' in os.environ:
+ return "/sdcard/electrum/"
+ else:
+ #raise Exception("No home directory found in environment variables.")
+ return
+
+def appdata_dir():
+ """Find the path to the application data directory; add an electrum folder and return path."""
+ if platform.system() == "Windows":
+ return os.path.join(os.environ["APPDATA"], "Electrum")
+ elif platform.system() == "Linux":
+ return os.path.join(sys.prefix, "share", "electrum")
+ elif (platform.system() == "Darwin" or
+ platform.system() == "DragonFly" or
+ platform.system() == "OpenBSD" or
+ platform.system() == "FreeBSD" or
+ platform.system() == "NetBSD"):
+ return "/Library/Application Support/Electrum"
+ else:
+ raise Exception("Unknown system")
+
+
+def get_resource_path(*args):
+ return os.path.join(".", *args)
+
+
+def local_data_dir():
+ """Return path to the data folder."""
+ assert sys.argv
+ prefix_path = os.path.dirname(sys.argv[0])
+ local_data = os.path.join(prefix_path, "data")
+ return local_data
+
+
+def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False):
+ from decimal import Decimal
+ s = Decimal(x)
+ sign, digits, exp = s.as_tuple()
+ digits = map(str, digits)
+ while len(digits) < decimal_point + 1:
+ digits.insert(0,'0')
+ digits.insert(-decimal_point,'.')
+ s = ''.join(digits).rstrip('0')
+ if sign:
+ s = '-' + s
+ elif is_diff:
+ s = "+" + s
+
+ p = s.find('.')
+ s += "0"*( 1 + num_zeros - ( len(s) - p ))
+ if whitespaces:
+ s += " "*( 1 + decimal_point - ( len(s) - p ))
+ s = " "*( 13 - decimal_point - ( p )) + s
+ return s
+
+
+# Takes a timestamp and returns a string with the approximation of the age
+def age(from_date, since_date = None, target_tz=None, include_seconds=False):
+ if from_date is None:
+ return "Unknown"
+
+ from_date = datetime.fromtimestamp(from_date)
+ if since_date is None:
+ since_date = datetime.now(target_tz)
+
+ distance_in_time = since_date - from_date
+ distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
+ distance_in_minutes = int(round(distance_in_seconds/60))
+
+ if distance_in_minutes <= 1:
+ if include_seconds:
+ for remainder in [5, 10, 20]:
+ if distance_in_seconds < remainder:
+ return "less than %s seconds ago" % remainder
+ if distance_in_seconds < 40:
+ return "half a minute ago"
+ elif distance_in_seconds < 60:
+ return "less than a minute ago"
+ else:
+ return "1 minute ago"
+ else:
+ if distance_in_minutes == 0:
+ return "less than a minute ago"
+ else:
+ return "1 minute ago"
+ elif distance_in_minutes < 45:
+ return "%s minutes ago" % distance_in_minutes
+ elif distance_in_minutes < 90:
+ return "about 1 hour ago"
+ elif distance_in_minutes < 1440:
+ return "about %d hours ago" % (round(distance_in_minutes / 60.0))
+ elif distance_in_minutes < 2880:
+ return "1 day ago"
+ elif distance_in_minutes < 43220:
+ return "%d days ago" % (round(distance_in_minutes / 1440))
+ elif distance_in_minutes < 86400:
+ return "about 1 month ago"
+ elif distance_in_minutes < 525600:
+ return "%d months ago" % (round(distance_in_minutes / 43200))
+ elif distance_in_minutes < 1051200:
+ return "about 1 year ago"
+ else:
+ return "over %d years ago" % (round(distance_in_minutes / 525600))
+
+
+# URL decode
+#_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
+#urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
+
+def parse_URI(uri):
+ import urlparse
+ import bitcoin
+ from decimal import Decimal
+
+ if ':' not in uri:
+ assert bitcoin.is_address(uri)
+ return uri, None, None, None, None
+
+ u = urlparse.urlparse(uri)
+ assert u.scheme == 'bitcoin'
+
+ address = u.path
+ assert bitcoin.is_address(address)
+
+ pq = urlparse.parse_qs(u.query)
+
+ for k, v in pq.items():
+ if len(v)!=1:
+ raise Exception('Duplicate Key', k)
+
+ amount = label = message = request_url = ''
+ if 'amount' in pq:
+ am = pq['amount'][0]
+ m = re.match('([0-9\.]+)X([0-9])', am)
+ if m:
+ k = int(m.group(2)) - 8
+ amount = Decimal(m.group(1)) * pow( Decimal(10) , k)
+ else:
+ amount = Decimal(am) * 100000000
+ if 'message' in pq:
+ message = pq['message'][0]
+ if 'label' in pq:
+ label = pq['label'][0]
+ if 'r' in pq:
+ request_url = pq['r'][0]
+
+ return address, amount, label, message, request_url
+
+
+# Python bug (http://bugs.python.org/issue1927) causes raw_input
+# to be redirected improperly between stdin/stderr on Unix systems
+def raw_input(prompt=None):
+ if prompt:
+ sys.stdout.write(prompt)
+ return builtin_raw_input()
+import __builtin__
+builtin_raw_input = __builtin__.raw_input
+__builtin__.raw_input = raw_input
--- /dev/null
+ELECTRUM_VERSION = "1.9.8" # version of the client package
+PROTOCOL_VERSION = '0.9' # protocol version requested
+NEW_SEED_VERSION = 7 # bip32 wallets
+OLD_SEED_VERSION = 4 # old electrum deterministic generation
+SEED_PREFIX = '01' # the hash of the mnemonic seed must begin with this
--- /dev/null
+#!/usr/bin/env python
+#
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2011 thomasv@gitorious
+#
+# 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/>.
+
+import sys
+import base64
+import os
+import re
+import hashlib
+import copy
+import operator
+import ast
+import threading
+import random
+#import aes
+import Queue
+import time
+import math
+
+from util import print_msg, print_error, format_satoshis
+#from bitcoin import *
+from account import *
+from transaction import Transaction
+#from plugins import run_hook
+#import bitcoin
+#from synchronizer import WalletSynchronizer
+
+COINBASE_MATURITY = 100
+DUST_THRESHOLD = 5430
+
+# internal ID for imported account
+IMPORTED_ACCOUNT = '/x'
+
+
+
+from version import *
+
+
+class WalletStorage:
+
+ def __init__(self, config):
+ self.lock = threading.Lock()
+ self.config = config
+ self.data = {}
+ self.file_exists = False
+ self.path = self.init_path(config)
+ print_error( "wallet path", self.path )
+ if self.path:
+ self.read(self.path)
+
+
+ def init_path(self, config):
+ """Set the path of the wallet."""
+
+ # command line -w option
+ path = config.get('wallet_path')
+ if path:
+ return path
+
+ # path in config file
+ path = config.get('default_wallet_path')
+ if path:
+ return path
+
+ # default path
+ dirpath = os.path.join(config.path, "wallets")
+ if not os.path.exists(dirpath):
+ os.mkdir(dirpath)
+
+ new_path = os.path.join(config.path, "wallets", "default_wallet")
+
+ # default path in pre 1.9 versions
+ old_path = os.path.join(config.path, "electrum.dat")
+ if os.path.exists(old_path) and not os.path.exists(new_path):
+ os.rename(old_path, new_path)
+
+ return new_path
+
+
+ def read(self, path):
+ """Read the contents of the wallet file."""
+ try:
+ with open(self.path, "r") as f:
+ data = f.read()
+ except IOError:
+ return
+ try:
+ d = ast.literal_eval( data ) #parse raw data from reading wallet file
+ except Exception:
+ raise IOError("Cannot read wallet file.")
+
+ self.data = d
+ self.file_exists = True
+
+
+ def get(self, key, default=None):
+ v = self.data.get(key)
+ if v is None:
+ v = default
+ return v
+
+ def put(self, key, value, save = True):
+
+ with self.lock:
+ if value is not None:
+ self.data[key] = value
+ elif key in self.data:
+ self.data.pop(key)
+ if save:
+ self.write()
+
+
+
+class Abstract_Wallet:
+
+ def __init__(self, storage):
+
+ self.storage = storage
+ self.electrum_version = ELECTRUM_VERSION
+ self.gap_limit_for_change = 3 # constant
+ # saved fields
+ self.seed_version = storage.get('seed_version', NEW_SEED_VERSION)
+ self.gap_limit = storage.get('gap_limit', 5)
+ self.use_change = storage.get('use_change',True)
+ self.use_encryption = storage.get('use_encryption', False)
+ self.seed = storage.get('seed', '') # encrypted
+ self.labels = storage.get('labels', {})
+ self.frozen_addresses = storage.get('frozen_addresses',[])
+ self.addressbook = storage.get('contacts', [])
+
+ self.history = storage.get('addr_history',{}) # address -> list(txid, height)
+
+ self.fee = int(storage.get('fee_per_kb', 10000))
+
+ self.master_public_keys = storage.get('master_public_keys',{})
+ self.master_private_keys = storage.get('master_private_keys', {})
+
+ self.next_addresses = storage.get('next_addresses',{})
+
+
+ self.load_accounts()
+
+ self.transactions = {}
+ tx_list = self.storage.get('transactions',{})
+ for k,v in tx_list.items():
+ try:
+ tx = Transaction(v)
+ except Exception:
+ print_msg("Warning: Cannot deserialize transactions. skipping")
+ continue
+
+ self.add_extra_addresses(tx)
+ self.transactions[k] = tx
+
+ for h,tx in self.transactions.items():
+ if not self.check_new_tx(h, tx):
+ print_error("removing unreferenced tx", h)
+ self.transactions.pop(h)
+
+
+ # not saved
+ self.prevout_values = {} # my own transaction outputs
+ self.spent_outputs = []
+
+ # spv
+ self.verifier = None
+
+ # there is a difference between wallet.up_to_date and interface.is_up_to_date()
+ # interface.is_up_to_date() returns true when all requests have been answered and processed
+ # wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
+
+ self.up_to_date = False
+ self.lock = threading.Lock()
+ self.transaction_lock = threading.Lock()
+ self.tx_event = threading.Event()
+
+ for tx_hash, tx in self.transactions.items():
+ self.update_tx_outputs(tx_hash)
+
+
+ def add_extra_addresses(self, tx):
+ h = tx.hash()
+ # find the address corresponding to pay-to-pubkey inputs
+ tx.add_extra_addresses(self.transactions)
+ for o in tx.d.get('outputs'):
+ if o.get('is_pubkey'):
+ for tx2 in self.transactions.values():
+ tx2.add_extra_addresses({h:tx})
+
+
+ def load_accounts(self):
+ self.accounts = {}
+ self.imported_keys = self.storage.get('imported_keys',{})
+
+ d = self.storage.get('accounts', {})
+ for k, v in d.items():
+ if k == 0:
+ v['mpk'] = self.storage.get('master_public_key')
+ self.accounts[k] = OldAccount(v)
+ elif v.get('imported'):
+ self.accounts[k] = ImportedAccount(v)
+ elif v.get('xpub3'):
+ self.accounts[k] = BIP32_Account_2of3(v)
+ elif v.get('xpub2'):
+ self.accounts[k] = BIP32_Account_2of2(v)
+ elif v.get('xpub'):
+ self.accounts[k] = BIP32_Account(v)
+ elif v.get('pending'):
+ self.accounts[k] = PendingAccount(v)
+ else:
+ print_error("cannot load account", v)
+
+
+ def can_create_accounts(self):
+ return False
+
+ def set_up_to_date(self,b):
+ with self.lock: self.up_to_date = b
+
+ def is_up_to_date(self):
+ with self.lock: return self.up_to_date
+
+
+ def update(self):
+ self.up_to_date = False
+ while not self.is_up_to_date():
+ time.sleep(0.1)
+
+ def is_imported(self, addr):
+ account = self.accounts.get(IMPORTED_ACCOUNT)
+ if account:
+ return addr in account.get_addresses(0)
+ else:
+ return False
+
+ def has_imported_keys(self):
+ account = self.accounts.get(IMPORTED_ACCOUNT)
+ return account is not None
+
+ def set_label(self, name, text = None):
+ changed = False
+ old_text = self.labels.get(name)
+ if text:
+ if old_text != text:
+ self.labels[name] = text
+ changed = True
+ else:
+ if old_text:
+ self.labels.pop(name)
+ changed = True
+
+ if changed:
+ self.storage.put('labels', self.labels, True)
+
+ run_hook('set_label', name, text, changed)
+ return changed
+
+ def addresses(self, include_change = True, _next=True):
+ o = []
+ for a in self.accounts.keys():
+ o += self.get_account_addresses(a, include_change)
+
+ if _next:
+ for addr in self.next_addresses.values():
+ if addr not in o:
+ o += [addr]
+ return o
+
+
+ def is_mine(self, address):
+ return address in self.addresses(True)
+
+
+ def is_change(self, address):
+ if not self.is_mine(address): return False
+ acct, s = self.get_address_index(address)
+ if s is None: return False
+ return s[0] == 1
+
+
+ def get_address_index(self, address):
+
+ for account in self.accounts.keys():
+ for for_change in [0,1]:
+ addresses = self.accounts[account].get_addresses(for_change)
+ for addr in addresses:
+ if address == addr:
+ return account, (for_change, addresses.index(addr))
+
+ for k,v in self.next_addresses.items():
+ if v == address:
+ return k, (0,0)
+
+ raise Exception("Address not found", address)
+
+
+ def getpubkeys(self, addr):
+ assert is_valid(addr) and self.is_mine(addr)
+ account, sequence = self.get_address_index(addr)
+ a = self.accounts[account]
+ return a.get_pubkeys( sequence )
+
+
+ def get_private_key(self, address, password):
+ if self.is_watching_only():
+ return []
+ account_id, sequence = self.get_address_index(address)
+ return self.accounts[account_id].get_private_key(sequence, self, password)
+
+
+ def get_public_keys(self, address):
+ account_id, sequence = self.get_address_index(address)
+ return self.accounts[account_id].get_pubkeys(sequence)
+
+
+ def sign_message(self, address, message, password):
+ keys = self.get_private_key(address, password)
+ assert len(keys) == 1
+ sec = keys[0]
+ key = regenerate_key(sec)
+ compressed = is_compressed(sec)
+ return key.sign_message(message, compressed, address)
+
+
+
+ def decrypt_message(self, pubkey, message, password):
+ address = public_key_to_bc_address(pubkey.decode('hex'))
+ keys = self.get_private_key(address, password)
+ secret = keys[0]
+ ec = regenerate_key(secret)
+ decrypted = ec.decrypt_message(message)
+ return decrypted
+
+
+
+ def is_found(self):
+ return self.history.values() != [[]] * len(self.history)
+
+
+ def get_tx_value(self, tx, account=None):
+ domain = self.get_account_addresses(account)
+ return tx.get_value(domain, self.prevout_values)
+
+
+ def update_tx_outputs(self, tx_hash):
+ tx = self.transactions.get(tx_hash)
+
+ for i, (addr, value) in enumerate(tx.outputs):
+ key = tx_hash+ ':%d'%i
+ self.prevout_values[key] = value
+
+ for item in tx.inputs:
+ if self.is_mine(item.get('address')):
+ key = item['prevout_hash'] + ':%d'%item['prevout_n']
+ self.spent_outputs.append(key)
+
+
+ def get_addr_balance(self, address):
+ #assert self.is_mine(address)
+ h = self.history.get(address,[])
+ if h == ['*']: return 0,0
+ c = u = 0
+ received_coins = [] # list of coins received at address
+
+ for tx_hash, tx_height in h:
+ tx = self.transactions.get(tx_hash)
+ if not tx: continue
+
+ for i, (addr, value) in enumerate(tx.outputs):
+ if addr == address:
+ key = tx_hash + ':%d'%i
+ received_coins.append(key)
+
+ for tx_hash, tx_height in h:
+ tx = self.transactions.get(tx_hash)
+ if not tx: continue
+ v = 0
+
+ for item in tx.inputs:
+ addr = item.get('address')
+ if addr == address:
+ key = item['prevout_hash'] + ':%d'%item['prevout_n']
+ value = self.prevout_values.get( key )
+ if key in received_coins:
+ v -= value
+
+ for i, (addr, value) in enumerate(tx.outputs):
+ key = tx_hash + ':%d'%i
+ if addr == address:
+ v += value
+
+ if tx_height:
+ c += v
+ else:
+ u += v
+ return c, u
+
+
+ def get_account_name(self, k):
+ return self.labels.get(k, self.accounts[k].get_name(k))
+
+
+ def get_account_names(self):
+ account_names = {}
+ for k in self.accounts.keys():
+ account_names[k] = self.get_account_name(k)
+ return account_names
+
+
+ def get_account_addresses(self, a, include_change=True):
+ if a is None:
+ o = self.addresses(True)
+ elif a in self.accounts:
+ ac = self.accounts[a]
+ o = ac.get_addresses(0)
+ if include_change: o += ac.get_addresses(1)
+ return o
+
+
+ def get_account_balance(self, account):
+ return self.get_balance(self.get_account_addresses(account))
+
+ def get_frozen_balance(self):
+ return self.get_balance(self.frozen_addresses)
+
+ def get_balance(self, domain=None):
+ if domain is None: domain = self.addresses(True)
+ cc = uu = 0
+ for addr in domain:
+ c, u = self.get_addr_balance(addr)
+ cc += c
+ uu += u
+ return cc, uu
+
+
+ def get_unspent_coins(self, domain=None):
+ coins = []
+ if domain is None: domain = self.addresses(True)
+ for addr in domain:
+ h = self.history.get(addr, [])
+ if h == ['*']: continue
+ for tx_hash, tx_height in h:
+ tx = self.transactions.get(tx_hash)
+ if tx is None: raise Exception("Wallet not synchronized")
+ is_coinbase = tx.inputs[0].get('prevout_hash') == '0'*64
+ for o in tx.d.get('outputs'):
+ output = o.copy()
+ if output.get('address') != addr: continue
+ key = tx_hash + ":%d" % output.get('prevout_n')
+ if key in self.spent_outputs: continue
+ output['prevout_hash'] = tx_hash
+ output['height'] = tx_height
+ output['coinbase'] = is_coinbase
+ coins.append((tx_height, output))
+
+ # sort by age
+ if coins:
+ coins = sorted(coins)
+ if coins[-1][0] != 0:
+ while coins[0][0] == 0:
+ coins = coins[1:] + [ coins[0] ]
+ return [x[1] for x in coins]
+
+
+ def get_history(self, address):
+ with self.lock:
+ return self.history.get(address)
+
+
+ def get_tx_history(self, account=None):
+# if not self.verifier:
+# return []
+
+ with self.transaction_lock:
+ history = self.transactions.items()
+ #history.sort(key = lambda x: self.verifier.get_txpos(x[0]))
+ result = []
+
+ balance = 0
+ for tx_hash, tx in history:
+ is_relevant, is_mine, v, fee = self.get_tx_value(tx, account)
+ if v is not None: balance += v
+
+ c, u = self.get_account_balance(account)
+
+ if balance != c+u:
+ result.append( ('', 1000, 0, c+u-balance, None, c+u-balance, None ) )
+
+ balance = c + u - balance
+ for tx_hash, tx in history:
+ is_relevant, is_mine, value, fee = self.get_tx_value(tx, account)
+ if not is_relevant:
+ continue
+ if value is not None:
+ balance += value
+
+ conf, timestamp = self.verifier.get_confirmations(tx_hash) if self.verifier else (None, None)
+ result.append( (tx_hash, conf, is_mine, value, fee, balance, timestamp) )
+
+ return result
+
+
+ def get_label(self, tx_hash):
+ label = self.labels.get(tx_hash)
+ is_default = (label == '') or (label is None)
+ if is_default: label = self.get_default_label(tx_hash)
+ return label, is_default
+
+
+ def get_default_label(self, tx_hash):
+ tx = self.transactions.get(tx_hash)
+ default_label = ''
+ if tx:
+ is_relevant, is_mine, _, _ = self.get_tx_value(tx)
+ if is_mine:
+ for o in tx.outputs:
+ o_addr, _ = o
+ if not self.is_mine(o_addr):
+ try:
+ default_label = self.labels[o_addr]
+ except KeyError:
+ default_label = '>' + o_addr
+ break
+ else:
+ default_label = '(internal)'
+ else:
+ for o in tx.outputs:
+ o_addr, _ = o
+ if self.is_mine(o_addr) and not self.is_change(o_addr):
+ break
+ else:
+ for o in tx.outputs:
+ o_addr, _ = o
+ if self.is_mine(o_addr):
+ break
+ else:
+ o_addr = None
+
+ if o_addr:
+ dest_label = self.labels.get(o_addr)
+ try:
+ default_label = self.labels[o_addr]
+ except KeyError:
+ default_label = '<' + o_addr
+
+ return default_label
+
+
+ def sign_transaction(self, tx, keypairs, password):
+ tx.sign(keypairs)
+ run_hook('sign_transaction', tx, password)
+
+
+ def check_new_tx(self, tx_hash, tx):
+ # 1 check that tx is referenced in addr_history.
+ addresses = []
+ for addr, hist in self.history.items():
+ if hist == ['*']:continue
+ for txh, height in hist:
+ if txh == tx_hash:
+ addresses.append(addr)
+
+ if not addresses:
+ return False
+
+ # 2 check that referencing addresses are in the tx
+ for addr in addresses:
+ if not tx.has_address(addr):
+ return False
+
+ return True
+
+
+class Deterministic_Wallet(Abstract_Wallet):
+
+ def __init__(self, storage):
+ Abstract_Wallet.__init__(self, storage)
+
+ def has_seed(self):
+ return self.seed != ''
+
+ def is_deterministic(self):
+ return True
+
+ def is_watching_only(self):
+ return not self.has_seed()
+
+ def get_seed(self, password):
+ return pw_decode(self.seed, password)
+
+ def get_mnemonic(self, password):
+ return self.get_seed(password)
+
+ def num_unused_trailing_addresses(self, addresses):
+ k = 0
+ for a in addresses[::-1]:
+ if self.history.get(a):break
+ k = k + 1
+ return k
+
+ def min_acceptable_gap(self):
+ # fixme: this assumes wallet is synchronized
+ n = 0
+ nmax = 0
+
+ for account in self.accounts.values():
+ addresses = account.get_addresses(0)
+ k = self.num_unused_trailing_addresses(addresses)
+ for a in addresses[0:-k]:
+ if self.history.get(a):
+ n = 0
+ else:
+ n += 1
+ if n > nmax: nmax = n
+ return nmax + 1
+
+
+ def address_is_old(self, address):
+ age = -1
+ h = self.history.get(address, [])
+ return False
+# if h == ['*']:
+# return True
+# for tx_hash, tx_height in h:
+# if tx_height == 0:
+# tx_age = 0
+# else:
+# tx_age = self.network.get_local_height() - tx_height + 1
+# if tx_age > age:
+# age = tx_age
+# return age > 2
+
+
+class OldWallet(Deterministic_Wallet):
+
+ def get_seed(self, password):
+ seed = pw_decode(self.seed, password).encode('utf8')
+ return seed
+
+ def check_password(self, password):
+ seed = self.get_seed(password)
+ self.accounts[0].check_seed(seed)
+
+ def get_mnemonic(self, password):
+ import mnemonic
+ s = self.get_seed(password)
+ return ' '.join(mnemonic.mn_encode(s))
+
+# former WalletFactory
+class Wallet(object):
+
+ def __new__(self, storage):
+ config = storage.config
+
+ if not storage.file_exists:
+ print ("Wallet does no exist")
+ sys.exit(1)
+
+ seed_version = storage.get('seed_version')
+ if not seed_version:
+ seed_version = OLD_SEED_VERSION if len(storage.get('master_public_key')) == 128 else NEW_SEED_VERSION
+
+ if seed_version == OLD_SEED_VERSION:
+ return OldWallet(storage)
+ elif seed_version == NEW_SEED_VERSION:
+ return NewWallet(storage)
+ else:
+ msg = "This wallet seed is not supported."
+ if seed_version in [5]:
+ msg += "\nTo open this wallet, try 'git checkout seed_v%d'"%seed_version
+ print msg
+ sys.exit(1)
+
+