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
+9.1k Golang : Go as a script or running go with shebang/hashbang style
+13.5k Golang : Read from buffered reader until specific number of bytes
+8.4k Golang : Emulate NumPy way of creating matrix example
+25.8k Golang : How to write CSV data to file
+6.9k Swift : substringWithRange() function example
+3.9k Golang : Switch Redis database redis.NewClient
+12.1k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+17.1k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+9.3k Golang : How to capture return values from goroutines?
+10.6k Generate Random number with math/rand in Go
+6.3k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+9.9k Golang : Detect number of active displays and the display's resolution