├── .gitignore ├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── doc └── contributor.md ├── .env.sample ├── rocro.yml ├── Gopkg.toml ├── .circleci └── config.yml ├── Gopkg.lock ├── type.go ├── type_test.go ├── README.md ├── btcrpc.go ├── btcrpc_test.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/ 2 | *.env 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **What happened? What is the problem?:** -------------------------------------------------------------------------------- /doc/contributor.md: -------------------------------------------------------------------------------- 1 | # Contributor 2 | - KeisukeYamashita <"19yamashita15@gmail.com"> -------------------------------------------------------------------------------- /.env.sample: -------------------------------------------------------------------------------- 1 | // Write your endpoint here. 2 | BTCD_ENDPOINT: 3 | USERNAME: 4 | PASSWORD: 5 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **Which issue is this pull request for?:** 2 | **Special notes for your reviewer:** -------------------------------------------------------------------------------- /rocro.yml: -------------------------------------------------------------------------------- 1 | inspecode: 2 | experimental: 3 | env: 4 | GLIDE_INSTALL_STRIP_VENDOR: 1 5 | # golang configuration. 6 | gas: default 7 | go-test: default 8 | errcheck: default 9 | go-vet: default 10 | gofmt: auto-fix 11 | goimports: auto-fix 12 | golint: auto-fix 13 | gosimple: default 14 | ineffassign: default 15 | interfacer: default 16 | misspell: auto-fix -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [prune] 29 | go-tests = true 30 | unused-packages = true 31 | 32 | [[constraint]] 33 | name = "github.com/KeisukeYamashita/go-jsonrpc" 34 | version = "1.0.1" 35 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.0 2 | 3 | reference: 4 | work_dir: &work_dir /go/src/github.com/KeisukeYamashita/go-btcrpc 5 | vendor_path: &vendor_path /go/src/github.com/KeisukeYamashita/go-btcrpc/vendor 6 | golang_container_config: &golang_container_config 7 | docker: 8 | - image: circleci/golang:1.9 9 | environment: 10 | VENDOR_PATH: *vendor_path 11 | working_directory: *work_dir 12 | 13 | vendoring: &vendoring 14 | run: 15 | name: Vendoring 16 | command: | 17 | if [ ! -e ${VENDOR_PATH} ]; then 18 | go get -u -v github.com/golang/dep/cmd/dep 19 | dep ensure -v 20 | fi 21 | 22 | jobs: 23 | test: 24 | <<: *golang_container_config 25 | steps: 26 | - checkout 27 | - *vendoring 28 | - run: 29 | name: Run Test 30 | command: | 31 | go get github.com/golang/lint/golint 32 | golint $(go list ./... | grep -v vendor) 33 | go vet $(go list ./... | grep -v vendor) 34 | GO_ENV=test go test -race $(go list ./... | grep -v vendor) 35 | workflows: 36 | version: 2 37 | test: 38 | jobs: 39 | - test: 40 | context: go-btcrpc 41 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "github.com/KeisukeYamashita/go-jsonrpc" 6 | packages = ["."] 7 | revision = "af3b3899128285b8a17568bb7936824759a12873" 8 | version = "v1.0.1" 9 | 10 | [[projects]] 11 | branch = "master" 12 | name = "github.com/gopherjs/gopherjs" 13 | packages = ["js"] 14 | revision = "3926a9f66452f7a8c8d9c0e4e3074383f9aff5cd" 15 | 16 | [[projects]] 17 | name = "github.com/joho/godotenv" 18 | packages = ["."] 19 | revision = "a79fa1e548e2c689c241d10173efd51e5d689d5b" 20 | version = "v1.2.0" 21 | 22 | [[projects]] 23 | name = "github.com/jtolds/gls" 24 | packages = ["."] 25 | revision = "77f18212c9c7edc9bd6a33d383a7b545ce62f064" 26 | version = "v4.2.1" 27 | 28 | [[projects]] 29 | name = "github.com/smartystreets/assertions" 30 | packages = [ 31 | ".", 32 | "internal/go-render/render", 33 | "internal/oglematchers" 34 | ] 35 | revision = "0b37b35ec7434b77e77a4bb29b79677cced992ea" 36 | version = "1.8.1" 37 | 38 | [[projects]] 39 | name = "github.com/smartystreets/goconvey" 40 | packages = [ 41 | "convey", 42 | "convey/gotest", 43 | "convey/reporting" 44 | ] 45 | revision = "9e8dc3f972df6c8fcc0375ef492c24d0bb204857" 46 | version = "1.6.3" 47 | 48 | [solve-meta] 49 | analyzer-name = "dep" 50 | analyzer-version = 1 51 | inputs-digest = "be81aa68c8aa01eea5c4f43eb7334a774249d7151b39c3346bcc5d3ceb465087" 52 | solver-name = "gps-cdcl" 53 | solver-version = 1 54 | -------------------------------------------------------------------------------- /type.go: -------------------------------------------------------------------------------- 1 | package btcrpc 2 | 3 | // Block ... 4 | type Block struct { 5 | Hash string `json:"hash"` 6 | Version int32 `json:"version"` 7 | Txs []string `json:"txs"` 8 | Time int32 `json:"time"` 9 | Size int32 `json:"size"` 10 | Nonce int32 `json:"nonce"` 11 | Weight int32 `json:"weight"` 12 | VersionHex string `json:"versionHex"` 13 | Difficulty int32 `json:"difficulty"` 14 | Mediantime int32 `json:"mediantime"` 15 | Chainwork string `json:"chainwork"` 16 | Strippedsize int32 `json:"strippedsize"` 17 | Merkleroot string `json:"merkleroot"` 18 | Bits string `json:"bits"` 19 | NextBlockhash string `json:"nextBlockhash"` 20 | Confirmations int32 `json:"confirmations"` 21 | Height int32 `json:"height"` 22 | } 23 | 24 | // Transaction ... 25 | type Transaction struct { 26 | Txid string `json:"txid"` 27 | Hash string `json:"hash"` 28 | Version int32 `json:"id"` 29 | Size int32 `json:"size"` 30 | Vsize int32 `json:"vsize"` 31 | Locktime int32 `json:"locktime"` 32 | Vins Vin 33 | Vouts []Vout 34 | } 35 | 36 | // Vin ... 37 | type Vin map[int]interface{} 38 | 39 | // Vout ... 40 | type Vout struct { 41 | Value float32 `json:"value"` 42 | N int32 `json:"n"` 43 | ScriptPubKey ScriptPubKey 44 | } 45 | 46 | // ScriptPubKey ... 47 | type ScriptPubKey struct { 48 | Asm string `json:"asm"` 49 | Hex string `json:"hex"` 50 | ReqSigs int32 `json:"reqSigs"` 51 | Type string `json:"type"` 52 | Addresses []string `json:"addresses"` 53 | } 54 | 55 | // VinTransaction is a struct of Vin(inputs) with normal transaction. 56 | type VinTransaction struct { 57 | Txid string `json:"txid"` 58 | Vout int32 `json:"vout"` 59 | ScriptSig ScriptSig 60 | TxinWitness []string `json:"txinWitness"` 61 | Sequence int64 `json:"Sequence"` 62 | } 63 | 64 | // VinCoinbaseTransaction is a struct of Vins(inputs) with mining. 65 | type VinCoinbaseTransaction struct { 66 | Coinbase string `json:"coinbase"` 67 | Sequence int64 `json:"sequence"` 68 | } 69 | 70 | // ScriptSig ... 71 | type ScriptSig struct { 72 | Asm string `json:"asm"` 73 | Hex string `json:"hex"` 74 | } 75 | -------------------------------------------------------------------------------- /type_test.go: -------------------------------------------------------------------------------- 1 | package btcrpc 2 | 3 | import ( 4 | "testing" 5 | 6 | . "github.com/smartystreets/goconvey/convey" 7 | ) 8 | 9 | func TestTransactionStruct(t *testing.T) { 10 | VinMap := make(map[int]interface{}) 11 | 12 | VinMap[1] = VinTransaction{ 13 | Txid: "09409e9151aeed67ed592c181840855c1f45d6ce3c1b8b0b3616f4dea2c22ccb", 14 | Vout: 0, 15 | ScriptSig: ScriptSig{ 16 | Asm: "", 17 | Hex: "", 18 | }, 19 | TxinWitness: []string{"", "3045022100a6cda8a54b4fee586fe8cf2bde6ecdef919823410cae86ee7907a538893f47c602201304b82d1a7b6b162be2197b433bd645241f17aa8c70a08040474598aac5ac9e01", "30450221008829bb92c399c1182f67ebffb1834375d7d206f6fbf1536a39b4cfaa29374f9002200f4dcf8cf07fd257be9d2338de9e0041b4bf1c16a652182296632a44a912880d01"}, 20 | Sequence: 4294967295, 21 | } 22 | VinMap[2] = VinCoinbaseTransaction{ 23 | Coinbase: "043jifdga345", 24 | Sequence: 4294967295, 25 | } 26 | 27 | Vout := []Vout{ 28 | Vout{ 29 | Value: 50.00000000, 30 | N: 0, 31 | ScriptPubKey: ScriptPubKey{ 32 | Asm: "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee OP_CHECKSIG", 33 | Hex: "410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac", 34 | ReqSigs: 1, 35 | Type: "pubkey", 36 | Addresses: []string{"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX"}, 37 | }, 38 | }, 39 | Vout{ 40 | Value: 1000.00000000, 41 | N: 1, 42 | ScriptPubKey: ScriptPubKey{ 43 | Asm: "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee OP_CHECKSIG", 44 | Hex: "410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac", 45 | ReqSigs: 1, 46 | Type: "pubkey", 47 | Addresses: []string{"1F1tAaz5x1HUXrCNLbtMDqcw6o5GNn4xqX", "1KJDckyDF54pH65quicuyCK7UH4Af7Wtpp"}, 48 | }, 49 | }, 50 | } 51 | rawTx := &Transaction{ 52 | Txid: "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098", 53 | Hash: "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098", 54 | Version: 1, 55 | Size: 134, 56 | Vsize: 134, 57 | Locktime: 0, 58 | Vins: VinMap, 59 | Vouts: Vout, 60 | } 61 | Convey("SuccessWithVin", t, func() { 62 | var VinCoinbaseTranscactionNum int 63 | var VinTransactionNum int 64 | for i, Vin := range rawTx.Vins { 65 | if _, ok := Vin.(VinTransaction); ok { 66 | VinTransactionNum = i 67 | } 68 | if _, ok := Vin.(VinCoinbaseTransaction); ok { 69 | VinCoinbaseTranscactionNum = i 70 | } 71 | } 72 | So(VinTransactionNum, ShouldEqual, 1) 73 | So(VinCoinbaseTranscactionNum, ShouldEqual, 2) 74 | }) 75 | } 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-btcrpc 2 | 3 | [![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://github.com/ellerbrock/open-source-badges/) 4 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://godoc.org/github.com/KeisukeYamashita/go-btcrpc) 5 | [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 6 | [![CircleCI](https://circleci.com/gh/KeisukeYamashita/go-btcrpc.svg?style=svg)](https://circleci.com/gh/KeisukeYamashita/go-btcrpc) 7 | [![Job Status](https://inspecode.rocro.com/badges/github.com/KeisukeYamashita/go-btcrpc/status?token=SGqr7pQjbMTQuMDLOPk_rvq_hGeF_hoLj_B7tbRKSXg)](https://inspecode.rocro.com/jobs/github.com/KeisukeYamashita/go-btcrpc/latest?completed=true) 8 | [![Report](https://inspecode.rocro.com/badges/github.com/KeisukeYamashita/go-btcrpc/report?token=SGqr7pQjbMTQuMDLOPk_rvq_hGeF_hoLj_B7tbRKSXg&branch=master)](https://inspecode.rocro.com/reports/github.com/KeisukeYamashita/go-btcrpc/branch/master/summary) 9 | 10 | 11 | go-btcrpc is a Go library use for interacting to the bitcoin node from your server with JSON-RPC which is a standard protocol for blockchain. 12 | 13 | This library provides the easiest way to send JSON-RPC. 14 | 15 | ![image.png](https://qiita-image-store.s3.amazonaws.com/0/153320/744a8c95-5e4e-73f4-9d4a-5e6d5e0cfcc5.png) 16 | 17 | ## Installation 18 | Use go get to install and update. 19 | 20 | ``` 21 | go get github.com/KeisukeYamashita/go-btcrpc.git 22 | ``` 23 | 24 | ## Setup 25 | You need to setup environmental variables. 26 | 27 | Firstly, copy the `.env.sample` as `.env` 28 | 29 | ``` 30 | cp .env.sample .env 31 | ``` 32 | 33 | Setup in your `.env`. 34 | 35 | ``` 36 | BTCD_ENDPOINT: NODE_ENDPOINT 37 | USERNAME: USERNAME_FOR_BASICAUTH 38 | PASSWORD: PASSWORD_FOR_BASICAUTH 39 | ``` 40 | 41 | ## Usage and Example 42 | This shows you that easiest request to the node which is getting the infos. 43 | 44 | ```go 45 | package main 46 | 47 | import ( 48 | "fmt" 49 | btcrpc "github.com/KeisukeYamashita/go-btcrpc" 50 | ) 51 | 52 | func main() { 53 | basicAuth := &BasicAuth{ 54 | Username: os.Getenv("USERNAME"), 55 | Password: os.Getenv("PASSWORD"), 56 | } 57 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 58 | address := "my88QLpf2RYYDdNMmDwYvfx6TFc6NXaELa" 59 | balance := c.GetBalance(address) 60 | fmt.Print(balance) // 0.13514 BTC 61 | } 62 | ``` 63 | 64 | ### Equal curl command 65 | 66 | ``` 67 | curl -X "POST" "" \ 68 | -H 'Content-Type: application/json; charset=utf-8' \ 69 | -u ':' \ 70 | -d $'{ 71 | "method": "getbalance", 72 | "id": "1", 73 | "params": [ 74 | "my88QLpf2RYYDdNMmDwYvfx6TFc6NXaELa" 75 | ] 76 | }' 77 | ``` 78 | 79 | It'll return a JSON. 80 | 81 | ### Available Methods 82 | 83 | | method| discription | 84 | |:----:|:----:| 85 | | getNewAddress | creates a new address to your account. | 86 | | getBalance | get the balance of your address. | 87 | | getBlockHash | get the hash of the block. | 88 | | getBlock | get the block by hash of the block. | 89 | | getBlockCount | get the newest block count by hash of the block. | 90 | | decodeTransaction | decode the raw transaction to humanreadable transaction by hash of the block. | 91 | | getrawTransaction | get the raw transaction hash block count by hash of the block. | 92 | 93 | 94 | ## Use tests 95 | Set up your environmental valiables in `.env` to conduct this test. 96 | 97 | ``` 98 | cp .env.sample .env 99 | ``` 100 | 101 | Then write in your endpoint in this file. 102 | 103 | 104 | Finally run your test. It will pass if your bitcoin node is setted up correctly. 105 | 106 | ``` 107 | GO_ENV = test go test btcrpc 108 | ``` 109 | 110 | ## Contribution 111 | To contribute, just send me a pull request! 112 | If it is valid, you will be added on the contribution doc in `/doc/contributor.md` . 113 | 114 | ## License 115 | Copyright 2017 Keisuke Yamashita. 116 | 117 | Licensed under the Apache 2.0 license. 118 | -------------------------------------------------------------------------------- /btcrpc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package btcrpc implements RPC methods to interact with the bitcoin node bitcoind. 3 | See informations in the pages link below about Bitcoin development. 4 | https://bitcoin.org/en/development 5 | */ 6 | package btcrpc 7 | 8 | import ( 9 | "encoding/json" 10 | "errors" 11 | 12 | jsonrpc "github.com/KeisukeYamashita/go-jsonrpc" 13 | ) 14 | 15 | /* 16 | BasicAuth is for Bitcoin Node supports basic auth. 17 | Some nodes do not need this. In that case, leave these blank. 18 | */ 19 | type BasicAuth struct { 20 | Username string 21 | Password string 22 | } 23 | 24 | /* 25 | RPCClient ... 26 | */ 27 | type RPCClient struct { 28 | *jsonrpc.RPCClient 29 | } 30 | 31 | /* 32 | RPCer ... 33 | */ 34 | type RPCer interface { 35 | GetBlockHash(height int32) (string, error) 36 | } 37 | 38 | /* 39 | NewRPCClient creates JSONRPC clients for your bitcoin node. 40 | */ 41 | func NewRPCClient(endpoint string, basicAuth *BasicAuth) *RPCClient { 42 | c := new(RPCClient) 43 | c.RPCClient = jsonrpc.NewRPCClient(endpoint) 44 | c.RPCClient.SetBasicAuth(basicAuth.Username, basicAuth.Password) 45 | return c 46 | } 47 | 48 | /* 49 | GetNewAddress gets new address associated with the account name given. 50 | If the account name is blank(nil), if will also returns a addresss with no associated account. 51 | */ 52 | func (c *RPCClient) GetNewAddress(account string) (string, error) { 53 | resp, err := c.RPCClient.Call("getnewaddress", account) 54 | if err != nil { 55 | return "", err 56 | } 57 | 58 | if resp.Error != nil { 59 | return "", errors.New(resp.Error.Message) 60 | } 61 | 62 | var address string 63 | resp.GetObject(&address) 64 | return address, nil 65 | } 66 | 67 | /* 68 | GetBalance gets the balance of the address. 69 | It is only possible to get the balance which is made by this node, otherwise it will return 0.00. 70 | */ 71 | func (c *RPCClient) GetBalance(address string) (float32, error) { 72 | resp, err := c.RPCClient.Call("getbalance", address) 73 | if err != nil { 74 | return -1, err 75 | } 76 | 77 | if resp.Error != nil { 78 | return -1, errors.New(resp.Error.Message) 79 | } 80 | 81 | var balance float32 82 | resp.GetObject(&balance) 83 | return balance, nil 84 | } 85 | 86 | /* 87 | GetBlockHash gets the block hash(id) associated with the block height. 88 | */ 89 | func (c *RPCClient) GetBlockHash(height int32) (string, error) { 90 | resp, err := c.RPCClient.Call("getblockhash", height) 91 | if err != nil { 92 | return "", err 93 | } 94 | 95 | if resp.Error != nil { 96 | return "", errors.New(resp.Error.Message) 97 | } 98 | 99 | var hash string 100 | resp.GetObject(&hash) 101 | return hash, nil 102 | } 103 | 104 | /* 105 | GetBlock gets the block information associated with the block hash(id). 106 | It contains a lot of infos about transactions. 107 | */ 108 | func (c *RPCClient) GetBlock(h string) (*Block, error) { 109 | resp, err := c.RPCClient.Call("getblock", h) 110 | if err != nil { 111 | return nil, err 112 | } 113 | 114 | if resp.Error != nil { 115 | return nil, errors.New(resp.Error.Message) 116 | } 117 | 118 | jsonData, err := json.Marshal(resp.Result) 119 | if err != nil { 120 | return nil, err 121 | } 122 | 123 | var block Block 124 | json.Unmarshal(jsonData, &block) 125 | return &block, nil 126 | } 127 | 128 | /* 129 | GetBlockCount gets the latest block height. 130 | Note that The methods name is "Count" not "Height". 131 | */ 132 | func (c *RPCClient) GetBlockCount() (int32, error) { 133 | resp, err := c.RPCClient.Call("getblockcount") 134 | if err != nil { 135 | return -1, err 136 | } 137 | 138 | if resp.Error != nil { 139 | return -1, errors.New(resp.Error.Message) 140 | } 141 | 142 | var count int32 143 | resp.GetObject(&count) 144 | return count, nil 145 | } 146 | 147 | /* 148 | GetRawTransactions gets the raw transactions associated with the transaction hashes(ids). 149 | */ 150 | func (c *RPCClient) GetRawTransactions(txids []string) ([]string, error) { 151 | rawTxs := make([]string, len(txids)) 152 | for i, txid := range txids { 153 | resp, err := c.RPCClient.Call("getrawtransaction", txid) 154 | if err != nil { 155 | return nil, err 156 | } 157 | 158 | if resp.Error != nil { 159 | return nil, errors.New(resp.Error.Message) 160 | } 161 | 162 | var rawTx string 163 | resp.GetObject(&rawTx) 164 | rawTxs[i] = rawTx 165 | } 166 | return rawTxs, nil 167 | } 168 | 169 | /* 170 | DecodeRawTransactions decodes the raw transactions to human readable transactions. 171 | */ 172 | func (c *RPCClient) DecodeRawTransactions(rawTxs []string) ([]*Transaction, error) { 173 | txs := make([]*Transaction, len(rawTxs)) 174 | for i, rawTx := range rawTxs { 175 | resp, err := c.RPCClient.Call("decoderawtransaction", rawTx) 176 | if err != nil { 177 | return nil, err 178 | } 179 | 180 | if resp.Error != nil { 181 | return nil, errors.New(resp.Error.Message) 182 | } 183 | 184 | jsonData, err := json.Marshal(resp.Result) 185 | if err != nil { 186 | return nil, err 187 | } 188 | 189 | var tx Transaction 190 | json.Unmarshal(jsonData, &tx) 191 | txs[i] = &tx 192 | } 193 | return txs, nil 194 | } 195 | -------------------------------------------------------------------------------- /btcrpc_test.go: -------------------------------------------------------------------------------- 1 | package btcrpc 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "testing" 7 | 8 | "github.com/joho/godotenv" 9 | 10 | . "github.com/smartystreets/goconvey/convey" 11 | ) 12 | 13 | func init() { 14 | err := godotenv.Load() 15 | if err != nil && os.Getenv("GO_ENV") != "test" { 16 | log.Fatal("Error loading .env file") 17 | } 18 | } 19 | 20 | func TestRPCClient(t *testing.T) { 21 | Convey("Success", t, func() { 22 | basicAuth := &BasicAuth{ 23 | Username: os.Getenv("USERNAME"), 24 | Password: os.Getenv("PASSWORD"), 25 | } 26 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 27 | _, err := c.GetBlockCount() 28 | So(err, ShouldBeNil) 29 | }) 30 | Convey("InvalidBasicAuth", t, func() { 31 | basicAuth := new(BasicAuth) 32 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 33 | _, err := c.GetBlockCount() 34 | So(err, ShouldNotBeNil) 35 | }) 36 | } 37 | 38 | func TestNewAddress(t *testing.T) { 39 | basicAuth := &BasicAuth{ 40 | Username: os.Getenv("USERNAME"), 41 | Password: os.Getenv("PASSWORD"), 42 | } 43 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 44 | Convey("Success", t, func() { 45 | _, err := c.GetNewAddress("KeisukeYamashita") 46 | So(err, ShouldBeNil) 47 | }) 48 | } 49 | 50 | func TestGetBalance(t *testing.T) { 51 | basicAuth := &BasicAuth{ 52 | Username: os.Getenv("USERNAME"), 53 | Password: os.Getenv("PASSWORD"), 54 | } 55 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 56 | Convey("Success", t, func() { 57 | result, err := c.GetBalance("address") 58 | So(err, ShouldBeNil) 59 | So(result, ShouldEqual, 0.00000000) // Block Height 60 | }) 61 | 62 | Convey("No addresss", t, func() { 63 | result, err := c.GetBalance("I do not exists") 64 | So(err, ShouldBeNil) 65 | So(result, ShouldEqual, 0.00000000) // 0.00000000 66 | }) 67 | } 68 | 69 | func TestGetBlockHash(t *testing.T) { 70 | basicAuth := &BasicAuth{ 71 | Username: os.Getenv("USERNAME"), 72 | Password: os.Getenv("PASSWORD"), 73 | } 74 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 75 | Convey("Success", t, func() { 76 | result, err := c.GetBlockHash(500954) 77 | So(err, ShouldBeNil) 78 | So(result, ShouldEqual, "00000000000a098712c8c196b42dfcb36ecf77c4620ba4719c868012ebaeec8a") // Block Hash 79 | }) 80 | 81 | Convey("Invalid block index", t, func() { 82 | _, err := c.GetBlockHash(-1) 83 | So(err.Error(), ShouldEqual, "Block height out of range") 84 | }) 85 | } 86 | 87 | // TODO: change for testnet*testing.T) { 88 | // basicAuth := &BasicAuth{ 89 | // Username: os.Getenv("USERNAME"), 90 | // Password: os.Getenv("PASSWORD"), 91 | // } 92 | // c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 93 | 94 | // Convey("Invalid block hash", t, func() { 95 | // _, err := c.GetBlock("Invalid transactionId") 96 | // So(err.Error(), ShouldEqual, "Block not found") 97 | // }) 98 | // } 99 | 100 | func TestGetBlockCount(t *testing.T) { 101 | basicAuth := &BasicAuth{ 102 | Username: os.Getenv("USERNAME"), 103 | Password: os.Getenv("PASSWORD"), 104 | } 105 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 106 | Convey("Success", t, func() { 107 | _, err := c.GetBlockCount() 108 | So(err, ShouldBeNil) 109 | }) 110 | } 111 | 112 | // TODO: change for testnet 113 | // func TestGetRawTransactions(t *testing.T) { 114 | // basicAuth := &BasicAuth{ 115 | // Username: os.Getenv("USERNAME"), 116 | // Password: os.Getenv("PASSWORD"), 117 | // } 118 | // c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 119 | // Convey("Success", t, func() { 120 | // result, err := c.GetRawTransactions([]string{"8878522366f6a4d9a7b4a88dca6d36b036f09d6093c1d39b8cf7bedd4dbf75d6", "abb3880f8f7d66effa540e8ca9ce8878e8b4978c9843ee8c3001c07d09ae5ce3"}) // Genesis Block 121 | // So(err, ShouldBeNil) 122 | // So(result[0], ShouldEqual, "010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff5503daa40741d6902f5030707d41d6902f4fc582f22f4254432e544f502ffabe6d6d3b1daff61de82061d499ed27ab8e058e615edea9175c01c8134c5b0f3321e2218000000000000000c100676b0000a1aeef6d0100ffffffff022e5cb258000000001976a914ba507bae8f1643d2556000ca26b9301b9069dc6b88ac0000000000000000266a24aa21a9ed8a7f6c7f59f1859daf7475f1d28be4113abb8b5365d4868b69b877a4f4665f280120000000000000000000000000000000000000000000000000000000000000000000000000") 123 | // So(result[1], ShouldEqual, "0100000001962328b4c86763f92ecf78180f015c236e53f34cb6860780d539f8a4072b8501060000006b483045022100c8c78ceb7d1affe434fe4952f32d066d1cd8e1dc418f10e752afaa2cf924629e0220615ca51233d3510868e3416ab4e8b0f7b83e68839716198586325abf2775dfe2012103f803ea646b6bdeb9ad2ebb486724e3a82a1b211666a9830714ba94e6214dfeabffffffff02d40a0200000000001976a914c7c04f2c8dfa53f542ce8abf49bd47ba06804a4788ac4d483700000000001976a914f7d6366850ec376c277e45b7c6984c126d25904e88ac00000000") 124 | // }) 125 | 126 | // Convey("Invalid transactionId", t, func() { 127 | // _, err := c.GetRawTransactions([]string{"Invalid transactionId"}) 128 | // So(err.Error(), ShouldContainSubstring, "parameter 1 must be hexadecimal string") 129 | // }) 130 | // } 131 | 132 | func TestDecodeRawTransaction(t *testing.T) { 133 | basicAuth := &BasicAuth{ 134 | Username: os.Getenv("USERNAME"), 135 | Password: os.Getenv("PASSWORD"), 136 | } 137 | c := NewRPCClient(os.Getenv("BTCD_ENDPOINT"), basicAuth) 138 | Convey("Success", t, func() { 139 | result, err := c.DecodeRawTransactions([]string{"010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff5503daa40741d6902f5030707d41d6902f4fc582f22f4254432e544f502ffabe6d6d3b1daff61de82061d499ed27ab8e058e615edea9175c01c8134c5b0f3321e2218000000000000000c100676b0000a1aeef6d0100ffffffff022e5cb258000000001976a914ba507bae8f1643d2556000ca26b9301b9069dc6b88ac0000000000000000266a24aa21a9ed8a7f6c7f59f1859daf7475f1d28be4113abb8b5365d4868b69b877a4f4665f280120000000000000000000000000000000000000000000000000000000000000000000000000", "0100000001962328b4c86763f92ecf78180f015c236e53f34cb6860780d539f8a4072b8501060000006b483045022100c8c78ceb7d1affe434fe4952f32d066d1cd8e1dc418f10e752afaa2cf924629e0220615ca51233d3510868e3416ab4e8b0f7b83e68839716198586325abf2775dfe2012103f803ea646b6bdeb9ad2ebb486724e3a82a1b211666a9830714ba94e6214dfeabffffffff02d40a0200000000001976a914c7c04f2c8dfa53f542ce8abf49bd47ba06804a4788ac4d483700000000001976a914f7d6366850ec376c277e45b7c6984c126d25904e88ac00000000"}) 140 | So(err, ShouldBeNil) 141 | So(result[0].Txid, ShouldEqual, "8878522366f6a4d9a7b4a88dca6d36b036f09d6093c1d39b8cf7bedd4dbf75d6") 142 | So(result[1].Txid, ShouldEqual, "abb3880f8f7d66effa540e8ca9ce8878e8b4978c9843ee8c3001c07d09ae5ce3") 143 | }) 144 | 145 | Convey("Invalid rawtx", t, func() { 146 | _, err := c.DecodeRawTransactions([]string{"Invalid rawTransaction"}) 147 | So(err.Error(), ShouldEqual, "TX decode failed") 148 | }) 149 | 150 | } 151 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------