crypto.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Copyright 2014 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 crypto
  17. import (
  18. "bufio"
  19. "crypto/ecdsa"
  20. "crypto/elliptic"
  21. "crypto/rand"
  22. "encoding/hex"
  23. "errors"
  24. "fmt"
  25. "hash"
  26. "io"
  27. "io/ioutil"
  28. "math/big"
  29. "os"
  30. "sync"
  31. "github.com/VictoriaMetrics/fastcache"
  32. "github.com/ethereum/go-ethereum/common"
  33. "github.com/ethereum/go-ethereum/common/math"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. "golang.org/x/crypto/sha3"
  36. )
  37. //SignatureLength indicates the byte length required to carry a signature with recovery id.
  38. const SignatureLength = 64 + 1 // 64 bytes ECDSA signature + 1 byte recovery id
  39. // RecoveryIDOffset points to the byte offset within the signature that contains the recovery id.
  40. const RecoveryIDOffset = 64
  41. // DigestLength sets the signature digest exact length
  42. const DigestLength = 32
  43. var (
  44. secp256k1N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
  45. secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
  46. keccakState256Cache = fastcache.New(100 * 1024 * 1024)
  47. )
  48. var errInvalidPubkey = errors.New("invalid secp256k1 public key")
  49. var keccakState256Pool = sync.Pool{
  50. New: func() interface{} {
  51. return sha3.NewLegacyKeccak256().(KeccakState)
  52. }}
  53. // KeccakState wraps sha3.state. In addition to the usual hash methods, it also supports
  54. // Read to get a variable amount of data from the hash state. Read is faster than Sum
  55. // because it doesn't copy the internal state, but also modifies the internal state.
  56. type KeccakState interface {
  57. hash.Hash
  58. Read([]byte) (int, error)
  59. }
  60. // NewKeccakState creates a new KeccakState
  61. func NewKeccakState() KeccakState {
  62. return sha3.NewLegacyKeccak256().(KeccakState)
  63. }
  64. // HashData hashes the provided data using the KeccakState and returns a 32 byte hash
  65. func HashData(kh KeccakState, data []byte) (h common.Hash) {
  66. if hash, ok := keccakState256Cache.HasGet(nil, data); ok {
  67. return common.BytesToHash(hash)
  68. }
  69. kh.Reset()
  70. kh.Write(data)
  71. kh.Read(h[:])
  72. keccakState256Cache.Set(data, h.Bytes())
  73. return h
  74. }
  75. // Keccak256 calculates and returns the Keccak256 hash of the input data.
  76. func Keccak256(data ...[]byte) []byte {
  77. if len(data) == 1 {
  78. if hash, ok := keccakState256Cache.HasGet(nil, data[0]); ok {
  79. return hash
  80. }
  81. }
  82. b := make([]byte, 32)
  83. d := keccakState256Pool.Get().(KeccakState)
  84. defer keccakState256Pool.Put(d)
  85. d.Reset()
  86. for _, b := range data {
  87. d.Write(b)
  88. }
  89. d.Read(b)
  90. if len(data) == 1 {
  91. keccakState256Cache.Set(data[0], b)
  92. }
  93. return b
  94. }
  95. // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
  96. // converting it to an internal Hash data structure.
  97. func Keccak256Hash(data ...[]byte) (h common.Hash) {
  98. if len(data) == 1 {
  99. if hash, ok := keccakState256Cache.HasGet(nil, data[0]); ok {
  100. return common.BytesToHash(hash)
  101. }
  102. }
  103. d := keccakState256Pool.Get().(KeccakState)
  104. defer keccakState256Pool.Put(d)
  105. d.Reset()
  106. for _, b := range data {
  107. d.Write(b)
  108. }
  109. d.Read(h[:])
  110. if len(data) == 1 {
  111. keccakState256Cache.Set(data[0], h.Bytes())
  112. }
  113. return h
  114. }
  115. // Keccak512 calculates and returns the Keccak512 hash of the input data.
  116. func Keccak512(data ...[]byte) []byte {
  117. d := sha3.NewLegacyKeccak512()
  118. for _, b := range data {
  119. d.Write(b)
  120. }
  121. return d.Sum(nil)
  122. }
  123. // CreateAddress creates an ethereum address given the bytes and the nonce
  124. func CreateAddress(b common.Address, nonce uint64) common.Address {
  125. data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
  126. return common.BytesToAddress(Keccak256(data)[12:])
  127. }
  128. // CreateAddress2 creates an ethereum address given the address bytes, initial
  129. // contract code hash and a salt.
  130. func CreateAddress2(b common.Address, salt [32]byte, inithash []byte) common.Address {
  131. return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], inithash)[12:])
  132. }
  133. // ToECDSA creates a private key with the given D value.
  134. func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
  135. return toECDSA(d, true)
  136. }
  137. // ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost
  138. // never be used unless you are sure the input is valid and want to avoid hitting
  139. // errors due to bad origin encoding (0 prefixes cut off).
  140. func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
  141. priv, _ := toECDSA(d, false)
  142. return priv
  143. }
  144. // toECDSA creates a private key with the given D value. The strict parameter
  145. // controls whether the key's length should be enforced at the curve size or
  146. // it can also accept legacy encodings (0 prefixes).
  147. func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
  148. priv := new(ecdsa.PrivateKey)
  149. priv.PublicKey.Curve = S256()
  150. if strict && 8*len(d) != priv.Params().BitSize {
  151. return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
  152. }
  153. priv.D = new(big.Int).SetBytes(d)
  154. // The priv.D must < N
  155. if priv.D.Cmp(secp256k1N) >= 0 {
  156. return nil, fmt.Errorf("invalid private key, >=N")
  157. }
  158. // The priv.D must not be zero or negative.
  159. if priv.D.Sign() <= 0 {
  160. return nil, fmt.Errorf("invalid private key, zero or negative")
  161. }
  162. priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
  163. if priv.PublicKey.X == nil {
  164. return nil, errors.New("invalid private key")
  165. }
  166. return priv, nil
  167. }
  168. // FromECDSA exports a private key into a binary dump.
  169. func FromECDSA(priv *ecdsa.PrivateKey) []byte {
  170. if priv == nil {
  171. return nil
  172. }
  173. return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
  174. }
  175. // UnmarshalPubkey converts bytes to a secp256k1 public key.
  176. func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
  177. x, y := elliptic.Unmarshal(S256(), pub)
  178. if x == nil {
  179. return nil, errInvalidPubkey
  180. }
  181. return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
  182. }
  183. func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
  184. if pub == nil || pub.X == nil || pub.Y == nil {
  185. return nil
  186. }
  187. return elliptic.Marshal(S256(), pub.X, pub.Y)
  188. }
  189. // HexToECDSA parses a secp256k1 private key.
  190. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
  191. b, err := hex.DecodeString(hexkey)
  192. if byteErr, ok := err.(hex.InvalidByteError); ok {
  193. return nil, fmt.Errorf("invalid hex character %q in private key", byte(byteErr))
  194. } else if err != nil {
  195. return nil, errors.New("invalid hex data for private key")
  196. }
  197. return ToECDSA(b)
  198. }
  199. // LoadECDSA loads a secp256k1 private key from the given file.
  200. func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
  201. fd, err := os.Open(file)
  202. if err != nil {
  203. return nil, err
  204. }
  205. defer fd.Close()
  206. r := bufio.NewReader(fd)
  207. buf := make([]byte, 64)
  208. n, err := readASCII(buf, r)
  209. if err != nil {
  210. return nil, err
  211. } else if n != len(buf) {
  212. return nil, fmt.Errorf("key file too short, want 64 hex characters")
  213. }
  214. if err := checkKeyFileEnd(r); err != nil {
  215. return nil, err
  216. }
  217. return HexToECDSA(string(buf))
  218. }
  219. // readASCII reads into 'buf', stopping when the buffer is full or
  220. // when a non-printable control character is encountered.
  221. func readASCII(buf []byte, r *bufio.Reader) (n int, err error) {
  222. for ; n < len(buf); n++ {
  223. buf[n], err = r.ReadByte()
  224. switch {
  225. case err == io.EOF || buf[n] < '!':
  226. return n, nil
  227. case err != nil:
  228. return n, err
  229. }
  230. }
  231. return n, nil
  232. }
  233. // checkKeyFileEnd skips over additional newlines at the end of a key file.
  234. func checkKeyFileEnd(r *bufio.Reader) error {
  235. for i := 0; ; i++ {
  236. b, err := r.ReadByte()
  237. switch {
  238. case err == io.EOF:
  239. return nil
  240. case err != nil:
  241. return err
  242. case b != '\n' && b != '\r':
  243. return fmt.Errorf("invalid character %q at end of key file", b)
  244. case i >= 2:
  245. return errors.New("key file too long, want 64 hex characters")
  246. }
  247. }
  248. }
  249. // SaveECDSA saves a secp256k1 private key to the given file with
  250. // restrictive permissions. The key data is saved hex-encoded.
  251. func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
  252. k := hex.EncodeToString(FromECDSA(key))
  253. return ioutil.WriteFile(file, []byte(k), 0600)
  254. }
  255. // GenerateKey generates a new private key.
  256. func GenerateKey() (*ecdsa.PrivateKey, error) {
  257. return ecdsa.GenerateKey(S256(), rand.Reader)
  258. }
  259. // ValidateSignatureValues verifies whether the signature values are valid with
  260. // the given chain rules. The v value is assumed to be either 0 or 1.
  261. func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
  262. if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
  263. return false
  264. }
  265. // reject upper range of s values (ECDSA malleability)
  266. // see discussion in secp256k1/libsecp256k1/include/secp256k1.h
  267. if homestead && s.Cmp(secp256k1halfN) > 0 {
  268. return false
  269. }
  270. // Frontier: allow s to be in full N range
  271. return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1)
  272. }
  273. func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
  274. pubBytes := FromECDSAPub(&p)
  275. return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
  276. }
  277. func zeroBytes(bytes []byte) {
  278. for i := range bytes {
  279. bytes[i] = 0
  280. }
  281. }