2022-10-24 12:36:50 +00:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
2022-10-30 16:40:56 +00:00
|
|
|
"crypto/rand"
|
2022-10-26 16:46:41 +00:00
|
|
|
"encoding/binary"
|
2023-05-20 08:49:05 +00:00
|
|
|
"git.gammaspectra.live/P2Pool/edwards25519"
|
2022-11-01 11:22:00 +00:00
|
|
|
"git.gammaspectra.live/P2Pool/p2pool-observer/types"
|
2022-10-26 16:46:41 +00:00
|
|
|
"unsafe"
|
2022-10-24 12:36:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func RandomScalar() *edwards25519.Scalar {
|
|
|
|
buf := make([]byte, 32)
|
|
|
|
for {
|
|
|
|
if _, err := rand.Read(buf); err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-11-03 14:25:15 +00:00
|
|
|
if !less32(buf, limit) {
|
2022-10-24 12:36:50 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
scalar := BytesToScalar(buf)
|
2022-11-03 14:25:15 +00:00
|
|
|
if scalar.Equal(zeroScalar) == 0 {
|
2022-10-24 12:36:50 +00:00
|
|
|
return scalar
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-10-26 16:46:41 +00:00
|
|
|
|
2022-11-08 13:25:29 +00:00
|
|
|
// DeterministicScalar consensus way of generating a deterministic scalar from given entropy
|
2023-07-18 09:31:08 +00:00
|
|
|
// Slice entropy will have data appended
|
2022-11-08 13:25:29 +00:00
|
|
|
func DeterministicScalar(entropy []byte) *edwards25519.Scalar {
|
2022-10-26 16:46:41 +00:00
|
|
|
|
|
|
|
var counter uint32
|
|
|
|
|
2022-11-08 13:25:29 +00:00
|
|
|
entropy = append(entropy, make([]byte, int(unsafe.Sizeof(counter)))...)
|
|
|
|
n := len(entropy) - int(unsafe.Sizeof(counter))
|
|
|
|
h := GetKeccak256Hasher()
|
|
|
|
defer PutKeccak256Hasher(h)
|
2022-11-07 08:52:35 +00:00
|
|
|
var hash types.Hash
|
2022-11-01 11:22:00 +00:00
|
|
|
|
2022-11-07 22:59:52 +00:00
|
|
|
scalar := GetEdwards25519Scalar()
|
2022-10-26 16:46:41 +00:00
|
|
|
|
|
|
|
for {
|
2022-10-28 09:47:14 +00:00
|
|
|
h.Reset()
|
2022-10-26 16:46:41 +00:00
|
|
|
counter++
|
2022-11-08 13:25:29 +00:00
|
|
|
binary.LittleEndian.PutUint32(entropy[n:], counter)
|
|
|
|
_, _ = h.Write(entropy)
|
|
|
|
HashFastSum(h, hash[:])
|
2022-11-07 08:52:35 +00:00
|
|
|
if !less32(hash[:], limit) {
|
2022-10-26 16:46:41 +00:00
|
|
|
continue
|
|
|
|
}
|
2022-11-07 08:52:35 +00:00
|
|
|
scReduce32(hash[:])
|
|
|
|
scalar, _ = scalar.SetCanonicalBytes(hash[:])
|
2022-10-26 16:46:41 +00:00
|
|
|
|
2022-11-03 14:25:15 +00:00
|
|
|
if scalar.Equal(zeroScalar) == 0 {
|
2022-10-26 16:46:41 +00:00
|
|
|
return scalar
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|