input+wallet: extract musig2 session management into new module

In this commit, we extract the musig2 session management into a new
module. This allows us to re-use the session logic elsewhere in unit
tests so we don't need to instantiate the entire wallet.
This commit is contained in:
Olaoluwa Osuntokun committed 2023-08-22 16:30:39 -07:00
1 parent 4733da5ccb
commit 9a65806c09
13 files changed
+402 -371

No files matched your search

+16 -12
View File
@@ -104,8 +104,7 @@ type BtcWallet struct {
blockCache *blockcache.BlockCache
musig2Sessions map[input.MuSig2SessionID]*muSig2State
musig2SessionsMtx sync.Mutex
*input.MusigSessionManager
}
// A compile time check to ensure that BtcWallet implements the
@@ -167,16 +166,21 @@ func New(cfg Config, blockCache *blockcache.BlockCache) (*BtcWallet, error) {
}
}
return &BtcWallet{
cfg: &cfg,
wallet: wallet,
db: wallet.Database(),
chain: cfg.ChainSource,
netParams: cfg.NetParams,
chainKeyScope: chainKeyScope,
blockCache: blockCache,
musig2Sessions: make(map[input.MuSig2SessionID]*muSig2State),
}, nil
finalWallet := &BtcWallet{
cfg: &cfg,
wallet: wallet,
db: wallet.Database(),
chain: cfg.ChainSource,
netParams: cfg.NetParams,
chainKeyScope: chainKeyScope,
blockCache: blockCache,
}
finalWallet.MusigSessionManager = input.NewMusigSessionManager(
finalWallet.fetchPrivKey,
)
return finalWallet, nil
}
// loaderCfg holds optional wallet loader configuration.
-263
View File
@@ -1,13 +1,11 @@
package btcwallet
import (
"crypto/sha256"
"fmt"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg/chainhash"
@@ -469,267 +467,6 @@ func (b *BtcWallet) ComputeInputScript(tx *wire.MsgTx,
}, nil
}
// muSig2State is a struct that holds on to the internal signing session state
// of a MuSig2 session.
type muSig2State struct {
// MuSig2SessionInfo is the associated meta information of the signing
// session.
input.MuSig2SessionInfo
// context is the signing context responsible for keeping track of the
// public keys involved in the signing process.
context input.MuSig2Context
// session is the signing session responsible for keeping track of the
// nonces and partial signatures involved in the signing process.
session input.MuSig2Session
}
// MuSig2CreateSession creates a new MuSig2 signing session using the local
// key identified by the key locator. The complete list of all public keys of
// all signing parties must be provided, including the public key of the local
// signing key. If nonces of other parties are already known, they can be
// submitted as well to reduce the number of method calls necessary later on.
func (b *BtcWallet) MuSig2CreateSession(bipVersion input.MuSig2Version,
keyLoc keychain.KeyLocator, allSignerPubKeys []*btcec.PublicKey,
tweaks *input.MuSig2Tweaks,
otherSignerNonces [][musig2.PubNonceSize]byte) (*input.MuSig2SessionInfo,
error) {
// We need to derive the private key for signing. In the remote signing
// setup, this whole RPC call will be forwarded to the signing
// instance, which requires it to be stateful.
privKey, err := b.fetchPrivKey(&keychain.KeyDescriptor{
KeyLocator: keyLoc,
})
if err != nil {
return nil, fmt.Errorf("error deriving private key: %w", err)
}
// Create a signing context and session with the given private key and
// list of all known signer public keys.
muSigContext, muSigSession, err := input.MuSig2CreateContext(
bipVersion, privKey, allSignerPubKeys, tweaks,
)
if err != nil {
return nil, fmt.Errorf("error creating signing context: %w",
err)
}
// Add all nonces we might've learned so far.
haveAllNonces := false
for _, otherSignerNonce := range otherSignerNonces {
haveAllNonces, err = muSigSession.RegisterPubNonce(
otherSignerNonce,
)
if err != nil {
return nil, fmt.Errorf("error registering other "+
"signer public nonce: %w", err)
}
}
// Register the new session.
combinedKey, err := muSigContext.CombinedKey()
if err != nil {
return nil, fmt.Errorf("error getting combined key: %w", err)
}
session := &muSig2State{
MuSig2SessionInfo: input.MuSig2SessionInfo{
SessionID: input.NewMuSig2SessionID(
combinedKey, muSigSession.PublicNonce(),
),
Version: bipVersion,
PublicNonce: muSigSession.PublicNonce(),
CombinedKey: combinedKey,
TaprootTweak: tweaks.HasTaprootTweak(),
HaveAllNonces: haveAllNonces,
},
context: muSigContext,
session: muSigSession,
}
// The internal key is only calculated if we are using a taproot tweak
// and need to know it for a potential script spend.
if tweaks.HasTaprootTweak() {
internalKey, err := muSigContext.TaprootInternalKey()
if err != nil {
return nil, fmt.Errorf("error getting internal key: %w",
err)
}
session.TaprootInternalKey = internalKey
}
// Since we generate new nonces for every session, there is no way that
// a session with the same ID already exists. So even if we call the API
// twice with the same signers, we still get a new ID.
b.musig2SessionsMtx.Lock()
b.musig2Sessions[session.SessionID] = session
b.musig2SessionsMtx.Unlock()
return &session.MuSig2SessionInfo, nil
}
// MuSig2RegisterNonces registers one or more public nonces of other signing
// participants for a session identified by its ID. This method returns true
// once we have all nonces for all other signing participants.
func (b *BtcWallet) MuSig2RegisterNonces(sessionID input.MuSig2SessionID,
otherSignerNonces [][musig2.PubNonceSize]byte) (bool, error) {
// We hold the lock during the whole operation, we don't want any
// interference with calls that might come through in parallel for the
// same session.
b.musig2SessionsMtx.Lock()
defer b.musig2SessionsMtx.Unlock()
session, ok := b.musig2Sessions[sessionID]
if !ok {
return false, fmt.Errorf("session with ID %x not found",
sessionID[:])
}
// Make sure we don't exceed the number of expected nonces as that would
// indicate something is wrong with the signing setup.
if session.HaveAllNonces {
return true, fmt.Errorf("already have all nonces")
}
numSigners := len(session.context.SigningKeys())
remainingNonces := numSigners - session.session.NumRegisteredNonces()
if len(otherSignerNonces) > remainingNonces {
return false, fmt.Errorf("only %d other nonces remaining but "+
"trying to register %d more", remainingNonces,
len(otherSignerNonces))
}
// Add all nonces we've learned so far.
var err error
for _, otherSignerNonce := range otherSignerNonces {
session.HaveAllNonces, err = session.session.RegisterPubNonce(
otherSignerNonce,
)
if err != nil {
return false, fmt.Errorf("error registering other "+
"signer public nonce: %w", err)
}
}
return session.HaveAllNonces, nil
}
// MuSig2Sign creates a partial signature using the local signing key
// that was specified when the session was created. This can only be
// called when all public nonces of all participants are known and have
// been registered with the session. If this node isn't responsible for
// combining all the partial signatures, then the cleanup parameter
// should be set, indicating that the session can be removed from memory
// once the signature was produced.
func (b *BtcWallet) MuSig2Sign(sessionID input.MuSig2SessionID,
msg [sha256.Size]byte, cleanUp bool) (*musig2.PartialSignature, error) {
// We hold the lock during the whole operation, we don't want any
// interference with calls that might come through in parallel for the
// same session.
b.musig2SessionsMtx.Lock()
defer b.musig2SessionsMtx.Unlock()
session, ok := b.musig2Sessions[sessionID]
if !ok {
return nil, fmt.Errorf("session with ID %x not found",
sessionID[:])
}
// We can only sign once we have all other signer's nonces.
if !session.HaveAllNonces {
return nil, fmt.Errorf("only have %d of %d required nonces",
session.session.NumRegisteredNonces(),
len(session.context.SigningKeys()))
}
// Create our own partial signature with the local signing key.
partialSig, err := input.MuSig2Sign(session.session, msg, true)
if err != nil {
return nil, fmt.Errorf("error signing with local key: %w", err)
}
// Clean up our local state if requested.
if cleanUp {
delete(b.musig2Sessions, sessionID)
}
return partialSig, nil
}
// MuSig2CombineSig combines the given partial signature(s) with the
// local one, if it already exists. Once a partial signature of all
// participants is registered, the final signature will be combined and
// returned.
func (b *BtcWallet) MuSig2CombineSig(sessionID input.MuSig2SessionID,
partialSigs []*musig2.PartialSignature) (*schnorr.Signature, bool,
error) {
// We hold the lock during the whole operation, we don't want any
// interference with calls that might come through in parallel for the
// same session.
b.musig2SessionsMtx.Lock()
defer b.musig2SessionsMtx.Unlock()
session, ok := b.musig2Sessions[sessionID]
if !ok {
return nil, false, fmt.Errorf("session with ID %x not found",
sessionID[:])
}
// Make sure we don't exceed the number of expected partial signatures
// as that would indicate something is wrong with the signing setup.
if session.HaveAllSigs {
return nil, true, fmt.Errorf("already have all partial" +
"signatures")
}
// Add all sigs we got so far.
var (
finalSig *schnorr.Signature
err error
)
for _, otherPartialSig := range partialSigs {
session.HaveAllSigs, err = input.MuSig2CombineSig(
session.session, otherPartialSig,
)
if err != nil {
return nil, false, fmt.Errorf("error combining "+
"partial signature: %w", err)
}
}
// If we have all partial signatures, we should be able to get the
// complete signature now. We also remove this session from memory since
// there is nothing more left to do.
if session.HaveAllSigs {
finalSig = session.session.FinalSig()
delete(b.musig2Sessions, sessionID)
}
return finalSig, session.HaveAllSigs, nil
}
// MuSig2Cleanup removes a session from memory to free up resources.
func (b *BtcWallet) MuSig2Cleanup(sessionID input.MuSig2SessionID) error {
// We hold the lock during the whole operation, we don't want any
// interference with calls that might come through in parallel for the
// same session.
b.musig2SessionsMtx.Lock()
defer b.musig2SessionsMtx.Unlock()
_, ok := b.musig2Sessions[sessionID]
if !ok {
return fmt.Errorf("session with ID %x not found", sessionID[:])
}
delete(b.musig2Sessions, sessionID)
return nil
}
// A compile time check to ensure that BtcWallet implements the Signer
// interface.
var _ input.Signer = (*BtcWallet)(nil)
+2 -3
View File
@@ -656,9 +656,8 @@ func (r *RPCKeyRing) ComputeInputScript(tx *wire.MsgTx,
// submitted as well to reduce the number of method calls necessary later on.
func (r *RPCKeyRing) MuSig2CreateSession(bipVersion input.MuSig2Version,
keyLoc keychain.KeyLocator, pubKeys []*btcec.PublicKey,
tweaks *input.MuSig2Tweaks,
otherNonces [][musig2.PubNonceSize]byte) (*input.MuSig2SessionInfo,
error) {
tweaks *input.MuSig2Tweaks, otherNonces [][musig2.PubNonceSize]byte,
sessionOpts ...musig2.SessionOption) (*input.MuSig2SessionInfo, error) {
apiVersion, err := signrpc.MarshalMuSig2Version(bipVersion)
if err != nil {
+2 -2
View File
@@ -343,8 +343,8 @@ func CreateTestChannels(t *testing.T, chanType channeldb.ChannelType,
Packager: channeldb.NewChannelPackager(shortChanID),
}
aliceSigner := &input.MockSigner{Privkeys: aliceKeys}
bobSigner := &input.MockSigner{Privkeys: bobKeys}
aliceSigner := input.NewMockSigner(aliceKeys, nil)
bobSigner := input.NewMockSigner(bobKeys, nil)
// TODO(roasbeef): make mock version of pre-image store
+8 -8
View File
@@ -587,9 +587,9 @@ func testSpendValidation(t *testing.T, tweakless bool) {
remoteCommitTweak := input.SingleTweakBytes(commitPoint, aliceKeyPub)
localCommitTweak := input.SingleTweakBytes(commitPoint, bobKeyPub)
aliceSelfOutputSigner := &input.MockSigner{
Privkeys: []*btcec.PrivateKey{aliceKeyPriv},
}
aliceSelfOutputSigner := input.NewMockSigner(
[]*btcec.PrivateKey{aliceKeyPriv}, nil,
)
// Calculate the dust limit we'll use for the test.
dustLimit := DustLimitForSize(input.UnknownWitnessSize)
@@ -679,7 +679,7 @@ func testSpendValidation(t *testing.T, tweakless bool) {
t.Fatalf("spend from delay output is invalid: %v", err)
}
localSigner := &input.MockSigner{Privkeys: []*btcec.PrivateKey{bobKeyPriv}}
localSigner := input.NewMockSigner([]*btcec.PrivateKey{bobKeyPriv}, nil)
// Next, we'll test bob spending with the derived revocation key to
// simulate the scenario when Alice broadcasts this commitment
@@ -994,15 +994,15 @@ func createTestChannelsForVectors(tc *testContext, chanType channeldb.ChannelTyp
}
// Create mock signers that can sign for the keys that are used.
localSigner := &input.MockSigner{Privkeys: []*btcec.PrivateKey{
localSigner := input.NewMockSigner([]*btcec.PrivateKey{
tc.localPaymentBasepointSecret, tc.localDelayedPaymentBasepointSecret,
tc.localFundingPrivkey, localDummy1, localDummy2,
}}
}, nil)
remoteSigner := &input.MockSigner{Privkeys: []*btcec.PrivateKey{
remoteSigner := input.NewMockSigner([]*btcec.PrivateKey{
tc.remoteFundingPrivkey, tc.remoteRevocationBasepointSecret,
tc.remotePaymentBasepointSecret, remoteDummy1, remoteDummy2,
}}
}, nil)
remotePool := NewSigPool(1, remoteSigner)
channelRemote, err := NewLightningChannel(