github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/crypto/mock/mock.go (about)

     1  package mock
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"github.com/gnolang/gno/tm2/pkg/amino"
     8  	"github.com/gnolang/gno/tm2/pkg/crypto"
     9  	"github.com/gnolang/gno/tm2/pkg/random"
    10  )
    11  
    12  // -------------------------------------
    13  // These are fake crypto implementations, useful for testing.
    14  
    15  var _ crypto.PrivKey = PrivKeyMock{}
    16  
    17  // PrivKeyMock implements crypto.PrivKey.
    18  type PrivKeyMock []byte
    19  
    20  // Bytes marshals the privkey using amino encoding w/ type information.
    21  func (privKey PrivKeyMock) Bytes() []byte {
    22  	return amino.MustMarshalAny(privKey)
    23  }
    24  
    25  // Make a fake signature.  Its length is variable.
    26  func (privKey PrivKeyMock) Sign(msg []byte) ([]byte, error) {
    27  	sigBytes := []byte(fmt.Sprintf("signature-for-%X-by-%X", msg, []byte(privKey)))
    28  	return sigBytes, nil
    29  }
    30  
    31  func (privKey PrivKeyMock) PubKey() crypto.PubKey {
    32  	return PubKeyMock(privKey)
    33  }
    34  
    35  func (privKey PrivKeyMock) Equals(other crypto.PrivKey) bool {
    36  	if otherMock, ok := other.(PrivKeyMock); ok {
    37  		return bytes.Equal(privKey, otherMock)
    38  	} else {
    39  		return false
    40  	}
    41  }
    42  
    43  func GenPrivKey() PrivKeyMock {
    44  	randstr := random.RandStr(12)
    45  	return PrivKeyMock([]byte(randstr))
    46  }
    47  
    48  // -------------------------------------
    49  
    50  var _ crypto.PubKey = PubKeyMock{}
    51  
    52  type PubKeyMock []byte
    53  
    54  // Returns address w/ pubkey as suffix (for debugging).
    55  func (pubKey PubKeyMock) Address() crypto.Address {
    56  	if len(pubKey) > 20 {
    57  		panic("PubKeyMock cannot have pubkey greater than 20 bytes")
    58  	}
    59  	addr := crypto.Address{}
    60  	copy(addr[20-len(pubKey):], pubKey)
    61  	return addr
    62  }
    63  
    64  // Bytes marshals the PubKey using amino encoding.
    65  func (pubKey PubKeyMock) Bytes() []byte {
    66  	return amino.MustMarshalAny(pubKey)
    67  }
    68  
    69  func (pubKey PubKeyMock) VerifyBytes(msg []byte, sig []byte) bool {
    70  	sigBytes := []byte(fmt.Sprintf("signature-for-%X-by-%X", msg, []byte(pubKey)))
    71  	return bytes.Equal(sig, sigBytes)
    72  }
    73  
    74  func (pubKey PubKeyMock) String() string {
    75  	return fmt.Sprintf("PubKeyMock{%X}", ([]byte(pubKey))[:])
    76  }
    77  
    78  func (pubKey PubKeyMock) Equals(other crypto.PubKey) bool {
    79  	if otherMock, ok := other.(PubKeyMock); ok {
    80  		return bytes.Equal(pubKey[:], otherMock[:])
    81  	} else {
    82  		return false
    83  	}
    84  }