Skip to content

Commit

Permalink
feat: optimize nonce generation (#232)
Browse files Browse the repository at this point in the history
  • Loading branch information
agaffney authored Jul 22, 2024
1 parent 73d8ca3 commit 9a26fd8
Showing 1 changed file with 13 additions and 15 deletions.
28 changes: 13 additions & 15 deletions internal/miner/miner.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ type Miner struct {
blockData any
state TargetState
hashCounter *atomic.Uint64
nonceCount uint8
}

type TargetState interface {
Expand Down Expand Up @@ -322,17 +323,6 @@ func randomNonce() [16]byte {
return ret
}

//nolint:unused
func incrementNonce(nonce []byte) {
for i := len(nonce) - 1; i >= 0; i-- {
if nonce[i] < 255 {
nonce[i]++
break
}
nonce[i] = 0
}
}

func (m *Miner) calculateHash() []byte {
var tmpLeadingZeros int64
var tmpDifficultyNumber int64
Expand Down Expand Up @@ -382,10 +372,18 @@ func (m *Miner) calculateHash() []byte {
return hash2
}

// Currently we create a new random nonce
// Uncomment if we decide to increment the nonce
// incrementNonce(m.state.Nonce[:])
m.state.SetNonce(randomNonce())
// Generate a new random nonce when nonceCount rolls over, and increment bytes in existing nonce otherwise
if m.nonceCount == 0 {
m.state.SetNonce(randomNonce())
} else {
nonce := m.state.GetNonce()
// Increment each byte of the nonce
for j := 0; j < 16; j++ {
nonce[j]++
}
m.state.SetNonce(nonce)
}
m.nonceCount++
}
}

Expand Down

0 comments on commit 9a26fd8

Please sign in to comment.