github.com/halybang/go-ethereum@v1.0.5-0.20180325041310-3b262bc1367c/accounts/keystore/keystore.go (about) 1 // Copyright 2018 Wanchain Foundation Ltd 2 // Copyright 2017 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum 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-ethereum 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-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 18 // Package keystore implements encrypted storage of secp256k1 private keys. 19 // 20 // Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification. 21 // See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information. 22 package keystore 23 24 import ( 25 "crypto/ecdsa" 26 crand "crypto/rand" 27 "errors" 28 "fmt" 29 "math/big" 30 "os" 31 "path/filepath" 32 "reflect" 33 "runtime" 34 "sync" 35 "time" 36 37 "github.com/wanchain/go-wanchain/accounts" 38 "github.com/wanchain/go-wanchain/common" 39 "github.com/wanchain/go-wanchain/common/hexutil" 40 "github.com/wanchain/go-wanchain/core/types" 41 "github.com/wanchain/go-wanchain/crypto" 42 "github.com/wanchain/go-wanchain/event" 43 ) 44 45 var ( 46 ErrLocked = accounts.NewAuthNeededError("password or unlock") 47 ErrNoMatch = errors.New("no key for given address or file") 48 ErrDecrypt = errors.New("could not decrypt key with given passphrase") 49 ) 50 51 // KeyStoreType is the reflect type of a keystore backend. 52 var KeyStoreType = reflect.TypeOf(&KeyStore{}) 53 54 // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs. 55 var KeyStoreScheme = "keystore" 56 57 // Maximum time between wallet refreshes (if filesystem notifications don't work). 58 const walletRefreshCycle = 3 * time.Second 59 60 // KeyStore manages a key storage directory on disk. 61 type KeyStore struct { 62 storage keyStore // Storage backend, might be cleartext or encrypted 63 cache *accountCache // In-memory account cache over the filesystem storage 64 changes chan struct{} // Channel receiving change notifications from the cache 65 unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys) 66 67 wallets []accounts.Wallet // Wallet wrappers around the individual key files 68 updateFeed event.Feed // Event feed to notify wallet additions/removals 69 updateScope event.SubscriptionScope // Subscription scope tracking current live listeners 70 updating bool // Whether the event notification loop is running 71 72 mu sync.RWMutex 73 } 74 75 type unlocked struct { 76 *Key 77 abort chan struct{} 78 } 79 80 // NewKeyStore creates a keystore for the given directory. 81 func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore { 82 keydir, _ = filepath.Abs(keydir) 83 ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP}} 84 ks.init(keydir) 85 return ks 86 } 87 88 // NewPlaintextKeyStore creates a keystore for the given directory. 89 // Deprecated: Use NewKeyStore. 90 func NewPlaintextKeyStore(keydir string) *KeyStore { 91 keydir, _ = filepath.Abs(keydir) 92 ks := &KeyStore{storage: &keyStorePlain{keydir}} 93 ks.init(keydir) 94 return ks 95 } 96 97 func (ks *KeyStore) init(keydir string) { 98 // Lock the mutex since the account cache might call back with events 99 ks.mu.Lock() 100 defer ks.mu.Unlock() 101 102 // Initialize the set of unlocked keys and the account cache 103 ks.unlocked = make(map[common.Address]*unlocked) 104 ks.cache, ks.changes = newAccountCache(keydir) 105 106 // TODO: In order for this finalizer to work, there must be no references 107 // to ks. addressCache doesn't keep a reference but unlocked keys do, 108 // so the finalizer will not trigger until all timed unlocks have expired. 109 runtime.SetFinalizer(ks, func(m *KeyStore) { 110 m.cache.close() 111 }) 112 // Create the initial list of wallets from the cache 113 accs := ks.cache.accounts() 114 ks.wallets = make([]accounts.Wallet, len(accs)) 115 for i := 0; i < len(accs); i++ { 116 ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks} 117 } 118 } 119 120 // Wallets implements accounts.Backend, returning all single-key wallets from the 121 // keystore directory. 122 func (ks *KeyStore) Wallets() []accounts.Wallet { 123 // Make sure the list of wallets is in sync with the account cache 124 ks.refreshWallets() 125 126 ks.mu.RLock() 127 defer ks.mu.RUnlock() 128 129 cpy := make([]accounts.Wallet, len(ks.wallets)) 130 copy(cpy, ks.wallets) 131 return cpy 132 } 133 134 // refreshWallets retrieves the current account list and based on that does any 135 // necessary wallet refreshes. 136 func (ks *KeyStore) refreshWallets() { 137 // Retrieve the current list of accounts 138 ks.mu.Lock() 139 accs := ks.cache.accounts() 140 141 // Transform the current list of wallets into the new one 142 wallets := make([]accounts.Wallet, 0, len(accs)) 143 events := []accounts.WalletEvent{} 144 145 for _, account := range accs { 146 // Drop wallets while they were in front of the next account 147 for len(ks.wallets) > 0 && ks.wallets[0].URL().Cmp(account.URL) < 0 { 148 events = append(events, accounts.WalletEvent{Wallet: ks.wallets[0], Kind: accounts.WalletDropped}) 149 ks.wallets = ks.wallets[1:] 150 } 151 // If there are no more wallets or the account is before the next, wrap new wallet 152 if len(ks.wallets) == 0 || ks.wallets[0].URL().Cmp(account.URL) > 0 { 153 wallet := &keystoreWallet{account: account, keystore: ks} 154 155 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived}) 156 wallets = append(wallets, wallet) 157 continue 158 } 159 // If the account is the same as the first wallet, keep it 160 if ks.wallets[0].Accounts()[0] == account { 161 wallets = append(wallets, ks.wallets[0]) 162 ks.wallets = ks.wallets[1:] 163 continue 164 } 165 } 166 // Drop any leftover wallets and set the new batch 167 for _, wallet := range ks.wallets { 168 events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped}) 169 } 170 ks.wallets = wallets 171 ks.mu.Unlock() 172 173 // Fire all wallet events and return 174 for _, event := range events { 175 ks.updateFeed.Send(event) 176 } 177 } 178 179 // Subscribe implements accounts.Backend, creating an async subscription to 180 // receive notifications on the addition or removal of keystore wallets. 181 func (ks *KeyStore) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription { 182 // We need the mutex to reliably start/stop the update loop 183 ks.mu.Lock() 184 defer ks.mu.Unlock() 185 186 // Subscribe the caller and track the subscriber count 187 sub := ks.updateScope.Track(ks.updateFeed.Subscribe(sink)) 188 189 // Subscribers require an active notification loop, start it 190 if !ks.updating { 191 ks.updating = true 192 go ks.updater() 193 } 194 return sub 195 } 196 197 // updater is responsible for maintaining an up-to-date list of wallets stored in 198 // the keystore, and for firing wallet addition/removal events. It listens for 199 // account change events from the underlying account cache, and also periodically 200 // forces a manual refresh (only triggers for systems where the filesystem notifier 201 // is not running). 202 func (ks *KeyStore) updater() { 203 for { 204 // Wait for an account update or a refresh timeout 205 select { 206 case <-ks.changes: 207 case <-time.After(walletRefreshCycle): 208 } 209 // Run the wallet refresher 210 ks.refreshWallets() 211 212 // If all our subscribers left, stop the updater 213 ks.mu.Lock() 214 if ks.updateScope.Count() == 0 { 215 ks.updating = false 216 ks.mu.Unlock() 217 return 218 } 219 ks.mu.Unlock() 220 } 221 } 222 223 // HasAddress reports whether a key with the given address is present. 224 func (ks *KeyStore) HasAddress(addr common.Address) bool { 225 return ks.cache.hasAddress(addr) 226 } 227 228 // Accounts returns all key files present in the directory. 229 func (ks *KeyStore) Accounts() []accounts.Account { 230 return ks.cache.accounts() 231 } 232 233 // Delete deletes the key matched by account if the passphrase is correct. 234 // If the account contains no filename, the address must match a unique key. 235 func (ks *KeyStore) Delete(a accounts.Account, passphrase string) error { 236 // Decrypting the key isn't really necessary, but we do 237 // it anyway to check the password and zero out the key 238 // immediately afterwards. 239 a, key, err := ks.getDecryptedKey(a, passphrase) 240 if key != nil { 241 zeroKey(key.PrivateKey) 242 } 243 if err != nil { 244 return err 245 } 246 // The order is crucial here. The key is dropped from the 247 // cache after the file is gone so that a reload happening in 248 // between won't insert it into the cache again. 249 err = os.Remove(a.URL.Path) 250 if err == nil { 251 ks.cache.delete(a) 252 ks.refreshWallets() 253 } 254 return err 255 } 256 257 // SignHash calculates a ECDSA signature for the given hash. The produced 258 // signature is in the [R || S || V] format where V is 0 or 1. 259 func (ks *KeyStore) SignHash(a accounts.Account, hash []byte) ([]byte, error) { 260 // Look up the key to sign with and abort if it cannot be found 261 ks.mu.RLock() 262 defer ks.mu.RUnlock() 263 264 unlockedKey, found := ks.unlocked[a.Address] 265 if !found { 266 return nil, ErrLocked 267 } 268 // Sign the hash using plain ECDSA operations 269 return crypto.Sign(hash, unlockedKey.PrivateKey) 270 } 271 272 // SignTx signs the given transaction with the requested account. 273 func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 274 // Look up the key to sign with and abort if it cannot be found 275 ks.mu.RLock() 276 defer ks.mu.RUnlock() 277 278 unlockedKey, found := ks.unlocked[a.Address] 279 if !found { 280 return nil, ErrLocked 281 } 282 // Depending on the presence of the chain ID, sign with EIP155 or homestead 283 if chainID != nil { 284 return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey) 285 } 286 return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey) 287 } 288 289 func (ks *KeyStore) ComputeOTAPPKeys(a accounts.Account, AX, AY, BX, BY string) ([]string, error) { 290 ks.mu.RLock() 291 defer ks.mu.RUnlock() 292 293 unlockedKey, found := ks.unlocked[a.Address] 294 if !found { 295 return nil, ErrLocked 296 } 297 298 pub1, priv1, priv2, err := crypto.GenerteOTAPrivateKey(unlockedKey.PrivateKey, unlockedKey.PrivateKey2, AX, AY, BX, BY) 299 300 pub1X := hexutil.Encode(common.LeftPadBytes(pub1.X.Bytes(), 32)) 301 pub1Y := hexutil.Encode(common.LeftPadBytes(pub1.Y.Bytes(), 32)) 302 priv1D := hexutil.Encode(common.LeftPadBytes(priv1.D.Bytes(), 32)) 303 priv2D := hexutil.Encode(common.LeftPadBytes(priv2.D.Bytes(), 32)) 304 305 return []string{pub1X, pub1Y, priv1D, priv2D}, err 306 } 307 308 // SignHashWithPassphrase signs hash if the private key matching the given address 309 // can be decrypted with the given passphrase. The produced signature is in the 310 // [R || S || V] format where V is 0 or 1. 311 func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) { 312 _, key, err := ks.getDecryptedKey(a, passphrase) 313 if err != nil { 314 return nil, err 315 } 316 defer zeroKey(key.PrivateKey) 317 return crypto.Sign(hash, key.PrivateKey) 318 } 319 320 // SignTxWithPassphrase signs the transaction if the private key matching the 321 // given address can be decrypted with the given passphrase. 322 func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 323 _, key, err := ks.getDecryptedKey(a, passphrase) 324 if err != nil { 325 return nil, err 326 } 327 defer zeroKey(key.PrivateKey) 328 329 // Depending on the presence of the chain ID, sign with EIP155 or homestead 330 if chainID != nil { 331 return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey) 332 } 333 return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey) 334 } 335 336 // Unlock unlocks the given account indefinitely. 337 func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error { 338 return ks.TimedUnlock(a, passphrase, 0) 339 } 340 341 // Lock removes the private key with the given address from memory. 342 func (ks *KeyStore) Lock(addr common.Address) error { 343 ks.mu.Lock() 344 if unl, found := ks.unlocked[addr]; found { 345 ks.mu.Unlock() 346 ks.expire(addr, unl, time.Duration(0)*time.Nanosecond) 347 } else { 348 ks.mu.Unlock() 349 } 350 return nil 351 } 352 353 // TimedUnlock unlocks the given account with the passphrase. The account 354 // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account 355 // until the program exits. The account must match a unique key file. 356 // 357 // If the account address is already unlocked for a duration, TimedUnlock extends or 358 // shortens the active unlock timeout. If the address was previously unlocked 359 // indefinitely the timeout is not altered. 360 func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error { 361 a, key, err := ks.getDecryptedKey(a, passphrase) 362 if err != nil { 363 return err 364 } 365 366 ks.mu.Lock() 367 defer ks.mu.Unlock() 368 u, found := ks.unlocked[a.Address] 369 if found { 370 if u.abort == nil { 371 // The address was unlocked indefinitely, so unlocking 372 // it with a timeout would be confusing. 373 zeroKey(key.PrivateKey) 374 return nil 375 } 376 // Terminate the expire goroutine and replace it below. 377 close(u.abort) 378 } 379 if timeout > 0 { 380 u = &unlocked{Key: key, abort: make(chan struct{})} 381 go ks.expire(a.Address, u, timeout) 382 } else { 383 u = &unlocked{Key: key} 384 } 385 ks.unlocked[a.Address] = u 386 return nil 387 } 388 389 // Find resolves the given account into a unique entry in the keystore. 390 func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) { 391 ks.cache.maybeReload() 392 ks.cache.mu.Lock() 393 a, err := ks.cache.find(a) 394 ks.cache.mu.Unlock() 395 return a, err 396 } 397 398 func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) { 399 a, err := ks.Find(a) 400 if err != nil { 401 return a, nil, err 402 } 403 key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth) 404 return a, key, err 405 } 406 407 // getEncryptedKey loads an encrypted keyfile from the disk 408 func (ks *KeyStore) getEncryptedKey(a accounts.Account) (accounts.Account, *Key, error) { 409 a, err := ks.Find(a) 410 if err != nil { 411 return a, nil, err 412 } 413 key, err := ks.storage.GetEncryptedKey(a.Address, a.URL.Path) 414 if err != nil { 415 return a, nil, err 416 } 417 return a, key, nil 418 419 } 420 421 func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) { 422 t := time.NewTimer(timeout) 423 defer t.Stop() 424 select { 425 case <-u.abort: 426 // just quit 427 case <-t.C: 428 ks.mu.Lock() 429 // only drop if it's still the same key instance that dropLater 430 // was launched with. we can check that using pointer equality 431 // because the map stores a new pointer every time the key is 432 // unlocked. 433 if ks.unlocked[addr] == u { 434 zeroKey(u.PrivateKey) 435 delete(ks.unlocked, addr) 436 } 437 ks.mu.Unlock() 438 } 439 } 440 441 // NewAccount generates a new key and stores it into the key directory, 442 // encrypting it with the passphrase. 443 func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) { 444 _, account, err := storeNewKey(ks.storage, crand.Reader, passphrase) 445 if err != nil { 446 return accounts.Account{}, err 447 } 448 // Add the account to the cache immediately rather 449 // than waiting for file system notifications to pick it up. 450 ks.cache.add(account) 451 ks.refreshWallets() 452 return account, nil 453 } 454 455 // Export exports as a JSON key, encrypted with newPassphrase. 456 func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) { 457 _, key, err := ks.getDecryptedKey(a, passphrase) 458 if err != nil { 459 return nil, err 460 } 461 var N, P int 462 if store, ok := ks.storage.(*keyStorePassphrase); ok { 463 N, P = store.scryptN, store.scryptP 464 } else { 465 N, P = StandardScryptN, StandardScryptP 466 } 467 return EncryptKey(key, newPassphrase, N, P) 468 } 469 470 // Import stores the given encrypted JSON key into the key directory. 471 func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) { 472 key, err := DecryptKey(keyJSON, passphrase) 473 if key != nil && key.PrivateKey != nil { 474 defer zeroKey(key.PrivateKey) 475 } 476 if err != nil { 477 return accounts.Account{}, err 478 } 479 return ks.importKey(key, newPassphrase) 480 } 481 482 // func (ks *KeyStore) ExportECDSA(a accounts.Account, passphrase string) ([]byte, []byte, error) { 483 // _, key, err := ks.getDecryptedKey(a, passphrase) 484 // if err != nil { 485 // return nil, nil, err 486 // } 487 // return crypto.FromECDSA(key.PrivateKey), crypto.FromECDSA(key.PrivateKey2), err 488 // } 489 490 // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase. 491 func (ks *KeyStore) ImportECDSA(priv1, priv2 *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) { 492 key := newKeyFromECDSA(priv1, priv2) 493 if ks.cache.hasAddress(key.Address) { 494 return accounts.Account{}, fmt.Errorf("account already exists") 495 } 496 return ks.importKey(key, passphrase) 497 } 498 499 func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) { 500 a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}} 501 if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil { 502 return accounts.Account{}, err 503 } 504 ks.cache.add(a) 505 ks.refreshWallets() 506 return a, nil 507 } 508 509 // Update transitions an account from a previous format to the current one, also providing the possibility to change the pass-phrase 510 func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error { 511 a, key, err := ks.getDecryptedKey(a, passphrase) 512 if err != nil { 513 return err 514 } 515 if key.PrivateKey2 == nil { 516 sk2, err := crypto.GenerateKey() 517 if err != nil { 518 return err 519 } 520 key.PrivateKey2 = sk2 521 } 522 updateWaddress(key) 523 return ks.storage.StoreKey(a.URL.Path, key, newPassphrase) 524 } 525 526 // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores 527 // a key file in the key directory. The key file is encrypted with the same passphrase. 528 func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) { 529 a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase) 530 if err != nil { 531 return a, err 532 } 533 ks.cache.add(a) 534 ks.refreshWallets() 535 return a, nil 536 } 537 538 // GetWanAddress represents the keystore to retrieve corresponding wanchain public address for a specific ordinary account/address 539 func (ks *KeyStore) GetWanAddress(account accounts.Account) (common.WAddress, error) { 540 ks.mu.RLock() 541 defer ks.mu.RUnlock() 542 543 unlockedKey, found := ks.unlocked[account.Address] 544 if !found { 545 _, ksen, err := ks.getEncryptedKey(account) 546 if err != nil { 547 return common.WAddress{}, ErrLocked 548 } 549 return ksen.WAddress, nil 550 } 551 552 ret := unlockedKey.WAddress 553 return ret, nil 554 } 555 556 // zeroKey zeroes a private key in memory. 557 func zeroKey(k *ecdsa.PrivateKey) { 558 if k == nil { 559 return 560 } 561 562 b := k.D.Bits() 563 for i := range b { 564 b[i] = 0 565 } 566 }