account_manager.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. )
  35. var (
  36. ErrLocked = errors.New("account is locked")
  37. ErrNoMatch = errors.New("no key for given address or file")
  38. ErrDecrypt = errors.New("could not decrypt key with given passphrase")
  39. )
  40. // Account represents a stored key.
  41. // When used as an argument, it selects a unique key file to act on.
  42. type Account struct {
  43. Address common.Address // Ethereum account address derived from the key
  44. // File contains the key file name.
  45. // When Acccount is used as an argument to select a key, File can be left blank to
  46. // select just by address or set to the basename or absolute path of a file in the key
  47. // directory. Accounts returned by Manager will always contain an absolute path.
  48. File string
  49. }
  50. func (acc *Account) MarshalJSON() ([]byte, error) {
  51. return []byte(`"` + acc.Address.Hex() + `"`), nil
  52. }
  53. func (acc *Account) UnmarshalJSON(raw []byte) error {
  54. return json.Unmarshal(raw, &acc.Address)
  55. }
  56. // Manager manages a key storage directory on disk.
  57. type Manager struct {
  58. cache *addrCache
  59. keyStore keyStore
  60. mu sync.RWMutex
  61. unlocked map[common.Address]*unlocked
  62. }
  63. type unlocked struct {
  64. *Key
  65. abort chan struct{}
  66. }
  67. // NewManager creates a manager for the given directory.
  68. func NewManager(keydir string, scryptN, scryptP int) *Manager {
  69. keydir, _ = filepath.Abs(keydir)
  70. am := &Manager{keyStore: &keyStorePassphrase{keydir, scryptN, scryptP}}
  71. am.init(keydir)
  72. return am
  73. }
  74. // NewPlaintextManager creates a manager for the given directory.
  75. // Deprecated: Use NewManager.
  76. func NewPlaintextManager(keydir string) *Manager {
  77. keydir, _ = filepath.Abs(keydir)
  78. am := &Manager{keyStore: &keyStorePlain{keydir}}
  79. am.init(keydir)
  80. return am
  81. }
  82. func (am *Manager) init(keydir string) {
  83. am.unlocked = make(map[common.Address]*unlocked)
  84. am.cache = newAddrCache(keydir)
  85. // TODO: In order for this finalizer to work, there must be no references
  86. // to am. addrCache doesn't keep a reference but unlocked keys do,
  87. // so the finalizer will not trigger until all timed unlocks have expired.
  88. runtime.SetFinalizer(am, func(m *Manager) {
  89. m.cache.close()
  90. })
  91. }
  92. // HasAddress reports whether a key with the given address is present.
  93. func (am *Manager) HasAddress(addr common.Address) bool {
  94. return am.cache.hasAddress(addr)
  95. }
  96. // Accounts returns all key files present in the directory.
  97. func (am *Manager) Accounts() []Account {
  98. return am.cache.accounts()
  99. }
  100. // Delete deletes the key matched by account if the passphrase is correct.
  101. // If the account contains no filename, the address must match a unique key.
  102. func (am *Manager) Delete(a Account, passphrase string) error {
  103. // Decrypting the key isn't really necessary, but we do
  104. // it anyway to check the password and zero out the key
  105. // immediately afterwards.
  106. a, key, err := am.getDecryptedKey(a, passphrase)
  107. if key != nil {
  108. zeroKey(key.PrivateKey)
  109. }
  110. if err != nil {
  111. return err
  112. }
  113. // The order is crucial here. The key is dropped from the
  114. // cache after the file is gone so that a reload happening in
  115. // between won't insert it into the cache again.
  116. err = os.Remove(a.File)
  117. if err == nil {
  118. am.cache.delete(a)
  119. }
  120. return err
  121. }
  122. // Sign calculates a ECDSA signature for the given hash. The produced signature
  123. // is in the [R || S || V] format where V is 0 or 1.
  124. func (am *Manager) Sign(addr common.Address, hash []byte) ([]byte, error) {
  125. am.mu.RLock()
  126. defer am.mu.RUnlock()
  127. unlockedKey, found := am.unlocked[addr]
  128. if !found {
  129. return nil, ErrLocked
  130. }
  131. return crypto.Sign(hash, unlockedKey.PrivateKey)
  132. }
  133. // SignWithPassphrase signs hash if the private key matching the given address
  134. // can be decrypted with the given passphrase. The produced signature is in the
  135. // [R || S || V] format where V is 0 or 1.
  136. func (am *Manager) SignWithPassphrase(a Account, passphrase string, hash []byte) (signature []byte, err error) {
  137. _, key, err := am.getDecryptedKey(a, 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. // Find resolves the given account into a unique entry in the keystore.
  195. func (am *Manager) Find(a Account) (Account, error) {
  196. am.cache.maybeReload()
  197. am.cache.mu.Lock()
  198. a, err := am.cache.find(a)
  199. am.cache.mu.Unlock()
  200. return a, err
  201. }
  202. func (am *Manager) getDecryptedKey(a Account, auth string) (Account, *Key, error) {
  203. a, err := am.Find(a)
  204. if err != nil {
  205. return a, nil, err
  206. }
  207. key, err := am.keyStore.GetKey(a.Address, a.File, auth)
  208. return a, key, err
  209. }
  210. func (am *Manager) expire(addr common.Address, u *unlocked, timeout time.Duration) {
  211. t := time.NewTimer(timeout)
  212. defer t.Stop()
  213. select {
  214. case <-u.abort:
  215. // just quit
  216. case <-t.C:
  217. am.mu.Lock()
  218. // only drop if it's still the same key instance that dropLater
  219. // was launched with. we can check that using pointer equality
  220. // because the map stores a new pointer every time the key is
  221. // unlocked.
  222. if am.unlocked[addr] == u {
  223. zeroKey(u.PrivateKey)
  224. delete(am.unlocked, addr)
  225. }
  226. am.mu.Unlock()
  227. }
  228. }
  229. // NewAccount generates a new key and stores it into the key directory,
  230. // encrypting it with the passphrase.
  231. func (am *Manager) NewAccount(passphrase string) (Account, error) {
  232. _, account, err := storeNewKey(am.keyStore, crand.Reader, passphrase)
  233. if err != nil {
  234. return Account{}, err
  235. }
  236. // Add the account to the cache immediately rather
  237. // than waiting for file system notifications to pick it up.
  238. am.cache.add(account)
  239. return account, nil
  240. }
  241. // AccountByIndex returns the ith account.
  242. func (am *Manager) AccountByIndex(i int) (Account, error) {
  243. accounts := am.Accounts()
  244. if i < 0 || i >= len(accounts) {
  245. return Account{}, fmt.Errorf("account index %d out of range [0, %d]", i, len(accounts)-1)
  246. }
  247. return accounts[i], nil
  248. }
  249. // Export exports as a JSON key, encrypted with newPassphrase.
  250. func (am *Manager) Export(a Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
  251. _, key, err := am.getDecryptedKey(a, passphrase)
  252. if err != nil {
  253. return nil, err
  254. }
  255. var N, P int
  256. if store, ok := am.keyStore.(*keyStorePassphrase); ok {
  257. N, P = store.scryptN, store.scryptP
  258. } else {
  259. N, P = StandardScryptN, StandardScryptP
  260. }
  261. return EncryptKey(key, newPassphrase, N, P)
  262. }
  263. // Import stores the given encrypted JSON key into the key directory.
  264. func (am *Manager) Import(keyJSON []byte, passphrase, newPassphrase string) (Account, error) {
  265. key, err := DecryptKey(keyJSON, passphrase)
  266. if key != nil && key.PrivateKey != nil {
  267. defer zeroKey(key.PrivateKey)
  268. }
  269. if err != nil {
  270. return Account{}, err
  271. }
  272. return am.importKey(key, newPassphrase)
  273. }
  274. // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
  275. func (am *Manager) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (Account, error) {
  276. key := newKeyFromECDSA(priv)
  277. if am.cache.hasAddress(key.Address) {
  278. return Account{}, fmt.Errorf("account already exists")
  279. }
  280. return am.importKey(key, passphrase)
  281. }
  282. func (am *Manager) importKey(key *Key, passphrase string) (Account, error) {
  283. a := Account{Address: key.Address, File: am.keyStore.JoinPath(keyFileName(key.Address))}
  284. if err := am.keyStore.StoreKey(a.File, key, passphrase); err != nil {
  285. return Account{}, err
  286. }
  287. am.cache.add(a)
  288. return a, nil
  289. }
  290. // Update changes the passphrase of an existing account.
  291. func (am *Manager) Update(a Account, passphrase, newPassphrase string) error {
  292. a, key, err := am.getDecryptedKey(a, passphrase)
  293. if err != nil {
  294. return err
  295. }
  296. return am.keyStore.StoreKey(a.File, key, newPassphrase)
  297. }
  298. // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
  299. // a key file in the key directory. The key file is encrypted with the same passphrase.
  300. func (am *Manager) ImportPreSaleKey(keyJSON []byte, passphrase string) (Account, error) {
  301. a, _, err := importPreSaleKey(am.keyStore, keyJSON, passphrase)
  302. if err != nil {
  303. return a, err
  304. }
  305. am.cache.add(a)
  306. return a, nil
  307. }
  308. // zeroKey zeroes a private key in memory.
  309. func zeroKey(k *ecdsa.PrivateKey) {
  310. b := k.D.Bits()
  311. for i := range b {
  312. b[i] = 0
  313. }
  314. }