1、导入
<script>
const bip39 = require('bip39')
const mnemonic = bip39.generateMnemonic()
</script>>
2、底层
// bip39/src/index.js
function generateMnemonic(strength, rng, wordlist) {
// 空参时长度默认为128,rng为randomBytes方法,wordlist为默认值
strength = strength || 128;
if (strength % 32 !== 0)
throw new TypeError(INVALID_ENTROPY);
rng = rng || randomBytes;// randomBytes(size)在第size大于0小于MAX_BYTES时,返回一个以随机数填充,长为size的Buffer
// 通过 rng = randomBytes,rng(strength / 8)获得了一个长为16,以随机数填充的Buffer,entropyToMnemonic基于该Buffer生成助记词
return entropyToMnemonic(rng(strength / 8), wordlist);
}
exports.generateMnemonic = generateMnemonic;
function randomBytes (size, cb) {
// phantomjs needs to throw
if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
var bytes = Buffer.allocUnsafe(size)
if (size > 0) { // getRandomValues fails on IE if size == 0
if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
// can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
for (var generated = 0; generated < size; generated += MAX_BYTES) {
// buffer.slice automatically checks if the end is past the end of
// the buffer so we don't have to here
crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
}
} else {
crypto.getRandomValues(bytes)
}
}
if (typeof cb === 'function') {
return process.nextTick(function () {
cb(null, bytes)
})
}
return bytes
}
function entropyToMnemonic(entropy, wordlist) {
// entropy:长度为16的Buffer
// wordlist:没有实参传入
if (!Buffer.isBuffer(entropy))
entropy = Buffer.from(entropy, 'hex');
wordlist = wordlist || DEFAULT_WORDLIST;
if (!wordlist) {
throw new Error(WORDLIST_REQUIRED);
}
// 128 <= ENT <= 256
if (entropy.length < 16)
throw new TypeError(INVALID_ENTROPY);
if (entropy.length > 32)
throw new TypeError(INVALID_ENTROPY);
if (entropy.length % 4 !== 0)
throw new TypeError(INVALID_ENTROPY);
// bytesToBinary:将entropy中每个元素转为2进制表示,如果长度小于8则高位补0
// entropyBits:长度为16 * 8的0/1序列
const entropyBits = bytesToBinary([...entropy]);
// checksumBits:二进制0/1序列,4位
const checksumBits = deriveChecksumBits(entropy);
const bits = entropyBits + checksumBits;
// 将128 + 4 = 132位0/1序列分割为长度等于11度子序列
const chunks = bits.match(/(.{1,11})/g);
// 将长度为11的子序列映射为Byte,并在wordlist map中获取对应的value
const words = chunks.map(binary => {
const index = binaryToByte(binary);
return wordlist[index];
});
return wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093' // Japanese wordlist
? words.join('\u3000')
: words.join(' ');
}
exports.entropyToMnemonic = entropyToMnemonic;
const createHash = require("create-hash");
function deriveChecksumBits(entropyBuffer) {
// entropyBuffer:长为16的Buffer
const ENT = entropyBuffer.length * 8;// 128
const CS = ENT / 32;// 4
// 对于entropyBuffer使用sha256加密并返回密文
const hash = createHash('sha256')
.update(entropyBuffer)
.digest();
// 返回hash转为二进制之后的前4位作为校验位
return bytesToBinary([...hash]).slice(0, CS);
}
3、总结
如1中调用 bip39.generateMnemonic() 时