blockbook/blockbook.go

514 lines
11 KiB
Go
Raw Normal View History

2017-08-28 09:50:57 -06:00
package main
import (
"context"
"encoding/hex"
2017-08-28 09:50:57 -06:00
"flag"
"os"
"os/signal"
2017-10-05 06:35:07 -06:00
"sync"
"syscall"
2017-08-28 09:50:57 -06:00
"time"
2017-09-12 18:50:34 -06:00
2018-01-31 07:23:17 -07:00
"blockbook/bchain"
2018-01-18 08:44:31 -07:00
"blockbook/db"
"blockbook/server"
"github.com/golang/glog"
2017-09-12 18:50:34 -06:00
"github.com/pkg/profile"
2017-08-28 09:50:57 -06:00
)
var (
rpcURL = flag.String("rpcurl", "http://localhost:8332", "url of bitcoin RPC service")
rpcUser = flag.String("rpcuser", "rpc", "rpc username")
rpcPass = flag.String("rpcpass", "rpc", "rpc password")
rpcTimeout = flag.Uint("rpctimeout", 25, "rpc timeout in seconds")
dbPath = flag.String("path", "./data", "path to address index directory")
2018-01-29 09:27:42 -07:00
blockHeight = flag.Int("blockheight", -1, "height of the starting block")
blockUntil = flag.Int("blockuntil", -1, "height of the final block")
rollbackHeight = flag.Int("rollback", -1, "rollback to the given height and quit")
2017-10-05 06:35:07 -06:00
2017-08-28 09:50:57 -06:00
queryAddress = flag.String("address", "", "query contents of this address")
2018-01-31 07:03:06 -07:00
synchronize = flag.Bool("sync", false, "synchronizes until tip, if together with zeromq, keeps index synchronized")
repair = flag.Bool("repair", false, "repair the database")
prof = flag.Bool("prof", false, "profile program execution")
2017-10-06 04:57:51 -06:00
syncChunk = flag.Int("chunk", 100, "block chunk size for processing")
syncWorkers = flag.Int("workers", 8, "number of workers to process blocks")
dryRun = flag.Bool("dryrun", false, "do not index blocks, only download")
2017-10-07 03:05:35 -06:00
parse = flag.Bool("parse", false, "use in-process block parsing")
2018-01-18 08:44:31 -07:00
2018-01-24 07:10:35 -07:00
httpServerBinding = flag.String("httpserver", "", "http server binding [address]:port, if missing no http server")
2018-01-19 07:58:46 -07:00
2018-01-24 07:10:35 -07:00
zeroMQBinding = flag.String("zeromq", "", "binding to zeromq, if missing no zeromq connection")
2017-08-28 09:50:57 -06:00
)
2018-01-31 07:03:06 -07:00
var (
2018-01-31 09:51:48 -07:00
chanSyncIndex = make(chan struct{})
chanSyncMempool = make(chan struct{})
chanSyncIndexDone = make(chan struct{})
chanSyncMempoolDone = make(chan struct{})
chain *bchain.BitcoinRPC
mempool *bchain.Mempool
index *db.RocksDB
2018-01-31 07:03:06 -07:00
)
2017-08-28 09:50:57 -06:00
func main() {
flag.Parse()
// override setting for glog to log only to stderr, to match the http handler
flag.Lookup("logtostderr").Value.Set("true")
2018-01-31 07:03:06 -07:00
defer glog.Flush()
if *prof {
defer profile.Start().Stop()
2018-01-19 07:58:46 -07:00
}
2017-09-12 08:53:40 -06:00
if *repair {
if err := db.RepairRocksDB(*dbPath); err != nil {
glog.Fatalf("RepairRocksDB %s: %v", *dbPath, err)
2017-09-12 08:53:40 -06:00
}
return
}
2018-01-31 07:23:17 -07:00
chain = bchain.NewBitcoinRPC(
2017-10-05 06:35:07 -06:00
*rpcURL,
*rpcUser,
*rpcPass,
time.Duration(*rpcTimeout)*time.Second)
2017-08-28 09:50:57 -06:00
2017-10-07 03:05:35 -06:00
if *parse {
2018-01-31 07:23:17 -07:00
chain.Parser = &bchain.BitcoinBlockParser{
Params: bchain.GetChainParams()[0],
2017-10-07 03:05:35 -06:00
}
}
2018-01-31 09:51:48 -07:00
mempool = bchain.NewMempool(chain)
2018-01-31 07:03:06 -07:00
var err error
index, err = db.NewRocksDB(*dbPath)
2017-08-28 09:50:57 -06:00
if err != nil {
glog.Fatalf("NewRocksDB %v", err)
2017-08-28 09:50:57 -06:00
}
2018-01-31 07:03:06 -07:00
defer index.Close()
2017-08-28 09:50:57 -06:00
2018-01-29 09:27:42 -07:00
if *rollbackHeight >= 0 {
2018-01-31 07:03:06 -07:00
bestHeight, _, err := index.GetBestBlock()
2018-01-29 09:27:42 -07:00
if err != nil {
glog.Fatalf("rollbackHeight: %v", err)
2018-01-29 09:27:42 -07:00
}
if uint32(*rollbackHeight) > bestHeight {
glog.Infof("nothing to rollback, rollbackHeight %d, bestHeight: %d", *rollbackHeight, bestHeight)
2018-01-29 09:27:42 -07:00
} else {
2018-01-31 07:03:06 -07:00
err = index.DisconnectBlocks(uint32(*rollbackHeight), bestHeight)
2018-01-29 09:27:42 -07:00
if err != nil {
glog.Fatalf("rollbackHeight: %v", err)
2018-01-29 09:27:42 -07:00
}
}
return
}
2018-01-31 09:51:48 -07:00
go syncIndexLoop()
go syncMempoolLoop()
2018-01-31 07:03:06 -07:00
if *synchronize {
if err := resyncIndex(); err != nil {
glog.Fatal("resyncIndex ", err)
2018-01-27 16:59:54 -07:00
}
}
2018-01-27 16:59:54 -07:00
var httpServer *server.HttpServer
2018-01-24 07:10:35 -07:00
if *httpServerBinding != "" {
2018-01-31 07:03:06 -07:00
httpServer, err = server.New(*httpServerBinding, index)
2018-01-18 08:44:31 -07:00
if err != nil {
2018-01-31 07:03:06 -07:00
glog.Fatal("https: ", err)
2018-01-18 08:44:31 -07:00
}
go func() {
err = httpServer.Run()
if err != nil {
2018-01-31 07:34:20 -07:00
if err.Error() == "http: Server closed" {
glog.Info(err)
} else {
glog.Fatal(err)
}
}
}()
2018-01-18 08:44:31 -07:00
}
2018-01-31 07:23:17 -07:00
var mq *bchain.MQ
2018-01-24 07:10:35 -07:00
if *zeroMQBinding != "" {
2018-01-31 07:03:06 -07:00
if !*synchronize {
glog.Error("zeromq connection without synchronization does not make sense, ignoring zeromq parameter")
} else {
2018-01-31 07:23:17 -07:00
mq, err = bchain.NewMQ(*zeroMQBinding, mqHandler)
2018-01-31 07:03:06 -07:00
if err != nil {
glog.Fatal("mq: ", err)
}
}
}
2017-08-28 09:50:57 -06:00
if *blockHeight >= 0 {
if *blockUntil < 0 {
*blockUntil = *blockHeight
}
height := uint32(*blockHeight)
until := uint32(*blockUntil)
address := *queryAddress
if address != "" {
2018-01-31 07:23:17 -07:00
script, err := bchain.AddressToOutputScript(address)
if err != nil {
glog.Fatalf("GetTransactions %v", err)
}
2018-01-31 07:03:06 -07:00
if err = index.GetTransactions(script, height, until, printResult); err != nil {
glog.Fatalf("GetTransactions %v", err)
2017-08-28 09:50:57 -06:00
}
2018-01-31 07:03:06 -07:00
} else if !*synchronize {
2017-10-06 04:57:51 -06:00
if err = connectBlocksParallel(
height,
until,
*syncChunk,
*syncWorkers,
); err != nil {
glog.Fatalf("connectBlocksParallel %v", err)
2017-08-28 09:50:57 -06:00
}
}
}
2018-01-31 07:03:06 -07:00
if httpServer != nil || mq != nil {
waitForSignalAndShutdown(httpServer, mq, 5*time.Second)
}
2018-01-31 07:03:06 -07:00
2018-01-31 09:51:48 -07:00
close(chanSyncIndex)
close(chanSyncMempool)
<-chanSyncIndexDone
<-chanSyncMempoolDone
2018-01-31 07:03:06 -07:00
}
2018-01-31 09:51:48 -07:00
func syncIndexLoop() {
defer close(chanSyncIndexDone)
glog.Info("syncIndexLoop starting")
for range chanSyncIndex {
if err := resyncIndex(); err != nil {
glog.Error(err)
}
2018-01-31 07:03:06 -07:00
}
2018-01-31 09:51:48 -07:00
glog.Info("syncIndexLoop stopped")
}
func syncMempoolLoop() {
defer close(chanSyncMempoolDone)
glog.Info("syncMempoolLoop starting")
for range chanSyncMempool {
if err := mempool.Resync(); err != nil {
glog.Error(err)
}
}
glog.Info("syncMempoolLoop stopped")
}
2018-01-31 07:23:17 -07:00
func mqHandler(m *bchain.MQMessage) {
body := hex.EncodeToString(m.Body)
2018-01-31 09:51:48 -07:00
glog.V(2).Infof("MQ: %s-%d %s", m.Topic, m.Sequence, body)
2018-01-31 07:03:06 -07:00
if m.Topic == "hashblock" {
2018-01-31 09:51:48 -07:00
chanSyncIndex <- struct{}{}
2018-01-31 07:03:06 -07:00
} else if m.Topic == "hashtx" {
2018-01-31 09:51:48 -07:00
chanSyncMempool <- struct{}{}
2018-01-31 07:03:06 -07:00
} else {
glog.Errorf("MQ: unknown message %s-%d %s", m.Topic, m.Sequence, body)
}
}
2018-01-31 07:23:17 -07:00
func waitForSignalAndShutdown(s *server.HttpServer, mq *bchain.MQ, timeout time.Duration) {
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
2018-01-18 12:32:10 -07:00
sig := <-stop
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
glog.Infof("Shutdown: %v", sig)
if mq != nil {
if err := mq.Shutdown(); err != nil {
glog.Error("MQ.Shutdown error: ", err)
}
}
2018-01-18 12:32:10 -07:00
if s != nil {
if err := s.Shutdown(ctx); err != nil {
glog.Error("HttpServer.Shutdown error: ", err)
2018-01-18 12:32:10 -07:00
}
}
2017-08-28 09:50:57 -06:00
}
2017-10-05 06:35:07 -06:00
func printResult(txid string) error {
glog.Info(txid)
2017-08-28 09:50:57 -06:00
return nil
}
2018-01-31 07:03:06 -07:00
func resyncIndex() error {
2017-10-05 06:35:07 -06:00
remote, err := chain.GetBestBlockHash()
if err != nil {
return err
}
2018-01-27 16:59:54 -07:00
localBestHeight, local, err := index.GetBestBlock()
if err != nil {
2017-10-05 06:35:07 -06:00
local = ""
}
2017-08-28 09:50:57 -06:00
2018-01-27 16:59:54 -07:00
// If the locally indexed block is the same as the best block on the
// network, we're done.
if local == remote {
glog.Infof("resync: synced on %d %s", localBestHeight, local)
2018-01-27 16:59:54 -07:00
return nil
}
2018-01-31 07:23:17 -07:00
var header *bchain.BlockHeader
if local != "" {
// Is local tip on the best chain?
header, err = chain.GetBlockHeader(local)
forked := false
2017-08-28 09:50:57 -06:00
if err != nil {
2018-01-31 07:23:17 -07:00
if e, ok := err.(*bchain.RPCError); ok && e.Message == "Block not found" {
forked = true
} else {
return err
}
} else {
if header.Confirmations < 0 {
forked = true
}
}
if forked {
// find and disconnect forked blocks and then synchronize again
glog.Info("resync: local is forked")
var height uint32
for height = localBestHeight - 1; height >= 0; height-- {
local, err = index.GetBlockHash(height)
if err != nil {
return err
}
remote, err = chain.GetBlockHash(height)
if err != nil {
return err
}
if local == remote {
break
}
2018-01-27 16:59:54 -07:00
}
err = index.DisconnectBlocks(height+1, localBestHeight)
2018-01-27 16:59:54 -07:00
if err != nil {
return err
}
2018-01-31 07:03:06 -07:00
return resyncIndex()
}
}
startHeight := uint32(0)
var hash string
if header != nil {
glog.Info("resync: local is behind")
hash = header.Next
startHeight = localBestHeight
} else {
// If the local block is missing, we're indexing from the genesis block
// or from the start block specified by flags
if *blockHeight > 0 {
startHeight = uint32(*blockHeight)
}
glog.Info("resync: genesis from block ", startHeight)
hash, err = chain.GetBlockHash(startHeight)
if err != nil {
return err
2018-01-27 16:59:54 -07:00
}
}
// if parallel operation is enabled and the number of blocks to be connected is large,
// use parallel routine to load majority of blocks
if *syncWorkers > 1 {
chainBestHeight, err := chain.GetBestBlockHeight()
2018-01-27 16:59:54 -07:00
if err != nil {
return err
}
if chainBestHeight-startHeight > uint32(*syncChunk) {
glog.Infof("resync: parallel sync of blocks %d-%d", startHeight, chainBestHeight)
err = connectBlocksParallel(
startHeight,
chainBestHeight,
*syncChunk,
*syncWorkers,
)
if err != nil {
return err
}
// after parallel load finish the sync using standard way,
// new blocks may have been created in the meantime
2018-01-31 07:03:06 -07:00
return resyncIndex()
}
}
2018-01-27 16:59:54 -07:00
2018-01-31 09:51:48 -07:00
err = connectBlocks(hash)
if err != nil {
return err
}
chanSyncMempool <- struct{}{}
return nil
}
2017-08-28 09:50:57 -06:00
2018-01-27 16:59:54 -07:00
func connectBlocks(
hash string,
) error {
2017-09-11 07:06:16 -06:00
bch := make(chan blockResult, 8)
done := make(chan struct{})
defer close(done)
2018-01-31 07:03:06 -07:00
go getBlockChain(hash, bch, done)
2017-09-11 07:06:16 -06:00
var lastRes blockResult
2017-09-11 07:06:16 -06:00
for res := range bch {
lastRes = res
2017-10-05 06:35:07 -06:00
if res.err != nil {
return res.err
2017-08-28 09:50:57 -06:00
}
2017-10-05 06:35:07 -06:00
err := index.ConnectBlock(res.block)
2017-08-28 09:50:57 -06:00
if err != nil {
return err
2017-08-28 09:50:57 -06:00
}
2017-09-06 07:36:55 -06:00
}
if lastRes.block != nil {
glog.Infof("resync: synced on %d %s", lastRes.block.Height, lastRes.block.Hash)
}
return nil
2017-08-28 09:50:57 -06:00
}
2017-10-05 06:35:07 -06:00
func connectBlocksParallel(
2017-09-04 06:16:37 -06:00
lower uint32,
higher uint32,
2017-10-06 04:57:51 -06:00
chunkSize int,
numWorkers int,
2017-09-04 06:16:37 -06:00
) error {
2017-10-05 06:35:07 -06:00
var wg sync.WaitGroup
2017-09-04 06:16:37 -06:00
2017-10-05 06:35:07 -06:00
work := func(i int) {
defer wg.Done()
offset := uint32(chunkSize * i)
stride := uint32(chunkSize * numWorkers)
2017-10-07 02:42:31 -06:00
for low := lower + offset; low <= higher; low += stride {
2017-10-06 04:57:51 -06:00
high := low + uint32(chunkSize-1)
2017-10-05 06:35:07 -06:00
if high > higher {
high = higher
}
2018-01-31 07:03:06 -07:00
err := connectBlockChunk(low, high)
2017-10-05 06:35:07 -06:00
if err != nil {
2018-01-31 07:23:17 -07:00
if e, ok := err.(*bchain.RPCError); ok && (e.Message == "Block height out of range" || e.Message == "Block not found") {
break
}
glog.Fatalf("connectBlocksParallel %d-%d %v", low, high, err)
2017-10-05 06:35:07 -06:00
}
2017-08-28 09:50:57 -06:00
}
2017-09-04 06:16:37 -06:00
}
2017-10-05 06:35:07 -06:00
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go work(i)
}
wg.Wait()
2017-09-04 06:16:37 -06:00
2017-10-05 06:35:07 -06:00
return nil
2017-09-04 06:16:37 -06:00
}
2017-10-05 06:35:07 -06:00
func connectBlockChunk(
lower uint32,
higher uint32,
2017-10-05 06:35:07 -06:00
) error {
2018-01-31 07:03:06 -07:00
connected, err := isBlockConnected(higher)
2017-10-05 06:35:07 -06:00
if err != nil || connected {
// if higher is over the best block, continue with lower block, otherwise return error
2018-01-31 07:23:17 -07:00
if e, ok := err.(*bchain.RPCError); !ok || e.Message != "Block height out of range" {
return err
}
2017-10-05 06:35:07 -06:00
}
2017-09-06 02:59:40 -06:00
height := lower
2017-10-05 06:35:07 -06:00
hash, err := chain.GetBlockHash(lower)
if err != nil {
2017-10-05 06:35:07 -06:00
return err
}
2017-09-06 02:59:40 -06:00
for height <= higher {
2017-10-05 06:35:07 -06:00
block, err := chain.GetBlock(hash)
2017-09-04 06:16:37 -06:00
if err != nil {
2017-10-05 06:35:07 -06:00
return err
2017-08-28 09:50:57 -06:00
}
2017-09-06 02:59:40 -06:00
hash = block.Next
height = block.Height + 1
2017-10-06 04:57:51 -06:00
if *dryRun {
continue
}
2017-10-05 06:35:07 -06:00
err = index.ConnectBlock(block)
if err != nil {
return err
}
if block.Height%1000 == 0 {
glog.Info("connected block ", block.Height, " ", block.Hash)
}
2017-08-28 09:50:57 -06:00
}
2017-10-05 06:35:07 -06:00
return nil
}
func isBlockConnected(
height uint32,
) (bool, error) {
local, err := index.GetBlockHash(height)
if err != nil {
return false, err
}
remote, err := chain.GetBlockHash(height)
if err != nil {
return false, err
}
if local != remote {
return false, nil
}
return true, nil
}
type blockResult struct {
2018-01-31 07:23:17 -07:00
block *bchain.Block
2017-10-05 06:35:07 -06:00
err error
2017-08-28 09:50:57 -06:00
}
2017-09-11 07:06:16 -06:00
func getBlockChain(
hash string,
out chan blockResult,
done chan struct{},
) {
defer close(out)
for hash != "" {
select {
case <-done:
return
default:
}
2017-10-05 06:35:07 -06:00
block, err := chain.GetBlock(hash)
2017-09-11 07:06:16 -06:00
if err != nil {
out <- blockResult{err: err}
return
}
hash = block.Next
out <- blockResult{block: block}
}
}