account_manager.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 implements a private key management facility.
  17. //
  18. // This abstracts part of a user's interaction with an account she controls.
  19. package accounts
  20. // Currently this is pretty much a passthrough to the KeyStore interface,
  21. // and accounts persistence is derived from stored keys' addresses
  22. import (
  23. "crypto/ecdsa"
  24. crand "crypto/rand"
  25. "errors"
  26. "fmt"
  27. "os"
  28. "sync"
  29. "time"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. )
  33. var (
  34. ErrLocked = errors.New("account is locked")
  35. ErrNoKeys = errors.New("no keys in store")
  36. )
  37. type Account struct {
  38. Address common.Address
  39. }
  40. type Manager struct {
  41. keyStore crypto.KeyStore
  42. unlocked map[common.Address]*unlocked
  43. mutex sync.RWMutex
  44. }
  45. type unlocked struct {
  46. *crypto.Key
  47. abort chan struct{}
  48. }
  49. func NewManager(keyStore crypto.KeyStore) *Manager {
  50. return &Manager{
  51. keyStore: keyStore,
  52. unlocked: make(map[common.Address]*unlocked),
  53. }
  54. }
  55. func (am *Manager) HasAccount(addr common.Address) bool {
  56. accounts, _ := am.Accounts()
  57. for _, acct := range accounts {
  58. if acct.Address == addr {
  59. return true
  60. }
  61. }
  62. return false
  63. }
  64. func (am *Manager) DeleteAccount(address common.Address, auth string) error {
  65. return am.keyStore.DeleteKey(address, auth)
  66. }
  67. func (am *Manager) Sign(a Account, toSign []byte) (signature []byte, err error) {
  68. am.mutex.RLock()
  69. defer am.mutex.RUnlock()
  70. unlockedKey, found := am.unlocked[a.Address]
  71. if !found {
  72. return nil, ErrLocked
  73. }
  74. signature, err = crypto.Sign(toSign, unlockedKey.PrivateKey)
  75. return signature, err
  76. }
  77. // Unlock unlocks the given account indefinitely.
  78. func (am *Manager) Unlock(addr common.Address, keyAuth string) error {
  79. return am.TimedUnlock(addr, keyAuth, 0)
  80. }
  81. // TimedUnlock unlocks the account with the given address. The account
  82. // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account
  83. // until the program exits.
  84. //
  85. // If the accout is already unlocked, TimedUnlock extends or shortens
  86. // the active unlock timeout.
  87. func (am *Manager) TimedUnlock(addr common.Address, keyAuth string, timeout time.Duration) error {
  88. key, err := am.keyStore.GetKey(addr, keyAuth)
  89. if err != nil {
  90. return err
  91. }
  92. var u *unlocked
  93. am.mutex.Lock()
  94. defer am.mutex.Unlock()
  95. var found bool
  96. u, found = am.unlocked[addr]
  97. if found {
  98. // terminate dropLater for this key to avoid unexpected drops.
  99. if u.abort != nil {
  100. close(u.abort)
  101. }
  102. }
  103. if timeout > 0 {
  104. u = &unlocked{Key: key, abort: make(chan struct{})}
  105. go am.expire(addr, u, timeout)
  106. } else {
  107. u = &unlocked{Key: key}
  108. }
  109. am.unlocked[addr] = u
  110. return nil
  111. }
  112. func (am *Manager) expire(addr common.Address, u *unlocked, timeout time.Duration) {
  113. t := time.NewTimer(timeout)
  114. defer t.Stop()
  115. select {
  116. case <-u.abort:
  117. // just quit
  118. case <-t.C:
  119. am.mutex.Lock()
  120. // only drop if it's still the same key instance that dropLater
  121. // was launched with. we can check that using pointer equality
  122. // because the map stores a new pointer every time the key is
  123. // unlocked.
  124. if am.unlocked[addr] == u {
  125. zeroKey(u.PrivateKey)
  126. delete(am.unlocked, addr)
  127. }
  128. am.mutex.Unlock()
  129. }
  130. }
  131. func (am *Manager) NewAccount(auth string) (Account, error) {
  132. key, err := am.keyStore.GenerateNewKey(crand.Reader, auth)
  133. if err != nil {
  134. return Account{}, err
  135. }
  136. return Account{Address: key.Address}, nil
  137. }
  138. func (am *Manager) AddressByIndex(index int) (addr string, err error) {
  139. var addrs []common.Address
  140. addrs, err = am.keyStore.GetKeyAddresses()
  141. if err != nil {
  142. return
  143. }
  144. if index < 0 || index >= len(addrs) {
  145. err = fmt.Errorf("index out of range: %d (should be 0-%d)", index, len(addrs)-1)
  146. } else {
  147. addr = addrs[index].Hex()
  148. }
  149. return
  150. }
  151. func (am *Manager) Accounts() ([]Account, error) {
  152. addresses, err := am.keyStore.GetKeyAddresses()
  153. if os.IsNotExist(err) {
  154. return nil, ErrNoKeys
  155. } else if err != nil {
  156. return nil, err
  157. }
  158. accounts := make([]Account, len(addresses))
  159. for i, addr := range addresses {
  160. accounts[i] = Account{
  161. Address: addr,
  162. }
  163. }
  164. return accounts, err
  165. }
  166. // zeroKey zeroes a private key in memory.
  167. func zeroKey(k *ecdsa.PrivateKey) {
  168. b := k.D.Bits()
  169. for i := range b {
  170. b[i] = 0
  171. }
  172. }
  173. // USE WITH CAUTION = this will save an unencrypted private key on disk
  174. // no cli or js interface
  175. func (am *Manager) Export(path string, addr common.Address, keyAuth string) error {
  176. key, err := am.keyStore.GetKey(addr, keyAuth)
  177. if err != nil {
  178. return err
  179. }
  180. return crypto.SaveECDSA(path, key.PrivateKey)
  181. }
  182. func (am *Manager) Import(path string, keyAuth string) (Account, error) {
  183. privateKeyECDSA, err := crypto.LoadECDSA(path)
  184. if err != nil {
  185. return Account{}, err
  186. }
  187. key := crypto.NewKeyFromECDSA(privateKeyECDSA)
  188. if err = am.keyStore.StoreKey(key, keyAuth); err != nil {
  189. return Account{}, err
  190. }
  191. return Account{Address: key.Address}, nil
  192. }
  193. func (am *Manager) Update(addr common.Address, authFrom, authTo string) (err error) {
  194. var key *crypto.Key
  195. key, err = am.keyStore.GetKey(addr, authFrom)
  196. if err == nil {
  197. err = am.keyStore.StoreKey(key, authTo)
  198. if err == nil {
  199. am.keyStore.Cleanup(addr)
  200. }
  201. }
  202. return
  203. }
  204. func (am *Manager) ImportPreSaleKey(keyJSON []byte, password string) (acc Account, err error) {
  205. var key *crypto.Key
  206. key, err = crypto.ImportPreSaleKey(am.keyStore, keyJSON, password)
  207. if err != nil {
  208. return
  209. }
  210. return Account{Address: key.Address}, nil
  211. }