github.com/iotexproject/iotex-core@v1.14.1-rc1/crypto/cryptosort.go (about) 1 // Copyright (c) 2019 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package crypto 7 8 import ( 9 "bytes" 10 "sort" 11 12 "github.com/iotexproject/go-pkgs/hash" 13 "github.com/iotexproject/iotex-core/pkg/enc" 14 ) 15 16 var ( 17 // CryptoSeed is a hardcoded seed that will be replaced by a seed produced dynamically. 18 CryptoSeed = []byte{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef} 19 ) 20 21 // Sort sorts a given slices of hashes cryptographically using hash function 22 func Sort(hashes [][]byte, nonce uint64) { 23 nb := make([]byte, 8) 24 enc.MachineEndian.PutUint64(nb, nonce) 25 26 hashMap := make(map[string]hash.Hash256) 27 for _, h := range hashes { 28 hash256 := hash.Hash256b(append(append(h, CryptoSeed...), nb...)) 29 hashMap[string(h)] = hash256 30 } 31 32 sort.Slice(hashes, func(i, j int) bool { 33 hi := hashMap[string(hashes[i])] 34 hj := hashMap[string(hashes[j])] 35 return bytes.Compare(hi[:], hj[:]) < 0 36 }) 37 } 38 39 // SortCandidates sorts a given slices of hashes cryptographically using hash function 40 func SortCandidates(candidates []string, epochNum uint64, cryptoSeed []byte) { 41 nb := make([]byte, 8) 42 enc.MachineEndian.PutUint64(nb, epochNum) 43 44 hashMap := make(map[string]hash.Hash256) 45 for _, cand := range candidates { 46 hash256 := hash.Hash256b(append(append([]byte(cand), cryptoSeed...), nb...)) 47 hashMap[cand] = hash256 48 } 49 50 sort.Slice(candidates, func(i, j int) bool { 51 hi := hashMap[candidates[i]] 52 hj := hashMap[candidates[j]] 53 return bytes.Compare(hi[:], hj[:]) < 0 54 }) 55 }