banner

I have been trying to build my own blockchain from scratch in Golang

I have coded the execution layer and recently got done with implementing the Consensus layer for my chain.

There’s one persistent issue though; I have this following function that is used to mine a particular block

func (bc *Blockchain) MineBlock(b *Block) error {
    bc.logger.Log(
        "msg", "mining block..",
    )
    var targetForBlock *big.Int
    var err error
    if (bc.Height() % HEIGHT_DIVISOR) == 0 {
        targetForBlock, err = bc.calcTargetValue(b)
        bc.Target = targetForBlock
        if err != nil {
            return err
        }
    } else {
        targetForBlock = bc.Target
        fmt.Printf("target is %x\n", targetForBlock)
    }
    fmt.Printf("target for block %x\n", targetForBlock)
    bHash := b.HashWithoutCache(BlockHasher{})
    hashBigInt, _ := new(big.Int).SetString(bHash.String(), 16)
    for isLowerThanTarget(hashBigInt, targetForBlock) != -1 {
        nonce := b.Header.Nonce
        b.Header.Nonce++
        bHash = b.HashWithoutCache(BlockHasher{})
        hashBigInt.SetString(bHash.String(), 16)
        fmt.Printf("trying new combo with nonce %v block hash %s and target %x \n", nonce, bHash.String(), targetForBlock)
    }

    // updating timestamp
    b.Header.Timestamp = uint64(time.Now().UnixNano())
    b.Header.Target = targetForBlock
    b.Header.NBits = targetToCompact(targetForBlock)

    fmt.Printf("block mined with hash %s and target %x \n", bHash.String(), targetForBlock)

    return nil
}
  • First the target for the block is calculated; the target is adjusted every 5 blocks
  • Once that is done I start the mining; by hashing the Block and comparing it against the target; in the event that it doesn’t I increment the NONCE until the condition is resolved.

What tends to happen is that; after 30k or so iterations; my program simply crashes. I want to know what I am doing wrong in the software architecture. The initial target for the chain is "0x00ffff0000000000000000000000000000000000000000000000000000"

Should I use GPU for mining ? How can I properly debug the issue?

banner

Converter

Source: CurrencyRate
Top Selling Multipurpose WP Theme

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

banner

Leave a Comment

Layer 1
Your Crypto & Blockchain Beacon

CryptoInsightful

Welcome to CryptoInsightful.com, your trusted source for in-depth analysis, news, and insights into the world of cryptocurrencies, blockchain technology, NFTs (Non-Fungible Tokens), and cybersecurity. Our mission is to empower you with the knowledge and understanding you need to navigate the rapidly evolving landscape of digital assets and emerging technologies.