]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blame - src/js/index.js
Derivation Path errors are detected.
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / index.js
CommitLineData
ebd8d4e8
IC
1(function() {
2
3 var mnemonic = new Mnemonic("english");
3e0ed16a 4 var seed = null
ebd8d4e8
IC
5 var bip32RootKey = null;
6 var bip32ExtendedKey = null;
1759e5e8 7 var network = bitcoin.networks.bitcoin;
ebd8d4e8
IC
8 var addressRowTemplate = $("#address-row-template");
9
700901cd
IC
10 var showIndex = true;
11 var showAddress = true;
12 var showPrivKey = true;
13
ebd8d4e8
IC
14 var phraseChangeTimeoutEvent = null;
15
16 var DOM = {};
d6cedc94
IC
17 DOM.network = $(".network");
18 DOM.phraseNetwork = $("#network-phrase");
ebd8d4e8 19 DOM.phrase = $(".phrase");
1abcc511 20 DOM.passphrase = $(".passphrase");
ebd8d4e8 21 DOM.generate = $(".generate");
3e0ed16a 22 DOM.seed = $(".seed");
ebd8d4e8
IC
23 DOM.rootKey = $(".root-key");
24 DOM.extendedPrivKey = $(".extended-priv-key");
25 DOM.extendedPubKey = $(".extended-pub-key");
d6cedc94
IC
26 DOM.bip32tab = $("#bip32-tab");
27 DOM.bip44tab = $("#bip44-tab");
28 DOM.bip32panel = $("#bip32");
29 DOM.bip44panel = $("#bip44");
ebd8d4e8
IC
30 DOM.bip32path = $("#bip32-path");
31 DOM.bip44path = $("#bip44-path");
32 DOM.bip44purpose = $("#bip44 .purpose");
33 DOM.bip44coin = $("#bip44 .coin");
34 DOM.bip44account = $("#bip44 .account");
35 DOM.bip44change = $("#bip44 .change");
36 DOM.strength = $(".strength");
37 DOM.addresses = $(".addresses");
38 DOM.rowsToAdd = $(".rows-to-add");
39 DOM.more = $(".more");
40 DOM.feedback = $(".feedback");
41 DOM.tab = $(".derivation-type a");
42 DOM.indexToggle = $(".index-toggle");
43 DOM.addressToggle = $(".address-toggle");
44 DOM.privateKeyToggle = $(".private-key-toggle");
45
ebd8d4e8
IC
46 function init() {
47 // Events
d6cedc94 48 DOM.network.on("change", networkChanged);
a19a5498
IC
49 DOM.phrase.on("input", delayedPhraseChanged);
50 DOM.passphrase.on("input", delayedPhraseChanged);
ebd8d4e8
IC
51 DOM.generate.on("click", generateClicked);
52 DOM.more.on("click", showMore);
38523d36
IC
53 DOM.bip32path.on("input", delayedPhraseChanged);
54 DOM.bip44purpose.on("input", delayedPhraseChanged);
55 DOM.bip44coin.on("input", delayedPhraseChanged);
56 DOM.bip44account.on("input", delayedPhraseChanged);
57 DOM.bip44change.on("input", delayedPhraseChanged);
58 DOM.tab.on("click", delayedPhraseChanged);
ebd8d4e8
IC
59 DOM.indexToggle.on("click", toggleIndexes);
60 DOM.addressToggle.on("click", toggleAddresses);
61 DOM.privateKeyToggle.on("click", togglePrivateKeys);
62 disableForms();
63 hidePending();
64 hideValidationError();
7f15cb6e 65 populateNetworkSelect();
ebd8d4e8
IC
66 }
67
68 // Event handlers
69
d6cedc94 70 function networkChanged(e) {
7a995731 71 var network = e.target.value;
7f15cb6e 72 networks[network].onSelect();
d6cedc94
IC
73 delayedPhraseChanged();
74 }
75
ebd8d4e8
IC
76 function delayedPhraseChanged() {
77 hideValidationError();
78 showPending();
79 if (phraseChangeTimeoutEvent != null) {
80 clearTimeout(phraseChangeTimeoutEvent);
81 }
82 phraseChangeTimeoutEvent = setTimeout(phraseChanged, 400);
83 }
84
85 function phraseChanged() {
86 showPending();
87 hideValidationError();
88 // Get the mnemonic phrase
89 var phrase = DOM.phrase.val();
1abcc511 90 var passphrase = DOM.passphrase.val();
ebd8d4e8
IC
91 var errorText = findPhraseErrors(phrase);
92 if (errorText) {
93 showValidationError(errorText);
94 return;
95 }
96 // Get the derivation path
38523d36
IC
97 var derivationPath = getDerivationPath();
98 var errorText = findDerivationPathErrors(derivationPath);
ebd8d4e8
IC
99 if (errorText) {
100 showValidationError(errorText);
101 return;
102 }
103 // Calculate and display
1abcc511 104 calcBip32Seed(phrase, passphrase, derivationPath);
ebd8d4e8
IC
105 displayBip32Info();
106 hidePending();
107 }
108
109 function generateClicked() {
110 clearDisplay();
111 showPending();
112 setTimeout(function() {
113 var phrase = generateRandomPhrase();
114 if (!phrase) {
115 return;
116 }
117 phraseChanged();
118 }, 50);
119 }
120
ebd8d4e8 121 function toggleIndexes() {
700901cd 122 showIndex = !showIndex;
ebd8d4e8
IC
123 $("td.index span").toggleClass("invisible");
124 }
125
126 function toggleAddresses() {
700901cd 127 showAddress = !showAddress;
ebd8d4e8
IC
128 $("td.address span").toggleClass("invisible");
129 }
130
131 function togglePrivateKeys() {
700901cd 132 showPrivKey = !showPrivKey;
ebd8d4e8
IC
133 $("td.privkey span").toggleClass("invisible");
134 }
135
136 // Private methods
137
138 function generateRandomPhrase() {
139 if (!hasStrongRandom()) {
140 var errorText = "This browser does not support strong randomness";
141 showValidationError(errorText);
142 return;
143 }
144 var numWords = parseInt(DOM.strength.val());
ebd8d4e8
IC
145 var strength = numWords / 3 * 32;
146 var words = mnemonic.generate(strength);
147 DOM.phrase.val(words);
148 return words;
149 }
150
1abcc511 151 function calcBip32Seed(phrase, passphrase, path) {
3e0ed16a 152 seed = mnemonic.toSeed(phrase, passphrase);
1759e5e8 153 bip32RootKey = bitcoin.HDNode.fromSeedHex(seed, network);
ebd8d4e8
IC
154 bip32ExtendedKey = bip32RootKey;
155 // Derive the key from the path
156 var pathBits = path.split("/");
157 for (var i=0; i<pathBits.length; i++) {
158 var bit = pathBits[i];
159 var index = parseInt(bit);
160 if (isNaN(index)) {
161 continue;
162 }
163 var hardened = bit[bit.length-1] == "'";
164 if (hardened) {
165 bip32ExtendedKey = bip32ExtendedKey.deriveHardened(index);
166 }
167 else {
168 bip32ExtendedKey = bip32ExtendedKey.derive(index);
169 }
170 }
171 }
172
173 function showValidationError(errorText) {
174 DOM.feedback
175 .text(errorText)
176 .show();
177 }
178
179 function hideValidationError() {
180 DOM.feedback
181 .text("")
182 .hide();
183 }
184
185 function findPhraseErrors(phrase) {
186 // TODO make this right
187 // Preprocess the words
783981de 188 phrase = mnemonic.normalizeString(phrase);
ebd8d4e8
IC
189 var parts = phrase.split(" ");
190 var proper = [];
191 for (var i=0; i<parts.length; i++) {
192 var part = parts[i];
193 if (part.length > 0) {
194 // TODO check that lowercasing is always valid to do
195 proper.push(part.toLowerCase());
196 }
197 }
198 // TODO some levenstein on the words
199 var properPhrase = proper.join(' ');
200 // Check the words are valid
201 var isValid = mnemonic.check(properPhrase);
202 if (!isValid) {
203 return "Invalid mnemonic";
204 }
205 return false;
206 }
207
38523d36
IC
208 function getDerivationPath() {
209 if (DOM.bip44tab.hasClass("active")) {
210 var purpose = parseIntNoNaN(DOM.bip44purpose.val(), 44);
211 var coin = parseIntNoNaN(DOM.bip44coin.val(), 0);
212 var account = parseIntNoNaN(DOM.bip44account.val(), 0);
213 var change = parseIntNoNaN(DOM.bip44change.val(), 0);
214 var path = "m/";
215 path += purpose + "'/";
216 path += coin + "'/";
217 path += account + "'/";
218 path += change;
219 DOM.bip44path.val(path);
220 var derivationPath = DOM.bip44path.val();
221 console.log("Using derivation path from BIP44 tab: " + derivationPath);
222 return derivationPath;
223 }
224 else if (DOM.bip32tab.hasClass("active")) {
225 var derivationPath = DOM.bip32path.val();
226 console.log("Using derivation path from BIP32 tab: " + derivationPath);
227 return derivationPath;
228 }
229 else {
230 console.log("Unknown derivation path");
231 }
232 }
233
ebd8d4e8 234 function findDerivationPathErrors(path) {
30c9e79d
IC
235 // TODO is not perfect but is better than nothing
236 // Inspired by
237 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
238 // and
239 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
240 var maxDepth = 255; // TODO verify this!!
241 var maxIndexValue = Math.pow(2, 31); // TODO verify this!!
242 if (path[0] != "m") {
243 return "First character must be 'm'";
244 }
245 if (path.length > 1) {
246 if (path[1] != "/") {
247 return "Separator must be '/'";
248 }
249 var indexes = path.split("/");
250 if (indexes.length > maxDepth) {
251 return "Derivation depth is " + indexes.length + ", must be less than " + maxDepth;
252 }
253 for (var depth = 1; depth<indexes.length; depth++) {
254 var index = indexes[depth];
255 var invalidChars = index.replace(/^[0-9]+'?$/g, "")
256 if (invalidChars.length > 0) {
257 return "Invalid characters " + invalidChars + " found at depth " + depth;
258 }
259 var indexValue = parseInt(index.replace("'", ""));
260 if (isNaN(depth)) {
261 return "Invalid number at depth " + depth;
262 }
263 if (indexValue > maxIndexValue) {
264 return "Value of " + indexValue + " at depth " + depth + " must be less than " + maxIndexValue;
265 }
266 }
267 }
ebd8d4e8
IC
268 return false;
269 }
270
271 function displayBip32Info() {
272 // Display the key
3e0ed16a 273 DOM.seed.val(seed);
ebd8d4e8
IC
274 var rootKey = bip32RootKey.toBase58();
275 DOM.rootKey.val(rootKey);
276 var extendedPrivKey = bip32ExtendedKey.toBase58();
277 DOM.extendedPrivKey.val(extendedPrivKey);
278 var extendedPubKey = bip32ExtendedKey.toBase58(false);
279 DOM.extendedPubKey.val(extendedPubKey);
280 // Display the addresses and privkeys
281 clearAddressesList();
282 displayAddresses(0, 20);
283 }
284
285 function displayAddresses(start, total) {
286 for (var i=0; i<total; i++) {
a8c45487
IC
287 var index = i + start;
288 new TableRow(index);
ebd8d4e8
IC
289 }
290 }
291
a8c45487
IC
292 function TableRow(index) {
293
294 function init() {
295 calculateValues();
296 }
297
298 function calculateValues() {
299 setTimeout(function() {
300 var key = bip32ExtendedKey.derive(index);
301 var address = key.getAddress().toString();
302 var privkey = key.privKey.toWIF(network);
38523d36
IC
303 var indexText = getDerivationPath() + "/" + index;
304 addAddressToList(indexText, address, privkey);
a8c45487
IC
305 }, 50)
306 }
307
308 init();
309
310 }
311
ebd8d4e8
IC
312 function showMore() {
313 var start = DOM.addresses.children().length;
314 var rowsToAdd = parseInt(DOM.rowsToAdd.val());
315 if (isNaN(rowsToAdd)) {
316 rowsToAdd = 20;
317 DOM.rowsToAdd.val("20");
318 }
319 if (rowsToAdd > 200) {
320 var msg = "Generating " + rowsToAdd + " rows could take a while. ";
321 msg += "Do you want to continue?";
322 if (!confirm(msg)) {
323 return;
324 }
325 }
ebd8d4e8 326 displayAddresses(start, rowsToAdd);
ebd8d4e8
IC
327 }
328
329 function clearDisplay() {
330 clearAddressesList();
331 clearKey();
332 hideValidationError();
333 }
334
335 function clearAddressesList() {
336 DOM.addresses.empty();
337 }
338
339 function clearKey() {
340 DOM.rootKey.val("");
341 DOM.extendedPrivKey.val("");
342 DOM.extendedPubKey.val("");
343 }
344
38523d36 345 function addAddressToList(indexText, address, privkey) {
ebd8d4e8 346 var row = $(addressRowTemplate.html());
700901cd
IC
347 // Elements
348 var indexCell = row.find(".index span");
349 var addressCell = row.find(".address span");
350 var privkeyCell = row.find(".privkey span");
351 // Content
ae30fed8 352 indexCell.text(indexText);
700901cd
IC
353 addressCell.text(address);
354 privkeyCell.text(privkey);
355 // Visibility
356 if (!showIndex) {
357 indexCell.addClass("invisible");
358 }
359 if (!showAddress) {
360 addressCell.addClass("invisible");
361 }
362 if (!showPrivKey) {
6d628db7 363 privkeyCell.addClass("invisible");
700901cd 364 }
ebd8d4e8
IC
365 DOM.addresses.append(row);
366 }
367
368 function hasStrongRandom() {
369 return 'crypto' in window && window['crypto'] !== null;
370 }
371
372 function disableForms() {
373 $("form").on("submit", function(e) {
374 e.preventDefault();
375 });
376 }
377
ebd8d4e8
IC
378 function parseIntNoNaN(val, defaultVal) {
379 var v = parseInt(val);
380 if (isNaN(v)) {
381 return defaultVal;
382 }
383 return v;
384 }
385
386 function showPending() {
387 DOM.feedback
388 .text("Calculating...")
389 .show();
390 }
391
392 function hidePending() {
393 DOM.feedback
394 .text("")
395 .hide();
396 }
397
7f15cb6e
IC
398 function populateNetworkSelect() {
399 for (var i=0; i<networks.length; i++) {
400 var network = networks[i];
401 var option = $("<option>");
402 option.attr("value", i);
403 option.text(network.name);
404 DOM.phraseNetwork.append(option);
405 }
406 }
407
408 var networks = [
409 {
7a995731
IC
410 name: "Bitcoin",
411 onSelect: function() {
1759e5e8 412 network = bitcoin.networks.bitcoin;
7a995731 413 DOM.bip44coin.val(0);
7a995731
IC
414 },
415 },
7f15cb6e 416 {
7a995731
IC
417 name: "Bitcoin Testnet",
418 onSelect: function() {
1759e5e8 419 network = bitcoin.networks.testnet;
7a995731 420 DOM.bip44coin.val(1);
7a995731
IC
421 },
422 },
7f15cb6e 423 {
7a995731
IC
424 name: "Litecoin",
425 onSelect: function() {
1759e5e8 426 network = bitcoin.networks.litecoin;
7a995731
IC
427 DOM.bip44coin.val(2);
428 },
429 },
7f15cb6e 430 {
7a995731
IC
431 name: "Dogecoin",
432 onSelect: function() {
1759e5e8 433 network = bitcoin.networks.dogecoin;
7a995731
IC
434 DOM.bip44coin.val(3);
435 },
436 },
e3a9508c
IC
437 {
438 name: "ShadowCash",
439 onSelect: function() {
440 network = bitcoin.networks.shadow;
441 DOM.bip44coin.val(35);
442 },
443 },
444 {
445 name: "ShadowCash Testnet",
446 onSelect: function() {
447 network = bitcoin.networks.shadowtn;
448 DOM.bip44coin.val(1);
449 },
450 },
a3baa26e
IC
451 {
452 name: "Viacoin",
453 onSelect: function() {
454 network = bitcoin.networks.viacoin;
455 DOM.bip44coin.val(14);
456 },
457 },
458 {
459 name: "Viacoin Testnet",
460 onSelect: function() {
461 network = bitcoin.networks.viacointestnet;
462 DOM.bip44coin.val(1);
463 },
464 },
465 {
466 name: "Jumbucks",
467 onSelect: function() {
468 network = bitcoin.networks.jumbucks;
469 DOM.bip44coin.val(26);
470 },
471 },
5c434a8a
CM
472 {
473 name: "CLAM",
474 onSelect: function() {
475 network = bitcoin.networks.clam;
476 DOM.bip44coin.val(23);
477 },
478 },
7f15cb6e 479 ]
7a995731 480
ebd8d4e8
IC
481 init();
482
483})();