Golang : Get final balance from bit coin address example
Here is an example of how to query blockchain.info to get the final balance(amount) with a given bitcoin transaction address. Some e-commerce merchants start to accept bitcoin instead of fiat money and this application can be useful in verifying the amount received before issuing a receipt and sending out the goods.
Basically what this program below does is to get the final balance of a transaction with the given bitcoin address. You can incorporate this code below into your e-commerce application to check for the bitcoin payment.
NOTE: The only known weakness in this program is that it relies on the HTML id final_balance
when parsing the HTML nodes to retrieve the BTC amount. IF the id final_balance
is removed from blockchain.info website, this program will break.
Here you go!
package main
import (
"fmt"
"golang.org/x/net/html"
"io/ioutil"
"net/http"
"os"
"strings"
)
func Get(httpClient *http.Client, url string) (resp *http.Response, err error) {
req, err := http.NewRequest("GET", url, nil)
resp, err = httpClient.Do(req)
return
}
func GetHtmlBody(httpClient *http.Client, url string) (string, error) {
response, err := Get(httpClient, url)
defer response.Body.Close()
htmlBody, err := ioutil.ReadAll(response.Body)
body := string(htmlBody)
return body, err
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage : %s <bitcoin transaction address>\n", os.Args[0])
os.Exit(0)
}
// randomly pick one or two addresses from https://blockchain.info/blocks
//bitcoinAddress := "152f1muMCNa7goXYhYAQC61hxEgGacmncB"
bitcoinAddress := os.Args[1]
fmt.Println("Querying Bitcoin address : ", bitcoinAddress)
if bitcoinAddress == "" {
fmt.Println("Bitcoin address cannot be empty!")
os.Exit(0)
}
client := &http.Client{}
body, err := GetHtmlBody(client, "https://blockchain.info/address/"+bitcoinAddress)
if err != nil {
fmt.Println(err)
}
htmlBody := string(body)
// adapted from https://godoc.org/golang.org/x/net/html#Parse
doc, err := html.Parse(strings.NewReader(htmlBody))
if err != nil {
fmt.Println(err)
}
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "td" {
for _, attr := range n.Attr {
if attr.Key == "id" && attr.Val == "final_balance" {
if n.FirstChild != nil && n.FirstChild.FirstChild != nil {
spanNode := n.FirstChild.FirstChild
if spanNode.Data == "span" {
if spanNode.FirstChild == nil {
// do nothing
}
balance := spanNode.FirstChild.Data
fmt.Println("Final balance: ", balance)
break
}
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
f(c)
}
}
f(doc)
}
Sample output with bit coin transaction addresses randomly picked up from https://blockchain.info/blocks
$ ./queryblockchain 1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY
Querying Bitcoin address : 1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY
Final balance: 1,342.4838477 BTC
$ ./queryblockchain 1JyiMwNfLcXHztZVMQJ5UWH6cJEyL24jKR
Querying Bitcoin address : 1JyiMwNfLcXHztZVMQJ5UWH6cJEyL24jKR
Final balance: 0 BTC
$ ./queryblockchain 152f1muMCNa7goXYhYAQC61hxEgGacmncB
Querying Bitcoin address : 152f1muMCNa7goXYhYAQC61hxEgGacmncB
Final balance: 4,356.19141589 BTC
References:
See also : Cash Flow : 50 days to pay your credit card debt
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.9k Golang : HttpRouter multiplexer routing example
+23.5k Golang : Fix type interface{} has no field or no methods and type assertions example
+11.4k Golang : Secure file deletion with wipe example
+33.7k Golang : Call a function after some delay(time.Sleep and Tick)
+7.9k Golang : Randomize letters from a string example
+18.2k Golang : Send email with attachment
+5.6k Linux : Disable and enable IPv4 forwarding
+44.4k Golang : Use wildcard patterns with filepath.Glob() example
+16.8k Golang : Covert map/slice/array to JSON or XML format
+12.9k Golang : How to get a user home directory path?
+10.2k Generate Random number with math/rand in Go
+10.9k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example