github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/accounts/keystore/key.go (about)

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