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