diff --git a/HOWTO.md b/HOWTO.md index eab9100b..8a9e711f 100644 --- a/HOWTO.md +++ b/HOWTO.md @@ -12,7 +12,7 @@ requirements. The most up-to date version of this document is available at: - https://github.com/spesmilo/electrum-server/blob/master/HOWTO.md + https://github.com/sherlockcoin/electrum-navcoin-server/blob/master/HOWTO.md Conventions ----------- @@ -20,20 +20,20 @@ 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. +document, we assume that user is called 'litecoin'). We also assume the +litecoin 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, -\ should be replaced by a password. Do not confuse this -notation with shell redirection (`command < file` or `command > file`)! +\ should be replaced by a user chosen password. Do not confuse this +notation with shell redirection ('command < file' or 'command > file')! Lines that lack hash or dollar signs are pastes from config files. They should be copied verbatim or adapted without the indentation tab. -`apt-get install` commands are suggestions for required dependencies. -They conform to an Ubuntu 15.10 system but may well work with Debian -or other versions of Ubuntu. +apt-get install commands are suggestions for required dependencies. +They conform to an Ubuntu 13.10 system but may well work with Debian +or earlier and later versions of Ubuntu. Prerequisites ------------- @@ -52,125 +52,117 @@ installed: `python`, `easy_install`, `git`, standard C/C++ build chain. You will need root access in order to install other software or Python libraries. Python 2.7 is the minimum supported version. -**Hardware.** The lightest setup is a pruning server with diskspace -requirements of about 30 GB for the Electrum database (February 2016). However note that -you also need to run bitcoind and keep a copy of the full blockchain, -which is roughly 55 GB (February 2016). Ideally you have a machine with 16 GB of RAM -and an equal amount of swap. If you have ~2 GB of RAM make sure you limit bitcoind -to 8 concurrent connections by disabling incoming connections. electrum-server may -bail-out on you from time to time with less than 4 GB of RAM, so you might have to -monitor the process and restart it. You can tweak cache sizes in the config to an extend -but most RAM will be used to process blocks and catch-up on initial start. - -CPU speed is less important than fast I/O speed. electrum-server makes uses of one core -only leaving spare cycles for bitcoind. Fast single core CPU power helps for the initial -block chain import. Any multi-core x86 CPU with CPU Mark / PassMark > 1500 will work -(see https://www.cpubenchmark.net/). An ideal setup in February 2016 has 16 GB+ RAM and -SSD for good i/o speed. +**Hardware.** The lightest setup is a pruning server with diskspace +requirements of about 4 GB for the electrum database. However note that +you also need to run litecoind and keep a copy of the full blockchain, +which is roughly 4 GB in April 2014. If you have less than 2 GB of RAM +make sure you limit litecoind to 8 concurrent connections. If you have more +resources to spare you can run the server with a higher limit of historic +transactions per address. CPU speed is important for the initial block +chain import, but is also important if you plan to run a public Electrum server, +which could serve tens of concurrent requests. Any multi-core x86 CPU from 2009 or +newer other than an Atom should do for good performance. An ideal setup +has enough RAM to hold and process the leveldb database in tmpfs (e.g. /dev/shm). Instructions ------------ -### Step 1. Create a user for running bitcoind and Electrum server +### Step 1. Create a user for running litecoind 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. +suggest you create a separate user just for running `litecoind` 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 --disabled-password + $ sudo adduser litecoin --disabled-password $ sudo apt-get install git - $ sudo su - bitcoin + $ sudo su - litecoin $ mkdir ~/bin ~/src $ echo $PATH -If you don't see `/home/bitcoin/bin` in the output, you should add this line +If you don't see `/home/litecoin/bin` in the output, you should add this line to your `.bashrc`, `.profile`, or `.bash_profile`, then logout and relogin: PATH="$HOME/bin:$PATH" $ exit -### Step 2. Download bitcoind +### Step 2. Download litecoind -We currently recommend bitcoin core 0.12.1 stable. If your package manager does not supply -a recent bitcoind or you prefer to compile it yourself, here are some pointers for Ubuntu: +We currently recommend litecoind 0.10.1.3 or 0.8.7.5 stable. - $ sudo apt-get install make g++ python-leveldb libboost-all-dev libssl-dev libdb++-dev pkg-config libevent-dev - $ sudo su - bitcoin - $ cd ~/src && wget https://bitcoin.org/bin/bitcoin-core-0.12.1/bitcoin-0.12.1.tar.gz - $ sha256sum bitcoin-0.12.1.tar.gz | grep 08fc3b6c05c39fb975bba1f6dd49992df46511790ce8dc67398208af9565e199 - $ tar xfz bitcoin-0.12.1.tar.gz - $ cd bitcoin-0.12.1 +If you prefer to compile litecoind, here are some pointers for Ubuntu: + + $ sudo apt-get install make g++ python-leveldb libboost-all-dev libssl-dev libdb++-dev pkg-config automake libtool + $ sudo su - litecoin + $ cd ~/src && git clone https://github.com/litecoin-project/litecoin.git -b master-0.10 + $ cd litecoin + $ ./autogen.sh $ ./configure --disable-wallet --without-miniupnpc $ make - $ strip src/bitcoind src/bitcoin-cli src/bitcoin-tx - $ cp -a src/bitcoind src/bitcoin-cli src/bitcoin-tx ~/bin + $ strip src/litecoind src/litecoin-cli src/litecoin-tx + $ cp -a src/litecoind src/litecoin-cli src/litecoin-tx ~/bin -### Step 3. Configure and start bitcoind +### Step 3. Configure and start litecoind -In order to allow Electrum to "talk" to `bitcoind`, we need to set up an RPC -username and password for `bitcoind`. We will then start `bitcoind` and +In order to allow Electrum to "talk" to `litecoind`, we need to set up an RPC +username and password for `litecoind`. We will then start `litecoind` and wait for it to complete downloading the blockchain. - $ mkdir ~/.bitcoin - $ $EDITOR ~/.bitcoin/bitcoin.conf + $ mkdir ~/.litecoin + $ $EDITOR ~/.litecoin/litecoin.conf -Write this in `bitcoin.conf`: +Write this in `litecoin.conf`: rpcuser= rpcpassword= daemon=1 txindex=1 + disablewallet=1 -If you have an existing installation of bitcoind and have not previously +If you have an existing installation of litecoind and have not previously set txindex=1 you need to reindex the blockchain by running - $ bitcoind -reindex + $ litecoind -reindex -If you already have a freshly indexed copy of the blockchain with txindex start `bitcoind`: +If you already have a freshly indexed copy of the blockchain with txindex start `litecoind`: - $ bitcoind + $ litecoind -Allow some time to pass for `bitcoind` to connect to the network and start +Allow some time to pass, so `litecoind` connects to the network and starts downloading blocks. You can check its progress by running: - $ bitcoin-cli getblockchaininfo + $ litecoin-cli getinfo -Before starting the Electrum server your bitcoind should have processed all +Before starting the electrum server your litecoind should have processed all blocks and caught up to the current height of the network (not just the headers). -You should also set up your system to automatically start bitcoind at boot -time, running as the 'bitcoin' user. Check your system documentation to +You should also set up your system to automatically start litecoind at boot +time, running as the 'litecoin' user. Check your system documentation to find out the best way to do this. -### Step 4. Download and install Electrum server +### Step 4. Download and install Electrum Server We will download the latest git snapshot for Electrum to configure and install it: $ cd ~ - $ git clone https://github.com/spesmilo/electrum-server.git - $ cd electrum-server - $ sudo apt-get install python-setuptools - $ sudo ./configure + $ git clone https://github.com/sherlockcoin/electrum-navcoin-server.git + $ cd electrum-navcoin-server + $ sudo configure $ sudo python setup.py install -See the INSTALL file for more information about the configure and install commands. +See the INSTALL file for more information about the configure and install commands. ### Optional Step 5: Install Electrum dependencies manually Electrum server depends on various standard Python libraries and leveldb. These will usually be -installed by calling `python setup.py install` above. They can be also be installed with your -package manager if you don't want to use the install routine. +installed by caling "python setup.py install" above. They can be also be installed with your +package manager if you don't want to use the install routine - $ sudo apt-get install python-setuptools python-openssl python-leveldb libleveldb-dev + $ sudo apt-get install python-setuptools python-openssl python-leveldb libleveldb-dev $ sudo easy_install jsonrpclib irc plyvel -For the python irc module please note electrum-server currently only supports versions between 11 and 14.0. -The setup.py takes care of installing a supported version but be aware of it when installing or upgrading -manually. - -Regarding leveldb, see the steps in README.leveldb for further details, especially if your system +Regarding leveldb see the steps in README.leveldb for further details, especially if your system doesn't have the python-leveldb package or if plyvel installation fails. leveldb should be at least version 1.9.0. Earlier version are believed to be buggy. @@ -198,17 +190,17 @@ The section in the electrum server configuration file (see step 10) looks like t ### Step 7. Import blockchain into the database or download it -It's recommended that you fetch a pre-processed leveldb from the net. +It's recommended to fetch a pre-processed leveldb from the net. The "configure" script above will offer you to download a database with pruning limit 100. -You can fetch recent copies of electrum leveldb databases with different pruning limits -and further instructions from the Electrum full archival server foundry at: -http://foundry.electrum.org/ +You can fetch recent copies of electrum leveldb databases with differnt pruning limits +and further instructions from the Electrum-LTC full archival server foundry at: +http://foundry.electrum-ltc.org/leveldb-dump/ Alternatively, if you have the time and nerve, you can import the blockchain yourself. -As of April 2014 it takes between two days and over a week to import 300k blocks, depending +As of April 2014 it takes between one and two days to import 500k blocks, depending on CPU speed, I/O speed, and your selected pruning limit. It's considerably faster and strongly recommended to index in memory. You can use /dev/shm or @@ -216,28 +208,28 @@ or create a tmpfs which will also use swap if you run out of memory: $ sudo mount -t tmpfs -o rw,nodev,nosuid,noatime,size=15000M,mode=0777 none /tmpfs -If you use tmpfs make sure you have enough RAM and swap to cover the size. If you only have 4 GB of -RAM but add 15 GB of swap from a file that's fine too; tmpfs is smart enough to swap out the least +If you use tmpfs make sure you have enough RAM and swap to cover the size. If you only have 2 gigs of +RAM but add 15 gigs of swap from a file that's fine too. tmpfs is rather smart to swap out the least used parts. It's fine to use a file on an SSD for swap in this case. -It's not recommended to do initial indexing of the database on an SSD because the indexing process -does at least 20 TB (!) of disk writes and puts considerable wear-and-tear on an SSD. It's a lot better -to use tmpfs and just swap out to disk when necessary. +It's not recommended to do initial indexing of the database on a SSD because the indexing process +does at least 10 TB (!) of disk writes and puts considerable wear-and-tear on an SSD. It's a lot better +to use tmpfs and just swap out to disk when necessary. -Databases have grown to roughly 30 GB as of February 2016. Leveldb prunes the database from time to time, -so it's not uncommon to see databases ~50% larger at times when it's writing a lot, especially when -indexing from the beginning. +Databases have grown to roughly 4 GB in April 2014, give or take a gigabyte between pruning limits +100 and 10000. Leveldb prunes the database from time to time, so it's not uncommon to see databases +~50% larger at times when it's writing a lot, especially when indexing from the beginning. ### Step 8. Create a self-signed SSL cert [Note: SSL certificates signed by a CA are supported by 2.0 clients.] -To run SSL / HTTPS you need to generate a self-signed certificate using openssl. +To run SSL / HTTPS you need to generate a self-signed certificateusing openssl. You could just comment out the SSL / HTTPS ports in the config and run without, but this is not recommended. -Use the sample code below to create a self-signed cert with a recommended validity +Use the sample code below to create a self-signed cert with a recommended validity of 5 years. You may supply any information for your sign request to identify your server. They are not currently checked by the client except for the validity date. When asked for a challenge password just leave it empty and press enter. @@ -255,27 +247,27 @@ When asked for a challenge password just leave it empty and press enter. A challenge password []: ... - $ openssl x509 -req -days 1825 -in server.csr -signkey server.key -out server.crt + $ openssl x509 -req -days 730 -in server.csr -signkey server.key -out server.crt -The server.crt file is your certificate suitable for the `ssl_certfile=` parameter and -server.key corresponds to `ssl_keyfile=` in your Electrum server config. +The server.crt file is your certificate suitable for the ssl_certfile= parameter and +server.key corresponds to ssl_keyfile= in your electrum server config. -Starting with Electrum 1.9, the client will learn and locally cache the SSL certificate +Starting with Electrum 1.9, the client will learn and locally cache the SSL certificate for your server upon the first request to prevent man-in-the middle attacks for all further connections. If your certificate is lost or expires on the server side, you will need to run your server with a different server name and a new certificate. Therefore it's a good idea to make an offline backup copy of your certificate and key -in case you need to restore them. +in case you need to restore it. ### Step 9. 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 +Electrum reads a config file (/etc/electrum-ltc.conf) when starting up. This +file includes the database setup, litecoind RPC setup, and a few other options. -The "configure" script listed above will create a config file at /etc/electrum.conf +The "configure" script listed above will create a config file at /etc/electrum-ltc.conf which you can edit to modify the settings. Go through the config options and set them to your liking. @@ -285,91 +277,68 @@ If you intend to run the server publicly have a look at README-IRC.md Electrum server currently needs quite a few file handles to use leveldb. It also requires file handles for each connection made to the server. It's good practice to increase the -open files limit to 64k. +open files limit to 64k. -The "configure" script will take care of this and ask you to create a user for running electrum-server. -If you're using the user `bitcoin` to run electrum and have added it as shown in this document, run +The "configure" script will take care of this and ask you to create a user for running electrum-ltc-server. +If you're using user litecoin to run electrum and have added it manually like shown in this HOWTO run the following code to add the limits to your /etc/security/limits.conf: - echo "bitcoin hard nofile 65536" >> /etc/security/limits.conf - echo "bitcoin soft nofile 65536" >> /etc/security/limits.conf - -If you are on Debian > 8.0 Jessie or another distribution based on it, you also need to add these lines in /etc/pam.d/common-session and /etc/pam.d/common-session-noninteractive otherwise the limits in /etc/security/limits.conf will not work: - - echo "session required pam_limits.so" >> /etc/pam.d/common-session - echo "session required pam_limits.so" >> /etc/pam.d/common-session-noninteractive - -Check if the limits are changed either by logging with the user configured to run Electrum server as. Example: - - su - bitcoin - ulimit -n - -Or if you use sudo and the user is added to sudoers group: - - sudo -u bitcoin -i ulimit -n - + echo "litecoin hard nofile 65536" >> /etc/security/limits.conf + echo "litecoin soft nofile 65536" >> /etc/security/limits.conf Two more things for you to consider: -1. To increase privacy of transactions going through your server - you may want to close bitcoind for incoming connections and connect outbound only. Most servers do run - full nodes with open incoming connections though. +1. To increase security you may want to close litecoind for incoming connections and connect outbound only -2. Consider restarting bitcoind (together with electrum-server) on a weekly basis to clear out unconfirmed +2. Consider restarting litecoind (together with electrum-ltc-server) on a weekly basis to clear out unconfirmed transactions from the local the memory pool which did not propagate over the network. ### Step 11. (Finally!) Run Electrum server The magic moment has come: you can now start your Electrum server as root (it will su to your unprivileged user): - # electrum-server start + # electrum-ltc-server start -Note: If you want to run the server without installing it on your system, just run 'run_electrum_server" as the +Note: If you want to run the server without installing it on your system, just run 'run_electrum_ltc_server" as the unprivileged user. You should see this in the log file: starting Electrum server -If your blockchain database is out of date Electrum Server will start updating it. You will see something similar to this in the log file: - - [09/02/2016-09:58:18] block 397319 (1727 197.37s) 0290aae5dc6395e2c60e8b2c9e48a7ee246cad7d0630d17dd5b54d70a41ffed7 (10.13tx/s, 139.78s/block) (eta 11.5 hours, 240 blocks) - -The important pieces to you are at the end. In this example, the server has to calculate 240 more blocks, with an ETA of 11.5 hours. Multiple entries will appear below this one as the server catches back up to the latest block. During this time the server will not accept incoming connections from clients or connect to the IRC channel. - If you want to stop Electrum server, use the 'stop' command: - # electrum-server stop + # electrum-ltc-server stop -If your system supports it, you may add electrum-server to the /etc/init.d directory. -This will ensure that the server is started and stopped automatically, and that the database is closed +If your system supports it, you may add electrum-ltc-server to the /etc/init.d directory. +This will ensure that the server is started and stopped automatically, and that the database is closed safely whenever your machine is rebooted. - # ln -s `which electrum-server` /etc/init.d/electrum-server - # update-rc.d electrum-server defaults + # ln -s `which electrum-ltc-server` /etc/init.d/electrum-ltc-server + # update-rc.d electrum-ltc-server defaults ### Step 12. Test the Electrum server We will assume you have a working Electrum client, a wallet, and some -transaction history. You should start the client and click on the green +transactions history. You should start the client and click on the green checkmark (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' and 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. +response time in the Server selection window. You should send/receive some +litecoins to confirm that everything is working properly. ### Step 13. Join us on IRC, subscribe to the server thread Say hi to the dev crew, other server operators, and fans on -irc.freenode.net #electrum and we'll try to congratulate you -on supporting the community by running an Electrum node. +irc.freenode.net #electrum-ltc and we'll try to congratulate you +on supporting the community by running an Electrum-LTC node. -If you're operating a public Electrum server please subscribe -to or regularly check the following thread: -https://bitcointalk.org/index.php?topic=85475.0 -It'll contain announcements about important updates to Electrum +If you're operating a public Electrum-LTC server please subscribe +to the following mailing list: +https://groups.google.com/forum/#!forum/electrum-ltc-server +It'll contain announcements about important updates to Electrum-LTC server required for a smooth user experience. diff --git a/INSTALL b/INSTALL index 02b5202d..4aaa8298 100644 --- a/INSTALL +++ b/INSTALL @@ -3,43 +3,47 @@ detailed information on how to configure your server. TLDR: -$ sudo ./configure -$ sudo python ./setup.py install -$ electrum-server start -$ electrum-server stop +# sudo apt-get install git +# sudo git clone https://github.com/sherlockcoin/electrum-navcoin-server +# sudo apt-get install libleveldb-dev +# sudo ./configure +# sudo python ./setup.py install +# electrum-navcoin-server start +# electrum-navcoin-server stop Note: If you want to run the server without installing it on your -system, just run 'run_electrum_server" +system, just run 'run_electrum_navcoin_server" -1. Install and run bitcoind. +1. Install and run navcoind. ---------------------------- -You will need to run bitcoind with the config option txindex=1. If you -have not previously done so, you may need to reindex the bitcoind +You will need to run navcoind with the config option txindex=1. If you +have not previously done so, you may need to reindex the navcoind blockchain -Note: you cannot use a pruning bitcoind. A full bitcoin node is -required in order to know for each address if it has been -used. Pruning occurs only at the level of the Electrum database. +Note: you cannot use a ultra-pruning navcoind (forthcoming in 0.9 or +later). A full navcoin node is required in order to know for each +address if it has been used. Pruning occurs only at the level of the +Electrum database. 2. Run the 'configure' script --------------------------- You need to run the script as root: -$ sudo ./configure +# sudo ./configure It will: - * create the configuration file in /etc/electrum.conf + * create the configuration file in /etc/electrum-navcoin.conf * create a user that will run the daemon - * optionally, download a fresh database from the Electrum Foundry. + * optionally, download a fresh database from the Electrum-NAVCOIN Foundry. If you choose not to use the Foundry, your server will have to build the database from scratch. This process can take several days. To speed it up, it is recommended to locate your database in shared -memory, in electrum.conf: path = /run/shm/electrum_db +memory, in electrum-navcoin.conf: path = /run/shm/electrum-navcoin_db Note: The 'configure' script does not configure SSL and IRC. You will need to manually edit the configuration file in order to enable SSL on @@ -49,7 +53,7 @@ your server, and to be visible on IRC. 3. Install the python package ----------------------------- -$ sudo python setup.py install +# sudo python setup.py install Note: You will need to redo this everytime you pull code from git. @@ -57,31 +61,31 @@ Note: You will need to redo this everytime you pull code from git. 4. Using the server ------------------- -Use 'electrum-server' to start and stop the server: +Use 'electrum-navcoin-server' to start and stop the server: -$ electrum-server +# electrum-navcoin-server The server will write a log file in its database path. -5. Add electrum-server to your system's services ------------------------------------------------- +5. Add electrum-navcoin-server to your system's services +---------------------------------------------------- -If your system supports it, you may add electrum-server to the +If your system supports it, you may add electrum-navcoin-server to the /etc/init.d directory. This will ensure that the server is started and stopped automatically, and that the database is closed safely whenever your machine is rebooted. -# ln -s `which electrum-server` /etc/init.d/electrum-server -# update-rc.d electrum-server defaults +# ln -s `which electrum-navcoin-server` /etc/init.d/electrum-navcoin-server +# update-rc.d electrum-navcoin-server defaults 6. Troubleshooting: ------------------- - * if your server or bitcoind is killed because is uses too much - memory, configure bitcoind to limit the number of connections + * if your server or navcoind is killed because is uses too much + memory, configure navcoind to limit the number of connections * if you see "Too many open files" errors, you may need to increase your user's File Descriptors limit. For this, see diff --git a/LICENSE b/LICENSE index b8bb9718..dba13ed2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,20 +1,661 @@ -The MIT License (MIT) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/README-IRC.md b/README-IRC.md index e0897cff..f6e04b86 100644 --- a/README-IRC.md +++ b/README-IRC.md @@ -1,44 +1,42 @@ IRC is used by Electrum server to find 'peers' - other Electrum servers. The current list can be seen by running: - electrum-server peers + electrum-navcoin-server peers The following config file options are used by the IRC part of Electrum server: [server] irc = yes - irc_nick = server_nickname host = fqdn.host.name.tld - # report_host = fqdn.host.name.tld - # report_stratum_tcp_port = 50001 + #report_host = fqdn.host.name.tld + irc_nick = server nickname + #report_stratum_http_port = 80 -`irc` is used to determine whether the IRC thread will be started or -the Electrum server will run in private mode (default). In private -mode, `electrum-server peers` will always return an empty list. +`irc` is used to determine whether the IRC thread will be started or the +Electrum server will run in private mode (default). In private mode, +`electrum-navcoin-server peers` will always return an empty list. -`host` is a fully-qualified domain name (FQDN) of your Electrum -server. It is used both when binding the listener for incoming client -connections and as part of the realname field in IRC (see below). +`host` is a fully-qualified domain name (FQDN) of your Electrum server. It is +used both when binding the listener for incoming client connections and as part +of the realname field in IRC (see below). -`report_host` is a an optional fully-qualified domain name (FQDN) of -your Electrum server instead of `host`. It is used as part of the name -field in IRC for incoming client connections. This is useful in a NAT -setup where you bind to a private IP locally but have an external IP +`report_host` is a an optional fully-qualified domain name (FQDN) of your Electrum server +instead of `host`. It is used as part of the name field in IRC for incoming client connections. +This is useful in a NAT setup where you bind to a private IP locally but have an external IP set up at your router and external DNS. -`report_stratum_tcp_port` and `report_stratum_tcp_ssl_port` are -optional settings for a port number to be reported in the IRC name -field without actually binding this port locally. This is useful in a -NAT setup where you might want to bind to a high port locally but DNAT -a different possibly privileged port for inbound connections +`report_stratum_tcp_port`, `report_stratum_http_port`, `report_stratum_tcp_ssl_port`, +`report_stratum_http_ssl_port` are optional settings for a port number to be reported in the +IRC name field without actually binding this port locally. This is useful in a NAT setup +where you might want to bind to a high port locally but DNAT a different possibly privileged +port for inbound connections -`irc_nick` is a nick name that will be appended to the E_ suffix when -composing the IRC nickname to identify your server on #electrum. +`irc_nick` is a nick name that will be appended to the EL_ suffix when +composing the IRC nickname to identify your server on #electrum-navcoin. -Please note the IRC name field can only contain 50 chars and will be -composed of `host` + protocol version number + Port numbers for the -various protocols. Please check whether port numbers are cut off at -the end +Please note the IRC name field can only contain 50 chars and will be composed +of `host` + protocol version number + Port numbers for the various protocols. +Please check whether port numbers are cut off at the end Example of port forwarding using iptables: diff --git a/README.md b/README.md index e9f1eb36..d13255d6 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,13 @@ -Electrum-server for the Electrum client -========================================= +![Electrum-NavCoin-Server](https://raw.githubusercontent.com/sherlockcoin/electrum-navcoin-server/master/navcoin.png) - * Author: Thomas Voegtlin (ThomasV on the bitcointalk forum) +electrum-navcoin-server for the electrum navcoin client +--------- + + * Author: Thomas Voegtlin (Bitcoin Electrum Creator) & Soopy452000 (NavCoin Fork) * Language: Python +## NavCoin Electrum Homepage: http://www.navcoin.org/electrum + Features -------- @@ -11,28 +15,24 @@ Features described by Alan Reiner (see the 'ultimate blockchain compression' thread in the Bitcointalk forum) - * The server requires bitcoind, leveldb and plyvel + * The server requires navcoind v3.6.0 or above, leveldb and plyvel * 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. - Installation ------------ 1. To install and run a server, see INSTALL. For greater detail on the installation process, see HOWTO.md. - 2. To start and stop the server, use the 'electrum-server' script + 2. To start and stop the server, use the 'electrum-navcoin-server' script License ------- -Electrum-server is made available under the terms of the MIT License. -See the included `LICENSE` for more details. +Electrum-server is made available under the terms of the [GNU Affero General +Public License](http://www.gnu.org/licenses/agpl.html), version 3. See the +included `LICENSE` for more details. diff --git a/configure b/configure index a5e50a83..57ae2a66 100755 --- a/configure +++ b/configure @@ -1,5 +1,4 @@ #!/bin/bash -set -e # check root if [ ! "$(id -u)" == "0" ]; then @@ -12,7 +11,7 @@ fi source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}" )"; pwd) -electrum_config="/etc/electrum.conf" +electrum_config="/etc/electrum-navcoin.conf" function read_config() { text=$1 @@ -26,7 +25,7 @@ function write_config() # create config file if [ ! -f $electrum_config ]; then echo "Creating config file" - cp $source_dir"/electrum.conf.sample" $electrum_config + cp $source_dir"/electrum-navcoin.conf.sample" $electrum_config fi @@ -53,7 +52,7 @@ fi # read path from config -default_path="/var/electrum-server" +default_path="/var/electrum-navcoin-server" path=$(read_config "path") if ! [ "$path" ]; then read -p "Path for database (default: $default_path) " -r @@ -66,7 +65,7 @@ if ! [ "$path" ]; then fi # read path from config -default_logfile="/var/log/electrum.log" +default_logfile="/var/log/electrum-navcoin.log" logfile=$(read_config "logfile") if ! [ "$logfile" ]; then read -p "Path of logfile (default: $default_logfile) " -r @@ -92,7 +91,7 @@ if [ ! -d $path ]; then echo if [[ $REPLY =~ ^[Yy]$ ]]; then mkdir -p $path - wget -O - "http://foundry.electrum.org/leveldb-dump/electrum-fulltree-100-latest.tar.gz" | tar --extract --gunzip --strip-components 1 --directory $path --file - + wget -O - "http://www.navcoin.org/leveldb-dump/electrum-fulltree-100-latest.tar.gz" | tar --extract --gunzip --strip-components 1 --directory $path --file - fi fi @@ -110,13 +109,13 @@ chown $user:$user $logfile bitcoind_user=$(read_config "bitcoind_user") if ! [ "$bitcoind_user" ]; then - read -p "rpcuser (from your bitcoin.conf file): " -r + read -p "rpcuser (from your navcoin.conf file): " -r write_config "bitcoind_user" $REPLY fi bitcoind_password=$(read_config "bitcoind_password") if ! [ "$bitcoind_password" ]; then - read -p "rpcpassword (from your bitcoin.conf file): " -r + read -p "rpcpassword (from your navcoin.conf file): " -r write_config "bitcoind_password" $REPLY fi @@ -125,4 +124,4 @@ fi echo "Configuration written to $electrum_config." echo "Please edit this file to finish the configuration." echo "If you have not done so, please run 'python setup.py install'" -echo "Then, run 'electrum-server' to start the daemon" +echo "Then, run 'electrum-navcoin-server' to start the daemon" diff --git a/electrum-pkb-server b/electrum-pkb-server new file mode 100644 index 00000000..ee0b98fa --- /dev/null +++ b/electrum-pkb-server @@ -0,0 +1,111 @@ +#! /bin/bash + + +electrum_config="/etc/electrum-navcoin.conf" +if [ ! -f $electrum_config ]; then + echo "$electrum_config does not exist" + echo "please run 'configure'" + exit 1 +fi + +if ! hash run_electrum_navcoin_server 2>/dev/null; then + echo "run_electrum_navcoin_server is not installed" + echo "Please run 'python setup.py install'" + exit 1 +fi + + + +function read_config() +{ + text=$1 + echo `grep -e ^$text $electrum_config |awk -F\= '{print $2}' | tail -n 1| tr -d ' '` +} + +# read path from config +path=$(read_config "path") +# read username +user=$(read_config "username") + +# get PID of server +if [ `id -u` = 0 ] ; then + if ! PID=`su $user -c "run_electrum_navcoin_server getpid"`; then + PID="" + fi +else + if ! PID=`run_electrum_navcoin_server getpid`; then + PID="" + fi +fi; + +case "$1" in + start) + if [ "$PID" ]; then + echo "Server already running (pid $PID)" + exit + fi + + if ! [ "$path" ]; then + echo "Variable path not set in $electrum_config" + exit + fi + + logfile=$(read_config "logfile") + if ! [ -f $logfile ]; then + touch $logfile + chown $user:$user $logfile + fi + + echo "Starting server as daemon" + cmd="ulimit -n 65536 ; nohup run_electrum_navcoin_server > /dev/null &" + if [ `id -u` = 0 ] ; then + su $user -c "$cmd" + else + eval $cmd + fi + ;; + stop) + if [ ! $PID ]; then + echo "Server not running" + exit + fi + cmd="run_electrum_navcoin_server stop" + if [ `id -u` = 0 ] ; then + su $user -c "$cmd" + else + $cmd + fi + echo "Waiting until process $PID terminates..." + while ps -p $PID > /dev/null; do sleep 1; done + echo "Done." + ;; + status) + if [ ! "$PID" ]; then + echo "Server not running" + else + echo "Server running (pid $PID)" + fi + ;; + getinfo|peers|numpeers|sessions|numsessions) + if [ ! "$PID" ]; then + echo "Server not running" + exit + fi + cmd="run_electrum_navcoin_server $1" + if [ `id -u` = 0 ] ; then + su $user -c "$cmd" + else + $cmd + fi + ;; + restart) + $0 stop + $0 start + ;; + *) + echo "Usage: electrum-navcoin-server {start|stop|restart|status|getinfo|peers|numpeers|sessions|numsessions}" + exit 1 + ;; +esac + +exit 0 diff --git a/electrum-pkb.conf.sample b/electrum-pkb.conf.sample new file mode 100644 index 00000000..0cc0353c --- /dev/null +++ b/electrum-pkb.conf.sample @@ -0,0 +1,33 @@ +[server] +# username for running the daemon +username = electrum +# hostname. set it to a FQDN in order to be reached from outside +host = mobile.navcoin.org +# ports +electrum_rpc_port = 8000 +stratum_tcp_port = 50001 +#stratum_tcp_ssl_port = 50002 +#report_host = +#report_stratum_tcp_port = 50001 +#report_stratum_tcp_ssl_port = 50002 +banner = Welcome to the NavCoin Electrum Server! +banner_file = /etc/electrum-navcoin.banner +irc = yes +irc_nick = electrum-navcoin +#ssl_certfile = /path/to/electrum-server.crt +#ssl_keyfile = /path/to/electrum-server.key +logfile = /var/log/electrum-navcoin.log +donation_address = PERu7znBafHURsxR749mQ2Teu6E8j95mct + +[leveldb] +# path to your database +path = /var/www/html +# for each address, history will be pruned if it is longer than this limit +pruning_limit = 10000 + +[bitcoind] +bitcoind_host = localhost +bitcoind_port = 59060 +# user and password from navcoin.conf +bitcoind_user = test +bitcoind_password = password diff --git a/kill_session b/kill_session index ead30bc6..9687de50 100755 --- a/kill_session +++ b/kill_session @@ -1,3 +1,3 @@ # run this script to close a session on your server # usage: su electrum -c "./kill_session ip:port" -./run_electrum_server debug "dispatcher.request_dispatcher.sessions['$1'].stop()" +./run_electrum_navcoin_server debug "dispatcher.request_dispatcher.sessions['$1'].stop()" diff --git a/navcoin.png b/navcoin.png new file mode 100644 index 00000000..a5851704 Binary files /dev/null and b/navcoin.png differ diff --git a/run_electrum_pkb_server b/run_electrum_pkb_server new file mode 100644 index 00000000..6c7fb255 --- /dev/null +++ b/run_electrum_pkb_server @@ -0,0 +1,308 @@ +#!/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 +# . + +import argparse +import ConfigParser +import logging +import socket +import sys +import time +import threading +import json +import os +import imp + + +if os.path.dirname(os.path.realpath(__file__)) == os.getcwd(): + imp.load_module('electrumnavcoinserver', *imp.find_module('src')) + + +from electrumnavcoinserver import storage, networks, utils +from electrumnavcoinserver.processor import Dispatcher, print_log +from electrumnavcoinserver.server_processor import ServerProcessor +from electrumnavcoinserver.blockchain_processor import BlockchainProcessor +from electrumnavcoinserver.stratum_tcp import TcpServer +from electrumnavcoinserver.stratum_http import HttpServer + + +logging.basicConfig() + +if sys.maxsize <= 2**32: + print "Warning: it looks like you are using a 32bit system. You may experience crashes caused by mmap" + +if os.getuid() == 0: + print "Do not run this program as root!" + print "Run the install script to create a non-privileged user." + sys.exit() + +def attempt_read_config(config, filename): + try: + with open(filename, 'r') as f: + config.readfp(f) + except IOError: + pass + +def load_banner(config): + try: + with open(config.get('server', 'banner_file'), 'r') as f: + config.set('server', 'banner', f.read()) + except IOError: + pass + +def setup_network_params(config): + type = config.get('network', 'type') + params = networks.params.get(type) + utils.PUBKEY_ADDRESS = int(params.get('pubkey_address')) + utils.SCRIPT_ADDRESS = int(params.get('script_address')) + storage.GENESIS_HASH = params.get('genesis_hash') + + if config.has_option('network', 'pubkey_address'): + utils.PUBKEY_ADDRESS = config.getint('network', 'pubkey_address') + if config.has_option('network', 'script_address'): + utils.SCRIPT_ADDRESS = config.getint('network', 'script_address') + if config.has_option('network', 'genesis_hash'): + storage.GENESIS_HASH = config.get('network', 'genesis_hash') + +def create_config(filename=None): + 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', 'banner_file', '/etc/electrum-navcoin.banner') + config.set('server', 'host', 'localhost') + config.set('server', 'electrum_rpc_port', '8000') + config.set('server', 'report_host', '') + config.set('server', 'stratum_tcp_port', '50001') + config.set('server', 'stratum_http_port', '') + config.set('server', 'stratum_tcp_ssl_port', '50002') + config.set('server', 'stratum_http_ssl_port', '') + config.set('server', 'report_stratum_tcp_port', '') + config.set('server', 'report_stratum_http_port', '') + config.set('server', 'report_stratum_tcp_ssl_port', '') + config.set('server', 'report_stratum_http_ssl_port', '') + config.set('server', 'ssl_certfile', '') + config.set('server', 'ssl_keyfile', '') + config.set('server', 'irc', 'yes') + config.set('server', 'irc_nick', '') + config.set('server', 'coin', 'navcoin') + config.set('server', 'logfile', '/var/log/electrum-navcoin.log') + config.set('server', 'donation_address', 'PERu7znBafHURsxR749mQ2Teu6E8j95mct') + config.set('server', 'max_subscriptions', '10000') + + config.add_section('leveldb') + config.set('leveldb', 'path', '/dev/shm/electrum-navcoin_db') + config.set('leveldb', 'pruning_limit', '100') + + # set network parameters + config.add_section('network') + config.set('network', 'type', 'navcoin_main') + + # try to find the config file in the default paths + if not filename: + for path in ('/etc/', ''): + filename = path + 'electrum-navcoin.conf' + if os.path.isfile(filename): + break + + if not os.path.isfile(filename): + print 'could not find electrum configuration file "%s"' % filename + sys.exit(1) + + attempt_read_config(config, filename) + + load_banner(config) + + return config + + +def run_rpc_command(params, electrum_rpc_port): + cmd = params[0] + import xmlrpclib + server = xmlrpclib.ServerProxy('http://localhost:%d' % electrum_rpc_port) + func = getattr(server, cmd) + r = func(*params[1:]) + if cmd == 'sessions': + now = time.time() + print 'type address sub version time' + for item in r: + print '%4s %21s %3s %7s %.2f' % (item.get('name'), + item.get('address'), + item.get('subscriptions'), + item.get('version'), + (now - item.get('time')), + ) + else: + print json.dumps(r, indent=4, sort_keys=True) + + +def cmd_banner_update(): + load_banner(dispatcher.shared.config) + return True + +def cmd_getinfo(): + return { + 'blocks': chain_proc.storage.height, + 'peers': len(server_proc.peers), + 'sessions': len(dispatcher.request_dispatcher.get_sessions()), + 'watched': len(chain_proc.watched_addresses), + 'cached': len(chain_proc.history_cache), + } + +def cmd_sessions(): + return map(lambda s: {"time": s.time, + "name": s.name, + "address": s.address, + "version": s.version, + "subscriptions": len(s.subscriptions)}, + dispatcher.request_dispatcher.get_sessions()) + +def cmd_numsessions(): + return len(dispatcher.request_dispatcher.get_sessions()) + +def cmd_peers(): + return server_proc.peers.keys() + +def cmd_numpeers(): + return len(server_proc.peers) + +def cmd_debug(s): + if s: + try: + result = str(eval(s)) + except: + result = "error" + return result + + +def get_port(config, name): + try: + return config.getint('server', name) + except: + return None + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--conf', metavar='path', default=None, help='specify a configuration file') + parser.add_argument('command', nargs='*', default=[], help='send a command to the server') + args = parser.parse_args() + + config = create_config(args.conf) + logfile = config.get('server', 'logfile') + utils.init_logger(logfile) + host = config.get('server', 'host') + electrum_rpc_port = get_port(config, 'electrum_rpc_port') + stratum_tcp_port = get_port(config, 'stratum_tcp_port') + stratum_http_port = get_port(config, 'stratum_http_port') + stratum_tcp_ssl_port = get_port(config, 'stratum_tcp_ssl_port') + stratum_http_ssl_port = get_port(config, 'stratum_http_ssl_port') + ssl_certfile = config.get('server', 'ssl_certfile') + ssl_keyfile = config.get('server', 'ssl_keyfile') + + setup_network_params(config) + + if ssl_certfile is '' or ssl_keyfile is '': + stratum_tcp_ssl_port = None + stratum_http_ssl_port = None + + if len(args.command) >= 1: + try: + run_rpc_command(args.command, electrum_rpc_port) + except socket.error: + print "server not running" + sys.exit(1) + sys.exit(0) + + try: + run_rpc_command(['getpid'], electrum_rpc_port) + is_running = True + except socket.error: + is_running = False + + if is_running: + print "server already running" + sys.exit(1) + + + print_log("Starting Electrum server on", host) + + # Create hub + dispatcher = Dispatcher(config) + shared = dispatcher.shared + + # handle termination signals + import signal + def handler(signum = None, frame = None): + print_log('Signal handler called with signal', signum) + shared.stop() + for sig in [signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT]: + signal.signal(sig, handler) + + + # Create and register processors + chain_proc = BlockchainProcessor(config, shared) + dispatcher.register('blockchain', chain_proc) + + server_proc = ServerProcessor(config, shared) + dispatcher.register('server', server_proc) + + transports = [] + # Create various transports we need + if stratum_tcp_port: + tcp_server = TcpServer(dispatcher, host, stratum_tcp_port, False, None, None) + transports.append(tcp_server) + + if stratum_tcp_ssl_port: + tcp_server = TcpServer(dispatcher, host, stratum_tcp_ssl_port, True, ssl_certfile, ssl_keyfile) + transports.append(tcp_server) + + if stratum_http_port: + http_server = HttpServer(dispatcher, host, stratum_http_port, False, None, None) + transports.append(http_server) + + if stratum_http_ssl_port: + http_server = HttpServer(dispatcher, host, stratum_http_ssl_port, True, ssl_certfile, ssl_keyfile) + transports.append(http_server) + + for server in transports: + server.start() + + + + from SimpleXMLRPCServer import SimpleXMLRPCServer + server = SimpleXMLRPCServer(('localhost', electrum_rpc_port), allow_none=True, logRequests=False) + server.register_function(lambda: os.getpid(), 'getpid') + server.register_function(shared.stop, 'stop') + server.register_function(cmd_getinfo, 'getinfo') + server.register_function(cmd_sessions, 'sessions') + server.register_function(cmd_numsessions, 'numsessions') + server.register_function(cmd_peers, 'peers') + server.register_function(cmd_numpeers, 'numpeers') + server.register_function(cmd_debug, 'debug') + server.register_function(cmd_banner_update, 'banner_update') + server.socket.settimeout(1) + + while not shared.stopped(): + try: + server.handle_request() + except socket.timeout: + continue + except: + shared.stop() + + server_proc.join() + chain_proc.join() + print_log("Electrum Server stopped") diff --git a/setup.py b/setup.py index 84c349af..f879d095 100644 --- a/setup.py +++ b/setup.py @@ -1,30 +1,33 @@ from setuptools import setup setup( - name="electrum-server", - version="1.0", - scripts=['run_electrum_server.py','electrum-server'], - install_requires=['plyvel','jsonrpclib', 'irc >= 11, <=14.0'], + name="electrum-navcoin-server", + version="0.9", + scripts=['run_electrum_navcoin_server','electrum-navcoin-server'], + install_requires=['plyvel','jsonrpclib', 'irc>=11'], package_dir={ - 'electrumserver':'src' + 'electrumnavcoinserver':'src' }, py_modules=[ - 'electrumserver.__init__', - 'electrumserver.utils', - 'electrumserver.storage', - 'electrumserver.deserialize', - 'electrumserver.networks', - 'electrumserver.blockchain_processor', - 'electrumserver.server_processor', - 'electrumserver.processor', - 'electrumserver.version', - 'electrumserver.ircthread', - 'electrumserver.stratum_tcp' + 'electrumnavcoinserver.__init__', + 'electrumnavcoinserver.utils', + 'electrumnavcoinserver.storage', + 'electrumnavcoinserver.deserialize', + 'electrumnavcoinserver.networks', + 'electrumnavcoinserver.blockchain_processor', + 'electrumnavcoinserver.server_processor', + 'electrumnavcoinserver.processor', + 'electrumnavcoinserver.version', + 'electrumnavcoinserver.ircthread', + 'electrumnavcoinserver.stratum_tcp', + 'electrumnavcoinserver.stratum_http' ], - description="Bitcoin Electrum Server", - author="Thomas Voegtlin", - author_email="thomasv@electrum.org", - license="MIT Licence", - url="https://github.com/spesmilo/electrum-server/", - long_description="""Server for the Electrum Lightweight Bitcoin Wallet""" + description="NavCoin Electrum Server", + author="Thomas Voegtlin & Soopy452000", + author_email="thomasv1@gmx.de", + license="GNU Affero GPLv3", + url="https://github.com/sherlockcoin/electrum-navcoin-server/", + long_description="""Server for the Electrum Lightweight NavCoin Wallet""" ) + + diff --git a/src/__init__.py b/src/__init__.py index 3434f4d6..d331b5d8 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -6,4 +6,4 @@ import processor import version import irc -import stratum_tcp +import stratum_tcp, stratum_http diff --git a/src/blockchain_processor.py b/src/blockchain_processor.py index 7b9cec35..0188d977 100644 --- a/src/blockchain_processor.py +++ b/src/blockchain_processor.py @@ -1,28 +1,6 @@ -#!/usr/bin/env python -# Copyright(C) 2011-2016 Thomas Voegtlin -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - +import ast import hashlib -from json import dumps, load +from json import dumps, loads import os from Queue import Queue import random @@ -33,19 +11,16 @@ import deserialize from processor import Processor, print_log +from utils import * from storage import Storage -from utils import logger, hash_decode, hash_encode, Hash, header_from_string, header_to_string, ProfiledThread, \ - rev_hex, int_to_hex4 +from utils import logger class BlockchainProcessor(Processor): def __init__(self, config, shared): Processor.__init__(self) - # monitoring - self.avg_time = 0,0,0 - self.time_ref = time.time() - + self.mtimes = {} # monitoring self.shared = shared self.config = config self.up_to_date = False @@ -56,19 +31,16 @@ def __init__(self, config, shared): self.watched_addresses = {} self.history_cache = {} - self.merkle_cache = {} self.max_cache_size = 100000 self.chunk_cache = {} self.cache_lock = threading.Lock() self.headers_data = '' self.headers_path = config.get('leveldb', 'path') - self.mempool_fees = {} self.mempool_values = {} self.mempool_addresses = {} - self.mempool_hist = {} # addr -> (txid, delta) - self.mempool_unconfirmed = {} # txid -> set of unconfirmed inputs - self.mempool_hashes = set() + self.mempool_hist = {} + self.mempool_hashes = set([]) self.mempool_lock = threading.Lock() self.address_queue = Queue() @@ -79,6 +51,8 @@ def __init__(self, config, shared): self.test_reorgs = False self.storage = Storage(config, shared, self.test_reorgs) + self.dblock = threading.Lock() + self.bitcoind_url = 'http://%s:%s@%s:%s/' % ( config.get('bitcoind', 'bitcoind_user'), config.get('bitcoind', 'bitcoind_password'), @@ -90,90 +64,71 @@ def __init__(self, config, shared): # catch_up headers self.init_headers(self.storage.height) - # start catch_up thread - if config.getboolean('leveldb', 'profiler'): - filename = os.path.join(config.get('leveldb', 'path'), 'profile') - print_log('profiled thread', filename) - self.blockchain_thread = ProfiledThread(filename, target = self.do_catch_up) - else: - self.blockchain_thread = threading.Thread(target = self.do_catch_up) + + self.blockchain_thread = threading.Thread(target = self.do_catch_up) self.blockchain_thread.start() def do_catch_up(self): - self.header = self.block2header(self.bitcoind('getblock', (self.storage.last_hash,))) + + self.header = self.block2header(self.bitcoind('getblock', [self.storage.last_hash])) self.header['utxo_root'] = self.storage.get_root_hash().encode('hex') self.catch_up(sync=False) - if not self.shared.stopped(): - print_log("Blockchain is up to date.") - self.memorypool_update() - print_log("Memory pool initialized.") + print_log("Blockchain is up to date.") + self.memorypool_update() + print_log("Memory pool initialized.") while not self.shared.stopped(): self.main_iteration() if self.shared.paused(): - print_log("bitcoind is responding") + print_log("navcoind is responding") self.shared.unpause() time.sleep(10) - def set_time(self): - self.time_ref = time.time() - - def print_time(self, num_tx): - delta = time.time() - self.time_ref - # leaky averages - seconds_per_block, tx_per_second, n = self.avg_time - alpha = (1. + 0.01 * n)/(n+1) - seconds_per_block = (1-alpha) * seconds_per_block + alpha * delta - alpha2 = alpha * delta / seconds_per_block - tx_per_second = (1-alpha2) * tx_per_second + alpha2 * num_tx / delta - self.avg_time = seconds_per_block, tx_per_second, n+1 - if self.storage.height%100 == 0 \ - or (self.storage.height%10 == 0 and self.storage.height >= 100000)\ - or self.storage.height >= 200000: - msg = "block %d (%d %.2fs) %s" %(self.storage.height, num_tx, delta, self.storage.get_root_hash().encode('hex')) - msg += " (%.2ftx/s, %.2fs/block)" % (tx_per_second, seconds_per_block) - run_blocks = self.storage.height - self.start_catchup_height - remaining_blocks = self.bitcoind_height - self.storage.height - if run_blocks>0 and remaining_blocks>0: - remaining_minutes = remaining_blocks * seconds_per_block / 60 - new_blocks = int(remaining_minutes / 10) # number of new blocks expected during catchup - blocks_to_process = remaining_blocks + new_blocks - minutes = blocks_to_process * seconds_per_block / 60 - rt = "%.0fmin"%minutes if minutes < 300 else "%.1f hours"%(minutes/60) - msg += " (eta %s, %d blocks)" % (rt, remaining_blocks) - print_log(msg) + + def mtime(self, name): + now = time.time() + if name != '': + delta = now - self.now + t = self.mtimes.get(name, 0) + self.mtimes[name] = t + delta + self.now = now + + def print_mtime(self): + s = '' + for k, v in self.mtimes.items(): + s += k+':'+"%.2f"%v+' ' + print_log(s) def wait_on_bitcoind(self): self.shared.pause() time.sleep(10) if self.shared.stopped(): # this will end the thread - raise BaseException() + raise - def bitcoind(self, method, params=()): + def bitcoind(self, method, params=[]): postdata = dumps({"method": method, 'params': params, 'id': 'jsonrpc'}) while True: try: - response = urllib.urlopen(self.bitcoind_url, postdata) - r = load(response) - response.close() + respdata = urllib.urlopen(self.bitcoind_url, postdata).read() except: - print_log("cannot reach bitcoind...") + print_log("cannot reach navcoind...") self.wait_on_bitcoind() else: + r = loads(respdata) if r['error'] is not None: if r['error'].get('code') == -28: - print_log("bitcoind still warming up...") + print_log("navcoind still warming up...") self.wait_on_bitcoind() continue raise BaseException(r['error']) break return r.get('result') - @staticmethod - def block2header(b): + + def block2header(self, b): return { "block_height": b.get('height'), "version": b.get('version'), @@ -185,11 +140,12 @@ def block2header(b): } def get_header(self, height): - block_hash = self.bitcoind('getblockhash', (height,)) - b = self.bitcoind('getblock', (block_hash,)) + block_hash = self.bitcoind('getblockhash', [height]) + b = self.bitcoind('getblock', [block_hash]) return self.block2header(b) def init_headers(self, db_height): + self.chunk_cache = {} self.headers_filename = os.path.join(self.headers_path, 'blockchain_headers') if os.path.exists(self.headers_filename): @@ -229,8 +185,7 @@ def init_headers(self, db_height): self.flush_headers() - @staticmethod - def hash_header(header): + def hash_header(self, header): return rev_hex(Hash(header_to_string(header).decode('hex')).encode('hex')) def read_header(self, block_height): @@ -258,8 +213,8 @@ def write_header(self, header, sync=True): with self.cache_lock: chunk_index = header.get('block_height')/2016 - if chunk_index in self.chunk_cache: - del self.chunk_cache[chunk_index] + if self.chunk_cache.get(chunk_index): + self.chunk_cache.pop(chunk_index) def pop_header(self): # we need to do this only if we have not flushed @@ -280,16 +235,16 @@ def get_chunk(self, i): chunk = self.chunk_cache.get(i) if not chunk: chunk = self.read_chunk(i) - if chunk: - self.chunk_cache[i] = chunk + self.chunk_cache[i] = chunk return chunk def get_mempool_transaction(self, txid): try: - raw_tx = self.bitcoind('getrawtransaction', (txid, 0)) + raw_tx = self.bitcoind('getrawtransaction', [txid, 0]) except: return None + vds = deserialize.BCDataStream() vds.write(raw_tx.decode('hex')) try: @@ -298,14 +253,6 @@ def get_mempool_transaction(self, txid): print_log("ERROR: cannot parse", txid) return None - def get_unconfirmed_history(self, addr): - hist = [] - with self.mempool_lock: - for tx_hash, delta in self.mempool_hist.get(addr, ()): - height = -1 if self.mempool_unconfirmed.get(tx_hash) else 0 - fee = self.mempool_fees.get(tx_hash) - hist.append({'tx_hash':tx_hash, 'height':height, 'fee':fee}) - return hist def get_history(self, addr, cache_only=False): with self.cache_lock: @@ -314,8 +261,15 @@ def get_history(self, addr, cache_only=False): return hist if cache_only: return -1 - hist = self.storage.get_history(addr) - hist.extend(self.get_unconfirmed_history(addr)) + + with self.dblock: + hist = self.storage.get_history(addr) + + # add memory pool + with self.mempool_lock: + for txid, delta in self.mempool_hist.get(addr, []): + hist.append({'tx_hash':txid, 'height':0}) + with self.cache_lock: if len(self.history_cache) > self.max_cache_size: logger.info("clearing cache") @@ -323,13 +277,21 @@ def get_history(self, addr, cache_only=False): self.history_cache[addr] = hist return hist + def get_unconfirmed_history(self, addr): + hist = [] + with self.mempool_lock: + for txid, delta in self.mempool_hist.get(addr, []): + hist.append({'tx_hash':txid, 'height':0}) + return hist + def get_unconfirmed_value(self, addr): v = 0 with self.mempool_lock: - for txid, delta in self.mempool_hist.get(addr, ()): + for txid, delta in self.mempool_hist.get(addr, []): v += delta return v + def get_status(self, addr, cache_only=False): tx_points = self.get_history(addr, cache_only) if cache_only and tx_points == -1: @@ -339,19 +301,15 @@ def get_status(self, addr, cache_only=False): return None if tx_points == ['*']: return '*' - status = ''.join(tx.get('tx_hash') + ':%d:' % tx.get('height') for tx in tx_points) + status = '' + for tx in tx_points: + status += tx.get('tx_hash') + ':%d:' % tx.get('height') return hashlib.sha256(status).digest().encode('hex') - def get_merkle(self, tx_hash, height, cache_only): - with self.cache_lock: - out = self.merkle_cache.get(tx_hash) - if out is not None: - return out - if cache_only: - return -1 + def get_merkle(self, tx_hash, height): - block_hash = self.bitcoind('getblockhash', (height,)) - b = self.bitcoind('getblock', (block_hash,)) + block_hash = self.bitcoind('getblockhash', [height]) + b = self.bitcoind('getblock', [block_hash]) tx_list = b.get('tx') tx_pos = tx_list.index(tx_hash) @@ -374,16 +332,38 @@ def get_merkle(self, tx_hash, height, cache_only): merkle = merkle[2:] merkle = n - out = {"block_height": height, "merkle": s, "pos": tx_pos} - with self.cache_lock: - if len(self.merkle_cache) > self.max_cache_size: - logger.info("clearing merkle cache") - self.merkle_cache.clear() - self.merkle_cache[tx_hash] = out - return out - - @staticmethod - def deserialize_block(block): + return {"block_height": height, "merkle": s, "pos": tx_pos} + + + def add_to_history(self, addr, tx_hash, tx_pos, tx_height): + # keep it sorted + s = self.serialize_item(tx_hash, tx_pos, tx_height) + 40*chr(0) + assert len(s) == 80 + + serialized_hist = self.batch_list[addr] + + l = len(serialized_hist)/80 + for i in range(l-1, -1, -1): + item = serialized_hist[80*i:80*(i+1)] + item_height = int(rev_hex(item[36:39].encode('hex')), 16) + if item_height <= tx_height: + serialized_hist = serialized_hist[0:80*(i+1)] + s + serialized_hist[80*(i+1):] + break + else: + serialized_hist = s + serialized_hist + + self.batch_list[addr] = serialized_hist + + # backlink + txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex') + self.batch_txio[txo] = addr + + + + + + + def deserialize_block(self, block): txlist = block.get('tx') tx_hashes = [] # ordered txids txdict = {} # deserialized tx @@ -404,9 +384,9 @@ def deserialize_block(block): - def import_block(self, block, block_hash, block_height, revert=False): + def import_block(self, block, block_hash, block_height, sync, revert=False): - touched_addr = set() + touched_addr = set([]) # deserialize transactions tx_hashes, txdict = self.deserialize_block(block) @@ -435,16 +415,12 @@ def import_block(self, block, block_hash, block_height, revert=False): self.storage.write_undo_info(block_height, self.bitcoind_height, undo_info) # add the max - self.storage.save_height(block_hash, block_height) + self.storage.db_undo.put('height', repr( (block_hash, block_height, self.storage.db_version) )) for addr in touched_addr: self.invalidate_cache(addr) self.storage.update_hashes() - # batch write modified nodes - self.storage.batch_write() - # return length for monitoring - return len(tx_hashes) def add_request(self, session, request): @@ -500,14 +476,14 @@ def do_unsubscribe(self, method, params, session): print_log("error rc!!") self.shared.stop() if l == []: - del self.watched_addresses[addr] + self.watched_addresses.pop(addr) def process(self, request, cache_only=False): message_id = request['id'] method = request['method'] - params = request.get('params', ()) + params = request.get('params', []) result = None error = None @@ -546,7 +522,7 @@ def process(self, request, cache_only=False): elif method == 'blockchain.utxo.get_address': txid = str(params[0]) pos = int(params[1]) - txi = (txid + int_to_hex4(pos)).decode('hex') + txi = (txid + int_to_hex(pos, 4)).decode('hex') result = self.storage.get_address(txi) elif method == 'blockchain.block.get_header': @@ -569,124 +545,117 @@ def process(self, request, cache_only=False): print_log("sent tx:", txo) result = txo except BaseException, e: - error = e.args[0] - if error["code"] == -26: - # If we return anything that's not the transaction hash, - # it's considered an error message - message = error["message"] - if "non-mandatory-script-verify-flag" in message: - result = "Your client produced a transaction that is not accepted by the Bitcoin network any more. Please upgrade to Electrum 2.5.1 or newer\n" - else: - result = "The transaction was rejected by network rules.(" + message + ")\n" \ - "[" + params[0] + "]" - else: - result = error["message"] # do send an error - print_log("error:", result) + result = str(e) # do not send an error + print_log("error:", result, params) elif method == 'blockchain.transaction.get_merkle': - tx_hash = params[0] - tx_height = params[1] - result = self.get_merkle(tx_hash, tx_height, cache_only) + if cache_only: + result = -1 + else: + tx_hash = params[0] + tx_height = params[1] + result = self.get_merkle(tx_hash, tx_height) elif method == 'blockchain.transaction.get': tx_hash = params[0] - result = self.bitcoind('getrawtransaction', (tx_hash, 0)) + result = self.bitcoind('getrawtransaction', [tx_hash, 0]) elif method == 'blockchain.estimatefee': num = int(params[0]) - result = self.bitcoind('estimatefee', (num,)) - - elif method == 'blockchain.relayfee': - result = self.relayfee + result = self.bitcoind('estimatefee', [num]) else: raise BaseException("unknown method:%s" % method) + if cache_only and result == -1: + return -1 + return result - def get_block(self, block_hash): - block = self.bitcoind('getblock', (block_hash,)) + def getfullblock(self, block_hash): + block = self.bitcoind('getblock', [block_hash]) rawtxreq = [] i = 0 for txid in block['tx']: rawtxreq.append({ "method": "getrawtransaction", - "params": (txid,), + "params": [txid], "id": i, }) i += 1 - postdata = dumps(rawtxreq) - - while True: - try: - response = urllib.urlopen(self.bitcoind_url, postdata) - r = load(response) - response.close() - except: - logger.error("bitcoind error (getfullblock)") - self.wait_on_bitcoind() - continue - try: - rawtxdata = [] - for ir in r: - assert ir['error'] is None, "Error: make sure you run bitcoind with txindex=1; use -reindex if needed." - rawtxdata.append(ir['result']) - except BaseException as e: - logger.error(str(e)) - self.wait_on_bitcoind() - continue - - block['tx'] = rawtxdata - return block - + postdata = dumps(rawtxreq) + try: + respdata = urllib.urlopen(self.bitcoind_url, postdata).read() + except: + logger.error("navcoind error (getfullblock)",exc_info=True) + self.shared.stop() + + r = loads(respdata) + rawtxdata = [] + for ir in r: + if ir['error'] is not None: + self.shared.stop() + print_log("Error: make sure you run navcoind with txindex=1; use -reindex if needed.") + raise BaseException(ir['error']) + rawtxdata.append(ir['result']) + block['tx'] = rawtxdata + return block def catch_up(self, sync=True): - self.start_catchup_height = self.storage.height prev_root_hash = None - n = 0 - while not self.shared.stopped(): + + self.mtime('') + # are we done yet? info = self.bitcoind('getinfo') - self.relayfee = info.get('relayfee') self.bitcoind_height = info.get('blocks') - bitcoind_block_hash = self.bitcoind('getblockhash', (self.bitcoind_height,)) + bitcoind_block_hash = self.bitcoind('getblockhash', [self.bitcoind_height]) if self.storage.last_hash == bitcoind_block_hash: self.up_to_date = True break - self.set_time() - - revert = (random.randint(1, 100) == 1) if self.test_reorgs and self.storage.height>100 else False + # fixme: this is unsafe, if we revert when the undo info is not yet written + revert = (random.randint(1, 100) == 1) if self.test_reorgs else False # not done.. self.up_to_date = False try: - next_block_hash = self.bitcoind('getblockhash', (self.storage.height + 1,)) + next_block_hash = self.bitcoind('getblockhash', [self.storage.height + 1]) + next_block = self.getfullblock(next_block_hash) except BaseException, e: revert = True + next_block = self.getfullblock(self.storage.last_hash) - next_block = self.get_block(next_block_hash if not revert else self.storage.last_hash) + self.mtime('daemon') if (next_block.get('previousblockhash') == self.storage.last_hash) and not revert: prev_root_hash = self.storage.get_root_hash() - n = self.import_block(next_block, next_block_hash, self.storage.height+1) + self.import_block(next_block, next_block_hash, self.storage.height+1, sync) self.storage.height = self.storage.height + 1 self.write_header(self.block2header(next_block), sync) self.storage.last_hash = next_block_hash + self.mtime('import') + + if self.storage.height % 1000 == 0 and not sync: + t_daemon = self.mtimes.get('daemon') + t_import = self.mtimes.get('import') + print_log("catch_up: block %d (%.3fs %.3fs)" % (self.storage.height, t_daemon, t_import), self.storage.get_root_hash().encode('hex')) + self.mtimes['daemon'] = 0 + self.mtimes['import'] = 0 else: # revert current block - block = self.get_block(self.storage.last_hash) + block = self.getfullblock(self.storage.last_hash) print_log("blockchain reorg", self.storage.height, block.get('previousblockhash'), self.storage.last_hash) - n = self.import_block(block, self.storage.last_hash, self.storage.height, revert=True) + self.import_block(block, self.storage.last_hash, self.storage.height, sync, revert=True) self.pop_header() self.flush_headers() @@ -700,10 +669,8 @@ def catch_up(self, sync=True): assert prev_root_hash == self.storage.get_root_hash() prev_root_hash = None - # print time - self.print_time(n) - self.header = self.block2header(self.bitcoind('getblock', (self.storage.last_hash,))) + self.header = self.block2header(self.bitcoind('getblock', [self.storage.last_hash])) self.header['utxo_root'] = self.storage.get_root_hash().encode('hex') if self.shared.stopped(): @@ -712,9 +679,8 @@ def catch_up(self, sync=True): def memorypool_update(self): - t0 = time.time() mempool_hashes = set(self.bitcoind('getrawmempool')) - touched_addresses = set() + touched_addresses = set([]) # get new transactions new_tx = {} @@ -727,88 +693,72 @@ def memorypool_update(self): continue new_tx[tx_hash] = tx + self.mempool_hashes.add(tx_hash) # remove older entries from mempool_hashes self.mempool_hashes = mempool_hashes + # check all tx outputs - for tx_hash, tx in new_tx.iteritems(): + for tx_hash, tx in new_tx.items(): mpa = self.mempool_addresses.get(tx_hash, {}) out_values = [] - out_sum = 0 for x in tx.get('outputs'): - addr = x.get('address', '') - value = x['value'] - out_values.append((addr, value)) + out_values.append( x['value'] ) + + addr = x.get('address') if not addr: continue - v = mpa.get(addr, 0) - v += value + v = mpa.get(addr,0) + v += x['value'] mpa[addr] = v touched_addresses.add(addr) - out_sum += value - self.mempool_fees[tx_hash] = -out_sum self.mempool_addresses[tx_hash] = mpa self.mempool_values[tx_hash] = out_values - self.mempool_unconfirmed[tx_hash] = set() # check all inputs - for tx_hash, tx in new_tx.iteritems(): + for tx_hash, tx in new_tx.items(): mpa = self.mempool_addresses.get(tx_hash, {}) - # are we spending unconfirmed inputs? - input_sum = 0 for x in tx.get('inputs'): - prev_hash = x.get('prevout_hash') - prev_n = x.get('prevout_n') - mpv = self.mempool_values.get(prev_hash) - if mpv: - addr, value = mpv[prev_n] - self.mempool_unconfirmed[tx_hash].add(prev_hash) + # we assume that the input address can be parsed by deserialize(); this is true for Electrum transactions + addr = x.get('address') + if not addr: + continue + + v = self.mempool_values.get(x.get('prevout_hash')) + if v: + value = v[ x.get('prevout_n')] else: - txi = (prev_hash + int_to_hex4(prev_n)).decode('hex') + txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex') try: - addr = self.storage.get_address(txi) value = self.storage.get_utxo_value(addr,txi) except: print_log("utxo not in database; postponing mempool update") return - # we can proceed - input_sum += value - if not addr: - continue - v = mpa.get(addr, 0) + + v = mpa.get(addr,0) v -= value mpa[addr] = v touched_addresses.add(addr) + self.mempool_addresses[tx_hash] = mpa - self.mempool_fees[tx_hash] += input_sum + # remove deprecated entries from mempool_addresses for tx_hash, addresses in self.mempool_addresses.items(): if tx_hash not in self.mempool_hashes: - del self.mempool_addresses[tx_hash] - del self.mempool_values[tx_hash] - del self.mempool_unconfirmed[tx_hash] - del self.mempool_fees[tx_hash] - touched_addresses.update(addresses) + self.mempool_addresses.pop(tx_hash) + self.mempool_values.pop(tx_hash) + for addr in addresses: + touched_addresses.add(addr) - # remove deprecated entries from mempool_hist + # rebuild mempool histories new_mempool_hist = {} - for addr in self.mempool_hist.iterkeys(): - h = self.mempool_hist[addr] - hh = [] - for tx_hash, delta in h: - if tx_hash in self.mempool_addresses: - hh.append((tx_hash, delta)) - if hh: - new_mempool_hist[addr] = hh - # add new transactions to mempool_hist - for tx_hash in new_tx.iterkeys(): - addresses = self.mempool_addresses[tx_hash] - for addr, delta in addresses.iteritems(): + for tx_hash, addresses in self.mempool_addresses.items(): + for addr, delta in addresses.items(): h = new_mempool_hist.get(addr, []) - if (tx_hash, delta) not in h: + if tx_hash not in h: h.append((tx_hash, delta)) new_mempool_hist[addr] = h @@ -819,16 +769,12 @@ def memorypool_update(self): for addr in touched_addresses: self.invalidate_cache(addr) - t1 = time.time() - if t1-t0>1: - print_log('mempool_update', t1-t0, len(self.mempool_hashes), len(self.mempool_hist)) - def invalidate_cache(self, address): with self.cache_lock: if address in self.history_cache: # print_log("cache: invalidating", address) - del self.history_cache[address] + self.history_cache.pop(address) with self.watch_lock: sessions = self.watched_addresses.get(address) @@ -850,7 +796,10 @@ def main_iteration(self): print_log("Stopping timer") return - self.catch_up() + with self.dblock: + t1 = time.time() + self.catch_up() + t2 = time.time() self.memorypool_update() @@ -860,16 +809,17 @@ def main_iteration(self): self.push_response(session, { 'id': None, 'method': 'blockchain.numblocks.subscribe', - 'params': (self.storage.height,), + 'params': [self.storage.height], }) if self.sent_header != self.header: + print_log("blockchain: %d (%.3fs)" % (self.storage.height, t2 - t1)) self.sent_header = self.header for session in self.watch_headers: self.push_response(session, { 'id': None, 'method': 'blockchain.headers.subscribe', - 'params': (self.header,), + 'params': [self.header], }) while True: @@ -883,7 +833,7 @@ def main_iteration(self): self.push_response(session, { 'id': None, 'method': 'blockchain.address.subscribe', - 'params': (addr, status), + 'params': [addr, status], }) diff --git a/src/deserialize.py b/src/deserialize.py index ccc4eaa7..8107d18b 100644 --- a/src/deserialize.py +++ b/src/deserialize.py @@ -216,6 +216,17 @@ def parse_TxIn(vds): d['prevout_n'] = vds.read_uint32() scriptSig = vds.read_bytes(vds.read_compact_size()) d['sequence'] = vds.read_uint32() + + if scriptSig: + pubkeys, signatures, address = get_address_from_input_script(scriptSig) + else: + pubkeys = [] + signatures = [] + address = None + + d['address'] = address + d['signatures'] = signatures + return d @@ -233,17 +244,23 @@ def parse_Transaction(vds, is_coinbase): d = {} start = vds.read_cursor d['version'] = vds.read_int32() + d['nTime'] = vds.read_uint32() n_vin = vds.read_compact_size() d['inputs'] = [] for i in xrange(n_vin): - o = parse_TxIn(vds) - if not is_coinbase: - d['inputs'].append(o) + o = parse_TxIn(vds) + if not is_coinbase: + d['inputs'].append(o) n_vout = vds.read_compact_size() d['outputs'] = [] for i in xrange(n_vout): - o = parse_TxOut(vds, i) - d['outputs'].append(o) + o = parse_TxOut(vds, i) + + #if o['address'] == "None" and o['value']==0: + # print("skipping strange tx output with zero value") + # continue + # if o['address'] != "None": + d['outputs'].append(o) d['lockTime'] = vds.read_uint32() return d @@ -330,6 +347,47 @@ def match_decoded(decoded, to_match): +def get_address_from_input_script(bytes): + try: + decoded = [ x for x in script_GetOp(bytes) ] + except: + # coinbase transactions raise an exception + return [], [], None + + # non-generated TxIn transactions push a signature + # (seventy-something bytes) and then their public key + # (33 or 65 bytes) onto the stack: + + match = [ opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4 ] + if match_decoded(decoded, match): + return None, None, public_key_to_pubkey_address(decoded[1][1]) + + # p2sh transaction, 2 of n + match = [ opcodes.OP_0 ] + while len(match) < len(decoded): + match.append(opcodes.OP_PUSHDATA4) + + if match_decoded(decoded, match): + + redeemScript = decoded[-1][1] + num = len(match) - 2 + signatures = map(lambda x:x[1].encode('hex'), decoded[1:-1]) + dec2 = [ x for x in script_GetOp(redeemScript) ] + + # 2 of 2 + match2 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_2, opcodes.OP_CHECKMULTISIG ] + if match_decoded(dec2, match2): + pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex') ] + return pubkeys, signatures, hash_160_to_script_address(hash_160(redeemScript)) + + # 2 of 3 + match2 = [ opcodes.OP_2, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_PUSHDATA4, opcodes.OP_3, opcodes.OP_CHECKMULTISIG ] + if match_decoded(dec2, match2): + pubkeys = [ dec2[1][1].encode('hex'), dec2[2][1].encode('hex'), dec2[3][1].encode('hex') ] + return pubkeys, signatures, hash_160_to_script_address(hash_160(redeemScript)) + + return [], [], None + def get_address_from_output_script(bytes): try: diff --git a/src/ircthread.py b/src/ircthread.py index 90631475..7a94f8a4 100644 --- a/src/ircthread.py +++ b/src/ircthread.py @@ -1,32 +1,7 @@ -#!/usr/bin/env python -# Copyright(C) 2011-2016 Thomas Voegtlin -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - import re import time import socket -import ssl import threading -import Queue import irc.client from utils import logger from utils import Hash @@ -40,28 +15,33 @@ def __init__(self, processor, config): threading.Thread.__init__(self) self.processor = processor self.daemon = True - options = dict(config.items('server')) - self.stratum_tcp_port = options.get('stratum_tcp_port') - self.stratum_tcp_ssl_port = options.get('stratum_tcp_ssl_port') - self.report_stratum_tcp_port = options.get('report_stratum_tcp_port') - self.report_stratum_tcp_ssl_port = options.get('report_stratum_tcp_ssl_port') - self.irc_bind_ip = options.get('irc_bind_ip') - self.host = options.get('host') - self.report_host = options.get('report_host') - self.nick = options.get('irc_nick') + self.stratum_tcp_port = config.get('server', 'stratum_tcp_port') + self.stratum_http_port = config.get('server', 'stratum_http_port') + self.stratum_tcp_ssl_port = config.get('server', 'stratum_tcp_ssl_port') + self.stratum_http_ssl_port = config.get('server', 'stratum_http_ssl_port') + self.report_stratum_tcp_port = config.get('server', 'report_stratum_tcp_port') + self.report_stratum_http_port = config.get('server', 'report_stratum_http_port') + self.report_stratum_tcp_ssl_port = config.get('server', 'report_stratum_tcp_ssl_port') + self.report_stratum_http_ssl_port = config.get('server', 'report_stratum_http_ssl_port') + self.host = config.get('server', 'host') + self.report_host = config.get('server', 'report_host') + self.nick = config.get('server', 'irc_nick') if self.report_stratum_tcp_port: self.stratum_tcp_port = self.report_stratum_tcp_port + if self.report_stratum_http_port: + self.stratum_http_port = self.report_stratum_http_port if self.report_stratum_tcp_ssl_port: self.stratum_tcp_ssl_port = self.report_stratum_tcp_ssl_port + if self.report_stratum_http_ssl_port: + self.stratum_http_ssl_port = self.report_stratum_http_ssl_port if self.report_host: self.host = self.report_host if not self.nick: self.nick = Hash(self.host)[:5].encode("hex") self.pruning = True self.pruning_limit = config.get('leveldb', 'pruning_limit') - self.nick = 'E_' + self.nick + self.nick = 'EL_' + self.nick self.password = None - self.who_queue = Queue.Queue() def getname(self): s = 'v' + VERSION + ' ' @@ -69,7 +49,7 @@ def getname(self): s += 'p' + self.pruning_limit + ' ' def add_port(letter, number): - DEFAULT_PORTS = {'t':'50001', 's':'50002'} + DEFAULT_PORTS = {'t':'50001', 's':'50002', 'h':'8081', 'g':'8082'} if not number: return '' if DEFAULT_PORTS[letter] == number: return letter + ' ' @@ -77,28 +57,30 @@ def add_port(letter, number): return letter + number + ' ' s += add_port('t',self.stratum_tcp_port) + s += add_port('h',self.stratum_http_port) s += add_port('s',self.stratum_tcp_ssl_port) + s += add_port('g',self.stratum_http_ssl_port) return s def start(self, queue): self.queue = queue threading.Thread.start(self) - + def on_connect(self, connection, event): - connection.join("#electrum") + connection.join("#electrum-navcoin") def on_join(self, connection, event): - m = re.match("(E_.*)!", event.source) + m = re.match("(EL_.*)!", event.source) if m: - self.who_queue.put((connection, m.group(1))) + connection.who(m.group(1)) def on_quit(self, connection, event): - m = re.match("(E_.*)!", event.source) + m = re.match("(EL_.*)!", event.source) if m: self.queue.put(('quit', [m.group(1)])) - + def on_kick(self, connection, event): - m = re.match("(E_.*)", event.arguments[0]) + m = re.match("(EL_.*)", event.arguments[0]) if m: self.queue.put(('quit', [m.group(1)])) @@ -111,8 +93,8 @@ def on_who(self, connection, event): try: ip = socket.gethostbyname(line[1]) except: - # no IPv4 address could be resolved. Could be .onion or IPv6. - ip = line[1] + logger.error("gethostbyname error " + line[1]) + return nick = event.arguments[4] host = line[1] ports = line[2:] @@ -120,21 +102,10 @@ def on_who(self, connection, event): def on_name(self, connection, event): for s in event.arguments[2].split(): - if s.startswith("E_"): - self.who_queue.put((connection, s)) - - def who_thread(self): - while not self.processor.shared.stopped(): - try: - connection, s = self.who_queue.get(timeout=1) - except Queue.Empty: - continue - #logger.info("who: "+ s) - connection.who(s) - time.sleep(1) + if s.startswith("EL_"): + connection.who(s) def run(self): - while self.processor.shared.paused(): time.sleep(1) @@ -143,16 +114,10 @@ def run(self): irc.client.ServerConnection.buffer_class = irc.buffer.LenientDecodingLineBuffer logger.info("joining IRC") - t = threading.Thread(target=self.who_thread) - t.start() - while not self.processor.shared.stopped(): client = irc.client.Reactor() try: - #bind_address = (self.irc_bind_ip, 0) if self.irc_bind_ip else None - #ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket, bind_address=bind_address) - #c = client.server().connect('irc.freenode.net', 6697, self.nick, self.password, ircname=self.ircname, connect_factory=ssl_factory) - c = client.server().connect('irc.freenode.net', 6667, self.nick, self.password, ircname=self.ircname) + c = client.server().connect('irc.freenode.net', 6667, self.nick, self.password, ircname=self.ircname) except irc.client.ServerConnectionError: logger.error('irc', exc_info=True) time.sleep(10) diff --git a/src/networks.py b/src/networks.py index 5142c63c..863f1191 100644 --- a/src/networks.py +++ b/src/networks.py @@ -1,14 +1,14 @@ # Main network and testnet3 definitions params = { - 'bitcoin_main': { - 'pubkey_address': 0, - 'script_address': 5, - 'genesis_hash': '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' + 'navcoin_main': { + 'pubkey_address': 55, + 'script_address': 28, + 'genesis_hash': '000000a49664091ce50794d84fb243cde97738534b554b2022fa00a029d0ab7c' }, - 'bitcoin_test': { + 'navcoin_test': { 'pubkey_address': 111, 'script_address': 196, - 'genesis_hash': '000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943' + 'genesis_hash': '000000a49664091ce50794d84fb243cde97738534b554b2022fa00a029d0ab7c' } } diff --git a/src/processor.py b/src/processor.py index e9aab6ec..6b2e676c 100644 --- a/src/processor.py +++ b/src/processor.py @@ -1,26 +1,3 @@ -#!/usr/bin/env python -# Copyright(C) 2011-2016 Thomas Voegtlin -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - import json import Queue as queue import socket @@ -89,8 +66,6 @@ def run(self): msg_id = request.get('id') except: continue - if session.stopped(): - continue try: result = self.process(request) self.push_response(session, {'id': msg_id, 'result': result}) @@ -161,6 +136,7 @@ def run(self): self.do_dispatch(session, request) except: logger.error('dispatch',exc_info=True) + self.collect_garbage() self.stop() @@ -208,7 +184,17 @@ def add_session(self, session): def remove_session(self, session): key = session.key() with self.lock: - del self.sessions[key] + self.sessions.pop(key) + + def collect_garbage(self): + # only for HTTP sessions. + now = time.time() + if time.time() - self.lastgc < 60.0: + return + self.lastgc = now + for session in self.sessions.values(): + if session.name == "HTTP" and (now - session.time) > session.timeout: + session.stop() class Session: @@ -265,7 +251,6 @@ def subscribe_to_service(self, method, params): if len(self.subscriptions) > self.max_subscriptions: print_log("max subscriptions reached", self.address) - self.stop() return False # append to self.subscriptions only if this does not raise diff --git a/src/server_processor.py b/src/server_processor.py index a6f87aec..a406b36a 100644 --- a/src/server_processor.py +++ b/src/server_processor.py @@ -1,26 +1,3 @@ -#!/usr/bin/env python -# Copyright(C) 2011-2016 Thomas Voegtlin -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - import socket import sys import threading @@ -68,8 +45,8 @@ def read_irc_results(self): self.peers[nick] = (ip, host, ports) if event == 'quit': nick = params[0] - if nick in self.peers: - del self.peers[nick] + if self.peers.get(nick): + self.peers.pop(nick) def get_peers(self): diff --git a/src/storage.py b/src/storage.py index 1e6a1d5b..a5d5b71b 100644 --- a/src/storage.py +++ b/src/storage.py @@ -1,299 +1,122 @@ -#!/usr/bin/env python -# Copyright(C) 2011-2016 Thomas Voegtlin -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - import plyvel import ast import hashlib import os import sys -import threading from processor import print_log, logger -from utils import bc_address_to_hash_160, hash_160_to_pubkey_address, Hash, \ - bytes8_to_int, bytes4_to_int, int_to_bytes8, \ - int_to_hex8, int_to_bytes4, int_to_hex4 +from utils import bc_address_to_hash_160, hash_160_to_pubkey_address, hex_to_int, int_to_hex, Hash +global GENESIS_HASH +GENESIS_HASH = '000000a49664091ce50794d84fb243cde97738534b554b2022fa00a029d0ab7c' """ Patricia tree for hashing unspents """ -# increase this when database needs to be updated -global GENESIS_HASH -GENESIS_HASH = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' -DB_VERSION = 3 -KEYLENGTH = 56 # 20 + 32 + 4 - - -class Node(object): - - def __init__(self, s): - self.k = int(s[0:32].encode('hex'), 16) - self.s = s[32:] - if self.k==0 and self.s: - print "init error", len(self.s), "0x%0.64X" % self.k - raise BaseException("z") - - def serialized(self): - k = "0x%0.64X" % self.k - k = k[2:].decode('hex') - assert len(k) == 32 - return k + self.s - - def has(self, c): - return (self.k & (1<<(ord(c)))) != 0 - - def is_singleton(self, key): - assert self.s != '' - return len(self.s) == 40 - - def get_singleton(self): - for i in xrange(256): - if self.k == (1< bitcoind_height - 100 or self.test_reorgs: self.db_undo.put("undo_info_%d" % (height % 100), repr(undo_info)) - @staticmethod - def common_prefix(word1, word2): + + def common_prefix(self, word1, word2): max_len = min(len(word1),len(word2)) - for i in xrange(max_len): + for i in range(max_len): if word2[i] != word1[i]: index = i break @@ -345,69 +176,109 @@ def common_prefix(word1, word2): index = max_len return word1[0:index] - def put_node(self, key, node): - self.db_utxo.put(key, node.serialized()) + + def put_node(self, key, d, batch=None): + k = 0 + serialized = '' + for i in range(256): + if chr(i) in d.keys(): + k += 1< addr self.db_addr.delete(txi) + # add to history s = self.db_hist.get(addr) if s is None: s = '' - txo = (txid + int_to_hex4(index) + int_to_hex4(height)).decode('hex') - s += txi + int_to_bytes4(in_height) + txo + txo = (txid + int_to_hex(index,4) + int_to_hex(height,4)).decode('hex') + s += txi + int_to_hex(in_height,4).decode('hex') + txo s = s[ -80*self.pruning_limit:] self.db_hist.put(addr, s) @@ -624,7 +552,7 @@ def revert_set_spent(self, addr, txi, undo): self.db_addr.put(txi, addr) v, height = undo.pop(leaf) - self.add_key(leaf, v, height) + self.add_address(leaf, v, height) # revert add to history s = self.db_hist.get(addr) @@ -638,20 +566,23 @@ def revert_set_spent(self, addr, txi, undo): + + + def import_transaction(self, txid, tx, block_height, touched_addr): undo = { 'prev_addr':[] } # contains the list of pruned items for each address in the tx; also, 'prev_addr' is a list of prev addresses - + prev_addr = [] for i, x in enumerate(tx.get('inputs')): - txi = (x.get('prevout_hash') + int_to_hex4(x.get('prevout_n'))).decode('hex') + txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex') addr = self.get_address(txi) - if addr is not None: + if addr is not None: self.set_spent(addr, txi, txid, i, block_height, undo) touched_addr.add(addr) prev_addr.append(addr) - undo['prev_addr'] = prev_addr + undo['prev_addr'] = prev_addr # here I add only the outputs to history; maybe I want to add inputs too (that's in the other loop) for x in tx.get('outputs'): @@ -675,8 +606,9 @@ def revert_transaction(self, txid, tx, block_height, touched_addr, undo): for i, x in reversed(list(enumerate(tx.get('inputs')))): addr = prev_addr[i] if addr is not None: - txi = (x.get('prevout_hash') + int_to_hex4(x.get('prevout_n'))).decode('hex') + txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex') self.revert_set_spent(addr, txi, undo) touched_addr.add(addr) assert undo == {} + diff --git a/src/stratum_http.py b/src/stratum_http.py new file mode 100644 index 00000000..b73ed83d --- /dev/null +++ b/src/stratum_http.py @@ -0,0 +1,382 @@ +#!/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 +# . +""" +sessions are identified with cookies + - each session has a buffer of responses to requests + + +from the processor point of view: + - the user only defines process() ; the rest is session management. thus sessions should not belong to processor + +""" +import json +import logging +import os +import Queue +import SimpleXMLRPCServer +import socket +import SocketServer +import sys +import time +import threading +import traceback +import types + +import jsonrpclib +from jsonrpclib import Fault +from jsonrpclib.jsonrpc import USE_UNIX_SOCKETS + +try: + import fcntl +except ImportError: + # For Windows + fcntl = None + + +from processor import Session +from utils import random_string, print_log + + +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 not isinstance(request, types.DictType): + return Fault(-32600, 'Request must be {}, not %s.' % type(request)) + rpcid = request.get('id', None) + version = get_version(request) + if not version: + return Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid) + 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: + return Fault(-32600, 'Invalid request parameters or method.', rpcid=rpcid) + return True + + +class StratumJSONRPCDispatcher(SimpleXMLRPCServer.SimpleXMLRPCDispatcher): + + def __init__(self, encoding=None): + # todo: use super + SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, allow_none=True, encoding=encoding) + + def _marshaled_dispatch(self, session_id, 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 + + session = self.dispatcher.get_session_by_address(session_id) + if not session: + return 'Error: session not found' + session.time = time.time() + + responses = [] + if not isinstance(request, types.ListType): + request = [request] + + for req_entry in request: + result = validate_request(req_entry) + if type(result) is Fault: + responses.append(result.response()) + continue + + self.dispatcher.do_dispatch(session, req_entry) + + if req_entry['method'] == 'server.stop': + return json.dumps({'result': 'ok'}) + + r = self.poll_session(session) + 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 create_session(self): + session_id = random_string(20) + session = HttpSession(self.dispatcher, session_id) + return session_id + + def poll_session(self, session): + q = session.pending_responses + responses = [] + while not q.empty(): + r = q.get() + responses.append(r) + #print "poll: %d responses"%len(responses) + return responses + + +class StratumJSONRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): + + def do_OPTIONS(self): + self.send_response(200) + self.send_header('Allow', 'GET, POST, OPTIONS') + self.send_header('Access-Control-Allow-Origin', '*') + self.send_header('Access-Control-Allow-Headers', 'Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, Accept-Language, Accept, Origin') + self.send_header('Content-Length', '0') + self.end_headers() + + def do_GET(self): + if not self.is_rpc_path_valid(): + self.report_404() + return + try: + session_id = None + c = self.headers.get('cookie') + if c: + if c[0:8] == 'SESSION=': + #print "found cookie", c[8:] + session_id = c[8:] + + if session_id is None: + session_id = self.server.create_session() + #print "setting cookie", session_id + + data = json.dumps([]) + response = self.server._marshaled_dispatch(session_id, 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 is None: + response = '' + + if session_id: + self.send_header("Set-Cookie", "SESSION=%s" % session_id) + + self.send_header("Content-type", "application/json-rpc") + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + self.wfile.flush() + self.shutdown_connection() + + 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) + + session_id = None + c = self.headers.get('cookie') + if c: + if c[0:8] == 'SESSION=': + #print "found cookie", c[8:] + session_id = c[8:] + + if session_id is None: + session_id = self.server.create_session() + #print "setting cookie", session_id + + response = self.server._marshaled_dispatch(session_id, 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 is None: + response = '' + + if session_id: + self.send_header("Set-Cookie", "SESSION=%s" % session_id) + + self.send_header("Content-type", "application/json-rpc") + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Content-length", str(len(response))) + self.end_headers() + self.wfile.write(response) + self.wfile.flush() + self.shutdown_connection() + + def shutdown_connection(self): + self.connection.shutdown(1) + + +class SSLRequestHandler(StratumJSONRPCRequestHandler): + def setup(self): + self.connection = self.request + self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) + self.wfile = socket._fileobject(self.request, "wb", self.wbufsize) + + def shutdown_connection(self): + self.connection.shutdown() + + +class SSLTCPServer(SocketServer.TCPServer): + def __init__(self, server_address, certfile, keyfile, RequestHandlerClass, bind_and_activate=True): + from OpenSSL import SSL + SocketServer.BaseServer.__init__(self, server_address, RequestHandlerClass) + ctx = SSL.Context(SSL.SSLv23_METHOD) + ctx.use_privatekey_file(keyfile) + ctx.use_certificate_file(certfile) + self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type)) + if bind_and_activate: + self.server_bind() + self.server_activate() + + def shutdown_request(self, request): + #request.shutdown() + pass + + +class StratumHTTPServer(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) + + 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) + + +class StratumHTTPSSLServer(SSLTCPServer, StratumJSONRPCDispatcher): + + allow_reuse_address = True + + def __init__(self, addr, certfile, keyfile, + requestHandler=SSLRequestHandler, + 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) + + SSLTCPServer.__init__(self, addr, certfile, keyfile, 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) + + +class HttpSession(Session): + + def __init__(self, dispatcher, session_id): + Session.__init__(self, dispatcher) + self.pending_responses = Queue.Queue() + self.address = session_id + self.name = "HTTP" + self.timeout = 60 + self.dispatcher.add_session(self) + + def send_response(self, response): + raw_response = json.dumps(response) + self.pending_responses.put(response) + + + +class HttpServer(threading.Thread): + def __init__(self, dispatcher, host, port, use_ssl, certfile, keyfile): + self.shared = dispatcher.shared + self.dispatcher = dispatcher.request_dispatcher + threading.Thread.__init__(self) + self.daemon = True + self.host = host + self.port = port + self.use_ssl = use_ssl + self.certfile = certfile + self.keyfile = keyfile + self.lock = threading.Lock() + + def run(self): + # see http://code.google.com/p/jsonrpclib/ + from SocketServer import ThreadingMixIn + if self.use_ssl: + class StratumThreadedServer(ThreadingMixIn, StratumHTTPSSLServer): + pass + self.server = StratumThreadedServer((self.host, self.port), self.certfile, self.keyfile) + print_log("HTTPS server started.") + else: + class StratumThreadedServer(ThreadingMixIn, StratumHTTPServer): + pass + self.server = StratumThreadedServer((self.host, self.port)) + print_log("HTTP server started.") + + self.server.dispatcher = self.dispatcher + self.server.register_function(None, 'server.stop') + self.server.register_function(None, 'server.info') + + self.server.serve_forever() diff --git a/src/stratum_tcp.py b/src/stratum_tcp.py index d7dad44b..6114d192 100644 --- a/src/stratum_tcp.py +++ b/src/stratum_tcp.py @@ -1,26 +1,3 @@ -#!/usr/bin/env python -# Copyright(C) 2011-2016 Thomas Voegtlin -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - import json import Queue as queue import socket @@ -35,7 +12,6 @@ READ_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR READ_WRITE = READ_ONLY | select.POLLOUT -WRITE_ONLY = select.POLLOUT TIMEOUT = 100 import ssl @@ -66,7 +42,7 @@ def __init__(self, dispatcher, connection, address, use_ssl, ssl_certfile, ssl_k self.message = '' self.retry_msg = '' self.handshake = not self.use_ssl - self.mode = None + self.need_write = True def connection(self): if self.stopped(): @@ -88,6 +64,8 @@ def send_response(self, response): except BaseException as e: logger.error('send_response:' + str(e)) return + if self.response_queue.empty(): + self.need_write = True self.response_queue.put(msg) def parse_message(self): @@ -131,17 +109,21 @@ def handle_command(self, raw_command, session): except: session.send_response({"error": "bad JSON"}) return True + try: # Try to load vital fields, and return an error if # unsuccessful. message_id = command['id'] method = command['method'] - except: + except KeyError: # Return an error JSON in response. session.send_response({"error": "syntax error", "request": raw_command}) else: - #print_log("new request", command) self.dispatcher.push_request(session, command) + ## sleep a bit to prevent a single session from DOSing the queue + #time.sleep(0.01) + + @@ -180,11 +162,11 @@ def stop_session(fd): try: # unregister before we close s poller.unregister(fd) - session = self.fd_to_session.pop(fd) - # this will close the socket - session.stop() except BaseException as e: - logger.error('stop_session error:' + str(e)) + logger.error('unregister error:' + str(e)) + session = self.fd_to_session.pop(fd) + # this will close the socket + session.stop() def check_do_handshake(session): if session.handshake: @@ -198,7 +180,7 @@ def check_do_handshake(session): poller.modify(session.raw_connection, READ_WRITE) return else: - raise BaseException(str(err)) + raise poller.modify(session.raw_connection, READ_ONLY) session.handshake = True @@ -221,40 +203,22 @@ def check_do_handshake(session): else: now = time.time() for fd, session in self.fd_to_session.items(): - # Anti-DOS: wait 0.01 second between requests - if now - session.time > 0.01 and session.message: - cmd = session.parse_message() - if not cmd: - break - if cmd == 'quit': - data = False - break - session.time = now - self.handle_command(cmd, session) - - # Anti-DOS: Stop reading if the session does not read responses - if session.response_queue.empty(): - mode = READ_ONLY - elif session.response_queue.qsize() < 200: - mode = READ_WRITE - else: - mode = WRITE_ONLY - if mode != session.mode: - poller.modify(session.raw_connection, mode) - session.mode = mode - - # Collect garbage + # check sessions that need to write + if session.need_write: + poller.modify(session.raw_connection, READ_WRITE) + session.need_write = False + # collect garbage if now - session.time > session.timeout: stop_session(fd) events = poller.poll(TIMEOUT) for fd, flag in events: - # open new session + if fd == sock_fd: if flag & (select.POLLIN | select.POLLPRI): + connection, address = sock.accept() try: - connection, address = sock.accept() session = TcpSession(self.dispatcher, connection, address, use_ssl=self.use_ssl, ssl_certfile=self.ssl_certfile, ssl_keyfile=self.ssl_keyfile) except BaseException as e: @@ -262,25 +226,25 @@ def check_do_handshake(session): connection.close() continue connection = session._connection - connection.setblocking(False) + connection.setblocking(0) self.fd_to_session[connection.fileno()] = session poller.register(connection, READ_ONLY) + try: + check_do_handshake(session) + except BaseException as e: + logger.error('handshake failure:' + str(e) + ' ' + repr(address)) + stop_session(connection.fileno()) continue - # existing session + session = self.fd_to_session[fd] s = session._connection - # non-blocking handshake try: check_do_handshake(session) - except BaseException as e: - #logger.error('handshake failure:' + str(e) + ' ' + repr(session.address)) + except: stop_session(fd) continue - # anti DOS - now = time.time() - if now - session.time < 0.01: - continue - # Read input messages. + + # handle inputs if flag & (select.POLLIN | select.POLLPRI): try: data = s.recv(self.buffer_size) @@ -297,21 +261,24 @@ def check_do_handshake(session): logger.error('recv error: ' + repr(x) +' %d'%fd) stop_session(fd) continue - except ValueError as e: - logger.error('recv error: ' + str(e) +' %d'%fd) - stop_session(fd) - continue if data: - session.message += data if len(data) == self.buffer_size: - redo.append((fd, flag)) - + redo.append( (fd, flag) ) + session.message += data + while True: + cmd = session.parse_message() + if not cmd: + break + if cmd == 'quit': + data = False + break + self.handle_command(cmd, session) if not data: stop_session(fd) continue elif flag & select.POLLHUP: - print_log('client hung up', session.address) + print_log('client hung up', address) stop_session(fd) elif flag & select.POLLOUT: @@ -322,6 +289,8 @@ def check_do_handshake(session): try: next_msg = session.response_queue.get_nowait() except queue.Empty: + # No messages waiting so stop checking for writability. + poller.modify(s, READ_ONLY) continue try: sent = s.send(next_msg) @@ -338,6 +307,3 @@ def check_do_handshake(session): elif flag & select.POLLNVAL: print_log('invalid request', session.address) stop_session(fd) - - - print_log('TCP thread terminating', self.shared.stopped()) diff --git a/src/test/test_utils.py b/src/test/test_utils.py index f7e22bf1..0c2c6d8e 100644 --- a/src/test/test_utils.py +++ b/src/test/test_utils.py @@ -11,14 +11,14 @@ def test_hash_160_to_address(self): self.assertEqual(hash_160_to_address('04e9fca1'.decode('hex')), None) self.assertEqual(hash_160_to_address('04e9fca1f96e021dfaf35bbea267ec2c60787c1b1337'.decode('hex')), None) self.assertEqual(hash_160_to_address('1ad3b0b711f211655a01142fbb8fecabe8e30b93'.decode('hex')), - '13SrAVFPVW1txSj34B8Bd6hnDbyPsVGa92') + 'LMfoRhZDaAFxDFRCEK7Uu7mYRpLg3BuCoQ') def test_bc_address_to_hash_160(self): self.assertEqual(bc_address_to_hash_160(None), None) self.assertEqual(bc_address_to_hash_160(''), None) - self.assertEqual(bc_address_to_hash_160('13SrAVFPVW1txSj34B8Bd6hnDbyPsVGa921337'), None) - self.assertEqual(bc_address_to_hash_160('13SrAVFPVW1txSj34B8Bd6hnDbyPsVGa92').encode('hex'), + self.assertEqual(bc_address_to_hash_160('LMfoRhZDaAFxDFRCEK7Uu7mYRpLg3BuCoQ1337'), None) + self.assertEqual(bc_address_to_hash_160('LMfoRhZDaAFxDFRCEK7Uu7mYRpLg3BuCoQ').encode('hex'), '1ad3b0b711f211655a01142fbb8fecabe8e30b93') diff --git a/src/utils.py b/src/utils.py index 99d8fcf4..00524e70 100644 --- a/src/utils.py +++ b/src/utils.py @@ -1,44 +1,56 @@ #!/usr/bin/env python -# Copyright(C) 2011-2016 Thomas Voegtlin # -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation files -# (the "Software"), to deal in the Software without restriction, -# including without limitation the rights to use, copy, modify, merge, -# publish, distribute, sublicense, and/or sell copies of the Software, -# and to permit persons to whom the Software is furnished to do so, -# subject to the following conditions: +# Electrum - lightweight Bitcoin client +# Copyright (C) 2011 thomasv@gitorious # -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . from itertools import imap import threading import time import hashlib -import struct +import sys __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) global PUBKEY_ADDRESS global SCRIPT_ADDRESS -PUBKEY_ADDRESS = 0 -SCRIPT_ADDRESS = 5 +PUBKEY_ADDRESS = 55 +SCRIPT_ADDRESS = 28 def rev_hex(s): return s.decode('hex')[::-1].encode('hex') +def int_to_hex(i, length=1): + s = hex(i)[2:].rstrip('L') + s = "0"*(2*length - len(s)) + s + return rev_hex(s) + + +def var_int(i): + if i < 0xfd: + return int_to_hex(i) + elif i <= 0xffff: + return "fd" + int_to_hex(i, 2) + elif i <= 0xffffffff: + return "fe" + int_to_hex(i, 4) + else: + return "ff" + int_to_hex(i, 8) + + Hash = lambda x: hashlib.sha256(hashlib.sha256(x).digest()).digest() @@ -53,46 +65,26 @@ def header_to_string(res): if pbh is None: pbh = '0'*64 - return int_to_hex4(res.get('version')) \ - + rev_hex(pbh) \ - + rev_hex(res.get('merkle_root')) \ - + int_to_hex4(int(res.get('timestamp'))) \ - + int_to_hex4(int(res.get('bits'))) \ - + int_to_hex4(int(res.get('nonce'))) - - -_unpack_bytes4_to_int = struct.Struct("