account_manager.go 6.0 KB

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