Commit graph

128 commits

Author SHA1 Message Date
David Hill
5016675d40 Move comment to where it belongs. 2015-11-10 13:20:29 -05:00
David Hill
cb71f278ec chaincfg: Move DNS Seeds to chaincfg.
This allows API users access to the DNS Seeds for use with SPV
clients, seeders, etc.
2015-11-09 17:21:16 -05:00
Dave Collins
aa0efa1f3e server: Allow IPv6 addresses with zone id.
This modifies the IP parsing code to work with IPv6 zone ids.  This is
needed since the net.ParseIP function does not allow zone ids even
though net.Listen does.
2015-11-09 10:39:30 -06:00
Javed Khan
00bddf7540 peer: Refactor peer code into its own package.
This commit introduces package peer which contains peer related features
refactored from peer.go.

The following is an overview of the features the package provides:

- Provides a basic concurrent safe bitcoin peer for handling bitcoin
  communications via the peer-to-peer protocol
- Full duplex reading and writing of bitcoin protocol messages
- Automatic handling of the initial handshake process including protocol
  version negotiation
- Automatic periodic keep-alive pinging and pong responses
- Asynchronous message queueing of outbound messages with optional
  channel for notification when the message is actually sent
- Inventory message batching and send trickling with known inventory
  detection and avoidance
- Ability to wait for shutdown/disconnect
- Flexible peer configuration
  - Caller is responsible for creating outgoing connections and listening
    for incoming connections so they have flexibility to establish
    connections as they see fit (proxies, etc.)
  - User agent name and version
  - Bitcoin network
  - Service support signalling (full nodes, bloom filters, etc.)
  - Maximum supported protocol version
  - Ability to register callbacks for handling bitcoin protocol messages
- Proper handling of bloom filter related commands when the caller does
  not specify the related flag to signal support
  - Disconnects the peer when the protocol version is high enough
  - Does not invoke the related callbacks for older protocol versions
- Snapshottable peer statistics such as the total number of bytes read
  and written, the remote address, user agent, and negotiated protocol
  version
- Helper functions for pushing addresses, getblocks, getheaders, and
  reject messages
  - These could all be sent manually via the standard message output
    function, but the helpers provide additional nice functionality such
    as duplicate filtering and address randomization
- Full documentation with example usage
- Test coverage

In addition to the addition of the new package, btcd has been refactored
to make use of the new package by extending the basic peer it provides to
work with the blockmanager and server to act as a full node.  The
following is a broad overview of the changes to integrate the package:

- The server is responsible for all connection management including
  persistent peers and banning
- Callbacks for all messages that are required to implement a full node
  are registered
- Logic necessary to serve data and behave as a full node is now in the
  callback registered with the peer

Finally, the following peer-related things have been improved as a part
of this refactor:

- Don't log or send reject message due to peer disconnects
- Remove trace logs that aren't particularly helpful
- Finish an old TODO to switch the queue WaitGroup over to a channel
- Improve various comments and fix some code consistency cases
- Improve a few logging bits
- Implement a most-recently-used nonce tracking for detecting self
  connections and generate a unique nonce for each peer
2015-10-23 06:17:29 +05:30
Dave Collins
5a9bac9668 Correct a few style related issues found by golint.
Also, update TravisCI goclean script to remove the special casing which
ignored 'Id' from the lint output since that exception is no longer
needed.  It was previously required due to the old version of btcjson,
but that is no longer in the repo.
2015-10-20 10:34:14 -05:00
Olaoluwa Osuntokun
0029905d43 Integrate a valid ECDSA signature cache into btcd
Introduce an ECDSA signature verification into btcd in order to
mitigate a certain DoS attack and as a performance optimization.

The benefits of SigCache are two fold. Firstly, usage of SigCache
mitigates a DoS attack wherein an attacker causes a victim's client to
hang due to worst-case behavior triggered while processing attacker
crafted invalid transactions. A detailed description of the mitigated
DoS attack can be found here: https://bitslog.wordpress.com/2013/01/23/fixed-bitcoin-vulnerability-explanation-why-the-signature-cache-is-a-dos-protection/
Secondly, usage of the SigCache introduces a signature verification
optimization which speeds up the validation of transactions within a
block, if they've already been seen and verified within the mempool.

The server itself manages the sigCache instance. The blockManager and
txMempool respectively now receive pointers to the created sigCache
instance. All read (sig triplet existence) operations on the sigCache
will not block unless a separate goroutine is adding an entry (writing)
to the sigCache. GetBlockTemplate generation now also utilizes the
sigCache in order to avoid unnecessarily double checking signatures
when generating a template after previously accepting a txn to the
mempool. Consequently, the CPU miner now also employs the same
optimization.

The maximum number of entries for the sigCache has been introduced as a
config parameter in order to allow users to configure the amount of
memory consumed by this new additional caching.
2015-10-08 17:31:42 -07:00
David Hill
c9ee3d9c5e wire: Implement SFNodeBloom (BIP0111).
SFNodeBloom is a new service flag that a node is required to use to
indicate that it supports bloom filtering.  This includes a protocol
version bump to 70011 and a wire version bump to 0.3.0.

btcd:
The SFNodeBloom flag is set by default.  A new configuration option
--nopeerbloomfilters has been added to to disable bloom filtering.

Any node advertising a version greater than or equal to 70011 that
attempts to use bloom filtering will be disconnected if bloom
filtering is disabled.

This mimics Bitcoin Core commit afb0ccaf9c9e4e8fac7db3564c4e19c9218c6b03
2015-09-28 16:25:44 -04:00
Daniel Krawisz
2dc8687728 Fix incorrect ip connection attempt logic.
The comment says "only allow recent nodes (10mins) after we failed 30 times",
but the server actually did the opposite and allowed only recent nodes before
30 failed connection attempts. This corrects the server's behavior.
2015-07-30 08:30:31 -05:00
Dave Collins
1ddf8e8edf Correct reconnect handling for persistent peers.
This commit correctly replaces persistent peers that are being retried in
the list of persistent peers so it will continue to be retried as
intended.

Also, limit the maximum retry interval for persistent peers to 5 minutes.

Fixes #463.
2015-07-20 12:35:44 -05:00
David Hill
9d6d0e4006 Keep track of peers with maps instead of lists. 2015-05-21 11:10:00 -04:00
Dave Collins
6e402deb35 Relicense to the btcsuite developers.
This commit relicenses all code in this repository to the btcsuite
developers.
2015-05-01 12:00:56 -05:00
Dave Collins
d8a4423b90 btcjson: Replace btcjson with version 2.
This commit removes the old and deprecated btcjsonv1 package, moves the
new version 2 package into its place, and updates all imports accordingly.
2015-05-01 00:43:09 -05:00
Olaoluwa Osuntokun
ab2ed710cb Fix 'add/delnode' type switch evaluation in server
* The cases for the 'addnode' command were previously
  stacked on top the new cases for the 'node' command.
  The intended behavior was to create a fall through and
  handle both commands. However, trying to use this
  syntax with a type switch caused the first case to be
  ignored.
* addnode' specific functions and structs in the server
  have been removed. Instead, the 'add' and 'del' subcommands
  are now proxied to the matching 'node' cmd functions.
2015-04-24 13:53:34 -07:00
Olaoluwa Osuntokun
65b044eea2 Fix #79 by adding a new node JSON-RPC command
* Gives node operators full control of peer connectivity
* RPC adds ability to disconnect all matching non-persistent peers,
  remove persistent peers, and connect to peers making them either
  temporary or persistent.
2015-04-14 23:07:51 -07:00
David Hill
0eef96e1c8 addrmgr: Always use a 50% chance between tried and new entries.
This change was suggested as Countermeasure 2 in
Eclipse Attacks on Bitcoin's Peer-to-Peer Network, Ethan
Heilman, Alison Kendler, Aviv Zohar, Sharon Goldberg. ePrint Archive
Report 2015/263. March 2015.

This mimics Bitcoin Core commit c6a63ceeb4956933588995bcf01dc3095aaeb1fc
2015-04-14 12:28:45 -04:00
Dave Collins
f5cdf2d6a8 Minor hashing-related optimizations.
This commit contains three classes of optimizations:
 - Reducing the number of unnecessary hash copies
 - Improve the performance of the DoubleSha256 function
 - A couple of minor optimizations of the ShaHash functions

The first class is a result of the Bytes function on a ShaHash making a
copy of the bytes before returning them.  It really should have been named
CloneBytes, but that would break the API now.

To address this, a comment has been added to the function which explicitly
calls out the copy behavior.  In addition, all call sites of .Bytes on a
ShaHash in the code base have been updated to simply slice the array when
a copy is not needed.  This saves a significant amount of data copying.

The second optimization modifies the DoubleSha256 function to directly use
fastsha256.Sum256 instead of the hasher interface.  This reduces the
number of allocations needed.  A benchmark for the function has been added
as well.

old: BenchmarkDoubleSha256  500000   3691 ns/op   192 B/op   3 allocs/op
new: BenchmarkDoubleSha256  500000   3081 ns/op    32 B/op   1 allocs/op

The final optimizations are for the ShaHash IsEqual and SetBytes functions
which have been modified to make use of the fact the type is an array and
remove an unneeded subslice.
2015-04-06 11:33:58 -05:00
Olaoluwa Osuntokun
1bf564d963 Fix #138 by dynamically updating heights of peers
In order to avoid prior situations of stalled syncs due to
outdated peer height data, we now update block heights up peers in
real-time as we learn of their announced
blocks.

Updates happen when:
   * A peer sends us an orphan block. We update based on
     the height embedded in the scriptSig for the coinbase tx
   * When a peer sends us an inv for a block we already know
     of
   * When peers announce new blocks. Subsequent
     announcements that lost the announcement race are
     recognized and peer heights are updated accordingly

Additionally, the `getpeerinfo` command has been modified
to include both the starting height, and current height of
connected peers.

Docs have been updated with `getpeerinfo` extension.
2015-04-01 17:22:45 -07:00
David Hill
db8fa6f850 Add id and timeoffset to getpeerinfo. 2015-03-09 23:27:53 -04:00
Dave Collins
637fbcadec rpcserver: Convert to make use of new btcjson.
This commit converts the RPC server over to use the new features available
in the latest version of btcjson and improve a few things along the way.
This following summarizes the changes:

- All btcjson imports have been updated to the latest package version
- The help has been significantly improved
  - Invoking help with no command specified now provides an alphabetized
    list of all supported commands along with one-line usage
  - The help for each command is automatically generated and provides much
    more explicit information such as the type of each parameter, whether
    or not it's optional or required, etc
  - The websocket-specific commands are now provided when accessing the
    help when connected via websockets
  - Help has been added for all websocket-specific commands and is only
    accessible when connected via websockets
- The error returns and handling of both the standard and websocket
  handlers has been made consistent
- All RPC errors have been converted to the new RPCError type
- Various variables have been renamed for consistency
- Several RPC errors have been improved
- The commands that are marked as unimplemented have been moved into the
  separate map where they belong
- Several comments have been improved
- An unnecessary check has been removed from the createrawtransaction
  handler
- The command parsing has been restructured a bit to pave the way for
  JSON-RPC 2.0 batching support
2015-02-24 23:46:51 -06:00
Dave Collins
6d289f602a Update btcjson path import paths to new location. 2015-02-19 11:55:22 -06:00
Dave Collins
c6bc8ac1eb Update btcnet path import paths to new location. 2015-02-05 23:24:53 -06:00
Olaoluwa Osuntokun
ecdffda748 Add support for an optional address-based transaction index.
* Address index is built up concurrently with the `--addrindex` flag.
* Entire index can be deleted with `--dropaddrindex`.
* New RPC call: `searchrawtransaction`
  * Returns all transacitons related to a particular address
  * Includes mempool transactions
  * Requires `--addrindex` to be activated and fully caught up.
* New `blockLogger` struct has been added to factor our common logging
  code
* Wiki and docs updated with new features.
2015-02-05 14:48:19 -08:00
Dave Collins
03433dad6a Update btcwire path import paths to new location. 2015-02-05 15:16:39 -06:00
Dave Collins
624bbb3216 Update btcchain import paths to new location. 2015-01-30 16:25:42 -06:00
Olaoluwa Osuntokun
c01d175fde Relay inv msgs now include underlying data object
* When an inv is to be sent to the server for relaying, the sender
already has access to the underlying data. So
instead of requiring the relay to look up the data by
hash, the data is now coupled in the request message.
2015-01-30 10:52:07 -08:00
Dave Collins
309a9ea31d Update database import paths to new location. 2015-01-27 15:38:23 -06:00
Dave Collins
f9f4d37976 Update btcd import paths to new location. 2015-01-17 00:48:13 -06:00
Dave Collins
919109f12c Update btcjson import paths to new location. 2015-01-16 23:58:09 -06:00
Dave Collins
528622b259 Update btcchain import paths to new location. 2015-01-16 18:47:50 -06:00
Dave Collins
0b7a9074ef Update btcdb import paths to new location. 2015-01-16 18:30:32 -06:00
Dave Collins
2bd21ead0b Update btcnet import paths to new location. 2015-01-16 17:31:08 -06:00
Dave Collins
54ccb83025 Update btcwire import paths to new location. 2015-01-16 15:13:21 -06:00
Dave Collins
c3065d32f4 Make use of the new btcchain MedianTimeSource.
This commit uses the new MedianTimeSource API in btcchain to create a
median time source which is stored in the server and is fed time samples
from all remote nodes that are connected.  It also modifies all call sites
which now require the the time source to pass it in.
2014-10-09 10:44:22 -05:00
David Hill
efcf90d83d Use Warnf when processing directives. 2014-09-17 09:37:37 -04:00
Olaoluwa Osuntokun
b97083f882 Fix some typos throughout repo. 2014-09-08 14:54:52 -05:00
Guilherme Salgado
ece3ed8443 Incrementally backoff when reconnecting to peers
This ensures we backoff when reconnecting to peers for which we don't
understand the replies, just like we do for peers we fail to connect to.

Closes #103
2014-07-25 14:05:56 -05:00
David Hill
ba937630d0 each goroutine needs its own random source.
caught by the race detector.
2014-07-10 14:52:02 -04:00
David Hill
e68d46f556 Add full support for BIP0037 bloom filters.
This commit implements full support for filtering based on the filterload,
filteradd, filterclear, and merkleblock messages introduced by BIP0037.

This allows btcd to work seamlessly with SPV wallets such as BitcoinJ.

Original code by @dajohi.  Cleanup, bug fixes, and polish by @davecgh.
2014-07-09 13:33:42 -05:00
David Hill
6f5a43d6c8 First round of address manager package refactor
These changes are a joint effort between myself and @dajohi.

- Separate IP address range/network code into its own file
- Group all of the RFC range declarations together
- Introduces a new unexported function to simplify the range declarations
- Add comments for all exported functions
- Use consistent variable casing in refactored code
- Add initial doc.go package overview
- Bump serialize interval to 10 minutes
- Correct GroupKey to perform as intended
- Make AddLocalAddress return error instead of just a debug message
- Add tests for AddLocalAddress
- Add tests for GroupKey
- Add tests for GetBestLocalAddress
- Use time.Time to improve readability
- Make address manager code golint clean
- Misc cleanup
- Add test coverage reporting
2014-07-07 09:04:22 -05:00
Dave Collins
62f21d3600 Move address manager to its own package.
This commit does just enough to move the address manager into its own
package.  Since it was not originally written as a package, it will
require a bit of refactoring and cleanup to turn it into a robust
package with a friendly API.
2014-07-06 01:06:38 -05:00
David Hill
ebc5db2710 Lookup each DNS seed in its own go routine.
By putting each DNS seed in its own go routine, btcd can start connecting
to nodes as they are found instead of waiting for all seeds to respond.  This
significantly speeds up startup time.

Additionally, logging was added to show how many addresses were fetched from
each seed.
2014-07-04 16:27:32 -04:00
Tomás Senart
f439dece37 Use chan struct{} for semaphores
With semaphores we don't actually care about the value passed in. It
makes sense to use a 0 bytes type in these cases.
There is also the added benefit of compiler optimisations for this
specific use case as described here:
https://docs.google.com/document/d/1yIAYmbvL3JxOKOjuCyon7JhW4cSv1wy5hC0ApeGMV9s/pub
2014-07-02 19:06:32 -05:00
Tomás Senart
a0f20007c5 golint -min_confidence=0.3 .
This commits removes a number of golint warnings. There is a class of
warnings which I can't fix due to unsufficient knowledge of the domain
at this point. These are listed here:

addrmanager.go:907:1: comment on exported method AddrManager.Attempt
should be of the form "Attempt ..."
addrmanager.go:1048:1: exported function RFC1918 should have comment or
be unexported
addrmanager.go:1058:1: exported function RFC3849 should have comment or
be unexported
addrmanager.go:1065:1: exported function RFC3927 should have comment or
be unexported
addrmanager.go:1073:1: exported function RFC3964 should have comment or
be unexported
addrmanager.go:1081:1: exported function RFC4193 should have comment or
be unexported
addrmanager.go:1089:1: exported function RFC4380 should have comment or
be unexported
addrmanager.go:1097:1: exported function RFC4843 should have comment or
be unexported
addrmanager.go:1105:1: exported function RFC4862 should have comment or
be unexported
addrmanager.go:1113:1: exported function RFC6052 should have comment or
be unexported
addrmanager.go:1121:1: exported function RFC6145 should have comment or
be unexported
addrmanager.go:1128:1: exported function Tor should have comment or be
unexported
addrmanager.go:1143:1: exported function Local should have comment or be
unexported
addrmanager.go:1228:2: exported const InterfacePrio should have comment
(or a comment on this block) or be unexported
discovery.go:26:2: exported var ErrTorInvalidAddressResponse should have
comment or be unexported
limits/limits_unix.go:19:1: exported function SetLimits should have
comment or be unexported
limits/limits_windows.go:7:1: exported function SetLimits should have
comment or be unexported
util/dropafter/dropafter.go:22:6: exported type ShaHash should have
comment or be unexported
util/dropafter/dropafter.go:38:2: exported const ArgSha should have
comment (or a comment on this block) or be unexported
util/dropafter/dropafter.go:128:5: exported var ErrBadShaPrefix should
have comment or be unexported
util/dropafter/dropafter.go:129:5: exported var ErrBadShaLen should have
comment or be unexported
util/dropafter/dropafter.go:130:5: exported var ErrBadShaChar should
have comment or be unexported
util/showblock/showblock.go:24:6: exported type ShaHash should have
comment or be unexported
util/showblock/showblock.go:46:2: exported const ArgSha should have
comment (or a comment on this block) or be unexported
util/showblock/showblock.go:163:1: exported function DumpBlock should
have comment or be unexported
util/showblock/showblock.go:211:5: exported var ErrBadShaPrefix should
have comment or be unexported
util/showblock/showblock.go:212:5: exported var ErrBadShaLen should have
comment or be unexported
util/showblock/showblock.go:213:5: exported var ErrBadShaChar should
have comment or be unexported
2014-07-02 11:01:56 -05:00
Tomás Senart
84fa553b65 Split imports into logical groups 2014-07-02 15:56:41 +02:00
Dave Collins
1db0eb4fec Update for recent btcjson changes.
This commit updates the types to match the recent changes to the btcjson
result types.
2014-06-29 16:37:21 -05:00
John C. Vernaleo
6a69acef21 Fix typo. 2014-06-12 15:41:57 -04:00
John C. Vernaleo
cd3d832551 Switch pingtime and pingwait to float64.
Needed to match bitcoin-core and btcjson.

ok @davec
2014-06-12 15:39:20 -04:00
Dave Collins
e25b644d3b Implement a built-in concurrent CPU miner.
This commit implements a built-in concurrent CPU miner that can be enabled
with the combination of the --generate and --miningaddr options.  The
--blockminsize, --blockmaxsize, and --blockprioritysize configuration
options wich already existed prior to this commit control the block
template generation and hence affect blocks mined via the new CPU miner.

The following is a quick overview of the changes and design:

- Starting btcd with --generate and no addresses specified via
  --miningaddr will give an error and exit immediately
- Makes use of multiple worker goroutines which independently create block
  templates, solve them, and submit the solved blocks
- The default number of worker threads are based on the number of
  processor cores in the system and can be dynamically changed at
  run-time
- There is a separate speed monitor goroutine used to collate periodic
  updates from the workers to calculate overall hashing speed
- The current mining state, number of workers, and hashes per second can
  be queried
- Updated sample-btcd.conf file has been updated to include the coin
  generation (mining) settings
- Updated doc.go for the new command line options

In addition the old --getworkkey option is now deprecated in favor of the
new --miningaddr option.  This was changed for a few reasons:

- There is no reason to have a separate list of keys for getwork and CPU
  mining
- getwork is deprecated and will be going away in the future so that means
  the --getworkkey flag will also be going away
- Having the work 'key' in the option can be confused with wanting a
  private key while --miningaddr make it a little more clear it is an
  address that is required

Closes #137.

Reviewed by @jrick.
2014-06-12 12:05:32 -05:00
Dave Collins
c673d76979 Fix case where block mgr could hang on shutdown.
This commit resolves an issue where it was possible the block manager
could hang on shutdown due to inventory rebroadcasting.  In particular, it
adds checks to prevent modification of the of rebroadcast inventory during
shutdown and adds a drain on the channel to ensure any outstanding
messages are discarded.

Found by @dajohi who also provided some of the code.
2014-06-02 16:15:24 -05:00
Dave Collins
605eb7f4b4 Add a simulation test network via --simnet param.
This commit, along with recent commits to btcnet and btcwire, expose a new
network that is intended to provide a private network useful for
simulation testing.  To that end, it has the special property that it has
no DNS seeds and will actively ignore all addr and getaddr messages.  It
will also not try to connect to any nodes other than those specified via
--connect.  This allows the network to remain private to the specific
nodes involved in the testing and not simply become another public
testnet.

The network difficulty is also set extremely low like the regression test
network so blocks can be created extremely quickly without requiring a lot
of hashing power.
2014-05-29 15:10:12 -05:00