-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathbase-convert.ts
More file actions
204 lines (178 loc) · 7.6 KB
/
base-convert.ts
File metadata and controls
204 lines (178 loc) · 7.6 KB
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
import { formatError } from './error.js';
export enum BaseConverterCreationError {
tooLong = 'Base converter creation error: an alphabet may be no longer than 254 characters.',
ambiguousCharacter = 'Base converter creation error: a character code may only appear once in a single alphabet.',
}
export enum BaseConversionError {
unknownCharacter = 'Base conversion error: encountered an unknown character for this alphabet.',
}
export type BaseConverter = {
decode: (source: string) => Uint8Array | string;
encode: (input: Uint8Array) => string;
};
/**
* Create a {@link BaseConverter}, exposing methods for encoding and decoding
* `Uint8Array`s using bitcoin-style padding: each leading zero in the input is
* replaced with the zero-index character of the `alphabet`, then the remainder
* of the input is encoded as a large number in the specified alphabet.
*
* For example, using the alphabet `01`, the input `[0, 15]` is encoded `01111`
* – a single `0` represents the leading padding, followed by the base2 encoded
* `0x1111` (15). With the same alphabet, the input `[0, 0, 255]` is encoded
* `0011111111` - only two `0` characters are required to represent both
* leading zeros, followed by the base2 encoded `0x11111111` (255).
*
* **This is not compatible with `RFC 3548`'s `Base16`, `Base32`, or `Base64`.**
*
* If the alphabet is malformed, this method returns the error as a `string`.
*
* @param alphabet - an ordered string that maps each index to a character,
* e.g. `0123456789`.
*/
// Algorithm from the `base-x` implementation (derived from the original Satoshi implementation): https://github.com/cryptocoinjs/base-x
export const createBaseConverter = (
alphabet: string,
): BaseConverter | string => {
const undefinedValue = 255;
const uint8ArrayBase = 256;
if (alphabet.length >= undefinedValue)
return formatError(
BaseConverterCreationError.tooLong,
`Alphabet length: ${alphabet.length}`,
);
const alphabetMap = new Uint8Array(uint8ArrayBase).fill(undefinedValue);
// eslint-disable-next-line functional/no-loop-statements, functional/no-let, no-plusplus
for (let index = 0; index < alphabet.length; index++) {
const characterCode = alphabet.charCodeAt(index);
if (alphabetMap[characterCode] !== undefinedValue) {
return formatError(
BaseConverterCreationError.ambiguousCharacter,
`Ambiguous character: ${alphabetMap[characterCode]}`,
);
}
// eslint-disable-next-line functional/no-expression-statements, functional/immutable-data
alphabetMap[characterCode] = index;
}
const base = alphabet.length;
const paddingCharacter = alphabet.charAt(0);
const factor = Math.log(base) / Math.log(uint8ArrayBase);
const inverseFactor = Math.log(uint8ArrayBase) / Math.log(base);
return {
// eslint-disable-next-line complexity
decode: (input: string) => {
if (input.length === 0) return Uint8Array.of();
const firstNonZeroIndex = input
.split('')
.findIndex((character) => character !== paddingCharacter);
if (firstNonZeroIndex === -1) {
return new Uint8Array(input.length);
}
const requiredLength = Math.floor(
(input.length - firstNonZeroIndex) * factor + 1,
);
const decoded = new Uint8Array(requiredLength);
/* eslint-disable functional/no-let, functional/no-expression-statements */
let nextByte = firstNonZeroIndex;
let remainingBytes = 0;
// eslint-disable-next-line functional/no-loop-statements
while (input[nextByte] !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
let carry = alphabetMap[input.charCodeAt(nextByte)]!;
if (carry === undefinedValue)
return formatError(
BaseConversionError.unknownCharacter,
`Unknown character: "${input[nextByte]}".`,
);
let digit = 0;
// eslint-disable-next-line functional/no-loop-statements
for (
let steps = requiredLength - 1;
(carry !== 0 || digit < remainingBytes) && steps !== -1;
// eslint-disable-next-line no-plusplus
steps--, digit++
) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
carry += Math.floor(base * decoded[steps]!);
// eslint-disable-next-line functional/immutable-data
decoded[steps] = Math.floor(carry % uint8ArrayBase);
carry = Math.floor(carry / uint8ArrayBase);
}
remainingBytes = digit;
// eslint-disable-next-line no-plusplus
nextByte++;
}
/* eslint-enable functional/no-let, functional/no-expression-statements */
const firstNonZeroResultDigit = decoded.findIndex((value) => value !== 0);
const bin = new Uint8Array(
firstNonZeroIndex + (requiredLength - firstNonZeroResultDigit),
);
// eslint-disable-next-line functional/no-expression-statements
bin.set(decoded.slice(firstNonZeroResultDigit), firstNonZeroIndex);
return bin;
},
// eslint-disable-next-line complexity
encode: (input: Uint8Array) => {
if (input.length === 0) return '';
const firstNonZeroIndex = input.findIndex((byte) => byte !== 0);
if (firstNonZeroIndex === -1) {
return paddingCharacter.repeat(input.length);
}
const requiredLength = Math.floor(
(input.length - firstNonZeroIndex) * inverseFactor + 1,
);
const encoded = new Uint8Array(requiredLength);
/* eslint-disable functional/no-let, functional/no-expression-statements */
let nextByte = firstNonZeroIndex;
let remainingBytes = 0;
// eslint-disable-next-line functional/no-loop-statements
while (nextByte !== input.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
let carry = input[nextByte]!;
let digit = 0;
// eslint-disable-next-line functional/no-loop-statements
for (
let steps = requiredLength - 1;
(carry !== 0 || digit < remainingBytes) && steps !== -1;
// eslint-disable-next-line no-plusplus
steps--, digit++
) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
carry += Math.floor(uint8ArrayBase * encoded[steps]!);
// eslint-disable-next-line functional/immutable-data
encoded[steps] = Math.floor(carry % base);
carry = Math.floor(carry / base);
}
remainingBytes = digit;
// eslint-disable-next-line no-plusplus
nextByte++;
}
/* eslint-enable functional/no-let, functional/no-expression-statements */
const firstNonZeroResultDigit = encoded.findIndex((value) => value !== 0);
const padding = paddingCharacter.repeat(firstNonZeroIndex);
return encoded
.slice(firstNonZeroResultDigit)
.reduce((all, digit) => all + alphabet.charAt(digit), padding);
},
};
};
export const bitcoinBase58Alphabet =
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const base58 = createBaseConverter(bitcoinBase58Alphabet) as BaseConverter;
/**
* Convert a bitcoin-style base58-encoded string to a Uint8Array.
*
* For the reverse, see {@link binToBase58}.
*
* See {@link createBaseConverter} for format details.
* @param input - a valid base58-encoded string to decode
*/
export const base58ToBin = base58.decode;
/**
* Convert a Uint8Array to a bitcoin-style base58-encoded string.
*
* For the reverse, see {@link base58ToBin}.
*
* See {@link createBaseConverter} for format details.
* @param input - the Uint8Array to base58 encode
*/
export const binToBase58 = base58.encode;