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

     1  //go:build libsodium
     2  // +build libsodium
     3  
     4  // This libsodium wrap package makes the VRF API in Algorand's libsodium C library available to golang.
     5  
     6  package vrf
     7  
     8  import (
     9  	"bytes"
    10  
    11  	libsodium "github.com/line/ostracon/crypto/vrf/internal/vrf"
    12  )
    13  
    14  type vrfEd25519libsodium struct {
    15  }
    16  
    17  func init() {
    18  	defaultVrf = newVrfEd25519libsodium()
    19  }
    20  
    21  const (
    22  	ProofSize  int = int(libsodium.PROOFBYTES)
    23  	OutputSize int = int(libsodium.OUTPUTBYTES)
    24  )
    25  
    26  func newVrfEd25519libsodium() vrfEd25519libsodium {
    27  	return vrfEd25519libsodium{}
    28  }
    29  
    30  func (base vrfEd25519libsodium) Prove(privateKey []byte, message []byte) (Proof, error) {
    31  	var privKey [libsodium.SECRETKEYBYTES]byte
    32  	copy(privKey[:], privateKey)
    33  	pf, err := libsodium.Prove(&privKey, message)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	return newProof(pf), nil
    38  }
    39  
    40  func (base vrfEd25519libsodium) Verify(publicKey []byte, proof Proof, message []byte) (bool, error) {
    41  	var pubKey [libsodium.PUBLICKEYBYTES]byte
    42  	copy(pubKey[:], publicKey)
    43  	op, err := libsodium.Verify(&pubKey, toArray(proof), message)
    44  	if err != nil {
    45  		return false, err
    46  	}
    47  	hash, err := base.ProofToHash(proof)
    48  	if err != nil {
    49  		return false, err
    50  	}
    51  	return bytes.Compare(op[:], hash) == 0, nil
    52  }
    53  
    54  func (base vrfEd25519libsodium) ProofToHash(proof Proof) (Output, error) {
    55  	op, err := libsodium.ProofToHash(toArray(proof))
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  	return newOutput(op), nil
    60  }
    61  
    62  func newProof(bytes *[libsodium.PROOFBYTES]byte) Proof {
    63  	proof := make([]byte, libsodium.PROOFBYTES)
    64  	copy(proof, bytes[:])
    65  	return proof
    66  }
    67  
    68  func toArray(pf Proof) *[libsodium.PROOFBYTES]byte {
    69  	var array [libsodium.PROOFBYTES]byte
    70  	copy(array[:], pf)
    71  	return &array
    72  }
    73  
    74  func newOutput(bytes *[libsodium.OUTPUTBYTES]byte) Output {
    75  	output := make([]byte, libsodium.OUTPUTBYTES)
    76  	copy(output[:], bytes[:])
    77  	return output
    78  }