account_manager.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. "crypto/ecdsa"
  30. crand "crypto/rand"
  31. "errors"
  32. "os"
  33. "sync"
  34. "time"
  35. "github.com/ethereum/go-ethereum/common"
  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. const (
  43. // Default unlock duration (in seconds) when an account is unlocked from the console
  44. DefaultAccountUnlockDuration = 300
  45. )
  46. type Account struct {
  47. Address common.Address
  48. }
  49. type Manager struct {
  50. keyStore crypto.KeyStore2
  51. unlocked map[common.Address]*unlocked
  52. mutex sync.RWMutex
  53. }
  54. type unlocked struct {
  55. *crypto.Key
  56. abort chan struct{}
  57. }
  58. func NewManager(keyStore crypto.KeyStore2) *Manager {
  59. return &Manager{
  60. keyStore: keyStore,
  61. unlocked: make(map[common.Address]*unlocked),
  62. }
  63. }
  64. func (am *Manager) HasAccount(addr common.Address) bool {
  65. accounts, _ := am.Accounts()
  66. for _, acct := range accounts {
  67. if acct.Address == addr {
  68. return true
  69. }
  70. }
  71. return false
  72. }
  73. func (am *Manager) Primary() (addr common.Address, err error) {
  74. addrs, err := am.keyStore.GetKeyAddresses()
  75. if os.IsNotExist(err) {
  76. return common.Address{}, ErrNoKeys
  77. } else if err != nil {
  78. return common.Address{}, err
  79. }
  80. if len(addrs) == 0 {
  81. return common.Address{}, ErrNoKeys
  82. }
  83. return addrs[0], nil
  84. }
  85. func (am *Manager) DeleteAccount(address common.Address, auth string) error {
  86. return am.keyStore.DeleteKey(address, auth)
  87. }
  88. func (am *Manager) Sign(a Account, toSign []byte) (signature []byte, err error) {
  89. am.mutex.RLock()
  90. unlockedKey, found := am.unlocked[a.Address]
  91. am.mutex.RUnlock()
  92. if !found {
  93. return nil, ErrLocked
  94. }
  95. signature, err = crypto.Sign(toSign, unlockedKey.PrivateKey)
  96. return signature, err
  97. }
  98. // TimedUnlock unlocks the account with the given address.
  99. // When timeout has passed, the account will be locked again.
  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. u := am.addUnlocked(addr, key)
  106. go am.dropLater(addr, u, timeout)
  107. return nil
  108. }
  109. // Unlock unlocks the account with the given address. The account
  110. // stays unlocked until the program exits or until a TimedUnlock
  111. // timeout (started after the call to Unlock) expires.
  112. func (am *Manager) Unlock(addr common.Address, keyAuth string) error {
  113. key, err := am.keyStore.GetKey(addr, keyAuth)
  114. if err != nil {
  115. return err
  116. }
  117. am.addUnlocked(addr, key)
  118. return nil
  119. }
  120. func (am *Manager) NewAccount(auth string) (Account, error) {
  121. key, err := am.keyStore.GenerateNewKey(crand.Reader, auth)
  122. if err != nil {
  123. return Account{}, err
  124. }
  125. return Account{Address: key.Address}, nil
  126. }
  127. func (am *Manager) Accounts() ([]Account, error) {
  128. addresses, err := am.keyStore.GetKeyAddresses()
  129. if os.IsNotExist(err) {
  130. return nil, ErrNoKeys
  131. } else if err != nil {
  132. return nil, err
  133. }
  134. accounts := make([]Account, len(addresses))
  135. for i, addr := range addresses {
  136. accounts[i] = Account{
  137. Address: addr,
  138. }
  139. }
  140. return accounts, err
  141. }
  142. func (am *Manager) addUnlocked(addr common.Address, key *crypto.Key) *unlocked {
  143. u := &unlocked{Key: key, abort: make(chan struct{})}
  144. am.mutex.Lock()
  145. prev, found := am.unlocked[addr]
  146. if found {
  147. // terminate dropLater for this key to avoid unexpected drops.
  148. close(prev.abort)
  149. // the key is zeroed here instead of in dropLater because
  150. // there might not actually be a dropLater running for this
  151. // key, i.e. when Unlock was used.
  152. zeroKey(prev.PrivateKey)
  153. }
  154. am.unlocked[addr] = u
  155. am.mutex.Unlock()
  156. return u
  157. }
  158. func (am *Manager) dropLater(addr common.Address, u *unlocked, timeout time.Duration) {
  159. t := time.NewTimer(timeout)
  160. defer t.Stop()
  161. select {
  162. case <-u.abort:
  163. // just quit
  164. case <-t.C:
  165. am.mutex.Lock()
  166. // only drop if it's still the same key instance that dropLater
  167. // was launched with. we can check that using pointer equality
  168. // because the map stores a new pointer every time the key is
  169. // unlocked.
  170. if am.unlocked[addr] == u {
  171. zeroKey(u.PrivateKey)
  172. delete(am.unlocked, addr)
  173. }
  174. am.mutex.Unlock()
  175. }
  176. }
  177. // zeroKey zeroes a private key in memory.
  178. func zeroKey(k *ecdsa.PrivateKey) {
  179. b := k.D.Bits()
  180. for i := range b {
  181. b[i] = 0
  182. }
  183. }
  184. // USE WITH CAUTION = this will save an unencrypted private key on disk
  185. // no cli or js interface
  186. func (am *Manager) Export(path string, addr common.Address, keyAuth string) error {
  187. key, err := am.keyStore.GetKey(addr, keyAuth)
  188. if err != nil {
  189. return err
  190. }
  191. return crypto.SaveECDSA(path, key.PrivateKey)
  192. }
  193. func (am *Manager) Import(path string, keyAuth string) (Account, error) {
  194. privateKeyECDSA, err := crypto.LoadECDSA(path)
  195. if err != nil {
  196. return Account{}, err
  197. }
  198. key := crypto.NewKeyFromECDSA(privateKeyECDSA)
  199. if err = am.keyStore.StoreKey(key, keyAuth); err != nil {
  200. return Account{}, err
  201. }
  202. return Account{Address: key.Address}, nil
  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. if err = am.keyStore.StoreKey(key, password); err != nil {
  211. return
  212. }
  213. return Account{Address: key.Address}, nil
  214. }