sign.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2018 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 feeds
  17. import (
  18. "crypto/ecdsa"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/crypto"
  21. )
  22. const signatureLength = 65
  23. // Signature is an alias for a static byte array with the size of a signature
  24. type Signature [signatureLength]byte
  25. // Signer signs Feed update payloads
  26. type Signer interface {
  27. Sign(common.Hash) (Signature, error)
  28. Address() common.Address
  29. }
  30. // GenericSigner implements the Signer interface
  31. // It is the vanilla signer that probably should be used in most cases
  32. type GenericSigner struct {
  33. PrivKey *ecdsa.PrivateKey
  34. address common.Address
  35. }
  36. // NewGenericSigner builds a signer that will sign everything with the provided private key
  37. func NewGenericSigner(privKey *ecdsa.PrivateKey) *GenericSigner {
  38. return &GenericSigner{
  39. PrivKey: privKey,
  40. address: crypto.PubkeyToAddress(privKey.PublicKey),
  41. }
  42. }
  43. // Sign signs the supplied data
  44. // It wraps the ethereum crypto.Sign() method
  45. func (s *GenericSigner) Sign(data common.Hash) (signature Signature, err error) {
  46. signaturebytes, err := crypto.Sign(data.Bytes(), s.PrivKey)
  47. if err != nil {
  48. return
  49. }
  50. copy(signature[:], signaturebytes)
  51. return
  52. }
  53. // Address returns the public key of the signer's private key
  54. func (s *GenericSigner) Address() common.Address {
  55. return s.address
  56. }
  57. // getUserAddr extracts the address of the Feed update signer
  58. func getUserAddr(digest common.Hash, signature Signature) (common.Address, error) {
  59. pub, err := crypto.SigToPub(digest.Bytes(), signature[:])
  60. if err != nil {
  61. return common.Address{}, err
  62. }
  63. return crypto.PubkeyToAddress(*pub), nil
  64. }