]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/index.js
Add Korean language
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / index.js
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 = bitcoinjs.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 var litecoinUseLtub = true;
18
19 var entropyChangeTimeoutEvent = null;
20 var phraseChangeTimeoutEvent = null;
21 var rootKeyChangedTimeoutEvent = null;
22
23 var generationProcesses = [];
24
25 var DOM = {};
26 DOM.network = $(".network");
27 DOM.bip32Client = $("#bip32-client");
28 DOM.phraseNetwork = $("#network-phrase");
29 DOM.useEntropy = $(".use-entropy");
30 DOM.entropyContainer = $(".entropy-container");
31 DOM.entropy = $(".entropy");
32 DOM.entropyFiltered = DOM.entropyContainer.find(".filtered");
33 DOM.entropyType = DOM.entropyContainer.find(".type");
34 DOM.entropyCrackTime = DOM.entropyContainer.find(".crack-time");
35 DOM.entropyEventCount = DOM.entropyContainer.find(".event-count");
36 DOM.entropyBits = DOM.entropyContainer.find(".bits");
37 DOM.entropyBitsPerEvent = DOM.entropyContainer.find(".bits-per-event");
38 DOM.entropyWordCount = DOM.entropyContainer.find(".word-count");
39 DOM.entropyBinary = DOM.entropyContainer.find(".binary");
40 DOM.entropyWordIndexes = DOM.entropyContainer.find(".word-indexes");
41 DOM.entropyChecksum = DOM.entropyContainer.find(".checksum");
42 DOM.entropyMnemonicLength = DOM.entropyContainer.find(".mnemonic-length");
43 DOM.entropyFilterWarning = DOM.entropyContainer.find(".filter-warning");
44 DOM.phrase = $(".phrase");
45 DOM.passphrase = $(".passphrase");
46 DOM.generateContainer = $(".generate-container");
47 DOM.generate = $(".generate");
48 DOM.seed = $(".seed");
49 DOM.rootKey = $(".root-key");
50 DOM.litecoinLtubContainer = $(".litecoin-ltub-container");
51 DOM.litecoinUseLtub = $(".litecoin-use-ltub");
52 DOM.extendedPrivKey = $(".extended-priv-key");
53 DOM.extendedPubKey = $(".extended-pub-key");
54 DOM.bip32tab = $("#bip32-tab");
55 DOM.bip44tab = $("#bip44-tab");
56 DOM.bip49tab = $("#bip49-tab");
57 DOM.bip84tab = $("#bip84-tab");
58 DOM.bip141tab = $("#bip141-tab");
59 DOM.bip32panel = $("#bip32");
60 DOM.bip44panel = $("#bip44");
61 DOM.bip49panel = $("#bip49");
62 DOM.bip32path = $("#bip32-path");
63 DOM.bip44path = $("#bip44-path");
64 DOM.bip44purpose = $("#bip44 .purpose");
65 DOM.bip44coin = $("#bip44 .coin");
66 DOM.bip44account = $("#bip44 .account");
67 DOM.bip44accountXprv = $("#bip44 .account-xprv");
68 DOM.bip44accountXpub = $("#bip44 .account-xpub");
69 DOM.bip44change = $("#bip44 .change");
70 DOM.bip49unavailable = $("#bip49 .unavailable");
71 DOM.bip49available = $("#bip49 .available");
72 DOM.bip49path = $("#bip49-path");
73 DOM.bip49purpose = $("#bip49 .purpose");
74 DOM.bip49coin = $("#bip49 .coin");
75 DOM.bip49account = $("#bip49 .account");
76 DOM.bip49accountXprv = $("#bip49 .account-xprv");
77 DOM.bip49accountXpub = $("#bip49 .account-xpub");
78 DOM.bip49change = $("#bip49 .change");
79 DOM.bip84path = $("#bip84-path");
80 DOM.bip84purpose = $("#bip84 .purpose");
81 DOM.bip84coin = $("#bip84 .coin");
82 DOM.bip84account = $("#bip84 .account");
83 DOM.bip84accountXprv = $("#bip84 .account-xprv");
84 DOM.bip84accountXpub = $("#bip84 .account-xpub");
85 DOM.bip84change = $("#bip84 .change");
86 DOM.bip141unavailable = $("#bip141 .unavailable");
87 DOM.bip141available = $("#bip141 .available");
88 DOM.bip141path = $("#bip141-path");
89 DOM.bip141semantics = $(".bip141-semantics");
90 DOM.generatedStrength = $(".generate-container .strength");
91 DOM.hardenedAddresses = $(".hardened-addresses");
92 DOM.useBitpayAddressesContainer = $(".use-bitpay-addresses-container");
93 DOM.useBitpayAddresses = $(".use-bitpay-addresses");
94 DOM.useBip38 = $(".use-bip38");
95 DOM.bip38Password = $(".bip38-password");
96 DOM.addresses = $(".addresses");
97 DOM.csvTab = $("#csv-tab a");
98 DOM.csv = $(".csv");
99 DOM.rowsToAdd = $(".rows-to-add");
100 DOM.more = $(".more");
101 DOM.moreRowsStartIndex = $(".more-rows-start-index");
102 DOM.feedback = $(".feedback");
103 DOM.tab = $(".derivation-type a");
104 DOM.indexToggle = $(".index-toggle");
105 DOM.addressToggle = $(".address-toggle");
106 DOM.publicKeyToggle = $(".public-key-toggle");
107 DOM.privateKeyToggle = $(".private-key-toggle");
108 DOM.languages = $(".languages a");
109 DOM.qrContainer = $(".qr-container");
110 DOM.qrHider = DOM.qrContainer.find(".qr-hider");
111 DOM.qrImage = DOM.qrContainer.find(".qr-image");
112 DOM.qrHint = DOM.qrContainer.find(".qr-hint");
113 DOM.showQrEls = $("[data-show-qr]");
114
115 function init() {
116 // Events
117 DOM.network.on("change", networkChanged);
118 DOM.bip32Client.on("change", bip32ClientChanged);
119 DOM.useEntropy.on("change", setEntropyVisibility);
120 DOM.entropy.on("input", delayedEntropyChanged);
121 DOM.entropyMnemonicLength.on("change", entropyChanged);
122 DOM.phrase.on("input", delayedPhraseChanged);
123 DOM.passphrase.on("input", delayedPhraseChanged);
124 DOM.generate.on("click", generateClicked);
125 DOM.more.on("click", showMore);
126 DOM.rootKey.on("input", delayedRootKeyChanged);
127 DOM.litecoinUseLtub.on("change", litecoinUseLtubChanged);
128 DOM.bip32path.on("input", calcForDerivationPath);
129 DOM.bip44account.on("input", calcForDerivationPath);
130 DOM.bip44change.on("input", calcForDerivationPath);
131 DOM.bip49account.on("input", calcForDerivationPath);
132 DOM.bip49change.on("input", calcForDerivationPath);
133 DOM.bip84account.on("input", calcForDerivationPath);
134 DOM.bip84change.on("input", calcForDerivationPath);
135 DOM.bip141path.on("input", calcForDerivationPath);
136 DOM.bip141semantics.on("change", tabChanged);
137 DOM.tab.on("shown.bs.tab", tabChanged);
138 DOM.hardenedAddresses.on("change", calcForDerivationPath);
139 DOM.useBip38.on("change", calcForDerivationPath);
140 DOM.bip38Password.on("change", calcForDerivationPath);
141 DOM.indexToggle.on("click", toggleIndexes);
142 DOM.addressToggle.on("click", toggleAddresses);
143 DOM.publicKeyToggle.on("click", togglePublicKeys);
144 DOM.privateKeyToggle.on("click", togglePrivateKeys);
145 DOM.csvTab.on("click", updateCsv);
146 DOM.languages.on("click", languageChanged);
147 DOM.useBitpayAddresses.on("change", useBitpayAddressesChange);
148 setQrEvents(DOM.showQrEls);
149 disableForms();
150 hidePending();
151 hideValidationError();
152 populateNetworkSelect();
153 populateClientSelect();
154 }
155
156 // Event handlers
157
158 function networkChanged(e) {
159 clearDerivedKeys();
160 clearAddressesList();
161 DOM.litecoinLtubContainer.addClass("hidden");
162 DOM.useBitpayAddressesContainer.addClass("hidden");
163 var networkIndex = e.target.value;
164 var network = networks[networkIndex];
165 network.onSelect();
166 if (network.segwitAvailable) {
167 adjustNetworkForSegwit();
168 showSegwitAvailable();
169 }
170 else {
171 showSegwitUnavailable();
172 }
173 if (seed != null) {
174 phraseChanged();
175 }
176 else {
177 rootKeyChanged();
178 }
179 }
180
181 function bip32ClientChanged(e) {
182 var clientIndex = DOM.bip32Client.val();
183 if (clientIndex == "custom") {
184 DOM.bip32path.prop("readonly", false);
185 }
186 else {
187 DOM.bip32path.prop("readonly", true);
188 clients[clientIndex].onSelect();
189 if (seed != null) {
190 phraseChanged();
191 }
192 else {
193 rootKeyChanged();
194 }
195 }
196 }
197
198 function setEntropyVisibility() {
199 if (isUsingOwnEntropy()) {
200 DOM.entropyContainer.removeClass("hidden");
201 DOM.generateContainer.addClass("hidden");
202 DOM.phrase.prop("readonly", true);
203 DOM.entropy.focus();
204 entropyChanged();
205 }
206 else {
207 DOM.entropyContainer.addClass("hidden");
208 DOM.generateContainer.removeClass("hidden");
209 DOM.phrase.prop("readonly", false);
210 hidePending();
211 }
212 }
213
214 function delayedPhraseChanged() {
215 hideValidationError();
216 seed = null;
217 bip32RootKey = null;
218 bip32ExtendedKey = null;
219 clearAddressesList();
220 showPending();
221 if (phraseChangeTimeoutEvent != null) {
222 clearTimeout(phraseChangeTimeoutEvent);
223 }
224 phraseChangeTimeoutEvent = setTimeout(phraseChanged, 400);
225 }
226
227 function phraseChanged() {
228 showPending();
229 setMnemonicLanguage();
230 // Get the mnemonic phrase
231 var phrase = DOM.phrase.val();
232 var errorText = findPhraseErrors(phrase);
233 if (errorText) {
234 showValidationError(errorText);
235 return;
236 }
237 // Calculate and display
238 var passphrase = DOM.passphrase.val();
239 calcBip32RootKeyFromSeed(phrase, passphrase);
240 calcForDerivationPath();
241 // Show the word indexes
242 showWordIndexes();
243 }
244
245 function tabChanged() {
246 showPending();
247 adjustNetworkForSegwit();
248 var phrase = DOM.phrase.val();
249 if (phrase != "") {
250 // Calculate and display for mnemonic
251 var errorText = findPhraseErrors(phrase);
252 if (errorText) {
253 showValidationError(errorText);
254 return;
255 }
256 // Calculate and display
257 var passphrase = DOM.passphrase.val();
258 calcBip32RootKeyFromSeed(phrase, passphrase);
259 }
260 else {
261 // Calculate and display for root key
262 var rootKeyBase58 = DOM.rootKey.val();
263 var errorText = validateRootKey(rootKeyBase58);
264 if (errorText) {
265 showValidationError(errorText);
266 return;
267 }
268 // Calculate and display
269 calcBip32RootKeyFromBase58(rootKeyBase58);
270 }
271 calcForDerivationPath();
272 }
273
274 function delayedEntropyChanged() {
275 hideValidationError();
276 showPending();
277 if (entropyChangeTimeoutEvent != null) {
278 clearTimeout(entropyChangeTimeoutEvent);
279 }
280 entropyChangeTimeoutEvent = setTimeout(entropyChanged, 400);
281 }
282
283 function entropyChanged() {
284 // If blank entropy, clear mnemonic, addresses, errors
285 if (DOM.entropy.val().trim().length == 0) {
286 clearDisplay();
287 clearEntropyFeedback();
288 DOM.phrase.val("");
289 showValidationError("Blank entropy");
290 return;
291 }
292 // Get the current phrase to detect changes
293 var phrase = DOM.phrase.val();
294 // Set the phrase from the entropy
295 setMnemonicFromEntropy();
296 // Recalc addresses if the phrase has changed
297 var newPhrase = DOM.phrase.val();
298 if (newPhrase != phrase) {
299 if (newPhrase.length == 0) {
300 clearDisplay();
301 }
302 else {
303 phraseChanged();
304 }
305 }
306 else {
307 hidePending();
308 }
309 }
310
311 function delayedRootKeyChanged() {
312 // Warn if there is an existing mnemonic or passphrase.
313 if (DOM.phrase.val().length > 0 || DOM.passphrase.val().length > 0) {
314 if (!confirm("This will clear existing mnemonic and passphrase")) {
315 DOM.rootKey.val(bip32RootKey);
316 return
317 }
318 }
319 hideValidationError();
320 showPending();
321 // Clear existing mnemonic and passphrase
322 DOM.phrase.val("");
323 DOM.passphrase.val("");
324 seed = null;
325 if (rootKeyChangedTimeoutEvent != null) {
326 clearTimeout(rootKeyChangedTimeoutEvent);
327 }
328 rootKeyChangedTimeoutEvent = setTimeout(rootKeyChanged, 400);
329 }
330
331 function rootKeyChanged() {
332 showPending();
333 hideValidationError();
334 var rootKeyBase58 = DOM.rootKey.val();
335 var errorText = validateRootKey(rootKeyBase58);
336 if (errorText) {
337 showValidationError(errorText);
338 return;
339 }
340 // Calculate and display
341 calcBip32RootKeyFromBase58(rootKeyBase58);
342 calcForDerivationPath();
343 }
344
345 function litecoinUseLtubChanged() {
346 litecoinUseLtub = DOM.litecoinUseLtub.prop("checked");
347 if (litecoinUseLtub) {
348 network = bitcoinjs.bitcoin.networks.litecoin;
349 }
350 else {
351 network = bitcoinjs.bitcoin.networks.litecoinXprv;
352 }
353 phraseChanged();
354 }
355
356 function calcForDerivationPath() {
357 clearDerivedKeys();
358 clearAddressesList();
359 showPending();
360 // Don't show segwit if it's selected but network doesn't support it
361 if (segwitSelected() && !networkHasSegwit()) {
362 return;
363 }
364 // Get the derivation path
365 var derivationPath = getDerivationPath();
366 var errorText = findDerivationPathErrors(derivationPath);
367 if (errorText) {
368 showValidationError(errorText);
369 return;
370 }
371 bip32ExtendedKey = calcBip32ExtendedKey(derivationPath);
372 if (bip44TabSelected()) {
373 displayBip44Info();
374 }
375 else if (bip49TabSelected()) {
376 displayBip49Info();
377 }
378 else if (bip84TabSelected()) {
379 displayBip84Info();
380 }
381 displayBip32Info();
382 }
383
384 function generateClicked() {
385 if (isUsingOwnEntropy()) {
386 return;
387 }
388 clearDisplay();
389 showPending();
390 setTimeout(function() {
391 setMnemonicLanguage();
392 var phrase = generateRandomPhrase();
393 if (!phrase) {
394 return;
395 }
396 phraseChanged();
397 }, 50);
398 }
399
400 function languageChanged() {
401 setTimeout(function() {
402 setMnemonicLanguage();
403 if (DOM.phrase.val().length > 0) {
404 var newPhrase = convertPhraseToNewLanguage();
405 DOM.phrase.val(newPhrase);
406 phraseChanged();
407 }
408 else {
409 DOM.generate.trigger("click");
410 }
411 }, 50);
412 }
413
414 function useBitpayAddressesChange() {
415 setBitcoinCashNetworkValues();
416 phraseChanged();
417 }
418
419 function toggleIndexes() {
420 showIndex = !showIndex;
421 $("td.index span").toggleClass("invisible");
422 }
423
424 function toggleAddresses() {
425 showAddress = !showAddress;
426 $("td.address span").toggleClass("invisible");
427 }
428
429 function togglePublicKeys() {
430 showPubKey = !showPubKey;
431 $("td.pubkey span").toggleClass("invisible");
432 }
433
434 function togglePrivateKeys() {
435 showPrivKey = !showPrivKey;
436 $("td.privkey span").toggleClass("invisible");
437 }
438
439 // Private methods
440
441 function generateRandomPhrase() {
442 if (!hasStrongRandom()) {
443 var errorText = "This browser does not support strong randomness";
444 showValidationError(errorText);
445 return;
446 }
447 // get the amount of entropy to use
448 var numWords = parseInt(DOM.generatedStrength.val());
449 var strength = numWords / 3 * 32;
450 var buffer = new Uint8Array(strength / 8);
451 // create secure entropy
452 var data = crypto.getRandomValues(buffer);
453 // show the words
454 var words = mnemonic.toMnemonic(data);
455 DOM.phrase.val(words);
456 // show the entropy
457 var entropyHex = uint8ArrayToHex(data);
458 DOM.entropy.val(entropyHex);
459 // ensure entropy fields are consistent with what is being displayed
460 DOM.entropyMnemonicLength.val("raw");
461 return words;
462 }
463
464 function calcBip32RootKeyFromSeed(phrase, passphrase) {
465 seed = mnemonic.toSeed(phrase, passphrase);
466 bip32RootKey = bitcoinjs.bitcoin.HDNode.fromSeedHex(seed, network);
467 }
468
469 function calcBip32RootKeyFromBase58(rootKeyBase58) {
470 bip32RootKey = bitcoinjs.bitcoin.HDNode.fromBase58(rootKeyBase58, network);
471 }
472
473 function calcBip32ExtendedKey(path) {
474 // Check there's a root key to derive from
475 if (!bip32RootKey) {
476 return bip32RootKey;
477 }
478 var extendedKey = bip32RootKey;
479 // Derive the key from the path
480 var pathBits = path.split("/");
481 for (var i=0; i<pathBits.length; i++) {
482 var bit = pathBits[i];
483 var index = parseInt(bit);
484 if (isNaN(index)) {
485 continue;
486 }
487 var hardened = bit[bit.length-1] == "'";
488 var isPriv = !(extendedKey.isNeutered());
489 var invalidDerivationPath = hardened && !isPriv;
490 if (invalidDerivationPath) {
491 extendedKey = null;
492 }
493 else if (hardened) {
494 extendedKey = extendedKey.deriveHardened(index);
495 }
496 else {
497 extendedKey = extendedKey.derive(index);
498 }
499 }
500 return extendedKey
501 }
502
503 function showValidationError(errorText) {
504 DOM.feedback
505 .text(errorText)
506 .show();
507 }
508
509 function hideValidationError() {
510 DOM.feedback
511 .text("")
512 .hide();
513 }
514
515 function findPhraseErrors(phrase) {
516 // Preprocess the words
517 phrase = mnemonic.normalizeString(phrase);
518 var words = phraseToWordArray(phrase);
519 // Detect blank phrase
520 if (words.length == 0) {
521 return "Blank mnemonic";
522 }
523 // Check each word
524 for (var i=0; i<words.length; i++) {
525 var word = words[i];
526 var language = getLanguage();
527 if (WORDLISTS[language].indexOf(word) == -1) {
528 console.log("Finding closest match to " + word);
529 var nearestWord = findNearestWord(word);
530 return word + " not in wordlist, did you mean " + nearestWord + "?";
531 }
532 }
533 // Check the words are valid
534 var properPhrase = wordArrayToPhrase(words);
535 var isValid = mnemonic.check(properPhrase);
536 if (!isValid) {
537 return "Invalid mnemonic";
538 }
539 return false;
540 }
541
542 function validateRootKey(rootKeyBase58) {
543 try {
544 bitcoinjs.bitcoin.HDNode.fromBase58(rootKeyBase58, network);
545 }
546 catch (e) {
547 return "Invalid root key";
548 }
549 return "";
550 }
551
552 function getDerivationPath() {
553 if (bip44TabSelected()) {
554 var purpose = parseIntNoNaN(DOM.bip44purpose.val(), 44);
555 var coin = parseIntNoNaN(DOM.bip44coin.val(), 0);
556 var account = parseIntNoNaN(DOM.bip44account.val(), 0);
557 var change = parseIntNoNaN(DOM.bip44change.val(), 0);
558 var path = "m/";
559 path += purpose + "'/";
560 path += coin + "'/";
561 path += account + "'/";
562 path += change;
563 DOM.bip44path.val(path);
564 var derivationPath = DOM.bip44path.val();
565 console.log("Using derivation path from BIP44 tab: " + derivationPath);
566 return derivationPath;
567 }
568 else if (bip49TabSelected()) {
569 var purpose = parseIntNoNaN(DOM.bip49purpose.val(), 49);
570 var coin = parseIntNoNaN(DOM.bip49coin.val(), 0);
571 var account = parseIntNoNaN(DOM.bip49account.val(), 0);
572 var change = parseIntNoNaN(DOM.bip49change.val(), 0);
573 var path = "m/";
574 path += purpose + "'/";
575 path += coin + "'/";
576 path += account + "'/";
577 path += change;
578 DOM.bip49path.val(path);
579 var derivationPath = DOM.bip49path.val();
580 console.log("Using derivation path from BIP49 tab: " + derivationPath);
581 return derivationPath;
582 }
583 else if (bip84TabSelected()) {
584 var purpose = parseIntNoNaN(DOM.bip84purpose.val(), 84);
585 var coin = parseIntNoNaN(DOM.bip84coin.val(), 0);
586 var account = parseIntNoNaN(DOM.bip84account.val(), 0);
587 var change = parseIntNoNaN(DOM.bip84change.val(), 0);
588 var path = "m/";
589 path += purpose + "'/";
590 path += coin + "'/";
591 path += account + "'/";
592 path += change;
593 DOM.bip84path.val(path);
594 var derivationPath = DOM.bip84path.val();
595 console.log("Using derivation path from BIP84 tab: " + derivationPath);
596 return derivationPath;
597 }
598 else if (bip32TabSelected()) {
599 var derivationPath = DOM.bip32path.val();
600 console.log("Using derivation path from BIP32 tab: " + derivationPath);
601 return derivationPath;
602 }
603 else if (bip141TabSelected()) {
604 var derivationPath = DOM.bip141path.val();
605 console.log("Using derivation path from BIP141 tab: " + derivationPath);
606 return derivationPath;
607 }
608 else {
609 console.log("Unknown derivation path");
610 }
611 }
612
613 function findDerivationPathErrors(path) {
614 // TODO is not perfect but is better than nothing
615 // Inspired by
616 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
617 // and
618 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
619 var maxDepth = 255; // TODO verify this!!
620 var maxIndexValue = Math.pow(2, 31); // TODO verify this!!
621 if (path[0] != "m") {
622 return "First character must be 'm'";
623 }
624 if (path.length > 1) {
625 if (path[1] != "/") {
626 return "Separator must be '/'";
627 }
628 var indexes = path.split("/");
629 if (indexes.length > maxDepth) {
630 return "Derivation depth is " + indexes.length + ", must be less than " + maxDepth;
631 }
632 for (var depth = 1; depth<indexes.length; depth++) {
633 var index = indexes[depth];
634 var invalidChars = index.replace(/^[0-9]+'?$/g, "")
635 if (invalidChars.length > 0) {
636 return "Invalid characters " + invalidChars + " found at depth " + depth;
637 }
638 var indexValue = parseInt(index.replace("'", ""));
639 if (isNaN(depth)) {
640 return "Invalid number at depth " + depth;
641 }
642 if (indexValue > maxIndexValue) {
643 return "Value of " + indexValue + " at depth " + depth + " must be less than " + maxIndexValue;
644 }
645 }
646 }
647 // Check root key exists or else derivation path is useless!
648 if (!bip32RootKey) {
649 return "No root key";
650 }
651 // Check no hardened derivation path when using xpub keys
652 var hardenedPath = path.indexOf("'") > -1;
653 var hardenedAddresses = bip32TabSelected() && DOM.hardenedAddresses.prop("checked");
654 var hardened = hardenedPath || hardenedAddresses;
655 var isXpubkey = bip32RootKey.isNeutered();
656 if (hardened && isXpubkey) {
657 return "Hardened derivation path is invalid with xpub key";
658 }
659 return false;
660 }
661
662 function displayBip44Info() {
663 // Get the derivation path for the account
664 var purpose = parseIntNoNaN(DOM.bip44purpose.val(), 44);
665 var coin = parseIntNoNaN(DOM.bip44coin.val(), 0);
666 var account = parseIntNoNaN(DOM.bip44account.val(), 0);
667 var path = "m/";
668 path += purpose + "'/";
669 path += coin + "'/";
670 path += account + "'/";
671 // Calculate the account extended keys
672 var accountExtendedKey = calcBip32ExtendedKey(path);
673 var accountXprv = accountExtendedKey.toBase58();
674 var accountXpub = accountExtendedKey.neutered().toBase58();
675 // Display the extended keys
676 DOM.bip44accountXprv.val(accountXprv);
677 DOM.bip44accountXpub.val(accountXpub);
678 }
679
680 function displayBip49Info() {
681 // Get the derivation path for the account
682 var purpose = parseIntNoNaN(DOM.bip49purpose.val(), 49);
683 var coin = parseIntNoNaN(DOM.bip49coin.val(), 0);
684 var account = parseIntNoNaN(DOM.bip49account.val(), 0);
685 var path = "m/";
686 path += purpose + "'/";
687 path += coin + "'/";
688 path += account + "'/";
689 // Calculate the account extended keys
690 var accountExtendedKey = calcBip32ExtendedKey(path);
691 var accountXprv = accountExtendedKey.toBase58();
692 var accountXpub = accountExtendedKey.neutered().toBase58();
693 // Display the extended keys
694 DOM.bip49accountXprv.val(accountXprv);
695 DOM.bip49accountXpub.val(accountXpub);
696 }
697
698 function displayBip84Info() {
699 // Get the derivation path for the account
700 var purpose = parseIntNoNaN(DOM.bip84purpose.val(), 84);
701 var coin = parseIntNoNaN(DOM.bip84coin.val(), 0);
702 var account = parseIntNoNaN(DOM.bip84account.val(), 0);
703 var path = "m/";
704 path += purpose + "'/";
705 path += coin + "'/";
706 path += account + "'/";
707 // Calculate the account extended keys
708 var accountExtendedKey = calcBip32ExtendedKey(path);
709 var accountXprv = accountExtendedKey.toBase58();
710 var accountXpub = accountExtendedKey.neutered().toBase58();
711 // Display the extended keys
712 DOM.bip84accountXprv.val(accountXprv);
713 DOM.bip84accountXpub.val(accountXpub);
714 }
715
716 function displayBip32Info() {
717 // Display the key
718 DOM.seed.val(seed);
719 var rootKey = bip32RootKey.toBase58();
720 DOM.rootKey.val(rootKey);
721 var xprvkeyB58 = "NA";
722 if (!bip32ExtendedKey.isNeutered()) {
723 xprvkeyB58 = bip32ExtendedKey.toBase58();
724 }
725 var extendedPrivKey = xprvkeyB58;
726 DOM.extendedPrivKey.val(extendedPrivKey);
727 var extendedPubKey = bip32ExtendedKey.neutered().toBase58();
728 DOM.extendedPubKey.val(extendedPubKey);
729 // Display the addresses and privkeys
730 clearAddressesList();
731 var initialAddressCount = parseInt(DOM.rowsToAdd.val());
732 displayAddresses(0, initialAddressCount);
733 }
734
735 function displayAddresses(start, total) {
736 generationProcesses.push(new (function() {
737
738 var rows = [];
739
740 this.stop = function() {
741 for (var i=0; i<rows.length; i++) {
742 rows[i].shouldGenerate = false;
743 }
744 hidePending();
745 }
746
747 for (var i=0; i<total; i++) {
748 var index = i + start;
749 var isLast = i == total - 1;
750 rows.push(new TableRow(index, isLast));
751 }
752
753 })());
754 }
755
756 function segwitSelected() {
757 return bip49TabSelected() || bip84TabSelected() || bip141TabSelected();
758 }
759
760 function p2wpkhSelected() {
761 return bip84TabSelected() ||
762 bip141TabSelected() && DOM.bip141semantics.val() == "p2wpkh";
763 }
764
765 function p2wpkhInP2shSelected() {
766 return bip49TabSelected() ||
767 (bip141TabSelected() && DOM.bip141semantics.val() == "p2wpkh-p2sh");
768 }
769
770 function TableRow(index, isLast) {
771
772 var self = this;
773 this.shouldGenerate = true;
774 var useHardenedAddresses = DOM.hardenedAddresses.prop("checked");
775 var useBip38 = DOM.useBip38.prop("checked");
776 var bip38password = DOM.bip38Password.val();
777 var isSegwit = segwitSelected();
778 var segwitAvailable = networkHasSegwit();
779 var isP2wpkh = p2wpkhSelected();
780 var isP2wpkhInP2sh = p2wpkhInP2shSelected();
781
782 function init() {
783 calculateValues();
784 }
785
786 function calculateValues() {
787 setTimeout(function() {
788 if (!self.shouldGenerate) {
789 return;
790 }
791 // derive HDkey for this row of the table
792 var key = "NA";
793 if (useHardenedAddresses) {
794 key = bip32ExtendedKey.deriveHardened(index);
795 }
796 else {
797 key = bip32ExtendedKey.derive(index);
798 }
799 // bip38 requires uncompressed keys
800 // see https://github.com/iancoleman/bip39/issues/140#issuecomment-352164035
801 var keyPair = key.keyPair;
802 var useUncompressed = useBip38;
803 if (useUncompressed) {
804 keyPair = new bitcoinjs.bitcoin.ECPair(keyPair.d, null, { compressed: false });
805 }
806 // get address
807 var address = keyPair.getAddress().toString();
808 // get privkey
809 var hasPrivkey = !key.isNeutered();
810 var privkey = "NA";
811 if (hasPrivkey) {
812 privkey = keyPair.toWIF(network);
813 // BIP38 encode private key if required
814 if (useBip38) {
815 privkey = bitcoinjsBip38.encrypt(keyPair.d.toBuffer(), false, bip38password, function(p) {
816 console.log("Progressed " + p.percent.toFixed(1) + "% for index " + index);
817 });
818 }
819 }
820 // get pubkey
821 var pubkey = keyPair.getPublicKeyBuffer().toString('hex');
822 var indexText = getDerivationPath() + "/" + index;
823 if (useHardenedAddresses) {
824 indexText = indexText + "'";
825 }
826 // Ethereum values are different
827 if (networks[DOM.network.val()].name == "ETH - Ethereum") {
828 var privKeyBuffer = keyPair.d.toBuffer(32);
829 privkey = privKeyBuffer.toString('hex');
830 var addressBuffer = ethUtil.privateToAddress(privKeyBuffer);
831 var hexAddress = addressBuffer.toString('hex');
832 var checksumAddress = ethUtil.toChecksumAddress(hexAddress);
833 address = ethUtil.addHexPrefix(checksumAddress);
834 privkey = ethUtil.addHexPrefix(privkey);
835 pubkey = ethUtil.addHexPrefix(pubkey);
836 }
837 // Ripple values are different
838 if (networks[DOM.network.val()].name == "XRP - Ripple") {
839 privkey = convertRipplePriv(privkey);
840 address = convertRippleAdrr(address);
841 }
842 // Segwit addresses are different
843 if (isSegwit) {
844 if (!segwitAvailable) {
845 return;
846 }
847 if (isP2wpkh) {
848 var keyhash = bitcoinjs.bitcoin.crypto.hash160(key.getPublicKeyBuffer());
849 var scriptpubkey = bitcoinjs.bitcoin.script.witnessPubKeyHash.output.encode(keyhash);
850 address = bitcoinjs.bitcoin.address.fromOutputScript(scriptpubkey, network)
851 }
852 else if (isP2wpkhInP2sh) {
853 var keyhash = bitcoinjs.bitcoin.crypto.hash160(key.getPublicKeyBuffer());
854 var scriptsig = bitcoinjs.bitcoin.script.witnessPubKeyHash.output.encode(keyhash);
855 var addressbytes = bitcoinjs.bitcoin.crypto.hash160(scriptsig);
856 var scriptpubkey = bitcoinjs.bitcoin.script.scriptHash.output.encode(addressbytes);
857 address = bitcoinjs.bitcoin.address.fromOutputScript(scriptpubkey, network)
858 }
859 }
860 addAddressToList(indexText, address, pubkey, privkey);
861 if (isLast) {
862 hidePending();
863 updateCsv();
864 }
865 }, 50)
866 }
867
868 init();
869
870 }
871
872 function showMore() {
873 var rowsToAdd = parseInt(DOM.rowsToAdd.val());
874 if (isNaN(rowsToAdd)) {
875 rowsToAdd = 20;
876 DOM.rowsToAdd.val("20");
877 }
878 var start = parseInt(DOM.moreRowsStartIndex.val())
879 if (isNaN(start)) {
880 start = lastIndexInTable() + 1;
881 }
882 else {
883 var newStart = start + rowsToAdd;
884 DOM.moreRowsStartIndex.val(newStart);
885 }
886 if (rowsToAdd > 200) {
887 var msg = "Generating " + rowsToAdd + " rows could take a while. ";
888 msg += "Do you want to continue?";
889 if (!confirm(msg)) {
890 return;
891 }
892 }
893 displayAddresses(start, rowsToAdd);
894 }
895
896 function clearDisplay() {
897 clearAddressesList();
898 clearKeys();
899 hideValidationError();
900 }
901
902 function clearAddressesList() {
903 DOM.addresses.empty();
904 DOM.csv.val("");
905 stopGenerating();
906 }
907
908 function stopGenerating() {
909 while (generationProcesses.length > 0) {
910 var generation = generationProcesses.shift();
911 generation.stop();
912 }
913 }
914
915 function clearKeys() {
916 clearRootKey();
917 clearDerivedKeys();
918 }
919
920 function clearRootKey() {
921 DOM.rootKey.val("");
922 }
923
924 function clearDerivedKeys() {
925 DOM.extendedPrivKey.val("");
926 DOM.extendedPubKey.val("");
927 DOM.bip44accountXprv.val("");
928 DOM.bip44accountXpub.val("");
929 }
930
931 function addAddressToList(indexText, address, pubkey, privkey) {
932 var row = $(addressRowTemplate.html());
933 // Elements
934 var indexCell = row.find(".index span");
935 var addressCell = row.find(".address span");
936 var pubkeyCell = row.find(".pubkey span");
937 var privkeyCell = row.find(".privkey span");
938 // Content
939 indexCell.text(indexText);
940 addressCell.text(address);
941 pubkeyCell.text(pubkey);
942 privkeyCell.text(privkey);
943 // Visibility
944 if (!showIndex) {
945 indexCell.addClass("invisible");
946 }
947 if (!showAddress) {
948 addressCell.addClass("invisible");
949 }
950 if (!showPubKey) {
951 pubkeyCell.addClass("invisible");
952 }
953 if (!showPrivKey) {
954 privkeyCell.addClass("invisible");
955 }
956 DOM.addresses.append(row);
957 var rowShowQrEls = row.find("[data-show-qr]");
958 setQrEvents(rowShowQrEls);
959 }
960
961 function hasStrongRandom() {
962 return 'crypto' in window && window['crypto'] !== null;
963 }
964
965 function disableForms() {
966 $("form").on("submit", function(e) {
967 e.preventDefault();
968 });
969 }
970
971 function parseIntNoNaN(val, defaultVal) {
972 var v = parseInt(val);
973 if (isNaN(v)) {
974 return defaultVal;
975 }
976 return v;
977 }
978
979 function showPending() {
980 DOM.feedback
981 .text("Calculating...")
982 .show();
983 }
984
985 function findNearestWord(word) {
986 var language = getLanguage();
987 var words = WORDLISTS[language];
988 var minDistance = 99;
989 var closestWord = words[0];
990 for (var i=0; i<words.length; i++) {
991 var comparedTo = words[i];
992 if (comparedTo.indexOf(word) == 0) {
993 return comparedTo;
994 }
995 var distance = Levenshtein.get(word, comparedTo);
996 if (distance < minDistance) {
997 closestWord = comparedTo;
998 minDistance = distance;
999 }
1000 }
1001 return closestWord;
1002 }
1003
1004 function hidePending() {
1005 DOM.feedback
1006 .text("")
1007 .hide();
1008 }
1009
1010 function populateNetworkSelect() {
1011 for (var i=0; i<networks.length; i++) {
1012 var network = networks[i];
1013 var option = $("<option>");
1014 option.attr("value", i);
1015 option.text(network.name);
1016 if (network.name == "BTC - Bitcoin") {
1017 option.prop("selected", true);
1018 }
1019 DOM.phraseNetwork.append(option);
1020 }
1021 }
1022
1023 function populateClientSelect() {
1024 for (var i=0; i<clients.length; i++) {
1025 var client = clients[i];
1026 var option = $("<option>");
1027 option.attr("value", i);
1028 option.text(client.name);
1029 DOM.bip32Client.append(option);
1030 }
1031 }
1032
1033 function getLanguage() {
1034 var defaultLanguage = "english";
1035 // Try to get from existing phrase
1036 var language = getLanguageFromPhrase();
1037 // Try to get from url if not from phrase
1038 if (language.length == 0) {
1039 language = getLanguageFromUrl();
1040 }
1041 // Default to English if no other option
1042 if (language.length == 0) {
1043 language = defaultLanguage;
1044 }
1045 return language;
1046 }
1047
1048 function getLanguageFromPhrase(phrase) {
1049 // Check if how many words from existing phrase match a language.
1050 var language = "";
1051 if (!phrase) {
1052 phrase = DOM.phrase.val();
1053 }
1054 if (phrase.length > 0) {
1055 var words = phraseToWordArray(phrase);
1056 var languageMatches = {};
1057 for (l in WORDLISTS) {
1058 // Track how many words match in this language
1059 languageMatches[l] = 0;
1060 for (var i=0; i<words.length; i++) {
1061 var wordInLanguage = WORDLISTS[l].indexOf(words[i]) > -1;
1062 if (wordInLanguage) {
1063 languageMatches[l]++;
1064 }
1065 }
1066 // Find languages with most word matches.
1067 // This is made difficult due to commonalities between Chinese
1068 // simplified vs traditional.
1069 var mostMatches = 0;
1070 var mostMatchedLanguages = [];
1071 for (var l in languageMatches) {
1072 var numMatches = languageMatches[l];
1073 if (numMatches > mostMatches) {
1074 mostMatches = numMatches;
1075 mostMatchedLanguages = [l];
1076 }
1077 else if (numMatches == mostMatches) {
1078 mostMatchedLanguages.push(l);
1079 }
1080 }
1081 }
1082 if (mostMatchedLanguages.length > 0) {
1083 // Use first language and warn if multiple detected
1084 language = mostMatchedLanguages[0];
1085 if (mostMatchedLanguages.length > 1) {
1086 console.warn("Multiple possible languages");
1087 console.warn(mostMatchedLanguages);
1088 }
1089 }
1090 }
1091 return language;
1092 }
1093
1094 function getLanguageFromUrl() {
1095 for (var language in WORDLISTS) {
1096 if (window.location.hash.indexOf(language) > -1) {
1097 return language;
1098 }
1099 }
1100 return "";
1101 }
1102
1103 function setMnemonicLanguage() {
1104 var language = getLanguage();
1105 // Load the bip39 mnemonic generator for this language if required
1106 if (!(language in mnemonics)) {
1107 mnemonics[language] = new Mnemonic(language);
1108 }
1109 mnemonic = mnemonics[language];
1110 }
1111
1112 function convertPhraseToNewLanguage() {
1113 var oldLanguage = getLanguageFromPhrase();
1114 var newLanguage = getLanguageFromUrl();
1115 var oldPhrase = DOM.phrase.val();
1116 var oldWords = phraseToWordArray(oldPhrase);
1117 var newWords = [];
1118 for (var i=0; i<oldWords.length; i++) {
1119 var oldWord = oldWords[i];
1120 var index = WORDLISTS[oldLanguage].indexOf(oldWord);
1121 var newWord = WORDLISTS[newLanguage][index];
1122 newWords.push(newWord);
1123 }
1124 newPhrase = wordArrayToPhrase(newWords);
1125 return newPhrase;
1126 }
1127
1128 // TODO look at jsbip39 - mnemonic.splitWords
1129 function phraseToWordArray(phrase) {
1130 var words = phrase.split(/\s/g);
1131 var noBlanks = [];
1132 for (var i=0; i<words.length; i++) {
1133 var word = words[i];
1134 if (word.length > 0) {
1135 noBlanks.push(word);
1136 }
1137 }
1138 return noBlanks;
1139 }
1140
1141 // TODO look at jsbip39 - mnemonic.joinWords
1142 function wordArrayToPhrase(words) {
1143 var phrase = words.join(" ");
1144 var language = getLanguageFromPhrase(phrase);
1145 if (language == "japanese" || language == "korean") {
1146 phrase = words.join("\u3000");
1147 }
1148 return phrase;
1149 }
1150
1151 function isUsingOwnEntropy() {
1152 return DOM.useEntropy.prop("checked");
1153 }
1154
1155 function setMnemonicFromEntropy() {
1156 clearEntropyFeedback();
1157 // Get entropy value
1158 var entropyStr = DOM.entropy.val();
1159 // Work out minimum base for entropy
1160 var entropy = Entropy.fromString(entropyStr);
1161 if (entropy.binaryStr.length == 0) {
1162 return;
1163 }
1164 // Show entropy details
1165 showEntropyFeedback(entropy);
1166 // Use entropy hash if not using raw entropy
1167 var bits = entropy.binaryStr;
1168 var mnemonicLength = DOM.entropyMnemonicLength.val();
1169 if (mnemonicLength != "raw") {
1170 // Get bits by hashing entropy with SHA256
1171 var hash = sjcl.hash.sha256.hash(entropy.cleanStr);
1172 var hex = sjcl.codec.hex.fromBits(hash);
1173 bits = BigInteger.parse(hex, 16).toString(2);
1174 while (bits.length % 256 != 0) {
1175 bits = "0" + bits;
1176 }
1177 // Truncate hash to suit number of words
1178 mnemonicLength = parseInt(mnemonicLength);
1179 var numberOfBits = 32 * mnemonicLength / 3;
1180 bits = bits.substring(0, numberOfBits);
1181 }
1182 // Discard trailing entropy
1183 var bitsToUse = Math.floor(bits.length / 32) * 32;
1184 var start = bits.length - bitsToUse;
1185 var binaryStr = bits.substring(start);
1186 // Convert entropy string to numeric array
1187 var entropyArr = [];
1188 for (var i=0; i<binaryStr.length / 8; i++) {
1189 var byteAsBits = binaryStr.substring(i*8, i*8+8);
1190 var entropyByte = parseInt(byteAsBits, 2);
1191 entropyArr.push(entropyByte)
1192 }
1193 // Convert entropy array to mnemonic
1194 var phrase = mnemonic.toMnemonic(entropyArr);
1195 // Set the mnemonic in the UI
1196 DOM.phrase.val(phrase);
1197 // Show the word indexes
1198 showWordIndexes();
1199 // Show the checksum
1200 showChecksum();
1201 }
1202
1203 function clearEntropyFeedback() {
1204 DOM.entropyCrackTime.text("...");
1205 DOM.entropyType.text("");
1206 DOM.entropyWordCount.text("0");
1207 DOM.entropyEventCount.text("0");
1208 DOM.entropyBitsPerEvent.text("0");
1209 DOM.entropyBits.text("0");
1210 DOM.entropyFiltered.html("&nbsp;");
1211 DOM.entropyBinary.html("&nbsp;");
1212 }
1213
1214 function showEntropyFeedback(entropy) {
1215 var numberOfBits = entropy.binaryStr.length;
1216 var timeToCrack = "unknown";
1217 try {
1218 var z = zxcvbn(entropy.base.parts.join(""));
1219 timeToCrack = z.crack_times_display.offline_fast_hashing_1e10_per_second;
1220 if (z.feedback.warning != "") {
1221 timeToCrack = timeToCrack + " - " + z.feedback.warning;
1222 };
1223 }
1224 catch (e) {
1225 console.log("Error detecting entropy strength with zxcvbn:");
1226 console.log(e);
1227 }
1228 var entropyTypeStr = getEntropyTypeStr(entropy);
1229 var wordCount = Math.floor(numberOfBits / 32) * 3;
1230 var bitsPerEvent = entropy.bitsPerEvent.toFixed(2);
1231 var spacedBinaryStr = addSpacesEveryElevenBits(entropy.binaryStr);
1232 DOM.entropyFiltered.html(entropy.cleanHtml);
1233 DOM.entropyType.text(entropyTypeStr);
1234 DOM.entropyCrackTime.text(timeToCrack);
1235 DOM.entropyEventCount.text(entropy.base.ints.length);
1236 DOM.entropyBits.text(numberOfBits);
1237 DOM.entropyWordCount.text(wordCount);
1238 DOM.entropyBinary.text(spacedBinaryStr);
1239 DOM.entropyBitsPerEvent.text(bitsPerEvent);
1240 // detect and warn of filtering
1241 var rawNoSpaces = DOM.entropy.val().replace(/\s/g, "");
1242 var cleanNoSpaces = entropy.cleanStr.replace(/\s/g, "");
1243 var isFiltered = rawNoSpaces.length != cleanNoSpaces.length;
1244 if (isFiltered) {
1245 DOM.entropyFilterWarning.removeClass('hidden');
1246 }
1247 else {
1248 DOM.entropyFilterWarning.addClass('hidden');
1249 }
1250 }
1251
1252 function getEntropyTypeStr(entropy) {
1253 var typeStr = entropy.base.str;
1254 // Add some detail if these are cards
1255 if (entropy.base.asInt == 52) {
1256 var cardDetail = []; // array of message strings
1257 // Detect duplicates
1258 var dupes = [];
1259 var dupeTracker = {};
1260 for (var i=0; i<entropy.base.parts.length; i++) {
1261 var card = entropy.base.parts[i];
1262 var cardUpper = card.toUpperCase();
1263 if (cardUpper in dupeTracker) {
1264 dupes.push(card);
1265 }
1266 dupeTracker[cardUpper] = true;
1267 }
1268 if (dupes.length > 0) {
1269 var dupeWord = "duplicates";
1270 if (dupes.length == 1) {
1271 dupeWord = "duplicate";
1272 }
1273 var msg = dupes.length + " " + dupeWord + ": " + dupes.slice(0,3).join(" ");
1274 if (dupes.length > 3) {
1275 msg += "...";
1276 }
1277 cardDetail.push(msg);
1278 }
1279 // Detect full deck
1280 var uniqueCards = [];
1281 for (var uniqueCard in dupeTracker) {
1282 uniqueCards.push(uniqueCard);
1283 }
1284 if (uniqueCards.length == 52) {
1285 cardDetail.unshift("full deck");
1286 }
1287 // Detect missing cards
1288 var values = "A23456789TJQK";
1289 var suits = "CDHS";
1290 var missingCards = [];
1291 for (var i=0; i<suits.length; i++) {
1292 for (var j=0; j<values.length; j++) {
1293 var card = values[j] + suits[i];
1294 if (!(card in dupeTracker)) {
1295 missingCards.push(card);
1296 }
1297 }
1298 }
1299 // Display missing cards if six or less, ie clearly going for full deck
1300 if (missingCards.length > 0 && missingCards.length <= 6) {
1301 var msg = missingCards.length + " missing: " + missingCards.slice(0,3).join(" ");
1302 if (missingCards.length > 3) {
1303 msg += "...";
1304 }
1305 cardDetail.push(msg);
1306 }
1307 // Add card details to typeStr
1308 if (cardDetail.length > 0) {
1309 typeStr += " (" + cardDetail.join(", ") + ")";
1310 }
1311 }
1312 return typeStr;
1313 }
1314
1315 function setQrEvents(els) {
1316 els.on("mouseenter", createQr);
1317 els.on("mouseleave", destroyQr);
1318 els.on("click", toggleQr);
1319 }
1320
1321 function createQr(e) {
1322 var content = e.target.textContent || e.target.value;
1323 if (content) {
1324 var qrEl = kjua({
1325 text: content,
1326 render: "canvas",
1327 size: 310,
1328 ecLevel: 'H',
1329 });
1330 DOM.qrImage.append(qrEl);
1331 if (!showQr) {
1332 DOM.qrHider.addClass("hidden");
1333 }
1334 else {
1335 DOM.qrHider.removeClass("hidden");
1336 }
1337 DOM.qrContainer.removeClass("hidden");
1338 }
1339 }
1340
1341 function destroyQr() {
1342 DOM.qrImage.text("");
1343 DOM.qrContainer.addClass("hidden");
1344 }
1345
1346 function toggleQr() {
1347 showQr = !showQr;
1348 DOM.qrHider.toggleClass("hidden");
1349 DOM.qrHint.toggleClass("hidden");
1350 }
1351
1352 function bip44TabSelected() {
1353 return DOM.bip44tab.hasClass("active");
1354 }
1355
1356 function bip32TabSelected() {
1357 return DOM.bip32tab.hasClass("active");
1358 }
1359
1360 function networkHasSegwit() {
1361 return networks[DOM.network.val()].segwitAvailable;
1362 }
1363
1364 function bip49TabSelected() {
1365 return DOM.bip49tab.hasClass("active");
1366 }
1367
1368 function bip84TabSelected() {
1369 return DOM.bip84tab.hasClass("active");
1370 }
1371
1372 function bip141TabSelected() {
1373 return DOM.bip141tab.hasClass("active");
1374 }
1375
1376 function setHdCoin(coinValue) {
1377 DOM.bip44coin.val(coinValue);
1378 DOM.bip49coin.val(coinValue);
1379 DOM.bip84coin.val(coinValue);
1380 }
1381
1382 function showSegwitAvailable() {
1383 DOM.bip49unavailable.addClass("hidden");
1384 DOM.bip49available.removeClass("hidden");
1385 DOM.bip141unavailable.addClass("hidden");
1386 DOM.bip141available.removeClass("hidden");
1387 }
1388
1389 function showSegwitUnavailable() {
1390 DOM.bip49available.addClass("hidden");
1391 DOM.bip49unavailable.removeClass("hidden");
1392 DOM.bip141available.addClass("hidden");
1393 DOM.bip141unavailable.removeClass("hidden");
1394 }
1395
1396 function useBitpayAddresses() {
1397 return !(DOM.useBitpayAddresses.prop("checked"));
1398 }
1399
1400 function setBitcoinCashNetworkValues() {
1401 if (useBitpayAddresses()) {
1402 network = bitcoinjs.bitcoin.networks.bitcoin;
1403 }
1404 else {
1405 network = bitcoinjs.bitcoin.networks.bitcoinCashBitbpay;
1406 }
1407 }
1408
1409 function adjustNetworkForSegwit() {
1410 // If segwit is selected the xpub/xprv prefixes need to be adjusted
1411 // to avoid accidentally importing BIP49 xpub to BIP44 watch only
1412 // wallet.
1413 // See https://github.com/iancoleman/bip39/issues/125
1414 var segwitNetworks = null;
1415 // if a segwit network is alread selected, need to use base network to
1416 // look up new parameters
1417 if ("baseNetwork" in network) {
1418 network = bitcoinjs.bitcoin.networks[network.baseNetwork];
1419 }
1420 // choose the right segwit params
1421 if (p2wpkhSelected() && "p2wpkh" in network) {
1422 network = network.p2wpkh;
1423 }
1424 else if (p2wpkhInP2shSelected() && "p2wpkhInP2sh" in network) {
1425 network = network.p2wpkhInP2sh;
1426 }
1427 }
1428
1429 function lastIndexInTable() {
1430 var pathText = DOM.addresses.find(".index").last().text();
1431 var pathBits = pathText.split("/");
1432 var lastBit = pathBits[pathBits.length-1];
1433 var lastBitClean = lastBit.replace("'", "");
1434 return parseInt(lastBitClean);
1435 }
1436
1437 function uint8ArrayToHex(a) {
1438 var s = ""
1439 for (var i=0; i<a.length; i++) {
1440 var h = a[i].toString(16);
1441 while (h.length < 2) {
1442 h = "0" + h;
1443 }
1444 s = s + h;
1445 }
1446 return s;
1447 }
1448
1449 function showWordIndexes() {
1450 var phrase = DOM.phrase.val();
1451 var words = phraseToWordArray(phrase);
1452 var wordIndexes = [];
1453 var language = getLanguage();
1454 for (var i=0; i<words.length; i++) {
1455 var word = words[i];
1456 var wordIndex = WORDLISTS[language].indexOf(word);
1457 wordIndexes.push(wordIndex);
1458 }
1459 var wordIndexesStr = wordIndexes.join(", ");
1460 DOM.entropyWordIndexes.text(wordIndexesStr);
1461 }
1462
1463 function showChecksum() {
1464 var phrase = DOM.phrase.val();
1465 var words = phraseToWordArray(phrase);
1466 var checksumBitlength = words.length / 3;
1467 var checksum = "";
1468 var binaryStr = "";
1469 var language = getLanguage();
1470 for (var i=words.length-1; i>=0; i--) {
1471 var word = words[i];
1472 var wordIndex = WORDLISTS[language].indexOf(word);
1473 var wordBinary = wordIndex.toString(2);
1474 while (wordBinary.length < 11) {
1475 wordBinary = "0" + wordBinary;
1476 }
1477 var binaryStr = wordBinary + binaryStr;
1478 if (binaryStr.length >= checksumBitlength) {
1479 var start = binaryStr.length - checksumBitlength;
1480 var end = binaryStr.length;
1481 checksum = binaryStr.substring(start, end);
1482 // add spaces so the last group is 11 bits, not the first
1483 checksum = checksum.split("").reverse().join("")
1484 checksum = addSpacesEveryElevenBits(checksum);
1485 checksum = checksum.split("").reverse().join("")
1486 break;
1487 }
1488 }
1489 DOM.entropyChecksum.text(checksum);
1490 }
1491
1492 function updateCsv() {
1493 var tableCsv = "path,address,public key,private key\n";
1494 var rows = DOM.addresses.find("tr");
1495 for (var i=0; i<rows.length; i++) {
1496 var row = $(rows[i]);
1497 var cells = row.find("td");
1498 for (var j=0; j<cells.length; j++) {
1499 var cell = $(cells[j]);
1500 if (!cell.children().hasClass("invisible")) {
1501 tableCsv = tableCsv + cell.text();
1502 }
1503 if (j != cells.length - 1) {
1504 tableCsv = tableCsv + ",";
1505 }
1506 }
1507 tableCsv = tableCsv + "\n";
1508 }
1509 DOM.csv.val(tableCsv);
1510 }
1511
1512 function addSpacesEveryElevenBits(binaryStr) {
1513 return binaryStr.match(/.{1,11}/g).join(" ");
1514 }
1515
1516 var networks = [
1517 {
1518 name: "AXE - Axe",
1519 segwitAvailable: false,
1520 onSelect: function() {
1521 network = bitcoinjs.bitcoin.networks.axe;
1522 setHdCoin(0);
1523 },
1524 },
1525 {
1526 name: "BCH - Bitcoin Cash",
1527 segwitAvailable: false,
1528 onSelect: function() {
1529 DOM.useBitpayAddressesContainer.removeClass("hidden");
1530 setBitcoinCashNetworkValues();
1531 setHdCoin(145);
1532 },
1533 },
1534 {
1535 name: "BLK - BlackCoin",
1536 segwitAvailable: false,
1537 onSelect: function() {
1538 network = bitcoinjs.bitcoin.networks.blackcoin;
1539 setHdCoin(10);
1540 },
1541 },
1542 {
1543 name: "BTC - Bitcoin",
1544 segwitAvailable: true,
1545 onSelect: function() {
1546 network = bitcoinjs.bitcoin.networks.bitcoin;
1547 setHdCoin(0);
1548 },
1549 },
1550 {
1551 name: "BTC - Bitcoin Testnet",
1552 segwitAvailable: true,
1553 onSelect: function() {
1554 network = bitcoinjs.bitcoin.networks.testnet;
1555 setHdCoin(1);
1556 },
1557 },
1558 {
1559 name: "BTG - Bitcoin Gold",
1560 segwitAvailable: true,
1561 onSelect: function() {
1562 network = bitcoinjs.bitcoin.networks.bgold;
1563 setHdCoin(0);
1564 },
1565 },
1566 {
1567 name: "CLAM - Clams",
1568 segwitAvailable: false,
1569 onSelect: function() {
1570 network = bitcoinjs.bitcoin.networks.clam;
1571 setHdCoin(23);
1572 },
1573 },
1574 {
1575 name: "CRW - Crown",
1576 segwitAvailable: false,
1577 onSelect: function() {
1578 network = bitcoinjs.bitcoin.networks.crown;
1579 setHdCoin(72);
1580 },
1581 },
1582 {
1583 name: "DASH - Dash",
1584 segwitAvailable: false,
1585 onSelect: function() {
1586 network = bitcoinjs.bitcoin.networks.dash;
1587 setHdCoin(5);
1588 },
1589 },
1590 {
1591 name: "DASH - Dash Testnet",
1592 segwitAvailable: false,
1593 onSelect: function() {
1594 network = bitcoinjs.bitcoin.networks.dashtn;
1595 setHdCoin(1);
1596 },
1597 },
1598 {
1599 name: "DNR - Denarius",
1600 segwitAvailable: false,
1601 onSelect: function() {
1602 network = bitcoinjs.bitcoin.networks.denarius;
1603 setHdCoin(0);
1604 },
1605 },
1606 {
1607 name: "DOGE - Dogecoin",
1608 segwitAvailable: false,
1609 onSelect: function() {
1610 network = bitcoinjs.bitcoin.networks.dogecoin;
1611 setHdCoin(3);
1612 },
1613 },
1614 {
1615 name: "ETH - Ethereum",
1616 segwitAvailable: false,
1617 onSelect: function() {
1618 network = bitcoinjs.bitcoin.networks.bitcoin;
1619 setHdCoin(60);
1620 },
1621 },
1622 {
1623 name: "FJC - Fujicoin",
1624 segwitAvailable: false,
1625 onSelect: function() {
1626 network = bitcoinjs.bitcoin.networks.fujicoin;
1627 setHdCoin(75);
1628 },
1629 },
1630 {
1631 name: "GAME - GameCredits",
1632 segwitAvailable: false,
1633 onSelect: function() {
1634 network = bitcoinjs.bitcoin.networks.game;
1635 setHdCoin(101);
1636 },
1637 },
1638 {
1639 name: "JBS - Jumbucks",
1640 segwitAvailable: false,
1641 onSelect: function() {
1642 network = bitcoinjs.bitcoin.networks.jumbucks;
1643 setHdCoin(26);
1644 },
1645 },
1646 {
1647 name: "KMD - Komodo",
1648 bip49available: false,
1649 onSelect: function() {
1650 network = bitcoinjs.bitcoin.networks.komodo;
1651 setHdCoin(141);
1652 },
1653 },
1654 {
1655 name: "LTC - Litecoin",
1656 segwitAvailable: true,
1657 onSelect: function() {
1658 network = bitcoinjs.bitcoin.networks.litecoin;
1659 setHdCoin(2);
1660 DOM.litecoinLtubContainer.removeClass("hidden");
1661 },
1662 },
1663 {
1664 name: "MAZA - Maza",
1665 segwitAvailable: false,
1666 onSelect: function() {
1667 network = bitcoinjs.bitcoin.networks.maza;
1668 setHdCoin(13);
1669 },
1670 },
1671 {
1672 name: "MONA - Monacoin",
1673 segwitAvailable: true,
1674 onSelect: function() {
1675 network = bitcoinjs.bitcoin.networks.monacoin,
1676 setHdCoin(22);
1677 },
1678 },
1679 {
1680 name: "NMC - Namecoin",
1681 segwitAvailable: false,
1682 onSelect: function() {
1683 network = bitcoinjs.bitcoin.networks.namecoin;
1684 setHdCoin(7);
1685 },
1686 },
1687 {
1688 name: "ONX - Onixcoin",
1689 segwitAvailable: false,
1690 onSelect: function() {
1691 network = bitcoinjs.bitcoin.networks.onixcoin;
1692 setHdCoin(174);
1693 },
1694 },
1695 {
1696 name: "PIVX - PIVX",
1697 segwitAvailable: false,
1698 onSelect: function() {
1699 network = bitcoinjs.bitcoin.networks.pivx;
1700 setHdCoin(119);
1701 },
1702 },
1703 {
1704 name: "PIVX - PIVX Testnet",
1705 segwitAvailable: false,
1706 onSelect: function() {
1707 network = bitcoinjs.bitcoin.networks.pivxtestnet;
1708 setHdCoin(1);
1709 },
1710 },
1711 {
1712 name: "PPC - Peercoin",
1713 segwitAvailable: false,
1714 onSelect: function() {
1715 network = bitcoinjs.bitcoin.networks.peercoin;
1716 setHdCoin(6);
1717 },
1718 },
1719 {
1720 name: "SDC - ShadowCash",
1721 segwitAvailable: false,
1722 onSelect: function() {
1723 network = bitcoinjs.bitcoin.networks.shadow;
1724 setHdCoin(35);
1725 },
1726 },
1727 {
1728 name: "SDC - ShadowCash Testnet",
1729 segwitAvailable: false,
1730 onSelect: function() {
1731 network = bitcoinjs.bitcoin.networks.shadowtn;
1732 setHdCoin(1);
1733 },
1734 },
1735 {
1736 name: "SLM - Slimcoin",
1737 segwitAvailable: false,
1738 onSelect: function() {
1739 network = bitcoinjs.bitcoin.networks.slimcoin;
1740 setHdCoin(63);
1741 },
1742 },
1743 {
1744 name: "SLM - Slimcoin Testnet",
1745 segwitAvailable: false,
1746 onSelect: function() {
1747 network = bitcoinjs.bitcoin.networks.slimcointn;
1748 setHdCoin(111);
1749 },
1750 },
1751 {
1752 name: "USNBT - NuBits",
1753 segwitAvailable: false,
1754 onSelect: function() {
1755 network = bitcoinjs.bitcoin.networks.nubits;
1756 setHdCoin(12);
1757 },
1758 },
1759 {
1760 name: "VIA - Viacoin",
1761 segwitAvailable: false,
1762 onSelect: function() {
1763 network = bitcoinjs.bitcoin.networks.viacoin;
1764 setHdCoin(14);
1765 },
1766 },
1767 {
1768 name: "VIA - Viacoin Testnet",
1769 segwitAvailable: false,
1770 onSelect: function() {
1771 network = bitcoinjs.bitcoin.networks.viacointestnet;
1772 setHdCoin(1);
1773 },
1774 },
1775 {
1776 name: "XMY - Myriadcoin",
1777 segwitAvailable: false,
1778 onSelect: function() {
1779 network = bitcoinjs.bitcoin.networks.myriadcoin;
1780 setHdCoin(90);
1781 },
1782 },
1783 {
1784 name: "XRP - Ripple",
1785 segwitAvailable: false,
1786 onSelect: function() {
1787 network = bitcoinjs.bitcoin.networks.bitcoin;
1788 setHdCoin(144);
1789 },
1790 },
1791 ]
1792
1793 var clients = [
1794 {
1795 name: "Bitcoin Core",
1796 onSelect: function() {
1797 DOM.bip32path.val("m/0'/0'");
1798 DOM.hardenedAddresses.prop('checked', true);
1799 },
1800 },
1801 {
1802 name: "blockchain.info",
1803 onSelect: function() {
1804 DOM.bip32path.val("m/44'/0'/0'");
1805 DOM.hardenedAddresses.prop('checked', false);
1806 },
1807 },
1808 {
1809 name: "MultiBit HD",
1810 onSelect: function() {
1811 DOM.bip32path.val("m/0'/0");
1812 DOM.hardenedAddresses.prop('checked', false);
1813 },
1814 }
1815 ]
1816
1817 init();
1818
1819 })();