Bump versions to 1.9.8, add 1.9.8 version of website (#5280)

* Bump versions to 1.9.8, add 1.9.8 version of website

* Update website version
This commit is contained in:
Chris Stewart 2024-03-25 09:06:31 -05:00 committed by GitHub
parent 4501e138a4
commit 6b21a900ce
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 3153 additions and 26 deletions

View file

@ -1,5 +1,5 @@
![Bitcoin-S logo](website/static/img/bitcoin-s-dark-logo.png)
[![Build Status](https://github.com/bitcoin-s/bitcoin-s/workflows/Release/badge.svg)](https://github.com/bitcoin-s/bitcoin-s/actions) [![Coverage Status](https://coveralls.io/repos/github/bitcoin-s/bitcoin-s/badge.svg?branch=master)](https://coveralls.io/github/bitcoin-s/bitcoin-s?branch=master) [![Maven Central](https://img.shields.io/badge/Maven%20Central-1.9.7-brightgreen.svg)](https://mvnrepository.com/artifact/org.bitcoin-s) [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/bitcoin-s-core)
[![Build Status](https://github.com/bitcoin-s/bitcoin-s/workflows/Release/badge.svg)](https://github.com/bitcoin-s/bitcoin-s/actions) [![Coverage Status](https://coveralls.io/repos/github/bitcoin-s/bitcoin-s/badge.svg?branch=master)](https://coveralls.io/github/bitcoin-s/bitcoin-s?branch=master) [![Maven Central](https://img.shields.io/badge/Maven%20Central-1.9.8-brightgreen.svg)](https://mvnrepository.com/artifact/org.bitcoin-s) [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/bitcoin-s-core)
Feature-rich toolkit for making Bitcoin and Lightning applications on the JVM.
@ -43,52 +43,52 @@ This link is intended for setting up development of bitcoin-s. If you want to ju
### Adding bitcoin-s to your library
The latest release of bitcoin-s is `1.9.7`, here is how you can use the dependencies in your projects:
The latest release of bitcoin-s is `1.9.8`, here is how you can use the dependencies in your projects:
```
libraryDependencies += "org.bitcoin-s" % "bitcoin-s-secp256k1jni" % "1.9.7"
libraryDependencies += "org.bitcoin-s" % "bitcoin-s-secp256k1jni" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-core" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-core" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-crypto" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-crypto" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-chain" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-chain" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-dlc-oracle" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-dlc-oracle" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-oracle-explorer-client" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-oracle-explorer-client" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-app-commons" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-app-commons" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-db-commons" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-db-commons" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-fee-provider" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-fee-provider" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-bitcoind-rpc" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-bitcoind-rpc" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-eclair-rpc" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-eclair-rpc" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-lnd-rpc" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-lnd-rpc" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-key-manager" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-key-manager" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-node" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-node" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-dlc-node" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-dlc-node" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-wallet" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-wallet" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-dlc-wallet" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-dlc-wallet" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-testkit-core" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-testkit-core" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-testkit" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-testkit" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-zmq" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-zmq" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-tor" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-tor" % "1.9.8"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-cli" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-cli" % "1.9.8"
```

View file

@ -1,5 +1,5 @@
package org.bitcoins.node.constant
case object NodeConstants {
val userAgent = "/bitcoin-s:1.9.7/"
val userAgent = "/bitcoin-s:1.9.8/"
}

View file

@ -31,7 +31,7 @@ import scala.util.Properties
object CommonSettings {
val previousStableVersion: String = "1.9.7"
val previousStableVersion: String = "1.9.8"
private def isCI = {
Properties

View file

@ -0,0 +1,420 @@
---
id: version-1.9.8-server
title: Application Server
original_id: server
---
## App server
The server project is the aggregation of these three sub projects
1. [Wallet](../wallet/wallet.md)
2. [Chain](../chain/chain.md)
3. [Node](../node/node.md)
The server project provides a away to access information from these three projects via a JSON RPC.
## Building the server
### Java binary
You can build the server with the [sbt native packager](https://github.com/sbt/sbt-native-packager).
The native packager offers [numerous ways to package the project](https://github.com/sbt/sbt-native-packager#examples).
In this example we are going to use `stage` which will produce bash scripts we can easily execute. You can stage the server with the following command.
```bash
sbt appServer/universal:stage
```
This will produce a script to execute bitcoin-s which you can start with
```bash
./app/server/target/universal/stage/bin/bitcoin-s-server
```
### Docker
The oracle server also has docker support. You can build a docker image with the following commands
#### Using an existing docker image
We publish docker images on every PR that is merged to bitcoin-s.
You can find the docker repo for the app server [here](https://hub.docker.com/r/bitcoinscala/bitcoin-s-server/tags?page=1&ordering=last_updated)
#### Building a docker image
```
sbt "appServer/docker:stage"
```
This will build a `Dockerfile` that is located in `app/server/target/docker/stage`
You can now build the docker image with
```
docker build app/server/target/docker/stage/ -t bitcoinscala/bitcoin-s-server:latest
```
Finally, let's run the image! It's important that you correctly configure port forwarding with the docker container so
you can interact with the running container with `bitcoin-s-cli` or `curl`. By default, our oracle
server listens for requests on port `9999`. By default, the server listens for websocket connections on port `19999` at `/events`.
This means we need to forward requests on the host machine to the docker container correctly.
This can be done with the following command
```
docker run -d -p 9999:9999 -p 19999:19999 -e BITCOIN_S_SERVER_RPC_PASSWORD='topsecret' bitcoinscala/bitcoin-s-server:latest
```
Now you can send requests with `bitcoin-s-cli` or `curl`.
Here is an example with `bitcoin-s-cli`
```
./bitcoin-s-cli getblockcount --password topsecret
10000
```
For more information on build configuration options with `sbt` please see the [sbt native packager docs](https://sbt-native-packager.readthedocs.io/en/latest/formats/docker.html#tasks)
## Configuration
### Java binary configuration
If you would like to pass in a custom datadir for your server, you can do
```bash
./app/server/target/universal/stage/bin/bitcoin-s-server --datadir /path/to/datadir/
```
To use a config file that is not the `bitcoin-s.conf` file in your datadir, you can do
```bash
./app/server/target/universal/stage/bin/bitcoin-s-server --conf /path/to/file.conf
```
You can also pass in a custom `rpcport` to bind to
```bash
./app/server/target/universal/stage/bin/bitcoin-s-server --rpcport 12345
```
Or set a custom `wsport` to bind to
```bash
./app/server/target/universal/stage/bin/bitcoin-s-server --wsport 54321
```
For more information on configuring the server please see our [configuration](../config/configuration.md) document
For more information on how to use our built in `cli` to interact with the server please see [cli.md](cli.md)
### Docker configuration
In this example, we are using the latest docker image published to our [docker hub](https://hub.docker.com/repository/docker/bitcoinscala/bitcoin-s-oracle-server/tags?page=1&ordering=last_updated)
which is referenced by `bitcoinscala/bitcoin-s-server:latest`
You can use bitcoin-s with docker volumes. You can also pass in a custom configuration at container runtime.
#### Using a docker volume
```basrc
docker volume create bitcoin-s
docker run -p 9999:9999 -p 19999:19999 \
--mount source=bitcoin-s,target=/home/bitcoin-s/ bitcoinscala/bitcoin-s-server:latest
```
Now you can re-use this volume across container runs. It will keep the same oracle database
and seeds directory located at `/home/bitcoin-s/.bitcoin-s/seeds` in the volume.
#### Using a custom bitcoin-s configuration with docker
You can also specify a custom bitcoin-s configuration at container runtime.
You can mount the configuration file on the docker container and that
configuration will be used in the docker container runtime rather than
the default one we provide [here](https://github.com/bitcoin-s/bitcoin-s/blob/master/app/oracle-server/src/universal/docker-application.conf)
You can do this with the following command
```bashrc
docker run -p 9999:9999 -p 19999:19999 \
--mount type=bind,source=/my/new/config/,target=/home/bitcoin-s/.bitcoin-s/ \
bitcoinscala/bitcoin-s-server:latest --conf /home/bitcoin-s/.bitcoin-s/bitcoin-s.conf
```
Note: If you adjust the `bitcoin-s.server.rpcport` setting you will need to adjust
the `-p 9999:9999` port mapping on the docker container to adjust for this.
## Server Endpoints
### Common
- `getversion` - The version of our application you are using
- `zipdatadir` `location` - Backs up the datadir in a safe and consistent manner.
- `location` - The locations of the backup zip
### Blockchain
- `getblockcount` - Get the current block height
- `getfiltercount` - Get the number of filters
- `getfilterheadercount` - Get the number of filter headers
- `getbestblockhash` - Get the best block hash
- `getblockheader` - Returns information about block header <hash>
- `hash` - The block hash
- `decoderawtransaction` `tx` - `Decode the given raw hex transaction`
- `tx` - Transaction encoded in hex to decode
- `getmediantimepast` - Returns the median time past
- `getinfo` returns general information about our blockchain state
### Wallet
- `rescan` `[options]` - Rescan for wallet UTXOs
- `--force` - Clears existing wallet records. Warning! Use with caution!
- `--batch-size <value>` - Number of filters that can be matched in one batch
- `--start <value>` - Start height
- `--end <value>` - End height
- `--ignorecreationtime` - Ignores the wallet creation date and will instead do a full rescan
- `isempty` - Checks if the wallet contains any data
- `walletinfo` - Returns data about the current wallet being used
- `getbalance` `[options]` - Get the wallet balance
- `--sats ` - Display balance in satoshis
- `getconfirmedbalance` `[options]` - Get the wallet balance of confirmed utxos
- `--sats ` - Display balance in satoshis
- `getunconfirmedbalance` `[options]` - Get the wallet balance of unconfirmed utxos
- `--sats ` - Display balance in satoshis
- `getbalances` `[options]` - Get the wallet balance by utxo state
- `--sats ` - Display balance in satoshis
- `getutxos` - Returns list of all wallet utxos
- `getaddresses` - Returns list of all wallet addresses currently being watched
- `getspentaddresses` - Returns list of all wallet addresses that have received funds and been spent
- `getfundedaddresses` - Returns list of all wallet addresses that are holding funds
- `getunusedaddresses` - Returns list of all wallet addresses that have not been used
- `getaccounts` - Returns list of all wallet accounts
- `walletinfo` - Returns meta information about the wallet
- `createnewaccount` - Creates a new wallet account
- `getaddressinfo` `address` - Returns list of all wallet accounts
- `address` - Address to get information about
- `getnewaddress` - Get a new address
- `listreservedutxos` - lists all utxos that are reserved in the wallet
- `sendtoaddress` `address` `amount` `[options]` - Send money to the given address
- `address` - Address to send to
- `amount` - Amount to send in BTC
- `--feerate <value>` - Fee rate in sats per virtual byte
- `sendfromoutpoints` `outpoints` `address` `amount` `[options]` - Send money to the given address
- `outpoints` - Out Points to send from
- `address` - Address to send to
- `amount` - Amount to send in BTC
- `--feerate <value>` - Fee rate in sats per virtual byte
- `sweepwallet` `address` `[options]` - Sends the entire wallet balance to the given address
- `address` - Address to send to
- `--feerate <value>` - Fee rate in sats per virtual byte
- `sendwithalgo` `address` `amount` `algo` `[options]` - Send money to the given address using a specific coin selection algo
- `address` - Address to send to
- `amount` - Amount to send in BTC
- `algo` - Coin selection algo
- `--feerate <value>` - Fee rate in sats per virtual byte
- `signpsbt` `psbt` - Signs the PSBT's inputs with keys that are associated with the wallet
- `psbt` - PSBT to sign
- `opreturncommit` `message` `[options]` - Creates OP_RETURN commitment transaction
- `message` - message to put into OP_RETURN commitment
- `--hashMessage` - should the message be hashed before commitment
- `--feerate <value>` - Fee rate in sats per virtual byte
- `bumpfeecpfp` `txid` `feerate` - Bump the fee of the given transaction id with a child tx using the given fee rate
- `txid` - Id of transaction to bump fee
- `feerate` - Fee rate in sats per virtual byte of the child transaction
- `bumpfeerbf` `txid` `feerate` - Replace given transaction with one with the new fee rate
- `txid` - Id of transaction to bump fee
- `feerate` - New fee rate in sats per virtual byte
- `gettransaction` `txid` - Get detailed information about in-wallet transaction <txid>
- `txid` - The transaction id
- `lockunspent` `unlock` `transactions` - Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.
- `unlock` - Whether to unlock (true) or lock (false) the specified transactions
- `transactions` - The transaction outpoints to unlock/lock, empty to apply to all utxos
- `importseed` `walletname` `words` `passphrase` - Imports a mnemonic seed as a new seed file
- `walletname` - Name to associate with this seed
- `words` - Mnemonic seed words, space separated
- `passphrase` - Passphrase to encrypt this seed with
- `importxprv` `walletname` `xprv` `passphrase` - Imports a mnemonic seed as a new seed file
- `walletname` - Name to associate with this seed
- `xprv` - base58 encoded extended private key
- `passphrase` - Passphrase to encrypt this seed with
- `exportseed` `walletname` `passphrase` - Exports the mnemonic seed phrase
- `walletname` - Name to associate with this seed
- `passphrase` - Passphrase to decrypt this seed with
- `markseedasbackedup` `walletname` `passphrase` - Marks the seed as backed up. It prevents `exportseed` from returning the mnemonic phrase
- `walletname` - Name to associate with this seed
- `passphrase` - Passphrase to decrypt this seed with
- `getseedbackuptime` `walletname` `passphrase` - Returns time when the seed was backed up
- `walletname` - Name to associate with this seed
- `passphrase` - Passphrase to decrypt this seed with
- `keymanagerpassphrasechange` `oldpassphrase` `newpassphrase` - Changes the wallet passphrase
- `oldpassphrase` - The current passphrase
- `newpassphrase` - The new passphrase
- `keymanagerpassphraseset` `passphrase` - Encrypts the wallet with the given passphrase
- `passphrase` - The passphrase to encrypt the wallet with
- `loadwallet` `walletname` `passphrase` - Loads a wallet
- `walletname` - Name to associate with this seed
- `passphrase` - Passphrase to decrypt this seed with
- `listwallets` - Returns a list of all wallets
### DLC
- `createcontractinfo` `announcement` `totalCollateral` `payouts`
- the announcement to build the contract info for
- the total amount of collateral in the DLC
- The payouts can be in two formats
1. `{ "outcomes" : { "outcome0" : 0, "outcome1": 1, ... }}`. The number is the amount of sats paid to YOU for that outcome.
2. `[{"outcome":0,"payout":0,"extraPrecision":0,"isEndpoint":true}, {"outcome":1,"payout":1,"extraPrecision":0,"isEndpoint":true}, ...]`
- `decodecontractinfo` `contractinfo` - Decodes a contract info into json
- `contractinfo` - Hex encoded contract info
- `decodeoffer` `offer` - Decodes an offer message into json
- `offer` - Hex encoded dlc offer message
- `decodeaccept` `accept` - Decodes an accept message into json
- `accept` - Hex encoded dlc accept message
- `decodesign` `sign` - Decodes a sign message into json
- `sign` - Hex encoded dlc sign message
- `decodeannouncement` `announcement` - Decodes an oracle announcement message into json
- `announcement` - Hex encoded oracle announcement message
- `decodeattestments` `attestments` - Decodes an oracle attestments message into json
- `attestments` - Hex encoded oracle attestments message
- `getdlchostaddress` - Returns the public listening address of the DLC Node
- `createdlcoffer` `contractInfo` `collateral` `[feerate]` `refundlocktime` `[options]` - Creates a DLC offer that another party can accept
- `contractInfo` - Hex encoded contractInfo message
- `collateral` - Satoshis to fund your side of the DLC
- `feerate` - Fee rate for both funding and closing transactions, in sats/vbytes
- `refundlocktime` - Locktime of the refund transaction
- `cetlocktime <value>` - Should not be set unless you know what you are doing. Locktime of the contract execution transactions (defaults to current height)
- `peer` - Peer's network address
- `acceptdlc` `offer` `peer` - Accepts a DLC offer given from another party
- `offer` - Hex encoded dlc offer message
- `peer` - Peer's network address
- `acceptdlcoffer` `offer` - Accepts a DLC offer given from another party
- `offer` - Hex encoded offer message
- `peer` - Peer's network address
- `acceptdlcofferfromfile` `path` `[destination]` - Accepts a DLC offer given from another party
- `path` - Path to dlc offer file
- `destination` - Path to write dlc accept message
- `contact-add` `alias` `address` `memo`
- `alias` - alias for the address like a name
- `address` - the tor address for the peer
- `memo` - a memo for this contact
- `contacts-list` - lists all contacts in the wallet
- `contact-remove` `address`
- `address` - the tor address for the peer to remove
- `dlc-contact-add` `dlcid` `address` - Associated a DLC with a peer
- `dlc-contact-remove` `dlcid` - Removes a DLC-peer association
- `address` - the tor address for the peer to remove
- `signdlc` `accept` - Signs a DLC
- `accept` - Hex encoded dlc accept message
- `signdlcfromfile` `path` `[destination]` - Signs a DLC
- `path` - Path to dlc accept file
- `destination` - Path to write dlc sign message
- `adddlcsigs` `sigs` - Adds DLC Signatures into the database
- `sigs` - Hex encoded dlc sign message
- `adddlcsigsfromfile` `path` - Adds DLC Signatures into the database
- `path` - Path to dlc sign file
- `adddlcsigsandbroadcast` `sigs` - Adds DLC Signatures into the database and broadcasts the funding transaction
- `sigs` - Hex encoded dlc sign message
- `adddlcsigsandbroadcastfromfile` `path` - Adds DLC Signatures into the database and broadcasts the funding transaction
- `path` - Path to dlc sign file
- `getdlcfundingtx` `contractId` - Returns the Funding Tx corresponding to the DLC with the given contractId
- `contractId` - ContractId of the DLC
- `broadcastdlcfundingtx` `contractId` - Broadcasts the funding Tx corresponding to the DLC with the given contractId
- `contractId` - ContractId of the DLC
- `executedlc` `contractId` `oraclesigs` `[options]` - Executes the DLC with the given contractId
- `contractId` - ContractId of the DLC
- `oraclesigs` - Array of oracle attestations
- `--noBroadcast` - Gives full serialized transaction instead of broadcasting
- `executedlcrefund` `contractId` `[options]` - Executes the Refund transaction for the given DLC
- `contractId` - ContractId of the DLC
- `--noBroadcast` - Gives full serialized transaction instead of broadcasting
- `canceldlc` `dlcId` - Cancels a DLC and unreserves used utxos
- `dlcId` - Internal id of the DLC
- `getdlcs` - Returns all dlcs in the wallet
- `address` - optional contact address, if specified the RPC returns only DLCs associated with the given address
- `getdlc` `dlcId` - Gets a specific dlc in the wallet
- `dlcId` - Internal id of the DLC
- `offer-add` `offerTLV` `peerAddress` `message` - Puts an incoming offer into the inbox
- `offerTLV` - Offer TLV
- `peer` - Peer URI (optional)
- `message` - Peer's message or note (optional)
- `"offer-remove` `hash` - Remove an incoming offer from inbox
- `hash` - Hash of the offer TLV
- `offer-send` `offerOrTempContractId` `peerAddress` `message` - Sends an offer to a peer. `offerOrTempContractId` is either an offer TLV or a temporary contract ID.
- `offers-list` - List all incoming offers from the inbox
- `getdlcoffer` `tempContractId` - Gets a DLC offer by temporary contract ID.
- `getaddresslabel` `address` - gets all labels for an address
- `getaddresslabels` - returns all addresses with labels in the wallet
- `dropaddresslabel` `address` `label` - drops the label for a given address
- `dropaddresslabels` `address` - drops all labels for the given address
### Network
- `getconnectioncount` - Get the number of connected peers
- `stop` - Request a graceful shutdown of Bitcoin-S
- `sendrawtransaction` `tx` `Broadcasts the raw transaction`
- `tx` - Transaction serialized in hex
### PSBT
- `decodepsbt` `psbt` - Return a JSON object representing the serialized, base64-encoded partially signed Bitcoin transaction.
- `psbt` - PSBT serialized in hex or base64 format
- `combinepsbts` `psbts` - Combines all the given PSBTs
- `psbts` - PSBTs serialized in hex or base64 format
- `joinpsbts` `psbts` - Combines all the given PSBTs
- `psbts` - PSBTs serialized in hex or base64 format
- `finalizepsbt` `psbt` - Finalizes the given PSBT if it can
- `psbt` - PSBT serialized in hex or base64 format
- `extractfrompsbt` `psbt` - Extracts a transaction from the given PSBT if it can
- `psbt` - PSBT serialized in hex or base64 format
- `converttopsbt` `unsignedTx` - Creates an empty psbt from the given transaction
- `unsignedTx` - serialized unsigned transaction in hex
### Util
- `createmultisig` `nrequired` `keys` `[address_type]` - Creates a multi-signature address with n signature of m keys required.
- `nrequired` - The number of required signatures out of the n keys.
- `keys` - The hex-encoded public keys.
- `address_type` -The address type to use. Options are "legacy", "p2sh-segwit", and "bech32"
- `estimatefee` - Returns the recommended fee rate using the fee provider
## getinfo
```bash
curl --data-binary '{"jsonrpc": "1.0", "id": "curltest", "method": "getinfo", "params": []}' -H "Content-Type: application/json" http://127.0.0.1:9999/
{"result":{"network":"main","blockHeight":750129,"blockHash":"00000000000000000002f7d39ca6c914329a8d87010215ef6466c17ffaba0a1f","torStarted":true,"syncing":false,"isinitialblockdownload":false},"error":null}
```
## Sign PSBT with Wallet Example
Bitcoin-S CLI:
```bash
bitcoin-s-cli signpsbt cHNidP8BAP0FAQIAAAABWUWxYiPKgdGfXcIxJ6MRDxEpUecw59Gk4NpROI5oukoBAAAAAAAAAAAEPttkvdwAAAAXqRSOVAp6Qe/u2hq74e/ThB8foBKn7IfZYMgGCAAAAADbmaQ2nwAAAEdRIQLpfVqyaL9Jb/IkveatNyVeONE8Q/6TzXAWosxLo9e21SECc5G3XiK7xKLlkBG7prMx7p0fMeQwMH5e9H10mBon39JSrtgtgjjLAQAAUGMhAn2YaZnv25I6d6vbb1kw6Xp5IToDrEzl/0VBIW21gHrTZwXg5jGdALJ1IQKyNpDNiOiN6lWpYethib04+XC9bpFXrdpec+xO3U5IM2is9ckf5AABAD0CAAAAAALuiOL0rRcAABYAFPnpLByQq1Gg3vwiP6qR8FmOOjwxvVllM08DAAALBfXJH+QAsXUAAK4AAAAAAQcBAAAAAAAA
cHNidP8BAP0FAQIAAAABWUWxYiPKgdGfXcIxJ6MRDxEpUecw59Gk4NpROI5oukoBAAAAAAAAAAAEPttkvdwAAAAXqRSOVAp6Qe/u2hq74e/ThB8foBKn7IfZYMgGCAAAAADbmaQ2nwAAAEdRIQLpfVqyaL9Jb/IkveatNyVeONE8Q/6TzXAWosxLo9e21SECc5G3XiK7xKLlkBG7prMx7p0fMeQwMH5e9H10mBon39JSrtgtgjjLAQAAUGMhAn2YaZnv25I6d6vbb1kw6Xp5IToDrEzl/0VBIW21gHrTZwXg5jGdALJ1IQKyNpDNiOiN6lWpYethib04+XC9bpFXrdpec+xO3U5IM2is9ckf5AABAD0CAAAAAALuiOL0rRcAABYAFPnpLByQq1Gg3vwiP6qR8FmOOjwxvVllM08DAAALBfXJH+QAsXUAAK4AAAAAAQcBAAAAAAAA
```
CURL:
```bash
curl --data-binary '{"jsonrpc": "1.0", "id": "curltest", "method": "signpsbt", "params": ["cHNidP8BAP0FAQIAAAABWUWxYiPKgdGfXcIxJ6MRDxEpUecw59Gk4NpROI5oukoBAAAAAAAAAAAEPttkvdwAAAAXqRSOVAp6Qe/u2hq74e/ThB8foBKn7IfZYMgGCAAAAADbmaQ2nwAAAEdRIQLpfVqyaL9Jb/IkveatNyVeONE8Q/6TzXAWosxLo9e21SECc5G3XiK7xKLlkBG7prMx7p0fMeQwMH5e9H10mBon39JSrtgtgjjLAQAAUGMhAn2YaZnv25I6d6vbb1kw6Xp5IToDrEzl/0VBIW21gHrTZwXg5jGdALJ1IQKyNpDNiOiN6lWpYethib04+XC9bpFXrdpec+xO3U5IM2is9ckf5AABAD0CAAAAAALuiOL0rRcAABYAFPnpLByQq1Gg3vwiP6qR8FmOOjwxvVllM08DAAALBfXJH+QAsXUAAK4AAAAAAQcBAAAAAAAA"]}' -H "Content-Type: application/json" http://127.0.0.1:9999/
{"result":"cHNidP8BAP0FAQIAAAABWUWxYiPKgdGfXcIxJ6MRDxEpUecw59Gk4NpROI5oukoBAAAAAAAAAAAEPttkvdwAAAAXqRSOVAp6Qe/u2hq74e/ThB8foBKn7IfZYMgGCAAAAADbmaQ2nwAAAEdRIQLpfVqyaL9Jb/IkveatNyVeONE8Q/6TzXAWosxLo9e21SECc5G3XiK7xKLlkBG7prMx7p0fMeQwMH5e9H10mBon39JSrtgtgjjLAQAAUGMhAn2YaZnv25I6d6vbb1kw6Xp5IToDrEzl/0VBIW21gHrTZwXg5jGdALJ1IQKyNpDNiOiN6lWpYethib04+XC9bpFXrdpec+xO3U5IM2is9ckf5AABAD0CAAAAAALuiOL0rRcAABYAFPnpLByQq1Gg3vwiP6qR8FmOOjwxvVllM08DAAALBfXJH+QAsXUAAK4AAAAAAQcBAAAAAAAA","error":null}
```
## Websocket endpoints
Bitcoin-s offers websocket endpoints. By default, the endpoint is `ws://localhost:1999/events`
You can configure where how the endpoints are configured inside your `bitcoin-s.conf`
```
bitcoin-s.server.wsbind=localhost
bitcoin-s.server.wsport=19999
```
These events are implemented using our [internal callback mechanism](../wallet/wallet-callbacks.md#wallet-callbacks).
An example event that is defined is our `blockprocess` event.
Everytime our wallet processes a block, our wallet will notify you via websockets.
Here is an example payload
The current types of events defined are
1. `txprocessed` - when the wallet processes a transaction. Every transaction in a block will get relayed currently
2. `reservedutxos` - when the wallet reserves OR unreserves utxos
3. `newaddress` - when the wallet generates a new address
4. `txbroadcast` - when the wallet broadcasts a tx
5. `blockprocessed` - when the wallet processes a block
```
{"type":"blockprocessed","payload":{"raw":"04e0ff2ffce8c3e866e367d305886a3f9d353e557524f61f9cf0c26c46000000000000001206d2e396387bff1c13cbe572d4646abae1ae405f4066ab5e6f5edd6d8f028008a8bb61ffff001af23dd47e","hash":"00000000000000de21f23f6945f028d5ecb47863428f6e9e035ab2fb7a3ef356","confirmations":1,"height":2131641,"version":805298180,"versionHex":"2fffe004","merkleroot":"80028f6ddd5e6f5eab66405f40aee1ba6a64d472e5cb131cff7b3896e3d20612","time":1639688200,"mediantime":1639688200,"nonce":2127838706,"bits":"1a00ffff","difficulty":1.6069135243303364E60,"chainwork":"00000000000000000000000000000000000000000000062438437ddd009e698b","previousblockhash":"00000000000000466cc2f09c1ff62475553e359d3f6a8805d367e366e8c3e8fc","nextblockhash":null}}
```

View file

@ -0,0 +1,173 @@
---
id: version-1.9.8-chain-query-api
title: Chain Query API
original_id: chain-query-api
---
### ChainQueryAPI
The ChainQueryApi is how the wallet project stays aware of the current best chain.
This allows the wallet for example to calculate the number of confirmations for a transaction,
get the current chain tip, or even retrieve block filters for a given set of blocks.
Since this is an API it can be hooked up to the `chain` module of bitcoin-s but it can also be linked to
any other implementation of your choosing. This allows you to use the bitcoin-s wallet in any schema that you
want.
The functions that the ChainQueryApi supports are:
```scala
trait ChainQueryApi {
/** Gets the height of the given block */
def getBlockHeight(blockHash: DoubleSha256DigestBE): Future[Option[Int]]
/** Gets the hash of the block that is what we consider "best" */
def getBestBlockHash(): Future[DoubleSha256DigestBE]
/** Gets number of confirmations for the given block hash*/
def getNumberOfConfirmations(
blockHashOpt: DoubleSha256DigestBE): Future[Option[Int]]
/** Gets the number of compact filters in the database */
def getFilterCount: Future[Int]
/** Returns the block height of the given block stamp */
def getHeightByBlockStamp(blockStamp: BlockStamp): Future[Int]
def getFiltersBetweenHeights(
startHeight: Int,
endHeight: Int): Future[Vector[FilterResponse]]
def getMedianTimePast(): Future[Long]
}
```
## Chain query with bitcoind
As an example, we will show you how to use the `ChainQueryApi` and bitcoind to query chain data.
```scala
implicit val system: ActorSystem = ActorSystem(s"node-api-example")
implicit val ec: ExecutionContextExecutor = system.dispatcher
implicit val walletConf: WalletAppConfig =
BitcoinSTestAppConfig.getNeutrinoTestConfig().walletConf
val instance = BitcoindInstanceLocal.fromConfigFile(BitcoindConfig.DEFAULT_CONF_FILE)
val bitcoind = BitcoindRpcClient(instance)
val nodeApi = MockNodeApi.mock
// This function can be used to create a callback for when our chain api receives a transaction, block, or
// a block filter, the returned NodeCallbacks will contain the necessary items to initialize the callbacks
def createCallbacks(
processTransaction: Transaction => Future[Unit],
processCompactFilters: (Vector[(DoubleSha256DigestBE, GolombFilter)]) => Future[Unit],
processBlock: Block => Future[Unit]): NodeCallbacks = {
lazy val onTx: OnTxReceived = { tx =>
processTransaction(tx)
}
lazy val onCompactFilters: OnCompactFiltersReceived = {
blockFilters =>
processCompactFilters(blockFilters)
}
lazy val onBlock: OnBlockReceived = { block =>
processBlock(block)
}
NodeCallbacks(onTxReceived = Vector(onTx),
onBlockReceived = Vector(onBlock),
onCompactFiltersReceived = Vector(onCompactFilters))
}
// Here is a super simple example of a callback, this could be replaced with anything, from
// relaying the block on the network, finding relevant wallet transactions, verifying the block,
// or writing it to disk
val exampleProcessTx = (tx: Transaction) =>
Future.successful(println(s"Received tx: ${tx.txIdBE}"))
val exampleProcessBlock = (block: Block) =>
Future.successful(println(s"Received block: ${block.blockHeader.hashBE}"))
val exampleProcessFilters =
(filters: Vector[(DoubleSha256DigestBE, GolombFilter)]) =>
Future.successful(println(s"Received filter: ${filters.head._1.flip.hex} ${filters.head._2.hash.flip.hex}"))
val exampleCallbacks =
createCallbacks(exampleProcessTx, exampleProcessFilters, exampleProcessBlock)
// Here is where we are defining our actual chain api, Ideally this could be it's own class
// but for the examples sake we will keep it small.
val chainApi = new ChainQueryApi {
override def epochSecondToBlockHeight(time: Long): Future[Int] =
Future.successful(0)
/** Gets the height of the given block */
override def getBlockHeight(
blockHash: DoubleSha256DigestBE): Future[Option[Int]] = {
bitcoind.getBlock(blockHash).map(block => Some(block.height))
}
/** Gets the hash of the block that is what we consider "best" */
override def getBestBlockHash(): Future[DoubleSha256DigestBE] = {
bitcoind.getBestBlockHash
}
/** Gets number of confirmations for the given block hash */
override def getNumberOfConfirmations(
blockHash: DoubleSha256DigestBE): Future[Option[Int]] = {
for {
tip <- bitcoind.getBlockCount
block <- bitcoind.getBlock(blockHash)
} yield {
Some(tip - block.height + 1)
}
}
/** Gets the number of compact filters in the database */
override def getFilterCount(): Future[Int] = {
// since bitcoind should have the filter for
// every block we can just return the block height
bitcoind.getBlockCount
}
/** Returns the block height of the given block stamp */
override def getHeightByBlockStamp(blockStamp: BlockStamp): Future[Int] = {
blockStamp match {
case blockHeight: BlockStamp.BlockHeight =>
Future.successful(blockHeight.height)
case blockHash: BlockStamp.BlockHash =>
getBlockHeight(blockHash.hash).map(_.get)
case blockTime: BlockStamp.BlockTime =>
Future.failed(new RuntimeException(s"Not implemented: $blockTime"))
}
}
override def getFiltersBetweenHeights(
startHeight: Int,
endHeight: Int): Future[Vector[FilterResponse]] = {
val filterFs = startHeight
.until(endHeight)
.map { height =>
for {
hash <- bitcoind.getBlockHash(height)
filter <- bitcoind.getBlockFilter(hash, FilterType.Basic)
} yield {
FilterResponse(filter.filter, hash, height)
}
}
.toVector
Future.sequence(filterFs)
}
override def getMedianTimePast(): Future[Long] = bitcoind.getMedianTimePast()
}
// Finally, we can initialize our wallet with our own node api
val wallet =
Wallet(nodeApi = nodeApi, chainQueryApi = chainApi, feeRateApi = ConstantFeeRateProvider(SatoshisPerVirtualByte.one))
// Then to trigger one of the events we can run
wallet.chainQueryApi.getFiltersBetweenHeights(100, 150)
```

View file

@ -0,0 +1,115 @@
---
title: Syncing Blockfilters
id: version-1.9.8-filter-sync
original_id: filter-sync
---
The `chain` module has the ability to store [BIP157](https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki) block filters locally. Generally these filters are useful
for doing wallet rescans. The idea is you can generate a list of script pubkeys you are interested in and see if
the block filter matches the scriptPubKey.
As we demonstrated in [the chain docs](chain.md) with block headers, you can sync block filters from an external data source
as well. We are going to use bitcoind as an example of an external data source to sync filters against. It is important
that the bitcoind version you are using is >= `v19` as the [`getblockfilter`](https://github.com/bitcoin/bitcoin/blob/master/doc/release-notes/release-notes-0.19.0.1.md#new-rpcs)
rpc is implemented there. You need to make sure bitcoind is started with the `-blockfilterindex` flag. This makes it
so we can query filters.
> It is important to remember that you need fully synced block headers before you can sync filter headers and filters. Please see [the chain docs](chain.md) for syncing block headers.
#### Abstract idea of syncing filters.
Our internal infrastructure depends on one function to be implemented to be able to sync filters.
```scala
val getFilterFunc: BlockHeader => Future[FilterWithHeaderHash] = ???
```
With `getFilterFunc` given a `BlockHeader` we can find it's associated `GolombFilter` -- which is our internal repesentation
of a BIP157 block filter.
The basic idea for `FilterSync.syncFilters()` is to look at our current best block header inside of our `ChainApi.getBestBlockHeader()`
and then check what our best block filter's block hash is with `ChainApi.getBestFilterHeader()`. If the blockfilter returned from our internal
data store is NOT associated with our best block header, we attempt to sync our filter headers to catch up to our best block header.
### Syncing block filters against bitcoind
We are going to implement `getFilterFunc` with bitcoind and then sync a few filter headers.
```scala
implicit val system = ActorSystem(s"filter-sync-example")
implicit val ec = system.dispatcher
implicit val chainAppConfig = BitcoinSTestAppConfig.getNeutrinoTestConfig().chainConf
val instance = BitcoindInstanceLocal.fromConfigFile(BitcoindConfig.DEFAULT_CONF_FILE)
val bitcoind = BitcoindRpcClient(instance)
val bitcoindWithChainApiF: Future[BitcoindBaseVersionChainHandlerViaRpc] = {
ChainUnitTest.createChainApiWithBitcoindRpc(bitcoind)
}
val bitcoindF = bitcoindWithChainApiF.map(_.bitcoindRpc)
val chainApiF = bitcoindWithChainApiF.map(_.chainHandler)
val filterType = FilterType.Basic
val addressF = bitcoindF.flatMap(_.getNewAddress)
//this is the function that we are going to use to sync
//our internal filters against. We use this function to query
//for each block filter associated with a blockheader
val getFilterFunc: BlockHeader => Future[FilterWithHeaderHash] = { blockHeader =>
val prevFilterResultF =
bitcoindF.flatMap(_.getBlockFilter(blockHeader.hashBE, filterType))
prevFilterResultF.map { filterResult =>
FilterWithHeaderHash(filterResult.filter, filterResult.header)
}
}
//ok enough setup, let's generate a block that we need to sync the filter for in bitcoind
val block1F = for {
bitcoind <- bitcoindF
address <- addressF
hashes <- bitcoind.generateToAddress(1,address)
} yield hashes
//to be able to sync filters, we need to make sure our block headers are synced first
//so let's sync our block headers to our internal chainstate
val chainApiSyncedHeadersF = for {
bitcoind <- bitcoindF
handler <- chainApiF
getBestBlockHash = SyncUtil.getBestBlockHashFunc(bitcoind)
getBlockHeader = SyncUtil.getBlockHeaderFunc(bitcoind)
syncedChainApiHeaders <- ChainSync.sync(handler, getBlockHeader, getBestBlockHash)
} yield syncedChainApiHeaders
//now that we have synced our 1 block header, we can now sync the 1 block filter
//associated with that header.
val chainApiSyncedFiltersF = for {
syncedHeadersChainApi <- chainApiSyncedHeadersF
syncedFilters <- FilterSync.syncFilters(syncedHeadersChainApi,getFilterFunc)
} yield syncedFilters
//now we should have synced our one filter, let's make sure we have it
val resultF = for {
chainApi <- chainApiSyncedFiltersF
filterHeaderCount <- chainApi.getFilterHeaderCount()
filterCount <- chainApi.getFilterCount()
} yield {
println(s"filterHeaderCount=$filterHeaderCount filterCount=$filterCount")
}
//cleanup
resultF.onComplete { _ =>
for {
c <- bitcoindWithChainApiF
_ <- ChainUnitTest.destroyBitcoindChainApiViaRpc(c)
_ <- system.terminate()
} yield ()
}
```
Yay! Now we have synced block filters from an external data source. If you want to repeatedly sync you can just call
`FilterSync.syncFilters(syncedFiltersChainApi,getFilterFunc)` every time you would like to sync.
Again, you need to ensure
your headers are synced before you can sync filters, so make sure that you are calling `ChainSync.sync()` before syncing
filters.

View file

@ -0,0 +1,540 @@
---
title: Application Configuration
id: version-1.9.8-configuration
original_id: configuration
---
Bitcoin-S uses [HOCON](https://github.com/lightbend/config/blob/master/HOCON.md)
to configure various parts of the application the library offers. HOCON is a superset of JSON, that is, all valid JSON
is valid HOCON.
All configuration for Bitcoin-S is under the `bitcoin-s` key.
If you have a file `application.conf` anywhere on your classpath when using bitcoin-s, the values there take precedence
over the ones found in our
`reference.conf`. We also look for the file `bitcoin-s.conf` in the current Bitcoin-S data directory.
The resolved configuration gets parsed by
[`AppConfig`](/api/org/bitcoins/db/AppConfig).
`AppConfig` is an abstract class that's implemented by corresponding case classes in the `wallet`, `chain` and `node`
projects. Here's some examples of how to construct a wallet configuration:
```scala
import org.apache.pekko.actor.ActorSystem
import org.bitcoins.wallet.config.WalletAppConfig
import com.typesafe.config.ConfigFactory
import java.nio.file.Paths
import scala.util.Properties
import scala.concurrent.ExecutionContext.Implicits.global
implicit val system: ActorSystem = ActorSystem("configuration-example")
// reads $HOME/.bitcoin-s/
val defaultConfig = WalletAppConfig.fromDefaultDatadir()
// reads a custom data directory
val customDirectory = Paths.get(Properties.userHome, "custom-bitcoin-s-directory")
val configFromCustomDatadir = WalletAppConfig(customDirectory, Vector.empty)
// reads a custom data directory and overrides the network to be testnet3
val customOverride = ConfigFactory.parseString("bitcoin-s.network = testnet3")
val configFromCustomDirAndOverride = WalletAppConfig(customDirectory, Vector(customOverride))
```
You can pass as many `com.typesafe.config.Config`s as you'd like. If any keys appear multiple times the last one
encountered takes precedence.
## Command Line Options
There are a few command line options available that take precedence over configuration file.
- `--datadir <directory>`
`datadir` sets the data directory instead of using the default `$HOME/.bitcoin-s`
- `--rpcbind <ip>`
`rpcbind` sets the interface the rpc server binds to instead of using the default `127.0.0.1`
- `--rpcport <port>`
`rpcport` sets the port the rpc server binds to instead of using the default `9999`
- `--force-recalc-chainwork`
`force-recalc-chainwork` will force a recalculation of the entire chain's chain work, this can be useful if there is
an incompatible migration or if it got out of sync.
- `-Dlogback.configurationFile=/path/to/config.xml`
You can set a custom logback configuration. If you need help creating a custom logback file you can
read [the logback configuration documentation](http://logback.qos.ch/manual/configuration.html).
## Internal configuration
Database connections are also configured by using HOCON. This is done
in [`reference.conf`](https://github.com/bitcoin-s/bitcoin-s/blob/master/db-commons/src/main/resources/reference.conf)
inside the `db-commons` module. The options exposed here are **not** intended to be used by users of Bitcoin-S, and are
internal only.
## Database Migrations
All of our modules that require databases now have database migrations. The tool we use for these migrations is
called [flyway](https://flywaydb.org/). To find your projects migraitons, you need to look inside of the
`[project-name]/src/main/resources/[database-name]/migration/`. For example, the chain projects migrations live under
the path `chain/src/main/resources/chaindb/migration/V1__chain_db_baseline.sql`.
Migrations can be executed by calling
the [`DbManagement.migrate()`](https://github.com/bitcoin-s/bitcoin-s/blob/e387d075b0ff2e0a0fec15788fcb48e4ddc4d9d5/db-commons/src/main/scala/org/bitcoins/db/DbManagement.scala#L92)
method. Migrations are applied by default on server startup, via
the [`AppConfig.start()`](https://github.com/bitcoin-s/bitcoin-s/blob/master/db-commons/src/main/scala/org/bitcoins/db/AppConfig.scala#L49)
method.
These migrations are setup so that project's databases and migrations are independent of each other. Therefore if you
want to use the `bitcoin-s-chain` project, but not the `bitcoin-s-wallet` project, wallet migrations are not applied. It
should be noted if you are using a module as a library, you are responsible for configuring the database via
[slick's configuration](https://scala-slick.org/doc/3.3.1/database.html#using-typesafe-config) and calling
[`AppConfig.start()`](https://github.com/bitcoin-s/bitcoin-s/blob/master/db-commons/src/main/scala/org/bitcoins/db/AppConfig.scala#L49)
to ensure the entire module is initialized correctly.
## Example Configuration File
```$xslt
bitcoin-s {
# the network your bitcoin-s node is running on
network = "testnet3" # regtest, testnet3, mainnet, signet
# specify what backend you are using with bitcoin-s
# by default we do neutrino, but you can also connect
# bitcoind with the configuration settings in bitcoin-s.bitcoind-rpc
node.mode = neutrino # neutrino, bitcoind
# configurations for connecting to bitcoind
bitcoind-rpc {
# bitcoind rpc username
rpcuser = user
# bitcoind rpc password
# If your password contains the characters '$','{', '}', '[', ']', ':', '=', ',', '+', '#', '`', '^', '?', '!', '@', '*', '&', whitespace
# or the string "//", enclose it in double quotes
# rpcpassword = "password=" if the original password is password=, rpcpassword = "passwo//rd" if the original password is passwo//rd etc.
# If it contains '\' or '"', escape it with '\'
# rpcpassword = "pass\\word" if the original password is pass\word, rpcpassword = "pass\"word" if the original password is pass"word
rpcpassword = password
# Binary location of bitcoind
binary = ${HOME}/.bitcoin-s/binaries/bitcoind/bitcoin-0.20.1/bin/bitcoind
# bitcoind datadir
datadir = ${HOME}/.bitcoin
# bitcoind network host
connect = localhost
# bitcoind p2p port
port = 8333
# bitcoind rpc host
rpcconnect = localhost
# bitcoind rpc port
rpcport = 8332
# bitcoind zmq raw tx
zmqpubrawtx = "tcp://127.0.0.1:28332"
# bitcoind zmq raw block
zmqpubrawblock = "tcp://127.0.0.1:28333"
# bitcoind zmq hash tx
zmqpubhashtx = "tcp://127.0.0.1:28330"
# bitcoind zmq raw block
zmqpubhashblock = "tcp://127.0.0.1:28331"
#If you have a bitcoind instance that is running remotely on another machine, you should set it to true
isRemote = false
}
# settings if you are using a neutrino node in bitcoin-s
node {
# a list of peer addresses in form "hostname:portnumber"
# Port number is optional, the default value is 8333 for mainnet,
# 18333 for testnet and 18444 for regtest.
peers = [""]
# try to connect to peers from dns seeds, database, addr messages etc
enable-peer-discovery = true
# number of persistent peer connections to maintain for node use
maxConnectedPeers = 1
# peers discovery configs, ideally you would not want to change this
# timeout for tcp connection
connection-timeout = 5s
# time interval for trying next set of peers in peer discovery
try-peers-interval = 12 hour
# the delay until we start attempting to connect to peers
try-peers-start-delay = 1 second
# wait time for queries like getheaders etc before switching to another
query-wait-time = 120s
hikari-logging = true
hikari-logging-interval = 10 minute
# whether to have p2p peers relay us unconfirmed txs
relay = false
# how often we run health checks for our peers
health-check-interval = 1 minutes
# if the peer does not send us a message within this duration
# we disconnect it for inactivity
peer-timeout = 20 minute
}
proxy {
# You can configure SOCKS5 proxy to use Tor for outgoing connections
enabled = false
socks5 = "127.0.0.1:9050"
}
# tor settings
tor {
# You can enable Tor for incoming connections
enabled = false
control = "127.0.0.1:9051"
# Tor daemon can be provided by the node operator.
# If this parameter set to true, bitcoin-s will connect the provided Tor daemon.
# Otherwise bitcoin-s will start its own pre-packaged daemon.
provided = false
# This parameter allows to use random port numbers for pre-packaged Tor daemon,
# which is useful if another Tor daemon instance already bound SOCKS5 and control ports.
# In this case bitcoin-s.tor.control and bitcoin-s.proxy.socks5
# addresses will be automatically changed to "localhost:<random port>"
use-random-ports = true
# The password used to arrive at the HashedControlPassword for the control port.
# If provided, the HASHEDPASSWORD authentication method will be used instead of
# the SAFECOOKIE one.
# password = securePassword
# The path to the private key of the onion service being created
# privateKeyPath = /path/to/priv/key
# Optonal Tor targets. If empty all hidden serices will be created at localhost.
targets = []
}
# settings for the chain module
chain {
neutrino {
filter-header-batch-size.default = 2000
filter-header-batch-size.regtest = 10
# You can set a network specific filter-header-batch-size
# by adding a trailing `.networkId` (main, test, regtest)
# It is recommended to keep the main and test batch size high
# to keep the sync time fast, however, for regtest it should be small
# so it does not exceed the chain size.
filter-batch-size = 1000
}
hikari-logging = true
hikari-logging-interval = 10 minute
websocket {
# don't emit block processed events over the websocket
# until IBD is complete. This is an optimization for the
# the UI so it doesn't have to handle hundreds of thousands of
# events while IBD is going on.
block-processed-ibd = false
}
}
# settings for wallet module
wallet {
# You can have multiple wallets by setting a different
# wallet name for each of them. They will each have
# their own unique seed and database or schema,
# depending on the database driver.
# The wallet name can contain letters, numbers, and underscores '_'.
# walletName = MyWallet0
defaultAccountType = segwit # legacy, segwit, nested-segwit
bloomFalsePositiveRate = 0.0001 # percentage
# the number of consecutive addresses that we do not
# discover funds in before we mark as rescan as exhausted
# this is needed because we can never truely tell how many addresses
# the wallet has used when executing a rescan from a seed
addressGapLimit = 100
# the number of addresses that get generated everytime
# we need to rescan. If a match occurs within the addressGapLimit
# we generate another discoveryBatchSize addresses and then rescan again
discoveryBatchSize = 100
requiredConfirmations = 6
# Expected average fee rate over the long term
# in satoshis per virtual byte
longTermFeeRate = 10
# How big the address queue size is before we throw an exception
# because of an overflow
addressQueueSize = 10
# How long we attempt to generate an address for
# before we timeout
addressQueueTimeout = 5 seconds
# Allow external payout and change addresses in DLCs
# By default all DLC addresses are generated by the wallet itself
allowExternalDLCAddresses = false
# How often the wallet will rebroadcast unconfirmed transactions
rebroadcastFrequency = 4 hours
hikari-logging = true
hikari-logging-interval = 10 minute
}
keymanager {
# You can optionally set a BIP 39 password
# bip39password = "changeMe"
# Password that your seed is encrypted with
# aesPassword = changeMe
# At least 16 bytes of entropy encoded in hex
# This will be used as the seed for any
# project that is dependent on the keymanager
# entropy = ""
}
# Bitcoin-S provides manny different fee providers
# You can configure your server to use any of them
# Below is some examples of different options
fee-provider {
# name = mempoolspace # Uses mempool.space's api
# The target is optional for mempool.space
# It refers to the expected number of blocks until confirmation
# target = 6
# name = bitcoinerlive # Uses bitcoiner.live's api
# The target is optional for Bitcoiner Live
# It refers to the expected number of blocks until confirmation
# target = 6
# name = bitgo # Uses BitGo's api
# The target is optional for BitGo
# It refers to the expected number of blocks until confirmation
# target = 6
# name = constant # A constant fee rate in sats/vbyte
# target = 1 # Will always use 1 sat/vbyte
}
dlcnode {
# The address we are listening on for incoming connections for DLCs
# Binding to 0.0.0.0 makes us listen to all incoming connections
# Consider using 127.0.0.1 listen address if Tor is enabled.
# listen = "0.0.0.0:2862"
# The address our peers use to connect to our node.
# By default it's the same as the listen address,
# or if Tor is enabled, the hidden service's onion address.
# You can specify a port number like this "192.168.0.1:12345",
# The default port number is the same as in the listen adrress
# external-ip = "192.168.0.1"
}
server {
# The port we bind our rpc server on
rpcport = 9999
# The ip address we bind our server too
rpcbind = "127.0.0.1"
# The port we bind our websocket server on
wsport = 19999
# The ip address we bind the websocket server too
wsbind = "127.0.0.1"
# The basic auth password. It must me must be non empty.
password = topsecret
}
oracle {
# The port we bind our rpc server on
rpcport = 9998
# The ip address we bind our server too
rpcbind = "127.0.0.1"
# The basic auth password. It must me must be non empty.
password = supersecret
hikari-logging = true
hikari-logging-interval = 10 minute
db {
path = ${bitcoin-s.datadir}/oracle/
}
}
dbDefault = {
dataSourceClass = slick.jdbc.DatabaseUrlDataSource
profile = "slick.jdbc.SQLiteProfile$"
db {
# for information on parameters available here see
# https://scala-slick.org/doc/3.3.1/api/index.html#slick.jdbc.JdbcBackend$DatabaseFactoryDef@forConfig(String,Config,Driver,ClassLoader):Database
path = ${bitcoin-s.datadir}/${bitcoin-s.network}/
driver = org.sqlite.JDBC
user = ""
password = ""
host = localhost
port = 5432
# this needs to be set to 1 for SQLITE as it does not support concurrent database operations
# see: https://github.com/bitcoin-s/bitcoin-s/pull/1840
numThreads = 1
queueSize=5000
connectionPool = "HikariCP"
registerMbeans = true
}
hikari-logging = false
hikari-logging-interval = 10 minute
}
testkit {
pg {
#enabled postgres backend database for all test cases
enabled = false
}
}
}
pekko {
loglevel = "OFF"
stdout-loglevel = "OFF"
http {
client {
# The time after which an idle connection will be automatically closed.
# Set to `infinite` to completely disable idle connection timeouts.
# some requests potentially take a long time, like generate and prune
idle-timeout = 5 minutes
}
server {
# The amount of time until a request times out on the server
# If you have a large payload this may need to be bumped
# https://doc.akka.io/docs/akka-http/current/common/timeouts.html#request-timeout
request-timeout = 10s
}
}
actor {
debug {
# enable DEBUG logging of all AutoReceiveMessages (Kill, PoisonPill etc.)
autoreceive= off
# enable function of LoggingReceive, which is to log any received message at
# DEBUG level
receive = on
# enable DEBUG logging of unhandled messages
unhandled = off
# enable DEBUG logging of actor lifecycle changes
lifecycle = off
event-stream=off
}
}
}
```
## Database configuration
By default, bitcoin-s uses Sqlite to store its data. It creates three Sqlite databases
in `~/.bitcoin-s/${network}`: `chain.sqlite` for `chain` project,
`node.sqlite` for `node` project and `wallet.sqlite` the wallet. This is the default configuration, it doesn't require
additional changes in the config file.
`bitcoin-s` also supports PostgreSQL as a database backend. In order to use a PostgreSQL database for all project you
need to add following into your config file:
```$xslt
bitcoin-s {
common {
profile = "slick.jdbc.PostgresProfile$"
db {
driver = org.postgresql.Driver
# these 3 options will result into a jdbc url of
# "jdbc:postgresql://localhost:5432/database"
name = database
host = localhost
port = 5432
user = "user"
password = "topsecret"
numThreads = 5
# http://scala-slick.org/doc/3.3.3/database.html
connectionPool = "HikariCP"
registerMbeans = true
}
}
chain.profile = ${bitcoin-s.common.profile}
chain.db = ${bitcoin-s.common.db}
chain.db.poolName = "chain-connection-pool"
node.profile = ${bitcoin-s.common.profile}
node.db = ${bitcoin-s.common.db}
node.db.poolName = "node-connection-pool"
wallet.profile = ${bitcoin-s.common.profile}
wallet.db = ${bitcoin-s.common.db}
wallet.db.poolName = "wallet-connection-pool"
oracle.profile = ${bitcoin-s.common.profile}
oracle.db = ${bitcoin-s.common.db}
oracle.db.poolName = "oracle-connection-pool"
}
```
The database driver will create a separate SQL namespace for each sub-project: `chain`, `node` and `wallet`.
Also you can use mix databases and drivers in one configuration. For example, This configuration file enables Sqlite
for `node` project (it's default, so its configuration is omitted), and `walletdb` and `chaindb` PostgreSQL databases
for `wallet` and `chain` projects:
```$xslt
bitcoin-s {
chain {
profile = "slick.jdbc.PostgresProfile$"
db {
driver = org.postgresql.Driver
name = chaindb
host = localhost
port = 5432
user = "user"
password = "topsecret"
}
}
wallet {
profile = "slick.jdbc.PostgresProfile$"
db {
driver = org.postgresql.Driver
name = walletdb
host = localhost
port = 5432
user = "user"
password = "topsecret"
}
}
}
```

View file

@ -0,0 +1,59 @@
---
id: version-1.9.8-addresses
title: Generating Addresses
original_id: addresses
---
Almost all Bitcoin applications need to generate addresses
for their users somehow. There's a lot going on in getting
a correct bitcoin address, but our APIs make it possible to
to get started with all types of addresses in a matter of
minutes.
## Generating SegWit (bech32) addresses
Generating native SegWit addresses in the bech32 format
is something that all Bitcoin applications should enable,
as it makes the transaction fees less expensive, and also
makes the addresses more readable by humans. However, it
has seen slower than necessary adoption. With Bitcoin-S
you can generate bech32 addresses in four(!) lines of code
(not counting comments and imports), so now there's no
reason to keep using legacy transaction formats.
```scala
// this generates a random private key
val privkey = ECPrivateKey()
// privkey: ECPrivateKey = Masked(ECPrivateKey)
val pubkey = privkey.publicKey
// pubkey: org.bitcoins.crypto.ECPublicKey = ECPublicKey(03bae899125438de69887b58c32e66dbc2febcb7180a1e602dd61c9f1388cd94bf)
val segwitAddress = {
// see https://bitcoin.org/en/glossary/pubkey-script
// for reading resources on the details of scriptPubKeys
// pay-to-witness-pubkey-hash scriptPubKey V0
val scriptPubKey = P2WPKHWitnessSPKV0(pubkey)
Bech32Address(scriptPubKey, TestNet3)
}
// segwitAddress: Bech32Address = tb1qmapc3z69etltt7gez7jkc47a80kjg3kraprs9q
println(segwitAddress.toString)
// tb1qmapc3z69etltt7gez7jkc47a80kjg3kraprs9q
```
## Generating legacy (base58) addresses
If you need to generate legacy addresses for backwards
compatability reasons, that's also a walk in the park.
Take a look:
```scala
// we're reusing the same private/public key pair
// from before. don't do this in an actual application!
val legacyAddress = P2PKHAddress(pubkey, TestNet3)
// legacyAddress: P2PKHAddress = n1sTt8guoyHZD6cTPb8nvxzGQv66MqStcq
println(legacyAddress.toString)
// n1sTt8guoyHZD6cTPb8nvxzGQv66MqStcq
```

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,149 @@
---
id: version-1.9.8-hd-keys
title: HD Key Generation
original_id: hd-keys
---
In modern Bitcoin wallets, users only need to write down
a sequence of words, and that sequence is a complete backup
of their wallet. This is thanks to what's called Hierarchical
Deterministic key generation. In short, every wallet using HD
key generation has a root seed for each wallet, and this
seed can be used to generate an arbitrary amount of later
private and public keys. This is done in a standardized manner,
so different wallets can operate with the same standard.
> If you want to jump into the details of how this work,
> you should check out
> [BIP 32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki).
Bitcoin-S supports generating keys in this fashion. Here's a
full example of how to obtain a wallet seed, and then
use that to generate further private and public keys:
```scala
import scodec.bits._
import org.bitcoins.core.crypto._
import org.bitcoins.core.hd._
// the length of the entropy bit vector determine
// how long our phrase ends up being
// 256 bits of entropy results in 24 words
val entropy: BitVector = MnemonicCode.getEntropy256Bits
// entropy: BitVector = BitVector(256 bits, 0x345bb3d5f1d5510bdb5ac05c548cd2d9e51922bec24ca3415e98dd41b2198cc3)
val mnemonicCode = MnemonicCode.fromEntropy(entropy)
// mnemonicCode: MnemonicCode = Masked(MnemonicCodeImpl)
mnemonicCode.words // the phrase the user should write down
// res0: Vector[String] = Vector(crowd, talk, voice, together, fence, magnet, hope, fix, fox, piece, cruise, record, face, mule, wild, end, person, april, plate, ritual, brass, art, credit, guide)
// the password argument is an optional, extra security
// measure. all MnemonicCode instances will give you a
// valid BIP39 seed, but different passwords will give
// you different seeds. So you could have as many wallets
// from the same seed as you'd like, by simply giving them
// different passwords.
val bip39Seed = BIP39Seed.fromMnemonic(mnemonicCode,
password = "secret password")
// bip39Seed: BIP39Seed = Masked(BIP39SeedImpl)
val xpriv = ExtPrivateKey.fromBIP39Seed(ExtKeyVersion.SegWitMainNetPriv,
bip39Seed)
// xpriv: ExtPrivateKey = Masked(ExtPrivateKeyImpl)
val xpub = xpriv.extPublicKey
// xpub: ExtPublicKey = zpub6jftahH18ngZwQXZhFHaUuu8bKnQPDRe5724RAjeMjfKRHoGJC5fukh5jJjw4TurAYCKFiuVHmUtbNqDUdgSDXZDSqXpBteBjQhPAcbvTyz
// you can now use the generated xpriv to derive further
// private or public keys
// this can be done with BIP89 paths (called SegWitHDPath in bitcoin-s)
val segwitPath = SegWitHDPath.fromString("m/84'/0'/0'/0/0")
// segwitPath: SegWitHDPath = m/84'/0'/0'/0/0
// alternatively:
val otherSegwitPath =
SegWitHDPath(HDCoinType.Bitcoin,
accountIndex = 0,
HDChainType.External,
addressIndex = 0)
// otherSegwitPath: SegWitHDPath = m/84'/0'/0'/0/0
segwitPath == otherSegwitPath
// res1: Boolean = true
// there's also paths available for legacy
// addresses (LegacyHDPath) as well as nested
// segwit paths (NestedSegWitPath)
```
## Generating new addresses without having access to the private key
One the coolest features of HD wallets is that it's possible
to generate addresses offline, without having access to the
private keys. This feature is commonly called watch-only
wallets, where a wallet can import information about all
your past and future transactions, without being able to
spend or steal any of your money.
Let's see an example of this:
```scala
import scala.util.Success
import org.bitcoins.core.protocol.script._
import org.bitcoins.core.protocol.Bech32Address
import org.bitcoins.core.config.TestNet3
// first account -------┐
// bitcoin ----------┐ |
// segwit --------┐ | |
val accountPath = BIP32Path.fromString("m/84'/0'/0'")
// accountPath: BIP32Path = m/84'/0'/0'
val accountXpub = {
// this key is sensitive, keep away from prying eyes!
val accountXpriv = xpriv.deriveChildPrivKey(accountPath)
// this key is not sufficient to spend from, but we
// can generate addresses with it!
accountXpriv.extPublicKey
}
// accountXpub: ExtPublicKey = zpub6qwCdTFjwSsoEaW1iiETNFttywdwCPx5YDuzJyMEqcF1gqwTK7M8tHsAs5NGvZbDky7L72DQmjArzH85SPEP6RCTqvxhiE8YXsrLoTB4uHb
// address no. 0 ---------------┐
// external address ----------┐ |
val firstAddressPath = SegWitHDPath.fromString("m/84'/0'/0'/0/0")
// firstAddressPath: SegWitHDPath = m/84'/0'/0'/0/0
val firstAccountAddress = {
// this is a bit quirky, but we're not interesting in
// deriving the complete path from our account xpub
// instead, we're only interested in the part after
// the account level (3rd level). the .diff() method
// achieves that
val Some(pathDiff) = accountPath.diff(firstAddressPath)
// deriving public keys from hardened extended keys
// is not possible, that's why .deriveChildPubKey()
// returns a Try[ExtPublicKey]. A hardened key is marked
// by a ' after the number in the notation we use above.
val Success(extPubKey) = accountXpub.deriveChildPubKey(pathDiff)
val pubkey = extPubKey.key
val scriptPubKey = P2WPKHWitnessSPKV0(pubkey)
Bech32Address(scriptPubKey, TestNet3)
}
// firstAccountAddress: Bech32Address = tb1qky9qh5fd7jlm3umjypdj8d3ycvp8cryk7hq7cr
// tada! We just generated an address you can send money to,
// without having access to the private key!
firstAccountAddress.value
// res2: String = tb1qky9qh5fd7jlm3umjypdj8d3ycvp8cryk7hq7cr
// you can now continue deriving addresses from the same public
// key, by imitating what we did above. To get the next
// HD path to generate an address at:
val nextAddressPath: SegWitHDPath = firstAddressPath.next
// nextAddressPath: SegWitHDPath = m/84'/0'/0'/0/1
```
### Signing things with HD keys
Please see [sign.md](../crypto/sign.md) for information on how to sign things with HD keys.

View file

@ -0,0 +1,158 @@
---
id: version-1.9.8-txbuilder
title: TxBuilder Example
original_id: txbuilder
---
Bitcoin-S features a transaction building API that allows you to construct and sign Bitcoin transactions. Here's an example of how to use it
```scala
implicit val ec: ExecutionContext = ExecutionContext.Implicits.global
// ec: ExecutionContext = scala.concurrent.impl.ExecutionContextImpl$$anon$3@7c906c98[Running, parallelism = 16, size = 0, active = 0, running = 0, steals = 2799, tasks = 0, submissions = 0]
// Initialize a transaction builder
val builder = RawTxBuilder()
// builder: RawTxBuilder = RawTxBuilder()
// generate a fresh private key that we are going to use in the scriptpubkey
val privKey = ECPrivateKey.freshPrivateKey
// privKey: ECPrivateKey = Masked(ECPrivateKey)
val pubKey = privKey.publicKey
// pubKey: ECPublicKey = ECPublicKey(02f6ec180dbc3588690aa3bce864f86e54ec289821342b090271488361841f8dd9)
// this is the script that the TxBuilder is going to create a
// script signature that validly spends this scriptPubKey
val creditingSpk = P2PKHScriptPubKey(pubKey = privKey.publicKey)
// creditingSpk: P2PKHScriptPubKey = pkh(241ad4894d3d6ed55d6dee9087a13cef8bbe3fb6)
val amount = 10000.satoshis
// amount: Satoshis = 10000 sats
// this is the UTXO we are going to be spending
val utxo =
TransactionOutput(value = amount, scriptPubKey = creditingSpk)
// utxo: TransactionOutput = TransactionOutput(10000 sats,pkh(241ad4894d3d6ed55d6dee9087a13cef8bbe3fb6))
// the private key that locks the funds for the script we are spending too
val destinationPrivKey = ECPrivateKey.freshPrivateKey
// destinationPrivKey: ECPrivateKey = Masked(ECPrivateKey)
// the amount we are sending -- 5000 satoshis -- to the destinationSPK
val destinationAmount = 5000.satoshis
// destinationAmount: Satoshis = 5000 sats
// the script that corresponds to destination private key, this is what is receiving the money
val destinationSPK =
P2PKHScriptPubKey(pubKey = destinationPrivKey.publicKey)
// destinationSPK: P2PKHScriptPubKey = pkh(5bc530a9388a51ba4b65d229246e579dcbc83f3c)
// this is where we are sending money too
// we could add more destinations here if we
// wanted to batch transactions
val destinations = {
val destination0 = TransactionOutput(value = destinationAmount,
scriptPubKey = destinationSPK)
Vector(destination0)
}
// destinations: Vector[TransactionOutput] = Vector(TransactionOutput(5000 sats,pkh(5bc530a9388a51ba4b65d229246e579dcbc83f3c)))
// Add the destinations to the tx builder
builder ++= destinations
// res0: RawTxBuilder = RawTxBuilder()
// we have to fabricate a transaction that contains the
// UTXO we are trying to spend. If this were a real blockchain
// we would need to reference the UTXO set
val creditingTx = BaseTransaction(version = Int32.one,
inputs = Vector.empty,
outputs = Vector(utxo),
lockTime = UInt32.zero)
// creditingTx: BaseTransaction = BaseTransaction(Int32Impl(1),Vector(),Vector(TransactionOutput(10000 sats,pkh(241ad4894d3d6ed55d6dee9087a13cef8bbe3fb6))),UInt32Impl(0))
// this is the information we need from the crediting TX
// to properly "link" it in the transaction we are creating
val outPoint = TransactionOutPoint(creditingTx.txId, UInt32.zero)
// outPoint: TransactionOutPoint = TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0)
val input = TransactionInput(
outPoint,
EmptyScriptSignature,
sequenceNumber = UInt32.zero)
// input: TransactionInput = TransactionInputImpl(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),EmptyScriptSignature,UInt32Impl(0))
// Add a new input to our builder
builder += input
// res1: RawTxBuilder = RawTxBuilder()
// We can now generate a RawTxBuilderResult ready to be finalized
val builderResult = builder.result()
// builderResult: RawTxBuilderResult = RawTxBuilderResult(Int32Impl(2),Vector(TransactionInputImpl(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),EmptyScriptSignature,UInt32Impl(0))),Vector(TransactionOutput(5000 sats,pkh(5bc530a9388a51ba4b65d229246e579dcbc83f3c))),UInt32Impl(0))
// this contains the information needed to analyze our input during finalization
val inputInfo = P2PKHInputInfo(outPoint, amount, privKey.publicKey)
// inputInfo: P2PKHInputInfo = P2PKHInputInfo(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),10000 sats,ECPublicKey(02f6ec180dbc3588690aa3bce864f86e54ec289821342b090271488361841f8dd9))
// this is how much we are going to pay as a fee to the network
// for this example, we are going to pay 1 satoshi per byte
val feeRate = SatoshisPerByte(1.satoshi)
// feeRate: SatoshisPerByte = 1 sats/byte
val changePrivKey = ECPrivateKey.freshPrivateKey
// changePrivKey: ECPrivateKey = Masked(ECPrivateKey)
val changeSPK = P2PKHScriptPubKey(pubKey = changePrivKey.publicKey)
// changeSPK: P2PKHScriptPubKey = pkh(3f4df7d840aee9abbe14e8f64d0677ccbb881342)
// We chose a finalizer that adds a change output to our tx based on a fee rate
val finalizer = StandardNonInteractiveFinalizer(
Vector(inputInfo),
feeRate,
changeSPK)
// finalizer: StandardNonInteractiveFinalizer = StandardNonInteractiveFinalizer(Vector(P2PKHInputInfo(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),10000 sats,ECPublicKey(02f6ec180dbc3588690aa3bce864f86e54ec289821342b090271488361841f8dd9))),1 sats/byte,pkh(3f4df7d840aee9abbe14e8f64d0677ccbb881342))
// We can now finalize the tx builder result from earlier with this finalizer
val unsignedTx: Transaction = finalizer.buildTx(builderResult)
// unsignedTx: Transaction = BaseTransaction(Int32Impl(2),Vector(TransactionInputImpl(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),EmptyScriptSignature,UInt32Impl(0))),Vector(TransactionOutput(5000 sats,pkh(5bc530a9388a51ba4b65d229246e579dcbc83f3c)), TransactionOutput(4775 sats,pkh(3f4df7d840aee9abbe14e8f64d0677ccbb881342))),UInt32Impl(0))
// We now turn to signing the unsigned transaction
// this contains all the information we need to
// validly sign the UTXO above
val utxoInfo = ScriptSignatureParams(inputInfo = inputInfo,
prevTransaction = creditingTx,
signers = Vector(privKey),
hashType =
HashType.sigHashAll)
// utxoInfo: ScriptSignatureParams[P2PKHInputInfo] = ScriptSignatureParams(P2PKHInputInfo(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),10000 sats,ECPublicKey(02f6ec180dbc3588690aa3bce864f86e54ec289821342b090271488361841f8dd9)),BaseTransaction(Int32Impl(1),Vector(),Vector(TransactionOutput(10000 sats,pkh(241ad4894d3d6ed55d6dee9087a13cef8bbe3fb6))),UInt32Impl(0)),Vector(Masked(ECPrivateKey)),SIGHASH_ALL(1))
// all of the UTXO spending information, since we only have
// one input, this is just one element
val utxoInfos: Vector[ScriptSignatureParams[InputInfo]] = Vector(utxoInfo)
// utxoInfos: Vector[ScriptSignatureParams[InputInfo]] = Vector(ScriptSignatureParams(P2PKHInputInfo(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),10000 sats,ECPublicKey(02f6ec180dbc3588690aa3bce864f86e54ec289821342b090271488361841f8dd9)),BaseTransaction(Int32Impl(1),Vector(),Vector(TransactionOutput(10000 sats,pkh(241ad4894d3d6ed55d6dee9087a13cef8bbe3fb6))),UInt32Impl(0)),Vector(Masked(ECPrivateKey)),SIGHASH_ALL(1)))
// Yay! Now we use the RawTxSigner object to sign the tx.
// The 'sign' method is going produce a validly signed transaction
// This is going to iterate through each of the UTXOs and use
// the corresponding ScriptSignatureParams to produce a validly
// signed input. This UTXO has:
// 1: one input
// 2: outputs (destination and change outputs)
// 3: a fee rate of 1 satoshi/byte
val signedTx: Transaction =
RawTxSigner.sign(
utx = unsignedTx,
utxoInfos = utxoInfos,
expectedFeeRate = feeRate
)
// signedTx: Transaction = BaseTransaction(Int32Impl(2),Vector(TransactionInputImpl(TransactionOutPoint(da61ba5a6f0fc0119e42f8887d55999352ecc6438a0e17f3081c434553d7c141:0),P2PKHScriptSignature(ECPublicKeyBytes(ByteVector(33 bytes, 0x02f6ec180dbc3588690aa3bce864f86e54ec289821342b090271488361841f8dd9)), ECDigitalSignature(304402201e30e76d8cc7cbb665bb06bca30727bd5ab2f6a1091b43025203c720d4d33b72022005e231de0e476d4d8333e78cab1d792fa08f889cc7d7c593add104b099dfb72f01)),UInt32Impl(0))),Vector(TransactionOutput(5000 sats,pkh(5bc530a9388a51ba4b65d229246e579dcbc83f3c)), TransactionOutput(4775 sats,pkh(3f4df7d840aee9abbe14e8f64d0677ccbb881342))),UInt32Impl(0))
```
```scala
signedTx.inputs.length
// res2: Int = 1
signedTx.outputs.length
// res3: Int = 2
//remember, you can call .hex on any bitcoin-s data structure to get the hex representation!
signedTx.hex
// res4: String = 020000000141c1d75345431c08f3170e8a43c6ec529399557d88f8429e11c00f6f5aba61da000000006a47304402201e30e76d8cc7cbb665bb06bca30727bd5ab2f6a1091b43025203c720d4d33b72022005e231de0e476d4d8333e78cab1d792fa08f889cc7d7c593add104b099dfb72f012102f6ec180dbc3588690aa3bce864f86e54ec289821342b090271488361841f8dd9000000000288130000000000001976a9145bc530a9388a51ba4b65d229246e579dcbc83f3c88aca7120000000000001976a9143f4df7d840aee9abbe14e8f64d0677ccbb88134288ac00000000
```

View file

@ -0,0 +1,84 @@
---
id: version-1.9.8-musig
title: MuSig
original_id: musig
---
Bitcoin-S now has support for [MuSig](https://github.com/jonasnick/bips/blob/musig2/bip-musig2.mediawiki).
This module contains classes representing public `KeySet`s, MuSig nonces, and MuSig aggregate key tweaks, as well as utility functions for all MuSig computations.
The functions for aggregating key data are:
* `aggPubKey`
* This is a member of `KeySet` and returns the aggregate public key for this set of signers, including the tweaks provided. In most uses, a subsequent call to `schnorrPublicKey` is required for Bitcoin applications.
* `MuSigNoncePub.aggregate`
* Given a `Vector[MuSigNoncePub]` of the signer's nonces, returns the aggregate `MuSigNoncePub`. This aggregation can be done before the message, or even the `KeySet` is known.
The functions for signing and verification are:
* `MuSigUtil.sign`
* This function generates a MuSig partial signature using a private key and `MuSigNoncePriv`. This consists of a pair `(R, s)` where `R` is the aggregate nonce key (same for all signers) and `s` is the actual partial signature that needs to be shared.
* `MuSigUtil.partialSigVerify`
* This function validates a single partial signature against that signer's public key and `MuSigNoncePub`.
* `MuSigUtil.signAgg`
* This function aggregates all of the `s` values into a single valid `SchnorrDigitalSignature` (using the aggregate nonce key `R`).
Note that no new function is required for aggregate verification as `SchnorrPublicKey`'s `verify` function is to be used.
Lastly, it should be mentioned that `MuSigNoncePriv`s must be constructed using either `MuSigNoncePriv.gen` or `MuSigNoncePriv.genInternal` (the latter should only be used with 32 bytes of secure random entropy). These generation functions take as input any context information that is available at nonce generation time, namely your signing key, aggregate public key, message, and any extra bytes you may have available. Including these optional inputs improves the security of nonce generation (which must be absolutely secure).
The following code shows a two-party MuSig execution:
```scala
// Alice and Bob generate and exchange nonce data (new nonces for every sig)
val aliceNoncePriv = MuSigNoncePriv.gen()
val aliceNonce = aliceNoncePriv.toPublicNonces // Alice sends this to Bob
val bobNoncePriv = MuSigNoncePriv.gen()
val bobNonce = bobNoncePriv.toPublicNonces // Bob sends this to Alice
// The aggregate musig nonce can be computed from Alice's and Bob's
val aggMuSigNonce = MuSigNoncePub.aggregate(Vector(aliceNonce, bobNonce))
// Any party can (non-interactively) compute the aggregate public key
val pubKeys = Vector(alicePubKey, bobPubKey)
val keySet = KeySet(pubKeys, tweaks) // This is where you put MuSigTweaks
val aggPubKey = keySet.aggPubKey.schnorrPublicKey
// Alice generates a partial signature for the message
val (aliceR, aliceSig) =
MuSigUtil.sign(aliceNoncePriv, aggMuSigNonce, alicePrivKey, msg, keySet)
// Bob generates a partial signature for the message
val (bobR, bobSig) =
MuSigUtil.sign(bobNoncePriv, aggMuSigNonce, bobPrivKey, msg, keySet)
require(aliceR == bobR)
val R = aliceR
// Alice and Bob exchange and verify each other's sigs (s values)
require(
MuSigUtil.partialSigVerify(aliceSig,
aliceNonce,
aggMuSigNonce,
alicePubKey,
keySet,
msg))
require(
MuSigUtil.partialSigVerify(bobSig,
bobNonce,
aggMuSigNonce,
bobPubKey,
keySet,
msg))
// In the case that the aggregator is not Alice or Bob, R can be computed as follows
val R2 = SigningSession(aggMuSigNonce, keySet, msg).aggNonce
require(R2 == R)
// Finally, any party can aggregate the partial signatures
val sig = MuSigUtil.signAgg(Vector(aliceSig, bobSig), R)
// This signature can now be validated as a normal BIP340 Schnorr signature
require(aggPubKey.verify(msg, sig))
```

View file

@ -0,0 +1,65 @@
---
id: version-1.9.8-sign
title: Sign API
original_id: sign
---
### The [`Sign` API](/api/org/bitcoins/crypto/Sign)
This is the API we define to sign things with. It takes in an arbitrary byte vector and returns a `Future[ECDigitalSignature]`. The reason we incorporate `Future`s here is for extensibility of this API. We would like to provide implementations of this API for hardware devices, which need to be asynchrnous since they may require user input.
From [Sign.scala](/api/org/bitcoins/crypto/Sign):
```scala
import scodec.bits._
import org.bitcoins.crypto._
import scala.concurrent._
import scala.concurrent.duration._
trait Sign {
def signFunction: ByteVector => Future[ECDigitalSignature]
def signFuture(bytes: ByteVector): Future[ECDigitalSignature] =
signFunction(bytes)
def sign(bytes: ByteVector): ECDigitalSignature = {
Await.result(signFuture(bytes), 30.seconds)
}
def publicKey: ECPublicKey
}
```
The `ByteVector` that is input to the `signFunction` should be the hash that is output from [`TransactionSignatureSerializer`](/api/org/bitcoins/core/crypto/TransactionSignatureSerializer)'s `hashForSignature` method. Our in-memory [`BaseECKey`](/api/org/bitcoins/crypto/BaseECKey) types implement the `Sign` API.
If you wanted to implement a new `Sign` api for a hardware wallet, you can easily pass it into the `TxBuilder`/`Signer` classes to allow for you to use those devices to sign with Bitcoin-S.
This API is currently used to sign ordinary transactions with our [`Signer`](/api/org/bitcoins/core/wallet/signer/Signer)s. The `Signer` subtypes (i.e. `P2PKHSigner`) implement the specific functionality needed to produce a valid digital signature for their corresponding script type.
### The [`ExtSign`](/api/org/bitcoins/crypto/Sign) API.
An [ExtKey](/api/org/bitcoins/core/crypto/ExtKey) is a data structure that can be used to generate more keys from a parent key. For more information look at [hd-keys.md](../core/hd-keys.md)
You can sign with `ExtPrivateKey` the same way you could with a normal `ECPrivateKey`.
```scala
import org.bitcoins.core.hd._
import org.bitcoins.core.crypto._
val extPrivKey = ExtPrivateKey(ExtKeyVersion.SegWitMainNetPriv)
// extPrivKey: ExtPrivateKey = Masked(ExtPrivateKeyImpl)
extPrivKey.sign(DoubleSha256Digest.empty.bytes)
// res0: ECDigitalSignature = ECDigitalSignature(3045022100b52c5c6c2382dc72e76edb09718159f613c197973d72a8fce15b408ec9c3ff10022047238108a9acab87518704eade56a268c96afaeec418f78f505d0c80df817997)
val path = BIP32Path(Vector(BIP32Node(0,false)))
// path: BIP32Path = m/0
extPrivKey.sign(DoubleSha256Digest.empty.bytes,path)
// res1: ECDigitalSignature = ECDigitalSignature(304502210089529a60e72807932f8f1e9c3c3b2fc3a5805af0fc6012bf7a8bb09e5e426a82022037fcd0b630882f90e7d4ebd710f75f558d86b66e86368cf7c5e9cd1e8e458a85)
```
With `ExtSign`, you can use `ExtPrivateKey` to sign transactions inside of `TxBuilder` since `UTXOSpendingInfo` takes in `Sign` as a parameter.
You can also provide a `path` to use to derive a child `ExtPrivateKey`, and then sign with that child private key

View file

@ -0,0 +1,127 @@
---
id: version-1.9.8-getting-started
title: Intro and Getting Started
original_id: getting-started
---
## Philosophy
Bitcoin-S is a loosely coupled set of cryptocurrency libraries for the JVM. They work well together, but also can be used
independently. This project's goal is NOT to be a full node implementation, rather a set of scalable cryptocurrency libraries
that use industry standard tools (rather than esoteric tech often found in cryptocurrency) where possible to make the lives of professional
software engineers, security engineers, devops engineers and accountants easier.
We are rapidly iterating on development with the goal of getting to a set of stable APIs that only change when the underlying bitcoin protocol changes.
If you are a professional working a cryptocurrency business and
have feedback on how to make your lives easier, please reach out on [slack](https://join.slack.com/t/suredbits/shared_invite/zt-eavycu0x-WQL7XOakzQo8tAy7jHHZUw),
[gitter](https://gitter.im/bitcoin-s-core/) or [twitter](https://twitter.com/Chris_Stewart_5/)!
## Getting prebuilt artifacts
### Java binaries
<details>
#### Latest release
Please see the release page on github, you can find it [here](https://github.com/bitcoin-s/bitcoin-s/releases)
#### Master builds
We build installers for mac, linux and windows everytime a PR is merged to master.
You can find the latest builds at this link:
https://github.com/bitcoin-s/bitcoin-s/actions/workflows/release.yml
Here is what the installers look like
![installers](/img/doc-imgs/github-artifacts.png)
</details>
### Docker
<details>
We publish docker images to docker hub on every PR merge and tag on github.
You can obtain the images for both the app server and oracle server on these
docker hub repos
[bitcoin-s-server docker hub repo](https://hub.docker.com/r/bitcoinscala/bitcoin-s-server/tags?page=1&ordering=last_updated)
[bitcoin-s-oracle-server docker hub repo](https://hub.docker.com/r/bitcoinscala/bitcoin-s-oracle-server/tags?page=1&ordering=last_updated)
</details>
### Library jars
<details>
Add this to your `build.sbt`:
```scala
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-bitcoind-rpc" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-core" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-chain" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-dlc-oracle" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-eclair-rpc" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-fee-provider" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-key-manager" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-lnd-rpc" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-node" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-oracle-explorer-client" % "1.9.7"
libraryDependencies += "org.bitcoin-s" % "bitcoin-s-secp256k1jni" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-testkit-core" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-testkit" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-wallet" % "1.9.7"
libraryDependencies += "org.bitcoin-s" %% "bitcoin-s-zmq" % "1.9.7"
```
### Nightly builds
You can also run on the bleeding edge of Bitcoin-S, by
adding a snapshot build to your `build.sbt`. The most
recent snapshot published is `1.9.7-468-ad4bfdd5-SNAPSHOT`.
To fetch snapshots, you will need to add the correct
resolver in your `build.sbt`:
```sbt
resolvers += Resolver.sonatypeRepo("snapshots")
```
The official maven repo for releases is
https://repo1.maven.org/maven2/org/bitcoin-s/
The repo for snapshots, which are published after everytime something is merged to master:
https://oss.sonatype.org/content/repositories/snapshots/org/bitcoin-s/
</details>
## Building JARs yourself
Please see [our setup docs](getting-setup.md)
## If you want to setup Bitcoin-S locally for development
Please see [our setup docs](getting-setup.md)

View file

@ -0,0 +1,124 @@
---
id: version-1.9.8-key-manager
title: Key Manager
original_id: key-manager
---
### Key Manager
The key manager module's goal is to encapsulate all private key interactions with the [wallet](../wallet/wallet.md) project.
As of this writing, there is only one type of `KeyManager` - [`BIP39KeyManager`](/api/org/bitcoins/keymanager/bip39/BIP39KeyManager).
The [`BIP39KeyManager`](/api/org/bitcoins/keymanager/bip39/BIP39KeyManager) stores a [`MnemonicCode`](/api/org/bitcoins/core/crypto/MnemonicCode) on disk which can be decrypted and used as a hot wallet.
Over the long run, we want to make it so that the wallet project needs to communicate with the key-manager to access private keys.
This means that ALL SIGNING should be done inside of the key-manager, and private keys should not leave the key manager.
This makes it easier to reason about the security characteristics of our private keys, and a way to provide a uniform interface for alternative key storage systems (hsm, cloud based key storage, etc) to be plugged into the bitcoin-s library.
#### Creating a key manager
The first thing you need create a key manager is some entropy.
A popular way for bitcoin wallet's to represent entropy is [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) which you [can use in bitcoin-s](/api/org/bitcoins/core/crypto/BIP39Seed)
You can generate a `MnemonicCode` in bitcoin-s with the following code
```scala
import org.bitcoins.core.crypto._
//get 256 bits of random entropy
val entropy = MnemonicCode.getEntropy256Bits
// entropy: scodec.bits.BitVector = BitVector(256 bits, 0x15acbeb8af0bea24f4eb1de1f17e0fbc063a14b64de00d4fb0775593865ce26d)
val mnemonic = MnemonicCode.fromEntropy(entropy)
// mnemonic: MnemonicCode = Masked(MnemonicCodeImpl)
//you can print that mnemonic seed with this
println(mnemonic.words)
// Vector(between, grass, purchase, fun, salt, bar, squirrel, glove, tiger, message, loop, job, glove, apart, summer, rose, ask, laugh, build, private, debris, common, meadow, relief)
```
Now that we have a `MnemonicCode` that was securely generated, we need to now create `KeyManagerParams` which tells us how to generate
generate specific kinds of addresses for wallets.
`KeyManagerParams` takes 3 parameters:
1. `seedPath` there is where we store the `MnemonicCode` on your file system
2. [`purpose`](/api/org/bitcoins/core/hd/HDPurpose) which represents what type of utxo this `KeyManager` is associated with. The specification for this is in [BIP43](https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki)
3. [`network`](/api/org/bitcoins/core/config/NetworkParameters) what cryptocurrency network this key manager is associated with
This controls how the root key is defined. The combination of `purpose` and `network` determine how the root `ExtKey` is serialized. For more information on how this works please see [hd-keys](../core/hd-keys.md)
Now we can construct a native segwit key manager for the regtest network!
```scala
//this will create a temp directory with the prefix 'key-manager-example` that will
//have a file in it called "encrypted-bitcoin-s-seed.json"
val seedPath = Files.createTempDirectory("key-manager-example").resolve(WalletStorage.ENCRYPTED_SEED_FILE_NAME)
// seedPath: Path = /tmp/key-manager-example18108531960447296408/encrypted-bitcoin-s-seed.json
//let's create a native segwit key manager
val purpose = HDPurposes.SegWit
// purpose: HDPurpose = m/84'
//let's choose regtest as our network
val network = RegTest
// network: RegTest.type = RegTest
val kmParams = KeyManagerParams(seedPath, purpose, network)
// kmParams: KeyManagerParams = KeyManagerParams(/tmp/key-manager-example18108531960447296408/encrypted-bitcoin-s-seed.json,m/84',RegTest)
val aesPasswordOpt = Some(AesPassword.fromString("password"))
// aesPasswordOpt: Some[AesPassword] = Some(Masked(AesPassword))
val km = BIP39KeyManager.initializeWithMnemonic(aesPasswordOpt, mnemonic, None, kmParams)
// km: Either[KeyManagerInitializeError, BIP39KeyManager] = Right(org.bitcoins.keymanager.bip39.BIP39KeyManager@3d6ad96a)
val rootXPub = km.right.get.getRootXPub
// rootXPub: ExtPublicKey = vpub5SLqN2bLY4WeYMKogZn5Jo4dbbZH65XGBjudJDtMSVmn5q838fy7TVok1PAUcZC19kQaEvyRADn2KDMYaB1KC7PRaWxKc9Bw4Lc1YqYMLfQ
println(rootXPub)
// vpub5SLqN2bLY4WeYMKogZn5Jo4dbbZH65XGBjudJDtMSVmn5q838fy7TVok1PAUcZC19kQaEvyRADn2KDMYaB1KC7PRaWxKc9Bw4Lc1YqYMLfQ
```
Which should print something that looks like this
`vpub5SLqN2bLY4WeXxMqwJHJFBEwxSscGB2uDUnsTS3edVjZEwTrQDFDNqoR2xLqARQPabGaXsHSTenTRcqm2EnB9MpuC4vSk3LqSgNmGGZtuq7`
which is a native segwit `ExtPubKey` for the regtest network!
You can always change the `network` or `purpose` to support different things. You do _not_ need to initialize the key manager
again after initializing it once. You can use the same `mnemonic` for different networks, which you control `KeyManagerParams`.
```scala
//let's create a nested segwit key manager for mainnet
val mainnetKmParams = KeyManagerParams(seedPath, HDPurposes.SegWit, MainNet)
// mainnetKmParams: KeyManagerParams = KeyManagerParams(/tmp/key-manager-example18108531960447296408/encrypted-bitcoin-s-seed.json,m/84',MainNet)
//we do not need to all `initializeWithMnemonic()` again as we have saved the seed to dis
val mainnetKeyManager = BIP39KeyManager.fromMnemonic(mnemonic, mainnetKmParams, None, Instant.now, false)
// mainnetKeyManager: BIP39KeyManager = org.bitcoins.keymanager.bip39.BIP39KeyManager@5e633ea0
val mainnetXpub = mainnetKeyManager.getRootXPub
// mainnetXpub: ExtPublicKey = zpub6jftahH18ngZwY6H1zva99SeHU94rZVFrBzWRoTtxXHJJENx9JdMwkSJ6CzpcBognJsoEqMezsCDrMooSxfNP47q3sk1wnTt9Erb7Cp46V1
println(mainnetXpub)
// zpub6jftahH18ngZwY6H1zva99SeHU94rZVFrBzWRoTtxXHJJENx9JdMwkSJ6CzpcBognJsoEqMezsCDrMooSxfNP47q3sk1wnTt9Erb7Cp46V1
```
Which gives us something that looks like this
`zpub6jftahH18ngZw98KGjRo5XcxeKTQ2eztsvskb1dC9XF5TLimQquTs6Ry7nBBA425D9joXmfgJJCexmJ1u2SELJZJfRi95gcnXadLpZzYb5c`
which is a p2sh wrapped segwit `ExtPubKey` for the bitcoin main network!
#### Creating a key manager from existing mnemonic
To create a `KeyManager` from existing mnemonic you need to specify the `seedPath` and then construct the `KeyManagerParams` that you would like.
Finally you call `KeyManager.fromParams()` that reads the mnemonic from disk and create's the key manager

View file

@ -0,0 +1,85 @@
---
id: version-1.9.8-node-api title: Node API
title: node-api title: Node API
original_id: node-api title: Node API
---
### NodeAPI
The NodeApi is how the wallet project retrieves relevant node data like blocks. This allows the wallet for example to
retrieve blocks for finding its relevant transactions.
Since this is an API it can be hooked up to the `node` module of bitcoin-s but it can also be linked to any other
implementation of your choosing. This allows you to use the bitcoin-s wallet in any schema that you want.
The functions that the NodeApi supports are:
```scala
trait NodeApi {
/** Request the underlying node to download the given blocks from its peers and feed the blocks to [[org.bitcoins.node.NodeCallbacks]] */
def downloadBlocks(blockHashes: Vector[DoubleSha256DigestBE]): Future[Unit]
}
```
## Downloading blocks with bitcoind
As an example, we will show you how to use the `NodeApi` and bitcoind to download blocks for a wallet.
```scala
implicit val system: ActorSystem = ActorSystem(s"node-api-example")
implicit val ec: ExecutionContextExecutor = system.dispatcher
implicit val walletConf: WalletAppConfig =
BitcoinSTestAppConfig.getNeutrinoTestConfig().walletConf
// let's use a helper method to get a v19 bitcoind
// and a ChainApi
val instance = BitcoindInstanceLocal.fromConfigFile(BitcoindConfig.DEFAULT_CONF_FILE)
val bitcoind = BitcoindRpcClient(instance)
val chainApi = MockChainQueryApi.mock
val aesPasswordOpt = Some(AesPassword.fromString("password"))
// This function can be used to create a callback for when our node api calls downloadBlocks,
// more specifically it will call the function every time we receive a block, the returned
// NodeCallbacks will contain the necessary items to initialize the callbacks
def createCallback(processBlock: Block => Future[Unit]): NodeCallbacks = {
lazy val onBlock: OnBlockReceived = { block =>
processBlock(block)
}
NodeCallbacks(onBlockReceived = Vector(onBlock))
}
// Here is a super simple example of a callback, this could be replaced with anything, from
// relaying the block on the network, finding relevant wallet transactions, verifying the block,
// or writing it to disk
val exampleProcessBlock = (block: Block) =>
Future.successful(println(s"Received block: ${block.blockHeader.hashBE}"))
val exampleCallback = createCallback(exampleProcessBlock)
// Here is where we are defining our actual node api, Ideally this could be it's own class
// but for the examples sake we will keep it small.
val nodeApi = new NodeApi {
override def broadcastTransactions(transactions: Vector[Transaction]): Future[Unit] = {
FutureUtil.sequentially(transactions)(bitcoind.sendRawTransaction(_)).map(_ => ())
}
override def downloadBlocks(
blockHashes: Vector[DoubleSha256DigestBE]): Future[Unit] = {
val blockFs = blockHashes.map(hash => bitcoind.getBlockRaw(hash))
Future.sequence(blockFs).map(_ => ())
}
override def getConnectionCount: Future[Int] = bitcoind.getConnectionCount
}
// Finally, we can initialize our wallet with our own node api
val wallet =
Wallet(nodeApi = nodeApi, chainQueryApi = chainApi, feeRateApi = ConstantFeeRateProvider(SatoshisPerVirtualByte.one))
// Then to trigger the event we can run
val exampleBlock = DoubleSha256DigestBE(
"000000000010dc23dc0d5acad64667a7a2b3010b6e02da4868bf392c90b6431d")
wallet.nodeApi.downloadBlocks(Vector(exampleBlock))
```

View file

@ -0,0 +1,135 @@
---
id: version-1.9.8-node
title: Light Client
original_id: node
---
Bitcoin-s has node module that allows you to connect to the p2p network.
### Neutrino Node
Bitcoin-s has experimental support for neutrino which is a new lite client proposal on the bitcoin p2p network. You can
read more about how neutrino works [here](https://suredbits.com/neutrino-what-is-it-and-why-we-need-it/). At this time,
bitcoin-s only supports connecting to one trusted peer.
#### Limitations
Currently, the node does not have an active mempool.
It is only aware of transactions it broadcasts and ones confirmed in blocks.
#### Callbacks
Bitcoin-S support call backs for the following events that happen on the bitcoin p2p network:
1. onTxReceived
2. onBlockReceived
3. onMerkleBlockReceived
4. onCompactFilterReceived
That means every time one of these events happens on the p2p network, we will call your callback
so that you can be notified of the event. These callbacks will be run after the message has been
recieved and will execute sequentially. If any of them fail an error log will be output and the remainder of the callbacks will continue.
Let's make an easy one
#### Example
Here is an example of constructing a neutrino node and registering a callback so you can be notified of an event.
To run the example, we need a bitcoind binary that has neutrino support.
Bitcoin Core only has p2p neutrino support as of version 0.21.0.
You will need to use a version of Bitcoin Core at least as old as 0.21.0.
For your node to be able to service these filters you will need set
`blockfilterindex=1` and `peerblockfilters=1` in your `bitcoin.conf` file.
```scala
implicit val system = ActorSystem(s"node-example")
implicit val ec = system.dispatcher
//we also require a bitcoind instance to connect to
//so let's start one (make sure you ran 'sbt downloadBitcoind')
val instance = BitcoindRpcTestUtil.instance(versionOpt = Some(BitcoindVersion.newest))
val p2pPort = instance.p2pPort
val bitcoindF = BitcoindRpcTestUtil.startedBitcoindRpcClient(Some(instance), Vector.newBuilder)
//contains information on how to connect to bitcoin's p2p info
val peerF = bitcoindF.flatMap(b => NodeUnitTest.createPeer(b))
// set a data directory
val prefix = s"node-example-${System.currentTimeMillis()}"
val datadir = Files.createTempDirectory(prefix)
val tmpDir = BitcoinSTestAppConfig.tmpDir()
// set the current network to regtest
val config = ConfigFactory.parseString {
s"""
| bitcoin-s {
| network = regtest
| node {
| mode = neutrino # neutrino, spv
|
| peers = ["127.0.0.1:$p2pPort"] # a list of peer addresses in form "hostname:portnumber"
| # (e.g. "neutrino.testnet3.suredbits.com:18333")
| # Port number is optional, the default value is 8333 for mainnet,
| # 18333 for testnet and 18444 for regtest.
| }
| }
|""".stripMargin
}
implicit val appConfig = BitcoinSAppConfig(datadir, Vector(config))
implicit val chainConfig = appConfig.chainConf
implicit val nodeConfig = appConfig.nodeConf
val initNodeF = nodeConfig.start()
//yay! All setup done, let's create a node and then start it!
val nodeF = for {
peer <- peerF
} yield {
NeutrinoNode(
walletCreationTimeOpt = None, //you can set this to only sync compact filters after the timestamp
paramPeers = Vector(peer),
nodeConfig = nodeConfig,
chainConfig = chainConfig,
actorSystem = system)
}
//let's start it
val startedNodeF = nodeF.flatMap(_.start())
//let's make a simple callback that print's the
//blockhash everytime we receive a block on the network
val blockReceivedFunc: OnBlockReceived = { block: Block =>
Future.successful(
println(s"Received blockhash=${block.blockHeader.hashBE}"))
}
// Create callback
val nodeCallbacks = NodeCallbacks.onBlockReceived(blockReceivedFunc)
// Add call to our node's config
nodeConfig.addCallbacks(nodeCallbacks)
//let's test it out by generating a block with bitcoind!
val genBlockF = for {
bitcoind <- bitcoindF
addr <- bitcoind.getNewAddress
hashes <- bitcoind.generateToAddress(1,addr)
} yield hashes
//you should see our callback print a block hash
//when running this code
//cleanup
val cleanupF = for {
_ <- genBlockF
bitcoind <- bitcoindF
node <- startedNodeF
x = NeutrinoNodeConnectedWithBitcoind(node.asInstanceOf[NeutrinoNode],bitcoind)
_ <- NodeUnitTest.destroyNodeConnectedWithBitcoind(x)
} yield ()
Await.result(cleanupF, 60.seconds)
```

View file

@ -0,0 +1,135 @@
---
id: version-1.9.8-rpc-bitcoind
title: bitcoind/Bitcoin Core
original_id: rpc-bitcoind
---
## Downloading bitcoind
The Bitcoin Core RPC client in Bitcoin-S currently supports the Bitcoin Core
- 0.16
- 0.17
- 0.18
- 0.19
- 0.20
- 0.21
- 22
- 23
version lines. It can be set up to work with both local and remote Bitcoin Core servers.
You can fetch them using bitcoin-s by running the following sbt command. If you already have bitcoind installed on your machine, you can skip this step.
```bash
sbt downloadBitcoind
```
The binaries will be stored in `~/.bitcoin-s/binaries/bitcoind/`
## Connecting to a local `bitcoind` instance
### Getting started quickly, with default options:
```scala
implicit val ec: ExecutionContext = ExecutionContext.global
implicit val system = ActorSystem("System")
// this reads authentication credentials and
// connection details from the default data
// directory on your platform
val client = BitcoindRpcClient.fromDatadir(binary=new File("/path/to/bitcoind"), datadir=new File("/path/to/bitcoind-datadir"))
val balance: Future[Bitcoins] = for {
_ <- client.start()
balance <- client.getBalance
} yield balance
```
## Multi-wallet `bitcoind` instances
When using the `bitcoind` with multiple wallets you will need to specify the wallet's name.
To do so the wallet rpc functions have an optional `walletName` parameter.
```scala
implicit val ec: ExecutionContext = ExecutionContext.global
implicit val system = ActorSystem("System")
val client = BitcoindRpcClient.fromDatadir(binary=new File("/path/to/bitcoind"), datadir=new File("/path/to/bitcoind-datadir"))
for {
_ <- client.start()
_ <- client.walletPassphrase("mypassword", 10000, Some("walletName"))
balance <- client.getBalance("walletName")
} yield balance
```
## Connecting to a remote `bitcoind`
First, we create a secure connection to our `bitcoind` instance by setting
up a SSH tunnel:
```bash
ssh -L 8332:localhost:8332 my-cool-user@my-cool-website.com
```
> Note: the port number '8332' is the default for mainnet. If you want to
> connect to a testnet `bitcoind`, the default port is '18332'
Now that we have a secure connection between our remote `bitcoind`, we're
ready to create the connection with our RPC client
```scala
implicit val ec: ExecutionContext = ExecutionContext.global
implicit val system = ActorSystem("System")
val username = "FILL_ME_IN" //this username comes from 'rpcuser' in your bitcoin.conf file
val password = "FILL_ME_IN" //this password comes from your 'rpcpassword' in your bitcoin.conf file
val authCredentials = BitcoindAuthCredentials.PasswordBased(
username = username,
password = password
)
val bitcoindInstance = {
BitcoindInstanceLocal(
network = MainNet,
uri = new URI(s"http://localhost:${MainNet.port}"),
rpcUri = new URI(s"http://localhost:${MainNet.rpcPort}"),
authCredentials = authCredentials
)
}
val rpcCli = BitcoindRpcClient(bitcoindInstance)
rpcCli.getBalance.onComplete { case balance =>
println(s"Wallet balance=${balance}")
}
```
## Error handling
All errors returned by Bitcoin Core are mapped to a corresponding
[`BitcoindException`](https://github.com/bitcoin-s/bitcoin-s/blob/master/bitcoind-rpc/src/main/scala/org/bitcoins/rpc/BitcoindException.scala).
These exceptions contain an error code and a message. `BitcoindException` is a sealed
trait, which means you can easily pattern match exhaustively. Of course, other errors
could also happen: network errors, stack overflows or out-of-memory errors. The provided
class is only intended to cover errors returned by Bitcoin Core. An example of how error
handling could look:
```scala
implicit val ec = ExecutionContext.global
// let's assume you have an already running client,
// so there's no need to start this one
val cli = BitcoindRpcClient.fromDatadir(binary=new File("/path/to/bitcoind"), datadir=new File("/path/to/bitcoind-datadir"))
// let's also assume you have a bitcoin address
val address: BitcoinAddress = BitcoinAddress("bc1qm8kec4xvucdgtzppzvvr2n6wp4m4w0k8akhf98")
val txid: Future[DoubleSha256DigestBE] =
cli.sendToAddress(address, 3.bitcoins).recoverWith {
case BitcoindWalletException.UnlockNeeded(_) =>
cli.walletPassphrase("my_passphrase", 60).flatMap { _ =>
cli.sendToAddress(address, 3.bitcoins)
}
}
```

View file

@ -0,0 +1,60 @@
---
id: version-1.9.8-lnd-rpc
title: LND
original_id: lnd-rpc
---
This is an RPC client for [LND](https://github.com/LightningNetwork/lnd). It assumes that a bitcoind instance is running.
Currently, this RPC client is written for [v0.17.3](https://github.com/lightningnetwork/lnd/releases/tag/v0.17.3-beta) version of LND.
## Configuration of LND
Please see the [sample configuration for LND](https://github.com/lightningnetwork/lnd/blob/v0.17.3-beta/sample-lnd.conf).
You can find the configuration we use for our testing infrastructure for lnd [here](https://github.com/bitcoin-s/bitcoin-s/blob/656e0928bf1bf4f511f60dec625699b454f29a1f/testkit/src/main/scala/org/bitcoins/testkit/lnd/LndRpcTestUtil.scala#L90).
## Starting LND
You need to download the binaries from the [LND's github](https://github.com/lightningnetwork/lnd/releases/tag/v0.17.3-beta).
To run lnd by unzipping the `lnd-linux-amd64-v0.17.3-beta.tar.gz` (or whichever platform you are on) and then running
```bash
$ ./lnd-linux-amd64-v0.17.3-beta/lnd
```
If you wish to start lnd from the RPC client, you can construct a [`LndRpcClient.binary`](https://github.com/bitcoin-s/bitcoin-s/blob/656e0928bf1bf4f511f60dec625699b454f29a1f/lnd-rpc/src/main/scala/org/bitcoins/lnd/rpc/LndRpcClient.scala#L35) field set
We will default to using the `binary` field first when trying to start the jar, and the fallback to the default datadir (`~/.lnd`).
Here is an example of how to start lnd:
```scala
implicit val system = ActorSystem(s"lnd-rpc-${System.currentTimeMillis}")
implicit val ec = system.dispatcher
val datadirPath = Paths.get("path", "to", "datadir")
val binaryPath = Paths.get("path", "to", "lnd-linux-amd64-v0.17.3-beta", "lnd")
val instance = LndInstanceLocal.fromDataDir(datadirPath.toFile)
val client = new LndRpcClient(instance, Some(binaryPath.toFile))
val startedF = client.start()
for {
lnd <- startedF
info <- lnd.getInfo
} yield {
println(s"Lnd info: $info")
}
```
### Updating to a new LND version
The lnd rpc module uses lnd's gRPC. This means when updating to the latest version, the `.proto` files will need to be updated.
Bitcoin-S stores them in [lnd-rpc/src/main/protobuf](https://github.com/bitcoin-s/bitcoin-s/tree/master/lnd-rpc/src/main/protobuf).
You can find the files to copy from LND [here](https://github.com/lightningnetwork/lnd/tree/master/lnrpc).
After updating the `proto` files you can run `sbt compile` and this will generate the corresponding class files, this should then give
compile warnings for changed rpc functions.

View file

@ -0,0 +1,92 @@
---
id: version-1.9.8-secp256k1
title: Secp256k1
original_id: secp256k1
---
[Libsecp256k1](https://github.com/bitcoin-core/secp256k1) is used to preform cryptographic operations on the secp256k1 curve.
This is the curve that bitcoin uses. There is a _signficant_ speedup when using this library compared to java crypto libraries
like bouncy castle.
In bitcoin-s, we support native binaries for libsecp256k1
1. [linux 32 bit](../../secp256k1jni/natives/linux_32)
2. [linux 64 bit](../../secp256k1jni/natives/linux_64)
3. [mac osx 64 bit](../../secp256k1jni/natives/osx_64)
4. [windows 64 bit](../../secp256k1jni/natives/windows_64)
Bitcoin-s uses a zero dependency library called [`native-lib-loader`](https://github.com/scijava/native-lib-loader).
That does the appropriate loading of the library onto your classpath to be accessed.
### Using libsecp256k1
To tell if you have access to libsecp256k1 you can do the following
```scala
val isEnabled = org.bitcoin.Secp256k1Context.isEnabled()
println(s"Secp256k1Context.isEnabled=${isEnabled}")
```
If libsecp256k1 is enabled, you can use [NativeSecp256k1](/api/org/bitcoin/NativeSecp256k1)
with static method defined in the class.
```scala
val privKey = ECPrivateKey.freshPrivateKey
val pubKey = privKey.publicKey
val dataToSign = DoubleSha256Digest.empty
val signature = NativeSecp256k1.sign(dataToSign.bytes.toArray, privKey.bytes.toArray)
val verify = NativeSecp256k1.verify(dataToSign.bytes.toArray, signature, pubKey.bytes.toArray)
println(s"Verified with NativeSecp256k1 signature=${verify}")
//you can also just directly sign with the ECKey interface:
val signature2 = privKey.sign(dataToSign)
val verified2 = pubKey.verify(dataToSign, signature2)
println(s"Verified with NativeSecp256k1 again=${verified2}")
```
### When libsecp256k1 isn't available, or you want to turn it off
There are two reasons you wouldn't want to use libsecp256k1
1. You don't trust the pre-compiled binaries we are using
2. Your OS/arch is not supported
There are two ways you can circumvent libsecp256k1
1. Set `DISABLE_SECP256K1=true` in your environment variables. This will force `CryptoContext.default` to return false which will make Bitcoin-S act like `Secp256k1Context.isEnabled()` has returned false.
2. Call Bouncy castle methods in `ECKey`.
Here is an example of calling bouncy castle methods in `ECKey`
```scala
val privKey = ECPrivateKey.freshPrivateKey
// privKey: ECPrivateKey = Masked(ECPrivateKey)
// calls bouncy castle indirectly via CryptoContext
val publicKey = privKey.publicKey
// publicKey: ECPublicKey = ECPublicKey(034a31c9db5f65304bf9024ae116ba6e6ecca73de32869bcb4ace2f3c0e0490f3d)
val dataToSign = DoubleSha256Digest.empty
// dataToSign: DoubleSha256Digest = DoubleSha256Digest(0000000000000000000000000000000000000000000000000000000000000000)
// calls bouncy castle indirectly via CryptoContext
val signature = privKey.sign(dataToSign.bytes)
// signature: ECDigitalSignature = ECDigitalSignature(30440220418c3218dc209f98871be65c4deba4061e8ef2beefd0cc0b71e84022954c248902205f8361ac18f8b499bef321c8bc17e5f3a3ccb68ad8ed1cd6a7f44264befebf22)
// calls bouncy castle indirectly via CryptoContext
val verified = publicKey.verify(dataToSign.bytes, signature)
// verified: Boolean = true
println(s"Verified with bouncy castle=${verified}")
// Verified with bouncy castle=true
```
### Building libsecp256k1
[See instructions here](add-to-jni.md#adding-to-bitcoin-s)

View file

@ -0,0 +1,169 @@
---
id: version-1.9.8-testkit
title: Testkit
original_id: testkit
---
## Philosophy of Testkit
The high level of of the bitcoin-s testkit is to mimic and provide functionality to test 3rd party applications.
There are other examples of these in the Scala ecosystem like the `akka-testkit` and `slick-testkit`.
We use this testkit to test bitcoin-s it self.
### Testkit for bitcoind
This gives the ability to create and destroy `bitcoind` on the underlying operating system to test against.
Our [BitcoindRpcClient](/api/org/bitcoins/rpc/client/common/BitcoindRpcClient) is tested with the functionality provided in the testkit.
A quick example of a useful utility method is [BitcoindRpcTestUtil.startedBitcoindRpcClient()](/api/org/bitcoins/testkit/rpc/BitcoindRpcTestUtil).
This spins up a bitcoind regtest instance on machine and generates 101 blocks on that node.
This gives you the ability to start spending money immediately with that bitcoind node.
```scala
implicit val system = ActorSystem("bitcoind-testkit-example")
implicit val ec = system.dispatcher
//pick our bitcoind version we want to spin up
val bitcoindV = BitcoindVersion.newest
//create an instance
val instance = BitcoindRpcTestUtil.instance(versionOpt = Some(bitcoindV))
//now let's create an rpc client off of that instance
val bitcoindRpcClientF = BitcoindRpcTestUtil.startedBitcoindRpcClient(Some(instance), Vector.newBuilder)
//yay! it's started. Now you can run tests against this.
//let's just grab the block count for an example
val blockCountF = for {
bitcoind <- bitcoindRpcClientF
count <- bitcoind.getBlockCount
} yield {
//run a test against the block count
assert(count > 0, s"Block count was not more than zero!")
}
//when you are done, don't forget to destroy it! Otherwise it will keep running on the underlying os
val stoppedF = for {
rpc <- bitcoindRpcClientF
_ <- blockCountF
stopped <- BitcoindRpcTestUtil.stopServers(Vector(rpc))
} yield stopped
```
For more information on how the bitcoind rpc client works, see our [bitcoind rpc docs](../rpc/bitcoind.md)
#### Caching bitcoind in test cases
When doing integration tests with bitcoind, you likely do not want to spin up a
new bitcoind for _every_ test that is run.
Not to fear, when using `testkit` you can use our bitcoind fixtures for your unit tests!
These will only spin up on bitcoind per test suite, rather than one bitcoind per test.
We currently have two types of fixtures available to users of this dependency
1. [Connected pairs of bitcoind nodes](https://github.com/bitcoin-s/bitcoin-s/blob/eaac9c154c25f3bd76615ea2151092f06df6bdb4/testkit/src/main/scala/org/bitcoins/testkit/rpc/BitcoindFixtures.scala#L282)
2. [Bitcoind nodes with funded wallets](https://github.com/bitcoin-s/bitcoin-s/blob/eaac9c154c25f3bd76615ea2151092f06df6bdb4/testkit/src/main/scala/org/bitcoins/testkit/rpc/BitcoindFixtures.scala#L161)
If you mixin either of those traits for your test, you will now have access to the corresponding fixture.
You can find an examples of how to use these two test fixtures
1. [Example of using a connected pair of nodes in test suite](https://github.com/bitcoin-s/bitcoin-s/blob/32a6db930bdf849a94d92cd1de160b87845ab168/bitcoind-rpc-test/src/test/scala/org/bitcoins/rpc/common/WalletRpcTest.scala#L37)
2. [Example of using a bitcoind with funded wallet in test suite](https://github.com/bitcoin-s/bitcoin-s/blob/eaac9c154c25f3bd76615ea2151092f06df6bdb4/testkit/src/main/scala/org/bitcoins/testkit/rpc/BitcoindFixtures.scala#L161)
### Testkit for eclair
We have similar utility methods for eclair. Eclair's testkit requires a bitcoind running (which we can spin up thanks to our bitcoind testkit).
Here is an example of spinning up an eclair lightning node, that is connected to a bitcoind and testing your lightning application.
Make sure to run `sbt downloadBitcoind downloadEclair` before running this so you have access to the underlying eclair binares
```scala
//Steps:
//1. Open and confirm channel on the underlying blockchain (regtest)
//2. pay an invoice
//3. Await until the payment is processed
//4. assert the node has received the payment
//5. cleanup
implicit val system = ActorSystem("eclair-testkit-example")
implicit val ec = system.dispatcher
//we need a bitcoind to connect eclair nodes to
lazy val bitcoindRpcClientF: Future[BitcoindRpcClient] = {
for {
cli <- EclairRpcTestUtil.startedBitcoindRpcClient()
// make sure we have enough money to open channels
address <- cli.getNewAddress
_ <- cli.generateToAddress(200, address)
} yield cli
}
//let's create two eclair nodes now
val clientF = for {
bitcoind <- bitcoindRpcClientF
e <- EclairRpcTestUtil.randomEclairClient(Some(bitcoind))
} yield e
val otherClientF = for {
bitcoind <- bitcoindRpcClientF
e <- EclairRpcTestUtil.randomEclairClient(Some(bitcoind))
} yield e
//great, setup done! Let's run the test
//to verify we can send a payment over the channel
for {
client <- clientF
otherClient <- otherClientF
_ <- EclairRpcTestUtil.openAndConfirmChannel(clientF, otherClientF)
invoice <- otherClient.createInvoice("abc", 50.msats)
info <- otherClient.getInfo
_ = assert(info.nodeId == invoice.nodeId)
infos <- client.getSentInfo(invoice.lnTags.paymentHash.hash)
_ = assert(infos.isEmpty)
paymentId <- client.payInvoice(invoice)
_ <- EclairRpcTestUtil.awaitUntilPaymentSucceeded(client, paymentId)
sentInfo <- client.getSentInfo(invoice.lnTags.paymentHash.hash)
} yield {
assert(sentInfo.head.amount == 50.msats)
}
//don't forget to shutdown everything!
val stop1F = clientF.map(c => EclairRpcTestUtil.shutdown(c))
val stop2F = otherClientF.map(o => EclairRpcTestUtil.shutdown(o))
val stoppedBitcoindF = for {
bitcoind <- bitcoindRpcClientF
_ <- BitcoindRpcTestUtil.stopServers(Vector(bitcoind))
} yield ()
val resultF = for {
_ <- stop1F
_ <- stop2F
_ <- stoppedBitcoindF
_ <- system.terminate()
} yield ()
Await.result(resultF, 180.seconds)
```
### Other modules
You may find useful testkit functionality for other modules here
1. [Chain](/api/org/bitcoins/testkit/chain/ChainUnitTest)
2. [Key Manager](/api/org/bitcoins/testkit/keymanager/KeyManagerApiUnitTest)
3. [Wallet](/api/org/bitcoins/testkit/wallet/BitcoinSWalletTest)
4. [Node](/api/org/bitcoins/testkit/node/NodeUnitTest)
In general, you will find constructors and destructors of fixtures that can be useful when testing your applications
if you are using any of those modules.

View file

@ -0,0 +1,69 @@
---
title: Wallet Callbacks
id: version-1.9.8-wallet-callbacks
original_id: wallet-callbacks
---
#### Wallet Callbacks
Bitcoin-S support call backs for the following events that happen in the wallet:
1. onTransactionProcessed
2. onTransactionBroadcast
3. onReservedUtxos
4. onNewAddressGenerated
5. onBlockProcessed
6. onRescanComplete
That means every time one of these events happens, we will call your callback
so that you can be notified of the event. These callbacks will be run after the message has been
recieved and will execute synchronously. If any of them fail an error log will be output, and the remainder of the callbacks will continue.
Let's make an easy one:
#### DLC Wallet callbacks
Bitcoin-s support callbacks for the following events in the DLC wallet:
1. onStateChange
That means everytime a DLC's state changes, your callback will be executed so
that you are notified of the event. For instance, if your DLC transitions from
`Offered` -> `Accepted`, your callback will be executed.
#### Example
Here is an example of constructing a wallet and registering a callback, so you can be notified of an event.
```scala
implicit val system: ActorSystem = ActorSystem("example")
implicit val ec: ExecutionContextExecutor = system.dispatcher
implicit val walletConf: WalletAppConfig =
BitcoinSTestAppConfig.getNeutrinoTestConfig().walletConf
val bitcoind = BitcoindRpcClient(BitcoindInstanceLocal.fromConfFile())
val aesPasswordOpt = Some(AesPassword.fromString("password"))
// Here is a super simple example of a callback, this could be replaced with anything, from
// relaying the transaction on the network, finding relevant wallet outputs, verifying the transaction,
// or writing it to disk
val exampleProcessTx: OnTransactionProcessed = (tx: Transaction) =>
Future.successful(println(s"Processed Tx: ${tx.txIdBE}"))
// Create our WalletCallbacks that
val exampleCallbacks = WalletCallbacks(
onTransactionProcessed = Vector(exampleProcessTx))
// Now we can create a wallet
val wallet =
Wallet(
nodeApi = bitcoind,
chainQueryApi = bitcoind,
feeRateApi = ConstantFeeRateProvider(SatoshisPerVirtualByte.one))
// Finally, we can add the callbacks to our wallet config
walletConf.addCallbacks(exampleCallbacks)
// Then to trigger the event we can run
val exampleTx = Transaction(
"0200000000010258e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd7500000000da00473044022074018ad4180097b873323c0015720b3684cc8123891048e7dbcd9b55ad679c99022073d369b740e3eb53dcefa33823c8070514ca55a7dd9544f157c167913261118c01483045022100f61038b308dc1da865a34852746f015772934208c6d24454393cd99bdf2217770220056e675a675a6d0a02b85b14e5e29074d8a25a9b5760bea2816f661910a006ea01475221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752aeffffffff838d0427d0ec650a68aa46bb0b098aea4422c071b2ca78352a077959d07cea1d01000000232200208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903ffffffff0270aaf00800000000160014d85c2b71d0060b09c9886aeb815e50991dda124d00e1f5050000000016001400aea9a2e5f0f876a588df5546e8742d1d87008f000400473044022062eb7a556107a7c73f45ac4ab5a1dddf6f7075fb1275969a7f383efff784bcb202200c05dbb7470dbf2f08557dd356c7325c1ed30913e996cd3840945db12228da5f01473044022065f45ba5998b59a27ffe1a7bed016af1f1f90d54b3aa8f7450aa5f56a25103bd02207f724703ad1edb96680b284b56d4ffcb88f7fb759eabbe08aa30f29b851383d20147522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae00000000")
wallet.processTransaction(exampleTx, None)
```

View file

@ -0,0 +1,141 @@
---
title: Wallet
id: version-1.9.8-wallet
original_id: wallet
---
## Bitcoin-s wallet
Bitcoin-s comes bundled with a rudimentary Bitcoin wallet. This wallet
is capable of managing private keys, generating addresses, constructing
and signing transactions, among other things. It is BIP32/BIP44/BIP49/BIP84
compatible.
This wallet is currently only released as a library, and not as a binary.
This is because it (nor the documentation) is not deemed production
ready. Use at your own risk, and without too much money depending on it.
### How is the bitcoin-s wallet implemented
The bitcoin-s wallet is a scalable way for individuals up to large bitcoin exchanges to safely and securely store their bitcoin in a scalable way.
All key interactions are delegated to the [key-manager](../key-manager/key-manager.md) which is a minimal dependency library to store and use key material.
By default, we store the encrypted root key in `$HOME/.bitcoin-s/seeds/encrypted-bitcoin-s-seed.json`. This is the seed that is used for each of the wallets on each bitcoin network.
Multiple wallet seeds can be saved using the `bitcoin-s.wallet.walletName` config option.
You can read more in the [key manager docs](../key-manager/server-key-manager.md).
The wallet itself is used to manage the utxo life cycle, create transactions, and update wallet balances to show how much money you have the on a bitcoin network.
We use [slick](https://scala-slick.org/doc/3.3.1/) as middleware to support different database types. Depending on your use case, you can use something as simple as sqlite, or something much more scalable like postgres.
### Example
This guide shows how to create a Bitcoin-s wallet and then
peer it with a `bitcoind` instance that relays
information about what is happening on the blockchain
through the P2P network.
This is useful if you want more flexible signing procedures in
the JVM ecosystem and more granular control over your
UTXOs with popular database like Postgres, SQLite, etc.
This code snippet you have a running `bitcoind` instance, locally
on regtest.
```scala
implicit val ec = scala.concurrent.ExecutionContext.global
implicit val system = ActorSystem("System")
val config = ConfigFactory.parseString {
"""
| bitcoin-s {
| network = regtest
| }
""".stripMargin
}
val datadir = Files.createTempDirectory("bitcoin-s-wallet")
implicit val walletConfig = WalletAppConfig(datadir, Vector(config))
// we also need to store chain state for syncing purposes
implicit val chainConfig = ChainAppConfig(datadir, Vector(config))
// when this future completes, we have
// created the necessary directories and
// databases for managing both chain state
// and wallet state
val configF: Future[Unit] = for {
_ <- walletConfig.start()
_ <- chainConfig.start()
} yield ()
val bitcoindInstance = BitcoindInstanceLocal.fromDatadir()
val bitcoind = BitcoindRpcClient(bitcoindInstance)
// when this future completes, we have
// synced our chain handler to our bitcoind
// peer
val syncF: Future[ChainApi] = configF.flatMap { _ =>
val getBestBlockHashFunc = { () =>
bitcoind.getBestBlockHash
}
val getBlockHeaderFunc = { hash: DoubleSha256DigestBE =>
bitcoind.getBlockHeader(hash).map(_.blockHeader)
}
val blockHeaderDAO = BlockHeaderDAO()
val compactFilterHeaderDAO = CompactFilterHeaderDAO()
val compactFilterDAO = CompactFilterDAO()
val stateDAO = ChainStateDescriptorDAO()
val chainHandler = ChainHandler(
blockHeaderDAO,
compactFilterHeaderDAO,
compactFilterDAO,
stateDAO,
blockFilterCheckpoints = Map.empty)
ChainSync.sync(chainHandler, getBlockHeaderFunc, getBestBlockHashFunc)
}
// once this future completes, we have a initialized
// wallet
val wallet = Wallet(new NodeApi {
override def broadcastTransactions(txs: Vector[Transaction]): Future[Unit] = Future.successful(())
override def downloadBlocks(blockHashes: Vector[DoubleSha256DigestBE]): Future[Unit] = Future.successful(())
override def getConnectionCount: Future[Int] = Future.successful(0)
}, chainApi, ConstantFeeRateProvider(SatoshisPerVirtualByte.one))
val walletF: Future[WalletApi] = configF.flatMap { _ =>
Wallet.initialize(wallet, None)
}
// when this future completes, ww have sent a transaction
// from bitcoind to the Bitcoin-S wallet
val transactionF: Future[(Transaction, Option[DoubleSha256DigestBE])] = for {
wallet <- walletF
address <- wallet.getNewAddress()
txid <- bitcoind.sendToAddress(address, 3.bitcoin)
transaction <- bitcoind.getRawTransaction(txid)
} yield (transaction.hex, transaction.blockhash)
// when this future completes, we have processed
// the transaction from bitcoind, and we have
// queried our balance for the current balance
val balanceF: Future[CurrencyUnit] = for {
wallet <- walletF
(tx, blockhash) <- transactionF
_ <- wallet.processTransaction(tx, blockhash)
balance <- wallet.getBalance()
} yield balance
balanceF.foreach { balance =>
println(s"Bitcoin-S wallet balance: $balance")
}
```

View file

@ -1,4 +1,5 @@
[
"1.9.8",
"1.9.7",
"1.9.6",
"1.9.5",