validator_test.go 1.61 KB
Newer Older
lash's avatar
lash committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package soc_test

import (
	"encoding/binary"
	"testing"

	"github.com/ethersphere/bee/pkg/crypto"
	"github.com/ethersphere/bee/pkg/soc"
	"github.com/ethersphere/bee/pkg/swarm"
)

16
// TestValidator verifies that the validator can detect both
lash's avatar
lash committed
17 18
// valid soc chunks, as well as chunks with invalid data and invalid
// address.
19
func TestValidator(t *testing.T) {
lash's avatar
lash committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
	id := make([]byte, soc.IdSize)
	privKey, err := crypto.GenerateSecp256k1Key()
	if err != nil {
		t.Fatal(err)
	}
	signer := crypto.NewDefaultSigner(privKey)

	bmtHashOfFoo := "2387e8e7d8a48c2a9339c97c1dc3461a9a7aa07e994c5cb8b38fd7c1b3e6ea48"
	address := swarm.MustParseHexAddress(bmtHashOfFoo)
	foo := "foo"
	fooLength := len(foo)
	fooBytes := make([]byte, 8+fooLength)
	binary.LittleEndian.PutUint64(fooBytes, uint64(fooLength))
	copy(fooBytes[8:], foo)
	ch := swarm.NewChunk(address, fooBytes)

	sch, err := soc.NewChunk(id, ch, signer)
	if err != nil {
		t.Fatal(err)
	}

	// check valid chunk
acud's avatar
acud committed
42
	if !soc.Valid(sch) {
lash's avatar
lash committed
43 44 45 46 47
		t.Fatal("valid chunk evaluates to invalid")
	}

	// check invalid data
	sch.Data()[0] = 0x01
acud's avatar
acud committed
48
	if soc.Valid(sch) {
lash's avatar
lash committed
49 50 51 52 53 54
		t.Fatal("chunk with invalid data evaluates to valid")
	}

	// check invalid address
	sch.Data()[0] = 0x00
	wrongAddressBytes := sch.Address().Bytes()
55
	wrongAddressBytes[0] = 255 - wrongAddressBytes[0]
lash's avatar
lash committed
56 57
	wrongAddress := swarm.NewAddress(wrongAddressBytes)
	sch = swarm.NewChunk(wrongAddress, sch.Data())
acud's avatar
acud committed
58
	if soc.Valid(sch) {
lash's avatar
lash committed
59 60 61
		t.Fatal("chunk with invalid address evaluates to valid")
	}
}