3 // mnemonics is populated as required by getLanguage
4 var mnemonics
= { "english": new Mnemonic("english") };
5 var mnemonic
= mnemonics
["english"];
7 var bip32RootKey
= null;
8 var bip32ExtendedKey
= null;
9 var network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
10 var addressRowTemplate
= $("#address-row-template");
13 var showAddress
= true;
14 var showPubKey
= true;
15 var showPrivKey
= true;
17 var litecoinUseLtub
= false;
19 var entropyChangeTimeoutEvent
= null;
20 var phraseChangeTimeoutEvent
= null;
21 var rootKeyChangedTimeoutEvent
= null;
23 var generationProcesses
= [];
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
.entropyMnemonicLength
= DOM
.entropyContainer
.find(".mnemonic-length");
41 DOM
.phrase
= $(".phrase");
42 DOM
.passphrase
= $(".passphrase");
43 DOM
.generateContainer
= $(".generate-container");
44 DOM
.generate
= $(".generate");
45 DOM
.seed
= $(".seed");
46 DOM
.rootKey
= $(".root-key");
47 DOM
.litecoinLtubContainer
= $(".litecoin-ltub-container");
48 DOM
.litecoinUseLtub
= $(".litecoin-use-ltub");
49 DOM
.extendedPrivKey
= $(".extended-priv-key");
50 DOM
.extendedPubKey
= $(".extended-pub-key");
51 DOM
.bip32tab
= $("#bip32-tab");
52 DOM
.bip44tab
= $("#bip44-tab");
53 DOM
.bip49tab
= $("#bip49-tab");
54 DOM
.bip32panel
= $("#bip32");
55 DOM
.bip44panel
= $("#bip44");
56 DOM
.bip49panel
= $("#bip49");
57 DOM
.bip32path
= $("#bip32-path");
58 DOM
.bip44path
= $("#bip44-path");
59 DOM
.bip44purpose
= $("#bip44 .purpose");
60 DOM
.bip44coin
= $("#bip44 .coin");
61 DOM
.bip44account
= $("#bip44 .account");
62 DOM
.bip44accountXprv
= $("#bip44 .account-xprv");
63 DOM
.bip44accountXpub
= $("#bip44 .account-xpub");
64 DOM
.bip44change
= $("#bip44 .change");
65 DOM
.bip49unavailable
= $("#bip49 .unavailable");
66 DOM
.bip49available
= $("#bip49 .available");
67 DOM
.bip49path
= $("#bip49-path");
68 DOM
.bip49purpose
= $("#bip49 .purpose");
69 DOM
.bip49coin
= $("#bip49 .coin");
70 DOM
.bip49account
= $("#bip49 .account");
71 DOM
.bip49accountXprv
= $("#bip49 .account-xprv");
72 DOM
.bip49accountXpub
= $("#bip49 .account-xpub");
73 DOM
.bip49change
= $("#bip49 .change");
74 DOM
.generatedStrength
= $(".generate-container .strength");
75 DOM
.hardenedAddresses
= $(".hardened-addresses");
76 DOM
.useP2wpkhNestedInP2sh
= $(".p2wpkh-nested-in-p2sh");
77 DOM
.addresses
= $(".addresses");
78 DOM
.rowsToAdd
= $(".rows-to-add");
79 DOM
.more
= $(".more");
80 DOM
.feedback
= $(".feedback");
81 DOM
.tab
= $(".derivation-type a");
82 DOM
.indexToggle
= $(".index-toggle");
83 DOM
.addressToggle
= $(".address-toggle");
84 DOM
.publicKeyToggle
= $(".public-key-toggle");
85 DOM
.privateKeyToggle
= $(".private-key-toggle");
86 DOM
.languages
= $(".languages a");
87 DOM
.qrContainer
= $(".qr-container");
88 DOM
.qrHider
= DOM
.qrContainer
.find(".qr-hider");
89 DOM
.qrImage
= DOM
.qrContainer
.find(".qr-image");
90 DOM
.qrHint
= DOM
.qrContainer
.find(".qr-hint");
91 DOM
.showQrEls
= $("[data-show-qr]");
95 DOM
.network
.on("change", networkChanged
);
96 DOM
.bip32Client
.on("change", bip32ClientChanged
);
97 DOM
.useEntropy
.on("change", setEntropyVisibility
);
98 DOM
.entropy
.on("input", delayedEntropyChanged
);
99 DOM
.entropyMnemonicLength
.on("change", entropyChanged
);
100 DOM
.phrase
.on("input", delayedPhraseChanged
);
101 DOM
.passphrase
.on("input", delayedPhraseChanged
);
102 DOM
.generate
.on("click", generateClicked
);
103 DOM
.more
.on("click", showMore
);
104 DOM
.rootKey
.on("input", delayedRootKeyChanged
);
105 DOM
.litecoinUseLtub
.on("change", litecoinUseLtubChanged
);
106 DOM
.bip32path
.on("input", calcForDerivationPath
);
107 DOM
.bip44account
.on("input", calcForDerivationPath
);
108 DOM
.bip44change
.on("input", calcForDerivationPath
);
109 DOM
.bip49account
.on("input", calcForDerivationPath
);
110 DOM
.bip49change
.on("input", calcForDerivationPath
);
111 DOM
.tab
.on("shown.bs.tab", calcForDerivationPath
);
112 DOM
.hardenedAddresses
.on("change", calcForDerivationPath
);
113 DOM
.useP2wpkhNestedInP2sh
.on("change", calcForDerivationPath
);
114 DOM
.indexToggle
.on("click", toggleIndexes
);
115 DOM
.addressToggle
.on("click", toggleAddresses
);
116 DOM
.publicKeyToggle
.on("click", togglePublicKeys
);
117 DOM
.privateKeyToggle
.on("click", togglePrivateKeys
);
118 DOM
.languages
.on("click", languageChanged
);
119 setQrEvents(DOM
.showQrEls
);
122 hideValidationError();
123 populateNetworkSelect();
124 populateClientSelect();
129 function networkChanged(e
) {
131 clearAddressesList();
132 DOM
.litecoinLtubContainer
.addClass("hidden");
133 var networkIndex
= e
.target
.value
;
134 var network
= networks
[networkIndex
];
136 if (network
.p2wpkhNestedInP2shAvailable
) {
137 showP2wpkhNestedInP2shAvailable();
140 showP2wpkhNestedInP2shUnavailable();
150 function bip32ClientChanged(e
) {
151 var clientIndex
= DOM
.bip32Client
.val();
152 if (clientIndex
== "custom") {
153 DOM
.bip32path
.prop("readonly", false);
156 DOM
.bip32path
.prop("readonly", true);
157 clients
[clientIndex
].onSelect();
167 function setEntropyVisibility() {
168 if (isUsingOwnEntropy()) {
169 DOM
.entropyContainer
.removeClass("hidden");
170 DOM
.generateContainer
.addClass("hidden");
171 DOM
.phrase
.prop("readonly", true);
176 DOM
.entropyContainer
.addClass("hidden");
177 DOM
.generateContainer
.removeClass("hidden");
178 DOM
.phrase
.prop("readonly", false);
183 function delayedPhraseChanged() {
184 hideValidationError();
187 bip32ExtendedKey
= null;
188 clearAddressesList();
190 if (phraseChangeTimeoutEvent
!= null) {
191 clearTimeout(phraseChangeTimeoutEvent
);
193 phraseChangeTimeoutEvent
= setTimeout(phraseChanged
, 400);
196 function phraseChanged() {
198 setMnemonicLanguage();
199 // Get the mnemonic phrase
200 var phrase
= DOM
.phrase
.val();
201 var errorText
= findPhraseErrors(phrase
);
203 showValidationError(errorText
);
206 // Calculate and display
207 var passphrase
= DOM
.passphrase
.val();
208 calcBip32RootKeyFromSeed(phrase
, passphrase
);
209 calcForDerivationPath();
212 function delayedEntropyChanged() {
213 hideValidationError();
215 if (entropyChangeTimeoutEvent
!= null) {
216 clearTimeout(entropyChangeTimeoutEvent
);
218 entropyChangeTimeoutEvent
= setTimeout(entropyChanged
, 400);
221 function entropyChanged() {
222 // If blank entropy, clear mnemonic, addresses, errors
223 if (DOM
.entropy
.val().trim().length
== 0) {
225 clearEntropyFeedback();
227 showValidationError("Blank entropy");
230 // Get the current phrase to detect changes
231 var phrase
= DOM
.phrase
.val();
232 // Set the phrase from the entropy
233 setMnemonicFromEntropy();
234 // Recalc addresses if the phrase has changed
235 var newPhrase
= DOM
.phrase
.val();
236 if (newPhrase
!= phrase
) {
237 if (newPhrase
.length
== 0) {
249 function delayedRootKeyChanged() {
250 // Warn if there is an existing mnemonic or passphrase.
251 if (DOM
.phrase
.val().length
> 0 || DOM
.passphrase
.val().length
> 0) {
252 if (!confirm("This will clear existing mnemonic and passphrase")) {
253 DOM
.rootKey
.val(bip32RootKey
);
257 hideValidationError();
259 // Clear existing mnemonic and passphrase
261 DOM
.passphrase
.val("");
263 if (rootKeyChangedTimeoutEvent
!= null) {
264 clearTimeout(rootKeyChangedTimeoutEvent
);
266 rootKeyChangedTimeoutEvent
= setTimeout(rootKeyChanged
, 400);
269 function rootKeyChanged() {
271 hideValidationError();
272 var rootKeyBase58
= DOM
.rootKey
.val();
273 var errorText
= validateRootKey(rootKeyBase58
);
275 showValidationError(errorText
);
278 // Calculate and display
279 calcBip32RootKeyFromBase58(rootKeyBase58
);
280 calcForDerivationPath();
283 function litecoinUseLtubChanged() {
284 litecoinUseLtub
= DOM
.litecoinUseLtub
.prop("checked");
285 if (litecoinUseLtub
) {
286 network
= bitcoinjs
.bitcoin
.networks
.litecoinLtub
;
289 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
294 function calcForDerivationPath() {
296 clearAddressesList();
298 // Don't show bip49 if it's selected but network doesn't support it
299 if (bip49TabSelected() && !networkHasBip49()) {
302 // Get the derivation path
303 var derivationPath
= getDerivationPath();
304 var errorText
= findDerivationPathErrors(derivationPath
);
306 showValidationError(errorText
);
309 bip32ExtendedKey
= calcBip32ExtendedKey(derivationPath
);
310 if (bip44TabSelected()) {
313 if (bip49TabSelected()) {
319 function generateClicked() {
320 if (isUsingOwnEntropy()) {
325 setTimeout(function() {
326 setMnemonicLanguage();
327 var phrase
= generateRandomPhrase();
335 function languageChanged() {
336 setTimeout(function() {
337 setMnemonicLanguage();
338 if (DOM
.phrase
.val().length
> 0) {
339 var newPhrase
= convertPhraseToNewLanguage();
340 DOM
.phrase
.val(newPhrase
);
344 DOM
.generate
.trigger("click");
349 function toggleIndexes() {
350 showIndex
= !showIndex
;
351 $("td.index span").toggleClass("invisible");
354 function toggleAddresses() {
355 showAddress
= !showAddress
;
356 $("td.address span").toggleClass("invisible");
359 function togglePublicKeys() {
360 showPubKey
= !showPubKey
;
361 $("td.pubkey span").toggleClass("invisible");
364 function togglePrivateKeys() {
365 showPrivKey
= !showPrivKey
;
366 $("td.privkey span").toggleClass("invisible");
371 function generateRandomPhrase() {
372 if (!hasStrongRandom()) {
373 var errorText
= "This browser does not support strong randomness";
374 showValidationError(errorText
);
377 var numWords
= parseInt(DOM
.generatedStrength
.val());
378 var strength
= numWords
/ 3 * 32;
379 var words
= mnemonic
.generate(strength
);
380 DOM
.phrase
.val(words
);
384 function calcBip32RootKeyFromSeed(phrase
, passphrase
) {
385 seed
= mnemonic
.toSeed(phrase
, passphrase
);
386 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromSeedHex(seed
, network
);
389 function calcBip32RootKeyFromBase58(rootKeyBase58
) {
390 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
393 function calcBip32ExtendedKey(path
) {
394 // Check there's a root key to derive from
398 var extendedKey
= bip32RootKey
;
399 // Derive the key from the path
400 var pathBits
= path
.split("/");
401 for (var i
=0; i
<pathBits
.length
; i
++) {
402 var bit
= pathBits
[i
];
403 var index
= parseInt(bit
);
407 var hardened
= bit
[bit
.length
-1] == "'";
408 var isPriv
= !(extendedKey
.isNeutered());
409 var invalidDerivationPath
= hardened
&& !isPriv
;
410 if (invalidDerivationPath
) {
414 extendedKey
= extendedKey
.deriveHardened(index
);
417 extendedKey
= extendedKey
.derive(index
);
423 function showValidationError(errorText
) {
429 function hideValidationError() {
435 function findPhraseErrors(phrase
) {
436 // Preprocess the words
437 phrase
= mnemonic
.normalizeString(phrase
);
438 var words
= phraseToWordArray(phrase
);
439 // Detect blank phrase
440 if (words
.length
== 0) {
441 return "Blank mnemonic";
444 for (var i
=0; i
<words
.length
; i
++) {
446 var language
= getLanguage();
447 if (WORDLISTS
[language
].indexOf(word
) == -1) {
448 console
.log("Finding closest match to " + word
);
449 var nearestWord
= findNearestWord(word
);
450 return word
+ " not in wordlist, did you mean " + nearestWord
+ "?";
453 // Check the words are valid
454 var properPhrase
= wordArrayToPhrase(words
);
455 var isValid
= mnemonic
.check(properPhrase
);
457 return "Invalid mnemonic";
462 function validateRootKey(rootKeyBase58
) {
464 bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
467 return "Invalid root key";
472 function getDerivationPath() {
473 if (bip44TabSelected()) {
474 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
475 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
476 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
477 var change
= parseIntNoNaN(DOM
.bip44change
.val(), 0);
479 path
+= purpose
+ "'/";
481 path
+= account
+ "'/";
483 DOM
.bip44path
.val(path
);
484 var derivationPath
= DOM
.bip44path
.val();
485 console
.log("Using derivation path from BIP44 tab: " + derivationPath
);
486 return derivationPath
;
488 if (bip49TabSelected()) {
489 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
490 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
491 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
492 var change
= parseIntNoNaN(DOM
.bip49change
.val(), 0);
494 path
+= purpose
+ "'/";
496 path
+= account
+ "'/";
498 DOM
.bip49path
.val(path
);
499 var derivationPath
= DOM
.bip49path
.val();
500 console
.log("Using derivation path from BIP49 tab: " + derivationPath
);
501 return derivationPath
;
503 else if (bip32TabSelected()) {
504 var derivationPath
= DOM
.bip32path
.val();
505 console
.log("Using derivation path from BIP32 tab: " + derivationPath
);
506 return derivationPath
;
509 console
.log("Unknown derivation path");
513 function findDerivationPathErrors(path
) {
514 // TODO is not perfect but is better than nothing
516 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
518 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
519 var maxDepth
= 255; // TODO verify this!!
520 var maxIndexValue
= Math
.pow(2, 31); // TODO verify this!!
521 if (path
[0] != "m") {
522 return "First character must be 'm'";
524 if (path
.length
> 1) {
525 if (path
[1] != "/") {
526 return "Separator must be '/'";
528 var indexes
= path
.split("/");
529 if (indexes
.length
> maxDepth
) {
530 return "Derivation depth is " + indexes
.length
+ ", must be less than " + maxDepth
;
532 for (var depth
= 1; depth
<indexes
.length
; depth
++) {
533 var index
= indexes
[depth
];
534 var invalidChars
= index
.replace(/^[0-9]+'?$/g, "")
535 if (invalidChars
.length
> 0) {
536 return "Invalid characters " + invalidChars
+ " found at depth " + depth
;
538 var indexValue
= parseInt(index
.replace("'", ""));
540 return "Invalid number at depth " + depth
;
542 if (indexValue
> maxIndexValue
) {
543 return "Value of " + indexValue
+ " at depth " + depth
+ " must be less than " + maxIndexValue
;
547 // Check root key exists or else derivation path is useless!
549 return "No root key";
551 // Check no hardened derivation path when using xpub keys
552 var hardenedPath
= path
.indexOf("'") > -1;
553 var hardenedAddresses
= bip32TabSelected() && DOM
.hardenedAddresses
.prop("checked");
554 var hardened
= hardenedPath
|| hardenedAddresses
;
555 var isXpubkey
= bip32RootKey
.isNeutered();
556 if (hardened
&& isXpubkey
) {
557 return "Hardened derivation path is invalid with xpub key";
562 function displayBip44Info() {
563 // Get the derivation path for the account
564 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
565 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
566 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
568 path
+= purpose
+ "'/";
570 path
+= account
+ "'/";
571 // Calculate the account extended keys
572 var accountExtendedKey
= calcBip32ExtendedKey(path
);
573 var accountXprv
= accountExtendedKey
.toBase58();
574 var accountXpub
= accountExtendedKey
.neutered().toBase58();
575 // Display the extended keys
576 DOM
.bip44accountXprv
.val(accountXprv
);
577 DOM
.bip44accountXpub
.val(accountXpub
);
580 function displayBip49Info() {
581 // Get the derivation path for the account
582 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
583 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
584 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
586 path
+= purpose
+ "'/";
588 path
+= account
+ "'/";
589 // Calculate the account extended keys
590 var accountExtendedKey
= calcBip32ExtendedKey(path
);
591 var accountXprv
= accountExtendedKey
.toBase58();
592 var accountXpub
= accountExtendedKey
.neutered().toBase58();
593 // Display the extended keys
594 DOM
.bip49accountXprv
.val(accountXprv
);
595 DOM
.bip49accountXpub
.val(accountXpub
);
598 function displayBip32Info() {
601 var rootKey
= bip32RootKey
.toBase58();
602 DOM
.rootKey
.val(rootKey
);
603 var xprvkeyB58
= "NA";
604 if (!bip32ExtendedKey
.isNeutered()) {
605 xprvkeyB58
= bip32ExtendedKey
.toBase58();
607 var extendedPrivKey
= xprvkeyB58
;
608 DOM
.extendedPrivKey
.val(extendedPrivKey
);
609 var extendedPubKey
= bip32ExtendedKey
.neutered().toBase58();
610 DOM
.extendedPubKey
.val(extendedPubKey
);
611 // Display the addresses and privkeys
612 clearAddressesList();
613 displayAddresses(0, 20);
616 function displayAddresses(start
, total
) {
617 generationProcesses
.push(new (function() {
621 this.stop = function() {
622 for (var i
=0; i
<rows
.length
; i
++) {
623 rows
[i
].shouldGenerate
= false;
628 for (var i
=0; i
<total
; i
++) {
629 var index
= i
+ start
;
630 var isLast
= i
== total
- 1;
631 rows
.push(new TableRow(index
, isLast
));
637 function TableRow(index
, isLast
) {
640 this.shouldGenerate
= true;
641 var useHardenedAddresses
= DOM
.hardenedAddresses
.prop("checked");
642 var isP2wpkhNestedInP2sh
= bip49TabSelected() || (bip32TabSelected() && useP2wpkhNestedInP2sh());
643 var p2wpkhNestedInP2shAvailable
= networkHasBip49();
649 function calculateValues() {
650 setTimeout(function() {
651 if (!self
.shouldGenerate
) {
655 if (useHardenedAddresses
) {
656 key
= bip32ExtendedKey
.deriveHardened(index
);
659 key
= bip32ExtendedKey
.derive(index
);
661 var address
= key
.getAddress().toString();
663 if (!key
.isNeutered()) {
664 privkey
= key
.keyPair
.toWIF(network
);
666 var pubkey
= key
.getPublicKeyBuffer().toString('hex');
667 var indexText
= getDerivationPath() + "/" + index
;
668 if (useHardenedAddresses
) {
669 indexText
= indexText
+ "'";
671 // Ethereum values are different
672 if (networks
[DOM
.network
.val()].name
== "ETH - Ethereum") {
673 var privKeyBuffer
= key
.keyPair
.d
.toBuffer();
674 privkey
= privKeyBuffer
.toString('hex');
675 var addressBuffer
= ethUtil
.privateToAddress(privKeyBuffer
);
676 var hexAddress
= addressBuffer
.toString('hex');
677 var checksumAddress
= ethUtil
.toChecksumAddress(hexAddress
);
678 address
= ethUtil
.addHexPrefix(checksumAddress
);
679 privkey
= ethUtil
.addHexPrefix(privkey
);
680 pubkey
= ethUtil
.addHexPrefix(pubkey
);
682 // Ripple values are different
683 if (networks
[DOM
.network
.val()].name
== "XRP - Ripple") {
684 privkey
= convertRipplePriv(privkey
);
685 address
= convertRippleAdrr(address
);
687 // BIP49 addresses are different
688 if (isP2wpkhNestedInP2sh
) {
689 if (!p2wpkhNestedInP2shAvailable
) {
692 var keyhash
= bitcoinjs
.bitcoin
.crypto
.hash160(key
.getPublicKeyBuffer());
693 var scriptsig
= bitcoinjs
.bitcoin
.script
.witnessPubKeyHash
.output
.encode(keyhash
);
694 var addressbytes
= bitcoinjs
.bitcoin
.crypto
.hash160(scriptsig
);
695 var scriptpubkey
= bitcoinjs
.bitcoin
.script
.scriptHash
.output
.encode(addressbytes
);
696 address
= bitcoinjs
.bitcoin
.address
.fromOutputScript(scriptpubkey
, network
)
698 addAddressToList(indexText
, address
, pubkey
, privkey
);
709 function showMore() {
710 var start
= DOM
.addresses
.children().length
;
711 var rowsToAdd
= parseInt(DOM
.rowsToAdd
.val());
712 if (isNaN(rowsToAdd
)) {
714 DOM
.rowsToAdd
.val("20");
716 if (rowsToAdd
> 200) {
717 var msg
= "Generating " + rowsToAdd
+ " rows could take a while. ";
718 msg
+= "Do you want to continue?";
723 displayAddresses(start
, rowsToAdd
);
726 function clearDisplay() {
727 clearAddressesList();
729 hideValidationError();
732 function clearAddressesList() {
733 DOM
.addresses
.empty();
737 function stopGenerating() {
738 while (generationProcesses
.length
> 0) {
739 var generation
= generationProcesses
.shift();
744 function clearKeys() {
749 function clearRootKey() {
753 function clearDerivedKeys() {
754 DOM
.extendedPrivKey
.val("");
755 DOM
.extendedPubKey
.val("");
756 DOM
.bip44accountXprv
.val("");
757 DOM
.bip44accountXpub
.val("");
760 function addAddressToList(indexText
, address
, pubkey
, privkey
) {
761 var row
= $(addressRowTemplate
.html());
763 var indexCell
= row
.find(".index span");
764 var addressCell
= row
.find(".address span");
765 var pubkeyCell
= row
.find(".pubkey span");
766 var privkeyCell
= row
.find(".privkey span");
768 indexCell
.text(indexText
);
769 addressCell
.text(address
);
770 pubkeyCell
.text(pubkey
);
771 privkeyCell
.text(privkey
);
774 indexCell
.addClass("invisible");
777 addressCell
.addClass("invisible");
780 pubkeyCell
.addClass("invisible");
783 privkeyCell
.addClass("invisible");
785 DOM
.addresses
.append(row
);
786 var rowShowQrEls
= row
.find("[data-show-qr]");
787 setQrEvents(rowShowQrEls
);
790 function hasStrongRandom() {
791 return 'crypto' in window
&& window
['crypto'] !== null;
794 function disableForms() {
795 $("form").on("submit", function(e
) {
800 function parseIntNoNaN(val
, defaultVal
) {
801 var v
= parseInt(val
);
808 function showPending() {
810 .text("Calculating...")
814 function findNearestWord(word
) {
815 var language
= getLanguage();
816 var words
= WORDLISTS
[language
];
817 var minDistance
= 99;
818 var closestWord
= words
[0];
819 for (var i
=0; i
<words
.length
; i
++) {
820 var comparedTo
= words
[i
];
821 if (comparedTo
.indexOf(word
) == 0) {
824 var distance
= Levenshtein
.get(word
, comparedTo
);
825 if (distance
< minDistance
) {
826 closestWord
= comparedTo
;
827 minDistance
= distance
;
833 function hidePending() {
839 function populateNetworkSelect() {
840 for (var i
=0; i
<networks
.length
; i
++) {
841 var network
= networks
[i
];
842 var option
= $("<option>");
843 option
.attr("value", i
);
844 option
.text(network
.name
);
845 if (network
.name
== "BTC - Bitcoin") {
846 option
.prop("selected", true);
848 DOM
.phraseNetwork
.append(option
);
852 function populateClientSelect() {
853 for (var i
=0; i
<clients
.length
; i
++) {
854 var client
= clients
[i
];
855 var option
= $("<option>");
856 option
.attr("value", i
);
857 option
.text(client
.name
);
858 DOM
.bip32Client
.append(option
);
862 function getLanguage() {
863 var defaultLanguage
= "english";
864 // Try to get from existing phrase
865 var language
= getLanguageFromPhrase();
866 // Try to get from url if not from phrase
867 if (language
.length
== 0) {
868 language
= getLanguageFromUrl();
870 // Default to English if no other option
871 if (language
.length
== 0) {
872 language
= defaultLanguage
;
877 function getLanguageFromPhrase(phrase
) {
878 // Check if how many words from existing phrase match a language.
881 phrase
= DOM
.phrase
.val();
883 if (phrase
.length
> 0) {
884 var words
= phraseToWordArray(phrase
);
885 var languageMatches
= {};
886 for (l
in WORDLISTS
) {
887 // Track how many words match in this language
888 languageMatches
[l
] = 0;
889 for (var i
=0; i
<words
.length
; i
++) {
890 var wordInLanguage
= WORDLISTS
[l
].indexOf(words
[i
]) > -1;
891 if (wordInLanguage
) {
892 languageMatches
[l
]++;
895 // Find languages with most word matches.
896 // This is made difficult due to commonalities between Chinese
897 // simplified vs traditional.
899 var mostMatchedLanguages
= [];
900 for (var l
in languageMatches
) {
901 var numMatches
= languageMatches
[l
];
902 if (numMatches
> mostMatches
) {
903 mostMatches
= numMatches
;
904 mostMatchedLanguages
= [l
];
906 else if (numMatches
== mostMatches
) {
907 mostMatchedLanguages
.push(l
);
911 if (mostMatchedLanguages
.length
> 0) {
912 // Use first language and warn if multiple detected
913 language
= mostMatchedLanguages
[0];
914 if (mostMatchedLanguages
.length
> 1) {
915 console
.warn("Multiple possible languages");
916 console
.warn(mostMatchedLanguages
);
923 function getLanguageFromUrl() {
924 for (var language
in WORDLISTS
) {
925 if (window
.location
.hash
.indexOf(language
) > -1) {
932 function setMnemonicLanguage() {
933 var language
= getLanguage();
934 // Load the bip39 mnemonic generator for this language if required
935 if (!(language
in mnemonics
)) {
936 mnemonics
[language
] = new Mnemonic(language
);
938 mnemonic
= mnemonics
[language
];
941 function convertPhraseToNewLanguage() {
942 var oldLanguage
= getLanguageFromPhrase();
943 var newLanguage
= getLanguageFromUrl();
944 var oldPhrase
= DOM
.phrase
.val();
945 var oldWords
= phraseToWordArray(oldPhrase
);
947 for (var i
=0; i
<oldWords
.length
; i
++) {
948 var oldWord
= oldWords
[i
];
949 var index
= WORDLISTS
[oldLanguage
].indexOf(oldWord
);
950 var newWord
= WORDLISTS
[newLanguage
][index
];
951 newWords
.push(newWord
);
953 newPhrase
= wordArrayToPhrase(newWords
);
957 // TODO look at jsbip39 - mnemonic.splitWords
958 function phraseToWordArray(phrase
) {
959 var words
= phrase
.split(/\s/g);
961 for (var i
=0; i
<words
.length
; i
++) {
963 if (word
.length
> 0) {
970 // TODO look at jsbip39 - mnemonic.joinWords
971 function wordArrayToPhrase(words
) {
972 var phrase
= words
.join(" ");
973 var language
= getLanguageFromPhrase(phrase
);
974 if (language
== "japanese") {
975 phrase
= words
.join("\u3000");
980 function isUsingOwnEntropy() {
981 return DOM
.useEntropy
.prop("checked");
984 function setMnemonicFromEntropy() {
985 clearEntropyFeedback();
987 var entropyStr
= DOM
.entropy
.val();
988 // Work out minimum base for entropy
989 var entropy
= Entropy
.fromString(entropyStr
);
990 if (entropy
.binaryStr
.length
== 0) {
993 // Show entropy details
994 showEntropyFeedback(entropy
);
995 // Use entropy hash if not using raw entropy
996 var bits
= entropy
.binaryStr
;
997 var mnemonicLength
= DOM
.entropyMnemonicLength
.val();
998 if (mnemonicLength
!= "raw") {
999 // Get bits by hashing entropy with SHA256
1000 var hash
= sjcl
.hash
.sha256
.hash(entropy
.cleanStr
);
1001 var hex
= sjcl
.codec
.hex
.fromBits(hash
);
1002 bits
= BigInteger
.parse(hex
, 16).toString(2);
1003 while (bits
.length
% 256 != 0) {
1006 // Truncate hash to suit number of words
1007 mnemonicLength
= parseInt(mnemonicLength
);
1008 var numberOfBits
= 32 * mnemonicLength
/ 3;
1009 bits
= bits
.substring(0, numberOfBits
);
1011 // Discard trailing entropy
1012 var bitsToUse
= Math
.floor(bits
.length
/ 32) * 32;
1013 var start
= bits
.length
- bitsToUse
;
1014 var binaryStr
= bits
.substring(start
);
1015 // Convert entropy string to numeric array
1016 var entropyArr
= [];
1017 for (var i
=0; i
<binaryStr
.length
/ 8; i
++) {
1018 var byteAsBits
= binaryStr
.substring(i
*8, i
*8+8);
1019 var entropyByte
= parseInt(byteAsBits
, 2);
1020 entropyArr
.push(entropyByte
)
1022 // Convert entropy array to mnemonic
1023 var phrase
= mnemonic
.toMnemonic(entropyArr
);
1024 // Set the mnemonic in the UI
1025 DOM
.phrase
.val(phrase
);
1028 function clearEntropyFeedback() {
1029 DOM
.entropyCrackTime
.text("...");
1030 DOM
.entropyType
.text("");
1031 DOM
.entropyWordCount
.text("0");
1032 DOM
.entropyEventCount
.text("0");
1033 DOM
.entropyBitsPerEvent
.text("0");
1034 DOM
.entropyBits
.text("0");
1035 DOM
.entropyFiltered
.html(" ");
1036 DOM
.entropyBinary
.html(" ");
1039 function showEntropyFeedback(entropy
) {
1040 var numberOfBits
= entropy
.binaryStr
.length
;
1041 var timeToCrack
= "unknown";
1043 var z
= zxcvbn(entropy
.base
.parts
.join(""));
1044 timeToCrack
= z
.crack_times_display
.offline_fast_hashing_1e10_per_second
;
1045 if (z
.feedback
.warning
!= "") {
1046 timeToCrack
= timeToCrack
+ " - " + z
.feedback
.warning
;
1050 console
.log("Error detecting entropy strength with zxcvbn:");
1053 var entropyTypeStr
= getEntropyTypeStr(entropy
);
1054 var wordCount
= Math
.floor(numberOfBits
/ 32) * 3;
1055 var bitsPerEvent
= entropy
.bitsPerEvent
.toFixed(2);
1056 DOM
.entropyFiltered
.html(entropy
.cleanHtml
);
1057 DOM
.entropyType
.text(entropyTypeStr
);
1058 DOM
.entropyCrackTime
.text(timeToCrack
);
1059 DOM
.entropyEventCount
.text(entropy
.base
.ints
.length
);
1060 DOM
.entropyBits
.text(numberOfBits
);
1061 DOM
.entropyWordCount
.text(wordCount
);
1062 DOM
.entropyBinary
.text(entropy
.binaryStr
);
1063 DOM
.entropyBitsPerEvent
.text(bitsPerEvent
);
1066 function getEntropyTypeStr(entropy
) {
1067 var typeStr
= entropy
.base
.str
;
1068 // Add some detail if these are cards
1069 if (entropy
.base
.asInt
== 52) {
1070 var cardDetail
= []; // array of message strings
1071 // Detect duplicates
1073 var dupeTracker
= {};
1074 for (var i
=0; i
<entropy
.base
.parts
.length
; i
++) {
1075 var card
= entropy
.base
.parts
[i
];
1076 var cardUpper
= card
.toUpperCase();
1077 if (cardUpper
in dupeTracker
) {
1080 dupeTracker
[cardUpper
] = true;
1082 if (dupes
.length
> 0) {
1083 var dupeWord
= "duplicates";
1084 if (dupes
.length
== 1) {
1085 dupeWord
= "duplicate";
1087 var msg
= dupes
.length
+ " " + dupeWord
+ ": " + dupes
.slice(0,3).join(" ");
1088 if (dupes
.length
> 3) {
1091 cardDetail
.push(msg
);
1094 var uniqueCards
= [];
1095 for (var uniqueCard
in dupeTracker
) {
1096 uniqueCards
.push(uniqueCard
);
1098 if (uniqueCards
.length
== 52) {
1099 cardDetail
.unshift("full deck");
1101 // Detect missing cards
1102 var values
= "A23456789TJQK";
1104 var missingCards
= [];
1105 for (var i
=0; i
<suits
.length
; i
++) {
1106 for (var j
=0; j
<values
.length
; j
++) {
1107 var card
= values
[j
] + suits
[i
];
1108 if (!(card
in dupeTracker
)) {
1109 missingCards
.push(card
);
1113 // Display missing cards if six or less, ie clearly going for full deck
1114 if (missingCards
.length
> 0 && missingCards
.length
<= 6) {
1115 var msg
= missingCards
.length
+ " missing: " + missingCards
.slice(0,3).join(" ");
1116 if (missingCards
.length
> 3) {
1119 cardDetail
.push(msg
);
1121 // Add card details to typeStr
1122 if (cardDetail
.length
> 0) {
1123 typeStr
+= " (" + cardDetail
.join(", ") + ")";
1129 function setQrEvents(els
) {
1130 els
.on("mouseenter", createQr
);
1131 els
.on("mouseleave", destroyQr
);
1132 els
.on("click", toggleQr
);
1135 function createQr(e
) {
1136 var content
= e
.target
.textContent
|| e
.target
.value
;
1139 DOM
.qrImage
.qrcode({width: size
, height: size
, text: content
});
1141 DOM
.qrHider
.addClass("hidden");
1144 DOM
.qrHider
.removeClass("hidden");
1146 DOM
.qrContainer
.removeClass("hidden");
1150 function destroyQr() {
1151 DOM
.qrImage
.text("");
1152 DOM
.qrContainer
.addClass("hidden");
1155 function toggleQr() {
1157 DOM
.qrHider
.toggleClass("hidden");
1158 DOM
.qrHint
.toggleClass("hidden");
1161 function bip44TabSelected() {
1162 return DOM
.bip44tab
.hasClass("active");
1165 function bip32TabSelected() {
1166 return DOM
.bip32tab
.hasClass("active");
1169 function useP2wpkhNestedInP2sh() {
1170 return DOM
.useP2wpkhNestedInP2sh
.prop("checked");
1173 function networkHasBip49() {
1174 return networks
[DOM
.network
.val()].p2wpkhNestedInP2shAvailable
;
1177 function bip49TabSelected() {
1178 return DOM
.bip49tab
.hasClass("active");
1181 function setHdCoin(coinValue
) {
1182 DOM
.bip44coin
.val(coinValue
);
1183 DOM
.bip49coin
.val(coinValue
);
1186 function showP2wpkhNestedInP2shAvailable() {
1187 DOM
.bip49unavailable
.addClass("hidden");
1188 DOM
.bip49available
.removeClass("hidden");
1189 DOM
.useP2wpkhNestedInP2sh
.prop("disabled", false);
1192 function showP2wpkhNestedInP2shUnavailable() {
1193 DOM
.bip49available
.addClass("hidden");
1194 DOM
.bip49unavailable
.removeClass("hidden");
1195 DOM
.useP2wpkhNestedInP2sh
.prop("disabled", true);
1196 DOM
.useP2wpkhNestedInP2sh
.prop("checked", false);
1201 name: "BCH - Bitcoin Cash",
1202 p2wpkhNestedInP2shAvailable: false,
1203 onSelect: function() {
1204 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1209 name: "BTC - Bitcoin",
1210 p2wpkhNestedInP2shAvailable: true,
1211 onSelect: function() {
1212 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1217 name: "BTC - Bitcoin Testnet",
1218 p2wpkhNestedInP2shAvailable: true,
1219 onSelect: function() {
1220 network
= bitcoinjs
.bitcoin
.networks
.testnet
;
1225 name: "CLAM - Clams",
1226 p2wpkhNestedInP2shAvailable: false,
1227 onSelect: function() {
1228 network
= bitcoinjs
.bitcoin
.networks
.clam
;
1233 name: "CRW - Crown",
1234 p2wpkhNestedInP2shAvailable: false,
1235 onSelect: function() {
1236 network
= bitcoinjs
.bitcoin
.networks
.crown
;
1241 name: "DASH - Dash",
1242 p2wpkhNestedInP2shAvailable: false,
1243 onSelect: function() {
1244 network
= bitcoinjs
.bitcoin
.networks
.dash
;
1249 name: "DASH - Dash Testnet",
1250 p2wpkhNestedInP2shAvailable: false,
1251 onSelect: function() {
1252 network
= bitcoinjs
.bitcoin
.networks
.dashtn
;
1257 name: "DOGE - Dogecoin",
1258 p2wpkhNestedInP2shAvailable: false,
1259 onSelect: function() {
1260 network
= bitcoinjs
.bitcoin
.networks
.dogecoin
;
1265 name: "ETH - Ethereum",
1266 p2wpkhNestedInP2shAvailable: false,
1267 onSelect: function() {
1268 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1273 name: "GAME - GameCredits",
1274 p2wpkhNestedInP2shAvailable: false,
1275 onSelect: function() {
1276 network
= bitcoinjs
.bitcoin
.networks
.game
;
1281 name: "JBS - Jumbucks",
1282 p2wpkhNestedInP2shAvailable: false,
1283 onSelect: function() {
1284 network
= bitcoinjs
.bitcoin
.networks
.jumbucks
;
1289 name: "LTC - Litecoin",
1290 p2wpkhNestedInP2shAvailable: false,
1291 onSelect: function() {
1292 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
1294 DOM
.litecoinLtubContainer
.removeClass("hidden");
1298 name: "MAZA - Maza",
1299 p2wpkhNestedInP2shAvailable: false,
1300 onSelect: function() {
1301 network
= bitcoinjs
.bitcoin
.networks
.maza
;
1307 name: "NMC - Namecoin",
1308 p2wpkhNestedInP2shAvailable: false,
1309 onSelect: function() {
1310 network
= bitcoinjs
.bitcoin
.networks
.namecoin
;
1315 name: "PIVX - PIVX",
1316 p2wpkhNestedInP2shAvailable: false,
1317 onSelect: function() {
1318 network
= bitcoinjs
.bitcoin
.networks
.pivx
;
1323 name: "PIVX - PIVX Testnet",
1324 p2wpkhNestedInP2shAvailable: false,
1325 onSelect: function() {
1326 network
= bitcoinjs
.bitcoin
.networks
.pivxtestnet
;
1331 name: "PPC - Peercoin",
1332 p2wpkhNestedInP2shAvailable: false,
1333 onSelect: function() {
1334 network
= bitcoinjs
.bitcoin
.networks
.peercoin
;
1339 name: "SDC - ShadowCash",
1340 p2wpkhNestedInP2shAvailable: false,
1341 onSelect: function() {
1342 network
= bitcoinjs
.bitcoin
.networks
.shadow
;
1347 name: "SDC - ShadowCash Testnet",
1348 p2wpkhNestedInP2shAvailable: false,
1349 onSelect: function() {
1350 network
= bitcoinjs
.bitcoin
.networks
.shadowtn
;
1355 name: "SLM - Slimcoin",
1356 p2wpkhNestedInP2shAvailable: false,
1357 onSelect: function() {
1358 network
= bitcoinjs
.bitcoin
.networks
.slimcoin
;
1363 name: "SLM - Slimcoin Testnet",
1364 p2wpkhNestedInP2shAvailable: false,
1365 onSelect: function() {
1366 network
= bitcoinjs
.bitcoin
.networks
.slimcointn
;
1371 name: "VIA - Viacoin",
1372 p2wpkhNestedInP2shAvailable: false,
1373 onSelect: function() {
1374 network
= bitcoinjs
.bitcoin
.networks
.viacoin
;
1379 name: "VIA - Viacoin Testnet",
1380 p2wpkhNestedInP2shAvailable: false,
1381 onSelect: function() {
1382 network
= bitcoinjs
.bitcoin
.networks
.viacointestnet
;
1387 name: "XMY - Myriadcoin",
1388 p2wpkhNestedInP2shAvailable: false,
1389 onSelect: function() {
1390 network
= bitcoinjs
.bitcoin
.networks
.myriadcoin
;
1395 name: "XRP - Ripple",
1396 p2wpkhNestedInP2shAvailable: false,
1397 onSelect: function() {
1398 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1406 name: "Bitcoin Core",
1407 onSelect: function() {
1408 DOM
.bip32path
.val("m/0'/0'");
1409 DOM
.hardenedAddresses
.prop('checked', true);
1413 name: "blockchain.info",
1414 onSelect: function() {
1415 DOM
.bip32path
.val("m/44'/0'/0'");
1416 DOM
.hardenedAddresses
.prop('checked', false);
1420 name: "MultiBit HD",
1421 onSelect: function() {
1422 DOM
.bip32path
.val("m/0'/0");
1423 DOM
.hardenedAddresses
.prop('checked', false);