Commit graph

270 commits

Author SHA1 Message Date
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
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
Josh Rickmar 07406791c9 rpcserver: Copy btcwallet fix for verifymessage. 2015-10-16 14:25:07 -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
Dario Nieuwenhuis 0190c349aa Add reverse order option to searchrawtransactions rpc 2015-10-08 16:31:39 +02:00
Dave Collins e4c053e504 rpcserver: Optimize JSON raw tx input list create.
This commit optimizes the createVinList function which is used to
generate the JSON list of transaction inputs.  It also makes it more
consistent with the createVinListPrevOut function.

In particular, it entails the following changes:
- Only do a single coinbase check and return right away instead of
  checking multiple times inside the loop over the inputs
- Use a pointer for populating the details of each entry to avoid
  multiple unnecessary array lookups and bounds checks
- Group all fields that populate the entry for better readability
2015-09-30 20:52:42 -05:00
Josh Rickmar 5983c9b98e Allow the session RPC for limited (read-only) clients. 2015-09-23 16:53:07 -04:00
Dario Nieuwenhuis 1806557d14 Fix skip not being applied to mempool txns in searchrawtransactions 2015-09-08 15:17:43 +02:00
danda 43774fe6bb adds optional prevOut section to vin for searchrawtransactions api. See https://github.com/btcsuite/btcd/issues/485 2015-08-23 09:58:03 -07:00
Dave Collins 0280fa0264 Convert block heights to int32.
This commit converts all block height references to int32 instead of
int64.  The current target block production rate is 10 mins per block
which means it will take roughly 40,800 years to reach the maximum
height an int32 affords.  Even if the target rate were lowered to one
block per minute, it would still take roughly another 4,080 years to
reach the maximum.

In the mean time, there is no reason to use a larger type which results
in higher memory and disk space usage.  However, for now, in order to
avoid having to reserialize a bunch of database information, the heights
are still serialized to the database as 8-byte uint64s.

This is being mainly being done in preparation for further upcoming
infrastructure changes which will use the smaller and more efficient
4-byte serialization in the database as well.
2015-08-11 11:13:17 -05:00
Dave Collins 506fc9fb94 rpcserver: Allow tx result creation without block.
This commit modifies the createTxRawResult code path along with callers
to work with block headers as opposed to btcutil.Blocks.  This in turn
allows the code in handleGetRawTransaction and
handleSearchRawTransactions to perform a much cheaper block header load
as opposed to a full block load.

While here, also very slightly optimize the createVinList function to
avoid creating a util.Tx wrapper and to take advantage of the
btcutil.Amount type added after the function was originally written
2015-07-28 18:44:30 -05:00
David Hill a6c79c7a91 Implement getblockheader RPC.
This mimics Bitcoin Core commit 076badb60f33f0c32b035de220ca14c52a423a2a
2015-07-23 15:22:17 -04:00
David Hill 7cfa843832 Support getmempoolinfo. 2015-06-24 20:34:56 -04:00
Alex Akselrod d26aaffb2b Create generate RPC command to close #362
Create GenerateCmd in btcjson v2. Update tests to check GenerateCmd.

Update chaincfg/params.go with a new bool in Params, GenerateSupported,
with true values in SimNetParams and RegressionNetParams and false in
the others.

Create new flag, discreteMining, in CPUMiner struct.

Add GenerateNBlocks function to cpuminer.go and handleGenerate
function to rpcserver.go.

Update documentation for the RPC calls.
2015-05-04 21:04:25 -04:00
Dave Collins 2dfb4be707 rpcserver: Increase getblock difficulty prec to 8.
This commit increases the precision of the difficulty field of the
getblock RPC to 8 to match Bitcoin Core.

Closes #414.
2015-05-04 03:53:39 -05: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
Dave Collins a4a52ae24f wire: Remove errs from BlockHeader/MsgBlock/MsgTx.
This commit removes the error returns from the BlockHeader.BlockSha,
MsgBlock.BlockSha, and MsgTx.TxSha functions since they can never fail and
end up causing a lot of unneeded error checking throughout the code base.

It also updates all call sites for the change.
2015-04-17 01:27:12 -05:00
Dave Collins 750d657666 Update for recent btcutil Block.Sha API change. 2015-04-17 00:44:15 -05: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
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
Alex Akselrod ead39153af Fix #303 and #346 and change addrindex sort order
Fix #303 by changing the addrindex key prefix to 3 characters so that
it's easy to check length when dropping the index. To drop the old
index, check to make sure we aren't dropping any entries that end in
"sx" or "tx" as those aren't part of the addrindex. Update test to
deal with the new prefix length.

Fix #346 by changing the pointers in the mempool's addrindex map to
wire.ShaHash 32-byte values. This lets them be deleted even if the
transaction data changes places in memory upon expanding the maps.

Change the way addrindex uint32s are stored to big-endian in order to
sort the transactions on disk in chronological/dependency order.

Change the "searchrawtransactions" RPC call to return transactions
from the database before the memory pool so that they're returned in
order. This commit DOES NOT do topological sorting of the memory pool
transactions to ensure they're returned in dependency order. This may
be a good idea for a future enhancement.

Add addrindex versioning to automatically drop the old/incompatible
version of the index and rebuild with the new sort method and key
prefix.
2015-03-23 13:05:54 -04:00
Dave Collins 28269d2598 rpcserver: Use default values for getnetworkhashps.
When the fields in the command for the getnetworkhashps RPC don't have the
fields set, use the intended default values.

Since the btcjson package sets these fields to the default values when a
command is unmarshaled from the wire, this typically isn't necessary.
However, when the RPC server calls the handler internally with optional
command fields set to nil, as is the case in getmininginfo, the defaults
need to be set as well.
2015-02-28 20:49:37 -06:00
Josh Rickmar 5ac0f1247d Fix return types for handleGetNetworkHashPS. 2015-02-28 21:40:13 -05:00
Dave Collins c0428f6f9f btcjson: Update searchrawtransactions verbose.
This commit updates the SearchRawTransactionsCmd verbose parameter in the
latest version of btcjson to an integer to match recent changes to the
previous version of btcjson.
2015-02-25 16:03:30 -06: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 c0c48e0efd Improve a couple of JSON-RPC server err conditions.
- When invalid HTTP Basic Access Authentication details are provided to
  the websocket endpoint, return a WWW-Authenticate header just like the
  non-websocket endpoint
- When a connection to the websocket endpoint fails to properly upgrade,
  return a 400 Bad Request HTTP error status code
2015-02-24 20:09:15 -06:00
Dave Collins 7b849ef3eb Improve internal RPC server function order.
This commit reorders the RPC server code to more closely match the
ordering used by the rest of the code base such that functions are
typically defined before they are used and near their call site.
2015-02-24 20:09:14 -06:00
Dave Collins 467d44cfc3 Update btcws path import paths to new location. 2015-02-19 13:07:25 -06:00
Dave Collins 6d289f602a Update btcjson path import paths to new location. 2015-02-19 11:55:22 -06:00
Dave Collins e7c7c3399f Update btcec path import paths to new location. 2015-02-06 10:54:32 -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 3b1a15d0d5 Update btcscript import paths to new location. 2015-01-30 12:14:33 -06:00
Dave Collins d67a0e207c Update for recent ScriptBuilder API change. 2015-01-29 00:11:19 -06:00
Dave Collins 309a9ea31d Update database import paths to new location. 2015-01-27 15:38:23 -06:00
Dave Collins 66a17f8a47 Return time offset in getinfo RPC.
This was previously hard-coded to zero instead of using the offset
provided by the median time source which takes time samples from the other
connected nodes.
2015-01-24 11:24:53 -06:00
Dave Collins 919109f12c Update btcjson import paths to new location. 2015-01-16 23:58:09 -06:00
Dave Collins 10643379a9 Update btcws import paths to new location. 2015-01-16 23:37:26 -06:00
Dave Collins a57505b7f0 Update btcscript import paths to new location. 2015-01-16 19:37:00 -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 44102d752a Update btcec import paths to new location. 2015-01-16 18:06:03 -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