keystore.go 17 KB

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