Skip to content

Commit 236b1f6

Browse files
committed
fundign: 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 a3d876e commit 236b1f6

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

funding/manager.go

Lines changed: 11 additions & 8 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"
@@ -561,10 +562,11 @@ type Manager struct {
561562
// temporary channel ID's.
562563
chanIDKey [32]byte
563564

565+
nonceMtx sync.RWMutex
566+
564567
// chanIDNonce is a nonce that's incremented for each new funding
565568
// reservation created.
566-
nonceMtx sync.RWMutex
567-
chanIDNonce uint64
569+
chanIDNonce atomic.Uint64
568570

569571
// pendingMusigNonces is used to store the musig2 nonce we generate to
570572
// send funding locked until we receive a funding locked message from
@@ -802,19 +804,20 @@ type PendingChanID = [32]byte
802804
func (f *Manager) nextPendingChanID() PendingChanID {
803805
// Obtain a fresh nonce. We do this by encoding the current nonce
804806
// counter, then incrementing it by one.
805-
f.nonceMtx.Lock()
806-
var nonce [8]byte
807-
binary.LittleEndian.PutUint64(nonce[:], f.chanIDNonce)
808-
f.chanIDNonce++
809-
f.nonceMtx.Unlock()
807+
nextNonce := f.chanIDNonce.Add(1)
808+
809+
var nonceBytes [8]byte
810+
binary.LittleEndian.PutUint64(nonceBytes[:], nextNonce)
810811

811812
// We'll generate the next pending channelID by "encrypting" 32-bytes
812813
// of zeroes which'll extract 32 random bytes from our stream cipher.
813814
var (
814815
nextChanID PendingChanID
815816
zeroes [32]byte
816817
)
817-
salsa20.XORKeyStream(nextChanID[:], zeroes[:], nonce[:], &f.chanIDKey)
818+
salsa20.XORKeyStream(
819+
nextChanID[:], zeroes[:], nonceBytes[:], &f.chanIDKey,
820+
)
818821

819822
return nextChanID
820823
}

0 commit comments

Comments
 (0)