This might be more correct calculation.
[core.git] / contrib / chash / chash.php
1 <?php
2 error_reporting(E_ALL | E_STRICT);
3
4 define('HASH_ALGO', MHASH_RIPEMD320);
5 define('BLOCK_SIZE', 1000);
6 define('NONCE_INCREMENT', 0.00001);
7 define('START_TIME', microtime(TRUE));
8
9 /**
10  * Continued-hashing
11  *
12  * @author              Roland Haeder <roland@mxchange.org>
13  * @copyright   Copyright (c) 2013 by Core Developer Team
14  * @license             See LICENSE (public-domain)
15  */
16
17 /**
18  * Calculates a simple but stronger hash from given string. No salts are being
19  * added here.
20  *
21  * @param       $str    The string to be hashed
22  * @return      $hash   The hash from string $str
23  */
24 function hashString ($str) {
25         // Calculate strong hash from given string
26         $hash = mhash(HASH_ALGO, $str);
27
28         // Return it hexadecimal-encoded
29         return bin2hex($hash);
30 }
31
32 /**
33  * Double-hashes given string. This is done by hashing the given string and
34  * then hashing the generated hash again.
35  *
36  * @param       $str    The string to be hashed 4 times
37  * @return      $hash   The generated hash
38  */
39 function doubleHashString ($str) {
40         // Generate hash from given hash
41         $hash = hashString(hashString($str));
42
43         // Return it
44         return $hash;
45 }
46
47 /**
48  * Calculates a "modula-hash" based given two hashes.
49  *
50  * @param       $hash1  Hash 1
51  * @param       $hash2  Hash 2
52  */
53 function modulaHash ($hash1, $hash2) {
54         // Both must have same length
55         assert(strlen($hash1) === strlen($hash2));
56
57         // Init new hash
58         $modulaHash = '';
59
60         // "Walk" trough first hash and get every 2 byte of both hashes
61         for ($idx = 0; $idx < strlen($hash1); $idx += 2) {
62                 // Init modula value
63                 $mod = 0;
64
65                 // Get both hash parts and convert to ASCII number
66                 $part1 = hexdec(substr($hash1, $idx, 2));
67                 $part2 = hexdec(substr($hash2, $idx, 2));
68
69                 /*
70                  * If part1 is larget part2, part1 is divident and vise-versa. But don't do it
71                  * if one is zero
72                  */
73                 if (($part1 > $part2) && ($part2 > 0)) {
74                         // 'part1' is larger than 'part2'
75                         $mod = $part1 % $part2;
76                 } elseif (($part1 < $part2) && ($part1 > 0)) {
77                         // 'part2' is larger than 'part1'
78                         $mod = $part2 % $part1;
79                 }
80
81                 // "Invert" the result against 255
82                 $mod = 255 - $mod;
83
84                 // Encode to hex, pre-pad it with zeros and add to new hash
85                 $modulaHash .= padHex($mod);
86         } // END - for
87
88         // Modula hash must have same length as input hash
89         assert(strlen($modulaHash) === strlen($hash1));
90
91         // Return modula hash
92         return $modulaHash;
93 }
94
95 /**
96  * Calculates a "sqrt-hash" based given two hashes and single-hash it
97  *
98  * @param       $hash1  Hash 1
99  * @param       $hash2  Hash 2
100  */
101 function sqrtHash ($hash1, $hash2) {
102         // Both must have same length
103         assert(strlen($hash1) === strlen($hash2));
104
105         // Init new hash
106         $sqrtHash = '';
107
108         // "Walk" trough first hash and get every 2 byte of both hashes
109         for ($idx = 0; $idx < strlen($hash1); $idx += 2) {
110                 // Init modula value
111                 $mod = 0;
112
113                 // Get both hash parts and convert to ASCII number
114                 $part1 = hexdec(substr($hash1, $idx, 2));
115                 $part2 = hexdec(substr($hash2, $idx, 2));
116
117                 // Calculate square root of both parts being multiplied and round up, then "invert" it against 255
118                 $sqrt = intval(255 - ceil(sqrt($part1 * $part2)));
119
120                 // Encode to hex, pre-pad it with zeros and add to new hash
121                 $sqrtHash .= padHex($sqrt);
122         } // END - for
123
124         // "sqrt-hash" must have same length as input hash
125         assert(strlen($sqrtHash) === strlen($hash1));
126
127         // Hash reversed "sqrt-hash" again and return it
128         return hashString(strrev($sqrtHash));
129 }
130
131 /**
132  * Converts a number between 0 and 255 into a zero-padded hexadecimal string
133  *
134  * @param       $num    Number between 0 and 255
135  * @return      $hex    Hexadecimal string, padded with zeros
136  */
137 function padHex ($num) {
138         // Must be a integer number and between 0 and 255
139         assert(is_int($num));
140         assert($num >= 0);
141         assert($num <= 255);
142
143         // Convert it
144         $hex = str_pad(dechex($num), 2, '0', STR_PAD_LEFT);
145
146         // ... and return it
147         return $hex;
148 }
149
150 /**
151  * Calculates sum from given hash
152  *
153  * @param       $hash   Hash to calculate sum from
154  * @return      $sum    Sum from given hash
155  */
156 function calculateSumFromHash ($hash) {
157         // Everything starts with zero ...
158         $sum = 0;
159
160         // Loop through hash
161         for ($idx = 0; $idx < (strlen($hash) / 2); $idx++) {
162                 // And add it
163                 $sum = $sum + (hexdec(substr($hash, $idx, 2)) * $idx & 256);
164         } // END - for
165
166         // And return it
167         return $sum;
168 }
169
170 /**
171  * Calculates new nonce
172  *
173  * @param       $nonce          Old nonce to be used
174  * @return      $newNonce       New nonce
175  */
176 function calculateNonce ($nonce) {
177         // Linear incrementation
178         $newNonce = $nonce + NONCE_INCREMENT;
179
180         // Return new value
181         return $newNonce;
182 }
183
184 /*
185  * Calculate "genesis" hashes, please note that these "genesis strings" are now
186  * known to the public as you can read them here in source code and therefore I
187  * will not use them for the real genesis hashes.
188  */
189 $hashes = array(
190         // A famous quote from Deus Ex 2 - Invisible War
191         doublehashString('"Informations must be free." - AI Helios from Deus Ex'),
192         // My name + URL of my first StatusNet instance
193         doubleHashString('Roland Haeder, https://status.mxchange.org'),
194         // A famous quote from Linus Torwalds
195         doubleHashString('"Software is like sex. Its better when its free." - Linus Torwalds'),
196         // Possible truth ;-)
197         doubleHashString('September 11 is a big lie.'),
198
199         // GNU is not Uni*
200         doubleHashString('GNU is Not Uni*.'),
201         // WINE is not an emulator
202         doubleHashString('WINE Is Not an Emulator.'),
203         // FlightGear - Fly free!
204         doubleHashString('FlightGear - Fly free!'),
205         // Linus Torwalds Quote
206         doubleHashString('Your code is shit.. your argument is shit.'),
207 );
208
209 // Calculate "modula hash" from 1st/4th and 2nd/3rd
210 $modulaHashes = array(
211         // "Block" 0
212         modulaHash($hashes[0], $hashes[3]),
213         modulaHash($hashes[1], $hashes[2]),
214
215         // "Block" 1
216         modulaHash($hashes[4], $hashes[7]),
217         modulaHash($hashes[5], $hashes[6]),
218 );
219
220 // Calculate "sqrt hash"
221 $sqrtHashes = array(
222         sqrtHash($modulaHashes[0], $modulaHashes[1]),
223         sqrtHash($modulaHashes[2], $modulaHashes[3])
224 );
225
226 // Calulcate modula hash
227 $modulaHash = doubleHashString(modulaHash($sqrtHashes[0], $sqrtHashes[1]));
228
229 // Output results
230 print ('hashes=' . print_r($hashes, TRUE));
231 print ('modulaHashes=' . print_r($modulaHashes, TRUE));
232 print ('sqrtHashes=' . print_r($sqrtHashes, TRUE));
233 print ('modulaHash=' . $modulaHash . PHP_EOL);
234
235 // Total reward + hashes
236 $totalReward = 0;
237 $totalHashes = 0;
238 $totalBlocks = 0;
239
240 // Create nonce (small)
241 $nonce = 1 / mt_rand();
242
243 while (TRUE) {
244         // Init hash-per-block counter and hashrate
245         $hashesPerBlock = 0;
246         $hashrate = 0;
247
248         // Wait for BLOCK_SIZE iterations (= found hashes). This is one block
249         $timeBlock = microtime(TRUE);
250         $timeDisplay = $timeBlock;
251
252         // Time waited for a good block again (no iteration)
253         $timeBadHashes = 0;
254
255         while ($hashesPerBlock <= BLOCK_SIZE) {
256                 // Create hash from modulaHash ("genesis hash") and nonce
257                 $nonceHash = doubleHashString($modulaHash . $nonce);
258
259                 // Calculate sums
260                 $sumNonce  = calculateSumFromHash($nonceHash);
261                 $sumModula = calculateSumFromHash($modulaHash);
262
263                 // Init counter
264                 $iter = 0;
265
266                 // Now start the "mining" ...
267                 $timeHash = microtime(TRUE);
268                 while ($sumNonce >= $sumModula) {
269                         // Calculate new nonce
270                         $nonce = calculateNonce($nonce);
271
272                         // And hash again
273                         $nonceHash = doubleHashString($modulaHash . $nonce);
274
275                         // Calculate sums
276                         $sumNonce  = calculateSumFromHash($nonceHash);
277                         //print('hashesPerBlock=' . $hashesPerBlock . PHP_EOL);
278
279                         // Time spend in loop
280                         $testTime = abs(microtime(TRUE) - $timeDisplay);
281
282                         // Calculate hashrate/sec
283                         $hashrate = 1 / $testTime * $iter * 2 + 2;
284
285                         // Only every second
286                         if ($testTime >= 1) {
287                                 // Display hash rate
288                                 print ('hashesPerBlock=' . $hashesPerBlock . ',hashrate=' . $hashrate . ' hashes/sec.' . PHP_EOL);
289
290                                 // Reset timer
291                                 $timeDisplay = microtime(TRUE);
292                         } // END - if
293
294                         // Next round
295                         $iter++;
296                         //print ('nonce=' . $nonce . ',iter=' . $iter . PHP_EOL);
297                         //print ('nonceHash=' . $nonceHash . PHP_EOL);
298                         //print ('sumNonce=' . $sumNonce . PHP_EOL);
299                         //print ('sumModula=' . $sumModula . PHP_EOL);
300                 } // END - while
301
302                 // Add amount of hashes to block (double-hash)
303                 $hashesPerBlock += $iter * 2 + 2;
304
305                 // If the iteration is zero, then no hash is found
306                 if ($iter == 0) {
307                         // Bad block found
308                         $timeBadHashes += abs(microtime(TRUE) - $timeHash);
309
310                         // And next round
311                         //print('bad:nonce=' . $nonce . PHP_EOL);
312
313                         // Nothing found, so calculate new nonce
314                         $nonce = calculateNonce($nonce);
315                         continue;
316                 } // END - if
317
318                 // Found hash:
319                 //print ('nonceHash=' . $nonceHash .',iter=' . $iter . PHP_EOL);
320
321                 // Use nonceHash as next modula hash
322                 $modulaHash = $nonceHash;
323         } // END - while
324
325         // Time taken for one block
326         $timeBlock = abs(microtime(TRUE) - $timeBlock);
327         //print ('calculateSumFromHash(modulaHash)=' . calculateSumFromHash($modulaHash) . PHP_EOL);
328         //print ('calculateSumFromHash(nonceHash)=' . calculateSumFromHash($nonceHash) . PHP_EOL);
329
330         // Calculate reward
331         $reward = abs($timeBlock - $timeBadHashes) / $hashrate * $hashesPerBlock / BLOCK_SIZE * 1000;
332         //print ('timeBlock=' . $timeBlock . ',timeBadHashes=' . $timeBadHashes . ',hashesPerBlock=' . $hashesPerBlock .',reward=' . $reward . PHP_EOL);
333
334         // Block completed
335         $totalHashes += $hashesPerBlock;
336         $totalBlocks++;
337         $hashesPerBlock = 0;
338
339         // Calculate new nonce
340         $nonce = calculateNonce($nonce);
341
342         // Add reward to total
343         $totalReward += $reward;
344
345         // Calculate average block value
346         $blockValue = $totalReward / $totalBlocks * $totalHashes / (BLOCK_SIZE * $totalBlocks);
347
348         // Calculate reward per hour (= 3600 seconds)
349         $rewardPerHour = $totalReward / abs(microtime(TRUE) - START_TIME) * 3600;
350
351         print ('totalReward=' . $totalReward . ',blockValue=' . $blockValue . ',rewardPerHour=' . $rewardPerHour . PHP_EOL);
352 } // END - while
353
354 // [EOF]
355 ?>