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
= true;
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
.useBitpayAddressesContainer
= $(".use-bitpay-addresses-container");
78 DOM
.useBitpayAddresses
= $(".use-bitpay-addresses");
79 DOM
.addresses
= $(".addresses");
80 DOM
.rowsToAdd
= $(".rows-to-add");
81 DOM
.more
= $(".more");
82 DOM
.moreRowsStartIndex
= $(".more-rows-start-index");
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", tabChanged
);
115 DOM
.hardenedAddresses
.on("change", calcForDerivationPath
);
116 DOM
.indexToggle
.on("click", toggleIndexes
);
117 DOM
.addressToggle
.on("click", toggleAddresses
);
118 DOM
.publicKeyToggle
.on("click", togglePublicKeys
);
119 DOM
.privateKeyToggle
.on("click", togglePrivateKeys
);
120 DOM
.languages
.on("click", languageChanged
);
121 DOM
.useBitpayAddresses
.on("change", useBitpayAddressesChange
);
122 setQrEvents(DOM
.showQrEls
);
125 hideValidationError();
126 populateNetworkSelect();
127 populateClientSelect();
132 function networkChanged(e
) {
134 clearAddressesList();
135 DOM
.litecoinLtubContainer
.addClass("hidden");
136 DOM
.useBitpayAddressesContainer
.addClass("hidden");
137 var networkIndex
= e
.target
.value
;
138 var network
= networks
[networkIndex
];
140 if (network
.segwitAvailable
) {
141 showSegwitAvailable();
144 showSegwitUnavailable();
154 function bip32ClientChanged(e
) {
155 var clientIndex
= DOM
.bip32Client
.val();
156 if (clientIndex
== "custom") {
157 DOM
.bip32path
.prop("readonly", false);
160 DOM
.bip32path
.prop("readonly", true);
161 clients
[clientIndex
].onSelect();
171 function setEntropyVisibility() {
172 if (isUsingOwnEntropy()) {
173 DOM
.entropyContainer
.removeClass("hidden");
174 DOM
.generateContainer
.addClass("hidden");
175 DOM
.phrase
.prop("readonly", true);
180 DOM
.entropyContainer
.addClass("hidden");
181 DOM
.generateContainer
.removeClass("hidden");
182 DOM
.phrase
.prop("readonly", false);
187 function delayedPhraseChanged() {
188 hideValidationError();
191 bip32ExtendedKey
= null;
192 clearAddressesList();
194 if (phraseChangeTimeoutEvent
!= null) {
195 clearTimeout(phraseChangeTimeoutEvent
);
197 phraseChangeTimeoutEvent
= setTimeout(phraseChanged
, 400);
200 function phraseChanged() {
202 setMnemonicLanguage();
203 // Get the mnemonic phrase
204 var phrase
= DOM
.phrase
.val();
205 var errorText
= findPhraseErrors(phrase
);
207 showValidationError(errorText
);
210 // Calculate and display
211 var passphrase
= DOM
.passphrase
.val();
212 calcBip32RootKeyFromSeed(phrase
, passphrase
);
213 calcForDerivationPath();
216 function tabChanged() {
218 adjustNetworkForSegwit();
219 var phrase
= DOM
.phrase
.val();
221 // Calculate and display for mnemonic
222 var errorText
= findPhraseErrors(phrase
);
224 showValidationError(errorText
);
227 // Calculate and display
228 var passphrase
= DOM
.passphrase
.val();
229 calcBip32RootKeyFromSeed(phrase
, passphrase
);
232 // Calculate and display for root key
233 var rootKeyBase58
= DOM
.rootKey
.val();
234 var errorText
= validateRootKey(rootKeyBase58
);
236 showValidationError(errorText
);
239 // Calculate and display
240 calcBip32RootKeyFromBase58(rootKeyBase58
);
242 calcForDerivationPath();
245 function delayedEntropyChanged() {
246 hideValidationError();
248 if (entropyChangeTimeoutEvent
!= null) {
249 clearTimeout(entropyChangeTimeoutEvent
);
251 entropyChangeTimeoutEvent
= setTimeout(entropyChanged
, 400);
254 function entropyChanged() {
255 // If blank entropy, clear mnemonic, addresses, errors
256 if (DOM
.entropy
.val().trim().length
== 0) {
258 clearEntropyFeedback();
260 showValidationError("Blank entropy");
263 // Get the current phrase to detect changes
264 var phrase
= DOM
.phrase
.val();
265 // Set the phrase from the entropy
266 setMnemonicFromEntropy();
267 // Recalc addresses if the phrase has changed
268 var newPhrase
= DOM
.phrase
.val();
269 if (newPhrase
!= phrase
) {
270 if (newPhrase
.length
== 0) {
282 function delayedRootKeyChanged() {
283 // Warn if there is an existing mnemonic or passphrase.
284 if (DOM
.phrase
.val().length
> 0 || DOM
.passphrase
.val().length
> 0) {
285 if (!confirm("This will clear existing mnemonic and passphrase")) {
286 DOM
.rootKey
.val(bip32RootKey
);
290 hideValidationError();
292 // Clear existing mnemonic and passphrase
294 DOM
.passphrase
.val("");
296 if (rootKeyChangedTimeoutEvent
!= null) {
297 clearTimeout(rootKeyChangedTimeoutEvent
);
299 rootKeyChangedTimeoutEvent
= setTimeout(rootKeyChanged
, 400);
302 function rootKeyChanged() {
304 hideValidationError();
305 var rootKeyBase58
= DOM
.rootKey
.val();
306 var errorText
= validateRootKey(rootKeyBase58
);
308 showValidationError(errorText
);
311 // Calculate and display
312 calcBip32RootKeyFromBase58(rootKeyBase58
);
313 calcForDerivationPath();
316 function litecoinUseLtubChanged() {
317 litecoinUseLtub
= DOM
.litecoinUseLtub
.prop("checked");
318 if (litecoinUseLtub
) {
319 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
322 network
= bitcoinjs
.bitcoin
.networks
.litecoinXprv
;
327 function calcForDerivationPath() {
329 clearAddressesList();
331 // Don't show segwit if it's selected but network doesn't support it
332 if (segwitSelected() && !networkHasSegwit()) {
335 // Get the derivation path
336 var derivationPath
= getDerivationPath();
337 var errorText
= findDerivationPathErrors(derivationPath
);
339 showValidationError(errorText
);
342 bip32ExtendedKey
= calcBip32ExtendedKey(derivationPath
);
343 if (bip44TabSelected()) {
346 if (bip49TabSelected()) {
352 function generateClicked() {
353 if (isUsingOwnEntropy()) {
358 setTimeout(function() {
359 setMnemonicLanguage();
360 var phrase
= generateRandomPhrase();
368 function languageChanged() {
369 setTimeout(function() {
370 setMnemonicLanguage();
371 if (DOM
.phrase
.val().length
> 0) {
372 var newPhrase
= convertPhraseToNewLanguage();
373 DOM
.phrase
.val(newPhrase
);
377 DOM
.generate
.trigger("click");
382 function useBitpayAddressesChange() {
383 setBitcoinCashNetworkValues();
387 function toggleIndexes() {
388 showIndex
= !showIndex
;
389 $("td.index span").toggleClass("invisible");
392 function toggleAddresses() {
393 showAddress
= !showAddress
;
394 $("td.address span").toggleClass("invisible");
397 function togglePublicKeys() {
398 showPubKey
= !showPubKey
;
399 $("td.pubkey span").toggleClass("invisible");
402 function togglePrivateKeys() {
403 showPrivKey
= !showPrivKey
;
404 $("td.privkey span").toggleClass("invisible");
409 function generateRandomPhrase() {
410 if (!hasStrongRandom()) {
411 var errorText
= "This browser does not support strong randomness";
412 showValidationError(errorText
);
415 var numWords
= parseInt(DOM
.generatedStrength
.val());
416 var strength
= numWords
/ 3 * 32;
417 var words
= mnemonic
.generate(strength
);
418 DOM
.phrase
.val(words
);
422 function calcBip32RootKeyFromSeed(phrase
, passphrase
) {
423 seed
= mnemonic
.toSeed(phrase
, passphrase
);
424 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromSeedHex(seed
, network
);
427 function calcBip32RootKeyFromBase58(rootKeyBase58
) {
428 bip32RootKey
= bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
431 function calcBip32ExtendedKey(path
) {
432 // Check there's a root key to derive from
436 var extendedKey
= bip32RootKey
;
437 // Derive the key from the path
438 var pathBits
= path
.split("/");
439 for (var i
=0; i
<pathBits
.length
; i
++) {
440 var bit
= pathBits
[i
];
441 var index
= parseInt(bit
);
445 var hardened
= bit
[bit
.length
-1] == "'";
446 var isPriv
= !(extendedKey
.isNeutered());
447 var invalidDerivationPath
= hardened
&& !isPriv
;
448 if (invalidDerivationPath
) {
452 extendedKey
= extendedKey
.deriveHardened(index
);
455 extendedKey
= extendedKey
.derive(index
);
461 function showValidationError(errorText
) {
467 function hideValidationError() {
473 function findPhraseErrors(phrase
) {
474 // Preprocess the words
475 phrase
= mnemonic
.normalizeString(phrase
);
476 var words
= phraseToWordArray(phrase
);
477 // Detect blank phrase
478 if (words
.length
== 0) {
479 return "Blank mnemonic";
482 for (var i
=0; i
<words
.length
; i
++) {
484 var language
= getLanguage();
485 if (WORDLISTS
[language
].indexOf(word
) == -1) {
486 console
.log("Finding closest match to " + word
);
487 var nearestWord
= findNearestWord(word
);
488 return word
+ " not in wordlist, did you mean " + nearestWord
+ "?";
491 // Check the words are valid
492 var properPhrase
= wordArrayToPhrase(words
);
493 var isValid
= mnemonic
.check(properPhrase
);
495 return "Invalid mnemonic";
500 function validateRootKey(rootKeyBase58
) {
502 bitcoinjs
.bitcoin
.HDNode
.fromBase58(rootKeyBase58
, network
);
505 return "Invalid root key";
510 function getDerivationPath() {
511 if (bip44TabSelected()) {
512 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
513 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
514 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
515 var change
= parseIntNoNaN(DOM
.bip44change
.val(), 0);
517 path
+= purpose
+ "'/";
519 path
+= account
+ "'/";
521 DOM
.bip44path
.val(path
);
522 var derivationPath
= DOM
.bip44path
.val();
523 console
.log("Using derivation path from BIP44 tab: " + derivationPath
);
524 return derivationPath
;
526 if (bip49TabSelected()) {
527 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
528 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
529 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
530 var change
= parseIntNoNaN(DOM
.bip49change
.val(), 0);
532 path
+= purpose
+ "'/";
534 path
+= account
+ "'/";
536 DOM
.bip49path
.val(path
);
537 var derivationPath
= DOM
.bip49path
.val();
538 console
.log("Using derivation path from BIP49 tab: " + derivationPath
);
539 return derivationPath
;
541 else if (bip32TabSelected()) {
542 var derivationPath
= DOM
.bip32path
.val();
543 console
.log("Using derivation path from BIP32 tab: " + derivationPath
);
544 return derivationPath
;
547 console
.log("Unknown derivation path");
551 function findDerivationPathErrors(path
) {
552 // TODO is not perfect but is better than nothing
554 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vectors
556 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#extended-keys
557 var maxDepth
= 255; // TODO verify this!!
558 var maxIndexValue
= Math
.pow(2, 31); // TODO verify this!!
559 if (path
[0] != "m") {
560 return "First character must be 'm'";
562 if (path
.length
> 1) {
563 if (path
[1] != "/") {
564 return "Separator must be '/'";
566 var indexes
= path
.split("/");
567 if (indexes
.length
> maxDepth
) {
568 return "Derivation depth is " + indexes
.length
+ ", must be less than " + maxDepth
;
570 for (var depth
= 1; depth
<indexes
.length
; depth
++) {
571 var index
= indexes
[depth
];
572 var invalidChars
= index
.replace(/^[0-9]+'?$/g, "")
573 if (invalidChars
.length
> 0) {
574 return "Invalid characters " + invalidChars
+ " found at depth " + depth
;
576 var indexValue
= parseInt(index
.replace("'", ""));
578 return "Invalid number at depth " + depth
;
580 if (indexValue
> maxIndexValue
) {
581 return "Value of " + indexValue
+ " at depth " + depth
+ " must be less than " + maxIndexValue
;
585 // Check root key exists or else derivation path is useless!
587 return "No root key";
589 // Check no hardened derivation path when using xpub keys
590 var hardenedPath
= path
.indexOf("'") > -1;
591 var hardenedAddresses
= bip32TabSelected() && DOM
.hardenedAddresses
.prop("checked");
592 var hardened
= hardenedPath
|| hardenedAddresses
;
593 var isXpubkey
= bip32RootKey
.isNeutered();
594 if (hardened
&& isXpubkey
) {
595 return "Hardened derivation path is invalid with xpub key";
600 function displayBip44Info() {
601 // Get the derivation path for the account
602 var purpose
= parseIntNoNaN(DOM
.bip44purpose
.val(), 44);
603 var coin
= parseIntNoNaN(DOM
.bip44coin
.val(), 0);
604 var account
= parseIntNoNaN(DOM
.bip44account
.val(), 0);
606 path
+= purpose
+ "'/";
608 path
+= account
+ "'/";
609 // Calculate the account extended keys
610 var accountExtendedKey
= calcBip32ExtendedKey(path
);
611 var accountXprv
= accountExtendedKey
.toBase58();
612 var accountXpub
= accountExtendedKey
.neutered().toBase58();
613 // Display the extended keys
614 DOM
.bip44accountXprv
.val(accountXprv
);
615 DOM
.bip44accountXpub
.val(accountXpub
);
618 function displayBip49Info() {
619 // Get the derivation path for the account
620 var purpose
= parseIntNoNaN(DOM
.bip49purpose
.val(), 49);
621 var coin
= parseIntNoNaN(DOM
.bip49coin
.val(), 0);
622 var account
= parseIntNoNaN(DOM
.bip49account
.val(), 0);
624 path
+= purpose
+ "'/";
626 path
+= account
+ "'/";
627 // Calculate the account extended keys
628 var accountExtendedKey
= calcBip32ExtendedKey(path
);
629 var accountXprv
= accountExtendedKey
.toBase58();
630 var accountXpub
= accountExtendedKey
.neutered().toBase58();
631 // Display the extended keys
632 DOM
.bip49accountXprv
.val(accountXprv
);
633 DOM
.bip49accountXpub
.val(accountXpub
);
636 function displayBip32Info() {
639 var rootKey
= bip32RootKey
.toBase58();
640 DOM
.rootKey
.val(rootKey
);
641 var xprvkeyB58
= "NA";
642 if (!bip32ExtendedKey
.isNeutered()) {
643 xprvkeyB58
= bip32ExtendedKey
.toBase58();
645 var extendedPrivKey
= xprvkeyB58
;
646 DOM
.extendedPrivKey
.val(extendedPrivKey
);
647 var extendedPubKey
= bip32ExtendedKey
.neutered().toBase58();
648 DOM
.extendedPubKey
.val(extendedPubKey
);
649 // Display the addresses and privkeys
650 clearAddressesList();
651 displayAddresses(0, 20);
654 function displayAddresses(start
, total
) {
655 generationProcesses
.push(new (function() {
659 this.stop = function() {
660 for (var i
=0; i
<rows
.length
; i
++) {
661 rows
[i
].shouldGenerate
= false;
666 for (var i
=0; i
<total
; i
++) {
667 var index
= i
+ start
;
668 var isLast
= i
== total
- 1;
669 rows
.push(new TableRow(index
, isLast
));
675 function segwitSelected() {
676 return bip49TabSelected();
679 function TableRow(index
, isLast
) {
682 this.shouldGenerate
= true;
683 var useHardenedAddresses
= DOM
.hardenedAddresses
.prop("checked");
684 var isSegwit
= segwitSelected();
685 var segwitAvailable
= networkHasSegwit();
691 function calculateValues() {
692 setTimeout(function() {
693 if (!self
.shouldGenerate
) {
697 if (useHardenedAddresses
) {
698 key
= bip32ExtendedKey
.deriveHardened(index
);
701 key
= bip32ExtendedKey
.derive(index
);
703 var address
= key
.getAddress().toString();
705 if (!key
.isNeutered()) {
706 privkey
= key
.keyPair
.toWIF(network
);
708 var pubkey
= key
.getPublicKeyBuffer().toString('hex');
709 var indexText
= getDerivationPath() + "/" + index
;
710 if (useHardenedAddresses
) {
711 indexText
= indexText
+ "'";
713 // Ethereum values are different
714 if (networks
[DOM
.network
.val()].name
== "ETH - Ethereum") {
715 var privKeyBuffer
= key
.keyPair
.d
.toBuffer();
716 privkey
= privKeyBuffer
.toString('hex');
717 var addressBuffer
= ethUtil
.privateToAddress(privKeyBuffer
);
718 var hexAddress
= addressBuffer
.toString('hex');
719 var checksumAddress
= ethUtil
.toChecksumAddress(hexAddress
);
720 address
= ethUtil
.addHexPrefix(checksumAddress
);
721 privkey
= ethUtil
.addHexPrefix(privkey
);
722 pubkey
= ethUtil
.addHexPrefix(pubkey
);
724 // Ripple values are different
725 if (networks
[DOM
.network
.val()].name
== "XRP - Ripple") {
726 privkey
= convertRipplePriv(privkey
);
727 address
= convertRippleAdrr(address
);
729 // Segwit addresses are different
731 if (!segwitAvailable
) {
734 var keyhash
= bitcoinjs
.bitcoin
.crypto
.hash160(key
.getPublicKeyBuffer());
735 var scriptsig
= bitcoinjs
.bitcoin
.script
.witnessPubKeyHash
.output
.encode(keyhash
);
736 var addressbytes
= bitcoinjs
.bitcoin
.crypto
.hash160(scriptsig
);
737 var scriptpubkey
= bitcoinjs
.bitcoin
.script
.scriptHash
.output
.encode(addressbytes
);
738 address
= bitcoinjs
.bitcoin
.address
.fromOutputScript(scriptpubkey
, network
)
740 addAddressToList(indexText
, address
, pubkey
, privkey
);
751 function showMore() {
752 var rowsToAdd
= parseInt(DOM
.rowsToAdd
.val());
753 if (isNaN(rowsToAdd
)) {
755 DOM
.rowsToAdd
.val("20");
757 var start
= parseInt(DOM
.moreRowsStartIndex
.val())
759 start
= lastIndexInTable() + 1;
762 var newStart
= start
+ rowsToAdd
;
763 DOM
.moreRowsStartIndex
.val(newStart
);
765 if (rowsToAdd
> 200) {
766 var msg
= "Generating " + rowsToAdd
+ " rows could take a while. ";
767 msg
+= "Do you want to continue?";
772 displayAddresses(start
, rowsToAdd
);
775 function clearDisplay() {
776 clearAddressesList();
778 hideValidationError();
781 function clearAddressesList() {
782 DOM
.addresses
.empty();
786 function stopGenerating() {
787 while (generationProcesses
.length
> 0) {
788 var generation
= generationProcesses
.shift();
793 function clearKeys() {
798 function clearRootKey() {
802 function clearDerivedKeys() {
803 DOM
.extendedPrivKey
.val("");
804 DOM
.extendedPubKey
.val("");
805 DOM
.bip44accountXprv
.val("");
806 DOM
.bip44accountXpub
.val("");
809 function addAddressToList(indexText
, address
, pubkey
, privkey
) {
810 var row
= $(addressRowTemplate
.html());
812 var indexCell
= row
.find(".index span");
813 var addressCell
= row
.find(".address span");
814 var pubkeyCell
= row
.find(".pubkey span");
815 var privkeyCell
= row
.find(".privkey span");
817 indexCell
.text(indexText
);
818 addressCell
.text(address
);
819 pubkeyCell
.text(pubkey
);
820 privkeyCell
.text(privkey
);
823 indexCell
.addClass("invisible");
826 addressCell
.addClass("invisible");
829 pubkeyCell
.addClass("invisible");
832 privkeyCell
.addClass("invisible");
834 DOM
.addresses
.append(row
);
835 var rowShowQrEls
= row
.find("[data-show-qr]");
836 setQrEvents(rowShowQrEls
);
839 function hasStrongRandom() {
840 return 'crypto' in window
&& window
['crypto'] !== null;
843 function disableForms() {
844 $("form").on("submit", function(e
) {
849 function parseIntNoNaN(val
, defaultVal
) {
850 var v
= parseInt(val
);
857 function showPending() {
859 .text("Calculating...")
863 function findNearestWord(word
) {
864 var language
= getLanguage();
865 var words
= WORDLISTS
[language
];
866 var minDistance
= 99;
867 var closestWord
= words
[0];
868 for (var i
=0; i
<words
.length
; i
++) {
869 var comparedTo
= words
[i
];
870 if (comparedTo
.indexOf(word
) == 0) {
873 var distance
= Levenshtein
.get(word
, comparedTo
);
874 if (distance
< minDistance
) {
875 closestWord
= comparedTo
;
876 minDistance
= distance
;
882 function hidePending() {
888 function populateNetworkSelect() {
889 for (var i
=0; i
<networks
.length
; i
++) {
890 var network
= networks
[i
];
891 var option
= $("<option>");
892 option
.attr("value", i
);
893 option
.text(network
.name
);
894 if (network
.name
== "BTC - Bitcoin") {
895 option
.prop("selected", true);
897 DOM
.phraseNetwork
.append(option
);
901 function populateClientSelect() {
902 for (var i
=0; i
<clients
.length
; i
++) {
903 var client
= clients
[i
];
904 var option
= $("<option>");
905 option
.attr("value", i
);
906 option
.text(client
.name
);
907 DOM
.bip32Client
.append(option
);
911 function getLanguage() {
912 var defaultLanguage
= "english";
913 // Try to get from existing phrase
914 var language
= getLanguageFromPhrase();
915 // Try to get from url if not from phrase
916 if (language
.length
== 0) {
917 language
= getLanguageFromUrl();
919 // Default to English if no other option
920 if (language
.length
== 0) {
921 language
= defaultLanguage
;
926 function getLanguageFromPhrase(phrase
) {
927 // Check if how many words from existing phrase match a language.
930 phrase
= DOM
.phrase
.val();
932 if (phrase
.length
> 0) {
933 var words
= phraseToWordArray(phrase
);
934 var languageMatches
= {};
935 for (l
in WORDLISTS
) {
936 // Track how many words match in this language
937 languageMatches
[l
] = 0;
938 for (var i
=0; i
<words
.length
; i
++) {
939 var wordInLanguage
= WORDLISTS
[l
].indexOf(words
[i
]) > -1;
940 if (wordInLanguage
) {
941 languageMatches
[l
]++;
944 // Find languages with most word matches.
945 // This is made difficult due to commonalities between Chinese
946 // simplified vs traditional.
948 var mostMatchedLanguages
= [];
949 for (var l
in languageMatches
) {
950 var numMatches
= languageMatches
[l
];
951 if (numMatches
> mostMatches
) {
952 mostMatches
= numMatches
;
953 mostMatchedLanguages
= [l
];
955 else if (numMatches
== mostMatches
) {
956 mostMatchedLanguages
.push(l
);
960 if (mostMatchedLanguages
.length
> 0) {
961 // Use first language and warn if multiple detected
962 language
= mostMatchedLanguages
[0];
963 if (mostMatchedLanguages
.length
> 1) {
964 console
.warn("Multiple possible languages");
965 console
.warn(mostMatchedLanguages
);
972 function getLanguageFromUrl() {
973 for (var language
in WORDLISTS
) {
974 if (window
.location
.hash
.indexOf(language
) > -1) {
981 function setMnemonicLanguage() {
982 var language
= getLanguage();
983 // Load the bip39 mnemonic generator for this language if required
984 if (!(language
in mnemonics
)) {
985 mnemonics
[language
] = new Mnemonic(language
);
987 mnemonic
= mnemonics
[language
];
990 function convertPhraseToNewLanguage() {
991 var oldLanguage
= getLanguageFromPhrase();
992 var newLanguage
= getLanguageFromUrl();
993 var oldPhrase
= DOM
.phrase
.val();
994 var oldWords
= phraseToWordArray(oldPhrase
);
996 for (var i
=0; i
<oldWords
.length
; i
++) {
997 var oldWord
= oldWords
[i
];
998 var index
= WORDLISTS
[oldLanguage
].indexOf(oldWord
);
999 var newWord
= WORDLISTS
[newLanguage
][index
];
1000 newWords
.push(newWord
);
1002 newPhrase
= wordArrayToPhrase(newWords
);
1006 // TODO look at jsbip39 - mnemonic.splitWords
1007 function phraseToWordArray(phrase
) {
1008 var words
= phrase
.split(/\s/g);
1010 for (var i
=0; i
<words
.length
; i
++) {
1011 var word
= words
[i
];
1012 if (word
.length
> 0) {
1013 noBlanks
.push(word
);
1019 // TODO look at jsbip39 - mnemonic.joinWords
1020 function wordArrayToPhrase(words
) {
1021 var phrase
= words
.join(" ");
1022 var language
= getLanguageFromPhrase(phrase
);
1023 if (language
== "japanese") {
1024 phrase
= words
.join("\u3000");
1029 function isUsingOwnEntropy() {
1030 return DOM
.useEntropy
.prop("checked");
1033 function setMnemonicFromEntropy() {
1034 clearEntropyFeedback();
1035 // Get entropy value
1036 var entropyStr
= DOM
.entropy
.val();
1037 // Work out minimum base for entropy
1038 var entropy
= Entropy
.fromString(entropyStr
);
1039 if (entropy
.binaryStr
.length
== 0) {
1042 // Show entropy details
1043 showEntropyFeedback(entropy
);
1044 // Use entropy hash if not using raw entropy
1045 var bits
= entropy
.binaryStr
;
1046 var mnemonicLength
= DOM
.entropyMnemonicLength
.val();
1047 if (mnemonicLength
!= "raw") {
1048 // Get bits by hashing entropy with SHA256
1049 var hash
= sjcl
.hash
.sha256
.hash(entropy
.cleanStr
);
1050 var hex
= sjcl
.codec
.hex
.fromBits(hash
);
1051 bits
= BigInteger
.parse(hex
, 16).toString(2);
1052 while (bits
.length
% 256 != 0) {
1055 // Truncate hash to suit number of words
1056 mnemonicLength
= parseInt(mnemonicLength
);
1057 var numberOfBits
= 32 * mnemonicLength
/ 3;
1058 bits
= bits
.substring(0, numberOfBits
);
1060 // Discard trailing entropy
1061 var bitsToUse
= Math
.floor(bits
.length
/ 32) * 32;
1062 var start
= bits
.length
- bitsToUse
;
1063 var binaryStr
= bits
.substring(start
);
1064 // Convert entropy string to numeric array
1065 var entropyArr
= [];
1066 for (var i
=0; i
<binaryStr
.length
/ 8; i
++) {
1067 var byteAsBits
= binaryStr
.substring(i
*8, i
*8+8);
1068 var entropyByte
= parseInt(byteAsBits
, 2);
1069 entropyArr
.push(entropyByte
)
1071 // Convert entropy array to mnemonic
1072 var phrase
= mnemonic
.toMnemonic(entropyArr
);
1073 // Set the mnemonic in the UI
1074 DOM
.phrase
.val(phrase
);
1077 function clearEntropyFeedback() {
1078 DOM
.entropyCrackTime
.text("...");
1079 DOM
.entropyType
.text("");
1080 DOM
.entropyWordCount
.text("0");
1081 DOM
.entropyEventCount
.text("0");
1082 DOM
.entropyBitsPerEvent
.text("0");
1083 DOM
.entropyBits
.text("0");
1084 DOM
.entropyFiltered
.html(" ");
1085 DOM
.entropyBinary
.html(" ");
1088 function showEntropyFeedback(entropy
) {
1089 var numberOfBits
= entropy
.binaryStr
.length
;
1090 var timeToCrack
= "unknown";
1092 var z
= zxcvbn(entropy
.base
.parts
.join(""));
1093 timeToCrack
= z
.crack_times_display
.offline_fast_hashing_1e10_per_second
;
1094 if (z
.feedback
.warning
!= "") {
1095 timeToCrack
= timeToCrack
+ " - " + z
.feedback
.warning
;
1099 console
.log("Error detecting entropy strength with zxcvbn:");
1102 var entropyTypeStr
= getEntropyTypeStr(entropy
);
1103 var wordCount
= Math
.floor(numberOfBits
/ 32) * 3;
1104 var bitsPerEvent
= entropy
.bitsPerEvent
.toFixed(2);
1105 DOM
.entropyFiltered
.html(entropy
.cleanHtml
);
1106 DOM
.entropyType
.text(entropyTypeStr
);
1107 DOM
.entropyCrackTime
.text(timeToCrack
);
1108 DOM
.entropyEventCount
.text(entropy
.base
.ints
.length
);
1109 DOM
.entropyBits
.text(numberOfBits
);
1110 DOM
.entropyWordCount
.text(wordCount
);
1111 DOM
.entropyBinary
.text(entropy
.binaryStr
);
1112 DOM
.entropyBitsPerEvent
.text(bitsPerEvent
);
1113 // detect and warn of filtering
1114 var rawNoSpaces
= DOM
.entropy
.val().replace(/\s/g, "");
1115 var cleanNoSpaces
= entropy
.cleanStr
.replace(/\s/g, "");
1116 var isFiltered
= rawNoSpaces
.length
!= cleanNoSpaces
.length
;
1118 DOM
.entropyFilterWarning
.removeClass('hidden');
1121 DOM
.entropyFilterWarning
.addClass('hidden');
1125 function getEntropyTypeStr(entropy
) {
1126 var typeStr
= entropy
.base
.str
;
1127 // Add some detail if these are cards
1128 if (entropy
.base
.asInt
== 52) {
1129 var cardDetail
= []; // array of message strings
1130 // Detect duplicates
1132 var dupeTracker
= {};
1133 for (var i
=0; i
<entropy
.base
.parts
.length
; i
++) {
1134 var card
= entropy
.base
.parts
[i
];
1135 var cardUpper
= card
.toUpperCase();
1136 if (cardUpper
in dupeTracker
) {
1139 dupeTracker
[cardUpper
] = true;
1141 if (dupes
.length
> 0) {
1142 var dupeWord
= "duplicates";
1143 if (dupes
.length
== 1) {
1144 dupeWord
= "duplicate";
1146 var msg
= dupes
.length
+ " " + dupeWord
+ ": " + dupes
.slice(0,3).join(" ");
1147 if (dupes
.length
> 3) {
1150 cardDetail
.push(msg
);
1153 var uniqueCards
= [];
1154 for (var uniqueCard
in dupeTracker
) {
1155 uniqueCards
.push(uniqueCard
);
1157 if (uniqueCards
.length
== 52) {
1158 cardDetail
.unshift("full deck");
1160 // Detect missing cards
1161 var values
= "A23456789TJQK";
1163 var missingCards
= [];
1164 for (var i
=0; i
<suits
.length
; i
++) {
1165 for (var j
=0; j
<values
.length
; j
++) {
1166 var card
= values
[j
] + suits
[i
];
1167 if (!(card
in dupeTracker
)) {
1168 missingCards
.push(card
);
1172 // Display missing cards if six or less, ie clearly going for full deck
1173 if (missingCards
.length
> 0 && missingCards
.length
<= 6) {
1174 var msg
= missingCards
.length
+ " missing: " + missingCards
.slice(0,3).join(" ");
1175 if (missingCards
.length
> 3) {
1178 cardDetail
.push(msg
);
1180 // Add card details to typeStr
1181 if (cardDetail
.length
> 0) {
1182 typeStr
+= " (" + cardDetail
.join(", ") + ")";
1188 function setQrEvents(els
) {
1189 els
.on("mouseenter", createQr
);
1190 els
.on("mouseleave", destroyQr
);
1191 els
.on("click", toggleQr
);
1194 function createQr(e
) {
1195 var content
= e
.target
.textContent
|| e
.target
.value
;
1198 DOM
.qrImage
.qrcode({width: size
, height: size
, text: content
});
1200 DOM
.qrHider
.addClass("hidden");
1203 DOM
.qrHider
.removeClass("hidden");
1205 DOM
.qrContainer
.removeClass("hidden");
1209 function destroyQr() {
1210 DOM
.qrImage
.text("");
1211 DOM
.qrContainer
.addClass("hidden");
1214 function toggleQr() {
1216 DOM
.qrHider
.toggleClass("hidden");
1217 DOM
.qrHint
.toggleClass("hidden");
1220 function bip44TabSelected() {
1221 return DOM
.bip44tab
.hasClass("active");
1224 function bip32TabSelected() {
1225 return DOM
.bip32tab
.hasClass("active");
1228 function networkHasSegwit() {
1229 return networks
[DOM
.network
.val()].segwitAvailable
;
1232 function bip49TabSelected() {
1233 return DOM
.bip49tab
.hasClass("active");
1236 function setHdCoin(coinValue
) {
1237 DOM
.bip44coin
.val(coinValue
);
1238 DOM
.bip49coin
.val(coinValue
);
1241 function showSegwitAvailable() {
1242 DOM
.bip49unavailable
.addClass("hidden");
1243 DOM
.bip49available
.removeClass("hidden");
1246 function showSegwitUnavailable() {
1247 DOM
.bip49available
.addClass("hidden");
1248 DOM
.bip49unavailable
.removeClass("hidden");
1251 function useBitpayAddresses() {
1252 return !(DOM
.useBitpayAddresses
.prop("checked"));
1255 function setBitcoinCashNetworkValues() {
1256 if (useBitpayAddresses()) {
1257 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1260 network
= bitcoinjs
.bitcoin
.networks
.bitcoinCashBitbpay
;
1264 function adjustNetworkForSegwit() {
1265 // If segwit is selected the xpub/xprv prefixes need to be adjusted
1266 // to avoid accidentally importing BIP49 xpub to BIP44 watch only
1268 // See https://github.com/iancoleman/bip39/issues/125
1269 if (segwitSelected()) {
1270 if (network
== bitcoinjs
.bitcoin
.networks
.bitcoin
) {
1271 network
= bitcoinjs
.bitcoin
.networks
.bitcoinBip49
;
1273 else if (network
== bitcoinjs
.bitcoin
.networks
.testnet
) {
1274 network
= bitcoinjs
.bitcoin
.networks
.testnetBip49
;
1276 else if (network
== bitcoinjs
.bitcoin
.networks
.litecoin
) {
1277 network
= bitcoinjs
.bitcoin
.networks
.litecoinBip49
;
1281 if (network
== bitcoinjs
.bitcoin
.networks
.bitcoinBip49
) {
1282 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1284 else if (network
== bitcoinjs
.bitcoin
.networks
.testnetBip49
) {
1285 network
= bitcoinjs
.bitcoin
.networks
.testnet
;
1287 else if (network
== bitcoinjs
.bitcoin
.networks
.litecoinBip49
) {
1288 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
1293 function lastIndexInTable() {
1294 var pathText
= DOM
.addresses
.find(".index").last().text();
1295 var pathBits
= pathText
.split("/");
1296 var lastBit
= pathBits
[pathBits
.length
-1];
1297 var lastBitClean
= lastBit
.replace("'", "");
1298 return parseInt(lastBitClean
);
1303 name: "BCH - Bitcoin Cash",
1304 segwitAvailable: false,
1305 onSelect: function() {
1306 DOM
.useBitpayAddressesContainer
.removeClass("hidden");
1307 setBitcoinCashNetworkValues();
1312 name: "BTC - Bitcoin",
1313 segwitAvailable: true,
1314 onSelect: function() {
1315 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1320 name: "BTC - Bitcoin Testnet",
1321 segwitAvailable: true,
1322 onSelect: function() {
1323 network
= bitcoinjs
.bitcoin
.networks
.testnet
;
1328 name: "BTG - Bitcoin Gold",
1329 segwitAvailable: true,
1330 onSelect: function() {
1331 network
= bitcoinjs
.bitcoin
.networks
.bgold
;
1336 name: "CLAM - Clams",
1337 segwitAvailable: false,
1338 onSelect: function() {
1339 network
= bitcoinjs
.bitcoin
.networks
.clam
;
1344 name: "CRW - Crown",
1345 segwitAvailable: false,
1346 onSelect: function() {
1347 network
= bitcoinjs
.bitcoin
.networks
.crown
;
1352 name: "DASH - Dash",
1353 segwitAvailable: false,
1354 onSelect: function() {
1355 network
= bitcoinjs
.bitcoin
.networks
.dash
;
1360 name: "DASH - Dash Testnet",
1361 segwitAvailable: false,
1362 onSelect: function() {
1363 network
= bitcoinjs
.bitcoin
.networks
.dashtn
;
1368 name: "DOGE - Dogecoin",
1369 segwitAvailable: false,
1370 onSelect: function() {
1371 network
= bitcoinjs
.bitcoin
.networks
.dogecoin
;
1376 name: "ETH - Ethereum",
1377 segwitAvailable: false,
1378 onSelect: function() {
1379 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1384 name: "FJC - Fujicoin",
1385 segwitAvailable: false,
1386 onSelect: function() {
1387 network
= bitcoinjs
.bitcoin
.networks
.fujicoin
;
1392 name: "GAME - GameCredits",
1393 segwitAvailable: false,
1394 onSelect: function() {
1395 network
= bitcoinjs
.bitcoin
.networks
.game
;
1400 name: "JBS - Jumbucks",
1401 segwitAvailable: false,
1402 onSelect: function() {
1403 network
= bitcoinjs
.bitcoin
.networks
.jumbucks
;
1408 name: "LTC - Litecoin",
1409 segwitAvailable: true,
1410 onSelect: function() {
1411 network
= bitcoinjs
.bitcoin
.networks
.litecoin
;
1413 DOM
.litecoinLtubContainer
.removeClass("hidden");
1417 name: "MAZA - Maza",
1418 segwitAvailable: false,
1419 onSelect: function() {
1420 network
= bitcoinjs
.bitcoin
.networks
.maza
;
1425 name: "MONA - Monacoin",
1426 segwitAvailable: true,
1427 onSelect: function() {
1428 network
= bitcoinjs
.bitcoin
.networks
.monacoin
,
1433 name: "NMC - Namecoin",
1434 segwitAvailable: false,
1435 onSelect: function() {
1436 network
= bitcoinjs
.bitcoin
.networks
.namecoin
;
1441 name: "PIVX - PIVX",
1442 segwitAvailable: false,
1443 onSelect: function() {
1444 network
= bitcoinjs
.bitcoin
.networks
.pivx
;
1449 name: "PIVX - PIVX Testnet",
1450 segwitAvailable: false,
1451 onSelect: function() {
1452 network
= bitcoinjs
.bitcoin
.networks
.pivxtestnet
;
1457 name: "PPC - Peercoin",
1458 segwitAvailable: false,
1459 onSelect: function() {
1460 network
= bitcoinjs
.bitcoin
.networks
.peercoin
;
1465 name: "SDC - ShadowCash",
1466 segwitAvailable: false,
1467 onSelect: function() {
1468 network
= bitcoinjs
.bitcoin
.networks
.shadow
;
1473 name: "SDC - ShadowCash Testnet",
1474 segwitAvailable: false,
1475 onSelect: function() {
1476 network
= bitcoinjs
.bitcoin
.networks
.shadowtn
;
1481 name: "SLM - Slimcoin",
1482 segwitAvailable: false,
1483 onSelect: function() {
1484 network
= bitcoinjs
.bitcoin
.networks
.slimcoin
;
1489 name: "SLM - Slimcoin Testnet",
1490 segwitAvailable: false,
1491 onSelect: function() {
1492 network
= bitcoinjs
.bitcoin
.networks
.slimcointn
;
1497 name: "USNBT - NuBits",
1498 segwitAvailable: false,
1499 onSelect: function() {
1500 network
= bitcoinjs
.bitcoin
.networks
.nubits
;
1505 name: "VIA - Viacoin",
1506 segwitAvailable: false,
1507 onSelect: function() {
1508 network
= bitcoinjs
.bitcoin
.networks
.viacoin
;
1513 name: "VIA - Viacoin Testnet",
1514 segwitAvailable: false,
1515 onSelect: function() {
1516 network
= bitcoinjs
.bitcoin
.networks
.viacointestnet
;
1521 name: "XMY - Myriadcoin",
1522 segwitAvailable: false,
1523 onSelect: function() {
1524 network
= bitcoinjs
.bitcoin
.networks
.myriadcoin
;
1529 name: "XRP - Ripple",
1530 segwitAvailable: false,
1531 onSelect: function() {
1532 network
= bitcoinjs
.bitcoin
.networks
.bitcoin
;
1540 name: "Bitcoin Core",
1541 onSelect: function() {
1542 DOM
.bip32path
.val("m/0'/0'");
1543 DOM
.hardenedAddresses
.prop('checked', true);
1547 name: "blockchain.info",
1548 onSelect: function() {
1549 DOM
.bip32path
.val("m/44'/0'/0'");
1550 DOM
.hardenedAddresses
.prop('checked', false);
1554 name: "MultiBit HD",
1555 onSelect: function() {
1556 DOM
.bip32path
.val("m/0'/0");
1557 DOM
.hardenedAddresses
.prop('checked', false);