Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions tss/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Binance

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 48 additions & 0 deletions tss/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
MODULE = github.com/bnb-chain/tss-lib/v2
PACKAGES = $(shell go list ./... | grep -v '/vendor/')

all: protob test

########################################
### Protocol Buffers

protob:
@echo "--> Building Protocol Buffers"
@for protocol in message signature ecdsa-keygen ecdsa-signing ecdsa-resharing eddsa-keygen eddsa-signing eddsa-resharing; do \
echo "Generating $$protocol.pb.go" ; \
protoc --go_out=. ./protob/$$protocol.proto ; \
done

build: protob
go fmt ./...

########################################
### Testing

test_unit:
@echo "--> Running Unit Tests"
@echo "!!! WARNING: This will take a long time :)"
go clean -testcache
go test -timeout 60m $(PACKAGES)

test_unit_race:
@echo "--> Running Unit Tests (with Race Detection)"
@echo "!!! WARNING: This will take a long time :)"
go clean -testcache
go test -timeout 60m -race $(PACKAGES)

test:
make test_unit

########################################
### Pre Commit

pre_commit: build test

########################################

# To avoid unintended conflicts with file names, always add to .PHONY
# # unless there is a reason not to.
# # https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html
.PHONY: protob build test_unit test_unit_race test

162 changes: 162 additions & 0 deletions tss/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Multi-Party Threshold Signature Scheme
[![MIT licensed][1]][2] [![GoDoc][3]][4] [![Go Report Card][5]][6]

[1]: https://img.shields.io/badge/license-MIT-blue.svg
[2]: LICENSE
[3]: https://godoc.org/github.com/bnb-chain/tss-lib?status.svg
[4]: https://godoc.org/github.com/bnb-chain/tss-lib
[5]: https://goreportcard.com/badge/github.com/bnb-chain/tss-lib
[6]: https://goreportcard.com/report/github.com/bnb-chain/tss-lib

Permissively MIT Licensed.

Note! This is a library for developers. You may find a TSS tool that you can use with the Binance Chain CLI [here](https://docs.binance.org/tss.html).

## Introduction
This is an implementation of multi-party {t,n}-threshold ECDSA (Elliptic Curve Digital Signature Algorithm) based on Gennaro and Goldfeder CCS 2018 [1] and EdDSA (Edwards-curve Digital Signature Algorithm) following a similar approach.

This library includes three protocols:

* Key Generation for creating secret shares with no trusted dealer ("keygen").
* Signing for using the secret shares to generate a signature ("signing").
* Dynamic Groups to change the group of participants while keeping the secret ("resharing").

⚠️ Do not miss [these important notes](#how-to-use-this-securely) on implementing this library securely

## Rationale
ECDSA is used extensively for crypto-currencies such as Bitcoin, Ethereum (secp256k1 curve), NEO (NIST P-256 curve) and many more.

EdDSA is used extensively for crypto-currencies such as Cardano, Aeternity, Stellar Lumens and many more.

For such currencies this technique may be used to create crypto wallets where multiple parties must collaborate to sign transactions. See [MultiSig Use Cases](https://en.bitcoin.it/wiki/Multisignature#Multisignature_Applications)

One secret share per key/address is stored locally by each participant and these are kept safe by the protocol – they are never revealed to others at any time. Moreover, there is no trusted dealer of the shares.

In contrast to MultiSig solutions, transactions produced by TSS preserve the privacy of the signers by not revealing which `t+1` participants were involved in their signing.

There is also a performance bonus in that blockchain nodes may check the validity of a signature without any extra MultiSig logic or processing.

## Usage
You should start by creating an instance of a `LocalParty` and giving it the arguments that it needs.

The `LocalParty` that you use should be from the `keygen`, `signing` or `resharing` package depending on what you want to do.

### Setup
```go
// When using the keygen party it is recommended that you pre-compute the "safe primes" and Paillier secret beforehand because this can take some time.
// This code will generate those parameters using a concurrency limit equal to the number of available CPU cores.
preParams, _ := keygen.GeneratePreParams(1 * time.Minute)

// Create a `*PartyID` for each participating peer on the network (you should call `tss.NewPartyID` for each one)
parties := tss.SortPartyIDs(getParticipantPartyIDs())

// Set up the parameters
// Note: The `id` and `moniker` fields are for convenience to allow you to easily track participants.
// The `id` should be a unique string representing this party in the network and `moniker` can be anything (even left blank).
// The `uniqueKey` is a unique identifying key for this peer (such as its p2p public key) as a big.Int.
thisParty := tss.NewPartyID(id, moniker, uniqueKey)
ctx := tss.NewPeerContext(parties)

// Select an elliptic curve
// use ECDSA
curve := tss.S256()
// or use EdDSA
// curve := tss.Edwards()

params := tss.NewParameters(curve, ctx, thisParty, len(parties), threshold)

// You should keep a local mapping of `id` strings to `*PartyID` instances so that an incoming message can have its origin party's `*PartyID` recovered for passing to `UpdateFromBytes` (see below)
partyIDMap := make(map[string]*PartyID)
for _, id := range parties {
partyIDMap[id.Id] = id
}
```

### Keygen
Use the `keygen.LocalParty` for the keygen protocol. The save data you receive through the `endCh` upon completion of the protocol should be persisted to secure storage.

```go
party := keygen.NewLocalParty(params, outCh, endCh, preParams) // Omit the last arg to compute the pre-params in round 1
go func() {
err := party.Start()
// handle err ...
}()
```

### Signing
Use the `signing.LocalParty` for signing and provide it with a `message` to sign. It requires the key data obtained from the keygen protocol. The signature will be sent through the `endCh` once completed.

Please note that `t+1` signers are required to sign a message and for optimal usage no more than this should be involved. Each signer should have the same view of who the `t+1` signers are.

```go
party := signing.NewLocalParty(message, params, ourKeyData, outCh, endCh)
go func() {
err := party.Start()
// handle err ...
}()
```

### Re-Sharing
Use the `resharing.LocalParty` to re-distribute the secret shares. The save data received through the `endCh` should overwrite the existing key data in storage, or write new data if the party is receiving a new share.

Please note that `ReSharingParameters` is used to give this Party more context about the re-sharing that should be carried out.

```go
party := resharing.NewLocalParty(params, ourKeyData, outCh, endCh)
go func() {
err := party.Start()
// handle err ...
}()
```

⚠️ During re-sharing the key data may be modified during the rounds. Do not ever overwrite any data saved on disk until the final struct has been received through the `end` channel.

## Messaging
In these examples the `outCh` will collect outgoing messages from the party and the `endCh` will receive save data or a signature when the protocol is complete.

During the protocol you should provide the party with updates received from other participating parties on the network.

A `Party` has two thread-safe methods on it for receiving updates.
```go
// The main entry point when updating a party's state from the wire
UpdateFromBytes(wireBytes []byte, from *tss.PartyID, isBroadcast bool) (ok bool, err *tss.Error)
// You may use this entry point to update a party's state when running locally or in tests
Update(msg tss.ParsedMessage) (ok bool, err *tss.Error)
```

And a `tss.Message` has the following two methods for converting messages to data for the wire:
```go
// Returns the encoded message bytes to send over the wire along with routing information
WireBytes() ([]byte, *tss.MessageRouting, error)
// Returns the protobuf wrapper message struct, used only in some exceptional scenarios (i.e. mobile apps)
WireMsg() *tss.MessageWrapper
```

In a typical use case, it is expected that a transport implementation will consume message bytes via the `out` channel of the local `Party`, send them to the destination(s) specified in the result of `msg.GetTo()`, and pass them to `UpdateFromBytes` on the receiving end.

This way there is no need to deal with Marshal/Unmarshalling Protocol Buffers to implement a transport.

## Changes of Preparams of ECDSA in v2.0

Two fields PaillierSK.P and PaillierSK.Q is added in version 2.0. They are used to generate Paillier key proofs. Key valuts generated from versions before 2.0 need to regenerate(resharing) the key valuts to update the praparams with the necessary fileds filled.

## How to use this securely

⚠️ This section is important. Be sure to read it!

The transport for messaging is left to the application layer and is not provided by this library. Each one of the following paragraphs should be read and followed carefully as it is crucial that you implement a secure transport to ensure safety of the protocol.

When you build a transport, it should offer a broadcast channel as well as point-to-point channels connecting every pair of parties. Your transport should also employ suitable end-to-end encryption (TLS with an [AEAD cipher](https://en.wikipedia.org/wiki/Authenticated_encryption#Authenticated_encryption_with_associated_data_(AEAD)) is recommended) between parties to ensure that a party can only read the messages sent to it.

Within your transport, each message should be wrapped with a **session ID** that is unique to a single run of the keygen, signing or re-sharing rounds. This session ID should be agreed upon out-of-band and known only by the participating parties before the rounds begin. Upon receiving any message, your program should make sure that the received session ID matches the one that was agreed upon at the start.

Additionally, there should be a mechanism in your transport to allow for "reliable broadcasts", meaning parties can broadcast a message to other parties such that it's guaranteed that each one receives the same message. There are several examples of algorithms online that do this by sharing and comparing hashes of received messages.

Timeouts and errors should be handled by your application. The method `WaitingFor` may be called on a `Party` to get the set of other parties that it is still waiting for messages from. You may also get the set of culprit parties that caused an error from a `*tss.Error`.

## Security Audit
A full review of this library was carried out by Kudelski Security and their final report was made available in October, 2019. A copy of this report [`audit-binance-tss-lib-final-20191018.pdf`](https://github.com/bnb-chain/tss-lib/releases/download/v1.0.0/audit-binance-tss-lib-final-20191018.pdf) may be found in the v1.0.0 release notes of this repository.

## References
\[1\] https://eprint.iacr.org/2019/114.pdf

156 changes: 156 additions & 0 deletions tss/common/hash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// Copyright © 2019 Binance
//
// This file is part of Binance. The full Binance copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.

package common

import (
"crypto"
_ "crypto/sha512"
"encoding/binary"
"math/big"
)

const (
hashInputDelimiter = byte('$')
)

// SHA-512/256 is protected against length extension attacks and is more performant than SHA-256 on 64-bit architectures.
// https://en.wikipedia.org/wiki/Template:Comparison_of_SHA_functions
func SHA512_256(in ...[]byte) []byte {
var data []byte
state := crypto.SHA512_256.New()
inLen := len(in)
if inLen == 0 {
return nil
}
bzSize := 0
// prevent hash collisions with this prefix containing the block count
inLenBz := make([]byte, 64/8)
// converting between int and uint64 doesn't change the sign bit, but it may be interpreted as a larger value.
// this prefix is never read/interpreted, so that doesn't matter.
binary.LittleEndian.PutUint64(inLenBz, uint64(inLen))
for _, bz := range in {
bzSize += len(bz)
}
dataCap := len(inLenBz) + bzSize + inLen + (inLen * 8)
data = make([]byte, 0, dataCap)
data = append(data, inLenBz...)
for _, bz := range in {
data = append(data, bz...)
data = append(data, hashInputDelimiter) // safety delimiter
dataLen := make([]byte, 8) // 64-bits
binary.LittleEndian.PutUint64(dataLen, uint64(len(bz)))
data = append(data, dataLen...) // Security audit: length of each byte buffer should be added after
// each security delimiters in order to enforce proper domain separation
}
// n < len(data) or an error will never happen.
// see: https://golang.org/pkg/hash/#Hash and https://github.com/golang/go/wiki/Hashing#the-hashhash-interface
if _, err := state.Write(data); err != nil {
Logger.Errorf("SHA512_256 Write() failed: %v", err)
return nil
}
return state.Sum(nil)
}

func SHA512_256i(in ...*big.Int) *big.Int {
var data []byte
state := crypto.SHA512_256.New()
inLen := len(in)
if inLen == 0 {
return nil
}
bzSize := 0
// prevent hash collisions with this prefix containing the block count
inLenBz := make([]byte, 64/8)
// converting between int and uint64 doesn't change the sign bit, but it may be interpreted as a larger value.
// this prefix is never read/interpreted, so that doesn't matter.
binary.LittleEndian.PutUint64(inLenBz, uint64(inLen))
ptrs := make([][]byte, inLen)
for i, n := range in {
ptrs[i] = n.Bytes()
bzSize += len(ptrs[i])
}
dataCap := len(inLenBz) + bzSize + inLen + (inLen * 8)
data = make([]byte, 0, dataCap)
data = append(data, inLenBz...)
for i := range in {
data = append(data, ptrs[i]...)
data = append(data, hashInputDelimiter) // safety delimiter
dataLen := make([]byte, 8) // 64-bits
binary.LittleEndian.PutUint64(dataLen, uint64(len(ptrs[i])))
data = append(data, dataLen...) // Security audit: length of each byte buffer should be added after
// each security delimiters in order to enforce proper domain separation
}
// n < len(data) or an error will never happen.
// see: https://golang.org/pkg/hash/#Hash and https://github.com/golang/go/wiki/Hashing#the-hashhash-interface
if _, err := state.Write(data); err != nil {
Logger.Errorf("SHA512_256i Write() failed: %v", err)
return nil
}
return new(big.Int).SetBytes(state.Sum(nil))
}

// SHA512_256i_TAGGED tagged version of SHA512_256i
func SHA512_256i_TAGGED(tag []byte, in ...*big.Int) *big.Int {
tagBz := SHA512_256(tag)
var data []byte
state := crypto.SHA512_256.New()
state.Write(tagBz)
state.Write(tagBz)
inLen := len(in)
if inLen == 0 {
return nil
}
bzSize := 0
// prevent hash collisions with this prefix containing the block count
inLenBz := make([]byte, 64/8)
// converting between int and uint64 doesn't change the sign bit, but it may be interpreted as a larger value.
// this prefix is never read/interpreted, so that doesn't matter.
binary.LittleEndian.PutUint64(inLenBz, uint64(inLen))
ptrs := make([][]byte, inLen)
for i, n := range in {
if n == nil {
ptrs[i] = zero.Bytes()
} else {
ptrs[i] = n.Bytes()
}
bzSize += len(ptrs[i])
}
dataCap := len(inLenBz) + bzSize + inLen + (inLen * 8)
data = make([]byte, 0, dataCap)
data = append(data, inLenBz...)
for i := range in {
data = append(data, ptrs[i]...)
data = append(data, hashInputDelimiter) // safety delimiter
dataLen := make([]byte, 8) // 64-bits
binary.LittleEndian.PutUint64(dataLen, uint64(len(ptrs[i])))
data = append(data, dataLen...) // Security audit: length of each byte buffer should be added after
// each security delimiters in order to enforce proper domain separation
}
// n < len(data) or an error will never happen.
// see: https://golang.org/pkg/hash/#Hash and https://github.com/golang/go/wiki/Hashing#the-hashhash-interface
if _, err := state.Write(data); err != nil {
Logger.Error(err)
return nil
}
return new(big.Int).SetBytes(state.Sum(nil))
}

func SHA512_256iOne(in *big.Int) *big.Int {
var data []byte
state := crypto.SHA512_256.New()
if in == nil {
return nil
}
data = in.Bytes()
// n < len(data) or an error will never happen.
// see: https://golang.org/pkg/hash/#Hash and https://github.com/golang/go/wiki/Hashing#the-hashhash-interface
if _, err := state.Write(data); err != nil {
Logger.Errorf("SHA512_256iOne Write() failed: %v", err)
return nil
}
return new(big.Int).SetBytes(state.Sum(nil))
}
Loading
Loading