1 // Package pseudohsm provides a pseudo HSM for development environments.
13 "github.com/pborman/uuid"
15 "github.com/bytom/bytom/crypto/ed25519/chainkd"
16 "github.com/bytom/bytom/errors"
17 mnem "github.com/bytom/bytom/wallet/mnemonic"
20 // pre-define errors for supporting bytom errorFormatter
22 ErrDuplicateKeyAlias = errors.New("duplicate key alias")
23 ErrXPubFormat = errors.New("xpub format error")
24 ErrLoadKey = errors.New("key not found or wrong password ")
25 ErrDecrypt = errors.New("could not decrypt key with given passphrase")
26 ErrMnemonicLength = errors.New("mnemonic length error")
29 // EntropyLength random entropy length to generate mnemonics.
30 const EntropyLength = 128
32 // HSM type for storing pubkey and privatekey
39 // XPub type for pubkey for anyone can see
41 Alias string `json:"alias"`
42 XPub chainkd.XPub `json:"xpub"`
43 File string `json:"file"`
46 // New method for HSM struct
47 func New(keypath string) (*HSM, error) {
48 keydir, _ := filepath.Abs(keypath)
50 keyStore: &keyStorePassphrase{keydir, LightScryptN, LightScryptP},
51 cache: newKeyCache(keydir),
55 // XCreate produces a new random xprv and stores it in the db.
56 func (h *HSM) XCreate(alias string, auth string, language string) (*XPub, *string, error) {
58 defer h.cacheMu.Unlock()
60 normalizedAlias := strings.ToLower(strings.TrimSpace(alias))
61 if ok := h.cache.hasAlias(normalizedAlias); ok {
62 return nil, nil, ErrDuplicateKeyAlias
65 xpub, mnemonic, err := h.createChainKDKey(normalizedAlias, auth, language)
70 return xpub, mnemonic, err
73 // ImportKeyFromMnemonic produces a xprv from mnemonic and stores it in the db.
74 func (h *HSM) ImportKeyFromMnemonic(alias string, auth string, mnemonic string, language string) (*XPub, error) {
76 defer h.cacheMu.Unlock()
78 // checksum length = entropy length /32
79 // mnemonic length = (entropy length + checksum length)/11
80 if len(strings.Fields(mnemonic)) != (EntropyLength+EntropyLength/32)/11 {
81 return nil, ErrMnemonicLength
84 normalizedAlias := strings.ToLower(strings.TrimSpace(alias))
85 if ok := h.cache.hasAlias(normalizedAlias); ok {
86 return nil, ErrDuplicateKeyAlias
89 // Pre validate that the mnemonic is well formed and only contains words that
90 // are present in the word list
91 if !mnem.IsMnemonicValid(mnemonic, language) {
92 return nil, mnem.ErrInvalidMnemonic
95 xpub, err := h.createKeyFromMnemonic(alias, auth, mnemonic)
104 func (h *HSM) createKeyFromMnemonic(alias string, auth string, mnemonic string) (*XPub, error) {
105 // Generate a Bip32 HD wallet for the mnemonic and a user supplied password
106 seed := mnem.NewSeed(mnemonic, "")
107 xprv, xpub, err := chainkd.NewXKeys(bytes.NewBuffer(seed))
111 id := uuid.NewRandom()
119 file := h.keyStore.JoinPath(keyFileName(key.ID.String()))
120 if err := h.keyStore.StoreKey(file, key, auth); err != nil {
121 return nil, errors.Wrap(err, "storing keys")
123 return &XPub{XPub: xpub, Alias: alias, File: file}, nil
126 func (h *HSM) createChainKDKey(alias string, auth string, language string) (*XPub, *string, error) {
127 // Generate a mnemonic for memorization or user-friendly seeds
128 entropy, err := mnem.NewEntropy(EntropyLength)
132 mnemonic, err := mnem.NewMnemonic(entropy, language)
136 xpub, err := h.createKeyFromMnemonic(alias, auth, mnemonic)
140 return xpub, &mnemonic, nil
143 // UpdateKeyAlias update key alias
144 func (h *HSM) UpdateKeyAlias(xpub chainkd.XPub, newAlias string) error {
146 defer h.cacheMu.Unlock()
148 h.cache.maybeReload()
150 xpb, err := h.cache.find(XPub{XPub: xpub})
156 keyjson, err := ioutil.ReadFile(xpb.File)
161 encrptKeyJSON := new(encryptedKeyJSON)
162 if err := json.Unmarshal(keyjson, encrptKeyJSON); err != nil {
166 normalizedAlias := strings.ToLower(strings.TrimSpace(newAlias))
167 if ok := h.cache.hasAlias(normalizedAlias); ok {
168 return ErrDuplicateKeyAlias
171 encrptKeyJSON.Alias = normalizedAlias
172 keyJSON, err := json.Marshal(encrptKeyJSON)
177 if err := writeKeyFile(xpb.File, keyJSON); err != nil {
183 xpb.Alias = normalizedAlias
189 // ListKeys returns a list of all xpubs from the store
190 func (h *HSM) ListKeys() []XPub {
191 xpubs := h.cache.keys()
195 // XSign looks up the xprv given the xpub, optionally derives a new
196 // xprv with the given path (but does not store the new xprv), and
197 // signs the given msg.
198 func (h *HSM) XSign(xpub chainkd.XPub, path [][]byte, msg []byte, auth string) ([]byte, error) {
199 xprv, err := h.LoadChainKDKey(xpub, auth)
204 xprv = xprv.Derive(path)
206 return xprv.Sign(msg), nil
209 //LoadChainKDKey get xprv from xpub
210 func (h *HSM) LoadChainKDKey(xpub chainkd.XPub, auth string) (xprv chainkd.XPrv, err error) {
212 defer h.cacheMu.Unlock()
214 _, xkey, err := h.loadDecryptedKey(xpub, auth)
216 return xprv, ErrLoadKey
219 return xkey.XPrv, nil
222 // XDelete deletes the key matched by xpub if the passphrase is correct.
223 // If a contains no filename, the address must match a unique key.
224 func (h *HSM) XDelete(xpub chainkd.XPub, auth string) error {
225 // Decrypting the key isn't really necessary, but we do
226 // it anyway to check the password and zero out the key
227 // immediately afterwards.
229 xpb, xkey, err := h.loadDecryptedKey(xpub, auth)
238 // The order is crucial here. The key is dropped from the
239 // cache after the file is gone so that a reload happening in
240 // between won't insert it into the cache again.
241 err = os.Remove(xpb.File)
249 func (h *HSM) loadDecryptedKey(xpub chainkd.XPub, auth string) (XPub, *XKey, error) {
250 h.cache.maybeReload()
252 xpb, err := h.cache.find(XPub{XPub: xpub})
258 xkey, err := h.keyStore.GetKey(xpb.Alias, xpb.File, auth)
259 return xpb, xkey, err
262 // ResetPassword reset passphrase for an existing xpub
263 func (h *HSM) ResetPassword(xpub chainkd.XPub, oldAuth, newAuth string) error {
264 xpb, xkey, err := h.loadDecryptedKey(xpub, oldAuth)
268 return h.keyStore.StoreKey(xpb.File, xkey, newAuth)
271 // HasAlias check whether the key alias exists
272 func (h *HSM) HasAlias(alias string) bool {
273 return h.cache.hasAlias(alias)
276 // HasKey check whether the private key exists
277 func (h *HSM) HasKey(xprv chainkd.XPrv) bool {
278 return h.cache.hasKey(xprv.XPub())