crypto_test.go 7.3 KB

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