]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blame_incremental - src/js/index.js
Add Slimcoin
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / index.js
... / ...
CommitLineData
1(function() {
2
3 // mnemonics is populated as required by getLanguage
4 var mnemonics = { "english": new Mnemonic("english") };
5 var mnemonic = mnemonics["english"];
6 var seed = null;
7 var bip32RootKey = null;
8 var bip32ExtendedKey = null;
9 var network = bitcoin.networks.bitcoin;
10 var addressRowTemplate = $("#address-row-template");
11
12 var showIndex = true;
13 var showAddress = true;
14 var showPubKey = true;
15 var showPrivKey = true;
16 var showQr = false;
17
18 var entropyChangeTimeoutEvent = null;
19 var phraseChangeTimeoutEvent = null;
20 var rootKeyChangedTimeoutEvent = null;
21
22 var generationProcesses = [];
23
24 var DOM = {};
25 DOM.network = $(".network");
26 DOM.bip32Client = $("#bip32-client");
27 DOM.phraseNetwork = $("#network-phrase");
28 DOM.useEntropy = $(".use-entropy");
29 DOM.entropyContainer = $(".entropy-container");
30 DOM.entropy = $(".entropy");
31 DOM.entropyFiltered = DOM.entropyContainer.find(".filtered");
32 DOM.entropyType = DOM.entropyContainer.find(".type");
33 DOM.entropyStrength = DOM.entropyContainer.find(".strength");
34 DOM.entropyEventCount = DOM.entropyContainer.find(".event-count");
35 DOM.entropyBits = DOM.entropyContainer.find(".bits");
36 DOM.entropyBitsPerEvent = DOM.entropyContainer.find(".bits-per-event");
37 DOM.entropyWordCount = DOM.entropyContainer.find(".word-count");
38 DOM.entropyBinary = DOM.entropyContainer.find(".binary");
39 DOM.entropyMnemonicLength = DOM.entropyContainer.find(".mnemonic-length");
40 DOM.phrase = $(".phrase");
41 DOM.passphrase = $(".passphrase");
42 DOM.generateContainer = $(".generate-container");
43 DOM.generate = $(".generate");
44 DOM.seed = $(".seed");
45 DOM.rootKey = $(".root-key");
46 DOM.extendedPrivKey = $(".extended-priv-key");
47 DOM.extendedPubKey = $(".extended-pub-key");
48 DOM.bip32tab = $("#bip32-tab");
49 DOM.bip44tab = $("#bip44-tab");
50 DOM.bip32panel = $("#bip32");
51 DOM.bip44panel = $("#bip44");
52 DOM.bip32path = $("#bip32-path");
53 DOM.bip44path = $("#bip44-path");
54 DOM.bip44purpose = $("#bip44 .purpose");
55 DOM.bip44coin = $("#bip44 .coin");
56 DOM.bip44account = $("#bip44 .account");
57 DOM.bip44accountXprv = $("#bip44 .account-xprv");
58 DOM.bip44accountXpub = $("#bip44 .account-xpub");
59 DOM.bip44change = $("#bip44 .change");
60 DOM.generatedStrength = $(".generate-container .strength");
61 DOM.hardenedAddresses = $(".hardened-addresses");
62 DOM.addresses = $(".addresses");
63 DOM.rowsToAdd = $(".rows-to-add");
64 DOM.more = $(".more");
65 DOM.feedback = $(".feedback");
66 DOM.tab = $(".derivation-type a");
67 DOM.indexToggle = $(".index-toggle");
68 DOM.addressToggle = $(".address-toggle");
69 DOM.publicKeyToggle = $(".public-key-toggle");
70 DOM.privateKeyToggle = $(".private-key-toggle");
71 DOM.languages = $(".languages a");
72 DOM.qrContainer = $(".qr-container");
73 DOM.qrHider = DOM.qrContainer.find(".qr-hider");
74 DOM.qrImage = DOM.qrContainer.find(".qr-image");
75 DOM.qrHint = DOM.qrContainer.find(".qr-hint");
76 DOM.showQrEls = $("[data-show-qr]");
77
78 function init() {
79 // Events
80 DOM.network.on("change", networkChanged);
81 DOM.bip32Client.on("change", bip32ClientChanged);
82 DOM.useEntropy.on("change", setEntropyVisibility);
83 DOM.entropy.on("input", delayedEntropyChanged);
84 DOM.entropyMnemonicLength.on("change", entropyChanged);
85 DOM.phrase.on("input", delayedPhraseChanged);
86 DOM.passphrase.on("input", delayedPhraseChanged);
87 DOM.generate.on("click", generateClicked);
88 DOM.more.on("click", showMore);
89 DOM.rootKey.on("input", delayedRootKeyChanged);
90 DOM.bip32path.on("input", calcForDerivationPath);
91 DOM.bip44purpose.on("input", calcForDerivationPath);
92 DOM.bip44coin.on("input", calcForDerivationPath);
93 DOM.bip44account.on("input", calcForDerivationPath);
94 DOM.bip44change.on("input", calcForDerivationPath);
95 DOM.tab.on("shown.bs.tab", calcForDerivationPath);
96 DOM.hardenedAddresses.on("change", calcForDerivationPath);
97 DOM.indexToggle.on("click", toggleIndexes);
98 DOM.addressToggle.on("click", toggleAddresses);
99 DOM.publicKeyToggle.on("click", togglePublicKeys);
100 DOM.privateKeyToggle.on("click", togglePrivateKeys);
101 DOM.languages.on("click", languageChanged);
102 setQrEvents(DOM.showQrEls);
103 disableForms();
104 hidePending();
105 hideValidationError();
106 populateNetworkSelect();
107 populateClientSelect();
108 }
109
110 // Event handlers
111
112 function networkChanged(e) {
113 var networkIndex = e.target.value;
114 networks[networkIndex].onSelect();
115 if (seed != null) {
116 phraseChanged();
117 }
118 else {
119 rootKeyChanged();
120 }
121 }
122
123 function bip32ClientChanged(e) {
124 var clientIndex = DOM.bip32Client.val();
125 if (clientIndex == "custom") {
126 DOM.bip32path.prop("readonly", false);
127 }
128 else {
129 DOM.bip32path.prop("readonly", true);
130 clients[clientIndex].onSelect();
131 if (seed != null) {
132 phraseChanged();
133 }
134 else {
135 rootKeyChanged();
136 }
137 }
138 }
139
140 function setEntropyVisibility() {
141 if (isUsingOwnEntropy()) {
142 DOM.entropyContainer.removeClass("hidden");
143 DOM.generateContainer.addClass("hidden");
144 DOM.phrase.prop("readonly", true);
145 DOM.entropy.focus();
146 entropyChanged();
147 }
148 else {
149 DOM.entropyContainer.addClass("hidden");
150 DOM.generateContainer.removeClass("hidden");
151 DOM.phrase.prop("readonly", false);
152 hidePending();
153 }
154 }
155
156 function delayedPhraseChanged() {
157 hideValidationError();
158 showPending();
159 if (phraseChangeTimeoutEvent != null) {
160 clearTimeout(phraseChangeTimeoutEvent);
161 }
162 phraseChangeTimeoutEvent = setTimeout(phraseChanged, 400);
163 }
164
165 function phraseChanged() {
166 showPending();
167 hideValidationError();
168 setMnemonicLanguage();
169 // Get the mnemonic phrase
170 var phrase = DOM.phrase.val();
171 var errorText = findPhraseErrors(phrase);
172 if (errorText) {
173 showValidationError(errorText);
174 return;
175 }
176 // Calculate and display
177 var passphrase = DOM.passphrase.val();
178 calcBip32RootKeyFromSeed(phrase, passphrase);
179 calcForDerivationPath();
180 hidePending();
181 }
182
183 function delayedEntropyChanged() {
184 hideValidationError();
185 showPending();
186 if (entropyChangeTimeoutEvent != null) {
187 clearTimeout(entropyChangeTimeoutEvent);
188 }
189 entropyChangeTimeoutEvent = setTimeout(entropyChanged, 400);
190 }
191
192 function entropyChanged() {
193 // If blank entropy, clear mnemonic, addresses, errors
194 if (DOM.entropy.val().trim().length == 0) {
195 clearDisplay();
196 clearEntropyFeedback();
197 DOM.phrase.val("");
198 showValidationError("Blank entropy");
199 return;
200 }
201 // Get the current phrase to detect changes
202 var phrase = DOM.phrase.val();
203 // Set the phrase from the entropy
204 setMnemonicFromEntropy();
205 // Recalc addresses if the phrase has changed
206 var newPhrase = DOM.phrase.val();
207 if (newPhrase != phrase) {
208 if (newPhrase.length == 0) {
209 clearDisplay();
210 }
211 else {
212 phraseChanged();
213 }
214 }
215 else {
216 hidePending();
217 }
218 }
219
220 function delayedRootKeyChanged() {
221 // Warn if there is an existing mnemonic or passphrase.
222 if (DOM.phrase.val().length > 0 || DOM.passphrase.val().length > 0) {
223 if (!confirm("This will clear existing mnemonic and passphrase")) {
224 DOM.rootKey.val(bip32RootKey);
225 return
226 }
227 }
228 hideValidationError();
229 showPending();
230 // Clear existing mnemonic and passphrase
231 DOM.phrase.val("");
232 DOM.passphrase.val("");
233 seed = null;
234 if (rootKeyChangedTimeoutEvent != null) {
235 clearTimeout(rootKeyChangedTimeoutEvent);
236 }
237 rootKeyChangedTimeoutEvent = setTimeout(rootKeyChanged, 400);
238 }
239
240 function rootKeyChanged() {
241 showPending();
242 hideValidationError();
243 // Validate the root key TODO
244 var rootKeyBase58 = DOM.rootKey.val();
245 var errorText = validateRootKey(rootKeyBase58);
246 if (errorText) {
247 showValidationError(errorText);
248 return;
249 }
250 // Calculate and display
251 calcBip32RootKeyFromBase58(rootKeyBase58);
252 calcForDerivationPath();
253 }
254
255 function calcForDerivationPath() {
256 showPending();
257 clearAddressesList();
258 hideValidationError();
259 // Get the derivation path
260 var derivationPath = getDerivationPath();
261 var errorText = findDerivationPathErrors(derivationPath);
262 if (errorText) {
263 showValidationError(errorText);
264 return;
265 }
266 bip32ExtendedKey = calcBip32ExtendedKey(derivationPath);
267 if (bip44TabSelected()) {
268 displayBip44Info();
269 }
270 displayBip32Info();
271 hidePending();
272 }
273
274 function generateClicked() {
275 if (isUsingOwnEntropy()) {
276 return;
277 }
278 clearDisplay();
279 showPending();
280 setTimeout(function() {
281 setMnemonicLanguage();
282 var phrase = generateRandomPhrase();
283 if (!phrase) {
284 return;
285 }
286 phraseChanged();
287 }, 50);
288 }
289
290 function languageChanged() {
291 setTimeout(function() {
292 setMnemonicLanguage();
293 if (DOM.phrase.val().length > 0) {
294 var newPhrase = convertPhraseToNewLanguage();
295 DOM.phrase.val(newPhrase);
296 phraseChanged();
297 }
298 else {
299 DOM.generate.trigger("click");
300 }
301 }, 50);
302 }
303
304 function toggleIndexes() {
305 showIndex = !showIndex;
306 $("td.index span").toggleClass("invisible");
307 }
308
309 function toggleAddresses() {
310 showAddress = !showAddress;
311 $("td.address span").toggleClass("invisible");
312 }
313
314 function togglePublicKeys() {
315 showPubKey = !showPubKey;
316 $("td.pubkey span").toggleClass("invisible");
317 }
318
319 function togglePrivateKeys() {
320 showPrivKey = !showPrivKey;
321 $("td.privkey span").toggleClass("invisible");
322 }
323
324 // Private methods
325
326 function generateRandomPhrase() {
327 if (!hasStrongRandom()) {
328 var errorText = "This browser does not support strong randomness";
329 showValidationError(errorText);
330 return;
331 }
332 var numWords = parseInt(DOM.generatedStrength.val());
333 var strength = numWords / 3 * 32;
334 var words = mnemonic.generate(strength);
335 DOM.phrase.val(words);
336 return words;
337 }
338
339 function calcBip32RootKeyFromSeed(phrase, passphrase) {
340 seed = mnemonic.toSeed(phrase, passphrase);
341 bip32RootKey = bitcoin.HDNode.fromSeedHex(seed, network);
342 }
343
344 function calcBip32RootKeyFromBase58(rootKeyBase58) {
345 bip32RootKey = bitcoin.HDNode.fromBase58(rootKeyBase58, network);
346 }
347
348 function calcBip32ExtendedKey(path) {
349 // Check there's a root key to derive from
350 if (!bip32RootKey) {
351 return bip32RootKey;
352 }
353 var extendedKey = bip32RootKey;
354 // Derive the key from the path
355 var pathBits = path.split("/");
356 for (var i=0; i<pathBits.length; i++) {
357 var bit = pathBits[i];
358 var index = parseInt(bit);
359 if (isNaN(index)) {
360 continue;
361 }
362 var hardened = bit[bit.length-1] == "'";
363 var isPriv = "privKey" in extendedKey;
364 var invalidDerivationPath = hardened && !isPriv;
365 if (invalidDerivationPath) {
366 extendedKey = null;
367 }
368 else if (hardened) {
369 extendedKey = extendedKey.deriveHardened(index);
370 }
371 else {
372 extendedKey = extendedKey.derive(index);
373 }
374 }
375 return extendedKey
376 }
377
378 function showValidationError(errorText) {
379 DOM.feedback
380 .text(errorText)
381 .show();
382 }
383
384 function hideValidationError() {
385 DOM.feedback
386 .text("")
387 .hide();
388 }
389
390 function findPhraseErrors(phrase) {
391 // Preprocess the words
392 phrase = mnemonic.normalizeString(phrase);
393 var words = phraseToWordArray(phrase);
394 // Detect blank phrase
395 if (words.length == 0) {
396 return "Blank mnemonic";
397 }
398 // Check each word
399 for (var i=0; i<words.length; i++) {
400 var word = words[i];
401 var language = getLanguage();
402 if (WORDLISTS[language].indexOf(word) == -1) {
403 console.log("Finding closest match to " + word);
404 var nearestWord = findNearestWord(word);
405 return word + " not in wordlist, did you mean " + nearestWord + "?";
406 }
407 }
408 // Check the words are valid
409 var properPhrase = wordArrayToPhrase(words);
410 var isValid = mnemonic.check(properPhrase);
411 if (!isValid) {
412 return "Invalid mnemonic";
413 }
414 return false;
415 }
416
417 function validateRootKey(rootKeyBase58) {
418 try {
419 bitcoin.HDNode.fromBase58(rootKeyBase58);
420 }
421 catch (e) {
422 return "Invalid root key";
423 }
424 return "";
425 }
426
427 function getDerivationPath() {
428 if (bip44TabSelected()) {
429 var purpose = parseIntNoNaN(DOM.bip44purpose.val(), 44);
430 var coin = parseIntNoNaN(DOM.bip44coin.val(), 0);
431 var account = parseIntNoNaN(DOM.bip44account.val(), 0);
432 var change = parseIntNoNaN(DOM.bip44change.val(), 0);
433 var path = "m/";
434 path += purpose + "'/";
435 path += coin + "'/";
436 path += account + "'/";
437 path += change;
438 DOM.bip44path.val(path);
439 var derivationPath = DOM.bip44path.val();
440 console.log("Using derivation path from BIP44 tab: " + derivationPath);
441 return derivationPath;
442 }
443 else if (bip32TabSelected()) {
444 var derivationPath = DOM.bip32path.val();
445 console.log("Using derivation path from BIP32 tab: " + derivationPath);
446 return derivationPath;
447 }
448 else {
449 console.log("Unknown derivation path");
450 }
451 }
452
453 function findDerivationPathErrors(path) {
454 // TODO is not perfect but is better than nothing
455 // Inspired by
456 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
457 // and
458 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
459 var maxDepth = 255; // TODO verify this!!
460 var maxIndexValue = Math.pow(2, 31); // TODO verify this!!
461 if (path[0] != "m") {
462 return "First character must be 'm'";
463 }
464 if (path.length > 1) {
465 if (path[1] != "/") {
466 return "Separator must be '/'";
467 }
468 var indexes = path.split("/");
469 if (indexes.length > maxDepth) {
470 return "Derivation depth is " + indexes.length + ", must be less than " + maxDepth;
471 }
472 for (var depth = 1; depth<indexes.length; depth++) {
473 var index = indexes[depth];
474 var invalidChars = index.replace(/^[0-9]+'?$/g, "")
475 if (invalidChars.length > 0) {
476 return "Invalid characters " + invalidChars + " found at depth " + depth;
477 }
478 var indexValue = parseInt(index.replace("'", ""));
479 if (isNaN(depth)) {
480 return "Invalid number at depth " + depth;
481 }
482 if (indexValue > maxIndexValue) {
483 return "Value of " + indexValue + " at depth " + depth + " must be less than " + maxIndexValue;
484 }
485 }
486 }
487 // Check root key exists or else derivation path is useless!
488 if (!bip32RootKey) {
489 return "No root key";
490 }
491 // Check no hardened derivation path when using xpub keys
492 var hardened = path.indexOf("'") > -1;
493 var isXpubkey = !("privKey" in bip32RootKey);
494 if (hardened && isXpubkey) {
495 return "Hardened derivation path is invalid with xpub key";
496 }
497 return false;
498 }
499
500 function displayBip44Info() {
501 // Get the derivation path for the account
502 var purpose = parseIntNoNaN(DOM.bip44purpose.val(), 44);
503 var coin = parseIntNoNaN(DOM.bip44coin.val(), 0);
504 var account = parseIntNoNaN(DOM.bip44account.val(), 0);
505 var path = "m/";
506 path += purpose + "'/";
507 path += coin + "'/";
508 path += account + "'/";
509 // Calculate the account extended keys
510 var accountExtendedKey = calcBip32ExtendedKey(path);
511 var accountXprv = accountExtendedKey.toBase58();
512 var accountXpub = accountExtendedKey.toBase58(false);
513 // Display the extended keys
514 DOM.bip44accountXprv.val(accountXprv);
515 DOM.bip44accountXpub.val(accountXpub);
516 }
517
518 function displayBip32Info() {
519 // Display the key
520 DOM.seed.val(seed);
521 var rootKey = bip32RootKey.toBase58();
522 DOM.rootKey.val(rootKey);
523 var xprvkeyB58 = "NA";
524 if (bip32ExtendedKey.privKey) {
525 xprvkeyB58 = bip32ExtendedKey.toBase58();
526 }
527 var extendedPrivKey = xprvkeyB58;
528 DOM.extendedPrivKey.val(extendedPrivKey);
529 var extendedPubKey = bip32ExtendedKey.toBase58(false);
530 DOM.extendedPubKey.val(extendedPubKey);
531 // Display the addresses and privkeys
532 clearAddressesList();
533 displayAddresses(0, 20);
534 }
535
536 function displayAddresses(start, total) {
537 generationProcesses.push(new (function() {
538
539 var rows = [];
540
541 this.stop = function() {
542 for (var i=0; i<rows.length; i++) {
543 rows[i].shouldGenerate = false;
544 }
545 }
546
547 for (var i=0; i<total; i++) {
548 var index = i + start;
549 rows.push(new TableRow(index));
550 }
551
552 })());
553 }
554
555 function TableRow(index) {
556
557 var self = this;
558 this.shouldGenerate = true;
559 var useHardenedAddresses = DOM.hardenedAddresses.prop("checked");
560
561 function init() {
562 calculateValues();
563 }
564
565 function calculateValues() {
566 setTimeout(function() {
567 if (!self.shouldGenerate) {
568 return;
569 }
570 var key = "";
571 if (useHardenedAddresses) {
572 key = bip32ExtendedKey.deriveHardened(index);
573 }
574 else {
575 key = bip32ExtendedKey.derive(index);
576 }
577 var address = key.getAddress().toString();
578 var privkey = "NA";
579 if (key.privKey) {
580 privkey = key.privKey.toWIF(network);
581 }
582 var pubkey = key.pubKey.toHex();
583 var indexText = getDerivationPath() + "/" + index;
584 if (useHardenedAddresses) {
585 indexText = indexText + "'";
586 }
587 // Ethereum values are different
588 if (networks[DOM.network.val()].name == "Ethereum") {
589 var privKeyBuffer = key.privKey.d.toBuffer();
590 privkey = privKeyBuffer.toString('hex');
591 var addressBuffer = ethUtil.privateToAddress(privKeyBuffer);
592 var hexAddress = addressBuffer.toString('hex');
593 var checksumAddress = ethUtil.toChecksumAddress(hexAddress);
594 address = ethUtil.addHexPrefix(checksumAddress);
595 }
596 addAddressToList(indexText, address, pubkey, privkey);
597 }, 50)
598 }
599
600 init();
601
602 }
603
604 function showMore() {
605 var start = DOM.addresses.children().length;
606 var rowsToAdd = parseInt(DOM.rowsToAdd.val());
607 if (isNaN(rowsToAdd)) {
608 rowsToAdd = 20;
609 DOM.rowsToAdd.val("20");
610 }
611 if (rowsToAdd > 200) {
612 var msg = "Generating " + rowsToAdd + " rows could take a while. ";
613 msg += "Do you want to continue?";
614 if (!confirm(msg)) {
615 return;
616 }
617 }
618 displayAddresses(start, rowsToAdd);
619 }
620
621 function clearDisplay() {
622 clearAddressesList();
623 clearKey();
624 hideValidationError();
625 }
626
627 function clearAddressesList() {
628 DOM.addresses.empty();
629 stopGenerating();
630 }
631
632 function stopGenerating() {
633 while (generationProcesses.length > 0) {
634 var generation = generationProcesses.shift();
635 generation.stop();
636 }
637 }
638
639 function clearKey() {
640 DOM.rootKey.val("");
641 DOM.extendedPrivKey.val("");
642 DOM.extendedPubKey.val("");
643 }
644
645 function addAddressToList(indexText, address, pubkey, privkey) {
646 var row = $(addressRowTemplate.html());
647 // Elements
648 var indexCell = row.find(".index span");
649 var addressCell = row.find(".address span");
650 var pubkeyCell = row.find(".pubkey span");
651 var privkeyCell = row.find(".privkey span");
652 // Content
653 indexCell.text(indexText);
654 addressCell.text(address);
655 pubkeyCell.text(pubkey);
656 privkeyCell.text(privkey);
657 // Visibility
658 if (!showIndex) {
659 indexCell.addClass("invisible");
660 }
661 if (!showAddress) {
662 addressCell.addClass("invisible");
663 }
664 if (!showPubKey) {
665 pubkeyCell.addClass("invisible");
666 }
667 if (!showPrivKey) {
668 privkeyCell.addClass("invisible");
669 }
670 DOM.addresses.append(row);
671 var rowShowQrEls = row.find("[data-show-qr]");
672 setQrEvents(rowShowQrEls);
673 }
674
675 function hasStrongRandom() {
676 return 'crypto' in window && window['crypto'] !== null;
677 }
678
679 function disableForms() {
680 $("form").on("submit", function(e) {
681 e.preventDefault();
682 });
683 }
684
685 function parseIntNoNaN(val, defaultVal) {
686 var v = parseInt(val);
687 if (isNaN(v)) {
688 return defaultVal;
689 }
690 return v;
691 }
692
693 function showPending() {
694 DOM.feedback
695 .text("Calculating...")
696 .show();
697 }
698
699 function findNearestWord(word) {
700 var language = getLanguage();
701 var words = WORDLISTS[language];
702 var minDistance = 99;
703 var closestWord = words[0];
704 for (var i=0; i<words.length; i++) {
705 var comparedTo = words[i];
706 if (comparedTo.indexOf(word) == 0) {
707 return comparedTo;
708 }
709 var distance = Levenshtein.get(word, comparedTo);
710 if (distance < minDistance) {
711 closestWord = comparedTo;
712 minDistance = distance;
713 }
714 }
715 return closestWord;
716 }
717
718 function hidePending() {
719 DOM.feedback
720 .text("")
721 .hide();
722 }
723
724 function populateNetworkSelect() {
725 for (var i=0; i<networks.length; i++) {
726 var network = networks[i];
727 var option = $("<option>");
728 option.attr("value", i);
729 option.text(network.name);
730 DOM.phraseNetwork.append(option);
731 }
732 }
733
734 function populateClientSelect() {
735 for (var i=0; i<clients.length; i++) {
736 var client = clients[i];
737 var option = $("<option>");
738 option.attr("value", i);
739 option.text(client.name);
740 DOM.bip32Client.append(option);
741 }
742 }
743
744 function getLanguage() {
745 var defaultLanguage = "english";
746 // Try to get from existing phrase
747 var language = getLanguageFromPhrase();
748 // Try to get from url if not from phrase
749 if (language.length == 0) {
750 language = getLanguageFromUrl();
751 }
752 // Default to English if no other option
753 if (language.length == 0) {
754 language = defaultLanguage;
755 }
756 return language;
757 }
758
759 function getLanguageFromPhrase(phrase) {
760 // Check if how many words from existing phrase match a language.
761 var language = "";
762 if (!phrase) {
763 phrase = DOM.phrase.val();
764 }
765 if (phrase.length > 0) {
766 var words = phraseToWordArray(phrase);
767 var languageMatches = {};
768 for (l in WORDLISTS) {
769 // Track how many words match in this language
770 languageMatches[l] = 0;
771 for (var i=0; i<words.length; i++) {
772 var wordInLanguage = WORDLISTS[l].indexOf(words[i]) > -1;
773 if (wordInLanguage) {
774 languageMatches[l]++;
775 }
776 }
777 // Find languages with most word matches.
778 // This is made difficult due to commonalities between Chinese
779 // simplified vs traditional.
780 var mostMatches = 0;
781 var mostMatchedLanguages = [];
782 for (var l in languageMatches) {
783 var numMatches = languageMatches[l];
784 if (numMatches > mostMatches) {
785 mostMatches = numMatches;
786 mostMatchedLanguages = [l];
787 }
788 else if (numMatches == mostMatches) {
789 mostMatchedLanguages.push(l);
790 }
791 }
792 }
793 if (mostMatchedLanguages.length > 0) {
794 // Use first language and warn if multiple detected
795 language = mostMatchedLanguages[0];
796 if (mostMatchedLanguages.length > 1) {
797 console.warn("Multiple possible languages");
798 console.warn(mostMatchedLanguages);
799 }
800 }
801 }
802 return language;
803 }
804
805 function getLanguageFromUrl() {
806 for (var language in WORDLISTS) {
807 if (window.location.hash.indexOf(language) > -1) {
808 return language;
809 }
810 }
811 return "";
812 }
813
814 function setMnemonicLanguage() {
815 var language = getLanguage();
816 // Load the bip39 mnemonic generator for this language if required
817 if (!(language in mnemonics)) {
818 mnemonics[language] = new Mnemonic(language);
819 }
820 mnemonic = mnemonics[language];
821 }
822
823 function convertPhraseToNewLanguage() {
824 var oldLanguage = getLanguageFromPhrase();
825 var newLanguage = getLanguageFromUrl();
826 var oldPhrase = DOM.phrase.val();
827 var oldWords = phraseToWordArray(oldPhrase);
828 var newWords = [];
829 for (var i=0; i<oldWords.length; i++) {
830 var oldWord = oldWords[i];
831 var index = WORDLISTS[oldLanguage].indexOf(oldWord);
832 var newWord = WORDLISTS[newLanguage][index];
833 newWords.push(newWord);
834 }
835 newPhrase = wordArrayToPhrase(newWords);
836 return newPhrase;
837 }
838
839 // TODO look at jsbip39 - mnemonic.splitWords
840 function phraseToWordArray(phrase) {
841 var words = phrase.split(/\s/g);
842 var noBlanks = [];
843 for (var i=0; i<words.length; i++) {
844 var word = words[i];
845 if (word.length > 0) {
846 noBlanks.push(word);
847 }
848 }
849 return noBlanks;
850 }
851
852 // TODO look at jsbip39 - mnemonic.joinWords
853 function wordArrayToPhrase(words) {
854 var phrase = words.join(" ");
855 var language = getLanguageFromPhrase(phrase);
856 if (language == "japanese") {
857 phrase = words.join("\u3000");
858 }
859 return phrase;
860 }
861
862 function isUsingOwnEntropy() {
863 return DOM.useEntropy.prop("checked");
864 }
865
866 function setMnemonicFromEntropy() {
867 clearEntropyFeedback();
868 // Get entropy value
869 var entropyStr = DOM.entropy.val();
870 // Work out minimum base for entropy
871 var entropy = Entropy.fromString(entropyStr);
872 if (entropy.binaryStr.length == 0) {
873 return;
874 }
875 // Show entropy details
876 showEntropyFeedback(entropy);
877 // Use entropy hash if not using raw entropy
878 var bits = entropy.binaryStr;
879 var mnemonicLength = DOM.entropyMnemonicLength.val();
880 if (mnemonicLength != "raw") {
881 // Get bits by hashing entropy with SHA256
882 var hash = sjcl.hash.sha256.hash(entropy.cleanStr);
883 var hex = sjcl.codec.hex.fromBits(hash);
884 bits = BigInteger.parse(hex, 16).toString(2);
885 while (bits.length % 256 != 0) {
886 bits = "0" + bits;
887 }
888 // Truncate hash to suit number of words
889 mnemonicLength = parseInt(mnemonicLength);
890 var numberOfBits = 32 * mnemonicLength / 3;
891 bits = bits.substring(0, numberOfBits);
892 }
893 // Discard trailing entropy
894 var bitsToUse = Math.floor(bits.length / 32) * 32;
895 var start = bits.length - bitsToUse;
896 var binaryStr = bits.substring(start);
897 // Convert entropy string to numeric array
898 var entropyArr = [];
899 for (var i=0; i<binaryStr.length / 8; i++) {
900 var byteAsBits = binaryStr.substring(i*8, i*8+8);
901 var entropyByte = parseInt(byteAsBits, 2);
902 entropyArr.push(entropyByte)
903 }
904 // Convert entropy array to mnemonic
905 var phrase = mnemonic.toMnemonic(entropyArr);
906 // Set the mnemonic in the UI
907 DOM.phrase.val(phrase);
908 }
909
910 function clearEntropyFeedback() {
911 DOM.entropyStrength.text("...");
912 DOM.entropyType.text("");
913 DOM.entropyWordCount.text("0");
914 DOM.entropyEventCount.text("0");
915 DOM.entropyBitsPerEvent.text("0");
916 DOM.entropyBits.text("0");
917 DOM.entropyFiltered.html("&nbsp;");
918 DOM.entropyBinary.html("&nbsp;");
919 }
920
921 function showEntropyFeedback(entropy) {
922 var numberOfBits = entropy.binaryStr.length;
923 var strength = "extremely weak";
924 if (numberOfBits >= 64) {
925 strength = "very weak";
926 }
927 if (numberOfBits >= 96) {
928 strength = "weak";
929 }
930 if (numberOfBits >= 128) {
931 strength = "strong";
932 }
933 if (numberOfBits >= 160) {
934 strength = "very strong";
935 }
936 if (numberOfBits >= 192) {
937 strength = "extremely strong";
938 }
939 // If time to crack is less than one day, and password is considered
940 // strong or better based on the number of bits, rename strength to
941 // 'easily cracked'.
942 try {
943 var z = zxcvbn(entropy.base.parts.join(""));
944 var timeToCrack = z.crack_times_seconds.offline_fast_hashing_1e10_per_second;
945 if (timeToCrack < 86400 && entropy.binaryStr.length >= 128) {
946 strength = "easily cracked";
947 if (z.feedback.warning != "") {
948 strength = strength + " - " + z.feedback.warning;
949 };
950 }
951 }
952 catch (e) {
953 strength = "unknown";
954 console.log("Error detecting entropy strength with zxcvbn:");
955 console.log(e);
956 }
957 var entropyTypeStr = getEntropyTypeStr(entropy);
958 var wordCount = Math.floor(numberOfBits / 32) * 3;
959 var bitsPerEvent = entropy.bitsPerEvent.toFixed(2);
960 DOM.entropyFiltered.html(entropy.cleanHtml);
961 DOM.entropyType.text(entropyTypeStr);
962 DOM.entropyStrength.text(strength);
963 DOM.entropyEventCount.text(entropy.base.ints.length);
964 DOM.entropyBits.text(numberOfBits);
965 DOM.entropyWordCount.text(wordCount);
966 DOM.entropyBinary.text(entropy.binaryStr);
967 DOM.entropyBitsPerEvent.text(bitsPerEvent);
968 }
969
970 function getEntropyTypeStr(entropy) {
971 var typeStr = entropy.base.str;
972 // Add some detail if these are cards
973 if (entropy.base.asInt == 52) {
974 var cardDetail = []; // array of message strings
975 // Detect duplicates
976 var dupes = [];
977 var dupeTracker = {};
978 for (var i=0; i<entropy.base.parts.length; i++) {
979 var card = entropy.base.parts[i];
980 var cardUpper = card.toUpperCase();
981 if (cardUpper in dupeTracker) {
982 dupes.push(card);
983 }
984 dupeTracker[cardUpper] = true;
985 }
986 if (dupes.length > 0) {
987 var dupeWord = "duplicates";
988 if (dupes.length == 1) {
989 dupeWord = "duplicate";
990 }
991 var msg = dupes.length + " " + dupeWord + ": " + dupes.slice(0,3).join(" ");
992 if (dupes.length > 3) {
993 msg += "...";
994 }
995 cardDetail.push(msg);
996 }
997 // Detect full deck
998 var uniqueCards = [];
999 for (var uniqueCard in dupeTracker) {
1000 uniqueCards.push(uniqueCard);
1001 }
1002 if (uniqueCards.length == 52) {
1003 cardDetail.unshift("full deck");
1004 }
1005 // Detect missing cards
1006 var values = "A23456789TJQK";
1007 var suits = "CDHS";
1008 var missingCards = [];
1009 for (var i=0; i<suits.length; i++) {
1010 for (var j=0; j<values.length; j++) {
1011 var card = values[j] + suits[i];
1012 if (!(card in dupeTracker)) {
1013 missingCards.push(card);
1014 }
1015 }
1016 }
1017 // Display missing cards if six or less, ie clearly going for full deck
1018 if (missingCards.length > 0 && missingCards.length <= 6) {
1019 var msg = missingCards.length + " missing: " + missingCards.slice(0,3).join(" ");
1020 if (missingCards.length > 3) {
1021 msg += "...";
1022 }
1023 cardDetail.push(msg);
1024 }
1025 // Add card details to typeStr
1026 if (cardDetail.length > 0) {
1027 typeStr += " (" + cardDetail.join(", ") + ")";
1028 }
1029 }
1030 return typeStr;
1031 }
1032
1033 function setQrEvents(els) {
1034 els.on("mouseenter", createQr);
1035 els.on("mouseleave", destroyQr);
1036 els.on("click", toggleQr);
1037 }
1038
1039 function createQr(e) {
1040 var content = e.target.textContent || e.target.value;
1041 if (content) {
1042 var size = 130;
1043 DOM.qrImage.qrcode({width: size, height: size, text: content});
1044 if (!showQr) {
1045 DOM.qrHider.addClass("hidden");
1046 }
1047 else {
1048 DOM.qrHider.removeClass("hidden");
1049 }
1050 DOM.qrContainer.removeClass("hidden");
1051 }
1052 }
1053
1054 function destroyQr() {
1055 DOM.qrImage.text("");
1056 DOM.qrContainer.addClass("hidden");
1057 }
1058
1059 function toggleQr() {
1060 showQr = !showQr;
1061 DOM.qrHider.toggleClass("hidden");
1062 DOM.qrHint.toggleClass("hidden");
1063 }
1064
1065 function bip44TabSelected() {
1066 return DOM.bip44tab.hasClass("active");
1067 }
1068
1069 function bip32TabSelected() {
1070 return DOM.bip32tab.hasClass("active");
1071 }
1072
1073 var networks = [
1074 {
1075 name: "Bitcoin",
1076 onSelect: function() {
1077 network = bitcoin.networks.bitcoin;
1078 DOM.bip44coin.val(0);
1079 },
1080 },
1081 {
1082 name: "Bitcoin Testnet",
1083 onSelect: function() {
1084 network = bitcoin.networks.testnet;
1085 DOM.bip44coin.val(1);
1086 },
1087 },
1088 {
1089 name: "CLAM",
1090 onSelect: function() {
1091 network = bitcoin.networks.clam;
1092 DOM.bip44coin.val(23);
1093 },
1094 },
1095 {
1096 name: "Dogecoin",
1097 onSelect: function() {
1098 network = bitcoin.networks.dogecoin;
1099 DOM.bip44coin.val(3);
1100 },
1101 },
1102 {
1103 name: "DASH",
1104 onSelect: function() {
1105 network = bitcoin.networks.dash;
1106 DOM.bip44coin.val(5);
1107 },
1108 },
1109 {
1110 name: "Ethereum",
1111 onSelect: function() {
1112 network = bitcoin.networks.bitcoin;
1113 DOM.bip44coin.val(60);
1114 },
1115 },
1116 {
1117 name: "GAME",
1118 onSelect: function() {
1119 network = bitcoin.networks.game;
1120 DOM.bip44coin.val(101);
1121 },
1122 },
1123 {
1124 name: "Jumbucks",
1125 onSelect: function() {
1126 network = bitcoin.networks.jumbucks;
1127 DOM.bip44coin.val(26);
1128 },
1129 },
1130 {
1131 name: "Litecoin",
1132 onSelect: function() {
1133 network = bitcoin.networks.litecoin;
1134 DOM.bip44coin.val(2);
1135 },
1136 },
1137 {
1138 name: "Namecoin",
1139 onSelect: function() {
1140 network = bitcoin.networks.namecoin;
1141 DOM.bip44coin.val(7);
1142 },
1143 },
1144 {
1145 name: "Peercoin",
1146 onSelect: function() {
1147 network = bitcoin.networks.peercoin;
1148 DOM.bip44coin.val(6);
1149 },
1150 },
1151 {
1152 name: "ShadowCash",
1153 onSelect: function() {
1154 network = bitcoin.networks.shadow;
1155 DOM.bip44coin.val(35);
1156 },
1157 },
1158 {
1159 name: "ShadowCash Testnet",
1160 onSelect: function() {
1161 network = bitcoin.networks.shadowtn;
1162 DOM.bip44coin.val(1);
1163 },
1164 },
1165 {
1166 name: "Slimcoin",
1167 onSelect: function() {
1168 network = bitcoin.networks.slimcoin;
1169 DOM.bip44coin.val(63);
1170 },
1171 },
1172 {
1173 name: "Slimcoin Testnet",
1174 onSelect: function() {
1175 network = bitcoin.networks.slimcointn;
1176 DOM.bip44coin.val(111);
1177 },
1178 },
1179 {
1180 name: "Viacoin",
1181 onSelect: function() {
1182 network = bitcoin.networks.viacoin;
1183 DOM.bip44coin.val(14);
1184 },
1185 },
1186 {
1187 name: "Viacoin Testnet",
1188 onSelect: function() {
1189 network = bitcoin.networks.viacointestnet;
1190 DOM.bip44coin.val(1);
1191 },
1192 },
1193 ]
1194
1195 var clients = [
1196 {
1197 name: "Bitcoin Core",
1198 onSelect: function() {
1199 DOM.bip32path.val("m/0'/0'");
1200 DOM.hardenedAddresses.prop('checked', true);
1201 },
1202 },
1203 {
1204 name: "blockchain.info",
1205 onSelect: function() {
1206 DOM.bip32path.val("m/44'/0'/0'");
1207 DOM.hardenedAddresses.prop('checked', false);
1208 },
1209 },
1210 {
1211 name: "MultiBit HD",
1212 onSelect: function() {
1213 DOM.bip32path.val("m/0'/0");
1214 DOM.hardenedAddresses.prop('checked', false);
1215 },
1216 }
1217 ]
1218
1219 init();
1220
1221})();