auth.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2016 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. package bind
  17. import (
  18. "crypto/ecdsa"
  19. "errors"
  20. "io"
  21. "io/ioutil"
  22. "github.com/ethereum/go-ethereum/accounts/keystore"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. )
  27. // NewTransactor is a utility method to easily create a transaction signer from
  28. // an encrypted json key stream and the associated passphrase.
  29. func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error) {
  30. json, err := ioutil.ReadAll(keyin)
  31. if err != nil {
  32. return nil, err
  33. }
  34. key, err := keystore.DecryptKey(json, passphrase)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return NewKeyedTransactor(key.PrivateKey), nil
  39. }
  40. // NewKeyedTransactor is a utility method to easily create a transaction signer
  41. // from a single private key.
  42. func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts {
  43. keyAddr := crypto.PubkeyToAddress(key.PublicKey)
  44. return &TransactOpts{
  45. From: keyAddr,
  46. Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) {
  47. if address != keyAddr {
  48. return nil, errors.New("not authorized to sign this account")
  49. }
  50. signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return tx.WithSignature(signer, signature)
  55. },
  56. }
  57. }