account_manager.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. // DeleteAccount deletes the key matched by account if the passphrase is correct.
  101. // If a contains no filename, the address must match a unique key.
  102. func (am *Manager) DeleteAccount(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.
  123. // Note, Ethereum signatures have a particular format as described in the
  124. // yellow paper. Use the SignEthereum function to calculate a signature
  125. // in Ethereum format.
  126. func (am *Manager) Sign(addr common.Address, hash []byte) ([]byte, error) {
  127. am.mu.RLock()
  128. defer am.mu.RUnlock()
  129. unlockedKey, found := am.unlocked[addr]
  130. if !found {
  131. return nil, ErrLocked
  132. }
  133. return crypto.Sign(hash, unlockedKey.PrivateKey)
  134. }
  135. // SignEthereum calculates a ECDSA signature for the given hash.
  136. // The signature has the format as described in the Ethereum yellow paper.
  137. func (am *Manager) SignEthereum(addr common.Address, hash []byte) ([]byte, error) {
  138. am.mu.RLock()
  139. defer am.mu.RUnlock()
  140. unlockedKey, found := am.unlocked[addr]
  141. if !found {
  142. return nil, ErrLocked
  143. }
  144. return crypto.SignEthereum(hash, unlockedKey.PrivateKey)
  145. }
  146. // SignWithPassphrase signs hash if the private key matching the given
  147. // address can be decrypted with the given passphrase.
  148. func (am *Manager) SignWithPassphrase(addr common.Address, passphrase string, hash []byte) (signature []byte, err error) {
  149. _, key, err := am.getDecryptedKey(Account{Address: addr}, passphrase)
  150. if err != nil {
  151. return nil, err
  152. }
  153. defer zeroKey(key.PrivateKey)
  154. return crypto.SignEthereum(hash, key.PrivateKey)
  155. }
  156. // Unlock unlocks the given account indefinitely.
  157. func (am *Manager) Unlock(a Account, passphrase string) error {
  158. return am.TimedUnlock(a, passphrase, 0)
  159. }
  160. // Lock removes the private key with the given address from memory.
  161. func (am *Manager) Lock(addr common.Address) error {
  162. am.mu.Lock()
  163. if unl, found := am.unlocked[addr]; found {
  164. am.mu.Unlock()
  165. am.expire(addr, unl, time.Duration(0)*time.Nanosecond)
  166. } else {
  167. am.mu.Unlock()
  168. }
  169. return nil
  170. }
  171. // TimedUnlock unlocks the given account with the passphrase. The account
  172. // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
  173. // until the program exits. The account must match a unique key file.
  174. //
  175. // If the account address is already unlocked for a duration, TimedUnlock extends or
  176. // shortens the active unlock timeout. If the address was previously unlocked
  177. // indefinitely the timeout is not altered.
  178. func (am *Manager) TimedUnlock(a Account, passphrase string, timeout time.Duration) error {
  179. a, key, err := am.getDecryptedKey(a, passphrase)
  180. if err != nil {
  181. return err
  182. }
  183. am.mu.Lock()
  184. defer am.mu.Unlock()
  185. u, found := am.unlocked[a.Address]
  186. if found {
  187. if u.abort == nil {
  188. // The address was unlocked indefinitely, so unlocking
  189. // it with a timeout would be confusing.
  190. zeroKey(key.PrivateKey)
  191. return nil
  192. } else {
  193. // Terminate the expire goroutine and replace it below.
  194. close(u.abort)
  195. }
  196. }
  197. if timeout > 0 {
  198. u = &unlocked{Key: key, abort: make(chan struct{})}
  199. go am.expire(a.Address, u, timeout)
  200. } else {
  201. u = &unlocked{Key: key}
  202. }
  203. am.unlocked[a.Address] = u
  204. return nil
  205. }
  206. func (am *Manager) getDecryptedKey(a Account, auth string) (Account, *Key, error) {
  207. am.cache.maybeReload()
  208. am.cache.mu.Lock()
  209. a, err := am.cache.find(a)
  210. am.cache.mu.Unlock()
  211. if err != nil {
  212. return a, nil, err
  213. }
  214. key, err := am.keyStore.GetKey(a.Address, a.File, auth)
  215. return a, key, err
  216. }
  217. func (am *Manager) expire(addr common.Address, u *unlocked, timeout time.Duration) {
  218. t := time.NewTimer(timeout)
  219. defer t.Stop()
  220. select {
  221. case <-u.abort:
  222. // just quit
  223. case <-t.C:
  224. am.mu.Lock()
  225. // only drop if it's still the same key instance that dropLater
  226. // was launched with. we can check that using pointer equality
  227. // because the map stores a new pointer every time the key is
  228. // unlocked.
  229. if am.unlocked[addr] == u {
  230. zeroKey(u.PrivateKey)
  231. delete(am.unlocked, addr)
  232. }
  233. am.mu.Unlock()
  234. }
  235. }
  236. // NewAccount generates a new key and stores it into the key directory,
  237. // encrypting it with the passphrase.
  238. func (am *Manager) NewAccount(passphrase string) (Account, error) {
  239. _, account, err := storeNewKey(am.keyStore, crand.Reader, passphrase)
  240. if err != nil {
  241. return Account{}, err
  242. }
  243. // Add the account to the cache immediately rather
  244. // than waiting for file system notifications to pick it up.
  245. am.cache.add(account)
  246. return account, nil
  247. }
  248. // AccountByIndex returns the ith account.
  249. func (am *Manager) AccountByIndex(i int) (Account, error) {
  250. accounts := am.Accounts()
  251. if i < 0 || i >= len(accounts) {
  252. return Account{}, fmt.Errorf("account index %d out of range [0, %d]", i, len(accounts)-1)
  253. }
  254. return accounts[i], nil
  255. }
  256. // Export exports as a JSON key, encrypted with newPassphrase.
  257. func (am *Manager) Export(a Account, passphrase, newPassphrase string) (keyJSON []byte, err error) {
  258. _, key, err := am.getDecryptedKey(a, passphrase)
  259. if err != nil {
  260. return nil, err
  261. }
  262. var N, P int
  263. if store, ok := am.keyStore.(*keyStorePassphrase); ok {
  264. N, P = store.scryptN, store.scryptP
  265. } else {
  266. N, P = StandardScryptN, StandardScryptP
  267. }
  268. return EncryptKey(key, newPassphrase, N, P)
  269. }
  270. // Import stores the given encrypted JSON key into the key directory.
  271. func (am *Manager) Import(keyJSON []byte, passphrase, newPassphrase string) (Account, error) {
  272. key, err := DecryptKey(keyJSON, passphrase)
  273. if key != nil && key.PrivateKey != nil {
  274. defer zeroKey(key.PrivateKey)
  275. }
  276. if err != nil {
  277. return Account{}, err
  278. }
  279. return am.importKey(key, newPassphrase)
  280. }
  281. // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase.
  282. func (am *Manager) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (Account, error) {
  283. key := newKeyFromECDSA(priv)
  284. if am.cache.hasAddress(key.Address) {
  285. return Account{}, fmt.Errorf("account already exists")
  286. }
  287. return am.importKey(key, passphrase)
  288. }
  289. func (am *Manager) importKey(key *Key, passphrase string) (Account, error) {
  290. a := Account{Address: key.Address, File: am.keyStore.JoinPath(keyFileName(key.Address))}
  291. if err := am.keyStore.StoreKey(a.File, key, passphrase); err != nil {
  292. return Account{}, err
  293. }
  294. am.cache.add(a)
  295. return a, nil
  296. }
  297. // Update changes the passphrase of an existing account.
  298. func (am *Manager) Update(a Account, passphrase, newPassphrase string) error {
  299. a, key, err := am.getDecryptedKey(a, passphrase)
  300. if err != nil {
  301. return err
  302. }
  303. return am.keyStore.StoreKey(a.File, key, newPassphrase)
  304. }
  305. // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
  306. // a key file in the key directory. The key file is encrypted with the same passphrase.
  307. func (am *Manager) ImportPreSaleKey(keyJSON []byte, passphrase string) (Account, error) {
  308. a, _, err := importPreSaleKey(am.keyStore, keyJSON, passphrase)
  309. if err != nil {
  310. return a, err
  311. }
  312. am.cache.add(a)
  313. return a, nil
  314. }
  315. // zeroKey zeroes a private key in memory.
  316. func zeroKey(k *ecdsa.PrivateKey) {
  317. b := k.D.Bits()
  318. for i := range b {
  319. b[i] = 0
  320. }
  321. }