transaction_signing.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 types
  17. import (
  18. "crypto/ecdsa"
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/params"
  25. )
  26. var (
  27. ErrInvalidChainId = errors.New("invalid chain id for signer")
  28. )
  29. // sigCache is used to cache the derived sender and contains
  30. // the signer used to derive it.
  31. type sigCache struct {
  32. signer Signer
  33. from common.Address
  34. }
  35. // MakeSigner returns a Signer based on the given chain config and block number.
  36. func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer {
  37. var signer Signer
  38. switch {
  39. case config.IsEIP155(blockNumber):
  40. signer = NewEIP155Signer(config.ChainId)
  41. case config.IsHomestead(blockNumber):
  42. signer = HomesteadSigner{}
  43. default:
  44. signer = FrontierSigner{}
  45. }
  46. return signer
  47. }
  48. // SignTx signs the transaction using the given signer and private key
  49. func SignTx(tx *Transaction, s Signer, prv *ecdsa.PrivateKey) (*Transaction, error) {
  50. h := s.Hash(tx)
  51. sig, err := crypto.Sign(h[:], prv)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return tx.WithSignature(s, sig)
  56. }
  57. // Sender returns the address derived from the signature (V, R, S) using secp256k1
  58. // elliptic curve and an error if it failed deriving or upon an incorrect
  59. // signature.
  60. //
  61. // Sender may cache the address, allowing it to be used regardless of
  62. // signing method. The cache is invalidated if the cached signer does
  63. // not match the signer used in the current call.
  64. func Sender(signer Signer, tx *Transaction) (common.Address, error) {
  65. if sc := tx.from.Load(); sc != nil {
  66. sigCache := sc.(sigCache)
  67. // If the signer used to derive from in a previous
  68. // call is not the same as used current, invalidate
  69. // the cache.
  70. if sigCache.signer.Equal(signer) {
  71. return sigCache.from, nil
  72. }
  73. }
  74. addr, err := signer.Sender(tx)
  75. if err != nil {
  76. return common.Address{}, err
  77. }
  78. tx.from.Store(sigCache{signer: signer, from: addr})
  79. return addr, nil
  80. }
  81. // Signer encapsulates transaction signature handling. Note that this interface is not a
  82. // stable API and may change at any time to accommodate new protocol rules.
  83. type Signer interface {
  84. // Sender returns the sender address of the transaction.
  85. Sender(tx *Transaction) (common.Address, error)
  86. // SignatureValues returns the raw R, S, V values corresponding to the
  87. // given signature.
  88. SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error)
  89. // Hash returns the hash to be signed.
  90. Hash(tx *Transaction) common.Hash
  91. // Equal returns true if the given signer is the same as the receiver.
  92. Equal(Signer) bool
  93. }
  94. // EIP155Transaction implements Signer using the EIP155 rules.
  95. type EIP155Signer struct {
  96. chainId, chainIdMul *big.Int
  97. }
  98. func NewEIP155Signer(chainId *big.Int) EIP155Signer {
  99. if chainId == nil {
  100. chainId = new(big.Int)
  101. }
  102. return EIP155Signer{
  103. chainId: chainId,
  104. chainIdMul: new(big.Int).Mul(chainId, big.NewInt(2)),
  105. }
  106. }
  107. func (s EIP155Signer) Equal(s2 Signer) bool {
  108. eip155, ok := s2.(EIP155Signer)
  109. return ok && eip155.chainId.Cmp(s.chainId) == 0
  110. }
  111. var big8 = big.NewInt(8)
  112. func (s EIP155Signer) Sender(tx *Transaction) (common.Address, error) {
  113. if !tx.Protected() {
  114. return HomesteadSigner{}.Sender(tx)
  115. }
  116. if tx.ChainId().Cmp(s.chainId) != 0 {
  117. return common.Address{}, ErrInvalidChainId
  118. }
  119. V := new(big.Int).Sub(tx.data.V, s.chainIdMul)
  120. V.Sub(V, big8)
  121. return recoverPlain(s.Hash(tx), tx.data.R, tx.data.S, V, true)
  122. }
  123. // WithSignature returns a new transaction with the given signature. This signature
  124. // needs to be in the [R || S || V] format where V is 0 or 1.
  125. func (s EIP155Signer) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) {
  126. R, S, V, err = HomesteadSigner{}.SignatureValues(tx, sig)
  127. if err != nil {
  128. return nil, nil, nil, err
  129. }
  130. if s.chainId.Sign() != 0 {
  131. V = big.NewInt(int64(sig[64] + 35))
  132. V.Add(V, s.chainIdMul)
  133. }
  134. return R, S, V, nil
  135. }
  136. // Hash returns the hash to be signed by the sender.
  137. // It does not uniquely identify the transaction.
  138. func (s EIP155Signer) Hash(tx *Transaction) common.Hash {
  139. return rlpHash([]interface{}{
  140. tx.data.AccountNonce,
  141. tx.data.Price,
  142. tx.data.GasLimit,
  143. tx.data.Recipient,
  144. tx.data.Amount,
  145. tx.data.Payload,
  146. s.chainId, uint(0), uint(0),
  147. })
  148. }
  149. // HomesteadTransaction implements TransactionInterface using the
  150. // homestead rules.
  151. type HomesteadSigner struct{ FrontierSigner }
  152. func (s HomesteadSigner) Equal(s2 Signer) bool {
  153. _, ok := s2.(HomesteadSigner)
  154. return ok
  155. }
  156. // SignatureValues returns signature values. This signature
  157. // needs to be in the [R || S || V] format where V is 0 or 1.
  158. func (hs HomesteadSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) {
  159. return hs.FrontierSigner.SignatureValues(tx, sig)
  160. }
  161. func (hs HomesteadSigner) Sender(tx *Transaction) (common.Address, error) {
  162. return recoverPlain(hs.Hash(tx), tx.data.R, tx.data.S, tx.data.V, true)
  163. }
  164. type FrontierSigner struct{}
  165. func (s FrontierSigner) Equal(s2 Signer) bool {
  166. _, ok := s2.(FrontierSigner)
  167. return ok
  168. }
  169. // SignatureValues returns signature values. This signature
  170. // needs to be in the [R || S || V] format where V is 0 or 1.
  171. func (fs FrontierSigner) SignatureValues(tx *Transaction, sig []byte) (r, s, v *big.Int, err error) {
  172. if len(sig) != 65 {
  173. panic(fmt.Sprintf("wrong size for signature: got %d, want 65", len(sig)))
  174. }
  175. r = new(big.Int).SetBytes(sig[:32])
  176. s = new(big.Int).SetBytes(sig[32:64])
  177. v = new(big.Int).SetBytes([]byte{sig[64] + 27})
  178. return r, s, v, nil
  179. }
  180. // Hash returns the hash to be signed by the sender.
  181. // It does not uniquely identify the transaction.
  182. func (fs FrontierSigner) Hash(tx *Transaction) common.Hash {
  183. return rlpHash([]interface{}{
  184. tx.data.AccountNonce,
  185. tx.data.Price,
  186. tx.data.GasLimit,
  187. tx.data.Recipient,
  188. tx.data.Amount,
  189. tx.data.Payload,
  190. })
  191. }
  192. func (fs FrontierSigner) Sender(tx *Transaction) (common.Address, error) {
  193. return recoverPlain(fs.Hash(tx), tx.data.R, tx.data.S, tx.data.V, false)
  194. }
  195. func recoverPlain(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (common.Address, error) {
  196. if Vb.BitLen() > 8 {
  197. return common.Address{}, ErrInvalidSig
  198. }
  199. V := byte(Vb.Uint64() - 27)
  200. if !crypto.ValidateSignatureValues(V, R, S, homestead) {
  201. return common.Address{}, ErrInvalidSig
  202. }
  203. // encode the snature in uncompressed format
  204. r, s := R.Bytes(), S.Bytes()
  205. sig := make([]byte, 65)
  206. copy(sig[32-len(r):32], r)
  207. copy(sig[64-len(s):64], s)
  208. sig[64] = V
  209. // recover the public key from the snature
  210. pub, err := crypto.Ecrecover(sighash[:], sig)
  211. if err != nil {
  212. return common.Address{}, err
  213. }
  214. if len(pub) == 0 || pub[0] != 4 {
  215. return common.Address{}, errors.New("invalid public key")
  216. }
  217. var addr common.Address
  218. copy(addr[:], crypto.Keccak256(pub[1:])[12:])
  219. return addr, nil
  220. }
  221. // deriveChainId derives the chain id from the given v parameter
  222. func deriveChainId(v *big.Int) *big.Int {
  223. if v.BitLen() <= 64 {
  224. v := v.Uint64()
  225. if v == 27 || v == 28 {
  226. return new(big.Int)
  227. }
  228. return new(big.Int).SetUint64((v - 35) / 2)
  229. }
  230. v = new(big.Int).Sub(v, big.NewInt(35))
  231. return v.Div(v, big.NewInt(2))
  232. }