account_manager.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. // Coinbase returns the account address that mining rewards are sent to.
  70. func (am *Manager) Coinbase() (addr []byte, err error) {
  71. // TODO: persist coinbase address on disk
  72. return am.firstAddr()
  73. }
  74. func (am *Manager) firstAddr() ([]byte, error) {
  75. addrs, err := am.keyStore.GetKeyAddresses()
  76. if os.IsNotExist(err) {
  77. return nil, ErrNoKeys
  78. } else if err != nil {
  79. return nil, err
  80. }
  81. if len(addrs) == 0 {
  82. return nil, ErrNoKeys
  83. }
  84. return addrs[0], nil
  85. }
  86. func (am *Manager) DeleteAccount(address []byte, auth string) error {
  87. return am.keyStore.DeleteKey(address, auth)
  88. }
  89. func (am *Manager) Sign(a Account, toSign []byte) (signature []byte, err error) {
  90. am.mutex.RLock()
  91. unlockedKey, found := am.unlocked[string(a.Address)]
  92. am.mutex.RUnlock()
  93. if !found {
  94. return nil, ErrLocked
  95. }
  96. signature, err = crypto.Sign(toSign, unlockedKey.PrivateKey)
  97. return signature, err
  98. }
  99. // TimedUnlock unlocks the account with the given address.
  100. // When timeout has passed, the account will be locked again.
  101. func (am *Manager) TimedUnlock(addr []byte, keyAuth string, timeout time.Duration) error {
  102. key, err := am.keyStore.GetKey(addr, keyAuth)
  103. if err != nil {
  104. return err
  105. }
  106. u := am.addUnlocked(addr, key)
  107. go am.dropLater(addr, u, timeout)
  108. return nil
  109. }
  110. // Unlock unlocks the account with the given address. The account
  111. // stays unlocked until the program exits or until a TimedUnlock
  112. // timeout (started after the call to Unlock) expires.
  113. func (am *Manager) Unlock(addr []byte, keyAuth string) error {
  114. key, err := am.keyStore.GetKey(addr, keyAuth)
  115. if err != nil {
  116. return err
  117. }
  118. am.addUnlocked(addr, key)
  119. return nil
  120. }
  121. func (am *Manager) NewAccount(auth string) (Account, error) {
  122. key, err := am.keyStore.GenerateNewKey(crand.Reader, auth)
  123. if err != nil {
  124. return Account{}, err
  125. }
  126. return Account{Address: key.Address}, nil
  127. }
  128. func (am *Manager) Accounts() ([]Account, error) {
  129. addresses, err := am.keyStore.GetKeyAddresses()
  130. if os.IsNotExist(err) {
  131. return nil, ErrNoKeys
  132. } else if err != nil {
  133. return nil, err
  134. }
  135. accounts := make([]Account, len(addresses))
  136. for i, addr := range addresses {
  137. accounts[i] = Account{
  138. Address: addr,
  139. }
  140. }
  141. return accounts, err
  142. }
  143. func (am *Manager) addUnlocked(addr []byte, key *crypto.Key) *unlocked {
  144. u := &unlocked{Key: key, abort: make(chan struct{})}
  145. am.mutex.Lock()
  146. prev, found := am.unlocked[string(addr)]
  147. if found {
  148. // terminate dropLater for this key to avoid unexpected drops.
  149. close(prev.abort)
  150. // the key is zeroed here instead of in dropLater because
  151. // there might not actually be a dropLater running for this
  152. // key, i.e. when Unlock was used.
  153. zeroKey(prev.PrivateKey)
  154. }
  155. am.unlocked[string(addr)] = u
  156. am.mutex.Unlock()
  157. return u
  158. }
  159. func (am *Manager) dropLater(addr []byte, u *unlocked, timeout time.Duration) {
  160. t := time.NewTimer(timeout)
  161. defer t.Stop()
  162. select {
  163. case <-u.abort:
  164. // just quit
  165. case <-t.C:
  166. am.mutex.Lock()
  167. // only drop if it's still the same key instance that dropLater
  168. // was launched with. we can check that using pointer equality
  169. // because the map stores a new pointer every time the key is
  170. // unlocked.
  171. if am.unlocked[string(addr)] == u {
  172. zeroKey(u.PrivateKey)
  173. delete(am.unlocked, string(addr))
  174. }
  175. am.mutex.Unlock()
  176. }
  177. }
  178. // zeroKey zeroes a private key in memory.
  179. func zeroKey(k *ecdsa.PrivateKey) {
  180. b := k.D.Bits()
  181. for i := range b {
  182. b[i] = 0
  183. }
  184. }
  185. // USE WITH CAUTION = this will save an unencrypted private key on disk
  186. // no cli or js interface
  187. func (am *Manager) Export(path string, addr []byte, keyAuth string) error {
  188. key, err := am.keyStore.GetKey(addr, keyAuth)
  189. if err != nil {
  190. return err
  191. }
  192. return crypto.SaveECDSA(path, key.PrivateKey)
  193. }
  194. func (am *Manager) Import(path string, keyAuth string) (Account, error) {
  195. privateKeyECDSA, err := crypto.LoadECDSA(path)
  196. if err != nil {
  197. return Account{}, err
  198. }
  199. key := crypto.NewKeyFromECDSA(privateKeyECDSA)
  200. if err = am.keyStore.StoreKey(key, keyAuth); err != nil {
  201. return Account{}, err
  202. }
  203. return Account{Address: key.Address}, nil
  204. }
  205. func (am *Manager) ImportPreSaleKey(keyJSON []byte, password string) (acc Account, err error) {
  206. var key *crypto.Key
  207. key, err = crypto.ImportPreSaleKey(am.keyStore, keyJSON, password)
  208. if err != nil {
  209. return
  210. }
  211. if err = am.keyStore.StoreKey(key, password); err != nil {
  212. return
  213. }
  214. return Account{Address: key.Address}, nil
  215. }