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