electrum

Electrum Bitcoin wallet
git clone https://git.parazyd.org/electrum
Log | Files | Refs | Submodules

commit 2e5d015917be5989f82d94b9c18c68b40f443da3
parent f0aae3cc0f587994c86c5bcbc083829c524d3b62
Author: thomasv <thomasv@gitorious>
Date:   Wed, 21 Mar 2012 10:18:46 +0100

remove server from repo

Diffstat:
Dserver/HOWTO | 220-------------------------------------------------------------------------------
Dserver/LICENSE | 661-------------------------------------------------------------------------------
Dserver/README | 34----------------------------------
Dserver/README-IRC.txt | 18------------------
Dserver/StratumJSONRPCServer.py | 311-------------------------------------------------------------------------------
Dserver/electrum.conf.sample | 29-----------------------------
Dserver/patches/bitcoin-0.5.1.diff | 82-------------------------------------------------------------------------------
Dserver/patches/bitcoin-0.5.2.diff | 82-------------------------------------------------------------------------------
Dserver/patches/bitcoinrpc.cpp.diff | 52----------------------------------------------------
Dserver/patches/main.cpp.diff | 33---------------------------------
Dserver/server.py | 1001-------------------------------------------------------------------------------
Dserver/start | 2--
Dserver/stop | 2--
13 files changed, 0 insertions(+), 2527 deletions(-)

diff --git a/server/HOWTO b/server/HOWTO @@ -1,220 +0,0 @@ -How to run your own Electrum server - - -Abstract - -This document is an easy to follow guide to installing and running your own Electrum server on Linux. It is structured as a series of steps you need to follow, ordered in the most logical way. The next two sections describe some conventions we use in this document and hardware, software and expertise requirements. - -The most up-to date version of this document is available at: https://gitorious.org/electrum/electrum/blobs/master/server/HOWTO - - -Conventions - -In this document, lines starting with a hash sign (#) or a dollar sign ($) contain commands. Commands starting with a hash should be run as root, commands starting with a dollar should be run as a normal user (in this document, we assume that user is called 'bitcoin'). We also assume the bitcoin user has sudo rights, so we use '$ sudo command' when we need to. - -Strings that are surrounded by "lower than" and "greater than" ( < and > ) should be replaced by the user with something appropriate. For example, <password> should be replaced by a user chosen password. Do not confuse this notation with shell redirection ('command < file' or 'command > file')! - -Lines that are indented with a tab are pastes from config files. They should be copied verbatim or adapted, without the indentation tab. - - -Prerequisites - -Expertise. You should be familiar with Linux command line and standard Linux commands. You should have basic understanding of git, Python packages, compiling and applying patches to source code. You should have knowledge about how to install and configure software on your Linux distribution. You should be able to add commands to your distribution's startup scripts. If one of the commands included in this document is not available or does not perform the operation described here, you are expected to fix the issue so you can continue following this howto. - -Software. A recent Linux distribution with the following software installed: python, easy_install, git, a SQL server, standard C/C++ build chain. You will need root access in order to install other software or Python libraries. You will need access to the SQL server to create users and databases. - -Hardware. Running a Bitcoin node and Electrum server is resource intensive. At the time of this writing, the Bitcoin blockchain is 1.2 GB large. The corresponding SQL database is about 4 time larger, so you should have a minimum of 6.5 GB free space. You should expect the total size to grow with time. CPU speed is also important, mostly for the initial blockchain import, but also if you plan to run a public Electrum server, which could serve tens of concurrent requests. See step 6 below for some initial import benchmarks. - - -Step 0. Create a user for running bitcoind and Electrum server - -This step is optional, but for better security and resource separation I suggest you create a separate user just for running bitcoind and Electrum. We will also use the ~/bin directory to keep locally installed files (others might want to use /usr/local/bin instead). We will download source code files to the ~/src directory. - -# sudo adduser bitcoin -# su - bitcoin -$ mkdir ~/bin ~/src -$ echo $PATH - -If you don't see /home/bitcoin/bin in the output, you should add this line to your .bashrc, .profile or .bash_profile, then logout and relogin: - - PATH="$HOME/bin:$PATH" - - -Step 1. Download and install Electrum - -We will download the latest git snapshot for Electrum and 'install' it in our ~/bin directory: - -$ cd ~/src -$ git clone git://gitorious.org/electrum/electrum.git -$ chmod +x ~/src/electrum/server/server.py -$ ln -s ~/src/electrum/server/server.py ~/bin/electrum-server - - -Step 2. Install a patched version of bitcoind - -Electrum server requires some small modifications to the bitcoind daemon. The patch is included in the Electrum sources we just downloaded, now we will download the Bitcoin sources, patch, compile and install the binary to our ~/bin directory. - -$ cd ~/src -$ wget https://github.com/bitcoin/bitcoin/tarball/v0.5.2 -O bitcoin-0.5.2.tgz -$ tar xvzf bitcoin-0.5.2.tgz -$ mv bitcoin-bitcoin-fb24b05 bitcoin-0.5.2 -$ cd bitcoin-0.5.2/src -$ patch -p 2 < ~/src/electrum/server/patches/bitcoin-0.5.2.diff -$ make -f makefile.unix -$ strip bitcoind -$ mv bitcoind ~/bin - - -Step 3. Configure and start bitcoind. - -In order to allow Electrum to "talk" to bitcoind, we need to set up a RPC username and password for bitcoind. We will then start bitcoind and wait for it to complete downloading the blockchain. - -$ mkdir ~/.bitcoin -$ $EDITOR ~/.bitcoin/bitcoin.conf - - rpcuser=<rpc-username> - rpcpassword=<rpc-password> - daemon=1 - -$ bitcoind - -Allow some time to pass, so bitcoind connects to the network and starts downloading blocks. You can check its progress by running: - -$ bitcoind getinfo - -You should also set up your system to automatically start bitcoind at boot time, running as the 'bitcoin' user. Check your system documentation to find out the best way to do this. - - -Step 4. Install Electrum dependencies - -Electrum server depends on various standard Python libraries. These will be already installed on your distribution, or can be installed with your package manager. Electrum also depends on two Python libraries which we will need to install "by hand": Abe and JSONRPClib. - -$ sudo easy_install jsonrpclib -$ cd ~/src -$ git clone git://github.com/jtobey/bitcoin-abe.git -$ cd bitcoin-abe -$ sudo python setup.py install -$ sudo chmod +x /usr/local/lib/python2.7/dist-packages/Abe/abe.py -$ ln -s /usr/local/lib/python2.7/dist-packages/Abe/abe.py ~/bin/abe - - -Step 5. Configure the database - -Electrum server uses a SQL database to store the blockchain data. In theory, it supports all databases supported by Abe. At the time of this writing, MySQL and PostgreSQL are tested and work ok, SQLite was tested and does not work with Electrum server. - -For MySQL: - -$ mysql -u root -p -mysql> create user 'electrum'@'localhost' identified by '<database-password>'; -mysql> create database electrum; -mysql> grant all on electrum.* to 'electrum'@'localhost'; -mysql> exit - -For PostgreSQL: - -TDB! - - -Step 6. Configure Abe and import blockchain into the database - -When you run Electrum server for the first time, it will automatically import the blockchain into the database, so it is safe to skip this step. However, our tests showed that, at the time of this writing, importing the blockchaind via Abe is much faster (about 20-30 times faster) than allowing Electrum to do it. - -$ cp ~/src/bitcoin-abe/abe.conf ~/abe.conf -$ $EDITOR ~/abe.conf - -For MySQL, you need these lines: - - dbtype MySQLdb - connect-args = { "db" : "electrum", "user" : "electrum" , "passwd" : "<database-password>" } - -For PostgreSQL, you need these lines: - - TBD! - -Start Abe: - -$ abe --config ~/abe.conf - -Abe will now start to import blocks. You will see a lot of lines like this: 'block_tx <block-number> <tx-number>'. You should wait until you see this message on the screen: - -Listening on http://localhost:2750 - -It means the blockchain is imported and you can exit Abe by pressing CTRL-C. You will not need to run Abe again after this step, Electrum server will update the blockchain by itsself. We only used Abe because it is much faster for the initial import. - -Important notice: This is a *very* long process. Even on fast machines you can expect it to take hours. Here are some benchmarks for importing ~159.400 blocks (size of the Bitcoin blockchain at the time of this writing): - -System 1: ~8 hours. - * CPU: Intel Core i7 Q740 @ 1.73GHz - * HDD: very fast SSD -System 2: ~48 hours. - * CPU: Intel Xeon X3430 @ 2.40GHz - * HDD: 2 x SATA in a RAID1. - - -Step 7. Configure Electrum server - -Electrum reads a config file (/etc/electrum.conf) when starting up. This file includes the database setup, bitcoind RPC setup and a few other options. - -$ sudo cp ~/src/electrum/server/electrum.conf.sample /etc/electrum.conf -$ sudo $EDITOR /etc/electrum.conf - - # sample server config for a public Electrum server - [server] - host = host-fqdn - port = 50000 - password = <electrum-server-password> - banner = Welcome to Electrum server! - irc = yes - ircname = public Electrum server - cache = yes - - # sample server config for a private (does not advertise on IRC) Electrum server - [server] - host = localhost - port = 50000 - password = <electrum-server-password> - banner = Welcome to Electrum server! - irc = no - ircname = foo - cache = yes - - # database setup - MySQL - [database] - type = MySQLdb - database = electrum - username = electrum - password = <database-password> - - # database setup - PostgreSQL - TBD! - - # bitcoind RPC setup - [bitcoind] - host = localhost - port = 8332 - user = <rpc-username> - password = <rpc-password> - - -Step 8. (Finally!) Run Electrum server - -The magic moment has come: you can now start your Electrum server: - -$ electrum-server - -You should see this on the screen: - -starting Electrum server -cache: yes - -If you want to stop Electrum server, open another shell and run: - -$ electrum-server stop - -You should also take a look at the 'start' and 'stop' scripts in ~/src/electrum/server . You can use them as a starting point to create a init script for your system. - - -9. Test the Electrum server - -We will assume you have a working Electrum client, a wallet and some transactions history. You should start the client and click on the green check mark (last button on the right of the status bar) to open the Server selection window. If your server is public, you should see it in the list and you can select it. If you server is private, you need to enter its IP or hostname and the port. Press Ok, the client will disconnect from the current server and connect to your new Electrum server. You should see your addresses and transactions history. You can see the number of blocks and response time in the Server selection window. You should send/receive some bitcoins to confirm that everything is working properly. - diff --git a/server/LICENSE b/server/LICENSE @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are 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. - - 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. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - 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 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 work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - <one line to give the program's name and a brief idea of what it does.> - Copyright (C) <year> <name of author> - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero 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 Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - 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 AGPL, see -<http://www.gnu.org/licenses/>. diff --git a/server/README b/server/README @@ -1,34 +0,0 @@ -Electrum - server for the Electrum client - -Licence: GNU GPL v3 -Author: thomasv@gitorious -Language: Python - -Features: - -* The server uses a patched version of the Bitcoin daemon that can -forward transactions, and bitcoin-abe - -* The server code is open source. Anyone can run a server, removing -single points of failure concerns. - -* The server knows which set of Bitcoin addresses belong to the same -wallet, which might raise concerns about anonymity. However, it should -be possible to write clients capable of using several servers. - - -INSTALL - -1. patch and recompile the bitcoin daemon: see bitcoinrpc.cpp.diff and main.cpp.diff - -2. install bitcoin-abe : https://github.com/jtobey/bitcoin-abe - -3. install jsonrpclib: code.google.com/p/jsonrpclib/ - -4. launch the server: nohup python -u server.py > /var/log/electrum.log & - - -Note: -You do not want to run bitcoin-abe and the server simultaneously, because they will both try to update the database. -If you want bitcoin-abe to be available on your website, run it with the --no-update option - diff --git a/server/README-IRC.txt b/server/README-IRC.txt @@ -1,18 +0,0 @@ -IRC is used by Electrum server to find 'peers' - other Electrum servers. The current list can be seen by running: - -./server.py peers - -The following config file options are used by the IRC part of Electrum server: - -[server] -irc = yes -host = fqdn.host.name.tld -ircname = some short description - -'irc' is used to determine whether the IRC thread will be started or the Electrum server will run in private mode. In private mode, ./server.py peers will always return an empty list. - -'host' is a fqdn of your Electrum server. It is used both when binding the listener for incoming client connections, and also as part of the realname field in IRC (see below). - -'ircname' is a short text that will be appended to 'host' when composing the IRC realname field: - -realname = 'host' + ' ' + 'ircname', for example 'fqdn.host.name.tld some short description' diff --git a/server/StratumJSONRPCServer.py b/server/StratumJSONRPCServer.py @@ -1,311 +0,0 @@ -#!/usr/bin/env python -# Copyright(C) 2012 thomasv@gitorious - -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero 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 -# Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/agpl.html>. - -import jsonrpclib -from jsonrpclib import Fault -from jsonrpclib.jsonrpc import USE_UNIX_SOCKETS -import SimpleXMLRPCServer -import SocketServer -import socket -import logging -import os -import types -import traceback -import sys -try: - import fcntl -except ImportError: - # For Windows - fcntl = None - -import json - -def get_version(request): - # must be a dict - if 'jsonrpc' in request.keys(): - return 2.0 - if 'id' in request.keys(): - return 1.0 - return None - -def validate_request(request): - if type(request) is not types.DictType: - fault = Fault( - -32600, 'Request must be {}, not %s.' % type(request) - ) - return fault - rpcid = request.get('id', None) - version = get_version(request) - if not version: - fault = Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid) - return fault - request.setdefault('params', []) - method = request.get('method', None) - params = request.get('params') - param_types = (types.ListType, types.DictType, types.TupleType) - if not method or type(method) not in types.StringTypes or \ - type(params) not in param_types: - fault = Fault( - -32600, 'Invalid request parameters or method.', rpcid=rpcid - ) - return fault - return True - -class StratumJSONRPCDispatcher(SimpleXMLRPCServer.SimpleXMLRPCDispatcher): - - def __init__(self, encoding=None): - SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, - allow_none=True, - encoding=encoding) - - def _marshaled_dispatch(self, data, dispatch_method = None): - response = None - try: - request = jsonrpclib.loads(data) - except Exception, e: - fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e)) - response = fault.response() - return response - - responses = [] - if type(request) is not types.ListType: - request = [ request ] - - for req_entry in request: - result = validate_request(req_entry) - if type(result) is Fault: - responses.append(result.response()) - continue - resp_entry = self._marshaled_single_dispatch(req_entry) - if resp_entry is not None: - responses.append(resp_entry) - - # poll - r = self._marshaled_single_dispatch({'method':'session.poll', 'params':[], 'id':'z' }) - r = jsonrpclib.loads(r) - r = r.get('result') - for item in r: - responses.append(json.dumps(item)) - - if len(responses) > 1: - response = '[%s]' % ','.join(responses) - elif len(responses) == 1: - response = responses[0] - else: - response = '' - - return response - - def _marshaled_single_dispatch(self, request): - # TODO - Use the multiprocessing and skip the response if - # it is a notification - # Put in support for custom dispatcher here - # (See SimpleXMLRPCServer._marshaled_dispatch) - method = request.get('method') - params = request.get('params') - if params is None: params=[] - params = [ self.session_id, request['id'] ] + params - #print method, params - try: - response = self._dispatch(method, params) - except: - exc_type, exc_value, exc_tb = sys.exc_info() - fault = Fault(-32603, '%s:%s' % (exc_type, exc_value)) - return fault.response() - if 'id' not in request.keys() or request['id'] == None: - # It's a notification - return None - - try: - response = jsonrpclib.dumps(response, - methodresponse=True, - rpcid=request['id'] - ) - return response - except: - exc_type, exc_value, exc_tb = sys.exc_info() - fault = Fault(-32603, '%s:%s' % (exc_type, exc_value)) - return fault.response() - - def _dispatch(self, method, params): - func = None - try: - func = self.funcs[method] - except KeyError: - if self.instance is not None: - if hasattr(self.instance, '_dispatch'): - return self.instance._dispatch(method, params) - else: - try: - func = SimpleXMLRPCServer.resolve_dotted_attribute( - self.instance, - method, - True - ) - except AttributeError: - pass - if func is not None: - try: - if type(params) is types.ListType: - response = func(*params) - else: - response = func(**params) - return response - except TypeError: - return Fault(-32602, 'Invalid parameters.') - except: - err_lines = traceback.format_exc().splitlines() - trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) - fault = jsonrpclib.Fault(-32603, 'Server error: %s' % - trace_string) - return fault - else: - return Fault(-32601, 'Method %s not supported.' % method) - -class StratumJSONRPCRequestHandler( - SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): - - def do_GET(self): - if not self.is_rpc_path_valid(): - self.report_404() - return - try: - self.server.session_id = None - c = self.headers.get('cookie') - if c: - if c[0:8]=='SESSION=': - #print "found cookie", c[8:] - self.server.session_id = c[8:] - - if self.server.session_id is None: - r = self.server._marshaled_single_dispatch({'method':'session.create', 'params':[], 'id':'z' }) - r = jsonrpclib.loads(r) - self.server.session_id = r.get('result') - #print "setting cookie", self.server.session_id - - data = json.dumps([]) - response = self.server._marshaled_dispatch(data) - self.send_response(200) - except Exception, e: - self.send_response(500) - err_lines = traceback.format_exc().splitlines() - trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) - fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) - response = fault.response() - print "500", trace_string - if response == None: - response = '' - - if hasattr(self.server, 'session_id'): - if self.server.session_id: - self.send_header("Set-Cookie", "SESSION=%s"%self.server.session_id) - self.session_id = None - - self.send_header("Content-type", "application/json-rpc") - self.send_header("Content-length", str(len(response))) - self.end_headers() - self.wfile.write(response) - self.wfile.flush() - self.connection.shutdown(1) - - - def do_POST(self): - if not self.is_rpc_path_valid(): - self.report_404() - return - try: - max_chunk_size = 10*1024*1024 - size_remaining = int(self.headers["content-length"]) - L = [] - while size_remaining: - chunk_size = min(size_remaining, max_chunk_size) - L.append(self.rfile.read(chunk_size)) - size_remaining -= len(L[-1]) - data = ''.join(L) - - self.server.session_id = None - c = self.headers.get('cookie') - if c: - if c[0:8]=='SESSION=': - #print "found cookie", c[8:] - self.server.session_id = c[8:] - - if self.server.session_id is None: - r = self.server._marshaled_single_dispatch({'method':'session.create', 'params':[], 'id':'z' }) - r = jsonrpclib.loads(r) - self.server.session_id = r.get('result') - #print "setting cookie", self.server.session_id - - response = self.server._marshaled_dispatch(data) - self.send_response(200) - except Exception, e: - self.send_response(500) - err_lines = traceback.format_exc().splitlines() - trace_string = '%s | %s' % (err_lines[-3], err_lines[-1]) - fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string) - response = fault.response() - print "500", trace_string - if response == None: - response = '' - - if hasattr(self.server, 'session_id'): - if self.server.session_id: - self.send_header("Set-Cookie", "SESSION=%s"%self.server.session_id) - self.session_id = None - - self.send_header("Content-type", "application/json-rpc") - self.send_header("Content-length", str(len(response))) - self.end_headers() - self.wfile.write(response) - self.wfile.flush() - self.connection.shutdown(1) - - -class StratumJSONRPCServer(SocketServer.TCPServer, StratumJSONRPCDispatcher): - - allow_reuse_address = True - - def __init__(self, addr, requestHandler=StratumJSONRPCRequestHandler, - logRequests=False, encoding=None, bind_and_activate=True, - address_family=socket.AF_INET): - self.logRequests = logRequests - StratumJSONRPCDispatcher.__init__(self, encoding) - # TCPServer.__init__ has an extra parameter on 2.6+, so - # check Python version and decide on how to call it - vi = sys.version_info - self.address_family = address_family - if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX: - # Unix sockets can't be bound if they already exist in the - # filesystem. The convention of e.g. X11 is to unlink - # before binding again. - if os.path.exists(addr): - try: - os.unlink(addr) - except OSError: - logging.warning("Could not unlink socket %s", addr) - # if python 2.5 and lower - if vi[0] < 3 and vi[1] < 6: - SocketServer.TCPServer.__init__(self, addr, requestHandler) - else: - SocketServer.TCPServer.__init__(self, addr, requestHandler, - bind_and_activate) - if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): - flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) - flags |= fcntl.FD_CLOEXEC - fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) - - diff --git a/server/electrum.conf.sample b/server/electrum.conf.sample @@ -1,29 +0,0 @@ -[server] -host = localhost -port = 50000 -password = secret -banner = Welcome to Electrum! -irc = yes -ircname = public Electrum server -cache = no - -[database] -type = MySQLdb -database = electrum -username = electrum -password = secret -# -# [database] -# type = psycopg2 -# database = electrum -# -# [database] -# type = sqlite3 -# database = electrum.sqlite - -[bitcoind] -host = localhost -port = 8332 -# user and password from bitcoin.conf -user = user -password = password diff --git a/server/patches/bitcoin-0.5.1.diff b/server/patches/bitcoin-0.5.1.diff @@ -1,82 +0,0 @@ -diff -ur bitcoin-0.5.1/src/bitcoinrpc.cpp bitcoin-0.5.1-electrum/src/bitcoinrpc.cpp ---- bitcoin-0.5.1/src/bitcoinrpc.cpp 2011-12-13 22:56:26.000000000 +0200 -+++ bitcoin-0.5.1-electrum/src/bitcoinrpc.cpp 2011-12-27 22:44:06.494789148 +0200 -@@ -1362,7 +1362,43 @@ - return entry; - } - -+Value importtransaction(const Array& params, bool fHelp) -+{ -+ string hexdump; -+ if (fHelp || params.size() != 1 || (hexdump=params[0].get_str()).size()&1) -+ throw runtime_error( -+ "importtransaction <hexdata>\n" -+ "Import an offline transaction to announce it into the network"); -+ -+ std::vector<unsigned char> rawtx; -+ for (int i=0; i<hexdump.size(); i+=2) -+ { -+ int v; -+ if (sscanf(hexdump.substr(i,2).c_str(), "%x", &v)!=1) -+ throw JSONRPCError(-4, "Error in hex data."); -+ rawtx.push_back((unsigned char)v); -+ } -+try -+ { -+ CDataStream ss(rawtx); -+ CTransaction tx; -+ ss >> tx; -+ CInv inv(MSG_TX, tx.GetHash()); -+ if(! tx.AcceptToMemoryPool(true)) throw JSONRPCError(-4, "Transaction not accepted to memory pool."); -+ CDataStream msg(rawtx); -+ RelayMessage(inv, msg); -+ return tx.GetHash().GetHex(); -+ } -+ catch (std::exception& e) -+ { -+ throw JSONRPCError(-4, "Exception while parsing the transaction data."); -+ } -+ -+} -+ -+ - -+ - Value backupwallet(const Array& params, bool fHelp) - { - if (fHelp || params.size() != 1) -@@ -1846,6 +1882,7 @@ - make_pair("settxfee", &settxfee), - make_pair("getmemorypool", &getmemorypool), - make_pair("listsinceblock", &listsinceblock), -+ make_pair("importtransaction", &importtransaction), - }; - map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0])); - -diff -ur bitcoin-0.5.1/src/main.cpp bitcoin-0.5.1-electrum/src/main.cpp ---- bitcoin-0.5.1/src/main.cpp 2011-12-13 22:56:26.000000000 +0200 -+++ bitcoin-0.5.1-electrum/src/main.cpp 2011-12-27 22:44:18.714789152 +0200 -@@ -2820,16 +2820,19 @@ - - // Size limits - unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK); -- if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) -- continue; -+ //if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) -+ // continue; - int nTxSigOps = tx.GetSigOpCount(); -- if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) -- continue; -+ //if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) -+ // continue; - - // Transaction fee required depends on block size - bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority)); - int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true); - -+ // electrum server: do not check fees -+ nMinFee = 0; -+ - // Connecting shouldn't fail due to dependency on other memory pool transactions - // because we're already processing them in order of dependency - map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); diff --git a/server/patches/bitcoin-0.5.2.diff b/server/patches/bitcoin-0.5.2.diff @@ -1,82 +0,0 @@ -diff -ur bitcoin-0.5.2/src/bitcoinrpc.cpp bitcoin-0.5.2-electrum/src/bitcoinrpc.cpp ---- bitcoin-0.5.2/src/bitcoinrpc.cpp 2012-01-06 01:19:29.000000000 +0200 -+++ bitcoin-0.5.2-electrum/src/bitcoinrpc.cpp 2012-02-16 12:59:03.000000000 +0200 -@@ -1362,7 +1362,43 @@ - return entry; - } - -+Value importtransaction(const Array& params, bool fHelp) -+{ -+ string hexdump; -+ if (fHelp || params.size() != 1 || (hexdump=params[0].get_str()).size()&1) -+ throw runtime_error( -+ "importtransaction <hexdata>\n" -+ "Import an offline transaction to announce it into the network"); -+ -+ std::vector<unsigned char> rawtx; -+ for (int i=0; i<hexdump.size(); i+=2) -+ { -+ int v; -+ if (sscanf(hexdump.substr(i,2).c_str(), "%x", &v)!=1) -+ throw JSONRPCError(-4, "Error in hex data."); -+ rawtx.push_back((unsigned char)v); -+ } -+try -+ { -+ CDataStream ss(rawtx); -+ CTransaction tx; -+ ss >> tx; -+ CInv inv(MSG_TX, tx.GetHash()); -+ if(! tx.AcceptToMemoryPool(true)) throw JSONRPCError(-4, "Transaction not accepted to memory pool."); -+ CDataStream msg(rawtx); -+ RelayMessage(inv, msg); -+ return tx.GetHash().GetHex(); -+ } -+ catch (std::exception& e) -+ { -+ throw JSONRPCError(-4, "Exception while parsing the transaction data."); -+ } -+ -+} -+ -+ - -+ - Value backupwallet(const Array& params, bool fHelp) - { - if (fHelp || params.size() != 1) -@@ -1846,6 +1882,7 @@ - make_pair("settxfee", &settxfee), - make_pair("getmemorypool", &getmemorypool), - make_pair("listsinceblock", &listsinceblock), -+ make_pair("importtransaction", &importtransaction), - }; - map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0])); - -diff -ur bitcoin-0.5.2/src/main.cpp bitcoin-0.5.2-electrum/src/main.cpp ---- bitcoin-0.5.2/src/main.cpp 2012-01-06 01:19:29.000000000 +0200 -+++ bitcoin-0.5.2-electrum/src/main.cpp 2012-02-16 13:02:55.000000000 +0200 -@@ -2819,16 +2819,19 @@ - - // Size limits - unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK); -- if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) -- continue; -+ //if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) -+ // continue; - int nTxSigOps = tx.GetSigOpCount(); -- if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) -- continue; -+ //if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) -+ // continue; - - // Transaction fee required depends on block size - bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority)); - int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree); - -+ // Electrum server: do not check fees -+ nMinFee = 0; -+ - // Connecting shouldn't fail due to dependency on other memory pool transactions - // because we're already processing them in order of dependency - map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); diff --git a/server/patches/bitcoinrpc.cpp.diff b/server/patches/bitcoinrpc.cpp.diff @@ -1,52 +0,0 @@ -diff -u -r bitcoin/src/bitcoinrpc.cpp bitcoin-electrum/src/bitcoinrpc.cpp ---- bitcoin/src/bitcoinrpc.cpp 2011-12-28 21:23:40.844812872 +0200 -+++ bitcoin-electrum/src/bitcoinrpc.cpp 2011-12-28 17:31:24.000000000 +0200 -@@ -1437,6 +1437,38 @@ - return entry; - } - -+Value importtransaction(const Array& params, bool fHelp) -+{ -+ string hexdump; -+ if (fHelp || params.size() != 1 || (hexdump=params[0].get_str()).size()&1) -+ throw runtime_error( -+ "importtransaction <hexdata>\n" -+ "Import an offline transaction to announce it into the network"); -+ -+ std::vector<unsigned char> rawtx; -+ for (int i=0; i<hexdump.size(); i+=2) -+ { -+ int v; -+ if (sscanf(hexdump.substr(i,2).c_str(), "%x", &v)!=1) -+ throw JSONRPCError(-4, "Error in hex data."); -+ rawtx.push_back((unsigned char)v); -+ } -+try -+ { -+ CDataStream ss(rawtx); -+ CTransaction tx; -+ ss >> tx; -+ CInv inv(MSG_TX, tx.GetHash()); -+ if(! tx.AcceptToMemoryPool(true)) throw JSONRPCError(-4, "Transaction not accepted to memory pool."); -+ CDataStream msg(rawtx); -+ RelayMessage(inv, msg); -+ return tx.GetHash().GetHex(); -+ } -+ catch (std::exception& e) -+ { -+ throw JSONRPCError(-4, "Exception while parsing the transaction data."); -+ } -+} - - Value backupwallet(const Array& params, bool fHelp) - { -@@ -1950,7 +1982,8 @@ - make_pair("getmemorypool", &getmemorypool), - make_pair("listsinceblock", &listsinceblock), - make_pair("dumpprivkey", &dumpprivkey), -- make_pair("importprivkey", &importprivkey) -+ make_pair("importprivkey", &importprivkey), -+ make_pair("importtransaction", &importtransaction) - }; - map<string, rpcfn_type> mapCallTable(pCallTable, pCallTable + sizeof(pCallTable)/sizeof(pCallTable[0])); - diff --git a/server/patches/main.cpp.diff b/server/patches/main.cpp.diff @@ -1,33 +0,0 @@ -diff -u -r bitcoin/src/main.cpp bitcoin-electrum/src/main.cpp ---- bitcoin/src/main.cpp 2011-12-28 21:23:40.844812872 +0200 -+++ bitcoin-electrum/src/main.cpp 2011-12-28 17:47:27.000000000 +0200 -@@ -2965,13 +2965,16 @@ - - // Size limits - unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK); -- if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) -- continue; -+ //if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) -+ // continue; - - // Transaction fee required depends on block size - bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority)); - int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK); - -+ // Electrum server: do not check fees -+ nMinFee = 0; -+ - // Connecting shouldn't fail due to dependency on other memory pool transactions - // because we're already processing them in order of dependency - map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); -@@ -2981,8 +2984,8 @@ - int nTxSigOps = 0; - if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee)) - continue; -- if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) -- continue; -+ //if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) -+ // continue; - swap(mapTestPool, mapTestPoolTmp); - - // Added diff --git a/server/server.py b/server/server.py @@ -1,1001 +0,0 @@ -#!/usr/bin/env python -# Copyright(C) 2012 thomasv@gitorious - -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero 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 -# Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/agpl.html>. - -""" -Todo: - * server should check and return bitcoind status.. - * improve txpoint sorting - * command to check cache - - mempool transactions do not need to be added to the database; it slows it down -""" - - -from Abe.abe import hash_to_address, decode_check_address -from Abe.DataStore import DataStore as Datastore_class -from Abe import DataStore, readconf, BCDataStream, deserialize, util, base58 - -import psycopg2, binascii - -import thread, traceback, sys, urllib, operator -from json import dumps, loads - - -class MyStore(Datastore_class): - - def __init__(self, config, address_queue): - conf = DataStore.CONFIG_DEFAULTS - args, argv = readconf.parse_argv( [], conf) - args.dbtype = config.get('database','type') - if args.dbtype == 'sqlite3': - args.connect_args = { 'database' : config.get('database','database') } - elif args.dbtype == 'MySQLdb': - args.connect_args = { 'db' : config.get('database','database'), 'user' : config.get('database','username'), 'passwd' : config.get('database','password') } - elif args.dbtype == 'psycopg2': - args.connect_args = { 'database' : config.get('database','database') } - - Datastore_class.__init__(self,args) - - self.tx_cache = {} - self.mempool_keys = {} - self.bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind','user'), config.get('bitcoind','password'), config.get('bitcoind','host'), config.get('bitcoind','port')) - - self.address_queue = address_queue - self.dblock = thread.allocate_lock() - - - - def import_block(self, b, chain_ids=frozenset()): - block_id = super(MyStore, self).import_block(b, chain_ids) - for pos in xrange(len(b['transactions'])): - tx = b['transactions'][pos] - if 'hash' not in tx: - tx['hash'] = util.double_sha256(tx['tx']) - tx_id = store.tx_find_id_and_value(tx) - if tx_id: - self.update_tx_cache(tx_id) - else: - print "error: import_block: no tx_id" - return block_id - - - def update_tx_cache(self, txid): - inrows = self.get_tx_inputs(txid, False) - for row in inrows: - _hash = self.binout(row[6]) - address = hash_to_address(chr(0), _hash) - if self.tx_cache.has_key(address): - print "cache: invalidating", address - self.tx_cache.pop(address) - self.address_queue.put(address) - - outrows = self.get_tx_outputs(txid, False) - for row in outrows: - _hash = self.binout(row[6]) - address = hash_to_address(chr(0), _hash) - if self.tx_cache.has_key(address): - print "cache: invalidating", address - self.tx_cache.pop(address) - self.address_queue.put(address) - - def safe_sql(self,sql, params=(), lock=True): - try: - if lock: self.dblock.acquire() - ret = self.selectall(sql,params) - if lock: self.dblock.release() - return ret - except: - print "sql error", sql - return [] - - def get_tx_outputs(self, tx_id, lock=True): - return self.safe_sql("""SELECT - txout.txout_pos, - txout.txout_scriptPubKey, - txout.txout_value, - nexttx.tx_hash, - nexttx.tx_id, - txin.txin_pos, - pubkey.pubkey_hash - FROM txout - LEFT JOIN txin ON (txin.txout_id = txout.txout_id) - LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id) - LEFT JOIN tx nexttx ON (txin.tx_id = nexttx.tx_id) - WHERE txout.tx_id = %d - ORDER BY txout.txout_pos - """%(tx_id), (), lock) - - def get_tx_inputs(self, tx_id, lock=True): - return self.safe_sql(""" SELECT - txin.txin_pos, - txin.txin_scriptSig, - txout.txout_value, - COALESCE(prevtx.tx_hash, u.txout_tx_hash), - prevtx.tx_id, - COALESCE(txout.txout_pos, u.txout_pos), - pubkey.pubkey_hash - FROM txin - LEFT JOIN txout ON (txout.txout_id = txin.txout_id) - LEFT JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id) - LEFT JOIN tx prevtx ON (txout.tx_id = prevtx.tx_id) - LEFT JOIN unlinked_txin u ON (u.txin_id = txin.txin_id) - WHERE txin.tx_id = %d - ORDER BY txin.txin_pos - """%(tx_id,), (), lock) - - def get_address_out_rows(self, dbhash): - return self.safe_sql(""" SELECT - b.block_nTime, - cc.chain_id, - b.block_height, - 1, - b.block_hash, - tx.tx_hash, - tx.tx_id, - txin.txin_pos, - -prevout.txout_value - FROM chain_candidate cc - JOIN block b ON (b.block_id = cc.block_id) - JOIN block_tx ON (block_tx.block_id = b.block_id) - JOIN tx ON (tx.tx_id = block_tx.tx_id) - JOIN txin ON (txin.tx_id = tx.tx_id) - JOIN txout prevout ON (txin.txout_id = prevout.txout_id) - JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id) - WHERE pubkey.pubkey_hash = ? - AND cc.in_longest = 1""", (dbhash,)) - - def get_address_out_rows_memorypool(self, dbhash): - return self.safe_sql(""" SELECT - 1, - tx.tx_hash, - tx.tx_id, - txin.txin_pos, - -prevout.txout_value - FROM tx - JOIN txin ON (txin.tx_id = tx.tx_id) - JOIN txout prevout ON (txin.txout_id = prevout.txout_id) - JOIN pubkey ON (pubkey.pubkey_id = prevout.pubkey_id) - WHERE pubkey.pubkey_hash = ? """, (dbhash,)) - - def get_address_in_rows(self, dbhash): - return self.safe_sql(""" SELECT - b.block_nTime, - cc.chain_id, - b.block_height, - 0, - b.block_hash, - tx.tx_hash, - tx.tx_id, - txout.txout_pos, - txout.txout_value - FROM chain_candidate cc - JOIN block b ON (b.block_id = cc.block_id) - JOIN block_tx ON (block_tx.block_id = b.block_id) - JOIN tx ON (tx.tx_id = block_tx.tx_id) - JOIN txout ON (txout.tx_id = tx.tx_id) - JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id) - WHERE pubkey.pubkey_hash = ? - AND cc.in_longest = 1""", (dbhash,)) - - def get_address_in_rows_memorypool(self, dbhash): - return self.safe_sql( """ SELECT - 0, - tx.tx_hash, - tx.tx_id, - txout.txout_pos, - txout.txout_value - FROM tx - JOIN txout ON (txout.tx_id = tx.tx_id) - JOIN pubkey ON (pubkey.pubkey_id = txout.pubkey_id) - WHERE pubkey.pubkey_hash = ? """, (dbhash,)) - - def get_history(self, addr): - - cached_version = self.tx_cache.get( addr ) - if cached_version is not None: - return cached_version - - version, binaddr = decode_check_address(addr) - if binaddr is None: - return None - - dbhash = self.binin(binaddr) - rows = [] - rows += self.get_address_out_rows( dbhash ) - rows += self.get_address_in_rows( dbhash ) - - txpoints = [] - known_tx = [] - - for row in rows: - try: - nTime, chain_id, height, is_in, blk_hash, tx_hash, tx_id, pos, value = row - except: - print "cannot unpack row", row - break - tx_hash = self.hashout_hex(tx_hash) - txpoint = { - "nTime": int(nTime), - "height": int(height), - "is_in": int(is_in), - "blk_hash": self.hashout_hex(blk_hash), - "tx_hash": tx_hash, - "tx_id": int(tx_id), - "pos": int(pos), - "value": int(value), - } - - txpoints.append(txpoint) - known_tx.append(self.hashout_hex(tx_hash)) - - - # todo: sort them really... - txpoints = sorted(txpoints, key=operator.itemgetter("nTime")) - - # read memory pool - rows = [] - rows += self.get_address_in_rows_memorypool( dbhash ) - rows += self.get_address_out_rows_memorypool( dbhash ) - address_has_mempool = False - - for row in rows: - is_in, tx_hash, tx_id, pos, value = row - tx_hash = self.hashout_hex(tx_hash) - if tx_hash in known_tx: - continue - - # this means that pending transactions were added to the db, even if they are not returned by getmemorypool - address_has_mempool = True - - # this means pending transactions are returned by getmemorypool - if tx_hash not in self.mempool_keys: - continue - - #print "mempool", tx_hash - txpoint = { - "nTime": 0, - "height": 0, - "is_in": int(is_in), - "blk_hash": 'mempool', - "tx_hash": tx_hash, - "tx_id": int(tx_id), - "pos": int(pos), - "value": int(value), - } - txpoints.append(txpoint) - - - for txpoint in txpoints: - tx_id = txpoint['tx_id'] - - txinputs = [] - inrows = self.get_tx_inputs(tx_id) - for row in inrows: - _hash = self.binout(row[6]) - address = hash_to_address(chr(0), _hash) - txinputs.append(address) - txpoint['inputs'] = txinputs - txoutputs = [] - outrows = self.get_tx_outputs(tx_id) - for row in outrows: - _hash = self.binout(row[6]) - address = hash_to_address(chr(0), _hash) - txoutputs.append(address) - txpoint['outputs'] = txoutputs - - # for all unspent inputs, I want their scriptpubkey. (actually I could deduce it from the address) - if not txpoint['is_in']: - # detect if already redeemed... - for row in outrows: - if row[6] == dbhash: break - else: - raise - #row = self.get_tx_output(tx_id,dbhash) - # pos, script, value, o_hash, o_id, o_pos, binaddr = row - # if not redeemed, we add the script - if row: - if not row[4]: txpoint['raw_scriptPubKey'] = row[1] - - # cache result - if not address_has_mempool: - self.tx_cache[addr] = txpoints - - return txpoints - - - - def memorypool_update(store): - - ds = BCDataStream.BCDataStream() - previous_transactions = store.mempool_keys - store.mempool_keys = [] - - postdata = dumps({"method": 'getmemorypool', 'params': [], 'id':'jsonrpc'}) - - respdata = urllib.urlopen(store.bitcoind_url, postdata).read() - r = loads(respdata) - if r['error'] != None: - return - - v = r['result'].get('transactions') - for hextx in v: - ds.clear() - ds.write(hextx.decode('hex')) - tx = deserialize.parse_Transaction(ds) - tx['hash'] = util.double_sha256(tx['tx']) - tx_hash = store.hashin(tx['hash']) - - def send_tx(self,tx): - postdata = dumps({"method": 'importtransaction', 'params': [tx], 'id':'jsonrpc'}) - respdata = urllib.urlopen(self.bitcoind_url, postdata).read() - r = loads(respdata) - if r['error'] != None: - out = "error: transaction rejected by memorypool\n"+tx - else: - out = r['result'] - return out - - - def main_iteration(store): - try: - store.dblock.acquire() - store.catch_up() - store.memorypool_update() - block_number = store.get_block_number(1) - - except IOError: - print "IOError: cannot reach bitcoind" - block_number = 0 - except: - traceback.print_exc(file=sys.stdout) - block_number = 0 - finally: - store.dblock.release() - - return block_number - - - -import time, json, socket, operator, thread, ast, sys, re, traceback -import ConfigParser -from json import dumps, loads -import urllib - - -config = ConfigParser.ConfigParser() -# set some defaults, which will be overwritten by the config file -config.add_section('server') -config.set('server','banner', 'Welcome to Electrum!') -config.set('server', 'host', 'localhost') -config.set('server', 'port', '50000') -config.set('server', 'password', '') -config.set('server', 'irc', 'yes') -config.set('server', 'ircname', 'Electrum server') -config.add_section('database') -config.set('database', 'type', 'psycopg2') -config.set('database', 'database', 'abe') - -try: - f = open('/etc/electrum.conf','r') - config.readfp(f) - f.close() -except: - print "Could not read electrum.conf. I will use the default values." - -try: - f = open('/etc/electrum.banner','r') - config.set('server','banner', f.read()) - f.close() -except: - pass - - -password = config.get('server','password') - -stopping = False -block_number = -1 -sessions = {} -sessions_sub_numblocks = {} # sessions that have subscribed to the service - -m_sessions = [{}] # served by http - -peer_list = {} - -wallets = {} # for ultra-light clients such as bccapi - -from Queue import Queue -input_queue = Queue() -output_queue = Queue() -address_queue = Queue() - - - - - - - -def random_string(N): - import random, string - return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N)) - - - -def cmd_stop(_,__,pw): - global stopping - if password == pw: - stopping = True - return 'ok' - else: - return 'wrong password' - -def cmd_load(_,__,pw): - if password == pw: - return repr( len(sessions) ) - else: - return 'wrong password' - - - - - -def modified_addresses(session): - if 1: - t1 = time.time() - addresses = session['addresses'] - session['last_time'] = time.time() - ret = {} - k = 0 - for addr in addresses: - status = get_address_status( addr ) - msg_id, last_status = addresses.get( addr ) - if last_status != status: - addresses[addr] = msg_id, status - ret[addr] = status - - t2 = time.time() - t1 - #if t2 > 10: print "high load:", session_id, "%d/%d"%(k,len(addresses)), t2 - return ret, addresses - - -def poll_session(session_id): - # native - session = sessions.get(session_id) - if session is None: - print time.asctime(), "session not found", session_id - return -1, {} - else: - ret, addresses = modified_addresses(session) - if ret: sessions[session_id]['addresses'] = addresses - return repr( (block_number,ret)) - - -def poll_session_json(session_id, message_id): - session = m_sessions[0].get(session_id) - if session is None: - raise BaseException("session not found %s"%session_id) - else: - out = [] - ret, addresses = modified_addresses(session) - if ret: - m_sessions[0][session_id]['addresses'] = addresses - for addr in ret: - msg_id, status = addresses[addr] - out.append( { 'id':msg_id, 'result':status } ) - - msg_id, last_nb = session.get('numblocks') - if last_nb: - if last_nb != block_number: - m_sessions[0][session_id]['numblocks'] = msg_id, block_number - out.append( {'id':msg_id, 'result':block_number} ) - - return out - - -def do_update_address(addr): - # an address was involved in a transaction; we check if it was subscribed to in a session - # the address can be subscribed in several sessions; the cache should ensure that we don't do redundant requests - - for session_id in sessions.keys(): - session = sessions[session_id] - if session.get('type') != 'persistent': continue - addresses = session['addresses'].keys() - - if addr in addresses: - status = get_address_status( addr ) - message_id, last_status = session['addresses'][addr] - if last_status != status: - #print "sending new status for %s:"%addr, status - send_status(session_id,message_id,addr,status) - sessions[session_id]['addresses'][addr] = (message_id,status) - -def get_address_status(addr): - # get address status, i.e. the last block for that address. - tx_points = store.get_history(addr) - if not tx_points: - status = None - else: - lastpoint = tx_points[-1] - status = lastpoint['blk_hash'] - # this is a temporary hack; move it up once old clients have disappeared - if status == 'mempool': # and session['version'] != "old": - status = status + ':%d'% len(tx_points) - return status - - -def send_numblocks(session_id): - message_id = sessions_sub_numblocks[session_id] - out = json.dumps( {'id':message_id, 'result':block_number} ) - output_queue.put((session_id, out)) - -def send_status(session_id, message_id, address, status): - out = json.dumps( { 'id':message_id, 'result':status } ) - output_queue.put((session_id, out)) - -def address_get_history_json(_,message_id,address): - return store.get_history(address) - -def subscribe_to_numblocks(session_id, message_id): - sessions_sub_numblocks[session_id] = message_id - send_numblocks(session_id) - -def subscribe_to_numblocks_json(session_id, message_id): - global m_sessions - m_sessions[0][session_id]['numblocks'] = message_id,block_number - return block_number - -def subscribe_to_address(session_id, message_id, address): - status = get_address_status(address) - sessions[session_id]['addresses'][address] = (message_id, status) - sessions[session_id]['last_time'] = time.time() - send_status(session_id, message_id, address, status) - -def add_address_to_session_json(session_id, message_id, address): - global m_sessions - sessions = m_sessions[0] - status = get_address_status(address) - sessions[session_id]['addresses'][address] = (message_id, status) - sessions[session_id]['last_time'] = time.time() - m_sessions[0] = sessions - return status - -def add_address_to_session(session_id, address): - status = get_address_status(address) - sessions[session_id]['addresses'][address] = ("", status) - sessions[session_id]['last_time'] = time.time() - return status - -def new_session(version, addresses): - session_id = random_string(10) - sessions[session_id] = { 'addresses':{}, 'version':version } - for a in addresses: - sessions[session_id]['addresses'][a] = ('','') - out = repr( (session_id, config.get('server','banner').replace('\\n','\n') ) ) - sessions[session_id]['last_time'] = time.time() - return out - - -def client_version_json(session_id, _, version): - global m_sessions - sessions = m_sessions[0] - sessions[session_id]['version'] = version - m_sessions[0] = sessions - -def create_session_json(_, __): - sessions = m_sessions[0] - session_id = random_string(10) - print "creating session", session_id - sessions[session_id] = { 'addresses':{}, 'numblocks':('','') } - sessions[session_id]['last_time'] = time.time() - m_sessions[0] = sessions - return session_id - - - -def get_banner(_,__): - return config.get('server','banner').replace('\\n','\n') - -def update_session(session_id,addresses): - """deprecated in 0.42""" - sessions[session_id]['addresses'] = {} - for a in addresses: - sessions[session_id]['addresses'][a] = '' - sessions[session_id]['last_time'] = time.time() - return 'ok' - -def native_server_thread(): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind((config.get('server','host'), config.getint('server','port'))) - s.listen(1) - while not stopping: - conn, addr = s.accept() - try: - thread.start_new_thread(native_client_thread, (addr, conn,)) - except: - # can't start new thread if there is no memory.. - traceback.print_exc(file=sys.stdout) - - -def native_client_thread(ipaddr,conn): - #print "client thread", ipaddr - try: - ipaddr = ipaddr[0] - msg = '' - while 1: - d = conn.recv(1024) - msg += d - if not d: - break - if '#' in msg: - msg = msg.split('#', 1)[0] - break - try: - cmd, data = ast.literal_eval(msg) - except: - print "syntax error", repr(msg), ipaddr - conn.close() - return - - out = do_command(cmd, data, ipaddr) - if out: - #print ipaddr, cmd, len(out) - try: - conn.send(out) - except: - print "error, could not send" - - finally: - conn.close() - - -def timestr(): - return time.strftime("[%d/%m/%Y-%H:%M:%S]") - -# used by the native handler -def do_command(cmd, data, ipaddr): - - if cmd=='b': - out = "%d"%block_number - - elif cmd in ['session','new_session']: - try: - if cmd == 'session': - addresses = ast.literal_eval(data) - version = "old" - else: - version, addresses = ast.literal_eval(data) - if version[0]=="0": version = "v" + version - except: - print "error", data - return None - print timestr(), "new session", ipaddr, addresses[0] if addresses else addresses, len(addresses), version - out = new_session(version, addresses) - - elif cmd=='address.subscribe': - try: - session_id, addr = ast.literal_eval(data) - except: - traceback.print_exc(file=sys.stdout) - print data - return None - out = add_address_to_session(session_id,addr) - - elif cmd=='update_session': - try: - session_id, addresses = ast.literal_eval(data) - except: - traceback.print_exc(file=sys.stdout) - return None - print timestr(), "update session", ipaddr, addresses[0] if addresses else addresses, len(addresses) - out = update_session(session_id,addresses) - - elif cmd=='poll': - out = poll_session(data) - - elif cmd == 'h': - # history - address = data - out = repr( store.get_history( address ) ) - - elif cmd == 'load': - out = cmd_load(None,None,data) - - elif cmd =='tx': - out = store.send_tx(data) - print timestr(), "sent tx:", ipaddr, out - - elif cmd == 'stop': - out = cmd_stop(data) - - elif cmd == 'peers': - out = repr(peer_list.values()) - - else: - out = None - - return out - - - -#################################################################### - -def tcp_server_thread(): - thread.start_new_thread(process_input_queue, ()) - thread.start_new_thread(process_output_queue, ()) - - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind((config.get('server','host'), 50001)) - s.listen(1) - while not stopping: - conn, addr = s.accept() - try: - thread.start_new_thread(tcp_client_thread, (addr, conn,)) - except: - # can't start new thread if there is no memory.. - traceback.print_exc(file=sys.stdout) - - -def close_session(session_id): - #print "lost connection", session_id - sessions.pop(session_id) - if session_id in sessions_sub_numblocks: - sessions_sub_numblocks.pop(session_id) - - -# one thread per client. put requests in a queue. -def tcp_client_thread(ipaddr,conn): - """ use a persistent connection. put commands in a queue.""" - - print timestr(), "TCP session", ipaddr - global sessions - - session_id = random_string(10) - sessions[session_id] = { 'conn':conn, 'addresses':{}, 'version':'unknown', 'type':'persistent' } - - ipaddr = ipaddr[0] - msg = '' - - while not stopping: - try: - d = conn.recv(1024) - except socket.error: - d = '' - if not d: - close_session(session_id) - break - - msg += d - while True: - s = msg.find('\n') - if s ==-1: - break - else: - c = msg[0:s].strip() - msg = msg[s+1:] - if c == 'quit': - conn.close() - close_session(session_id) - return - try: - c = json.loads(c) - except: - print "json error", repr(c) - continue - try: - message_id = c.get('id') - method = c.get('method') - params = c.get('params') - except: - print "syntax error", repr(c), ipaddr - continue - - # add to queue - input_queue.put((session_id, message_id, method, params)) - - - -# read commands from the input queue. perform requests, etc. this should be called from the main thread. -def process_input_queue(): - while not stopping: - session_id, message_id, method, data = input_queue.get() - if session_id not in sessions.keys(): - continue - out = None - if method == 'address.subscribe': - address = data[0] - subscribe_to_address(session_id,message_id,address) - elif method == 'numblocks.subscribe': - subscribe_to_numblocks(session_id,message_id) - elif method == 'client.version': - sessions[session_id]['version'] = data[0] - elif method == 'server.banner': - out = { 'result':config.get('server','banner').replace('\\n','\n') } - elif method == 'server.peers': - out = { 'result':peer_list.values() } - elif method == 'address.get_history': - address = data[0] - out = { 'result':store.get_history( address ) } - elif method == 'transaction.broadcast': - postdata = dumps({"method": 'importtransaction', 'params': [data], 'id':'jsonrpc'}) - txo = urllib.urlopen(bitcoind_url, postdata).read() - print "sent tx:", txo - out = json.loads(txo) - else: - print "unknown command", method - if out: - out['id'] = message_id - out = json.dumps( out ) - output_queue.put((session_id, out)) - -# this is a separate thread -def process_output_queue(): - while not stopping: - session_id, out = output_queue.get() - session = sessions.get(session_id) - if session: - try: - conn = session.get('conn') - conn.send(out+'\n') - except: - close_session(session_id) - - - - -#################################################################### - - - - -def clean_session_thread(): - while not stopping: - time.sleep(30) - t = time.time() - for k,s in sessions.items(): - if s.get('type') == 'persistent': continue - t0 = s['last_time'] - if t - t0 > 5*60: - sessions.pop(k) - print "lost session", k - - -def irc_thread(): - global peer_list - NICK = 'E_'+random_string(10) - while not stopping: - try: - s = socket.socket() - s.connect(('irc.freenode.net', 6667)) - s.send('USER electrum 0 * :'+config.get('server','host')+' '+config.get('server','ircname')+'\n') - s.send('NICK '+NICK+'\n') - s.send('JOIN #electrum\n') - sf = s.makefile('r', 0) - t = 0 - while not stopping: - line = sf.readline() - line = line.rstrip('\r\n') - line = line.split() - if line[0]=='PING': - s.send('PONG '+line[1]+'\n') - elif '353' in line: # answer to /names - k = line.index('353') - for item in line[k+1:]: - if item[0:2] == 'E_': - s.send('WHO %s\n'%item) - elif '352' in line: # answer to /who - # warning: this is a horrible hack which apparently works - k = line.index('352') - ip = line[k+4] - ip = socket.gethostbyname(ip) - name = line[k+6] - host = line[k+9] - peer_list[name] = (ip,host) - if time.time() - t > 5*60: - s.send('NAMES #electrum\n') - t = time.time() - peer_list = {} - except: - traceback.print_exc(file=sys.stdout) - finally: - sf.close() - s.close() - - -def get_peers_json(_,__): - return peer_list.values() - -def http_server_thread(): - # see http://code.google.com/p/jsonrpclib/ - from SocketServer import ThreadingMixIn - from StratumJSONRPCServer import StratumJSONRPCServer - class StratumThreadedJSONRPCServer(ThreadingMixIn, StratumJSONRPCServer): pass - server = StratumThreadedJSONRPCServer(( config.get('server','host'), 8081)) - server.register_function(get_peers_json, 'server.peers') - server.register_function(cmd_stop, 'stop') - server.register_function(cmd_load, 'load') - server.register_function(get_banner, 'server.banner') - server.register_function(lambda a,b,c: store.send_tx(c), 'transaction.broadcast') - server.register_function(address_get_history_json, 'address.get_history') - server.register_function(add_address_to_session_json, 'address.subscribe') - server.register_function(subscribe_to_numblocks_json, 'numblocks.subscribe') - server.register_function(client_version_json, 'client.version') - server.register_function(create_session_json, 'session.create') # internal message (not part of protocol) - server.register_function(poll_session_json, 'session.poll') # internal message (not part of protocol) - server.serve_forever() - - -if __name__ == '__main__': - - if len(sys.argv)>1: - import jsonrpclib - server = jsonrpclib.Server('http://%s:8081'%config.get('server','host')) - cmd = sys.argv[1] - if cmd == 'load': - out = server.load(password) - elif cmd == 'peers': - out = server.server.peers() - elif cmd == 'stop': - out = server.stop(password) - elif cmd == 'clear_cache': - out = server.clear_cache(password) - elif cmd == 'get_cache': - out = server.get_cache(password,sys.argv[2]) - elif cmd == 'h': - out = server.address.get_history(sys.argv[2]) - elif cmd == 'tx': - out = server.transaction.broadcast(sys.argv[2]) - elif cmd == 'b': - out = server.numblocks.subscribe() - else: - out = "Unknown command: '%s'" % cmd - print out - sys.exit(0) - - # backend - # from db import MyStore - store = MyStore(config,address_queue) - - # supported protocols - thread.start_new_thread(native_server_thread, ()) - thread.start_new_thread(tcp_server_thread, ()) - thread.start_new_thread(http_server_thread, ()) - thread.start_new_thread(clean_session_thread, ()) - - if (config.get('server','irc') == 'yes' ): - thread.start_new_thread(irc_thread, ()) - - print "starting Electrum server" - - old_block_number = None - while not stopping: - block_number = store.main_iteration() - - if block_number != old_block_number: - old_block_number = block_number - for session_id in sessions_sub_numblocks.keys(): - send_numblocks(session_id) - while True: - try: - addr = address_queue.get(False) - except: - break - do_update_address(addr) - - time.sleep(10) - print "server stopped" - diff --git a/server/start b/server/start @@ -1,2 +0,0 @@ -#!/bin/bash -nohup /usr/bin/python -u server.py &>> /var/log/electrum.log & diff --git a/server/stop b/server/stop @@ -1,2 +0,0 @@ -#!/bin/bash -/usr/bin/python server.py stop