key_store_plain.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. package crypto
  21. import (
  22. "encoding/hex"
  23. "encoding/json"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "os"
  28. "path/filepath"
  29. "time"
  30. "github.com/ethereum/go-ethereum/common"
  31. )
  32. type KeyStore interface {
  33. // create new key using io.Reader entropy source and optionally using auth string
  34. GenerateNewKey(io.Reader, string) (*Key, error)
  35. GetKey(common.Address, string) (*Key, error) // get key from addr and auth string
  36. GetKeyAddresses() ([]common.Address, error) // get all addresses
  37. StoreKey(*Key, string) error // store key optionally using auth string
  38. DeleteKey(common.Address, string) error // delete key by addr and auth string
  39. Cleanup(keyAddr common.Address) (err error)
  40. }
  41. type keyStorePlain struct {
  42. keysDirPath string
  43. }
  44. func NewKeyStorePlain(path string) KeyStore {
  45. return &keyStorePlain{path}
  46. }
  47. func (ks keyStorePlain) GenerateNewKey(rand io.Reader, auth string) (key *Key, err error) {
  48. return GenerateNewKeyDefault(ks, rand, auth)
  49. }
  50. func GenerateNewKeyDefault(ks KeyStore, rand io.Reader, auth string) (key *Key, err error) {
  51. defer func() {
  52. if r := recover(); r != nil {
  53. err = fmt.Errorf("GenerateNewKey error: %v", r)
  54. }
  55. }()
  56. key = NewKey(rand)
  57. err = ks.StoreKey(key, auth)
  58. return key, err
  59. }
  60. func (ks keyStorePlain) GetKey(keyAddr common.Address, auth string) (key *Key, err error) {
  61. key = new(Key)
  62. err = getKey(ks.keysDirPath, keyAddr, key)
  63. return
  64. }
  65. func getKey(keysDirPath string, keyAddr common.Address, content interface{}) (err error) {
  66. fileContent, err := getKeyFile(keysDirPath, keyAddr)
  67. if err != nil {
  68. return
  69. }
  70. return json.Unmarshal(fileContent, content)
  71. }
  72. func (ks keyStorePlain) GetKeyAddresses() (addresses []common.Address, err error) {
  73. return getKeyAddresses(ks.keysDirPath)
  74. }
  75. func (ks keyStorePlain) Cleanup(keyAddr common.Address) (err error) {
  76. return cleanup(ks.keysDirPath, keyAddr)
  77. }
  78. func (ks keyStorePlain) StoreKey(key *Key, auth string) (err error) {
  79. keyJSON, err := json.Marshal(key)
  80. if err != nil {
  81. return
  82. }
  83. err = writeKeyFile(key.Address, ks.keysDirPath, keyJSON)
  84. return
  85. }
  86. func (ks keyStorePlain) DeleteKey(keyAddr common.Address, auth string) (err error) {
  87. return deleteKey(ks.keysDirPath, keyAddr)
  88. }
  89. func deleteKey(keysDirPath string, keyAddr common.Address) (err error) {
  90. var path string
  91. path, err = getKeyFilePath(keysDirPath, keyAddr)
  92. if err == nil {
  93. addrHex := hex.EncodeToString(keyAddr[:])
  94. if path == filepath.Join(keysDirPath, addrHex, addrHex) {
  95. path = filepath.Join(keysDirPath, addrHex)
  96. }
  97. err = os.RemoveAll(path)
  98. }
  99. return
  100. }
  101. func getKeyFilePath(keysDirPath string, keyAddr common.Address) (keyFilePath string, err error) {
  102. addrHex := hex.EncodeToString(keyAddr[:])
  103. matches, err := filepath.Glob(filepath.Join(keysDirPath, fmt.Sprintf("*--%s", addrHex)))
  104. if len(matches) > 0 {
  105. if err == nil {
  106. keyFilePath = matches[len(matches)-1]
  107. }
  108. return
  109. }
  110. keyFilePath = filepath.Join(keysDirPath, addrHex, addrHex)
  111. _, err = os.Stat(keyFilePath)
  112. return
  113. }
  114. func cleanup(keysDirPath string, keyAddr common.Address) (err error) {
  115. fileInfos, err := ioutil.ReadDir(keysDirPath)
  116. if err != nil {
  117. return
  118. }
  119. var paths []string
  120. account := hex.EncodeToString(keyAddr[:])
  121. for _, fileInfo := range fileInfos {
  122. path := filepath.Join(keysDirPath, fileInfo.Name())
  123. if len(path) >= 40 {
  124. addr := path[len(path)-40 : len(path)]
  125. if addr == account {
  126. if path == filepath.Join(keysDirPath, addr, addr) {
  127. path = filepath.Join(keysDirPath, addr)
  128. }
  129. paths = append(paths, path)
  130. }
  131. }
  132. }
  133. if len(paths) > 1 {
  134. for i := 0; err == nil && i < len(paths)-1; i++ {
  135. err = os.RemoveAll(paths[i])
  136. if err != nil {
  137. break
  138. }
  139. }
  140. }
  141. return
  142. }
  143. func getKeyFile(keysDirPath string, keyAddr common.Address) (fileContent []byte, err error) {
  144. var keyFilePath string
  145. keyFilePath, err = getKeyFilePath(keysDirPath, keyAddr)
  146. if err == nil {
  147. fileContent, err = ioutil.ReadFile(keyFilePath)
  148. }
  149. return
  150. }
  151. func writeKeyFile(addr common.Address, keysDirPath string, content []byte) (err error) {
  152. filename := keyFileName(addr)
  153. // read, write and dir search for user
  154. err = os.MkdirAll(keysDirPath, 0700)
  155. if err != nil {
  156. return err
  157. }
  158. // read, write for user
  159. return ioutil.WriteFile(filepath.Join(keysDirPath, filename), content, 0600)
  160. }
  161. // keyFilePath implements the naming convention for keyfiles:
  162. // UTC--<created_at UTC ISO8601>-<address hex>
  163. func keyFileName(keyAddr common.Address) string {
  164. ts := time.Now().UTC()
  165. return fmt.Sprintf("UTC--%s--%s", toISO8601(ts), hex.EncodeToString(keyAddr[:]))
  166. }
  167. func toISO8601(t time.Time) string {
  168. var tz string
  169. name, offset := t.Zone()
  170. if name == "UTC" {
  171. tz = "Z"
  172. } else {
  173. tz = fmt.Sprintf("%03d00", offset/3600)
  174. }
  175. return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%09d%s", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), tz)
  176. }
  177. func getKeyAddresses(keysDirPath string) (addresses []common.Address, err error) {
  178. fileInfos, err := ioutil.ReadDir(keysDirPath)
  179. if err != nil {
  180. return nil, err
  181. }
  182. for _, fileInfo := range fileInfos {
  183. filename := fileInfo.Name()
  184. if len(filename) >= 40 {
  185. addr := filename[len(filename)-40 : len(filename)]
  186. address, err := hex.DecodeString(addr)
  187. if err == nil {
  188. addresses = append(addresses, common.BytesToAddress(address))
  189. }
  190. }
  191. }
  192. return addresses, err
  193. }