No commit suggestions generated

This commit is contained in:
Prad Nukala
2025-10-09 15:10:39 -04:00
commit a934caa7d3
323 changed files with 98121 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
---
aliases: [README]
tags: []
title: README
linter-yaml-title-alias: README
date created: Wednesday, April 17th 2024, 4:11:40 pm
date modified: Thursday, April 18th 2024, 8:19:25 am
---
## FROST: Flexible Round-Optimized Schnorr Threshold Signatures
This package is an implementation of the DKG part of
[FROST: Flexible Round-Optimized Schnorr Threshold Signatures](https://eprint.iacr.org/2020/852.pdf)
+153
View File
@@ -0,0 +1,153 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package frost
import (
"bytes"
crand "crypto/rand"
"encoding/gob"
"fmt"
"reflect"
"github.com/pkg/errors"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/internal"
"github.com/sonr-io/sonr/crypto/sharing"
)
// Round1Bcast are values that are broadcast to all other participants
// after round1 completes
type Round1Bcast struct {
Verifiers *sharing.FeldmanVerifier
Wi, Ci curves.Scalar
}
type Round1Result struct {
Broadcast *Round1Bcast
P2P *sharing.ShamirShare
}
func (result *Round1Result) Encode() ([]byte, error) {
gob.Register(result.Broadcast.Verifiers.Commitments[0]) // just the point for now
gob.Register(result.Broadcast.Ci)
buf := &bytes.Buffer{}
enc := gob.NewEncoder(buf)
if err := enc.Encode(result); err != nil {
return nil, errors.Wrap(err, "couldn't encode round 1 broadcast")
}
return buf.Bytes(), nil
}
func (result *Round1Result) Decode(input []byte) error {
buf := bytes.NewBuffer(input)
dec := gob.NewDecoder(buf)
if err := dec.Decode(result); err != nil {
return errors.Wrap(err, "couldn't encode round 1 broadcast")
}
return nil
}
// Round1P2PSend are values that are P2PSend to all other participants
// after round1 completes
type Round1P2PSend = map[uint32]*sharing.ShamirShare
// Round1 implements dkg round 1 of FROST
func (dp *DkgParticipant) Round1(secret []byte) (*Round1Bcast, Round1P2PSend, error) {
// Make sure dkg participant is not empty
if dp == nil || dp.Curve == nil {
return nil, nil, internal.ErrNilArguments
}
// Make sure round number is correct
if dp.round != 1 {
return nil, nil, internal.ErrInvalidRound
}
// Check number of participants
if uint32(len(dp.otherParticipantShares)+1) > dp.feldman.Limit ||
uint32(len(dp.otherParticipantShares)+1) < dp.feldman.Threshold {
return nil, nil, fmt.Errorf(
"length of dp.otherParticipantShares + 1 should be equal to feldman limit",
)
}
// If secret is nil, sample a new one
// If not, check secret is valid
var s curves.Scalar
var err error
if secret == nil {
s = dp.Curve.Scalar.Random(crand.Reader)
} else {
s, err = dp.Curve.Scalar.SetBytes(secret)
if err != nil {
return nil, nil, err
}
if s.IsZero() {
return nil, nil, internal.ErrZeroValue
}
}
// Step 1 - (Aj0,...Ajt), (xi1,...,xin) <- FeldmanShare(s)
// We should validate types of Feldman curve scalar and participant's curve scalar.
if reflect.TypeOf(dp.feldman.Curve.Scalar) != reflect.TypeOf(dp.Curve.Scalar) {
return nil, nil, fmt.Errorf(
"feldman scalar should have the same type as the dkg participant scalar",
)
}
verifiers, shares, err := dp.feldman.Split(s, crand.Reader)
if err != nil {
return nil, nil, err
}
// Store Verifiers and shares
dp.verifiers = verifiers
dp.secretShares = shares
// Step 2 - Sample ki <- Z_q
ki := dp.Curve.Scalar.Random(crand.Reader)
// Step 3 - Compute Ri = ki*G
Ri := dp.Curve.ScalarBaseMult(ki)
// Step 4 - Compute Ci = H(i, CTX, g^{a_(i,0)}, R_i), where CTX is fixed context string
var msg []byte
// Append participant id
msg = append(msg, byte(dp.Id))
// Append CTX
msg = append(msg, dp.ctx)
// Append a_{i,0}*G
msg = append(msg, verifiers.Commitments[0].ToAffineCompressed()...)
// Append Ri
msg = append(msg, Ri.ToAffineCompressed()...)
// Hash the message and get Ci
ci := dp.Curve.Scalar.Hash(msg)
// Step 5 - Compute Wi = ki+a_{i,0}*c_i mod q. Note that a_{i,0} is the secret.
// Note: We have to compute scalar in the following way when using ed25519 curve, rather than scalar := dp.Scalar.Mul(s, Ci)
// there is an invalid encoding error when we compute scalar as above.
wi := s.MulAdd(ci, ki)
// Step 6 - Broadcast (Ci, Wi, Ci) to other participants
round1Bcast := &Round1Bcast{
verifiers,
wi,
ci,
}
// Step 7 - P2PSend f_i(j) to each participant Pj and keep (i, f_j(i)) for himself
p2pSend := make(Round1P2PSend, len(dp.otherParticipantShares))
for id := range dp.otherParticipantShares {
p2pSend[id] = shares[id-1]
}
// Update internal state
dp.round = 2
// return
return round1Bcast, p2pSend, nil
}
+162
View File
@@ -0,0 +1,162 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package frost
import (
"fmt"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/internal"
"github.com/sonr-io/sonr/crypto/sharing"
)
// Round2Bcast are values that are broadcast to all other participants
// after round2 completes
type Round2Bcast struct {
VerificationKey curves.Point
VkShare curves.Point
}
// Round2 implements dkg round 2 of FROST
func (dp *DkgParticipant) Round2(
bcast map[uint32]*Round1Bcast,
p2psend map[uint32]*sharing.ShamirShare,
) (*Round2Bcast, error) {
// Make sure dkg participant is not empty
if dp == nil || dp.Curve == nil {
return nil, internal.ErrNilArguments
}
// Check dkg participant has the correct dkg round number
if dp.round != 2 {
return nil, internal.ErrInvalidRound
}
// Check the input is valid
if bcast == nil || p2psend == nil || len(p2psend) == 0 {
return nil, internal.ErrNilArguments
}
// Check length of bcast and p2psend
if uint32(len(bcast)) > dp.feldman.Limit || uint32(len(bcast)) < dp.feldman.Threshold-1 {
return nil, fmt.Errorf("invalid broadcast length")
}
if uint32(len(p2psend)) > dp.feldman.Limit-1 || uint32(len(p2psend)) < dp.feldman.Threshold-1 {
return nil, fmt.Errorf("invalid p2pSend length")
}
// We should validate Wi and Ci values in Round1Bcast
for id := range bcast {
// ci should be within the range 1 to q-1, q is the group order.
if bcast[id].Ci.IsZero() {
return nil, fmt.Errorf("ci should not be zero from participant %d", id)
}
}
// Validate each received commitment is on curve
for id := range bcast {
for _, com := range bcast[id].Verifiers.Commitments {
if !com.IsOnCurve() || com.IsIdentity() {
return nil, fmt.Errorf("some commitment is not on curve from participant %d", id)
}
}
}
var err error
// Step 2 - for j in 1,...,n
for id := range bcast {
// Step 3 - if j == i, continue
if id == dp.Id {
continue
}
// Step 4 - Check equation c_j = H(j, CTX, A_{j,0}, g^{w_j}*A_{j,0}^{-c_j}
// Get Aj0
Aj0 := bcast[id].Verifiers.Commitments[0]
// Compute g^{w_j}
prod1 := dp.Curve.ScalarBaseMult(bcast[id].Wi)
// Compute A_{j,0}^{-c_j}
prod2 := Aj0.Mul(bcast[id].Ci.Neg())
// We need to check Aj0 and prod2 are points on the same curve.
if !Aj0.IsOnCurve() || Aj0.IsIdentity() || !prod2.IsOnCurve() || prod2.IsIdentity() ||
Aj0.CurveName() != prod2.CurveName() {
return nil, fmt.Errorf("invalid Aj0 or prod2 which is not on the same curve")
}
if prod2 == nil {
return nil, fmt.Errorf("invalid should not be nil")
}
prod := prod1.Add(prod2)
var msg []byte
// Append participant id
msg = append(msg, byte(id))
// Append CTX
msg = append(msg, dp.ctx)
// Append Aj0
msg = append(msg, Aj0.ToAffineCompressed()...)
// Append prod
msg = append(msg, prod.ToAffineCompressed()...)
// Hash the message and get cj
cj := dp.Curve.Scalar.Hash(msg)
// Check equation
if cj.Cmp(bcast[id].Ci) != 0 {
return nil, fmt.Errorf("hash check fails for participant with id %d", id)
}
// Step 5 - FeldmanVerify
fji := p2psend[id]
if err = bcast[id].Verifiers.Verify(fji); err != nil {
return nil, fmt.Errorf("feldman verify fails for participant with id %d", id)
}
}
sk, err := dp.Curve.Scalar.SetBytes(dp.secretShares[dp.Id-1].Value)
if err != nil {
return nil, err
}
vk := dp.verifiers.Commitments[0]
// Step 6 - Compute signing key share ski = \sum_{j=1}^n xji
for id := range bcast {
if id == dp.Id {
continue
}
t2, err := dp.Curve.Scalar.SetBytes(p2psend[id].Value)
if err != nil {
return nil, err
}
sk = sk.Add(t2)
}
// Step 8 - Compute verification key vk = sum(A_{j,0}), j = 1,...,n
for id := range bcast {
if id == dp.Id {
continue
}
vk = vk.Add(bcast[id].Verifiers.Commitments[0])
}
// Store signing key share
dp.SkShare = sk
// Step 7 - Compute verification key share vki = ski*G and store
dp.VkShare = dp.Curve.ScalarBaseMult(sk)
// Store verification key
dp.VerificationKey = vk
// Update round number
dp.round = 3
// Broadcast
return &Round2Bcast{
vk,
dp.VkShare,
}, nil
}
+206
View File
@@ -0,0 +1,206 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package frost
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/sharing"
)
var (
testCurve = curves.ED25519()
Ctx = "string to prevent replay attack"
)
// Test dkg round1 works for 2 participants
func TestDkgRound1Works(t *testing.T) {
p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2)
require.NoError(t, err)
bcast, p2psend, err := p1.Round1(nil)
require.NoError(t, err)
require.NotNil(t, bcast)
require.NotNil(t, p2psend)
require.NotNil(t, p1.ctx)
require.Equal(t, len(p2psend), 1)
require.Equal(t, p1.round, 2)
_, ok := p2psend[2]
require.True(t, ok)
}
func TestDkgRound1RepeatCall(t *testing.T) {
p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2)
require.NoError(t, err)
_, _, err = p1.Round1(nil)
require.NoError(t, err)
_, _, err = p1.Round1(nil)
require.Error(t, err)
}
func TestDkgRound1BadSecret(t *testing.T) {
p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2)
require.NoError(t, err)
// secret == 0
secret := []byte{0}
_, _, err = p1.Round1(secret)
require.Error(t, err)
// secret too big
secret = []byte{
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
}
_, _, err = p1.Round1(secret)
require.Error(t, err)
}
func PrepareRound2Input(
t *testing.T,
) (*DkgParticipant, *DkgParticipant, *Round1Bcast, *Round1Bcast, Round1P2PSend, Round1P2PSend) {
// Prepare round 1 output of 2 participants
p1, err := NewDkgParticipant(1, 2, Ctx, testCurve, 2)
require.NoError(t, err)
require.Equal(t, p1.otherParticipantShares[2].Id, uint32(2))
p2, err := NewDkgParticipant(2, 2, Ctx, testCurve, 1)
require.NoError(t, err)
require.Equal(t, p2.otherParticipantShares[1].Id, uint32(1))
bcast1, p2psend1, _ := p1.Round1(nil)
bcast2, p2psend2, _ := p2.Round1(nil)
return p1, p2, bcast1, bcast2, p2psend1, p2psend2
}
// Test FROST DKG round 2 works
func TestDkgRound2Works(t *testing.T) {
// Prepare Dkg Round1 output
p1, _, bcast1, bcast2, _, p2psend2 := PrepareRound2Input(t)
// Actual Test
require.NotNil(t, bcast1)
require.NotNil(t, bcast2)
require.NotNil(t, p2psend2[1])
bcast := make(map[uint32]*Round1Bcast)
p2p := make(map[uint32]*sharing.ShamirShare)
bcast[1] = bcast1
bcast[2] = bcast2
p2p[2] = p2psend2[1]
round2Out, err := p1.Round2(bcast, p2p)
require.NoError(t, err)
require.NotNil(t, round2Out)
require.NotNil(t, p1.SkShare)
require.NotNil(t, p1.VkShare)
require.NotNil(t, p1.VerificationKey)
require.NotNil(t, p1.otherParticipantShares)
}
// Test FROST DKG round 2 repeat call
func TestDkgRound2RepeatCall(t *testing.T) {
// Prepare round 1 output
p1, _, bcast1, bcast2, _, p2psend2 := PrepareRound2Input(t)
// Actual Test
require.NotNil(t, bcast1)
require.NotNil(t, bcast2)
require.NotNil(t, p2psend2[1])
bcast := make(map[uint32]*Round1Bcast)
p2p := make(map[uint32]*sharing.ShamirShare)
bcast[1] = bcast1
bcast[2] = bcast2
p2p[2] = p2psend2[1]
_, err := p1.Round2(bcast, p2p)
require.NoError(t, err)
_, err = p1.Round2(bcast, p2p)
require.Error(t, err)
}
// Test FROST Dkg Round 2 Bad Input
func TestDkgRound2BadInput(t *testing.T) {
// Prepare Dkg Round 1 output
p1, _, _, _, _, _ := PrepareRound2Input(t)
bcast := make(map[uint32]*Round1Bcast)
p2p := make(map[uint32]*sharing.ShamirShare)
// Test empty bcast and p2p
_, err := p1.Round2(bcast, p2p)
require.Error(t, err)
// Test nil bcast and p2p
p1, _, _, _, _, _ = PrepareRound2Input(t)
_, err = p1.Round2(nil, nil)
require.Error(t, err)
// Test tampered input bcast and p2p
p1, _, bcast1, bcast2, _, p2psend2 := PrepareRound2Input(t)
bcast = make(map[uint32]*Round1Bcast)
p2p = make(map[uint32]*sharing.ShamirShare)
// Tamper p2psend2 by doubling the value
tmp, _ := testCurve.Scalar.SetBytes(p2psend2[1].Value)
p2psend2[1].Value = tmp.Double().Bytes()
bcast[1] = bcast1
bcast[2] = bcast2
p2p[2] = p2psend2[1]
_, err = p1.Round2(bcast, p2p)
require.Error(t, err)
}
// Test full round works
func TestFullDkgRoundsWorks(t *testing.T) {
// Initiate two participants and running round 1
p1, p2, bcast1, bcast2, p2psend1, p2psend2 := PrepareRound2Input(t)
bcast := make(map[uint32]*Round1Bcast)
p2p1 := make(map[uint32]*sharing.ShamirShare)
p2p2 := make(map[uint32]*sharing.ShamirShare)
bcast[1] = bcast1
bcast[2] = bcast2
p2p1[2] = p2psend2[1]
p2p2[1] = p2psend1[2]
// Running round 2
round2Out1, _ := p1.Round2(bcast, p2p1)
round2Out2, _ := p2.Round2(bcast, p2p2)
require.Equal(t, round2Out1.VerificationKey, round2Out2.VerificationKey)
s, _ := sharing.NewShamir(2, 2, testCurve)
sk, err := s.Combine(&sharing.ShamirShare{Id: p1.Id, Value: p1.SkShare.Bytes()},
&sharing.ShamirShare{Id: p2.Id, Value: p2.SkShare.Bytes()})
require.NoError(t, err)
vk := testCurve.ScalarBaseMult(sk)
require.True(t, vk.Equal(p1.VerificationKey))
}
+70
View File
@@ -0,0 +1,70 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// Package frost is an implementation of the DKG part of https://eprint.iacr.org/2020/852.pdf
package frost
import (
"strconv"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/internal"
"github.com/sonr-io/sonr/crypto/sharing"
)
type DkgParticipant struct {
round int
Curve *curves.Curve
otherParticipantShares map[uint32]*dkgParticipantData
Id uint32
SkShare curves.Scalar
VerificationKey curves.Point
VkShare curves.Point
feldman *sharing.Feldman
verifiers *sharing.FeldmanVerifier
secretShares []*sharing.ShamirShare
ctx byte
}
type dkgParticipantData struct {
Id uint32
Share *sharing.ShamirShare
Verifiers *sharing.FeldmanVerifier
}
func NewDkgParticipant(
id, threshold uint32,
ctx string,
curve *curves.Curve,
otherParticipants ...uint32,
) (*DkgParticipant, error) {
if curve == nil || len(otherParticipants) == 0 {
return nil, internal.ErrNilArguments
}
limit := uint32(len(otherParticipants)) + 1
feldman, err := sharing.NewFeldman(threshold, limit, curve)
if err != nil {
return nil, err
}
otherParticipantShares := make(map[uint32]*dkgParticipantData, len(otherParticipants))
for _, id := range otherParticipants {
otherParticipantShares[id] = &dkgParticipantData{
Id: id,
}
}
// SetBigInt the common fixed string
ctxV, _ := strconv.Atoi(ctx)
return &DkgParticipant{
Id: id,
round: 1,
Curve: curve,
feldman: feldman,
otherParticipantShares: otherParticipantShares,
ctx: byte(ctxV),
}, nil
}
+13
View File
@@ -0,0 +1,13 @@
---
aliases: [README]
tags: []
title: README
linter-yaml-title-alias: README
date created: Wednesday, April 17th 2024, 4:11:40 pm
date modified: Thursday, April 18th 2024, 8:19:25 am
---
## One Round Threshold ECDSA with Identifiable Abort (GG20)
This package is an implementation of the DKG part of
[One Round Threshold ECDSA with Identifiable Abort](https://eprint.iacr.org/2020/540.pdf).
+102
View File
@@ -0,0 +1,102 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// Package gennaro is an implementation of the DKG part of https://eprint.iacr.org/2020/540.pdf
package gennaro
import (
"crypto/elliptic"
"fmt"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/internal"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
// Participant is a DKG player that contains information needed to perform DKG rounds
// and yield a secret key share and public key when finished
type Participant struct {
round int
curve elliptic.Curve
scalar curves.EcScalar
otherParticipantShares map[uint32]*dkgParticipantData
id uint32
skShare *curves.Element
verificationKey *v1.ShareVerifier
feldman *v1.Feldman
pedersen *v1.Pedersen
pedersenResult *v1.PedersenResult
}
// NewParticipant creates a participant ready to perform a DKG
// `id` is the integer value identifier for this participant
// `threshold` is the minimum bound for the secret sharing scheme
// `generator` is the blinding factor generator used by pedersen's verifiable secret sharing
// `otherParticipants` is the integer value identifiers for the other participants
// `id` and `otherParticipants` must be the set of integers 1,2,....,n
func NewParticipant(
id, threshold uint32,
generator *curves.EcPoint,
scalar curves.EcScalar,
otherParticipants ...uint32,
) (*Participant, error) {
if generator == nil || len(otherParticipants) == 0 {
return nil, internal.ErrNilArguments
}
err := validIds(append(otherParticipants, id))
if err != nil {
return nil, err
}
limit := uint32(len(otherParticipants)) + 1
feldman, err := v1.NewFeldman(threshold, limit, generator.Curve)
if err != nil {
return nil, err
}
pedersen, err := v1.NewPedersen(threshold, limit, generator)
if err != nil {
return nil, err
}
otherParticipantShares := make(map[uint32]*dkgParticipantData, len(otherParticipants))
for _, id := range otherParticipants {
otherParticipantShares[id] = &dkgParticipantData{
Id: id,
}
}
return &Participant{
id: id,
round: 1,
curve: generator.Curve,
scalar: scalar,
feldman: feldman,
pedersen: pedersen,
otherParticipantShares: otherParticipantShares,
}, nil
}
// Determines if the SSIDs are exactly the values 1..n.
func validIds(ids []uint32) error {
// Index
idMap := make(map[uint32]bool, len(ids))
for _, id := range ids {
idMap[id] = true
}
// Check
for i := 1; i <= len(ids); i++ {
if ok := idMap[uint32(i)]; !ok {
return fmt.Errorf("the ID list %v is invalid; values must be 1,2,..,n", ids)
}
}
return nil
}
type dkgParticipantData struct {
Id uint32
Share *v1.ShamirShare
Verifiers []*v1.ShareVerifier
}
+48
View File
@@ -0,0 +1,48 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package gennaro
import (
"math/big"
"testing"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/stretchr/testify/require"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/internal"
)
var testGenerator, _ = curves.NewScalarBaseMult(btcec.S256(), big.NewInt(3333))
func TestNewParticipantWorks(t *testing.T) {
p, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
require.NoError(t, err)
require.NotNil(t, p)
require.Equal(t, p.id, uint32(1))
require.Equal(t, p.round, 1)
require.Equal(t, p.curve, btcec.S256())
require.NotNil(t, p.pedersen)
require.NotNil(t, p.feldman)
require.Nil(t, p.pedersenResult)
require.NotNil(t, p.otherParticipantShares)
require.NotNil(t, p.scalar)
_, ok := p.otherParticipantShares[2]
require.True(t, ok)
}
func TestNewParticipantBadInputs(t *testing.T) {
_, err := NewParticipant(0, 0, nil, nil)
require.Error(t, err)
require.Equal(t, err, internal.ErrNilArguments)
_, err = NewParticipant(1, 2, nil, nil)
require.Error(t, err)
require.Equal(t, err, internal.ErrNilArguments)
_, err = NewParticipant(1, 2, testGenerator, nil)
require.Error(t, err)
require.Equal(t, err, internal.ErrNilArguments)
}
+79
View File
@@ -0,0 +1,79 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package gennaro
import (
"fmt"
"math/big"
"github.com/sonr-io/sonr/crypto/core"
"github.com/sonr-io/sonr/crypto/internal"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
// Round1Bcast are the values that are broadcast to all other participants
// after round1 completes
type Round1Bcast = []*v1.ShareVerifier
// Round1P2PSend are the values that are sent to individual participants based
// on the id
type Round1P2PSend = map[uint32]*Round1P2PSendPacket
// Round1P2PSendPacket are the shares generated from the secret for a specific participant
type Round1P2PSendPacket struct {
SecretShare *v1.ShamirShare
BlindingShare *v1.ShamirShare
}
// Round1 computes the first round for the DKG
// `secret` can be nil
// NOTE: if `secret` is nil, a new secret is generated which creates a new key
// if `secret` is set, then this performs key resharing aka proactive secret sharing update
func (dp *Participant) Round1(secret []byte) (Round1Bcast, Round1P2PSend, error) {
if dp.round != 1 {
return nil, nil, internal.ErrInvalidRound
}
if secret == nil {
// 1. x $← Zq
s, err := dp.scalar.Random()
if err != nil {
return nil, nil, err
}
secret = s.Bytes()
} else {
s := new(big.Int).SetBytes(secret)
if !dp.scalar.IsValid(s) {
return nil, nil, fmt.Errorf("invalid secret value")
}
if s.Cmp(core.Zero) == 0 {
return nil, nil, internal.ErrZeroValue
}
}
var err error
// 2. {X1,...,Xt},{R1,...,Rt},{x1,...,xn},{r1,...,rn}= PedersenFeldmanShare(E,Q,x,t,{p1,...,pn})
dp.pedersenResult, err = dp.pedersen.Split(secret)
if err != nil {
return nil, nil, err
}
// 4. P2PSend x_j,r_j to participant p_j in {p_1,...,p_n}_{i != j}
p2pSend := make(Round1P2PSend, len(dp.otherParticipantShares))
for id := range dp.otherParticipantShares {
p2pSend[id] = &Round1P2PSendPacket{
SecretShare: dp.pedersenResult.SecretShares[id-1],
BlindingShare: dp.pedersenResult.BlindingShares[id-1],
}
}
// Update internal state
dp.round = 2
// 3. EchoBroadcast {X_1,...,X_t} to all other participants.
return dp.pedersenResult.BlindedVerifiers, p2pSend, nil
}
+93
View File
@@ -0,0 +1,93 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package gennaro
import (
"fmt"
"github.com/sonr-io/sonr/crypto/internal"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
type Round2Bcast = []*v1.ShareVerifier
// Round2 computes the second round for Gennaro DKG
// Algorithm 3 - Gennaro DKG Round 2
// bcast contains all Round1 broadcast from other participants to this participant
// p2p contains all Round1 P2P send message from other participants to this participant
func (dp *Participant) Round2(
bcast map[uint32]Round1Bcast,
p2p map[uint32]*Round1P2PSendPacket,
) (Round2Bcast, error) {
// Check participant is not empty
if dp == nil || dp.curve == nil {
return nil, internal.ErrNilArguments
}
// Check participant has the correct dkg round number
if dp.round != 2 {
return nil, internal.ErrInvalidRound
}
// Check the input is valid
if bcast == nil || p2p == nil || len(bcast) == 0 || len(p2p) == 0 {
return nil, internal.ErrNilArguments
}
// 1. set sk = x_{ii}
sk := dp.pedersenResult.SecretShares[dp.id-1].Value
// 2. for j in 1,...,n
for id := range bcast {
// 3. if i = j continue
if id == dp.id {
continue
}
// Ensure a valid p2p entry exists
if p2p[id] == nil {
return nil, fmt.Errorf("missing p2p packet for id=%v", id)
}
// 4. If PedersenVerify(E, Q, x_ji, r_ji, {X_ji,...,X_jt}) = false, abort
xji := p2p[id].SecretShare
rji := p2p[id].BlindingShare
bvs := bcast[id]
if ok, err := dp.pedersen.Verify(xji, rji, bvs); !ok {
if err != nil {
return nil, err
} else {
return nil, fmt.Errorf("invalid share for participant id=%v", id)
}
}
// Store other participants' shares xji for usage in round 3
dp.otherParticipantShares[id].Share = p2p[id].SecretShare
// 5. sk = (sk+xji) mod q
// NOTE: we use the EcScalar class to add instead of
// just using big.Int Add and Mod
// because Ed25519 will fail with the big.Int Add and Mod
// and Ed25519 uses different little endian vs big endian
// in big.Int
t1 := sk.BigInt()
t2 := xji.Value.BigInt()
r := dp.scalar.Add(t1, t2)
sk = sk.Field().NewElement(r)
}
// Update internal state
dp.round = 3
// 7. Store ski as participant i's secret key share
dp.skShare = sk
// 6. EchoBroadcast {R_1,...,R_t} to all other participants.
return dp.pedersenResult.Verifiers, nil
}
+89
View File
@@ -0,0 +1,89 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package gennaro
import (
"fmt"
"github.com/sonr-io/sonr/crypto/internal"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
// Round3Bcast contains values that will be broadcast to other participants.
type Round3Bcast = v1.ShareVerifier
// Round3 computes the third round for Gennaro DKG
// Algorithm 4 - Gennaro DKG Round 3
// bcast contains all Round2 broadcast from other participants to this participant.
func (dp *Participant) Round3(bcast map[uint32]Round2Bcast) (*Round3Bcast, *v1.ShamirShare, error) {
// Check participant is not empty
if dp == nil || dp.curve == nil {
return nil, nil, internal.ErrNilArguments
}
// Check participant has the correct dkg round number
if dp.round != 3 {
return nil, nil, internal.ErrInvalidRound
}
// Check the input is valid
if len(bcast) == 0 {
return nil, nil, internal.ErrNilArguments
}
// 1. SetBigInt Pk = R_i1
Pk := dp.pedersenResult.Verifiers[0]
// 2. for j in 1,...,n
for id := range bcast {
// 3. if i = j continue
if id == dp.id {
continue
}
// 4. If FeldmanVerify(E, xji, {R_j1,...,R_jt}) = false; abort
xji := dp.otherParticipantShares[id].Share
vs := bcast[id]
if ok, err := dp.feldman.Verify(xji, vs); !ok {
if err != nil {
return nil, nil, err
} else {
return nil, nil, fmt.Errorf("invalid share for participant #{id}")
}
}
// Store the feldman verifiers for round 4
dp.otherParticipantShares[id].Verifiers = vs
// 5. Pk = Pk+R_j1
temp, err := Pk.Add(bcast[id][0])
if err != nil {
return nil, nil, fmt.Errorf("error in computing Pk+R_j1")
}
Pk = temp
}
// This is a sanity check to make sure nothing went wrong
// when computing the public key
if !Pk.IsOnCurve() || Pk.IsIdentity() {
return nil, nil, fmt.Errorf("invalid public key")
}
// 6. Store Pk as the public verification key
dp.verificationKey = Pk
// Update internal state
dp.round = 4
skShare := v1.ShamirShare{
Identifier: dp.id,
Value: dp.skShare,
}
// Output Pk as the public verification key
return Pk, &skShare, nil
}
+76
View File
@@ -0,0 +1,76 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package gennaro
import (
"math/big"
"github.com/sonr-io/sonr/crypto/core"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/internal"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
// Round4 computes the public shares used by tECDSA during signing
// that are converted to additive shares once the signing participants
// are known. This function is idempotent
func (dp *Participant) Round4() (map[uint32]*curves.EcPoint, error) {
// Check participant is not empty
if dp == nil || dp.curve == nil {
return nil, internal.ErrNilArguments
}
// Check participant has the correct dkg round number
if dp.round != 4 {
return nil, internal.ErrInvalidRound
}
n := len(dp.otherParticipantShares) + 1 //+1 to include self
// Wj's
publicShares := make(map[uint32]*curves.EcPoint, n)
// 1. R = {{R1,...,Rt},{Rij,...,Rit}i!=j}
r := make(map[uint32][]*v1.ShareVerifier, n)
r[dp.id] = dp.pedersenResult.Verifiers
for j := range dp.otherParticipantShares {
r[j] = dp.otherParticipantShares[j].Verifiers
}
// 2. for j in 1,...,n
for j, v := range r {
// 3. Wj = Pk
publicShares[j] = &curves.EcPoint{
Curve: dp.verificationKey.Curve,
X: new(big.Int).Set(dp.verificationKey.X),
Y: new(big.Int).Set(dp.verificationKey.Y),
}
// 4. for k in 1,...,t
for k := 0; k < len(dp.pedersenResult.Verifiers); k++ {
// 5. ck = pj * k mod q
pj := big.NewInt(int64(j))
ck, err := core.Mul(pj, big.NewInt(int64(k+1)), dp.curve.Params().N)
if err != nil {
return nil, err
}
// 6a. t = ck * Rj
t, err := v[k].ScalarMult(ck)
if err != nil {
return nil, err
}
// 6b. Wj = Wj + t
publicShares[j], err = publicShares[j].Add(t)
if err != nil {
return nil, err
}
}
}
return publicShares, nil
}
+419
View File
@@ -0,0 +1,419 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package gennaro
import (
"fmt"
"testing"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/stretchr/testify/require"
"github.com/sonr-io/sonr/crypto/core/curves"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
func TestParticipantRound1Works(t *testing.T) {
p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
require.NoError(t, err)
bcast, p2psend, err := p1.Round1(nil)
require.NoError(t, err)
require.NotNil(t, bcast)
require.NotNil(t, p2psend)
require.Equal(t, len(p2psend), 1)
require.Equal(t, len(bcast), 2)
require.NotNil(t, p1.pedersenResult)
require.Equal(t, p1.round, 2)
_, ok := p2psend[2]
require.True(t, ok)
}
func TestParticipantRound1RepeatCall(t *testing.T) {
p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
require.NoError(t, err)
_, _, err = p1.Round1(nil)
require.NoError(t, err)
_, _, err = p1.Round1(nil)
require.Error(t, err)
}
func TestParticipantRound1BadSecret(t *testing.T) {
p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
require.NoError(t, err)
// secret == 0
secret := []byte{0}
_, _, err = p1.Round1(secret)
require.Error(t, err)
// secret too big
secret = []byte{
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
7,
}
_, _, err = p1.Round1(secret)
require.Error(t, err)
}
func PrepareRound2Input(
t *testing.T,
) (*Participant, *Participant, Round1Bcast, Round1Bcast, Round1P2PSend) {
// Prepare round 1 output of 2 participants
p1, err := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
require.NoError(t, err)
require.Equal(t, p1.otherParticipantShares[2].Id, uint32(2))
p2, err := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1)
require.NoError(t, err)
require.Equal(t, p2.otherParticipantShares[1].Id, uint32(1))
bcast1, _, _ := p1.Round1(nil)
bcast2, p2psend2, _ := p2.Round1(nil)
return p1, p2, bcast1, bcast2, p2psend2
}
// Test Gennaro DKG round2 works
func TestParticipantRound2Works(t *testing.T) {
// Prepare Dkg Round 1 output
p1, _, bcast1, bcast2, p2psend2 := PrepareRound2Input(t)
// Actual Test
require.NotNil(t, bcast1)
require.NotNil(t, bcast2)
require.NotNil(t, p2psend2[1])
bcast := make(map[uint32]Round1Bcast)
p2p := make(map[uint32]*Round1P2PSendPacket)
bcast[1] = bcast1
bcast[2] = bcast2
p2p[2] = p2psend2[1]
round2Out, err := p1.Round2(bcast, p2p)
require.NoError(t, err)
require.NotNil(t, round2Out)
require.Equal(t, len(round2Out), 2)
require.NotNil(t, p1.skShare)
require.Equal(t, p1.round, 3)
require.NotNil(t, p1.otherParticipantShares)
}
// Test Gennaro DKG round 2 repeat call
func TestParticipantRound2RepeatCall(t *testing.T) {
// Prepare Dkg Round 1 output
p1, _, bcast1, bcast2, p2psend2 := PrepareRound2Input(t)
// Actual Test
require.NotNil(t, bcast1)
require.NotNil(t, bcast2)
require.NotNil(t, p2psend2[1])
bcast := make(map[uint32]Round1Bcast)
p2p := make(map[uint32]*Round1P2PSendPacket)
bcast[1] = bcast1
bcast[2] = bcast2
p2p[2] = p2psend2[1]
_, err := p1.Round2(bcast, p2p)
require.NoError(t, err)
_, err = p1.Round2(bcast, p2p)
require.Error(t, err)
}
// Test Gennaro Dkg Round 2 Bad Input
func TestParticipantRound2BadInput(t *testing.T) {
// Prepare Dkg Round 1 output
p1, _, _, _, _ := PrepareRound2Input(t)
bcast := make(map[uint32]Round1Bcast)
p2p := make(map[uint32]*Round1P2PSendPacket)
// Test empty bcast and p2p
_, err := p1.Round2(bcast, p2p)
require.Error(t, err)
// Test nil bcast and p2p
p1, _, _, _, _ = PrepareRound2Input(t)
_, err = p1.Round2(nil, nil)
require.Error(t, err)
// Test tampered input bcast and p2p
p1, _, bcast1, bcast2, p2psend2 := PrepareRound2Input(t)
bcast = make(map[uint32]Round1Bcast)
p2p = make(map[uint32]*Round1P2PSendPacket)
// Tamper bcast1 and p2psend2 by doubling their value
bcast1[1].Y = bcast1[1].Y.Add(bcast1[1].Y, bcast1[1].Y)
p2psend2[1].SecretShare.Value = p2psend2[1].SecretShare.Value.Add(p2psend2[1].SecretShare.Value)
bcast[1] = bcast1
bcast[2] = bcast2
p2p[2] = p2psend2[1]
_, err = p1.Round2(bcast, p2p)
require.Error(t, err)
}
func PrepareRound3Input(t *testing.T) (*Participant, *Participant, map[uint32]Round2Bcast) {
p1, _ := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
p2, _ := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1)
bcast1, p2psend1, _ := p1.Round1(nil)
bcast2, p2psend2, _ := p2.Round1(nil)
bcast := make(map[uint32]Round1Bcast)
p2p1 := make(map[uint32]*Round1P2PSendPacket)
p2p2 := make(map[uint32]*Round1P2PSendPacket)
bcast[1] = bcast1
bcast[2] = bcast2
p2p1[2] = p2psend2[1]
p2p2[1] = p2psend1[2]
round2Out1, _ := p1.Round2(bcast, p2p1)
round2Out2, _ := p2.Round2(bcast, p2p2)
round3Input := make(map[uint32]Round2Bcast)
round3Input[1] = round2Out1
round3Input[2] = round2Out2
return p1, p2, round3Input
}
// Test Gennaro Dkg Round 3 Works
func TestParticipantRound3Works(t *testing.T) {
// Prepare Gennaro Dkg Round 3 Input
p1, p2, round3Input := PrepareRound3Input(t)
// Actual Test
round3Out1, _, err := p1.Round3(round3Input)
require.NoError(t, err)
require.NotNil(t, round3Out1)
round3Out2, _, err := p2.Round3(round3Input)
require.NoError(t, err)
require.NotNil(t, round3Out2)
require.Equal(t, p1.round, 4)
require.Equal(t, p2.round, 4)
require.Equal(t, p1.verificationKey, p2.verificationKey)
// Test if shares recombine properly
s, _ := v1.NewShamir(2, 2, curves.NewField(btcec.S256().N))
sk, err := s.Combine(&v1.ShamirShare{Identifier: p1.id, Value: p1.skShare},
&v1.ShamirShare{Identifier: p2.id, Value: p2.skShare})
require.NoError(t, err)
// Test verification keys are G * sk
x, y := btcec.S256().ScalarBaseMult(sk)
tmp := &curves.EcPoint{
Curve: btcec.S256(),
X: x,
Y: y,
}
require.True(t, tmp.Equals(p1.verificationKey))
require.True(t, tmp.Equals(p2.verificationKey))
}
// Test Gennaro Dkg Round3 Repeat Call
func TestParticipantRound3RepeatCall(t *testing.T) {
// Prepare Round 3 Input
p1, _, round3Input := PrepareRound3Input(t)
// Actual Test
_, _, err := p1.Round3(round3Input)
require.NoError(t, err)
_, _, err = p1.Round3(round3Input)
require.Error(t, err)
}
// Test Gennaro DKG Round 3 Bad Input
func TestParticipantRound3BadInput(t *testing.T) {
// Test empty round 3 input
p1, _, _ := PrepareRound3Input(t)
emptyInput := make(map[uint32]Round2Bcast)
_, _, err := p1.Round3(emptyInput)
require.Error(t, err)
// Test nil round 3 input
p1, _, _ = PrepareRound3Input(t)
_, _, err = p1.Round3(nil)
require.Error(t, err)
// Test tampered round 3 input
p1, _, round3Input := PrepareRound3Input(t)
// Tamper participant2's broadcast
round3Input[2][0], _ = round3Input[2][0].Add(round3Input[2][1])
_, _, err = p1.Round3(round3Input)
require.Error(t, err)
}
// Test Gennaro Dkg Round 4 Works
func TestParticipantRound4Works(t *testing.T) {
// Prepare Gennaro Dkg Round 3 Input
p1, p2, round3Input := PrepareRound3Input(t)
round3Out1, _, err := p1.Round3(round3Input)
require.NoError(t, err)
require.NotNil(t, round3Out1)
round3Out2, _, err := p2.Round3(round3Input)
require.NoError(t, err)
require.NotNil(t, round3Out2)
// Actual test
publicShares1, err := p1.Round4()
require.NoError(t, err)
require.NotNil(t, publicShares1)
publicShares2, err := p2.Round4()
require.NoError(t, err)
require.NotNil(t, publicShares2)
require.Equal(t, publicShares1, publicShares2)
}
// Test Gennaro Dkg Round 4 Works
func TestParticipantRound4RepeatCall(t *testing.T) {
// Prepare Gennaro Dkg Round 3 Input
p1, p2, round3Input := PrepareRound3Input(t)
round3Out1, _, err := p1.Round3(round3Input)
require.NoError(t, err)
require.NotNil(t, round3Out1)
round3Out2, _, err := p2.Round3(round3Input)
require.NoError(t, err)
require.NotNil(t, round3Out2)
// Actual test
publicShares1, err := p1.Round4()
require.NoError(t, err)
require.NotNil(t, publicShares1)
publicShares2, err := p1.Round4()
require.NoError(t, err)
require.NotNil(t, publicShares2)
require.Equal(t, publicShares1, publicShares2)
}
// Test all Gennaro DKG rounds
func TestAllGennaroDkgRounds(t *testing.T) {
// Initiate two participants
p1, _ := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
p2, _ := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1)
// Running round 1
bcast1, p2psend1, _ := p1.Round1(nil)
bcast2, p2psend2, _ := p2.Round1(nil)
bcast := make(map[uint32]Round1Bcast)
p2p1 := make(map[uint32]*Round1P2PSendPacket)
p2p2 := make(map[uint32]*Round1P2PSendPacket)
bcast[1] = bcast1
bcast[2] = bcast2
p2p1[2] = p2psend2[1]
p2p2[1] = p2psend1[2]
// Running round 2
round2Out1, _ := p1.Round2(bcast, p2p1)
round2Out2, _ := p2.Round2(bcast, p2p2)
round3Input := make(map[uint32]Round2Bcast)
round3Input[1] = round2Out1
round3Input[2] = round2Out2
// Running round 3
round3Out1, _, _ := p1.Round3(round3Input)
round3Out2, _, _ := p2.Round3(round3Input)
require.NotNil(t, round3Out1)
require.NotNil(t, round3Out2)
// Running round 4
publicShares1, _ := p1.Round4()
publicShares2, _ := p2.Round4()
// Test output of all rounds
require.Equal(t, publicShares1, publicShares2)
s, _ := v1.NewShamir(2, 2, curves.NewField(btcec.S256().N))
sk, err := s.Combine(&v1.ShamirShare{Identifier: p1.id, Value: p1.skShare},
&v1.ShamirShare{Identifier: p2.id, Value: p2.skShare})
require.NoError(t, err)
x, y := btcec.S256().ScalarBaseMult(sk)
tmp := &curves.EcPoint{
Curve: btcec.S256(),
X: x,
Y: y,
}
require.True(t, tmp.Equals(p1.verificationKey))
require.True(t, tmp.Equals(p2.verificationKey))
}
// Ensure correct functioning when input is missing
func TestParticipant2BadInput(t *testing.T) {
//
// Setup
//
p1, _ := NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 2)
p2, _ := NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 1)
bcast1, _, _ := p1.Round1(nil)
bcast2, p2psend2, _ := p2.Round1(nil)
bcast := make(map[uint32]Round1Bcast)
p2p1 := make(map[uint32]*Round1P2PSendPacket)
bcast[1] = bcast1
bcast[2] = bcast2
// Exclude p2p 2>1
p2p1[4] = p2psend2[1]
// Run round 2
_, err := p1.Round2(bcast, p2p1)
require.Error(t, err)
}
func TestValidIDs(t *testing.T) {
err := fmt.Errorf("")
tests := []struct {
name string
in []uint32
expected error
}{
{"positive-1,2", []uint32{1, 2}, nil},
{"positive-2,1", []uint32{2, 1}, nil},
{"positive-1-10", []uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil},
{"positive-1-10-random", []uint32{10, 9, 6, 5, 3, 2, 8, 7, 1, 4}, nil},
{"negative-1,3", []uint32{1, 3}, err},
{"negative-1-10-missing-5", []uint32{10, 9, 6, 3, 2, 8, 7, 1, 4}, err},
}
// Run all the tests!
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := validIds(test.in)
if test.expected == nil {
require.NoError(t, err)
} else {
require.Error(t, err)
}
})
}
}
// Test newParticipant with arbitrary IDs
func TestParticipantArbitraryIds(t *testing.T) {
_, err := NewParticipant(3, 2, testGenerator, curves.NewK256Scalar(), 4)
require.Error(t, err)
_, err = NewParticipant(0, 2, testGenerator, curves.NewK256Scalar(), 1)
require.Error(t, err)
_, err = NewParticipant(2, 2, testGenerator, curves.NewK256Scalar(), 2, 3, 5)
require.Error(t, err)
_, err = NewParticipant(1, 2, testGenerator, curves.NewK256Scalar(), 4)
require.Error(t, err)
}
+12
View File
@@ -0,0 +1,12 @@
---
aliases: [README]
tags: []
title: README
linter-yaml-title-alias: README
date created: Wednesday, April 17th 2024, 4:11:40 pm
date modified: Thursday, April 18th 2024, 8:19:25 am
---
## Two-party GG20
This package wraps dkg/genarro and specializes it for the 2-party case.
+151
View File
@@ -0,0 +1,151 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// Package gennaro2p wraps dkg/genarro and specializes it for the 2-party case. Simpler API, no
// distinction between broadcast and peer messages, and only counterparty messages are
// used as round inputs since self-inputs are always ignored.
package gennaro2p
import (
"crypto/elliptic"
"fmt"
"github.com/pkg/errors"
"github.com/sonr-io/sonr/crypto/core/curves"
"github.com/sonr-io/sonr/crypto/dkg/gennaro"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
const threshold = 2
// Participant is a DKG player that contains information needed to perform DKG rounds
// and yield a secret key share and public key when finished
type Participant struct {
id uint32
counterPartyId uint32
embedded *gennaro.Participant
blind *curves.EcPoint
}
type Round1Message struct {
Verifiers []*v1.ShareVerifier
SecretShare *v1.ShamirShare
BlindingShare *v1.ShamirShare
Blind *curves.EcPoint
}
type Round2Message struct {
Verifiers []*v1.ShareVerifier
}
type DkgResult struct {
PublicKey *curves.EcPoint
SecretShare *v1.ShamirShare
PublicShares map[uint32]*curves.EcPoint
}
// NewParticipant creates a participant ready to perform a DKG
// blind must be a generator and must be synchronized between counterparties.
// The first participant can set it to `nil` and a secure blinding factor will be
// generated.
func NewParticipant(id, counterPartyId uint32, blind *curves.EcPoint,
scalar curves.EcScalar, curve elliptic.Curve,
) (*Participant, error) {
// Generate blinding value, if required
var err error
if blind == nil {
blind, err = newBlind(scalar, curve)
if err != nil {
return nil, errors.Wrap(err, "generating fresh blinding generator")
}
}
p, err := gennaro.NewParticipant(id, threshold, blind, scalar, counterPartyId)
if err != nil {
return nil, errors.Wrap(err, "created genarro.Participant")
}
return &Participant{id, counterPartyId, p, blind}, nil
}
// Creates a random blinding factor (as a generator) required for pedersen's VSS
func newBlind(curveScalar curves.EcScalar, curve elliptic.Curve) (*curves.EcPoint, error) {
rScalar, err := curveScalar.Random()
if err != nil {
return nil, errors.Wrap(err, "generating blinding scalar")
}
return curves.NewScalarBaseMult(curve, rScalar)
}
// Runs DKG round 1. If `secret` is nil, shares of a new, random signing key are generated.
// Otherwise, the existing secret shares will be refreshed but the privkey and pubkey
// will remain unchanged.
func (p *Participant) Round1(secret []byte) (*Round1Message, error) {
// Run round 1
bcast, p2p, err := p.embedded.Round1(secret)
if err != nil {
return nil, errors.Wrap(err, "calling embedded.Round1()")
}
// Ensure the map has the expected entry so there's no SIGSEGV when we
// repackage it
if p2p[p.counterPartyId] == nil {
return nil, fmt.Errorf("round1 response for p2p[%v] is nil", p.counterPartyId)
}
// Package response
return &Round1Message{
bcast,
p2p[p.counterPartyId].SecretShare,
p2p[p.counterPartyId].BlindingShare,
p.blind,
}, nil
}
// Runs DKG round 2 using the counterparty's output from round 1.
func (p *Participant) Round2(msg *Round1Message) (*Round2Message, error) {
// Run round 2
bcast, err := p.embedded.Round2(
map[uint32]gennaro.Round1Bcast{
p.counterPartyId: msg.Verifiers,
},
map[uint32]*gennaro.Round1P2PSendPacket{
p.counterPartyId: {
SecretShare: msg.SecretShare,
BlindingShare: msg.BlindingShare,
},
})
if err != nil {
return nil, errors.Wrap(err, "calling embedded.Round2()")
}
// Package response
return &Round2Message{bcast}, nil
}
// Completes the DKG using the counterparty's output from round 2.
func (p *Participant) Finalize(msg *Round2Message) (*DkgResult, error) {
// Run round 3
pk, share, err := p.embedded.Round3(
map[uint32]gennaro.Round2Bcast{
p.counterPartyId: msg.Verifiers,
})
if err != nil {
return nil, errors.Wrap(err, "calling embedded.Round3()")
}
// Compute public shares
pubShares, err := p.embedded.Round4()
if err != nil {
return nil, errors.Wrap(err, "calling embedded.Roun4()")
}
// Package response
return &DkgResult{
PublicKey: pk,
SecretShare: share,
PublicShares: pubShares,
}, nil
}
+181
View File
@@ -0,0 +1,181 @@
//
// Copyright Coinbase, Inc. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
package gennaro2p
import (
"crypto/elliptic"
"fmt"
"reflect"
"testing"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/stretchr/testify/require"
"github.com/sonr-io/sonr/crypto/core/curves"
v1 "github.com/sonr-io/sonr/crypto/sharing/v1"
)
var (
curveScalar = curves.NewK256Scalar()
curve = btcec.S256()
)
const (
clientId = 1
serverId = 2
)
// Benchmark full DKG including blind selection and setup
func BenchmarkDkg(b *testing.B) {
if testing.Short() {
b.Skip("skipping test in short mode.")
}
for i := 0; i < b.N; i++ {
_, _, err := dkg()
require.NoError(b, err)
}
}
// Run a DKG and reports the client/server results
func dkg() (*DkgResult, *DkgResult, error) {
// Create client/server
blind, _ := newBlind(curveScalar, curve)
client, err := NewParticipant(clientId, serverId, blind, curveScalar, curve)
if err != nil {
return nil, nil, err
}
server, err := NewParticipant(serverId, clientId, blind, curveScalar, curve)
if err != nil {
return nil, nil, err
}
// R1
clientR1, err := client.Round1(nil)
if err != nil {
return nil, nil, err
}
serverR1, err := server.Round1(nil)
if err != nil {
return nil, nil, err
}
// R2
clientR2, err := client.Round2(serverR1)
if err != nil {
return nil, nil, err
}
serverR2, err := server.Round2(clientR1)
if err != nil {
return nil, nil, err
}
// Finalize
clientResult, err := client.Finalize(serverR2)
if err != nil {
return nil, nil, err
}
serverResult, err := server.Finalize(clientR2)
if err != nil {
return nil, nil, err
}
return clientResult, serverResult, nil
}
// Run a full DKG and verify the absence of errors and valid results
func TestDkg(t *testing.T) {
// Setup and ensure no errors
clientResult, serverResult, err := dkg()
require.NoError(t, err)
require.NotNil(t, clientResult)
require.NotNil(t, serverResult)
// Now run tests
t.Run("produce the same public key", func(t *testing.T) {
require.Equal(t, clientResult.PublicKey, serverResult.PublicKey)
})
t.Run("produce identical public shares", func(t *testing.T) {
require.True(t, reflect.DeepEqual(clientResult.PublicShares, serverResult.PublicShares))
})
t.Run("produce distinct secret shares", func(t *testing.T) {
require.NotEqual(t, clientResult.SecretShare, serverResult.SecretShare)
})
t.Run("produce distinct secret shares", func(t *testing.T) {
require.NotEqual(t, clientResult.SecretShare, serverResult.SecretShare)
})
t.Run("shares sum to expected public key", func(t *testing.T) {
pubkey, err := reconstructPubkey(
clientResult.SecretShare,
serverResult.SecretShare,
curve)
require.NoError(t, err)
require.Equal(t, serverResult.PublicKey, pubkey)
})
}
// Reconstruct the pubkey from 2 shares
func reconstructPubkey(s1, s2 *v1.ShamirShare, curve elliptic.Curve) (*curves.EcPoint, error) {
s, err := v1.NewShamir(2, 2, s1.Value.Field())
if err != nil {
return nil, err
}
sk, err := s.Combine(s1, s2)
if err != nil {
return nil, err
}
x, y := curve.ScalarBaseMult(sk)
return &curves.EcPoint{
Curve: curve,
X: x,
Y: y,
}, nil
}
// Test blind generator helper function produces a value on the expected curve
func TestNewBlindOnCurve(t *testing.T) {
const n = 1024
for i := 0; i < n; i++ {
b, err := newBlind(curveScalar, curve)
require.NoError(t, err)
require.NotNil(t, b)
// Valid point?
require.True(t, b.IsOnCurve() && b.IsValid())
require.True(t, b.IsValid())
require.False(t, b.IsIdentity())
require.False(t, b.IsBasePoint())
}
}
func TestNewBlindProvidesDistinctPoints(t *testing.T) {
const n = 1024
seen := make(map[string]bool, n)
// seen := make(map[core.EcPoint]bool, n)
for i := 0; i < n; i++ {
b, err := newBlind(curveScalar, curve)
require.NoError(t, err)
// serialize so the point is hashable
txt := fmt.Sprintf("%#v", b)
// We shouldn't see the same point twice
ok := seen[txt]
require.False(t, ok)
// store
seen[txt] = true
}
}