micw/common/signatue.go
2024-11-13 22:10:13 +01:00

53 lines
1.3 KiB
Go

package common
import (
"bytes"
ed "crypto/ed25519"
"crypto/sha512"
"encoding/binary"
"time"
)
func Float64ToBytes(f float64) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(f))
return buf
}
func GetTransactionHash(receiverPubKey []byte, message string, amount float64, createdAt time.Time) []byte {
amountBytes := Float64ToBytes(amount)
hash := sha512.New()
timestamp := createdAt.Unix()
_ = binary.Write(hash, binary.BigEndian, timestamp)
hash.Write([]byte(message))
hash.Write(receiverPubKey)
hash.Write(amountBytes)
return hash.Sum(nil)
}
func getSignMsg(txHash []byte, createdAt time.Time) ([]byte, error) {
buf := bytes.NewBuffer(txHash)
timestamp := createdAt.Unix()
if err := binary.Write(buf, binary.BigEndian, timestamp); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func SingTransaction(key ed.PrivateKey, txHash []byte, signedAt time.Time) (sig []byte, err error) {
msg, err := getSignMsg(txHash, signedAt)
if err != nil {
return nil, err
}
sig = ed.Sign(key, msg)
return sig, nil
}
func VerifyTransactionSignature(key ed.PublicKey, signature []byte, txHash []byte, signedAt time.Time) (valid bool, err error) {
msg, err := getSignMsg(txHash, signedAt)
if err != nil {
return false, err
}
return ed.Verify(key, msg, signature), nil
}