]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/entropy.js
BigInteger library moved to own file
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / entropy.js
1 /*
2 * Detects entropy from a string.
3 *
4 * Formats include:
5 * binary [0-1]
6 * base 6 [0-5]
7 * dice 6 [1-6]
8 * decimal [0-9]
9 * hexadecimal [0-9A-F]
10 *
11 * Automatically uses lowest entropy to avoid issues such as interpretting 0101
12 * as hexadecimal which would be 16 bits when really it's only 4 bits of binary
13 * entropy.
14 */
15
16 window.Entropy = new (function() {
17
18 // matchers returns an array of the matched events for each type of entropy.
19 // eg
20 // matchers.binary("010") returns ["0", "1", "0"]
21 // matchers.binary("a10") returns ["1", "0"]
22 // matchers.hex("a10") returns ["a", "1", "0"]
23 var matchers = {
24 binary: function(str) {
25 return str.match(/[0-1]/gi) || [];
26 },
27 base6: function(str) {
28 return str.match(/[0-5]/gi) || [];
29 },
30 dice: function(str) {
31 return str.match(/[1-6]/gi) || []; // ie dice numbers
32 },
33 base10: function(str) {
34 return str.match(/[0-9]/gi) || [];
35 },
36 hex: function(str) {
37 return str.match(/[0-9A-F]/gi) || [];
38 },
39 card: function(str) {
40 // Format is NumberSuit, eg
41 // AH ace of hearts
42 // 8C eight of clubs
43 // TD ten of diamonds
44 // JS jack of spades
45 // QH queen of hearts
46 // KC king of clubs
47 return str.match(/([A2-9TJQK][CDHS])/gi) || [];
48 }
49 }
50
51 // Convert array of cards from ["ac", "4d", "ks"]
52 // to numbers between 0 and 51 [0, 16, 51]
53 function convertCardsToInts(cards) {
54 var ints = [];
55 var values = "a23456789tjqk";
56 var suits = "cdhs";
57 for (var i=0; i<cards.length; i++) {
58 var card = cards[i].toLowerCase();
59 var value = card[0];
60 var suit = card[1];
61 var asInt = 13 * suits.indexOf(suit) + values.indexOf(value);
62 ints.push(asInt);
63 }
64 return ints;
65 }
66
67 this.fromString = function(rawEntropyStr) {
68 // Find type of entropy being used (binary, hex, dice etc)
69 var base = getBase(rawEntropyStr);
70 // Convert dice to base6 entropy (ie 1-6 to 0-5)
71 // This is done by changing all 6s to 0s
72 if (base.str == "dice") {
73 var newParts = [];
74 var newInts = [];
75 for (var i=0; i<base.parts.length; i++) {
76 var c = base.parts[i];
77 if ("12345".indexOf(c) > -1) {
78 newParts[i] = base.parts[i];
79 newInts[i] = base.ints[i];
80 }
81 else {
82 newParts[i] = "0";
83 newInts[i] = 0;
84 }
85 }
86 base.str = "base 6 (dice)";
87 base.ints = newInts;
88 base.parts = newParts;
89 base.matcher = matchers.base6;
90 }
91 // Detect empty entropy
92 if (base.parts.length == 0) {
93 return {
94 binaryStr: "",
95 cleanStr: "",
96 cleanHtml: "",
97 base: base,
98 };
99 }
100 // Convert base.ints to BigInteger.
101 // Due to using unusual bases, eg cards of base52, this is not as simple as
102 // using BigInteger.parse()
103 var entropyInt = BigInteger.ZERO;
104 for (var i=base.ints.length-1; i>=0; i--) {
105 var thisInt = BigInteger.parse(base.ints[i]);
106 var power = (base.ints.length - 1) - i;
107 var additionalEntropy = BigInteger.parse(base.asInt).pow(power).multiply(thisInt);
108 entropyInt = entropyInt.add(additionalEntropy);
109 }
110 // Convert entropy to binary
111 var entropyBin = entropyInt.toString(2);
112 // If the first integer is small, it must be padded with zeros.
113 // Otherwise the chance of the first bit being 1 is 100%, which is
114 // obviously incorrect.
115 // This is not perfect for non-2^n bases.
116 var expectedBits = Math.floor(base.parts.length * Math.log2(base.asInt));
117 while (entropyBin.length < expectedBits) {
118 entropyBin = "0" + entropyBin;
119 }
120 // Supply a 'filtered' entropy string for display purposes
121 var entropyClean = base.parts.join("");
122 var entropyHtml = base.parts.join("");
123 if (base.asInt == 52) {
124 entropyClean = base.parts.join(" ").toUpperCase();
125 entropyClean = entropyClean.replace(/C/g, "\u2663");
126 entropyClean = entropyClean.replace(/D/g, "\u2666");
127 entropyClean = entropyClean.replace(/H/g, "\u2665");
128 entropyClean = entropyClean.replace(/S/g, "\u2660");
129 entropyHtml = base.parts.join(" ").toUpperCase();
130 entropyHtml = entropyHtml.replace(/C/g, "<span class='card-suit club'>\u2663</span>");
131 entropyHtml = entropyHtml.replace(/D/g, "<span class='card-suit diamond'>\u2666</span>");
132 entropyHtml = entropyHtml.replace(/H/g, "<span class='card-suit heart'>\u2665</span>");
133 entropyHtml = entropyHtml.replace(/S/g, "<span class='card-suit spade'>\u2660</span>");
134 }
135 var e = {
136 binaryStr: entropyBin,
137 cleanStr: entropyClean,
138 cleanHtml: entropyHtml,
139 base: base,
140 }
141 return e;
142 }
143
144 function getBase(str) {
145 // Need to get the lowest base for the supplied entropy.
146 // This prevents interpreting, say, dice rolls as hexadecimal.
147 var binaryMatches = matchers.binary(str);
148 var hexMatches = matchers.hex(str);
149 // Find the lowest base that can be used, whilst ignoring any irrelevant chars
150 if (binaryMatches.length == hexMatches.length && hexMatches.length > 0) {
151 var ints = binaryMatches.map(function(i) { return parseInt(i, 2) });
152 return {
153 ints: ints,
154 parts: binaryMatches,
155 matcher: matchers.binary,
156 asInt: 2,
157 str: "binary",
158 }
159 }
160 var cardMatches = matchers.card(str);
161 if (cardMatches.length >= hexMatches.length / 2) {
162 var ints = convertCardsToInts(cardMatches);
163 return {
164 ints: ints,
165 parts: cardMatches,
166 matcher: matchers.card,
167 asInt: 52,
168 str: "card",
169 }
170 }
171 var diceMatches = matchers.dice(str);
172 if (diceMatches.length == hexMatches.length && hexMatches.length > 0) {
173 var ints = diceMatches.map(function(i) { return parseInt(i) });
174 return {
175 ints: ints,
176 parts: diceMatches,
177 matcher: matchers.dice,
178 asInt: 6,
179 str: "dice",
180 }
181 }
182 var base6Matches = matchers.base6(str);
183 if (base6Matches.length == hexMatches.length && hexMatches.length > 0) {
184 var ints = base6Matches.map(function(i) { return parseInt(i) });
185 return {
186 ints: ints,
187 parts: base6Matches,
188 matcher: matchers.base6,
189 asInt: 6,
190 str: "base 6",
191 }
192 }
193 var base10Matches = matchers.base10(str);
194 if (base10Matches.length == hexMatches.length && hexMatches.length > 0) {
195 var ints = base10Matches.map(function(i) { return parseInt(i) });
196 return {
197 ints: ints,
198 parts: base10Matches,
199 matcher: matchers.base10,
200 asInt: 10,
201 str: "base 10",
202 }
203 }
204 var ints = hexMatches.map(function(i) { return parseInt(i, 16) });
205 return {
206 ints: ints,
207 parts: hexMatches,
208 matcher: matchers.hex,
209 asInt: 16,
210 str: "hexadecimal",
211 }
212 }
213
214 // Polyfill for Math.log2
215 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill
216 Math.log2 = Math.log2 || function(x) {
217 // The polyfill isn't good enough because of the poor accuracy of
218 // Math.LOG2E
219 // log2(8) gave 2.9999999999999996 which when floored causes issues.
220 // So instead use the BigInteger library to get it right.
221 return BigInteger.log(x) / BigInteger.log(2);
222 };
223
224 })();