1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//! multibase codec
//!
//! encodes and decodes multibase-encoded strings (prefix + encoded data).
//! supports base58btc (z prefix) and base32lower (b prefix).
//!
//! see: https://github.com/multiformats/multibase
const std = @import("std");
/// multibase encoding types
pub const Encoding = enum {
base58btc, // z prefix
base32lower, // b prefix
pub fn fromPrefix(prefix: u8) ?Encoding {
return switch (prefix) {
'z' => .base58btc,
'b' => .base32lower,
else => null,
};
}
};
/// decode a multibase string, returning the raw bytes
/// the first character is the encoding prefix
pub fn decode(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
if (input.len == 0) return error.EmptyInput;
const encoding = Encoding.fromPrefix(input[0]) orelse return error.UnsupportedEncoding;
return switch (encoding) {
.base58btc => try base58btc.decode(allocator, input[1..]),
.base32lower => try base32lower.decode(allocator, input[1..]),
};
}
/// encode raw bytes to a multibase string with the given encoding
pub fn encode(allocator: std.mem.Allocator, encoding: Encoding, data: []const u8) ![]u8 {
return switch (encoding) {
.base58btc => try base58btc.encode(allocator, data),
.base32lower => try base32lower.encode(allocator, data),
};
}
/// base58btc codec (bitcoin alphabet)
pub const base58btc = struct {
/// bitcoin base58 alphabet
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
/// reverse lookup table
const decode_table = blk: {
var table: [256]i8 = @splat(-1);
for (alphabet, 0..) |c, i| {
table[c] = @intCast(i);
}
break :blk table;
};
/// encode bytes to base58btc string with 'z' multibase prefix
pub fn encode(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
// count leading zero bytes → leading '1's
var leading_zeros: usize = 0;
for (input) |b| {
if (b != 0) break;
leading_zeros += 1;
}
if (input.len == 0 or leading_zeros == input.len) {
// all zeros (or empty)
const result = try allocator.alloc(u8, 1 + leading_zeros);
result[0] = 'z'; // multibase prefix
@memset(result[1..], '1');
return result;
}
// load bytes into big integer (big-endian)
var acc: std.math.big.int.Managed = try .init(allocator);
defer acc.deinit();
for (input) |b| {
try acc.shiftLeft(&acc, 8);
try acc.addScalar(&acc, b);
}
// repeatedly divide by 58 to extract base58 digits
var digits: std.ArrayList(u8) = .empty;
defer digits.deinit(allocator);
var divisor: std.math.big.int.Managed = try .initSet(allocator, @as(u64, 58));
defer divisor.deinit();
var quotient: std.math.big.int.Managed = try .init(allocator);
defer quotient.deinit();
var remainder: std.math.big.int.Managed = try .init(allocator);
defer remainder.deinit();
while (!acc.toConst().eqlZero()) {
try quotient.divFloor(&remainder, &acc, &divisor);
const digit: usize = @intCast(remainder.toConst().toInt(u64) catch 0);
try digits.append(allocator, alphabet[digit]);
try acc.copy(quotient.toConst());
}
// result: 'z' prefix + leading '1's + reversed digits
const total_len = 1 + leading_zeros + digits.items.len;
const result = try allocator.alloc(u8, total_len);
result[0] = 'z'; // multibase prefix
@memset(result[1..][0..leading_zeros], '1');
// digits were accumulated LSB-first, reverse into result
const digit_slice = result[1 + leading_zeros ..];
for (digits.items, 0..) |d, i| {
digit_slice[digits.items.len - 1 - i] = d;
}
return result;
}
/// decode base58btc string to bytes
pub fn decode(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
if (input.len == 0) return &.{};
// count leading zeros (1s in base58)
var leading_zeros: usize = 0;
for (input) |c| {
if (c != '1') break;
leading_zeros += 1;
}
// decode using big integer arithmetic
var acc: std.math.big.int.Managed = try .init(allocator);
defer acc.deinit();
var multiplier: std.math.big.int.Managed = try .initSet(allocator, @as(u64, 58));
defer multiplier.deinit();
var temp: std.math.big.int.Managed = try .init(allocator);
defer temp.deinit();
for (input) |c| {
const digit = decode_table[c];
if (digit < 0) return error.InvalidCharacter;
try temp.mul(&acc, &multiplier);
try acc.copy(temp.toConst());
try acc.addScalar(&acc, @as(u8, @intCast(digit)));
}
// convert big int to bytes (big-endian)
const limbs = acc.toConst().limbs;
const limb_count = acc.len();
var byte_count: usize = 0;
if (limb_count > 0 and !acc.toConst().eqlZero()) {
byte_count = (acc.toConst().bitCountAbs() + 7) / 8;
}
const result = try allocator.alloc(u8, leading_zeros + byte_count);
@memset(result[0..leading_zeros], 0);
// convert limbs to big-endian bytes
if (byte_count > 0) {
const output_slice = result[leading_zeros..];
var pos: usize = byte_count;
for (limbs[0..limb_count]) |limb| {
const limb_bytes = @sizeOf(@TypeOf(limb));
for (0..@min(limb_bytes, pos)) |i| {
pos -= 1;
output_slice[pos] = @truncate(limb >> @intCast(i * 8));
}
}
}
return result;
}
};
/// base32lower codec (RFC 4648, lowercase, no padding)
pub const base32lower = struct {
const alphabet = "abcdefghijklmnopqrstuvwxyz234567";
const decode_table = blk: {
var table: [256]i8 = @splat(-1);
for (alphabet, 0..) |c, i| {
table[c] = @intCast(i);
}
break :blk table;
};
/// encode bytes to base32lower string with 'b' multibase prefix
pub fn encode(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
if (input.len == 0) {
const result = try allocator.alloc(u8, 1);
result[0] = 'b';
return result;
}
// base32: 5 bytes → 8 chars
const out_len = (input.len * 8 + 4) / 5; // ceil(bits / 5)
const result = try allocator.alloc(u8, 1 + out_len);
result[0] = 'b'; // multibase prefix
const pos = 1 + encodeInto(result[1..], input);
return result[0..pos];
}
/// encode input into out (no multibase prefix), 5-byte chunks at a time.
/// out must have room for ceil(input.len * 8 / 5) bytes; returns bytes written.
pub fn encodeInto(out: []u8, input: []const u8) usize {
var pos: usize = 0;
var i: usize = 0;
while (i + 5 <= input.len) : (i += 5) {
const chunk = input[i..][0..5].*;
const v: @Vector(8, u5) = @bitCast(@byteSwap(@as(u40, @bitCast(chunk))));
inline for (0..8) |j| {
out[pos + j] = alphabet[v[7 - j]];
}
pos += 8;
}
var bit_buf: u32 = 0;
var bits: u5 = 0;
for (input[i..]) |byte| {
bit_buf = (bit_buf << 8) | byte;
bits += 8;
while (bits >= 5) {
bits -= 5;
out[pos] = alphabet[@as(u5, @truncate(bit_buf >> bits))];
pos += 1;
}
}
if (bits > 0) {
out[pos] = alphabet[@as(u5, @truncate(bit_buf << (5 - bits)))];
pos += 1;
}
return pos;
}
/// decode base32lower string (no multibase prefix) to bytes
pub fn decode(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
if (input.len == 0) return &.{};
const out_len = input.len * 5 / 8;
const result = try allocator.alloc(u8, out_len);
errdefer allocator.free(result);
var bit_buf: u32 = 0;
var bits: u4 = 0;
var pos: usize = 0;
for (input) |c| {
if (c == '=') break; // stop at padding
const digit = decode_table[c];
if (digit < 0) return error.InvalidCharacter;
bit_buf = (bit_buf << 5) | @as(u32, @intCast(digit));
bits += 5;
if (bits >= 8) {
bits -= 8;
result[pos] = @truncate(bit_buf >> bits);
pos += 1;
}
}
return allocator.realloc(result, pos);
}
};
// === tests ===
test "base58btc decode" {
const alloc = std.testing.allocator;
// "abc" in base58btc
// "abc" = 0x616263 = 6382179
// expected base58btc: "ZiCa" (verify with external tool)
{
const decoded = try base58btc.decode(alloc, "ZiCa");
defer alloc.free(decoded);
try std.testing.expectEqualSlices(u8, "abc", decoded);
}
}
test "base58btc decode with leading zeros" {
const alloc = std.testing.allocator;
// leading 1s map to leading zero bytes
{
const decoded = try base58btc.decode(alloc, "111");
defer alloc.free(decoded);
try std.testing.expectEqual(@as(usize, 3), decoded.len);
try std.testing.expectEqualSlices(u8, &[_]u8{ 0, 0, 0 }, decoded);
}
}
test "multibase decode base58btc" {
const alloc = std.testing.allocator;
// z prefix = base58btc
{
const decoded = try decode(alloc, "zZiCa");
defer alloc.free(decoded);
try std.testing.expectEqualSlices(u8, "abc", decoded);
}
}
test "base58btc decode real multibase key - secp256k1" {
const alloc = std.testing.allocator;
const multicodec = @import("multicodec.zig");
// from a real DID document: zQ3shXjHeiBuRCKmM36cuYnm7YEMzhGnCmCyW92sRJ9pribSF
// this is a compressed secp256k1 public key with multicodec prefix
const key = "zQ3shXjHeiBuRCKmM36cuYnm7YEMzhGnCmCyW92sRJ9pribSF";
const decoded = try decode(alloc, key);
defer alloc.free(decoded);
// should decode to 35 bytes: 2-byte multicodec prefix (0xe7 0x01 varint) + 33-byte compressed key
try std.testing.expectEqual(@as(usize, 35), decoded.len);
// first two bytes should be secp256k1-pub multicodec prefix (0xe7 0x01 varint for 231)
try std.testing.expectEqual(@as(u8, 0xe7), decoded[0]);
try std.testing.expectEqual(@as(u8, 0x01), decoded[1]);
// parse with multicodec
const parsed = try multicodec.parsePublicKey(decoded);
try std.testing.expectEqual(multicodec.KeyType.secp256k1, parsed.key_type);
try std.testing.expectEqual(@as(usize, 33), parsed.raw.len);
// compressed point prefix should be 0x02 or 0x03
try std.testing.expect(parsed.raw[0] == 0x02 or parsed.raw[0] == 0x03);
}
test "base58btc encode-decode round-trip" {
const alloc = std.testing.allocator;
{
const original = "abc";
const encoded = try base58btc.encode(alloc, original);
defer alloc.free(encoded);
// should have 'z' prefix
try std.testing.expectEqual(@as(u8, 'z'), encoded[0]);
const decoded = try decode(alloc, encoded);
defer alloc.free(decoded);
try std.testing.expectEqualSlices(u8, original, decoded);
}
// round-trip with leading zeros
{
const original = &[_]u8{ 0, 0, 0x01 };
const encoded = try base58btc.encode(alloc, original);
defer alloc.free(encoded);
const decoded = try decode(alloc, encoded);
defer alloc.free(decoded);
try std.testing.expectEqualSlices(u8, original, decoded);
}
}
test "base32lower encode-decode round-trip" {
const alloc = std.testing.allocator;
{
const original = "hello";
const encoded = try base32lower.encode(alloc, original);
defer alloc.free(encoded);
try std.testing.expectEqual(@as(u8, 'b'), encoded[0]);
const decoded = try decode(alloc, encoded);
defer alloc.free(decoded);
try std.testing.expectEqualSlices(u8, original, decoded);
}
// empty
{
const encoded = try base32lower.encode(alloc, "");
defer alloc.free(encoded);
try std.testing.expectEqualStrings("b", encoded);
}
}
test "base32lower decode bafyrei prefix" {
const alloc = std.testing.allocator;
// CIDv1 dag-cbor sha2-256 always starts with "bafyrei" in base32lower
// "bafyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454"
const input = "afyreie5cvv4h45feadgeuwhbcutmh6t2ceseocckahdoe6uat64zmz454";
const decoded = try base32lower.decode(alloc, input);
defer alloc.free(decoded);
// CIDv1: version=1(0x01), codec=dag-cbor(0x71), hash=sha2-256(0x12), len=32(0x20)
try std.testing.expectEqual(@as(u8, 0x01), decoded[0]);
try std.testing.expectEqual(@as(u8, 0x71), decoded[1]);
try std.testing.expectEqual(@as(u8, 0x12), decoded[2]);
try std.testing.expectEqual(@as(u8, 0x20), decoded[3]);
}