crypto_test.go 6.3 KB
Newer Older
F
Felix Lange 已提交
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
F
Felix Lange 已提交
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
F
Felix Lange 已提交
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
F
Felix Lange 已提交
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
12 13 14
// GNU Lesser General Public License for more details.
//
// 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/>.
F
Felix Lange 已提交
16

O
obscuren 已提交
17
package crypto
18 19 20

import (
	"bytes"
21
	"crypto/ecdsa"
F
Felix Lange 已提交
22
	"encoding/hex"
23 24 25
	"io/ioutil"
	"math/big"
	"os"
26
	"testing"
O
obscuren 已提交
27

O
obscuren 已提交
28
	"github.com/ethereum/go-ethereum/common"
29 30
)

31 32 33
var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791"
var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"

F
Felix Lange 已提交
34 35 36
// These tests are sanity checks.
// They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256
// and that the sha3 library uses keccak-f permutation.
37
func TestKeccak256Hash(t *testing.T) {
38 39
	msg := []byte("abc")
	exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
40
	checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
41 42
}

O
pre-pow  
obscuren 已提交
43 44
func BenchmarkSha3(b *testing.B) {
	a := []byte("hello world")
45
	for i := 0; i < b.N; i++ {
46
		Keccak256(a)
O
pre-pow  
obscuren 已提交
47 48
	}
}
O
obscuren 已提交
49

50
func TestSign(t *testing.T) {
51 52 53
	key, _ := HexToECDSA(testPrivHex)
	addr := common.HexToAddress(testAddrHex)

54
	msg := Keccak256([]byte("foo"))
55
	sig, err := Sign(msg, key)
56 57 58 59 60 61 62
	if err != nil {
		t.Errorf("Sign error: %s", err)
	}
	recoveredPub, err := Ecrecover(msg, sig)
	if err != nil {
		t.Errorf("ECRecover error: %s", err)
	}
63 64
	pubKey := ToECDSAPub(recoveredPub)
	recoveredAddr := PubkeyToAddress(*pubKey)
65 66 67 68 69 70 71 72 73 74 75 76 77
	if addr != recoveredAddr {
		t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
	}

	// should be equal to SigToPub
	recoveredPub2, err := SigToPub(msg, sig)
	if err != nil {
		t.Errorf("ECRecover error: %s", err)
	}
	recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
	if addr != recoveredAddr2 {
		t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
	}
78
}
O
obscuren 已提交
79

80 81
func TestInvalidSign(t *testing.T) {
	if _, err := Sign(make([]byte, 1), nil); err == nil {
82 83
		t.Errorf("expected sign with hash 1 byte to error")
	}
84
	if _, err := Sign(make([]byte, 33), nil); err == nil {
85 86 87
		t.Errorf("expected sign with hash 33 byte to error")
	}
}
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

func TestNewContractAddress(t *testing.T) {
	key, _ := HexToECDSA(testPrivHex)
	addr := common.HexToAddress(testAddrHex)
	genAddr := PubkeyToAddress(key.PublicKey)
	// sanity check before using addr to create contract address
	checkAddr(t, genAddr, addr)

	caddr0 := CreateAddress(addr, 0)
	caddr1 := CreateAddress(addr, 1)
	caddr2 := CreateAddress(addr, 2)
	checkAddr(t, common.HexToAddress("333c3310824b7c685133f2bedb2ca4b8b4df633d"), caddr0)
	checkAddr(t, common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), caddr1)
	checkAddr(t, common.HexToAddress("c9ddedf451bc62ce88bf9292afb13df35b670699"), caddr2)
}

func TestLoadECDSAFile(t *testing.T) {
	keyBytes := common.FromHex(testPrivHex)
	fileName0 := "test_key0"
	fileName1 := "test_key1"
	checkKey := func(k *ecdsa.PrivateKey) {
		checkAddr(t, PubkeyToAddress(k.PublicKey), common.HexToAddress(testAddrHex))
		loadedKeyBytes := FromECDSA(k)
		if !bytes.Equal(loadedKeyBytes, keyBytes) {
			t.Fatalf("private key mismatch: want: %x have: %x", keyBytes, loadedKeyBytes)
		}
	}

	ioutil.WriteFile(fileName0, []byte(testPrivHex), 0600)
	defer os.Remove(fileName0)

	key0, err := LoadECDSA(fileName0)
	if err != nil {
		t.Fatal(err)
	}
	checkKey(key0)

	// again, this time with SaveECDSA instead of manual save:
	err = SaveECDSA(fileName1, key0)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(fileName1)

	key1, err := LoadECDSA(fileName1)
	if err != nil {
		t.Fatal(err)
	}
	checkKey(key1)
}

func TestValidateSignatureValues(t *testing.T) {
	check := func(expected bool, v byte, r, s *big.Int) {
141
		if ValidateSignatureValues(v, r, s, false) != expected {
142 143 144 145 146 147
			t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
		}
	}
	minusOne := big.NewInt(-1)
	one := common.Big1
	zero := common.Big0
148
	secp256k1nMinus1 := new(big.Int).Sub(secp256k1_N, common.Big1)
149 150

	// correct v,r,s
151 152
	check(true, 0, one, one)
	check(true, 1, one, one)
153
	// incorrect v, correct r,s,
154 155
	check(false, 2, one, one)
	check(false, 3, one, one)
156 157

	// incorrect v, combinations of incorrect/correct r,s at lower limit
158 159 160 161 162 163
	check(false, 2, zero, zero)
	check(false, 2, zero, one)
	check(false, 2, one, zero)
	check(false, 2, one, one)

	// correct v for any combination of incorrect r,s
164 165 166 167
	check(false, 0, zero, zero)
	check(false, 0, zero, one)
	check(false, 0, one, zero)

168 169 170
	check(false, 1, zero, zero)
	check(false, 1, zero, one)
	check(false, 1, one, zero)
171 172

	// correct sig with max r,s
173
	check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
174
	// correct v, combinations of incorrect r,s at upper limit
175 176 177
	check(false, 0, secp256k1_N, secp256k1nMinus1)
	check(false, 0, secp256k1nMinus1, secp256k1_N)
	check(false, 0, secp256k1_N, secp256k1_N)
178 179 180

	// current callers ensures r,s cannot be negative, but let's test for that too
	// as crypto package could be used stand-alone
181 182
	check(false, 0, minusOne, one)
	check(false, 0, one, minusOne)
183 184 185 186
}

func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
	sum := f(msg)
187
	if !bytes.Equal(exp, sum) {
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
		t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
	}
}

func checkAddr(t *testing.T, addr0, addr1 common.Address) {
	if addr0 != addr1 {
		t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
	}
}

// test to help Python team with integration of libsecp256k1
// skip but keep it after they are done
func TestPythonIntegration(t *testing.T) {
	kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
	k0, _ := HexToECDSA(kh)

204
	msg0 := Keccak256([]byte("foo"))
205
	sig0, _ := Sign(msg0, k0)
206 207

	msg1 := common.FromHex("00000000000000000000000000000000")
208
	sig1, _ := Sign(msg0, k0)
209

210 211
	t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
	t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
212
}