Repository: electroneum/electroneum-pool Branch: master Commit: a00d271505d2 Files: 29 Total size: 160.0 KB Directory structure: gitextract_5psyk48y/ ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── config_example.json ├── init.js ├── lib/ │ ├── api.js │ ├── apiInterfaces.js │ ├── blockUnlocker.js │ ├── cli.js │ ├── configReader.js │ ├── exceptionWriter.js │ ├── logger.js │ ├── paymentProcessor.js │ ├── pool.js │ └── utils.js ├── package.json ├── redisBlocksUpgrade.js └── website_example/ ├── admin_core_stats_massive_stuff.html ├── config.js ├── custom.css ├── custom.js ├── index.html └── pages/ ├── .home.html.swp ├── downloads.html ├── home.html ├── payments.html ├── pool_blocks.html └── support.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules/ .idea/ config.json logs/ ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - "0.10.48" addons: apt: sources: - ubuntu-toolchain-r-test packages: - libssl-dev - libboost-all-dev - build-essential - cmake - pkg-config - libunbound-dev ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ Electroneum Pool (node-cryptonote-pool) ==================== High performance Node.js (with native C addons) mining pool for CryptoNote based coins such as Electroneum, Monero, Bytecoin, QuazarCoin, HoneyPenny, etc.. Comes with lightweight example front-end script which uses the pool's AJAX API. #### Table of Contents * [Features](#features) * [Community Support](#community--support) * [Pools Using This Software](#pools-using-this-software) * [Usage](#usage) * [Requirements](#requirements) * [Downloading & Installing](#1-downloading--installing) * [Configuration](#3-configuration) * [Configure Easyminer](#4-optional-configure-cryptonote-easy-miner-for-your-pool) * [Starting the Pool](#5-start-the-pool) * [Host the front-end](#6-host-the-front-end) * [Customizing your website](#7-customize-your-website) * [SSL](#ssl) * [Upgrading](#upgrading) * [Donations](#donations) * [Credits](#credits) * [License](#license) #### Features * TCP (stratum-like) protocol for server-push based jobs * Compared to old HTTP protocol, this has a higher hash rate, lower network/CPU server load, lower orphan block percent, and less error prone * IP banning to prevent low-diff share attacks * Socket flooding detection * Payment processing * Splintered transactions to deal with max transaction size * Minimum payment threshold before balance will be paid out * Minimum denomination for truncating payment amount precision to reduce size/complexity of block transactions * Detailed logging * Ability to configure multiple ports - each with their own difficulty * Variable difficulty / share limiter * Share trust algorithm to reduce share validation hashing CPU load * Clustering for vertical scaling * Modular components for horizontal scaling (pool server, database, stats/API, payment processing, front-end) * Live stats API (using AJAX long polling with CORS) * Currency network/block difficulty * Current block height * Network hashrate * Pool hashrate * Each miners' individual stats (hashrate, shares submitted, pending balance, total paid, etc) * Blocks found (pending, confirmed, and orphaned) * An easily extendable, responsive, light-weight front-end using API to display data * Worker login validation (make sure miners are using proper wallet addresses for mining) ### Community / Support * [Electroneum Forum](https://electroneumtalk.proboards.com/) * [Electroneum Github](https://github.com/electroneum) #### Pools Using This Software * http://etn.kkmining.club/ <-- Hongkong Pool 0.1% fee * https://easyhash.io/pools/etn * http://etn.proxpool.com <- cloud based, high efficiency, EU Pool Server, 0% fee * https://easyhash.io/pools/etn * https://etn.mymininghub.com/ * https://dedpool.io/etn <- US Pool * http://etn.pool.nocroom.com < - cloud based, US Pool Server * http://etn.bl0ck.party <- Atlanta, GA, USA -- 0.5% fee * https://www.etn.rustylock.club - cloud based, high efficiency, EU Pool Server * https://supportetn.eu - nodejs-pool, EU Pool Server, 0.2 % fee Usage === #### Requirements * A non root user. To intall & run the pool, you should do so as a user that is NOT root. Running as root will cause issues. * Coin daemon [electroneum repo](https://www.github.com/electroneum/electroneum) * To compile the coin you'll need several packages as detailed in the repo's readme. A quick one line command is below: * `sudo apt install build-essential cmake pkg-config libboost-all-dev libssl-dev libunbound-dev` * [NVM](https://github.com/creationix/nvm) to install v0.10.48. Follow the instructions for installing nvm (Node Version Manager). Then type `nvm install 0.10.48`. Once finished, type `nvm use 0.10.48`. * [Redis](http://redis.io/) key-value store v2.6+ ([follow these instructions](http://redis.io/topics/quickstart)) * libssl required for the node-multi-hashing module * For Ubuntu: `sudo apt-get install libssl-dev` * Boost is required for the cryptonote-util module * For Ubuntu: `sudo apt-get install libboost-all-dev` * Screen - for running the different parts of the pool in the background. This may come pre-installed on some systems. * For Ubuntu: `sudo apt-get install screen` * Usage: `screen -S daemond` <--- Use to run the daemond `screen -S rpc` <---- Use to run rpc `screen -S website` < --- use to run website `screen -list` <---- List screens `screen -x website` <--- reconnect to screen website `CTRL + a` then `CTRL + d` <----- detatch from a screen ##### Node.js v0.10.48 * This version of node.js is required to run the cryptonight-util and node-multi-hashing modules. These modules were created by other users and currently only work with Node.js 0.10.48. Please ensure that you have this version of node.js installed before opening an issue asking for help. ##### Seriously Those are legitimate requirements. If you use a different version of Node.js or Redis that may come with your system package manager then you will have problems. Follow the linked instructions to get the last stable versions. [**Redis security warning**](http://redis.io/topics/security): be sure firewall access to redis - an easy way is to include `bind 127.0.0.1` in your `redis.conf` file. Also it's a good idea to learn about and understand software that you are using - a good place to start with redis is [data persistence](http://redis.io/topics/persistence). #### 1) Downloading & Installing Clone the repository and run `npm update` for all the dependencies to be installed: ```bash git clone https://github.com/electroneum/electroneum-pool.git pool cd pool npm update ``` #### 2) Daemon & Wallet Firstly, You'll need to download & compile the daemon source code found [here](https://www.github.com/electroneum/electroneum) Secondly, Start a screen session, e.g `screen -S daemon`. Then run `./electroneumd` wherever the compiled binaries are. This will download the blockchain. You'll need to wait until you're fully synced before continuing. Thirdly, Once synced you'll need to create a wallet. Detatch from the screen session using `CTRL + A, CTRL + D` (This works for me on putty). Open up another screen session, e.g `screen -S wallet`. Then run `./electroneum-wallet-cli` wherever the compiled binaries are, This will take your through creating a wallet. Once generated, type `exit` to close the wallet. Lastly you need to start the wallet RPC server which makes the payments to your miners. This can be started using `./electroneum-wallet-rpc --wallet-file walletfilename --password walletfilepassword --rpc-bind-port 26969 --disable-rpc-login` `walletfilename` & `walletfilepassword` are what you supplied when generating the wallet. You can change the port, just remember to change it in the config.json file. [**Security Warning**]We strongly recommend that you transfer funds out of this wallet regularly. This way, if your server is comprimised you won't lose all your profits. Bear in mind you'll need to leave enough to pay any outstanding payments to miners. #### 3) Configuration *Warning for Cryptonote coins other than Electroneum:* this software may or may not work with any given cryptonote coin. Be wary of altcoins that change the number of minimum coin units because you will have to reconfigure several config values to account for those changes. Unless you're offering a bounty reward - do not open an issue asking for help getting a coin other than electroneum working with this software. Copy the `config_example.json` file to `config.json` then overview each options and change any to match your preferred setup. Explanation for each field: ```javascript { "coin": "electroneum", "symbol": "ETN", "logging": { "files": { "level": "info", "directory": "logs", "flushInterval": 5 }, "console": { "level": "info", "colors": true } }, "poolServer": { "enabled": true, "clusterForks": "auto", "poolAddress": "WALLETADDRESSHERE", "blockRefreshInterval": 1000, "minerTimeout": 900, "ports": [ { "port": 3333, "difficulty": 100, "desc": "Low end hardware" }, { "port": 5555, "difficulty": 2000, "desc": "Mid range hardware" }, { "port": 7777, "difficulty": 10000, "desc": "High end hardware" } ], "varDiff": { "minDiff": 2, "maxDiff": 100000, "targetTime": 100, "retargetTime": 30, "variancePercent": 30, "maxJump": 100 }, "shareTrust": { "enabled": true, "min": 10, "stepDown": 3, "threshold": 10, "penalty": 30 }, "banning": { "enabled": true, "time": 600, "invalidPercent": 25, "checkThreshold": 30 }, "slushMining": { "enabled": false, "weight": 300, "lastBlockCheckRate": 1 } }, "payments": { "enabled": true, "interval": 600, "maxAddresses": 10, "mixin": 0, "transferFee": 1, "minPayment": 10000, "denomination": 100 }, "blockUnlocker": { "enabled": true, "interval": 30, "depth": 20, "poolFee": 1.8, "devDonation": 0.1, "coreDevDonation": 0.1 }, "api": { "enabled": true, "hashrateWindow": 600, "updateInterval": 3, "port": 8117, "blocks": 30, "payments": 30, "password": "test" }, "daemon": { "host": "127.0.0.1", "port": 26968 }, "wallet": { "host": "127.0.0.1", "port": 26969 }, "redis": { "host": "127.0.0.1", "port": 6379, "auth": null } } ``` #### 4) [Optional] Configure cryptonote-easy-miner for your pool Your miners that are Windows users can use [cryptonote-easy-miner](https://github.com/zone117x/cryptonote-easy-miner) which will automatically generate their wallet address and stratup multiple threads of simpleminer. You can download it and edit the `config.ini` file to point to your own pool. Inside the `easyminer` folder, edit `config.init` to point to your pool details ```ini pool_host=example.com pool_port=5555 ``` Rezip and upload to your server or a file host. Then change the `easyminerDownload` link in your `config.json` file to point to your zip file. #### 5) Start the pool ```bash node init.js ``` The file `config.json` is used by default but a file can be specified using the `-config=file` command argument, for example: ```bash node init.js -config=config_backup.json ``` This software contains four distinct modules: * `pool` - Which opens ports for miners to connect and processes shares * `api` - Used by the website to display network, pool and miners' data * `unlocker` - Processes block candidates and increases miners' balances when blocks are unlocked * `payments` - Sends out payments to miners according to their balances stored in redis By default, running the `init.js` script will start up all four modules. You can optionally have the script start only start a specific module by using the `-module=name` command argument, for example: ```bash node init.js -module=api ``` [Example screenshot](http://i.imgur.com/SEgrI3b.png) of running the pool in single module mode with tmux. #### 6) Host the front-end Simply host the contents of the `website_example` directory on file server capable of serving simple static files. Edit the variables in the `website_example/config.js` file to use your pool's specific configuration. Variable explanations: ```javascript /* Must point to the API setup in your config.json file. */ var api = "http://poolhost:8117"; /* Minimum units in a single coin, for Electroneum its 100. */ var coinUnits = 100; /* Pool server host to instruct your miners to point to. */ var poolHost = "poolhost.com"; /* IRC Server and room used for embedded KiwiIRC chat. */ var irc = "irc.freenode.net/#electroneum"; /* Contact email address. */ var email = "support@poolhost.com"; /* Market stat display params from https://www.cryptonator.com/widget - Not used for Electroneum pool */ var cryptonatorWidget = ["XMR-BTC", "XMR-USD", "XMR-EUR", "XMR-GBP"]; /* Download link to cryptonote-easy-miner for Windows users. */ var easyminerDownload = "https://github.com/zone117x/cryptonote-easy-miner/releases/"; /* Used for front-end block links. */ var blockchainExplorer = "https://blockexplorer.electroneum.com/block/"; /* Used by front-end transaction links. */ var transactionExplorer = "https://blockexplorer.electroneum.com/tx"; ``` #### 7) Customize your website The following files are included so that you can customize your pool website without having to make significant changes to `index.html` or other front-end files thus reducing the difficulty of merging updates with your own changes: * `custom.css` for creating your own pool style * `custom.js` for changing the functionality of your pool website Then simply serve the files via nginx, Apache, Google Drive, or anything that can host static content. #### SSL You can configure the API to be accessible via SSL using various methods. Find an example for nginx below: * Inside your SSL Listener add the following: ``` javascript location /json_rpc { proxy_pass http://127.0.0.1:26968/json_rpc; } location ~ ^/api/(.*) { proxy_pass http://127.0.0.1:8117/$1$is_args$args; } ``` By adding this you will need to make your `api` variable in the `website_example/config.js` include the /api. For example: `var api = "http://poolhost/api";` You no longer need to include the port in the variable because of the proxy connection. #### Upgrading When updating to the latest code its important to not only `git pull` the latest from this repo, but to also update the Node.js modules, and any config files that may have been changed. * Inside your pool directory (where the init.js script is) do `git pull` to get the latest code. * Remove the dependencies by deleting the `node_modules` directory with `rm -r node_modules`. * Run `npm update` to force updating/reinstalling of the dependencies. * Compare your `config.json` to the latest example ones in this repo or the ones in the setup instructions where each config field is explained. You may need to modify or add any new changes. Donations --------- * ETN: `etnkCFXeExRaBhbDNq66TQ3rF9XSkMreei8t1jXfT2ndgY6bnsNEUtEKbEhba3YHk2CuPCpxZFrGNcAJ9Lv22ACY7eapPgQtNb` * XMR: `48rB9X6ygZQ4uNBSKJP3MKU9iFK87e8vejEi762eNdTPB61A9VayUnL75HHi2SER3gf5i9PXpiS2kiCwDyanvNm5S5Aq3WF` Credits === * [LucasJones](//github.com/LucasJones) - Co-dev on this project; did tons of debugging for binary structures and fixing them. Pool couldn't have been made without him. * [surfer43](//github.com/iamasupernova) - Did lots of testing during development to help figure out bugs and get them fixed * [wallet42](http://moneropool.com) - Funded development of payment denominating and min threshold feature * [Wolf0](https://bitcointalk.org/index.php?action=profile;u=80740) - Helped try to deobfuscate some of the daemon code for getting a bug fixed * [Tacotime](https://bitcointalk.org/index.php?action=profile;u=19270) - helping with figuring out certain problems and lead the bounty for this project's creation License ------- Released under the GNU General Public License v2 http://www.gnu.org/licenses/gpl-2.0.html ================================================ FILE: config_example.json ================================================ { "coin": "electroneum", "symbol": "ETN", "logging": { "files": { "level": "info", "directory": "logs", "flushInterval": 5 }, "console": { "level": "info", "colors": true } }, "poolServer": { "enabled": true, "clusterForks": "auto", "poolAddress": "WALLETADDRESSHERE", "blockRefreshInterval": 1000, "minerTimeout": 900, "ports": [ { "port": 3333, "difficulty": 100, "desc": "Low end hardware" }, { "port": 5555, "difficulty": 2000, "desc": "Mid range hardware" }, { "port": 7777, "difficulty": 10000, "desc": "High end hardware" } ], "varDiff": { "minDiff": 2, "maxDiff": 100000, "targetTime": 100, "retargetTime": 30, "variancePercent": 30, "maxJump": 100 }, "shareTrust": { "enabled": true, "min": 10, "stepDown": 3, "threshold": 10, "penalty": 30 }, "banning": { "enabled": true, "time": 600, "invalidPercent": 25, "checkThreshold": 30 }, "slushMining": { "enabled": false, "weight": 300, "lastBlockCheckRate": 1 } }, "payments": { "enabled": true, "interval": 600, "maxAddresses": 10, "mixin": 0, "transferFee": 1, "minPayment": 10000, "denomination": 100 }, "blockUnlocker": { "enabled": true, "interval": 30, "depth": 20, "poolFee": 1.8, "devDonation": 0.1, "coreDevDonation": 0.1 }, "api": { "enabled": true, "hashrateWindow": 600, "updateInterval": 3, "port": 8117, "blocks": 30, "payments": 30, "password": "your_password" }, "daemon": { "host": "127.0.0.1", "port": 26968 }, "wallet": { "host": "127.0.0.1", "port": 26969 }, "redis": { "host": "127.0.0.1", "port": 6379, "auth": null } } ================================================ FILE: init.js ================================================ var fs = require('fs'); var cluster = require('cluster'); var os = require('os'); var redis = require('redis'); require('./lib/configReader.js'); require('./lib/logger.js'); global.redisClient = redis.createClient(config.redis.port, config.redis.host, {auth_pass: config.redis.auth}); if (cluster.isWorker){ switch(process.env.workerType){ case 'pool': require('./lib/pool.js'); break; case 'blockUnlocker': require('./lib/blockUnlocker.js'); break; case 'paymentProcessor': require('./lib/paymentProcessor.js'); break; case 'api': require('./lib/api.js'); break; case 'cli': require('./lib/cli.js'); break } return; } var logSystem = 'master'; require('./lib/exceptionWriter.js')(logSystem); var singleModule = (function(){ var validModules = ['pool', 'api', 'unlocker', 'payments']; for (var i = 0; i < process.argv.length; i++){ if (process.argv[i].indexOf('-module=') === 0){ var moduleName = process.argv[i].split('=')[1]; if (validModules.indexOf(moduleName) > -1) return moduleName; log('error', logSystem, 'Invalid module "%s", valid modules: %s', [moduleName, validModules.join(', ')]); process.exit(); } } })(); (function init(){ checkRedisVersion(function(){ if (singleModule){ log('info', logSystem, 'Running in single module mode: %s', [singleModule]); switch(singleModule){ case 'pool': spawnPoolWorkers(); break; case 'unlocker': spawnBlockUnlocker(); break; case 'payments': spawnPaymentProcessor(); break; case 'api': spawnApi(); break; } } else{ spawnPoolWorkers(); spawnBlockUnlocker(); spawnPaymentProcessor(); spawnApi(); } spawnCli(); }); })(); function checkRedisVersion(callback){ redisClient.info(function(error, response){ if (error){ log('error', logSystem, 'Redis version check failed'); return; } var parts = response.split('\r\n'); var version; var versionString; for (var i = 0; i < parts.length; i++){ if (parts[i].indexOf(':') !== -1){ var valParts = parts[i].split(':'); if (valParts[0] === 'redis_version'){ versionString = valParts[1]; version = parseFloat(versionString); break; } } } if (!version){ log('error', logSystem, 'Could not detect redis version - must be super old or broken'); return; } else if (version < 2.6){ log('error', logSystem, "You're using redis version %s the minimum required version is 2.6. Follow the damn usage instructions...", [versionString]); return; } callback(); }); } function spawnPoolWorkers(){ if (!config.poolServer || !config.poolServer.enabled || !config.poolServer.ports || config.poolServer.ports.length === 0) return; if (config.poolServer.ports.length === 0){ log('error', logSystem, 'Pool server enabled but no ports specified'); return; } var numForks = (function(){ if (!config.poolServer.clusterForks) return 1; if (config.poolServer.clusterForks === 'auto') return os.cpus().length; if (isNaN(config.poolServer.clusterForks)) return 1; return config.poolServer.clusterForks; })(); var poolWorkers = {}; var createPoolWorker = function(forkId){ var worker = cluster.fork({ workerType: 'pool', forkId: forkId }); worker.forkId = forkId; worker.type = 'pool'; poolWorkers[forkId] = worker; worker.on('exit', function(code, signal){ log('error', logSystem, 'Pool fork %s died, spawning replacement worker...', [forkId]); setTimeout(function(){ createPoolWorker(forkId); }, 2000); }).on('message', function(msg){ switch(msg.type){ case 'banIP': Object.keys(cluster.workers).forEach(function(id) { if (cluster.workers[id].type === 'pool'){ cluster.workers[id].send({type: 'banIP', ip: msg.ip}); } }); break; } }); }; var i = 1; var spawnInterval = setInterval(function(){ createPoolWorker(i.toString()); i++; if (i - 1 === numForks){ clearInterval(spawnInterval); log('info', logSystem, 'Pool spawned on %d thread(s)', [numForks]); } }, 10); } function spawnBlockUnlocker(){ if (!config.blockUnlocker || !config.blockUnlocker.enabled) return; var worker = cluster.fork({ workerType: 'blockUnlocker' }); worker.on('exit', function(code, signal){ log('error', logSystem, 'Block unlocker died, spawning replacement...'); setTimeout(function(){ spawnBlockUnlocker(); }, 2000); }); } function spawnPaymentProcessor(){ if (!config.payments || !config.payments.enabled) return; var worker = cluster.fork({ workerType: 'paymentProcessor' }); worker.on('exit', function(code, signal){ log('error', logSystem, 'Payment processor died, spawning replacement...'); setTimeout(function(){ spawnPaymentProcessor(); }, 2000); }); } function spawnApi(){ if (!config.api || !config.api.enabled) return; var worker = cluster.fork({ workerType: 'api' }); worker.on('exit', function(code, signal){ log('error', logSystem, 'API died, spawning replacement...'); setTimeout(function(){ spawnApi(); }, 2000); }); } function spawnCli(){ } ================================================ FILE: lib/api.js ================================================ var fs = require('fs'); var http = require('http'); var url = require("url"); var zlib = require('zlib'); var async = require('async'); var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet); var logSystem = 'api'; require('./exceptionWriter.js')(logSystem); var redisCommands = [ ['zremrangebyscore', config.coin + ':hashrate', '-inf', ''], ['zrange', config.coin + ':hashrate', 0, -1], ['hgetall', config.coin + ':stats'], ['zrange', config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES'], ['zrevrange', config.coin + ':blocks:matured', 0, config.api.blocks - 1, 'WITHSCORES'], ['hgetall', config.coin + ':shares:roundCurrent'], ['hgetall', config.coin + ':stats'], ['zcard', config.coin + ':blocks:matured'], ['zrevrange', config.coin + ':payments:all', 0, config.api.payments - 1, 'WITHSCORES'], ['zcard', config.coin + ':payments:all'], ['keys', config.coin + ':payments:*'] ]; var currentStats = ""; var currentStatsCompressed = ""; var minerStats = {}; var liveConnections = {}; var addressConnections = {}; function collectStats(){ var startTime = Date.now(); var redisFinished; var daemonFinished; var windowTime = (((Date.now() / 1000) - config.api.hashrateWindow) | 0).toString(); redisCommands[0][3] = '(' + windowTime; async.parallel({ pool: function(callback){ redisClient.multi(redisCommands).exec(function(error, replies){ redisFinished = Date.now(); var dateNowSeconds = Date.now() / 1000 | 0; if (error){ log('error', logSystem, 'Error getting redis data %j', [error]); callback(true); return; } var data = { stats: replies[2], blocks: replies[3].concat(replies[4]), totalBlocks: parseInt(replies[7]) + (replies[3].length / 2), payments: replies[8], totalPayments: parseInt(replies[9]), totalMinersPaid: replies[10].length - 1 }; var hashrates = replies[1]; minerStats = {}; for (var i = 0; i < hashrates.length; i++){ var hashParts = hashrates[i].split(':'); minerStats[hashParts[1]] = (minerStats[hashParts[1]] || 0) + parseInt(hashParts[0]); } var totalShares = 0; for (var miner in minerStats){ var shares = minerStats[miner]; totalShares += shares; minerStats[miner] = getReadableHashRateString(shares / config.api.hashrateWindow); } data.miners = Object.keys(minerStats).length; data.hashrate = totalShares / config.api.hashrateWindow; data.roundHashes = 0; if (replies[5]){ for (var miner in replies[5]){ if (config.poolServer.slushMining.enabled) { data.roundHashes += parseInt(replies[5][miner]) / Math.pow(Math.E, ((data.lastBlockFound - dateNowSeconds) / config.poolServer.slushMining.weight)); //TODO: Abstract: If something different than lastBlockfound is used for scoreTime, this needs change. } else { data.roundHashes += parseInt(replies[5][miner]); } } } if (replies[6]) { data.lastBlockFound = replies[6].lastBlockFound; } callback(null, data); }); }, network: function(callback){ apiInterfaces.rpcDaemon('getlastblockheader', {}, function(error, reply){ daemonFinished = Date.now(); if (error){ log('error', logSystem, 'Error getting daemon data %j', [error]); callback(true); return; } var blockHeader = reply.block_header; callback(null, { difficulty: blockHeader.difficulty, height: blockHeader.height, timestamp: blockHeader.timestamp, reward: blockHeader.reward, hash: blockHeader.hash }); }); }, config: function(callback){ callback(null, { ports: getPublicPorts(config.poolServer.ports), hashrateWindow: config.api.hashrateWindow, fee: config.blockUnlocker.poolFee, coin: config.coin, symbol: config.symbol, depth: config.blockUnlocker.depth, donation: config.blockUnlocker.devDonation, coreDonation: config.blockUnlocker.coreDevDonation, doDonations: doDonations, version: version, minPaymentThreshold: config.payments.minPayment, denominationUnit: config.payments.denomination, blockTime: config.poolServer.slushMining.blockTime, slushMiningEnabled: config.poolServer.slushMining.enabled, weight: config.poolServer.slushMining.weight }); } }, function(error, results){ log('info', logSystem, 'Stat collection finished: %d ms redis, %d ms daemon', [redisFinished - startTime, daemonFinished - startTime]); if (error){ log('error', logSystem, 'Error collecting all stats'); } else{ currentStats = JSON.stringify(results); zlib.deflateRaw(currentStats, function(error, result){ currentStatsCompressed = result; broadcastLiveStats(); }); } setTimeout(collectStats, config.api.updateInterval * 1000); }); } function getPublicPorts(ports){ return ports.filter(function(port) { return !port.hidden; }); } function getReadableHashRateString(hashrate){ var i = 0; var byteUnits = [' H', ' KH', ' MH', ' GH', ' TH', ' PH' ]; while (hashrate > 1000){ hashrate = hashrate / 1000; i++; } return hashrate.toFixed(2) + byteUnits[i]; } function broadcastLiveStats(){ log('info', logSystem, 'Broadcasting to %d visitors and %d address lookups', [Object.keys(liveConnections).length, Object.keys(addressConnections).length]); for (var uid in liveConnections){ var res = liveConnections[uid]; res.end(currentStatsCompressed); } var redisCommands = []; for (var address in addressConnections){ redisCommands.push(['hgetall', config.coin + ':workers:' + address]); redisCommands.push(['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES']); } redisClient.multi(redisCommands).exec(function(error, replies){ var addresses = Object.keys(addressConnections); for (var i = 0; i < addresses.length; i++){ var offset = i * 2; var address = addresses[i]; var stats = replies[offset]; var res = addressConnections[address]; if (!stats){ res.end(JSON.stringify({error: "not found"})); return; } stats.hashrate = minerStats[address]; res.end(JSON.stringify({stats: stats, payments: replies[offset + 1]})); } }); } function handleMinerStats(urlParts, response){ response.writeHead(200, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', 'Connection': 'keep-alive' }); response.write('\n'); var address = urlParts.query.address; console.log(urlParts); if (urlParts.query.longpoll === 'true'){ redisClient.exists(config.coin + ':workers:' + address, function(error, result){ if (!result){ response.end(JSON.stringify({error: 'not found'})); return; } addressConnections[address] = response; response.on('finish', function(){ delete addressConnections[address]; }) }); } else{ redisClient.multi([ ['hgetall', config.coin + ':workers:' + address], ['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES'] ]).exec(function(error, replies){ if (error || !replies[0]){ response.end(JSON.stringify({error: 'not found'})); return; } var stats = replies[0]; stats.hashrate = minerStats[address]; response.end(JSON.stringify({stats: stats, payments: replies[1]})); }); } } function handleGetPayments(urlParts, response){ var paymentKey = ':payments:all'; if (urlParts.query.address) paymentKey = ':payments:' + urlParts.query.address; redisClient.zrevrangebyscore( config.coin + paymentKey, '(' + urlParts.query.time, '-inf', 'WITHSCORES', 'LIMIT', 0, config.api.payments, function(err, result){ var reply; if (err) reply = JSON.stringify({error: 'query failed'}); else reply = JSON.stringify(result); response.writeHead("200", { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', 'Content-Length': reply.length }); response.end(reply); } ) } function handleGetBlocks(urlParts, response){ redisClient.zrevrangebyscore( config.coin + ':blocks:matured', '(' + urlParts.query.height, '-inf', 'WITHSCORES', 'LIMIT', 0, config.api.blocks, function(err, result){ var reply; if (err) reply = JSON.stringify({error: 'query failed'}); else reply = JSON.stringify(result); response.writeHead("200", { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', 'Content-Length': reply.length }); response.end(reply); }); } collectStats(); function authorize(request, response){ response.setHeader('Access-Control-Allow-Origin', '*'); var sentPass = url.parse(request.url, true).query.password; if (sentPass !== config.api.password){ response.statusCode = 401; response.end('invalid password'); return; } response.statusCode = 200; response.setHeader('Cache-Control', 'no-cache'); response.setHeader('Content-Type', 'application/json'); return true; } function handleAdminStats(response){ async.waterfall([ //Get worker keys & unlocked blocks function(callback){ redisClient.multi([ ['keys', config.coin + ':workers:*'], ['zrange', config.coin + ':blocks:matured', 0, -1] ]).exec(function(error, replies) { if (error) { log('error', logSystem, 'Error trying to get admin data from redis %j', [error]); callback(true); return; } callback(null, replies[0], replies[1]); }); }, //Get worker balances function(workerKeys, blocks, callback){ var redisCommands = workerKeys.map(function(k){ return ['hmget', k, 'balance', 'paid']; }); redisClient.multi(redisCommands).exec(function(error, replies){ if (error){ log('error', logSystem, 'Error with getting balances from redis %j', [error]); callback(true); return; } callback(null, replies, blocks); }); }, function(workerData, blocks, callback){ var stats = { totalOwed: 0, totalPaid: 0, totalRevenue: 0, totalDiff: 0, totalShares: 0, blocksOrphaned: 0, blocksUnlocked: 0, totalWorkers: 0 }; for (var i = 0; i < workerData.length; i++){ stats.totalOwed += parseInt(workerData[i][0]) || 0; stats.totalPaid += parseInt(workerData[i][1]) || 0; stats.totalWorkers++; } for (var i = 0; i < blocks.length; i++){ var block = blocks[i].split(':'); if (block[5]) { stats.blocksUnlocked++; stats.totalDiff += parseInt(block[2]); stats.totalShares += parseInt(block[3]); stats.totalRevenue += parseInt(block[5]); } else{ stats.blocksOrphaned++; } } callback(null, stats); } ], function(error, stats){ if (error){ response.end(JSON.stringify({error: 'error collecting stats'})); return; } response.end(JSON.stringify(stats)); } ); } var server = http.createServer(function(request, response){ if (request.method.toUpperCase() === "OPTIONS"){ response.writeHead("204", "No Content", { "access-control-allow-origin": '*', "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS", "access-control-allow-headers": "content-type, accept", "access-control-max-age": 10, // Seconds. "content-length": 0 }); return(response.end()); } var urlParts = url.parse(request.url, true); switch(urlParts.pathname){ case '/stats': var reply = currentStatsCompressed; response.writeHead("200", { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', 'Content-Encoding': 'deflate', 'Content-Length': reply.length }); response.end(reply); break; case '/live_stats': response.writeHead(200, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', 'Content-Encoding': 'deflate', 'Connection': 'keep-alive' }); var uid = Math.random().toString(); liveConnections[uid] = response; response.on("finish", function() { delete liveConnections[uid]; }); break; case '/stats_address': handleMinerStats(urlParts, response); break; case '/get_payments': handleGetPayments(urlParts, response); break; case '/get_blocks': handleGetBlocks(urlParts, response); break; case '/admin_stats': if (!authorize(request, response)) return; log('warn', logSystem, 'Admin authorized'); handleAdminStats(response); break; default: response.writeHead(404, { 'Access-Control-Allow-Origin': '*' }); response.end('Invalid API call'); break; } }); server.listen(config.api.port, function(){ log('info', logSystem, 'API started & listening on port %d', [config.api.port]); }); ================================================ FILE: lib/apiInterfaces.js ================================================ var http = require('http'); function jsonHttpRequest(host, port, data, callback){ var options = { hostname: host, port: port, path: '/json_rpc', method: 'POST', headers: { 'Content-Length': data.length, 'Content-Type': 'application/json', 'Accept': 'application/json' } }; var req = http.request(options, function(res){ var replyData = ''; res.setEncoding('utf8'); res.on('data', function(chunk){ replyData += chunk; }); res.on('end', function(){ var replyJson; try{ replyJson = JSON.parse(replyData); } catch(e){ callback(e); return; } callback(null, replyJson); }); }); req.on('error', function(e){ callback(e); }); req.end(data); } function rpc(host, port, method, params, callback){ var data = JSON.stringify({ id: "0", jsonrpc: "2.0", method: method, params: params }); jsonHttpRequest(host, port, data, function(error, replyJson){ if (error){ callback(error); return; } callback(replyJson.error, replyJson.result) }); } function batchRpc(host, port, array, callback){ var rpcArray = []; for (var i = 0; i < array.length; i++){ rpcArray.push({ id: i.toString(), jsonrpc: "2.0", method: array[i][0], params: array[i][1] }); } var data = JSON.stringify(rpcArray); jsonHttpRequest(host, port, data, callback); } module.exports = function(daemonConfig, walletConfig){ return { batchRpcDaemon: function(batchArray, callback){ batchRpc(daemonConfig.host, daemonConfig.port, batchArray, callback); }, rpcDaemon: function(method, params, callback){ rpc(daemonConfig.host, daemonConfig.port, method, params, callback); }, rpcWallet: function(method, params, callback){ rpc(walletConfig.host, walletConfig.port, method, params, callback); } } }; ================================================ FILE: lib/blockUnlocker.js ================================================ var async = require('async'); var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet); var logSystem = 'unlocker'; require('./exceptionWriter.js')(logSystem); log('info', logSystem, 'Started'); //Use this in payment processing to get block info once batch RPC is supported /* var batchArray = [ ['getblockheaderbyheight', {height: 21}], ['getblockheaderbyheight', {height: 22}], ['getblockheaderbyheight', {height: 23 }] ]; apiInterfaces.batchRpcDaemon(batchArray, function(error, response){ }); */ function runInterval(){ async.waterfall([ //Get all block candidates in redis function(callback){ redisClient.zrange(config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES', function(error, results){ if (error){ log('error', logSystem, 'Error trying to get pending blocks from redis %j', [error]); callback(true); return; } if (results.length === 0){ log('info', logSystem, 'No blocks candidates in redis'); callback(true); return; } var blocks = []; for (var i = 0; i < results.length; i += 2){ var parts = results[i].split(':'); blocks.push({ serialized: results[i], height: parseInt(results[i + 1]), hash: parts[0], time: parts[1], difficulty: parts[2], shares: parts[3] }); } callback(null, blocks); }); }, //Check if blocks are orphaned function(blocks, callback){ async.filter(blocks, function(block, mapCback){ apiInterfaces.rpcDaemon('getblockheaderbyheight', {height: block.height}, function(error, result){ if (error){ log('error', logSystem, 'Error with getblockheaderbyheight RPC request for block %s - %j', [block.serialized, error]); block.unlocked = false; mapCback(); return; } if (!result.block_header){ log('error', logSystem, 'Error with getblockheaderbyheight, no details returned for %s - %j', [block.serialized, result]); block.unlocked = false; mapCback(); return; } var blockHeader = result.block_header; block.orphaned = blockHeader.hash === block.hash ? 0 : 1; block.unlocked = blockHeader.depth >= config.blockUnlocker.depth; block.reward = blockHeader.reward; mapCback(block.unlocked); }); }, function(unlockedBlocks){ if (unlockedBlocks.length === 0){ log('info', logSystem, 'No pending blocks are unlocked yet (%d pending)', [blocks.length]); callback(true); return; } callback(null, unlockedBlocks) }) }, //Get worker shares for each unlocked block function(blocks, callback){ var redisCommands = blocks.map(function(block){ return ['hgetall', config.coin + ':shares:round' + block.height]; }); redisClient.multi(redisCommands).exec(function(error, replies){ if (error){ log('error', logSystem, 'Error with getting round shares from redis %j', [error]); callback(true); return; } for (var i = 0; i < replies.length; i++){ var workerShares = replies[i]; blocks[i].workerShares = workerShares; } callback(null, blocks); }); }, //Handle orphaned blocks function(blocks, callback){ var orphanCommands = []; blocks.forEach(function(block){ if (!block.orphaned) return; orphanCommands.push(['del', config.coin + ':shares:round' + block.height]); orphanCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]); orphanCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [ block.hash, block.time, block.difficulty, block.shares, block.orphaned ].join(':')]); if (block.workerShares) { var workerShares = block.workerShares; Object.keys(workerShares).forEach(function (worker) { orphanCommands.push(['hincrby', config.coin + ':shares:roundCurrent', worker, workerShares[worker]]); }); } }); if (orphanCommands.length > 0){ redisClient.multi(orphanCommands).exec(function(error, replies){ if (error){ log('error', logSystem, 'Error with cleaning up data in redis for orphan block(s) %j', [error]); callback(true); return; } callback(null, blocks); }); } else{ callback(null, blocks); } }, //Handle unlocked blocks function(blocks, callback){ var unlockedBlocksCommands = []; var payments = {}; var totalBlocksUnlocked = 0; blocks.forEach(function(block){ if (block.orphaned) return; totalBlocksUnlocked++; unlockedBlocksCommands.push(['del', config.coin + ':shares:round' + block.height]); unlockedBlocksCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]); unlockedBlocksCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [ block.hash, block.time, block.difficulty, block.shares, block.orphaned, block.reward ].join(':')]); var feePercent = config.blockUnlocker.poolFee / 100; if (doDonations) { feePercent += config.blockUnlocker.devDonation / 100; feePercent += config.blockUnlocker.coreDevDonation / 100; var devDonation = block.reward * (config.blockUnlocker.devDonation / 100); payments[devDonationAddress] = devDonation; var coreDevDonation = block.reward * (config.blockUnlocker.coreDevDonation / 100); payments[coreDevDonationAddress] = coreDevDonation; } var reward = block.reward - (block.reward * feePercent); if (block.workerShares) { var totalShares = parseInt(block.shares); Object.keys(block.workerShares).forEach(function (worker) { var percent = block.workerShares[worker] / totalShares; var workerReward = reward * percent; payments[worker] = (payments[worker] || 0) + workerReward; }); } }); for (var worker in payments) { var amount = parseInt(payments[worker]); if (amount <= 0){ delete payments[worker]; continue; } unlockedBlocksCommands.push(['hincrby', config.coin + ':workers:' + worker, 'balance', amount]); } if (unlockedBlocksCommands.length === 0){ log('info', logSystem, 'No unlocked blocks yet (%d pending)', [blocks.length]); callback(true); return; } redisClient.multi(unlockedBlocksCommands).exec(function(error, replies){ if (error){ log('error', logSystem, 'Error with unlocking blocks %j', [error]); callback(true); return; } log('info', logSystem, 'Unlocked %d blocks and update balances for %d workers', [totalBlocksUnlocked, Object.keys(payments).length]); callback(null); }); } ], function(error, result){ setTimeout(runInterval, config.blockUnlocker.interval * 1000); }) } runInterval(); ================================================ FILE: lib/cli.js ================================================ ================================================ FILE: lib/configReader.js ================================================ var fs = require('fs'); var configFile = (function(){ for (var i = 0; i < process.argv.length; i++){ if (process.argv[i].indexOf('-config=') === 0) return process.argv[i].split('=')[1]; } return 'config.json'; })(); try { global.config = JSON.parse(fs.readFileSync(configFile)); } catch(e){ console.error('Failed to read config file ' + configFile + '\n\n' + e); return; } global.version = "v0.99.3.3"; global.devDonationAddress = '45Jmf8PnJKziGyrLouJMeBFw2yVyX1QB52sKEQ4S1VSU2NVsaVGPNu4bWKkaHaeZ6tWCepP6iceZk8XhTLzDaEVa72QrtVh'; global.coreDevDonationAddress = '46BeWrHpwXmHDpDEUmZBWZfoQpdc6HaERCNmx1pEYL2rAcuwufPN9rXHHtyUA4QVy66qeFQkn6sfK8aHYjA3jk3o1Bv16em'; global.doDonations = devDonationAddress[0] === config.poolServer.poolAddress[0] && ( config.blockUnlocker.devDonation > 0 || config.blockUnlocker.coreDevDonation > 0 ); ================================================ FILE: lib/exceptionWriter.js ================================================ var fs = require('fs'); var cluster = require('cluster'); var dateFormat = require('dateformat'); module.exports = function(logSystem){ process.on('uncaughtException', function(err) { console.log('\n' + err.stack + '\n'); var time = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'); fs.appendFile(config.logging.files.directory + '/' + logSystem + '_crash.log', time + '\n' + err.stack + '\n\n', function(err){ if (cluster.isWorker) process.exit(); }); }); }; ================================================ FILE: lib/logger.js ================================================ var fs = require('fs'); var util = require('util'); var dateFormat = require('dateformat'); var clc = require('cli-color'); var severityMap = { 'info': clc.blue, 'warn': clc.yellow, 'error': clc.red }; var severityLevels = ['info', 'warn', 'error']; var logDir = config.logging.files.directory; if (!fs.existsSync(logDir)){ try { fs.mkdirSync(logDir); } catch(e){ throw e; } } var pendingWrites = {}; setInterval(function(){ for (var fileName in pendingWrites){ var data = pendingWrites[fileName]; fs.appendFile(fileName, data); delete pendingWrites[fileName]; } }, config.logging.files.flushInterval * 1000); global.log = function(severity, system, text, data){ var logConsole = severityLevels.indexOf(severity) >= severityLevels.indexOf(config.logging.console.level); var logFiles = severityLevels.indexOf(severity) >= severityLevels.indexOf(config.logging.files.level); if (!logConsole && !logFiles) return; var time = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'); var formattedMessage = text; if (data) { data.unshift(text); formattedMessage = util.format.apply(null, data); } if (logConsole){ if (config.logging.console.colors) console.log(severityMap[severity](time) + clc.white.bold(' [' + system + '] ') + formattedMessage); else console.log(time + ' [' + system + '] ' + formattedMessage); } if (logFiles) { var fileName = logDir + '/' + system + '_' + severity + '.log'; var fileLine = time + ' ' + formattedMessage + '\n'; pendingWrites[fileName] = (pendingWrites[fileName] || '') + fileLine; } }; ================================================ FILE: lib/paymentProcessor.js ================================================ var fs = require('fs'); var async = require('async'); var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet); var logSystem = 'payments'; require('./exceptionWriter.js')(logSystem); log('info', logSystem, 'Started'); function runInterval(){ async.waterfall([ //Get worker keys function(callback){ redisClient.keys(config.coin + ':workers:*', function(error, result) { if (error) { log('error', logSystem, 'Error trying to get worker balances from redis %j', [error]); callback(true); return; } callback(null, result); }); }, //Get worker balances function(keys, callback){ var redisCommands = keys.map(function(k){ return ['hget', k, 'balance']; }); redisClient.multi(redisCommands).exec(function(error, replies){ if (error){ log('error', logSystem, 'Error with getting balances from redis %j', [error]); callback(true); return; } var balances = {}; for (var i = 0; i < replies.length; i++){ var parts = keys[i].split(':'); var workerId = parts[parts.length - 1]; balances[workerId] = parseInt(replies[i]) || 0 } callback(null, balances); }); }, //Filter workers under balance threshold for payment function(balances, callback){ var payments = {}; for (var worker in balances){ var balance = balances[worker]; if (balance >= config.payments.minPayment){ var remainder = balance % config.payments.denomination; var payout = balance - remainder; if (payout < 0) continue; payments[worker] = payout; } } if (Object.keys(payments).length === 0){ log('info', logSystem, 'No workers\' balances reached the minimum payment threshold'); callback(true); return; } var transferCommands = []; var transferCommandsLength = Math.ceil(Object.keys(payments).length / config.payments.maxAddresses); for (var i = 0; i < transferCommandsLength; i++){ transferCommands.push({ redis: [], amount : 0, rpc: { destinations: [], fee: config.payments.transferFee, mixin: config.payments.mixin, unlock_time: 0 } }); } var addresses = 0; var commandIndex = 0; for (var worker in payments){ var anAmount = payments[worker].toString(); var amount = parseFloat(anAmount); transferCommands[commandIndex].rpc.destinations.push({amount: amount, address: worker}); transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'balance', -amount]); transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'paid', amount]); transferCommands[commandIndex].amount += amount; addresses++; if (addresses >= config.payments.maxAddresses){ commandIndex++; addresses = 0; } } var timeOffset = 0; async.filter(transferCommands, function(transferCmd, cback){ apiInterfaces.rpcWallet('transfer', transferCmd.rpc, function(error, result){ if (error){ log('error', logSystem, 'Error with transfer RPC request to wallet daemon %j', [error]); log('error', logSystem, 'Payments failed to send to %j', transferCmd.rpc.destinations); cback(false); return; } var now = (timeOffset++) + Date.now() / 1000 | 0; var txHash = result.tx_hash.replace('<', '').replace('>', ''); transferCmd.redis.push(['zadd', config.coin + ':payments:all', now, [ txHash, transferCmd.amount, transferCmd.rpc.fee, transferCmd.rpc.mixin, Object.keys(transferCmd.rpc.destinations).length ].join(':')]); for (var i = 0; i < transferCmd.rpc.destinations.length; i++){ var destination = transferCmd.rpc.destinations[i]; transferCmd.redis.push(['zadd', config.coin + ':payments:' + destination.address, now, [ txHash, destination.amount, transferCmd.rpc.fee, transferCmd.rpc.mixin ].join(':')]); } log('info', logSystem, 'Payments sent via wallet daemon %j', [result]); redisClient.multi(transferCmd.redis).exec(function(error, replies){ if (error){ log('error', logSystem, 'Super critical error! Payments sent yet failing to update balance in redis, double payouts likely to happen %j', [error]); log('error', logSystem, 'Double payments likely to be sent to %j', transferCmd.rpc.destinations); cback(false); return; } cback(true); }); }); }, function(succeeded){ var failedAmount = transferCommands.length - succeeded.length; log('info', logSystem, 'Payments splintered and %d successfully sent, %d failed', [succeeded.length, failedAmount]); callback(null); }); } ], function(error, result){ setTimeout(runInterval, config.payments.interval * 1000); }); } runInterval(); ================================================ FILE: lib/pool.js ================================================ var fs = require('fs'); var net = require('net'); var crypto = require('crypto'); var async = require('async'); var bignum = require('bignum'); var multiHashing = require('multi-hashing'); var cnUtil = require('cryptonote-util'); // Must exactly be 8 hex chars var noncePattern = new RegExp("^[0-9A-Fa-f]{8}$"); var threadId = '(Thread ' + process.env.forkId + ') '; var logSystem = 'pool'; require('./exceptionWriter.js')(logSystem); var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet); var utils = require('./utils.js'); var log = function(severity, system, text, data){ global.log(severity, system, threadId + text, data); }; var cryptoNight = multiHashing['cryptonight']; function cryptoNightFast(buf) { return cryptoNight(Buffer.concat([new Buffer([buf.length]), buf]), true); } var diff1 = bignum('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 16); var instanceId = crypto.randomBytes(4); var validBlockTemplates = []; var currentBlockTemplate; //Vars for slush mining var scoreTime; var lastChecked = 0; var connectedMiners = {}; var bannedIPs = {}; var perIPStats = {}; var shareTrustEnabled = config.poolServer.shareTrust && config.poolServer.shareTrust.enabled; var shareTrustStepFloat = shareTrustEnabled ? config.poolServer.shareTrust.stepDown / 100 : 0; var shareTrustMinFloat = shareTrustEnabled ? config.poolServer.shareTrust.min / 100 : 0; var banningEnabled = config.poolServer.banning && config.poolServer.banning.enabled; setInterval(function(){ var now = Date.now() / 1000 | 0; for (var minerId in connectedMiners){ var miner = connectedMiners[minerId]; miner.retarget(now); } }, config.poolServer.varDiff.retargetTime * 1000); /* Every 30 seconds clear out timed-out miners and old bans */ setInterval(function(){ var now = Date.now(); var timeout = config.poolServer.minerTimeout * 1000; for (var minerId in connectedMiners){ var miner = connectedMiners[minerId]; if (now - miner.lastBeat > timeout){ log('warn', logSystem, 'Miner timed out and disconnected %s@%s', [miner.login, miner.ip]); delete connectedMiners[minerId]; } } if (banningEnabled){ for (ip in bannedIPs){ var banTime = bannedIPs[ip]; if (now - banTime > config.poolServer.banning.time * 1000) { delete bannedIPs[ip]; delete perIPStats[ip]; log('info', logSystem, 'Ban dropped for %s', [ip]); } } } }, 30000); process.on('message', function(message) { switch (message.type) { case 'banIP': bannedIPs[message.ip] = Date.now(); break; } }); function IsBannedIp(ip){ if (!banningEnabled || !bannedIPs[ip]) return false; var bannedTime = bannedIPs[ip]; var bannedTimeAgo = Date.now() - bannedTime; var timeLeft = config.poolServer.banning.time * 1000 - bannedTimeAgo; if (timeLeft > 0){ return true; } else { delete bannedIPs[ip]; log('info', logSystem, 'Ban dropped for %s', [ip]); return false; } } function BlockTemplate(template){ this.blob = template.blocktemplate_blob; this.difficulty = template.difficulty; this.height = template.height; this.reserveOffset = template.reserved_offset; this.buffer = new Buffer(this.blob, 'hex'); instanceId.copy(this.buffer, this.reserveOffset + 4, 0, 3); this.extraNonce = 0; } BlockTemplate.prototype = { nextBlob: function(){ this.buffer.writeUInt32BE(++this.extraNonce, this.reserveOffset); return cnUtil.convert_blob(this.buffer).toString('hex'); } }; function getBlockTemplate(callback){ apiInterfaces.rpcDaemon('getblocktemplate', {reserve_size: 8, wallet_address: config.poolServer.poolAddress}, callback); } function jobRefresh(loop, callback){ callback = callback || function(){}; getBlockTemplate(function(error, result){ if (loop) setTimeout(function(){ jobRefresh(true); }, config.poolServer.blockRefreshInterval); if (error){ log('error', logSystem, 'Error polling getblocktemplate %j', [error]); callback(false); return; } if (!currentBlockTemplate || result.height > currentBlockTemplate.height){ log('info', logSystem, 'New block to mine at height %d w/ difficulty of %d', [result.height, result.difficulty]); processBlockTemplate(result); } callback(true); }) } function processBlockTemplate(template){ if (currentBlockTemplate) validBlockTemplates.push(currentBlockTemplate); if (validBlockTemplates.length > 3) validBlockTemplates.shift(); currentBlockTemplate = new BlockTemplate(template); for (var minerId in connectedMiners){ var miner = connectedMiners[minerId]; miner.pushMessage('job', miner.getJob()); } } (function init(){ jobRefresh(true, function(sucessful){ if (!sucessful){ log('error', logSystem, 'Could not start pool'); return; } startPoolServerTcp(function(successful){ }); }); })(); var VarDiff = (function(){ var variance = config.poolServer.varDiff.variancePercent / 100 * config.poolServer.varDiff.targetTime; return { variance: variance, bufferSize: config.poolServer.varDiff.retargetTime / config.poolServer.varDiff.targetTime * 4, tMin: config.poolServer.varDiff.targetTime - variance, tMax: config.poolServer.varDiff.targetTime + variance, maxJump: config.poolServer.varDiff.maxJump }; })(); function Miner(id, login, pass, ip, startingDiff, pushMessage){ this.id = id; this.login = login; this.pass = pass; this.ip = ip; this.pushMessage = pushMessage; this.heartbeat(); this.difficulty = startingDiff; this.validJobs = []; // Vardiff related variables this.shareTimeRing = utils.ringBuffer(16); this.lastShareTime = Date.now() / 1000 | 0; if (shareTrustEnabled) { this.trust = { threshold: config.poolServer.shareTrust.threshold, probability: 1, penalty: 0 }; } } Miner.prototype = { retarget: function(now){ var options = config.poolServer.varDiff; var sinceLast = now - this.lastShareTime; var decreaser = sinceLast > VarDiff.tMax; var avg = this.shareTimeRing.avg(decreaser ? sinceLast : null); var newDiff; var direction; if (avg > VarDiff.tMax && this.difficulty > options.minDiff){ newDiff = options.targetTime / avg * this.difficulty; newDiff = newDiff > options.minDiff ? newDiff : options.minDiff; direction = -1; } else if (avg < VarDiff.tMin && this.difficulty < options.maxDiff){ newDiff = options.targetTime / avg * this.difficulty; newDiff = newDiff < options.maxDiff ? newDiff : options.maxDiff; direction = 1; } else{ return; } if (Math.abs(newDiff - this.difficulty) / this.difficulty * 100 > options.maxJump){ var change = options.maxJump / 100 * this.difficulty * direction; newDiff = this.difficulty + change; } this.setNewDiff(newDiff); this.shareTimeRing.clear(); if (decreaser) this.lastShareTime = now; }, setNewDiff: function(newDiff){ newDiff = Math.round(newDiff); if (this.difficulty === newDiff) return; log('info', logSystem, 'Retargetting difficulty %d to %d for %s', [this.difficulty, newDiff, this.login]); this.pendingDifficulty = newDiff; this.pushMessage('job', this.getJob()); }, heartbeat: function(){ this.lastBeat = Date.now(); }, getTargetHex: function(){ if (this.pendingDifficulty){ this.lastDifficulty = this.difficulty; this.difficulty = this.pendingDifficulty; this.pendingDifficulty = null; } var padded = new Buffer(32); padded.fill(0); var diffBuff = diff1.div(this.difficulty).toBuffer(); diffBuff.copy(padded, 32 - diffBuff.length); var buff = padded.slice(0, 4); var buffArray = buff.toJSON(); buffArray.reverse(); var buffReversed = new Buffer(buffArray); this.target = buffReversed.readUInt32BE(0); var hex = buffReversed.toString('hex'); return hex; }, getJob: function(){ if (this.lastBlockHeight === currentBlockTemplate.height && !this.pendingDifficulty) { return { blob: '', job_id: '', target: '' }; } var blob = currentBlockTemplate.nextBlob(); this.lastBlockHeight = currentBlockTemplate.height; var target = this.getTargetHex(); var newJob = { id: utils.uid(), extraNonce: currentBlockTemplate.extraNonce, height: currentBlockTemplate.height, difficulty: this.difficulty, score: this.score, diffHex: this.diffHex, submissions: [] }; this.validJobs.push(newJob); if (this.validJobs.length > 4) this.validJobs.shift(); return { blob: blob, job_id: newJob.id, target: target, id: this.id }; }, checkBan: function(validShare){ if (!banningEnabled) return; // Init global per-IP shares stats if (!perIPStats[this.ip]){ perIPStats[this.ip] = { validShares: 0, invalidShares: 0 }; } var stats = perIPStats[this.ip]; validShare ? stats.validShares++ : stats.invalidShares++; if (stats.validShares + stats.invalidShares >= config.poolServer.banning.checkThreshold){ if (stats.invalidShares / stats.validShares >= config.poolServer.banning.invalidPercent / 100){ log('warn', logSystem, 'Banned %s@%s', [this.login, this.ip]); bannedIPs[this.ip] = Date.now(); delete connectedMiners[this.id]; process.send({type: 'banIP', ip: this.ip}); } else{ stats.invalidShares = 0; stats.validShares = 0; } } } }; function recordShareData(miner, job, shareDiff, blockCandidate, hashHex, shareType, blockTemplate){ var dateNow = Date.now(); var dateNowSeconds = dateNow / 1000 | 0; //Weighting older shares lower than newer ones to prevent pool hopping if (config.poolServer.slushMining.enabled) { if (lastChecked + config.poolServer.slushMining.lastBlockCheckRate <= dateNowSeconds || lastChecked == 0) { redisClient.hget(config.coin + ':stats', 'lastBlockFound', function(error, result) { if (error) { log('error', logSystem, 'Unable to determine the timestamp of the last block found'); return; } scoreTime = result / 1000 | 0; //scoreTime could potentially be something else than the beginning of the current round, though this would warrant changes in api.js (and potentially the redis db) lastChecked = dateNowSeconds; }); } job.score = job.difficulty * Math.pow(Math.E, ((dateNowSeconds - scoreTime) / config.poolServer.slushMining.weight)); //Score Calculation log('info', logSystem, 'Submitted score ' + job.score + ' with difficulty ' + job.difficulty + ' and the time ' + scoreTime); } else { job.score = job.difficulty; } var redisCommands = [ ['hincrby', config.coin + ':shares:roundCurrent', miner.login, job.score], ['zadd', config.coin + ':hashrate', dateNowSeconds, [job.difficulty, miner.login, dateNow].join(':')], ['hincrby', config.coin + ':workers:' + miner.login, 'hashes', job.difficulty], ['hset', config.coin + ':workers:' + miner.login, 'lastShare', dateNowSeconds] ]; if (blockCandidate){ redisCommands.push(['hset', config.coin + ':stats', 'lastBlockFound', Date.now()]); redisCommands.push(['rename', config.coin + ':shares:roundCurrent', config.coin + ':shares:round' + job.height]); redisCommands.push(['hgetall', config.coin + ':shares:round' + job.height]); } redisClient.multi(redisCommands).exec(function(err, replies){ if (err){ log('error', logSystem, 'Failed to insert share data into redis %j \n %j', [err, redisCommands]); return; } if (blockCandidate){ var workerShares = replies[replies.length - 1]; var totalShares = Object.keys(workerShares).reduce(function(p, c){ return p + parseInt(workerShares[c]) }, 0); redisClient.zadd(config.coin + ':blocks:candidates', job.height, [ hashHex, Date.now() / 1000 | 0, blockTemplate.difficulty, totalShares ].join(':'), function(err, result){ if (err){ log('error', logSystem, 'Failed inserting block candidate %s \n %j', [hashHex, err]); } }); } }); log('info', logSystem, 'Accepted %s share at difficulty %d/%d from %s@%s', [shareType, job.difficulty, shareDiff, miner.login, miner.ip]); } function processShare(miner, job, blockTemplate, nonce, resultHash){ var shareBuffer = new Buffer(blockTemplate.buffer.length); blockTemplate.buffer.copy(shareBuffer); shareBuffer.writeUInt32BE(job.extraNonce, blockTemplate.reserveOffset); new Buffer(nonce, 'hex').copy(shareBuffer, 39); var convertedBlob; var hash; var shareType; if (shareTrustEnabled && miner.trust.threshold <= 0 && miner.trust.penalty <= 0 && Math.random() > miner.trust.probability){ hash = new Buffer(resultHash, 'hex'); shareType = 'trusted'; } else { convertedBlob = cnUtil.convert_blob(shareBuffer); var cn_variant = convertedBlob[0] == 6 ? 1 : 0; //If v6 then use new variant else use previous hash = cryptoNight(convertedBlob, cn_variant); shareType = 'valid'; } if (hash.toString('hex') !== resultHash) { log('warn', logSystem, 'Bad hash from miner %s@%s', [miner.login, miner.ip]); return false; } var hashArray = hash.toJSON(); hashArray.reverse(); var hashNum = bignum.fromBuffer(new Buffer(hashArray)); var hashDiff = diff1.div(hashNum); if (hashDiff.ge(blockTemplate.difficulty)){ apiInterfaces.rpcDaemon('submitblock', [shareBuffer.toString('hex')], function(error, result){ if (error){ log('error', logSystem, 'Error submitting block at height %d from %s@%s, share type: "%s" - %j', [job.height, miner.login, miner.ip, shareType, error]); recordShareData(miner, job, hashDiff.toString(), false, null, shareType); } else{ var blockFastHash = cryptoNightFast(convertedBlob || cnUtil.convert_blob(shareBuffer)).toString('hex'); log('info', logSystem, 'Block %s found at height %d by miner %s@%s - submit result: %j', [blockFastHash.substr(0, 6), job.height, miner.login, miner.ip, result] ); recordShareData(miner, job, hashDiff.toString(), true, blockFastHash, shareType, blockTemplate); jobRefresh(); } }); } else if (hashDiff.lt(job.difficulty)){ log('warn', logSystem, 'Rejected low difficulty share of %s from %s@%s', [hashDiff.toString(), miner.login, miner.ip]); return false; } else{ recordShareData(miner, job, hashDiff.toString(), false, null, shareType); } return true; } function handleMinerMethod(method, params, ip, portData, sendReply, pushMessage){ var miner = connectedMiners[params.id]; // Check for ban here, so preconnected attackers can't continue to screw you if (IsBannedIp(ip)){ sendReply('your IP is banned'); return; } switch(method){ case 'login': if (!params.login){ sendReply('missing login'); return; } if (!utils.isValidAddress(params.login, config.poolServer.poolAddress[0])){ sendReply('invalid address used for login'); return; } var minerId = utils.uid(); miner = new Miner(minerId, params.login, params.pass, ip, portData.difficulty, pushMessage); connectedMiners[minerId] = miner; sendReply(null, { id: minerId, job: miner.getJob(), status: 'OK' }); log('info', logSystem, 'Miner connected %s@%s', [params.login, miner.ip]); break; case 'getjob': if (!miner){ sendReply('Unauthenticated'); return; } miner.heartbeat(); sendReply(null, miner.getJob()); break; case 'submit': if (!miner){ sendReply('Unauthenticated'); return; } miner.heartbeat(); var job = miner.validJobs.filter(function(job){ return job.id === params.job_id; })[0]; if (!job){ sendReply('Invalid job id'); return; } if (!noncePattern.test(params.nonce)) { var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : ''; log('warn', logSystem, 'Malformed nonce: ' + JSON.stringify(params) + ' from ' + minerText); perIPStats[miner.ip] = { validShares: 0, invalidShares: 999999 }; miner.checkBan(false); sendReply('Duplicate share'); return; } // Force lowercase for further comparison params.nonce = params.nonce.toLowerCase(); if (job.submissions.indexOf(params.nonce) !== -1){ var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : ''; log('warn', logSystem, 'Duplicate share: ' + JSON.stringify(params) + ' from ' + minerText); perIPStats[miner.ip] = { validShares: 0, invalidShares: 999999 }; miner.checkBan(false); sendReply('Duplicate share'); return; } job.submissions.push(params.nonce); var blockTemplate = currentBlockTemplate.height === job.height ? currentBlockTemplate : validBlockTemplates.filter(function(t){ return t.height === job.height; })[0]; if (!blockTemplate){ sendReply('Block expired'); return; } var shareAccepted = processShare(miner, job, blockTemplate, params.nonce, params.result); miner.checkBan(shareAccepted); if (shareTrustEnabled){ if (shareAccepted){ miner.trust.probability -= shareTrustStepFloat; if (miner.trust.probability < shareTrustMinFloat) miner.trust.probability = shareTrustMinFloat; miner.trust.penalty--; miner.trust.threshold--; } else{ log('warn', logSystem, 'Share trust broken by %s@%s', [miner.login, miner.ip]); miner.trust.probability = 1; miner.trust.penalty = config.poolServer.shareTrust.penalty; } } if (!shareAccepted){ sendReply('Low difficulty share'); return; } var now = Date.now() / 1000 | 0; miner.shareTimeRing.append(now - miner.lastShareTime); miner.lastShareTime = now; //miner.retarget(now); sendReply(null, {status: 'OK'}); break; case 'keepalived' : if (!miner){ sendReply('Unauthenticated'); return; } miner.heartbeat() sendReply(null, { status:'KEEPALIVED' }); break; default: sendReply("invalid method"); var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : ''; log('warn', logSystem, 'Invalid method: %s (%j) from %s', [method, params, minerText]); break; } } var httpResponse = ' 200 OK\nContent-Type: text/plain\nContent-Length: 20\n\nmining server online'; function startPoolServerTcp(callback){ async.each(config.poolServer.ports, function(portData, cback){ var handleMessage = function(socket, jsonData, pushMessage){ if (!jsonData.id) { log('warn', logSystem, 'Miner RPC request missing RPC id'); return; } else if (!jsonData.method) { log('warn', logSystem, 'Miner RPC request missing RPC method'); return; } else if (!jsonData.params) { log('warn', logSystem, 'Miner RPC request missing RPC params'); return; } var sendReply = function(error, result){ if(!socket.writable) return; var sendData = JSON.stringify({ id: jsonData.id, jsonrpc: "2.0", error: error ? {code: -1, message: error} : null, result: result }) + "\n"; socket.write(sendData); }; handleMinerMethod(jsonData.method, jsonData.params, socket.remoteAddress, portData, sendReply, pushMessage); }; net.createServer(function(socket){ socket.setKeepAlive(true); socket.setEncoding('utf8'); var dataBuffer = ''; var pushMessage = function(method, params){ if(!socket.writable) return; var sendData = JSON.stringify({ jsonrpc: "2.0", method: method, params: params }) + "\n"; socket.write(sendData); }; socket.on('data', function(d){ dataBuffer += d; if (Buffer.byteLength(dataBuffer, 'utf8') > 10240){ //10KB dataBuffer = null; log('warn', logSystem, 'Socket flooding detected and prevented from %s', [socket.remoteAddress]); socket.destroy(); return; } if (dataBuffer.indexOf('\n') !== -1){ var messages = dataBuffer.split('\n'); var incomplete = dataBuffer.slice(-1) === '\n' ? '' : messages.pop(); for (var i = 0; i < messages.length; i++){ var message = messages[i]; if (message.trim() === '') continue; var jsonData; try{ jsonData = JSON.parse(message); } catch(e){ if (message.indexOf('GET /') === 0) { if (message.indexOf('HTTP/1.1') !== -1) { socket.end('HTTP/1.1' + httpResponse); break; } else if (message.indexOf('HTTP/1.0') !== -1) { socket.end('HTTP/1.0' + httpResponse); break; } } log('warn', logSystem, 'Malformed message from %s: %s', [socket.remoteAddress, message]); socket.destroy(); break; } handleMessage(socket, jsonData, pushMessage); } dataBuffer = incomplete; } }).on('error', function(err){ if (err.code !== 'ECONNRESET') log('warn', logSystem, 'Socket error from %s %j', [socket.remoteAddress, err]); }).on('close', function(){ pushMessage = function(){}; }); }).listen(portData.port, function (error, result) { if (error) { log('error', logSystem, 'Could not start server listening on port %d, error: $j', [portData.port, error]); cback(true); return; } log('info', logSystem, 'Started server listening on port %d', [portData.port]); cback(); }); }, function(err){ if (err) callback(false); else callback(true); }); } ================================================ FILE: lib/utils.js ================================================ var base58 = require('base58-native'); var cnUtil = require('cryptonote-util'); var addressBase58Prefix = cnUtil.address_decode(new Buffer(config.poolServer.poolAddress)); exports.uid = function(){ var min = 100000000000000; var max = 999999999999999; var id = Math.floor(Math.random() * (max - min + 1)) + min; return id.toString(); }; exports.ringBuffer = function(maxSize){ var data = []; var cursor = 0; var isFull = false; return { append: function(x){ if (isFull){ data[cursor] = x; cursor = (cursor + 1) % maxSize; } else{ data.push(x); cursor++; if (data.length === maxSize){ cursor = 0; isFull = true; } } }, avg: function(plusOne){ var sum = data.reduce(function(a, b){ return a + b }, plusOne || 0); return sum / ((isFull ? maxSize : cursor) + (plusOne ? 1 : 0)); }, size: function(){ return isFull ? maxSize : cursor; }, clear: function(){ data = []; cursor = 0; isFull = false; } }; }; exports.varIntEncode = function(n){ }; exports.isValidAddress = function(addr){ // config.poolServer.poolAddress // return addressBase58Prefix === cnUtil.address_decode(new Buffer(addr)); }; ================================================ FILE: package.json ================================================ { "name": "cryptonote-pool", "version": "0.0.1", "license": "GPL-2.0", "author": "Matthew Little", "repository": { "type": "git", "url": "https://github.com/zone117x/node-cryptonote-pool.git" }, "dependencies": { "bignum": "0.12.5", "async": "1.5.2", "redis": "0.12.1", "cli-color": "1.1.0", "dateformat": "1.0.12", "base58-native": "0.1.4", "multi-hashing": "git://github.com/zone117x/node-multi-hashing.git", "cryptonote-util": "git://github.com/electroneum/node-cryptonote-util#xmr-Nan-2.0" }, "engines": { "node": ">=0.10" } } ================================================ FILE: redisBlocksUpgrade.js ================================================ /* This script converts the block data in redis from the old format (v0.99.0.6 and earlier) to the new format used in v0.99.1+ */ var util = require('util'); var async = require('async'); var redis = require('redis'); require('./lib/configReader.js'); var apiInterfaces = require('./lib/apiInterfaces.js')(config.daemon, config.wallet); function log(severity, system, text, data){ var formattedMessage = text; if (data) { data.unshift(text); formattedMessage = util.format.apply(null, data); } console.log(severity + ': ' + formattedMessage); } var logSystem = 'reward script'; var redisClient = redis.createClient(config.redis.port, config.redis.host); function getTotalShares(height, callback){ redisClient.hgetall(config.coin + ':shares:round' + height, function(err, workerShares){ if (err) { callback(err); return; } var totalShares = Object.keys(workerShares).reduce(function(p, c){ return p + parseInt(workerShares[c]) }, 0); callback(null, totalShares); }); } async.series([ function(callback){ redisClient.smembers(config.coin + ':blocksUnlocked', function(error, result){ if (error){ log('error', logSystem, 'Error trying to get unlocke blocks from redis %j', [error]); callback(); return; } if (result.length === 0){ log('info', logSystem, 'No unlocked blocks in redis'); callback(); return; } var blocks = result.map(function(item){ var parts = item.split(':'); return { height: parseInt(parts[0]), difficulty: parts[1], hash: parts[2], time: parts[3], shares: parts[4], orphaned: 0 }; }); async.map(blocks, function(block, mapCback){ apiInterfaces.rpcDaemon('getblockheaderbyheight', {height: block.height}, function(error, result){ if (error){ log('error', logSystem, 'Error with getblockheaderbyheight RPC request for block %s - %j', [block.serialized, error]); mapCback(null, block); return; } if (!result.block_header){ log('error', logSystem, 'Error with getblockheaderbyheight, no details returned for %s - %j', [block.serialized, result]); mapCback(null, block); return; } var blockHeader = result.block_header; block.reward = blockHeader.reward; mapCback(null, block); }); }, function(err, blocks){ if (blocks.length === 0){ log('info', logSystem, 'No unlocked blocks'); callback(); return; } var zaddCommands = [config.coin + ':blocks:matured']; for (var i = 0; i < blocks.length; i++){ var block = blocks[i]; zaddCommands.push(block.height); zaddCommands.push([ block.hash, block.time, block.difficulty, block.shares, block.orphaned, block.reward ].join(':')); } redisClient.zadd(zaddCommands, function(err, result){ if (err){ console.log('failed zadd ' + JSON.stringify(err)); callback(); return; } console.log('successfully converted unlocked blocks to matured blocks'); callback(); }); }); }); }, function(callback){ redisClient.smembers(config.coin + ':blocksPending', function(error, result) { if (error) { log('error', logSystem, 'Error trying to get pending blocks from redis %j', [error]); callback(); return; } if (result.length === 0) { log('info', logSystem, 'No pending blocks in redis'); callback(); return; } async.map(result, function(item, mapCback){ var parts = item.split(':'); var block = { height: parseInt(parts[0]), difficulty: parts[1], hash: parts[2], time: parts[3], serialized: item }; getTotalShares(block.height, function(err, shares){ block.shares = shares; mapCback(null, block); }); }, function(err, blocks){ var zaddCommands = [config.coin + ':blocks:candidates']; for (var i = 0; i < blocks.length; i++){ var block = blocks[i]; zaddCommands.push(block.height); zaddCommands.push([ block.hash, block.time, block.difficulty, block.shares ].join(':')); } redisClient.zadd(zaddCommands, function(err, result){ if (err){ console.log('failed zadd ' + JSON.stringify(err)); return; } console.log('successfully converted pending blocks to block candidates'); }); }); }); } ], function(){ process.exit(); }); ================================================ FILE: website_example/admin_core_stats_massive_stuff.html ================================================

Admin Center


Stats

Total Owed
...
Total Paid
...
Total Mined
...
Profit (before tx fees)
...
Average Luck
...
Orphan Percent
...
Registered Addresses
...


Miner Lookup

================================================ FILE: website_example/config.js ================================================ var api = "https://eupool.electroneum.com/api"; var coinUnits = 100; var coinDecimalPlaces = 2; var poolHost = "eupool.electroneum.com"; var irc = "irc.freenode.net/#monero-pools"; var email = "support@electroneum.com"; var easyminerDownload = "https://github.com/zone117x/cryptonote-easy-miner/releases/"; var blockchainExplorer = "https://blockexplorer.electroneum.com/block/"; var transactionExplorer = "https://blockexplorer.electroneum.com/tx/"; ================================================ FILE: website_example/custom.css ================================================ /* Insert your pool's unique css here */ .alert-primary { color: #004085; background-color: #cce5ff; border-color: #b8daff; } .alert-warning { color: #856404; background-color: #fff3cd; border-color: #ffeeba; } .btn-primary { background-color: #23bee2; border-color: #13acd0; } .btn-primary:hover { background-color: #13acd0; border-color: #13acd0; } .container{ font-size: 14px!important; } .float-right { float: right; } /* Custom margins */ .mb-20 { margin-bottom: 20px !important; } .navbar-inverse { background-color: #091b26; } .navbar-brand { height: 70px; padding: 10px 15px; } .navbar-brand img { height: 100%; display: inline-block; } .navbar-nav>li>a { padding-top: 25px; padding-bottom: 25px; } #stats_updated { line-height: 70px!important; } ================================================ FILE: website_example/custom.js ================================================ /* Insert your pool's unique Javascript here */ ================================================ FILE: website_example/index.html ================================================ Electroneum Mining Pool

================================================ FILE: website_example/pages/downloads.html ================================================

Beginner's Pool Mining Software

If you are new to crypto mining then this option is the one for you.


Advanced Pool Mining Software

If you are a crypto mining pro then you'll probably prefer these options.

App Name Architecture Downloads Discussion Source Code
CPUMiner (forked by LucasJones & Wolf) CPU BitcoinTalk BitcoinTalk Github
Example: minerd -a cryptonight -o stratum+tcp://: -u YOUR_WALLET_ADDRESS -p x
YAM Miner (by yvg1900) CPU MEGA Twitter Proprietary
Example: yam -c x -M stratum+tcp://YOUR_WALLET_ADDRESS:x@:/xmr
Claymore CPU Miner CPU BitcoinTalk BitcoinTalk Proprietary
Example: NsCpuCNMiner64 -o stratum+tcp://: -u YOUR_WALLET_ADDRESS -p x
Claymore GPU Miner OpenCL (AMD) BitcoinTalk Discussion Proprietary
Example: NsGpuCNMiner -o stratum+tcp://: -u YOUR_WALLET_ADDRESS -p x
ccminer (forked by tsiv) CUDA (Nvidia) Github BitcoinTalk Github
Example: ccminer -o stratum+tcp://: -u YOUR_WALLET_ADDRESS -p x

Mining Pool Connection Details

Mining Pool Address:

Mining Ports

Port:
Starting Difficulty:
Description:

Direct mining software

App Name Architecture Downloads Discussion Source Code
Direct CPU Download BitcoinTalk Github

================================================ FILE: website_example/pages/home.html ================================================

Getting started

Step 1

Download a miner

First of all you'll need to download a mining program in order to allow your computer to mine Electroneum.

View downloads

Step 2

Connect to a mining pool

Once you've chosen a miner you need to connect it to this mining pool.

View instructions

Step 3

Earn Electroneum

After you've connected to the mining pool simply sit back and watch the Electroneum getting mined.

Advanced options

Mining Pool stats

This Pool

Hash Rate:
Block Found:
Connected Miners:
Donations:
Total Pool Fee:
Block Found Every: (est.)

Electroneum Pool Network

Hash Rate:
Block Found:
Difficulty:
Blockchain Height:
Last Reward:
Last Hash:

Your Stats & Payment History

Wallet Address:
Pending Balance:
Total Paid:
Last Share Submitted:
Hash Rate:
Total Hashes Submitted:

Payments

Time Sent Transaction Hash Amount Mixin

================================================ FILE: website_example/pages/payments.html ================================================
Total Payments: Total Miners Paid: Minimum Payment Threshold: Denomination Unit:

Time Sent Transaction Hash Amount Fee Mixin Payees

================================================ FILE: website_example/pages/pool_blocks.html ================================================
Total Blocks Mined: Maturity Depth Requirement:

Height Maturity Difficulty Block Hash Time Found Luck

================================================ FILE: website_example/pages/support.html ================================================

Contact

Email pool support at

Chat Room