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
.addresses
= $(".addresses");
77 DOM
.rowsToAdd
= $(".rows-to-add");
78 DOM
.more
= $(".more");
79 DOM
.feedback
= $(".feedback");
80 DOM
.tab
= $(".derivation-type a");
81 DOM
.indexToggle
= $(".index-toggle");
82 DOM
.addressToggle
= $(".address-toggle");
83 DOM
.publicKeyToggle
= $(".public-key-toggle");
84 DOM
.privateKeyToggle
= $(".private-key-toggle");
85 DOM
.languages
= $(".languages a");
86 DOM
.qrContainer
= $(".qr-container");
87 DOM
.qrHider
= DOM
.qrContainer
.find(".qr-hider");
88 DOM
.qrImage
= DOM
.qrContainer
.find(".qr-image");
89 DOM
.qrHint
= DOM
.qrContainer
.find(".qr-hint");
90 DOM
.showQrEls
= $("[data-show-qr]");
94 DOM
.network
.on("change", networkChanged
);
95 DOM
.bip32Client
.on("change", bip32ClientChanged
);
96 DOM
.useEntropy
.on("change", setEntropyVisibility
);
97 DOM
.entropy
.on("input", delayedEntropyChanged
);
98 DOM
.entropyMnemonicLength
.on("change", entropyChanged
);
99 DOM
.phrase
.on("input", delayedPhraseChanged
);
100 DOM
.passphrase
.on("input", delayedPhraseChanged
);
101 DOM
.generate
.on("click", generateClicked
);
102 DOM
.more
.on("click", showMore
);
103 DOM
.rootKey
.on("input", delayedRootKeyChanged
);
104 DOM
.litecoinUseLtub
.on("change", litecoinUseLtubChanged
);
105 DOM
.bip32path
.on("input", calcForDerivationPath
);
106 DOM
.bip44account
.on("input", calcForDerivationPath
);
107 DOM
.bip44change
.on("input", calcForDerivationPath
);
108 DOM
.bip49account
.on("input", calcForDerivationPath
);
109 DOM
.bip49change
.on("input", calcForDerivationPath
);
110 DOM
.tab
.on("shown.bs.tab", calcForDerivationPath
);
111 DOM
.hardenedAddresses
.on("change", calcForDerivationPath
);
112 DOM
.indexToggle
.on("click", toggleIndexes
);
113 DOM
.addressToggle
.on("click", toggleAddresses
);
114 DOM
.publicKeyToggle
.on("click", togglePublicKeys
);
115 DOM
.privateKeyToggle
.on("click", togglePrivateKeys
);
116 DOM
.languages
.on("click", languageChanged
);
117 setQrEvents(DOM
.showQrEls
);
120 hideValidationError();
121 populateNetworkSelect();
122 populateClientSelect();
127 function networkChanged(e
) {
129 clearAddressesList();
130 DOM
.litecoinLtubContainer
.addClass("hidden");
131 var networkIndex
= e
.target
.value
;
132 var network
= networks
[networkIndex
];
134 if (network
.p2wpkhNestedInP2shAvailable
) {
135 showP2wpkhNestedInP2shAvailable();
138 showP2wpkhNestedInP2shUnavailable();
148 function bip32ClientChanged(e
) {
149 var clientIndex
= DOM
.bip32Client
.val();
150 if (clientIndex
== "custom") {
151 DOM
.bip32path
.prop("readonly", false);
154 DOM
.bip32path
.prop("readonly", true);
155 clients
[clientIndex
].onSelect();
165 function setEntropyVisibility() {
166 if (isUsingOwnEntropy()) {
167 DOM
.entropyContainer
.removeClass("hidden");
168 DOM
.generateContainer
.addClass("hidden");
169 DOM
.phrase
.prop("readonly", true);
174 DOM
.entropyContainer
.addClass("hidden");
175 DOM
.generateContainer
.removeClass("hidden");
176 DOM
.phrase
.prop("readonly", false);
181 function delayedPhraseChanged() {
182 hideValidationError();
185 bip32ExtendedKey
= null;
186 clearAddressesList();
188 if (phraseChangeTimeoutEvent
!= null) {
189 clearTimeout(phraseChangeTimeoutEvent
);
191 phraseChangeTimeoutEvent
= setTimeout(phraseChanged
, 400);
194 function phraseChanged() {
196 setMnemonicLanguage();
197 // Get the mnemonic phrase
198 var phrase
= DOM
.phrase
.val();
199 var errorText
= findPhraseErrors(phrase
);
201 showValidationError(errorText
);
204 // Calculate and display
205 var passphrase
= DOM
.passphrase
.val();
206 calcBip32RootKeyFromSeed(phrase
, passphrase
);
207 calcForDerivationPath();
210 function delayedEntropyChanged() {
211 hideValidationError();
213 if (entropyChangeTimeoutEvent
!= null) {
214 clearTimeout(entropyChangeTimeoutEvent
);
216 entropyChangeTimeoutEvent
= setTimeout(entropyChanged
, 400);
219 function entropyChanged() {
220 // If blank entropy, clear mnemonic, addresses, errors
221 if (DOM
.entropy
.val().trim().length
== 0) {
223 clearEntropyFeedback();
225 showValidationError("Blank entropy");
228 // Get the current phrase to detect changes
229 var phrase
= DOM
.phrase
.val();
230 // Set the phrase from the entropy
231 setMnemonicFromEntropy();
232 // Recalc addresses if the phrase has changed
233 var newPhrase
= DOM
.phrase
.val();
234 if (newPhrase
!= phrase
) {
235 if (newPhrase
.length
== 0) {
247 function delayedRootKeyChanged() {
248 // Warn if there is an existing mnemonic or passphrase.
249 if (DOM
.phrase
.val().length
> 0 || DOM
.passphrase
.val().length
> 0) {
250 if (!confirm("This will clear existing mnemonic and passphrase")) {
251 DOM
.rootKey
.val(bip32RootKey
);
255 hideValidationError();
257 // Clear existing mnemonic and passphrase
259 DOM
.passphrase
.val("");
261 if (rootKeyChangedTimeoutEvent
!= null) {
262 clearTimeout(rootKeyChangedTimeoutEvent
);
264 rootKeyChangedTimeoutEvent
= setTimeout(rootKeyChanged
, 400);
267 function rootKeyChanged() {
269 hideValidationError();
270 var rootKeyBase58
= DOM
.rootKey
.val();
271 var errorText
= validateRootKey(rootKeyBase58
);
273 showValidationError(errorText
);
276 // Calculate and display
277 calcBip32RootKeyFromBase58(rootKeyBase58
);
278 calcForDerivationPath();
281 function litecoinUseLtubChanged() {
282 litecoinUseLtub
= DOM
.litecoinUseLtub
.prop("checked");
283 if (litecoinUseLtub
) {
284 network
= bitcoinjs
.bitcoin
.networks
.litecoinLtub
;
287 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
292 function calcForDerivationPath() {
294 clearAddressesList();
296 // Don't show bip49 if it's selected but network doesn't support it
297 if (bip49TabSelected() && !networkHasBip49()) {
300 // Get the derivation path
301 var derivationPath
= getDerivationPath();
302 var errorText
= findDerivationPathErrors(derivationPath
);
304 showValidationError(errorText
);
307 bip32ExtendedKey
= calcBip32ExtendedKey(derivationPath
);
308 if (bip44TabSelected()) {
311 if (bip49TabSelected()) {
317 function generateClicked() {
318 if (isUsingOwnEntropy()) {
323 setTimeout(function() {
324 setMnemonicLanguage();
325 var phrase
= generateRandomPhrase();
333 function languageChanged() {
334 setTimeout(function() {
335 setMnemonicLanguage();
336 if (DOM
.phrase
.val().length
> 0) {
337 var newPhrase
= convertPhraseToNewLanguage();
338 DOM
.phrase
.val(newPhrase
);
342 DOM
.generate
.trigger("click");
347 function toggleIndexes() {
348 showIndex
= !showIndex
;
349 $("td.index span").toggleClass("invisible");
352 function toggleAddresses() {
353 showAddress
= !showAddress
;
354 $("td.address span").toggleClass("invisible");
357 function togglePublicKeys() {
358 showPubKey
= !showPubKey
;
359 $("td.pubkey span").toggleClass("invisible");
362 function togglePrivateKeys() {
363 showPrivKey
= !showPrivKey
;
364 $("td.privkey span").toggleClass("invisible");
369 function generateRandomPhrase() {
370 if (!hasStrongRandom()) {
371 var errorText
= "This browser does not support strong randomness";
372 showValidationError(errorText
);
375 var numWords
= parseInt(DOM
.generatedStrength
.val());
376 var strength
= numWords
/ 3 * 32;
377 var words
= mnemonic
.generate(strength
);
378 DOM
.phrase
.val(words
);
382 function calcBip32RootKeyFromSeed(phrase
, passphrase
) {
383 seed
= mnemonic
.toSeed(phrase
, passphrase
);
384 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromSeedHex(seed
, network
);
387 function calcBip32RootKeyFromBase58(rootKeyBase58
) {
388 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
391 function calcBip32ExtendedKey(path
) {
392 // Check there's a root key to derive from
396 var extendedKey
= bip32RootKey
;
397 // Derive the key from the path
398 var pathBits
= path
.split("/");
399 for (var i
=0; i
<pathBits
.length
; i
++) {
400 var bit
= pathBits
[i
];
401 var index
= parseInt(bit
);
405 var hardened
= bit
[bit
.length
-1] == "'";
406 var isPriv
= !(extendedKey
.isNeutered());
407 var invalidDerivationPath
= hardened
&& !isPriv
;
408 if (invalidDerivationPath
) {
412 extendedKey
= extendedKey
.deriveHardened(index
);
415 extendedKey
= extendedKey
.derive(index
);
421 function showValidationError(errorText
) {
427 function hideValidationError() {
433 function findPhraseErrors(phrase
) {
434 // Preprocess the words
435 phrase
= mnemonic
.normalizeString(phrase
);
436 var words
= phraseToWordArray(phrase
);
437 // Detect blank phrase
438 if (words
.length
== 0) {
439 return "Blank mnemonic";
442 for (var i
=0; i
<words
.length
; i
++) {
444 var language
= getLanguage();
445 if (WORDLISTS
[language
].indexOf(word
) == -1) {
446 console
.log("Finding closest match to " + word
);
447 var nearestWord
= findNearestWord(word
);
448 return word
+ " not in wordlist, did you mean " + nearestWord
+ "?";
451 // Check the words are valid
452 var properPhrase
= wordArrayToPhrase(words
);
453 var isValid
= mnemonic
.check(properPhrase
);
455 return "Invalid mnemonic";
460 function validateRootKey(rootKeyBase58
) {
462 bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
465 return "Invalid root key";
470 function getDerivationPath() {
471 if (bip44TabSelected()) {
472 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
473 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
474 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
475 var change
= parseIntNoNaN(DOM
.bip44change
.val(), 0);
477 path
+= purpose
+ "'/";
479 path
+= account
+ "'/";
481 DOM
.bip44path
.val(path
);
482 var derivationPath
= DOM
.bip44path
.val();
483 console
.log("Using derivation path from BIP44 tab: " + derivationPath
);
484 return derivationPath
;
486 if (bip49TabSelected()) {
487 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
488 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
489 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
490 var change
= parseIntNoNaN(DOM
.bip49change
.val(), 0);
492 path
+= purpose
+ "'/";
494 path
+= account
+ "'/";
496 DOM
.bip49path
.val(path
);
497 var derivationPath
= DOM
.bip49path
.val();
498 console
.log("Using derivation path from BIP49 tab: " + derivationPath
);
499 return derivationPath
;
501 else if (bip32TabSelected()) {
502 var derivationPath
= DOM
.bip32path
.val();
503 console
.log("Using derivation path from BIP32 tab: " + derivationPath
);
504 return derivationPath
;
507 console
.log("Unknown derivation path");
511 function findDerivationPathErrors(path
) {
512 // TODO is not perfect but is better than nothing
514 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
516 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
517 var maxDepth
= 255; // TODO verify this!!
518 var maxIndexValue
= Math
.pow(2, 31); // TODO verify this!!
519 if (path
[0] != "m") {
520 return "First character must be 'm'";
522 if (path
.length
> 1) {
523 if (path
[1] != "/") {
524 return "Separator must be '/'";
526 var indexes
= path
.split("/");
527 if (indexes
.length
> maxDepth
) {
528 return "Derivation depth is " + indexes
.length
+ ", must be less than " + maxDepth
;
530 for (var depth
= 1; depth
<indexes
.length
; depth
++) {
531 var index
= indexes
[depth
];
532 var invalidChars
= index
.replace(/^[0-9]+'?$/g, "")
533 if (invalidChars
.length
> 0) {
534 return "Invalid characters " + invalidChars
+ " found at depth " + depth
;
536 var indexValue
= parseInt(index
.replace("'", ""));
538 return "Invalid number at depth " + depth
;
540 if (indexValue
> maxIndexValue
) {
541 return "Value of " + indexValue
+ " at depth " + depth
+ " must be less than " + maxIndexValue
;
545 // Check root key exists or else derivation path is useless!
547 return "No root key";
549 // Check no hardened derivation path when using xpub keys
550 var hardenedPath
= path
.indexOf("'") > -1;
551 var hardenedAddresses
= bip32TabSelected() && DOM
.hardenedAddresses
.prop("checked");
552 var hardened
= hardenedPath
|| hardenedAddresses
;
553 var isXpubkey
= bip32RootKey
.isNeutered();
554 if (hardened
&& isXpubkey
) {
555 return "Hardened derivation path is invalid with xpub key";
560 function displayBip44Info() {
561 // Get the derivation path for the account
562 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
563 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
564 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
566 path
+= purpose
+ "'/";
568 path
+= account
+ "'/";
569 // Calculate the account extended keys
570 var accountExtendedKey
= calcBip32ExtendedKey(path
);
571 var accountXprv
= accountExtendedKey
.toBase58();
572 var accountXpub
= accountExtendedKey
.neutered().toBase58();
573 // Display the extended keys
574 DOM
.bip44accountXprv
.val(accountXprv
);
575 DOM
.bip44accountXpub
.val(accountXpub
);
578 function displayBip49Info() {
579 // Get the derivation path for the account
580 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
581 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
582 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
584 path
+= purpose
+ "'/";
586 path
+= account
+ "'/";
587 // Calculate the account extended keys
588 var accountExtendedKey
= calcBip32ExtendedKey(path
);
589 var accountXprv
= accountExtendedKey
.toBase58();
590 var accountXpub
= accountExtendedKey
.neutered().toBase58();
591 // Display the extended keys
592 DOM
.bip49accountXprv
.val(accountXprv
);
593 DOM
.bip49accountXpub
.val(accountXpub
);
596 function displayBip32Info() {
599 var rootKey
= bip32RootKey
.toBase58();
600 DOM
.rootKey
.val(rootKey
);
601 var xprvkeyB58
= "NA";
602 if (!bip32ExtendedKey
.isNeutered()) {
603 xprvkeyB58
= bip32ExtendedKey
.toBase58();
605 var extendedPrivKey
= xprvkeyB58
;
606 DOM
.extendedPrivKey
.val(extendedPrivKey
);
607 var extendedPubKey
= bip32ExtendedKey
.neutered().toBase58();
608 DOM
.extendedPubKey
.val(extendedPubKey
);
609 // Display the addresses and privkeys
610 clearAddressesList();
611 displayAddresses(0, 20);
614 function displayAddresses(start
, total
) {
615 generationProcesses
.push(new (function() {
619 this.stop = function() {
620 for (var i
=0; i
<rows
.length
; i
++) {
621 rows
[i
].shouldGenerate
= false;
626 for (var i
=0; i
<total
; i
++) {
627 var index
= i
+ start
;
628 var isLast
= i
== total
- 1;
629 rows
.push(new TableRow(index
, isLast
));
635 function TableRow(index
, isLast
) {
638 this.shouldGenerate
= true;
639 var useHardenedAddresses
= DOM
.hardenedAddresses
.prop("checked");
640 var isP2wpkhNestedInP2sh
= bip49TabSelected();
641 var p2wpkhNestedInP2shAvailable
= networkHasBip49();
647 function calculateValues() {
648 setTimeout(function() {
649 if (!self
.shouldGenerate
) {
653 if (useHardenedAddresses
) {
654 key
= bip32ExtendedKey
.deriveHardened(index
);
657 key
= bip32ExtendedKey
.derive(index
);
659 var address
= key
.getAddress().toString();
661 if (!key
.isNeutered()) {
662 privkey
= key
.keyPair
.toWIF(network
);
664 var pubkey
= key
.getPublicKeyBuffer().toString('hex');
665 var indexText
= getDerivationPath() + "/" + index
;
666 if (useHardenedAddresses
) {
667 indexText
= indexText
+ "'";
669 // Ethereum values are different
670 if (networks
[DOM
.network
.val()].name
== "ETH - Ethereum") {
671 var privKeyBuffer
= key
.keyPair
.d
.toBuffer();
672 privkey
= privKeyBuffer
.toString('hex');
673 var addressBuffer
= ethUtil
.privateToAddress(privKeyBuffer
);
674 var hexAddress
= addressBuffer
.toString('hex');
675 var checksumAddress
= ethUtil
.toChecksumAddress(hexAddress
);
676 address
= ethUtil
.addHexPrefix(checksumAddress
);
677 privkey
= ethUtil
.addHexPrefix(privkey
);
678 pubkey
= ethUtil
.addHexPrefix(pubkey
);
680 // Ripple values are different
681 if (networks
[DOM
.network
.val()].name
== "XRP - Ripple") {
682 privkey
= convertRipplePriv(privkey
);
683 address
= convertRippleAdrr(address
);
685 // BIP49 addresses are different
686 if (isP2wpkhNestedInP2sh
) {
687 if (!p2wpkhNestedInP2shAvailable
) {
690 var keyhash
= bitcoinjs
.bitcoin
.crypto
.hash160(key
.getPublicKeyBuffer());
691 var scriptsig
= bitcoinjs
.bitcoin
.script
.witnessPubKeyHash
.output
.encode(keyhash
);
692 var addressbytes
= bitcoinjs
.bitcoin
.crypto
.hash160(scriptsig
);
693 var scriptpubkey
= bitcoinjs
.bitcoin
.script
.scriptHash
.output
.encode(addressbytes
);
694 address
= bitcoinjs
.bitcoin
.address
.fromOutputScript(scriptpubkey
, network
)
696 addAddressToList(indexText
, address
, pubkey
, privkey
);
707 function showMore() {
708 var start
= DOM
.addresses
.children().length
;
709 var rowsToAdd
= parseInt(DOM
.rowsToAdd
.val());
710 if (isNaN(rowsToAdd
)) {
712 DOM
.rowsToAdd
.val("20");
714 if (rowsToAdd
> 200) {
715 var msg
= "Generating " + rowsToAdd
+ " rows could take a while. ";
716 msg
+= "Do you want to continue?";
721 displayAddresses(start
, rowsToAdd
);
724 function clearDisplay() {
725 clearAddressesList();
727 hideValidationError();
730 function clearAddressesList() {
731 DOM
.addresses
.empty();
735 function stopGenerating() {
736 while (generationProcesses
.length
> 0) {
737 var generation
= generationProcesses
.shift();
742 function clearKeys() {
747 function clearRootKey() {
751 function clearDerivedKeys() {
752 DOM
.extendedPrivKey
.val("");
753 DOM
.extendedPubKey
.val("");
754 DOM
.bip44accountXprv
.val("");
755 DOM
.bip44accountXpub
.val("");
758 function addAddressToList(indexText
, address
, pubkey
, privkey
) {
759 var row
= $(addressRowTemplate
.html());
761 var indexCell
= row
.find(".index span");
762 var addressCell
= row
.find(".address span");
763 var pubkeyCell
= row
.find(".pubkey span");
764 var privkeyCell
= row
.find(".privkey span");
766 indexCell
.text(indexText
);
767 addressCell
.text(address
);
768 pubkeyCell
.text(pubkey
);
769 privkeyCell
.text(privkey
);
772 indexCell
.addClass("invisible");
775 addressCell
.addClass("invisible");
778 pubkeyCell
.addClass("invisible");
781 privkeyCell
.addClass("invisible");
783 DOM
.addresses
.append(row
);
784 var rowShowQrEls
= row
.find("[data-show-qr]");
785 setQrEvents(rowShowQrEls
);
788 function hasStrongRandom() {
789 return 'crypto' in window
&& window
['crypto'] !== null;
792 function disableForms() {
793 $("form").on("submit", function(e
) {
798 function parseIntNoNaN(val
, defaultVal
) {
799 var v
= parseInt(val
);
806 function showPending() {
808 .text("Calculating...")
812 function findNearestWord(word
) {
813 var language
= getLanguage();
814 var words
= WORDLISTS
[language
];
815 var minDistance
= 99;
816 var closestWord
= words
[0];
817 for (var i
=0; i
<words
.length
; i
++) {
818 var comparedTo
= words
[i
];
819 if (comparedTo
.indexOf(word
) == 0) {
822 var distance
= Levenshtein
.get(word
, comparedTo
);
823 if (distance
< minDistance
) {
824 closestWord
= comparedTo
;
825 minDistance
= distance
;
831 function hidePending() {
837 function populateNetworkSelect() {
838 for (var i
=0; i
<networks
.length
; i
++) {
839 var network
= networks
[i
];
840 var option
= $("<option>");
841 option
.attr("value", i
);
842 option
.text(network
.name
);
843 if (network
.name
== "BTC - Bitcoin") {
844 option
.prop("selected", true);
846 DOM
.phraseNetwork
.append(option
);
850 function populateClientSelect() {
851 for (var i
=0; i
<clients
.length
; i
++) {
852 var client
= clients
[i
];
853 var option
= $("<option>");
854 option
.attr("value", i
);
855 option
.text(client
.name
);
856 DOM
.bip32Client
.append(option
);
860 function getLanguage() {
861 var defaultLanguage
= "english";
862 // Try to get from existing phrase
863 var language
= getLanguageFromPhrase();
864 // Try to get from url if not from phrase
865 if (language
.length
== 0) {
866 language
= getLanguageFromUrl();
868 // Default to English if no other option
869 if (language
.length
== 0) {
870 language
= defaultLanguage
;
875 function getLanguageFromPhrase(phrase
) {
876 // Check if how many words from existing phrase match a language.
879 phrase
= DOM
.phrase
.val();
881 if (phrase
.length
> 0) {
882 var words
= phraseToWordArray(phrase
);
883 var languageMatches
= {};
884 for (l
in WORDLISTS
) {
885 // Track how many words match in this language
886 languageMatches
[l
] = 0;
887 for (var i
=0; i
<words
.length
; i
++) {
888 var wordInLanguage
= WORDLISTS
[l
].indexOf(words
[i
]) > -1;
889 if (wordInLanguage
) {
890 languageMatches
[l
]++;
893 // Find languages with most word matches.
894 // This is made difficult due to commonalities between Chinese
895 // simplified vs traditional.
897 var mostMatchedLanguages
= [];
898 for (var l
in languageMatches
) {
899 var numMatches
= languageMatches
[l
];
900 if (numMatches
> mostMatches
) {
901 mostMatches
= numMatches
;
902 mostMatchedLanguages
= [l
];
904 else if (numMatches
== mostMatches
) {
905 mostMatchedLanguages
.push(l
);
909 if (mostMatchedLanguages
.length
> 0) {
910 // Use first language and warn if multiple detected
911 language
= mostMatchedLanguages
[0];
912 if (mostMatchedLanguages
.length
> 1) {
913 console
.warn("Multiple possible languages");
914 console
.warn(mostMatchedLanguages
);
921 function getLanguageFromUrl() {
922 for (var language
in WORDLISTS
) {
923 if (window
.location
.hash
.indexOf(language
) > -1) {
930 function setMnemonicLanguage() {
931 var language
= getLanguage();
932 // Load the bip39 mnemonic generator for this language if required
933 if (!(language
in mnemonics
)) {
934 mnemonics
[language
] = new Mnemonic(language
);
936 mnemonic
= mnemonics
[language
];
939 function convertPhraseToNewLanguage() {
940 var oldLanguage
= getLanguageFromPhrase();
941 var newLanguage
= getLanguageFromUrl();
942 var oldPhrase
= DOM
.phrase
.val();
943 var oldWords
= phraseToWordArray(oldPhrase
);
945 for (var i
=0; i
<oldWords
.length
; i
++) {
946 var oldWord
= oldWords
[i
];
947 var index
= WORDLISTS
[oldLanguage
].indexOf(oldWord
);
948 var newWord
= WORDLISTS
[newLanguage
][index
];
949 newWords
.push(newWord
);
951 newPhrase
= wordArrayToPhrase(newWords
);
955 // TODO look at jsbip39 - mnemonic.splitWords
956 function phraseToWordArray(phrase
) {
957 var words
= phrase
.split(/\s/g);
959 for (var i
=0; i
<words
.length
; i
++) {
961 if (word
.length
> 0) {
968 // TODO look at jsbip39 - mnemonic.joinWords
969 function wordArrayToPhrase(words
) {
970 var phrase
= words
.join(" ");
971 var language
= getLanguageFromPhrase(phrase
);
972 if (language
== "japanese") {
973 phrase
= words
.join("\u3000");
978 function isUsingOwnEntropy() {
979 return DOM
.useEntropy
.prop("checked");
982 function setMnemonicFromEntropy() {
983 clearEntropyFeedback();
985 var entropyStr
= DOM
.entropy
.val();
986 // Work out minimum base for entropy
987 var entropy
= Entropy
.fromString(entropyStr
);
988 if (entropy
.binaryStr
.length
== 0) {
991 // Show entropy details
992 showEntropyFeedback(entropy
);
993 // Use entropy hash if not using raw entropy
994 var bits
= entropy
.binaryStr
;
995 var mnemonicLength
= DOM
.entropyMnemonicLength
.val();
996 if (mnemonicLength
!= "raw") {
997 // Get bits by hashing entropy with SHA256
998 var hash
= sjcl
.hash
.sha256
.hash(entropy
.cleanStr
);
999 var hex
= sjcl
.codec
.hex
.fromBits(hash
);
1000 bits
= BigInteger
.parse(hex
, 16).toString(2);
1001 while (bits
.length
% 256 != 0) {
1004 // Truncate hash to suit number of words
1005 mnemonicLength
= parseInt(mnemonicLength
);
1006 var numberOfBits
= 32 * mnemonicLength
/ 3;
1007 bits
= bits
.substring(0, numberOfBits
);
1009 // Discard trailing entropy
1010 var bitsToUse
= Math
.floor(bits
.length
/ 32) * 32;
1011 var start
= bits
.length
- bitsToUse
;
1012 var binaryStr
= bits
.substring(start
);
1013 // Convert entropy string to numeric array
1014 var entropyArr
= [];
1015 for (var i
=0; i
<binaryStr
.length
/ 8; i
++) {
1016 var byteAsBits
= binaryStr
.substring(i
*8, i
*8+8);
1017 var entropyByte
= parseInt(byteAsBits
, 2);
1018 entropyArr
.push(entropyByte
)
1020 // Convert entropy array to mnemonic
1021 var phrase
= mnemonic
.toMnemonic(entropyArr
);
1022 // Set the mnemonic in the UI
1023 DOM
.phrase
.val(phrase
);
1026 function clearEntropyFeedback() {
1027 DOM
.entropyCrackTime
.text("...");
1028 DOM
.entropyType
.text("");
1029 DOM
.entropyWordCount
.text("0");
1030 DOM
.entropyEventCount
.text("0");
1031 DOM
.entropyBitsPerEvent
.text("0");
1032 DOM
.entropyBits
.text("0");
1033 DOM
.entropyFiltered
.html(" ");
1034 DOM
.entropyBinary
.html(" ");
1037 function showEntropyFeedback(entropy
) {
1038 var numberOfBits
= entropy
.binaryStr
.length
;
1039 var timeToCrack
= "unknown";
1041 var z
= zxcvbn(entropy
.base
.parts
.join(""));
1042 timeToCrack
= z
.crack_times_display
.offline_fast_hashing_1e10_per_second
;
1043 if (z
.feedback
.warning
!= "") {
1044 timeToCrack
= timeToCrack
+ " - " + z
.feedback
.warning
;
1048 console
.log("Error detecting entropy strength with zxcvbn:");
1051 var entropyTypeStr
= getEntropyTypeStr(entropy
);
1052 var wordCount
= Math
.floor(numberOfBits
/ 32) * 3;
1053 var bitsPerEvent
= entropy
.bitsPerEvent
.toFixed(2);
1054 DOM
.entropyFiltered
.html(entropy
.cleanHtml
);
1055 DOM
.entropyType
.text(entropyTypeStr
);
1056 DOM
.entropyCrackTime
.text(timeToCrack
);
1057 DOM
.entropyEventCount
.text(entropy
.base
.ints
.length
);
1058 DOM
.entropyBits
.text(numberOfBits
);
1059 DOM
.entropyWordCount
.text(wordCount
);
1060 DOM
.entropyBinary
.text(entropy
.binaryStr
);
1061 DOM
.entropyBitsPerEvent
.text(bitsPerEvent
);
1064 function getEntropyTypeStr(entropy
) {
1065 var typeStr
= entropy
.base
.str
;
1066 // Add some detail if these are cards
1067 if (entropy
.base
.asInt
== 52) {
1068 var cardDetail
= []; // array of message strings
1069 // Detect duplicates
1071 var dupeTracker
= {};
1072 for (var i
=0; i
<entropy
.base
.parts
.length
; i
++) {
1073 var card
= entropy
.base
.parts
[i
];
1074 var cardUpper
= card
.toUpperCase();
1075 if (cardUpper
in dupeTracker
) {
1078 dupeTracker
[cardUpper
] = true;
1080 if (dupes
.length
> 0) {
1081 var dupeWord
= "duplicates";
1082 if (dupes
.length
== 1) {
1083 dupeWord
= "duplicate";
1085 var msg
= dupes
.length
+ " " + dupeWord
+ ": " + dupes
.slice(0,3).join(" ");
1086 if (dupes
.length
> 3) {
1089 cardDetail
.push(msg
);
1092 var uniqueCards
= [];
1093 for (var uniqueCard
in dupeTracker
) {
1094 uniqueCards
.push(uniqueCard
);
1096 if (uniqueCards
.length
== 52) {
1097 cardDetail
.unshift("full deck");
1099 // Detect missing cards
1100 var values
= "A23456789TJQK";
1102 var missingCards
= [];
1103 for (var i
=0; i
<suits
.length
; i
++) {
1104 for (var j
=0; j
<values
.length
; j
++) {
1105 var card
= values
[j
] + suits
[i
];
1106 if (!(card
in dupeTracker
)) {
1107 missingCards
.push(card
);
1111 // Display missing cards if six or less, ie clearly going for full deck
1112 if (missingCards
.length
> 0 && missingCards
.length
<= 6) {
1113 var msg
= missingCards
.length
+ " missing: " + missingCards
.slice(0,3).join(" ");
1114 if (missingCards
.length
> 3) {
1117 cardDetail
.push(msg
);
1119 // Add card details to typeStr
1120 if (cardDetail
.length
> 0) {
1121 typeStr
+= " (" + cardDetail
.join(", ") + ")";
1127 function setQrEvents(els
) {
1128 els
.on("mouseenter", createQr
);
1129 els
.on("mouseleave", destroyQr
);
1130 els
.on("click", toggleQr
);
1133 function createQr(e
) {
1134 var content
= e
.target
.textContent
|| e
.target
.value
;
1137 DOM
.qrImage
.qrcode({width: size
, height: size
, text: content
});
1139 DOM
.qrHider
.addClass("hidden");
1142 DOM
.qrHider
.removeClass("hidden");
1144 DOM
.qrContainer
.removeClass("hidden");
1148 function destroyQr() {
1149 DOM
.qrImage
.text("");
1150 DOM
.qrContainer
.addClass("hidden");
1153 function toggleQr() {
1155 DOM
.qrHider
.toggleClass("hidden");
1156 DOM
.qrHint
.toggleClass("hidden");
1159 function bip44TabSelected() {
1160 return DOM
.bip44tab
.hasClass("active");
1163 function bip32TabSelected() {
1164 return DOM
.bip32tab
.hasClass("active");
1167 function networkHasBip49() {
1168 return networks
[DOM
.network
.val()].p2wpkhNestedInP2shAvailable
;
1171 function bip49TabSelected() {
1172 return DOM
.bip49tab
.hasClass("active");
1175 function setHdCoin(coinValue
) {
1176 DOM
.bip44coin
.val(coinValue
);
1177 DOM
.bip49coin
.val(coinValue
);
1180 function showP2wpkhNestedInP2shAvailable() {
1181 DOM
.bip49unavailable
.addClass("hidden");
1182 DOM
.bip49available
.removeClass("hidden");
1185 function showP2wpkhNestedInP2shUnavailable() {
1186 DOM
.bip49available
.addClass("hidden");
1187 DOM
.bip49unavailable
.removeClass("hidden");
1192 name: "BCH - Bitcoin Cash",
1193 p2wpkhNestedInP2shAvailable: false,
1194 onSelect: function() {
1195 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1200 name: "BTC - Bitcoin",
1201 p2wpkhNestedInP2shAvailable: true,
1202 onSelect: function() {
1203 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1208 name: "BTC - Bitcoin Testnet",
1209 p2wpkhNestedInP2shAvailable: true,
1210 onSelect: function() {
1211 network
= bitcoinjs
.bitcoin
.networks
.testnet
;
1216 name: "CLAM - Clams",
1217 p2wpkhNestedInP2shAvailable: false,
1218 onSelect: function() {
1219 network
= bitcoinjs
.bitcoin
.networks
.clam
;
1224 name: "CRW - Crown",
1225 p2wpkhNestedInP2shAvailable: false,
1226 onSelect: function() {
1227 network
= bitcoinjs
.bitcoin
.networks
.crown
;
1232 name: "DASH - Dash",
1233 p2wpkhNestedInP2shAvailable: false,
1234 onSelect: function() {
1235 network
= bitcoinjs
.bitcoin
.networks
.dash
;
1240 name: "DASH - Dash Testnet",
1241 p2wpkhNestedInP2shAvailable: false,
1242 onSelect: function() {
1243 network
= bitcoinjs
.bitcoin
.networks
.dashtn
;
1248 name: "DOGE - Dogecoin",
1249 p2wpkhNestedInP2shAvailable: false,
1250 onSelect: function() {
1251 network
= bitcoinjs
.bitcoin
.networks
.dogecoin
;
1256 name: "ETH - Ethereum",
1257 p2wpkhNestedInP2shAvailable: false,
1258 onSelect: function() {
1259 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1264 name: "GAME - GameCredits",
1265 p2wpkhNestedInP2shAvailable: false,
1266 onSelect: function() {
1267 network
= bitcoinjs
.bitcoin
.networks
.game
;
1272 name: "JBS - Jumbucks",
1273 p2wpkhNestedInP2shAvailable: false,
1274 onSelect: function() {
1275 network
= bitcoinjs
.bitcoin
.networks
.jumbucks
;
1280 name: "LTC - Litecoin",
1281 p2wpkhNestedInP2shAvailable: false,
1282 onSelect: function() {
1283 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
1285 DOM
.litecoinLtubContainer
.removeClass("hidden");
1289 name: "MAZA - Maza",
1290 p2wpkhNestedInP2shAvailable: false,
1291 onSelect: function() {
1292 network
= bitcoinjs
.bitcoin
.networks
.maza
;
1298 name: "NMC - Namecoin",
1299 p2wpkhNestedInP2shAvailable: false,
1300 onSelect: function() {
1301 network
= bitcoinjs
.bitcoin
.networks
.namecoin
;
1306 name: "PIVX - PIVX",
1307 p2wpkhNestedInP2shAvailable: false,
1308 onSelect: function() {
1309 network
= bitcoinjs
.bitcoin
.networks
.pivx
;
1314 name: "PIVX - PIVX Testnet",
1315 p2wpkhNestedInP2shAvailable: false,
1316 onSelect: function() {
1317 network
= bitcoinjs
.bitcoin
.networks
.pivxtestnet
;
1322 name: "PPC - Peercoin",
1323 p2wpkhNestedInP2shAvailable: false,
1324 onSelect: function() {
1325 network
= bitcoinjs
.bitcoin
.networks
.peercoin
;
1330 name: "SDC - ShadowCash",
1331 p2wpkhNestedInP2shAvailable: false,
1332 onSelect: function() {
1333 network
= bitcoinjs
.bitcoin
.networks
.shadow
;
1338 name: "SDC - ShadowCash Testnet",
1339 p2wpkhNestedInP2shAvailable: false,
1340 onSelect: function() {
1341 network
= bitcoinjs
.bitcoin
.networks
.shadowtn
;
1346 name: "SLM - Slimcoin",
1347 p2wpkhNestedInP2shAvailable: false,
1348 onSelect: function() {
1349 network
= bitcoinjs
.bitcoin
.networks
.slimcoin
;
1354 name: "SLM - Slimcoin Testnet",
1355 p2wpkhNestedInP2shAvailable: false,
1356 onSelect: function() {
1357 network
= bitcoinjs
.bitcoin
.networks
.slimcointn
;
1362 name: "VIA - Viacoin",
1363 p2wpkhNestedInP2shAvailable: false,
1364 onSelect: function() {
1365 network
= bitcoinjs
.bitcoin
.networks
.viacoin
;
1370 name: "VIA - Viacoin Testnet",
1371 p2wpkhNestedInP2shAvailable: false,
1372 onSelect: function() {
1373 network
= bitcoinjs
.bitcoin
.networks
.viacointestnet
;
1378 name: "XMY - Myriadcoin",
1379 p2wpkhNestedInP2shAvailable: false,
1380 onSelect: function() {
1381 network
= bitcoinjs
.bitcoin
.networks
.myriadcoin
;
1386 name: "XRP - Ripple",
1387 p2wpkhNestedInP2shAvailable: false,
1388 onSelect: function() {
1389 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1397 name: "Bitcoin Core",
1398 onSelect: function() {
1399 DOM
.bip32path
.val("m/0'/0'");
1400 DOM
.hardenedAddresses
.prop('checked', true);
1404 name: "blockchain.info",
1405 onSelect: function() {
1406 DOM
.bip32path
.val("m/44'/0'/0'");
1407 DOM
.hardenedAddresses
.prop('checked', false);
1411 name: "MultiBit HD",
1412 onSelect: function() {
1413 DOM
.bip32path
.val("m/0'/0");
1414 DOM
.hardenedAddresses
.prop('checked', false);