OSDN Git Service

Various improvements to MIX table generation.
[mhash384/mhash384.git] / tools / GenTables / src / gen_table_mix.c
1 /* ----------------------------------------------------------------------------------------------- */
2 /* MHash-384 - Generate tables utility program                                                     */
3 /* Copyright(c) 2016-2017 LoRd_MuldeR <mulder2@gmx.de>                                             */
4 /*                                                                                                 */
5 /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software   */
6 /* and associated documentation files(the "Software"), to deal in the Software without             */
7 /* restriction, including without limitation the rights to use, copy, modify, merge, publish,      */
8 /* distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the */
9 /* Software is furnished to do so, subject to the following conditions:                            */
10 /*                                                                                                 */
11 /* The above copyright notice and this permission notice shall be included in all copies or        */
12 /* substantial portions of the Software.                                                           */
13 /*                                                                                                 */
14 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING   */
15 /* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND      */
16 /* NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,     */
17 /* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  */
18 /* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.         */
19 /* ----------------------------------------------------------------------------------------------- */
20
21 #include "common.h"
22 #include "thread_utils.h"
23 #include "twister.h"
24 #include "boxmuller.h"
25
26 #include <stdio.h>
27 #include <stdint.h>
28 #include <string.h>
29 #include <time.h>
30 #include <stdbool.h>
31 #include <io.h>
32
33 //-----------------------------------------------------------------------------
34 // Const
35 //-----------------------------------------------------------------------------
36
37 #define HASH_LEN 384U
38
39 #define ROW_NUM 997U                    /*total number of rows*/
40 #define ROW_LEN (HASH_LEN / CHAR_BIT)   /*number of indices per row*/
41
42 #define DISTANCE_MIN ROW_LEN-1
43
44 #undef ENABLE_TRACE
45
46 #define __DISTANCE_STR(X) #X
47 #define _DISTANCE_STR(X) __DISTANCE_STR(X)
48 #define DISTANCE_STR _DISTANCE_STR(DISTANCE_MIN)
49
50 #define MAGIC_NUMBER 0x76A3D06509A73016ui64
51
52 //-----------------------------------------------------------------------------
53 // Globals
54 //-----------------------------------------------------------------------------
55
56 static uint8_t g_table[ROW_NUM][HASH_LEN];
57
58 static size_t g_spinpos = 0;
59 static char SPINNER[4] = { '/', '-', '\\', '|' };
60
61 //-----------------------------------------------------------------------------
62 // Utility Functions
63 //-----------------------------------------------------------------------------
64
65 #ifdef ENABLE_TRACE
66 #define TRACE(X, ...) printf(X "\n", __VA_ARGS__)
67 #else
68 #define TRACE(X, ...) __noop()
69 #endif
70
71 static inline void swap(uint8_t *const row_buffer, const size_t a, const size_t b)
72 {
73         const uint8_t temp = row_buffer[a];
74         row_buffer[a] = row_buffer[b];
75         row_buffer[b] = temp;
76 }
77
78 static inline void random_permutation(twister_t *const rand, uint8_t *const row_buffer)
79 {
80         for (uint32_t i = 0; i < ROW_LEN; ++i)
81         {
82                 row_buffer[i] = ((uint8_t)i);
83         }
84         for (uint32_t i = 0; i < ROW_LEN - 1U; ++i)
85         {
86                 swap(row_buffer, i, next_rand_range(rand, ROW_LEN - i) + i);
87         }
88 }
89
90 static inline void swap_multiple_random(twister_t *const rand, uint8_t *const row_buffer, const size_t count)
91 {
92         const count_min = min(count, ROW_LEN / 2U);
93         bool map[ROW_LEN];
94         memset(&map[0], 0, sizeof(bool) * ROW_LEN);
95         for (size_t i = 0U; i < count_min; ++i)
96         {
97                 size_t a, b;
98                 do
99                 {
100                         a = next_rand_range(rand, ROW_LEN);
101                         b = next_rand_range(rand, ROW_LEN);
102                 } 
103                 while(map[a] || (a == b));
104                 map[a] = map[b] = true;
105                 swap(row_buffer, a, b);
106         }
107 }
108
109 static inline void rotate_row(uint8_t *const row_buffer)
110 {
111         const uint8_t temp = row_buffer[0];
112         for (uint32_t k = 0U; k < ROW_LEN - 1U; ++k)
113         {
114                 row_buffer[k] = row_buffer[k + 1U];
115         }
116         row_buffer[ROW_LEN - 1U] = temp;
117 }
118
119 static inline void reverse_row(uint8_t *const row_buffer)
120 {
121         size_t j = ROW_LEN - 1U;
122         for (size_t i = 0U; i < ROW_LEN / 2U; ++i)
123         {
124                 swap(row_buffer, i, j--);
125         }
126 }
127
128 static inline uint32_t check_permutation(const size_t index, const uint8_t *const row_buffer, const uint32_t limit)
129 {
130         uint32_t error = 0U;
131         for (size_t i = 0; i < ROW_LEN; ++i)
132         {
133                 if (row_buffer[i] == ((uint8_t)i))
134                 {
135                         if (++error >= limit)
136                         {
137                                 break; /*early termination*/
138                         }
139                 }
140         }
141         if(error)
142         {
143                 return ROW_LEN + error;
144         }
145         for (size_t i = 0; i < index; ++i)
146         {
147                 uint32_t distance = 0U;
148                 for (size_t j = 0; j < ROW_LEN; ++j)
149                 {
150                         if (g_table[i][j] != row_buffer[j])
151                         {
152                                 distance++;
153                         }
154                 }
155                 if (distance < DISTANCE_MIN)
156                 {
157                         if ((error = max_ui32(error, DISTANCE_MIN - distance)) >= limit)
158                         {
159                                 break; /*early termination*/
160                         }
161                 }
162         }
163         return error;
164 }
165
166 static void print_row(const uint8_t *const row_buffer)
167 {
168         for (size_t i = 0; i < ROW_LEN; ++i)
169         {
170                 printf(i ? ",%02X" : "%02X", row_buffer[i]);
171         }
172         puts("");
173 }
174
175 static inline void permutation_to_shuffle_indices(const uint8_t *const row_buffer, uint8_t *const indices_out)
176 {
177         uint8_t reference[ROW_LEN];
178         for (uint32_t i = 0U; i < ROW_LEN; ++i)
179         {
180                 reference[i] = ((uint8_t)i);
181         }
182         for (uint32_t i = 0U; i < ROW_LEN; ++i)
183         {
184                 indices_out[i] = UINT8_MAX;
185                 for (uint32_t j = i; j < ROW_LEN; ++j)
186                 {
187                         if (reference[j] == row_buffer[i])
188                         {
189                                 swap(&reference[0], i, j);
190                                 indices_out[i] = ((uint8_t)j);
191                                 break;
192                         }
193                 }
194         }
195         for (uint32_t i = 0; i < ROW_LEN; ++i)
196         {
197                 if ((indices_out[i] == UINT8_MAX) || (reference[i] != row_buffer[i]))
198                 {
199                         puts("ERROR: Failed to derive shuffle indices!\n");
200                 }
201         }
202 }
203
204 static dump_table(FILE *out)
205 {
206         fprintf(out, "uint8_t MHASH_384_TABLE_MIX[%u][MHASH_384_LEN] =\n{\n", ROW_NUM);
207         for (size_t i = 0; i < ROW_NUM; i++)
208         {
209                 fputs("\t{ ", out);
210                 for (size_t j = 0; j < ROW_LEN; j++)
211                 {
212                         if (j > 0)
213                         {
214                                 fputs(", ", out);
215                         }
216                         fprintf(out, "0x%02X", g_table[i][j]);
217                 }
218                 fprintf(out, " }%s /*%03u*/\n", (i != (ROW_NUM - 1)) ? "," : " ", (uint32_t)i);
219         }
220         fputs("};\n", out);
221 }
222
223 //-----------------------------------------------------------------------------
224 // Save / Load
225 //-----------------------------------------------------------------------------
226
227 static bool save_table_data(const wchar_t *const filename, const size_t rows_completed_in)
228 {
229         FILE *const file = _wfopen(filename, L"wb");
230         if (file)
231         {
232                 bool success = true;
233                 const uint64_t magic_number = MAGIC_NUMBER;
234                 const uint32_t hash_len = HASH_LEN, distance_min = DISTANCE_MIN, rows_completed = (uint32_t)rows_completed_in;
235                 fwrite(&magic_number, sizeof(uint64_t), 1, file);
236                 fwrite(&hash_len, sizeof(uint32_t), 1, file);
237                 fwrite(&distance_min, sizeof(uint32_t), 1, file);
238                 fwrite(&rows_completed, sizeof(uint32_t), 1, file);
239                 for (uint32_t i = 0; i < rows_completed; ++i)
240                 {
241                         const uint32_t checksum = adler32(&g_table[i][0], ROW_LEN);
242                         fwrite(&checksum, sizeof(uint32_t), 1, file);
243                         fwrite(&g_table[i][0], sizeof(uint8_t), ROW_LEN, file);
244                 }
245                 if (ferror(file))
246                 {
247                         printf("ERROR: Failed to write table data!\n");
248                         success = false;
249                 }
250                 fclose(file);
251                 return success;
252         }
253         else
254         {
255                 printf("ERROR: Failed to open table file for writing!\n");
256                 return false;
257         }
258 }
259
260 static bool load_table_data(const wchar_t *const filename, size_t *const rows_completed_out)
261 {
262         FILE *const file = _wfopen(filename, L"rb");
263         if (file)
264         {
265                 bool success = true;
266                 uint64_t magic_number;
267                 uint32_t hash_len, distance_min, rows_completed;
268                 fread(&magic_number, sizeof(uint64_t), 1, file);
269                 fread(&hash_len, sizeof(uint32_t), 1, file);
270                 fread(&distance_min, sizeof(uint32_t), 1, file);
271                 fread(&rows_completed, sizeof(uint32_t), 1, file);
272                 if (ferror(file) || feof(file))
273                 {
274                         printf("ERROR: Failed to read the table header!\n");
275                         success = false;
276                         goto failed;
277                 }
278                 if (magic_number != MAGIC_NUMBER)
279                 {
280                         printf("ERROR: Table file format could not be recognized!\n");
281                         success = false;
282                         goto failed;
283                 }
284                 if ((hash_len != HASH_LEN) || (distance_min != DISTANCE_MIN) || (rows_completed > ROW_NUM))
285                 {
286                         printf("ERROR: Table properties are incompatibe with this instance!\n");
287                         success = false;
288                         goto failed;
289                 }
290                 for (size_t i = 0; i < rows_completed; ++i)
291                 {
292                         uint32_t checksum_expected;
293                         if ((fread(&checksum_expected, sizeof(uint32_t), 1, file) != 1) || (fread(&g_table[i][0], sizeof(uint8_t), ROW_LEN, file) != ROW_LEN))
294                         {
295                                 printf("ERROR: Failed to read table data from file!\n");
296                                 success = false;
297                                 goto failed;
298                         }
299                         if (adler32(&g_table[i][0], ROW_LEN) != checksum_expected)
300                         {
301                                 printf("ERROR: Table checksum does *not* match table contents!\n");
302                                 success = false;
303                                 goto failed;
304                         }
305                         if (check_permutation(i, &g_table[i][0], 0U) != 0U)
306                         {
307                                 printf("ERROR: Table distance verification has failed!\n");
308                                 success = false;
309                                 goto failed;
310                         }
311                 }
312         failed:
313                 fclose(file);
314                 if (success && rows_completed_out)
315                 {
316                         *rows_completed_out = (size_t)rows_completed;
317                 }
318                 return success;
319         }
320         else
321         {
322                 printf("ERROR: Failed to open table file for reading!\n");
323                 return false;
324         }
325 }
326 //-----------------------------------------------------------------------------
327 // MAIN
328 //-----------------------------------------------------------------------------
329
330 int wmain(int argc, wchar_t *argv[])
331 {
332         FILE *file_out = NULL;
333         size_t initial_row_index = 0;
334         char time_string[64];
335
336         printf("MHash GenTableMIX [%s]\n\n", __DATE__);
337         printf("HashLen: %d, Distance Min: %d\n\n", HASH_LEN, DISTANCE_MIN);
338
339         if ((HASH_LEN % (8 * sizeof(uint32_t))) != 0)
340         {
341                 crit_exit("FATAL: Hash length must be a multiple of 32 bits!");
342         }
343
344         if (argc < 2)
345         {
346                 printf("Table file not specified!\n\n");
347                 printf("Usage:\n");
348                 printf("   GenTables_MIX.exe <table_file>\n\n");
349                 return 1;
350         }
351
352         twister_t rand;
353         rand_init(&rand, make_seed());
354
355         bxmller_t bxmller;
356         gaussian_noise_init(&bxmller);
357
358         if (_waccess(argv[1], 4) == 0)
359         {
360                 printf("Loading existing table data and proceeding...\n");
361                 if (!load_table_data(argv[1], &initial_row_index))
362                 {
363                         return 1;
364                 }
365         }
366
367         for (size_t i = initial_row_index; i < ROW_NUM; ++i)
368         {
369                 printf("Row %03u of %03u [%c]", (uint32_t)(i + 1U), ROW_NUM, SPINNER[g_spinpos]);
370                 uint_fast16_t counter = 0U;
371                 time_t ref_time = time(NULL);
372                 uint8_t temp[ROW_LEN];
373                 for (;;)
374                 {
375                         random_permutation(&rand, &g_table[i][0]);
376                         uint32_t error = check_permutation(i, &g_table[i][0], 2U * ROW_LEN);
377                         for (int_fast16_t retry = 0; retry < 4999; ++retry)
378                         {
379                                 if (!((++counter) & 0x3F))
380                                 {
381                                         printf("\b\b\b[%c]", SPINNER[g_spinpos]);
382                                         g_spinpos = (g_spinpos + 1) % 4;
383                                 }
384                                 for (uint_fast16_t rand_init = 0U; rand_init < 9973U; ++rand_init)
385                                 {
386                                         random_permutation(&rand, &temp[0]);
387                                         const uint32_t error_next = check_permutation(i, &temp[0], error);
388                                         if (error_next < error)
389                                         {
390                                                 TRACE("Improved by rand init!");
391                                                 retry = -1;
392                                                 memcpy(&g_table[i][0], &temp[0], sizeof(uint8_t) * ROW_LEN); /*keep*/
393                                                 if (!((error = error_next) > 0U))
394                                                 {
395                                                         goto success;
396                                                 }
397                                         }
398                                         for (uint_fast8_t rotate = 0U; rotate < ROW_LEN; ++rotate)
399                                         {
400                                                 rotate_row(&temp[0]);
401                                                 const uint32_t error_next = check_permutation(i, &temp[0], error);
402                                                 if (error_next < error)
403                                                 {
404                                                         TRACE("Improved by rotate!");
405                                                         retry = -1;
406                                                         memcpy(&g_table[i][0], &temp[0], sizeof(uint8_t) * ROW_LEN); /*keep*/
407                                                         if (!((error = error_next) > 0U))
408                                                         {
409                                                                 goto success;
410                                                         }
411                                                         break;
412                                                 }
413                                         }
414                                         reverse_row(&temp[0]);
415                                         const uint32_t error_next_reverse = check_permutation(i, &temp[0], error);
416                                         if (error_next_reverse < error)
417                                         {
418                                                 TRACE("Improved by reverse!");
419                                                 retry = -1;
420                                                 memcpy(&g_table[i][0], &temp[0], sizeof(uint8_t) * ROW_LEN); /*keep*/
421                                                 if (!((error = error_next_reverse) > 0U))
422                                                 {
423                                                         goto success;
424                                                 }
425                                                 break;
426                                         }
427                                 }
428                         }
429                         if (error > 0U)
430                         {
431                                 for (int_fast16_t retry = 0; retry < 4999; ++retry)
432                                 {
433                                         TRACE("Optimizer round %u of 4999", retry);
434                                         if (!retry)
435                                         {
436                                                 rand_init(&rand, make_seed());
437                                                 TRACE("First round!");
438                                                 for (uint_fast8_t swap_x1 = 0; swap_x1 < ROW_LEN; ++swap_x1)
439                                                 {
440                                                         printf("\b\b\b[%c]", SPINNER[g_spinpos]);
441                                                         g_spinpos = (g_spinpos + 1) % 4;
442                                                         for (uint_fast8_t swap_y1 = swap_x1 + 1U; swap_y1 < ROW_LEN; ++swap_y1)
443                                                         {
444                                                                 bool revert_1 = true;
445                                                                 swap(&g_table[i][0], swap_x1, swap_y1);
446                                                                 const uint32_t error_next = check_permutation(i, &g_table[i][0], error);
447                                                                 if (error_next < error)
448                                                                 {
449                                                                         TRACE("Improved by swap-1!");
450                                                                         revert_1 = false;
451                                                                         retry = -1;
452                                                                         if (!((error = error_next) > 0U))
453                                                                         {
454                                                                                 goto success;
455                                                                         }
456                                                                 }
457                                                                 for (uint_fast8_t swap_x2 = 0; swap_x2 < ROW_LEN; ++swap_x2)
458                                                                 {
459                                                                         for (uint_fast8_t swap_y2 = swap_x2 + 1U; swap_y2 < ROW_LEN; ++swap_y2)
460                                                                         {
461                                                                                 bool revert_2 = true;
462                                                                                 swap(&g_table[i][0], swap_x2, swap_y2);
463                                                                                 const uint32_t error_next = check_permutation(i, &g_table[i][0], error);
464                                                                                 if (error_next < error)
465                                                                                 {
466                                                                                         TRACE("Improved by swap-2!");
467                                                                                         revert_1 = revert_2 = false;
468                                                                                         retry = -1;
469                                                                                         if (!((error = error_next) > 0U))
470                                                                                         {
471                                                                                                 goto success;
472                                                                                         }
473                                                                                 }
474                                                                                 for (uint_fast8_t swap_x3 = 0; swap_x3 < ROW_LEN; ++swap_x3)
475                                                                                 {
476                                                                                         for (uint_fast8_t swap_y3 = swap_x3 + 1U; swap_y3 < ROW_LEN; ++swap_y3)
477                                                                                         {
478                                                                                                 swap(&g_table[i][0], swap_x3, swap_y3);
479                                                                                                 const uint32_t error_next = check_permutation(i, &g_table[i][0], error);
480                                                                                                 if (error_next >= error)
481                                                                                                 {
482                                                                                                         swap(&g_table[i][0], swap_x3, swap_y3); /*revert*/
483                                                                                                 }
484                                                                                                 else
485                                                                                                 {
486                                                                                                         TRACE("Improved by swap-3!");
487                                                                                                         revert_1 = revert_2 = false;
488                                                                                                         retry = -1;
489                                                                                                         if (!((error = error_next) > 0U))
490                                                                                                         {
491                                                                                                                 goto success;
492                                                                                                         }
493                                                                                                 }
494                                                                                         }
495                                                                                 }
496                                                                                 if (revert_2)
497                                                                                 {
498                                                                                         swap(&g_table[i][0], swap_x2, swap_y2); /*revert*/
499                                                                                 }
500                                                                         }
501                                                                 }
502                                                                 if (revert_1)
503                                                                 {
504                                                                         swap(&g_table[i][0], swap_x1, swap_y1); /*revert*/
505                                                                 }
506                                                         }
507                                                 }
508                                         }
509                                         const double sigma = 3.14159 * (1.0 + (retry / 4999.0));
510                                         for (int_fast16_t loop = 0; loop < 9973U; ++loop)
511                                         {
512                                                 const uint32_t swap_count = gaussian_noise_next(&rand, &bxmller, sigma, 4U, (ROW_LEN / 2U));
513                                                 if (!((++counter) & 0x3FFF))
514                                                 {
515                                                         printf("\b\b\b[%c]", SPINNER[g_spinpos]);
516                                                         g_spinpos = (g_spinpos + 1) % 4;
517                                                 }
518                                                 for (int_fast16_t round = 0; round < 997U; ++round)
519                                                 {
520                                                         memcpy(&temp[0], &g_table[i][0], sizeof(uint8_t) * ROW_LEN);
521                                                         swap_multiple_random(&rand, &temp[0], swap_count);
522                                                         const uint32_t error_next = check_permutation(i, &temp[0], error);
523                                                         if (error_next < error)
524                                                         {
525                                                                 TRACE("Improved by swap-n (%u)!", swap_count);
526                                                                 memcpy(&g_table[i][0], &temp[0], sizeof(uint8_t) * ROW_LEN); /*keep*/
527                                                                 retry = -1;
528                                                                 if (!((error = error_next) > 0U))
529                                                                 {
530                                                                         goto success;
531                                                                 }
532                                                         }
533                                                 }
534                                         }
535                                 }
536                         }
537                         else
538                         {
539                                 break; /*success*/
540                         }
541                 }
542
543         success:
544                 get_time_str(time_string, 64);
545                 printf("\b\b\b[#] - %s\n", time_string);
546
547                 if (!save_table_data(argv[1], i + 1U))
548                 {
549                         return 1; /*failed to save current table data*/
550                 }
551         }
552
553         printf("\n-----\n\n");
554
555         dump_table(stdout);
556         if (fopen_s(&file_out, "table_MIX." DISTANCE_STR ".txt", "w") == 0)
557         {
558                 dump_table(file_out);
559                 fclose(file_out);
560         }
561
562         printf("\n-----\n\n");
563
564         printf("COMPLETED.\n\n");
565         return getchar();
566 }