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
+18k Golang : How to run your code only once with sync.Once object
+4.8k Golang : Struct field tags and what is their purpose?
+6.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+5.9k Golang : How to call function inside template with template.FuncMap
+6.2k Golang : Example of custom handler for Gorilla's Path usage.
+6.8k Android Studio : Rating bar example
+15k Golang : Execute terminal command to remote machine example
+4.9k Facebook : How to force facebook to scrape latest URL link data?
+28.3k Golang : Get and Set User-Agent examples
+20.6k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+15k Golang : How to extract links from web page ?
+5.7k Restart Apache or Nginx web server without password prompt