keystore.go 16 KB

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