crypto_test.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. "bytes"
  19. "crypto/ecdsa"
  20. "encoding/hex"
  21. "fmt"
  22. "io/ioutil"
  23. "math/big"
  24. "os"
  25. "testing"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. )
  29. var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791"
  30. var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
  31. // These tests are sanity checks.
  32. // They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256
  33. // and that the sha3 library uses keccak-f permutation.
  34. func TestSha3Hash(t *testing.T) {
  35. msg := []byte("abc")
  36. exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
  37. checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
  38. }
  39. func BenchmarkSha3(b *testing.B) {
  40. a := []byte("hello world")
  41. amount := 1000000
  42. start := time.Now()
  43. for i := 0; i < amount; i++ {
  44. Keccak256(a)
  45. }
  46. fmt.Println(amount, ":", time.Since(start))
  47. }
  48. func TestSign(t *testing.T) {
  49. key, _ := HexToECDSA(testPrivHex)
  50. addr := common.HexToAddress(testAddrHex)
  51. msg := Keccak256([]byte("foo"))
  52. sig, err := Sign(msg, key)
  53. if err != nil {
  54. t.Errorf("Sign error: %s", err)
  55. }
  56. recoveredPub, err := Ecrecover(msg, sig)
  57. if err != nil {
  58. t.Errorf("ECRecover error: %s", err)
  59. }
  60. pubKey := ToECDSAPub(recoveredPub)
  61. recoveredAddr := PubkeyToAddress(*pubKey)
  62. if addr != recoveredAddr {
  63. t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
  64. }
  65. // should be equal to SigToPub
  66. recoveredPub2, err := SigToPub(msg, sig)
  67. if err != nil {
  68. t.Errorf("ECRecover error: %s", err)
  69. }
  70. recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
  71. if addr != recoveredAddr2 {
  72. t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
  73. }
  74. }
  75. func TestInvalidSign(t *testing.T) {
  76. if _, err := Sign(make([]byte, 1), nil); err == nil {
  77. t.Errorf("expected sign with hash 1 byte to error")
  78. }
  79. if _, err := Sign(make([]byte, 33), nil); err == nil {
  80. t.Errorf("expected sign with hash 33 byte to error")
  81. }
  82. }
  83. func TestNewContractAddress(t *testing.T) {
  84. key, _ := HexToECDSA(testPrivHex)
  85. addr := common.HexToAddress(testAddrHex)
  86. genAddr := PubkeyToAddress(key.PublicKey)
  87. // sanity check before using addr to create contract address
  88. checkAddr(t, genAddr, addr)
  89. caddr0 := CreateAddress(addr, 0)
  90. caddr1 := CreateAddress(addr, 1)
  91. caddr2 := CreateAddress(addr, 2)
  92. checkAddr(t, common.HexToAddress("333c3310824b7c685133f2bedb2ca4b8b4df633d"), caddr0)
  93. checkAddr(t, common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), caddr1)
  94. checkAddr(t, common.HexToAddress("c9ddedf451bc62ce88bf9292afb13df35b670699"), caddr2)
  95. }
  96. func TestLoadECDSAFile(t *testing.T) {
  97. keyBytes := common.FromHex(testPrivHex)
  98. fileName0 := "test_key0"
  99. fileName1 := "test_key1"
  100. checkKey := func(k *ecdsa.PrivateKey) {
  101. checkAddr(t, PubkeyToAddress(k.PublicKey), common.HexToAddress(testAddrHex))
  102. loadedKeyBytes := FromECDSA(k)
  103. if !bytes.Equal(loadedKeyBytes, keyBytes) {
  104. t.Fatalf("private key mismatch: want: %x have: %x", keyBytes, loadedKeyBytes)
  105. }
  106. }
  107. ioutil.WriteFile(fileName0, []byte(testPrivHex), 0600)
  108. defer os.Remove(fileName0)
  109. key0, err := LoadECDSA(fileName0)
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. checkKey(key0)
  114. // again, this time with SaveECDSA instead of manual save:
  115. err = SaveECDSA(fileName1, key0)
  116. if err != nil {
  117. t.Fatal(err)
  118. }
  119. defer os.Remove(fileName1)
  120. key1, err := LoadECDSA(fileName1)
  121. if err != nil {
  122. t.Fatal(err)
  123. }
  124. checkKey(key1)
  125. }
  126. func TestValidateSignatureValues(t *testing.T) {
  127. check := func(expected bool, v byte, r, s *big.Int) {
  128. if ValidateSignatureValues(v, r, s, false) != expected {
  129. t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
  130. }
  131. }
  132. minusOne := big.NewInt(-1)
  133. one := common.Big1
  134. zero := common.Big0
  135. secp256k1nMinus1 := new(big.Int).Sub(secp256k1_N, common.Big1)
  136. // correct v,r,s
  137. check(true, 0, one, one)
  138. check(true, 1, one, one)
  139. // incorrect v, correct r,s,
  140. check(false, 2, one, one)
  141. check(false, 3, one, one)
  142. // incorrect v, combinations of incorrect/correct r,s at lower limit
  143. check(false, 2, zero, zero)
  144. check(false, 2, zero, one)
  145. check(false, 2, one, zero)
  146. check(false, 2, one, one)
  147. // correct v for any combination of incorrect r,s
  148. check(false, 0, zero, zero)
  149. check(false, 0, zero, one)
  150. check(false, 0, one, zero)
  151. check(false, 1, zero, zero)
  152. check(false, 1, zero, one)
  153. check(false, 1, one, zero)
  154. // correct sig with max r,s
  155. check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
  156. // correct v, combinations of incorrect r,s at upper limit
  157. check(false, 0, secp256k1_N, secp256k1nMinus1)
  158. check(false, 0, secp256k1nMinus1, secp256k1_N)
  159. check(false, 0, secp256k1_N, secp256k1_N)
  160. // current callers ensures r,s cannot be negative, but let's test for that too
  161. // as crypto package could be used stand-alone
  162. check(false, 0, minusOne, one)
  163. check(false, 0, one, minusOne)
  164. }
  165. func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
  166. sum := f(msg)
  167. if !bytes.Equal(exp, sum) {
  168. t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
  169. }
  170. }
  171. func checkAddr(t *testing.T, addr0, addr1 common.Address) {
  172. if addr0 != addr1 {
  173. t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
  174. }
  175. }
  176. // test to help Python team with integration of libsecp256k1
  177. // skip but keep it after they are done
  178. func TestPythonIntegration(t *testing.T) {
  179. kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
  180. k0, _ := HexToECDSA(kh)
  181. msg0 := Keccak256([]byte("foo"))
  182. sig0, _ := Sign(msg0, k0)
  183. msg1 := common.FromHex("00000000000000000000000000000000")
  184. sig1, _ := Sign(msg0, k0)
  185. t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
  186. t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
  187. }