account_manager.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /*
  2. This file is part of go-ethereum
  3. go-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. go-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @authors
  16. * Gustav Simonsson <gustav.simonsson@gmail.com>
  17. * @date 2015
  18. *
  19. */
  20. /*
  21. This abstracts part of a user's interaction with an account she controls.
  22. It's not an abstraction of core Ethereum accounts data type / logic -
  23. for that see the core processing code of blocks / txs.
  24. Currently this is pretty much a passthrough to the KeyStore2 interface,
  25. and accounts persistence is derived from stored keys' addresses
  26. */
  27. package accounts
  28. import (
  29. "bytes"
  30. "crypto/ecdsa"
  31. crand "crypto/rand"
  32. "errors"
  33. "os"
  34. "sync"
  35. "time"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. )
  38. var (
  39. ErrLocked = errors.New("account is locked")
  40. ErrNoKeys = errors.New("no keys in store")
  41. )
  42. type Account struct {
  43. Address []byte
  44. }
  45. type Manager struct {
  46. keyStore crypto.KeyStore2
  47. unlocked map[string]*unlocked
  48. mutex sync.RWMutex
  49. }
  50. type unlocked struct {
  51. *crypto.Key
  52. abort chan struct{}
  53. }
  54. func NewManager(keyStore crypto.KeyStore2) *Manager {
  55. return &Manager{
  56. keyStore: keyStore,
  57. unlocked: make(map[string]*unlocked),
  58. }
  59. }
  60. func (am *Manager) HasAccount(addr []byte) bool {
  61. accounts, _ := am.Accounts()
  62. for _, acct := range accounts {
  63. if bytes.Compare(acct.Address, addr) == 0 {
  64. return true
  65. }
  66. }
  67. return false
  68. }
  69. func (am *Manager) Primary() (addr []byte, err error) {
  70. addrs, err := am.keyStore.GetKeyAddresses()
  71. if os.IsNotExist(err) {
  72. return nil, ErrNoKeys
  73. } else if err != nil {
  74. return nil, err
  75. }
  76. if len(addrs) == 0 {
  77. return nil, ErrNoKeys
  78. }
  79. return addrs[0], nil
  80. }
  81. func (am *Manager) DeleteAccount(address []byte, auth string) error {
  82. return am.keyStore.DeleteKey(address, auth)
  83. }
  84. func (am *Manager) Sign(a Account, toSign []byte) (signature []byte, err error) {
  85. am.mutex.RLock()
  86. unlockedKey, found := am.unlocked[string(a.Address)]
  87. am.mutex.RUnlock()
  88. if !found {
  89. return nil, ErrLocked
  90. }
  91. signature, err = crypto.Sign(toSign, unlockedKey.PrivateKey)
  92. return signature, err
  93. }
  94. // TimedUnlock unlocks the account with the given address.
  95. // When timeout has passed, the account will be locked again.
  96. func (am *Manager) TimedUnlock(addr []byte, keyAuth string, timeout time.Duration) error {
  97. key, err := am.keyStore.GetKey(addr, keyAuth)
  98. if err != nil {
  99. return err
  100. }
  101. u := am.addUnlocked(addr, key)
  102. go am.dropLater(addr, u, timeout)
  103. return nil
  104. }
  105. // Unlock unlocks the account with the given address. The account
  106. // stays unlocked until the program exits or until a TimedUnlock
  107. // timeout (started after the call to Unlock) expires.
  108. func (am *Manager) Unlock(addr []byte, keyAuth string) error {
  109. key, err := am.keyStore.GetKey(addr, keyAuth)
  110. if err != nil {
  111. return err
  112. }
  113. am.addUnlocked(addr, key)
  114. return nil
  115. }
  116. func (am *Manager) NewAccount(auth string) (Account, error) {
  117. key, err := am.keyStore.GenerateNewKey(crand.Reader, auth)
  118. if err != nil {
  119. return Account{}, err
  120. }
  121. return Account{Address: key.Address}, nil
  122. }
  123. func (am *Manager) Accounts() ([]Account, error) {
  124. addresses, err := am.keyStore.GetKeyAddresses()
  125. if os.IsNotExist(err) {
  126. return nil, ErrNoKeys
  127. } else if err != nil {
  128. return nil, err
  129. }
  130. accounts := make([]Account, len(addresses))
  131. for i, addr := range addresses {
  132. accounts[i] = Account{
  133. Address: addr,
  134. }
  135. }
  136. return accounts, err
  137. }
  138. func (am *Manager) addUnlocked(addr []byte, key *crypto.Key) *unlocked {
  139. u := &unlocked{Key: key, abort: make(chan struct{})}
  140. am.mutex.Lock()
  141. prev, found := am.unlocked[string(addr)]
  142. if found {
  143. // terminate dropLater for this key to avoid unexpected drops.
  144. close(prev.abort)
  145. // the key is zeroed here instead of in dropLater because
  146. // there might not actually be a dropLater running for this
  147. // key, i.e. when Unlock was used.
  148. zeroKey(prev.PrivateKey)
  149. }
  150. am.unlocked[string(addr)] = u
  151. am.mutex.Unlock()
  152. return u
  153. }
  154. func (am *Manager) dropLater(addr []byte, u *unlocked, timeout time.Duration) {
  155. t := time.NewTimer(timeout)
  156. defer t.Stop()
  157. select {
  158. case <-u.abort:
  159. // just quit
  160. case <-t.C:
  161. am.mutex.Lock()
  162. // only drop if it's still the same key instance that dropLater
  163. // was launched with. we can check that using pointer equality
  164. // because the map stores a new pointer every time the key is
  165. // unlocked.
  166. if am.unlocked[string(addr)] == u {
  167. zeroKey(u.PrivateKey)
  168. delete(am.unlocked, string(addr))
  169. }
  170. am.mutex.Unlock()
  171. }
  172. }
  173. // zeroKey zeroes a private key in memory.
  174. func zeroKey(k *ecdsa.PrivateKey) {
  175. b := k.D.Bits()
  176. for i := range b {
  177. b[i] = 0
  178. }
  179. }
  180. // USE WITH CAUTION = this will save an unencrypted private key on disk
  181. // no cli or js interface
  182. func (am *Manager) Export(path string, addr []byte, keyAuth string) error {
  183. key, err := am.keyStore.GetKey(addr, keyAuth)
  184. if err != nil {
  185. return err
  186. }
  187. return crypto.SaveECDSA(path, key.PrivateKey)
  188. }
  189. func (am *Manager) Import(path string, keyAuth string) (Account, error) {
  190. privateKeyECDSA, err := crypto.LoadECDSA(path)
  191. if err != nil {
  192. return Account{}, err
  193. }
  194. key := crypto.NewKeyFromECDSA(privateKeyECDSA)
  195. if err = am.keyStore.StoreKey(key, keyAuth); err != nil {
  196. return Account{}, err
  197. }
  198. return Account{Address: key.Address}, nil
  199. }
  200. func (am *Manager) ImportPreSaleKey(keyJSON []byte, password string) (acc Account, err error) {
  201. var key *crypto.Key
  202. key, err = crypto.ImportPreSaleKey(am.keyStore, keyJSON, password)
  203. if err != nil {
  204. return
  205. }
  206. if err = am.keyStore.StoreKey(key, password); err != nil {
  207. return
  208. }
  209. return Account{Address: key.Address}, nil
  210. }