account_manager.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 accounts 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 accounts
  21. import (
  22. "crypto/ecdsa"
  23. crand "crypto/rand"
  24. "encoding/json"
  25. "errors"
  26. "fmt"
  27. "os"
  28. "path/filepath"
  29. "runtime"
  30. "sync"
  31. "time"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/crypto"
  34. "github.com/ethereum/go-ethereum/p2p"
  35. "github.com/ethereum/go-ethereum/rpc"
  36. )
  37. var (
  38. ErrLocked = errors.New("account is locked")
  39. ErrNoMatch = errors.New("no key for given address or file")
  40. ErrDecrypt = errors.New("could not decrypt key with given passphrase")
  41. )
  42. // Account represents a stored key.
  43. // When used as an argument, it selects a unique key file to act on.
  44. type Account struct {
  45. Address common.Address // Ethereum account address derived from the key
  46. // File contains the key file name.
  47. // When Acccount is used as an argument to select a key, File can be left blank to
  48. // select just by address or set to the basename or absolute path of a file in the key
  49. // directory. Accounts returned by Manager will always contain an absolute path.
  50. File string
  51. }
  52. func (acc *Account) MarshalJSON() ([]byte, error) {
  53. return []byte(`"` + acc.Address.Hex() + `"`), nil
  54. }
  55. func (acc *Account) UnmarshalJSON(raw []byte) error {
  56. return json.Unmarshal(raw, &acc.Address)
  57. }
  58. // Manager manages a key storage directory on disk.
  59. type Manager struct {
  60. cache *addrCache
  61. keyStore keyStore
  62. mu sync.RWMutex
  63. unlocked map[common.Address]*unlocked
  64. }
  65. type unlocked struct {
  66. *Key
  67. abort chan struct{}
  68. }
  69. // NewManager creates a manager for the given directory.
  70. func NewManager(keydir string, scryptN, scryptP int) *Manager {
  71. keydir, _ = filepath.Abs(keydir)
  72. am := &Manager{keyStore: &keyStorePassphrase{keydir, scryptN, scryptP}}
  73. am.init(keydir)
  74. return am
  75. }
  76. // NewPlaintextManager creates a manager for the given directory.
  77. // Deprecated: Use NewManager.
  78. func NewPlaintextManager(keydir string) *Manager {
  79. keydir, _ = filepath.Abs(keydir)
  80. am := &Manager{keyStore: &keyStorePlain{keydir}}
  81. am.init(keydir)
  82. return am
  83. }
  84. func (am *Manager) init(keydir string) {
  85. am.unlocked = make(map[common.Address]*unlocked)
  86. am.cache = newAddrCache(keydir)
  87. // TODO: In order for this finalizer to work, there must be no references
  88. // to am. addrCache doesn't keep a reference but unlocked keys do,
  89. // so the finalizer will not trigger until all timed unlocks have expired.
  90. runtime.SetFinalizer(am, func(m *Manager) {
  91. m.cache.close()
  92. })
  93. }
  94. // HasAddress reports whether a key with the given address is present.
  95. func (am *Manager) HasAddress(addr common.Address) bool {
  96. return am.cache.hasAddress(addr)
  97. }
  98. // Accounts returns all key files present in the directory.
  99. func (am *Manager) Accounts() []Account {
  100. return am.cache.accounts()
  101. }
  102. // DeleteAccount deletes the key matched by account if the passphrase is correct.
  103. // If a contains no filename, the address must match a unique key.
  104. func (am *Manager) DeleteAccount(a Account, passphrase string) error {
  105. // Decrypting the key isn't really necessary, but we do
  106. // it anyway to check the password and zero out the key
  107. // immediately afterwards.
  108. a, key, err := am.getDecryptedKey(a, passphrase)
  109. if key != nil {
  110. zeroKey(key.PrivateKey)
  111. }
  112. if err != nil {
  113. return err
  114. }
  115. // The order is crucial here. The key is dropped from the
  116. // cache after the file is gone so that a reload happening in
  117. // between won't insert it into the cache again.
  118. err = os.Remove(a.File)
  119. if err == nil {
  120. am.cache.delete(a)
  121. }
  122. return err
  123. }
  124. // Sign signs hash with an unlocked private key matching the given address.
  125. func (am *Manager) Sign(addr common.Address, hash []byte) (signature []byte, err error) {
  126. am.mu.RLock()
  127. defer am.mu.RUnlock()
  128. unlockedKey, found := am.unlocked[addr]
  129. if !found {
  130. return nil, ErrLocked
  131. }
  132. return crypto.Sign(hash, unlockedKey.PrivateKey)
  133. }
  134. // SignWithPassphrase signs hash if the private key matching the given address can be
  135. // decrypted with the given passphrase.
  136. func (am *Manager) SignWithPassphrase(addr common.Address, passphrase string, hash []byte) (signature []byte, err error) {
  137. _, key, err := am.getDecryptedKey(Account{Address: addr}, passphrase)
  138. if err != nil {
  139. return nil, err
  140. }
  141. defer zeroKey(key.PrivateKey)
  142. return crypto.Sign(hash, key.PrivateKey)
  143. }
  144. // Unlock unlocks the given account indefinitely.
  145. func (am *Manager) Unlock(a Account, passphrase string) error {
  146. return am.TimedUnlock(a, passphrase, 0)
  147. }
  148. // Lock removes the private key with the given address from memory.
  149. func (am *Manager) Lock(addr common.Address) error {
  150. am.mu.Lock()
  151. if unl, found := am.unlocked[addr]; found {
  152. am.mu.Unlock()
  153. am.expire(addr, unl, time.Duration(0)*time.Nanosecond)
  154. } else {
  155. am.mu.Unlock()
  156. }
  157. return nil
  158. }
  159. // TimedUnlock unlocks the given account with the passphrase. The account
  160. // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
  161. // until the program exits. The account must match a unique key file.
  162. //
  163. // If the account address is already unlocked for a duration, TimedUnlock extends or
  164. // shortens the active unlock timeout. If the address was previously unlocked
  165. // indefinitely the timeout is not altered.
  166. func (am *Manager) TimedUnlock(a Account, passphrase string, timeout time.Duration) error {
  167. a, key, err := am.getDecryptedKey(a, passphrase)
  168. if err != nil {
  169. return err
  170. }
  171. am.mu.Lock()
  172. defer am.mu.Unlock()
  173. u, found := am.unlocked[a.Address]
  174. if found {
  175. if u.abort == nil {
  176. // The address was unlocked indefinitely, so unlocking
  177. // it with a timeout would be confusing.
  178. zeroKey(key.PrivateKey)
  179. return nil
  180. } else {
  181. // Terminate the expire goroutine and replace it below.
  182. close(u.abort)
  183. }
  184. }
  185. if timeout > 0 {
  186. u = &unlocked{Key: key, abort: make(chan struct{})}
  187. go am.expire(a.Address, u, timeout)
  188. } else {
  189. u = &unlocked{Key: key}
  190. }
  191. am.unlocked[a.Address] = u
  192. return nil
  193. }
  194. func (am *Manager) getDecryptedKey(a Account, auth string) (Account, *Key, error) {
  195. am.cache.maybeReload()
  196. am.cache.mu.Lock()
  197. a, err := am.cache.find(a)
  198. am.cache.mu.Unlock()
  199. if err != nil {
  200. return a, nil, err
  201. }
  202. key, err := am.keyStore.GetKey(a.Address, a.File, auth)
  203. return a, key, err
  204. }
  205. func (am *Manager) expire(addr common.Address, u *unlocked, timeout time.Duration) {
  206. t := time.NewTimer(timeout)
  207. defer t.Stop()
  208. select {
  209. case <-u.abort:
  210. // just quit
  211. case <-t.C:
  212. am.mu.Lock()
  213. // only drop if it's still the same key instance that dropLater
  214. // was launched with. we can check that using pointer equality
  215. // because the map stores a new pointer every time the key is
  216. // unlocked.
  217. if am.unlocked[addr] == u {
  218. zeroKey(u.PrivateKey)
  219. delete(am.unlocked, addr)
  220. }
  221. am.mu.Unlock()
  222. }
  223. }
  224. // NewAccount generates a new key and stores it into the key directory,
  225. // encrypting it with the passphrase.
  226. func (am *Manager) NewAccount(passphrase string) (Account, error) {
  227. _, account, err := storeNewKey(am.keyStore, crand.Reader, passphrase)
  228. if err != nil {
  229. return Account{}, err
  230. }
  231. // Add the account to the cache immediately rather
  232. // than waiting for file system notifications to pick it up.
  233. am.cache.add(account)
  234. return account, nil
  235. }
  236. // AccountByIndex returns the ith account.
  237. func (am *Manager) AccountByIndex(i int) (Account, error) {
  238. accounts := am.Accounts()
  239. if i < 0 || i >= len(accounts) {
  240. return Account{}, fmt.Errorf("account index %d out of range [0, %d]", i, len(accounts)-1)
  241. }
  242. return accounts[i], nil
  243. }
  244. // Export exports as a JSON key, encrypted with newPassphrase.
  245. func (am *Manager) Export(a Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
  246. _, key, err := am.getDecryptedKey(a, passphrase)
  247. if err != nil {
  248. return nil, err
  249. }
  250. var N, P int
  251. if store, ok := am.keyStore.(*keyStorePassphrase); ok {
  252. N, P = store.scryptN, store.scryptP
  253. } else {
  254. N, P = StandardScryptN, StandardScryptP
  255. }
  256. return EncryptKey(key, newPassphrase, N, P)
  257. }
  258. // Import stores the given encrypted JSON key into the key directory.
  259. func (am *Manager) Import(keyJSON []byte, passphrase, newPassphrase string) (Account, error) {
  260. key, err := DecryptKey(keyJSON, passphrase)
  261. if key != nil && key.PrivateKey != nil {
  262. defer zeroKey(key.PrivateKey)
  263. }
  264. if err != nil {
  265. return Account{}, err
  266. }
  267. return am.importKey(key, newPassphrase)
  268. }
  269. // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
  270. func (am *Manager) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (Account, error) {
  271. key := newKeyFromECDSA(priv)
  272. if am.cache.hasAddress(key.Address) {
  273. return Account{}, fmt.Errorf("account already exists")
  274. }
  275. return am.importKey(key, passphrase)
  276. }
  277. func (am *Manager) importKey(key *Key, passphrase string) (Account, error) {
  278. a := Account{Address: key.Address, File: am.keyStore.JoinPath(keyFileName(key.Address))}
  279. if err := am.keyStore.StoreKey(a.File, key, passphrase); err != nil {
  280. return Account{}, err
  281. }
  282. am.cache.add(a)
  283. return a, nil
  284. }
  285. // Update changes the passphrase of an existing account.
  286. func (am *Manager) Update(a Account, passphrase, newPassphrase string) error {
  287. a, key, err := am.getDecryptedKey(a, passphrase)
  288. if err != nil {
  289. return err
  290. }
  291. return am.keyStore.StoreKey(a.File, key, newPassphrase)
  292. }
  293. // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
  294. // a key file in the key directory. The key file is encrypted with the same passphrase.
  295. func (am *Manager) ImportPreSaleKey(keyJSON []byte, passphrase string) (Account, error) {
  296. a, _, err := importPreSaleKey(am.keyStore, keyJSON, passphrase)
  297. if err != nil {
  298. return a, err
  299. }
  300. am.cache.add(a)
  301. return a, nil
  302. }
  303. // zeroKey zeroes a private key in memory.
  304. func zeroKey(k *ecdsa.PrivateKey) {
  305. b := k.D.Bits()
  306. for i := range b {
  307. b[i] = 0
  308. }
  309. }
  310. // APIs implements node.Service
  311. func (am *Manager) APIs() []rpc.API {
  312. return nil
  313. }
  314. // Protocols implements node.Service
  315. func (am *Manager) Protocols() []p2p.Protocol {
  316. return nil
  317. }
  318. // Start implements node.Service
  319. func (am *Manager) Start(srvr *p2p.Server) error {
  320. return nil
  321. }
  322. // Stop implements node.Service
  323. func (am *Manager) Stop() error {
  324. return nil
  325. }