From bcc0e46568546b67feea647e658e201e4b0c59ce Mon Sep 17 00:00:00 2001 From: Luke Plaster Date: Thu, 16 May 2019 19:42:14 +0800 Subject: [PATCH] Add initial crypto and tests --- common/math/random.go | 63 ++++++++ common/math/random_test.go | 35 +++++ crypto/commitments/hash_commitment.go | 113 +++++++++++++ crypto/commitments/hash_commitment_test.go | 55 +++++++ crypto/paillier/paillier.go | 163 +++++++++++++++++++ crypto/paillier/paillier_test.go | 79 ++++++++++ crypto/schnorrZK/schnorrZK.go | 68 ++++++++ crypto/schnorrZK/schnorrZK_test.go | 32 ++++ crypto/vss/feldman_vss.go | 175 +++++++++++++++++++++ crypto/vss/feldman_vss_test.go | 96 +++++++++++ go.mod | 13 ++ go.sum | 49 ++++++ 12 files changed, 941 insertions(+) create mode 100644 common/math/random.go create mode 100644 common/math/random_test.go create mode 100644 crypto/commitments/hash_commitment.go create mode 100644 crypto/commitments/hash_commitment_test.go create mode 100644 crypto/paillier/paillier.go create mode 100644 crypto/paillier/paillier_test.go create mode 100644 crypto/schnorrZK/schnorrZK.go create mode 100644 crypto/schnorrZK/schnorrZK_test.go create mode 100644 crypto/vss/feldman_vss.go create mode 100644 crypto/vss/feldman_vss_test.go create mode 100644 go.mod create mode 100644 go.sum diff --git a/common/math/random.go b/common/math/random.go new file mode 100644 index 0000000..dfa7cde --- /dev/null +++ b/common/math/random.go @@ -0,0 +1,63 @@ +package math + +import ( + "math/big" + "math/rand" + "time" +) + +func GetRandomInt(length int) *big.Int { + // NewInt allocates and returns a new Int set to x. + one := big.NewInt(1) + // Lsh sets z = x << n and returns z. + maxi := new(big.Int).Lsh(one, uint(length)) + + // New returns a new Rand that uses random values from src to generate other random values. + // NewSource returns a new pseudo-random Source seeded with the given value. + random := rand.New(rand.NewSource(time.Now().UnixNano())) + // Returns a pseudo-random number in (0, n) + return new(big.Int).Rand(random, maxi) +} + +func GetRandomPositiveInt(n *big.Int) *big.Int { + var rnd *big.Int + zero := big.NewInt(0) + + for { + rnd = GetRandomInt(n.BitLen()) + if rnd.Cmp(n) < 0 && rnd.Cmp(zero) >= 0 { + break + } + } + + return rnd +} + +func GetRandomPositiveIntStar(n *big.Int) *big.Int { + var rnd *big.Int + gcd := big.NewInt(0) + one := big.NewInt(1) + + for { + rnd = GetRandomInt(n.BitLen()) + if rnd.Cmp(n) < 0 && rnd.Cmp(one) >= 0 && + gcd.GCD(nil, nil, rnd, n).Cmp(one) == 0 { + break + } + } + + return rnd +} + +func GetRandomPrimeInt(length int) *big.Int { + var rnd *big.Int + + for { + rnd = GetRandomInt(length) + if rnd.ProbablyPrime(512) { + break + } + } + + return rnd +} diff --git a/common/math/random_test.go b/common/math/random_test.go new file mode 100644 index 0000000..12f4fa6 --- /dev/null +++ b/common/math/random_test.go @@ -0,0 +1,35 @@ +package math_test + +import ( + "testing" + + "tss-lib/common/math" +) + +const ( + randomIntLength = 1024 +) + +func TestGetRandomInt(t *testing.T) { + rndInt := math.GetRandomInt(randomIntLength) + t.Log(rndInt) +} + +func TestGetRandomPositiveInt(t *testing.T) { + rndInt := math.GetRandomInt(randomIntLength) + t.Log(rndInt) + rndIntZn := math.GetRandomPositiveInt(rndInt) + t.Log(rndIntZn) +} + +func TestGetRandomPositiveIntStar(t *testing.T) { + rndInt := math.GetRandomInt(randomIntLength) + t.Log(rndInt) + rndIntZnStar := math.GetRandomPositiveIntStar(rndInt) + t.Log(rndIntZnStar) +} + +func TestGetRandomPrimeInt(t *testing.T) { + primeInt := math.GetRandomPrimeInt(randomIntLength) + t.Log(primeInt) +} diff --git a/crypto/commitments/hash_commitment.go b/crypto/commitments/hash_commitment.go new file mode 100644 index 0000000..2133e77 --- /dev/null +++ b/crypto/commitments/hash_commitment.go @@ -0,0 +1,113 @@ +// ported from: +// https://github.com/KZen-networks/curv/blob/78a70f43f5eda376e5888ce33aec18962f572bbe/src/cryptographic_primitives/commitments/hash_commitment.rs + +package commitments + +import ( + "math/big" + + "golang.org/x/crypto/sha3" + + "tss-lib/common/math" +) + +const ( + HashLength = 256 +) + +type ( + HashCommitment = *big.Int + HashDeCommitment = []*big.Int + + HashCommitDecommit struct { + C HashCommitment + D HashDeCommitment + } +) + + +func NewHashCommitment(secrets ...*big.Int) (cmt *HashCommitDecommit, err error) { + cmt = &HashCommitDecommit{} + + // Generate the random num + rnd := math.GetRandomInt(HashLength) + + // TODO revise use of legacy keccak256 which uses non-standard padding + keccak256 := sha3.NewLegacyKeccak256() + + _, err = keccak256.Write(rnd.Bytes()) + if err != nil { + return + } + + for _, secret := range secrets { + _, err = keccak256.Write(secret.Bytes()) + if err != nil { + return + } + } + + digestKeccak256 := keccak256.Sum(nil) + + // second, hash with the SHA3-256 + sha3256 := sha3.New256() + + _, err = sha3256.Write(digestKeccak256) + if err != nil { + return + } + + digest := sha3256.Sum(nil) + + // convert the hash ([]byte) to big.Int + digestBigInt := new(big.Int).SetBytes(digest) + + D := []*big.Int{rnd} + D = append(D, secrets...) + + cmt.C = digestBigInt + cmt.D = D + + return +} + +func (cmt *HashCommitDecommit) Verify() (bool, error) { + C, D := cmt.C, cmt.D + + // TODO revise use of legacy keccak256 which uses non-standard padding + keccak256 := sha3.NewLegacyKeccak256() + for _, secret := range D { + _, err := keccak256.Write(secret.Bytes()) + if err != nil { + return false, err + } + } + digestKeccak256 := keccak256.Sum(nil) + + sha3256 := sha3.New256() + _, err := sha3256.Write(digestKeccak256) + if err != nil { + return false, err + } + computeDigest := sha3256.Sum(nil) + + computeDigestBigInt := new(big.Int).SetBytes(computeDigest) + + if computeDigestBigInt.Cmp(C) == 0 { + return true, nil + } else { + return false, nil + } +} + +func (cmt *HashCommitDecommit) DeCommit() (bool, HashDeCommitment, error) { + result, err := cmt.Verify() + if err != nil { + return false, nil, err + } + if result { + return true, cmt.D[1:], nil + } else { + return false, nil, nil + } +} diff --git a/crypto/commitments/hash_commitment_test.go b/crypto/commitments/hash_commitment_test.go new file mode 100644 index 0000000..8e0d295 --- /dev/null +++ b/crypto/commitments/hash_commitment_test.go @@ -0,0 +1,55 @@ +package commitments_test + +import ( + "math/big" + "testing" + + "github.com/stretchr/testify/assert" + + "tss-lib/crypto/commitments" +) + +func TestCommit(t *testing.T) { + one := big.NewInt(1) + zero := big.NewInt(0) + + commitment, err := commitments.NewHashCommitment(zero, one) + assert.NoError(t, err) + + t.Log(commitment.C) + t.Log(commitment.D) +} + +func TestVerify(t *testing.T) { + one := big.NewInt(1) + zero := big.NewInt(0) + + commitment, err := commitments.NewHashCommitment(zero, one) + assert.NoError(t, err) + + pass, err := commitment.Verify() + assert.NoError(t, err) + + t.Log(commitment.C) + t.Log(commitment.D) + + assert.True(t, pass, "must pass") +} + +func TestDeCommit(t *testing.T) { + one := big.NewInt(1) + zero := big.NewInt(0) + + commitment, err := commitments.NewHashCommitment(zero, one) + assert.NoError(t, err) + + pass, secrets, err := commitment.DeCommit() + assert.NoError(t, err) + + t.Log(commitment.D) + t.Log(commitment.C) + + assert.True(t, pass, "must pass") + + assert.NotZero(t, len(secrets), "len(secrets) must be non-zero") +} diff --git a/crypto/paillier/paillier.go b/crypto/paillier/paillier.go new file mode 100644 index 0000000..b9ff8a4 --- /dev/null +++ b/crypto/paillier/paillier.go @@ -0,0 +1,163 @@ +// The Paillier Crypto-system is an additive crypto-system. This means that given two ciphertexts, one can perform operations equivalent to adding the respective plain texts. +// Additionally, Paillier Crypto-system supports further computations: +// +// * Encrypted integers can be added together +// * Encrypted integers can be multiplied by an unencrypted integer +// * Encrypted integers and unencrypted integers can be added together + +package paillier + +import ( + "fmt" + "math/big" + "strconv" + + "golang.org/x/crypto/sha3" + + "tss-lib/common/math" +) + +var ErrMessageTooLong = fmt.Errorf("the message is too long") + +type ( + PublicKey struct { + Length string + N *big.Int // modulus + G *big.Int // n+1, since p and q are same length + NSquared *big.Int // NSquared = N * N + } + + PrivateKey struct { + PublicKey + Length string + L *big.Int // (p-1)*(q-1) + U *big.Int // L^-1 mod N + } + + Proof struct { + H1 *big.Int + H2 *big.Int + Y *big.Int // r+(n-\phi(n))*e + E *big.Int + N *big.Int + } +) + +func GenerateKeyPair(len int) (*PublicKey, *PrivateKey) { + one := big.NewInt(1) + + p := math.GetRandomPrimeInt(len / 2) + q := math.GetRandomPrimeInt(len / 2) + + n := new(big.Int).Mul(p, q) + n2 := new(big.Int).Mul(n, n) + g := new(big.Int).Add(n, one) + + pMinus1 := new(big.Int).Sub(p, one) + qMinus1 := new(big.Int).Sub(q, one) + + l := new(big.Int).Mul(pMinus1, qMinus1) + u := new(big.Int).ModInverse(l, n) + + publicKey := &PublicKey{Length: strconv.Itoa(len), N: n, G: g, NSquared: n2} + privateKey := &PrivateKey{Length: strconv.Itoa(len), PublicKey: *publicKey, L: l, U: u} + + return publicKey, privateKey +} + +//func (publicKey *PublicKey) Encrypt(mBigInt *big.Int) (*big.Int, error) { +func (publicKey *PublicKey) Encrypt(mBigInt *big.Int) (*big.Int, *big.Int, error) { + if mBigInt.Cmp(publicKey.N) > 0 { + return nil, nil,ErrMessageTooLong + } + + rndStar := math.GetRandomPositiveIntStar(publicKey.N) + + // G^m mod NSq + Gm := new(big.Int).Exp(publicKey.G, mBigInt, publicKey.NSquared) + // R^N mod NSq + RN := new(big.Int).Exp(rndStar, publicKey.N, publicKey.NSquared) + // G^m * R^n + GmRN := new(big.Int).Mul(Gm, RN) + // G^m * R^n mod NSq + cipher := new(big.Int).Mod(GmRN, publicKey.NSquared) + + return cipher, rndStar,nil +} + +func (privateKey *PrivateKey) Decrypt(cipherBigInt *big.Int) (*big.Int, error) { + one := big.NewInt(1) + + if cipherBigInt.Cmp(privateKey.NSquared) > 0 { + return nil, ErrMessageTooLong + } + + // c^L mod NSq + cL := new(big.Int).Exp(cipherBigInt, privateKey.L, privateKey.NSquared) + // c^L-1 + cLMinus1 := new(big.Int).Sub(cL, one) + // (c^L-1) / N + cLMinus1DivN := new(big.Int).Div(cLMinus1, privateKey.N) + // (c^L-1) / N*U + cLMinus1DivNMulU := new(big.Int).Mul(cLMinus1DivN, privateKey.U) + // (c^L-1) / N*U mod N + mBigInt := new(big.Int).Mod(cLMinus1DivNMulU, privateKey.N) + + return mBigInt, nil +} + +func (publicKey *PublicKey) HomoAdd(c1, c2 *big.Int) *big.Int { + // c1 * c2 + c1c2 := new(big.Int).Mul(c1, c2) + // c1 * c2 mod NSq + newCipher := new(big.Int).Mod(c1c2, publicKey.NSquared) + + return newCipher +} + +// TODO add Homo Multiply method + +// ----- // + +func (privateKey *PrivateKey) ZKFactProve() *Proof { + h1 := math.GetRandomPositiveIntStar(privateKey.N) + h2 := math.GetRandomPositiveIntStar(privateKey.N) + r := math.GetRandomPositiveInt(privateKey.N) + + h1R := new(big.Int).Exp(h1, r, privateKey.N) + h2R := new(big.Int).Exp(h2, r, privateKey.N) + + sha3256 := sha3.New256() + sha3256.Write(h1R.Bytes()) + sha3256.Write(h2R.Bytes()) + eBytes := sha3256.Sum(nil) + e := new(big.Int).SetBytes(eBytes) + + y := new(big.Int).Add(privateKey.N, privateKey.L) + y = new(big.Int).Mul(y, e) + y = new(big.Int).Add(y, r) + + return &Proof{H1: h1, H2: h2, Y: y, E: e,N: privateKey.N} +} + +func (publicKey *PublicKey) ZKFactVerify(proof *Proof) bool { + ySubNE := new(big.Int).Mul(publicKey.N, proof.E) + ySubNE = new(big.Int).Sub(proof.Y, ySubNE) + + h1R := new(big.Int).Exp(proof.H1, ySubNE, publicKey.N) + h2R := new(big.Int).Exp(proof.H2, ySubNE, publicKey.N) + + sha3256 := sha3.New256() + sha3256.Write(h1R.Bytes()) + sha3256.Write(h2R.Bytes()) + eBytes := sha3256.Sum(nil) + e := new(big.Int).SetBytes(eBytes) + + if e.Cmp(proof.E) == 0 { + return true + } else { + return false + } +} + +// ----- // diff --git a/crypto/paillier/paillier_test.go b/crypto/paillier/paillier_test.go new file mode 100644 index 0000000..70f4048 --- /dev/null +++ b/crypto/paillier/paillier_test.go @@ -0,0 +1,79 @@ +package paillier + +import ( + "math/big" + "testing" + + "github.com/stretchr/testify/assert" + + "tss-lib/common/math" +) + +const KeyPairLength = 2048 + +func TestGenerateKeyPair(t *testing.T) { + publicKey, privateKey := GenerateKeyPair(KeyPairLength) + t.Log(publicKey) + t.Log(privateKey) +} + +func TestEncrypt(t *testing.T) { + publicKey, _ := GenerateKeyPair(KeyPairLength) + + one := big.NewInt(1) + + cipher, _,_ := publicKey.Encrypt(one) + t.Log(cipher) +} + +func TestDecrypt(t *testing.T) { + publicKey, privateKey := GenerateKeyPair(KeyPairLength) + + num := math.GetRandomPositiveInt(publicKey.N) + t.Log(num) + + cipher, _,_ := publicKey.Encrypt(num) + + m, err := privateKey.Decrypt(cipher) + + assert.NoError(t, err, "must not error") + + t.Log(m) +} + +func TestHomoAdd(t *testing.T) { + publicKey, privateKey := GenerateKeyPair(KeyPairLength) + + num1 := big.NewInt(10) + num2 := big.NewInt(32) + + sum := new(big.Int).Add(num1, num2) + sum = new(big.Int).Mod(sum, publicKey.N) + + one, _,_ := publicKey.Encrypt(num1) + two, _,_ := publicKey.Encrypt(num2) + + ciphered := publicKey.HomoAdd(one, two) + + plain, _ := privateKey.Decrypt(ciphered) + + assert.Equal(t, new(big.Int).Add(num1, num2), plain) +} + +func TestZKFactProve(t *testing.T) { + _, privateKey := GenerateKeyPair(KeyPairLength) + + zkFactProof := privateKey.ZKFactProve() + + t.Log(zkFactProof) +} + +func TestZKFactVerify(t *testing.T) { + publicKey, privateKey := GenerateKeyPair(KeyPairLength) + + zkFactProof := privateKey.ZKFactProve() + + res := publicKey.ZKFactVerify(zkFactProof) + + assert.True(t, res, "zk fact verify result must be true") +} diff --git a/crypto/schnorrZK/schnorrZK.go b/crypto/schnorrZK/schnorrZK.go new file mode 100644 index 0000000..cb43a5b --- /dev/null +++ b/crypto/schnorrZK/schnorrZK.go @@ -0,0 +1,68 @@ +package schnorrZK + +import ( + "math/big" + + s256k1 "github.com/btcsuite/btcd/btcec" + "golang.org/x/crypto/sha3" + + "tss-lib/common/math" +) + +var ( + EC *s256k1.KoblitzCurve +) + +func init() { + EC = s256k1.S256() +} + +type ZKProof struct { + E *big.Int + S *big.Int +} + +func ZKProve(u *big.Int) *ZKProof { + r := math.GetRandomPositiveInt(EC.N) + rGx, rGy := EC.ScalarBaseMult(r.Bytes()) + + plain := "BNC_PLAINTEXT" + sha3256 := sha3.New256() + sha3256.Write(rGx.Bytes()) + sha3256.Write(rGy.Bytes()) + sha3256.Write([]byte(plain)) + eBytes := sha3256.Sum(nil) + + e := new(big.Int).SetBytes(eBytes) + + s := new(big.Int).Mul(e, u) + s = new(big.Int).Add(r, s) + s = new(big.Int).Mod(s, EC.N) + + return &ZKProof{E: e, S: s} +} + +func ZKVerify(uG []*big.Int, zkProof *ZKProof) bool { + sGx, sGy := EC.ScalarBaseMult(zkProof.S.Bytes()) + + minusE := new(big.Int).Mul(big.NewInt(-1), zkProof.E) + minusE = new(big.Int).Mod(minusE, EC.N) + + eUx, eUy := EC.ScalarMult(uG[0], uG[1], minusE.Bytes()) + rGx, rGy := EC.Add(sGx, sGy, eUx, eUy) + + plain := "BNC_PLAINTEXT" + sha3256 := sha3.New256() + sha3256.Write(rGx.Bytes()) + sha3256.Write(rGy.Bytes()) + sha3256.Write([]byte(plain)) + eBytes := sha3256.Sum(nil) + + e := new(big.Int).SetBytes(eBytes) + + if e.Cmp(zkProof.E) == 0 { + return true + } else { + return false + } +} diff --git a/crypto/schnorrZK/schnorrZK_test.go b/crypto/schnorrZK/schnorrZK_test.go new file mode 100644 index 0000000..c8022cb --- /dev/null +++ b/crypto/schnorrZK/schnorrZK_test.go @@ -0,0 +1,32 @@ +package schnorrZK_test + +import ( + "math/big" + "testing" + + s256k1 "github.com/btcsuite/btcd/btcec" + "github.com/stretchr/testify/assert" + + "tss-lib/common/math" + "tss-lib/crypto/schnorrZK" +) + +func TestZKProve(t *testing.T) { + u := math.GetRandomPositiveInt(schnorrZK.EC.N) + proof := schnorrZK.ZKProve(u) + + t.Log(proof) +} + +func TestZKVerify(t *testing.T) { + u := math.GetRandomPositiveInt(schnorrZK.EC.N) + + uGx, uGy := s256k1.S256().ScalarBaseMult(u.Bytes()) + uG := []*big.Int{uGx, uGy} + + proof := schnorrZK.ZKProve(u) + + res := schnorrZK.ZKVerify(uG, proof) + + assert.True(t, res, "verify result must be true") +} diff --git a/crypto/vss/feldman_vss.go b/crypto/vss/feldman_vss.go new file mode 100644 index 0000000..8f82d21 --- /dev/null +++ b/crypto/vss/feldman_vss.go @@ -0,0 +1,175 @@ +// Feldman VSS, based on Paul Feldman, 1987., A practical scheme for non-interactive verifiable secret sharing. +// In Foundations of Computer Science, 1987., 28th Annual Symposium on. IEEE, 427–43 +// +// Implementation details: The code is using EC Points and Scalars. Each party is given an index from 1,..,n and a secret share scalar +// The index of the party is also the point on the polynomial where we treat this number as u32 + +package vss + +import ( + "fmt" + "math/big" + + s256k1 "github.com/btcsuite/btcd/btcec" + + "tss-lib/common/math" +) + +var ( + ErrIdsLenNotEqualToNumShares = fmt.Errorf("the length of input ids is not equal to the number of shares") + ErrNumSharesBelowThreshold = fmt.Errorf("not enough shares to satisfy the threshold") + + EC *s256k1.KoblitzCurve +) + +func init() { + EC = s256k1.S256() +} + +type ( + // Params represents the parameters used in Shamir secret sharing + Params struct { + Threshold int // threshold + NumShares int // total num + } + + PolyG struct { + Params + PolyG [][]*big.Int // x and y + } + + Poly struct { + PolyG + Poly []*big.Int // coefficient set + } + + Share struct { + Threshold int + Id *big.Int // ID, x coordinate + Share *big.Int + } +) + +// Returns a new array of secret shares created by Shamir's Secret Sharing Algorithm, +// requiring a minimum number of shares to recreate, of length shares, from the input secret +// +func Create(threshold int, num int, indexes []*big.Int, secret *big.Int) (*Params, *PolyG, *Poly, []*Share, error) { + if len(indexes) != num { + return nil, nil, nil, nil, ErrIdsLenNotEqualToNumShares + } + + shares := make([]*Share, 0, num) + + // polynomials for commitments + poly := make([]*big.Int, 0, threshold) + + poly = append(poly, secret) + + // commitments + polyG := make([][]*big.Int, 0, threshold) + + pointX, pointY := EC.ScalarBaseMult(secret.Bytes()) + polyG = append(polyG, []*big.Int{pointX, pointY}) + + for i := 0; i < threshold-1; i++ { + // sample polynomial + rnd := math.GetRandomPositiveInt(EC.N) + poly = append(poly, rnd) + + // generate commitment + pointX, pointY := EC.ScalarBaseMult(rnd.Bytes()) + polyG = append(polyG, []*big.Int{pointX, pointY}) + + } + + params := Params{Threshold: threshold, NumShares: num} + pg := PolyG{Params: params, PolyG: polyG} + + for i := 0; i < num; i++ { + shareVal := evaluatePolynomial(poly, indexes[i]) + shareStruct := &Share{Threshold: threshold, Id: indexes[i], Share: shareVal} + shares = append(shares, shareStruct) + } + + ps := &Poly{PolyG: pg, Poly: poly} + + return ¶ms, &pg, ps, shares, nil +} + +func (share *Share) Verify(polyG *PolyG) bool { + if share.Threshold != polyG.Threshold { + return false + } + id := share.Id + + tmpPointX, tmpPointY := polyG.PolyG[0][0], polyG.PolyG[0][1] + + for i := 1; i < polyG.Threshold; i++ { + pointX, pointY := EC.ScalarMult(polyG.PolyG[i][0], polyG.PolyG[i][1], id.Bytes()) + + tmpPointX, tmpPointY = EC.Add(tmpPointX, tmpPointY, pointX, pointY) + id = new(big.Int).Mul(id, share.Id) + id = new(big.Int).Mod(id, EC.N) + } + + originalPointX, originalPointY := EC.ScalarBaseMult(share.Share.Bytes()) + + if tmpPointX.Cmp(originalPointX) == 0 && tmpPointY.Cmp(originalPointY) == 0 { + return true + } else { + return false + } +} + +func Combine(shares []*Share) (*big.Int, error) { + if shares != nil && shares[0].Threshold > len(shares) { + return nil, ErrNumSharesBelowThreshold + } + + // x coords + xs := make([]*big.Int, 0) + for _, share := range shares { + xs = append(xs, share.Id) + } + + secret := big.NewInt(0) + + for i, share := range shares { + times := big.NewInt(1) + + // times() + for j := 0; j < len(xs); j++ { + if j != i { + sub := new(big.Int).Sub(xs[j], share.Id) + subInverse := new(big.Int).ModInverse(sub, EC.N) + div := new(big.Int).Mul(xs[j], subInverse) + times = new(big.Int).Mul(times, div) + times = new(big.Int).Mod(times, EC.N) + } + } + + // sum(f(x) * times()) + fTimes := new(big.Int).Mul(share.Share, times) + secret = new(big.Int).Add(secret, fTimes) + secret = new(big.Int).Mod(secret, EC.N) + } + + return secret, nil +} + +// Evauluates a polynomial with coefficients specified in reverse order: +// evaluatePolynomial([a, b, c, d], x): +// returns a + bx + cx^2 + dx^3 +// +func evaluatePolynomial(poly []*big.Int, value *big.Int) *big.Int { + last := len(poly) - 1 + result := big.NewInt(0).Set(poly[last]) + + for i := last - 1; i >= 0; i-- { + result = result.Mul(result, value) + result = result.Add(result, poly[i]) + result = result.Mod(result, EC.N) + } + + return result +} diff --git a/crypto/vss/feldman_vss_test.go b/crypto/vss/feldman_vss_test.go new file mode 100644 index 0000000..db01a14 --- /dev/null +++ b/crypto/vss/feldman_vss_test.go @@ -0,0 +1,96 @@ +package vss_test + +import ( + "math/big" + "testing" + + "github.com/stretchr/testify/assert" + + "tss-lib/common/math" + "tss-lib/crypto/vss" +) + +func TestCreate(t *testing.T) { + num, threshold := 3, 2 + + secret := math.GetRandomPositiveInt(vss.EC.N) + t.Log(secret) + + ids := make([]*big.Int, 0) + for i := 0; i < num; i++ { + ids = append(ids, math.GetRandomPositiveInt(vss.EC.N)) + } + + params, polyG, poly, shares, err := vss.Create(threshold, num, ids, secret) + assert.Nil(t, err) + + assert.Equal(t, threshold, params.Threshold) + assert.Equal(t, num, params.NumShares) + + assert.Equal(t, threshold, len(poly.Poly)) + assert.Equal(t, threshold, len(polyG.PolyG)) + + // coefs must not be zero + for i := 0; i < len(poly.Poly); i++ { + assert.NotZero(t, poly.Poly[i]) + } + + // ensure that each polyG len() == 2 + for i := 0; i < len(polyG.PolyG); i++ { + assert.Equal(t, len(polyG.PolyG[i]), 2) + assert.NotZero(t, polyG.PolyG[i][0]) + assert.NotZero(t, polyG.PolyG[i][1]) + } + + t.Log(polyG) + t.Log(poly) + t.Log(shares) +} + +func TestVerify(t *testing.T) { + num, threshold := 3, 2 + + secret := math.GetRandomPositiveInt(vss.EC.N) + + ids := make([]*big.Int, 0) + for i := 0; i < num; i++ { + ids = append(ids, math.GetRandomPositiveInt(vss.EC.N)) + } + + _, polyG, _, shares, err := vss.Create(threshold, num, ids, secret) + assert.Nil(t, err) + + for i := 0; i < num; i++ { + assert.True(t, shares[i].Verify(polyG)) + } +} + +func TestCombine(t *testing.T) { + num, threshold := 3, 2 + + secret := math.GetRandomPositiveInt(vss.EC.N) + t.Log(secret) + + ids := make([]*big.Int, 0) + for i := 0; i < num; i++ { + ids = append(ids, math.GetRandomPositiveInt(vss.EC.N)) + } + + _, _, _, shares, err := vss.Create(threshold, num, ids, secret) + assert.Nil(t, err) + + secret2, err2 := vss.Combine(shares[:threshold-1]) + assert.Error(t, err2) // not enough shares to satisfy the threshold + t.Log(err2) + t.Log(secret2) + + secret3, err3 := vss.Combine(shares[:threshold]) + assert.Nil(t, err3) + t.Log(err3) + t.Log(secret3) + + secret4, err4 := vss.Combine(shares[:num]) + assert.Nil(t, err4) + t.Log(err4) + t.Log(secret4) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c6ba0cb --- /dev/null +++ b/go.mod @@ -0,0 +1,13 @@ +module tss-lib + +go 1.12 + +require ( + github.com/NebulousLabs/hdkey v0.0.0-20160410223530-aee6f80cd15d + github.com/btcsuite/btcd v0.0.0-20190427004231-96897255fd17 + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/stretchr/testify v1.3.0 + golang.org/x/crypto v0.0.0-20190506204251-e1dfcc566284 + golang.org/x/sys v0.0.0-20190508100423-12bbe5a7a520 // indirect + gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..6971422 --- /dev/null +++ b/go.sum @@ -0,0 +1,49 @@ +github.com/NebulousLabs/hdkey v0.0.0-20160410223530-aee6f80cd15d h1:G/786juQ/tF4+NsIZuNXmILMJYhDEk1Qqw3ukUs0IAM= +github.com/NebulousLabs/hdkey v0.0.0-20160410223530-aee6f80cd15d/go.mod h1:xkvlXyPND9pgE7xyhjWMrqLYWceMwbeorlJSFmHYONU= +github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= +github.com/btcsuite/btcd v0.0.0-20190427004231-96897255fd17 h1:m0N5Vg5nP3zEz8TREZpwX3gt4Biw3/8fbIf4A3hO96g= +github.com/btcsuite/btcd v0.0.0-20190427004231-96897255fd17/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI= +github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= +github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= +github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= +github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= +github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= +github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= +github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495 h1:6IyqGr3fnd0tM3YxipK27TUskaOVUjU2nG45yzwcQKY= +github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= +github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190506204251-e1dfcc566284 h1:rlLehGeYg6jfoyz/eDqDU1iRXLKfR42nnNh57ytKEWo= +golang.org/x/crypto v0.0.0-20190506204251-e1dfcc566284/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190508100423-12bbe5a7a520 h1:5/ojcKo2vQ2eroPDFcBB9tuc4N42a5njs7UWP2jk3KU= +golang.org/x/sys v0.0.0-20190508100423-12bbe5a7a520/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=