Merge pull request #11281 from ziggie1984/lint-intrange-cleanup
What changed, and why it matters
This commit is a large but purely cosmetic code cleanup. It replaces old-style Go for loops like 'for i := 0; i < N; i++' with the newer 'for i := range N' syntax introduced in Go 1.22. No logic, behavior, or security properties of the code are changed.
No security action needed. Treat as normal maintenance; standard review/CI verification is sufficient.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit updates 49 files across the lnd codebase to use Go’s integer range syntax (‘for range N’ / ‘for i := range N’). These are syntactic substitutions only: loop bounds, variable types, and body code remain identical. The change is a lint-driven refactor (intrange cleanup) and does not alter serialization, wire parsing, concurrency, rate limiting, or any runtime semantics.
Changed components
Inspect captured patch +144 / −144
### batch/batch_test.go
@@ -151,7 +151,7 @@ func TestReadOnly(t *testing.T) {
writes = 0
writesMu sync.Mutex
)
- for i := 0; i < 100; i++ {
+ for range 100 {
// Spin off the reads.
wg.Add(1)
go func() {
@@ -286,7 +286,7 @@ func TestReadOnly(t *testing.T) {
// Execute a bunch of read-only requests in parallel. These
// should be batched together and kept as read only.
var wg sync.WaitGroup
- for i := 0; i < 100; i++ {
+ for i := range 100 {
wg.Add(1)
go func(i int) {
defer wg.Done()
@@ -311,7 +311,7 @@ func TestReadOnly(t *testing.T) {
// batched together and the tx should be updated to read-write.
// We just simulate this scenario. Write transactions succeeding
// are how we know that the tx was upgraded to read-write.
- for i := 0; i < 100; i++ {
+ for i := range 100 {
// Spin off the writes.
wg.Add(1)
go func(i int) {
@@ -414,7 +414,7 @@ func BenchmarkBoltBatching(b *testing.B) {
b.ResetTimer()
var wg sync.WaitGroup
- for i := 0; i < b.N; i++ {
+ for range b.N {
wg.Add(1)
go func() {
defer wg.Done()
@@ -439,7 +439,7 @@ func BenchmarkBoltBatching(b *testing.B) {
b.ResetTimer()
err := db.Update(func(tx kvdb.RwTx) error {
- for i := 0; i < b.N; i++ {
+ for range b.N {
writeRecord(b, tx)
}
@@ -470,7 +470,7 @@ func BenchmarkBoltBatching(b *testing.B) {
b.ResetTimer()
var wg sync.WaitGroup
- for i := 0; i < b.N; i++ {
+ for range b.N {
wg.Add(1)
go func() {
defer wg.Done()
@@ -594,7 +594,7 @@ func benchmarkSQLBatching(b *testing.B, sqlite bool) {
b.ResetTimer()
var wg sync.WaitGroup
- for i := 0; i < b.N; i++ {
+ for i := range b.N {
wg.Add(1)
go func(j int) {
defer wg.Done()
@@ -624,7 +624,7 @@ func benchmarkSQLBatching(b *testing.B, sqlite bool) {
err := db.ExecTx(
ctx, opts,
func(tx *sqlc.Queries) error {
- for i := 0; i < b.N; i++ {
+ for i := range b.N {
writeRecord(b, tx, int64(i))
}
@@ -654,7 +654,7 @@ func benchmarkSQLBatching(b *testing.B, sqlite bool) {
b.ResetTimer()
var wg sync.WaitGroup
- for i := 0; i < b.N; i++ {
+ for i := range b.N {
wg.Add(1)
go func(j int) {
defer wg.Done()
### bolt12/bech32.go
@@ -301,7 +301,7 @@ func isWhitespace(c byte) bool {
// continuation stripping.
func toBech32Bytes(s string) ([]byte, error) {
result := make([]byte, len(s))
- for i := 0; i < len(s); i++ {
+ for i := range len(s) {
idx := strings.IndexByte(charset, s[i])
if idx < 0 {
return nil, fmt.Errorf(
### brontide/bench_test.go
@@ -87,7 +87,7 @@ func BenchmarkWriteMessage(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
- for i := 0; i < b.N; i++ {
+ for range b.N {
// Write our massive message, then call flush to actually write
// the encrypted message This simulates a full write operation
// to a network.
### chanstate/codec.go
@@ -434,7 +434,7 @@ func ReadElement(r io.Reader, element interface{}) error { //nolint:funlen
}
*e = make([]net.Addr, numAddrs)
- for i := uint32(0); i < numAddrs; i++ {
+ for i := range numAddrs {
addr, err := graphdb.DeserializeAddr(r)
if err != nil {
return err
### chanstate/forwarding.go
@@ -123,7 +123,7 @@ func (f *PkgFilter) Equal(f2 *PkgFilter) bool {
// otherwise.
func (f *PkgFilter) IsFull() bool {
// Batch validate bytes that are fully used.
- for i := uint16(0); i < f.count/8; i++ {
+ for i := range f.count / 8 {
if f.filter[i] != 0xFF {
return false
}
### chanstate/kv_commitment.go
@@ -149,7 +149,7 @@ func DeserializeHtlcs(r io.Reader) ([]HTLC, error) {
}
htlcs = make([]HTLC, numHtlcs)
- for i := uint16(0); i < numHtlcs; i++ {
+ for i := range numHtlcs {
var onionAndExtraData []byte
if err := ReadElements(r,
&htlcs[i].Signature, &htlcs[i].RHash, &htlcs[i].Amt,
@@ -528,7 +528,7 @@ func DeserializeLogUpdates(r io.Reader) ([]LogUpdate, error) {
}
logUpdates := make([]LogUpdate, numUpdates)
- for i := 0; i < int(numUpdates); i++ {
+ for i := range numUpdates {
err := ReadElements(r,
&logUpdates[i].LogIndex, &logUpdates[i].UpdateMsg,
)
@@ -622,7 +622,7 @@ func DeserializeCommitDiff(r io.Reader) (*CommitDiff, error) {
}
d.OpenedCircuitKeys = make([]models.CircuitKey, numOpenRefs)
- for i := 0; i < int(numOpenRefs); i++ {
+ for i := range numOpenRefs {
err := ReadElements(r,
&d.OpenedCircuitKeys[i].ChanID,
&d.OpenedCircuitKeys[i].HtlcID)
@@ -637,7 +637,7 @@ func DeserializeCommitDiff(r io.Reader) (*CommitDiff, error) {
}
d.ClosedCircuitKeys = make([]models.CircuitKey, numClosedRefs)
- for i := 0; i < int(numClosedRefs); i++ {
+ for i := range numClosedRefs {
err := ReadElements(r,
&d.ClosedCircuitKeys[i].ChanID,
&d.ClosedCircuitKeys[i].HtlcID)
### config_builder.go
@@ -1260,7 +1260,7 @@ func (d *DefaultDatabaseBuilder) BuildDatabase(
// Make sure we attach the custom migration function to
// the correct migration version.
- for i := 0; i < len(migrations); i++ {
+ for i := range migrations {
version := migrations[i].Version
switch version {
case invoiceMigration:
### contractcourt/chain_watcher_coop_reorg_test.go
@@ -171,7 +171,7 @@ func TestChainWatcherCoopCloseRapidReorgs(t *testing.T) {
harness.sendSpend(tx)
// Trigger multiple rapid reorgs to stress the state machine.
- for i := 0; i < 5; i++ {
+ for i := range 5 {
harness.waitForConfRegistration()
harness.mineBlocks(1)
harness.triggerReorg(tx, int32(i+1))
### contractcourt/chain_watcher_reorg_test.go
@@ -134,7 +134,7 @@ func generateAltTxsForReorgs(h *chainWatcherTestHarness, ct closeType,
altTxs := make([]*wire.MsgTx, numReorgs)
- for i := 0; i < numReorgs; i++ {
+ for i := range numReorgs {
switch ct {
case closeTypeBreach, closeTypeRemoteUnilateral,
closeTypeLocalForce:
@@ -215,7 +215,7 @@ func testReorgProperties(testingT *testing.T) func(*rapid.T) {
// Execute the set of re-orgs, based on our random sample, we'll
// mine N blocks, do a re-org of size N, then wait for
// detection, and repeat.
- for i := 0; i < numReorgs; i++ {
+ for i := range numReorgs {
// Generate random reorg depth (1 to requiredConfs-1).
// We cap it to avoid reorging too far back.
reorgDepth := rapid.IntRange(
### discovery/gossiper_test.go
@@ -4177,7 +4177,7 @@ func TestRateLimitChannelUpdates(t *testing.T) {
require.NoError(t, err)
timeout := time.After(2 * trickleDelay)
- for i := 0; i < 3; i++ {
+ for range 3 {
select {
case <-tCtx.broadcastedMessage:
case <-timeout:
@@ -4238,7 +4238,7 @@ func TestRateLimitChannelUpdates(t *testing.T) {
// seconds with a max burst of 5 per direction. We'll process the max
// burst of one direction first. None of these should be rate limited.
updateSameDirection := keepAliveUpdate
- for i := uint32(0); i < uint32(tCtx.gossiper.cfg.MaxChannelUpdateBurst); i++ { //nolint:ll
+ for range uint32(tCtx.gossiper.cfg.MaxChannelUpdateBurst) {
updateSameDirection.Timestamp++
updateSameDirection.BaseFee++
require.NoError(
@@ -4264,7 +4264,7 @@ func TestRateLimitChannelUpdates(t *testing.T) {
// Wait for the next interval to tick. Since we've only waited for one,
// only one more update is allowed.
<-time.After(tCtx.gossiper.cfg.ChannelUpdateInterval)
- for i := 0; i < tCtx.gossiper.cfg.MaxChannelUpdateBurst; i++ {
+ for i := range tCtx.gossiper.cfg.MaxChannelUpdateBurst {
updateSameDirection.Timestamp++
updateSameDirection.BaseFee++
require.NoError(t, signUpdate(remoteKeyPriv1, &updateSameDirection))
### discovery/sync_manager.go
@@ -247,7 +247,7 @@ func newSyncManager(cfg *SyncManagerCfg) *SyncManager {
}
filterSema := make(chan struct{}, filterConcurrency)
- for i := 0; i < filterConcurrency; i++ {
+ for range filterConcurrency {
filterSema <- struct{}{}
}
@@ -684,7 +684,7 @@ func (m *SyncManager) promoteSyncers() {
log.Debugf("Attempting to transition %v passive "+
"GossipSyncers to active", numActiveLeft)
- for i := 0; i < numActiveLeft; i++ {
+ for range numActiveLeft {
chooseRandomSyncer(
m.inactiveSyncers, m.transitionPassiveSyncer,
)
### discovery/syncer_atomic_test.go
@@ -116,7 +116,7 @@ func TestGossipSyncerSingleBacklogSend(t *testing.T) {
earlyReturns atomic.Int32
)
- for i := 0; i < 5; i++ {
+ for range 5 {
wg.Add(1)
go func() {
defer wg.Done()
### discovery/syncer_queue_test.go
@@ -74,7 +74,7 @@ func TestGossipSyncerQueueTimestampRangeFull(t *testing.T) {
// Fill the queue to capacity (10 messages for test syncer).
queueSize := 10
- for i := 0; i < queueSize; i++ {
+ for i := range queueSize {
msg := &lnwire.GossipTimestampRange{
ChainHash: chainhash.Hash{byte(i)},
FirstTimestamp: uint32(i),
@@ -121,12 +121,12 @@ func TestGossipSyncerQueueTimestampRangeConcurrent(t *testing.T) {
numGoroutines := 20
messagesPerGoroutine := 10
- for i := 0; i < numGoroutines; i++ {
+ for i := range numGoroutines {
wg.Add(1)
go func(id int) {
defer wg.Done()
- for j := 0; j < messagesPerGoroutine; j++ {
+ for j := range messagesPerGoroutine {
msg := &lnwire.GossipTimestampRange{
ChainHash: chainhash.Hash{
byte(id), byte(j),
@@ -277,7 +277,7 @@ func TestGossipSyncerQueueInvariants(t *testing.T) {
)
// Run through each of the operations.
- for i := 0; i < numOps; i++ {
+ for range numOps {
// Generate a random message.
msg := genTimestampRange(t)
@@ -372,7 +372,7 @@ func TestGossipSyncerQueueOrder(t *testing.T) {
// Set up a goroutine to respond to horizon queries.
go func() {
- for i := 0; i < 5; i++ {
+ for range 5 {
// Wait for horizon query from ApplyGossipFilter.
req := <-chanSeries.horizonReq
@@ -406,7 +406,7 @@ func TestGossipSyncerQueueOrder(t *testing.T) {
processWg.Add(numMessages)
var queuedMessages []*lnwire.GossipTimestampRange
- for i := 0; i < numMessages; i++ {
+ for i := range numMessages {
msg := &lnwire.GossipTimestampRange{
ChainHash: chainhash.Hash{},
FirstTimestamp: uint32(1000 + i*100),
@@ -428,7 +428,7 @@ func TestGossipSyncerQueueOrder(t *testing.T) {
defer orderMu.Unlock()
require.Len(t, processedRanges, numMessages)
- for i := 0; i < len(processedRanges); i++ {
+ for i := range processedRanges {
// Check that timestamps match what we queued.
require.Equal(
t, queuedMessages[i].FirstTimestamp,
### discovery/syncer_test.go
@@ -2686,7 +2686,7 @@ func TestGossipSyncerMaxChannelRangeSCIDs(t *testing.T) {
}
numFullReplies := maxChanRangeReplySCIDs / len(scids)
- for i := 0; i < numFullReplies; i++ {
+ for range numFullReplies {
require.NoError(t, syncer.processChanRangeReply(ctx, reply))
}
### discovery/validation_barrier.go
@@ -87,7 +87,7 @@ func NewValidationBarrier(numActiveReqs int,
// We'll first initialize a set of semaphores to limit our concurrency
// when validating incoming requests in parallel.
v.validationSemaphore = make(chan struct{}, numActiveReqs)
- for i := 0; i < numActiveReqs; i++ {
+ for range numActiveReqs {
v.validationSemaphore <- struct{}{}
}
### discovery/validation_barrier_test.go
@@ -29,7 +29,7 @@ func TestValidationBarrierSemaphore(t *testing.T) {
currentScid := lnwire.ShortChannelID{}
// Saturate the semaphore with jobs.
- for i := 0; i < numTasks; i++ {
+ for range numTasks {
scidMtx.Lock()
dummyUpdate := &lnwire.ChannelUpdate1{
ShortChannelID: currentScid,
@@ -43,7 +43,7 @@ func TestValidationBarrierSemaphore(t *testing.T) {
// Spawn additional tasks that will signal completion when added.
jobAdded := make(chan struct{})
- for i := 0; i < numPendingTasks; i++ {
+ for range numPendingTasks {
go func() {
scidMtx.Lock()
dummyUpdate := &lnwire.ChannelUpdate1{
@@ -68,7 +68,7 @@ func TestValidationBarrierSemaphore(t *testing.T) {
}
// Complete jobs one at a time and verify that they get added.
- for i := 0; i < numPendingTasks; i++ {
+ for range numPendingTasks {
barrier.CompleteJob()
select {
@@ -97,7 +97,7 @@ func TestValidationBarrierQuit(t *testing.T) {
// validation.
anns := make([]*lnwire.ChannelAnnouncement1, 0, numTasks)
parentJobIDs := make([]JobID, 0, numTasks)
- for i := 0; i < numTasks; i++ {
+ for i := range numTasks {
anns = append(anns, &lnwire.ChannelAnnouncement1{
ShortChannelID: lnwire.NewShortChanIDFromInt(uint64(i)),
NodeID1: nodeIDFromInt(uint64(2 * i)),
@@ -113,7 +113,7 @@ func TestValidationBarrierQuit(t *testing.T) {
// associated channel announcement has been verified.
chanUpds := make([]*lnwire.ChannelUpdate1, 0, numTasks)
childJobIDs := make([]JobID, 0, numTasks)
- for i := 0; i < numTasks; i++ {
+ for i := range numTasks {
chanUpds = append(chanUpds, &lnwire.ChannelUpdate1{
ShortChannelID: lnwire.NewShortChanIDFromInt(uint64(i)),
})
@@ -128,7 +128,7 @@ func TestValidationBarrierQuit(t *testing.T) {
// iteratively queue the channel updates, which will send back the error
// returned from waiting.
jobErrs := make(chan error)
- for i := 0; i < numTasks; i++ {
+ for i := range numTasks {
go func(ii int) {
jobErrs <- barrier.WaitForParents(
childJobIDs[ii], chanUpds[ii],
@@ -147,7 +147,7 @@ func TestValidationBarrierQuit(t *testing.T) {
// Complete the first half of jobs, one at a time, verifying that they
// get signaled. Then, quit the barrier and check that all others exit
// with the correct error.
- for i := 0; i < numTasks; i++ {
+ for i := range numTasks {
switch {
case i < numTasks/2:
err := barrier.SignalDependents(
### funding/manager_test.go
@@ -5783,7 +5783,7 @@ func TestChannelReadyUnknownChannelID(t *testing.T) {
// Send a batch of channel_ready messages with random (unknown)
// ChannelIDs to Alice from Bob.
const numUnknownMessages = 100
- for i := 0; i < numUnknownMessages; i++ {
+ for range numUnknownMessages {
var randomChanID lnwire.ChannelID
_, err := rand.Read(randomChanID[:])
require.NoError(t, err)
### graph/db/benchmark_test.go
@@ -578,7 +578,7 @@ func BenchmarkCacheLoading(b *testing.B) {
// Reset timer to exclude setup time.
b.ResetTimer()
- for i := 0; i < b.N; i++ {
+ for range b.N {
b.StopTimer()
graph, err := NewChannelGraph(store)
require.NoError(b, err)
@@ -740,7 +740,7 @@ func BenchmarkGraphReadMethods(b *testing.B) {
// Reset timer to exclude setup time.
b.ResetTimer()
- for i := 0; i < b.N; i++ {
+ for range b.N {
test.fn(b, store)
}
})
@@ -892,7 +892,7 @@ CREATE INDEX IF NOT EXISTS graph_channels_node_id_2_idx
b.ResetTimer()
//nolint:ll
- for i := 0; i < b.N; i++ {
+ for range b.N {
iter := backend.store.NodeUpdatesInHorizon(
ctx,
lnwire.GossipVersion1,
@@ -987,7 +987,7 @@ func BenchmarkFindOptimalSQLQueryConfig(b *testing.B) {
// Reset timer to exclude setup time.
b.ResetTimer()
- for i := 0; i < b.N; i++ {
+ for range b.N {
var (
numNodes = 0
numChannels = 0
### graph/db/graph_test.go
@@ -2781,7 +2781,7 @@ func testNodeUpdatesWithBatchSize(t *testing.T, ctx context.Context,
startTime := time.Unix(1234567890, 0)
var nodeAnns []models.Node
- for i := 0; i < 25; i++ {
+ for i := range 25 {
nodeAnn := createTestVertex(t, lnwire.GossipVersion1)
nodeAnn.LastUpdate = startTime.Add(
time.Duration(i) * time.Hour,
@@ -2953,7 +2953,7 @@ func TestNodeUpdatesInHorizonEarlyTermination(t *testing.T) {
// We'll start by creating 100 nodes, each with an update time spaced
// one hour apart.
startTime := time.Unix(1234567890, 0)
- for i := 0; i < 100; i++ {
+ for i := range 100 {
nodeAnn := createTestVertex(t, lnwire.GossipVersion1)
nodeAnn.LastUpdate = startTime.Add(time.Duration(i) * time.Hour)
require.NoError(t, graph.AddNode(ctx, nodeAnn))
@@ -3020,7 +3020,7 @@ func TestChanUpdatesInHorizonBoundaryConditions(t *testing.T) {
startTime := time.Unix(1234567890, 0)
const numChans = 25
- for i := 0; i < numChans; i++ {
+ for i := range numChans {
updateTime := startTime.Add(
time.Duration(i) * time.Hour,
)
@@ -3193,7 +3193,7 @@ func TestNodeUpdatesInHorizonV2(t *testing.T) {
const heightStep uint32 = 10
nodeAnns := make([]models.Node, 0, numNodes)
- for i := 0; i < numNodes; i++ {
+ for i := range numNodes {
node := createTestVertex(t, lnwire.GossipVersion2)
node.LastBlockHeight = startHeight + uint32(i)*heightStep
nodeAnns = append(nodeAnns, *node)
@@ -3432,7 +3432,7 @@ func TestChanUpdatesInHorizonV2(t *testing.T) {
const startHeight uint32 = 100
const heightStep uint32 = 10
- for i := 0; i < numChans; i++ {
+ for i := range numChans {
height := startHeight + uint32(i)*heightStep
channel, chanID := createEdge(
@@ -3755,7 +3755,7 @@ func testFilterKnownChanIDs(t *testing.T, v lnwire.GossipVersion) {
// block height 10 blocks after the previous.
const numChans = 5
chanIDs := make([]ChannelUpdateInfo, 0, numChans)
- for i := 0; i < numChans; i++ {
+ for i := range numChans {
channel, chanID := createEdge(
v, uint32(i*10), 0, 0, 0, node1, node2,
)
@@ -3766,7 +3766,7 @@ func testFilterKnownChanIDs(t *testing.T, v lnwire.GossipVersion) {
const numZombies = 5
zombieIDs := make([]ChannelUpdateInfo, 0, numZombies)
- for i := 0; i < numZombies; i++ {
+ for i := range numZombies {
channel, chanID := createEdge(
v, uint32(i*10+1), 0, 0, 0, node1, node2,
)
@@ -4493,7 +4493,7 @@ func testFetchChanInfos(t *testing.T, v lnwire.GossipVersion) {
require.NoError(t, err, "unable to fetch chan edges")
require.Len(t, resp, len(edges))
- for i := 0; i < len(resp); i++ {
+ for i := range resp {
compareEdgePolicies(t, resp[i].Policy1, edges[i].Policy1)
compareEdgePolicies(t, resp[i].Policy2, edges[i].Policy2)
assertEdgeInfoEqual(t, resp[i].Info, edges[i].Info)
@@ -4521,7 +4521,7 @@ func testChannelView(t *testing.T, v lnwire.GossipVersion) {
const numChans = 3
edgePoints := make([]EdgePoint, 0, numChans)
- for i := 0; i < numChans; i++ {
+ for i := range numChans {
edge, _ := createEdge(
v, uint32(i+1), 0, 0, uint32(i), node1, node2,
)
@@ -5755,7 +5755,7 @@ func testBatchedUpdateEdgePolicy(t *testing.T, v lnwire.GossipVersion) {
}
wg.Wait()
- for i := 0; i < len(updates); i++ {
+ for range updates {
err := <-errChan
require.Nil(t, err)
}
@@ -5775,7 +5775,7 @@ func BenchmarkForEachChannel(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
- for i := 0; i < b.N; i++ {
+ for range b.N {
var (
totalCapacity btcutil.Amount
maxHTLCs lnwire.MilliSatoshi
@@ -6042,7 +6042,7 @@ func TestAsyncGraphCache(t *testing.T) {
wg sync.WaitGroup
numRuns = 10
)
- for i := 0; i < numRuns; i++ {
+ for range numRuns {
wg.Add(1)
go func() {
defer wg.Done()
### graph/db/kv_store.go
@@ -4890,7 +4890,7 @@ func deserializeLightningNode(r io.Reader) (*models.Node, error) {
numAddresses := int(byteOrder.Uint16(scratch[:2]))
var addresses []net.Addr
- for i := 0; i < numAddresses; i++ {
+ for range numAddresses {
address, err := DeserializeAddr(r)
if err != nil {
return nil, err
### graph/db/kv_store_features_test.go
@@ -278,7 +278,7 @@ func TestDeserializeChanEdgeFeaturesPropertyBased(t *testing.T) {
// Generate random feature bits (max 256 to keep reasonable).
numFeatures := rapid.IntRange(0, 20).Draw(t, "numFeatures")
featureBits := make([]lnwire.FeatureBit, numFeatures)
- for i := 0; i < numFeatures; i++ {
+ for i := range numFeatures {
featureBits[i] = lnwire.FeatureBit(
rapid.IntRange(0, 255).Draw(t, "featureBit"),
)
@@ -305,7 +305,7 @@ func TestDeserializeChanEdgeFeaturesPropertyBased(t *testing.T) {
// Generate random feature bits.
numFeatures := rapid.IntRange(0, 20).Draw(t, "numFeatures")
featureBits := make([]lnwire.FeatureBit, numFeatures)
- for i := 0; i < numFeatures; i++ {
+ for i := range numFeatures {
featureBits[i] = lnwire.FeatureBit(
rapid.IntRange(0, 255).Draw(t, "featureBit"),
)
@@ -348,7 +348,7 @@ func TestDeserializeChanEdgeFeaturesLegacyFormatNoCollision(t *testing.T) {
numExtra := rapid.IntRange(0, 10).Draw(t, "numExtra")
featureBits := []lnwire.FeatureBit{lnwire.FeatureBit(maxBit)}
- for i := 0; i < numExtra; i++ {
+ for range numExtra {
bit := rapid.IntRange(0, maxBit).Draw(t, "extraBit")
featureBits = append(featureBits,
lnwire.FeatureBit(bit))
### graph/db/migration1/kv_store.go
@@ -1556,7 +1556,7 @@ func deserializeLightningNode(r io.Reader) (*models.Node, error) {
numAddresses := int(byteOrder.Uint16(scratch[:2]))
var addresses []net.Addr
- for i := 0; i < numAddresses; i++ {
+ for range numAddresses {
address, err := DeserializeAddr(r)
if err != nil {
return nil, err
### graph/db/migration1/sqlc/db_custom.go
@@ -21,7 +21,7 @@ func makeQueryParams(numTotalArgs, numListArgs int) string {
b.Grow(numListArgs * 6)
diff := numTotalArgs - numListArgs
- for i := 0; i < numListArgs; i++ {
+ for i := range numListArgs {
if i > 0 {
// We don't need to check the error here because the
// WriteString method of strings.Builder always returns
### htlcswitch/link_fee_update_test.go
@@ -155,7 +155,7 @@ func TestLinkLogDeduplication(t *testing.T) {
logger, logBuffer := newLinkCapturingLogger()
link.log = logger
- for i := 0; i < 2; i++ {
+ for range 2 {
link.handleUpstreamMsg(t.Context(), &lnwire.Warning{})
link.handleUpstreamMsg(
t.Context(), &lnwire.ChannelReestablish{},
@@ -195,7 +195,7 @@ func TestChannelMessageAdmissionError(t *testing.T) {
mailbox := newMemoryMailBox(&mailBoxConfig{})
link.mailBox = mailbox
- for i := 0; i < maxWireMessages; i++ {
+ for range maxWireMessages {
require.NoError(t, mailbox.AddMessage(&lnwire.UpdateFee{}))
}
### htlcswitch/mailbox_test.go
@@ -179,7 +179,7 @@ func TestMailBoxAdmissionBudgets(t *testing.T) {
mailbox := newMemoryMailBox(&mailBoxConfig{})
msg := &lnwire.UpdateFee{}
- for i := 0; i < maxWireMessages; i++ {
+ for range maxWireMessages {
require.NoError(t, mailbox.AddMessage(msg))
}
### htlcswitch/switch_test.go
@@ -2030,7 +2030,7 @@ func TestNodeIDNonStrictRouting(t *testing.T) {
// Forward many HTLCs so that random selection would almost certainly
// land on the incoming channel, which will be sorted out by the switch.
const numHTLCs = 20
- for i := 0; i < numHTLCs; i++ {
+ for i := range numHTLCs {
var hash [sha256.Size]byte
hash[0] = byte(i)
### invoices/kv_sql_migration_test.go
@@ -103,7 +103,7 @@ func TestMigrationWithChannelDB(t *testing.T) {
// Simply zero out the add index so we don't fail on that when
// comparing.
- for i := 0; i < numInvoices; i++ {
+ for i := range numInvoices {
result1.Invoices[i].AddIndex = 0
result2.Invoices[i].AddIndex = 0
### invoices/sql_migration_test.go
@@ -120,7 +120,7 @@ func randHTLCRapid(t *rapid.T, invoice *Invoice, amt lnwire.MilliSatoshi) (
// Add randomized custom records to the HTLC.
htlc.CustomRecords = make(record.CustomSet)
numRecords := rapid.IntRange(0, 5).Draw(t, "numRecords")
- for i := 0; i < numRecords; i++ {
+ for range numRecords {
key := rapid.Uint64Range(
record.CustomTypeStart, 1000+record.CustomTypeStart,
).Draw(t, "customRecordKey")
@@ -163,7 +163,7 @@ func generateInvoiceHTLCsRapid(t *rapid.T, invoice *Invoice) {
amt := total / lnwire.MilliSatoshi(numHTLCs)
remainder := total - amt*lnwire.MilliSatoshi(numHTLCs)
- for i := 0; i < numHTLCs; i++ {
+ for i := range numHTLCs {
if i == numHTLCs-1 {
// Add remainder to the last HTLC.
amt += remainder
@@ -184,7 +184,7 @@ func generateAMPHtlcsRapid(t *rapid.T, invoice *Invoice) {
numSetIDs := rapid.IntRange(1, 5).Draw(t, "numSetIDs")
settledIdx := uint64(1)
- for i := 0; i < numSetIDs; i++ {
+ for range numSetIDs {
var setID SetID
_, err := crand.Read(setID[:])
require.NoError(t, err)
@@ -200,7 +200,7 @@ func generateAMPHtlcsRapid(t *rapid.T, invoice *Invoice) {
remainder := total - amt*lnwire.MilliSatoshi(numHTLCs)
var htlcState HtlcState
- for j := 0; j < numHTLCs; j++ {
+ for j := range numHTLCs {
if j == numHTLCs-1 {
amt += remainder
}
### itest/lnd_channel_force_close_test.go
@@ -159,7 +159,7 @@ func runChannelForceClosureTest(ht *lntest.HarnessTest,
// htlc outputs should be left unsettled, and should be swept by the
// utxo nursery.
carolPubKey := carol.PubKey[:]
- for i := 0; i < numInvoices; i++ {
+ for range numInvoices {
req := &routerrpc.SendPaymentRequest{
Dest: carolPubKey,
Amt: int64(paymentAmt),
### itest/lnd_forward_delete_test.go
@@ -70,7 +70,7 @@ func testBasicDeletion(ht *lntest.HarnessTest) {
// Send multiple payments from Alice to Carol through Bob. Sleep after
// each payment to ensure minimum age validation.
- for i := 0; i < numPayments; i++ {
+ for i := range numPayments {
invoice := carol.RPC.AddInvoice(&lnrpc.Invoice{
ValueMsat: paymentAmt,
Memo: fmt.Sprintf("test payment %d", i),
@@ -181,7 +181,7 @@ func testPartialDeletion(ht *lntest.HarnessTest) {
const paymentAmt = 1000
// Send first batch of payments.
- for i := 0; i < firstBatch; i++ {
+ for i := range firstBatch {
invoice := carol.RPC.AddInvoice(&lnrpc.Invoice{
ValueMsat: paymentAmt,
Memo: fmt.Sprintf("batch 1 payment %d", i),
@@ -204,7 +204,7 @@ func testPartialDeletion(ht *lntest.HarnessTest) {
// Send a second batch of payments.
const secondBatch = 5
- for i := 0; i < secondBatch; i++ {
+ for i := range secondBatch {
invoice := carol.RPC.AddInvoice(&lnrpc.Invoice{
ValueMsat: paymentAmt,
Memo: fmt.Sprintf("batch 2 payment %d", i),
@@ -311,7 +311,7 @@ func testDeletionIdempotency(ht *lntest.HarnessTest) {
const numPayments = 5
const paymentAmt = 1000
- for i := 0; i < numPayments; i++ {
+ for i := range numPayments {
invoice := carol.RPC.AddInvoice(&lnrpc.Invoice{
ValueMsat: paymentAmt,
Memo: fmt.Sprintf("payment %d", i),
@@ -398,7 +398,7 @@ func testTimeFormats(ht *lntest.HarnessTest) {
// Helper function to create forwarding events.
createForwards := func(count int) {
- for i := 0; i < count; i++ {
+ for i := range count {
invoice := carol.RPC.AddInvoice(&lnrpc.Invoice{
ValueMsat: 1000,
Memo: fmt.Sprintf("payment %d", i),
### itest/lnd_graph_migration_test.go
@@ -93,7 +93,7 @@ func testGraphMigration(ht *lntest.HarnessTest) {
// Now run the migration flow three times to ensure that each run is
// idempotent.
- for i := 0; i < 3; i++ {
+ for range 3 {
// Start Alice with the native SQL flag set. This will trigger
// the migration to run.
require.NoError(ht, alice.Start(ht.Context()))
### itest/lnd_invoice_migration_test.go
@@ -173,7 +173,7 @@ func testInvoiceMigration(ht *lntest.HarnessTest) {
// Step 1: Add 10 normal invoices and pay 5 of them.
normalInvoices := make([]*lnrpc.AddInvoiceResponse, 10)
- for i := 0; i < 10; i++ {
+ for i := range 10 {
invoice := &lnrpc.Invoice{
Value: int64(1000 + i*100), // Varying amounts
IsAmp: false,
@@ -195,7 +195,7 @@ func testInvoiceMigration(ht *lntest.HarnessTest) {
// Step 2: Add 10 AMP invoices and send multiple payments to 5 of them.
ampInvoices := make([]*lnrpc.AddInvoiceResponse, 10)
- for i := 0; i < 10; i++ {
+ for i := range 10 {
invoice := &lnrpc.Invoice{
Value: int64(2000 + i*200), // Varying amounts
IsAmp: true,
@@ -206,11 +206,11 @@ func testInvoiceMigration(ht *lntest.HarnessTest) {
}
// Select the first 5 invoices to send multiple AMP payments.
- for i := 0; i < 5; i++ {
+ for i := range 5 {
inv := ampInvoices[i]
// Send 3 payments to each.
- for j := 0; j < 3; j++ {
+ for range 3 {
payReq := &routerrpc.SendPaymentRequest{
PaymentRequest: inv.PaymentRequest,
TimeoutSeconds: 60,
@@ -264,7 +264,7 @@ func testInvoiceMigration(ht *lntest.HarnessTest) {
// Now run the migration flow three times to ensure that each run is
// idempotent.
- for i := 0; i < 3; i++ {
+ for range 3 {
// Start bob with the native SQL flag set. This will trigger the
// migration to run.
require.NoError(ht, bob.Start(ht.Context()))
@@ -285,7 +285,7 @@ func testInvoiceMigration(ht *lntest.HarnessTest) {
// Simply zero out the add index so we don't fail on that when
// comparing.
- for i := 0; i < numInvoices; i++ {
+ for i := range numInvoices {
result1.Invoices[i].AddIndex = 0
result2.Invoices[i].AddIndex = 0
### itest/lnd_multi-hop_force_close_test.go
@@ -3342,7 +3342,7 @@ func runHtlcAggregation(ht *lntest.HarnessTest,
)
// Add Carol invoices.
- for i := 0; i < numInvoices; i++ {
+ for range numInvoices {
preimage := ht.RandomPreimage()
payHash := preimage.Hash()
@@ -3364,7 +3364,7 @@ func runHtlcAggregation(ht *lntest.HarnessTest,
// We'll give Alice's invoices a longer CLTV expiry, to ensure the
// channel Bob<->Carol will be closed first.
- for i := 0; i < numInvoices; i++ {
+ for range numInvoices {
preimage := ht.RandomPreimage()
payHash := preimage.Hash()
### itest/lnd_onchain_test.go
@@ -568,7 +568,7 @@ func testAnchorThirdPartySpend(ht *lntest.HarnessTest) {
blocks := anchorCsv - defaultCSV
// Mine empty blocks and check Alice still has the two pending sweeps.
- for i := 0; i < blocks; i++ {
+ for range blocks {
ht.MineEmptyBlocks(1)
ht.AssertNumPendingSweeps(alice, 2)
}
### itest/lnd_sweep_test.go
@@ -1855,7 +1855,7 @@ func testFeeReplacement(ht *lntest.HarnessTest) {
// Create numPayments HTLCs on Bob's incoming and outgoing channels.
preimages := make([][]byte, 0, numPayments)
streams := make([]rpc.SingleInvoiceClient, 0, numPayments)
- for i := 0; i < numPayments; i++ {
+ for range numPayments {
// Create the preimage.
var preimage lntypes.Preimage
copy(preimage[:], ht.Random32Bytes())
### itest/lnd_test.go
@@ -198,7 +198,7 @@ func createIndices(numCases, numTranches uint) [][2]uint {
indices := make([][2]uint, numTranches)
start := uint(0)
- for i := uint(0); i < numTranches; i++ {
+ for i := range numTranches {
end := start + base
if i < remainder {
// Add one for the remainder.
### lntest/harness.go
@@ -536,7 +536,7 @@ func (h *HarnessTest) NewNodeWithCoins(name string,
totalAmount = fundAmount * numOutputs
)
- for i := 0; i < numOutputs; i++ {
+ for range numOutputs {
h.createAndSendOutput(
node, fundAmount,
lnrpc.AddressType_WITNESS_PUBKEY_HASH,
@@ -1579,7 +1579,7 @@ func (h *HarnessTest) FundNumCoins(hn *node.HarnessNode, num int) {
const fundAmount = 1 * btcutil.SatoshiPerBitcoin
// Send out the outputs from the miner.
- for i := 0; i < num; i++ {
+ for range num {
h.createAndSendOutput(
hn, fundAmount, lnrpc.AddressType_WITNESS_PUBKEY_HASH,
)
### lntest/miner/bitcoind_miner.go
@@ -213,7 +213,7 @@ func (b *BitcoindMinerBackend) Start(setupChain bool,
maxRetries := 120
retryDelay := 1 * time.Second
- for i := 0; i < maxRetries; i++ {
+ for i := range maxRetries {
_, err = b.rpcClient.GetBlockCount()
if err == nil {
// Successfully connected!
### lnwire/local_nonces.go
@@ -149,7 +149,7 @@ func decodeLocalNoncesData(r io.Reader, val any, _ *[8]byte,
// existing entries if the LocalNoncesData instance is being reused.
l.NoncesMap = make(map[chainhash.Hash]Musig2Nonce, numEntries)
- for i := uint64(0); i < numEntries; i++ {
+ for range numEntries {
var (
txid chainhash.Hash
nonce Musig2Nonce
### lnwire/test_message.go
@@ -391,7 +391,7 @@ func (a *ChannelReestablish) RandTestMessage(t *rapid.T) Message {
if includeLocalNonces {
numNonces := rapid.IntRange(0, 3).Draw(t, "numLocalNonces")
nonces := make(map[chainhash.Hash]Musig2Nonce)
- for i := 0; i < numNonces; i++ {
+ for range numNonces {
txid := RandChainHash(t)
// Ensure unique txids for the map.
@@ -883,7 +883,7 @@ func (c *CommitSig) RandTestMessage(t *rapid.T) Message {
numHtlcSigs := rapid.IntRange(0, 20).Draw(t, "numHtlcSigs")
htlcSigs := make([]Sig, numHtlcSigs)
- for i := 0; i < numHtlcSigs; i++ {
+ for i := range numHtlcSigs {
htlcSigs[i] = RandSignature(t)
}
@@ -1078,7 +1078,7 @@ func (dr *DynReject) RandTestMessage(t *rapid.T) Message {
featureVec := NewRawFeatureVector()
numFeatures := rapid.IntRange(0, 8).Draw(t, "numRejections")
- for i := 0; i < numFeatures; i++ {
+ for i := range numFeatures {
bit := FeatureBit(
rapid.IntRange(0, 31).Draw(
t, fmt.Sprintf("rejectionBit-%d", i),
@@ -1315,7 +1315,7 @@ func (msg *Init) RandTestMessage(t *rapid.T) Message {
local := NewRawFeatureVector()
numGlobalFeatures := rapid.IntRange(0, 20).Draw(t, "numGlobalFeatures")
- for i := 0; i < numGlobalFeatures; i++ {
+ for i := range numGlobalFeatures {
bit := FeatureBit(
rapid.IntRange(0, 100).Draw(
t, fmt.Sprintf("globalFeatureBit%d", i),
@@ -1325,7 +1325,7 @@ func (msg *Init) RandTestMessage(t *rapid.T) Message {
}
numLocalFeatures := rapid.IntRange(0, 20).Draw(t, "numLocalFeatures")
- for i := 0; i < numLocalFeatures; i++ {
+ for i := range numLocalFeatures {
bit := FeatureBit(
rapid.IntRange(0, 100).Draw(
t, fmt.Sprintf("localFeatureBit%d", i),
@@ -1462,7 +1462,7 @@ func (n *NodeAnnouncement2) RandTestMessage(t *rapid.T) Message {
ipv6Addrs := make(IPV6Addrs, 1)
ip := make(net.IP, 16)
// Generate random IPv6 address.
- for j := 0; j < 16; j++ {
+ for j := range 16 {
ip[j] = uint8(rapid.IntRange(0, 255).Draw(
t, fmt.Sprintf("ip6_%d", j)),
)
@@ -1636,7 +1636,7 @@ func (p *Ping) RandTestMessage(t *rapid.T) Message {
padding := make(PingPayload, paddingLen)
// Fill padding with random bytes
- for i := 0; i < paddingLen; i++ {
+ for i := range paddingLen {
padding[i] = byte(rapid.IntRange(0, 255).Draw(
t, fmt.Sprintf("paddingByte%d", i)),
)
@@ -1731,7 +1731,7 @@ func (q *QueryShortChanIDs) RandTestMessage(t *rapid.T) Message {
// Generate sorted short channel IDs.
shortChanIDs := make([]ShortChannelID, numIDs)
- for i := 0; i < numIDs; i++ {
+ for i := range numIDs {
shortChanIDs[i] = RandShortChannelID(t)
// Ensure they're properly sorted.
@@ -1782,7 +1782,7 @@ func (c *ReplyChannelRange) RandTestMessage(t *rapid.T) Message {
scidSet := fn.NewSet[ShortChannelID]()
scids := make([]ShortChannelID, numShortChanIDs)
- for i := 0; i < numShortChanIDs; i++ {
+ for i := range numShortChanIDs {
scid := RandShortChannelID(t)
for scidSet.Contains(scid) {
scid = RandShortChannelID(t)
@@ -1798,7 +1798,7 @@ func (c *ReplyChannelRange) RandTestMessage(t *rapid.T) Message {
if rapid.Bool().Draw(t, "includeTimestamps") && numShortChanIDs > 0 {
msg.Timestamps = make(Timestamps, numShortChanIDs)
- for i := 0; i < numShortChanIDs; i++ {
+ for i := range numShortChanIDs {
msg.Timestamps[i] = ChanUpdateTimestamps{
Timestamp1: uint32(rapid.IntRange(0, math.MaxInt32).Draw(t, fmt.Sprintf("timestamp-1-%d", i))), //nolint:ll
Timestamp2: uint32(rapid.IntRange(0, math.MaxInt32).Draw(t, fmt.Sprintf("timestamp-2-%d", i))), //nolint:ll
@@ -1858,7 +1858,7 @@ func (c *RevokeAndAck) RandTestMessage(t *rapid.T) Message {
if rapid.Bool().Draw(t, "includeLocalNonces") {
numNonces := rapid.IntRange(0, 3).Draw(t, "numLocalNonces")
nonces := make(map[chainhash.Hash]Musig2Nonce)
- for i := 0; i < numNonces; i++ {
+ for range numNonces {
txid := RandChainHash(t)
// Ensure unique txids for the map.
@@ -2092,7 +2092,7 @@ func (c *Warning) RandTestMessage(t *rapid.T) Message {
if useASCII {
length := rapid.IntRange(1, 100).Draw(t, "warningDataLength")
data := make([]byte, length)
- for i := 0; i < length; i++ {
+ for i := range length {
data[i] = byte(
rapid.IntRange(32, 126).Draw(
t, fmt.Sprintf("warningDataByte-%d", i),
@@ -2127,7 +2127,7 @@ func (c *Error) RandTestMessage(t *rapid.T) Message {
if useASCII {
length := rapid.IntRange(1, 100).Draw(t, "errorDataLength")
data := make([]byte, length)
- for i := 0; i < length; i++ {
+ for i := range length {
data[i] = byte(
rapid.IntRange(32, 126).Draw(
t, fmt.Sprintf("errorDataByte-%d", i),
@@ -2157,7 +2157,7 @@ func genValidHostname(t *rapid.T) string {
length := rapid.IntRange(1, 255).Draw(t, "hostname_length")
hostname := make([]byte, length)
- for i := 0; i < length; i++ {
+ for i := range length {
charIndex := rapid.IntRange(0, len(validChars)-1).Draw(
t, fmt.Sprintf("char_%d", i),
)
### lnwire/test_utils.go
@@ -125,7 +125,7 @@ func RandFeatureVector(t *rapid.T) *RawFeatureVector {
// Add a random number of random feature bits
numFeatures := rapid.IntRange(0, 20).Draw(t, "numFeatures")
- for i := 0; i < numFeatures; i++ {
+ for i := range numFeatures {
bit := FeatureBit(rapid.IntRange(0, 100).Draw(
t, fmt.Sprintf("featureBit-%d", i)),
)
@@ -218,7 +218,7 @@ func RandNetAddrs(t *rapid.T) []net.Addr {
}
addresses := make([]net.Addr, numAddresses)
- for i := 0; i < numAddresses; i++ {
+ for i := range numAddresses {
addressType := rapid.IntRange(0, 1).Draw(
t, fmt.Sprintf("addressType-%d", i),
)
@@ -289,7 +289,7 @@ func RandTLVRecords(t *rapid.T, ignoreRecords fn.Set[uint64],
rangeStop := rangeStart + 30_000
ignoreSet := fn.NewSet[uint64]()
- for i := 0; i < numRecords; i++ {
+ for i := range numRecords {
recordType := uint64(
rapid.IntRange(rangeStart, rangeStop).
Filter(func(i int) bool {
### multimutex/multimutex_test.go
@@ -39,7 +39,7 @@ func TestMultiMutexConcurrency(t *testing.T) {
var wg sync.WaitGroup
const numOps = 100
- for i := 0; i < numOps; i++ {
+ for range numOps {
wg.Add(1)
go func() {
defer wg.Done()
@@ -70,7 +70,7 @@ func TestMultiMutexMultipleIDs(t *testing.T) {
var wg sync.WaitGroup
const numOps = 50
- for i := 0; i < numOps; i++ {
+ for range numOps {
wg.Add(2)
go func(id string) {
@@ -110,7 +110,7 @@ func TestMultiMutexReuse(t *testing.T) {
t.Parallel()
mtx := newTestMutex[int]()
- for i := 0; i < 5; i++ {
+ for range 5 {
mtx.Lock(1)
mtx.Unlock(1)
}
### onionmessage/ratelimit_test.go
@@ -32,7 +32,7 @@ func TestGlobalLimiterDisabled(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
lim := NewGlobalLimiter(tc.kbps, tc.burstBytes)
- for i := 0; i < 1000; i++ {
+ for range 1000 {
require.True(t, lim.AllowN(msgBytes))
}
// Disabled limiters must be noopLimiters, not
@@ -56,7 +56,7 @@ func TestGlobalLimiterBurstExhaustion(t *testing.T) {
const burstMessages = 5
lim := NewGlobalLimiter(1, burstMessages*msgBytes)
- for i := 0; i < burstMessages; i++ {
+ for i := range burstMessages {
require.True(t, lim.AllowN(msgBytes),
"burst slot %d should pass", i)
}
@@ -89,7 +89,7 @@ func TestPeerRateLimiterDisabled(t *testing.T) {
var peer [33]byte
peer[0] = 0x02
- for i := 0; i < 1000; i++ {
+ for range 1000 {
require.True(t, p.AllowN(peer, msgBytes))
}
require.Equal(t, uint64(0), p.Dropped())
@@ -112,14 +112,14 @@ func TestPeerRateLimiterIsolation(t *testing.T) {
peerB[0] = 0x03
// Drain peer A's bucket.
- for i := 0; i < burstMessages; i++ {
+ for range burstMessages {
require.True(t, p.AllowN(peerA, msgBytes))
}
require.False(t, p.AllowN(peerA, msgBytes),
"peer A should be exhausted")
// Peer B should still have its full burst.
- for i := 0; i < burstMessages; i++ {
+ for i := range burstMessages {
require.True(t, p.AllowN(peerB, msgBytes),
"peer B slot %d", i)
}
@@ -146,7 +146,7 @@ func TestCountingLimiterFirstDropClaimOnce(t *testing.T) {
const workers = 32
var wins atomic.Uint64
var wg sync.WaitGroup
- for i := 0; i < workers; i++ {
+ for range workers {
wg.Add(1)
go func() {
defer wg.Done()
@@ -173,7 +173,7 @@ func TestPeerRateLimiterFirstDropClaimOnce(t *testing.T) {
const workers = 32
var wins atomic.Uint64
var wg sync.WaitGroup
- for i := 0; i < workers; i++ {
+ for range workers {
wg.Add(1)
go func() {
defer wg.Done()
@@ -214,13 +214,13 @@ func TestPeerRateLimiterConcurrentAllowN(t *testing.T) {
var wg sync.WaitGroup
var ops atomic.Uint64
- for w := 0; w < workers; w++ {
+ for w := range workers {
wg.Add(1)
go func() {
defer wg.Done()
var key [33]byte
key[0] = byte(w)
- for i := 0; i < iters; i++ {
+ for range iters {
p.AllowN(key, msgBytes)
ops.Add(1)
}
### payments/db/kv_store_test.go
@@ -589,7 +589,7 @@ func TestKVStoreQueryPaymentsDuplicates(t *testing.T) {
// bucket.
nonDuplicatePayments := 6
- for i := 0; i < nonDuplicatePayments; i++ {
+ for i := range nonDuplicatePayments {
// Generate a test payment.
info, preimg := genInfo(t)
### payments/db/migration1/kv_store.go
@@ -1855,7 +1855,7 @@ func deserializeHop(r io.Reader) (*Hop, error) {
}
tlvMap := make(map[uint64][]byte)
- for i := uint32(0); i < numElements; i++ {
+ for range numElements {
var tlvType uint64
if err := ReadElements(r, &tlvType); err != nil {
return nil, err
@@ -2007,7 +2007,7 @@ func DeserializeRoute(r io.Reader) (Route, error) {
}
var hops []*Hop
- for i := uint32(0); i < numHops; i++ {
+ for range numHops {
hop, err := deserializeHop(r)
if err != nil {
return rt, err
### payments/db/migration1/sqlc/db_custom.go
@@ -27,7 +27,7 @@ func makeQueryParams(numTotalArgs, numListArgs int) string {
b.Grow(numListArgs * 6)
diff := numTotalArgs - numListArgs
- for i := 0; i < numListArgs; i++ {
+ for i := range numListArgs {
if i > 0 {
// We don't need to check the error here because the
// WriteString method of strings.Builder always returns
### payments/db/payment_test.go
@@ -133,7 +133,7 @@ func createTestPayments(t *testing.T, p DB, payments []*payment) {
attemptID := uint64(0)
- for i := 0; i < len(payments); i++ {
+ for i := range payments {
preimg := genPreimage(t)
rhash := sha256.Sum256(preimg[:])
@@ -2118,7 +2118,7 @@ func TestMultiShard(t *testing.T) {
shardAmt := info.Value / 3
var attempts []*HTLCAttemptInfo
- for i := uint64(0); i < 3; i++ {
+ for i := range uint64(3) {
a := genAttemptWithHash(
t, i, genSessionKey(t), rhash,
)
### peer/brontide_test.go
@@ -1350,7 +1350,7 @@ func TestPeerPingLimitsAllowHonestCadence(t *testing.T) {
// Act: Advance a synthetic clock at the selected
// cadence, avoiding scheduler and wall-clock noise.
- for i := 0; i < 5000; i++ {
+ for i := range 5000 {
elapsed := time.Duration(i) * test.cadence
now := start.Add(elapsed)
@@ -1383,7 +1383,7 @@ func TestPeerValidPingsReceivePongs(t *testing.T) {
// Act: Deliver exactly the admitted burst of valid Pings through the
// normal read path. Drain one wire response after each request to avoid
// mock backpressure while observing the protocol behavior.
- for i := 0; i < pingFloodBurst; i++ {
+ for i := range pingFloodBurst {
var b bytes.Buffer
ping := lnwire.NewPing(1)
ping.PaddingBytes = []byte{byte(i)}
@@ -1554,7 +1554,7 @@ func TestPeerPingFloodDisconnects(t *testing.T) {
// Act: Send two oversized Pings. The first spends the sole token and
// reaches the router; the second finds no budget and disconnects before
// routing.
- for i := 0; i < 2; i++ {
+ for range 2 {
select {
case params.mockConn.readMessages <- b.Bytes():
case <-peer.cg.Done():
@@ -1617,7 +1617,7 @@ func TestPeerMaxPongBurstDisconnects(t *testing.T) {
// Act: Deliver and drain 20 maximum-size requests so the queue cannot
// back up, then send the 21st and wait for its insufficient weighted
// budget to disconnect.
- for i := 0; i < admittedMaxPongs; i++ {
+ for range admittedMaxPongs {
select {
case params.mockConn.readMessages <- b.Bytes():
case <-peer.cg.Done():
@@ -1846,7 +1846,7 @@ func TestPeerSendMessageQueueBounds(t *testing.T) {
// Act: Queue the exact boundary through SendMessage.
// Its async path waits for queueHandler to
// receive its message without requiring a writer.
- for i := 0; i < test.numAtLimit; i++ {
+ for range test.numAtLimit {
err := peer.SendMessage(false, newMsg())
require.NoError(t, err)
}
@@ -1966,15 +1966,15 @@ func TestPeerConcurrentSenders(t *testing.T) {
// Act: Launch all synchronous senders concurrently and collect each
// public result through a buffered channel that cannot serialize them.
results := make(chan error, numSenders)
- for i := 0; i < numSenders; i++ {
+ for range numSenders {
go func() {
results <- peer.SendMessage(true, lnwire.NewPing(0))
}()
}
// Assert: Every sender receives its successful writer acknowledgment,
// all expected wire operations occur, and both handlers join cleanly.
- for i := 0; i < numSenders; i++ {
+ for range numSenders {
err, recvErr := fn.RecvOrTimeout(results, timeout)
require.NoError(t, recvErr)
require.NoError(t, err)
### peer/onion_ratelimit_test.go
@@ -241,7 +241,7 @@ func TestAllowOnionMessageHappyPath(t *testing.T) {
var key [33]byte
key[0] = 0x04
- for i := 0; i < 10; i++ {
+ for i := range 10 {
result := allowOnionMessage(
limiter, key, testMsgBytes, true, false,
)
@@ -270,7 +270,7 @@ func TestAllowOnionMessagePeerIsolation(t *testing.T) {
keyB[0] = 0x03
// Drain peer A.
- for i := 0; i < 2; i++ {
+ for range 2 {
result := allowOnionMessage(
limiter, keyA, testMsgBytes, true, false,
)
@@ -280,7 +280,7 @@ func TestAllowOnionMessagePeerIsolation(t *testing.T) {
require.Error(t, result.Err())
// Peer B must still have its full burst available.
- for i := 0; i < 2; i++ {
+ for i := range 2 {
result := allowOnionMessage(
limiter, keyB, testMsgBytes, true, false,
)
@@ -315,11 +315,11 @@ func TestAllowOnionMessageConcurrent(t *testing.T) {
var wg sync.WaitGroup
var accepted atomic.Uint64
- for w := 0; w < workers; w++ {
+ for range workers {
wg.Add(1)
go func() {
defer wg.Done()
- for i := 0; i < perWorker; i++ {
+ for range perWorker {
result := allowOnionMessage(
limiter, key, testMsgBytes, true, false,
)Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.