package sm2a

import (
	"io"
	"math/big"

	"xdx.jelly/xgcl/gmath"
	"xdx.jelly/xgcl/sm/sm2"
	"xdx.jelly/xgcl/sm/sm3"
)

// ServerSign 服务端根据客户端的协同签名中间数据计算
// in = e || [k_1](P+G)
// out = r || k_2 + r*d_s
func ServerSign(serverKey *sm2.PrivateKey, pk *sm2.PublicKey, in []byte, rand io.Reader) ([]byte, error) {
	k2 := make([]byte, sm2.ByteSize())
	if n, err := rand.Read(k2); n != len(k2) || err != nil {
		return nil, err
	}
	var x, y *big.Int
	tx := new(big.Int)
	ty := new(big.Int)
	r := new(big.Int)
	r.SetBytes(in[:sm3.Size])
	tx.SetBytes(in[sm3.Size : sm3.Size+sm2.ByteSize()])
	ty.SetBytes(in[sm3.Size+sm2.ByteSize() : sm3.Size+2*sm2.ByteSize()])
	x, y = sm2.Curve().Add(pk.X, pk.Y, sm2.BaseX(), sm2.BaseY())
	x, y = sm2.Curve256.ScalarMult(x, y, k2)
	x, y = sm2.Curve().Add(x, y, tx, ty)
	r.Add(r, x)
	r.Mod(r, sm2.OrderN())
	x.Mul(r, serverKey.D)
	y.SetBytes(k2)
	x.Add(x, y)
	x.Mod(x, sm2.OrderN())
	out := make([]byte, 2*sm2.ByteSize())
	copy(out, gmath.BigIntToNByte(r, sm2.ByteSize()))
	copy(out[sm2.ByteSize():], gmath.BigIntToNByte(x, sm2.ByteSize()))

	// 清除中间变量
	gmath.ClearBigInt(x)
	gmath.ClearBigInt(y)
	gmath.ClearBigInt(tx)
	gmath.ClearBigInt(ty)
	gmath.ClearBigInt(r)
	return out, nil
}
