key.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/google/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. func (k *Key) MarshalJSON() (j []byte, err error) {
  83. jStruct := plainKeyJSON{
  84. hex.EncodeToString(k.Address[:]),
  85. hex.EncodeToString(crypto.FromECDSA(k.PrivateKey)),
  86. k.Id.String(),
  87. version,
  88. }
  89. j, err = json.Marshal(jStruct)
  90. return j, err
  91. }
  92. func (k *Key) UnmarshalJSON(j []byte) (err error) {
  93. keyJSON := new(plainKeyJSON)
  94. err = json.Unmarshal(j, &keyJSON)
  95. if err != nil {
  96. return err
  97. }
  98. u := new(uuid.UUID)
  99. *u, err = uuid.Parse(keyJSON.Id)
  100. if err != nil {
  101. return err
  102. }
  103. k.Id = *u
  104. addr, err := hex.DecodeString(keyJSON.Address)
  105. if err != nil {
  106. return err
  107. }
  108. privkey, err := crypto.HexToECDSA(keyJSON.PrivateKey)
  109. if err != nil {
  110. return err
  111. }
  112. k.Address = common.BytesToAddress(addr)
  113. k.PrivateKey = privkey
  114. return nil
  115. }
  116. func newKeyFromECDSA(privateKeyECDSA *ecdsa.PrivateKey) *Key {
  117. id, err := uuid.NewRandom()
  118. if err != nil {
  119. panic(fmt.Sprintf("Could not create random uuid: %v", err))
  120. }
  121. key := &Key{
  122. Id: id,
  123. Address: crypto.PubkeyToAddress(privateKeyECDSA.PublicKey),
  124. PrivateKey: privateKeyECDSA,
  125. }
  126. return key
  127. }
  128. // NewKeyForDirectICAP generates a key whose address fits into < 155 bits so it can fit
  129. // into the Direct ICAP spec. for simplicity and easier compatibility with other libs, we
  130. // retry until the first byte is 0.
  131. func NewKeyForDirectICAP(rand io.Reader) *Key {
  132. randBytes := make([]byte, 64)
  133. _, err := rand.Read(randBytes)
  134. if err != nil {
  135. panic("key generation: could not read from random source: " + err.Error())
  136. }
  137. reader := bytes.NewReader(randBytes)
  138. privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), reader)
  139. if err != nil {
  140. panic("key generation: ecdsa.GenerateKey failed: " + err.Error())
  141. }
  142. key := newKeyFromECDSA(privateKeyECDSA)
  143. if !strings.HasPrefix(key.Address.Hex(), "0x00") {
  144. return NewKeyForDirectICAP(rand)
  145. }
  146. return key
  147. }
  148. func newKey(rand io.Reader) (*Key, error) {
  149. privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), rand)
  150. if err != nil {
  151. return nil, err
  152. }
  153. return newKeyFromECDSA(privateKeyECDSA), nil
  154. }
  155. func storeNewKey(ks keyStore, rand io.Reader, auth string) (*Key, accounts.Account, error) {
  156. key, err := newKey(rand)
  157. if err != nil {
  158. return nil, accounts.Account{}, err
  159. }
  160. a := accounts.Account{
  161. Address: key.Address,
  162. URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.JoinPath(keyFileName(key.Address))},
  163. }
  164. if err := ks.StoreKey(a.URL.Path, key, auth); err != nil {
  165. zeroKey(key.PrivateKey)
  166. return nil, a, err
  167. }
  168. return key, a, err
  169. }
  170. func writeTemporaryKeyFile(file string, content []byte) (string, error) {
  171. // Create the keystore directory with appropriate permissions
  172. // in case it is not present yet.
  173. const dirPerm = 0700
  174. if err := os.MkdirAll(filepath.Dir(file), dirPerm); err != nil {
  175. return "", err
  176. }
  177. // Atomic write: create a temporary hidden file first
  178. // then move it into place. TempFile assigns mode 0600.
  179. f, err := ioutil.TempFile(filepath.Dir(file), "."+filepath.Base(file)+".tmp")
  180. if err != nil {
  181. return "", err
  182. }
  183. if _, err := f.Write(content); err != nil {
  184. f.Close()
  185. os.Remove(f.Name())
  186. return "", err
  187. }
  188. f.Close()
  189. return f.Name(), nil
  190. }
  191. func writeKeyFile(file string, content []byte) error {
  192. name, err := writeTemporaryKeyFile(file, content)
  193. if err != nil {
  194. return err
  195. }
  196. return os.Rename(name, file)
  197. }
  198. // keyFileName implements the naming convention for keyfiles:
  199. // UTC--<created_at UTC ISO8601>-<address hex>
  200. func keyFileName(keyAddr common.Address) string {
  201. ts := time.Now().UTC()
  202. return fmt.Sprintf("UTC--%s--%s", toISO8601(ts), hex.EncodeToString(keyAddr[:]))
  203. }
  204. func toISO8601(t time.Time) string {
  205. var tz string
  206. name, offset := t.Zone()
  207. if name == "UTC" {
  208. tz = "Z"
  209. } else {
  210. tz = fmt.Sprintf("%03d00", offset/3600)
  211. }
  212. return fmt.Sprintf("%04d-%02d-%02dT%02d-%02d-%02d.%09d%s",
  213. t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), tz)
  214. }