HD钱包其实就是管理一堆的Seed以及密钥。记住32byte的私钥是个反人性的事。所以,就有了助记词(Mnemonics)。本文讨论由助记词(Mnemonics)生成种子, and vice versa.
首先,借用Mastering Bitcoin书里的几张图,说明一下HD钱包
下面是变换框图
图片借用到此为止,下面是捋代码
如何生成初始的熵(entropy)
func NewEntropy(bitSize int) ([]byte, error) {
err := validateEntropyBitSize(bitSize)
if err != nil {
return nil, err
}
entropy := make([]byte, bitSize/8)
_, err = rand.Read(entropy)
return entropy, err
}
validateEntropyBitsize : bitSize只能是128,256,512。一定是8的倍数
如何生成checksum
func addChecksum(data []byte) []byte {
// Get first byte of sha256
hasher := sha256.New()
hasher.Write(data)
hash := hasher.Sum(nil)
firstChecksumByte := hash[0]
// len() is in bytes so we divide by 4
checksumBitLength := uint(len(data) / 4)
// For each bit of check sum we want we shift the data one the left
// and then set the (new) right most bit equal to checksum bit at that index
// staring from the left
dataBigInt := new(big.Int).SetBytes(data)
for i := uint(0); i < checksumBitLength; i++ {
// Bitshift 1 left
dataBigInt.Mul(dataBigInt, bigTwo)
// Set rightmost bit if leftmost checksum bit is set
if uint8(firstChecksumByte&(1<<(7-i))) > 0 {
dataBigInt.Or(dataBigInt, bigOne)
}
}
return dataBigInt.Bytes()
}
剩下把bits分成12个segment,然后查字典,就不用说了吧
在此处验证