key.go 6.4 KB

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