Skip to content

Commit 75477c8

Browse files
Roasbeefguggero
authored andcommitted
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.
1 parent 6147117 commit 75477c8

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

funding/manager.go

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"io"
88
"sync"
9+
"sync/atomic"
910
"time"
1011

1112
"github.com/btcsuite/btcd/blockchain"
@@ -568,8 +569,10 @@ type Manager struct {
568569

569570
// chanIDNonce is a nonce that's incremented for each new funding
570571
// reservation created.
571-
nonceMtx sync.RWMutex
572-
chanIDNonce uint64
572+
chanIDNonce atomic.Uint64
573+
574+
// nonceMtx is a mutex that guards the pendingMusigNonces.
575+
nonceMtx sync.RWMutex
573576

574577
// pendingMusigNonces is used to store the musig2 nonce we generate to
575578
// send funding locked until we receive a funding locked message from
@@ -805,21 +808,21 @@ type PendingChanID = [32]byte
805808
// nextPendingChanID returns the next free pending channel ID to be used to
806809
// identify a particular future channel funding workflow.
807810
func (f *Manager) nextPendingChanID() PendingChanID {
808-
// Obtain a fresh nonce. We do this by encoding the current nonce
809-
// counter, then incrementing it by one.
810-
f.nonceMtx.Lock()
811-
var nonce [8]byte
812-
binary.LittleEndian.PutUint64(nonce[:], f.chanIDNonce)
813-
f.chanIDNonce++
814-
f.nonceMtx.Unlock()
811+
// Obtain a fresh nonce. We do this by encoding the incremented nonce.
812+
nextNonce := f.chanIDNonce.Add(1)
813+
814+
var nonceBytes [8]byte
815+
binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
815816

816817
// We'll generate the next pending channelID by "encrypting" 32-bytes
817818
// of zeroes which'll extract 32 random bytes from our stream cipher.
818819
var (
819820
nextChanID PendingChanID
820821
zeroes [32]byte
821822
)
822-
salsa20.XORKeyStream(nextChanID[:], zeroes[:], nonce[:], &f.chanIDKey)
823+
salsa20.XORKeyStream(
824+
nextChanID[:], zeroes[:], nonceBytes[:], &f.chanIDKey,
825+
)
823826

824827
return nextChanID
825828
}

0 commit comments

Comments
 (0)