package outsource

import (
	"crypto/rand"
	"errors"
	"io"
	"math/big"

	"xdx.jelly/xgcl/grand"
	"xdx.jelly/xgcl/he/paillier"
	"xdx.jelly/xgcl/sm/sm2"
)

// osBlindSignContext 外包服务盲协同签名上下文. 使用NewOSBlindSignContext生成.

// 与盲签名外包服务端一致
type OSBlindSignContext struct {
	OSSignContext
}

func NewOSBlindSignContext() *OSBlindSignContext {
	return new(OSBlindSignContext)
}

// 盲签名客户端(与JS一致)
type clientBlindSignContext struct {
	pprivateKey *paillier.PrivateKey
	r           *big.Int
	k1pp        *big.Int
	rnd         io.Reader
}

// NewClientBlindSignContext simple factory for creating clientBlindSignContext
func NewClientBlindSignContext(pprivateKey *paillier.PrivateKey, rnd io.Reader) *clientBlindSignContext {
	ctx := &clientBlindSignContext{
		pprivateKey: pprivateKey,
		rnd:         rnd,
	}
	if rnd == nil {
		ctx.rnd = grand.Reader
	}
	return ctx
}

// Step1 客户端签名第一步 收到外包服务返回的pp, 返回ecipher, p给虎符服务端
//
// pp是外包服务第一步返回的P'=k1p*G
// 返回ecipher = Enc_paillier(e), p = k1p * k2pp * G
func (c *clientBlindSignContext) Step1(e []byte, pp *sm2.PublicKey) (ecipher *paillier.Cipher, p *sm2.PublicKey, err error) {
	c.k1pp, err = rand.Int(c.rnd, sm2.OrderN())
	if err != nil {
		return nil, nil, err
	}
	x, y := sm2.Curve256.ScalarMult(pp.X, pp.Y, c.k1pp.Bytes())

	p = &sm2.PublicKey{Curve: sm2.Curve(), X: x, Y: y}

	ecipher, err = c.pprivateKey.Encrypt(new(big.Int).SetBytes(e), c.rnd)

	return ecipher, p, err
}

// Step2 客户端签名第二步, 收到虎符服务端盲签名接口ServerBlindSign返回的rcipher, s1, s2cipher, 计算s1p, 把s1p, s2p给外包服务
func (c *clientBlindSignContext) Step2(rcipher *paillier.Cipher, s1 *big.Int, s2cipher *paillier.Cipher) (s1p *big.Int, s2p *big.Int, err error) {
	c.r, err = c.pprivateKey.Decrypt(rcipher)
	if err != nil {
		return nil, nil, err
	}
	c.r.Mod(c.r, sm2.OrderN())
	if c.r.Sign() == 0 {
		return nil, nil, errors.New("Outsource sign failed, r = 0")
	}
	s1p = c.k1pp
	c.k1pp = nil
	s1p.Mul(s1p, s1).Mod(s1p, sm2.OrderN())
	s2p, err = c.pprivateKey.Decrypt(s2cipher)
	s2p.Mod(s2p, sm2.OrderN())
	if err != nil {
		return nil, nil, err
	}
	return s1p, s2p, nil
}

// Step3 客户端签名第三步, 收到外包服务返回的w = Enc(s+r), 输出签名
func (c *clientBlindSignContext) Step3(w *paillier.Cipher) (*sm2.Signature, error) {
	s, err := c.pprivateKey.Decrypt(w)
	if err != nil {
		return nil, err
	}
	if s.Sign() == 0 {
		return nil, errors.New("Outsource sign failed, s = 0")
	}
	s.Sub(s, c.r).Mod(s, sm2.OrderN())
	r := c.r
	c.r = nil
	return &sm2.Signature{R: r, S: s}, nil
}
