Skip to content

Instantly share code, notes, and snippets.

@ferranbt
Created September 16, 2019 08:45
Show Gist options
  • Save ferranbt/4ab9730cf764eab0b44bae27cfc3b755 to your computer and use it in GitHub Desktop.
Save ferranbt/4ab9730cf764eab0b44bae27cfc3b755 to your computer and use it in GitHub Desktop.
test-geth-setHead.go
package main
import (
"context"
"fmt"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
// Geth: 1.9.3-unstable-22fdbee8-20190822
// geth --dev --rpc --rpcapi eth,debug
var account common.Address
var dummy = common.HexToAddress("0x27E8C31b5f3A73a2C4d3555c28E53D10F7a7e747")
var (
rpcRaw *rpc.Client
client *ethclient.Client
)
func main() {
var err error
rpcRaw, err = rpc.Dial("http://127.0.0.1:8545")
if err != nil {
panic(err)
}
client = ethclient.NewClient(rpcRaw)
accounts := []common.Address{}
if err := rpcRaw.Call(&accounts, "eth_accounts"); err != nil {
panic(err)
}
account = accounts[0]
// Add a couple of blocks
readHead()
processBlock("0x1000")
readHead()
processBlock("0x1001")
readHead()
// reset to one
resetHead("0x1")
readHead()
// Add the same txn again
processBlock("0x1002")
}
func readHead() {
var num string
if err := rpcRaw.Call(&num, "eth_blockNumber"); err != nil {
panic(err)
}
fmt.Println(num)
}
func resetHead(str string) {
if err := rpcRaw.Call(nil, "debug_setHead", str); err != nil {
panic(err)
}
}
func processBlock(value string) *types.Receipt {
txn := map[string]string{
"from": account.String(),
"to": dummy.String(),
"value": value,
"gasPrice": "0x70000000",
"gas": "0x500000",
}
var hash common.Hash
err := rpcRaw.Call(&hash, "eth_sendTransaction", txn)
if err != nil {
panic(err)
}
var receipt *types.Receipt
var count int
for {
receipt, err = client.TransactionReceipt(context.Background(), hash)
if err != nil {
if err.Error() == "not found" {
if count > 20 {
panic("timeout")
}
time.Sleep(100 * time.Millisecond)
count++
continue
}
panic(err)
} else {
break
}
}
return receipt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment