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
.entropyFilterWarning
= DOM
.entropyContainer
.find(".filter-warning");
42 DOM
.phrase
= $(".phrase");
43 DOM
.passphrase
= $(".passphrase");
44 DOM
.generateContainer
= $(".generate-container");
45 DOM
.generate
= $(".generate");
46 DOM
.seed
= $(".seed");
47 DOM
.rootKey
= $(".root-key");
48 DOM
.litecoinLtubContainer
= $(".litecoin-ltub-container");
49 DOM
.litecoinUseLtub
= $(".litecoin-use-ltub");
50 DOM
.extendedPrivKey
= $(".extended-priv-key");
51 DOM
.extendedPubKey
= $(".extended-pub-key");
52 DOM
.bip32tab
= $("#bip32-tab");
53 DOM
.bip44tab
= $("#bip44-tab");
54 DOM
.bip49tab
= $("#bip49-tab");
55 DOM
.bip32panel
= $("#bip32");
56 DOM
.bip44panel
= $("#bip44");
57 DOM
.bip49panel
= $("#bip49");
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");
63 DOM
.bip44accountXprv
= $("#bip44 .account-xprv");
64 DOM
.bip44accountXpub
= $("#bip44 .account-xpub");
65 DOM
.bip44change
= $("#bip44 .change");
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");
75 DOM
.generatedStrength
= $(".generate-container .strength");
76 DOM
.hardenedAddresses
= $(".hardened-addresses");
77 DOM
.useP2wpkhNestedInP2sh
= $(".p2wpkh-nested-in-p2sh");
78 DOM
.useBitpayAddressesContainer
= $(".use-bitpay-addresses-container");
79 DOM
.useBitpayAddresses
= $(".use-bitpay-addresses");
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");
87 DOM
.publicKeyToggle
= $(".public-key-toggle");
88 DOM
.privateKeyToggle
= $(".private-key-toggle");
89 DOM
.languages
= $(".languages a");
90 DOM
.qrContainer
= $(".qr-container");
91 DOM
.qrHider
= DOM
.qrContainer
.find(".qr-hider");
92 DOM
.qrImage
= DOM
.qrContainer
.find(".qr-image");
93 DOM
.qrHint
= DOM
.qrContainer
.find(".qr-hint");
94 DOM
.showQrEls
= $("[data-show-qr]");
98 DOM
.network
.on("change", networkChanged
);
99 DOM
.bip32Client
.on("change", bip32ClientChanged
);
100 DOM
.useEntropy
.on("change", setEntropyVisibility
);
101 DOM
.entropy
.on("input", delayedEntropyChanged
);
102 DOM
.entropyMnemonicLength
.on("change", entropyChanged
);
103 DOM
.phrase
.on("input", delayedPhraseChanged
);
104 DOM
.passphrase
.on("input", delayedPhraseChanged
);
105 DOM
.generate
.on("click", generateClicked
);
106 DOM
.more
.on("click", showMore
);
107 DOM
.rootKey
.on("input", delayedRootKeyChanged
);
108 DOM
.litecoinUseLtub
.on("change", litecoinUseLtubChanged
);
109 DOM
.bip32path
.on("input", calcForDerivationPath
);
110 DOM
.bip44account
.on("input", calcForDerivationPath
);
111 DOM
.bip44change
.on("input", calcForDerivationPath
);
112 DOM
.bip49account
.on("input", calcForDerivationPath
);
113 DOM
.bip49change
.on("input", calcForDerivationPath
);
114 DOM
.tab
.on("shown.bs.tab", calcForDerivationPath
);
115 DOM
.hardenedAddresses
.on("change", calcForDerivationPath
);
116 DOM
.useP2wpkhNestedInP2sh
.on("change", calcForDerivationPath
);
117 DOM
.indexToggle
.on("click", toggleIndexes
);
118 DOM
.addressToggle
.on("click", toggleAddresses
);
119 DOM
.publicKeyToggle
.on("click", togglePublicKeys
);
120 DOM
.privateKeyToggle
.on("click", togglePrivateKeys
);
121 DOM
.languages
.on("click", languageChanged
);
122 DOM
.useBitpayAddresses
.on("change", useBitpayAddressesChange
);
123 setQrEvents(DOM
.showQrEls
);
126 hideValidationError();
127 populateNetworkSelect();
128 populateClientSelect();
133 function networkChanged(e
) {
135 clearAddressesList();
136 DOM
.litecoinLtubContainer
.addClass("hidden");
137 DOM
.useBitpayAddressesContainer
.addClass("hidden");
138 var networkIndex
= e
.target
.value
;
139 var network
= networks
[networkIndex
];
141 if (network
.p2wpkhNestedInP2shAvailable
) {
142 showP2wpkhNestedInP2shAvailable();
145 showP2wpkhNestedInP2shUnavailable();
155 function bip32ClientChanged(e
) {
156 var clientIndex
= DOM
.bip32Client
.val();
157 if (clientIndex
== "custom") {
158 DOM
.bip32path
.prop("readonly", false);
161 DOM
.bip32path
.prop("readonly", true);
162 clients
[clientIndex
].onSelect();
172 function setEntropyVisibility() {
173 if (isUsingOwnEntropy()) {
174 DOM
.entropyContainer
.removeClass("hidden");
175 DOM
.generateContainer
.addClass("hidden");
176 DOM
.phrase
.prop("readonly", true);
181 DOM
.entropyContainer
.addClass("hidden");
182 DOM
.generateContainer
.removeClass("hidden");
183 DOM
.phrase
.prop("readonly", false);
188 function delayedPhraseChanged() {
189 hideValidationError();
192 bip32ExtendedKey
= null;
193 clearAddressesList();
195 if (phraseChangeTimeoutEvent
!= null) {
196 clearTimeout(phraseChangeTimeoutEvent
);
198 phraseChangeTimeoutEvent
= setTimeout(phraseChanged
, 400);
201 function phraseChanged() {
203 setMnemonicLanguage();
204 // Get the mnemonic phrase
205 var phrase
= DOM
.phrase
.val();
206 var errorText
= findPhraseErrors(phrase
);
208 showValidationError(errorText
);
211 // Calculate and display
212 var passphrase
= DOM
.passphrase
.val();
213 calcBip32RootKeyFromSeed(phrase
, passphrase
);
214 calcForDerivationPath();
217 function delayedEntropyChanged() {
218 hideValidationError();
220 if (entropyChangeTimeoutEvent
!= null) {
221 clearTimeout(entropyChangeTimeoutEvent
);
223 entropyChangeTimeoutEvent
= setTimeout(entropyChanged
, 400);
226 function entropyChanged() {
227 // If blank entropy, clear mnemonic, addresses, errors
228 if (DOM
.entropy
.val().trim().length
== 0) {
230 clearEntropyFeedback();
232 showValidationError("Blank entropy");
235 // Get the current phrase to detect changes
236 var phrase
= DOM
.phrase
.val();
237 // Set the phrase from the entropy
238 setMnemonicFromEntropy();
239 // Recalc addresses if the phrase has changed
240 var newPhrase
= DOM
.phrase
.val();
241 if (newPhrase
!= phrase
) {
242 if (newPhrase
.length
== 0) {
254 function delayedRootKeyChanged() {
255 // Warn if there is an existing mnemonic or passphrase.
256 if (DOM
.phrase
.val().length
> 0 || DOM
.passphrase
.val().length
> 0) {
257 if (!confirm("This will clear existing mnemonic and passphrase")) {
258 DOM
.rootKey
.val(bip32RootKey
);
262 hideValidationError();
264 // Clear existing mnemonic and passphrase
266 DOM
.passphrase
.val("");
268 if (rootKeyChangedTimeoutEvent
!= null) {
269 clearTimeout(rootKeyChangedTimeoutEvent
);
271 rootKeyChangedTimeoutEvent
= setTimeout(rootKeyChanged
, 400);
274 function rootKeyChanged() {
276 hideValidationError();
277 var rootKeyBase58
= DOM
.rootKey
.val();
278 var errorText
= validateRootKey(rootKeyBase58
);
280 showValidationError(errorText
);
283 // Calculate and display
284 calcBip32RootKeyFromBase58(rootKeyBase58
);
285 calcForDerivationPath();
288 function litecoinUseLtubChanged() {
289 litecoinUseLtub
= DOM
.litecoinUseLtub
.prop("checked");
290 if (litecoinUseLtub
) {
291 network
= bitcoinjs
.bitcoin
.networks
.litecoinLtub
;
294 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
299 function calcForDerivationPath() {
301 clearAddressesList();
303 // Don't show bip49 if it's selected but network doesn't support it
304 if (bip49TabSelected() && !networkHasBip49()) {
307 // Get the derivation path
308 var derivationPath
= getDerivationPath();
309 var errorText
= findDerivationPathErrors(derivationPath
);
311 showValidationError(errorText
);
314 bip32ExtendedKey
= calcBip32ExtendedKey(derivationPath
);
315 if (bip44TabSelected()) {
318 if (bip49TabSelected()) {
324 function generateClicked() {
325 if (isUsingOwnEntropy()) {
330 setTimeout(function() {
331 setMnemonicLanguage();
332 var phrase
= generateRandomPhrase();
340 function languageChanged() {
341 setTimeout(function() {
342 setMnemonicLanguage();
343 if (DOM
.phrase
.val().length
> 0) {
344 var newPhrase
= convertPhraseToNewLanguage();
345 DOM
.phrase
.val(newPhrase
);
349 DOM
.generate
.trigger("click");
354 function useBitpayAddressesChange() {
355 setBitcoinCashNetworkValues();
359 function toggleIndexes() {
360 showIndex
= !showIndex
;
361 $("td.index span").toggleClass("invisible");
364 function toggleAddresses() {
365 showAddress
= !showAddress
;
366 $("td.address span").toggleClass("invisible");
369 function togglePublicKeys() {
370 showPubKey
= !showPubKey
;
371 $("td.pubkey span").toggleClass("invisible");
374 function togglePrivateKeys() {
375 showPrivKey
= !showPrivKey
;
376 $("td.privkey span").toggleClass("invisible");
381 function generateRandomPhrase() {
382 if (!hasStrongRandom()) {
383 var errorText
= "This browser does not support strong randomness";
384 showValidationError(errorText
);
387 var numWords
= parseInt(DOM
.generatedStrength
.val());
388 var strength
= numWords
/ 3 * 32;
389 var words
= mnemonic
.generate(strength
);
390 DOM
.phrase
.val(words
);
394 function calcBip32RootKeyFromSeed(phrase
, passphrase
) {
395 seed
= mnemonic
.toSeed(phrase
, passphrase
);
396 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromSeedHex(seed
, network
);
399 function calcBip32RootKeyFromBase58(rootKeyBase58
) {
400 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
403 function calcBip32ExtendedKey(path
) {
404 // Check there's a root key to derive from
408 var extendedKey
= bip32RootKey
;
409 // Derive the key from the path
410 var pathBits
= path
.split("/");
411 for (var i
=0; i
<pathBits
.length
; i
++) {
412 var bit
= pathBits
[i
];
413 var index
= parseInt(bit
);
417 var hardened
= bit
[bit
.length
-1] == "'";
418 var isPriv
= !(extendedKey
.isNeutered());
419 var invalidDerivationPath
= hardened
&& !isPriv
;
420 if (invalidDerivationPath
) {
424 extendedKey
= extendedKey
.deriveHardened(index
);
427 extendedKey
= extendedKey
.derive(index
);
433 function showValidationError(errorText
) {
439 function hideValidationError() {
445 function findPhraseErrors(phrase
) {
446 // Preprocess the words
447 phrase
= mnemonic
.normalizeString(phrase
);
448 var words
= phraseToWordArray(phrase
);
449 // Detect blank phrase
450 if (words
.length
== 0) {
451 return "Blank mnemonic";
454 for (var i
=0; i
<words
.length
; i
++) {
456 var language
= getLanguage();
457 if (WORDLISTS
[language
].indexOf(word
) == -1) {
458 console
.log("Finding closest match to " + word
);
459 var nearestWord
= findNearestWord(word
);
460 return word
+ " not in wordlist, did you mean " + nearestWord
+ "?";
463 // Check the words are valid
464 var properPhrase
= wordArrayToPhrase(words
);
465 var isValid
= mnemonic
.check(properPhrase
);
467 return "Invalid mnemonic";
472 function validateRootKey(rootKeyBase58
) {
474 bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
477 return "Invalid root key";
482 function getDerivationPath() {
483 if (bip44TabSelected()) {
484 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
485 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
486 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
487 var change
= parseIntNoNaN(DOM
.bip44change
.val(), 0);
489 path
+= purpose
+ "'/";
491 path
+= account
+ "'/";
493 DOM
.bip44path
.val(path
);
494 var derivationPath
= DOM
.bip44path
.val();
495 console
.log("Using derivation path from BIP44 tab: " + derivationPath
);
496 return derivationPath
;
498 if (bip49TabSelected()) {
499 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
500 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
501 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
502 var change
= parseIntNoNaN(DOM
.bip49change
.val(), 0);
504 path
+= purpose
+ "'/";
506 path
+= account
+ "'/";
508 DOM
.bip49path
.val(path
);
509 var derivationPath
= DOM
.bip49path
.val();
510 console
.log("Using derivation path from BIP49 tab: " + derivationPath
);
511 return derivationPath
;
513 else if (bip32TabSelected()) {
514 var derivationPath
= DOM
.bip32path
.val();
515 console
.log("Using derivation path from BIP32 tab: " + derivationPath
);
516 return derivationPath
;
519 console
.log("Unknown derivation path");
523 function findDerivationPathErrors(path
) {
524 // TODO is not perfect but is better than nothing
526 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
528 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
529 var maxDepth
= 255; // TODO verify this!!
530 var maxIndexValue
= Math
.pow(2, 31); // TODO verify this!!
531 if (path
[0] != "m") {
532 return "First character must be 'm'";
534 if (path
.length
> 1) {
535 if (path
[1] != "/") {
536 return "Separator must be '/'";
538 var indexes
= path
.split("/");
539 if (indexes
.length
> maxDepth
) {
540 return "Derivation depth is " + indexes
.length
+ ", must be less than " + maxDepth
;
542 for (var depth
= 1; depth
<indexes
.length
; depth
++) {
543 var index
= indexes
[depth
];
544 var invalidChars
= index
.replace(/^[0-9]+'?$/g, "")
545 if (invalidChars
.length
> 0) {
546 return "Invalid characters " + invalidChars
+ " found at depth " + depth
;
548 var indexValue
= parseInt(index
.replace("'", ""));
550 return "Invalid number at depth " + depth
;
552 if (indexValue
> maxIndexValue
) {
553 return "Value of " + indexValue
+ " at depth " + depth
+ " must be less than " + maxIndexValue
;
557 // Check root key exists or else derivation path is useless!
559 return "No root key";
561 // Check no hardened derivation path when using xpub keys
562 var hardenedPath
= path
.indexOf("'") > -1;
563 var hardenedAddresses
= bip32TabSelected() && DOM
.hardenedAddresses
.prop("checked");
564 var hardened
= hardenedPath
|| hardenedAddresses
;
565 var isXpubkey
= bip32RootKey
.isNeutered();
566 if (hardened
&& isXpubkey
) {
567 return "Hardened derivation path is invalid with xpub key";
572 function displayBip44Info() {
573 // Get the derivation path for the account
574 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
575 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
576 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
578 path
+= purpose
+ "'/";
580 path
+= account
+ "'/";
581 // Calculate the account extended keys
582 var accountExtendedKey
= calcBip32ExtendedKey(path
);
583 var accountXprv
= accountExtendedKey
.toBase58();
584 var accountXpub
= accountExtendedKey
.neutered().toBase58();
585 // Display the extended keys
586 DOM
.bip44accountXprv
.val(accountXprv
);
587 DOM
.bip44accountXpub
.val(accountXpub
);
590 function displayBip49Info() {
591 // Get the derivation path for the account
592 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
593 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
594 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
596 path
+= purpose
+ "'/";
598 path
+= account
+ "'/";
599 // Calculate the account extended keys
600 var accountExtendedKey
= calcBip32ExtendedKey(path
);
601 var accountXprv
= accountExtendedKey
.toBase58();
602 var accountXpub
= accountExtendedKey
.neutered().toBase58();
603 // Display the extended keys
604 DOM
.bip49accountXprv
.val(accountXprv
);
605 DOM
.bip49accountXpub
.val(accountXpub
);
608 function displayBip32Info() {
611 var rootKey
= bip32RootKey
.toBase58();
612 DOM
.rootKey
.val(rootKey
);
613 var xprvkeyB58
= "NA";
614 if (!bip32ExtendedKey
.isNeutered()) {
615 xprvkeyB58
= bip32ExtendedKey
.toBase58();
617 var extendedPrivKey
= xprvkeyB58
;
618 DOM
.extendedPrivKey
.val(extendedPrivKey
);
619 var extendedPubKey
= bip32ExtendedKey
.neutered().toBase58();
620 DOM
.extendedPubKey
.val(extendedPubKey
);
621 // Display the addresses and privkeys
622 clearAddressesList();
623 displayAddresses(0, 20);
626 function displayAddresses(start
, total
) {
627 generationProcesses
.push(new (function() {
631 this.stop = function() {
632 for (var i
=0; i
<rows
.length
; i
++) {
633 rows
[i
].shouldGenerate
= false;
638 for (var i
=0; i
<total
; i
++) {
639 var index
= i
+ start
;
640 var isLast
= i
== total
- 1;
641 rows
.push(new TableRow(index
, isLast
));
647 function TableRow(index
, isLast
) {
650 this.shouldGenerate
= true;
651 var useHardenedAddresses
= DOM
.hardenedAddresses
.prop("checked");
652 var isP2wpkhNestedInP2sh
= bip49TabSelected() || (bip32TabSelected() && useP2wpkhNestedInP2sh());
653 var p2wpkhNestedInP2shAvailable
= networkHasBip49();
659 function calculateValues() {
660 setTimeout(function() {
661 if (!self
.shouldGenerate
) {
665 if (useHardenedAddresses
) {
666 key
= bip32ExtendedKey
.deriveHardened(index
);
669 key
= bip32ExtendedKey
.derive(index
);
671 var address
= key
.getAddress().toString();
673 if (!key
.isNeutered()) {
674 privkey
= key
.keyPair
.toWIF(network
);
676 var pubkey
= key
.getPublicKeyBuffer().toString('hex');
677 var indexText
= getDerivationPath() + "/" + index
;
678 if (useHardenedAddresses
) {
679 indexText
= indexText
+ "'";
681 // Ethereum values are different
682 if (networks
[DOM
.network
.val()].name
== "ETH - Ethereum") {
683 var privKeyBuffer
= key
.keyPair
.d
.toBuffer();
684 privkey
= privKeyBuffer
.toString('hex');
685 var addressBuffer
= ethUtil
.privateToAddress(privKeyBuffer
);
686 var hexAddress
= addressBuffer
.toString('hex');
687 var checksumAddress
= ethUtil
.toChecksumAddress(hexAddress
);
688 address
= ethUtil
.addHexPrefix(checksumAddress
);
689 privkey
= ethUtil
.addHexPrefix(privkey
);
690 pubkey
= ethUtil
.addHexPrefix(pubkey
);
692 // Ripple values are different
693 if (networks
[DOM
.network
.val()].name
== "XRP - Ripple") {
694 privkey
= convertRipplePriv(privkey
);
695 address
= convertRippleAdrr(address
);
697 // BIP49 addresses are different
698 if (isP2wpkhNestedInP2sh
) {
699 if (!p2wpkhNestedInP2shAvailable
) {
702 var keyhash
= bitcoinjs
.bitcoin
.crypto
.hash160(key
.getPublicKeyBuffer());
703 var scriptsig
= bitcoinjs
.bitcoin
.script
.witnessPubKeyHash
.output
.encode(keyhash
);
704 var addressbytes
= bitcoinjs
.bitcoin
.crypto
.hash160(scriptsig
);
705 var scriptpubkey
= bitcoinjs
.bitcoin
.script
.scriptHash
.output
.encode(addressbytes
);
706 address
= bitcoinjs
.bitcoin
.address
.fromOutputScript(scriptpubkey
, network
)
708 addAddressToList(indexText
, address
, pubkey
, privkey
);
719 function showMore() {
720 var start
= DOM
.addresses
.children().length
;
721 var rowsToAdd
= parseInt(DOM
.rowsToAdd
.val());
722 if (isNaN(rowsToAdd
)) {
724 DOM
.rowsToAdd
.val("20");
726 if (rowsToAdd
> 200) {
727 var msg
= "Generating " + rowsToAdd
+ " rows could take a while. ";
728 msg
+= "Do you want to continue?";
733 displayAddresses(start
, rowsToAdd
);
736 function clearDisplay() {
737 clearAddressesList();
739 hideValidationError();
742 function clearAddressesList() {
743 DOM
.addresses
.empty();
747 function stopGenerating() {
748 while (generationProcesses
.length
> 0) {
749 var generation
= generationProcesses
.shift();
754 function clearKeys() {
759 function clearRootKey() {
763 function clearDerivedKeys() {
764 DOM
.extendedPrivKey
.val("");
765 DOM
.extendedPubKey
.val("");
766 DOM
.bip44accountXprv
.val("");
767 DOM
.bip44accountXpub
.val("");
770 function addAddressToList(indexText
, address
, pubkey
, privkey
) {
771 var row
= $(addressRowTemplate
.html());
773 var indexCell
= row
.find(".index span");
774 var addressCell
= row
.find(".address span");
775 var pubkeyCell
= row
.find(".pubkey span");
776 var privkeyCell
= row
.find(".privkey span");
778 indexCell
.text(indexText
);
779 addressCell
.text(address
);
780 pubkeyCell
.text(pubkey
);
781 privkeyCell
.text(privkey
);
784 indexCell
.addClass("invisible");
787 addressCell
.addClass("invisible");
790 pubkeyCell
.addClass("invisible");
793 privkeyCell
.addClass("invisible");
795 DOM
.addresses
.append(row
);
796 var rowShowQrEls
= row
.find("[data-show-qr]");
797 setQrEvents(rowShowQrEls
);
800 function hasStrongRandom() {
801 return 'crypto' in window
&& window
['crypto'] !== null;
804 function disableForms() {
805 $("form").on("submit", function(e
) {
810 function parseIntNoNaN(val
, defaultVal
) {
811 var v
= parseInt(val
);
818 function showPending() {
820 .text("Calculating...")
824 function findNearestWord(word
) {
825 var language
= getLanguage();
826 var words
= WORDLISTS
[language
];
827 var minDistance
= 99;
828 var closestWord
= words
[0];
829 for (var i
=0; i
<words
.length
; i
++) {
830 var comparedTo
= words
[i
];
831 if (comparedTo
.indexOf(word
) == 0) {
834 var distance
= Levenshtein
.get(word
, comparedTo
);
835 if (distance
< minDistance
) {
836 closestWord
= comparedTo
;
837 minDistance
= distance
;
843 function hidePending() {
849 function populateNetworkSelect() {
850 for (var i
=0; i
<networks
.length
; i
++) {
851 var network
= networks
[i
];
852 var option
= $("<option>");
853 option
.attr("value", i
);
854 option
.text(network
.name
);
855 if (network
.name
== "BTC - Bitcoin") {
856 option
.prop("selected", true);
858 DOM
.phraseNetwork
.append(option
);
862 function populateClientSelect() {
863 for (var i
=0; i
<clients
.length
; i
++) {
864 var client
= clients
[i
];
865 var option
= $("<option>");
866 option
.attr("value", i
);
867 option
.text(client
.name
);
868 DOM
.bip32Client
.append(option
);
872 function getLanguage() {
873 var defaultLanguage
= "english";
874 // Try to get from existing phrase
875 var language
= getLanguageFromPhrase();
876 // Try to get from url if not from phrase
877 if (language
.length
== 0) {
878 language
= getLanguageFromUrl();
880 // Default to English if no other option
881 if (language
.length
== 0) {
882 language
= defaultLanguage
;
887 function getLanguageFromPhrase(phrase
) {
888 // Check if how many words from existing phrase match a language.
891 phrase
= DOM
.phrase
.val();
893 if (phrase
.length
> 0) {
894 var words
= phraseToWordArray(phrase
);
895 var languageMatches
= {};
896 for (l
in WORDLISTS
) {
897 // Track how many words match in this language
898 languageMatches
[l
] = 0;
899 for (var i
=0; i
<words
.length
; i
++) {
900 var wordInLanguage
= WORDLISTS
[l
].indexOf(words
[i
]) > -1;
901 if (wordInLanguage
) {
902 languageMatches
[l
]++;
905 // Find languages with most word matches.
906 // This is made difficult due to commonalities between Chinese
907 // simplified vs traditional.
909 var mostMatchedLanguages
= [];
910 for (var l
in languageMatches
) {
911 var numMatches
= languageMatches
[l
];
912 if (numMatches
> mostMatches
) {
913 mostMatches
= numMatches
;
914 mostMatchedLanguages
= [l
];
916 else if (numMatches
== mostMatches
) {
917 mostMatchedLanguages
.push(l
);
921 if (mostMatchedLanguages
.length
> 0) {
922 // Use first language and warn if multiple detected
923 language
= mostMatchedLanguages
[0];
924 if (mostMatchedLanguages
.length
> 1) {
925 console
.warn("Multiple possible languages");
926 console
.warn(mostMatchedLanguages
);
933 function getLanguageFromUrl() {
934 for (var language
in WORDLISTS
) {
935 if (window
.location
.hash
.indexOf(language
) > -1) {
942 function setMnemonicLanguage() {
943 var language
= getLanguage();
944 // Load the bip39 mnemonic generator for this language if required
945 if (!(language
in mnemonics
)) {
946 mnemonics
[language
] = new Mnemonic(language
);
948 mnemonic
= mnemonics
[language
];
951 function convertPhraseToNewLanguage() {
952 var oldLanguage
= getLanguageFromPhrase();
953 var newLanguage
= getLanguageFromUrl();
954 var oldPhrase
= DOM
.phrase
.val();
955 var oldWords
= phraseToWordArray(oldPhrase
);
957 for (var i
=0; i
<oldWords
.length
; i
++) {
958 var oldWord
= oldWords
[i
];
959 var index
= WORDLISTS
[oldLanguage
].indexOf(oldWord
);
960 var newWord
= WORDLISTS
[newLanguage
][index
];
961 newWords
.push(newWord
);
963 newPhrase
= wordArrayToPhrase(newWords
);
967 // TODO look at jsbip39 - mnemonic.splitWords
968 function phraseToWordArray(phrase
) {
969 var words
= phrase
.split(/\s/g);
971 for (var i
=0; i
<words
.length
; i
++) {
973 if (word
.length
> 0) {
980 // TODO look at jsbip39 - mnemonic.joinWords
981 function wordArrayToPhrase(words
) {
982 var phrase
= words
.join(" ");
983 var language
= getLanguageFromPhrase(phrase
);
984 if (language
== "japanese") {
985 phrase
= words
.join("\u3000");
990 function isUsingOwnEntropy() {
991 return DOM
.useEntropy
.prop("checked");
994 function setMnemonicFromEntropy() {
995 clearEntropyFeedback();
997 var entropyStr
= DOM
.entropy
.val();
998 // Work out minimum base for entropy
999 var entropy
= Entropy
.fromString(entropyStr
);
1000 if (entropy
.binaryStr
.length
== 0) {
1003 // Show entropy details
1004 showEntropyFeedback(entropy
);
1005 // Use entropy hash if not using raw entropy
1006 var bits
= entropy
.binaryStr
;
1007 var mnemonicLength
= DOM
.entropyMnemonicLength
.val();
1008 if (mnemonicLength
!= "raw") {
1009 // Get bits by hashing entropy with SHA256
1010 var hash
= sjcl
.hash
.sha256
.hash(entropy
.cleanStr
);
1011 var hex
= sjcl
.codec
.hex
.fromBits(hash
);
1012 bits
= BigInteger
.parse(hex
, 16).toString(2);
1013 while (bits
.length
% 256 != 0) {
1016 // Truncate hash to suit number of words
1017 mnemonicLength
= parseInt(mnemonicLength
);
1018 var numberOfBits
= 32 * mnemonicLength
/ 3;
1019 bits
= bits
.substring(0, numberOfBits
);
1021 // Discard trailing entropy
1022 var bitsToUse
= Math
.floor(bits
.length
/ 32) * 32;
1023 var start
= bits
.length
- bitsToUse
;
1024 var binaryStr
= bits
.substring(start
);
1025 // Convert entropy string to numeric array
1026 var entropyArr
= [];
1027 for (var i
=0; i
<binaryStr
.length
/ 8; i
++) {
1028 var byteAsBits
= binaryStr
.substring(i
*8, i
*8+8);
1029 var entropyByte
= parseInt(byteAsBits
, 2);
1030 entropyArr
.push(entropyByte
)
1032 // Convert entropy array to mnemonic
1033 var phrase
= mnemonic
.toMnemonic(entropyArr
);
1034 // Set the mnemonic in the UI
1035 DOM
.phrase
.val(phrase
);
1038 function clearEntropyFeedback() {
1039 DOM
.entropyCrackTime
.text("...");
1040 DOM
.entropyType
.text("");
1041 DOM
.entropyWordCount
.text("0");
1042 DOM
.entropyEventCount
.text("0");
1043 DOM
.entropyBitsPerEvent
.text("0");
1044 DOM
.entropyBits
.text("0");
1045 DOM
.entropyFiltered
.html(" ");
1046 DOM
.entropyBinary
.html(" ");
1049 function showEntropyFeedback(entropy
) {
1050 var numberOfBits
= entropy
.binaryStr
.length
;
1051 var timeToCrack
= "unknown";
1053 var z
= zxcvbn(entropy
.base
.parts
.join(""));
1054 timeToCrack
= z
.crack_times_display
.offline_fast_hashing_1e10_per_second
;
1055 if (z
.feedback
.warning
!= "") {
1056 timeToCrack
= timeToCrack
+ " - " + z
.feedback
.warning
;
1060 console
.log("Error detecting entropy strength with zxcvbn:");
1063 var entropyTypeStr
= getEntropyTypeStr(entropy
);
1064 var wordCount
= Math
.floor(numberOfBits
/ 32) * 3;
1065 var bitsPerEvent
= entropy
.bitsPerEvent
.toFixed(2);
1066 DOM
.entropyFiltered
.html(entropy
.cleanHtml
);
1067 DOM
.entropyType
.text(entropyTypeStr
);
1068 DOM
.entropyCrackTime
.text(timeToCrack
);
1069 DOM
.entropyEventCount
.text(entropy
.base
.ints
.length
);
1070 DOM
.entropyBits
.text(numberOfBits
);
1071 DOM
.entropyWordCount
.text(wordCount
);
1072 DOM
.entropyBinary
.text(entropy
.binaryStr
);
1073 DOM
.entropyBitsPerEvent
.text(bitsPerEvent
);
1074 // detect and warn of filtering
1075 var rawNoSpaces
= DOM
.entropy
.val().replace(/\s/g, "");
1076 var cleanNoSpaces
= entropy
.cleanStr
.replace(/\s/g, "");
1077 var isFiltered
= rawNoSpaces
.length
!= cleanNoSpaces
.length
;
1079 DOM
.entropyFilterWarning
.removeClass('hidden');
1082 DOM
.entropyFilterWarning
.addClass('hidden');
1086 function getEntropyTypeStr(entropy
) {
1087 var typeStr
= entropy
.base
.str
;
1088 // Add some detail if these are cards
1089 if (entropy
.base
.asInt
== 52) {
1090 var cardDetail
= []; // array of message strings
1091 // Detect duplicates
1093 var dupeTracker
= {};
1094 for (var i
=0; i
<entropy
.base
.parts
.length
; i
++) {
1095 var card
= entropy
.base
.parts
[i
];
1096 var cardUpper
= card
.toUpperCase();
1097 if (cardUpper
in dupeTracker
) {
1100 dupeTracker
[cardUpper
] = true;
1102 if (dupes
.length
> 0) {
1103 var dupeWord
= "duplicates";
1104 if (dupes
.length
== 1) {
1105 dupeWord
= "duplicate";
1107 var msg
= dupes
.length
+ " " + dupeWord
+ ": " + dupes
.slice(0,3).join(" ");
1108 if (dupes
.length
> 3) {
1111 cardDetail
.push(msg
);
1114 var uniqueCards
= [];
1115 for (var uniqueCard
in dupeTracker
) {
1116 uniqueCards
.push(uniqueCard
);
1118 if (uniqueCards
.length
== 52) {
1119 cardDetail
.unshift("full deck");
1121 // Detect missing cards
1122 var values
= "A23456789TJQK";
1124 var missingCards
= [];
1125 for (var i
=0; i
<suits
.length
; i
++) {
1126 for (var j
=0; j
<values
.length
; j
++) {
1127 var card
= values
[j
] + suits
[i
];
1128 if (!(card
in dupeTracker
)) {
1129 missingCards
.push(card
);
1133 // Display missing cards if six or less, ie clearly going for full deck
1134 if (missingCards
.length
> 0 && missingCards
.length
<= 6) {
1135 var msg
= missingCards
.length
+ " missing: " + missingCards
.slice(0,3).join(" ");
1136 if (missingCards
.length
> 3) {
1139 cardDetail
.push(msg
);
1141 // Add card details to typeStr
1142 if (cardDetail
.length
> 0) {
1143 typeStr
+= " (" + cardDetail
.join(", ") + ")";
1149 function setQrEvents(els
) {
1150 els
.on("mouseenter", createQr
);
1151 els
.on("mouseleave", destroyQr
);
1152 els
.on("click", toggleQr
);
1155 function createQr(e
) {
1156 var content
= e
.target
.textContent
|| e
.target
.value
;
1159 DOM
.qrImage
.qrcode({width: size
, height: size
, text: content
});
1161 DOM
.qrHider
.addClass("hidden");
1164 DOM
.qrHider
.removeClass("hidden");
1166 DOM
.qrContainer
.removeClass("hidden");
1170 function destroyQr() {
1171 DOM
.qrImage
.text("");
1172 DOM
.qrContainer
.addClass("hidden");
1175 function toggleQr() {
1177 DOM
.qrHider
.toggleClass("hidden");
1178 DOM
.qrHint
.toggleClass("hidden");
1181 function bip44TabSelected() {
1182 return DOM
.bip44tab
.hasClass("active");
1185 function bip32TabSelected() {
1186 return DOM
.bip32tab
.hasClass("active");
1189 function useP2wpkhNestedInP2sh() {
1190 return DOM
.useP2wpkhNestedInP2sh
.prop("checked");
1193 function networkHasBip49() {
1194 return networks
[DOM
.network
.val()].p2wpkhNestedInP2shAvailable
;
1197 function bip49TabSelected() {
1198 return DOM
.bip49tab
.hasClass("active");
1201 function setHdCoin(coinValue
) {
1202 DOM
.bip44coin
.val(coinValue
);
1203 DOM
.bip49coin
.val(coinValue
);
1206 function showP2wpkhNestedInP2shAvailable() {
1207 DOM
.bip49unavailable
.addClass("hidden");
1208 DOM
.bip49available
.removeClass("hidden");
1209 DOM
.useP2wpkhNestedInP2sh
.prop("disabled", false);
1212 function showP2wpkhNestedInP2shUnavailable() {
1213 DOM
.bip49available
.addClass("hidden");
1214 DOM
.bip49unavailable
.removeClass("hidden");
1215 DOM
.useP2wpkhNestedInP2sh
.prop("disabled", true);
1216 DOM
.useP2wpkhNestedInP2sh
.prop("checked", false);
1219 function useBitpayAddresses() {
1220 return !(DOM
.useBitpayAddresses
.prop("checked"));
1223 function setBitcoinCashNetworkValues() {
1224 if (useBitpayAddresses()) {
1225 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1228 network
= bitcoinjs
.bitcoin
.networks
.bitcoinCashBitbpay
;
1234 name: "BCH - Bitcoin Cash",
1235 p2wpkhNestedInP2shAvailable: false,
1236 onSelect: function() {
1237 DOM
.useBitpayAddressesContainer
.removeClass("hidden");
1238 setBitcoinCashNetworkValues();
1243 name: "BTC - Bitcoin",
1244 p2wpkhNestedInP2shAvailable: true,
1245 onSelect: function() {
1246 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1251 name: "BTC - Bitcoin Testnet",
1252 p2wpkhNestedInP2shAvailable: true,
1253 onSelect: function() {
1254 network
= bitcoinjs
.bitcoin
.networks
.testnet
;
1259 name: "CLAM - Clams",
1260 p2wpkhNestedInP2shAvailable: false,
1261 onSelect: function() {
1262 network
= bitcoinjs
.bitcoin
.networks
.clam
;
1267 name: "CRW - Crown",
1268 p2wpkhNestedInP2shAvailable: false,
1269 onSelect: function() {
1270 network
= bitcoinjs
.bitcoin
.networks
.crown
;
1275 name: "DASH - Dash",
1276 p2wpkhNestedInP2shAvailable: false,
1277 onSelect: function() {
1278 network
= bitcoinjs
.bitcoin
.networks
.dash
;
1283 name: "DASH - Dash Testnet",
1284 p2wpkhNestedInP2shAvailable: false,
1285 onSelect: function() {
1286 network
= bitcoinjs
.bitcoin
.networks
.dashtn
;
1291 name: "DOGE - Dogecoin",
1292 p2wpkhNestedInP2shAvailable: false,
1293 onSelect: function() {
1294 network
= bitcoinjs
.bitcoin
.networks
.dogecoin
;
1299 name: "ETH - Ethereum",
1300 p2wpkhNestedInP2shAvailable: false,
1301 onSelect: function() {
1302 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1307 name: "FJC - Fujicoin",
1308 p2wpkhNestedInP2shAvailable: false,
1309 onSelect: function() {
1310 network
= bitcoinjs
.bitcoin
.networks
.fujicoin
;
1315 name: "GAME - GameCredits",
1316 p2wpkhNestedInP2shAvailable: false,
1317 onSelect: function() {
1318 network
= bitcoinjs
.bitcoin
.networks
.game
;
1323 name: "JBS - Jumbucks",
1324 p2wpkhNestedInP2shAvailable: false,
1325 onSelect: function() {
1326 network
= bitcoinjs
.bitcoin
.networks
.jumbucks
;
1331 name: "LTC - Litecoin",
1332 p2wpkhNestedInP2shAvailable: false,
1333 onSelect: function() {
1334 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
1336 DOM
.litecoinLtubContainer
.removeClass("hidden");
1340 name: "MAZA - Maza",
1341 p2wpkhNestedInP2shAvailable: false,
1342 onSelect: function() {
1343 network
= bitcoinjs
.bitcoin
.networks
.maza
;
1349 name: "NMC - Namecoin",
1350 p2wpkhNestedInP2shAvailable: false,
1351 onSelect: function() {
1352 network
= bitcoinjs
.bitcoin
.networks
.namecoin
;
1357 name: "PIVX - PIVX",
1358 p2wpkhNestedInP2shAvailable: false,
1359 onSelect: function() {
1360 network
= bitcoinjs
.bitcoin
.networks
.pivx
;
1365 name: "PIVX - PIVX Testnet",
1366 p2wpkhNestedInP2shAvailable: false,
1367 onSelect: function() {
1368 network
= bitcoinjs
.bitcoin
.networks
.pivxtestnet
;
1373 name: "PPC - Peercoin",
1374 p2wpkhNestedInP2shAvailable: false,
1375 onSelect: function() {
1376 network
= bitcoinjs
.bitcoin
.networks
.peercoin
;
1381 name: "SDC - ShadowCash",
1382 p2wpkhNestedInP2shAvailable: false,
1383 onSelect: function() {
1384 network
= bitcoinjs
.bitcoin
.networks
.shadow
;
1389 name: "SDC - ShadowCash Testnet",
1390 p2wpkhNestedInP2shAvailable: false,
1391 onSelect: function() {
1392 network
= bitcoinjs
.bitcoin
.networks
.shadowtn
;
1397 name: "SLM - Slimcoin",
1398 p2wpkhNestedInP2shAvailable: false,
1399 onSelect: function() {
1400 network
= bitcoinjs
.bitcoin
.networks
.slimcoin
;
1405 name: "SLM - Slimcoin Testnet",
1406 p2wpkhNestedInP2shAvailable: false,
1407 onSelect: function() {
1408 network
= bitcoinjs
.bitcoin
.networks
.slimcointn
;
1413 name: "USNBT - NuBits",
1414 p2wpkhNestedInP2shAvailable: false,
1415 onSelect: function() {
1416 network
= bitcoinjs
.bitcoin
.networks
.nubits
;
1421 name: "VIA - Viacoin",
1422 p2wpkhNestedInP2shAvailable: false,
1423 onSelect: function() {
1424 network
= bitcoinjs
.bitcoin
.networks
.viacoin
;
1429 name: "VIA - Viacoin Testnet",
1430 p2wpkhNestedInP2shAvailable: false,
1431 onSelect: function() {
1432 network
= bitcoinjs
.bitcoin
.networks
.viacointestnet
;
1437 name: "XMY - Myriadcoin",
1438 p2wpkhNestedInP2shAvailable: false,
1439 onSelect: function() {
1440 network
= bitcoinjs
.bitcoin
.networks
.myriadcoin
;
1445 name: "XRP - Ripple",
1446 p2wpkhNestedInP2shAvailable: false,
1447 onSelect: function() {
1448 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1456 name: "Bitcoin Core",
1457 onSelect: function() {
1458 DOM
.bip32path
.val("m/0'/0'");
1459 DOM
.hardenedAddresses
.prop('checked', true);
1463 name: "blockchain.info",
1464 onSelect: function() {
1465 DOM
.bip32path
.val("m/44'/0'/0'");
1466 DOM
.hardenedAddresses
.prop('checked', false);
1470 name: "MultiBit HD",
1471 onSelect: function() {
1472 DOM
.bip32path
.val("m/0'/0");
1473 DOM
.hardenedAddresses
.prop('checked', false);