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