From c025901ad0279b61452ae3bf11e8184a27754baa Mon Sep 17 00:00:00 2001 From: lukechampine Date: Tue, 12 Dec 2023 17:22:10 -0500 Subject: [PATCH] main: More mining speedups --- cmd/walletd/testnet.go | 55 +++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/cmd/walletd/testnet.go b/cmd/walletd/testnet.go index 7cbb1ba..ab8c6c9 100644 --- a/cmd/walletd/testnet.go +++ b/cmd/walletd/testnet.go @@ -125,6 +125,31 @@ func initTestnetClient(addr string, network string, seed wallet.Seed) *api.Clien return c } +func mineBlock(cs consensus.State, b *types.Block) (hashes int, found bool) { + buf := make([]byte, 32+8+8+32) + binary.LittleEndian.PutUint64(buf[32:], b.Nonce) + binary.LittleEndian.PutUint64(buf[40:], uint64(b.Timestamp.Unix())) + if b.V2 != nil { + copy(buf[:32], "sia/id/block|") + copy(buf[48:], b.V2.Commitment[:]) + } else { + root := b.MerkleRoot() + copy(buf[:32], b.ParentID[:]) + copy(buf[48:], root[:]) + } + factor := cs.NonceFactor() + startBlock := time.Now() + for types.BlockID(types.HashBytes(buf)).CmpWork(cs.ChildTarget) < 0 { + b.Nonce += factor + hashes++ + binary.LittleEndian.PutUint64(buf[32:], b.Nonce) + if time.Since(startBlock) > 10*time.Second { + return hashes, false + } + } + return hashes, true +} + func runTestnetMiner(c *api.Client, seed wallet.Seed) { minerAddr := types.StandardUnlockHash(seed.PublicKey(0)) log.Println("Started mining into", minerAddr) @@ -148,7 +173,7 @@ outer: check("Couldn't get txpool transactions:", err) b := types.Block{ ParentID: cs.Index.ID, - Nonce: cs.NonceFactor() * frand.Uint64n(100000), + Nonce: cs.NonceFactor() * frand.Uint64n(100), Timestamp: types.CurrentTimestamp(), MinerPayouts: []types.SiacoinOutput{{Address: minerAddr, Value: cs.BlockReward()}}, Transactions: txns, @@ -166,30 +191,10 @@ outer: } b.V2.Commitment = cs.Commitment(cs.TransactionsCommitment(b.Transactions, b.V2Transactions()), b.MinerPayouts[0].Address) } - - buf := make([]byte, 32+8+8+32) - binary.LittleEndian.PutUint64(buf[32:], b.Nonce) - binary.LittleEndian.PutUint64(buf[40:], uint64(b.Timestamp.Unix())) - if b.V2 != nil { - copy(buf[:32], "sia/id/block|") - copy(buf[48:], b.V2.Commitment[:]) - } else { - root := b.MerkleRoot() // NOTE: expensive! - copy(buf[:32], b.ParentID[:]) - copy(buf[48:], root[:]) - } - startBlock := time.Now() - for types.BlockID(types.HashBytes(buf)).CmpWork(cs.ChildTarget) < 0 { - b.Nonce += cs.NonceFactor() - // ensure nonce meets factor requirement - for b.Nonce%cs.NonceFactor() != 0 { - b.Nonce++ - } - hashes++ - binary.LittleEndian.PutUint64(buf[32:], b.Nonce) - if time.Since(startBlock) > 30*time.Second { - continue outer - } + h, ok := mineBlock(cs, &b) + hashes += float64(h) + if !ok { + continue outer } blocks++ index := types.ChainIndex{Height: cs.Index.Height + 1, ID: b.ID()}