github.com/line/ostracon@v1.0.10-0.20230328032236-7f20145f065d/crypto/vrf/vrf_coniks.go (about)

     1  //go:build coniks
     2  // +build coniks
     3  
     4  package vrf
     5  
     6  import (
     7  	"bytes"
     8  	"errors"
     9  
    10  	coniks "github.com/coniks-sys/coniks-go/crypto/vrf"
    11  )
    12  
    13  type vrfEd25519coniks struct {
    14  	generatedHash  []byte
    15  	generatedProof []byte
    16  }
    17  
    18  func init() {
    19  	defaultVrf = newVrfEd25519coniks()
    20  }
    21  
    22  const (
    23  	ProofSize  int = coniks.ProofSize
    24  	OutputSize int = coniks.Size
    25  )
    26  
    27  func newVrfEd25519coniks() *vrfEd25519coniks {
    28  	return &vrfEd25519coniks{nil, nil}
    29  }
    30  
    31  func newVrfEd25519coniksForVerifier(output Output, proof Proof) *vrfEd25519coniks {
    32  	return &vrfEd25519coniks{output, proof}
    33  }
    34  
    35  func (base *vrfEd25519coniks) Prove(privateKey []byte, message []byte) (Proof, error) {
    36  	if len(privateKey) != coniks.PrivateKeySize {
    37  		return nil, errors.New("private key size is invalid")
    38  	}
    39  	coniksPrivKey := coniks.PrivateKey(make([]byte, coniks.PrivateKeySize))
    40  	copy(coniksPrivKey, privateKey)
    41  	hash, proof := coniksPrivKey.Prove(message)
    42  	base.generatedHash = hash
    43  	base.generatedProof = proof
    44  	return proof, nil
    45  }
    46  
    47  func (base *vrfEd25519coniks) Verify(publicKey []byte, proof Proof, message []byte) (bool, error) {
    48  	if base.generatedHash == nil {
    49  		return false, errors.New("vrf hash was not given")
    50  	}
    51  	if !bytes.Equal(base.generatedProof, proof) {
    52  		return false, errors.New("proof is not same to the previously generated proof")
    53  	}
    54  	if len(publicKey) != coniks.PublicKeySize {
    55  		return false, errors.New("public key size is invalid")
    56  	}
    57  	coniksPubKey := coniks.PublicKey(make([]byte, coniks.PublicKeySize))
    58  	copy(coniksPubKey, publicKey)
    59  	return coniksPubKey.Verify(message, base.generatedHash, proof), nil
    60  }
    61  
    62  func (base *vrfEd25519coniks) ProofToHash(proof Proof) (Output, error) {
    63  	if base.generatedHash == nil {
    64  		return nil, errors.New("vrf hash was not given")
    65  	}
    66  	if !bytes.Equal(base.generatedProof, proof) {
    67  		return nil, errors.New("proof is not same to the previously generated proof")
    68  	}
    69  	return base.generatedHash, nil
    70  }