From b3fd4a28325ac6077640e0af5ab713f566d0370b Mon Sep 17 00:00:00 2001 From: genjix Date: Sun, 29 Apr 2012 17:49:41 +0100 Subject: [PATCH] mv client/* . && rm -fr client --- LICENCE | 674 ++++++++++++++ MANIFEST.in | 9 + README | 55 ++ RELEASE-NOTES | 38 + blocks | 11 + bmp.py | 206 +++++ client/LICENCE | 674 -------------- client/MANIFEST.in | 9 - client/README | 55 -- client/RELEASE-NOTES | 38 - client/blocks | 11 - client/bmp.py | 206 ----- client/docs/android.html | 60 -- client/electrum | 408 -------- client/electrum4a.py | 981 -------------------- client/electrum_text_320.png | Bin 4634 -> 0 bytes client/gui.py | 1265 ------------------------- client/gui_qt.py | 1057 --------------------- client/icons.qrc | 13 - client/icons/confirmed.png | Bin 1267 -> 0 bytes client/icons/lock.png | Bin 1994 -> 0 bytes client/icons/lock.svg | 276 ------ client/icons/network.png | Bin 3031 -> 0 bytes client/icons/preferences.png | Bin 1691 -> 0 bytes client/icons/seed.png | Bin 10322 -> 0 bytes client/icons/status_connected.png | Bin 1044 -> 0 bytes client/icons/status_disconnected.png | Bin 952 -> 0 bytes client/icons/status_disconnected.svg | 292 ------ client/icons/status_waiting.png | Bin 1501 -> 0 bytes client/icons/status_waiting.svg | 397 -------- client/icons/unconfirmed.png | Bin 1574 -> 0 bytes client/icons/unconfirmed.svg | 562 ----------- client/interface.py | 425 --------- client/mnemonic.py | 1689 ---------------------------------- client/msqr.py | 94 -- client/peers | 11 - client/pyqrnative.py | 962 ------------------- client/remote.php | 24 - client/remote_wallet.py | 127 --- client/ripemd.py | 399 -------- client/setup.py | 32 - client/upgrade.py | 75 -- client/version.py | 2 - client/wallet.py | 953 ------------------- docs/android.html | 60 ++ electrum | 408 ++++++++ electrum4a.py | 981 ++++++++++++++++++++ electrum_text_320.png | Bin 0 -> 4634 bytes gui.py | 1265 +++++++++++++++++++++++++ gui_qt.py | 1057 +++++++++++++++++++++ icons.qrc | 13 + icons/confirmed.png | Bin 0 -> 1267 bytes icons/lock.png | Bin 0 -> 1994 bytes icons/lock.svg | 276 ++++++ icons/network.png | Bin 0 -> 3031 bytes icons/preferences.png | Bin 0 -> 1691 bytes icons/seed.png | Bin 0 -> 10322 bytes icons/status_connected.png | Bin 0 -> 1044 bytes icons/status_disconnected.png | Bin 0 -> 952 bytes icons/status_disconnected.svg | 292 ++++++ icons/status_waiting.png | Bin 0 -> 1501 bytes icons/status_waiting.svg | 397 ++++++++ icons/unconfirmed.png | Bin 0 -> 1574 bytes icons/unconfirmed.svg | 562 +++++++++++ interface.py | 425 +++++++++ mnemonic.py | 1689 ++++++++++++++++++++++++++++++++++ msqr.py | 94 ++ peers | 11 + pyqrnative.py | 962 +++++++++++++++++++ remote.php | 24 + remote_wallet.py | 127 +++ ripemd.py | 399 ++++++++ setup.py | 32 + upgrade.py | 75 ++ version.py | 2 + wallet.py | 953 +++++++++++++++++++ 76 files changed, 11097 insertions(+), 11097 deletions(-) create mode 100644 LICENCE create mode 100644 MANIFEST.in create mode 100644 README create mode 100644 RELEASE-NOTES create mode 100755 blocks create mode 100644 bmp.py delete mode 100644 client/LICENCE delete mode 100644 client/MANIFEST.in delete mode 100644 client/README delete mode 100644 client/RELEASE-NOTES delete mode 100755 client/blocks delete mode 100644 client/bmp.py delete mode 100644 client/docs/android.html delete mode 100755 client/electrum delete mode 100755 client/electrum4a.py delete mode 100644 client/electrum_text_320.png delete mode 100644 client/gui.py delete mode 100644 client/gui_qt.py delete mode 100644 client/icons.qrc delete mode 100644 client/icons/confirmed.png delete mode 100644 client/icons/lock.png delete mode 100644 client/icons/lock.svg delete mode 100644 client/icons/network.png delete mode 100644 client/icons/preferences.png delete mode 100644 client/icons/seed.png delete mode 100644 client/icons/status_connected.png delete mode 100644 client/icons/status_disconnected.png delete mode 100644 client/icons/status_disconnected.svg delete mode 100644 client/icons/status_waiting.png delete mode 100644 client/icons/status_waiting.svg delete mode 100644 client/icons/unconfirmed.png delete mode 100644 client/icons/unconfirmed.svg delete mode 100644 client/interface.py delete mode 100644 client/mnemonic.py delete mode 100644 client/msqr.py delete mode 100755 client/peers delete mode 100644 client/pyqrnative.py delete mode 100644 client/remote.php delete mode 100644 client/remote_wallet.py delete mode 100644 client/ripemd.py delete mode 100644 client/setup.py delete mode 100644 client/upgrade.py delete mode 100644 client/version.py delete mode 100644 client/wallet.py create mode 100644 docs/android.html create mode 100755 electrum create mode 100755 electrum4a.py create mode 100644 electrum_text_320.png create mode 100644 gui.py create mode 100644 gui_qt.py create mode 100644 icons.qrc create mode 100644 icons/confirmed.png create mode 100644 icons/lock.png create mode 100644 icons/lock.svg create mode 100644 icons/network.png create mode 100644 icons/preferences.png create mode 100644 icons/seed.png create mode 100644 icons/status_connected.png create mode 100644 icons/status_disconnected.png create mode 100644 icons/status_disconnected.svg create mode 100644 icons/status_waiting.png create mode 100644 icons/status_waiting.svg create mode 100644 icons/unconfirmed.png create mode 100644 icons/unconfirmed.svg create mode 100644 interface.py create mode 100644 mnemonic.py create mode 100644 msqr.py create mode 100755 peers create mode 100644 pyqrnative.py create mode 100644 remote.php create mode 100644 remote_wallet.py create mode 100644 ripemd.py create mode 100644 setup.py create mode 100644 upgrade.py create mode 100644 version.py create mode 100644 wallet.py diff --git a/LICENCE b/LICENCE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENCE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..6962801 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,9 @@ +include README LICENCE RELEASE-NOTES +include *.py +include electrum +exclude setup.py +recursive-include ecdsa *.py +recursive-include aes *.py +include icons.qrc +include remote.php +recursive-include icons * diff --git a/README b/README new file mode 100644 index 0000000..a90857e --- /dev/null +++ b/README @@ -0,0 +1,55 @@ +Electrum - lightweight Bitcoin client + +Licence: GNU GPL v3 +Author: thomasv@gitorious +Language: Python + +Features: + +* Encrypted wallet: the file that contains your bitcoins is protected with a password. You are protected from thieves. +* Deterministic key generation: If you lose your wallet, you can recover it from its seed. You are protected from your own mistakes. +* No blockchain download: the client requests blockchain information from a server. No delays, always up-to-date. +* Transactions are signed locally: Your private keys are not shared with the server. You do not have to trust the server with your money. +* Privacy: The server does not know you, it does not store user accounts. You are not tied to a particular server. +* No single point of failure: The server code is open source, anyone can run a server. +* Firewall friendly: The client does not need to open a port, it simply polls the server for updates. +* Open Source: Anyone can audit the code. +* Python. Very compact code, easy to contribute. + + +INSTALL + +If you use the source from git, you will need to install python-ecdsa and slowaes: +* sudo easy_install ecdsa +* sudo easy_install slowaes +These packages are included in the tar.gz and zip archives. + + +In order to use the gtk gui, you need pygtk and tk. +* apt-get install python-gtk2 +* apt-get install python-tk + + +RUN + +To start the Qt gui, type: + python electrum +To use the Gtk gui, type: + python electrum --gui gtk + +If arguments are passed to the command line, Electrum will run in text mode. +Examples: + python electrum balance + python electrum help + + + +HELP + +the most up-to-date information is on the wiki: +https://en.bitcoin.it/wiki/Electrum + + +BROWSER CONFIGURATION + +see http://ecdsa.org/bitcoin_URIs.html diff --git a/RELEASE-NOTES b/RELEASE-NOTES new file mode 100644 index 0000000..01488e6 --- /dev/null +++ b/RELEASE-NOTES @@ -0,0 +1,38 @@ + +This page lists versions of Electrum that are incompatible with the +previous version. These incompatibilities are caused by a change in +the key derivation algorithm. + +Wallets created before the change are incompatible with the new +version, and that users need to move their bitcoins. We apologize for +the inconvenience. We try to keep this kind of upgrades as rare as +possible. + + +LIST OF UPGRADES: +----------------- + +Version 0.34: The key derivation was changed again in version 0.34, in order to offer "type 2 wallet" capabilities. +Version 0.31: This version fixes a vulnerability in the key generation function. + + +HOW TO UPGRADE: +--------------- + +If your wallet is deprecated, you will see a message asking you to +create a new wallet and to move your balance to the new wallet. + +Here are the steps that you need to follow: +* create a new wallet with the new version of Electrum: /path/to/new/electrum.py -w my_new_wallet.dat +* copy a receiving address from the new wallet +* open your old wallet with the old version of Electrum: /path/to/old/electrum.py -w my_old_wallet +* move your entire balance to the new address. + +Note that you may keep your current seed. For this, all you need to do +is to create the new wallet using the wallet recovery procedure. You +will not recover your old wallet with the new software, but you will +get a new wallet instead. + + + + diff --git a/blocks b/blocks new file mode 100755 index 0000000..baf4548 --- /dev/null +++ b/blocks @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import interface + +i = interface.TcpStratumInterface('ecdsa.org', 50001) +i.start() +i.send([('blockchain.numblocks.subscribe',[])]) + +while True: + r = i.responses.get(True, 100000000000) + print r.get('result') diff --git a/bmp.py b/bmp.py new file mode 100644 index 0000000..bfdd165 --- /dev/null +++ b/bmp.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- +""" +bmp.py - module for constructing simple BMP graphics files + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +""" +__version__ = "0.3" +__about = "bmp module, version %s, written by Paul McGuire, October, 2003, updated by Margus Laak, September, 2009" % __version__ + +from math import ceil, hypot + + +def shortToString(i): + hi = (i & 0xff00) >> 8 + lo = i & 0x00ff + return chr(lo) + chr(hi) + +def longToString(i): + hi = (long(i) & 0x7fff0000) >> 16 + lo = long(i) & 0x0000ffff + return shortToString(lo) + shortToString(hi) + +def long24ToString(i): + return chr(i & 0xff) + chr(i >> 8 & 0xff) + chr(i >> 16 & 0xff) + +def stringToLong(input_string, offset): + return ord(input_string[offset+3]) << 24 | ord(input_string[offset+2]) << 16 | ord(input_string[offset+1]) << 8 | ord(input_string[offset]) + +def stringToLong24(input_string, offset): + return ord(input_string[offset+2]) << 16 | ord(input_string[offset+1]) << 8 | ord(input_string[offset]) + +class Color(object): + """class for specifying colors while drawing BitMap elements""" + __slots__ = [ 'red', 'grn', 'blu' ] + __shade = 32 + + def __init__( self, r=0, g=0, b=0 ): + self.red = r + self.grn = g + self.blu = b + + def __setattr__(self, name, value): + if hasattr(self, name): + raise AttributeError, "Color is immutable" + else: + object.__setattr__(self, name, value) + + def __str__( self ): + return "R:%d G:%d B:%d" % (self.red, self.grn, self.blu ) + + def __hash__( self ): + return ( ( long(self.blu) ) + + ( long(self.grn) << 8 ) + + ( long(self.red) << 16 ) ) + + def __eq__( self, other ): + return (self is other) or (self.toLong == other.toLong) + + def lighten( self ): + return Color( + min( self.red + Color.__shade, 255), + min( self.grn + Color.__shade, 255), + min( self.blu + Color.__shade, 255) + ) + + def darken( self ): + return Color( + max( self.red - Color.__shade, 0), + max( self.grn - Color.__shade, 0), + max( self.blu - Color.__shade, 0) + ) + + def toLong( self ): + return self.__hash__() + + def fromLong( l ): + b = l & 0xff + l = l >> 8 + g = l & 0xff + l = l >> 8 + r = l & 0xff + return Color( r, g, b ) + fromLong = staticmethod(fromLong) + +# define class constants for common colors +Color.BLACK = Color( 0, 0, 0 ) +Color.RED = Color( 255, 0, 0 ) +Color.GREEN = Color( 0, 255, 0 ) +Color.BLUE = Color( 0, 0, 255 ) +Color.CYAN = Color( 0, 255, 255 ) +Color.MAGENTA = Color( 255, 0, 255 ) +Color.YELLOW = Color( 255, 255, 0 ) +Color.WHITE = Color( 255, 255, 255 ) +Color.DKRED = Color( 128, 0, 0 ) +Color.DKGREEN = Color( 0, 128, 0 ) +Color.DKBLUE = Color( 0, 0, 128 ) +Color.TEAL = Color( 0, 128, 128 ) +Color.PURPLE = Color( 128, 0, 128 ) +Color.BROWN = Color( 128, 128, 0 ) +Color.GRAY = Color( 128, 128, 128 ) + + +class BitMap(object): + """class for drawing and saving simple Windows bitmap files""" + + LINE_SOLID = 0 + LINE_DASHED = 1 + LINE_DOTTED = 2 + LINE_DOT_DASH=3 + _DASH_LEN = 12.0 + _DOT_LEN = 6.0 + _DOT_DASH_LEN = _DOT_LEN + _DASH_LEN + + def __init__( self, width, height, + bkgd = Color.WHITE, frgd = Color.BLACK ): + self.wd = int( ceil(width) ) + self.ht = int( ceil(height) ) + self.bgcolor = 0 + self.fgcolor = 1 + self.palette = [] + self.palette.append( bkgd.toLong() ) + self.palette.append( frgd.toLong() ) + self.currentPen = self.fgcolor + + tmparray = [ self.bgcolor ] * self.wd + self.bitarray = [ tmparray[:] for i in range( self.ht ) ] + self.currentPen = 1 + + + def plotPoint( self, x, y ): + if ( 0 <= x < self.wd and 0 <= y < self.ht ): + x = int(x) + y = int(y) + self.bitarray[y][x] = self.currentPen + + + def _saveBitMapNoCompression( self ): + line_padding = (4 - (self.wd % 4)) % 4 + + # write bitmap header + _bitmap = "BM" + _bitmap += longToString( 54 + self.ht*(self.wd*3 + line_padding) ) # DWORD size in bytes of the file + _bitmap += longToString( 0 ) # DWORD 0 + _bitmap += longToString( 54 ) + _bitmap += longToString( 40 ) # DWORD header size = 40 + _bitmap += longToString( self.wd ) # DWORD image width + _bitmap += longToString( self.ht ) # DWORD image height + _bitmap += shortToString( 1 ) # WORD planes = 1 + _bitmap += shortToString( 24 ) # WORD bits per pixel = 8 + _bitmap += longToString( 0 ) # DWORD compression = 0 + _bitmap += longToString( self.ht * (self.wd * 3 + line_padding) ) # DWORD sizeimage = size in bytes of the bitmap = width * height + _bitmap += longToString( 0 ) # DWORD horiz pixels per meter (?) + _bitmap += longToString( 0 ) # DWORD ver pixels per meter (?) + _bitmap += longToString( 0 ) # DWORD number of colors used = 256 + _bitmap += longToString( 0 ) # DWORD number of "import colors = len( self.palette ) + + # write pixels + self.bitarray.reverse() + for row in self.bitarray: + for pixel in row: + c = self.palette[pixel] + _bitmap += long24ToString(c) + for i in range(line_padding): + _bitmap += chr( 0 ) + + return _bitmap + + + + def saveFile( self, filename): + _b = self._saveBitMapNoCompression( ) + + f = file(filename, 'wb') + f.write(_b) + f.close() + + + + + + +if __name__ == "__main__": + + bmp = BitMap( 10, 10 ) + bmp.plotPoint( 5, 5 ) + bmp.plotPoint( 0, 0 ) + bmp.saveFile( "test.bmp" ) + diff --git a/client/LICENCE b/client/LICENCE deleted file mode 100644 index 94a9ed0..0000000 --- a/client/LICENCE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - 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. - - - Copyright (C) - - 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 . - -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: - - Copyright (C) - 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 -. - - 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 -. diff --git a/client/MANIFEST.in b/client/MANIFEST.in deleted file mode 100644 index 6962801..0000000 --- a/client/MANIFEST.in +++ /dev/null @@ -1,9 +0,0 @@ -include README LICENCE RELEASE-NOTES -include *.py -include electrum -exclude setup.py -recursive-include ecdsa *.py -recursive-include aes *.py -include icons.qrc -include remote.php -recursive-include icons * diff --git a/client/README b/client/README deleted file mode 100644 index a90857e..0000000 --- a/client/README +++ /dev/null @@ -1,55 +0,0 @@ -Electrum - lightweight Bitcoin client - -Licence: GNU GPL v3 -Author: thomasv@gitorious -Language: Python - -Features: - -* Encrypted wallet: the file that contains your bitcoins is protected with a password. You are protected from thieves. -* Deterministic key generation: If you lose your wallet, you can recover it from its seed. You are protected from your own mistakes. -* No blockchain download: the client requests blockchain information from a server. No delays, always up-to-date. -* Transactions are signed locally: Your private keys are not shared with the server. You do not have to trust the server with your money. -* Privacy: The server does not know you, it does not store user accounts. You are not tied to a particular server. -* No single point of failure: The server code is open source, anyone can run a server. -* Firewall friendly: The client does not need to open a port, it simply polls the server for updates. -* Open Source: Anyone can audit the code. -* Python. Very compact code, easy to contribute. - - -INSTALL - -If you use the source from git, you will need to install python-ecdsa and slowaes: -* sudo easy_install ecdsa -* sudo easy_install slowaes -These packages are included in the tar.gz and zip archives. - - -In order to use the gtk gui, you need pygtk and tk. -* apt-get install python-gtk2 -* apt-get install python-tk - - -RUN - -To start the Qt gui, type: - python electrum -To use the Gtk gui, type: - python electrum --gui gtk - -If arguments are passed to the command line, Electrum will run in text mode. -Examples: - python electrum balance - python electrum help - - - -HELP - -the most up-to-date information is on the wiki: -https://en.bitcoin.it/wiki/Electrum - - -BROWSER CONFIGURATION - -see http://ecdsa.org/bitcoin_URIs.html diff --git a/client/RELEASE-NOTES b/client/RELEASE-NOTES deleted file mode 100644 index 01488e6..0000000 --- a/client/RELEASE-NOTES +++ /dev/null @@ -1,38 +0,0 @@ - -This page lists versions of Electrum that are incompatible with the -previous version. These incompatibilities are caused by a change in -the key derivation algorithm. - -Wallets created before the change are incompatible with the new -version, and that users need to move their bitcoins. We apologize for -the inconvenience. We try to keep this kind of upgrades as rare as -possible. - - -LIST OF UPGRADES: ------------------ - -Version 0.34: The key derivation was changed again in version 0.34, in order to offer "type 2 wallet" capabilities. -Version 0.31: This version fixes a vulnerability in the key generation function. - - -HOW TO UPGRADE: ---------------- - -If your wallet is deprecated, you will see a message asking you to -create a new wallet and to move your balance to the new wallet. - -Here are the steps that you need to follow: -* create a new wallet with the new version of Electrum: /path/to/new/electrum.py -w my_new_wallet.dat -* copy a receiving address from the new wallet -* open your old wallet with the old version of Electrum: /path/to/old/electrum.py -w my_old_wallet -* move your entire balance to the new address. - -Note that you may keep your current seed. For this, all you need to do -is to create the new wallet using the wallet recovery procedure. You -will not recover your old wallet with the new software, but you will -get a new wallet instead. - - - - diff --git a/client/blocks b/client/blocks deleted file mode 100755 index baf4548..0000000 --- a/client/blocks +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import interface - -i = interface.TcpStratumInterface('ecdsa.org', 50001) -i.start() -i.send([('blockchain.numblocks.subscribe',[])]) - -while True: - r = i.responses.get(True, 100000000000) - print r.get('result') diff --git a/client/bmp.py b/client/bmp.py deleted file mode 100644 index bfdd165..0000000 --- a/client/bmp.py +++ /dev/null @@ -1,206 +0,0 @@ -# -*- coding: utf-8 -*- -""" -bmp.py - module for constructing simple BMP graphics files - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -""" -__version__ = "0.3" -__about = "bmp module, version %s, written by Paul McGuire, October, 2003, updated by Margus Laak, September, 2009" % __version__ - -from math import ceil, hypot - - -def shortToString(i): - hi = (i & 0xff00) >> 8 - lo = i & 0x00ff - return chr(lo) + chr(hi) - -def longToString(i): - hi = (long(i) & 0x7fff0000) >> 16 - lo = long(i) & 0x0000ffff - return shortToString(lo) + shortToString(hi) - -def long24ToString(i): - return chr(i & 0xff) + chr(i >> 8 & 0xff) + chr(i >> 16 & 0xff) - -def stringToLong(input_string, offset): - return ord(input_string[offset+3]) << 24 | ord(input_string[offset+2]) << 16 | ord(input_string[offset+1]) << 8 | ord(input_string[offset]) - -def stringToLong24(input_string, offset): - return ord(input_string[offset+2]) << 16 | ord(input_string[offset+1]) << 8 | ord(input_string[offset]) - -class Color(object): - """class for specifying colors while drawing BitMap elements""" - __slots__ = [ 'red', 'grn', 'blu' ] - __shade = 32 - - def __init__( self, r=0, g=0, b=0 ): - self.red = r - self.grn = g - self.blu = b - - def __setattr__(self, name, value): - if hasattr(self, name): - raise AttributeError, "Color is immutable" - else: - object.__setattr__(self, name, value) - - def __str__( self ): - return "R:%d G:%d B:%d" % (self.red, self.grn, self.blu ) - - def __hash__( self ): - return ( ( long(self.blu) ) + - ( long(self.grn) << 8 ) + - ( long(self.red) << 16 ) ) - - def __eq__( self, other ): - return (self is other) or (self.toLong == other.toLong) - - def lighten( self ): - return Color( - min( self.red + Color.__shade, 255), - min( self.grn + Color.__shade, 255), - min( self.blu + Color.__shade, 255) - ) - - def darken( self ): - return Color( - max( self.red - Color.__shade, 0), - max( self.grn - Color.__shade, 0), - max( self.blu - Color.__shade, 0) - ) - - def toLong( self ): - return self.__hash__() - - def fromLong( l ): - b = l & 0xff - l = l >> 8 - g = l & 0xff - l = l >> 8 - r = l & 0xff - return Color( r, g, b ) - fromLong = staticmethod(fromLong) - -# define class constants for common colors -Color.BLACK = Color( 0, 0, 0 ) -Color.RED = Color( 255, 0, 0 ) -Color.GREEN = Color( 0, 255, 0 ) -Color.BLUE = Color( 0, 0, 255 ) -Color.CYAN = Color( 0, 255, 255 ) -Color.MAGENTA = Color( 255, 0, 255 ) -Color.YELLOW = Color( 255, 255, 0 ) -Color.WHITE = Color( 255, 255, 255 ) -Color.DKRED = Color( 128, 0, 0 ) -Color.DKGREEN = Color( 0, 128, 0 ) -Color.DKBLUE = Color( 0, 0, 128 ) -Color.TEAL = Color( 0, 128, 128 ) -Color.PURPLE = Color( 128, 0, 128 ) -Color.BROWN = Color( 128, 128, 0 ) -Color.GRAY = Color( 128, 128, 128 ) - - -class BitMap(object): - """class for drawing and saving simple Windows bitmap files""" - - LINE_SOLID = 0 - LINE_DASHED = 1 - LINE_DOTTED = 2 - LINE_DOT_DASH=3 - _DASH_LEN = 12.0 - _DOT_LEN = 6.0 - _DOT_DASH_LEN = _DOT_LEN + _DASH_LEN - - def __init__( self, width, height, - bkgd = Color.WHITE, frgd = Color.BLACK ): - self.wd = int( ceil(width) ) - self.ht = int( ceil(height) ) - self.bgcolor = 0 - self.fgcolor = 1 - self.palette = [] - self.palette.append( bkgd.toLong() ) - self.palette.append( frgd.toLong() ) - self.currentPen = self.fgcolor - - tmparray = [ self.bgcolor ] * self.wd - self.bitarray = [ tmparray[:] for i in range( self.ht ) ] - self.currentPen = 1 - - - def plotPoint( self, x, y ): - if ( 0 <= x < self.wd and 0 <= y < self.ht ): - x = int(x) - y = int(y) - self.bitarray[y][x] = self.currentPen - - - def _saveBitMapNoCompression( self ): - line_padding = (4 - (self.wd % 4)) % 4 - - # write bitmap header - _bitmap = "BM" - _bitmap += longToString( 54 + self.ht*(self.wd*3 + line_padding) ) # DWORD size in bytes of the file - _bitmap += longToString( 0 ) # DWORD 0 - _bitmap += longToString( 54 ) - _bitmap += longToString( 40 ) # DWORD header size = 40 - _bitmap += longToString( self.wd ) # DWORD image width - _bitmap += longToString( self.ht ) # DWORD image height - _bitmap += shortToString( 1 ) # WORD planes = 1 - _bitmap += shortToString( 24 ) # WORD bits per pixel = 8 - _bitmap += longToString( 0 ) # DWORD compression = 0 - _bitmap += longToString( self.ht * (self.wd * 3 + line_padding) ) # DWORD sizeimage = size in bytes of the bitmap = width * height - _bitmap += longToString( 0 ) # DWORD horiz pixels per meter (?) - _bitmap += longToString( 0 ) # DWORD ver pixels per meter (?) - _bitmap += longToString( 0 ) # DWORD number of colors used = 256 - _bitmap += longToString( 0 ) # DWORD number of "import colors = len( self.palette ) - - # write pixels - self.bitarray.reverse() - for row in self.bitarray: - for pixel in row: - c = self.palette[pixel] - _bitmap += long24ToString(c) - for i in range(line_padding): - _bitmap += chr( 0 ) - - return _bitmap - - - - def saveFile( self, filename): - _b = self._saveBitMapNoCompression( ) - - f = file(filename, 'wb') - f.write(_b) - f.close() - - - - - - -if __name__ == "__main__": - - bmp = BitMap( 10, 10 ) - bmp.plotPoint( 5, 5 ) - bmp.plotPoint( 0, 0 ) - bmp.saveFile( "test.bmp" ) - diff --git a/client/docs/android.html b/client/docs/android.html deleted file mode 100644 index 1aed1a4..0000000 --- a/client/docs/android.html +++ /dev/null @@ -1,60 +0,0 @@ - - -
-

Electrum for Android

- -This page explains how to install Electrum on Android devices.

- -Please note that Electrum is not distributed as a binary package, but -as python source code; this gives users the possibility to see what -the code is doing, and to check that it does not contain malware. The -downside is that installation is slightly more complicated than -downloading an app on the Android market, but it remains very -simple.

- -It is possible to print this page on paper and to install everything from -QR codes. If you encounter problems, you may find help at - -this link. - - -

1. Download and install Google Scripting Layer for Android

- -You can get -it here, -or by scanning the following qr code:
- - - -

2. Download and install Python for Android

- -You can get -it here, -or by scanning the following qr code:
- -
-Once you have installed the apk, launch the Python for Android application and click 'install' - -

3. Download the Electrum install script

- -Download e4a_install.py and install it in your sl4a/scripts directory. -You can do it manually, or from QR code, as follows: -
-1. Launch SL4A.
-2. Press the Menu button.
-3. Tap Add.
-4. Tap Scan Barcode.
-5. Scan the following QRcode:
-
- -
This will install a script named e4a_install.py
- -

4. Download and install Electrum

-
-1. Tap e4a_install.py: it will download and install a directory named "Electrum-0.43d"
-2. To launch Electrum, visit the "Electrum-0.43d" directory and tap 'electrum4a.py'
-
- - diff --git a/client/electrum b/client/electrum deleted file mode 100755 index 011d56f..0000000 --- a/client/electrum +++ /dev/null @@ -1,408 +0,0 @@ -#!/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 . - -import re, sys, getpass - -from optparse import OptionParser -from wallet import Wallet, SecretToASecret -from interface import WalletSynchronizer -from decimal import Decimal -from wallet import format_satoshis - -known_commands = ['help', 'validateaddress', 'balance', 'contacts', 'create', 'restore', 'payto', 'sendtx', 'password', 'addresses', 'history', 'label', 'mktx','seed','import','signmessage','verifymessage','eval'] -offline_commands = ['password', 'mktx', 'history', 'label', 'contacts', 'help', 'validateaddress', 'signmessage', 'verifymessage', 'eval', 'create', 'addresses', 'import', 'seed'] -protected_commands = ['payto', 'password', 'mktx', 'seed', 'import','signmessage' ] - -if __name__ == '__main__': - - usage = "usage: %prog [options] command args\nCommands: "+ (', '.join(known_commands)) - parser = OptionParser(usage=usage) - parser.add_option("-g", "--gui", dest="gui", default="qt", help="gui") - parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)") - parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses") - parser.add_option("-b", "--balance", action="store_true", dest="show_balance", default=False, help="show the balance at listed addresses") - parser.add_option("-k", "--keys",action="store_true", dest="show_keys",default=False, help="show the private keys of listed addresses") - parser.add_option("-f", "--fee", dest="tx_fee", default="0.005", help="set tx fee") - parser.add_option("-s", "--fromaddr", dest="from_addr", default=None, help="set source address for payto/mktx. if it isn't in the wallet, it will ask for the private key unless supplied in the format public_key:private_key. It's not saved in the wallet.") - parser.add_option("-c", "--changeaddr", dest="change_addr", default=None, help="set the change address for payto/mktx. default is a spare address, or the source address if it's not in the wallet") - parser.add_option("-r", "--remote", dest="remote_url", default=None, help="URL of a remote wallet") - options, args = parser.parse_args() - - wallet = Wallet() - wallet.set_path(options.wallet_path) - wallet.read() - wallet.remote_url = options.remote_url - - if len(args)==0: - url = None - cmd = 'gui' - elif len(args)==1 and re.match('^bitcoin:', args[0]): - url = args[0] - cmd = 'gui' - else: - cmd = args[0] - firstarg = args[1] if len(args) > 1 else '' - - if cmd == 'gui': - if options.gui=='gtk': - import gui - elif options.gui=='qt': - import gui_qt as gui - else: - print "unknown gui", options.gui - exit(1) - - gui = gui.ElectrumGui(wallet) - WalletSynchronizer(wallet,True).start() - - try: - found = wallet.file_exists - if not found: - found = gui.restore_or_create() - except SystemExit, e: - exit(e) - except BaseException, e: - import traceback - traceback.print_exc(file=sys.stdout) - #gui.show_message(e.message) - exit(1) - - if not found: exit(1) - - gui.main(url) - wallet.save() - sys.exit(0) - - if cmd not in known_commands: - cmd = 'help' - - if not wallet.file_exists and cmd not in ['help','create','restore']: - print "Wallet file not found." - print "Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option" - sys.exit(0) - - if cmd in ['create', 'restore']: - import mnemonic - if wallet.file_exists: - print "remove the existing wallet first!" - sys.exit(0) - password = getpass.getpass("Password (hit return if you do not wish to encrypt your wallet):") - if password: - password2 = getpass.getpass("Confirm password:") - if password != password2: - print "error" - sys.exit(1) - else: - password = None - - w_host, w_port, w_protocol = wallet.server.split(':') - host = raw_input("server (default:%s):"%w_host) - port = raw_input("port (default:%s):"%w_port) - protocol = raw_input("protocol [t=tcp;h=http;n=native] (default:%s):"%w_protocol) - fee = raw_input("fee (default:%s):"%( str(Decimal(wallet.fee)/100000000)) ) - gap = raw_input("gap limit (default 5):") - if host: w_host = host - if port: w_port = port - if protocol: w_protocol = protocol - wallet.server = w_host + ':' + w_port + ':' +w_protocol - if fee: wallet.fee = float(fee) - if gap: wallet.gap_limit = int(gap) - - if cmd == 'restore': - seed = raw_input("seed:") - try: - seed.decode('hex') - except: - print "not hex, trying decode" - seed = mnemonic.mn_decode( seed.split(' ') ) - if not seed: - print "no seed" - sys.exit(1) - - wallet.seed = str(seed) - WalletSynchronizer(wallet).start() - print "recovering wallet..." - wallet.init_mpk( wallet.seed ) - wallet.up_to_date_event.clear() - wallet.up_to_date = False - wallet.update() - if wallet.is_found(): - wallet.fill_addressbook() - wallet.save() - print "recovery successful" - else: - print "found no history for this wallet" - else: - wallet.new_seed(None) - wallet.init_mpk( wallet.seed ) - wallet.synchronize() # there is no wallet thread - wallet.save() - print "Your wallet generation seed is: " + wallet.seed - print "Please keep it in a safe place; if you lose it, you will not be able to restore your wallet." - print "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:" - print "\""+' '.join(mnemonic.mn_encode(wallet.seed))+"\"" - - # check syntax - if cmd in ['payto', 'mktx']: - try: - to_address = args[1] - amount = int( 100000000 * Decimal(args[2]) ) - change_addr = None - label = ' '.join(args[3:]) - if options.tx_fee: - options.tx_fee = int( 100000000 * Decimal(options.tx_fee) ) - except: - firstarg = cmd - cmd = 'help' - - # open session - if cmd not in offline_commands: - WalletSynchronizer(wallet).start() - wallet.update() - wallet.save() - - # check if --from_addr not in wallet (for mktx/payto) - is_temporary = False - from_addr = None - if options.from_addr: - from_addr = options.from_addr - if from_addr not in wallet.all_addresses(): - is_temporary = True - - # commands needing password - if cmd in protected_commands or ( cmd=='addresses' and options.show_keys): - password = getpass.getpass('Password:') if wallet.use_encryption and not is_temporary else None - # check password - try: - wallet.pw_decode( wallet.seed, password) - except: - print "invalid password" - exit(1) - - if cmd == 'import': - keypair = args[1] - if wallet.import_key(keypair,password): - print "keypair imported" - else: - print "error" - wallet.save() - - if cmd=='help': - cmd2 = firstarg - if cmd2 not in known_commands: - print "known commands:", ', '.join(known_commands) - print "'electrum help ' shows the help on a specific command" - print "'electrum --help' shows the list of options" - elif cmd2 == 'balance': - print "Display the balance of your wallet or a specific address. The address does not have to be a owned address (you know the private key)." - print "syntax: balance [
]" - elif cmd2 == 'contacts': - print "show your list of contacts" - elif cmd2 == 'payto': - print "payto [label]" - print "create and broadcast a transaction." - print " can be a bitcoin address or a label" - print "options: --fee, --fromaddr, --changeaddr" - elif cmd2== 'sendtx': - print "sendtx " - print "broadcast a transaction to the network. must be in hexadecimal" - elif cmd2 == 'password': - print "change your password" - elif cmd2 == 'addresses': - print "show your list of addresses. options: -a, -k, -b" - elif cmd2 == 'history': - print "show the transaction history" - elif cmd2 == 'label': - print "assign a label to an item" - elif cmd2 == 'gtk': - print "start the GUI" - elif cmd2 == 'mktx': - print "create a signed transaction. password protected" - print "syntax: mktx [label]" - print "options: --fee, --fromaddr, --changeaddr" - elif cmd2 == 'seed': - print "show generation seed of your wallet. password protected." - elif cmd2 == 'eval': - print "Run python eval() on an object\nSyntax: eval \nExample: eval \"wallet.aliases\"" - - elif cmd == 'seed': - import mnemonic - seed = wallet.pw_decode( wallet.seed, password) - print seed, '"'+' '.join(mnemonic.mn_encode(seed))+'"' - - elif cmd == 'validateaddress': - addr = args[1] - print wallet.is_valid(addr) - - elif cmd == 'balance': - try: - addrs = args[1:] - except: - pass - if addrs == []: - c, u = wallet.get_balance() - if u: - print Decimal( c ) / 100000000 , Decimal( u ) / 100000000 - else: - print Decimal( c ) / 100000000 - else: - for addr in addrs: - c, u = wallet.get_addr_balance(addr) - if u: - print "%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000)) - else: - print "%s %s" % (addr, str(Decimal(c)/100000000)) - - elif cmd in [ 'contacts']: - for addr in wallet.addressbook: - print addr, " ", wallet.labels.get(addr) - - elif cmd == 'eval': - print eval(args[1]) - wallet.save() - - elif cmd in [ 'addresses']: - for addr in wallet.all_addresses(): - if options.show_all or not wallet.is_change(addr): - label = wallet.labels.get(addr) - _type = '' - if wallet.is_change(addr): _type = "[change]" - if addr in wallet.imported_keys.keys(): _type = "[imported]" - if label is None: label = '' - if options.show_balance: - h = wallet.history.get(addr,[]) - ni = no = 0 - for item in h: - if item['is_in']: ni += 1 - else: no += 1 - b = "%d %d %s"%(no, ni, str(Decimal(wallet.get_addr_balance(addr)[0])/100000000)) - else: b='' - if options.show_keys: - pk = wallet.get_private_key(addr, password) - addr = addr + ':' + SecretToASecret(pk) - print addr, b, _type, label - - if cmd == 'history': - lines = wallet.get_tx_history() - b = 0 - for line in lines: - import datetime - v = line['value'] - b += v - try: - time_str = str( datetime.datetime.fromtimestamp( line['timestamp'])) - except: - print line['timestamp'] - time_str = 'pending' - label = line.get('label') - if not label: label = line['tx_hash'] - else: label = label + ' '*(64 - len(label) ) - - print time_str , " " + label + " " + format_satoshis(v)+ " "+ format_satoshis(b) - print "# balance: ", format_satoshis(b) - - elif cmd == 'label': - try: - tx = args[1] - label = ' '.join(args[2:]) - except: - print "syntax: label " - sys.exit(1) - wallet.labels[tx] = label - wallet.save() - - elif cmd in ['payto', 'mktx']: - if from_addr and is_temporary: - if from_addr.find(":") == -1: - keypair = from_addr + ":" + getpass.getpass('Private key:') - else: - keypair = from_addr - from_addr = keypair.split(':')[0] - if not wallet.import_key(keypair,password): - print "invalid key pair" - exit(1) - wallet.history[from_addr] = interface.retrieve_history(from_addr) - wallet.update_tx_history() - change_addr = from_addr - - if options.change_addr: - change_addr = options.change_addr - - for k, v in wallet.labels.items(): - if v == to_address: - to_address = k - print "alias", to_address - break - if change_addr and v == change_addr: - change_addr = k - try: - tx = wallet.mktx( to_address, amount, label, password, - fee = options.tx_fee, change_addr = change_addr, from_addr = from_addr ) - except: - import traceback - traceback.print_exc(file=sys.stdout) - tx = None - - if tx and cmd=='payto': - r, h = wallet.sendtx( tx ) - print h - else: - print tx - - if is_temporary: - wallet.imported_keys.pop(from_addr) - del(wallet.history[from_addr]) - wallet.save() - - elif cmd == 'sendtx': - tx = args[1] - r, h = wallet.sendtx( tx ) - print h - - elif cmd == 'password': - try: - seed = wallet.pw_decode( wallet.seed, password) - except: - print "sorry" - sys.exit(1) - new_password = getpass.getpass('New password:') - if new_password == getpass.getpass('Confirm new password:'): - wallet.use_encryption = (new_password != '') - wallet.seed = wallet.pw_encode( seed, new_password) - for k in wallet.imported_keys.keys(): - a = wallet.imported_keys[k] - b = wallet.pw_decode(a, password) - c = wallet.pw_encode(b, new_password) - wallet.imported_keys[k] = c - wallet.save() - else: - print "error: mismatch" - - elif cmd == 'signmessage': - address, message = args[1:3] - print wallet.sign_message(address, message, password) - - elif cmd == 'verifymessage': - address, signature, message = args[1:4] - try: - wallet.verify_message(address, signature, message) - print True - except: - print False - - diff --git a/client/electrum4a.py b/client/electrum4a.py deleted file mode 100755 index f247764..0000000 --- a/client/electrum4a.py +++ /dev/null @@ -1,981 +0,0 @@ -#!/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 . - - - - -import android -from interface import WalletSynchronizer -from wallet import Wallet -from wallet import format_satoshis -from decimal import Decimal -import mnemonic - -import datetime - - - -def modal_dialog(title, msg = None): - droid.dialogCreateAlert(title,msg) - droid.dialogSetPositiveButtonText('OK') - droid.dialogShow() - droid.dialogGetResponse() - droid.dialogDismiss() - -def modal_input(title, msg, value = None, etype=None): - droid.dialogCreateInput(title, msg, value, etype) - droid.dialogSetPositiveButtonText('OK') - droid.dialogSetNegativeButtonText('Cancel') - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - if response.get('which') == 'positive': - return response.get('value') - -def modal_question(q, msg, pos_text = 'OK', neg_text = 'Cancel'): - droid.dialogCreateAlert(q, msg) - droid.dialogSetPositiveButtonText(pos_text) - droid.dialogSetNegativeButtonText(neg_text) - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - return response.get('which') == 'positive' - -def edit_label(addr): - v = modal_input('Edit label',None,wallet.labels.get(addr)) - if v is not None: - if v: - wallet.labels[addr] = v - else: - if addr in wallet.labels.keys(): - wallet.labels.pop(addr) - wallet.update_tx_history() - wallet.save() - droid.fullSetProperty("labelTextView", "text", v) - -def select_from_contacts(): - title = 'Contacts:' - droid.dialogCreateAlert(title) - l = [] - for i in range(len(wallet.addressbook)): - addr = wallet.addressbook[i] - label = wallet.labels.get(addr,addr) - l.append( label ) - droid.dialogSetItems(l) - droid.dialogSetPositiveButtonText('New contact') - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - - if response.get('which') == 'positive': - return 'newcontact' - - result = response.get('item') - print result - if result is not None: - addr = wallet.addressbook[result] - return addr - - -def select_from_addresses(): - droid.dialogCreateAlert("Addresses:") - l = [] - for i in range(len(wallet.addresses)): - addr = wallet.addresses[i] - label = wallet.labels.get(addr,addr) - l.append( label ) - droid.dialogSetItems(l) - droid.dialogShow() - response = droid.dialogGetResponse() - result = response.result.get('item') - droid.dialogDismiss() - if result is not None: - addr = wallet.addresses[result] - return addr - - -def protocol_name(p): - if p == 't': return 'TCP/stratum' - if p == 'h': return 'HTTP/Stratum' - if p == 'n': return 'TCP/native' - -def protocol_dialog(host, protocol, z): - droid.dialogCreateAlert('Protocol',host) - if z: - protocols = z.keys() - else: - protocols = ['t','h','n'] - l = [] - current = protocols.index(protocol) - for p in protocols: - l.append(protocol_name(p)) - droid.dialogSetSingleChoiceItems(l, current) - droid.dialogSetPositiveButtonText('OK') - droid.dialogSetNegativeButtonText('Cancel') - droid.dialogShow() - response = droid.dialogGetResponse().result - if not response: return - if response.get('which') == 'positive': - response = droid.dialogGetSelectedItems().result[0] - droid.dialogDismiss() - p = protocols[response] - port = z[p] - return host + ':' + port + ':' + p - - - - -def make_layout(s, scrollable = False): - content = """ - - - - - - - %s """%s - - if scrollable: - content = """ - - - - - %s - - - - """%content - - - return """ - - - %s - """%content - - - - -def main_layout(): - return make_layout(""" - - - - - - - %s """%get_history_layout(15),True) - - - -def qr_layout(addr): - return make_layout(""" - - - - - - - - - - """%(addr,wallet.labels.get(addr,'')), True) - -payto_layout = make_layout(""" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """,False) - - - -settings_layout = make_layout(""" """) - - - -def get_history_values(n): - values = [] - h = wallet.get_tx_history() - - length = min(n, len(h)) - for i in range(length): - line = h[-i-1] - v = line['value'] - try: - dt = datetime.datetime.fromtimestamp( line['timestamp'] ) - if dt.date() == dt.today().date(): - time_str = str( dt.time() ) - else: - time_str = str( dt.date() ) - conf = 'v' - - except: - print line['timestamp'] - time_str = 'pending' - conf = 'o' - - tx_hash = line['tx_hash'] - label = wallet.labels.get(tx_hash) - is_default_label = (label == '') or (label is None) - if is_default_label: label = line['default_label'] - values.append((conf, ' ' + time_str, ' ' + format_satoshis(v,True), ' ' + label )) - - return values - - -def get_history_layout(n): - rows = "" - i = 0 - values = get_history_values(n) - for v in values: - a,b,c,d = v - color = "#ff00ff00" if a == 'v' else "#ffff0000" - rows += """ - - - - - - """%(i,a,color,i,b,i,c,i,d) - i += 1 - - output = """ - - %s -"""% rows - return output - - -def set_history_layout(n): - values = get_history_values(n) - i = 0 - for v in values: - a,b,c,d = v - droid.fullSetProperty("hl_%d_col1"%i,"text", a) - - if a == 'v': - droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ff00ff00") - else: - droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ffff0000") - - droid.fullSetProperty("hl_%d_col2"%i,"text", b) - droid.fullSetProperty("hl_%d_col3"%i,"text", c) - droid.fullSetProperty("hl_%d_col4"%i,"text", d) - i += 1 - - - - -status_text = '' -def update_layout(): - global status_text - if not wallet.interface.is_connected: - text = "Not connected..." - elif wallet.blocks == 0: - text = "Server not ready" - elif not wallet.up_to_date: - text = "Synchronizing..." - else: - c, u = wallet.get_balance() - text = "Balance:"+format_satoshis(c) - if u : text += ' [' + format_satoshis(u,True).strip() + ']' - - - # vibrate if status changed - if text != status_text: - if status_text and wallet.interface.is_connected and wallet.up_to_date: - droid.vibrate() - status_text = text - - droid.fullSetProperty("balanceTextView", "text", status_text) - - if wallet.up_to_date: - set_history_layout(15) - - - - -def pay_to(recipient, amount, fee, label): - - if wallet.use_encryption: - password = droid.dialogGetPassword('Password').result - if not password: return - else: - password = None - - droid.dialogCreateSpinnerProgress("Electrum", "signing transaction...") - droid.dialogShow() - - try: - tx = wallet.mktx( recipient, amount, label, password, fee) - except BaseException, e: - modal_dialog('error', e.message) - droid.dialogDismiss() - return - - droid.dialogDismiss() - - r, h = wallet.sendtx( tx ) - if r: - modal_dialog('Payment sent', h) - return True - else: - modal_dialog('Error', h) - - - - - -def recover(): - - droid.dialogCreateAlert("Wallet not found","Do you want to create a new wallet, or restore an existing one?") - droid.dialogSetPositiveButtonText('Create') - droid.dialogSetNeutralButtonText('Restore') - droid.dialogSetNegativeButtonText('Cancel') - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - if response.get('which') == 'negative': - exit(1) - - is_recovery = response.get('which') == 'neutral' - - if not is_recovery: - wallet.new_seed(None) - else: - if modal_question("Input method",None,'QR Code', 'mnemonic'): - code = droid.scanBarcode() - r = code.result - if r: - seed = r['extras']['SCAN_RESULT'] - else: - exit(1) - else: - m = modal_input('Mnemonic','please enter your code') - try: - seed = mnemonic.mn_decode(m.split(' ')) - except: - modal_dialog('error: could not decode this seed') - exit(1) - - wallet.seed = str(seed) - - modal_dialog('Your seed is:', wallet.seed) - modal_dialog('Mnemonic code:', ' '.join(mnemonic.mn_encode(wallet.seed)) ) - - msg = "recovering wallet..." if is_recovery else "creating wallet..." - droid.dialogCreateSpinnerProgress("Electrum", msg) - droid.dialogShow() - - wallet.init_mpk( wallet.seed ) - WalletSynchronizer(wallet,True).start() - wallet.update() - - droid.dialogDismiss() - droid.vibrate() - - if is_recovery: - if wallet.is_found(): - wallet.update_tx_history() - wallet.fill_addressbook() - modal_dialog("recovery successful") - else: - if not modal_question("no transactions found for this seed","do you want to keep this wallet?"): - exit(1) - - change_password_dialog() - wallet.save() - - - -def make_new_contact(): - code = droid.scanBarcode() - r = code.result - if r: - address = r['extras']['SCAN_RESULT'] - if address: - if wallet.is_valid(address): - if modal_question('Add to contacts?', address): - wallet.addressbook.append(address) - wallet.save() - else: - modal_dialog('Invalid address', address) - - -do_refresh = False - -def update_callback(): - global do_refresh - print "gui callback", wallet.interface.is_connected, wallet.up_to_date - do_refresh = True - droid.eventPost("refresh",'z') - -def main_loop(): - global do_refresh - - update_layout() - out = None - quitting = False - while out is None: - - event = droid.eventWait(1000).result - if event is None: - if do_refresh: - update_layout() - do_refresh = False - continue - - print "got event in main loop", repr(event) - if event == 'OK': continue - if event is None: continue - #if event["name"]=="refresh": - - - # request 2 taps before we exit - if event["name"]=="key": - if event["data"]["key"] == '4': - if quitting: - out = 'quit' - else: - quitting = True - else: quitting = False - - if event["name"]=="click": - id=event["data"]["id"] - - elif event["name"]=="settings": - out = 'settings' - - elif event["name"] in menu_commands: - out = event["name"] - - if out == 'contacts': - global contact_addr - contact_addr = select_from_contacts() - if contact_addr == 'newcontact': - make_new_contact() - contact_addr = None - if not contact_addr: - out = None - - elif out == "receive": - global receive_addr - receive_addr = select_from_addresses() - if not receive_addr: - out = None - - - return out - - -def payto_loop(): - global recipient - if recipient: - droid.fullSetProperty("recipient","text",recipient) - recipient = None - - out = None - while out is None: - event = droid.eventWait().result - print "got event in payto loop", event - - if event["name"] == "click": - id = event["data"]["id"] - - if id=="buttonPay": - - droid.fullQuery() - recipient = droid.fullQueryDetail("recipient").result.get('text') - label = droid.fullQueryDetail("label").result.get('text') - amount = droid.fullQueryDetail('amount').result.get('text') - - if not wallet.is_valid(recipient): - modal_dialog('Error','Invalid Bitcoin address') - continue - - try: - amount = int( 100000000 * Decimal(amount) ) - except: - modal_dialog('Error','Invalid amount') - continue - - result = pay_to(recipient, amount, wallet.fee, label) - if result: - out = 'main' - - elif id=="buttonContacts": - addr = select_from_contacts() - droid.fullSetProperty("recipient","text",addr) - - elif id=="buttonQR": - code = droid.scanBarcode() - r = code.result - if r: - addr = r['extras']['SCAN_RESULT'] - if addr: - droid.fullSetProperty("recipient","text",addr) - - elif event["name"] in menu_commands: - out = event["name"] - - elif event["name"]=="key": - if event["data"]["key"] == '4': - out = 'main' - - #elif event["name"]=="screen": - # if event["data"]=="destroy": - # out = 'main' - - return out - - -receive_addr = '' -contact_addr = '' -recipient = '' - -def receive_loop(): - out = None - while out is None: - event = droid.eventWait().result - print "got event", event - if event["name"]=="key": - if event["data"]["key"] == '4': - out = 'main' - - elif event["name"]=="clipboard": - droid.setClipboard(receive_addr) - modal_dialog('Address copied to clipboard',receive_addr) - - elif event["name"]=="edit": - edit_label(receive_addr) - - return out - -def contacts_loop(): - global recipient - out = None - while out is None: - event = droid.eventWait().result - print "got event", event - if event["name"]=="key": - if event["data"]["key"] == '4': - out = 'main' - - elif event["name"]=="clipboard": - droid.setClipboard(contact_addr) - modal_dialog('Address copied to clipboard',contact_addr) - - elif event["name"]=="edit": - edit_label(contact_addr) - - elif event["name"]=="paytocontact": - recipient = contact_addr - out = 'send' - - elif event["name"]=="deletecontact": - if modal_question('delete contact', contact_addr): - out = 'main' - - return out - - -def server_dialog(plist): - droid.dialogCreateAlert("Public servers") - droid.dialogSetItems( plist.keys() ) - droid.dialogSetPositiveButtonText('Private server') - droid.dialogShow() - response = droid.dialogGetResponse().result - droid.dialogDismiss() - - if response.get('which') == 'positive': - return modal_input('Private server', None) - - i = response.get('item') - if i is not None: - response = plist.keys()[i] - return response - - -def seed_dialog(): - if wallet.use_encryption: - password = droid.dialogGetPassword('Seed').result - if not password: return - else: - password = None - - try: - seed = wallet.pw_decode( wallet.seed, password) - except: - modal_dialog('error','incorrect password') - return - - modal_dialog('Your seed is',seed) - modal_dialog('Mnemonic code:', ' '.join(mnemonic.mn_encode(seed)) ) - -def change_password_dialog(): - if wallet.use_encryption: - password = droid.dialogGetPassword('Your wallet is encrypted').result - if password is None: return - else: - password = None - - try: - seed = wallet.pw_decode( wallet.seed, password) - except: - modal_dialog('error','incorrect password') - return - - new_password = droid.dialogGetPassword('Choose a password').result - if new_password == None: - return - - if new_password != '': - password2 = droid.dialogGetPassword('Confirm new password').result - if new_password != password2: - modal_dialog('error','passwords do not match') - return - - wallet.update_password(seed, new_password) - if new_password: - modal_dialog('Password updated','your wallet is encrypted') - else: - modal_dialog('No password','your wallet is not encrypted') - return True - - -def settings_loop(): - - - def set_listview(): - server, port, p = wallet.server.split(':') - fee = str( Decimal( wallet.fee)/100000000 ) - is_encrypted = 'yes' if wallet.use_encryption else 'no' - protocol = protocol_name(p) - droid.fullShow(settings_layout) - droid.fullSetList("myListView",['Server: ' + server, 'Protocol: '+ protocol, 'Port: '+port, 'Transaction fee: '+fee, 'Password: '+is_encrypted, 'Seed']) - - set_listview() - - out = None - while out is None: - event = droid.eventWait().result - print "got event", event - if event == 'OK': continue - if not event: continue - - plist = {} - for item in wallet.interface.servers: - host, pp = item - z = {} - for item2 in pp: - protocol, port = item2 - z[protocol] = port - plist[host] = z - - if event["name"] == "itemclick": - pos = event["data"]["position"] - host, port, protocol = wallet.server.split(':') - - if pos == "0": #server - host = server_dialog(plist) - if host: - p = plist[host] - port = p['t'] - srv = host + ':' + port + ':t' - try: - wallet.set_server(srv) - except: - modal_dialog('error','invalid server') - set_listview() - - elif pos == "1": #protocol - if host in plist: - srv = protocol_dialog(host, protocol, plist[host]) - if srv: - try: - wallet.set_server(srv) - except: - modal_dialog('error','invalid server') - set_listview() - - elif pos == "2": #port - a_port = modal_input('Port number', 'If you use a public server, this field is set automatically when you set the protocol', port, "number") - if a_port: - if a_port != port: - srv = host + ':' + a_port + ':'+ protocol - try: - wallet.set_server(srv) - except: - modal_dialog('error','invalid port number') - set_listview() - - elif pos == "3": #fee - fee = modal_input('Transaction fee', 'The fee will be this amount multiplied by the number of inputs in your transaction. ', str( Decimal( wallet.fee)/100000000 ), "numberDecimal") - if fee: - try: - fee = int( 100000000 * Decimal(fee) ) - except: - modal_dialog('error','invalid fee value') - if wallet.fee != fee: - wallet.fee = fee - wallet.save() - set_listview() - - elif pos == "4": - if change_password_dialog(): - set_listview() - - elif pos == "5": - seed_dialog() - - - elif event["name"] in menu_commands: - out = event["name"] - - elif event["name"] == 'cancel': - out = 'main' - - elif event["name"] == "key": - if event["data"]["key"] == '4': - out = 'main' - - return out - - - - -menu_commands = ["send", "receive", "settings", "contacts", "main"] -droid = android.Android() -wallet = Wallet(update_callback) - -wallet.set_path("/sdcard/electrum.dat") -wallet.read() -if not wallet.file_exists: - recover() -else: - WalletSynchronizer(wallet,True).start() - - -s = 'main' - -def add_menu(s): - droid.clearOptionsMenu() - if s == 'main': - droid.addOptionsMenuItem("Send","send",None,"") - droid.addOptionsMenuItem("Receive","receive",None,"") - droid.addOptionsMenuItem("Contacts","contacts",None,"") - droid.addOptionsMenuItem("Settings","settings",None,"") - elif s == 'receive': - droid.addOptionsMenuItem("Copy","clipboard",None,"") - droid.addOptionsMenuItem("Label","edit",None,"") - elif s == 'contacts': - droid.addOptionsMenuItem("Copy","clipboard",None,"") - droid.addOptionsMenuItem("Label","edit",None,"") - droid.addOptionsMenuItem("Pay to","paytocontact",None,"") - #droid.addOptionsMenuItem("Delete","deletecontact",None,"") - -def make_bitmap(addr): - # fixme: this is highly inefficient - droid.dialogCreateSpinnerProgress("please wait") - droid.dialogShow() - import pyqrnative, bmp - qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) - qr.addData(addr) - qr.make() - k = qr.getModuleCount() - bitmap = bmp.BitMap( 35*8, 35*8 ) - print len(bitmap.bitarray) - bitmap.bitarray = [] - assert k == 33 - - for r in range(35): - tmparray = [ 0 ] * 35*8 - - if 0 < r < 34: - for c in range(k): - if qr.isDark(r-1, c): - tmparray[ (1+c)*8:(2+c)*8] = [1]*8 - - for i in range(8): - bitmap.bitarray.append( tmparray[:] ) - - bitmap.saveFile( "/sdcard/sl4a/qrcode.bmp" ) - droid.dialogDismiss() - - - -while True: - add_menu(s) - if s == 'main': - droid.fullShow(main_layout()) - s = main_loop() - #droid.fullDismiss() - - elif s == 'send': - droid.fullShow(payto_layout) - s = payto_loop() - #droid.fullDismiss() - - elif s == 'receive': - make_bitmap(receive_addr) - droid.fullShow(qr_layout(receive_addr)) - s = receive_loop() - - elif s == 'contacts': - make_bitmap(contact_addr) - droid.fullShow(qr_layout(contact_addr)) - s = contacts_loop() - - elif s == 'settings': - #droid.fullShow(settings_layout) - s = settings_loop() - #droid.fullDismiss() - else: - break - -droid.makeToast("Bye!") diff --git a/client/electrum_text_320.png b/client/electrum_text_320.png deleted file mode 100644 index 4a8f8375d22649ba464aec1f98fd196d7d415f42..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4634 zcmZu#c{mhM*PjhzvM;ZF4-t`NG>FKWHOny8QFf-0$UfH6Vkt{f#zdByAyY#t+fZ2| z`xeCri7=zW#NeCvpYN~txzF9s^W1ZvbI$Lad+xdI>}bsklY{{P0A5=g3l{(Yc#gf+ zfpW4(O({@b3k)fTcT+)*~DYXHD8;s16Z;8B@4 zo5&So>tM51-?;h?wIMQ_ehxtE;tT?)+hk&5#G+$HlCpGD>)0Q(_P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up3$B{ZM*RX-G;mV zkb|;3%nL?1W|#q4yb+GVX#9AZvz68-7{I9ev=((o zoqUp^$VkAjI723`a?8i(zz^XWLpvNJUk$1Nov~DH4C@CQi=v-&4d9EW^%uOYy55eX zVy|V?VM+^sY+@%fDG+L@-kX!2pf=T^eB>PsE)$S6F}FiAfIlatX-id51(2LepQ*`< zHW?2z`zegM{ED(hd{}d~{GKhWPVtuPb{k4hE-I1&n<709GtY z;fa(LnYi{AerS(=06(0o;vKOwTvjC3j$Kf9ngmQ=wOgnOIE*$A4h0YS_A&-ISA2KOduyrcP< zKOADKeJonu$l)<$b#-ZwZ{4w1meK(~?BHI_f(h^}XnWidXc+DuQVjflV&MBEW5LXv zrkh0;c}(_I8zj1>(}8k|Oh~iVa-lTc?3S5yZEkAL`emPN+ocZyS*0t2h%Z(Z!+?Hn zeg>bye>isK-mu!l~g5~2|;D>h9 z4qyoT!}`>m_VVvbk0r`k#_VXMx+47~H!5gT;kefuAE{IXL!4npYmz({<=r)yvH#KW z2*eao@F5C`Z&%xl&+=GmuC}FY1A<0hc(y>(A`3I~1UbHyJD+lm8Hl?IWq{4!)iYDJ zhi5^uy3o=qk_pHMjXdHTb&0ike5r~G)TDWhe+3hH2{TM5z^NebqYtRqNIX5Ev1-hN z_?YW;EV4e5?58TsO4jdluD+hzw=YPIG`EjD`&+i-&>hY8=34HT>5J)v>g1t(yt}Y& z!Ce`P`?iVLzw?lgiEk(Xdc1dKnd*k5wha=kiO;uPe%$}wGyM+unF&Kz8`IGeqOJZQOL8UuVjVAr)QfL$-zZ>uigCepN(=6 ot|AYN{%1ww|EnCC_(Oh&uwO~#S67$VRT_Y;rK80Qb9Bc40gA1&6aWAK diff --git a/client/gui.py b/client/gui.py deleted file mode 100644 index 77acdd1..0000000 --- a/client/gui.py +++ /dev/null @@ -1,1265 +0,0 @@ -#!/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 . - -import datetime -import thread, time, ast, sys, re -import socket, traceback -import pygtk -pygtk.require('2.0') -import gtk, gobject -import pyqrnative -from decimal import Decimal - -gtk.gdk.threads_init() -APP_NAME = "Electrum" -import platform -MONOSPACE_FONT = 'Lucida Console' if platform.system() == 'Windows' else 'monospace' - -from wallet import format_satoshis -from interface import DEFAULT_SERVERS - -def numbify(entry, is_int = False): - text = entry.get_text().strip() - chars = '0123456789' - if not is_int: chars +='.' - s = ''.join([i for i in text if i in chars]) - if not is_int: - if '.' in s: - p = s.find('.') - s = s.replace('.','') - s = s[:p] + '.' + s[p:p+8] - try: - amount = int( Decimal(s) * 100000000 ) - except: - amount = None - else: - try: - amount = int( s ) - except: - amount = None - entry.set_text(s) - return amount - - - - -def show_seed_dialog(wallet, password, parent): - import mnemonic - try: - seed = wallet.pw_decode( wallet.seed, password) - except: - show_message("Incorrect password") - return - dialog = gtk.MessageDialog( - parent = parent, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_OK, - message_format = "Your wallet generation seed is:\n\n" + seed \ - + "\n\nPlease keep it in a safe place; if you lose it, you will not be able to restore your wallet.\n\n" \ - + "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:\n\n\"" + ' '.join(mnemonic.mn_encode(seed)) + "\"" ) - dialog.set_title("Seed") - dialog.show() - dialog.run() - dialog.destroy() - -def restore_create_dialog(wallet): - - # ask if the user wants to create a new wallet, or recover from a seed. - # if he wants to recover, and nothing is found, do not create wallet - dialog = gtk.Dialog("electrum", parent=None, - flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, - buttons= ("create", 0, "restore",1, "cancel",2) ) - - label = gtk.Label("Wallet file not found.\nDo you want to create a new wallet,\n or to restore an existing one?" ) - label.show() - dialog.vbox.pack_start(label) - dialog.show() - r = dialog.run() - dialog.destroy() - - if r==2: return False - - is_recovery = (r==1) - - # ask for the server. - if not run_network_dialog( wallet, parent=None ): return False - - if not is_recovery: - - wallet.new_seed(None) - # generate first key - wallet.init_mpk( wallet.seed ) - wallet.up_to_date_event.clear() - wallet.update() - - # run a dialog indicating the seed, ask the user to remember it - show_seed_dialog(wallet, None, None) - - #ask for password - change_password_dialog(wallet, None, None) - else: - # ask for seed and gap. - run_recovery_dialog( wallet ) - - dialog = gtk.MessageDialog( - parent = None, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_CANCEL, - message_format = "Please wait..." ) - dialog.show() - - def recover_thread( wallet, dialog ): - wallet.init_mpk( wallet.seed ) # not encrypted at this point - wallet.up_to_date_event.clear() - wallet.update() - - if wallet.is_found(): - # history and addressbook - wallet.update_tx_history() - wallet.fill_addressbook() - print "recovery successful" - - gobject.idle_add( dialog.destroy ) - - thread.start_new_thread( recover_thread, ( wallet, dialog ) ) - r = dialog.run() - dialog.destroy() - if r==gtk.RESPONSE_CANCEL: return False - if not wallet.is_found: - show_message("No transactions found for this seed") - - wallet.save() - return True - - -def run_recovery_dialog(wallet): - message = "Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet." - dialog = gtk.MessageDialog( - parent = None, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_OK_CANCEL, - message_format = message) - - vbox = dialog.vbox - dialog.set_default_response(gtk.RESPONSE_OK) - - # ask seed, server and gap in the same dialog - seed_box = gtk.HBox() - seed_label = gtk.Label('Seed or mnemonic:') - seed_label.set_size_request(150,-1) - seed_box.pack_start(seed_label, False, False, 10) - seed_label.show() - seed_entry = gtk.Entry() - seed_entry.show() - seed_entry.set_size_request(450,-1) - seed_box.pack_start(seed_entry, False, False, 10) - add_help_button(seed_box, '.') - seed_box.show() - vbox.pack_start(seed_box, False, False, 5) - - gap = gtk.HBox() - gap_label = gtk.Label('Gap limit:') - gap_label.set_size_request(150,10) - gap_label.show() - gap.pack_start(gap_label,False, False, 10) - gap_entry = gtk.Entry() - gap_entry.set_text("%d"%wallet.gap_limit) - gap_entry.connect('changed', numbify, True) - gap_entry.show() - gap.pack_start(gap_entry,False,False, 10) - add_help_button(gap, 'The maximum gap that is allowed between unused addresses in your wallet. During wallet recovery, this parameter is used to decide when to stop the recovery process. If you increase this value, you will need to remember it in order to be able to recover your wallet from seed.') - gap.show() - vbox.pack_start(gap, False,False, 5) - - dialog.show() - r = dialog.run() - gap = gap_entry.get_text() - seed = seed_entry.get_text() - dialog.destroy() - - if r==gtk.RESPONSE_CANCEL: - sys.exit(1) - try: - gap = int(gap) - except: - show_message("error") - sys.exit(1) - - try: - seed.decode('hex') - except: - import mnemonic - print "not hex, trying decode" - seed = mnemonic.mn_decode( seed.split(' ') ) - if not seed: - show_message("no seed") - sys.exit(1) - - wallet.seed = seed - wallet.gap_limit = gap - wallet.save() - - - -def run_settings_dialog(wallet, parent): - - message = "Here are the settings of your wallet. For more explanations, click on the question mark buttons next to each input field." - - dialog = gtk.MessageDialog( - parent = parent, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_OK_CANCEL, - message_format = message) - - image = gtk.Image() - image.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_DIALOG) - image.show() - dialog.set_image(image) - dialog.set_title("Settings") - - vbox = dialog.vbox - dialog.set_default_response(gtk.RESPONSE_OK) - - fee = gtk.HBox() - fee_entry = gtk.Entry() - fee_label = gtk.Label('Transaction fee:') - fee_label.set_size_request(150,10) - fee_label.show() - fee.pack_start(fee_label,False, False, 10) - fee_entry.set_text( str( Decimal(wallet.fee) /100000000 ) ) - fee_entry.connect('changed', numbify, False) - fee_entry.show() - fee.pack_start(fee_entry,False,False, 10) - add_help_button(fee, 'Fee per transaction input. Transactions involving multiple inputs tend to have a higher fee. Recommended value:0.0005') - fee.show() - vbox.pack_start(fee, False,False, 5) - - dialog.show() - r = dialog.run() - fee = fee_entry.get_text() - - dialog.destroy() - if r==gtk.RESPONSE_CANCEL: - return - - try: - fee = int( 100000000 * Decimal(fee) ) - except: - show_message("error") - return - - wallet.fee = fee - wallet.save() - - - - -def run_network_dialog( wallet, parent ): - image = gtk.Image() - image.set_from_stock(gtk.STOCK_NETWORK, gtk.ICON_SIZE_DIALOG) - interface = wallet.interface - if parent: - if interface.is_connected: - status = "Connected to %s:%d\n%d blocks\nresponse time: %f"%(interface.host, interface.port, wallet.blocks, interface.rtime) - else: - status = "Not connected" - server = wallet.server - else: - import random - status = "Please choose a server." - server = random.choice( DEFAULT_SERVERS ) - - plist = {} - for item in wallet.interface.servers: - host, pp = item - z = {} - for item2 in pp: - protocol, port = item2 - z[protocol] = port - plist[host] = z - - dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, - gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, status) - dialog.set_title("Server") - dialog.set_image(image) - image.show() - - vbox = dialog.vbox - host_box = gtk.HBox() - host_label = gtk.Label('Connect to:') - host_label.set_size_request(100,-1) - host_label.show() - host_box.pack_start(host_label, False, False, 10) - host_entry = gtk.Entry() - host_entry.set_size_request(200,-1) - host_entry.set_text(server) - host_entry.show() - host_box.pack_start(host_entry, False, False, 10) - add_help_button(host_box, 'The name and port number of your Electrum server, separated by a colon. Example: "ecdsa.org:50000". If no port number is provided, port 50000 will be tried. Some servers allow you to connect through http (port 80) or https (port 443)') - host_box.show() - - - p_box = gtk.HBox(False, 10) - p_box.show() - - p_label = gtk.Label('Protocol:') - p_label.set_size_request(100,-1) - p_label.show() - p_box.pack_start(p_label, False, False, 10) - - radio1 = gtk.RadioButton(None, "tcp") - p_box.pack_start(radio1, True, True, 0) - radio1.show() - radio2 = gtk.RadioButton(radio1, "http") - p_box.pack_start(radio2, True, True, 0) - radio2.show() - radio3 = gtk.RadioButton(radio1, "native") - p_box.pack_start(radio3, True, True, 0) - radio3.show() - - def current_line(): - return unicode(host_entry.get_text()).split(':') - - def set_button(protocol): - if protocol == 't': - radio1.set_active(1) - elif protocol == 'h': - radio2.set_active(1) - elif protocol == 'n': - radio3.set_active(1) - - def set_protocol(protocol): - host = current_line()[0] - pp = plist[host] - if protocol not in pp.keys(): - protocol = pp.keys()[0] - set_button(protocol) - port = pp[protocol] - host_entry.set_text( host + ':' + port + ':' + protocol) - - radio1.connect("toggled", lambda x,y:set_protocol('t'), "radio button 1") - radio2.connect("toggled", lambda x,y:set_protocol('h'), "radio button 1") - radio3.connect("toggled", lambda x,y:set_protocol('n'), "radio button 1") - - server_list = gtk.ListStore(str) - for host in plist.keys(): - server_list.append([host]) - - treeview = gtk.TreeView(model=server_list) - treeview.show() - - tvcolumn = gtk.TreeViewColumn('Active servers') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 0) - - scroll = gtk.ScrolledWindow() - scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) - scroll.add(treeview) - scroll.show() - - vbox.pack_start(host_box, False,False, 5) - vbox.pack_start(p_box, True, True, 0) - vbox.pack_start(scroll) - - def my_treeview_cb(treeview): - path, view_column = treeview.get_cursor() - host = server_list.get_value( server_list.get_iter(path), 0) - - pp = plist[host] - if 't' in pp.keys(): - protocol = 't' - else: - protocol = pp.keys()[0] - port = pp[protocol] - host_entry.set_text( host + ':' + port + ':' + protocol) - set_button(protocol) - - treeview.connect('cursor-changed', my_treeview_cb) - - dialog.show() - r = dialog.run() - server = host_entry.get_text() - dialog.destroy() - - if r==gtk.RESPONSE_CANCEL: - return False - - try: - wallet.set_server(server) - except: - show_message("error:" + server) - return False - - if parent: - wallet.save() - return True - - - -def show_message(message, parent=None): - dialog = gtk.MessageDialog( - parent = parent, - flags = gtk.DIALOG_MODAL, - buttons = gtk.BUTTONS_CLOSE, - message_format = message ) - dialog.show() - dialog.run() - dialog.destroy() - -def password_line(label): - password = gtk.HBox() - password_label = gtk.Label(label) - password_label.set_size_request(120,10) - password_label.show() - password.pack_start(password_label,False, False, 10) - password_entry = gtk.Entry() - password_entry.set_size_request(300,-1) - password_entry.set_visibility(False) - password_entry.show() - password.pack_start(password_entry,False,False, 10) - password.show() - return password, password_entry - -def password_dialog(parent): - dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, - gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, "Please enter your password.") - dialog.get_image().set_visible(False) - current_pw, current_pw_entry = password_line('Password:') - current_pw_entry.connect("activate", lambda entry, dialog, response: dialog.response(response), dialog, gtk.RESPONSE_OK) - dialog.vbox.pack_start(current_pw, False, True, 0) - dialog.show() - result = dialog.run() - pw = current_pw_entry.get_text() - dialog.destroy() - if result != gtk.RESPONSE_CANCEL: return pw - -def change_password_dialog(wallet, parent, icon): - if parent: - msg = 'Your wallet is encrypted. Use this dialog to change the password. To disable wallet encryption, enter an empty new password.' if wallet.use_encryption else 'Your wallet keys are not encrypted' - else: - msg = "Please choose a password to encrypt your wallet keys" - - dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) - dialog.set_title("Change password") - image = gtk.Image() - image.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_DIALOG) - image.show() - dialog.set_image(image) - - if wallet.use_encryption: - current_pw, current_pw_entry = password_line('Current password:') - dialog.vbox.pack_start(current_pw, False, True, 0) - - password, password_entry = password_line('New password:') - dialog.vbox.pack_start(password, False, True, 5) - password2, password2_entry = password_line('Confirm password:') - dialog.vbox.pack_start(password2, False, True, 5) - - dialog.show() - result = dialog.run() - password = current_pw_entry.get_text() if wallet.use_encryption else None - new_password = password_entry.get_text() - new_password2 = password2_entry.get_text() - dialog.destroy() - if result == gtk.RESPONSE_CANCEL: - return - - try: - seed = wallet.pw_decode( wallet.seed, password) - except: - show_message("Incorrect password") - return - - if new_password != new_password2: - show_message("passwords do not match") - return - - wallet.update_password(seed, new_password) - - if icon: - if wallet.use_encryption: - icon.set_tooltip_text('wallet is encrypted') - else: - icon.set_tooltip_text('wallet is unencrypted') - - -def add_help_button(hbox, message): - button = gtk.Button('?') - button.connect("clicked", lambda x: show_message(message)) - button.show() - hbox.pack_start(button,False, False) - - -class MyWindow(gtk.Window): __gsignals__ = dict( mykeypress = (gobject.SIGNAL_RUN_LAST | gobject.SIGNAL_ACTION, None, (str,)) ) - -gobject.type_register(MyWindow) -gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.W, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+W') -gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.Q, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+Q') - - -class ElectrumWindow: - - def show_message(self, msg): - show_message(msg, self.window) - - def __init__(self, wallet): - self.wallet = wallet - self.funds_error = False # True if not enough funds - - self.window = MyWindow(gtk.WINDOW_TOPLEVEL) - self.window.set_title(APP_NAME + " " + self.wallet.electrum_version) - self.window.connect("destroy", gtk.main_quit) - self.window.set_border_width(0) - self.window.connect('mykeypress', gtk.main_quit) - self.window.set_default_size(720, 350) - - vbox = gtk.VBox() - - self.notebook = gtk.Notebook() - self.create_history_tab() - self.create_send_tab() - self.create_recv_tab() - self.create_book_tab() - self.create_about_tab() - self.notebook.show() - vbox.pack_start(self.notebook, True, True, 2) - - self.status_bar = gtk.Statusbar() - vbox.pack_start(self.status_bar, False, False, 0) - - self.status_image = gtk.Image() - self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) - self.status_image.set_alignment(True, 0.5 ) - self.status_image.show() - - self.network_button = gtk.Button() - self.network_button.connect("clicked", lambda x: run_network_dialog(self.wallet, self.window) ) - self.network_button.add(self.status_image) - self.network_button.set_relief(gtk.RELIEF_NONE) - self.network_button.show() - self.status_bar.pack_end(self.network_button, False, False) - - def seedb(w, wallet): - if wallet.use_encryption: - password = password_dialog(self.window) - if not password: return - else: password = None - show_seed_dialog(wallet, password, self.window) - button = gtk.Button('S') - button.connect("clicked", seedb, wallet ) - button.set_relief(gtk.RELIEF_NONE) - button.show() - self.status_bar.pack_end(button,False, False) - - settings_icon = gtk.Image() - settings_icon.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_MENU) - settings_icon.set_alignment(0.5, 0.5) - settings_icon.set_size_request(16,16 ) - settings_icon.show() - - prefs_button = gtk.Button() - prefs_button.connect("clicked", lambda x: run_settings_dialog(self.wallet, self.window) ) - prefs_button.add(settings_icon) - prefs_button.set_tooltip_text("Settings") - prefs_button.set_relief(gtk.RELIEF_NONE) - prefs_button.show() - self.status_bar.pack_end(prefs_button,False,False) - - pw_icon = gtk.Image() - pw_icon.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_MENU) - pw_icon.set_alignment(0.5, 0.5) - pw_icon.set_size_request(16,16 ) - pw_icon.show() - - password_button = gtk.Button() - password_button.connect("clicked", lambda x: change_password_dialog(self.wallet, self.window, pw_icon)) - password_button.add(pw_icon) - password_button.set_relief(gtk.RELIEF_NONE) - password_button.show() - self.status_bar.pack_end(password_button,False,False) - - self.window.add(vbox) - self.window.show_all() - #self.fee_box.hide() - - self.context_id = self.status_bar.get_context_id("statusbar") - self.update_status_bar() - - def update_status_bar_thread(): - while True: - gobject.idle_add( self.update_status_bar ) - time.sleep(0.5) - - - def check_recipient_thread(): - old_r = '' - while True: - time.sleep(0.5) - if self.payto_entry.is_focus(): - continue - r = self.payto_entry.get_text() - if r != old_r: - old_r = r - r = r.strip() - if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): - try: - to_address = self.wallet.get_alias(r, interactive=False) - except: - continue - if to_address: - s = r + ' <' + to_address + '>' - gobject.idle_add( lambda: self.payto_entry.set_text(s) ) - - - thread.start_new_thread(update_status_bar_thread, ()) - thread.start_new_thread(check_recipient_thread, ()) - self.notebook.set_current_page(0) - - - def add_tab(self, page, name): - tab_label = gtk.Label(name) - tab_label.show() - self.notebook.append_page(page, tab_label) - - - def create_send_tab(self): - - page = vbox = gtk.VBox() - page.show() - - payto = gtk.HBox() - payto_label = gtk.Label('Pay to:') - payto_label.set_size_request(100,-1) - payto.pack_start(payto_label, False) - payto_entry = gtk.Entry() - payto_entry.set_size_request(450, 26) - payto.pack_start(payto_entry, False) - vbox.pack_start(payto, False, False, 5) - - message = gtk.HBox() - message_label = gtk.Label('Description:') - message_label.set_size_request(100,-1) - message.pack_start(message_label, False) - message_entry = gtk.Entry() - message_entry.set_size_request(450, 26) - message.pack_start(message_entry, False) - vbox.pack_start(message, False, False, 5) - - amount_box = gtk.HBox() - amount_label = gtk.Label('Amount:') - amount_label.set_size_request(100,-1) - amount_box.pack_start(amount_label, False) - amount_entry = gtk.Entry() - amount_entry.set_size_request(120, -1) - amount_box.pack_start(amount_entry, False) - vbox.pack_start(amount_box, False, False, 5) - - self.fee_box = fee_box = gtk.HBox() - fee_label = gtk.Label('Fee:') - fee_label.set_size_request(100,-1) - fee_box.pack_start(fee_label, False) - fee_entry = gtk.Entry() - fee_entry.set_size_request(60, 26) - fee_box.pack_start(fee_entry, False) - vbox.pack_start(fee_box, False, False, 5) - - end_box = gtk.HBox() - empty_label = gtk.Label('') - empty_label.set_size_request(100,-1) - end_box.pack_start(empty_label, False) - send_button = gtk.Button("Send") - send_button.show() - end_box.pack_start(send_button, False, False, 0) - clear_button = gtk.Button("Clear") - clear_button.show() - end_box.pack_start(clear_button, False, False, 15) - send_button.connect("clicked", self.do_send, (payto_entry, message_entry, amount_entry, fee_entry)) - clear_button.connect("clicked", self.do_clear, (payto_entry, message_entry, amount_entry, fee_entry)) - - vbox.pack_start(end_box, False, False, 5) - - # display this line only if there is a signature - payto_sig = gtk.HBox() - payto_sig_id = gtk.Label('') - payto_sig.pack_start(payto_sig_id, False) - vbox.pack_start(payto_sig, True, True, 5) - - - self.user_fee = False - - def entry_changed( entry, is_fee ): - self.funds_error = False - amount = numbify(amount_entry) - fee = numbify(fee_entry) - if not is_fee: fee = None - if amount is None: - return - inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) - if not is_fee: - fee_entry.set_text( str( Decimal( fee ) / 100000000 ) ) - self.fee_box.show() - if inputs: - amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) - fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) - send_button.set_sensitive(True) - else: - send_button.set_sensitive(False) - amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) - fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) - self.funds_error = True - - amount_entry.connect('changed', entry_changed, False) - fee_entry.connect('changed', entry_changed, True) - - self.payto_entry = payto_entry - self.payto_fee_entry = fee_entry - self.payto_sig_id = payto_sig_id - self.payto_sig = payto_sig - self.amount_entry = amount_entry - self.message_entry = message_entry - self.add_tab(page, 'Send') - - def set_frozen(self,entry,frozen): - if frozen: - entry.set_editable(False) - entry.set_has_frame(False) - entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#eeeeee")) - else: - entry.set_editable(True) - entry.set_has_frame(True) - entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#ffffff")) - - def set_url(self, url): - payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) - self.notebook.set_current_page(1) - self.payto_entry.set_text(payto) - self.message_entry.set_text(message) - self.amount_entry.set_text(amount) - if identity: - self.set_frozen(self.payto_entry,True) - self.set_frozen(self.amount_entry,True) - self.set_frozen(self.message_entry,True) - self.payto_sig_id.set_text( ' The bitcoin URI was signed by ' + identity ) - else: - self.payto_sig.set_visible(False) - - def create_about_tab(self): - import pango - page = gtk.VBox() - page.show() - tv = gtk.TextView() - tv.set_editable(False) - tv.set_cursor_visible(False) - tv.modify_font(pango.FontDescription(MONOSPACE_FONT)) - page.pack_start(tv) - self.info = tv.get_buffer() - self.add_tab(page, 'Wall') - - def do_clear(self, w, data): - self.payto_sig.set_visible(False) - self.payto_fee_entry.set_text('') - for entry in [self.payto_entry,self.amount_entry,self.message_entry]: - self.set_frozen(entry,False) - entry.set_text('') - - def question(self,msg): - dialog = gtk.MessageDialog( self.window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) - dialog.show() - result = dialog.run() - dialog.destroy() - return result == gtk.RESPONSE_OK - - def do_send(self, w, data): - payto_entry, label_entry, amount_entry, fee_entry = data - label = label_entry.get_text() - r = payto_entry.get_text() - r = r.strip() - - m1 = re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r) - m2 = re.match('(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+) \<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) - - if m1: - to_address = self.wallet.get_alias(r, True, self.show_message, self.question) - if not to_address: - return - else: - self.update_sending_tab() - - elif m2: - to_address = m2.group(5) - else: - to_address = r - - if not self.wallet.is_valid(to_address): - self.show_message( "invalid bitcoin address:\n"+to_address) - return - - try: - amount = int( Decimal(amount_entry.get_text()) * 100000000 ) - except: - self.show_message( "invalid amount") - return - try: - fee = int( Decimal(fee_entry.get_text()) * 100000000 ) - except: - self.show_message( "invalid fee") - return - - if self.wallet.use_encryption: - password = password_dialog(self.window) - if not password: - return - else: - password = None - - try: - tx = self.wallet.mktx( to_address, amount, label, password, fee ) - except BaseException, e: - self.show_message(e.message) - return - - status, msg = self.wallet.sendtx( tx ) - if status: - self.show_message( "payment sent.\n" + msg ) - payto_entry.set_text("") - label_entry.set_text("") - amount_entry.set_text("") - fee_entry.set_text("") - #self.fee_box.hide() - self.update_sending_tab() - else: - self.show_message( msg ) - - - def treeview_button_press(self, treeview, event): - if event.type == gtk.gdk._2BUTTON_PRESS: - c = treeview.get_cursor()[0] - if treeview == self.history_treeview: - tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) - self.show_message(tx_details) - elif treeview == self.contacts_treeview: - m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) - a = self.wallet.aliases.get(m) - if a: - if a[0] in self.wallet.authorities.keys(): - s = self.wallet.authorities.get(a[0]) - else: - s = "self-signed" - msg = 'Alias: '+ m + '\nTarget address: '+ a[1] + '\n\nSigned by: ' + s + '\nSigning address:' + a[0] - self.show_message(msg) - - - def treeview_key_press(self, treeview, event): - c = treeview.get_cursor()[0] - if event.keyval == gtk.keysyms.Up: - if c and c[0] == 0: - treeview.parent.grab_focus() - treeview.set_cursor((0,)) - elif event.keyval == gtk.keysyms.Return: - if treeview == self.history_treeview: - tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) - self.show_message(tx_details) - elif treeview == self.contacts_treeview: - m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) - a = self.wallet.aliases.get(m) - if a: - if a[0] in self.wallet.authorities.keys(): - s = self.wallet.authorities.get(a[0]) - else: - s = "self" - msg = 'Alias:'+ m + '\n\nTarget: '+ a[1] + '\nSigned by: ' + s + '\nSigning address:' + a[0] - self.show_message(msg) - - return False - - def create_history_tab(self): - - self.history_list = gtk.ListStore(str, str, str, str, 'gboolean', str, str, str, str) - treeview = gtk.TreeView(model=self.history_list) - self.history_treeview = treeview - treeview.set_tooltip_column(7) - treeview.show() - treeview.connect('key-press-event', self.treeview_key_press) - treeview.connect('button-press-event', self.treeview_button_press) - - tvcolumn = gtk.TreeViewColumn('') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererPixbuf() - tvcolumn.pack_start(cell, False) - tvcolumn.set_attributes(cell, stock_id=1) - - tvcolumn = gtk.TreeViewColumn('Date') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 2) - - tvcolumn = gtk.TreeViewColumn('Description') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_property('foreground', 'grey') - cell.set_property('family', MONOSPACE_FONT) - cell.set_property('editable', True) - def edited_cb(cell, path, new_text, h_list): - tx = h_list.get_value( h_list.get_iter(path), 0) - self.wallet.labels[tx] = new_text - self.wallet.save() - self.update_history_tab() - cell.connect('edited', edited_cb, self.history_list) - def editing_started(cell, entry, path, h_list): - tx = h_list.get_value( h_list.get_iter(path), 0) - if not self.wallet.labels.get(tx): entry.set_text('') - cell.connect('editing-started', editing_started, self.history_list) - tvcolumn.set_expand(True) - tvcolumn.pack_start(cell, True) - tvcolumn.set_attributes(cell, text=3, foreground_set = 4) - - tvcolumn = gtk.TreeViewColumn('Amount') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_alignment(1, 0.5) - cell.set_property('family', MONOSPACE_FONT) - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 5) - - tvcolumn = gtk.TreeViewColumn('Balance') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_alignment(1, 0.5) - cell.set_property('family', MONOSPACE_FONT) - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 6) - - tvcolumn = gtk.TreeViewColumn('Tooltip') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, False) - tvcolumn.add_attribute(cell, 'text', 7) - tvcolumn.set_visible(False) - - scroll = gtk.ScrolledWindow() - scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) - scroll.add(treeview) - - self.add_tab(scroll, 'History') - self.update_history_tab() - - - def create_recv_tab(self): - self.recv_list = gtk.ListStore(str, str, str) - self.add_tab( self.make_address_list(True), 'Receive') - self.update_receiving_tab() - - def create_book_tab(self): - self.addressbook_list = gtk.ListStore(str, str, str) - self.add_tab( self.make_address_list(False), 'Contacts') - self.update_sending_tab() - - def make_address_list(self, is_recv): - liststore = self.recv_list if is_recv else self.addressbook_list - treeview = gtk.TreeView(model= liststore) - treeview.connect('key-press-event', self.treeview_key_press) - treeview.connect('button-press-event', self.treeview_button_press) - treeview.show() - if not is_recv: - self.contacts_treeview = treeview - - tvcolumn = gtk.TreeViewColumn('Address') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_property('family', MONOSPACE_FONT) - tvcolumn.pack_start(cell, True) - tvcolumn.add_attribute(cell, 'text', 0) - - tvcolumn = gtk.TreeViewColumn('Label') - tvcolumn.set_expand(True) - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - cell.set_property('editable', True) - def edited_cb2(cell, path, new_text, liststore): - address = liststore.get_value( liststore.get_iter(path), 0) - self.wallet.labels[address] = new_text - self.wallet.save() - self.wallet.update_tx_labels() - self.update_receiving_tab() - self.update_sending_tab() - self.update_history_tab() - cell.connect('edited', edited_cb2, liststore) - tvcolumn.pack_start(cell, True) - tvcolumn.add_attribute(cell, 'text', 1) - - tvcolumn = gtk.TreeViewColumn('Tx') - treeview.append_column(tvcolumn) - cell = gtk.CellRendererText() - tvcolumn.pack_start(cell, True) - tvcolumn.add_attribute(cell, 'text', 2) - - scroll = gtk.ScrolledWindow() - scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) - scroll.add(treeview) - - hbox = gtk.HBox() - if not is_recv: - button = gtk.Button("New") - button.connect("clicked", self.newaddress_dialog) - button.show() - hbox.pack_start(button,False) - - def showqrcode(w, treeview, liststore): - path, col = treeview.get_cursor() - if not path: return - address = liststore.get_value(liststore.get_iter(path), 0) - qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) - qr.addData(address) - qr.make() - boxsize = 7 - size = qr.getModuleCount()*boxsize - def area_expose_cb(area, event): - style = area.get_style() - k = qr.getModuleCount() - for r in range(k): - for c in range(k): - gc = style.black_gc if qr.isDark(r, c) else style.white_gc - area.window.draw_rectangle(gc, True, c*boxsize, r*boxsize, boxsize, boxsize) - area = gtk.DrawingArea() - area.set_size_request(size, size) - area.connect("expose-event", area_expose_cb) - area.show() - dialog = gtk.Dialog(address, parent=self.window, flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, buttons = ("ok",1)) - dialog.vbox.add(area) - dialog.run() - dialog.destroy() - - button = gtk.Button("QR") - button.connect("clicked", showqrcode, treeview, liststore) - button.show() - hbox.pack_start(button,False) - - button = gtk.Button("Copy to clipboard") - def copy2clipboard(w, treeview, liststore): - import platform - path, col = treeview.get_cursor() - if path: - address = liststore.get_value( liststore.get_iter(path), 0) - if platform.system() == 'Windows': - from Tkinter import Tk - r = Tk() - r.withdraw() - r.clipboard_clear() - r.clipboard_append( address ) - r.destroy() - else: - c = gtk.clipboard_get() - c.set_text( address ) - button.connect("clicked", copy2clipboard, treeview, liststore) - button.show() - hbox.pack_start(button,False) - - if not is_recv: - button = gtk.Button("Pay to") - def payto(w, treeview, liststore): - path, col = treeview.get_cursor() - if path: - address = liststore.get_value( liststore.get_iter(path), 0) - self.payto_entry.set_text( address ) - self.notebook.set_current_page(1) - self.amount_entry.grab_focus() - - button.connect("clicked", payto, treeview, liststore) - button.show() - hbox.pack_start(button,False) - - vbox = gtk.VBox() - vbox.pack_start(scroll,True) - vbox.pack_start(hbox, False) - return vbox - - def update_status_bar(self): - interface = self.wallet.interface - if self.funds_error: - text = "Not enough funds" - elif interface.is_connected: - self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks\nresponse time: %f"%(interface.host, interface.port, self.wallet.blocks, interface.rtime)) - if self.wallet.blocks == -1: - self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) - text = "Connecting..." - elif self.wallet.blocks == 0: - self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) - text = "Server not ready" - elif not self.wallet.up_to_date: - self.status_image.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU) - text = "Synchronizing..." - else: - self.status_image.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_MENU) - self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks\nresponse time: %f"%(interface.host, interface.port, self.wallet.blocks, interface.rtime)) - c, u = self.wallet.get_balance() - text = "Balance: %s "%( format_satoshis(c) ) - if u: text += "[%s unconfirmed]"%( format_satoshis(u,True).strip() ) - else: - self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) - self.network_button.set_tooltip_text("Trying to contact %s.\n%d blocks"%(interface.host, self.wallet.blocks)) - text = "Not connected" - - self.status_bar.pop(self.context_id) - self.status_bar.push(self.context_id, text) - - if self.wallet.was_updated and self.wallet.up_to_date: - self.update_history_tab() - self.update_receiving_tab() - # addressbook too... - self.info.set_text( self.wallet.banner ) - self.wallet.was_updated = False - - - def update_receiving_tab(self): - self.recv_list.clear() - for address in self.wallet.all_addresses(): - if self.wallet.is_change(address):continue - label = self.wallet.labels.get(address) - n = 0 - h = self.wallet.history.get(address,[]) - for item in h: - if not item['is_input'] : n=n+1 - tx = "None" if n==0 else "%d"%n - self.recv_list.append((address, label, tx )) - - def update_sending_tab(self): - # detect addresses that are not mine in history, add them here... - self.addressbook_list.clear() - for alias, v in self.wallet.aliases.items(): - s, target = v - label = self.wallet.labels.get(alias) - self.addressbook_list.append((alias, label, '-')) - - for address in self.wallet.addressbook: - label = self.wallet.labels.get(address) - n = 0 - for item in self.wallet.tx_history.values(): - if address in item['outputs'] : n=n+1 - tx = "None" if n==0 else "%d"%n - self.addressbook_list.append((address, label, tx)) - - def update_history_tab(self): - cursor = self.history_treeview.get_cursor()[0] - self.history_list.clear() - balance = 0 - for tx in self.wallet.get_tx_history(): - tx_hash = tx['tx_hash'] - if tx['height']: - conf = self.wallet.blocks - tx['height'] + 1 - time_str = datetime.datetime.fromtimestamp( tx['timestamp']).isoformat(' ')[:-3] - conf_icon = gtk.STOCK_APPLY - else: - conf = 0 - time_str = 'pending' - conf_icon = gtk.STOCK_EXECUTE - v = tx['value'] - balance += v - label = self.wallet.labels.get(tx_hash) - is_default_label = (label == '') or (label is None) - if is_default_label: label = tx['default_label'] - tooltip = tx_hash + "\n%d confirmations"%conf - - # tx = self.wallet.tx_history.get(tx_hash) - details = "Transaction Details:\n\n" \ - + "Transaction ID:\n" + tx_hash + "\n\n" \ - + "Status: %d confirmations\n\n"%conf \ - + "Date: %s\n\n"%time_str \ - + "Inputs:\n-"+ '\n-'.join(tx['inputs']) + "\n\n" \ - + "Outputs:\n-"+ '\n-'.join(tx['outputs']) - r = self.wallet.receipts.get(tx_hash) - if r: - details += "\n_______________________________________" \ - + '\n\nSigned URI: ' + r[2] \ - + "\n\nSigned by: " + r[0] \ - + '\n\nSignature: ' + r[1] - - - self.history_list.prepend( [tx_hash, conf_icon, time_str, label, is_default_label, - format_satoshis(v,True), format_satoshis(balance), tooltip, details] ) - if cursor: self.history_treeview.set_cursor( cursor ) - - - - def newaddress_dialog(self, w): - - title = "New Contact" - dialog = gtk.Dialog(title, parent=self.window, - flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, - buttons= ("cancel", 0, "ok",1) ) - dialog.show() - - label = gtk.HBox() - label_label = gtk.Label('Label:') - label_label.set_size_request(120,10) - label_label.show() - label.pack_start(label_label) - label_entry = gtk.Entry() - label_entry.show() - label.pack_start(label_entry) - label.show() - dialog.vbox.pack_start(label, False, True, 5) - - address = gtk.HBox() - address_label = gtk.Label('Address:') - address_label.set_size_request(120,10) - address_label.show() - address.pack_start(address_label) - address_entry = gtk.Entry() - address_entry.show() - address.pack_start(address_entry) - address.show() - dialog.vbox.pack_start(address, False, True, 5) - - result = dialog.run() - address = address_entry.get_text() - label = label_entry.get_text() - dialog.destroy() - - if result == 1: - if self.wallet.is_valid(address): - self.wallet.addressbook.append(address) - if label: self.wallet.labels[address] = label - self.wallet.save() - self.update_sending_tab() - else: - errorDialog = gtk.MessageDialog( - parent=self.window, - flags=gtk.DIALOG_MODAL, - buttons= gtk.BUTTONS_CLOSE, - message_format = "Invalid address") - errorDialog.show() - errorDialog.run() - errorDialog.destroy() - - - -class ElectrumGui(): - - def __init__(self, wallet): - self.wallet = wallet - - def main(self, url=None): - ew = ElectrumWindow(self.wallet) - if url: ew.set_url(url) - gtk.main() - - def restore_or_create(self): - return restore_create_dialog(self.wallet) diff --git a/client/gui_qt.py b/client/gui_qt.py deleted file mode 100644 index 2620ac0..0000000 --- a/client/gui_qt.py +++ /dev/null @@ -1,1057 +0,0 @@ -#!/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 . - -import sys, time, datetime, re - -# todo: see PySide - -from PyQt4.QtGui import * -from PyQt4.QtCore import * -import PyQt4.QtCore as QtCore -import PyQt4.QtGui as QtGui -from interface import DEFAULT_SERVERS - -try: - import icons_rc -except: - print "Could not import icons_rp.py" - print "Please generate it with: 'pyrcc4 icons.qrc -o icons_rc.py'" - sys.exit(1) - -from wallet import format_satoshis -from decimal import Decimal - -import platform -MONOSPACE_FONT = 'Lucida Console' if platform.system() == 'Windows' else 'monospace' - - -def numbify(entry, is_int = False): - text = unicode(entry.text()).strip() - chars = '0123456789' - if not is_int: chars +='.' - s = ''.join([i for i in text if i in chars]) - if not is_int: - if '.' in s: - p = s.find('.') - s = s.replace('.','') - s = s[:p] + '.' + s[p:p+8] - try: - amount = int( Decimal(s) * 100000000 ) - except: - amount = None - else: - try: - amount = int( s ) - except: - amount = None - entry.setText(s) - return amount - - -class Timer(QtCore.QThread): - def run(self): - while True: - self.emit(QtCore.SIGNAL('timersignal')) - time.sleep(0.5) - -class EnterButton(QPushButton): - def __init__(self, text, func): - QPushButton.__init__(self, text) - self.func = func - self.clicked.connect(func) - - def keyPressEvent(self, e): - if e.key() == QtCore.Qt.Key_Return: - apply(self.func,()) - -class StatusBarButton(QPushButton): - def __init__(self, icon, tooltip, func): - QPushButton.__init__(self, icon, '') - self.setToolTip(tooltip) - self.setFlat(True) - self.setMaximumWidth(25) - self.clicked.connect(func) - self.func = func - - def keyPressEvent(self, e): - if e.key() == QtCore.Qt.Key_Return: - apply(self.func,()) - - -class QRCodeWidget(QWidget): - - def __init__(self, addr): - import pyqrnative - super(QRCodeWidget, self).__init__() - self.addr = addr - self.setGeometry(300, 300, 350, 350) - self.qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) - self.qr.addData(addr) - self.qr.make() - - def paintEvent(self, e): - qp = QtGui.QPainter() - qp.begin(self) - boxsize = 7 - size = self.qr.getModuleCount()*boxsize - k = self.qr.getModuleCount() - black = QColor(0, 0, 0, 255) - white = QColor(255, 255, 255, 255) - for r in range(k): - for c in range(k): - if self.qr.isDark(r, c): - qp.setBrush(black) - qp.setPen(black) - else: - qp.setBrush(white) - qp.setPen(white) - qp.drawRect(c*boxsize, r*boxsize, boxsize, boxsize) - qp.end() - - - -def ok_cancel_buttons(dialog): - hbox = QHBoxLayout() - hbox.addStretch(1) - b = QPushButton("OK") - hbox.addWidget(b) - b.clicked.connect(dialog.accept) - b = QPushButton("Cancel") - hbox.addWidget(b) - b.clicked.connect(dialog.reject) - return hbox - - -class ElectrumWindow(QMainWindow): - - def __init__(self, wallet): - QMainWindow.__init__(self) - self.wallet = wallet - self.wallet.gui_callback = self.update_callback - - self.funds_error = False - - self.tabs = tabs = QTabWidget(self) - tabs.addTab(self.create_history_tab(), 'History') - tabs.addTab(self.create_send_tab(), 'Send') - tabs.addTab(self.create_receive_tab(), 'Receive') - tabs.addTab(self.create_contacts_tab(),'Contacts') - tabs.addTab(self.create_wall_tab(), 'Wall') - tabs.setMinimumSize(600, 400) - tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - self.setCentralWidget(tabs) - self.create_status_bar() - self.setGeometry(100,100,840,400) - self.setWindowTitle( 'Electrum ' + self.wallet.electrum_version ) - self.show() - - QShortcut(QKeySequence("Ctrl+W"), self, self.close) - QShortcut(QKeySequence("Ctrl+Q"), self, self.close) - QShortcut(QKeySequence("Ctrl+PgUp"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() - 1 )%tabs.count() )) - QShortcut(QKeySequence("Ctrl+PgDown"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() + 1 )%tabs.count() )) - - self.connect(self, QtCore.SIGNAL('updatesignal'), self.update_wallet) - - - def connect_slots(self, sender): - self.connect(sender, QtCore.SIGNAL('timersignal'), self.check_recipient) - self.previous_payto_e='' - - def check_recipient(self): - if self.payto_e.hasFocus(): - return - r = unicode( self.payto_e.text() ) - if r != self.previous_payto_e: - self.previous_payto_e = r - r = r.strip() - if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): - try: - to_address = self.wallet.get_alias(r, True, self.show_message, self.question) - except: - return - if to_address: - s = r + ' <' + to_address + '>' - self.payto_e.setText(s) - - - def update_callback(self): - self.emit(QtCore.SIGNAL('updatesignal')) - - def update_wallet(self): - if self.wallet.interface.is_connected: - if self.wallet.blocks == -1: - text = "Connecting..." - icon = QIcon(":icons/status_disconnected.png") - elif self.wallet.blocks == 0: - text = "Server not ready" - icon = QIcon(":icons/status_disconnected.png") - elif not self.wallet.up_to_date: - text = "Synchronizing..." - icon = QIcon(":icons/status_waiting.png") - else: - c, u = self.wallet.get_balance() - text = "Balance: %s "%( format_satoshis(c) ) - if u: text += "[%s unconfirmed]"%( format_satoshis(u,True).strip() ) - icon = QIcon(":icons/status_connected.png") - else: - text = "Not connected" - icon = QIcon(":icons/status_disconnected.png") - - if self.funds_error: - text = "Not enough funds" - - self.statusBar().showMessage(text) - self.status_button.setIcon( icon ) - - if self.wallet.up_to_date: - self.textbox.setText( self.wallet.banner ) - self.update_history_tab() - self.update_receive_tab() - self.update_contacts_tab() - - - def create_history_tab(self): - self.history_list = w = QTreeWidget(self) - #print w.getContentsMargins() - w.setColumnCount(5) - w.setColumnWidth(0, 40) - w.setColumnWidth(1, 140) - w.setColumnWidth(2, 350) - w.setColumnWidth(3, 140) - w.setColumnWidth(4, 140) - w.setHeaderLabels( [ '', 'Date', 'Description', 'Amount', 'Balance'] ) - self.connect(w, SIGNAL('itemActivated(QTreeWidgetItem*, int)'), self.tx_details) - self.connect(w, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.tx_label_clicked) - self.connect(w, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), self.tx_label_changed) - return w - - def tx_details(self, item, column): - tx_hash = str(item.toolTip(0)) - tx = self.wallet.tx_history.get(tx_hash) - - if tx['height']: - conf = self.wallet.blocks - tx['height'] + 1 - time_str = datetime.datetime.fromtimestamp( tx['timestamp']).isoformat(' ')[:-3] - else: - conf = 0 - time_str = 'pending' - - tx_details = "Transaction Details:\n\n" \ - + "Transaction ID:\n" + tx_hash + "\n\n" \ - + "Status: %d confirmations\n\n"%conf \ - + "Date: %s\n\n"%time_str \ - + "Inputs:\n-"+ '\n-'.join(tx['inputs']) + "\n\n" \ - + "Outputs:\n-"+ '\n-'.join(tx['outputs']) - - r = self.wallet.receipts.get(tx_hash) - if r: - tx_details += "\n_______________________________________" \ - + '\n\nSigned URI: ' + r[2] \ - + "\n\nSigned by: " + r[0] \ - + '\n\nSignature: ' + r[1] - - QMessageBox.information(self, 'Details', tx_details, 'OK') - - - def tx_label_clicked(self, item, column): - if column==2 and item.isSelected(): - tx_hash = str(item.toolTip(0)) - self.is_edit=True - #if not self.wallet.labels.get(tx_hash): item.setText(2,'') - item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - self.history_list.editItem( item, column ) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - self.is_edit=False - - def tx_label_changed(self, item, column): - if self.is_edit: - return - self.is_edit=True - tx_hash = str(item.toolTip(0)) - tx = self.wallet.tx_history.get(tx_hash) - s = self.wallet.labels.get(tx_hash) - text = unicode( item.text(2) ) - if text: - self.wallet.labels[tx_hash] = text - item.setForeground(2, QBrush(QColor('black'))) - else: - if s: self.wallet.labels.pop(tx_hash) - text = tx['default_label'] - item.setText(2, text) - item.setForeground(2, QBrush(QColor('gray'))) - self.is_edit=False - - def address_label_clicked(self, item, column, l): - if column==1 and item.isSelected(): - item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - l.editItem( item, column ) - item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) - - def address_label_changed(self, item, column, l): - addr = unicode( item.text(0) ) - text = unicode( item.text(1) ) - if text: - self.wallet.labels[addr] = text - else: - s = self.wallet.labels.get(addr) - if s: self.wallet.labels.pop(addr) - self.update_history_tab() - - def update_history_tab(self): - self.history_list.clear() - balance = 0 - for tx in self.wallet.get_tx_history(): - tx_hash = tx['tx_hash'] - if tx['height']: - conf = self.wallet.blocks - tx['height'] + 1 - time_str = datetime.datetime.fromtimestamp( tx['timestamp']).isoformat(' ')[:-3] - icon = QIcon(":icons/confirmed.png") - else: - conf = 0 - time_str = 'pending' - icon = QIcon(":icons/unconfirmed.png") - v = tx['value'] - balance += v - label = self.wallet.labels.get(tx_hash) - is_default_label = (label == '') or (label is None) - if is_default_label: label = tx['default_label'] - - item = QTreeWidgetItem( [ '', time_str, label, format_satoshis(v,True), format_satoshis(balance)] ) - item.setFont(2, QFont(MONOSPACE_FONT)) - item.setFont(3, QFont(MONOSPACE_FONT)) - item.setFont(4, QFont(MONOSPACE_FONT)) - item.setToolTip(0, tx_hash) - if is_default_label: - item.setForeground(2, QBrush(QColor('grey'))) - - item.setIcon(0, icon) - self.history_list.insertTopLevelItem(0,item) - - - def create_send_tab(self): - w = QWidget() - - grid = QGridLayout() - grid.setSpacing(8) - grid.setColumnMinimumWidth(3,300) - grid.setColumnStretch(4,1) - - self.payto_e = QLineEdit() - grid.addWidget(QLabel('Pay to'), 1, 0) - grid.addWidget(self.payto_e, 1, 1, 1, 3) - - self.message_e = QLineEdit() - grid.addWidget(QLabel('Description'), 2, 0) - grid.addWidget(self.message_e, 2, 1, 1, 3) - - self.amount_e = QLineEdit() - grid.addWidget(QLabel('Amount'), 3, 0) - grid.addWidget(self.amount_e, 3, 1, 1, 2) - - self.fee_e = QLineEdit() - grid.addWidget(QLabel('Fee'), 4, 0) - grid.addWidget(self.fee_e, 4, 1, 1, 2) - - b = EnterButton("Send", self.do_send) - grid.addWidget(b, 5, 1) - - b = EnterButton("Clear",self.do_clear) - grid.addWidget(b, 5, 2) - - self.payto_sig = QLabel('') - grid.addWidget(self.payto_sig, 6, 0, 1, 4) - - w.setLayout(grid) - w.show() - - w2 = QWidget() - vbox = QVBoxLayout() - vbox.addWidget(w) - vbox.addStretch(1) - w2.setLayout(vbox) - - def entry_changed( is_fee ): - self.funds_error = False - amount = numbify(self.amount_e) - fee = numbify(self.fee_e) - if not is_fee: fee = None - if amount is None: - return - inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) - if not is_fee: - self.fee_e.setText( str( Decimal( fee ) / 100000000 ) ) - if inputs: - palette = QPalette() - palette.setColor(self.amount_e.foregroundRole(), QColor('black')) - else: - palette = QPalette() - palette.setColor(self.amount_e.foregroundRole(), QColor('red')) - self.funds_error = True - self.amount_e.setPalette(palette) - self.fee_e.setPalette(palette) - - self.amount_e.textChanged.connect(lambda: entry_changed(False) ) - self.fee_e.textChanged.connect(lambda: entry_changed(True) ) - - return w2 - - def do_send(self): - - label = unicode( self.message_e.text() ) - r = unicode( self.payto_e.text() ) - r = r.strip() - - m1 = re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r) - m2 = re.match('(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+) \<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) - - if m1: - to_address = self.wallet.get_alias(r, True, self.show_message, self.question) - if not to_address: - return - elif m2: - to_address = m2.group(5) - else: - to_address = r - - if not self.wallet.is_valid(to_address): - QMessageBox.warning(self, 'Error', 'Invalid Bitcoin Address:\n'+to_address, 'OK') - return - - try: - amount = int( Decimal( unicode( self.amount_e.text())) * 100000000 ) - except: - QMessageBox.warning(self, 'Error', 'Invalid Amount', 'OK') - return - try: - fee = int( Decimal( unicode( self.fee_e.text())) * 100000000 ) - except: - QMessageBox.warning(self, 'Error', 'Invalid Fee', 'OK') - return - - if self.wallet.use_encryption: - password = self.password_dialog() - if not password: - return - else: - password = None - - try: - tx = self.wallet.mktx( to_address, amount, label, password, fee ) - except BaseException, e: - self.show_message(e.message) - return - - status, msg = self.wallet.sendtx( tx ) - if status: - QMessageBox.information(self, '', 'Payment sent.\n'+msg, 'OK') - self.do_clear() - self.update_contacts_tab() - else: - QMessageBox.warning(self, 'Error', msg, 'OK') - - - def set_url(self, url): - payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) - self.tabs.setCurrentIndex(1) - self.payto_e.setText(payto) - self.message_e.setText(message) - self.amount_e.setText(amount) - if identity: - self.set_frozen(self.payto_e,True) - self.set_frozen(self.amount_e,True) - self.set_frozen(self.message_e,True) - self.payto_sig.setText( ' The bitcoin URI was signed by ' + identity ) - else: - self.payto_sig.setVisible(False) - - def do_clear(self): - self.payto_sig.setVisible(False) - for e in [self.payto_e, self.message_e, self.amount_e, self.fee_e]: - e.setText('') - self.set_frozen(e,False) - - def set_frozen(self,entry,frozen): - if frozen: - entry.setReadOnly(True) - entry.setFrame(False) - palette = QPalette() - palette.setColor(entry.backgroundRole(), QColor('lightgray')) - entry.setPalette(palette) - else: - entry.setReadOnly(False) - entry.setFrame(True) - palette = QPalette() - palette.setColor(entry.backgroundRole(), QColor('white')) - entry.setPalette(palette) - - - def make_address_list(self, is_recv): - - l = QTreeWidget(self) - l.setColumnCount(3) - l.setColumnWidth(0, 350) - l.setColumnWidth(1, 330) - l.setColumnWidth(2, 20) - l.setHeaderLabels( ['Address', 'Label','Tx']) - - vbox = QVBoxLayout() - vbox.setMargin(0) - vbox.setSpacing(0) - vbox.addWidget(l) - - hbox = QHBoxLayout() - hbox.setMargin(0) - hbox.setSpacing(0) - - def get_addr(l): - i = l.currentItem() - if not i: return - addr = unicode( i.text(0) ) - return addr - - qrButton = EnterButton("QR",lambda: ElectrumWindow.showqrcode(get_addr(l))) - - def copy2clipboard(addr): - self.app.clipboard().setText(addr) - copyButton = EnterButton("Copy to Clipboard", lambda: copy2clipboard(get_addr(l))) - hbox.addWidget(qrButton) - hbox.addWidget(copyButton) - if not is_recv: - addButton = EnterButton("New", self.newaddress_dialog) - hbox.addWidget(addButton) - def payto(addr): - if not addr:return - self.tabs.setCurrentIndex(1) - self.payto_e.setText(addr) - self.amount_e.setFocus() - paytoButton = EnterButton('Pay to', lambda: payto(get_addr(l))) - hbox.addWidget(paytoButton) - hbox.addStretch(1) - buttons = QWidget() - buttons.setLayout(hbox) - vbox.addWidget(buttons) - - w = QWidget() - w.setLayout(vbox) - return w, l - - def create_receive_tab(self): - w, l = self.make_address_list(True) - self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l)) - self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l)) - self.receive_list = l - return w - - def create_contacts_tab(self): - w, l = self.make_address_list(False) - self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l)) - self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l)) - self.connect(l, SIGNAL('itemActivated(QTreeWidgetItem*, int)'), self.show_contact_details) - self.contacts_list = l - return w - - def update_receive_tab(self): - self.receive_list.clear() - for address in self.wallet.all_addresses(): - if self.wallet.is_change(address):continue - label = self.wallet.labels.get(address,'') - n = 0 - h = self.wallet.history.get(address,[]) - for item in h: - if not item['is_input'] : n=n+1 - tx = "None" if n==0 else "%d"%n - item = QTreeWidgetItem( [ address, label, tx] ) - item.setFont(0, QFont(MONOSPACE_FONT)) - self.receive_list.addTopLevelItem(item) - - def show_contact_details(self, item, column): - m = unicode(item.text(0)) - a = self.wallet.aliases.get(m) - if a: - if a[0] in self.wallet.authorities.keys(): - s = self.wallet.authorities.get(a[0]) - else: - s = "self-signed" - msg = 'Alias: '+ m + '\nTarget address: '+ a[1] + '\n\nSigned by: ' + s + '\nSigning address:' + a[0] - QMessageBox.information(self, 'Alias', msg, 'OK') - - def update_contacts_tab(self): - self.contacts_list.clear() - for alias, v in self.wallet.aliases.items(): - s, target = v - label = self.wallet.labels.get(alias,'') - item = QTreeWidgetItem( [ alias, label, '-'] ) - self.contacts_list.addTopLevelItem(item) - - for address in self.wallet.addressbook: - label = self.wallet.labels.get(address,'') - n = 0 - for item in self.wallet.tx_history.values(): - if address in item['outputs'] : n=n+1 - tx = "None" if n==0 else "%d"%n - item = QTreeWidgetItem( [ address, label, tx] ) - item.setFont(0, QFont(MONOSPACE_FONT)) - self.contacts_list.addTopLevelItem(item) - - - def create_wall_tab(self): - self.textbox = textbox = QTextEdit(self) - textbox.setFont(QFont(MONOSPACE_FONT)) - textbox.setReadOnly(True) - return textbox - - def create_status_bar(self): - sb = QStatusBar() - sb.setFixedHeight(35) - sb.addPermanentWidget( StatusBarButton( QIcon(":icons/lock.png"), "Password", lambda: self.change_password_dialog(self.wallet, self) ) ) - sb.addPermanentWidget( StatusBarButton( QIcon(":icons/preferences.png"), "Preferences", self.settings_dialog ) ) - sb.addPermanentWidget( StatusBarButton( QIcon(":icons/seed.png"), "Seed", lambda: self.show_seed_dialog(self.wallet, self) ) ) - self.status_button = StatusBarButton( QIcon(":icons/status_disconnected.png"), "Network", lambda: self.network_dialog(self.wallet, self) ) - sb.addPermanentWidget( self.status_button ) - self.setStatusBar(sb) - - def newaddress_dialog(self): - text, ok = QInputDialog.getText(self, 'New Contact', 'Address:') - address = unicode(text) - if ok: - if self.wallet.is_valid(address): - self.wallet.addressbook.append(address) - self.wallet.save() - self.update_contacts_tab() - else: - QMessageBox.warning(self, 'Error', 'Invalid Address', 'OK') - - @staticmethod - def show_seed_dialog(wallet, parent=None): - import mnemonic - if wallet.use_encryption: - password = parent.password_dialog() - if not password: return - else: - password = None - - try: - seed = wallet.pw_decode( wallet.seed, password) - except: - QMessageBox.warning(parent, 'Error', 'Invalid Password', 'OK') - return - - msg = "Your wallet generation seed is:\n\n" + seed \ - + "\n\nPlease keep it in a safe place; if you lose it, you will not be able to restore your wallet.\n\n" \ - + "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:\n\n\"" \ - + ' '.join(mnemonic.mn_encode(seed)) + "\"" - - QMessageBox.information(parent, 'Seed', msg, 'OK') - ElectrumWindow.showqrcode(seed) - - @staticmethod - def showqrcode(address): - if not address: return - d = QDialog(None) - d.setModal(1) - d.setWindowTitle(address) - d.setMinimumSize(270, 300) - vbox = QVBoxLayout() - vbox.addWidget(QRCodeWidget(address)) - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - d.exec_() - - def question(self, msg): - return QMessageBox.question(self, 'Message', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes - - def show_message(self, msg): - QMessageBox.information(self, 'Message', msg, 'OK') - - def password_dialog(self ): - d = QDialog(self) - d.setModal(1) - - pw = QLineEdit() - pw.setEchoMode(2) - - vbox = QVBoxLayout() - msg = 'Please enter your password' - vbox.addWidget(QLabel(msg)) - - grid = QGridLayout() - grid.setSpacing(8) - grid.addWidget(QLabel('Password'), 1, 0) - grid.addWidget(pw, 1, 1) - vbox.addLayout(grid) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - return unicode(pw.text()) - - @staticmethod - def change_password_dialog( wallet, parent=None ): - d = QDialog(parent) - d.setModal(1) - - pw = QLineEdit() - pw.setEchoMode(2) - new_pw = QLineEdit() - new_pw.setEchoMode(2) - conf_pw = QLineEdit() - conf_pw.setEchoMode(2) - - vbox = QVBoxLayout() - if parent: - msg = 'Your wallet is encrypted. Use this dialog to change your password.\nTo disable wallet encryption, enter an empty new password.' if wallet.use_encryption else 'Your wallet keys are not encrypted' - else: - msg = "Please choose a password to encrypt your wallet keys.\nLeave these fields empty if you want to disable encryption." - vbox.addWidget(QLabel(msg)) - - grid = QGridLayout() - grid.setSpacing(8) - - if wallet.use_encryption: - grid.addWidget(QLabel('Password'), 1, 0) - grid.addWidget(pw, 1, 1) - - grid.addWidget(QLabel('New Password'), 2, 0) - grid.addWidget(new_pw, 2, 1) - - grid.addWidget(QLabel('Confirm Password'), 3, 0) - grid.addWidget(conf_pw, 3, 1) - vbox.addLayout(grid) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - - password = unicode(pw.text()) if wallet.use_encryption else None - new_password = unicode(new_pw.text()) - new_password2 = unicode(conf_pw.text()) - - try: - seed = wallet.pw_decode( wallet.seed, password) - except: - QMessageBox.warning(parent, 'Error', 'Incorrect Password', 'OK') - return - - if new_password != new_password2: - QMessageBox.warning(parent, 'Error', 'Passwords do not match', 'OK') - return - - wallet.update_password(seed, new_password) - - @staticmethod - def seed_dialog(wallet, parent=None): - d = QDialog(parent) - d.setModal(1) - - vbox = QVBoxLayout() - msg = "Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet." - vbox.addWidget(QLabel(msg)) - - grid = QGridLayout() - grid.setSpacing(8) - - seed_e = QLineEdit() - grid.addWidget(QLabel('Seed or mnemonic'), 1, 0) - grid.addWidget(seed_e, 1, 1) - - gap_e = QLineEdit() - gap_e.setText("5") - grid.addWidget(QLabel('Gap limit'), 2, 0) - grid.addWidget(gap_e, 2, 1) - gap_e.textChanged.connect(lambda: numbify(gap_e,True)) - vbox.addLayout(grid) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - - try: - gap = int(unicode(gap_e.text())) - except: - QMessageBox.warning(None, 'Error', 'error', 'OK') - sys.exit(0) - - try: - seed = unicode(seed_e.text()) - seed.decode('hex') - except: - import mnemonic - print "not hex, trying decode" - try: - seed = mnemonic.mn_decode( seed.split(' ') ) - except: - QMessageBox.warning(None, 'Error', 'I cannot decode this', 'OK') - sys.exit(0) - if not seed: - QMessageBox.warning(None, 'Error', 'no seed', 'OK') - sys.exit(0) - - wallet.seed = str(seed) - #print repr(wallet.seed) - wallet.gap_limit = gap - return True - - - def settings_dialog(self): - d = QDialog(self) - d.setModal(1) - - vbox = QVBoxLayout() - - msg = 'Here are the settings of your wallet.' - vbox.addWidget(QLabel(msg)) - - grid = QGridLayout() - grid.setSpacing(8) - - fee_e = QLineEdit() - fee_e.setText("%s"% str( Decimal( self.wallet.fee)/100000000 ) ) - grid.addWidget(QLabel('Fee per tx. input'), 2, 0) - grid.addWidget(fee_e, 2, 1) - vbox.addLayout(grid) - fee_e.textChanged.connect(lambda: numbify(fee_e,False)) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - - fee = unicode(fee_e.text()) - try: - fee = int( 100000000 * Decimal(fee) ) - except: - QMessageBox.warning(self, 'Error', 'Invalid value:%s'%fee, 'OK') - return - - self.wallet.fee = fee - self.wallet.save() - - @staticmethod - def network_dialog(wallet, parent=None): - interface = wallet.interface - if parent: - if interface.is_connected: - status = "Connected to %s:%d\n%d blocks\nresponse time: %f"%(interface.host, interface.port, wallet.blocks, interface.rtime) - else: - status = "Not connected" - server = wallet.server - else: - import random - status = "Please choose a server." - server = random.choice( DEFAULT_SERVERS ) - - plist = {} - for item in wallet.interface.servers: - host, pp = item - z = {} - for item2 in pp: - protocol, port = item2 - z[protocol] = port - plist[host] = z - - d = QDialog(parent) - d.setModal(1) - d.setWindowTitle('Server') - d.setMinimumSize(375, 20) - - vbox = QVBoxLayout() - vbox.setSpacing(20) - - hbox = QHBoxLayout() - l = QLabel() - l.setPixmap(QPixmap(":icons/network.png")) - hbox.addWidget(l) - hbox.addWidget(QLabel(status)) - - vbox.addLayout(hbox) - - hbox = QHBoxLayout() - host_line = QLineEdit() - host_line.setText(server) - hbox.addWidget(QLabel('Connect to:')) - hbox.addWidget(host_line) - vbox.addLayout(hbox) - - hbox = QHBoxLayout() - - buttonGroup = QGroupBox("protocol") - radio1 = QRadioButton("tcp", buttonGroup) - radio2 = QRadioButton("http", buttonGroup) - radio3 = QRadioButton("native", buttonGroup) - - def current_line(): - return unicode(host_line.text()).split(':') - - def set_button(protocol): - if protocol == 't': - radio1.setChecked(1) - elif protocol == 'h': - radio2.setChecked(1) - elif protocol == 'n': - radio3.setChecked(1) - - def set_protocol(protocol): - host = current_line()[0] - pp = plist[host] - if protocol not in pp.keys(): - protocol = pp.keys()[0] - set_button(protocol) - port = pp[protocol] - host_line.setText( host + ':' + port + ':' + protocol) - - radio1.clicked.connect(lambda x: set_protocol('t') ) - radio2.clicked.connect(lambda x: set_protocol('h') ) - radio3.clicked.connect(lambda x: set_protocol('n') ) - - set_button(current_line()[2]) - - hbox.addWidget(QLabel('Protocol:')) - hbox.addWidget(radio1) - hbox.addWidget(radio2) - hbox.addWidget(radio3) - - vbox.addLayout(hbox) - - if wallet.interface.servers: - servers_list = QTreeWidget(parent) - servers_list.setHeaderLabels( [ 'Active servers'] ) - servers_list.setMaximumHeight(150) - for host in plist.keys(): - servers_list.addTopLevelItem(QTreeWidgetItem( [ host ] )) - - def do_set_line(x): - host = unicode(x.text(0)) - pp = plist[host] - if 't' in pp.keys(): - protocol = 't' - else: - protocol = pp.keys()[0] - port = pp[protocol] - host_line.setText( host + ':' + port + ':' + protocol) - set_button(protocol) - - servers_list.connect(servers_list, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), do_set_line) - vbox.addWidget(servers_list) - else: - hbox = QHBoxLayout() - hbox.addWidget(QLabel('No nodes available')) - b = EnterButton("Find nodes", lambda: wallet.interface.get_servers(wallet) ) - hbox.addWidget(b) - vbox.addLayout(hbox) - - vbox.addLayout(ok_cancel_buttons(d)) - d.setLayout(vbox) - - if not d.exec_(): return - server = unicode( host_line.text() ) - - try: - wallet.set_server(server) - except: - QMessageBox.information(None, 'Error', 'error', 'OK') - if parent == None: - sys.exit(1) - else: - return - - return True - - - -class ElectrumGui(): - - def __init__(self, wallet): - self.wallet = wallet - self.app = QApplication(sys.argv) - - def waiting_dialog(self): - - s = Timer() - s.start() - w = QDialog() - w.resize(200, 70) - w.setWindowTitle('Electrum') - l = QLabel('') - vbox = QVBoxLayout() - vbox.addWidget(l) - w.setLayout(vbox) - w.show() - def f(): - if self.wallet.up_to_date: w.close() - else: - l.setText("Please wait...\nGenerating addresses: %d"%len(self.wallet.all_addresses())) - pass - w.connect(s, QtCore.SIGNAL('timersignal'), f) - self.wallet.interface.poke() - w.exec_() - w.destroy() - - - def restore_or_create(self): - - msg = "Wallet file not found.\nDo you want to create a new wallet,\n or to restore an existing one?" - r = QMessageBox.question(None, 'Message', msg, 'create', 'restore', 'cancel', 0, 2) - if r==2: return False - - is_recovery = (r==1) - wallet = self.wallet - # ask for the server. - if not ElectrumWindow.network_dialog( wallet, parent=None ): return False - - if not is_recovery: - wallet.new_seed(None) - wallet.init_mpk( wallet.seed ) - wallet.up_to_date_event.clear() - wallet.up_to_date = False - self.waiting_dialog() - # run a dialog indicating the seed, ask the user to remember it - ElectrumWindow.show_seed_dialog(wallet) - #ask for password - ElectrumWindow.change_password_dialog(wallet) - else: - # ask for seed and gap. - if not ElectrumWindow.seed_dialog( wallet ): return False - wallet.init_mpk( wallet.seed ) - wallet.up_to_date_event.clear() - wallet.up_to_date = False - self.waiting_dialog() - if wallet.is_found(): - # history and addressbook - wallet.update_tx_history() - wallet.fill_addressbook() - print "recovery successful" - wallet.save() - else: - QMessageBox.information(None, 'Message', "No transactions found for this seed", 'OK') - - wallet.save() - return True - - def main(self,url): - s = Timer() - s.start() - w = ElectrumWindow(self.wallet) - if url: w.set_url(url) - w.app = self.app - w.connect_slots(s) - w.update_wallet() - - self.app.exec_() diff --git a/client/icons.qrc b/client/icons.qrc deleted file mode 100644 index 9ee8acd..0000000 --- a/client/icons.qrc +++ /dev/null @@ -1,13 +0,0 @@ - - - icons/confirmed.png - icons/lock.png - icons/preferences.png - icons/seed.png - icons/status_connected.png - icons/status_disconnected.png - icons/status_waiting.png - icons/unconfirmed.png - icons/network.png - - diff --git a/client/icons/confirmed.png b/client/icons/confirmed.png deleted file mode 100644 index 901be189a6fca7d9d3f7efb2c5a494a5ec0b93ea..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1267 zcmV(G);P$p;kx>XP_3jgx;v64^oz(P$HEdhO+fyVb;Y=l74C{pt9#P8qQwek6QMfeLMqOrjB0$Q+a&4L{Z z=RFkkU|?98OxT=6^U06h)`N*X$pkkF0Pu~cqPZ)ITN>WjG;c~?G3pyuS7jB8w{IJH zjHWMoV%DA|RZDW1On79#69!lqaFD{`_D}f7-RJi8p5}D`AVP7P|4425cl9s5Q0g0} z!h?ZH6AQ$ejWu=QLRvW*JdjKI^Qwy*m#?VKV_}W}V`zQ6Yab5o__L|!1Zs!R$XXB^ zO6TWJ60!#u1^^ErMnzeLzo)kQy+D*&2YdO9no0WH$75eUy=G~VkQ^{P5HWaYf9u7A zXx`p-sOuN3U}kTaK=gOu*#mpOZoic71d{<4=8!e;Xw9O$vdX-@M3h~&Wc)X4>z7WK z6$VQNAelqfKT04|t3TsGVB+4du?ZC`O!{{`;3T~mw@5Ro=xDIHm`UMkn* zaZqI+6iJ030tr9}fXRgi6E3IWk%iwr_u5bIM@?@BcZ}82BQKem%~)w>-Nob7TvnA6 z4Qny@l`P0Y1qlM+!9fZsFM*_U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>ee-Q zGz3%w-sil2syp%);NJcr8jJI^8Vy458wDQPyW^$?Jo)JPRYK%;fRBIXvv`x?TwtNz zKxU;2+-U&Lc~s7Q|A>i@ww2fP^x_xprM2!~NM3 zR5@?7GJIK;so7)v?eHuM4ae-sX)a$=<|Ct3N{MaHm3QXWq9iMXWh})5Q?V3wY63;Mi3ln zF_1s{{i4jUgH1H zOGL}5grcAU2&l^YewgK}ml{CZacq!oeEY!z*7jGsYF@y$g{>bf32TwFc)(ziD(V~} zS~OKe0umH44lx!Hb2{@lqefBmMGRsT!C+KS1REvTsDzD6*f_<;88+@YyD}730(=Bm zf9%Lhj9s}2FhxOxB1_VuG6+Nj42T62gNczSL2MHfm9R@Q4s`?{ii{%!g7?@sCQ34F zlwxdrI<-<|^6!T`EH5u#TN8ayR33QtH@`%F`)dY~nXS!?_Ff3^E>wDoaLz@aPzVOmuFsYXv2l_^ALM07^*Q%Bq - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/icons/network.png b/client/icons/network.png deleted file mode 100644 index 6a5bcba970804a39a01ba4cae4bd6992a2330e38..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3031 zcmV;|3n=u7P)>JN&I zR5ThHbX&x5BDXOb$5K*9p=4ST#ivAam%B6fo_@HqOHz{cq7cF80K>UEJ3D*+_dI^* z&eEwW@8-?DtF8ZkFJSoF&;Knd528rWKnQ^l6kR^{fk41}MMEH{kLN>ijVj*z;v*cY7K7r*yjkV zt_6z5!+E#Piev8=KTYszRvkj^FhLpEvJC~autJqM^R08s#v9jngM#;-JSfe~b8=<@ zRp_Xs+_0gSP|QdSrMPEV#{Ycp-${~$pn)qRKou~k*cCIW#YoRM=bXV>NA3eEprR}^ zG6EJASl73P5QI>O4MiBn-2jjzDIr`D0Wp?gbD(dy-fYjGkqCWelW0v75`avuPt zx2sH}>7(a#DIbDHU;5k^9!Rc?2fWY8ni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icons/preferences.png b/client/icons/preferences.png deleted file mode 100644 index 2596f3cc5eb500a4b866146ef4f2b1706b72aae4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1691 zcmV;M24wk(P)=DcaWxi`ep6rD=zgT=e~d=}J9qD}F$_7s`q|YEizS5|`skn}iemkqnuhA>Od1<& z=YcQ>WkT0iZmPWbV2+uh-byL8_=oQjLC}*;zuzomWMsVd>efH}ZYuNorrL6oIjMW? znu z41xgw9vKz^GrPEWi7*-oA~F_6Vv?E3$;q+mz&20RaP^I~Jj=4(E1oXTk|YW3U$pnJ zEE6yq41(EYg4vV=_Z_#UD9W)1&8y$8PBgK?^E{tGDL_O?L@*FSzq?RW!s;astnJYp^X-R2bN=hP949J?SuC07++xh!lQcAI>;f(^8WiLFv;wb~mvXidCk?Dl0sMz=BzGyTWS(lmN z=wx|xl$Mm{XU~|ywYZwaKp@bqC`yY)nH!a_R=Or#h5B6QY_Kecru~g$Nr{QRvSnp69NF1iOKYb?m#;8nq}$Qn-i9ZhSOAB^0axn@F&GSeX*O6^ zO=ms{FkNilv2`=Ya@F?COvB&_R#VE_lM+e_OwEcSlKYZ!b45N-c>PSl{TvcRe z{`~1Bl+PKFjOy^M;gOM9&#hf0*fMOeB&On%BZtM}qGDZURu)4w4euOyC)(fN-*o7M zzf?^LDBO7V7aWUsE0(4kiwn}on55v&&^_$`;G~*BrJN^c4!+3qeD&IjH9}gN6=}&< zgu+3H(ik*N1IH#{Z^K?O5{VQX{`g4${Ta;L*pd9>SI!-`S`yyf_Tp?)QGOZ;kIDFM zD1wWZZ>vNZJ9_o#7XO?3-hN9I#RF&0oD*X)2_D}7Mk8SagCX1t-Giczqj*UXuhZ%N z1OOZW8)S zHh%sO($Ui1C12>dbbX-fy?OvbTzXknxWf5`1%W^yb>_?*)?hGV?wmZ{JLFjdptZB3 z`BBL0xKoPgn2XR~~QeV6I-fA>O^#_A6y9AjWHGTx#F7>!&lb zGM!hiT(ghM5=*H@`}+DuJs!`YyFPyifE))<5+5297YiW4GG|$CY@jzFia`Q^kBf~9 z6QG|iU6Pw$khewCXwJ92msfm!p~nMY9Dp*>0il$F5Q6wACm_rNh7+2|PXH(Y4S<^E l$YMN$9w~0B#@8tT`frm{0s2>vdAk4r002ovPDHLkV1m?gC#wJe diff --git a/client/icons/seed.png b/client/icons/seed.png deleted file mode 100644 index 54c38b6abb1b81f353b1bfcc4635fc4cf8cb165e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10322 zcmY*G(TCGEosZ`os>VCTH>XuYUWgE zsAmcAT_rRUhk!^Z5wub0iOibUJ_pb>_o-*|&H5-TV1=U2)pNiULj})fW3Ycs^U{C* zj-xG(stmLWpuJW^Jc+=2hA^;>4%)_3{h=BFff2s^9(fW@)jNAZGWUY=nYys+EIbdt zMkx^XOQ=L(tYMcDl=p^r2}p!z?UPO{=}I+SayU@$m!uBy8z7{0eNddt=zY~UG{)gbV0xidjs~XoM#m3`AFx<;$hAetLcGbUVL{X?AmMgK6 z8-DcZ>~CDTyqMoH%kq0*Ue`|2~py^0e`aTihSdu2LIZmNwW^`%BLxh5h)K{-&3wru0PJ) z`@oMNd_csmo_`9p>JuU@Ktoj@zOcqz9#P=eDJUEr%$m%#$>N5{M46iHDqjhG z9B<-6+i!9Y2ts}T0pM+q)Lr`A7>mCzr&iHK4S~ z;vWc97>eRSzoqN-e^!B#h9ZWcxbyc5f^|X=883RybwAo>>@Fzn2L40f(-qhepccdmz*Fc_LR$&ArZ)$YKHZ;QLxXcY&<3nN3{l&2#J? zAIMhuM~Dc5h19ry#}UraOO)!z0uue;j}3*X6(95Le(R znS5AdDq!x8Tys9EMx}T0>s8cQ@SMz-0g@ay#E_qlWJ2yaqqD4X_X+dY4kG?O7rS+o zYqp{>qt_By$-jE;%KB6eob7|wAHi8Hv_4nfQkh_w{c0nz)_3MTt@U)*(*#Q?%hgvN2;Aovj#NWj2A~#

ERd2S{ zWV$rsDpZ18$3QP{oyf533S+3d3H+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G-7Pgme-I}VF%M4CVkR%~$wTOb?6=iYE<#m0m^j=pFH86)m3Y(-F&Fj z{c)EyY`nd&V3N~Q2t#xjq8taEFHsfyEJ7xNWEnb1kT4`VJ>}+&8|Lu%cmvpXb33fh zmP)Sbbg+OrJ45?EI?GVkfSCwn*@zuQqufr1ndxcQf%S2P8Qh)qeVmgMT)^%1aQb~5 z5fq^E{gF{FX+EcbtlMQ~VS&P{V`J+i!HA&qNmm3X-{kASG*^n02MF;7;EYD`*8|; zV_*im&2BfrT3l;!@@1O|XaRH!`99+NG{Z2-V0R3BB(fhT$}ry=|?3uUz&@QG}Z$BNGGSy2QpX@H~F(_v6FiaQHiX{vG@PybzJ- zI&cQ4EyD7r@MTr0wRb(wS+mz;zbqf*z0000 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - Lapo Calamandrei - - - - - Record - - - record - media - - - - - Jakub Steiner - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/icons/status_waiting.png b/client/icons/status_waiting.png deleted file mode 100644 index 41a4ea059a648484e6c4987bd90935f76ea051d2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1501 zcmV<31tR*1P)Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01ejw01ejxLMWSf00007bV*G`2iyY^ z3n2yMIGw!!00mu1L_t(Y$F){lY*bYgUFUIMGtIl%wC$bJ8Y!?gUg5poG1N4XS4ifBpFZfR%;yZ75RdD*+c zzrNnm1pxeB0hKFuJk1SbEpMh%tTJD|Zg8JQ82}LzuG77sd|%t`So}gd6W{gsv27QJ z?k!y&4hSLI0q7$tsCqc;V-tdhg28c%90^Mi0!k?uV_=MeQ3}pEay%OR9u00L+1uLQ z+0-8C-Pu_GN_}YYc7IK6@eh^d<4fLpX-V*|3KU@zb{{P*D_I;%+8|IcGy+Z2U}zjl z5x5E<1W4NwhOXfE`|}>1R4`xJnHfJ9?%!_YD@gs-8`4YkFZ~;n)o`t4gcXKaD;*!BK;r%r8IQ2JV?}_$}&(F{Q*q>`P<$AoAq?FfOsE*M_@$Bat zKWI49yy4u1fBHD1pp+nGOQdW8N~j!Gfj0^_>2Zwe%F+e~JxRHnvZ?8?o3KYCsD9$T z;`tAT_RN}5k(;(%2&s^=1yZ&I$Xya$Xb8tc%ieiE$8Vm0b5*572vPSlQfTpZ|D0K6 z$5%c!yCRVh$hA09wt~hPyrzaoijfgcu3oe2L&MM*B@`M57@_?FN+4s~f!B3OygG#| z6##+HzB+xrt3CGpK`Zti7hk4C^WK1NDW9#1<{y89B;?41xVE|Q_2BqY9>$0 z8xyGWc|O|E)zi24a&6zI2#4k1`9+UB5RD}Ycl+VkH_RSvK*8OU1O(JMXNo5V5w<%#^|QUtGMowLXnJ}if59EF6pGMB|5JixPEHS2>|IK$P75y$e+HV zFmnD#41kfn?uLQ`pq!hUSx`NWTVrz=)r1r8i1fAo)(XJRA~OVO0P5~bpJyx5vtOQ- zaX`v}c$tL&;AY`u6T1M^e|uHjS#(JJz-Bcx(P-;m+SqXb@Dz@x00000NkvXXu0mjf Dz+SxI diff --git a/client/icons/status_waiting.svg b/client/icons/status_waiting.svg deleted file mode 100644 index fb51a42..0000000 --- a/client/icons/status_waiting.svg +++ /dev/null @@ -1,397 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - Jakub Steiner - - - http://jimmac.musichall.cz - - View Refresh - - - reload - refresh - view - - - - - Ricardo 'Rick' González - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/icons/unconfirmed.png b/client/icons/unconfirmed.png deleted file mode 100644 index f8d87ed5f052ef2fa75365ee08acfd7933e38867..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1574 zcmV+>2HE+EP)Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01ejw01ejxLMWSf00007bV*G`2iyY^ z3m!5ATM~`{00pK=L_t(Y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V|sZy53GS1_1qjpcjuHR0b+QIX@5{X2v0EosFAOXYxr~srm z9t98qp#A*^MgYcd_wQdPO43%3tLJQYSI4E7H@vbTB_&zMv1~p7CK8DV@j=7!p+sDc z7yvomv74o7V!TZN3;?*&va-h_;jpLE;W(%$%4Gl{0Kxc{|60T-I31UOh;O9CHy%^{ Y1#Gf$Vc%2N4FCWD07*qoM6N<$f|hXf0{{R3 diff --git a/client/icons/unconfirmed.svg b/client/icons/unconfirmed.svg deleted file mode 100644 index 36560ca..0000000 --- a/client/icons/unconfirmed.svg +++ /dev/null @@ -1,562 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - Lapo Calamandrei - - - System Run - - - - run - launch - exec - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/interface.py b/client/interface.py deleted file mode 100644 index 21ea5a8..0000000 --- a/client/interface.py +++ /dev/null @@ -1,425 +0,0 @@ -#!/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 . - - -import random, socket, ast, re -import threading, traceback, sys, time, json, Queue - -DEFAULT_TIMEOUT = 5 -DEFAULT_SERVERS = [ 'ecdsa.org:50001:t', 'electrum.novit.ro:50001:t', 'electrum.bitcoins.sk:50001:t'] # list of default servers - - -def old_to_new(s): - s = s.replace("'blk_hash'", "'block_hash'") - s = s.replace("'pos'", "'index'") - s = s.replace("'nTime'", "'timestamp'") - s = s.replace("'is_in'", "'is_input'") - s = s.replace("'raw_scriptPubKey'","'raw_output_script'") - return s - - -class Interface(threading.Thread): - def __init__(self, host, port): - threading.Thread.__init__(self) - self.daemon = True - self.host = host - self.port = port - - self.servers = [] # actual list from IRC - self.rtime = 0 - - self.is_connected = True - self.poll_interval = 1 - - #json - self.message_id = 0 - self.responses = Queue.Queue() - self.methods = {} - - def poke(self): - # push a fake response so that the getting thread exits its loop - self.responses.put(None) - - def queue_json_response(self, c): - - #print "<--",c - msg_id = c.get('id') - error = c.get('error') - - if error: - print "received error:", c - return - - if msg_id is not None: - method, params = self.methods.pop(msg_id) - result = c.get('result') - else: - # notification - method = c.get('method') - params = c.get('params') - - if method == 'blockchain.numblocks.subscribe': - result = params[0] - params = [] - - elif method == 'blockchain.address.subscribe': - addr = params[0] - result = params[1] - params = [addr] - - self.responses.put({'method':method, 'params':params, 'result':result}) - - - - def subscribe(self, addresses): - messages = [] - for addr in addresses: - messages.append(('blockchain.address.subscribe', [addr])) - self.send(messages) - - - def get_servers(self, wallet): - # loop over default servers - # requesting servers could be an independent process - addresses = wallet.all_addresses() - version = wallet.electrum_version - - for server in DEFAULT_SERVERS: - print "connecting to", server - try: - self.host = server - self.start_session(addresses, version) - wallet.host = self.host - break - except socket.timeout: - continue - except socket.error: - continue - except: - traceback.print_exc(file=sys.stdout) - - - def start_session(self, addresses, version): - #print "Starting new session: %s:%d"%(self.host,self.port) - self.send([('server.version', [version]), ('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])]) - self.subscribe(addresses) - - -class PollingInterface(Interface): - """ non-persistent connection. synchronous calls""" - - def __init__(self, host, port): - Interface.__init__(self, host, port) - self.session_id = None - - def get_history(self, address): - self.send([('blockchain.address.get_history', [address] )]) - - def poll(self): - pass - #if is_new or wallet.remote_url: - # self.was_updated = True - # is_new = wallet.synchronize() - # wallet.update_tx_history() - # wallet.save() - # return is_new - #else: - # return False - - def run(self): - self.is_connected = True - while self.is_connected: - try: - if self.session_id: - self.poll() - time.sleep(self.poll_interval) - except socket.gaierror: - break - except socket.error: - break - except: - traceback.print_exc(file=sys.stdout) - break - - self.is_connected = False - self.poke() - - - - - - - - - -class HttpStratumInterface(PollingInterface): - - def poll(self): - self.send([]) - - def send(self, messages): - import urllib2, json, time, cookielib - - cj = cookielib.CookieJar() - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - urllib2.install_opener(opener) - - t1 = time.time() - - data = [] - for m in messages: - method, params = m - if type(params) != type([]): params = [params] - data.append( { 'method':method, 'id':self.message_id, 'params':params } ) - self.methods[self.message_id] = method, params - self.message_id += 1 - - if data: - data_json = json.dumps(data) - else: - # poll with GET - data_json = None - - host = 'http://%s:%d'%( self.host, self.port ) - headers = {'content-type': 'application/json'} - if self.session_id: - headers['cookie'] = 'SESSION=%s'%self.session_id - - req = urllib2.Request(host, data_json, headers) - response_stream = urllib2.urlopen(req) - - for index, cookie in enumerate(cj): - if cookie.name=='SESSION': - self.session_id = cookie.value - - response = response_stream.read() - if response: - response = json.loads( response ) - if type(response) is not type([]): - self.queue_json_response(response) - else: - for item in response: - self.queue_json_response(item) - - if response: - self.poll_interval = 1 - else: - if self.poll_interval < 15: - self.poll_interval += 1 - #print self.poll_interval, response - - self.rtime = time.time() - t1 - self.is_connected = True - - - - -class TcpStratumInterface(Interface): - """json-rpc over persistent TCP connection, asynchronous""" - - def __init__(self, host, port): - Interface.__init__(self, host, port) - self.s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) - self.s.settimeout(5) - self.s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) - try: - self.s.connect(( self.host, self.port)) - self.is_connected = True - except: - self.is_connected = False - print "not connected" - - def run(self): - try: - out = '' - while self.is_connected: - try: msg = self.s.recv(1024) - except socket.timeout: - continue - out += msg - if msg == '': - self.is_connected = False - print "disconnected." - - while True: - s = out.find('\n') - if s==-1: break - c = out[0:s] - out = out[s+1:] - c = json.loads(c) - self.queue_json_response(c) - - except: - traceback.print_exc(file=sys.stdout) - - self.is_connected = False - print "poking" - self.poke() - - def send(self, messages): - out = '' - for m in messages: - method, params = m - request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } ) - self.methods[self.message_id] = method, params - #print "-->",request - self.message_id += 1 - out += request + '\n' - self.s.send( out ) - - def get_history(self, addr): - self.send([('blockchain.address.get_history', [addr])]) - - - - - -class WalletSynchronizer(threading.Thread): - - def __init__(self, wallet, loop=False): - threading.Thread.__init__(self) - self.daemon = True - self.wallet = wallet - self.loop = loop - self.start_interface() - - - def handle_response(self, r): - if r is None: - return - - method = r['method'] - params = r['params'] - result = r['result'] - - if method == 'server.banner': - self.wallet.banner = result - self.wallet.was_updated = True - - elif method == 'server.peers.subscribe': - servers = [] - for item in result: - s = [] - host = item[1] - ports = [] - if len(item)>2: - for v in item[2]: - if re.match("[th]\d+",v): - ports.append((v[0],v[1:])) - if ports: - servers.append( (host, ports) ) - self.interface.servers = servers - - elif method == 'blockchain.address.subscribe': - addr = params[0] - self.wallet.receive_status_callback(addr, result) - - elif method == 'blockchain.address.get_history': - addr = params[0] - self.wallet.receive_history_callback(addr, result) - self.wallet.was_updated = True - - elif method == 'blockchain.transaction.broadcast': - self.wallet.tx_result = result - self.wallet.tx_event.set() - - elif method == 'blockchain.numblocks.subscribe': - self.wallet.blocks = result - - elif method == 'server.version': - pass - - else: - print "unknown message:", method, params, result - - - def start_interface(self): - try: - host, port, protocol = self.wallet.server.split(':') - port = int(port) - except: - self.wallet.pick_random_server() - host, port, protocol = self.wallet.server.split(':') - port = int(port) - - #print protocol, host, port - if protocol == 't': - InterfaceClass = TcpStratumInterface - elif protocol == 'h': - InterfaceClass = HttpStratumInterface - else: - print "unknown protocol" - InterfaceClass = TcpStratumInterface - - self.interface = InterfaceClass(host, port) - self.wallet.interface = self.interface - - with self.wallet.lock: - self.wallet.addresses_waiting_for_status = [] - self.wallet.addresses_waiting_for_history = [] - addresses = self.wallet.all_addresses() - version = self.wallet.electrum_version - for addr in addresses: - self.wallet.addresses_waiting_for_status.append(addr) - - try: - self.interface.start() - self.interface.start_session(addresses,version) - except: - self.interface.is_connected = False - - - def run(self): - import socket, time - while True: - while self.interface.is_connected: - new_addresses = self.wallet.synchronize() - if new_addresses: - self.interface.subscribe(new_addresses) - for addr in new_addresses: - with self.wallet.lock: - self.wallet.addresses_waiting_for_status.append(addr) - - if self.wallet.is_up_to_date(): - if not self.wallet.up_to_date: - self.wallet.up_to_date = True - self.wallet.was_updated = True - self.wallet.up_to_date_event.set() - else: - if self.wallet.up_to_date: - self.wallet.up_to_date = False - self.wallet.was_updated = True - - if self.wallet.was_updated: - self.wallet.gui_callback() - self.wallet.was_updated = False - - response = self.interface.responses.get() - self.handle_response(response) - - print "disconnected, gui callback" - self.wallet.gui_callback() - if self.loop: - time.sleep(5) - self.start_interface() - continue - else: - break - - - diff --git a/client/mnemonic.py b/client/mnemonic.py deleted file mode 100644 index 82d2624..0000000 --- a/client/mnemonic.py +++ /dev/null @@ -1,1689 +0,0 @@ -#!/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 . - - - -# list of words from http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/Contemporary_poetry - -words = [ -"like", -"just", -"love", -"know", -"never", -"want", -"time", -"out", -"there", -"make", -"look", -"eye", -"down", -"only", -"think", -"heart", -"back", -"then", -"into", -"about", -"more", -"away", -"still", -"them", -"take", -"thing", -"even", -"through", -"long", -"always", -"world", -"too", -"friend", -"tell", -"try", -"hand", -"thought", -"over", -"here", -"other", -"need", -"smile", -"again", -"much", -"cry", -"been", -"night", -"ever", -"little", -"said", -"end", -"some", -"those", -"around", -"mind", -"people", -"girl", -"leave", -"dream", -"left", -"turn", -"myself", -"give", -"nothing", -"really", -"off", -"before", -"something", -"find", -"walk", -"wish", -"good", -"once", -"place", -"ask", -"stop", -"keep", -"watch", -"seem", -"everything", -"wait", -"got", -"yet", -"made", -"remember", -"start", -"alone", -"run", -"hope", -"maybe", -"believe", -"body", -"hate", -"after", -"close", -"talk", -"stand", -"own", -"each", -"hurt", -"help", -"home", -"god", -"soul", -"new", -"many", -"two", -"inside", -"should", -"true", -"first", -"fear", -"mean", -"better", -"play", -"another", -"gone", -"change", -"use", -"wonder", -"someone", -"hair", -"cold", -"open", -"best", -"any", -"behind", -"happen", -"water", -"dark", -"laugh", -"stay", -"forever", -"name", -"work", -"show", -"sky", -"break", -"came", -"deep", -"door", -"put", -"black", -"together", -"upon", -"happy", -"such", -"great", -"white", -"matter", -"fill", -"past", -"please", -"burn", -"cause", -"enough", -"touch", -"moment", -"soon", -"voice", -"scream", -"anything", -"stare", -"sound", -"red", -"everyone", -"hide", -"kiss", -"truth", -"death", -"beautiful", -"mine", -"blood", -"broken", -"very", -"pass", -"next", -"forget", -"tree", -"wrong", -"air", -"mother", -"understand", -"lip", -"hit", -"wall", -"memory", -"sleep", -"free", -"high", -"realize", -"school", -"might", -"skin", -"sweet", -"perfect", -"blue", -"kill", -"breath", -"dance", -"against", -"fly", -"between", -"grow", -"strong", -"under", -"listen", -"bring", -"sometimes", -"speak", -"pull", -"person", -"become", -"family", -"begin", -"ground", -"real", -"small", -"father", -"sure", -"feet", -"rest", -"young", -"finally", -"land", -"across", -"today", -"different", -"guy", -"line", -"fire", -"reason", -"reach", -"second", -"slowly", -"write", -"eat", -"smell", -"mouth", -"step", -"learn", -"three", -"floor", -"promise", -"breathe", -"darkness", -"push", -"earth", -"guess", -"save", -"song", -"above", -"along", -"both", -"color", -"house", -"almost", -"sorry", -"anymore", -"brother", -"okay", -"dear", -"game", -"fade", -"already", -"apart", -"warm", -"beauty", -"heard", -"notice", -"question", -"shine", -"began", -"piece", -"whole", -"shadow", -"secret", -"street", -"within", -"finger", -"point", -"morning", -"whisper", -"child", -"moon", -"green", -"story", -"glass", -"kid", -"silence", -"since", -"soft", -"yourself", -"empty", -"shall", -"angel", -"answer", -"baby", -"bright", -"dad", -"path", -"worry", -"hour", -"drop", -"follow", -"power", -"war", -"half", -"flow", -"heaven", -"act", -"chance", -"fact", -"least", -"tired", -"children", -"near", -"quite", -"afraid", -"rise", -"sea", -"taste", -"window", -"cover", -"nice", -"trust", -"lot", -"sad", -"cool", -"force", -"peace", -"return", -"blind", -"easy", -"ready", -"roll", -"rose", -"drive", -"held", -"music", -"beneath", -"hang", -"mom", -"paint", -"emotion", -"quiet", -"clear", -"cloud", -"few", -"pretty", -"bird", -"outside", -"paper", -"picture", -"front", -"rock", -"simple", -"anyone", -"meant", -"reality", -"road", -"sense", -"waste", -"bit", -"leaf", -"thank", -"happiness", -"meet", -"men", -"smoke", -"truly", -"decide", -"self", -"age", -"book", -"form", -"alive", -"carry", -"escape", -"damn", -"instead", -"able", -"ice", -"minute", -"throw", -"catch", -"leg", -"ring", -"course", -"goodbye", -"lead", -"poem", -"sick", -"corner", -"desire", -"known", -"problem", -"remind", -"shoulder", -"suppose", -"toward", -"wave", -"drink", -"jump", -"woman", -"pretend", -"sister", -"week", -"human", -"joy", -"crack", -"grey", -"pray", -"surprise", -"dry", -"knee", -"less", -"search", -"bleed", -"caught", -"clean", -"embrace", -"future", -"king", -"son", -"sorrow", -"chest", -"hug", -"remain", -"sat", -"worth", -"blow", -"daddy", -"final", -"parent", -"tight", -"also", -"create", -"lonely", -"safe", -"cross", -"dress", -"evil", -"silent", -"bone", -"fate", -"perhaps", -"anger", -"class", -"scar", -"snow", -"tiny", -"tonight", -"continue", -"control", -"dog", -"edge", -"mirror", -"month", -"suddenly", -"comfort", -"given", -"loud", -"quickly", -"gaze", -"plan", -"rush", -"stone", -"town", -"battle", -"ignore", -"spirit", -"stood", -"stupid", -"yours", -"brown", -"build", -"dust", -"hey", -"kept", -"pay", -"phone", -"twist", -"although", -"ball", -"beyond", -"hidden", -"nose", -"taken", -"fail", -"float", -"pure", -"somehow", -"wash", -"wrap", -"angry", -"cheek", -"creature", -"forgotten", -"heat", -"rip", -"single", -"space", -"special", -"weak", -"whatever", -"yell", -"anyway", -"blame", -"job", -"choose", -"country", -"curse", -"drift", -"echo", -"figure", -"grew", -"laughter", -"neck", -"suffer", -"worse", -"yeah", -"disappear", -"foot", -"forward", -"knife", -"mess", -"somewhere", -"stomach", -"storm", -"beg", -"idea", -"lift", -"offer", -"breeze", -"field", -"five", -"often", -"simply", -"stuck", -"win", -"allow", -"confuse", -"enjoy", -"except", -"flower", -"seek", -"strength", -"calm", -"grin", -"gun", -"heavy", -"hill", -"large", -"ocean", -"shoe", -"sigh", -"straight", -"summer", -"tongue", -"accept", -"crazy", -"everyday", -"exist", -"grass", -"mistake", -"sent", -"shut", -"surround", -"table", -"ache", -"brain", -"destroy", -"heal", -"nature", -"shout", -"sign", -"stain", -"choice", -"doubt", -"glance", -"glow", -"mountain", -"queen", -"stranger", -"throat", -"tomorrow", -"city", -"either", -"fish", -"flame", -"rather", -"shape", -"spin", -"spread", -"ash", -"distance", -"finish", -"image", -"imagine", -"important", -"nobody", -"shatter", -"warmth", -"became", -"feed", -"flesh", -"funny", -"lust", -"shirt", -"trouble", -"yellow", -"attention", -"bare", -"bite", -"money", -"protect", -"amaze", -"appear", -"born", -"choke", -"completely", -"daughter", -"fresh", -"friendship", -"gentle", -"probably", -"six", -"deserve", -"expect", -"grab", -"middle", -"nightmare", -"river", -"thousand", -"weight", -"worst", -"wound", -"barely", -"bottle", -"cream", -"regret", -"relationship", -"stick", -"test", -"crush", -"endless", -"fault", -"itself", -"rule", -"spill", -"art", -"circle", -"join", -"kick", -"mask", -"master", -"passion", -"quick", -"raise", -"smooth", -"unless", -"wander", -"actually", -"broke", -"chair", -"deal", -"favorite", -"gift", -"note", -"number", -"sweat", -"box", -"chill", -"clothes", -"lady", -"mark", -"park", -"poor", -"sadness", -"tie", -"animal", -"belong", -"brush", -"consume", -"dawn", -"forest", -"innocent", -"pen", -"pride", -"stream", -"thick", -"clay", -"complete", -"count", -"draw", -"faith", -"press", -"silver", -"struggle", -"surface", -"taught", -"teach", -"wet", -"bless", -"chase", -"climb", -"enter", -"letter", -"melt", -"metal", -"movie", -"stretch", -"swing", -"vision", -"wife", -"beside", -"crash", -"forgot", -"guide", -"haunt", -"joke", -"knock", -"plant", -"pour", -"prove", -"reveal", -"steal", -"stuff", -"trip", -"wood", -"wrist", -"bother", -"bottom", -"crawl", -"crowd", -"fix", -"forgive", -"frown", -"grace", -"loose", -"lucky", -"party", -"release", -"surely", -"survive", -"teacher", -"gently", -"grip", -"speed", -"suicide", -"travel", -"treat", -"vein", -"written", -"cage", -"chain", -"conversation", -"date", -"enemy", -"however", -"interest", -"million", -"page", -"pink", -"proud", -"sway", -"themselves", -"winter", -"church", -"cruel", -"cup", -"demon", -"experience", -"freedom", -"pair", -"pop", -"purpose", -"respect", -"shoot", -"softly", -"state", -"strange", -"bar", -"birth", -"curl", -"dirt", -"excuse", -"lord", -"lovely", -"monster", -"order", -"pack", -"pants", -"pool", -"scene", -"seven", -"shame", -"slide", -"ugly", -"among", -"blade", -"blonde", -"closet", -"creek", -"deny", -"drug", -"eternity", -"gain", -"grade", -"handle", -"key", -"linger", -"pale", -"prepare", -"swallow", -"swim", -"tremble", -"wheel", -"won", -"cast", -"cigarette", -"claim", -"college", -"direction", -"dirty", -"gather", -"ghost", -"hundred", -"loss", -"lung", -"orange", -"present", -"swear", -"swirl", -"twice", -"wild", -"bitter", -"blanket", -"doctor", -"everywhere", -"flash", -"grown", -"knowledge", -"numb", -"pressure", -"radio", -"repeat", -"ruin", -"spend", -"unknown", -"buy", -"clock", -"devil", -"early", -"false", -"fantasy", -"pound", -"precious", -"refuse", -"sheet", -"teeth", -"welcome", -"add", -"ahead", -"block", -"bury", -"caress", -"content", -"depth", -"despite", -"distant", -"marry", -"purple", -"threw", -"whenever", -"bomb", -"dull", -"easily", -"grasp", -"hospital", -"innocence", -"normal", -"receive", -"reply", -"rhyme", -"shade", -"someday", -"sword", -"toe", -"visit", -"asleep", -"bought", -"center", -"consider", -"flat", -"hero", -"history", -"ink", -"insane", -"muscle", -"mystery", -"pocket", -"reflection", -"shove", -"silently", -"smart", -"soldier", -"spot", -"stress", -"train", -"type", -"view", -"whether", -"bus", -"energy", -"explain", -"holy", -"hunger", -"inch", -"magic", -"mix", -"noise", -"nowhere", -"prayer", -"presence", -"shock", -"snap", -"spider", -"study", -"thunder", -"trail", -"admit", -"agree", -"bag", -"bang", -"bound", -"butterfly", -"cute", -"exactly", -"explode", -"familiar", -"fold", -"further", -"pierce", -"reflect", -"scent", -"selfish", -"sharp", -"sink", -"spring", -"stumble", -"universe", -"weep", -"women", -"wonderful", -"action", -"ancient", -"attempt", -"avoid", -"birthday", -"branch", -"chocolate", -"core", -"depress", -"drunk", -"especially", -"focus", -"fruit", -"honest", -"match", -"palm", -"perfectly", -"pillow", -"pity", -"poison", -"roar", -"shift", -"slightly", -"thump", -"truck", -"tune", -"twenty", -"unable", -"wipe", -"wrote", -"coat", -"constant", -"dinner", -"drove", -"egg", -"eternal", -"flight", -"flood", -"frame", -"freak", -"gasp", -"glad", -"hollow", -"motion", -"peer", -"plastic", -"root", -"screen", -"season", -"sting", -"strike", -"team", -"unlike", -"victim", -"volume", -"warn", -"weird", -"attack", -"await", -"awake", -"built", -"charm", -"crave", -"despair", -"fought", -"grant", -"grief", -"horse", -"limit", -"message", -"ripple", -"sanity", -"scatter", -"serve", -"split", -"string", -"trick", -"annoy", -"blur", -"boat", -"brave", -"clearly", -"cling", -"connect", -"fist", -"forth", -"imagination", -"iron", -"jock", -"judge", -"lesson", -"milk", -"misery", -"nail", -"naked", -"ourselves", -"poet", -"possible", -"princess", -"sail", -"size", -"snake", -"society", -"stroke", -"torture", -"toss", -"trace", -"wise", -"bloom", -"bullet", -"cell", -"check", -"cost", -"darling", -"during", -"footstep", -"fragile", -"hallway", -"hardly", -"horizon", -"invisible", -"journey", -"midnight", -"mud", -"nod", -"pause", -"relax", -"shiver", -"sudden", -"value", -"youth", -"abuse", -"admire", -"blink", -"breast", -"bruise", -"constantly", -"couple", -"creep", -"curve", -"difference", -"dumb", -"emptiness", -"gotta", -"honor", -"plain", -"planet", -"recall", -"rub", -"ship", -"slam", -"soar", -"somebody", -"tightly", -"weather", -"adore", -"approach", -"bond", -"bread", -"burst", -"candle", -"coffee", -"cousin", -"crime", -"desert", -"flutter", -"frozen", -"grand", -"heel", -"hello", -"language", -"level", -"movement", -"pleasure", -"powerful", -"random", -"rhythm", -"settle", -"silly", -"slap", -"sort", -"spoken", -"steel", -"threaten", -"tumble", -"upset", -"aside", -"awkward", -"bee", -"blank", -"board", -"button", -"card", -"carefully", -"complain", -"crap", -"deeply", -"discover", -"drag", -"dread", -"effort", -"entire", -"fairy", -"giant", -"gotten", -"greet", -"illusion", -"jeans", -"leap", -"liquid", -"march", -"mend", -"nervous", -"nine", -"replace", -"rope", -"spine", -"stole", -"terror", -"accident", -"apple", -"balance", -"boom", -"childhood", -"collect", -"demand", -"depression", -"eventually", -"faint", -"glare", -"goal", -"group", -"honey", -"kitchen", -"laid", -"limb", -"machine", -"mere", -"mold", -"murder", -"nerve", -"painful", -"poetry", -"prince", -"rabbit", -"shelter", -"shore", -"shower", -"soothe", -"stair", -"steady", -"sunlight", -"tangle", -"tease", -"treasure", -"uncle", -"begun", -"bliss", -"canvas", -"cheer", -"claw", -"clutch", -"commit", -"crimson", -"crystal", -"delight", -"doll", -"existence", -"express", -"fog", -"football", -"gay", -"goose", -"guard", -"hatred", -"illuminate", -"mass", -"math", -"mourn", -"rich", -"rough", -"skip", -"stir", -"student", -"style", -"support", -"thorn", -"tough", -"yard", -"yearn", -"yesterday", -"advice", -"appreciate", -"autumn", -"bank", -"beam", -"bowl", -"capture", -"carve", -"collapse", -"confusion", -"creation", -"dove", -"feather", -"girlfriend", -"glory", -"government", -"harsh", -"hop", -"inner", -"loser", -"moonlight", -"neighbor", -"neither", -"peach", -"pig", -"praise", -"screw", -"shield", -"shimmer", -"sneak", -"stab", -"subject", -"throughout", -"thrown", -"tower", -"twirl", -"wow", -"army", -"arrive", -"bathroom", -"bump", -"cease", -"cookie", -"couch", -"courage", -"dim", -"guilt", -"howl", -"hum", -"husband", -"insult", -"led", -"lunch", -"mock", -"mostly", -"natural", -"nearly", -"needle", -"nerd", -"peaceful", -"perfection", -"pile", -"price", -"remove", -"roam", -"sanctuary", -"serious", -"shiny", -"shook", -"sob", -"stolen", -"tap", -"vain", -"void", -"warrior", -"wrinkle", -"affection", -"apologize", -"blossom", -"bounce", -"bridge", -"cheap", -"crumble", -"decision", -"descend", -"desperately", -"dig", -"dot", -"flip", -"frighten", -"heartbeat", -"huge", -"lazy", -"lick", -"odd", -"opinion", -"process", -"puzzle", -"quietly", -"retreat", -"score", -"sentence", -"separate", -"situation", -"skill", -"soak", -"square", -"stray", -"taint", -"task", -"tide", -"underneath", -"veil", -"whistle", -"anywhere", -"bedroom", -"bid", -"bloody", -"burden", -"careful", -"compare", -"concern", -"curtain", -"decay", -"defeat", -"describe", -"double", -"dreamer", -"driver", -"dwell", -"evening", -"flare", -"flicker", -"grandma", -"guitar", -"harm", -"horrible", -"hungry", -"indeed", -"lace", -"melody", -"monkey", -"nation", -"object", -"obviously", -"rainbow", -"salt", -"scratch", -"shown", -"shy", -"stage", -"stun", -"third", -"tickle", -"useless", -"weakness", -"worship", -"worthless", -"afternoon", -"beard", -"boyfriend", -"bubble", -"busy", -"certain", -"chin", -"concrete", -"desk", -"diamond", -"doom", -"drawn", -"due", -"felicity", -"freeze", -"frost", -"garden", -"glide", -"harmony", -"hopefully", -"hunt", -"jealous", -"lightning", -"mama", -"mercy", -"peel", -"physical", -"position", -"pulse", -"punch", -"quit", -"rant", -"respond", -"salty", -"sane", -"satisfy", -"savior", -"sheep", -"slept", -"social", -"sport", -"tuck", -"utter", -"valley", -"wolf", -"aim", -"alas", -"alter", -"arrow", -"awaken", -"beaten", -"belief", -"brand", -"ceiling", -"cheese", -"clue", -"confidence", -"connection", -"daily", -"disguise", -"eager", -"erase", -"essence", -"everytime", -"expression", -"fan", -"flag", -"flirt", -"foul", -"fur", -"giggle", -"glorious", -"ignorance", -"law", -"lifeless", -"measure", -"mighty", -"muse", -"north", -"opposite", -"paradise", -"patience", -"patient", -"pencil", -"petal", -"plate", -"ponder", -"possibly", -"practice", -"slice", -"spell", -"stock", -"strife", -"strip", -"suffocate", -"suit", -"tender", -"tool", -"trade", -"velvet", -"verse", -"waist", -"witch", -"aunt", -"bench", -"bold", -"cap", -"certainly", -"click", -"companion", -"creator", -"dart", -"delicate", -"determine", -"dish", -"dragon", -"drama", -"drum", -"dude", -"everybody", -"feast", -"forehead", -"former", -"fright", -"fully", -"gas", -"hook", -"hurl", -"invite", -"juice", -"manage", -"moral", -"possess", -"raw", -"rebel", -"royal", -"scale", -"scary", -"several", -"slight", -"stubborn", -"swell", -"talent", -"tea", -"terrible", -"thread", -"torment", -"trickle", -"usually", -"vast", -"violence", -"weave", -"acid", -"agony", -"ashamed", -"awe", -"belly", -"blend", -"blush", -"character", -"cheat", -"common", -"company", -"coward", -"creak", -"danger", -"deadly", -"defense", -"define", -"depend", -"desperate", -"destination", -"dew", -"duck", -"dusty", -"embarrass", -"engine", -"example", -"explore", -"foe", -"freely", -"frustrate", -"generation", -"glove", -"guilty", -"health", -"hurry", -"idiot", -"impossible", -"inhale", -"jaw", -"kingdom", -"mention", -"mist", -"moan", -"mumble", -"mutter", -"observe", -"ode", -"pathetic", -"pattern", -"pie", -"prefer", -"puff", -"rape", -"rare", -"revenge", -"rude", -"scrape", -"spiral", -"squeeze", -"strain", -"sunset", -"suspend", -"sympathy", -"thigh", -"throne", -"total", -"unseen", -"weapon", -"weary" -] - - - -n = 1626 - -# Note about US patent no 5892470: Here each word does not represent a given digit. -# Instead, the digit represented by a word is variable, it depends on the previous word. - -def mn_encode( message ): - out = [] - for i in range(len(message)/8): - word = message[8*i:8*i+8] - x = int(word, 16) - w1 = (x%n) - w2 = ((x/n) + w1)%n - w3 = ((x/n/n) + w2)%n - out += [ words[w1], words[w2], words[w3] ] - return out - -def mn_decode( wlist ): - out = '' - for i in range(len(wlist)/3): - word1, word2, word3 = wlist[3*i:3*i+3] - w1 = words.index(word1) - w2 = (words.index(word2))%n - w3 = (words.index(word3))%n - x = w1 +n*((w2-w1)%n) +n*n*((w3-w2)%n) - out += '%08x'%x - return out - - -if __name__ == '__main__': - import sys - if len( sys.argv ) == 1: - print 'I need arguments: a hex string to encode, or a list of words to decode' - elif len( sys.argv ) == 2: - print ' '.join(mn_encode(sys.argv[1])) - else: - print mn_decode(sys.argv[1:]) diff --git a/client/msqr.py b/client/msqr.py deleted file mode 100644 index da3c6fd..0000000 --- a/client/msqr.py +++ /dev/null @@ -1,94 +0,0 @@ -# from http://eli.thegreenplace.net/2009/03/07/computing-modular-square-roots-in-python/ - -def modular_sqrt(a, p): - """ Find a quadratic residue (mod p) of 'a'. p - must be an odd prime. - - Solve the congruence of the form: - x^2 = a (mod p) - And returns x. Note that p - x is also a root. - - 0 is returned is no square root exists for - these a and p. - - The Tonelli-Shanks algorithm is used (except - for some simple cases in which the solution - is known from an identity). This algorithm - runs in polynomial time (unless the - generalized Riemann hypothesis is false). - """ - # Simple cases - # - if legendre_symbol(a, p) != 1: - return 0 - elif a == 0: - return 0 - elif p == 2: - return p - elif p % 4 == 3: - return pow(a, (p + 1) / 4, p) - - # Partition p-1 to s * 2^e for an odd s (i.e. - # reduce all the powers of 2 from p-1) - # - s = p - 1 - e = 0 - while s % 2 == 0: - s /= 2 - e += 1 - - # Find some 'n' with a legendre symbol n|p = -1. - # Shouldn't take long. - # - n = 2 - while legendre_symbol(n, p) != -1: - n += 1 - - # Here be dragons! - # Read the paper "Square roots from 1; 24, 51, - # 10 to Dan Shanks" by Ezra Brown for more - # information - # - - # x is a guess of the square root that gets better - # with each iteration. - # b is the "fudge factor" - by how much we're off - # with the guess. The invariant x^2 = ab (mod p) - # is maintained throughout the loop. - # g is used for successive powers of n to update - # both a and b - # r is the exponent - decreases with each update - # - x = pow(a, (s + 1) / 2, p) - b = pow(a, s, p) - g = pow(n, s, p) - r = e - - while True: - t = b - m = 0 - for m in xrange(r): - if t == 1: - break - t = pow(t, 2, p) - - if m == 0: - return x - - gs = pow(g, 2 ** (r - m - 1), p) - g = (gs * gs) % p - x = (x * gs) % p - b = (b * g) % p - r = m - -def legendre_symbol(a, p): - """ Compute the Legendre symbol a|p using - Euler's criterion. p is a prime, a is - relatively prime to p (if p divides - a, then a|p = 0) - - Returns 1 if a has a square root modulo - p, -1 otherwise. - """ - ls = pow(a, (p - 1) / 2, p) - return -1 if ls == p - 1 else ls diff --git a/client/peers b/client/peers deleted file mode 100755 index 0b5d1e0..0000000 --- a/client/peers +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import interface - -i = interface.TcpStratumInterface('ecdsa.org', 50001) -i.start() -i.send([('server.peers.subscribe',[])]) - -while True: - r = i.responses.get(True, 100000000000) - print r.get('result') diff --git a/client/pyqrnative.py b/client/pyqrnative.py deleted file mode 100644 index 7f9c750..0000000 --- a/client/pyqrnative.py +++ /dev/null @@ -1,962 +0,0 @@ -import math - -#from PIL import Image, ImageDraw - -#QRCode for Python -# -#Ported from the Javascript library by Sam Curren -# -#QRCode for Javascript -#http://d-project.googlecode.com/svn/trunk/misc/qrcode/js/qrcode.js -# -#Copyright (c) 2009 Kazuhiko Arase -# -#URL: http://www.d-project.com/ -# -#Licensed under the MIT license: -# http://www.opensource.org/licenses/mit-license.php -# -# The word "QR Code" is registered trademark of -# DENSO WAVE INCORPORATED -# http://www.denso-wave.com/qrcode/faqpatent-e.html - - -class QR8bitByte: - - def __init__(self, data): - self.mode = QRMode.MODE_8BIT_BYTE - self.data = data - - def getLength(self): - return len(self.data) - - def write(self, buffer): - for i in range(len(self.data)): - #// not JIS ... - buffer.put(ord(self.data[i]), 8) - def __repr__(self): - return self.data - -class QRCode: - def __init__(self, typeNumber, errorCorrectLevel): - self.typeNumber = typeNumber - self.errorCorrectLevel = errorCorrectLevel - self.modules = None - self.moduleCount = 0 - self.dataCache = None - self.dataList = [] - def addData(self, data): - newData = QR8bitByte(data) - self.dataList.append(newData) - self.dataCache = None - def isDark(self, row, col): - if (row < 0 or self.moduleCount <= row or col < 0 or self.moduleCount <= col): - raise Exception("%s,%s - %s" % (row, col, self.moduleCount)) - return self.modules[row][col] - def getModuleCount(self): - return self.moduleCount - def make(self): - self.makeImpl(False, self.getBestMaskPattern() ) - def makeImpl(self, test, maskPattern): - - self.moduleCount = self.typeNumber * 4 + 17 - self.modules = [None for x in range(self.moduleCount)] - - for row in range(self.moduleCount): - - self.modules[row] = [None for x in range(self.moduleCount)] - - for col in range(self.moduleCount): - self.modules[row][col] = None #//(col + row) % 3; - - self.setupPositionProbePattern(0, 0) - self.setupPositionProbePattern(self.moduleCount - 7, 0) - self.setupPositionProbePattern(0, self.moduleCount - 7) - self.setupPositionAdjustPattern() - self.setupTimingPattern() - self.setupTypeInfo(test, maskPattern) - - if (self.typeNumber >= 7): - self.setupTypeNumber(test) - - if (self.dataCache == None): - self.dataCache = QRCode.createData(self.typeNumber, self.errorCorrectLevel, self.dataList) - self.mapData(self.dataCache, maskPattern) - - def setupPositionProbePattern(self, row, col): - - for r in range(-1, 8): - - if (row + r <= -1 or self.moduleCount <= row + r): continue - - for c in range(-1, 8): - - if (col + c <= -1 or self.moduleCount <= col + c): continue - - if ( (0 <= r and r <= 6 and (c == 0 or c == 6) ) - or (0 <= c and c <= 6 and (r == 0 or r == 6) ) - or (2 <= r and r <= 4 and 2 <= c and c <= 4) ): - self.modules[row + r][col + c] = True; - else: - self.modules[row + r][col + c] = False; - - def getBestMaskPattern(self): - - minLostPoint = 0 - pattern = 0 - - for i in range(8): - - self.makeImpl(True, i); - - lostPoint = QRUtil.getLostPoint(self); - - if (i == 0 or minLostPoint > lostPoint): - minLostPoint = lostPoint - pattern = i - - return pattern - - - def setupTimingPattern(self): - - for r in range(8, self.moduleCount - 8): - if (self.modules[r][6] != None): - continue - self.modules[r][6] = (r % 2 == 0) - - for c in range(8, self.moduleCount - 8): - if (self.modules[6][c] != None): - continue - self.modules[6][c] = (c % 2 == 0) - - def setupPositionAdjustPattern(self): - - pos = QRUtil.getPatternPosition(self.typeNumber) - - for i in range(len(pos)): - - for j in range(len(pos)): - - row = pos[i] - col = pos[j] - - if (self.modules[row][col] != None): - continue - - for r in range(-2, 3): - - for c in range(-2, 3): - - if (r == -2 or r == 2 or c == -2 or c == 2 or (r == 0 and c == 0) ): - self.modules[row + r][col + c] = True - else: - self.modules[row + r][col + c] = False - - def setupTypeNumber(self, test): - - bits = QRUtil.getBCHTypeNumber(self.typeNumber) - - for i in range(18): - mod = (not test and ( (bits >> i) & 1) == 1) - self.modules[i // 3][i % 3 + self.moduleCount - 8 - 3] = mod; - - for i in range(18): - mod = (not test and ( (bits >> i) & 1) == 1) - self.modules[i % 3 + self.moduleCount - 8 - 3][i // 3] = mod; - - def setupTypeInfo(self, test, maskPattern): - - data = (self.errorCorrectLevel << 3) | maskPattern - bits = QRUtil.getBCHTypeInfo(data) - - #// vertical - for i in range(15): - - mod = (not test and ( (bits >> i) & 1) == 1) - - if (i < 6): - self.modules[i][8] = mod - elif (i < 8): - self.modules[i + 1][8] = mod - else: - self.modules[self.moduleCount - 15 + i][8] = mod - - #// horizontal - for i in range(15): - - mod = (not test and ( (bits >> i) & 1) == 1); - - if (i < 8): - self.modules[8][self.moduleCount - i - 1] = mod - elif (i < 9): - self.modules[8][15 - i - 1 + 1] = mod - else: - self.modules[8][15 - i - 1] = mod - - #// fixed module - self.modules[self.moduleCount - 8][8] = (not test) - - def mapData(self, data, maskPattern): - - inc = -1 - row = self.moduleCount - 1 - bitIndex = 7 - byteIndex = 0 - - for col in range(self.moduleCount - 1, 0, -2): - - if (col == 6): col-=1 - - while (True): - - for c in range(2): - - if (self.modules[row][col - c] == None): - - dark = False - - if (byteIndex < len(data)): - dark = ( ( (data[byteIndex] >> bitIndex) & 1) == 1) - - mask = QRUtil.getMask(maskPattern, row, col - c) - - if (mask): - dark = not dark - - self.modules[row][col - c] = dark - bitIndex-=1 - - if (bitIndex == -1): - byteIndex+=1 - bitIndex = 7 - - row += inc - - if (row < 0 or self.moduleCount <= row): - row -= inc - inc = -inc - break - PAD0 = 0xEC - PAD1 = 0x11 - - @staticmethod - def createData(typeNumber, errorCorrectLevel, dataList): - - rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel) - - buffer = QRBitBuffer(); - - for i in range(len(dataList)): - data = dataList[i] - buffer.put(data.mode, 4) - buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber) ) - data.write(buffer) - - #// calc num max data. - totalDataCount = 0; - for i in range(len(rsBlocks)): - totalDataCount += rsBlocks[i].dataCount - - if (buffer.getLengthInBits() > totalDataCount * 8): - raise Exception("code length overflow. (" - + buffer.getLengthInBits() - + ">" - + totalDataCount * 8 - + ")") - - #// end code - if (buffer.getLengthInBits() + 4 <= totalDataCount * 8): - buffer.put(0, 4) - - #// padding - while (buffer.getLengthInBits() % 8 != 0): - buffer.putBit(False) - - #// padding - while (True): - - if (buffer.getLengthInBits() >= totalDataCount * 8): - break - buffer.put(QRCode.PAD0, 8) - - if (buffer.getLengthInBits() >= totalDataCount * 8): - break - buffer.put(QRCode.PAD1, 8) - - return QRCode.createBytes(buffer, rsBlocks) - - @staticmethod - def createBytes(buffer, rsBlocks): - - offset = 0 - - maxDcCount = 0 - maxEcCount = 0 - - dcdata = [0 for x in range(len(rsBlocks))] - ecdata = [0 for x in range(len(rsBlocks))] - - for r in range(len(rsBlocks)): - - dcCount = rsBlocks[r].dataCount - ecCount = rsBlocks[r].totalCount - dcCount - - maxDcCount = max(maxDcCount, dcCount) - maxEcCount = max(maxEcCount, ecCount) - - dcdata[r] = [0 for x in range(dcCount)] - - for i in range(len(dcdata[r])): - dcdata[r][i] = 0xff & buffer.buffer[i + offset] - offset += dcCount - - rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount) - rawPoly = QRPolynomial(dcdata[r], rsPoly.getLength() - 1) - - modPoly = rawPoly.mod(rsPoly) - ecdata[r] = [0 for x in range(rsPoly.getLength()-1)] - for i in range(len(ecdata[r])): - modIndex = i + modPoly.getLength() - len(ecdata[r]) - if (modIndex >= 0): - ecdata[r][i] = modPoly.get(modIndex) - else: - ecdata[r][i] = 0 - - totalCodeCount = 0 - for i in range(len(rsBlocks)): - totalCodeCount += rsBlocks[i].totalCount - - data = [None for x in range(totalCodeCount)] - index = 0 - - for i in range(maxDcCount): - for r in range(len(rsBlocks)): - if (i < len(dcdata[r])): - data[index] = dcdata[r][i] - index+=1 - - for i in range(maxEcCount): - for r in range(len(rsBlocks)): - if (i < len(ecdata[r])): - data[index] = ecdata[r][i] - index+=1 - - return data - - -class QRMode: - MODE_NUMBER = 1 << 0 - MODE_ALPHA_NUM = 1 << 1 - MODE_8BIT_BYTE = 1 << 2 - MODE_KANJI = 1 << 3 - -class QRErrorCorrectLevel: - L = 1 - M = 0 - Q = 3 - H = 2 - -class QRMaskPattern: - PATTERN000 = 0 - PATTERN001 = 1 - PATTERN010 = 2 - PATTERN011 = 3 - PATTERN100 = 4 - PATTERN101 = 5 - PATTERN110 = 6 - PATTERN111 = 7 - -class QRUtil(object): - PATTERN_POSITION_TABLE = [ - [], - [6, 18], - [6, 22], - [6, 26], - [6, 30], - [6, 34], - [6, 22, 38], - [6, 24, 42], - [6, 26, 46], - [6, 28, 50], - [6, 30, 54], - [6, 32, 58], - [6, 34, 62], - [6, 26, 46, 66], - [6, 26, 48, 70], - [6, 26, 50, 74], - [6, 30, 54, 78], - [6, 30, 56, 82], - [6, 30, 58, 86], - [6, 34, 62, 90], - [6, 28, 50, 72, 94], - [6, 26, 50, 74, 98], - [6, 30, 54, 78, 102], - [6, 28, 54, 80, 106], - [6, 32, 58, 84, 110], - [6, 30, 58, 86, 114], - [6, 34, 62, 90, 118], - [6, 26, 50, 74, 98, 122], - [6, 30, 54, 78, 102, 126], - [6, 26, 52, 78, 104, 130], - [6, 30, 56, 82, 108, 134], - [6, 34, 60, 86, 112, 138], - [6, 30, 58, 86, 114, 142], - [6, 34, 62, 90, 118, 146], - [6, 30, 54, 78, 102, 126, 150], - [6, 24, 50, 76, 102, 128, 154], - [6, 28, 54, 80, 106, 132, 158], - [6, 32, 58, 84, 110, 136, 162], - [6, 26, 54, 82, 110, 138, 166], - [6, 30, 58, 86, 114, 142, 170] - ] - - G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0) - G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0) - G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) - - @staticmethod - def getBCHTypeInfo(data): - d = data << 10; - while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0): - d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) ) - - return ( (data << 10) | d) ^ QRUtil.G15_MASK - @staticmethod - def getBCHTypeNumber(data): - d = data << 12; - while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0): - d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) ) - return (data << 12) | d - @staticmethod - def getBCHDigit(data): - digit = 0; - while (data != 0): - digit += 1 - data >>= 1 - return digit - @staticmethod - def getPatternPosition(typeNumber): - return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1] - @staticmethod - def getMask(maskPattern, i, j): - if maskPattern == QRMaskPattern.PATTERN000 : return (i + j) % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN001 : return i % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN010 : return j % 3 == 0 - if maskPattern == QRMaskPattern.PATTERN011 : return (i + j) % 3 == 0 - if maskPattern == QRMaskPattern.PATTERN100 : return (math.floor(i / 2) + math.floor(j / 3) ) % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 == 0 - if maskPattern == QRMaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 == 0 - if maskPattern == QRMaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 == 0 - raise Exception("bad maskPattern:" + maskPattern); - @staticmethod - def getErrorCorrectPolynomial(errorCorrectLength): - a = QRPolynomial([1], 0); - for i in range(errorCorrectLength): - a = a.multiply(QRPolynomial([1, QRMath.gexp(i)], 0) ) - return a - @staticmethod - def getLengthInBits(mode, type): - - if 1 <= type and type < 10: - - #// 1 - 9 - - if mode == QRMode.MODE_NUMBER : return 10 - if mode == QRMode.MODE_ALPHA_NUM : return 9 - if mode == QRMode.MODE_8BIT_BYTE : return 8 - if mode == QRMode.MODE_KANJI : return 8 - raise Exception("mode:" + mode) - - elif (type < 27): - - #// 10 - 26 - - if mode == QRMode.MODE_NUMBER : return 12 - if mode == QRMode.MODE_ALPHA_NUM : return 11 - if mode == QRMode.MODE_8BIT_BYTE : return 16 - if mode == QRMode.MODE_KANJI : return 10 - raise Exception("mode:" + mode) - - elif (type < 41): - - #// 27 - 40 - - if mode == QRMode.MODE_NUMBER : return 14 - if mode == QRMode.MODE_ALPHA_NUM : return 13 - if mode == QRMode.MODE_8BIT_BYTE : return 16 - if mode == QRMode.MODE_KANJI : return 12 - raise Exception("mode:" + mode) - - else: - raise Exception("type:" + type) - @staticmethod - def getLostPoint(qrCode): - - moduleCount = qrCode.getModuleCount(); - - lostPoint = 0; - - #// LEVEL1 - - for row in range(moduleCount): - - for col in range(moduleCount): - - sameCount = 0; - dark = qrCode.isDark(row, col); - - for r in range(-1, 2): - - if (row + r < 0 or moduleCount <= row + r): - continue - - for c in range(-1, 2): - - if (col + c < 0 or moduleCount <= col + c): - continue - if (r == 0 and c == 0): - continue - - if (dark == qrCode.isDark(row + r, col + c) ): - sameCount+=1 - if (sameCount > 5): - lostPoint += (3 + sameCount - 5) - - #// LEVEL2 - - for row in range(moduleCount - 1): - for col in range(moduleCount - 1): - count = 0; - if (qrCode.isDark(row, col ) ): count+=1 - if (qrCode.isDark(row + 1, col ) ): count+=1 - if (qrCode.isDark(row, col + 1) ): count+=1 - if (qrCode.isDark(row + 1, col + 1) ): count+=1 - if (count == 0 or count == 4): - lostPoint += 3 - - #// LEVEL3 - - for row in range(moduleCount): - for col in range(moduleCount - 6): - if (qrCode.isDark(row, col) - and not qrCode.isDark(row, col + 1) - and qrCode.isDark(row, col + 2) - and qrCode.isDark(row, col + 3) - and qrCode.isDark(row, col + 4) - and not qrCode.isDark(row, col + 5) - and qrCode.isDark(row, col + 6) ): - lostPoint += 40 - - for col in range(moduleCount): - for row in range(moduleCount - 6): - if (qrCode.isDark(row, col) - and not qrCode.isDark(row + 1, col) - and qrCode.isDark(row + 2, col) - and qrCode.isDark(row + 3, col) - and qrCode.isDark(row + 4, col) - and not qrCode.isDark(row + 5, col) - and qrCode.isDark(row + 6, col) ): - lostPoint += 40 - - #// LEVEL4 - - darkCount = 0; - - for col in range(moduleCount): - for row in range(moduleCount): - if (qrCode.isDark(row, col) ): - darkCount+=1 - - ratio = abs(100 * darkCount / moduleCount / moduleCount - 50) / 5 - lostPoint += ratio * 10 - - return lostPoint - -class QRMath: - - @staticmethod - def glog(n): - if (n < 1): - raise Exception("glog(" + n + ")") - return LOG_TABLE[n]; - @staticmethod - def gexp(n): - while n < 0: - n += 255 - while n >= 256: - n -= 255 - return EXP_TABLE[n]; - -EXP_TABLE = [x for x in range(256)] - -LOG_TABLE = [x for x in range(256)] - -for i in range(8): - EXP_TABLE[i] = 1 << i; - -for i in range(8, 256): - EXP_TABLE[i] = EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8] - -for i in range(255): - LOG_TABLE[EXP_TABLE[i] ] = i - -class QRPolynomial: - - def __init__(self, num, shift): - - if (len(num) == 0): - raise Exception(num.length + "/" + shift) - - offset = 0 - - while offset < len(num) and num[offset] == 0: - offset += 1 - - self.num = [0 for x in range(len(num)-offset+shift)] - for i in range(len(num) - offset): - self.num[i] = num[i + offset] - - - def get(self, index): - return self.num[index] - def getLength(self): - return len(self.num) - def multiply(self, e): - num = [0 for x in range(self.getLength() + e.getLength() - 1)]; - - for i in range(self.getLength()): - for j in range(e.getLength()): - num[i + j] ^= QRMath.gexp(QRMath.glog(self.get(i) ) + QRMath.glog(e.get(j) ) ) - - return QRPolynomial(num, 0); - def mod(self, e): - - if (self.getLength() - e.getLength() < 0): - return self; - - ratio = QRMath.glog(self.get(0) ) - QRMath.glog(e.get(0) ) - - num = [0 for x in range(self.getLength())] - - for i in range(self.getLength()): - num[i] = self.get(i); - - for i in range(e.getLength()): - num[i] ^= QRMath.gexp(QRMath.glog(e.get(i) ) + ratio) - - # recursive call - return QRPolynomial(num, 0).mod(e); - -class QRRSBlock: - - RS_BLOCK_TABLE = [ - - #// L - #// M - #// Q - #// H - - #// 1 - [1, 26, 19], - [1, 26, 16], - [1, 26, 13], - [1, 26, 9], - - #// 2 - [1, 44, 34], - [1, 44, 28], - [1, 44, 22], - [1, 44, 16], - - #// 3 - [1, 70, 55], - [1, 70, 44], - [2, 35, 17], - [2, 35, 13], - - #// 4 - [1, 100, 80], - [2, 50, 32], - [2, 50, 24], - [4, 25, 9], - - #// 5 - [1, 134, 108], - [2, 67, 43], - [2, 33, 15, 2, 34, 16], - [2, 33, 11, 2, 34, 12], - - #// 6 - [2, 86, 68], - [4, 43, 27], - [4, 43, 19], - [4, 43, 15], - - #// 7 - [2, 98, 78], - [4, 49, 31], - [2, 32, 14, 4, 33, 15], - [4, 39, 13, 1, 40, 14], - - #// 8 - [2, 121, 97], - [2, 60, 38, 2, 61, 39], - [4, 40, 18, 2, 41, 19], - [4, 40, 14, 2, 41, 15], - - #// 9 - [2, 146, 116], - [3, 58, 36, 2, 59, 37], - [4, 36, 16, 4, 37, 17], - [4, 36, 12, 4, 37, 13], - - #// 10 - [2, 86, 68, 2, 87, 69], - [4, 69, 43, 1, 70, 44], - [6, 43, 19, 2, 44, 20], - [6, 43, 15, 2, 44, 16], - - # 11 - [4, 101, 81], - [1, 80, 50, 4, 81, 51], - [4, 50, 22, 4, 51, 23], - [3, 36, 12, 8, 37, 13], - - # 12 - [2, 116, 92, 2, 117, 93], - [6, 58, 36, 2, 59, 37], - [4, 46, 20, 6, 47, 21], - [7, 42, 14, 4, 43, 15], - - # 13 - [4, 133, 107], - [8, 59, 37, 1, 60, 38], - [8, 44, 20, 4, 45, 21], - [12, 33, 11, 4, 34, 12], - - # 14 - [3, 145, 115, 1, 146, 116], - [4, 64, 40, 5, 65, 41], - [11, 36, 16, 5, 37, 17], - [11, 36, 12, 5, 37, 13], - - # 15 - [5, 109, 87, 1, 110, 88], - [5, 65, 41, 5, 66, 42], - [5, 54, 24, 7, 55, 25], - [11, 36, 12], - - # 16 - [5, 122, 98, 1, 123, 99], - [7, 73, 45, 3, 74, 46], - [15, 43, 19, 2, 44, 20], - [3, 45, 15, 13, 46, 16], - - # 17 - [1, 135, 107, 5, 136, 108], - [10, 74, 46, 1, 75, 47], - [1, 50, 22, 15, 51, 23], - [2, 42, 14, 17, 43, 15], - - # 18 - [5, 150, 120, 1, 151, 121], - [9, 69, 43, 4, 70, 44], - [17, 50, 22, 1, 51, 23], - [2, 42, 14, 19, 43, 15], - - # 19 - [3, 141, 113, 4, 142, 114], - [3, 70, 44, 11, 71, 45], - [17, 47, 21, 4, 48, 22], - [9, 39, 13, 16, 40, 14], - - # 20 - [3, 135, 107, 5, 136, 108], - [3, 67, 41, 13, 68, 42], - [15, 54, 24, 5, 55, 25], - [15, 43, 15, 10, 44, 16], - - # 21 - [4, 144, 116, 4, 145, 117], - [17, 68, 42], - [17, 50, 22, 6, 51, 23], - [19, 46, 16, 6, 47, 17], - - # 22 - [2, 139, 111, 7, 140, 112], - [17, 74, 46], - [7, 54, 24, 16, 55, 25], - [34, 37, 13], - - # 23 - [4, 151, 121, 5, 152, 122], - [4, 75, 47, 14, 76, 48], - [11, 54, 24, 14, 55, 25], - [16, 45, 15, 14, 46, 16], - - # 24 - [6, 147, 117, 4, 148, 118], - [6, 73, 45, 14, 74, 46], - [11, 54, 24, 16, 55, 25], - [30, 46, 16, 2, 47, 17], - - # 25 - [8, 132, 106, 4, 133, 107], - [8, 75, 47, 13, 76, 48], - [7, 54, 24, 22, 55, 25], - [22, 45, 15, 13, 46, 16], - - # 26 - [10, 142, 114, 2, 143, 115], - [19, 74, 46, 4, 75, 47], - [28, 50, 22, 6, 51, 23], - [33, 46, 16, 4, 47, 17], - - # 27 - [8, 152, 122, 4, 153, 123], - [22, 73, 45, 3, 74, 46], - [8, 53, 23, 26, 54, 24], - [12, 45, 15, 28, 46, 16], - - # 28 - [3, 147, 117, 10, 148, 118], - [3, 73, 45, 23, 74, 46], - [4, 54, 24, 31, 55, 25], - [11, 45, 15, 31, 46, 16], - - # 29 - [7, 146, 116, 7, 147, 117], - [21, 73, 45, 7, 74, 46], - [1, 53, 23, 37, 54, 24], - [19, 45, 15, 26, 46, 16], - - # 30 - [5, 145, 115, 10, 146, 116], - [19, 75, 47, 10, 76, 48], - [15, 54, 24, 25, 55, 25], - [23, 45, 15, 25, 46, 16], - - # 31 - [13, 145, 115, 3, 146, 116], - [2, 74, 46, 29, 75, 47], - [42, 54, 24, 1, 55, 25], - [23, 45, 15, 28, 46, 16], - - # 32 - [17, 145, 115], - [10, 74, 46, 23, 75, 47], - [10, 54, 24, 35, 55, 25], - [19, 45, 15, 35, 46, 16], - - # 33 - [17, 145, 115, 1, 146, 116], - [14, 74, 46, 21, 75, 47], - [29, 54, 24, 19, 55, 25], - [11, 45, 15, 46, 46, 16], - - # 34 - [13, 145, 115, 6, 146, 116], - [14, 74, 46, 23, 75, 47], - [44, 54, 24, 7, 55, 25], - [59, 46, 16, 1, 47, 17], - - # 35 - [12, 151, 121, 7, 152, 122], - [12, 75, 47, 26, 76, 48], - [39, 54, 24, 14, 55, 25], - [22, 45, 15, 41, 46, 16], - - # 36 - [6, 151, 121, 14, 152, 122], - [6, 75, 47, 34, 76, 48], - [46, 54, 24, 10, 55, 25], - [2, 45, 15, 64, 46, 16], - - # 37 - [17, 152, 122, 4, 153, 123], - [29, 74, 46, 14, 75, 47], - [49, 54, 24, 10, 55, 25], - [24, 45, 15, 46, 46, 16], - - # 38 - [4, 152, 122, 18, 153, 123], - [13, 74, 46, 32, 75, 47], - [48, 54, 24, 14, 55, 25], - [42, 45, 15, 32, 46, 16], - - # 39 - [20, 147, 117, 4, 148, 118], - [40, 75, 47, 7, 76, 48], - [43, 54, 24, 22, 55, 25], - [10, 45, 15, 67, 46, 16], - - # 40 - [19, 148, 118, 6, 149, 119], - [18, 75, 47, 31, 76, 48], - [34, 54, 24, 34, 55, 25], - [20, 45, 15, 61, 46, 16] - - ] - - def __init__(self, totalCount, dataCount): - self.totalCount = totalCount - self.dataCount = dataCount - - @staticmethod - def getRSBlocks(typeNumber, errorCorrectLevel): - rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel); - if rsBlock == None: - raise Exception("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + errorCorrectLevel) - - length = len(rsBlock) / 3 - - list = [] - - for i in range(length): - - count = rsBlock[i * 3 + 0] - totalCount = rsBlock[i * 3 + 1] - dataCount = rsBlock[i * 3 + 2] - - for j in range(count): - list.append(QRRSBlock(totalCount, dataCount)) - - return list; - - @staticmethod - def getRsBlockTable(typeNumber, errorCorrectLevel): - if errorCorrectLevel == QRErrorCorrectLevel.L: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]; - elif errorCorrectLevel == QRErrorCorrectLevel.M: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]; - elif errorCorrectLevel == QRErrorCorrectLevel.Q: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]; - elif errorCorrectLevel == QRErrorCorrectLevel.H: - return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]; - else: - return None; - -class QRBitBuffer: - def __init__(self): - self.buffer = [] - self.length = 0 - def __repr__(self): - return ".".join([str(n) for n in self.buffer]) - def get(self, index): - bufIndex = math.floor(index / 8) - val = ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 - print "get ", val - return ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 - def put(self, num, length): - for i in range(length): - self.putBit( ( (num >> (length - i - 1) ) & 1) == 1) - def getLengthInBits(self): - return self.length - def putBit(self, bit): - bufIndex = self.length // 8 - if len(self.buffer) <= bufIndex: - self.buffer.append(0) - if bit: - self.buffer[bufIndex] |= (0x80 >> (self.length % 8) ) - self.length+=1 diff --git a/client/remote.php b/client/remote.php deleted file mode 100644 index 8ad2319..0000000 --- a/client/remote.php +++ /dev/null @@ -1,24 +0,0 @@ -\n"; -echo "This page demonstrates the generation of new addresses by a neutralized Electrum wallet.\n\n"; -echo "A neutralized wallet does not contain the seed that allows to generate private keys.\nIt contains a master public key that allows to create new addresses.\n\n"; -echo "An attacker getting access to the neutralized wallet cannot steal the bitcoins.\n"; -echo "The full wallet (with seed) is not stored on the webserver.\n\n"; -echo "

"; - -if($_POST['submit']) { - $daemon = new jsonRPCClient('http://foo:bar@ecdsa.org:8444/'); - try{ - $r = $daemon->getnewaddress(); - if($r) { - echo '
'; - echo "bitcoin:$r\n\n"; - } - } catch(Exception $e) { - echo "error: cannot reach wallet daemon"; - } -} -echo ""; -?> diff --git a/client/remote_wallet.py b/client/remote_wallet.py deleted file mode 100644 index be87df8..0000000 --- a/client/remote_wallet.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/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 . - -import time, thread, sys, socket - -# see http://code.google.com/p/jsonrpclib/ -import jsonrpclib -from wallet import Wallet - -""" -Simple wallet daemon for webservers. -- generates new addresses on request -- private keys are not needed in order to generate new addresses. A neutralized wallet can be used (seed removed) -- no gap limit: use 'getnum' to know how many addresses have been created. - -todo: -- return the max gap -- add expiration date - -""" - - -host = 'ecdsa.org' -port = 8444 -wallet_path = 'wallet_path' -username = 'foo' -password = 'bar' -wallet = Wallet() -stopping = False - - - -from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCRequestHandler -import SimpleXMLRPCServer - -class authHandler(SimpleJSONRPCRequestHandler): - def parse_request(self): - if SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.parse_request(self): - if self.authenticate(self.headers): - return True - else: - self.send_error(401, 'Authentication failed') - return False - - def authenticate(self, headers): - from base64 import b64decode - basic, _, encoded = headers.get('Authorization').partition(' ') - assert basic == 'Basic', 'Only basic authentication supported' - x_username, _, x_password = b64decode(encoded).partition(':') - return username == x_username and password == x_password - - -def do_stop(): - global stopping - stopping = True - -def get_new_address(): - a = wallet.create_new_address(False) - wallet.save() - return a - -def get_num(): - return len(wallet.addresses) - -def get_mpk(): - return wallet.master_public_key.encode('hex') - - - -if __name__ == '__main__': - - if len(sys.argv)>1: - import jsonrpclib - server = jsonrpclib.Server('http://%s:%s@%s:%d'%(username, password, host, port)) - cmd = sys.argv[1] - - try: - if cmd == 'getnum': - out = server.getnum() - elif cmd == 'getkey': - out = server.getkey() - elif cmd == 'getnewaddress': - out = server.getnewaddress() - elif cmd == 'stop': - out = server.stop() - except socket.error: - print "server not running" - sys.exit(1) - print out - sys.exit(0) - - else: - - wallet.set_path(wallet_path) - wallet.read() - - def server_thread(): - from SocketServer import ThreadingMixIn - from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer - server = SimpleJSONRPCServer(( host, port), requestHandler=authHandler) - server.register_function(get_new_address, 'getnewaddress') - server.register_function(get_num, 'getnum') - server.register_function(get_mpk, 'getkey') - server.register_function(do_stop, 'stop') - server.serve_forever() - - thread.start_new_thread(server_thread, ()) - while not stopping: time.sleep(0.1) - - - - diff --git a/client/ripemd.py b/client/ripemd.py deleted file mode 100644 index a9d652c..0000000 --- a/client/ripemd.py +++ /dev/null @@ -1,399 +0,0 @@ -## ripemd.py - pure Python implementation of the RIPEMD-160 algorithm. -## Bjorn Edstrom 16 december 2007. -## -## Copyrights -## ========== -## -## This code is a derived from an implementation by Markus Friedl which is -## subject to the following license. This Python implementation is not -## subject to any other license. -## -##/* -## * Copyright (c) 2001 Markus Friedl. All rights reserved. -## * -## * Redistribution and use in source and binary forms, with or without -## * modification, are permitted provided that the following conditions -## * are met: -## * 1. Redistributions of source code must retain the above copyright -## * notice, this list of conditions and the following disclaimer. -## * 2. Redistributions in binary form must reproduce the above copyright -## * notice, this list of conditions and the following disclaimer in the -## * documentation and/or other materials provided with the distribution. -## * -## * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -## * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -## * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -## * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -## * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -## * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -## * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -## * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -## * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -## * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -## */ -##/* -## * Preneel, Bosselaers, Dobbertin, "The Cryptographic Hash Function RIPEMD-160", -## * RSA Laboratories, CryptoBytes, Volume 3, Number 2, Autumn 1997, -## * ftp://ftp.rsasecurity.com/pub/cryptobytes/crypto3n2.pdf -## */ - -try: - import psyco - psyco.full() -except ImportError: - pass - -#block_size = 1 -digest_size = 20 -digestsize = 20 - -class RIPEMD160: - """Return a new RIPEMD160 object. An optional string argument - may be provided; if present, this string will be automatically - hashed.""" - - def __init__(self, arg=None): - self.ctx = RMDContext() - if arg: - self.update(arg) - self.dig = None - - def update(self, arg): - """update(arg)""" - RMD160Update(self.ctx, arg, len(arg)) - self.dig = None - - def digest(self): - """digest()""" - if self.dig: - return self.dig - ctx = self.ctx.copy() - self.dig = RMD160Final(self.ctx) - self.ctx = ctx - return self.dig - - def hexdigest(self): - """hexdigest()""" - dig = self.digest() - hex_digest = '' - for d in dig: - hex_digest += '%02x' % ord(d) - return hex_digest - - def copy(self): - """copy()""" - import copy - return copy.deepcopy(self) - - - -def new(arg=None): - """Return a new RIPEMD160 object. An optional string argument - may be provided; if present, this string will be automatically - hashed.""" - return RIPEMD160(arg) - - - -# -# Private. -# - -class RMDContext: - def __init__(self): - self.state = [0x67452301, 0xEFCDAB89, 0x98BADCFE, - 0x10325476, 0xC3D2E1F0] # uint32 - self.count = 0 # uint64 - self.buffer = [0]*64 # uchar - def copy(self): - ctx = RMDContext() - ctx.state = self.state[:] - ctx.count = self.count - ctx.buffer = self.buffer[:] - return ctx - -K0 = 0x00000000 -K1 = 0x5A827999 -K2 = 0x6ED9EBA1 -K3 = 0x8F1BBCDC -K4 = 0xA953FD4E - -KK0 = 0x50A28BE6 -KK1 = 0x5C4DD124 -KK2 = 0x6D703EF3 -KK3 = 0x7A6D76E9 -KK4 = 0x00000000 - -def ROL(n, x): - return ((x << n) & 0xffffffff) | (x >> (32 - n)) - -def F0(x, y, z): - return x ^ y ^ z - -def F1(x, y, z): - return (x & y) | (((~x) % 0x100000000) & z) - -def F2(x, y, z): - return (x | ((~y) % 0x100000000)) ^ z - -def F3(x, y, z): - return (x & z) | (((~z) % 0x100000000) & y) - -def F4(x, y, z): - return x ^ (y | ((~z) % 0x100000000)) - -def R(a, b, c, d, e, Fj, Kj, sj, rj, X): - a = ROL(sj, (a + Fj(b, c, d) + X[rj] + Kj) % 0x100000000) + e - c = ROL(10, c) - return a % 0x100000000, c - -PADDING = [0x80] + [0]*63 - -import sys -import struct - -def RMD160Transform(state, block): #uint32 state[5], uchar block[64] - x = [0]*16 - if sys.byteorder == 'little': - x = struct.unpack('<16L', ''.join([chr(x) for x in block[0:64]])) - else: - raise "Error!!" - a = state[0] - b = state[1] - c = state[2] - d = state[3] - e = state[4] - - #/* Round 1 */ - a, c = R(a, b, c, d, e, F0, K0, 11, 0, x); - e, b = R(e, a, b, c, d, F0, K0, 14, 1, x); - d, a = R(d, e, a, b, c, F0, K0, 15, 2, x); - c, e = R(c, d, e, a, b, F0, K0, 12, 3, x); - b, d = R(b, c, d, e, a, F0, K0, 5, 4, x); - a, c = R(a, b, c, d, e, F0, K0, 8, 5, x); - e, b = R(e, a, b, c, d, F0, K0, 7, 6, x); - d, a = R(d, e, a, b, c, F0, K0, 9, 7, x); - c, e = R(c, d, e, a, b, F0, K0, 11, 8, x); - b, d = R(b, c, d, e, a, F0, K0, 13, 9, x); - a, c = R(a, b, c, d, e, F0, K0, 14, 10, x); - e, b = R(e, a, b, c, d, F0, K0, 15, 11, x); - d, a = R(d, e, a, b, c, F0, K0, 6, 12, x); - c, e = R(c, d, e, a, b, F0, K0, 7, 13, x); - b, d = R(b, c, d, e, a, F0, K0, 9, 14, x); - a, c = R(a, b, c, d, e, F0, K0, 8, 15, x); #/* #15 */ - #/* Round 2 */ - e, b = R(e, a, b, c, d, F1, K1, 7, 7, x); - d, a = R(d, e, a, b, c, F1, K1, 6, 4, x); - c, e = R(c, d, e, a, b, F1, K1, 8, 13, x); - b, d = R(b, c, d, e, a, F1, K1, 13, 1, x); - a, c = R(a, b, c, d, e, F1, K1, 11, 10, x); - e, b = R(e, a, b, c, d, F1, K1, 9, 6, x); - d, a = R(d, e, a, b, c, F1, K1, 7, 15, x); - c, e = R(c, d, e, a, b, F1, K1, 15, 3, x); - b, d = R(b, c, d, e, a, F1, K1, 7, 12, x); - a, c = R(a, b, c, d, e, F1, K1, 12, 0, x); - e, b = R(e, a, b, c, d, F1, K1, 15, 9, x); - d, a = R(d, e, a, b, c, F1, K1, 9, 5, x); - c, e = R(c, d, e, a, b, F1, K1, 11, 2, x); - b, d = R(b, c, d, e, a, F1, K1, 7, 14, x); - a, c = R(a, b, c, d, e, F1, K1, 13, 11, x); - e, b = R(e, a, b, c, d, F1, K1, 12, 8, x); #/* #31 */ - #/* Round 3 */ - d, a = R(d, e, a, b, c, F2, K2, 11, 3, x); - c, e = R(c, d, e, a, b, F2, K2, 13, 10, x); - b, d = R(b, c, d, e, a, F2, K2, 6, 14, x); - a, c = R(a, b, c, d, e, F2, K2, 7, 4, x); - e, b = R(e, a, b, c, d, F2, K2, 14, 9, x); - d, a = R(d, e, a, b, c, F2, K2, 9, 15, x); - c, e = R(c, d, e, a, b, F2, K2, 13, 8, x); - b, d = R(b, c, d, e, a, F2, K2, 15, 1, x); - a, c = R(a, b, c, d, e, F2, K2, 14, 2, x); - e, b = R(e, a, b, c, d, F2, K2, 8, 7, x); - d, a = R(d, e, a, b, c, F2, K2, 13, 0, x); - c, e = R(c, d, e, a, b, F2, K2, 6, 6, x); - b, d = R(b, c, d, e, a, F2, K2, 5, 13, x); - a, c = R(a, b, c, d, e, F2, K2, 12, 11, x); - e, b = R(e, a, b, c, d, F2, K2, 7, 5, x); - d, a = R(d, e, a, b, c, F2, K2, 5, 12, x); #/* #47 */ - #/* Round 4 */ - c, e = R(c, d, e, a, b, F3, K3, 11, 1, x); - b, d = R(b, c, d, e, a, F3, K3, 12, 9, x); - a, c = R(a, b, c, d, e, F3, K3, 14, 11, x); - e, b = R(e, a, b, c, d, F3, K3, 15, 10, x); - d, a = R(d, e, a, b, c, F3, K3, 14, 0, x); - c, e = R(c, d, e, a, b, F3, K3, 15, 8, x); - b, d = R(b, c, d, e, a, F3, K3, 9, 12, x); - a, c = R(a, b, c, d, e, F3, K3, 8, 4, x); - e, b = R(e, a, b, c, d, F3, K3, 9, 13, x); - d, a = R(d, e, a, b, c, F3, K3, 14, 3, x); - c, e = R(c, d, e, a, b, F3, K3, 5, 7, x); - b, d = R(b, c, d, e, a, F3, K3, 6, 15, x); - a, c = R(a, b, c, d, e, F3, K3, 8, 14, x); - e, b = R(e, a, b, c, d, F3, K3, 6, 5, x); - d, a = R(d, e, a, b, c, F3, K3, 5, 6, x); - c, e = R(c, d, e, a, b, F3, K3, 12, 2, x); #/* #63 */ - #/* Round 5 */ - b, d = R(b, c, d, e, a, F4, K4, 9, 4, x); - a, c = R(a, b, c, d, e, F4, K4, 15, 0, x); - e, b = R(e, a, b, c, d, F4, K4, 5, 5, x); - d, a = R(d, e, a, b, c, F4, K4, 11, 9, x); - c, e = R(c, d, e, a, b, F4, K4, 6, 7, x); - b, d = R(b, c, d, e, a, F4, K4, 8, 12, x); - a, c = R(a, b, c, d, e, F4, K4, 13, 2, x); - e, b = R(e, a, b, c, d, F4, K4, 12, 10, x); - d, a = R(d, e, a, b, c, F4, K4, 5, 14, x); - c, e = R(c, d, e, a, b, F4, K4, 12, 1, x); - b, d = R(b, c, d, e, a, F4, K4, 13, 3, x); - a, c = R(a, b, c, d, e, F4, K4, 14, 8, x); - e, b = R(e, a, b, c, d, F4, K4, 11, 11, x); - d, a = R(d, e, a, b, c, F4, K4, 8, 6, x); - c, e = R(c, d, e, a, b, F4, K4, 5, 15, x); - b, d = R(b, c, d, e, a, F4, K4, 6, 13, x); #/* #79 */ - - aa = a; - bb = b; - cc = c; - dd = d; - ee = e; - - a = state[0] - b = state[1] - c = state[2] - d = state[3] - e = state[4] - - #/* Parallel round 1 */ - a, c = R(a, b, c, d, e, F4, KK0, 8, 5, x) - e, b = R(e, a, b, c, d, F4, KK0, 9, 14, x) - d, a = R(d, e, a, b, c, F4, KK0, 9, 7, x) - c, e = R(c, d, e, a, b, F4, KK0, 11, 0, x) - b, d = R(b, c, d, e, a, F4, KK0, 13, 9, x) - a, c = R(a, b, c, d, e, F4, KK0, 15, 2, x) - e, b = R(e, a, b, c, d, F4, KK0, 15, 11, x) - d, a = R(d, e, a, b, c, F4, KK0, 5, 4, x) - c, e = R(c, d, e, a, b, F4, KK0, 7, 13, x) - b, d = R(b, c, d, e, a, F4, KK0, 7, 6, x) - a, c = R(a, b, c, d, e, F4, KK0, 8, 15, x) - e, b = R(e, a, b, c, d, F4, KK0, 11, 8, x) - d, a = R(d, e, a, b, c, F4, KK0, 14, 1, x) - c, e = R(c, d, e, a, b, F4, KK0, 14, 10, x) - b, d = R(b, c, d, e, a, F4, KK0, 12, 3, x) - a, c = R(a, b, c, d, e, F4, KK0, 6, 12, x) #/* #15 */ - #/* Parallel round 2 */ - e, b = R(e, a, b, c, d, F3, KK1, 9, 6, x) - d, a = R(d, e, a, b, c, F3, KK1, 13, 11, x) - c, e = R(c, d, e, a, b, F3, KK1, 15, 3, x) - b, d = R(b, c, d, e, a, F3, KK1, 7, 7, x) - a, c = R(a, b, c, d, e, F3, KK1, 12, 0, x) - e, b = R(e, a, b, c, d, F3, KK1, 8, 13, x) - d, a = R(d, e, a, b, c, F3, KK1, 9, 5, x) - c, e = R(c, d, e, a, b, F3, KK1, 11, 10, x) - b, d = R(b, c, d, e, a, F3, KK1, 7, 14, x) - a, c = R(a, b, c, d, e, F3, KK1, 7, 15, x) - e, b = R(e, a, b, c, d, F3, KK1, 12, 8, x) - d, a = R(d, e, a, b, c, F3, KK1, 7, 12, x) - c, e = R(c, d, e, a, b, F3, KK1, 6, 4, x) - b, d = R(b, c, d, e, a, F3, KK1, 15, 9, x) - a, c = R(a, b, c, d, e, F3, KK1, 13, 1, x) - e, b = R(e, a, b, c, d, F3, KK1, 11, 2, x) #/* #31 */ - #/* Parallel round 3 */ - d, a = R(d, e, a, b, c, F2, KK2, 9, 15, x) - c, e = R(c, d, e, a, b, F2, KK2, 7, 5, x) - b, d = R(b, c, d, e, a, F2, KK2, 15, 1, x) - a, c = R(a, b, c, d, e, F2, KK2, 11, 3, x) - e, b = R(e, a, b, c, d, F2, KK2, 8, 7, x) - d, a = R(d, e, a, b, c, F2, KK2, 6, 14, x) - c, e = R(c, d, e, a, b, F2, KK2, 6, 6, x) - b, d = R(b, c, d, e, a, F2, KK2, 14, 9, x) - a, c = R(a, b, c, d, e, F2, KK2, 12, 11, x) - e, b = R(e, a, b, c, d, F2, KK2, 13, 8, x) - d, a = R(d, e, a, b, c, F2, KK2, 5, 12, x) - c, e = R(c, d, e, a, b, F2, KK2, 14, 2, x) - b, d = R(b, c, d, e, a, F2, KK2, 13, 10, x) - a, c = R(a, b, c, d, e, F2, KK2, 13, 0, x) - e, b = R(e, a, b, c, d, F2, KK2, 7, 4, x) - d, a = R(d, e, a, b, c, F2, KK2, 5, 13, x) #/* #47 */ - #/* Parallel round 4 */ - c, e = R(c, d, e, a, b, F1, KK3, 15, 8, x) - b, d = R(b, c, d, e, a, F1, KK3, 5, 6, x) - a, c = R(a, b, c, d, e, F1, KK3, 8, 4, x) - e, b = R(e, a, b, c, d, F1, KK3, 11, 1, x) - d, a = R(d, e, a, b, c, F1, KK3, 14, 3, x) - c, e = R(c, d, e, a, b, F1, KK3, 14, 11, x) - b, d = R(b, c, d, e, a, F1, KK3, 6, 15, x) - a, c = R(a, b, c, d, e, F1, KK3, 14, 0, x) - e, b = R(e, a, b, c, d, F1, KK3, 6, 5, x) - d, a = R(d, e, a, b, c, F1, KK3, 9, 12, x) - c, e = R(c, d, e, a, b, F1, KK3, 12, 2, x) - b, d = R(b, c, d, e, a, F1, KK3, 9, 13, x) - a, c = R(a, b, c, d, e, F1, KK3, 12, 9, x) - e, b = R(e, a, b, c, d, F1, KK3, 5, 7, x) - d, a = R(d, e, a, b, c, F1, KK3, 15, 10, x) - c, e = R(c, d, e, a, b, F1, KK3, 8, 14, x) #/* #63 */ - #/* Parallel round 5 */ - b, d = R(b, c, d, e, a, F0, KK4, 8, 12, x) - a, c = R(a, b, c, d, e, F0, KK4, 5, 15, x) - e, b = R(e, a, b, c, d, F0, KK4, 12, 10, x) - d, a = R(d, e, a, b, c, F0, KK4, 9, 4, x) - c, e = R(c, d, e, a, b, F0, KK4, 12, 1, x) - b, d = R(b, c, d, e, a, F0, KK4, 5, 5, x) - a, c = R(a, b, c, d, e, F0, KK4, 14, 8, x) - e, b = R(e, a, b, c, d, F0, KK4, 6, 7, x) - d, a = R(d, e, a, b, c, F0, KK4, 8, 6, x) - c, e = R(c, d, e, a, b, F0, KK4, 13, 2, x) - b, d = R(b, c, d, e, a, F0, KK4, 6, 13, x) - a, c = R(a, b, c, d, e, F0, KK4, 5, 14, x) - e, b = R(e, a, b, c, d, F0, KK4, 15, 0, x) - d, a = R(d, e, a, b, c, F0, KK4, 13, 3, x) - c, e = R(c, d, e, a, b, F0, KK4, 11, 9, x) - b, d = R(b, c, d, e, a, F0, KK4, 11, 11, x) #/* #79 */ - - t = (state[1] + cc + d) % 0x100000000; - state[1] = (state[2] + dd + e) % 0x100000000; - state[2] = (state[3] + ee + a) % 0x100000000; - state[3] = (state[4] + aa + b) % 0x100000000; - state[4] = (state[0] + bb + c) % 0x100000000; - state[0] = t % 0x100000000; - - pass - - -def RMD160Update(ctx, inp, inplen): - if type(inp) == str: - inp = [ord(i)&0xff for i in inp] - - have = (ctx.count / 8) % 64 - need = 64 - have - ctx.count += 8 * inplen - off = 0 - if inplen >= need: - if have: - for i in xrange(need): - ctx.buffer[have+i] = inp[i] - RMD160Transform(ctx.state, ctx.buffer) - off = need - have = 0 - while off + 64 <= inplen: - RMD160Transform(ctx.state, inp[off:]) #<--- - off += 64 - if off < inplen: - # memcpy(ctx->buffer + have, input+off, len-off); - for i in xrange(inplen - off): - ctx.buffer[have+i] = inp[off+i] - -def RMD160Final(ctx): - size = struct.pack(". - - -import sys, base64, os, re, hashlib, copy, operator, ast, threading, random - -try: - import ecdsa - from ecdsa.util import string_to_number, number_to_string -except: - print "python-ecdsa does not seem to be installed. Try 'sudo easy_install ecdsa'" - sys.exit(1) - -try: - import aes -except: - print "AES does not seem to be installed. Try 'sudo easy_install slowaes'" - sys.exit(1) - - -############ functions from pywallet ##################### - -addrtype = 0 - -def hash_160(public_key): - try: - md = hashlib.new('ripemd160') - md.update(hashlib.sha256(public_key).digest()) - return md.digest() - except: - import ripemd - md = ripemd.new(hashlib.sha256(public_key).digest()) - 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): - 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 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 Hash(data): - return hashlib.sha256(hashlib.sha256(data).digest()).digest() - -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): - vchIn = chr(addrtype+128) + secret - return EncodeBase58Check(vchIn) - -def ASecretToSecret(key): - vch = DecodeBase58Check(key) - if vch and vch[0] == chr(addrtype+128): - return vch[1:] - else: - return False - -########### end pywallet functions ####################### - -# 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 int_to_hex(i, length=1): - s = hex(i)[2:].rstrip('L') - s = "0"*(2*length - len(s)) + s - return s.decode('hex')[::-1].encode('hex') - - -# AES -EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s)) -DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e)) - - - -# secp256k1, http://www.oid-info.com/get/1.3.132.0.10 -_p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL -_r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L -_b = 0x0000000000000000000000000000000000000000000000000000000000000007L -_a = 0x0000000000000000000000000000000000000000000000000000000000000000L -_Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L -_Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L -curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b ) -generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r ) -oid_secp256k1 = (1,3,132,0,10) -SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) - - -def filter(s): - out = re.sub('( [^\n]*|)\n','',s) - out = out.replace(' ','') - out = out.replace('\n','') - return out - -def raw_tx( inputs, outputs, for_sig = None ): - s = int_to_hex(1,4) + ' version\n' - s += int_to_hex( len(inputs) ) + ' number of inputs\n' - for i in range(len(inputs)): - _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i] - s += p_hash.decode('hex')[::-1].encode('hex') + ' prev hash\n' - s += int_to_hex(p_index,4) + ' prev index\n' - if for_sig is None: - sig = sig + chr(1) # hashtype - script = int_to_hex( len(sig)) + ' push %d bytes\n'%len(sig) - script += sig.encode('hex') + ' sig\n' - pubkey = chr(4) + pubkey - script += int_to_hex( len(pubkey)) + ' push %d bytes\n'%len(pubkey) - script += pubkey.encode('hex') + ' pubkey\n' - elif for_sig==i: - script = p_script + ' scriptsig \n' - else: - script='' - s += int_to_hex( len(filter(script))/2 ) + ' script length \n' - s += script - s += "ffffffff" + ' sequence\n' - s += int_to_hex( len(outputs) ) + ' number of outputs\n' - for output in outputs: - addr, amount = output - s += int_to_hex( amount, 8) + ' amount: %d\n'%amount - script = '76a9' # op_dup, op_hash_160 - script += '14' # push 0x14 bytes - script += bc_address_to_hash_160(addr).encode('hex') - script += '88ac' # op_equalverify, op_checksig - s += int_to_hex( len(filter(script))/2 ) + ' script length \n' - s += script + ' script \n' - s += int_to_hex(0,4) # lock time - if for_sig is not None: s += int_to_hex(1, 4) # hash type - return s - - - - -def format_satoshis(x, is_diff=False): - from decimal import Decimal - s = str( Decimal(x) /100000000 ) - if is_diff and x>0: - s = "+" + s - if not '.' in s: s += '.' - p = s.find('.') - s += " "*( 9 - ( len(s) - p )) - s = " "*( 5 - ( p )) + s - return s - - -from version import ELECTRUM_VERSION, SEED_VERSION -from interface import DEFAULT_SERVERS - - - - -class Wallet: - def __init__(self, gui_callback = lambda: None): - - self.electrum_version = ELECTRUM_VERSION - self.seed_version = SEED_VERSION - self.gui_callback = gui_callback - - self.gap_limit = 5 # configuration - self.fee = 100000 - self.master_public_key = '' - - # saved fields - self.use_encryption = False - self.addresses = [] # receiving addresses visible for user - self.change_addresses = [] # addresses used as change - self.seed = '' # encrypted - self.history = {} - self.labels = {} # labels for addresses and transactions - self.aliases = {} # aliases for addresses - self.authorities = {} # trusted addresses - - self.receipts = {} # signed URIs - self.receipt = None # next receipt - self.addressbook = [] # outgoing addresses, for payments - - # not saved - self.tx_history = {} - - self.imported_keys = {} - self.remote_url = None - - self.was_updated = True - self.blocks = -1 - self.banner = '' - self.up_to_date_event = threading.Event() - self.up_to_date_event.clear() - self.up_to_date = False - self.lock = threading.Lock() - self.tx_event = threading.Event() - - # - self.addresses_waiting_for_status = [] - self.addresses_waiting_for_history = [] - self.pick_random_server() - - - - def pick_random_server(self): - self.server = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created - - def is_up_to_date(self): - return self.interface.responses.empty() and not ( self.addresses_waiting_for_status or self.addresses_waiting_for_history ) - - - def set_server(self, server): - # raise an error if the format isnt correct - a,b,c = server.split(':') - b = int(b) - assert c in ['t','h','n'] - # set the server - if server != self.server: - self.server = server - self.save() - self.interface.is_connected = False # this exits the polling loop - - def set_path(self, wallet_path): - - if wallet_path is not None: - self.path = wallet_path - else: - # backward compatibility: look for wallet file in the default data directory - if "HOME" in os.environ: - wallet_dir = os.path.join( os.environ["HOME"], '.electrum') - elif "LOCALAPPDATA" in os.environ: - wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' ) - elif "APPDATA" in os.environ: - wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' ) - else: - raise BaseException("No home directory found in environment variables.") - - if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir ) - self.path = os.path.join( wallet_dir, 'electrum.dat' ) - - def import_key(self, keypair, password): - address, key = keypair.split(':') - if not self.is_valid(address): return False - if address in self.all_addresses(): return False - b = ASecretToSecret( key ) - if not b: return False - secexp = int( b.encode('hex'), 16) - private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 ) - # sanity check - public_key = private_key.get_verifying_key() - if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False - self.imported_keys[address] = self.pw_encode( key, password ) - return True - - def new_seed(self, password): - seed = "%032x"%ecdsa.util.randrange( pow(2,128) ) - #self.init_mpk(seed) - # encrypt - self.seed = self.pw_encode( seed, password ) - - - def init_mpk(self,seed): - # public key - curve = SECP256k1 - secexp = self.stretch_key(seed) - master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) - self.master_public_key = master_private_key.get_verifying_key().to_string() - - def all_addresses(self): - return self.addresses + self.change_addresses + self.imported_keys.keys() - - def is_mine(self, address): - return address in self.all_addresses() - - def is_change(self, address): - return address in self.change_addresses - - def is_valid(self,addr): - ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z') - if not ADDRESS_RE.match(addr): return False - try: - h = bc_address_to_hash_160(addr) - except: - return False - return addr == hash_160_to_bc_address(h) - - 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,n,for_change): - return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) ) - - def get_private_key(self, address, password): - """ Privatekey(type,n) = Master_private_key + H(n|S|type) """ - order = generator_secp256k1.order() - - if address in self.imported_keys.keys(): - b = self.pw_decode( self.imported_keys[address], password ) - b = ASecretToSecret( b ) - secexp = int( b.encode('hex'), 16) - else: - if address in self.addresses: - n = self.addresses.index(address) - for_change = False - elif address in self.change_addresses: - n = self.change_addresses.index(address) - for_change = True - else: - raise BaseException("unknown address") - try: - seed = self.pw_decode( self.seed, password) - except: - raise BaseException("Invalid password") - secexp = self.stretch_key(seed) - secexp = ( secexp + self.get_sequence(n,for_change) ) % order - - pk = number_to_string(secexp,order) - return pk - - def msg_magic(self, message): - return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message - - def sign_message(self, address, message, password): - private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 ) - public_key = private_key.get_verifying_key() - signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string ) - assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string) - for i in range(4): - sig = base64.b64encode( chr(27+i) + signature ) - try: - self.verify_message( address, sig, message) - return sig - except: - continue - else: - raise BaseException("error: cannot sign message") - - - def verify_message(self, address, signature, message): - """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """ - from ecdsa import numbertheory, ellipticcurve, util - import msqr - curve = curve_secp256k1 - G = generator_secp256k1 - order = G.order() - # extract r,s from signature - sig = base64.b64decode(signature) - if len(sig) != 65: raise BaseException("Wrong encoding") - r,s = util.sigdecode_string(sig[1:], order) - recid = ord(sig[0]) - 27 - # 1.1 - x = r + (recid/2) * order - # 1.3 - alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p() - beta = msqr.modular_sqrt(alpha, curve.p()) - y = beta if (beta - recid) % 2 == 0 else curve.p() - beta - # 1.4 the constructor checks that nR is at infinity - R = ellipticcurve.Point(curve, x, y, order) - # 1.5 compute e from message: - h = Hash( self.msg_magic( 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 ) - public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 ) - # check that Q is the 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( '04'.decode('hex') + public_key.to_string() ) - # print addr - if address != addr: - print "bad signature" - raise BaseException("Bad signature") - - - def create_new_address(self, for_change): - """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """ - curve = SECP256k1 - n = len(self.change_addresses) if for_change else len(self.addresses) - z = self.get_sequence(n,for_change) - master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 ) - pubkey_point = master_public_key.pubkey.point + z*curve.generator - public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 ) - address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() ) - if for_change: - self.change_addresses.append(address) - else: - self.addresses.append(address) - - self.history[address] = [] - print address - return address - - - - def synchronize(self): - if not self.master_public_key: - return [] - - new_addresses = [] - while True: - if self.change_addresses == []: - new_addresses.append( self.create_new_address(True) ) - continue - a = self.change_addresses[-1] - if self.history.get(a): - new_addresses.append( self.create_new_address(True) ) - else: - break - - n = self.gap_limit - while True: - if len(self.addresses) < n: - new_addresses.append( self.create_new_address(False) ) - continue - if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]: - break - else: - new_addresses.append( self.create_new_address(False) ) - - if self.remote_url: - num = self.get_remote_number() - while len(self.addresses) 1 ) or ( len(self.addresses) > self.gap_limit ) - - def fill_addressbook(self): - for tx in self.tx_history.values(): - if tx['value']<0: - for i in tx['outputs']: - if not self.is_mine(i) and i not in self.addressbook: - self.addressbook.append(i) - # redo labels - self.update_tx_labels() - - - def save(self): - s = { - 'seed_version':self.seed_version, - 'use_encryption':self.use_encryption, - 'master_public_key': self.master_public_key.encode('hex'), - 'fee':self.fee, - 'server':self.server, - 'seed':self.seed, - 'addresses':self.addresses, - 'change_addresses':self.change_addresses, - 'history':self.history, - 'labels':self.labels, - 'contacts':self.addressbook, - 'imported_keys':self.imported_keys, - 'aliases':self.aliases, - 'authorities':self.authorities, - 'receipts':self.receipts, - } - f = open(self.path,"w") - f.write( repr(s) ) - f.close() - - def read(self): - import interface - - upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic.""" - self.file_exists = False - try: - f = open(self.path,"r") - data = f.read() - f.close() - except: - return - data = interface.old_to_new(data) - try: - d = ast.literal_eval( data ) - self.seed_version = d.get('seed_version') - self.master_public_key = d.get('master_public_key').decode('hex') - self.use_encryption = d.get('use_encryption') - self.fee = int( d.get('fee') ) - self.seed = d.get('seed') - self.server = d.get('server') - #blocks = d.get('blocks') - self.addresses = d.get('addresses') - self.change_addresses = d.get('change_addresses') - self.history = d.get('history') - self.labels = d.get('labels') - self.addressbook = d.get('contacts') - self.imported_keys = d.get('imported_keys',{}) - self.aliases = d.get('aliases',{}) - self.authorities = d.get('authorities',{}) - self.receipts = d.get('receipts',{}) - except: - raise BaseException("cannot read wallet file") - - self.update_tx_history() - - if self.seed_version != SEED_VERSION: - raise BaseException(upgrade_msg) - - if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk() - - self.file_exists = True - - - - - def get_addr_balance(self, addr): - if self.is_mine(addr): - h = self.history.get(addr) - else: - h = self.interface.retrieve_history(addr) - if not h: return 0,0 - c = u = 0 - for item in h: - v = item['value'] - if item['height']: - c += v - else: - u += v - return c, u - - def get_balance(self): - conf = unconf = 0 - for addr in self.all_addresses(): - c, u = self.get_addr_balance(addr) - conf += c - unconf += u - return conf, unconf - - - def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ): - """ todo: minimize tx size """ - total = 0 - fee = self.fee if fixed_fee is None else fixed_fee - - coins = [] - domain = [from_addr] if from_addr else self.all_addresses() - for addr in domain: - h = self.history.get(addr) - if h is None: continue - for item in h: - if item.get('raw_output_script'): - coins.append( (addr,item)) - - coins = sorted( coins, key = lambda x: x[1]['timestamp'] ) - inputs = [] - for c in coins: - addr, item = c - v = item.get('value') - total += v - inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) ) - fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee - if total >= amount + fee: break - else: - #print "not enough funds: %d %d"%(total, fee) - inputs = [] - return inputs, total, fee - - def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ): - outputs = [ (to_addr, amount) ] - change_amount = total - ( amount + fee ) - if change_amount != 0: - # normally, the update thread should ensure that the last change address is unused - if not change_addr: - change_addr = self.change_addresses[-1] - outputs.append( ( change_addr, change_amount) ) - return outputs - - def sign_inputs( self, inputs, outputs, password ): - s_inputs = [] - for i in range(len(inputs)): - addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i] - private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 ) - public_key = private_key.get_verifying_key() - pubkey = public_key.to_string() - tx = filter( raw_tx( inputs, outputs, for_sig = i ) ) - sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der ) - assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der) - s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) ) - return s_inputs - - def pw_encode(self, s, password): - if password: - secret = Hash(password) - return EncodeAES(secret, s) - else: - return s - - def pw_decode(self, s, password): - if password is not None: - secret = Hash(password) - d = DecodeAES(secret, s) - if s == self.seed: - try: - d.decode('hex') - except: - raise BaseException("Invalid password") - return d - else: - return s - - def get_status(self, address): - h = self.history.get(address) - if not h: - status = None - else: - lastpoint = h[-1] - status = lastpoint['block_hash'] - if status == 'mempool': - status = status + ':%d'% len(h) - return status - - def receive_status_callback(self, addr, status): - with self.lock: - if self.get_status(addr) != status: - #print "updating status for", addr, status - self.addresses_waiting_for_history.append(addr) - self.interface.get_history(addr) - if addr in self.addresses_waiting_for_status: - self.addresses_waiting_for_status.remove(addr) - - def receive_history_callback(self, addr, data): - #print "updating history for", addr - with self.lock: - self.history[addr] = data - self.update_tx_history() - self.save() - if addr in self.addresses_waiting_for_history: self.addresses_waiting_for_history.remove(addr) - - def get_tx_history(self): - lines = self.tx_history.values() - lines = sorted(lines, key=operator.itemgetter("timestamp")) - return lines - - def update_tx_history(self): - self.tx_history= {} - for addr in self.all_addresses(): - h = self.history.get(addr) - if h is None: continue - for tx in h: - tx_hash = tx['tx_hash'] - line = self.tx_history.get(tx_hash) - if not line: - self.tx_history[tx_hash] = copy.copy(tx) - line = self.tx_history.get(tx_hash) - else: - line['value'] += tx['value'] - if line['height'] == 0: - line['timestamp'] = 1e12 - self.update_tx_labels() - - def update_tx_labels(self): - for tx in self.tx_history.values(): - default_label = '' - if tx['value']<0: - for o_addr in tx['outputs']: - if not self.is_change(o_addr): - dest_label = self.labels.get(o_addr) - if dest_label: - default_label = 'to: ' + dest_label - else: - default_label = 'to: ' + o_addr - else: - for o_addr in tx['outputs']: - if self.is_mine(o_addr) and not self.is_change(o_addr): - dest_label = self.labels.get(o_addr) - if dest_label: - default_label = 'at: ' + dest_label - else: - default_label = 'at: ' + o_addr - tx['default_label'] = default_label - - def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None): - if not self.is_valid(to_address): - raise BaseException("Invalid address") - inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr ) - if not inputs: - raise BaseException("Not enough funds") - outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr ) - s_inputs = self.sign_inputs( inputs, outputs, password ) - - tx = filter( raw_tx( s_inputs, outputs ) ) - if to_address not in self.addressbook: - self.addressbook.append(to_address) - if label: - tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex') - self.labels[tx_hash] = label - - return tx - - def sendtx(self, tx): - tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex') - self.tx_event.clear() - self.interface.send([('blockchain.transaction.broadcast', [tx])]) - self.tx_event.wait() - out = self.tx_result - if out != tx_hash: - return False, "error: " + out - if self.receipt: - self.receipts[tx_hash] = self.receipt - self.receipt = None - return True, out - - - def read_alias(self, alias): - # this might not be the right place for this function. - import urllib - - m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias) - m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias) - if m1: - url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) - elif m2: - url = 'http://' + alias + '/bitcoin.id' - else: - return '' - try: - lines = urllib.urlopen(url).readlines() - except: - return '' - - # line 0 - line = lines[0].strip().split(':') - if len(line) == 1: - auth_name = None - target = signing_addr = line[0] - else: - target, auth_name, signing_addr, signature = line - msg = "alias:%s:%s:%s"%(alias,target,auth_name) - print msg, signature - self.verify_message(signing_addr, signature, msg) - - # other lines are signed updates - for line in lines[1:]: - line = line.strip() - if not line: continue - line = line.split(':') - previous = target - print repr(line) - target, signature = line - self.verify_message(previous, signature, "alias:%s:%s"%(alias,target)) - - if not self.is_valid(target): - raise BaseException("Invalid bitcoin address") - - return target, signing_addr, auth_name - - def update_password(self, seed, new_password): - if new_password == '': new_password = None - self.use_encryption = (new_password != None) - self.seed = self.pw_encode( seed, new_password) - for k in self.imported_keys.keys(): - a = self.imported_keys[k] - b = self.pw_decode(a, password) - c = self.pw_encode(b, new_password) - self.imported_keys[k] = c - self.save() - - def get_alias(self, alias, interactive = False, show_message=None, question = None): - try: - target, signing_address, auth_name = self.read_alias(alias) - except BaseException, e: - # raise exception if verify fails (verify the chain) - if interactive: - show_message("Alias error: " + e.message) - return - - print target, signing_address, auth_name - - if auth_name is None: - a = self.aliases.get(alias) - if not a: - msg = "Warning: the alias '%s' is self-signed.\nThe signing address is %s.\n\nDo you want to add this alias to your list of contacts?"%(alias,signing_address) - if interactive and question( msg ): - self.aliases[alias] = (signing_address, target) - else: - target = None - else: - if signing_address != a[0]: - msg = "Warning: the key of alias '%s' has changed since your last visit! It is possible that someone is trying to do something nasty!!!\nDo you accept to change your trusted key?"%alias - if interactive and question( msg ): - self.aliases[alias] = (signing_address, target) - else: - target = None - else: - if signing_address not in self.authorities.keys(): - msg = "The alias: '%s' links to %s\n\nWarning: this alias was signed by an unknown key.\nSigning authority: %s\nSigning address: %s\n\nDo you want to add this key to your list of trusted keys?"%(alias,target,auth_name,signing_address) - if interactive and question( msg ): - self.authorities[signing_address] = auth_name - else: - target = None - - if target: - self.aliases[alias] = (signing_address, target) - - return target - - - def parse_url(self, url, show_message, question): - o = url[8:].split('?') - address = o[0] - if len(o)>1: - params = o[1].split('&') - else: - params = [] - - amount = label = message = signature = identity = '' - for p in params: - k,v = p.split('=') - uv = urldecode(v) - if k == 'amount': amount = uv - elif k == 'message': message = uv - elif k == 'label': label = uv - elif k == 'signature': - identity, signature = uv.split(':') - url = url.replace('&%s=%s'%(k,v),'') - else: - print k,v - - if signature: - if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity): - signing_address = self.get_alias(identity, True, show_message, question) - elif self.is_valid(identity): - signing_address = identity - else: - signing_address = None - if not signing_address: - return - try: - self.verify_message(signing_address, signature, url ) - self.receipt = (signing_address, signature, url) - except: - show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.') - address = amount = label = identity = message = '' - - if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address): - payto_address = self.get_alias(address, True, show_message, question) - if payto_address: - address = address + ' <' + payto_address + '>' - - return address, amount, label, message, signature, identity, url - - - def update(self): - self.interface.poke() - self.up_to_date_event.wait() - - - diff --git a/docs/android.html b/docs/android.html new file mode 100644 index 0000000..1aed1a4 --- /dev/null +++ b/docs/android.html @@ -0,0 +1,60 @@ + + +
+

Electrum for Android

+ +This page explains how to install Electrum on Android devices.

+ +Please note that Electrum is not distributed as a binary package, but +as python source code; this gives users the possibility to see what +the code is doing, and to check that it does not contain malware. The +downside is that installation is slightly more complicated than +downloading an app on the Android market, but it remains very +simple.

+ +It is possible to print this page on paper and to install everything from +QR codes. If you encounter problems, you may find help at + +this link. + + +

1. Download and install Google Scripting Layer for Android

+ +You can get +it here, +or by scanning the following qr code:
+ + + +

2. Download and install Python for Android

+ +You can get +it here, +or by scanning the following qr code:
+ +
+Once you have installed the apk, launch the Python for Android application and click 'install' + +

3. Download the Electrum install script

+ +Download e4a_install.py and install it in your sl4a/scripts directory. +You can do it manually, or from QR code, as follows: +
+1. Launch SL4A.
+2. Press the Menu button.
+3. Tap Add.
+4. Tap Scan Barcode.
+5. Scan the following QRcode:
+
+ +
This will install a script named e4a_install.py
+ +

4. Download and install Electrum

+
+1. Tap e4a_install.py: it will download and install a directory named "Electrum-0.43d"
+2. To launch Electrum, visit the "Electrum-0.43d" directory and tap 'electrum4a.py'
+
+ + diff --git a/electrum b/electrum new file mode 100755 index 0000000..011d56f --- /dev/null +++ b/electrum @@ -0,0 +1,408 @@ +#!/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 . + +import re, sys, getpass + +from optparse import OptionParser +from wallet import Wallet, SecretToASecret +from interface import WalletSynchronizer +from decimal import Decimal +from wallet import format_satoshis + +known_commands = ['help', 'validateaddress', 'balance', 'contacts', 'create', 'restore', 'payto', 'sendtx', 'password', 'addresses', 'history', 'label', 'mktx','seed','import','signmessage','verifymessage','eval'] +offline_commands = ['password', 'mktx', 'history', 'label', 'contacts', 'help', 'validateaddress', 'signmessage', 'verifymessage', 'eval', 'create', 'addresses', 'import', 'seed'] +protected_commands = ['payto', 'password', 'mktx', 'seed', 'import','signmessage' ] + +if __name__ == '__main__': + + usage = "usage: %prog [options] command args\nCommands: "+ (', '.join(known_commands)) + parser = OptionParser(usage=usage) + parser.add_option("-g", "--gui", dest="gui", default="qt", help="gui") + parser.add_option("-w", "--wallet", dest="wallet_path", help="wallet path (default: electrum.dat)") + parser.add_option("-a", "--all", action="store_true", dest="show_all", default=False, help="show all addresses") + parser.add_option("-b", "--balance", action="store_true", dest="show_balance", default=False, help="show the balance at listed addresses") + parser.add_option("-k", "--keys",action="store_true", dest="show_keys",default=False, help="show the private keys of listed addresses") + parser.add_option("-f", "--fee", dest="tx_fee", default="0.005", help="set tx fee") + parser.add_option("-s", "--fromaddr", dest="from_addr", default=None, help="set source address for payto/mktx. if it isn't in the wallet, it will ask for the private key unless supplied in the format public_key:private_key. It's not saved in the wallet.") + parser.add_option("-c", "--changeaddr", dest="change_addr", default=None, help="set the change address for payto/mktx. default is a spare address, or the source address if it's not in the wallet") + parser.add_option("-r", "--remote", dest="remote_url", default=None, help="URL of a remote wallet") + options, args = parser.parse_args() + + wallet = Wallet() + wallet.set_path(options.wallet_path) + wallet.read() + wallet.remote_url = options.remote_url + + if len(args)==0: + url = None + cmd = 'gui' + elif len(args)==1 and re.match('^bitcoin:', args[0]): + url = args[0] + cmd = 'gui' + else: + cmd = args[0] + firstarg = args[1] if len(args) > 1 else '' + + if cmd == 'gui': + if options.gui=='gtk': + import gui + elif options.gui=='qt': + import gui_qt as gui + else: + print "unknown gui", options.gui + exit(1) + + gui = gui.ElectrumGui(wallet) + WalletSynchronizer(wallet,True).start() + + try: + found = wallet.file_exists + if not found: + found = gui.restore_or_create() + except SystemExit, e: + exit(e) + except BaseException, e: + import traceback + traceback.print_exc(file=sys.stdout) + #gui.show_message(e.message) + exit(1) + + if not found: exit(1) + + gui.main(url) + wallet.save() + sys.exit(0) + + if cmd not in known_commands: + cmd = 'help' + + if not wallet.file_exists and cmd not in ['help','create','restore']: + print "Wallet file not found." + print "Type 'electrum create' to create a new wallet, or provide a path to a wallet with the -w option" + sys.exit(0) + + if cmd in ['create', 'restore']: + import mnemonic + if wallet.file_exists: + print "remove the existing wallet first!" + sys.exit(0) + password = getpass.getpass("Password (hit return if you do not wish to encrypt your wallet):") + if password: + password2 = getpass.getpass("Confirm password:") + if password != password2: + print "error" + sys.exit(1) + else: + password = None + + w_host, w_port, w_protocol = wallet.server.split(':') + host = raw_input("server (default:%s):"%w_host) + port = raw_input("port (default:%s):"%w_port) + protocol = raw_input("protocol [t=tcp;h=http;n=native] (default:%s):"%w_protocol) + fee = raw_input("fee (default:%s):"%( str(Decimal(wallet.fee)/100000000)) ) + gap = raw_input("gap limit (default 5):") + if host: w_host = host + if port: w_port = port + if protocol: w_protocol = protocol + wallet.server = w_host + ':' + w_port + ':' +w_protocol + if fee: wallet.fee = float(fee) + if gap: wallet.gap_limit = int(gap) + + if cmd == 'restore': + seed = raw_input("seed:") + try: + seed.decode('hex') + except: + print "not hex, trying decode" + seed = mnemonic.mn_decode( seed.split(' ') ) + if not seed: + print "no seed" + sys.exit(1) + + wallet.seed = str(seed) + WalletSynchronizer(wallet).start() + print "recovering wallet..." + wallet.init_mpk( wallet.seed ) + wallet.up_to_date_event.clear() + wallet.up_to_date = False + wallet.update() + if wallet.is_found(): + wallet.fill_addressbook() + wallet.save() + print "recovery successful" + else: + print "found no history for this wallet" + else: + wallet.new_seed(None) + wallet.init_mpk( wallet.seed ) + wallet.synchronize() # there is no wallet thread + wallet.save() + print "Your wallet generation seed is: " + wallet.seed + print "Please keep it in a safe place; if you lose it, you will not be able to restore your wallet." + print "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:" + print "\""+' '.join(mnemonic.mn_encode(wallet.seed))+"\"" + + # check syntax + if cmd in ['payto', 'mktx']: + try: + to_address = args[1] + amount = int( 100000000 * Decimal(args[2]) ) + change_addr = None + label = ' '.join(args[3:]) + if options.tx_fee: + options.tx_fee = int( 100000000 * Decimal(options.tx_fee) ) + except: + firstarg = cmd + cmd = 'help' + + # open session + if cmd not in offline_commands: + WalletSynchronizer(wallet).start() + wallet.update() + wallet.save() + + # check if --from_addr not in wallet (for mktx/payto) + is_temporary = False + from_addr = None + if options.from_addr: + from_addr = options.from_addr + if from_addr not in wallet.all_addresses(): + is_temporary = True + + # commands needing password + if cmd in protected_commands or ( cmd=='addresses' and options.show_keys): + password = getpass.getpass('Password:') if wallet.use_encryption and not is_temporary else None + # check password + try: + wallet.pw_decode( wallet.seed, password) + except: + print "invalid password" + exit(1) + + if cmd == 'import': + keypair = args[1] + if wallet.import_key(keypair,password): + print "keypair imported" + else: + print "error" + wallet.save() + + if cmd=='help': + cmd2 = firstarg + if cmd2 not in known_commands: + print "known commands:", ', '.join(known_commands) + print "'electrum help ' shows the help on a specific command" + print "'electrum --help' shows the list of options" + elif cmd2 == 'balance': + print "Display the balance of your wallet or a specific address. The address does not have to be a owned address (you know the private key)." + print "syntax: balance [
]" + elif cmd2 == 'contacts': + print "show your list of contacts" + elif cmd2 == 'payto': + print "payto [label]" + print "create and broadcast a transaction." + print " can be a bitcoin address or a label" + print "options: --fee, --fromaddr, --changeaddr" + elif cmd2== 'sendtx': + print "sendtx " + print "broadcast a transaction to the network. must be in hexadecimal" + elif cmd2 == 'password': + print "change your password" + elif cmd2 == 'addresses': + print "show your list of addresses. options: -a, -k, -b" + elif cmd2 == 'history': + print "show the transaction history" + elif cmd2 == 'label': + print "assign a label to an item" + elif cmd2 == 'gtk': + print "start the GUI" + elif cmd2 == 'mktx': + print "create a signed transaction. password protected" + print "syntax: mktx [label]" + print "options: --fee, --fromaddr, --changeaddr" + elif cmd2 == 'seed': + print "show generation seed of your wallet. password protected." + elif cmd2 == 'eval': + print "Run python eval() on an object\nSyntax: eval \nExample: eval \"wallet.aliases\"" + + elif cmd == 'seed': + import mnemonic + seed = wallet.pw_decode( wallet.seed, password) + print seed, '"'+' '.join(mnemonic.mn_encode(seed))+'"' + + elif cmd == 'validateaddress': + addr = args[1] + print wallet.is_valid(addr) + + elif cmd == 'balance': + try: + addrs = args[1:] + except: + pass + if addrs == []: + c, u = wallet.get_balance() + if u: + print Decimal( c ) / 100000000 , Decimal( u ) / 100000000 + else: + print Decimal( c ) / 100000000 + else: + for addr in addrs: + c, u = wallet.get_addr_balance(addr) + if u: + print "%s %s, %s" % (addr, str(Decimal(c)/100000000), str(Decimal(u)/100000000)) + else: + print "%s %s" % (addr, str(Decimal(c)/100000000)) + + elif cmd in [ 'contacts']: + for addr in wallet.addressbook: + print addr, " ", wallet.labels.get(addr) + + elif cmd == 'eval': + print eval(args[1]) + wallet.save() + + elif cmd in [ 'addresses']: + for addr in wallet.all_addresses(): + if options.show_all or not wallet.is_change(addr): + label = wallet.labels.get(addr) + _type = '' + if wallet.is_change(addr): _type = "[change]" + if addr in wallet.imported_keys.keys(): _type = "[imported]" + if label is None: label = '' + if options.show_balance: + h = wallet.history.get(addr,[]) + ni = no = 0 + for item in h: + if item['is_in']: ni += 1 + else: no += 1 + b = "%d %d %s"%(no, ni, str(Decimal(wallet.get_addr_balance(addr)[0])/100000000)) + else: b='' + if options.show_keys: + pk = wallet.get_private_key(addr, password) + addr = addr + ':' + SecretToASecret(pk) + print addr, b, _type, label + + if cmd == 'history': + lines = wallet.get_tx_history() + b = 0 + for line in lines: + import datetime + v = line['value'] + b += v + try: + time_str = str( datetime.datetime.fromtimestamp( line['timestamp'])) + except: + print line['timestamp'] + time_str = 'pending' + label = line.get('label') + if not label: label = line['tx_hash'] + else: label = label + ' '*(64 - len(label) ) + + print time_str , " " + label + " " + format_satoshis(v)+ " "+ format_satoshis(b) + print "# balance: ", format_satoshis(b) + + elif cmd == 'label': + try: + tx = args[1] + label = ' '.join(args[2:]) + except: + print "syntax: label " + sys.exit(1) + wallet.labels[tx] = label + wallet.save() + + elif cmd in ['payto', 'mktx']: + if from_addr and is_temporary: + if from_addr.find(":") == -1: + keypair = from_addr + ":" + getpass.getpass('Private key:') + else: + keypair = from_addr + from_addr = keypair.split(':')[0] + if not wallet.import_key(keypair,password): + print "invalid key pair" + exit(1) + wallet.history[from_addr] = interface.retrieve_history(from_addr) + wallet.update_tx_history() + change_addr = from_addr + + if options.change_addr: + change_addr = options.change_addr + + for k, v in wallet.labels.items(): + if v == to_address: + to_address = k + print "alias", to_address + break + if change_addr and v == change_addr: + change_addr = k + try: + tx = wallet.mktx( to_address, amount, label, password, + fee = options.tx_fee, change_addr = change_addr, from_addr = from_addr ) + except: + import traceback + traceback.print_exc(file=sys.stdout) + tx = None + + if tx and cmd=='payto': + r, h = wallet.sendtx( tx ) + print h + else: + print tx + + if is_temporary: + wallet.imported_keys.pop(from_addr) + del(wallet.history[from_addr]) + wallet.save() + + elif cmd == 'sendtx': + tx = args[1] + r, h = wallet.sendtx( tx ) + print h + + elif cmd == 'password': + try: + seed = wallet.pw_decode( wallet.seed, password) + except: + print "sorry" + sys.exit(1) + new_password = getpass.getpass('New password:') + if new_password == getpass.getpass('Confirm new password:'): + wallet.use_encryption = (new_password != '') + wallet.seed = wallet.pw_encode( seed, new_password) + for k in wallet.imported_keys.keys(): + a = wallet.imported_keys[k] + b = wallet.pw_decode(a, password) + c = wallet.pw_encode(b, new_password) + wallet.imported_keys[k] = c + wallet.save() + else: + print "error: mismatch" + + elif cmd == 'signmessage': + address, message = args[1:3] + print wallet.sign_message(address, message, password) + + elif cmd == 'verifymessage': + address, signature, message = args[1:4] + try: + wallet.verify_message(address, signature, message) + print True + except: + print False + + diff --git a/electrum4a.py b/electrum4a.py new file mode 100755 index 0000000..f247764 --- /dev/null +++ b/electrum4a.py @@ -0,0 +1,981 @@ +#!/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 . + + + + +import android +from interface import WalletSynchronizer +from wallet import Wallet +from wallet import format_satoshis +from decimal import Decimal +import mnemonic + +import datetime + + + +def modal_dialog(title, msg = None): + droid.dialogCreateAlert(title,msg) + droid.dialogSetPositiveButtonText('OK') + droid.dialogShow() + droid.dialogGetResponse() + droid.dialogDismiss() + +def modal_input(title, msg, value = None, etype=None): + droid.dialogCreateInput(title, msg, value, etype) + droid.dialogSetPositiveButtonText('OK') + droid.dialogSetNegativeButtonText('Cancel') + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + if response.get('which') == 'positive': + return response.get('value') + +def modal_question(q, msg, pos_text = 'OK', neg_text = 'Cancel'): + droid.dialogCreateAlert(q, msg) + droid.dialogSetPositiveButtonText(pos_text) + droid.dialogSetNegativeButtonText(neg_text) + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + return response.get('which') == 'positive' + +def edit_label(addr): + v = modal_input('Edit label',None,wallet.labels.get(addr)) + if v is not None: + if v: + wallet.labels[addr] = v + else: + if addr in wallet.labels.keys(): + wallet.labels.pop(addr) + wallet.update_tx_history() + wallet.save() + droid.fullSetProperty("labelTextView", "text", v) + +def select_from_contacts(): + title = 'Contacts:' + droid.dialogCreateAlert(title) + l = [] + for i in range(len(wallet.addressbook)): + addr = wallet.addressbook[i] + label = wallet.labels.get(addr,addr) + l.append( label ) + droid.dialogSetItems(l) + droid.dialogSetPositiveButtonText('New contact') + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + + if response.get('which') == 'positive': + return 'newcontact' + + result = response.get('item') + print result + if result is not None: + addr = wallet.addressbook[result] + return addr + + +def select_from_addresses(): + droid.dialogCreateAlert("Addresses:") + l = [] + for i in range(len(wallet.addresses)): + addr = wallet.addresses[i] + label = wallet.labels.get(addr,addr) + l.append( label ) + droid.dialogSetItems(l) + droid.dialogShow() + response = droid.dialogGetResponse() + result = response.result.get('item') + droid.dialogDismiss() + if result is not None: + addr = wallet.addresses[result] + return addr + + +def protocol_name(p): + if p == 't': return 'TCP/stratum' + if p == 'h': return 'HTTP/Stratum' + if p == 'n': return 'TCP/native' + +def protocol_dialog(host, protocol, z): + droid.dialogCreateAlert('Protocol',host) + if z: + protocols = z.keys() + else: + protocols = ['t','h','n'] + l = [] + current = protocols.index(protocol) + for p in protocols: + l.append(protocol_name(p)) + droid.dialogSetSingleChoiceItems(l, current) + droid.dialogSetPositiveButtonText('OK') + droid.dialogSetNegativeButtonText('Cancel') + droid.dialogShow() + response = droid.dialogGetResponse().result + if not response: return + if response.get('which') == 'positive': + response = droid.dialogGetSelectedItems().result[0] + droid.dialogDismiss() + p = protocols[response] + port = z[p] + return host + ':' + port + ':' + p + + + + +def make_layout(s, scrollable = False): + content = """ + + + + + + + %s """%s + + if scrollable: + content = """ + + + + + %s + + + + """%content + + + return """ + + + %s + """%content + + + + +def main_layout(): + return make_layout(""" + + + + + + + %s """%get_history_layout(15),True) + + + +def qr_layout(addr): + return make_layout(""" + + + + + + + + + + """%(addr,wallet.labels.get(addr,'')), True) + +payto_layout = make_layout(""" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + """,False) + + + +settings_layout = make_layout(""" """) + + + +def get_history_values(n): + values = [] + h = wallet.get_tx_history() + + length = min(n, len(h)) + for i in range(length): + line = h[-i-1] + v = line['value'] + try: + dt = datetime.datetime.fromtimestamp( line['timestamp'] ) + if dt.date() == dt.today().date(): + time_str = str( dt.time() ) + else: + time_str = str( dt.date() ) + conf = 'v' + + except: + print line['timestamp'] + time_str = 'pending' + conf = 'o' + + tx_hash = line['tx_hash'] + label = wallet.labels.get(tx_hash) + is_default_label = (label == '') or (label is None) + if is_default_label: label = line['default_label'] + values.append((conf, ' ' + time_str, ' ' + format_satoshis(v,True), ' ' + label )) + + return values + + +def get_history_layout(n): + rows = "" + i = 0 + values = get_history_values(n) + for v in values: + a,b,c,d = v + color = "#ff00ff00" if a == 'v' else "#ffff0000" + rows += """ + + + + + + """%(i,a,color,i,b,i,c,i,d) + i += 1 + + output = """ + + %s +"""% rows + return output + + +def set_history_layout(n): + values = get_history_values(n) + i = 0 + for v in values: + a,b,c,d = v + droid.fullSetProperty("hl_%d_col1"%i,"text", a) + + if a == 'v': + droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ff00ff00") + else: + droid.fullSetProperty("hl_%d_col1"%i, "textColor","#ffff0000") + + droid.fullSetProperty("hl_%d_col2"%i,"text", b) + droid.fullSetProperty("hl_%d_col3"%i,"text", c) + droid.fullSetProperty("hl_%d_col4"%i,"text", d) + i += 1 + + + + +status_text = '' +def update_layout(): + global status_text + if not wallet.interface.is_connected: + text = "Not connected..." + elif wallet.blocks == 0: + text = "Server not ready" + elif not wallet.up_to_date: + text = "Synchronizing..." + else: + c, u = wallet.get_balance() + text = "Balance:"+format_satoshis(c) + if u : text += ' [' + format_satoshis(u,True).strip() + ']' + + + # vibrate if status changed + if text != status_text: + if status_text and wallet.interface.is_connected and wallet.up_to_date: + droid.vibrate() + status_text = text + + droid.fullSetProperty("balanceTextView", "text", status_text) + + if wallet.up_to_date: + set_history_layout(15) + + + + +def pay_to(recipient, amount, fee, label): + + if wallet.use_encryption: + password = droid.dialogGetPassword('Password').result + if not password: return + else: + password = None + + droid.dialogCreateSpinnerProgress("Electrum", "signing transaction...") + droid.dialogShow() + + try: + tx = wallet.mktx( recipient, amount, label, password, fee) + except BaseException, e: + modal_dialog('error', e.message) + droid.dialogDismiss() + return + + droid.dialogDismiss() + + r, h = wallet.sendtx( tx ) + if r: + modal_dialog('Payment sent', h) + return True + else: + modal_dialog('Error', h) + + + + + +def recover(): + + droid.dialogCreateAlert("Wallet not found","Do you want to create a new wallet, or restore an existing one?") + droid.dialogSetPositiveButtonText('Create') + droid.dialogSetNeutralButtonText('Restore') + droid.dialogSetNegativeButtonText('Cancel') + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + if response.get('which') == 'negative': + exit(1) + + is_recovery = response.get('which') == 'neutral' + + if not is_recovery: + wallet.new_seed(None) + else: + if modal_question("Input method",None,'QR Code', 'mnemonic'): + code = droid.scanBarcode() + r = code.result + if r: + seed = r['extras']['SCAN_RESULT'] + else: + exit(1) + else: + m = modal_input('Mnemonic','please enter your code') + try: + seed = mnemonic.mn_decode(m.split(' ')) + except: + modal_dialog('error: could not decode this seed') + exit(1) + + wallet.seed = str(seed) + + modal_dialog('Your seed is:', wallet.seed) + modal_dialog('Mnemonic code:', ' '.join(mnemonic.mn_encode(wallet.seed)) ) + + msg = "recovering wallet..." if is_recovery else "creating wallet..." + droid.dialogCreateSpinnerProgress("Electrum", msg) + droid.dialogShow() + + wallet.init_mpk( wallet.seed ) + WalletSynchronizer(wallet,True).start() + wallet.update() + + droid.dialogDismiss() + droid.vibrate() + + if is_recovery: + if wallet.is_found(): + wallet.update_tx_history() + wallet.fill_addressbook() + modal_dialog("recovery successful") + else: + if not modal_question("no transactions found for this seed","do you want to keep this wallet?"): + exit(1) + + change_password_dialog() + wallet.save() + + + +def make_new_contact(): + code = droid.scanBarcode() + r = code.result + if r: + address = r['extras']['SCAN_RESULT'] + if address: + if wallet.is_valid(address): + if modal_question('Add to contacts?', address): + wallet.addressbook.append(address) + wallet.save() + else: + modal_dialog('Invalid address', address) + + +do_refresh = False + +def update_callback(): + global do_refresh + print "gui callback", wallet.interface.is_connected, wallet.up_to_date + do_refresh = True + droid.eventPost("refresh",'z') + +def main_loop(): + global do_refresh + + update_layout() + out = None + quitting = False + while out is None: + + event = droid.eventWait(1000).result + if event is None: + if do_refresh: + update_layout() + do_refresh = False + continue + + print "got event in main loop", repr(event) + if event == 'OK': continue + if event is None: continue + #if event["name"]=="refresh": + + + # request 2 taps before we exit + if event["name"]=="key": + if event["data"]["key"] == '4': + if quitting: + out = 'quit' + else: + quitting = True + else: quitting = False + + if event["name"]=="click": + id=event["data"]["id"] + + elif event["name"]=="settings": + out = 'settings' + + elif event["name"] in menu_commands: + out = event["name"] + + if out == 'contacts': + global contact_addr + contact_addr = select_from_contacts() + if contact_addr == 'newcontact': + make_new_contact() + contact_addr = None + if not contact_addr: + out = None + + elif out == "receive": + global receive_addr + receive_addr = select_from_addresses() + if not receive_addr: + out = None + + + return out + + +def payto_loop(): + global recipient + if recipient: + droid.fullSetProperty("recipient","text",recipient) + recipient = None + + out = None + while out is None: + event = droid.eventWait().result + print "got event in payto loop", event + + if event["name"] == "click": + id = event["data"]["id"] + + if id=="buttonPay": + + droid.fullQuery() + recipient = droid.fullQueryDetail("recipient").result.get('text') + label = droid.fullQueryDetail("label").result.get('text') + amount = droid.fullQueryDetail('amount').result.get('text') + + if not wallet.is_valid(recipient): + modal_dialog('Error','Invalid Bitcoin address') + continue + + try: + amount = int( 100000000 * Decimal(amount) ) + except: + modal_dialog('Error','Invalid amount') + continue + + result = pay_to(recipient, amount, wallet.fee, label) + if result: + out = 'main' + + elif id=="buttonContacts": + addr = select_from_contacts() + droid.fullSetProperty("recipient","text",addr) + + elif id=="buttonQR": + code = droid.scanBarcode() + r = code.result + if r: + addr = r['extras']['SCAN_RESULT'] + if addr: + droid.fullSetProperty("recipient","text",addr) + + elif event["name"] in menu_commands: + out = event["name"] + + elif event["name"]=="key": + if event["data"]["key"] == '4': + out = 'main' + + #elif event["name"]=="screen": + # if event["data"]=="destroy": + # out = 'main' + + return out + + +receive_addr = '' +contact_addr = '' +recipient = '' + +def receive_loop(): + out = None + while out is None: + event = droid.eventWait().result + print "got event", event + if event["name"]=="key": + if event["data"]["key"] == '4': + out = 'main' + + elif event["name"]=="clipboard": + droid.setClipboard(receive_addr) + modal_dialog('Address copied to clipboard',receive_addr) + + elif event["name"]=="edit": + edit_label(receive_addr) + + return out + +def contacts_loop(): + global recipient + out = None + while out is None: + event = droid.eventWait().result + print "got event", event + if event["name"]=="key": + if event["data"]["key"] == '4': + out = 'main' + + elif event["name"]=="clipboard": + droid.setClipboard(contact_addr) + modal_dialog('Address copied to clipboard',contact_addr) + + elif event["name"]=="edit": + edit_label(contact_addr) + + elif event["name"]=="paytocontact": + recipient = contact_addr + out = 'send' + + elif event["name"]=="deletecontact": + if modal_question('delete contact', contact_addr): + out = 'main' + + return out + + +def server_dialog(plist): + droid.dialogCreateAlert("Public servers") + droid.dialogSetItems( plist.keys() ) + droid.dialogSetPositiveButtonText('Private server') + droid.dialogShow() + response = droid.dialogGetResponse().result + droid.dialogDismiss() + + if response.get('which') == 'positive': + return modal_input('Private server', None) + + i = response.get('item') + if i is not None: + response = plist.keys()[i] + return response + + +def seed_dialog(): + if wallet.use_encryption: + password = droid.dialogGetPassword('Seed').result + if not password: return + else: + password = None + + try: + seed = wallet.pw_decode( wallet.seed, password) + except: + modal_dialog('error','incorrect password') + return + + modal_dialog('Your seed is',seed) + modal_dialog('Mnemonic code:', ' '.join(mnemonic.mn_encode(seed)) ) + +def change_password_dialog(): + if wallet.use_encryption: + password = droid.dialogGetPassword('Your wallet is encrypted').result + if password is None: return + else: + password = None + + try: + seed = wallet.pw_decode( wallet.seed, password) + except: + modal_dialog('error','incorrect password') + return + + new_password = droid.dialogGetPassword('Choose a password').result + if new_password == None: + return + + if new_password != '': + password2 = droid.dialogGetPassword('Confirm new password').result + if new_password != password2: + modal_dialog('error','passwords do not match') + return + + wallet.update_password(seed, new_password) + if new_password: + modal_dialog('Password updated','your wallet is encrypted') + else: + modal_dialog('No password','your wallet is not encrypted') + return True + + +def settings_loop(): + + + def set_listview(): + server, port, p = wallet.server.split(':') + fee = str( Decimal( wallet.fee)/100000000 ) + is_encrypted = 'yes' if wallet.use_encryption else 'no' + protocol = protocol_name(p) + droid.fullShow(settings_layout) + droid.fullSetList("myListView",['Server: ' + server, 'Protocol: '+ protocol, 'Port: '+port, 'Transaction fee: '+fee, 'Password: '+is_encrypted, 'Seed']) + + set_listview() + + out = None + while out is None: + event = droid.eventWait().result + print "got event", event + if event == 'OK': continue + if not event: continue + + plist = {} + for item in wallet.interface.servers: + host, pp = item + z = {} + for item2 in pp: + protocol, port = item2 + z[protocol] = port + plist[host] = z + + if event["name"] == "itemclick": + pos = event["data"]["position"] + host, port, protocol = wallet.server.split(':') + + if pos == "0": #server + host = server_dialog(plist) + if host: + p = plist[host] + port = p['t'] + srv = host + ':' + port + ':t' + try: + wallet.set_server(srv) + except: + modal_dialog('error','invalid server') + set_listview() + + elif pos == "1": #protocol + if host in plist: + srv = protocol_dialog(host, protocol, plist[host]) + if srv: + try: + wallet.set_server(srv) + except: + modal_dialog('error','invalid server') + set_listview() + + elif pos == "2": #port + a_port = modal_input('Port number', 'If you use a public server, this field is set automatically when you set the protocol', port, "number") + if a_port: + if a_port != port: + srv = host + ':' + a_port + ':'+ protocol + try: + wallet.set_server(srv) + except: + modal_dialog('error','invalid port number') + set_listview() + + elif pos == "3": #fee + fee = modal_input('Transaction fee', 'The fee will be this amount multiplied by the number of inputs in your transaction. ', str( Decimal( wallet.fee)/100000000 ), "numberDecimal") + if fee: + try: + fee = int( 100000000 * Decimal(fee) ) + except: + modal_dialog('error','invalid fee value') + if wallet.fee != fee: + wallet.fee = fee + wallet.save() + set_listview() + + elif pos == "4": + if change_password_dialog(): + set_listview() + + elif pos == "5": + seed_dialog() + + + elif event["name"] in menu_commands: + out = event["name"] + + elif event["name"] == 'cancel': + out = 'main' + + elif event["name"] == "key": + if event["data"]["key"] == '4': + out = 'main' + + return out + + + + +menu_commands = ["send", "receive", "settings", "contacts", "main"] +droid = android.Android() +wallet = Wallet(update_callback) + +wallet.set_path("/sdcard/electrum.dat") +wallet.read() +if not wallet.file_exists: + recover() +else: + WalletSynchronizer(wallet,True).start() + + +s = 'main' + +def add_menu(s): + droid.clearOptionsMenu() + if s == 'main': + droid.addOptionsMenuItem("Send","send",None,"") + droid.addOptionsMenuItem("Receive","receive",None,"") + droid.addOptionsMenuItem("Contacts","contacts",None,"") + droid.addOptionsMenuItem("Settings","settings",None,"") + elif s == 'receive': + droid.addOptionsMenuItem("Copy","clipboard",None,"") + droid.addOptionsMenuItem("Label","edit",None,"") + elif s == 'contacts': + droid.addOptionsMenuItem("Copy","clipboard",None,"") + droid.addOptionsMenuItem("Label","edit",None,"") + droid.addOptionsMenuItem("Pay to","paytocontact",None,"") + #droid.addOptionsMenuItem("Delete","deletecontact",None,"") + +def make_bitmap(addr): + # fixme: this is highly inefficient + droid.dialogCreateSpinnerProgress("please wait") + droid.dialogShow() + import pyqrnative, bmp + qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) + qr.addData(addr) + qr.make() + k = qr.getModuleCount() + bitmap = bmp.BitMap( 35*8, 35*8 ) + print len(bitmap.bitarray) + bitmap.bitarray = [] + assert k == 33 + + for r in range(35): + tmparray = [ 0 ] * 35*8 + + if 0 < r < 34: + for c in range(k): + if qr.isDark(r-1, c): + tmparray[ (1+c)*8:(2+c)*8] = [1]*8 + + for i in range(8): + bitmap.bitarray.append( tmparray[:] ) + + bitmap.saveFile( "/sdcard/sl4a/qrcode.bmp" ) + droid.dialogDismiss() + + + +while True: + add_menu(s) + if s == 'main': + droid.fullShow(main_layout()) + s = main_loop() + #droid.fullDismiss() + + elif s == 'send': + droid.fullShow(payto_layout) + s = payto_loop() + #droid.fullDismiss() + + elif s == 'receive': + make_bitmap(receive_addr) + droid.fullShow(qr_layout(receive_addr)) + s = receive_loop() + + elif s == 'contacts': + make_bitmap(contact_addr) + droid.fullShow(qr_layout(contact_addr)) + s = contacts_loop() + + elif s == 'settings': + #droid.fullShow(settings_layout) + s = settings_loop() + #droid.fullDismiss() + else: + break + +droid.makeToast("Bye!") diff --git a/electrum_text_320.png b/electrum_text_320.png new file mode 100644 index 0000000000000000000000000000000000000000..4a8f8375d22649ba464aec1f98fd196d7d415f42 GIT binary patch literal 4634 zcmZu#c{mhM*PjhzvM;ZF4-t`NG>FKWHOny8QFf-0$UfH6Vkt{f#zdByAyY#t+fZ2| z`xeCri7=zW#NeCvpYN~txzF9s^W1ZvbI$Lad+xdI>}bsklY{{P0A5=g3l{(Yc#gf+ zfpW4(O({@b3k)fTcT+)*~DYXHD8;s16Z;8B@4 zo5&So>tM51-?;h?wIMQ_ehxtE;tT?)+hk&5#G+$HlCpGD>)0Q(_Pem(I1k`-NH)^g@Eo$|-&V#%Sr_VJZaeTh$Ldv+(ZUMGO+{ zqS2>{UPtCrE-3q$iatbz^i(~FYa;Vj8uB`D`67=4J~t>i+KbPUn~-{P-iI2%(tR8l)h4=?S@bzK)91>XYuYSRDL4~R+Wc|u9<<|Dwq$)3t_vFIF6{;aE5W_+_NS_%5Ip(3Vu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?2z`zegM{ED(hd{}d~{GKhWPVtuPb{k4hE-I1&n<709GtY z;fa(LnYi{AerS(=06(0o;vKOwTvjC3j$Kf9ngmQ=wOgnOIE*$A4h0YS_A&-ISA2KOduyrcP< zKOADKeJonu$l)<$b#-ZwZ{4w1meK(~?BHI_f(h^}XnWidXc+DuQVjflV&MBEW5LXv zrkh0;c}(_I8zj1>(}8k|Oh~iVa-lTc?3S5yZEkAL`emPN+ocZyS*0t2h%Z(Z!+?Hn zeg>bye>isK-mu!l~g5~2|;D>h9 z4qyoT!}`>m_VVvbk0r`k#_VXMx+47~H!5gT;kefuAE{IXL!4npYmz({<=r)yvH#KW z2*eao@F5C`Z&%xl&+=GmuC}FY1A<0hc(y>(A`3I~1UbHyJD+lm8Hl?IWq{4!)iYDJ zhi5^uy3o=qk_pHMjXdHTb&0ike5r~G)TDWhe+3hH2{TM5z^NebqYtRqNIX5Ev1-hN z_?YW;EV4e5?58TsO4jdluD+hzw=YPIG`EjD`&+i-&>hY8=34HT>5J)v>g1t(yt}Y& z!Ce`P`?iVLzw?lgiEk(Xdc1dKnd*k5wha=kiO;uPe%$}wGyM+unF&Kz8`IGeqOJZQOL8UuVjVAr)QfL$-zZ>uigCepN(=6 ot|AYN{%1ww|EnCC_(Oh&uwO~#S67$VRT_Y;rK80Qb9Bc40gA1&6aWAK literal 0 HcmV?d00001 diff --git a/gui.py b/gui.py new file mode 100644 index 0000000..77acdd1 --- /dev/null +++ b/gui.py @@ -0,0 +1,1265 @@ +#!/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 . + +import datetime +import thread, time, ast, sys, re +import socket, traceback +import pygtk +pygtk.require('2.0') +import gtk, gobject +import pyqrnative +from decimal import Decimal + +gtk.gdk.threads_init() +APP_NAME = "Electrum" +import platform +MONOSPACE_FONT = 'Lucida Console' if platform.system() == 'Windows' else 'monospace' + +from wallet import format_satoshis +from interface import DEFAULT_SERVERS + +def numbify(entry, is_int = False): + text = entry.get_text().strip() + chars = '0123456789' + if not is_int: chars +='.' + s = ''.join([i for i in text if i in chars]) + if not is_int: + if '.' in s: + p = s.find('.') + s = s.replace('.','') + s = s[:p] + '.' + s[p:p+8] + try: + amount = int( Decimal(s) * 100000000 ) + except: + amount = None + else: + try: + amount = int( s ) + except: + amount = None + entry.set_text(s) + return amount + + + + +def show_seed_dialog(wallet, password, parent): + import mnemonic + try: + seed = wallet.pw_decode( wallet.seed, password) + except: + show_message("Incorrect password") + return + dialog = gtk.MessageDialog( + parent = parent, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_OK, + message_format = "Your wallet generation seed is:\n\n" + seed \ + + "\n\nPlease keep it in a safe place; if you lose it, you will not be able to restore your wallet.\n\n" \ + + "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:\n\n\"" + ' '.join(mnemonic.mn_encode(seed)) + "\"" ) + dialog.set_title("Seed") + dialog.show() + dialog.run() + dialog.destroy() + +def restore_create_dialog(wallet): + + # ask if the user wants to create a new wallet, or recover from a seed. + # if he wants to recover, and nothing is found, do not create wallet + dialog = gtk.Dialog("electrum", parent=None, + flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, + buttons= ("create", 0, "restore",1, "cancel",2) ) + + label = gtk.Label("Wallet file not found.\nDo you want to create a new wallet,\n or to restore an existing one?" ) + label.show() + dialog.vbox.pack_start(label) + dialog.show() + r = dialog.run() + dialog.destroy() + + if r==2: return False + + is_recovery = (r==1) + + # ask for the server. + if not run_network_dialog( wallet, parent=None ): return False + + if not is_recovery: + + wallet.new_seed(None) + # generate first key + wallet.init_mpk( wallet.seed ) + wallet.up_to_date_event.clear() + wallet.update() + + # run a dialog indicating the seed, ask the user to remember it + show_seed_dialog(wallet, None, None) + + #ask for password + change_password_dialog(wallet, None, None) + else: + # ask for seed and gap. + run_recovery_dialog( wallet ) + + dialog = gtk.MessageDialog( + parent = None, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_CANCEL, + message_format = "Please wait..." ) + dialog.show() + + def recover_thread( wallet, dialog ): + wallet.init_mpk( wallet.seed ) # not encrypted at this point + wallet.up_to_date_event.clear() + wallet.update() + + if wallet.is_found(): + # history and addressbook + wallet.update_tx_history() + wallet.fill_addressbook() + print "recovery successful" + + gobject.idle_add( dialog.destroy ) + + thread.start_new_thread( recover_thread, ( wallet, dialog ) ) + r = dialog.run() + dialog.destroy() + if r==gtk.RESPONSE_CANCEL: return False + if not wallet.is_found: + show_message("No transactions found for this seed") + + wallet.save() + return True + + +def run_recovery_dialog(wallet): + message = "Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet." + dialog = gtk.MessageDialog( + parent = None, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_OK_CANCEL, + message_format = message) + + vbox = dialog.vbox + dialog.set_default_response(gtk.RESPONSE_OK) + + # ask seed, server and gap in the same dialog + seed_box = gtk.HBox() + seed_label = gtk.Label('Seed or mnemonic:') + seed_label.set_size_request(150,-1) + seed_box.pack_start(seed_label, False, False, 10) + seed_label.show() + seed_entry = gtk.Entry() + seed_entry.show() + seed_entry.set_size_request(450,-1) + seed_box.pack_start(seed_entry, False, False, 10) + add_help_button(seed_box, '.') + seed_box.show() + vbox.pack_start(seed_box, False, False, 5) + + gap = gtk.HBox() + gap_label = gtk.Label('Gap limit:') + gap_label.set_size_request(150,10) + gap_label.show() + gap.pack_start(gap_label,False, False, 10) + gap_entry = gtk.Entry() + gap_entry.set_text("%d"%wallet.gap_limit) + gap_entry.connect('changed', numbify, True) + gap_entry.show() + gap.pack_start(gap_entry,False,False, 10) + add_help_button(gap, 'The maximum gap that is allowed between unused addresses in your wallet. During wallet recovery, this parameter is used to decide when to stop the recovery process. If you increase this value, you will need to remember it in order to be able to recover your wallet from seed.') + gap.show() + vbox.pack_start(gap, False,False, 5) + + dialog.show() + r = dialog.run() + gap = gap_entry.get_text() + seed = seed_entry.get_text() + dialog.destroy() + + if r==gtk.RESPONSE_CANCEL: + sys.exit(1) + try: + gap = int(gap) + except: + show_message("error") + sys.exit(1) + + try: + seed.decode('hex') + except: + import mnemonic + print "not hex, trying decode" + seed = mnemonic.mn_decode( seed.split(' ') ) + if not seed: + show_message("no seed") + sys.exit(1) + + wallet.seed = seed + wallet.gap_limit = gap + wallet.save() + + + +def run_settings_dialog(wallet, parent): + + message = "Here are the settings of your wallet. For more explanations, click on the question mark buttons next to each input field." + + dialog = gtk.MessageDialog( + parent = parent, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_OK_CANCEL, + message_format = message) + + image = gtk.Image() + image.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_DIALOG) + image.show() + dialog.set_image(image) + dialog.set_title("Settings") + + vbox = dialog.vbox + dialog.set_default_response(gtk.RESPONSE_OK) + + fee = gtk.HBox() + fee_entry = gtk.Entry() + fee_label = gtk.Label('Transaction fee:') + fee_label.set_size_request(150,10) + fee_label.show() + fee.pack_start(fee_label,False, False, 10) + fee_entry.set_text( str( Decimal(wallet.fee) /100000000 ) ) + fee_entry.connect('changed', numbify, False) + fee_entry.show() + fee.pack_start(fee_entry,False,False, 10) + add_help_button(fee, 'Fee per transaction input. Transactions involving multiple inputs tend to have a higher fee. Recommended value:0.0005') + fee.show() + vbox.pack_start(fee, False,False, 5) + + dialog.show() + r = dialog.run() + fee = fee_entry.get_text() + + dialog.destroy() + if r==gtk.RESPONSE_CANCEL: + return + + try: + fee = int( 100000000 * Decimal(fee) ) + except: + show_message("error") + return + + wallet.fee = fee + wallet.save() + + + + +def run_network_dialog( wallet, parent ): + image = gtk.Image() + image.set_from_stock(gtk.STOCK_NETWORK, gtk.ICON_SIZE_DIALOG) + interface = wallet.interface + if parent: + if interface.is_connected: + status = "Connected to %s:%d\n%d blocks\nresponse time: %f"%(interface.host, interface.port, wallet.blocks, interface.rtime) + else: + status = "Not connected" + server = wallet.server + else: + import random + status = "Please choose a server." + server = random.choice( DEFAULT_SERVERS ) + + plist = {} + for item in wallet.interface.servers: + host, pp = item + z = {} + for item2 in pp: + protocol, port = item2 + z[protocol] = port + plist[host] = z + + dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, + gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, status) + dialog.set_title("Server") + dialog.set_image(image) + image.show() + + vbox = dialog.vbox + host_box = gtk.HBox() + host_label = gtk.Label('Connect to:') + host_label.set_size_request(100,-1) + host_label.show() + host_box.pack_start(host_label, False, False, 10) + host_entry = gtk.Entry() + host_entry.set_size_request(200,-1) + host_entry.set_text(server) + host_entry.show() + host_box.pack_start(host_entry, False, False, 10) + add_help_button(host_box, 'The name and port number of your Electrum server, separated by a colon. Example: "ecdsa.org:50000". If no port number is provided, port 50000 will be tried. Some servers allow you to connect through http (port 80) or https (port 443)') + host_box.show() + + + p_box = gtk.HBox(False, 10) + p_box.show() + + p_label = gtk.Label('Protocol:') + p_label.set_size_request(100,-1) + p_label.show() + p_box.pack_start(p_label, False, False, 10) + + radio1 = gtk.RadioButton(None, "tcp") + p_box.pack_start(radio1, True, True, 0) + radio1.show() + radio2 = gtk.RadioButton(radio1, "http") + p_box.pack_start(radio2, True, True, 0) + radio2.show() + radio3 = gtk.RadioButton(radio1, "native") + p_box.pack_start(radio3, True, True, 0) + radio3.show() + + def current_line(): + return unicode(host_entry.get_text()).split(':') + + def set_button(protocol): + if protocol == 't': + radio1.set_active(1) + elif protocol == 'h': + radio2.set_active(1) + elif protocol == 'n': + radio3.set_active(1) + + def set_protocol(protocol): + host = current_line()[0] + pp = plist[host] + if protocol not in pp.keys(): + protocol = pp.keys()[0] + set_button(protocol) + port = pp[protocol] + host_entry.set_text( host + ':' + port + ':' + protocol) + + radio1.connect("toggled", lambda x,y:set_protocol('t'), "radio button 1") + radio2.connect("toggled", lambda x,y:set_protocol('h'), "radio button 1") + radio3.connect("toggled", lambda x,y:set_protocol('n'), "radio button 1") + + server_list = gtk.ListStore(str) + for host in plist.keys(): + server_list.append([host]) + + treeview = gtk.TreeView(model=server_list) + treeview.show() + + tvcolumn = gtk.TreeViewColumn('Active servers') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 0) + + scroll = gtk.ScrolledWindow() + scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) + scroll.add(treeview) + scroll.show() + + vbox.pack_start(host_box, False,False, 5) + vbox.pack_start(p_box, True, True, 0) + vbox.pack_start(scroll) + + def my_treeview_cb(treeview): + path, view_column = treeview.get_cursor() + host = server_list.get_value( server_list.get_iter(path), 0) + + pp = plist[host] + if 't' in pp.keys(): + protocol = 't' + else: + protocol = pp.keys()[0] + port = pp[protocol] + host_entry.set_text( host + ':' + port + ':' + protocol) + set_button(protocol) + + treeview.connect('cursor-changed', my_treeview_cb) + + dialog.show() + r = dialog.run() + server = host_entry.get_text() + dialog.destroy() + + if r==gtk.RESPONSE_CANCEL: + return False + + try: + wallet.set_server(server) + except: + show_message("error:" + server) + return False + + if parent: + wallet.save() + return True + + + +def show_message(message, parent=None): + dialog = gtk.MessageDialog( + parent = parent, + flags = gtk.DIALOG_MODAL, + buttons = gtk.BUTTONS_CLOSE, + message_format = message ) + dialog.show() + dialog.run() + dialog.destroy() + +def password_line(label): + password = gtk.HBox() + password_label = gtk.Label(label) + password_label.set_size_request(120,10) + password_label.show() + password.pack_start(password_label,False, False, 10) + password_entry = gtk.Entry() + password_entry.set_size_request(300,-1) + password_entry.set_visibility(False) + password_entry.show() + password.pack_start(password_entry,False,False, 10) + password.show() + return password, password_entry + +def password_dialog(parent): + dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, + gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, "Please enter your password.") + dialog.get_image().set_visible(False) + current_pw, current_pw_entry = password_line('Password:') + current_pw_entry.connect("activate", lambda entry, dialog, response: dialog.response(response), dialog, gtk.RESPONSE_OK) + dialog.vbox.pack_start(current_pw, False, True, 0) + dialog.show() + result = dialog.run() + pw = current_pw_entry.get_text() + dialog.destroy() + if result != gtk.RESPONSE_CANCEL: return pw + +def change_password_dialog(wallet, parent, icon): + if parent: + msg = 'Your wallet is encrypted. Use this dialog to change the password. To disable wallet encryption, enter an empty new password.' if wallet.use_encryption else 'Your wallet keys are not encrypted' + else: + msg = "Please choose a password to encrypt your wallet keys" + + dialog = gtk.MessageDialog( parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) + dialog.set_title("Change password") + image = gtk.Image() + image.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_DIALOG) + image.show() + dialog.set_image(image) + + if wallet.use_encryption: + current_pw, current_pw_entry = password_line('Current password:') + dialog.vbox.pack_start(current_pw, False, True, 0) + + password, password_entry = password_line('New password:') + dialog.vbox.pack_start(password, False, True, 5) + password2, password2_entry = password_line('Confirm password:') + dialog.vbox.pack_start(password2, False, True, 5) + + dialog.show() + result = dialog.run() + password = current_pw_entry.get_text() if wallet.use_encryption else None + new_password = password_entry.get_text() + new_password2 = password2_entry.get_text() + dialog.destroy() + if result == gtk.RESPONSE_CANCEL: + return + + try: + seed = wallet.pw_decode( wallet.seed, password) + except: + show_message("Incorrect password") + return + + if new_password != new_password2: + show_message("passwords do not match") + return + + wallet.update_password(seed, new_password) + + if icon: + if wallet.use_encryption: + icon.set_tooltip_text('wallet is encrypted') + else: + icon.set_tooltip_text('wallet is unencrypted') + + +def add_help_button(hbox, message): + button = gtk.Button('?') + button.connect("clicked", lambda x: show_message(message)) + button.show() + hbox.pack_start(button,False, False) + + +class MyWindow(gtk.Window): __gsignals__ = dict( mykeypress = (gobject.SIGNAL_RUN_LAST | gobject.SIGNAL_ACTION, None, (str,)) ) + +gobject.type_register(MyWindow) +gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.W, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+W') +gtk.binding_entry_add_signal(MyWindow, gtk.keysyms.Q, gtk.gdk.CONTROL_MASK, 'mykeypress', str, 'ctrl+Q') + + +class ElectrumWindow: + + def show_message(self, msg): + show_message(msg, self.window) + + def __init__(self, wallet): + self.wallet = wallet + self.funds_error = False # True if not enough funds + + self.window = MyWindow(gtk.WINDOW_TOPLEVEL) + self.window.set_title(APP_NAME + " " + self.wallet.electrum_version) + self.window.connect("destroy", gtk.main_quit) + self.window.set_border_width(0) + self.window.connect('mykeypress', gtk.main_quit) + self.window.set_default_size(720, 350) + + vbox = gtk.VBox() + + self.notebook = gtk.Notebook() + self.create_history_tab() + self.create_send_tab() + self.create_recv_tab() + self.create_book_tab() + self.create_about_tab() + self.notebook.show() + vbox.pack_start(self.notebook, True, True, 2) + + self.status_bar = gtk.Statusbar() + vbox.pack_start(self.status_bar, False, False, 0) + + self.status_image = gtk.Image() + self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) + self.status_image.set_alignment(True, 0.5 ) + self.status_image.show() + + self.network_button = gtk.Button() + self.network_button.connect("clicked", lambda x: run_network_dialog(self.wallet, self.window) ) + self.network_button.add(self.status_image) + self.network_button.set_relief(gtk.RELIEF_NONE) + self.network_button.show() + self.status_bar.pack_end(self.network_button, False, False) + + def seedb(w, wallet): + if wallet.use_encryption: + password = password_dialog(self.window) + if not password: return + else: password = None + show_seed_dialog(wallet, password, self.window) + button = gtk.Button('S') + button.connect("clicked", seedb, wallet ) + button.set_relief(gtk.RELIEF_NONE) + button.show() + self.status_bar.pack_end(button,False, False) + + settings_icon = gtk.Image() + settings_icon.set_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_MENU) + settings_icon.set_alignment(0.5, 0.5) + settings_icon.set_size_request(16,16 ) + settings_icon.show() + + prefs_button = gtk.Button() + prefs_button.connect("clicked", lambda x: run_settings_dialog(self.wallet, self.window) ) + prefs_button.add(settings_icon) + prefs_button.set_tooltip_text("Settings") + prefs_button.set_relief(gtk.RELIEF_NONE) + prefs_button.show() + self.status_bar.pack_end(prefs_button,False,False) + + pw_icon = gtk.Image() + pw_icon.set_from_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_MENU) + pw_icon.set_alignment(0.5, 0.5) + pw_icon.set_size_request(16,16 ) + pw_icon.show() + + password_button = gtk.Button() + password_button.connect("clicked", lambda x: change_password_dialog(self.wallet, self.window, pw_icon)) + password_button.add(pw_icon) + password_button.set_relief(gtk.RELIEF_NONE) + password_button.show() + self.status_bar.pack_end(password_button,False,False) + + self.window.add(vbox) + self.window.show_all() + #self.fee_box.hide() + + self.context_id = self.status_bar.get_context_id("statusbar") + self.update_status_bar() + + def update_status_bar_thread(): + while True: + gobject.idle_add( self.update_status_bar ) + time.sleep(0.5) + + + def check_recipient_thread(): + old_r = '' + while True: + time.sleep(0.5) + if self.payto_entry.is_focus(): + continue + r = self.payto_entry.get_text() + if r != old_r: + old_r = r + r = r.strip() + if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): + try: + to_address = self.wallet.get_alias(r, interactive=False) + except: + continue + if to_address: + s = r + ' <' + to_address + '>' + gobject.idle_add( lambda: self.payto_entry.set_text(s) ) + + + thread.start_new_thread(update_status_bar_thread, ()) + thread.start_new_thread(check_recipient_thread, ()) + self.notebook.set_current_page(0) + + + def add_tab(self, page, name): + tab_label = gtk.Label(name) + tab_label.show() + self.notebook.append_page(page, tab_label) + + + def create_send_tab(self): + + page = vbox = gtk.VBox() + page.show() + + payto = gtk.HBox() + payto_label = gtk.Label('Pay to:') + payto_label.set_size_request(100,-1) + payto.pack_start(payto_label, False) + payto_entry = gtk.Entry() + payto_entry.set_size_request(450, 26) + payto.pack_start(payto_entry, False) + vbox.pack_start(payto, False, False, 5) + + message = gtk.HBox() + message_label = gtk.Label('Description:') + message_label.set_size_request(100,-1) + message.pack_start(message_label, False) + message_entry = gtk.Entry() + message_entry.set_size_request(450, 26) + message.pack_start(message_entry, False) + vbox.pack_start(message, False, False, 5) + + amount_box = gtk.HBox() + amount_label = gtk.Label('Amount:') + amount_label.set_size_request(100,-1) + amount_box.pack_start(amount_label, False) + amount_entry = gtk.Entry() + amount_entry.set_size_request(120, -1) + amount_box.pack_start(amount_entry, False) + vbox.pack_start(amount_box, False, False, 5) + + self.fee_box = fee_box = gtk.HBox() + fee_label = gtk.Label('Fee:') + fee_label.set_size_request(100,-1) + fee_box.pack_start(fee_label, False) + fee_entry = gtk.Entry() + fee_entry.set_size_request(60, 26) + fee_box.pack_start(fee_entry, False) + vbox.pack_start(fee_box, False, False, 5) + + end_box = gtk.HBox() + empty_label = gtk.Label('') + empty_label.set_size_request(100,-1) + end_box.pack_start(empty_label, False) + send_button = gtk.Button("Send") + send_button.show() + end_box.pack_start(send_button, False, False, 0) + clear_button = gtk.Button("Clear") + clear_button.show() + end_box.pack_start(clear_button, False, False, 15) + send_button.connect("clicked", self.do_send, (payto_entry, message_entry, amount_entry, fee_entry)) + clear_button.connect("clicked", self.do_clear, (payto_entry, message_entry, amount_entry, fee_entry)) + + vbox.pack_start(end_box, False, False, 5) + + # display this line only if there is a signature + payto_sig = gtk.HBox() + payto_sig_id = gtk.Label('') + payto_sig.pack_start(payto_sig_id, False) + vbox.pack_start(payto_sig, True, True, 5) + + + self.user_fee = False + + def entry_changed( entry, is_fee ): + self.funds_error = False + amount = numbify(amount_entry) + fee = numbify(fee_entry) + if not is_fee: fee = None + if amount is None: + return + inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) + if not is_fee: + fee_entry.set_text( str( Decimal( fee ) / 100000000 ) ) + self.fee_box.show() + if inputs: + amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) + fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#000000")) + send_button.set_sensitive(True) + else: + send_button.set_sensitive(False) + amount_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) + fee_entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#cc0000")) + self.funds_error = True + + amount_entry.connect('changed', entry_changed, False) + fee_entry.connect('changed', entry_changed, True) + + self.payto_entry = payto_entry + self.payto_fee_entry = fee_entry + self.payto_sig_id = payto_sig_id + self.payto_sig = payto_sig + self.amount_entry = amount_entry + self.message_entry = message_entry + self.add_tab(page, 'Send') + + def set_frozen(self,entry,frozen): + if frozen: + entry.set_editable(False) + entry.set_has_frame(False) + entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#eeeeee")) + else: + entry.set_editable(True) + entry.set_has_frame(True) + entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#ffffff")) + + def set_url(self, url): + payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) + self.notebook.set_current_page(1) + self.payto_entry.set_text(payto) + self.message_entry.set_text(message) + self.amount_entry.set_text(amount) + if identity: + self.set_frozen(self.payto_entry,True) + self.set_frozen(self.amount_entry,True) + self.set_frozen(self.message_entry,True) + self.payto_sig_id.set_text( ' The bitcoin URI was signed by ' + identity ) + else: + self.payto_sig.set_visible(False) + + def create_about_tab(self): + import pango + page = gtk.VBox() + page.show() + tv = gtk.TextView() + tv.set_editable(False) + tv.set_cursor_visible(False) + tv.modify_font(pango.FontDescription(MONOSPACE_FONT)) + page.pack_start(tv) + self.info = tv.get_buffer() + self.add_tab(page, 'Wall') + + def do_clear(self, w, data): + self.payto_sig.set_visible(False) + self.payto_fee_entry.set_text('') + for entry in [self.payto_entry,self.amount_entry,self.message_entry]: + self.set_frozen(entry,False) + entry.set_text('') + + def question(self,msg): + dialog = gtk.MessageDialog( self.window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, msg) + dialog.show() + result = dialog.run() + dialog.destroy() + return result == gtk.RESPONSE_OK + + def do_send(self, w, data): + payto_entry, label_entry, amount_entry, fee_entry = data + label = label_entry.get_text() + r = payto_entry.get_text() + r = r.strip() + + m1 = re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r) + m2 = re.match('(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+) \<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) + + if m1: + to_address = self.wallet.get_alias(r, True, self.show_message, self.question) + if not to_address: + return + else: + self.update_sending_tab() + + elif m2: + to_address = m2.group(5) + else: + to_address = r + + if not self.wallet.is_valid(to_address): + self.show_message( "invalid bitcoin address:\n"+to_address) + return + + try: + amount = int( Decimal(amount_entry.get_text()) * 100000000 ) + except: + self.show_message( "invalid amount") + return + try: + fee = int( Decimal(fee_entry.get_text()) * 100000000 ) + except: + self.show_message( "invalid fee") + return + + if self.wallet.use_encryption: + password = password_dialog(self.window) + if not password: + return + else: + password = None + + try: + tx = self.wallet.mktx( to_address, amount, label, password, fee ) + except BaseException, e: + self.show_message(e.message) + return + + status, msg = self.wallet.sendtx( tx ) + if status: + self.show_message( "payment sent.\n" + msg ) + payto_entry.set_text("") + label_entry.set_text("") + amount_entry.set_text("") + fee_entry.set_text("") + #self.fee_box.hide() + self.update_sending_tab() + else: + self.show_message( msg ) + + + def treeview_button_press(self, treeview, event): + if event.type == gtk.gdk._2BUTTON_PRESS: + c = treeview.get_cursor()[0] + if treeview == self.history_treeview: + tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) + self.show_message(tx_details) + elif treeview == self.contacts_treeview: + m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) + a = self.wallet.aliases.get(m) + if a: + if a[0] in self.wallet.authorities.keys(): + s = self.wallet.authorities.get(a[0]) + else: + s = "self-signed" + msg = 'Alias: '+ m + '\nTarget address: '+ a[1] + '\n\nSigned by: ' + s + '\nSigning address:' + a[0] + self.show_message(msg) + + + def treeview_key_press(self, treeview, event): + c = treeview.get_cursor()[0] + if event.keyval == gtk.keysyms.Up: + if c and c[0] == 0: + treeview.parent.grab_focus() + treeview.set_cursor((0,)) + elif event.keyval == gtk.keysyms.Return: + if treeview == self.history_treeview: + tx_details = self.history_list.get_value( self.history_list.get_iter(c), 8) + self.show_message(tx_details) + elif treeview == self.contacts_treeview: + m = self.addressbook_list.get_value( self.addressbook_list.get_iter(c), 0) + a = self.wallet.aliases.get(m) + if a: + if a[0] in self.wallet.authorities.keys(): + s = self.wallet.authorities.get(a[0]) + else: + s = "self" + msg = 'Alias:'+ m + '\n\nTarget: '+ a[1] + '\nSigned by: ' + s + '\nSigning address:' + a[0] + self.show_message(msg) + + return False + + def create_history_tab(self): + + self.history_list = gtk.ListStore(str, str, str, str, 'gboolean', str, str, str, str) + treeview = gtk.TreeView(model=self.history_list) + self.history_treeview = treeview + treeview.set_tooltip_column(7) + treeview.show() + treeview.connect('key-press-event', self.treeview_key_press) + treeview.connect('button-press-event', self.treeview_button_press) + + tvcolumn = gtk.TreeViewColumn('') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererPixbuf() + tvcolumn.pack_start(cell, False) + tvcolumn.set_attributes(cell, stock_id=1) + + tvcolumn = gtk.TreeViewColumn('Date') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 2) + + tvcolumn = gtk.TreeViewColumn('Description') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_property('foreground', 'grey') + cell.set_property('family', MONOSPACE_FONT) + cell.set_property('editable', True) + def edited_cb(cell, path, new_text, h_list): + tx = h_list.get_value( h_list.get_iter(path), 0) + self.wallet.labels[tx] = new_text + self.wallet.save() + self.update_history_tab() + cell.connect('edited', edited_cb, self.history_list) + def editing_started(cell, entry, path, h_list): + tx = h_list.get_value( h_list.get_iter(path), 0) + if not self.wallet.labels.get(tx): entry.set_text('') + cell.connect('editing-started', editing_started, self.history_list) + tvcolumn.set_expand(True) + tvcolumn.pack_start(cell, True) + tvcolumn.set_attributes(cell, text=3, foreground_set = 4) + + tvcolumn = gtk.TreeViewColumn('Amount') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_alignment(1, 0.5) + cell.set_property('family', MONOSPACE_FONT) + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 5) + + tvcolumn = gtk.TreeViewColumn('Balance') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_alignment(1, 0.5) + cell.set_property('family', MONOSPACE_FONT) + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 6) + + tvcolumn = gtk.TreeViewColumn('Tooltip') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, False) + tvcolumn.add_attribute(cell, 'text', 7) + tvcolumn.set_visible(False) + + scroll = gtk.ScrolledWindow() + scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) + scroll.add(treeview) + + self.add_tab(scroll, 'History') + self.update_history_tab() + + + def create_recv_tab(self): + self.recv_list = gtk.ListStore(str, str, str) + self.add_tab( self.make_address_list(True), 'Receive') + self.update_receiving_tab() + + def create_book_tab(self): + self.addressbook_list = gtk.ListStore(str, str, str) + self.add_tab( self.make_address_list(False), 'Contacts') + self.update_sending_tab() + + def make_address_list(self, is_recv): + liststore = self.recv_list if is_recv else self.addressbook_list + treeview = gtk.TreeView(model= liststore) + treeview.connect('key-press-event', self.treeview_key_press) + treeview.connect('button-press-event', self.treeview_button_press) + treeview.show() + if not is_recv: + self.contacts_treeview = treeview + + tvcolumn = gtk.TreeViewColumn('Address') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_property('family', MONOSPACE_FONT) + tvcolumn.pack_start(cell, True) + tvcolumn.add_attribute(cell, 'text', 0) + + tvcolumn = gtk.TreeViewColumn('Label') + tvcolumn.set_expand(True) + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + cell.set_property('editable', True) + def edited_cb2(cell, path, new_text, liststore): + address = liststore.get_value( liststore.get_iter(path), 0) + self.wallet.labels[address] = new_text + self.wallet.save() + self.wallet.update_tx_labels() + self.update_receiving_tab() + self.update_sending_tab() + self.update_history_tab() + cell.connect('edited', edited_cb2, liststore) + tvcolumn.pack_start(cell, True) + tvcolumn.add_attribute(cell, 'text', 1) + + tvcolumn = gtk.TreeViewColumn('Tx') + treeview.append_column(tvcolumn) + cell = gtk.CellRendererText() + tvcolumn.pack_start(cell, True) + tvcolumn.add_attribute(cell, 'text', 2) + + scroll = gtk.ScrolledWindow() + scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) + scroll.add(treeview) + + hbox = gtk.HBox() + if not is_recv: + button = gtk.Button("New") + button.connect("clicked", self.newaddress_dialog) + button.show() + hbox.pack_start(button,False) + + def showqrcode(w, treeview, liststore): + path, col = treeview.get_cursor() + if not path: return + address = liststore.get_value(liststore.get_iter(path), 0) + qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) + qr.addData(address) + qr.make() + boxsize = 7 + size = qr.getModuleCount()*boxsize + def area_expose_cb(area, event): + style = area.get_style() + k = qr.getModuleCount() + for r in range(k): + for c in range(k): + gc = style.black_gc if qr.isDark(r, c) else style.white_gc + area.window.draw_rectangle(gc, True, c*boxsize, r*boxsize, boxsize, boxsize) + area = gtk.DrawingArea() + area.set_size_request(size, size) + area.connect("expose-event", area_expose_cb) + area.show() + dialog = gtk.Dialog(address, parent=self.window, flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, buttons = ("ok",1)) + dialog.vbox.add(area) + dialog.run() + dialog.destroy() + + button = gtk.Button("QR") + button.connect("clicked", showqrcode, treeview, liststore) + button.show() + hbox.pack_start(button,False) + + button = gtk.Button("Copy to clipboard") + def copy2clipboard(w, treeview, liststore): + import platform + path, col = treeview.get_cursor() + if path: + address = liststore.get_value( liststore.get_iter(path), 0) + if platform.system() == 'Windows': + from Tkinter import Tk + r = Tk() + r.withdraw() + r.clipboard_clear() + r.clipboard_append( address ) + r.destroy() + else: + c = gtk.clipboard_get() + c.set_text( address ) + button.connect("clicked", copy2clipboard, treeview, liststore) + button.show() + hbox.pack_start(button,False) + + if not is_recv: + button = gtk.Button("Pay to") + def payto(w, treeview, liststore): + path, col = treeview.get_cursor() + if path: + address = liststore.get_value( liststore.get_iter(path), 0) + self.payto_entry.set_text( address ) + self.notebook.set_current_page(1) + self.amount_entry.grab_focus() + + button.connect("clicked", payto, treeview, liststore) + button.show() + hbox.pack_start(button,False) + + vbox = gtk.VBox() + vbox.pack_start(scroll,True) + vbox.pack_start(hbox, False) + return vbox + + def update_status_bar(self): + interface = self.wallet.interface + if self.funds_error: + text = "Not enough funds" + elif interface.is_connected: + self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks\nresponse time: %f"%(interface.host, interface.port, self.wallet.blocks, interface.rtime)) + if self.wallet.blocks == -1: + self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) + text = "Connecting..." + elif self.wallet.blocks == 0: + self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) + text = "Server not ready" + elif not self.wallet.up_to_date: + self.status_image.set_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU) + text = "Synchronizing..." + else: + self.status_image.set_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_MENU) + self.network_button.set_tooltip_text("Connected to %s:%d.\n%d blocks\nresponse time: %f"%(interface.host, interface.port, self.wallet.blocks, interface.rtime)) + c, u = self.wallet.get_balance() + text = "Balance: %s "%( format_satoshis(c) ) + if u: text += "[%s unconfirmed]"%( format_satoshis(u,True).strip() ) + else: + self.status_image.set_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_MENU) + self.network_button.set_tooltip_text("Trying to contact %s.\n%d blocks"%(interface.host, self.wallet.blocks)) + text = "Not connected" + + self.status_bar.pop(self.context_id) + self.status_bar.push(self.context_id, text) + + if self.wallet.was_updated and self.wallet.up_to_date: + self.update_history_tab() + self.update_receiving_tab() + # addressbook too... + self.info.set_text( self.wallet.banner ) + self.wallet.was_updated = False + + + def update_receiving_tab(self): + self.recv_list.clear() + for address in self.wallet.all_addresses(): + if self.wallet.is_change(address):continue + label = self.wallet.labels.get(address) + n = 0 + h = self.wallet.history.get(address,[]) + for item in h: + if not item['is_input'] : n=n+1 + tx = "None" if n==0 else "%d"%n + self.recv_list.append((address, label, tx )) + + def update_sending_tab(self): + # detect addresses that are not mine in history, add them here... + self.addressbook_list.clear() + for alias, v in self.wallet.aliases.items(): + s, target = v + label = self.wallet.labels.get(alias) + self.addressbook_list.append((alias, label, '-')) + + for address in self.wallet.addressbook: + label = self.wallet.labels.get(address) + n = 0 + for item in self.wallet.tx_history.values(): + if address in item['outputs'] : n=n+1 + tx = "None" if n==0 else "%d"%n + self.addressbook_list.append((address, label, tx)) + + def update_history_tab(self): + cursor = self.history_treeview.get_cursor()[0] + self.history_list.clear() + balance = 0 + for tx in self.wallet.get_tx_history(): + tx_hash = tx['tx_hash'] + if tx['height']: + conf = self.wallet.blocks - tx['height'] + 1 + time_str = datetime.datetime.fromtimestamp( tx['timestamp']).isoformat(' ')[:-3] + conf_icon = gtk.STOCK_APPLY + else: + conf = 0 + time_str = 'pending' + conf_icon = gtk.STOCK_EXECUTE + v = tx['value'] + balance += v + label = self.wallet.labels.get(tx_hash) + is_default_label = (label == '') or (label is None) + if is_default_label: label = tx['default_label'] + tooltip = tx_hash + "\n%d confirmations"%conf + + # tx = self.wallet.tx_history.get(tx_hash) + details = "Transaction Details:\n\n" \ + + "Transaction ID:\n" + tx_hash + "\n\n" \ + + "Status: %d confirmations\n\n"%conf \ + + "Date: %s\n\n"%time_str \ + + "Inputs:\n-"+ '\n-'.join(tx['inputs']) + "\n\n" \ + + "Outputs:\n-"+ '\n-'.join(tx['outputs']) + r = self.wallet.receipts.get(tx_hash) + if r: + details += "\n_______________________________________" \ + + '\n\nSigned URI: ' + r[2] \ + + "\n\nSigned by: " + r[0] \ + + '\n\nSignature: ' + r[1] + + + self.history_list.prepend( [tx_hash, conf_icon, time_str, label, is_default_label, + format_satoshis(v,True), format_satoshis(balance), tooltip, details] ) + if cursor: self.history_treeview.set_cursor( cursor ) + + + + def newaddress_dialog(self, w): + + title = "New Contact" + dialog = gtk.Dialog(title, parent=self.window, + flags=gtk.DIALOG_MODAL|gtk.DIALOG_NO_SEPARATOR, + buttons= ("cancel", 0, "ok",1) ) + dialog.show() + + label = gtk.HBox() + label_label = gtk.Label('Label:') + label_label.set_size_request(120,10) + label_label.show() + label.pack_start(label_label) + label_entry = gtk.Entry() + label_entry.show() + label.pack_start(label_entry) + label.show() + dialog.vbox.pack_start(label, False, True, 5) + + address = gtk.HBox() + address_label = gtk.Label('Address:') + address_label.set_size_request(120,10) + address_label.show() + address.pack_start(address_label) + address_entry = gtk.Entry() + address_entry.show() + address.pack_start(address_entry) + address.show() + dialog.vbox.pack_start(address, False, True, 5) + + result = dialog.run() + address = address_entry.get_text() + label = label_entry.get_text() + dialog.destroy() + + if result == 1: + if self.wallet.is_valid(address): + self.wallet.addressbook.append(address) + if label: self.wallet.labels[address] = label + self.wallet.save() + self.update_sending_tab() + else: + errorDialog = gtk.MessageDialog( + parent=self.window, + flags=gtk.DIALOG_MODAL, + buttons= gtk.BUTTONS_CLOSE, + message_format = "Invalid address") + errorDialog.show() + errorDialog.run() + errorDialog.destroy() + + + +class ElectrumGui(): + + def __init__(self, wallet): + self.wallet = wallet + + def main(self, url=None): + ew = ElectrumWindow(self.wallet) + if url: ew.set_url(url) + gtk.main() + + def restore_or_create(self): + return restore_create_dialog(self.wallet) diff --git a/gui_qt.py b/gui_qt.py new file mode 100644 index 0000000..2620ac0 --- /dev/null +++ b/gui_qt.py @@ -0,0 +1,1057 @@ +#!/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 . + +import sys, time, datetime, re + +# todo: see PySide + +from PyQt4.QtGui import * +from PyQt4.QtCore import * +import PyQt4.QtCore as QtCore +import PyQt4.QtGui as QtGui +from interface import DEFAULT_SERVERS + +try: + import icons_rc +except: + print "Could not import icons_rp.py" + print "Please generate it with: 'pyrcc4 icons.qrc -o icons_rc.py'" + sys.exit(1) + +from wallet import format_satoshis +from decimal import Decimal + +import platform +MONOSPACE_FONT = 'Lucida Console' if platform.system() == 'Windows' else 'monospace' + + +def numbify(entry, is_int = False): + text = unicode(entry.text()).strip() + chars = '0123456789' + if not is_int: chars +='.' + s = ''.join([i for i in text if i in chars]) + if not is_int: + if '.' in s: + p = s.find('.') + s = s.replace('.','') + s = s[:p] + '.' + s[p:p+8] + try: + amount = int( Decimal(s) * 100000000 ) + except: + amount = None + else: + try: + amount = int( s ) + except: + amount = None + entry.setText(s) + return amount + + +class Timer(QtCore.QThread): + def run(self): + while True: + self.emit(QtCore.SIGNAL('timersignal')) + time.sleep(0.5) + +class EnterButton(QPushButton): + def __init__(self, text, func): + QPushButton.__init__(self, text) + self.func = func + self.clicked.connect(func) + + def keyPressEvent(self, e): + if e.key() == QtCore.Qt.Key_Return: + apply(self.func,()) + +class StatusBarButton(QPushButton): + def __init__(self, icon, tooltip, func): + QPushButton.__init__(self, icon, '') + self.setToolTip(tooltip) + self.setFlat(True) + self.setMaximumWidth(25) + self.clicked.connect(func) + self.func = func + + def keyPressEvent(self, e): + if e.key() == QtCore.Qt.Key_Return: + apply(self.func,()) + + +class QRCodeWidget(QWidget): + + def __init__(self, addr): + import pyqrnative + super(QRCodeWidget, self).__init__() + self.addr = addr + self.setGeometry(300, 300, 350, 350) + self.qr = pyqrnative.QRCode(4, pyqrnative.QRErrorCorrectLevel.H) + self.qr.addData(addr) + self.qr.make() + + def paintEvent(self, e): + qp = QtGui.QPainter() + qp.begin(self) + boxsize = 7 + size = self.qr.getModuleCount()*boxsize + k = self.qr.getModuleCount() + black = QColor(0, 0, 0, 255) + white = QColor(255, 255, 255, 255) + for r in range(k): + for c in range(k): + if self.qr.isDark(r, c): + qp.setBrush(black) + qp.setPen(black) + else: + qp.setBrush(white) + qp.setPen(white) + qp.drawRect(c*boxsize, r*boxsize, boxsize, boxsize) + qp.end() + + + +def ok_cancel_buttons(dialog): + hbox = QHBoxLayout() + hbox.addStretch(1) + b = QPushButton("OK") + hbox.addWidget(b) + b.clicked.connect(dialog.accept) + b = QPushButton("Cancel") + hbox.addWidget(b) + b.clicked.connect(dialog.reject) + return hbox + + +class ElectrumWindow(QMainWindow): + + def __init__(self, wallet): + QMainWindow.__init__(self) + self.wallet = wallet + self.wallet.gui_callback = self.update_callback + + self.funds_error = False + + self.tabs = tabs = QTabWidget(self) + tabs.addTab(self.create_history_tab(), 'History') + tabs.addTab(self.create_send_tab(), 'Send') + tabs.addTab(self.create_receive_tab(), 'Receive') + tabs.addTab(self.create_contacts_tab(),'Contacts') + tabs.addTab(self.create_wall_tab(), 'Wall') + tabs.setMinimumSize(600, 400) + tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.setCentralWidget(tabs) + self.create_status_bar() + self.setGeometry(100,100,840,400) + self.setWindowTitle( 'Electrum ' + self.wallet.electrum_version ) + self.show() + + QShortcut(QKeySequence("Ctrl+W"), self, self.close) + QShortcut(QKeySequence("Ctrl+Q"), self, self.close) + QShortcut(QKeySequence("Ctrl+PgUp"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() - 1 )%tabs.count() )) + QShortcut(QKeySequence("Ctrl+PgDown"), self, lambda: tabs.setCurrentIndex( (tabs.currentIndex() + 1 )%tabs.count() )) + + self.connect(self, QtCore.SIGNAL('updatesignal'), self.update_wallet) + + + def connect_slots(self, sender): + self.connect(sender, QtCore.SIGNAL('timersignal'), self.check_recipient) + self.previous_payto_e='' + + def check_recipient(self): + if self.payto_e.hasFocus(): + return + r = unicode( self.payto_e.text() ) + if r != self.previous_payto_e: + self.previous_payto_e = r + r = r.strip() + if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r): + try: + to_address = self.wallet.get_alias(r, True, self.show_message, self.question) + except: + return + if to_address: + s = r + ' <' + to_address + '>' + self.payto_e.setText(s) + + + def update_callback(self): + self.emit(QtCore.SIGNAL('updatesignal')) + + def update_wallet(self): + if self.wallet.interface.is_connected: + if self.wallet.blocks == -1: + text = "Connecting..." + icon = QIcon(":icons/status_disconnected.png") + elif self.wallet.blocks == 0: + text = "Server not ready" + icon = QIcon(":icons/status_disconnected.png") + elif not self.wallet.up_to_date: + text = "Synchronizing..." + icon = QIcon(":icons/status_waiting.png") + else: + c, u = self.wallet.get_balance() + text = "Balance: %s "%( format_satoshis(c) ) + if u: text += "[%s unconfirmed]"%( format_satoshis(u,True).strip() ) + icon = QIcon(":icons/status_connected.png") + else: + text = "Not connected" + icon = QIcon(":icons/status_disconnected.png") + + if self.funds_error: + text = "Not enough funds" + + self.statusBar().showMessage(text) + self.status_button.setIcon( icon ) + + if self.wallet.up_to_date: + self.textbox.setText( self.wallet.banner ) + self.update_history_tab() + self.update_receive_tab() + self.update_contacts_tab() + + + def create_history_tab(self): + self.history_list = w = QTreeWidget(self) + #print w.getContentsMargins() + w.setColumnCount(5) + w.setColumnWidth(0, 40) + w.setColumnWidth(1, 140) + w.setColumnWidth(2, 350) + w.setColumnWidth(3, 140) + w.setColumnWidth(4, 140) + w.setHeaderLabels( [ '', 'Date', 'Description', 'Amount', 'Balance'] ) + self.connect(w, SIGNAL('itemActivated(QTreeWidgetItem*, int)'), self.tx_details) + self.connect(w, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), self.tx_label_clicked) + self.connect(w, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), self.tx_label_changed) + return w + + def tx_details(self, item, column): + tx_hash = str(item.toolTip(0)) + tx = self.wallet.tx_history.get(tx_hash) + + if tx['height']: + conf = self.wallet.blocks - tx['height'] + 1 + time_str = datetime.datetime.fromtimestamp( tx['timestamp']).isoformat(' ')[:-3] + else: + conf = 0 + time_str = 'pending' + + tx_details = "Transaction Details:\n\n" \ + + "Transaction ID:\n" + tx_hash + "\n\n" \ + + "Status: %d confirmations\n\n"%conf \ + + "Date: %s\n\n"%time_str \ + + "Inputs:\n-"+ '\n-'.join(tx['inputs']) + "\n\n" \ + + "Outputs:\n-"+ '\n-'.join(tx['outputs']) + + r = self.wallet.receipts.get(tx_hash) + if r: + tx_details += "\n_______________________________________" \ + + '\n\nSigned URI: ' + r[2] \ + + "\n\nSigned by: " + r[0] \ + + '\n\nSignature: ' + r[1] + + QMessageBox.information(self, 'Details', tx_details, 'OK') + + + def tx_label_clicked(self, item, column): + if column==2 and item.isSelected(): + tx_hash = str(item.toolTip(0)) + self.is_edit=True + #if not self.wallet.labels.get(tx_hash): item.setText(2,'') + item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + self.history_list.editItem( item, column ) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + self.is_edit=False + + def tx_label_changed(self, item, column): + if self.is_edit: + return + self.is_edit=True + tx_hash = str(item.toolTip(0)) + tx = self.wallet.tx_history.get(tx_hash) + s = self.wallet.labels.get(tx_hash) + text = unicode( item.text(2) ) + if text: + self.wallet.labels[tx_hash] = text + item.setForeground(2, QBrush(QColor('black'))) + else: + if s: self.wallet.labels.pop(tx_hash) + text = tx['default_label'] + item.setText(2, text) + item.setForeground(2, QBrush(QColor('gray'))) + self.is_edit=False + + def address_label_clicked(self, item, column, l): + if column==1 and item.isSelected(): + item.setFlags(Qt.ItemIsEditable|Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + l.editItem( item, column ) + item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDragEnabled) + + def address_label_changed(self, item, column, l): + addr = unicode( item.text(0) ) + text = unicode( item.text(1) ) + if text: + self.wallet.labels[addr] = text + else: + s = self.wallet.labels.get(addr) + if s: self.wallet.labels.pop(addr) + self.update_history_tab() + + def update_history_tab(self): + self.history_list.clear() + balance = 0 + for tx in self.wallet.get_tx_history(): + tx_hash = tx['tx_hash'] + if tx['height']: + conf = self.wallet.blocks - tx['height'] + 1 + time_str = datetime.datetime.fromtimestamp( tx['timestamp']).isoformat(' ')[:-3] + icon = QIcon(":icons/confirmed.png") + else: + conf = 0 + time_str = 'pending' + icon = QIcon(":icons/unconfirmed.png") + v = tx['value'] + balance += v + label = self.wallet.labels.get(tx_hash) + is_default_label = (label == '') or (label is None) + if is_default_label: label = tx['default_label'] + + item = QTreeWidgetItem( [ '', time_str, label, format_satoshis(v,True), format_satoshis(balance)] ) + item.setFont(2, QFont(MONOSPACE_FONT)) + item.setFont(3, QFont(MONOSPACE_FONT)) + item.setFont(4, QFont(MONOSPACE_FONT)) + item.setToolTip(0, tx_hash) + if is_default_label: + item.setForeground(2, QBrush(QColor('grey'))) + + item.setIcon(0, icon) + self.history_list.insertTopLevelItem(0,item) + + + def create_send_tab(self): + w = QWidget() + + grid = QGridLayout() + grid.setSpacing(8) + grid.setColumnMinimumWidth(3,300) + grid.setColumnStretch(4,1) + + self.payto_e = QLineEdit() + grid.addWidget(QLabel('Pay to'), 1, 0) + grid.addWidget(self.payto_e, 1, 1, 1, 3) + + self.message_e = QLineEdit() + grid.addWidget(QLabel('Description'), 2, 0) + grid.addWidget(self.message_e, 2, 1, 1, 3) + + self.amount_e = QLineEdit() + grid.addWidget(QLabel('Amount'), 3, 0) + grid.addWidget(self.amount_e, 3, 1, 1, 2) + + self.fee_e = QLineEdit() + grid.addWidget(QLabel('Fee'), 4, 0) + grid.addWidget(self.fee_e, 4, 1, 1, 2) + + b = EnterButton("Send", self.do_send) + grid.addWidget(b, 5, 1) + + b = EnterButton("Clear",self.do_clear) + grid.addWidget(b, 5, 2) + + self.payto_sig = QLabel('') + grid.addWidget(self.payto_sig, 6, 0, 1, 4) + + w.setLayout(grid) + w.show() + + w2 = QWidget() + vbox = QVBoxLayout() + vbox.addWidget(w) + vbox.addStretch(1) + w2.setLayout(vbox) + + def entry_changed( is_fee ): + self.funds_error = False + amount = numbify(self.amount_e) + fee = numbify(self.fee_e) + if not is_fee: fee = None + if amount is None: + return + inputs, total, fee = self.wallet.choose_tx_inputs( amount, fee ) + if not is_fee: + self.fee_e.setText( str( Decimal( fee ) / 100000000 ) ) + if inputs: + palette = QPalette() + palette.setColor(self.amount_e.foregroundRole(), QColor('black')) + else: + palette = QPalette() + palette.setColor(self.amount_e.foregroundRole(), QColor('red')) + self.funds_error = True + self.amount_e.setPalette(palette) + self.fee_e.setPalette(palette) + + self.amount_e.textChanged.connect(lambda: entry_changed(False) ) + self.fee_e.textChanged.connect(lambda: entry_changed(True) ) + + return w2 + + def do_send(self): + + label = unicode( self.message_e.text() ) + r = unicode( self.payto_e.text() ) + r = r.strip() + + m1 = re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', r) + m2 = re.match('(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+) \<([1-9A-HJ-NP-Za-km-z]{26,})\>', r) + + if m1: + to_address = self.wallet.get_alias(r, True, self.show_message, self.question) + if not to_address: + return + elif m2: + to_address = m2.group(5) + else: + to_address = r + + if not self.wallet.is_valid(to_address): + QMessageBox.warning(self, 'Error', 'Invalid Bitcoin Address:\n'+to_address, 'OK') + return + + try: + amount = int( Decimal( unicode( self.amount_e.text())) * 100000000 ) + except: + QMessageBox.warning(self, 'Error', 'Invalid Amount', 'OK') + return + try: + fee = int( Decimal( unicode( self.fee_e.text())) * 100000000 ) + except: + QMessageBox.warning(self, 'Error', 'Invalid Fee', 'OK') + return + + if self.wallet.use_encryption: + password = self.password_dialog() + if not password: + return + else: + password = None + + try: + tx = self.wallet.mktx( to_address, amount, label, password, fee ) + except BaseException, e: + self.show_message(e.message) + return + + status, msg = self.wallet.sendtx( tx ) + if status: + QMessageBox.information(self, '', 'Payment sent.\n'+msg, 'OK') + self.do_clear() + self.update_contacts_tab() + else: + QMessageBox.warning(self, 'Error', msg, 'OK') + + + def set_url(self, url): + payto, amount, label, message, signature, identity, url = self.wallet.parse_url(url, self.show_message, self.question) + self.tabs.setCurrentIndex(1) + self.payto_e.setText(payto) + self.message_e.setText(message) + self.amount_e.setText(amount) + if identity: + self.set_frozen(self.payto_e,True) + self.set_frozen(self.amount_e,True) + self.set_frozen(self.message_e,True) + self.payto_sig.setText( ' The bitcoin URI was signed by ' + identity ) + else: + self.payto_sig.setVisible(False) + + def do_clear(self): + self.payto_sig.setVisible(False) + for e in [self.payto_e, self.message_e, self.amount_e, self.fee_e]: + e.setText('') + self.set_frozen(e,False) + + def set_frozen(self,entry,frozen): + if frozen: + entry.setReadOnly(True) + entry.setFrame(False) + palette = QPalette() + palette.setColor(entry.backgroundRole(), QColor('lightgray')) + entry.setPalette(palette) + else: + entry.setReadOnly(False) + entry.setFrame(True) + palette = QPalette() + palette.setColor(entry.backgroundRole(), QColor('white')) + entry.setPalette(palette) + + + def make_address_list(self, is_recv): + + l = QTreeWidget(self) + l.setColumnCount(3) + l.setColumnWidth(0, 350) + l.setColumnWidth(1, 330) + l.setColumnWidth(2, 20) + l.setHeaderLabels( ['Address', 'Label','Tx']) + + vbox = QVBoxLayout() + vbox.setMargin(0) + vbox.setSpacing(0) + vbox.addWidget(l) + + hbox = QHBoxLayout() + hbox.setMargin(0) + hbox.setSpacing(0) + + def get_addr(l): + i = l.currentItem() + if not i: return + addr = unicode( i.text(0) ) + return addr + + qrButton = EnterButton("QR",lambda: ElectrumWindow.showqrcode(get_addr(l))) + + def copy2clipboard(addr): + self.app.clipboard().setText(addr) + copyButton = EnterButton("Copy to Clipboard", lambda: copy2clipboard(get_addr(l))) + hbox.addWidget(qrButton) + hbox.addWidget(copyButton) + if not is_recv: + addButton = EnterButton("New", self.newaddress_dialog) + hbox.addWidget(addButton) + def payto(addr): + if not addr:return + self.tabs.setCurrentIndex(1) + self.payto_e.setText(addr) + self.amount_e.setFocus() + paytoButton = EnterButton('Pay to', lambda: payto(get_addr(l))) + hbox.addWidget(paytoButton) + hbox.addStretch(1) + buttons = QWidget() + buttons.setLayout(hbox) + vbox.addWidget(buttons) + + w = QWidget() + w.setLayout(vbox) + return w, l + + def create_receive_tab(self): + w, l = self.make_address_list(True) + self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l)) + self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l)) + self.receive_list = l + return w + + def create_contacts_tab(self): + w, l = self.make_address_list(False) + self.connect(l, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), lambda a, b: self.address_label_clicked(a,b,l)) + self.connect(l, SIGNAL('itemChanged(QTreeWidgetItem*, int)'), lambda a,b: self.address_label_changed(a,b,l)) + self.connect(l, SIGNAL('itemActivated(QTreeWidgetItem*, int)'), self.show_contact_details) + self.contacts_list = l + return w + + def update_receive_tab(self): + self.receive_list.clear() + for address in self.wallet.all_addresses(): + if self.wallet.is_change(address):continue + label = self.wallet.labels.get(address,'') + n = 0 + h = self.wallet.history.get(address,[]) + for item in h: + if not item['is_input'] : n=n+1 + tx = "None" if n==0 else "%d"%n + item = QTreeWidgetItem( [ address, label, tx] ) + item.setFont(0, QFont(MONOSPACE_FONT)) + self.receive_list.addTopLevelItem(item) + + def show_contact_details(self, item, column): + m = unicode(item.text(0)) + a = self.wallet.aliases.get(m) + if a: + if a[0] in self.wallet.authorities.keys(): + s = self.wallet.authorities.get(a[0]) + else: + s = "self-signed" + msg = 'Alias: '+ m + '\nTarget address: '+ a[1] + '\n\nSigned by: ' + s + '\nSigning address:' + a[0] + QMessageBox.information(self, 'Alias', msg, 'OK') + + def update_contacts_tab(self): + self.contacts_list.clear() + for alias, v in self.wallet.aliases.items(): + s, target = v + label = self.wallet.labels.get(alias,'') + item = QTreeWidgetItem( [ alias, label, '-'] ) + self.contacts_list.addTopLevelItem(item) + + for address in self.wallet.addressbook: + label = self.wallet.labels.get(address,'') + n = 0 + for item in self.wallet.tx_history.values(): + if address in item['outputs'] : n=n+1 + tx = "None" if n==0 else "%d"%n + item = QTreeWidgetItem( [ address, label, tx] ) + item.setFont(0, QFont(MONOSPACE_FONT)) + self.contacts_list.addTopLevelItem(item) + + + def create_wall_tab(self): + self.textbox = textbox = QTextEdit(self) + textbox.setFont(QFont(MONOSPACE_FONT)) + textbox.setReadOnly(True) + return textbox + + def create_status_bar(self): + sb = QStatusBar() + sb.setFixedHeight(35) + sb.addPermanentWidget( StatusBarButton( QIcon(":icons/lock.png"), "Password", lambda: self.change_password_dialog(self.wallet, self) ) ) + sb.addPermanentWidget( StatusBarButton( QIcon(":icons/preferences.png"), "Preferences", self.settings_dialog ) ) + sb.addPermanentWidget( StatusBarButton( QIcon(":icons/seed.png"), "Seed", lambda: self.show_seed_dialog(self.wallet, self) ) ) + self.status_button = StatusBarButton( QIcon(":icons/status_disconnected.png"), "Network", lambda: self.network_dialog(self.wallet, self) ) + sb.addPermanentWidget( self.status_button ) + self.setStatusBar(sb) + + def newaddress_dialog(self): + text, ok = QInputDialog.getText(self, 'New Contact', 'Address:') + address = unicode(text) + if ok: + if self.wallet.is_valid(address): + self.wallet.addressbook.append(address) + self.wallet.save() + self.update_contacts_tab() + else: + QMessageBox.warning(self, 'Error', 'Invalid Address', 'OK') + + @staticmethod + def show_seed_dialog(wallet, parent=None): + import mnemonic + if wallet.use_encryption: + password = parent.password_dialog() + if not password: return + else: + password = None + + try: + seed = wallet.pw_decode( wallet.seed, password) + except: + QMessageBox.warning(parent, 'Error', 'Invalid Password', 'OK') + return + + msg = "Your wallet generation seed is:\n\n" + seed \ + + "\n\nPlease keep it in a safe place; if you lose it, you will not be able to restore your wallet.\n\n" \ + + "Equivalently, your wallet seed can be stored and recovered with the following mnemonic code:\n\n\"" \ + + ' '.join(mnemonic.mn_encode(seed)) + "\"" + + QMessageBox.information(parent, 'Seed', msg, 'OK') + ElectrumWindow.showqrcode(seed) + + @staticmethod + def showqrcode(address): + if not address: return + d = QDialog(None) + d.setModal(1) + d.setWindowTitle(address) + d.setMinimumSize(270, 300) + vbox = QVBoxLayout() + vbox.addWidget(QRCodeWidget(address)) + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + d.exec_() + + def question(self, msg): + return QMessageBox.question(self, 'Message', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes + + def show_message(self, msg): + QMessageBox.information(self, 'Message', msg, 'OK') + + def password_dialog(self ): + d = QDialog(self) + d.setModal(1) + + pw = QLineEdit() + pw.setEchoMode(2) + + vbox = QVBoxLayout() + msg = 'Please enter your password' + vbox.addWidget(QLabel(msg)) + + grid = QGridLayout() + grid.setSpacing(8) + grid.addWidget(QLabel('Password'), 1, 0) + grid.addWidget(pw, 1, 1) + vbox.addLayout(grid) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + return unicode(pw.text()) + + @staticmethod + def change_password_dialog( wallet, parent=None ): + d = QDialog(parent) + d.setModal(1) + + pw = QLineEdit() + pw.setEchoMode(2) + new_pw = QLineEdit() + new_pw.setEchoMode(2) + conf_pw = QLineEdit() + conf_pw.setEchoMode(2) + + vbox = QVBoxLayout() + if parent: + msg = 'Your wallet is encrypted. Use this dialog to change your password.\nTo disable wallet encryption, enter an empty new password.' if wallet.use_encryption else 'Your wallet keys are not encrypted' + else: + msg = "Please choose a password to encrypt your wallet keys.\nLeave these fields empty if you want to disable encryption." + vbox.addWidget(QLabel(msg)) + + grid = QGridLayout() + grid.setSpacing(8) + + if wallet.use_encryption: + grid.addWidget(QLabel('Password'), 1, 0) + grid.addWidget(pw, 1, 1) + + grid.addWidget(QLabel('New Password'), 2, 0) + grid.addWidget(new_pw, 2, 1) + + grid.addWidget(QLabel('Confirm Password'), 3, 0) + grid.addWidget(conf_pw, 3, 1) + vbox.addLayout(grid) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + + password = unicode(pw.text()) if wallet.use_encryption else None + new_password = unicode(new_pw.text()) + new_password2 = unicode(conf_pw.text()) + + try: + seed = wallet.pw_decode( wallet.seed, password) + except: + QMessageBox.warning(parent, 'Error', 'Incorrect Password', 'OK') + return + + if new_password != new_password2: + QMessageBox.warning(parent, 'Error', 'Passwords do not match', 'OK') + return + + wallet.update_password(seed, new_password) + + @staticmethod + def seed_dialog(wallet, parent=None): + d = QDialog(parent) + d.setModal(1) + + vbox = QVBoxLayout() + msg = "Please enter your wallet seed or the corresponding mnemonic list of words, and the gap limit of your wallet." + vbox.addWidget(QLabel(msg)) + + grid = QGridLayout() + grid.setSpacing(8) + + seed_e = QLineEdit() + grid.addWidget(QLabel('Seed or mnemonic'), 1, 0) + grid.addWidget(seed_e, 1, 1) + + gap_e = QLineEdit() + gap_e.setText("5") + grid.addWidget(QLabel('Gap limit'), 2, 0) + grid.addWidget(gap_e, 2, 1) + gap_e.textChanged.connect(lambda: numbify(gap_e,True)) + vbox.addLayout(grid) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + + try: + gap = int(unicode(gap_e.text())) + except: + QMessageBox.warning(None, 'Error', 'error', 'OK') + sys.exit(0) + + try: + seed = unicode(seed_e.text()) + seed.decode('hex') + except: + import mnemonic + print "not hex, trying decode" + try: + seed = mnemonic.mn_decode( seed.split(' ') ) + except: + QMessageBox.warning(None, 'Error', 'I cannot decode this', 'OK') + sys.exit(0) + if not seed: + QMessageBox.warning(None, 'Error', 'no seed', 'OK') + sys.exit(0) + + wallet.seed = str(seed) + #print repr(wallet.seed) + wallet.gap_limit = gap + return True + + + def settings_dialog(self): + d = QDialog(self) + d.setModal(1) + + vbox = QVBoxLayout() + + msg = 'Here are the settings of your wallet.' + vbox.addWidget(QLabel(msg)) + + grid = QGridLayout() + grid.setSpacing(8) + + fee_e = QLineEdit() + fee_e.setText("%s"% str( Decimal( self.wallet.fee)/100000000 ) ) + grid.addWidget(QLabel('Fee per tx. input'), 2, 0) + grid.addWidget(fee_e, 2, 1) + vbox.addLayout(grid) + fee_e.textChanged.connect(lambda: numbify(fee_e,False)) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + + fee = unicode(fee_e.text()) + try: + fee = int( 100000000 * Decimal(fee) ) + except: + QMessageBox.warning(self, 'Error', 'Invalid value:%s'%fee, 'OK') + return + + self.wallet.fee = fee + self.wallet.save() + + @staticmethod + def network_dialog(wallet, parent=None): + interface = wallet.interface + if parent: + if interface.is_connected: + status = "Connected to %s:%d\n%d blocks\nresponse time: %f"%(interface.host, interface.port, wallet.blocks, interface.rtime) + else: + status = "Not connected" + server = wallet.server + else: + import random + status = "Please choose a server." + server = random.choice( DEFAULT_SERVERS ) + + plist = {} + for item in wallet.interface.servers: + host, pp = item + z = {} + for item2 in pp: + protocol, port = item2 + z[protocol] = port + plist[host] = z + + d = QDialog(parent) + d.setModal(1) + d.setWindowTitle('Server') + d.setMinimumSize(375, 20) + + vbox = QVBoxLayout() + vbox.setSpacing(20) + + hbox = QHBoxLayout() + l = QLabel() + l.setPixmap(QPixmap(":icons/network.png")) + hbox.addWidget(l) + hbox.addWidget(QLabel(status)) + + vbox.addLayout(hbox) + + hbox = QHBoxLayout() + host_line = QLineEdit() + host_line.setText(server) + hbox.addWidget(QLabel('Connect to:')) + hbox.addWidget(host_line) + vbox.addLayout(hbox) + + hbox = QHBoxLayout() + + buttonGroup = QGroupBox("protocol") + radio1 = QRadioButton("tcp", buttonGroup) + radio2 = QRadioButton("http", buttonGroup) + radio3 = QRadioButton("native", buttonGroup) + + def current_line(): + return unicode(host_line.text()).split(':') + + def set_button(protocol): + if protocol == 't': + radio1.setChecked(1) + elif protocol == 'h': + radio2.setChecked(1) + elif protocol == 'n': + radio3.setChecked(1) + + def set_protocol(protocol): + host = current_line()[0] + pp = plist[host] + if protocol not in pp.keys(): + protocol = pp.keys()[0] + set_button(protocol) + port = pp[protocol] + host_line.setText( host + ':' + port + ':' + protocol) + + radio1.clicked.connect(lambda x: set_protocol('t') ) + radio2.clicked.connect(lambda x: set_protocol('h') ) + radio3.clicked.connect(lambda x: set_protocol('n') ) + + set_button(current_line()[2]) + + hbox.addWidget(QLabel('Protocol:')) + hbox.addWidget(radio1) + hbox.addWidget(radio2) + hbox.addWidget(radio3) + + vbox.addLayout(hbox) + + if wallet.interface.servers: + servers_list = QTreeWidget(parent) + servers_list.setHeaderLabels( [ 'Active servers'] ) + servers_list.setMaximumHeight(150) + for host in plist.keys(): + servers_list.addTopLevelItem(QTreeWidgetItem( [ host ] )) + + def do_set_line(x): + host = unicode(x.text(0)) + pp = plist[host] + if 't' in pp.keys(): + protocol = 't' + else: + protocol = pp.keys()[0] + port = pp[protocol] + host_line.setText( host + ':' + port + ':' + protocol) + set_button(protocol) + + servers_list.connect(servers_list, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), do_set_line) + vbox.addWidget(servers_list) + else: + hbox = QHBoxLayout() + hbox.addWidget(QLabel('No nodes available')) + b = EnterButton("Find nodes", lambda: wallet.interface.get_servers(wallet) ) + hbox.addWidget(b) + vbox.addLayout(hbox) + + vbox.addLayout(ok_cancel_buttons(d)) + d.setLayout(vbox) + + if not d.exec_(): return + server = unicode( host_line.text() ) + + try: + wallet.set_server(server) + except: + QMessageBox.information(None, 'Error', 'error', 'OK') + if parent == None: + sys.exit(1) + else: + return + + return True + + + +class ElectrumGui(): + + def __init__(self, wallet): + self.wallet = wallet + self.app = QApplication(sys.argv) + + def waiting_dialog(self): + + s = Timer() + s.start() + w = QDialog() + w.resize(200, 70) + w.setWindowTitle('Electrum') + l = QLabel('') + vbox = QVBoxLayout() + vbox.addWidget(l) + w.setLayout(vbox) + w.show() + def f(): + if self.wallet.up_to_date: w.close() + else: + l.setText("Please wait...\nGenerating addresses: %d"%len(self.wallet.all_addresses())) + pass + w.connect(s, QtCore.SIGNAL('timersignal'), f) + self.wallet.interface.poke() + w.exec_() + w.destroy() + + + def restore_or_create(self): + + msg = "Wallet file not found.\nDo you want to create a new wallet,\n or to restore an existing one?" + r = QMessageBox.question(None, 'Message', msg, 'create', 'restore', 'cancel', 0, 2) + if r==2: return False + + is_recovery = (r==1) + wallet = self.wallet + # ask for the server. + if not ElectrumWindow.network_dialog( wallet, parent=None ): return False + + if not is_recovery: + wallet.new_seed(None) + wallet.init_mpk( wallet.seed ) + wallet.up_to_date_event.clear() + wallet.up_to_date = False + self.waiting_dialog() + # run a dialog indicating the seed, ask the user to remember it + ElectrumWindow.show_seed_dialog(wallet) + #ask for password + ElectrumWindow.change_password_dialog(wallet) + else: + # ask for seed and gap. + if not ElectrumWindow.seed_dialog( wallet ): return False + wallet.init_mpk( wallet.seed ) + wallet.up_to_date_event.clear() + wallet.up_to_date = False + self.waiting_dialog() + if wallet.is_found(): + # history and addressbook + wallet.update_tx_history() + wallet.fill_addressbook() + print "recovery successful" + wallet.save() + else: + QMessageBox.information(None, 'Message', "No transactions found for this seed", 'OK') + + wallet.save() + return True + + def main(self,url): + s = Timer() + s.start() + w = ElectrumWindow(self.wallet) + if url: w.set_url(url) + w.app = self.app + w.connect_slots(s) + w.update_wallet() + + self.app.exec_() diff --git a/icons.qrc b/icons.qrc new file mode 100644 index 0000000..9ee8acd --- /dev/null +++ b/icons.qrc @@ -0,0 +1,13 @@ + + + icons/confirmed.png + icons/lock.png + icons/preferences.png + icons/seed.png + icons/status_connected.png + icons/status_disconnected.png + icons/status_waiting.png + icons/unconfirmed.png + icons/network.png + + diff --git a/icons/confirmed.png b/icons/confirmed.png new file mode 100644 index 0000000000000000000000000000000000000000..901be189a6fca7d9d3f7efb2c5a494a5ec0b93ea GIT binary patch literal 1267 zcmV(G);P$p;kx>XP_3jgx;v64^oz(P$HEdhO+fyVb;Y=l74C{pt9#P8qQwek6QMfeLMqOrjB0$Q+a&4L{Z z=RFkkU|?98OxT=6^U06h)`N*X$pkkF0Pu~cqPZ)ITN>WjG;c~?G3pyuS7jB8w{IJH zjHWMoV%DA|RZDW1On79#69!lqaFD{`_D}f7-RJi8p5}D`AVP7P|4425cl9s5Q0g0} z!h?ZH6AQ$ejWu=QLRvW*JdjKI^Qwy*m#?VKV_}W}V`zQ6Yab5o__L|!1Zs!R$XXB^ zO6TWJ60!#u1^^ErMnzeLzo)kQy+D*&2YdO9no0WH$75eUy=G~VkQ^{P5HWaYf9u7A zXx`p-sOuN3U}kTaK=gOu*#mpOZoic71d{<4=8!e;Xw9O$vdX-@M3h~&Wc)X4>z7WK z6$VQNAelqfKT04|t3TsGVB+4du?ZC`O!{{`;3T~mw@5Ro=xDIHm`UMkn* zaZqI+6iJ030tr9}fXRgi6E3IWk%iwr_u5bIM@?@BcZ}82BQKem%~)w>-Nob7TvnA6 z4Qny@l`P0Y1qlM+!9fZsFM*_U0lyx&a=zmbuj=iv#st5C006q$QYRm%p16DVeEpSZ z_GBrdPKG80Kty2JNPB(w+W|U$xRU5Smbw0D(~;A-p3E_)7LA%{lt?7}>2zA(`q9e9 zWt%6IN3;THA_yXa2MgEGi$6}DzuMO1-?p&)sU`qsAP}$ufq%K?A*FZ1%8O?{`5 z{!}WZIgTSFDZ`cJh^5G~G3XB3p-{*ZLa-!BEQA0Nu_Q@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{CZacq!oeEY!z*7jGsYF@y$g{>bf32TwFc)(ziD(V~} zS~OKe0umH44lx!Hb2{@lqefBmMGRsT!C+KS1REvTsDzD6*f_<;88+@YyD}730(=Bm zf9%Lhj9s}2FhxOxB1_VuG6+Nj42T62gNczSL2MHfm9R@Q4s`?{ii{%!g7?@sCQ34F zlwxdrI<-<|^6!T`EH5u#TN8ayR33QtH@`%F`)dY~nXS!?_Ff3^E>wDoaLz@aPzVOmuFsYXv2l_^ALM07^*Q%Bq + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/icons/network.png b/icons/network.png new file mode 100644 index 0000000000000000000000000000000000000000..6a5bcba970804a39a01ba4cae4bd6992a2330e38 GIT binary patch literal 3031 zcmV;|3n=u7P)>JN&I zR5ThHbX&x5BDXOb$5K*9p=4ST#ivAam%B6fo_@HqOHz{cq7cF80K>UEJ3D*+_dI^* z&eEwW@8-?DtF8ZkFJSoF&;Knd528rWKnQ^l6kR^{fk41}MMEH{kLN>ijVj*z;v*cY7K7r*yjkV zt_6z5!+E#Piev8=KTYszRvkj^FhLpEvJC~autJqM^R08s#v9jngM#;-JSfe~b8=<@ zRp_Xs+_0gSP|QdSrMPEV#{Ycp-${~$pn)qRKou~k*cCIW#YoRM=bXV>NA3eEprR}^ zG6EJASl73P5QI>O4MiBn-2jjzDIr`D0Wp?gbD(dy-fYjGkqCWelW0v75`avuPt zx2sH}>7(a#DIbDHU;5k^9!Rc?2fWY8ni;6#ecm>5$rG$FMp2AWnpuYT;1%X;4Kyfe zYO&VP%wySX-=p|^P(}R}6fg_eMuWNe(`cUIv&ABmmcAIIeSJ|`5psN{gaC~^kmorf zmab}vEcd8Nd&W`P$*e`v132f}q3c!=K`dnRGBI%y%@+yH`NB|x2$%?iCF_C2TC}l% zFOoBBcoH$V)KX3ziqOj0pb&fkE)DpwWT@;*7UuL`~rn@F71#z*VHFO%j~57-zva0@4On+mQiO1QXj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0f? z7emwjYkFxm8f@LV)&1n~n>x_f2S&JQ%gy%iPY=uHEgNNWa*EBHHXf1M zo@Qa8#?GOg%*`)w{Ma#OW~RCEhMSlepWyiM)xlWvnhFgT23uy9hZYq}4drqfmnIkr&xwIz!Eddjr>BQU3FK9}{nI^Wgg7 z;eGeF1pqwq$Rj7;DF-DsL=LEY;cx!>SBJLmXx{#d+bfMmW5so)QkjrveB)o9U7Vbp z^rccMBrYjRBZ$a3@_ngE6eAb4Xl*u{r98_=+BqOAI<~Vm1Ef24?bvwl$3Oo0zW!_O zHsVU(f9*Az&E^>bN>r;|d}!CMq_(hdJV}xtcdhMly$Nuoq>xy3U!p|m@OQNZ+;+IA@I5-%_#>RAZc6P;0@;ndT`-XGw z)1axKfk`-Xr_IAy-ZC_b1BD0 zz1}EQDy6BZ=}V&Nsst1_@SpwMp1-{A+QHHBlj9pU_4F_~ImOL4-Ec|AZQHiHA0B-D z{4^aOKZ~ZT5&-bv?xzf3N%ixx3sg%mh^h}F>bgk(mYc|h$^jXf}=1sJ&pPxHz zKXBXo`RV8={R92yrs*&3I*X>O7SL$sfAQ(h{N~YP$B%vBweP=1ATWCLNL)oCXz{F) z;_0z0Yv;zs#!yw>dTWgB+qQFhZk}Urzs>aY)H~4hSI(m8ss!A3-+le1N_yw@*Wb{2 z{d=!x*Bu{f8yFX2OGdYl(LUc=87|9fMd9AxVCgyO*)-jFMNWxGksYs&imuWF#m4YV@w#-u3_N Z@qe8?M#M5n{0jg8002ovPDHLkV1kvE;jsV! literal 0 HcmV?d00001 diff --git a/icons/preferences.png b/icons/preferences.png new file mode 100644 index 0000000000000000000000000000000000000000..2596f3cc5eb500a4b866146ef4f2b1706b72aae4 GIT binary patch literal 1691 zcmV;M24wk(P)=DcaWxi`ep6rD=zgT=e~d=}J9qD}F$_7s`q|YEizS5|`skn}iemkqnuhA>Od1<& z=YcQ>WkT0iZmPWbV2+uh-byL8_=oQjLC}*;zuzomWMsVd>efH}ZYuNorrL6oIjMW? znu z41xgw9vKz^GrPEWi7*-oA~F_6Vv?E3$;q+mz&20RaP^I~Jj=4(E1oXTk|YW3U$pnJ zEE6yq41(EYg4vV=_Z_#UD9W)1&8y$8PBgK?^E{tGDL_O?L@*FSzq?RW!s;astnJYp^X-R2bN=hP949J?SuC07++xh!lQcAI>;f(^8WiLFv;wb~mvXidCk?Dl0sMz=BzGyTWS(lmN z=wx|xl$Mm{XU~|ywYZwaKp@bqC`yY)nH!a_R=Or#h5B6QY_Kecru~g$Nr{QRvSnp69NF1iOKYb?m#;8nq}$Qn-i9ZhSOAB^0axn@F&GSeX*O6^ zO=ms{FkNilv2`=Ya@F?COvB&_R#VE_lM+e_OwEcSlKYZ!b45N-c>PSl{TvcRe z{`~1Bl+PKFjOy^M;gOM9&#hf0*fMOeB&On%BZtM}qGDZURu)4w4euOyC)(fN-*o7M zzf?^LDBO7V7aWUsE0(4kiwn}on55v&&^_$`;G~*BrJN^c4!+3qeD&IjH9}gN6=}&< zgu+3H(ik*N1IH#{Z^K?O5{VQX{`g4${Ta;L*pd9>SI!-`S`yyf_Tp?)QGOZ;kIDFM zD1wWZZ>vNZJ9_o#7XO?3-hN9I#RF&0oD*X)2_D}7Mk8SagCX1t-Giczqj*UXuhZ%N z1OOZW8)S zHh%sO($Ui1C12>dbbX-fy?OvbTzXknxWf5`1%W^yb>_?*)?hGV?wmZ{JLFjdptZB3 z`BBL0xKoPgn2XR~~QeV6I-fA>O^#_A6y9AjWHGTx#F7>!&lb zGM!hiT(ghM5=*H@`}+DuJs!`YyFPyifE))<5+5297YiW4GG|$CY@jzFia`Q^kBf~9 z6QG|iU6Pw$khewCXwJ92msfm!p~nMY9Dp*>0il$F5Q6wACm_rNh7+2|PXH(Y4S<^E l$YMN$9w~0B#@8tT`frm{0s2>vdAk4r002ovPDHLkV1m?gC#wJe literal 0 HcmV?d00001 diff --git a/icons/seed.png b/icons/seed.png new file mode 100644 index 0000000000000000000000000000000000000000..54c38b6abb1b81f353b1bfcc4635fc4cf8cb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YD`*8|; zV_*im&2BfrT3l;!@@1O|XaRH!`99+NG{Z2-V0R3BB(fhT$}ry=|?3uUz&@QG}Z$BNGGSy2QpX@H~F(_v6FiaQHiX{vG@PybzJ- zI&cQ4EyD7r@MTr0wRb(wS+mz;zbqf*z0000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + Lapo Calamandrei + + + + + Record + + + record + media + + + + + Jakub Steiner + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/icons/status_waiting.png b/icons/status_waiting.png new file mode 100644 index 0000000000000000000000000000000000000000..41a4ea059a648484e6c4987bd90935f76ea051d2 GIT binary patch literal 1501 zcmV<31tR*1P)Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01ejw01ejxLMWSf00007bV*G`2iyY^ z3n2yMIGw!!00mu1L_t(Y$F){lY*bYgUFUIMGtIl%wC$bJ8Y!?gUg5poG1N4XS4ifBpFZfR%;yZ75RdD*+c zzrNnm1pxeB0hKFuJk1SbEpMh%tTJD|Zg8JQ82}LzuG77sd|%t`So}gd6W{gsv27QJ z?k!y&4hSLI0q7$tsCqc;V-tdhg28c%90^Mi0!k?uV_=MeQ3}pEay%OR9u00L+1uLQ z+0-8C-Pu_GN_}YYc7IK6@eh^d<4fLpX-V*|3KU@zb{{P*D_I;%+8|IcGy+Z2U}zjl z5x5E<1W4NwhOXfE`|}>1R4`xJnHfJ9?%!_YD@gs-8`4YkFZ~;n)o`t4gcXKaD;*!BK;r%r8IQ2JV?}_$}&(F{Q*q>`P<$AoAq?FfOsE*M_@$Bat zKWI49yy4u1fBHD1pp+nGOQdW8N~j!Gfj0^_>2Zwe%F+e~JxRHnvZ?8?o3KYCsD9$T z;`tAT_RN}5k(;(%2&s^=1yZ&I$Xya$Xb8tc%ieiE$8Vm0b5*572vPSlQfTpZ|D0K6 z$5%c!yCRVh$hA09wt~hPyrzaoijfgcu3oe2L&MM*B@`M57@_?FN+4s~f!B3OygG#| z6##+HzB+xrt3CGpK`Zti7hk4C^WK1NDW9#1<{y89B;?41xVE|Q_2BqY9>$0 z8xyGWc|O|E)zi24a&6zI2#4k1`9+UB5RD}Ycl+VkH_RSvK*8OU1O(JMXNo5V5w<%#^|QUtGMowLXnJ}if59EF6pGMB|5JixPEHS2>|IK$P75y$e+HV zFmnD#41kfn?uLQ`pq!hUSx`NWTVrz=)r1r8i1fAo)(XJRA~OVO0P5~bpJyx5vtOQ- zaX`v}c$tL&;AY`u6T1M^e|uHjS#(JJz-Bcx(P-;m+SqXb@Dz@x00000NkvXXu0mjf Dz+SxI literal 0 HcmV?d00001 diff --git a/icons/status_waiting.svg b/icons/status_waiting.svg new file mode 100644 index 0000000..fb51a42 --- /dev/null +++ b/icons/status_waiting.svg @@ -0,0 +1,397 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + Jakub Steiner + + + http://jimmac.musichall.cz + + View Refresh + + + reload + refresh + view + + + + + Ricardo 'Rick' González + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/icons/unconfirmed.png b/icons/unconfirmed.png new file mode 100644 index 0000000000000000000000000000000000000000..f8d87ed5f052ef2fa75365ee08acfd7933e38867 GIT binary patch literal 1574 zcmV+>2HE+EP)Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01ejw01ejxLMWSf00007bV*G`2iyY^ z3m!5ATM~`{00pK=L_t(Y$E8$zY*Td@J@?()c4chqUS*C!*_+24fq~-KY9}Bu2yO@w z#do4XMU5z6g3qX+7<`amOu!MCZh#M>4E7L2B;ddaRJWD2E8U}ADXhD+xA)QOKm9`o zOc%f8`{(?U?|i>=z8ngp)SNkUc(2#10)Tzdq7@S-PA;HGTnq+-D*kURsi}EsZ~a$+ zm8&1z1OU5gYcKhH1F@>bi+7A=4tcYO%*;&N^y1>=M^~?2f9ls$V#$nYmX59tA{-XG z0g$)OzPgsCB;c#e4sp*;X=gqYPG0NxfqlblI!emN-y>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null +++ b/icons/unconfirmed.svg @@ -0,0 +1,562 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + Lapo Calamandrei + + + System Run + + + + run + launch + exec + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/interface.py b/interface.py new file mode 100644 index 0000000..21ea5a8 --- /dev/null +++ b/interface.py @@ -0,0 +1,425 @@ +#!/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 . + + +import random, socket, ast, re +import threading, traceback, sys, time, json, Queue + +DEFAULT_TIMEOUT = 5 +DEFAULT_SERVERS = [ 'ecdsa.org:50001:t', 'electrum.novit.ro:50001:t', 'electrum.bitcoins.sk:50001:t'] # list of default servers + + +def old_to_new(s): + s = s.replace("'blk_hash'", "'block_hash'") + s = s.replace("'pos'", "'index'") + s = s.replace("'nTime'", "'timestamp'") + s = s.replace("'is_in'", "'is_input'") + s = s.replace("'raw_scriptPubKey'","'raw_output_script'") + return s + + +class Interface(threading.Thread): + def __init__(self, host, port): + threading.Thread.__init__(self) + self.daemon = True + self.host = host + self.port = port + + self.servers = [] # actual list from IRC + self.rtime = 0 + + self.is_connected = True + self.poll_interval = 1 + + #json + self.message_id = 0 + self.responses = Queue.Queue() + self.methods = {} + + def poke(self): + # push a fake response so that the getting thread exits its loop + self.responses.put(None) + + def queue_json_response(self, c): + + #print "<--",c + msg_id = c.get('id') + error = c.get('error') + + if error: + print "received error:", c + return + + if msg_id is not None: + method, params = self.methods.pop(msg_id) + result = c.get('result') + else: + # notification + method = c.get('method') + params = c.get('params') + + if method == 'blockchain.numblocks.subscribe': + result = params[0] + params = [] + + elif method == 'blockchain.address.subscribe': + addr = params[0] + result = params[1] + params = [addr] + + self.responses.put({'method':method, 'params':params, 'result':result}) + + + + def subscribe(self, addresses): + messages = [] + for addr in addresses: + messages.append(('blockchain.address.subscribe', [addr])) + self.send(messages) + + + def get_servers(self, wallet): + # loop over default servers + # requesting servers could be an independent process + addresses = wallet.all_addresses() + version = wallet.electrum_version + + for server in DEFAULT_SERVERS: + print "connecting to", server + try: + self.host = server + self.start_session(addresses, version) + wallet.host = self.host + break + except socket.timeout: + continue + except socket.error: + continue + except: + traceback.print_exc(file=sys.stdout) + + + def start_session(self, addresses, version): + #print "Starting new session: %s:%d"%(self.host,self.port) + self.send([('server.version', [version]), ('server.banner',[]), ('blockchain.numblocks.subscribe',[]), ('server.peers.subscribe',[])]) + self.subscribe(addresses) + + +class PollingInterface(Interface): + """ non-persistent connection. synchronous calls""" + + def __init__(self, host, port): + Interface.__init__(self, host, port) + self.session_id = None + + def get_history(self, address): + self.send([('blockchain.address.get_history', [address] )]) + + def poll(self): + pass + #if is_new or wallet.remote_url: + # self.was_updated = True + # is_new = wallet.synchronize() + # wallet.update_tx_history() + # wallet.save() + # return is_new + #else: + # return False + + def run(self): + self.is_connected = True + while self.is_connected: + try: + if self.session_id: + self.poll() + time.sleep(self.poll_interval) + except socket.gaierror: + break + except socket.error: + break + except: + traceback.print_exc(file=sys.stdout) + break + + self.is_connected = False + self.poke() + + + + + + + + + +class HttpStratumInterface(PollingInterface): + + def poll(self): + self.send([]) + + def send(self, messages): + import urllib2, json, time, cookielib + + cj = cookielib.CookieJar() + opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) + urllib2.install_opener(opener) + + t1 = time.time() + + data = [] + for m in messages: + method, params = m + if type(params) != type([]): params = [params] + data.append( { 'method':method, 'id':self.message_id, 'params':params } ) + self.methods[self.message_id] = method, params + self.message_id += 1 + + if data: + data_json = json.dumps(data) + else: + # poll with GET + data_json = None + + host = 'http://%s:%d'%( self.host, self.port ) + headers = {'content-type': 'application/json'} + if self.session_id: + headers['cookie'] = 'SESSION=%s'%self.session_id + + req = urllib2.Request(host, data_json, headers) + response_stream = urllib2.urlopen(req) + + for index, cookie in enumerate(cj): + if cookie.name=='SESSION': + self.session_id = cookie.value + + response = response_stream.read() + if response: + response = json.loads( response ) + if type(response) is not type([]): + self.queue_json_response(response) + else: + for item in response: + self.queue_json_response(item) + + if response: + self.poll_interval = 1 + else: + if self.poll_interval < 15: + self.poll_interval += 1 + #print self.poll_interval, response + + self.rtime = time.time() - t1 + self.is_connected = True + + + + +class TcpStratumInterface(Interface): + """json-rpc over persistent TCP connection, asynchronous""" + + def __init__(self, host, port): + Interface.__init__(self, host, port) + self.s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) + self.s.settimeout(5) + self.s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + try: + self.s.connect(( self.host, self.port)) + self.is_connected = True + except: + self.is_connected = False + print "not connected" + + def run(self): + try: + out = '' + while self.is_connected: + try: msg = self.s.recv(1024) + except socket.timeout: + continue + out += msg + if msg == '': + self.is_connected = False + print "disconnected." + + while True: + s = out.find('\n') + if s==-1: break + c = out[0:s] + out = out[s+1:] + c = json.loads(c) + self.queue_json_response(c) + + except: + traceback.print_exc(file=sys.stdout) + + self.is_connected = False + print "poking" + self.poke() + + def send(self, messages): + out = '' + for m in messages: + method, params = m + request = json.dumps( { 'id':self.message_id, 'method':method, 'params':params } ) + self.methods[self.message_id] = method, params + #print "-->",request + self.message_id += 1 + out += request + '\n' + self.s.send( out ) + + def get_history(self, addr): + self.send([('blockchain.address.get_history', [addr])]) + + + + + +class WalletSynchronizer(threading.Thread): + + def __init__(self, wallet, loop=False): + threading.Thread.__init__(self) + self.daemon = True + self.wallet = wallet + self.loop = loop + self.start_interface() + + + def handle_response(self, r): + if r is None: + return + + method = r['method'] + params = r['params'] + result = r['result'] + + if method == 'server.banner': + self.wallet.banner = result + self.wallet.was_updated = True + + elif method == 'server.peers.subscribe': + servers = [] + for item in result: + s = [] + host = item[1] + ports = [] + if len(item)>2: + for v in item[2]: + if re.match("[th]\d+",v): + ports.append((v[0],v[1:])) + if ports: + servers.append( (host, ports) ) + self.interface.servers = servers + + elif method == 'blockchain.address.subscribe': + addr = params[0] + self.wallet.receive_status_callback(addr, result) + + elif method == 'blockchain.address.get_history': + addr = params[0] + self.wallet.receive_history_callback(addr, result) + self.wallet.was_updated = True + + elif method == 'blockchain.transaction.broadcast': + self.wallet.tx_result = result + self.wallet.tx_event.set() + + elif method == 'blockchain.numblocks.subscribe': + self.wallet.blocks = result + + elif method == 'server.version': + pass + + else: + print "unknown message:", method, params, result + + + def start_interface(self): + try: + host, port, protocol = self.wallet.server.split(':') + port = int(port) + except: + self.wallet.pick_random_server() + host, port, protocol = self.wallet.server.split(':') + port = int(port) + + #print protocol, host, port + if protocol == 't': + InterfaceClass = TcpStratumInterface + elif protocol == 'h': + InterfaceClass = HttpStratumInterface + else: + print "unknown protocol" + InterfaceClass = TcpStratumInterface + + self.interface = InterfaceClass(host, port) + self.wallet.interface = self.interface + + with self.wallet.lock: + self.wallet.addresses_waiting_for_status = [] + self.wallet.addresses_waiting_for_history = [] + addresses = self.wallet.all_addresses() + version = self.wallet.electrum_version + for addr in addresses: + self.wallet.addresses_waiting_for_status.append(addr) + + try: + self.interface.start() + self.interface.start_session(addresses,version) + except: + self.interface.is_connected = False + + + def run(self): + import socket, time + while True: + while self.interface.is_connected: + new_addresses = self.wallet.synchronize() + if new_addresses: + self.interface.subscribe(new_addresses) + for addr in new_addresses: + with self.wallet.lock: + self.wallet.addresses_waiting_for_status.append(addr) + + if self.wallet.is_up_to_date(): + if not self.wallet.up_to_date: + self.wallet.up_to_date = True + self.wallet.was_updated = True + self.wallet.up_to_date_event.set() + else: + if self.wallet.up_to_date: + self.wallet.up_to_date = False + self.wallet.was_updated = True + + if self.wallet.was_updated: + self.wallet.gui_callback() + self.wallet.was_updated = False + + response = self.interface.responses.get() + self.handle_response(response) + + print "disconnected, gui callback" + self.wallet.gui_callback() + if self.loop: + time.sleep(5) + self.start_interface() + continue + else: + break + + + diff --git a/mnemonic.py b/mnemonic.py new file mode 100644 index 0000000..82d2624 --- /dev/null +++ b/mnemonic.py @@ -0,0 +1,1689 @@ +#!/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 . + + + +# list of words from http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/Contemporary_poetry + +words = [ +"like", +"just", +"love", +"know", +"never", +"want", +"time", +"out", +"there", +"make", +"look", +"eye", +"down", +"only", +"think", +"heart", +"back", +"then", +"into", +"about", +"more", +"away", +"still", +"them", +"take", +"thing", +"even", +"through", +"long", +"always", +"world", +"too", +"friend", +"tell", +"try", +"hand", +"thought", +"over", +"here", +"other", +"need", +"smile", +"again", +"much", +"cry", +"been", +"night", +"ever", +"little", +"said", +"end", +"some", +"those", +"around", +"mind", +"people", +"girl", +"leave", +"dream", +"left", +"turn", +"myself", +"give", +"nothing", +"really", +"off", +"before", +"something", +"find", +"walk", +"wish", +"good", +"once", +"place", +"ask", +"stop", +"keep", +"watch", +"seem", +"everything", +"wait", +"got", +"yet", +"made", +"remember", +"start", +"alone", +"run", +"hope", +"maybe", +"believe", +"body", +"hate", +"after", +"close", +"talk", +"stand", +"own", +"each", +"hurt", +"help", +"home", +"god", +"soul", +"new", +"many", +"two", +"inside", +"should", +"true", +"first", +"fear", +"mean", +"better", +"play", +"another", +"gone", +"change", +"use", +"wonder", +"someone", +"hair", +"cold", +"open", +"best", +"any", +"behind", +"happen", +"water", +"dark", +"laugh", +"stay", +"forever", +"name", +"work", +"show", +"sky", +"break", +"came", +"deep", +"door", +"put", +"black", +"together", +"upon", +"happy", +"such", +"great", +"white", +"matter", +"fill", +"past", +"please", +"burn", +"cause", +"enough", +"touch", +"moment", +"soon", +"voice", +"scream", +"anything", +"stare", +"sound", +"red", +"everyone", +"hide", +"kiss", +"truth", +"death", +"beautiful", +"mine", +"blood", +"broken", +"very", +"pass", +"next", +"forget", +"tree", +"wrong", +"air", +"mother", +"understand", +"lip", +"hit", +"wall", +"memory", +"sleep", +"free", +"high", +"realize", +"school", +"might", +"skin", +"sweet", +"perfect", +"blue", +"kill", +"breath", +"dance", +"against", +"fly", +"between", +"grow", +"strong", +"under", +"listen", +"bring", +"sometimes", +"speak", +"pull", +"person", +"become", +"family", +"begin", +"ground", +"real", +"small", +"father", +"sure", +"feet", +"rest", +"young", +"finally", +"land", +"across", +"today", +"different", +"guy", +"line", +"fire", +"reason", +"reach", +"second", +"slowly", +"write", +"eat", +"smell", +"mouth", +"step", +"learn", +"three", +"floor", +"promise", +"breathe", +"darkness", +"push", +"earth", +"guess", +"save", +"song", +"above", +"along", +"both", +"color", +"house", +"almost", +"sorry", +"anymore", +"brother", +"okay", +"dear", +"game", +"fade", +"already", +"apart", +"warm", +"beauty", +"heard", +"notice", +"question", +"shine", +"began", +"piece", +"whole", +"shadow", +"secret", +"street", +"within", +"finger", +"point", +"morning", +"whisper", +"child", +"moon", +"green", +"story", +"glass", +"kid", +"silence", +"since", +"soft", +"yourself", +"empty", +"shall", +"angel", +"answer", +"baby", +"bright", +"dad", +"path", +"worry", +"hour", +"drop", +"follow", +"power", +"war", +"half", +"flow", +"heaven", +"act", +"chance", +"fact", +"least", +"tired", +"children", +"near", +"quite", +"afraid", +"rise", +"sea", +"taste", +"window", +"cover", +"nice", +"trust", +"lot", +"sad", +"cool", +"force", +"peace", +"return", +"blind", +"easy", +"ready", +"roll", +"rose", +"drive", +"held", +"music", +"beneath", +"hang", +"mom", +"paint", +"emotion", +"quiet", +"clear", +"cloud", +"few", +"pretty", +"bird", +"outside", +"paper", +"picture", +"front", +"rock", +"simple", +"anyone", +"meant", +"reality", +"road", +"sense", +"waste", +"bit", +"leaf", +"thank", +"happiness", +"meet", +"men", +"smoke", +"truly", +"decide", +"self", +"age", +"book", +"form", +"alive", +"carry", +"escape", +"damn", +"instead", +"able", +"ice", +"minute", +"throw", +"catch", +"leg", +"ring", +"course", +"goodbye", +"lead", +"poem", +"sick", +"corner", +"desire", +"known", +"problem", +"remind", +"shoulder", +"suppose", +"toward", +"wave", +"drink", +"jump", +"woman", +"pretend", +"sister", +"week", +"human", +"joy", +"crack", +"grey", +"pray", +"surprise", +"dry", +"knee", +"less", +"search", +"bleed", +"caught", +"clean", +"embrace", +"future", +"king", +"son", +"sorrow", +"chest", +"hug", +"remain", +"sat", +"worth", +"blow", +"daddy", +"final", +"parent", +"tight", +"also", +"create", +"lonely", +"safe", +"cross", +"dress", +"evil", +"silent", +"bone", +"fate", +"perhaps", +"anger", +"class", +"scar", +"snow", +"tiny", +"tonight", +"continue", +"control", +"dog", +"edge", +"mirror", +"month", +"suddenly", +"comfort", +"given", +"loud", +"quickly", +"gaze", +"plan", +"rush", +"stone", +"town", +"battle", +"ignore", +"spirit", +"stood", +"stupid", +"yours", +"brown", +"build", +"dust", +"hey", +"kept", +"pay", +"phone", +"twist", +"although", +"ball", +"beyond", +"hidden", +"nose", +"taken", +"fail", +"float", +"pure", +"somehow", +"wash", +"wrap", +"angry", +"cheek", +"creature", +"forgotten", +"heat", +"rip", +"single", +"space", +"special", +"weak", +"whatever", +"yell", +"anyway", +"blame", +"job", +"choose", +"country", +"curse", +"drift", +"echo", +"figure", +"grew", +"laughter", +"neck", +"suffer", +"worse", +"yeah", +"disappear", +"foot", +"forward", +"knife", +"mess", +"somewhere", +"stomach", +"storm", +"beg", +"idea", +"lift", +"offer", +"breeze", +"field", +"five", +"often", +"simply", +"stuck", +"win", +"allow", +"confuse", +"enjoy", +"except", +"flower", +"seek", +"strength", +"calm", +"grin", +"gun", +"heavy", +"hill", +"large", +"ocean", +"shoe", +"sigh", +"straight", +"summer", +"tongue", +"accept", +"crazy", +"everyday", +"exist", +"grass", +"mistake", +"sent", +"shut", +"surround", +"table", +"ache", +"brain", +"destroy", +"heal", +"nature", +"shout", +"sign", +"stain", +"choice", +"doubt", +"glance", +"glow", +"mountain", +"queen", +"stranger", +"throat", +"tomorrow", +"city", +"either", +"fish", +"flame", +"rather", +"shape", +"spin", +"spread", +"ash", +"distance", +"finish", +"image", +"imagine", +"important", +"nobody", +"shatter", +"warmth", +"became", +"feed", +"flesh", +"funny", +"lust", +"shirt", +"trouble", +"yellow", +"attention", +"bare", +"bite", +"money", +"protect", +"amaze", +"appear", +"born", +"choke", +"completely", +"daughter", +"fresh", +"friendship", +"gentle", +"probably", +"six", +"deserve", +"expect", +"grab", +"middle", +"nightmare", +"river", +"thousand", +"weight", +"worst", +"wound", +"barely", +"bottle", +"cream", +"regret", +"relationship", +"stick", +"test", +"crush", +"endless", +"fault", +"itself", +"rule", +"spill", +"art", +"circle", +"join", +"kick", +"mask", +"master", +"passion", +"quick", +"raise", +"smooth", +"unless", +"wander", +"actually", +"broke", +"chair", +"deal", +"favorite", +"gift", +"note", +"number", +"sweat", +"box", +"chill", +"clothes", +"lady", +"mark", +"park", +"poor", +"sadness", +"tie", +"animal", +"belong", +"brush", +"consume", +"dawn", +"forest", +"innocent", +"pen", +"pride", +"stream", +"thick", +"clay", +"complete", +"count", +"draw", +"faith", +"press", +"silver", +"struggle", +"surface", +"taught", +"teach", +"wet", +"bless", +"chase", +"climb", +"enter", +"letter", +"melt", +"metal", +"movie", +"stretch", +"swing", +"vision", +"wife", +"beside", +"crash", +"forgot", +"guide", +"haunt", +"joke", +"knock", +"plant", +"pour", +"prove", +"reveal", +"steal", +"stuff", +"trip", +"wood", +"wrist", +"bother", +"bottom", +"crawl", +"crowd", +"fix", +"forgive", +"frown", +"grace", +"loose", +"lucky", +"party", +"release", +"surely", +"survive", +"teacher", +"gently", +"grip", +"speed", +"suicide", +"travel", +"treat", +"vein", +"written", +"cage", +"chain", +"conversation", +"date", +"enemy", +"however", +"interest", +"million", +"page", +"pink", +"proud", +"sway", +"themselves", +"winter", +"church", +"cruel", +"cup", +"demon", +"experience", +"freedom", +"pair", +"pop", +"purpose", +"respect", +"shoot", +"softly", +"state", +"strange", +"bar", +"birth", +"curl", +"dirt", +"excuse", +"lord", +"lovely", +"monster", +"order", +"pack", +"pants", +"pool", +"scene", +"seven", +"shame", +"slide", +"ugly", +"among", +"blade", +"blonde", +"closet", +"creek", +"deny", +"drug", +"eternity", +"gain", +"grade", +"handle", +"key", +"linger", +"pale", +"prepare", +"swallow", +"swim", +"tremble", +"wheel", +"won", +"cast", +"cigarette", +"claim", +"college", +"direction", +"dirty", +"gather", +"ghost", +"hundred", +"loss", +"lung", +"orange", +"present", +"swear", +"swirl", +"twice", +"wild", +"bitter", +"blanket", +"doctor", +"everywhere", +"flash", +"grown", +"knowledge", +"numb", +"pressure", +"radio", +"repeat", +"ruin", +"spend", +"unknown", +"buy", +"clock", +"devil", +"early", +"false", +"fantasy", +"pound", +"precious", +"refuse", +"sheet", +"teeth", +"welcome", +"add", +"ahead", +"block", +"bury", +"caress", +"content", +"depth", +"despite", +"distant", +"marry", +"purple", +"threw", +"whenever", +"bomb", +"dull", +"easily", +"grasp", +"hospital", +"innocence", +"normal", +"receive", +"reply", +"rhyme", +"shade", +"someday", +"sword", +"toe", +"visit", +"asleep", +"bought", +"center", +"consider", +"flat", +"hero", +"history", +"ink", +"insane", +"muscle", +"mystery", +"pocket", +"reflection", +"shove", +"silently", +"smart", +"soldier", +"spot", +"stress", +"train", +"type", +"view", +"whether", +"bus", +"energy", +"explain", +"holy", +"hunger", +"inch", +"magic", +"mix", +"noise", +"nowhere", +"prayer", +"presence", +"shock", +"snap", +"spider", +"study", +"thunder", +"trail", +"admit", +"agree", +"bag", +"bang", +"bound", +"butterfly", +"cute", +"exactly", +"explode", +"familiar", +"fold", +"further", +"pierce", +"reflect", +"scent", +"selfish", +"sharp", +"sink", +"spring", +"stumble", +"universe", +"weep", +"women", +"wonderful", +"action", +"ancient", +"attempt", +"avoid", +"birthday", +"branch", +"chocolate", +"core", +"depress", +"drunk", +"especially", +"focus", +"fruit", +"honest", +"match", +"palm", +"perfectly", +"pillow", +"pity", +"poison", +"roar", +"shift", +"slightly", +"thump", +"truck", +"tune", +"twenty", +"unable", +"wipe", +"wrote", +"coat", +"constant", +"dinner", +"drove", +"egg", +"eternal", +"flight", +"flood", +"frame", +"freak", +"gasp", +"glad", +"hollow", +"motion", +"peer", +"plastic", +"root", +"screen", +"season", +"sting", +"strike", +"team", +"unlike", +"victim", +"volume", +"warn", +"weird", +"attack", +"await", +"awake", +"built", +"charm", +"crave", +"despair", +"fought", +"grant", +"grief", +"horse", +"limit", +"message", +"ripple", +"sanity", +"scatter", +"serve", +"split", +"string", +"trick", +"annoy", +"blur", +"boat", +"brave", +"clearly", +"cling", +"connect", +"fist", +"forth", +"imagination", +"iron", +"jock", +"judge", +"lesson", +"milk", +"misery", +"nail", +"naked", +"ourselves", +"poet", +"possible", +"princess", +"sail", +"size", +"snake", +"society", +"stroke", +"torture", +"toss", +"trace", +"wise", +"bloom", +"bullet", +"cell", +"check", +"cost", +"darling", +"during", +"footstep", +"fragile", +"hallway", +"hardly", +"horizon", +"invisible", +"journey", +"midnight", +"mud", +"nod", +"pause", +"relax", +"shiver", +"sudden", +"value", +"youth", +"abuse", +"admire", +"blink", +"breast", +"bruise", +"constantly", +"couple", +"creep", +"curve", +"difference", +"dumb", +"emptiness", +"gotta", +"honor", +"plain", +"planet", +"recall", +"rub", +"ship", +"slam", +"soar", +"somebody", +"tightly", +"weather", +"adore", +"approach", +"bond", +"bread", +"burst", +"candle", +"coffee", +"cousin", +"crime", +"desert", +"flutter", +"frozen", +"grand", +"heel", +"hello", +"language", +"level", +"movement", +"pleasure", +"powerful", +"random", +"rhythm", +"settle", +"silly", +"slap", +"sort", +"spoken", +"steel", +"threaten", +"tumble", +"upset", +"aside", +"awkward", +"bee", +"blank", +"board", +"button", +"card", +"carefully", +"complain", +"crap", +"deeply", +"discover", +"drag", +"dread", +"effort", +"entire", +"fairy", +"giant", +"gotten", +"greet", +"illusion", +"jeans", +"leap", +"liquid", +"march", +"mend", +"nervous", +"nine", +"replace", +"rope", +"spine", +"stole", +"terror", +"accident", +"apple", +"balance", +"boom", +"childhood", +"collect", +"demand", +"depression", +"eventually", +"faint", +"glare", +"goal", +"group", +"honey", +"kitchen", +"laid", +"limb", +"machine", +"mere", +"mold", +"murder", +"nerve", +"painful", +"poetry", +"prince", +"rabbit", +"shelter", +"shore", +"shower", +"soothe", +"stair", +"steady", +"sunlight", +"tangle", +"tease", +"treasure", +"uncle", +"begun", +"bliss", +"canvas", +"cheer", +"claw", +"clutch", +"commit", +"crimson", +"crystal", +"delight", +"doll", +"existence", +"express", +"fog", +"football", +"gay", +"goose", +"guard", +"hatred", +"illuminate", +"mass", +"math", +"mourn", +"rich", +"rough", +"skip", +"stir", +"student", +"style", +"support", +"thorn", +"tough", +"yard", +"yearn", +"yesterday", +"advice", +"appreciate", +"autumn", +"bank", +"beam", +"bowl", +"capture", +"carve", +"collapse", +"confusion", +"creation", +"dove", +"feather", +"girlfriend", +"glory", +"government", +"harsh", +"hop", +"inner", +"loser", +"moonlight", +"neighbor", +"neither", +"peach", +"pig", +"praise", +"screw", +"shield", +"shimmer", +"sneak", +"stab", +"subject", +"throughout", +"thrown", +"tower", +"twirl", +"wow", +"army", +"arrive", +"bathroom", +"bump", +"cease", +"cookie", +"couch", +"courage", +"dim", +"guilt", +"howl", +"hum", +"husband", +"insult", +"led", +"lunch", +"mock", +"mostly", +"natural", +"nearly", +"needle", +"nerd", +"peaceful", +"perfection", +"pile", +"price", +"remove", +"roam", +"sanctuary", +"serious", +"shiny", +"shook", +"sob", +"stolen", +"tap", +"vain", +"void", +"warrior", +"wrinkle", +"affection", +"apologize", +"blossom", +"bounce", +"bridge", +"cheap", +"crumble", +"decision", +"descend", +"desperately", +"dig", +"dot", +"flip", +"frighten", +"heartbeat", +"huge", +"lazy", +"lick", +"odd", +"opinion", +"process", +"puzzle", +"quietly", +"retreat", +"score", +"sentence", +"separate", +"situation", +"skill", +"soak", +"square", +"stray", +"taint", +"task", +"tide", +"underneath", +"veil", +"whistle", +"anywhere", +"bedroom", +"bid", +"bloody", +"burden", +"careful", +"compare", +"concern", +"curtain", +"decay", +"defeat", +"describe", +"double", +"dreamer", +"driver", +"dwell", +"evening", +"flare", +"flicker", +"grandma", +"guitar", +"harm", +"horrible", +"hungry", +"indeed", +"lace", +"melody", +"monkey", +"nation", +"object", +"obviously", +"rainbow", +"salt", +"scratch", +"shown", +"shy", +"stage", +"stun", +"third", +"tickle", +"useless", +"weakness", +"worship", +"worthless", +"afternoon", +"beard", +"boyfriend", +"bubble", +"busy", +"certain", +"chin", +"concrete", +"desk", +"diamond", +"doom", +"drawn", +"due", +"felicity", +"freeze", +"frost", +"garden", +"glide", +"harmony", +"hopefully", +"hunt", +"jealous", +"lightning", +"mama", +"mercy", +"peel", +"physical", +"position", +"pulse", +"punch", +"quit", +"rant", +"respond", +"salty", +"sane", +"satisfy", +"savior", +"sheep", +"slept", +"social", +"sport", +"tuck", +"utter", +"valley", +"wolf", +"aim", +"alas", +"alter", +"arrow", +"awaken", +"beaten", +"belief", +"brand", +"ceiling", +"cheese", +"clue", +"confidence", +"connection", +"daily", +"disguise", +"eager", +"erase", +"essence", +"everytime", +"expression", +"fan", +"flag", +"flirt", +"foul", +"fur", +"giggle", +"glorious", +"ignorance", +"law", +"lifeless", +"measure", +"mighty", +"muse", +"north", +"opposite", +"paradise", +"patience", +"patient", +"pencil", +"petal", +"plate", +"ponder", +"possibly", +"practice", +"slice", +"spell", +"stock", +"strife", +"strip", +"suffocate", +"suit", +"tender", +"tool", +"trade", +"velvet", +"verse", +"waist", +"witch", +"aunt", +"bench", +"bold", +"cap", +"certainly", +"click", +"companion", +"creator", +"dart", +"delicate", +"determine", +"dish", +"dragon", +"drama", +"drum", +"dude", +"everybody", +"feast", +"forehead", +"former", +"fright", +"fully", +"gas", +"hook", +"hurl", +"invite", +"juice", +"manage", +"moral", +"possess", +"raw", +"rebel", +"royal", +"scale", +"scary", +"several", +"slight", +"stubborn", +"swell", +"talent", +"tea", +"terrible", +"thread", +"torment", +"trickle", +"usually", +"vast", +"violence", +"weave", +"acid", +"agony", +"ashamed", +"awe", +"belly", +"blend", +"blush", +"character", +"cheat", +"common", +"company", +"coward", +"creak", +"danger", +"deadly", +"defense", +"define", +"depend", +"desperate", +"destination", +"dew", +"duck", +"dusty", +"embarrass", +"engine", +"example", +"explore", +"foe", +"freely", +"frustrate", +"generation", +"glove", +"guilty", +"health", +"hurry", +"idiot", +"impossible", +"inhale", +"jaw", +"kingdom", +"mention", +"mist", +"moan", +"mumble", +"mutter", +"observe", +"ode", +"pathetic", +"pattern", +"pie", +"prefer", +"puff", +"rape", +"rare", +"revenge", +"rude", +"scrape", +"spiral", +"squeeze", +"strain", +"sunset", +"suspend", +"sympathy", +"thigh", +"throne", +"total", +"unseen", +"weapon", +"weary" +] + + + +n = 1626 + +# Note about US patent no 5892470: Here each word does not represent a given digit. +# Instead, the digit represented by a word is variable, it depends on the previous word. + +def mn_encode( message ): + out = [] + for i in range(len(message)/8): + word = message[8*i:8*i+8] + x = int(word, 16) + w1 = (x%n) + w2 = ((x/n) + w1)%n + w3 = ((x/n/n) + w2)%n + out += [ words[w1], words[w2], words[w3] ] + return out + +def mn_decode( wlist ): + out = '' + for i in range(len(wlist)/3): + word1, word2, word3 = wlist[3*i:3*i+3] + w1 = words.index(word1) + w2 = (words.index(word2))%n + w3 = (words.index(word3))%n + x = w1 +n*((w2-w1)%n) +n*n*((w3-w2)%n) + out += '%08x'%x + return out + + +if __name__ == '__main__': + import sys + if len( sys.argv ) == 1: + print 'I need arguments: a hex string to encode, or a list of words to decode' + elif len( sys.argv ) == 2: + print ' '.join(mn_encode(sys.argv[1])) + else: + print mn_decode(sys.argv[1:]) diff --git a/msqr.py b/msqr.py new file mode 100644 index 0000000..da3c6fd --- /dev/null +++ b/msqr.py @@ -0,0 +1,94 @@ +# from http://eli.thegreenplace.net/2009/03/07/computing-modular-square-roots-in-python/ + +def modular_sqrt(a, p): + """ Find a quadratic residue (mod p) of 'a'. p + must be an odd prime. + + Solve the congruence of the form: + x^2 = a (mod p) + And returns x. Note that p - x is also a root. + + 0 is returned is no square root exists for + these a and p. + + The Tonelli-Shanks algorithm is used (except + for some simple cases in which the solution + is known from an identity). This algorithm + runs in polynomial time (unless the + generalized Riemann hypothesis is false). + """ + # Simple cases + # + if legendre_symbol(a, p) != 1: + return 0 + elif a == 0: + return 0 + elif p == 2: + return p + elif p % 4 == 3: + return pow(a, (p + 1) / 4, p) + + # Partition p-1 to s * 2^e for an odd s (i.e. + # reduce all the powers of 2 from p-1) + # + s = p - 1 + e = 0 + while s % 2 == 0: + s /= 2 + e += 1 + + # Find some 'n' with a legendre symbol n|p = -1. + # Shouldn't take long. + # + n = 2 + while legendre_symbol(n, p) != -1: + n += 1 + + # Here be dragons! + # Read the paper "Square roots from 1; 24, 51, + # 10 to Dan Shanks" by Ezra Brown for more + # information + # + + # x is a guess of the square root that gets better + # with each iteration. + # b is the "fudge factor" - by how much we're off + # with the guess. The invariant x^2 = ab (mod p) + # is maintained throughout the loop. + # g is used for successive powers of n to update + # both a and b + # r is the exponent - decreases with each update + # + x = pow(a, (s + 1) / 2, p) + b = pow(a, s, p) + g = pow(n, s, p) + r = e + + while True: + t = b + m = 0 + for m in xrange(r): + if t == 1: + break + t = pow(t, 2, p) + + if m == 0: + return x + + gs = pow(g, 2 ** (r - m - 1), p) + g = (gs * gs) % p + x = (x * gs) % p + b = (b * g) % p + r = m + +def legendre_symbol(a, p): + """ Compute the Legendre symbol a|p using + Euler's criterion. p is a prime, a is + relatively prime to p (if p divides + a, then a|p = 0) + + Returns 1 if a has a square root modulo + p, -1 otherwise. + """ + ls = pow(a, (p - 1) / 2, p) + return -1 if ls == p - 1 else ls diff --git a/peers b/peers new file mode 100755 index 0000000..0b5d1e0 --- /dev/null +++ b/peers @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import interface + +i = interface.TcpStratumInterface('ecdsa.org', 50001) +i.start() +i.send([('server.peers.subscribe',[])]) + +while True: + r = i.responses.get(True, 100000000000) + print r.get('result') diff --git a/pyqrnative.py b/pyqrnative.py new file mode 100644 index 0000000..7f9c750 --- /dev/null +++ b/pyqrnative.py @@ -0,0 +1,962 @@ +import math + +#from PIL import Image, ImageDraw + +#QRCode for Python +# +#Ported from the Javascript library by Sam Curren +# +#QRCode for Javascript +#http://d-project.googlecode.com/svn/trunk/misc/qrcode/js/qrcode.js +# +#Copyright (c) 2009 Kazuhiko Arase +# +#URL: http://www.d-project.com/ +# +#Licensed under the MIT license: +# http://www.opensource.org/licenses/mit-license.php +# +# The word "QR Code" is registered trademark of +# DENSO WAVE INCORPORATED +# http://www.denso-wave.com/qrcode/faqpatent-e.html + + +class QR8bitByte: + + def __init__(self, data): + self.mode = QRMode.MODE_8BIT_BYTE + self.data = data + + def getLength(self): + return len(self.data) + + def write(self, buffer): + for i in range(len(self.data)): + #// not JIS ... + buffer.put(ord(self.data[i]), 8) + def __repr__(self): + return self.data + +class QRCode: + def __init__(self, typeNumber, errorCorrectLevel): + self.typeNumber = typeNumber + self.errorCorrectLevel = errorCorrectLevel + self.modules = None + self.moduleCount = 0 + self.dataCache = None + self.dataList = [] + def addData(self, data): + newData = QR8bitByte(data) + self.dataList.append(newData) + self.dataCache = None + def isDark(self, row, col): + if (row < 0 or self.moduleCount <= row or col < 0 or self.moduleCount <= col): + raise Exception("%s,%s - %s" % (row, col, self.moduleCount)) + return self.modules[row][col] + def getModuleCount(self): + return self.moduleCount + def make(self): + self.makeImpl(False, self.getBestMaskPattern() ) + def makeImpl(self, test, maskPattern): + + self.moduleCount = self.typeNumber * 4 + 17 + self.modules = [None for x in range(self.moduleCount)] + + for row in range(self.moduleCount): + + self.modules[row] = [None for x in range(self.moduleCount)] + + for col in range(self.moduleCount): + self.modules[row][col] = None #//(col + row) % 3; + + self.setupPositionProbePattern(0, 0) + self.setupPositionProbePattern(self.moduleCount - 7, 0) + self.setupPositionProbePattern(0, self.moduleCount - 7) + self.setupPositionAdjustPattern() + self.setupTimingPattern() + self.setupTypeInfo(test, maskPattern) + + if (self.typeNumber >= 7): + self.setupTypeNumber(test) + + if (self.dataCache == None): + self.dataCache = QRCode.createData(self.typeNumber, self.errorCorrectLevel, self.dataList) + self.mapData(self.dataCache, maskPattern) + + def setupPositionProbePattern(self, row, col): + + for r in range(-1, 8): + + if (row + r <= -1 or self.moduleCount <= row + r): continue + + for c in range(-1, 8): + + if (col + c <= -1 or self.moduleCount <= col + c): continue + + if ( (0 <= r and r <= 6 and (c == 0 or c == 6) ) + or (0 <= c and c <= 6 and (r == 0 or r == 6) ) + or (2 <= r and r <= 4 and 2 <= c and c <= 4) ): + self.modules[row + r][col + c] = True; + else: + self.modules[row + r][col + c] = False; + + def getBestMaskPattern(self): + + minLostPoint = 0 + pattern = 0 + + for i in range(8): + + self.makeImpl(True, i); + + lostPoint = QRUtil.getLostPoint(self); + + if (i == 0 or minLostPoint > lostPoint): + minLostPoint = lostPoint + pattern = i + + return pattern + + + def setupTimingPattern(self): + + for r in range(8, self.moduleCount - 8): + if (self.modules[r][6] != None): + continue + self.modules[r][6] = (r % 2 == 0) + + for c in range(8, self.moduleCount - 8): + if (self.modules[6][c] != None): + continue + self.modules[6][c] = (c % 2 == 0) + + def setupPositionAdjustPattern(self): + + pos = QRUtil.getPatternPosition(self.typeNumber) + + for i in range(len(pos)): + + for j in range(len(pos)): + + row = pos[i] + col = pos[j] + + if (self.modules[row][col] != None): + continue + + for r in range(-2, 3): + + for c in range(-2, 3): + + if (r == -2 or r == 2 or c == -2 or c == 2 or (r == 0 and c == 0) ): + self.modules[row + r][col + c] = True + else: + self.modules[row + r][col + c] = False + + def setupTypeNumber(self, test): + + bits = QRUtil.getBCHTypeNumber(self.typeNumber) + + for i in range(18): + mod = (not test and ( (bits >> i) & 1) == 1) + self.modules[i // 3][i % 3 + self.moduleCount - 8 - 3] = mod; + + for i in range(18): + mod = (not test and ( (bits >> i) & 1) == 1) + self.modules[i % 3 + self.moduleCount - 8 - 3][i // 3] = mod; + + def setupTypeInfo(self, test, maskPattern): + + data = (self.errorCorrectLevel << 3) | maskPattern + bits = QRUtil.getBCHTypeInfo(data) + + #// vertical + for i in range(15): + + mod = (not test and ( (bits >> i) & 1) == 1) + + if (i < 6): + self.modules[i][8] = mod + elif (i < 8): + self.modules[i + 1][8] = mod + else: + self.modules[self.moduleCount - 15 + i][8] = mod + + #// horizontal + for i in range(15): + + mod = (not test and ( (bits >> i) & 1) == 1); + + if (i < 8): + self.modules[8][self.moduleCount - i - 1] = mod + elif (i < 9): + self.modules[8][15 - i - 1 + 1] = mod + else: + self.modules[8][15 - i - 1] = mod + + #// fixed module + self.modules[self.moduleCount - 8][8] = (not test) + + def mapData(self, data, maskPattern): + + inc = -1 + row = self.moduleCount - 1 + bitIndex = 7 + byteIndex = 0 + + for col in range(self.moduleCount - 1, 0, -2): + + if (col == 6): col-=1 + + while (True): + + for c in range(2): + + if (self.modules[row][col - c] == None): + + dark = False + + if (byteIndex < len(data)): + dark = ( ( (data[byteIndex] >> bitIndex) & 1) == 1) + + mask = QRUtil.getMask(maskPattern, row, col - c) + + if (mask): + dark = not dark + + self.modules[row][col - c] = dark + bitIndex-=1 + + if (bitIndex == -1): + byteIndex+=1 + bitIndex = 7 + + row += inc + + if (row < 0 or self.moduleCount <= row): + row -= inc + inc = -inc + break + PAD0 = 0xEC + PAD1 = 0x11 + + @staticmethod + def createData(typeNumber, errorCorrectLevel, dataList): + + rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel) + + buffer = QRBitBuffer(); + + for i in range(len(dataList)): + data = dataList[i] + buffer.put(data.mode, 4) + buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber) ) + data.write(buffer) + + #// calc num max data. + totalDataCount = 0; + for i in range(len(rsBlocks)): + totalDataCount += rsBlocks[i].dataCount + + if (buffer.getLengthInBits() > totalDataCount * 8): + raise Exception("code length overflow. (" + + buffer.getLengthInBits() + + ">" + + totalDataCount * 8 + + ")") + + #// end code + if (buffer.getLengthInBits() + 4 <= totalDataCount * 8): + buffer.put(0, 4) + + #// padding + while (buffer.getLengthInBits() % 8 != 0): + buffer.putBit(False) + + #// padding + while (True): + + if (buffer.getLengthInBits() >= totalDataCount * 8): + break + buffer.put(QRCode.PAD0, 8) + + if (buffer.getLengthInBits() >= totalDataCount * 8): + break + buffer.put(QRCode.PAD1, 8) + + return QRCode.createBytes(buffer, rsBlocks) + + @staticmethod + def createBytes(buffer, rsBlocks): + + offset = 0 + + maxDcCount = 0 + maxEcCount = 0 + + dcdata = [0 for x in range(len(rsBlocks))] + ecdata = [0 for x in range(len(rsBlocks))] + + for r in range(len(rsBlocks)): + + dcCount = rsBlocks[r].dataCount + ecCount = rsBlocks[r].totalCount - dcCount + + maxDcCount = max(maxDcCount, dcCount) + maxEcCount = max(maxEcCount, ecCount) + + dcdata[r] = [0 for x in range(dcCount)] + + for i in range(len(dcdata[r])): + dcdata[r][i] = 0xff & buffer.buffer[i + offset] + offset += dcCount + + rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount) + rawPoly = QRPolynomial(dcdata[r], rsPoly.getLength() - 1) + + modPoly = rawPoly.mod(rsPoly) + ecdata[r] = [0 for x in range(rsPoly.getLength()-1)] + for i in range(len(ecdata[r])): + modIndex = i + modPoly.getLength() - len(ecdata[r]) + if (modIndex >= 0): + ecdata[r][i] = modPoly.get(modIndex) + else: + ecdata[r][i] = 0 + + totalCodeCount = 0 + for i in range(len(rsBlocks)): + totalCodeCount += rsBlocks[i].totalCount + + data = [None for x in range(totalCodeCount)] + index = 0 + + for i in range(maxDcCount): + for r in range(len(rsBlocks)): + if (i < len(dcdata[r])): + data[index] = dcdata[r][i] + index+=1 + + for i in range(maxEcCount): + for r in range(len(rsBlocks)): + if (i < len(ecdata[r])): + data[index] = ecdata[r][i] + index+=1 + + return data + + +class QRMode: + MODE_NUMBER = 1 << 0 + MODE_ALPHA_NUM = 1 << 1 + MODE_8BIT_BYTE = 1 << 2 + MODE_KANJI = 1 << 3 + +class QRErrorCorrectLevel: + L = 1 + M = 0 + Q = 3 + H = 2 + +class QRMaskPattern: + PATTERN000 = 0 + PATTERN001 = 1 + PATTERN010 = 2 + PATTERN011 = 3 + PATTERN100 = 4 + PATTERN101 = 5 + PATTERN110 = 6 + PATTERN111 = 7 + +class QRUtil(object): + PATTERN_POSITION_TABLE = [ + [], + [6, 18], + [6, 22], + [6, 26], + [6, 30], + [6, 34], + [6, 22, 38], + [6, 24, 42], + [6, 26, 46], + [6, 28, 50], + [6, 30, 54], + [6, 32, 58], + [6, 34, 62], + [6, 26, 46, 66], + [6, 26, 48, 70], + [6, 26, 50, 74], + [6, 30, 54, 78], + [6, 30, 56, 82], + [6, 30, 58, 86], + [6, 34, 62, 90], + [6, 28, 50, 72, 94], + [6, 26, 50, 74, 98], + [6, 30, 54, 78, 102], + [6, 28, 54, 80, 106], + [6, 32, 58, 84, 110], + [6, 30, 58, 86, 114], + [6, 34, 62, 90, 118], + [6, 26, 50, 74, 98, 122], + [6, 30, 54, 78, 102, 126], + [6, 26, 52, 78, 104, 130], + [6, 30, 56, 82, 108, 134], + [6, 34, 60, 86, 112, 138], + [6, 30, 58, 86, 114, 142], + [6, 34, 62, 90, 118, 146], + [6, 30, 54, 78, 102, 126, 150], + [6, 24, 50, 76, 102, 128, 154], + [6, 28, 54, 80, 106, 132, 158], + [6, 32, 58, 84, 110, 136, 162], + [6, 26, 54, 82, 110, 138, 166], + [6, 30, 58, 86, 114, 142, 170] + ] + + G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0) + G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0) + G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) + + @staticmethod + def getBCHTypeInfo(data): + d = data << 10; + while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0): + d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) ) + + return ( (data << 10) | d) ^ QRUtil.G15_MASK + @staticmethod + def getBCHTypeNumber(data): + d = data << 12; + while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0): + d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) ) + return (data << 12) | d + @staticmethod + def getBCHDigit(data): + digit = 0; + while (data != 0): + digit += 1 + data >>= 1 + return digit + @staticmethod + def getPatternPosition(typeNumber): + return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1] + @staticmethod + def getMask(maskPattern, i, j): + if maskPattern == QRMaskPattern.PATTERN000 : return (i + j) % 2 == 0 + if maskPattern == QRMaskPattern.PATTERN001 : return i % 2 == 0 + if maskPattern == QRMaskPattern.PATTERN010 : return j % 3 == 0 + if maskPattern == QRMaskPattern.PATTERN011 : return (i + j) % 3 == 0 + if maskPattern == QRMaskPattern.PATTERN100 : return (math.floor(i / 2) + math.floor(j / 3) ) % 2 == 0 + if maskPattern == QRMaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 == 0 + if maskPattern == QRMaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 == 0 + if maskPattern == QRMaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 == 0 + raise Exception("bad maskPattern:" + maskPattern); + @staticmethod + def getErrorCorrectPolynomial(errorCorrectLength): + a = QRPolynomial([1], 0); + for i in range(errorCorrectLength): + a = a.multiply(QRPolynomial([1, QRMath.gexp(i)], 0) ) + return a + @staticmethod + def getLengthInBits(mode, type): + + if 1 <= type and type < 10: + + #// 1 - 9 + + if mode == QRMode.MODE_NUMBER : return 10 + if mode == QRMode.MODE_ALPHA_NUM : return 9 + if mode == QRMode.MODE_8BIT_BYTE : return 8 + if mode == QRMode.MODE_KANJI : return 8 + raise Exception("mode:" + mode) + + elif (type < 27): + + #// 10 - 26 + + if mode == QRMode.MODE_NUMBER : return 12 + if mode == QRMode.MODE_ALPHA_NUM : return 11 + if mode == QRMode.MODE_8BIT_BYTE : return 16 + if mode == QRMode.MODE_KANJI : return 10 + raise Exception("mode:" + mode) + + elif (type < 41): + + #// 27 - 40 + + if mode == QRMode.MODE_NUMBER : return 14 + if mode == QRMode.MODE_ALPHA_NUM : return 13 + if mode == QRMode.MODE_8BIT_BYTE : return 16 + if mode == QRMode.MODE_KANJI : return 12 + raise Exception("mode:" + mode) + + else: + raise Exception("type:" + type) + @staticmethod + def getLostPoint(qrCode): + + moduleCount = qrCode.getModuleCount(); + + lostPoint = 0; + + #// LEVEL1 + + for row in range(moduleCount): + + for col in range(moduleCount): + + sameCount = 0; + dark = qrCode.isDark(row, col); + + for r in range(-1, 2): + + if (row + r < 0 or moduleCount <= row + r): + continue + + for c in range(-1, 2): + + if (col + c < 0 or moduleCount <= col + c): + continue + if (r == 0 and c == 0): + continue + + if (dark == qrCode.isDark(row + r, col + c) ): + sameCount+=1 + if (sameCount > 5): + lostPoint += (3 + sameCount - 5) + + #// LEVEL2 + + for row in range(moduleCount - 1): + for col in range(moduleCount - 1): + count = 0; + if (qrCode.isDark(row, col ) ): count+=1 + if (qrCode.isDark(row + 1, col ) ): count+=1 + if (qrCode.isDark(row, col + 1) ): count+=1 + if (qrCode.isDark(row + 1, col + 1) ): count+=1 + if (count == 0 or count == 4): + lostPoint += 3 + + #// LEVEL3 + + for row in range(moduleCount): + for col in range(moduleCount - 6): + if (qrCode.isDark(row, col) + and not qrCode.isDark(row, col + 1) + and qrCode.isDark(row, col + 2) + and qrCode.isDark(row, col + 3) + and qrCode.isDark(row, col + 4) + and not qrCode.isDark(row, col + 5) + and qrCode.isDark(row, col + 6) ): + lostPoint += 40 + + for col in range(moduleCount): + for row in range(moduleCount - 6): + if (qrCode.isDark(row, col) + and not qrCode.isDark(row + 1, col) + and qrCode.isDark(row + 2, col) + and qrCode.isDark(row + 3, col) + and qrCode.isDark(row + 4, col) + and not qrCode.isDark(row + 5, col) + and qrCode.isDark(row + 6, col) ): + lostPoint += 40 + + #// LEVEL4 + + darkCount = 0; + + for col in range(moduleCount): + for row in range(moduleCount): + if (qrCode.isDark(row, col) ): + darkCount+=1 + + ratio = abs(100 * darkCount / moduleCount / moduleCount - 50) / 5 + lostPoint += ratio * 10 + + return lostPoint + +class QRMath: + + @staticmethod + def glog(n): + if (n < 1): + raise Exception("glog(" + n + ")") + return LOG_TABLE[n]; + @staticmethod + def gexp(n): + while n < 0: + n += 255 + while n >= 256: + n -= 255 + return EXP_TABLE[n]; + +EXP_TABLE = [x for x in range(256)] + +LOG_TABLE = [x for x in range(256)] + +for i in range(8): + EXP_TABLE[i] = 1 << i; + +for i in range(8, 256): + EXP_TABLE[i] = EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8] + +for i in range(255): + LOG_TABLE[EXP_TABLE[i] ] = i + +class QRPolynomial: + + def __init__(self, num, shift): + + if (len(num) == 0): + raise Exception(num.length + "/" + shift) + + offset = 0 + + while offset < len(num) and num[offset] == 0: + offset += 1 + + self.num = [0 for x in range(len(num)-offset+shift)] + for i in range(len(num) - offset): + self.num[i] = num[i + offset] + + + def get(self, index): + return self.num[index] + def getLength(self): + return len(self.num) + def multiply(self, e): + num = [0 for x in range(self.getLength() + e.getLength() - 1)]; + + for i in range(self.getLength()): + for j in range(e.getLength()): + num[i + j] ^= QRMath.gexp(QRMath.glog(self.get(i) ) + QRMath.glog(e.get(j) ) ) + + return QRPolynomial(num, 0); + def mod(self, e): + + if (self.getLength() - e.getLength() < 0): + return self; + + ratio = QRMath.glog(self.get(0) ) - QRMath.glog(e.get(0) ) + + num = [0 for x in range(self.getLength())] + + for i in range(self.getLength()): + num[i] = self.get(i); + + for i in range(e.getLength()): + num[i] ^= QRMath.gexp(QRMath.glog(e.get(i) ) + ratio) + + # recursive call + return QRPolynomial(num, 0).mod(e); + +class QRRSBlock: + + RS_BLOCK_TABLE = [ + + #// L + #// M + #// Q + #// H + + #// 1 + [1, 26, 19], + [1, 26, 16], + [1, 26, 13], + [1, 26, 9], + + #// 2 + [1, 44, 34], + [1, 44, 28], + [1, 44, 22], + [1, 44, 16], + + #// 3 + [1, 70, 55], + [1, 70, 44], + [2, 35, 17], + [2, 35, 13], + + #// 4 + [1, 100, 80], + [2, 50, 32], + [2, 50, 24], + [4, 25, 9], + + #// 5 + [1, 134, 108], + [2, 67, 43], + [2, 33, 15, 2, 34, 16], + [2, 33, 11, 2, 34, 12], + + #// 6 + [2, 86, 68], + [4, 43, 27], + [4, 43, 19], + [4, 43, 15], + + #// 7 + [2, 98, 78], + [4, 49, 31], + [2, 32, 14, 4, 33, 15], + [4, 39, 13, 1, 40, 14], + + #// 8 + [2, 121, 97], + [2, 60, 38, 2, 61, 39], + [4, 40, 18, 2, 41, 19], + [4, 40, 14, 2, 41, 15], + + #// 9 + [2, 146, 116], + [3, 58, 36, 2, 59, 37], + [4, 36, 16, 4, 37, 17], + [4, 36, 12, 4, 37, 13], + + #// 10 + [2, 86, 68, 2, 87, 69], + [4, 69, 43, 1, 70, 44], + [6, 43, 19, 2, 44, 20], + [6, 43, 15, 2, 44, 16], + + # 11 + [4, 101, 81], + [1, 80, 50, 4, 81, 51], + [4, 50, 22, 4, 51, 23], + [3, 36, 12, 8, 37, 13], + + # 12 + [2, 116, 92, 2, 117, 93], + [6, 58, 36, 2, 59, 37], + [4, 46, 20, 6, 47, 21], + [7, 42, 14, 4, 43, 15], + + # 13 + [4, 133, 107], + [8, 59, 37, 1, 60, 38], + [8, 44, 20, 4, 45, 21], + [12, 33, 11, 4, 34, 12], + + # 14 + [3, 145, 115, 1, 146, 116], + [4, 64, 40, 5, 65, 41], + [11, 36, 16, 5, 37, 17], + [11, 36, 12, 5, 37, 13], + + # 15 + [5, 109, 87, 1, 110, 88], + [5, 65, 41, 5, 66, 42], + [5, 54, 24, 7, 55, 25], + [11, 36, 12], + + # 16 + [5, 122, 98, 1, 123, 99], + [7, 73, 45, 3, 74, 46], + [15, 43, 19, 2, 44, 20], + [3, 45, 15, 13, 46, 16], + + # 17 + [1, 135, 107, 5, 136, 108], + [10, 74, 46, 1, 75, 47], + [1, 50, 22, 15, 51, 23], + [2, 42, 14, 17, 43, 15], + + # 18 + [5, 150, 120, 1, 151, 121], + [9, 69, 43, 4, 70, 44], + [17, 50, 22, 1, 51, 23], + [2, 42, 14, 19, 43, 15], + + # 19 + [3, 141, 113, 4, 142, 114], + [3, 70, 44, 11, 71, 45], + [17, 47, 21, 4, 48, 22], + [9, 39, 13, 16, 40, 14], + + # 20 + [3, 135, 107, 5, 136, 108], + [3, 67, 41, 13, 68, 42], + [15, 54, 24, 5, 55, 25], + [15, 43, 15, 10, 44, 16], + + # 21 + [4, 144, 116, 4, 145, 117], + [17, 68, 42], + [17, 50, 22, 6, 51, 23], + [19, 46, 16, 6, 47, 17], + + # 22 + [2, 139, 111, 7, 140, 112], + [17, 74, 46], + [7, 54, 24, 16, 55, 25], + [34, 37, 13], + + # 23 + [4, 151, 121, 5, 152, 122], + [4, 75, 47, 14, 76, 48], + [11, 54, 24, 14, 55, 25], + [16, 45, 15, 14, 46, 16], + + # 24 + [6, 147, 117, 4, 148, 118], + [6, 73, 45, 14, 74, 46], + [11, 54, 24, 16, 55, 25], + [30, 46, 16, 2, 47, 17], + + # 25 + [8, 132, 106, 4, 133, 107], + [8, 75, 47, 13, 76, 48], + [7, 54, 24, 22, 55, 25], + [22, 45, 15, 13, 46, 16], + + # 26 + [10, 142, 114, 2, 143, 115], + [19, 74, 46, 4, 75, 47], + [28, 50, 22, 6, 51, 23], + [33, 46, 16, 4, 47, 17], + + # 27 + [8, 152, 122, 4, 153, 123], + [22, 73, 45, 3, 74, 46], + [8, 53, 23, 26, 54, 24], + [12, 45, 15, 28, 46, 16], + + # 28 + [3, 147, 117, 10, 148, 118], + [3, 73, 45, 23, 74, 46], + [4, 54, 24, 31, 55, 25], + [11, 45, 15, 31, 46, 16], + + # 29 + [7, 146, 116, 7, 147, 117], + [21, 73, 45, 7, 74, 46], + [1, 53, 23, 37, 54, 24], + [19, 45, 15, 26, 46, 16], + + # 30 + [5, 145, 115, 10, 146, 116], + [19, 75, 47, 10, 76, 48], + [15, 54, 24, 25, 55, 25], + [23, 45, 15, 25, 46, 16], + + # 31 + [13, 145, 115, 3, 146, 116], + [2, 74, 46, 29, 75, 47], + [42, 54, 24, 1, 55, 25], + [23, 45, 15, 28, 46, 16], + + # 32 + [17, 145, 115], + [10, 74, 46, 23, 75, 47], + [10, 54, 24, 35, 55, 25], + [19, 45, 15, 35, 46, 16], + + # 33 + [17, 145, 115, 1, 146, 116], + [14, 74, 46, 21, 75, 47], + [29, 54, 24, 19, 55, 25], + [11, 45, 15, 46, 46, 16], + + # 34 + [13, 145, 115, 6, 146, 116], + [14, 74, 46, 23, 75, 47], + [44, 54, 24, 7, 55, 25], + [59, 46, 16, 1, 47, 17], + + # 35 + [12, 151, 121, 7, 152, 122], + [12, 75, 47, 26, 76, 48], + [39, 54, 24, 14, 55, 25], + [22, 45, 15, 41, 46, 16], + + # 36 + [6, 151, 121, 14, 152, 122], + [6, 75, 47, 34, 76, 48], + [46, 54, 24, 10, 55, 25], + [2, 45, 15, 64, 46, 16], + + # 37 + [17, 152, 122, 4, 153, 123], + [29, 74, 46, 14, 75, 47], + [49, 54, 24, 10, 55, 25], + [24, 45, 15, 46, 46, 16], + + # 38 + [4, 152, 122, 18, 153, 123], + [13, 74, 46, 32, 75, 47], + [48, 54, 24, 14, 55, 25], + [42, 45, 15, 32, 46, 16], + + # 39 + [20, 147, 117, 4, 148, 118], + [40, 75, 47, 7, 76, 48], + [43, 54, 24, 22, 55, 25], + [10, 45, 15, 67, 46, 16], + + # 40 + [19, 148, 118, 6, 149, 119], + [18, 75, 47, 31, 76, 48], + [34, 54, 24, 34, 55, 25], + [20, 45, 15, 61, 46, 16] + + ] + + def __init__(self, totalCount, dataCount): + self.totalCount = totalCount + self.dataCount = dataCount + + @staticmethod + def getRSBlocks(typeNumber, errorCorrectLevel): + rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel); + if rsBlock == None: + raise Exception("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + errorCorrectLevel) + + length = len(rsBlock) / 3 + + list = [] + + for i in range(length): + + count = rsBlock[i * 3 + 0] + totalCount = rsBlock[i * 3 + 1] + dataCount = rsBlock[i * 3 + 2] + + for j in range(count): + list.append(QRRSBlock(totalCount, dataCount)) + + return list; + + @staticmethod + def getRsBlockTable(typeNumber, errorCorrectLevel): + if errorCorrectLevel == QRErrorCorrectLevel.L: + return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]; + elif errorCorrectLevel == QRErrorCorrectLevel.M: + return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]; + elif errorCorrectLevel == QRErrorCorrectLevel.Q: + return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]; + elif errorCorrectLevel == QRErrorCorrectLevel.H: + return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]; + else: + return None; + +class QRBitBuffer: + def __init__(self): + self.buffer = [] + self.length = 0 + def __repr__(self): + return ".".join([str(n) for n in self.buffer]) + def get(self, index): + bufIndex = math.floor(index / 8) + val = ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 + print "get ", val + return ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 + def put(self, num, length): + for i in range(length): + self.putBit( ( (num >> (length - i - 1) ) & 1) == 1) + def getLengthInBits(self): + return self.length + def putBit(self, bit): + bufIndex = self.length // 8 + if len(self.buffer) <= bufIndex: + self.buffer.append(0) + if bit: + self.buffer[bufIndex] |= (0x80 >> (self.length % 8) ) + self.length+=1 diff --git a/remote.php b/remote.php new file mode 100644 index 0000000..8ad2319 --- /dev/null +++ b/remote.php @@ -0,0 +1,24 @@ +\n"; +echo "This page demonstrates the generation of new addresses by a neutralized Electrum wallet.\n\n"; +echo "A neutralized wallet does not contain the seed that allows to generate private keys.\nIt contains a master public key that allows to create new addresses.\n\n"; +echo "An attacker getting access to the neutralized wallet cannot steal the bitcoins.\n"; +echo "The full wallet (with seed) is not stored on the webserver.\n\n"; +echo "

"; + +if($_POST['submit']) { + $daemon = new jsonRPCClient('http://foo:bar@ecdsa.org:8444/'); + try{ + $r = $daemon->getnewaddress(); + if($r) { + echo '
'; + echo "bitcoin:$r\n\n"; + } + } catch(Exception $e) { + echo "error: cannot reach wallet daemon"; + } +} +echo ""; +?> diff --git a/remote_wallet.py b/remote_wallet.py new file mode 100644 index 0000000..be87df8 --- /dev/null +++ b/remote_wallet.py @@ -0,0 +1,127 @@ +#!/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 . + +import time, thread, sys, socket + +# see http://code.google.com/p/jsonrpclib/ +import jsonrpclib +from wallet import Wallet + +""" +Simple wallet daemon for webservers. +- generates new addresses on request +- private keys are not needed in order to generate new addresses. A neutralized wallet can be used (seed removed) +- no gap limit: use 'getnum' to know how many addresses have been created. + +todo: +- return the max gap +- add expiration date + +""" + + +host = 'ecdsa.org' +port = 8444 +wallet_path = 'wallet_path' +username = 'foo' +password = 'bar' +wallet = Wallet() +stopping = False + + + +from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCRequestHandler +import SimpleXMLRPCServer + +class authHandler(SimpleJSONRPCRequestHandler): + def parse_request(self): + if SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.parse_request(self): + if self.authenticate(self.headers): + return True + else: + self.send_error(401, 'Authentication failed') + return False + + def authenticate(self, headers): + from base64 import b64decode + basic, _, encoded = headers.get('Authorization').partition(' ') + assert basic == 'Basic', 'Only basic authentication supported' + x_username, _, x_password = b64decode(encoded).partition(':') + return username == x_username and password == x_password + + +def do_stop(): + global stopping + stopping = True + +def get_new_address(): + a = wallet.create_new_address(False) + wallet.save() + return a + +def get_num(): + return len(wallet.addresses) + +def get_mpk(): + return wallet.master_public_key.encode('hex') + + + +if __name__ == '__main__': + + if len(sys.argv)>1: + import jsonrpclib + server = jsonrpclib.Server('http://%s:%s@%s:%d'%(username, password, host, port)) + cmd = sys.argv[1] + + try: + if cmd == 'getnum': + out = server.getnum() + elif cmd == 'getkey': + out = server.getkey() + elif cmd == 'getnewaddress': + out = server.getnewaddress() + elif cmd == 'stop': + out = server.stop() + except socket.error: + print "server not running" + sys.exit(1) + print out + sys.exit(0) + + else: + + wallet.set_path(wallet_path) + wallet.read() + + def server_thread(): + from SocketServer import ThreadingMixIn + from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer + server = SimpleJSONRPCServer(( host, port), requestHandler=authHandler) + server.register_function(get_new_address, 'getnewaddress') + server.register_function(get_num, 'getnum') + server.register_function(get_mpk, 'getkey') + server.register_function(do_stop, 'stop') + server.serve_forever() + + thread.start_new_thread(server_thread, ()) + while not stopping: time.sleep(0.1) + + + + diff --git a/ripemd.py b/ripemd.py new file mode 100644 index 0000000..a9d652c --- /dev/null +++ b/ripemd.py @@ -0,0 +1,399 @@ +## ripemd.py - pure Python implementation of the RIPEMD-160 algorithm. +## Bjorn Edstrom 16 december 2007. +## +## Copyrights +## ========== +## +## This code is a derived from an implementation by Markus Friedl which is +## subject to the following license. This Python implementation is not +## subject to any other license. +## +##/* +## * Copyright (c) 2001 Markus Friedl. All rights reserved. +## * +## * Redistribution and use in source and binary forms, with or without +## * modification, are permitted provided that the following conditions +## * are met: +## * 1. Redistributions of source code must retain the above copyright +## * notice, this list of conditions and the following disclaimer. +## * 2. Redistributions in binary form must reproduce the above copyright +## * notice, this list of conditions and the following disclaimer in the +## * documentation and/or other materials provided with the distribution. +## * +## * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +## * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +## * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +## * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +## * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +## * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +## * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +## * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +## * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +## * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## */ +##/* +## * Preneel, Bosselaers, Dobbertin, "The Cryptographic Hash Function RIPEMD-160", +## * RSA Laboratories, CryptoBytes, Volume 3, Number 2, Autumn 1997, +## * ftp://ftp.rsasecurity.com/pub/cryptobytes/crypto3n2.pdf +## */ + +try: + import psyco + psyco.full() +except ImportError: + pass + +#block_size = 1 +digest_size = 20 +digestsize = 20 + +class RIPEMD160: + """Return a new RIPEMD160 object. An optional string argument + may be provided; if present, this string will be automatically + hashed.""" + + def __init__(self, arg=None): + self.ctx = RMDContext() + if arg: + self.update(arg) + self.dig = None + + def update(self, arg): + """update(arg)""" + RMD160Update(self.ctx, arg, len(arg)) + self.dig = None + + def digest(self): + """digest()""" + if self.dig: + return self.dig + ctx = self.ctx.copy() + self.dig = RMD160Final(self.ctx) + self.ctx = ctx + return self.dig + + def hexdigest(self): + """hexdigest()""" + dig = self.digest() + hex_digest = '' + for d in dig: + hex_digest += '%02x' % ord(d) + return hex_digest + + def copy(self): + """copy()""" + import copy + return copy.deepcopy(self) + + + +def new(arg=None): + """Return a new RIPEMD160 object. An optional string argument + may be provided; if present, this string will be automatically + hashed.""" + return RIPEMD160(arg) + + + +# +# Private. +# + +class RMDContext: + def __init__(self): + self.state = [0x67452301, 0xEFCDAB89, 0x98BADCFE, + 0x10325476, 0xC3D2E1F0] # uint32 + self.count = 0 # uint64 + self.buffer = [0]*64 # uchar + def copy(self): + ctx = RMDContext() + ctx.state = self.state[:] + ctx.count = self.count + ctx.buffer = self.buffer[:] + return ctx + +K0 = 0x00000000 +K1 = 0x5A827999 +K2 = 0x6ED9EBA1 +K3 = 0x8F1BBCDC +K4 = 0xA953FD4E + +KK0 = 0x50A28BE6 +KK1 = 0x5C4DD124 +KK2 = 0x6D703EF3 +KK3 = 0x7A6D76E9 +KK4 = 0x00000000 + +def ROL(n, x): + return ((x << n) & 0xffffffff) | (x >> (32 - n)) + +def F0(x, y, z): + return x ^ y ^ z + +def F1(x, y, z): + return (x & y) | (((~x) % 0x100000000) & z) + +def F2(x, y, z): + return (x | ((~y) % 0x100000000)) ^ z + +def F3(x, y, z): + return (x & z) | (((~z) % 0x100000000) & y) + +def F4(x, y, z): + return x ^ (y | ((~z) % 0x100000000)) + +def R(a, b, c, d, e, Fj, Kj, sj, rj, X): + a = ROL(sj, (a + Fj(b, c, d) + X[rj] + Kj) % 0x100000000) + e + c = ROL(10, c) + return a % 0x100000000, c + +PADDING = [0x80] + [0]*63 + +import sys +import struct + +def RMD160Transform(state, block): #uint32 state[5], uchar block[64] + x = [0]*16 + if sys.byteorder == 'little': + x = struct.unpack('<16L', ''.join([chr(x) for x in block[0:64]])) + else: + raise "Error!!" + a = state[0] + b = state[1] + c = state[2] + d = state[3] + e = state[4] + + #/* Round 1 */ + a, c = R(a, b, c, d, e, F0, K0, 11, 0, x); + e, b = R(e, a, b, c, d, F0, K0, 14, 1, x); + d, a = R(d, e, a, b, c, F0, K0, 15, 2, x); + c, e = R(c, d, e, a, b, F0, K0, 12, 3, x); + b, d = R(b, c, d, e, a, F0, K0, 5, 4, x); + a, c = R(a, b, c, d, e, F0, K0, 8, 5, x); + e, b = R(e, a, b, c, d, F0, K0, 7, 6, x); + d, a = R(d, e, a, b, c, F0, K0, 9, 7, x); + c, e = R(c, d, e, a, b, F0, K0, 11, 8, x); + b, d = R(b, c, d, e, a, F0, K0, 13, 9, x); + a, c = R(a, b, c, d, e, F0, K0, 14, 10, x); + e, b = R(e, a, b, c, d, F0, K0, 15, 11, x); + d, a = R(d, e, a, b, c, F0, K0, 6, 12, x); + c, e = R(c, d, e, a, b, F0, K0, 7, 13, x); + b, d = R(b, c, d, e, a, F0, K0, 9, 14, x); + a, c = R(a, b, c, d, e, F0, K0, 8, 15, x); #/* #15 */ + #/* Round 2 */ + e, b = R(e, a, b, c, d, F1, K1, 7, 7, x); + d, a = R(d, e, a, b, c, F1, K1, 6, 4, x); + c, e = R(c, d, e, a, b, F1, K1, 8, 13, x); + b, d = R(b, c, d, e, a, F1, K1, 13, 1, x); + a, c = R(a, b, c, d, e, F1, K1, 11, 10, x); + e, b = R(e, a, b, c, d, F1, K1, 9, 6, x); + d, a = R(d, e, a, b, c, F1, K1, 7, 15, x); + c, e = R(c, d, e, a, b, F1, K1, 15, 3, x); + b, d = R(b, c, d, e, a, F1, K1, 7, 12, x); + a, c = R(a, b, c, d, e, F1, K1, 12, 0, x); + e, b = R(e, a, b, c, d, F1, K1, 15, 9, x); + d, a = R(d, e, a, b, c, F1, K1, 9, 5, x); + c, e = R(c, d, e, a, b, F1, K1, 11, 2, x); + b, d = R(b, c, d, e, a, F1, K1, 7, 14, x); + a, c = R(a, b, c, d, e, F1, K1, 13, 11, x); + e, b = R(e, a, b, c, d, F1, K1, 12, 8, x); #/* #31 */ + #/* Round 3 */ + d, a = R(d, e, a, b, c, F2, K2, 11, 3, x); + c, e = R(c, d, e, a, b, F2, K2, 13, 10, x); + b, d = R(b, c, d, e, a, F2, K2, 6, 14, x); + a, c = R(a, b, c, d, e, F2, K2, 7, 4, x); + e, b = R(e, a, b, c, d, F2, K2, 14, 9, x); + d, a = R(d, e, a, b, c, F2, K2, 9, 15, x); + c, e = R(c, d, e, a, b, F2, K2, 13, 8, x); + b, d = R(b, c, d, e, a, F2, K2, 15, 1, x); + a, c = R(a, b, c, d, e, F2, K2, 14, 2, x); + e, b = R(e, a, b, c, d, F2, K2, 8, 7, x); + d, a = R(d, e, a, b, c, F2, K2, 13, 0, x); + c, e = R(c, d, e, a, b, F2, K2, 6, 6, x); + b, d = R(b, c, d, e, a, F2, K2, 5, 13, x); + a, c = R(a, b, c, d, e, F2, K2, 12, 11, x); + e, b = R(e, a, b, c, d, F2, K2, 7, 5, x); + d, a = R(d, e, a, b, c, F2, K2, 5, 12, x); #/* #47 */ + #/* Round 4 */ + c, e = R(c, d, e, a, b, F3, K3, 11, 1, x); + b, d = R(b, c, d, e, a, F3, K3, 12, 9, x); + a, c = R(a, b, c, d, e, F3, K3, 14, 11, x); + e, b = R(e, a, b, c, d, F3, K3, 15, 10, x); + d, a = R(d, e, a, b, c, F3, K3, 14, 0, x); + c, e = R(c, d, e, a, b, F3, K3, 15, 8, x); + b, d = R(b, c, d, e, a, F3, K3, 9, 12, x); + a, c = R(a, b, c, d, e, F3, K3, 8, 4, x); + e, b = R(e, a, b, c, d, F3, K3, 9, 13, x); + d, a = R(d, e, a, b, c, F3, K3, 14, 3, x); + c, e = R(c, d, e, a, b, F3, K3, 5, 7, x); + b, d = R(b, c, d, e, a, F3, K3, 6, 15, x); + a, c = R(a, b, c, d, e, F3, K3, 8, 14, x); + e, b = R(e, a, b, c, d, F3, K3, 6, 5, x); + d, a = R(d, e, a, b, c, F3, K3, 5, 6, x); + c, e = R(c, d, e, a, b, F3, K3, 12, 2, x); #/* #63 */ + #/* Round 5 */ + b, d = R(b, c, d, e, a, F4, K4, 9, 4, x); + a, c = R(a, b, c, d, e, F4, K4, 15, 0, x); + e, b = R(e, a, b, c, d, F4, K4, 5, 5, x); + d, a = R(d, e, a, b, c, F4, K4, 11, 9, x); + c, e = R(c, d, e, a, b, F4, K4, 6, 7, x); + b, d = R(b, c, d, e, a, F4, K4, 8, 12, x); + a, c = R(a, b, c, d, e, F4, K4, 13, 2, x); + e, b = R(e, a, b, c, d, F4, K4, 12, 10, x); + d, a = R(d, e, a, b, c, F4, K4, 5, 14, x); + c, e = R(c, d, e, a, b, F4, K4, 12, 1, x); + b, d = R(b, c, d, e, a, F4, K4, 13, 3, x); + a, c = R(a, b, c, d, e, F4, K4, 14, 8, x); + e, b = R(e, a, b, c, d, F4, K4, 11, 11, x); + d, a = R(d, e, a, b, c, F4, K4, 8, 6, x); + c, e = R(c, d, e, a, b, F4, K4, 5, 15, x); + b, d = R(b, c, d, e, a, F4, K4, 6, 13, x); #/* #79 */ + + aa = a; + bb = b; + cc = c; + dd = d; + ee = e; + + a = state[0] + b = state[1] + c = state[2] + d = state[3] + e = state[4] + + #/* Parallel round 1 */ + a, c = R(a, b, c, d, e, F4, KK0, 8, 5, x) + e, b = R(e, a, b, c, d, F4, KK0, 9, 14, x) + d, a = R(d, e, a, b, c, F4, KK0, 9, 7, x) + c, e = R(c, d, e, a, b, F4, KK0, 11, 0, x) + b, d = R(b, c, d, e, a, F4, KK0, 13, 9, x) + a, c = R(a, b, c, d, e, F4, KK0, 15, 2, x) + e, b = R(e, a, b, c, d, F4, KK0, 15, 11, x) + d, a = R(d, e, a, b, c, F4, KK0, 5, 4, x) + c, e = R(c, d, e, a, b, F4, KK0, 7, 13, x) + b, d = R(b, c, d, e, a, F4, KK0, 7, 6, x) + a, c = R(a, b, c, d, e, F4, KK0, 8, 15, x) + e, b = R(e, a, b, c, d, F4, KK0, 11, 8, x) + d, a = R(d, e, a, b, c, F4, KK0, 14, 1, x) + c, e = R(c, d, e, a, b, F4, KK0, 14, 10, x) + b, d = R(b, c, d, e, a, F4, KK0, 12, 3, x) + a, c = R(a, b, c, d, e, F4, KK0, 6, 12, x) #/* #15 */ + #/* Parallel round 2 */ + e, b = R(e, a, b, c, d, F3, KK1, 9, 6, x) + d, a = R(d, e, a, b, c, F3, KK1, 13, 11, x) + c, e = R(c, d, e, a, b, F3, KK1, 15, 3, x) + b, d = R(b, c, d, e, a, F3, KK1, 7, 7, x) + a, c = R(a, b, c, d, e, F3, KK1, 12, 0, x) + e, b = R(e, a, b, c, d, F3, KK1, 8, 13, x) + d, a = R(d, e, a, b, c, F3, KK1, 9, 5, x) + c, e = R(c, d, e, a, b, F3, KK1, 11, 10, x) + b, d = R(b, c, d, e, a, F3, KK1, 7, 14, x) + a, c = R(a, b, c, d, e, F3, KK1, 7, 15, x) + e, b = R(e, a, b, c, d, F3, KK1, 12, 8, x) + d, a = R(d, e, a, b, c, F3, KK1, 7, 12, x) + c, e = R(c, d, e, a, b, F3, KK1, 6, 4, x) + b, d = R(b, c, d, e, a, F3, KK1, 15, 9, x) + a, c = R(a, b, c, d, e, F3, KK1, 13, 1, x) + e, b = R(e, a, b, c, d, F3, KK1, 11, 2, x) #/* #31 */ + #/* Parallel round 3 */ + d, a = R(d, e, a, b, c, F2, KK2, 9, 15, x) + c, e = R(c, d, e, a, b, F2, KK2, 7, 5, x) + b, d = R(b, c, d, e, a, F2, KK2, 15, 1, x) + a, c = R(a, b, c, d, e, F2, KK2, 11, 3, x) + e, b = R(e, a, b, c, d, F2, KK2, 8, 7, x) + d, a = R(d, e, a, b, c, F2, KK2, 6, 14, x) + c, e = R(c, d, e, a, b, F2, KK2, 6, 6, x) + b, d = R(b, c, d, e, a, F2, KK2, 14, 9, x) + a, c = R(a, b, c, d, e, F2, KK2, 12, 11, x) + e, b = R(e, a, b, c, d, F2, KK2, 13, 8, x) + d, a = R(d, e, a, b, c, F2, KK2, 5, 12, x) + c, e = R(c, d, e, a, b, F2, KK2, 14, 2, x) + b, d = R(b, c, d, e, a, F2, KK2, 13, 10, x) + a, c = R(a, b, c, d, e, F2, KK2, 13, 0, x) + e, b = R(e, a, b, c, d, F2, KK2, 7, 4, x) + d, a = R(d, e, a, b, c, F2, KK2, 5, 13, x) #/* #47 */ + #/* Parallel round 4 */ + c, e = R(c, d, e, a, b, F1, KK3, 15, 8, x) + b, d = R(b, c, d, e, a, F1, KK3, 5, 6, x) + a, c = R(a, b, c, d, e, F1, KK3, 8, 4, x) + e, b = R(e, a, b, c, d, F1, KK3, 11, 1, x) + d, a = R(d, e, a, b, c, F1, KK3, 14, 3, x) + c, e = R(c, d, e, a, b, F1, KK3, 14, 11, x) + b, d = R(b, c, d, e, a, F1, KK3, 6, 15, x) + a, c = R(a, b, c, d, e, F1, KK3, 14, 0, x) + e, b = R(e, a, b, c, d, F1, KK3, 6, 5, x) + d, a = R(d, e, a, b, c, F1, KK3, 9, 12, x) + c, e = R(c, d, e, a, b, F1, KK3, 12, 2, x) + b, d = R(b, c, d, e, a, F1, KK3, 9, 13, x) + a, c = R(a, b, c, d, e, F1, KK3, 12, 9, x) + e, b = R(e, a, b, c, d, F1, KK3, 5, 7, x) + d, a = R(d, e, a, b, c, F1, KK3, 15, 10, x) + c, e = R(c, d, e, a, b, F1, KK3, 8, 14, x) #/* #63 */ + #/* Parallel round 5 */ + b, d = R(b, c, d, e, a, F0, KK4, 8, 12, x) + a, c = R(a, b, c, d, e, F0, KK4, 5, 15, x) + e, b = R(e, a, b, c, d, F0, KK4, 12, 10, x) + d, a = R(d, e, a, b, c, F0, KK4, 9, 4, x) + c, e = R(c, d, e, a, b, F0, KK4, 12, 1, x) + b, d = R(b, c, d, e, a, F0, KK4, 5, 5, x) + a, c = R(a, b, c, d, e, F0, KK4, 14, 8, x) + e, b = R(e, a, b, c, d, F0, KK4, 6, 7, x) + d, a = R(d, e, a, b, c, F0, KK4, 8, 6, x) + c, e = R(c, d, e, a, b, F0, KK4, 13, 2, x) + b, d = R(b, c, d, e, a, F0, KK4, 6, 13, x) + a, c = R(a, b, c, d, e, F0, KK4, 5, 14, x) + e, b = R(e, a, b, c, d, F0, KK4, 15, 0, x) + d, a = R(d, e, a, b, c, F0, KK4, 13, 3, x) + c, e = R(c, d, e, a, b, F0, KK4, 11, 9, x) + b, d = R(b, c, d, e, a, F0, KK4, 11, 11, x) #/* #79 */ + + t = (state[1] + cc + d) % 0x100000000; + state[1] = (state[2] + dd + e) % 0x100000000; + state[2] = (state[3] + ee + a) % 0x100000000; + state[3] = (state[4] + aa + b) % 0x100000000; + state[4] = (state[0] + bb + c) % 0x100000000; + state[0] = t % 0x100000000; + + pass + + +def RMD160Update(ctx, inp, inplen): + if type(inp) == str: + inp = [ord(i)&0xff for i in inp] + + have = (ctx.count / 8) % 64 + need = 64 - have + ctx.count += 8 * inplen + off = 0 + if inplen >= need: + if have: + for i in xrange(need): + ctx.buffer[have+i] = inp[i] + RMD160Transform(ctx.state, ctx.buffer) + off = need + have = 0 + while off + 64 <= inplen: + RMD160Transform(ctx.state, inp[off:]) #<--- + off += 64 + if off < inplen: + # memcpy(ctx->buffer + have, input+off, len-off); + for i in xrange(inplen - off): + ctx.buffer[have+i] = inp[off+i] + +def RMD160Final(ctx): + size = struct.pack(". + + +import sys, base64, os, re, hashlib, copy, operator, ast, threading, random + +try: + import ecdsa + from ecdsa.util import string_to_number, number_to_string +except: + print "python-ecdsa does not seem to be installed. Try 'sudo easy_install ecdsa'" + sys.exit(1) + +try: + import aes +except: + print "AES does not seem to be installed. Try 'sudo easy_install slowaes'" + sys.exit(1) + + +############ functions from pywallet ##################### + +addrtype = 0 + +def hash_160(public_key): + try: + md = hashlib.new('ripemd160') + md.update(hashlib.sha256(public_key).digest()) + return md.digest() + except: + import ripemd + md = ripemd.new(hashlib.sha256(public_key).digest()) + 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): + 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 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 Hash(data): + return hashlib.sha256(hashlib.sha256(data).digest()).digest() + +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): + vchIn = chr(addrtype+128) + secret + return EncodeBase58Check(vchIn) + +def ASecretToSecret(key): + vch = DecodeBase58Check(key) + if vch and vch[0] == chr(addrtype+128): + return vch[1:] + else: + return False + +########### end pywallet functions ####################### + +# 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 int_to_hex(i, length=1): + s = hex(i)[2:].rstrip('L') + s = "0"*(2*length - len(s)) + s + return s.decode('hex')[::-1].encode('hex') + + +# AES +EncodeAES = lambda secret, s: base64.b64encode(aes.encryptData(secret,s)) +DecodeAES = lambda secret, e: aes.decryptData(secret, base64.b64decode(e)) + + + +# secp256k1, http://www.oid-info.com/get/1.3.132.0.10 +_p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL +_r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L +_b = 0x0000000000000000000000000000000000000000000000000000000000000007L +_a = 0x0000000000000000000000000000000000000000000000000000000000000000L +_Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L +_Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L +curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b ) +generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r ) +oid_secp256k1 = (1,3,132,0,10) +SECP256k1 = ecdsa.curves.Curve("SECP256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1 ) + + +def filter(s): + out = re.sub('( [^\n]*|)\n','',s) + out = out.replace(' ','') + out = out.replace('\n','') + return out + +def raw_tx( inputs, outputs, for_sig = None ): + s = int_to_hex(1,4) + ' version\n' + s += int_to_hex( len(inputs) ) + ' number of inputs\n' + for i in range(len(inputs)): + _, _, p_hash, p_index, p_script, pubkey, sig = inputs[i] + s += p_hash.decode('hex')[::-1].encode('hex') + ' prev hash\n' + s += int_to_hex(p_index,4) + ' prev index\n' + if for_sig is None: + sig = sig + chr(1) # hashtype + script = int_to_hex( len(sig)) + ' push %d bytes\n'%len(sig) + script += sig.encode('hex') + ' sig\n' + pubkey = chr(4) + pubkey + script += int_to_hex( len(pubkey)) + ' push %d bytes\n'%len(pubkey) + script += pubkey.encode('hex') + ' pubkey\n' + elif for_sig==i: + script = p_script + ' scriptsig \n' + else: + script='' + s += int_to_hex( len(filter(script))/2 ) + ' script length \n' + s += script + s += "ffffffff" + ' sequence\n' + s += int_to_hex( len(outputs) ) + ' number of outputs\n' + for output in outputs: + addr, amount = output + s += int_to_hex( amount, 8) + ' amount: %d\n'%amount + script = '76a9' # op_dup, op_hash_160 + script += '14' # push 0x14 bytes + script += bc_address_to_hash_160(addr).encode('hex') + script += '88ac' # op_equalverify, op_checksig + s += int_to_hex( len(filter(script))/2 ) + ' script length \n' + s += script + ' script \n' + s += int_to_hex(0,4) # lock time + if for_sig is not None: s += int_to_hex(1, 4) # hash type + return s + + + + +def format_satoshis(x, is_diff=False): + from decimal import Decimal + s = str( Decimal(x) /100000000 ) + if is_diff and x>0: + s = "+" + s + if not '.' in s: s += '.' + p = s.find('.') + s += " "*( 9 - ( len(s) - p )) + s = " "*( 5 - ( p )) + s + return s + + +from version import ELECTRUM_VERSION, SEED_VERSION +from interface import DEFAULT_SERVERS + + + + +class Wallet: + def __init__(self, gui_callback = lambda: None): + + self.electrum_version = ELECTRUM_VERSION + self.seed_version = SEED_VERSION + self.gui_callback = gui_callback + + self.gap_limit = 5 # configuration + self.fee = 100000 + self.master_public_key = '' + + # saved fields + self.use_encryption = False + self.addresses = [] # receiving addresses visible for user + self.change_addresses = [] # addresses used as change + self.seed = '' # encrypted + self.history = {} + self.labels = {} # labels for addresses and transactions + self.aliases = {} # aliases for addresses + self.authorities = {} # trusted addresses + + self.receipts = {} # signed URIs + self.receipt = None # next receipt + self.addressbook = [] # outgoing addresses, for payments + + # not saved + self.tx_history = {} + + self.imported_keys = {} + self.remote_url = None + + self.was_updated = True + self.blocks = -1 + self.banner = '' + self.up_to_date_event = threading.Event() + self.up_to_date_event.clear() + self.up_to_date = False + self.lock = threading.Lock() + self.tx_event = threading.Event() + + # + self.addresses_waiting_for_status = [] + self.addresses_waiting_for_history = [] + self.pick_random_server() + + + + def pick_random_server(self): + self.server = random.choice( DEFAULT_SERVERS ) # random choice when the wallet is created + + def is_up_to_date(self): + return self.interface.responses.empty() and not ( self.addresses_waiting_for_status or self.addresses_waiting_for_history ) + + + def set_server(self, server): + # raise an error if the format isnt correct + a,b,c = server.split(':') + b = int(b) + assert c in ['t','h','n'] + # set the server + if server != self.server: + self.server = server + self.save() + self.interface.is_connected = False # this exits the polling loop + + def set_path(self, wallet_path): + + if wallet_path is not None: + self.path = wallet_path + else: + # backward compatibility: look for wallet file in the default data directory + if "HOME" in os.environ: + wallet_dir = os.path.join( os.environ["HOME"], '.electrum') + elif "LOCALAPPDATA" in os.environ: + wallet_dir = os.path.join( os.environ["LOCALAPPDATA"], 'Electrum' ) + elif "APPDATA" in os.environ: + wallet_dir = os.path.join( os.environ["APPDATA"], 'Electrum' ) + else: + raise BaseException("No home directory found in environment variables.") + + if not os.path.exists( wallet_dir ): os.mkdir( wallet_dir ) + self.path = os.path.join( wallet_dir, 'electrum.dat' ) + + def import_key(self, keypair, password): + address, key = keypair.split(':') + if not self.is_valid(address): return False + if address in self.all_addresses(): return False + b = ASecretToSecret( key ) + if not b: return False + secexp = int( b.encode('hex'), 16) + private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve=SECP256k1 ) + # sanity check + public_key = private_key.get_verifying_key() + if not address == public_key_to_bc_address( '04'.decode('hex') + public_key.to_string() ): return False + self.imported_keys[address] = self.pw_encode( key, password ) + return True + + def new_seed(self, password): + seed = "%032x"%ecdsa.util.randrange( pow(2,128) ) + #self.init_mpk(seed) + # encrypt + self.seed = self.pw_encode( seed, password ) + + + def init_mpk(self,seed): + # public key + curve = SECP256k1 + secexp = self.stretch_key(seed) + master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 ) + self.master_public_key = master_private_key.get_verifying_key().to_string() + + def all_addresses(self): + return self.addresses + self.change_addresses + self.imported_keys.keys() + + def is_mine(self, address): + return address in self.all_addresses() + + def is_change(self, address): + return address in self.change_addresses + + def is_valid(self,addr): + ADDRESS_RE = re.compile('[1-9A-HJ-NP-Za-km-z]{26,}\\Z') + if not ADDRESS_RE.match(addr): return False + try: + h = bc_address_to_hash_160(addr) + except: + return False + return addr == hash_160_to_bc_address(h) + + 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,n,for_change): + return string_to_number( Hash( "%d:%d:"%(n,for_change) + self.master_public_key ) ) + + def get_private_key(self, address, password): + """ Privatekey(type,n) = Master_private_key + H(n|S|type) """ + order = generator_secp256k1.order() + + if address in self.imported_keys.keys(): + b = self.pw_decode( self.imported_keys[address], password ) + b = ASecretToSecret( b ) + secexp = int( b.encode('hex'), 16) + else: + if address in self.addresses: + n = self.addresses.index(address) + for_change = False + elif address in self.change_addresses: + n = self.change_addresses.index(address) + for_change = True + else: + raise BaseException("unknown address") + try: + seed = self.pw_decode( self.seed, password) + except: + raise BaseException("Invalid password") + secexp = self.stretch_key(seed) + secexp = ( secexp + self.get_sequence(n,for_change) ) % order + + pk = number_to_string(secexp,order) + return pk + + def msg_magic(self, message): + return "\x18Bitcoin Signed Message:\n" + chr( len(message) ) + message + + def sign_message(self, address, message, password): + private_key = ecdsa.SigningKey.from_string( self.get_private_key(address, password), curve = SECP256k1 ) + public_key = private_key.get_verifying_key() + signature = private_key.sign_digest( Hash( self.msg_magic( message ) ), sigencode = ecdsa.util.sigencode_string ) + assert public_key.verify_digest( signature, Hash( self.msg_magic( message ) ), sigdecode = ecdsa.util.sigdecode_string) + for i in range(4): + sig = base64.b64encode( chr(27+i) + signature ) + try: + self.verify_message( address, sig, message) + return sig + except: + continue + else: + raise BaseException("error: cannot sign message") + + + def verify_message(self, address, signature, message): + """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """ + from ecdsa import numbertheory, ellipticcurve, util + import msqr + curve = curve_secp256k1 + G = generator_secp256k1 + order = G.order() + # extract r,s from signature + sig = base64.b64decode(signature) + if len(sig) != 65: raise BaseException("Wrong encoding") + r,s = util.sigdecode_string(sig[1:], order) + recid = ord(sig[0]) - 27 + # 1.1 + x = r + (recid/2) * order + # 1.3 + alpha = ( x * x * x + curve.a() * x + curve.b() ) % curve.p() + beta = msqr.modular_sqrt(alpha, curve.p()) + y = beta if (beta - recid) % 2 == 0 else curve.p() - beta + # 1.4 the constructor checks that nR is at infinity + R = ellipticcurve.Point(curve, x, y, order) + # 1.5 compute e from message: + h = Hash( self.msg_magic( 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 ) + public_key = ecdsa.VerifyingKey.from_public_point( Q, curve = SECP256k1 ) + # check that Q is the 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( '04'.decode('hex') + public_key.to_string() ) + # print addr + if address != addr: + print "bad signature" + raise BaseException("Bad signature") + + + def create_new_address(self, for_change): + """ Publickey(type,n) = Master_public_key + H(n|S|type)*point """ + curve = SECP256k1 + n = len(self.change_addresses) if for_change else len(self.addresses) + z = self.get_sequence(n,for_change) + master_public_key = ecdsa.VerifyingKey.from_string( self.master_public_key, curve = SECP256k1 ) + pubkey_point = master_public_key.pubkey.point + z*curve.generator + public_key2 = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 ) + address = public_key_to_bc_address( '04'.decode('hex') + public_key2.to_string() ) + if for_change: + self.change_addresses.append(address) + else: + self.addresses.append(address) + + self.history[address] = [] + print address + return address + + + + def synchronize(self): + if not self.master_public_key: + return [] + + new_addresses = [] + while True: + if self.change_addresses == []: + new_addresses.append( self.create_new_address(True) ) + continue + a = self.change_addresses[-1] + if self.history.get(a): + new_addresses.append( self.create_new_address(True) ) + else: + break + + n = self.gap_limit + while True: + if len(self.addresses) < n: + new_addresses.append( self.create_new_address(False) ) + continue + if map( lambda a: self.history.get(a), self.addresses[-n:] ) == n*[[]]: + break + else: + new_addresses.append( self.create_new_address(False) ) + + if self.remote_url: + num = self.get_remote_number() + while len(self.addresses) 1 ) or ( len(self.addresses) > self.gap_limit ) + + def fill_addressbook(self): + for tx in self.tx_history.values(): + if tx['value']<0: + for i in tx['outputs']: + if not self.is_mine(i) and i not in self.addressbook: + self.addressbook.append(i) + # redo labels + self.update_tx_labels() + + + def save(self): + s = { + 'seed_version':self.seed_version, + 'use_encryption':self.use_encryption, + 'master_public_key': self.master_public_key.encode('hex'), + 'fee':self.fee, + 'server':self.server, + 'seed':self.seed, + 'addresses':self.addresses, + 'change_addresses':self.change_addresses, + 'history':self.history, + 'labels':self.labels, + 'contacts':self.addressbook, + 'imported_keys':self.imported_keys, + 'aliases':self.aliases, + 'authorities':self.authorities, + 'receipts':self.receipts, + } + f = open(self.path,"w") + f.write( repr(s) ) + f.close() + + def read(self): + import interface + + upgrade_msg = """This wallet seed is deprecated. Please run upgrade.py for a diagnostic.""" + self.file_exists = False + try: + f = open(self.path,"r") + data = f.read() + f.close() + except: + return + data = interface.old_to_new(data) + try: + d = ast.literal_eval( data ) + self.seed_version = d.get('seed_version') + self.master_public_key = d.get('master_public_key').decode('hex') + self.use_encryption = d.get('use_encryption') + self.fee = int( d.get('fee') ) + self.seed = d.get('seed') + self.server = d.get('server') + #blocks = d.get('blocks') + self.addresses = d.get('addresses') + self.change_addresses = d.get('change_addresses') + self.history = d.get('history') + self.labels = d.get('labels') + self.addressbook = d.get('contacts') + self.imported_keys = d.get('imported_keys',{}) + self.aliases = d.get('aliases',{}) + self.authorities = d.get('authorities',{}) + self.receipts = d.get('receipts',{}) + except: + raise BaseException("cannot read wallet file") + + self.update_tx_history() + + if self.seed_version != SEED_VERSION: + raise BaseException(upgrade_msg) + + if self.remote_url: assert self.master_public_key.encode('hex') == self.get_remote_mpk() + + self.file_exists = True + + + + + def get_addr_balance(self, addr): + if self.is_mine(addr): + h = self.history.get(addr) + else: + h = self.interface.retrieve_history(addr) + if not h: return 0,0 + c = u = 0 + for item in h: + v = item['value'] + if item['height']: + c += v + else: + u += v + return c, u + + def get_balance(self): + conf = unconf = 0 + for addr in self.all_addresses(): + c, u = self.get_addr_balance(addr) + conf += c + unconf += u + return conf, unconf + + + def choose_tx_inputs( self, amount, fixed_fee, from_addr = None ): + """ todo: minimize tx size """ + total = 0 + fee = self.fee if fixed_fee is None else fixed_fee + + coins = [] + domain = [from_addr] if from_addr else self.all_addresses() + for addr in domain: + h = self.history.get(addr) + if h is None: continue + for item in h: + if item.get('raw_output_script'): + coins.append( (addr,item)) + + coins = sorted( coins, key = lambda x: x[1]['timestamp'] ) + inputs = [] + for c in coins: + addr, item = c + v = item.get('value') + total += v + inputs.append((addr, v, item['tx_hash'], item['index'], item['raw_output_script'], None, None) ) + fee = self.fee*len(inputs) if fixed_fee is None else fixed_fee + if total >= amount + fee: break + else: + #print "not enough funds: %d %d"%(total, fee) + inputs = [] + return inputs, total, fee + + def choose_tx_outputs( self, to_addr, amount, fee, total, change_addr=None ): + outputs = [ (to_addr, amount) ] + change_amount = total - ( amount + fee ) + if change_amount != 0: + # normally, the update thread should ensure that the last change address is unused + if not change_addr: + change_addr = self.change_addresses[-1] + outputs.append( ( change_addr, change_amount) ) + return outputs + + def sign_inputs( self, inputs, outputs, password ): + s_inputs = [] + for i in range(len(inputs)): + addr, v, p_hash, p_pos, p_scriptPubKey, _, _ = inputs[i] + private_key = ecdsa.SigningKey.from_string( self.get_private_key(addr, password), curve = SECP256k1 ) + public_key = private_key.get_verifying_key() + pubkey = public_key.to_string() + tx = filter( raw_tx( inputs, outputs, for_sig = i ) ) + sig = private_key.sign_digest( Hash( tx.decode('hex') ), sigencode = ecdsa.util.sigencode_der ) + assert public_key.verify_digest( sig, Hash( tx.decode('hex') ), sigdecode = ecdsa.util.sigdecode_der) + s_inputs.append( (addr, v, p_hash, p_pos, p_scriptPubKey, pubkey, sig) ) + return s_inputs + + def pw_encode(self, s, password): + if password: + secret = Hash(password) + return EncodeAES(secret, s) + else: + return s + + def pw_decode(self, s, password): + if password is not None: + secret = Hash(password) + d = DecodeAES(secret, s) + if s == self.seed: + try: + d.decode('hex') + except: + raise BaseException("Invalid password") + return d + else: + return s + + def get_status(self, address): + h = self.history.get(address) + if not h: + status = None + else: + lastpoint = h[-1] + status = lastpoint['block_hash'] + if status == 'mempool': + status = status + ':%d'% len(h) + return status + + def receive_status_callback(self, addr, status): + with self.lock: + if self.get_status(addr) != status: + #print "updating status for", addr, status + self.addresses_waiting_for_history.append(addr) + self.interface.get_history(addr) + if addr in self.addresses_waiting_for_status: + self.addresses_waiting_for_status.remove(addr) + + def receive_history_callback(self, addr, data): + #print "updating history for", addr + with self.lock: + self.history[addr] = data + self.update_tx_history() + self.save() + if addr in self.addresses_waiting_for_history: self.addresses_waiting_for_history.remove(addr) + + def get_tx_history(self): + lines = self.tx_history.values() + lines = sorted(lines, key=operator.itemgetter("timestamp")) + return lines + + def update_tx_history(self): + self.tx_history= {} + for addr in self.all_addresses(): + h = self.history.get(addr) + if h is None: continue + for tx in h: + tx_hash = tx['tx_hash'] + line = self.tx_history.get(tx_hash) + if not line: + self.tx_history[tx_hash] = copy.copy(tx) + line = self.tx_history.get(tx_hash) + else: + line['value'] += tx['value'] + if line['height'] == 0: + line['timestamp'] = 1e12 + self.update_tx_labels() + + def update_tx_labels(self): + for tx in self.tx_history.values(): + default_label = '' + if tx['value']<0: + for o_addr in tx['outputs']: + if not self.is_change(o_addr): + dest_label = self.labels.get(o_addr) + if dest_label: + default_label = 'to: ' + dest_label + else: + default_label = 'to: ' + o_addr + else: + for o_addr in tx['outputs']: + if self.is_mine(o_addr) and not self.is_change(o_addr): + dest_label = self.labels.get(o_addr) + if dest_label: + default_label = 'at: ' + dest_label + else: + default_label = 'at: ' + o_addr + tx['default_label'] = default_label + + def mktx(self, to_address, amount, label, password, fee=None, change_addr=None, from_addr= None): + if not self.is_valid(to_address): + raise BaseException("Invalid address") + inputs, total, fee = self.choose_tx_inputs( amount, fee, from_addr ) + if not inputs: + raise BaseException("Not enough funds") + outputs = self.choose_tx_outputs( to_address, amount, fee, total, change_addr ) + s_inputs = self.sign_inputs( inputs, outputs, password ) + + tx = filter( raw_tx( s_inputs, outputs ) ) + if to_address not in self.addressbook: + self.addressbook.append(to_address) + if label: + tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex') + self.labels[tx_hash] = label + + return tx + + def sendtx(self, tx): + tx_hash = Hash(tx.decode('hex') )[::-1].encode('hex') + self.tx_event.clear() + self.interface.send([('blockchain.transaction.broadcast', [tx])]) + self.tx_event.wait() + out = self.tx_result + if out != tx_hash: + return False, "error: " + out + if self.receipt: + self.receipts[tx_hash] = self.receipt + self.receipt = None + return True, out + + + def read_alias(self, alias): + # this might not be the right place for this function. + import urllib + + m1 = re.match('([\w\-\.]+)@((\w[\w\-]+\.)+[\w\-]+)', alias) + m2 = re.match('((\w[\w\-]+\.)+[\w\-]+)', alias) + if m1: + url = 'http://' + m1.group(2) + '/bitcoin.id/' + m1.group(1) + elif m2: + url = 'http://' + alias + '/bitcoin.id' + else: + return '' + try: + lines = urllib.urlopen(url).readlines() + except: + return '' + + # line 0 + line = lines[0].strip().split(':') + if len(line) == 1: + auth_name = None + target = signing_addr = line[0] + else: + target, auth_name, signing_addr, signature = line + msg = "alias:%s:%s:%s"%(alias,target,auth_name) + print msg, signature + self.verify_message(signing_addr, signature, msg) + + # other lines are signed updates + for line in lines[1:]: + line = line.strip() + if not line: continue + line = line.split(':') + previous = target + print repr(line) + target, signature = line + self.verify_message(previous, signature, "alias:%s:%s"%(alias,target)) + + if not self.is_valid(target): + raise BaseException("Invalid bitcoin address") + + return target, signing_addr, auth_name + + def update_password(self, seed, new_password): + if new_password == '': new_password = None + self.use_encryption = (new_password != None) + self.seed = self.pw_encode( seed, new_password) + for k in self.imported_keys.keys(): + a = self.imported_keys[k] + b = self.pw_decode(a, password) + c = self.pw_encode(b, new_password) + self.imported_keys[k] = c + self.save() + + def get_alias(self, alias, interactive = False, show_message=None, question = None): + try: + target, signing_address, auth_name = self.read_alias(alias) + except BaseException, e: + # raise exception if verify fails (verify the chain) + if interactive: + show_message("Alias error: " + e.message) + return + + print target, signing_address, auth_name + + if auth_name is None: + a = self.aliases.get(alias) + if not a: + msg = "Warning: the alias '%s' is self-signed.\nThe signing address is %s.\n\nDo you want to add this alias to your list of contacts?"%(alias,signing_address) + if interactive and question( msg ): + self.aliases[alias] = (signing_address, target) + else: + target = None + else: + if signing_address != a[0]: + msg = "Warning: the key of alias '%s' has changed since your last visit! It is possible that someone is trying to do something nasty!!!\nDo you accept to change your trusted key?"%alias + if interactive and question( msg ): + self.aliases[alias] = (signing_address, target) + else: + target = None + else: + if signing_address not in self.authorities.keys(): + msg = "The alias: '%s' links to %s\n\nWarning: this alias was signed by an unknown key.\nSigning authority: %s\nSigning address: %s\n\nDo you want to add this key to your list of trusted keys?"%(alias,target,auth_name,signing_address) + if interactive and question( msg ): + self.authorities[signing_address] = auth_name + else: + target = None + + if target: + self.aliases[alias] = (signing_address, target) + + return target + + + def parse_url(self, url, show_message, question): + o = url[8:].split('?') + address = o[0] + if len(o)>1: + params = o[1].split('&') + else: + params = [] + + amount = label = message = signature = identity = '' + for p in params: + k,v = p.split('=') + uv = urldecode(v) + if k == 'amount': amount = uv + elif k == 'message': message = uv + elif k == 'label': label = uv + elif k == 'signature': + identity, signature = uv.split(':') + url = url.replace('&%s=%s'%(k,v),'') + else: + print k,v + + if signature: + if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', identity): + signing_address = self.get_alias(identity, True, show_message, question) + elif self.is_valid(identity): + signing_address = identity + else: + signing_address = None + if not signing_address: + return + try: + self.verify_message(signing_address, signature, url ) + self.receipt = (signing_address, signature, url) + except: + show_message('Warning: the URI contains a bad signature.\nThe identity of the recipient cannot be verified.') + address = amount = label = identity = message = '' + + if re.match('^(|([\w\-\.]+)@)((\w[\w\-]+\.)+[\w\-]+)$', address): + payto_address = self.get_alias(address, True, show_message, question) + if payto_address: + address = address + ' <' + payto_address + '>' + + return address, amount, label, message, signature, identity, url + + + def update(self): + self.interface.poke() + self.up_to_date_event.wait() + + + -- 1.7.1