crypto_test.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. "math/big"
  22. "os"
  23. "reflect"
  24. "testing"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/hexutil"
  27. )
  28. var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791"
  29. var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
  30. // These tests are sanity checks.
  31. // They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256
  32. // and that the sha3 library uses keccak-f permutation.
  33. func TestKeccak256Hash(t *testing.T) {
  34. msg := []byte("abc")
  35. exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
  36. checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
  37. }
  38. func TestKeccak256Hasher(t *testing.T) {
  39. msg := []byte("abc")
  40. exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
  41. hasher := NewKeccakState()
  42. checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := HashData(hasher, in); return h[:] }, msg, exp)
  43. }
  44. func TestToECDSAErrors(t *testing.T) {
  45. if _, err := HexToECDSA("0000000000000000000000000000000000000000000000000000000000000000"); err == nil {
  46. t.Fatal("HexToECDSA should've returned error")
  47. }
  48. if _, err := HexToECDSA("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); err == nil {
  49. t.Fatal("HexToECDSA should've returned error")
  50. }
  51. }
  52. func BenchmarkSha3(b *testing.B) {
  53. a := []byte("hello world")
  54. for i := 0; i < b.N; i++ {
  55. Keccak256(a)
  56. }
  57. }
  58. func TestUnmarshalPubkey(t *testing.T) {
  59. key, err := UnmarshalPubkey(nil)
  60. if err != errInvalidPubkey || key != nil {
  61. t.Fatalf("expected error, got %v, %v", err, key)
  62. }
  63. key, err = UnmarshalPubkey([]byte{1, 2, 3})
  64. if err != errInvalidPubkey || key != nil {
  65. t.Fatalf("expected error, got %v, %v", err, key)
  66. }
  67. var (
  68. enc, _ = hex.DecodeString("04760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1b01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d")
  69. dec = &ecdsa.PublicKey{
  70. Curve: S256(),
  71. X: hexutil.MustDecodeBig("0x760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1"),
  72. Y: hexutil.MustDecodeBig("0xb01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d"),
  73. }
  74. )
  75. key, err = UnmarshalPubkey(enc)
  76. if err != nil {
  77. t.Fatalf("expected no error, got %v", err)
  78. }
  79. if !reflect.DeepEqual(key, dec) {
  80. t.Fatal("wrong result")
  81. }
  82. }
  83. func TestSign(t *testing.T) {
  84. key, _ := HexToECDSA(testPrivHex)
  85. addr := common.HexToAddress(testAddrHex)
  86. msg := Keccak256([]byte("foo"))
  87. sig, err := Sign(msg, key)
  88. if err != nil {
  89. t.Errorf("Sign error: %s", err)
  90. }
  91. recoveredPub, err := Ecrecover(msg, sig)
  92. if err != nil {
  93. t.Errorf("ECRecover error: %s", err)
  94. }
  95. pubKey, _ := UnmarshalPubkey(recoveredPub)
  96. recoveredAddr := PubkeyToAddress(*pubKey)
  97. if addr != recoveredAddr {
  98. t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
  99. }
  100. // should be equal to SigToPub
  101. recoveredPub2, err := SigToPub(msg, sig)
  102. if err != nil {
  103. t.Errorf("ECRecover error: %s", err)
  104. }
  105. recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
  106. if addr != recoveredAddr2 {
  107. t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
  108. }
  109. }
  110. func TestInvalidSign(t *testing.T) {
  111. if _, err := Sign(make([]byte, 1), nil); err == nil {
  112. t.Errorf("expected sign with hash 1 byte to error")
  113. }
  114. if _, err := Sign(make([]byte, 33), nil); err == nil {
  115. t.Errorf("expected sign with hash 33 byte to error")
  116. }
  117. }
  118. func TestNewContractAddress(t *testing.T) {
  119. key, _ := HexToECDSA(testPrivHex)
  120. addr := common.HexToAddress(testAddrHex)
  121. genAddr := PubkeyToAddress(key.PublicKey)
  122. // sanity check before using addr to create contract address
  123. checkAddr(t, genAddr, addr)
  124. caddr0 := CreateAddress(addr, 0)
  125. caddr1 := CreateAddress(addr, 1)
  126. caddr2 := CreateAddress(addr, 2)
  127. checkAddr(t, common.HexToAddress("333c3310824b7c685133f2bedb2ca4b8b4df633d"), caddr0)
  128. checkAddr(t, common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), caddr1)
  129. checkAddr(t, common.HexToAddress("c9ddedf451bc62ce88bf9292afb13df35b670699"), caddr2)
  130. }
  131. func TestLoadECDSA(t *testing.T) {
  132. tests := []struct {
  133. input string
  134. err string
  135. }{
  136. // good
  137. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"},
  138. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n"},
  139. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\r"},
  140. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\r\n"},
  141. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\n"},
  142. {input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\r"},
  143. // bad
  144. {
  145. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde",
  146. err: "key file too short, want 64 hex characters",
  147. },
  148. {
  149. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde\n",
  150. err: "key file too short, want 64 hex characters",
  151. },
  152. {
  153. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeX",
  154. err: "invalid hex character 'X' in private key",
  155. },
  156. {
  157. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdefX",
  158. err: "invalid character 'X' at end of key file",
  159. },
  160. {
  161. input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\n\n",
  162. err: "key file too long, want 64 hex characters",
  163. },
  164. }
  165. for _, test := range tests {
  166. f, err := os.CreateTemp("", "loadecdsa_test.*.txt")
  167. if err != nil {
  168. t.Fatal(err)
  169. }
  170. filename := f.Name()
  171. f.WriteString(test.input)
  172. f.Close()
  173. _, err = LoadECDSA(filename)
  174. switch {
  175. case err != nil && test.err == "":
  176. t.Fatalf("unexpected error for input %q:\n %v", test.input, err)
  177. case err != nil && err.Error() != test.err:
  178. t.Fatalf("wrong error for input %q:\n %v", test.input, err)
  179. case err == nil && test.err != "":
  180. t.Fatalf("LoadECDSA did not return error for input %q", test.input)
  181. }
  182. }
  183. }
  184. func TestSaveECDSA(t *testing.T) {
  185. f, err := os.CreateTemp("", "saveecdsa_test.*.txt")
  186. if err != nil {
  187. t.Fatal(err)
  188. }
  189. file := f.Name()
  190. f.Close()
  191. defer os.Remove(file)
  192. key, _ := HexToECDSA(testPrivHex)
  193. if err := SaveECDSA(file, key); err != nil {
  194. t.Fatal(err)
  195. }
  196. loaded, err := LoadECDSA(file)
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. if !reflect.DeepEqual(key, loaded) {
  201. t.Fatal("loaded key not equal to saved key")
  202. }
  203. }
  204. func TestValidateSignatureValues(t *testing.T) {
  205. check := func(expected bool, v byte, r, s *big.Int) {
  206. if ValidateSignatureValues(v, r, s, false) != expected {
  207. t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
  208. }
  209. }
  210. minusOne := big.NewInt(-1)
  211. one := common.Big1
  212. zero := common.Big0
  213. secp256k1nMinus1 := new(big.Int).Sub(secp256k1N, common.Big1)
  214. // correct v,r,s
  215. check(true, 0, one, one)
  216. check(true, 1, one, one)
  217. // incorrect v, correct r,s,
  218. check(false, 2, one, one)
  219. check(false, 3, one, one)
  220. // incorrect v, combinations of incorrect/correct r,s at lower limit
  221. check(false, 2, zero, zero)
  222. check(false, 2, zero, one)
  223. check(false, 2, one, zero)
  224. check(false, 2, one, one)
  225. // correct v for any combination of incorrect r,s
  226. check(false, 0, zero, zero)
  227. check(false, 0, zero, one)
  228. check(false, 0, one, zero)
  229. check(false, 1, zero, zero)
  230. check(false, 1, zero, one)
  231. check(false, 1, one, zero)
  232. // correct sig with max r,s
  233. check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
  234. // correct v, combinations of incorrect r,s at upper limit
  235. check(false, 0, secp256k1N, secp256k1nMinus1)
  236. check(false, 0, secp256k1nMinus1, secp256k1N)
  237. check(false, 0, secp256k1N, secp256k1N)
  238. // current callers ensures r,s cannot be negative, but let's test for that too
  239. // as crypto package could be used stand-alone
  240. check(false, 0, minusOne, one)
  241. check(false, 0, one, minusOne)
  242. }
  243. func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
  244. sum := f(msg)
  245. if !bytes.Equal(exp, sum) {
  246. t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
  247. }
  248. }
  249. func checkAddr(t *testing.T, addr0, addr1 common.Address) {
  250. if addr0 != addr1 {
  251. t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
  252. }
  253. }
  254. // test to help Python team with integration of libsecp256k1
  255. // skip but keep it after they are done
  256. func TestPythonIntegration(t *testing.T) {
  257. kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
  258. k0, _ := HexToECDSA(kh)
  259. msg0 := Keccak256([]byte("foo"))
  260. sig0, _ := Sign(msg0, k0)
  261. msg1 := common.FromHex("00000000000000000000000000000000")
  262. sig1, _ := Sign(msg0, k0)
  263. t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
  264. t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
  265. }