1

I was reading the fantastic https://goethereumbook.org book and found this example to listen to new blocks from Ethereum.

Could I ask in this case, how is uncle blocks handled? To put it in another way, how do I be certain that the new block I get here is not an uncle block?

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("wss://ropsten.infura.io/ws")
    if err != nil {
        log.Fatal(err)
    }

    headers := make(chan *types.Header)
    sub, err := client.SubscribeNewHead(context.Background(), headers)
    if err != nil {
        log.Fatal(err)
    }

    for {
        select {
        case err := <-sub.Err():
            log.Fatal(err)
        case header := <-headers:
            fmt.Println(header.Hash().Hex()) // 0xbc10defa8dda384c96a17640d84de5578804945d347072e091b4e5f390ddea7f

            block, err := client.BlockByHash(context.Background(), header.Hash())
            if err != nil {
                log.Fatal(err)
            }

            fmt.Println(block.Hash().Hex())        // 0xbc10defa8dda384c96a17640d84de5578804945d347072e091b4e5f390ddea7f
            fmt.Println(block.Number().Uint64())   // 3477413
            fmt.Println(block.Time().Uint64())     // 1529525947
            fmt.Println(block.Nonce())             // 130524141876765836
            fmt.Println(len(block.Transactions())) // 7
        }
    }
}
2

You can never be 100% sure that any given block will be in the long term chain, but as more blocks are added on top of it, the chance that a given block will become an uncle decreases exponentially. This is exactly the concept of "confirmations" that you may have heard about.

To be relatively sure that any particular block will not be reverted, you should wait ~12 blocks, then check to make sure the block of interest is still in the chain. The more blocks you wait the less likely the block will be lost.

So essentially, you can't be sure that every new block you get will not become an uncle, but if you wait a bit you can be almost certain.

  • Thank you! So there is no api like sub to new block with confirmation > 12 only.. And I need to do my own bookkeeping. – noooooooob Nov 6 '18 at 2:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.