[
  {
    "path": ".gitignore",
    "content": "node_modules/\n.idea/\nconfig.json\nlogs/\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n  - \"0.10.48\"\naddons:\n  apt:\n    sources:\n      - ubuntu-toolchain-r-test\n    packages:\n      - libssl-dev\n      - libboost-all-dev\n      - build-essential\n      - cmake\n      - pkg-config\n      - libunbound-dev\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {description}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  {signature of Ty Coon}, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License."
  },
  {
    "path": "README.md",
    "content": "Electroneum Pool (node-cryptonote-pool)\n====================\n\nHigh performance Node.js (with native C addons) mining pool for CryptoNote based coins such as Electroneum, Monero, Bytecoin, QuazarCoin, HoneyPenny, etc..\nComes with lightweight example front-end script which uses the pool's AJAX API.\n\n\n#### Table of Contents\n* [Features](#features)\n* [Community Support](#community--support)\n* [Pools Using This Software](#pools-using-this-software)\n* [Usage](#usage)\n  * [Requirements](#requirements)\n  * [Downloading & Installing](#1-downloading--installing)\n  * [Configuration](#3-configuration)\n  * [Configure Easyminer](#4-optional-configure-cryptonote-easy-miner-for-your-pool)\n  * [Starting the Pool](#5-start-the-pool)\n  * [Host the front-end](#6-host-the-front-end)\n  * [Customizing your website](#7-customize-your-website)\n  * [SSL](#ssl)\n  * [Upgrading](#upgrading)\n* [Donations](#donations)\n* [Credits](#credits)\n* [License](#license)\n\n\n#### Features\n\n* TCP (stratum-like) protocol for server-push based jobs\n  * Compared to old HTTP protocol, this has a higher hash rate, lower network/CPU server load, lower orphan\n    block percent, and less error prone\n* IP banning to prevent low-diff share attacks\n* Socket flooding detection\n* Payment processing\n  * Splintered transactions to deal with max transaction size\n  * Minimum payment threshold before balance will be paid out\n  * Minimum denomination for truncating payment amount precision to reduce size/complexity of block transactions\n* Detailed logging\n* Ability to configure multiple ports - each with their own difficulty\n* Variable difficulty / share limiter\n* Share trust algorithm to reduce share validation hashing CPU load\n* Clustering for vertical scaling\n* Modular components for horizontal scaling (pool server, database, stats/API, payment processing, front-end)\n* Live stats API (using AJAX long polling with CORS)\n  * Currency network/block difficulty\n  * Current block height\n  * Network hashrate\n  * Pool hashrate\n  * Each miners' individual stats (hashrate, shares submitted, pending balance, total paid, etc)\n  * Blocks found (pending, confirmed, and orphaned)\n* An easily extendable, responsive, light-weight front-end using API to display data\n* Worker login validation (make sure miners are using proper wallet addresses for mining)\n\n\n### Community / Support\n\n* [Electroneum Forum](https://electroneumtalk.proboards.com/)\n* [Electroneum Github](https://github.com/electroneum)\n\n\n#### Pools Using This Software\n* http://etn.kkmining.club/ <-- Hongkong Pool 0.1% fee\n* https://easyhash.io/pools/etn\n* http://etn.proxpool.com <- cloud based, high efficiency, EU Pool Server, 0% fee\n* https://easyhash.io/pools/etn\n* https://etn.mymininghub.com/\n* https://dedpool.io/etn <- US Pool\n* http://etn.pool.nocroom.com < - cloud based, US Pool Server\n* http://etn.bl0ck.party <- Atlanta, GA, USA -- 0.5% fee\n* https://www.etn.rustylock.club - cloud based, high efficiency, EU Pool Server\n* https://supportetn.eu - nodejs-pool, EU Pool Server, 0.2 % fee\n\nUsage\n===\n#### Requirements\n* 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.\n* Coin daemon [electroneum repo](https://www.github.com/electroneum/electroneum)\n  * To compile the coin you'll need several packages as detailed in the repo's readme. A quick one line command is below:\n  * `sudo apt install build-essential cmake pkg-config libboost-all-dev libssl-dev libunbound-dev`\n* [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`.\n* [Redis](http://redis.io/) key-value store v2.6+ ([follow these instructions](http://redis.io/topics/quickstart))\n* libssl required for the node-multi-hashing module\n  * For Ubuntu: `sudo apt-get install libssl-dev`\n* Boost is required for the cryptonote-util module\n  * For Ubuntu: `sudo apt-get install libboost-all-dev`\n* Screen - for running the different parts of the pool in the background. This may come pre-installed on some systems.\n  * For Ubuntu: `sudo apt-get install screen`\n  * Usage:  \n    `screen -S daemond` <--- Use to run the daemond  \n    `screen -S rpc` <---- Use to run rpc  \n    `screen -S website` < --- use to run website  \n    `screen -list` <---- List screens  \n    `screen -x website` <--- reconnect to screen website  \n    `CTRL + a` then `CTRL + d` <----- detatch from a screen  \n\n##### Node.js v0.10.48\n* 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.\n\n##### Seriously\nThose 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.\n\n\n[**Redis security warning**](http://redis.io/topics/security): be sure firewall access to redis - an easy way is to\ninclude `bind 127.0.0.1` in your `redis.conf` file. Also it's a good idea to learn about and understand software that\nyou are using - a good place to start with redis is [data persistence](http://redis.io/topics/persistence).\n\n\n#### 1) Downloading & Installing\n\n\nClone the repository and run `npm update` for all the dependencies to be installed:\n\n```bash\ngit clone https://github.com/electroneum/electroneum-pool.git pool\ncd pool\nnpm update\n```\n\n\n#### 2) Daemon & Wallet\n\nFirstly, You'll need to download & compile the daemon source code found [here](https://www.github.com/electroneum/electroneum)  \n\nSecondly, 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.  \n\nThirdly, 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.  \n\nLastly 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`  \n\n`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.  \n\n[**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.\n\n\n#### 3) Configuration\n\n*Warning for Cryptonote coins other than Electroneum:* this software may or may not work with any given cryptonote coin.\nBe wary of altcoins that change the number of minimum coin units because you will have to reconfigure several config\nvalues to account for those changes. Unless you're offering a bounty reward - do not open an issue asking for help\ngetting a coin other than electroneum working with this software.\n\n\nCopy the `config_example.json` file to `config.json` then overview each options and change any to match your preferred setup.\n\n\nExplanation for each field:\n```javascript\n{\n    \"coin\": \"electroneum\",\n    \"symbol\": \"ETN\",\n    \"logging\": {\n        \"files\": {\n            \"level\": \"info\",\n            \"directory\": \"logs\",\n            \"flushInterval\": 5\n        },\n\n        \"console\": {\n            \"level\": \"info\",\n            \"colors\": true\n        }\n    },\n    \"poolServer\": {\n        \"enabled\": true,\n        \"clusterForks\": \"auto\",\n        \"poolAddress\": \"WALLETADDRESSHERE\",\n        \"blockRefreshInterval\": 1000,\n        \"minerTimeout\": 900,\n        \"ports\": [\n            {\n                \"port\": 3333,\n                \"difficulty\": 100,\n                \"desc\": \"Low end hardware\"\n            },\n            {\n                \"port\": 5555,\n                \"difficulty\": 2000,\n                \"desc\": \"Mid range hardware\"\n            },\n            {\n                \"port\": 7777,\n                \"difficulty\": 10000,\n                \"desc\": \"High end hardware\"\n            }\n        ],\n        \"varDiff\": {\n            \"minDiff\": 2,\n            \"maxDiff\": 100000,\n            \"targetTime\": 100,\n            \"retargetTime\": 30,\n            \"variancePercent\": 30,\n            \"maxJump\": 100\n        },\n        \"shareTrust\": {\n            \"enabled\": true,\n            \"min\": 10,\n            \"stepDown\": 3,\n            \"threshold\": 10,\n            \"penalty\": 30\n        },\n        \"banning\": {\n            \"enabled\": true,\n            \"time\": 600,\n            \"invalidPercent\": 25,\n            \"checkThreshold\": 30\n        },\n        \"slushMining\": {\n            \"enabled\": false,\n            \"weight\": 300,\n            \"lastBlockCheckRate\": 1\n        }\n    },\n    \"payments\": {\n        \"enabled\": true,\n        \"interval\": 600,\n        \"maxAddresses\": 10,\n        \"mixin\": 0,\n        \"transferFee\": 1,\n        \"minPayment\": 10000,\n        \"denomination\": 100\n    },\n    \"blockUnlocker\": {\n        \"enabled\": true,\n        \"interval\": 30,\n        \"depth\": 20,\n        \"poolFee\": 1.8,\n        \"devDonation\": 0.1,\n        \"coreDevDonation\": 0.1\n    },\n    \"api\": {\n        \"enabled\": true,\n        \"hashrateWindow\": 600,\n        \"updateInterval\": 3,\n        \"port\": 8117,\n        \"blocks\": 30,\n        \"payments\": 30,\n        \"password\": \"test\"\n    },\n    \"daemon\": {\n        \"host\": \"127.0.0.1\",\n        \"port\": 26968\n    },\n    \"wallet\": {\n        \"host\": \"127.0.0.1\",\n        \"port\": 26969\n    },\n    \"redis\": {\n        \"host\": \"127.0.0.1\",\n        \"port\": 6379,\n        \"auth\": null\n    }\n}\n```\n\n#### 4) [Optional] Configure cryptonote-easy-miner for your pool\nYour miners that are Windows users can use [cryptonote-easy-miner](https://github.com/zone117x/cryptonote-easy-miner)\nwhich will automatically generate their wallet address and stratup multiple threads of simpleminer. You can download\nit and edit the `config.ini` file to point to your own pool.\nInside the `easyminer` folder, edit `config.init` to point to your pool details\n```ini\npool_host=example.com\npool_port=5555\n```\n\nRezip and upload to your server or a file host. Then change the `easyminerDownload` link in your `config.json` file to\npoint to your zip file.\n\n\n#### 5) Start the pool\n\n```bash\nnode init.js\n```\n\nThe file `config.json` is used by default but a file can be specified using the `-config=file` command argument, for example:\n\n```bash\nnode init.js -config=config_backup.json\n```\n\nThis software contains four distinct modules:\n* `pool` - Which opens ports for miners to connect and processes shares\n* `api` - Used by the website to display network, pool and miners' data\n* `unlocker` - Processes block candidates and increases miners' balances when blocks are unlocked\n* `payments` - Sends out payments to miners according to their balances stored in redis\n\n\nBy default, running the `init.js` script will start up all four modules. You can optionally have the script start\nonly start a specific module by using the `-module=name` command argument, for example:\n\n```bash\nnode init.js -module=api\n```\n\n[Example screenshot](http://i.imgur.com/SEgrI3b.png) of running the pool in single module mode with tmux.\n\n\n#### 6) Host the front-end\n\nSimply host the contents of the `website_example` directory on file server capable of serving simple static files.\n\n\nEdit the variables in the `website_example/config.js` file to use your pool's specific configuration.\nVariable explanations:\n\n```javascript\n\n/* Must point to the API setup in your config.json file. */\nvar api = \"http://poolhost:8117\";\n\n/* Minimum units in a single coin, for Electroneum its 100. */\nvar coinUnits = 100;\n\n/* Pool server host to instruct your miners to point to.  */\nvar poolHost = \"poolhost.com\";\n\n/* IRC Server and room used for embedded KiwiIRC chat. */\nvar irc = \"irc.freenode.net/#electroneum\";\n\n/* Contact email address. */\nvar email = \"support@poolhost.com\";\n\n/* Market stat display params from https://www.cryptonator.com/widget - Not used for Electroneum pool */\nvar cryptonatorWidget = [\"XMR-BTC\", \"XMR-USD\", \"XMR-EUR\", \"XMR-GBP\"];\n\n/* Download link to cryptonote-easy-miner for Windows users. */\nvar easyminerDownload = \"https://github.com/zone117x/cryptonote-easy-miner/releases/\";\n\n/* Used for front-end block links. */\nvar blockchainExplorer = \"https://blockexplorer.electroneum.com/block/\";\n\n/* Used by front-end transaction links. */\nvar transactionExplorer = \"https://blockexplorer.electroneum.com/tx\";\n\n```\n\n\n#### 7) Customize your website\n\nThe following files are included so that you can customize your pool website without having to make significant changes\nto `index.html` or other front-end files thus reducing the difficulty of merging updates with your own changes:\n* `custom.css` for creating your own pool style\n* `custom.js` for changing the functionality of your pool website\n\n\nThen simply serve the files via nginx, Apache, Google Drive, or anything that can host static content.\n\n\n#### SSL\n\nYou can configure the API to be accessible via SSL using various methods. Find an example for nginx below:\n\n* Inside your SSL Listener add the following:\n\n``` javascript\nlocation /json_rpc {\n    proxy_pass http://127.0.0.1:26968/json_rpc;\n}\n\nlocation ~ ^/api/(.*) {\n    proxy_pass http://127.0.0.1:8117/$1$is_args$args;\n}\n```\n\nBy adding this you will need to make your `api` variable in the `website_example/config.js` include the /api. For example:  \n`var api = \"http://poolhost/api\";`\n\nYou no longer need to include the port in the variable because of the proxy connection.\n\n\n#### Upgrading\nWhen updating to the latest code its important to not only `git pull` the latest from this repo, but to also update\nthe Node.js modules, and any config files that may have been changed.\n* Inside your pool directory (where the init.js script is) do `git pull` to get the latest code.\n* Remove the dependencies by deleting the `node_modules` directory with `rm -r node_modules`.\n* Run `npm update` to force updating/reinstalling of the dependencies.\n* 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.\n\nDonations\n---------\n* ETN: `etnkCFXeExRaBhbDNq66TQ3rF9XSkMreei8t1jXfT2ndgY6bnsNEUtEKbEhba3YHk2CuPCpxZFrGNcAJ9Lv22ACY7eapPgQtNb`\n* XMR: `48rB9X6ygZQ4uNBSKJP3MKU9iFK87e8vejEi762eNdTPB61A9VayUnL75HHi2SER3gf5i9PXpiS2kiCwDyanvNm5S5Aq3WF`\n\n\nCredits\n===\n\n* [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.\n* [surfer43](//github.com/iamasupernova) - Did lots of testing during development to help figure out bugs and get them fixed\n* [wallet42](http://moneropool.com) - Funded development of payment denominating and min threshold feature\n* [Wolf0](https://bitcointalk.org/index.php?action=profile;u=80740) - Helped try to deobfuscate some of the daemon code for getting a bug fixed\n* [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\n\n\nLicense\n-------\nReleased under the GNU General Public License v2\n\nhttp://www.gnu.org/licenses/gpl-2.0.html\n"
  },
  {
    "path": "config_example.json",
    "content": "{\n    \"coin\": \"electroneum\",\n    \"symbol\": \"ETN\",\n    \"logging\": {\n        \"files\": {\n            \"level\": \"info\",\n            \"directory\": \"logs\",\n            \"flushInterval\": 5\n        },\n\n        \"console\": {\n            \"level\": \"info\",\n            \"colors\": true\n        }\n    },\n    \"poolServer\": {\n        \"enabled\": true,\n        \"clusterForks\": \"auto\",\n        \"poolAddress\": \"WALLETADDRESSHERE\",\n        \"blockRefreshInterval\": 1000,\n        \"minerTimeout\": 900,\n        \"ports\": [\n            {\n                \"port\": 3333,\n                \"difficulty\": 100,\n                \"desc\": \"Low end hardware\"\n            },\n            {\n                \"port\": 5555,\n                \"difficulty\": 2000,\n                \"desc\": \"Mid range hardware\"\n            },\n            {\n                \"port\": 7777,\n                \"difficulty\": 10000,\n                \"desc\": \"High end hardware\"\n            }\n        ],\n        \"varDiff\": {\n            \"minDiff\": 2,\n            \"maxDiff\": 100000,\n            \"targetTime\": 100,\n            \"retargetTime\": 30,\n            \"variancePercent\": 30,\n            \"maxJump\": 100\n        },\n        \"shareTrust\": {\n            \"enabled\": true,\n            \"min\": 10,\n            \"stepDown\": 3,\n            \"threshold\": 10,\n            \"penalty\": 30\n        },\n        \"banning\": {\n            \"enabled\": true,\n            \"time\": 600,\n            \"invalidPercent\": 25,\n            \"checkThreshold\": 30\n        },\n        \"slushMining\": {\n            \"enabled\": false,\n            \"weight\": 300,\n            \"lastBlockCheckRate\": 1\n        }\n    },\n    \"payments\": {\n        \"enabled\": true,\n        \"interval\": 600,\n        \"maxAddresses\": 10,\n        \"mixin\": 0,\n        \"transferFee\": 1,\n        \"minPayment\": 10000,\n        \"denomination\": 100\n    },\n    \"blockUnlocker\": {\n        \"enabled\": true,\n        \"interval\": 30,\n        \"depth\": 20,\n        \"poolFee\": 1.8,\n        \"devDonation\": 0.1,\n        \"coreDevDonation\": 0.1\n    },\n    \"api\": {\n        \"enabled\": true,\n        \"hashrateWindow\": 600,\n        \"updateInterval\": 3,\n        \"port\": 8117,\n        \"blocks\": 30,\n        \"payments\": 30,\n        \"password\": \"your_password\"\n    },\n    \"daemon\": {\n        \"host\": \"127.0.0.1\",\n        \"port\": 26968\n    },\n    \"wallet\": {\n        \"host\": \"127.0.0.1\",\n        \"port\": 26969\n    },\n    \"redis\": {\n        \"host\": \"127.0.0.1\",\n        \"port\": 6379,\n        \"auth\": null\n    }\n}\n"
  },
  {
    "path": "init.js",
    "content": "var fs = require('fs');\nvar cluster = require('cluster');\nvar os = require('os');\n\nvar redis = require('redis');\n\n\nrequire('./lib/configReader.js');\n\nrequire('./lib/logger.js');\n\n\nglobal.redisClient = redis.createClient(config.redis.port, config.redis.host, {auth_pass: config.redis.auth});\n\n\nif (cluster.isWorker){\n    switch(process.env.workerType){\n        case 'pool':\n            require('./lib/pool.js');\n            break;\n        case 'blockUnlocker':\n            require('./lib/blockUnlocker.js');\n            break;\n        case 'paymentProcessor':\n            require('./lib/paymentProcessor.js');\n            break;\n        case 'api':\n            require('./lib/api.js');\n            break;\n        case 'cli':\n            require('./lib/cli.js');\n            break\n    }\n    return;\n}\n\nvar logSystem = 'master';\nrequire('./lib/exceptionWriter.js')(logSystem);\n\n\nvar singleModule = (function(){\n\n    var validModules = ['pool', 'api', 'unlocker', 'payments'];\n\n    for (var i = 0; i < process.argv.length; i++){\n        if (process.argv[i].indexOf('-module=') === 0){\n            var moduleName = process.argv[i].split('=')[1];\n            if (validModules.indexOf(moduleName) > -1)\n                return moduleName;\n\n            log('error', logSystem, 'Invalid module \"%s\", valid modules: %s', [moduleName, validModules.join(', ')]);\n            process.exit();\n        }\n    }\n})();\n\n\n(function init(){\n\n    checkRedisVersion(function(){\n\n        if (singleModule){\n            log('info', logSystem, 'Running in single module mode: %s', [singleModule]);\n\n            switch(singleModule){\n                case 'pool':\n                    spawnPoolWorkers();\n                    break;\n                case 'unlocker':\n                    spawnBlockUnlocker();\n                    break;\n                case 'payments':\n                    spawnPaymentProcessor();\n                    break;\n                case 'api':\n                    spawnApi();\n                    break;\n            }\n        }\n        else{\n            spawnPoolWorkers();\n            spawnBlockUnlocker();\n            spawnPaymentProcessor();\n            spawnApi();\n        }\n\n        spawnCli();\n\n    });\n})();\n\n\nfunction checkRedisVersion(callback){\n\n    redisClient.info(function(error, response){\n        if (error){\n            log('error', logSystem, 'Redis version check failed');\n            return;\n        }\n        var parts = response.split('\\r\\n');\n        var version;\n        var versionString;\n        for (var i = 0; i < parts.length; i++){\n            if (parts[i].indexOf(':') !== -1){\n                var valParts = parts[i].split(':');\n                if (valParts[0] === 'redis_version'){\n                    versionString = valParts[1];\n                    version = parseFloat(versionString);\n                    break;\n                }\n            }\n        }\n        if (!version){\n            log('error', logSystem, 'Could not detect redis version - must be super old or broken');\n            return;\n        }\n        else if (version < 2.6){\n            log('error', logSystem, \"You're using redis version %s the minimum required version is 2.6. Follow the damn usage instructions...\", [versionString]);\n            return;\n        }\n        callback();\n    });\n}\n\nfunction spawnPoolWorkers(){\n\n    if (!config.poolServer || !config.poolServer.enabled || !config.poolServer.ports || config.poolServer.ports.length === 0) return;\n\n    if (config.poolServer.ports.length === 0){\n        log('error', logSystem, 'Pool server enabled but no ports specified');\n        return;\n    }\n\n\n    var numForks = (function(){\n        if (!config.poolServer.clusterForks)\n            return 1;\n        if (config.poolServer.clusterForks === 'auto')\n            return os.cpus().length;\n        if (isNaN(config.poolServer.clusterForks))\n            return 1;\n        return config.poolServer.clusterForks;\n    })();\n\n    var poolWorkers = {};\n\n    var createPoolWorker = function(forkId){\n        var worker = cluster.fork({\n            workerType: 'pool',\n            forkId: forkId\n        });\n        worker.forkId = forkId;\n        worker.type = 'pool';\n        poolWorkers[forkId] = worker;\n        worker.on('exit', function(code, signal){\n            log('error', logSystem, 'Pool fork %s died, spawning replacement worker...', [forkId]);\n            setTimeout(function(){\n                createPoolWorker(forkId);\n            }, 2000);\n        }).on('message', function(msg){\n            switch(msg.type){\n                case 'banIP':\n                    Object.keys(cluster.workers).forEach(function(id) {\n                        if (cluster.workers[id].type === 'pool'){\n                            cluster.workers[id].send({type: 'banIP', ip: msg.ip});\n                        }\n                    });\n                    break;\n            }\n        });\n    };\n\n    var i = 1;\n    var spawnInterval = setInterval(function(){\n        createPoolWorker(i.toString());\n        i++;\n        if (i - 1 === numForks){\n            clearInterval(spawnInterval);\n            log('info', logSystem, 'Pool spawned on %d thread(s)', [numForks]);\n        }\n    }, 10);\n}\n\nfunction spawnBlockUnlocker(){\n\n    if (!config.blockUnlocker || !config.blockUnlocker.enabled) return;\n\n    var worker = cluster.fork({\n        workerType: 'blockUnlocker'\n    });\n    worker.on('exit', function(code, signal){\n        log('error', logSystem, 'Block unlocker died, spawning replacement...');\n        setTimeout(function(){\n            spawnBlockUnlocker();\n        }, 2000);\n    });\n\n}\n\nfunction spawnPaymentProcessor(){\n\n    if (!config.payments || !config.payments.enabled) return;\n\n    var worker = cluster.fork({\n        workerType: 'paymentProcessor'\n    });\n    worker.on('exit', function(code, signal){\n        log('error', logSystem, 'Payment processor died, spawning replacement...');\n        setTimeout(function(){\n            spawnPaymentProcessor();\n        }, 2000);\n    });\n}\n\nfunction spawnApi(){\n    if (!config.api || !config.api.enabled) return;\n\n    var worker = cluster.fork({\n        workerType: 'api'\n    });\n    worker.on('exit', function(code, signal){\n        log('error', logSystem, 'API died, spawning replacement...');\n        setTimeout(function(){\n            spawnApi();\n        }, 2000);\n    });\n}\n\nfunction spawnCli(){\n\n}"
  },
  {
    "path": "lib/api.js",
    "content": "var fs = require('fs');\nvar http = require('http');\nvar url = require(\"url\");\nvar zlib = require('zlib');\n\nvar async = require('async');\n\nvar apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet);\n\nvar logSystem = 'api';\nrequire('./exceptionWriter.js')(logSystem);\n\nvar redisCommands = [\n    ['zremrangebyscore', config.coin + ':hashrate', '-inf', ''],\n    ['zrange', config.coin + ':hashrate', 0, -1],\n    ['hgetall', config.coin + ':stats'],\n    ['zrange', config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES'],\n    ['zrevrange', config.coin + ':blocks:matured', 0, config.api.blocks - 1, 'WITHSCORES'],\n    ['hgetall', config.coin + ':shares:roundCurrent'],\n    ['hgetall', config.coin + ':stats'],\n    ['zcard', config.coin + ':blocks:matured'],\n    ['zrevrange', config.coin + ':payments:all', 0, config.api.payments - 1, 'WITHSCORES'],\n    ['zcard', config.coin + ':payments:all'],\n    ['keys', config.coin + ':payments:*']\n];\n\nvar currentStats = \"\";\nvar currentStatsCompressed = \"\";\n\nvar minerStats = {};\n\nvar liveConnections = {};\nvar addressConnections = {};\n\n\n\nfunction collectStats(){\n\n    var startTime = Date.now();\n    var redisFinished;\n    var daemonFinished;\n\n    var windowTime = (((Date.now() / 1000) - config.api.hashrateWindow) | 0).toString();\n    redisCommands[0][3] = '(' + windowTime;\n\n    async.parallel({\n        pool: function(callback){\n            redisClient.multi(redisCommands).exec(function(error, replies){\n\n                redisFinished = Date.now();\n                var dateNowSeconds = Date.now() / 1000 | 0;\n\n                if (error){\n                    log('error', logSystem, 'Error getting redis data %j', [error]);\n                    callback(true);\n                    return;\n                }\n\n                var data = {\n                    stats: replies[2],\n                    blocks: replies[3].concat(replies[4]),\n                    totalBlocks: parseInt(replies[7]) + (replies[3].length / 2),\n                    payments: replies[8],\n                    totalPayments: parseInt(replies[9]),\n                    totalMinersPaid: replies[10].length - 1\n                };\n\n                var hashrates = replies[1];\n\n                minerStats = {};\n\n                for (var i = 0; i < hashrates.length; i++){\n                    var hashParts = hashrates[i].split(':');\n                    minerStats[hashParts[1]] = (minerStats[hashParts[1]] || 0) + parseInt(hashParts[0]);\n                }\n\n                var totalShares = 0;\n\n                for (var miner in minerStats){\n                    var shares = minerStats[miner];\n                    totalShares += shares;\n                    minerStats[miner] = getReadableHashRateString(shares / config.api.hashrateWindow);\n                }\n\n                data.miners = Object.keys(minerStats).length;\n\n                data.hashrate = totalShares / config.api.hashrateWindow;\n\n                data.roundHashes = 0;\n\n                if (replies[5]){\n                    for (var miner in replies[5]){\n                        if (config.poolServer.slushMining.enabled) {\n                            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. \n                        }\n                        else {\n                            data.roundHashes +=  parseInt(replies[5][miner]);\n                        }\n                    }\n                }\n\n                if (replies[6]) {\n                    data.lastBlockFound = replies[6].lastBlockFound;\n                }\n\n                callback(null, data);\n            });\n        },\n        network: function(callback){\n            apiInterfaces.rpcDaemon('getlastblockheader', {}, function(error, reply){\n                daemonFinished = Date.now();\n                if (error){\n                    log('error', logSystem, 'Error getting daemon data %j', [error]);\n                    callback(true);\n                    return;\n                }\n                var blockHeader = reply.block_header;\n                callback(null, {\n                    difficulty: blockHeader.difficulty,\n                    height: blockHeader.height,\n                    timestamp: blockHeader.timestamp,\n                    reward: blockHeader.reward,\n                    hash:  blockHeader.hash\n                });\n            });\n        },\n        config: function(callback){\n            callback(null, {\n                ports: getPublicPorts(config.poolServer.ports),\n                hashrateWindow: config.api.hashrateWindow,\n                fee: config.blockUnlocker.poolFee,\n                coin: config.coin,\n                symbol: config.symbol,\n                depth: config.blockUnlocker.depth,\n                donation: config.blockUnlocker.devDonation,\n                coreDonation: config.blockUnlocker.coreDevDonation,\n                doDonations: doDonations,\n                version: version,\n                minPaymentThreshold: config.payments.minPayment,\n                denominationUnit: config.payments.denomination,\n                blockTime: config.poolServer.slushMining.blockTime,\n                slushMiningEnabled: config.poolServer.slushMining.enabled,\n                weight: config.poolServer.slushMining.weight\n            });\n        }\n    }, function(error, results){\n\n        log('info', logSystem, 'Stat collection finished: %d ms redis, %d ms daemon', [redisFinished - startTime, daemonFinished - startTime]);\n\n        if (error){\n            log('error', logSystem, 'Error collecting all stats');\n        }\n        else{\n            currentStats = JSON.stringify(results);\n            zlib.deflateRaw(currentStats, function(error, result){\n                currentStatsCompressed = result;\n                broadcastLiveStats();\n            });\n\n        }\n\n        setTimeout(collectStats, config.api.updateInterval * 1000);\n    });\n\n}\n\nfunction getPublicPorts(ports){\n    return ports.filter(function(port) {\n        return !port.hidden;\n    });\n}\n\nfunction getReadableHashRateString(hashrate){\n    var i = 0;\n    var byteUnits = [' H', ' KH', ' MH', ' GH', ' TH', ' PH' ];\n    while (hashrate > 1000){\n        hashrate = hashrate / 1000;\n        i++;\n    }\n    return hashrate.toFixed(2) + byteUnits[i];\n}\n\nfunction broadcastLiveStats(){\n\n    log('info', logSystem, 'Broadcasting to %d visitors and %d address lookups', [Object.keys(liveConnections).length, Object.keys(addressConnections).length]);\n\n    for (var uid in liveConnections){\n        var res = liveConnections[uid];\n        res.end(currentStatsCompressed);\n    }\n\n    var redisCommands = [];\n    for (var address in addressConnections){\n        redisCommands.push(['hgetall', config.coin + ':workers:' + address]);\n        redisCommands.push(['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES']);\n    }\n    redisClient.multi(redisCommands).exec(function(error, replies){\n\n        var addresses = Object.keys(addressConnections);\n\n        for (var i = 0; i < addresses.length; i++){\n            var offset = i * 2;\n            var address = addresses[i];\n            var stats = replies[offset];\n            var res = addressConnections[address];\n            if (!stats){\n                res.end(JSON.stringify({error: \"not found\"}));\n                return;\n            }\n            stats.hashrate = minerStats[address];\n            res.end(JSON.stringify({stats: stats, payments: replies[offset + 1]}));\n        }\n    });\n}\n\nfunction handleMinerStats(urlParts, response){\n    response.writeHead(200, {\n        'Access-Control-Allow-Origin': '*',\n        'Cache-Control': 'no-cache',\n        'Content-Type': 'application/json',\n        'Connection': 'keep-alive'\n    });\n    response.write('\\n');\n    var address = urlParts.query.address;\nconsole.log(urlParts);\n\n    if (urlParts.query.longpoll === 'true'){\n        redisClient.exists(config.coin + ':workers:' + address, function(error, result){\n            if (!result){\n                response.end(JSON.stringify({error: 'not found'}));\n                return;\n            }\n            addressConnections[address] = response;\n            response.on('finish', function(){\n                delete addressConnections[address];\n            })\n        });\n    }\n    else{\n        redisClient.multi([\n            ['hgetall', config.coin + ':workers:' + address],\n            ['zrevrange', config.coin + ':payments:' + address, 0, config.api.payments - 1, 'WITHSCORES']\n        ]).exec(function(error, replies){\n            if (error || !replies[0]){\n                response.end(JSON.stringify({error: 'not found'}));\n                return;\n            }\n            var stats = replies[0];\n            stats.hashrate = minerStats[address];\n            response.end(JSON.stringify({stats: stats, payments: replies[1]}));\n        });\n    }\n}\n\n\nfunction handleGetPayments(urlParts, response){\n    var paymentKey = ':payments:all';\n\n    if (urlParts.query.address)\n        paymentKey = ':payments:' + urlParts.query.address;\n\n    redisClient.zrevrangebyscore(\n            config.coin + paymentKey,\n            '(' + urlParts.query.time,\n            '-inf',\n            'WITHSCORES',\n            'LIMIT',\n            0,\n            config.api.payments,\n        function(err, result){\n\n            var reply;\n\n            if (err)\n                reply = JSON.stringify({error: 'query failed'});\n            else\n                reply = JSON.stringify(result);\n\n            response.writeHead(\"200\", {\n                'Access-Control-Allow-Origin': '*',\n                'Cache-Control': 'no-cache',\n                'Content-Type': 'application/json',\n                'Content-Length': reply.length\n            });\n            response.end(reply);\n\n        }\n    )\n}\n\nfunction handleGetBlocks(urlParts, response){\n    redisClient.zrevrangebyscore(\n            config.coin + ':blocks:matured',\n            '(' + urlParts.query.height,\n            '-inf',\n            'WITHSCORES',\n            'LIMIT',\n            0,\n            config.api.blocks,\n        function(err, result){\n\n        var reply;\n\n        if (err)\n            reply = JSON.stringify({error: 'query failed'});\n        else\n            reply = JSON.stringify(result);\n\n        response.writeHead(\"200\", {\n            'Access-Control-Allow-Origin': '*',\n            'Cache-Control': 'no-cache',\n            'Content-Type': 'application/json',\n            'Content-Length': reply.length\n        });\n        response.end(reply);\n\n    });\n}\n\n\ncollectStats();\n\nfunction authorize(request, response){\n\n    response.setHeader('Access-Control-Allow-Origin', '*');\n\n    var sentPass = url.parse(request.url, true).query.password;\n\n    if (sentPass !== config.api.password){\n        response.statusCode = 401;\n        response.end('invalid password');\n        return;\n    }\n\n    response.statusCode = 200;\n    response.setHeader('Cache-Control', 'no-cache');\n    response.setHeader('Content-Type', 'application/json');\n\n    return true;\n}\n\nfunction handleAdminStats(response){\n\n    async.waterfall([\n\n        //Get worker keys & unlocked blocks\n        function(callback){\n            redisClient.multi([\n                ['keys', config.coin + ':workers:*'],\n                ['zrange', config.coin + ':blocks:matured', 0, -1]\n            ]).exec(function(error, replies) {\n                if (error) {\n                    log('error', logSystem, 'Error trying to get admin data from redis %j', [error]);\n                    callback(true);\n                    return;\n                }\n                callback(null, replies[0], replies[1]);\n            });\n        },\n\n        //Get worker balances\n        function(workerKeys, blocks, callback){\n            var redisCommands = workerKeys.map(function(k){\n                return ['hmget', k, 'balance', 'paid'];\n            });\n            redisClient.multi(redisCommands).exec(function(error, replies){\n                if (error){\n                    log('error', logSystem, 'Error with getting balances from redis %j', [error]);\n                    callback(true);\n                    return;\n                }\n\n                callback(null, replies, blocks);\n            });\n        },\n        function(workerData, blocks, callback){\n            var stats = {\n                totalOwed: 0,\n                totalPaid: 0,\n                totalRevenue: 0,\n                totalDiff: 0,\n                totalShares: 0,\n                blocksOrphaned: 0,\n                blocksUnlocked: 0,\n                totalWorkers: 0\n            };\n\n            for (var i = 0; i < workerData.length; i++){\n                stats.totalOwed += parseInt(workerData[i][0]) || 0;\n                stats.totalPaid += parseInt(workerData[i][1]) || 0;\n                stats.totalWorkers++;\n            }\n\n            for (var i = 0; i < blocks.length; i++){\n                var block = blocks[i].split(':');\n                if (block[5]) {\n                    stats.blocksUnlocked++;\n                    stats.totalDiff += parseInt(block[2]);\n                    stats.totalShares += parseInt(block[3]);\n                    stats.totalRevenue += parseInt(block[5]);\n                }\n                else{\n                    stats.blocksOrphaned++;\n                }\n            }\n            callback(null, stats);\n        }\n    ], function(error, stats){\n            if (error){\n                response.end(JSON.stringify({error: 'error collecting stats'}));\n                return;\n            }\n            response.end(JSON.stringify(stats));\n        }\n    );\n\n}\n\nvar server = http.createServer(function(request, response){\n\n    if (request.method.toUpperCase() === \"OPTIONS\"){\n\n        response.writeHead(\"204\", \"No Content\", {\n            \"access-control-allow-origin\": '*',\n            \"access-control-allow-methods\": \"GET, POST, PUT, DELETE, OPTIONS\",\n            \"access-control-allow-headers\": \"content-type, accept\",\n            \"access-control-max-age\": 10, // Seconds.\n            \"content-length\": 0\n        });\n\n        return(response.end());\n    }\n\n\n    var urlParts = url.parse(request.url, true);\n\n    switch(urlParts.pathname){\n        case '/stats':\n            var reply = currentStatsCompressed;\n            response.writeHead(\"200\", {\n                'Access-Control-Allow-Origin': '*',\n                'Cache-Control': 'no-cache',\n                'Content-Type': 'application/json',\n                'Content-Encoding': 'deflate',\n                'Content-Length': reply.length\n            });\n            response.end(reply);\n            break;\n        case '/live_stats':\n            response.writeHead(200, {\n                'Access-Control-Allow-Origin': '*',\n                'Cache-Control': 'no-cache',\n                'Content-Type': 'application/json',\n                'Content-Encoding': 'deflate',\n                'Connection': 'keep-alive'\n            });\n            var uid = Math.random().toString();\n            liveConnections[uid] = response;\n            response.on(\"finish\", function() {\n                delete liveConnections[uid];\n            });\n            break;\n        case '/stats_address':\n            handleMinerStats(urlParts, response);\n            break;\n        case '/get_payments':\n            handleGetPayments(urlParts, response);\n            break;\n        case '/get_blocks':\n            handleGetBlocks(urlParts, response);\n            break;\n        case '/admin_stats':\n            if (!authorize(request, response))\n                return;\n            log('warn', logSystem, 'Admin authorized');\n            handleAdminStats(response);\n            break;\n        default:\n            response.writeHead(404, {\n                'Access-Control-Allow-Origin': '*'\n            });\n            response.end('Invalid API call');\n            break;\n    }\n\n\n});\n\n\nserver.listen(config.api.port, function(){\n    log('info', logSystem, 'API started & listening on port %d', [config.api.port]);\n});\n"
  },
  {
    "path": "lib/apiInterfaces.js",
    "content": "var http = require('http');\n\nfunction jsonHttpRequest(host, port, data, callback){\n\n    var options = {\n        hostname: host,\n        port: port,\n        path: '/json_rpc',\n        method: 'POST',\n        headers: {\n            'Content-Length': data.length,\n            'Content-Type': 'application/json',\n            'Accept': 'application/json'\n        }\n    };\n\n    var req = http.request(options, function(res){\n        var replyData = '';\n        res.setEncoding('utf8');\n        res.on('data', function(chunk){\n            replyData += chunk;\n        });\n        res.on('end', function(){\n            var replyJson;\n            try{\n                replyJson = JSON.parse(replyData);\n            }\n            catch(e){\n                callback(e);\n                return;\n            }\n            callback(null, replyJson);\n        });\n    });\n\n    req.on('error', function(e){\n        callback(e);\n    });\n\n    req.end(data);\n}\n\nfunction rpc(host, port, method, params, callback){\n\n    var data = JSON.stringify({\n        id: \"0\",\n        jsonrpc: \"2.0\",\n        method: method,\n        params: params\n    });\n    jsonHttpRequest(host, port, data, function(error, replyJson){\n        if (error){\n            callback(error);\n            return;\n        }\n        callback(replyJson.error, replyJson.result)\n    });\n}\n\nfunction batchRpc(host, port, array, callback){\n    var rpcArray = [];\n    for (var i = 0; i < array.length; i++){\n        rpcArray.push({\n            id: i.toString(),\n            jsonrpc: \"2.0\",\n            method: array[i][0],\n            params: array[i][1]\n        });\n    }\n    var data = JSON.stringify(rpcArray);\n    jsonHttpRequest(host, port, data, callback);\n}\n\n\nmodule.exports = function(daemonConfig, walletConfig){\n    return {\n        batchRpcDaemon: function(batchArray, callback){\n            batchRpc(daemonConfig.host, daemonConfig.port, batchArray, callback);\n        },\n        rpcDaemon: function(method, params, callback){\n            rpc(daemonConfig.host, daemonConfig.port, method, params, callback);\n        },\n        rpcWallet: function(method, params, callback){\n            rpc(walletConfig.host, walletConfig.port, method, params, callback);\n        }\n    }\n};"
  },
  {
    "path": "lib/blockUnlocker.js",
    "content": "var async = require('async');\n\nvar apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet);\n\nvar logSystem = 'unlocker';\nrequire('./exceptionWriter.js')(logSystem);\n\n\nlog('info', logSystem, 'Started');\n\n\n//Use this in payment processing to get block info once batch RPC is supported\n/*\nvar batchArray = [\n    ['getblockheaderbyheight', {height: 21}],\n    ['getblockheaderbyheight', {height: 22}],\n    ['getblockheaderbyheight', {height: 23\n    }]\n];\n\napiInterfaces.batchRpcDaemon(batchArray, function(error, response){\n\n});\n*/\n\n\nfunction runInterval(){\n    async.waterfall([\n\n        //Get all block candidates in redis\n        function(callback){\n            redisClient.zrange(config.coin + ':blocks:candidates', 0, -1, 'WITHSCORES', function(error, results){\n                if (error){\n                    log('error', logSystem, 'Error trying to get pending blocks from redis %j', [error]);\n                    callback(true);\n                    return;\n                }\n                if (results.length === 0){\n                    log('info', logSystem, 'No blocks candidates in redis');\n                    callback(true);\n                    return;\n                }\n\n                var blocks = [];\n\n                for (var i = 0; i < results.length; i += 2){\n                    var parts = results[i].split(':');\n                    blocks.push({\n                        serialized: results[i],\n                        height: parseInt(results[i + 1]),\n                        hash: parts[0],\n                        time: parts[1],\n                        difficulty: parts[2],\n                        shares: parts[3]\n                    });\n                }\n\n                callback(null, blocks);\n            });\n        },\n\n        //Check if blocks are orphaned\n        function(blocks, callback){\n            async.filter(blocks, function(block, mapCback){\n                apiInterfaces.rpcDaemon('getblockheaderbyheight', {height: block.height}, function(error, result){\n                    if (error){\n                        log('error', logSystem, 'Error with getblockheaderbyheight RPC request for block %s - %j', [block.serialized, error]);\n                        block.unlocked = false;\n                        mapCback();\n                        return;\n                    }\n                    if (!result.block_header){\n                        log('error', logSystem, 'Error with getblockheaderbyheight, no details returned for %s - %j', [block.serialized, result]);\n                        block.unlocked = false;\n                        mapCback();\n                        return;\n                    }\n                    var blockHeader = result.block_header;\n                    block.orphaned = blockHeader.hash === block.hash ? 0 : 1;\n                    block.unlocked = blockHeader.depth >= config.blockUnlocker.depth;\n                    block.reward = blockHeader.reward;\n                    mapCback(block.unlocked);\n                });\n            }, function(unlockedBlocks){\n\n                if (unlockedBlocks.length === 0){\n                    log('info', logSystem, 'No pending blocks are unlocked yet (%d pending)', [blocks.length]);\n                    callback(true);\n                    return;\n                }\n\n                callback(null, unlockedBlocks)\n            })\n        },\n\n        //Get worker shares for each unlocked block\n        function(blocks, callback){\n\n\n            var redisCommands = blocks.map(function(block){\n                return ['hgetall', config.coin + ':shares:round' + block.height];\n            });\n\n\n            redisClient.multi(redisCommands).exec(function(error, replies){\n                if (error){\n                    log('error', logSystem, 'Error with getting round shares from redis %j', [error]);\n                    callback(true);\n                    return;\n                }\n                for (var i = 0; i < replies.length; i++){\n                    var workerShares = replies[i];\n                    blocks[i].workerShares = workerShares;\n                }\n                callback(null, blocks);\n            });\n        },\n\n        //Handle orphaned blocks\n        function(blocks, callback){\n            var orphanCommands = [];\n\n            blocks.forEach(function(block){\n                if (!block.orphaned) return;\n\n                orphanCommands.push(['del', config.coin + ':shares:round' + block.height]);\n\n                orphanCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]);\n                orphanCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [\n                    block.hash,\n                    block.time,\n                    block.difficulty,\n                    block.shares,\n                    block.orphaned\n                ].join(':')]);\n\n                if (block.workerShares) {\n                    var workerShares = block.workerShares;\n                    Object.keys(workerShares).forEach(function (worker) {\n                        orphanCommands.push(['hincrby', config.coin + ':shares:roundCurrent', worker, workerShares[worker]]);\n                    });\n                }\n            });\n\n            if (orphanCommands.length > 0){\n                redisClient.multi(orphanCommands).exec(function(error, replies){\n                    if (error){\n                        log('error', logSystem, 'Error with cleaning up data in redis for orphan block(s) %j', [error]);\n                        callback(true);\n                        return;\n                    }\n                    callback(null, blocks);\n                });\n            }\n            else{\n                callback(null, blocks);\n            }\n        },\n\n        //Handle unlocked blocks\n        function(blocks, callback){\n            var unlockedBlocksCommands = [];\n            var payments = {};\n            var totalBlocksUnlocked = 0;\n            blocks.forEach(function(block){\n                if (block.orphaned) return;\n                totalBlocksUnlocked++;\n\n                unlockedBlocksCommands.push(['del', config.coin + ':shares:round' + block.height]);\n                unlockedBlocksCommands.push(['zrem', config.coin + ':blocks:candidates', block.serialized]);\n                unlockedBlocksCommands.push(['zadd', config.coin + ':blocks:matured', block.height, [\n                    block.hash,\n                    block.time,\n                    block.difficulty,\n                    block.shares,\n                    block.orphaned,\n                    block.reward\n                ].join(':')]);\n\n                var feePercent = config.blockUnlocker.poolFee / 100;\n\n                if (doDonations) {\n                    feePercent += config.blockUnlocker.devDonation / 100;\n                    feePercent += config.blockUnlocker.coreDevDonation / 100;\n\n                    var devDonation = block.reward * (config.blockUnlocker.devDonation / 100);\n                    payments[devDonationAddress] = devDonation;\n\n                    var coreDevDonation = block.reward * (config.blockUnlocker.coreDevDonation / 100);\n                    payments[coreDevDonationAddress] = coreDevDonation;\n                }\n\n                var reward = block.reward - (block.reward * feePercent);\n\n                if (block.workerShares) {\n                    var totalShares = parseInt(block.shares);\n                    Object.keys(block.workerShares).forEach(function (worker) {\n                        var percent = block.workerShares[worker] / totalShares;\n                        var workerReward = reward * percent;\n                        payments[worker] = (payments[worker] || 0) + workerReward;\n                    });\n                }\n            });\n\n            for (var worker in payments) {\n                var amount = parseInt(payments[worker]);\n                if (amount <= 0){\n                    delete payments[worker];\n                    continue;\n                }\n                unlockedBlocksCommands.push(['hincrby', config.coin + ':workers:' + worker, 'balance', amount]);\n            }\n\n            if (unlockedBlocksCommands.length === 0){\n                log('info', logSystem, 'No unlocked blocks yet (%d pending)', [blocks.length]);\n                callback(true);\n                return;\n            }\n\n            redisClient.multi(unlockedBlocksCommands).exec(function(error, replies){\n                if (error){\n                    log('error', logSystem, 'Error with unlocking blocks %j', [error]);\n                    callback(true);\n                    return;\n                }\n                log('info', logSystem, 'Unlocked %d blocks and update balances for %d workers', [totalBlocksUnlocked, Object.keys(payments).length]);\n                callback(null);\n            });\n        }\n    ], function(error, result){\n        setTimeout(runInterval, config.blockUnlocker.interval * 1000);\n    })\n}\n\nrunInterval();\n"
  },
  {
    "path": "lib/cli.js",
    "content": ""
  },
  {
    "path": "lib/configReader.js",
    "content": "var fs = require('fs');\n\nvar configFile = (function(){\n    for (var i = 0; i < process.argv.length; i++){\n        if (process.argv[i].indexOf('-config=') === 0)\n            return process.argv[i].split('=')[1];\n    }\n    return 'config.json';\n})();\n\n\ntry {\n    global.config = JSON.parse(fs.readFileSync(configFile));\n}\ncatch(e){\n    console.error('Failed to read config file ' + configFile + '\\n\\n' + e);\n    return;\n}\n\nglobal.version = \"v0.99.3.3\";\nglobal.devDonationAddress = '45Jmf8PnJKziGyrLouJMeBFw2yVyX1QB52sKEQ4S1VSU2NVsaVGPNu4bWKkaHaeZ6tWCepP6iceZk8XhTLzDaEVa72QrtVh';\nglobal.coreDevDonationAddress = '46BeWrHpwXmHDpDEUmZBWZfoQpdc6HaERCNmx1pEYL2rAcuwufPN9rXHHtyUA4QVy66qeFQkn6sfK8aHYjA3jk3o1Bv16em';\nglobal.doDonations =  devDonationAddress[0] === config.poolServer.poolAddress[0] && (\n    config.blockUnlocker.devDonation > 0 || config.blockUnlocker.coreDevDonation > 0\n);"
  },
  {
    "path": "lib/exceptionWriter.js",
    "content": "var fs = require('fs');\nvar cluster = require('cluster');\n\nvar dateFormat = require('dateformat');\n\n\nmodule.exports = function(logSystem){\n\n    process.on('uncaughtException', function(err) {\n        console.log('\\n' + err.stack + '\\n');\n        var time = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss');\n        fs.appendFile(config.logging.files.directory + '/' + logSystem + '_crash.log', time + '\\n' + err.stack + '\\n\\n', function(err){\n            if (cluster.isWorker)\n                process.exit();\n        });\n    });\n};"
  },
  {
    "path": "lib/logger.js",
    "content": "var fs = require('fs');\nvar util = require('util');\n\nvar dateFormat = require('dateformat');\nvar clc = require('cli-color');\n\nvar severityMap = {\n    'info': clc.blue,\n    'warn': clc.yellow,\n    'error': clc.red\n};\n\nvar severityLevels = ['info', 'warn', 'error'];\n\n\nvar logDir = config.logging.files.directory;\n\nif (!fs.existsSync(logDir)){\n    try {\n        fs.mkdirSync(logDir);\n    }\n    catch(e){\n        throw e;\n    }\n}\n\nvar pendingWrites = {};\n\nsetInterval(function(){\n    for (var fileName in pendingWrites){\n        var data = pendingWrites[fileName];\n        fs.appendFile(fileName, data);\n        delete pendingWrites[fileName];\n    }\n}, config.logging.files.flushInterval * 1000);\n\nglobal.log = function(severity, system, text, data){\n\n    var logConsole = severityLevels.indexOf(severity) >= severityLevels.indexOf(config.logging.console.level);\n    var logFiles = severityLevels.indexOf(severity) >= severityLevels.indexOf(config.logging.files.level);\n\n    if (!logConsole && !logFiles) return;\n\n    var time = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss');\n    var formattedMessage = text;\n\n    if (data) {\n        data.unshift(text);\n        formattedMessage = util.format.apply(null, data);\n    }\n\n    if (logConsole){\n        if (config.logging.console.colors)\n            console.log(severityMap[severity](time) + clc.white.bold(' [' + system + '] ') + formattedMessage);\n        else\n            console.log(time + ' [' + system + '] ' + formattedMessage);\n    }\n\n\n    if (logFiles) {\n        var fileName = logDir + '/' + system + '_' + severity + '.log';\n        var fileLine = time + ' ' + formattedMessage + '\\n';\n        pendingWrites[fileName] = (pendingWrites[fileName] || '') + fileLine;\n    }\n};"
  },
  {
    "path": "lib/paymentProcessor.js",
    "content": "var fs = require('fs');\n\nvar async = require('async');\n\nvar apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet);\n\n\nvar logSystem = 'payments';\nrequire('./exceptionWriter.js')(logSystem);\n\n\nlog('info', logSystem, 'Started');\n\n\nfunction runInterval(){\n    async.waterfall([\n\n        //Get worker keys\n        function(callback){\n            redisClient.keys(config.coin + ':workers:*', function(error, result) {\n                if (error) {\n                    log('error', logSystem, 'Error trying to get worker balances from redis %j', [error]);\n                    callback(true);\n                    return;\n                }\n                callback(null, result);\n            });\n        },\n\n        //Get worker balances\n        function(keys, callback){\n            var redisCommands = keys.map(function(k){\n                return ['hget', k, 'balance'];\n            });\n            redisClient.multi(redisCommands).exec(function(error, replies){\n                if (error){\n                    log('error', logSystem, 'Error with getting balances from redis %j', [error]);\n                    callback(true);\n                    return;\n                }\n                var balances = {};\n                for (var i = 0; i < replies.length; i++){\n                    var parts = keys[i].split(':');\n                    var workerId = parts[parts.length - 1];\n                    balances[workerId] = parseInt(replies[i]) || 0\n\n                }\n                callback(null, balances);\n            });\n        },\n\n        //Filter workers under balance threshold for payment\n        function(balances, callback){\n\n            var payments = {};\n\n            for (var worker in balances){\n                var balance = balances[worker];\n                if (balance >= config.payments.minPayment){\n                    var remainder = balance % config.payments.denomination;\n                    var payout = balance - remainder;\n                    if (payout < 0) continue;\n                    payments[worker] = payout;\n                }\n            }\n\n            if (Object.keys(payments).length === 0){\n                log('info', logSystem, 'No workers\\' balances reached the minimum payment threshold');\n                callback(true);\n                return;\n            }\n\n            var transferCommands = [];\n\n            var transferCommandsLength = Math.ceil(Object.keys(payments).length / config.payments.maxAddresses);\n\n            for (var i = 0; i < transferCommandsLength; i++){\n                transferCommands.push({\n                    redis: [],\n                    amount : 0,\n                    rpc: {\n                        destinations: [],\n                        fee: config.payments.transferFee,\n                        mixin: config.payments.mixin,\n                        unlock_time: 0\n                    }\n                });\n            }\n\n            var addresses = 0;\n            var commandIndex = 0;\n\n            for (var worker in payments){\n\t\tvar anAmount = payments[worker].toString();\n\t\tvar amount = parseFloat(anAmount);\n                transferCommands[commandIndex].rpc.destinations.push({amount: amount, address: worker});\n                transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'balance', -amount]);\n                transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'paid', amount]);\n                transferCommands[commandIndex].amount += amount;\n\n                addresses++;\n                if (addresses >= config.payments.maxAddresses){\n                    commandIndex++;\n                    addresses = 0;\n                }\n            }\n\n            var timeOffset = 0;\n\n            async.filter(transferCommands, function(transferCmd, cback){\n                apiInterfaces.rpcWallet('transfer', transferCmd.rpc, function(error, result){\n                    if (error){\n                        log('error', logSystem, 'Error with transfer RPC request to wallet daemon %j', [error]);\n                        log('error', logSystem, 'Payments failed to send to %j', transferCmd.rpc.destinations);\n                        cback(false);\n                        return;\n                    }\n\n                    var now = (timeOffset++) + Date.now() / 1000 | 0;\n                    var txHash = result.tx_hash.replace('<', '').replace('>', '');\n\n\n                    transferCmd.redis.push(['zadd', config.coin + ':payments:all', now, [\n                        txHash,\n                        transferCmd.amount,\n                        transferCmd.rpc.fee,\n                        transferCmd.rpc.mixin,\n                        Object.keys(transferCmd.rpc.destinations).length\n                    ].join(':')]);\n\n\n                    for (var i = 0; i < transferCmd.rpc.destinations.length; i++){\n                        var destination = transferCmd.rpc.destinations[i];\n                        transferCmd.redis.push(['zadd', config.coin + ':payments:' + destination.address, now, [\n                            txHash,\n                            destination.amount,\n                            transferCmd.rpc.fee,\n                            transferCmd.rpc.mixin\n                        ].join(':')]);\n                    }\n\n\n                    log('info', logSystem, 'Payments sent via wallet daemon %j', [result]);\n                    redisClient.multi(transferCmd.redis).exec(function(error, replies){\n                        if (error){\n                            log('error', logSystem, 'Super critical error! Payments sent yet failing to update balance in redis, double payouts likely to happen %j', [error]);\n                            log('error', logSystem, 'Double payments likely to be sent to %j', transferCmd.rpc.destinations);\n                            cback(false);\n                            return;\n                        }\n                        cback(true);\n                    });\n                });\n            }, function(succeeded){\n                var failedAmount = transferCommands.length - succeeded.length;\n                log('info', logSystem, 'Payments splintered and %d successfully sent, %d failed', [succeeded.length, failedAmount]);\n                callback(null);\n            });\n\n        }\n\n    ], function(error, result){\n        setTimeout(runInterval, config.payments.interval * 1000);\n    });\n}\n\nrunInterval();\n"
  },
  {
    "path": "lib/pool.js",
    "content": "var fs = require('fs');\nvar net = require('net');\nvar crypto = require('crypto');\n\nvar async = require('async');\nvar bignum = require('bignum');\nvar multiHashing = require('multi-hashing');\nvar cnUtil = require('cryptonote-util');\n\n// Must exactly be 8 hex chars\nvar noncePattern = new RegExp(\"^[0-9A-Fa-f]{8}$\");\n\nvar threadId = '(Thread ' + process.env.forkId + ') ';\n\nvar logSystem = 'pool';\nrequire('./exceptionWriter.js')(logSystem);\n\nvar apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet);\nvar utils = require('./utils.js');\n\nvar log = function(severity, system, text, data){\n    global.log(severity, system, threadId + text, data);\n};\n\nvar cryptoNight = multiHashing['cryptonight'];\n\nfunction cryptoNightFast(buf) {\n    return cryptoNight(Buffer.concat([new Buffer([buf.length]), buf]), true);\n}\n\nvar diff1 = bignum('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', 16);\n\nvar instanceId = crypto.randomBytes(4);\n\nvar validBlockTemplates = [];\nvar currentBlockTemplate;\n\n//Vars for slush mining\nvar scoreTime;\nvar lastChecked = 0;\n\nvar connectedMiners = {};\n\nvar bannedIPs = {};\nvar perIPStats = {};\n\nvar shareTrustEnabled = config.poolServer.shareTrust && config.poolServer.shareTrust.enabled;\nvar shareTrustStepFloat = shareTrustEnabled ? config.poolServer.shareTrust.stepDown / 100 : 0;\nvar shareTrustMinFloat = shareTrustEnabled ? config.poolServer.shareTrust.min / 100 : 0;\n\n\nvar banningEnabled = config.poolServer.banning && config.poolServer.banning.enabled;\n\n\nsetInterval(function(){\n    var now = Date.now() / 1000 | 0;\n    for (var minerId in connectedMiners){\n        var miner = connectedMiners[minerId];\n        miner.retarget(now);\n    }\n}, config.poolServer.varDiff.retargetTime * 1000);\n\n\n/* Every 30 seconds clear out timed-out miners and old bans */\nsetInterval(function(){\n    var now = Date.now();\n    var timeout = config.poolServer.minerTimeout * 1000;\n    for (var minerId in connectedMiners){\n        var miner = connectedMiners[minerId];\n        if (now - miner.lastBeat > timeout){\n            log('warn', logSystem, 'Miner timed out and disconnected %s@%s', [miner.login, miner.ip]);\n            delete connectedMiners[minerId];\n        }\n    }\n\n    if (banningEnabled){\n        for (ip in bannedIPs){\n            var banTime = bannedIPs[ip];\n            if (now - banTime > config.poolServer.banning.time * 1000) {\n                delete bannedIPs[ip];\n                delete perIPStats[ip];\n                log('info', logSystem, 'Ban dropped for %s', [ip]);\n            }\n        }\n    }\n\n}, 30000);\n\n\nprocess.on('message', function(message) {\n    switch (message.type) {\n        case 'banIP':\n            bannedIPs[message.ip] = Date.now();\n            break;\n    }\n});\n\n\nfunction IsBannedIp(ip){\n    if (!banningEnabled || !bannedIPs[ip]) return false;\n\n    var bannedTime = bannedIPs[ip];\n    var bannedTimeAgo = Date.now() - bannedTime;\n    var timeLeft = config.poolServer.banning.time * 1000 - bannedTimeAgo;\n    if (timeLeft > 0){\n        return true;\n    }\n    else {\n        delete bannedIPs[ip];\n        log('info', logSystem, 'Ban dropped for %s', [ip]);\n        return false;\n    }\n}\n\n\nfunction BlockTemplate(template){\n    this.blob = template.blocktemplate_blob;\n    this.difficulty = template.difficulty;\n    this.height = template.height;\n    this.reserveOffset = template.reserved_offset;\n    this.buffer = new Buffer(this.blob, 'hex');\n    instanceId.copy(this.buffer, this.reserveOffset + 4, 0, 3);\n    this.extraNonce = 0;\n}\nBlockTemplate.prototype = {\n    nextBlob: function(){\n        this.buffer.writeUInt32BE(++this.extraNonce, this.reserveOffset);\n        return cnUtil.convert_blob(this.buffer).toString('hex');\n    }\n};\n\n\n\nfunction getBlockTemplate(callback){\n    apiInterfaces.rpcDaemon('getblocktemplate', {reserve_size: 8, wallet_address: config.poolServer.poolAddress}, callback);\n}\n\n\n\nfunction jobRefresh(loop, callback){\n    callback = callback || function(){};\n    getBlockTemplate(function(error, result){\n        if (loop)\n            setTimeout(function(){\n                jobRefresh(true);\n            }, config.poolServer.blockRefreshInterval);\n        if (error){\n            log('error', logSystem, 'Error polling getblocktemplate %j', [error]);\n            callback(false);\n            return;\n        }\n        if (!currentBlockTemplate || result.height > currentBlockTemplate.height){\n            log('info', logSystem, 'New block to mine at height %d w/ difficulty of %d', [result.height, result.difficulty]);\n            processBlockTemplate(result);\n        }\n        callback(true);\n    })\n}\n\n\n\nfunction processBlockTemplate(template){\n\n    if (currentBlockTemplate)\n        validBlockTemplates.push(currentBlockTemplate);\n\n    if (validBlockTemplates.length > 3)\n        validBlockTemplates.shift();\n\n    currentBlockTemplate = new BlockTemplate(template);\n\n    for (var minerId in connectedMiners){\n        var miner = connectedMiners[minerId];\n        miner.pushMessage('job', miner.getJob());\n    }\n}\n\n\n\n(function init(){\n    jobRefresh(true, function(sucessful){\n        if (!sucessful){\n            log('error', logSystem, 'Could not start pool');\n            return;\n        }\n        startPoolServerTcp(function(successful){\n\n        });\n    });\n})();\n\nvar VarDiff = (function(){\n    var variance = config.poolServer.varDiff.variancePercent / 100 * config.poolServer.varDiff.targetTime;\n    return {\n        variance: variance,\n        bufferSize: config.poolServer.varDiff.retargetTime / config.poolServer.varDiff.targetTime * 4,\n        tMin: config.poolServer.varDiff.targetTime - variance,\n        tMax: config.poolServer.varDiff.targetTime + variance,\n        maxJump: config.poolServer.varDiff.maxJump\n    };\n})();\n\nfunction Miner(id, login, pass, ip, startingDiff, pushMessage){\n    this.id = id;\n    this.login = login;\n    this.pass = pass;\n    this.ip = ip;\n    this.pushMessage = pushMessage;\n    this.heartbeat();\n    this.difficulty = startingDiff;\n    this.validJobs = [];\n\n    // Vardiff related variables\n    this.shareTimeRing = utils.ringBuffer(16);\n    this.lastShareTime = Date.now() / 1000 | 0;\n\n    if (shareTrustEnabled) {\n        this.trust = {\n            threshold: config.poolServer.shareTrust.threshold,\n            probability: 1,\n            penalty: 0\n        };\n    }\n}\nMiner.prototype = {\n    retarget: function(now){\n\n        var options = config.poolServer.varDiff;\n\n        var sinceLast = now - this.lastShareTime;\n        var decreaser = sinceLast > VarDiff.tMax;\n\n        var avg = this.shareTimeRing.avg(decreaser ? sinceLast : null);\n        var newDiff;\n\n        var direction;\n\n        if (avg > VarDiff.tMax && this.difficulty > options.minDiff){\n            newDiff = options.targetTime / avg * this.difficulty;\n            newDiff = newDiff > options.minDiff ? newDiff : options.minDiff;\n            direction = -1;\n        }\n        else if (avg < VarDiff.tMin && this.difficulty < options.maxDiff){\n            newDiff = options.targetTime / avg * this.difficulty;\n            newDiff = newDiff < options.maxDiff ? newDiff : options.maxDiff;\n            direction = 1;\n        }\n        else{\n            return;\n        }\n\n        if (Math.abs(newDiff - this.difficulty) / this.difficulty * 100 > options.maxJump){\n            var change = options.maxJump / 100 * this.difficulty * direction;\n            newDiff = this.difficulty + change;\n        }\n\n        this.setNewDiff(newDiff);\n        this.shareTimeRing.clear();\n        if (decreaser) this.lastShareTime = now;\n    },\n    setNewDiff: function(newDiff){\n        newDiff = Math.round(newDiff);\n        if (this.difficulty === newDiff) return;\n        log('info', logSystem, 'Retargetting difficulty %d to %d for %s', [this.difficulty, newDiff, this.login]);\n        this.pendingDifficulty = newDiff;\n        this.pushMessage('job', this.getJob());\n    },\n    heartbeat: function(){\n        this.lastBeat = Date.now();\n    },\n    getTargetHex: function(){\n        if (this.pendingDifficulty){\n            this.lastDifficulty = this.difficulty;\n            this.difficulty = this.pendingDifficulty;\n            this.pendingDifficulty = null;\n        }\n\n        var padded = new Buffer(32);\n        padded.fill(0);\n\n        var diffBuff = diff1.div(this.difficulty).toBuffer();\n        diffBuff.copy(padded, 32 - diffBuff.length);\n\n        var buff = padded.slice(0, 4);\n        var buffArray = buff.toJSON();\n        buffArray.reverse();\n        var buffReversed = new Buffer(buffArray);\n        this.target = buffReversed.readUInt32BE(0);\n        var hex = buffReversed.toString('hex');\n        return hex;\n    },\n    getJob: function(){\n        if (this.lastBlockHeight === currentBlockTemplate.height && !this.pendingDifficulty) {\n            return {\n                blob: '',\n                job_id: '',\n                target: ''\n            };\n        }\n\n        var blob = currentBlockTemplate.nextBlob();\n        this.lastBlockHeight = currentBlockTemplate.height;\n        var target = this.getTargetHex();\n\n        var newJob = {\n            id: utils.uid(),\n            extraNonce: currentBlockTemplate.extraNonce,\n            height: currentBlockTemplate.height,\n            difficulty: this.difficulty,\n            score: this.score,\n            diffHex: this.diffHex,\n            submissions: []\n        };\n\n        this.validJobs.push(newJob);\n\n        if (this.validJobs.length > 4)\n            this.validJobs.shift();\n\n        return {\n            blob: blob,\n            job_id: newJob.id,\n            target: target,\n            id: this.id\n        };\n    },\n    checkBan: function(validShare){\n        if (!banningEnabled) return;\n\n        // Init global per-IP shares stats\n        if (!perIPStats[this.ip]){\n            perIPStats[this.ip] = { validShares: 0, invalidShares: 0 };\n        }\n\n        var stats = perIPStats[this.ip];\n        validShare ? stats.validShares++ : stats.invalidShares++;\n\n        if (stats.validShares + stats.invalidShares >= config.poolServer.banning.checkThreshold){\n            if (stats.invalidShares / stats.validShares >= config.poolServer.banning.invalidPercent / 100){\n                log('warn', logSystem, 'Banned %s@%s', [this.login, this.ip]);\n                bannedIPs[this.ip] = Date.now();\n                delete connectedMiners[this.id];\n                process.send({type: 'banIP', ip: this.ip});\n            }\n            else{\n                stats.invalidShares = 0;\n                stats.validShares = 0;\n            }\n        }\n    }\n};\n\n\n\nfunction recordShareData(miner, job, shareDiff, blockCandidate, hashHex, shareType, blockTemplate){\n\n    var dateNow = Date.now();\n    var dateNowSeconds = dateNow / 1000 | 0;\n\n    //Weighting older shares lower than newer ones to prevent pool hopping\n    if (config.poolServer.slushMining.enabled) {                \n        if (lastChecked + config.poolServer.slushMining.lastBlockCheckRate <= dateNowSeconds || lastChecked == 0) {\n            redisClient.hget(config.coin + ':stats', 'lastBlockFound', function(error, result) {\n                if (error) {\n                    log('error', logSystem, 'Unable to determine the timestamp of the last block found');\n                    return;\n                }\n                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)\n                lastChecked = dateNowSeconds;\n            });\n        }\n        \n        job.score = job.difficulty * Math.pow(Math.E, ((dateNowSeconds - scoreTime) / config.poolServer.slushMining.weight)); //Score Calculation\n        log('info', logSystem, 'Submitted score ' + job.score + ' with difficulty ' + job.difficulty + ' and the time ' + scoreTime);\n    }\n    else {\n        job.score = job.difficulty;\n    }\n\n    var redisCommands = [\n        ['hincrby', config.coin + ':shares:roundCurrent', miner.login, job.score],\n        ['zadd', config.coin + ':hashrate', dateNowSeconds, [job.difficulty, miner.login, dateNow].join(':')],\n        ['hincrby', config.coin + ':workers:' + miner.login, 'hashes', job.difficulty],\n        ['hset', config.coin + ':workers:' + miner.login, 'lastShare', dateNowSeconds]\n    ];\n\n    if (blockCandidate){\n        redisCommands.push(['hset', config.coin + ':stats', 'lastBlockFound', Date.now()]);\n        redisCommands.push(['rename', config.coin + ':shares:roundCurrent', config.coin + ':shares:round' + job.height]);\n        redisCommands.push(['hgetall', config.coin + ':shares:round' + job.height]);\n    }\n\n    redisClient.multi(redisCommands).exec(function(err, replies){\n        if (err){\n            log('error', logSystem, 'Failed to insert share data into redis %j \\n %j', [err, redisCommands]);\n            return;\n        }\n        if (blockCandidate){\n            var workerShares = replies[replies.length - 1];\n            var totalShares = Object.keys(workerShares).reduce(function(p, c){\n                return p + parseInt(workerShares[c])\n            }, 0);\n            redisClient.zadd(config.coin + ':blocks:candidates', job.height, [\n                hashHex,\n                Date.now() / 1000 | 0,\n                blockTemplate.difficulty,\n                totalShares\n            ].join(':'), function(err, result){\n                if (err){\n                    log('error', logSystem, 'Failed inserting block candidate %s \\n %j', [hashHex, err]);\n                }\n            });\n        }\n\n    });\n\n    log('info', logSystem, 'Accepted %s share at difficulty %d/%d from %s@%s', [shareType, job.difficulty, shareDiff, miner.login, miner.ip]);\n\n}\n\nfunction processShare(miner, job, blockTemplate, nonce, resultHash){\n    var shareBuffer = new Buffer(blockTemplate.buffer.length);\n    blockTemplate.buffer.copy(shareBuffer);\n    shareBuffer.writeUInt32BE(job.extraNonce, blockTemplate.reserveOffset);\n    new Buffer(nonce, 'hex').copy(shareBuffer, 39);\n\n    var convertedBlob;\n    var hash;\n    var shareType;\n\n    if (shareTrustEnabled && miner.trust.threshold <= 0 && miner.trust.penalty <= 0 && Math.random() > miner.trust.probability){\n        hash = new Buffer(resultHash, 'hex');\n        shareType = 'trusted';\n    }\n    else {\n        convertedBlob = cnUtil.convert_blob(shareBuffer);\n        var cn_variant = convertedBlob[0] == 6 ? 1 : 0; //If v6 then use new variant else use previous\n        hash = cryptoNight(convertedBlob, cn_variant);\n        shareType = 'valid';\n    }\n\n\n    if (hash.toString('hex') !== resultHash) {\n        log('warn', logSystem, 'Bad hash from miner %s@%s', [miner.login, miner.ip]);\n        return false;\n    }\n\n    var hashArray = hash.toJSON();\n    hashArray.reverse();\n    var hashNum = bignum.fromBuffer(new Buffer(hashArray));\n    var hashDiff = diff1.div(hashNum);\n\n\n\n    if (hashDiff.ge(blockTemplate.difficulty)){\n\n        apiInterfaces.rpcDaemon('submitblock', [shareBuffer.toString('hex')], function(error, result){\n            if (error){\n                log('error', logSystem, 'Error submitting block at height %d from %s@%s, share type: \"%s\" - %j', [job.height, miner.login, miner.ip, shareType, error]);\n                recordShareData(miner, job, hashDiff.toString(), false, null, shareType);\n            }\n            else{\n                var blockFastHash = cryptoNightFast(convertedBlob || cnUtil.convert_blob(shareBuffer)).toString('hex');\n                log('info', logSystem,\n                    'Block %s found at height %d by miner %s@%s - submit result: %j',\n                    [blockFastHash.substr(0, 6), job.height, miner.login, miner.ip, result]\n                );\n                recordShareData(miner, job, hashDiff.toString(), true, blockFastHash, shareType, blockTemplate);\n                jobRefresh();\n            }\n        });\n    }\n\n    else if (hashDiff.lt(job.difficulty)){\n        log('warn', logSystem, 'Rejected low difficulty share of %s from %s@%s', [hashDiff.toString(), miner.login, miner.ip]);\n        return false;\n    }\n    else{\n        recordShareData(miner, job, hashDiff.toString(), false, null, shareType);\n    }\n\n    return true;\n}\n\n\nfunction handleMinerMethod(method, params, ip, portData, sendReply, pushMessage){\n\n\n    var miner = connectedMiners[params.id];\n\n    // Check for ban here, so preconnected attackers can't continue to screw you\n    if (IsBannedIp(ip)){\n        sendReply('your IP is banned');\n        return;\n    }\n\n    switch(method){\n        case 'login':\n            if (!params.login){\n                sendReply('missing login');\n                return;\n            }\n            if (!utils.isValidAddress(params.login, config.poolServer.poolAddress[0])){\n                sendReply('invalid address used for login');\n                return;\n            }\n            var minerId = utils.uid();\n            miner = new Miner(minerId, params.login, params.pass, ip, portData.difficulty, pushMessage);\n            connectedMiners[minerId] = miner;\n            sendReply(null, {\n                id: minerId,\n                job: miner.getJob(),\n                status: 'OK'\n            });\n            log('info', logSystem, 'Miner connected %s@%s',  [params.login, miner.ip]);\n            break;\n        case 'getjob':\n            if (!miner){\n                sendReply('Unauthenticated');\n                return;\n            }\n            miner.heartbeat();\n            sendReply(null, miner.getJob());\n            break;\n        case 'submit':\n            if (!miner){\n                sendReply('Unauthenticated');\n                return;\n            }\n            miner.heartbeat();\n\n            var job = miner.validJobs.filter(function(job){\n                return job.id === params.job_id;\n            })[0];\n\n            if (!job){\n                sendReply('Invalid job id');\n                return;\n            }\n\n            if (!noncePattern.test(params.nonce)) {\n                var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : '';\n                log('warn', logSystem, 'Malformed nonce: ' + JSON.stringify(params) + ' from ' + minerText);\n                perIPStats[miner.ip] = { validShares: 0, invalidShares: 999999 };\n                miner.checkBan(false);\n                sendReply('Duplicate share');\n                return;\n            }\n\n            // Force lowercase for further comparison\n            params.nonce = params.nonce.toLowerCase();\n\n            if (job.submissions.indexOf(params.nonce) !== -1){\n                 var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : '';\n                 log('warn', logSystem, 'Duplicate share: ' + JSON.stringify(params) + ' from ' + minerText);\n                 perIPStats[miner.ip] = { validShares: 0, invalidShares: 999999 };\n                 miner.checkBan(false);\n                 sendReply('Duplicate share');\n                 return;\n            }\n\n            job.submissions.push(params.nonce);\n\n            var blockTemplate = currentBlockTemplate.height === job.height ? currentBlockTemplate : validBlockTemplates.filter(function(t){\n                return t.height === job.height;\n            })[0];\n\n            if (!blockTemplate){\n                sendReply('Block expired');\n                return;\n            }\n\n            var shareAccepted = processShare(miner, job, blockTemplate, params.nonce, params.result);\n            miner.checkBan(shareAccepted);\n            if (shareTrustEnabled){\n                if (shareAccepted){\n                    miner.trust.probability -= shareTrustStepFloat;\n                    if (miner.trust.probability < shareTrustMinFloat)\n                        miner.trust.probability = shareTrustMinFloat;\n                    miner.trust.penalty--;\n                    miner.trust.threshold--;\n                }\n                else{\n                    log('warn', logSystem, 'Share trust broken by %s@%s', [miner.login, miner.ip]);\n                    miner.trust.probability = 1;\n                    miner.trust.penalty = config.poolServer.shareTrust.penalty;\n                }\n            }\n\n            if (!shareAccepted){\n                sendReply('Low difficulty share');\n                return;\n            }\n\n            var now = Date.now() / 1000 | 0;\n            miner.shareTimeRing.append(now - miner.lastShareTime);\n            miner.lastShareTime = now;\n            //miner.retarget(now);\n\n            sendReply(null, {status: 'OK'});\n            break;\n        case 'keepalived' :\n            if (!miner){\n                sendReply('Unauthenticated');\n                return;\n            }\n            miner.heartbeat()\n            sendReply(null, { status:'KEEPALIVED' });\n            break;\n        default:\n            sendReply(\"invalid method\");\n            var minerText = miner ? (' ' + miner.login + '@' + miner.ip) : '';\n            log('warn', logSystem, 'Invalid method: %s (%j) from %s', [method, params, minerText]);\n            break;\n    }\n}\n\n\nvar httpResponse = ' 200 OK\\nContent-Type: text/plain\\nContent-Length: 20\\n\\nmining server online';\n\n\nfunction startPoolServerTcp(callback){\n    async.each(config.poolServer.ports, function(portData, cback){\n        var handleMessage = function(socket, jsonData, pushMessage){\n            if (!jsonData.id) {\n                log('warn', logSystem, 'Miner RPC request missing RPC id');\n                return;\n            }\n            else if (!jsonData.method) {\n                log('warn', logSystem, 'Miner RPC request missing RPC method');\n                return;\n            }\n            else if (!jsonData.params) {\n                log('warn', logSystem, 'Miner RPC request missing RPC params');\n                return;\n            }\n\n            var sendReply = function(error, result){\n                if(!socket.writable) return;\n                var sendData = JSON.stringify({\n                    id: jsonData.id,\n                    jsonrpc: \"2.0\",\n                    error: error ? {code: -1, message: error} : null,\n                    result: result\n                }) + \"\\n\";\n                socket.write(sendData);\n            };\n\n            handleMinerMethod(jsonData.method, jsonData.params, socket.remoteAddress, portData, sendReply, pushMessage);\n        };\n\n        net.createServer(function(socket){\n            socket.setKeepAlive(true);\n            socket.setEncoding('utf8');\n\n            var dataBuffer = '';\n\n            var pushMessage = function(method, params){\n                if(!socket.writable) return;\n                var sendData = JSON.stringify({\n                    jsonrpc: \"2.0\",\n                    method: method,\n                    params: params\n                }) + \"\\n\";\n                socket.write(sendData);\n            };\n\n            socket.on('data', function(d){\n                dataBuffer += d;\n                if (Buffer.byteLength(dataBuffer, 'utf8') > 10240){ //10KB\n                    dataBuffer = null;\n                    log('warn', logSystem, 'Socket flooding detected and prevented from %s', [socket.remoteAddress]);\n                    socket.destroy();\n                    return;\n                }\n                if (dataBuffer.indexOf('\\n') !== -1){\n                    var messages = dataBuffer.split('\\n');\n                    var incomplete = dataBuffer.slice(-1) === '\\n' ? '' : messages.pop();\n                    for (var i = 0; i < messages.length; i++){\n                        var message = messages[i];\n                        if (message.trim() === '') continue;\n                        var jsonData;\n                        try{\n                            jsonData = JSON.parse(message);\n                        }\n                        catch(e){\n                            if (message.indexOf('GET /') === 0) {\n                                if (message.indexOf('HTTP/1.1') !== -1) {\n                                    socket.end('HTTP/1.1' + httpResponse);\n                                    break;\n                                }\n                                else if (message.indexOf('HTTP/1.0') !== -1) {\n                                    socket.end('HTTP/1.0' + httpResponse);\n                                    break;\n                                }\n                            }\n\n                            log('warn', logSystem, 'Malformed message from %s: %s', [socket.remoteAddress, message]);\n                            socket.destroy();\n\n                            break;\n                        }\n                        handleMessage(socket, jsonData, pushMessage);\n                    }\n                    dataBuffer = incomplete;\n                }\n            }).on('error', function(err){\n                if (err.code !== 'ECONNRESET')\n                    log('warn', logSystem, 'Socket error from %s %j', [socket.remoteAddress, err]);\n            }).on('close', function(){\n                pushMessage = function(){};\n            });\n\n        }).listen(portData.port, function (error, result) {\n            if (error) {\n                log('error', logSystem, 'Could not start server listening on port %d, error: $j', [portData.port, error]);\n                cback(true);\n                return;\n            }\n            log('info', logSystem, 'Started server listening on port %d', [portData.port]);\n            cback();\n        });\n\n    }, function(err){\n        if (err)\n            callback(false);\n        else\n            callback(true);\n    });\n}\n\n\n\n\n"
  },
  {
    "path": "lib/utils.js",
    "content": "var base58 = require('base58-native');\nvar cnUtil = require('cryptonote-util');\n\nvar addressBase58Prefix = cnUtil.address_decode(new Buffer(config.poolServer.poolAddress));\n\nexports.uid = function(){\n    var min = 100000000000000;\n    var max = 999999999999999;\n    var id = Math.floor(Math.random() * (max - min + 1)) + min;\n    return id.toString();\n};\n\nexports.ringBuffer = function(maxSize){\n    var data = [];\n    var cursor = 0;\n    var isFull = false;\n\n    return {\n        append: function(x){\n            if (isFull){\n                data[cursor] = x;\n                cursor = (cursor + 1) % maxSize;\n            }\n            else{\n                data.push(x);\n                cursor++;\n                if (data.length === maxSize){\n                    cursor = 0;\n                    isFull = true;\n                }\n            }\n        },\n        avg: function(plusOne){\n            var sum = data.reduce(function(a, b){ return a + b }, plusOne || 0);\n            return sum / ((isFull ? maxSize : cursor) + (plusOne ? 1 : 0));\n        },\n        size: function(){\n            return isFull ? maxSize : cursor;\n        },\n        clear: function(){\n            data = [];\n            cursor = 0;\n            isFull = false;\n        }\n    };\n};\n\nexports.varIntEncode = function(n){\n\n};\n\nexports.isValidAddress = function(addr){\n\n    // config.poolServer.poolAddress\n    //\n\n    return addressBase58Prefix === cnUtil.address_decode(new Buffer(addr));\n\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n    \"name\": \"cryptonote-pool\",\n    \"version\": \"0.0.1\",\n    \"license\": \"GPL-2.0\",\n    \"author\": \"Matthew Little\",\n    \"repository\": {\n        \"type\": \"git\",\n        \"url\": \"https://github.com/zone117x/node-cryptonote-pool.git\"\n    },\n    \"dependencies\": {\n        \"bignum\": \"0.12.5\",\n        \"async\": \"1.5.2\",\n        \"redis\": \"0.12.1\",\n        \"cli-color\": \"1.1.0\",\n        \"dateformat\": \"1.0.12\",\n        \"base58-native\": \"0.1.4\",\n        \"multi-hashing\": \"git://github.com/zone117x/node-multi-hashing.git\",\n        \"cryptonote-util\": \"git://github.com/electroneum/node-cryptonote-util#xmr-Nan-2.0\"\n    },\n    \"engines\": {\n        \"node\": \">=0.10\"\n    }\n}\n"
  },
  {
    "path": "redisBlocksUpgrade.js",
    "content": "\n\n/*\n\nThis script converts the block data in redis from the old format (v0.99.0.6 and earlier) to the new format\nused in v0.99.1+\n\n*/\n\nvar util = require('util');\n\nvar async = require('async');\n\nvar redis = require('redis');\n\nrequire('./lib/configReader.js');\n\nvar apiInterfaces = require('./lib/apiInterfaces.js')(config.daemon, config.wallet);\n\n\nfunction log(severity, system, text, data){\n\n    var formattedMessage = text;\n\n    if (data) {\n        data.unshift(text);\n        formattedMessage = util.format.apply(null, data);\n    }\n\n    console.log(severity + ': ' + formattedMessage);\n}\n\n\nvar logSystem = 'reward script';\n\nvar redisClient = redis.createClient(config.redis.port, config.redis.host);\n\nfunction getTotalShares(height, callback){\n\n    redisClient.hgetall(config.coin + ':shares:round' + height, function(err, workerShares){\n\n        if (err) {\n            callback(err);\n            return;\n        }\n\n        var totalShares = Object.keys(workerShares).reduce(function(p, c){\n            return p + parseInt(workerShares[c])\n        }, 0);\n\n        callback(null, totalShares);\n\n    });\n}\n\n\nasync.series([\n    function(callback){\n        redisClient.smembers(config.coin + ':blocksUnlocked', function(error, result){\n            if (error){\n                log('error', logSystem, 'Error trying to get unlocke blocks from redis %j', [error]);\n                callback();\n                return;\n            }\n            if (result.length === 0){\n                log('info', logSystem, 'No unlocked blocks in redis');\n                callback();\n                return;\n            }\n\n            var blocks = result.map(function(item){\n                var parts = item.split(':');\n                return {\n                    height: parseInt(parts[0]),\n                    difficulty: parts[1],\n                    hash: parts[2],\n                    time: parts[3],\n                    shares: parts[4],\n                    orphaned: 0\n                };\n            });\n\n            async.map(blocks, function(block, mapCback){\n                apiInterfaces.rpcDaemon('getblockheaderbyheight', {height: block.height}, function(error, result){\n                    if (error){\n                        log('error', logSystem, 'Error with getblockheaderbyheight RPC request for block %s - %j', [block.serialized, error]);\n                        mapCback(null, block);\n                        return;\n                    }\n                    if (!result.block_header){\n                        log('error', logSystem, 'Error with getblockheaderbyheight, no details returned for %s - %j', [block.serialized, result]);\n                        mapCback(null, block);\n                        return;\n                    }\n                    var blockHeader = result.block_header;\n                    block.reward = blockHeader.reward;\n                    mapCback(null, block);\n                });\n            }, function(err, blocks){\n\n                if (blocks.length === 0){\n                    log('info', logSystem, 'No unlocked blocks');\n                    callback();\n                    return;\n                }\n\n                var zaddCommands = [config.coin + ':blocks:matured'];\n\n                for (var i = 0; i < blocks.length; i++){\n                    var block = blocks[i];\n                    zaddCommands.push(block.height);\n                    zaddCommands.push([\n                        block.hash,\n                        block.time,\n                        block.difficulty,\n                        block.shares,\n                        block.orphaned,\n                        block.reward\n                    ].join(':'));\n                }\n\n                redisClient.zadd(zaddCommands, function(err, result){\n                    if (err){\n                        console.log('failed zadd ' + JSON.stringify(err));\n                        callback();\n                        return;\n                    }\n                    console.log('successfully converted unlocked blocks to matured blocks');\n                    callback();\n                });\n\n\n            });\n        });\n    },\n    function(callback){\n        redisClient.smembers(config.coin + ':blocksPending', function(error, result) {\n            if (error) {\n                log('error', logSystem, 'Error trying to get pending blocks from redis %j', [error]);\n                callback();\n                return;\n            }\n            if (result.length === 0) {\n                log('info', logSystem, 'No pending blocks in redis');\n                callback();\n                return;\n            }\n\n            async.map(result, function(item, mapCback){\n                var parts = item.split(':');\n                var block = {\n                    height: parseInt(parts[0]),\n                    difficulty: parts[1],\n                    hash: parts[2],\n                    time: parts[3],\n                    serialized: item\n                };\n                getTotalShares(block.height, function(err, shares){\n                    block.shares = shares;\n                    mapCback(null, block);\n                });\n            }, function(err, blocks){\n\n                var zaddCommands = [config.coin + ':blocks:candidates'];\n\n                for (var i = 0; i < blocks.length; i++){\n                    var block = blocks[i];\n                    zaddCommands.push(block.height);\n                    zaddCommands.push([\n                        block.hash,\n                        block.time,\n                        block.difficulty,\n                        block.shares\n                    ].join(':'));\n                }\n\n                redisClient.zadd(zaddCommands, function(err, result){\n                    if (err){\n                        console.log('failed zadd ' + JSON.stringify(err));\n                        return;\n                    }\n                    console.log('successfully converted pending blocks to block candidates');\n                });\n\n            });\n\n        });\n    }\n], function(){\n    process.exit();\n});"
  },
  {
    "path": "website_example/admin_core_stats_massive_stuff.html",
    "content": "<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n    <meta charset=\"UTF-8\">\n    <title></title>\n\n    <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n    <script src=\"//cdnjs.cloudflare.com/ajax/libs/jquery-timeago/1.4.0/jquery.timeago.min.js\"></script>\n\n    <link href=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\" rel=\"stylesheet\">\n    <script src=\"//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js\"></script>\n\n    <link href=\"//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n\n    <style>\n        #statsHolder{\n            margin-bottom: 0;\n        }\n        .luckGood{\n            color: darkgreen;\n        }\n        .luckBad{\n            color: darkred;\n        }\n    </style>\n\n    <script src=\"config.js\"></script>\n\n    <script>\n\n\n        $(function(){\n            getStats();\n        });\n\n\n        var docCookies = {\n            getItem: function (sKey) {\n                return decodeURIComponent(document.cookie.replace(new RegExp(\"(?:(?:^|.*;)\\\\s*\" + encodeURIComponent(sKey).replace(/[\\-\\.\\+\\*]/g, \"\\\\$&\") + \"\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$\"), \"$1\")) || null;\n            },\n            setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {\n                if (!sKey || /^(?:expires|max\\-age|path|domain|secure)$/i.test(sKey)) { return false; }\n                var sExpires = \"\";\n                if (vEnd) {\n                    switch (vEnd.constructor) {\n                        case Number:\n                            sExpires = vEnd === Infinity ? \"; expires=Fri, 31 Dec 9999 23:59:59 GMT\" : \"; max-age=\" + vEnd;\n                            break;\n                        case String:\n                            sExpires = \"; expires=\" + vEnd;\n                            break;\n                        case Date:\n                            sExpires = \"; expires=\" + vEnd.toUTCString();\n                            break;\n                    }\n                }\n                document.cookie = encodeURIComponent(sKey) + \"=\" + encodeURIComponent(sValue) + sExpires + (sDomain ? \"; domain=\" + sDomain : \"\") + (sPath ? \"; path=\" + sPath : \"\") + (bSecure ? \"; secure\" : \"\");\n                return true;\n            },\n            removeItem: function (sKey, sPath, sDomain) {\n                if (!sKey || !this.hasItem(sKey)) { return false; }\n                document.cookie = encodeURIComponent(sKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 GMT\" + ( sDomain ? \"; domain=\" + sDomain : \"\") + ( sPath ? \"; path=\" + sPath : \"\");\n                return true;\n            },\n            hasItem: function (sKey) {\n                return (new RegExp(\"(?:^|;\\\\s*)\" + encodeURIComponent(sKey).replace(/[\\-\\.\\+\\*]/g, \"\\\\$&\") + \"\\\\s*\\\\=\")).test(document.cookie);\n            }\n        };\n\n\n        function getReadableCoins(coins){\n            return (parseInt(coins || 0) / coinUnits).toFixed(coinUnits.toString().length - 1);\n        }\n\n        function getStats(promptPassword){\n\n            var password = docCookies.getItem('password');\n\n\n            if (!password || promptPassword)\n                password = prompt('Enter admin password');\n\n\n            $('#loading').show();\n            $.ajax({\n                url: api + '/admin_stats',\n                data: {password: password},\n                success: function(data){\n                    docCookies.setItem('password', password, Infinity);\n                    $('#loading').hide();\n                    renderData(data);\n                },\n                error: function(e){\n                    docCookies.removeItem('password');\n                    getStats(true);\n                }\n            });\n        }\n\n        var formatLuck = function(difficulty, shares){\n\n            if (difficulty > shares){\n                var percent = 100 - Math.round(shares / difficulty * 100);\n                return '<span class=\"luckGood\">' + percent + '%</span>';\n            }\n            else{\n                var percent = (100 - Math.round(difficulty / shares * 100)) * -1;\n                return '<span class=\"luckBad\">' + percent + '%</span>';\n            }\n\n        };\n\n        function renderData(data){\n            $('#totalOwed').text(getReadableCoins(data.totalOwed));\n            $('#totalPaid').text(getReadableCoins(data.totalPaid));\n            $('#totalMined').text(getReadableCoins(data.totalRevenue));\n            $('#profit').text(getReadableCoins(data.totalRevenue - data.totalOwed - data.totalPaid));\n            $('#averageLuck').html(formatLuck(data.totalDiff, data.totalShares));\n            $('#orphanPercent').text((data.blocksOrphaned / data.blocksUnlocked * 100).toFixed(2));\n            $('#registeredAddresses').text(data.totalWorkers);\n        }\n\n    </script>\n\n</head>\n<body>\n\n<div class=\"container\">\n\n    <h3>Admin Center <i id=\"loading\" class=\"fa fa-circle-o-notch fa-spin\"></i></h3>\n\n    <hr>\n\n    <h4>Stats</h4>\n    <dl class=\"dl-horizontal\" id=\"statsHolder\">\n        <dt>Total Owed</dt><dd id=\"totalOwed\">...</dd>\n        <dt>Total Paid</dt><dd id=\"totalPaid\">...</dd>\n        <dt>Total Mined</dt><dd id=\"totalMined\">...</dd>\n        <dt>Profit (before tx fees)</dt><dd id=\"profit\">...</dd>\n        <dt>Average Luck</dt><dd id=\"averageLuck\">...</dd>\n        <dt>Orphan Percent</dt><dd id=\"orphanPercent\">...</dd>\n        <dt>Registered Addresses</dt><dd id=\"registeredAddresses\">...</dd>\n    </dl>\n    <br>\n\n    <hr>\n\n    <h4>Miner Lookup</h4>\n\n\n</div>\n\n</body>\n</html>"
  },
  {
    "path": "website_example/config.js",
    "content": "var api = \"https://eupool.electroneum.com/api\";\n\nvar coinUnits = 100;\nvar coinDecimalPlaces = 2;\n\nvar poolHost = \"eupool.electroneum.com\";\n\nvar irc = \"irc.freenode.net/#monero-pools\";\n\nvar email = \"support@electroneum.com\";\n\nvar easyminerDownload = \"https://github.com/zone117x/cryptonote-easy-miner/releases/\";\n\nvar blockchainExplorer = \"https://blockexplorer.electroneum.com/block/\";\n\nvar transactionExplorer = \"https://blockexplorer.electroneum.com/tx/\";\n"
  },
  {
    "path": "website_example/custom.css",
    "content": "/* Insert your pool's unique css here */\n.alert-primary {\n\tcolor: #004085;\n\tbackground-color: #cce5ff;\n\tborder-color: #b8daff;\n}\n.alert-warning {\n\tcolor: #856404;\n\tbackground-color: #fff3cd;\n\tborder-color: #ffeeba;\n}\n\n\n\n.btn-primary {\n\tbackground-color: #23bee2;\n\tborder-color: #13acd0;\n}\n.btn-primary:hover {\n\tbackground-color: #13acd0;\n\tborder-color: #13acd0;\n}\n\n.container{\n\tfont-size: 14px!important;\n}\n\n.float-right {\n\tfloat: right;\n}\n\n\n\n/* Custom margins */\n.mb-20 {\n  margin-bottom: 20px !important;\n}\n\n\n\n\n\n.navbar-inverse {\n\tbackground-color: #091b26;\n}\n.navbar-brand {\n\theight: 70px;\n\tpadding: 10px 15px;\n}\n.navbar-brand img {\n\theight: 100%;\n\tdisplay: inline-block;\n}\n.navbar-nav>li>a {\n\tpadding-top: 25px;\n\tpadding-bottom: 25px;\n}\n\n#stats_updated {\n\tline-height: 70px!important;\n}"
  },
  {
    "path": "website_example/custom.js",
    "content": "/* Insert your pool's unique Javascript here */"
  },
  {
    "path": "website_example/index.html",
    "content": "<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n\n\t<meta charset=\"UTF-8\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1\">\n\n\t<title>Electroneum Mining Pool</title>\n\n\n\t<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n\t<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-timeago/1.4.0/jquery.timeago.min.js\"></script>\n\n\t<link href=\"https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css\" rel=\"stylesheet\">\n\t<script src=\"https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js\"></script>\n\n\t<link href=\"https://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n\n\t<link href='https://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>\n\n\t<script src=\"config.js\"></script>\n\t<script src=\"custom.js\"></script>\n\t<link href=\"custom.css\" rel=\"stylesheet\">\n\n\t<style>\n\t\t#coinName{\n\t\t\ttext-transform: capitalize;\n\t\t}\n\t\tbody {\n\t\t\tpadding-top: 90px;\n\t\t\tpadding-bottom: 80px;\n\t\t\toverflow-y: scroll;\n\t\t}\n\t\t.container{\n\t\t\tfont-size: 1.2em;\n\t\t}\n\t\t#loading{\n\t\t\tfont-size: 2em;\n\t\t}\n\t\t.stats {\n\t\t\tmargin-bottom: 10px;\n\t\t\tmargin-top: 5px;\n\t\t}\n\t\t.stats:last-child{\n\t\t\twidth: auto;\n\t\t}\n\t\t.stats > h3 > i{\n\t\t\tfont-size: 0.80em;\n\t\t\twidth: 21px;\n\t\t}\n\t\t.stats > div{\n\t\t\tpadding: 5px 0;\n\t\t}\n\t\t.stats > div > .fa {\n\t\t\twidth: 25px;\n\t\t}\n\t\t.stats > div > span:first-of-type{\n\t\t\tfont-weight: bold;\n\t\t}\n\t\t#stats_updated{\n\t\t\topacity: 0;\n\t\t\tfloat: right;\n\t\t\tmargin-left: 30px;\n\t\t\tcolor: #e8e8e8;\n\t\t\tline-height: 47px;\n\t\t\tfont-size: 0.9em;\n\t\t}\n\n\t\tfooter{\n\t\t\tposition: fixed;\n\t\t\tbottom: 0;\n\t\t\twidth: 100%;\n\t\t\tbackground-color: #f5f5f5;\n\t\t}\n\n\t\tfooter > div{\n\t\t\tmargin: 10px auto;\n\t\t\ttext-align: center;\n\t\t}\n\n\t</style>\n\n</head>\n<body>\n<script>\n\n\n\tvar docCookies = {\n\t\tgetItem: function (sKey) {\n\t\t\treturn decodeURIComponent(document.cookie.replace(new RegExp(\"(?:(?:^|.*;)\\\\s*\" + encodeURIComponent(sKey).replace(/[\\-\\.\\+\\*]/g, \"\\\\$&\") + \"\\\\s*\\\\=\\\\s*([^;]*).*$)|^.*$\"), \"$1\")) || null;\n\t\t},\n\t\tsetItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {\n\t\t\tif (!sKey || /^(?:expires|max\\-age|path|domain|secure)$/i.test(sKey)) { return false; }\n\t\t\tvar sExpires = \"\";\n\t\t\tif (vEnd) {\n\t\t\t\tswitch (vEnd.constructor) {\n\t\t\t\t\tcase Number:\n\t\t\t\t\t\tsExpires = vEnd === Infinity ? \"; expires=Fri, 31 Dec 9999 23:59:59 GMT\" : \"; max-age=\" + vEnd;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase String:\n\t\t\t\t\t\tsExpires = \"; expires=\" + vEnd;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Date:\n\t\t\t\t\t\tsExpires = \"; expires=\" + vEnd.toUTCString();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdocument.cookie = encodeURIComponent(sKey) + \"=\" + encodeURIComponent(sValue) + sExpires + (sDomain ? \"; domain=\" + sDomain : \"\") + (sPath ? \"; path=\" + sPath : \"\") + (bSecure ? \"; secure\" : \"\");\n\t\t\treturn true;\n\t\t},\n\t\tremoveItem: function (sKey, sPath, sDomain) {\n\t\t\tif (!sKey || !this.hasItem(sKey)) { return false; }\n\t\t\tdocument.cookie = encodeURIComponent(sKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 GMT\" + ( sDomain ? \"; domain=\" + sDomain : \"\") + ( sPath ? \"; path=\" + sPath : \"\");\n\t\t\treturn true;\n\t\t},\n\t\thasItem: function (sKey) {\n\t\t\treturn (new RegExp(\"(?:^|;\\\\s*)\" + encodeURIComponent(sKey).replace(/[\\-\\.\\+\\*]/g, \"\\\\$&\") + \"\\\\s*\\\\=\")).test(document.cookie);\n\t\t}\n\t};\n\n\t$.fn.update = function(txt){\n\t\tvar el = this[0];\n\t\tif (el.textContent !== txt)\n\t\t\tel.textContent = txt;\n\t\treturn this;\n\t};\n\n\tfunction updateTextClasses(className, text){\n\t\tvar els = document.getElementsByClassName(className);\n\t\tfor (var i = 0; i < els.length; i++){\n\t\t\tvar el = els[i];\n\t\t\tif (el.textContent !== text)\n\t\t\t\tel.textContent = text;\n\t\t}\n\t}\n\n\tfunction updateText(elementId, text){\n\t\tvar el = document.getElementById(elementId);\n\t\tif (el.textContent !== text){\n\t\t\tel.textContent = text;\n\t\t}\n\t\treturn el;\n\t}\n\n\n\tvar currentPage;\n\tvar lastStats;\n\n\tfunction getReadableCoins(coins, digits, withoutSymbol){\n\t\tvar amount = (parseInt(coins || 0) / coinUnits).toFixed(digits || coinUnits.toString().length - 1);\n\t\treturn amount + (withoutSymbol ? '' : (' ' + lastStats.config.symbol));\n\t}\n\n\tfunction formatDate(time){\n\t\tif (!time) return '';\n\t\treturn new Date(parseInt(time) * 1000).toLocaleString();\n\t}\n\n\tfunction formatPaymentLink(hash){\n\t\treturn '<a target=\"_blank\" href=\"' + transactionExplorer + hash + '\">' + hash + '</a>';\n\t}\n\n\tfunction getPaymentRowElement(payment, jsonString){\n\n\t\tvar row = document.createElement('tr');\n\t\trow.setAttribute('data-json', jsonString);\n\t\trow.setAttribute('data-time', payment.time);\n\t\trow.setAttribute('id', 'paymentRow' + payment.time);\n\n\t\trow.innerHTML = getPaymentCells(payment);\n\n\t\treturn row;\n\t}\n\n\n\tfunction parsePayment(time, serializedPayment){\n\t\tvar parts = serializedPayment.split(':');\n\t\treturn {\n\t\t\ttime: parseInt(time),\n\t\t\thash: parts[0],\n\t\t\tamount: parts[1],\n\t\t\tfee: parts[2],\n\t\t\tmixin: parts[3],\n\t\t\trecipients: parts[4]\n\t\t};\n\t}\n\n\tfunction renderPayments(paymentsResults){\n\n\t\tvar $paymentsRows = $('#payments_rows');\n\n\t\tfor (var i = 0; i < paymentsResults.length; i += 2){\n\n\t\t\tvar payment = parsePayment(paymentsResults[i + 1], paymentsResults[i]);\n\n\t\t\tvar paymentJson = JSON.stringify(payment);\n\n\t\t\tvar existingRow = document.getElementById('paymentRow' + payment.time);\n\n\t\t\tif (existingRow && existingRow.getAttribute('data-json') !== paymentJson){\n\t\t\t\t$(existingRow).replaceWith(getPaymentRowElement(payment, paymentJson));\n\t\t\t}\n\t\t\telse if (!existingRow){\n\n\t\t\t\tvar paymentElement = getPaymentRowElement(payment, paymentJson);\n\n\t\t\t\tvar inserted = false;\n\t\t\t\tvar rows = $paymentsRows.children().get();\n\t\t\t\tfor (var f = 0; f < rows.length; f++) {\n\t\t\t\t\tvar pTime = parseInt(rows[f].getAttribute('data-time'));\n\t\t\t\t\tif (pTime < payment.time){\n\t\t\t\t\t\tinserted = true;\n\t\t\t\t\t\t$(rows[f]).before(paymentElement);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!inserted)\n\t\t\t\t\t$paymentsRows.append(paymentElement);\n\t\t\t}\n\n\t\t}\n\t}\n\n\tfunction pulseLiveUpdate(){\n\t\tvar stats_update = document.getElementById('stats_updated');\n\t\tstats_update.style.transition = 'opacity 100ms ease-out';\n\t\tstats_update.style.opacity = 1;\n\t\tsetTimeout(function(){\n\t\t\tstats_update.style.transition = 'opacity 7000ms linear';\n\t\t\tstats_update.style.opacity = 0;\n\t\t}, 500);\n\t}\n\n\twindow.onhashchange = function(){\n\t\troutePage();\n\t};\n\n\n\tfunction fetchLiveStats() {\n\t\t$.ajax({\n\t\t\turl: api + '/live_stats',\n\t\t\tdataType: 'json',\n\t\t\tcache: 'false'\n\t\t}).done(function(data){\n\t\t\tpulseLiveUpdate();\n\t\t\tlastStats = data;\n\t\t\tupdateIndex();\n\t\t\tcurrentPage.update();\n\t\t}).always(function () {\n\t\t\tfetchLiveStats();\n\t\t});\n\t}\n\n\n\tvar xhrPageLoading;\n\tfunction routePage(loadedCallback) {\n\n\t\tif (currentPage) currentPage.destroy();\n\t\t$('#page').html('');\n\t\t$('#loading').show();\n\n\t\tif (xhrPageLoading)\n\t\t\txhrPageLoading.abort();\n\n\t\t$('.hot_link').parent().removeClass('active');\n\t\tvar $link = $('a.hot_link[href=\"' + (window.location.hash || '#') + '\"]');\n\n\t\t$link.parent().addClass('active');\n\t\tvar page = $link.data('page');\n\n\t\txhrPageLoading = $.ajax({\n\t\t\turl: 'pages/' + page,\n\t\t\tcache: false,\n\t\t\tsuccess: function (data) {\n\t\t\t\t$('#loading').hide();\n\t\t\t\t$('#page').show().html(data);\n\t\t\t\tcurrentPage.update();\n\t\t\t\tif (loadedCallback) loadedCallback();\n\t\t\t}\n\t\t});\n\t}\n\n\tfunction updateIndex(){\n\t\t// updateText('coinName', lastStats.config.coin);\n\t\tupdateText('poolVersion', lastStats.config.version);\n\t}\n\n\t$(function(){\n\t\t$.get(api + '/stats', function(data){\n\t\t\tlastStats = data;\n\t\t\tupdateIndex();\n\t\t\troutePage(fetchLiveStats);\n\t\t});\n\t});\n\n\n</script>\n\n<div class=\"navbar navbar-inverse navbar-fixed-top\" role=\"navigation\">\n\t<div class=\"container\">\n\t\t<div class=\"navbar-header\">\n\t\t\t<button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-collapse\">\n\t\t\t\t<span class=\"sr-only\">Toggle navigation</span>\n\t\t\t\t<span class=\"icon-bar\"></span>\n\t\t\t\t<span class=\"icon-bar\"></span>\n\t\t\t\t<span class=\"icon-bar\"></span>\n\t\t\t</button>\n\t\t\t<a class=\"navbar-brand\">\n\t\t\t\t<img src=\"images/logo.png\">\n\t\t\t\t<!-- <span id=\"coinName\"></span> Mining Pool -->\n\t\t\t</a>\n\t\t</div>\n\t\t<div class=\"collapse navbar-collapse\">\n\t\t\t<ul class=\"nav navbar-nav\">\n\n\t\t\t\t<li class=\"active\"><a class=\"hot_link\" data-page=\"home.html\" href=\"#\">\n\t\t\t\t\t<i class=\"fa fa-home\"></i> Home\n\t\t\t\t</a></li>\n\n\t\t\t\t<li><a class=\"hot_link\" target=\"_blank\" href=\"https://downloads.electroneum.com\">\n\t\t\t\t\t<i class=\"fa fa-download\"></i> Downloads\n\t\t\t\t</a></li>\n\n\t\t\t\t<li><a class=\"hot_link\" data-page=\"pool_blocks.html\" href=\"#pool_blocks\">\n\t\t\t\t\t<i class=\"fa fa-cubes\"></i> Pool Blocks\n\t\t\t\t</a></li>\n\n\t\t\t\t<li><a class=\"hot_link\" data-page=\"payments.html\" href=\"#payments\">\n\t\t\t\t\t<i class=\"fa fa-paper-plane-o\"></i> Payments\n\t\t\t\t</a></li>\n\t\t\t</ul>\n\t\t\t<div id=\"stats_updated\">Stats Updated &nbsp;<i class=\"fa fa-bolt\"></i></div>\n\t\t</div>\n\n\t</div>\n</div>\n\n<div class=\"container\">\n\n\t<div id=\"page\"></div>\n\n\t<p id=\"loading\" class=\"text-center\"><i class=\"fa fa-circle-o-notch fa-spin\"></i></p>\n\n</div>\n\n<footer>\n\t<div class=\"text-muted\">\n\t\tPowered by <a target=\"_blank\" href=\"//github.com/electroneum/electroneum-pool\"><i class=\"fa fa-github\"></i> electroneum-pool</a>\n\t\t<span id=\"poolVersion\"></span>\n\t</div>\n</footer>\n\n\n</body>\n</html>\n"
  },
  {
    "path": "website_example/pages/downloads.html",
    "content": "<style>\n\thr{\n\t\tborder-top-color: #d9d9d9 !important;\n\t\tmargin-top: 40px !important;\n\t\tmargin-bottom: 40px !important;\n\t}\n\t#miningPorts > .stats{\n\t\twidth: auto !important;\n\t\tmargin-right: 70px;\n\t\tmargin-left: 15px;\n\t\tdisplay: inline-block;\n\t}\n\t#miningPorts > .stats:last-child{\n\t\tmargin-right: 0;\n\t}\n\t.getting_started_windows{\n\t\tline-height: 40px;\n\t}\n\t#getting_started_list > li{\n\t\tmargin-bottom: 20px;\n\t}\n\t#mining_apps > tr:first-child > td{\n\t\tpadding-top: 35px;\n\t}\n\t#mining_apps > tr > td{\n\t\tborder-top: none;\n\t}\n\t#mining_apps > tr:nth-child(even) > td{\n\t\tborder-bottom: 1px solid #e5e5e5;\n\t\tpadding-bottom: 20px;\n\t}\n\t#mining_apps > tr:nth-child(odd) > td{\n\t\tpadding-top: 20px;\n\t}\n\t#mining_apps{\n\t\tmargin-top: 10px;\n\t}\n\t.miningAppTitle{\n\t\tfont-weight: bold;\n\t}\n\t.exampleAddress{\n\t\tfont-style: italic;\n\t}\n\t#cpuminer_code{\n\t\tdisplay: inline-block;\n\t\twhite-space: normal;\n\t}\n</style>\n\n<!-- <div class=\"alert alert-warning\" role=\"alert\">\n  Please note that the mining software only works on <span class=\"fa fa-windows\"></span> Windows machines.\n</div> -->\n\n<div class=\"container\">\n\t<div class=\"row\">\n\t\t<div class=\"col-md-6\">\n\t\t\t<h3>Beginner's Pool Mining Software</h3>\n\t\t\t<p>If you are new to crypto mining then this option is the one for you.</p>\n\t\t\t<button type=\"button\" class=\"btn btn-primary\">Download <span class=\"fa fa-windows\"></span> Windows miner</button>\n\t\t</div>\n\t</div>\n</div>\n<!-- <div class=\"yourStats table-responsive\">\n\t<table class=\"table\">\n\t\t<thead>\n\t\t<tr>\n\t\t\t<th><i class=\"fa fa-book\"></i> App Name</th>\n\t\t\t<th><i class=\"fa fa-car\"></i> Architecture</th>\n\t\t\t<th><i class=\"fa fa-download\"></i> Downloads</th>\n\t\t\t<th><i class=\"fa fa-comments\"></i> Discussion</th>\n\t\t\t<th><i class=\"fa fa-file-code-o\"></i> Source Code</th>\n\t\t</tr>\n\t\t</thead>\n\t\t<tbody id=\"mining_apps\">\n\t\t\t<tr>\n\t\t\t\t<td class=\"miningAppTitle\">CPU GUI Miner</td>\n\t\t\t\t<td>CPU</td>\n\t\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=632724\">Download</a></td>\n\t\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=632724\">BitcoinTalk</a></td>\n\t\t\t\t<td><a target=\"_blank\" href=\"https://github.com/wolf9466/cpuminer-multi\">Github</a></td>\n\t\t\t</tr>\n\t\t</tbody>\n\t</table>\n</div> -->\n\n<hr>\n\n\n\n<h3>Advanced Pool Mining Software</h3>\n<p>If you are a crypto mining pro then you'll probably prefer these options.</p>\n<div class=\"yourStats table-responsive\">\n\t<table class=\"table\">\n\t\t<thead>\n\t\t<tr>\n\t\t\t<th><i class=\"fa fa-book\"></i> App Name</th>\n\t\t\t<th><i class=\"fa fa-car\"></i> Architecture</th>\n\t\t\t<th><i class=\"fa fa-download\"></i> Downloads</th>\n\t\t\t<th><i class=\"fa fa-comments\"></i> Discussion</th>\n\t\t\t<th><i class=\"fa fa-file-code-o\"></i> Source Code</th>\n\t\t</tr>\n\t\t</thead>\n\t\t<tbody id=\"mining_apps\">\n\t\t<tr>\n\t\t\t<td class=\"miningAppTitle\">CPUMiner (forked by LucasJones & Wolf)</td>\n\t\t\t<td>CPU</td>\n\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=632724\">BitcoinTalk</a></td>\n\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=632724\">BitcoinTalk</a></td>\n\t\t\t<td><a target=\"_blank\" href=\"https://github.com/wolf9466/cpuminer-multi\">Github</a></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan=\"5\">\n\t\t\t\t<span>Example:</span>\n\t\t\t\t<code>minerd -a cryptonight -o stratum+tcp://<span class=\"exampleHost\"></span>:<span class=\"examplePort\"></span> -u <span class=\"exampleAddress\">YOUR_WALLET_ADDRESS</span> -p x</code>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class=\"miningAppTitle\">YAM Miner (by yvg1900)</td>\n\t\t\t<td>CPU</td>\n\t\t\t<td><a target=\"_blank\" href=\"https://mega.co.nz/#F!UlkU0RyR!E8n4CFkqVu0WoOnsJnQkSg\">MEGA</a></td>\n\t\t\t<td><a target=\"_blank\" href=\"https://twitter.com/yvg1900\">Twitter</a></td>\n\t\t\t<td>Proprietary <i class=\"fa fa-frown-o\"></i></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan=\"5\">\n\t\t\t\t<span>Example:</span>\n\t\t\t\t<code>yam -c x -M stratum+tcp://<span class=\"exampleAddress\">YOUR_WALLET_ADDRESS</span>:x@<span class=\"exampleHost\"></span>:<span class=\"examplePort\"></span>/xmr</code>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class=\"miningAppTitle\">Claymore CPU Miner</td>\n\t\t\t<td>CPU</td>\n\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=647251.0\">BitcoinTalk</a></td>\n\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=647251.0\">BitcoinTalk</a></td>\n\t\t\t<td>Proprietary <i class=\"fa fa-frown-o\"></i></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan=\"5\">\n\t\t\t\t<span>Example:</span>\n\t\t\t\t<code>NsCpuCNMiner64 -o stratum+tcp://<span class=\"exampleHost\"></span>:<span class=\"examplePort\"></span> -u <span class=\"exampleAddress\">YOUR_WALLET_ADDRESS</span> -p x</code>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class=\"miningAppTitle\">Claymore GPU Miner</td>\n\t\t\t<td>OpenCL (AMD)</td>\n\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=638915.0\">BitcoinTalk</a></td>\n\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=638915.0\">Discussion</a></td>\n\t\t\t<td>Proprietary <i class=\"fa fa-frown-o\"></i></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan=\"5\">\n\t\t\t\t<span>Example:</span>\n\t\t\t\t<code>NsGpuCNMiner -o stratum+tcp://<span class=\"exampleHost\"></span>:<span class=\"examplePort\"></span> -u <span class=\"exampleAddress\">YOUR_WALLET_ADDRESS</span> -p x</code>\n\t\t\t</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td class=\"miningAppTitle\">ccminer (forked by tsiv)</td>\n\t\t\t<td>CUDA (Nvidia)</td>\n\t\t\t<td><a target=\"_blank\" href=\"https://github.com/tsiv/ccminer-cryptonight/releases\">Github</a></td>\n\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=656841.msg7487737#msg7487737\">BitcoinTalk</a></td>\n\t\t\t<td><a target=\"_blank\" href=\"https://github.com/tsiv/ccminer-cryptonight\">Github</a></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td colspan=\"5\">\n\t\t\t\t<span>Example:</span>\n\t\t\t\t<code>ccminer -o stratum+tcp://<span class=\"exampleHost\"></span>:<span class=\"examplePort\"></span> -u <span class=\"exampleAddress\">YOUR_WALLET_ADDRESS</span> -p x</code>\n\t\t\t</td>\n\t\t</tr>\n\t\t</tbody>\n\t</table>\n</div>\n\n\n<h3>Mining Pool Connection Details</h3>\n<div class=\"stats\">\n\t<div><i class=\"fa fa-cloud\"></i> Mining Pool Address: <span id=\"miningPoolHost\"></span></div>\n</div>\n\n<h4>Mining Ports</h4>\n<div id=\"miningPorts\" class=\"row\">\n\t<div class=\"stats\">\n\t\t<div><i class=\"fa fa-tachometer\"></i> Port: <span class=\"miningPort\"></span></div>\n\t\t<div><i class=\"fa fa-unlock-alt\"></i> Starting Difficulty: <span class=\"miningPortDiff\"></span></div>\n\t\t<div><i class=\"fa fa-question\"></i> Description: <span class=\"miningPortDesc\"></span></div>\n\t</div>\n</div>\n\n<hr>\n\n<!-- <h3>For <i class=\"fa fa-windows\"></i> Windows users new to mining</h3>\n<p class=\"getting_started_windows\">\n\tYou can <a class=\"btn btn-default btn-sm\" target=\"_blank\" id=\"easyminer_link\"><i class=\"fa fa-download\"></i> Download</a>\n\tand run <a target=\"_blank\" href=\"https://github.com/zone117x/cryptonote-easy-miner\">cryptonote-easy-miner</a> <i class=\"fa fa-github\"></i>\n\twhich will automatically generate your wallet address and run CPUMiner with the proper parameters.\n</p>\n\n<hr> -->\n\n<h3>Direct mining software</h3>\n<div class=\"yourStats table-responsive\">\n\t<table class=\"table\">\n\t\t<thead>\n\t\t<tr>\n\t\t\t<th><i class=\"fa fa-book\"></i> App Name</th>\n\t\t\t<th><i class=\"fa fa-car\"></i> Architecture</th>\n\t\t\t<th><i class=\"fa fa-download\"></i> Downloads</th>\n\t\t\t<th><i class=\"fa fa-comments\"></i> Discussion</th>\n\t\t\t<th><i class=\"fa fa-file-code-o\"></i> Source Code</th>\n\t\t</tr>\n\t\t</thead>\n\t\t<tbody id=\"mining_apps\">\n\t\t\t<tr>\n\t\t\t\t<td class=\"miningAppTitle\">Direct</td>\n\t\t\t\t<td>CPU</td>\n\t\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=632724\">Download</a></td>\n\t\t\t\t<td><a target=\"_blank\" href=\"https://bitcointalk.org/index.php?topic=632724\">BitcoinTalk</a></td>\n\t\t\t\t<td><a target=\"_blank\" href=\"https://github.com/wolf9466/cpuminer-multi\">Github</a></td>\n\t\t\t</tr>\n\t\t</tbody>\n\t</table>\n</div>\n\n\n<hr>\n\n\n<script>\n\n\tcurrentPage = {\n\t\tdestroy: function(){\n\n\t\t},\n\t\tupdate: function(){\n\n\t\t\tvar portsJson = JSON.stringify(lastStats.config.ports);\n\t\t\tif (lastPortsJson !== portsJson) {\n\t\t\t\tlastPortsJson = portsJson;\n\t\t\t\tvar $miningPortChildren = [];\n\t\t\t\tfor (var i = 0; i < lastStats.config.ports.length; i++) {\n\t\t\t\t\tvar portData = lastStats.config.ports[i];\n\t\t\t\t\tvar $portChild = $(miningPortTemplate);\n\t\t\t\t\t$portChild.find('.miningPort').text(portData.port);\n\t\t\t\t\t$portChild.find('.miningPortDiff').text(portData.difficulty);\n\t\t\t\t\t$portChild.find('.miningPortDesc').text(portData.desc);\n\t\t\t\t\t$miningPortChildren.push($portChild);\n\t\t\t\t}\n\t\t\t\t$miningPorts.empty().append($miningPortChildren);\n\t\t\t}\n\n\t\t\tupdateTextClasses('exampleHost', poolHost);\n\t\t\tupdateTextClasses('examplePort', lastStats.config.ports[0].port.toString());\n\n\t\t}\n\t};\n\n\t// document.getElementById('easyminer_link').setAttribute('href', easyminerDownload);\n\tdocument.getElementById('miningPoolHost').textContent = poolHost;\n\n\tvar lastPortsJson = '';\n\tvar $miningPorts = $('#miningPorts');\n\tvar miningPortTemplate = $miningPorts.html();\n\t$miningPorts.empty();\n\n</script>"
  },
  {
    "path": "website_example/pages/home.html",
    "content": "<style>\n\t.marketFooter{\n\t\tfont-size: 10px;\n\t\topacity: 0.6;\n\t}\n\t#networkLastReward{\n\t\ttext-transform: uppercase;\n\t}\n\t#lastHash{\n\t\tfont-family: 'Inconsolata', monospace;\n\t\tfont-size: 0.8em;\n\t}\n\t#poolDonations{\n\t\tfont-size: 0.75em;\n\t}\n\t#miningProfitCalc{\n\t\tmargin: 35px 0;\n\t}\n\t#calcHashDropdown{\n\t\tborder-radius: 0;\n\t\tborder-left: 0;\n\t\tborder-right: 0;\n\t}\n\t#calcHashHolder{\n\t\twidth: 590px;\n\t\tmax-width: 100%;\n\t}\n\t#calcHashRate{\n\t\tz-index: inherit;\n\t\tfont-family: 'Inconsolata', monospace;\n\t}\n\t#calcHashAmount{\n\t\tfont-family: 'Inconsolata', monospace;\n\t}\n\t#calcHashResultsHolder{\n\t\tmin-width: 145px;\n\t\tmax-width: 145px;\n\t\twhite-space: nowrap;\n\t\toverflow: hidden;\n\t\ttext-overflow: ellipsis;\n\t}\n\t#yourStatsInput{\n\t\tz-index: inherit;\n\t\tfont-family: 'Inconsolata', monospace;\n\t}\n\t#yourAddressDisplay > span {\n\t\tfont-family: 'Inconsolata', monospace;\n\t}\n\t#lookUp > span:nth-child(2){\n\t\tdisplay: none;\n\t}\n\t.yourStats{\n\t\tdisplay: none;\n\t}\n\t#yourAddressDisplay{\n\t\tdisplay: inline-block;\n\t\tmax-width: 100%;\n\t\toverflow: hidden;\n\t\ttext-overflow: ellipsis;\n\t\tvertical-align: middle;\n\t\tfont-family: 'Inconsolata', monospace;\n\t\tfont-size: 0.9em;\n\t}\n\t#addressError{\n\t\tcolor: red;\n\t}\n\n\n\t#payments_rows > tr > td{\n\t\tvertical-align: middle;\n\t\tfont-family: 'Inconsolata', monospace;\n\t\tfont-size: 0.95em;\n\t\ttext-align: center;\n\t}\n\t#payments_rows > tr > td:nth-child(2){\n\t\ttext-align: left;\n\t}\n\n</style>\n\n\n<div id=\"siteInfo\">\n\t<!-- Description or information about this pool -->\n\t<div class=\"container\">\n\t\t<div class=\"row mb-20\">\n\t\t\t<h1 class=\"mb-20\">Getting started</h1>\n\t\t\t<div class=\"col-md-4\">\n\t\t\t\t<p><small class=\"text-muted\">Step 1</small></p>\n\t\t\t\t<h4>Download a miner</h4>\n\t\t\t\t<p>First of all you'll need to download a mining program in order to allow your computer to mine Electroneum.</p>\n\t\t\t\t<a href=\"https://downloads.electroneum.com/\" target=\"_blank\" class=\"btn btn-primary\">View downloads</a>\n\t\t\t</div>\n\t\t\t<div class=\"col-md-4\">\n\t\t\t\t<p><small class=\"text-muted\">Step 2</small></p>\n\t\t\t\t<h4>Connect to a mining pool</h4>\n\t\t\t\t<p>Once you've chosen a miner you need to connect it to this mining pool.</p>\n\t\t\t\t<a href=\"https://downloads.electroneum.com/\" target=\"_blank\" class=\"btn btn-primary\">View instructions</a>\n\t\t\t</div>\n\t\t\t<div class=\"col-md-4\">\n\t\t\t\t<p><small class=\"text-muted\">Step 3</small></p>\n\t\t\t\t<h4>Earn Electroneum</h4>\n\t\t\t\t<p>After you've connected to the mining pool simply sit back and watch the Electroneum getting mined.</p>\n\t\t\t\t<a href=\"https://downloads.electroneum.com/\" target=\"_blank\" class=\"btn btn-primary\">Advanced options</a>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n</div>\n\n<hr>\n\n<div class=\"modal fade\" id=\"exampleModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"exampleModalLabel\" aria-hidden=\"true\">\n\t<div class=\"modal-dialog\" role=\"document\">\n\t\t<div class=\"modal-content\">\n\t\t\t<div class=\"modal-header\">\n\t\t\t\t<h5 class=\"modal-title\" id=\"exampleModalLabel\">What is a mining pool?\n\t\t\t\t\t<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n\t\t\t\t\t  <span aria-hidden=\"true\">&times;</span>\n\t\t\t\t\t</button>\n\t\t\t\t</h5>\n\t\t\t</div>\n\t\t\t<div class=\"modal-body\">\n\t\t\t\t<p>A mining pool is a way of being able to mine cryptocurrency quicker by multiple miners working together rather than individually.</p>\n\n\t\t\t\t<p>Normally you would mine cyrptocurrency from your own machine and it might take a while before you receive any currency as it might take a while before the calculations required to mine a block are completed. What the mining pool does is distribute the processing power needed to mine each block. This means that blocks can be mined quicker and the appropriate amount of currency is allocated depending on how much work your machine has put in.</p>\n\t\t\t</div>\n\t\t\t<div class=\"modal-footer\">\n\t\t\t<!-- <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Close</button> -->\n\t\t\t\t<button type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\">Close</button>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n</div>\n\n<div class=\"row\">\n\t<h1 class=\"mb-20\">Mining Pool stats <button type=\"button\" class=\"btn btn-secondary btn-sm float-right\" data-toggle=\"modal\" data-target=\"#exampleModal\">What is a mining pool?</button></h1>\n\t<div class=\"col-md-4 stats\">\n\t\t<h3>This Pool</h3>\n\t\t<div><i class=\"fa fa-tachometer\"></i> Hash Rate: <span id=\"poolHashrate\"></span></div>\n\t\t<div><i class=\"fa fa-clock-o\"></i> Block Found: <span id=\"poolLastBlockFound\"></span></div>\n\t\t<div><i class=\"fa fa-users\"></i> Connected Miners: <span id=\"poolMiners\"></span></div>\n\t\t<div><i class=\"fa fa-gift\"></i> Donations: <span id=\"poolDonations\"></span></div>\n\t\t<div><i class=\"fa fa-money\"></i> Total Pool Fee: <span id=\"poolFee\"></span></div>\n\t\t<div><i class=\"fa fa-history\"></i> Block Found Every: <span id=\"blockSolvedTime\"></span> (est.)</div>\n\t</div>\n\n\t<div class=\"col-md-4 stats\">\n\t\t<h3>Electroneum Pool Network</h3>\n\t\t<div><i class=\"fa fa-tachometer\"></i> Hash Rate: <span id=\"networkHashrate\"></span></div>\n\t\t<div><i class=\"fa fa-clock-o\"></i> Block Found: <span id=\"networkLastBlockFound\"></span></div>\n\t\t<div><i class=\"fa fa-unlock-alt\"></i> Difficulty: <span id=\"networkDifficulty\"></span></div>\n\t\t<div><i class=\"fa fa-bars\"></i> Blockchain Height: <span id=\"blockchainHeight\"></span></div>\n\t\t<div><i class=\"fa fa-money\"></i> Last Reward: <span id=\"networkLastReward\"></span></div>\n\t\t<div><i class=\"fa fa-paw\"></i> Last Hash: <a id=\"lastHash\" target=\"_blank\"></a></div>\n\t</div>\n</div>\n\n<hr>\n\n<!--<div id=\"miningProfitCalc\">\n\t<h3>Estimate Mining Profits</h3>\n\t<div id=\"calcHashHolder\">\n\t\t<div class=\"input-group\">\n\t\t\t<input type=\"number\" class=\"form-control\" id=\"calcHashRate\" placeholder=\"Enter Your Hash Rate\">\n\t\t\t<div class=\"input-group-btn\">\n\t\t\t\t<button type=\"button\" class=\"btn btn-default dropdown-toggle\" data-toggle=\"dropdown\" id=\"calcHashDropdown\">\n\t\t\t\t\t<span id=\"calcHashUnit\" data-mul=\"1\">KH/s</span> <span class=\"caret\"></span>\n\t\t\t\t</button>\n\t\t\t\t<ul class=\"dropdown-menu dropdown-menu-right\" role=\"menu\" id=\"calcHashUnits\">\n\t\t\t\t\t<li><a href=\"#\" data-mul=\"0\">H/s</a></li>\n\t\t\t\t\t<li><a href=\"#\" data-mul=\"1\">KH/s</a></li>\n\t\t\t\t\t<li><a href=\"#\" data-mul=\"2\">MH/s</a></li>\n\t\t\t\t</ul>\n\t\t\t</div>\n\t\t\t<span class=\"input-group-addon\">=</span>\n\t\t\t<span class=\"input-group-addon\" id=\"calcHashResultsHolder\"><span id=\"calcHashAmount\"></span> <span id=\"calcHashSymbol\"></span>/day</span>\n\t\t</div>\n\t</div>\n</div>\n\n<hr>-->\n\n<div class=\"row\">\n\t<h1 class=\"mb-20\">Your Stats & Payment History</h1>\n\t<div class=\"stats\">\n\n\t\t<div class=\"input-group\">\n\t\t\t<input class=\"form-control\" id=\"yourStatsInput\" type=\"text\" placeholder=\"Enter Your Wallet Address\">\n\t\t\t<span class=\"input-group-btn\"><button class=\"btn btn-default\" type=\"button\" id=\"lookUp\">\n\t\t\t\t<span><i class=\"fa fa-search\"></i> Lookup</span>\n\t\t\t\t<span><i class=\"fa fa-refresh fa-spin\"></i> Searching...</span>\n\t\t\t</button></span>\n\t\t</div>\n\n\t\t<div id=\"addressError\"></div>\n\t\t<div class=\"yourStats\"><i class=\"fa fa-key\"></i> Wallet Address: <span id=\"yourAddressDisplay\"></span></div>\n\t\t<div class=\"yourStats\"><i class=\"fa fa-bank\"></i> Pending Balance: <span id=\"yourPendingBalance\"></span></div>\n\t\t<div class=\"yourStats\"><i class=\"fa fa-money\"></i> Total Paid: <span id=\"yourPaid\"></span></div>\n\t\t<div class=\"yourStats\"><i class=\"fa fa-clock-o\"></i> Last Share Submitted: <span id=\"yourLastShare\"></span></div>\n\t\t<div class=\"yourStats\"><i class=\"fa fa-tachometer\"></i> Hash Rate: <span id=\"yourHashrateHolder\"></span></div>\n\t\t<div class=\"yourStats\"><i class=\"fa fa-cloud-upload\"></i> Total Hashes Submitted: <span id=\"yourHashes\"></span></div>\n\n\t\t<br class=\"yourStats\">\n\n\t\t<h4 class=\"yourStats\">Payments</h4>\n\t\t<div class=\"yourStats table-responsive\">\n\t\t\t<table class=\"table table-striped\">\n\t\t\t\t<thead>\n\t\t\t\t<tr>\n\t\t\t\t\t<th><i class=\"fa fa-clock-o\"></i> Time Sent</th>\n\t\t\t\t\t<th><i class=\"fa fa-paw\"></i> Transaction Hash</th>\n\t\t\t\t\t<th><i class=\"fa fa-money\"></i> Amount</th>\n\t\t\t\t\t<th><i class=\"fa fa-sitemap\"></i> Mixin</th>\n\t\t\t\t</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody id=\"payments_rows\">\n\n\t\t\t\t</tbody>\n\t\t\t</table>\n\t\t</div>\n\t\t<p class=\"yourStats text-center\">\n\t\t\t<button type=\"button\" class=\"btn btn-default\" id=\"loadMorePayments\">Load More</button>\n\t\t</p>\n\n\t</div>\n</div>\n\n<script>\n\n\n\tcurrentPage = {\n\t\tdestroy: function(){\n\t\t\t$('#networkLastBlockFound,#poolLastBlockFound,#yourLastShare,#marketLastUpdated').timeago('dispose');\n\t\t\tif (xhrAddressPoll) xhrAddressPoll.abort();\n\t\t\tif (addressTimeout) clearTimeout(addressTimeout);\n\t\t\tif (xhrGetPayments) xhrGetPayments.abort();\n\t\t},\n\t\tupdate: function(){\n\n\t\t\t$('#networkLastBlockFound').timeago('update', new Date(lastStats.network.timestamp * 1000).toISOString());\n\n\t\t\tupdateText('networkHashrate', getReadableHashRateString(lastStats.network.difficulty / 120) + '/sec');\n\t\t\tupdateText('networkDifficulty', lastStats.network.difficulty.toString());\n\t\t\tupdateText('blockchainHeight', lastStats.network.height.toString());\n\t\t\tupdateText('networkLastReward', getReadableCoins(lastStats.network.reward, coinDecimalPlaces));\n\t\t\tupdateText('lastHash', lastStats.network.hash.substr(0, 13) + '...').setAttribute('href',\n\t\t\t\tblockchainExplorer + lastStats.network.hash\n\t\t\t);\n\n\t\t\tupdateText('poolHashrate', getReadableHashRateString(lastStats.pool.hashrate) + '/sec');\n\n\t\t\tif (lastStats.pool.lastBlockFound){\n\t\t\t\tvar d = new Date(parseInt(lastStats.pool.lastBlockFound)).toISOString();\n\t\t\t\t$('#poolLastBlockFound').timeago('update', d);\n\t\t\t}\n\t\t\telse\n\t\t\t\t$('#poolLastBlockFound').removeAttr('title').data('ts', '').update('Never');\n\n\t\t\t//updateText('poolRoundHashes', lastStats.pool.roundHashes.toString());\n\t\t\tupdateText('poolMiners', lastStats.pool.miners.toString());\n\n\n\t\t\tvar totalFee = lastStats.config.fee;\n\t\t\tif (lastStats.config.doDonations){\n\t\t\t\ttotalFee += lastStats.config.donation;\n\t\t\t\ttotalFee += lastStats.config.coreDonation;\n\t\t\t\tvar feeText = [];\n\t\t\t\tif (lastStats.config.donation > 0) feeText.push(lastStats.config.donation + '% to pool dev');\n\t\t\t\tif (lastStats.config.coreDonation > 0) feeText.push(lastStats.config.coreDonation + '% to core devs');\n\t\t\t\tupdateText('poolDonations', feeText.join(', '));\n\t\t\t}\n\t\t\telse{\n\t\t\t\tupdateText('poolDonations', '');\n\t\t\t}\n\n\t\t\tupdateText('poolFee', totalFee + '%');\n\n\n\t\t\tupdateText('blockSolvedTime', getReadableTime(lastStats.network.difficulty / lastStats.pool.hashrate));\n\t\t\t// updateText('calcHashSymbol', lastStats.config.symbol);\n\n\t\t\t// calcEstimateProfit();\n\t\t}\n\t};\n\n\n\t$('#networkLastBlockFound,#poolLastBlockFound,#yourLastShare,#marketLastUpdated').timeago();\n\n\n\tfunction getReadableTime(seconds){\n\n\t\tvar units = [ [60, 'second'], [60, 'minute'], [24, 'hour'],\n\t\t\t[7, 'day'], [4, 'week'], [12, 'month'], [1, 'year'] ];\n\n\t\tfunction formatAmounts(amount, unit){\n\t\t\tvar rounded = Math.round(amount);\n\t\t\treturn '' + rounded + ' ' + unit + (rounded > 1 ? 's' : '');\n\t\t}\n\n\t\tvar amount = seconds;\n\t\tfor (var i = 0; i < units.length; i++){\n\t\t\tif (amount < units[i][0])\n\t\t\t\treturn formatAmounts(amount, units[i][1]);\n\t\t\tamount = amount / units[i][0];\n\t\t}\n\t\treturn formatAmounts(amount,  units[units.length - 1][1]);\n\t}\n\n\tfunction getReadableHashRateString(hashrate){\n\t\tvar i = 0;\n\t\tvar byteUnits = [' H', ' KH', ' MH', ' GH', ' TH', ' PH' ];\n\t\twhile (hashrate > 1000){\n\t\t\thashrate = hashrate / 1000;\n\t\t\ti++;\n\t\t}\n\t\treturn hashrate.toFixed(2) + byteUnits[i];\n\t}\n\n\n\t/* Hash Profitability Calculator */\n\n\t/*$('#calcHashRate').keyup(calcEstimateProfit).change(calcEstimateProfit);\n\n\t$('#calcHashUnits > li > a').click(function(e){\n\t\te.preventDefault();\n\t\t$('#calcHashUnit').text($(this).text()).data('mul', $(this).data('mul'));\n\t\tcalcEstimateProfit();\n\t});\n\n\tfunction calcEstimateProfit(){\n\t\ttry {\n\t\t\tvar rateUnit = Math.pow(1000,parseInt($('#calcHashUnit').data('mul')));\n\t\t\tvar inp2 = parseFloat($('#calcHashRate').val()) * rateUnit;\n\t\t\tvar resl = ( lastStats.network.reward / coinUnits) / ((lastStats.network.difficulty / inp2) / 86400  );\n\t\t\tif (!isNaN(resl)) {\n\t\t\t\tupdateText('calcHashAmount', (Math.round(resl * 100) / 100).toString());\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcatch(e){ }\n\t\tupdateText('calcHashAmount', '');\n\t}*/\n\n\n\n\n\n\t/* Stats by mining address lookup */\n\n\tfunction getPaymentCells(payment){\n\t\treturn '<td>' + formatDate(payment.time) + '</td>' +\n\t\t\t\t'<td>' + formatPaymentLink(payment.hash) + '</td>' +\n\t\t\t\t'<td>' + getReadableCoins(payment.amount, coinDecimalPlaces, true) + '</td>' +\n\t\t\t\t'<td>' + payment.mixin + '</td>';\n\t}\n\n\tvar xhrAddressPoll;\n\tvar addressTimeout;\n\n\t$('#lookUp').click(function(){\n\n\t\tvar address = $('#yourStatsInput').val().trim();\n\t\tif (!address){\n\t\t\t$('#yourStatsInput').focus();\n\t\t\treturn;\n\t\t}\n\n\t\t$('#addressError').hide();\n\t\t$('.yourStats').hide();\n\t\t$('#payments_rows').empty();\n\n\t\t$('#lookUp > span:first-child').hide();\n\t\t$('#lookUp > span:last-child').show();\n\n\n\t\tif (xhrAddressPoll) xhrAddressPoll.abort();\n\t\tif (addressTimeout) clearTimeout(addressTimeout);\n\n\t\tfunction fetchAddressStats(longpoll){\n\t\t\txhrAddressPoll = $.ajax({\n\t\t\t\turl: api + '/stats_address',\n\t\t\t\tdata: {\n\t\t\t\t\taddress: address,\n\t\t\t\t\tlongpoll: longpoll\n\t\t\t\t},\n\t\t\t\tdataType: 'json',\n\t\t\t\tcache: 'false',\n\t\t\t\tsuccess: function(data){\n\n\t\t\t\t\t$('#lookUp > span:last-child').hide();\n\t\t\t\t\t$('#lookUp > span:first-child').show();\n\n\t\t\t\t\tif (!data.stats){\n\t\t\t\t\t\t$('.yourStats').hide();\n\t\t\t\t\t\t$('#addressError').text(data.error).show();\n\n\t\t\t\t\t\tif (addressTimeout) clearTimeout(addressTimeout);\n\t\t\t\t\t\taddressTimeout = setTimeout(function(){\n\t\t\t\t\t\t\tfetchAddressStats(false);\n\t\t\t\t\t\t}, 2000);\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\n\t\t\t\t\t$('#addressError').hide();\n\t\t\t\t\tupdateText('yourAddressDisplay', address);\n\n\t\t\t\t\tif (data.stats.lastShare)\n\t\t\t\t\t\t$('#yourLastShare').timeago('update', new Date(parseInt(data.stats.lastShare) * 1000).toISOString());\n\t\t\t\t\telse\n\t\t\t\t\t\tupdateText('yourLastShare', 'Never');\n\n\t\t\t\t\tupdateText('yourHashrateHolder', (data.stats.hashrate || '0 H') + '/sec');\n\t\t\t\t\tupdateText('yourHashes', (data.stats.hashes || 0).toString());\n\t\t\t\t\tupdateText('yourPaid', getReadableCoins(data.stats.paid));\n\t\t\t\t\tupdateText('yourPendingBalance', getReadableCoins(data.stats.balance));\n\n\t\t\t\t\trenderPayments(data.payments);\n\n\t\t\t\t\t$('.yourStats').show();\n\n\t\t\t\t\tdocCookies.setItem('mining_address', address, Infinity);\n\n\t\t\t\t\tfetchAddressStats(true);\n\n\t\t\t\t},\n\t\t\t\terror: function(e){\n\t\t\t\t\tif (e.statusText === 'abort') return;\n\t\t\t\t\t$('#lookUp').html(lookupBtnHtml);\n\t\t\t\t\t$('#addressError').text('Connection error').show();\n\n\t\t\t\t\tif (addressTimeout) clearTimeout(addressTimeout);\n\t\t\t\t\taddressTimeout = setTimeout(function(){\n\t\t\t\t\t\tfetchAddressStats(false);\n\t\t\t\t\t}, 2000);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tfetchAddressStats(false);\n\t});\n\n\tvar address = docCookies.getItem('mining_address');\n\n\tif (address){\n\t\t$('#yourStatsInput').val(address);\n\t\t$('#lookUp').click();\n\t}\n\n\t$('#yourStatsInput').keyup(function(e){\n\t\tif(e.keyCode === 13)\n\t\t\t$('#lookUp').click();\n\t});\n\n\tvar xhrGetPayments;\n\t$('#loadMorePayments').click(function(){\n\t\tif (xhrGetPayments) xhrGetPayments.abort();\n\t\txhrGetPayments = $.ajax({\n\t\t\turl: api + '/get_payments',\n\t\t\tdata: {\n\t\t\t\ttime: $('#payments_rows').children().last().data('time'),\n\t\t\t\taddress: address\n\t\t\t},\n\t\t\tdataType: 'json',\n\t\t\tcache: 'false',\n\t\t\tsuccess: function(data){\n\t\t\t\trenderPayments(data);\n\t\t\t}\n\t\t});\n\t});\n\n</script>\n"
  },
  {
    "path": "website_example/pages/payments.html",
    "content": "<style>\n    .paymentsStatHolder > span{\n        display: inline-block;\n        border-radius: 5px;\n        padding: 1px 9px;\n        border: 1px solid #e5e5e5;\n        margin: 2px;\n    }\n    .paymentsStatHolder > span > span{\n        font-weight: bold;\n    }\n    #payments_rows > tr > td{\n        vertical-align: middle;\n        font-family: 'Inconsolata', monospace;\n        font-size: 0.95em;\n        text-align: center;\n    }\n</style>\n\n<div class=\"paymentsStatHolder\">\n    <span class=\"bg-primary\">Total Payments: <span id=\"paymentsTotal\"></span></span>\n    <span class=\"bg-info\">Total Miners Paid: <span id=\"paymentsTotalPaid\"></span></span>\n    <span class=\"bg-info\">Minimum Payment Threshold: <span id=\"paymentsMinimum\"></span></span>\n    <span class=\"bg-info\">Denomination Unit: <span id=\"paymentsDenomination\"></span></span>\n</div>\n\n<hr>\n\n<div class=\"table-responsive\">\n    <table class=\"table table-hover table-striped\">\n        <thead>\n        <tr>\n            <th><i class=\"fa fa-clock-o\"></i> Time Sent</th>\n            <th><i class=\"fa fa-paw\"></i> Transaction Hash</th>\n            <th><i class=\"fa fa-money\"></i> Amount</th>\n            <th><i class=\"fa fa-tag\"></i> Fee</th>\n            <th><i class=\"fa fa-sitemap\"></i> Mixin</th>\n            <th><i class=\"fa fa-group\"></i> Payees</th>\n        </tr>\n        </thead>\n        <tbody id=\"payments_rows\">\n\n        </tbody>\n    </table>\n</div>\n\n<p class=\"text-center\">\n    <button type=\"button\" class=\"btn btn-default\" id=\"loadMorePayments\">Load More</button>\n</p>\n\n\n<script>\n    currentPage = {\n        destroy: function(){\n            if (xhrGetPayments) xhrGetPayments.abort();\n        },\n        update: function(){\n            updateText('paymentsTotal', lastStats.pool.totalPayments.toString());\n            updateText('paymentsTotalPaid', lastStats.pool.totalMinersPaid.toString());\n            updateText('paymentsMinimum', getReadableCoins(lastStats.config.minPaymentThreshold, coinDecimalPlaces));\n            updateText('paymentsDenomination', getReadableCoins(lastStats.config.denominationUnit, coinDecimalPlaces));\n            renderPayments(lastStats.pool.payments);\n        }\n    };\n\n\n    var xhrGetPayments;\n    $('#loadMorePayments').click(function(){\n        if (xhrGetPayments) xhrGetPayments.abort();\n        xhrGetPayments = $.ajax({\n            url: api + '/get_payments',\n            data: {\n                time: $('#payments_rows').children().last().data('time')\n            },\n            dataType: 'json',\n            cache: 'false',\n            success: function(data){\n                renderPayments(data);\n            }\n        });\n    });\n\n\n    function getPaymentCells(payment){\n        return '<td>' + formatDate(payment.time) + '</td>' +\n                '<td>' + formatPaymentLink(payment.hash) + '</td>' +\n                '<td>' + getReadableCoins(payment.amount, coinDecimalPlaces, true) + '</td>' +\n                '<td>' + getReadableCoins(payment.fee, coinDecimalPlaces, true) + '</td>' +\n                '<td>' + payment.mixin + '</td>' +\n                '<td>' + payment.recipients + '</td>';\n    }\n\n</script>\n"
  },
  {
    "path": "website_example/pages/pool_blocks.html",
    "content": "<style>\n    .blocksStatHolder > span{\n        display: inline-block;\n        border-radius: 5px;\n        padding: 1px 9px;\n        border: 1px solid #e5e5e5;\n        margin: 2px;\n    }\n    .blocksStatHolder > span > span{\n        font-weight: bold;\n    }\n    #blocks_rows > tr > td{\n        vertical-align: middle;\n        font-family: 'Inconsolata', monospace;\n        font-size: 0.95em;\n        text-align: center;\n    }\n    .luckGood{\n        color: darkgreen;\n    }\n    .luckBad{\n        color: darkred;\n    }\n</style>\n\n<div class=\"blocksStatHolder\">\n    <span class=\"bg-primary\">Total Blocks Mined: <span id=\"blocksTotal\"></span></span>\n    <span class=\"bg-info\">Maturity Depth Requirement: <span id=\"blocksMaturityCount\"></span></span>\n</div>\n\n<hr>\n\n<div class=\"table-responsive\">\n    <table class=\"table table-hover\">\n        <thead>\n        <tr>\n            <th><i class=\"fa fa-bars\"></i> Height</th>\n            <th title=\"How many more blocks network must mine before this block is matured\"><i class=\"fa fa-link\"></i> Maturity</th>\n            <th><i class=\"fa fa-unlock-alt\"></i> Difficulty</th>\n            <th><i class=\"fa fa-paw\"></i> Block Hash</th>\n            <th><i class=\"fa fa-clock-o\"></i> Time Found</th>\n            <th><i class=\"fa fa-star-half-o\"></i> Luck</th>\n        </tr>\n        </thead>\n        <tbody id=\"blocks_rows\">\n\n        </tbody>\n    </table>\n</div>\n\n<p class=\"text-center\">\n    <button type=\"button\" class=\"btn btn-default\" id=\"loadMoreBlocks\">Load More</button>\n</p>\n\n<script>\n\n    currentPage = {\n        destroy: function(){\n            if (xhrGetBlocks) xhrGetBlocks.abort();\n        },\n        update: function(){\n            updateText('blocksTotal', lastStats.pool.totalBlocks.toString());\n            updateText('blocksMaturityCount', lastStats.config.depth.toString());\n            renderBlocks(lastStats.pool.blocks);\n        }\n    };\n\n\n\n    var xhrGetBlocks;\n    $('#loadMoreBlocks').click(function(){\n        if (xhrGetBlocks) xhrGetBlocks.abort();\n        xhrGetBlocks = $.ajax({\n            url: api + '/get_blocks',\n            data: {\n                height: $('#blocks_rows').children().last().data('height')\n            },\n            dataType: 'json',\n            cache: 'false',\n            success: function(data){\n                renderBlocks(data);\n            }\n        });\n    });\n\n\n    function parseBlock(height, serializedBlock){\n        var parts = serializedBlock.split(':');\n        var block = {\n            height: parseInt(height),\n            hash: parts[0],\n            time: parts[1],\n            difficulty: parseInt(parts[2]),\n            shares: parseInt(parts[3]),\n            orphaned: parts[4],\n            reward: parts[5]\n        };\n\n        var toGo = lastStats.config.depth - (lastStats.network.height - block.height);\n        block.maturity = toGo < 1 ? '' : (toGo + ' to go');\n\n        switch (block.orphaned){\n            case '0':\n                block.status = 'unlocked';\n                break;\n            case '1':\n                block.status = 'orphaned';\n                break;\n            default:\n                block.status = 'pending';\n                break;\n        }\n\n        return block;\n    }\n\n\n\n    function getBlockRowElement(block, jsonString){\n\n        function formatLuck(difficulty, shares){\n            //Only an approximation to reverse the calculations done in pool.js, because the shares with their respective times are not recorded in redis\n            //Approximation assumes equal pool hashrate for the whole round\n            //Could potentially be replaced by storing the sum of all job.difficulty in the redis db. \n            if (lastStats.config.slushMiningEnabled) {                                      //Uses integral calculus to calculate the average of a dynamic function\n                var accurateShares = 1/lastStats.config.blockTime * (                       //1/blockTime to get the average\n                    shares * lastStats.config.weight * (                                    //Basically calculates the 'area below the graph' between 0 and blockTime\n                        1 - Math.pow(\n                                Math.E, \n                                ((- lastStats.config.blockTime) / lastStats.config.weight)  //blockTime is equal to the highest possible result of (dateNowSeconds - scoreTime)\n                            )\n                    )\n                );\n            }\n            else {\n                var accurateShares = shares;\n            }\n\n            if (difficulty > accurateShares){\n                var percent = 100 - Math.round(accurateShares / difficulty * 100);\n                return '<span class=\"luckGood\">' + percent + '%</span>';\n            }\n            else{\n                var percent = (100 - Math.round(difficulty / accurateShares * 100)) * -1;\n                return '<span class=\"luckBad\">' + percent + '%</span>';\n            }\n        }\n\n        function formatBlockLink(hash){\n            return '<a target=\"_blank\" href=\"' + blockchainExplorer + hash + '\">' + hash + '</a>';\n        }\n\n        var blockStatusClasses = {\n            'pending': '',\n            'unlocked': 'success',\n            'orphaned': 'danger'\n        };\n\n        var row = document.createElement('tr');\n        row.setAttribute('data-json', jsonString);\n        row.setAttribute('data-height', block.height);\n        row.setAttribute('id', 'blockRow' + block.height);\n        row.setAttribute('title', block.status);\n        row.className = blockStatusClasses[block.status];\n\n        var columns =\n            '<td>' + block.height + '</td>' +\n            '<td>' + block.maturity + '</td>' +\n            '<td>' + block.difficulty + '</td>' +\n            '<td>' + formatBlockLink(block.hash) + '</td>' +\n            '<td>' + formatDate(block.time) + '</td>' +\n            '<td>' + formatLuck(block.difficulty, block.shares) + '</td>';\n\n        row.innerHTML = columns;\n\n        return row;\n    }\n\n\n    function renderBlocks(blocksResults){\n\n        var $blocksRows = $('#blocks_rows');\n\n        for (var i = 0; i < blocksResults.length; i += 2){\n\n            var block = parseBlock(blocksResults[i + 1], blocksResults[i]);\n\n            var blockJson = JSON.stringify(block);\n\n            var existingRow = document.getElementById('blockRow' + block.height);\n\n            if (existingRow && existingRow.getAttribute('data-json') !== blockJson){\n                $(existingRow).replaceWith(getBlockRowElement(block, blockJson));\n            }\n            else if (!existingRow){\n\n                var blockElement = getBlockRowElement(block, blockJson);\n\n                var inserted = false;\n                var rows = $blocksRows.children().get();\n                for (var f = 0; f < rows.length; f++) {\n                    var bHeight = parseInt(rows[f].getAttribute('data-height'));\n                    if (bHeight < block.height){\n                        inserted = true;\n                        $(rows[f]).before(blockElement);\n                        break;\n                    }\n                }\n                if (!inserted)\n                    $blocksRows.append(blockElement);\n            }\n\n        }\n    }\n\n</script>\n"
  },
  {
    "path": "website_example/pages/support.html",
    "content": "<h3>Contact</h3>\n<p>Email pool support at <a id=\"emailLink\" href=\"\"></a></p>\n\n<h3>Chat Room</h3>\n<iframe id=\"kiwi_irc\" style=\"border:0; width:100%; height:500px;\"></iframe>\n\n<script>\n\n    currentPage = {\n        destroy: function(){\n\n        },\n        update: function(){\n\n        }\n    };\n\n    document.getElementById('kiwi_irc').setAttribute('src', 'https://kiwiirc.com/client/' + irc);\n\n    var emailEl = document.getElementById('emailLink');\n    emailEl.setAttribute('href', 'mailto:' + email);\n    emailEl.textContent = email;\n\n</script>"
  }
]