keystore.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package keystore implements encrypted storage of secp256k1 private keys.
  17. //
  18. // Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification.
  19. // See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information.
  20. package keystore
  21. import (
  22. "crypto/ecdsa"
  23. crand "crypto/rand"
  24. "errors"
  25. "fmt"
  26. "math/big"
  27. "os"
  28. "path/filepath"
  29. "reflect"
  30. "runtime"
  31. "sync"
  32. "time"
  33. "github.com/ethereum/go-ethereum/accounts"
  34. "github.com/ethereum/go-ethereum/common"
  35. "github.com/ethereum/go-ethereum/core/types"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. )
  38. var (
  39. ErrNeedPasswordOrUnlock = accounts.NewAuthNeededError("password or unlock")
  40. ErrNoMatch = errors.New("no key for given address or file")
  41. ErrDecrypt = errors.New("could not decrypt key with given passphrase")
  42. )
  43. // BackendType can be used to query the account manager for encrypted keystores.
  44. var BackendType = reflect.TypeOf(new(KeyStore))
  45. // KeyStore manages a key storage directory on disk.
  46. type KeyStore struct {
  47. cache *addressCache
  48. keyStore keyStore
  49. mu sync.RWMutex
  50. unlocked map[common.Address]*unlocked
  51. }
  52. type unlocked struct {
  53. *Key
  54. abort chan struct{}
  55. }
  56. // NewKeyStore creates a keystore for the given directory.
  57. func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore {
  58. keydir, _ = filepath.Abs(keydir)
  59. ks := &KeyStore{keyStore: &keyStorePassphrase{keydir, scryptN, scryptP}}
  60. ks.init(keydir)
  61. return ks
  62. }
  63. // NewPlaintextKeyStore creates a keystore for the given directory.
  64. // Deprecated: Use NewKeyStore.
  65. func NewPlaintextKeyStore(keydir string) *KeyStore {
  66. keydir, _ = filepath.Abs(keydir)
  67. ks := &KeyStore{keyStore: &keyStorePlain{keydir}}
  68. ks.init(keydir)
  69. return ks
  70. }
  71. func (ks *KeyStore) init(keydir string) {
  72. ks.unlocked = make(map[common.Address]*unlocked)
  73. ks.cache = newAddrCache(keydir)
  74. // TODO: In order for this finalizer to work, there must be no references
  75. // to ks. addressCache doesn't keep a reference but unlocked keys do,
  76. // so the finalizer will not trigger until all timed unlocks have expired.
  77. runtime.SetFinalizer(ks, func(m *KeyStore) {
  78. m.cache.close()
  79. })
  80. }
  81. // HasAddress reports whether a key with the given address is present.
  82. func (ks *KeyStore) HasAddress(addr common.Address) bool {
  83. return ks.cache.hasAddress(addr)
  84. }
  85. // Accounts returns all key files present in the directory.
  86. func (ks *KeyStore) Accounts() []accounts.Account {
  87. return ks.cache.accounts()
  88. }
  89. // Delete deletes the key matched by account if the passphrase is correct.
  90. // If the account contains no filename, the address must match a unique key.
  91. func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
  92. // Decrypting the key isn't really necessary, but we do
  93. // it anyway to check the password and zero out the key
  94. // immediately afterwards.
  95. a, key, err := ks.getDecryptedKey(a, passphrase)
  96. if key != nil {
  97. zeroKey(key.PrivateKey)
  98. }
  99. if err != nil {
  100. return err
  101. }
  102. // The order is crucial here. The key is dropped from the
  103. // cache after the file is gone so that a reload happening in
  104. // between won't insert it into the cache again.
  105. err = os.Remove(a.URL)
  106. if err == nil {
  107. ks.cache.delete(a)
  108. }
  109. return err
  110. }
  111. // SignHash calculates a ECDSA signature for the given hash. The produced
  112. // signature is in the [R || S || V] format where V is 0 or 1.
  113. func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
  114. // Look up the key to sign with and abort if it cannot be found
  115. ks.mu.RLock()
  116. defer ks.mu.RUnlock()
  117. unlockedKey, found := ks.unlocked[a.Address]
  118. if !found {
  119. return nil, ErrNeedPasswordOrUnlock
  120. }
  121. // Sign the hash using plain ECDSA operations
  122. return crypto.Sign(hash, unlockedKey.PrivateKey)
  123. }
  124. // SignTx signs the given transaction with the requested account.
  125. func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  126. // Look up the key to sign with and abort if it cannot be found
  127. ks.mu.RLock()
  128. defer ks.mu.RUnlock()
  129. unlockedKey, found := ks.unlocked[a.Address]
  130. if !found {
  131. return nil, ErrNeedPasswordOrUnlock
  132. }
  133. // Depending on the presence of the chain ID, sign with EIP155 or homestead
  134. if chainID != nil {
  135. return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
  136. }
  137. return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
  138. }
  139. // SignHashWithPassphrase signs hash if the private key matching the given address
  140. // can be decrypted with the given passphrase. The produced signature is in the
  141. // [R || S || V] format where V is 0 or 1.
  142. func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
  143. _, key, err := ks.getDecryptedKey(a, passphrase)
  144. if err != nil {
  145. return nil, err
  146. }
  147. defer zeroKey(key.PrivateKey)
  148. return crypto.Sign(hash, key.PrivateKey)
  149. }
  150. // SignTxWithPassphrase signs the transaction if the private key matching the
  151. // given address can be decrypted with the given passphrase.
  152. func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  153. _, key, err := ks.getDecryptedKey(a, passphrase)
  154. if err != nil {
  155. return nil, err
  156. }
  157. defer zeroKey(key.PrivateKey)
  158. // Depending on the presence of the chain ID, sign with EIP155 or homestead
  159. if chainID != nil {
  160. return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
  161. }
  162. return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
  163. }
  164. // Unlock unlocks the given account indefinitely.
  165. func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
  166. return ks.TimedUnlock(a, passphrase, 0)
  167. }
  168. // Lock removes the private key with the given address from memory.
  169. func (ks *KeyStore) Lock(addr common.Address) error {
  170. ks.mu.Lock()
  171. if unl, found := ks.unlocked[addr]; found {
  172. ks.mu.Unlock()
  173. ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
  174. } else {
  175. ks.mu.Unlock()
  176. }
  177. return nil
  178. }
  179. // TimedUnlock unlocks the given account with the passphrase. The account
  180. // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
  181. // until the program exits. The account must match a unique key file.
  182. //
  183. // If the account address is already unlocked for a duration, TimedUnlock extends or
  184. // shortens the active unlock timeout. If the address was previously unlocked
  185. // indefinitely the timeout is not altered.
  186. func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
  187. a, key, err := ks.getDecryptedKey(a, passphrase)
  188. if err != nil {
  189. return err
  190. }
  191. ks.mu.Lock()
  192. defer ks.mu.Unlock()
  193. u, found := ks.unlocked[a.Address]
  194. if found {
  195. if u.abort == nil {
  196. // The address was unlocked indefinitely, so unlocking
  197. // it with a timeout would be confusing.
  198. zeroKey(key.PrivateKey)
  199. return nil
  200. } else {
  201. // Terminate the expire goroutine and replace it below.
  202. close(u.abort)
  203. }
  204. }
  205. if timeout > 0 {
  206. u = &unlocked{Key: key, abort: make(chan struct{})}
  207. go ks.expire(a.Address, u, timeout)
  208. } else {
  209. u = &unlocked{Key: key}
  210. }
  211. ks.unlocked[a.Address] = u
  212. return nil
  213. }
  214. // Find resolves the given account into a unique entry in the keystore.
  215. func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
  216. ks.cache.maybeReload()
  217. ks.cache.mu.Lock()
  218. a, err := ks.cache.find(a)
  219. ks.cache.mu.Unlock()
  220. return a, err
  221. }
  222. func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
  223. a, err := ks.Find(a)
  224. if err != nil {
  225. return a, nil, err
  226. }
  227. key, err := ks.keyStore.GetKey(a.Address, a.URL, auth)
  228. return a, key, err
  229. }
  230. func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
  231. t := time.NewTimer(timeout)
  232. defer t.Stop()
  233. select {
  234. case <-u.abort:
  235. // just quit
  236. case <-t.C:
  237. ks.mu.Lock()
  238. // only drop if it's still the same key instance that dropLater
  239. // was launched with. we can check that using pointer equality
  240. // because the map stores a new pointer every time the key is
  241. // unlocked.
  242. if ks.unlocked[addr] == u {
  243. zeroKey(u.PrivateKey)
  244. delete(ks.unlocked, addr)
  245. }
  246. ks.mu.Unlock()
  247. }
  248. }
  249. // NewAccount generates a new key and stores it into the key directory,
  250. // encrypting it with the passphrase.
  251. func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
  252. _, account, err := storeNewKey(ks.keyStore, crand.Reader, passphrase)
  253. if err != nil {
  254. return accounts.Account{}, err
  255. }
  256. // Add the account to the cache immediately rather
  257. // than waiting for file system notifications to pick it up.
  258. ks.cache.add(account)
  259. return account, nil
  260. }
  261. // Export exports as a JSON key, encrypted with newPassphrase.
  262. func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
  263. _, key, err := ks.getDecryptedKey(a, passphrase)
  264. if err != nil {
  265. return nil, err
  266. }
  267. var N, P int
  268. if store, ok := ks.keyStore.(*keyStorePassphrase); ok {
  269. N, P = store.scryptN, store.scryptP
  270. } else {
  271. N, P = StandardScryptN, StandardScryptP
  272. }
  273. return EncryptKey(key, newPassphrase, N, P)
  274. }
  275. // Import stores the given encrypted JSON key into the key directory.
  276. func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
  277. key, err := DecryptKey(keyJSON, passphrase)
  278. if key != nil && key.PrivateKey != nil {
  279. defer zeroKey(key.PrivateKey)
  280. }
  281. if err != nil {
  282. return accounts.Account{}, err
  283. }
  284. return ks.importKey(key, newPassphrase)
  285. }
  286. // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
  287. func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
  288. key := newKeyFromECDSA(priv)
  289. if ks.cache.hasAddress(key.Address) {
  290. return accounts.Account{}, fmt.Errorf("account already exists")
  291. }
  292. return ks.importKey(key, passphrase)
  293. }
  294. func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
  295. a := accounts.Account{Address: key.Address, URL: ks.keyStore.JoinPath(keyFileName(key.Address))}
  296. if err := ks.keyStore.StoreKey(a.URL, key, passphrase); err != nil {
  297. return accounts.Account{}, err
  298. }
  299. ks.cache.add(a)
  300. return a, nil
  301. }
  302. // Update changes the passphrase of an existing account.
  303. func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
  304. a, key, err := ks.getDecryptedKey(a, passphrase)
  305. if err != nil {
  306. return err
  307. }
  308. return ks.keyStore.StoreKey(a.URL, key, newPassphrase)
  309. }
  310. // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
  311. // a key file in the key directory. The key file is encrypted with the same passphrase.
  312. func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
  313. a, _, err := importPreSaleKey(ks.keyStore, keyJSON, passphrase)
  314. if err != nil {
  315. return a, err
  316. }
  317. ks.cache.add(a)
  318. return a, nil
  319. }
  320. // zeroKey zeroes a private key in memory.
  321. func zeroKey(k *ecdsa.PrivateKey) {
  322. b := k.D.Bits()
  323. for i := range b {
  324. b[i] = 0
  325. }
  326. }