├── PreLoad.cmake ├── assets └── images │ └── koinos-cli-miner-banner.png ├── .gitignore ├── miner ├── CMakeLists.txt ├── keccak256.h ├── bn.h ├── keccak256.c ├── bn.c └── main.c ├── retry.js ├── package.json ├── CMakeLists.txt ├── looper.js ├── app.js ├── README.md ├── abi.js ├── index.js └── LICENSE.md /PreLoad.cmake: -------------------------------------------------------------------------------- 1 | if (WIN32) 2 | set (CMAKE_GENERATOR "MinGW Makefiles" CACHE INTERNAL "" FORCE) 3 | endif() 4 | -------------------------------------------------------------------------------- /assets/images/koinos-cli-miner-banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koinos/koinos-miner/HEAD/assets/images/koinos-cli-miner-banner.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | build 3 | Testing 4 | libraries/pack/gen 5 | 6 | # Mac files 7 | .DS_Store 8 | 9 | # Python temp files 10 | *.pyc 11 | *.pyo 12 | __pycache__ 13 | 14 | # Editor cache files 15 | *~* 16 | *#* 17 | 18 | .vscode/ 19 | 20 | # npm 21 | node_modules 22 | 23 | -------------------------------------------------------------------------------- /miner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(OPENSSL_USE_STATIC_LIBS TRUE) 2 | find_package( OpenSSL REQUIRED ) 3 | 4 | add_executable( koinos_miner 5 | main.c 6 | bn.c 7 | bn.h 8 | keccak256.c 9 | keccak256.h ) 10 | 11 | target_link_libraries( koinos_miner ${OPENSSL_LIBRARIES} ) 12 | target_include_directories( koinos_miner PUBLIC ${OPENSSL_INCLUDE_DIR} ) 13 | install( TARGETS 14 | koinos_miner 15 | RUNTIME DESTINATION bin 16 | LIBRARY DESTINATION lib 17 | ARCHIVE DESTINATION lib 18 | ) 19 | -------------------------------------------------------------------------------- /retry.js: -------------------------------------------------------------------------------- 1 | const { sleep } = require("./looper"); 2 | 3 | async function retry(msg, fn) { 4 | let tries = 0; 5 | let sleepTime = 200; 6 | let MAX_SLEEP_TIME = 60000; 7 | 8 | while (true) { 9 | try { 10 | if( tries > 0 ) { 11 | console.log("[JS] Attempting to " + msg + " ("+tries+" failed attempts)" ); 12 | } 13 | return await fn(); 14 | } 15 | catch (e) { 16 | ++tries; 17 | await sleep( (0.75 + 0.25*Math.random()) * sleepTime ); 18 | sleepTime = Math.min( sleepTime*2, MAX_SLEEP_TIME ); 19 | } 20 | } 21 | } 22 | 23 | module.exports = retry; 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "koinos-miner", 3 | "version": "1.0.0", 4 | "description": "Mining application used to mint the KOIN ERC-20.", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "node app.js", 8 | "test": "echo \"Error: no test specified\" && exit 1", 9 | "postinstall": "rm -rf build && mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX=.. -DCMAKE_BUILD_TYPE=Release .. && cmake --build . --target install --config Release && cd .. && rm -rf build" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/open-orchard/koinos-miner.git" 14 | }, 15 | "keywords": [], 16 | "author": "OpenOrchard, Inc.", 17 | "license": "GPL-3.0", 18 | "bugs": { 19 | "url": "https://github.com/open-orchard/koinos-miner/issues" 20 | }, 21 | "homepage": "https://github.com/open-orchard/koinos-miner#readme", 22 | "dependencies": { 23 | "commander": "^6.0.0", 24 | "readline-sync": "^1.4.10", 25 | "web3": "^1.2.11" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | cmake_minimum_required (VERSION 3.10.2) 3 | 4 | find_program(CCACHE_PROGRAM ccache) 5 | if(CCACHE_PROGRAM) 6 | set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CCACHE_PROGRAM}") 7 | set(CMAKE_XCODE_ATTRIBUTE_CC "${CMAKE_SOURCE_DIR}/ci/ccache_clang") 8 | set(CMAKE_XCODE_ATTRIBUTE_CXX "${CMAKE_SOURCE_DIR}/ci/ccache_clang++") 9 | set(CMAKE_XCODE_ATTRIBUTE_LD "${CMAKE_SOURCE_DIR}/ci/ccache_clang") 10 | set(CMAKE_XCODE_ATTRIBUTE_LDPLUSPLUS "${CMAKE_SOURCE_DIR}/ci/ccache_clang++") 11 | endif() 12 | 13 | project( koinos-miner ) 14 | 15 | option (FORCE_COLORED_OUTPUT "Always produce ANSI-colored output (GNU/Clang only)." OFF) 16 | 17 | # This is to force color output when using ccache with Unix Makefiles 18 | if( ${FORCE_COLORED_OUTPUT} ) 19 | if( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" ) 20 | add_compile_options (-fdiagnostics-color=always) 21 | elseif( "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang" ) 22 | add_compile_options (-fcolor-diagnostics) 23 | endif () 24 | endif () 25 | 26 | set(CMAKE_C_STANDARD 11) 27 | 28 | if (NOT CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") 29 | SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror" ) 30 | 31 | SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unknown-pragmas" ) 32 | endif() 33 | 34 | if(MINGW) 35 | set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,--no-whole-archive") 36 | endif() 37 | 38 | SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread -fopenmp -static-libgcc") 39 | 40 | if(APPLE) 41 | SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_GNU_SOURCE") 42 | endif() 43 | 44 | if(${CMAKE_GENERATOR} MATCHES "Xcode") 45 | set(CMAKE_XCODE_GENERATE_SCHEME YES) 46 | endif() 47 | 48 | add_subdirectory(miner) 49 | -------------------------------------------------------------------------------- /miner/keccak256.h: -------------------------------------------------------------------------------- 1 | 2 | /* sha3 - an implementation of Secure Hash Algorithm 3 (Keccak). 3 | * based on the 4 | * The Keccak SHA-3 submission. Submission to NIST (Round 3), 2011 5 | * by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche 6 | * 7 | * Copyright: 2013 Aleksey Kravchenko 8 | * 9 | * Permission is hereby granted, free of charge, to any person obtaining a 10 | * copy of this software and associated documentation files (the "Software"), 11 | * to deal in the Software without restriction, including without limitation 12 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 13 | * and/or sell copies of the Software, and to permit persons to whom the 14 | * Software is furnished to do so. 15 | * 16 | * This program is distributed in the hope that it will be useful, but 17 | * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 18 | * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk! 19 | */ 20 | 21 | #ifndef __KECCAK256_H_ 22 | #define __KECCAK256_H_ 23 | 24 | #include 25 | 26 | #define sha3_max_permutation_size 25 27 | #define sha3_max_rate_in_qwords 24 28 | 29 | typedef struct SHA3_CTX { 30 | /* 1600 bits algorithm hashing state */ 31 | uint64_t hash[sha3_max_permutation_size]; 32 | /* 1536-bit buffer for leftovers */ 33 | uint64_t message[sha3_max_rate_in_qwords]; 34 | /* count of bytes in the message[] buffer */ 35 | uint16_t rest; 36 | /* size of a message block processed at once */ 37 | //unsigned block_size; 38 | } SHA3_CTX; 39 | 40 | 41 | #ifdef __cplusplus 42 | extern "C" { 43 | #endif /* __cplusplus */ 44 | 45 | 46 | void keccak_init(SHA3_CTX *ctx); 47 | void keccak_update(SHA3_CTX *ctx, const unsigned char *msg, uint16_t size); 48 | void keccak_final(SHA3_CTX *ctx, unsigned char* result); 49 | 50 | 51 | #ifdef __cplusplus 52 | } 53 | #endif /* __cplusplus */ 54 | 55 | #endif /* __KECCAK256_H_ */ 56 | -------------------------------------------------------------------------------- /looper.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * An exception used to shut down the loop. 4 | * 5 | * User code should not need to be aware of this class. 6 | */ 7 | class InterruptLooper extends Error { 8 | constructor(message) { 9 | super(message); 10 | this.name = "InterruptLooper"; 11 | } 12 | } 13 | 14 | /** 15 | * An exception thrown when calling stop() multiple times. 16 | */ 17 | class LooperAlreadyStopping extends Error { 18 | constructor(message) { 19 | super(message); 20 | this.name = "LooperAlreadyStopping"; 21 | } 22 | } 23 | 24 | /** 25 | * An exception thrown when calling start() multiple times. 26 | */ 27 | class LooperAlreadyRunning extends Error { 28 | constructor(message) { 29 | super(message); 30 | this.name = "LooperAlreadyRunning"; 31 | } 32 | } 33 | 34 | function sleep(ms=0) 35 | { 36 | return new Promise(function(resolve) { setTimeout(resolve, ms); }); 37 | } 38 | 39 | /** 40 | * Run a loop in the background. 41 | * 42 | * - async function updateFunc runs every updateTime ms 43 | * - Error in updateFunc calls errorCallback but does not stop the loop 44 | * - Call start() to start the loop 45 | * - Call stop() to stop the loop 46 | * - Does not guarantee updateFunc() will not be called after stop 47 | */ 48 | class Looper { 49 | constructor( updateFunc, updateTime, errorCallback ) { 50 | this.updateFunc = updateFunc; 51 | this.updateTime = updateTime; 52 | this.errorCallback = errorCallback; 53 | this._joinWaiters = []; 54 | this._runningUpdateLoop = null; 55 | 56 | this._interruptResolve = null; 57 | } 58 | 59 | /** 60 | * Return a promise that resolves when this task is finished. 61 | */ 62 | join() { 63 | let resolve = null; 64 | let prom = new Promise(function(res) { resolve = res; }); 65 | if( this._runningUpdateLoop === null ) { 66 | // Not running, so join() will return a promise that resolves immediately 67 | resolve(); 68 | } 69 | else { 70 | // Running, so join() will add to _joinWaiters 71 | this._joinWaiters.push(resolve); 72 | } 73 | return prom; 74 | } 75 | 76 | /** 77 | * Ask the loop to stop. Return a promise that resolves when the loop has stopped. 78 | * 79 | * If stop() was already called, immediately throw a LooperAlreadyStopping exception. 80 | */ 81 | stop() { 82 | if( this._interruptResolve == null ) { 83 | throw new LooperAlreadyStopping(); 84 | } 85 | 86 | // Call _interruptResolve() to fire the promise. 87 | setTimeout( this._interruptResolve, 0 ); 88 | this._interruptResolve = null; 89 | return this.join(); 90 | } 91 | 92 | try_stop() { 93 | if( this._interruptResolve !== null ) { 94 | setTimeout( this._interruptResolve, 0 ); 95 | this._interruptResolve = null; 96 | } 97 | 98 | return this.join(); 99 | } 100 | 101 | /** 102 | * Start the loop. Fire-and-forget. 103 | * 104 | * If start() was already called, immediately throw a LooperAlreadyStarting exception. 105 | */ 106 | start() { 107 | if( this._runningUpdateLoop !== null ) { 108 | throw new LooperAlreadyRunning(); 109 | } 110 | 111 | // Create promise for interrupt. 112 | let reject = null; 113 | let prom = new Promise( function(res, rej) { reject = rej; } ); 114 | // _interruptResolve() will inject an InterruptLooper exception into the loop. 115 | this._interruptResolve = function() { reject( new InterruptLooper("Interrupt") ); }; 116 | 117 | this._runningUpdateLoop = this._updateLoop(prom); // Fire-and-forget 118 | } 119 | 120 | /** 121 | * The main loop. 122 | * 123 | * Runs forever, until _interruptPromise is triggered. 124 | * You should call start() instead of calling this method directly. 125 | */ 126 | async _updateLoop( _interruptPromise ) { 127 | while( true ) 128 | { 129 | try 130 | { 131 | await Promise.race( [ _interruptPromise, sleep( (0.75 + 0.5*Math.random()) * this.updateTime ) ] ); 132 | await Promise.race( [ _interruptPromise, this.updateFunc()] ); 133 | } 134 | catch( e ) 135 | { 136 | if( e.name === "InterruptLooper" ) 137 | break; 138 | if (this.errorCallback && typeof this.errorCallback === "function") { 139 | this.errorCallback(e); 140 | } 141 | } 142 | } 143 | 144 | // 145 | // Use setTimeout(f, 0) here so we don't immediately call external code which might attempt to mutate 146 | // this._joinWaiters during the loop. 147 | // 148 | // If join() is called before we get to this point, the result will be resolved due to the following loop. 149 | // If join() is called after this point, it will correctly return a resolved promise due to _runningUpdateLoop == null. 150 | // 151 | for( let i=0; i 2 | 3 | #ifndef __BIGNUM_H__ 4 | #define __BIGNUM_H__ 5 | /* 6 | Big number library - arithmetic on multiple-precision unsigned integers. 7 | This library is an implementation of arithmetic on arbitrarily large integers. 8 | The difference between this and other implementations, is that the data structure 9 | has optimal memory utilization (i.e. a 1024 bit integer takes up 128 bytes RAM), 10 | and all memory is allocated statically: no dynamic allocation for better or worse. 11 | Primary goals are correctness, clarity of code and clean, portable implementation. 12 | Secondary goal is a memory footprint small enough to make it suitable for use in 13 | embedded applications. 14 | The current state is correct functionality and adequate performance. 15 | There may well be room for performance-optimizations and improvements. 16 | */ 17 | 18 | /* 19 | This was taken from https://github.com/kokke/tiny-bignum-c with a public domain license 20 | Thanks! :) 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | 27 | /* This macro defines the word size in bytes of the array that constitues the big-number data structure. */ 28 | #ifndef WORD_SIZE 29 | #define WORD_SIZE 4 30 | #endif 31 | 32 | /* Size of big-numbers in bytes */ 33 | #define BN_ARRAY_SIZE (32 / WORD_SIZE) 34 | 35 | 36 | /* Here comes the compile-time specialization for how large the underlying array size should be. */ 37 | /* The choices are 1, 2 and 4 bytes in size with uint32, uint64 for WORD_SIZE==4, as temporary. */ 38 | #ifndef WORD_SIZE 39 | #error Must define WORD_SIZE to be 1, 2, 4 40 | #elif (WORD_SIZE == 1) 41 | /* Data type of array in structure */ 42 | #define DTYPE uint8_t 43 | /* bitmask for getting MSB */ 44 | #define DTYPE_MSB ((DTYPE_TMP)(0x80)) 45 | /* Data-type larger than DTYPE, for holding intermediate results of calculations */ 46 | #define DTYPE_TMP uint32_t 47 | /* sprintf format string */ 48 | #define SPRINTF_FORMAT_STR "%.02x" 49 | #define SSCANF_FORMAT_STR "%2hhx" 50 | /* Max value of integer type */ 51 | #define MAX_VAL ((DTYPE_TMP)0xFF) 52 | #elif (WORD_SIZE == 2) 53 | #define DTYPE uint16_t 54 | #define DTYPE_TMP uint32_t 55 | #define DTYPE_MSB ((DTYPE_TMP)(0x8000)) 56 | #define SPRINTF_FORMAT_STR "%.04x" 57 | #define SSCANF_FORMAT_STR "%4hx" 58 | #define MAX_VAL ((DTYPE_TMP)0xFFFF) 59 | #elif (WORD_SIZE == 4) 60 | #define DTYPE uint32_t 61 | #define DTYPE_TMP uint64_t 62 | #define DTYPE_MSB ((DTYPE_TMP)(0x80000000)) 63 | #define SPRINTF_FORMAT_STR "%.08x" 64 | #define SSCANF_FORMAT_STR "%8x" 65 | #define MAX_VAL ((DTYPE_TMP)0xFFFFFFFF) 66 | #endif 67 | #ifndef DTYPE 68 | #error DTYPE must be defined to uint8_t, uint16_t uint32_t or whatever 69 | #endif 70 | 71 | 72 | /* Custom assert macro - easy to disable */ 73 | #define require(p, msg) assert(p && msg) 74 | 75 | 76 | /* Data-holding structure: array of DTYPEs */ 77 | struct bn 78 | { 79 | DTYPE array[BN_ARRAY_SIZE]; 80 | }; 81 | 82 | 83 | 84 | /* Tokens returned by bignum_cmp() for value comparison */ 85 | enum { SMALLER = -1, EQUAL = 0, LARGER = 1 }; 86 | 87 | 88 | 89 | /* Initialization functions: */ 90 | void bignum_init(struct bn* n); 91 | void bignum_from_int(struct bn* n, DTYPE_TMP i); 92 | int bignum_to_int(struct bn* n); 93 | void bignum_from_string(struct bn* n, char* str, int nbytes); 94 | void bignum_to_string(struct bn* n, char* str, int maxsize, bool leading_zeros); 95 | 96 | /* Basic arithmetic operations: */ 97 | void bignum_add(struct bn* a, struct bn* b, struct bn* c); /* c = a + b */ 98 | void bignum_sub(struct bn* a, struct bn* b, struct bn* c); /* c = a - b */ 99 | void bignum_mul(struct bn* a, struct bn* b, struct bn* c); /* c = a * b */ 100 | void bignum_div(struct bn* a, struct bn* b, struct bn* c); /* c = a / b */ 101 | void bignum_mod(struct bn* a, struct bn* b, struct bn* c); /* c = a % b */ 102 | void bignum_divmod(struct bn* a, struct bn* b, struct bn* c, struct bn* d); /* c = a/b, d = a%b */ 103 | 104 | /* Bitwise operations: */ 105 | void bignum_and(struct bn* a, struct bn* b, struct bn* c); /* c = a & b */ 106 | void bignum_or(struct bn* a, struct bn* b, struct bn* c); /* c = a | b */ 107 | void bignum_xor(struct bn* a, struct bn* b, struct bn* c); /* c = a ^ b */ 108 | void bignum_lshift(struct bn* a, struct bn* b, int nbits); /* b = a << nbits */ 109 | void bignum_rshift(struct bn* a, struct bn* b, int nbits); /* b = a >> nbits */ 110 | 111 | /* Special operators and comparison */ 112 | int bignum_cmp(struct bn* a, struct bn* b); /* Compare: returns LARGER, EQUAL or SMALLER */ 113 | int bignum_is_zero(struct bn* n); /* For comparison with zero */ 114 | void bignum_inc(struct bn* n); /* Increment: add one to n */ 115 | void bignum_dec(struct bn* n); /* Decrement: subtract one from n */ 116 | void bignum_pow(struct bn* a, struct bn* b, struct bn* c); /* Calculate a^b -- e.g. 2^10 => 1024 */ 117 | void bignum_isqrt(struct bn* a, struct bn* b); /* Integer square root -- e.g. isqrt(5) => 2*/ 118 | void bignum_assign(struct bn* dst, struct bn* src); /* Copy src into dst -- dst := src */ 119 | 120 | void bignum_endian_swap(struct bn* n); /* In place endiam swap on n */ 121 | 122 | #endif /* #ifndef __BIGNUM_H__ */ 123 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { program } = require('commander'); 4 | 5 | program 6 | .version('1.0.0', '-v, --version') 7 | .usage('[OPTIONS]...') 8 | .requiredOption('-a, --addr ', 'An ethereum address') 9 | .option('-e, --endpoint ', 'An ethereum endpoint', 'http://mining.koinos.io') 10 | .option('-t, --tip ', 'The percentage of mined coins to tip the developers', '5') 11 | .option('-p, --proof-period ', 'How often you want to submit a proof on average', '86400') 12 | .option('-k, --key-file ', 'AES encrypted file containing private key') 13 | .option('-m, --gas-multiplier ', 'The multiplier to apply to the recommended gas price', '1') 14 | .option('-l, --gas-price-limit ', 'The maximum amount of gas to be spent on a proof submission', '1000000000000') 15 | .option('--import', 'Import a private key') 16 | .option('--export', 'Export a private key') 17 | .parse(process.argv); 18 | 19 | console.log(` _ __ _ __ __ _`); 20 | console.log(`| |/ / (_) | \\/ (_)`); 21 | console.log(`| ' / ___ _ _ __ ___ ___ | \\ / |_ _ __ ___ _ __`); 22 | console.log(`| < / _ \\| | '_ \\ / _ \\/ __| | |\\/| | | '_ \\ / _ \\ '__|`); 23 | console.log(`| . \\ (_) | | | | | (_) \\__ \\ | | | | | | | | __/ |`); 24 | console.log(`|_|\\_\\___/|_|_| |_|\\___/|___/ |_| |_|_|_| |_|\\___|_|`); 25 | console.log(``); 26 | console.log(`[JS](app.js) Mining with the following arguments:`); 27 | console.log(`[JS](app.js) Ethereum Address: ${program.addr}`); 28 | console.log(`[JS](app.js) Ethereum Endpoint: ${program.endpoint}`); 29 | console.log(`[JS](app.js) Developer Tip: ${program.tip}%`); 30 | console.log(`[JS](app.js) Proof Period: ${program.proofPeriod}`); 31 | console.log(``); 32 | 33 | let KoinosMiner = require('.'); 34 | const readlineSync = require('readline-sync'); 35 | const crypto = require('crypto') 36 | var Web3 = require('web3'); 37 | var fs = require('fs'); 38 | 39 | const tip_addresses = [ 40 | "0x292B59941aE124acFca9a759892Ae5Ce246eaAD2", 41 | "0xbf3C8Ffc87Ba300f43B2fDaa805CcA5DcB4bC984", 42 | "0x407A73626697fd22b1717d294E6B39437531013d", 43 | "0x69486fda786D82dBb61C78847A815d5F615C2B15", 44 | "0x434eAbB24c0051280D1CC0AF6E12bF59b5F932e9", 45 | "0xa524095504833359E6E1d41161102B1a314b97C0", 46 | "0xf7771105679d2bfc27820B93C54516f1d8772C88", 47 | "0xa0fc784961E6aCc30D28FA072Aa4FB3892C1938A", 48 | "0x306443eeBf036A35a360f005BE306FD7855e8Cb5", 49 | "0x40609227175ac3093086072391Ff603db2e3D72a", 50 | "0xE536fdfF635aEB8B9DFd6Be207e1aE10A58fB85e", 51 | "0x9d2DfA864887dF1f41bC02CE94C74Bb0dE471Da6", 52 | "0x563f6EB769883f98e56BF20127c116ABce8EF564", 53 | "0x33D682B145f4AA664353b6B6A7B42a13D1c190a9", 54 | "0xea701365BC23Aa696D5DaFa0394cC6f1a18b2832", 55 | "0xc8B02B313Bd56372D278CAfd275641181d29793d", 56 | "0xd73B6Da85bE7Dae4AC2A7D5388e9F237ed235450", 57 | "0x03b6470040b5139b82F96f8D9D61DAb43a01a75c", 58 | "0xF8357581107a12c3989FFec217ACb6cd0336acbE", 59 | "0xeAdB773d0896EC5A3463EFAF6A1b763ECEC33743" 60 | ]; 61 | const contract_address = '0xa18c8756ee6B303190A702e81324C72C0E7080c5'; 62 | 63 | var account; 64 | 65 | var w3 = new Web3(program.endpoint); 66 | 67 | let warningCallback = function(warning) { 68 | console.log(`[JS](app.js) Warning: `, warning); 69 | } 70 | 71 | let errorCallback = function(error) { 72 | console.log(`[JS](app.js) Error: `, error); 73 | } 74 | 75 | let hashrateCallback = function(hashrate) 76 | { 77 | console.log(`[JS](app.js) Hashrate: ` + KoinosMiner.formatHashrate(hashrate)); 78 | } 79 | 80 | let proofCallback = function(submission) {} 81 | 82 | let signCallback = async function(web3, txData) 83 | { 84 | return (await web3.eth.accounts.signTransaction(txData, account.privateKey)).rawTransaction; 85 | } 86 | 87 | function enterPassword() 88 | { 89 | return readlineSync.questionNewPassword('Enter password for encryption: ', {mask: ''}); 90 | } 91 | 92 | function encrypt(data, password) 93 | { 94 | const passwordHash = crypto.createHmac('sha256', password).digest(); 95 | const key = Buffer.from(passwordHash.toString('hex').slice(16), 'hex'); 96 | const iv = Buffer.from(crypto.createHmac('sha256', passwordHash).digest('hex').slice(32), 'hex'); 97 | var cipher = crypto.createCipheriv('aes-192-cbc', key, iv ); 98 | 99 | var cipherText = cipher.update(data, 'utf8', 'hex'); 100 | cipherText += cipher.final('hex'); 101 | 102 | return cipherText; 103 | } 104 | 105 | function decrypt(cipherText, password) 106 | { 107 | const passwordHash = crypto.createHmac('sha256', password).digest(); 108 | const key = Buffer.from(passwordHash.toString('hex').slice(16), 'hex'); 109 | const iv = Buffer.from(crypto.createHmac('sha256', passwordHash).digest('hex').slice(32), 'hex'); 110 | var decipher = crypto.createDecipheriv('aes-192-cbc', key, iv ); 111 | 112 | let decrypted = ''; 113 | 114 | decipher.on('readable', () => { 115 | let chunk; 116 | while (null !== (chunk = decipher.read())) { 117 | decrypted += chunk.toString('utf8'); 118 | } 119 | }); 120 | 121 | decipher.write(cipherText, 'hex'); 122 | decipher.end(); 123 | 124 | return decrypted 125 | } 126 | 127 | if (program.import) 128 | { 129 | account = w3.eth.accounts.privateKeyToAccount( 130 | readlineSync.questionNewPassword('Enter private key: ', { 131 | mask: '', 132 | min: 64, 133 | max: 66, 134 | charlist: '$<0-9>$$x' 135 | })); 136 | 137 | if(readlineSync.keyInYNStrict('Do you want to store your private key encrypted on disk?')) 138 | { 139 | var cipherText = encrypt(account.privateKey, enterPassword()); 140 | 141 | var filename = readlineSync.question('Where do you want to save the encrypted private key? '); 142 | fs.writeFileSync(filename, cipherText); 143 | } 144 | 145 | console.log('Imported Ethereum address: ' + account.address); 146 | } 147 | else if (program.keyFile) 148 | { 149 | if(program.export && !readlineSync.keyInYNStrict('Outputting your private key unencrypted can be dangerous. Are you sure you want to continue?')) 150 | { 151 | process.exit(0); 152 | } 153 | 154 | var data = fs.readFileSync(program.keyFile, 'utf8'); 155 | account = w3.eth.accounts.privateKeyToAccount(decrypt(data, enterPassword())); 156 | 157 | console.log('Decrypted Ethereum address: ' + account.address); 158 | 159 | if(program.export) 160 | { 161 | console.log(account.privateKey); 162 | process.exit(0); 163 | } 164 | } 165 | else 166 | { 167 | if(!readlineSync.keyInYNStrict('No private key file specified. Do you want to create a new key?')) 168 | { 169 | process.exit(0); 170 | } 171 | 172 | var seed = readlineSync.question('Enter seed for entropy: ', {hideEchoBack: true, mask: ''}); 173 | account = w3.eth.accounts.create(crypto.createHmac('sha256', seed).digest('hex')); 174 | 175 | var cipherText = encrypt(account.privateKey, enterPassword()); 176 | 177 | var filename = readlineSync.question('Where do you want to save the encrypted private key? '); 178 | fs.writeFileSync(filename, cipherText); 179 | 180 | console.log('Created new Ethereum address: ' + account.address); 181 | } 182 | 183 | var miner = new KoinosMiner( 184 | program.addr, 185 | tip_addresses, 186 | account.address, 187 | contract_address, 188 | program.endpoint, 189 | program.tip, 190 | program.proofPeriod, 191 | program.gasMultiplier, 192 | program.gasPriceLimit, 193 | signCallback, 194 | hashrateCallback, 195 | proofCallback, 196 | errorCallback, 197 | warningCallback); 198 | 199 | miner.start(); 200 | -------------------------------------------------------------------------------- /miner/keccak256.c: -------------------------------------------------------------------------------- 1 | /* sha3 - an implementation of Secure Hash Algorithm 3 (Keccak). 2 | * based on the 3 | * The Keccak SHA-3 submission. Submission to NIST (Round 3), 2011 4 | * by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche 5 | * 6 | * Copyright: 2013 Aleksey Kravchenko 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a 9 | * copy of this software and associated documentation files (the "Software"), 10 | * to deal in the Software without restriction, including without limitation 11 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 12 | * and/or sell copies of the Software, and to permit persons to whom the 13 | * Software is furnished to do so. 14 | * 15 | * This program is distributed in the hope that it will be useful, but 16 | * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 17 | * or FITNESS FOR A PARTICULAR PURPOSE. Use this program at your own risk! 18 | */ 19 | 20 | #include "keccak256.h" 21 | 22 | //#include 23 | 24 | #include 25 | #include 26 | 27 | #define BLOCK_SIZE ((1600 - 256 * 2) / 8) 28 | 29 | #define I64(x) x##LL 30 | #define ROTL64(qword, n) ((qword) << (n) ^ ((qword) >> (64 - (n)))) 31 | #define le2me_64(x) (x) 32 | #define IS_ALIGNED_64(p) (0 == (7 & ((const char*)(p) - (const char*)0))) 33 | #define me64_to_le_str(to, from, length) memcpy((to), (from), (length)) 34 | 35 | /* constants */ 36 | 37 | //const uint8_t round_constant_info[] PROGMEM = { 38 | //const uint8_t constants[] PROGMEM = { 39 | const uint8_t constants[] = { 40 | 41 | 1, 26, 94, 112, 31, 33, 121, 85, 14, 12, 53, 38, 63, 79, 93, 83, 82, 72, 22, 102, 121, 88, 33, 116, 42 | //}; 43 | 44 | //const uint8_t pi_transform[] PROGMEM = { 45 | 1, 6, 9, 22, 14, 20, 2, 12, 13, 19, 23, 15, 4, 24, 21, 8, 16, 5, 3, 18, 17, 11, 7, 10, 46 | //}; 47 | 48 | //const uint8_t rhoTransforms[] PROGMEM = { 49 | 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14, 50 | }; 51 | 52 | #define TYPE_ROUND_INFO 0 53 | #define TYPE_PI_TRANSFORM 24 54 | #define TYPE_RHO_TRANSFORM 48 55 | 56 | uint8_t getConstant(uint8_t type, uint8_t index) { 57 | return constants[type + index]; 58 | //return pgm_read_byte(&constants[type + index]); 59 | } 60 | 61 | static uint64_t get_round_constant(uint8_t round) { 62 | uint64_t result = 0; 63 | 64 | //uint8_t roundInfo = pgm_read_byte(&round_constant_info[round]); 65 | uint8_t roundInfo = getConstant(TYPE_ROUND_INFO, round); 66 | if (roundInfo & (1 << 6)) { result |= ((uint64_t)1 << 63); } 67 | if (roundInfo & (1 << 5)) { result |= ((uint64_t)1 << 31); } 68 | if (roundInfo & (1 << 4)) { result |= ((uint64_t)1 << 15); } 69 | if (roundInfo & (1 << 3)) { result |= ((uint64_t)1 << 7); } 70 | if (roundInfo & (1 << 2)) { result |= ((uint64_t)1 << 3); } 71 | if (roundInfo & (1 << 1)) { result |= ((uint64_t)1 << 1); } 72 | if (roundInfo & (1 << 0)) { result |= ((uint64_t)1 << 0); } 73 | 74 | return result; 75 | } 76 | 77 | 78 | /* Initializing a sha3 context for given number of output bits */ 79 | void keccak_init(SHA3_CTX *ctx) { 80 | /* NB: The Keccak capacity parameter = bits * 2 */ 81 | 82 | memset(ctx, 0, sizeof(SHA3_CTX)); 83 | } 84 | 85 | /* Keccak theta() transformation */ 86 | static void keccak_theta(uint64_t *A) { 87 | uint64_t C[5], D[5]; 88 | 89 | for (uint8_t i = 0; i < 5; i++) { 90 | C[i] = A[i]; 91 | for (uint8_t j = 5; j < 25; j += 5) { C[i] ^= A[i + j]; } 92 | } 93 | 94 | for (uint8_t i = 0; i < 5; i++) { 95 | D[i] = ROTL64(C[(i + 1) % 5], 1) ^ C[(i + 4) % 5]; 96 | } 97 | 98 | for (uint8_t i = 0; i < 5; i++) { 99 | //for (uint8_t j = 0; j < 25; j += 5) { 100 | for (uint8_t j = 0; j < 25; j += 5) { A[i + j] ^= D[i]; } 101 | } 102 | } 103 | 104 | 105 | /* Keccak pi() transformation */ 106 | static void keccak_pi(uint64_t *A) { 107 | uint64_t A1 = A[1]; 108 | //for (uint8_t i = 1; i < sizeof(pi_transform); i++) { 109 | for (uint8_t i = 1; i < 24; i++) { 110 | //A[pgm_read_byte(&pi_transform[i - 1])] = A[pgm_read_byte(&pi_transform[i])]; 111 | A[getConstant(TYPE_PI_TRANSFORM, i - 1)] = A[getConstant(TYPE_PI_TRANSFORM, i)]; 112 | } 113 | A[10] = A1; 114 | /* note: A[ 0] is left as is */ 115 | } 116 | 117 | /* 118 | ketch uses 30084 bytes (93%) of program storage space. Maximum is 32256 bytes. 119 | Global variables use 743 bytes (36%) of dynamic memory, leaving 1305 bytes for local variables. Maximum is 2048 bytes. 120 | */ 121 | /* Keccak chi() transformation */ 122 | static void keccak_chi(uint64_t *A) { 123 | for (uint8_t i = 0; i < 25; i += 5) { 124 | uint64_t A0 = A[0 + i], A1 = A[1 + i]; 125 | A[0 + i] ^= ~A1 & A[2 + i]; 126 | A[1 + i] ^= ~A[2 + i] & A[3 + i]; 127 | A[2 + i] ^= ~A[3 + i] & A[4 + i]; 128 | A[3 + i] ^= ~A[4 + i] & A0; 129 | A[4 + i] ^= ~A0 & A1; 130 | } 131 | } 132 | 133 | 134 | static void sha3_permutation(uint64_t *state) { 135 | //for (uint8_t round = 0; round < sizeof(round_constant_info); round++) { 136 | for (uint8_t round = 0; round < 24; round++) { 137 | keccak_theta(state); 138 | 139 | /* apply Keccak rho() transformation */ 140 | for (uint8_t i = 1; i < 25; i++) { 141 | //state[i] = ROTL64(state[i], pgm_read_byte(&rhoTransforms[i - 1])); 142 | state[i] = ROTL64(state[i], getConstant(TYPE_RHO_TRANSFORM, i - 1)); 143 | } 144 | 145 | keccak_pi(state); 146 | keccak_chi(state); 147 | 148 | /* apply iota(state, round) */ 149 | *state ^= get_round_constant(round); 150 | } 151 | } 152 | 153 | /** 154 | * The core transformation. Process the specified block of data. 155 | * 156 | * @param hash the algorithm state 157 | * @param block the message block to process 158 | * @param block_size the size of the processed block in bytes 159 | */ 160 | static void sha3_process_block(uint64_t hash[25], const uint64_t *block) { 161 | for (uint8_t i = 0; i < 17; i++) { 162 | hash[i] ^= le2me_64(block[i]); 163 | } 164 | 165 | /* make a permutation of the hash */ 166 | sha3_permutation(hash); 167 | } 168 | 169 | //#define SHA3_FINALIZED 0x80000000 170 | //#define SHA3_FINALIZED 0x8000 171 | 172 | /** 173 | * Calculate message hash. 174 | * Can be called repeatedly with chunks of the message to be hashed. 175 | * 176 | * @param ctx the algorithm context containing current hashing state 177 | * @param msg message chunk 178 | * @param size length of the message chunk 179 | */ 180 | void keccak_update(SHA3_CTX *ctx, const unsigned char *msg, uint16_t size) 181 | { 182 | uint16_t idx = (uint16_t)ctx->rest; 183 | 184 | //if (ctx->rest & SHA3_FINALIZED) return; /* too late for additional input */ 185 | ctx->rest = (unsigned)((ctx->rest + size) % BLOCK_SIZE); 186 | 187 | /* fill partial block */ 188 | if (idx) { 189 | uint16_t left = BLOCK_SIZE - idx; 190 | memcpy((char*)ctx->message + idx, msg, (size < left ? size : left)); 191 | if (size < left) return; 192 | 193 | /* process partial block */ 194 | sha3_process_block(ctx->hash, ctx->message); 195 | msg += left; 196 | size -= left; 197 | } 198 | 199 | while (size >= BLOCK_SIZE) { 200 | uint64_t* aligned_message_block; 201 | if (IS_ALIGNED_64(msg)) { 202 | // the most common case is processing of an already aligned message without copying it 203 | aligned_message_block = (uint64_t*)(void*)msg; 204 | } else { 205 | memcpy(ctx->message, msg, BLOCK_SIZE); 206 | aligned_message_block = ctx->message; 207 | } 208 | 209 | sha3_process_block(ctx->hash, aligned_message_block); 210 | msg += BLOCK_SIZE; 211 | size -= BLOCK_SIZE; 212 | } 213 | 214 | if (size) { 215 | memcpy(ctx->message, msg, size); /* save leftovers */ 216 | } 217 | } 218 | 219 | /** 220 | * Store calculated hash into the given array. 221 | * 222 | * @param ctx the algorithm context containing current hashing state 223 | * @param result calculated hash in binary form 224 | */ 225 | void keccak_final(SHA3_CTX *ctx, unsigned char* result) 226 | { 227 | uint16_t digest_length = 100 - BLOCK_SIZE / 2; 228 | 229 | // if (!(ctx->rest & SHA3_FINALIZED)) { 230 | /* clear the rest of the data queue */ 231 | memset((char*)ctx->message + ctx->rest, 0, BLOCK_SIZE - ctx->rest); 232 | ((char*)ctx->message)[ctx->rest] |= 0x01; 233 | ((char*)ctx->message)[BLOCK_SIZE - 1] |= 0x80; 234 | 235 | /* process final block */ 236 | sha3_process_block(ctx->hash, ctx->message); 237 | // ctx->rest = SHA3_FINALIZED; /* mark context as finalized */ 238 | // } 239 | 240 | if (result) { 241 | me64_to_le_str(result, ctx->hash, digest_length); 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Koinos Miner](assets/images/koinos-cli-miner-banner.png) 2 | 3 | [![GitHub Issues](https://img.shields.io/github/issues/open-orchard/koinos-miner.svg)](https://github.com/open-orchard/koinos-miner/issues) 4 | [![GitHub License](https://img.shields.io/badge/license-GPLv3-blue.svg)](https://github.com/open-orchard/koinos-miner/blob/master/LICENSE.md) 5 | 6 | ## Table of Contents 7 | - [Dependencies](#dependencies) 8 | - [Installation](#installation) 9 | - [Getting Started](#getting-started) 10 | - [Key Management](#key-management) 11 | - [Example Run](#example-run) 12 | - [FAQ](#FAQ) 13 | 14 | ## Dependencies 15 | 16 | Prior to installation, you'll need to install the necessary dependencies. 17 | 18 | ### Linux (Debian based) 19 | 20 | ``` 21 | sudo apt-get install git cmake build-essential libssl-dev 22 | ``` 23 | 24 | ### macOS 25 | 26 | On macOS, installing `gcc` is required to support OpenMP parallelization. Using the `brew` package manager, install OpenSSL and gcc. 27 | ``` 28 | brew install openssl gcc cmake 29 | ``` 30 | 31 | ### Windows 32 | 33 | On Windows, ensure that you are using the `MingW` compiler and you have installed `CMake`. Using the cholocately package manager, install OpenSSL. 34 | 35 | ``` 36 | choco install openssl 37 | ``` 38 | 39 | ## Installation 40 | 41 | For both Windows and Linux, you should be able to simply invoke the standard `npm` installer. 42 | 43 | ``` 44 | npm install 45 | ``` 46 | 47 | For macOS, you will need to specify the C compiler as `gcc`. 48 | 49 | ``` 50 | CC=gcc-10 npm install 51 | ``` 52 | 53 | ## Getting started 54 | 55 | You can view the CLI miner arguments by using `npm` like so: 56 | 57 | ``` 58 | npm start -- --help 59 | ``` 60 | 61 | And get the following output: 62 | 63 | ``` 64 | ❯ npm start -- --help 65 | 66 | > koinos-miner@1.0.0 start /path/to/koinos-miner 67 | > node app.js "--help" 68 | 69 | Usage: app [OPTIONS]... 70 | 71 | Options: 72 | -v, --version output the version number 73 | -a, --addr An ethereum address 74 | -e, --endpoint An ethereum endpoint (default: "http://mining.koinos.io") 75 | -t, --tip The percentage of mined coins to tip the developers (default: "5") 76 | -p, --proof-period How often you want to submit a proof on average (default: "86400") 77 | -k, --key-file AES encrypted file containing private key 78 | -m, --gas-multiplier The multiplier to apply to the recommended gas price (default: "1") 79 | -l, --gas-price-limit The maximum amount of gas to be spent on a proof submission (default: "1000000000000") 80 | --import Import a private key 81 | --export Export a private key 82 | -h, --help display help for command 83 | ``` 84 | 85 | **Recipient Address**: The `--addr` argument specifies the recipient address, this is where KOIN will be rewarded. 86 | 87 | **Ethereum Endpoint**: The `--endpoint` argument specifies the Ethereum node to be used when querying contract information and submitting proofs. 88 | 89 | **Developer Tip**: The `--tip` argument specifies the percentage of rewarded KOIN to donate to the development team, thank you! 90 | 91 | **Proof Period**: The `--proof-period` argument specifies the number of seconds on average the miner will attempt to mine and submit proofs. 92 | 93 | **Gas Multiplier**: The `--gas-multiplier` argument specifies a multiplier to apply to the calculated gas price. This can be used to get your proofs submitted when the Ethereum network gas fees are spiking or are unpredictable. 94 | 95 | **Gas Price Limit**: The `--gas-price-limit` argument specifies a cap in the acceptable gas price for a proof submission. 96 | 97 | A more detailed explanation of the different miner configurations can be found in the [Koinos GUI Miner](https://github.com/open-orchard/koinos-gui-miner) `README.md`. 98 | 99 | ## Key Management 100 | 101 | The CLI miner provides the arguments `--import`, `--export`, and `--key-file`. These are used in handling the private key of the funding address. The user may import a private key and optionally store it in a key file in which case exporting the key is now possible. 102 | 103 | ## Example Run 104 | 105 | A simple example of running the miner: 106 | 107 | ``` 108 | ❯ npm start -- --endpoint http://167.172.118.40:8545 --addr 0x98047645bf61644caa0c24daabd118cc1d640f62 --import 109 | 110 | > koinos-miner@1.0.0 start /path/to/koinos-miner 111 | > node app.js "--endpoint" "http://167.172.118.40:8545" "--addr" "0x98047645bf61644caa0c24daabd118cc1d640f62" "--import" 112 | 113 | _ __ _ __ __ _ 114 | | |/ / (_) | \/ (_) 115 | | ' / ___ _ _ __ ___ ___ | \ / |_ _ __ ___ _ __ 116 | | < / _ \| | '_ \ / _ \/ __| | |\/| | | '_ \ / _ \ '__| 117 | | . \ (_) | | | | | (_) \__ \ | | | | | | | | __/ | 118 | |_|\_\___/|_|_| |_|\___/|___/ |_| |_|_|_| |_|\___|_| 119 | 120 | [JS](app.js) Mining with the following arguments: 121 | [JS](app.js) Ethereum Address: 0x98047645bf61644caa0c24daabd118cc1d640f62 122 | [JS](app.js) Ethereum Endpoint: http://167.172.118.40:8545 123 | [JS](app.js) Developer Tip: 5% 124 | [JS](app.js) Proof Period: 86400 125 | 126 | Enter private key: 127 | Reinput a same one to confirm it: 128 | Do you want to store your private key encrypted on disk? [y/n]: n 129 | Imported Ethereum address: 0x98047645BF61644CAA0c24dAABD118cC1D640F62 130 | [JS] Starting miner 131 | ``` 132 | # FAQ 133 | 134 | ## What is “Proof Frequency?” 135 | 136 | The key to understanding the proof frequency is that this number isn’t a “real” setting in the miner. Instead what you are modifying is the *difficulty* of the problem your miner is trying to solve. Harder problems take longer to solve, but the time it takes to solve them is just a guesstimation. The miner might solve the problem right away, or take an unusually long time. It will only rarely take exactly the time you expect it to take. 137 | 138 | ## Why Set a Low Frequency? 139 | 140 | In the case of PoW KOIN mining, increased difficulty results in a higher *potential* KOIN reward. But again, there is randomness here too. The KOIN reward *might* be large, but it might also be small. So a lower number (e.g. 1 per day or 2 per day) is likely to win you larger KOIN rewards. But an added benefit is that it minimizes your Ethereum fees as well. 141 | 142 | ## Why Set a High Frequency? 143 | 144 | Low frequency proofs (i.e. high difficulty) give you bigger potential rewards, so why would you increase the frequency especially considering it will result in higher Ethereum fees? One way to think about mining is like it’s a lottery (except it has slightly better odds ;) ). If you buy enough tickets, you can expect to win an approximate number of times. But you know that your odds of winning with any single ticket is very low. So what do you do? You increase the number of tickets you buy. You make sure that you’re playing the game enough times so that *over the long run* you receive the rewards that the probabilities say you should. 145 | 146 | ## What Happens if I Shut Down the Miner? 147 | 148 | Note that setting a higher frequency doesn’t help you beat someone else to the punch. Your computer is solving hundreds of thousands (or millions) of “losing” hashes every second that it is throwing in the trash, just as you would a losing lottery ticket. It is not saving those hashes, it is searching for one “winning” hash and when it finds that hash it immediately submits a proof to the Ethereum network. This is why it doesn’t matter if your computer loses access to the internet or you just turn off the miner for a moment. You don’t “lose” anything other than the opportunity costs associated with the time that could have been spent mining. 149 | 150 | # Why Mine? 151 | 152 | It’s important to remember that our mission is to give everyone ownership and control over their digital selves. The foundational product we are releasing to serve that mission is the Koinos mainnet and the purpose of this mining phase is to decentralize the token distribution and ensure that when it launches, the Koinos mainnet is as decentralized as any blockchain out there, if not more! 153 | 154 | KOIN will be the cryptocurrency that powers a decentralized computer built from the ground up to enable developers to offer delightful user experiences while protecting the user’s digital information through blockchain integration. The purpose of this phase is to get KOIN into the hands of developers and users who want be able to use the types of applications that Koinos is capable of powering. 155 | 156 | ## License 157 | 158 | Copyright 2020 Open Orchard, Inc. 159 | 160 | Koinos Miner is free software: you can redistribute it and/or modify 161 | it under the terms of the GNU General Public License as published by 162 | the Free Software Foundation, either version 3 of the License, or 163 | (at your option) any later version. 164 | 165 | Koinos Miner is distributed in the hope that it will be useful, 166 | but WITHOUT ANY WARRANTY; without even the implied warranty of 167 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 168 | GNU General Public License for more details. 169 | 170 | You should have received a copy of the GNU General Public License 171 | along with Koinos Miner. If not, see . 172 | -------------------------------------------------------------------------------- /miner/bn.c: -------------------------------------------------------------------------------- 1 | /* 2 | Big number library - arithmetic on multiple-precision unsigned integers. 3 | This library is an implementation of arithmetic on arbitrarily large integers. 4 | The difference between this and other implementations, is that the data structure 5 | has optimal memory utilization (i.e. a 1024 bit integer takes up 128 bytes RAM), 6 | and all memory is allocated statically: no dynamic allocation for better or worse. 7 | Primary goals are correctness, clarity of code and clean, portable implementation. 8 | Secondary goal is a memory footprint small enough to make it suitable for use in 9 | embedded applications. 10 | The current state is correct functionality and adequate performance. 11 | There may well be room for performance-optimizations and improvements. 12 | */ 13 | 14 | #include 15 | #include 16 | #include 17 | #include "bn.h" 18 | 19 | 20 | 21 | /* Functions for shifting number in-place. */ 22 | static void _lshift_one_bit(struct bn* a); 23 | static void _rshift_one_bit(struct bn* a); 24 | static void _lshift_word(struct bn* a, int nwords); 25 | static void _rshift_word(struct bn* a, int nwords); 26 | 27 | 28 | 29 | /* Public / Exported functions. */ 30 | void bignum_init(struct bn* n) 31 | { 32 | require(n, "n is null"); 33 | 34 | int i; 35 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 36 | { 37 | n->array[i] = 0; 38 | } 39 | } 40 | 41 | 42 | void bignum_from_int(struct bn* n, DTYPE_TMP i) 43 | { 44 | require(n, "n is null"); 45 | 46 | bignum_init(n); 47 | 48 | /* Endianness issue if machine is not little-endian? */ 49 | #ifdef WORD_SIZE 50 | #if (WORD_SIZE == 1) 51 | n->array[0] = (i & 0x000000ff); 52 | n->array[1] = (i & 0x0000ff00) >> 8; 53 | n->array[2] = (i & 0x00ff0000) >> 16; 54 | n->array[3] = (i & 0xff000000) >> 24; 55 | #elif (WORD_SIZE == 2) 56 | n->array[0] = (i & 0x0000ffff); 57 | n->array[1] = (i & 0xffff0000) >> 16; 58 | #elif (WORD_SIZE == 4) 59 | n->array[0] = i; 60 | DTYPE_TMP num_32 = 32; 61 | DTYPE_TMP tmp = i >> num_32; /* bit-shift with U64 operands to force 64-bit results */ 62 | n->array[1] = tmp; 63 | #endif 64 | #endif 65 | } 66 | 67 | 68 | int bignum_to_int(struct bn* n) 69 | { 70 | require(n, "n is null"); 71 | 72 | int ret = 0; 73 | 74 | /* Endianness issue if machine is not little-endian? */ 75 | #if (WORD_SIZE == 1) 76 | ret += n->array[0]; 77 | ret += n->array[1] << 8; 78 | ret += n->array[2] << 16; 79 | ret += n->array[3] << 24; 80 | #elif (WORD_SIZE == 2) 81 | ret += n->array[0]; 82 | ret += n->array[1] << 16; 83 | #elif (WORD_SIZE == 4) 84 | ret += n->array[0]; 85 | #endif 86 | 87 | return ret; 88 | } 89 | 90 | 91 | void bignum_from_string(struct bn* n, char* str, int nbytes) 92 | { 93 | require(n, "n is null"); 94 | require(str, "str is null"); 95 | require(nbytes > 0, "nbytes must be positive"); 96 | require((nbytes & 1) == 0, "string format must be in hex -> equal number of bytes"); 97 | require((nbytes % (sizeof(DTYPE) * 2)) == 0, "string length must be a multiple of (sizeof(DTYPE) * 2) characters"); 98 | 99 | bignum_init(n); 100 | 101 | DTYPE tmp; /* DTYPE is defined in bn.h - uint{8,16,32,64}_t */ 102 | int i = nbytes - (2 * WORD_SIZE); /* index into string */ 103 | int j = 0; /* index into array */ 104 | 105 | /* reading last hex-byte "MSB" from string first -> big endian */ 106 | /* MSB ~= most significant byte / block ? :) */ 107 | while (i >= 0) 108 | { 109 | tmp = 0; 110 | sscanf(&str[i], SSCANF_FORMAT_STR, &tmp); 111 | n->array[j] = tmp; 112 | i -= (2 * WORD_SIZE); /* step WORD_SIZE hex-byte(s) back in the string. */ 113 | j += 1; /* step one element forward in the array. */ 114 | } 115 | } 116 | 117 | 118 | void bignum_to_string(struct bn* n, char* str, int nbytes, bool leading_zeros) 119 | { 120 | require(n, "n is null"); 121 | require(str, "str is null"); 122 | require(nbytes > 0, "nbytes must be positive"); 123 | require((nbytes & 1) == 0, "string format must be in hex -> equal number of bytes"); 124 | 125 | int j = BN_ARRAY_SIZE - 1; /* index into array - reading "MSB" first -> big-endian */ 126 | int i = 0; /* index into string representation. */ 127 | 128 | /* reading last array-element "MSB" first -> big endian */ 129 | while ((j >= 0) && (nbytes > (i + 1))) 130 | { 131 | sprintf(&str[i], SPRINTF_FORMAT_STR, n->array[j]); 132 | i += (2 * WORD_SIZE); /* step WORD_SIZE hex-byte(s) forward in the string. */ 133 | j -= 1; /* step one element back in the array. */ 134 | } 135 | 136 | if( !leading_zeros ) 137 | { 138 | /* Count leading zeros: */ 139 | j = 0; 140 | while (str[j] == '0') 141 | { 142 | j += 1; 143 | } 144 | 145 | /* Move string j places ahead, effectively skipping leading zeros */ 146 | for (i = 0; i < (nbytes - j); ++i) 147 | { 148 | str[i] = str[i + j]; 149 | } 150 | } 151 | 152 | /* Zero-terminate string */ 153 | str[i] = 0; 154 | } 155 | 156 | 157 | void bignum_dec(struct bn* n) 158 | { 159 | require(n, "n is null"); 160 | 161 | DTYPE tmp; /* copy of n */ 162 | DTYPE res; 163 | 164 | int i; 165 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 166 | { 167 | tmp = n->array[i]; 168 | res = tmp - 1; 169 | n->array[i] = res; 170 | 171 | if (!(res > tmp)) 172 | { 173 | break; 174 | } 175 | } 176 | } 177 | 178 | 179 | void bignum_inc(struct bn* n) 180 | { 181 | require(n, "n is null"); 182 | 183 | DTYPE res; 184 | DTYPE_TMP tmp; /* copy of n */ 185 | 186 | int i; 187 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 188 | { 189 | tmp = n->array[i]; 190 | res = tmp + 1; 191 | n->array[i] = res; 192 | 193 | if (res > tmp) 194 | { 195 | break; 196 | } 197 | } 198 | } 199 | 200 | 201 | void bignum_add(struct bn* a, struct bn* b, struct bn* c) 202 | { 203 | require(a, "a is null"); 204 | require(b, "b is null"); 205 | require(c, "c is null"); 206 | 207 | DTYPE_TMP tmp; 208 | int carry = 0; 209 | int i; 210 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 211 | { 212 | tmp = (DTYPE_TMP)a->array[i] + b->array[i] + carry; 213 | carry = (tmp > MAX_VAL); 214 | c->array[i] = (tmp & MAX_VAL); 215 | } 216 | } 217 | 218 | 219 | void bignum_sub(struct bn* a, struct bn* b, struct bn* c) 220 | { 221 | require(a, "a is null"); 222 | require(b, "b is null"); 223 | require(c, "c is null"); 224 | 225 | DTYPE_TMP res; 226 | DTYPE_TMP tmp1; 227 | DTYPE_TMP tmp2; 228 | int borrow = 0; 229 | int i; 230 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 231 | { 232 | tmp1 = (DTYPE_TMP)a->array[i] + (MAX_VAL + 1); /* + number_base */ 233 | tmp2 = (DTYPE_TMP)b->array[i] + borrow;; 234 | res = (tmp1 - tmp2); 235 | c->array[i] = (DTYPE)(res & MAX_VAL); /* "modulo number_base" == "% (number_base - 1)" if number_base is 2^N */ 236 | borrow = (res <= MAX_VAL); 237 | } 238 | } 239 | 240 | 241 | void bignum_mul(struct bn* a, struct bn* b, struct bn* c) 242 | { 243 | require(a, "a is null"); 244 | require(b, "b is null"); 245 | require(c, "c is null"); 246 | 247 | struct bn row; 248 | struct bn tmp; 249 | int i, j; 250 | 251 | bignum_init(c); 252 | 253 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 254 | { 255 | bignum_init(&row); 256 | 257 | for (j = 0; j < BN_ARRAY_SIZE; ++j) 258 | { 259 | if (i + j < BN_ARRAY_SIZE) 260 | { 261 | bignum_init(&tmp); 262 | DTYPE_TMP intermediate = ((DTYPE_TMP)a->array[i] * (DTYPE_TMP)b->array[j]); 263 | bignum_from_int(&tmp, intermediate); 264 | _lshift_word(&tmp, i + j); 265 | bignum_add(&tmp, &row, &row); 266 | } 267 | } 268 | bignum_add(c, &row, c); 269 | } 270 | } 271 | 272 | 273 | void bignum_div(struct bn* a, struct bn* b, struct bn* c) 274 | { 275 | require(a, "a is null"); 276 | require(b, "b is null"); 277 | require(c, "c is null"); 278 | 279 | struct bn current; 280 | struct bn denom; 281 | struct bn tmp; 282 | 283 | bignum_from_int(¤t, 1); // int current = 1; 284 | bignum_assign(&denom, b); // denom = b 285 | bignum_assign(&tmp, a); // tmp = a 286 | 287 | const DTYPE_TMP half_max = 1 + (DTYPE_TMP)(MAX_VAL / 2); 288 | bool overflow = false; 289 | while (bignum_cmp(&denom, a) != LARGER) // while (denom <= a) { 290 | { 291 | if (denom.array[BN_ARRAY_SIZE - 1] >= half_max) 292 | { 293 | overflow = true; 294 | break; 295 | } 296 | _lshift_one_bit(¤t); // current <<= 1; 297 | _lshift_one_bit(&denom); // denom <<= 1; 298 | } 299 | if (!overflow) 300 | { 301 | _rshift_one_bit(&denom); // denom >>= 1; 302 | _rshift_one_bit(¤t); // current >>= 1; 303 | } 304 | bignum_init(c); // int answer = 0; 305 | 306 | while (!bignum_is_zero(¤t)) // while (current != 0) 307 | { 308 | if (bignum_cmp(&tmp, &denom) != SMALLER) // if (dividend >= denom) 309 | { 310 | bignum_sub(&tmp, &denom, &tmp); // dividend -= denom; 311 | bignum_or(c, ¤t, c); // answer |= current; 312 | } 313 | _rshift_one_bit(¤t); // current >>= 1; 314 | _rshift_one_bit(&denom); // denom >>= 1; 315 | } // return answer; 316 | } 317 | 318 | 319 | void bignum_lshift(struct bn* a, struct bn* b, int nbits) 320 | { 321 | require(a, "a is null"); 322 | require(b, "b is null"); 323 | require(nbits >= 0, "no negative shifts"); 324 | 325 | bignum_assign(b, a); 326 | /* Handle shift in multiples of word-size */ 327 | const int nbits_pr_word = (WORD_SIZE * 8); 328 | int nwords = nbits / nbits_pr_word; 329 | if (nwords != 0) 330 | { 331 | _lshift_word(b, nwords); 332 | nbits -= (nwords * nbits_pr_word); 333 | } 334 | 335 | if (nbits != 0) 336 | { 337 | int i; 338 | for (i = (BN_ARRAY_SIZE - 1); i > 0; --i) 339 | { 340 | b->array[i] = (b->array[i] << nbits) | (b->array[i - 1] >> ((8 * WORD_SIZE) - nbits)); 341 | } 342 | b->array[i] <<= nbits; 343 | } 344 | } 345 | 346 | 347 | void bignum_rshift(struct bn* a, struct bn* b, int nbits) 348 | { 349 | require(a, "a is null"); 350 | require(b, "b is null"); 351 | require(nbits >= 0, "no negative shifts"); 352 | 353 | bignum_assign(b, a); 354 | /* Handle shift in multiples of word-size */ 355 | const int nbits_pr_word = (WORD_SIZE * 8); 356 | int nwords = nbits / nbits_pr_word; 357 | if (nwords != 0) 358 | { 359 | _rshift_word(b, nwords); 360 | nbits -= (nwords * nbits_pr_word); 361 | } 362 | 363 | if (nbits != 0) 364 | { 365 | int i; 366 | for (i = 0; i < (BN_ARRAY_SIZE - 1); ++i) 367 | { 368 | b->array[i] = (b->array[i] >> nbits) | (b->array[i + 1] << ((8 * WORD_SIZE) - nbits)); 369 | } 370 | b->array[i] >>= nbits; 371 | } 372 | 373 | } 374 | 375 | 376 | void bignum_mod(struct bn* a, struct bn* b, struct bn* c) 377 | { 378 | /* 379 | Take divmod and throw away div part 380 | */ 381 | require(a, "a is null"); 382 | require(b, "b is null"); 383 | require(c, "c is null"); 384 | 385 | struct bn tmp; 386 | 387 | bignum_divmod(a,b,&tmp,c); 388 | } 389 | 390 | void bignum_divmod(struct bn* a, struct bn* b, struct bn* c, struct bn* d) 391 | { 392 | /* 393 | Puts a%b in d 394 | and a/b in c 395 | mod(a,b) = a - ((a / b) * b) 396 | example: 397 | mod(8, 3) = 8 - ((8 / 3) * 3) = 2 398 | */ 399 | require(a, "a is null"); 400 | require(b, "b is null"); 401 | require(c, "c is null"); 402 | 403 | struct bn tmp; 404 | 405 | /* c = (a / b) */ 406 | bignum_div(a, b, c); 407 | 408 | /* tmp = (c * b) */ 409 | bignum_mul(c, b, &tmp); 410 | 411 | /* c = a - tmp */ 412 | bignum_sub(a, &tmp, d); 413 | } 414 | 415 | 416 | void bignum_and(struct bn* a, struct bn* b, struct bn* c) 417 | { 418 | require(a, "a is null"); 419 | require(b, "b is null"); 420 | require(c, "c is null"); 421 | 422 | int i; 423 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 424 | { 425 | c->array[i] = (a->array[i] & b->array[i]); 426 | } 427 | } 428 | 429 | 430 | void bignum_or(struct bn* a, struct bn* b, struct bn* c) 431 | { 432 | require(a, "a is null"); 433 | require(b, "b is null"); 434 | require(c, "c is null"); 435 | 436 | int i; 437 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 438 | { 439 | c->array[i] = (a->array[i] | b->array[i]); 440 | } 441 | } 442 | 443 | 444 | void bignum_xor(struct bn* a, struct bn* b, struct bn* c) 445 | { 446 | require(a, "a is null"); 447 | require(b, "b is null"); 448 | require(c, "c is null"); 449 | 450 | int i; 451 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 452 | { 453 | c->array[i] = (a->array[i] ^ b->array[i]); 454 | } 455 | } 456 | 457 | 458 | int bignum_cmp(struct bn* a, struct bn* b) 459 | { 460 | require(a, "a is null"); 461 | require(b, "b is null"); 462 | 463 | int i = BN_ARRAY_SIZE; 464 | do 465 | { 466 | i -= 1; /* Decrement first, to start with last array element */ 467 | if (a->array[i] > b->array[i]) 468 | { 469 | return LARGER; 470 | } 471 | else if (a->array[i] < b->array[i]) 472 | { 473 | return SMALLER; 474 | } 475 | } 476 | while (i != 0); 477 | 478 | return EQUAL; 479 | } 480 | 481 | 482 | int bignum_is_zero(struct bn* n) 483 | { 484 | require(n, "n is null"); 485 | 486 | int i; 487 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 488 | { 489 | if (n->array[i]) 490 | { 491 | return 0; 492 | } 493 | } 494 | 495 | return 1; 496 | } 497 | 498 | 499 | void bignum_pow(struct bn* a, struct bn* b, struct bn* c) 500 | { 501 | require(a, "a is null"); 502 | require(b, "b is null"); 503 | require(c, "c is null"); 504 | 505 | struct bn tmp; 506 | 507 | bignum_init(c); 508 | 509 | if (bignum_cmp(b, c) == EQUAL) 510 | { 511 | /* Return 1 when exponent is 0 -- n^0 = 1 */ 512 | bignum_inc(c); 513 | } 514 | else 515 | { 516 | struct bn bcopy; 517 | bignum_assign(&bcopy, b); 518 | 519 | /* Copy a -> tmp */ 520 | bignum_assign(&tmp, a); 521 | 522 | bignum_dec(&bcopy); 523 | 524 | /* Begin summing products: */ 525 | while (!bignum_is_zero(&bcopy)) 526 | { 527 | 528 | /* c = tmp * tmp */ 529 | bignum_mul(&tmp, a, c); 530 | /* Decrement b by one */ 531 | bignum_dec(&bcopy); 532 | 533 | bignum_assign(&tmp, c); 534 | } 535 | 536 | /* c = tmp */ 537 | bignum_assign(c, &tmp); 538 | } 539 | } 540 | 541 | void bignum_isqrt(struct bn *a, struct bn* b) 542 | { 543 | require(a, "a is null"); 544 | require(b, "b is null"); 545 | 546 | struct bn low, high, mid, tmp; 547 | 548 | bignum_init(&low); 549 | bignum_assign(&high, a); 550 | bignum_rshift(&high, &mid, 1); 551 | bignum_inc(&mid); 552 | 553 | while (bignum_cmp(&high, &low) > 0) 554 | { 555 | bignum_mul(&mid, &mid, &tmp); 556 | if (bignum_cmp(&tmp, a) > 0) 557 | { 558 | bignum_assign(&high, &mid); 559 | bignum_dec(&high); 560 | } 561 | else 562 | { 563 | bignum_assign(&low, &mid); 564 | } 565 | bignum_sub(&high,&low,&mid); 566 | _rshift_one_bit(&mid); 567 | bignum_add(&low,&mid,&mid); 568 | bignum_inc(&mid); 569 | } 570 | bignum_assign(b,&low); 571 | } 572 | 573 | 574 | void bignum_assign(struct bn* dst, struct bn* src) 575 | { 576 | require(dst, "dst is null"); 577 | require(src, "src is null"); 578 | 579 | int i; 580 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 581 | { 582 | dst->array[i] = src->array[i]; 583 | } 584 | } 585 | 586 | 587 | void bignum_endian_swap(struct bn* n ) 588 | { 589 | #ifdef WORD_SIZE 590 | int i; 591 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 592 | { 593 | #if (WORD_SIZE == 1) 594 | /* Do nothing, already endianness doesn't matter */ 595 | #elif (WORD_SIZE == 2) 596 | n->array[i] = ((n->array[i] << 8) & 0xff00 ) | // Move byte 0 to byte 1 597 | ((n->array[i] >> 8) & 0x00ff ); // Move byte 1 to byte 0 598 | #elif (WORD_SIZE == 4) 599 | n->array[i] = ((n->array[i] << 24) & 0xff000000 ) | // Move byte 0 to byte 3 600 | ((n->array[i] << 8) & 0x00ff0000 ) | // Move byte 1 to byte 2 601 | ((n->array[i] >> 8) & 0x0000ff00 ) | // Move byte 2 to byte 1 602 | ((n->array[i] >> 24) & 0x000000ff ); // Move byte 3 to byte 0 603 | #endif 604 | } 605 | 606 | for (i = 0; i < BN_ARRAY_SIZE / 2; ++i ) 607 | { 608 | // Swap n->array[i] and n->array[BN_ARRAY_SIZE - i - 1] 609 | n->array[i] ^= n->array[BN_ARRAY_SIZE - i - 1]; 610 | n->array[BN_ARRAY_SIZE - i - 1] ^= n->array[i]; 611 | n->array[i] ^= n->array[BN_ARRAY_SIZE - i - 1]; 612 | } 613 | #endif 614 | } 615 | 616 | 617 | /* Private / Static functions. */ 618 | static void _rshift_word(struct bn* a, int nwords) 619 | { 620 | /* Naive method: */ 621 | require(a, "a is null"); 622 | require(nwords >= 0, "no negative shifts"); 623 | 624 | int i; 625 | if (nwords >= BN_ARRAY_SIZE) 626 | { 627 | for (i = 0; i < BN_ARRAY_SIZE; ++i) 628 | { 629 | a->array[i] = 0; 630 | } 631 | return; 632 | } 633 | 634 | for (i = 0; i < BN_ARRAY_SIZE - nwords; ++i) 635 | { 636 | a->array[i] = a->array[i + nwords]; 637 | } 638 | for (; i < BN_ARRAY_SIZE; ++i) 639 | { 640 | a->array[i] = 0; 641 | } 642 | } 643 | 644 | 645 | static void _lshift_word(struct bn* a, int nwords) 646 | { 647 | require(a, "a is null"); 648 | require(nwords >= 0, "no negative shifts"); 649 | 650 | int i; 651 | /* Shift whole words */ 652 | for (i = (BN_ARRAY_SIZE - 1); i >= nwords; --i) 653 | { 654 | a->array[i] = a->array[i - nwords]; 655 | } 656 | /* Zero pad shifted words. */ 657 | for (; i >= 0; --i) 658 | { 659 | a->array[i] = 0; 660 | } 661 | } 662 | 663 | 664 | static void _lshift_one_bit(struct bn* a) 665 | { 666 | require(a, "a is null"); 667 | 668 | int i; 669 | for (i = (BN_ARRAY_SIZE - 1); i > 0; --i) 670 | { 671 | a->array[i] = (a->array[i] << 1) | (a->array[i - 1] >> ((8 * WORD_SIZE) - 1)); 672 | } 673 | a->array[0] <<= 1; 674 | } 675 | 676 | 677 | static void _rshift_one_bit(struct bn* a) 678 | { 679 | require(a, "a is null"); 680 | 681 | int i; 682 | for (i = 0; i < (BN_ARRAY_SIZE - 1); ++i) 683 | { 684 | a->array[i] = (a->array[i] >> 1) | (a->array[i + 1] << ((8 * WORD_SIZE) - 1)); 685 | } 686 | a->array[BN_ARRAY_SIZE - 1] >>= 1; 687 | } 688 | -------------------------------------------------------------------------------- /miner/main.c: -------------------------------------------------------------------------------- 1 | 2 | #include "bn.h" 3 | #include "keccak256.h" 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #ifdef _WIN32 14 | #include 15 | #include 16 | #else 17 | #include 18 | #endif 19 | 20 | #define WORD_BUFFER_BYTES (2 << 20) // 2 MB 21 | #define WORD_BUFFER_LENGTH (WORD_BUFFER_BYTES / sizeof(struct bn)) 22 | 23 | #define SAMPLE_INDICES 10 24 | #define READ_BUFSIZE 1024 25 | #define ETH_HASH_SIZE 66 26 | #define ETH_ADDRESS_SIZE 42 27 | #define PERCENT_100 10000 28 | 29 | #define THREAD_ITERATIONS 600000 30 | 31 | #define HASH_REPORT_THRESHOLD 1 32 | 33 | int to_hex_string( unsigned char* n, unsigned char* dest, int len ) 34 | { 35 | static const char hex[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 36 | 37 | for( int i = 0; i < len; i++ ) 38 | { 39 | dest[2 * i] = hex[(n[i] & 0xF0) >> 4]; 40 | dest[2 * i + 1] = hex[n[i] & 0x0F]; 41 | } 42 | 43 | return len * 2; 44 | } 45 | 46 | bool is_hex_prefixed( char* str ) 47 | { 48 | return str[0] == '0' && str[1] == 'x'; 49 | } 50 | 51 | uint32_t coprimes[10]; 52 | 53 | uint32_t bignum_mod_small( struct bn* b, uint32_t m ) 54 | { 55 | // Compute b % m 56 | uint64_t tmp = 0; 57 | size_t i; 58 | for( int i=BN_ARRAY_SIZE-1; i>=0; i-- ) 59 | { 60 | tmp = (tmp << 32) | b->array[i]; 61 | tmp %= m; 62 | } 63 | return (uint32_t) tmp; 64 | } 65 | 66 | void bignum_add_small( struct bn* b, uint32_t n ) 67 | { 68 | 69 | uint32_t tmp = b->array[0]; 70 | b->array[0] += n; 71 | int i = 0; 72 | while( i < BN_ARRAY_SIZE - 1 && tmp > b->array[i] ) 73 | { 74 | tmp = b->array[i+1]; 75 | b->array[i+1]++; 76 | i++; 77 | } 78 | } 79 | 80 | void init_work_constants() 81 | { 82 | size_t i; 83 | 84 | coprimes[0] = 0x0000fffd; 85 | coprimes[1] = 0x0000fffb; 86 | coprimes[2] = 0x0000fff7; 87 | coprimes[3] = 0x0000fff1; 88 | coprimes[4] = 0x0000ffef; 89 | coprimes[5] = 0x0000ffe5; 90 | coprimes[6] = 0x0000ffdf; 91 | coprimes[7] = 0x0000ffd9; 92 | coprimes[8] = 0x0000ffd3; 93 | coprimes[9] = 0x0000ffd1; 94 | } 95 | 96 | struct work_data 97 | { 98 | uint32_t x[10]; 99 | }; 100 | 101 | void init_work_data( struct work_data* wdata, struct bn* secured_struct_hash ) 102 | { 103 | size_t i; 104 | struct bn x; 105 | for( i=0; i<10; i++ ) 106 | { 107 | wdata->x[i] = bignum_mod_small( secured_struct_hash, coprimes[i] ); 108 | } 109 | } 110 | 111 | /* 112 | * Solidity definition: 113 | * 114 | * address[] memory recipients, 115 | * uint256[] memory split_percents, 116 | * uint256 recent_eth_block_number, 117 | * uint256 recent_eth_block_hash, 118 | * uint256 target, 119 | * uint256 pow_height 120 | */ 121 | struct secured_struct 122 | { 123 | struct bn miner_address; 124 | struct bn oo_address; 125 | struct bn miner_percent; 126 | struct bn oo_percent; 127 | struct bn recent_eth_block_number; 128 | struct bn recent_eth_block_hash; 129 | struct bn target; 130 | struct bn pow_height; 131 | }; 132 | 133 | struct input_data 134 | { 135 | char miner_address[ETH_ADDRESS_SIZE + 1]; 136 | char tip_address[ETH_ADDRESS_SIZE + 1]; 137 | char block_hash[ETH_HASH_SIZE + 1]; 138 | uint64_t block_num; 139 | char difficulty_str[ETH_HASH_SIZE + 1]; 140 | uint64_t tip; 141 | uint64_t pow_height; 142 | uint64_t thread_iterations; 143 | uint64_t hash_limit; 144 | char nonce_offset[ETH_HASH_SIZE + 1]; 145 | }; 146 | 147 | void read_data( struct input_data* d ) 148 | { 149 | char buf[READ_BUFSIZE] = { '\0' }; 150 | 151 | int i = 0; 152 | do 153 | { 154 | int c; 155 | while ((c = getchar()) != '\n' && c != EOF) 156 | { 157 | if ( i < READ_BUFSIZE ) 158 | { 159 | buf[i++] = c; 160 | } 161 | else 162 | { 163 | fprintf(stderr, "[C] Buffer was about to overflow!"); 164 | } 165 | } 166 | } while ( strlen(buf) == 0 || buf[strlen(buf)-1] != ';' ); 167 | 168 | fprintf(stderr, "[C] Buffer: %s\n", buf); 169 | sscanf(buf, "%42s %42s %66s %" SCNu64 " %66s %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %66s", 170 | d->miner_address, 171 | d->tip_address, 172 | d->block_hash, 173 | &d->block_num, 174 | d->difficulty_str, 175 | &d->tip, 176 | &d->pow_height, 177 | &d->thread_iterations, 178 | &d->hash_limit, 179 | d->nonce_offset); 180 | 181 | fprintf(stderr, "[C] Miner address: %s\n", d->miner_address); 182 | fprintf(stderr, "[C] Tip address: %s\n", d->tip_address); 183 | fprintf(stderr, "[C] Ethereum Block Hash: %s\n", d->block_hash ); 184 | fprintf(stderr, "[C] Ethereum Block Number: %" PRIu64 "\n", d->block_num ); 185 | fprintf(stderr, "[C] Difficulty Target: %s\n", d->difficulty_str ); 186 | fprintf(stderr, "[C] OpenOrchard Tip: %" PRIu64 "\n", d->tip ); 187 | fprintf(stderr, "[C] PoW Height: %" PRIu64 "\n", d->pow_height ); 188 | fprintf(stderr, "[C] Thread Iterations: %" PRIu64 "\n", d->thread_iterations ); 189 | fprintf(stderr, "[C] Hash Limit: %" PRIu64 "\n", d->hash_limit ); 190 | fprintf(stderr, "[C] Nonce Offset: %s\n", d->nonce_offset ); 191 | fflush(stderr); 192 | } 193 | 194 | 195 | void hash_secured_struct( struct bn* res, struct secured_struct* ss ) 196 | { 197 | /* Solidity ABI encodes as follows: 198 | * 199 | * Offset pointer to recipient array (256 bits big endian) 200 | * Offset pointer to split_perecents array (256 bits big endian) 201 | * recent_eth_block_number (256 bit big endian) 202 | * recent_eth_block_hash (256 bit big endian) 203 | * target (256 bit big endian) 204 | * pow_height (256 bit big endian) 205 | * size of recipient array (256 bit big endian) 206 | * miner_address 207 | * oo_address 208 | * size of split_percent_array (256 bit big endian) 209 | * miner_percent 210 | * recipient_offset 211 | */ 212 | 213 | struct bn recipient_offset, split_percent_offset, array_size; 214 | bignum_from_int( &recipient_offset, 6 * 32 ); 215 | bignum_endian_swap( &recipient_offset ); 216 | bignum_from_int( &split_percent_offset, 9 * 32 ); 217 | bignum_endian_swap( &split_percent_offset ); 218 | bignum_from_int( &array_size, 2 ); 219 | bignum_endian_swap( &array_size ); 220 | 221 | bignum_endian_swap( &ss->target ); 222 | 223 | SHA3_CTX c; 224 | keccak_init( &c ); 225 | keccak_update( &c, (unsigned char*)&recipient_offset, sizeof(struct bn) ); 226 | keccak_update( &c, (unsigned char*)&split_percent_offset, sizeof(struct bn) ); 227 | keccak_update( &c, (unsigned char*)&ss->recent_eth_block_number, sizeof(struct bn) ); 228 | keccak_update( &c, (unsigned char*)&ss->recent_eth_block_hash, sizeof(struct bn) ); 229 | keccak_update( &c, (unsigned char*)&ss->target, sizeof(struct bn) ); 230 | keccak_update( &c, (unsigned char*)&ss->pow_height, sizeof(struct bn) ); 231 | keccak_update( &c, (unsigned char*)&array_size, sizeof(struct bn) ); 232 | keccak_update( &c, (unsigned char*)&ss->miner_address, sizeof(struct bn) ); 233 | keccak_update( &c, (unsigned char*)&ss->oo_address, sizeof(struct bn) ); 234 | keccak_update( &c, (unsigned char*)&array_size, sizeof(struct bn) ); 235 | keccak_update( &c, (unsigned char*)&ss->miner_percent, sizeof(struct bn) ); 236 | keccak_update( &c, (unsigned char*)&ss->oo_percent, sizeof(struct bn) ); 237 | keccak_final( &c, (unsigned char*)res ); 238 | 239 | bignum_endian_swap( res ); 240 | bignum_endian_swap( &ss->target ); 241 | } 242 | 243 | 244 | void find_word( struct bn* result, uint32_t x, uint32_t* coefficients, struct bn* word_buffer ) 245 | { 246 | uint64_t y = coefficients[4]; 247 | y *= x; 248 | y += coefficients[3]; 249 | y %= WORD_BUFFER_LENGTH - 1; 250 | y *= x; 251 | y += coefficients[2]; 252 | y %= WORD_BUFFER_LENGTH - 1; 253 | y *= x; 254 | y += coefficients[1]; 255 | y %= WORD_BUFFER_LENGTH - 1; 256 | y *= x; 257 | y += coefficients[0]; 258 | y %= WORD_BUFFER_LENGTH - 1; 259 | bignum_assign( result, word_buffer + y ); 260 | } 261 | 262 | 263 | void find_and_xor_word( struct bn* result, uint32_t x, uint32_t* coefficients, struct bn* word_buffer ) 264 | { 265 | uint64_t y = coefficients[4]; 266 | y *= x; 267 | y += coefficients[3]; 268 | y %= WORD_BUFFER_LENGTH - 1; 269 | y *= x; 270 | y += coefficients[2]; 271 | y %= WORD_BUFFER_LENGTH - 1; 272 | y *= x; 273 | y += coefficients[1]; 274 | y %= WORD_BUFFER_LENGTH - 1; 275 | y *= x; 276 | y += coefficients[0]; 277 | y %= WORD_BUFFER_LENGTH - 1; 278 | bignum_xor( result, word_buffer + y, result ); 279 | } 280 | 281 | 282 | void work( struct bn* result, struct bn* secured_struct_hash, struct bn* nonce, struct bn* word_buffer ) 283 | { 284 | struct work_data wdata; 285 | init_work_data( &wdata, secured_struct_hash ); 286 | 287 | bignum_assign( result, secured_struct_hash ); // result = secured_struct_hash; 288 | 289 | uint32_t coefficients[5]; 290 | 291 | int i; 292 | for( i = 0; i < sizeof(coefficients) / sizeof(uint32_t); ++i ) 293 | { 294 | coefficients[i] = 1 + bignum_mod_small( nonce, coprimes[i] ); 295 | } 296 | 297 | for( i = 0; i < sizeof(coprimes) / sizeof(uint32_t); ++i ) 298 | { 299 | find_and_xor_word( result, wdata.x[i], coefficients, word_buffer ); 300 | } 301 | } 302 | 303 | 304 | int words_are_unique( struct bn* secured_struct_hash, struct bn* nonce, struct bn* word_buffer ) 305 | { 306 | struct work_data wdata; 307 | struct bn w[sizeof(coprimes) / sizeof(uint32_t)]; 308 | init_work_data( &wdata, secured_struct_hash ); 309 | 310 | uint32_t coefficients[5]; 311 | 312 | int i, j; 313 | for( i = 0; i < sizeof(coefficients) / sizeof(uint32_t); ++i ) 314 | { 315 | coefficients[i] = 1 + bignum_mod_small( nonce, coprimes[i] ); 316 | } 317 | 318 | for( i = 0; i < sizeof(coprimes) / sizeof(uint32_t); ++i ) 319 | { 320 | find_word( w+i, wdata.x[i], coefficients, word_buffer ); 321 | for( j = 0; j < i; j++ ) 322 | { 323 | if( bignum_cmp( w+i, w+j ) == 0 ) 324 | return 0; 325 | } 326 | } 327 | return 1; 328 | } 329 | 330 | 331 | int main( int argc, char** argv ) 332 | { 333 | #ifdef _WIN32 334 | _setmode( _fileno( stdin ), _O_BINARY ); 335 | #endif 336 | 337 | struct bn* word_buffer = malloc( WORD_BUFFER_BYTES ); 338 | struct bn seed, bn_i; 339 | 340 | char bn_str[78]; 341 | 342 | SHA3_CTX c; 343 | 344 | struct secured_struct ss; 345 | 346 | init_work_constants(); 347 | 348 | bignum_init( &seed ); 349 | 350 | while ( true ) 351 | { 352 | struct input_data input; 353 | 354 | read_data( &input ); 355 | 356 | if( is_hex_prefixed( input.miner_address ) ) 357 | { 358 | bignum_from_string( &ss.miner_address, input.miner_address + 2, strlen(input.miner_address) - 2 ); 359 | } 360 | else 361 | { 362 | bignum_from_string( &ss.miner_address, input.miner_address , strlen(input.miner_address) ); 363 | } 364 | 365 | if( is_hex_prefixed( input.tip_address ) ) 366 | { 367 | bignum_from_string( &ss.oo_address, input.tip_address + 2, strlen(input.tip_address) - 2 ); 368 | } 369 | else 370 | { 371 | bignum_from_string( &ss.oo_address, input.tip_address, strlen(input.tip_address) ); 372 | } 373 | 374 | bignum_to_string( &ss.miner_address, bn_str, sizeof(bn_str), false ); 375 | fprintf(stderr, "[C] Miner Address: %s\n", bn_str); 376 | 377 | bignum_to_string( &ss.oo_address, bn_str, sizeof(bn_str), false ); 378 | fprintf(stderr, "[C] OpenOrchard Address: %s\n", bn_str); 379 | fflush(stderr); 380 | 381 | bignum_endian_swap( &ss.miner_address ); 382 | bignum_endian_swap( &ss.oo_address ); 383 | 384 | uint64_t miner_pay = PERCENT_100 - input.tip; 385 | uint64_t oo_pay = input.tip; 386 | 387 | fprintf(stderr, "[C] Miner pay: %" PRIu64 "\n", miner_pay); 388 | fprintf(stderr, "[C] OpenOrchard tip: %" PRIu64 "\n", oo_pay); 389 | 390 | bignum_from_int( &ss.miner_percent, PERCENT_100 - input.tip ); 391 | bignum_endian_swap( &ss.miner_percent ); 392 | bignum_from_int( &ss.oo_percent, input.tip ); 393 | bignum_endian_swap( &ss.oo_percent ); 394 | bignum_from_int( &ss.recent_eth_block_number, input.block_num ); 395 | bignum_endian_swap( &ss.recent_eth_block_number ); 396 | 397 | if( is_hex_prefixed( input.block_hash ) ) 398 | { 399 | bignum_from_string( &ss.recent_eth_block_hash, input.block_hash + 2, ETH_HASH_SIZE - 2 ); 400 | } 401 | else 402 | { 403 | bignum_from_string( &ss.recent_eth_block_hash, input.block_hash, ETH_HASH_SIZE - 2 ); 404 | } 405 | 406 | bignum_endian_swap( &ss.recent_eth_block_hash ); 407 | 408 | if( is_hex_prefixed( input.difficulty_str ) ) 409 | { 410 | bignum_from_string( &ss.target, input.difficulty_str + 2, ETH_HASH_SIZE - 2 ); 411 | } 412 | else 413 | { 414 | bignum_from_string( &ss.target, input.difficulty_str, ETH_HASH_SIZE - 2 ); 415 | } 416 | 417 | bignum_from_int( &ss.pow_height, input.pow_height ); 418 | bignum_endian_swap( &ss.pow_height ); 419 | 420 | if( bignum_cmp( &seed, &ss.recent_eth_block_hash ) ) 421 | { 422 | bignum_assign( &seed, &ss.recent_eth_block_hash ); 423 | // Procedurally generate word buffer w[i] from a seed 424 | // Each word buffer element is computed by w[i] = H(seed, i) 425 | for( unsigned long i = 0; i < WORD_BUFFER_LENGTH; i++ ) 426 | { 427 | keccak_init( &c ); 428 | keccak_update( &c, (unsigned char*)&seed, sizeof(seed) ); 429 | bignum_from_int( &bn_i, i ); 430 | bignum_endian_swap( &bn_i ); 431 | keccak_update( &c, (unsigned char*)&bn_i, sizeof(struct bn) ); 432 | keccak_final( &c, (unsigned char*)(word_buffer + i) ); 433 | bignum_endian_swap( word_buffer + i ); 434 | } 435 | } 436 | 437 | bignum_to_string( &seed, bn_str, sizeof(bn_str), true ); 438 | fprintf(stderr, "[C] Seed: %s\n", bn_str); 439 | 440 | bignum_to_string( &ss.target, bn_str, sizeof(bn_str), true ); 441 | fprintf(stderr, "[C] Difficulty Target: %s\n", bn_str); 442 | fflush(stderr); 443 | 444 | struct bn secured_struct_hash; 445 | hash_secured_struct( &secured_struct_hash, &ss ); 446 | 447 | bignum_to_string( &secured_struct_hash, bn_str, sizeof(bn_str), true); 448 | fprintf(stderr, "[C] Secured Struct Hash: %s\n", bn_str ); 449 | 450 | struct bn nonce; 451 | bignum_assign( &nonce, &ss.recent_eth_block_hash ); 452 | bignum_endian_swap( &nonce ); 453 | 454 | struct bn nonce_offset; 455 | if( is_hex_prefixed( input.nonce_offset ) ) 456 | { 457 | bignum_from_string( &nonce_offset, input.nonce_offset + 2, ETH_HASH_SIZE - 2 ); 458 | } 459 | else 460 | { 461 | bignum_from_string( &nonce_offset, input.nonce_offset, ETH_HASH_SIZE - 2 ); 462 | } 463 | bignum_add( &nonce, &nonce_offset, &nonce ); 464 | 465 | bignum_to_string( &nonce, bn_str, sizeof(bn_str), true ); 466 | fprintf(stderr, "[C] Starting Nonce: %s\n", bn_str ); 467 | 468 | struct bn result, t_nonce, t_result, s_nonce; 469 | bool stop = false; 470 | 471 | bignum_assign( &s_nonce, &nonce ); 472 | uint32_t hash_report_counter = 0; 473 | time_t timer; 474 | struct tm* timeinfo; 475 | char time_str[20]; 476 | 477 | uint64_t hashes = 0; 478 | 479 | bignum_init( &result ); 480 | 481 | #pragma omp parallel private(t_nonce, t_result) 482 | { 483 | while( !stop && hashes <= input.hash_limit ) 484 | { 485 | #pragma omp critical 486 | { 487 | if( omp_get_thread_num() == 0 ) 488 | { 489 | if( hash_report_counter >= HASH_REPORT_THRESHOLD ) 490 | { 491 | time( &timer ); 492 | timeinfo = localtime( &timer ); 493 | strftime( time_str, sizeof(time_str), "%FT%T", timeinfo ); 494 | fprintf( stdout, "H:%s %" PRId64 ";\n", time_str, hashes ); 495 | fflush( stdout ); 496 | hash_report_counter = 0; 497 | } 498 | else 499 | { 500 | hash_report_counter++; 501 | } 502 | 503 | } 504 | bignum_assign( &t_nonce, &s_nonce ); 505 | bignum_add_small( &s_nonce, input.thread_iterations ); 506 | hashes += input.thread_iterations; 507 | } 508 | 509 | for( uint64_t i = 0; i < input.thread_iterations && !stop; i++ ) 510 | { 511 | work( &t_result, &secured_struct_hash, &t_nonce, word_buffer ); 512 | 513 | if( bignum_cmp( &t_result, &ss.target ) <= 0) 514 | { 515 | if( !words_are_unique( &secured_struct_hash, &t_nonce, word_buffer ) ) 516 | { 517 | // Non-unique, do nothing 518 | // This is normal 519 | fprintf( stderr, "[C] Possible proof failed uniqueness check\n"); 520 | bignum_inc( &t_nonce ); 521 | } 522 | else 523 | { 524 | #pragma omp critical 525 | { 526 | // Two threads could find a valid proof at the same time (unlikely, but possible). 527 | // We want to return the more difficult proof 528 | if( !stop ) 529 | { 530 | stop = true; 531 | bignum_assign( &result, &t_result ); 532 | bignum_assign( &nonce, &t_nonce ); 533 | } 534 | else if( bignum_cmp( &t_result, &result ) < 0 ) 535 | { 536 | bignum_assign( &result, &t_result ); 537 | bignum_assign( &nonce, &t_nonce ); 538 | } 539 | } 540 | } 541 | } 542 | else 543 | bignum_inc( &t_nonce ); 544 | } 545 | } 546 | } 547 | 548 | if( bignum_is_zero( &result ) ) 549 | { 550 | fprintf( stdout, "F:1;\n" ); 551 | 552 | fprintf(stderr, "[C] Finished without nonce\n"); 553 | fflush(stderr); 554 | } 555 | else 556 | { 557 | bignum_to_string( &nonce, bn_str, sizeof(bn_str), false ); 558 | fprintf( stdout, "N:%s;\n", bn_str ); 559 | 560 | fprintf(stderr, "[C] Nonce: %s\n", bn_str); 561 | fflush(stderr); 562 | } 563 | 564 | fflush( stdout ); 565 | } 566 | } 567 | -------------------------------------------------------------------------------- /abi.js: -------------------------------------------------------------------------------- 1 | let abi = 2 | [ 3 | { 4 | "inputs": [ 5 | { 6 | "internalType": "address", 7 | "name": "tok", 8 | "type": "address" 9 | }, 10 | { 11 | "internalType": "uint256", 12 | "name": "start_t", 13 | "type": "uint256" 14 | }, 15 | { 16 | "internalType": "uint256", 17 | "name": "start_hc_reserve", 18 | "type": "uint256" 19 | }, 20 | { 21 | "internalType": "bool", 22 | "name": "testing", 23 | "type": "bool" 24 | } 25 | ], 26 | "stateMutability": "nonpayable", 27 | "type": "constructor" 28 | }, 29 | { 30 | "anonymous": false, 31 | "inputs": [ 32 | { 33 | "indexed": false, 34 | "internalType": "address[]", 35 | "name": "recipients", 36 | "type": "address[]" 37 | }, 38 | { 39 | "indexed": false, 40 | "internalType": "uint256[]", 41 | "name": "split_percents", 42 | "type": "uint256[]" 43 | }, 44 | { 45 | "indexed": false, 46 | "internalType": "uint256", 47 | "name": "hc_submit", 48 | "type": "uint256" 49 | }, 50 | { 51 | "indexed": false, 52 | "internalType": "uint256", 53 | "name": "hc_decay", 54 | "type": "uint256" 55 | }, 56 | { 57 | "indexed": false, 58 | "internalType": "uint256", 59 | "name": "token_virtual_mint", 60 | "type": "uint256" 61 | }, 62 | { 63 | "indexed": false, 64 | "internalType": "uint256[]", 65 | "name": "tokens_mined", 66 | "type": "uint256[]" 67 | } 68 | ], 69 | "name": "Mine", 70 | "type": "event" 71 | }, 72 | { 73 | "anonymous": false, 74 | "inputs": [ 75 | { 76 | "indexed": true, 77 | "internalType": "bytes32", 78 | "name": "role", 79 | "type": "bytes32" 80 | }, 81 | { 82 | "indexed": true, 83 | "internalType": "bytes32", 84 | "name": "previousAdminRole", 85 | "type": "bytes32" 86 | }, 87 | { 88 | "indexed": true, 89 | "internalType": "bytes32", 90 | "name": "newAdminRole", 91 | "type": "bytes32" 92 | } 93 | ], 94 | "name": "RoleAdminChanged", 95 | "type": "event" 96 | }, 97 | { 98 | "anonymous": false, 99 | "inputs": [ 100 | { 101 | "indexed": true, 102 | "internalType": "bytes32", 103 | "name": "role", 104 | "type": "bytes32" 105 | }, 106 | { 107 | "indexed": true, 108 | "internalType": "address", 109 | "name": "account", 110 | "type": "address" 111 | }, 112 | { 113 | "indexed": true, 114 | "internalType": "address", 115 | "name": "sender", 116 | "type": "address" 117 | } 118 | ], 119 | "name": "RoleGranted", 120 | "type": "event" 121 | }, 122 | { 123 | "anonymous": false, 124 | "inputs": [ 125 | { 126 | "indexed": true, 127 | "internalType": "bytes32", 128 | "name": "role", 129 | "type": "bytes32" 130 | }, 131 | { 132 | "indexed": true, 133 | "internalType": "address", 134 | "name": "account", 135 | "type": "address" 136 | }, 137 | { 138 | "indexed": true, 139 | "internalType": "address", 140 | "name": "sender", 141 | "type": "address" 142 | } 143 | ], 144 | "name": "RoleRevoked", 145 | "type": "event" 146 | }, 147 | { 148 | "inputs": [], 149 | "name": "DEFAULT_ADMIN_ROLE", 150 | "outputs": [ 151 | { 152 | "internalType": "bytes32", 153 | "name": "", 154 | "type": "bytes32" 155 | } 156 | ], 157 | "stateMutability": "view", 158 | "type": "function" 159 | }, 160 | { 161 | "inputs": [], 162 | "name": "EMISSION_COEFF_1", 163 | "outputs": [ 164 | { 165 | "internalType": "uint256", 166 | "name": "", 167 | "type": "uint256" 168 | } 169 | ], 170 | "stateMutability": "view", 171 | "type": "function" 172 | }, 173 | { 174 | "inputs": [], 175 | "name": "EMISSION_COEFF_2", 176 | "outputs": [ 177 | { 178 | "internalType": "uint256", 179 | "name": "", 180 | "type": "uint256" 181 | } 182 | ], 183 | "stateMutability": "view", 184 | "type": "function" 185 | }, 186 | { 187 | "inputs": [], 188 | "name": "FINAL_PRINT_RATE", 189 | "outputs": [ 190 | { 191 | "internalType": "uint256", 192 | "name": "", 193 | "type": "uint256" 194 | } 195 | ], 196 | "stateMutability": "view", 197 | "type": "function" 198 | }, 199 | { 200 | "inputs": [], 201 | "name": "HC_RESERVE_DECAY_TIME", 202 | "outputs": [ 203 | { 204 | "internalType": "uint256", 205 | "name": "", 206 | "type": "uint256" 207 | } 208 | ], 209 | "stateMutability": "view", 210 | "type": "function" 211 | }, 212 | { 213 | "inputs": [], 214 | "name": "MINEABLE_TOKENS", 215 | "outputs": [ 216 | { 217 | "internalType": "uint256", 218 | "name": "", 219 | "type": "uint256" 220 | } 221 | ], 222 | "stateMutability": "view", 223 | "type": "function" 224 | }, 225 | { 226 | "inputs": [], 227 | "name": "ONE_KNS", 228 | "outputs": [ 229 | { 230 | "internalType": "uint256", 231 | "name": "", 232 | "type": "uint256" 233 | } 234 | ], 235 | "stateMutability": "view", 236 | "type": "function" 237 | }, 238 | { 239 | "inputs": [], 240 | "name": "RECENT_BLOCK_LIMIT", 241 | "outputs": [ 242 | { 243 | "internalType": "uint256", 244 | "name": "", 245 | "type": "uint256" 246 | } 247 | ], 248 | "stateMutability": "view", 249 | "type": "function" 250 | }, 251 | { 252 | "inputs": [], 253 | "name": "TOTAL_EMISSION_TIME", 254 | "outputs": [ 255 | { 256 | "internalType": "uint256", 257 | "name": "", 258 | "type": "uint256" 259 | } 260 | ], 261 | "stateMutability": "view", 262 | "type": "function" 263 | }, 264 | { 265 | "inputs": [ 266 | { 267 | "internalType": "address[]", 268 | "name": "recipients", 269 | "type": "address[]" 270 | }, 271 | { 272 | "internalType": "uint256[]", 273 | "name": "split_percents", 274 | "type": "uint256[]" 275 | }, 276 | { 277 | "internalType": "uint256", 278 | "name": "recent_eth_block_number", 279 | "type": "uint256" 280 | }, 281 | { 282 | "internalType": "uint256", 283 | "name": "recent_eth_block_hash", 284 | "type": "uint256" 285 | }, 286 | { 287 | "internalType": "uint256", 288 | "name": "target", 289 | "type": "uint256" 290 | }, 291 | { 292 | "internalType": "uint256", 293 | "name": "pow_height", 294 | "type": "uint256" 295 | }, 296 | { 297 | "internalType": "uint256", 298 | "name": "nonce", 299 | "type": "uint256" 300 | } 301 | ], 302 | "name": "check_pow", 303 | "outputs": [], 304 | "stateMutability": "view", 305 | "type": "function" 306 | }, 307 | { 308 | "inputs": [ 309 | { 310 | "internalType": "bytes32", 311 | "name": "role", 312 | "type": "bytes32" 313 | } 314 | ], 315 | "name": "getRoleAdmin", 316 | "outputs": [ 317 | { 318 | "internalType": "bytes32", 319 | "name": "", 320 | "type": "bytes32" 321 | } 322 | ], 323 | "stateMutability": "view", 324 | "type": "function" 325 | }, 326 | { 327 | "inputs": [ 328 | { 329 | "internalType": "bytes32", 330 | "name": "role", 331 | "type": "bytes32" 332 | }, 333 | { 334 | "internalType": "uint256", 335 | "name": "index", 336 | "type": "uint256" 337 | } 338 | ], 339 | "name": "getRoleMember", 340 | "outputs": [ 341 | { 342 | "internalType": "address", 343 | "name": "", 344 | "type": "address" 345 | } 346 | ], 347 | "stateMutability": "view", 348 | "type": "function" 349 | }, 350 | { 351 | "inputs": [ 352 | { 353 | "internalType": "bytes32", 354 | "name": "role", 355 | "type": "bytes32" 356 | } 357 | ], 358 | "name": "getRoleMemberCount", 359 | "outputs": [ 360 | { 361 | "internalType": "uint256", 362 | "name": "", 363 | "type": "uint256" 364 | } 365 | ], 366 | "stateMutability": "view", 367 | "type": "function" 368 | }, 369 | { 370 | "inputs": [ 371 | { 372 | "internalType": "uint256", 373 | "name": "current_time", 374 | "type": "uint256" 375 | } 376 | ], 377 | "name": "get_background_activity", 378 | "outputs": [ 379 | { 380 | "internalType": "uint256", 381 | "name": "hc_decay", 382 | "type": "uint256" 383 | }, 384 | { 385 | "internalType": "uint256", 386 | "name": "token_virtual_mint", 387 | "type": "uint256" 388 | } 389 | ], 390 | "stateMutability": "view", 391 | "type": "function" 392 | }, 393 | { 394 | "inputs": [ 395 | { 396 | "internalType": "uint256", 397 | "name": "t", 398 | "type": "uint256" 399 | } 400 | ], 401 | "name": "get_emission_curve", 402 | "outputs": [ 403 | { 404 | "internalType": "uint256", 405 | "name": "", 406 | "type": "uint256" 407 | } 408 | ], 409 | "stateMutability": "view", 410 | "type": "function" 411 | }, 412 | { 413 | "inputs": [ 414 | { 415 | "internalType": "uint256", 416 | "name": "hc", 417 | "type": "uint256" 418 | } 419 | ], 420 | "name": "get_hash_credits_conversion", 421 | "outputs": [ 422 | { 423 | "internalType": "uint256", 424 | "name": "", 425 | "type": "uint256" 426 | } 427 | ], 428 | "stateMutability": "view", 429 | "type": "function" 430 | }, 431 | { 432 | "inputs": [ 433 | { 434 | "internalType": "uint256", 435 | "name": "dt", 436 | "type": "uint256" 437 | } 438 | ], 439 | "name": "get_hc_reserve_multiplier", 440 | "outputs": [ 441 | { 442 | "internalType": "uint256", 443 | "name": "", 444 | "type": "uint256" 445 | } 446 | ], 447 | "stateMutability": "pure", 448 | "type": "function" 449 | }, 450 | { 451 | "inputs": [ 452 | { 453 | "internalType": "address", 454 | "name": "from", 455 | "type": "address" 456 | }, 457 | { 458 | "internalType": "address[]", 459 | "name": "recipients", 460 | "type": "address[]" 461 | }, 462 | { 463 | "internalType": "uint256[]", 464 | "name": "split_percents", 465 | "type": "uint256[]" 466 | } 467 | ], 468 | "name": "get_pow_height", 469 | "outputs": [ 470 | { 471 | "internalType": "uint256", 472 | "name": "", 473 | "type": "uint256" 474 | } 475 | ], 476 | "stateMutability": "view", 477 | "type": "function" 478 | }, 479 | { 480 | "inputs": [ 481 | { 482 | "internalType": "address[]", 483 | "name": "recipients", 484 | "type": "address[]" 485 | }, 486 | { 487 | "internalType": "uint256[]", 488 | "name": "split_percents", 489 | "type": "uint256[]" 490 | }, 491 | { 492 | "internalType": "uint256", 493 | "name": "recent_eth_block_number", 494 | "type": "uint256" 495 | }, 496 | { 497 | "internalType": "uint256", 498 | "name": "recent_eth_block_hash", 499 | "type": "uint256" 500 | }, 501 | { 502 | "internalType": "uint256", 503 | "name": "target", 504 | "type": "uint256" 505 | }, 506 | { 507 | "internalType": "uint256", 508 | "name": "pow_height", 509 | "type": "uint256" 510 | } 511 | ], 512 | "name": "get_secured_struct_hash", 513 | "outputs": [ 514 | { 515 | "internalType": "uint256", 516 | "name": "", 517 | "type": "uint256" 518 | } 519 | ], 520 | "stateMutability": "pure", 521 | "type": "function" 522 | }, 523 | { 524 | "inputs": [ 525 | { 526 | "internalType": "bytes32", 527 | "name": "role", 528 | "type": "bytes32" 529 | }, 530 | { 531 | "internalType": "address", 532 | "name": "account", 533 | "type": "address" 534 | } 535 | ], 536 | "name": "grantRole", 537 | "outputs": [], 538 | "stateMutability": "nonpayable", 539 | "type": "function" 540 | }, 541 | { 542 | "inputs": [ 543 | { 544 | "internalType": "bytes32", 545 | "name": "role", 546 | "type": "bytes32" 547 | }, 548 | { 549 | "internalType": "address", 550 | "name": "account", 551 | "type": "address" 552 | } 553 | ], 554 | "name": "hasRole", 555 | "outputs": [ 556 | { 557 | "internalType": "bool", 558 | "name": "", 559 | "type": "bool" 560 | } 561 | ], 562 | "stateMutability": "view", 563 | "type": "function" 564 | }, 565 | { 566 | "inputs": [], 567 | "name": "hc_reserve", 568 | "outputs": [ 569 | { 570 | "internalType": "uint256", 571 | "name": "", 572 | "type": "uint256" 573 | } 574 | ], 575 | "stateMutability": "view", 576 | "type": "function" 577 | }, 578 | { 579 | "inputs": [], 580 | "name": "is_testing", 581 | "outputs": [ 582 | { 583 | "internalType": "bool", 584 | "name": "", 585 | "type": "bool" 586 | } 587 | ], 588 | "stateMutability": "view", 589 | "type": "function" 590 | }, 591 | { 592 | "inputs": [], 593 | "name": "last_mint_time", 594 | "outputs": [ 595 | { 596 | "internalType": "uint256", 597 | "name": "", 598 | "type": "uint256" 599 | } 600 | ], 601 | "stateMutability": "view", 602 | "type": "function" 603 | }, 604 | { 605 | "inputs": [ 606 | { 607 | "internalType": "address[]", 608 | "name": "recipients", 609 | "type": "address[]" 610 | }, 611 | { 612 | "internalType": "uint256[]", 613 | "name": "split_percents", 614 | "type": "uint256[]" 615 | }, 616 | { 617 | "internalType": "uint256", 618 | "name": "recent_eth_block_number", 619 | "type": "uint256" 620 | }, 621 | { 622 | "internalType": "uint256", 623 | "name": "recent_eth_block_hash", 624 | "type": "uint256" 625 | }, 626 | { 627 | "internalType": "uint256", 628 | "name": "target", 629 | "type": "uint256" 630 | }, 631 | { 632 | "internalType": "uint256", 633 | "name": "pow_height", 634 | "type": "uint256" 635 | }, 636 | { 637 | "internalType": "uint256", 638 | "name": "nonce", 639 | "type": "uint256" 640 | } 641 | ], 642 | "name": "mine", 643 | "outputs": [], 644 | "stateMutability": "nonpayable", 645 | "type": "function" 646 | }, 647 | { 648 | "inputs": [ 649 | { 650 | "internalType": "bytes32", 651 | "name": "role", 652 | "type": "bytes32" 653 | }, 654 | { 655 | "internalType": "address", 656 | "name": "account", 657 | "type": "address" 658 | } 659 | ], 660 | "name": "renounceRole", 661 | "outputs": [], 662 | "stateMutability": "nonpayable", 663 | "type": "function" 664 | }, 665 | { 666 | "inputs": [ 667 | { 668 | "internalType": "bytes32", 669 | "name": "role", 670 | "type": "bytes32" 671 | }, 672 | { 673 | "internalType": "address", 674 | "name": "account", 675 | "type": "address" 676 | } 677 | ], 678 | "name": "revokeRole", 679 | "outputs": [], 680 | "stateMutability": "nonpayable", 681 | "type": "function" 682 | }, 683 | { 684 | "inputs": [], 685 | "name": "start_time", 686 | "outputs": [ 687 | { 688 | "internalType": "uint256", 689 | "name": "", 690 | "type": "uint256" 691 | } 692 | ], 693 | "stateMutability": "view", 694 | "type": "function" 695 | }, 696 | { 697 | "inputs": [ 698 | { 699 | "internalType": "address[]", 700 | "name": "recipients", 701 | "type": "address[]" 702 | }, 703 | { 704 | "internalType": "uint256[]", 705 | "name": "split_percents", 706 | "type": "uint256[]" 707 | }, 708 | { 709 | "internalType": "uint256", 710 | "name": "recent_eth_block_number", 711 | "type": "uint256" 712 | }, 713 | { 714 | "internalType": "uint256", 715 | "name": "recent_eth_block_hash", 716 | "type": "uint256" 717 | }, 718 | { 719 | "internalType": "uint256", 720 | "name": "target", 721 | "type": "uint256" 722 | }, 723 | { 724 | "internalType": "uint256", 725 | "name": "pow_height", 726 | "type": "uint256" 727 | }, 728 | { 729 | "internalType": "uint256", 730 | "name": "nonce", 731 | "type": "uint256" 732 | }, 733 | { 734 | "internalType": "uint256", 735 | "name": "current_time", 736 | "type": "uint256" 737 | } 738 | ], 739 | "name": "test_mine", 740 | "outputs": [], 741 | "stateMutability": "nonpayable", 742 | "type": "function" 743 | }, 744 | { 745 | "inputs": [ 746 | { 747 | "internalType": "uint256", 748 | "name": "current_time", 749 | "type": "uint256" 750 | } 751 | ], 752 | "name": "test_process_background_activity", 753 | "outputs": [], 754 | "stateMutability": "nonpayable", 755 | "type": "function" 756 | }, 757 | { 758 | "inputs": [], 759 | "name": "token", 760 | "outputs": [ 761 | { 762 | "internalType": "contract IMintableERC20", 763 | "name": "", 764 | "type": "address" 765 | } 766 | ], 767 | "stateMutability": "view", 768 | "type": "function" 769 | }, 770 | { 771 | "inputs": [], 772 | "name": "token_reserve", 773 | "outputs": [ 774 | { 775 | "internalType": "uint256", 776 | "name": "", 777 | "type": "uint256" 778 | } 779 | ], 780 | "stateMutability": "view", 781 | "type": "function" 782 | }, 783 | { 784 | "inputs": [ 785 | { 786 | "internalType": "uint256", 787 | "name": "seed", 788 | "type": "uint256" 789 | }, 790 | { 791 | "internalType": "uint256", 792 | "name": "secured_struct_hash", 793 | "type": "uint256" 794 | }, 795 | { 796 | "internalType": "uint256", 797 | "name": "nonce", 798 | "type": "uint256" 799 | } 800 | ], 801 | "name": "work", 802 | "outputs": [ 803 | { 804 | "internalType": "uint256[11]", 805 | "name": "work_result", 806 | "type": "uint256[11]" 807 | } 808 | ], 809 | "stateMutability": "pure", 810 | "type": "function" 811 | } 812 | ] 813 | 814 | module.exports = abi; 815 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var Web3 = require('web3'); 4 | var Tx = require('ethereumjs-tx').Transaction; 5 | const os = require('os'); 6 | const abi = require('./abi.js'); 7 | const crypto = require('crypto'); 8 | const {Looper} = require("./looper.js"); 9 | const Retry = require("./retry.js"); 10 | 11 | function difficultyToString( difficulty ) { 12 | let difficultyStr = difficulty.toString(16); 13 | difficultyStr = "0x" + "0".repeat(64 - difficultyStr.length) + difficultyStr; 14 | return difficultyStr; 15 | } 16 | 17 | function addressToBytes( addr ) { 18 | // Convert a string address to bytes 19 | let ADDRESS_LENGTH = 42; 20 | if( addr.startsWith("0x") ) 21 | addr = addr.substring(2); 22 | addr = "0".repeat(ADDRESS_LENGTH - addr.length) + addr; 23 | return Buffer.from(addr, "hex"); 24 | } 25 | 26 | /** 27 | * A simple queue class for request/response processing. 28 | * 29 | * Keep track of the information that was used in a request, so we can use it in response processing. 30 | */ 31 | class MiningRequestQueue { 32 | constructor( reqStream ) { 33 | this.pendingRequests = []; 34 | this.reqStream = reqStream; 35 | } 36 | 37 | sendRequest(req) { 38 | let difficultyStr = difficultyToString( req.difficulty ); 39 | console.log( "[JS] Ethereum Block Number: " + req.block.number ); 40 | console.log( "[JS] Ethereum Block Hash: " + req.block.hash ); 41 | console.log( "[JS] Target Difficulty: " + difficultyStr ); 42 | this.reqStream.write( 43 | req.minerAddress + " " + 44 | req.tipAddress + " " + 45 | req.block.hash + " " + 46 | req.block.number.toString() + " " + 47 | difficultyStr + " " + 48 | req.tipAmount + " " + 49 | req.powHeight + " " + 50 | req.threadIterations + " " + 51 | req.hashLimit + " " + 52 | req.nonceOffset + ";\n"); 53 | this.pendingRequests.push(req); 54 | } 55 | 56 | getHead() { 57 | if( this.pendingRequests.length === 0 ) 58 | return null; 59 | return this.pendingRequests[0]; 60 | } 61 | 62 | popHead() { 63 | if( this.pendingRequests.length === 0 ) 64 | return null; 65 | return this.pendingRequests.shift(); 66 | } 67 | } 68 | 69 | module.exports = class KoinosMiner { 70 | threadIterations = 600000; 71 | hashLimit = 100000000; 72 | // Start at 32 bits of difficulty 73 | difficulty = BigInt("0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); 74 | startTime = Date.now(); 75 | endTime = Date.now(); 76 | lastProof = Date.now(); 77 | hashes = 0; 78 | hashRate = 0; 79 | child = null; 80 | contract = null; 81 | 82 | constructor(address, tipAddresses, fromAddress, contractAddress, endpoint, tipAmount, period, gasMultiplier, gasPriceLimit, signCallback, hashrateCallback, proofCallback, errorCallback, warningCallback) { 83 | let self = this; 84 | 85 | this.address = address; 86 | this.tipAddresses = tipAddresses; 87 | this.web3 = new Web3( endpoint ); 88 | this.tipAmount = Math.trunc(tipAmount * 100); 89 | this.proofPeriod = period; 90 | this.signCallback = signCallback; 91 | this.hashrateCallback = hashrateCallback; 92 | this.errorCallback = errorCallback; 93 | this.warningCallback = warningCallback; 94 | this.fromAddress = fromAddress; 95 | this.gasMultiplier = gasMultiplier; 96 | this.gasPriceLimit = gasPriceLimit; 97 | this.contractAddress = contractAddress; 98 | this.proofCallback = proofCallback; 99 | this.updateBlockchainLoop = new Looper( 100 | function() { return self.updateBlockchain(); }, 101 | 60*1000, 102 | function(e) { return self.updateBlockchainError(e); } ); 103 | this.contract = new this.web3.eth.Contract( abi, this.contractAddress ); 104 | this.miningQueue = null; 105 | this.powHeightCache = {}; 106 | this.currentPHKIndex = 0; 107 | this.numTipAddresses = 3; 108 | this.startTimeout = null; 109 | 110 | this.contractStartTimePromise = this.contract.methods.start_time().call().then( (startTime) => { 111 | this.contractStartTime = startTime; 112 | }).catch( (e) => { 113 | let error = { 114 | kMessage: "Failed to retrieve the start time from the token mining contract.", 115 | exception: e 116 | }; 117 | console.log(error); 118 | if (this.errorCallback && typeof this.errorCallback === "function") { 119 | this.errorCallback(error); 120 | } 121 | }); 122 | 123 | // We don't want the mining manager to go down and leave the 124 | // C process running indefinitely, so we send SIGINT before 125 | // exiting. 126 | process.on('uncaughtException', function (err) { 127 | console.error('[JS] uncaughtException:', err.message); 128 | console.error(err.stack); 129 | if (self.child !== null) { 130 | self.stop(); 131 | } 132 | let error = { 133 | kMessage: "An uncaught exception was thrown.", 134 | exception: err 135 | }; 136 | if (self.errorCallback && typeof self.errorCallback === "function") { 137 | self.errorCallback(error); 138 | } 139 | }); 140 | } 141 | 142 | async awaitInitialization() { 143 | if (this.contractStartTimePromise !== null) { 144 | await this.contractStartTimePromise; 145 | this.contractStartTimePromise = null; 146 | } 147 | } 148 | 149 | getMiningStartTime() { 150 | return this.contractStartTime; 151 | } 152 | 153 | async retrievePowHeight(phk) { 154 | try 155 | { 156 | let [fromAddress, address, tipAddress, one_minus_ta, ta] = phk.split(","); 157 | let result = await this.contract.methods.get_pow_height( 158 | fromAddress, 159 | [address, tipAddress], 160 | [parseInt(one_minus_ta), parseInt(ta)] 161 | ).call(); 162 | this.powHeightCache[phk] = parseInt(result); 163 | } 164 | catch(e) 165 | { 166 | let error = { 167 | kMessage: "Could not retrieve the PoW height.", 168 | exception: e 169 | }; 170 | throw error; 171 | } 172 | } 173 | 174 | sendTransaction(txData) { 175 | var self = this; 176 | self.signCallback(self.web3, txData).then( (rawTx) => { 177 | self.web3.eth.sendSignedTransaction(rawTx).then( (receipt) => { 178 | console.log("[JS] Transaction hash is", receipt.transactionHash); 179 | if (self.proofCallback && typeof self.proofCallback === "function") { 180 | self.proofCallback(receipt, txData.gasPrice); 181 | } 182 | }). 183 | catch( async (e) => { 184 | console.log('[JS] Error sending transaction:', e.message); 185 | let warning = { 186 | kMessage: e.message, 187 | exception: e 188 | }; 189 | if(self.warningCallback && typeof self.warningCallback === "function") { 190 | self.warningCallback(warning); 191 | } 192 | }); 193 | }); 194 | } 195 | 196 | getPHK( tipAddress ) { 197 | // Get the pow height key for the given tip address 198 | let ta = this.tipAmount.toString(); 199 | let one_minus_ta = (10000 - this.tipAmount).toString(); 200 | return [this.fromAddress, this.address, tipAddress, one_minus_ta, ta].join(","); 201 | } 202 | 203 | getActivePHKs() { 204 | // Get the currently active PHK's 205 | let minerTipAddresses = this.getTipAddressesForMiner( this.address ); 206 | let result = []; 207 | for( let i=0; i b[0] ) 235 | return 1; 236 | if( a[1] < b[1] ) 237 | return -1; 238 | if( a[1] > b[1] ) 239 | return 1; 240 | return 0; 241 | } ); 242 | 243 | let result = []; 244 | for( let i=0; i this.gasPriceLimit) { 310 | let error = { 311 | kMessage: "The gas price (" + gasPrice + ") has exceeded the gas price limit (" + this.gasPriceLimit + ")." 312 | }; 313 | if (this.errorCallback && typeof this.errorCallback === "function") { 314 | this.errorCallback(error); 315 | } 316 | } 317 | 318 | this.sendTransaction({ 319 | from: req.fromAddress, 320 | to: this.contractAddress, 321 | gas: (req.powHeight == 1 ? 900000 : 500000), 322 | gasPrice: gasPrice, 323 | data: this.contract.methods.mine(...mineArgs).encodeABI() 324 | }); 325 | 326 | this.rotateTipAddress(); 327 | this.adjustDifficulty(); 328 | this.startTime = Date.now(); 329 | this.sendMiningRequest(); 330 | } 331 | 332 | async onRespHashReport( req, newHashes ) 333 | { 334 | let now = Date.now(); 335 | this.updateHashrate(newHashes - this.hashes, now - this.endTime); 336 | this.hashes = newHashes; 337 | this.endTime = now; 338 | } 339 | 340 | async runMiner() { 341 | if (this.startTimeout) { 342 | clearTimeout(this.startTimeout); 343 | this.startTimeout = null; 344 | } 345 | var self = this; 346 | 347 | let tipAddresses = this.getTipAddressesForMiner( this.address ); 348 | console.log("[JS] Selected tip addresses", tipAddresses ); 349 | 350 | this.currentPHKIndex = Math.floor(this.numTipAddresses * Math.random()); 351 | 352 | var spawn = require('child_process').spawn; 353 | this.child = spawn( this.minerPath(), [this.address, this.oo_address] ); 354 | this.child.stdin.setEncoding('utf-8'); 355 | this.child.stderr.pipe(process.stdout); 356 | this.miningQueue = new MiningRequestQueue(this.child.stdin); 357 | this.child.stdout.on('data', async function (data) { 358 | if ( self.isFinishedWithoutNonce(data) ) { 359 | await self.onRespFinished(self.miningQueue.popHead()); 360 | } 361 | else if ( self.isFinishedWithNonce(data) ) { 362 | let nonce = BigInt('0x' + self.getValue(data)); 363 | await self.onRespNonce(self.miningQueue.popHead(), nonce); 364 | } 365 | else if ( self.isHashReport(data) ) { 366 | let ret = self.getValue(data).split(" "); 367 | let newHashes = parseInt(ret[1]); 368 | await self.onRespHashReport(self.miningQueue.getHead(), newHashes); 369 | } 370 | else { 371 | let error = { 372 | kMessage: 'Unrecognized response from the C mining application.' 373 | }; 374 | if (self.errorCallback && typeof self.errorCallback === "function") { 375 | self.errorCallback(error); 376 | } 377 | } 378 | }); 379 | self.updateBlockchainLoop.start(); 380 | self.sendMiningRequest(); 381 | } 382 | 383 | async start() { 384 | if (this.startTimeout !== null) { 385 | console.log("[JS] Miner is already scheduled to start"); 386 | return; 387 | } 388 | 389 | if (this.child !== null) { 390 | console.log("[JS] Miner has already started"); 391 | return; 392 | } 393 | 394 | console.log("[JS] Starting miner"); 395 | var self = this; 396 | 397 | try { 398 | await self.updateBlockchain(); 399 | } 400 | catch( e ) { 401 | self.updateBlockchainError(e); 402 | } 403 | await this.awaitInitialization(); 404 | 405 | self.startTime = Date.now(); 406 | let now = Math.floor(Date.now() / 1000); 407 | if (now < this.contractStartTime) { 408 | let startDateTime = new Date(this.contractStartTime * 1000); 409 | console.log("[JS] Mining will begin at " + startDateTime.toLocaleString()); 410 | this.startTimeout = setTimeout(function() { 411 | self.runMiner(); 412 | }, (this.contractStartTime - now) * 1000); 413 | } 414 | else { 415 | this.runMiner(); 416 | } 417 | } 418 | 419 | stop() { 420 | if (this.child !== null) { 421 | console.log("[JS] Stopping miner"); 422 | this.child.kill('SIGINT'); 423 | this.child = null; 424 | } 425 | else { 426 | console.log("[JS] Miner has already stopped"); 427 | } 428 | 429 | if (this.startTimeout !== null) { 430 | clearTimeout(this.startTimeout); 431 | this.startTimeout = null; 432 | } 433 | 434 | console.log("[JS] Stopping blockchain update loop"); 435 | try { 436 | this.updateBlockchainLoop.stop(); 437 | } 438 | catch( e ) { 439 | if( e.name === "LooperAlreadyStopping" ) { 440 | console.log("[JS] Blockchain update loop was already stopping"); 441 | } 442 | } 443 | } 444 | 445 | minerPath() { 446 | var miner = __dirname + '/bin/koinos_miner'; 447 | if ( process.platform === "win32" ) { 448 | miner += '.exe'; 449 | } 450 | return miner; 451 | } 452 | 453 | getValue(s) { 454 | let str = s.toString(); 455 | return str.substring(2, str.indexOf(";")); 456 | } 457 | 458 | isFinishedWithoutNonce(s) { 459 | let str = s.toString(); 460 | return "F:" === str.substring(0, 2); 461 | } 462 | 463 | isFinishedWithNonce(s) { 464 | let str = s.toString(); 465 | return "N:" === str.substring(0, 2); 466 | } 467 | 468 | isHashReport(s) { 469 | let str = s.toString(); 470 | return "H:" === str.substring(0,2); 471 | } 472 | 473 | updateHashrate(d_hashes, d_time) { 474 | d_time = Math.max(d_time, 1); 475 | if ( this.hashRate > 0 ) { 476 | this.hashRate += Math.trunc((d_hashes * 1000) / d_time); 477 | this.hashRate /= 2; 478 | } 479 | else { 480 | this.hashRate = Math.trunc((d_hashes * 1000) / d_time); 481 | } 482 | 483 | if (this.hashrateCallback && typeof this.hashrateCallback === "function") { 484 | this.hashrateCallback(this.hashRate); 485 | } 486 | } 487 | 488 | adjustDifficulty() { 489 | const maxHash = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); // 2^256 - 1 490 | this.hashRate = Math.max(this.hashRate, 1); 491 | var hashesPerPeriod = this.hashRate * parseInt(this.proofPeriod); 492 | this.difficulty = maxHash / BigInt(Math.trunc(hashesPerPeriod)); 493 | this.threadIterations = Math.max(this.hashRate / (2 * os.cpus().length), 1); // Per thread hash rate, sync twice a second 494 | this.hashLimit = this.hashRate * 60 * 1; // Hashes for 1 minute 495 | } 496 | 497 | static formatHashrate(h) { 498 | var units = "" 499 | switch( Math.trunc(Math.log10(h) / 3) ) { 500 | case 0: 501 | return h + " H/s" 502 | case 1: 503 | return Math.trunc(h/ 1000) + "." + Math.trunc(h % 1000) + " KH/s" 504 | case 2: 505 | return Math.trunc(h/ 1000000) + "." + Math.trunc((h / 1000) % 1000) + " MH/s" 506 | default: 507 | return Math.trunc(h/ 1000000000) + "." + Math.trunc((h / 1000000) % 1000) + " GH/s" 508 | } 509 | } 510 | 511 | bufToBigInt(buf) { 512 | let result = 0n; 513 | if( buf.length == 0 ) 514 | return result; 515 | let s = BigInt(8*(buf.length - 1)); 516 | for( let i=0; i 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | ### Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for 14 | software and other kinds of works. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | the GNU General Public License is intended to guarantee your freedom 19 | to share and change all versions of a program--to make sure it remains 20 | free software for all its users. We, the Free Software Foundation, use 21 | the GNU General Public License for most of our software; it applies 22 | also to any other work released this way by its authors. You can apply 23 | it to your programs, too. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | To protect your rights, we need to prevent others from denying you 33 | these rights or asking you to surrender the rights. Therefore, you 34 | have certain responsibilities if you distribute copies of the 35 | software, or if you modify it: responsibilities to respect the freedom 36 | of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the 56 | manufacturer can do so. This is fundamentally incompatible with the 57 | aim of protecting users' freedom to change the software. The 58 | systematic pattern of such abuse occurs in the area of products for 59 | individuals to use, which is precisely where it is most unacceptable. 60 | Therefore, we have designed this version of the GPL to prohibit the 61 | practice for those products. If such problems arise substantially in 62 | other domains, we stand ready to extend this provision to those 63 | domains in future versions of the GPL, as needed to protect the 64 | freedom of users. 65 | 66 | Finally, every program is threatened constantly by software patents. 67 | States should not allow patents to restrict development and use of 68 | software on general-purpose computers, but in those that do, we wish 69 | to avoid the special danger that patents applied to a free program 70 | could make it effectively proprietary. To prevent this, the GPL 71 | assures that patents cannot be used to render the program non-free. 72 | 73 | The precise terms and conditions for copying, distribution and 74 | modification follow. 75 | 76 | ### TERMS AND CONDITIONS 77 | 78 | #### 0. Definitions. 79 | 80 | "This License" refers to version 3 of the GNU General Public License. 81 | 82 | "Copyright" also means copyright-like laws that apply to other kinds 83 | of works, such as semiconductor masks. 84 | 85 | "The Program" refers to any copyrightable work licensed under this 86 | License. Each licensee is addressed as "you". "Licensees" and 87 | "recipients" may be individuals or organizations. 88 | 89 | To "modify" a work means to copy from or adapt all or part of the work 90 | in a fashion requiring copyright permission, other than the making of 91 | an exact copy. The resulting work is called a "modified version" of 92 | the earlier work or a work "based on" the earlier work. 93 | 94 | A "covered work" means either the unmodified Program or a work based 95 | on the Program. 96 | 97 | To "propagate" a work means to do anything with it that, without 98 | permission, would make you directly or secondarily liable for 99 | infringement under applicable copyright law, except executing it on a 100 | computer or modifying a private copy. Propagation includes copying, 101 | distribution (with or without modification), making available to the 102 | public, and in some countries other activities as well. 103 | 104 | To "convey" a work means any kind of propagation that enables other 105 | parties to make or receive copies. Mere interaction with a user 106 | through a computer network, with no transfer of a copy, is not 107 | conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" to 110 | the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | #### 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work for 121 | making modifications to it. "Object code" means any non-source form of 122 | a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users can 154 | regenerate automatically from other parts of the Corresponding Source. 155 | 156 | The Corresponding Source for a work in source code form is that same 157 | work. 158 | 159 | #### 2. Basic Permissions. 160 | 161 | All rights granted under this License are granted for the term of 162 | copyright on the Program, and are irrevocable provided the stated 163 | conditions are met. This License explicitly affirms your unlimited 164 | permission to run the unmodified Program. The output from running a 165 | covered work is covered by this License only if the output, given its 166 | content, constitutes a covered work. This License acknowledges your 167 | rights of fair use or other equivalent, as provided by copyright law. 168 | 169 | You may make, run and propagate covered works that you do not convey, 170 | without conditions so long as your license otherwise remains in force. 171 | You may convey covered works to others for the sole purpose of having 172 | them make modifications exclusively for you, or provide you with 173 | facilities for running those works, provided that you comply with the 174 | terms of this License in conveying all material for which you do not 175 | control copyright. Those thus making or running the covered works for 176 | you must do so exclusively on your behalf, under your direction and 177 | control, on terms that prohibit them from making any copies of your 178 | copyrighted material outside their relationship with you. 179 | 180 | Conveying under any other circumstances is permitted solely under the 181 | conditions stated below. Sublicensing is not allowed; section 10 makes 182 | it unnecessary. 183 | 184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 185 | 186 | No covered work shall be deemed part of an effective technological 187 | measure under any applicable law fulfilling obligations under article 188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 189 | similar laws prohibiting or restricting circumvention of such 190 | measures. 191 | 192 | When you convey a covered work, you waive any legal power to forbid 193 | circumvention of technological measures to the extent such 194 | circumvention is effected by exercising rights under this License with 195 | respect to the covered work, and you disclaim any intention to limit 196 | operation or modification of the work as a means of enforcing, against 197 | the work's users, your or third parties' legal rights to forbid 198 | circumvention of technological measures. 199 | 200 | #### 4. Conveying Verbatim Copies. 201 | 202 | You may convey verbatim copies of the Program's source code as you 203 | receive it, in any medium, provided that you conspicuously and 204 | appropriately publish on each copy an appropriate copyright notice; 205 | keep intact all notices stating that this License and any 206 | non-permissive terms added in accord with section 7 apply to the code; 207 | keep intact all notices of the absence of any warranty; and give all 208 | recipients a copy of this License along with the Program. 209 | 210 | You may charge any price or no price for each copy that you convey, 211 | and you may offer support or warranty protection for a fee. 212 | 213 | #### 5. Conveying Modified Source Versions. 214 | 215 | You may convey a work based on the Program, or the modifications to 216 | produce it from the Program, in the form of source code under the 217 | terms of section 4, provided that you also meet all of these 218 | conditions: 219 | 220 | - a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | - b) The work must carry prominent notices stating that it is 223 | released under this License and any conditions added under 224 | section 7. This requirement modifies the requirement in section 4 225 | to "keep intact all notices". 226 | - c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | - d) If the work has interactive user interfaces, each must display 234 | Appropriate Legal Notices; however, if the Program has interactive 235 | interfaces that do not display Appropriate Legal Notices, your 236 | work need not make them do so. 237 | 238 | A compilation of a covered work with other separate and independent 239 | works, which are not by their nature extensions of the covered work, 240 | and which are not combined with it such as to form a larger program, 241 | in or on a volume of a storage or distribution medium, is called an 242 | "aggregate" if the compilation and its resulting copyright are not 243 | used to limit the access or legal rights of the compilation's users 244 | beyond what the individual works permit. Inclusion of a covered work 245 | in an aggregate does not cause this License to apply to the other 246 | parts of the aggregate. 247 | 248 | #### 6. Conveying Non-Source Forms. 249 | 250 | You may convey a covered work in object code form under the terms of 251 | sections 4 and 5, provided that you also convey the machine-readable 252 | Corresponding Source under the terms of this License, in one of these 253 | ways: 254 | 255 | - a) Convey the object code in, or embodied in, a physical product 256 | (including a physical distribution medium), accompanied by the 257 | Corresponding Source fixed on a durable physical medium 258 | customarily used for software interchange. 259 | - b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the Corresponding 269 | Source from a network server at no charge. 270 | - c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | - d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | - e) Convey the object code using peer-to-peer transmission, 288 | provided you inform other peers where the object code and 289 | Corresponding Source of the work are being offered to the general 290 | public at no charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, 298 | family, or household purposes, or (2) anything designed or sold for 299 | incorporation into a dwelling. In determining whether a product is a 300 | consumer product, doubtful cases shall be resolved in favor of 301 | coverage. For a particular product received by a particular user, 302 | "normally used" refers to a typical or common use of that class of 303 | product, regardless of the status of the particular user or of the way 304 | in which the particular user actually uses, or expects or is expected 305 | to use, the product. A product is a consumer product regardless of 306 | whether the product has substantial commercial, industrial or 307 | non-consumer uses, unless such uses represent the only significant 308 | mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to 312 | install and execute modified versions of a covered work in that User 313 | Product from a modified version of its Corresponding Source. The 314 | information must suffice to ensure that the continued functioning of 315 | the modified object code is in no case prevented or interfered with 316 | solely because modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or 331 | updates for a work that has been modified or installed by the 332 | recipient, or for the User Product in which it has been modified or 333 | installed. Access to a network may be denied when the modification 334 | itself materially and adversely affects the operation of the network 335 | or violates the rules and protocols for communication across the 336 | network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | #### 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders 364 | of that material) supplement the terms of this License with terms: 365 | 366 | - a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | - b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | - c) Prohibiting misrepresentation of the origin of that material, 372 | or requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | - d) Limiting the use for publicity purposes of names of licensors 375 | or authors of the material; or 376 | - e) Declining to grant rights under trademark law for use of some 377 | trade names, trademarks, or service marks; or 378 | - f) Requiring indemnification of licensors and authors of that 379 | material by anyone who conveys the material (or modified versions 380 | of it) with contractual assumptions of liability to the recipient, 381 | for any liability that these contractual assumptions directly 382 | impose on those licensors and authors. 383 | 384 | All other non-permissive additional terms are considered "further 385 | restrictions" within the meaning of section 10. If the Program as you 386 | received it, or any part of it, contains a notice stating that it is 387 | governed by this License along with a term that is a further 388 | restriction, you may remove that term. If a license document contains 389 | a further restriction but permits relicensing or conveying under this 390 | License, you may add to a covered work material governed by the terms 391 | of that license document, provided that the further restriction does 392 | not survive such relicensing or conveying. 393 | 394 | If you add terms to a covered work in accord with this section, you 395 | must place, in the relevant source files, a statement of the 396 | additional terms that apply to those files, or a notice indicating 397 | where to find the applicable terms. 398 | 399 | Additional terms, permissive or non-permissive, may be stated in the 400 | form of a separately written license, or stated as exceptions; the 401 | above requirements apply either way. 402 | 403 | #### 8. Termination. 404 | 405 | You may not propagate or modify a covered work except as expressly 406 | provided under this License. Any attempt otherwise to propagate or 407 | modify it is void, and will automatically terminate your rights under 408 | this License (including any patent licenses granted under the third 409 | paragraph of section 11). 410 | 411 | However, if you cease all violation of this License, then your license 412 | from a particular copyright holder is reinstated (a) provisionally, 413 | unless and until the copyright holder explicitly and finally 414 | terminates your license, and (b) permanently, if the copyright holder 415 | fails to notify you of the violation by some reasonable means prior to 416 | 60 days after the cessation. 417 | 418 | Moreover, your license from a particular copyright holder is 419 | reinstated permanently if the copyright holder notifies you of the 420 | violation by some reasonable means, this is the first time you have 421 | received notice of violation of this License (for any work) from that 422 | copyright holder, and you cure the violation prior to 30 days after 423 | your receipt of the notice. 424 | 425 | Termination of your rights under this section does not terminate the 426 | licenses of parties who have received copies or rights from you under 427 | this License. If your rights have been terminated and not permanently 428 | reinstated, you do not qualify to receive new licenses for the same 429 | material under section 10. 430 | 431 | #### 9. Acceptance Not Required for Having Copies. 432 | 433 | You are not required to accept this License in order to receive or run 434 | a copy of the Program. Ancillary propagation of a covered work 435 | occurring solely as a consequence of using peer-to-peer transmission 436 | to receive a copy likewise does not require acceptance. However, 437 | nothing other than this License grants you permission to propagate or 438 | modify any covered work. These actions infringe copyright if you do 439 | not accept this License. Therefore, by modifying or propagating a 440 | covered work, you indicate your acceptance of this License to do so. 441 | 442 | #### 10. Automatic Licensing of Downstream Recipients. 443 | 444 | Each time you convey a covered work, the recipient automatically 445 | receives a license from the original licensors, to run, modify and 446 | propagate that work, subject to this License. You are not responsible 447 | for enforcing compliance by third parties with this License. 448 | 449 | An "entity transaction" is a transaction transferring control of an 450 | organization, or substantially all assets of one, or subdividing an 451 | organization, or merging organizations. If propagation of a covered 452 | work results from an entity transaction, each party to that 453 | transaction who receives a copy of the work also receives whatever 454 | licenses to the work the party's predecessor in interest had or could 455 | give under the previous paragraph, plus a right to possession of the 456 | Corresponding Source of the work from the predecessor in interest, if 457 | the predecessor has it or can get it with reasonable efforts. 458 | 459 | You may not impose any further restrictions on the exercise of the 460 | rights granted or affirmed under this License. For example, you may 461 | not impose a license fee, royalty, or other charge for exercise of 462 | rights granted under this License, and you may not initiate litigation 463 | (including a cross-claim or counterclaim in a lawsuit) alleging that 464 | any patent claim is infringed by making, using, selling, offering for 465 | sale, or importing the Program or any portion of it. 466 | 467 | #### 11. Patents. 468 | 469 | A "contributor" is a copyright holder who authorizes use under this 470 | License of the Program or a work on which the Program is based. The 471 | work thus licensed is called the contributor's "contributor version". 472 | 473 | A contributor's "essential patent claims" are all patent claims owned 474 | or controlled by the contributor, whether already acquired or 475 | hereafter acquired, that would be infringed by some manner, permitted 476 | by this License, of making, using, or selling its contributor version, 477 | but do not include claims that would be infringed only as a 478 | consequence of further modification of the contributor version. For 479 | purposes of this definition, "control" includes the right to grant 480 | patent sublicenses in a manner consistent with the requirements of 481 | this License. 482 | 483 | Each contributor grants you a non-exclusive, worldwide, royalty-free 484 | patent license under the contributor's essential patent claims, to 485 | make, use, sell, offer for sale, import and otherwise run, modify and 486 | propagate the contents of its contributor version. 487 | 488 | In the following three paragraphs, a "patent license" is any express 489 | agreement or commitment, however denominated, not to enforce a patent 490 | (such as an express permission to practice a patent or covenant not to 491 | sue for patent infringement). To "grant" such a patent license to a 492 | party means to make such an agreement or commitment not to enforce a 493 | patent against the party. 494 | 495 | If you convey a covered work, knowingly relying on a patent license, 496 | and the Corresponding Source of the work is not available for anyone 497 | to copy, free of charge and under the terms of this License, through a 498 | publicly available network server or other readily accessible means, 499 | then you must either (1) cause the Corresponding Source to be so 500 | available, or (2) arrange to deprive yourself of the benefit of the 501 | patent license for this particular work, or (3) arrange, in a manner 502 | consistent with the requirements of this License, to extend the patent 503 | license to downstream recipients. "Knowingly relying" means you have 504 | actual knowledge that, but for the patent license, your conveying the 505 | covered work in a country, or your recipient's use of the covered work 506 | in a country, would infringe one or more identifiable patents in that 507 | country that you have reason to believe are valid. 508 | 509 | If, pursuant to or in connection with a single transaction or 510 | arrangement, you convey, or propagate by procuring conveyance of, a 511 | covered work, and grant a patent license to some of the parties 512 | receiving the covered work authorizing them to use, propagate, modify 513 | or convey a specific copy of the covered work, then the patent license 514 | you grant is automatically extended to all recipients of the covered 515 | work and works based on it. 516 | 517 | A patent license is "discriminatory" if it does not include within the 518 | scope of its coverage, prohibits the exercise of, or is conditioned on 519 | the non-exercise of one or more of the rights that are specifically 520 | granted under this License. You may not convey a covered work if you 521 | are a party to an arrangement with a third party that is in the 522 | business of distributing software, under which you make payment to the 523 | third party based on the extent of your activity of conveying the 524 | work, and under which the third party grants, to any of the parties 525 | who would receive the covered work from you, a discriminatory patent 526 | license (a) in connection with copies of the covered work conveyed by 527 | you (or copies made from those copies), or (b) primarily for and in 528 | connection with specific products or compilations that contain the 529 | covered work, unless you entered into that arrangement, or that patent 530 | license was granted, prior to 28 March 2007. 531 | 532 | Nothing in this License shall be construed as excluding or limiting 533 | any implied license or other defenses to infringement that may 534 | otherwise be available to you under applicable patent law. 535 | 536 | #### 12. No Surrender of Others' Freedom. 537 | 538 | If conditions are imposed on you (whether by court order, agreement or 539 | otherwise) that contradict the conditions of this License, they do not 540 | excuse you from the conditions of this License. If you cannot convey a 541 | covered work so as to satisfy simultaneously your obligations under 542 | this License and any other pertinent obligations, then as a 543 | consequence you may not convey it at all. For example, if you agree to 544 | terms that obligate you to collect a royalty for further conveying 545 | from those to whom you convey the Program, the only way you could 546 | satisfy both those terms and this License would be to refrain entirely 547 | from conveying the Program. 548 | 549 | #### 13. Use with the GNU Affero General Public License. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU Affero General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the special requirements of the GNU Affero General Public License, 557 | section 13, concerning interaction through a network will apply to the 558 | combination as such. 559 | 560 | #### 14. Revised Versions of this License. 561 | 562 | The Free Software Foundation may publish revised and/or new versions 563 | of the GNU General Public License from time to time. Such new versions 564 | will be similar in spirit to the present version, but may differ in 565 | detail to address new problems or concerns. 566 | 567 | Each version is given a distinguishing version number. If the Program 568 | specifies that a certain numbered version of the GNU General Public 569 | License "or any later version" applies to it, you have the option of 570 | following the terms and conditions either of that numbered version or 571 | of any later version published by the Free Software Foundation. If the 572 | Program does not specify a version number of the GNU General Public 573 | License, you may choose any version ever published by the Free 574 | Software Foundation. 575 | 576 | If the Program specifies that a proxy can decide which future versions 577 | of the GNU General Public License can be used, that proxy's public 578 | statement of acceptance of a version permanently authorizes you to 579 | choose that version for the Program. 580 | 581 | Later license versions may give you additional or different 582 | permissions. However, no additional obligations are imposed on any 583 | author or copyright holder as a result of your choosing to follow a 584 | later version. 585 | 586 | #### 15. Disclaimer of Warranty. 587 | 588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 596 | CORRECTION. 597 | 598 | #### 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR 606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM 607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER 608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 609 | 610 | #### 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | ### How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these 626 | terms. 627 | 628 | To do so, attach the following notices to the program. It is safest to 629 | attach them to the start of each source file to most effectively state 630 | the exclusion of warranty; and each file should have at least the 631 | "copyright" line and a pointer to where the full notice is found. 632 | 633 | 634 | Copyright (C) 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU General Public License for more details. 645 | 646 | You should have received a copy of the GNU General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper 650 | mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands \`show w' and \`show c' should show the 661 | appropriate parts of the General Public License. Of course, your 662 | program's commands might be different; for a GUI interface, you would 663 | use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or 666 | school, if any, to sign a "copyright disclaimer" for the program, if 667 | necessary. For more information on this, and how to apply and follow 668 | the GNU GPL, see . 669 | 670 | The GNU General Public License does not permit incorporating your 671 | program into proprietary programs. If your program is a subroutine 672 | library, you may consider it more useful to permit linking proprietary 673 | applications with the library. If this is what you want to do, use the 674 | GNU Lesser General Public License instead of this License. But first, 675 | please read . 676 | --------------------------------------------------------------------------------