-
Notifications
You must be signed in to change notification settings - Fork 0
/
entropy.go
80 lines (67 loc) · 2.17 KB
/
entropy.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
/*
* Copyright 2019 Insolar Technologies
*
* 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 entropy
import (
"encoding/binary"
"errors"
"github.com/insolar/insolar/core"
)
// SelectByEntropy selects value from list based on provided crypto scheme and entropy data.
// Beware: requires sorted values for deterministic selection!
func SelectByEntropy(
scheme core.PlatformCryptographyScheme,
entropy []byte,
values []interface{},
count int,
) ([]interface{}, error) {
if count > len(values) {
return nil, errors.New("count value should be less than values size")
}
if count == 1 && count == len(values) {
return values, nil
}
// prepare buffers and objects before selection loop
h := scheme.ReferenceHasher()
selected := make([]interface{}, count)
indexes := make([]int, len(values))
for i := 0; i < len(values); i++ {
indexes[i] = i
}
entopylen := len(entropy)
hashbytes := make([]byte, entopylen+8)
copy(hashbytes[:entopylen], entropy)
hashUint64Buf := make([]byte, 8)
ucount := uint64(count)
for i := uint64(0); i < ucount; i++ {
h.Reset()
// put i-step as hash input (convert to variadic uint)
binary.LittleEndian.PutUint64(hashbytes[entopylen:], i)
if _, err := h.Write(hashbytes); err != nil {
return nil, err
}
hsum := h.Sum(nil)
// convert first hash bytes to uint64
copy(hashUint64Buf, hsum)
n := binary.LittleEndian.Uint64(hashUint64Buf)
// calc and get index from list of indexes and remove it
idx2idx := n % uint64(len(indexes))
idx := indexes[idx2idx]
indexes[idx2idx] = indexes[len(indexes)-1]
indexes = indexes[:len(indexes)-1]
selected[i] = values[idx]
}
return selected, nil
}