crypto_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. "io/ioutil"
  22. "math/big"
  23. "os"
  24. "reflect"
  25. "testing"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/common/hexutil"
  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 TestKeccak256Hash(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 TestToECDSAErrors(t *testing.T) {
  40. if _, err := HexToECDSA("0000000000000000000000000000000000000000000000000000000000000000"); err == nil {
  41. t.Fatal("HexToECDSA should've returned error")
  42. }
  43. if _, err := HexToECDSA("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); err == nil {
  44. t.Fatal("HexToECDSA should've returned error")
  45. }
  46. }
  47. func BenchmarkSha3(b *testing.B) {
  48. a := []byte("hello world")
  49. for i := 0; i < b.N; i++ {
  50. Keccak256(a)
  51. }
  52. }
  53. func TestUnmarshalPubkey(t *testing.T) {
  54. key, err := UnmarshalPubkey(nil)
  55. if err != errInvalidPubkey || key != nil {
  56. t.Fatalf("expected error, got %v, %v", err, key)
  57. }
  58. key, err = UnmarshalPubkey([]byte{1, 2, 3})
  59. if err != errInvalidPubkey || key != nil {
  60. t.Fatalf("expected error, got %v, %v", err, key)
  61. }
  62. var (
  63. enc, _ = hex.DecodeString("04760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1b01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d")
  64. dec = &ecdsa.PublicKey{
  65. Curve: S256(),
  66. X: hexutil.MustDecodeBig("0x760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1"),
  67. Y: hexutil.MustDecodeBig("0xb01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d"),
  68. }
  69. )
  70. key, err = UnmarshalPubkey(enc)
  71. if err != nil {
  72. t.Fatalf("expected no error, got %v", err)
  73. }
  74. if !reflect.DeepEqual(key, dec) {
  75. t.Fatal("wrong result")
  76. }
  77. }
  78. func TestSign(t *testing.T) {
  79. key, _ := HexToECDSA(testPrivHex)
  80. addr := common.HexToAddress(testAddrHex)
  81. msg := Keccak256([]byte("foo"))
  82. sig, err := Sign(msg, key)
  83. if err != nil {
  84. t.Errorf("Sign error: %s", err)
  85. }
  86. recoveredPub, err := Ecrecover(msg, sig)
  87. if err != nil {
  88. t.Errorf("ECRecover error: %s", err)
  89. }
  90. pubKey, _ := UnmarshalPubkey(recoveredPub)
  91. recoveredAddr := PubkeyToAddress(*pubKey)
  92. if addr != recoveredAddr {
  93. t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
  94. }
  95. // should be equal to SigToPub
  96. recoveredPub2, err := SigToPub(msg, sig)
  97. if err != nil {
  98. t.Errorf("ECRecover error: %s", err)
  99. }
  100. recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
  101. if addr != recoveredAddr2 {
  102. t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
  103. }
  104. }
  105. func TestInvalidSign(t *testing.T) {
  106. if _, err := Sign(make([]byte, 1), nil); err == nil {
  107. t.Errorf("expected sign with hash 1 byte to error")
  108. }
  109. if _, err := Sign(make([]byte, 33), nil); err == nil {
  110. t.Errorf("expected sign with hash 33 byte to error")
  111. }
  112. }
  113. func TestNewContractAddress(t *testing.T) {
  114. key, _ := HexToECDSA(testPrivHex)
  115. addr := common.HexToAddress(testAddrHex)
  116. genAddr := PubkeyToAddress(key.PublicKey)
  117. // sanity check before using addr to create contract address
  118. checkAddr(t, genAddr, addr)
  119. caddr0 := CreateAddress(addr, 0)
  120. caddr1 := CreateAddress(addr, 1)
  121. caddr2 := CreateAddress(addr, 2)
  122. checkAddr(t, common.HexToAddress("333c3310824b7c685133f2bedb2ca4b8b4df633d"), caddr0)
  123. checkAddr(t, common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), caddr1)
  124. checkAddr(t, common.HexToAddress("c9ddedf451bc62ce88bf9292afb13df35b670699"), caddr2)
  125. }
  126. func TestLoadECDSAFile(t *testing.T) {
  127. keyBytes := common.FromHex(testPrivHex)
  128. fileName0 := "test_key0"
  129. fileName1 := "test_key1"
  130. checkKey := func(k *ecdsa.PrivateKey) {
  131. checkAddr(t, PubkeyToAddress(k.PublicKey), common.HexToAddress(testAddrHex))
  132. loadedKeyBytes := FromECDSA(k)
  133. if !bytes.Equal(loadedKeyBytes, keyBytes) {
  134. t.Fatalf("private key mismatch: want: %x have: %x", keyBytes, loadedKeyBytes)
  135. }
  136. }
  137. ioutil.WriteFile(fileName0, []byte(testPrivHex), 0600)
  138. defer os.Remove(fileName0)
  139. key0, err := LoadECDSA(fileName0)
  140. if err != nil {
  141. t.Fatal(err)
  142. }
  143. checkKey(key0)
  144. // again, this time with SaveECDSA instead of manual save:
  145. err = SaveECDSA(fileName1, key0)
  146. if err != nil {
  147. t.Fatal(err)
  148. }
  149. defer os.Remove(fileName1)
  150. key1, err := LoadECDSA(fileName1)
  151. if err != nil {
  152. t.Fatal(err)
  153. }
  154. checkKey(key1)
  155. }
  156. func TestValidateSignatureValues(t *testing.T) {
  157. check := func(expected bool, v byte, r, s *big.Int) {
  158. if ValidateSignatureValues(v, r, s, false) != expected {
  159. t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
  160. }
  161. }
  162. minusOne := big.NewInt(-1)
  163. one := common.Big1
  164. zero := common.Big0
  165. secp256k1nMinus1 := new(big.Int).Sub(secp256k1N, common.Big1)
  166. // correct v,r,s
  167. check(true, 0, one, one)
  168. check(true, 1, one, one)
  169. // incorrect v, correct r,s,
  170. check(false, 2, one, one)
  171. check(false, 3, one, one)
  172. // incorrect v, combinations of incorrect/correct r,s at lower limit
  173. check(false, 2, zero, zero)
  174. check(false, 2, zero, one)
  175. check(false, 2, one, zero)
  176. check(false, 2, one, one)
  177. // correct v for any combination of incorrect r,s
  178. check(false, 0, zero, zero)
  179. check(false, 0, zero, one)
  180. check(false, 0, one, zero)
  181. check(false, 1, zero, zero)
  182. check(false, 1, zero, one)
  183. check(false, 1, one, zero)
  184. // correct sig with max r,s
  185. check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
  186. // correct v, combinations of incorrect r,s at upper limit
  187. check(false, 0, secp256k1N, secp256k1nMinus1)
  188. check(false, 0, secp256k1nMinus1, secp256k1N)
  189. check(false, 0, secp256k1N, secp256k1N)
  190. // current callers ensures r,s cannot be negative, but let's test for that too
  191. // as crypto package could be used stand-alone
  192. check(false, 0, minusOne, one)
  193. check(false, 0, one, minusOne)
  194. }
  195. func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
  196. sum := f(msg)
  197. if !bytes.Equal(exp, sum) {
  198. t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
  199. }
  200. }
  201. func checkAddr(t *testing.T, addr0, addr1 common.Address) {
  202. if addr0 != addr1 {
  203. t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
  204. }
  205. }
  206. // test to help Python team with integration of libsecp256k1
  207. // skip but keep it after they are done
  208. func TestPythonIntegration(t *testing.T) {
  209. kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
  210. k0, _ := HexToECDSA(kh)
  211. msg0 := Keccak256([]byte("foo"))
  212. sig0, _ := Sign(msg0, k0)
  213. msg1 := common.FromHex("00000000000000000000000000000000")
  214. sig1, _ := Sign(msg0, k0)
  215. t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
  216. t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
  217. }