github.com/cranelv/ethereum_mpc@v0.0.0-20191031014521-23aeb1415092/accounts/keystore/key.go (about)

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