keystore.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // Copyright 2017 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. "math/big"
  26. "os"
  27. "path/filepath"
  28. "reflect"
  29. "runtime"
  30. "sync"
  31. "time"
  32. "github.com/ethereum/go-ethereum/accounts"
  33. "github.com/ethereum/go-ethereum/common"
  34. "github.com/ethereum/go-ethereum/core/types"
  35. "github.com/ethereum/go-ethereum/crypto"
  36. "github.com/ethereum/go-ethereum/event"
  37. )
  38. var (
  39. ErrLocked = 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 password")
  42. // ErrAccountAlreadyExists is returned if an account attempted to import is
  43. // already present in the keystore.
  44. ErrAccountAlreadyExists = errors.New("account already exists")
  45. )
  46. // KeyStoreType is the reflect type of a keystore backend.
  47. var KeyStoreType = reflect.TypeOf(&KeyStore{})
  48. // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs.
  49. const KeyStoreScheme = "keystore"
  50. // Maximum time between wallet refreshes (if filesystem notifications don't work).
  51. const walletRefreshCycle = 3 * time.Second
  52. // KeyStore manages a key storage directory on disk.
  53. type KeyStore struct {
  54. storage keyStore // Storage backend, might be cleartext or encrypted
  55. cache *accountCache // In-memory account cache over the filesystem storage
  56. changes chan struct{} // Channel receiving change notifications from the cache
  57. unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys)
  58. wallets []accounts.Wallet // Wallet wrappers around the individual key files
  59. updateFeed event.Feed // Event feed to notify wallet additions/removals
  60. updateScope event.SubscriptionScope // Subscription scope tracking current live listeners
  61. updating bool // Whether the event notification loop is running
  62. mu sync.RWMutex
  63. importMu sync.Mutex // Import Mutex locks the import to prevent two insertions from racing
  64. }
  65. type unlocked struct {
  66. *Key
  67. abort chan struct{}
  68. }
  69. // NewKeyStore creates a keystore for the given directory.
  70. func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore {
  71. keydir, _ = filepath.Abs(keydir)
  72. ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP, false}}
  73. ks.init(keydir)
  74. return ks
  75. }
  76. // NewPlaintextKeyStore creates a keystore for the given directory.
  77. // Deprecated: Use NewKeyStore.
  78. func NewPlaintextKeyStore(keydir string) *KeyStore {
  79. keydir, _ = filepath.Abs(keydir)
  80. ks := &KeyStore{storage: &keyStorePlain{keydir}}
  81. ks.init(keydir)
  82. return ks
  83. }
  84. func (ks *KeyStore) init(keydir string) {
  85. // Lock the mutex since the account cache might call back with events
  86. ks.mu.Lock()
  87. defer ks.mu.Unlock()
  88. // Initialize the set of unlocked keys and the account cache
  89. ks.unlocked = make(map[common.Address]*unlocked)
  90. ks.cache, ks.changes = newAccountCache(keydir)
  91. // TODO: In order for this finalizer to work, there must be no references
  92. // to ks. addressCache doesn't keep a reference but unlocked keys do,
  93. // so the finalizer will not trigger until all timed unlocks have expired.
  94. runtime.SetFinalizer(ks, func(m *KeyStore) {
  95. m.cache.close()
  96. })
  97. // Create the initial list of wallets from the cache
  98. accs := ks.cache.accounts()
  99. ks.wallets = make([]accounts.Wallet, len(accs))
  100. for i := 0; i < len(accs); i++ {
  101. ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks}
  102. }
  103. }
  104. // Wallets implements accounts.Backend, returning all single-key wallets from the
  105. // keystore directory.
  106. func (ks *KeyStore) Wallets() []accounts.Wallet {
  107. // Make sure the list of wallets is in sync with the account cache
  108. ks.refreshWallets()
  109. ks.mu.RLock()
  110. defer ks.mu.RUnlock()
  111. cpy := make([]accounts.Wallet, len(ks.wallets))
  112. copy(cpy, ks.wallets)
  113. return cpy
  114. }
  115. // refreshWallets retrieves the current account list and based on that does any
  116. // necessary wallet refreshes.
  117. func (ks *KeyStore) refreshWallets() {
  118. // Retrieve the current list of accounts
  119. ks.mu.Lock()
  120. accs := ks.cache.accounts()
  121. // Transform the current list of wallets into the new one
  122. var (
  123. wallets = make([]accounts.Wallet, 0, len(accs))
  124. events []accounts.WalletEvent
  125. )
  126. for _, account := range accs {
  127. // Drop wallets while they were in front of the next account
  128. for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
  129. events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
  130. ks.wallets = ks.wallets[1:]
  131. }
  132. // If there are no more wallets or the account is before the next, wrap new wallet
  133. if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
  134. wallet := &keystoreWallet{account: account, keystore: ks}
  135. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  136. wallets = append(wallets, wallet)
  137. continue
  138. }
  139. // If the account is the same as the first wallet, keep it
  140. if ks.wallets[0].Accounts()[0] == account {
  141. wallets = append(wallets, ks.wallets[0])
  142. ks.wallets = ks.wallets[1:]
  143. continue
  144. }
  145. }
  146. // Drop any leftover wallets and set the new batch
  147. for _, wallet := range ks.wallets {
  148. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  149. }
  150. ks.wallets = wallets
  151. ks.mu.Unlock()
  152. // Fire all wallet events and return
  153. for _, event := range events {
  154. ks.updateFeed.Send(event)
  155. }
  156. }
  157. // Subscribe implements accounts.Backend, creating an async subscription to
  158. // receive notifications on the addition or removal of keystore wallets.
  159. func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  160. // We need the mutex to reliably start/stop the update loop
  161. ks.mu.Lock()
  162. defer ks.mu.Unlock()
  163. // Subscribe the caller and track the subscriber count
  164. sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
  165. // Subscribers require an active notification loop, start it
  166. if !ks.updating {
  167. ks.updating = true
  168. go ks.updater()
  169. }
  170. return sub
  171. }
  172. // updater is responsible for maintaining an up-to-date list of wallets stored in
  173. // the keystore, and for firing wallet addition/removal events. It listens for
  174. // account change events from the underlying account cache, and also periodically
  175. // forces a manual refresh (only triggers for systems where the filesystem notifier
  176. // is not running).
  177. func (ks *KeyStore) updater() {
  178. for {
  179. // Wait for an account update or a refresh timeout
  180. select {
  181. case <-ks.changes:
  182. case <-time.After(walletRefreshCycle):
  183. }
  184. // Run the wallet refresher
  185. ks.refreshWallets()
  186. // If all our subscribers left, stop the updater
  187. ks.mu.Lock()
  188. if ks.updateScope.Count() == 0 {
  189. ks.updating = false
  190. ks.mu.Unlock()
  191. return
  192. }
  193. ks.mu.Unlock()
  194. }
  195. }
  196. // HasAddress reports whether a key with the given address is present.
  197. func (ks *KeyStore) HasAddress(addr common.Address) bool {
  198. return ks.cache.hasAddress(addr)
  199. }
  200. // Accounts returns all key files present in the directory.
  201. func (ks *KeyStore) Accounts() []accounts.Account {
  202. return ks.cache.accounts()
  203. }
  204. // Delete deletes the key matched by account if the passphrase is correct.
  205. // If the account contains no filename, the address must match a unique key.
  206. func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
  207. // Decrypting the key isn't really necessary, but we do
  208. // it anyway to check the password and zero out the key
  209. // immediately afterwards.
  210. a, key, err := ks.getDecryptedKey(a, passphrase)
  211. if key != nil {
  212. zeroKey(key.PrivateKey)
  213. }
  214. if err != nil {
  215. return err
  216. }
  217. // The order is crucial here. The key is dropped from the
  218. // cache after the file is gone so that a reload happening in
  219. // between won't insert it into the cache again.
  220. err = os.Remove(a.URL.Path)
  221. if err == nil {
  222. ks.cache.delete(a)
  223. ks.refreshWallets()
  224. }
  225. return err
  226. }
  227. // SignHash calculates a ECDSA signature for the given hash. The produced
  228. // signature is in the [R || S || V] format where V is 0 or 1.
  229. func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
  230. // Look up the key to sign with and abort if it cannot be found
  231. ks.mu.RLock()
  232. defer ks.mu.RUnlock()
  233. unlockedKey, found := ks.unlocked[a.Address]
  234. if !found {
  235. return nil, ErrLocked
  236. }
  237. // Sign the hash using plain ECDSA operations
  238. return crypto.Sign(hash, unlockedKey.PrivateKey)
  239. }
  240. // SignTx signs the given transaction with the requested account.
  241. func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  242. // Look up the key to sign with and abort if it cannot be found
  243. ks.mu.RLock()
  244. defer ks.mu.RUnlock()
  245. unlockedKey, found := ks.unlocked[a.Address]
  246. if !found {
  247. return nil, ErrLocked
  248. }
  249. // Depending on the presence of the chain ID, sign with 2718 or homestead
  250. signer := types.LatestSignerForChainID(chainID)
  251. return types.SignTx(tx, signer, unlockedKey.PrivateKey)
  252. }
  253. // SignHashWithPassphrase signs hash if the private key matching the given address
  254. // can be decrypted with the given passphrase. The produced signature is in the
  255. // [R || S || V] format where V is 0 or 1.
  256. func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
  257. _, key, err := ks.getDecryptedKey(a, passphrase)
  258. if err != nil {
  259. return nil, err
  260. }
  261. defer zeroKey(key.PrivateKey)
  262. return crypto.Sign(hash, key.PrivateKey)
  263. }
  264. // SignTxWithPassphrase signs the transaction if the private key matching the
  265. // given address can be decrypted with the given passphrase.
  266. func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  267. _, key, err := ks.getDecryptedKey(a, passphrase)
  268. if err != nil {
  269. return nil, err
  270. }
  271. defer zeroKey(key.PrivateKey)
  272. // Depending on the presence of the chain ID, sign with or without replay protection.
  273. signer := types.LatestSignerForChainID(chainID)
  274. return types.SignTx(tx, signer, key.PrivateKey)
  275. }
  276. // Unlock unlocks the given account indefinitely.
  277. func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
  278. return ks.TimedUnlock(a, passphrase, 0)
  279. }
  280. // Lock removes the private key with the given address from memory.
  281. func (ks *KeyStore) Lock(addr common.Address) error {
  282. ks.mu.Lock()
  283. if unl, found := ks.unlocked[addr]; found {
  284. ks.mu.Unlock()
  285. ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
  286. } else {
  287. ks.mu.Unlock()
  288. }
  289. return nil
  290. }
  291. // TimedUnlock unlocks the given account with the passphrase. The account
  292. // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
  293. // until the program exits. The account must match a unique key file.
  294. //
  295. // If the account address is already unlocked for a duration, TimedUnlock extends or
  296. // shortens the active unlock timeout. If the address was previously unlocked
  297. // indefinitely the timeout is not altered.
  298. func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
  299. a, key, err := ks.getDecryptedKey(a, passphrase)
  300. if err != nil {
  301. return err
  302. }
  303. ks.mu.Lock()
  304. defer ks.mu.Unlock()
  305. u, found := ks.unlocked[a.Address]
  306. if found {
  307. if u.abort == nil {
  308. // The address was unlocked indefinitely, so unlocking
  309. // it with a timeout would be confusing.
  310. zeroKey(key.PrivateKey)
  311. return nil
  312. }
  313. // Terminate the expire goroutine and replace it below.
  314. close(u.abort)
  315. }
  316. if timeout > 0 {
  317. u = &unlocked{Key: key, abort: make(chan struct{})}
  318. go ks.expire(a.Address, u, timeout)
  319. } else {
  320. u = &unlocked{Key: key}
  321. }
  322. ks.unlocked[a.Address] = u
  323. return nil
  324. }
  325. // Find resolves the given account into a unique entry in the keystore.
  326. func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
  327. ks.cache.maybeReload()
  328. ks.cache.mu.Lock()
  329. a, err := ks.cache.find(a)
  330. ks.cache.mu.Unlock()
  331. return a, err
  332. }
  333. func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
  334. a, err := ks.Find(a)
  335. if err != nil {
  336. return a, nil, err
  337. }
  338. key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
  339. return a, key, err
  340. }
  341. func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
  342. t := time.NewTimer(timeout)
  343. defer t.Stop()
  344. select {
  345. case <-u.abort:
  346. // just quit
  347. case <-t.C:
  348. ks.mu.Lock()
  349. // only drop if it's still the same key instance that dropLater
  350. // was launched with. we can check that using pointer equality
  351. // because the map stores a new pointer every time the key is
  352. // unlocked.
  353. if ks.unlocked[addr] == u {
  354. zeroKey(u.PrivateKey)
  355. delete(ks.unlocked, addr)
  356. }
  357. ks.mu.Unlock()
  358. }
  359. }
  360. // NewAccount generates a new key and stores it into the key directory,
  361. // encrypting it with the passphrase.
  362. func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
  363. _, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
  364. if err != nil {
  365. return accounts.Account{}, err
  366. }
  367. // Add the account to the cache immediately rather
  368. // than waiting for file system notifications to pick it up.
  369. ks.cache.add(account)
  370. ks.refreshWallets()
  371. return account, nil
  372. }
  373. // Export exports as a JSON key, encrypted with newPassphrase.
  374. func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
  375. _, key, err := ks.getDecryptedKey(a, passphrase)
  376. if err != nil {
  377. return nil, err
  378. }
  379. var N, P int
  380. if store, ok := ks.storage.(*keyStorePassphrase); ok {
  381. N, P = store.scryptN, store.scryptP
  382. } else {
  383. N, P = StandardScryptN, StandardScryptP
  384. }
  385. return EncryptKey(key, newPassphrase, N, P)
  386. }
  387. // Import stores the given encrypted JSON key into the key directory.
  388. func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
  389. key, err := DecryptKey(keyJSON, passphrase)
  390. if key != nil && key.PrivateKey != nil {
  391. defer zeroKey(key.PrivateKey)
  392. }
  393. if err != nil {
  394. return accounts.Account{}, err
  395. }
  396. ks.importMu.Lock()
  397. defer ks.importMu.Unlock()
  398. if ks.cache.hasAddress(key.Address) {
  399. return accounts.Account{
  400. Address: key.Address,
  401. }, ErrAccountAlreadyExists
  402. }
  403. return ks.importKey(key, newPassphrase)
  404. }
  405. // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
  406. func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
  407. ks.importMu.Lock()
  408. defer ks.importMu.Unlock()
  409. key := newKeyFromECDSA(priv)
  410. if ks.cache.hasAddress(key.Address) {
  411. return accounts.Account{
  412. Address: key.Address,
  413. }, ErrAccountAlreadyExists
  414. }
  415. return ks.importKey(key, passphrase)
  416. }
  417. func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
  418. a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
  419. if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
  420. return accounts.Account{}, err
  421. }
  422. ks.cache.add(a)
  423. ks.refreshWallets()
  424. return a, nil
  425. }
  426. // Update changes the passphrase of an existing account.
  427. func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
  428. a, key, err := ks.getDecryptedKey(a, passphrase)
  429. if err != nil {
  430. return err
  431. }
  432. return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
  433. }
  434. // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
  435. // a key file in the key directory. The key file is encrypted with the same passphrase.
  436. func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
  437. a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
  438. if err != nil {
  439. return a, err
  440. }
  441. ks.cache.add(a)
  442. ks.refreshWallets()
  443. return a, nil
  444. }
  445. // zeroKey zeroes a private key in memory.
  446. func zeroKey(k *ecdsa.PrivateKey) {
  447. b := k.D.Bits()
  448. for i := range b {
  449. b[i] = 0
  450. }
  451. }