mirror of
https://github.com/status-im/bip39.git
synced 2025-01-24 03:19:02 +00:00
add mnemonic validate method
This commit is contained in:
parent
895341924a
commit
e625e4defc
32
index.js
32
index.js
@ -37,6 +37,38 @@ BIP39.prototype.generateMnemonic = function(strength){
|
|||||||
return this.entropyToMnemonic(entropy)
|
return this.entropyToMnemonic(entropy)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BIP39.prototype.validate = function(mnemonic){
|
||||||
|
mnemonic = mnemonic.split(' ')
|
||||||
|
|
||||||
|
if(mnemonic.length % 3 !== 0) return false
|
||||||
|
|
||||||
|
var wordlist = this.wordlist
|
||||||
|
var belongToList = mnemonic.reduce(function(memo, m){
|
||||||
|
return memo && (wordlist.indexOf(m) > -1)
|
||||||
|
}, true)
|
||||||
|
|
||||||
|
if(!belongToList) return false
|
||||||
|
|
||||||
|
var bits = mnemonic.map(function(m){
|
||||||
|
var id = wordlist.indexOf(m)
|
||||||
|
return lpad(id.toString(2), '0', 11)
|
||||||
|
}).join('')
|
||||||
|
|
||||||
|
var length = bits.length
|
||||||
|
var dividerIndex = Math.floor(length / 33) * 32
|
||||||
|
var checksum = bits.substring(dividerIndex)
|
||||||
|
|
||||||
|
var data = bits.substring(0, dividerIndex)
|
||||||
|
var bytes = data.match(/(.{1,8})/g).map(function(bin){
|
||||||
|
return parseInt(bin, 2)
|
||||||
|
})
|
||||||
|
var hash = Crypto.SHA256(bytesToWordArray(bytes))
|
||||||
|
var checksumBits = bytesToBinary(wordsToBytes(hash.words))
|
||||||
|
var checksum2 = checksumBits.substr(0, length - dividerIndex)
|
||||||
|
|
||||||
|
return checksum === checksum2
|
||||||
|
}
|
||||||
|
|
||||||
function salt(password) {
|
function salt(password) {
|
||||||
return encode_utf8('mnemonic' + (password || ''))
|
return encode_utf8('mnemonic' + (password || ''))
|
||||||
}
|
}
|
||||||
|
@ -26,3 +26,24 @@ describe('entropyToMnemonic', function(){
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('validate', function(){
|
||||||
|
vectors.forEach(function(v, i){
|
||||||
|
it('passes check ' + i, function(){
|
||||||
|
assert(bip39.validate(v[1]))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fails for mnemonics of wrong length', function(){
|
||||||
|
assert(!bip39.validate('sleep kitten'))
|
||||||
|
assert(!bip39.validate('sleep kitten sleep kitten sleep kitten'))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fails for mnemonics that contains words not from the word list', function(){
|
||||||
|
assert(!bip39.validate("turtle front uncle idea crush write shrug there lottery flower risky shell"))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('fails for mnemonics of invalid checksum', function(){
|
||||||
|
assert(!bip39.validate('sleep kitten sleep kitten sleep kitten sleep kitten sleep kitten sleep kitten'))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
Loading…
x
Reference in New Issue
Block a user