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