validator.go 1.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// 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 validator contains file-oriented chunk validation implementations
package validator

import (
	"encoding/binary"
	"hash"

	"github.com/ethersphere/bee/pkg/swarm"
	bmtlegacy "github.com/ethersphere/bmt/legacy"
	"golang.org/x/crypto/sha3"
)

var _ swarm.ChunkValidator = (*ContentAddressValidator)(nil)

func hashFunc() hash.Hash {
	return sha3.NewLegacyKeccak256()
}

// ContentAddressValidator validates that the address of a given chunk
// is the content address of its contents
type ContentAddressValidator struct {
}

// New constructs a new ContentAddressValidator
29
func NewContentAddressValidator() swarm.ChunkValidator {
30

31
	return &ContentAddressValidator{}
32 33 34 35
}

// Validate performs the validation check
func (v *ContentAddressValidator) Validate(ch swarm.Chunk) (valid bool) {
36 37
	p := bmtlegacy.NewTreePool(hashFunc, swarm.Branches, bmtlegacy.PoolSize)
	hasher := bmtlegacy.New(p)
38 39 40 41 42 43 44

	// prepare data
	data := ch.Data()
	address := ch.Address()
	span := binary.LittleEndian.Uint64(data[:8])

	// execute hash, compare and return result
45 46
	hasher.Reset()
	err := hasher.SetSpan(int64(span))
47 48 49
	if err != nil {
		return false
	}
50
	_, err = hasher.Write(data[8:])
51 52 53
	if err != nil {
		return false
	}
54
	s := hasher.Sum(nil)
55 56 57

	return address.Equal(swarm.NewAddress(s))
}