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