Welcome to BlockCypher's API documentation! BlockCypher is a simple, mostly RESTful JSON API for interacting with blockchains, accessed over HTTP or HTTPS from the api.blockcypher.com domain. Currently, BlockCypher supports Bitcoin, Ethereum, Litecoin, Dash, Dogecoin, Bitcoin Testnet3, and BlockCypher's Test Chain (more about BlockCypher's Test Chain below).
BlockCypher's API provides a superset of the endpoints you'd find in reference implementations, in addition to some special features that make BlockCypher uniquely powerful, like our unconfirmed transaction Confidence Factor, dependable WebHook or WebSockets-based Events, and Address Forwarding.
Consequently, if you're familiar with a blockchain's reference implementation, you'll feel at home using BlockCypher, but without worrying about scaling or implementation challenges. And if you're not familiar---with the reference implementations or blockchains in general---BlockCypher's API is a great way to dip your toes into blockchain development, without a lengthy setup process. In either case, BlockCypher has 99.99% up-time, and maintains an expressive, logical API that you'll love.
Documentation Structure
man curl | grep-A 3 "DESCRIPTION"
DESCRIPTION
curl is a tool to transfer data from or to a server, using one of the supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP). The command is designed to work without user interaction.
// JavaScript examples use JQuery and can be run directly in your browser// console (ctrl+shift+i or cmd+shift+i).// Porting them to node.js should be trivial, replacing JQuery methods with// request.js for example.console.log('Welcome to BlockCypher');
# Ruby examples use irb, and our official ruby sdk:# https://github.com/blockcypher/ruby-client# You can install it easily from rubygems.org:# https://rubygems.org/gems/blockcypher-rubygeminstallblockcypher-ruby# Remember to require the library after installing>require'blockcypher'=>true# Unless otherwise noted, all requests assume an initialized API 'block_cypher' API object>block_cypher=BlockCypher::Api.new(api_token:"YOURTOKEN")=>#<BlockCypher::Api:0x000000010e4060 @api_token="YOURTOKEN", @currency="btc", @network="main", @version="v1">
# The official python library (https://github.com/blockcypher/blockcypher-python) works with python2/3
# Install it like this at the command line:
$pipinstallblockcypher# To access any method, first import the blockcypher module:
>>>importblockcypher# Then call the method:
>>>blockcypher.foo()# In your codebase, you should probably do it like this though:
>>>fromblockcypherimportfoo>>>foo()# By default, all methods return results for BTC, but blockcyphers support many coins.
# You can pass coin_sybmol='foo' as an argument to any method, where foo is one of the following:
>>>blockcypher.constants.COIN_SYMBOL_LIST["btc","btc-testnet","ltc","dash","doge","bcy",# blockcypher's testnet
]# Here's how to determine which version of the blockcypher SDK you're running:
>>>importpkg_resources>>>pkg_resources.get_distribution("blockcypher")blockcypher1.0.39(/usr/local/lib/python2.7/site-packages)
// Go examples use the official SDK, which you can find here:// https://github.com/blockcypher/gobcy// To install, use Go Get on the command line// go get github.com/blockcypher/gobcy// Then import the package in your Go application// All examples assume fmt is also imported, and// will require additional packages as necessarypackagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){// For Bitcoin main:btc:=gobcy.API{"YOURTOKEN","btc","main"}// For BlockCypher's internal testnet:bcy:=gobcy.API{"YOURTOKEN","bcy","test"}//examples will always follow in main()}// You can see additional info in the GoDoc, accessible here:// https://godoc.org/github.com/blockcypher/gobcy
PHP Client
----------
REQUIREMENTS
- PHP 5.4+
- ext-curl
- ext-gmp
- ext-mcrypt
- Composer
- Git
INSTALL SAMPLES
git clone https://github.com/blockcypher/php-client.git
cd php-client
RUNNING SAMPLES ON CONSOLE
php -f .\sample\docs-sample\address-api\address-endpoint.php
Log file is generate in the folder when you run the command
To see detailed PHP client info, check the official PHP repository:
https://github.com/blockcypher/php-client
Less relevant/repetitive code is not shown in samples. You can get the full sample version from:
https://github.com/blockcypher/php-client/tree/master/sample
Unless noted otherwise, all samples assume this initializing code:
<?phprequire__DIR__.'/../bootstrap.php';useBlockCypher\Auth\SimpleTokenCredential;useBlockCypher\Rest\ApiContext;// ... other classes$apiContext=ApiContext::create('main','btc','v1',newSimpleTokenCredential('$YOUR_TOKEN'),array('log.LogEnabled'=>true,'log.FileName'=>'BlockCypher.log','log.LogLevel'=>'DEBUG'));
In these docs you'll find everything you need to leverage BlockCypher for your applications. For all officially supported languages, you'll see code samples, in addition to basic cURL requests/responses for every endpoint. You can switch between cURL/language samples via the selector in the upper right. We're working on supporting more languages, but if you're working on your own language library, definitely let us know: we'd love to add more community supported libraries here.
Section Summaries
Objects: An overview of all the objects in the API, alongside detailed descriptions of every field.
Blockchain API: Endpoints to query general information about a blockchain and its blocks.
Address API: Query information about addresses, generate addresses, and generate multisig addresses from public keys.
Wallet API: Build and modify multiple-address-watching and hierarchical deterministic (HD) wallets, usable throughout the BlockCypher API.
Transaction API: Information about transactions, how to generate/send your own, and how to embed data into the blockchain.
Confidence Factor: Get an accurate measure of the likelihood of a successful double-spend against your unconfirmed transactions.
Metadata API: Store both public and private key-value pairs against addresses, transactions, and blocks.
Asset API: Create and manage your own assets---embedded on a public blockchain---via the Open Assets standard.
Address Forwarding: Create one-time addresses that will automatically forward to an address of your choosing, while optionally adding processing fees.
Events and Hooks: Reliable notifications system for a wide variety of events on blockchains, available through WebHooks or WebSockets.
Updates: List all the updates, bugfixes and new features in reverse chronological order.
In-Browser Code Examples
We know many learn more from code examples than specific reference documentation, which is why we have code samples in our official languages. In addition, we have a number of in-browser code examples for particular use cases, which you can see here:
Our documentation is powered by GitHub Pages and Slate, which makes viewing changes as simple as checking the git commit history. If there's an error or you'd like to suggest a change, please consider submitting a pull request to benefit the broader BlockCypher community.
API Versions
All API calls are versioned, and the current BlockCypher API is v1. We will never introduce any breaking changes within v1, but we may add new, non-breaking features from time to time.
BlockCypher Supported Language SDKs
BlockCypher has client SDKs for the following languages:
If you're using these languages, we strongly encourage you to use an official SDK. Of course, all our API calls are standard HTTP endpoints using JSON formatted responses, so any language (or cURL from the command-line) will work just fine.
Deprecated SDKs
Due to the lack of usage, the following SDKs have been deprecated and as such will not be updated:
You can still use them but beware that there might be some bugs or missing features.
Unofficial Libraries
This client SDK was made by the community, and is not officially supported by BlockCypher. As such, BlockCypher cannot guarantee that it's fully up to date, but we hope it will provide a nice jumping-off point for developers using this language. We'll endeavor to keep this list updated, if any of these prove obsolete. If there's enough support for a particular language, we'll work with the community to turn it into an officially supported SDK.
# Import Ruby SDK>require'blockcypher'=>true# Make new Api object, intialize with your token>block_cypher=BlockCypher::Api.new(api_token:"YOURTOKEN")=>#<BlockCypher::Api:0x000000010e4060 @api_token="YOURTOKEN", @currency="btc", @network="main", @version="v1"># Query base resource>block_cypher.blockchain=>{"name"=>"BTC.main","height"=>361218,"hash"=>"00000000000000000be2dca8e5336b01454fa032635a6f92d6adf0b98cdc6324","time"=>"2015-06-16T19:53:57.157318741Z","latest_url"=>"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000be2dca8e5336b01454fa032635a6f92d6adf0b98cdc6324","previous_hash"=>"00000000000000000c2f3f4b87214d1791289820f9f7b696d7484987a073f567","previous_url"=>"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000c2f3f4b87214d1791289820f9f7b696d7484987a073f567","peer_count"=>260,"unconfirmed_count"=>4442,"high_fee_per_kb"=>45494,"medium_fee_per_kb"=>24444,"low_fee_per_kb"=>12301,"last_fork_height"=>360362,"last_fork_hash"=>"000000000000000002d5cf67bfaa92ba5b371c1590eb48d25031c669ef6233a0"}
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}chainInfo,err:=btc.GetChain()iferr!=nil{fmt.Println(err)}fmt.Printf("%+v\n",chainInfo)}//Result from `go run`://{Name:BTC.main Height:648798 Hash:0000000000000000000eb01cbd9eb74c58d70ddb93f34e4e1bf71aeb8a6917fb Time:2020-09-17 20:20:20.214279195 +0000 UTC PrevHash:0000000000000000000a63f225af9678b8cd9dd4fb1dec67b6ca2e329d5efe48 PeerCount:1045 HighFee:84203 MediumFee:61367 LowFee:49335 UnconfirmedCount:17944 LastForkHeight:644543 LastForkHash:0000000000000000000ac8d61492ab76dab7451373c6eaa6803ec0244f623395}
<?php// Run on console:// php -f .\sample\chain-api\ChainEndpoint.php$blockchainClient=newBlockchainClient($apiContext);$blockchain=$blockchainClient->get('BTC.main');{"name":"BTC.main","height":360602,"hash":"00000000000000000a1268afd1eb419817106a37c9a87852228cadb752a64f2a","time":"2015-06-12T13:09:56.69966089Z","latest_url":"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000a1268afd1eb419817106a37c9a87852228cadb752a64f2a","previous_hash":"00000000000000000cea706491da61bc755a1250d7260becff5aafc9d26613f2","previous_url":"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000cea706491da61bc755a1250d7260becff5aafc9d26613f2","peer_count":250,"unconfirmed_count":1794,"high_fee_per_kb":40018,"medium_fee_per_kb":26652,"low_fee_per_kb":12299,"last_fork_height":360362,"last_fork_hash":"000000000000000002d5cf67bfaa92ba5b371c1590eb48d25031c669ef6233a0"}
Almost all resources exist under a given blockchain, and follow this pattern:
Currently, there's only one version of the API (v1). Thus, here's an exhaustive list of blockchains and their corresponding resources:
Coin
Chain
Resource
Bitcoin
Main
api.blockcypher.com/v1/btc/main
Bitcoin
Testnet3
api.blockcypher.com/v1/btc/test3
Dash
Main
api.blockcypher.com/v1/dash/main
Dogecoin
Main
api.blockcypher.com/v1/doge/main
Litecoin
Main
api.blockcypher.com/v1/ltc/main
BlockCypher
Test
api.blockcypher.com/v1/bcy/test
Rate Limits and Tokens
# Adding your token as URL parameter
curl https://api.blockcypher.com/v1/btc/main?token=$YOURTOKEN# Checking your token's limits
curl https://api.blockcypher.com/v1/tokens/$YOURTOKEN{"token": "YOURTOKEN",
"limits": {"api/hour": 10000,
"api/second": 500,
"hooks/hour": 5000,
"confidence/hour": 1000,
"hooks": 5000,
"payments": 5000
},
"hits": {"api/hour": 280,
"hooks/hour": 240,
"confidence/hour": 100
},
"hits_history": {{"api/hour": 253,
"confidence/hour": 50,
"time": "2016-06-15T07:00:00-00:00",
"hooks": 358,
},
{"api/hour": 2,
"hooks/hour": 30,
"time": "2016-06-15T06:00:00-00:00""hooks": 358,
},
...
}}# These are quite above the default limits, but if you'd like them, reach out at contact@blockcypher.com ;)
// Adding your token as URL parameterconstTOKEN='YOUR_TOKEN';$.get('https://api.blockcypher.com/v1/btc/main?token='+TOKEN);
# Import Ruby SDK>require'blockcypher'=>true# Make new Api object, intialize with your token>block_cypher=BlockCypher::Api.new(api_token:"YOURTOKEN")=>#<BlockCypher::Api:0x000000010e4060 @api_token="YOURTOKEN", @currency="btc", @network="main", @version="v1">
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){//Adding your token is part of the API coin/chain initializationbtc:=gobcy.API{"YOURTOKEN","btc","main"}fmt.Printf("%+v\n",btc)}//Result from `go run`://{Token:YOURTOKEN Coin:btc Chain:main}
<?php# Adding your token as client credential to API context$apiContext=ApiContext::create('main','btc','v1',newSimpleTokenCredential('c0afcccdde5081d6429de37d16166ead'),array('log.LogEnabled'=>true,'log.FileName'=>'BlockCypher.log','log.LogLevel'=>'DEBUG'));# Use $apiContext as function param or set as default ApiContext
We want everyone to try BlockCypher with as little friction as possible, which is why you don't need a token for any read-only GET calls. Please register for a user token if you want to use POST and DELETE calls. Once you have your token, you can append it to all your requests like any other URL parameter if you're using cURL, or through the appropriate method in the language SDK you're using.
We do rate-limit our free tier, with or without a token (though tokens are required for Confidence lookups, WebHooks/Sockets, Payments, and any POST or DELETE calls):
Classic requests, up to 3 requests/sec and 100 requests/hr
WebHooks and WebSockets, up to 100 requests sent to your servers/hr
WebHooks, up to 100 stored on our servers
Confidence lookups, up to 10 requests/hour
The hourly rate limits reset on the top of the hour UTC. For example, if you're under the free tier, and you have used 100 regular requests by 03:58 UTC, you'll hit a rate limit until it resets at 04:00 UTC.
On the accounts page, you'll find paid plans starting at $119 a month (with a 10% discount if you pay with Bitcoin). To request higher limits or SLAs beyond what's offered on the accounts page, please email us.
You can check your current limits and usage via a GET on the following endpoint, outside of our normal coin/chain pattern:
Within that return object, you'll also find hits_history array, which shows your token's last 48 hours of usage, while hits shows the current hour's usage.
You can even see information about your remaining limits by checking the X-Ratelimit-Remaining attribute in the HTTP header in normal API calls. Keep in mind the X-Ratelimit-Remaining attribute corresponds to the hourly rate limit associated with the endpoint you call (e.g., if it's from a WebHook, that corresponds to the Hooks/Hour; if it's a normal call, the number corresponds to the normal Requests/Hour limit).
//Batching requests is currently unsupported in the Go SDK//But you can still request things seriallypackagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}blocks:=make([]gobcy.Block,3)heights:=[]int{5,6,7}fori,v:=rangeheights{blk,err:=btc.GetBlock(v,"",nil)iferr!=nil{fmt.Println(err)}blocks[i]=blk}fmt.Printf("%+v\n",blocks)}//Result from `go run`://[{Hash:000000009b7262315dbf071787ad3656097b892abffd1f95a1a022f896f533fc Height:5 Depth:648793 Chain:BTC.main Total:{neg:false abs:[]} Fees:{neg:false abs:[]} Ver:1 Time:2009-01-09 03:23:48 +0000 UTC ReceivedTime:2009-01-09 03:23:48 +0000 UTC RelayedBy:<nil> Bits:486604799 Nonce:2011431709 NumTX:1 PrevBlock:000000004ebadb55ee9096c9a2f8880e09da59c0d68b1c228da88e48844a1485 MerkleRoot:63522845d294ee9b0188ae5cac91bf389a0c3723f084ca1025e7d9cdfe481ce1 TXids:[63522845d294ee9b0188ae5cac91bf389a0c3723f084ca1025e7d9cdfe481ce1] NextTXs:} {Hash:000000003031a0e73735690c5a1ff2a4be82553b2a12b776fbd3a215dc8f778d Height:6 Depth:648792 Chain:BTC.main Total:{neg:false abs:[]} Fees:{neg:false abs:[]} Ver:1 Time:2009-01-09 03:29:49 +0000 UTC ReceivedTime:2009-01-09 03:29:49 +0000 UTC RelayedBy:<nil> Bits:486604799 Nonce:2538380312 NumTX:1 PrevBlock:000000009b7262315dbf071787ad3656097b892abffd1f95a1a022f896f533fc MerkleRoot:20251a76e64e920e58291a30d4b212939aae976baca40e70818ceaa596fb9d37 TXids:[20251a76e64e920e58291a30d4b212939aae976baca40e70818ceaa596fb9d37] NextTXs:} {Hash:0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444 Height:7 Depth:648791 Chain:BTC.main Total:{neg:false abs:[]} Fees:{neg:false abs:[]} Ver:1 Time:2009-01-09 03:39:29 +0000 UTC ReceivedTime:2009-01-09 03:39:29 +0000 UTC RelayedBy:<nil> Bits:486604799 Nonce:2258412857 NumTX:1 PrevBlock:000000003031a0e73735690c5a1ff2a4be82553b2a12b776fbd3a215dc8f778d MerkleRoot:8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f TXids:[8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f] NextTXs:}]
<?php// Run on console:// php -f .\sample\introduction\Batching.php// Batching blocks 5, 6, and 7$blockClient=newBlockClient($apiContext);$blockList=array('5','6','7');$blocks=$blockClient->getMultiple($blockList);[{"hash":"000000003031a0e73735690c5a1ff2a4be82553b2a12b776fbd3a215dc8f778d","height":6,"chain":"BTC.main","total":0,"fees":0,"ver":1,"time":"2009-01-09T03:29:49Z",...,},{"hash":"000000009b7262315dbf071787ad3656097b892abffd1f95a1a022f896f533fc","height":5,"chain":"BTC.main","total":0,"fees":0,"ver":1,"time":"2009-01-09T03:23:48Z",...,},{"hash":"0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444","height":7,"chain":"BTC.main","total":0,"fees":0,"ver":1,"time":"2009-01-09T03:39:29Z",...,}]# Note, when constructing the block array (first param) programatically you can use alternative syntax like:$blockList=array('5','6','7');$blockList=explode(";","5;6;7");$blockList=[5,6,7];// PHP 5.4
All endpoints that can retrieve a single Object can be batched to return multiple objects. If you're cURLing the API directly, batching simply requires appending each identifier to the previous one using a semicolon (check the code pane for an example). The results are aggregated in a JSON array. The other supported client SDKs batch differently, but each idiomatic to their respective language (check the code pane examples in each library).
When cURLing BlockCypher, batching also works when the identifiers aren't the last part of the URL; e.g., this URL will return the balances of three separate addresses:
We offer an automated faucets for BlockCypher's Test Chain. We recommend using BlockCypher's Test Chain for a variety of reasons:
It's nearly identical in characteristics to Bitcoin Main, with a few differences listed below.
The prefix for standard addreses is 'B' or 'C' (0x1B). The prefix for multisig addresses is 'D' (0x1F). This is also known as the "address version byte," which you can read more about here.
The chain is private (no data is broadcasted, only BlockCypher mines the transactions), making it much more predictable than the Bitcoin's testnet (which is frequently under attack).
New blocks get built every minute, confirming the transactions that have been created using our transaction API.
In case you missed the Resources section, the BlockCypher Test Chain is accessible from this resource:
# Note resource change to bcy/test instead of btc/main# Make new address; returns private key/public key/address
curl -X POST https://api.blockcypher.com/v1/bcy/test/addrs?token=$YOURTOKEN{"private": "26415016a2fb49f51aef161cb35bd537be07b75a6ac1e297d3b7a370cc85433b",
"public": "02c572d062fefcc8c3e1bf5016450addcedb89cd7e4507d8a323f327b4ad1018e0",
"address": "CFqoZmZ3ePwK5wnkhxJjJAQKJ82C7RJdmd"}# Fund prior address with faucet
curl -d'{"address": "CFqoZmZ3ePwK5wnkhxJjJAQKJ82C7RJdmd", "amount": 100000}' https://api.blockcypher.com/v1/bcy/test/faucet?token=$YOURTOKEN{"tx_ref": "02dbf5585d438a1cba82a9041dd815635a6b0df684225cb5271e11397a759479"}
// Make new address; returns private key/public key/address$.post('https://api.blockcypher.com/v1/bcy/test/addrs?token=$YOUR_TOKEN').then(function(d){console.log(d)});>{>"private":"26415016a2fb49f51aef161cb35bd537be07b75a6ac1e297d3b7a370cc85433b",>"public":"02c572d062fefcc8c3e1bf5016450addcedb89cd7e4507d8a323f327b4ad1018e0",>"address":"CFqoZmZ3ePwK5wnkhxJjJAQKJ82C7RJdmd">}// Fund prior address with faucetvardata={"address":"CFqoZmZ3ePwK5wnkhxJjJAQKJ82C7RJdmd","amount":100000}$.post('https://api.blockcypher.com/v1/bcy/test/faucet?token=$YOUR_TOKEN',JSON.stringify(data)).then(function(d){console.log(d)});>{>"tx_ref":"02dbf5585d438a1cba82a9041dd815635a6b0df684225cb5271e11397a759479">}
# Create new api object on BlockCypher Testnet>bc_test=BlockCypher::Api.new(currency:BlockCypher::BCY,network:BlockCypher::TEST_NET,api_token:"YOURTOKEN")=>#<BlockCypher::Api:0x000000030169b0 @api_token="YOURTOKEN", @currency="bcy", @network="test", @version="v1"># Generate new test address>bc_test.address_generate=>{"private"=>"5a3675bbc7e24e63224bff60a3850a77d5a494419735e3b94173eac5379437c9","public"=>"0311ab9780760dd8c5d2d9319f1eee9c9328eddd503d0b86e3af253b1665638b8a","address"=>"Bv6rJzFmSg41nhibjfEfqSeeb2Te1Hh3FG","wif"=>"BrMPimGAWyUUuGduxHZi1Q9n9Nveunton8sC5ouZeJp6EhKNaAcZ"}# Fund with faucet>bc_test.faucet("Bv6rJzFmSg41nhibjfEfqSeeb2Te1Hh3FG",1000000)=>{"tx_ref"=>"59ddf03d9e292da5b3160e6ac341c9773873b693203c799a4ba8a4e05ef5a0d7"}
# Fund existing address with faucet
>>>fromblockcypherimportsend_faucet_coins# bcy is the coin_symbol for the blockcypher (not bitcoin) testnet
>>>send_faucet_coins(address_to_fund='CFqoZmZ3ePwK5wnkhxJjJAQKJ82C7RJdmd',satoshis=10000,api_key='YOUR_TOKEN',coin_symbol='bcy'){"tx_ref":"5d59f2ff777594fdfd964cd5ee4853e80cc3dc097a2ce67a55c16e643a99dddb"}
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){bcy:=gobcy.API{"YOURTOKEN","bcy","test"}//Generate new addresspair,err:=bcy.GenAddrKeychain()//Fund it with faucettxhash,err:=bcy.Faucet(pair,100000)iferr!=nil{fmt.Println(err)}fmt.Printf("Address: %v, Faucet TXHash: %v\n",pair.Address,txhash)}//Result from `go run`://Address: CF2ge9wF1KERoSrk9eRR8s2EJSLHiRMLPE, Faucet TXHash: aad5399bb760307e3d8b9c4d1d1480d0baddccc7f0ce2aca8df6e54ad4b260b3
<?php// Make new address; returns private key/public key/address// Run on console:// php -f .\sample\introduction\GenerateBcyAddress.php$addressClient=newAddressClient($apiContext);$addressKeyChain=$addressClient->generateAddress();{"private":"40e0d6e6210307b9b9d0113bceb9b8c5be6b9e010a03e07f25f75f462ed00a90","public":"03bd50fc57b1cdf3badbdf0662a4bb54b4d7a0b96eb27cc216b01503b8bf29b29e","address":"Bxi1GmU6xgqgyBEzugcqFZRLyJd1cpEv2S","wif":"BqW9QJ24VFcEvDp8UvYvLTnDxn1SjpxsvTeysPAjBW6BX9NggYfr"}<?php// Fund prior address with faucet// Run on console:// php -f .\sample\introduction\FundAddressWithFaucetEndpoint.php$faucetClient=newFaucetClient($apiContext);$faucetResponse=$faucetClient->fundAddress('Bxi1GmU6xgqgyBEzugcqFZRLyJd1cpEv2S',100000);{"tx_ref":"0fa68cf5c39dbd918a5ca49fc092be36b8bcece83cbfed919ad6c77b5f24cceb"}
Test Faucets
To help facilitate automated testing in your applications, a faucet endpoint is available on BlockCypher's Test Chain. Calling the faucet endpoint, along with passing a valid address, will automatically create---and propagate---a new transaction funding the address with the amount you provide.
This example shows how to leverage the faucet to programmatically fund addresses, to test your applications.
Objects
# All cURL'd Objects are JSON:{
key: value,
key: value,
}
Before diving into BlockCypher's endpoints, this section details all the Objects exposed and expected by the API. Some of you might be more interested in the endpoints themselves, in which case, feel free to skip to the next section. But for others, a section dedicated to all of BlockCypher's Objects might prove a useful overview, especially if you're new to Blockchain development in general. And in either case, this section provides a comprehensive reference for Objects in the API. For each Object there's a description and a link to a germane API endpoint.
A Blockchain represents the current state of a particular blockchain from the Coin/Chain resources that BlockCypher supports. Typically returned from the Chain API endpoint.
Attribute
Type
Description
name
string
The name of the blockchain represented, in the form of $COIN.$CHAIN.
height
integer
The current height of the blockchain; i.e., the number of blocks in the blockchain.
The time of the latest update to the blockchain; typically when the latest block was added.
latest_url
url
The BlockCypher URL to query for more information on the latest confirmed block; returns a Block.
previous_hash
string
The hash of the second-to-latest confirmed block in the blockchain.
previous_url
url
The BlockCypher URL to query for more information on the second-to-latest confirmed block; returns a Block.
peer_count
integer
N/A, will be deprecated soon.
high_fee_per_kb
integer
A rolling average of the fee (in satoshis) paid per kilobyte for transactions to be confirmed within 1 to 2 blocks.
medium_fee_per_kb
integer
A rolling average of the fee (in satoshis) paid per kilobyte for transactions to be confirmed within 3 to 6 blocks.
low_fee_per_kb
integer
A rolling average of the fee (in satoshis) paid per kilobyte for transactions to be confirmed in 7 or more blocks.
unconfirmed_count
integer
Number of unconfirmed transactions in memory pool (likely to be included in next block).
last_fork_height
integer
Optional The current height of the latest fork to the blockchain; when no competing blockchain fork present, not returned with endpoints that return Blockchains.
last_fork_hash
string
Optional The hash of the latest confirmed block in the latest fork of the blockchain; when no competing blockchain fork present, not returned with endpoints that return Blockchains.
The BlockCypher URL to query for more information on the previous block.
tx_url
url
The base BlockCypher URL to receive transaction details. To get more details about specific transactions, you must concatenate this URL with the desired transaction hash(es).
An array of transaction hashes in this block. By default, only 20 are included.
next_txids
url
Optional If there are more transactions that couldn't fit in the txids array, this is the BlockCypher URL to query the next set of transactions (within a Block object).
A TX represents the current state of a particular transaction from either a Block within a Blockchain, or an unconfirmed transaction that has yet to be included in a Block. Typically returned from the Unconfirmed Transactions and Transaction Hash endpoints.
Attribute
Type
Description
block_height
integer
Height of the block that contains this transaction. If this is an unconfirmed transaction, it will equal -1.
hash
string
The hash of the transaction. While reasonably unique, using hashes as identifiers may be unsafe.
addresses
array[string]
Array of bitcoin public addresses involved in the transaction.
total
integer
The total number of satoshis exchanged in this transaction.
fees
integer
The total number of fees---in satoshis---collected by miners in this transaction.
size
integer
The size of the transaction in bytes.
vsize
integer
The virtual size of the transaction in bytes.
preference
string
The likelihood that this transaction will make it to the next block; reflects the preference level miners have to include this transaction. Can be high, medium or low.
relayed_by
string
Address of the peer that sent BlockCypher's servers this transaction.
Time when transaction can be valid. Can be interpreted in two ways: if less than 500 million, refers to block height. If more, refers to Unix epoch time.
double_spend
bool
true if this is an attempted double spend; false otherwise.
vin_sz
integer
Total number of inputs in the transaction.
vout_sz
integer
Total number of outputs in the transaction.
confirmations
integer
Number of subsequent blocks, including the block the transaction is in. Unconfirmed transactions have 0 confirmations.
Optional Returns true if this transaction has opted in to Replace-By-Fee (RBF), either true or not present. You can read more about Opt-In RBF here.
confidence
float
Optional The percentage chance this transaction will not be double-spent against, if unconfirmed. For more information, check the section on Confidence Factor.
Optional Time at which transaction was included in a block; only present for confirmed transactions.
receive_count
integer
Optional Number of peers that have sent this transaction to BlockCypher; only present for unconfirmed transactions.
change_address
string
Optional Address BlockCypher will use to send back your change, if you constructed this transaction. If not set, defaults to the address from which the coins were originally sent.
block_hash
string
Optional Hash of the block that contains this transaction; only present for confirmed transactions.
block_index
integer
Optional Canonical, zero-indexed location of this transaction in a block; only present for confirmed transactions.
double_of
string
Optional If this transaction is a double-spend (i.e. double_spend == true) then this is the hash of the transaction it's double-spending.
data_protocol
string
Optional Returned if this transaction contains an OP_RETURN associated with a known data protocol. Data protocols currently detected: blockchainid ; openassets ; factom ; colu ; coinspark ; omni
hex
string
Optional Hex-encoded bytes of the transaction, as sent over the network.
next_inputs
url
Optional If there are more transaction inptus that couldn't fit into the TXInput array, this is the BlockCypher URL to query the next set of TXInputs (within a TX object).
next_outputs
url
Optional If there are more transaction outputs that couldn't fit into the TXOutput array, this is the BlockCypher URL to query the next set of TXOutputs(within a TX object).
A TXInput represents an input consumed within a transaction. Typically found within an array in a TX. In most cases, TXInputs are from previous UTXOs, with the most prominent exceptions being attempted double-spend and coinbase inputs.
Attribute
Type
Description
prev_hash
string
The previous transaction hash where this input was an output. Not present for coinbase transactions.
output_index
integer
The index of the output being spent within the previous transaction. Not present for coinbase transactions.
output_value
integer
The value of the output being spent within the previous transaction. Not present for coinbase transactions.
script_type
string
The type of script that encumbers the output corresponding to this input.
script
string
Raw hexadecimal encoding of the script.
addresses
array[string]
An array of public addresses associated with the output of the previous transaction.
sequence
integer
Legacy 4-byte sequence number, not usually relevant unless dealing with locktime encumbrances.
age
integer
Optional Number of confirmations of the previous transaction for which this input was an output. Currently, only returned in unconfirmed transactions.
wallet_name
string
Optional Name of Wallet or HDWallet from which to derive inputs. Only used when constructing transactions via the Creating Transactions process.
wallet_token
string
Optional Token associated with Wallet or HDWallet used to derive inputs. Only used when constructing transactions via the Creating Transactions process.
A TXOutput represents an output created by a transaction. Typically found within an array in a TX.
Attribute
Type
Description
value
int
Value in this transaction output, in satoshis.
script
string
Raw hexadecimal encoding of the encumbrance script for this output.
addresses
array[string]
Addresses that correspond to this output; typically this will only have a single address, and you can think of this output as having "sent" value to the address contained herein.
script_type
string
The type of encumbrance script used for this output.
spent_by
string
Optional The transaction hash that spent this output. Only returned for outputs that have been spent. The spending transaction may be unconfirmed.
data_hex
string
Optional A hex-encoded representation of an OP_RETURN data output, without any other script instructions. Only returned for outputs whose script_type is null-data.
data_string
string
Optional An ASCII representation of an OP_RETURN data output, without any other script instructions. Only returned for outputs whose script_type is null-data and if its data falls into the visible ASCII range.
A TXConfidence represents information about the confidence that an unconfirmed transaction will make it into the next block. Typically used as a return object from the Transaction Confidence Endpoint.
Attribute
Type
Description
age_millis
integer
The age of the transaction in milliseconds, based on the earliest time BlockCypher saw it relayed in the network.
receive_count
integer
Number of peers that have sent this transaction to BlockCypher; only positive for unconfirmed transactions. -1 for confirmed transactions.
confidence
float
A number from 0 to 1 representing BlockCypher's confidence that the transaction won't be double-spent against.
txhash
string
The hash of the transaction. While reasonably unique, using hashes as identifiers may be unsafe.
txurl
url
The BlockCypher URL one can use to query more detailed information about this transaction.
A TXRef object represents summarized data about a transaction input or output. Typically found in an array within an Address object, which is usually returned from the standard Address Endpoint.
Attribute
Type
Description
address
string
Optional The address associated with this transaction input/output. Only returned when querying an address endpoint via a wallet/HD wallet name.
block_height
integer
Height of the block that contains this transaction input/output. If it's unconfirmed, this will equal -1.
tx_hash
string
The hash of the transaction containing this input/output. While reasonably unique, using hashes as identifiers may be unsafe.
tx_input_n
integer
Index of this input in the enclosing transaction. It's a negative number for an output.
tx_output_n
integer
Index of this output in the enclosing transaction. It's a negative number for an input.
value
integer
The value transfered by this input/output in satoshis exchanged in the enclosing transaction.
preference
string
The likelihood that the enclosing transaction will make it to the next block; reflects the preference level miners have to include the enclosing transaction. Can be high, medium or low.
spent
bool
true if this is an output and was spent. If it's an input, or an unspent output, it will be false.
double_spend
bool
true if this is an attempted double spend; false otherwise.
confirmations
integer
Number of subsequent blocks, including the block the transaction is in. Unconfirmed transactions have 0 confirmations.
script
string
Optional Raw, hex-encoded script of this input/output.
ref_balance
integer
Optional The past balance of the parent address the moment this transaction was confirmed. Not present for unconfirmed transactions.
confidence
float
Optional The percentage chance this transaction will not be double-spent against, if unconfirmed. For more information, check the section on Confidence Factor.
A temporary TX, usually returned fully filled but missing input scripts.
tosign
array[string]
Array of hex-encoded data for you to sign, one for each input.
signatures
array[string]
Array of signatures corresponding to all the data in tosign, typically provided by you.
pubkeys
array[string]
Array of public keys corresponding to each signature. In general, these are provided by you, and correspond to the signatures you provide.
tosign_tx
array[string]
Optional Array of hex-encoded, work-in-progress transactions; optionally returned to validate the tosign data locally.
errors
array["error":string]
Optional Array of errors in the form "error":"description-of-error". This is only returned if there was an error in any stage of transaction generation, and is usually accompanied by a HTTP 400 code.
An Address represents a public address on a blockchain, and contains information about the state of balances and transactions related to this address. Typically returned from the Address Balance, Address, and Address Full Endpoint.
Attribute
Type
Description
address
string
Optional The requested address. Not returned if querying a wallet/HD wallet.
Optional The requested HD wallet object. Only returned if querying by HD wallet name instead of public address.
total_received
integer
Total amount of confirmed satoshis received by this address.
total_sent
integer
Total amount of confirmed satoshis sent by this address.
balance
integer
Balance of confirmed satoshis on this address. This is the difference between outputs and inputs on this address, but only for transactions that have been included into a block (i.e., for transactions whose confirmations > 0).
unconfirmed_balance
integer
Balance of unconfirmed satoshis on this address. Can be negative (if unconfirmed transactions are just spending outputs). Only unconfirmed transactions (haven't made it into a block) are included.
final_balance
integer
Total balance of satoshis, including confirmed and unconfirmed transactions, for this address.
n_tx
integer
Number of confirmed transactions on this address. Only transactions that have made it into a block (confirmations > 0) are counted.
unconfirmed_n_tx
integer
Number of unconfirmed transactions for this address. Only unconfirmed transactions (confirmations == 0) are counted.
final_n_tx
integer
Final number of transactions, including confirmed and unconfirmed transactions, for this address.
tx_url
url
Optional To retrieve base URL transactions. To get the full URL, concatenate this URL with a transaction's hash.
Optional All unconfirmed transaction inputs and outputs for this address. Usually only returned from the standard Address Endpoint.
hasMore
bool
Optional If true, then the Address object contains more transactions than shown. Useful for determining whether to poll the API for more transaction information.
An AddressKeychain represents an associated collection of public and private keys alongside their respective public address. Generally returned and used with the Generate Address Endpoint.
A Wallet contains a list of addresses associated by its name and the user's token. It can be used interchangeably with all the Address API endpoints, and in many places that require addresses, like when Creating Transactions.
The name of a wallet must be 1-25 characters long and cannot start with any characters that start an address for the currency contained in the wallet. For example, bitcoin wallet names cannot start with '1' or '3'.
An HDWallet contains addresses derived from a single seed. Like normal wallets, it can be used interchangeably with all the Address API endpoints, and in many places that require addresses, like when Creating Transactions.
List of HD chains associated with this wallet, each containing HDAddresses. A single chain is returned if the wallet has no subchains.
hd
bool
true for HD wallets, not present for normal wallets.
extended_public_key
string
The extended public key all addresses in the HD wallet are derived from. It's encoded in BIP32 format
subchain_indexes
array[integer]
optional returned for HD wallets created with subchains.
The name of a wallet must be 1-25 characters long and cannot start with any characters that start an address for the currency contained in the wallet. For example, bitcoin wallet names cannot start with '1' or '3'.
An HD Address object contains an address and its BIP32 HD path (location of the address in the HD tree). It also contains the hex-encoded public key when returned from the Derive Address in Wallet endpoint.
Optional Associated hex-encoded metadata with this transaction, if it exists.
double_spend
bool
true if this is an attempted double spend; false otherwise.
inputs
array[...]
Array of input data, which can be seen explicitly in the cURL example. Very similar to array of TXInputs, but with values related to assets instead of satoshis.
outputs
array[...]
Array of output data, which can be seen explicitly in the cURL example. Very similar to array of TXOutputs, but with values related to assets instead of satoshis.
An Event represents a WebHooks or WebSockets-based notification request, as detailed in the Events & Hooks section of the documentation.
Attribute
Type
Description
id
string
Identifier of the event; generated when a new request is created.
event
string
Type of event; can be unconfirmed-tx, new-block, confirmed-tx, tx-confirmation, double-spend-tx, tx-confidence.
hash
string
optional Only objects with a matching hash will be sent. The hash can either be for a block or a transaction.
wallet_name
string
optional Only transactions associated with the given wallet will be sent; can use a regular or HD wallet name. If used, requires a user token.
token
string
optional Required if wallet_name is used, though generally we advise users to include it (as they can reach API throttling thresholds rapidly).
address
string
optional Only transactions associated with the given address will be sent. A wallet name can also be used instead of an address, which will then match on any address in the wallet.
confirmations
integer
optional Used in concert with the tx-confirmation event type to set the number of confirmations desired for which to receive an update. You'll receive an updated TX for every confirmation up to this amount. The maximum allowed is 10; if not set, it will default to 6.
confidence
float
optional Used in concert with the tx-confidence event type to set the minimum confidence for which you'll receive a notification. You'll receive a TX once this threshold is met. Will accept any float between 0 and 1, exclusive; if not set, defaults to 0.99.
script
string
optional Only transactions with an output script of the provided type will be sent. The recognized types of scripts are: pay-to-pubkey-hash, pay-to-multi-pubkey-hash, pay-to-pubkey, pay-to-script-hash, null-data (sometimes called OP_RETURN), empty or unknown.
url
url
optional Callback URL for this Event's WebHook; not applicable for WebSockets usage.
callback_errors
int
Number of errors when attempting to POST to callback URL; not applicable for WebSockets usage.
A AddressForward object represents a request set up through the Address Forwarding service.
Attribute
Type
Description
id
string
Identifier of the orwarding request; generated when a new request is created.
token
string
The mandatory user token.
destination
string
The required destination address to forward to.
input_address
string
The address which will automatically forward to destination; generated when a new request is created.
process_fees_address
string
Optional Address to forward processing fees, if specified. Allows you to receive a fee for your own services.
process_fees_satoshis
int
Optional Fixed processing fee amount to be sent to the fee address. A fixed satoshi amount or a percentage is required if a process_fees_address has been specified.
process_fees_percent
float
Optional Percentage of the transaction to be sent to the fee address. A fixed satoshi amount or a percentage is required if a process_fees_address has been specified.
callback_url
url
Optional The URL to call anytime a new transaction is forwarded.
enable_confirmations
bool
Optional Whether to also call the callback_url with subsequent confirmations of the forwarding transactions. Automatically sets up a WebHook.
mining_fees_satoshis
int
Optional Mining fee amount to include in the forwarding transaction, in satoshis. If not set, defaults to 10,000.
txs
array[string]
Optional History of forwarding transaction hashes for this forward; not present if this request has yet to forward any transactions.
A AddressForwardCallback object represents the payload delivered to the optional callback_url in a AddressForward request.
Attribute
Type
Description
value
int
Amount sent to the destination address, in satoshis.
input_address
string
The intermediate address to which the transaction was originally sent.
destination
string
The final destination address to which the forward will eventually be sent.
input_transaction_hash
string
The transaction hash representing the initial transaction to the input_address.
transaction_hash
string
The transaction hash of the generated transaction that forwards from the input_address to the destination.
Blockchain API
The first component---and highest level---of the BlockCypher API allows you to query general information about blockchain and blocks based on the coin/chain resource you've selected for your endpoints.
If you're new to blockchains, you can think of the blockchain itself as an immutable, distributed ledger. Each block in the blockchain is like a "page" in the ledger containing information about transactions between parties. A great place to start understanding the mechanics behind blockchains is the original Bitcoin whitepaper.
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}chain,err:=btc.GetChain()iferr!=nil{fmt.Println(err)}fmt.Printf("%+v\n",chain)}//Result from `go run`://{Name:BTC.main Height:648800 Hash:00000000000000000006f4157b3fa48928e09f5d8a6696604df43f1187547354 Time:2020-09-17 20:39:41.770732359 +0000 UTC PrevHash:000000000000000000017aa67661ee1764357965e04b58b7b789be67af2b5acc PeerCount:1045 HighFee:86603 MediumFee:61014 LowFee:49127 UnconfirmedCount:17910 LastForkHeight:644543 LastForkHash:0000000000000000000ac8d61492ab76dab7451373c6eaa6803ec0244f623395}
<?php// Run on console:// php -f .\sample\chain-api\ChainEndpoint.php$blockchainClient=newBlockchainClient($apiContext);$blockchain=$blockchainClient->get('BTC.main');{"name":"BTC.main","height":360602,"hash":"00000000000000000a1268afd1eb419817106a37c9a87852228cadb752a64f2a","time":"2015-06-12T13:09:56.69966089Z","latest_url":"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000a1268afd1eb419817106a37c9a87852228cadb752a64f2a","previous_hash":"00000000000000000cea706491da61bc755a1250d7260becff5aafc9d26613f2","previous_url":"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000cea706491da61bc755a1250d7260becff5aafc9d26613f2","peer_count":250,"unconfirmed_count":1794,"high_fee_per_kb":40018,"medium_fee_per_kb":26652,"low_fee_per_kb":12299,"last_fork_height":360362,"last_fork_hash":"000000000000000002d5cf67bfaa92ba5b371c1590eb48d25031c669ef6233a0"}
General information about a blockchain is available by GET-ing the base resource.
>>>fromblockcypherimportget_block_overview>>>get_block_overview('00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db'){'hash':'00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db','height':671142,'chain':'BTC.main','total':2928942845838,'fees':135268918,'size':1448143,'vsize':998941,'ver':1073725440,'time':datetime.datetime(2021,2,18,16,1,12,tzinfo=tzlocal()),'received_time':datetime.datetime(2021,2,18,16,2,17,341000,tzinfo=tzlocal()),'coinbase_addr':'','relayed_by':'68.168.176.51:8333','bits':386736569,'nonce':3270005482,'n_tx':2025,'prev_block':'00000000000000000001245ac74971793689be7924cd0b031302661e806deb0d','mrkl_root':'5283c26fb8d64d2284ffda76af6cd584292b76f265932cd121ac16fb475d7a8a','txids':['39dec39382157569b809446037c6d5658d490e38907060112c16d8de49aeab0b','ce0a8256a459ba14feb48931a2344ff7af3af4f9aa2b5acb795a1b0b9fd8806e','2d11ef988d9960a12f94d76525cc0001cf56bb9d3c7d47d405e8a40a008da653','17648e06bdb4a126b8ebdf763e21107a5e54b548c266b056dfcb4aae3343253e','7fbb8ce7ab5aba798eca6eab0076af2f5c621576d90a1cb471da62f4fca61df3','acf6a8781c6df77a437daa70fa2d51acf4b2fc70dc60cb3890b74901173ad125','cab8f38c42d82524767ad1c3443bf4c00cb6a4f9f5b19eb1c57e6c13123c2d67','dfb6dcce198a2d6415d3e322a0c3b6957d5a35e7cbdffeac209ed71cac9dd3f5','786c4e4bd5f456bf2c42eef8374cf41b5a4e6ccccda3043ea2612840a2523fc4','f28339e0247323e59c0d49d2480b8abb48fba4190e8f83bc37d1f095e29dd958','f7133abcf74884575296c1e2c3545080f88aa753f9542c88bffb79cdb34a4aa5','5db89c67ccaaa248028989c52bfa952eafc171d3e48fd15ba5dd0dfd368e1c06','dc4cc5acf9edb14cd9b8659d4a2405eae5d425867d861607f89826ffcb0f5459','fec4304054685c4a25f56b057ae3bab421fa998ca91812ad849c2518b3969288','e8441b85cc6036e40f745de4fd909b98507656d7e3a5762578ec50a03219099a','023c1577f21a7fdd428cc514726483c10039bd65afdf2f3da2b890f74350a073','389a04bfa0b809c33b147f24104d4a60581578da644282931abfff8d5a248679','ea31698b76076d4a2fef47d1c0dbc9df4539abf072e8bd29cefbf65daddaa6c5','1d52fbf97eaf19935edf21543f27455b7102290edc1d1f143fcb7b235196ddd3','60e5282257e1ebd742589a7122ff52aa7d78ef1821027301e84335e71ac19790'],'depth':1,'prev_block_url':'https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000001245ac74971793689be7924cd0b031302661e806deb0d','tx_url':'https://api.blockcypher.com/v1/btc/main/txs/','next_txids':'https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db?txstart=20&limit=20'}# note that you can batch blocks with blockcypher.get_blocks_overview()
<?php// Run on console:// php -f .\sample\block-api\BlockHashEndpoint.php$blockClient=newBlockClient($apiContext);$block=$blockClient->get('00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db');{"hash":"00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db","height":671142,"chain":"BTC.main","total":2928942845838,"fees":135268918,"size":1448143,"vsize":998941,"ver":1073725440,"time":"2021-02-18T16:01:12Z","received_time":"2021-02-18T16:02:17.341Z","coinbase_addr":"","relayed_by":"68.168.176.51:8333","bits":386736569,"nonce":3270005482,"n_tx":2025,"prev_block":"00000000000000000001245ac74971793689be7924cd0b031302661e806deb0d","mrkl_root":"5283c26fb8d64d2284ffda76af6cd584292b76f265932cd121ac16fb475d7a8a","txids":["39dec39382157569b809446037c6d5658d490e38907060112c16d8de49aeab0b","ce0a8256a459ba14feb48931a2344ff7af3af4f9aa2b5acb795a1b0b9fd8806e","2d11ef988d9960a12f94d76525cc0001cf56bb9d3c7d47d405e8a40a008da653","17648e06bdb4a126b8ebdf763e21107a5e54b548c266b056dfcb4aae3343253e","7fbb8ce7ab5aba798eca6eab0076af2f5c621576d90a1cb471da62f4fca61df3","acf6a8781c6df77a437daa70fa2d51acf4b2fc70dc60cb3890b74901173ad125","cab8f38c42d82524767ad1c3443bf4c00cb6a4f9f5b19eb1c57e6c13123c2d67","dfb6dcce198a2d6415d3e322a0c3b6957d5a35e7cbdffeac209ed71cac9dd3f5","786c4e4bd5f456bf2c42eef8374cf41b5a4e6ccccda3043ea2612840a2523fc4","f28339e0247323e59c0d49d2480b8abb48fba4190e8f83bc37d1f095e29dd958","f7133abcf74884575296c1e2c3545080f88aa753f9542c88bffb79cdb34a4aa5","5db89c67ccaaa248028989c52bfa952eafc171d3e48fd15ba5dd0dfd368e1c06","dc4cc5acf9edb14cd9b8659d4a2405eae5d425867d861607f89826ffcb0f5459","fec4304054685c4a25f56b057ae3bab421fa998ca91812ad849c2518b3969288","e8441b85cc6036e40f745de4fd909b98507656d7e3a5762578ec50a03219099a","023c1577f21a7fdd428cc514726483c10039bd65afdf2f3da2b890f74350a073","389a04bfa0b809c33b147f24104d4a60581578da644282931abfff8d5a248679","ea31698b76076d4a2fef47d1c0dbc9df4539abf072e8bd29cefbf65daddaa6c5","1d52fbf97eaf19935edf21543f27455b7102290edc1d1f143fcb7b235196ddd3","60e5282257e1ebd742589a7122ff52aa7d78ef1821027301e84335e71ac19790"],"depth":5,"prev_block_url":"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000001245ac74971793689be7924cd0b031302661e806deb0d","tx_url":"https://api.blockcypher.com/v1/btc/main/txs/","next_txids":"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db?txstart=20\u0026limit=20"}
If you want more data on a particular block, you can use the Block Hash endpoint.
The returned object contains information about the block, including its height, the total amount of satoshis transacted within it, the number of transactions in it, transaction hashes listed in the canonical order in which they appear in the block, and more. For more detail on the data returned, check the Block object.
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}//setting txstart to 1 and limit to 1params:=make(map[string]string)params["txstart"]="1"params["limit"]="1"block,err:=btc.GetBlock(671142,"",params)iferr!=nil{fmt.Println(err)}fmt.Printf("%+v\n",block)}//Result from `go run`://{Hash:00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db Height:671142 Depth:9 Chain:BTC.main Total:{neg:false abs:[2928942845838]} Fees:{neg:false abs:[135268918]} Size:1448143 VirtualSize:998941 Ver:1073725440 Time:2021-02-18 16:01:12 +0000 UTC ReceivedTime:2021-02-18 16:02:17.341 +0000 UTC RelayedBy:68.168.176.51:8333 Bits:386736569 Nonce:3270005482 NumTX:2025 PrevBlock:00000000000000000001245ac74971793689be7924cd0b031302661e806deb0d MerkleRoot:5283c26fb8d64d2284ffda76af6cd584292b76f265932cd121ac16fb475d7a8a TXids:[ce0a8256a459ba14feb48931a2344ff7af3af4f9aa2b5acb795a1b0b9fd8806e] NextTXs:https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000003dc20b868d17121303308f6bba329302e75913f0790db?txstart=2&limit=1}
<?php// Run on console:// php -f .\sample\block-api\BlockHeightEndpoint.php$blockClient=newBlockClient($apiContext);$params=array('txstart'=>1,'limit'=>1,);$block=$blockClient->get('671142',$params);{"hash":"000000000000000000058b0392acad50a141c980a0137fa381eed4bb9da2266b","height":671142,"chain":"BTC.main","total":288801092067,"size":1337178,"vsize":999378,"ver":939515904,"time":"2021-02-16T14:30:47Z","received_time":"2021-02-16T14:30:50.082Z","coinbase_addr":"","relayed_by":"100.19.55.173:8333","bits":386736569,"nonce":3721541004,"n_tx":3238,"prev_block":"00000000000000000007d284fb11be7e6adcc81d05177f05ff5ba6b906f151d2","mrkl_root":"67ebfe25f76df77fe4c46e9474a4bcdaeb71034da6fc3509fdd2c6d0817b9de8","txids":["67f0821545bbfd815d2fc37dd24b945b76dcebb7b78f7dafbe55c5d09418a63e"],"depth":292,"prev_block_url":"https://api.blockcypher.com/v1/btc/main/blocks/00000000000000000007d284fb11be7e6adcc81d05177f05ff5ba6b906f151d2","tx_url":"https://api.blockcypher.com/v1/btc/main/txs/","next_txids":"https://api.blockcypher.com/v1/btc/main/blocks/000000000000000000058b0392acad50a141c980a0137fa381eed4bb9da2266b?txstart=20\u0026limit=20"}
You can also query for information on a block using its height, using the same resource but with a different variable type.
Filters response to only include transaction hashes after txstart in the block.
limit
integer
Filters response to only include a maximum of limit transactions hashes in the block. Maximum value allowed is 500.
BLOCK_HEIGHT is an integer representing the height of the block you're interested in querying, for example:
294322
As above, the returned object contains information about the block, including its hash, the total amount of satoshis transacted within it, the number of transactions in it, transaction hashes listed in the canonical order in which they appear in the block, and more. For more detail on the data returned, check the Block object.
If you're curious about the adoption of upgrade features on a blockchain, you can use this endpoint to get some information about its state on the network. For example, for bip65 on bitcoin, you could check its state via this URL: https://api.blockcypher.com/v1/btc/main/feature/bip65?token=YOURTOKEN. Generally speaking, for bitcoin, this will follow the form of tracking bipXX (where XX = a number), but the list of features we're tracking is always changing.
Address API
BlockCypher's Address API allows you to look up information about public addresses on the blockchain, generate single-use, low-value key pairs with corresponding addresses, help generate multisig addresses, and collect multiple addresses into a single shortcut for address viewing, all based on the coin/chain resource you've selected for your endpoints.
If you're new to blockchains, you can think of public addresses as similar to bank account numbers in a traditional ledger. The biggest differences:
Anyone can generate a public address themselves (through ECDSA in Bitcoin). No single authority is needed to generate new addresses; it's just public-private key cryptography.
Public addresses are significantly more lightweight. Consequently, and unlike traditional bank accounts, you can (and should!) generate new addresses for every transaction.
Addresses can also leverage pay-to-script-hash, which means they can represent exotic things beyond a single private-public key pair; the most prominent example being multi-signature addresses that require n-of-m signatures to spend.
# Full balance>block_cypher.address_balance("1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD")=>{"address"=>"1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD","total_received"=>4433416,"total_sent"=>0,"balance"=>4433416,"unconfirmed_balance"=>0,"final_balance"=>4433416,"n_tx"=>7,"unconfirmed_n_tx"=>0,"final_n_tx"=>7}# Just final balance>block_cypher.address_final_balance("1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD")=>4433416
<?php// Run on console:// php -f .\sample\address-api\AddressBalanceEndpoint.php$addressClient=newAddressClient($apiContext);$addressBalance=$addressClient->getBalance('1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD');{"address":"1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD","total_received":4433416,"total_sent":0,"balance":4433416,"unconfirmed_balance":0,"final_balance":4433416,"n_tx":7,"unconfirmed_n_tx":0,"final_n_tx":7}
The Address Balance Endpoint is the simplest---and fastest---method to get a subset of information on a public address.
If omitWalletAddresses is true and you're querying a Wallet or HDWallet, the response will omit address information (useful to speed up the API call for larger wallets).
ADDRESS is a string representing the public address (or wallet/HD wallet name) you're interested in querying, for example:
1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD
The returned object contains information about the address, including its balance in satoshis and the number of transactions associated with it. The endpoint omits any detailed transaction information, but if that isn't required by your application, then it's the fastest and preferred way to get public address information.
<?php// Run on console:// php -f .\sample\address-api\AddressEndpoint.php$addressClient=newAddressClient($apiContext);$address=$addressClient->get('1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD');{"address":"1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD","total_received":4433416,"total_sent":0,"balance":4433416,"unconfirmed_balance":0,"final_balance":4433416,"n_tx":7,"unconfirmed_n_tx":0,"final_n_tx":7,"txrefs":[{"tx_hash":"14b1052855bbf6561bc4db8aa501762e7cc1e86994dda9e782a6b73b1ce0dc1e","block_height":302013,"tx_input_n":-1,"tx_output_n":0,"value":20213,"ref_balance":4433416,"spent":false,"confirmations":58584,"confirmed":"2014-05-22T03:46:25Z","double_spend":false},...],"tx_url":"https://api.blockcypher.com/v1/btc/main/txs/"}
The default Address Endpoint strikes a balance between speed of response and data on Addresses. It returns more information about an address' transactions than the Address Balance Endpoint but doesn't return full transaction information (like the Address Full Endpoint).
If unspentOnly is true, filters response to only include unspent transaction outputs (UTXOs).
includeScript
bool
If includeScript is true, includes raw script of input or output within returned TXRefs.
includeConfidence
bool
If true, includes the confidence attribute (useful for unconfirmed transactions) within returned TXRefs. For more info about this figure, check the Confidence Factor documentation.
before
integer
Filters response to only include transactions below before height in the blockchain.
after
integer
Filters response to only include transactions above after height in the blockchain.
limit
integer
limit sets the minimum number of returned TXRefs; there can be less if there are less than limit TXRefs associated with this address, but there can be more in the rare case of more TXRefs in the block at the bottom of your call. This ensures paging by block height never misses TXRefs. Defaults to 200, maximum is 2000.
confirmations
integer
If set, only returns the balance and TXRefs that have at least this number of confirmations.
confidence
integer
Filters response to only include TXRefs above confidence in percent; e.g., if this is set to 99, will only return TXRefs with 99% confidence or above (including all confirmed TXRefs). For more detail on confidence, check the Confidence Factor documentation.
omitWalletAddresses
bool
If omitWalletAddresses is true and you're querying a Wallet or HDWallet, the response will omit address information (useful to speed up the API call for larger wallets).
ADDRESS is a string representing the public address (or wallet/HD wallet name) you're interested in querying, for example:
1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD
The returned object contains information about the address, including its balance in satoshis, the number of transactions associated with it, and transaction inputs/outputs in descending order by block height---and if multiple transaction inputs/outputs associated with this address exist within the same block, by descending block index (position in block).
<?php// Run on console:// php -f .\sample\address-api\AddressFullEndpoint.php$addressClient=newAddressClient($apiContext);$fullAddress=$addressClient->getFullAddress('1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD');{"address":"1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD","total_received":4433416,"total_sent":0,"balance":4433416,"unconfirmed_balance":0,"final_balance":4433416,"n_tx":7,"unconfirmed_n_tx":0,"final_n_tx":7,"txs":[{"block_hash":"00000000000000006548ac8dc283c97e8165023dc1fdbbca2eaa75f0143f4a8c","block_height":302013,"hash":"14b1052855bbf6561bc4db8aa501762e7cc1e86994dda9e782a6b73b1ce0dc1e","addresses":["17astdTmG8zzVmry8mV8A7atAr3XefEgRX","1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD"],"total":8835413,"fees":10000,"size":258,"preference":"medium","relayed_by":"","confirmed":"2014-05-22T03:46:25Z","received":"2014-05-22T03:46:25Z","ver":1,"lock_time":0,"double_spend":false,"vin_sz":1,"vout_sz":2,"confirmations":58588,"confidence":1,"inputs":[{"prev_hash":"4cff011ec53022f2ae47197d1a2fd4a6ac2a80139f4d0131c1fed625ed5dc869","output_index":1,"script":"483045022035695e3b237733c70a56286eccd8df41b4d22cd103ed9b2df44010caa3bc71430221008f58461c937e8fe6cc6d37a9aaee3927762cce4565a4c386bbcd9d82915acfc50141047b1d511b8559a2003ca88715bc8331f057fa4ebf11f411142509a8ffd2f2d36d5a5e4b6019d6eb3e16878f24fd8d55676050c28b4bc5e4c44f39245beedae100","output_value":8845413,"sequence":4294967295,"addresses":["17astdTmG8zzVmry8mV8A7atAr3XefEgRX"],"script_type":"pay-to-pubkey-hash"}],"outputs":[{"value":20213,"script":"76a9148629647bd642a2372d846a7660e210c8414f047c88ac","addresses":["1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD"],"script_type":"pay-to-pubkey-hash"},{"value":8815200,"script":"76a9144838f65fc4e06c644423ad0430de11ca5785dcd088ac","spent_by":"582a50f3a756c3261f8f085185e5975a762e239e95a30bcf1a4f2e31e0f834ab","addresses":["17astdTmG8zzVmry8mV8A7atAr3XefEgRX"],"script_type":"pay-to-pubkey-hash"}]},...]}
The Address Full Endpoint returns all information available about a particular address, including an array of complete transactions instead of just transaction inputs and outputs. Unfortunately, because of the amount of data returned, it is the slowest of the address endpoints, but it returns the most detailed data record.
Filters response to only include transactions below before height in the blockchain.
after
integer
Filters response to only include transactions above after height in the blockchain.
limit
integer
limit sets the minimum number of returned TXs; there can be less if there are less than limit TXs associated with this address, but there can also be more in the rare case of more TXs in the block at the bottom of your call. This ensures paging by block height never misses TXs. Defaults to 10, maximum is 50.
txlimit
integer
This filters the TXInputs/TXOutputs within the returned TXs to include a maximum of txlimit items.
confirmations
integer
If set, only returns the balance and TXs that have at least this number of confirmations.
confidence
integer
Filters response to only include TXs above confidence in percent; e.g., if this is set to 99, will only return TXs with 99% confidence or above (including all confirmed TXs). For more detail on confidence, check the Confidence Factor documentation.
legacyaddrs
bool
Litecoin Only. Replaces P2SH prefix with legacy 3 instead of M. Disabled by default.
includeHex
bool
If true, includes hex-encoded raw transaction for each TX; false by default.
includeConfidence
bool
If true, includes the confidence attribute (useful for unconfirmed transactions) within returned TXs. For more info about this figure, check the Confidence Factor documentation.
omitWalletAddresses
bool
If omitWalletAddresses is true and you're querying a Wallet or HDWallet, the response will omit address information (useful to speed up the API call for larger wallets).
ADDRESS is a string representing the public address (or wallet/HD wallet name) you're interested in querying, for example:
1DEP8i3QJCsomS4BSMY2RpU1upv62aGvhD
The returned object contains information about the address, including its balance in satoshis, the number of transactions associated with it, and the corresponding full transaction records in descending order by block height---and if multiple transactions associated with this address exist within the same block, by descending block index (position in block).
# Please use a python library such as https://github.com/sbuss/bitmerchant to securely generate an address client-side
<?php// Run on console:// php -f .\sample\address-api\GenerateAddressEndpoint.php$addressClient=newAddressClient($apiContext);$addressKeyChain=$addressClient->generateAddress();{"private":"3f3cea5a7373011d6f51844bf986abe6950d7a30eaaab247fc951c3ea9f13705","public":"02d1c8ccc7131a3c39b9e7001741f68d339e5d6941caf31fe9f43b15d6cf09dcb9","address":"1rA7AB93qziWzHfTFXn5n3GYJ1mhkG8tn","wif":"KyLdumvGqB86v3D9sKqAMGhNXB1UtYSsxb9deH1nxpooskVF7Rgz"}
The Generate Address endpoint allows you to generate private-public key-pairs along with an associated public address. No information is required with this POST request.
<?php// Run on console:// php -f .\sample\address-api\GenerateMultisigAddressEndpoint.php$addressClient=newAddressClient($apiContext);$pubkeys=array("02c716d071a76cbf0d29c29cacfec76e0ef8116b37389fb7a3e76d6d32cf59f4d3","033ef4d5165637d99b673bcdbb7ead359cee6afd7aaf78d3da9d2392ee4102c8ea","022b8934cc41e76cb4286b9f3ed57e2d27798395b04dd23711981a77dc216df8ca");$addressKeyChain=$addressClient->generateMultisigAddress($pubkeys,'multisig-2-of-3');{"pubkeys":["02c716d071a76cbf0d29c29cacfec76e0ef8116b37389fb7a3e76d6d32cf59f4d3","033ef4d5165637d99b673bcdbb7ead359cee6afd7aaf78d3da9d2392ee4102c8ea","022b8934cc41e76cb4286b9f3ed57e2d27798395b04dd23711981a77dc216df8ca"],"script_type":"multisig-2-of-3","private":"","public":"","address":"3BF1M1PnTge94QewuWh3B8mRVw8U4SVnb4","wif":""}
The Generate Multisig Address Endpoint is a convenience method to help you generate multisig addresses from multiple public keys. After supplying a partially filled-out AddressKeychain object (including only an array of hex-encoded public keys and the script type), the returned object includes the computed public address.
The Wallet API allows you to group multiple addresses under a single name. It only holds public address information and never requires any private keys.
A normal Wallet can be created, deleted, and have addresses added and removed. The Wallet itself can have any custom name as long as it does not start with the standard address prefix (1, 3 or bc1 for Bitcoin Mainnet).
Hierarchical Deterministic (HD) Wallets
We also offer support for HD Wallets, which make it easy to manage multiple addresses under a single name. All HD wallet addresses are derived from a single seed. Please see BIP32 for more background on HD wallets.
HD Wallets can be created, deleted, and have new addresses generated. However, unlike normal Wallets, addresses cannot be removed.
When creating a wallet, one can optionally include one or more "subchain" indexes. These subchains can later be referenced when generating new addresses or sending txs. If none are provided in wallet creation, the wallet will derive & use addresses straight from the given extended pubkey. If no index is given when using the wallet with other APIs, it defaults to using the wallet's first (sub) chain.
In BIP32 notation, the wallet layout is m/0, m/1, ... and m/i/0, m/i/1, ... for each subchain i if the wallet has subchains. For example, the path of the fourth address generated is m/3 for a non-subchain wallet. The path of the fourth address at subchain index two is m/2/3. Note that this is different from the default BIP32 wallet layout.
If you want to use BIP32 default wallet layout you can submit the extended public key of m/0' (which can only be derived from your master private key) with subchain indexes = [0, 1]. Subchain index 0 represents the external chain (of account 0) and will discover all k keypairs that look like: m/0'/0/k. Subchain index 1 represents the internal chain (of account 0) and will discover all k keypairs in m/0'/1/k.
If you want to use BIP 44 layout (for BTC), you can submit the extended public key of m/44'/0'/0'. (which can only be derived from your master private key) with subchain indexes = [0, 1]. Subchain index 0 represents the external chain (of account 0) and will discover all k keypairs in m/44'/0'/0'/0/k. Subchain index 1 represents the internal chain (of account 0) and will discover all k keypairs in m/44'/0'/0'/1/k.
If you want to use BIP 84 layout (for BTC), you can submit the extended public key of m/84'/0'/0'. (which can only be derived from your master private key) with subchain indexes = [0, 1]. Subchain index 0 represents the external chain (of account 0) and will discover all k keypairs in m/84'/0'/0'/0/k. Subchain index 1 represents the internal chain (of account 0) and will discover all k keypairs in m/84'/0'/0'/1/k.
If an address ahead of current addresses listed in an HD Wallet receives a transaction, it will be added, along with any addresses between the new address and the last used one. We limit looking ahead to 20 addresses; if more than 20 addresses are skipped for the next payment to an HD Wallet, it won't be detected/added to the HD Wallet.
Using Wallets
Both HD Wallets and normal Wallets can be leveraged by the Address API, just by using their $NAME instead of $ADDRESS. They can also be used with Events and with the Transaction API. In general, using a wallet instead of an address in an API will have the effect of batching the set of addresses contained in the wallet.
The following code examples should be considered serially; that is to say, the results will appear as if each API call were done sequentially. Also, $NAME is a string representing the name of your wallet, for example:
alice
As you'll see in the examples, if you're using HD Wallets, take care to use the appropriate resource (e.g. /wallets/hd instead of /wallets ).
>block_cypher.wallet_create("alice",["1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"])=>{"token"=>"YOURTOKEN","name"=>"alice","addresses"=>["1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"]}# TODO: ruby hd wallet example
# Regular wallet
>>>fromblockcypherimportcreate_wallet_from_address>>>create_wallet_from_address(wallet_name='alice',address='1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e',api_key='YOUR_TOKEN'){"addresses":["1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"],"name":"alice","token":"YOUR_TOKEN"}# HD wallet
>>>fromblockcypherimportcreate_hd_wallet>>>create_hd_wallet(wallet_name='bob',xpubkey='xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8',api_key='YOUR_TOKEN'){"chains":[{"chain_addresses":[{"address":"1FHz8bpEE5qUZ9XhfjzAbCCwo5bT1HMNAc","path":"m/0"},{"address":"1J8QDN1u7iDMbJktbqXPSrAqruNjkmRFmT","path":"m/1"},{"address":"1MWNKnYfE2LVdvAzFUioF3F3JXFpRfDCQb","path":"m/2"}]}],"extended_public_key":"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8","hd":True,"name":"bob","token":"YOUR_TOKEN"}
<?php// normal wallet// Run on console:// php -f .\sample\wallet-api\CreateWalletEndpoint.php// Create a new instance of Wallet object$wallet=newWallet();$wallet->setName('alice');$wallet->setAddresses(array("1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"));$walletClient=newWalletClient($apiContext);$createdWallet=$walletClient->create($wallet);{"token":"c0afcccdde5081d6429de37d16166ead","name":"alice","addresses":["1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"]}// hd wallet// Run on console:// php -f .\sample\wallet-api\CreateHDWalletEndpoint.php// Create a new instance of HDWallet object$wallet=newHDWallet();$wallet->setName('bob');$wallet->setExtendedPublicKey('xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8');$walletClient=newHDWalletClient($apiContext);$createdWallet=$walletClient->create($wallet);{"token":"c0afcccdde5081d6429de37d16166ead","name":"bob","hd":true,"extended_public_key":"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8","chains":[{"chain_addresses":[{"address":"1FHz8bpEE5qUZ9XhfjzAbCCwo5bT1HMNAc","path":"m/0"},{"address":"1J8QDN1u7iDMbJktbqXPSrAqruNjkmRFmT","path":"m/1"},{"address":"1MWNKnYfE2LVdvAzFUioF3F3JXFpRfDCQb","path":"m/2"}]}]}
This endpoint allows you to create a new wallet, by POSTing a partially filled out Wallet or HDWallet object, depending on the endpoint.
For normal wallets, at minimum, you must include the name attribute and at least one public address in the addresses array.
For HD wallets, at minimum, you must include the name and the extended_public_key attributes. The encoding of the key is documented here. You can optionally include subchain_indexes to initialize the wallet with one or more subchains. If not given, the wallet will derive address straight from the given extended pubkey. See BIP32 for more info.
If successful, it will return the same Wallet or HDWallet object you requested, appended with your user token.
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}walletNames,err:=btc.ListWallets()iferr!=nil{fmt.Println(err)}fmt.Printf("Wallets:%v\n",walletNames)}//Result from `go run`://Wallets: [alice catheryne bob]
<?php//TODO: php examples
Resource
Method
Return Object
/wallets
GET
{"wallet_names":$NAMEARRAY}
This endpoint returns a string array ($NAMEARRAY) of active wallet names (both normal and HD) under the token you queried. You can then query detailed information on individual wallets (via their names) by leveraging the Get Wallet Endpoint.
<?php// normal wallet// Run on console:// php -f .\sample\wallet-api\GetWalletEndpoint.php$walletClient=newWalletClient($apiContext);$wallet=$walletClient->get('alice');{"token":"c0afcccdde5081d6429de37d16166ead","name":"alice","addresses":["1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"]}// hd wallet// Run on console:// php -f .\sample\wallet-api\GetHDWalletEndpoint.php$walletClient=newHDWalletClient($apiContext);$wallet=$walletClient->get('bob');{"token":"c0afcccdde5081d6429de37d16166ead","name":"bob","hd":true,"extended_public_key":"xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8","chains":[{"chain_addresses":[{"address":"1FHz8bpEE5qUZ9XhfjzAbCCwo5bT1HMNAc","path":"m/0"},{"address":"1J8QDN1u7iDMbJktbqXPSrAqruNjkmRFmT","path":"m/1"},{"address":"1MWNKnYfE2LVdvAzFUioF3F3JXFpRfDCQb","path":"m/2"}]}]}
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}//normal walletalice,err:=btc.AddAddrWallet("alice",[]string{"13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j"},false)iferr!=nil{fmt.Println(err)}fmt.Printf("%+v\n",alice)}//Result from `go run`://{Name:alice Addresses:[13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j 1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e]}
<?php// Run on console:// php -f .\sample\wallet-api\AddAddressesToWalletEndpoint.php$walletClient=newWalletClient($apiContext);$addressList=AddressList::fromAddressesArray(array("13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j"));$wallet=$walletClient->addAddresses('alice',$addressList);{"token":"c0afcccdde5081d6429de37d16166ead","name":"alice","addresses":["1jr1rHMthQVMNSYswB9ExSvYn339fWMzn","13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j"]}
If omitWalletAddresses is true, the response will omit address information (useful to speed up the API call for larger wallets).
This endpoint allows you to add public addresses to the $NAME wallet, by POSTing a partially filled out Wallet object. You only need to include the additional addresses in a new addresses array in the object. If successful, it will return the newly modified Wallet, including an up-to-date, complete listing of addresses.
>block_cypher.wallet_get_addr("alice")=>{"addresses"=>["13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j","1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"]}# TODO: ruby hd example
# Regular wallet
>>>fromblockcypherimportget_wallet_addresses>>>get_wallet_addresses(wallet_name='alice',api_key='YOUR_TOKEN'){"addresses":["13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j","1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"]}# HD wallet
>>>fromblockcypherimportget_wallet_addresses>>>get_wallet_addresses(wallet_name='alice',api_key='YOUR_TOKEN',is_hd_wallet=True){"chains":[{"chain_addresses":[{"address":"1FHz8bpEE5qUZ9XhfjzAbCCwo5bT1HMNAc","path":"m/0"},{"address":"1J8QDN1u7iDMbJktbqXPSrAqruNjkmRFmT","path":"m/1"},{"address":"1MWNKnYfE2LVdvAzFUioF3F3JXFpRfDCQb","path":"m/2"}]}]}
<?php// normal wallet// Run on console:// php -f .\sample\wallet-api\WalletAddressesEndpoint.php$walletClient=newWalletClient($apiContext);$addressList=$walletClient->getWalletAddresses('alice');{"addresses":["13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j","1jr1rHMthQVMNSYswB9ExSvYn339fWMzn"]}// hd wallet// Run on console:// php -f .\sample\wallet-api\GetHDWalletAddressesEndpoint.php$walletClient=newHDWalletClient($apiContext);$addressList=$walletClient->getWalletAddresses('bob');{"chains":[{"chain_addresses":[{"address":"1FHz8bpEE5qUZ9XhfjzAbCCwo5bT1HMNAc","path":"m/0"},{"address":"1J8QDN1u7iDMbJktbqXPSrAqruNjkmRFmT","path":"m/1"},{"address":"1MWNKnYfE2LVdvAzFUioF3F3JXFpRfDCQb","path":"m/2"}]}]}
Returns only used addresses if set to true and only unused if false. Only valid on HD wallets.
zerobalance
bool
Returns only addresses with zero balance if set to true and only addresses with non-zero balance if false. Only valid on HD wallets.
This endpoint returns a list of the addresses associated with the $NAME wallet. It returns the addresses in a partially filled out Wallet which you'll find under the addresses attribute. For HD wallets it returns an HDChain object.
Remove Addresses from Wallet Endpoint
#pipe to grep to check status code$ curl -X DELETE -Is https://api.blockcypher.com/v1/btc/main/wallets/alice/addresses?token=USERTOKEN&address=1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e | grep"HTTP/1.1"
HTTP/1.1 204 OK
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}//normal wallet onlyerr:=btc.DeleteAddrWallet("alice",[]string{"1JcX75oraJEmzXXHpDjRctw3BX6qDmFM8e"})iferr!=nil{fmt.Println(err)}else{fmt.Printf("Address deleted")}}//Result from `go run`://Address deleted
<?php// Run on console:// php -f .\sample\wallet-api\RemoveAddressesFromWalletEndpoint.php$walletClient=newWalletClient($apiContext);// List of addresses to be removed from the wallet$addressList=AddressList::fromAddressesArray(array("13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j"));$wallet=$walletClient->removeAddresses('alice',$addressList);{"token":"c0afcccdde5081d6429de37d16166ead","name":"alice","addresses":["1jr1rHMthQVMNSYswB9ExSvYn339fWMzn"]}
Resource
Method
Return Object
/wallets/$NAME/addresses?address=$ADDRESS
DELETE
nil
This endpoint allows you to delete an $ADDRESS associated with the $NAME wallet. As a reminder, you can batch multiple addresses by appending them with semicolons within the $ADDRESS URL parameter. If successful, it will return an HTTP 204 status code with no return object.
# Please use a python library such as https://github.com/blockcypher/blockcypher-python to securely generate an address client-side
<?php// Run on console:// php -f .\sample\wallet-api\GenerateAddressInWalletEndpoint.php$walletClient=newWalletClient($apiContext);$walletGenerateAddressResponse=$walletClient->generateAddress('alice');{"token":"c0afcccdde5081d6429de37d16166ead","name":"alice","addresses":["1jr1rHMthQVMNSYswB9ExSvYn339fWMzn","13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j"],"private":"0d42eb9fa80301aa3a5c4e91d2a5c892b4fb99b10bc1f0d636d46ecba32d37e6","public":"030b4780c12784456291191318b231dcce64c93f8eb211fa78eb7e95663009e414","address":"1GuPv187EEUi3BDypdpMS7cmMuaVpWy6PM","wif":"KwfVLLsRSgSC6pkDLkEmMn8fH5VFceaYT9B58Cu8QHZtZzJvnpYZ"}
Whether or not to generate a p2wpkh bech32 address. Default is false.
This endpoint allows you to generate a new address associated with the $NAME wallet, similar to the Generate Address Endpoint. If successful, it will returned the newly modified Wallet composed with an AddressKeychain.
Only works for regular Wallets; for HD Wallets, use the Derive Address endpoint specified below.
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}//hdwallet onlybob,err:=btc.DeriveAddrHDWallet("bob",map[string]string{"count":"1"})iferr!=nil{fmt.Println(err)}fmt.Printf("Parital HD Wallet: %+v\n",bob)}//Result from `go run`://Partial HD Wallet: {Name: ExtPubKey: SubchainIndexes:[] Chains:[{ChainAddr:[{Address:19urzZsoBNsomSfj68PUUGLXDz261tK5Jo Path:m/3 Public:02c85080e00080aa933f93a2718bba9f01fd6fdc8e4712a155849f5ba588666471}] Index:0}]}
// Run on console:// php -f .\sample\wallet-api\GenerateAddressInHDWalletEndpoint.php$walletClient=newHDWalletClient($apiContext);$hdWalletGenerateAddressResponse=$walletClient->generateAddress('bob');// with subchain_index// Run on console:// php -f .\sample\wallet-api\GenerateAddressInHDWalletWithSubchainIndexEndpoint.php$walletClient=newHDWalletClient($apiContexts['BTC.main']);$params=array('subchain_index'=>1);$hdWalletGenerateAddressResponse=$walletClient->deriveAddress('bob',$params);
Number of addresses to derive. If not set, default is one address.
subchain_index
integer
Derives address(es) on this specific subchain. If not set, address will be generated on the first chain in the HD wallet.
lookahead
boolean
Default to true. If set to false will not try to check the balance of the subsequent addresses. Set to false if this endpoint is too slow.
This endpoint allows you to derive a new address (or multiple addresses) associated with the $NAME HD Wallet. If successful, it will return an HDWalletbut only with the newly derived address(es) represented in its chains field to limit the data transmitted; for the full address list after derivation, you can follow up this API call with the Get Wallet Addresses Endpoint.
Only works for HD Wallets; for regular wallets, use the Generate Address in Wallet endpoint specified above.
Delete Wallet Endpoint
# normal wallet, pipe to grep to check status code
curl -X DELETE -Is https://api.blockcypher.com/v1/btc/main/wallets/alice?token=YOURTOKEN | grep"HTTP/1.1"
HTTP/1.1 204 OK
# hd wallet
curl -X DELETE -Is https://api.blockcypher.com/v1/btc/main/wallets/hd/bob?token=YOURTOKEN | grep"HTTP/1.1"
HTTP/1.1 204 OK
>block_cypher.wallet_delete("alice")=>nil# TODO: Ruby hd wallet example
# Regular wallet
>>>fromblockcypherimportdelete_wallet>>>delete_wallet(wallet_name='alice',api_key='YOUR_TOKEN')True# HD wallet
>>>fromblockcypherimportdelete_wallet>>>delete_wallet(wallet_name='bob',api_key='YOUR_TOKEN',is_hd_wallet=True)True
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}//walleterr:=btc.DeleteWallet("alice")//hdwalleterr=btc.DeleteHDWallet("bob")iferr!=nil{fmt.Println(err)}else{fmt.Println("Alice and Bob Deleted")}}//Result from `go run`://Alice and Bob Deleted
<?php// normal wallet// Run on console:// php -f .\sample\wallet-api\DeleteWalletEndpoint.php$walletClient=newWalletClient($apiContext);$result=$walletClient->delete('alice');// hd wallet// Run on console:// php -f .\sample\wallet-api\DeleteHDWalletEndpoint.php$walletClient=newHDWalletClient($apiContext);$result=$walletClient->delete('bob');
Resource
Method
Return Object
/wallets/$NAME
DELETE
nil
/wallets/hd/$NAME
DELETE
nil
This endpoint deletes the Wallet or HD Wallet with $NAME. If successful, it will return an HTTP 204 status code with no return object.
Transaction API
BlockCypher's Transaction API allows you to look up information about unconfirmed transactions, query transactions based on hash, create and propagate your own transactions, including multisignature transactions, and embed data on the blockchain---all based on the coin/chain resource you've selected for your endpoints.
If you're new to blockchains, the idea of transactions is relatively self-explanatory. Here's what's going on underneath the hood: a transaction takes previous "unspent transaction outputs" (also known as UTXOs) as "transaction inputs" and creates new "locking scripts" on those inputs such that they are "sent" to new addresses (to become new UTXOs). While most of these public addresses are reference points for single private keys that can "unlock" the newly created UTXOs, occasionally they are sent to more exotic addresses through pay-to-script-hash, typically multisignature addresses.
Generally speaking, UTXOs are generated from previous transactions (except for Coinbase inputs).
<?php// Run on console:// php -f .\sample\transaction-api\TransactionHashEndpoint.php$txClient=newTXClient($apiContext);$transaction=$txClient->get('f854aebae95150b379cc1187d848d58225f3c4157fe992bcd166f58bd5063449');{"block_hash":"0000000000000000c504bdea36e531d80...","block_height":293000,"hash":"f854aebae95150b379cc1187d848d58225f3c41...","addresses":["13XXaBufpMvqRqLkyDty1AXqueZHVe6iyy","19YtzZdcfs1V2ZCgyRWo8i2wLT8ND1Tu4L","1BNiazBzCxJacAKo2yL83Wq1VJ18AYzNHy","1GbMfYui17L5m6sAy3L3WXAtf1P32bxJXq","1N2f642sbgCMbNtXFajz9XDACDFnFzdXzV"],"total":70320221545,"fees":0,"size":636,"vsize":636,"preference":"low","relayed_by":"","confirmed":"2014-03-29T01:29:19Z","received":"2014-03-29T01:29:19Z","ver":1,"lock_time":0,"double_spend":false,"vin_sz":4,"vout_sz":1,"confirmations":63171,"inputs":[{"prev_hash":"583910b7bf90ab802e22e5c25a89...","output_index":1,"script":"4830450220504b1ccfddf508422bdd8...","output_value":16450000,"sequence":4294967295,"addresses":["1GbMfYui17L5m6sAy3L3WXAtf1P32bxJXq"],"script_type":"pay-to-pubkey-hash"},...,...,],"outputs":[{"value":70320221545,"script":"76a914e6aad9d712c419ea8febf009a...","spent_by":"35832d6c70b98b54e9a53ab2d5117...","addresses":["1N2f642sbgCMbNtXFajz9XDACDFnFzdXzV"],"script_type":"pay-to-pubkey-hash"}]}
The Transaction Hash Endpoint returns detailed information about a given transaction based on its hash.
Filters TXInputs/TXOutputs, if unset, default is 20.
instart
integer
Filters TX to only include TXInputs from this input index and above.
outstart
integer
Filters TX to only include TXOutputs from this output index and above.
legacyaddrs
bool
Litecoin Only. Replaces P2SH prefix with legacy 3 instead of M. Disabled by default.
includeHex
bool
If true, includes hex-encoded raw transaction; false by default.
includeConfidence
bool
If true, includes the confidence attribute (useful for unconfirmed transactions). For more info about this figure, check the Confidence Factor documentation.
TXHASH is a string representing the hex-encoded transaction hash you're interested in querying, for example:
The returned object contains detailed information about the transaction, including the value transfered, date received, and a full listing of inputs and outputs.
<?php// Run on console:// php -f .\sample\transaction-api\UnconfirmedTransactionsEndpoint.php$txClient=newTXClient($apiContext);$txs=$txClient->getUnconfirmed(array(),$apiContext);[{'received':'2015-06-10T23:10:31.534Z','ver':1,'double_spend':False,'outputs':[{'value':131910000,'addresses':['1Gb4TAU4GD73akvt4V7tg2WdqadcpQSvhH'],'script_type':'pay-to-pubkey-hash','script':'76a914aafae908428a1778d0e76f0dca4cb800f731873e88ac'},...],'block_height':-1,'receive_count':109,'total':131940196,'fees':13754,'inputs':[{'output_value':9467,'sequence':4294967295,'prev_hash':'3c65f3bdec16c55fcedec8159ca8b7decf12393e3a7088febbfacfd752534ee0','script':'47304402207510efc3ff2ed868478ef627c4fd53a27254874e61c1ff1be6fb5221844c08ac02204a8a50c35d3fac8ec0c15f468c98abb629cadf3ac898f7be5e6f464ba9e4fba00121035649100ba29d0b34df8a928c2ed7ab1389d017b4ed206f6df5c212a461a764f2','age':38,'addresses':['1MBuZ5ZxhytsjRZmec5rLr1WhDWm9DgFUJ'],'output_index':1,'script_type':'pay-to-pubkey-hash'},...],'preference':'medium','vout_sz':2,'vin_sz':3,'relayed_by':'167.114.118.213:8333','hash':'97f551c7d200f3acf322160d6ada87830d2ad8d935909630a35a87d61bc8fa74','addresses':['1DLDFKuAWGUJqZoYrevG8bHufuZCjCdSFZ','1Gb4TAU4GD73akvt4V7tg2WdqadcpQSvhH',...]'lock_time':0,'size':521,'vsize':521,'confirmations':0},...]
The Unconfirmed Transactions Endpoint returns an array of the latest transactions relayed by nodes in a blockchain that haven't been included in any blocks.
Maximum number of transactions returned, if unset, default is 10. Maximum is 100.
minValue
integer
Filter transactions that transfer a total above the minimal value provided (in satoshis).
The returned object is an array of transactions that haven't been included in blocks, arranged in reverse chronological order (latest is first, then older transactions follow).
Creating Transactions
Using BlockCypher's API, you can push transactions to blockchains one of two ways:
# Using BlockCypher's Internal Testnet>bc_test=BlockCypher::Api.new(api_token:"YOURTOKEN",currency:BlockCypher::BCY,network:BlockCypher::TEST_NET)=>#<BlockCypher::Api:0x00000001a9ebf0 @api_token="YOURTOKEN", @currency="bcy", @network="test", @version="v1">>txskel=bc_test.transaction_new(["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],100000)=>{"tx"=>{"block_height"=>-1,"hash"=>"2094c09f880f88dea1a1ff3a6e19c6af4892b4b26f8e6315fd76c6ddc369ffbf","addresses"=>["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn","CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],"total"=>3856000,"fees"=>12000,"size"=>119,"vsize"=>119,"preference"=>"high","relayed_by"=>"199.83.221.11","received"=>"2015-06-17T20:41:22.818882286Z","ver"=>1,"lock_time"=>0,"double_spend"=>false,"vin_sz"=>1,"vout_sz"=>2,"confirmations"=>0,"inputs"=>[{"prev_hash"=>"6b1c30cad97df956cfcb47b4cd471bb69112fb726b0fb129575337e3fb9f2c1a","output_index"=>2,"script"=>"","output_value"=>3868000,"sequence"=>4294967295,"addresses"=>["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],"script_type"=>"","age"=>9739}],"outputs"=>[{"value"=>100000,"script"=>"76a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac","addresses"=>["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],"script_type"=>"pay-to-pubkey-hash"},{"value"=>3756000,"script"=>"76a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac","addresses"=>["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],"script_type"=>"pay-to-pubkey-hash"}]},"tosign"=>["c24150bea2d3b50c852d1c5eaccd3b6e286623b516e255f876d2b7c0d93f200b"]}
# Creating transactions manually is very complicated.
# We recommend you look at blockcypher.simple_spend() for a full working example of building a transaction using the blockcypher API, verifying and signing that transactionally locally, and then broadcasting it to the network using blockypher's API
# With blockcypher.simple_spend(), this whole example would look like just the following:
>>>fromblockcypherimportsimple_spend>>>simple_spend(from_privkey='97838249d77bfa65f97be02b63fd1b7bb6a58474c7c22784a0da63993d1c2f90',to_address='C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn',to_satoshis=1000000,coin_symbol='bcy')'7981c7849294648c1e79dd16077a388b808fcf8c20035aec7cc5315b37dacfee'# That said, here it is in parts
>>>fromblockcypherimportcreate_unsigned_tx>>>inputs=[{'address':'CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9'},]>>>outputs=[{'address':'C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn','value':1000000}]>>>unsigned_tx=create_unsigned_tx(inputs=inputs,outputs=outputs,coin_symbol='bcy')>>>unsigned_tx{"tosign":["c55602559d9306c0932da726ceda788bdca7f7b82d989f0c76c99161941f1198","9b3fcf3d94fae6fe0cf4e8a82fa408c5e8c56ee1c03ae88962e3f03879f1ffdb","eb2beed1f015ec88714e1e2335af3a0d8e535397ce52a430f649b4f465677ed0",...,],"tx":{"addresses":["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9","C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],"block_height":-1,"confidence":0,"confirmations":0,"double_spend":False,"fees":142700,"hash":"afceb017a0d280a746ad5ed5c18228e302ebc2aa71ec768454b9a768f73c24c1","inputs":[{"addresses":["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],"age":163376,"output_index":0,"output_value":23455,"prev_hash":"457a538479fb50f3e060702594ef92962c2570d592b8e7c089d7b13fc9b5b3dc","script":"","script_type":"","sequence":4294967295},...,],"lock_time":0,"outputs":[{"addresses":["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],"script":"76a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac","script_type":"pay-to-pubkey-hash","value":1000000},...,],"preference":"high","received":"2015-10-21T19:11:35.774722671Z","relayed_by":"207.38.134.25, 127.0.0.1","size":775,"vsize":775,"total":3773210,"ver":1,"vin_sz":17,"vout_sz":2}}
//this is the same example as below, demonstrates//creating New TXSkels, signing, and Sending TXSkelspackagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){//note the change to BlockCypher Testnetbcy:=gobcy.API{"YOURTOKEN","bcy","test"}//generate two addressesaddr1,err:=bcy.GenAddrKeychain()addr2,err:=bcy.GenAddrKeychain()//use faucet to fund first_,err=bcy.Faucet(addr1,3e5)iferr!=nil{fmt.Println(err)}//Post New TXSkeletonskel,err:=bcy.NewTX(gobcy.TempNewTX(addr1.Address,addr2.Address,*big.NewInt(2e5)),false)//Sign it locallyerr=skel.Sign([]string{addr1.Private})iferr!=nil{fmt.Println(err)}//Send TXSkeletonskel,err=bcy.SendTX(skel)iferr!=nil{fmt.Println(err)}fmt.Printf("%+v\n",skel)}//Result from `go run`://{Trans:{BlockHash: BlockHeight:-1 Hash:fbf755272feac2e82e86c8bd46edcf427d88667737d27557ac0ff51a347b14bc Addresses:[BuDPcfmGXfhkkVkJpNjeofiyEedHnUyJqs BsZhuenEzwAVWJC5KVKj4M4cbuownuwDsN] Total:{neg:false abs:[272700]} Fees:{neg:false abs:[27300]} Size:225 VirtualSize:225 Preference:high RelayedBy:147.253.37.187 Received:2020-09-17 21:16:42.749132419 +0000 UTC Confirmed:0001-01-01 00:00:00 +0000 UTC Confirmations:0 Confidence:0 Ver:1 LockTime:0 DoubleSpend:false DoubleOf: ReceiveCount:0 VinSize:1 VoutSize:2 Hex: DataProtocol: ChangeAddress: NextInputs: NextOutputs: Inputs:[{PrevHash:38776ceecb3b5541e5d4863124a72dc20dc913156075b8c7f09e1435cfaded84 OutputIndex:0 OutputValue:300000 Addresses:[BsZhuenEzwAVWJC5KVKj4M4cbuownuwDsN] Sequence:4294967295 ScriptType:pay-to-pubkey-hash Script:47304402200d144dad3ca80337d33d4ab4622c2e74e97be366c3f8f752d7835dedc7a5b39902202b2ddb1b46cc82040e0821f7f6e446c8a186c77a726dfc73509ed1727deb787e0121020c78f0b849ba80d7ad91e0fac7943965380582e751376721f7180c13163ba711 Age:0 WalletName:}] Outputs:[{SpentBy: Value:{neg:false abs:[200000]} Addresses:[BuDPcfmGXfhkkVkJpNjeofiyEedHnUyJqs] ScriptType:pay-to-pubkey-hash Script:76a91416e75d6b264c4643a76bb21ead74d3a7aefce49288ac DataHex: DataString:} {SpentBy: Value:{neg:false abs:[72700]} Addresses:[BsZhuenEzwAVWJC5KVKj4M4cbuownuwDsN] ScriptType:pay-to-pubkey-hash Script:76a91404ceb3e125b65c12c6bb13e20137e8d0bcefb35288ac DataHex: DataString:}]} ToSign:[] Signatures:[] PubKeys:[] ToSignTX:[] Errors:[]}
<?php// Run on console:// php -f .\sample\transaction-api\NewTransactionEndpoint.php// Create a new instance of Transaction object$tx=newTransaction();// Tx inputs$input=new\BlockCypher\Api\Input();$input->addAddress("C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm");$tx->addInput($input);// Tx outputs$output=new\BlockCypher\Api\Output();$output->addAddress("C4MYFr4EAdqEeUKxTnPUF3d3whWcPMz1Fi");$tx->addOutput($output);// Tx amount$output->setValue(1000);// Satoshis$txClient=newTXClient($apiContext);$txSkeleton=$txClient->create($tx);{"tx":{"block_height":-1,"hash":"edb785c310ea58c70245c9a89130efca8fb0a02d4bee47b18542986e7bf95806","addresses":["C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm","C4MYFr4EAdqEeUKxTnPUF3d3whWcPMz1Fi"],"total":5420100,"fees":12000,"size":119,"vsize":119,"preference":"high","relayed_by":"88.7.90.149","received":"2015-06-17T10:23:02.475392139Z","ver":1,"lock_time":0,"double_spend":false,"vin_sz":1,"vout_sz":2,"confirmations":0,"inputs":[{"prev_hash":"64e39fa5322ee604ad548dc5d4ae1a61b0a575278724d0df7e53dd334f5f13e3","output_index":0,"script":"","output_value":5432100,"sequence":4294967295,"addresses":["C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm"],"script_type":"","age":0}],"outputs":[{"value":1000,"script":"76a9147b2b09ad46d95e177df6969a275db321c66cecf388ac","addresses":["C4MYFr4EAdqEeUKxTnPUF3d3whWcPMz1Fi"],"script_type":"pay-to-pubkey-hash"},{"value":5419100,"script":"76a9148c6f28c814116f1ae3d0940b2fb05a68a9507e8a88ac","addresses":["C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm"],"script_type":"pay-to-pubkey-hash"}]},"tosign":["770af2c9a9b7b8b1998e36d4c1ce2b8fa3b9d4d6575679a513722d9f478177d2"]}
To use BlockCypher's two-endpoint transaction creation tool, first you need to provide the input address(es), output address, and value to transfer (in satoshis). Provide this in a partially-filled out TX request object.
If true, includes tosign_tx array in TXSkeleton, useful for validating data to sign; false by default.
As you can see from the code example, you only need to provide a single public address within the addresses array of both the input and output of your TX request object. You also need to fill in the value with the amount you'd like to transfer from one address to another.
If you'd like, you can even use a Wallet instead of addresses as your input. You just need to use two non-standard fields (your wallet_name and wallet_token) within the inputs array in your transaction, instead of addresses:
While this particular usage will differ between client libraries, the result is the same: the addresses within your wallet will be used as the inputs, as if all of them had been placed within the addresses array.
As a return object, you'll receive a TXSkeleton containing a slightly-more complete TX alongside data you need to sign in the tosign array. You'll need this object for the next steps of the transaction creation process.
Validating the Data to Sign
For the extra cautious, you can protect yourself from a potential malicious attack on BlockCypher by validating the data we're asking you to sign. Unfortunately, it's impossible to do so directly, as pre-signed signature data is hashed twice using SHA256. To get around this, set the includeToSignTx URL flag to true. The optional tosign_tx array will be returned within the TXSkeleton, which you can use in the following way:
Hashing the hex-encoded string twice using SHA256 should give you back the corresponding tosign data.
Decoding the hex-encoded string using our /txs/decode endpoint (or an independent, client-side source) should give you the output addresses and amounts that match your work-in-progress transaction.
# next, you sign the data returned in the tosign array locally# here we're using our signer tool (https://github.com/blockcypher/btcutils/tree/master/signer), but any ECDSA secp256k1 signing tool should work# $PRIVATEKEY here is a hex-encoded private key corresponding to the input from address CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9
./signer 32b5ea64c253b6b466366647458cfd60de9cd29d7dc542293aa0b8b7300cd827 $PRIVATEKEY
3045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca
// next, you sign the data returned in the tosign array locally// here we're using bitcoinjs built to expose bigi, buffer, and require// you can get bitcoin.js here:// http://bitcoinjs.org/varbitcoin=require("bitcoinjs-lib");varsecp=require('tiny-secp256k1');varecfacory=require('ecpair');varECPair=ecfacory.ECPairFactory(secp);constkeyBuffer=Buffer.from(my_hex_private_key,'hex')varkeys=ECPair.fromPrivateKey(keyBuffer)varnewtx={inputs:[{addresses:['CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9']}],outputs:[{addresses:['C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn'],value:100000}]};// calling the new endpoint, same as above$.post('https://api.blockcypher.com/v1/bcy/test/txs/new',JSON.stringify(newtx)).then(function(tmptx){// signing each of the hex-encoded string required to finalize the transactiontmptx.pubkeys=[];tmptx.signatures=tmptx.tosign.map(function(tosign,n){tmptx.pubkeys.push(keys.publicKey.toString('hex'));returnbitcoin.script.signature.encode(keys.sign(Buffer.from(tosign,"hex")),0x01,).toString("hex").slice(0,-2);});// sending back the transaction with all the signatures to broadcast$.post('https://api.blockcypher.com/v1/bcy/test/txs/send',JSON.stringify(tmptx)).done(function(finaltx){console.log(finaltx);}).fail(function(xhr){console.log(xhr.responseText);});});
>>>fromblockcypherimportmake_tx_signatures# Using our same unsigned_tx as before, iterate through unsigned_tx['tx']['inputs'] to find each address in order.
# Include duplicates as many times as they may appear:
>>>privkey_list=['privkeyhex1','privkeyhex2',...]>>>pubkey_list=['pubkeyhex1','pubkeyhex2',,,,]>>>tx_signatures=make_tx_signatures(txs_to_sign=unsigned_tx['tosign'],privkey_list=privkey_list,pubkey_list=pubkey_list)
# Signing is handled by our SDK in the next step
//signing handled in both examples
<?php// Sign the transaction// Private key for address: C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm$privateKeys=array("2c2cc015519b79782bd9c5af66f442e808f573714e3c4dc6df7d79c183963cff");$txSkeleton=$txClient->sign($txSkeleton,$privateKeys);
Locally Sign Your Transaction
With your TXSkeleton returned from the New Transaction Endpoint, you now need to use your private key(s) to sign the data provided in the tosign array.
Digital signing can be a difficult process, and is where the majority of issues arise when dealing with cryptocurrency transactions. We are working on integrating client-side signing solutions into our libraries to make this process easier. You can read more about signing here. In the mean time, if you want to experiment with client-side signing, consider using our signer tool.
# the request body is truncated because it's huge, but it's the same as the returned object from above plus the signatures and public keys# remember, still using bcy/test instead of btc/main
curl -d'{"tx": {...}, "tosign": [ "32b5ea64c253b6b466366647458cfd60de9cd29d7dc542293aa0b8b7300cd827" ], "signatures": [ "3045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca" ], "pubkeys": [ "02152e2bb5b273561ece7bbe8b1df51a4c44f5ab0bc940c105045e2cc77e618044" ] }' https://api.blockcypher.com/v1/bcy/test/txs/send?token=YOURTOKEN
{"tx": {"block_height": -1,
"hash": "4e6dfb1415b4fba5bd257c129847c70fbd4e45e41828079c4a282680528f3a50",
"addresses": ["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9",
"C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],
"total": 4988000,
"fees": 12000,
"size": 226,
"vsize": 226,
"preference": "high",
...,
"confirmations": 0,
"inputs": [{"prev_hash": "c8ea8b221580ebb2f1cabc8b40797bffec742b97c82a329df96d93121db43519",
"output_value": 5000000,
"addresses": ["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],
"script": "483045022100921fc36b911094280f...",
"script_type": "pay-to-pubkey-hash",
...
}],
"outputs": [{"value": 1000000,
"script": "76a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac",
"addresses": ["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],
"script_type": "pay-to-pubkey-hash"},
{"value": 3988000,
"script": "76a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac",
"addresses": ["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],
"script_type": "pay-to-pubkey-hash"}]},
"tosign": [""]}
// this shows just the last step of sending your transaction, see the signing section// for the fully integrated sample// the request body is truncated because it's huge, but it's the same as the returned// object from calling the new endpoint plus the signatures and public keys added in the// signing sectionvarsendtx={tx:{...},tosign:["32b5ea64c253b6b466366647458cfd60de9cd29d7dc542293aa0b8b7300cd827"],signatures:["3045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca"],pubkeys:["02152e2bb5b273561ece7bbe8b1df51a4c44f5ab0bc940c105045e2cc77e618044"]};$.post('https://api.blockcypher.com/v1/bcy/test/txs/send',JSON.stringify(sendtx)).then(function(d){console.log(d)});>{>"tx":{>"block_height":-1,>"hash":"4e6dfb1415b4fba5bd257c129847c70fbd4e45e41828079c4a282680528f3a50",>"addresses":[>"CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9",>"C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn">],>"total":4988000,>"fees":12000,>"size":226,>"vsize":226,>"preference":"high",>"relayed_by":"73.162.198.68",>"received":"2015-05-22T04:38:57.470017042Z",>"ver":1,>"lock_time":0,>"double_spend":false,>"vin_sz":1,>"vout_sz":2,>"confirmations":0,>"inputs":[>{>"prev_hash":"c8ea8b221580ebb2f1cabc8b40797bffec742b97c82a329df96d93121db43519",>"output_index":0,>"script":"483045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca012102152e2bb5b273561ece7bbe8b1df51a4c44f5ab0bc940c105045e2cc77e618044",>"output_value":5000000,>"sequence":4294967295,>"addresses":[>"CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9">],>"script_type":"pay-to-pubkey-hash",>"age":546>}>],>"outputs":[>{>"value":1000000,>"script":"76a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac",>"addresses":[>"C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn">],>"script_type":"pay-to-pubkey-hash">},>{>"value":3988000,>"script":"76a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac",>"addresses":[>"CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9">],>"script_type":"pay-to-pubkey-hash">}>]>},>"tosign":[>"">]>}
<?php// Send the transaction$txSkeleton=$txClient->send($txSkeleton);{"tx":{"block_height":-1,"hash":"edb785c310ea58c70245c9a89130efca8fb0a02d4bee47b18542986e7bf95806","addresses":["C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm","C4MYFr4EAdqEeUKxTnPUF3d3whWcPMz1Fi"],"total":5420100,"fees":12000,"size":119,"vsize":119,"preference":"high","relayed_by":"88.7.90.149","received":"2015-06-17T10:23:02.475392139Z","ver":1,"lock_time":0,"double_spend":false,"vin_sz":1,"vout_sz":2,"confirmations":0,"inputs":[{"prev_hash":"64e39fa5322ee604ad548dc5d4ae1a61b0a575278724d0df7e53dd334f5f13e3","output_index":0,"script":"","output_value":5432100,"sequence":4294967295,"addresses":["C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm"],"script_type":"","age":0}],"outputs":[{"value":1000,"script":"76a9147b2b09ad46d95e177df6969a275db321c66cecf388ac","addresses":["C4MYFr4EAdqEeUKxTnPUF3d3whWcPMz1Fi"],"script_type":"pay-to-pubkey-hash"},{"value":5419100,"script":"76a9148c6f28c814116f1ae3d0940b2fb05a68a9507e8a88ac","addresses":["C5vqMGme4FThKnCY44gx1PLgWr86uxRbDm"],"script_type":"pay-to-pubkey-hash"}]},"tosign":[]}
Send Transaction Endpoint
Once you've finished signing the tosign array locally, put that (hex-encoded) data into the signatures array of the TXSkeleton. You also need to include the corresponding (hex-encoded) public key(s) in the pubkeys array, in the order of the addresses/inputs provided. Signature and public key order matters, so make sure they are returned in the same order as the inputs you provided.
If the transaction was successful, you'll receive a TXSkeleton with the completed TX (which contains its final hash) and an HTTP Status Code 201.
Dealing with Errors
Signing and creating transactions can be one of the trickiest parts of using blockchains in your applications. Consequently, when an error is encountered when Creating Transactions, we send back an HTTP Status Code 400 alongside a descriptive array of errors within the TXSkeleton.
Customizing Transaction Requests
# here are some example request objects for `/txs/new`# simplest posssible case, with input address, output address and value'{
"inputs":
[{"addresses": ["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"]}],
"outputs":
[{"addresses": ["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"], "value": 1000000}]
}'# let's add confirmation field to only allow UTXOs, and set fee preference to medium'{
"inputs":
[{"addresses": ["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"]}],
"outputs":
[{"addresses": ["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"], "value": 1000000}],
"confirmations": 1,
"preference": "medium"
}'# instead of providing an address, let's specify a particular UTXO via prev_hash and output_index, and add a different change_address'{
"inputs":
[{"prev_hash":"a238c817bea2d54dad4cdde38a1cfeb2aa5592313bc49514f3cd0d9db71c69c8", "output_index":0}],
"outputs":
[{"addresses": ["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"], "value": 1000000}],
"confirmations": 1,
"preference": "medium",
"change_address": "CFr99841LyMkyX5ZTGepY58rjXJhyNGXHf"
}'
While we demonstrated the simplest use of our two-endpoint process to create transactions, you can have finer-grain control by modifying the TX request object before sending to /txs/new.
By default, we allow unconfirmed UTXOs as inputs when creating transactions. If you only want to allow confirmed UTXOs, set the confirmations value in your TX request object to 1.
Instead of providing addresses, you can use prev_hash and output_index within the inputs array of your request object, in which case, we'll use the inputs as provided and not attempt to generate them from a list of addresses. We will compute change and fees the same way.
BlockCypher will set the change address to the first transaction input/address listed in the transaction. To redirect this default behavior, you can set an optional change_address field within the TX request object.
Fees in cryptocurrencies can be complex. We provide 2 different ways for you to control the fees included in your transactions:
Set the preference property in your TX request object to "high", "medium", or "low". This will calculate and include appropriate fees for your transaction to be included in the next 1-2 blocks, 3-6 blocks or 7 or more blocks respectively. You can see the explicit estimates per kilobyte for these high, medium, and low ranges by calling your base resource through the Chain Endpoint. The default fee calculation is based on a "high" preference. A preference set to "zero" will set no fee.
Manually set the fee to a desired amount by setting the fees property in your TX request object. Note that a fee too low may result in an error for some transactions that would require it.
To learn more about fees, bitcoinfees.com is a good resource.
For even more control, you can also change the script_type in the outputs of your partially filled TX. You'll notice this used to powerful effect in the section on Multisig Transactions. These are the possible script types:
pay-to-pubkey-hash (most common transaction transferring to a public key hash, and the default behavior if no out)
pay-to-multi-pubkey-hash (multi-signatures transaction, now actually less used than pay-to-script-hash for this purpose)
pay-to-pubkey (used for mining transactions)
pay-to-script-hash (used for transactions relying on arbitrary scripts, now used primarily for multi-sig transactions)
multisig-m-of-n (not present in blockchain, but used by BlockCypher to construct P2SH multisig transactions; see Multisig Transactions for more info)
null-data (sometimes called op-return; used to embed small chunks of data in the blockchain)
empty (no script present, mostly used for mining transaction inputs)
<?php// Run on console:// php -f .\sample\transaction-api\PushRawTransactionEndpoint.php$txClient=newTXClient($apiContext);$hexRawTx="01000000011935b41d12936df99d322ac8972b74ecff7b79408bbccaf1b2eb8015228beac8000000006b483045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca012102152e2bb5b273561ece7bbe8b1df51a4c44f5ab0bc940c105045e2cc77e618044ffffffff0240420f00000000001976a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac20da3c00000000001976a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac00000000";$tx=$txClient->push($hexRawTx);{"block_height":-1,"hash":"4e6dfb1415b4fba5bd257c129847c70fbd4e45e41828079c4a282680528f3a50","addresses":["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9","C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],"total":4988000,"fees":12000,"size":226,"vsize":226,"preference":"high","relayed_by":"73.162.198.68","received":"2015-05-22T05:10:00.305308666Z","ver":1,"lock_time":0,"double_spend":false,"vin_sz":1,"vout_sz":2,"confirmations":0,"inputs":[{"prev_hash":"c8ea8b221580ebb2f1cabc8b40797bffec742b97c82a329df96d93121db43519","output_index":0,"script":"483045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca012102152e2bb5b273561ece7bbe8b1df51a4c44f5ab0bc940c105045e2cc77e618044","output_value":5000000,"sequence":4294967295,"addresses":["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],"script_type":"pay-to-pubkey-hash","age":576}],"outputs":[{"value":1000000,"script":"76a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac","addresses":["C1rGdt7QEPGiwPMFhNKNhHmyoWpa5X92pn"],"script_type":"pay-to-pubkey-hash"},{"value":3988000,"script":"76a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac","addresses":["CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9"],"script_type":"pay-to-pubkey-hash"}]}
If you'd prefer to use your own transaction library instead of the recommended path of our two-endpoint transaction generation we're still happy to help you propagate your raw transactions. Simply send your raw hex-encoded transaction to this endpoint and we'll leverage our huge network of nodes to propagate your transaction faster than anywhere else.
If it succeeds, you'll receive a decoded TX object and an HTTP Status Code 201. If you'd like, you can use the decoded transaction hash alongside an Event to track its progress in the network.
<?php// Run on console:// php -f .\sample\transaction-api\DecodeRawTransactionEndpoint.php$txClient=newTXClient($apiContext);$hexRawTx="01000000011935b41d12936df99d322ac8972b74ecff7b79408bbccaf1b2eb8015228beac8000000006b483045022100921fc36b911094280f07d8504a80fbab9b823a25f102e2bc69b14bcd369dfc7902200d07067d47f040e724b556e5bc3061af132d5a47bd96e901429d53c41e0f8cca012102152e2bb5b273561ece7bbe8b1df51a4c44f5ab0bc940c105045e2cc77e618044ffffffff0240420f00000000001976a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac20da3c00000000001976a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac00000000";$tx=$txClient->decode($hexRawTx);{"block_height":-1,"hash":"4e6dfb1415b4fba5bd257c129847c70fbd4e45e41828079c4a282680528f3a50","addresses":["1NsbjF7mCvxa9sdCwRyeZ8qqvWMWuAyjtg","19iz3x4d4Wm4rgav33KmbuRjots6r1K9Wg"],"total":4988000,"fees":0,"size":226,"vsize":226,"preference":"low","relayed_by":"","received":"0001-01-01T00:00:00Z","ver":1,"lock_time":0,"double_spend":false,"vin_sz":1,"vout_sz":2,"confirmations":0,"inputs":[{"prev_hash":"c8ea8b221580ebb2f1cabc8b40797bffec742b97c82a329df96d93121db43519","output_index":0,"script":"483045022100921fc36b9110942...44f5ab0bc940c105045e2cc77e618044","output_value":0,"sequence":4294967295,"script_type":"empty","age":0}],"outputs":[{"value":1000000,"script":"76a9145fb1af31edd2aa5a2bbaa24f6043d6ec31f7e63288ac","addresses":["19iz3x4d4Wm4rgav33KmbuRjots6r1K9Wg"],"script_type":"pay-to-pubkey-hash"},{"value":3988000,"script":"76a914efec6de6c253e657a9d5506a78ee48d89762fb3188ac","addresses":["1NsbjF7mCvxa9sdCwRyeZ8qqvWMWuAyjtg"],"script_type":"pay-to-pubkey-hash"}]}
We also offer the ability to decode raw transactions without sending propagating them to the network; perhaps you want to double-check another client library or confirm that another service is sending proper transactions.
This endpoint allows you to decode the tosign_tx only in the case of the spending of a native segwit input (P2WPKH).
This allows you to double check the which input you are spending and the value transfered.
# Create a custom payload, then use the function:# BlockCypher.transaction_new_custom(payload)# Sign your data in the returned TXSkeleton, then use:# BlockCypher.transaction_send_custom(your_signed_tx_skeleton)require'JSON'payload=JSON.parse('{ "inputs": [{"addresses": [sourceAddr]}],
"outputs": [{
"addresses" : [pubkey1, pubkey2, pubkey3],
"script_type" : "multisig-2-of-3",
"value" : 250000
}]
}')
packagemainimport"github.com/blockcypher/gobcy"funcmain(){//note the change to BlockCypher Testnetbcy:=gobcy.API{"YOURTOKEN","bcy","test"}//use TempMultiTX to set up multisigtemptx:=gobcy.TempMultiTX("sourceAddr","",25000,2,[]string{"pubkey1","pubkey2","pubkey3"})//Then follow the New/Send two-step process with this temptx as the input}
<?php// Run on console:// php -f .\sample\transaction-api\CreateTxToFundMultisigAddrWithBuilderEndpoint.php// Builder classes are optional, see CreateTxToFundMultisigAddrEndpoint.php to see a sample using only base API classes.$input=TXInputBuilder::aTXInput()->addAddress("n3D2YXwvpoPg8FhcWpzJiS3SvKKGD8AXZ4")->build();$output=TXOutputBuilder::aTXOutput()->withScryptType("multisig-2-of-3")->withValue(1000)->addAddress("03798be8162d7d6bc5c4e3b236100fcc0dfee899130f84c97d3a49faf83450fd81")->addAddress("03dd9f1d4a39951013b4305bf61887ada66439ab84a9a2f8aca9dc736041f815f1")->addAddress("03c8e6e99c1d0b42120d5cf40c963e5e8048fd2d2a184758784a041a9d101f1f02")->build();$tx=TXBuilder::aTX()->addTXInput($input)->addTXOutput($output)->build();$txClient=newTXClient($apiContext);$txSkeleton=$txClient->create($tx);
Multisignature transactions are made simple by the method described in the Creating Transactions section, but they deserve special mention. In order to use them, you first need to fund a multisignature address. You use the /txs/new endpoint as before, but instead of the outputsaddresses array containing public addresses, it instead contains the public keys associated with the new address. In addition, you must select a script_type of mutlisig-n-of-m, where n and m are numbers (e.g., multisig-2-of-3). The code example demonstrates how the partially filled TX request object would appear.
After you've set up your request object, you send to /txs/new and receive a partially filled TXSkeleton as before, but with data to sign from the source address. Sign this data and include the public key(s) of the source address---as demonstrated in the Creating Transactions---then send along to the /txs/send endpoint. If it returns with an HTTP Status Code 201, then your multisignature address (via a pay-to-script-hash address) is funded.
# Create a custom payload, then use the function:# BlockCypher.transaction_new_custom(payload)# Sign your data in the returned TXSkeleton, then use:# BlockCypher.transaction_send_custom(your_signed_tx_skeleton)require'JSON'payload=JSON.parse('{ "inputs": [{
"addresses" : [pubkey1, pubkey2, pubkey3],
"script_type" : "multisig-2-of-3"
}],
"outputs": [{
"addresses" : [destAddr],
"value" : 150000
}] }')
packagemainimport"github.com/blockcypher/gobcy"funcmain(){//note the change to BlockCypher Testnetbcy:=gobcy.API{"YOURTOKEN","bcy","test"}//use TempMultiTX to set up multisigtemptx:=gobcy.TempMultiTX("","destAddr",25000,2,[]string{"pubkey1","pubkey2","pubkey3"})//Then follow the New/Send two-step process with this temptx as the input}
<?php// Run on console:// php -f .\sample\transaction-api\CreateTxToSpendMultisigFundsWithBuilderEndpoint.php// Builder classes are optional, see CreateTxToSpendMultisigFunds.php to see a sample using only base API classes.$input=TXInputBuilder::aTXInput()->addAddress("03798be8162d7d6bc5c4e3b236100fcc0dfee899130f84c97d3a49faf83450fd81")->addAddress("03dd9f1d4a39951013b4305bf61887ada66439ab84a9a2f8aca9dc736041f815f1")->addAddress("03c8e6e99c1d0b42120d5cf40c963e5e8048fd2d2a184758784a041a9d101f1f02")->withScryptType("multisig-2-of-3")->build();$output=TXOutputBuilder::aTXOutput()->addAddress("n3D2YXwvpoPg8FhcWpzJiS3SvKKGD8AXZ4")->withValue(1000)->build();$tx=TXBuilder::aTX()->addTXInput($input)->addTXOutput($output)->build();$txClient=newTXClient($apiContext);$txSkeleton=$txClient->create($tx);
Once funded, you might want to programmatically spend the money in the address at some point. Here the process is similar, but with the inputs and outputs reversed. As you can see in the code sample, you need to provide the public keys within the inputsaddresses array, and the corresponding script_type of multisig-n-of-m (e.g., multisig-2-of-3). Then you follow the same process of sending to /txs/new and getting an array of data to be signed.
Each party can send their signed data individually to /txs/send and we can correlate the signatures to the public keys; once we have enough signatures we'll propagate the transaction. Or you can send all needed signatures alongside ordered public keys with a single call to /txs/send.
If you send all signatures in a single call, and you're spending inputs locked by a multisig-n-of-mscript_type, remember that you'll need n signatures for every element in the TXSkeleton'stosign array. For example, let's say /txs/new returns two elements in the tosign array, corresponding to two multisig-2-of-3 inputs locked by pubkey1, pubkey2, and pubkey3:
{...,"tosign":[data1,data2],...}
Then you'd need to return each piece of data signed twice, preserving order between signatures and pubkeys, resulting in four elements for the signatures and pubkeys arrays:
By operating a well-connected node, we collect a lot of information about how transactions propagate; for example, our Confidence Factor relies on this connectivity. With this endpoint, you can leverage our connectivity to get an approximation of a transaction's location of origin.
Resource
Method
Return Object
/txs/$TXHASH/propagation
GET
Described Below
TXHASH is a string representing the hex-encoded transaction hash you're interested in querying for propagation information. The return object is described below:
Attribute
Type
Description
transaction
string
The hash of the transaction you queried.
first_location
Object
An object containing latitude and longitudefloats representing the first location to broadcast this transaction to BlockCypher.
first_city
string
Optional The name of the city closest to the first_location. If no nearby city can be found, this is not returned.
first_country
string
The name of the country containing the first_location.
aggregated_origin
Object
An object containing latitude and longitudefloats representing BlockCypher's best guess of likely origin of this transaction, based on the radius of the smallest circle containing the first peer from which we detect this transaction, the average of the first five peers, and the average of the first ten peers.
aggregated_origin_radius
integer
The radius (in meters) of the smallest circle containing the first peer from which we detect this transaction, the average of the first five peers, and the average of the first ten peers. In a general sense, this represents an approximate confidence interval in our calculated aggregated_origin; the smaller the radius, the more confidence in our aggregated_origin assessment.
The timestamp when BlockCypher first received this transaction.
Transaction Propagation WebSocket
You can get a live view of unconfirmed transaction propagation analysis on Bitcoin by connecting to our Transaction Propagation WebSocket, at the following address:
As soon as an unconfirmed transaction hits 10 peers, we send the object described above through this WebSocket. For more WebSocket implementation details, check Using WebSockets.
Confidence Factor
One of the things that makes BlockCypher's API uniquely powerful is our ability to accurately predict the likelihood of an attempted double-spend succeeding against a transaction; this percentage probability is optionally included within the confidence attribute on any unconfirmed transaction returned by the Transaction Hash Endpoint when using the includeConfidence flag, in addition to the explicit Transaction Confidence Endpoint detailed below.
So what does that confidence attribute actually mean? In simpler terms, if an unconfirmed transaction returns a confidence factor of 99.9%, then our data says there's a 0.1% chance that an attempted double-spend will succeed. By design, we're conservative. Even when we return 90% confidence, the likelihood of a successful double-spend is significantly lower than 10%.
As you may have gathered from the frequency of links to this feature in these docs, we're exceptionally proud of the work we've done to build this feature and provide it to our users. And that pride extends to our own confidence in our confidence product. We've leveraged this product internally on a major feature: our live block explorer visually shows confidence intervals on unconfirmed transactions directly. Check out a live view of bitcoin and click on one of the most recent unconfirmed transactions. Make sure you pick a very recent transaction: our confidence interval rapidly approaches 99% so quickly that you might miss it!
How does it work?
There are a host of factors that go into our confidence calculation, but you can broadly organize them into two categories. The shape of transactions refers to aspects of transactions that don't vary with time (time-invariant) in our model. The behavior of transactions refers to aspects of transactions that do vary with time (time-variant) in our model.
On the shape side of our model, we ask a number of questions about a transaction: How is it structured? What are its inputs and outputs? What's its signature type? Broadly speaking, without knowing anything about the network, does it look like this transaction will be confirmed soon?
The behavior part of our model primarily focuses on how a transaction propagates through the network. In order to model this correctly, you need both a great connection to the network and a lot of past data, which we have. As BlockCypher pools resources for many users, we're always connected to a statistically significant number of nodes on the network---we target anywhere between 10 to 20% of the active nodes on any given blockchain---and offer connections in return. By monitoring transaction propagation, the number of nodes that have received it, and how quickly they received it, we can calculate its probability to be the "winning" transaction at any given point in time, if a double-spend was attempted. (As an aside, you can always see if a double spend was attempted by checking the double_spend and double_spend_tx attributes on an unconfirmed transaction)
The result is a robust and reliable metric for judging unconfirmed transaction confidence, especially when used in concert with webhooks and websockets. Our work here is based on several public research results in addition to our own in-depth follow-up research, which you can read about here. We are constantly improving our confidence model, and we always publish our findings when we do.
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}//querying a recent TX hash detected on BTC networkconf,err:=btc.GetTXConf("bb01beea75683be16b5d59dd3e084d167f41a6866b6880b3070eefff392fdd2a")iferr!=nil{fmt.Println(err)}fmt.Printf("%+v\n",conf)}//Result from `go run`://{Age:21112 ReceiveCount:756 Confidence:0.9995223691726662 TXHash:bb01beea75683be16b5d59dd3e084d167f41a6866b6880b3070eefff392fdd2a}
<?php// Run on console:// php -f .\sample\confidence-factor\TransactionConfidenceEndpoint.php$txClient=newTXClient($apiContext);$txConfidence=$txClient->getConfidence('43fa951e1bea87c282f6725cf8bdc08bb48761396c3af8dd5a41a085ab62acc9');{"age_millis":2188284017,"receive_count":-1,"confidence":1,"txhash":"43fa951e1bea87c282f6725cf8bdc08bb48761396c3af8dd5a41a085ab62acc9","txurl":"https://api.blockcypher.com/v1/btc/main/txs/43fa951e1bea87c282f6725cf8bdc08bb48761396c3af8dd5a41a085ab62acc9"}
The returned TXConfidence object contains the all-important confidence percentage, receive count and more.
You can find an unconfirmed transaction hash from our block explorer here.
Metadata API
Cryptocurrency addresses, transactions, and blocks are extremely powerful, but the labels they employ can be...cryptic. That's why we have a Metadata API, allowing both public and private key-value storage against addresses, transactions, and blocks.
Private vs Public Metadata
The Metadata API supports both public and private key-value storage. In both cases, setting metadata requires use of a token (if you haven't already, you can register for one here). Public metadata is immutable; once set, it cannot be modified or deleted. If you accidentally set public metadata and need it deleted, contact us. Also, as implied by the name, it's openly accessible to the whole world---regardless of whether they have a token or not. Consequently, private metadata is associated and only accessible with your user token. The methods for interacting with metadata are outlined below.
Get Metadata Endpoint
# Get Public Metadata (set by you or anyone else)
curl https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN
{"name":"silkroad","owner":"dpr"}# Get Private Metadata (none set yet, returns empty)
curl https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN&private=true{}
//todo: JS examples
#todo: ruby examples
>>>fromblockcypherimportget_metadata# Get Private Metadata (none set yet, returns empty)
>>>get_metadata(address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN',private=True){}# Get Public Metadata (set by you or anyone else)
>>>get_metadata(address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN'){"name":"silkroad","owner":"dpr"}# Note: get_metadata also accepts 'tx_hash' and 'block_hash' as arguments (instead of 'address')
<?php//todo: php examples
Resource
Method
Return Object
/addrs/$ADDRESS/meta
GET
{"$KEY":"$VALUE",...}
/txs/$TXHASH/meta
GET
{"$KEY":"$VALUE",...}
/blocks/$BLOCKHASH/meta
GET
{"$KEY":"$VALUE",...}
Flag
Type
Effect
private
bool
If private is true, it will return privately stored metadata under your token. Otherwise, returns public metadata. If not set, it defaults to false, returning public data.
This endpoint retrieves metadata associated with a given $ADDRESS, $TXHASH, or $BLOCKHASH.
Put Metadata Endpoint
# Put Private Metadata, piping to grep to check 204 status code
curl -X PUT -d'{"satoshi":"nakamoto", "alice":"bob"}'-is'https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN&private=true' | grep"HTTP/1.1"
HTTP/1.1 204 No Content
# Get Metadata Again
curl https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN&private=true{"satoshi":"nakamoto", "alice":"bob"}# Modify/Add Private Metadata
curl -X PUT -d'{"satoshi":"moto", "charlie":"tango"}'-is'https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN&private=true' | grep"HTTP/1.1"
HTTP/1.1 204 No Content
# Get Metadata Again
curl https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN&private=true{"satoshi":"moto", "alice":"bob", "charlie":"tango"}
//todo: JS examples
#todo: ruby examples
>>>fromblockcypherimportput_metadata# Put Private Metadata
>>>put_metadata(metadata_dict={"satoshi":"nakamoto","alice":"bob"},address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN',private=True)True# Get Metadata Again
>>>get_metadata(address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN',private=True){"alice":"bob","satoshi":"nakamoto"}# Modify/Add Private Metadata
>>>put_metadata(metadata_dict={"satoshi":"moto","charlie":"tango"},address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN',private=True)True# Get Metadata Again
>>>get_metadata(address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN',private=True){"alice":"bob","charlie":"tango","satoshi":"moto"}# Note: put_metadata also accepts 'tx_hash' and 'block_hash' as arguments (instead of 'address')
<?php//todo: php examples
Resource
Method
Request Object
Return Object
/addrs/$ADDRESS/meta
PUT
{"$KEY":"$VALUE",...}
nil
/txs/$TXHASH/meta
PUT
{"$KEY":"$VALUE",...}
nil
/blocks/$BLOCKHASH/meta
PUT
{"$KEY":"$VALUE",...}
nil
Flag
Type
Effect
private
bool
If private is true, it will set/update privately stored metadata under your token. Otherwise, sets public metadata. If not set, it defaults to false, setting public metadata.
This endpoint sets or updates metadata (of the form {"$KEY1:$VALUE1,$KEY2:$VALUE2,...}") associated with a given $ADDRESS, $TXHASH, or $BLOCKHASH. If another key with the same name already exists under your private metadata store, supplying a new value will replace it. New key-value pairs will be added without replacing prexisting key-value pairs. If successful, it will return an HTTP Status Code 204 with no return object.
Delete Metadata Endpoint
# Delete Private Metadata, pipes to grep to check for 204 status code
curl -X DELETE -Is https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN | grep"HTTP/1.1"
HTTP/1.1 204 No Content
# Get Private Metadata Again to Confirm Deletion
curl https://api.blockcypher.com/v1/btc/main/addrs/1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp/meta?token=YOURTOKEN&private=true{}
//todo: JS examples
#todo: ruby examples
>>>fromblockcypherimportdelete_metadata>>>delete_metadata(address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN')True# Get Private Metadata Again to Confirm Deletion
>>>get_metadata(address='1rundZJCMJhUiWQNFS5uT3BvisBuLxkAp',api_key='YOUR_TOKEN',private=True){}# Note: delete_metadata also accepts 'tx_hash' and 'block_hash' as arguments (instead of 'address')
<?php//todo: php examples
Resource
Method
Return Object
/addrs/$ADDRESS/meta
DELETE
nil
/txs/$TXHASH/meta
DELETE
nil
/blocks/$BLOCKHASH/meta
DELETE
nil
This endpoint deletes all private metadata associated with a given $ADDRESS, $TXHASH, or $BLOCKHASH and your token.
Asset API
Blockchains are about transferring value and ownership, so why can't that value extend beyond a blockchain's native token? Thanks to the possibility of embedding arbitrary data through null-data outputs, a blockchain can!
However, the act of creating these alternate forms of value---and choosing a format that was universally readable---can be fraught with difficulty. We built our Asset API to simplify that process. Now instead of spelunking through a blockchain's native transactions and interpreting them yourself, you can utilize this set of APIs to easily issue, check, and transfer assets. This set of endpoints currently leverages the Open Assets Protocol, a simple, robust method of embedding assets across any blockchain that supports null-data outputs.
The endpoints (and code examples) are ordered below to demonstrate how to create asset addresses, issue assets, transfer them, then query the assets/asset addresses you initially created.
Generate Asset Address Endpoint
# generate on bitcoin mainnet
curl -X POST https://api.blockcypher.com/v1/btc/main/oap/addrs?token=YOURTOKEN
{"private": "c0e09905fddb1b4a42d297cae1a5f20ca4cbe813e92a7dc4035ffc54561c05de",
"public": "02e9431a3ba8d756a26c03c07ffda2a7e28a17b62051f77ea3944c21dc090ba45b",
"oap_address": "akFjrBkcu9QQoJeBkwWeH54jnymaGVSUBAs",
"original_address": "15mxwaoZfvX7SQ2PttY6RCqDeAQ6UqVjuM",
"wif": "L3ge2aRsGReaBtYVYg9Lau2LxDkRW4Cak1dQsuttShEnRXcA1Vfy"}# generate on blockcypher testnet
curl -X POST https://api.blockcypher.com/v1/bcy/test/oap/addrs?token=YOURTOKEN
{"private": "0eb369746401c3369517239314a6bc0f2bda6124a4dda15643887f86dc0590cf",
"public": "026b9f2786b96f7f1aae011a08f5aaccc70f2249606fac4c400d6aa35f50bf7373",
"oap_address": "1ByJUiocpifLPaYVTALpA7JYa9DxpGxXKKP",
"original_address": "ByJUiocpifLPaYVTALpA7JYa9DxpLQwte4",
"wif": "BopcB66fRGgKkwiT2fKyxcawQBJ57DgNyvFq65XuVQdTboxsBkRm"}# generate another oap_address to use in examples below
curl -X POST https://api.blockcypher.com/v1/bcy/test/oap/addrs?token=YOURTOKEN
{"private": "442abd64783a6411d9e6eb0ed9575c6676bb51824aa3ad4b53577e3d344910c6",
"public": "03121e17e0996513813c504c63016cea9a7cf9689025e33f9157bccea67ba60846",
"oap_address": "1C3nrGhUDxBbr393u2Wq4PiE8T6oEYjYhrK",
"original_address": "C3nrGhUDxBbr393u2Wq4PiE8T6oEYU9At1",
"wif": "BqcYBWUvXszsRi1A5cD6t21CT7sbBoJQEkRSnFuoznJDn4hw5aGg"}
The Generate Asset Address Endpoint returns a private/public keypair and the associated oap_address (the asset address) and original_address (native address on parent blockchain). Asset addresses are just like regular bitcoin addresses, and are generated from a private-public keypair. They only differ by a prefix (ex: 'a' for instead of '1') to distinguish them.
Issue Asset Endpoint
# Since this is a new address, I need to fund underlying bcy original_address # to enable issuance transaction (otherwise no money available for mining fees)# Going to use a faucet thanks to testnet
curl -d'{"address": "ByJUiocpifLPaYVTALpA7JYa9DxpLQwte4", "amount": 1000000}' https://api.blockcypher.com/v1/bcy/test/faucet?token=YOURTOKEN
{"tx_ref": "e7ca58724100f20b81e82ac24cb83cc112627be9cbfd2d09b96a87fbafe9e636"}# using same underlying (now-funded address) to issue 1000 assets# also could have used a different, funded bcy address to issue assets to a new oap_address
curl -d'{"from_private": "0eb369746401c3369517239314a6bc0f2bda6124a4dda15643887f86dc0590cf", "to_address": "1ByJUiocpifLPaYVTALpA7JYa9DxpGxXKKP", "amount": 1000, "metadata": "1a2b3c4d5e6f"}' https://api.blockcypher.com/v1/bcy/test/oap/issue?token=YOURTOKEN
{"ver": 1,
"assetid": "1Npqwstp55vgThp4pwAC9UhYkvPJ28b2Ui",
"hash": "56253cffa1b3508d106391da3646cda2aee0bd080db427321c77ad11739e4239",
"received": "2015-10-25T05:41:45.092075094Z",
"double_spend": false,
"oap_meta": "1a2b3c4d5e6f",
"inputs": [],
"outputs": [{"address": "1ByJUiocpifLPaYVTALpA7JYa9DxpGxXKKP",
"value": 1000,
"original_output_index": 0
}]}
The Issue Asset Endpoint issues new assets onto an OAP to_address, using your private key. Notice that an issuance returns an OAPTX with no inputs, since it is the original issue.
The Transfer Asset Endpoint transfers already issued assets (represented by ASSETID) onto a different OAP to_address, using your private key.
List Asset TXs Endpoint
# using asset id as generated above
curl https://api.blockcypher.com/v1/bcy/test/oap/1Npqwstp55vgThp4pwAC9UhYkvPJ28b2Ui/txs?token=YOURTOKEN
["5f13d5c56ed5b7fe673832e2b5b21feceecebfd08aef03f3208ee855d25f050c",
"022e05bdfa2e148bc1882cb7a81506b8316fee6957b11625126d075a8cf8791b",
"7216fd3fb2908f87255f9514c98f40cf1299ea6b9182fa4825f5c5bfacf8b038",
"56253cffa1b3508d106391da3646cda2aee0bd080db427321c77ad11739e4239",
"dff06ef62b8d67ce6eb0750ed0a414932c1b13b825870d8711cd81219418f6d4"]
Resource
Method
Return Object
/oap/$ASSETID/txs
GET
Array[String]
The List Asset TXs Endpoint returns an array of strings representing transaction hashes associated with this ASSETID.
Get Asset TX Endpoint
# using asset id as generated above, and first txhash from list asset txs endpoint
curl https://api.blockcypher.com/v1/bcy/test/oap/1Npqwstp55vgThp4pwAC9UhYkvPJ28b2Ui/txs/5f13d5c56ed5b7fe673832e2b5b21feceecebfd08aef03f3208ee855d25f050c?token=YOURTOKEN
{"ver": 1,
"assetid": "1Npqwstp55vgThp4pwAC9UhYkvPJ28b2Ui",
"hash": "5f13d5c56ed5b7fe673832e2b5b21feceecebfd08aef03f3208ee855d25f050c",
"block_height": 506539,
"confirmed": "2015-10-25T04:50:06Z",
"received": "2015-10-25T04:49:32.37Z",
"double_spend": false,
"oap_meta": "1a2b3c4d5e6f",
"inputs": [],
"outputs": [{"address": "1ByJUiocpifLPaYVTALpA7JYa9DxpGxXKKP",
"value": 1000,
"original_output_index": 0
}]}
The Get Asset Address Endpoint returns an Address representing information about a particular OAPADDR underneath a given ASSETID. Note that while it returns an Address object, anything that would have represented "satoshis" now represents "amount of asset." (e.g., balance, value, etc.)
Address Forwarding
One of the well-known benefits of cryptocurrency is the ability to allow users to partake in online commerce without necessarily requiring extensive setup barriers, like registering new accounts. In that spirit, our Address Forwarding API is the easiest way to accept---and consolidate---payments securely without forcing your users to create accounts and jump through unnecessary loops. It's also a generic way to automatically transfer value from one address to another. While there are many possible use cases, the two we hear most about are:
A way to generate payment-specific addresses for which funds will automatically transfer to a main merchant address. Great for automatic merchandise (whether physical or virtual) processing.
A method to easily fund a multisignature address from any wallet by providing a classic address that will automatically transfer to the multisignature/pay-to-script-hash address.
We do not take a fee on address forwarding, other than the required miner fee which depends on network conditions; forwards are free. However, as part of your own services, you can include a fee (either fixed or a percentage) that will also be automatically transfered to your own address in the same transaction. Fee-based business models are thus easily achieved, and moreover, easily auditable via the blockchain.
>>>fromblockcypherimportcreate_forwarding_address_with_details>>>create_forwarding_address_with_details(destination_address='15qx9ug952GWGTNn7Uiv6vode4RcGrRemh',api_key='YOUR_TOKEN',callback_url='https://my.domain.com/callbacks/new-pay'){"callback_url":"https://my.domain.com/callbacks/new-pay","destination":"15qx9ug952GWGTNn7Uiv6vode4RcGrRemh","id":"f35c80c2-3347-410d-b4ac-d049910289ec","input_address":"1CUYiFY3LzEd9dXgR6ubRaYPTq2SMxFFCJ","token":"YOUR_TOKEN"}# You can use create_forwarding_address to just return the input_address and not the rest of the JSON
<?php// Run on console:// php -f .\sample\payment-api\CreatePaymentEndpoint.php$paymentForwardClient=newPaymentForwardClient($apiContext);$options=array('callback_url'=>'http://requestb.in/rwp6jirw?uniqid='.uniqid());$paymentForward=$paymentForwardClient->createForwardingAddress('15qx9ug952GWGTNn7Uiv6vode4RcGrRemh',$options);{"destination":"15qx9ug952GWGTNn7Uiv6vode4RcGrRemh","callback_url":"http://requestb.in/rwp6jirw?uniqid=5583de7d87288","id":"ec2b4b4f-eeb2-4824-b528-7d78a6f52492","token":"c0afcccdde5081d6429de37d16166ead","input_address":"17h2S1KtX7AqS9DJexqqSTNFCgwCoqqxhU"}
First, to create an address forwarding address, you need to POST a partially filled AddressForward object to the payment creation endpoint. You need to include at least a destination address and your token; optionally, you can add a callback_url, processing fees (either percent or fixed) and a process_fee_address, and a few other options. You can see more details about these options in the AddressForward object details.
<?php// Run on console:// php -f .\sample\payment-api\ListPaymentsEndpoint.php$paymentForwardClient=newPaymentForwardClient($apiContext);$paymentForwardArray=$paymentForwardClient->listForwardingAddresses();[{"id":"ec2b4b4f-eeb2-4824-b528-7d78a6f52492","token":"c0afcccdde5081d6429de37d16166ead","destination":"15qx9ug952GWGTNn7Uiv6vode4RcGrRemh","input_address":"17h2S1KtX7AqS9DJexqqSTNFCgwCoqqxhU","callback_url":"http://requestb.in/rwp6jirw?uniqid=5583de7d87288"}]
To list your currently active address forwarding addresses, you can use this endpoint.
Returns list of address forwards starting at the start index; useful for paging beyond the limit of 200 address forwards.
This returns the full array of your currently active address forwarding addresses, based on your token. By default, this endpoint only returns the first 200 address forwards. If you have more, you can page through them using the optional start parameter.
Delete Payment Endpoint
# Piping to grep to just show status code
curl -X DELETE -Is https://api.blockcypher.com/v1/btc/main/forwards/399d0923-e920-48ee-8928-2051cbfbc369?token=YOURTOKEN | grep"HTTP/1.1"
HTTP/1.1 204 No Content
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}err:=btc.DeletePayFwd("6fbe2b48-fe79-44a2-9cdc-8114bc4d5fcc ")iferr!=nil{fmt.Println(err)}else{fmt.Println("PayFwd Deleted")}}//Result from `go run`://PayFwd Deleted
<?php// Run on console:// php -f .\sample\payment-api\DeletePaymentEndpoint.php$paymentForwardClient=newPaymentForwardClient($apiContext);$paymentForwardClient->deleteForwardingAddress('1fdf8f9b-cc37-4955-882b-8cbcd670a433');HTTP/1.1204NoContent
When you're done with an address forwarding address, you can delete it via its id.
Resource
Method
Return Object
/forwards/$PAYID
DELETE
nil
PAYID is a string representing the address forwarding request you want to delete, for example:
399d0923-e920-48ee-8928-2051cbfbc369
This will return no object, but will return an HTTP Status Code 204 if the request was successfully deleted.
Events and Hooks
Blockchains are highly transactional systems. Many usage patterns require knowing when an event occurs: i.e., when a transaction is included into a block, or when an unconfirmed transaction is relayed through the network. Instead of requiring you to continuously poll resources, we provide push APIs to facilitate those use cases, and support both WebSockets and WebHooks.
Which Should I Use?
WebSockets are typically used in client applications when a server is not already running: e.g., a web page displaying the most recent transactions or a wallet app updating its UI when a transaction has been confirmed. Websockets are less reliable in longer interactions (> 1 hour) because they require a connection to stay open.
WebHooks are the most reliable way to get event notifications but requires running a server to receive the callbacks. We automatically retry HTTP requests 5 times.
Types of Events
We support a number of different event types, and you can filter your notification requests depending on how you structure your Event request object.
Event
Description
unconfirmed-tx
Triggered for every new transaction BlockCypher receives before it's confirmed in a block; basically, for every unconfirmed transaction. The payload is an unconfirmed TX.
new-block
Triggered for every new block added to the blockchain you've selected as your base resource. The payload is a Block.
confirmed-tx
Triggered for every new transaction making it into a new block; in other words, for every first transaction confirmation. This is equivalent to listening to the new-block event and fetching each transaction in the new Block. The payload is a confirmed TX.
tx-confirmation
Simplifies listening to confirmations on all transactions for a given address up to a provided threshold. Sends first the unconfirmed transaction and then the transaction for each confirmation. Use the confirmations property within the Event to manually specify the number of confirmations desired (maximum 10, defaults to 6). The payload is a TX.
double-spend-tx
Triggered any time a double spend is detected by BlockCypher. The payload is the TX that triggered the event; the hash of the transaction that it's trying to double spend is included in its double_spend_tx property.
tx-confidence
Triggered any time an address has an unconfirmed transaction above the confidence property specified in the Event, based on our Confidence Factor. The payload is the TX that triggered the event. If confidence is not set, defaults to 0.99. To ensure transactions are not missed, even if your confidence threshold is not reached, a transaction is still sent after a minute timeout; please remember to double-check the confidence attribute in the TX payload.
Using WebSockets
# no websockets via cURL, check the Javascript example
# no websockets via PHP, check the Javascript example
Opening a WebSocket to listen to our feeds is easy, like so in Javascript:
new WebSocket("wss://socket.blockcypher.com/v1/btc/main?token=$TOKEN");
The code may differ if you're not programming in Javascript (check relevant code examples for our standard libraries) but the URL will be identical. Once the socket is opened, the JSON document representing the Event of interest should be sent.
In addition to standard events, WebSockets accept a "ping" event. If you send the following, you will receive the same message back with "ping" replaced by "pong":
{ "event": "ping" }
A regular ping (i.e. every 20 seconds) allows the WebSocket to stay connected for a longer period of time.
Using WebHooks
WebHooks leverage similar objects and interactions but with two key differences:
The JSON Event should be sent using a POST request to the "create webhook endpoint" and include a url property to denote where payloads should be delivered.
The TX or Block associated with the Event will be POSTed to the provided url. The POSTed payload will also include X-EventType and X-EventId metadata in the HTTP header specifying the event type and id of the WebHook which triggered the payload.
We retry individual payloads to your url five times; if one fails, we wait exponentially between retries: 1 second, 2s, 4s, 8s, 16s. In order to protect against stale callback urls, your Event will be deleted if it reaches 50 aggregate callback_errors from failed payloads.
>>>fromblockcypherimportsubscribe_to_address_webhook>>>subscribe_to_address_webhook(callback_url='https://my.domain.com/callbacks/new-tx',subscription_address='15qx9ug952GWGTNn7Uiv6vode4RcGrRemh',event='unconfirmed-tx',api_key='YOUR_TOKEN')'bcaf7c39-9a7f-4e8b-8ba4-23b3c1806039'# returns the webhook ID
<?php// Run on console:// php -f .\sample\hook-api\CreateWebHookEndpoint.php$webHook=newWebHook();$webHook->setUrl("http://requestb.in/rwp6jirw?uniqid=".uniqid());$webHook->setEvent('unconfirmed-tx');$webHook->setHash('2b17f5589528f97436b5d563635b4b27ca8980aa20c300abdc538f2a8bfa871b');$webHookClient=new\BlockCypher\Client\WebHookClient($apiContext);$webHook=$webHookClient->create($webHook);{"url":"http://requestb.in/rwp6jirw?uniqid=5581998e19114","event":"unconfirmed-tx","hash":"2b17f5589528f97436b5d563635b4b27ca8980aa20c300abdc538f2a8bfa871b","id":"d5ca3bd3-5dfb-477d-9fb4-ac3510af258d","token":"c0afcccdde5081d6429de37d16166ead","callback_errors":0,"filter":"event=unconfirmed-tx\u0026hash=2b17f5589528f97436b5d563635b4b27ca8980aa20c300abdc538f2a8bfa871b"}
Using a partially filled out Event, you can create a WebHook using this resource. Check the Event object description and types of events to understand the options available for your events.
<?php// Run on console:// php -f .\sample\hook-api\ListWebHooksEndpoint.php$webHookClient=new\BlockCypher\Client\WebHookClient($apiContext);$webHooks=$webHookClient->getAll();[{"id":"d5ca3bd3-5dfb-477d-9fb4-ac3510af258d","token":"c0afcccdde5081d6429de37d16166ead","url":"http://requestb.in/rwp6jirw?uniqid=5581998e19114","callback_errors":0,"event":"unconfirmed-tx","hash":"2b17f5589528f97436b5d563635b4b27ca8980aa20c300abdc538f2a8bfa871b","filter":"event=unconfirmed-tx\u0026hash=2b17f5589528f97436b5d563635b4b27ca8980aa20c300abdc538f2a8bfa871b"}]
This resource lists your currently active events, according to the base resource and $YOURTOKEN.
<?php// Run on console:// php -f .\sample\hook-api\WebHookIdEndpoint.php$webHookClient=new\BlockCypher\Client\WebHookClient($apiContext);$webHook=$webHookClient->get('d5ca3bd3-5dfb-477d-9fb4-ac3510af258d');{"id":"d5ca3bd3-5dfb-477d-9fb4-ac3510af258d","token":"c0afcccdde5081d6429de37d16166ead","url":"http://requestb.in/rwp6jirw?uniqid=5581998e19114","callback_errors":0,"event":"unconfirmed-tx","hash":"2b17f5589528f97436b5d563635b4b27ca8980aa20c300abdc538f2a8bfa871b","filter":"event=unconfirmed-tx\u0026hash=2b17f5589528f97436b5d563635b4b27ca8980aa20c300abdc538f2a8bfa871b"}
This resource returns an Event based on its generated id.
WEBHOOKID is a string representing the event's generated id, for example:
399d0923-e920-48ee-8928-2051cbfbc369
Delete WebHook Endpoint
# Piping into grep to get status code
curl -X DELETE -Is https://api.blockcypher.com/v1/btc/main/hooks/399d0923-e920-48ee-8928-2051cbfbc369?token=YOURTOKEN | grep"HTTP/1.1"
HTTP/1.1 204 OK
packagemainimport("fmt""github.com/blockcypher/gobcy")funcmain(){btc:=gobcy.API{"YOURTOKEN","btc","main"}err:=btc.DeleteHook("86a85527-7c36-435b-bab8-5638d033ead4")iferr!=nil{fmt.Println(err)}else{fmt.Println("Hook deleted")}}//Result from `go run`://Hook deleted
<?php// Run on console:// php -f .\sample\hook-api\DeleteWebHookEndpoint.php$webHookClient=new\BlockCypher\Client\WebHookClient($apiContext);$webHookClient->delete('d5ca3bd3-5dfb-477d-9fb4-ac3510af258d');HTTP/1.1204OK
This resource deletes an active Event based on its id. Remember to include your token, or the request will fail.
Resource
Method
Return Object
/hooks/$WEBHOOKID
DELETE
nil
WEBHOOKID is a string representing the event's generated id, for example:
399d0923-e920-48ee-8928-2051cbfbc369
If successful, it won't return any objects, but will respond with an HTTP Status Code 204.
WebHook Signing
To guarantee the origin and integrity of the webhook data, webhooks can optionally be signed by our servers. An optional JSON attribute called "signkey" can be provided with the webhook when created to either:
A PEM-encoded ECDSA private key that you created.
The string "preset", in which case the BlockCypher signing key will be used. The associated x509 PKIX encoded public key for our webhook signing key is MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEflgGqpIAC9k65JicOPBgXZUExen4rWLq05KwYmZHphTU/fmi3Oe/ckyxo2w3Ayo/SCO/rU2NB90jtCJfz9i1ow==
Once the "signkey" attribute is set on a webhook, all webhook requests will be signed following the sha256-ecdsa scheme of the HTTP signatures specification.
Updates
This section list all the updates in reverse chronological order. All dates are in the DD/MM/YY format.
28/10/21 - Partial Taproot Support
We are happy to announce that BlockCypher now support P2TR (Taproot). Please not that it is not possible to create a transaction that spend a P2TR but you can send to P2TR.
We support the new bech32m address format for v1 witness.
18/10/21 - Fix Unconfirmed Transactions on Address Full Endpoint
Previously, when using the address full endpoint with confirmations>0, you'd still get unconfirmed transactions. This is fixed.
14/10/21 - Fix Websocket Origin Check
We fixed an error where using blockcypher websocket would returns a 403.
06/08/21 - New Filters for Uncofirmed Transactions Endpoint
The data endpoint no longer exists as it was uneconomical and thus non functional since a long time.
19/02/21 - Node-Client Archived
BlockCypher Node.js SDK is now archived. We recommend that javascript users use HTTP libraries such as Axios. The POSTMAN documentation contains all the examples that you need.
18/02/21 - Virtual Size for Blocks
Virtual size (vsize) for blocks.
12/02/21 - Virtual Size for Segwit Transaction
We've added the virtual size (vsize) for segwit transaction. For regular (non-segwit) transaction the vsize is the same as the size.
This is how you can see how much fees you are saving by using segwit. Enjoy!
04/02/21 - Creation of the "Updates" Section
We've created this new "Updates" section to let you know about the new feature and bugfixes we deployed :).
03/02/21 - Additional DNS Seeds for Doge
Following last week Dogecoin chain lag due to unhealthy network conditions, we've added new DNS seeds thanks to Denarius.
02/02/21 - Additional Support for Litecoin Maddrs
Following previous updates to enhance the support of "Maddrs" on Litecoin, we've added several bugfixes:
Correctly display "Maddrs" webhooks with standard wallet.
Correctly display wallet webhooks with "Maddrs".
Fix an error where a webhook will not be delivered if created with a standard wallet and a "Maddr". If you encounter this issue please recreate your wallet.
In standard wallet, listing all addresses will correctly convert "3addrs" to "Maddrs".
In standard wallet, getting a wallet will always show "Maddrs".
27/11/20 - New DASH DNS Seeds
We've updated our DASH DNS seeds in order to provide a more reliable service.
23/11/20 - Payment Forward for Litecoin MAddrs
We've added the ability to create payment forward to Litecoin address with the M prefix.
17/11/20 - OP_RETURN Simplification
We've added the ability to create OP_RETURN output as easily as including null-data as script-type. See the TXOutput object for more details.