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
.addresses
= $(".addresses");
79 DOM
.rowsToAdd
= $(".rows-to-add");
80 DOM
.more
= $(".more");
81 DOM
.feedback
= $(".feedback");
82 DOM
.tab
= $(".derivation-type a");
83 DOM
.indexToggle
= $(".index-toggle");
84 DOM
.addressToggle
= $(".address-toggle");
85 DOM
.publicKeyToggle
= $(".public-key-toggle");
86 DOM
.privateKeyToggle
= $(".private-key-toggle");
87 DOM
.languages
= $(".languages a");
88 DOM
.qrContainer
= $(".qr-container");
89 DOM
.qrHider
= DOM
.qrContainer
.find(".qr-hider");
90 DOM
.qrImage
= DOM
.qrContainer
.find(".qr-image");
91 DOM
.qrHint
= DOM
.qrContainer
.find(".qr-hint");
92 DOM
.showQrEls
= $("[data-show-qr]");
96 DOM
.network
.on("change", networkChanged
);
97 DOM
.bip32Client
.on("change", bip32ClientChanged
);
98 DOM
.useEntropy
.on("change", setEntropyVisibility
);
99 DOM
.entropy
.on("input", delayedEntropyChanged
);
100 DOM
.entropyMnemonicLength
.on("change", entropyChanged
);
101 DOM
.phrase
.on("input", delayedPhraseChanged
);
102 DOM
.passphrase
.on("input", delayedPhraseChanged
);
103 DOM
.generate
.on("click", generateClicked
);
104 DOM
.more
.on("click", showMore
);
105 DOM
.rootKey
.on("input", delayedRootKeyChanged
);
106 DOM
.litecoinUseLtub
.on("change", litecoinUseLtubChanged
);
107 DOM
.bip32path
.on("input", calcForDerivationPath
);
108 DOM
.bip44account
.on("input", calcForDerivationPath
);
109 DOM
.bip44change
.on("input", calcForDerivationPath
);
110 DOM
.bip49account
.on("input", calcForDerivationPath
);
111 DOM
.bip49change
.on("input", calcForDerivationPath
);
112 DOM
.tab
.on("shown.bs.tab", calcForDerivationPath
);
113 DOM
.hardenedAddresses
.on("change", calcForDerivationPath
);
114 DOM
.useP2wpkhNestedInP2sh
.on("change", calcForDerivationPath
);
115 DOM
.indexToggle
.on("click", toggleIndexes
);
116 DOM
.addressToggle
.on("click", toggleAddresses
);
117 DOM
.publicKeyToggle
.on("click", togglePublicKeys
);
118 DOM
.privateKeyToggle
.on("click", togglePrivateKeys
);
119 DOM
.languages
.on("click", languageChanged
);
120 setQrEvents(DOM
.showQrEls
);
123 hideValidationError();
124 populateNetworkSelect();
125 populateClientSelect();
130 function networkChanged(e
) {
132 clearAddressesList();
133 DOM
.litecoinLtubContainer
.addClass("hidden");
134 var networkIndex
= e
.target
.value
;
135 var network
= networks
[networkIndex
];
137 if (network
.p2wpkhNestedInP2shAvailable
) {
138 showP2wpkhNestedInP2shAvailable();
141 showP2wpkhNestedInP2shUnavailable();
151 function bip32ClientChanged(e
) {
152 var clientIndex
= DOM
.bip32Client
.val();
153 if (clientIndex
== "custom") {
154 DOM
.bip32path
.prop("readonly", false);
157 DOM
.bip32path
.prop("readonly", true);
158 clients
[clientIndex
].onSelect();
168 function setEntropyVisibility() {
169 if (isUsingOwnEntropy()) {
170 DOM
.entropyContainer
.removeClass("hidden");
171 DOM
.generateContainer
.addClass("hidden");
172 DOM
.phrase
.prop("readonly", true);
177 DOM
.entropyContainer
.addClass("hidden");
178 DOM
.generateContainer
.removeClass("hidden");
179 DOM
.phrase
.prop("readonly", false);
184 function delayedPhraseChanged() {
185 hideValidationError();
188 bip32ExtendedKey
= null;
189 clearAddressesList();
191 if (phraseChangeTimeoutEvent
!= null) {
192 clearTimeout(phraseChangeTimeoutEvent
);
194 phraseChangeTimeoutEvent
= setTimeout(phraseChanged
, 400);
197 function phraseChanged() {
199 setMnemonicLanguage();
200 // Get the mnemonic phrase
201 var phrase
= DOM
.phrase
.val();
202 var errorText
= findPhraseErrors(phrase
);
204 showValidationError(errorText
);
207 // Calculate and display
208 var passphrase
= DOM
.passphrase
.val();
209 calcBip32RootKeyFromSeed(phrase
, passphrase
);
210 calcForDerivationPath();
213 function delayedEntropyChanged() {
214 hideValidationError();
216 if (entropyChangeTimeoutEvent
!= null) {
217 clearTimeout(entropyChangeTimeoutEvent
);
219 entropyChangeTimeoutEvent
= setTimeout(entropyChanged
, 400);
222 function entropyChanged() {
223 // If blank entropy, clear mnemonic, addresses, errors
224 if (DOM
.entropy
.val().trim().length
== 0) {
226 clearEntropyFeedback();
228 showValidationError("Blank entropy");
231 // Get the current phrase to detect changes
232 var phrase
= DOM
.phrase
.val();
233 // Set the phrase from the entropy
234 setMnemonicFromEntropy();
235 // Recalc addresses if the phrase has changed
236 var newPhrase
= DOM
.phrase
.val();
237 if (newPhrase
!= phrase
) {
238 if (newPhrase
.length
== 0) {
250 function delayedRootKeyChanged() {
251 // Warn if there is an existing mnemonic or passphrase.
252 if (DOM
.phrase
.val().length
> 0 || DOM
.passphrase
.val().length
> 0) {
253 if (!confirm("This will clear existing mnemonic and passphrase")) {
254 DOM
.rootKey
.val(bip32RootKey
);
258 hideValidationError();
260 // Clear existing mnemonic and passphrase
262 DOM
.passphrase
.val("");
264 if (rootKeyChangedTimeoutEvent
!= null) {
265 clearTimeout(rootKeyChangedTimeoutEvent
);
267 rootKeyChangedTimeoutEvent
= setTimeout(rootKeyChanged
, 400);
270 function rootKeyChanged() {
272 hideValidationError();
273 var rootKeyBase58
= DOM
.rootKey
.val();
274 var errorText
= validateRootKey(rootKeyBase58
);
276 showValidationError(errorText
);
279 // Calculate and display
280 calcBip32RootKeyFromBase58(rootKeyBase58
);
281 calcForDerivationPath();
284 function litecoinUseLtubChanged() {
285 litecoinUseLtub
= DOM
.litecoinUseLtub
.prop("checked");
286 if (litecoinUseLtub
) {
287 network
= bitcoinjs
.bitcoin
.networks
.litecoinLtub
;
290 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
295 function calcForDerivationPath() {
297 clearAddressesList();
299 // Don't show bip49 if it's selected but network doesn't support it
300 if (bip49TabSelected() && !networkHasBip49()) {
303 // Get the derivation path
304 var derivationPath
= getDerivationPath();
305 var errorText
= findDerivationPathErrors(derivationPath
);
307 showValidationError(errorText
);
310 bip32ExtendedKey
= calcBip32ExtendedKey(derivationPath
);
311 if (bip44TabSelected()) {
314 if (bip49TabSelected()) {
320 function generateClicked() {
321 if (isUsingOwnEntropy()) {
326 setTimeout(function() {
327 setMnemonicLanguage();
328 var phrase
= generateRandomPhrase();
336 function languageChanged() {
337 setTimeout(function() {
338 setMnemonicLanguage();
339 if (DOM
.phrase
.val().length
> 0) {
340 var newPhrase
= convertPhraseToNewLanguage();
341 DOM
.phrase
.val(newPhrase
);
345 DOM
.generate
.trigger("click");
350 function toggleIndexes() {
351 showIndex
= !showIndex
;
352 $("td.index span").toggleClass("invisible");
355 function toggleAddresses() {
356 showAddress
= !showAddress
;
357 $("td.address span").toggleClass("invisible");
360 function togglePublicKeys() {
361 showPubKey
= !showPubKey
;
362 $("td.pubkey span").toggleClass("invisible");
365 function togglePrivateKeys() {
366 showPrivKey
= !showPrivKey
;
367 $("td.privkey span").toggleClass("invisible");
372 function generateRandomPhrase() {
373 if (!hasStrongRandom()) {
374 var errorText
= "This browser does not support strong randomness";
375 showValidationError(errorText
);
378 var numWords
= parseInt(DOM
.generatedStrength
.val());
379 var strength
= numWords
/ 3 * 32;
380 var words
= mnemonic
.generate(strength
);
381 DOM
.phrase
.val(words
);
385 function calcBip32RootKeyFromSeed(phrase
, passphrase
) {
386 seed
= mnemonic
.toSeed(phrase
, passphrase
);
387 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromSeedHex(seed
, network
);
390 function calcBip32RootKeyFromBase58(rootKeyBase58
) {
391 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
394 function calcBip32ExtendedKey(path
) {
395 // Check there's a root key to derive from
399 var extendedKey
= bip32RootKey
;
400 // Derive the key from the path
401 var pathBits
= path
.split("/");
402 for (var i
=0; i
<pathBits
.length
; i
++) {
403 var bit
= pathBits
[i
];
404 var index
= parseInt(bit
);
408 var hardened
= bit
[bit
.length
-1] == "'";
409 var isPriv
= !(extendedKey
.isNeutered());
410 var invalidDerivationPath
= hardened
&& !isPriv
;
411 if (invalidDerivationPath
) {
415 extendedKey
= extendedKey
.deriveHardened(index
);
418 extendedKey
= extendedKey
.derive(index
);
424 function showValidationError(errorText
) {
430 function hideValidationError() {
436 function findPhraseErrors(phrase
) {
437 // Preprocess the words
438 phrase
= mnemonic
.normalizeString(phrase
);
439 var words
= phraseToWordArray(phrase
);
440 // Detect blank phrase
441 if (words
.length
== 0) {
442 return "Blank mnemonic";
445 for (var i
=0; i
<words
.length
; i
++) {
447 var language
= getLanguage();
448 if (WORDLISTS
[language
].indexOf(word
) == -1) {
449 console
.log("Finding closest match to " + word
);
450 var nearestWord
= findNearestWord(word
);
451 return word
+ " not in wordlist, did you mean " + nearestWord
+ "?";
454 // Check the words are valid
455 var properPhrase
= wordArrayToPhrase(words
);
456 var isValid
= mnemonic
.check(properPhrase
);
458 return "Invalid mnemonic";
463 function validateRootKey(rootKeyBase58
) {
465 bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
468 return "Invalid root key";
473 function getDerivationPath() {
474 if (bip44TabSelected()) {
475 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
476 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
477 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
478 var change
= parseIntNoNaN(DOM
.bip44change
.val(), 0);
480 path
+= purpose
+ "'/";
482 path
+= account
+ "'/";
484 DOM
.bip44path
.val(path
);
485 var derivationPath
= DOM
.bip44path
.val();
486 console
.log("Using derivation path from BIP44 tab: " + derivationPath
);
487 return derivationPath
;
489 if (bip49TabSelected()) {
490 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
491 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
492 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
493 var change
= parseIntNoNaN(DOM
.bip49change
.val(), 0);
495 path
+= purpose
+ "'/";
497 path
+= account
+ "'/";
499 DOM
.bip49path
.val(path
);
500 var derivationPath
= DOM
.bip49path
.val();
501 console
.log("Using derivation path from BIP49 tab: " + derivationPath
);
502 return derivationPath
;
504 else if (bip32TabSelected()) {
505 var derivationPath
= DOM
.bip32path
.val();
506 console
.log("Using derivation path from BIP32 tab: " + derivationPath
);
507 return derivationPath
;
510 console
.log("Unknown derivation path");
514 function findDerivationPathErrors(path
) {
515 // TODO is not perfect but is better than nothing
517 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
519 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
520 var maxDepth
= 255; // TODO verify this!!
521 var maxIndexValue
= Math
.pow(2, 31); // TODO verify this!!
522 if (path
[0] != "m") {
523 return "First character must be 'm'";
525 if (path
.length
> 1) {
526 if (path
[1] != "/") {
527 return "Separator must be '/'";
529 var indexes
= path
.split("/");
530 if (indexes
.length
> maxDepth
) {
531 return "Derivation depth is " + indexes
.length
+ ", must be less than " + maxDepth
;
533 for (var depth
= 1; depth
<indexes
.length
; depth
++) {
534 var index
= indexes
[depth
];
535 var invalidChars
= index
.replace(/^[0-9]+'?$/g, "")
536 if (invalidChars
.length
> 0) {
537 return "Invalid characters " + invalidChars
+ " found at depth " + depth
;
539 var indexValue
= parseInt(index
.replace("'", ""));
541 return "Invalid number at depth " + depth
;
543 if (indexValue
> maxIndexValue
) {
544 return "Value of " + indexValue
+ " at depth " + depth
+ " must be less than " + maxIndexValue
;
548 // Check root key exists or else derivation path is useless!
550 return "No root key";
552 // Check no hardened derivation path when using xpub keys
553 var hardenedPath
= path
.indexOf("'") > -1;
554 var hardenedAddresses
= bip32TabSelected() && DOM
.hardenedAddresses
.prop("checked");
555 var hardened
= hardenedPath
|| hardenedAddresses
;
556 var isXpubkey
= bip32RootKey
.isNeutered();
557 if (hardened
&& isXpubkey
) {
558 return "Hardened derivation path is invalid with xpub key";
563 function displayBip44Info() {
564 // Get the derivation path for the account
565 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
566 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
567 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
569 path
+= purpose
+ "'/";
571 path
+= account
+ "'/";
572 // Calculate the account extended keys
573 var accountExtendedKey
= calcBip32ExtendedKey(path
);
574 var accountXprv
= accountExtendedKey
.toBase58();
575 var accountXpub
= accountExtendedKey
.neutered().toBase58();
576 // Display the extended keys
577 DOM
.bip44accountXprv
.val(accountXprv
);
578 DOM
.bip44accountXpub
.val(accountXpub
);
581 function displayBip49Info() {
582 // Get the derivation path for the account
583 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
584 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
585 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
587 path
+= purpose
+ "'/";
589 path
+= account
+ "'/";
590 // Calculate the account extended keys
591 var accountExtendedKey
= calcBip32ExtendedKey(path
);
592 var accountXprv
= accountExtendedKey
.toBase58();
593 var accountXpub
= accountExtendedKey
.neutered().toBase58();
594 // Display the extended keys
595 DOM
.bip49accountXprv
.val(accountXprv
);
596 DOM
.bip49accountXpub
.val(accountXpub
);
599 function displayBip32Info() {
602 var rootKey
= bip32RootKey
.toBase58();
603 DOM
.rootKey
.val(rootKey
);
604 var xprvkeyB58
= "NA";
605 if (!bip32ExtendedKey
.isNeutered()) {
606 xprvkeyB58
= bip32ExtendedKey
.toBase58();
608 var extendedPrivKey
= xprvkeyB58
;
609 DOM
.extendedPrivKey
.val(extendedPrivKey
);
610 var extendedPubKey
= bip32ExtendedKey
.neutered().toBase58();
611 DOM
.extendedPubKey
.val(extendedPubKey
);
612 // Display the addresses and privkeys
613 clearAddressesList();
614 displayAddresses(0, 20);
617 function displayAddresses(start
, total
) {
618 generationProcesses
.push(new (function() {
622 this.stop = function() {
623 for (var i
=0; i
<rows
.length
; i
++) {
624 rows
[i
].shouldGenerate
= false;
629 for (var i
=0; i
<total
; i
++) {
630 var index
= i
+ start
;
631 var isLast
= i
== total
- 1;
632 rows
.push(new TableRow(index
, isLast
));
638 function TableRow(index
, isLast
) {
641 this.shouldGenerate
= true;
642 var useHardenedAddresses
= DOM
.hardenedAddresses
.prop("checked");
643 var isP2wpkhNestedInP2sh
= bip49TabSelected() || (bip32TabSelected() && useP2wpkhNestedInP2sh());
644 var p2wpkhNestedInP2shAvailable
= networkHasBip49();
650 function calculateValues() {
651 setTimeout(function() {
652 if (!self
.shouldGenerate
) {
656 if (useHardenedAddresses
) {
657 key
= bip32ExtendedKey
.deriveHardened(index
);
660 key
= bip32ExtendedKey
.derive(index
);
662 var address
= key
.getAddress().toString();
664 if (!key
.isNeutered()) {
665 privkey
= key
.keyPair
.toWIF(network
);
667 var pubkey
= key
.getPublicKeyBuffer().toString('hex');
668 var indexText
= getDerivationPath() + "/" + index
;
669 if (useHardenedAddresses
) {
670 indexText
= indexText
+ "'";
672 // Ethereum values are different
673 if (networks
[DOM
.network
.val()].name
== "ETH - Ethereum") {
674 var privKeyBuffer
= key
.keyPair
.d
.toBuffer();
675 privkey
= privKeyBuffer
.toString('hex');
676 var addressBuffer
= ethUtil
.privateToAddress(privKeyBuffer
);
677 var hexAddress
= addressBuffer
.toString('hex');
678 var checksumAddress
= ethUtil
.toChecksumAddress(hexAddress
);
679 address
= ethUtil
.addHexPrefix(checksumAddress
);
680 privkey
= ethUtil
.addHexPrefix(privkey
);
681 pubkey
= ethUtil
.addHexPrefix(pubkey
);
683 // Ripple values are different
684 if (networks
[DOM
.network
.val()].name
== "XRP - Ripple") {
685 privkey
= convertRipplePriv(privkey
);
686 address
= convertRippleAdrr(address
);
688 // BIP49 addresses are different
689 if (isP2wpkhNestedInP2sh
) {
690 if (!p2wpkhNestedInP2shAvailable
) {
693 var keyhash
= bitcoinjs
.bitcoin
.crypto
.hash160(key
.getPublicKeyBuffer());
694 var scriptsig
= bitcoinjs
.bitcoin
.script
.witnessPubKeyHash
.output
.encode(keyhash
);
695 var addressbytes
= bitcoinjs
.bitcoin
.crypto
.hash160(scriptsig
);
696 var scriptpubkey
= bitcoinjs
.bitcoin
.script
.scriptHash
.output
.encode(addressbytes
);
697 address
= bitcoinjs
.bitcoin
.address
.fromOutputScript(scriptpubkey
, network
)
699 addAddressToList(indexText
, address
, pubkey
, privkey
);
710 function showMore() {
711 var start
= DOM
.addresses
.children().length
;
712 var rowsToAdd
= parseInt(DOM
.rowsToAdd
.val());
713 if (isNaN(rowsToAdd
)) {
715 DOM
.rowsToAdd
.val("20");
717 if (rowsToAdd
> 200) {
718 var msg
= "Generating " + rowsToAdd
+ " rows could take a while. ";
719 msg
+= "Do you want to continue?";
724 displayAddresses(start
, rowsToAdd
);
727 function clearDisplay() {
728 clearAddressesList();
730 hideValidationError();
733 function clearAddressesList() {
734 DOM
.addresses
.empty();
738 function stopGenerating() {
739 while (generationProcesses
.length
> 0) {
740 var generation
= generationProcesses
.shift();
745 function clearKeys() {
750 function clearRootKey() {
754 function clearDerivedKeys() {
755 DOM
.extendedPrivKey
.val("");
756 DOM
.extendedPubKey
.val("");
757 DOM
.bip44accountXprv
.val("");
758 DOM
.bip44accountXpub
.val("");
761 function addAddressToList(indexText
, address
, pubkey
, privkey
) {
762 var row
= $(addressRowTemplate
.html());
764 var indexCell
= row
.find(".index span");
765 var addressCell
= row
.find(".address span");
766 var pubkeyCell
= row
.find(".pubkey span");
767 var privkeyCell
= row
.find(".privkey span");
769 indexCell
.text(indexText
);
770 addressCell
.text(address
);
771 pubkeyCell
.text(pubkey
);
772 privkeyCell
.text(privkey
);
775 indexCell
.addClass("invisible");
778 addressCell
.addClass("invisible");
781 pubkeyCell
.addClass("invisible");
784 privkeyCell
.addClass("invisible");
786 DOM
.addresses
.append(row
);
787 var rowShowQrEls
= row
.find("[data-show-qr]");
788 setQrEvents(rowShowQrEls
);
791 function hasStrongRandom() {
792 return 'crypto' in window
&& window
['crypto'] !== null;
795 function disableForms() {
796 $("form").on("submit", function(e
) {
801 function parseIntNoNaN(val
, defaultVal
) {
802 var v
= parseInt(val
);
809 function showPending() {
811 .text("Calculating...")
815 function findNearestWord(word
) {
816 var language
= getLanguage();
817 var words
= WORDLISTS
[language
];
818 var minDistance
= 99;
819 var closestWord
= words
[0];
820 for (var i
=0; i
<words
.length
; i
++) {
821 var comparedTo
= words
[i
];
822 if (comparedTo
.indexOf(word
) == 0) {
825 var distance
= Levenshtein
.get(word
, comparedTo
);
826 if (distance
< minDistance
) {
827 closestWord
= comparedTo
;
828 minDistance
= distance
;
834 function hidePending() {
840 function populateNetworkSelect() {
841 for (var i
=0; i
<networks
.length
; i
++) {
842 var network
= networks
[i
];
843 var option
= $("<option>");
844 option
.attr("value", i
);
845 option
.text(network
.name
);
846 if (network
.name
== "BTC - Bitcoin") {
847 option
.prop("selected", true);
849 DOM
.phraseNetwork
.append(option
);
853 function populateClientSelect() {
854 for (var i
=0; i
<clients
.length
; i
++) {
855 var client
= clients
[i
];
856 var option
= $("<option>");
857 option
.attr("value", i
);
858 option
.text(client
.name
);
859 DOM
.bip32Client
.append(option
);
863 function getLanguage() {
864 var defaultLanguage
= "english";
865 // Try to get from existing phrase
866 var language
= getLanguageFromPhrase();
867 // Try to get from url if not from phrase
868 if (language
.length
== 0) {
869 language
= getLanguageFromUrl();
871 // Default to English if no other option
872 if (language
.length
== 0) {
873 language
= defaultLanguage
;
878 function getLanguageFromPhrase(phrase
) {
879 // Check if how many words from existing phrase match a language.
882 phrase
= DOM
.phrase
.val();
884 if (phrase
.length
> 0) {
885 var words
= phraseToWordArray(phrase
);
886 var languageMatches
= {};
887 for (l
in WORDLISTS
) {
888 // Track how many words match in this language
889 languageMatches
[l
] = 0;
890 for (var i
=0; i
<words
.length
; i
++) {
891 var wordInLanguage
= WORDLISTS
[l
].indexOf(words
[i
]) > -1;
892 if (wordInLanguage
) {
893 languageMatches
[l
]++;
896 // Find languages with most word matches.
897 // This is made difficult due to commonalities between Chinese
898 // simplified vs traditional.
900 var mostMatchedLanguages
= [];
901 for (var l
in languageMatches
) {
902 var numMatches
= languageMatches
[l
];
903 if (numMatches
> mostMatches
) {
904 mostMatches
= numMatches
;
905 mostMatchedLanguages
= [l
];
907 else if (numMatches
== mostMatches
) {
908 mostMatchedLanguages
.push(l
);
912 if (mostMatchedLanguages
.length
> 0) {
913 // Use first language and warn if multiple detected
914 language
= mostMatchedLanguages
[0];
915 if (mostMatchedLanguages
.length
> 1) {
916 console
.warn("Multiple possible languages");
917 console
.warn(mostMatchedLanguages
);
924 function getLanguageFromUrl() {
925 for (var language
in WORDLISTS
) {
926 if (window
.location
.hash
.indexOf(language
) > -1) {
933 function setMnemonicLanguage() {
934 var language
= getLanguage();
935 // Load the bip39 mnemonic generator for this language if required
936 if (!(language
in mnemonics
)) {
937 mnemonics
[language
] = new Mnemonic(language
);
939 mnemonic
= mnemonics
[language
];
942 function convertPhraseToNewLanguage() {
943 var oldLanguage
= getLanguageFromPhrase();
944 var newLanguage
= getLanguageFromUrl();
945 var oldPhrase
= DOM
.phrase
.val();
946 var oldWords
= phraseToWordArray(oldPhrase
);
948 for (var i
=0; i
<oldWords
.length
; i
++) {
949 var oldWord
= oldWords
[i
];
950 var index
= WORDLISTS
[oldLanguage
].indexOf(oldWord
);
951 var newWord
= WORDLISTS
[newLanguage
][index
];
952 newWords
.push(newWord
);
954 newPhrase
= wordArrayToPhrase(newWords
);
958 // TODO look at jsbip39 - mnemonic.splitWords
959 function phraseToWordArray(phrase
) {
960 var words
= phrase
.split(/\s/g);
962 for (var i
=0; i
<words
.length
; i
++) {
964 if (word
.length
> 0) {
971 // TODO look at jsbip39 - mnemonic.joinWords
972 function wordArrayToPhrase(words
) {
973 var phrase
= words
.join(" ");
974 var language
= getLanguageFromPhrase(phrase
);
975 if (language
== "japanese") {
976 phrase
= words
.join("\u3000");
981 function isUsingOwnEntropy() {
982 return DOM
.useEntropy
.prop("checked");
985 function setMnemonicFromEntropy() {
986 clearEntropyFeedback();
988 var entropyStr
= DOM
.entropy
.val();
989 // Work out minimum base for entropy
990 var entropy
= Entropy
.fromString(entropyStr
);
991 if (entropy
.binaryStr
.length
== 0) {
994 // Show entropy details
995 showEntropyFeedback(entropy
);
996 // Use entropy hash if not using raw entropy
997 var bits
= entropy
.binaryStr
;
998 var mnemonicLength
= DOM
.entropyMnemonicLength
.val();
999 if (mnemonicLength
!= "raw") {
1000 // Get bits by hashing entropy with SHA256
1001 var hash
= sjcl
.hash
.sha256
.hash(entropy
.cleanStr
);
1002 var hex
= sjcl
.codec
.hex
.fromBits(hash
);
1003 bits
= BigInteger
.parse(hex
, 16).toString(2);
1004 while (bits
.length
% 256 != 0) {
1007 // Truncate hash to suit number of words
1008 mnemonicLength
= parseInt(mnemonicLength
);
1009 var numberOfBits
= 32 * mnemonicLength
/ 3;
1010 bits
= bits
.substring(0, numberOfBits
);
1012 // Discard trailing entropy
1013 var bitsToUse
= Math
.floor(bits
.length
/ 32) * 32;
1014 var start
= bits
.length
- bitsToUse
;
1015 var binaryStr
= bits
.substring(start
);
1016 // Convert entropy string to numeric array
1017 var entropyArr
= [];
1018 for (var i
=0; i
<binaryStr
.length
/ 8; i
++) {
1019 var byteAsBits
= binaryStr
.substring(i
*8, i
*8+8);
1020 var entropyByte
= parseInt(byteAsBits
, 2);
1021 entropyArr
.push(entropyByte
)
1023 // Convert entropy array to mnemonic
1024 var phrase
= mnemonic
.toMnemonic(entropyArr
);
1025 // Set the mnemonic in the UI
1026 DOM
.phrase
.val(phrase
);
1029 function clearEntropyFeedback() {
1030 DOM
.entropyCrackTime
.text("...");
1031 DOM
.entropyType
.text("");
1032 DOM
.entropyWordCount
.text("0");
1033 DOM
.entropyEventCount
.text("0");
1034 DOM
.entropyBitsPerEvent
.text("0");
1035 DOM
.entropyBits
.text("0");
1036 DOM
.entropyFiltered
.html(" ");
1037 DOM
.entropyBinary
.html(" ");
1040 function showEntropyFeedback(entropy
) {
1041 var numberOfBits
= entropy
.binaryStr
.length
;
1042 var timeToCrack
= "unknown";
1044 var z
= zxcvbn(entropy
.base
.parts
.join(""));
1045 timeToCrack
= z
.crack_times_display
.offline_fast_hashing_1e10_per_second
;
1046 if (z
.feedback
.warning
!= "") {
1047 timeToCrack
= timeToCrack
+ " - " + z
.feedback
.warning
;
1051 console
.log("Error detecting entropy strength with zxcvbn:");
1054 var entropyTypeStr
= getEntropyTypeStr(entropy
);
1055 var wordCount
= Math
.floor(numberOfBits
/ 32) * 3;
1056 var bitsPerEvent
= entropy
.bitsPerEvent
.toFixed(2);
1057 DOM
.entropyFiltered
.html(entropy
.cleanHtml
);
1058 DOM
.entropyType
.text(entropyTypeStr
);
1059 DOM
.entropyCrackTime
.text(timeToCrack
);
1060 DOM
.entropyEventCount
.text(entropy
.base
.ints
.length
);
1061 DOM
.entropyBits
.text(numberOfBits
);
1062 DOM
.entropyWordCount
.text(wordCount
);
1063 DOM
.entropyBinary
.text(entropy
.binaryStr
);
1064 DOM
.entropyBitsPerEvent
.text(bitsPerEvent
);
1065 // detect and warn of filtering
1066 var rawNoSpaces
= DOM
.entropy
.val().replace(/\s/g, "");
1067 var cleanNoSpaces
= entropy
.cleanStr
.replace(/\s/g, "");
1068 var isFiltered
= rawNoSpaces
.length
!= cleanNoSpaces
.length
;
1070 DOM
.entropyFilterWarning
.removeClass('hidden');
1073 DOM
.entropyFilterWarning
.addClass('hidden');
1077 function getEntropyTypeStr(entropy
) {
1078 var typeStr
= entropy
.base
.str
;
1079 // Add some detail if these are cards
1080 if (entropy
.base
.asInt
== 52) {
1081 var cardDetail
= []; // array of message strings
1082 // Detect duplicates
1084 var dupeTracker
= {};
1085 for (var i
=0; i
<entropy
.base
.parts
.length
; i
++) {
1086 var card
= entropy
.base
.parts
[i
];
1087 var cardUpper
= card
.toUpperCase();
1088 if (cardUpper
in dupeTracker
) {
1091 dupeTracker
[cardUpper
] = true;
1093 if (dupes
.length
> 0) {
1094 var dupeWord
= "duplicates";
1095 if (dupes
.length
== 1) {
1096 dupeWord
= "duplicate";
1098 var msg
= dupes
.length
+ " " + dupeWord
+ ": " + dupes
.slice(0,3).join(" ");
1099 if (dupes
.length
> 3) {
1102 cardDetail
.push(msg
);
1105 var uniqueCards
= [];
1106 for (var uniqueCard
in dupeTracker
) {
1107 uniqueCards
.push(uniqueCard
);
1109 if (uniqueCards
.length
== 52) {
1110 cardDetail
.unshift("full deck");
1112 // Detect missing cards
1113 var values
= "A23456789TJQK";
1115 var missingCards
= [];
1116 for (var i
=0; i
<suits
.length
; i
++) {
1117 for (var j
=0; j
<values
.length
; j
++) {
1118 var card
= values
[j
] + suits
[i
];
1119 if (!(card
in dupeTracker
)) {
1120 missingCards
.push(card
);
1124 // Display missing cards if six or less, ie clearly going for full deck
1125 if (missingCards
.length
> 0 && missingCards
.length
<= 6) {
1126 var msg
= missingCards
.length
+ " missing: " + missingCards
.slice(0,3).join(" ");
1127 if (missingCards
.length
> 3) {
1130 cardDetail
.push(msg
);
1132 // Add card details to typeStr
1133 if (cardDetail
.length
> 0) {
1134 typeStr
+= " (" + cardDetail
.join(", ") + ")";
1140 function setQrEvents(els
) {
1141 els
.on("mouseenter", createQr
);
1142 els
.on("mouseleave", destroyQr
);
1143 els
.on("click", toggleQr
);
1146 function createQr(e
) {
1147 var content
= e
.target
.textContent
|| e
.target
.value
;
1150 DOM
.qrImage
.qrcode({width: size
, height: size
, text: content
});
1152 DOM
.qrHider
.addClass("hidden");
1155 DOM
.qrHider
.removeClass("hidden");
1157 DOM
.qrContainer
.removeClass("hidden");
1161 function destroyQr() {
1162 DOM
.qrImage
.text("");
1163 DOM
.qrContainer
.addClass("hidden");
1166 function toggleQr() {
1168 DOM
.qrHider
.toggleClass("hidden");
1169 DOM
.qrHint
.toggleClass("hidden");
1172 function bip44TabSelected() {
1173 return DOM
.bip44tab
.hasClass("active");
1176 function bip32TabSelected() {
1177 return DOM
.bip32tab
.hasClass("active");
1180 function useP2wpkhNestedInP2sh() {
1181 return DOM
.useP2wpkhNestedInP2sh
.prop("checked");
1184 function networkHasBip49() {
1185 return networks
[DOM
.network
.val()].p2wpkhNestedInP2shAvailable
;
1188 function bip49TabSelected() {
1189 return DOM
.bip49tab
.hasClass("active");
1192 function setHdCoin(coinValue
) {
1193 DOM
.bip44coin
.val(coinValue
);
1194 DOM
.bip49coin
.val(coinValue
);
1197 function showP2wpkhNestedInP2shAvailable() {
1198 DOM
.bip49unavailable
.addClass("hidden");
1199 DOM
.bip49available
.removeClass("hidden");
1200 DOM
.useP2wpkhNestedInP2sh
.prop("disabled", false);
1203 function showP2wpkhNestedInP2shUnavailable() {
1204 DOM
.bip49available
.addClass("hidden");
1205 DOM
.bip49unavailable
.removeClass("hidden");
1206 DOM
.useP2wpkhNestedInP2sh
.prop("disabled", true);
1207 DOM
.useP2wpkhNestedInP2sh
.prop("checked", false);
1212 name: "BCH - Bitcoin Cash",
1213 p2wpkhNestedInP2shAvailable: false,
1214 onSelect: function() {
1215 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1220 name: "BTC - Bitcoin",
1221 p2wpkhNestedInP2shAvailable: true,
1222 onSelect: function() {
1223 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1228 name: "BTC - Bitcoin Testnet",
1229 p2wpkhNestedInP2shAvailable: true,
1230 onSelect: function() {
1231 network
= bitcoinjs
.bitcoin
.networks
.testnet
;
1236 name: "CLAM - Clams",
1237 p2wpkhNestedInP2shAvailable: false,
1238 onSelect: function() {
1239 network
= bitcoinjs
.bitcoin
.networks
.clam
;
1244 name: "CRW - Crown",
1245 p2wpkhNestedInP2shAvailable: false,
1246 onSelect: function() {
1247 network
= bitcoinjs
.bitcoin
.networks
.crown
;
1252 name: "DASH - Dash",
1253 p2wpkhNestedInP2shAvailable: false,
1254 onSelect: function() {
1255 network
= bitcoinjs
.bitcoin
.networks
.dash
;
1260 name: "DASH - Dash Testnet",
1261 p2wpkhNestedInP2shAvailable: false,
1262 onSelect: function() {
1263 network
= bitcoinjs
.bitcoin
.networks
.dashtn
;
1268 name: "DOGE - Dogecoin",
1269 p2wpkhNestedInP2shAvailable: false,
1270 onSelect: function() {
1271 network
= bitcoinjs
.bitcoin
.networks
.dogecoin
;
1276 name: "ETH - Ethereum",
1277 p2wpkhNestedInP2shAvailable: false,
1278 onSelect: function() {
1279 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1284 name: "FJC - Fujicoin",
1285 p2wpkhNestedInP2shAvailable: false,
1286 onSelect: function() {
1287 network
= bitcoinjs
.bitcoin
.networks
.fujicoin
;
1292 name: "GAME - GameCredits",
1293 p2wpkhNestedInP2shAvailable: false,
1294 onSelect: function() {
1295 network
= bitcoinjs
.bitcoin
.networks
.game
;
1300 name: "JBS - Jumbucks",
1301 p2wpkhNestedInP2shAvailable: false,
1302 onSelect: function() {
1303 network
= bitcoinjs
.bitcoin
.networks
.jumbucks
;
1308 name: "LTC - Litecoin",
1309 p2wpkhNestedInP2shAvailable: false,
1310 onSelect: function() {
1311 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
1313 DOM
.litecoinLtubContainer
.removeClass("hidden");
1317 name: "MAZA - Maza",
1318 p2wpkhNestedInP2shAvailable: false,
1319 onSelect: function() {
1320 network
= bitcoinjs
.bitcoin
.networks
.maza
;
1326 name: "NMC - Namecoin",
1327 p2wpkhNestedInP2shAvailable: false,
1328 onSelect: function() {
1329 network
= bitcoinjs
.bitcoin
.networks
.namecoin
;
1334 name: "PIVX - PIVX",
1335 p2wpkhNestedInP2shAvailable: false,
1336 onSelect: function() {
1337 network
= bitcoinjs
.bitcoin
.networks
.pivx
;
1342 name: "PIVX - PIVX Testnet",
1343 p2wpkhNestedInP2shAvailable: false,
1344 onSelect: function() {
1345 network
= bitcoinjs
.bitcoin
.networks
.pivxtestnet
;
1350 name: "PPC - Peercoin",
1351 p2wpkhNestedInP2shAvailable: false,
1352 onSelect: function() {
1353 network
= bitcoinjs
.bitcoin
.networks
.peercoin
;
1358 name: "SDC - ShadowCash",
1359 p2wpkhNestedInP2shAvailable: false,
1360 onSelect: function() {
1361 network
= bitcoinjs
.bitcoin
.networks
.shadow
;
1366 name: "SDC - ShadowCash Testnet",
1367 p2wpkhNestedInP2shAvailable: false,
1368 onSelect: function() {
1369 network
= bitcoinjs
.bitcoin
.networks
.shadowtn
;
1374 name: "SLM - Slimcoin",
1375 p2wpkhNestedInP2shAvailable: false,
1376 onSelect: function() {
1377 network
= bitcoinjs
.bitcoin
.networks
.slimcoin
;
1382 name: "SLM - Slimcoin Testnet",
1383 p2wpkhNestedInP2shAvailable: false,
1384 onSelect: function() {
1385 network
= bitcoinjs
.bitcoin
.networks
.slimcointn
;
1390 name: "USNBT - NuBits",
1391 p2wpkhNestedInP2shAvailable: false,
1392 onSelect: function() {
1393 network
= bitcoinjs
.bitcoin
.networks
.nubits
;
1398 name: "VIA - Viacoin",
1399 p2wpkhNestedInP2shAvailable: false,
1400 onSelect: function() {
1401 network
= bitcoinjs
.bitcoin
.networks
.viacoin
;
1406 name: "VIA - Viacoin Testnet",
1407 p2wpkhNestedInP2shAvailable: false,
1408 onSelect: function() {
1409 network
= bitcoinjs
.bitcoin
.networks
.viacointestnet
;
1414 name: "XMY - Myriadcoin",
1415 p2wpkhNestedInP2shAvailable: false,
1416 onSelect: function() {
1417 network
= bitcoinjs
.bitcoin
.networks
.myriadcoin
;
1422 name: "XRP - Ripple",
1423 p2wpkhNestedInP2shAvailable: false,
1424 onSelect: function() {
1425 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1433 name: "Bitcoin Core",
1434 onSelect: function() {
1435 DOM
.bip32path
.val("m/0'/0'");
1436 DOM
.hardenedAddresses
.prop('checked', true);
1440 name: "blockchain.info",
1441 onSelect: function() {
1442 DOM
.bip32path
.val("m/44'/0'/0'");
1443 DOM
.hardenedAddresses
.prop('checked', false);
1447 name: "MultiBit HD",
1448 onSelect: function() {
1449 DOM
.bip32path
.val("m/0'/0");
1450 DOM
.hardenedAddresses
.prop('checked', false);