github.com/annchain/OG@v0.0.9/p2p/raw_trasport_test.go (about)

     1  // Copyright © 2019 Annchain Authors <EMAIL ADDRESS>
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  package p2p
    15  
    16  import (
    17  	"bytes"
    18  	"crypto/ecdsa"
    19  	"crypto/rand"
    20  	"encoding/hex"
    21  	"fmt"
    22  	"github.com/annchain/OG/common/hexutil"
    23  	"github.com/annchain/OG/deprecated/ogcrypto"
    24  	msg2 "github.com/annchain/OG/types/msg"
    25  	"io/ioutil"
    26  	"net"
    27  	"reflect"
    28  	"testing"
    29  	"time"
    30  )
    31  
    32  func TestRawFrameRW_ReadMsg(t *testing.T) {
    33  	buf := new(bytes.Buffer)
    34  	rw := newRawFrameRW(buf)
    35  	golden := unhex(`000006c28080089401020304`)
    36  
    37  	// Check WriteMsg. This puts a message into the buffer.
    38  	a := msg2.Uints{1, 2, 3, 4}
    39  	b, _ := a.MarshalMsg(nil)
    40  	fmt.Println(hexutil.Encode(b), len(b))
    41  	if err := Send(rw, 8, b); err != nil {
    42  		t.Fatalf("WriteMsg error: %v", err)
    43  	}
    44  	written := buf.Bytes()
    45  	fmt.Println(len(written), hex.EncodeToString(written))
    46  	if !bytes.Equal(written, golden) {
    47  		t.Fatalf("output mismatch:\n  got:  %x\n  want: %x", written, golden)
    48  	}
    49  
    50  	// Check ReadMsg. It reads the message encoded by WriteMsg, which
    51  	// is equivalent to the golden message above.
    52  	msg, err := rw.ReadMsg()
    53  	if err != nil {
    54  		t.Fatalf("ReadMsg error: %v", err)
    55  	}
    56  	if msg.Size != 5 {
    57  		t.Errorf("msg size mismatch: got %d, want %d", msg.Size, 5)
    58  	}
    59  	if msg.Code != 8 {
    60  		t.Errorf("msg code mismatch: got %d, want %d", msg.Code, 8)
    61  	}
    62  	payload, _ := ioutil.ReadAll(msg.Payload)
    63  	wantPayload := unhex("9401020304")
    64  	if !bytes.Equal(payload, wantPayload) {
    65  		t.Errorf("msg payload mismatch:\ngot  %x\nwant %x", payload, wantPayload)
    66  	}
    67  }
    68  
    69  func TestRawEncHandshake(t *testing.T) {
    70  	log.Info("hi")
    71  	for i := 0; i < 10; i++ {
    72  		start := time.Now()
    73  		if err := testRawEncHandshake(nil); err != nil {
    74  			t.Fatalf("i=%d %v", i, err)
    75  		}
    76  		t.Logf("(without token) %d %v\n", i+1, time.Since(start))
    77  	}
    78  	for i := 0; i < 10; i++ {
    79  		tok := make([]byte, shaLen)
    80  		rand.Reader.Read(tok)
    81  		start := time.Now()
    82  		if err := testRawEncHandshake(tok); err != nil {
    83  			t.Fatalf("i=%d %v", i, err)
    84  		}
    85  		t.Logf("(with token) %d %v\n", i+1, time.Since(start))
    86  	}
    87  }
    88  
    89  func testRawEncHandshake(token []byte) error {
    90  	type result struct {
    91  		side   string
    92  		pubkey *ecdsa.PublicKey
    93  		err    error
    94  	}
    95  	var (
    96  		prv0, _  = ogcrypto.GenerateKey()
    97  		prv1, _  = ogcrypto.GenerateKey()
    98  		fd0, fd1 = net.Pipe()
    99  		c0, c1   = newrawTransport(fd0).(*rawTransport), newrawTransport(fd1).(*rawTransport)
   100  		output   = make(chan result)
   101  	)
   102  
   103  	go func() {
   104  		r := result{side: "initiator"}
   105  		defer func() { output <- r }()
   106  		defer fd0.Close()
   107  
   108  		r.pubkey, r.err = c0.doEncHandshake(prv0, &prv1.PublicKey)
   109  		if r.err != nil {
   110  			log.WithError(r.err).Error("error")
   111  			return
   112  		}
   113  		if !reflect.DeepEqual(r.pubkey, &prv1.PublicKey) {
   114  			r.err = fmt.Errorf("remote pubkey mismatch: got %v, want: %v", r.pubkey, &prv1.PublicKey)
   115  		}
   116  	}()
   117  	go func() {
   118  		r := result{side: "receiver"}
   119  		defer func() { output <- r }()
   120  		defer fd1.Close()
   121  
   122  		r.pubkey, r.err = c1.doEncHandshake(prv1, nil)
   123  		if r.err != nil {
   124  			log.WithError(r.err).Error("error")
   125  			return
   126  		}
   127  		if !reflect.DeepEqual(r.pubkey, &prv0.PublicKey) {
   128  			r.err = fmt.Errorf("remote ID mismatch: got %v, want: %v", r.pubkey, &prv0.PublicKey)
   129  		}
   130  	}()
   131  
   132  	// wait for results from both sides
   133  	r1, r2 := <-output, <-output
   134  	if r1.err != nil {
   135  		return fmt.Errorf("%s side error: %v", r1.side, r1.err)
   136  	}
   137  	if r2.err != nil {
   138  		return fmt.Errorf("%s side error: %v", r2.side, r2.err)
   139  	}
   140  	return nil
   141  
   142  }
   143  
   144  func TestCryptoSignature(t *testing.T) {
   145  	prv, _ := ogcrypto.GenerateKey()
   146  	initNonce := make([]byte, shaLen)
   147  	_, err := rand.Read(initNonce)
   148  	if err != nil {
   149  		t.Fatal(err)
   150  	}
   151  	msg := &RawHandshakeMsg{
   152  		Version: 1,
   153  	}
   154  	copy(msg.Nonce[:], initNonce)
   155  	signature, err := ogcrypto.Sign(initNonce, prv)
   156  	if err != nil {
   157  		t.Fatal(err)
   158  	}
   159  	copy(msg.Signature[:], signature)
   160  	copy(msg.Nonce[:], initNonce)
   161  	//ok := ogcrypto.VerifySignature(msg.InitiatorPubkey[:],msg.Nonce[:],msg.Signature[:])
   162  	res, err := ogcrypto.Ecrecover(msg.Nonce[:], msg.Signature[:])
   163  	log.Debug(hex.EncodeToString(res))
   164  	if err != nil {
   165  		t.Fatal("sig failed ", err, hex.EncodeToString(res))
   166  	}
   167  }