From 619e747d1a170699e3cc4dcf06ccdd1eee30c412 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Wed, 14 Mar 2018 08:48:02 -0700 Subject: [PATCH] pkg: remove docs and some other things for now. --- browser/debug.html | 11 - browser/index.html | 110 ------- browser/server.js | 44 --- browser/src/app.js | 291 ------------------ browser/src/proxysocket.js | 154 --------- browser/wsproxy.js | 204 ------------ docs/Beginner's-Guide.md | 147 --------- docs/CLI.md | 235 -------------- docs/Configuration.md | 98 ------ docs/Design.md | 71 ----- docs/Examples/client-api.js | 119 ------- docs/Examples/connect-to-peer.js | 47 --- docs/Examples/connect-to-the-p2p-network.js | 98 ------ .../create-a-blockchain-and-mempool.js | 42 --- docs/Examples/create-sign-tx.js | 79 ----- docs/Examples/fullnode-and-wallet.js | 83 ----- docs/Examples/fullnode.js | 28 -- docs/Examples/get-tx-from-chain.js | 52 ---- docs/Examples/miner-configs.js | 49 --- docs/Examples/peers-plugin.js | 59 ---- docs/Examples/spv-sync-wallet.js | 56 ---- docs/Examples/wallet.js | 49 --- docs/README.md | 51 --- docs/Running-in-the-browser.md | 16 - docs/Wallet-System.md | 22 -- etc/authorized-peers | 1 - etc/known-peers | 1 - etc/sample.conf | 22 +- snap/snapcraft.yaml | 20 -- 29 files changed, 9 insertions(+), 2250 deletions(-) delete mode 100644 browser/debug.html delete mode 100644 browser/index.html delete mode 100644 browser/server.js delete mode 100644 browser/src/app.js delete mode 100644 browser/src/proxysocket.js delete mode 100644 browser/wsproxy.js delete mode 100644 docs/Beginner's-Guide.md delete mode 100644 docs/CLI.md delete mode 100644 docs/Configuration.md delete mode 100644 docs/Design.md delete mode 100644 docs/Examples/client-api.js delete mode 100644 docs/Examples/connect-to-peer.js delete mode 100644 docs/Examples/connect-to-the-p2p-network.js delete mode 100644 docs/Examples/create-a-blockchain-and-mempool.js delete mode 100644 docs/Examples/create-sign-tx.js delete mode 100644 docs/Examples/fullnode-and-wallet.js delete mode 100644 docs/Examples/fullnode.js delete mode 100644 docs/Examples/get-tx-from-chain.js delete mode 100644 docs/Examples/miner-configs.js delete mode 100644 docs/Examples/peers-plugin.js delete mode 100644 docs/Examples/spv-sync-wallet.js delete mode 100644 docs/Examples/wallet.js delete mode 100644 docs/README.md delete mode 100644 docs/Running-in-the-browser.md delete mode 100644 docs/Wallet-System.md delete mode 100644 etc/authorized-peers delete mode 100644 etc/known-peers delete mode 100644 snap/snapcraft.yaml diff --git a/browser/debug.html b/browser/debug.html deleted file mode 100644 index 8d30d3483..000000000 --- a/browser/debug.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - bcoin - - - -

Bcoin

-

Use the console to access `global.bcoin`.

- - diff --git a/browser/index.html b/browser/index.html deleted file mode 100644 index fc5a054ed..000000000 --- a/browser/index.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - bcoin - - - - - -

Bcoin, the browser full node

- - Welcome. Your machine is currently validating the blockchain. The blocks - and wallet are stored on your local disk with indexed DB. You are - connecting to the actual bitcoin P2P network via a websocket->tcp - proxy. Enjoy. (See the - bcoin repo - for more bitcoin magic). - -
-
Chain State:
-
Last 20 Blocks/TXs:
-
-
-
-
- -
-
-
- - - -
- -
- - diff --git a/browser/server.js b/browser/server.js deleted file mode 100644 index 79dcc009e..000000000 --- a/browser/server.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const bweb = require('bweb'); -const fs = require('bfile'); -const WSProxy = require('./wsproxy'); - -const index = fs.readFileSync(`${__dirname}/index.html`); -const app = fs.readFileSync(`${__dirname}/app.js`); -const worker = fs.readFileSync(`${__dirname}/worker.js`); - -const proxy = new WSProxy({ - ports: [8333, 18333, 18444, 28333, 28901] -}); - -const server = bweb.server({ - port: Number(process.argv[2]) || 8080, - sockets: false -}); - -server.use(server.router()); - -proxy.on('error', (err) => { - console.error(err.stack); -}); - -server.on('error', (err) => { - console.error(err.stack); -}); - -server.get('/', (req, res) => { - res.send(200, index, 'html'); -}); - -server.get('/app.js', (req, res) => { - res.send(200, app, 'js'); -}); - -server.get('/worker.js', (req, res) => { - res.send(200, worker, 'js'); -}); - -proxy.attach(server.http); - -server.open(); diff --git a/browser/src/app.js b/browser/src/app.js deleted file mode 100644 index 1bbece6ce..000000000 --- a/browser/src/app.js +++ /dev/null @@ -1,291 +0,0 @@ -'use strict'; - -const Logger = require('blgr'); -const FullNode = require('../../lib/node/fullnode'); -const Amount = require('../../lib/btc/amount'); -const plugin = require('../../lib/wallet/plugin'); -const ProxySocket = require('./proxysocket'); - -const body = document.getElementsByTagName('body')[0]; -const log = document.getElementById('log'); -const wdiv = document.getElementById('wallet'); -const tdiv = document.getElementById('tx'); -const floating = document.getElementById('floating'); -const send = document.getElementById('send'); -const newaddr = document.getElementById('newaddr'); -const chainState = document.getElementById('state'); -const rpc = document.getElementById('rpc'); -const cmd = document.getElementById('cmd'); -const items = []; - -let scrollback = 0; - -const logger = new Logger({ - level: 'debug', - console: true -}); - -logger.writeConsole = function writeConsole(level, module, args) { - const name = Logger.levelsByVal[level]; - const msg = this.fmt(args, false); - - if (++scrollback > 1000) { - log.innerHTML = ''; - scrollback = 1; - } - - const now = Math.floor(Date.now() / 1000); - - log.innerHTML += `${now} `; - - if (name === 'error') { - log.innerHTML += `[${name}] `; - if (module) - log.innerHTML += `(${module}) `; - log.innerHTML += ''; - } else { - log.innerHTML += `[${name}] `; - if (module) - log.innerHTML += `(${module}) `; - } - - log.innerHTML += escape(msg) + '\n'; - log.scrollTop = log.scrollHeight; -}; - -const node = new FullNode({ - hash: true, - query: true, - prune: true, - network: 'main', - memory: false, - coinCache: 30, - logConsole: true, - workers: true, - workerFile: '/worker.js', - createSocket: (port, host) => { - const proto = global.location.protocol === 'https:' ? 'wss' : 'ws'; - const hostname = global.location.host; - return ProxySocket.connect(`${proto}://${hostname}`, port, host); - }, - logger: logger, - plugins: [plugin] -}); - -const {wdb} = node.require('walletdb'); -wdb.options.witness = true; - -window.onunhandledrejection = function onunhandledrejection(event) { - throw event.reason; -}; - -body.onmouseup = function onmouseup() { - floating.style.display = 'none'; -}; - -floating.onmouseup = function onmouseup(ev) { - ev.stopPropagation(); - return false; -}; - -function show(obj) { - if (obj instanceof Error) { - floating.innerHTML = obj.stack; - floating.style.display = 'block'; - return; - } - const json = obj && obj.toJSON ? obj.toJSON() : null; - floating.innerHTML = escape(JSON.stringify(json, null, 2)); - floating.style.display = 'block'; -} - -rpc.onsubmit = function onsubmit(ev) { - const text = cmd.value || ''; - const argv = text.trim().split(/\s+/); - const method = argv.shift(); - const params = []; - - cmd.value = ''; - - for (const arg of argv) { - let param; - try { - param = JSON.parse(arg); - } catch (e) { - param = arg; - } - params.push(param); - } - - (async () => { - try { - const result = await node.rpc.execute({ method, params }); - show(result); - } catch (e) { - show(e); - } - })(); - - ev.preventDefault(); - ev.stopPropagation(); - - return false; -}; - -send.onsubmit = function onsubmit(ev) { - const value = document.getElementById('amount').value; - const address = document.getElementById('address').value; - - const options = { - outputs: [{ - address: address, - value: Amount.value(value) - }] - }; - - (async () => { - try { - const mtx = await wdb.primary.createTX(options); - await wdb.primary.sign(mtx); - await node.relay(mtx.toTX()); - show(mtx); - } catch (e) { - show(e); - } - })(); - - ev.preventDefault(); - ev.stopPropagation(); - - return false; -}; - -newaddr.onmouseup = function onmouseup() { - (async () => { - try { - await wdb.primary.createReceive(); - formatWallet(wdb.primary); - } catch (e) { - show(e); - } - })(); -}; - -function kb(size) { - size /= 1000; - return size.toFixed(2) + 'kb'; -} - -function create(html) { - const el = document.createElement('div'); - el.innerHTML = html; - return el.firstChild; -} - -function escape(html, encode) { - return html - .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} - -function addItem(item, entry) { - const height = entry ? entry.height : -1; - - if (items.length === 20) { - const el = items.shift(); - tdiv.removeChild(el); - el.onmouseup = null; - } - - const el = create('' - + `` - + `${item.hash('hex')} (${height} - ${kb(item.getSize())})` - + '' - ); - - tdiv.appendChild(el); - - setMouseup(el, item); - - items.push(el); - - chainState.innerHTML = '' - + `tx=${node.chain.db.state.tx} ` - + `coin=${node.chain.db.state.coin} ` - + `value=${Amount.coin(node.chain.db.state.value)}`; -} - -function setMouseup(el, obj) { - el.onmouseup = function onmouseup(ev) { - show(obj); - ev.stopPropagation(); - return false; - }; -} - -async function formatWallet(wallet) { - try { - await _formatWallet(wallet); - } catch (e) { - show(e); - } -} - -async function _formatWallet(wallet) { - const {key, mnemonic} = wallet.master.toJSON(node.network, true); - const account = await wallet.getAccount('default'); - const receive = account.receiveAddress(); - const nested = account.nestedAddress(); - const raddr = receive.toString(node.network); - const naddr = nested ? nested.toString(node.network) : null; - - let html = ''; - - html += 'Wallet
'; - - if (naddr) { - html += `Current Address (p2wpkh): ${raddr}
`; - html += `Current Address (p2wpkh behind p2sh): ${naddr}
`; - } else { - html += `Current Address: ${raddr}
`; - } - - html += `Extended Private Key: ${key.xprivkey}
`; - html += `Mnemonic: ${mnemonic.phrase}
`; - - const balance = await wallet.getBalance(); - - html += `Confirmed Balance: ${Amount.coin(balance.confirmed)}
`; - html += `Unconfirmed Balance: ${Amount.coin(balance.unconfirmed)}
`; - - const txs = await wallet.getHistory(); - const det = await wallet.toDetails(txs); - - html += 'TXs:\n'; - wdiv.innerHTML = html; - - for (const tx of det) { - const el = create( - `${tx.hash}`); - wdiv.appendChild(el); - setMouseup(el, tx.toJSON()); - } -} - -node.chain.on('block', addItem); -node.mempool.on('tx', addItem); - -(async () => { - await node.open(); - await node.connect(); - node.startSync(); - wdb.primary.on('balance', () => { - formatWallet(wdb.primary); - }); - formatWallet(wdb.primary); -})().catch((err) => { - throw err; -}); diff --git a/browser/src/proxysocket.js b/browser/src/proxysocket.js deleted file mode 100644 index 67608c647..000000000 --- a/browser/src/proxysocket.js +++ /dev/null @@ -1,154 +0,0 @@ -/*! - * proxysocket.js - wsproxy socket for bcoin - * Copyright (c) 2017-2018, Christopher Jeffrey (MIT License). - * https://github.com/bcoin-org/bcoin - */ - -'use strict'; - -const assert = require('assert'); -const EventEmitter = require('events'); -const bsock = require('bsock'); - -class ProxySocket extends EventEmitter { - constructor(uri) { - super(); - - this.socket = bsock.socket(); - this.socket.reconnection = false; - this.socket.connect(uri); - - this.sendBuffer = []; - this.recvBuffer = []; - this.paused = false; - this.bytesWritten = 0; - this.bytesRead = 0; - this.remoteAddress = null; - this.remotePort = 0; - - this.closed = false; - - this.init(); - } - - init() { - this.socket.on('error', (err) => { - console.error(err); - }); - - this.socket.bind('tcp connect', (addr, port) => { - if (this.closed) - return; - this.remoteAddress = addr; - this.remotePort = port; - this.emit('connect'); - }); - - this.socket.bind('tcp data', (data) => { - data = Buffer.from(data, 'hex'); - if (this.paused) { - this.recvBuffer.push(data); - return; - } - this.bytesRead += data.length; - this.emit('data', data); - }); - - this.socket.bind('tcp close', (data) => { - if (this.closed) - return; - this.closed = true; - this.emit('close'); - }); - - this.socket.bind('tcp error', (e) => { - const err = new Error(e.message); - err.code = e.code; - this.emit('error', err); - }); - - this.socket.bind('tcp timeout', () => { - this.emit('timeout'); - }); - - this.socket.on('disconnect', () => { - if (this.closed) - return; - this.closed = true; - this.emit('close'); - }); - } - - connect(port, host) { - this.remoteAddress = host; - this.remotePort = port; - - if (this.closed) { - this.sendBuffer.length = 0; - return; - } - - this.socket.fire('tcp connect', port, host); - - for (const chunk of this.sendBuffer) - this.write(chunk); - - this.sendBuffer.length = 0; - } - - setKeepAlive(enable, delay) { - this.socket.fire('tcp keep alive', enable, delay); - } - - setNoDelay(enable) { - this.socket.fire('tcp no delay', enable); - } - - setTimeout(timeout, callback) { - this.socket.fire('tcp set timeout', timeout); - if (callback) - this.on('timeout', callback); - } - - write(data, callback) { - this.bytesWritten += data.length; - - this.socket.fire('tcp data', data.toString('hex')); - - if (callback) - callback(); - - return true; - } - - pause() { - this.paused = true; - } - - resume() { - const recv = this.recvBuffer; - - this.paused = false; - this.recvBuffer = []; - - for (const data of recv) { - this.bytesRead += data.length; - this.emit('data', data); - } - } - - destroy() { - if (this.closed) - return; - this.closed = true; - this.socket.destroy(); - } - - static connect(uri, port, host) { - const socket = new this(uri); - socket.connect(port, host); - return socket; - } -} - -module.exports = ProxySocket; diff --git a/browser/wsproxy.js b/browser/wsproxy.js deleted file mode 100644 index 3b219dd58..000000000 --- a/browser/wsproxy.js +++ /dev/null @@ -1,204 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const net = require('net'); -const EventEmitter = require('events'); -const bsock = require('bsock'); -const IP = require('binet'); - -class WSProxy extends EventEmitter { - constructor(options) { - super(); - - if (!options) - options = {}; - - this.options = options; - this.ports = new Set(); - this.io = bsock.server(); - this.sockets = new WeakMap(); - - if (options.ports) { - for (const port of options.ports) - this.ports.add(port); - } - - this.init(); - } - - init() { - this.io.on('error', (err) => { - this.emit('error', err); - }); - - this.io.on('socket', (ws) => { - this.handleSocket(ws); - }); - } - - handleSocket(ws) { - const state = new SocketState(this, ws); - - // Use a weak map to avoid - // mutating the websocket object. - this.sockets.set(ws, state); - - ws.on('error', (err) => { - this.emit('error', err); - }); - - ws.bind('tcp connect', (port, host) => { - this.handleConnect(ws, port, host); - }); - } - - handleConnect(ws, port, host) { - const state = this.sockets.get(ws); - assert(state); - - if (state.socket) { - this.log('Client is trying to reconnect (%s).', state.host); - return; - } - - if ((port & 0xffff) !== port - || typeof host !== 'string' - || host.length === 0) { - this.log('Client gave bad arguments (%s).', state.host); - ws.fire('tcp close'); - ws.destroy(); - return; - } - - let raw, addr; - try { - raw = IP.toBuffer(host); - addr = IP.toString(raw); - } catch (e) { - this.log('Client gave a bad host: %s (%s).', host, state.host); - ws.fire('tcp error', { - message: 'EHOSTUNREACH', - code: 'EHOSTUNREACH' - }); - ws.destroy(); - return; - } - - if (!IP.isRoutable(raw) || IP.isOnion(raw)) { - this.log( - 'Client is trying to connect to a bad ip: %s (%s).', - addr, state.host); - ws.fire('tcp error', { - message: 'ENETUNREACH', - code: 'ENETUNREACH' - }); - ws.destroy(); - return; - } - - if (!this.ports.has(port)) { - this.log('Client is connecting to non-whitelist port (%s).', state.host); - ws.fire('tcp error', { - message: 'ENETUNREACH', - code: 'ENETUNREACH' - }); - ws.destroy(); - return; - } - - let socket; - try { - socket = state.connect(port, addr); - this.log('Connecting to %s (%s).', state.remoteHost, state.host); - } catch (e) { - this.log(e.message); - this.log('Closing %s (%s).', state.remoteHost, state.host); - ws.fire('tcp error', { - message: 'ENETUNREACH', - code: 'ENETUNREACH' - }); - ws.destroy(); - return; - } - - socket.on('connect', () => { - ws.fire('tcp connect', socket.remoteAddress, socket.remotePort); - }); - - socket.on('data', (data) => { - ws.fire('tcp data', data.toString('hex')); - }); - - socket.on('error', (err) => { - ws.fire('tcp error', { - message: err.message, - code: err.code || null - }); - }); - - socket.on('timeout', () => { - ws.fire('tcp timeout'); - }); - - socket.on('close', () => { - this.log('Closing %s (%s).', state.remoteHost, state.host); - ws.fire('tcp close'); - ws.destroy(); - }); - - ws.bind('tcp data', (data) => { - if (typeof data !== 'string') - return; - socket.write(Buffer.from(data, 'hex')); - }); - - ws.bind('tcp keep alive', (enable, delay) => { - socket.setKeepAlive(enable, delay); - }); - - ws.bind('tcp no delay', (enable) => { - socket.setNoDelay(enable); - }); - - ws.bind('tcp set timeout', (timeout) => { - socket.setTimeout(timeout); - }); - - ws.bind('tcp pause', () => { - socket.pause(); - }); - - ws.bind('tcp resume', () => { - socket.resume(); - }); - - ws.on('disconnect', () => { - socket.destroy(); - }); - } - - log(...args) { - process.stdout.write('wsproxy: '); - console.log(...args); - } - - attach(server) { - this.io.attach(server); - } -} - -class SocketState { - constructor(server, socket) { - this.socket = null; - this.host = socket.host; - this.remoteHost = null; - } - - connect(port, host) { - this.socket = net.connect(port, host); - this.remoteHost = IP.toHostname(host, port); - return this.socket; - } -} - -module.exports = WSProxy; diff --git a/docs/Beginner's-Guide.md b/docs/Beginner's-Guide.md deleted file mode 100644 index 90d197357..000000000 --- a/docs/Beginner's-Guide.md +++ /dev/null @@ -1,147 +0,0 @@ -## Introduction - -Bcoin is an _alternative_ implementation of the bitcoin protocol, written in node.js. It is a full node which can be used for full blockchain validation and is aware of all known consensus rules. - -## Requirements - -- Linux, OSX, or Windows (\*) (\*\*) -- node.js >=v5.0.0 -- npm >=v4.0.0 -- python2 (for node-gyp) -- gcc/g++ (for leveldb and secp256k1) -- git (optional, see below) - -(\*): Note that bcoin works best with unix-like OSes, and has not yet been thoroughly tested on windows. - -(\*\*): The BSDs and Solaris have also not been tested yet, but should work in theory. - -## Build & Install - -Bcoin is meant to be installed via npm, but for the security conscious, it may be better to clone from github. All tagged commits for release should be signed by @chjj's [PGP key][keybase] (`B4B1F62DBAC084E333F3A04A8962AB9DE6666BBD`). Signed copies of node.js are available from [nodejs.org][node], or from your respective OS's package repositories. - -### Installing via NPM - -``` bash -$ npm install -g bcoin --production -``` - -### Installing via Git - -``` bash -$ curl https://keybase.io/chjj/pgp_keys.asc | gpg --import -$ git clone git://github.com/bcoin-org/bcoin.git -$ cd bcoin -$ git tag -... -v1.0.0-alpha # latest version -$ git tag -v v1.0.0-alpha # verify signature -$ git checkout v1.0.0-alpha -$ npm install -g --production -``` - -### Troubleshooting - -If the build fails compilation for `bcoin-native` or `secp256k1-node` __validation will be slow__ (a block verification which should take 1 second on consumer grade hardware may take up to 15 seconds). Bcoin will throw a warning on boot if it detects a build failure. If you run into this issue, please post an issue on the repo. - -## Starting up your first bcoin node - -If bcoin is installed globally, `$ bcoin` should be in your PATH. If not, the bcoin bootstrap script resides in `/path/to/bcoin/bin/bcoin`. - -``` bash -$ bcoin -``` - -Will run a bcoin node as the foreground process, displaying all debug logs. - -To run as a daemon: - -``` bash -$ bcoin --daemon -``` - -This will start up a full node, complete with: a blockchain, mempool, miner, p2p server, wallet server, and an HTTP REST+RPC server. - -All logs will be written to `~/.bcoin/debug.log` by default. - -By default, the http server will only listen on `127.0.0.1:8332`. No auth will be required if an API key was not passed in. If you listen on any other host, auth will be required and an API key will be auto-generated if one was not passed in. - -## Listening Externally - -To listen publicly on the HTTP server, `--http-host=0.0.0.0` (ipv4) or `--http-host=::` (ipv4 and ipv6) can be passed. Additionally this: `--http-port=1337` can set the port. - -To advertise your node on the P2P network `--public-host=[your-public-ip]` and `--public-port=[your-public-port]` may be passed. - -## Using an API Key - -If listening publicly on the HTTP server, an API key is required. One will be generated and reported in the logs automatically if no key was chosen. An api key can be chosen with the `--api-key` option. - -Example: - -``` bash -$ bcoin --http-host=0.0.0.0 --api-key hunter2 --daemon -``` - -API keys are used with HTTP Basic Auth: - -``` bash -$ curl http://x:hunter2@localhost:8332/ -``` - -Bcoin CLI is the prepackaged tool for hitting both the REST and RPC api. - -``` bash -$ bcoin cli info --api-key hunter2 -$ bcoin rpc getblockchaininfo --api-key hunter2 -``` - -## Using Tor/SOCKS - -Bcoin has native support for SOCKS proxies, and will accept a `--proxy` option in the format of `--proxy=[user]:[pass]@host:port`. - -Passing the `--onion` option tells bcoin that the SOCKS proxy is a Tor socks proxy, and will enable Tor resolution for DNS lookups, as well as try to connect to `.onion` addresses found on the P2P network. - -``` bash -$ bcoin --proxy joe:hunter2@127.0.0.1:9050 --onion -``` - -### Running bcoin as a tor hidden service - -Your hidden service must first be configured with `tor`. Once you have the `.onion` address, it can be passed into `--public-host` in the form of `--public-host foo.onion`. - -## Target Nodes - -It's often desirable to run behind several trusted bitcoin nodes. To select permanent nodes to connect to, the `--nodes` option is available: - -``` bash -$ bcoin --nodes foo.example.com:8333,1.2.3.4:8333,5.6.7.8:8333 -``` - -If chosen, bcoin will _always_ try to connect to these nodes as outbound peers. They are top priority and whitelisted (not susceptible to permanent bans, only disconnections). - -To _only_ connect to these nodes. `--max-outbound` could be set to 3: - -``` bash -$ bcoin --nodes foo.example.com,1.2.3.4,5.6.7.8 --max-outbound 3 -``` - -## Disabling Listening - -To avoid accepting connections on the P2P network altogether, `--listen=false` can be passed to bcoin. - -### Selfish Mode - -Bcoin also supports a "selfish" mode. In this mode, bcoin still has full blockchain and mempool validation, but network services are disabled: it will not relay transactions or serve blocks to anyone. - -``` bash -$ bcoin --selfish --listen=false -``` - -Note: Selfish mode is not recommended. We encourage you to _help_ the network by relaying transactions and blocks. At the same time, selfish mode does have its uses if you do not have the bandwidth to spare, or if you're absolutely worried about potential DoS attacks. - -## Further Configuration - -See [Configuration][configuration]. - -[keybase]: https://keybase.io/chjj#show-public -[node]: https://nodejs.org/dist/v7.5.0/ -[configuration]: Configuration.md diff --git a/docs/CLI.md b/docs/CLI.md deleted file mode 100644 index 38d497fd0..000000000 --- a/docs/CLI.md +++ /dev/null @@ -1,235 +0,0 @@ -Bcoin ships with bcoin-cli as its default HTTP client for command line access. - -## Configuration - -Examples: - -``` bash -$ export BCOIN_API_KEY=hunter2 -$ export BCOIN_NETWORK=main -$ export BCOIN_URI=http://localhost:8332 -$ bcoin cli info -``` - -``` bash -$ bcoin cli info --api-key=hunter2 --uri=http://localhost -``` - -``` bash -$ echo 'api-key: hunter2' > ~/cli.conf -$ bcoin cli info --config=~/cli.conf -``` - -## Examples - -``` bash -$ export BCOIN_API_KEY=your-api-key - -# View the genesis block -$ bcoin cli block 0 - -# View the mempool -$ bcoin cli mempool - -# View primary wallet -$ bcoin wallet get - -# View transaction history -$ bcoin wallet history - -# Send a transaction -$ bcoin wallet send [address] 0.01 - -# View balance -$ bcoin wallet balance - -# Derive new address -$ bcoin wallet address - -# Create a new account -$ bcoin wallet account create foo - -# Send from account -$ bcoin wallet send [address] 0.01 --account=foo -``` - -RPC examples: - -``` bash -$ bcoin rpc getblockchaininfo -$ bcoin rpc getwalletinfo -$ bcoin rpc getpeerinfo -$ bcoin rpc getbalance -$ bcoin rpc listtransactions -$ bcoin rpc sendtoaddress [address] 0.01 -``` - -## Commands - -bcoin-cli commands are split into 3 categories: cli, rpc, and wallet. - -### Top-level Commands - -- `info`: Get server info. -- `wallets`: List all wallets. -- `wallet create [id]`: Create wallet. -- `broadcast [tx-hex]`: Broadcast transaction. -- `mempool`: Get mempool snapshot. -- `tx [hash/address]`: View transactions. -- `coin [hash+index/address]`: View coins. -- `block [hash/height]`: View block. -- `rescan [height]`: Rescan for transactions. -- `reset [height/hash]`: Reset chain to desired block. -- `resend`: Resend pending transactions. -- `backup [path]`: Backup the wallet db. -- `wallet [command]`: Execute wallet command. -- `rpc [command] [args]`: Execute RPC command. - -### Wallet Commands - -- `listen`: Listen for events. -- `get`: View wallet. -- `master`: View wallet master key. -- `shared add [xpubkey]`: Add key to wallet. -- `shared remove [xpubkey]`: Remove key from wallet. -- `balance`: Get wallet balance. -- `history`: View TX history. -- `pending`: View pending TXs. -- `coins`: View wallet coins. -- `account list`: List account names. -- `account create [account-name]`: Create account. -- `account get [account-name]`: Get account details. -- `address`: Derive new receiving address. -- `change`: Derive new change address. -- `nested`: Derive new nested address. -- `retoken`: Create new api key. -- `send [address] [value]`: Send transaction. -- `mktx [address] [value]`: Create transaction. -- `sign [tx-hex]`: Sign transaction. -- `zap [age?]`: Zap pending wallet TXs. -- `tx [hash]`: View transaction details. -- `blocks`: List wallet blocks. -- `block [height]`: View wallet block. -- `view [tx-hex]`: Parse and view transaction. -- `import [wif|hex]`: Import private or public key. -- `watch [address]`: Import an address. -- `key [address]`: Get wallet key by address. -- `dump [address]`: Get wallet key WIF by address. -- `lock`: Lock wallet. -- `unlock [passphrase] [timeout?]`: Unlock wallet. -- `resend`: Resend pending transactions. - -### RPC Commands - -Bcoin implements nearly all bitcoind calls along with some custom calls. - -- `stop` -- `help` -- `getblockchaininfo` -- `getbestblockhash` -- `getblockcount` -- `getblock` -- `getblockhash` -- `getblockheader` -- `getchaintips` -- `getdifficulty` -- `getmempoolancestors` -- `getmempooldescendants` -- `getmempoolentry` -- `getmempoolinfo` -- `getrawmempool` -- `gettxout` -- `gettxoutsetinfo` -- `verifychain` -- `invalidateblock` -- `reconsiderblock` -- `getnetworkhashps` -- `getmininginfo` -- `prioritisetransaction` -- `getwork` -- `getworklp` -- `getblocktemplate` -- `submitblock` -- `setgenerate` -- `getgenerate` -- `generate` -- `generatetoaddress` -- `estimatefee` -- `estimatepriority` -- `estimatesmartfee` -- `estimatesmartpriority` -- `getinfo` -- `validateaddress` -- `createmultisig` -- `createwitnessaddress` -- `verifymessage` -- `signmessagewithprivkey` -- `setmocktime` -- `getconnectioncount` -- `ping` -- `getpeerinfo` -- `addnode` -- `disconnectnode` -- `getaddednodeinfo` -- `getnettotals` -- `getnetworkinfo` -- `setban` -- `listbanned` -- `clearbanned` -- `getrawtransaction` -- `createrawtransaction` -- `decoderawtransaction` -- `decodescript` -- `sendrawtransaction` -- `signrawtransaction` -- `gettxoutproof` -- `verifytxoutproof` -- `fundrawtransaction` -- `resendwallettransactions` -- `abandontransaction` -- `addmultisigaddress` -- `addwitnessaddress` -- `backupwallet` -- `dumpprivkey` -- `dumpwallet` -- `encryptwallet` -- `getaccountaddress` -- `getaccount` -- `getaddressesbyaccount` -- `getbalance` -- `getnewaddress` -- `getrawchangeaddress` -- `getreceivedbyaccount` -- `getreceivedbyaddress` -- `gettransaction` -- `getunconfirmedbalance` -- `getwalletinfo` -- `importprivkey` -- `importwallet` -- `importaddress` -- `importprunedfunds` -- `importpubkey` -- `keypoolrefill` -- `listaccounts` -- `listaddressgroupings` -- `listlockunspent` -- `listreceivedbyaccount` -- `listreceivedbyaddress` -- `listsinceblock` -- `listtransactions` -- `listunspent` -- `lockunspent` -- `move` -- `sendfrom` -- `sendmany` -- `sendtoaddress` -- `setaccount` -- `settxfee` -- `signmessage` -- `walletlock` -- `walletpassphrasechange` -- `walletpassphrase` -- `removeprunedfunds` -- `getmemory` -- `selectwallet` -- `setloglevel` \ No newline at end of file diff --git a/docs/Configuration.md b/docs/Configuration.md deleted file mode 100644 index b094e1d0f..000000000 --- a/docs/Configuration.md +++ /dev/null @@ -1,98 +0,0 @@ -By default, the mainnet bcoin config file will reside in ~/.bcoin/bcoin.conf. - -All bcoin configuration options work in the config file, CLI arguments, and -process environment (with a `BCOIN_` prefix). - -## Datadir/Prefix - -Bcoin's datadir is determined by the `prefix` option. - -Example: - -``` bash -$ bcoin --prefix ~/.bcoin_spv --spv -``` - -Will create a datadir of `~/.bcoin_spv`, containing a chain database, wallet database and log file. - -## Common Options - -- `config`: Points to a custom config file, not in the prefix directory. -- `network`: Which network's chainparams to use for the node (main, testnet, regtest, or segnet4) (default: main). -- `workers`: Whether to use a worker process pool for transaction verification (default: true). -- `workers-size`: Number of worker processes to spawn for transaction verification. By default, the worker pool will be sized based on the number of CPUs/cores in the machine. -- `workers-timeout`: Worker process execution timeout in milliseconds (default: 120000). -- `sigcache-size`: Max number of items in signature cache. - -## Node Options - -- `prefix`: The data directory (stores databases, logs, and configs) (default=~/.bcoin). -- `db`: Which database backend to use (default=leveldb). -- `max-files`: Max open files for leveldb. Higher generally means more disk page cache benefits, but also more memory usage (default: 64). -- `cache-size`: Size (in MB) of leveldb cache and write buffer (default: 32mb). - -## Logger Options - -- `log-level`: `error`, `warning`, `info`, `debug`, or `spam` (default: debug). -- `log-console`: `true` or `false` - whether to actually write to stdout/stderr - if foregrounded (default: true). -- `log-file`: Whether to use a log file (default: true). - -## Chain Options - -Note that certain chain options affect the format and indexing of the chain database and must be passed in consistently each time. - -- `prune`: Prune from the last 288 blocks (default: false). -- `checkpoints`: Use checkpoints and getheaders for the initial sync (default: true). -- `coin-cache`: The size (in MB) of the in-memory UTXO cache. By default, there is no UTXO cache enabled. To get a good number of cache hits per block, the coin cache has to be fairly large (60-100mb recommended at least). -- `index-tx`: Index transactions (enables transaction endpoints in REST api) (default: false). -- `index-address`: Index transactions and utxos by address (default: false). - -## Mempool Options - -- `mempool-size`: Max mempool size in MB (default: 100). -- `replace-by-fee`: Allow replace-by-fee transactions (default: false). -- `persistent-mempool`: Save mempool to disk and read into memory on boot (default: false). - -## Pool Options - -- `selfish`: Enable "selfish" mode (no relaying of txes or blocks) (default: false). -- `compact`: Enable compact block relay (default: true). -- `bip37`: Enable serving of bip37 merkleblocks (default: false). -- `bip151`: Enable bip151 peer-to-peer encryption (default: false). -- `listen`: Accept incoming connections (default: true). -- `max-outbound`: Max number of outbound connections (default: 8). -- `max-inbound`: Max number of inbound connections (default: 30). -- `seeds`: Custom list of DNS seeds (comma-separated). -- `host`: Host to listen on (default: 0.0.0.0). -- `port`: Port to listen on (default: 8333). -- `public-host`: Public host to advertise on network. -- `public-port`: Public port to advertise on network. -- `bip150`: Enable bip150 peer auth (default: false). -- `identity-key`: BIP150 identity key (32 byte hex string). -- `auth-peers`: Path to `authorized-peers` file for BIP150. -- `known-peers`: Path to `known-peers` file for BIP150. -- `nodes`: List of target nodes to connect to (comma-separated). - -## Miner Options - -- `coinbase-flags`: Coinbase flags (default: mined by bcoin). -- `coinbase-address`: List of payout addresses, randomly selected during block creation (comma-separated). -- `max-block-weight`: Max block weight to mine (default: 4000000). -- `reserved-block-weight`: Amount of space reserved for coinbase (default: 4000). -- `reserved-block-sigops`: Amount of sigops reserved for coinbase (default: 400). - -## HTTP - -- `http-host`: HTTP host to listen on (default: 127.0.0.1). -- `http-port`: HTTP port to listen on (default: 8332). -- `ssl-cert`: Path to SSL cert. -- `ssl-key`: Path to SSL key. -- `service-key`: Service key (used for accessing wallet system only). -- `api-key`: API key (used for accessing all node APIs). -- `wallet-auth`: Enable token auth for wallets (default: false). -- `no-auth`: Disable auth for API server and wallets (default: false). - -## Sample Config File - -See https://github.com/bcoin-org/bcoin/blob/master/etc/sample.conf. diff --git a/docs/Design.md b/docs/Design.md deleted file mode 100644 index ed02fe3f3..000000000 --- a/docs/Design.md +++ /dev/null @@ -1,71 +0,0 @@ -## Notes on Design - -Bcoin is thoroughly event driven. It has a fullnode object, but Bcoin was -specifically designed so the mempool, blockchain, p2p pool, and wallet database -could all be used separately. All the fullnode object does is tie these things -together. It's essentially a huge proxying of events. The general communication -between these things looks something like this: - -``` -pool -> block event -> chain -pool -> tx event -> mempool -chain -> block event -> mempool/miner -chain -> tx event -> walletdb -chain -> reorg event -> walletdb/mempool/miner -mempool -> tx event -> walletdb/miner -miner -> block event -> chain -walletdb -> tx event -> websocket server -websocket server -> tx event -> websocket client -http client -> tx -> http server -> mempool -``` - -Not only does the loose coupling make testing easier, it ensures people can -utilize bcoin for many use cases. - -### Performance - -Non-javscript people reading this may think using javascript isn't a wise -decision. - -#### Javascript - -Javascript is inherently slow due to how dynamic it is, but modern JITs have -solved this issue using very clever optimization and dynamic recompilation -techniques. v8 in some cases can [rival the speed of C++][v8] if the code is -well-written. - -#### Concurrency - -Bcoin runs in node.js, so the javascript code is limited to one thread. We -solve this limitation by spinning up persistent worker processes for -transaction verification (webworkers when in the browser). This ensures the -blockchain and mempool do not block the master process very much. It also means -transaction verification can be parallelized. - -Strangely enough, workers are faster in the browser than they are in node since -you are allowed to share memory between threads using the transferrable api -(Uint8Arrays can be "transferred" to another thread). In node, you have to pipe -data to another process. - -But of course, there is a benefit to having a multi-process architecture: the -worker processes can die on their own without disturbing the master process. - -Bcoin uses [secp256k1-node][secp256k1-node] for ecdsa verification, which is a -node.js binding to Pieter Wuille's blazingly fast [libsecp256k1][libsecp256k1] -library. - -In the browser, bcoin will use [elliptic][elliptic], the fastest javascript -ecdsa implementation. It will obviously never beat C and hand-optimized -assembly, but it's still usable. - -#### Benefits - -The real feature of javascript is that your code will run almost anywhere. With -bcoin, we now have a full node that will run on almost any browser, on laptops, -on servers, on smartphones, on most devices you can imagine, even by simply -visiting a webpage. - -[v8]: https://www.youtube.com/watch?v=UJPdhx5zTaw -[libsecp256k1]: https://github.com/bitcoin-core/secp256k1 -[secp256k1-node]: https://github.com/cryptocoinjs/secp256k1-node -[elliptic]: https://github.com/indutny/elliptic \ No newline at end of file diff --git a/docs/Examples/client-api.js b/docs/Examples/client-api.js deleted file mode 100644 index 3946366d4..000000000 --- a/docs/Examples/client-api.js +++ /dev/null @@ -1,119 +0,0 @@ -'use strict'; - -const bcoin = require('../..'); -const encoding = bcoin.encoding; -const Outpoint = bcoin.outpoint; -const MTX = bcoin.mtx; -const HTTP = bcoin.http; -const FullNode = bcoin.fullnode; -const plugin = bcoin.wallet.plugin; - -const node = new FullNode({ - network: 'regtest', - apiKey: 'foo', - walletAuth: true, - db: 'memory' -}); - -node.use(plugin); - -const wallet = new HTTP.Wallet({ - network: 'regtest', - apiKey: 'foo' -}); - -async function fundWallet(wdb, addr) { - // Coinbase - const mtx = new MTX(); - mtx.addOutpoint(new Outpoint(encoding.NULL_HASH, 0)); - mtx.addOutput(addr, 50460); - mtx.addOutput(addr, 50460); - mtx.addOutput(addr, 50460); - mtx.addOutput(addr, 50460); - - const tx = mtx.toTX(); - - wallet.once('balance', (balance) => { - console.log('New Balance:'); - console.log(balance); - }); - - wallet.once('address', (receive) => { - console.log('New Receiving Address:'); - console.log(receive); - }); - - wallet.once('tx', (details) => { - console.log('New Wallet TX:'); - console.log(details); - }); - - await wdb.addTX(tx); - await new Promise(r => setTimeout(r, 300)); -} - -async function sendTX(addr, value) { - const options = { - rate: 10000, - outputs: [{ - value: value, - address: addr - }] - }; - - const tx = await wallet.send(options); - - return tx.hash; -} - -async function callNodeApi() { - const info = await wallet.client.getInfo(); - - console.log('Server Info:'); - console.log(info); - - const json = await wallet.client.rpc.execute('getblocktemplate', []); - - console.log('Block Template (RPC):'); - console.log(json); -} - -(async () => { - const wdb = node.require('walletdb'); - - await node.open(); - - const w = await wallet.create({ id: 'test' }); - - console.log('Wallet:'); - console.log(w); - - // Fund default account. - await fundWallet(wdb, w.account.receiveAddress); - - const balance = await wallet.getBalance(); - - console.log('Balance:'); - console.log(balance); - - const acct = await wallet.createAccount('foo'); - - console.log('Account:'); - console.log(acct); - - // Send to our new account. - const hash = await sendTX(acct.receiveAddress, 10000); - - console.log('Sent TX:'); - console.log(hash); - - const tx = await wallet.getTX(hash); - - console.log('Sent TX details:'); - console.log(tx); - - await callNodeApi(); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/connect-to-peer.js b/docs/Examples/connect-to-peer.js deleted file mode 100644 index 321cd141b..000000000 --- a/docs/Examples/connect-to-peer.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -// Usage: $ node ./docs/Examples/connect-to-peer.js [ip]:[port] - -const bcoin = require('../..'); -const Peer = bcoin.peer; -const NetAddress = bcoin.netaddress; -const Network = bcoin.network; -const network = Network.get('testnet'); - -const peer = Peer.fromOptions({ - network: 'testnet', - agent: 'my-subversion', - hasWitness: () => { - return false; - } -}); - -const addr = NetAddress.fromHostname(process.argv[2], 'testnet'); - -console.log(`Connecting to ${addr.hostname}`); - -peer.connect(addr); -peer.tryOpen(); - -peer.on('error', (err) => { - console.error(err); -}); - -peer.on('packet', (msg) => { - console.log(msg); - - if (msg.cmd === 'block') { - console.log('Block!'); - console.log(msg.block.toBlock()); - return; - } - - if (msg.cmd === 'inv') { - peer.getData(msg.items); - return; - } -}); - -peer.on('open', () => { - peer.getBlock([network.genesis.hash]); -}); diff --git a/docs/Examples/connect-to-the-p2p-network.js b/docs/Examples/connect-to-the-p2p-network.js deleted file mode 100644 index 8024fa66d..000000000 --- a/docs/Examples/connect-to-the-p2p-network.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; -const bcoin = require('../..').set('main'); -const Chain = bcoin.chain; -const Mempool = bcoin.mempool; -const Pool = bcoin.pool; - -// Create a blockchain and store it in leveldb. -// `db` also accepts `rocksdb` and `lmdb`. -const prefix = process.env.HOME + '/my-bcoin-environment'; -const chain = new Chain({ - db: 'leveldb', - location: prefix + '/chain', - network: 'main' -}); - -const mempool = new Mempool({ chain: chain }); - -// Create a network pool of peers with a limit of 8 peers. -const pool = new Pool({ - chain: chain, - mempool: mempool, - maxPeers: 8 -}); - -// Open the pool (implicitly opens mempool and chain). -(async function() { - await pool.open(); - - // Connect, start retrieving and relaying txs - await pool.connect(); - - // Start the blockchain sync. - pool.startSync(); - - // Watch the action - chain.on('block', (block) => { - console.log('Connected block to blockchain:'); - console.log(block); - }); - - mempool.on('tx', (tx) => { - console.log('Added tx to mempool:'); - console.log(tx); - }); - - pool.on('tx', (tx) => { - console.log('Saw transaction:'); - console.log(tx.rhash); - }); -})(); - -// Start up a testnet sync in-memory -// while we're at it (because we can). - -const tchain = new Chain({ - network: 'testnet', - db: 'memory' -}); - -const tmempool = new Mempool({ - network: 'testnet', - chain: tchain -}); - -const tpool = new Pool({ - network: 'testnet', - chain: tchain, - mempool: tmempool, - size: 8 -}); - -(async function() { - await tpool.open(); - - // Connect, start retrieving and relaying txs - await tpool.connect(); - - // Start the blockchain sync. - tpool.startSync(); - - tchain.on('block', (block) => { - console.log('Added testnet block:'); - console.log(block); - }); - - tmempool.on('tx', (tx) => { - console.log('Added testnet tx to mempool:'); - console.log(tx); - }); - - tpool.on('tx', (tx) => { - console.log('Saw testnet transaction:'); - console.log(tx); - }); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/create-a-blockchain-and-mempool.js b/docs/Examples/create-a-blockchain-and-mempool.js deleted file mode 100644 index 1c3d42802..000000000 --- a/docs/Examples/create-a-blockchain-and-mempool.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; -const bcoin = require('../..'); -const Chain = bcoin.chain; -const Mempool = bcoin.mempool; -const Miner = bcoin.miner; - -// Default network (so we can avoid passing -// the `network` option into every object below.) -bcoin.set('regtest'); - -// Start up a blockchain, mempool, and miner using in-memory -// databases (stored in a red-black tree instead of on-disk). -const chain = new Chain({ db: 'memory' }); -const mempool = new Mempool({ chain: chain }); -const miner = new Miner({ - chain: chain, - mempool: mempool, - - // Make sure miner won't block the main thread. - useWorkers: true -}); - -(async () => { - // Open the miner (initialize the databases, etc). - // Miner will implicitly call `open` on chain and mempool. - await miner.open(); - - // Create a Cpu miner job - const job = await miner.createJob(); - - // run miner - const block = await job.mineAsync(); - - // Add the block to the chain - console.log('Adding %s to the blockchain.', block.rhash); - console.log(block); - await chain.add(block); - console.log('Added block!'); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/create-sign-tx.js b/docs/Examples/create-sign-tx.js deleted file mode 100644 index 6661626c2..000000000 --- a/docs/Examples/create-sign-tx.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -/* eslint new-cap: "off" */ - -const bcoin = require('../..'); -const assert = require('assert'); - -(async () => { - const master = bcoin.hd.generate(); - const key = master.derivePath('m/44/0/0/0/0'); - const keyring = new bcoin.keyring(key.privateKey); - const cb = new bcoin.mtx(); - - cb.addInput({ - prevout: new bcoin.outpoint(), - script: new bcoin.script(), - sequence: 0xffffffff - }); - - // Send 50,000 satoshis to ourselves. - cb.addOutput({ - address: keyring.getAddress(), - value: 50000 - }); - - // Our available coins. - const coins = []; - - // Convert the coinbase output to a Coin - // object and add it to our available coins. - // In reality you might get these coins from a wallet. - const coin = bcoin.coin.fromTX(cb, 0, -1); - coins.push(coin); - - // Create our redeeming transaction. - const mtx = new bcoin.mtx(); - - // Send 10,000 satoshis to ourself. - mtx.addOutput({ - address: keyring.getAddress(), - value: 10000 - }); - - // Now that we've created the output, we can do some coin selection (the - // output must be added first so we know how much money is needed and also so - // we can accurately estimate the size for fee calculation). - - // Select coins from our array and add inputs. - // Calculate fee and add a change output. - await mtx.fund(coins, { - // Use a rate of 10,000 satoshis per kb. - // With the `fullnode` object, you can - // use the fee estimator for this instead - // of blindly guessing. - rate: 10000, - // Send the change back to ourselves. - changeAddress: keyring.getAddress() - }); - - // Sign input 0 - mtx.sign(keyring); - - // The transaction should now verify. - assert(mtx.verify()); - - // Commit our transaction and make it immutable. - // This turns it from an MTX into a TX. - const tx = mtx.toTX(); - - // The transaction should still verify. - // Regular transactions require a coin - // viewpoint to be passed in. - assert(tx.verify(mtx.view)); - - console.log(mtx); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/fullnode-and-wallet.js b/docs/Examples/fullnode-and-wallet.js deleted file mode 100644 index 50d64198f..000000000 --- a/docs/Examples/fullnode-and-wallet.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; -const bcoin = require('../..').set('main'); -const walletPlugin = bcoin.wallet.plugin; - -const node = bcoin.fullnode({ - checkpoints: true, - // Primary wallet passphrase - passsphrase: 'node', - logLevel: 'info' -}); - -node.use(walletPlugin); - -// We get a lot of errors sometimes, -// usually from peers hanging up on us. -// Just ignore them for now. -node.on('error', (err) => { - ; -}); - -// New Address we'll be sending to. -const newReceiving = 'AddressHere'; - -// Start the node -(async () => { - await node.open(); - - const options = { - id: 'mywallet', - passphrase: 'foo', - witness: false, - type: 'pubkeyhash' - }; - - const walletdb = node.require('walletdb'); - - await walletdb.open(); - const wallet = await walletdb.create(options); - - console.log('Created wallet with address: %s', wallet.getAddress('base58')); - - await node.connect(); - - // Start syncing the blockchain - node.startSync(); - - // Wait for balance and send it to a new address. - wallet.once('balance', async (balance) => { - // Create a transaction, fill - // it with coins, and sign it. - const options = { - subtractFee: true, - outputs: [{ - address: newReceiving, - value: balance.total - }] - }; - - const tx = await wallet.createTX(options); - const stx = await wallet.sign(tx, 'foo'); - - console.log('sending tx:'); - console.log(stx); - - await node.sendTX(stx); - console.log('tx sent!'); - }); - - node.chain.on('block', (block) => { - ; - }); - - node.mempool.on('tx', (tx) => { - ; - }); - - node.chain.on('full', () => { - node.mempool.getHistory().then(console.log); - }); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/fullnode.js b/docs/Examples/fullnode.js deleted file mode 100644 index c63ec67ed..000000000 --- a/docs/Examples/fullnode.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const bcoin = require('../..'); -const FullNode = bcoin.fullnode; - -const node = new FullNode({ - network: 'testnet', - db: 'memory', - workers: true -}); - -(async () => { - await node.open(); - await node.connect(); - - node.on('connect', (entry, block) => { - console.log('%s (%d) added to chain.', entry.rhash(), entry.height); - }); - - node.on('tx', (tx) => { - console.log('%s added to mempool.', tx.txid()); - }); - - node.startSync(); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/get-tx-from-chain.js b/docs/Examples/get-tx-from-chain.js deleted file mode 100644 index 39c1646fc..000000000 --- a/docs/Examples/get-tx-from-chain.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const path = require('path'); -const bcoin = require('../..'); -const Chain = bcoin.chain; -const Logger = bcoin.logger; -const util = bcoin.util; - -const HOME = process.env.HOME; - -// Setup logger to see what's Bcoin doing. -const logger = new Logger({ - level: 'debug' -}); - -// Create chain for testnet, specify chain directory -const chain = new Chain({ - logger: logger, - network: 'testnet', - db: 'leveldb', - prefix: path.join(HOME, '.bcoin/testnet'), - indexTX: true, - indexAddress: true -}); - -(async () => { - await logger.open(); - await chain.open(); - - console.log('Current height:', chain.height); - - const entry = await chain.getEntry(50000); - console.log('Block at 50k:', entry); - - // eslint-disable-next-line max-len - const txhash = '4dd628123dcde4f2fb3a8b8a18b806721b56007e32497ebe76cde598ce1652af'; - const txmeta = await chain.db.getMeta(util.revHex(txhash)); - const tx = txmeta.tx; - const coinview = await chain.db.getSpentView(tx); - - console.log(`Tx with hash ${txhash}:`, txmeta); - console.log(`Tx input: ${tx.getInputValue(coinview)},` + - ` output: ${tx.getOutputValue()}, fee: ${tx.getFee(coinview)}`); - - // eslint-disable-next-line max-len - const bhash = '00000000077eacdd2c803a742195ba430a6d9545e43128ba55ec3c80beea6c0c'; - const block = await chain.db.getBlock(util.revHex(bhash)); - console.log(`Block with hash ${bhash}:`, block); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/miner-configs.js b/docs/Examples/miner-configs.js deleted file mode 100644 index b6ad820b4..000000000 --- a/docs/Examples/miner-configs.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -const bcoin = require('../..'); -const KeyRing = bcoin.keyring; -const WorkerPool = bcoin.workerpool; -const Chain = bcoin.chain; -const Miner = bcoin.miner; - -const key = KeyRing.generate('regtest'); - -const workers = new WorkerPool({ - enabled: true -}); - -const chain = new Chain({ - network: 'regtest', - workers: workers -}); - -const miner = new Miner({ - chain: chain, - addresses: [key.getAddress()], - coinbaseFlags: 'my-miner', - workers: workers -}); - -(async () => { - await miner.open(); - - const tmpl = await miner.createBlock(); - - console.log('Block template:'); - console.log(tmpl); - - const job = await miner.createJob(); - const block = await job.mineAsync(); - - console.log('Mined block:'); - console.log(block); - console.log(block.txs[0]); - - await chain.add(block); - - console.log('New tip:'); - console.log(chain.tip); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/peers-plugin.js b/docs/Examples/peers-plugin.js deleted file mode 100644 index fb7881825..000000000 --- a/docs/Examples/peers-plugin.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -const bcoin = require('../..'); -const FullNode = bcoin.fullnode; - -function MyPlugin(node) { - this.node = node; -} - -MyPlugin.id = 'my-plugin'; - -MyPlugin.init = function init(node) { - return new MyPlugin(node); -}; - -MyPlugin.prototype.open = function open() { - console.log('Opened my plugin.'); - return Promise.resolve(); -}; - -MyPlugin.prototype.close = function close() { - console.log('Closed my plugin.'); - return Promise.resolve(); -}; - -MyPlugin.prototype.sayPeers = function sayPeers() { - console.log('Number of peers: %d', this.node.pool.peers.size()); -}; - -const node = new FullNode({ - network: 'testnet', - db: 'memory', - workers: true -}); - -node.use(MyPlugin); - -(async () => { - const plugin = node.require('my-plugin'); - - await node.open(); - - await node.connect(); - - plugin.sayPeers(); - - node.on('connect', (entry, block) => { - console.log('%s (%d) added to chain.', entry.rhash(), entry.height); - }); - - node.on('tx', (tx) => { - console.log('%s added to mempool.', tx.txid()); - }); - - node.startSync(); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/spv-sync-wallet.js b/docs/Examples/spv-sync-wallet.js deleted file mode 100644 index 75f5992d5..000000000 --- a/docs/Examples/spv-sync-wallet.js +++ /dev/null @@ -1,56 +0,0 @@ -'use strict'; - -const bcoin = require('../..'); -const Chain = bcoin.chain; -const Pool = bcoin.pool; -const WalletDB = bcoin.walletdb; - -bcoin.set('testnet'); - -// SPV chains only store the chain headers. -const chain = Chain({ - db: 'leveldb', - location: process.env.HOME + '/spvchain', - spv: true -}); - -const pool = new Pool({ - chain: chain, - spv: true, - maxPeers: 8 -}); - -const walletdb = new WalletDB({ db: 'memory' }); - -(async () => { - await pool.open(); - await walletdb.open(); - - const wallet = await walletdb.create(); - - console.log('Created wallet with address %s', wallet.getAddress('base58')); - - // Add our address to the spv filter. - pool.watchAddress(wallet.getAddress()); - - // Connect, start retrieving and relaying txs - await pool.connect(); - - // Start the blockchain sync. - pool.startSync(); - - pool.on('tx', async (tx) => { - console.log('received TX'); - - await walletdb.addTX(tx); - console.log('Transaction added to walletDB'); - }); - - wallet.on('balance', (balance) => { - console.log('Balance updated.'); - console.log(bcoin.amount.btc(balance.unconfirmed)); - }); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/Examples/wallet.js b/docs/Examples/wallet.js deleted file mode 100644 index fc066e14e..000000000 --- a/docs/Examples/wallet.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -const bcoin = require('../..'); -const random = bcoin.crypto.random; -const WalletDB = bcoin.walletdb; -const MTX = bcoin.mtx; -const Outpoint = bcoin.outpoint; - -function dummy() { - const hash = random.randomBytes(32).toString('hex'); - return new Outpoint(hash, 0); -} - -const walletdb = new WalletDB({ - network: 'testnet', - db: 'memory' -}); - -(async () => { - await walletdb.open(); - - const wallet = await walletdb.create(); - - console.log('Created wallet'); - console.log(wallet); - - const acct = await wallet.createAccount({ - name: 'foo' - }); - - console.log('Created account'); - console.log(acct); - - const mtx = new MTX(); - mtx.addOutpoint(dummy()); - mtx.addOutput(acct.getReceive(), 50460); - - const tx = mtx.toTX(); - - await walletdb.addTX(tx); - - const wtx = await wallet.getTX(tx.hash('hex')); - - console.log('Added transaction'); - console.log(wtx); -})().catch((err) => { - console.error(err.stack); - process.exit(1); -}); diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 997bee266..000000000 --- a/docs/README.md +++ /dev/null @@ -1,51 +0,0 @@ -Welcome to the bcoin docs! - -## Getting Started -- [Getting Started][getting-started] -- [Configuration][configuration] -- [Wallet System][wallet-system] -- [Design][design] -- [Guides][guides] - -## Running -- [Bcoin CLI][cli] -- [Running in the Browser][browser] -- [REST and RPC API][rest-rpc] - -## Code Examples -- [Simple Fullnode][example-simple-fullnode] -- [Connect to Peer][example-connect-peer] -- [Connecting to the P2P Network][example-p2p] -- [Creating a Blockchain and Mempool][example-blockchain] -- [Wallet with Dummy TX][example-wallet-dummy] -- [Fullnode Object][example-fullnode-wallet] -- [SPV Sync][example-spv] -- [Plugin Example][example-peers-plugin] -- [Client API Usage][example-client-api] -- [Miner with WorkerPool][example-miner-configs] -- [Create and Sign TX][example-tx-create-sign] -- [Get Transaction from Chain][example-tx-from-chain] - - -[getting-started]: Beginner's-Guide.md -[configuration]: Configuration.md -[design]: Design.md -[wallet-system]: Wallet-System.md -[guides]: http://bcoin.io/guides.html - -[cli]: CLI.md -[browser]: Running-in-the-browser.md -[rest-rpc]: http://bcoin.io/api-docs/index.html#introduction - -[example-p2p]: Examples/connect-to-the-p2p-network.js -[example-blockchain]: Examples/create-a-blockchain-and-mempool.js -[example-fullnode-wallet]: Examples/fullnode-and-wallet.js -[example-spv]: Examples/spv-sync-wallet.js -[example-wallet-dummy]: Examples/wallet.js -[example-peers-plugin]: Examples/peers-plugin.js -[example-client-api]: Examples/client-api.js -[example-miner-configs]: Examples/miner-configs.js -[example-connect-peer]: Examples/connect-to-peer.js -[example-simple-fullnode]: Examples/fullnode.js -[example-tx-create-sign]: Examples/create-sign-tx.js -[example-tx-from-chain]: Examples/get-tx-from-chain.js diff --git a/docs/Running-in-the-browser.md b/docs/Running-in-the-browser.md deleted file mode 100644 index 0e3a525d6..000000000 --- a/docs/Running-in-the-browser.md +++ /dev/null @@ -1,16 +0,0 @@ -Because bcoin is written in node.js, it is capable of being browserified. - -## Running a full node in the browser - -``` bash -$ cd ~/bcoin -$ make # Browserify bcoin -$ node browser/server.js 8080 # Start up a simple webserver and websocket->tcp bridge -$ chromium http://localhost:8080 -``` - -You should see something like this: http://i.imgur.com/0pWySyZ.png - -This is a simple proof-of-concept. It's not a pretty interface. I hope to see -others doing something far more interesting. A browser extension may be better: -the chrome extension API exposes raw TCP access. \ No newline at end of file diff --git a/docs/Wallet-System.md b/docs/Wallet-System.md deleted file mode 100644 index 0655c0852..000000000 --- a/docs/Wallet-System.md +++ /dev/null @@ -1,22 +0,0 @@ -Wallet REST API: [REST-RPC-API](REST-RPC-API.md) - -## Notes on wallet system - -Bcoin maintains a wallet database which contains every wallet. Wallets are _not -usable_ without also using a wallet database. For testing, the wallet database -can be in-memory, but it must be there. - -Wallets in bcoin use bip44. They also originally supported bip45 for multisig, -but support was removed to reduce code complexity, and also because bip45 -doesn't seem to add any benefit in practice. - -The wallet database can contain many different wallets, with many different -accounts, with many different addresses for each account. Bcoin should -theoretically be able to scale to hundreds of thousands of -wallets/accounts/addresses. - -Each account can be of a different type. You could have a pubkeyhash account, -as well as a multisig account, a witness pubkeyhash account, etc. - -Note that accounts should not be accessed directly from the public API. They do -not have locks which can lead to race conditions during writes. diff --git a/etc/authorized-peers b/etc/authorized-peers deleted file mode 100644 index 0039fff50..000000000 --- a/etc/authorized-peers +++ /dev/null @@ -1 +0,0 @@ -02b9f7499c4166e76d3a64326bbbe92dc02f0e07dc184f94995da61683c311cb0f diff --git a/etc/known-peers b/etc/known-peers deleted file mode 100644 index 695f51b9b..000000000 --- a/etc/known-peers +++ /dev/null @@ -1 +0,0 @@ -node.bcoin.io,52.39.113.206 02b9f7499c4166e76d3a64326bbbe92dc02f0e07dc184f94995da61683c311cb0f diff --git a/etc/sample.conf b/etc/sample.conf index 9715be662..7d23ef771 100644 --- a/etc/sample.conf +++ b/etc/sample.conf @@ -50,7 +50,6 @@ mempool-size: 100 limit-free: true limit-free-relay: 15 reject-absurd-fees: true -replace-by-fee: false persistent-mempool: false # @@ -60,7 +59,6 @@ persistent-mempool: false selfish: false compact: true bip37: false -bip151: true listen: true max-outbound: 8 max-inbound: 30 @@ -70,33 +68,32 @@ max-inbound: 30 # onion: true # upnp: true -# Custom list of DNS seeds -# seeds: seed.bitcoin.sipa.be +# Custom list of seeds +# seeds: key@127.0.0.1 # Local Host & Port (to listen on) host: :: -# port: 8333 +# port: 12038 # Public Host & Port (to advertise to peers) # public-host: 1.2.3.4 -# public-port: 8444 +# public-port: 12038 -# BIP151 AuthDB and Identity Key -bip150: false +# Brontide Identity Key (see also ~/.hsk/key) identity-key: 74b4147957813b62cc8987f2b711ddb31f8cb46dcbf71502033da66053c8780a # Always try to connect to these nodes. -# nodes: 127.0.0.1,127.0.0.2 +# nodes: key@127.0.0.1,key@127.0.0.2 # Only try to connect to these nodes. -# only: 127.0.0.1,127.0.0.2 +# only: key@127.0.0.1,key@127.0.0.2 # # Miner # coinbase-flags: mined by hsk -# coinbase-address: 1111111111111111111114oLvT2,1111111111111111111114oLvT2 +# coinbase-address: hs1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqrfy4d0 preverify: false max-block-weight: 4000000 reserved-block-weight: 4000 @@ -107,7 +104,7 @@ reserved-block-sigops: 400 # http-host: :: -# http-port: 8332 +# http-port: 12037 # ssl: true # ssl-cert: @/ssl/cert.crt # ssl-key: @/ssl/priv.key @@ -118,6 +115,5 @@ api-key: bikeshed # Wallet # -wallet-witness: false wallet-checkpoints: true wallet-auth: false diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml deleted file mode 100644 index ad3e6d530..000000000 --- a/snap/snapcraft.yaml +++ /dev/null @@ -1,20 +0,0 @@ -name: hskd -version: git -summary: A Handshake implementation for miners, wallets, and exchanges -description: | - HSKD is an implementation of the Handshake Protocol. - -grade: devel # must be 'stable' to release into candidate/stable channels -confinement: strict - -apps: - hskd: - command: hskd - plugs: [network, network-bind] - -parts: - hskd: - source: . - plugin: nodejs - build-packages: [python, gcc] - node-engine: 7.9.0