├── docs ├── README.md ├── .gitignore ├── requirements.txt ├── wallet.md ├── update.md ├── table_of_content.md ├── contact.md ├── Makefile ├── make.bat ├── controlling.md ├── mining.md ├── developer_resources.md ├── installation.md ├── conf.py └── index.md ├── wire ├── testdata │ └── megatx.bin.bz2 ├── error.go ├── msgsendaddrv2.go ├── msgverack.go ├── msggetaddr.go ├── protocol_test.go ├── fakemessage_test.go ├── msgmempool_test.go ├── msgmempool.go ├── msgfilterclear.go ├── msgsendheaders.go ├── msgfeefilter.go ├── msggetcfcheckpt.go ├── fixedIO_test.go ├── msggetcfheaders.go ├── msggetcfilters.go ├── msgpong.go ├── msgfilteradd.go └── invvect.go ├── blockchain ├── testdata │ ├── 277647.dat.bz2 │ ├── blk_3A.dat.bz2 │ ├── blk_4A.dat.bz2 │ ├── blk_5A.dat.bz2 │ ├── 277647.utxostore.bz2 │ └── blk_0_to_4.dat.bz2 ├── merkle_test.go ├── bench_test.go ├── log.go ├── timesorter.go ├── indexers │ ├── log.go │ ├── README.md │ └── blocklogger.go ├── fullblocktests │ ├── doc.go │ └── README.md ├── scriptval_test.go ├── timesorter_test.go ├── notifications_test.go └── difficulty_test.go ├── database ├── testdata │ └── blocks1-256.bz2 ├── export_test.go ├── ffldb │ ├── doc.go │ ├── export_test.go │ ├── README.md │ ├── ldbtreapiter.go │ ├── driver.go │ └── bench_test.go ├── log.go ├── internal │ └── treap │ │ ├── doc.go │ │ └── README.md ├── cmd │ └── dbtool │ │ ├── fetchblock.go │ │ ├── fetchblockregion.go │ │ ├── signal.go │ │ └── loadheaders.go └── README.md ├── chaincfg ├── chainhash │ ├── doc.go │ ├── hashfuncs.go │ └── README.md ├── README.md └── doc.go ├── limits ├── limits_windows.go ├── limits_plan9.go └── limits_unix.go ├── integration ├── main.go ├── README.md └── rpctest │ ├── doc.go │ ├── README.md │ └── btcd.go ├── txscript ├── data │ └── LICENSE ├── consensus.go ├── log.go ├── doc.go └── README.md ├── signalsigterm.go ├── connmgr ├── doc.go ├── log.go ├── README.md ├── seed.go └── dynamicbanscore_test.go ├── .gitignore ├── rpcclient ├── CONTRIBUTORS ├── cookiefile.go ├── examples │ ├── bitcoincorehttpbulk │ │ ├── README.md │ │ └── main.go │ ├── bitcoincorehttp │ │ ├── README.md │ │ └── main.go │ ├── btcdwebsockets │ │ ├── README.md │ │ └── main.go │ └── btcwalletwebsockets │ │ ├── README.md │ │ └── main.go ├── log.go ├── README.md ├── rawrequest.go └── chain_test.go ├── addrmgr ├── cov_report.sh ├── internal_test.go ├── log.go └── doc.go ├── netsync ├── doc.go ├── log.go ├── README.md ├── interface.go └── blocklogger.go ├── go.mod ├── btcjson ├── CONTRIBUTORS ├── chainsvrwsresults.go ├── btcdextresults.go ├── chainsvrwsresults_test.go ├── btcdextresults_test.go ├── export_test.go ├── error_test.go ├── helpers_test.go └── helpers.go ├── mining ├── README.md ├── log.go └── cpuminer │ ├── log.go │ └── README.md ├── goclean.sh ├── LICENSE ├── .github └── workflows │ └── go.yml ├── btcec ├── doc.go ├── privkey_test.go ├── genprecomps.go ├── precompute.go └── privkey.go ├── mempool └── log.go ├── Dockerfile ├── config_test.go ├── rpcserverhelp_test.go ├── signal.go ├── version.go └── cmd └── btcctl └── version.go /docs/README.md: -------------------------------------------------------------------------------- 1 | index.md -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx_markdown_tables 2 | -------------------------------------------------------------------------------- /wire/testdata/megatx.bin.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/wire/testdata/megatx.bin.bz2 -------------------------------------------------------------------------------- /blockchain/testdata/277647.dat.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/blockchain/testdata/277647.dat.bz2 -------------------------------------------------------------------------------- /blockchain/testdata/blk_3A.dat.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/blockchain/testdata/blk_3A.dat.bz2 -------------------------------------------------------------------------------- /blockchain/testdata/blk_4A.dat.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/blockchain/testdata/blk_4A.dat.bz2 -------------------------------------------------------------------------------- /blockchain/testdata/blk_5A.dat.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/blockchain/testdata/blk_5A.dat.bz2 -------------------------------------------------------------------------------- /database/testdata/blocks1-256.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/database/testdata/blocks1-256.bz2 -------------------------------------------------------------------------------- /blockchain/testdata/277647.utxostore.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/blockchain/testdata/277647.utxostore.bz2 -------------------------------------------------------------------------------- /blockchain/testdata/blk_0_to_4.dat.bz2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/phoenixchain/btcd/HEAD/blockchain/testdata/blk_0_to_4.dat.bz2 -------------------------------------------------------------------------------- /docs/wallet.md: -------------------------------------------------------------------------------- 1 | # Wallet 2 | 3 | btcd was intentionally developed without an integrated wallet for security 4 | reasons. Please see [btcwallet](https://github.com/btcsuite/btcwallet) for more 5 | information. 6 | -------------------------------------------------------------------------------- /docs/update.md: -------------------------------------------------------------------------------- 1 | # Update 2 | 3 | * Run the following commands to update btcd, all dependencies, and install it: 4 | 5 | ```bash 6 | cd $GOPATH/src/github.com/btcsuite/btcd 7 | git pull && GO111MODULE=on go install -v . ./cmd/... 8 | ``` 9 | -------------------------------------------------------------------------------- /chaincfg/chainhash/doc.go: -------------------------------------------------------------------------------- 1 | // Package chainhash provides abstracted hash functionality. 2 | // 3 | // This package provides a generic hash type and associated functions that 4 | // allows the specific hash algorithm to be abstracted. 5 | package chainhash 6 | -------------------------------------------------------------------------------- /limits/limits_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package limits 6 | 7 | // SetLimits is a no-op on Windows since it's not required there. 8 | func SetLimits() error { 9 | return nil 10 | } 11 | -------------------------------------------------------------------------------- /limits/limits_plan9.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package limits 6 | 7 | // SetLimits is a no-op on Plan 9 due to the lack of process accounting. 8 | func SetLimits() error { 9 | return nil 10 | } 11 | -------------------------------------------------------------------------------- /integration/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package integration 6 | 7 | // This file only exists to prevent warnings due to no buildable source files 8 | // when the build tag for enabling the tests is not specified. 9 | -------------------------------------------------------------------------------- /txscript/data/LICENSE: -------------------------------------------------------------------------------- 1 | The json files in this directory come from the bitcoind project 2 | (https://github.com/bitcoin/bitcoin) and is released under the following 3 | license: 4 | 5 | Copyright (c) 2012-2014 The Bitcoin Core developers 6 | Distributed under the MIT/X11 software license, see the accompanying 7 | file COPYING or http://www.opensource.org/licenses/mit-license.php. 8 | 9 | -------------------------------------------------------------------------------- /signalsigterm.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build darwin dragonfly freebsd linux netbsd openbsd solaris 6 | 7 | package main 8 | 9 | import ( 10 | "os" 11 | "syscall" 12 | ) 13 | 14 | func init() { 15 | interruptSignals = []os.Signal{os.Interrupt, syscall.SIGTERM} 16 | } 17 | -------------------------------------------------------------------------------- /docs/table_of_content.md: -------------------------------------------------------------------------------- 1 | # Contents 2 | 3 | * [Installation](installation.md) 4 | * [Update](update.md) 5 | * [Configuration](configuration.md) 6 | * [Configuring TOR](configuring_tor.md) 7 | * [Controlling](controlling.md) 8 | * [Mining](mining.md) 9 | * [Wallet](wallet.md) 10 | * [Developer resources](developer_resources.md) 11 | * [JSON RPC API](json_rpc_api.md) 12 | * [Code contribution guidelines](code_contribution_guidelines.md) 13 | * [Contact](contact.md) 14 | -------------------------------------------------------------------------------- /docs/contact.md: -------------------------------------------------------------------------------- 1 | # Contact 2 | 3 | ## IRC 4 | 5 | * [irc.freenode.net](irc://irc.freenode.net), channel `#btcd` 6 | 7 | ## Mailing Lists 8 | 9 | * [btcd](mailto:btcd+subscribe@opensource.conformal.com): discussion of btcd and its packages. 10 | * [btcd-commits](mailto:btcd-commits+subscribe@opensource.conformal.com): readonly mail-out of source code changes. 11 | 12 | ## Issue Tracker 13 | 14 | The [integrated github issue tracker](https://github.com/btcsuite/btcd/issues) 15 | is used for this project. 16 | -------------------------------------------------------------------------------- /txscript/consensus.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package txscript 6 | 7 | const ( 8 | // LockTimeThreshold is the number below which a lock time is 9 | // interpreted to be a block number. Since an average of one block 10 | // is generated per 10 minutes, this allows blocks for about 9,512 11 | // years. 12 | LockTimeThreshold = 5e8 // Tue Nov 5 00:53:20 1985 UTC 13 | ) 14 | -------------------------------------------------------------------------------- /connmgr/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package connmgr implements a generic Bitcoin network connection manager. 7 | 8 | Connection Manager Overview 9 | 10 | Connection Manager handles all the general connection concerns such as 11 | maintaining a set number of outbound connections, sourcing peers, banning, 12 | limiting max connections, tor lookup, etc. 13 | */ 14 | package connmgr 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Temp files 2 | *~ 3 | 4 | # Databases 5 | btcd.db 6 | *-shm 7 | *-wal 8 | 9 | # Log files 10 | *.log 11 | 12 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 13 | *.o 14 | *.a 15 | *.so 16 | 17 | # Folders 18 | _obj 19 | _test 20 | vendor 21 | 22 | # Architecture specific extensions/prefixes 23 | *.[568vq] 24 | [568vq].out 25 | 26 | *.cgo1.go 27 | *.cgo2.c 28 | _cgo_defun.c 29 | _cgo_gotypes.go 30 | _cgo_export.* 31 | 32 | _testmain.go 33 | 34 | *.exe 35 | 36 | # Code coverage files 37 | profile.tmp 38 | profile.cov 39 | -------------------------------------------------------------------------------- /rpcclient/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This is the list of people who have contributed code to the repository. 2 | # 3 | # Names should be added to this file only after verifying that the individual 4 | # or the individual's organization has agreed to the LICENSE. 5 | # 6 | # Names should be added to this file like so: 7 | # Name 8 | 9 | Dave Collins 10 | Geert-Johan Riemer 11 | Josh Rickmar 12 | Michalis Kargakis 13 | Ruben de Vries /dev/null 2>&1 11 | if [ $? -ne 0 ]; then 12 | echo >&2 "This script requires the gocov tool." 13 | echo >&2 "You may obtain it with the following command:" 14 | echo >&2 "go get github.com/axw/gocov/gocov" 15 | exit 1 16 | fi 17 | gocov test | gocov report 18 | -------------------------------------------------------------------------------- /netsync/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package netsync implements a concurrency safe block syncing protocol. The 7 | SyncManager communicates with connected peers to perform an initial block 8 | download, keep the chain and unconfirmed transaction pool in sync, and announce 9 | new blocks connected to the chain. Currently the sync manager selects a single 10 | sync peer that it downloads all blocks from until it is up to date with the 11 | longest chain the sync peer is aware of. 12 | */ 13 | package netsync 14 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/btcsuite/btcd 2 | 3 | require ( 4 | github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f 5 | github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce 6 | github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd 7 | github.com/btcsuite/goleveldb v1.0.0 8 | github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 9 | github.com/btcsuite/winsvc v1.0.0 10 | github.com/davecgh/go-spew v1.1.1 11 | github.com/decred/dcrd/lru v1.0.0 12 | github.com/jessevdk/go-flags v1.4.0 13 | github.com/jrick/logrotate v1.0.0 14 | golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 15 | ) 16 | 17 | go 1.14 18 | -------------------------------------------------------------------------------- /btcjson/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This is the list of people who have contributed code to the repository. 2 | # 3 | # Names should be added to this file only after verifying that the individual 4 | # or the individual's organization has agreed to the LICENSE. 5 | # 6 | # Names should be added to this file like so: 7 | # Name 8 | 9 | John C. Vernaleo 10 | Dave Collins 11 | Owain G. Ainsworth 12 | David Hill 13 | Josh Rickmar 14 | Andreas Metsälä 15 | Francis Lam 16 | Geert-Johan Riemer 17 | -------------------------------------------------------------------------------- /mining/README.md: -------------------------------------------------------------------------------- 1 | mining 2 | ====== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/mining) 7 | 8 | ## Overview 9 | 10 | This package is currently a work in progress. 11 | 12 | ## Installation and Updating 13 | 14 | ```bash 15 | $ go get -u github.com/btcsuite/btcd/mining 16 | ``` 17 | 18 | ## License 19 | 20 | Package mining is licensed under the [copyfree](http://copyfree.org) ISC 21 | License. 22 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /database/export_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | This test file is part of the database package rather than than the 7 | database_test package so it can bridge access to the internals to properly test 8 | cases which are either not possible or can't reliably be tested via the public 9 | interface. The functions, constants, and variables are only exported while the 10 | tests are being run. 11 | */ 12 | 13 | package database 14 | 15 | // TstNumErrorCodes makes the internal numErrorCodes parameter available to the 16 | // test package. 17 | const TstNumErrorCodes = numErrorCodes 18 | -------------------------------------------------------------------------------- /btcjson/chainsvrwsresults.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2017 The btcsuite developers 2 | // Copyright (c) 2015-2017 The Decred developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package btcjson 7 | 8 | // SessionResult models the data from the session command. 9 | type SessionResult struct { 10 | SessionID uint64 `json:"sessionid"` 11 | } 12 | 13 | // RescannedBlock contains the hash and all discovered transactions of a single 14 | // rescanned block. 15 | // 16 | // NOTE: This is a btcsuite extension ported from 17 | // github.com/decred/dcrd/dcrjson. 18 | type RescannedBlock struct { 19 | Hash string `json:"hash"` 20 | Transactions []string `json:"transactions"` 21 | } 22 | -------------------------------------------------------------------------------- /integration/rpctest/doc.go: -------------------------------------------------------------------------------- 1 | // Package rpctest provides a btcd-specific RPC testing harness crafting and 2 | // executing integration tests by driving a `btcd` instance via the `RPC` 3 | // interface. Each instance of an active harness comes equipped with a simple 4 | // in-memory HD wallet capable of properly syncing to the generated chain, 5 | // creating new addresses, and crafting fully signed transactions paying to an 6 | // arbitrary set of outputs. 7 | // 8 | // This package was designed specifically to act as an RPC testing harness for 9 | // `btcd`. However, the constructs presented are general enough to be adapted to 10 | // any project wishing to programmatically drive a `btcd` instance of its 11 | // systems/integration tests. 12 | package rpctest 13 | -------------------------------------------------------------------------------- /goclean.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # The script does automatic checking on a Go package and its sub-packages, including: 3 | # 1. gofmt (http://golang.org/cmd/gofmt/) 4 | # 3. go vet (http://golang.org/cmd/vet) 5 | # 4. gosimple (https://github.com/dominikh/go-simple) 6 | # 5. unconvert (https://github.com/mdempsky/unconvert) 7 | # 6. race detector (http://blog.golang.org/race-detector) 8 | # 7. test coverage (http://blog.golang.org/cover) 9 | 10 | set -ex 11 | 12 | env GORACE="halt_on_error=1" go test -race -tags="rpctest" -covermode atomic -coverprofile=profile.cov ./... 13 | 14 | # Automatic checks 15 | golangci-lint run --deadline=10m --disable-all \ 16 | --enable=gofmt \ 17 | --enable=vet \ 18 | --enable=gosimple \ 19 | --enable=unconvert 20 | -------------------------------------------------------------------------------- /addrmgr/internal_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package addrmgr 6 | 7 | import ( 8 | "time" 9 | 10 | "github.com/btcsuite/btcd/wire" 11 | ) 12 | 13 | func TstKnownAddressIsBad(ka *KnownAddress) bool { 14 | return ka.isBad() 15 | } 16 | 17 | func TstKnownAddressChance(ka *KnownAddress) float64 { 18 | return ka.chance() 19 | } 20 | 21 | func TstNewKnownAddress(na *wire.NetAddress, attempts int, 22 | lastattempt, lastsuccess time.Time, tried bool, refs int) *KnownAddress { 23 | return &KnownAddress{na: na, attempts: attempts, lastattempt: lastattempt, 24 | lastsuccess: lastsuccess, tried: tried, refs: refs} 25 | } 26 | -------------------------------------------------------------------------------- /blockchain/merkle_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | import ( 8 | "testing" 9 | 10 | "github.com/btcsuite/btcutil" 11 | ) 12 | 13 | // TestMerkle tests the BuildMerkleTreeStore API. 14 | func TestMerkle(t *testing.T) { 15 | block := btcutil.NewBlock(&Block100000) 16 | merkles := BuildMerkleTreeStore(block.Transactions(), false) 17 | calculatedMerkleRoot := merkles[len(merkles)-1] 18 | wantMerkle := &Block100000.Header.MerkleRoot 19 | if !wantMerkle.IsEqual(calculatedMerkleRoot) { 20 | t.Errorf("BuildMerkleTreeStore: merkle root mismatch - "+ 21 | "got %v, want %v", calculatedMerkleRoot, wantMerkle) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /btcjson/btcdextresults.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 The btcsuite developers 2 | // Copyright (c) 2015-2017 The Decred developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package btcjson 7 | 8 | // VersionResult models objects included in the version response. In the actual 9 | // result, these objects are keyed by the program or API name. 10 | // 11 | // NOTE: This is a btcsuite extension ported from 12 | // github.com/decred/dcrd/dcrjson. 13 | type VersionResult struct { 14 | VersionString string `json:"versionstring"` 15 | Major uint32 `json:"major"` 16 | Minor uint32 `json:"minor"` 17 | Patch uint32 `json:"patch"` 18 | Prerelease string `json:"prerelease"` 19 | BuildMetadata string `json:"buildmetadata"` 20 | } 21 | -------------------------------------------------------------------------------- /blockchain/bench_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | import ( 8 | "testing" 9 | 10 | "github.com/btcsuite/btcutil" 11 | ) 12 | 13 | // BenchmarkIsCoinBase performs a simple benchmark against the IsCoinBase 14 | // function. 15 | func BenchmarkIsCoinBase(b *testing.B) { 16 | tx, _ := btcutil.NewBlock(&Block100000).Tx(1) 17 | b.ResetTimer() 18 | for i := 0; i < b.N; i++ { 19 | IsCoinBase(tx) 20 | } 21 | } 22 | 23 | // BenchmarkIsCoinBaseTx performs a simple benchmark against the IsCoinBaseTx 24 | // function. 25 | func BenchmarkIsCoinBaseTx(b *testing.B) { 26 | tx := Block100000.Transactions[1] 27 | b.ResetTimer() 28 | for i := 0; i < b.N; i++ { 29 | IsCoinBaseTx(tx) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2013-2017 The btcsuite developers 4 | Copyright (c) 2015-2016 The Decred developers 5 | 6 | Permission to use, copy, modify, and distribute this software for any 7 | purpose with or without fee is hereby granted, provided that the above 8 | copyright notice and this permission notice appear in all copies. 9 | 10 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 | -------------------------------------------------------------------------------- /rpcclient/cookiefile.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The Namecoin developers 2 | // Copyright (c) 2019 The btcsuite developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package rpcclient 7 | 8 | import ( 9 | "bufio" 10 | "fmt" 11 | "os" 12 | "strings" 13 | ) 14 | 15 | func readCookieFile(path string) (username, password string, err error) { 16 | f, err := os.Open(path) 17 | if err != nil { 18 | return 19 | } 20 | defer f.Close() 21 | 22 | scanner := bufio.NewScanner(f) 23 | scanner.Scan() 24 | err = scanner.Err() 25 | if err != nil { 26 | return 27 | } 28 | s := scanner.Text() 29 | 30 | parts := strings.SplitN(s, ":", 2) 31 | if len(parts) != 2 { 32 | err = fmt.Errorf("malformed cookie file") 33 | return 34 | } 35 | 36 | username, password = parts[0], parts[1] 37 | return 38 | } 39 | -------------------------------------------------------------------------------- /mining/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package mining 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until UseLogger is called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | } 31 | -------------------------------------------------------------------------------- /blockchain/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until UseLogger is called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | } 31 | -------------------------------------------------------------------------------- /mining/cpuminer/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package cpuminer 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until UseLogger is called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | } 31 | -------------------------------------------------------------------------------- /netsync/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package netsync 6 | 7 | import "github.com/btcsuite/btclog" 8 | 9 | // log is a logger that is initialized with no output filters. This 10 | // means the package will not perform any logging by default until the caller 11 | // requests it. 12 | var log btclog.Logger 13 | 14 | // DisableLog disables all library log output. Logging output is disabled 15 | // by default until either UseLogger or SetLogWriter are called. 16 | func DisableLog() { 17 | log = btclog.Disabled 18 | } 19 | 20 | // UseLogger uses a specified Logger to output package logging info. 21 | // This should be used in preference to SetLogWriter if the caller is also 22 | // using btclog. 23 | func UseLogger(logger btclog.Logger) { 24 | log = logger 25 | } 26 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/controlling.md: -------------------------------------------------------------------------------- 1 | # Controlling and querying btcd via btcctl 2 | 3 | btcctl is a command line utility that can be used to both control and query btcd 4 | via [RPC](http://www.wikipedia.org/wiki/Remote_procedure_call). btcd does 5 | **not** enable its RPC server by default; You must configure at minimum both an 6 | RPC username and password or both an RPC limited username and password: 7 | 8 | * btcd.conf configuration file 9 | 10 | ```bash 11 | [Application Options] 12 | rpcuser=myuser 13 | rpcpass=SomeDecentp4ssw0rd 14 | rpclimituser=mylimituser 15 | rpclimitpass=Limitedp4ssw0rd 16 | ``` 17 | 18 | * btcctl.conf configuration file 19 | 20 | ```bash 21 | [Application Options] 22 | rpcuser=myuser 23 | rpcpass=SomeDecentp4ssw0rd 24 | ``` 25 | 26 | OR 27 | 28 | ```bash 29 | [Application Options] 30 | rpclimituser=mylimituser 31 | rpclimitpass=Limitedp4ssw0rd 32 | ``` 33 | 34 | For a list of available options, run: `$ btcctl --help` 35 | -------------------------------------------------------------------------------- /mining/cpuminer/README.md: -------------------------------------------------------------------------------- 1 | cpuminer 2 | ======== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/mining/cpuminer) 7 | ======= 8 | 9 | ## Overview 10 | 11 | This package is currently a work in progress. It works without issue since it 12 | is used in several of the integration tests, but the API is not really ready for 13 | public consumption as it has simply been refactored out of the main codebase for 14 | now. 15 | 16 | ## Installation and Updating 17 | 18 | ```bash 19 | $ go get -u github.com/btcsuite/btcd/mining/cpuminer 20 | ``` 21 | 22 | ## License 23 | 24 | Package cpuminer is licensed under the [copyfree](http://copyfree.org) ISC 25 | License. 26 | -------------------------------------------------------------------------------- /blockchain/timesorter.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | // timeSorter implements sort.Interface to allow a slice of timestamps to 8 | // be sorted. 9 | type timeSorter []int64 10 | 11 | // Len returns the number of timestamps in the slice. It is part of the 12 | // sort.Interface implementation. 13 | func (s timeSorter) Len() int { 14 | return len(s) 15 | } 16 | 17 | // Swap swaps the timestamps at the passed indices. It is part of the 18 | // sort.Interface implementation. 19 | func (s timeSorter) Swap(i, j int) { 20 | s[i], s[j] = s[j], s[i] 21 | } 22 | 23 | // Less returns whether the timstamp with index i should sort before the 24 | // timestamp with index j. It is part of the sort.Interface implementation. 25 | func (s timeSorter) Less(i, j int) bool { 26 | return s[i] < s[j] 27 | } 28 | -------------------------------------------------------------------------------- /rpcclient/examples/bitcoincorehttpbulk/README.md: -------------------------------------------------------------------------------- 1 | Bitcoin Core Batch HTTP POST Example 2 | ============================== 3 | 4 | This example shows how to use the rpclient package to connect to a Bitcoin Core RPC server using HTTP POST and batch JSON-RPC mode with TLS disabled. 5 | 6 | ## Running the Example 7 | 8 | The first step is to use `go get` to download and install the rpcclient package: 9 | 10 | ```bash 11 | $ go get github.com/btcsuite/btcd/rpcclient 12 | ``` 13 | 14 | Next, modify the `main.go` source to specify the correct RPC username and 15 | password for the RPC server: 16 | 17 | ```Go 18 | User: "yourrpcuser", 19 | Pass: "yourrpcpass", 20 | ``` 21 | 22 | Finally, navigate to the example's directory and run it with: 23 | 24 | ```bash 25 | $ cd $GOPATH/src/github.com/btcsuite/btcd/rpcclient/examples/bitcoincorehttp 26 | $ go run *.go 27 | ``` 28 | 29 | ## License 30 | 31 | This example is licensed under the [copyfree](http://copyfree.org) ISC License. 32 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test 2 | on: [push, pull_request] 3 | jobs: 4 | build: 5 | name: Go CI 6 | runs-on: ubuntu-latest 7 | strategy: 8 | matrix: 9 | go: [1.14, 1.15] 10 | steps: 11 | - name: Set up Go 12 | uses: actions/setup-go@v2 13 | with: 14 | go-version: ${{ matrix.go }} 15 | - name: Check out source 16 | uses: actions/checkout@v2 17 | - name: Install Linters 18 | run: "curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.26.0" 19 | - name: Build 20 | env: 21 | GO111MODULE: "on" 22 | run: go build ./... 23 | - name: Test 24 | env: 25 | GO111MODULE: "on" 26 | run: | 27 | sh ./goclean.sh 28 | 29 | - name: Send coverage 30 | uses: shogo82148/actions-goveralls@v1 31 | with: 32 | path-to-profile: profile.cov 33 | -------------------------------------------------------------------------------- /rpcclient/examples/bitcoincorehttp/README.md: -------------------------------------------------------------------------------- 1 | Bitcoin Core HTTP POST Example 2 | ============================== 3 | 4 | This example shows how to use the rpcclient package to connect to a Bitcoin 5 | Core RPC server using HTTP POST mode with TLS disabled and gets the current 6 | block count. 7 | 8 | ## Running the Example 9 | 10 | The first step is to use `go get` to download and install the rpcclient package: 11 | 12 | ```bash 13 | $ go get github.com/btcsuite/btcd/rpcclient 14 | ``` 15 | 16 | Next, modify the `main.go` source to specify the correct RPC username and 17 | password for the RPC server: 18 | 19 | ```Go 20 | User: "yourrpcuser", 21 | Pass: "yourrpcpass", 22 | ``` 23 | 24 | Finally, navigate to the example's directory and run it with: 25 | 26 | ```bash 27 | $ cd $GOPATH/src/github.com/btcsuite/btcd/rpcclient/examples/bitcoincorehttp 28 | $ go run *.go 29 | ``` 30 | 31 | ## License 32 | 33 | This example is licensed under the [copyfree](http://copyfree.org) ISC License. 34 | -------------------------------------------------------------------------------- /connmgr/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package connmgr 6 | 7 | import "github.com/btcsuite/btclog" 8 | 9 | // log is a logger that is initialized with no output filters. This 10 | // means the package will not perform any logging by default until the caller 11 | // requests it. 12 | var log btclog.Logger 13 | 14 | // The default amount of logging is none. 15 | func init() { 16 | DisableLog() 17 | } 18 | 19 | // DisableLog disables all library log output. Logging output is disabled 20 | // by default until either UseLogger or SetLogWriter are called. 21 | func DisableLog() { 22 | log = btclog.Disabled 23 | } 24 | 25 | // UseLogger uses a specified Logger to output package logging info. 26 | // This should be used in preference to SetLogWriter if the caller is also 27 | // using btclog. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | } 31 | -------------------------------------------------------------------------------- /blockchain/indexers/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package indexers 6 | 7 | import "github.com/btcsuite/btclog" 8 | 9 | // log is a logger that is initialized with no output filters. This 10 | // means the package will not perform any logging by default until the caller 11 | // requests it. 12 | var log btclog.Logger 13 | 14 | // The default amount of logging is none. 15 | func init() { 16 | DisableLog() 17 | } 18 | 19 | // DisableLog disables all library log output. Logging output is disabled 20 | // by default until either UseLogger or SetLogWriter are called. 21 | func DisableLog() { 22 | log = btclog.Disabled 23 | } 24 | 25 | // UseLogger uses a specified Logger to output package logging info. 26 | // This should be used in preference to SetLogWriter if the caller is also 27 | // using btclog. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | } 31 | -------------------------------------------------------------------------------- /addrmgr/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package addrmgr 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until either UseLogger or SetLogWriter are called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | // This should be used in preference to SetLogWriter if the caller is also 29 | // using btclog. 30 | func UseLogger(logger btclog.Logger) { 31 | log = logger 32 | } 33 | -------------------------------------------------------------------------------- /btcec/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package btcec implements support for the elliptic curves needed for bitcoin. 7 | 8 | Bitcoin uses elliptic curve cryptography using koblitz curves 9 | (specifically secp256k1) for cryptographic functions. See 10 | http://www.secg.org/collateral/sec2_final.pdf for details on the 11 | standard. 12 | 13 | This package provides the data structures and functions implementing the 14 | crypto/elliptic Curve interface in order to permit using these curves 15 | with the standard crypto/ecdsa package provided with go. Helper 16 | functionality is provided to parse signatures and public keys from 17 | standard formats. It was designed for use with btcd, but should be 18 | general enough for other uses of elliptic curve crypto. It was originally based 19 | on some initial work by ThePiachu, but has significantly diverged since then. 20 | */ 21 | package btcec 22 | -------------------------------------------------------------------------------- /chaincfg/chainhash/hashfuncs.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 The Decred developers 2 | // Copyright (c) 2016-2017 The btcsuite developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package chainhash 7 | 8 | import "crypto/sha256" 9 | 10 | // HashB calculates hash(b) and returns the resulting bytes. 11 | func HashB(b []byte) []byte { 12 | hash := sha256.Sum256(b) 13 | return hash[:] 14 | } 15 | 16 | // HashH calculates hash(b) and returns the resulting bytes as a Hash. 17 | func HashH(b []byte) Hash { 18 | return Hash(sha256.Sum256(b)) 19 | } 20 | 21 | // DoubleHashB calculates hash(hash(b)) and returns the resulting bytes. 22 | func DoubleHashB(b []byte) []byte { 23 | first := sha256.Sum256(b) 24 | second := sha256.Sum256(first[:]) 25 | return second[:] 26 | } 27 | 28 | // DoubleHashH calculates hash(hash(b)) and returns the resulting bytes as a 29 | // Hash. 30 | func DoubleHashH(b []byte) Hash { 31 | first := sha256.Sum256(b) 32 | return Hash(sha256.Sum256(first[:])) 33 | } 34 | -------------------------------------------------------------------------------- /database/ffldb/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package ffldb implements a driver for the database package that uses leveldb 7 | for the backing metadata and flat files for block storage. 8 | 9 | This driver is the recommended driver for use with btcd. It makes use leveldb 10 | for the metadata, flat files for block storage, and checksums in key areas to 11 | ensure data integrity. 12 | 13 | Usage 14 | 15 | This package is a driver to the database package and provides the database type 16 | of "ffldb". The parameters the Open and Create functions take are the 17 | database path as a string and the block network: 18 | 19 | db, err := database.Open("ffldb", "path/to/database", wire.MainNet) 20 | if err != nil { 21 | // Handle error 22 | } 23 | 24 | db, err := database.Create("ffldb", "path/to/database", wire.MainNet) 25 | if err != nil { 26 | // Handle error 27 | } 28 | */ 29 | package ffldb 30 | -------------------------------------------------------------------------------- /database/ffldb/export_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | This test file is part of the ffldb package rather than than the ffldb_test 7 | package so it can bridge access to the internals to properly test cases which 8 | are either not possible or can't reliably be tested via the public interface. 9 | The functions are only exported while the tests are being run. 10 | */ 11 | 12 | package ffldb 13 | 14 | import "github.com/btcsuite/btcd/database" 15 | 16 | // TstRunWithMaxBlockFileSize runs the passed function with the maximum allowed 17 | // file size for the database set to the provided value. The value will be set 18 | // back to the original value upon completion. 19 | func TstRunWithMaxBlockFileSize(idb database.DB, size uint32, fn func()) { 20 | ffldb := idb.(*db) 21 | origSize := ffldb.store.maxBlockFileSize 22 | 23 | ffldb.store.maxBlockFileSize = size 24 | fn() 25 | ffldb.store.maxBlockFileSize = origSize 26 | } 27 | -------------------------------------------------------------------------------- /database/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package database 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until UseLogger is called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | 31 | // Update the logger for the registered drivers. 32 | for _, drv := range drivers { 33 | if drv.UseLogger != nil { 34 | drv.UseLogger(logger) 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /netsync/README.md: -------------------------------------------------------------------------------- 1 | netsync 2 | ======= 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/netsync) 7 | 8 | ## Overview 9 | 10 | This package implements a concurrency safe block syncing protocol. The 11 | SyncManager communicates with connected peers to perform an initial block 12 | download, keep the chain and unconfirmed transaction pool in sync, and announce 13 | new blocks connected to the chain. Currently the sync manager selects a single 14 | sync peer that it downloads all blocks from until it is up to date with the 15 | longest chain the sync peer is aware of. 16 | 17 | ## Installation and Updating 18 | 19 | ```bash 20 | $ go get -u github.com/btcsuite/btcd/netsync 21 | ``` 22 | 23 | ## License 24 | 25 | Package netsync is licensed under the [copyfree](http://copyfree.org) ISC License. 26 | -------------------------------------------------------------------------------- /blockchain/fullblocktests/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package fullblocktests provides a set of block consensus validation tests. 7 | 8 | All of the generated test instances involve full blocks that are to be used for 9 | testing the consensus validation rules. The tests are intended to be flexible 10 | enough to allow both unit-style tests directly against the blockchain code as 11 | well as integration style tests over the peer-to-peer network. To achieve that 12 | goal, each test contains additional information about the expected result, 13 | however that information can be ignored when doing comparison tests between two 14 | independent versions over the peer-to-peer network. 15 | 16 | This package has intentionally been designed so it can be used as a standalone 17 | package for any projects needing to test their implementation against a full set 18 | of blocks that exercise the consensus validation rules. 19 | */ 20 | package fullblocktests 21 | -------------------------------------------------------------------------------- /rpcclient/examples/bitcoincorehttp/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "log" 9 | 10 | "github.com/btcsuite/btcd/rpcclient" 11 | ) 12 | 13 | func main() { 14 | // Connect to local bitcoin core RPC server using HTTP POST mode. 15 | connCfg := &rpcclient.ConnConfig{ 16 | Host: "localhost:8332", 17 | User: "yourrpcuser", 18 | Pass: "yourrpcpass", 19 | HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode 20 | DisableTLS: true, // Bitcoin core does not provide TLS by default 21 | } 22 | // Notice the notification parameter is nil since notifications are 23 | // not supported in HTTP POST mode. 24 | client, err := rpcclient.New(connCfg, nil) 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | defer client.Shutdown() 29 | 30 | // Get the current block count. 31 | blockCount, err := client.GetBlockCount() 32 | if err != nil { 33 | log.Fatal(err) 34 | } 35 | log.Printf("Block count: %d", blockCount) 36 | } 37 | -------------------------------------------------------------------------------- /rpcclient/examples/btcdwebsockets/README.md: -------------------------------------------------------------------------------- 1 | btcd Websockets Example 2 | ======================= 3 | 4 | This example shows how to use the rpcclient package to connect to a btcd RPC 5 | server using TLS-secured websockets, register for block connected and block 6 | disconnected notifications, and get the current block count. 7 | 8 | This example also sets a timer to shutdown the client after 10 seconds to 9 | demonstrate clean shutdown. 10 | 11 | ## Running the Example 12 | 13 | The first step is to use `go get` to download and install the rpcclient package: 14 | 15 | ```bash 16 | $ go get github.com/btcsuite/btcd/rpcclient 17 | ``` 18 | 19 | Next, modify the `main.go` source to specify the correct RPC username and 20 | password for the RPC server: 21 | 22 | ```Go 23 | User: "yourrpcuser", 24 | Pass: "yourrpcpass", 25 | ``` 26 | 27 | Finally, navigate to the example's directory and run it with: 28 | 29 | ```bash 30 | $ cd $GOPATH/src/github.com/btcsuite/btcd/rpcclient/examples/btcdwebsockets 31 | $ go run *.go 32 | ``` 33 | 34 | ## License 35 | 36 | This example is licensed under the [copyfree](http://copyfree.org) ISC License. 37 | -------------------------------------------------------------------------------- /docs/mining.md: -------------------------------------------------------------------------------- 1 | # Mining 2 | 3 | btcd supports the `getblocktemplate` RPC. 4 | The limited user cannot access this RPC. 5 | 6 | ## Add the payment addresses with the `miningaddr` option 7 | 8 | ```bash 9 | [Application Options] 10 | rpcuser=myuser 11 | rpcpass=SomeDecentp4ssw0rd 12 | miningaddr=12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX 13 | miningaddr=1M83ju3EChKYyysmM2FXtLNftbacagd8FR 14 | ``` 15 | 16 | ## Add btcd's RPC TLS certificate to system Certificate Authority list 17 | 18 | `cgminer` uses [curl](http://curl.haxx.se/) to fetch data from the RPC server. 19 | Since curl validates the certificate by default, we must install the `btcd` RPC 20 | certificate into the default system Certificate Authority list. 21 | 22 | ## Ubuntu 23 | 24 | 1. Copy rpc.cert to /usr/share/ca-certificates: `# cp /home/user/.btcd/rpc.cert /usr/share/ca-certificates/btcd.crt` 25 | 2. Add btcd.crt to /etc/ca-certificates.conf: `# echo btcd.crt >> /etc/ca-certificates.conf` 26 | 3. Update the CA certificate list: `# update-ca-certificates` 27 | 28 | ## Set your mining software url to use https 29 | 30 | `cgminer -o https://127.0.0.1:8334 -u rpcuser -p rpcpassword` 31 | -------------------------------------------------------------------------------- /rpcclient/examples/btcwalletwebsockets/README.md: -------------------------------------------------------------------------------- 1 | btcwallet Websockets Example 2 | ============================ 3 | 4 | This example shows how to use the rpcclient package to connect to a btcwallet 5 | RPC server using TLS-secured websockets, register for notifications about 6 | changes to account balances, and get a list of unspent transaction outputs 7 | (utxos) the wallet can sign. 8 | 9 | This example also sets a timer to shutdown the client after 10 seconds to 10 | demonstrate clean shutdown. 11 | 12 | ## Running the Example 13 | 14 | The first step is to use `go get` to download and install the rpcclient package: 15 | 16 | ```bash 17 | $ go get github.com/btcsuite/btcd/rpcclient 18 | ``` 19 | 20 | Next, modify the `main.go` source to specify the correct RPC username and 21 | password for the RPC server: 22 | 23 | ```Go 24 | User: "yourrpcuser", 25 | Pass: "yourrpcpass", 26 | ``` 27 | 28 | Finally, navigate to the example's directory and run it with: 29 | 30 | ```bash 31 | $ cd $GOPATH/src/github.com/btcsuite/btcd/rpcclient/examples/btcwalletwebsockets 32 | $ go run *.go 33 | ``` 34 | 35 | ## License 36 | 37 | This example is licensed under the [copyfree](http://copyfree.org) ISC License. 38 | -------------------------------------------------------------------------------- /mempool/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package mempool 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until either UseLogger or SetLogWriter are called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | // This should be used in preference to SetLogWriter if the caller is also 29 | // using btclog. 30 | func UseLogger(logger btclog.Logger) { 31 | log = logger 32 | } 33 | 34 | // pickNoun returns the singular or plural form of a noun depending 35 | // on the count n. 36 | func pickNoun(n int, singular, plural string) string { 37 | if n == 1 { 38 | return singular 39 | } 40 | return plural 41 | } 42 | -------------------------------------------------------------------------------- /wire/error.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | // MessageError describes an issue with a message. 12 | // An example of some potential issues are messages from the wrong bitcoin 13 | // network, invalid commands, mismatched checksums, and exceeding max payloads. 14 | // 15 | // This provides a mechanism for the caller to type assert the error to 16 | // differentiate between general io errors such as io.EOF and issues that 17 | // resulted from malformed messages. 18 | type MessageError struct { 19 | Func string // Function name 20 | Description string // Human readable description of the issue 21 | } 22 | 23 | // Error satisfies the error interface and prints human-readable errors. 24 | func (e *MessageError) Error() string { 25 | if e.Func != "" { 26 | return fmt.Sprintf("%v: %v", e.Func, e.Description) 27 | } 28 | return e.Description 29 | } 30 | 31 | // messageError creates an error for the given function and description. 32 | func messageError(f string, desc string) *MessageError { 33 | return &MessageError{Func: f, Description: desc} 34 | } 35 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # This Dockerfile builds btcd from source and creates a small (55 MB) docker container based on alpine linux. 2 | # 3 | # Clone this repository and run the following command to build and tag a fresh btcd amd64 container: 4 | # 5 | # docker build . -t yourregistry/btcd 6 | # 7 | # You can use the following command to buid an arm64v8 container: 8 | # 9 | # docker build . -t yourregistry/btcd --build-arg ARCH=arm64v8 10 | # 11 | # For more information how to use this docker image visit: 12 | # https://github.com/btcsuite/btcd/tree/master/docs 13 | # 14 | # 8333 Mainnet Bitcoin peer-to-peer port 15 | # 8334 Mainet RPC port 16 | 17 | ARG ARCH=amd64 18 | 19 | FROM golang:1.14-alpine3.12 AS build-container 20 | 21 | ARG ARCH 22 | ENV GO111MODULE=on 23 | 24 | ADD . /app 25 | WORKDIR /app 26 | RUN set -ex \ 27 | && if [ "${ARCH}" = "amd64" ]; then export GOARCH=amd64; fi \ 28 | && if [ "${ARCH}" = "arm32v7" ]; then export GOARCH=arm; fi \ 29 | && if [ "${ARCH}" = "arm64v8" ]; then export GOARCH=arm64; fi \ 30 | && echo "Compiling for $GOARCH" \ 31 | && go install -v . ./cmd/... 32 | 33 | FROM $ARCH/alpine:3.12 34 | 35 | COPY --from=build-container /go/bin /bin 36 | 37 | VOLUME ["/root/.btcd"] 38 | 39 | EXPOSE 8333 8334 40 | 41 | ENTRYPOINT ["btcd"] 42 | -------------------------------------------------------------------------------- /limits/limits_unix.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !windows,!plan9 6 | 7 | package limits 8 | 9 | import ( 10 | "fmt" 11 | "syscall" 12 | ) 13 | 14 | const ( 15 | fileLimitWant = 2048 16 | fileLimitMin = 1024 17 | ) 18 | 19 | // SetLimits raises some process limits to values which allow btcd and 20 | // associated utilities to run. 21 | func SetLimits() error { 22 | var rLimit syscall.Rlimit 23 | 24 | err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) 25 | if err != nil { 26 | return err 27 | } 28 | if rLimit.Cur > fileLimitWant { 29 | return nil 30 | } 31 | if rLimit.Max < fileLimitMin { 32 | err = fmt.Errorf("need at least %v file descriptors", 33 | fileLimitMin) 34 | return err 35 | } 36 | if rLimit.Max < fileLimitWant { 37 | rLimit.Cur = rLimit.Max 38 | } else { 39 | rLimit.Cur = fileLimitWant 40 | } 41 | err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) 42 | if err != nil { 43 | // try min value 44 | rLimit.Cur = fileLimitMin 45 | err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) 46 | if err != nil { 47 | return err 48 | } 49 | } 50 | 51 | return nil 52 | } 53 | -------------------------------------------------------------------------------- /txscript/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package txscript 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until UseLogger is called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | } 31 | 32 | // LogClosure is a closure that can be printed with %v to be used to 33 | // generate expensive-to-create data for a detailed log level and avoid doing 34 | // the work if the data isn't printed. 35 | type logClosure func() string 36 | 37 | func (c logClosure) String() string { 38 | return c() 39 | } 40 | 41 | func newLogClosure(c func() string) logClosure { 42 | return logClosure(c) 43 | } 44 | -------------------------------------------------------------------------------- /blockchain/indexers/README.md: -------------------------------------------------------------------------------- 1 | indexers 2 | ======== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://pkg.go.dev/github.com/btcsuite/btcd/blockchain/indexers?status.png)](https://pkg.go.dev/github.com/btcsuite/btcd/blockchain/indexers) 7 | 8 | Package indexers implements optional block chain indexes. 9 | 10 | These indexes are typically used to enhance the amount of information available 11 | via an RPC interface. 12 | 13 | ## Supported Indexers 14 | 15 | - Transaction-by-hash (txbyhashidx) Index 16 | - Creates a mapping from the hash of each transaction to the block that 17 | contains it along with its offset and length within the serialized block 18 | - Transaction-by-address (txbyaddridx) Index 19 | - Creates a mapping from every address to all transactions which either credit 20 | or debit the address 21 | - Requires the transaction-by-hash index 22 | 23 | ## Installation 24 | 25 | ```bash 26 | $ go get -u github.com/btcsuite/btcd/blockchain/indexers 27 | ``` 28 | 29 | ## License 30 | 31 | Package indexers is licensed under the [copyfree](http://copyfree.org) ISC 32 | License. 33 | -------------------------------------------------------------------------------- /integration/rpctest/README.md: -------------------------------------------------------------------------------- 1 | rpctest 2 | ======= 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/integration/rpctest) 7 | 8 | Package rpctest provides a btcd-specific RPC testing harness crafting and 9 | executing integration tests by driving a `btcd` instance via the `RPC` 10 | interface. Each instance of an active harness comes equipped with a simple 11 | in-memory HD wallet capable of properly syncing to the generated chain, 12 | creating new addresses, and crafting fully signed transactions paying to an 13 | arbitrary set of outputs. 14 | 15 | This package was designed specifically to act as an RPC testing harness for 16 | `btcd`. However, the constructs presented are general enough to be adapted to 17 | any project wishing to programmatically drive a `btcd` instance of its 18 | systems/integration tests. 19 | 20 | ## Installation and Updating 21 | 22 | ```bash 23 | $ go get -u github.com/btcsuite/btcd/integration/rpctest 24 | ``` 25 | 26 | ## License 27 | 28 | Package rpctest is licensed under the [copyfree](http://copyfree.org) ISC 29 | License. 30 | 31 | -------------------------------------------------------------------------------- /netsync/interface.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package netsync 6 | 7 | import ( 8 | "github.com/btcsuite/btcd/blockchain" 9 | "github.com/btcsuite/btcd/chaincfg" 10 | "github.com/btcsuite/btcd/chaincfg/chainhash" 11 | "github.com/btcsuite/btcd/mempool" 12 | "github.com/btcsuite/btcd/peer" 13 | "github.com/btcsuite/btcd/wire" 14 | "github.com/btcsuite/btcutil" 15 | ) 16 | 17 | // PeerNotifier exposes methods to notify peers of status changes to 18 | // transactions, blocks, etc. Currently server (in the main package) implements 19 | // this interface. 20 | type PeerNotifier interface { 21 | AnnounceNewTransactions(newTxs []*mempool.TxDesc) 22 | 23 | UpdatePeerHeights(latestBlkHash *chainhash.Hash, latestHeight int32, updateSource *peer.Peer) 24 | 25 | RelayInventory(invVect *wire.InvVect, data interface{}) 26 | 27 | TransactionConfirmed(tx *btcutil.Tx) 28 | } 29 | 30 | // Config is a configuration struct used to initialize a new SyncManager. 31 | type Config struct { 32 | PeerNotifier PeerNotifier 33 | Chain *blockchain.BlockChain 34 | TxMemPool *mempool.TxPool 35 | ChainParams *chaincfg.Params 36 | 37 | DisableCheckpoints bool 38 | MaxPeers int 39 | 40 | FeeEstimator *mempool.FeeEstimator 41 | } 42 | -------------------------------------------------------------------------------- /blockchain/scriptval_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | import ( 8 | "fmt" 9 | "testing" 10 | 11 | "github.com/btcsuite/btcd/txscript" 12 | ) 13 | 14 | // TestCheckBlockScripts ensures that validating the all of the scripts in a 15 | // known-good block doesn't return an error. 16 | func TestCheckBlockScripts(t *testing.T) { 17 | testBlockNum := 277647 18 | blockDataFile := fmt.Sprintf("%d.dat.bz2", testBlockNum) 19 | blocks, err := loadBlocks(blockDataFile) 20 | if err != nil { 21 | t.Errorf("Error loading file: %v\n", err) 22 | return 23 | } 24 | if len(blocks) > 1 { 25 | t.Errorf("The test block file must only have one block in it") 26 | return 27 | } 28 | if len(blocks) == 0 { 29 | t.Errorf("The test block file may not be empty") 30 | return 31 | } 32 | 33 | storeDataFile := fmt.Sprintf("%d.utxostore.bz2", testBlockNum) 34 | view, err := loadUtxoView(storeDataFile) 35 | if err != nil { 36 | t.Errorf("Error loading txstore: %v\n", err) 37 | return 38 | } 39 | 40 | scriptFlags := txscript.ScriptBip16 41 | err = checkBlockScripts(blocks[0], view, scriptFlags, nil, nil) 42 | if err != nil { 43 | t.Errorf("Transaction script validation failed: %v\n", err) 44 | return 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /btcjson/chainsvrwsresults_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Copyright (c) 2017 The Decred developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package btcjson_test 7 | 8 | import ( 9 | "encoding/json" 10 | "testing" 11 | 12 | "github.com/btcsuite/btcd/btcjson" 13 | ) 14 | 15 | // TestChainSvrWsResults ensures any results that have custom marshalling 16 | // work as inteded. 17 | func TestChainSvrWsResults(t *testing.T) { 18 | t.Parallel() 19 | 20 | tests := []struct { 21 | name string 22 | result interface{} 23 | expected string 24 | }{ 25 | { 26 | name: "RescannedBlock", 27 | result: &btcjson.RescannedBlock{ 28 | Hash: "blockhash", 29 | Transactions: []string{"serializedtx"}, 30 | }, 31 | expected: `{"hash":"blockhash","transactions":["serializedtx"]}`, 32 | }, 33 | } 34 | 35 | t.Logf("Running %d tests", len(tests)) 36 | for i, test := range tests { 37 | marshalled, err := json.Marshal(test.result) 38 | if err != nil { 39 | t.Errorf("Test #%d (%s) unexpected error: %v", i, 40 | test.name, err) 41 | continue 42 | } 43 | if string(marshalled) != test.expected { 44 | t.Errorf("Test #%d (%s) unexpected marhsalled data - "+ 45 | "got %s, want %s", i, test.name, marshalled, 46 | test.expected) 47 | continue 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /blockchain/fullblocktests/README.md: -------------------------------------------------------------------------------- 1 | fullblocktests 2 | ============== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/blockchain/fullblocktests) 7 | 8 | Package fullblocktests provides a set of full block tests to be used for testing 9 | the consensus validation rules. The tests are intended to be flexible enough to 10 | allow both unit-style tests directly against the blockchain code as well as 11 | integration style tests over the peer-to-peer network. To achieve that goal, 12 | each test contains additional information about the expected result, however 13 | that information can be ignored when doing comparison tests between two 14 | independent versions over the peer-to-peer network. 15 | 16 | This package has intentionally been designed so it can be used as a standalone 17 | package for any projects needing to test their implementation against a full set 18 | of blocks that exercise the consensus validation rules. 19 | 20 | ## Installation and Updating 21 | 22 | ```bash 23 | $ go get -u github.com/btcsuite/btcd/blockchain/fullblocktests 24 | ``` 25 | 26 | ## License 27 | 28 | Package fullblocktests is licensed under the [copyfree](http://copyfree.org) ISC 29 | License. 30 | -------------------------------------------------------------------------------- /database/ffldb/README.md: -------------------------------------------------------------------------------- 1 | ffldb 2 | ===== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://pkg.go.dev/github.com/btcsuite/btcd/database/ffldb?status.png)](https://pkg.go.dev/github.com/btcsuite/btcd/database/ffldb) 7 | ======= 8 | 9 | Package ffldb implements a driver for the database package that uses leveldb for 10 | the backing metadata and flat files for block storage. 11 | 12 | This driver is the recommended driver for use with btcd. It makes use leveldb 13 | for the metadata, flat files for block storage, and checksums in key areas to 14 | ensure data integrity. 15 | 16 | Package ffldb is licensed under the copyfree ISC license. 17 | 18 | ## Usage 19 | 20 | This package is a driver to the database package and provides the database type 21 | of "ffldb". The parameters the Open and Create functions take are the 22 | database path as a string and the block network. 23 | 24 | ```Go 25 | db, err := database.Open("ffldb", "path/to/database", wire.MainNet) 26 | if err != nil { 27 | // Handle error 28 | } 29 | ``` 30 | 31 | ```Go 32 | db, err := database.Create("ffldb", "path/to/database", wire.MainNet) 33 | if err != nil { 34 | // Handle error 35 | } 36 | ``` 37 | 38 | ## License 39 | 40 | Package ffldb is licensed under the [copyfree](http://copyfree.org) ISC 41 | License. 42 | -------------------------------------------------------------------------------- /rpcclient/examples/bitcoincorehttpbulk/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2020 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "log" 10 | 11 | "github.com/btcsuite/btcd/rpcclient" 12 | ) 13 | 14 | func main() { 15 | // Connect to local bitcoin core RPC server using HTTP POST mode. 16 | connCfg := &rpcclient.ConnConfig{ 17 | Host: "localhost:8332", 18 | User: "yourrpcuser", 19 | Pass: "yourrpcpass", 20 | DisableConnectOnNew: true, 21 | HTTPPostMode: true, // Bitcoin core only supports HTTP POST mode 22 | DisableTLS: true, // Bitcoin core does not provide TLS by default 23 | } 24 | batchClient, err := rpcclient.NewBatch(connCfg) 25 | defer batchClient.Shutdown() 26 | 27 | if err != nil { 28 | log.Fatal(err) 29 | } 30 | 31 | // batch mode requires async requests 32 | blockCount := batchClient.GetBlockCountAsync() 33 | block1 := batchClient.GetBlockHashAsync(1) 34 | batchClient.GetBlockHashAsync(2) 35 | batchClient.GetBlockHashAsync(3) 36 | block4 := batchClient.GetBlockHashAsync(4) 37 | difficulty := batchClient.GetDifficultyAsync() 38 | 39 | // sends all queued batch requests 40 | batchClient.Send() 41 | 42 | fmt.Println(blockCount.Receive()) 43 | fmt.Println(block1.Receive()) 44 | fmt.Println(block4.Receive()) 45 | fmt.Println(difficulty.Receive()) 46 | } 47 | -------------------------------------------------------------------------------- /chaincfg/chainhash/README.md: -------------------------------------------------------------------------------- 1 | chainhash 2 | ========= 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/chaincfg/chainhash) 7 | ======= 8 | 9 | chainhash provides a generic hash type and associated functions that allows the 10 | specific hash algorithm to be abstracted. 11 | 12 | ## Installation and Updating 13 | 14 | ```bash 15 | $ go get -u github.com/btcsuite/btcd/chaincfg/chainhash 16 | ``` 17 | 18 | ## GPG Verification Key 19 | 20 | All official release tags are signed by Conformal so users can ensure the code 21 | has not been tampered with and is coming from the btcsuite developers. To 22 | verify the signature perform the following: 23 | 24 | - Download the public key from the Conformal website at 25 | https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt 26 | 27 | - Import the public key into your GPG keyring: 28 | ```bash 29 | gpg --import GIT-GPG-KEY-conformal.txt 30 | ``` 31 | 32 | - Verify the release tag with the following command where `TAG_NAME` is a 33 | placeholder for the specific tag: 34 | ```bash 35 | git tag -v TAG_NAME 36 | ``` 37 | 38 | ## License 39 | 40 | Package chainhash is licensed under the [copyfree](http://copyfree.org) ISC 41 | License. 42 | -------------------------------------------------------------------------------- /btcec/privkey_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcec 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | ) 11 | 12 | func TestPrivKeys(t *testing.T) { 13 | tests := []struct { 14 | name string 15 | key []byte 16 | }{ 17 | { 18 | name: "check curve", 19 | key: []byte{ 20 | 0xea, 0xf0, 0x2c, 0xa3, 0x48, 0xc5, 0x24, 0xe6, 21 | 0x39, 0x26, 0x55, 0xba, 0x4d, 0x29, 0x60, 0x3c, 22 | 0xd1, 0xa7, 0x34, 0x7d, 0x9d, 0x65, 0xcf, 0xe9, 23 | 0x3c, 0xe1, 0xeb, 0xff, 0xdc, 0xa2, 0x26, 0x94, 24 | }, 25 | }, 26 | } 27 | 28 | for _, test := range tests { 29 | priv, pub := PrivKeyFromBytes(S256(), test.key) 30 | 31 | _, err := ParsePubKey(pub.SerializeUncompressed(), S256()) 32 | if err != nil { 33 | t.Errorf("%s privkey: %v", test.name, err) 34 | continue 35 | } 36 | 37 | hash := []byte{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9} 38 | sig, err := priv.Sign(hash) 39 | if err != nil { 40 | t.Errorf("%s could not sign: %v", test.name, err) 41 | continue 42 | } 43 | 44 | if !sig.Verify(hash, pub) { 45 | t.Errorf("%s could not verify: %v", test.name, err) 46 | continue 47 | } 48 | 49 | serializedKey := priv.Serialize() 50 | if !bytes.Equal(serializedKey, test.key) { 51 | t.Errorf("%s unexpected serialized bytes - got: %x, "+ 52 | "want: %x", test.name, serializedKey, test.key) 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /wire/msgsendaddrv2.go: -------------------------------------------------------------------------------- 1 | package wire 2 | 3 | import ( 4 | "io" 5 | ) 6 | 7 | // MsgSendAddrV2 defines a bitcoin sendaddrv2 message which is used for a peer 8 | // to signal support for receiving ADDRV2 messages (BIP155). It implements the 9 | // Message interface. 10 | // 11 | // This message has no payload. 12 | type MsgSendAddrV2 struct{} 13 | 14 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 15 | // This is part of the Message interface implementation. 16 | func (msg *MsgSendAddrV2) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 17 | return nil 18 | } 19 | 20 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 21 | // This is part of the Message interface implementation. 22 | func (msg *MsgSendAddrV2) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 23 | return nil 24 | } 25 | 26 | // Command returns the protocol command string for the message. This is part 27 | // of the Message interface implementation. 28 | func (msg *MsgSendAddrV2) Command() string { 29 | return CmdSendAddrV2 30 | } 31 | 32 | // MaxPayloadLength returns the maximum length the payload can be for the 33 | // receiver. This is part of the Message interface implementation. 34 | func (msg *MsgSendAddrV2) MaxPayloadLength(pver uint32) uint32 { 35 | return 0 36 | } 37 | 38 | // NewMsgSendAddrV2 returns a new bitcoin sendaddrv2 message that conforms to the 39 | // Message interface. 40 | func NewMsgSendAddrV2() *MsgSendAddrV2 { 41 | return &MsgSendAddrV2{} 42 | } 43 | -------------------------------------------------------------------------------- /blockchain/timesorter_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | import ( 8 | "reflect" 9 | "sort" 10 | "testing" 11 | ) 12 | 13 | // TestTimeSorter tests the timeSorter implementation. 14 | func TestTimeSorter(t *testing.T) { 15 | tests := []struct { 16 | in []int64 17 | want []int64 18 | }{ 19 | { 20 | in: []int64{ 21 | 1351228575, // Fri Oct 26 05:16:15 UTC 2012 (Block #205000) 22 | 1348310759, // Sat Sep 22 10:45:59 UTC 2012 (Block #200000) 23 | 1305758502, // Wed May 18 22:41:42 UTC 2011 (Block #125000) 24 | 1347777156, // Sun Sep 16 06:32:36 UTC 2012 (Block #199000) 25 | 1349492104, // Sat Oct 6 02:55:04 UTC 2012 (Block #202000) 26 | }, 27 | want: []int64{ 28 | 1305758502, // Wed May 18 22:41:42 UTC 2011 (Block #125000) 29 | 1347777156, // Sun Sep 16 06:32:36 UTC 2012 (Block #199000) 30 | 1348310759, // Sat Sep 22 10:45:59 UTC 2012 (Block #200000) 31 | 1349492104, // Sat Oct 6 02:55:04 UTC 2012 (Block #202000) 32 | 1351228575, // Fri Oct 26 05:16:15 UTC 2012 (Block #205000) 33 | }, 34 | }, 35 | } 36 | 37 | for i, test := range tests { 38 | result := make([]int64, len(test.in)) 39 | copy(result, test.in) 40 | sort.Sort(timeSorter(result)) 41 | if !reflect.DeepEqual(result, test.want) { 42 | t.Errorf("timeSorter #%d got %v want %v", i, result, 43 | test.want) 44 | continue 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /blockchain/notifications_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | import ( 8 | "testing" 9 | 10 | "github.com/btcsuite/btcd/chaincfg" 11 | ) 12 | 13 | // TestNotifications ensures that notification callbacks are fired on events. 14 | func TestNotifications(t *testing.T) { 15 | blocks, err := loadBlocks("blk_0_to_4.dat.bz2") 16 | if err != nil { 17 | t.Fatalf("Error loading file: %v\n", err) 18 | } 19 | 20 | // Create a new database and chain instance to run tests against. 21 | chain, teardownFunc, err := chainSetup("notifications", 22 | &chaincfg.MainNetParams) 23 | if err != nil { 24 | t.Fatalf("Failed to setup chain instance: %v", err) 25 | } 26 | defer teardownFunc() 27 | 28 | notificationCount := 0 29 | callback := func(notification *Notification) { 30 | if notification.Type == NTBlockAccepted { 31 | notificationCount++ 32 | } 33 | } 34 | 35 | // Register callback multiple times then assert it is called that many 36 | // times. 37 | const numSubscribers = 3 38 | for i := 0; i < numSubscribers; i++ { 39 | chain.Subscribe(callback) 40 | } 41 | 42 | _, _, err = chain.ProcessBlock(blocks[1], BFNone) 43 | if err != nil { 44 | t.Fatalf("ProcessBlock fail on block 1: %v\n", err) 45 | } 46 | 47 | if notificationCount != numSubscribers { 48 | t.Fatalf("Expected notification callback to be executed %d "+ 49 | "times, found %d", numSubscribers, notificationCount) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /btcjson/btcdextresults_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 The btcsuite developers 2 | // Copyright (c) 2015-2016 The Decred developers 3 | // Use of this source code is governed by an ISC 4 | // license that can be found in the LICENSE file. 5 | 6 | package btcjson_test 7 | 8 | import ( 9 | "encoding/json" 10 | "testing" 11 | 12 | "github.com/btcsuite/btcd/btcjson" 13 | ) 14 | 15 | // TestBtcdExtCustomResults ensures any results that have custom marshalling 16 | // work as inteded. 17 | // and unmarshal code of results are as expected. 18 | func TestBtcdExtCustomResults(t *testing.T) { 19 | t.Parallel() 20 | 21 | tests := []struct { 22 | name string 23 | result interface{} 24 | expected string 25 | }{ 26 | { 27 | name: "versionresult", 28 | result: &btcjson.VersionResult{ 29 | VersionString: "1.0.0", 30 | Major: 1, 31 | Minor: 0, 32 | Patch: 0, 33 | Prerelease: "pr", 34 | BuildMetadata: "bm", 35 | }, 36 | expected: `{"versionstring":"1.0.0","major":1,"minor":0,"patch":0,"prerelease":"pr","buildmetadata":"bm"}`, 37 | }, 38 | } 39 | 40 | t.Logf("Running %d tests", len(tests)) 41 | for i, test := range tests { 42 | marshalled, err := json.Marshal(test.result) 43 | if err != nil { 44 | t.Errorf("Test #%d (%s) unexpected error: %v", i, 45 | test.name, err) 46 | continue 47 | } 48 | if string(marshalled) != test.expected { 49 | t.Errorf("Test #%d (%s) unexpected marhsalled data - "+ 50 | "got %s, want %s", i, test.name, marshalled, 51 | test.expected) 52 | continue 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /rpcclient/log.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package rpcclient 6 | 7 | import ( 8 | "github.com/btcsuite/btclog" 9 | ) 10 | 11 | // log is a logger that is initialized with no output filters. This 12 | // means the package will not perform any logging by default until the caller 13 | // requests it. 14 | var log btclog.Logger 15 | 16 | // The default amount of logging is none. 17 | func init() { 18 | DisableLog() 19 | } 20 | 21 | // DisableLog disables all library log output. Logging output is disabled 22 | // by default until UseLogger is called. 23 | func DisableLog() { 24 | log = btclog.Disabled 25 | } 26 | 27 | // UseLogger uses a specified Logger to output package logging info. 28 | func UseLogger(logger btclog.Logger) { 29 | log = logger 30 | } 31 | 32 | // LogClosure is a closure that can be printed with %v to be used to 33 | // generate expensive-to-create data for a detailed log level and avoid doing 34 | // the work if the data isn't printed. 35 | type logClosure func() string 36 | 37 | // String invokes the log closure and returns the results string. 38 | func (c logClosure) String() string { 39 | return c() 40 | } 41 | 42 | // newLogClosure returns a new closure over the passed function which allows 43 | // it to be used as a parameter in a logging function that is only invoked when 44 | // the logging level is such that the message will actually be logged. 45 | func newLogClosure(c func() string) logClosure { 46 | return logClosure(c) 47 | } 48 | -------------------------------------------------------------------------------- /connmgr/README.md: -------------------------------------------------------------------------------- 1 | connmgr 2 | ======= 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/connmgr) 7 | 8 | Package connmgr implements a generic Bitcoin network connection manager. 9 | 10 | ## Overview 11 | 12 | Connection Manager handles all the general connection concerns such as 13 | maintaining a set number of outbound connections, sourcing peers, banning, 14 | limiting max connections, tor lookup, etc. 15 | 16 | The package provides a generic connection manager which is able to accept 17 | connection requests from a source or a set of given addresses, dial them and 18 | notify the caller on connections. The main intended use is to initialize a pool 19 | of active connections and maintain them to remain connected to the P2P network. 20 | 21 | In addition the connection manager provides the following utilities: 22 | 23 | - Notifications on connections or disconnections 24 | - Handle failures and retry new addresses from the source 25 | - Connect only to specified addresses 26 | - Permanent connections with increasing backoff retry timers 27 | - Disconnect or Remove an established connection 28 | 29 | ## Installation and Updating 30 | 31 | ```bash 32 | $ go get -u github.com/btcsuite/btcd/connmgr 33 | ``` 34 | 35 | ## License 36 | 37 | Package connmgr is licensed under the [copyfree](http://copyfree.org) ISC License. 38 | -------------------------------------------------------------------------------- /database/internal/treap/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package treap implements a treap data structure that is used to hold ordered 7 | key/value pairs using a combination of binary search tree and heap semantics. 8 | It is a self-organizing and randomized data structure that doesn't require 9 | complex operations to to maintain balance. Search, insert, and delete 10 | operations are all O(log n). Both mutable and immutable variants are provided. 11 | 12 | The mutable variant is typically faster since it is able to simply update the 13 | treap when modifications are made. However, a mutable treap is not safe for 14 | concurrent access without careful use of locking by the caller and care must be 15 | taken when iterating since it can change out from under the iterator. 16 | 17 | The immutable variant works by creating a new version of the treap for all 18 | mutations by replacing modified nodes with new nodes that have updated values 19 | while sharing all unmodified nodes with the previous version. This is extremely 20 | useful in concurrent applications since the caller only has to atomically 21 | replace the treap pointer with the newly returned version after performing any 22 | mutations. All readers can simply use their existing pointer as a snapshot 23 | since the treap it points to is immutable. This effectively provides O(1) 24 | snapshot capability with efficient memory usage characteristics since the old 25 | nodes only remain allocated until there are no longer any references to them. 26 | */ 27 | package treap 28 | -------------------------------------------------------------------------------- /wire/msgverack.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | ) 10 | 11 | // MsgVerAck defines a bitcoin verack message which is used for a peer to 12 | // acknowledge a version message (MsgVersion) after it has used the information 13 | // to negotiate parameters. It implements the Message interface. 14 | // 15 | // This message has no payload. 16 | type MsgVerAck struct{} 17 | 18 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 19 | // This is part of the Message interface implementation. 20 | func (msg *MsgVerAck) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 21 | return nil 22 | } 23 | 24 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 25 | // This is part of the Message interface implementation. 26 | func (msg *MsgVerAck) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 27 | return nil 28 | } 29 | 30 | // Command returns the protocol command string for the message. This is part 31 | // of the Message interface implementation. 32 | func (msg *MsgVerAck) Command() string { 33 | return CmdVerAck 34 | } 35 | 36 | // MaxPayloadLength returns the maximum length the payload can be for the 37 | // receiver. This is part of the Message interface implementation. 38 | func (msg *MsgVerAck) MaxPayloadLength(pver uint32) uint32 { 39 | return 0 40 | } 41 | 42 | // NewMsgVerAck returns a new bitcoin verack message that conforms to the 43 | // Message interface. 44 | func NewMsgVerAck() *MsgVerAck { 45 | return &MsgVerAck{} 46 | } 47 | -------------------------------------------------------------------------------- /wire/msggetaddr.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | ) 10 | 11 | // MsgGetAddr implements the Message interface and represents a bitcoin 12 | // getaddr message. It is used to request a list of known active peers on the 13 | // network from a peer to help identify potential nodes. The list is returned 14 | // via one or more addr messages (MsgAddr). 15 | // 16 | // This message has no payload. 17 | type MsgGetAddr struct{} 18 | 19 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 20 | // This is part of the Message interface implementation. 21 | func (msg *MsgGetAddr) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 22 | return nil 23 | } 24 | 25 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 26 | // This is part of the Message interface implementation. 27 | func (msg *MsgGetAddr) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 28 | return nil 29 | } 30 | 31 | // Command returns the protocol command string for the message. This is part 32 | // of the Message interface implementation. 33 | func (msg *MsgGetAddr) Command() string { 34 | return CmdGetAddr 35 | } 36 | 37 | // MaxPayloadLength returns the maximum length the payload can be for the 38 | // receiver. This is part of the Message interface implementation. 39 | func (msg *MsgGetAddr) MaxPayloadLength(pver uint32) uint32 { 40 | return 0 41 | } 42 | 43 | // NewMsgGetAddr returns a new bitcoin getaddr message that conforms to the 44 | // Message interface. See MsgGetAddr for details. 45 | func NewMsgGetAddr() *MsgGetAddr { 46 | return &MsgGetAddr{} 47 | } 48 | -------------------------------------------------------------------------------- /wire/protocol_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import "testing" 8 | 9 | // TestServiceFlagStringer tests the stringized output for service flag types. 10 | func TestServiceFlagStringer(t *testing.T) { 11 | tests := []struct { 12 | in ServiceFlag 13 | want string 14 | }{ 15 | {0, "0x0"}, 16 | {SFNodeNetwork, "SFNodeNetwork"}, 17 | {SFNodeGetUTXO, "SFNodeGetUTXO"}, 18 | {SFNodeBloom, "SFNodeBloom"}, 19 | {SFNodeWitness, "SFNodeWitness"}, 20 | {SFNodeXthin, "SFNodeXthin"}, 21 | {SFNodeBit5, "SFNodeBit5"}, 22 | {SFNodeCF, "SFNodeCF"}, 23 | {SFNode2X, "SFNode2X"}, 24 | {0xffffffff, "SFNodeNetwork|SFNodeGetUTXO|SFNodeBloom|SFNodeWitness|SFNodeXthin|SFNodeBit5|SFNodeCF|SFNode2X|0xffffff00"}, 25 | } 26 | 27 | t.Logf("Running %d tests", len(tests)) 28 | for i, test := range tests { 29 | result := test.in.String() 30 | if result != test.want { 31 | t.Errorf("String #%d\n got: %s want: %s", i, result, 32 | test.want) 33 | continue 34 | } 35 | } 36 | } 37 | 38 | // TestBitcoinNetStringer tests the stringized output for bitcoin net types. 39 | func TestBitcoinNetStringer(t *testing.T) { 40 | tests := []struct { 41 | in BitcoinNet 42 | want string 43 | }{ 44 | {MainNet, "MainNet"}, 45 | {TestNet, "TestNet"}, 46 | {TestNet3, "TestNet3"}, 47 | {SimNet, "SimNet"}, 48 | {0xffffffff, "Unknown BitcoinNet (4294967295)"}, 49 | } 50 | 51 | t.Logf("Running %d tests", len(tests)) 52 | for i, test := range tests { 53 | result := test.in.String() 54 | if result != test.want { 55 | t.Errorf("String #%d\n got: %s want: %s", i, result, 56 | test.want) 57 | continue 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /database/cmd/dbtool/fetchblock.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "encoding/hex" 9 | "errors" 10 | "time" 11 | 12 | "github.com/btcsuite/btcd/chaincfg/chainhash" 13 | "github.com/btcsuite/btcd/database" 14 | ) 15 | 16 | // fetchBlockCmd defines the configuration options for the fetchblock command. 17 | type fetchBlockCmd struct{} 18 | 19 | var ( 20 | // fetchBlockCfg defines the configuration options for the command. 21 | fetchBlockCfg = fetchBlockCmd{} 22 | ) 23 | 24 | // Execute is the main entry point for the command. It's invoked by the parser. 25 | func (cmd *fetchBlockCmd) Execute(args []string) error { 26 | // Setup the global config options and ensure they are valid. 27 | if err := setupGlobalConfig(); err != nil { 28 | return err 29 | } 30 | 31 | if len(args) < 1 { 32 | return errors.New("required block hash parameter not specified") 33 | } 34 | blockHash, err := chainhash.NewHashFromStr(args[0]) 35 | if err != nil { 36 | return err 37 | } 38 | 39 | // Load the block database. 40 | db, err := loadBlockDB() 41 | if err != nil { 42 | return err 43 | } 44 | defer db.Close() 45 | 46 | return db.View(func(tx database.Tx) error { 47 | log.Infof("Fetching block %s", blockHash) 48 | startTime := time.Now() 49 | blockBytes, err := tx.FetchBlock(blockHash) 50 | if err != nil { 51 | return err 52 | } 53 | log.Infof("Loaded block in %v", time.Since(startTime)) 54 | log.Infof("Block Hex: %s", hex.EncodeToString(blockBytes)) 55 | return nil 56 | }) 57 | } 58 | 59 | // Usage overrides the usage display for the command. 60 | func (cmd *fetchBlockCmd) Usage() string { 61 | return "" 62 | } 63 | -------------------------------------------------------------------------------- /wire/fakemessage_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import "io" 8 | 9 | // fakeMessage implements the Message interface and is used to force encode 10 | // errors in messages. 11 | type fakeMessage struct { 12 | command string 13 | payload []byte 14 | forceEncodeErr bool 15 | forceLenErr bool 16 | } 17 | 18 | // BtcDecode doesn't do anything. It just satisfies the wire.Message 19 | // interface. 20 | func (msg *fakeMessage) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 21 | return nil 22 | } 23 | 24 | // BtcEncode writes the payload field of the fake message or forces an error 25 | // if the forceEncodeErr flag of the fake message is set. It also satisfies the 26 | // wire.Message interface. 27 | func (msg *fakeMessage) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 28 | if msg.forceEncodeErr { 29 | err := &MessageError{ 30 | Func: "fakeMessage.BtcEncode", 31 | Description: "intentional error", 32 | } 33 | return err 34 | } 35 | 36 | _, err := w.Write(msg.payload) 37 | return err 38 | } 39 | 40 | // Command returns the command field of the fake message and satisfies the 41 | // Message interface. 42 | func (msg *fakeMessage) Command() string { 43 | return msg.command 44 | } 45 | 46 | // MaxPayloadLength returns the length of the payload field of fake message 47 | // or a smaller value if the forceLenErr flag of the fake message is set. It 48 | // satisfies the Message interface. 49 | func (msg *fakeMessage) MaxPayloadLength(pver uint32) uint32 { 50 | lenp := uint32(len(msg.payload)) 51 | if msg.forceLenErr { 52 | return lenp - 1 53 | } 54 | 55 | return lenp 56 | } 57 | -------------------------------------------------------------------------------- /blockchain/difficulty_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package blockchain 6 | 7 | import ( 8 | "math/big" 9 | "testing" 10 | ) 11 | 12 | // TestBigToCompact ensures BigToCompact converts big integers to the expected 13 | // compact representation. 14 | func TestBigToCompact(t *testing.T) { 15 | tests := []struct { 16 | in int64 17 | out uint32 18 | }{ 19 | {0, 0}, 20 | {-1, 25231360}, 21 | } 22 | 23 | for x, test := range tests { 24 | n := big.NewInt(test.in) 25 | r := BigToCompact(n) 26 | if r != test.out { 27 | t.Errorf("TestBigToCompact test #%d failed: got %d want %d\n", 28 | x, r, test.out) 29 | return 30 | } 31 | } 32 | } 33 | 34 | // TestCompactToBig ensures CompactToBig converts numbers using the compact 35 | // representation to the expected big intergers. 36 | func TestCompactToBig(t *testing.T) { 37 | tests := []struct { 38 | in uint32 39 | out int64 40 | }{ 41 | {10000000, 0}, 42 | } 43 | 44 | for x, test := range tests { 45 | n := CompactToBig(test.in) 46 | want := big.NewInt(test.out) 47 | if n.Cmp(want) != 0 { 48 | t.Errorf("TestCompactToBig test #%d failed: got %d want %d\n", 49 | x, n.Int64(), want.Int64()) 50 | return 51 | } 52 | } 53 | } 54 | 55 | // TestCalcWork ensures CalcWork calculates the expected work value from values 56 | // in compact representation. 57 | func TestCalcWork(t *testing.T) { 58 | tests := []struct { 59 | in uint32 60 | out int64 61 | }{ 62 | {10000000, 0}, 63 | } 64 | 65 | for x, test := range tests { 66 | bits := test.in 67 | 68 | r := CalcWork(bits) 69 | if r.Int64() != test.out { 70 | t.Errorf("TestCalcWork test #%d failed: got %v want %d\n", 71 | x, r.Int64(), test.out) 72 | return 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /btcjson/export_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcjson 6 | 7 | // TstHighestUsageFlagBit makes the internal highestUsageFlagBit parameter 8 | // available to the test package. 9 | var TstHighestUsageFlagBit = highestUsageFlagBit 10 | 11 | // TstNumErrorCodes makes the internal numErrorCodes parameter available to the 12 | // test package. 13 | var TstNumErrorCodes = numErrorCodes 14 | 15 | // TstAssignField makes the internal assignField function available to the test 16 | // package. 17 | var TstAssignField = assignField 18 | 19 | // TstFieldUsage makes the internal fieldUsage function available to the test 20 | // package. 21 | var TstFieldUsage = fieldUsage 22 | 23 | // TstReflectTypeToJSONType makes the internal reflectTypeToJSONType function 24 | // available to the test package. 25 | var TstReflectTypeToJSONType = reflectTypeToJSONType 26 | 27 | // TstResultStructHelp makes the internal resultStructHelp function available to 28 | // the test package. 29 | var TstResultStructHelp = resultStructHelp 30 | 31 | // TstReflectTypeToJSONExample makes the internal reflectTypeToJSONExample 32 | // function available to the test package. 33 | var TstReflectTypeToJSONExample = reflectTypeToJSONExample 34 | 35 | // TstResultTypeHelp makes the internal resultTypeHelp function available to the 36 | // test package. 37 | var TstResultTypeHelp = resultTypeHelp 38 | 39 | // TstArgHelp makes the internal argHelp function available to the test package. 40 | var TstArgHelp = argHelp 41 | 42 | // TestMethodHelp makes the internal methodHelp function available to the test 43 | // package. 44 | var TestMethodHelp = methodHelp 45 | 46 | // TstIsValidResultType makes the internal isValidResultType function available 47 | // to the test package. 48 | var TstIsValidResultType = isValidResultType 49 | -------------------------------------------------------------------------------- /wire/msgmempool_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "bytes" 9 | "testing" 10 | ) 11 | 12 | func TestMemPool(t *testing.T) { 13 | pver := ProtocolVersion 14 | enc := BaseEncoding 15 | 16 | // Ensure the command is expected value. 17 | wantCmd := "mempool" 18 | msg := NewMsgMemPool() 19 | if cmd := msg.Command(); cmd != wantCmd { 20 | t.Errorf("NewMsgMemPool: wrong command - got %v want %v", 21 | cmd, wantCmd) 22 | } 23 | 24 | // Ensure max payload is expected value. 25 | wantPayload := uint32(0) 26 | maxPayload := msg.MaxPayloadLength(pver) 27 | if maxPayload != wantPayload { 28 | t.Errorf("MaxPayloadLength: wrong max payload length for "+ 29 | "protocol version %d - got %v, want %v", pver, 30 | maxPayload, wantPayload) 31 | } 32 | 33 | // Test encode with latest protocol version. 34 | var buf bytes.Buffer 35 | err := msg.BtcEncode(&buf, pver, enc) 36 | if err != nil { 37 | t.Errorf("encode of MsgMemPool failed %v err <%v>", msg, err) 38 | } 39 | 40 | // Older protocol versions should fail encode since message didn't 41 | // exist yet. 42 | oldPver := BIP0035Version - 1 43 | err = msg.BtcEncode(&buf, oldPver, enc) 44 | if err == nil { 45 | s := "encode of MsgMemPool passed for old protocol version %v err <%v>" 46 | t.Errorf(s, msg, err) 47 | } 48 | 49 | // Test decode with latest protocol version. 50 | readmsg := NewMsgMemPool() 51 | err = readmsg.BtcDecode(&buf, pver, enc) 52 | if err != nil { 53 | t.Errorf("decode of MsgMemPool failed [%v] err <%v>", buf, err) 54 | } 55 | 56 | // Older protocol versions should fail decode since message didn't 57 | // exist yet. 58 | err = readmsg.BtcDecode(&buf, oldPver, enc) 59 | if err == nil { 60 | s := "decode of MsgMemPool passed for old protocol version %v err <%v>" 61 | t.Errorf(s, msg, err) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /integration/rpctest/btcd.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package rpctest 6 | 7 | import ( 8 | "fmt" 9 | "os/exec" 10 | "path/filepath" 11 | "runtime" 12 | "sync" 13 | ) 14 | 15 | var ( 16 | // compileMtx guards access to the executable path so that the project is 17 | // only compiled once. 18 | compileMtx sync.Mutex 19 | 20 | // executablePath is the path to the compiled executable. This is the empty 21 | // string until btcd is compiled. This should not be accessed directly; 22 | // instead use the function btcdExecutablePath(). 23 | executablePath string 24 | ) 25 | 26 | // btcdExecutablePath returns a path to the btcd executable to be used by 27 | // rpctests. To ensure the code tests against the most up-to-date version of 28 | // btcd, this method compiles btcd the first time it is called. After that, the 29 | // generated binary is used for subsequent test harnesses. The executable file 30 | // is not cleaned up, but since it lives at a static path in a temp directory, 31 | // it is not a big deal. 32 | func btcdExecutablePath() (string, error) { 33 | compileMtx.Lock() 34 | defer compileMtx.Unlock() 35 | 36 | // If btcd has already been compiled, just use that. 37 | if len(executablePath) != 0 { 38 | return executablePath, nil 39 | } 40 | 41 | testDir, err := baseDir() 42 | if err != nil { 43 | return "", err 44 | } 45 | 46 | // Build btcd and output an executable in a static temp path. 47 | outputPath := filepath.Join(testDir, "btcd") 48 | if runtime.GOOS == "windows" { 49 | outputPath += ".exe" 50 | } 51 | cmd := exec.Command( 52 | "go", "build", "-o", outputPath, "github.com/btcsuite/btcd", 53 | ) 54 | err = cmd.Run() 55 | if err != nil { 56 | return "", fmt.Errorf("Failed to build btcd: %v", err) 57 | } 58 | 59 | // Save executable path so future calls do not recompile. 60 | executablePath = outputPath 61 | return executablePath, nil 62 | } 63 | -------------------------------------------------------------------------------- /config_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | "regexp" 8 | "runtime" 9 | "testing" 10 | ) 11 | 12 | var ( 13 | rpcuserRegexp = regexp.MustCompile("(?m)^rpcuser=.+$") 14 | rpcpassRegexp = regexp.MustCompile("(?m)^rpcpass=.+$") 15 | ) 16 | 17 | func TestCreateDefaultConfigFile(t *testing.T) { 18 | // find out where the sample config lives 19 | _, path, _, ok := runtime.Caller(0) 20 | if !ok { 21 | t.Fatalf("Failed finding config file path") 22 | } 23 | sampleConfigFile := filepath.Join(filepath.Dir(path), "sample-btcd.conf") 24 | 25 | // Setup a temporary directory 26 | tmpDir, err := ioutil.TempDir("", "btcd") 27 | if err != nil { 28 | t.Fatalf("Failed creating a temporary directory: %v", err) 29 | } 30 | testpath := filepath.Join(tmpDir, "test.conf") 31 | 32 | // copy config file to location of btcd binary 33 | data, err := ioutil.ReadFile(sampleConfigFile) 34 | if err != nil { 35 | t.Fatalf("Failed reading sample config file: %v", err) 36 | } 37 | appPath, err := filepath.Abs(filepath.Dir(os.Args[0])) 38 | if err != nil { 39 | t.Fatalf("Failed obtaining app path: %v", err) 40 | } 41 | tmpConfigFile := filepath.Join(appPath, "sample-btcd.conf") 42 | err = ioutil.WriteFile(tmpConfigFile, data, 0644) 43 | if err != nil { 44 | t.Fatalf("Failed copying sample config file: %v", err) 45 | } 46 | 47 | // Clean-up 48 | defer func() { 49 | os.Remove(testpath) 50 | os.Remove(tmpConfigFile) 51 | os.Remove(tmpDir) 52 | }() 53 | 54 | err = createDefaultConfigFile(testpath) 55 | 56 | if err != nil { 57 | t.Fatalf("Failed to create a default config file: %v", err) 58 | } 59 | 60 | content, err := ioutil.ReadFile(testpath) 61 | if err != nil { 62 | t.Fatalf("Failed to read generated default config file: %v", err) 63 | } 64 | 65 | if !rpcuserRegexp.Match(content) { 66 | t.Error("Could not find rpcuser in generated default config file.") 67 | } 68 | 69 | if !rpcpassRegexp.Match(content) { 70 | t.Error("Could not find rpcpass in generated default config file.") 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /txscript/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package txscript implements the bitcoin transaction script language. 7 | 8 | A complete description of the script language used by bitcoin can be found at 9 | https://en.bitcoin.it/wiki/Script. The following only serves as a quick 10 | overview to provide information on how to use the package. 11 | 12 | This package provides data structures and functions to parse and execute 13 | bitcoin transaction scripts. 14 | 15 | Script Overview 16 | 17 | Bitcoin transaction scripts are written in a stack-base, FORTH-like language. 18 | 19 | The bitcoin script language consists of a number of opcodes which fall into 20 | several categories such pushing and popping data to and from the stack, 21 | performing basic and bitwise arithmetic, conditional branching, comparing 22 | hashes, and checking cryptographic signatures. Scripts are processed from left 23 | to right and intentionally do not provide loops. 24 | 25 | The vast majority of Bitcoin scripts at the time of this writing are of several 26 | standard forms which consist of a spender providing a public key and a signature 27 | which proves the spender owns the associated private key. This information 28 | is used to prove the the spender is authorized to perform the transaction. 29 | 30 | One benefit of using a scripting language is added flexibility in specifying 31 | what conditions must be met in order to spend bitcoins. 32 | 33 | Errors 34 | 35 | Errors returned by this package are of type txscript.Error. This allows the 36 | caller to programmatically determine the specific error by examining the 37 | ErrorCode field of the type asserted txscript.Error while still providing rich 38 | error messages with contextual information. A convenience function named 39 | IsErrorCode is also provided to allow callers to easily check for a specific 40 | error code. See ErrorCode in the package documentation for a full list. 41 | */ 42 | package txscript 43 | -------------------------------------------------------------------------------- /btcec/genprecomps.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | // This file is ignored during the regular build due to the following build tag. 6 | // It is called by go generate and used to automatically generate pre-computed 7 | // tables used to accelerate operations. 8 | // +build ignore 9 | 10 | package main 11 | 12 | import ( 13 | "bytes" 14 | "compress/zlib" 15 | "encoding/base64" 16 | "fmt" 17 | "log" 18 | "os" 19 | 20 | "github.com/btcsuite/btcd/btcec" 21 | ) 22 | 23 | func main() { 24 | fi, err := os.Create("secp256k1.go") 25 | if err != nil { 26 | log.Fatal(err) 27 | } 28 | defer fi.Close() 29 | 30 | // Compress the serialized byte points. 31 | serialized := btcec.S256().SerializedBytePoints() 32 | var compressed bytes.Buffer 33 | w := zlib.NewWriter(&compressed) 34 | if _, err := w.Write(serialized); err != nil { 35 | fmt.Println(err) 36 | os.Exit(1) 37 | } 38 | w.Close() 39 | 40 | // Encode the compressed byte points with base64. 41 | encoded := make([]byte, base64.StdEncoding.EncodedLen(compressed.Len())) 42 | base64.StdEncoding.Encode(encoded, compressed.Bytes()) 43 | 44 | fmt.Fprintln(fi, "// Copyright (c) 2015 The btcsuite developers") 45 | fmt.Fprintln(fi, "// Use of this source code is governed by an ISC") 46 | fmt.Fprintln(fi, "// license that can be found in the LICENSE file.") 47 | fmt.Fprintln(fi) 48 | fmt.Fprintln(fi, "package btcec") 49 | fmt.Fprintln(fi) 50 | fmt.Fprintln(fi, "// Auto-generated file (see genprecomps.go)") 51 | fmt.Fprintln(fi, "// DO NOT EDIT") 52 | fmt.Fprintln(fi) 53 | fmt.Fprintf(fi, "var secp256k1BytePoints = %q\n", string(encoded)) 54 | 55 | a1, b1, a2, b2 := btcec.S256().EndomorphismVectors() 56 | fmt.Println("The following values are the computed linearly " + 57 | "independent vectors needed to make use of the secp256k1 " + 58 | "endomorphism:") 59 | fmt.Printf("a1: %x\n", a1) 60 | fmt.Printf("b1: %x\n", b1) 61 | fmt.Printf("a2: %x\n", a2) 62 | fmt.Printf("b2: %x\n", b2) 63 | } 64 | -------------------------------------------------------------------------------- /addrmgr/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | /* 6 | Package addrmgr implements concurrency safe Bitcoin address manager. 7 | 8 | Address Manager Overview 9 | 10 | In order maintain the peer-to-peer Bitcoin network, there needs to be a source 11 | of addresses to connect to as nodes come and go. The Bitcoin protocol provides 12 | the getaddr and addr messages to allow peers to communicate known addresses with 13 | each other. However, there needs to a mechanism to store those results and 14 | select peers from them. It is also important to note that remote peers can't 15 | be trusted to send valid peers nor attempt to provide you with only peers they 16 | control with malicious intent. 17 | 18 | With that in mind, this package provides a concurrency safe address manager for 19 | caching and selecting peers in a non-deterministic manner. The general idea is 20 | the caller adds addresses to the address manager and notifies it when addresses 21 | are connected, known good, and attempted. The caller also requests addresses as 22 | it needs them. 23 | 24 | The address manager internally segregates the addresses into groups and 25 | non-deterministically selects groups in a cryptographically random manner. This 26 | reduce the chances multiple addresses from the same nets are selected which 27 | generally helps provide greater peer diversity, and perhaps more importantly, 28 | drastically reduces the chances an attacker is able to coerce your peer into 29 | only connecting to nodes they control. 30 | 31 | The address manager also understands routability and Tor addresses and tries 32 | hard to only return routable addresses. In addition, it uses the information 33 | provided by the caller about connected, known good, and attempted addresses to 34 | periodically purge peers which no longer appear to be good peers as well as 35 | bias the selection toward known good peers. The general idea is to make a best 36 | effort at only providing usable addresses. 37 | */ 38 | package addrmgr 39 | -------------------------------------------------------------------------------- /wire/msgmempool.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | ) 11 | 12 | // MsgMemPool implements the Message interface and represents a bitcoin mempool 13 | // message. It is used to request a list of transactions still in the active 14 | // memory pool of a relay. 15 | // 16 | // This message has no payload and was not added until protocol versions 17 | // starting with BIP0035Version. 18 | type MsgMemPool struct{} 19 | 20 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 21 | // This is part of the Message interface implementation. 22 | func (msg *MsgMemPool) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 23 | if pver < BIP0035Version { 24 | str := fmt.Sprintf("mempool message invalid for protocol "+ 25 | "version %d", pver) 26 | return messageError("MsgMemPool.BtcDecode", str) 27 | } 28 | 29 | return nil 30 | } 31 | 32 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 33 | // This is part of the Message interface implementation. 34 | func (msg *MsgMemPool) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 35 | if pver < BIP0035Version { 36 | str := fmt.Sprintf("mempool message invalid for protocol "+ 37 | "version %d", pver) 38 | return messageError("MsgMemPool.BtcEncode", str) 39 | } 40 | 41 | return nil 42 | } 43 | 44 | // Command returns the protocol command string for the message. This is part 45 | // of the Message interface implementation. 46 | func (msg *MsgMemPool) Command() string { 47 | return CmdMemPool 48 | } 49 | 50 | // MaxPayloadLength returns the maximum length the payload can be for the 51 | // receiver. This is part of the Message interface implementation. 52 | func (msg *MsgMemPool) MaxPayloadLength(pver uint32) uint32 { 53 | return 0 54 | } 55 | 56 | // NewMsgMemPool returns a new bitcoin pong message that conforms to the Message 57 | // interface. See MsgPong for details. 58 | func NewMsgMemPool() *MsgMemPool { 59 | return &MsgMemPool{} 60 | } 61 | -------------------------------------------------------------------------------- /wire/msgfilterclear.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | ) 11 | 12 | // MsgFilterClear implements the Message interface and represents a bitcoin 13 | // filterclear message which is used to reset a Bloom filter. 14 | // 15 | // This message was not added until protocol version BIP0037Version and has 16 | // no payload. 17 | type MsgFilterClear struct{} 18 | 19 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 20 | // This is part of the Message interface implementation. 21 | func (msg *MsgFilterClear) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 22 | if pver < BIP0037Version { 23 | str := fmt.Sprintf("filterclear message invalid for protocol "+ 24 | "version %d", pver) 25 | return messageError("MsgFilterClear.BtcDecode", str) 26 | } 27 | 28 | return nil 29 | } 30 | 31 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 32 | // This is part of the Message interface implementation. 33 | func (msg *MsgFilterClear) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 34 | if pver < BIP0037Version { 35 | str := fmt.Sprintf("filterclear message invalid for protocol "+ 36 | "version %d", pver) 37 | return messageError("MsgFilterClear.BtcEncode", str) 38 | } 39 | 40 | return nil 41 | } 42 | 43 | // Command returns the protocol command string for the message. This is part 44 | // of the Message interface implementation. 45 | func (msg *MsgFilterClear) Command() string { 46 | return CmdFilterClear 47 | } 48 | 49 | // MaxPayloadLength returns the maximum length the payload can be for the 50 | // receiver. This is part of the Message interface implementation. 51 | func (msg *MsgFilterClear) MaxPayloadLength(pver uint32) uint32 { 52 | return 0 53 | } 54 | 55 | // NewMsgFilterClear returns a new bitcoin filterclear message that conforms to the Message 56 | // interface. See MsgFilterClear for details. 57 | func NewMsgFilterClear() *MsgFilterClear { 58 | return &MsgFilterClear{} 59 | } 60 | -------------------------------------------------------------------------------- /rpcserverhelp_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import "testing" 8 | 9 | // TestHelp ensures the help is reasonably accurate by checking that every 10 | // command specified also has result types defined and the one-line usage and 11 | // help text can be generated for them. 12 | func TestHelp(t *testing.T) { 13 | // Ensure there are result types specified for every handler. 14 | for k := range rpcHandlers { 15 | if _, ok := rpcResultTypes[k]; !ok { 16 | t.Errorf("RPC handler defined for method '%v' without "+ 17 | "also specifying result types", k) 18 | continue 19 | } 20 | 21 | } 22 | for k := range wsHandlers { 23 | if _, ok := rpcResultTypes[k]; !ok { 24 | t.Errorf("RPC handler defined for method '%v' without "+ 25 | "also specifying result types", k) 26 | continue 27 | } 28 | 29 | } 30 | 31 | // Ensure the usage for every command can be generated without errors. 32 | helpCacher := newHelpCacher() 33 | if _, err := helpCacher.rpcUsage(true); err != nil { 34 | t.Fatalf("Failed to generate one-line usage: %v", err) 35 | } 36 | if _, err := helpCacher.rpcUsage(true); err != nil { 37 | t.Fatalf("Failed to generate one-line usage (cached): %v", err) 38 | } 39 | 40 | // Ensure the help for every command can be generated without errors. 41 | for k := range rpcHandlers { 42 | if _, err := helpCacher.rpcMethodHelp(k); err != nil { 43 | t.Errorf("Failed to generate help for method '%v': %v", 44 | k, err) 45 | continue 46 | } 47 | if _, err := helpCacher.rpcMethodHelp(k); err != nil { 48 | t.Errorf("Failed to generate help for method '%v'"+ 49 | "(cached): %v", k, err) 50 | continue 51 | } 52 | } 53 | for k := range wsHandlers { 54 | if _, err := helpCacher.rpcMethodHelp(k); err != nil { 55 | t.Errorf("Failed to generate help for method '%v': %v", 56 | k, err) 57 | continue 58 | } 59 | if _, err := helpCacher.rpcMethodHelp(k); err != nil { 60 | t.Errorf("Failed to generate help for method '%v'"+ 61 | "(cached): %v", k, err) 62 | continue 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /database/internal/treap/README.md: -------------------------------------------------------------------------------- 1 | treap 2 | ===== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://pkg.go.dev/github.com/btcsuite/btcd/database/internal/treap?status.png)](https://pkg.go.dev/github.com/btcsuite/btcd/database/internal/treap) 7 | 8 | Package treap implements a treap data structure that is used to hold ordered 9 | key/value pairs using a combination of binary search tree and heap semantics. 10 | It is a self-organizing and randomized data structure that doesn't require 11 | complex operations to maintain balance. Search, insert, and delete 12 | operations are all O(log n). Both mutable and immutable variants are provided. 13 | 14 | The mutable variant is typically faster since it is able to simply update the 15 | treap when modifications are made. However, a mutable treap is not safe for 16 | concurrent access without careful use of locking by the caller and care must be 17 | taken when iterating since it can change out from under the iterator. 18 | 19 | The immutable variant works by creating a new version of the treap for all 20 | mutations by replacing modified nodes with new nodes that have updated values 21 | while sharing all unmodified nodes with the previous version. This is extremely 22 | useful in concurrent applications since the caller only has to atomically 23 | replace the treap pointer with the newly returned version after performing any 24 | mutations. All readers can simply use their existing pointer as a snapshot 25 | since the treap it points to is immutable. This effectively provides O(1) 26 | snapshot capability with efficient memory usage characteristics since the old 27 | nodes only remain allocated until there are no longer any references to them. 28 | 29 | Package treap is licensed under the copyfree ISC license. 30 | 31 | ## Usage 32 | 33 | This package is only used internally in the database code and as such is not 34 | available for use outside of it. 35 | 36 | ## License 37 | 38 | Package treap is licensed under the [copyfree](http://copyfree.org) ISC 39 | License. 40 | -------------------------------------------------------------------------------- /wire/msgsendheaders.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | ) 11 | 12 | // MsgSendHeaders implements the Message interface and represents a bitcoin 13 | // sendheaders message. It is used to request the peer send block headers 14 | // rather than inventory vectors. 15 | // 16 | // This message has no payload and was not added until protocol versions 17 | // starting with SendHeadersVersion. 18 | type MsgSendHeaders struct{} 19 | 20 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 21 | // This is part of the Message interface implementation. 22 | func (msg *MsgSendHeaders) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 23 | if pver < SendHeadersVersion { 24 | str := fmt.Sprintf("sendheaders message invalid for protocol "+ 25 | "version %d", pver) 26 | return messageError("MsgSendHeaders.BtcDecode", str) 27 | } 28 | 29 | return nil 30 | } 31 | 32 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 33 | // This is part of the Message interface implementation. 34 | func (msg *MsgSendHeaders) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 35 | if pver < SendHeadersVersion { 36 | str := fmt.Sprintf("sendheaders message invalid for protocol "+ 37 | "version %d", pver) 38 | return messageError("MsgSendHeaders.BtcEncode", str) 39 | } 40 | 41 | return nil 42 | } 43 | 44 | // Command returns the protocol command string for the message. This is part 45 | // of the Message interface implementation. 46 | func (msg *MsgSendHeaders) Command() string { 47 | return CmdSendHeaders 48 | } 49 | 50 | // MaxPayloadLength returns the maximum length the payload can be for the 51 | // receiver. This is part of the Message interface implementation. 52 | func (msg *MsgSendHeaders) MaxPayloadLength(pver uint32) uint32 { 53 | return 0 54 | } 55 | 56 | // NewMsgSendHeaders returns a new bitcoin sendheaders message that conforms to 57 | // the Message interface. See MsgSendHeaders for details. 58 | func NewMsgSendHeaders() *MsgSendHeaders { 59 | return &MsgSendHeaders{} 60 | } 61 | -------------------------------------------------------------------------------- /btcec/precompute.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcec 6 | 7 | import ( 8 | "compress/zlib" 9 | "encoding/base64" 10 | "encoding/binary" 11 | "io/ioutil" 12 | "strings" 13 | ) 14 | 15 | //go:generate go run -tags gensecp256k1 genprecomps.go 16 | 17 | // loadS256BytePoints decompresses and deserializes the pre-computed byte points 18 | // used to accelerate scalar base multiplication for the secp256k1 curve. This 19 | // approach is used since it allows the compile to use significantly less ram 20 | // and be performed much faster than it is with hard-coding the final in-memory 21 | // data structure. At the same time, it is quite fast to generate the in-memory 22 | // data structure at init time with this approach versus computing the table. 23 | func loadS256BytePoints() error { 24 | // There will be no byte points to load when generating them. 25 | bp := secp256k1BytePoints 26 | if len(bp) == 0 { 27 | return nil 28 | } 29 | 30 | // Decompress the pre-computed table used to accelerate scalar base 31 | // multiplication. 32 | decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(bp)) 33 | r, err := zlib.NewReader(decoder) 34 | if err != nil { 35 | return err 36 | } 37 | serialized, err := ioutil.ReadAll(r) 38 | if err != nil { 39 | return err 40 | } 41 | 42 | // Deserialize the precomputed byte points and set the curve to them. 43 | offset := 0 44 | var bytePoints [32][256][3]fieldVal 45 | for byteNum := 0; byteNum < 32; byteNum++ { 46 | // All points in this window. 47 | for i := 0; i < 256; i++ { 48 | px := &bytePoints[byteNum][i][0] 49 | py := &bytePoints[byteNum][i][1] 50 | pz := &bytePoints[byteNum][i][2] 51 | for i := 0; i < 10; i++ { 52 | px.n[i] = binary.LittleEndian.Uint32(serialized[offset:]) 53 | offset += 4 54 | } 55 | for i := 0; i < 10; i++ { 56 | py.n[i] = binary.LittleEndian.Uint32(serialized[offset:]) 57 | offset += 4 58 | } 59 | for i := 0; i < 10; i++ { 60 | pz.n[i] = binary.LittleEndian.Uint32(serialized[offset:]) 61 | offset += 4 62 | } 63 | } 64 | } 65 | secp256k1.bytePoints = &bytePoints 66 | return nil 67 | } 68 | -------------------------------------------------------------------------------- /database/ffldb/ldbtreapiter.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package ffldb 6 | 7 | import ( 8 | "github.com/btcsuite/btcd/database/internal/treap" 9 | "github.com/btcsuite/goleveldb/leveldb/iterator" 10 | "github.com/btcsuite/goleveldb/leveldb/util" 11 | ) 12 | 13 | // ldbTreapIter wraps a treap iterator to provide the additional functionality 14 | // needed to satisfy the leveldb iterator.Iterator interface. 15 | type ldbTreapIter struct { 16 | *treap.Iterator 17 | tx *transaction 18 | released bool 19 | } 20 | 21 | // Enforce ldbTreapIter implements the leveldb iterator.Iterator interface. 22 | var _ iterator.Iterator = (*ldbTreapIter)(nil) 23 | 24 | // Error is only provided to satisfy the iterator interface as there are no 25 | // errors for this memory-only structure. 26 | // 27 | // This is part of the leveldb iterator.Iterator interface implementation. 28 | func (iter *ldbTreapIter) Error() error { 29 | return nil 30 | } 31 | 32 | // SetReleaser is only provided to satisfy the iterator interface as there is no 33 | // need to override it. 34 | // 35 | // This is part of the leveldb iterator.Iterator interface implementation. 36 | func (iter *ldbTreapIter) SetReleaser(releaser util.Releaser) { 37 | } 38 | 39 | // Release releases the iterator by removing the underlying treap iterator from 40 | // the list of active iterators against the pending keys treap. 41 | // 42 | // This is part of the leveldb iterator.Iterator interface implementation. 43 | func (iter *ldbTreapIter) Release() { 44 | if !iter.released { 45 | iter.tx.removeActiveIter(iter.Iterator) 46 | iter.released = true 47 | } 48 | } 49 | 50 | // newLdbTreapIter creates a new treap iterator for the given slice against the 51 | // pending keys for the passed transaction and returns it wrapped in an 52 | // ldbTreapIter so it can be used as a leveldb iterator. It also adds the new 53 | // iterator to the list of active iterators for the transaction. 54 | func newLdbTreapIter(tx *transaction, slice *util.Range) *ldbTreapIter { 55 | iter := tx.pendingKeys.Iterator(slice.Start, slice.Limit) 56 | tx.addActiveIter(iter) 57 | return &ldbTreapIter{Iterator: iter, tx: tx} 58 | } 59 | -------------------------------------------------------------------------------- /wire/msgfeefilter.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | ) 11 | 12 | // MsgFeeFilter implements the Message interface and represents a bitcoin 13 | // feefilter message. It is used to request the receiving peer does not 14 | // announce any transactions below the specified minimum fee rate. 15 | // 16 | // This message was not added until protocol versions starting with 17 | // FeeFilterVersion. 18 | type MsgFeeFilter struct { 19 | MinFee int64 20 | } 21 | 22 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 23 | // This is part of the Message interface implementation. 24 | func (msg *MsgFeeFilter) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 25 | if pver < FeeFilterVersion { 26 | str := fmt.Sprintf("feefilter message invalid for protocol "+ 27 | "version %d", pver) 28 | return messageError("MsgFeeFilter.BtcDecode", str) 29 | } 30 | 31 | return readElement(r, &msg.MinFee) 32 | } 33 | 34 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 35 | // This is part of the Message interface implementation. 36 | func (msg *MsgFeeFilter) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 37 | if pver < FeeFilterVersion { 38 | str := fmt.Sprintf("feefilter message invalid for protocol "+ 39 | "version %d", pver) 40 | return messageError("MsgFeeFilter.BtcEncode", str) 41 | } 42 | 43 | return writeElement(w, msg.MinFee) 44 | } 45 | 46 | // Command returns the protocol command string for the message. This is part 47 | // of the Message interface implementation. 48 | func (msg *MsgFeeFilter) Command() string { 49 | return CmdFeeFilter 50 | } 51 | 52 | // MaxPayloadLength returns the maximum length the payload can be for the 53 | // receiver. This is part of the Message interface implementation. 54 | func (msg *MsgFeeFilter) MaxPayloadLength(pver uint32) uint32 { 55 | return 8 56 | } 57 | 58 | // NewMsgFeeFilter returns a new bitcoin feefilter message that conforms to 59 | // the Message interface. See MsgFeeFilter for details. 60 | func NewMsgFeeFilter(minfee int64) *MsgFeeFilter { 61 | return &MsgFeeFilter{ 62 | MinFee: minfee, 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /wire/msggetcfcheckpt.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/btcsuite/btcd/chaincfg/chainhash" 11 | ) 12 | 13 | // MsgGetCFCheckpt is a request for filter headers at evenly spaced intervals 14 | // throughout the blockchain history. It allows to set the FilterType field to 15 | // get headers in the chain of basic (0x00) or extended (0x01) headers. 16 | type MsgGetCFCheckpt struct { 17 | FilterType FilterType 18 | StopHash chainhash.Hash 19 | } 20 | 21 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 22 | // This is part of the Message interface implementation. 23 | func (msg *MsgGetCFCheckpt) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error { 24 | err := readElement(r, &msg.FilterType) 25 | if err != nil { 26 | return err 27 | } 28 | 29 | return readElement(r, &msg.StopHash) 30 | } 31 | 32 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 33 | // This is part of the Message interface implementation. 34 | func (msg *MsgGetCFCheckpt) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error { 35 | err := writeElement(w, msg.FilterType) 36 | if err != nil { 37 | return err 38 | } 39 | 40 | return writeElement(w, &msg.StopHash) 41 | } 42 | 43 | // Command returns the protocol command string for the message. This is part 44 | // of the Message interface implementation. 45 | func (msg *MsgGetCFCheckpt) Command() string { 46 | return CmdGetCFCheckpt 47 | } 48 | 49 | // MaxPayloadLength returns the maximum length the payload can be for the 50 | // receiver. This is part of the Message interface implementation. 51 | func (msg *MsgGetCFCheckpt) MaxPayloadLength(pver uint32) uint32 { 52 | // Filter type + uint32 + block hash 53 | return 1 + chainhash.HashSize 54 | } 55 | 56 | // NewMsgGetCFCheckpt returns a new bitcoin getcfcheckpt message that conforms 57 | // to the Message interface using the passed parameters and defaults for the 58 | // remaining fields. 59 | func NewMsgGetCFCheckpt(filterType FilterType, stopHash *chainhash.Hash) *MsgGetCFCheckpt { 60 | return &MsgGetCFCheckpt{ 61 | FilterType: filterType, 62 | StopHash: *stopHash, 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /wire/fixedIO_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "bytes" 9 | "io" 10 | ) 11 | 12 | // fixedWriter implements the io.Writer interface and intentially allows 13 | // testing of error paths by forcing short writes. 14 | type fixedWriter struct { 15 | b []byte 16 | pos int 17 | } 18 | 19 | // Write writes the contents of p to w. When the contents of p would cause 20 | // the writer to exceed the maximum allowed size of the fixed writer, 21 | // io.ErrShortWrite is returned and the writer is left unchanged. 22 | // 23 | // This satisfies the io.Writer interface. 24 | func (w *fixedWriter) Write(p []byte) (n int, err error) { 25 | lenp := len(p) 26 | if w.pos+lenp > cap(w.b) { 27 | return 0, io.ErrShortWrite 28 | } 29 | n = lenp 30 | w.pos += copy(w.b[w.pos:], p) 31 | return 32 | } 33 | 34 | // Bytes returns the bytes already written to the fixed writer. 35 | func (w *fixedWriter) Bytes() []byte { 36 | return w.b 37 | } 38 | 39 | // newFixedWriter returns a new io.Writer that will error once more bytes than 40 | // the specified max have been written. 41 | func newFixedWriter(max int) io.Writer { 42 | b := make([]byte, max) 43 | fw := fixedWriter{b, 0} 44 | return &fw 45 | } 46 | 47 | // fixedReader implements the io.Reader interface and intentially allows 48 | // testing of error paths by forcing short reads. 49 | type fixedReader struct { 50 | buf []byte 51 | pos int 52 | iobuf *bytes.Buffer 53 | } 54 | 55 | // Read reads the next len(p) bytes from the fixed reader. When the number of 56 | // bytes read would exceed the maximum number of allowed bytes to be read from 57 | // the fixed writer, an error is returned. 58 | // 59 | // This satisfies the io.Reader interface. 60 | func (fr *fixedReader) Read(p []byte) (n int, err error) { 61 | n, err = fr.iobuf.Read(p) 62 | fr.pos += n 63 | return 64 | } 65 | 66 | // newFixedReader returns a new io.Reader that will error once more bytes than 67 | // the specified max have been read. 68 | func newFixedReader(max int, buf []byte) io.Reader { 69 | b := make([]byte, max) 70 | if buf != nil { 71 | copy(b, buf) 72 | } 73 | 74 | iobuf := bytes.NewBuffer(b) 75 | fr := fixedReader{b, 0, iobuf} 76 | return &fr 77 | } 78 | -------------------------------------------------------------------------------- /signal.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "os" 9 | "os/signal" 10 | ) 11 | 12 | // shutdownRequestChannel is used to initiate shutdown from one of the 13 | // subsystems using the same code paths as when an interrupt signal is received. 14 | var shutdownRequestChannel = make(chan struct{}) 15 | 16 | // interruptSignals defines the default signals to catch in order to do a proper 17 | // shutdown. This may be modified during init depending on the platform. 18 | var interruptSignals = []os.Signal{os.Interrupt} 19 | 20 | // interruptListener listens for OS Signals such as SIGINT (Ctrl+C) and shutdown 21 | // requests from shutdownRequestChannel. It returns a channel that is closed 22 | // when either signal is received. 23 | func interruptListener() <-chan struct{} { 24 | c := make(chan struct{}) 25 | go func() { 26 | interruptChannel := make(chan os.Signal, 1) 27 | signal.Notify(interruptChannel, interruptSignals...) 28 | 29 | // Listen for initial shutdown signal and close the returned 30 | // channel to notify the caller. 31 | select { 32 | case sig := <-interruptChannel: 33 | btcdLog.Infof("Received signal (%s). Shutting down...", 34 | sig) 35 | 36 | case <-shutdownRequestChannel: 37 | btcdLog.Info("Shutdown requested. Shutting down...") 38 | } 39 | close(c) 40 | 41 | // Listen for repeated signals and display a message so the user 42 | // knows the shutdown is in progress and the process is not 43 | // hung. 44 | for { 45 | select { 46 | case sig := <-interruptChannel: 47 | btcdLog.Infof("Received signal (%s). Already "+ 48 | "shutting down...", sig) 49 | 50 | case <-shutdownRequestChannel: 51 | btcdLog.Info("Shutdown requested. Already " + 52 | "shutting down...") 53 | } 54 | } 55 | }() 56 | 57 | return c 58 | } 59 | 60 | // interruptRequested returns true when the channel returned by 61 | // interruptListener was closed. This simplifies early shutdown slightly since 62 | // the caller can just use an if statement instead of a select. 63 | func interruptRequested(interrupted <-chan struct{}) bool { 64 | select { 65 | case <-interrupted: 66 | return true 67 | default: 68 | } 69 | 70 | return false 71 | } 72 | -------------------------------------------------------------------------------- /connmgr/seed.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package connmgr 6 | 7 | import ( 8 | "fmt" 9 | mrand "math/rand" 10 | "net" 11 | "strconv" 12 | "time" 13 | 14 | "github.com/btcsuite/btcd/chaincfg" 15 | "github.com/btcsuite/btcd/wire" 16 | ) 17 | 18 | const ( 19 | // These constants are used by the DNS seed code to pick a random last 20 | // seen time. 21 | secondsIn3Days int32 = 24 * 60 * 60 * 3 22 | secondsIn4Days int32 = 24 * 60 * 60 * 4 23 | ) 24 | 25 | // OnSeed is the signature of the callback function which is invoked when DNS 26 | // seeding is succesfull. 27 | type OnSeed func(addrs []*wire.NetAddress) 28 | 29 | // LookupFunc is the signature of the DNS lookup function. 30 | type LookupFunc func(string) ([]net.IP, error) 31 | 32 | // SeedFromDNS uses DNS seeding to populate the address manager with peers. 33 | func SeedFromDNS(chainParams *chaincfg.Params, reqServices wire.ServiceFlag, 34 | lookupFn LookupFunc, seedFn OnSeed) { 35 | 36 | for _, dnsseed := range chainParams.DNSSeeds { 37 | var host string 38 | if !dnsseed.HasFiltering || reqServices == wire.SFNodeNetwork { 39 | host = dnsseed.Host 40 | } else { 41 | host = fmt.Sprintf("x%x.%s", uint64(reqServices), dnsseed.Host) 42 | } 43 | 44 | go func(host string) { 45 | randSource := mrand.New(mrand.NewSource(time.Now().UnixNano())) 46 | 47 | seedpeers, err := lookupFn(host) 48 | if err != nil { 49 | log.Infof("DNS discovery failed on seed %s: %v", host, err) 50 | return 51 | } 52 | numPeers := len(seedpeers) 53 | 54 | log.Infof("%d addresses found from DNS seed %s", numPeers, host) 55 | 56 | if numPeers == 0 { 57 | return 58 | } 59 | addresses := make([]*wire.NetAddress, len(seedpeers)) 60 | // if this errors then we have *real* problems 61 | intPort, _ := strconv.Atoi(chainParams.DefaultPort) 62 | for i, peer := range seedpeers { 63 | addresses[i] = wire.NewNetAddressTimestamp( 64 | // bitcoind seeds with addresses from 65 | // a time randomly selected between 3 66 | // and 7 days ago. 67 | time.Now().Add(-1*time.Second*time.Duration(secondsIn3Days+ 68 | randSource.Int31n(secondsIn4Days))), 69 | 0, peer, uint16(intPort)) 70 | } 71 | 72 | seedFn(addresses) 73 | }(host) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /connmgr/dynamicbanscore_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package connmgr 6 | 7 | import ( 8 | "math" 9 | "testing" 10 | "time" 11 | ) 12 | 13 | // TestDynamicBanScoreDecay tests the exponential decay implemented in 14 | // DynamicBanScore. 15 | func TestDynamicBanScoreDecay(t *testing.T) { 16 | var bs DynamicBanScore 17 | base := time.Now() 18 | 19 | r := bs.increase(100, 50, base) 20 | if r != 150 { 21 | t.Errorf("Unexpected result %d after ban score increase.", r) 22 | } 23 | 24 | r = bs.int(base.Add(time.Minute)) 25 | if r != 125 { 26 | t.Errorf("Halflife check failed - %d instead of 125", r) 27 | } 28 | 29 | r = bs.int(base.Add(7 * time.Minute)) 30 | if r != 100 { 31 | t.Errorf("Decay after 7m - %d instead of 100", r) 32 | } 33 | } 34 | 35 | // TestDynamicBanScoreLifetime tests that DynamicBanScore properly yields zero 36 | // once the maximum age is reached. 37 | func TestDynamicBanScoreLifetime(t *testing.T) { 38 | var bs DynamicBanScore 39 | base := time.Now() 40 | 41 | r := bs.increase(0, math.MaxUint32, base) 42 | r = bs.int(base.Add(Lifetime * time.Second)) 43 | if r != 3 { // 3, not 4 due to precision loss and truncating 3.999... 44 | t.Errorf("Pre max age check with MaxUint32 failed - %d", r) 45 | } 46 | r = bs.int(base.Add((Lifetime + 1) * time.Second)) 47 | if r != 0 { 48 | t.Errorf("Zero after max age check failed - %d instead of 0", r) 49 | } 50 | } 51 | 52 | // TestDynamicBanScore tests exported functions of DynamicBanScore. Exponential 53 | // decay or other time based behavior is tested by other functions. 54 | func TestDynamicBanScoreReset(t *testing.T) { 55 | var bs DynamicBanScore 56 | if bs.Int() != 0 { 57 | t.Errorf("Initial state is not zero.") 58 | } 59 | bs.Increase(100, 0) 60 | r := bs.Int() 61 | if r != 100 { 62 | t.Errorf("Unexpected result %d after ban score increase.", r) 63 | } 64 | bs.Reset() 65 | if bs.Int() != 0 { 66 | t.Errorf("Failed to reset ban score.") 67 | } 68 | } 69 | 70 | // TestDynamicBanScoreString 71 | func TestDynamicBanScoreString(t *testing.T) { 72 | var bs DynamicBanScore 73 | base := time.Now() 74 | 75 | r := bs.increase(100, 50, base) 76 | if r != 150 { 77 | t.Errorf("Unexpected result %d after ban score increase.", r) 78 | } 79 | t.Log(bs.String()) 80 | } 81 | -------------------------------------------------------------------------------- /docs/developer_resources.md: -------------------------------------------------------------------------------- 1 | # Developer Resources 2 | 3 | * [Code Contribution Guidelines](https://github.com/btcsuite/btcd/tree/master/docs/code_contribution_guidelines.md) 4 | 5 | * [JSON-RPC Reference](https://github.com/btcsuite/btcd/tree/master/docs/json_rpc_api.md) 6 | * [RPC Examples](https://github.com/btcsuite/btcd/tree/master/docs/json_rpc_api.md#ExampleCode) 7 | 8 | * The btcsuite Bitcoin-related Go Packages: 9 | * [btcrpcclient](https://github.com/btcsuite/btcd/tree/master/rpcclient) - Implements a 10 | robust and easy to use Websocket-enabled Bitcoin JSON-RPC client 11 | * [btcjson](https://github.com/btcsuite/btcd/tree/master/btcjson) - Provides an extensive API 12 | for the underlying JSON-RPC command and return values 13 | * [wire](https://github.com/btcsuite/btcd/tree/master/wire) - Implements the 14 | Bitcoin wire protocol 15 | * [peer](https://github.com/btcsuite/btcd/tree/master/peer) - 16 | Provides a common base for creating and managing Bitcoin network peers. 17 | * [blockchain](https://github.com/btcsuite/btcd/tree/master/blockchain) - 18 | Implements Bitcoin block handling and chain selection rules 19 | * [blockchain/fullblocktests](https://github.com/btcsuite/btcd/tree/master/blockchain/fullblocktests) - 20 | Provides a set of block tests for testing the consensus validation rules 21 | * [txscript](https://github.com/btcsuite/btcd/tree/master/txscript) - 22 | Implements the Bitcoin transaction scripting language 23 | * [btcec](https://github.com/btcsuite/btcd/tree/master/btcec) - Implements 24 | support for the elliptic curve cryptographic functions needed for the 25 | Bitcoin scripts 26 | * [database](https://github.com/btcsuite/btcd/tree/master/database) - 27 | Provides a database interface for the Bitcoin block chain 28 | * [mempool](https://github.com/btcsuite/btcd/tree/master/mempool) - 29 | Package mempool provides a policy-enforced pool of unmined bitcoin 30 | transactions. 31 | * [btcutil](https://github.com/btcsuite/btcutil) - Provides Bitcoin-specific 32 | convenience functions and types 33 | * [chainhash](https://github.com/btcsuite/btcd/tree/master/chaincfg/chainhash) - 34 | Provides a generic hash type and associated functions that allows the 35 | specific hash algorithm to be abstracted. 36 | * [connmgr](https://github.com/btcsuite/btcd/tree/master/connmgr) - 37 | Package connmgr implements a generic Bitcoin network connection manager. 38 | -------------------------------------------------------------------------------- /btcjson/error_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcjson_test 6 | 7 | import ( 8 | "testing" 9 | 10 | "github.com/btcsuite/btcd/btcjson" 11 | ) 12 | 13 | // TestErrorCodeStringer tests the stringized output for the ErrorCode type. 14 | func TestErrorCodeStringer(t *testing.T) { 15 | t.Parallel() 16 | 17 | tests := []struct { 18 | in btcjson.ErrorCode 19 | want string 20 | }{ 21 | {btcjson.ErrDuplicateMethod, "ErrDuplicateMethod"}, 22 | {btcjson.ErrInvalidUsageFlags, "ErrInvalidUsageFlags"}, 23 | {btcjson.ErrInvalidType, "ErrInvalidType"}, 24 | {btcjson.ErrEmbeddedType, "ErrEmbeddedType"}, 25 | {btcjson.ErrUnexportedField, "ErrUnexportedField"}, 26 | {btcjson.ErrUnsupportedFieldType, "ErrUnsupportedFieldType"}, 27 | {btcjson.ErrNonOptionalField, "ErrNonOptionalField"}, 28 | {btcjson.ErrNonOptionalDefault, "ErrNonOptionalDefault"}, 29 | {btcjson.ErrMismatchedDefault, "ErrMismatchedDefault"}, 30 | {btcjson.ErrUnregisteredMethod, "ErrUnregisteredMethod"}, 31 | {btcjson.ErrNumParams, "ErrNumParams"}, 32 | {btcjson.ErrMissingDescription, "ErrMissingDescription"}, 33 | {0xffff, "Unknown ErrorCode (65535)"}, 34 | } 35 | 36 | // Detect additional error codes that don't have the stringer added. 37 | if len(tests)-1 != int(btcjson.TstNumErrorCodes) { 38 | t.Errorf("It appears an error code was added without adding an " + 39 | "associated stringer test") 40 | } 41 | 42 | t.Logf("Running %d tests", len(tests)) 43 | for i, test := range tests { 44 | result := test.in.String() 45 | if result != test.want { 46 | t.Errorf("String #%d\n got: %s want: %s", i, result, 47 | test.want) 48 | continue 49 | } 50 | } 51 | } 52 | 53 | // TestError tests the error output for the Error type. 54 | func TestError(t *testing.T) { 55 | t.Parallel() 56 | 57 | tests := []struct { 58 | in btcjson.Error 59 | want string 60 | }{ 61 | { 62 | btcjson.Error{Description: "some error"}, 63 | "some error", 64 | }, 65 | { 66 | btcjson.Error{Description: "human-readable error"}, 67 | "human-readable error", 68 | }, 69 | } 70 | 71 | t.Logf("Running %d tests", len(tests)) 72 | for i, test := range tests { 73 | result := test.in.Error() 74 | if result != test.want { 75 | t.Errorf("Error #%d\n got: %s want: %s", i, result, 76 | test.want) 77 | continue 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /rpcclient/examples/btcwalletwebsockets/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "io/ioutil" 9 | "log" 10 | "path/filepath" 11 | "time" 12 | 13 | "github.com/btcsuite/btcd/rpcclient" 14 | "github.com/btcsuite/btcutil" 15 | "github.com/davecgh/go-spew/spew" 16 | ) 17 | 18 | func main() { 19 | // Only override the handlers for notifications you care about. 20 | // Also note most of the handlers will only be called if you register 21 | // for notifications. See the documentation of the rpcclient 22 | // NotificationHandlers type for more details about each handler. 23 | ntfnHandlers := rpcclient.NotificationHandlers{ 24 | OnAccountBalance: func(account string, balance btcutil.Amount, confirmed bool) { 25 | log.Printf("New balance for account %s: %v", account, 26 | balance) 27 | }, 28 | } 29 | 30 | // Connect to local btcwallet RPC server using websockets. 31 | certHomeDir := btcutil.AppDataDir("btcwallet", false) 32 | certs, err := ioutil.ReadFile(filepath.Join(certHomeDir, "rpc.cert")) 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | connCfg := &rpcclient.ConnConfig{ 37 | Host: "localhost:18332", 38 | Endpoint: "ws", 39 | User: "yourrpcuser", 40 | Pass: "yourrpcpass", 41 | Certificates: certs, 42 | } 43 | client, err := rpcclient.New(connCfg, &ntfnHandlers) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | 48 | // Get the list of unspent transaction outputs (utxos) that the 49 | // connected wallet has at least one private key for. 50 | unspent, err := client.ListUnspent() 51 | if err != nil { 52 | log.Fatal(err) 53 | } 54 | log.Printf("Num unspent outputs (utxos): %d", len(unspent)) 55 | if len(unspent) > 0 { 56 | log.Printf("First utxo:\n%v", spew.Sdump(unspent[0])) 57 | } 58 | 59 | // For this example gracefully shutdown the client after 10 seconds. 60 | // Ordinarily when to shutdown the client is highly application 61 | // specific. 62 | log.Println("Client shutdown in 10 seconds...") 63 | time.AfterFunc(time.Second*10, func() { 64 | log.Println("Client shutting down...") 65 | client.Shutdown() 66 | log.Println("Client shutdown complete.") 67 | }) 68 | 69 | // Wait until the client either shuts down gracefully (or the user 70 | // terminates the process with Ctrl+C). 71 | client.WaitForShutdown() 72 | } 73 | -------------------------------------------------------------------------------- /database/ffldb/driver.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package ffldb 6 | 7 | import ( 8 | "fmt" 9 | 10 | "github.com/btcsuite/btcd/database" 11 | "github.com/btcsuite/btcd/wire" 12 | "github.com/btcsuite/btclog" 13 | ) 14 | 15 | var log = btclog.Disabled 16 | 17 | const ( 18 | dbType = "ffldb" 19 | ) 20 | 21 | // parseArgs parses the arguments from the database Open/Create methods. 22 | func parseArgs(funcName string, args ...interface{}) (string, wire.BitcoinNet, error) { 23 | if len(args) != 2 { 24 | return "", 0, fmt.Errorf("invalid arguments to %s.%s -- "+ 25 | "expected database path and block network", dbType, 26 | funcName) 27 | } 28 | 29 | dbPath, ok := args[0].(string) 30 | if !ok { 31 | return "", 0, fmt.Errorf("first argument to %s.%s is invalid -- "+ 32 | "expected database path string", dbType, funcName) 33 | } 34 | 35 | network, ok := args[1].(wire.BitcoinNet) 36 | if !ok { 37 | return "", 0, fmt.Errorf("second argument to %s.%s is invalid -- "+ 38 | "expected block network", dbType, funcName) 39 | } 40 | 41 | return dbPath, network, nil 42 | } 43 | 44 | // openDBDriver is the callback provided during driver registration that opens 45 | // an existing database for use. 46 | func openDBDriver(args ...interface{}) (database.DB, error) { 47 | dbPath, network, err := parseArgs("Open", args...) 48 | if err != nil { 49 | return nil, err 50 | } 51 | 52 | return openDB(dbPath, network, false) 53 | } 54 | 55 | // createDBDriver is the callback provided during driver registration that 56 | // creates, initializes, and opens a database for use. 57 | func createDBDriver(args ...interface{}) (database.DB, error) { 58 | dbPath, network, err := parseArgs("Create", args...) 59 | if err != nil { 60 | return nil, err 61 | } 62 | 63 | return openDB(dbPath, network, true) 64 | } 65 | 66 | // useLogger is the callback provided during driver registration that sets the 67 | // current logger to the provided one. 68 | func useLogger(logger btclog.Logger) { 69 | log = logger 70 | } 71 | 72 | func init() { 73 | // Register the driver. 74 | driver := database.Driver{ 75 | DbType: dbType, 76 | Create: createDBDriver, 77 | Open: openDBDriver, 78 | UseLogger: useLogger, 79 | } 80 | if err := database.RegisterDriver(driver); err != nil { 81 | panic(fmt.Sprintf("Failed to regiser database driver '%s': %v", 82 | dbType, err)) 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /btcec/privkey.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcec 6 | 7 | import ( 8 | "crypto/ecdsa" 9 | "crypto/elliptic" 10 | "crypto/rand" 11 | "math/big" 12 | ) 13 | 14 | // PrivateKey wraps an ecdsa.PrivateKey as a convenience mainly for signing 15 | // things with the the private key without having to directly import the ecdsa 16 | // package. 17 | type PrivateKey ecdsa.PrivateKey 18 | 19 | // PrivKeyFromBytes returns a private and public key for `curve' based on the 20 | // private key passed as an argument as a byte slice. 21 | func PrivKeyFromBytes(curve elliptic.Curve, pk []byte) (*PrivateKey, 22 | *PublicKey) { 23 | x, y := curve.ScalarBaseMult(pk) 24 | 25 | priv := &ecdsa.PrivateKey{ 26 | PublicKey: ecdsa.PublicKey{ 27 | Curve: curve, 28 | X: x, 29 | Y: y, 30 | }, 31 | D: new(big.Int).SetBytes(pk), 32 | } 33 | 34 | return (*PrivateKey)(priv), (*PublicKey)(&priv.PublicKey) 35 | } 36 | 37 | // NewPrivateKey is a wrapper for ecdsa.GenerateKey that returns a PrivateKey 38 | // instead of the normal ecdsa.PrivateKey. 39 | func NewPrivateKey(curve elliptic.Curve) (*PrivateKey, error) { 40 | key, err := ecdsa.GenerateKey(curve, rand.Reader) 41 | if err != nil { 42 | return nil, err 43 | } 44 | return (*PrivateKey)(key), nil 45 | } 46 | 47 | // PubKey returns the PublicKey corresponding to this private key. 48 | func (p *PrivateKey) PubKey() *PublicKey { 49 | return (*PublicKey)(&p.PublicKey) 50 | } 51 | 52 | // ToECDSA returns the private key as a *ecdsa.PrivateKey. 53 | func (p *PrivateKey) ToECDSA() *ecdsa.PrivateKey { 54 | return (*ecdsa.PrivateKey)(p) 55 | } 56 | 57 | // Sign generates an ECDSA signature for the provided hash (which should be the result 58 | // of hashing a larger message) using the private key. Produced signature 59 | // is deterministic (same message and same key yield the same signature) and canonical 60 | // in accordance with RFC6979 and BIP0062. 61 | func (p *PrivateKey) Sign(hash []byte) (*Signature, error) { 62 | return signRFC6979(p, hash) 63 | } 64 | 65 | // PrivKeyBytesLen defines the length in bytes of a serialized private key. 66 | const PrivKeyBytesLen = 32 67 | 68 | // Serialize returns the private key number d as a big-endian binary-encoded 69 | // number, padded to a length of 32 bytes. 70 | func (p *PrivateKey) Serialize() []byte { 71 | b := make([]byte, 0, PrivKeyBytesLen) 72 | return paddedAppend(PrivKeyBytesLen, b, p.ToECDSA().D.Bytes()) 73 | } 74 | -------------------------------------------------------------------------------- /wire/msggetcfheaders.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/btcsuite/btcd/chaincfg/chainhash" 11 | ) 12 | 13 | // MsgGetCFHeaders is a message similar to MsgGetHeaders, but for committed 14 | // filter headers. It allows to set the FilterType field to get headers in the 15 | // chain of basic (0x00) or extended (0x01) headers. 16 | type MsgGetCFHeaders struct { 17 | FilterType FilterType 18 | StartHeight uint32 19 | StopHash chainhash.Hash 20 | } 21 | 22 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 23 | // This is part of the Message interface implementation. 24 | func (msg *MsgGetCFHeaders) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error { 25 | err := readElement(r, &msg.FilterType) 26 | if err != nil { 27 | return err 28 | } 29 | 30 | err = readElement(r, &msg.StartHeight) 31 | if err != nil { 32 | return err 33 | } 34 | 35 | return readElement(r, &msg.StopHash) 36 | } 37 | 38 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 39 | // This is part of the Message interface implementation. 40 | func (msg *MsgGetCFHeaders) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error { 41 | err := writeElement(w, msg.FilterType) 42 | if err != nil { 43 | return err 44 | } 45 | 46 | err = writeElement(w, &msg.StartHeight) 47 | if err != nil { 48 | return err 49 | } 50 | 51 | return writeElement(w, &msg.StopHash) 52 | } 53 | 54 | // Command returns the protocol command string for the message. This is part 55 | // of the Message interface implementation. 56 | func (msg *MsgGetCFHeaders) Command() string { 57 | return CmdGetCFHeaders 58 | } 59 | 60 | // MaxPayloadLength returns the maximum length the payload can be for the 61 | // receiver. This is part of the Message interface implementation. 62 | func (msg *MsgGetCFHeaders) MaxPayloadLength(pver uint32) uint32 { 63 | // Filter type + uint32 + block hash 64 | return 1 + 4 + chainhash.HashSize 65 | } 66 | 67 | // NewMsgGetCFHeaders returns a new bitcoin getcfheader message that conforms to 68 | // the Message interface using the passed parameters and defaults for the 69 | // remaining fields. 70 | func NewMsgGetCFHeaders(filterType FilterType, startHeight uint32, 71 | stopHash *chainhash.Hash) *MsgGetCFHeaders { 72 | return &MsgGetCFHeaders{ 73 | FilterType: filterType, 74 | StartHeight: startHeight, 75 | StopHash: *stopHash, 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /blockchain/indexers/blocklogger.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package indexers 6 | 7 | import ( 8 | "sync" 9 | "time" 10 | 11 | "github.com/btcsuite/btclog" 12 | "github.com/btcsuite/btcutil" 13 | ) 14 | 15 | // blockProgressLogger provides periodic logging for other services in order 16 | // to show users progress of certain "actions" involving some or all current 17 | // blocks. Ex: syncing to best chain, indexing all blocks, etc. 18 | type blockProgressLogger struct { 19 | receivedLogBlocks int64 20 | receivedLogTx int64 21 | lastBlockLogTime time.Time 22 | 23 | subsystemLogger btclog.Logger 24 | progressAction string 25 | sync.Mutex 26 | } 27 | 28 | // newBlockProgressLogger returns a new block progress logger. 29 | // The progress message is templated as follows: 30 | // {progressAction} {numProcessed} {blocks|block} in the last {timePeriod} 31 | // ({numTxs}, height {lastBlockHeight}, {lastBlockTimeStamp}) 32 | func newBlockProgressLogger(progressMessage string, logger btclog.Logger) *blockProgressLogger { 33 | return &blockProgressLogger{ 34 | lastBlockLogTime: time.Now(), 35 | progressAction: progressMessage, 36 | subsystemLogger: logger, 37 | } 38 | } 39 | 40 | // LogBlockHeight logs a new block height as an information message to show 41 | // progress to the user. In order to prevent spam, it limits logging to one 42 | // message every 10 seconds with duration and totals included. 43 | func (b *blockProgressLogger) LogBlockHeight(block *btcutil.Block) { 44 | b.Lock() 45 | defer b.Unlock() 46 | 47 | b.receivedLogBlocks++ 48 | b.receivedLogTx += int64(len(block.MsgBlock().Transactions)) 49 | 50 | now := time.Now() 51 | duration := now.Sub(b.lastBlockLogTime) 52 | if duration < time.Second*10 { 53 | return 54 | } 55 | 56 | // Truncate the duration to 10s of milliseconds. 57 | durationMillis := int64(duration / time.Millisecond) 58 | tDuration := 10 * time.Millisecond * time.Duration(durationMillis/10) 59 | 60 | // Log information about new block height. 61 | blockStr := "blocks" 62 | if b.receivedLogBlocks == 1 { 63 | blockStr = "block" 64 | } 65 | txStr := "transactions" 66 | if b.receivedLogTx == 1 { 67 | txStr = "transaction" 68 | } 69 | b.subsystemLogger.Infof("%s %d %s in the last %s (%d %s, height %d, %s)", 70 | b.progressAction, b.receivedLogBlocks, blockStr, tDuration, b.receivedLogTx, 71 | txStr, block.Height(), block.MsgBlock().Header.Timestamp) 72 | 73 | b.receivedLogBlocks = 0 74 | b.receivedLogTx = 0 75 | b.lastBlockLogTime = now 76 | } 77 | -------------------------------------------------------------------------------- /database/README.md: -------------------------------------------------------------------------------- 1 | database 2 | ======== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/database) 7 | 8 | Package database provides a block and metadata storage database. 9 | 10 | Please note that this package is intended to enable btcd to support different 11 | database backends and is not something that a client can directly access as only 12 | one entity can have the database open at a time (for most database backends), 13 | and that entity will be btcd. 14 | 15 | When a client wants programmatic access to the data provided by btcd, they'll 16 | likely want to use the [rpcclient](https://github.com/btcsuite/btcd/tree/master/rpcclient) 17 | package which makes use of the [JSON-RPC API](https://github.com/btcsuite/btcd/tree/master/docs/json_rpc_api.md). 18 | 19 | However, this package could be extremely useful for any applications requiring 20 | Bitcoin block storage capabilities. 21 | 22 | The default backend, ffldb, has a strong focus on speed, efficiency, and 23 | robustness. It makes use of leveldb for the metadata, flat files for block 24 | storage, and strict checksums in key areas to ensure data integrity. 25 | 26 | ## Feature Overview 27 | 28 | - Key/value metadata store 29 | - Bitcoin block storage 30 | - Efficient retrieval of block headers and regions (transactions, scripts, etc) 31 | - Read-only and read-write transactions with both manual and managed modes 32 | - Nested buckets 33 | - Iteration support including cursors with seek capability 34 | - Supports registration of backend databases 35 | - Comprehensive test coverage 36 | 37 | ## Installation and Updating 38 | 39 | ```bash 40 | $ go get -u github.com/btcsuite/btcd/database 41 | ``` 42 | 43 | ## Examples 44 | 45 | * [Basic Usage Example](https://pkg.go.dev/github.com/btcsuite/btcd/database#example-package--BasicUsage) 46 | Demonstrates creating a new database and using a managed read-write 47 | transaction to store and retrieve metadata. 48 | 49 | * [Block Storage and Retrieval Example](https://pkg.go.dev/github.com/btcsuite/btcd/database#example-package--BlockStorageAndRetrieval) 50 | Demonstrates creating a new database, using a managed read-write transaction 51 | to store a block, and then using a managed read-only transaction to fetch the 52 | block. 53 | 54 | ## License 55 | 56 | Package database is licensed under the [copyfree](http://copyfree.org) ISC 57 | License. 58 | -------------------------------------------------------------------------------- /txscript/README.md: -------------------------------------------------------------------------------- 1 | txscript 2 | ======== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://pkg.go.dev/github.com/btcsuite/btcd/txscript?status.png)](https://pkg.go.dev/github.com/btcsuite/btcd/txscript) 7 | 8 | Package txscript implements the bitcoin transaction script language. There is 9 | a comprehensive test suite. 10 | 11 | This package has intentionally been designed so it can be used as a standalone 12 | package for any projects needing to use or validate bitcoin transaction scripts. 13 | 14 | ## Bitcoin Scripts 15 | 16 | Bitcoin provides a stack-based, FORTH-like language for the scripts in 17 | the bitcoin transactions. This language is not turing complete 18 | although it is still fairly powerful. A description of the language 19 | can be found at https://en.bitcoin.it/wiki/Script 20 | 21 | ## Installation and Updating 22 | 23 | ```bash 24 | $ go get -u github.com/btcsuite/btcd/txscript 25 | ``` 26 | 27 | ## Examples 28 | 29 | * [Standard Pay-to-pubkey-hash Script](https://pkg.go.dev/github.com/btcsuite/btcd/txscript#example-PayToAddrScript) 30 | Demonstrates creating a script which pays to a bitcoin address. It also 31 | prints the created script hex and uses the DisasmString function to display 32 | the disassembled script. 33 | 34 | * [Extracting Details from Standard Scripts](https://pkg.go.dev/github.com/btcsuite/btcd/txscript#example-ExtractPkScriptAddrs) 35 | Demonstrates extracting information from a standard public key script. 36 | 37 | * [Manually Signing a Transaction Output](https://pkg.go.dev/github.com/btcsuite/btcd/txscript#example-SignTxOutput) 38 | Demonstrates manually creating and signing a redeem transaction. 39 | 40 | ## GPG Verification Key 41 | 42 | All official release tags are signed by Conformal so users can ensure the code 43 | has not been tampered with and is coming from the btcsuite developers. To 44 | verify the signature perform the following: 45 | 46 | - Download the public key from the Conformal website at 47 | https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt 48 | 49 | - Import the public key into your GPG keyring: 50 | ```bash 51 | gpg --import GIT-GPG-KEY-conformal.txt 52 | ``` 53 | 54 | - Verify the release tag with the following command where `TAG_NAME` is a 55 | placeholder for the specific tag: 56 | ```bash 57 | git tag -v TAG_NAME 58 | ``` 59 | 60 | ## License 61 | 62 | Package txscript is licensed under the [copyfree](http://copyfree.org) ISC 63 | License. 64 | -------------------------------------------------------------------------------- /chaincfg/README.md: -------------------------------------------------------------------------------- 1 | chaincfg 2 | ======== 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/chaincfg) 7 | 8 | Package chaincfg defines chain configuration parameters for the three standard 9 | Bitcoin networks and provides the ability for callers to define their own custom 10 | Bitcoin networks. 11 | 12 | Although this package was primarily written for btcd, it has intentionally been 13 | designed so it can be used as a standalone package for any projects needing to 14 | use parameters for the standard Bitcoin networks or for projects needing to 15 | define their own network. 16 | 17 | ## Sample Use 18 | 19 | ```Go 20 | package main 21 | 22 | import ( 23 | "flag" 24 | "fmt" 25 | "log" 26 | 27 | "github.com/btcsuite/btcutil" 28 | "github.com/btcsuite/btcd/chaincfg" 29 | ) 30 | 31 | var testnet = flag.Bool("testnet", false, "operate on the testnet Bitcoin network") 32 | 33 | // By default (without -testnet), use mainnet. 34 | var chainParams = &chaincfg.MainNetParams 35 | 36 | func main() { 37 | flag.Parse() 38 | 39 | // Modify active network parameters if operating on testnet. 40 | if *testnet { 41 | chainParams = &chaincfg.TestNet3Params 42 | } 43 | 44 | // later... 45 | 46 | // Create and print new payment address, specific to the active network. 47 | pubKeyHash := make([]byte, 20) 48 | addr, err := btcutil.NewAddressPubKeyHash(pubKeyHash, chainParams) 49 | if err != nil { 50 | log.Fatal(err) 51 | } 52 | fmt.Println(addr) 53 | } 54 | ``` 55 | 56 | ## Installation and Updating 57 | 58 | ```bash 59 | $ go get -u github.com/btcsuite/btcd/chaincfg 60 | ``` 61 | 62 | ## GPG Verification Key 63 | 64 | All official release tags are signed by Conformal so users can ensure the code 65 | has not been tampered with and is coming from the btcsuite developers. To 66 | verify the signature perform the following: 67 | 68 | - Download the public key from the Conformal website at 69 | https://opensource.conformal.com/GIT-GPG-KEY-conformal.txt 70 | 71 | - Import the public key into your GPG keyring: 72 | ```bash 73 | gpg --import GIT-GPG-KEY-conformal.txt 74 | ``` 75 | 76 | - Verify the release tag with the following command where `TAG_NAME` is a 77 | placeholder for the specific tag: 78 | ```bash 79 | git tag -v TAG_NAME 80 | ``` 81 | 82 | ## License 83 | 84 | Package chaincfg is licensed under the [copyfree](http://copyfree.org) ISC 85 | License. 86 | -------------------------------------------------------------------------------- /database/cmd/dbtool/fetchblockregion.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "encoding/hex" 9 | "errors" 10 | "strconv" 11 | "time" 12 | 13 | "github.com/btcsuite/btcd/chaincfg/chainhash" 14 | "github.com/btcsuite/btcd/database" 15 | ) 16 | 17 | // blockRegionCmd defines the configuration options for the fetchblockregion 18 | // command. 19 | type blockRegionCmd struct{} 20 | 21 | var ( 22 | // blockRegionCfg defines the configuration options for the command. 23 | blockRegionCfg = blockRegionCmd{} 24 | ) 25 | 26 | // Execute is the main entry point for the command. It's invoked by the parser. 27 | func (cmd *blockRegionCmd) Execute(args []string) error { 28 | // Setup the global config options and ensure they are valid. 29 | if err := setupGlobalConfig(); err != nil { 30 | return err 31 | } 32 | 33 | // Ensure expected arguments. 34 | if len(args) < 1 { 35 | return errors.New("required block hash parameter not specified") 36 | } 37 | if len(args) < 2 { 38 | return errors.New("required start offset parameter not " + 39 | "specified") 40 | } 41 | if len(args) < 3 { 42 | return errors.New("required region length parameter not " + 43 | "specified") 44 | } 45 | 46 | // Parse arguments. 47 | blockHash, err := chainhash.NewHashFromStr(args[0]) 48 | if err != nil { 49 | return err 50 | } 51 | startOffset, err := strconv.ParseUint(args[1], 10, 32) 52 | if err != nil { 53 | return err 54 | } 55 | regionLen, err := strconv.ParseUint(args[2], 10, 32) 56 | if err != nil { 57 | return err 58 | } 59 | 60 | // Load the block database. 61 | db, err := loadBlockDB() 62 | if err != nil { 63 | return err 64 | } 65 | defer db.Close() 66 | 67 | return db.View(func(tx database.Tx) error { 68 | log.Infof("Fetching block region %s<%d:%d>", blockHash, 69 | startOffset, startOffset+regionLen-1) 70 | region := database.BlockRegion{ 71 | Hash: blockHash, 72 | Offset: uint32(startOffset), 73 | Len: uint32(regionLen), 74 | } 75 | startTime := time.Now() 76 | regionBytes, err := tx.FetchBlockRegion(®ion) 77 | if err != nil { 78 | return err 79 | } 80 | log.Infof("Loaded block region in %v", time.Since(startTime)) 81 | log.Infof("Double Hash: %s", chainhash.DoubleHashH(regionBytes)) 82 | log.Infof("Region Hex: %s", hex.EncodeToString(regionBytes)) 83 | return nil 84 | }) 85 | } 86 | 87 | // Usage overrides the usage display for the command. 88 | func (cmd *blockRegionCmd) Usage() string { 89 | return " " 90 | } 91 | -------------------------------------------------------------------------------- /wire/msggetcfilters.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "io" 9 | 10 | "github.com/btcsuite/btcd/chaincfg/chainhash" 11 | ) 12 | 13 | // MaxGetCFiltersReqRange the maximum number of filters that may be requested in 14 | // a getcfheaders message. 15 | const MaxGetCFiltersReqRange = 1000 16 | 17 | // MsgGetCFilters implements the Message interface and represents a bitcoin 18 | // getcfilters message. It is used to request committed filters for a range of 19 | // blocks. 20 | type MsgGetCFilters struct { 21 | FilterType FilterType 22 | StartHeight uint32 23 | StopHash chainhash.Hash 24 | } 25 | 26 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 27 | // This is part of the Message interface implementation. 28 | func (msg *MsgGetCFilters) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error { 29 | err := readElement(r, &msg.FilterType) 30 | if err != nil { 31 | return err 32 | } 33 | 34 | err = readElement(r, &msg.StartHeight) 35 | if err != nil { 36 | return err 37 | } 38 | 39 | return readElement(r, &msg.StopHash) 40 | } 41 | 42 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 43 | // This is part of the Message interface implementation. 44 | func (msg *MsgGetCFilters) BtcEncode(w io.Writer, pver uint32, _ MessageEncoding) error { 45 | err := writeElement(w, msg.FilterType) 46 | if err != nil { 47 | return err 48 | } 49 | 50 | err = writeElement(w, &msg.StartHeight) 51 | if err != nil { 52 | return err 53 | } 54 | 55 | return writeElement(w, &msg.StopHash) 56 | } 57 | 58 | // Command returns the protocol command string for the message. This is part 59 | // of the Message interface implementation. 60 | func (msg *MsgGetCFilters) Command() string { 61 | return CmdGetCFilters 62 | } 63 | 64 | // MaxPayloadLength returns the maximum length the payload can be for the 65 | // receiver. This is part of the Message interface implementation. 66 | func (msg *MsgGetCFilters) MaxPayloadLength(pver uint32) uint32 { 67 | // Filter type + uint32 + block hash 68 | return 1 + 4 + chainhash.HashSize 69 | } 70 | 71 | // NewMsgGetCFilters returns a new bitcoin getcfilters message that conforms to 72 | // the Message interface using the passed parameters and defaults for the 73 | // remaining fields. 74 | func NewMsgGetCFilters(filterType FilterType, startHeight uint32, 75 | stopHash *chainhash.Hash) *MsgGetCFilters { 76 | return &MsgGetCFilters{ 77 | FilterType: filterType, 78 | StartHeight: startHeight, 79 | StopHash: *stopHash, 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /database/ffldb/bench_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package ffldb 6 | 7 | import ( 8 | "os" 9 | "path/filepath" 10 | "testing" 11 | 12 | "github.com/btcsuite/btcd/chaincfg" 13 | "github.com/btcsuite/btcd/database" 14 | "github.com/btcsuite/btcutil" 15 | ) 16 | 17 | // BenchmarkBlockHeader benchmarks how long it takes to load the mainnet genesis 18 | // block header. 19 | func BenchmarkBlockHeader(b *testing.B) { 20 | // Start by creating a new database and populating it with the mainnet 21 | // genesis block. 22 | dbPath := filepath.Join(os.TempDir(), "ffldb-benchblkhdr") 23 | _ = os.RemoveAll(dbPath) 24 | db, err := database.Create("ffldb", dbPath, blockDataNet) 25 | if err != nil { 26 | b.Fatal(err) 27 | } 28 | defer os.RemoveAll(dbPath) 29 | defer db.Close() 30 | err = db.Update(func(tx database.Tx) error { 31 | block := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock) 32 | return tx.StoreBlock(block) 33 | }) 34 | if err != nil { 35 | b.Fatal(err) 36 | } 37 | 38 | b.ReportAllocs() 39 | b.ResetTimer() 40 | err = db.View(func(tx database.Tx) error { 41 | blockHash := chaincfg.MainNetParams.GenesisHash 42 | for i := 0; i < b.N; i++ { 43 | _, err := tx.FetchBlockHeader(blockHash) 44 | if err != nil { 45 | return err 46 | } 47 | } 48 | return nil 49 | }) 50 | if err != nil { 51 | b.Fatal(err) 52 | } 53 | 54 | // Don't benchmark teardown. 55 | b.StopTimer() 56 | } 57 | 58 | // BenchmarkBlockHeader benchmarks how long it takes to load the mainnet genesis 59 | // block. 60 | func BenchmarkBlock(b *testing.B) { 61 | // Start by creating a new database and populating it with the mainnet 62 | // genesis block. 63 | dbPath := filepath.Join(os.TempDir(), "ffldb-benchblk") 64 | _ = os.RemoveAll(dbPath) 65 | db, err := database.Create("ffldb", dbPath, blockDataNet) 66 | if err != nil { 67 | b.Fatal(err) 68 | } 69 | defer os.RemoveAll(dbPath) 70 | defer db.Close() 71 | err = db.Update(func(tx database.Tx) error { 72 | block := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock) 73 | return tx.StoreBlock(block) 74 | }) 75 | if err != nil { 76 | b.Fatal(err) 77 | } 78 | 79 | b.ReportAllocs() 80 | b.ResetTimer() 81 | err = db.View(func(tx database.Tx) error { 82 | blockHash := chaincfg.MainNetParams.GenesisHash 83 | for i := 0; i < b.N; i++ { 84 | _, err := tx.FetchBlock(blockHash) 85 | if err != nil { 86 | return err 87 | } 88 | } 89 | return nil 90 | }) 91 | if err != nil { 92 | b.Fatal(err) 93 | } 94 | 95 | // Don't benchmark teardown. 96 | b.StopTimer() 97 | } 98 | -------------------------------------------------------------------------------- /rpcclient/examples/btcdwebsockets/main.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "io/ioutil" 9 | "log" 10 | "path/filepath" 11 | "time" 12 | 13 | "github.com/btcsuite/btcd/rpcclient" 14 | "github.com/btcsuite/btcd/wire" 15 | "github.com/btcsuite/btcutil" 16 | ) 17 | 18 | func main() { 19 | // Only override the handlers for notifications you care about. 20 | // Also note most of these handlers will only be called if you register 21 | // for notifications. See the documentation of the rpcclient 22 | // NotificationHandlers type for more details about each handler. 23 | ntfnHandlers := rpcclient.NotificationHandlers{ 24 | OnFilteredBlockConnected: func(height int32, header *wire.BlockHeader, txns []*btcutil.Tx) { 25 | log.Printf("Block connected: %v (%d) %v", 26 | header.BlockHash(), height, header.Timestamp) 27 | }, 28 | OnFilteredBlockDisconnected: func(height int32, header *wire.BlockHeader) { 29 | log.Printf("Block disconnected: %v (%d) %v", 30 | header.BlockHash(), height, header.Timestamp) 31 | }, 32 | } 33 | 34 | // Connect to local btcd RPC server using websockets. 35 | btcdHomeDir := btcutil.AppDataDir("btcd", false) 36 | certs, err := ioutil.ReadFile(filepath.Join(btcdHomeDir, "rpc.cert")) 37 | if err != nil { 38 | log.Fatal(err) 39 | } 40 | connCfg := &rpcclient.ConnConfig{ 41 | Host: "localhost:8334", 42 | Endpoint: "ws", 43 | User: "yourrpcuser", 44 | Pass: "yourrpcpass", 45 | Certificates: certs, 46 | } 47 | client, err := rpcclient.New(connCfg, &ntfnHandlers) 48 | if err != nil { 49 | log.Fatal(err) 50 | } 51 | 52 | // Register for block connect and disconnect notifications. 53 | if err := client.NotifyBlocks(); err != nil { 54 | log.Fatal(err) 55 | } 56 | log.Println("NotifyBlocks: Registration Complete") 57 | 58 | // Get the current block count. 59 | blockCount, err := client.GetBlockCount() 60 | if err != nil { 61 | log.Fatal(err) 62 | } 63 | log.Printf("Block count: %d", blockCount) 64 | 65 | // For this example gracefully shutdown the client after 10 seconds. 66 | // Ordinarily when to shutdown the client is highly application 67 | // specific. 68 | log.Println("Client shutdown in 10 seconds...") 69 | time.AfterFunc(time.Second*10, func() { 70 | log.Println("Client shutting down...") 71 | client.Shutdown() 72 | log.Println("Client shutdown complete.") 73 | }) 74 | 75 | // Wait until the client either shuts down gracefully (or the user 76 | // terminates the process with Ctrl+C). 77 | client.WaitForShutdown() 78 | } 79 | -------------------------------------------------------------------------------- /database/cmd/dbtool/signal.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "os" 9 | "os/signal" 10 | ) 11 | 12 | // interruptChannel is used to receive SIGINT (Ctrl+C) signals. 13 | var interruptChannel chan os.Signal 14 | 15 | // addHandlerChannel is used to add an interrupt handler to the list of handlers 16 | // to be invoked on SIGINT (Ctrl+C) signals. 17 | var addHandlerChannel = make(chan func()) 18 | 19 | // mainInterruptHandler listens for SIGINT (Ctrl+C) signals on the 20 | // interruptChannel and invokes the registered interruptCallbacks accordingly. 21 | // It also listens for callback registration. It must be run as a goroutine. 22 | func mainInterruptHandler() { 23 | // interruptCallbacks is a list of callbacks to invoke when a 24 | // SIGINT (Ctrl+C) is received. 25 | var interruptCallbacks []func() 26 | 27 | // isShutdown is a flag which is used to indicate whether or not 28 | // the shutdown signal has already been received and hence any future 29 | // attempts to add a new interrupt handler should invoke them 30 | // immediately. 31 | var isShutdown bool 32 | 33 | for { 34 | select { 35 | case <-interruptChannel: 36 | // Ignore more than one shutdown signal. 37 | if isShutdown { 38 | log.Infof("Received SIGINT (Ctrl+C). " + 39 | "Already shutting down...") 40 | continue 41 | } 42 | 43 | isShutdown = true 44 | log.Infof("Received SIGINT (Ctrl+C). Shutting down...") 45 | 46 | // Run handlers in LIFO order. 47 | for i := range interruptCallbacks { 48 | idx := len(interruptCallbacks) - 1 - i 49 | callback := interruptCallbacks[idx] 50 | callback() 51 | } 52 | 53 | // Signal the main goroutine to shutdown. 54 | go func() { 55 | shutdownChannel <- nil 56 | }() 57 | 58 | case handler := <-addHandlerChannel: 59 | // The shutdown signal has already been received, so 60 | // just invoke and new handlers immediately. 61 | if isShutdown { 62 | handler() 63 | } 64 | 65 | interruptCallbacks = append(interruptCallbacks, handler) 66 | } 67 | } 68 | } 69 | 70 | // addInterruptHandler adds a handler to call when a SIGINT (Ctrl+C) is 71 | // received. 72 | func addInterruptHandler(handler func()) { 73 | // Create the channel and start the main interrupt handler which invokes 74 | // all other callbacks and exits if not already done. 75 | if interruptChannel == nil { 76 | interruptChannel = make(chan os.Signal, 1) 77 | signal.Notify(interruptChannel, os.Interrupt) 78 | go mainInterruptHandler() 79 | } 80 | 81 | addHandlerChannel <- handler 82 | } 83 | -------------------------------------------------------------------------------- /btcjson/helpers_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcjson_test 6 | 7 | import ( 8 | "reflect" 9 | "testing" 10 | 11 | "github.com/btcsuite/btcd/btcjson" 12 | ) 13 | 14 | // TestHelpers tests the various helper functions which create pointers to 15 | // primitive types. 16 | func TestHelpers(t *testing.T) { 17 | t.Parallel() 18 | 19 | tests := []struct { 20 | name string 21 | f func() interface{} 22 | expected interface{} 23 | }{ 24 | { 25 | name: "bool", 26 | f: func() interface{} { 27 | return btcjson.Bool(true) 28 | }, 29 | expected: func() interface{} { 30 | val := true 31 | return &val 32 | }(), 33 | }, 34 | { 35 | name: "int", 36 | f: func() interface{} { 37 | return btcjson.Int(5) 38 | }, 39 | expected: func() interface{} { 40 | val := int(5) 41 | return &val 42 | }(), 43 | }, 44 | { 45 | name: "uint", 46 | f: func() interface{} { 47 | return btcjson.Uint(5) 48 | }, 49 | expected: func() interface{} { 50 | val := uint(5) 51 | return &val 52 | }(), 53 | }, 54 | { 55 | name: "int32", 56 | f: func() interface{} { 57 | return btcjson.Int32(5) 58 | }, 59 | expected: func() interface{} { 60 | val := int32(5) 61 | return &val 62 | }(), 63 | }, 64 | { 65 | name: "uint32", 66 | f: func() interface{} { 67 | return btcjson.Uint32(5) 68 | }, 69 | expected: func() interface{} { 70 | val := uint32(5) 71 | return &val 72 | }(), 73 | }, 74 | { 75 | name: "int64", 76 | f: func() interface{} { 77 | return btcjson.Int64(5) 78 | }, 79 | expected: func() interface{} { 80 | val := int64(5) 81 | return &val 82 | }(), 83 | }, 84 | { 85 | name: "uint64", 86 | f: func() interface{} { 87 | return btcjson.Uint64(5) 88 | }, 89 | expected: func() interface{} { 90 | val := uint64(5) 91 | return &val 92 | }(), 93 | }, 94 | { 95 | name: "string", 96 | f: func() interface{} { 97 | return btcjson.String("abc") 98 | }, 99 | expected: func() interface{} { 100 | val := "abc" 101 | return &val 102 | }(), 103 | }, 104 | } 105 | 106 | t.Logf("Running %d tests", len(tests)) 107 | for i, test := range tests { 108 | result := test.f() 109 | if !reflect.DeepEqual(result, test.expected) { 110 | t.Errorf("Test #%d (%s) unexpected value - got %v, "+ 111 | "want %v", i, test.name, result, test.expected) 112 | continue 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /rpcclient/README.md: -------------------------------------------------------------------------------- 1 | rpcclient 2 | ========= 3 | 4 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 5 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 6 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd/rpcclient) 7 | 8 | rpcclient implements a Websocket-enabled Bitcoin JSON-RPC client package written 9 | in [Go](http://golang.org/). It provides a robust and easy to use client for 10 | interfacing with a Bitcoin RPC server that uses a btcd/bitcoin core compatible 11 | Bitcoin JSON-RPC API. 12 | 13 | ## Status 14 | 15 | This package is currently under active development. It is already stable and 16 | the infrastructure is complete. However, there are still several RPCs left to 17 | implement and the API is not stable yet. 18 | 19 | ## Documentation 20 | 21 | * [API Reference](https://pkg.go.dev/github.com/btcsuite/btcd/rpcclient) 22 | * [btcd Websockets Example](https://github.com/btcsuite/btcd/tree/master/rpcclient/examples/btcdwebsockets) 23 | Connects to a btcd RPC server using TLS-secured websockets, registers for 24 | block connected and block disconnected notifications, and gets the current 25 | block count 26 | * [btcwallet Websockets Example](https://github.com/btcsuite/btcd/tree/master/rpcclient/examples/btcwalletwebsockets) 27 | Connects to a btcwallet RPC server using TLS-secured websockets, registers for 28 | notifications about changes to account balances, and gets a list of unspent 29 | transaction outputs (utxos) the wallet can sign 30 | * [Bitcoin Core HTTP POST Example](https://github.com/btcsuite/btcd/tree/master/rpcclient/examples/bitcoincorehttp) 31 | Connects to a bitcoin core RPC server using HTTP POST mode with TLS disabled 32 | and gets the current block count 33 | 34 | ## Major Features 35 | 36 | * Supports Websockets (btcd/btcwallet) and HTTP POST mode (bitcoin core) 37 | * Provides callback and registration functions for btcd/btcwallet notifications 38 | * Supports btcd extensions 39 | * Translates to and from higher-level and easier to use Go types 40 | * Offers a synchronous (blocking) and asynchronous API 41 | * When running in Websockets mode (the default): 42 | * Automatic reconnect handling (can be disabled) 43 | * Outstanding commands are automatically reissued 44 | * Registered notifications are automatically reregistered 45 | * Back-off support on reconnect attempts 46 | 47 | ## Installation 48 | 49 | ```bash 50 | $ go get -u github.com/btcsuite/btcd/rpcclient 51 | ``` 52 | 53 | ## License 54 | 55 | Package rpcclient is licensed under the [copyfree](http://copyfree.org) ISC 56 | License. 57 | -------------------------------------------------------------------------------- /version.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "bytes" 9 | "fmt" 10 | "strings" 11 | ) 12 | 13 | // semanticAlphabet 14 | const semanticAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-" 15 | 16 | // These constants define the application version and follow the semantic 17 | // versioning 2.0.0 spec (http://semver.org/). 18 | const ( 19 | appMajor uint = 0 20 | appMinor uint = 22 21 | appPatch uint = 0 22 | 23 | // appPreRelease MUST only contain characters from semanticAlphabet 24 | // per the semantic versioning spec. 25 | appPreRelease = "beta" 26 | ) 27 | 28 | // appBuild is defined as a variable so it can be overridden during the build 29 | // process with '-ldflags "-X main.appBuild foo' if needed. It MUST only 30 | // contain characters from semanticAlphabet per the semantic versioning spec. 31 | var appBuild string 32 | 33 | // version returns the application version as a properly formed string per the 34 | // semantic versioning 2.0.0 spec (http://semver.org/). 35 | func version() string { 36 | // Start with the major, minor, and patch versions. 37 | version := fmt.Sprintf("%d.%d.%d", appMajor, appMinor, appPatch) 38 | 39 | // Append pre-release version if there is one. The hyphen called for 40 | // by the semantic versioning spec is automatically appended and should 41 | // not be contained in the pre-release string. The pre-release version 42 | // is not appended if it contains invalid characters. 43 | preRelease := normalizeVerString(appPreRelease) 44 | if preRelease != "" { 45 | version = fmt.Sprintf("%s-%s", version, preRelease) 46 | } 47 | 48 | // Append build metadata if there is any. The plus called for 49 | // by the semantic versioning spec is automatically appended and should 50 | // not be contained in the build metadata string. The build metadata 51 | // string is not appended if it contains invalid characters. 52 | build := normalizeVerString(appBuild) 53 | if build != "" { 54 | version = fmt.Sprintf("%s+%s", version, build) 55 | } 56 | 57 | return version 58 | } 59 | 60 | // normalizeVerString returns the passed string stripped of all characters which 61 | // are not valid according to the semantic versioning guidelines for pre-release 62 | // version and build metadata strings. In particular they MUST only contain 63 | // characters in semanticAlphabet. 64 | func normalizeVerString(str string) string { 65 | var result bytes.Buffer 66 | for _, r := range str { 67 | if strings.ContainsRune(semanticAlphabet, r) { 68 | result.WriteRune(r) 69 | } 70 | } 71 | return result.String() 72 | } 73 | -------------------------------------------------------------------------------- /netsync/blocklogger.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package netsync 6 | 7 | import ( 8 | "sync" 9 | "time" 10 | 11 | "github.com/btcsuite/btclog" 12 | "github.com/btcsuite/btcutil" 13 | ) 14 | 15 | // blockProgressLogger provides periodic logging for other services in order 16 | // to show users progress of certain "actions" involving some or all current 17 | // blocks. Ex: syncing to best chain, indexing all blocks, etc. 18 | type blockProgressLogger struct { 19 | receivedLogBlocks int64 20 | receivedLogTx int64 21 | lastBlockLogTime time.Time 22 | 23 | subsystemLogger btclog.Logger 24 | progressAction string 25 | sync.Mutex 26 | } 27 | 28 | // newBlockProgressLogger returns a new block progress logger. 29 | // The progress message is templated as follows: 30 | // {progressAction} {numProcessed} {blocks|block} in the last {timePeriod} 31 | // ({numTxs}, height {lastBlockHeight}, {lastBlockTimeStamp}) 32 | func newBlockProgressLogger(progressMessage string, logger btclog.Logger) *blockProgressLogger { 33 | return &blockProgressLogger{ 34 | lastBlockLogTime: time.Now(), 35 | progressAction: progressMessage, 36 | subsystemLogger: logger, 37 | } 38 | } 39 | 40 | // LogBlockHeight logs a new block height as an information message to show 41 | // progress to the user. In order to prevent spam, it limits logging to one 42 | // message every 10 seconds with duration and totals included. 43 | func (b *blockProgressLogger) LogBlockHeight(block *btcutil.Block) { 44 | b.Lock() 45 | defer b.Unlock() 46 | 47 | b.receivedLogBlocks++ 48 | b.receivedLogTx += int64(len(block.MsgBlock().Transactions)) 49 | 50 | now := time.Now() 51 | duration := now.Sub(b.lastBlockLogTime) 52 | if duration < time.Second*10 { 53 | return 54 | } 55 | 56 | // Truncate the duration to 10s of milliseconds. 57 | durationMillis := int64(duration / time.Millisecond) 58 | tDuration := 10 * time.Millisecond * time.Duration(durationMillis/10) 59 | 60 | // Log information about new block height. 61 | blockStr := "blocks" 62 | if b.receivedLogBlocks == 1 { 63 | blockStr = "block" 64 | } 65 | txStr := "transactions" 66 | if b.receivedLogTx == 1 { 67 | txStr = "transaction" 68 | } 69 | b.subsystemLogger.Infof("%s %d %s in the last %s (%d %s, height %d, %s)", 70 | b.progressAction, b.receivedLogBlocks, blockStr, tDuration, b.receivedLogTx, 71 | txStr, block.Height(), block.MsgBlock().Header.Timestamp) 72 | 73 | b.receivedLogBlocks = 0 74 | b.receivedLogTx = 0 75 | b.lastBlockLogTime = now 76 | } 77 | 78 | func (b *blockProgressLogger) SetLastLogTime(time time.Time) { 79 | b.lastBlockLogTime = time 80 | } 81 | -------------------------------------------------------------------------------- /chaincfg/doc.go: -------------------------------------------------------------------------------- 1 | // Package chaincfg defines chain configuration parameters. 2 | // 3 | // In addition to the main Bitcoin network, which is intended for the transfer 4 | // of monetary value, there also exists two currently active standard networks: 5 | // regression test and testnet (version 3). These networks are incompatible 6 | // with each other (each sharing a different genesis block) and software should 7 | // handle errors where input intended for one network is used on an application 8 | // instance running on a different network. 9 | // 10 | // For library packages, chaincfg provides the ability to lookup chain 11 | // parameters and encoding magics when passed a *Params. Older APIs not updated 12 | // to the new convention of passing a *Params may lookup the parameters for a 13 | // wire.BitcoinNet using ParamsForNet, but be aware that this usage is 14 | // deprecated and will be removed from chaincfg in the future. 15 | // 16 | // For main packages, a (typically global) var may be assigned the address of 17 | // one of the standard Param vars for use as the application's "active" network. 18 | // When a network parameter is needed, it may then be looked up through this 19 | // variable (either directly, or hidden in a library call). 20 | // 21 | // package main 22 | // 23 | // import ( 24 | // "flag" 25 | // "fmt" 26 | // "log" 27 | // 28 | // "github.com/btcsuite/btcutil" 29 | // "github.com/btcsuite/btcd/chaincfg" 30 | // ) 31 | // 32 | // var testnet = flag.Bool("testnet", false, "operate on the testnet Bitcoin network") 33 | // 34 | // // By default (without -testnet), use mainnet. 35 | // var chainParams = &chaincfg.MainNetParams 36 | // 37 | // func main() { 38 | // flag.Parse() 39 | // 40 | // // Modify active network parameters if operating on testnet. 41 | // if *testnet { 42 | // chainParams = &chaincfg.TestNet3Params 43 | // } 44 | // 45 | // // later... 46 | // 47 | // // Create and print new payment address, specific to the active network. 48 | // pubKeyHash := make([]byte, 20) 49 | // addr, err := btcutil.NewAddressPubKeyHash(pubKeyHash, chainParams) 50 | // if err != nil { 51 | // log.Fatal(err) 52 | // } 53 | // fmt.Println(addr) 54 | // } 55 | // 56 | // If an application does not use one of the three standard Bitcoin networks, 57 | // a new Params struct may be created which defines the parameters for the 58 | // non-standard network. As a general rule of thumb, all network parameters 59 | // should be unique to the network, but parameter collisions can still occur 60 | // (unfortunately, this is the case with regtest and testnet3 sharing magics). 61 | package chaincfg 62 | -------------------------------------------------------------------------------- /database/cmd/dbtool/loadheaders.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2015-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "time" 9 | 10 | "github.com/btcsuite/btcd/chaincfg/chainhash" 11 | "github.com/btcsuite/btcd/database" 12 | ) 13 | 14 | // headersCmd defines the configuration options for the loadheaders command. 15 | type headersCmd struct { 16 | Bulk bool `long:"bulk" description:"Use bulk loading of headers instead of one at a time"` 17 | } 18 | 19 | var ( 20 | // headersCfg defines the configuration options for the command. 21 | headersCfg = headersCmd{ 22 | Bulk: false, 23 | } 24 | ) 25 | 26 | // Execute is the main entry point for the command. It's invoked by the parser. 27 | func (cmd *headersCmd) Execute(args []string) error { 28 | // Setup the global config options and ensure they are valid. 29 | if err := setupGlobalConfig(); err != nil { 30 | return err 31 | } 32 | 33 | // Load the block database. 34 | db, err := loadBlockDB() 35 | if err != nil { 36 | return err 37 | } 38 | defer db.Close() 39 | 40 | // NOTE: This code will only work for ffldb. Ideally the package using 41 | // the database would keep a metadata index of its own. 42 | blockIdxName := []byte("ffldb-blockidx") 43 | if !headersCfg.Bulk { 44 | err = db.View(func(tx database.Tx) error { 45 | totalHdrs := 0 46 | blockIdxBucket := tx.Metadata().Bucket(blockIdxName) 47 | blockIdxBucket.ForEach(func(k, v []byte) error { 48 | totalHdrs++ 49 | return nil 50 | }) 51 | log.Infof("Loading headers for %d blocks...", totalHdrs) 52 | numLoaded := 0 53 | startTime := time.Now() 54 | blockIdxBucket.ForEach(func(k, v []byte) error { 55 | var hash chainhash.Hash 56 | copy(hash[:], k) 57 | _, err := tx.FetchBlockHeader(&hash) 58 | if err != nil { 59 | return err 60 | } 61 | numLoaded++ 62 | return nil 63 | }) 64 | log.Infof("Loaded %d headers in %v", numLoaded, 65 | time.Since(startTime)) 66 | return nil 67 | }) 68 | return err 69 | } 70 | 71 | // Bulk load headers. 72 | err = db.View(func(tx database.Tx) error { 73 | blockIdxBucket := tx.Metadata().Bucket(blockIdxName) 74 | hashes := make([]chainhash.Hash, 0, 500000) 75 | blockIdxBucket.ForEach(func(k, v []byte) error { 76 | var hash chainhash.Hash 77 | copy(hash[:], k) 78 | hashes = append(hashes, hash) 79 | return nil 80 | }) 81 | 82 | log.Infof("Loading headers for %d blocks...", len(hashes)) 83 | startTime := time.Now() 84 | hdrs, err := tx.FetchBlockHeaders(hashes) 85 | if err != nil { 86 | return err 87 | } 88 | log.Infof("Loaded %d headers in %v", len(hdrs), 89 | time.Since(startTime)) 90 | return nil 91 | }) 92 | return err 93 | } 94 | -------------------------------------------------------------------------------- /btcjson/helpers.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package btcjson 6 | 7 | // Bool is a helper routine that allocates a new bool value to store v and 8 | // returns a pointer to it. This is useful when assigning optional parameters. 9 | func Bool(v bool) *bool { 10 | p := new(bool) 11 | *p = v 12 | return p 13 | } 14 | 15 | // Int is a helper routine that allocates a new int value to store v and 16 | // returns a pointer to it. This is useful when assigning optional parameters. 17 | func Int(v int) *int { 18 | p := new(int) 19 | *p = v 20 | return p 21 | } 22 | 23 | // Uint is a helper routine that allocates a new uint value to store v and 24 | // returns a pointer to it. This is useful when assigning optional parameters. 25 | func Uint(v uint) *uint { 26 | p := new(uint) 27 | *p = v 28 | return p 29 | } 30 | 31 | // Int32 is a helper routine that allocates a new int32 value to store v and 32 | // returns a pointer to it. This is useful when assigning optional parameters. 33 | func Int32(v int32) *int32 { 34 | p := new(int32) 35 | *p = v 36 | return p 37 | } 38 | 39 | // Uint32 is a helper routine that allocates a new uint32 value to store v and 40 | // returns a pointer to it. This is useful when assigning optional parameters. 41 | func Uint32(v uint32) *uint32 { 42 | p := new(uint32) 43 | *p = v 44 | return p 45 | } 46 | 47 | // Int64 is a helper routine that allocates a new int64 value to store v and 48 | // returns a pointer to it. This is useful when assigning optional parameters. 49 | func Int64(v int64) *int64 { 50 | p := new(int64) 51 | *p = v 52 | return p 53 | } 54 | 55 | // Uint64 is a helper routine that allocates a new uint64 value to store v and 56 | // returns a pointer to it. This is useful when assigning optional parameters. 57 | func Uint64(v uint64) *uint64 { 58 | p := new(uint64) 59 | *p = v 60 | return p 61 | } 62 | 63 | // Float64 is a helper routine that allocates a new float64 value to store v and 64 | // returns a pointer to it. This is useful when assigning optional parameters. 65 | func Float64(v float64) *float64 { 66 | p := new(float64) 67 | *p = v 68 | return p 69 | } 70 | 71 | // String is a helper routine that allocates a new string value to store v and 72 | // returns a pointer to it. This is useful when assigning optional parameters. 73 | func String(v string) *string { 74 | p := new(string) 75 | *p = v 76 | return p 77 | } 78 | 79 | // NewFilterTypeName is a helper routine that allocates a new FilterTypeName value to store v and 80 | // returns a pointer to it. This is useful when assigning optional parameters. 81 | func NewFilterTypeName(v FilterTypeName) *FilterTypeName { 82 | p := new(FilterTypeName) 83 | *p = v 84 | return p 85 | } 86 | -------------------------------------------------------------------------------- /rpcclient/rawrequest.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2017 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package rpcclient 6 | 7 | import ( 8 | "encoding/json" 9 | "errors" 10 | 11 | "github.com/btcsuite/btcd/btcjson" 12 | ) 13 | 14 | // FutureRawResult is a future promise to deliver the result of a RawRequest RPC 15 | // invocation (or an applicable error). 16 | type FutureRawResult chan *response 17 | 18 | // Receive waits for the response promised by the future and returns the raw 19 | // response, or an error if the request was unsuccessful. 20 | func (r FutureRawResult) Receive() (json.RawMessage, error) { 21 | return receiveFuture(r) 22 | } 23 | 24 | // RawRequestAsync returns an instance of a type that can be used to get the 25 | // result of a custom RPC request at some future time by invoking the Receive 26 | // function on the returned instance. 27 | // 28 | // See RawRequest for the blocking version and more details. 29 | func (c *Client) RawRequestAsync(method string, params []json.RawMessage) FutureRawResult { 30 | // Method may not be empty. 31 | if method == "" { 32 | return newFutureError(errors.New("no method")) 33 | } 34 | 35 | // Marshal parameters as "[]" instead of "null" when no parameters 36 | // are passed. 37 | if params == nil { 38 | params = []json.RawMessage{} 39 | } 40 | 41 | // Create a raw JSON-RPC request using the provided method and params 42 | // and marshal it. This is done rather than using the sendCmd function 43 | // since that relies on marshalling registered btcjson commands rather 44 | // than custom commands. 45 | id := c.NextID() 46 | rawRequest := &btcjson.Request{ 47 | Jsonrpc: btcjson.RpcVersion1, 48 | ID: id, 49 | Method: method, 50 | Params: params, 51 | } 52 | marshalledJSON, err := json.Marshal(rawRequest) 53 | if err != nil { 54 | return newFutureError(err) 55 | } 56 | 57 | // Generate the request and send it along with a channel to respond on. 58 | responseChan := make(chan *response, 1) 59 | jReq := &jsonRequest{ 60 | id: id, 61 | method: method, 62 | cmd: nil, 63 | marshalledJSON: marshalledJSON, 64 | responseChan: responseChan, 65 | } 66 | c.sendRequest(jReq) 67 | 68 | return responseChan 69 | } 70 | 71 | // RawRequest allows the caller to send a raw or custom request to the server. 72 | // This method may be used to send and receive requests and responses for 73 | // requests that are not handled by this client package, or to proxy partially 74 | // unmarshaled requests to another JSON-RPC server if a request cannot be 75 | // handled directly. 76 | func (c *Client) RawRequest(method string, params []json.RawMessage) (json.RawMessage, error) { 77 | return c.RawRequestAsync(method, params).Receive() 78 | } 79 | -------------------------------------------------------------------------------- /wire/msgpong.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | ) 11 | 12 | // MsgPong implements the Message interface and represents a bitcoin pong 13 | // message which is used primarily to confirm that a connection is still valid 14 | // in response to a bitcoin ping message (MsgPing). 15 | // 16 | // This message was not added until protocol versions AFTER BIP0031Version. 17 | type MsgPong struct { 18 | // Unique value associated with message that is used to identify 19 | // specific ping message. 20 | Nonce uint64 21 | } 22 | 23 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 24 | // This is part of the Message interface implementation. 25 | func (msg *MsgPong) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 26 | // NOTE: <= is not a mistake here. The BIP0031 was defined as AFTER 27 | // the version unlike most others. 28 | if pver <= BIP0031Version { 29 | str := fmt.Sprintf("pong message invalid for protocol "+ 30 | "version %d", pver) 31 | return messageError("MsgPong.BtcDecode", str) 32 | } 33 | 34 | return readElement(r, &msg.Nonce) 35 | } 36 | 37 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 38 | // This is part of the Message interface implementation. 39 | func (msg *MsgPong) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 40 | // NOTE: <= is not a mistake here. The BIP0031 was defined as AFTER 41 | // the version unlike most others. 42 | if pver <= BIP0031Version { 43 | str := fmt.Sprintf("pong message invalid for protocol "+ 44 | "version %d", pver) 45 | return messageError("MsgPong.BtcEncode", str) 46 | } 47 | 48 | return writeElement(w, msg.Nonce) 49 | } 50 | 51 | // Command returns the protocol command string for the message. This is part 52 | // of the Message interface implementation. 53 | func (msg *MsgPong) Command() string { 54 | return CmdPong 55 | } 56 | 57 | // MaxPayloadLength returns the maximum length the payload can be for the 58 | // receiver. This is part of the Message interface implementation. 59 | func (msg *MsgPong) MaxPayloadLength(pver uint32) uint32 { 60 | plen := uint32(0) 61 | // The pong message did not exist for BIP0031Version and earlier. 62 | // NOTE: > is not a mistake here. The BIP0031 was defined as AFTER 63 | // the version unlike most others. 64 | if pver > BIP0031Version { 65 | // Nonce 8 bytes. 66 | plen += 8 67 | } 68 | 69 | return plen 70 | } 71 | 72 | // NewMsgPong returns a new bitcoin pong message that conforms to the Message 73 | // interface. See MsgPong for details. 74 | func NewMsgPong(nonce uint64) *MsgPong { 75 | return &MsgPong{ 76 | Nonce: nonce, 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /docs/installation.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | The first step is to install btcd. See one of the following sections for 4 | details on how to install on the supported operating systems. 5 | 6 | ## Requirements 7 | 8 | [Go](http://golang.org) 1.11 or newer. 9 | 10 | ## GPG Verification Key 11 | 12 | All official release tags are signed by Conformal so users can ensure the code 13 | has not been tampered with and is coming from the btcsuite developers. To 14 | verify the signature perform the following: 15 | 16 | * Download the Conformal public key: 17 | https://raw.githubusercontent.com/btcsuite/btcd/master/release/GIT-GPG-KEY-conformal.txt 18 | 19 | * Import the public key into your GPG keyring: 20 | 21 | ```bash 22 | gpg --import GIT-GPG-KEY-conformal.txt 23 | ``` 24 | 25 | * Verify the release tag with the following command where `TAG_NAME` is a 26 | placeholder for the specific tag: 27 | 28 | ```bash 29 | git tag -v TAG_NAME 30 | ``` 31 | 32 | ## Windows Installation 33 | 34 | * Install the MSI available at: [btcd windows installer](https://github.com/btcsuite/btcd/releases) 35 | * Launch btcd from the Start Menu 36 | 37 | ## Linux/BSD/MacOSX/POSIX Installation 38 | 39 | * Install Go according to the [installation instructions](http://golang.org/doc/install) 40 | * Ensure Go was installed properly and is a supported version: 41 | 42 | ```bash 43 | go version 44 | go env GOROOT GOPATH 45 | ``` 46 | 47 | NOTE: The `GOROOT` and `GOPATH` above must not be the same path. It is 48 | recommended that `GOPATH` is set to a directory in your home directory such as 49 | `~/goprojects` to avoid write permission issues. It is also recommended to add 50 | `$GOPATH/bin` to your `PATH` at this point. 51 | 52 | * Run the following commands to obtain btcd, all dependencies, and install it: 53 | 54 | ```bash 55 | git clone https://github.com/btcsuite/btcd $GOPATH/src/github.com/btcsuite/btcd 56 | cd $GOPATH/src/github.com/btcsuite/btcd 57 | GO111MODULE=on go install -v . ./cmd/... 58 | ``` 59 | 60 | * btcd (and utilities) will now be installed in ```$GOPATH/bin```. If you did 61 | not already add the bin directory to your system path during Go installation, 62 | we recommend you do so now. 63 | 64 | ## Gentoo Linux Installation 65 | 66 | * [Install Layman](https://gitlab.com/bitcoin/gentoo) and enable the Bitcoin overlay. 67 | * Copy or symlink `/var/lib/layman/bitcoin/Documentation/package.keywords/btcd-live` to `/etc/portage/package.keywords/` 68 | * Install btcd: `$ emerge net-p2p/btcd` 69 | 70 | ## Startup 71 | 72 | Typically btcd will run and start downloading the block chain with no extra 73 | configuration necessary, however, there is an optional method to use a 74 | `bootstrap.dat` file that may speed up the initial block chain download process. 75 | 76 | * [Using bootstrap.dat](https://github.com/btcsuite/btcd/blob/master/docs/configuration.md#using-bootstrapdat) 77 | -------------------------------------------------------------------------------- /wire/msgfilteradd.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014-2015 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | ) 11 | 12 | const ( 13 | // MaxFilterAddDataSize is the maximum byte size of a data 14 | // element to add to the Bloom filter. It is equal to the 15 | // maximum element size of a script. 16 | MaxFilterAddDataSize = 520 17 | ) 18 | 19 | // MsgFilterAdd implements the Message interface and represents a bitcoin 20 | // filteradd message. It is used to add a data element to an existing Bloom 21 | // filter. 22 | // 23 | // This message was not added until protocol version BIP0037Version. 24 | type MsgFilterAdd struct { 25 | Data []byte 26 | } 27 | 28 | // BtcDecode decodes r using the bitcoin protocol encoding into the receiver. 29 | // This is part of the Message interface implementation. 30 | func (msg *MsgFilterAdd) BtcDecode(r io.Reader, pver uint32, enc MessageEncoding) error { 31 | if pver < BIP0037Version { 32 | str := fmt.Sprintf("filteradd message invalid for protocol "+ 33 | "version %d", pver) 34 | return messageError("MsgFilterAdd.BtcDecode", str) 35 | } 36 | 37 | var err error 38 | msg.Data, err = ReadVarBytes(r, pver, MaxFilterAddDataSize, 39 | "filteradd data") 40 | return err 41 | } 42 | 43 | // BtcEncode encodes the receiver to w using the bitcoin protocol encoding. 44 | // This is part of the Message interface implementation. 45 | func (msg *MsgFilterAdd) BtcEncode(w io.Writer, pver uint32, enc MessageEncoding) error { 46 | if pver < BIP0037Version { 47 | str := fmt.Sprintf("filteradd message invalid for protocol "+ 48 | "version %d", pver) 49 | return messageError("MsgFilterAdd.BtcEncode", str) 50 | } 51 | 52 | size := len(msg.Data) 53 | if size > MaxFilterAddDataSize { 54 | str := fmt.Sprintf("filteradd size too large for message "+ 55 | "[size %v, max %v]", size, MaxFilterAddDataSize) 56 | return messageError("MsgFilterAdd.BtcEncode", str) 57 | } 58 | 59 | return WriteVarBytes(w, pver, msg.Data) 60 | } 61 | 62 | // Command returns the protocol command string for the message. This is part 63 | // of the Message interface implementation. 64 | func (msg *MsgFilterAdd) Command() string { 65 | return CmdFilterAdd 66 | } 67 | 68 | // MaxPayloadLength returns the maximum length the payload can be for the 69 | // receiver. This is part of the Message interface implementation. 70 | func (msg *MsgFilterAdd) MaxPayloadLength(pver uint32) uint32 { 71 | return uint32(VarIntSerializeSize(MaxFilterAddDataSize)) + 72 | MaxFilterAddDataSize 73 | } 74 | 75 | // NewMsgFilterAdd returns a new bitcoin filteradd message that conforms to the 76 | // Message interface. See MsgFilterAdd for details. 77 | func NewMsgFilterAdd(data []byte) *MsgFilterAdd { 78 | return &MsgFilterAdd{ 79 | Data: data, 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | # import os 14 | # import sys 15 | # sys.path.insert(0, os.path.abspath('.')) 16 | import recommonmark 17 | from recommonmark.transform import AutoStructify 18 | 19 | # -- Project information ----------------------------------------------------- 20 | 21 | project = 'btcd' 22 | copyright = '2020, btcd' 23 | author = 'btcsuite developers' 24 | 25 | # The full version, including alpha/beta/rc tags 26 | release = 'beta' 27 | 28 | source_suffix = ['.md'] 29 | 30 | # The master toctree document. 31 | master_doc = 'index' 32 | 33 | # -- General configuration --------------------------------------------------- 34 | 35 | # Add any Sphinx extension module names here, as strings. They can be 36 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 37 | # ones. 38 | extensions = [ 39 | 'sphinx.ext.autodoc', 40 | 'sphinx.ext.napoleon', 41 | 'sphinx.ext.mathjax', 42 | 'sphinx_markdown_tables', 43 | 'recommonmark', 44 | ] 45 | 46 | # Add any paths that contain templates here, relative to this directory. 47 | templates_path = ['_templates'] 48 | 49 | # List of patterns, relative to source directory, that match files and 50 | # directories to ignore when looking for source files. 51 | # This pattern also affects html_static_path and html_extra_path. 52 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 53 | 54 | 55 | # -- Options for HTML output ------------------------------------------------- 56 | 57 | # The theme to use for HTML and HTML Help pages. See the documentation for 58 | # a list of builtin themes. 59 | # 60 | html_theme = 'sphinx_rtd_theme' 61 | 62 | # Add any paths that contain custom static files (such as style sheets) here, 63 | # relative to this directory. They are copied after the builtin static files, 64 | # so a file named "default.css" will overwrite the builtin "default.css". 65 | html_static_path = ['_static'] 66 | 67 | # app setup hook 68 | def setup(app): 69 | app.add_config_value('recommonmark_config', { 70 | #'url_resolver': lambda url: github_doc_root + url, 71 | 'auto_toc_tree_section': 'Contents', 72 | 'enable_math': False, 73 | 'enable_inline_math': False, 74 | 'enable_eval_rst': True, 75 | 'enable_auto_doc_ref': True, 76 | }, True) 77 | app.add_transform(AutoStructify) 78 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # btcd 2 | 3 | [![Build Status](https://github.com/btcsuite/btcd/workflows/Build%20and%20Test/badge.svg)](https://github.com/btcsuite/btcd/actions) 4 | [![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) 5 | [![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/btcsuite/btcd) 6 | 7 | btcd is an alternative full node bitcoin implementation written in Go (golang). 8 | 9 | This project is currently under active development and is in a Beta state. It 10 | is extremely stable and has been in production use since October 2013. 11 | 12 | It properly downloads, validates, and serves the block chain using the exact 13 | rules (including consensus bugs) for block acceptance as Bitcoin Core. We have 14 | taken great care to avoid btcd causing a fork to the block chain. It includes a 15 | full block validation testing framework which contains all of the 'official' 16 | block acceptance tests (and some additional ones) that is run on every pull 17 | request to help ensure it properly follows consensus. Also, it passes all of 18 | the JSON test data in the Bitcoin Core code. 19 | 20 | It also properly relays newly mined blocks, maintains a transaction pool, and 21 | relays individual transactions that have not yet made it into a block. It 22 | ensures all individual transactions admitted to the pool follow the rules 23 | required by the block chain and also includes more strict checks which filter 24 | transactions based on miner requirements ("standard" transactions). 25 | 26 | One key difference between btcd and Bitcoin Core is that btcd does *NOT* include 27 | wallet functionality and this was a very intentional design decision. See the 28 | blog entry [here](https://web.archive.org/web/20171125143919/https://blog.conformal.com/btcd-not-your-moms-bitcoin-daemon) 29 | for more details. This means you can't actually make or receive payments 30 | directly with btcd. That functionality is provided by the 31 | [btcwallet](https://github.com/btcsuite/btcwallet) and 32 | [Paymetheus](https://github.com/btcsuite/Paymetheus) (Windows-only) projects 33 | which are both under active development. 34 | 35 | ## Documentation 36 | 37 | Documentation is a work-in-progress. It is available at [btcd.readthedocs.io](https://btcd.readthedocs.io). 38 | 39 | ## Contents 40 | 41 | * [Installation](installation.md) 42 | * [Update](update.md) 43 | * [Configuration](configuration.md) 44 | * [Configuring TOR](configuring_tor.md) 45 | * [Docker](using_docker.md) 46 | * [Controlling](controlling.md) 47 | * [Mining](mining.md) 48 | * [Wallet](wallet.md) 49 | * [Developer resources](developer_resources.md) 50 | * [JSON RPC API](json_rpc_api.md) 51 | * [Code contribution guidelines](code_contribution_guidelines.md) 52 | * [Contact](contact.md) 53 | 54 | ## License 55 | 56 | btcd is licensed under the [copyfree](http://copyfree.org) ISC License. 57 | 58 | -------------------------------------------------------------------------------- /cmd/btcctl/version.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | import ( 8 | "bytes" 9 | "fmt" 10 | "strings" 11 | ) 12 | 13 | // semanticAlphabet 14 | const semanticAlphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-" 15 | 16 | // These constants define the application version and follow the semantic 17 | // versioning 2.0.0 spec (http://semver.org/). 18 | const ( 19 | appMajor uint = 0 20 | appMinor uint = 22 21 | appPatch uint = 0 22 | 23 | // appPreRelease MUST only contain characters from semanticAlphabet 24 | // per the semantic versioning spec. 25 | appPreRelease = "beta" 26 | ) 27 | 28 | // appBuild is defined as a variable so it can be overridden during the build 29 | // process with '-ldflags "-X main.appBuild foo' if needed. It MUST only 30 | // contain characters from semanticAlphabet per the semantic versioning spec. 31 | var appBuild string 32 | 33 | // version returns the application version as a properly formed string per the 34 | // semantic versioning 2.0.0 spec (http://semver.org/). 35 | func version() string { 36 | // Start with the major, minor, and patch versions. 37 | version := fmt.Sprintf("%d.%d.%d", appMajor, appMinor, appPatch) 38 | 39 | // Append pre-release version if there is one. The hyphen called for 40 | // by the semantic versioning spec is automatically appended and should 41 | // not be contained in the pre-release string. The pre-release version 42 | // is not appended if it contains invalid characters. 43 | preRelease := normalizeVerString(appPreRelease) 44 | if preRelease != "" { 45 | version = fmt.Sprintf("%s-%s", version, preRelease) 46 | } 47 | 48 | // Append build metadata if there is any. The plus called for 49 | // by the semantic versioning spec is automatically appended and should 50 | // not be contained in the build metadata string. The build metadata 51 | // string is not appended if it contains invalid characters. 52 | build := normalizeVerString(appBuild) 53 | if build != "" { 54 | version = fmt.Sprintf("%s+%s", version, build) 55 | } 56 | 57 | return version 58 | } 59 | 60 | // normalizeVerString returns the passed string stripped of all characters which 61 | // are not valid according to the semantic versioning guidelines for pre-release 62 | // version and build metadata strings. In particular they MUST only contain 63 | // characters in semanticAlphabet. 64 | func normalizeVerString(str string) string { 65 | var result bytes.Buffer 66 | for _, r := range str { 67 | if strings.ContainsRune(semanticAlphabet, r) { 68 | // Ignoring the error here since it can only fail if 69 | // the the system is out of memory and there are much 70 | // bigger issues at that point. 71 | _, _ = result.WriteRune(r) 72 | } 73 | } 74 | return result.String() 75 | } 76 | -------------------------------------------------------------------------------- /rpcclient/chain_test.go: -------------------------------------------------------------------------------- 1 | package rpcclient 2 | 3 | import "testing" 4 | 5 | // TestUnmarshalGetBlockChainInfoResult ensures that the SoftForks and 6 | // UnifiedSoftForks fields of GetBlockChainInfoResult are properly unmarshaled 7 | // when using the expected backend version. 8 | func TestUnmarshalGetBlockChainInfoResultSoftForks(t *testing.T) { 9 | t.Parallel() 10 | 11 | tests := []struct { 12 | name string 13 | version BackendVersion 14 | res []byte 15 | compatible bool 16 | }{ 17 | { 18 | name: "bitcoind < 0.19.0 with separate softforks", 19 | version: BitcoindPre19, 20 | res: []byte(`{"softforks": [{"version": 2}]}`), 21 | compatible: true, 22 | }, 23 | { 24 | name: "bitcoind >= 0.19.0 with separate softforks", 25 | version: BitcoindPost19, 26 | res: []byte(`{"softforks": [{"version": 2}]}`), 27 | compatible: false, 28 | }, 29 | { 30 | name: "bitcoind < 0.19.0 with unified softforks", 31 | version: BitcoindPre19, 32 | res: []byte(`{"softforks": {"segwit": {"type": "bip9"}}}`), 33 | compatible: false, 34 | }, 35 | { 36 | name: "bitcoind >= 0.19.0 with unified softforks", 37 | version: BitcoindPost19, 38 | res: []byte(`{"softforks": {"segwit": {"type": "bip9"}}}`), 39 | compatible: true, 40 | }, 41 | } 42 | 43 | for _, test := range tests { 44 | success := t.Run(test.name, func(t *testing.T) { 45 | // We'll start by unmarshaling the JSON into a struct. 46 | // The SoftForks and UnifiedSoftForks field should not 47 | // be set yet, as they are unmarshaled within a 48 | // different function. 49 | info, err := unmarshalPartialGetBlockChainInfoResult(test.res) 50 | if err != nil { 51 | t.Fatal(err) 52 | } 53 | if info.SoftForks != nil { 54 | t.Fatal("expected SoftForks to be empty") 55 | } 56 | if info.UnifiedSoftForks != nil { 57 | t.Fatal("expected UnifiedSoftForks to be empty") 58 | } 59 | 60 | // Proceed to unmarshal the softforks of the response 61 | // with the expected version. If the version is 62 | // incompatible with the response, then this should 63 | // fail. 64 | err = unmarshalGetBlockChainInfoResultSoftForks( 65 | info, test.version, test.res, 66 | ) 67 | if test.compatible && err != nil { 68 | t.Fatalf("unable to unmarshal softforks: %v", err) 69 | } 70 | if !test.compatible && err == nil { 71 | t.Fatal("expected to not unmarshal softforks") 72 | } 73 | if !test.compatible { 74 | return 75 | } 76 | 77 | // If the version is compatible with the response, we 78 | // should expect to see the proper softforks field set. 79 | if test.version == BitcoindPost19 && 80 | info.SoftForks != nil { 81 | t.Fatal("expected SoftForks to be empty") 82 | } 83 | if test.version == BitcoindPre19 && 84 | info.UnifiedSoftForks != nil { 85 | t.Fatal("expected UnifiedSoftForks to be empty") 86 | } 87 | }) 88 | if !success { 89 | return 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /wire/invvect.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2016 The btcsuite developers 2 | // Use of this source code is governed by an ISC 3 | // license that can be found in the LICENSE file. 4 | 5 | package wire 6 | 7 | import ( 8 | "fmt" 9 | "io" 10 | 11 | "github.com/btcsuite/btcd/chaincfg/chainhash" 12 | ) 13 | 14 | const ( 15 | // MaxInvPerMsg is the maximum number of inventory vectors that can be in a 16 | // single bitcoin inv message. 17 | MaxInvPerMsg = 50000 18 | 19 | // Maximum payload size for an inventory vector. 20 | maxInvVectPayload = 4 + chainhash.HashSize 21 | 22 | // InvWitnessFlag denotes that the inventory vector type is requesting, 23 | // or sending a version which includes witness data. 24 | InvWitnessFlag = 1 << 30 25 | ) 26 | 27 | // InvType represents the allowed types of inventory vectors. See InvVect. 28 | type InvType uint32 29 | 30 | // These constants define the various supported inventory vector types. 31 | const ( 32 | InvTypeError InvType = 0 33 | InvTypeTx InvType = 1 34 | InvTypeBlock InvType = 2 35 | InvTypeFilteredBlock InvType = 3 36 | InvTypeWitnessBlock InvType = InvTypeBlock | InvWitnessFlag 37 | InvTypeWitnessTx InvType = InvTypeTx | InvWitnessFlag 38 | InvTypeFilteredWitnessBlock InvType = InvTypeFilteredBlock | InvWitnessFlag 39 | ) 40 | 41 | // Map of service flags back to their constant names for pretty printing. 42 | var ivStrings = map[InvType]string{ 43 | InvTypeError: "ERROR", 44 | InvTypeTx: "MSG_TX", 45 | InvTypeBlock: "MSG_BLOCK", 46 | InvTypeFilteredBlock: "MSG_FILTERED_BLOCK", 47 | InvTypeWitnessBlock: "MSG_WITNESS_BLOCK", 48 | InvTypeWitnessTx: "MSG_WITNESS_TX", 49 | InvTypeFilteredWitnessBlock: "MSG_FILTERED_WITNESS_BLOCK", 50 | } 51 | 52 | // String returns the InvType in human-readable form. 53 | func (invtype InvType) String() string { 54 | if s, ok := ivStrings[invtype]; ok { 55 | return s 56 | } 57 | 58 | return fmt.Sprintf("Unknown InvType (%d)", uint32(invtype)) 59 | } 60 | 61 | // InvVect defines a bitcoin inventory vector which is used to describe data, 62 | // as specified by the Type field, that a peer wants, has, or does not have to 63 | // another peer. 64 | type InvVect struct { 65 | Type InvType // Type of data 66 | Hash chainhash.Hash // Hash of the data 67 | } 68 | 69 | // NewInvVect returns a new InvVect using the provided type and hash. 70 | func NewInvVect(typ InvType, hash *chainhash.Hash) *InvVect { 71 | return &InvVect{ 72 | Type: typ, 73 | Hash: *hash, 74 | } 75 | } 76 | 77 | // readInvVect reads an encoded InvVect from r depending on the protocol 78 | // version. 79 | func readInvVect(r io.Reader, pver uint32, iv *InvVect) error { 80 | return readElements(r, &iv.Type, &iv.Hash) 81 | } 82 | 83 | // writeInvVect serializes an InvVect to w depending on the protocol version. 84 | func writeInvVect(w io.Writer, pver uint32, iv *InvVect) error { 85 | return writeElements(w, iv.Type, &iv.Hash) 86 | } 87 | --------------------------------------------------------------------------------