github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/utilities/crypto/crypto_test.go (about)

     1  package crypto
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/ecdsa"
     6  	"encoding/hex"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"math/big"
    10  	"os"
    11  	"reflect"
    12  	"testing"
    13  
    14  	"github.com/neatio-net/neatio/utilities/common"
    15  	"github.com/neatio-net/neatio/utilities/common/hexutil"
    16  )
    17  
    18  var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791"
    19  
    20  var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
    21  
    22  func TestKeccak256Hash(t *testing.T) {
    23  	msg := []byte("abc")
    24  	exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
    25  	checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
    26  }
    27  
    28  func TestToECDSAErrors(t *testing.T) {
    29  	if _, err := HexToECDSA("0000000000000000000000000000000000000000000000000000000000000000"); err == nil {
    30  		t.Fatal("HexToECDSA should've returned error")
    31  	}
    32  	if _, err := HexToECDSA("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); err == nil {
    33  		t.Fatal("HexToECDSA should've returned error")
    34  	}
    35  }
    36  
    37  func BenchmarkSha3(b *testing.B) {
    38  	a := []byte("hello world")
    39  	for i := 0; i < b.N; i++ {
    40  		Keccak256(a)
    41  	}
    42  }
    43  
    44  func TestSign(t *testing.T) {
    45  	key, _ := HexToECDSA(testPrivHex)
    46  	addr := common.HexToAddress(testAddrHex)
    47  
    48  	msg := Keccak256([]byte("foo"))
    49  	sig, err := Sign(msg, key)
    50  	if err != nil {
    51  		t.Errorf("Sign error: %s", err)
    52  	}
    53  	recoveredPub, err := Ecrecover(msg, sig)
    54  	if err != nil {
    55  		t.Errorf("ECRecover error: %s", err)
    56  	}
    57  	pubKey, _ := UnmarshalPubkey(recoveredPub)
    58  	recoveredAddr := PubkeyToAddress(*pubKey)
    59  	if addr != recoveredAddr {
    60  		t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
    61  	}
    62  
    63  	recoveredPub2, err := SigToPub(msg, sig)
    64  	if err != nil {
    65  		t.Errorf("ECRecover error: %s", err)
    66  	}
    67  	recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
    68  	if addr != recoveredAddr2 {
    69  		t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
    70  	}
    71  }
    72  
    73  func TestUnmarshalPubkey(t *testing.T) {
    74  	key, err := UnmarshalPubkey(nil)
    75  	if err != errInvalidPubkey || key != nil {
    76  		t.Fatalf("expected error, got %v, %v", err, key)
    77  	}
    78  	key, err = UnmarshalPubkey([]byte{1, 2, 3})
    79  	if err != errInvalidPubkey || key != nil {
    80  		t.Fatalf("expected error, got %v, %v", err, key)
    81  	}
    82  
    83  	var (
    84  		enc, _ = hex.DecodeString("04760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1b01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d")
    85  		dec    = &ecdsa.PublicKey{
    86  			Curve: S256(),
    87  			X:     hexutil.MustDecodeBig("0x760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1"),
    88  			Y:     hexutil.MustDecodeBig("0xb01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d"),
    89  		}
    90  	)
    91  	key, err = UnmarshalPubkey(enc)
    92  	if err != nil {
    93  		t.Fatalf("expected no error, got %v", err)
    94  	}
    95  	if !reflect.DeepEqual(key, dec) {
    96  		t.Fatal("wrong result")
    97  	}
    98  }
    99  
   100  func TestInvalidSign(t *testing.T) {
   101  	if _, err := Sign(make([]byte, 1), nil); err == nil {
   102  		t.Errorf("expected sign with hash 1 byte to error")
   103  	}
   104  	if _, err := Sign(make([]byte, 33), nil); err == nil {
   105  		t.Errorf("expected sign with hash 33 byte to error")
   106  	}
   107  }
   108  
   109  func TestNewContractAddress(t *testing.T) {
   110  	key, _ := HexToECDSA(testPrivHex)
   111  	addr := common.HexToAddress(testAddrHex)
   112  	fmt.Printf("byte addr=%v\n", addr)
   113  	genAddr := PubkeyToAddress(key.PublicKey)
   114  	fmt.Printf("gen addr=%v\n", addr)
   115  	checkAddr(t, genAddr, addr)
   116  
   117  	caddr0 := CreateAddress(addr, 0)
   118  	caddr1 := CreateAddress(addr, 1)
   119  	caddr2 := CreateAddress(addr, 2)
   120  	checkAddr(t, common.HexToAddress("3343384b35786b757666344431674c5376684346413467674b73506b7268316f4c31"), caddr0)
   121  	checkAddr(t, common.HexToAddress("334b713575554c4c594e6e65546831544e7a4352767377626e554a55334a6d6f3773"), caddr1)
   122  	checkAddr(t, common.HexToAddress("3339416a5166364c48454346596a316e45566a67414d675250723578414d69334b67"), caddr2)
   123  }
   124  
   125  func TestLoadECDSAFile(t *testing.T) {
   126  	keyBytes := common.FromHex(testPrivHex)
   127  	fileName0 := "test_key0"
   128  	fileName1 := "test_key1"
   129  	checkKey := func(k *ecdsa.PrivateKey) {
   130  		checkAddr(t, PubkeyToAddress(k.PublicKey), common.HexToAddress(testAddrHex))
   131  		loadedKeyBytes := FromECDSA(k)
   132  		if !bytes.Equal(loadedKeyBytes, keyBytes) {
   133  			t.Fatalf("private key mismatch: want: %x have: %x", keyBytes, loadedKeyBytes)
   134  		}
   135  	}
   136  
   137  	ioutil.WriteFile(fileName0, []byte(testPrivHex), 0600)
   138  	defer os.Remove(fileName0)
   139  
   140  	key0, err := LoadECDSA(fileName0)
   141  	if err != nil {
   142  		t.Fatal(err)
   143  	}
   144  	checkKey(key0)
   145  
   146  	err = SaveECDSA(fileName1, key0)
   147  	if err != nil {
   148  		t.Fatal(err)
   149  	}
   150  	defer os.Remove(fileName1)
   151  
   152  	key1, err := LoadECDSA(fileName1)
   153  	if err != nil {
   154  		t.Fatal(err)
   155  	}
   156  	checkKey(key1)
   157  }
   158  
   159  func TestValidateSignatureValues(t *testing.T) {
   160  	check := func(expected bool, v byte, r, s *big.Int) {
   161  		if ValidateSignatureValues(v, r, s, false) != expected {
   162  			t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
   163  		}
   164  	}
   165  	minusOne := big.NewInt(-1)
   166  	one := common.Big1
   167  	zero := common.Big0
   168  	secp256k1nMinus1 := new(big.Int).Sub(secp256k1N, common.Big1)
   169  
   170  	check(true, 0, one, one)
   171  	check(true, 1, one, one)
   172  
   173  	check(false, 2, one, one)
   174  	check(false, 3, one, one)
   175  
   176  	check(false, 2, zero, zero)
   177  	check(false, 2, zero, one)
   178  	check(false, 2, one, zero)
   179  	check(false, 2, one, one)
   180  
   181  	check(false, 0, zero, zero)
   182  	check(false, 0, zero, one)
   183  	check(false, 0, one, zero)
   184  
   185  	check(false, 1, zero, zero)
   186  	check(false, 1, zero, one)
   187  	check(false, 1, one, zero)
   188  
   189  	check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
   190  
   191  	check(false, 0, secp256k1N, secp256k1nMinus1)
   192  	check(false, 0, secp256k1nMinus1, secp256k1N)
   193  	check(false, 0, secp256k1N, secp256k1N)
   194  
   195  	check(false, 0, minusOne, one)
   196  	check(false, 0, one, minusOne)
   197  }
   198  
   199  func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
   200  	sum := f(msg)
   201  	if !bytes.Equal(exp, sum) {
   202  		t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
   203  	}
   204  }
   205  
   206  func checkAddr(t *testing.T, addr0, addr1 common.Address) {
   207  	if addr0 != addr1 {
   208  		t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
   209  	}
   210  }
   211  
   212  func TestPythonIntegration(t *testing.T) {
   213  	kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
   214  	k0, _ := HexToECDSA(kh)
   215  
   216  	msg0 := Keccak256([]byte("foo"))
   217  	sig0, _ := Sign(msg0, k0)
   218  
   219  	msg1 := common.FromHex("00000000000000000000000000000000")
   220  	sig1, _ := Sign(msg0, k0)
   221  
   222  	t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
   223  	t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
   224  }
   225  
   226  func TestEthAddress(t *testing.T) {
   227  	privateKeyHex := "c15c038a5a9f8f948a2ac0eb102c249e4ae1c4fa1e0971b50c63db46dc5fcf8b"
   228  	privateKey, err := HexToECDSA(privateKeyHex)
   229  	if err != nil {
   230  		t.Fatalf("failed to decode private key %v\n", err)
   231  	}
   232  
   233  	publicKey := FromECDSAPub(&privateKey.PublicKey)
   234  
   235  	ethAddress := hexutil.Encode(Keccak256(publicKey[1:])[12:])
   236  
   237  	fmt.Printf("ethereum address %v\n", ethAddress)
   238  
   239  	addrHex := "0xc84e9eba34cfb0690ae607207a64d662686d17f7"
   240  
   241  	addrBytes := common.HexToAddress(addrHex).Big()
   242  
   243  	b, _ := new(big.Int).SetString("862381068151338842291839054294319045153034925969", 10)
   244  
   245  	addrBig := common.BigToAddress(b).String()
   246  
   247  	fmt.Printf("address bytes %v, address big %v\n", addrBytes, addrBig)
   248  }