crypto_test.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 TestLoadECDSA(t *testing.T) {
  127. tests := []struct {
  128. input string
  129. err string
  130. }{
  131. // good
  132. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"},
  133. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n"},
  134. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\r"},
  135. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\r\n"},
  136. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\n"},
  137. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\r"},
  138. // bad
  139. {
  140. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde",
  141. err: "key file too short, want 64 hex characters",
  142. },
  143. {
  144. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde\n",
  145. err: "key file too short, want 64 hex characters",
  146. },
  147. {
  148. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeX",
  149. err: "invalid hex character 'X' in private key",
  150. },
  151. {
  152. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdefX",
  153. err: "invalid character 'X' at end of key file",
  154. },
  155. {
  156. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\n\n",
  157. err: "key file too long, want 64 hex characters",
  158. },
  159. }
  160. for _, test := range tests {
  161. f, err := ioutil.TempFile("", "loadecdsa_test.*.txt")
  162. if err != nil {
  163. t.Fatal(err)
  164. }
  165. filename := f.Name()
  166. f.WriteString(test.input)
  167. f.Close()
  168. _, err = LoadECDSA(filename)
  169. switch {
  170. case err != nil && test.err == "":
  171. t.Fatalf("unexpected error for input %q:\n %v", test.input, err)
  172. case err != nil && err.Error() != test.err:
  173. t.Fatalf("wrong error for input %q:\n %v", test.input, err)
  174. case err == nil && test.err != "":
  175. t.Fatalf("LoadECDSA did not return error for input %q", test.input)
  176. }
  177. }
  178. }
  179. func TestSaveECDSA(t *testing.T) {
  180. f, err := ioutil.TempFile("", "saveecdsa_test.*.txt")
  181. if err != nil {
  182. t.Fatal(err)
  183. }
  184. file := f.Name()
  185. f.Close()
  186. defer os.Remove(file)
  187. key, _ := HexToECDSA(testPrivHex)
  188. if err := SaveECDSA(file, key); err != nil {
  189. t.Fatal(err)
  190. }
  191. loaded, err := LoadECDSA(file)
  192. if err != nil {
  193. t.Fatal(err)
  194. }
  195. if !reflect.DeepEqual(key, loaded) {
  196. t.Fatal("loaded key not equal to saved key")
  197. }
  198. }
  199. func TestValidateSignatureValues(t *testing.T) {
  200. check := func(expected bool, v byte, r, s *big.Int) {
  201. if ValidateSignatureValues(v, r, s, false) != expected {
  202. t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
  203. }
  204. }
  205. minusOne := big.NewInt(-1)
  206. one := common.Big1
  207. zero := common.Big0
  208. secp256k1nMinus1 := new(big.Int).Sub(secp256k1N, common.Big1)
  209. // correct v,r,s
  210. check(true, 0, one, one)
  211. check(true, 1, one, one)
  212. // incorrect v, correct r,s,
  213. check(false, 2, one, one)
  214. check(false, 3, one, one)
  215. // incorrect v, combinations of incorrect/correct r,s at lower limit
  216. check(false, 2, zero, zero)
  217. check(false, 2, zero, one)
  218. check(false, 2, one, zero)
  219. check(false, 2, one, one)
  220. // correct v for any combination of incorrect r,s
  221. check(false, 0, zero, zero)
  222. check(false, 0, zero, one)
  223. check(false, 0, one, zero)
  224. check(false, 1, zero, zero)
  225. check(false, 1, zero, one)
  226. check(false, 1, one, zero)
  227. // correct sig with max r,s
  228. check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
  229. // correct v, combinations of incorrect r,s at upper limit
  230. check(false, 0, secp256k1N, secp256k1nMinus1)
  231. check(false, 0, secp256k1nMinus1, secp256k1N)
  232. check(false, 0, secp256k1N, secp256k1N)
  233. // current callers ensures r,s cannot be negative, but let's test for that too
  234. // as crypto package could be used stand-alone
  235. check(false, 0, minusOne, one)
  236. check(false, 0, one, minusOne)
  237. }
  238. func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
  239. sum := f(msg)
  240. if !bytes.Equal(exp, sum) {
  241. t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
  242. }
  243. }
  244. func checkAddr(t *testing.T, addr0, addr1 common.Address) {
  245. if addr0 != addr1 {
  246. t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
  247. }
  248. }
  249. // test to help Python team with integration of libsecp256k1
  250. // skip but keep it after they are done
  251. func TestPythonIntegration(t *testing.T) {
  252. kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
  253. k0, _ := HexToECDSA(kh)
  254. msg0 := Keccak256([]byte("foo"))
  255. sig0, _ := Sign(msg0, k0)
  256. msg1 := common.FromHex("00000000000000000000000000000000")
  257. sig1, _ := Sign(msg0, k0)
  258. t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
  259. t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
  260. }