git.gammaspectra.live/P2Pool/consensus/v3@v3.8.0/monero/address/crypto_test.go (about)

     1  package address
     2  
     3  import (
     4  	"git.gammaspectra.live/P2Pool/consensus/v3/monero/crypto"
     5  	"git.gammaspectra.live/P2Pool/consensus/v3/types"
     6  	"os"
     7  	"path"
     8  	"runtime"
     9  	"strconv"
    10  	"strings"
    11  	"testing"
    12  )
    13  
    14  func init() {
    15  	_, filename, _, _ := runtime.Caller(0)
    16  	// The ".." may change depending on you folder structure
    17  	dir := path.Join(path.Dir(filename), "../..")
    18  	err := os.Chdir(dir)
    19  	if err != nil {
    20  		panic(err)
    21  	}
    22  
    23  }
    24  
    25  func GetTestEntries(name string, n int) chan []string {
    26  	buf, err := os.ReadFile("testdata/crypto_tests.txt")
    27  	if err != nil {
    28  		return nil
    29  	}
    30  	result := make(chan []string)
    31  	go func() {
    32  		defer close(result)
    33  		for _, line := range strings.Split(string(buf), "\n") {
    34  			entries := strings.Split(strings.TrimSpace(line), " ")
    35  			if entries[0] == name && len(entries) >= (n+1) {
    36  				result <- entries[1:]
    37  			}
    38  		}
    39  	}()
    40  	return result
    41  }
    42  
    43  func TestDerivePublicKey(t *testing.T) {
    44  	results := GetTestEntries("derive_public_key", 4)
    45  	if results == nil {
    46  		t.Fatal()
    47  	}
    48  
    49  	hasher := crypto.GetKeccak256Hasher()
    50  	defer crypto.PutKeccak256Hasher(hasher)
    51  
    52  	for e := range results {
    53  		var expectedDerivedKey types.Hash
    54  
    55  		derivation := crypto.PublicKeyBytes(types.MustHashFromString(e[0]))
    56  		outputIndex, _ := strconv.ParseUint(e[1], 10, 0)
    57  
    58  		base := crypto.PublicKeyBytes(types.MustHashFromString(e[2]))
    59  
    60  		result := e[3] == "true"
    61  		if result {
    62  			expectedDerivedKey = types.MustHashFromString(e[4])
    63  		}
    64  
    65  		point2 := base.AsPoint()
    66  
    67  		if result == false && point2 == nil {
    68  			//expected failure
    69  			continue
    70  		} else if point2 == nil {
    71  			t.Errorf("invalid point %s / %s", derivation.String(), base.String())
    72  			continue
    73  		}
    74  
    75  		sharedData := crypto.GetDerivationSharedDataForOutputIndex(&derivation, outputIndex)
    76  
    77  		sharedData2, _ := crypto.GetDerivationSharedDataAndViewTagForOutputIndexNoAllocate(derivation, outputIndex, hasher)
    78  
    79  		if sharedData.AsBytes() != crypto.PrivateKeyFromScalar(&sharedData2).AsBytes() {
    80  			t.Errorf("derive_public_key differs from no_allocate: %s != %s", sharedData, crypto.PrivateKeyFromScalar(&sharedData2))
    81  		}
    82  
    83  		var addr PackedAddress
    84  		addr[0] = base
    85  		derivedKey := GetPublicKeyForSharedData(&addr, sharedData)
    86  
    87  		derivedKey2, _ := GetEphemeralPublicKeyAndViewTagNoAllocate(base.AsPoint().Point(), derivation, outputIndex, hasher)
    88  
    89  		if derivedKey.AsBytes() != derivedKey2 {
    90  			t.Errorf("derive_public_key differs from no_allocate: %s != %s", derivedKey, &derivedKey2)
    91  		}
    92  
    93  		if result {
    94  			if expectedDerivedKey.String() != derivedKey.String() {
    95  				t.Errorf("expected %s, got %s", expectedDerivedKey.String(), derivedKey.String())
    96  			}
    97  		}
    98  	}
    99  }
   100  
   101  var testThrowawayAddress = FromBase58("42ecNLuoGtn1qC9SPSD9FPMNfsv35RE66Eu8WJJtyEHKfEsEiALVVp7GBCeAYFb7PHcSZmz9sDUtRMnKk2as1KfuLuTQJ3i")
   102  var signatureMessage = []byte("test_message")
   103  var signatureMessage2 = []byte("test_message2")
   104  
   105  const (
   106  	SignatureSpendSuccess      = "SigV2DnQYF11xZ1ahLJxddohCroiEJRnUe1tgwD5ksmFMzQ9NcRdbxLPrEdQW3e8w4sLpqhSup5tU9igQqeAR8j7r7Sty"
   107  	SignatureSpendWrongMessage = "SigV26RKRd31efizGHrWHwtYG6EN2MmwvF1rjU4ygZQuDmSxvCJnky1GJTzaM49naQeKvXbaGcnpZ1b3k8gVQLaFMFiBJ"
   108  	SignatureViewSuccess       = "SigV2b7LaAuXrFvPAXwU11SJwHbcXJoKfQ5aBJ9FwMJNxvMTu78AebqNUCWPH1BVfNRvy1f3GCTLjHfWvuRJMZtSHu5uj"
   109  	SignatureViewWrongMessage  = "SigV2AxWUATswZvnHSR5mMRsn9GcJe2gSCv3SbFwHv6J8THkj5KvmR8gUnTidHovZVyxgNHcUuiunM2dfVhbZvBTS6sZZ"
   110  )
   111  
   112  func TestSignature(t *testing.T) {
   113  	result := VerifyMessage(testThrowawayAddress, signatureMessage, SignatureSpendSuccess)
   114  	if result != ResultSuccessSpend {
   115  		t.Fatalf("unexpected %d", result)
   116  	}
   117  	result = VerifyMessage(testThrowawayAddress, signatureMessage, SignatureSpendWrongMessage)
   118  	if result != ResultFail {
   119  		t.Fatalf("unexpected %d", result)
   120  	}
   121  	result = VerifyMessage(testThrowawayAddress, signatureMessage2, SignatureSpendSuccess)
   122  	if result != ResultFail {
   123  		t.Fatalf("unexpected %d", result)
   124  	}
   125  	result = VerifyMessage(testThrowawayAddress, signatureMessage, SignatureViewSuccess)
   126  	if result != ResultFailZeroSpend {
   127  		t.Fatalf("unexpected %d", result)
   128  	}
   129  	result = VerifyMessage(testThrowawayAddress, signatureMessage, SignatureViewWrongMessage)
   130  	if result != ResultFail {
   131  		t.Fatalf("unexpected %d", result)
   132  	}
   133  	result = VerifyMessage(testThrowawayAddress, signatureMessage2, SignatureViewSuccess)
   134  	if result != ResultFail {
   135  		t.Fatalf("unexpected %d", result)
   136  	}
   137  	result = VerifyMessage(&ZeroPrivateKeyAddress, signatureMessage, SignatureViewSuccess)
   138  	if result != ResultFail {
   139  		t.Fatalf("unexpected %d", result)
   140  	}
   141  }