cpu-miner.c 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718
  1. /*
  2. * Copyright 2010 Jeff Garzik
  3. * Copyright 2012-2014 pooler
  4. * Copyright 2014 Lucas Jones
  5. * Copyright 2014 Tanguy Pruvot
  6. * Copyright 2024 epsylon (psy)
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 2 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include <cpuminer-config.h>
  14. #define _GNU_SOURCE
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <stdbool.h>
  19. #include <inttypes.h>
  20. #include <unistd.h>
  21. #include <sys/time.h>
  22. #include <time.h>
  23. #include <signal.h>
  24. #include <curl/curl.h>
  25. #include <jansson.h>
  26. #include <openssl/sha.h>
  27. #ifdef _MSC_VER
  28. #include <windows.h>
  29. #include <stdint.h>
  30. #else
  31. #include <errno.h>
  32. #if HAVE_SYS_SYSCTL_H
  33. #include <sys/types.h>
  34. #if HAVE_SYS_PARAM_H
  35. #include <sys/param.h>
  36. #endif
  37. #include <sys/sysctl.h>
  38. #endif
  39. #endif
  40. #ifndef WIN32
  41. #include <sys/resource.h>
  42. #endif
  43. #include "miner.h"
  44. #ifdef WIN32
  45. #include "compat/winansi.h"
  46. BOOL WINAPI ConsoleHandler(DWORD);
  47. #endif
  48. #ifdef _MSC_VER
  49. #include <Mmsystem.h>
  50. #pragma comment(lib, "winmm.lib")
  51. #endif
  52. #define LP_SCANTIME 60
  53. #ifndef min
  54. #define min(a,b) (a>b ? b : a)
  55. #define max(a,b) (a<b ? b : a)
  56. #endif
  57. enum workio_commands {
  58. WC_GET_WORK,
  59. WC_SUBMIT_WORK,
  60. };
  61. struct workio_cmd {
  62. enum workio_commands cmd;
  63. struct thr_info *thr;
  64. union {
  65. struct work *work;
  66. } u;
  67. };
  68. enum algos {
  69. ALGO_KECCAK, /* Keccak (old) */
  70. ALGO_KECCAKC, /* Keccak */
  71. ALGO_HEAVY, /* Heavy */
  72. ALGO_NEOSCRYPT, /* NeoScrypt(128, 2, 1) with Salsa20/20 and ChaCha20/20 */
  73. ALGO_QUARK, /* Quark */
  74. ALGO_ALLIUM, /* Garlicoin double lyra2 */
  75. ALGO_AXIOM, /* Shabal 256 Memohash */
  76. ALGO_BASTION,
  77. ALGO_BLAKE, /* Blake 256 */
  78. ALGO_BLAKECOIN, /* Simplified 8 rounds Blake 256 */
  79. ALGO_BLAKE2B,
  80. ALGO_BLAKE2S, /* Blake2s */
  81. ALGO_BMW, /* BMW 256 */
  82. ALGO_C11, /* C11 Chaincoin/Flaxcoin X11 variant */
  83. ALGO_CRYPTOLIGHT, /* cryptonight-light (Aeon) */
  84. ALGO_CRYPTONIGHT, /* CryptoNight */
  85. ALGO_DECRED, /* Decred */
  86. ALGO_DMD_GR, /* Diamond */
  87. ALGO_DROP, /* Dropcoin */
  88. ALGO_FRESH, /* Fresh */
  89. ALGO_GEEK,
  90. ALGO_GROESTL, /* Groestl */
  91. ALGO_JHA,
  92. ALGO_LBRY, /* Lbry Sha Ripemd */
  93. ALGO_LUFFA, /* Luffa (Joincoin, Doom) */
  94. ALGO_LYRA2, /* Lyra2RE */
  95. ALGO_LYRA2REV2, /* Lyra2REv2 */
  96. ALGO_LYRA2V3, /* Lyra2REv3 (Vertcoin) */
  97. ALGO_MYR_GR, /* Myriad Groestl */
  98. ALGO_NIST5, /* Nist5 */
  99. ALGO_PENTABLAKE, /* Pentablake */
  100. ALGO_PHI1612,
  101. ALGO_PHI2,
  102. ALGO_PLUCK, /* Pluck (Supcoin) */
  103. ALGO_QUBIT, /* Qubit */
  104. ALGO_RAINFOREST, /* RainForest */
  105. ALGO_SCRYPT, /* scrypt */
  106. ALGO_SCRYPTJANE, /* Chacha */
  107. ALGO_SHAVITE3, /* Shavite3 */
  108. ALGO_SHA256D, /* SHA-256d */
  109. ALGO_SIA, /* Blake2-B */
  110. ALGO_SIB, /* X11 + gost (Sibcoin) */
  111. ALGO_SKEIN, /* Skein */
  112. ALGO_SKEIN2, /* Double skein (Woodcoin) */
  113. ALGO_SONOA,
  114. ALGO_S3, /* S3 */
  115. ALGO_TIMETRAVEL, /* Timetravel-8 (Machinecoin) */
  116. ALGO_BITCORE, /* Timetravel-10 (Bitcore) */
  117. ALGO_TRIBUS, /* Denarius jh/keccak/echo */
  118. ALGO_VANILLA, /* Vanilla (Blake256 8-rounds - double sha256) */
  119. ALGO_VELTOR, /* Skein Shavite Shabal Streebog */
  120. ALGO_X11EVO, /* Permuted X11 */
  121. ALGO_X11, /* X11 */
  122. ALGO_X12,
  123. ALGO_X13, /* X13 */
  124. ALGO_X14, /* X14 */
  125. ALGO_X15, /* X15 */
  126. ALGO_X16R, /* X16R */
  127. ALGO_X16RV2, /* X16Rv2 */
  128. ALGO_X16S,
  129. ALGO_X17, /* X17 */
  130. ALGO_X20R,
  131. ALGO_XEVAN,
  132. ALGO_YESCRYPT,
  133. ALGO_YESCRYPTR8,
  134. ALGO_YESCRYPTR16,
  135. ALGO_YESCRYPTR32,
  136. ALGO_ZR5,
  137. ALGO_COUNT
  138. };
  139. static const char *algo_names[] = {
  140. "keccak",
  141. "keccakc",
  142. "heavy",
  143. "neoscrypt",
  144. "quark",
  145. "allium",
  146. "axiom",
  147. "bastion",
  148. "blake",
  149. "blakecoin",
  150. "blake2b",
  151. "blake2s",
  152. "bmw",
  153. "c11",
  154. "cryptolight",
  155. "cryptonight",
  156. "decred",
  157. "dmd-gr",
  158. "drop",
  159. "fresh",
  160. "geek",
  161. "groestl",
  162. "jha",
  163. "lbry",
  164. "luffa",
  165. "lyra2re",
  166. "lyra2rev2",
  167. "lyra2v3",
  168. "myr-gr",
  169. "nist5",
  170. "pentablake",
  171. "phi1612",
  172. "phi2",
  173. "pluck",
  174. "qubit",
  175. "rainforest",
  176. "scrypt",
  177. "scrypt-jane",
  178. "shavite3",
  179. "sha256d",
  180. "sia",
  181. "sib",
  182. "skein",
  183. "skein2",
  184. "sonoa",
  185. "s3",
  186. "timetravel",
  187. "bitcore",
  188. "tribus",
  189. "vanilla",
  190. "veltor",
  191. "x11evo",
  192. "x11",
  193. "x12",
  194. "x13",
  195. "x14",
  196. "x15",
  197. "x16r",
  198. "x16rv2",
  199. "x16s",
  200. "x17",
  201. "x20r",
  202. "xevan",
  203. "yescrypt",
  204. "yescryptr8",
  205. "yescryptr16",
  206. "yescryptr32",
  207. "zr5",
  208. "\0"
  209. };
  210. bool opt_debug = false;
  211. bool opt_debug_diff = false;
  212. bool opt_protocol = false;
  213. bool opt_benchmark = false;
  214. bool opt_redirect = true;
  215. bool opt_showdiff = true;
  216. bool opt_extranonce = true;
  217. bool want_longpoll = true;
  218. bool have_longpoll = false;
  219. bool have_gbt = true;
  220. bool allow_getwork = true;
  221. bool want_stratum = true;
  222. bool have_stratum = false;
  223. bool opt_stratum_stats = false;
  224. bool allow_mininginfo = true;
  225. bool use_syslog = false;
  226. bool use_colors = true;
  227. static bool opt_background = false;
  228. bool opt_quiet = false;
  229. int opt_maxlograte = 5;
  230. bool opt_randomize = false;
  231. static int opt_retries = -1;
  232. static int opt_fail_pause = 10;
  233. static int opt_time_limit = 0;
  234. int opt_timeout = 300;
  235. static int opt_scantime = 5;
  236. static enum algos opt_algo = ALGO_SCRYPT;
  237. static int opt_scrypt_n = 1024;
  238. static int opt_pluck_n = 128;
  239. static unsigned int opt_nfactor = 6;
  240. int opt_n_threads = 0;
  241. int64_t opt_affinity = -1L;
  242. int opt_priority = 0;
  243. int num_cpus;
  244. char *rpc_url;
  245. char *rpc_userpass;
  246. char *rpc_user, *rpc_pass;
  247. char *short_url = NULL;
  248. static unsigned char pk_script[25] = { 0 };
  249. static size_t pk_script_size = 0;
  250. static char coinbase_sig[101] = { 0 };
  251. char *opt_cert;
  252. char *opt_proxy;
  253. long opt_proxy_type;
  254. struct thr_info *thr_info;
  255. int work_thr_id;
  256. int longpoll_thr_id = -1;
  257. int stratum_thr_id = -1;
  258. int api_thr_id = -1;
  259. bool stratum_need_reset = false;
  260. struct work_restart *work_restart = NULL;
  261. struct stratum_ctx stratum;
  262. bool jsonrpc_2 = false;
  263. char rpc2_id[64] = "";
  264. char *rpc2_blob = NULL;
  265. size_t rpc2_bloblen = 0;
  266. uint32_t rpc2_target = 0;
  267. char *rpc2_job_id = NULL;
  268. bool aes_ni_supported = false;
  269. double opt_diff_factor = 1.0;
  270. pthread_mutex_t rpc2_job_lock;
  271. pthread_mutex_t rpc2_login_lock;
  272. pthread_mutex_t applog_lock;
  273. pthread_mutex_t stats_lock;
  274. uint32_t zr5_pok = 0;
  275. bool use_roots = false;
  276. uint32_t solved_count = 0L;
  277. uint32_t accepted_count = 0L;
  278. uint32_t rejected_count = 0L;
  279. double *thr_hashrates;
  280. uint64_t global_hashrate = 0;
  281. double stratum_diff = 0.;
  282. double net_diff = 0.;
  283. double net_hashrate = 0.;
  284. uint64_t net_blocks = 0;
  285. // conditional mining
  286. bool conditional_state[MAX_CPUS] = { 0 };
  287. double opt_max_temp = 0.0;
  288. double opt_max_diff = 0.0;
  289. double opt_max_rate = 0.0;
  290. uint32_t opt_work_size = 0; /* default */
  291. char *opt_api_allow = NULL;
  292. int opt_api_remote = 0;
  293. int opt_api_listen = 4048; /* 0 to disable */
  294. #ifdef HAVE_GETOPT_LONG
  295. #include <getopt.h>
  296. #else
  297. struct option {
  298. const char *name;
  299. int has_arg;
  300. int *flag;
  301. int val;
  302. };
  303. #endif
  304. static char const usage[] = "\
  305. Usage: cpuminer [OPTIONS]\n\
  306. Options:\n\
  307. -a, --algo=ALGO specify the algorithm to use\n\
  308. allium Garlicoin double lyra2\n\
  309. axiom Shabal-256 MemoHash\n\
  310. bitcore Timetravel with 10 algos\n\
  311. blake Blake-256 14-rounds (SFR)\n\
  312. blakecoin Blake-256 single sha256 merkle\n\
  313. blake2b Blake2-B (512)\n\
  314. blake2s Blake2-S (256)\n\
  315. bmw BMW 256\n\
  316. c11/flax C11\n\
  317. cryptolight Cryptonight-light\n\
  318. cryptonight Monero\n\
  319. decred Blake-256 14-rounds 180 bytes\n\
  320. dmd-gr Diamond-Groestl\n\
  321. drop Dropcoin\n\
  322. fresh Fresh\n\
  323. geek GeekCash\n\
  324. groestl GroestlCoin\n\
  325. heavy Heavy\n\
  326. jha JHA\n\
  327. keccak Keccak (Old and deprecated)\n\
  328. keccakc Keccak (CreativeCoin)\n\
  329. luffa Luffa\n\
  330. lyra2re Lyra2RE\n\
  331. lyra2rev2 Lyra2REv2\n\
  332. lyra2v3 Lyra2REv3 (Vertcoin)\n\
  333. myr-gr Myriad-Groestl\n\
  334. neoscrypt NeoScrypt(128, 2, 1)\n\
  335. nist5 Nist5\n\
  336. pluck Pluck:128 (Supcoin)\n\
  337. pentablake Pentablake\n\
  338. phi LUX initial algo\n\
  339. phi2 LUX newer algo\n\
  340. quark Quark\n\
  341. qubit Qubit\n\
  342. rainforest RainForest (256)\n\
  343. scrypt scrypt(1024, 1, 1) (default)\n\
  344. scrypt:N scrypt(N, 1, 1)\n\
  345. scrypt-jane:N (with N factor from 4 to 30)\n\
  346. shavite3 Shavite3\n\
  347. sha256d SHA-256d\n\
  348. sia Blake2-B\n\
  349. sib X11 + gost (SibCoin)\n\
  350. skein Skein+Sha (Skeincoin)\n\
  351. skein2 Double Skein (Woodcoin)\n\
  352. sonoa A series of 97 hashes from x17\n\
  353. s3 S3\n\
  354. timetravel Timetravel (Machinecoin)\n\
  355. vanilla Blake-256 8-rounds\n\
  356. x11evo Permuted x11\n\
  357. x11 X11\n\
  358. x12 X12\n\
  359. x13 X13\n\
  360. x14 X14\n\
  361. x15 X15\n\
  362. x16r X16R\n\
  363. x16rv2 X16Rv2 (Raven / Trivechain)\n\
  364. x16s X16S (Pigeon)\n\
  365. x17 X17\n\
  366. x20r X20R\n\
  367. xevan Xevan (BitSend)\n\
  368. yescrypt Yescrypt\n\
  369. yescryptr8 Yescrypt r8\n\
  370. yescryptr16 Yescrypt r16\n\
  371. yescryptr32 Yescrypt r32\n\
  372. zr5 ZR5\n\
  373. -o, --url=URL URL of mining server\n\
  374. -O, --userpass=U:P username:password pair for mining server\n\
  375. -u, --user=USERNAME username for mining server\n\
  376. -p, --pass=PASSWORD password for mining server\n\
  377. --cert=FILE certificate for mining server using SSL\n\
  378. -x, --proxy=[PROTOCOL://]HOST[:PORT] connect through a proxy\n\
  379. -t, --threads=N number of miner threads (default: number of processors)\n\
  380. -r, --retries=N number of times to retry if a network call fails\n\
  381. (default: retry indefinitely)\n\
  382. -R, --retry-pause=N time to pause between retries, in seconds (default: 30)\n\
  383. --time-limit=N maximum time [s] to mine before exiting the program.\n\
  384. -T, --timeout=N timeout for long poll and stratum (default: 300 seconds)\n\
  385. -s, --scantime=N upper bound on time spent scanning current work when\n\
  386. long polling is unavailable, in seconds (default: 5)\n\
  387. --randomize Randomize scan range start to reduce duplicates\n\
  388. -f, --diff-factor Divide req. difficulty by this factor (std is 1.0)\n\
  389. -m, --diff-multiplier Multiply difficulty by this factor (std is 1.0)\n\
  390. -n, --nfactor neoscrypt N-Factor\n\
  391. --coinbase-addr=ADDR payout address for solo mining\n\
  392. --coinbase-sig=TEXT data to insert in the coinbase when possible\n\
  393. --max-log-rate limit per-core hashrate logs (default: 5s)\n\
  394. --no-longpoll disable long polling support\n\
  395. --no-getwork disable getwork support\n\
  396. --no-gbt disable getblocktemplate support\n\
  397. --no-stratum disable X-Stratum support\n\
  398. --no-extranonce disable Stratum extranonce support\n\
  399. --no-redirect ignore requests to change the URL of the mining server\n\
  400. -q, --quiet disable per-thread hashmeter output\n\
  401. --no-color disable colored output\n\
  402. -D, --debug enable debug output\n\
  403. -P, --protocol-dump verbose dump of protocol-level activities\n\
  404. --hide-diff Hide submitted block and net difficulty\n"
  405. #ifdef HAVE_SYSLOG_H
  406. "\
  407. -S, --syslog use system log for output messages\n"
  408. #endif
  409. "\
  410. -B, --background run the miner in the background\n\
  411. --benchmark run in offline benchmark mode\n\
  412. --cputest debug hashes from cpu algorithms\n\
  413. --cpu-affinity set process affinity to cpu core(s), mask 0x3 for cores 0 and 1\n\
  414. --cpu-priority set process priority (default: 0 idle, 2 normal to 5 highest)\n\
  415. -b, --api-bind IP/Port for the miner API (default: 127.0.0.1:4048)\n\
  416. --api-remote Allow remote control\n\
  417. --max-temp=N Only mine if cpu temp is less than specified value (linux)\n\
  418. --max-rate=N[KMG] Only mine if net hashrate is less than specified value\n\
  419. --max-diff=N Only mine if net difficulty is less than specified value\n\
  420. -c, --config=FILE load a JSON-format configuration file\n\
  421. -V, --version display version information and exit\n\
  422. -h, --help display this help text and exit\n\
  423. ";
  424. static char const short_options[] =
  425. #ifdef HAVE_SYSLOG_H
  426. "S"
  427. #endif
  428. "a:b:Bc:CDf:hm:n:p:Px:qr:R:s:t:T:o:u:O:V";
  429. static struct option const options[] = {
  430. { "algo", 1, NULL, 'a' },
  431. { "api-bind", 1, NULL, 'b' },
  432. { "api-remote", 0, NULL, 1030 },
  433. { "background", 0, NULL, 'B' },
  434. { "benchmark", 0, NULL, 1005 },
  435. { "cputest", 0, NULL, 1006 },
  436. { "cert", 1, NULL, 1001 },
  437. { "coinbase-addr", 1, NULL, 1016 },
  438. { "coinbase-sig", 1, NULL, 1015 },
  439. { "config", 1, NULL, 'c' },
  440. { "cpu-affinity", 1, NULL, 1020 },
  441. { "cpu-priority", 1, NULL, 1021 },
  442. { "no-color", 0, NULL, 1002 },
  443. { "debug", 0, NULL, 'D' },
  444. { "diff-factor", 1, NULL, 'f' },
  445. { "diff", 1, NULL, 'f' }, // deprecated (alias)
  446. { "diff-multiplier", 1, NULL, 'm' },
  447. { "help", 0, NULL, 'h' },
  448. { "nfactor", 1, NULL, 'n' },
  449. { "no-gbt", 0, NULL, 1011 },
  450. { "no-getwork", 0, NULL, 1010 },
  451. { "no-longpoll", 0, NULL, 1003 },
  452. { "no-redirect", 0, NULL, 1009 },
  453. { "no-stratum", 0, NULL, 1007 },
  454. { "no-extranonce", 0, NULL, 1012 },
  455. { "max-temp", 1, NULL, 1060 },
  456. { "max-diff", 1, NULL, 1061 },
  457. { "max-rate", 1, NULL, 1062 },
  458. { "pass", 1, NULL, 'p' },
  459. { "protocol", 0, NULL, 'P' },
  460. { "protocol-dump", 0, NULL, 'P' },
  461. { "proxy", 1, NULL, 'x' },
  462. { "quiet", 0, NULL, 'q' },
  463. { "retries", 1, NULL, 'r' },
  464. { "retry-pause", 1, NULL, 'R' },
  465. { "randomize", 0, NULL, 1024 },
  466. { "scantime", 1, NULL, 's' },
  467. { "show-diff", 0, NULL, 1013 },
  468. { "hide-diff", 0, NULL, 1014 },
  469. { "max-log-rate", 1, NULL, 1019 },
  470. #ifdef HAVE_SYSLOG_H
  471. { "syslog", 0, NULL, 'S' },
  472. #endif
  473. { "time-limit", 1, NULL, 1008 },
  474. { "threads", 1, NULL, 't' },
  475. { "timeout", 1, NULL, 'T' },
  476. { "url", 1, NULL, 'o' },
  477. { "user", 1, NULL, 'u' },
  478. { "userpass", 1, NULL, 'O' },
  479. { "version", 0, NULL, 'V' },
  480. { 0, 0, 0, 0 }
  481. };
  482. static struct work g_work = {{ 0 }};
  483. static time_t g_work_time = 0;
  484. static pthread_mutex_t g_work_lock;
  485. static bool submit_old = false;
  486. static char *lp_id;
  487. static void workio_cmd_free(struct workio_cmd *wc);
  488. #ifdef __linux /* Linux specific policy and affinity management */
  489. #include <sched.h>
  490. static inline void drop_policy(void)
  491. {
  492. struct sched_param param;
  493. param.sched_priority = 0;
  494. #ifdef SCHED_IDLE
  495. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  496. #endif
  497. #ifdef SCHED_BATCH
  498. sched_setscheduler(0, SCHED_BATCH, &param);
  499. #endif
  500. }
  501. #ifdef __BIONIC__
  502. #define pthread_setaffinity_np(tid,sz,s) {} /* only do process affinity */
  503. #endif
  504. static void affine_to_cpu_mask(int id, unsigned long mask) {
  505. cpu_set_t set;
  506. CPU_ZERO(&set);
  507. for (uint8_t i = 0; i < num_cpus; i++) {
  508. // cpu mask
  509. if (mask & (1UL<<i)) { CPU_SET(i, &set); }
  510. }
  511. if (id == -1) {
  512. // process affinity
  513. sched_setaffinity(0, sizeof(&set), &set);
  514. } else {
  515. // thread only
  516. pthread_setaffinity_np(thr_info[id].pth, sizeof(&set), &set);
  517. }
  518. }
  519. #elif defined(WIN32) /* Windows */
  520. static inline void drop_policy(void) { }
  521. static void affine_to_cpu_mask(int id, unsigned long mask) {
  522. if (id == -1)
  523. SetProcessAffinityMask(GetCurrentProcess(), mask);
  524. else
  525. SetThreadAffinityMask(GetCurrentThread(), mask);
  526. }
  527. #else
  528. static inline void drop_policy(void) { }
  529. static void affine_to_cpu_mask(int id, unsigned long mask) { }
  530. #endif
  531. void get_currentalgo(char* buf, int sz)
  532. {
  533. if (opt_algo == ALGO_SCRYPTJANE)
  534. snprintf(buf, sz, "%s:%d", algo_names[opt_algo], opt_scrypt_n);
  535. else
  536. snprintf(buf, sz, "%s", algo_names[opt_algo]);
  537. }
  538. void proper_exit(int reason)
  539. {
  540. #ifdef WIN32
  541. if (opt_background) {
  542. HWND hcon = GetConsoleWindow();
  543. if (hcon) {
  544. // unhide parent command line windows
  545. ShowWindow(hcon, SW_SHOWMINNOACTIVE);
  546. }
  547. }
  548. #endif
  549. exit(reason);
  550. }
  551. static inline void work_free(struct work *w)
  552. {
  553. if (w->txs) free(w->txs);
  554. if (w->workid) free(w->workid);
  555. if (w->job_id) free(w->job_id);
  556. if (w->xnonce2) free(w->xnonce2);
  557. }
  558. static inline void work_copy(struct work *dest, const struct work *src)
  559. {
  560. memcpy(dest, src, sizeof(struct work));
  561. if (src->txs)
  562. dest->txs = strdup(src->txs);
  563. if (src->workid)
  564. dest->workid = strdup(src->workid);
  565. if (src->job_id)
  566. dest->job_id = strdup(src->job_id);
  567. if (src->xnonce2) {
  568. dest->xnonce2 = (uchar*) malloc(src->xnonce2_len);
  569. memcpy(dest->xnonce2, src->xnonce2, src->xnonce2_len);
  570. }
  571. }
  572. /* compute nbits to get the network diff */
  573. static void calc_network_diff(struct work *work)
  574. {
  575. // sample for diff 43.281 : 1c05ea29
  576. // todo: endian reversed on longpoll could be zr5 specific...
  577. uint32_t nbits = have_longpoll ? work->data[18] : swab32(work->data[18]);
  578. if (opt_algo == ALGO_LBRY) nbits = swab32(work->data[26]);
  579. if (opt_algo == ALGO_DECRED) nbits = work->data[29];
  580. if (opt_algo == ALGO_SIA) nbits = work->data[11]; // unsure if correct
  581. uint32_t bits = (nbits & 0xffffff);
  582. int16_t shift = (swab32(nbits) & 0xff); // 0x1c = 28
  583. double d = (double)0x0000ffff / (double)bits;
  584. for (int m=shift; m < 29; m++) d *= 256.0;
  585. for (int m=29; m < shift; m++) d /= 256.0;
  586. if (opt_algo == ALGO_DECRED && shift == 28) d *= 256.0; // testnet
  587. if (opt_debug_diff)
  588. applog(LOG_DEBUG, "net diff: %f -> shift %u, bits %08x", d, shift, bits);
  589. net_diff = d;
  590. }
  591. static bool work_decode(const json_t *val, struct work *work)
  592. {
  593. int i;
  594. int data_size = 128, target_size = sizeof(work->target);
  595. int adata_sz = 32, atarget_sz = ARRAY_SIZE(work->target);
  596. if (opt_algo == ALGO_DROP || opt_algo == ALGO_NEOSCRYPT || opt_algo == ALGO_ZR5) {
  597. data_size = 80; target_size = 32;
  598. adata_sz = 20;
  599. atarget_sz = target_size / sizeof(uint32_t);
  600. } else if (opt_algo == ALGO_DECRED) {
  601. allow_mininginfo = false;
  602. data_size = 192;
  603. adata_sz = 180/4;
  604. } else if (use_roots) {
  605. data_size = 144;
  606. adata_sz = 36;
  607. }
  608. if (jsonrpc_2) {
  609. return rpc2_job_decode(val, work);
  610. }
  611. if (unlikely(!jobj_binary(val, "data", work->data, data_size))) {
  612. applog(LOG_ERR, "JSON invalid data");
  613. goto err_out;
  614. }
  615. if (unlikely(!jobj_binary(val, "target", work->target, target_size))) {
  616. applog(LOG_ERR, "JSON invalid target");
  617. goto err_out;
  618. }
  619. for (i = 0; i < adata_sz; i++)
  620. work->data[i] = le32dec(work->data + i);
  621. for (i = 0; i < atarget_sz; i++)
  622. work->target[i] = le32dec(work->target + i);
  623. if ((opt_showdiff || opt_max_diff > 0.) && !allow_mininginfo)
  624. calc_network_diff(work);
  625. work->targetdiff = target_to_diff(work->target);
  626. // for api stats, on longpoll pools
  627. stratum_diff = work->targetdiff;
  628. if (opt_algo == ALGO_DROP || opt_algo == ALGO_ZR5) {
  629. #define POK_BOOL_MASK 0x00008000
  630. #define POK_DATA_MASK 0xFFFF0000
  631. if (work->data[0] & POK_BOOL_MASK) {
  632. applog(LOG_BLUE, "POK received: %08xx", work->data[0]);
  633. zr5_pok = work->data[0] & POK_DATA_MASK;
  634. }
  635. } else if (opt_algo == ALGO_DECRED) {
  636. // some random extradata to make the work unique
  637. work->data[36] = (rand()*4);
  638. work->height = work->data[32];
  639. // required for the getwork pools (multicoin.co)
  640. if (!have_longpoll && work->height > net_blocks + 1) {
  641. char netinfo[64] = { 0 };
  642. if (opt_showdiff && net_diff > 0.) {
  643. if (net_diff != work->targetdiff)
  644. sprintf(netinfo, ", diff %.3f, target %.1f", net_diff, work->targetdiff);
  645. else
  646. sprintf(netinfo, ", diff %.3f", net_diff);
  647. }
  648. applog(LOG_BLUE, "%s block %d%s",
  649. algo_names[opt_algo], work->height, netinfo);
  650. net_blocks = work->height - 1;
  651. }
  652. } else if (opt_algo == ALGO_PHI2) {
  653. if (work->data[0] & (1<<30)) use_roots = true;
  654. else for (i = 20; i < 36; i++) {
  655. if (work->data[i]) { use_roots = true; break; }
  656. }
  657. }
  658. return true;
  659. err_out:
  660. return false;
  661. }
  662. // good alternative for wallet mining, difficulty and net hashrate
  663. static const char *info_req =
  664. "{\"method\": \"getmininginfo\", \"params\": [], \"id\":8}\r\n";
  665. static bool get_mininginfo(CURL *curl, struct work *work)
  666. {
  667. if (have_stratum || have_longpoll || !allow_mininginfo)
  668. return false;
  669. int curl_err = 0;
  670. json_t *val = json_rpc_call(curl, rpc_url, rpc_userpass, info_req, &curl_err, 0);
  671. if (!val && curl_err == -1) {
  672. allow_mininginfo = false;
  673. if (opt_debug) {
  674. applog(LOG_DEBUG, "getmininginfo not supported");
  675. }
  676. return false;
  677. }
  678. else {
  679. json_t *res = json_object_get(val, "result");
  680. // "blocks": 491493 (= current work height - 1)
  681. // "difficulty": 0.99607860999999998
  682. // "networkhashps": 56475980
  683. if (res) {
  684. json_t *key = json_object_get(res, "difficulty");
  685. if (key) {
  686. if (json_is_object(key))
  687. key = json_object_get(key, "proof-of-work");
  688. if (json_is_real(key))
  689. net_diff = json_real_value(key);
  690. }
  691. key = json_object_get(res, "networkhashps");
  692. if (key && json_is_integer(key)) {
  693. net_hashrate = (double) json_integer_value(key);
  694. }
  695. key = json_object_get(res, "blocks");
  696. if (key && json_is_integer(key)) {
  697. net_blocks = json_integer_value(key);
  698. }
  699. if (!work->height) {
  700. // complete missing data from getwork
  701. work->height = (uint32_t) net_blocks + 1;
  702. if (work->height > g_work.height) {
  703. restart_threads();
  704. if (!opt_quiet) {
  705. char netinfo[64] = { 0 };
  706. char srate[32] = { 0 };
  707. sprintf(netinfo, "diff %.2f", net_diff);
  708. if (net_hashrate) {
  709. format_hashrate(net_hashrate, srate);
  710. strcat(netinfo, ", net ");
  711. strcat(netinfo, srate);
  712. }
  713. applog(LOG_BLUE, "%s block %d, %s",
  714. algo_names[opt_algo], work->height, netinfo);
  715. }
  716. }
  717. }
  718. }
  719. }
  720. json_decref(val);
  721. return true;
  722. }
  723. #define BLOCK_VERSION_CURRENT 3
  724. static bool gbt_work_decode(const json_t *val, struct work *work)
  725. {
  726. int i, n;
  727. uint32_t version, curtime, bits;
  728. uint32_t prevhash[8];
  729. uint32_t target[8];
  730. int cbtx_size;
  731. uchar *cbtx = NULL;
  732. int tx_count, tx_size;
  733. uchar txc_vi[9];
  734. uchar(*merkle_tree)[32] = NULL;
  735. bool coinbase_append = false;
  736. bool submit_coinbase = false;
  737. bool version_force = false;
  738. bool version_reduce = false;
  739. json_t *tmp, *txa;
  740. bool rc = false;
  741. tmp = json_object_get(val, "mutable");
  742. if (tmp && json_is_array(tmp)) {
  743. n = (int) json_array_size(tmp);
  744. for (i = 0; i < n; i++) {
  745. const char *s = json_string_value(json_array_get(tmp, i));
  746. if (!s)
  747. continue;
  748. if (!strcmp(s, "coinbase/append"))
  749. coinbase_append = true;
  750. else if (!strcmp(s, "submit/coinbase"))
  751. submit_coinbase = true;
  752. else if (!strcmp(s, "version/force"))
  753. version_force = true;
  754. else if (!strcmp(s, "version/reduce"))
  755. version_reduce = true;
  756. }
  757. }
  758. tmp = json_object_get(val, "height");
  759. if (!tmp || !json_is_integer(tmp)) {
  760. applog(LOG_ERR, "JSON invalid height");
  761. goto out;
  762. }
  763. work->height = (int) json_integer_value(tmp);
  764. applog(LOG_BLUE, "Current block is %d", work->height);
  765. tmp = json_object_get(val, "version");
  766. if (!tmp || !json_is_integer(tmp)) {
  767. applog(LOG_ERR, "JSON invalid version");
  768. goto out;
  769. }
  770. version = (uint32_t) json_integer_value(tmp);
  771. if ((version & 0xffU) > BLOCK_VERSION_CURRENT) {
  772. if (version_reduce) {
  773. version = (version & ~0xffU) | BLOCK_VERSION_CURRENT;
  774. } else if (have_gbt && allow_getwork && !version_force) {
  775. applog(LOG_DEBUG, "Switching to getwork, gbt version %d", version);
  776. have_gbt = false;
  777. goto out;
  778. } else if (!version_force) {
  779. applog(LOG_ERR, "Unrecognized block version: %u", version);
  780. goto out;
  781. }
  782. }
  783. if (unlikely(!jobj_binary(val, "previousblockhash", prevhash, sizeof(prevhash)))) {
  784. applog(LOG_ERR, "JSON invalid previousblockhash");
  785. goto out;
  786. }
  787. tmp = json_object_get(val, "curtime");
  788. if (!tmp || !json_is_integer(tmp)) {
  789. applog(LOG_ERR, "JSON invalid curtime");
  790. goto out;
  791. }
  792. curtime = (uint32_t) json_integer_value(tmp);
  793. if (unlikely(!jobj_binary(val, "bits", &bits, sizeof(bits)))) {
  794. applog(LOG_ERR, "JSON invalid bits");
  795. goto out;
  796. }
  797. /* find count and size of transactions */
  798. txa = json_object_get(val, "transactions");
  799. if (!txa || !json_is_array(txa)) {
  800. applog(LOG_ERR, "JSON invalid transactions");
  801. goto out;
  802. }
  803. tx_count = (int) json_array_size(txa);
  804. tx_size = 0;
  805. for (i = 0; i < tx_count; i++) {
  806. const json_t *tx = json_array_get(txa, i);
  807. const char *tx_hex = json_string_value(json_object_get(tx, "data"));
  808. if (!tx_hex) {
  809. applog(LOG_ERR, "JSON invalid transactions");
  810. goto out;
  811. }
  812. tx_size += (int) (strlen(tx_hex) / 2);
  813. }
  814. /* build coinbase transaction */
  815. tmp = json_object_get(val, "coinbasetxn");
  816. if (tmp) {
  817. const char *cbtx_hex = json_string_value(json_object_get(tmp, "data"));
  818. cbtx_size = cbtx_hex ? (int) strlen(cbtx_hex) / 2 : 0;
  819. cbtx = (uchar*) malloc(cbtx_size + 100);
  820. if (cbtx_size < 60 || !hex2bin(cbtx, cbtx_hex, cbtx_size)) {
  821. applog(LOG_ERR, "JSON invalid coinbasetxn");
  822. goto out;
  823. }
  824. } else {
  825. int64_t cbvalue;
  826. if (!pk_script_size) {
  827. if (allow_getwork) {
  828. applog(LOG_INFO, "No payout address provided, switching to getwork");
  829. have_gbt = false;
  830. } else
  831. applog(LOG_ERR, "No payout address provided");
  832. goto out;
  833. }
  834. tmp = json_object_get(val, "coinbasevalue");
  835. if (!tmp || !json_is_number(tmp)) {
  836. applog(LOG_ERR, "JSON invalid coinbasevalue");
  837. goto out;
  838. }
  839. cbvalue = (int64_t) (json_is_integer(tmp) ? json_integer_value(tmp) : json_number_value(tmp));
  840. cbtx = (uchar*) malloc(256);
  841. le32enc((uint32_t *)cbtx, 1); /* version */
  842. cbtx[4] = 1; /* in-counter */
  843. memset(cbtx+5, 0x00, 32); /* prev txout hash */
  844. le32enc((uint32_t *)(cbtx+37), 0xffffffff); /* prev txout index */
  845. cbtx_size = 43;
  846. /* BIP 34: height in coinbase */
  847. for (n = work->height; n; n >>= 8)
  848. cbtx[cbtx_size++] = n & 0xff;
  849. /* If the last byte pushed is >= 0x80, then we need to add
  850. another zero byte to signal that the block height is a
  851. positive number. */
  852. if (cbtx[cbtx_size - 1] & 0x80)
  853. cbtx[cbtx_size++] = 0;
  854. cbtx[42] = cbtx_size - 43;
  855. cbtx[41] = cbtx_size - 42; /* scriptsig length */
  856. le32enc((uint32_t *)(cbtx+cbtx_size), 0xffffffff); /* sequence */
  857. cbtx_size += 4;
  858. cbtx[cbtx_size++] = 1; /* out-counter */
  859. le32enc((uint32_t *)(cbtx+cbtx_size), (uint32_t)cbvalue); /* value */
  860. le32enc((uint32_t *)(cbtx+cbtx_size+4), cbvalue >> 32);
  861. cbtx_size += 8;
  862. cbtx[cbtx_size++] = (uint8_t) pk_script_size; /* txout-script length */
  863. memcpy(cbtx+cbtx_size, pk_script, pk_script_size);
  864. cbtx_size += (int) pk_script_size;
  865. le32enc((uint32_t *)(cbtx+cbtx_size), 0); /* lock time */
  866. cbtx_size += 4;
  867. coinbase_append = true;
  868. }
  869. if (coinbase_append) {
  870. unsigned char xsig[100];
  871. int xsig_len = 0;
  872. if (*coinbase_sig) {
  873. n = (int) strlen(coinbase_sig);
  874. if (cbtx[41] + xsig_len + n <= 100) {
  875. memcpy(xsig+xsig_len, coinbase_sig, n);
  876. xsig_len += n;
  877. } else {
  878. applog(LOG_WARNING, "Signature does not fit in coinbase, skipping");
  879. }
  880. }
  881. tmp = json_object_get(val, "coinbaseaux");
  882. if (tmp && json_is_object(tmp)) {
  883. void *iter = json_object_iter(tmp);
  884. while (iter) {
  885. unsigned char buf[100];
  886. const char *s = json_string_value(json_object_iter_value(iter));
  887. n = s ? (int) (strlen(s) / 2) : 0;
  888. if (!s || n > 100 || !hex2bin(buf, s, n)) {
  889. applog(LOG_ERR, "JSON invalid coinbaseaux");
  890. break;
  891. }
  892. if (cbtx[41] + xsig_len + n <= 100) {
  893. memcpy(xsig+xsig_len, buf, n);
  894. xsig_len += n;
  895. }
  896. iter = json_object_iter_next(tmp, iter);
  897. }
  898. }
  899. if (xsig_len) {
  900. unsigned char *ssig_end = cbtx + 42 + cbtx[41];
  901. int push_len = cbtx[41] + xsig_len < 76 ? 1 :
  902. cbtx[41] + 2 + xsig_len > 100 ? 0 : 2;
  903. n = xsig_len + push_len;
  904. memmove(ssig_end + n, ssig_end, cbtx_size - 42 - cbtx[41]);
  905. cbtx[41] += n;
  906. if (push_len == 2)
  907. *(ssig_end++) = 0x4c; /* OP_PUSHDATA1 */
  908. if (push_len)
  909. *(ssig_end++) = xsig_len;
  910. memcpy(ssig_end, xsig, xsig_len);
  911. cbtx_size += n;
  912. }
  913. }
  914. n = varint_encode(txc_vi, 1 + tx_count);
  915. work->txs = (char*) malloc(2 * (n + cbtx_size + tx_size) + 1);
  916. bin2hex(work->txs, txc_vi, n);
  917. bin2hex(work->txs + 2*n, cbtx, cbtx_size);
  918. /* generate merkle root */
  919. merkle_tree = (uchar(*)[32]) calloc(((1 + tx_count + 1) & ~1), 32);
  920. sha256d(merkle_tree[0], cbtx, cbtx_size);
  921. for (i = 0; i < tx_count; i++) {
  922. tmp = json_array_get(txa, i);
  923. const char *tx_hex = json_string_value(json_object_get(tmp, "data"));
  924. const int tx_size = tx_hex ? (int) (strlen(tx_hex) / 2) : 0;
  925. unsigned char *tx = (uchar*) malloc(tx_size);
  926. if (!tx_hex || !hex2bin(tx, tx_hex, tx_size)) {
  927. applog(LOG_ERR, "JSON invalid transactions");
  928. free(tx);
  929. goto out;
  930. }
  931. sha256d(merkle_tree[1 + i], tx, tx_size);
  932. if (!submit_coinbase)
  933. strcat(work->txs, tx_hex);
  934. }
  935. n = 1 + tx_count;
  936. while (n > 1) {
  937. if (n % 2) {
  938. memcpy(merkle_tree[n], merkle_tree[n-1], 32);
  939. ++n;
  940. }
  941. n /= 2;
  942. for (i = 0; i < n; i++)
  943. sha256d(merkle_tree[i], merkle_tree[2*i], 64);
  944. }
  945. /* assemble block header */
  946. work->data[0] = swab32(version);
  947. for (i = 0; i < 8; i++)
  948. work->data[8 - i] = le32dec(prevhash + i);
  949. for (i = 0; i < 8; i++)
  950. work->data[9 + i] = be32dec((uint32_t *)merkle_tree[0] + i);
  951. work->data[17] = swab32(curtime);
  952. work->data[18] = le32dec(&bits);
  953. memset(work->data + 19, 0x00, 52);
  954. work->data[20] = 0x80000000;
  955. work->data[31] = 0x00000280;
  956. if (unlikely(!jobj_binary(val, "target", target, sizeof(target)))) {
  957. applog(LOG_ERR, "JSON invalid target");
  958. goto out;
  959. }
  960. for (i = 0; i < ARRAY_SIZE(work->target); i++)
  961. work->target[7 - i] = be32dec(target + i);
  962. tmp = json_object_get(val, "workid");
  963. if (tmp) {
  964. if (!json_is_string(tmp)) {
  965. applog(LOG_ERR, "JSON invalid workid");
  966. goto out;
  967. }
  968. work->workid = strdup(json_string_value(tmp));
  969. }
  970. rc = true;
  971. out:
  972. /* Long polling */
  973. tmp = json_object_get(val, "longpollid");
  974. if (want_longpoll && json_is_string(tmp)) {
  975. free(lp_id);
  976. lp_id = strdup(json_string_value(tmp));
  977. if (!have_longpoll) {
  978. char *lp_uri;
  979. tmp = json_object_get(val, "longpolluri");
  980. lp_uri = json_is_string(tmp) ? strdup(json_string_value(tmp)) : rpc_url;
  981. have_longpoll = true;
  982. tq_push(thr_info[longpoll_thr_id].q, lp_uri);
  983. }
  984. }
  985. free(merkle_tree);
  986. free(cbtx);
  987. return rc;
  988. }
  989. #define YES "yes!"
  990. #define YAY "yay!!!"
  991. #define BOO "booooo"
  992. static int share_result(int result, struct work *work, const char *reason)
  993. {
  994. const char *flag;
  995. char suppl[32] = { 0 };
  996. char s[345];
  997. double hashrate;
  998. double sharediff = work ? work->sharediff : stratum.sharediff;
  999. int i;
  1000. hashrate = 0.;
  1001. pthread_mutex_lock(&stats_lock);
  1002. for (i = 0; i < opt_n_threads; i++)
  1003. hashrate += thr_hashrates[i];
  1004. result ? accepted_count++ : rejected_count++;
  1005. pthread_mutex_unlock(&stats_lock);
  1006. global_hashrate = (uint64_t) hashrate;
  1007. if (!net_diff || sharediff < net_diff) {
  1008. flag = use_colors ?
  1009. (result ? CL_GRN YES : CL_RED BOO)
  1010. : (result ? "(" YES ")" : "(" BOO ")");
  1011. } else {
  1012. solved_count++;
  1013. flag = use_colors ?
  1014. (result ? CL_GRN YAY : CL_RED BOO)
  1015. : (result ? "(" YAY ")" : "(" BOO ")");
  1016. }
  1017. if (opt_showdiff)
  1018. sprintf(suppl, "diff %.3f", sharediff);
  1019. else // accepted percent
  1020. sprintf(suppl, "%.2f%%", 100. * accepted_count / (accepted_count + rejected_count));
  1021. switch (opt_algo) {
  1022. case ALGO_AXIOM:
  1023. case ALGO_CRYPTOLIGHT:
  1024. case ALGO_CRYPTONIGHT:
  1025. case ALGO_PLUCK:
  1026. case ALGO_SCRYPTJANE:
  1027. sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", hashrate);
  1028. applog(LOG_NOTICE, "accepted: %lu/%lu (%s), %s H/s %s",
  1029. accepted_count, accepted_count + rejected_count,
  1030. suppl, s, flag);
  1031. break;
  1032. default:
  1033. sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", hashrate / 1000.0);
  1034. applog(LOG_NOTICE, "accepted: %lu/%lu (%s), %s kH/s %s",
  1035. accepted_count, accepted_count + rejected_count,
  1036. suppl, s, flag);
  1037. break;
  1038. }
  1039. if (reason) {
  1040. applog(LOG_WARNING, "reject reason: %s", reason);
  1041. if (0 && strncmp(reason, "low difficulty share", 20) == 0) {
  1042. opt_diff_factor = (opt_diff_factor * 2.0) / 3.0;
  1043. applog(LOG_WARNING, "factor reduced to : %0.2f", opt_diff_factor);
  1044. return 0;
  1045. }
  1046. }
  1047. return 1;
  1048. }
  1049. static bool submit_upstream_work(CURL *curl, struct work *work)
  1050. {
  1051. json_t *val, *res, *reason;
  1052. char s[JSON_BUF_LEN];
  1053. int i;
  1054. bool rc = false;
  1055. /* pass if the previous hash is not the current previous hash */
  1056. if (opt_algo != ALGO_SIA && !submit_old && memcmp(&work->data[1], &g_work.data[1], 32)) {
  1057. if (opt_debug)
  1058. applog(LOG_DEBUG, "DEBUG: stale work detected, discarding");
  1059. return true;
  1060. }
  1061. if (!have_stratum && allow_mininginfo) {
  1062. struct work wheight;
  1063. get_mininginfo(curl, &wheight);
  1064. if (work->height && work->height <= net_blocks) {
  1065. if (opt_debug)
  1066. applog(LOG_WARNING, "block %u was already solved", work->height);
  1067. return true;
  1068. }
  1069. }
  1070. if (have_stratum) {
  1071. uint32_t ntime, nonce;
  1072. char ntimestr[9], noncestr[9];
  1073. if (jsonrpc_2) {
  1074. uchar hash[32];
  1075. bin2hex(noncestr, (const unsigned char *)work->data + 39, 4);
  1076. switch(opt_algo) {
  1077. case ALGO_CRYPTOLIGHT:
  1078. cryptolight_hash(hash, work->data);
  1079. break;
  1080. case ALGO_CRYPTONIGHT:
  1081. cryptonight_hash(hash, work->data);
  1082. default:
  1083. break;
  1084. }
  1085. char *hashhex = abin2hex(hash, 32);
  1086. snprintf(s, JSON_BUF_LEN,
  1087. "{\"method\": \"submit\", \"params\": {\"id\": \"%s\", \"job_id\": \"%s\", \"nonce\": \"%s\", \"result\": \"%s\"}, \"id\":4}\r\n",
  1088. rpc2_id, work->job_id, noncestr, hashhex);
  1089. free(hashhex);
  1090. } else {
  1091. char *xnonce2str;
  1092. switch (opt_algo) {
  1093. case ALGO_DECRED:
  1094. /* reversed */
  1095. be32enc(&ntime, work->data[34]);
  1096. be32enc(&nonce, work->data[35]);
  1097. break;
  1098. case ALGO_LBRY:
  1099. le32enc(&ntime, work->data[25]);
  1100. le32enc(&nonce, work->data[27]);
  1101. break;
  1102. case ALGO_DROP:
  1103. case ALGO_NEOSCRYPT:
  1104. case ALGO_ZR5:
  1105. /* reversed */
  1106. be32enc(&ntime, work->data[17]);
  1107. be32enc(&nonce, work->data[19]);
  1108. break;
  1109. case ALGO_SIA:
  1110. /* reversed */
  1111. be32enc(&ntime, work->data[10]);
  1112. be32enc(&nonce, work->data[8]);
  1113. break;
  1114. default:
  1115. le32enc(&ntime, work->data[17]);
  1116. le32enc(&nonce, work->data[19]);
  1117. }
  1118. bin2hex(ntimestr, (const unsigned char *)(&ntime), 4);
  1119. bin2hex(noncestr, (const unsigned char *)(&nonce), 4);
  1120. if (opt_algo == ALGO_DECRED) {
  1121. xnonce2str = abin2hex((unsigned char*)(&work->data[36]), stratum.xnonce1_size);
  1122. } else if (opt_algo == ALGO_SIA) {
  1123. uint16_t high_nonce = swab32(work->data[9]) >> 16;
  1124. xnonce2str = abin2hex((unsigned char*)(&high_nonce), 2);
  1125. } else {
  1126. xnonce2str = abin2hex(work->xnonce2, work->xnonce2_len);
  1127. }
  1128. snprintf(s, JSON_BUF_LEN,
  1129. "{\"method\": \"mining.submit\", \"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":4}",
  1130. rpc_user, work->job_id, xnonce2str, ntimestr, noncestr);
  1131. free(xnonce2str);
  1132. }
  1133. // store to keep/display solved blocs (work struct not linked on accept notification)
  1134. stratum.sharediff = work->sharediff;
  1135. if (unlikely(!stratum_send_line(&stratum, s))) {
  1136. applog(LOG_ERR, "submit_upstream_work stratum_send_line failed");
  1137. goto out;
  1138. }
  1139. } else if (work->txs) { /* gbt */
  1140. char data_str[2 * sizeof(work->data) + 1];
  1141. char *req;
  1142. for (i = 0; i < ARRAY_SIZE(work->data); i++)
  1143. be32enc(work->data + i, work->data[i]);
  1144. bin2hex(data_str, (unsigned char *)work->data, 80);
  1145. if (work->workid) {
  1146. char *params;
  1147. val = json_object();
  1148. json_object_set_new(val, "workid", json_string(work->workid));
  1149. params = json_dumps(val, 0);
  1150. json_decref(val);
  1151. req = (char*) malloc(128 + 2 * 80 + strlen(work->txs) + strlen(params));
  1152. sprintf(req,
  1153. "{\"method\": \"submitblock\", \"params\": [\"%s%s\", %s], \"id\":4}\r\n",
  1154. data_str, work->txs, params);
  1155. free(params);
  1156. } else {
  1157. req = (char*) malloc(128 + 2 * 80 + strlen(work->txs));
  1158. sprintf(req,
  1159. "{\"method\": \"submitblock\", \"params\": [\"%s%s\"], \"id\":4}\r\n",
  1160. data_str, work->txs);
  1161. }
  1162. val = json_rpc_call(curl, rpc_url, rpc_userpass, req, NULL, 0);
  1163. free(req);
  1164. if (unlikely(!val)) {
  1165. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  1166. goto out;
  1167. }
  1168. res = json_object_get(val, "result");
  1169. if (json_is_object(res)) {
  1170. char *res_str;
  1171. bool sumres = false;
  1172. void *iter = json_object_iter(res);
  1173. while (iter) {
  1174. if (json_is_null(json_object_iter_value(iter))) {
  1175. sumres = true;
  1176. break;
  1177. }
  1178. iter = json_object_iter_next(res, iter);
  1179. }
  1180. res_str = json_dumps(res, 0);
  1181. share_result(sumres, work, res_str);
  1182. free(res_str);
  1183. } else
  1184. share_result(json_is_null(res), work, json_string_value(res));
  1185. json_decref(val);
  1186. } else {
  1187. char* gw_str = NULL;
  1188. int data_size = 128;
  1189. int adata_sz;
  1190. if (jsonrpc_2) {
  1191. char noncestr[9];
  1192. uchar hash[32];
  1193. char *hashhex;
  1194. bin2hex(noncestr, (const unsigned char *)work->data + 39, 4);
  1195. switch(opt_algo) {
  1196. case ALGO_CRYPTOLIGHT:
  1197. cryptolight_hash(hash, work->data);
  1198. break;
  1199. case ALGO_CRYPTONIGHT:
  1200. cryptonight_hash(hash, work->data);
  1201. default:
  1202. break;
  1203. }
  1204. hashhex = abin2hex(&hash[0], 32);
  1205. snprintf(s, JSON_BUF_LEN,
  1206. "{\"method\": \"submit\", \"params\": "
  1207. "{\"id\": \"%s\", \"job_id\": \"%s\", \"nonce\": \"%s\", \"result\": \"%s\"},"
  1208. "\"id\":4}\r\n",
  1209. rpc2_id, work->job_id, noncestr, hashhex);
  1210. free(hashhex);
  1211. /* issue JSON-RPC request */
  1212. val = json_rpc2_call(curl, rpc_url, rpc_userpass, s, NULL, 0);
  1213. if (unlikely(!val)) {
  1214. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  1215. goto out;
  1216. }
  1217. res = json_object_get(val, "result");
  1218. json_t *status = json_object_get(res, "status");
  1219. bool valid = !strcmp(status ? json_string_value(status) : "", "OK");
  1220. if (valid)
  1221. share_result(valid, work, NULL);
  1222. else {
  1223. json_t *err = json_object_get(res, "error");
  1224. const char *sreason = json_string_value(json_object_get(err, "message"));
  1225. share_result(valid, work, sreason);
  1226. if (!strcasecmp("Invalid job id", sreason)) {
  1227. work_free(work);
  1228. work_copy(work, &g_work);
  1229. g_work_time = 0;
  1230. restart_threads();
  1231. }
  1232. }
  1233. json_decref(val);
  1234. return true;
  1235. } else if (opt_algo == ALGO_DROP || opt_algo == ALGO_NEOSCRYPT || opt_algo == ALGO_ZR5) {
  1236. /* different data size */
  1237. data_size = 80;
  1238. } else if (opt_algo == ALGO_DECRED) {
  1239. /* bigger data size : 180 + terminal hash ending */
  1240. data_size = 192;
  1241. } else if (opt_algo == ALGO_PHI2 && use_roots) {
  1242. data_size = 144;
  1243. }
  1244. adata_sz = data_size / sizeof(uint32_t);
  1245. if (opt_algo == ALGO_DECRED) adata_sz = 180 / 4; // dont touch the end tag
  1246. /* build hex string */
  1247. for (i = 0; i < adata_sz; i++)
  1248. le32enc(&work->data[i], work->data[i]);
  1249. gw_str = abin2hex((uchar*)work->data, data_size);
  1250. if (unlikely(!gw_str)) {
  1251. applog(LOG_ERR, "submit_upstream_work OOM");
  1252. return false;
  1253. }
  1254. //applog(LOG_WARNING, gw_str);
  1255. /* build JSON-RPC request */
  1256. snprintf(s, JSON_BUF_LEN,
  1257. "{\"method\": \"getwork\", \"params\": [\"%s\"], \"id\":4}\r\n", gw_str);
  1258. free(gw_str);
  1259. /* issue JSON-RPC request */
  1260. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, NULL, 0);
  1261. if (unlikely(!val)) {
  1262. applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
  1263. goto out;
  1264. }
  1265. res = json_object_get(val, "result");
  1266. reason = json_object_get(val, "reject-reason");
  1267. share_result(json_is_true(res), work, reason ? json_string_value(reason) : NULL);
  1268. json_decref(val);
  1269. }
  1270. rc = true;
  1271. out:
  1272. return rc;
  1273. }
  1274. static const char *getwork_req =
  1275. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1276. #define GBT_CAPABILITIES "[\"coinbasetxn\", \"coinbasevalue\", \"longpoll\", \"workid\"]"
  1277. static const char *gbt_req =
  1278. "{\"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": "
  1279. GBT_CAPABILITIES "}], \"id\":0}\r\n";
  1280. static const char *gbt_lp_req =
  1281. "{\"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": "
  1282. GBT_CAPABILITIES ", \"longpollid\": \"%s\"}], \"id\":0}\r\n";
  1283. static bool get_upstream_work(CURL *curl, struct work *work)
  1284. {
  1285. json_t *val;
  1286. int err;
  1287. bool rc;
  1288. struct timeval tv_start, tv_end, diff;
  1289. start:
  1290. gettimeofday(&tv_start, NULL);
  1291. if (jsonrpc_2) {
  1292. char s[128];
  1293. snprintf(s, 128, "{\"method\": \"getjob\", \"params\": {\"id\": \"%s\"}, \"id\":1}\r\n", rpc2_id);
  1294. val = json_rpc2_call(curl, rpc_url, rpc_userpass, s, NULL, 0);
  1295. } else {
  1296. val = json_rpc_call(curl, rpc_url, rpc_userpass,
  1297. have_gbt ? gbt_req : getwork_req,
  1298. &err, have_gbt ? JSON_RPC_QUIET_404 : 0);
  1299. }
  1300. gettimeofday(&tv_end, NULL);
  1301. if (have_stratum) {
  1302. if (val)
  1303. json_decref(val);
  1304. return true;
  1305. }
  1306. if (!have_gbt && !allow_getwork) {
  1307. applog(LOG_ERR, "No usable protocol");
  1308. if (val)
  1309. json_decref(val);
  1310. return false;
  1311. }
  1312. if (have_gbt && allow_getwork && !val && err == CURLE_OK) {
  1313. applog(LOG_NOTICE, "getblocktemplate failed, falling back to getwork");
  1314. have_gbt = false;
  1315. goto start;
  1316. }
  1317. if (!val)
  1318. return false;
  1319. if (have_gbt) {
  1320. rc = gbt_work_decode(json_object_get(val, "result"), work);
  1321. if (!have_gbt) {
  1322. json_decref(val);
  1323. goto start;
  1324. }
  1325. } else {
  1326. rc = work_decode(json_object_get(val, "result"), work);
  1327. }
  1328. if (opt_protocol && rc) {
  1329. timeval_subtract(&diff, &tv_end, &tv_start);
  1330. applog(LOG_DEBUG, "got new work in %.2f ms",
  1331. (1000.0 * diff.tv_sec) + (0.001 * diff.tv_usec));
  1332. }
  1333. json_decref(val);
  1334. // store work height in solo
  1335. get_mininginfo(curl, work);
  1336. return rc;
  1337. }
  1338. static void workio_cmd_free(struct workio_cmd *wc)
  1339. {
  1340. if (!wc)
  1341. return;
  1342. switch (wc->cmd) {
  1343. case WC_SUBMIT_WORK:
  1344. work_free(wc->u.work);
  1345. free(wc->u.work);
  1346. break;
  1347. default: /* do nothing */
  1348. break;
  1349. }
  1350. memset(wc, 0, sizeof(*wc)); /* poison */
  1351. free(wc);
  1352. }
  1353. static bool workio_get_work(struct workio_cmd *wc, CURL *curl)
  1354. {
  1355. struct work *ret_work;
  1356. int failures = 0;
  1357. ret_work = (struct work*) calloc(1, sizeof(*ret_work));
  1358. if (!ret_work)
  1359. return false;
  1360. /* obtain new work from bitcoin via JSON-RPC */
  1361. while (!get_upstream_work(curl, ret_work)) {
  1362. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1363. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1364. free(ret_work);
  1365. return false;
  1366. }
  1367. /* pause, then restart work-request loop */
  1368. applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
  1369. opt_fail_pause);
  1370. sleep(opt_fail_pause);
  1371. }
  1372. /* send work to requesting thread */
  1373. if (!tq_push(wc->thr->q, ret_work))
  1374. free(ret_work);
  1375. return true;
  1376. }
  1377. static bool workio_submit_work(struct workio_cmd *wc, CURL *curl)
  1378. {
  1379. int failures = 0;
  1380. /* submit solution to bitcoin via JSON-RPC */
  1381. while (!submit_upstream_work(curl, wc->u.work)) {
  1382. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1383. applog(LOG_ERR, "...terminating workio thread");
  1384. return false;
  1385. }
  1386. /* pause, then restart work-request loop */
  1387. if (!opt_benchmark)
  1388. applog(LOG_ERR, "...retry after %d seconds", opt_fail_pause);
  1389. sleep(opt_fail_pause);
  1390. }
  1391. return true;
  1392. }
  1393. bool rpc2_login(CURL *curl)
  1394. {
  1395. json_t *val;
  1396. bool rc = false;
  1397. struct timeval tv_start, tv_end, diff;
  1398. char s[JSON_BUF_LEN];
  1399. if (!jsonrpc_2)
  1400. return false;
  1401. snprintf(s, JSON_BUF_LEN, "{\"method\": \"login\", \"params\": {"
  1402. "\"login\": \"%s\", \"pass\": \"%s\", \"agent\": \"%s\"}, \"id\": 1}",
  1403. rpc_user, rpc_pass, USER_AGENT);
  1404. gettimeofday(&tv_start, NULL);
  1405. val = json_rpc_call(curl, rpc_url, rpc_userpass, s, NULL, 0);
  1406. gettimeofday(&tv_end, NULL);
  1407. if (!val)
  1408. goto end;
  1409. // applog(LOG_DEBUG, "JSON value: %s", json_dumps(val, 0));
  1410. rc = rpc2_login_decode(val);
  1411. json_t *result = json_object_get(val, "result");
  1412. if (!result)
  1413. goto end;
  1414. json_t *job = json_object_get(result, "job");
  1415. if (!rpc2_job_decode(job, &g_work)) {
  1416. goto end;
  1417. }
  1418. if (opt_debug && rc) {
  1419. timeval_subtract(&diff, &tv_end, &tv_start);
  1420. applog(LOG_DEBUG, "DEBUG: authenticated in %d ms",
  1421. diff.tv_sec * 1000 + diff.tv_usec / 1000);
  1422. }
  1423. json_decref(val);
  1424. end:
  1425. return rc;
  1426. }
  1427. bool rpc2_workio_login(CURL *curl)
  1428. {
  1429. int failures = 0;
  1430. if (opt_benchmark)
  1431. return true;
  1432. /* submit solution to bitcoin via JSON-RPC */
  1433. pthread_mutex_lock(&rpc2_login_lock);
  1434. while (!rpc2_login(curl)) {
  1435. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1436. applog(LOG_ERR, "...terminating workio thread");
  1437. pthread_mutex_unlock(&rpc2_login_lock);
  1438. return false;
  1439. }
  1440. /* pause, then restart work-request loop */
  1441. if (!opt_benchmark)
  1442. applog(LOG_ERR, "...retry after %d seconds", opt_fail_pause);
  1443. sleep(opt_fail_pause);
  1444. pthread_mutex_unlock(&rpc2_login_lock);
  1445. pthread_mutex_lock(&rpc2_login_lock);
  1446. }
  1447. pthread_mutex_unlock(&rpc2_login_lock);
  1448. return true;
  1449. }
  1450. static void *workio_thread(void *userdata)
  1451. {
  1452. struct thr_info *mythr = (struct thr_info *) userdata;
  1453. CURL *curl;
  1454. bool ok = true;
  1455. curl = curl_easy_init();
  1456. if (unlikely(!curl)) {
  1457. applog(LOG_ERR, "CURL initialization failed");
  1458. return NULL;
  1459. }
  1460. if(jsonrpc_2 && !have_stratum) {
  1461. ok = rpc2_workio_login(curl);
  1462. }
  1463. while (ok) {
  1464. struct workio_cmd *wc;
  1465. /* wait for workio_cmd sent to us, on our queue */
  1466. wc = (struct workio_cmd *) tq_pop(mythr->q, NULL);
  1467. if (!wc) {
  1468. ok = false;
  1469. break;
  1470. }
  1471. /* process workio_cmd */
  1472. switch (wc->cmd) {
  1473. case WC_GET_WORK:
  1474. ok = workio_get_work(wc, curl);
  1475. break;
  1476. case WC_SUBMIT_WORK:
  1477. ok = workio_submit_work(wc, curl);
  1478. break;
  1479. default: /* should never happen */
  1480. ok = false;
  1481. break;
  1482. }
  1483. workio_cmd_free(wc);
  1484. }
  1485. tq_freeze(mythr->q);
  1486. curl_easy_cleanup(curl);
  1487. return NULL;
  1488. }
  1489. static bool get_work(struct thr_info *thr, struct work *work)
  1490. {
  1491. struct workio_cmd *wc;
  1492. struct work *work_heap;
  1493. if (opt_benchmark) {
  1494. uint32_t ts = (uint32_t) time(NULL);
  1495. for (int n=0; n<74; n++) ((char*)work->data)[n] = n;
  1496. //memset(work->data, 0x55, 76);
  1497. work->data[17] = swab32(ts);
  1498. memset(work->data + 19, 0x00, 52);
  1499. if (opt_algo == ALGO_DECRED) {
  1500. memset(&work->data[35], 0x00, 52);
  1501. } else {
  1502. work->data[20] = 0x80000000;
  1503. work->data[31] = 0x00000280;
  1504. }
  1505. memset(work->target, 0x00, sizeof(work->target));
  1506. return true;
  1507. }
  1508. /* fill out work request message */
  1509. wc = (struct workio_cmd *) calloc(1, sizeof(*wc));
  1510. if (!wc)
  1511. return false;
  1512. wc->cmd = WC_GET_WORK;
  1513. wc->thr = thr;
  1514. /* send work request to workio thread */
  1515. if (!tq_push(thr_info[work_thr_id].q, wc)) {
  1516. workio_cmd_free(wc);
  1517. return false;
  1518. }
  1519. /* wait for response, a unit of work */
  1520. work_heap = (struct work*) tq_pop(thr->q, NULL);
  1521. if (!work_heap)
  1522. return false;
  1523. /* copy returned work into storage provided by caller */
  1524. memcpy(work, work_heap, sizeof(*work));
  1525. free(work_heap);
  1526. return true;
  1527. }
  1528. static bool submit_work(struct thr_info *thr, const struct work *work_in)
  1529. {
  1530. struct workio_cmd *wc;
  1531. /* fill out work request message */
  1532. wc = (struct workio_cmd *) calloc(1, sizeof(*wc));
  1533. if (!wc)
  1534. return false;
  1535. wc->u.work = (struct work*) malloc(sizeof(*work_in));
  1536. if (!wc->u.work)
  1537. goto err_out;
  1538. wc->cmd = WC_SUBMIT_WORK;
  1539. wc->thr = thr;
  1540. work_copy(wc->u.work, work_in);
  1541. /* send solution to workio thread */
  1542. if (!tq_push(thr_info[work_thr_id].q, wc))
  1543. goto err_out;
  1544. return true;
  1545. err_out:
  1546. workio_cmd_free(wc);
  1547. return false;
  1548. }
  1549. static void stratum_gen_work(struct stratum_ctx *sctx, struct work *work)
  1550. {
  1551. uint32_t extraheader[32] = { 0 };
  1552. uchar merkle_root[64] = { 0 };
  1553. int i, headersize = 0;
  1554. pthread_mutex_lock(&sctx->work_lock);
  1555. if (jsonrpc_2) {
  1556. work_free(work);
  1557. work_copy(work, &sctx->work);
  1558. pthread_mutex_unlock(&sctx->work_lock);
  1559. } else {
  1560. free(work->job_id);
  1561. work->job_id = strdup(sctx->job.job_id);
  1562. work->xnonce2_len = sctx->xnonce2_size;
  1563. work->xnonce2 = (uchar*) realloc(work->xnonce2, sctx->xnonce2_size);
  1564. memcpy(work->xnonce2, sctx->job.xnonce2, sctx->xnonce2_size);
  1565. /* Generate merkle root */
  1566. switch (opt_algo) {
  1567. case ALGO_DECRED:
  1568. // getwork over stratum, getwork merkle + header passed in coinb1
  1569. memcpy(merkle_root, sctx->job.coinbase, 32);
  1570. headersize = min((int)sctx->job.coinbase_size - 32, sizeof(extraheader));
  1571. memcpy(extraheader, &sctx->job.coinbase[32], headersize);
  1572. break;
  1573. case ALGO_HEAVY:
  1574. heavyhash(merkle_root, sctx->job.coinbase, (int)sctx->job.coinbase_size);
  1575. break;
  1576. case ALGO_GROESTL:
  1577. case ALGO_KECCAK:
  1578. case ALGO_BLAKECOIN:
  1579. SHA256(sctx->job.coinbase, (int) sctx->job.coinbase_size, merkle_root);
  1580. break;
  1581. case ALGO_SIA:
  1582. // getwork over stratum, getwork merkle + header passed in coinb1
  1583. memcpy(merkle_root, sctx->job.coinbase, 32);
  1584. headersize = min((int)sctx->job.coinbase_size - 32, sizeof(extraheader));
  1585. memcpy(extraheader, &sctx->job.coinbase[32], headersize);
  1586. break;
  1587. default:
  1588. sha256d(merkle_root, sctx->job.coinbase, (int) sctx->job.coinbase_size);
  1589. }
  1590. if (!headersize)
  1591. for (i = 0; i < sctx->job.merkle_count; i++) {
  1592. memcpy(merkle_root + 32, sctx->job.merkle[i], 32);
  1593. if (opt_algo == ALGO_HEAVY)
  1594. heavyhash(merkle_root, merkle_root, 64);
  1595. else
  1596. sha256d(merkle_root, merkle_root, 64);
  1597. }
  1598. /* Increment extranonce2 */
  1599. for (size_t t = 0; t < sctx->xnonce2_size && !(++sctx->job.xnonce2[t]); t++)
  1600. ;
  1601. /* Assemble block header */
  1602. memset(work->data, 0, 128);
  1603. work->data[0] = le32dec(sctx->job.version);
  1604. for (i = 0; i < 8; i++)
  1605. work->data[1 + i] = le32dec((uint32_t *) sctx->job.prevhash + i);
  1606. for (i = 0; i < 8; i++)
  1607. work->data[9 + i] = be32dec((uint32_t *) merkle_root + i);
  1608. if (opt_algo == ALGO_DECRED) {
  1609. uint32_t* extradata = (uint32_t*) sctx->xnonce1;
  1610. for (i = 0; i < 8; i++) // prevhash
  1611. work->data[1 + i] = swab32(work->data[1 + i]);
  1612. for (i = 0; i < 8; i++) // merkle
  1613. work->data[9 + i] = swab32(work->data[9 + i]);
  1614. for (i = 0; i < headersize/4; i++) // header
  1615. work->data[17 + i] = extraheader[i];
  1616. // extradata
  1617. for (i = 0; i < sctx->xnonce1_size/4; i++)
  1618. work->data[36 + i] = extradata[i];
  1619. for (i = 36 + (int) sctx->xnonce1_size/4; i < 45; i++)
  1620. work->data[i] = 0;
  1621. work->data[37] = (rand()*4) << 8;
  1622. sctx->bloc_height = work->data[32];
  1623. //applog_hex(work->data, 180);
  1624. //applog_hex(&work->data[36], 36);
  1625. } else if (opt_algo == ALGO_LBRY) {
  1626. for (i = 0; i < 8; i++)
  1627. work->data[17 + i] = ((uint32_t*)sctx->job.extra)[i];
  1628. work->data[25] = le32dec(sctx->job.ntime);
  1629. work->data[26] = le32dec(sctx->job.nbits);
  1630. work->data[28] = 0x80000000;
  1631. } else if (opt_algo == ALGO_PHI2) {
  1632. work->data[17] = le32dec(sctx->job.ntime);
  1633. work->data[18] = le32dec(sctx->job.nbits);
  1634. for (i = 0; i < 16; i++)
  1635. work->data[20 + i] = ((uint32_t*)sctx->job.extra)[i];
  1636. //applog_hex(&work->data[0], 144);
  1637. } else if (opt_algo == ALGO_SIA) {
  1638. for (i = 0; i < 8; i++) // prevhash
  1639. work->data[i] = ((uint32_t*)sctx->job.prevhash)[7-i];
  1640. work->data[8] = 0; // nonce
  1641. work->data[9] = swab32(extraheader[0]);
  1642. work->data[9] |= rand() & 0xF0;
  1643. work->data[10] = be32dec(sctx->job.ntime);
  1644. work->data[11] = be32dec(sctx->job.nbits);
  1645. for (i = 0; i < 8; i++) // prevhash
  1646. work->data[12+i] = ((uint32_t*)merkle_root)[i];
  1647. //applog_hex(&work->data[0], 80);
  1648. } else {
  1649. work->data[17] = le32dec(sctx->job.ntime);
  1650. work->data[18] = le32dec(sctx->job.nbits);
  1651. // required ?
  1652. work->data[20] = 0x80000000;
  1653. work->data[31] = 0x00000280;
  1654. }
  1655. if (opt_showdiff || opt_max_diff > 0.)
  1656. calc_network_diff(work);
  1657. if (opt_algo == ALGO_DROP || opt_algo == ALGO_NEOSCRYPT || opt_algo == ALGO_ZR5) {
  1658. /* reversed endian */
  1659. for (i = 0; i <= 18; i++)
  1660. work->data[i] = swab32(work->data[i]);
  1661. }
  1662. pthread_mutex_unlock(&sctx->work_lock);
  1663. if (opt_debug && opt_algo != ALGO_DECRED && opt_algo != ALGO_SIA) {
  1664. char *xnonce2str = abin2hex(work->xnonce2, work->xnonce2_len);
  1665. applog(LOG_DEBUG, "DEBUG: job_id='%s' extranonce2=%s ntime=%08x",
  1666. work->job_id, xnonce2str, swab32(work->data[17]));
  1667. free(xnonce2str);
  1668. }
  1669. switch (opt_algo) {
  1670. case ALGO_DROP:
  1671. case ALGO_JHA:
  1672. case ALGO_SCRYPT:
  1673. case ALGO_SCRYPTJANE:
  1674. case ALGO_NEOSCRYPT:
  1675. case ALGO_PLUCK:
  1676. case ALGO_YESCRYPT:
  1677. case ALGO_YESCRYPTR8:
  1678. case ALGO_YESCRYPTR16:
  1679. case ALGO_YESCRYPTR32:
  1680. work_set_target(work, sctx->job.diff / (65536.0 * opt_diff_factor));
  1681. break;
  1682. case ALGO_ALLIUM:
  1683. case ALGO_FRESH:
  1684. case ALGO_DMD_GR:
  1685. case ALGO_GROESTL:
  1686. case ALGO_KECCAKC:
  1687. case ALGO_LBRY:
  1688. case ALGO_LYRA2REV2:
  1689. case ALGO_LYRA2V3:
  1690. case ALGO_PHI2:
  1691. case ALGO_TIMETRAVEL:
  1692. case ALGO_BITCORE:
  1693. case ALGO_XEVAN:
  1694. case ALGO_X16R:
  1695. case ALGO_X16RV2:
  1696. case ALGO_X16S:
  1697. case ALGO_X20R:
  1698. work_set_target(work, sctx->job.diff / (256.0 * opt_diff_factor));
  1699. break;
  1700. case ALGO_KECCAK:
  1701. case ALGO_LYRA2:
  1702. work_set_target(work, sctx->job.diff / (128.0 * opt_diff_factor));
  1703. break;
  1704. default:
  1705. work_set_target(work, sctx->job.diff / opt_diff_factor);
  1706. }
  1707. if (stratum_diff != sctx->job.diff) {
  1708. char sdiff[32] = { 0 };
  1709. // store for api stats
  1710. stratum_diff = sctx->job.diff;
  1711. if (opt_showdiff && work->targetdiff != stratum_diff)
  1712. snprintf(sdiff, 32, " (%.5f)", work->targetdiff);
  1713. applog(LOG_WARNING, "Stratum difficulty set to %g%s", stratum_diff, sdiff);
  1714. }
  1715. }
  1716. }
  1717. bool rpc2_stratum_job(struct stratum_ctx *sctx, json_t *params)
  1718. {
  1719. bool ret = false;
  1720. pthread_mutex_lock(&sctx->work_lock);
  1721. ret = rpc2_job_decode(params, &sctx->work);
  1722. if (ret) {
  1723. work_free(&g_work);
  1724. work_copy(&g_work, &sctx->work);
  1725. g_work_time = 0;
  1726. }
  1727. pthread_mutex_unlock(&sctx->work_lock);
  1728. return ret;
  1729. }
  1730. static bool wanna_mine(int thr_id)
  1731. {
  1732. bool state = true;
  1733. if (opt_max_temp > 0.0) {
  1734. float temp = cpu_temp(0);
  1735. if (temp > opt_max_temp) {
  1736. if (!thr_id && !conditional_state[thr_id] && !opt_quiet)
  1737. applog(LOG_INFO, "temperature too high (%.0fC), waiting...", temp);
  1738. state = false;
  1739. }
  1740. }
  1741. if (opt_max_diff > 0.0 && net_diff > opt_max_diff) {
  1742. if (!thr_id && !conditional_state[thr_id] && !opt_quiet)
  1743. applog(LOG_INFO, "network diff too high, waiting...");
  1744. state = false;
  1745. }
  1746. if (opt_max_rate > 0.0 && net_hashrate > opt_max_rate) {
  1747. if (!thr_id && !conditional_state[thr_id] && !opt_quiet) {
  1748. char rate[32];
  1749. format_hashrate(opt_max_rate, rate);
  1750. applog(LOG_INFO, "network hashrate too high, waiting %s...", rate);
  1751. }
  1752. state = false;
  1753. }
  1754. if (thr_id < MAX_CPUS)
  1755. conditional_state[thr_id] = (uint8_t) !state;
  1756. return state;
  1757. }
  1758. static void *miner_thread(void *userdata)
  1759. {
  1760. struct thr_info *mythr = (struct thr_info *) userdata;
  1761. int thr_id = mythr->id;
  1762. struct work work;
  1763. uint32_t max_nonce;
  1764. uint32_t end_nonce = 0xffffffffU / opt_n_threads * (thr_id + 1) - 0x20;
  1765. time_t tm_rate_log = 0;
  1766. time_t firstwork_time = 0;
  1767. unsigned char *scratchbuf = NULL;
  1768. char s[16];
  1769. int i;
  1770. memset(&work, 0, sizeof(work));
  1771. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  1772. * and if that fails, then SCHED_BATCH. No need for this to be an
  1773. * error if it fails */
  1774. if (!opt_benchmark && opt_priority == 0) {
  1775. setpriority(PRIO_PROCESS, 0, 19);
  1776. drop_policy();
  1777. } else {
  1778. int prio = 0;
  1779. #ifndef WIN32
  1780. prio = 18;
  1781. // note: different behavior on linux (-19 to 19)
  1782. switch (opt_priority) {
  1783. case 1:
  1784. prio = 5;
  1785. break;
  1786. case 2:
  1787. prio = 0;
  1788. break;
  1789. case 3:
  1790. prio = -5;
  1791. break;
  1792. case 4:
  1793. prio = -10;
  1794. break;
  1795. case 5:
  1796. prio = -15;
  1797. }
  1798. if (opt_debug)
  1799. applog(LOG_DEBUG, "Thread %d priority %d (nice %d)",
  1800. thr_id, opt_priority, prio);
  1801. #endif
  1802. setpriority(PRIO_PROCESS, 0, prio);
  1803. if (opt_priority == 0) {
  1804. drop_policy();
  1805. }
  1806. }
  1807. /* Cpu thread affinity */
  1808. if (num_cpus > 1) {
  1809. if (opt_affinity == -1 && opt_n_threads > 1) {
  1810. if (opt_debug)
  1811. applog(LOG_DEBUG, "Binding thread %d to cpu %d (mask %x)", thr_id,
  1812. thr_id % num_cpus, (1 << (thr_id % num_cpus)));
  1813. affine_to_cpu_mask(thr_id, 1UL << (thr_id % num_cpus));
  1814. } else if (opt_affinity != -1L) {
  1815. if (opt_debug)
  1816. applog(LOG_DEBUG, "Binding thread %d to cpu mask %x", thr_id,
  1817. opt_affinity);
  1818. affine_to_cpu_mask(thr_id, (unsigned long)opt_affinity);
  1819. }
  1820. }
  1821. if (opt_algo == ALGO_SCRYPT) {
  1822. scratchbuf = scrypt_buffer_alloc(opt_scrypt_n);
  1823. if (!scratchbuf) {
  1824. applog(LOG_ERR, "scrypt buffer allocation failed");
  1825. pthread_mutex_lock(&applog_lock);
  1826. exit(1);
  1827. }
  1828. }
  1829. else if (opt_algo == ALGO_PLUCK) {
  1830. scratchbuf = malloc(opt_pluck_n * 1024);
  1831. if (!scratchbuf) {
  1832. applog(LOG_ERR, "pluck buffer allocation failed");
  1833. pthread_mutex_lock(&applog_lock);
  1834. exit(1);
  1835. }
  1836. }
  1837. while (1) {
  1838. uint64_t hashes_done;
  1839. struct timeval tv_start, tv_end, diff;
  1840. int64_t max64;
  1841. bool regen_work = false;
  1842. int wkcmp_offset = 0;
  1843. int nonce_oft = 19*sizeof(uint32_t); // 76
  1844. int wkcmp_sz = nonce_oft;
  1845. int rc = 0;
  1846. if (opt_algo == ALGO_DROP || opt_algo == ALGO_ZR5) {
  1847. // Duplicates: ignore pok in data[0]
  1848. wkcmp_sz -= sizeof(uint32_t);
  1849. wkcmp_offset = 1;
  1850. } else if (opt_algo == ALGO_DECRED) {
  1851. wkcmp_sz = nonce_oft = 140; // 35 * 4
  1852. regen_work = true; // ntime not changed ?
  1853. } else if (opt_algo == ALGO_LBRY) {
  1854. wkcmp_sz = nonce_oft = 108; // 27
  1855. //regen_work = true;
  1856. } else if (opt_algo == ALGO_SIA) {
  1857. nonce_oft = 32;
  1858. wkcmp_offset = 32 + 16;
  1859. wkcmp_sz = 32; // 35 * 4
  1860. }
  1861. if (jsonrpc_2) {
  1862. wkcmp_sz = nonce_oft = 39;
  1863. }
  1864. uint32_t *nonceptr = (uint32_t*) (((char*)work.data) + nonce_oft);
  1865. if (have_stratum) {
  1866. while (!jsonrpc_2 && time(NULL) >= g_work_time + 120)
  1867. sleep(1);
  1868. while (!stratum.job.diff && opt_algo == ALGO_NEOSCRYPT) {
  1869. applog(LOG_DEBUG, "Waiting for Stratum to set the job difficulty");
  1870. sleep(1);
  1871. }
  1872. pthread_mutex_lock(&g_work_lock);
  1873. // to clean: is g_work loaded before the memcmp ?
  1874. regen_work = regen_work || ( (*nonceptr) >= end_nonce
  1875. && !( memcmp(&work.data[wkcmp_offset], &g_work.data[wkcmp_offset], wkcmp_sz) ||
  1876. jsonrpc_2 ? memcmp(((uint8_t*) work.data) + 43, ((uint8_t*) g_work.data) + 43, 33) : 0));
  1877. if (regen_work) {
  1878. stratum_gen_work(&stratum, &g_work);
  1879. }
  1880. } else {
  1881. int min_scantime = have_longpoll ? LP_SCANTIME : opt_scantime;
  1882. /* obtain new work from internal workio thread */
  1883. pthread_mutex_lock(&g_work_lock);
  1884. if (!have_stratum &&
  1885. (time(NULL) - g_work_time >= min_scantime ||
  1886. work.data[19] >= end_nonce)) {
  1887. if (unlikely(!get_work(mythr, &g_work))) {
  1888. applog(LOG_ERR, "work retrieval failed, exiting "
  1889. "mining thread %d", mythr->id);
  1890. pthread_mutex_unlock(&g_work_lock);
  1891. goto out;
  1892. }
  1893. g_work_time = have_stratum ? 0 : time(NULL);
  1894. }
  1895. if (have_stratum) {
  1896. pthread_mutex_unlock(&g_work_lock);
  1897. continue;
  1898. }
  1899. }
  1900. if (memcmp(&work.data[wkcmp_offset], &g_work.data[wkcmp_offset], wkcmp_sz) ||
  1901. jsonrpc_2 ? memcmp(((uint8_t*) work.data) + 43, ((uint8_t*) g_work.data) + 43, 33) : 0)
  1902. {
  1903. work_free(&work);
  1904. work_copy(&work, &g_work);
  1905. nonceptr = (uint32_t*) (((char*)work.data) + nonce_oft);
  1906. *nonceptr = 0xffffffffU / opt_n_threads * thr_id;
  1907. if (opt_randomize)
  1908. nonceptr[0] += ((rand()*4) & UINT32_MAX) / opt_n_threads;
  1909. } else
  1910. ++(*nonceptr);
  1911. pthread_mutex_unlock(&g_work_lock);
  1912. work_restart[thr_id].restart = 0;
  1913. if (opt_algo == ALGO_DECRED) {
  1914. if (have_stratum && strcmp(stratum.job.job_id, work.job_id))
  1915. continue; // need to regen g_work..
  1916. // extradata: prevent duplicates
  1917. nonceptr[1] += 1;
  1918. nonceptr[2] |= thr_id;
  1919. } else if (opt_algo == ALGO_SIA) {
  1920. if (have_stratum && strcmp(stratum.job.job_id, work.job_id))
  1921. continue; // need to regen g_work..
  1922. // extradata: prevent duplicates
  1923. nonceptr[1] += 0x10;
  1924. nonceptr[1] |= thr_id;
  1925. //applog_hex(nonceptr, 8);
  1926. }
  1927. // prevent scans before a job is received
  1928. // beware, some testnet (decred) are using version 0
  1929. // no version in sia draft protocol
  1930. if (opt_algo != ALGO_SIA && have_stratum && !work.data[0] && !opt_benchmark) {
  1931. sleep(1);
  1932. continue;
  1933. }
  1934. /* conditional mining */
  1935. if (!wanna_mine(thr_id)) {
  1936. sleep(5);
  1937. continue;
  1938. }
  1939. /* adjust max_nonce to meet target scan time */
  1940. if (have_stratum)
  1941. max64 = LP_SCANTIME;
  1942. else
  1943. max64 = g_work_time + (have_longpoll ? LP_SCANTIME : opt_scantime)
  1944. - time(NULL);
  1945. /* time limit */
  1946. if (opt_time_limit && firstwork_time) {
  1947. int passed = (int)(time(NULL) - firstwork_time);
  1948. int remain = (int)(opt_time_limit - passed);
  1949. if (remain < 0) {
  1950. if (thr_id != 0) {
  1951. sleep(1);
  1952. continue;
  1953. }
  1954. if (opt_benchmark) {
  1955. char rate[32];
  1956. format_hashrate((double)global_hashrate, rate);
  1957. applog(LOG_NOTICE, "Benchmark: %s", rate);
  1958. fprintf(stderr, "%llu\n", (long long unsigned int) global_hashrate);
  1959. } else {
  1960. applog(LOG_NOTICE,
  1961. "Mining timeout of %ds reached, exiting...", opt_time_limit);
  1962. }
  1963. proper_exit(0);
  1964. }
  1965. if (remain < max64) max64 = remain;
  1966. }
  1967. max64 *= (int64_t) thr_hashrates[thr_id];
  1968. if (max64 <= 0) {
  1969. switch (opt_algo) {
  1970. case ALGO_SCRYPT:
  1971. case ALGO_NEOSCRYPT:
  1972. max64 = opt_scrypt_n < 16 ? 0x3ffff : 0x3fffff / opt_scrypt_n;
  1973. if (opt_nfactor > 3)
  1974. max64 >>= (opt_nfactor - 3);
  1975. else if (opt_nfactor > 16)
  1976. max64 = 0xF;
  1977. break;
  1978. case ALGO_AXIOM:
  1979. case ALGO_CRYPTOLIGHT:
  1980. case ALGO_CRYPTONIGHT:
  1981. case ALGO_SCRYPTJANE:
  1982. max64 = 0x40LL;
  1983. break;
  1984. case ALGO_DROP:
  1985. case ALGO_PLUCK:
  1986. case ALGO_YESCRYPT:
  1987. case ALGO_YESCRYPTR8:
  1988. max64 = 0x1ff;
  1989. break;
  1990. case ALGO_YESCRYPTR16:
  1991. case ALGO_YESCRYPTR32:
  1992. max64 = 0xfff;
  1993. break;
  1994. case ALGO_ALLIUM:
  1995. case ALGO_LYRA2:
  1996. case ALGO_LYRA2REV2:
  1997. case ALGO_LYRA2V3:
  1998. case ALGO_PHI1612:
  1999. case ALGO_PHI2:
  2000. case ALGO_TIMETRAVEL:
  2001. case ALGO_BITCORE:
  2002. case ALGO_XEVAN:
  2003. max64 = 0xffff;
  2004. break;
  2005. case ALGO_C11:
  2006. case ALGO_DMD_GR:
  2007. case ALGO_FRESH:
  2008. case ALGO_GEEK:
  2009. case ALGO_GROESTL:
  2010. case ALGO_MYR_GR:
  2011. case ALGO_SIB:
  2012. case ALGO_VELTOR:
  2013. case ALGO_X11EVO:
  2014. case ALGO_X11:
  2015. case ALGO_X12:
  2016. case ALGO_X13:
  2017. case ALGO_X14:
  2018. max64 = 0x3ffff;
  2019. break;
  2020. case ALGO_LBRY:
  2021. case ALGO_SONOA:
  2022. case ALGO_TRIBUS:
  2023. case ALGO_X15:
  2024. case ALGO_X16R:
  2025. case ALGO_X16RV2:
  2026. case ALGO_X16S:
  2027. case ALGO_X17:
  2028. case ALGO_X20R:
  2029. case ALGO_ZR5:
  2030. max64 = 0x1ffff;
  2031. break;
  2032. case ALGO_BMW:
  2033. case ALGO_PENTABLAKE:
  2034. max64 = 0x3ffff;
  2035. break;
  2036. case ALGO_SKEIN:
  2037. case ALGO_SKEIN2:
  2038. max64 = 0x7ffffLL;
  2039. break;
  2040. case ALGO_BLAKE:
  2041. case ALGO_BLAKECOIN:
  2042. case ALGO_DECRED:
  2043. case ALGO_VANILLA:
  2044. max64 = 0x3fffffLL;
  2045. break;
  2046. case ALGO_SIA:
  2047. default:
  2048. max64 = 0x1fffffLL;
  2049. break;
  2050. }
  2051. }
  2052. if ((*nonceptr) + max64 > end_nonce)
  2053. max_nonce = end_nonce;
  2054. else
  2055. max_nonce = (*nonceptr) + (uint32_t) max64;
  2056. hashes_done = 0;
  2057. gettimeofday((struct timeval *) &tv_start, NULL);
  2058. if (firstwork_time == 0)
  2059. firstwork_time = time(NULL);
  2060. /* scan nonces for a proof-of-work hash */
  2061. switch (opt_algo) {
  2062. case ALGO_ALLIUM:
  2063. rc = scanhash_allium(thr_id, &work, max_nonce, &hashes_done);
  2064. break;
  2065. case ALGO_AXIOM:
  2066. rc = scanhash_axiom(thr_id, &work, max_nonce, &hashes_done);
  2067. break;
  2068. case ALGO_BASTION:
  2069. rc = scanhash_bastion(thr_id, &work, max_nonce, &hashes_done);
  2070. break;
  2071. case ALGO_BLAKE:
  2072. rc = scanhash_blake(thr_id, &work, max_nonce, &hashes_done);
  2073. break;
  2074. case ALGO_BLAKECOIN:
  2075. rc = scanhash_blakecoin(thr_id, &work, max_nonce, &hashes_done);
  2076. break;
  2077. case ALGO_BLAKE2B:
  2078. rc = scanhash_blake2b(thr_id, &work, max_nonce, &hashes_done);
  2079. break;
  2080. case ALGO_BLAKE2S:
  2081. rc = scanhash_blake2s(thr_id, &work, max_nonce, &hashes_done);
  2082. break;
  2083. case ALGO_BMW:
  2084. rc = scanhash_bmw(thr_id, &work, max_nonce, &hashes_done);
  2085. break;
  2086. case ALGO_C11:
  2087. rc = scanhash_c11(thr_id, &work, max_nonce, &hashes_done);
  2088. break;
  2089. case ALGO_CRYPTOLIGHT:
  2090. rc = scanhash_cryptolight(thr_id, &work, max_nonce, &hashes_done);
  2091. break;
  2092. case ALGO_CRYPTONIGHT:
  2093. rc = scanhash_cryptonight(thr_id, &work, max_nonce, &hashes_done);
  2094. break;
  2095. case ALGO_DECRED:
  2096. rc = scanhash_decred(thr_id, &work, max_nonce, &hashes_done);
  2097. break;
  2098. case ALGO_DROP:
  2099. rc = scanhash_drop(thr_id, &work, max_nonce, &hashes_done);
  2100. break;
  2101. case ALGO_FRESH:
  2102. rc = scanhash_fresh(thr_id, &work, max_nonce, &hashes_done);
  2103. break;
  2104. case ALGO_GEEK:
  2105. rc = scanhash_geek(thr_id, &work, max_nonce, &hashes_done);
  2106. break;
  2107. case ALGO_DMD_GR:
  2108. case ALGO_GROESTL:
  2109. rc = scanhash_groestl(thr_id, &work, max_nonce, &hashes_done);
  2110. break;
  2111. case ALGO_KECCAK:
  2112. case ALGO_KECCAKC:
  2113. rc = scanhash_keccak(thr_id, &work, max_nonce, &hashes_done);
  2114. break;
  2115. case ALGO_HEAVY:
  2116. rc = scanhash_heavy(thr_id, &work, max_nonce, &hashes_done);
  2117. break;
  2118. case ALGO_JHA:
  2119. rc = scanhash_jha(thr_id, &work, max_nonce, &hashes_done);
  2120. break;
  2121. case ALGO_LBRY:
  2122. rc = scanhash_lbry(thr_id, &work, max_nonce, &hashes_done);
  2123. break;
  2124. case ALGO_LUFFA:
  2125. rc = scanhash_luffa(thr_id, &work, max_nonce, &hashes_done);
  2126. break;
  2127. case ALGO_LYRA2:
  2128. rc = scanhash_lyra2(thr_id, &work, max_nonce, &hashes_done);
  2129. break;
  2130. case ALGO_LYRA2REV2:
  2131. rc = scanhash_lyra2rev2(thr_id, &work, max_nonce, &hashes_done);
  2132. break;
  2133. case ALGO_LYRA2V3:
  2134. rc = scanhash_lyra2v3(thr_id, &work, max_nonce, &hashes_done);
  2135. break;
  2136. case ALGO_MYR_GR:
  2137. rc = scanhash_myriad(thr_id, &work, max_nonce, &hashes_done);
  2138. break;
  2139. case ALGO_NEOSCRYPT:
  2140. rc = scanhash_neoscrypt(thr_id, &work, max_nonce, &hashes_done,
  2141. 0x80000020 | (opt_nfactor << 8));
  2142. break;
  2143. case ALGO_NIST5:
  2144. rc = scanhash_nist5(thr_id, &work, max_nonce, &hashes_done);
  2145. break;
  2146. case ALGO_PENTABLAKE:
  2147. rc = scanhash_pentablake(thr_id, &work, max_nonce, &hashes_done);
  2148. break;
  2149. case ALGO_PHI1612:
  2150. rc = scanhash_phi1612(thr_id, &work, max_nonce, &hashes_done);
  2151. break;
  2152. case ALGO_PHI2:
  2153. rc = scanhash_phi2(thr_id, &work, max_nonce, &hashes_done);
  2154. break;
  2155. case ALGO_PLUCK:
  2156. rc = scanhash_pluck(thr_id, &work, max_nonce, &hashes_done, scratchbuf, opt_pluck_n);
  2157. break;
  2158. case ALGO_QUARK:
  2159. rc = scanhash_quark(thr_id, &work, max_nonce, &hashes_done);
  2160. break;
  2161. case ALGO_QUBIT:
  2162. rc = scanhash_qubit(thr_id, &work, max_nonce, &hashes_done);
  2163. break;
  2164. case ALGO_RAINFOREST:
  2165. rc = scanhash_rf256(thr_id, &work, max_nonce, &hashes_done);
  2166. break;
  2167. case ALGO_SCRYPT:
  2168. rc = scanhash_scrypt(thr_id, &work, max_nonce, &hashes_done, scratchbuf, opt_scrypt_n);
  2169. break;
  2170. case ALGO_SCRYPTJANE:
  2171. rc = scanhash_scryptjane(opt_scrypt_n, thr_id, &work, max_nonce, &hashes_done);
  2172. break;
  2173. case ALGO_SHAVITE3:
  2174. rc = scanhash_ink(thr_id, &work, max_nonce, &hashes_done);
  2175. break;
  2176. case ALGO_SHA256D:
  2177. rc = scanhash_sha256d(thr_id, &work, max_nonce, &hashes_done);
  2178. break;
  2179. case ALGO_SIA:
  2180. rc = scanhash_sia(thr_id, &work, max_nonce, &hashes_done);
  2181. break;
  2182. case ALGO_SIB:
  2183. rc = scanhash_sib(thr_id, &work, max_nonce, &hashes_done);
  2184. break;
  2185. case ALGO_SKEIN:
  2186. rc = scanhash_skein(thr_id, &work, max_nonce, &hashes_done);
  2187. break;
  2188. case ALGO_SKEIN2:
  2189. rc = scanhash_skein2(thr_id, &work, max_nonce, &hashes_done);
  2190. break;
  2191. case ALGO_SONOA:
  2192. rc = scanhash_sonoa(thr_id, &work, max_nonce, &hashes_done);
  2193. break;
  2194. case ALGO_S3:
  2195. rc = scanhash_s3(thr_id, &work, max_nonce, &hashes_done);
  2196. break;
  2197. case ALGO_TIMETRAVEL:
  2198. rc = scanhash_timetravel(thr_id, &work, max_nonce, &hashes_done);
  2199. break;
  2200. case ALGO_BITCORE:
  2201. rc = scanhash_bitcore(thr_id, &work, max_nonce, &hashes_done);
  2202. break;
  2203. case ALGO_TRIBUS:
  2204. rc = scanhash_tribus(thr_id, &work, max_nonce, &hashes_done);
  2205. break;
  2206. case ALGO_VANILLA:
  2207. rc = scanhash_blakecoin(thr_id, &work, max_nonce, &hashes_done);
  2208. break;
  2209. case ALGO_VELTOR:
  2210. rc = scanhash_veltor(thr_id, &work, max_nonce, &hashes_done);
  2211. break;
  2212. case ALGO_X11EVO:
  2213. rc = scanhash_x11evo(thr_id, &work, max_nonce, &hashes_done);
  2214. break;
  2215. case ALGO_X11:
  2216. rc = scanhash_x11(thr_id, &work, max_nonce, &hashes_done);
  2217. break;
  2218. case ALGO_X12:
  2219. rc = scanhash_x12(thr_id, &work, max_nonce, &hashes_done);
  2220. break;
  2221. case ALGO_X13:
  2222. rc = scanhash_x13(thr_id, &work, max_nonce, &hashes_done);
  2223. break;
  2224. case ALGO_X14:
  2225. rc = scanhash_x14(thr_id, &work, max_nonce, &hashes_done);
  2226. break;
  2227. case ALGO_X15:
  2228. rc = scanhash_x15(thr_id, &work, max_nonce, &hashes_done);
  2229. break;
  2230. case ALGO_X16R:
  2231. rc = scanhash_x16r(thr_id, &work, max_nonce, &hashes_done);
  2232. break;
  2233. case ALGO_X16RV2:
  2234. rc = scanhash_x16rv2(thr_id, &work, max_nonce, &hashes_done);
  2235. break;
  2236. case ALGO_X20R:
  2237. rc = scanhash_x20r(thr_id, &work, max_nonce, &hashes_done);
  2238. break;
  2239. case ALGO_X16S:
  2240. rc = scanhash_x16s(thr_id, &work, max_nonce, &hashes_done);
  2241. break;
  2242. case ALGO_X17:
  2243. rc = scanhash_x17(thr_id, &work, max_nonce, &hashes_done);
  2244. break;
  2245. case ALGO_XEVAN:
  2246. rc = scanhash_xevan(thr_id, &work, max_nonce, &hashes_done);
  2247. break;
  2248. case ALGO_YESCRYPT:
  2249. rc = scanhash_yescrypt(thr_id, &work, max_nonce, &hashes_done);
  2250. break;
  2251. case ALGO_YESCRYPTR8:
  2252. rc = scanhash_yescryptr8(thr_id, &work, max_nonce, &hashes_done);
  2253. break;
  2254. case ALGO_YESCRYPTR16:
  2255. rc = scanhash_yescryptr16(thr_id, &work, max_nonce, &hashes_done);
  2256. break;
  2257. case ALGO_YESCRYPTR32:
  2258. rc = scanhash_yescryptr32(thr_id, &work, max_nonce, &hashes_done);
  2259. break;
  2260. case ALGO_ZR5:
  2261. rc = scanhash_zr5(thr_id, &work, max_nonce, &hashes_done);
  2262. break;
  2263. default:
  2264. /* should never happen */
  2265. goto out;
  2266. }
  2267. /* record scanhash elapsed time */
  2268. gettimeofday(&tv_end, NULL);
  2269. timeval_subtract(&diff, &tv_end, &tv_start);
  2270. if (diff.tv_usec || diff.tv_sec) {
  2271. pthread_mutex_lock(&stats_lock);
  2272. thr_hashrates[thr_id] =
  2273. hashes_done / (diff.tv_sec + diff.tv_usec * 1e-6);
  2274. pthread_mutex_unlock(&stats_lock);
  2275. }
  2276. if (!opt_quiet && (time(NULL) - tm_rate_log) > opt_maxlograte) {
  2277. switch(opt_algo) {
  2278. case ALGO_AXIOM:
  2279. case ALGO_CRYPTOLIGHT:
  2280. case ALGO_CRYPTONIGHT:
  2281. case ALGO_PLUCK:
  2282. case ALGO_SCRYPTJANE:
  2283. applog(LOG_INFO, "CPU #%d: %.2f H/s", thr_id, thr_hashrates[thr_id]);
  2284. break;
  2285. default:
  2286. sprintf(s, thr_hashrates[thr_id] >= 1e6 ? "%.0f" : "%.2f",
  2287. thr_hashrates[thr_id] / 1e3);
  2288. applog(LOG_INFO, "CPU #%d: %s kH/s", thr_id, s);
  2289. break;
  2290. }
  2291. tm_rate_log = time(NULL);
  2292. }
  2293. if (opt_benchmark && thr_id == opt_n_threads - 1) {
  2294. double hashrate = 0.;
  2295. for (i = 0; i < opt_n_threads && thr_hashrates[i]; i++)
  2296. hashrate += thr_hashrates[i];
  2297. if (i == opt_n_threads) {
  2298. switch(opt_algo) {
  2299. case ALGO_CRYPTOLIGHT:
  2300. case ALGO_CRYPTONIGHT:
  2301. case ALGO_AXIOM:
  2302. case ALGO_SCRYPTJANE:
  2303. sprintf(s, "%.3f", hashrate);
  2304. applog(LOG_NOTICE, "Total: %s H/s", s);
  2305. break;
  2306. default:
  2307. sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", hashrate / 1000);
  2308. applog(LOG_NOTICE, "Total: %s kH/s", s);
  2309. break;
  2310. }
  2311. global_hashrate = (uint64_t) hashrate;
  2312. }
  2313. }
  2314. /* if nonce found, submit work */
  2315. if (rc && !opt_benchmark) {
  2316. if (!submit_work(mythr, &work))
  2317. break;
  2318. // prevent stale work in solo
  2319. // we can't submit twice a block!
  2320. if (!have_stratum && !have_longpoll) {
  2321. pthread_mutex_lock(&g_work_lock);
  2322. // will force getwork
  2323. g_work_time = 0;
  2324. pthread_mutex_unlock(&g_work_lock);
  2325. continue;
  2326. }
  2327. }
  2328. }
  2329. out:
  2330. tq_freeze(mythr->q);
  2331. return NULL;
  2332. }
  2333. void restart_threads(void)
  2334. {
  2335. int i;
  2336. for (i = 0; i < opt_n_threads; i++)
  2337. work_restart[i].restart = 1;
  2338. }
  2339. static void *longpoll_thread(void *userdata)
  2340. {
  2341. struct thr_info *mythr = (struct thr_info*) userdata;
  2342. CURL *curl = NULL;
  2343. char *copy_start, *hdr_path = NULL, *lp_url = NULL;
  2344. bool need_slash = false;
  2345. curl = curl_easy_init();
  2346. if (unlikely(!curl)) {
  2347. applog(LOG_ERR, "CURL init failed");
  2348. goto out;
  2349. }
  2350. start:
  2351. hdr_path = (char*) tq_pop(mythr->q, NULL);
  2352. if (!hdr_path)
  2353. goto out;
  2354. /* full URL */
  2355. if (strstr(hdr_path, "://")) {
  2356. lp_url = hdr_path;
  2357. hdr_path = NULL;
  2358. }
  2359. /* absolute path, on current server */
  2360. else {
  2361. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2362. if (rpc_url[strlen(rpc_url) - 1] != '/')
  2363. need_slash = true;
  2364. lp_url = (char*) malloc(strlen(rpc_url) + strlen(copy_start) + 2);
  2365. if (!lp_url)
  2366. goto out;
  2367. sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
  2368. }
  2369. if (!opt_quiet)
  2370. applog(LOG_BLUE, "Long-polling on %s", lp_url);
  2371. while (1) {
  2372. json_t *val;
  2373. char *req = NULL;
  2374. int err;
  2375. if (jsonrpc_2) {
  2376. char s[128];
  2377. pthread_mutex_lock(&rpc2_login_lock);
  2378. if (!strlen(rpc2_id)) {
  2379. sleep(1);
  2380. continue;
  2381. }
  2382. snprintf(s, 128, "{\"method\": \"getjob\", \"params\": {\"id\": \"%s\"}, \"id\":1}\r\n", rpc2_id);
  2383. pthread_mutex_unlock(&rpc2_login_lock);
  2384. val = json_rpc2_call(curl, rpc_url, rpc_userpass, s, &err, JSON_RPC_LONGPOLL);
  2385. } else {
  2386. if (have_gbt) {
  2387. req = (char*) malloc(strlen(gbt_lp_req) + strlen(lp_id) + 1);
  2388. sprintf(req, gbt_lp_req, lp_id);
  2389. }
  2390. val = json_rpc_call(curl, rpc_url, rpc_userpass, getwork_req, &err, JSON_RPC_LONGPOLL);
  2391. val = json_rpc_call(curl, lp_url, rpc_userpass,
  2392. req ? req : getwork_req, &err,
  2393. JSON_RPC_LONGPOLL);
  2394. free(req);
  2395. }
  2396. if (have_stratum) {
  2397. if (val)
  2398. json_decref(val);
  2399. goto out;
  2400. }
  2401. if (likely(val)) {
  2402. bool rc;
  2403. char *start_job_id;
  2404. double start_diff = 0.0;
  2405. json_t *res, *soval;
  2406. res = json_object_get(val, "result");
  2407. if (!jsonrpc_2) {
  2408. soval = json_object_get(res, "submitold");
  2409. submit_old = soval ? json_is_true(soval) : false;
  2410. }
  2411. pthread_mutex_lock(&g_work_lock);
  2412. start_job_id = g_work.job_id ? strdup(g_work.job_id) : NULL;
  2413. if (have_gbt)
  2414. rc = gbt_work_decode(res, &g_work);
  2415. else
  2416. rc = work_decode(res, &g_work);
  2417. if (rc) {
  2418. bool newblock = g_work.job_id && strcmp(start_job_id, g_work.job_id);
  2419. newblock |= (start_diff != net_diff); // the best is the height but... longpoll...
  2420. if (newblock) {
  2421. start_diff = net_diff;
  2422. if (!opt_quiet) {
  2423. char netinfo[64] = { 0 };
  2424. if (net_diff > 0.) {
  2425. sprintf(netinfo, ", diff %.3f", net_diff);
  2426. }
  2427. if (opt_showdiff)
  2428. sprintf(&netinfo[strlen(netinfo)], ", target %.3f", g_work.targetdiff);
  2429. applog(LOG_BLUE, "%s detected new block%s", short_url, netinfo);
  2430. }
  2431. time(&g_work_time);
  2432. restart_threads();
  2433. }
  2434. }
  2435. free(start_job_id);
  2436. pthread_mutex_unlock(&g_work_lock);
  2437. json_decref(val);
  2438. } else {
  2439. pthread_mutex_lock(&g_work_lock);
  2440. g_work_time -= LP_SCANTIME;
  2441. pthread_mutex_unlock(&g_work_lock);
  2442. if (err == CURLE_OPERATION_TIMEDOUT) {
  2443. restart_threads();
  2444. } else {
  2445. have_longpoll = false;
  2446. restart_threads();
  2447. free(hdr_path);
  2448. free(lp_url);
  2449. lp_url = NULL;
  2450. sleep(opt_fail_pause);
  2451. goto start;
  2452. }
  2453. }
  2454. }
  2455. out:
  2456. free(hdr_path);
  2457. free(lp_url);
  2458. tq_freeze(mythr->q);
  2459. if (curl)
  2460. curl_easy_cleanup(curl);
  2461. return NULL;
  2462. }
  2463. static bool stratum_handle_response(char *buf)
  2464. {
  2465. json_t *val, *err_val, *res_val, *id_val;
  2466. json_error_t err;
  2467. bool ret = false;
  2468. bool valid = false;
  2469. val = JSON_LOADS(buf, &err);
  2470. if (!val) {
  2471. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2472. goto out;
  2473. }
  2474. res_val = json_object_get(val, "result");
  2475. err_val = json_object_get(val, "error");
  2476. id_val = json_object_get(val, "id");
  2477. if (!id_val || json_is_null(id_val))
  2478. goto out;
  2479. if (jsonrpc_2)
  2480. {
  2481. if (!res_val && !err_val)
  2482. goto out;
  2483. json_t *status = json_object_get(res_val, "status");
  2484. if(status) {
  2485. const char *s = json_string_value(status);
  2486. valid = !strcmp(s, "OK") && json_is_null(err_val);
  2487. } else {
  2488. valid = json_is_null(err_val);
  2489. }
  2490. share_result(valid, NULL, err_val ? json_string_value(err_val) : NULL);
  2491. } else {
  2492. if (!res_val || json_integer_value(id_val) < 4)
  2493. goto out;
  2494. valid = json_is_true(res_val);
  2495. share_result(valid, NULL, err_val ? json_string_value(json_array_get(err_val, 1)) : NULL);
  2496. }
  2497. ret = true;
  2498. out:
  2499. if (val)
  2500. json_decref(val);
  2501. return ret;
  2502. }
  2503. static void *stratum_thread(void *userdata)
  2504. {
  2505. struct thr_info *mythr = (struct thr_info *) userdata;
  2506. char *s;
  2507. stratum.url = (char*) tq_pop(mythr->q, NULL);
  2508. if (!stratum.url)
  2509. goto out;
  2510. applog(LOG_INFO, "Starting Stratum on %s", stratum.url);
  2511. while (1) {
  2512. int failures = 0;
  2513. if (stratum_need_reset) {
  2514. stratum_need_reset = false;
  2515. stratum_disconnect(&stratum);
  2516. if (strcmp(stratum.url, rpc_url)) {
  2517. free(stratum.url);
  2518. stratum.url = strdup(rpc_url);
  2519. applog(LOG_BLUE, "Connection changed to %s", short_url);
  2520. } else if (!opt_quiet) {
  2521. applog(LOG_DEBUG, "Stratum connection reset");
  2522. }
  2523. }
  2524. while (!stratum.curl) {
  2525. pthread_mutex_lock(&g_work_lock);
  2526. g_work_time = 0;
  2527. pthread_mutex_unlock(&g_work_lock);
  2528. restart_threads();
  2529. if (!stratum_connect(&stratum, stratum.url)
  2530. || !stratum_subscribe(&stratum)
  2531. || !stratum_authorize(&stratum, rpc_user, rpc_pass)) {
  2532. stratum_disconnect(&stratum);
  2533. if (opt_retries >= 0 && ++failures > opt_retries) {
  2534. applog(LOG_ERR, "...terminating workio thread");
  2535. tq_push(thr_info[work_thr_id].q, NULL);
  2536. goto out;
  2537. }
  2538. if (!opt_benchmark)
  2539. applog(LOG_ERR, "...retry after %d seconds", opt_fail_pause);
  2540. sleep(opt_fail_pause);
  2541. }
  2542. if (jsonrpc_2) {
  2543. work_free(&g_work);
  2544. work_copy(&g_work, &stratum.work);
  2545. }
  2546. }
  2547. if (stratum.job.job_id &&
  2548. (!g_work_time || strcmp(stratum.job.job_id, g_work.job_id)) )
  2549. {
  2550. pthread_mutex_lock(&g_work_lock);
  2551. stratum_gen_work(&stratum, &g_work);
  2552. time(&g_work_time);
  2553. pthread_mutex_unlock(&g_work_lock);
  2554. if (stratum.job.clean || jsonrpc_2) {
  2555. static uint32_t last_bloc_height;
  2556. if (!opt_quiet && last_bloc_height != stratum.bloc_height) {
  2557. last_bloc_height = stratum.bloc_height;
  2558. if (net_diff > 0.)
  2559. applog(LOG_BLUE, "%s block %d, diff %.3f", algo_names[opt_algo],
  2560. stratum.bloc_height, net_diff);
  2561. else
  2562. applog(LOG_BLUE, "%s %s block %d", short_url, algo_names[opt_algo],
  2563. stratum.bloc_height);
  2564. }
  2565. restart_threads();
  2566. } else if (opt_debug && !opt_quiet) {
  2567. applog(LOG_BLUE, "%s asks job %lu for block %d", short_url,
  2568. strtoul(stratum.job.job_id, NULL, 16), stratum.bloc_height);
  2569. }
  2570. }
  2571. if (!stratum_socket_full(&stratum, opt_timeout)) {
  2572. applog(LOG_ERR, "Stratum connection timeout");
  2573. s = NULL;
  2574. } else
  2575. s = stratum_recv_line(&stratum);
  2576. if (!s) {
  2577. stratum_disconnect(&stratum);
  2578. applog(LOG_ERR, "Stratum connection interrupted");
  2579. continue;
  2580. }
  2581. if (!stratum_handle_method(&stratum, s))
  2582. stratum_handle_response(s);
  2583. free(s);
  2584. }
  2585. out:
  2586. return NULL;
  2587. }
  2588. static void show_version_and_exit(void)
  2589. {
  2590. printf(" built "
  2591. #ifdef _MSC_VER
  2592. "with VC++ %d", msver());
  2593. #elif defined(__GNUC__)
  2594. "with GCC ");
  2595. printf("%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
  2596. #endif
  2597. printf(" the " __DATE__ "\n");
  2598. // Note: if compiled with cpu opts (instruction sets),
  2599. // the binary is no more compatible with older ones!
  2600. printf(" compiled for"
  2601. #if defined(__ARM_NEON__)
  2602. " ARM NEON"
  2603. #elif defined(__AVX2__)
  2604. " AVX2"
  2605. #elif defined(__AVX__)
  2606. " AVX"
  2607. #elif defined(__XOP__)
  2608. " XOP"
  2609. #elif defined(__SSE4_1__)
  2610. " SSE4"
  2611. #elif defined(_M_X64) || defined(__x86_64__)
  2612. " x64"
  2613. #elif defined(_M_IX86) || defined(__x86__)
  2614. " x86"
  2615. #else
  2616. " general use"
  2617. #endif
  2618. "\n");
  2619. printf(" config features:"
  2620. #if defined(USE_ASM) && defined(__i386__)
  2621. " i386"
  2622. #endif
  2623. #if defined(USE_ASM) && defined(__x86_64__)
  2624. " x86_64"
  2625. #endif
  2626. #if defined(USE_ASM) && (defined(__i386__) || defined(__x86_64__))
  2627. " SSE2"
  2628. #endif
  2629. #if defined(__x86_64__) && defined(USE_XOP)
  2630. " XOP"
  2631. #endif
  2632. #if defined(__x86_64__) && defined(USE_AVX)
  2633. " AVX"
  2634. #endif
  2635. #if defined(__x86_64__) && defined(USE_AVX2)
  2636. " AVX2"
  2637. #endif
  2638. #if defined(USE_ASM) && defined(__arm__) && defined(__APCS_32__)
  2639. " ARM"
  2640. #if defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) || \
  2641. defined(__ARM_ARCH_5TEJ__) || defined(__ARM_ARCH_6__) || \
  2642. defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || \
  2643. defined(__ARM_ARCH_6M__) || defined(__ARM_ARCH_6T2__) || \
  2644. defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || \
  2645. defined(__ARM_ARCH_7__) || \
  2646. defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || \
  2647. defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
  2648. " ARMv5E"
  2649. #endif
  2650. #if defined(__ARM_NEON__)
  2651. " NEON"
  2652. #endif
  2653. #endif
  2654. "\n\n");
  2655. /* dependencies versions */
  2656. printf("%s\n", curl_version());
  2657. #ifdef JANSSON_VERSION
  2658. printf("jansson/%s ", JANSSON_VERSION);
  2659. #endif
  2660. #ifdef PTW32_VERSION
  2661. printf("pthreads/%d.%d.%d.%d ", PTW32_VERSION);
  2662. #endif
  2663. printf("\n");
  2664. exit(0);
  2665. }
  2666. static void show_usage_and_exit(int status)
  2667. {
  2668. if (status)
  2669. fprintf(stderr, "Try `cpuminer --help' for more information.\n");
  2670. else
  2671. printf(usage);
  2672. exit(status);
  2673. }
  2674. static void strhide(char *s)
  2675. {
  2676. if (*s) *s++ = 'x';
  2677. while (*s) *s++ = '\0';
  2678. }
  2679. void parse_arg(int key, char *arg)
  2680. {
  2681. char *p;
  2682. int v, i;
  2683. uint64_t ul;
  2684. double d;
  2685. switch(key) {
  2686. case 'a':
  2687. for (i = 0; i < ALGO_COUNT; i++) {
  2688. v = (int) strlen(algo_names[i]);
  2689. if (v && !strncasecmp(arg, algo_names[i], v)) {
  2690. if (arg[v] == '\0') {
  2691. opt_algo = (enum algos) i;
  2692. break;
  2693. }
  2694. if (arg[v] == ':') {
  2695. char *ep;
  2696. v = strtol(arg+v+1, &ep, 10);
  2697. if (*ep || (i == ALGO_SCRYPT && v & (v-1)) || v < 2)
  2698. continue;
  2699. opt_algo = (enum algos) i;
  2700. opt_scrypt_n = v;
  2701. break;
  2702. }
  2703. }
  2704. }
  2705. if (i == ALGO_COUNT) {
  2706. if (strstr(arg, ":")) {
  2707. // pick and strip the optional factor
  2708. char *nf = strstr(arg, ":");
  2709. opt_scrypt_n = strtol(&nf[1], NULL, 10);
  2710. *nf = '\0';
  2711. }
  2712. // some aliases...
  2713. if (!strcasecmp("blake2", arg))
  2714. i = opt_algo = ALGO_BLAKE2S;
  2715. else if (!strcasecmp("cryptonight-light", arg))
  2716. i = opt_algo = ALGO_CRYPTOLIGHT;
  2717. else if (!strcasecmp("flax", arg))
  2718. i = opt_algo = ALGO_C11;
  2719. else if (!strcasecmp("diamond", arg))
  2720. i = opt_algo = ALGO_DMD_GR;
  2721. else if (!strcasecmp("droplp", arg))
  2722. i = opt_algo = ALGO_DROP;
  2723. else if (!strcasecmp("jackpot", arg))
  2724. i = opt_algo = ALGO_JHA;
  2725. else if (!strcasecmp("lyra2", arg))
  2726. i = opt_algo = ALGO_LYRA2;
  2727. else if (!strcasecmp("lyra2v2", arg))
  2728. i = opt_algo = ALGO_LYRA2REV2;
  2729. else if (!strcasecmp("lyra2rev3", arg))
  2730. i = opt_algo = ALGO_LYRA2V3;
  2731. else if (!strcasecmp("monero", arg))
  2732. i = opt_algo = ALGO_CRYPTONIGHT;
  2733. else if (!strcasecmp("phi", arg))
  2734. i = opt_algo = ALGO_PHI1612;
  2735. else if (!strcasecmp("scryptjane", arg))
  2736. i = opt_algo = ALGO_SCRYPTJANE;
  2737. else if (!strcasecmp("sibcoin", arg))
  2738. i = opt_algo = ALGO_SIB;
  2739. else if (!strcasecmp("timetravel10", arg))
  2740. i = opt_algo = ALGO_BITCORE;
  2741. else if (!strcasecmp("ziftr", arg))
  2742. i = opt_algo = ALGO_ZR5;
  2743. else
  2744. applog(LOG_ERR, "Unknown algo parameter '%s'", arg);
  2745. }
  2746. if (i == ALGO_COUNT) {
  2747. show_usage_and_exit(1);
  2748. }
  2749. if (!opt_nfactor && opt_algo == ALGO_SCRYPT)
  2750. opt_nfactor = 9;
  2751. if (opt_algo == ALGO_SCRYPTJANE && opt_scrypt_n == 0)
  2752. opt_scrypt_n = 5;
  2753. break;
  2754. case 'b':
  2755. p = strstr(arg, ":");
  2756. if (p) {
  2757. /* ip:port */
  2758. if (p - arg > 0) {
  2759. free(opt_api_allow);
  2760. opt_api_allow = strdup(arg);
  2761. opt_api_allow[p - arg] = '\0';
  2762. }
  2763. opt_api_listen = atoi(p + 1);
  2764. }
  2765. else if (arg && strstr(arg, ".")) {
  2766. /* ip only */
  2767. free(opt_api_allow);
  2768. opt_api_allow = strdup(arg);
  2769. }
  2770. else if (arg) {
  2771. /* port or 0 to disable */
  2772. opt_api_listen = atoi(arg);
  2773. }
  2774. break;
  2775. case 1030: /* --api-remote */
  2776. opt_api_remote = 1;
  2777. break;
  2778. case 'n':
  2779. if (opt_algo == ALGO_NEOSCRYPT) {
  2780. v = atoi(arg);
  2781. /* Nfactor = lb(N) - 1; N = (1 << (Nfactor + 1)) */
  2782. if ((v < 0) || (v > 30)) {
  2783. fprintf(stderr, "incorrect Nfactor %d\n", v);
  2784. show_usage_and_exit(1);
  2785. }
  2786. opt_nfactor = v;
  2787. }
  2788. break;
  2789. case 'B':
  2790. opt_background = true;
  2791. use_colors = false;
  2792. break;
  2793. case 'c': {
  2794. json_error_t err;
  2795. json_t *config;
  2796. if (arg && strstr(arg, "://")) {
  2797. config = json_load_url(arg, &err);
  2798. } else {
  2799. config = JSON_LOADF(arg, &err);
  2800. }
  2801. if (!json_is_object(config)) {
  2802. if (err.line < 0)
  2803. fprintf(stderr, "%s\n", err.text);
  2804. else
  2805. fprintf(stderr, "%s:%d: %s\n",
  2806. arg, err.line, err.text);
  2807. } else {
  2808. parse_config(config, arg);
  2809. json_decref(config);
  2810. }
  2811. break;
  2812. }
  2813. case 'C':
  2814. break;
  2815. case 'q':
  2816. opt_quiet = true;
  2817. break;
  2818. case 'D':
  2819. opt_debug = true;
  2820. break;
  2821. case 'p':
  2822. free(rpc_pass);
  2823. rpc_pass = strdup(arg);
  2824. strhide(arg);
  2825. break;
  2826. case 'P':
  2827. opt_protocol = true;
  2828. break;
  2829. case 'r':
  2830. v = atoi(arg);
  2831. if (v < -1 || v > 9999) /* sanity check */
  2832. show_usage_and_exit(1);
  2833. opt_retries = v;
  2834. break;
  2835. case 'R':
  2836. v = atoi(arg);
  2837. if (v < 1 || v > 9999) /* sanity check */
  2838. show_usage_and_exit(1);
  2839. opt_fail_pause = v;
  2840. break;
  2841. case 's':
  2842. v = atoi(arg);
  2843. if (v < 1 || v > 9999) /* sanity check */
  2844. show_usage_and_exit(1);
  2845. opt_scantime = v;
  2846. break;
  2847. case 'T':
  2848. v = atoi(arg);
  2849. if (v < 1 || v > 99999) /* sanity check */
  2850. show_usage_and_exit(1);
  2851. opt_timeout = v;
  2852. break;
  2853. case 't':
  2854. v = atoi(arg);
  2855. if (v < 0 || v > 9999) /* sanity check */
  2856. show_usage_and_exit(1);
  2857. opt_n_threads = v;
  2858. break;
  2859. case 'u':
  2860. free(rpc_user);
  2861. rpc_user = strdup(arg);
  2862. break;
  2863. case 'o': { /* --url */
  2864. char *ap, *hp;
  2865. ap = strstr(arg, "://");
  2866. ap = ap ? ap + 3 : arg;
  2867. hp = strrchr(arg, '@');
  2868. if (hp) {
  2869. *hp = '\0';
  2870. p = strchr(ap, ':');
  2871. if (p) {
  2872. free(rpc_userpass);
  2873. rpc_userpass = strdup(ap);
  2874. free(rpc_user);
  2875. rpc_user = (char*) calloc(p - ap + 1, 1);
  2876. strncpy(rpc_user, ap, p - ap);
  2877. free(rpc_pass);
  2878. rpc_pass = strdup(++p);
  2879. if (*p) *p++ = 'x';
  2880. v = (int) strlen(hp + 1) + 1;
  2881. memmove(p + 1, hp + 1, v);
  2882. memset(p + v, 0, hp - p);
  2883. hp = p;
  2884. } else {
  2885. free(rpc_user);
  2886. rpc_user = strdup(ap);
  2887. }
  2888. *hp++ = '@';
  2889. } else
  2890. hp = ap;
  2891. if (ap != arg) {
  2892. if (strncasecmp(arg, "http://", 7) &&
  2893. strncasecmp(arg, "https://", 8) &&
  2894. strncasecmp(arg, "stratum+tcp://", 14)) {
  2895. fprintf(stderr, "unknown protocol -- '%s'\n", arg);
  2896. show_usage_and_exit(1);
  2897. }
  2898. free(rpc_url);
  2899. rpc_url = strdup(arg);
  2900. strcpy(rpc_url + (ap - arg), hp);
  2901. short_url = &rpc_url[ap - arg];
  2902. } else {
  2903. if (*hp == '\0' || *hp == '/') {
  2904. fprintf(stderr, "invalid URL -- '%s'\n",
  2905. arg);
  2906. show_usage_and_exit(1);
  2907. }
  2908. free(rpc_url);
  2909. rpc_url = (char*) malloc(strlen(hp) + 8);
  2910. sprintf(rpc_url, "http://%s", hp);
  2911. short_url = &rpc_url[sizeof("http://")-1];
  2912. }
  2913. have_stratum = !opt_benchmark && !strncasecmp(rpc_url, "stratum", 7);
  2914. break;
  2915. }
  2916. case 'O': /* --userpass */
  2917. p = strchr(arg, ':');
  2918. if (!p) {
  2919. fprintf(stderr, "invalid username:password pair -- '%s'\n", arg);
  2920. show_usage_and_exit(1);
  2921. }
  2922. free(rpc_userpass);
  2923. rpc_userpass = strdup(arg);
  2924. free(rpc_user);
  2925. rpc_user = (char*) calloc(p - arg + 1, 1);
  2926. strncpy(rpc_user, arg, p - arg);
  2927. free(rpc_pass);
  2928. rpc_pass = strdup(++p);
  2929. strhide(p);
  2930. break;
  2931. case 'x': /* --proxy */
  2932. if (!strncasecmp(arg, "socks4://", 9))
  2933. opt_proxy_type = CURLPROXY_SOCKS4;
  2934. else if (!strncasecmp(arg, "socks5://", 9))
  2935. opt_proxy_type = CURLPROXY_SOCKS5;
  2936. #if LIBCURL_VERSION_NUM >= 0x071200
  2937. else if (!strncasecmp(arg, "socks4a://", 10))
  2938. opt_proxy_type = CURLPROXY_SOCKS4A;
  2939. else if (!strncasecmp(arg, "socks5h://", 10))
  2940. opt_proxy_type = CURLPROXY_SOCKS5_HOSTNAME;
  2941. #endif
  2942. else
  2943. opt_proxy_type = CURLPROXY_HTTP;
  2944. free(opt_proxy);
  2945. opt_proxy = strdup(arg);
  2946. break;
  2947. case 1001:
  2948. free(opt_cert);
  2949. opt_cert = strdup(arg);
  2950. break;
  2951. case 1002:
  2952. use_colors = false;
  2953. break;
  2954. case 1003:
  2955. want_longpoll = false;
  2956. break;
  2957. case 1005:
  2958. opt_benchmark = true;
  2959. want_longpoll = false;
  2960. want_stratum = false;
  2961. have_stratum = false;
  2962. break;
  2963. case 1006:
  2964. print_hash_tests();
  2965. exit(0);
  2966. case 1007:
  2967. want_stratum = false;
  2968. opt_extranonce = false;
  2969. break;
  2970. case 1008:
  2971. opt_time_limit = atoi(arg);
  2972. break;
  2973. case 1009:
  2974. opt_redirect = false;
  2975. break;
  2976. case 1010:
  2977. allow_getwork = false;
  2978. break;
  2979. case 1011:
  2980. have_gbt = false;
  2981. break;
  2982. case 1012:
  2983. opt_extranonce = false;
  2984. break;
  2985. case 1013:
  2986. opt_showdiff = true;
  2987. break;
  2988. case 1014:
  2989. opt_showdiff = false;
  2990. break;
  2991. case 1016: /* --coinbase-addr */
  2992. pk_script_size = address_to_script(pk_script, sizeof(pk_script), arg);
  2993. if (!pk_script_size) {
  2994. fprintf(stderr, "invalid address -- '%s'\n", arg);
  2995. show_usage_and_exit(1);
  2996. }
  2997. break;
  2998. case 1015: /* --coinbase-sig */
  2999. if (strlen(arg) + 1 > sizeof(coinbase_sig)) {
  3000. fprintf(stderr, "coinbase signature too long\n");
  3001. show_usage_and_exit(1);
  3002. }
  3003. strcpy(coinbase_sig, arg);
  3004. break;
  3005. case 'f':
  3006. d = atof(arg);
  3007. if (d == 0.) /* --diff-factor */
  3008. show_usage_and_exit(1);
  3009. opt_diff_factor = d;
  3010. break;
  3011. case 'm':
  3012. d = atof(arg);
  3013. if (d == 0.) /* --diff-multiplier */
  3014. show_usage_and_exit(1);
  3015. opt_diff_factor = 1.0/d;
  3016. break;
  3017. case 'S':
  3018. use_syslog = true;
  3019. use_colors = false;
  3020. break;
  3021. case 1019: // max-log-rate
  3022. opt_maxlograte = atoi(arg);
  3023. break;
  3024. case 1020:
  3025. p = strstr(arg, "0x");
  3026. if (p)
  3027. ul = strtoul(p, NULL, 16);
  3028. else
  3029. ul = atol(arg);
  3030. if (ul > (1UL<<num_cpus)-1)
  3031. ul = -1;
  3032. opt_affinity = ul;
  3033. break;
  3034. case 1021:
  3035. v = atoi(arg);
  3036. if (v < 0 || v > 5) /* sanity check */
  3037. show_usage_and_exit(1);
  3038. opt_priority = v;
  3039. break;
  3040. case 1060: // max-temp
  3041. d = atof(arg);
  3042. opt_max_temp = d;
  3043. break;
  3044. case 1061: // max-diff
  3045. d = atof(arg);
  3046. opt_max_diff = d;
  3047. break;
  3048. case 1062: // max-rate
  3049. d = atof(arg);
  3050. p = strstr(arg, "K");
  3051. if (p) d *= 1e3;
  3052. p = strstr(arg, "M");
  3053. if (p) d *= 1e6;
  3054. p = strstr(arg, "G");
  3055. if (p) d *= 1e9;
  3056. opt_max_rate = d;
  3057. break;
  3058. case 1024:
  3059. opt_randomize = true;
  3060. break;
  3061. case 'V':
  3062. show_version_and_exit();
  3063. case 'h':
  3064. show_usage_and_exit(0);
  3065. default:
  3066. show_usage_and_exit(1);
  3067. }
  3068. }
  3069. void parse_config(json_t *config, char *ref)
  3070. {
  3071. int i;
  3072. json_t *val;
  3073. for (i = 0; i < ARRAY_SIZE(options); i++) {
  3074. if (!options[i].name)
  3075. break;
  3076. val = json_object_get(config, options[i].name);
  3077. if (!val)
  3078. continue;
  3079. if (options[i].has_arg && json_is_string(val)) {
  3080. char *s = strdup(json_string_value(val));
  3081. if (!s)
  3082. break;
  3083. parse_arg(options[i].val, s);
  3084. free(s);
  3085. }
  3086. else if (options[i].has_arg && json_is_integer(val)) {
  3087. char buf[16];
  3088. sprintf(buf, "%d", (int)json_integer_value(val));
  3089. parse_arg(options[i].val, buf);
  3090. }
  3091. else if (options[i].has_arg && json_is_real(val)) {
  3092. char buf[16];
  3093. sprintf(buf, "%f", json_real_value(val));
  3094. parse_arg(options[i].val, buf);
  3095. }
  3096. else if (!options[i].has_arg) {
  3097. if (json_is_true(val))
  3098. parse_arg(options[i].val, "");
  3099. }
  3100. else
  3101. applog(LOG_ERR, "JSON option %s invalid",
  3102. options[i].name);
  3103. }
  3104. }
  3105. static void parse_cmdline(int argc, char *argv[])
  3106. {
  3107. int key;
  3108. while (1) {
  3109. #if HAVE_GETOPT_LONG
  3110. key = getopt_long(argc, argv, short_options, options, NULL);
  3111. #else
  3112. key = getopt(argc, argv, short_options);
  3113. #endif
  3114. if (key < 0)
  3115. break;
  3116. parse_arg(key, optarg);
  3117. }
  3118. if (optind < argc) {
  3119. fprintf(stderr, "%s: unsupported non-option argument -- '%s'\n",
  3120. argv[0], argv[optind]);
  3121. show_usage_and_exit(1);
  3122. }
  3123. }
  3124. #ifndef WIN32
  3125. static void signal_handler(int sig)
  3126. {
  3127. switch (sig) {
  3128. case SIGHUP:
  3129. applog(LOG_INFO, "SIGHUP received");
  3130. break;
  3131. case SIGINT:
  3132. applog(LOG_INFO, "SIGINT received, exiting");
  3133. proper_exit(0);
  3134. break;
  3135. case SIGTERM:
  3136. applog(LOG_INFO, "SIGTERM received, exiting");
  3137. proper_exit(0);
  3138. break;
  3139. }
  3140. }
  3141. #else
  3142. BOOL WINAPI ConsoleHandler(DWORD dwType)
  3143. {
  3144. switch (dwType) {
  3145. case CTRL_C_EVENT:
  3146. applog(LOG_INFO, "CTRL_C_EVENT received, exiting");
  3147. proper_exit(0);
  3148. break;
  3149. case CTRL_BREAK_EVENT:
  3150. applog(LOG_INFO, "CTRL_BREAK_EVENT received, exiting");
  3151. proper_exit(0);
  3152. break;
  3153. default:
  3154. return false;
  3155. }
  3156. return true;
  3157. }
  3158. #endif
  3159. static int thread_create(struct thr_info *thr, void* func)
  3160. {
  3161. int err = 0;
  3162. pthread_attr_init(&thr->attr);
  3163. err = pthread_create(&thr->pth, &thr->attr, func, thr);
  3164. pthread_attr_destroy(&thr->attr);
  3165. return err;
  3166. }
  3167. static void show_credits()
  3168. {
  3169. printf("** cpuminer (ECOIN) by psy (03c8.net): **\n");
  3170. printf("BTC donation address: 19aXfJtoYJUoXEZtjNwsah2JKN9CK5Pcjw (psy)\n");
  3171. printf("ECO donation address: ETsRCBzaMawx3isvb5svX7tAukLdUFHKze (ECOin)\n\n");
  3172. printf("** usage: **\n");
  3173. printf("1) ./ecoin-qt -server\n");
  3174. printf("2) ./cpuminer -o http://0.0.0.0:7474 -O <rpcuser>:<rpcpassword> --coinbase-addr=<YOUR_ECOIN_ADDRESS>\n\n");
  3175. }
  3176. void get_defconfig_path(char *out, size_t bufsize, char *argv0);
  3177. int main(int argc, char *argv[]) {
  3178. struct thr_info *thr;
  3179. long flags;
  3180. int i, err;
  3181. pthread_mutex_init(&applog_lock, NULL);
  3182. show_credits();
  3183. rpc_user = strdup("");
  3184. rpc_pass = strdup("");
  3185. opt_api_allow = strdup("0.0.0.0");
  3186. #if defined(WIN32)
  3187. SYSTEM_INFO sysinfo;
  3188. GetSystemInfo(&sysinfo);
  3189. num_cpus = sysinfo.dwNumberOfProcessors;
  3190. #elif defined(_SC_NPROCESSORS_CONF)
  3191. num_cpus = sysconf(_SC_NPROCESSORS_CONF);
  3192. #elif defined(CTL_HW) && defined(HW_NCPU)
  3193. int req[] = { CTL_HW, HW_NCPU };
  3194. size_t len = sizeof(num_cpus);
  3195. sysctl(req, 2, &num_cpus, &len, NULL, 0);
  3196. #else
  3197. num_cpus = 1;
  3198. #endif
  3199. if (num_cpus < 1)
  3200. num_cpus = 1;
  3201. /* parse command line */
  3202. parse_cmdline(argc, argv);
  3203. if (!opt_benchmark && !rpc_url) {
  3204. // try default config file in binary folder
  3205. char defconfig[MAX_PATH] = { 0 };
  3206. get_defconfig_path(defconfig, MAX_PATH, argv[0]);
  3207. if (strlen(defconfig)) {
  3208. if (opt_debug)
  3209. applog(LOG_DEBUG, "Using config %s", defconfig);
  3210. parse_arg('c', defconfig);
  3211. parse_cmdline(argc, argv);
  3212. }
  3213. }
  3214. if (!opt_n_threads)
  3215. opt_n_threads = num_cpus;
  3216. if (!opt_n_threads)
  3217. opt_n_threads = 1;
  3218. if (opt_algo == ALGO_QUARK) {
  3219. init_quarkhash_contexts();
  3220. } else if(opt_algo == ALGO_CRYPTONIGHT || opt_algo == ALGO_CRYPTOLIGHT) {
  3221. jsonrpc_2 = true;
  3222. opt_extranonce = false;
  3223. aes_ni_supported = has_aes_ni();
  3224. if (!opt_quiet) {
  3225. applog(LOG_INFO, "Using JSON-RPC 2.0");
  3226. applog(LOG_INFO, "CPU Supports AES-NI: %s", aes_ni_supported ? "YES" : "NO");
  3227. }
  3228. } else if(opt_algo == ALGO_DECRED || opt_algo == ALGO_SIA) {
  3229. have_gbt = false;
  3230. }
  3231. if (!opt_benchmark && !rpc_url) {
  3232. fprintf(stderr, "%s: no URL supplied\n", argv[0]);
  3233. show_usage_and_exit(1);
  3234. }
  3235. if (!rpc_userpass) {
  3236. rpc_userpass = (char*) malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
  3237. if (!rpc_userpass)
  3238. return 1;
  3239. sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
  3240. }
  3241. pthread_mutex_init(&stats_lock, NULL);
  3242. pthread_mutex_init(&g_work_lock, NULL);
  3243. pthread_mutex_init(&rpc2_job_lock, NULL);
  3244. pthread_mutex_init(&rpc2_login_lock, NULL);
  3245. pthread_mutex_init(&stratum.sock_lock, NULL);
  3246. pthread_mutex_init(&stratum.work_lock, NULL);
  3247. flags = !opt_benchmark && strncmp(rpc_url, "https:", 6)
  3248. ? (CURL_GLOBAL_ALL & ~CURL_GLOBAL_SSL)
  3249. : CURL_GLOBAL_ALL;
  3250. if (curl_global_init(flags)) {
  3251. applog(LOG_ERR, "CURL initialization failed");
  3252. return 1;
  3253. }
  3254. #ifndef WIN32
  3255. if (opt_background) {
  3256. i = fork();
  3257. if (i < 0) exit(1);
  3258. if (i > 0) exit(0);
  3259. i = setsid();
  3260. if (i < 0)
  3261. applog(LOG_ERR, "setsid() failed (errno = %d)", errno);
  3262. i = chdir("/");
  3263. if (i < 0)
  3264. applog(LOG_ERR, "chdir() failed (errno = %d)", errno);
  3265. signal(SIGHUP, signal_handler);
  3266. signal(SIGTERM, signal_handler);
  3267. }
  3268. /* Always catch Ctrl+C */
  3269. signal(SIGINT, signal_handler);
  3270. #else
  3271. SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE);
  3272. if (opt_background) {
  3273. HWND hcon = GetConsoleWindow();
  3274. if (hcon) {
  3275. // this method also hide parent command line window
  3276. ShowWindow(hcon, SW_HIDE);
  3277. } else {
  3278. HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
  3279. CloseHandle(h);
  3280. FreeConsole();
  3281. }
  3282. }
  3283. if (opt_priority > 0) {
  3284. DWORD prio = NORMAL_PRIORITY_CLASS;
  3285. switch (opt_priority) {
  3286. case 1:
  3287. prio = BELOW_NORMAL_PRIORITY_CLASS;
  3288. break;
  3289. case 3:
  3290. prio = ABOVE_NORMAL_PRIORITY_CLASS;
  3291. break;
  3292. case 4:
  3293. prio = HIGH_PRIORITY_CLASS;
  3294. break;
  3295. case 5:
  3296. prio = REALTIME_PRIORITY_CLASS;
  3297. }
  3298. SetPriorityClass(GetCurrentProcess(), prio);
  3299. }
  3300. #endif
  3301. if (opt_affinity != -1) {
  3302. if (!opt_quiet)
  3303. applog(LOG_DEBUG, "Binding process to cpu mask %x", opt_affinity);
  3304. affine_to_cpu_mask(-1, (unsigned long)opt_affinity);
  3305. }
  3306. #ifdef HAVE_SYSLOG_H
  3307. if (use_syslog)
  3308. openlog("cpuminer", LOG_PID, LOG_USER);
  3309. #endif
  3310. work_restart = (struct work_restart*) calloc(opt_n_threads, sizeof(*work_restart));
  3311. if (!work_restart)
  3312. return 1;
  3313. thr_info = (struct thr_info*) calloc(opt_n_threads + 4, sizeof(*thr));
  3314. if (!thr_info)
  3315. return 1;
  3316. thr_hashrates = (double *) calloc(opt_n_threads, sizeof(double));
  3317. if (!thr_hashrates)
  3318. return 1;
  3319. /* init workio thread info */
  3320. work_thr_id = opt_n_threads;
  3321. thr = &thr_info[work_thr_id];
  3322. thr->id = work_thr_id;
  3323. thr->q = tq_new();
  3324. if (!thr->q)
  3325. return 1;
  3326. if (rpc_pass && rpc_user)
  3327. opt_stratum_stats = (strstr(rpc_pass, "stats") != NULL) || (strcmp(rpc_user, "benchmark") == 0);
  3328. /* start work I/O thread */
  3329. if (thread_create(thr, workio_thread)) {
  3330. applog(LOG_ERR, "work thread create failed");
  3331. return 1;
  3332. }
  3333. /* ESET-NOD32 Detects these 2 thread_create... */
  3334. if (want_longpoll && !have_stratum) {
  3335. /* init longpoll thread info */
  3336. longpoll_thr_id = opt_n_threads + 1;
  3337. thr = &thr_info[longpoll_thr_id];
  3338. thr->id = longpoll_thr_id;
  3339. thr->q = tq_new();
  3340. if (!thr->q)
  3341. return 1;
  3342. /* start longpoll thread */
  3343. err = thread_create(thr, longpoll_thread);
  3344. if (err) {
  3345. applog(LOG_ERR, "long poll thread create failed");
  3346. return 1;
  3347. }
  3348. }
  3349. if (want_stratum) {
  3350. /* init stratum thread info */
  3351. stratum_thr_id = opt_n_threads + 2;
  3352. thr = &thr_info[stratum_thr_id];
  3353. thr->id = stratum_thr_id;
  3354. thr->q = tq_new();
  3355. if (!thr->q)
  3356. return 1;
  3357. /* start stratum thread */
  3358. err = thread_create(thr, stratum_thread);
  3359. if (err) {
  3360. applog(LOG_ERR, "stratum thread create failed");
  3361. return 1;
  3362. }
  3363. if (have_stratum)
  3364. tq_push(thr_info[stratum_thr_id].q, strdup(rpc_url));
  3365. }
  3366. if (opt_api_listen) {
  3367. /* api thread */
  3368. api_thr_id = opt_n_threads + 3;
  3369. thr = &thr_info[api_thr_id];
  3370. thr->id = api_thr_id;
  3371. thr->q = tq_new();
  3372. if (!thr->q)
  3373. return 1;
  3374. err = thread_create(thr, api_thread);
  3375. if (err) {
  3376. applog(LOG_ERR, "api thread create failed");
  3377. return 1;
  3378. }
  3379. }
  3380. /* start mining threads */
  3381. for (i = 0; i < opt_n_threads; i++) {
  3382. thr = &thr_info[i];
  3383. thr->id = i;
  3384. thr->q = tq_new();
  3385. if (!thr->q)
  3386. return 1;
  3387. err = thread_create(thr, miner_thread);
  3388. if (err) {
  3389. applog(LOG_ERR, "thread %d create failed", i);
  3390. return 1;
  3391. }
  3392. }
  3393. applog(LOG_INFO, "%d miner threads started, "
  3394. "using '%s' algorithm.",
  3395. opt_n_threads,
  3396. algo_names[opt_algo]);
  3397. /* main loop - simply wait for workio thread to exit */
  3398. pthread_join(thr_info[work_thr_id].pth, NULL);
  3399. applog(LOG_WARNING, "workio thread dead, exiting.");
  3400. return 0;
  3401. }