-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathrepair-passphrase.html
309 lines (267 loc) · 27.4 KB
/
repair-passphrase.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<!DOCTYPE html>
<html>
<head>
<title>Repair a Passphrase</title>
<script>
function myFunction() {
// 1626 word dictionary for passphrase
var words = ["like","just","love","know","never","want","time","out","there","make","look","eye","down","only","think","heart","back","then","into","about","more","away","still","them","take","thing","even","through","long","always","world","too","friend","tell","try","hand","thought","over","here","other","need","smile","again","much","cry","been","night","ever","little","said","end","some","those","around","mind","people","girl","leave","dream","left","turn","myself","give","nothing","really","off","before","something","find","walk","wish","good","once","place","ask","stop","keep","watch","seem","everything","wait","got","yet","made","remember","start","alone","run","hope","maybe","believe","body","hate","after","close","talk","stand","own","each","hurt","help","home","god","soul","new","many","two","inside","should","true","first","fear","mean","better","play","another","gone","change","use","wonder","someone","hair","cold","open","best","any","behind","happen","water","dark","laugh","stay","forever","name","work","show","sky","break","came","deep","door","put","black","together","upon","happy","such","great","white","matter","fill","past","please","burn","cause","enough","touch","moment","soon","voice","scream","anything","stare","sound","red","everyone","hide","kiss","truth","death","beautiful","mine","blood","broken","very","pass","next","forget","tree","wrong","air","mother","understand","lip","hit","wall","memory","sleep","free","high","realize","school","might","skin","sweet","perfect","blue","kill","breath","dance","against","fly","between","grow","strong","under","listen","bring","sometimes","speak","pull","person","become","family","begin","ground","real","small","father","sure","feet","rest","young","finally","land","across","today","different","guy","line","fire","reason","reach","second","slowly","write","eat","smell","mouth","step","learn","three","floor","promise","breathe","darkness","push","earth","guess","save","song","above","along","both","color","house","almost","sorry","anymore","brother","okay","dear","game","fade","already","apart","warm","beauty","heard","notice","question","shine","began","piece","whole","shadow","secret","street","within","finger","point","morning","whisper","child","moon","green","story","glass","kid","silence","since","soft","yourself","empty","shall","angel","answer","baby","bright","dad","path","worry","hour","drop","follow","power","war","half","flow","heaven","act","chance","fact","least","tired","children","near","quite","afraid","rise","sea","taste","window","cover","nice","trust","lot","sad","cool","force","peace","return","blind","easy","ready","roll","rose","drive","held","music","beneath","hang","mom","paint","emotion","quiet","clear","cloud","few","pretty","bird","outside","paper","picture","front","rock","simple","anyone","meant","reality","road","sense","waste","bit","leaf","thank","happiness","meet","men","smoke","truly","decide","self","age","book","form","alive","carry","escape","damn","instead","able","ice","minute","throw","catch","leg","ring","course","goodbye","lead","poem","sick","corner","desire","known","problem","remind","shoulder","suppose","toward","wave","drink","jump","woman","pretend","sister","week","human","joy","crack","grey","pray","surprise","dry","knee","less","search","bleed","caught","clean","embrace","future","king","son","sorrow","chest","hug","remain","sat","worth","blow","daddy","final","parent","tight","also","create","lonely","safe","cross","dress","evil","silent","bone","fate","perhaps","anger","class","scar","snow","tiny","tonight","continue","control","dog","edge","mirror","month","suddenly","comfort","given","loud","quickly","gaze","plan","rush","stone","town","battle","ignore","spirit","stood","stupid","yours","brown","build","dust","hey","kept","pay","phone","twist","although","ball","beyond","hidden","nose","taken","fail","float","pure","somehow","wash","wrap","angry","cheek","creature","forgotten","heat","rip","single","space","special","weak","whatever","yell","anyway","blame","job","choose","country","curse","drift","echo","figure","grew","laughter","neck","suffer","worse","yeah","disappear","foot","forward","knife","mess","somewhere","stomach","storm","beg","idea","lift","offer","breeze","field","five","often","simply","stuck","win","allow","confuse","enjoy","except","flower","seek","strength","calm","grin","gun","heavy","hill","large","ocean","shoe","sigh","straight","summer","tongue","accept","crazy","everyday","exist","grass","mistake","sent","shut","surround","table","ache","brain","destroy","heal","nature","shout","sign","stain","choice","doubt","glance","glow","mountain","queen","stranger","throat","tomorrow","city","either","fish","flame","rather","shape","spin","spread","ash","distance","finish","image","imagine","important","nobody","shatter","warmth","became","feed","flesh","funny","lust","shirt","trouble","yellow","attention","bare","bite","money","protect","amaze","appear","born","choke","completely","daughter","fresh","friendship","gentle","probably","six","deserve","expect","grab","middle","nightmare","river","thousand","weight","worst","wound","barely","bottle","cream","regret","relationship","stick","test","crush","endless","fault","itself","rule","spill","art","circle","join","kick","mask","master","passion","quick","raise","smooth","unless","wander","actually","broke","chair","deal","favorite","gift","note","number","sweat","box","chill","clothes","lady","mark","park","poor","sadness","tie","animal","belong","brush","consume","dawn","forest","innocent","pen","pride","stream","thick","clay","complete","count","draw","faith","press","silver","struggle","surface","taught","teach","wet","bless","chase","climb","enter","letter","melt","metal","movie","stretch","swing","vision","wife","beside","crash","forgot","guide","haunt","joke","knock","plant","pour","prove","reveal","steal","stuff","trip","wood","wrist","bother","bottom","crawl","crowd","fix","forgive","frown","grace","loose","lucky","party","release","surely","survive","teacher","gently","grip","speed","suicide","travel","treat","vein","written","cage","chain","conversation","date","enemy","however","interest","million","page","pink","proud","sway","themselves","winter","church","cruel","cup","demon","experience","freedom","pair","pop","purpose","respect","shoot","softly","state","strange","bar","birth","curl","dirt","excuse","lord","lovely","monster","order","pack","pants","pool","scene","seven","shame","slide","ugly","among","blade","blonde","closet","creek","deny","drug","eternity","gain","grade","handle","key","linger","pale","prepare","swallow","swim","tremble","wheel","won","cast","cigarette","claim","college","direction","dirty","gather","ghost","hundred","loss","lung","orange","present","swear","swirl","twice","wild","bitter","blanket","doctor","everywhere","flash","grown","knowledge","numb","pressure","radio","repeat","ruin","spend","unknown","buy","clock","devil","early","false","fantasy","pound","precious","refuse","sheet","teeth","welcome","add","ahead","block","bury","caress","content","depth","despite","distant","marry","purple","threw","whenever","bomb","dull","easily","grasp","hospital","innocence","normal","receive","reply","rhyme","shade","someday","sword","toe","visit","asleep","bought","center","consider","flat","hero","history","ink","insane","muscle","mystery","pocket","reflection","shove","silently","smart","soldier","spot","stress","train","type","view","whether","bus","energy","explain","holy","hunger","inch","magic","mix","noise","nowhere","prayer","presence","shock","snap","spider","study","thunder","trail","admit","agree","bag","bang","bound","butterfly","cute","exactly","explode","familiar","fold","further","pierce","reflect","scent","selfish","sharp","sink","spring","stumble","universe","weep","women","wonderful","action","ancient","attempt","avoid","birthday","branch","chocolate","core","depress","drunk","especially","focus","fruit","honest","match","palm","perfectly","pillow","pity","poison","roar","shift","slightly","thump","truck","tune","twenty","unable","wipe","wrote","coat","constant","dinner","drove","egg","eternal","flight","flood","frame","freak","gasp","glad","hollow","motion","peer","plastic","root","screen","season","sting","strike","team","unlike","victim","volume","warn","weird","attack","await","awake","built","charm","crave","despair","fought","grant","grief","horse","limit","message","ripple","sanity","scatter","serve","split","string","trick","annoy","blur","boat","brave","clearly","cling","connect","fist","forth","imagination","iron","jock","judge","lesson","milk","misery","nail","naked","ourselves","poet","possible","princess","sail","size","snake","society","stroke","torture","toss","trace","wise","bloom","bullet","cell","check","cost","darling","during","footstep","fragile","hallway","hardly","horizon","invisible","journey","midnight","mud","nod","pause","relax","shiver","sudden","value","youth","abuse","admire","blink","breast","bruise","constantly","couple","creep","curve","difference","dumb","emptiness","gotta","honor","plain","planet","recall","rub","ship","slam","soar","somebody","tightly","weather","adore","approach","bond","bread","burst","candle","coffee","cousin","crime","desert","flutter","frozen","grand","heel","hello","language","level","movement","pleasure","powerful","random","rhythm","settle","silly","slap","sort","spoken","steel","threaten","tumble","upset","aside","awkward","bee","blank","board","button","card","carefully","complain","crap","deeply","discover","drag","dread","effort","entire","fairy","giant","gotten","greet","illusion","jeans","leap","liquid","march","mend","nervous","nine","replace","rope","spine","stole","terror","accident","apple","balance","boom","childhood","collect","demand","depression","eventually","faint","glare","goal","group","honey","kitchen","laid","limb","machine","mere","mold","murder","nerve","painful","poetry","prince","rabbit","shelter","shore","shower","soothe","stair","steady","sunlight","tangle","tease","treasure","uncle","begun","bliss","canvas","cheer","claw","clutch","commit","crimson","crystal","delight","doll","existence","express","fog","football","gay","goose","guard","hatred","illuminate","mass","math","mourn","rich","rough","skip","stir","student","style","support","thorn","tough","yard","yearn","yesterday","advice","appreciate","autumn","bank","beam","bowl","capture","carve","collapse","confusion","creation","dove","feather","girlfriend","glory","government","harsh","hop","inner","loser","moonlight","neighbor","neither","peach","pig","praise","screw","shield","shimmer","sneak","stab","subject","throughout","thrown","tower","twirl","wow","army","arrive","bathroom","bump","cease","cookie","couch","courage","dim","guilt","howl","hum","husband","insult","led","lunch","mock","mostly","natural","nearly","needle","nerd","peaceful","perfection","pile","price","remove","roam","sanctuary","serious","shiny","shook","sob","stolen","tap","vain","void","warrior","wrinkle","affection","apologize","blossom","bounce","bridge","cheap","crumble","decision","descend","desperately","dig","dot","flip","frighten","heartbeat","huge","lazy","lick","odd","opinion","process","puzzle","quietly","retreat","score","sentence","separate","situation","skill","soak","square","stray","taint","task","tide","underneath","veil","whistle","anywhere","bedroom","bid","bloody","burden","careful","compare","concern","curtain","decay","defeat","describe","double","dreamer","driver","dwell","evening","flare","flicker","grandma","guitar","harm","horrible","hungry","indeed","lace","melody","monkey","nation","object","obviously","rainbow","salt","scratch","shown","shy","stage","stun","third","tickle","useless","weakness","worship","worthless","afternoon","beard","boyfriend","bubble","busy","certain","chin","concrete","desk","diamond","doom","drawn","due","felicity","freeze","frost","garden","glide","harmony","hopefully","hunt","jealous","lightning","mama","mercy","peel","physical","position","pulse","punch","quit","rant","respond","salty","sane","satisfy","savior","sheep","slept","social","sport","tuck","utter","valley","wolf","aim","alas","alter","arrow","awaken","beaten","belief","brand","ceiling","cheese","clue","confidence","connection","daily","disguise","eager","erase","essence","everytime","expression","fan","flag","flirt","foul","fur","giggle","glorious","ignorance","law","lifeless","measure","mighty","muse","north","opposite","paradise","patience","patient","pencil","petal","plate","ponder","possibly","practice","slice","spell","stock","strife","strip","suffocate","suit","tender","tool","trade","velvet","verse","waist","witch","aunt","bench","bold","cap","certainly","click","companion","creator","dart","delicate","determine","dish","dragon","drama","drum","dude","everybody","feast","forehead","former","fright","fully","gas","hook","hurl","invite","juice","manage","moral","possess","raw","rebel","royal","scale","scary","several","slight","stubborn","swell","talent","tea","terrible","thread","torment","trickle","usually","vast","violence","weave","acid","agony","ashamed","awe","belly","blend","blush","character","cheat","common","company","coward","creak","danger","deadly","defense","define","depend","desperate","destination","dew","duck","dusty","embarrass","engine","example","explore","foe","freely","frustrate","generation","glove","guilty","health","hurry","idiot","impossible","inhale","jaw","kingdom","mention","mist","moan","mumble","mutter","observe","ode","pathetic","pattern","pie","prefer","puff","rape","rare","revenge","rude","scrape","spiral","squeeze","strain","sunset","suspend","sympathy","thigh","throne","total","unseen","weapon","weary"];
var inputpp, cosmeticpp, repairedpp, formatpp;
var passphrase = [];
var passphraseprint = "";
var feedback = "";
inputpp = document.getElementById("inputphrase").value;
//Check for leading and trailing white spaces, as well as double spaces between words and punctuations.
cosmeticpp = cleanPassphrase(inputpp);
//Repair by replacing words not found in dictionary with closest match in dictionary (if no close match; "???")
repairedpp = repairPassphrase(cosmeticpp, words);
//Prepare HTML-encoded repaired passphrase for display
var cosmeticwords = cosmeticpp.split(' ');
var repairedwords = repairedpp.split(' ');
formatpp = '';
var valid = 0;
var repaired = 0;
var unrepaired = 0;
var surplus = 0;
for (i = 0; i < Math.max(repairedwords.length,12); i++) {
if (i > repairedwords.length-1) { unrepaired += 1; formatpp += '<i><b>???</b></i> '; }
else if (i > 11) { surplus += 1; formatpp += '<del>' + repairedwords[i] + '</del> '; }
else if (repairedwords[i] == '???') { unrepaired += 1; formatpp += '<i><b>???</b></i> '; }
else if (repairedwords[i] != cosmeticwords[i]) { repaired += 1; formatpp += '<i><b>' + repairedwords[i] + '</b></i> '; }
else { valid += 1; formatpp += repairedwords[i] + ' '; }
}
formatpp = formatpp.trim();
var output = '<p> </p>';//"<p> </p>Input<br /><pre><span style=\"background-color:#F0F0F5;\">" + inputpp + "</span></pre><br />";
if (repairedwords.length > 12) output += "IMPOSSIBLE TO REPAIR. You submitted more than 12 words.";
else if (repairedwords.length < 12) output += "IMPOSSIBLE TO REPAIR. You submitted less than 12 words.";
else if (valid == 12 && inputpp != cosmeticpp) output += "VALID PASSPHRASE SUBMITTED. We only made some cosmetic changes to ensure it can be pasted into all wallets.";
else if (valid == 12) output += "VALID PASSPHRASE SUBMITTED. No need to repair.";
else if (valid + repaired == 12) output += "REPAIRED SUCCESSFULLY. Note, the repaired passphrase is just one suggestion. There are other similar-looking passphrases too.";
else output += "UNABLE TO REPAIR PASSPHRASE.";
if (!(valid == 12 && inputpp == cosmeticpp)) output += "<br /><span style=\"background-color:#F0F0F5;\">" + formatpp + "</span><br />";
document.getElementById("demo").innerHTML = output;
/*
if (inputwords.length >= 14) {
feedback +="ERROR: Submitted passphrase contains " + inputwords.length + " words. Cannot repair.<br />";
} else {
//Get Levenstein distance for each input word to closest dictionary word.
//This is an integer; 0 if word in dictionary (what we want), 1 if very close (e.g. short instead of shirt), and higher if less similar
//E.g. "like" is in dictionary. Therefore input "like" gets score 0. "luke" gets 1 because 1 transformation needed.
// "likes" is also 1 because only "s" is removed and "lik" is 1.
// However, "l" is 2 "li" is 1 because they are more similar to another dictionary word, "lip".
var levDis = [];
var closest = [];
for (i = 0; i < inputwords.length; i++) {
levDis[i] = levDist(inputwords[i],words[0]);
closest[i] = 0;
for (j = 1; j < words.length; j++) {
var levDisTemp = levDist(inputwords[i],words[j]);
if (levDisTemp < levDis[i]) {
levDis[i] = levDisTemp;
closest[i] = j;
}
}
}
//Check if all words are valid
var invalid = 0;
for (i = 0; i < inputwords.length; i++) {
if (levDis[i] != 0) { invalid += 1; }
}
//If not 12 words, give a warning
if (inputwords.length != 12) {
feedback += "WARNING: Submitted passphrase contains " + inputwords.length + " words. A valid passphrase must contain exactly 12 words.<br />";
}
//If all words are valid
if (invalid == 0) {
//If 12 valid words, but suggest recovery tool
if (inputwords.length == 12) {
feedback +="SUCCESS: The passphrase you entered is valid.<br />NOTE: If you have logged in but cannot see your funds, you may accidentially have mistaken one word for a similar one. If you know one corresponding Bitcoin address. you will be able to recover the passphrase with the Recovery Tool.<br />";
} else if (inputwords.length == 11) { //If 11 valid words, suggest recovery tool
feedback +="SUGGESTION: The passphrase is missing the 12th word. If you know one corresponding Bitcoin address. you will be able to recover the passphrase with the Recovery Tool.<br />";
} else if (inputwords.length == 13) { //If 13 valid words, suggest recovery tool
feedback +="SUGGESTION: The passphrase contains one word too many. If you know one corresponding Bitcoin address. you will be able to recover the passphrase with the Recovery Tool.<br />";
} else {
feedback +="ERROR: Submitted passphrase contains " + inputwords.length + " words. A valid passphrase must contain exactly 12 words.<br />";
}
} else { //Not all words are correct
//If not 12 words and some word(s) not correct
if (inputwords.length != 12) {
feedback +="ERROR: Submitted passphrase contains " + inputwords.length + " words and not all words are from the passphrase dictionary either.<br />";
} else { //Try to repair
var suggestpp = [];
var formatSuggestpp = '';
var canRepair = true;
for (i = 0; i < 12; i++) {
if (levDis[i] == 0) { suggestpp[i] = words[closest[i]]; formatSuggestpp += words[closest[i]] + ' ' ; }
else if (levDis[i] <= 2 && inputwords[i].length >= 5 && words[closest[i]].lenght >= 5) { suggestpp[i] = words[closest[i]]; formatSuggestpp += "<i>" + words[closest[i]] + "</i> " ; }
else if (levDis[i] <= 1) { suggestpp[i] = words[closest[i]]; formatSuggestpp += "<i>" + words[closest[i]] + "</i> " ; }
else { suggestpp[i] = '???'; formatSuggestpp += "<i>???</i> "; canRepair = false; }
}
formatSuggestpp = formatSuggestpp.trim();
if (canRepair) {
feedback +="REPAIRED: The submitted passphrased was not spelled correctly, but was successfully repaired: " + formatSuggestpp + "<br />";
} else {
feedback +="ERROR: The submitted passphrased was not spelled correctly, and we were not able to successfully repair it: " + formatSuggestpp + "<br />";
}
}
}
}
/*
passphraseprint = passphraseprint.trim();
xrender = x.replace(/&/g,'&');
xrender = xrender.replace(/</g,'<');
document.getElementById("demo").innerHTML = "<p> </p><pre>Input <span style=\"background-color:#F0F0F5;\">" + xrender + "</span> generates passphrase:</pre><h2>" + passphraseprint + "</h2><p>Keep these 12 words secret! If someone gets your passphrase, they gain access to your funds!</p>";
*/
//document.getElementById("demo").innerHTML = feedback;
/*
var inputppRender = inputpp.replace(/&/g,'&');
inputppRender = inputppRender.replace(/</g,'<');
var output = "<p> </p>Input <span style=\"background-color:#F0F0F5;\">" + inputppRender + "</span><br />";
if (cosmeticpp != inputpp) output += "Minor cosmetic repairs were made: <span style=\"background-color:#F0F0F5;\">" + cosmeticpp + "</span><br />";
if (invalid == 0 && inputwords.length == 12) output += "Success! This is a valid passphrase.";
else if (inputwords.length != 12) output += "Your input does not contain 12 words. Therefore it is NOT a valid passphrase.";
else if (canRepair) output += "Your passphrase is not valid, but we've repaired it for you: <span style=\"background-color:#F0F0F5;\">" + formatSuggestpp + "</span><br />";
else if (!canRepair) output += "Your passphrase is not valid, and we were not able to fully restore it: <span style=\"background-color:#F0F0F5;\">" + formatSuggestpp + "</span><br />";
document.getElementById("demo").innerHTML = output; */
}
function cleanPassphrase(inputpp) {
//Check for leading and trailing white spaces, as well as double spaces between words and punctuations.
//Don't assume the passphrase is invalid (a good wallet should "forgive" such mistakes) but give a warning.
var cosmeticpp = inputpp.toLowerCase();
cosmeticpp = cosmeticpp.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g, '');
cosmeticpp = cosmeticpp.replace(/\s\s+/g, ' ');
cosmeticpp = cosmeticpp.trim();
return cosmeticpp;
}
function repairPassphrase(inputpp, dictionary) {
//Get Levenstein distance for each input word to closest dictionary word.
//This is an integer; 0 if word in dictionary (what we want), 1 if very close (e.g. short instead of shirt), and higher if less similar
var inputwords = inputpp.split(' ');
var levDis = [];
var closest = [];
for (i = 0; i < inputwords.length; i++) {
levDis[i] = levDist(inputwords[i],dictionary[0]);
//Special case. Prioritize if all chars of shortest string is in longest. Useful when more than one best fit.
if ((levDis[i] == 1 || levDis[i] == 2) && dictionary[0].length != inputwords[i].length) {
if (allSameChars(dictionary[0], inputwords[i])) levDis[i] -= 0.5;
}
closest[i] = 0;
for (j = 1; j < dictionary.length; j++) {
var levDisTemp = levDist(inputwords[i],dictionary[j]);
//Special case. Prioritize one where all chars of shortest string is in longest
if ((levDisTemp == 1 || (levDis[i] >= 2 && levDisTemp == 2)) && dictionary[j].length != inputwords[i].length) {
if (allSameChars(dictionary[j], inputwords[i])) levDisTemp -= 0.5;
}
if (levDisTemp < levDis[i]) {
levDis[i] = levDisTemp;
closest[i] = j;
}
}
}
//Repair by replacing words not found in dictionary with closest match in dictionary (if no close match; "???")
var repairedpp = '';
for (i = 0; i < inputwords.length; i++) {
if (levDis[i] <= 1 || (levDis[i] <= 2 && inputwords[i].length >= 5 && dictionary[closest[i]].lenght >= 5)) {
repairedpp += dictionary[closest[i]] + ' ';
} else {
repairedpp += '??? ';
}
}
repairedpp = repairedpp.trim();
return repairedpp;
}
//http://www.merriampark.com/ld.htm, http://www.mgilleland.com/ld/ldjavascript.htm, Damerau–Levenshtein distance (Wikipedia)
var levDist = function(s, t) {
var d = []; //2d matrix
// Step 1
var n = s.length;
var m = t.length;
if (n == 0) return m;
if (m == 0) return n;
//Create an array of arrays in javascript (a descending loop is quicker)
for (var i = n; i >= 0; i--) d[i] = [];
// Step 2
for (var i = n; i >= 0; i--) d[i][0] = i;
for (var j = m; j >= 0; j--) d[0][j] = j;
// Step 3
for (var i = 1; i <= n; i++) {
var s_i = s.charAt(i - 1);
// Step 4
for (var j = 1; j <= m; j++) {
//Check the jagged ld total so far
if (i == j && d[i][j] > 4) return n;
var t_j = t.charAt(j - 1);
var cost = (s_i == t_j) ? 0 : 1; // Step 5
//Calculate the minimum
var mi = d[i - 1][j] + 1;
var b = d[i][j - 1] + 1;
var c = d[i - 1][j - 1] + cost;
if (b < mi) mi = b;
if (c < mi) mi = c;
d[i][j] = mi; // Step 6
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
}
//Check if all same characters. True if longest string only contains characters from shortest
function allSameChars(word1, word2) {
var shortest = ''; var longest = '';
if (word1.length > word2.length) { shortest = word2; longest = word1; }
else { shortest = word1; longest = word2; }
var shortestChars = shortest.split('');
for (k = 0; k < shortestChars.length; k++) {
if (longest.indexOf(shortestChars[k]) == -1) return false;
}
return true;
}
</script>
<style>
#page-wrap {
width: 700px;
margin: 0 auto;
}
table, th, td {
border: 0px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
#footer {
font-size: 12px;
}
</style>
</head>
<body style="font-family:courier; padding:30px">
<div id="page-wrap">
<h1>Repair a Passphrase</h1>
<p>Insert a broken 12-word passphrase.</p>
<input id="inputphrase" type="text" style="width: 500px"> <button type="button" onclick="myFunction()">Repair Passphrase</button>
<p id="demo"></p>
<div style="margin-top: 50px; margin-bottom: 50px;" id="instructions">
<h3>FAQ</h3>
<dl>
<dt>What is a broken passphrase?</dt>
<dd>A Counterwallet passphrase exists of 12 random words from a 1626 word dictionary. Any combiantion of these words is valid. If the passphrase contains a word <i>not</i> included in the dictionary, e.g. due to a typo, the passphrase is invalid or broken.</dd>
<dt>How is the passphrase repaired?</dt>
<dd>An invalid word is compared to all words in the 1626 word dictionary. The invalid word is replaced by its closest match. A slight modification of the Damerau-Levenshtein algorithm is used for this search.</dd>
<dt>Can every passphrase be repaired?</dt>
<dd>No, if there are no close matches, question marks are returned. Sometimes there may even be two close matches, and then the repaired passphrase may be different from the original one. E.g. you write "sing" instead of "song". The algorithm returns "swing".</dd>
<dt>What are the use cases?</dt>
<dd><ul><li>If you cannot login to Counterwallet, you may have written down a word wrongly (it's another real word, but one that's not included in the dictionary). This script will help you find the typo.</li><li>Wallet software can include this algorithm. Users will be able to log in despite mionor typos.</li></ul></dd>
</dl>
</div>
<div style="margin-top: 50px; margin-bottom: 0px;" id="footer">
No warranty.<br />
Developed by JP Janssen. View on <a href="https://github.com/jpja">GitHub</a>. Skype: jp.janssen. <a href="https://twitter.com/jp_janssen">Twitter</a>. <a href="https://counterpartytalk.org/users/jpja/activity">CounterpartyTalk</a>.<br />
The project utilizes code from jQuery, <a href="https://github.com/bitpay/bitcore">Bitcore</a>, <a href="http://github.com/ggozad/mnemonic.js">Mnemonic.js</a>, and numerous Bitcoin and crypto libraries.
</div>
</div>
</body>
</html>