Commit graph

113 commits

Author SHA1 Message Date
Tibor Bősze 6b8a24918e rpcserver: Improve JSON-RPC compatibility
Avoid compatibility issues with software that relies on the behavior of
bitcoind's JSON-RPC implementation.

The JSON-RPC 1.0 spec defines that notifications must have their "id"
set to null and states that notifications do not have a response.

A JSON-RPC 2.0 notification is a request with "json-rpc":"2.0", and
without an "id" member. The specification states that notifications
must not be responded to. JSON-RPC 2.0 permits the null value as a
valid request id, therefore such requests are not notifications.

Bitcoin Core serves requests with "id":null or even an absent "id", and
responds to such requests with "id":null in the response.

Btcd does not respond to any request without and "id" or with "id":null,
regardless the indicated JSON-RPC protocol version.

In order to avoid compatibility issues with software relying on
Core's behavior, this commit implements "quirks mode" as follows:
 - quirks mode can be enabled via configuration (disabled by default)
 - If no JSON-RPC version is indicated in the request, accept and
respond to request with "id":null
 - If no JSON-RPC version is indicated in the request, accept and
respond to requests without an "id" member
 - In both cases above, use "id":null in the response
 - Do not respond to request without an "id" or with "id":null when
JSON-RPC version is indicated in the request (process as notification)
2016-10-24 13:24:18 -05:00
Javed Khan bff2ba70fd connmgr: Refactor connection management into pkg
This commit introduces package connmgr which contains connection
management related functionality.

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

- Maintain fixed number of outbound connections
- Optional connect-only mode
- Retry persistent connections with increasing back-off
- Source peers from DNS seeds
- Use Tor to resolve DNS
- Dynamic ban scores
- Test coverage

In addition, btcd has been refactored to make use of the new package by
extending the connection manager to work with the server to source and
maintain peer connections. The following is a broad overview of the
changes to integrate the package:

- Simplify peer state by removing pending, retry peers
- Refactor to remove retries which are now handled by connmgr
- Use callback to add addresses sourced from the  DNS seed

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

- Fixes 100% cpu usage when network is down (#129)
- Fixes issues with max peers (#577)
- Simplify outbound peer connections management
2016-10-22 01:11:57 -05:00
Marco Peereboom 69fca4d9b1 Reconcile differences between btcd/dcrd.
Fixes #793
2016-10-21 16:37:30 -05:00
Josh Rickmar d0a9c03844 Concurrently handle websocket client JSON-RPC requests. 2016-10-20 19:55:58 -04:00
Marco Peereboom 5e93b1664e config: Replace log outputs with fmt.Fprintln.
This corrects the case where any errors that might have happened when
creating the config file were not being displayed due to the logging
system not being initialized yet.

While here, consistently use fmt.Fprint{f,ln} throughout the loadConfig
function even after the logging system is initialized since it will
help prevent copy/paste errors such as the one that induced this change
to begin with.
2016-09-12 02:21:37 -05:00
Olaoluwa Osuntokun 815ded348e
config: introduce new flags to accept/reject non-std transactions
This commit adds two new cli flags: one for accepting non-std
transactions, and the other for rejecting non-std transactions.

The two flag are rejected when using concurrently. Config parsing is
set up such that, the desired policy expressed via the config always
overrides the policy set by default for a particular chain.

The doc.go files and the sample-btcd.conf file have been updated to document
the new flags exposing further policy control.
2016-08-24 15:43:26 -07:00
Dave Collins 7fac099bee mempool: Refactor mempool code to its own package. (#737)
This does the minimum work necessary to refactor the mempool code into
its own package.  The idea is that separating this code into its own
package will greatly improve its testability, allow independent
benchmarking and profiling, and open up some interesting opportunities
for future development related to the memory pool.

There are likely some areas related to policy that could be further
refactored, however it is better to do that in future commits in order
to keep the changeset as small as possible during this refactor.

Overview of the major changes:

- Create the new package
- Move several files into the new package:
  - mempool.go -> mempool/mempool.go
  - mempoolerror.go -> mempool/error.go
  - policy.go -> mempool/policy.go
  - policy_test.go -> mempool/policy_test.go
- Update mempool logging to use the new mempool package logger
- Rename mempoolPolicy to Policy (so it's now mempool.Policy)
- Rename mempoolConfig to Config (so it's now mempool.Config)
- Rename mempoolTxDesc to TxDesc (so it's now mempool.TxDesc)
- Rename txMemPool to TxPool (so it's now mempool.TxPool)
- Move defaultBlockPrioritySize to the new package and export it
- Export DefaultMinRelayTxFee from the mempool package
- Export the CalcPriority function from the mempool package
- Introduce a new RawMempoolVerbose function on the TxPool and update
  the RPC server to use it
- Update all references to the mempool to use the package.
- Add a skeleton README.md
2016-08-19 11:08:37 -05:00
Hector Jusforgues ff4ada0b0e Add automatic RPC configuration. 2016-06-03 21:14:15 -05:00
Olaoluwa Osuntokun 3b39edcaa1 txscript: optimize sigcache lookup (#598)
Profiles discovered that lookups into the signature cache included an
expensive comparison to the stored `sigInfo` struct. This lookup had the
potential to be more expensive than directly verifying the signature
itself!

In addition, evictions were rather expensive because they involved
reading from /dev/urandom, or equivalent, for each eviction once the
signature cache was full as well as potentially iterating over every
item in the cache in the worst-case.

To remedy this poor performance several changes have been made:
* Change the lookup key to the fixed sized 32-byte signature hash
* Perform a full equality check only if there is a cache hit which
    results in a significant  speed up for both insertions and existence
checks
* Override entries in the case of a colliding hash on insert Add an
* .IsEqual() method to the Signature and PublicKey types in the
  btcec package to facilitate easy equivalence testing
* Allocate the signature cache map with the max number of entries in
  order to avoid unnecessary map re-sizes/allocations
* Optimize evictions from the signature cache Delete the first entry
* seen which is safe from manipulation due to
    the pre image resistance of the hash function
* Double the default maximum number of entries within the signature
  cache due to the reduction in the size of a cache entry
  * With this eviction scheme, removals are effectively O(1)

Fixes #575.
2016-04-13 21:56:10 -05:00
Dave Collins b580cdb7d3 database: Replace with new version.
This commit removes the old database package, moves the new package into
its place, and updates all imports accordingly.
2016-04-12 14:55:15 -05:00
Dave Collins 7c174620f7 indexers: Implement optional tx/address indexes.
This introduces a new indexing infrastructure for supporting optional
indexes using the new database and blockchain infrastructure along with
two concrete indexer implementations which provide both a
transaction-by-hash and a transaction-by-address index.

The new infrastructure is mostly separated into a package named indexers
which is housed under the blockchain package.  In order to support this,
a new interface named IndexManager has been introduced in the blockchain
package which provides methods to be notified when the chain has been
initialized and when blocks are connected and disconnected from the main
chain.  A concrete implementation of an index manager is provided by the
new indexers package.

The new indexers package also provides a new interface named Indexer
which allows the index manager to manage concrete index implementations
which conform to the interface.

The following is high level overview of the main index infrastructure
changes:

- Define a new IndexManager interface in the blockchain package and
  modify the package to make use of the interface when specified
- Create a new indexers package
  - Provides an Index interface which allows concrete indexes to plugin
    to an index manager
  - Provides a concrete IndexManager implementation
    - Handles the lifecycle of all indexes it manages
    - Tracks the index tips
    - Handles catching up disabled indexes that have been reenabled
    - Handles reorgs while the index was disabled
    - Invokes the appropriate methods for all managed indexes to allow
      them to index and deindex the blocks and transactions
  - Implement a transaction-by-hash index
    - Makes use of internal block IDs to save a significant amount of
      space and indexing costs over the old transaction index format
  - Implement a transaction-by-address index
    - Makes use of a leveling scheme in order to provide a good tradeoff
      between space required and indexing costs
- Supports enabling and disabling indexes at will
- Support the ability to drop indexes if they are no longer desired

The following is an overview of the btcd changes:

- Add a new index logging subsystem
- Add new options --txindex and --addrindex in order to enable the
  optional indexes
  - NOTE: The transaction index will automatically be enabled when the
    address index is enabled because it depends on it
- Add new options --droptxindex and --dropaddrindex to allow the indexes
  to be removed
  - NOTE: The address index will also be removed when the transaction
    index is dropped because it depends on it
- Update getrawtransactions RPC to make use of the transaction index
- Reimplement the searchrawtransaction RPC that makes use of the address
  index
- Update sample-btcd.conf to include sample usage for the new optional
  index flags
2016-04-11 17:16:42 -05:00
Dave Collins 491acd4ca6 blockchain: Rework to use new db interface.
This commit is the first stage of several that are planned to convert
the blockchain package into a concurrent safe package that will
ultimately allow support for multi-peer download and concurrent chain
processing.  The goal is to update btcd proper after each step so it can
take advantage of the enhancements as they are developed.

In addition to the aforementioned benefit, this staged approach has been
chosen since it is absolutely critical to maintain consensus.
Separating the changes into several stages makes it easier for reviewers
to logically follow what is happening and therefore helps prevent
consensus bugs.  Naturally there are significant automated tests to help
prevent consensus issues as well.

The main focus of this stage is to convert the blockchain package to use
the new database interface and implement the chain-related functionality
which it no longer handles.  It also aims to improve efficiency in
various areas by making use of the new database and chain capabilities.

The following is an overview of the chain changes:

- Update to use the new database interface
- Add chain-related functionality that the old database used to handle
  - Main chain structure and state
  - Transaction spend tracking
- Implement a new pruned unspent transaction output (utxo) set
  - Provides efficient direct access to the unspent transaction outputs
  - Uses a domain specific compression algorithm that understands the
    standard transaction scripts in order to significantly compress them
  - Removes reliance on the transaction index and paves the way toward
    eventually enabling block pruning
- Modify the New function to accept a Config struct instead of
  inidividual parameters
- Replace the old TxStore type with a new UtxoViewpoint type that makes
  use of the new pruned utxo set
- Convert code to treat the new UtxoViewpoint as a rolling view that is
  used between connects and disconnects to improve efficiency
- Make best chain state always set when the chain instance is created
  - Remove now unnecessary logic for dealing with unset best state
- Make all exported functions concurrent safe
  - Currently using a single chain state lock as it provides a straight
    forward and easy to review path forward however this can be improved
    with more fine grained locking
- Optimize various cases where full blocks were being loaded when only
  the header is needed to help reduce the I/O load
- Add the ability for callers to get a snapshot of the current best
  chain stats in a concurrent safe fashion
  - Does not block callers while new blocks are being processed
- Make error messages that reference transaction outputs consistently
  use <transaction hash>:<output index>
- Introduce a new AssertError type an convert internal consistency
  checks to use it
- Update tests and examples to reflect the changes
- Add a full suite of tests to ensure correct functionality of the new
  code

The following is an overview of the btcd changes:

- Update to use the new database and chain interfaces
- Temporarily remove all code related to the transaction index
- Temporarily remove all code related to the address index
- Convert all code that uses transaction stores to use the new utxo
  view
- Rework several calls that required the block manager for safe
  concurrency to use the chain package directly now that it is
  concurrent safe
- Change all calls to obtain the best hash to use the new best state
  snapshot capability from the chain package
- Remove workaround for limits on fetching height ranges since the new
  database interface no longer imposes them
- Correct the gettxout RPC handler to return the best chain hash as
  opposed the hash the txout was found in
- Optimize various RPC handlers:
  - Change several of the RPC handlers to use the new chain snapshot
    capability to avoid needlessly loading data
  - Update several handlers to use new functionality to avoid accessing
    the block manager so they are able to return the data without
    blocking when the server is busy processing blocks
  - Update non-verbose getblock to avoid deserialization and
    serialization overhead
  - Update getblockheader to request the block height directly from
    chain and only load the header
  - Update getdifficulty to use the new cached data from chain
  - Update getmininginfo to use the new cached data from chain
  - Update non-verbose getrawtransaction to avoid deserialization and
    serialization overhead
  - Update gettxout to use the new utxo store versus loading
    full transactions using the transaction index

The following is an overview of the utility changes:
- Update addblock to use the new database and chain interfaces
- Update findcheckpoint to use the new database and chain interfaces
- Remove the dropafter utility which is no longer supported

NOTE: The transaction index and address index will be reimplemented in
another commit.
2016-04-11 16:47:27 -05:00
David Hill 123ff368f4 mempool: Create and use mempoolPolicy. (#571)
mempoolPolicy contains the values that configure the mempool policy.
This decouples the values from the internals of btcd to move closer
to a mempool package.
2016-04-11 16:37:52 -05:00
David Hill d1e493f4ee config: New option --blocksonly (#553)
The --blocksonly configuration option disables accepting transactions
from remote peers.  It will still accept, relay, and rebroadcast
valid transactions sent via RPC or websockets.
2016-04-07 18:16:46 -05:00
Dave Collins f389742b39 multi: Update with result of gofmt -s.
This commit updates the code to make use of the most recent simplified
output from gofmt.
2016-02-25 13:02:54 -06:00
Dave Collins eb882f39f8 multi: Fix several misspellings in the comments.
This commit corrects several typos in the comments found by misspell.
2016-02-25 11:17:12 -06:00
Tibor Bősze c75fea9c94 Implement banning based on dynamic ban scores
Dynamic ban scores consist of a persistent and a decaying component. The
persistent score can be used to create simple additive banning policies
simlar to those found in other bitcoin node implementations. The
decaying score enables the creation of evasive logic which handles
misbehaving peers (especially application layer DoS attacks) gracefully
by disconnecting and banning peers attempting various kinds of flooding.
Dynamic ban scores allow these two approaches to be used in tandem.

This pull request includes the following:

 - Dynamic ban score type & functions, with tests for core functionality
 - Ban score of connected peers can be queried via rpc (getpeerinfo)
 - Example policy with decaying score increments on mempool and getdata
 - Logging of misbehavior once half of the ban threshold is reached
 - Banning logic can be disabled via configuration (enabled by default)
 - User defined ban threshold can be set via configuration
2016-02-16 10:10:29 +01:00
Michail Kargakis 09874f1e91 Fix dropaddrindex flag usage message 2015-11-23 22:20:02 +01: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
David Hill a56db22e9b config: New option --minrelaytxfee
--minrelaytxfee allows the user to specify the minimum transaction
fee in BTC/kB in which the fee is considered a non-zero fee.
2015-10-20 12:41:12 -04: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
David Hill a1bd15e7c2 Fix --onion.
The configured onion proxy was not being used due to checking if the
passed string had suffix '.onion', which never matched because the
port number is part of the string.
2015-06-10 09:56:25 -04:00
David Hill 007bee5ec8 Add new option --torisolation
Tor stream isolation randomizes proxy user credentials resulting in
Tor creating a new circuit for each connection.  This makes it more
difficult to correlate connections.

Idea from Wladimir J. van der Laan via Bitcoin Core.
2015-05-13 18:30:48 -04:00
David Hill 5f8dbab47a Add new option -maxorphantx
The option -maxorphantx allows the user to specify the number of
orphan transactions to keep in memory.

Also, lower the default max orphan count from 10000 to 1000.
2015-05-12 17:22:13 -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
Alex Akselrod 4a1445a032 Create limited RPC user.
The limited user is specified with the --rpclimituser and
--rpclimitpass options (or the equivalent in the config file).
The config struct and loadConfig() are updated to take the
new options into account. The limited user can have neither
the same username nor the same password as the admin user.

The package-level rpcLimit map in rpcserver.go specifies
the RPC commands accessible by limited users. This map
includes both HTTP/S and websocket commands.

The checkAuth function gets a new return parameter to
signify whether the user is authorized to change server
state. The result is passed to the jsonRPCRead function and
to the WebsocketHandler function in rpcwebsocket.go.

The wsClient struct is updated with an "isAdmin" field
signifying that the client is authorized to change server
state, written by WebsocketHandler and handleMessage.
The handleMessage function also checks the field to
allow or disallow an RPC call.

The following documentation files are updated:
- doc.go
- sample-btcd.conf
- docs/README.md
- docs/json_rpc_api.md
- docs/configure_rpc_server_listen_interfaces.md
2015-04-13 14:14:52 -04:00
David Hill 833bb04775 Reject free/low-fee transactions with insufficient priority.
By default, have the mempool reject free and low-fee transactions that
have insufficient priority to be mined in the next block.

Addtionally, add a new configuration option, -norelaypriority, to
disable the check.
2015-02-25 11:27:41 -05: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 309a9ea31d Update database import paths to new location. 2015-01-27 15:38:23 -06:00
Dave Collins 0b7a9074ef Update btcdb import paths to new location. 2015-01-16 18:30:32 -06:00
Dave Collins 54ccb83025 Update btcwire import paths to new location. 2015-01-16 15:13:21 -06:00
Dave Collins f4e426c69f Update go-socks import paths to new location. 2015-01-16 01:21:57 -06:00
Dave Collins 8975c0c459 Update go-flags import paths to new location. 2015-01-16 00:56:49 -06:00
Dave Collins 58db4a8b7e Update btcutil import paths to new location. 2015-01-15 10:30:38 -06:00
Dave Collins 04d47de262 Allow disabling RPC server TLS for localhost only.
This commit introduces a new flag, --notls, which can be used to disable
TLS for the RPC server.  However, the flag can only be used when the RPC
server is bound to localhost interfaces.  This is intended to prevent the
situation where someone decides they want to expose the RPC server to the
web for remote management/access, but forgot they have TLS disabled.
2015-01-02 11:17:23 -06:00
Dave Collins f1cbd40713 Improve handling of the home directory creation.
This commit improves a couple of issues surrounding the creation of the
btcd home directory.

First, the code was previously attempting to log any errors that occurred
while creating the directory using the logging system which is not
initialized at that point.  Thus, nothing was displayed to the user.

Second, if any component of btcd home directory path already exists, but
is not a directory, such as in the case of symlinks, the error returned
from the os.MkDirAll call indicates the directory can't be created.  While
this is true, it's not always the most helpful error to display to the
user.  So, this commit adds logic to detect when the failure case is due
to an existing symlink and displays a nicer error message suggesting the
user check if the destination of the link is mounted.

Fixes #193.
2014-12-21 17:01:56 -06:00
Olaoluwa Osuntokun b97083f882 Fix some typos throughout repo. 2014-09-08 14:54:52 -05:00
Dave Collins ca13333d25 Always show help on help flag.
This commit resolves a minor issue where an error in the config file would
prevent the help from being shown until the config file error was
resolved.

This results in the following behavior:

- With a malformed header:
  $ ./btcd
  Error parsing config file: ~/btcd/btcd.conf:14: malformed section header
  Use btcd -h to show usage
- With an invalid option:
  $ ./btcd
  Error parsing config file: unknown option: bogus
  Use btcd -h to show usage
- Invoking help with an error in the config file:
  $ ./btcd -h
  Usage:
  ...
- Invoking with an invalid command line option:
  $ ./btcd --bogus=bogus
  unknown flag `bogus'
  Use btcd -h to show usage

ok @jrick
2014-08-19 20:29:59 -05:00
Javed Khan 458a996ae6 updated utils to handle regtest, simnet
handle active network assignment in the same if-else
instead of having another switch-case
2014-07-22 08:28:33 -05:00
Dave Collins 08c01f08b1 Only show parse errors and command to invoke usage.
Rather than showing the usage when an error is encounted during options
parsing, show a message that describes how to invoke help instead.  This
is useful because the help is long enough now that the error is often
overlooked since it scrolls out of view.

ok @jrick
2014-07-14 20:43:54 -05:00
Tomás Senart cc2c486791 Replace map[a]bool with map[a]struct{}
The later uses no memory storage for values and provides the same
functionality.
2014-07-02 19:06:29 -05:00
Tomás Senart 76d258e2a1 Avoid reallocs in removeDuplicateAddresses 2014-07-02 11:01:57 -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 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 cc3e49fabb Make loadConfig function name a variable.
The errors in the loadConfig function had the function name hardcoded in
each error.  This commit assigns the function name to a variable instead.
2014-06-07 14:42:54 -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
Dave Collins 252c022644 Convert to default net ports provided by btcnet.
ok @jrick
2014-05-29 12:47:08 -05:00