github.com/simplechain-org/go-simplechain@v1.0.6/accounts/keystore/keystore.go (about) 1 // Copyright 2017 The go-simplechain Authors 2 // This file is part of the go-simplechain library. 3 // 4 // The go-simplechain 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-simplechain 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-simplechain library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package keystore implements encrypted storage of secp256k1 private keys. 18 // 19 // Keys are stored as encrypted JSON files according to the Web3 Secret Storage specification. 20 // See https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition for more information. 21 package keystore 22 23 import ( 24 "crypto/ecdsa" 25 crand "crypto/rand" 26 "errors" 27 "fmt" 28 "math/big" 29 "os" 30 "path/filepath" 31 "reflect" 32 "runtime" 33 "sync" 34 "time" 35 36 "github.com/simplechain-org/go-simplechain/accounts" 37 "github.com/simplechain-org/go-simplechain/common" 38 "github.com/simplechain-org/go-simplechain/core/types" 39 "github.com/simplechain-org/go-simplechain/crypto" 40 "github.com/simplechain-org/go-simplechain/event" 41 ) 42 43 var ( 44 ErrLocked = accounts.NewAuthNeededError("password or unlock") 45 ErrNoMatch = errors.New("no key for given address or file") 46 ErrDecrypt = errors.New("could not decrypt key with given password") 47 ) 48 49 // KeyStoreType is the reflect type of a keystore backend. 50 var KeyStoreType = reflect.TypeOf(&KeyStore{}) 51 52 // KeyStoreScheme is the protocol scheme prefixing account and wallet URLs. 53 const KeyStoreScheme = "keystore" 54 55 // Maximum time between wallet refreshes (if filesystem notifications don't work). 56 const walletRefreshCycle = 3 * time.Second 57 58 // KeyStore manages a key storage directory on disk. 59 type KeyStore struct { 60 storage keyStore // Storage backend, might be cleartext or encrypted 61 cache *accountCache // In-memory account cache over the filesystem storage 62 changes chan struct{} // Channel receiving change notifications from the cache 63 unlocked map[common.Address]*unlocked // Currently unlocked account (decrypted private keys) 64 65 wallets []accounts.Wallet // Wallet wrappers around the individual key files 66 updateFeed event.Feed // Event feed to notify wallet additions/removals 67 updateScope event.SubscriptionScope // Subscription scope tracking current live listeners 68 updating bool // Whether the event notification loop is running 69 70 mu sync.RWMutex 71 } 72 73 type unlocked struct { 74 *Key 75 abort chan struct{} 76 } 77 78 // NewKeyStore creates a keystore for the given directory. 79 func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore { 80 keydir, _ = filepath.Abs(keydir) 81 ks := &KeyStore{storage: &keyStorePassphrase{keydir, scryptN, scryptP, false}} 82 ks.init(keydir) 83 return ks 84 } 85 86 // NewPlaintextKeyStore creates a keystore for the given directory. 87 // Deprecated: Use NewKeyStore. 88 func NewPlaintextKeyStore(keydir string) *KeyStore { 89 keydir, _ = filepath.Abs(keydir) 90 ks := &KeyStore{storage: &keyStorePlain{keydir}} 91 ks.init(keydir) 92 return ks 93 } 94 95 func (ks *KeyStore) init(keydir string) { 96 // Lock the mutex since the account cache might call back with events 97 ks.mu.Lock() 98 defer ks.mu.Unlock() 99 100 // Initialize the set of unlocked keys and the account cache 101 ks.unlocked = make(map[common.Address]*unlocked) 102 ks.cache, ks.changes = newAccountCache(keydir) 103 104 // TODO: In order for this finalizer to work, there must be no references 105 // to ks. addressCache doesn't keep a reference but unlocked keys do, 106 // so the finalizer will not trigger until all timed unlocks have expired. 107 runtime.SetFinalizer(ks, func(m *KeyStore) { 108 m.cache.close() 109 }) 110 // Create the initial list of wallets from the cache 111 accs := ks.cache.accounts() 112 ks.wallets = make([]accounts.Wallet, len(accs)) 113 for i := 0; i < len(accs); i++ { 114 ks.wallets[i] = &keystoreWallet{account: accs[i], keystore: ks} 115 } 116 } 117 118 // Wallets implements accounts.Backend, returning all single-key wallets from the 119 // keystore directory. 120 func (ks *KeyStore) Wallets() []accounts.Wallet { 121 // Make sure the list of wallets is in sync with the account cache 122 ks.refreshWallets() 123 124 ks.mu.RLock() 125 defer ks.mu.RUnlock() 126 127 cpy := make([]accounts.Wallet, len(ks.wallets)) 128 copy(cpy, ks.wallets) 129 return cpy 130 } 131 132 // refreshWallets retrieves the current account list and based on that does any 133 // necessary wallet refreshes. 134 func (ks *KeyStore) refreshWallets() { 135 // Retrieve the current list of accounts 136 ks.mu.Lock() 137 accs := ks.cache.accounts() 138 139 // Transform the current list of wallets into the new one 140 var ( 141 wallets = make([]accounts.Wallet, 0, len(accs)) 142 events []accounts.WalletEvent 143 ) 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 269 // Sign the hash using plain ECDSA operations 270 return crypto.Sign(hash, unlockedKey.PrivateKey) 271 } 272 273 // SignTx signs the given transaction with the requested account. 274 func (ks *KeyStore) SignTx(a accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 275 // Look up the key to sign with and abort if it cannot be found 276 ks.mu.RLock() 277 defer ks.mu.RUnlock() 278 279 unlockedKey, found := ks.unlocked[a.Address] 280 if !found { 281 return nil, ErrLocked 282 } 283 // Depending on the presence of the chain ID, sign with EIP155 or homestead 284 if chainID != nil { 285 return types.SignTx(tx, types.NewEIP155Signer(chainID), unlockedKey.PrivateKey) 286 } 287 return types.SignTx(tx, types.HomesteadSigner{}, unlockedKey.PrivateKey) 288 } 289 290 // SignHashWithPassphrase signs hash if the private key matching the given address 291 // can be decrypted with the given passphrase. The produced signature is in the 292 // [R || S || V] format where V is 0 or 1. 293 func (ks *KeyStore) SignHashWithPassphrase(a accounts.Account, passphrase string, hash []byte) (signature []byte, err error) { 294 _, key, err := ks.getDecryptedKey(a, passphrase) 295 if err != nil { 296 return nil, err 297 } 298 defer zeroKey(key.PrivateKey) 299 return crypto.Sign(hash, key.PrivateKey) 300 } 301 302 // SignTxWithPassphrase signs the transaction if the private key matching the 303 // given address can be decrypted with the given passphrase. 304 func (ks *KeyStore) SignTxWithPassphrase(a accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { 305 _, key, err := ks.getDecryptedKey(a, passphrase) 306 if err != nil { 307 return nil, err 308 } 309 defer zeroKey(key.PrivateKey) 310 311 // Depending on the presence of the chain ID, sign with EIP155 or homestead 312 if chainID != nil { 313 return types.SignTx(tx, types.NewEIP155Signer(chainID), key.PrivateKey) 314 } 315 return types.SignTx(tx, types.HomesteadSigner{}, key.PrivateKey) 316 } 317 318 // Unlock unlocks the given account indefinitely. 319 func (ks *KeyStore) Unlock(a accounts.Account, passphrase string) error { 320 return ks.TimedUnlock(a, passphrase, 0) 321 } 322 323 // Lock removes the private key with the given address from memory. 324 func (ks *KeyStore) Lock(addr common.Address) error { 325 ks.mu.Lock() 326 if unl, found := ks.unlocked[addr]; found { 327 ks.mu.Unlock() 328 ks.expire(addr, unl, time.Duration(0)*time.Nanosecond) 329 } else { 330 ks.mu.Unlock() 331 } 332 return nil 333 } 334 335 // TimedUnlock unlocks the given account with the passphrase. The account 336 // stays unlocked for the duration of timeout. A timeout of 0 unlocks the account 337 // until the program exits. The account must match a unique key file. 338 // 339 // If the account address is already unlocked for a duration, TimedUnlock extends or 340 // shortens the active unlock timeout. If the address was previously unlocked 341 // indefinitely the timeout is not altered. 342 func (ks *KeyStore) TimedUnlock(a accounts.Account, passphrase string, timeout time.Duration) error { 343 a, key, err := ks.getDecryptedKey(a, passphrase) 344 if err != nil { 345 return err 346 } 347 348 ks.mu.Lock() 349 defer ks.mu.Unlock() 350 u, found := ks.unlocked[a.Address] 351 if found { 352 if u.abort == nil { 353 // The address was unlocked indefinitely, so unlocking 354 // it with a timeout would be confusing. 355 zeroKey(key.PrivateKey) 356 return nil 357 } 358 // Terminate the expire goroutine and replace it below. 359 close(u.abort) 360 } 361 if timeout > 0 { 362 u = &unlocked{Key: key, abort: make(chan struct{})} 363 go ks.expire(a.Address, u, timeout) 364 } else { 365 u = &unlocked{Key: key} 366 } 367 ks.unlocked[a.Address] = u 368 return nil 369 } 370 371 // Find resolves the given account into a unique entry in the keystore. 372 func (ks *KeyStore) Find(a accounts.Account) (accounts.Account, error) { 373 ks.cache.maybeReload() 374 ks.cache.mu.Lock() 375 a, err := ks.cache.find(a) 376 ks.cache.mu.Unlock() 377 return a, err 378 } 379 380 func (ks *KeyStore) getDecryptedKey(a accounts.Account, auth string) (accounts.Account, *Key, error) { 381 a, err := ks.Find(a) 382 if err != nil { 383 return a, nil, err 384 } 385 key, err := ks.storage.GetKey(a.Address, a.URL.Path, auth) 386 return a, key, err 387 } 388 389 func (ks *KeyStore) expire(addr common.Address, u *unlocked, timeout time.Duration) { 390 t := time.NewTimer(timeout) 391 defer t.Stop() 392 select { 393 case <-u.abort: 394 // just quit 395 case <-t.C: 396 ks.mu.Lock() 397 // only drop if it's still the same key instance that dropLater 398 // was launched with. we can check that using pointer equality 399 // because the map stores a new pointer every time the key is 400 // unlocked. 401 if ks.unlocked[addr] == u { 402 zeroKey(u.PrivateKey) 403 delete(ks.unlocked, addr) 404 } 405 ks.mu.Unlock() 406 } 407 } 408 409 // NewAccount generates a new key and stores it into the key directory, 410 // encrypting it with the passphrase. 411 func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) { 412 _, account, err := storeNewKey(ks.storage, crand.Reader, passphrase) 413 if err != nil { 414 return accounts.Account{}, err 415 } 416 // Add the account to the cache immediately rather 417 // than waiting for file system notifications to pick it up. 418 ks.cache.add(account) 419 ks.refreshWallets() 420 return account, nil 421 } 422 423 // Export exports as a JSON key, encrypted with newPassphrase. 424 func (ks *KeyStore) Export(a accounts.Account, passphrase, newPassphrase string) (keyJSON []byte, err error) { 425 _, key, err := ks.getDecryptedKey(a, passphrase) 426 if err != nil { 427 return nil, err 428 } 429 var N, P int 430 if store, ok := ks.storage.(*keyStorePassphrase); ok { 431 N, P = store.scryptN, store.scryptP 432 } else { 433 N, P = StandardScryptN, StandardScryptP 434 } 435 return EncryptKey(key, newPassphrase, N, P) 436 } 437 438 // Import stores the given encrypted JSON key into the key directory. 439 func (ks *KeyStore) Import(keyJSON []byte, passphrase, newPassphrase string) (accounts.Account, error) { 440 key, err := DecryptKey(keyJSON, passphrase) 441 if key != nil && key.PrivateKey != nil { 442 defer zeroKey(key.PrivateKey) 443 } 444 if err != nil { 445 return accounts.Account{}, err 446 } 447 return ks.importKey(key, newPassphrase) 448 } 449 450 // ImportECDSA stores the given key into the key directory, encrypting it with the passphrase. 451 func (ks *KeyStore) ImportECDSA(priv *ecdsa.PrivateKey, passphrase string) (accounts.Account, error) { 452 key := newKeyFromECDSA(priv) 453 if ks.cache.hasAddress(key.Address) { 454 return accounts.Account{}, fmt.Errorf("account already exists") 455 } 456 return ks.importKey(key, passphrase) 457 } 458 459 func (ks *KeyStore) importKey(key *Key, passphrase string) (accounts.Account, error) { 460 a := accounts.Account{Address: key.Address, URL: accounts.URL{Scheme: KeyStoreScheme, Path: ks.storage.JoinPath(keyFileName(key.Address))}} 461 if err := ks.storage.StoreKey(a.URL.Path, key, passphrase); err != nil { 462 return accounts.Account{}, err 463 } 464 ks.cache.add(a) 465 ks.refreshWallets() 466 return a, nil 467 } 468 469 // Update changes the passphrase of an existing account. 470 func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error { 471 a, key, err := ks.getDecryptedKey(a, passphrase) 472 if err != nil { 473 return err 474 } 475 return ks.storage.StoreKey(a.URL.Path, key, newPassphrase) 476 } 477 478 // ImportPreSaleKey decrypts the given Ethereum presale wallet and stores 479 // a key file in the key directory. The key file is encrypted with the same passphrase. 480 func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (accounts.Account, error) { 481 a, _, err := importPreSaleKey(ks.storage, keyJSON, passphrase) 482 if err != nil { 483 return a, err 484 } 485 ks.cache.add(a) 486 ks.refreshWallets() 487 return a, nil 488 } 489 490 // zeroKey zeroes a private key in memory. 491 func zeroKey(k *ecdsa.PrivateKey) { 492 b := k.D.Bits() 493 for i := range b { 494 b[i] = 0 495 } 496 }