Skip to content

Commit dd357fb

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 8ba3f3a commit dd357fb

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"
@@ -567,8 +568,10 @@ type Manager struct {
567568

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

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

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

823826
return nextChanID
824827
}

0 commit comments

Comments
 (0)