signer.go 4.79 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package crypto

import (
	"crypto/ecdsa"
9 10
	"errors"
	"fmt"
11 12

	"github.com/btcsuite/btcd/btcec"
13 14
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
15
	"github.com/ethersphere/bee/pkg/crypto/eip712"
16 17
)

18 19 20 21
var (
	ErrInvalidLength = errors.New("invalid signature length")
)

22
type Signer interface {
23
	// Sign signs data with ethereum prefix (eip191 type 0x45).
24
	Sign(data []byte) ([]byte, error)
25
	// SignTx signs an ethereum transaction.
26
	SignTx(transaction *types.Transaction) (*types.Transaction, error)
27 28 29
	// SignTypedData signs data according to eip712.
	SignTypedData(typedData *eip712.TypedData) ([]byte, error)
	// PublicKey returns the public key this signer uses.
30
	PublicKey() (*ecdsa.PublicKey, error)
31
	// EthereumAddress returns the ethereum address this signer uses.
32
	EthereumAddress() (common.Address, error)
33 34
}

35
// addEthereumPrefix adds the ethereum prefix to the data.
36 37 38 39
func addEthereumPrefix(data []byte) []byte {
	return []byte(fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data))
}

40
// hashWithEthereumPrefix returns the hash that should be signed for the given data.
41 42 43 44
func hashWithEthereumPrefix(data []byte) ([]byte, error) {
	return LegacyKeccak256(addEthereumPrefix(data))
}

45
// Recover verifies signature with the data base provided.
46
// It is using `btcec.RecoverCompact` function.
47
func Recover(signature, data []byte) (*ecdsa.PublicKey, error) {
48 49 50 51 52 53 54 55 56 57 58 59 60 61
	if len(signature) != 65 {
		return nil, ErrInvalidLength
	}
	// Convert to btcec input format with 'recovery id' v at the beginning.
	btcsig := make([]byte, 65)
	btcsig[0] = signature[64]
	copy(btcsig[1:], signature)

	hash, err := hashWithEthereumPrefix(data)
	if err != nil {
		return nil, err
	}

	p, _, err := btcec.RecoverCompact(btcec.S256(), btcsig, hash)
62 63 64 65 66 67 68 69 70 71 72 73 74
	return (*ecdsa.PublicKey)(p), err
}

type defaultSigner struct {
	key *ecdsa.PrivateKey
}

func NewDefaultSigner(key *ecdsa.PrivateKey) Signer {
	return &defaultSigner{
		key: key,
	}
}

75
// PublicKey returns the public key this signer uses.
76 77 78 79
func (d *defaultSigner) PublicKey() (*ecdsa.PublicKey, error) {
	return &d.key.PublicKey, nil
}

80
// Sign signs data with ethereum prefix (eip191 type 0x45).
81
func (d *defaultSigner) Sign(data []byte) (signature []byte, err error) {
82 83 84 85 86
	hash, err := hashWithEthereumPrefix(data)
	if err != nil {
		return nil, err
	}

87
	return d.sign(hash, true)
88
}
89

90
// SignTx signs an ethereum transaction.
91 92 93
func (d *defaultSigner) SignTx(transaction *types.Transaction) (*types.Transaction, error) {
	hash := (&types.HomesteadSigner{}).Hash(transaction).Bytes()
	// isCompressedKey is false here so we get the expected v value (27 or 28)
94
	signature, err := d.sign(hash, false)
95 96 97 98 99
	if err != nil {
		return nil, err
	}

	// v value needs to be adjusted by 27 as transaction.WithSignature expects it to be 0 or 1
100
	signature[64] -= 27
101 102 103
	return transaction.WithSignature(&types.HomesteadSigner{}, signature)
}

104
// EthereumAddress returns the ethereum address this signer uses.
105 106 107 108 109 110 111 112 113 114 115 116 117
func (d *defaultSigner) EthereumAddress() (common.Address, error) {
	publicKey, err := d.PublicKey()
	if err != nil {
		return common.Address{}, err
	}
	eth, err := NewEthereumAddress(*publicKey)
	if err != nil {
		return common.Address{}, err
	}
	var ethAddress common.Address
	copy(ethAddress[:], eth)
	return ethAddress, nil
}
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

// SignTypedData signs data according to eip712.
func (d *defaultSigner) SignTypedData(typedData *eip712.TypedData) ([]byte, error) {
	rawData, err := eip712.EncodeForSigning(typedData)
	if err != nil {
		return nil, err
	}

	sighash, err := LegacyKeccak256(rawData)
	if err != nil {
		return nil, err
	}

	return d.sign(sighash, false)
}

// sign the provided hash and convert it to the ethereum (r,s,v) format.
func (d *defaultSigner) sign(sighash []byte, isCompressedKey bool) ([]byte, error) {
	signature, err := btcec.SignCompact(btcec.S256(), (*btcec.PrivateKey)(d.key), sighash, false)
	if err != nil {
		return nil, err
	}

	// Convert to Ethereum signature format with 'recovery id' v at the end.
	v := signature[0]
	copy(signature, signature[1:])
	signature[64] = v
	return signature, nil
}

// RecoverEIP712 recovers the public key for eip712 signed data.
func RecoverEIP712(signature []byte, data *eip712.TypedData) (*ecdsa.PublicKey, error) {
	if len(signature) != 65 {
		return nil, errors.New("invalid length")
	}
	// Convert to btcec input format with 'recovery id' v at the beginning.
	btcsig := make([]byte, 65)
	btcsig[0] = signature[64]
	copy(btcsig[1:], signature)

	rawData, err := eip712.EncodeForSigning(data)
	if err != nil {
		return nil, err
	}

	sighash, err := LegacyKeccak256(rawData)
	if err != nil {
		return nil, err
	}

	p, _, err := btcec.RecoverCompact(btcec.S256(), btcsig, sighash)
	return (*ecdsa.PublicKey)(p), err
}