account_manager.go 6.3 KB

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