keystore.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 password")
  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. const 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, false}}
  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. var (
  120. wallets = make([]accounts.Wallet, 0, len(accs))
  121. events []accounts.WalletEvent
  122. )
  123. for _, account := range accs {
  124. // Drop wallets while they were in front of the next account
  125. for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 {
  126. events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped})
  127. ks.wallets = ks.wallets[1:]
  128. }
  129. // If there are no more wallets or the account is before the next, wrap new wallet
  130. if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 {
  131. wallet := &keystoreWallet{account: account, keystore: ks}
  132. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
  133. wallets = append(wallets, wallet)
  134. continue
  135. }
  136. // If the account is the same as the first wallet, keep it
  137. if ks.wallets[0].Accounts()[0] == account {
  138. wallets = append(wallets, ks.wallets[0])
  139. ks.wallets = ks.wallets[1:]
  140. continue
  141. }
  142. }
  143. // Drop any leftover wallets and set the new batch
  144. for _, wallet := range ks.wallets {
  145. events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
  146. }
  147. ks.wallets = wallets
  148. ks.mu.Unlock()
  149. // Fire all wallet events and return
  150. for _, event := range events {
  151. ks.updateFeed.Send(event)
  152. }
  153. }
  154. // Subscribe implements accounts.Backend, creating an async subscription to
  155. // receive notifications on the addition or removal of keystore wallets.
  156. func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription {
  157. // We need the mutex to reliably start/stop the update loop
  158. ks.mu.Lock()
  159. defer ks.mu.Unlock()
  160. // Subscribe the caller and track the subscriber count
  161. sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink))
  162. // Subscribers require an active notification loop, start it
  163. if !ks.updating {
  164. ks.updating = true
  165. go ks.updater()
  166. }
  167. return sub
  168. }
  169. // updater is responsible for maintaining an up-to-date list of wallets stored in
  170. // the keystore, and for firing wallet addition/removal events. It listens for
  171. // account change events from the underlying account cache, and also periodically
  172. // forces a manual refresh (only triggers for systems where the filesystem notifier
  173. // is not running).
  174. func (ks *KeyStore) updater() {
  175. for {
  176. // Wait for an account update or a refresh timeout
  177. select {
  178. case <-ks.changes:
  179. case <-time.After(walletRefreshCycle):
  180. }
  181. // Run the wallet refresher
  182. ks.refreshWallets()
  183. // If all our subscribers left, stop the updater
  184. ks.mu.Lock()
  185. if ks.updateScope.Count() == 0 {
  186. ks.updating = false
  187. ks.mu.Unlock()
  188. return
  189. }
  190. ks.mu.Unlock()
  191. }
  192. }
  193. // HasAddress reports whether a key with the given address is present.
  194. func (ks *KeyStore) HasAddress(addr common.Address) bool {
  195. return ks.cache.hasAddress(addr)
  196. }
  197. // Accounts returns all key files present in the directory.
  198. func (ks *KeyStore) Accounts() []accounts.Account {
  199. return ks.cache.accounts()
  200. }
  201. // Delete deletes the key matched by account if the passphrase is correct.
  202. // If the account contains no filename, the address must match a unique key.
  203. func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error {
  204. // Decrypting the key isn't really necessary, but we do
  205. // it anyway to check the password and zero out the key
  206. // immediately afterwards.
  207. a, key, err := ks.getDecryptedKey(a, passphrase)
  208. if key != nil {
  209. zeroKey(key.PrivateKey)
  210. }
  211. if err != nil {
  212. return err
  213. }
  214. // The order is crucial here. The key is dropped from the
  215. // cache after the file is gone so that a reload happening in
  216. // between won't insert it into the cache again.
  217. err = os.Remove(a.URL.Path)
  218. if err == nil {
  219. ks.cache.delete(a)
  220. ks.refreshWallets()
  221. }
  222. return err
  223. }
  224. // SignHash calculates a ECDSA signature for the given hash. The produced
  225. // signature is in the [R || S || V] format where V is 0 or 1.
  226. func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) {
  227. // Look up the key to sign with and abort if it cannot be found
  228. ks.mu.RLock()
  229. defer ks.mu.RUnlock()
  230. unlockedKey, found := ks.unlocked[a.Address]
  231. if !found {
  232. return nil, ErrLocked
  233. }
  234. // Sign the hash using plain ECDSA operations
  235. return crypto.Sign(hash, unlockedKey.PrivateKey)
  236. }
  237. // SignTx signs the given transaction with the requested account.
  238. func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  239. // Look up the key to sign with and abort if it cannot be found
  240. ks.mu.RLock()
  241. defer ks.mu.RUnlock()
  242. unlockedKey, found := ks.unlocked[a.Address]
  243. if !found {
  244. return nil, ErrLocked
  245. }
  246. // Depending on the presence of the chain ID, sign with EIP155 or homestead
  247. if chainID != nil {
  248. return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey)
  249. }
  250. return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey)
  251. }
  252. // SignHashWithPassphrase signs hash if the private key matching the given address
  253. // can be decrypted with the given passphrase. The produced signature is in the
  254. // [R || S || V] format where V is 0 or 1.
  255. func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) {
  256. _, key, err := ks.getDecryptedKey(a, passphrase)
  257. if err != nil {
  258. return nil, err
  259. }
  260. defer zeroKey(key.PrivateKey)
  261. return crypto.Sign(hash, key.PrivateKey)
  262. }
  263. // SignTxWithPassphrase signs the transaction if the private key matching the
  264. // given address can be decrypted with the given passphrase.
  265. func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
  266. _, key, err := ks.getDecryptedKey(a, passphrase)
  267. if err != nil {
  268. return nil, err
  269. }
  270. defer zeroKey(key.PrivateKey)
  271. // Depending on the presence of the chain ID, sign with EIP155 or homestead
  272. if chainID != nil {
  273. return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey)
  274. }
  275. return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey)
  276. }
  277. // Unlock unlocks the given account indefinitely.
  278. func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error {
  279. return ks.TimedUnlock(a, passphrase, 0)
  280. }
  281. // Lock removes the private key with the given address from memory.
  282. func (ks *KeyStore) Lock(addr common.Address) error {
  283. ks.mu.Lock()
  284. if unl, found := ks.unlocked[addr]; found {
  285. ks.mu.Unlock()
  286. ks.expire(addr, unl, time.Duration(0)*time.Nanosecond)
  287. } else {
  288. ks.mu.Unlock()
  289. }
  290. return nil
  291. }
  292. // TimedUnlock unlocks the given account with the passphrase. The account
  293. // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
  294. // until the program exits. The account must match a unique key file.
  295. //
  296. // If the account address is already unlocked for a duration, TimedUnlock extends or
  297. // shortens the active unlock timeout. If the address was previously unlocked
  298. // indefinitely the timeout is not altered.
  299. func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error {
  300. a, key, err := ks.getDecryptedKey(a, passphrase)
  301. if err != nil {
  302. return err
  303. }
  304. ks.mu.Lock()
  305. defer ks.mu.Unlock()
  306. u, found := ks.unlocked[a.Address]
  307. if found {
  308. if u.abort == nil {
  309. // The address was unlocked indefinitely, so unlocking
  310. // it with a timeout would be confusing.
  311. zeroKey(key.PrivateKey)
  312. return nil
  313. }
  314. // Terminate the expire goroutine and replace it below.
  315. close(u.abort)
  316. }
  317. if timeout > 0 {
  318. u = &unlocked{Key: key, abort: make(chan struct{})}
  319. go ks.expire(a.Address, u, timeout)
  320. } else {
  321. u = &unlocked{Key: key}
  322. }
  323. ks.unlocked[a.Address] = u
  324. return nil
  325. }
  326. // Find resolves the given account into a unique entry in the keystore.
  327. func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) {
  328. ks.cache.maybeReload()
  329. ks.cache.mu.Lock()
  330. a, err := ks.cache.find(a)
  331. ks.cache.mu.Unlock()
  332. return a, err
  333. }
  334. func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) {
  335. a, err := ks.Find(a)
  336. if err != nil {
  337. return a, nil, err
  338. }
  339. key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth)
  340. return a, key, err
  341. }
  342. func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) {
  343. t := time.NewTimer(timeout)
  344. defer t.Stop()
  345. select {
  346. case <-u.abort:
  347. // just quit
  348. case <-t.C:
  349. ks.mu.Lock()
  350. // only drop if it's still the same key instance that dropLater
  351. // was launched with. we can check that using pointer equality
  352. // because the map stores a new pointer every time the key is
  353. // unlocked.
  354. if ks.unlocked[addr] == u {
  355. zeroKey(u.PrivateKey)
  356. delete(ks.unlocked, addr)
  357. }
  358. ks.mu.Unlock()
  359. }
  360. }
  361. // NewAccount generates a new key and stores it into the key directory,
  362. // encrypting it with the passphrase.
  363. func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {
  364. _, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)
  365. if err != nil {
  366. return accounts.Account{}, err
  367. }
  368. // Add the account to the cache immediately rather
  369. // than waiting for file system notifications to pick it up.
  370. ks.cache.add(account)
  371. ks.refreshWallets()
  372. return account, nil
  373. }
  374. // Export exports as a JSON key, encrypted with newPassphrase.
  375. func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
  376. _, key, err := ks.getDecryptedKey(a, passphrase)
  377. if err != nil {
  378. return nil, err
  379. }
  380. var N, P int
  381. if store, ok := ks.storage.(*keyStorePassphrase); ok {
  382. N, P = store.scryptN, store.scryptP
  383. } else {
  384. N, P = StandardScryptN, StandardScryptP
  385. }
  386. return EncryptKey(key, newPassphrase, N, P)
  387. }
  388. // Import stores the given encrypted JSON key into the key directory.
  389. func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) {
  390. key, err := DecryptKey(keyJSON, passphrase)
  391. if key != nil && key.PrivateKey != nil {
  392. defer zeroKey(key.PrivateKey)
  393. }
  394. if err != nil {
  395. return accounts.Account{}, err
  396. }
  397. return ks.importKey(key, newPassphrase)
  398. }
  399. // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
  400. func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) {
  401. key := newKeyFromECDSA(priv)
  402. if ks.cache.hasAddress(key.Address) {
  403. return accounts.Account{}, fmt.Errorf("account already exists")
  404. }
  405. return ks.importKey(key, passphrase)
  406. }
  407. func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) {
  408. a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}}
  409. if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil {
  410. return accounts.Account{}, err
  411. }
  412. ks.cache.add(a)
  413. ks.refreshWallets()
  414. return a, nil
  415. }
  416. // Update changes the passphrase of an existing account.
  417. func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error {
  418. a, key, err := ks.getDecryptedKey(a, passphrase)
  419. if err != nil {
  420. return err
  421. }
  422. return ks.storage.StoreKey(a.URL.Path, key, newPassphrase)
  423. }
  424. // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
  425. // a key file in the key directory. The key file is encrypted with the same passphrase.
  426. func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) {
  427. a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase)
  428. if err != nil {
  429. return a, err
  430. }
  431. ks.cache.add(a)
  432. ks.refreshWallets()
  433. return a, nil
  434. }
  435. // zeroKey zeroes a private key in memory.
  436. func zeroKey(k *ecdsa.PrivateKey) {
  437. b := k.D.Bits()
  438. for i := range b {
  439. b[i] = 0
  440. }
  441. }