github.com/cloudflare/circl@v1.5.0/ecc/bls12381/encoding_test.go (about)

     1  package bls12381
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os"
     7  	"testing"
     8  
     9  	"github.com/cloudflare/circl/internal/test"
    10  )
    11  
    12  func isEqual(p, q interface{}) bool {
    13  	switch P := p.(type) {
    14  	case *G1:
    15  		return P.IsEqual(q.(*G1))
    16  	case *G2:
    17  		return P.IsEqual(q.(*G2))
    18  	default:
    19  		panic("bad type")
    20  	}
    21  }
    22  
    23  func addGenerator(p interface{}) {
    24  	switch P := p.(type) {
    25  	case *G1:
    26  		P.Add(P, G1Generator())
    27  	case *G2:
    28  		P.Add(P, G2Generator())
    29  	default:
    30  		panic("bad type")
    31  	}
    32  }
    33  
    34  func testSerialVector(t *testing.T, file io.Reader, v *serialVector) {
    35  	var bP []byte
    36  	bQ := make([]byte, v.length)
    37  	v.P.SetIdentity()
    38  	for i := 0; i < 1000; i++ {
    39  		n, err := file.Read(bQ)
    40  		if n != v.length || err != nil {
    41  			t.Fatalf("error reading %v file: %v", v.fileName, err)
    42  		}
    43  		test.CheckNoErr(t, v.Q.SetBytes(bQ), "failed deserialization")
    44  
    45  		if !isEqual(v.P, v.Q) {
    46  			test.ReportError(t, v.P, v.Q, i)
    47  		}
    48  
    49  		if v.compressed {
    50  			bP = v.P.BytesCompressed()
    51  		} else {
    52  			bP = v.P.Bytes()
    53  		}
    54  		if !bytes.Equal(bP, bQ) {
    55  			test.ReportError(t, bP, bQ, i)
    56  		}
    57  		addGenerator(v.P)
    58  	}
    59  }
    60  
    61  type serialVector struct {
    62  	fileName   string
    63  	length     int
    64  	compressed bool
    65  	P, Q       interface {
    66  		SetIdentity()
    67  		SetBytes([]byte) error
    68  		Bytes() []byte
    69  		BytesCompressed() []byte
    70  	}
    71  }
    72  
    73  func TestSerializationVector(t *testing.T) {
    74  	for _, vv := range []serialVector{
    75  		{"g1_uncompressed", G1Size, false, new(G1), new(G1)},
    76  		{"g1_compressed", G1SizeCompressed, true, new(G1), new(G1)},
    77  		{"g2_uncompressed", G2Size, false, new(G2), new(G2)},
    78  		{"g2_compressed", G2SizeCompressed, true, new(G2), new(G2)},
    79  	} {
    80  		v := vv
    81  		file, err := os.Open("testdata/" + v.fileName + "_valid_test_vectors.dat")
    82  		if err != nil {
    83  			t.Fatalf("file %v can not be opened: %v", v.fileName, err)
    84  		}
    85  		defer file.Close()
    86  
    87  		t.Run(v.fileName[:7], func(t *testing.T) { testSerialVector(t, file, &v) })
    88  	}
    89  }