key.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library 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. // The go-ethereum library 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package keystore
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "encoding/hex"
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "os"
  26. "path/filepath"
  27. "strings"
  28. "time"
  29. "github.com/ethereum/go-ethereum/accounts"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/pborman/uuid"
  33. )
  34. const (
  35. version = 3
  36. )
  37. type Key struct {
  38. Id uuid.UUID // Version 4 "random" for unique id not derived from key data
  39. // to simplify lookups we also store the address
  40. Address common.Address
  41. // we only store privkey as pubkey/address can be derived from it
  42. // privkey in this struct is always in plaintext
  43. PrivateKey *ecdsa.PrivateKey
  44. }
  45. type keyStore interface {
  46. // Loads and decrypts the key from disk.
  47. GetKey(addr common.Address, filename string, auth string) (*Key, error)
  48. // Writes and encrypts the key.
  49. StoreKey(filename string, k *Key, auth string) error
  50. // Joins filename with the key directory unless it is already absolute.
  51. JoinPath(filename string) string
  52. }
  53. type plainKeyJSON struct {
  54. Address string `json:"address"`
  55. PrivateKey string `json:"privatekey"`
  56. Id string `json:"id"`
  57. Version int `json:"version"`
  58. }
  59. type encryptedKeyJSONV3 struct {
  60. Address string `json:"address"`
  61. Crypto cryptoJSON `json:"crypto"`
  62. Id string `json:"id"`
  63. Version int `json:"version"`
  64. }
  65. type encryptedKeyJSONV1 struct {
  66. Address string `json:"address"`
  67. Crypto cryptoJSON `json:"crypto"`
  68. Id string `json:"id"`
  69. Version string `json:"version"`
  70. }
  71. type cryptoJSON struct {
  72. Cipher string `json:"cipher"`
  73. CipherText string `json:"ciphertext"`
  74. CipherParams cipherparamsJSON `json:"cipherparams"`
  75. KDF string `json:"kdf"`
  76. KDFParams map[string]interface{} `json:"kdfparams"`
  77. MAC string `json:"mac"`
  78. }
  79. type cipherparamsJSON struct {
  80. IV string `json:"iv"`
  81. }
  82. type scryptParamsJSON struct {
  83. N int `json:"n"`
  84. R int `json:"r"`
  85. P int `json:"p"`
  86. DkLen int `json:"dklen"`
  87. Salt string `json:"salt"`
  88. }
  89. func (k *Key) MarshalJSON() (j []byte, err error) {
  90. jStruct := plainKeyJSON{
  91. hex.EncodeToString(k.Address[:]),
  92. hex.EncodeToString(crypto.FromECDSA(k.PrivateKey)),
  93. k.Id.String(),
  94. version,
  95. }
  96. j, err = json.Marshal(jStruct)
  97. return j, err
  98. }
  99. func (k *Key) UnmarshalJSON(j []byte) (err error) {
  100. keyJSON := new(plainKeyJSON)
  101. err = json.Unmarshal(j, &keyJSON)
  102. if err != nil {
  103. return err
  104. }
  105. u := new(uuid.UUID)
  106. *u = uuid.Parse(keyJSON.Id)
  107. k.Id = *u
  108. addr, err := hex.DecodeString(keyJSON.Address)
  109. if err != nil {
  110. return err
  111. }
  112. privkey, err := hex.DecodeString(keyJSON.PrivateKey)
  113. if err != nil {
  114. return err
  115. }
  116. k.Address = common.BytesToAddress(addr)
  117. k.PrivateKey = crypto.ToECDSA(privkey)
  118. return nil
  119. }
  120. func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
  121. id := uuid.NewRandom()
  122. key := &Key{
  123. Id: id,
  124. Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
  125. PrivateKey: privateKeyECDSA,
  126. }
  127. return key
  128. }
  129. // NewKeyForDirectICAP generates a key whose address fits into < 155 bits so it can fit
  130. // into the Direct ICAP spec. for simplicity and easier compatibility with other libs, we
  131. // retry until the first byte is 0.
  132. func NewKeyForDirectICAP(rand io.Reader) *Key {
  133. randBytes := make([]byte, 64)
  134. _, err := rand.Read(randBytes)
  135. if err != nil {
  136. panic("key generation: could not read from random source: " + err.Error())
  137. }
  138. reader := bytes.NewReader(randBytes)
  139. privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), reader)
  140. if err != nil {
  141. panic("key generation: ecdsa.GenerateKey failed: " + err.Error())
  142. }
  143. key := newKeyFromECDSA(privateKeyECDSA)
  144. if !strings.HasPrefix(key.Address.Hex(), "0x00") {
  145. return NewKeyForDirectICAP(rand)
  146. }
  147. return key
  148. }
  149. func newKey(rand io.Reader) (*Key, error) {
  150. privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return newKeyFromECDSA(privateKeyECDSA), nil
  155. }
  156. func storeNewKey(ks keyStore, rand io.Reader, auth string) (*Key, accounts.Account, error) {
  157. key, err := newKey(rand)
  158. if err != nil {
  159. return nil, accounts.Account{}, err
  160. }
  161. a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.JoinPath(keyFileName(key.Address))}}
  162. if err := ks.StoreKey(a.URL.Path, key, auth); err != nil {
  163. zeroKey(key.PrivateKey)
  164. return nil, a, err
  165. }
  166. return key, a, err
  167. }
  168. func writeKeyFile(file string, content []byte) error {
  169. // Create the keystore directory with appropriate permissions
  170. // in case it is not present yet.
  171. const dirPerm = 0700
  172. if err := os.MkdirAll(filepath.Dir(file), dirPerm); err != nil {
  173. return err
  174. }
  175. // Atomic write: create a temporary hidden file first
  176. // then move it into place. TempFile assigns mode 0600.
  177. f, err := ioutil.TempFile(filepath.Dir(file), "."+filepath.Base(file)+".tmp")
  178. if err != nil {
  179. return err
  180. }
  181. if _, err := f.Write(content); err != nil {
  182. f.Close()
  183. os.Remove(f.Name())
  184. return err
  185. }
  186. f.Close()
  187. return os.Rename(f.Name(), file)
  188. }
  189. // keyFileName implements the naming convention for keyfiles:
  190. // UTC--<created_at UTC ISO8601>-<address hex>
  191. func keyFileName(keyAddr common.Address) string {
  192. ts := time.Now().UTC()
  193. return fmt.Sprintf("UTC--%s--%s", toISO8601(ts), hex.EncodeToString(keyAddr[:]))
  194. }
  195. func toISO8601(t time.Time) string {
  196. var tz string
  197. name, offset := t.Zone()
  198. if name == "UTC" {
  199. tz = "Z"
  200. } else {
  201. tz = fmt.Sprintf("%03d00", offset/3600)
  202. }
  203. 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)
  204. }