### Setup Go Environment (Bash) Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Installs a specific version of Go and configures the GOPATH and PATH environment variables for development. This is a prerequisite for building Go-based projects like Blockbook. ```bash wget https://golang.org/dl/go1.22.8.linux-amd64.tar.gz && tar xf go1.22.8.linux-amd64.tar.gz sudo mv go /opt/go sudo ln -s /opt/go/bin/go /usr/bin/go # see `go help gopath` for details mkdir $HOME/go export GOPATH=$HOME/go export PATH=$PATH:$GOPATH/bin ``` -------------------------------- ### Install ZeroMQ (Bash) Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Clones the ZeroMQ library, generates its build scripts, configures the build, and installs it system-wide. ZeroMQ is a messaging library often used for inter-process communication. ```bash git clone https://github.com/zeromq/libzmq cd libzmq ./autogen.sh ./configure make sudo make install ``` -------------------------------- ### Install RocksDB and Compile (Bash) Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Installs necessary build tools and libraries for RocksDB, clones the RocksDB repository, checks out a specific version, and compiles it for release. This provides the key-value store used by Blockbook. ```bash sudo apt-get update && sudo apt-get install -y \ build-essential git wget pkg-config libzmq3-dev libgflags-dev libsnappy-dev zlib1g-dev libzstd-dev libbz2-dev liblz4-dev git clone https://github.com/facebook/rocksdb.git cd rocksdb git checkout v9.10.0 CFLAGS=-fPIC CXXFLAGS=-fPIC make release ``` -------------------------------- ### Start Blockbook Service with Synchronization Source: https://github.com/trezor/blockbook/blob/master/docs/build.md This command starts the Blockbook service with parallel synchronization enabled. It specifies the blockchain configuration file, internal and public API ports, and enables logging to stderr. Requires a running backend daemon. ```shell ./blockbook -sync -blockchaincfg=build/blockchaincfg.json -internal=:9030 -public=:9130 -certfile=server/testcert -logtostderr ``` -------------------------------- ### Build Blockbook Binary Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Compiles the main Blockbook binary. The output binary is placed in the 'build' directory. Note that while Blockbook is a Go application, it has dynamic links to RocksDB and ZeroMQ, requiring these to be installed on the target operating system. ```bash make ``` -------------------------------- ### Build Blockbook (Bash) Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Fetches the Blockbook source code, navigates into the project directory, and compiles the application using the Go toolchain. This assumes Go and its dependencies are already set up. ```bash cd $GOPATH/src git clone https://github.com/trezor/blockbook.git cd blockbook go build ``` -------------------------------- ### Blockbook Websocket API Subscribe Addresses Example Source: https://github.com/trezor/blockbook/blob/master/docs/api.md An example demonstrating how to subscribe to new transactions for specific addresses using the Blockbook Websocket API. This requires the `subscribeAddresses` method and a list of addresses in the `params`. Ensure the websocket connection is established before sending. ```json { "id":"1", "method":"subscribeAddresses", "params":{ "addresses":["mnYYiDCb2JZXnqEeXta1nkt5oCVe2RVhJj", "tb1qp0we5epypgj4acd2c4au58045ruud2pd6heuee"] } } ``` -------------------------------- ### Get Block Information Response Example (JavaScript) Source: https://github.com/trezor/blockbook/blob/master/docs/api.md Demonstrates the JSON structure returned when requesting block information. It includes identifiers like hash, previous/next block hashes, height, confirmations, size, time, Merkle root, difficulty, and a list of transactions within the block. ```javascript { "page": 1, "totalPages": 1, "itemsOnPage": 1000, "hash": "760f8ed32894ccce9c1ea11c8a019cadaa82bcb434b25c30102dd7e43f326217", "previousBlockHash": "786a1f9f38493d32fd9f9c104d748490a070bc74a83809103bcadd93ae98288f", "nextBlockHash": "151615691b209de41dda4798a07e62db8429488554077552ccb1c4f8c7e9f57a", "height": 2648059, "confirmations": 47, "size": 951, "time": 1553096617, "version": 6422787, "merkleRoot": "6783f6083788c4f69b8af23bd2e4a194cf36ac34d590dfd97e510fe7aebc72c8", "nonce": "0", "bits": "1a063f3b", "difficulty": "2685605.260733312", "txCount": 2, "txs": [ { "txid": "2b9fc57aaa8d01975631a703b0fc3f11d70671953fc769533b8078a04d029bf9", "vin": [ { "n": 0, "value": "0" } ], "vout": [ { "value": "1000100000000", "n": 0, "addresses": [ "D6ravJL6Fgxtgp8k2XZZt1QfUmwwGuLwQJ" ], "isAddress": true } ], "blockHash": "760f8ed32894ccce9c1ea11c8a019cadaa82bcb434b25c30102dd7e43f326217", "blockHeight": 2648059, "confirmations": 47, "blockTime": 1553096617, "value": "1000100000000", "valueIn": "0", "fees": "0" }, { "txid": "d7ce10ecf9819801ecd6ee045cbb33436eef36a7db138206494bacedfd2832cf", "vin": [ { "n": 0, "addresses": [ "9sLa1AKzjWuNTe1CkLh5GDYyRP9enb1Spp" ], "isAddress": true, "value": "1277595845202" } ], "vout": [ { "value": "9900000000", "n": 0, "addresses": [ "DMnjrbcCEoeyvr7GEn8DS4ZXQjwq7E2zQU" ], "isAddress": true }, { "value": "1267595845202", "n": 1, "spent": true, "addresses": [ "9sLa1AKzjWuNTe1CkLh5GDYyRP9enb1Spp" ], "isAddress": true } ], "blockHash": "760f8ed32894ccce9c1ea11c8a019cadaa82bcb434b25c30102dd7e43f326217", "blockHeight": 2648059, "confirmations": 47, "blockTime": 1553096617, "value": "1277495845202", "valueIn": "1277595845202", "fees": "100000000" } ] } ``` -------------------------------- ### Build Debug Binary for Blockbook Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Compiles a debug version of the Blockbook binary, which includes debug symbols. This is useful for development and troubleshooting purposes. ```bash make build-debug ``` -------------------------------- ### Get UTXO Details Response Example (JavaScript) Source: https://github.com/trezor/blockbook/blob/master/docs/api.md Illustrates the structure of the response when querying for UTXOs. Each UTXO object contains details like transaction ID (txid), output index (vout), value, confirmations, and potentially height, lockTime, or coinbase status. ```javascript [ { "txid": "13d26cd939bf5d155b1c60054e02d9c9b832a85e6ec4f2411be44b6b5a2842e9", "vout": 0, "value": "1422303206539", "confirmations": 0, "lockTime": 2648100, }, { "txid": "a79e396a32e10856c97b95f43da7e9d2b9a11d446f7638dbd75e5e7603128cac", "vout": 1, "value": "39748685", "height": 2648043, "confirmations": 47, "coinbase": true, }, { "txid": "de4f379fdc3ea9be063e60340461a014f372a018d70c3db35701654e7066b3ef", "vout": 0, "value": "122492339065", "height": 2646043, "confirmations": 2047, }, { "txid": "9e8eb9b3d2e8e4b5d6af4c43a9196dfc55a05945c8675904d8c61f404ea7b1e9", "vout": 0, "value": "142771322208", "height": 2644885, "confirmations": 3205, }, ]; ``` -------------------------------- ### Send Signed Transaction via GET or POST Source: https://context7.com/trezor/blockbook/llms.txt Broadcasts a signed cryptocurrency transaction to the network. This can be done using either the HTTP GET or POST method. The transaction data should be properly formatted and signed before submission. The API returns a transaction ID upon successful broadcasting or an error message if the transaction fails. ```bash curl "https://btc1.trezor.io/api/v2/sendtx/0100000001..." ``` ```bash curl -X POST "https://btc1.trezor.io/api/v2/sendtx/" \ -H "Content-Type: text/plain" \ -d "0100000001..." ``` -------------------------------- ### GET /api/v2/tx/{txid} Source: https://context7.com/trezor/blockbook/llms.txt Fetch complete transaction information including inputs, outputs, confirmations, and blockchain-specific data. ```APIDOC ## GET /api/v2/tx/{txid} ### Description Fetches complete details for a specific blockchain transaction, including inputs, outputs, confirmations, and any relevant blockchain-specific data (e.g., gas usage for Ethereum transactions). ### Method GET ### Endpoint /api/v2/tx/{txid} ### Parameters #### Path Parameters - **txid** (string) - Required - The unique identifier (hash) of the transaction. ### Request Example ```bash # Bitcoin transaction curl "https://btc1.trezor.io/api/v2/tx/8c1e3dec662d1f2a5e322ccef5eca263f98eb16723c6f990be0c88c1db113fb1" ``` ### Response #### Success Response (200) *The response structure will vary based on the specific blockchain. Common fields include:* - **hash** (string) - The transaction hash. - **version** (integer) - The transaction version. - **locktime** (integer) - The locktime of the transaction. - **vin** (array of objects) - Input details. - **vout** (array of objects) - Output details. - **blockHash** (string) - The hash of the block containing the transaction. - **blockHeight** (integer) - The height of the block containing the transaction. - **confirmations** (integer) - The number of confirmations for the transaction. - **timestamp** (integer) - The timestamp of the transaction. - **size** (integer) - The size of the transaction in bytes. - **weight** (integer) - The transaction weight. - **fee** (string) - The transaction fee. - **gasUsed** (string) - Gas used for Ethereum-like transactions. - **gasPrice** (string) - Gas price for Ethereum-like transactions. #### Response Example *(Example for a Bitcoin transaction - structure may differ for other chains)* ```json { "hash": "8c1e3dec662d1f2a5e322ccef5eca263f98eb16723c6f990be0c88c1db113fb1", "version": 1, "locktime": 0, "vin": [ { "txid": "f1a1b1c1d1e1f1a1b1c1d1e1f1a1b1c1d1e1f1a1b1c1d1e1f1a1b1c1d1e1f1a1", "vout": 0, "scriptSig": { "asm": "SIG", "hex": "4104..." }, "txinwitness": [ "02..." ], "sequence": 4294967295 } ], "vout": [ { "value": "10000", "n": 0, "scriptPubKey": { "asm": "OP_DUP OP_HASH160 ... OP_EQUALVERIFY OP_CHECKSIG", "hex": "76a914...", "reqSigs": 1, "type": "pubkeyhash", "addresses": [ "1BoatSLRHtkn8zz0uZzzUFdK37yNfR2aZ4" ] } } ], "blockHash": "00000000000000000000abcdef0123456789abcdef0123456789abcdef012345", "blockHeight": 860000, "confirmations": 730, "timestamp": 1694000000, "size": 226, "weight": 904, "fee": "500" } ``` ``` -------------------------------- ### Configure Go for RocksDB (Bash) Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Sets environment variables to inform the Go compiler about the location of RocksDB headers and libraries. This is crucial for CGO to link against the compiled RocksDB static library. ```bash export CGO_CFLAGS="-I/path/to/rocksdb/include" export CGO_LDFLAGS="-L/path/to/rocksdb -lrocksdb -lstdc++ -lm -lz -ldl -lbz2 -lsnappy -llz4 -lzstd" ``` -------------------------------- ### Generate Blockbook Blockchain Configuration Source: https://github.com/trezor/blockbook/blob/master/docs/build.md This script generates the Blockbook's blockchain configuration file from coin definition files. It requires the coin name as an argument and outputs a JSON configuration. ```shell ./contrib/scripts/build-blockchaincfg.sh ``` -------------------------------- ### WebSocket API - Estimate Transaction Fees Source: https://context7.com/trezor/blockbook/llms.txt Get dynamic fee estimates for different confirmation targets, supporting both legacy and EIP-1559 fee structures for Bitcoin and Ethereum. ```APIDOC ## WebSocket API - Estimate Transaction Fees ### Description Get dynamic fee estimates for different confirmation targets with support for legacy and EIP-1559 fee structures. ### Method WebSocket Connection ### Endpoint `wss://[network].trezor.io/websocket/` (e.g., `wss://btc1.trezor.io/websocket/`, `wss://eth1.trezor.io/websocket/`) ### Parameters #### Request Body (for `estimateFee` - Bitcoin) - **id** (string) - Unique identifier for the request. - **method** (string) - Must be `estimateFee`. - **params** (object) - Contains the confirmation targets. - **blocks** (array of numbers) - Required - An array of block confirmation targets (e.g., [1, 3, 6, 10]). ### Request Example (Bitcoin) ```json { "id": "fee1", "method": "estimateFee", "params": { "blocks": [1, 3, 6, 10] } } ``` ### Response (Bitcoin) - **id** (string) - The ID of the request. - **data** (array) - An array of fee estimates per unit (e.g., sat/byte). - **feePerUnit** (string) - Estimated fee per unit for the corresponding confirmation target. ### Response Example (Bitcoin) ```json { "id": "fee1", "data": [ {"feePerUnit": "50"}, // 1 block (sat/byte) {"feePerUnit": "30"}, // 3 blocks {"feePerUnit": "20"}, // 6 blocks {"feePerUnit": "10"} // 10 blocks ] } ``` ### Parameters #### Request Body (for `estimateFee` - Ethereum EIP-1559) - **id** (string) - Unique identifier for the request. - **method** (string) - Must be `estimateFee`. ### Request Example (Ethereum) ```javascript const wsEth = new WebSocket('wss://eth1.trezor.io/websocket/'); wsEth.send(JSON.stringify({ "id": "fee2", "method": "estimateFee" })); ``` ### Response (Ethereum with EIP-1559) - **id** (string) - The ID of the request. - **data** (object) - Contains EIP-1559 fee details. - **eip1559** (object) - EIP-1559 specific fee information. - **baseFeePerGas** (string) - The current base fee per gas. - **low** (object) - Fee recommendation for slow confirmation. - **maxFeePerGas** (string) - Maximum fee per gas for slow confirmation. - **maxPriorityFeePerGas** (string) - Maximum priority fee per gas for slow confirmation. - **minWaitTimeEstimate** (number) - Minimum estimated wait time in seconds. - **maxWaitTimeEstimate** (number) - Maximum estimated wait time in seconds. - **medium** (object) - Fee recommendation for medium confirmation. - **high** (object) - Fee recommendation for fast confirmation. - **networkCongestion** (number) - Current network congestion level. - **priorityFeeTrend** (string) - Trend of priority fees (`up`, `down`, `stable`). - **baseFeeTrend** (string) - Trend of base fees (`up`, `down`, `stable`). ### Response Example (Ethereum) ```json { "id": "fee2", "data": { "eip1559": { "baseFeePerGas": "25000000000", "low": { "maxFeePerGas": "26000000000", "maxPriorityFeePerGas": "1000000000", "minWaitTimeEstimate": 300, "maxWaitTimeEstimate": 600 }, "medium": { "maxFeePerGas": "28000000000", "maxPriorityFeePerGas": "1500000000", "minWaitTimeEstimate": 60, "maxWaitTimeEstimate": 180 }, "high": { "maxFeePerGas": "32000000000", "maxPriorityFeePerGas": "2500000000", "minWaitTimeEstimate": 15, "maxWaitTimeEstimate": 60 }, "networkCongestion": 0.65, "priorityFeeTrend": "up", "baseFeeTrend": "down" } } } ``` ``` -------------------------------- ### Build Debian Packages for Blockbook and Coin Back-ends Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Builds Debian packages for Blockbook and a specified coin's back-end. The 'all-' target cleans the repository and rebuilds the Docker image before packaging, which is useful for production deployments. ```bash make all-bitcoin deb-blockbook-bitcoin_testnet ``` -------------------------------- ### List Built Debian Packages Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Lists the generated Debian package files (.deb) in the 'build' directory after executing build commands. This helps verify the successful creation of back-end and Blockbook packages. ```bash ls build/*.deb ``` -------------------------------- ### Get Xpub Balances and Transactions (HTTP) Source: https://github.com/trezor/blockbook/blob/master/docs/api.md This snippet demonstrates how to make an HTTP GET request to the Blockbook API to retrieve xpub details. It includes optional parameters for pagination, transaction filtering by block height, detail level, token information, and secondary currency display. The request targets a specific xpub or descriptor. ```HTTP GET /api/v2/xpub/[?page=&pageSize=&from=&to=&details=&tokens=&secondary=eur] ``` -------------------------------- ### Display Address Details using Go Templates Source: https://github.com/trezor/blockbook/blob/master/static/templates/xpub.html Renders detailed information for a given address, including balance, total received/sent amounts, transaction count, and token-specific details. It utilizes Go's templating engine for dynamic content generation. Outputs formatted HTML for display. ```go {{define "specific"}} {{$addr := .}} {{$data := .}} XPUB ==== ##### {{$addr.AddrStr}} #### {{formattedAmountSpan $addr.BalanceSat 0 $data.CoinShortcut $data "copyable"}} {{if $addr.SecondaryValue}} {{summaryValuesSpan 0 $addr.SecondaryValue $data}} {{end}} ##### Confirmed Total Received {{amountSpan $addr.TotalReceivedSat $data "copyable"}} Total Sent {{amountSpan $addr.TotalSentSat $data "copyable"}} Final Balance {{amountSpan $addr.BalanceSat $data "copyable"}} No. Transactions {{formatInt $addr.Txs}} Used XPUB Addresses {{formatInt $addr.UsedTokens}} {{if $addr.Tokens}} {{range $t := $addr.Tokens}} {{end}} {{else}} {{end}} ##### {{if $data.NonZeroBalanceTokens}}XPUB Addresses with Balance{{else}}XPUB Addresses{{end}} Address Balance Txs Path [{{$t.Name}}](/address/{{$t.Name}}) {{amountSpan $t.BalanceSat $data "copyable"}} {{formatInt $t.Transfers}} {{$t.Path}} No addresses {{if $data.NonZeroBalanceTokens}} [Show used XPUB addresses](?tokens=used)[Show all derived XPUB addresses](?tokens=derived) {{else}} [Show XPUB addresses with nonzero balance](?tokens=nonzero) {{end}} {{if $addr.UnconfirmedTxs}} ##### Unconfirmed Unconfirmed Balance {{amountSpan $addr.UnconfirmedBalanceSat $data "copyable"}} No. Transactions {{formatInt $addr.UnconfirmedTxs}} {{end}} {{if or $addr.Transactions $addr.Filter}} ### Transactions All XPUB addresses on input side XPUB addresses on output side {{template "paging" $data}} {{range $tx := $addr.Transactions}}{{$data := setTxToTemplateData $data $tx}}{{template "txdetail" $data}}{{end}} {{template "paging" $data }} {{end}}{{end}} ``` -------------------------------- ### Initialize Blockbook API Worker in Go Source: https://context7.com/trezor/blockbook/llms.txt This snippet shows the initialization of the Blockbook API worker in Go. It sets up the necessary dependencies including RocksDB for database operations, a blockchain connection for chain-specific data, a transaction cache, and fiat rate services. The worker is then used to fetch address details. ```go package main import ( "log" "github.com/trezor/blockbook/api" "github.com/trezor/blockbook/bchain" "github.com/trezor/blockbook/bchain/coins" "github.com/trezor/blockbook/common" "github.com/trezor/blockbook/db" "github.com/trezor/blockbook/fiat" ) func main() { // Initialize RocksDB database index, err := db.NewRocksDB( "/data/bitcoin/blockbook/db", 1<<29, // 512MB cache 1<<14, // 16384 max open files chainParser, metrics, false, // extended index disabled ) if err != nil { log.Fatal("Failed to open database:", err) } defer index.Close() // Initialize blockchain connection chain, mempool, err := coins.NewBlockChain( "Bitcoin", "/etc/blockbook/bitcoin.json", pushHandler, metrics, ) if err != nil { log.Fatal("Failed to connect to blockchain:", err) } // Initialize transaction cache txCache, err := db.NewTxCache(index, chain, metrics, internalState, true) if err != nil { log.Fatal("Failed to initialize tx cache:", err) } // Initialize fiat rates fiatRates, err := fiat.NewFiatRates(index, config, metrics, onNewRates) if err != nil { log.Fatal("Failed to initialize fiat rates:", err) } // Create API worker worker, err := api.NewWorker( index, chain, mempool, txCache, metrics, internalState, fiatRates, ) if err != nil { log.Fatal("Failed to create API worker:", err) } // Use worker to query address address, err := worker.GetAddress( "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh", api.AddressFilterOptions{ Details: api.AccountDetailsTxidHistory, PageSize: 100, Page: 1, }, nil, ) if err != nil { log.Fatal("Failed to get address:", err) } log.Printf("Address balance: %s satoshis\n", address.Balance) log.Printf("Total transactions: %d\n", address.Txs) } ``` -------------------------------- ### GET /api/v2/block-index/ Source: https://github.com/trezor/blockbook/blob/master/docs/api.md Retrieves the block hash for a given block height. This endpoint is part of API V2. ```APIDOC ## GET /api/v2/block-index/ ### Description Retrieves the block hash for a specified block height. ### Method GET ### Endpoint /api/v2/block-index/{block height} ### Parameters #### Path Parameters - **block height** (integer) - Required - The height of the block for which to retrieve the hash. ### Request Example None ### Response #### Success Response (200) - **blockHash** (string) - The hash of the block at the specified height. #### Response Example ```json { "blockHash": "0000000000000000000b7b8574bc6fd285825ec2dbcbeca149121fc05b0c828c" } ``` _Note: Blockbook always follows the main chain of the backend it is attached to. See notes on **Get Block** below_ ``` -------------------------------- ### Build Docker Images for Blockbook Source: https://github.com/trezor/blockbook/blob/master/docs/build.md Rebuilds the Docker images used for building Blockbook. This command is necessary when changes are made to the Dockerfile or related build configurations, ensuring the build environment is up-to-date. ```bash make build-images ``` -------------------------------- ### Send Transaction Source: https://context7.com/trezor/blockbook/llms.txt Broadcasts a signed transaction to the blockchain network. Supports both GET and POST methods for submitting the transaction. ```APIDOC ## POST /api/v2/sendtx/ or GET /api/v2/sendtx/{txHex} ### Description Broadcast a signed transaction to the blockchain network. The transaction can be sent via GET by appending the hex-encoded transaction to the endpoint, or via POST with the transaction in the request body. ### Method GET or POST ### Endpoint - GET: `/api/v2/sendtx/{txHex}` - POST: `/api/v2/sendtx/` ### Request Body (for POST) - **txHex** (string) - Required - The hex-encoded signed transaction. ### Request Example (POST) ```bash curl -X POST "https://btc1.trezor.io/api/v2/sendtx/" \ -H "Content-Type: text/plain" \ -d "0100000001..." ``` ### Response #### Success Response (200) - **result** (string) - The transaction ID of the broadcasted transaction. #### Error Response - **error** (object) - **message** (string) - Description of the error. ### Response Example (Success) ```json { "result": "7c3be24063f268aaa1ed81b64776798f56088757641a34fb156c4f51ed2e9d25" } ``` ### Response Example (Error) ```json { "error": { "message": "Transaction already in block chain" } } ``` ``` -------------------------------- ### Go SyncWorker: Initialize and Synchronize Blockchain Data Source: https://context7.com/trezor/blockbook/llms.txt Demonstrates initializing the SyncWorker for parallel blockchain data synchronization into RocksDB. It covers setting up signal handling for graceful shutdown, configuring worker parameters like parallel threads and chunk size, performing an initial resync to the blockchain tip, syncing a specific block range, and rolling back to a target height. ```go package main import ( "log" "os" "os/signal" "syscall" "github.com/trezor/blockbook/db" ) func main() { // Create signal channel for graceful shutdown chanOsSignal := make(chan os.Signal, 1) signal.Notify(chanOsSignal, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM) // Initialize sync worker syncWorker, err := db.NewSyncWorker( index, // RocksDB database chain, // blockchain connection 8, // number of parallel workers 100, // chunk size (blocks per batch) -1, // start from best height false, // not a dry run chanOsSignal, // interrupt signal metrics, // prometheus metrics internalState, ) if err != nil { log.Fatal("Failed to create sync worker:", err) } // Perform initial synchronization internalState.SyncMode = true internalState.InitialSync = true // Resync index to blockchain tip err = syncWorker.ResyncIndex( func(hash string, height uint32) { log.Printf("New block: %s at height %d\n", hash, height) }, true, // force resync ) if err != nil { log.Fatal("Sync failed:", err) } internalState.InitialSync = false log.Println("Initial synchronization complete") // Sync specific block range err = syncWorker.BulkConnectBlocks(850000, 850100) if err != nil { log.Fatal("Block range sync failed:", err) } // Perform rollback to specific height bestHeight, bestHash, _ := index.GetBestBlock() hashes := []string{bestHash} targetHeight := uint32(860000) for height := bestHeight - 1; height >= targetHeight; height-- { hash, _ := index.GetBlockHash(height) hashes = append(hashes, hash) } err = syncWorker.DisconnectBlocks(targetHeight, bestHeight, hashes) if err != nil { log.Fatal("Rollback failed:", err) } log.Printf("Rolled back to height %d\n", targetHeight) } ``` -------------------------------- ### GET /api/status Source: https://context7.com/trezor/blockbook/llms.txt Query the current synchronization status and system information for the Blockbook instance and connected blockchain backend. ```APIDOC ## GET /api/status ### Description Retrieves the current synchronization status and system information for the Blockbook instance and its connected blockchain backend. ### Method GET ### Endpoint /api/status ### Parameters None ### Request Example ```bash curl https://btc1.trezor.io/api/status ``` ### Response #### Success Response (200) - **blockbook** (object) - Information about the Blockbook service. - **coin** (string) - The cryptocurrency supported by this instance (e.g., "Bitcoin"). - **network** (string) - The network identifier (e.g., "BTC"). - **host** (string) - The host of the backend service. - **version** (string) - The Blockbook version. - **gitCommit** (string) - The Git commit hash. - **buildTime** (string) - The build time of Blockbook. - **syncMode** (boolean) - Indicates if Blockbook is in sync mode. - **initialSync** (boolean) - Indicates if the initial sync is in progress. - **inSync** (boolean) - Indicates if Blockbook is currently in sync. - **bestHeight** (integer) - The height of the best block. - **lastBlockTime** (string) - The timestamp of the last block. - **inSyncMempool** (boolean) - Indicates if the mempool is in sync. - **lastMempoolTime** (string) - The timestamp of the last mempool update. - **mempoolSize** (integer) - The current size of the mempool. - **decimals** (integer) - The number of decimal places for the cryptocurrency. - **dbSize** (integer) - The size of the Blockbook database. - **hasFiatRates** (boolean) - Indicates if fiat rates are available. - **currentFiatRatesTime** (string) - The timestamp of the latest fiat rates. - **about** (string) - A brief description of Blockbook. - **backend** (object) - Information about the connected blockchain backend. - **chain** (string) - The blockchain chain type (e.g., "main"). - **blocks** (integer) - The number of blocks on the chain. - **headers** (integer) - The number of headers on the chain. - **bestBlockHash** (string) - The hash of the best block. - **difficulty** (string) - The current mining difficulty. - **version** (string) - The version of the backend node. - **subversion** (string) - The subversion of the backend node. #### Response Example ```json { "blockbook": { "coin": "Bitcoin", "network": "BTC", "host": "backend5", "version": "0.5.0", "gitCommit": "a0960c8e", "buildTime": "2024-08-08T12:32:50+00:00", "syncMode": true, "initialSync": false, "inSync": true, "bestHeight": 860730, "lastBlockTime": "2024-09-10T08:19:04.471017534Z", "inSyncMempool": true, "lastMempoolTime": "2024-09-10T08:42:39.38871351Z", "mempoolSize": 232021, "decimals": 8, "dbSize": 761283489075, "hasFiatRates": true, "currentFiatRatesTime": "2024-09-10T08:42:00.898792419Z", "about": "Blockbook - blockchain indexer for Trezor Suite" }, "backend": { "chain": "main", "blocks": 860730, "headers": 860730, "bestBlockHash": "0000000000000000000effeb0c4460480e6a347deab95332c63007a68646ee5", "difficulty": "89471664776970.77", "version": "270100", "subversion": "/Satoshi:27.1.0/" } } ``` ``` -------------------------------- ### Filtering Integration Tests with Go's -run Flag Source: https://github.com/trezor/blockbook/blob/master/docs/testing.md Examples demonstrating how to filter integration tests in Blockbook using Go's built-in '-run' flag. This allows for precise control over which tests or test suites are executed, facilitating targeted testing and debugging. Various patterns are shown for selecting single tests, test suites, or sets of coins. ```bash make test-integration ARGS="-run=TestIntegration/bitcoin/" make test-integration ARGS="-run=TestIntegration//sync/" make test-integration ARGS="-run=TestIntegration//sync/HandleFork" make test-integration ARGS="-run='TestIntegration/(bcash|bgold|bitcoin|dash|dogecoin|litecoin|snowgem|vertcoin|zcash|zelcash)/'" ``` -------------------------------- ### GET /api/v2/address/{address} Source: https://context7.com/trezor/blockbook/llms.txt Retrieve balance, transaction history, and token holdings for a blockchain address with pagination and filtering options. ```APIDOC ## GET /api/v2/address/{address} ### Description Retrieves balance, transaction history, and token holdings for a given blockchain address. Supports various details and secondary currency conversions. ### Method GET ### Endpoint /api/v2/address/{address} ### Parameters #### Path Parameters - **address** (string) - Required - The blockchain address to query. #### Query Parameters - **details** (string) - Optional - Specifies additional details to include (e.g., "txids", "tokenBalances"). - **secondary** (string) - Optional - Specifies a secondary currency for conversion (e.g., "usd"). ### Request Example ```bash # Bitcoin address with transaction IDs curl "https://btc1.trezor.io/api/v2/address/bc1q0wd209cv5k9pd9mhk7nspacywcj038xxdhnt5u?details=txids" # Ethereum address with token balances and USD conversion curl "https://eth1.trezor.io/api/v2/address/0x2df3951b2037bA620C20Ed0B73CCF45Ea473e83B?details=tokenBalances&secondary=usd" ``` ### Response #### Success Response (200) - **page** (integer) - The current page number for paginated results. - **totalPages** (integer) - The total number of pages available. - **itemsOnPage** (integer) - The number of items displayed on the current page. - **address** (string) - The queried blockchain address. - **balance** (string) - The confirmed balance of the address. - **totalReceived** (string) - The total amount received by the address. - **totalSent** (string) - The total amount sent from the address. - **unconfirmedBalance** (string) - The unconfirmed balance of the address. - **unconfirmedTxs** (integer) - The number of unconfirmed transactions for the address. - **txs** (integer) - The total number of confirmed transactions for the address. - **txids** (array of strings) - A list of transaction IDs associated with the address (if `details=txids` is used). - **nonce** (string) - The nonce for Ethereum-like accounts. - **tokens** (array of objects) - List of token holdings (if `details=tokenBalances` is used). - **type** (string) - The token type (e.g., "ERC20"). - **name** (string) - The token name. - **contract** (string) - The token contract address. - **transfers** (integer) - The number of transfers for this token. - **symbol** (string) - The token symbol. - **decimals** (integer) - The token's decimal places. - **balance** (string) - The token balance. - **baseValue** (number) - The value of the token balance in the native currency. - **secondaryValue** (number) - The value of the token balance in the secondary currency. - **nonTokenTxs** (integer) - The number of non-token transactions (for Ethereum-like addresses). - **secondaryValue** (number) - The total value of the address balance in the secondary currency. - **totalBaseValue** (number) - The total value of the address balance in the native currency. - **totalSecondaryValue** (number) - The total value of all token balances in the secondary currency. #### Response Example ```json { "page": 1, "totalPages": 1, "itemsOnPage": 1000, "address": "bc1q0wd209cv5k9pd9mhk7nspacywcj038xxdhnt5u", "balance": "4225100", "totalReceived": "4225100", "totalSent": "0", "unconfirmedBalance": "0", "unconfirmedTxs": 0, "txs": 2, "txids": [ "0db6010dc0815a4bdaa505bd1ccc851056b0d53c7e4ea7af39c4d648a2c0c019", "7532920ddc506218337cceac978cce9c7f98e27ad3226dee55f3e934e0b32e80" ] } ``` ```json { "address": "0x2df3951b2037bA620C20Ed0B73CCF45Ea473e83B", "balance": "21004631949601199", "unconfirmedBalance": "0", "unconfirmedTxs": 0, "txs": 5, "nonTokenTxs": 3, "nonce": "1", "tokens": [ { "type": "ERC20", "name": "Tether USD", "contract": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "transfers": 3, "symbol": "USDT", "decimals": 6, "balance": "4913000000", "baseValue": 3.104622978658881, "secondaryValue": 4914.214559070491 } ], "secondaryValue": 33.247601671503574, "totalBaseValue": 3.125627610608482, "totalSecondaryValue": 4947.462160741995 } ``` ``` -------------------------------- ### Legacy REST API v1 Source: https://github.com/trezor/blockbook/blob/master/docs/api.md A subset of the Bitcore Insight API, primarily for Bitcoin-type coins. Supports various GET and POST requests for blockchain data. ```APIDOC ## Legacy REST API V1 ### Description Provides a compatible subset of the Bitcore Insight API, mainly for Bitcoin-type coins. Supports RESTful endpoints for retrieving blockchain information. ### Endpoints - **GET `/api/v1/block-index/`**: Get block index by height. - **GET `/api/v1/tx/`**: Get transaction details by transaction ID. - **GET `/api/v1/address/
`**: Get information about a specific address. - **GET `/api/v1/utxo/
`**: Get unspent transaction outputs (UTXOs) for an address. - **GET `/api/v1/block/`**: Get block details by height or hash. - **GET `/api/v1/estimatefee/`**: Estimate transaction fee based on number of blocks. - **GET `/api/v1/sendtx/`**: Broadcast a raw transaction (hex format) via GET request. - **POST `/api/v1/sendtx/`**: Broadcast a raw transaction (hex format) via POST request body. ### Note on Versioning As of Blockbook v0.5.0, the legacy API is also accessible without the `v1/` prefix. However, this version-less access will be removed in future versions. ``` -------------------------------- ### Running Blockbook Tests with Make Source: https://github.com/trezor/blockbook/blob/master/docs/testing.md These commands utilize the 'make' utility to execute different categories of tests within the Blockbook project. This includes running unit tests, integration tests, or all available tests. The ARGS variable can be used to pass additional arguments to the test runner, such as filtering specific tests. ```makefile make test make test-integration make test-all make test-all ARGS="-run TestBitcoin" ```