funding: use atomic.Uint64 for chanIDNonce

This lets us get rid of the mutex usage there. We also shift the algo slightly to increment by 1, then use that as the next value, which plays nicer with the atomics.
This commit is contained in:
Olaoluwa Osuntokun authored and Oliver Gugger committed 2024-08-22 18:33:24 +02:00
1 parent 614711748c
commit 75477c8896
1 file changed
+12 -9
+12 -9
View File
@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io" "io"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/blockchain"
@@ -568,8 +569,10 @@ type Manager struct {
// chanIDNonce is a nonce that's incremented for each new funding // chanIDNonce is a nonce that's incremented for each new funding
// reservation created. // reservation created.
chanIDNonce atomic.Uint64
// nonceMtx is a mutex that guards the pendingMusigNonces.
nonceMtx sync.RWMutex nonceMtx sync.RWMutex
chanIDNonce uint64
// pendingMusigNonces is used to store the musig2 nonce we generate to // pendingMusigNonces is used to store the musig2 nonce we generate to
// send funding locked until we receive a funding locked message from // send funding locked until we receive a funding locked message from
@@ -805,13 +808,11 @@ type PendingChanID = [32]byte
// nextPendingChanID returns the next free pending channel ID to be used to // nextPendingChanID returns the next free pending channel ID to be used to
// identify a particular future channel funding workflow. // identify a particular future channel funding workflow.
func (f *Manager) nextPendingChanID() PendingChanID { func (f *Manager) nextPendingChanID() PendingChanID {
// Obtain a fresh nonce. We do this by encoding the current nonce // Obtain a fresh nonce. We do this by encoding the incremented nonce.
// counter, then incrementing it by one. nextNonce := f.chanIDNonce.Add(1)
f.nonceMtx.Lock()
var nonce [8]byte var nonceBytes [8]byte
binary.LittleEndian.PutUint64(nonce[:], f.chanIDNonce) binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
f.chanIDNonce++
f.nonceMtx.Unlock()
// We'll generate the next pending channelID by "encrypting" 32-bytes // We'll generate the next pending channelID by "encrypting" 32-bytes
// of zeroes which'll extract 32 random bytes from our stream cipher. // of zeroes which'll extract 32 random bytes from our stream cipher.
@@ -819,7 +820,9 @@ func (f *Manager) nextPendingChanID() PendingChanID {
nextChanID PendingChanID nextChanID PendingChanID
zeroes [32]byte zeroes [32]byte
) )
salsa20.XORKeyStream(nextChanID[:], zeroes[:], nonce[:], &f.chanIDKey) salsa20.XORKeyStream(
nextChanID[:], zeroes[:], nonceBytes[:], &f.chanIDKey,
)
return nextChanID return nextChanID
} }