This repository has been archived by the owner on Feb 14, 2023. It is now read-only.
/
multivalidator.go
95 lines (79 loc) · 2.47 KB
/
multivalidator.go
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2016-2018 Stratumn SAS. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package validators
import (
"context"
"crypto/sha256"
"github.com/pkg/errors"
"github.com/stratumn/go-chainscript"
"github.com/stratumn/go-core/monitoring/errorcode"
"github.com/stratumn/go-core/store"
"github.com/stratumn/go-core/types"
)
const (
// MultiValidatorName for monitoring.
MultiValidatorName = "multivalidator"
)
// Errors used by the multi-validator.
var (
ErrNoMatchingValidator = errors.New("link does not match any validator")
)
// MultiValidator is a collection of validators.
type MultiValidator struct {
validators Validators
}
// NewMultiValidator creates a validator that will simply be a collection of
// single-purpose validators.
func NewMultiValidator(validators Validators) Validator {
return &MultiValidator{validators: validators}
}
// ShouldValidate returns true if at least one of the children matches.
func (v MultiValidator) ShouldValidate(link *chainscript.Link) bool {
for _, child := range v.validators {
if child.ShouldValidate(link) {
return true
}
}
return false
}
// Hash concatenates the hashes from its children and hashes the result.
func (v MultiValidator) Hash() ([]byte, error) {
var toHash []byte
for _, child := range v.validators {
childHash, err := child.Hash()
if err != nil {
return nil, err
}
toHash = append(toHash, childHash...)
}
h := sha256.Sum256(toHash)
return h[:], nil
}
// Validate forwards the link to every child validator that matches.
func (v MultiValidator) Validate(ctx context.Context, r store.SegmentReader, l *chainscript.Link) error {
validated := false
for _, child := range v.validators {
if child.ShouldValidate(l) {
validated = true
err := child.Validate(ctx, r, l)
if err != nil {
return err
}
}
}
if !validated {
return types.WrapError(ErrNoMatchingValidator, errorcode.FailedPrecondition, MultiValidatorName, "could not validate link")
}
return nil
}