2016 / Day 05
How About a Nice Game of Chess?
Read the original puzzle on adventofcode.com ↗
The solution
solution.c
1#include "aoc.h"
2
3#include <string.h>
4
5/* 2016 day 5. Both passwords mine ordinary MD5 from index zero.
6 * IDs have at most 32 bytes of [a-z0-9], indices are below 30 million,
7 * and each padded message fits one block. Ten consecutive candidates
8 * share the suffix prefix. Inline the unrolled MD5 into those trials so
9 * the basic-block work budget does not charge a helper entry per hash.
10 * Part 2 uses the sixth hex digit as position and the seventh as value.
11 */
12
13enum { MAXIDX = 30000000 };
14
15enum { SALTMAX = 32 };
16
17#define MD5ROL(x, s) (((x) << (s)) | ((x) >> (32 - (s))))
18#define MD5F(x, y, z) (((x) & (y)) | (~(x) & (z)))
19#define MD5G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
20#define MD5H(x, y, z) ((x) ^ (y) ^ (z))
21#define MD5I(x, y, z) ((y) ^ ((x) | ~(z)))
22#define MD5STEP(fn, a, b, c, d, x, s, k) \
23 a = b + MD5ROL(a + fn(b, c, d) + (x) + (uint32_t)(k), (s))
24
25/* One-block MD5 over a pre-padded 64-byte block. The digest comes
26 * back as four little-endian words: bytes 0..3 are st[0].
27 */
28static inline __attribute__((always_inline)) void md5_64(const uint8_t *blk,
29 uint32_t st[4]) {
30 uint32_t w0, w1, w2, w3, w4, w5, w6, w7;
31 uint32_t w8, w9, w10, w11, w12, w13, w14, w15;
32 uint32_t a, b, c, d;
33
34#define WLOAD(i) \
35 ((uint32_t)blk[4 * (i)] | ((uint32_t)blk[4 * (i) + 1] << 8) | \
36 ((uint32_t)blk[4 * (i) + 2] << 16) | ((uint32_t)blk[4 * (i) + 3] << 24))
37 w0 = WLOAD(0);
38 w1 = WLOAD(1);
39 w2 = WLOAD(2);
40 w3 = WLOAD(3);
41 w4 = WLOAD(4);
42 w5 = WLOAD(5);
43 w6 = WLOAD(6);
44 w7 = WLOAD(7);
45 w8 = WLOAD(8);
46 w9 = WLOAD(9);
47 w10 = WLOAD(10);
48 w11 = WLOAD(11);
49 w12 = WLOAD(12);
50 w13 = WLOAD(13);
51 w14 = WLOAD(14);
52 w15 = WLOAD(15);
53#undef WLOAD
54
55 a = 0x67452301u;
56 b = 0xefcdab89u;
57 c = 0x98badcfeu;
58 d = 0x10325476u;
59
60 MD5STEP(MD5F, a, b, c, d, w0, 7, 0xd76aa478u);
61 MD5STEP(MD5F, d, a, b, c, w1, 12, 0xe8c7b756u);
62 MD5STEP(MD5F, c, d, a, b, w2, 17, 0x242070dbu);
63 MD5STEP(MD5F, b, c, d, a, w3, 22, 0xc1bdceeeu);
64 MD5STEP(MD5F, a, b, c, d, w4, 7, 0xf57c0fafu);
65 MD5STEP(MD5F, d, a, b, c, w5, 12, 0x4787c62au);
66 MD5STEP(MD5F, c, d, a, b, w6, 17, 0xa8304613u);
67 MD5STEP(MD5F, b, c, d, a, w7, 22, 0xfd469501u);
68 MD5STEP(MD5F, a, b, c, d, w8, 7, 0x698098d8u);
69 MD5STEP(MD5F, d, a, b, c, w9, 12, 0x8b44f7afu);
70 MD5STEP(MD5F, c, d, a, b, w10, 17, 0xffff5bb1u);
71 MD5STEP(MD5F, b, c, d, a, w11, 22, 0x895cd7beu);
72 MD5STEP(MD5F, a, b, c, d, w12, 7, 0x6b901122u);
73 MD5STEP(MD5F, d, a, b, c, w13, 12, 0xfd987193u);
74 MD5STEP(MD5F, c, d, a, b, w14, 17, 0xa679438eu);
75 MD5STEP(MD5F, b, c, d, a, w15, 22, 0x49b40821u);
76 MD5STEP(MD5G, a, b, c, d, w1, 5, 0xf61e2562u);
77 MD5STEP(MD5G, d, a, b, c, w6, 9, 0xc040b340u);
78 MD5STEP(MD5G, c, d, a, b, w11, 14, 0x265e5a51u);
79 MD5STEP(MD5G, b, c, d, a, w0, 20, 0xe9b6c7aau);
80 MD5STEP(MD5G, a, b, c, d, w5, 5, 0xd62f105du);
81 MD5STEP(MD5G, d, a, b, c, w10, 9, 0x02441453u);
82 MD5STEP(MD5G, c, d, a, b, w15, 14, 0xd8a1e681u);
83 MD5STEP(MD5G, b, c, d, a, w4, 20, 0xe7d3fbc8u);
84 MD5STEP(MD5G, a, b, c, d, w9, 5, 0x21e1cde6u);
85 MD5STEP(MD5G, d, a, b, c, w14, 9, 0xc33707d6u);
86 MD5STEP(MD5G, c, d, a, b, w3, 14, 0xf4d50d87u);
87 MD5STEP(MD5G, b, c, d, a, w8, 20, 0x455a14edu);
88 MD5STEP(MD5G, a, b, c, d, w13, 5, 0xa9e3e905u);
89 MD5STEP(MD5G, d, a, b, c, w2, 9, 0xfcefa3f8u);
90 MD5STEP(MD5G, c, d, a, b, w7, 14, 0x676f02d9u);
91 MD5STEP(MD5G, b, c, d, a, w12, 20, 0x8d2a4c8au);
92 MD5STEP(MD5H, a, b, c, d, w5, 4, 0xfffa3942u);
93 MD5STEP(MD5H, d, a, b, c, w8, 11, 0x8771f681u);
94 MD5STEP(MD5H, c, d, a, b, w11, 16, 0x6d9d6122u);
95 MD5STEP(MD5H, b, c, d, a, w14, 23, 0xfde5380cu);
96 MD5STEP(MD5H, a, b, c, d, w1, 4, 0xa4beea44u);
97 MD5STEP(MD5H, d, a, b, c, w4, 11, 0x4bdecfa9u);
98 MD5STEP(MD5H, c, d, a, b, w7, 16, 0xf6bb4b60u);
99 MD5STEP(MD5H, b, c, d, a, w10, 23, 0xbebfbc70u);
100 MD5STEP(MD5H, a, b, c, d, w13, 4, 0x289b7ec6u);
101 MD5STEP(MD5H, d, a, b, c, w0, 11, 0xeaa127fau);
102 MD5STEP(MD5H, c, d, a, b, w3, 16, 0xd4ef3085u);
103 MD5STEP(MD5H, b, c, d, a, w6, 23, 0x04881d05u);
104 MD5STEP(MD5H, a, b, c, d, w9, 4, 0xd9d4d039u);
105 MD5STEP(MD5H, d, a, b, c, w12, 11, 0xe6db99e5u);
106 MD5STEP(MD5H, c, d, a, b, w15, 16, 0x1fa27cf8u);
107 MD5STEP(MD5H, b, c, d, a, w2, 23, 0xc4ac5665u);
108 MD5STEP(MD5I, a, b, c, d, w0, 6, 0xf4292244u);
109 MD5STEP(MD5I, d, a, b, c, w7, 10, 0x432aff97u);
110 MD5STEP(MD5I, c, d, a, b, w14, 15, 0xab9423a7u);
111 MD5STEP(MD5I, b, c, d, a, w5, 21, 0xfc93a039u);
112 MD5STEP(MD5I, a, b, c, d, w12, 6, 0x655b59c3u);
113 MD5STEP(MD5I, d, a, b, c, w3, 10, 0x8f0ccc92u);
114 MD5STEP(MD5I, c, d, a, b, w10, 15, 0xffeff47du);
115 MD5STEP(MD5I, b, c, d, a, w1, 21, 0x85845dd1u);
116 MD5STEP(MD5I, a, b, c, d, w8, 6, 0x6fa87e4fu);
117 MD5STEP(MD5I, d, a, b, c, w15, 10, 0xfe2ce6e0u);
118 MD5STEP(MD5I, c, d, a, b, w6, 15, 0xa3014314u);
119 MD5STEP(MD5I, b, c, d, a, w13, 21, 0x4e0811a1u);
120 MD5STEP(MD5I, a, b, c, d, w4, 6, 0xf7537e82u);
121 MD5STEP(MD5I, d, a, b, c, w11, 10, 0xbd3af235u);
122 MD5STEP(MD5I, c, d, a, b, w2, 15, 0x2ad7d2bbu);
123 MD5STEP(MD5I, b, c, d, a, w9, 21, 0xeb86d391u);
124
125 st[0] = a + 0x67452301u;
126 st[1] = b + 0xefcdab89u;
127 st[2] = c + 0x98badcfeu;
128 st[3] = d + 0x10325476u;
129}
130
131static size_t salt_of(slice in, uint8_t *salt) {
132 size_t n = in.l;
133 if (n && in.p[n - 1] == '\n') {
134 n--;
135 }
136 if (n && in.p[n - 1] == '\r') {
137 n--;
138 }
139 aoc_assert(n, "empty door id");
140 aoc_assert(n <= SALTMAX, "door id too long");
141 for (size_t i = 0; i < n; i++) {
142 aoc_assert((in.p[i] >= 'a' && in.p[i] <= 'z') ||
143 (in.p[i] >= '0' && in.p[i] <= '9'),
144 "bad door id");
145 }
146 memcpy(salt, in.p, n);
147 return n;
148}
149
150static char hexdig(uint32_t v) {
151 return (char)(v < 10 ? '0' + (int)v : 'a' + (int)(v - 10));
152}
153
154/* Build blk = salt + decimal(1), padded to one MD5 block. */
155static size_t block_init(uint8_t *blk, const uint8_t *salt, size_t saltlen) {
156 size_t len = saltlen + 1;
157 size_t i;
158 memcpy(blk, salt, saltlen);
159 blk[saltlen] = '1';
160 for (i = len; i < 56; i++) {
161 blk[i] = 0;
162 }
163 blk[len] = 0x80;
164 blk[56] = (uint8_t)(len * 8);
165 blk[57] = (uint8_t)((len * 8) >> 8);
166 blk[58] = (uint8_t)((len * 8) >> 16);
167 blk[59] = (uint8_t)((len * 8) >> 24);
168 blk[60] = 0;
169 blk[61] = 0;
170 blk[62] = 0;
171 blk[63] = 0;
172 return len;
173}
174
175/* Patch the padding of blk after the payload length changed. */
176static void block_repad(uint8_t *blk, size_t len) {
177 size_t i;
178 for (i = len; i < 56; i++) {
179 blk[i] = 0;
180 }
181 blk[len] = 0x80;
182 blk[56] = (uint8_t)(len * 8);
183 blk[57] = (uint8_t)((len * 8) >> 8);
184 blk[58] = (uint8_t)((len * 8) >> 16);
185 blk[59] = (uint8_t)((len * 8) >> 24);
186 blk[60] = 0;
187 blk[61] = 0;
188 blk[62] = 0;
189 blk[63] = 0;
190}
191
192/* Bump the decimal suffix of blk (digits start at saltlen). Returns
193 * the new payload length when the digit count grew, else 0.
194 */
195static size_t bump(uint8_t *blk, size_t saltlen, size_t ndig) {
196 size_t d = saltlen + ndig - 1;
197 while (blk[d] == '9') {
198 blk[d] = '0';
199 if (d == saltlen) {
200 blk[saltlen] = '1';
201 return saltlen + ndig + 1;
202 }
203 d--;
204 }
205 blk[d]++;
206 return 0;
207}
208
209static slice solve(slice input, int positional) {
210 uint8_t salt[SALTMAX], blk[64];
211 size_t saltlen = salt_of(input, salt), ndig = 1;
212 char pw[8] = {0};
213 size_t found = 0;
214 block_init(blk, salt, saltlen);
215 blk[saltlen] = '0';
216 /* Ten consecutive indices share every suffix digit except the last.
217 * Carry and padding work happens once per batch; the straight-line
218 * trials keep both passwords inside the instrumented work budget. */
219#define TRIAL(digit_) \
220 do { \
221 uint32_t st[4]; \
222 blk[saltlen + ndig - 1] = (uint8_t)('0' + (digit_)); \
223 md5_64(blk, st); \
224 if ((st[0] & 0x00f0ffffu) == 0) { \
225 uint32_t digit = (st[0] >> 16) & 15u; \
226 if (!positional) \
227 pw[found++] = hexdig(digit); \
228 else if (digit < 8 && !pw[digit]) { \
229 pw[digit] = hexdig((st[0] >> 28) & 15u); \
230 found++; \
231 } \
232 if (found == 8) \
233 return slice_from_text(pw, 8); \
234 } \
235 } while (0)
236 for (uint32_t n = 0; n < MAXIDX; n += 10) {
237 TRIAL(0);
238 TRIAL(1);
239 TRIAL(2);
240 TRIAL(3);
241 TRIAL(4);
242 TRIAL(5);
243 TRIAL(6);
244 TRIAL(7);
245 TRIAL(8);
246 TRIAL(9);
247 size_t grown = bump(blk, saltlen, ndig);
248 if (grown) {
249 ndig++;
250 block_repad(blk, grown);
251 }
252 }
253#undef TRIAL
254 aoc_assert(0, "no password in search budget");
255}
256
257slice part1(slice input) {
258 return solve(input, 0);
259}
260
261slice part2(slice input) {
262 return solve(input, 1);
263}
264
265const struct aoc_method aoc_methods[] = {
266 {0, 0},
267};aoc.h
1#ifndef AOC_H
2#define AOC_H
3
4#include <stdarg.h>
5#include <stddef.h>
6#include <stdint.h>
7#include <stdlib.h>
8#include <string.h>
9
10/* The only required boundary between infra and a solution.
11 * `input` is read-only and is not owned by the solution.
12 * The returned slice is allocated with malloc. It is the only
13 * block still live when the function returns. Infra copies it
14 * and then frees it.
15 */
16typedef struct {
17 uint8_t *p;
18 size_t l;
19} slice;
20
21/* p is null and l is 0. Infra uses this when a run has no output. */
22static const slice empty_slice = {0};
23
24typedef slice (*aoc_fn)(slice);
25
26/* One named method. The name is a C identifier, at most 31
27 * characters, and it is the URL suffix: /YYYY/D/P/<name>.
28 * estimate and span are examples, not a fixed list. A day
29 * exports as many as it wants. The array ends with {0, 0}.
30 * part1 and part2 are not entries in this list.
31 */
32struct aoc_method {
33 const char *name;
34 aoc_fn fn;
35};
36
37slice part1(slice input);
38slice part2(slice input);
39
40extern const struct aoc_method aoc_methods[];
41
42/* Provided by the runtime. Records msg and returns. */
43void aoc_fail(const char *msg);
44
45/* Stops the run when cond is false and reports msg. */
46_Noreturn void aoc_assert_fail(const char *msg);
47#ifndef aoc_assert
48#define aoc_assert(cond, msg) \
49 do { \
50 if (!(cond)) { \
51 aoc_assert_fail(msg); \
52 } \
53 } while (0)
54#endif
55
56/* Decimal text of a uint64_t is at most 20 digits. A sign and a
57 * little spare fit here. Size a number buffer from this.
58 */
59enum { AOC_I64_TEXT = 32 };
60
61/* Decimal digits of v. No sign. d has room for 20 digits. */
62static inline char *aoc_u64_text(char *d, uint64_t v) {
63 char tmp[AOC_I64_TEXT];
64 char *end = tmp + AOC_I64_TEXT;
65 char *p = end;
66 size_t n;
67 do {
68 *--p = (char)('0' + (v % 10ull));
69 v /= 10ull;
70 } while (v);
71 n = (size_t)(end - p);
72 memcpy(d, p, n);
73 return d + n;
74}
75
76/* Decimal digits of v. The minimum int64_t is not negated. */
77static inline char *aoc_i64_text(char *d, int64_t v) {
78 uint64_t u;
79 if (v < 0) {
80 *d++ = '-';
81 u = (uint64_t)(-(v + 1)) + 1ull;
82 } else {
83 u = (uint64_t)v;
84 }
85 return aoc_u64_text(d, u);
86}
87
88/* n values, one space between them. The author knows the order. */
89static inline char *aoc_u64s(char *d, const uint64_t *v, size_t n) {
90 size_t i;
91 for (i = 0; i < n; i++) {
92 if (i) {
93 *d++ = ' ';
94 }
95 d = aoc_u64_text(d, v[i]);
96 }
97 return d;
98}
99
100static inline char *aoc_i64s(char *d, const int64_t *v, size_t n) {
101 size_t i;
102 for (i = 0; i < n; i++) {
103 if (i) {
104 *d++ = ' ';
105 }
106 d = aoc_i64_text(d, v[i]);
107 }
108 return d;
109}
110
111static inline char *aoc_ints(char *d, const int *v, size_t n) {
112 size_t i;
113 for (i = 0; i < n; i++) {
114 if (i) {
115 *d++ = ' ';
116 }
117 d = aoc_i64_text(d, (int64_t)v[i]);
118 }
119 return d;
120}
121
122/* Write fmt at buf. Return the cursor for the next call.
123 * %d takes int. %i takes int64_t. %u takes uint64_t.
124 * %s takes a C string. %% is a percent sign.
125 * A literal run is memcpy.
126 * %D takes (int *, size_t). %I takes (int64_t *, size_t).
127 * %U takes (uint64_t *, size_t). One space between values.
128 */
129static inline char *aoc_vprintf(const char *fmt, char *buf, va_list ap) {
130 while (*fmt) {
131 const char *lit = fmt;
132 size_t n;
133 while (*fmt && *fmt != '%') {
134 fmt++;
135 }
136 n = (size_t)(fmt - lit);
137 if (n) {
138 memcpy(buf, lit, n);
139 buf += n;
140 }
141 if (*fmt != '%') {
142 break;
143 }
144 fmt++;
145 if (*fmt == '%') {
146 *buf++ = '%';
147 fmt++;
148 continue;
149 }
150 if (*fmt == 's') {
151 const char *s = va_arg(ap, const char *);
152 n = strlen(s);
153 if (n) {
154 memcpy(buf, s, n);
155 buf += n;
156 }
157 fmt++;
158 continue;
159 }
160 if (*fmt == 'd') {
161 buf = aoc_i64_text(buf, (int64_t)va_arg(ap, int));
162 fmt++;
163 continue;
164 }
165 if (*fmt == 'i') {
166 buf = aoc_i64_text(buf, va_arg(ap, int64_t));
167 fmt++;
168 continue;
169 }
170 if (*fmt == 'u') {
171 buf = aoc_u64_text(buf, va_arg(ap, uint64_t));
172 fmt++;
173 continue;
174 }
175 if (*fmt == 'D') {
176 const int *v = va_arg(ap, int *);
177 buf = aoc_ints(buf, v, va_arg(ap, size_t));
178 fmt++;
179 continue;
180 }
181 if (*fmt == 'I') {
182 const int64_t *v = va_arg(ap, int64_t *);
183 buf = aoc_i64s(buf, v, va_arg(ap, size_t));
184 fmt++;
185 continue;
186 }
187 if (*fmt == 'U') {
188 const uint64_t *v = va_arg(ap, uint64_t *);
189 buf = aoc_u64s(buf, v, va_arg(ap, size_t));
190 fmt++;
191 continue;
192 }
193 aoc_assert(0, "bad format");
194 }
195 return buf;
196}
197
198static inline char *aoc_printf(const char *fmt, char *buf, ...) {
199 va_list ap;
200 va_start(ap, buf);
201 buf = aoc_vprintf(fmt, buf, ap);
202 va_end(ap);
203 return buf;
204}
205
206/* Copy n bytes of text into a malloc'd slice. */
207static inline slice slice_from_text(const char *s, size_t n) {
208 uint8_t *p = malloc(n);
209 aoc_assert(p, "out of memory");
210 if (n) {
211 memcpy(p, s, n);
212 }
213 return (slice){p, n};
214}
215
216/* Decimal text of v, allocated at AOC_I64_TEXT. The minimum
217 * int64_t is not negated. slice.l is the bytes written.
218 */
219static inline slice slice_from_i64(int64_t v) {
220 char tmp[AOC_I64_TEXT];
221 char *d;
222 uint8_t *p;
223 size_t n;
224 d = aoc_printf("%i", tmp, v);
225 n = (size_t)(d - tmp);
226 p = malloc(AOC_I64_TEXT);
227 aoc_assert(p, "out of memory");
228 memcpy(p, tmp, n);
229 return (slice){p, n};
230}
231
232/* Parse one decimal slice into *out. A leading '-' is allowed.
233 * Returns 1 on success, 0 for invalid text or int64_t overflow.
234 */
235static inline int slice_to_i64(slice s, int64_t *out) {
236 size_t i = 0;
237 int neg = 0;
238 uint64_t u = 0;
239 if (!s.p || s.l == 0 || !out) {
240 return 0;
241 }
242 if (s.p[0] == '-') {
243 neg = 1;
244 i = 1;
245 if (s.l == 1) {
246 return 0;
247 }
248 }
249 for (; i < s.l; i++) {
250 uint8_t c = s.p[i];
251 if (c < '0' || c > '9') {
252 return 0;
253 }
254 uint64_t digit = (uint64_t)(c - '0');
255 uint64_t limit = (uint64_t)INT64_MAX + (uint64_t)neg;
256 if (u > (limit - digit) / 10u) {
257 return 0;
258 }
259 u = u * 10u + digit;
260 }
261 if (neg) {
262 *out = u == (uint64_t)INT64_MAX + 1u ? INT64_MIN : -(int64_t)u;
263 } else {
264 *out = (int64_t)u;
265 }
266 return 1;
267}
268
269#endifThe aha moment
Eight letters in the local door ID, eight letters in the password. This could look like a quick job right up until the loop produces nothing for a million attempts. The input's shortness was no help in estimating the wait. Each candidate is the ID followed by a decimal index, starting at zero. Five leading hexadecimal zeroes specify 20 digest bits; treating MD5 outputs as uniformly distributed, roughly one candidate in 16⁵, or 1,048,576, qualifies. Now the silence has an explanation.
Part 1 needs eight such hits, so a reasonable first estimate is about 8.4 million hashes. This is an estimate of waiting time, not a bound. The local input's eighth hit occurs at index 7,777,889. A loop over consecutive integers is therefore a sensible plan, provided each iteration is cheap. A hash that almost starts with five zeroes gives us no useful direction for choosing the next index. There is no distance to the answer that we can follow downhill.
The door opens onto another door. This time a rare five-zero hash can arrive and give us… nothing. Its sixth digit selects a position, and 8 through f are invalid. Even a valid position is useless if already filled. The seventh digit supplies the value, but only the first hit for a position counts. Keep scanning indices in order and resist replacing an old character with a shiny new hit.
Seven characters filled, one blank stubbornly blinking: is something broken? With one position left, only one of the sixteen sixth-digit values helps. With k positions left, the expected wait is 16/k qualifying hashes. Filling all eight therefore takes about 16 × (1 + 1/2 + … + 1/8), or 43.5 qualifying hashes on average: roughly 45.6 million MD5 computations. Progress naturally slows as the password fills. The local input is luckier, finishing at index 25,651,067 after 30 qualifying hashes. A little probability helps us distinguish an ordinary wait from a bug.
Once this estimate tells us where the time goes, optimize the repeated work. Test the digest's leading bits directly instead of formatting every digest as hexadecimal text. Reuse the decimal index buffer. Here the implementation goes further: ten consecutive candidates share almost all their message preparation, and the MD5 rounds are unrolled. These changes make each trial cheaper; they do not reduce the number of trials required by the puzzle. Repeatedly hashing a digest, or key stretching, belongs to day 14 and would change this puzzle's answer.
The implementation accepts door IDs of at most 32 lowercase letters or digits and searches indices below 30,000,000. That covers both measured local passwords but is below the probabilistic average for part 2, so some otherwise legitimate IDs will be explicitly refused when the search is exhausted. Every candidate fits one MD5 block. This much hashing can still exceed the deployed CPU limit even when it fits the separate Wasm work budget; the search cap is not a timing guarantee.
See also
Categories for 2015–2024 adapted from u/Boojum’s 500 Stars: A Categorization and Mega-Guide ↗. A day can belong to several categories. Tags from 2025 onward are our additions.
Try your input
One POST, one reply. Your input is not saved.