bindbox-game/internal/api/admin/draw_verify_helper.go
邹方成 81e2fb5a75
Some checks failed
Build docker and publish / linux (1.24.5) (push) Failing after 41s
feat(activity): 实现抽奖随机承诺与验证功能
新增随机种子生成与验证逻辑,包括:
1. 添加随机承诺生成接口
2. 实现抽奖执行与验证流程
3. 新增批量用户创建与删除功能
4. 添加抽奖收据记录表
5. 完善配置管理与错误码

新增测试用例验证随机算法正确性
2025-11-15 20:39:13 +08:00

88 lines
2.1 KiB
Go

package admin
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"bindbox-game/configs"
)
func unmaskSeed(enc []byte, issueID int64, version int32) []byte {
key := masterKey()
if key == nil {
return enc
}
ks := deriveMask(key, issueID, version)
out := make([]byte, len(enc))
for i := range enc {
out[i] = enc[i] ^ ks[i%len(ks)]
}
return out
}
func masterKey() []byte {
s := configs.Get().Random.CommitMasterKey
if s == "" {
return nil
}
b, err := hex.DecodeString(s)
if err != nil || len(b) == 0 {
return nil
}
return b
}
func deriveMask(key []byte, issueID int64, version int32) []byte {
m := hmac.New(sha256.New, key)
buf := make([]byte, 12)
binary.BigEndian.PutUint64(buf[:8], uint64(issueID))
binary.BigEndian.PutUint32(buf[8:12], uint32(version))
m.Write(buf)
sum := m.Sum(nil)
return sum[:32]
}
func encodeMessage(algo string, roundId int64, drawId int64, clientId int64, clientSeed []byte, nonce uint64, itemsRoot []byte, weightsTotal uint64) []byte {
var buf []byte
buf = appendUint32String(buf, algo)
buf = appendUint64(buf, uint64(roundId))
buf = appendUint64(buf, uint64(drawId))
buf = appendUint64(buf, uint64(clientId))
buf = appendUint32Bytes(buf, clientSeed)
buf = appendUint64(buf, nonce)
buf = append(buf, itemsRoot...)
buf = appendUint64(buf, weightsTotal)
return buf
}
func appendUint32String(b []byte, s string) []byte {
bs := []byte(s)
nb := make([]byte, 4)
binary.BigEndian.PutUint32(nb, uint32(len(bs)))
b = append(b, nb...)
b = append(b, bs...)
return b
}
func appendUint32Bytes(b []byte, bs []byte) []byte {
nb := make([]byte, 4)
binary.BigEndian.PutUint32(nb, uint32(len(bs)))
b = append(b, nb...)
b = append(b, bs...)
return b
}
func appendUint64(b []byte, v uint64) []byte {
nb := make([]byte, 8)
binary.BigEndian.PutUint64(nb, v)
b = append(b, nb...)
return b
}
func hmacSha256(key []byte, msg []byte) []byte {
m := hmac.New(sha256.New, key)
m.Write(msg)
return m.Sum(nil)
}