Github地址:https://github.com/Bytom/bytom9 g$ z8 M F3 l5 ]- ?# K5 W' K" J
Gitee地址:https://gitee.com/BytomBlockchain/bytom
背景知识
Bytom 使用的 密钥类型为基于 ed25519 的 chainkd.XPub
预备
代码修改5 e# t! s# P1 E6 U; _7 B
首先适当修改代码,添加一些打印输出,使得我们更好的进行验证。 如果只是想看 xpub ,而不关心 xprv(对于验证导入导出助记词功能来说已经够了)的话可以跳过这一步,不必修改源码 。
在 bytom/blockchain/pseudohsm/pseudohsm.go 中的
func (h *HSM) createKeyFromMnemonic(alias string, auth string, mnemonic string) (*XPub, error)
添加输出打印 root XPub 对应的 私钥 和 公钥
func (h *HSM) createKeyFromMnemonic(alias string, auth string, mnemonic string) (*XPub, error) {) ?+ O7 p) r8 U% i+ a
// Generate a Bip32 HD wallet for the mnemonic and a user supplied password
seed := mnem.NewSeed(mnemonic, "")+ O+ t) ~+ z* ~4 @9 g5 T
xprv, xpub, err := chainkd.NewXKeys(bytes.NewBuffer(seed))/ E6 h, Q3 p5 [/ ]/ C1 h* Z8 Z
if err != nil {
return nil, err
}
& ^) [& j# b- y; c, Z l7 U6 L) Q( {
fmt.Println(hex.EncodeToString(xprv[:])) // Add info printing5 X- G4 \* n. P& a e
fmt.Println(hex.EncodeToString(xpub[:])) // Add info printing/ M& S3 g. k( i4 D! C
id := uuid.NewRandom()
key := &XKey{, w( r: A# n5 ^
ID: id,
KeyType: "bytom_kd",+ ~3 P3 t% G9 R
XPub: xpub,; {# u$ k1 G! e5 B6 Q
XPrv: xprv,
Alias: alias,
}! E3 V8 |3 `" t! K
file := h.keyStore.JoinPath(keyFileName(key.ID.String()))
if err := h.keyStore.StoreKey(file, key, auth); err != nil {0 H8 X4 Q* E1 d9 z2 a5 x
return nil, errors.Wrap(err, "storing keys")
}
return &XPub{XPub: xpub, Alias: alias, File: file}, nil
} K9 v( c3 [: }# }& E
工具准备
因为 bytomd 目前 dashboard 钱包图形界面还没有助记词相关功能,我们需要准备工具使用 POST 请求来使用。比如 curl 或者 postman 。' G1 s) c# S$ D0 \
获取密钥对应助记词) q1 j2 f! D' C# A/ r8 Y" y* u0 i. ]
dashboard 目前还没有 从 密钥导出助记词的功能,现有只是在创建密钥时有助记词相应输出信息。可以修改源码在查看密钥时 打印对应助记词。
因为只是测试,这里为了方便,直接查看在创建密钥时返回的助记词。
对 bytomd 发起 post 请求 /create-key
{7 T+ l% P1 A+ o& r3 p# {
"alias": "create_key_test",
"password": "createkeytest", r: x, v/ L) V+ q" R+ M
"language": "en"! O) a; {, z6 T3 z0 s$ H# t
}
可以看到 响应中 显示了 xpub 和 助记词
由于修改了源码,添加了打印信息,bytomd 命令行也打印出了相印的 xprv 和 xpub9 e: ~7 H& ^# \1 C/ N4 l
步骤6 ]! T" H" c/ W- y' U
如何通过导入助记词恢复密钥呢?$ K* l( k9 y0 }- H: e3 ^
假设目前 已经有一个 xprv9 w+ K6 q% M4 L
50db5bfe21b08462972eadbce08ec92d078a45fa7a280d175a823f9e457faf447d1f501b69f895b830138fabc6f91e2b3b3c8df26642a34be4af27886b9134dc+ W Z8 t9 a4 X3 J
对应的 助记词为# d0 P- b" M9 I- p% v& \2 {: W- O
pudding
room
business) R# T- `" ~) W
river
pattern
box# m( j: c9 G1 D
snap
merit
unfold' k+ O9 j R+ k3 W `
speak) V( d1 U+ _- _ c
hat
task5 C: D' m! N$ d R7 Y
发起 post 请求 /create-key
{
"alias": "nnemonic_test"," @4 z" a$ f& m2 X- f
"password": "nnemonicnnemonic",- M8 F4 ~' v- L) v- e
"nnemonic": "pudding room business river pattern box snap merit unfold speak hat task",: Z/ `# C3 J, D8 p
"language": "en"
}- D/ g# a, j# T
返回相应:
+ m3 t* k1 Y# s( ~" \
bytomd 输出
可以看到,恢复出来的 xprv 和 我们本来的 xprv 一致,验证成功。- F- s/ J M$ Q) j9 B1 y2 ^
dashaboard 中也能见到我们恢复的 密钥。