/
cryptosort.go
42 lines (34 loc) · 1.55 KB
/
cryptosort.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
// Copyright (c) 2019 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package crypto
import (
"bytes"
"sort"
"github.com/iotexproject/go-pkgs/byteutil"
"github.com/iotexproject/go-pkgs/hash"
)
var (
// CryptoSeed is a hardcoded seed that will be replaced by a seed produced dynamically.
CryptoSeed = []byte{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}
)
// Sort sorts a given slices of hashes cryptographically using hash function
func Sort(hashes [][]byte, nonce uint64) {
nb := byteutil.Uint64ToBytes(nonce)
sort.Slice(hashes, func(i, j int) bool {
hi := hash.Hash256b(append(append(hashes[i], CryptoSeed...), nb...))
hj := hash.Hash256b(append(append(hashes[j], CryptoSeed...), nb...))
return bytes.Compare(hi[:], hj[:]) < 0
})
}
// SortCandidates sorts a given slices of hashes cryptographically using hash function
func SortCandidates(candidates []string, epochNum uint64, cryptoSeed []byte) {
nb := byteutil.Uint64ToBytes(epochNum)
sort.Slice(candidates, func(i, j int) bool {
hi := hash.Hash256b(append(append([]byte(candidates[i]), cryptoSeed...), nb...))
hj := hash.Hash256b(append(append([]byte(candidates[j]), cryptoSeed...), nb...))
return bytes.Compare(hi[:], hj[:]) < 0
})
}