package outsource

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"xdx.jelly/xgcl/grand"
	"xdx.jelly/xgcl/sm/sm2"
	"xdx.jelly/xgcl/tpc/sm2/sm2m"
)

// 外包盲签名流程示例
func TestOSBlindSign(t *testing.T) {
	//O、客户端生成paillier密钥
	var err error
	rnd := grand.Reader
	paiPrivKey, paiPubKey, encryptedClientKey1, _, serverKey, publicKey := osGenerateKey(t)

	e := make([]byte, 32)
	rnd.Read(e)

	clientCtx := NewClientBlindSignContext(paiPrivKey, rnd)
	// 1) client -> os

	// 2）os -> client
	osServerCtx := NewOSBlindSignContext()
	pp, err := osServerCtx.Step1(rnd) // P'
	assert.Nil(t, err)

	// 3) client -> hfserver
	ecipher, p, err := clientCtx.Step1(e, pp)
	assert.Nil(t, err)

	// 4) hfserver -> client
	rcipher, s1, s2cipher, err := sm2m.ServerBlindSign(serverKey, ecipher, p, paiPubKey, rnd)
	assert.Nil(t, err)

	// 5) clinet -> os
	s1p, s2p, err := clientCtx.Step2(rcipher, s1, s2cipher)
	assert.Nil(t, err)

	// 6) 外包服务器解析data并计算c,把c发送给客户端
	w, err := osServerCtx.Step2(s1p, s2p, encryptedClientKey1, paiPubKey)
	assert.Nil(t, err)

	// 7) 客户端计算签名值
	sig, err := clientCtx.Step3(w)
	assert.Nil(t, err)

	// 8) 客户端验证签名
	assert.True(t, sm2.Verify(e, publicKey, sig))
}
