Compare commits

..

1 Commits

Author SHA1 Message Date
Christopher Jeffrey
3c22d7050f
blockdb: flat files. 2016-11-18 18:01:33 -08:00
428 changed files with 124026 additions and 99781 deletions

9
.babelrc Normal file
View File

@ -0,0 +1,9 @@
{
"presets": ["es2015"],
"plugins": [
["transform-runtime", {
"polyfill": true,
"regenerator": true
}]
]
}

View File

@ -1,59 +0,0 @@
defaults: &defaults
working_directory: ~/repo
docker:
- image: circleci/node:10.2
version: 2.0
jobs:
install:
<<: *defaults
working_directory: ~/repo
steps:
- checkout
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package-lock.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run: npm install
- run: npm install bslint nyc codecov
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package-lock.json" }}
- persist_to_workspace:
root: .
paths: .
test:
<<: *defaults
steps:
- attach_workspace:
at: .
- run:
name: Tests with coverage
command: npm run test-ci
- run:
name: Submit coverage
command: ./node_modules/.bin/codecov
lint:
<<: *defaults
steps:
- attach_workspace:
at: .
- run:
name: Lint
command: npm run lint-ci
workflows:
version: 2
test_and_lint:
jobs:
- install
- lint:
requires:
- install
- test:
requires:
- install

2
.dockerignore Normal file
View File

@ -0,0 +1,2 @@
node_modules/
docker_data/

View File

@ -1,13 +0,0 @@
bench/
bin/cli
bin/node
bin/spvnode
bin/wallet
browser/server.js
browser/wsproxy.js
browser/src/app.js
lib/
migrate/
scripts/
test/
docs/examples

View File

@ -1,152 +0,0 @@
{
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"globals": {
"Atomics": "readable",
"BigInt": "readable",
"BigInt64Array": "readable",
"BigUint64Array": "readable",
"queueMicrotask": "readable",
"SharedArrayBuffer": "readable",
"TextEncoder": "readable",
"TextDecoder": "readable"
},
"overrides": [
{
"files": ["*.mjs"],
"parserOptions": {
"sourceType": "module"
}
},
{
"files": ["*.cjs"],
"parserOptions": {
"sourceType": "script"
}
},
{
"files": [
"test/{,**/}*.{mjs,cjs,js}"
],
"env": {
"mocha": true
},
"globals": {
"register": "readable"
},
"rules": {
"max-len": "off",
"prefer-arrow-callback": "off"
}
}
],
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 10,
"ecmaFeatures": {
"globalReturn": true
},
"requireConfigFile": false,
"sourceType": "script"
},
"root": true,
"rules": {
"array-bracket-spacing": ["error", "never"],
"arrow-parens": ["error", "as-needed", {
"requireForBlockBody": true
}],
"arrow-spacing": "error",
"block-spacing": ["error", "always"],
"brace-style": ["error", "1tbs"],
"camelcase": ["error", {
"properties": "never"
}],
"comma-dangle": ["error", "never"],
"consistent-return": "error",
"eol-last": ["error", "always"],
"eqeqeq": ["error", "always", {
"null": "ignore"
}],
"func-name-matching": "error",
"indent": ["off", 2, {
"ArrayExpression": "off",
"SwitchCase": 1,
"CallExpression": {
"arguments": "off"
},
"FunctionDeclaration": {
"parameters": "off"
},
"FunctionExpression": {
"parameters": "off"
},
"MemberExpression": "off",
"ObjectExpression": "off",
"ImportDeclaration": "off"
}],
"handle-callback-err": "off",
"linebreak-style": ["error", "unix"],
"max-len": ["error", {
"code": 80,
"ignorePattern": "function \\w+\\(",
"ignoreUrls": true
}],
"max-statements-per-line": ["error", {
"max": 1
}],
"new-cap": ["error", {
"newIsCap": true,
"capIsNew": false
}],
"new-parens": "error",
"no-buffer-constructor": "error",
"no-console": "off",
"no-extra-semi": "off",
"no-fallthrough": "off",
"no-func-assign": "off",
"no-implicit-coercion": "error",
"no-multi-assign": "error",
"no-multiple-empty-lines": ["error", {
"max": 1
}],
"no-nested-ternary": "error",
"no-param-reassign": "off",
"no-return-assign": "error",
"no-return-await": "off",
"no-shadow-restricted-names": "error",
"no-tabs": "error",
"no-trailing-spaces": "error",
"no-unused-vars": ["error", {
"vars": "all",
"args": "none",
"ignoreRestSiblings": false
}],
"no-use-before-define": ["error", {
"functions": false,
"classes": false
}],
"no-useless-escape": "off",
"no-var": "error",
"nonblock-statement-body-position": ["error", "below"],
"padded-blocks": ["error", "never"],
"prefer-arrow-callback": "error",
"prefer-const": ["error", {
"destructuring": "all",
"ignoreReadBeforeAssign": true
}],
"prefer-template": "off",
"quotes": ["error", "single"],
"semi": ["error", "always"],
"spaced-comment": ["error", "always", {
"exceptions": ["!"]
}],
"space-before-blocks": "error",
"strict": "error",
"unicode-bom": ["error", "never"],
"valid-jsdoc": "error",
"wrap-iife": ["error", "inside"]
}
}

14
.gitignore vendored
View File

@ -1,11 +1,5 @@
node_modules/
.nyc_output
docs/reference/
docker_data/
browser/bcoin*
npm-debug.log
coverage/
yarn.lock
webpack.*.js
.DS_Store
tmp*
key.key
node_modules/
test.js
docker_data/

43
.jshintrc Normal file
View File

@ -0,0 +1,43 @@
{
"bitwise": false,
"esversion": 6,
"curly": false,
"eqeqeq": true,
"freeze": true,
"latedef": "nofunc",
"maxparams": 7,
"noarg": true,
"shadow": "inner",
"undef": true,
"unused": "vars",
"boss": true,
"expr": true,
"eqnull": true,
"evil": true,
"loopfunc": true,
"proto": true,
"supernew": true,
"-W018": true,
"-W064": true,
"-W086": true,
"-W032": true,
"-W021": true,
"browser": true,
"browserify": true,
"node": true,
"nonstandard": true,
"typed": true,
"worker": false,
"camelcase": false,
"indent": 2,
"maxlen": 110,
"newcap": false,
"quotmark": "single",
"laxbreak": true,
"laxcomma": true
}

View File

@ -1,18 +1,6 @@
.babel*
.bmocharc*
.bpkgignore
.editorconfig
.eslint*
.git*
.mocharc*
.yarnignore
yarn.lock
node_modules/
package-lock.json
npm-debug.log
webpack.*.js
browser/bcoin*
bench/
build/
docs/
test/
node_modules/
.jshintrc
.jscsrc
jsdoc.json

View File

@ -1,603 +0,0 @@
# Bcoin release notes & changelog
## v2.0.0-dev
### How to upgrade
The way that block data is stored has changed for greater performance,
efficiency, reliability and portability.
- Block and undo block data has been moved from LevelDB into flat files.
- The transaction and address indexes have been moved into separate
LevelDB databases.
- The transaction has been de-duplicated, and will reduce disk usage by
half for those running with `txindex` enabled.
- The `txindex` and `addrindex` can now be enabled after the initial
block download.
- The `addrindex` has been sorted to support querying for large sets
of results, and will no longer cause CPU and memory exhaustion issues.
- The `addrindex` will correctly distinguish between `p2pkh` and
`p2wpkh` addresses.
To upgrade to the new disk layout it's necessary to move block data
from LevelDB (e.g. `~/.bcoin/chain`) to a new file based block
storage (e.g. `~./.bcoin/blocks`), and remove `txindex` and `addrindex`
data from the chain database, for those that have that feature enabled.
To do this you can run:
```
node ./migrate/chaindb4to6.js /path/to/bcoin/chain
```
The migration will take 1-3 hours, depending on hardware. The block data
will now be stored at `/path/to/bcoin/blocks`, after the data has been moved
the chain database will be compacted to free disk space.
Alternatively, you can also sync the chain again, however the above
migration will be faster as additional network bandwidth won't be used
for downloading the blocks again.
For those with `txindex` and `addrindex` enabled, the indexes will be
regenerated by rescanning the chain on next startup, this process can
take multiple hours (e.g. 8 hours) depending on hardware and the
index. Please take the potential downtime in re-indexing into account
before upgrading.
### Wallet API changes
#### HTTP
- `PUT /wallet/:id` Creating a watch-only wallet now requires an `accountKey`
argument. This is to prevent bcoin from generating keys and addresses the
user can not spend from.
- `POST /wallet/:id/create`
- Now has a `sign` argument for optional signing of transactions.
- Now has a `template` option, that will skip templating inputs when
`sign = false`, but you can enable it if necessary. It does not have an
effect when `sign = true`.
- Exposes `blocks`, which can will be used if there is no `rate` option.
- Exposes `sort` (Default `true`), that can be used to disable BIP69 sorting.
#### RPC
- Bug fix addresses for the `getnewaddress` command with various networks.
- Deprecate the `ismine` and `iswatchonly` fields from the `validateaddress`
command and add `isscript`, `iswitness`, `ischange`, `witness_version`
and `witness_program` to partially match the v0.18.0 Bitcoin Core release
(26a2000b0177fd2668b7d82e5aa52829cf2bfdf6)
- Add wallet RPC `getaddressinfo` to return `ismine` and `iswatchonly`
with the correct values instead of their previous values which were
hardcoded to false. Also returns `address`, `scriptPubKey`, `isscript`,
`iswitness`, `witness_version` and `witness_program`.
(a28ffa272a3c4d90d0273d9aa223a23becc08e0e)
### Node API changes
#### HTTP
Several CPU and memory exhaustion issues have been resolved with some
additional arguments for querying multiple sets of results for addresses
that have many transactions.
- `GET /tx/address/:address` has several new arguments: `after`, `reverse`
and `limit`. The `after` argument is a txid, for querying additional results
after a previous result. The `reverse` argument will change the order that
results are returned, the default order is oldest to latest. The `limit`
argument can be used to give results back in smaller sets if necessary.
- `POST /tx/address` This has been deprecated, instead query for each address
individually with `GET /tx/address/:address` with the expectation that
there could be _many_ results that would additionally need to be queried
in a subsequent query using the `after` argument to request the next set.
- `POST /coin/address` and `GET /coin/address/:address` are deprecated as
coins can be generated using results from `/tx/address/:address` and
querying by only a range of the latest transactions to stay synchronized.
Coins could otherwise be removed from results at any point, and thus the
entire set of results would need to be queried every time to discover
which coins have been spent and are currently available.
- `GET /` has new fields `.indexes.{addr,tx}` for the status of indexers.
### Network changes
- Regtest params have been updated to correspond with other bitcoin
implementations for cross testing. Key prefixes have been updated and
segwit is always active (39684df6051b599da9ed1383cb7e3f8605806a74). The
regtest seeds have also been cleared so that the node will not attempt
to connect to itself.
- Testnet seeds have been updated (8b6eba165b090edfc1ff5dbc9c422758d60b6342)
### Logging changes
- Wallet and node HTTP and RPC is now more clearly identified. The wallet
HTTP server will log with the context `wallet-http` and the RPC as
`wallet-rpc`. The node HTTP will log with the context `node-http` and the
RPC as `node-rpc`. There was also a reduction in the duplicate logs in
the case of an error for the node RPC, and the addition of method logging
for the wallet RPC.
- There is now also additional logging during wallet rescans.
### Configuration changes
- Pool options now has a `--discover` option exposed, and the `--only` node
option will disable discovery of new nodes.
- The option for `coin-cache` has been removed, this setting was causing
issues during the sync with out-of-memory errors and was making performance
worse instead of better.
- The database location for indexes can be configured via the
`--index-prefix` option. Default locations are `prefix` + `/index`
(e.g. `~/.bcoin/testnet/index/tx` and `~/.bcoin/testnet/index/addr`).
### Script changes
- Script has been updated for policy flags. For example
`VERIFY_CONST_SCRIPTCODE` to disable `OP_CODESEPARATOR` in non-segwit
scripts and make a positive `findAndDelete` result invalid.
- Segwit scripts that terminate with a stack size not equal to one
now has as error of `CLEANSTACK` instead of `EVAL_FALSE`.
- `VERIFY_UPGRADABLE_NOPS` now does not apply to `OP_CHECKLOCKTIMEVERIFY`
and `OP_CHECKSEQUENCEVERIFY`.
### Testing changes
- Switched to use a security focused rewrite of `mocha` called
`bmocha`, for further details see: https://github.com/bcoin-org/bmocha
- Data has been updated to be in sync with other implementations
around policy-only script validation.
- Tests now cleanly close with all timers being cleared.
- Config file `wallet.conf` won't be read during test runs that was
causing issues with some testing environments.
### Chain changes
- The transaction index methods are now implemented at `node.txindex`:
- `getMeta(hash)`
- `getTX(hash)`
- `hasTX(hash)`
- `getSpentView(tx)`
- The address index method `getHashesByAddress` is now implemented
at `node.addrindex`:
- `getHashesByAddress(addr)` It now accepts `Address` instances
rather than `Address|String` and the results are now sorted in
order of appearance in the blockchain.
- `getHashesByAddress(addr, options)` A new options argument has
been added with the fields:
- `after` - A transaction hash for results to begin after.
- `limit` - The total number of results to return at maximum.
- `reverse` - Will give results in order of latest to oldest.
- The following methods require `node.addrindex.getHashesByAddress`
in conjunction with `node.txindex.getTX` and `node.txindex.getMeta`
respectively, and now includes a new options argument as described
above for `getHashesByAddress`:
- `node.getMetaByAddress(addr, options)`
- `node.getTXByAddress(addr, options)`
- The following method has been deprecated:
- `getCoinsByAddress(addr)`
### Other changes
- A new module for storing block data in files.
- Use of `buffer-map` for storing hashes
(see https://github.com/bcoin-org/bcoin/issues/533).
- Use of `bsert` for assertions.
- `SIGINT` handling will close the full node, spvnode and wallet.
- Using the bcoin library in a REPL now has auto-completion by pressing tab.
- Various documentation updates.
- Mempool fix to add non-standard (non-segwit) to reject cache.
- A lockfile is now included and all dependencies integrity verified
with sha512 hash and not the vulnerable sha1 hash.
- Updates to dependencies including `bcrypto` to version > 3.
- Various small fixes to run bcoin in a browser.
## v1.0.0
### Migration
The latest bcoin release contains almost a total rewrite of the wallet. A
migration is required.
Bcoin has also been modularized quite a bit. Users installing globally from npm
should be sure to run:
``` bash
$ npm update -g bcoin
```
For users who cloned the respository themselves, it might be wise to simply
remove the `node_modules` directory and do a fresh `npm install`.
``` bash
$ cd bcoin/
$ git pull origin master
$ rm -rf node_modules/
$ npm install
$ npm test
```
---
Once upgrading is complete, a migration script must be executed. The migration
script resides in `./migrate/latest` as an executable file.
A bcoin __prefix directory__ must be passed as the first argument.
Example:
``` bash
$ ./migrate/latest ~/.bcoin
```
What this does:
- Renames `chain.ldb` to `chain`.
- Renames `spvchain.ldb` to `spvchain`.
- Renames `walletdb.ldb` to `wallet`.
- Runs a migration (`chaindb3to4.js`) on `chain`.
- Runs a migration (`chaindb3to4.js`) on `spvchain`.
- Runs a migration (`walletdb6to7.js`) on `wallet`.
The chain migration should be minor, and only taxing if you have
`--index-address` enabled.
If you have a testnet, regtest, or simnet directory, the migration must also be
run on these, e.g.
``` bash
$ ./migrate/latest ~/.bcoin/testnet
```
Also note that the `--prefix` argument now __always__ creates a fully-fledged
prefix directory. For example `--prefix ~/.bcoin_whatever --network testnet`
will create a directory structure of `~/.bcoin_whatever/testnet/` instead of
`~/.bcoin_whatever`. Please update your directory structure accordingly.
### Configuration changes
Wallet and Node are now separated and use different persistent configuration files.
Some configuration options have moved to `wallet.conf`, which is stored in the prefix
directory next to the existing `bcoin.conf`.
All configuration options in `wallet.conf` will have the `wallet-`
prefix added implicitly. The prefix is still needed when using CLI/ENV configuration
methods. The wallet now has it's own HTTP server, so options such as
`wallet-http-host` must also be specified along with `http-host`
if you require this setting (required for Docker networking).
Wallet-specific settings such as `api-key` and `wallet-auth`
have moved to `wallet.conf`. If using CLI/ENV options, these are prefixed with `wallet-`.
Various configuration method examples are shown below.
Note some config options (eg. `network`) are automatically passed to wallet plugin
if specified through CLI/ENV, but should be specified in `wallet.conf` for `bwallet-cli`.
Example using wallet.conf:
```
network: testnet
wallet-auth: true
api-key: hunter2
http-host: 0.0.0.0
```
Example using CLI options:
`./bin/node --network=testnet --http-host=0.0.0.0 --wallet-http-host=0.0.0.0 --wallet-api-key=hunter2 --wallet-wallet-auth=true`
Example using ENV:
`BCOIN_NETWORK=simnet BCOIN_HTTP_HOST=0.0.0.0 BCOIN_WALLET_HTTP_HOST=0.0.0.0 BCOIN_WALLET_API_KEY=hunter2 BCOIN_WALLET_WALLET_AUTH=true ./bin/node`
### Bcoin client changes
The `bcoin cli` interface has been deprecated and is now replaced with a
separate tool: `bcoin-cli`. `bcoin wallet` has also been deprecated and is
replaced with `bwallet-cli`. Both `bcoin-cli` and `bwallet-cli` can be
installed with the `bclient` package in npm.
### Wallet API changes
The main wallet API changes have to do with changes in the structure of the
HTTP server itself. The bcoin wallet HTTP server will now always listen on it's
own port. Standard ports are:
```
main: 8334
testnet: 18334
regtest: 48334
simnet: 18558
```
The default account object is no longer present on the wallet. To retrieve it,
request `/wallet/:id/account/default` instead. More minor changes to the JSON
output include the removal of `id` and `wid` properties on a number of objects.
Please update your code accordingly.
For socket.io events, all `wallet ` prefixes have been removed. For example,
`wallet join` should be replaced with simply `join`. All wallet-related events
(`tx`, `confirmed`, etc) now receive the wallet ID as the first argument. The
`tx` event will receive `[id, details]` instead of `[details]`.
The `_admin` endpoints have been moved up a level. Instead of requesting
`/wallet/_admin/backup` (for example), request `/backup` instead. If
`--wallet-auth` is enabled, a new flag `--admin-token` is accepted. Admin token
is a 64 character hex string and allows access to all admin routes. For
example, `GET /backup?token=xxx...`. It also allows access to any wallet on the
HTTP or websocket layer (websockets who use the admin token can join a wallet
of `*`, which notifies them of events on _all_ wallets).
### Notable changes
- __wallet/http__ - A `conflict` event will be correctly emitted for _all_
double spends.
- __wallet/http__ - Account balances are now indexed and will appear on account
objects via the API.
- __bcoin__ - Bcoin has been rewritten using class syntax. Objects will not be
inheritable with legacy prototypal inheritance.
- __pkg__ - Bcoin is once again buildable with browserify.
- __pkg__ - Numerous modules have been moved out to separate dependencies. For
example, the `lib/crypto` module has been moved to the `bcrypto` package (and
also heavily optimized even further).
- __bcoin__ - The main `bcoin` module has been rewritten in terms of what it
exposes and how. Conventions have changed (`Address` instead of `address`).
Due to the use of class syntax, something like `bcoin.Address(str)` is no
longer possible. Please take a look at `lib/bcoin.js` to get a better idea of
what has changed.
- __net__ - Support for BIP151 and BIP150 has been dropped.
## v1.0.0-beta.15
### Notable changes
## v1.0.0-beta.14
### Notable changes
- __pkg__ - Ignored `bcoin*` files in npmignore have been removed. This fixes
the npm install.
## v1.0.0-beta.13
### Notable changes
- __config__ - Options using megabyte units are now calculated properly again
(6182df044228f9215938e7d314435f3f2640acca,
a630d23a97b68f189a85105856fedc4e9e515754,
7728a0047053d4c368e60426e5fc7cc812d54caf).
- __address__ - Bech32 addresses are now supported
(6acef06cbc87a3051ba238a2fb640562e718135e). This changes the semantics of
the `Address` object: to support bech32, `Address.fromBase58` calls should be
replaced with `Address.fromString`. Likewise, `addr.toBase58` calls should
be replaced with `addr.toString`
- __rpc__ - `getblockbyheight` is now exposed via JSON-RPC. It takes the same
parameters as the `getblock` call, requiring a height instead of block hash
(12d3ee6f9582afa9a3ba8984c63dcbc27b8db57e).
- __bin__ - `bcoin --version` and `bcoin --help` now exit with appropriate
messages (f2f94a800e37c5dbdda6920fa6b85fbd485c212a).
- __net__ - The p2p pool now exposes an `--only` option
(a1d0948f2e528c5d77d6502659fafd064b1e693b).
- __mempool__ - The mempool `indexAddress` option should now work correctly
(fba9b46d253c19bbf8e662d9d75ab03dc9e20a78).
- __rpc__ - JSON-RPC calls now properly cast booleans a la bitcoin core
(dd49ee076196d2353783e3044185165dbac4aeb9).
- __rpc__ - Various RPC calls have been improved and updated
(c78707ed6a71ce46c41c4e43ecb505e78a84b380,
c1e684dc12d0a86573a905d54d4f81fce921987a,
5bde338a53117b1bd0fd92df0abc23d95180ab32).
- __rpc__ - Retroactive pruning is now available via the `pruneblockchain` call
(f0bc6d5925419ba4a8289fa7828efc48ecc152d4).
- __http__ - Getting block by height via the Rest API now works again
(df4c8cc68c965bd818a5004354d2652751d4a702).
- __net__ - Peers who serve invalid orphans are now punished properly
(0ceca23cb5a3d724c79c6bf587ede5d473df8486).
- __utils__ - An implementation of GCS filters is now supported
(b994c278f25408886c3095d0c24123baaf07f78f).
- __http__ - The `witness` option is now properly exposed on the Rest API for
segwit wallets (f04ad612b216becd35765c6e231f7820c7eee358).
- __deps__ - Node.js >=v7.6.0 is now a required dependency
(a0bd9680fed07c5eb37c227d160b0868f8adaf31).
- __build__ - The browser build has switched from browserify to webpack
(19f236f74072d473123d20282d2119f6d9130458).
- __bcoin__ - The codebase has been rewritten to use all ES6 and ES7 features
supported by node.js
(aa05bb5df79d9a3af53060a4c0c066226f6e9e4c,
78d62c73b82e1953999d1cf80c90ed2035d4996e,
e00472891df5934d8fc3aa63662f852816aa86b0,
c53f4cf89e46d9de8ab7f65430310567558fe03f,
8c7279518f5341a2482a79ac98f0574468541edc).
- __workers__ - The worker pool has been refactored to solve the dissonance
between the browser and node.js (27c60ce76e57af1695d78f912227d93194812c88).
- __net__ - DNS requests should now timeout sooner
(647b6909c6d527eb82f6d789c88a23b2f8a60126).
- __http__ - Satoshi values are now required for all JSON serialization, as
opposed to BTC strings which were used in the past
(2f51fd1c5066f194a5a52383f4dd45497b882706).
- __bin__ - The `--no-wallet` flag is now exposed for nodes who want to run
without a wallet.
- __chain__ - BIP91 support is now exposed via the `--bip91` option. The
`segwit` and `segsignal` rules will be automatically added when calling
`getblocktemplate`. To enable bip91 on an existing database `--force-flags`
must be passed. This will force bip91 to be enforced, but will not invalidate
any previous blocks (`bcoin cli reset [height]` may need to be used).
- __chain__ - BIP148 support is now exposed via the `--bip148` option. This
likewise must be enabled with `--force-flags` on existing chains. This has
the same potential "reset" implications as the `--bip91` option.
### Migrating
This release contains a few non-backward-compatible changes.
Bcoin now requires node.js >=7.6.0 due to the use of ES6/7 features, and for
the sake of more stability.
Bcoin's rest API now assumes satoshi values for in all JSON serialization.
__This is a breaking change__ for code that is not aware of it. All code which
hits the rest API must be updated to use only satoshi values as opposed to BTC
strings.
In other words, this:
``` json
{
"unconfirmed": "1.12",
"confirmed": "1.12"
}
```
Becomes this:
``` json
{
"unconfirmed": 112000000,
"confirmed": 112000000
}
```
## v1.0.0-beta.12
### Notable changes
- __networks__ - Fixed simnet wpkh prefix.
- __http__ - `wallet join` without wallet auth has been fixed for responses.
This was causing a hanging issue with the client.
## v1.0.0-beta.11
### Notable changes
- __networks__ - Simnet params have been fixed.
- __cli__ - Chain reset call has been fixed.
## v1.0.0-beta.10
### Notable changes
- __wallet/http__ - Create wallet route modified
(`POST /wallet/:id?` changed to `PUT /wallet/:id`).
- __wallet/http__ - Create account route modified
(`POST /wallet/:id/account/:account?` changed to
`PUT /wallet/:id/account/:account`).
- __wallet/http__ - `auth` socket.io event name for wallet auth changed to
`wallet auth`.
- __config__ - `payout-address` option was changed to `coinbase-address`.
- __node__ - Plugin system is now exposed.
See https://github.com/bcoin-org/bcoin/pull/156.
- __config__ - The internal API for the config object has been rewritten
and is now more reusable, particularly by node plugins.
- __http/rpc__ - Both the HTTPBase and RPCBase objects now allow "mounting" by
other rpc and http servers.
- __wallet__ - The wallet code has been completely removed from the node, and
now resides entirely within one module. The wallet is exposed only as a
plugin or a separate server.
- __rpc__ - `prioritisetransaction` is now exposed properly (`deltaFee`s are
now tracked on mempool entries).
- __rpc__ - Proper `id` and error codes are now implemented.
- __rpc__ - Several `getblocktemplate` improvements have been implemented for
more accuracy. e.g. `curtime` will now be updated each call.
- __mining__ - The internal miner API has been rewritten, and now mimics
stratum in a sense.
- __chain__ - Faster verification with checkpoints.
- __net__ - Fixed a potential block stalling issue.
- __net__ - Hardcoded seeds for main added. Makes
for better shipping with browsers.
- __wsproxy/proxysocket__ - DNS resolution is no longer exposed.
- __logger__ - Log files now trim to 20mb on boot.
- __hostlist__ - A persistent `hosts` file is now written by default.
## v1.0.0-beta.9
### Notable changes
- __mempool__ - Trimming now removes dependency chains by cumulative fee rate.
- __mempool__ - Cumulative descendant fees are now updated properly when
removing a transaction.
- __net__ - Preliminary upnp support for adding port mappings.
- __chain/mempool/miner__ - Various atomicity fixes and extra sanity checking.
- __pool/peer__ - Peer height is now tracked and exposed on the RPC as
`bestheight`.
## v1.0.0-beta.8
### Notable changes
- __mempool__ - Fixed critical fee estimator bug causing throwing in the
mempool.
## v1.0.0-beta.7
### Notable changes
- __http__ - Always display spent coins in tx routes (e.g. `/tx/[txid]`).
- __mempool__ - An on-disk mempool is now exposed via `--persistent-mempool`
(also makes fee data persistent).
- __chain__ - `chain.add` now takes a `flags` parameter to avoid POW and
non-contextual checks if necessary.
- __net__ - HostList is now potentially persistent with a `hostLocation` option.
- __net__ - Smarter stall behavior and timeouts.
## v1.0.0-beta.6
### Notable changes
- __http__ - Better bitcoind compatability for JSON-RPC.
## v1.0.0-beta.5
### Notable changes
- __miner__ - Better fee rate comparisons.
- __deps__ - Upgrade deps, fix build on arm and windows.
## v1.0.0-beta.4
### Notable changes
- __miner__ - Optimized TX sorting.
- __rpc__ - Improved getblocktemplate to provide more
accurate results to bitcoind.
## v1.0.0-beta.3
### Notable changes
- __miner__ - Improved fee rate sorting.
- __rpc__ - Fix incompatibilities in rpc api (getblocktemplate & submitblock).
## v1.0.0-beta.2
### Notable changes
- __pool__ - Increase max header chain failures to 500 (prevents the initial
sync from reverting to getblocks so frequently).
## v1.0.0-beta.1
### Notable changes
- __wsproxy__: Fixed proof of work handling in websocket proxy (43c491b).
- __chain__: Optimized MTP and network target calculations (1e07d1b).
- __wallet__: Implemented "smart" coin selection (304f0e7e).
- __protocol__: Increased default network fees for main (09c2357).
- __http__: Fix for handling `DELETE` http method (393dd5d).
- __miner__: Improved handling of default reserved size and sigops (f2964e0
and 7104e4c).
## v1.0.0-beta
### Notable changes
- Initial tagged release.

18
Dockerfile Normal file
View File

@ -0,0 +1,18 @@
FROM alpine:edge
MAINTAINER Steven Bower <steven@purse.io>
RUN apk update && \
apk upgrade
RUN apk add nodejs bash unrar git python build-base make
RUN mkdir /code /data
ADD . /code
WORKDIR /code
RUN npm install --production
RUN npm uninstall node-gyp
RUN apk del unrar git python build-base make && \
rm /var/cache/apk/*
CMD ["node", "/code/bin/node"]

View File

@ -2,7 +2,7 @@ This software is licensed under the MIT License.
Copyright (c) 2014-2015, Fedor Indutny (https://github.com/indutny)
Copyright (c) 2014-2017, Christopher Jeffrey (https://github.com/chjj)
Copyright (c) 2014-2016, Christopher Jeffrey (https://github.com/chjj)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

11
Makefile Normal file
View File

@ -0,0 +1,11 @@
all:
@npm run browserify
@npm run uglify
clean:
@npm run clean
test:
@npm test
.PHONY: all clean test

710
README.md
View File

@ -1,67 +1,668 @@
# Fcoin (Bcoin ported to Lcoin ported to Flo)
# BCoin
## Differences between this repo and [bcoin-org/bcoin](https://github.com/bcoin-org/bcoin)
**BCoin** is a bitcoin library which can also act as an SPV node or a full
node. It is consensus aware and is up to date with the latest BIPs: it supports
segregated witness, versionbits, CSV, and compact block relay. It also has
preliminary support for bip151 (peer-to-peer encryption), bip150 (peer auth),
and bip114 (MAST). It runs in node.js, but it can also be browserified.
* Based on latest bcoin repo, pick flo related commits from bcoin-org/fcoin, applied some modifications and fixed more tests.
* **May rebase and `push --force` frequently, to catch up with bcoin and make repo easy to maintain.**
Try it in the browser: http://bcoin.io/browser.html
## TODO
## Features
* [ ] Fix tests:
* [ ] block-test
* [ ] tx-test
## Fcoin
__NOTE__: The latest release of fcoin contains a non-backward compatible change
to the rest API. Please read the [changelog]'s "migrating" section for more
details.
---
**Fcoin** is an alternative implementation of the flo protocol, written in
node.js.
Bcoin, the parent project, is well tested and aware of all known consensus rules. It is currently
used in production as the consensus backend and wallet system for
[purse.io][purse].
## Uses
- Full Node
- SPV Node
- Wallet Backend (bip44 derivation)
- Mining Backend (getblocktemplate support)
- Layer 2 Backend (lightning)
- General Purpose Bitcoin Library
Try it in the browser: [https://bcoin.io/browser/](https://bcoin.io/browser/)
- Browserifiable
- Full blockchain validation
- Blockchain database
- Mempool/Miner
- Wallet system & wallet database (HD keys w/ bip44 derivation)
- Bitcoind-compatible JSON rpc api
- REST api
- Support for: Versionbits, CSV, Segwit, BIP70, BIP151, BIP152, BIP150,
and MAST.
- SPV mode
## Install
```
$ git clone git://github.com/oipwg/fcoin.git
$ cd fcoin
$ git clone git://github.com/bcoin-org/bcoin.git
$ cd bcoin
$ npm install
$ ./bin/fcoin
$ bcoin --fast
```
See the [Getting started][guide] guide for more in-depth installation
instructions, including verifying releases.
Note that the latest BCoin has not been published to NPM yet, as it is still
under fairly heavy development (which may involve changing serialization
formats for the database).
## Documentation
- General docs: [docs/](docs/README.md)
- Wallet and node API docs: https://bcoin.io/api-docs/
- Library API docs: https://bcoin.io/docs/
Read the docs here: http://bcoin.io/docs/
## Support
## Example Usage
Join us on [freenode][freenode] in the [#bcoin][irc] channel.
- [CLI Usage](#cli-usage)
- [Creating a blockchain and mempool](#creating-a-blockchain-and-mempool)
- [Connecting to the P2P network](#connecting-to-the-p2p-network)
- [Doing an SPV sync](#doing-an-spv-sync)
- [High-level usage with the Node object](#high-level-usage-with-the-node-object)
- [Running the default full node](#running-the-default-full-node)
- [Running a full node in the browser](#running-a-full-node-in-the-browser)
### CLI Usage
``` 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 cli wallet get
# View transaction history
$ bcoin cli wallet history
# Send a transaction
$ bcoin cli wallet send [address] 0.01
# View balance
$ bcoin cli wallet balance
# Derive new address
$ bcoin cli wallet address
# Create a new account
$ bcoin cli wallet account create foo
# Send from account
$ bcoin cli wallet send [address] 0.01 --account=foo
```
#### RPC (bitcoind-like)
``` bash
$ bcoin rpc getblockchaininfo
$ bcoin rpc getwalletinfo
$ bcoin rpc getpeerinfo
$ bcoin rpc getbalance
$ bcoin rpc listtransactions
$ bcoin rpc sendtoaddress [address] 0.01
```
### Creating a blockchain and mempool
``` js
var bcoin = require('bcoin');
bcoin.set({
// Default network (so we can avoid passing
// the `network` option into every object below.
network: 'regtest',
// Enable the global worker pool
// for mining and transaction verification.
useWorkers: true
});
// Start up a blockchain, mempool, and miner using in-memory
// databases (stored in a red-black tree instead of on-disk).
var chain = new bcoin.chain({ db: 'memory' });
var mempool = new bcoin.mempool({ chain: chain });
var miner = new bcoin.miner({ chain: chain, mempool: mempool });
// Open the miner (initialize the databases, etc).
// Miner will implicitly call `open` on chain and mempool.
miner.open().then(function() {
// Create a block "attempt".
return miner.createBlock();
}).then(function(attempt) {
// Mine the block on the worker pool (use mine() for the master process)
return attempt.mineAsync();
}).then(function(block) {
// Add the block to the chain
console.log('Adding %s to the blockchain.', block.rhash);
console.log(block);
return chain.add(block);
}).then(function() {
console.log('Added block!');
});
```
### Connecting to the P2P network
``` js
var bcoin = require('bcoin').set('main');
// Create a blockchain and store it in leveldb.
// `db` also accepts `rocksdb` and `lmdb`.
var prefix = process.env.HOME + '/my-bcoin-environment';
var chain = new bcoin.chain({ db: 'leveldb', location: prefix + '/chain' });
var mempool = new bcoin.mempool({ chain: chain });
// Create a network pool of peers with a limit of 8 peers.
var pool = new bcoin.pool({ chain: chain, mempool: mempool, maxPeers: 8 });
// Open the pool (implicitly opens mempool and chain).
pool.open().then(function() {
// Connect, start retrieving and relaying txs
pool.connect();
// Start the blockchain sync.
pool.startSync();
// Watch the action
chain.on('block', function(block) {
console.log('Connected block to blockchain:');
console.log(block);
});
mempool.on('tx', function(tx) {
console.log('Added tx to mempool:');
console.log(tx);
});
pool.on('tx', function(tx) {
console.log('Saw transaction:');
console.log(tx.rhash);
});
});
// Start up a segnet4 sync in-memory
// while we're at it (because we can).
var tchain = new bcoin.chain({
network: 'segnet4',
db: 'memory'
});
var tmempool = new bcoin.mempool({
network: 'segnet4',
chain: tchain
});
var tpool = new bcoin.pool({
network: 'segnet4',
chain: tchain,
mempool: tmempool,
size: 8
});
tpool.open().then(function() {
// Connect, start retrieving and relaying txs
tpool.connect();
// Start the blockchain sync.
tpool.startSync();
tchain.on('block', function(block) {
console.log('Added segnet4 block:');
console.log(block);
});
tmempool.on('tx', function(tx) {
console.log('Added segnet4 tx to mempool:');
console.log(tx);
});
tpool.on('tx', function(tx) {
console.log('Saw segnet4 transaction:');
console.log(tx);
});
});
```
### Doing an SPV sync
``` js
var bcoin = require('bcoin').set('testnet');
// SPV chains only store the chain headers.
var chain = new bcoin.chain({
db: 'leveldb',
location: process.env.HOME + '/spvchain',
spv: true
});
var pool = new bcoin.pool({
chain: chain,
spv: true,
maxPeers: 8
});
var walletdb = new bcoin.walletdb({ db: 'memory' });
pool.open().then(function() {
return walletdb.open();
}).then(function() {
return walletdb.create();
}).then(function(wallet) {
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
pool.connect();
// Start the blockchain sync.
pool.startSync();
pool.on('tx', function(tx) {
wallet.addTX(tx);
});
wallet.on('balance', function(balance) {
console.log('Balance updated.');
console.log(bcoin.utils.btc(balance.unconfirmed));
});
});
```
### High-level usage with the Node object
``` js
var bcoin = require('bcoin').set('main');
var node = bcoin.fullnode({
prune: false,
useCheckpoints: true,
debug: true,
// Primary wallet passphrase
passsphrase: 'node',
logLevel: 'info'
});
// We get a lot of errors sometimes,
// usually from peers hanging up on us.
// Just ignore them for now.
node.on('error', function(err) {
;
});
// Start the node
node.open().then(function() {
// Create a new wallet (or get an existing one with the same ID)
var options = {
id: 'mywallet',
passphrase: 'foo',
witness: false,
type: 'pubkeyhash'
};
return node.walletdb.create(options);
}).then(function(wallet) {
console.log('Created wallet with address: %s', wallet.getAddress('base58'));
// Start syncing the blockchain
node.startSync();
// Wait for balance and send it to a new address.
wallet.once('balance', function(balance) {
// Create a transaction, fill
// it with coins, and sign it.
var options = {
subtractFee: true,
outputs: [{
address: newReceiving,
value: balance.total
}]
};
wallet.createTX(options).then(function(tx) {
// Need to pass our passphrase back in to sign!
return wallet.sign(tx, 'foo');
}).then(function(tx) {
console.log('sending tx:');
console.log(tx);
return node.sendTX(tx);
}).then(function() {
console.log('tx sent!');
});
});
});
node.chain.on('block', function(block) {
;
});
node.mempool.on('tx', function(tx) {
;
});
node.chain.on('full', function() {
node.mempool.getHistory().then(console.log);
});
```
### Running the default full node
``` bash
$ bcoin --fast
```
`--fast` will enable checkpoints, coin cache, and getheaders.
Your config file should reside in `~/.bcoin/bcoin.conf`. See `etc/sample.conf`
for an example.
### 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.
## TX creation
Normal transactions in bcoin are immutable. The primary TX object contains a
bunch of consensus and policy checking methods. A lot of it is for internal use
and pretty boring for users of this library.
BCoin also offers a mutable transaction object (MTX). Mutable transactions
inherit from the TX object, but can also be signed and modified.
``` js
var bcoin = require('bcoin');
var assert = require('assert');
var constants = bcoin.constants;
// Create an HD master keypair with a mnemonic.
var master = bcoin.hd.fromMnemonic();
// Derive another private hd key (we don't want to use our master key!).
var key = master.derive('m/44/0/0/0/0');
// Create a "keyring" object. A keyring object is basically a key manager that
// is also able to tell you info such as: your redeem script, your scripthash,
// your program hash, your pubkey hash, your scripthash program hash, etc.
// In this case, we'll make it simple and just add one key for a
// pubkeyhash address. `getPublicKey` returns the non-hd public key.
var keyring = new bcoin.keyring(key.privateKey);
console.log(keyring.getAddress());
// Create a fake coinbase for our funding.
var cb = new bcoin.mtx();
// Add a typical coinbase input
cb.addInput({
prevout: {
hash: constants.NULL_HASH,
index: 0
},
script: new bcoin.script(),
sequence: 0xffffffff
});
// Send 50,000 satoshis to ourself.
cb.addOutput({
address: keyring.getAddress(),
value: 50000
});
// Create our redeeming transaction.
var tx = new bcoin.mtx();
// Add output 0 from our coinbase.
tx.addInput(cb, 0);
// Send 10,000 satoshis to ourself,
// creating a fee of 40,000 satoshis.
tx.addOutput({
address: keyring.getAddress(),
value: 10000
});
// Sign input 0: pass in our keyring.
tx.sign(keyring);
// Commit our transaction and make it immutable.
// This turns it from an MTX into a TX object.
tx = tx.toTX();
// The transaction should now verify.
assert(tx.verify());
assert(tx.getFee() === 40000);
```
### Coin Selection
The above method works, but is pretty contrived. In reality, you probably
wouldn't select inputs and calculate the fee by hand. You would want a
change output added. BCoin has a nice method of dealing with this.
Let's try it more realistically:
``` js
var bcoin = require('bcoin');
var assert = require('assert');
var constants = bcoin.constants;
var master = bcoin.hd.fromMnemonic();
var key = master.derive('m/44/0/0/0/0');
var keyring = new bcoin.keyring(key.privateKey);
var cb = new bcoin.mtx();
cb.addInput({
prevout: {
hash: constants.NULL_HASH,
index: 0
},
script: new bcoin.script(),
sequence: 0xffffffff
});
// Send 50,000 satoshis to ourselves.
cb.addOutput({
address: keyring.getAddress(),
value: 50000
});
// Our available coins.
var 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.
var coin = bcoin.coin.fromTX(cb, 0);
coins.push(coin);
// Create our redeeming transaction.
var tx = new bcoin.mtx();
// Send 10,000 satoshis to ourself.
tx.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.
tx.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
tx.sign(keyring);
// Commit our transaction and make it immutable.
// This turns it from an MTX into a TX.
tx = tx.toTX();
// The transaction should now verify.
assert(tx.verify());
```
## Scripting
Scripts are array-like objects with some helper functions.
``` js
var bcoin = require('bcoin');
var assert = require('assert');
var BN = bcoin.bn;
var opcodes = bcoin.script.opcodes;
var output = new bcoin.script();
output.push(opcodes.OP_DROP);
output.push(opcodes.OP_ADD);
output.push(new BN(7));
output.push(opcodes.OP_NUMEQUAL);
// Compile the script to its binary representation
// (you must do this if you change something!).
output.compile();
assert(output.getSmall(2) === 7); // compiled as OP_7
var input = new bcoin.script();
input.set(0, 'hello world'); // add some metadata
input.push(new BN(2));
input.push(new BN(5));
input.push(input.shift());
assert(input.getString(2) === 'hello world');
input.compile();
// A stack is another array-like object which contains
// only Buffers (whereas scripts contain Opcode objects).
var stack = new bcoin.stack();
input.execute(stack);
output.execute(stack);
// Verify the script was successful in its execution:
assert(stack.length === 1);
assert(bcoin.script.bool(stack.pop()) === true);
```
Using a witness would be similar, but witnesses do not get executed, they
simply _become_ the stack. The witness object itself is very similar to the
Stack object (an array-like object containing Buffers).
``` js
var witness = new bcoin.witness();
witness.push(new BN(2));
witness.push(new BN(5));
witness.push('hello world');
var stack = witness.toStack();
output.execute(stack);
```
## Wallet usage
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.
TODO
## HTTP API & Websocket Events
TODO
## 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
descision.
#### 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
visting a webpage.
## Disclaimer
Fcoin does not guarantee you against theft or lost funds due to bugs, mishaps,
BCoin does not guarantee you against theft or lost funds due to bugs, mishaps,
or your own incompetence. You and you alone are responsible for securing your
money.
@ -73,18 +674,13 @@ all code is your original work. `</legalese>`
## License
- Copyright (c) 2014-2015, Fedor Indutny (MIT License).
- Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
Copyright (c) 2014-2015, Fedor Indutny (MIT License).
Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
See LICENSE for more info.
[purse]: https://purse.io
[guide]: docs/getting-started.md
[freenode]: https://freenode.net/
[irc]: irc://irc.freenode.net/bcoin
[changelog]: CHANGELOG.md
[coverage-status-img]: https://codecov.io/gh/bcoin-org/bcoin/badge.svg?branch=master
[coverage-status-url]: https://codecov.io/gh/bcoin-org/bcoin?branch=master
[circleci-status-img]: https://circleci.com/gh/bcoin-org/bcoin/tree/master.svg?style=shield
[circleci-status-url]: https://circleci.com/gh/bcoin-org/bcoin/tree/master
[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

20
TODO.md Normal file
View File

@ -0,0 +1,20 @@
# Todo
Todo before release. Excuse the mess.
- prioritization for mining.
- switch entirely to secp256k1-node. note that payment-protocol still directly
requires elliptic.
- walletdb removes coins from txs - potentially have it clone the tx (slower).
- refactor and add all network packets.
- rename keyring object.
- browser-side dsa signing/verify for payment-protocol.
- do not output bitcoin strings (utils.btc) on the api layer. use satoshis
instead.
- implement jl's latest MAST.
- rewrite readme. move examples to wiki.
- fix docs.
- implement rpc calls:
- listaddressgroupings
- importaddress (maybe)
- man pages

View File

@ -1,27 +0,0 @@
'use strict';
const Address = require('../lib/primitives/address');
const random = require('bcrypto/lib/random');
const bench = require('./bench');
const addrs = [];
{
const end = bench('serialize');
for (let i = 0; i < 100000; i++) {
const addr = Address.fromProgram(0, random.randomBytes(20));
addrs.push(addr.toBech32());
}
end(100000);
}
{
const end = bench('parse');
for (let i = 0; i < 100000; i++) {
const b32 = addrs[i];
const addr = Address.fromBech32(b32);
addrs[i] = addr;
}
end(100000);
}
console.error(addrs[0][0]);

View File

@ -1,11 +1,11 @@
'use strict';
module.exports = function bench(name) {
const start = process.hrtime();
var start = process.hrtime();
return function end(ops) {
const elapsed = process.hrtime(start);
const time = elapsed[0] + elapsed[1] / 1e9;
const rate = ops / time;
var elapsed = process.hrtime(start);
var time = elapsed[0] + elapsed[1] / 1e9;
var rate = ops / time;
console.log('%s: ops=%d, time=%d, rate=%s',
name, ops, time, rate.toFixed(5));

View File

@ -1,476 +0,0 @@
/*!
* bench/blockstore.js - benchmark blockstore for bcoin
*
* This can be run to benchmark the performance of the blockstore
* module for writing, reading and pruning block data. Results are
* written to stdout as JSON or formated bench results.
*
* Usage:
* node ./blockstore.js [--maxfile=<bytes>] [--total=<bytes>]
* [--location=<path>] [--store=<name>]
* [--output=<name>] [--unsafe]
*
* Options:
* - `maxfile` The maximum file size (applies to "file" store).
* - `total` The total number of block bytes to write.
* - `location` The location to store block data.
* - `store` This can be "file" or "level".
* - `output` This can be "json", "bench" or "benchjson".
* - `unsafe` This will allocate block data directly from memory
* instead of random, it is faster.
*
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
process.title = 'blockstore-bench';
const {isAbsolute} = require('path');
const {mkdirp} = require('bfile');
const random = require('bcrypto/lib/random');
const {BufferMap} = require('buffer-map');
const {
FileBlockStore,
LevelBlockStore
} = require('../lib/blockstore');
const config = {
'maxfile': {
value: true,
parse: a => parseInt(a),
valid: a => Number.isSafeInteger(a),
fallback: 128 * 1024 * 1024
},
'total': {
value: true,
parse: a => parseInt(a),
valid: a => Number.isSafeInteger(a),
fallback: 3 * 1024 * 1024 * 1024
},
'location': {
value: true,
valid: a => isAbsolute(a),
fallback: '/tmp/bcoin-bench-blockstore'
},
'store': {
value: true,
valid: a => (a === 'file' || a === 'level'),
fallback: 'file'
},
'output': {
value: true,
valid: a => (a === 'json' || a === 'bench' || a === 'benchjson'),
fallback: 'bench'
},
'unsafe': {
value: false,
valid: a => (a === true || a === false),
fallback: false
}
};
/**
* These block sizes were generated from bitcoin mainnet blocks by putting
* sizes into bins of 256 ^ (2 * n) as the upper bound and calculating
* the percentage of each and then distributing to roughly match the
* percentage of the following:
*
* |-------------|------------|
* | percentage | bytes |
* |-------------|------------|
* | 23.4055 | 1048576 |
* | 15.5338 | 256 |
* | 12.2182 | 262144 |
* | 8.4079 | 524288 |
* | 7.1289 | 131072 |
* | 6.9197 | 65536 |
* | 6.7073 | 2097152 |
* | 4.6753 | 32768 |
* | 3.9695 | 4096 |
* | 3.3885 | 16384 |
* | 2.6526 | 8192 |
* | 2.0048 | 512 |
* | 1.587 | 1024 |
* | 1.3976 | 2048 |
* | 0.0032 | 4194304 |
* |-------------|------------|
*/
const distribution = [
1048576, 256, 256, 524288, 262144, 256, 131072, 256, 524288, 256, 131072,
1048576, 262144, 1048576, 2097152, 256, 1048576, 65536, 256, 262144, 8192,
32768, 32768, 256, 1048576, 524288, 2097152, 1024, 1048576, 1048576, 131072,
131072, 262144, 512, 1048576, 1048576, 1024, 1048576, 1048576, 262144, 2048,
262144, 256, 1048576, 131072, 4096, 524288, 65536, 4096, 65536, 131072,
2097152, 2097152, 2097152, 256, 524288, 4096, 262144, 65536, 65536, 262144,
16384, 1048576, 32768, 262144, 1048576, 256, 131072, 1048576, 1048576,
1048576, 8192, 1048576, 256, 16384, 1048576, 256, 256, 524288, 256, 32768,
16384, 32768, 1048576, 512, 4096, 1048576, 1048576, 524288, 65536, 2097152,
512, 262144, 8192, 524288, 131072, 65536, 16384, 2048, 262144, 1048576,
1048576, 256, 524288, 262144, 4194304, 262144, 2097152
];
(async () => {
let settings = null;
try {
settings = processArgs(process.argv, config);
} catch (err) {
console.log(err.message);
process.exit(1);
}
await mkdirp(settings.location);
let store = null;
let output = null;
if (settings.store === 'file') {
store = new FileBlockStore({
location: settings.location,
maxFileLength: settings.maxfile
});
} else if (settings.store === 'level') {
store = new LevelBlockStore({
location: settings.location
});
}
if (settings.output === 'bench') {
output = new BenchOutput();
} else if (settings.output === 'benchjson') {
output = new BenchJSONOutput();
} else if (settings.output === 'json') {
output = new JSONOutput();
}
await store.open();
const hashes = [];
const lengths = new BufferMap();
output.start();
// 1. Write data to the block store
let written = 0;
async function write() {
for (const length of distribution) {
const hash = random.randomBytes(32);
let raw = null;
if (settings.unsafe) {
raw = Buffer.allocUnsafe(length);
} else {
raw = random.randomBytes(length);
}
const start = process.hrtime();
await store.write(hash, raw);
const elapsed = process.hrtime(start);
hashes.push(hash);
lengths.set(hash, length);
written += length;
output.result('write', start, elapsed, length);
if (written >= settings.total)
break;
}
}
while (written < settings.total)
await write();
// 2. Read data from the block store
for (const hash of hashes) {
const start = process.hrtime();
const raw = await store.read(hash);
const elapsed = process.hrtime(start);
output.result('read', start, elapsed, raw.length);
}
// 3. Read data not in the order it was written (random)
for (let i = 0; i < hashes.length; i++) {
const rand = random.randomInt() / 0xffffffff * (hashes.length - 1) | 0;
const hash = hashes[rand];
const start = process.hrtime();
const raw = await store.read(hash);
const elapsed = process.hrtime(start);
output.result('randomread', start, elapsed, raw.length);
}
// 4. Prune data from the block store
for (const hash of hashes) {
const start = process.hrtime();
await store.prune(hash);
const elapsed = process.hrtime(start);
const length = lengths.get(hash);
output.result('prune', start, elapsed, length);
}
output.end();
await store.close();
})().catch((err) => {
console.error(err);
process.exit(1);
});
class JSONOutput {
constructor() {
this.time = process.hrtime();
this.index = 0;
}
start() {
process.stdout.write('[');
}
result(type, start, elapsed, length) {
if (this.index > 0)
process.stdout.write(',');
const since = [start[0] - this.time[0], start[1] - this.time[1]];
const smicro = hrToMicro(since);
const emicro = hrToMicro(elapsed);
process.stdout.write(`{"type":"${type}","start":${smicro},`);
process.stdout.write(`"elapsed":${emicro},"length":${length},`);
process.stdout.write(`"index":${this.index}}`);
this.index += 1;
}
end() {
process.stdout.write(']');
}
}
class BenchOutput {
constructor() {
this.time = process.hrtime();
this.index = 0;
this.results = {};
this.interval = null;
this.stdout = process.stdout;
}
start() {
this.stdout.write('Starting benchmark...\n');
this.interval = setInterval(() => {
this.stdout.write(`Operation count=${this.index}\n`);
}, 5000);
}
result(type, start, elapsed, length) {
const micro = hrToMicro(elapsed);
if (!this.results[type])
this.results[type] = {};
if (!this.results[type][length])
this.results[type][length] = [];
this.results[type][length].push(micro);
this.index += 1;
}
end() {
clearInterval(this.interval);
this.stdout.write('Benchmark finished.\n');
function format(value) {
if (typeof value === 'number')
value = value.toFixed(2);
if (typeof value !== 'string')
value = value.toString();
while (value.length < 15)
value = `${value} `;
return value;
}
function title(value) {
if (typeof value !== 'string')
value = value.toString();
while (value.length < 85)
value = ` ${value} `;
if (value.length > 85)
value = value.slice(0, 85);
return value;
}
for (const type in this.results) {
this.stdout.write('\n');
this.stdout.write(`${title(type)}\n`);
this.stdout.write(`${'='.repeat(85)}\n`);
this.stdout.write(`${format('length')}`);
this.stdout.write(`${format('operations')}`);
this.stdout.write(`${format('min')}`);
this.stdout.write(`${format('max')}`);
this.stdout.write(`${format('average')}`);
this.stdout.write(`${format('median')}`);
this.stdout.write('\n');
this.stdout.write(`${'-'.repeat(85)}\n`);
for (const length in this.results[type]) {
const cal = calculate(this.results[type][length]);
this.stdout.write(`${format(length)}`);
this.stdout.write(`${format(cal.operations.toString())}`);
this.stdout.write(`${format(cal.min)}`);
this.stdout.write(`${format(cal.max)}`);
this.stdout.write(`${format(cal.average)}`);
this.stdout.write(`${format(cal.median)}`);
this.stdout.write('\n');
}
this.stdout.write('\n');
}
this.stdout.write('\n');
}
}
class BenchJSONOutput {
constructor() {
this.time = null;
this.results = {};
this.stdout = process.stdout;
}
start() {
this.time = process.hrtime();
}
result(type, start, elapsed, length) {
const micro = hrToMicro(elapsed);
if (!this.results[type])
this.results[type] = {};
if (!this.results[type][length])
this.results[type][length] = [];
this.results[type][length].push(micro);
}
end() {
const report = {
summary: [],
time: hrToMicro(process.hrtime(this.time)),
elapsed: 0
};
for (const type in this.results) {
for (const length in this.results[type]) {
const cal = calculate(this.results[type][length]);
report.elapsed += cal.total;
report.summary.push({
type: type,
length: length,
operations: cal.operations,
min: cal.min,
max: cal.max,
average: cal.average,
median: cal.median
});
}
}
this.stdout.write(JSON.stringify(report, null, 2));
this.stdout.write('\n');
}
}
function hrToMicro(time) {
return (time[0] * 1000000) + (time[1] / 1000);
}
function calculate(times) {
times.sort((a, b) => a - b);
let min = Infinity;
let max = 0;
let total = 0;
for (const micro of times) {
if (micro < min)
min = micro;
if (micro > max)
max = micro;
total += micro;
}
const average = total / times.length;
const median = times[times.length / 2 | 0];
const operations = times.length;
return {
total,
operations,
min,
max,
average,
median
};
}
function processArgs(argv, config) {
const args = {};
for (const key in config)
args[key] = config[key].fallback;
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i];
const match = arg.match(/^(\-){1,2}([a-z]+)(\=)?(.*)?$/);
if (!match) {
throw new Error(`Unexpected argument: ${arg}.`);
} else {
const key = match[2];
let value = match[4];
if (!config[key])
throw new Error(`Invalid argument: ${arg}.`);
if (config[key].value && !value) {
value = process.argv[i + 1];
i++;
} else if (!config[key].value && !value) {
value = true;
} else if (!config[key].value && value) {
throw new Error(`Unexpected value: ${key}=${value}`);
}
if (config[key].parse)
value = config[key].parse(value);
if (value)
args[key] = value;
if (!config[key].valid(args[key]))
throw new Error(`Invalid value: ${key}=${value}`);
}
}
return args;
}

View File

@ -1,33 +0,0 @@
'use strict';
const BufferWriter = require('bufio').BufferWriter;
const StaticWriter = require('bufio').StaticWriter;
const common = require('../test/util/common');
const bench = require('./bench');
const tx5 = common.readTX('tx5');
{
const [tx] = tx5.getTX();
const end = bench('serialize (static-writer)');
for (let i = 0; i < 10000; i++) {
tx.refresh();
const {size} = tx.getWitnessSizes();
const bw = new StaticWriter(size);
tx.toWriter(bw);
bw.render();
}
end(10000);
}
{
const [tx] = tx5.getTX();
const end = bench('serialize (buffer-writer)');
for (let i = 0; i < 10000; i++) {
tx.refresh();
const bw = new BufferWriter();
tx.toWriter(bw);
bw.render();
}
end(10000);
}

45
bench/chacha.js Normal file
View File

@ -0,0 +1,45 @@
'use strict';
var chachapoly = require('../lib/crypto/chachapoly');
var bench = require('./bench');
console.log('note: rate measured in kb/s');
var chacha = new chachapoly.ChaCha20();
var iv = new Buffer('0102030405060708', 'hex');
chacha.init(iv, 0);
var data = new Buffer(32);
for (var i = 0; i < 32; i++)
data[i] = i;
var end = bench('encrypt');
for (var i = 0; i < 1000000; i++)
chacha.encrypt(data);
end(i * 32 / 1024);
var poly = new chachapoly.Poly1305();
var key = new Buffer('000102030405060708090a0b0c0d0e0f', 'hex');
poly.init(key);
var data = new Buffer(32);
for (var i = 0; i < 32; i++)
data[i] = i & 0xff;
var end = bench('update');
for (var i = 0; i < 1000000; i++)
poly.update(data);
end(i * 32 / 1024);
var end = bench('finish');
for (var i = 0; i < 1000000; i++) {
poly.init(key);
poly.update(data);
poly.finish();
}
end(i * 32 / 1024);
// For reference:
var crypto = require('../lib/crypto/crypto');
var end = bench('sha256');
for (var i = 0; i < 1000000; i++)
crypto.hash256(data);
end(i * 32 / 1024);

42
bench/coin.js Normal file
View File

@ -0,0 +1,42 @@
'use strict';
var BN = require('bn.js');
var constants = require('../lib/protocol/constants');
var utils = require('../lib/utils/utils');
var assert = require('assert');
var scriptTypes = constants.scriptTypes;
var bench = require('./bench');
var fs = require('fs');
var Coins = require('../lib/chain/coins');
var TX = require('../lib/primitives/tx');
var wtx = fs.readFileSync(__dirname + '/../test/data/wtx.hex', 'utf8');
wtx = tx.fromRaw(wtx.trim(), 'hex');
var coins = Coins.fromTX(wtx);
var raw;
var end = bench('serialize');
for (var i = 0; i < 10000; i++)
raw = coins.toRaw();
end(i);
var end = bench('parse');
for (var i = 0; i < 10000; i++)
Coins.fromRaw(raw);
end(i);
var end = bench('parse-single');
var hash = wtx.hash('hex');
for (var i = 0; i < 10000; i++)
Coins.parseCoin(raw, hash, 5);
end(i);
var coins = Coins.fromRaw(raw);
var end = bench('get');
var j;
for (var i = 0; i < 10000; i++)
for (var j = 0; j < coins.outputs.length; j++)
coins.get(j);
end(i * coins.outputs.length);

View File

@ -1,34 +0,0 @@
'use strict';
const CoinView = require('../lib/coins/coinview');
const BufferReader = require('bufio').BufferReader;
const StaticWriter = require('bufio').StaticWriter;
const common = require('../test/util/common');
const bench = require('./bench');
const [tx, view] = common.readTX('tx3').getTX();
{
const end = bench('serialize');
for (let i = 0; i < 10000000; i++) {
const bw = new StaticWriter(view.getSize(tx));
view.toWriter(bw, tx).render();
}
end(10000000);
}
{
const bw = new StaticWriter(view.getSize(tx));
const raw = view.toWriter(bw, tx).render();
const end = bench('parse');
for (let i = 0; i < 10000000; i++) {
const br = new BufferReader(raw);
CoinView.fromReader(br, tx);
}
end(10000000);
}

View File

@ -1,17 +0,0 @@
'use strict';
const random = require('bcrypto/lib/random');
const util = require('../lib/utils/util');
const bench = require('./bench');
const hashes = [];
for (let i = 0; i < 100000; i++)
hashes.push(random.randomBytes(32));
{
const end = bench('hexstring');
for (let i = 0; i < hashes.length; i++)
util.fromRev(util.revHex(hashes[i]));
end(100000);
}

View File

@ -1,22 +0,0 @@
'use strict';
const assert = require('assert');
const merkle = require('bcrypto/lib/merkle');
const random = require('bcrypto/lib/random');
const SHA256 = require('bcrypto/lib/sha256');
const bench = require('./bench');
const leaves = [];
for (let i = 0; i < 3000; i++)
leaves.push(random.randomBytes(32));
{
const end = bench('tree');
for (let i = 0; i < 1000; i++) {
const [n, m] = merkle.createTree(SHA256, leaves.slice());
assert(n);
assert(!m);
}
end(1000);
}

View File

@ -1,20 +1,19 @@
'use strict';
const assert = require('assert');
const bench = require('./bench');
const HD = require('../lib/hd');
const Mnemonic = require('../lib/hd/mnemonic');
var BN = require('bn.js');
var bcoin = require('../').set('main');
var constants = bcoin.constants;
var utils = bcoin.utils;
var assert = require('assert');
var bench = require('./bench');
var Mnemonic = bcoin.hd.Mnemonic;
const mnemonic = new Mnemonic();
HD.fromMnemonic(mnemonic);
var key = bcoin.hd.fromMnemonic();
var phrase = key.mnemonic.getPhrase();
const phrase = mnemonic.getPhrase();
assert.equal(Mnemonic.fromPhrase(phrase).getPhrase(), phrase);
assert.strictEqual(Mnemonic.fromPhrase(phrase).getPhrase(), phrase);
{
const end = bench('fromPhrase');
for (let i = 0; i < 10000; i++)
Mnemonic.fromPhrase(phrase);
end(10000);
}
var end = bench('fromPhrase');
for (var i = 0; i < 10000; i++)
Mnemonic.fromPhrase(phrase);
end(i);

View File

@ -1,17 +1,43 @@
'use strict';
const random = require('bcrypto/lib/random');
const Script = require('../lib/script/script');
const bench = require('./bench');
var BN = require('bn.js');
var bcoin = require('../').set('main');
var constants = bcoin.constants;
var utils = bcoin.utils;
var assert = require('assert');
var scriptTypes = constants.scriptTypes;
var opcodes = constants.opcodes;
var bench = require('./bench');
var fs = require('fs');
var Script = bcoin.script;
const hashes = [];
bcoin.cache();
for (let i = 0; i < 100000; i++)
hashes.push(random.randomBytes(20));
Script.prototype.fromPubkeyhashOld = function fromScripthash(hash) {
assert(Buffer.isBuffer(hash) && hash.length === 20);
this.push(opcodes.OP_DUP);
this.push(opcodes.OP_HASH160);
this.push(hash);
this.push(opcodes.OP_EQUALVERIFY);
this.push(opcodes.OP_CHECKSIG);
this.compile();
return this;
};
{
const end = bench('hash');
for (let i = 0; i < hashes.length; i++)
Script.fromPubkeyhash(hashes[i]);
end(100000);
}
Script.fromPubkeyhashOld = function fromScripthash(hash) {
return new Script().fromPubkeyhashOld(hash);
};
var hashes = [];
for (var i = 0; i < 100000; i++)
hashes.push(bcoin.crypto.randomBytes(20));
var end = bench('old');
for (var i = 0; i < hashes.length; i++)
Script.fromPubkeyhashOld(hashes[i]);
end(i);
var end = bench('hash');
for (var i = 0; i < hashes.length; i++)
Script.fromPubkeyhash(hashes[i]);
end(i);

View File

@ -1,200 +1,131 @@
'use strict';
const random = require('bcrypto/lib/random');
const Address = require('../lib/primitives/address');
const TX = require('../lib/primitives/tx');
const Script = require('../lib/script/script');
const MTX = require('../lib/primitives/mtx');
const consensus = require('../lib/protocol/consensus');
const common = require('../test/util/common');
const bench = require('./bench');
var BN = require('bn.js');
var bcoin = require('../').set('main');
var constants = bcoin.constants;
var utils = bcoin.utils;
var assert = require('assert');
var scriptTypes = constants.scriptTypes;
var bench = require('./bench');
var fs = require('fs');
const tx3 = common.readTX('tx3');
const tx5 = common.readTX('tx5');
const tx10 = common.readTX('tx10');
bcoin.cache();
{
const raw = tx5.getRaw();
const end = bench('parse');
var block = bcoin.block.fromJSON(require('../test/data/block300025.json'));
var btx = block.txs[397];
for (let i = 0; i < 10000; i++)
TX.fromRaw(raw);
var tx1 = parseTX('../test/data/tx3.hex');
var tx4 = parseTX('../test/data/tx4.hex');
var wtx = fs.readFileSync(__dirname + '/../test/data/wtx.hex', 'utf8');
wtx = new Buffer(wtx.trim(), 'hex');
var tx;
end(10000);
}
{
const [tx, view] = tx5.getTX();
const end = bench('sigops');
for (let i = 0; i < 100000; i++)
tx.getSigopsCost(view);
end(100000);
}
{
const [tx] = tx5.getTX();
const end = bench('serialize');
for (let i = 0; i < 10000; i++) {
tx._raw = null;
tx.toRaw();
function parseTX(file) {
file = fs.readFileSync(__dirname + '/' + file, 'utf8').trim().split(/\n+/);
var tx = bcoin.tx.fromRaw(file.shift().trim(), 'hex');
for (var i = 0; i < file.length; i++) {
var coin = bcoin.tx.fromRaw(file[i].trim(), 'hex');
tx.fillCoins(coin);
}
end(10000);
return tx;
}
{
const [tx] = tx3.getTX();
const end = bench('hash');
var end = bench('parse');
for (var i = 0; i < 1000; i++)
tx = bcoin.tx.fromRaw(wtx);
end(i);
for (let i = 0; i < 30000; i++) {
tx.hash();
tx._hash = null;
}
var end = bench('serialize');
var raw;
end(30000);
for (var i = 0; i < 1000; i++) {
tx._raw = null;
raw = tx.toRaw();
}
end(i);
{
const [tx] = tx5.getTX();
const end = bench('witness hash');
for (let i = 0; i < 30000; i++) {
tx.witnessHash();
tx._whash = null;
}
end(30000);
var end = bench('hash');
for (var i = 0; i < 3000; i++) {
tx1.hash();
tx1._hash = null;
}
end(i);
{
const [tx] = tx5.getTX();
const end = bench('sanity');
for (let i = 0; i < 10000; i++)
tx.isSane();
end(10000);
var end = bench('witness hash');
for (var i = 0; i < 3000; i++) {
tx.witnessHash();
tx._whash = null;
}
end(i);
{
const [tx] = tx5.getTX();
const end = bench('input hashes');
var end = bench('fee');
for (var i = 0; i < 1000; i++)
tx.getFee();
end(i);
for (let i = 0; i < 10000; i++)
tx.getInputHashes();
var end = bench('sanity');
for (var i = 0; i < 1000; i++)
tx.isSane();
end(i);
end(10000);
}
var end = bench('input hashes');
for (var i = 0; i < 1000; i++)
tx.getInputHashes('hex');
end(i);
{
const [tx] = tx5.getTX();
const end = bench('output hashes');
var end = bench('output hashes');
for (var i = 0; i < 1000; i++)
tx.getOutputHashes('hex');
end(i);
for (let i = 0; i < 10000; i++)
tx.getOutputHashes();
var end = bench('all hashes');
for (var i = 0; i < 1000; i++)
tx.getHashes('hex');
end(i);
end(10000);
}
var end = bench('verify');
for (var i = 0; i < 3000; i++)
tx1.verify(constants.flags.VERIFY_P2SH);
end(i * tx1.inputs.length);
{
const [tx] = tx5.getTX();
const end = bench('all hashes');
var flags = constants.flags.VERIFY_P2SH | constants.flags.VERIFY_DERSIG;
var end = bench('verify multisig');
for (var i = 0; i < 3000; i++)
btx.verify(flags);
end(i * btx.inputs.length);
for (let i = 0; i < 10000; i++)
tx.getHashes();
var tx = bcoin.mtx();
end(10000);
}
{
const [tx, view] = tx3.getTX();
const end = bench('verify');
for (let i = 0; i < 30000; i++)
tx.verify(view, Script.flags.VERIFY_P2SH);
end(30000 * tx.inputs.length);
}
{
const [tx, view] = tx3.getTX();
const {script} = view.getOutputFor(tx.inputs[0]);
const end = bench('sighash');
for (let i = 0; i < 1000000; i++)
tx.signatureHashV0(0, script, Script.hashType.ALL);
end(1000000);
}
{
const [tx, view] = tx3.getTX();
const end = bench('fee');
for (let i = 0; i < 10000; i++)
tx.getFee(view);
end(10000);
}
{
const [tx, view] = tx10.getTX();
const flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_DERSIG;
const end = bench('verify multisig');
for (let i = 0; i < 30000; i++)
tx.verify(view, flags);
end(30000 * tx.inputs.length);
}
const mtx = new MTX();
for (let i = 0; i < 100; i++) {
mtx.addInput({
for (var i = 0; i < 100; i++) {
tx.addInput({
prevout: {
hash: consensus.ZERO_HASH,
hash: constants.NULL_HASH,
index: 0
},
script: new Script()
.pushData(Buffer.allocUnsafe(9))
.pushData(random.randomBytes(33))
.compile()
script: [
new Buffer(9),
bcoin.crypto.randomBytes(33)
]
});
mtx.addOutput({
address: Address.fromHash(random.randomBytes(20)),
tx.addOutput({
address: bcoin.address.fromHash(bcoin.crypto.randomBytes(20)),
value: 0
});
}
const tx2 = mtx.toTX();
tx = tx.toTX();
{
const end = bench('input hashes');
var end = bench('input hashes');
for (var i = 0; i < 1000; i++)
tx.getInputHashes('hex');
end(i);
for (let i = 0; i < 10000; i++)
tx2.getInputHashes();
var end = bench('output hashes');
for (var i = 0; i < 1000; i++)
tx.getOutputHashes('hex');
end(i);
end(10000);
}
{
const end = bench('output hashes');
for (let i = 0; i < 10000; i++)
tx2.getOutputHashes();
end(10000);
}
{
const end = bench('all hashes');
for (let i = 0; i < 10000; i++)
tx2.getHashes();
end(10000);
}
var end = bench('all hashes');
for (var i = 0; i < 1000; i++)
tx.getHashes('hex');
end(i);

View File

@ -1,132 +1,143 @@
'use strict';
const bench = require('./bench');
const random = require('bcrypto/lib/random');
const WalletDB = require('../lib/wallet/walletdb');
const MTX = require('../lib/primitives/mtx');
const Outpoint = require('../lib/primitives/outpoint');
var BN = require('bn.js');
var bcoin = require('../').set('main');
var constants = bcoin.constants;
var utils = bcoin.utils;
var assert = require('assert');
var scriptTypes = constants.scriptTypes;
var bench = require('./bench');
var co = require('../lib/utils/co');
var crypto = require('../lib/crypto/crypto');
bcoin.cache();
function dummy() {
const hash = random.randomBytes(32);
return new Outpoint(hash, 0);
var hash = crypto.randomBytes(32).toString('hex');
return {
prevout: {
hash: hash,
index: 0
},
coin: {
version: 1,
height: 0,
value: 50460 * 4,
script: new bcoin.script(),
coinbase: false,
hash: hash,
index: 0
},
script: new bcoin.script(),
witness: new bcoin.witness(),
sequence: 0xffffffff
};
}
const walletdb = new WalletDB({
var walletdb = new bcoin.walletdb({
name: 'wallet-test',
// location: __dirname + '/../walletdb-bench',
// db: 'leveldb'
db: 'memory',
resolution: false,
verify: false
});
(async () => {
// Open and Create
await walletdb.open();
var runBench = co(function* runBench() {
var i, j, wallet, addrs, jobs, end;
var result, tx, options;
const wallet = await walletdb.create();
const addrs = [];
let tx;
// Open and Create
yield walletdb.open();
wallet = yield walletdb.create();
addrs = [];
// Accounts
{
const jobs = [];
for (let i = 0; i < 1000; i++)
jobs.push(wallet.createAccount({}));
jobs = [];
for (i = 0; i < 1000; i++)
jobs.push(wallet.createAccount({}));
const end = bench('accounts');
const result = await Promise.all(jobs);
end(1000);
end = bench('accounts');
result = yield Promise.all(jobs);
end(1000);
for (const addr of result)
addrs.push(addr.receiveAddress());
for (i = 0; i < result.length; i++)
addrs.push(result[i].receive.getAddress());
// Addresses
jobs = [];
for (i = 0; i < 1000; i++) {
for (j = 0; j < 10; j++)
jobs.push(wallet.createReceive(i));
}
// Keys
{
const jobs = [];
for (let i = 0; i < 1000; i++) {
for (let j = 0; j < 10; j++)
jobs.push(wallet.createReceive(i));
}
end = bench('addrs');
result = yield Promise.all(jobs);
end(1000 * 10);
const end = bench('keys');
const result = await Promise.all(jobs);
end(1000 * 10);
for (const addr of result)
addrs.push(addr.getAddress());
}
for (i = 0; i < result.length; i++)
addrs.push(result[i].getAddress());
// TX deposit
{
const jobs = [];
for (let i = 0; i < 10000; i++) {
const mtx = new MTX();
mtx.addOutpoint(dummy());
mtx.addOutput(addrs[(i + 0) % addrs.length], 50460);
mtx.addOutput(addrs[(i + 1) % addrs.length], 50460);
mtx.addOutput(addrs[(i + 2) % addrs.length], 50460);
mtx.addOutput(addrs[(i + 3) % addrs.length], 50460);
tx = mtx.toTX();
jobs = [];
for (i = 0; i < 10000; i++) {
tx = bcoin.mtx()
.addInput(dummy())
.addOutput(addrs[(i + 0) % addrs.length], 50460)
.addOutput(addrs[(i + 1) % addrs.length], 50460)
.addOutput(addrs[(i + 2) % addrs.length], 50460)
.addOutput(addrs[(i + 3) % addrs.length], 50460)
.toTX();
jobs.push(walletdb.addTX(tx));
}
const end = bench('deposit');
await Promise.all(jobs);
end(10000);
jobs.push(walletdb.addTX(tx));
}
end = bench('deposit');
result = yield Promise.all(jobs);
end(10000);
// TX redemption
{
const jobs = [];
for (let i = 0; i < 10000; i++) {
const mtx = new MTX();
mtx.addTX(tx, 0);
mtx.addTX(tx, 1);
mtx.addTX(tx, 2);
mtx.addTX(tx, 3);
mtx.addOutput(addrs[(i + 0) % addrs.length], 50460);
mtx.addOutput(addrs[(i + 1) % addrs.length], 50460);
mtx.addOutput(addrs[(i + 2) % addrs.length], 50460);
mtx.addOutput(addrs[(i + 3) % addrs.length], 50460);
tx = mtx.toTX();
jobs = [];
for (i = 0; i < 10000; i++) {
tx = bcoin.mtx()
.addInput(tx, 0)
.addInput(tx, 1)
.addInput(tx, 2)
.addInput(tx, 3)
.addOutput(addrs[(i + 0) % addrs.length], 50460)
.addOutput(addrs[(i + 1) % addrs.length], 50460)
.addOutput(addrs[(i + 2) % addrs.length], 50460)
.addOutput(addrs[(i + 3) % addrs.length], 50460)
.toTX();
jobs.push(walletdb.addTX(tx));
}
const end = bench('redemption');
await Promise.all(jobs);
end(10000);
jobs.push(walletdb.addTX(tx));
}
end = bench('redemption');
result = yield Promise.all(jobs);
end(10000);
// Balance
{
const end = bench('balance');
await wallet.getBalance();
end(1);
}
end = bench('balance');
result = yield wallet.getBalance();
end(1);
// Coins
{
const end = bench('coins');
await wallet.getCoins();
end(1);
}
end = bench('coins');
result = yield wallet.getCoins();
end(1);
// Create
{
const end = bench('create');
const options = {
rate: 10000,
outputs: [{
value: 50460,
address: addrs[0]
}]
};
await wallet.createTX(options);
end(1);
}
})().catch((err) => {
console.error(err);
process.exit(1);
end = bench('create');
options = {
rate: 10000,
outputs: [{
value: 50460,
address: addrs[0]
}]
};
yield wallet.createTX(options);
end(1);
});
runBench().then(process.exit);

View File

@ -6,7 +6,7 @@ cmd='node'
if ! type perl > /dev/null 2>& 1; then
if uname | grep -i 'darwin' > /dev/null; then
echo 'Bcoin requires perl to start on OSX.' >& 2
echo 'BCoin requires perl to start.' >& 2
exit 1
fi
rl=1
@ -50,13 +50,9 @@ for arg in "$@"; do
done
if test $daemon -eq 1; then
# And yet again, OSX doesn't support something.
if ! type setsid > /dev/null 2>& 1; then
(
"${dir}/${cmd}" "$@" > /dev/null 2>& 1 &
echo "$!"
)
exit 0
echo 'BCoin requires setsid to start as a daemon.' >& 2
exit 1
fi
(
setsid "${dir}/${cmd}" "$@" > /dev/null 2>& 1 &

685
bin/cli
View File

@ -2,6 +2,685 @@
'use strict';
console.error('%s%s',
'Warning: The `fcoin cli` interface is deprecated.\n',
'Please use `fcoin-cli` and `fwallet-cli` instead.');
var config = require('../lib/node/config');
var utils = require('../lib/utils/utils');
var co = require('../lib/utils/co');
var Client = require('../lib/http/client');
var Wallet = require('../lib/http/wallet');
var main;
function CLI() {
this.config = config({
config: true,
arg: true,
env: true,
network: 'main'
}).data;
this.argv = this.config.args;
this.client = null;
this.wallet = null;
}
CLI.prototype.log = function log(json) {
if (typeof json === 'string')
return console.log.apply(console, arguments);
console.log(JSON.stringify(json, null, 2));
};
CLI.prototype.getInfo = co(function* getInfo() {
var info = yield this.client.getInfo();
this.log(info);
});
CLI.prototype.createWallet = co(function* createWallet() {
var options = { id: this.argv[0] };
var wallet;
if (this.config.type)
options.type = this.config.type;
if (this.config.master)
options.master = this.config.master;
if (this.config.mnemonic)
options.master = this.config.mnemonic;
if (this.config.m)
options.m = this.config.m >>> 0;
if (this.config.n)
options.n = this.config.n >>> 0;
if (this.config.witness != null)
options.witness = !!this.config.witness;
if (this.config.passphrase)
options.passphrase = this.config.passphrase;
if (this.config.watch) {
options.watchOnly = true;
options.accountKey = this.config.watch;
}
wallet = yield this.client.createWallet(options);
this.log(wallet);
});
CLI.prototype.getMaster = co(function* getMaster() {
var master = yield this.wallet.getMaster();
this.log(master);
});
CLI.prototype.getKey = co(function* getKey() {
var address = this.argv[0];
var key = yield this.wallet.getKey(address);
this.log(key);
});
CLI.prototype.getWIF = co(function* getWIF() {
var address = this.argv[0];
var key = yield this.wallet.getWIF(address, this.config.passphrase);
this.log(key.privateKey);
});
CLI.prototype.addSharedKey = co(function* addSharedKey() {
var key = this.argv[0];
yield this.wallet.addSharedKey(this.config.account, key);
this.log('Added key.');
});
CLI.prototype.removeSharedKey = co(function* removeSharedKey() {
var key = this.argv[0];
yield this.wallet.removeSharedKey(this.config.account, key);
this.log('Removed key.');
});
CLI.prototype.getSharedKeys = co(function* getSharedKeys() {
var acct = this.argv[0] || this.config.account;
var account = yield this.wallet.getAccount(acct);
this.log(account.keys);
});
CLI.prototype.getAccount = co(function* getAccount() {
var acct = this.argv[0] || this.config.account;
var account = yield this.wallet.getAccount(acct);
this.log(account);
});
CLI.prototype.createAccount = co(function* createAccount() {
var options = { name: this.argv[0] };
var account;
if (this.config.type)
options.type = this.config.type;
if (this.config.m)
options.m = this.config.m >>> 0;
if (this.config.n)
options.n = this.config.n >>> 0;
if (this.config.witness != null)
options.witness = !!this.config.witness;
if (this.config.watch)
options.accountKey = this.config.watch;
account = yield this.wallet.createAccount(options);
this.log(account);
});
CLI.prototype.createAddress = co(function* createAddress() {
var account = this.argv[0];
var addr = yield this.wallet.createAddress(account);
this.log(addr);
});
CLI.prototype.createChange = co(function* createChange() {
var account = this.argv[0];
var addr = yield this.wallet.createChange(account);
this.log(addr);
});
CLI.prototype.createNested = co(function* createNested() {
var account = this.argv[0];
var addr = yield this.wallet.createNested(account);
this.log(addr);
});
CLI.prototype.getAccounts = co(function* getAccounts() {
var accounts = yield this.wallet.getAccounts();
this.log(accounts);
});
CLI.prototype.getWallet = co(function* getWallet() {
var info = yield this.wallet.getInfo();
this.log(info);
});
CLI.prototype.getTX = co(function* getTX() {
var hash = this.argv[0];
var txs, tx;
if (utils.isBase58(hash)) {
txs = yield this.client.getTXByAddress(hash);
this.log(txs);
return;
}
tx = yield this.client.getTX(hash);
if (!tx) {
this.log('TX not found.');
return;
}
this.log(tx);
});
CLI.prototype.getBlock = co(function* getBlock() {
var hash = this.argv[0];
var block;
if (hash.length !== 64)
hash = +hash;
block = yield this.client.getBlock(hash);
if (!block) {
this.log('Block not found.');
return;
}
this.log(block);
});
CLI.prototype.getCoin = co(function* getCoin() {
var hash = this.argv[0];
var index = this.argv[1];
var coins, coin;
if (utils.isBase58(hash)) {
coins = yield this.client.getCoinsByAddress(hash);
this.log(coins);
return;
}
coin = yield this.client.getCoin(hash, index);
if (!coin) {
this.log('Coin not found.');
return;
}
this.log(coin);
});
CLI.prototype.getWalletHistory = co(function* getWalletHistory() {
var txs = yield this.wallet.getHistory(this.config.account);
this.log(txs);
});
CLI.prototype.getWalletPending = co(function* getWalletPending() {
var txs = yield this.wallet.getPending(this.config.account);
this.log(txs);
});
CLI.prototype.getWalletCoins = co(function* getWalletCoins() {
var coins = yield this.wallet.getCoins(this.config.account);
this.log(coins);
});
CLI.prototype.listenWallet = co(function* listenWallet() {
var self = this;
yield this.wallet.open();
this.wallet.on('tx', function(details) {
self.log('TX:');
self.log(details);
});
this.wallet.on('confirmed', function(details) {
self.log('TX confirmed:');
self.log(details);
});
this.wallet.on('unconfirmed', function(details) {
self.log('TX unconfirmed:');
self.log(details);
});
this.wallet.on('conflict', function(details) {
self.log('TX conflict:');
self.log(details);
});
this.wallet.on('address', function(receive) {
self.log('New addresses allocated:');
self.log(receive);
});
this.wallet.on('balance', function(balance) {
self.log('Balance:');
self.log(balance);
});
return yield this.wallet.onDisconnect();
});
CLI.prototype.getBalance = co(function* getBalance() {
var balance = yield this.wallet.getBalance(this.config.account);
this.log(balance);
});
CLI.prototype.getMempool = co(function* getMempool() {
var txs = yield this.client.getMempool();
this.log(txs);
});
CLI.prototype.sendTX = co(function* sendTX() {
var output = {};
var options, tx;
if (this.config.script) {
output.script = this.config.script;
output.value = utils.satoshi(this.config.value || this.argv[0]);
} else {
output.address = this.config.address || this.argv[0];
output.value = utils.satoshi(this.config.value || this.argv[1]);
}
options = {
account: this.config.account,
passphrase: this.config.passphrase,
outputs: [output]
};
tx = yield this.wallet.send(options);
this.log(tx);
});
CLI.prototype.createTX = co(function* createTX() {
var output = {};
var options, tx;
if (this.config.script) {
output.script = this.config.script;
output.value = utils.satoshi(this.config.value || this.argv[0]);
} else {
output.address = this.config.address || this.argv[0];
output.value = utils.satoshi(this.config.value || this.argv[1]);
}
options = {
account: this.config.account,
passphrase: this.config.passphrase,
outputs: [output]
};
tx = yield this.wallet.createTX(options);
this.log(tx);
});
CLI.prototype.signTX = co(function* signTX() {
var options = { passphrase: this.config.passphrase };
var raw = options.tx || this.argv[0];
var tx = yield this.wallet.sign(raw, options);
this.log(tx);
});
CLI.prototype.zapWallet = co(function* zapWallet() {
var age = (this.config.age >>> 0) || 72 * 60 * 60;
yield this.wallet.zap(this.config.account, age);
this.log('Zapped!');
});
CLI.prototype.broadcast = co(function* broadcast() {
var raw = this.argv[0] || this.config.tx;
var tx = yield this.client.broadcast(raw);
this.log('Broadcasted:');
this.log(tx);
});
CLI.prototype.viewTX = co(function* viewTX() {
var raw = this.argv[0] || this.config.tx;
var tx = yield this.wallet.fill(raw);
this.log(tx);
});
CLI.prototype.getDetails = co(function* getDetails() {
var hash = this.argv[0];
var details = yield this.wallet.getTX(hash);
this.log(details);
});
CLI.prototype.getWalletBlocks = co(function* getWalletBlocks() {
var blocks = yield this.wallet.getBlocks();
this.log(blocks);
});
CLI.prototype.getWalletBlock = co(function* getWalletBlock() {
var height = this.argv[0] | 0;
var block = yield this.wallet.getBlock(height);
this.log(block);
});
CLI.prototype.retoken = co(function* retoken() {
var result = yield this.wallet.retoken();
this.log(result);
});
CLI.prototype.rescan = co(function* rescan() {
var height = this.argv[0];
if (!utils.isUInt32(height))
height = null;
yield this.client.rescan(height);
this.log('Rescanning...');
});
CLI.prototype.reset = co(function* reset() {
var hash = this.argv[0];
if (hash.length !== 64)
hash = +hash;
yield this.client.reset(hash);
this.log('Chain has been reset.');
});
CLI.prototype.resend = co(function* resend() {
yield this.client.resend();
this.log('Resending...');
});
CLI.prototype.resendWallet = co(function* resendWallet() {
yield this.wallet.resend();
this.log('Resending...');
});
CLI.prototype.backup = co(function* backup() {
var path = this.argv[0];
yield this.client.backup(path);
this.log('Backup complete.');
});
CLI.prototype.importKey = co(function* importKey() {
var key = this.argv[0];
if (!key)
throw new Error('No key for import.');
if (utils.isBase58(key)) {
yield this.wallet.importPrivate(key);
this.log('Imported private key.');
return;
}
if (utils.isHex(key)) {
yield this.wallet.importPublic(key);
this.log('Imported public key.');
return;
}
throw new Error('Bad key for import.');
});
CLI.prototype.importAddress = co(function* importKey() {
var address = this.argv[0];
yield this.wallet.importAddress(address);
this.log('Imported address.');
});
CLI.prototype.lock = co(function* lock() {
yield this.wallet.lock();
this.log('Locked.');
});
CLI.prototype.unlock = co(function* unlock() {
var passphrase = this.argv[0];
var timeout = +this.argv[1] || null;
yield this.wallet.unlock(passphrase, timeout);
this.log('Unlocked.');
});
CLI.prototype.rpc = co(function* rpc() {
var method = this.argv.shift();
var params = [];
var i, arg, param, result;
for (i = 0; i < this.argv.length; i++) {
arg = this.argv[i];
try {
param = JSON.parse(arg);
} catch (e) {
param = arg;
}
params.push(param);
}
result = yield this.client.rpc.call(method, params);
this.log(result);
});
CLI.prototype.handleWallet = co(function* handleWallet() {
this.wallet = new Wallet({
uri: this.config.url || this.config.uri,
apiKey: this.config.apikey,
network: this.config.network,
id: this.config.id || 'primary',
token: this.config.token
});
switch (this.argv.shift()) {
case 'listen':
return yield this.listenWallet();
case 'get':
return yield this.getWallet();
case 'master':
return yield this.getMaster();
case 'shared':
if (this.argv[0] === 'add') {
this.argv.shift();
return yield this.addSharedKey();
}
if (this.argv[0] === 'remove') {
this.argv.shift();
return yield this.removeSharedKey();
}
if (this.argv[0] === 'list')
this.argv.shift();
return yield this.getSharedKeys();
case 'balance':
return yield this.getBalance();
case 'history':
return yield this.getWalletHistory();
case 'pending':
return yield this.getWalletPending();
case 'coins':
return yield this.getWalletCoins();
case 'account':
if (this.argv[0] === 'list') {
this.argv.shift();
return yield this.getAccounts();
}
if (this.argv[0] === 'create') {
this.argv.shift();
return yield this.createAccount();
}
if (this.argv[0] === 'get')
this.argv.shift();
return yield this.getAccount();
case 'address':
return yield this.createAddress();
case 'change':
return yield this.createChange();
case 'nested':
return yield this.createNested();
case 'retoken':
return yield this.retoken();
case 'sign':
return yield this.signTX();
case 'mktx':
return yield this.createTX();
case 'send':
return yield this.sendTX();
case 'zap':
return yield this.zapWallet();
case 'tx':
return yield this.getDetails();
case 'blocks':
return yield this.getWalletBlocks();
case 'block':
return yield this.getWalletBlock();
case 'view':
return yield this.viewTX();
case 'import':
return yield this.importKey();
case 'watch':
return yield this.importAddress();
case 'key':
return yield this.getKey();
case 'dump':
return yield this.getWIF();
case 'lock':
return yield this.lock();
case 'unlock':
return yield this.unlock();
case 'resend':
return yield this.resendWallet();
default:
this.log('Unrecognized command.');
this.log('Commands:');
this.log(' $ listen: Listen for events.');
this.log(' $ get: View wallet.');
this.log(' $ master: View wallet master key.');
this.log(' $ shared add [xpubkey]: Add key to wallet.');
this.log(' $ shared remove [xpubkey]: Remove key from wallet.');
this.log(' $ balance: Get wallet balance.');
this.log(' $ history: View TX history.');
this.log(' $ pending: View pending TXs.');
this.log(' $ coins: View wallet coins.');
this.log(' $ account list: List account names.');
this.log(' $ account create [account-name]: Create account.');
this.log(' $ account get [account-name]: Get account details.');
this.log(' $ address: Derive new address.');
this.log(' $ change: Derive new change address.');
this.log(' $ nested: Derive new nested address.');
this.log(' $ retoken: Create new api key.');
this.log(' $ send [address] [value]: Send transaction.');
this.log(' $ mktx [address] [value]: Create transaction.');
this.log(' $ sign [tx-hex]: Sign transaction.');
this.log(' $ zap [age?]: Zap pending wallet TXs.');
this.log(' $ tx [hash]: View transaction details.');
this.log(' $ blocks: List wallet blocks.');
this.log(' $ block [height]: View wallet block.');
this.log(' $ view [tx-hex]: Parse and view transaction.');
this.log(' $ import [wif|hex]: Import private or public key.');
this.log(' $ watch [address]: Import an address.');
this.log(' $ key [address]: Get wallet key by address.');
this.log(' $ dump [address]: Get wallet key WIF by address.');
this.log(' $ lock: Lock wallet.');
this.log(' $ unlock [passphrase] [timeout?]: Unlock wallet.');
this.log(' $ resend: Resend pending transactions.');
this.log('Other Options:');
this.log(' --passphrase [passphrase]: For signing and account creation.');
this.log(' --account [account-name]: Account name.');
return;
}
});
CLI.prototype.handleNode = co(function* handleNode() {
this.client = new Client({
uri: this.config.url || this.config.uri,
apiKey: this.config.apikey,
network: this.config.network
});
switch (this.argv.shift()) {
case 'info':
return yield this.getInfo();
case 'mkwallet':
return yield this.createWallet();
case 'broadcast':
return yield this.broadcast();
case 'mempool':
return yield this.getMempool();
case 'tx':
return yield this.getTX();
case 'coin':
return yield this.getCoin();
case 'block':
return yield this.getBlock();
case 'rescan':
return yield this.rescan();
case 'reset':
return yield this.reset();
case 'resend':
return yield this.resend();
case 'backup':
return yield this.backup();
case 'rpc':
return yield this.rpc();
default:
this.log('Unrecognized command.');
this.log('Commands:');
this.log(' $ info: Get server info.');
this.log(' $ wallet create [id]: Create wallet.');
this.log(' $ broadcast [tx-hex]: Broadcast transaction.');
this.log(' $ mempool: Get mempool snapshot.');
this.log(' $ tx [hash/address]: View transactions.');
this.log(' $ coin [hash+index/address]: View coins.');
this.log(' $ block [hash/height]: View block.');
this.log(' $ rescan [height]: Rescan for transactions.');
this.log(' $ reset [height/hash]: Reset chain to desired block.');
this.log(' $ resend: Resend pending transactions.');
this.log(' $ backup [path]: Backup the wallet db.');
this.log(' $ rpc [command] [args]: Execute RPC command.');
return;
}
});
CLI.prototype.open = co(function* open() {
switch (this.argv[0]) {
case 'w':
case 'wallet':
this.argv.shift();
if (this.argv[0] === 'create') {
this.argv[0] = 'mkwallet';
return yield this.handleNode();
}
return yield this.handleWallet();
default:
return yield this.handleNode();
}
});
CLI.prototype.destroy = function destroy() {
if (this.wallet)
this.wallet.client.destroy();
if (this.client)
this.client.destroy();
return Promise.resolve();
};
main = co(function* main() {
var cli = new CLI();
yield cli.open();
yield cli.destroy();
});
main().then(process.exit).catch(function(err) {
console.error(err.stack + '');
return process.exit(1);
});

View File

@ -1,5 +0,0 @@
#!/usr/bin/env node
'use strict';
require('@oipwg/fclient/bin/fcoin-cli');

View File

@ -1,55 +0,0 @@
#!/bin/bash
rl=0
daemon=0
if ! type perl > /dev/null 2>& 1; then
if uname | grep -i 'darwin' > /dev/null; then
echo 'Bcoin requires perl to start on OSX.' >& 2
exit 1
fi
rl=1
fi
if test $rl -eq 1; then
file=$(readlink -f "$0")
else
# Have to do it this way
# because OSX isn't a real OS
file=$(perl -MCwd -e "print Cwd::realpath('$0')")
fi
dir=$(dirname "$file")
if test x"$1" = x'cli'; then
shift
exec "${dir}/cli" "wallet" "$@"
exit 1
fi
for arg in "$@"; do
case "$arg" in
--daemon)
daemon=1
;;
esac
done
if test $daemon -eq 1; then
# And yet again, OSX doesn't support something.
if ! type setsid > /dev/null 2>& 1; then
(
"${dir}/wallet" "$@" > /dev/null 2>& 1 &
echo "$!"
)
exit 0
fi
(
setsid "${dir}/wallet" "$@" > /dev/null 2>& 1 &
echo "$!"
)
exit 0
else
exec "${dir}/wallet" "$@"
exit 1
fi

View File

@ -1,5 +0,0 @@
#!/usr/bin/env node
'use strict';
require('@oipwg/fclient/bin/fwallet-cli');

View File

@ -2,59 +2,37 @@
'use strict';
process.title = 'fcoin';
process.title = 'bcoin';
if (process.argv.indexOf('--help') !== -1
|| process.argv.indexOf('-h') !== -1) {
console.error('See the bcoin docs at: https://github.com/bcoin-org/bcoin/tree/master/docs.');
process.exit(1);
throw new Error('Could not exit.');
}
var bcoin = require('../');
var utils = bcoin.utils;
var assert = require('assert');
if (process.argv.indexOf('--version') !== -1
|| process.argv.indexOf('-v') !== -1) {
const pkg = require('../package.json');
console.log(pkg.version);
process.exit(0);
throw new Error('Could not exit.');
}
const FullNode = require('../lib/node/fullnode');
const node = new FullNode({
file: true,
argv: true,
var options = bcoin.config({
config: true,
arg: true,
env: true,
logFile: true,
logConsole: true,
logLevel: 'debug',
checkpoints: true,
memory: false,
workers: true,
listen: true,
loader: require
logFile: true,
db: 'leveldb',
listen: true
});
// Temporary hack
if (!node.config.bool('no-wallet') && !node.has('walletdb')) {
const plugin = require('../lib/wallet/plugin');
node.use(plugin);
}
bcoin.set(options);
process.on('unhandledRejection', (err, promise) => {
throw err;
var node = new bcoin.fullnode(options);
node.on('error', function(err) {
;
});
process.on('SIGINT', async () => {
await node.close();
});
(async () => {
await node.ensure();
await node.open();
await node.connect();
node.startSync();
})().catch((err) => {
console.error(err.stack);
process.on('uncaughtException', function(err) {
node.logger.debug(err.stack);
node.logger.error(err);
process.exit(1);
});
node.open().then(function() {
node.pool.connect();
node.startSync();
});

View File

@ -2,58 +2,45 @@
'use strict';
process.title = 'fcoin';
process.title = 'bcoin';
const assert = require('assert');
const SPVNode = require('../lib/node/spvnode');
const Outpoint = require('../lib/primitives/outpoint');
var bcoin = require('../');
var utils = bcoin.utils;
var assert = require('assert');
const node = new SPVNode({
file: true,
argv: true,
var options = bcoin.config({
config: true,
arg: true,
env: true,
logFile: true,
logConsole: true,
logLevel: 'debug',
db: 'leveldb',
memory: false,
persistent: true,
workers: true,
listen: true,
loader: require
logFile: true,
db: 'leveldb'
});
// Temporary hack
if (!node.config.bool('no-wallet') && !node.has('walletdb')) {
const plugin = require('../lib/wallet/plugin');
node.use(plugin);
}
bcoin.set(options);
process.on('unhandledRejection', (err, promise) => {
throw err;
var node = bcoin.spvnode(options);
node.on('error', function(err) {
;
});
process.on('SIGINT', async () => {
await node.close();
process.on('uncaughtException', function(err) {
node.logger.debug(err.stack);
node.logger.error(err);
process.exit(1);
});
(async () => {
await node.ensure();
await node.open();
await node.connect();
if (node.config.bool('test')) {
node.open().then(function() {
if (process.argv.indexOf('--test') !== -1) {
node.pool.watchAddress('1VayNert3x1KzbpzMGt2qdqrAThiRovi8');
node.pool.watchOutpoint(new Outpoint());
node.on('block', (block) => {
node.pool.watch(bcoin.outpoint().toRaw());
node.on('block', function(block) {
assert(block.txs.length >= 1);
if (block.txs.length > 1)
console.log(block.txs[1]);
utils.log(block.txs[1]);
});
}
node.startSync();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,51 +0,0 @@
#!/usr/bin/env node
'use strict';
process.title = 'fwallet';
if (process.argv.indexOf('--help') !== -1
|| process.argv.indexOf('-h') !== -1) {
console.error('See the bcoin docs at: https://github.com/bcoin-org/bcoin/tree/master/docs.');
process.exit(1);
throw new Error('Could not exit.');
}
if (process.argv.indexOf('--version') !== -1
|| process.argv.indexOf('-v') !== -1) {
const pkg = require('../package.json');
console.log(pkg.version);
process.exit(0);
throw new Error('Could not exit.');
}
const Node = require('../lib/wallet/node');
const node = new Node({
file: true,
argv: true,
env: true,
logFile: true,
logConsole: true,
logLevel: 'debug',
memory: false,
workers: true,
listen: true,
loader: require
});
process.on('unhandledRejection', (err, promise) => {
throw err;
});
process.on('SIGINT', async () => {
await node.close();
});
(async () => {
await node.ensure();
await node.open();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>bcoin</title>
<script src="/bcoin.js"></script>
</head>
<body>
<h1>Bcoin</h1>
<p>Use the console to access `global.bcoin`.</p>
</body>
</html>

3
browser/empty.js Normal file
View File

@ -0,0 +1,3 @@
// Empty module for browserify.
module.exports = null;
throw new Error('Module not available.');

View File

@ -1,110 +1,101 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>bcoin</title>
<meta charset="utf-8">
<style>
html {
height: 100%;
}
body {
height: 90%;
padding: 20px;
}
h1 {
font: 3em monospace;
margin: 10px;
padding: 0;
}
small {
margin: 10px;
width: 50%;
display: block;
}
.log {
padding: 5px;
margin-left: 10px;
overflow-y: scroll;
border: 1px solid black;
white-space: pre-wrap;
height: 40%;
width: 40%;
font: 1em monospace;
margin-top: 10px;
}
.wallet {
padding: 5px;
margin-left: 5px;
margin-top: 10px;
font: 1em monospace;
}
.rpc, .send {
padding: 5px;
margin-left: 5px;
margin-top: 10px;
font: 1em monospace;
}
#newaddr{
display: block;
margin-left: 10px;
}
.tx {
float: right;
font: 1em monospace;
padding: 5px;
border: 1px solid black;
margin-top: 10px;
}
a {
text-decoration: none;
}
.floating {
font: 1em monospace;
white-space: pre-wrap;
position: absolute;
display: none;
padding: 5px;
background: white;
border: 1px solid black;
width: 40%;
height: 30%;
top: 50%;
left: 50%;
margin-left: -20%;
margin-top: -15%;
overflow-y: scroll;
}
</style>
<script src="app.js" defer></script>
</head>
<body>
<h1>Bcoin, the browser full node</h1>
<small>
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-&gt;tcp
proxy. Enjoy. (See the
<a href="https://github.com/bcoin-org/bcoin"
target="_blank">bcoin repo</a>
for more bitcoin magic).
</small>
<div class="tx">
<div>Chain State: <span id="state"></span></div>
<div>Last 20 Blocks/TXs:</div>
<div id="tx"></div>
</div>
<div id="log" class="log"></div>
<form id="rpc" class="rpc" action="#">
<input type="text" name="cmd" id="cmd"
placeholder="RPC command (e.g. getblockchaininfo)">
</form>
<div id="wallet" class="wallet"></div>
<form id="send" class="send" action="#">
<input type="text" name="address" id="address" placeholder="Address">
<input type="text" name="amount" id="amount" placeholder="Amount (BTC)">
<input type="submit" value="Send">
</form>
<input type="button" id="newaddr" value="New Address">
<div id="floating" class="floating"></div>
</body>
<!doctype html>
<html>
<head>
<title>bcoin</title>
<style>
html { height: 100%; }
body { height: 90%; padding: 20px; }
h1 {
font: 3em monospace;
margin: 10px;
padding: 0;
}
small {
margin: 10px;
width: 50%;
display: block;
}
.log {
padding: 5px;
margin-left: 10px;
overflow-y: scroll;
border: 1px solid black;
white-space: pre-wrap;
height: 40%;
width: 40%;
font: 1em monospace;
margin-top: 10px;
}
.wallet {
padding: 5px;
margin-left: 5px;
margin-top: 10px;
font: 1em monospace;
}
.rpc, .send {
padding: 5px;
margin-left: 5px;
margin-top: 10px;
font: 1em monospace;
}
#newaddr{
display: block;
margin-left: 10px;
}
.tx {
float: right;
font: 1em monospace;
padding: 5px;
border: 1px solid black;
margin-top: 10px;
}
a {
text-decoration: none;
}
.floating {
font: 1em monospace;
white-space: pre-wrap;
position: absolute;
display: none;
padding: 5px;
background: white;
border: 1px solid black;
width: 40%;
height: 30%;
top: 50%;
left: 50%;
margin-left: -20%;
margin-top: -15%;
overflow-y: scroll;
}
</style>
<script src="/bcoin.js"></script>
</head>
<body>
<h1>BCoin, the browser full node</h1>
<small>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-&gt;tcp proxy.
Enjoy. (See the <a href="https://github.com/bcoin-org/bcoin">bcoin repo</a> for
more bitcoin magic).</small>
<div class="tx">
<div>Chain State: <span id="state"></span></div>
<div>Last 20 Blocks/TXs:</div>
<div id="tx"></div>
</div>
<div id="log" class="log"></div>
<form id="rpc" class="rpc" action="#">
<input type="text" name="cmd" id="cmd"
placeholder="RPC command (e.g. getblockchaininfo)">
</form>
<div id="wallet" class="wallet"></div>
<form id="send" class="send" action="#">
<input type="text" name="address" id="address" placeholder="Address">
<input type="text" name="amount" id="amount" placeholder="Amount (BTC)">
<input type="submit" value="Send">
</form>
<input type="button" id="newaddr" value="New Address">
<div id="floating" class="floating"></div>
<script src="/index.js"></script>
</body>
</html>

243
browser/index.js Normal file
View File

@ -0,0 +1,243 @@
;(function() {
'use strict';
var utils = bcoin.utils;
var body = document.getElementsByTagName('body')[0];
var log = document.getElementById('log');
var wdiv = document.getElementById('wallet');
var tdiv = document.getElementById('tx');
var floating = document.getElementById('floating');
var send = document.getElementById('send');
var newaddr = document.getElementById('newaddr');
var chainState = document.getElementById('state');
var rpc = document.getElementById('rpc');
var cmd = document.getElementById('cmd');
var items = [];
var scrollback = 0;
var logger, node, options;
body.onmouseup = function() {
floating.style.display = 'none';
};
floating.onmouseup = function(ev) {
ev.stopPropagation();
return false;
};
function show(obj) {
floating.innerHTML = escape(utils.inspectify(obj, false));
floating.style.display = 'block';
}
logger = new bcoin.logger({ level: 'debug' });
logger.writeConsole = function(level, args) {
var msg = utils.format(args, false);
if (++scrollback > 1000) {
log.innerHTML = '';
scrollback = 1;
}
log.innerHTML += '<span style="color:blue;">' + utils.now() + '</span> ';
if (level === 'error')
log.innerHTML += '<span style="color:red;">[' + level + ']</span> ';
else
log.innerHTML += '[' + level + '] ';
log.innerHTML += escape(msg) + '\n';
log.scrollTop = log.scrollHeight;
};
rpc.onsubmit = function(ev) {
var text = cmd.value || '';
var argv = text.trim().split(/\s+/);
var method = argv.shift();
var params = [];
var i, arg, param;
cmd.value = '';
for (i = 0; i < argv.length; i++) {
arg = argv[i];
try {
param = JSON.parse(arg);
} catch (e) {
param = arg;
}
params.push(param);
}
node.rpc.execute({ method: method, params: params }).then(show, show);
ev.preventDefault();
ev.stopPropagation();
return false;
};
send.onsubmit = function(ev) {
var value = document.getElementById('amount').value;
var address = document.getElementById('address').value;
var tx, options;
options = {
outputs: [{
address: address,
value: utils.satoshi(value)
}]
};
node.wallet.createTX(options).then(function(mtx) {
tx = mtx;
return node.wallet.sign(tx);
}).then(function() {
return node.sendTX(tx);
}).then(function() {
show(tx);
});
ev.preventDefault();
ev.stopPropagation();
return false;
};
newaddr.onmouseup = function() {
node.wallet.createReceive().then(function() {
formatWallet(node.wallet);
});
};
function kb(size) {
size /= 1000;
return size.toFixed(2) + 'kb';
}
function create(html) {
var el = document.createElement('div');
el.innerHTML = html;
return el.firstChild;
}
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function addItem(tx) {
var el;
if (items.length === 20) {
el = items.shift();
tdiv.removeChild(el);
el.onmouseup = null;
}
el = create('<a style="display:block;" href="#'
+ tx.rhash + '">' + tx.rhash + ' (' + tx.height
+ ' - ' + kb(tx.getSize()) + ')</a>');
tdiv.appendChild(el);
setMouseup(el, tx);
items.push(el);
chainState.innerHTML = ''
+ 'tx=' + node.chain.db.state.tx
+ ' coin=' + node.chain.db.state.coin
+ ' value=' + utils.btc(node.chain.db.state.value);
}
function setMouseup(el, obj) {
el.onmouseup = function(ev) {
show(obj);
ev.stopPropagation();
return false;
};
}
function formatWallet(wallet) {
var html = '';
var key = wallet.master.toJSON(true).key;
var i, tx, el;
html += '<b>Wallet</b><br>';
if (wallet.account.witness) {
html += 'Current Address (p2wpkh): <b>'
+ wallet.getAddress()
+ '</b><br>';
html += 'Current Address (p2wpkh behind p2sh): <b>'
+ wallet.getNestedAddress()
+ '</b><br>';
} else {
html += 'Current Address: <b>' + wallet.getAddress() + '</b><br>';
}
html += 'Extended Private Key: <b>' + key.xprivkey + '</b><br>';
html += 'Mnemonic: <b>' + key.mnemonic.phrase + '</b><br>';
wallet.getBalance().then(function(balance) {
html += 'Confirmed Balance: <b>'
+ utils.btc(balance.confirmed)
+ '</b><br>';
html += 'Unconfirmed Balance: <b>'
+ utils.btc(balance.unconfirmed)
+ '</b><br>';
return wallet.getHistory();
}).then(function(txs) {
return wallet.toDetails(txs);
}).then(function(txs) {
html += 'TXs:\n';
wdiv.innerHTML = html;
for (i = 0; i < txs.length; i++) {
tx = txs[i];
el = create(
'<a style="display:block;" href="#' + tx.hash + '">'
+ tx.hash + '</a>');
wdiv.appendChild(el);
setMouseup(el, tx.toJSON());
}
});
}
options = bcoin.config({
query: true,
network: 'segnet4',
db: 'leveldb',
useWorkers: true,
coinCache: true,
logger: logger
});
bcoin.set(options);
node = new bcoin.fullnode(options);
node.rpc = new bcoin.rpc(node);
node.on('error', function(err) {
;
});
node.chain.on('block', addItem);
node.mempool.on('tx', addItem);
node.open().then(function() {
node.startSync();
formatWallet(node.wallet);
node.wallet.on('balance', function() {
formatWallet(node.wallet);
});
});
})();

View File

@ -1,45 +1,48 @@
'use strict';
const bweb = require('bweb');
const fs = require('bfile');
const WSProxy = require('./wsproxy');
var HTTPBase = require('../lib/http/base');
var WSProxy = require('./wsproxy');
var fs = require('fs');
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({
var server = new HTTPBase();
var proxy = new WSProxy({
pow: process.argv.indexOf('--pow') !== -1,
ports: [7312, 17312, 17412, 28333, 28901]
ports: [8333, 18333, 18444, 28333, 28901]
});
const server = bweb.server({
port: Number(process.argv[2]) || 8080,
sockets: false
proxy.on('error', function(err) {
console.error(err.stack + '');
});
server.use(server.router());
var index = fs.readFileSync(__dirname + '/index.html');
var indexjs = fs.readFileSync(__dirname + '/index.js');
var bcoin = fs.readFileSync(__dirname + '/bcoin.js');
var worker = fs.readFileSync(__dirname + '/../lib/workers/worker-browser.js');
proxy.on('error', (err) => {
console.error(err.stack);
server.get('/favicon.ico', function(req, res, send, next) {
send(404, '', 'text');
});
server.on('error', (err) => {
console.error(err.stack);
server.get('/', function(req, res, send, next) {
send(200, index, 'html');
});
server.get('/', (req, res) => {
res.send(200, index, 'html');
server.get('/index.js', function(req, res, send, next) {
send(200, indexjs, 'js');
});
server.get('/app.js', (req, res) => {
res.send(200, app, 'js');
server.get('/bcoin.js', function(req, res, send, next) {
send(200, bcoin, 'js');
});
server.get('/worker.js', (req, res) => {
res.send(200, worker, 'js');
server.get('/bcoin-worker.js', function(req, res, send, next) {
send(200, worker, 'js');
});
proxy.attach(server.http);
server.on('error', function(err) {
console.error(err.stack + '');
});
server.open();
proxy.attach(server.server);
server.listen(+process.argv[2] || 8080);

View File

@ -1,292 +0,0 @@
/* eslint-env browser */
'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 util = require('../../lib/utils/util');
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 += `<span style="color:blue;">${now}</span> `;
if (name === 'error') {
log.innerHTML += `<span style="color:red;">[${name}] `;
if (module)
log.innerHTML += `(${module}) `;
log.innerHTML += '</span>';
} 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,
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;
}
floating.innerHTML = escape(JSON.stringify(obj, 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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
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(''
+ `<a style="display:block;" href="#${item.rhash()}">`
+ `${item.rhash()} (${height} - ${kb(item.getSize())})`
+ '</a>'
);
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.btc(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 += '<b>Wallet</b><br>';
if (naddr) {
html += `Current Address (p2wpkh): <b>${raddr}</b><br>`;
html += `Current Address (p2wpkh behind p2sh): <b>${naddr}</b><br>`;
} else {
html += `Current Address: <b>${raddr}</b><br>`;
}
html += `Extended Private Key: <b>${key.xprivkey}</b><br>`;
html += `Mnemonic: <b>${mnemonic.phrase}</b><br>`;
const balance = await wallet.getBalance();
html += `Confirmed Balance: <b>${Amount.btc(balance.confirmed)}</b><br>`;
html += `Unconfirmed Balance: <b>${Amount.btc(balance.unconfirmed)}</b><br>`;
const txs = await wallet.getHistory();
const det = await wallet.toDetails(txs);
html += 'TXs:\n';
wdiv.innerHTML = html;
for (const tx of det) {
const hash = util.revHex(tx.hash);
const el = create(
`<a style="display:block;" href="#${hash}">${hash}</a>`);
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;
});

View File

@ -1,154 +0,0 @@
/*!
* proxysocket.js - wsproxy socket for bcoin
* Copyright (c) 2016-2017, 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;

75
browser/transform.js Normal file
View File

@ -0,0 +1,75 @@
var Transform = require('stream').Transform;
var path = require('path');
var assert = require('assert');
var fs = require('fs');
var StringDecoder = require('string_decoder').StringDecoder;
function nil() {
var stream = new Transform();
stream._transform = function(chunk, encoding, callback) {
callback(null, chunk);
};
stream._flush = function(callback) {
callback();
};
return stream;
}
function processEnv(str) {
return str.replace(
/^( *)this\.require\('(\w+)', '([^']+)'\)/gm,
'$1this.$2 = require(\'$3\')');
}
function processLazy(str) {
str.replace(
/^( *)lazy\('(\w+)', '([^']+)'\)/gm,
function(_, sp, w1, w2) {
str += sp + 'if (0) require(\'' + w2 + '\');\n';
return '';
}
);
return str;
}
function transformer(file, process) {
var stream = new Transform();
var decoder = new StringDecoder('utf8');
var str = '';
stream._transform = function(chunk, encoding, callback) {
assert(Buffer.isBuffer(chunk));
str += decoder.write(chunk);
callback(null, new Buffer(0));
};
stream._flush = function(callback) {
str = process(str);
stream.push(new Buffer(str, 'utf8'));
callback();
};
return stream;
}
function end(file, offset) {
return path.normalize(file).split(path.sep).slice(-offset).join('/');
}
module.exports = function(file) {
if (end(file, 3) === 'lib/utils/utils.js')
return transformer(file, processLazy);
if (end(file, 3) === 'lib/crypto/crypto.js')
return transformer(file, processLazy);
if (end(file, 2) === 'lib/env.js')
return transformer(file, processEnv);
return nil();
};

View File

@ -1,204 +1,216 @@
'use strict';
const assert = require('assert');
const net = require('net');
const EventEmitter = require('events');
const bsock = require('bsock');
const IP = require('binet');
var net = require('net');
var IOServer = require('socket.io');
var utils = require('../lib/utils/utils');
var IP = require('../lib/utils/ip');
var BufferWriter = require('../lib/utils/writer');
var EventEmitter = require('events').EventEmitter;
class WSProxy extends EventEmitter {
constructor(options) {
super();
var TARGET = new Buffer(
'0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'hex');
if (!options)
options = {};
function WSProxy(options) {
if (!(this instanceof WSProxy))
return new WSProxy(options);
this.options = options;
this.ports = new Set();
this.io = bsock.server();
this.sockets = new WeakMap();
EventEmitter.call(this);
if (options.ports) {
for (const port of options.ports)
this.ports.add(port);
}
if (!options)
options = {};
this.init();
}
this.options = options;
this.target = options.target || TARGET;
this.pow = options.pow === true;
this.ports = options.ports || [];
this.io = new IOServer();
this.sockets = new WeakMap();
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);
}
this._init();
}
class SocketState {
constructor(server, socket) {
this.socket = null;
this.host = socket.host;
this.remoteHost = null;
utils.inherits(WSProxy, EventEmitter);
WSProxy.prototype._init = function _init() {
var self = this;
this.io.on('error', function(err) {
self.emit('error', err);
});
this.io.on('connection', function(ws) {
self._handleSocket(ws);
});
};
WSProxy.prototype._handleSocket = function _handleSocket(ws) {
var self = this;
var state = new SocketState(this, ws);
// Use a weak map to avoid
// mutating the websocket object.
this.sockets.set(ws, state);
ws.emit('info', state.toInfo());
ws.on('error', function(err) {
self.emit('error', err);
});
ws.on('tcp connect', function(port, host, nonce) {
self._handleConnect(ws, port, host, nonce);
});
};
WSProxy.prototype._handleConnect = function _handleConnect(ws, port, host, nonce) {
var self = this;
var state = this.sockets.get(ws);
var socket, pow;
if (state.socket) {
this.log('Client is trying to reconnect (%s).', state.host);
return;
}
connect(port, host) {
this.socket = net.connect(port, host);
this.remoteHost = IP.toHostname(host, port);
return this.socket;
if (!utils.isNumber(port)
|| typeof host !== 'string'
|| host.length === 0) {
this.log('Client gave bad arguments (%s).', state.host);
ws.emit('tcp close');
ws.disconnect();
return;
}
if (this.pow) {
if (!utils.isNumber(nonce)) {
this.log('Client did not solve proof of work.', state.host);
ws.emit('tcp close');
ws.disconnect();
return;
}
pow = new BufferWriter();
pow.writeU32(nonce);
pow.writeBytes(state.snonce);
pow.writeU32(port);
pow.writeString(host, 'ascii');
pow = pow.render();
if (utils.cmp(utils.hash256(pow), this.target) > 0) {
this.log('Client did not solve proof of work (%s).', state.host);
ws.emit('tcp close');
ws.disconnect();
return;
}
}
if (!/^[a-zA-Z0-9\.:\-]+$/.test(host)) {
this.log('Client gave a bad host (%s).', state.host);
ws.emit('tcp error', {
message: 'EHOSTUNREACH',
code: 'EHOSTUNREACH'
});
ws.disconnect();
return;
}
if (IP.isPrivate(host)) {
this.log('Client is trying to connect to a private ip (%s).', state.host);
ws.emit('tcp error', {
message: 'ENETUNREACH',
code: 'ENETUNREACH'
});
ws.disconnect();
return;
}
if (this.ports.indexOf(port) === -1) {
this.log('Client is connecting to non-whitelist port (%s).', state.host);
ws.emit('tcp error', {
message: 'ENETUNREACH',
code: 'ENETUNREACH'
});
ws.disconnect();
return;
}
try {
socket = state.connect(port, host);
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.emit('tcp error', {
message: 'ENETUNREACH',
code: 'ENETUNREACH'
});
ws.disconnect();
return;
}
socket.on('connect', function() {
ws.emit('tcp connect');
});
socket.on('data', function(data) {
ws.emit('tcp data', data.toString('hex'));
});
socket.on('error', function(err) {
ws.emit('tcp error', {
message: err.message,
code: err.code || null
});
});
socket.on('close', function() {
self.log('Closing %s (%s).', state.remoteHost, state.host);
ws.emit('tcp close');
ws.disconnect();
});
ws.on('tcp data', function(data) {
if (typeof data !== 'string')
return;
socket.write(new Buffer(data, 'hex'));
});
ws.on('disconnect', function() {
socket.destroy();
});
};
WSProxy.prototype.log = function log() {
process.stdout.write('wsproxy: ');
console.log.apply(console, arguments);
};
WSProxy.prototype.attach = function attach(server) {
this.io.attach(server);
};
function SocketState(server, socket) {
this.pow = server.pow;
this.target = server.target;
this.snonce = utils.nonce(true);
this.socket = null;
this.host = IP.normalize(socket.conn.remoteAddress);
this.remoteHost = null;
}
SocketState.prototype.toInfo = function toInfo() {
return {
pow: this.pow,
target: this.target.toString('hex'),
snonce: this.snonce.toString('hex')
};
};
SocketState.prototype.connect = function connect(port, host) {
this.socket = net.connect(port, host);
this.remoteHost = IP.hostname(host, port);
return this.socket;
};
module.exports = WSProxy;

28
docker-compose.yml Normal file
View File

@ -0,0 +1,28 @@
version: '2'
services:
bcoin:
build: .
ports:
#-- Mainnet
#- "8333:8333"
#- "8332:8332" # RPC
#-- Testnet
#- "18333:18333"
#- "18332:18332" # RPC
#-- SEGNET4
- "28901:28901"
- "28902:28902" # RPC
environment:
BCOIN_NETWORK: segnet4 # main, testnet
BCOIN_PREFIX: /data
networks:
- "bcoin"
volumes:
- ./docker_data:/data
networks:
bcoin:
external:
# docker network create bcoin
name: "bcoin"

View File

@ -1,44 +0,0 @@
# Documentation
## Table of contents
- [Getting started](getting-started.md)
- [Configuration](configuration.md)
- [Wallet system](wallet-system.md)
- [Design](design.md)
- [Node and wallet CLI](cli.md)
## External links
- [Guides](https://bcoin.io/guides.html)
- [Running in the browser](https://bcoin.io/guides/browser.html)
- [Node and wallet REST and RPC API](https://bcoin.io/api-docs/index.html)
## Library examples
These code examples are designed to demonstrate how to integrate bcoin modules
with minimal configuration.
- [Simple fullnode](examples/fullnode.js) - Creates a `FullNode` object and
connects to `testnet`.
- [Connect to peer](examples/connect-to-peer.js) - Connects to a user-defined
peer in `regtest` mode.
- [Connecting to the P2P network](examples/connect-to-the-p2p-network.js) -
Creates `chain`, `pool`, and `mempool` objects for both main and
testnet networks.
- [Creating a blockchain and mempool](examples/create-a-blockchain-and-mempool.js) -
Mines a block from the mempool to the chain.
- [Wallet with dummy TX](examples/wallet.js) - Adds a "dummy" transaction to
the wallet and `tx` event is handled.
- [SPV sync](examples/spv-sync-wallet.js) - A transaction matching the SPV
node's bloom filter is broadcast by a minimal full node to the SPV node.
- [Plugin example](examples/peers-plugin.js) - Demonstrates the `plugin`
feature of bcoin's `node` object.
- [Client API usage](examples/client-api.js) - Demonstrates usage of the node
and wallet API.
- [Create and sign TX](examples/create-sign-tx.js) - Demonstrates how to use
`mtx` and `keyring` modules to sign a transaction.
- [Get transaction from chain](examples/get-tx-from-chain.js) - Connects to
live testnet network and syncs the first 1000 blocks with tx indexing active.
- [Create watch only wallet](examples/watch-only-wallet.js) - Imports an `xpub`
into a new watch-only wallet that can derive addresses.

View File

@ -1,73 +0,0 @@
# Node and wallet CLI
Bcoin ships with [bclient](https://github.com/bcoin-org/bclient) as its
default client to the [API](https://bcoin.io/api-docs) for command
line access.
## Configuration
Using environment variables:
```bash
$ export BCOIN_API_KEY=hunter2
$ export BCOIN_NETWORK=testnet
$ bcoin --daemon
$ bcoin-cli info
```
With command-line arguments:
```bash
$ bcoin-cli --network=testnet --api-key=hunter2 info
```
You can also use `~/.bcoin/bcoin.conf` for configuration options,
see [Configuration](configuration.md) for the full details.
## Examples
Common node commands:
```bash
# View the genesis block
$ bcoin-cli block 0
# View the mempool
$ bcoin-cli mempool
# Execute an RPC command to list network peers
$ bcoin-cli rpc getpeerinfo
```
Common wallet commands:
```bash
# View primary wallet
$ bwallet-cli get
# View transaction history
$ bwallet-cli history
# Send a transaction
$ bwallet-cli send <address> 0.01
# View balance
$ bwallet-cli balance
# Derive new address
$ bwallet-cli address
# Create a new account
$ bwallet-cli account create foo
# Send from account
$ bwallet-cli send <address> 0.01 --account=foo
```
Get more help:
```bash
$ bcoin-cli help
$ bcoin-cli rpc help
$ bwallet-cli help
$ bwallet-cli rpc help
```

View File

@ -1,190 +0,0 @@
# Configuration
By default, the mainnet bcoin config files will reside in `~/.bcoin/bcoin.conf`
and `~/.bcoin/wallet.conf`. Any parameter passed to bcoin at startup will have
precedence over the config file. Even if you are just running `bclient` without
bcoin installed (to access a remote server, for example) the configuration
files would still reside in `~/.bcoin/`
For example:
``` bash
bcoin --network=regtest --api-key=menace --daemon
```
...will read the config file at `~/.bcoin/regtest/bcoin.conf` and ignore any
`network` or `api-key` parameters listed in that file.
All bcoin configuration options work in the config file, CLI arguments,
process environment, and in the constructor parameters when instantiating
new `node` objects in JavaScript. Each method has slightly different
formatting. Note specifically the usage of hyphens and capital letters.
See the examples below:
| config file | CLI parameter | environment variable | JS object constructor |
|---|---|---|---|
| `network: testnet` | `--network=testnet` | `BCOIN_NETWORK=testnet` | `{network: 'testnet'}` |
| `log-level: debug` | `--log-level=debug` | `BCOIN_LOG_LEVEL=debug` | `{logLevel: 'debug'}` |
| `max-outbound: 8` | `--max-outbound=8` | `BCOIN_MAX_OUTBOUND=8` | `{maxOutbound: 8}`|
## Prefix
Bcoin's data directory 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 simnet) (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).
- `spv`: Enable Simplified Payments Verification (SPV) mode
*Note: The `spv` and `daemon` options can not be entered in `bcoin.conf`.
They will only work when passed as a launch argument:*
```
bcoin --spv --daemon
```
## 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.
- `prune`: Prune from the last 288 blocks (default: false).
- `checkpoints`: Use checkpoints and getheaders for the initial
sync (default: true).
- `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).
- `listen`: Accept incoming connections (default: true).
- `max-outbound`: Max number of outbound connections (default: 8).
- `max-inbound`: Max number of inbound connections (default: 8).
- `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.
- `nodes`: List of target nodes to connect to (comma-separated).
- `only`: List of nodes to ONLY connect to (no other nodes or dns seeds will
be contacted).
## 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 for mainnet).
- `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, may be different than
API key for wallet server).
- `cors`: Enable "Cross-Origin Resource Sharing" HTTP headers (default: false).
Note: For security `cors` should not be used with `no-auth`. \
If enabled you should also enable `wallet-auth` and set `api-key`.
## Wallet options
These options must be saved in `wallet.conf`. They can also be passed as
environment variables or command-line variables if they are preceeded with
a `wallet-` prefix. (See [CHANGELOG.md](https://github.com/bcoin-org/bcoin/blob/master/CHANGELOG.md#configuration-changes))
For example, to run a bcoin and wallet node on a remote server that you can
access from a local machine, you would launch bcoin with the command:
`bcoin --network=testnet --http-host=0.0.0.0 --wallet-http-host=0.0.0.0
--wallet-api-key=hunter2 --wallet-wallet-auth=true`
### Bcoin client:
- `node-host`: Location of bcoin node HTTP server (default: localhost).
- `node-port`: Port of bcoin node HTTP server (defaults to RPC port
of network).
- `node-ssl`: Whether to use SSL (default: false).
- `node-api-key`: API-key for bcoin HTTP server.
### Wallet database:
- `memory`: Keep database in memory rather than write to disk.
- `max-files`: Max open files for leveldb.
- `cache-size`: Size (in MB) of leveldb cache and write buffer.
- `witness`: Make SegWit enabled wallets.
- `checkpoints`: Trust hard-coded blockchain checkpoints.
### Wallet http server:
- `ssl`: Whether to use SSL (default: false).
- `ssl-key`: Path to SSL key.
- `ssl-cert`: Path to SSL cert.
- `http-host`: HTTP host to listen on (default: 127.0.0.1).
- `http-port`: HTTP port to listen on (default: 8334 for mainnet).
- `api-key`: API key (used for accessing all wallet APIs, may be different
than API key for node server).
- `cors`: Enable "Cross-Origin Resource Sharing" HTTP headers (default: false).
- `no-auth`: Disable auth for API server and wallets (default: false).
- `wallet-auth`: Enable token auth for wallets (default: false).
- `admin-token`: Token required if `wallet-auth` is enabled: restricts access
to [all wallet admin routes.](https://bcoin.io/api-docs/#wallet-admin-commands)
## Sample config files
- Node https://github.com/bcoin-org/bcoin/blob/master/etc/sample.conf
- Wallet https://github.com/bcoin-org/bcoin/blob/master/etc/sample.wallet.conf

View File

@ -1,72 +0,0 @@
# 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. Learn more about specific events and
event emitters at https://bcoin.io/guides/events.html
## 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 transferable 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

View File

@ -1,144 +0,0 @@
'use strict';
const bcoin = require('../..');
const client = require('bclient');
const plugin = bcoin.wallet.plugin;
const network = bcoin.Network.get('regtest');
const node = new bcoin.FullNode({
network: 'regtest',
memory: true
});
node.use(plugin);
const walletClient = new client.WalletClient({
port: network.walletPort
});
const nodeClient = new client.NodeClient({
port: network.rpcPort
});
async function fundWallet(wdb, addr) {
// Coinbase
const mtx = new bcoin.MTX();
mtx.addOutpoint(new bcoin.Outpoint(bcoin.consensus.ZERO_HASH, 0));
mtx.addOutput(addr, 50460);
mtx.addOutput(addr, 50460);
mtx.addOutput(addr, 50460);
mtx.addOutput(addr, 50460);
const tx = mtx.toTX();
walletClient.bind('balance', (walletID, balance) => {
console.log('New Balance:');
console.log(walletID, balance);
});
walletClient.bind('address', (walletID, receive) => {
console.log('New Receiving Address:');
console.log(walletID, receive);
});
walletClient.bind('tx', (walletID, details) => {
console.log('New Wallet TX:');
console.log(walletID, 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
}]
};
// API call: walletClient.send('test', options)
const tx = await walletClient.request('POST', '/wallet/test/send', options);
return tx.hash;
}
async function callNodeApi() {
// API call: nodeClient.getInfo()
const info = await nodeClient.request('GET', '/');
console.log('Server Info:');
console.log(info);
const json = await nodeClient.execute(
'getblocktemplate',
[{rules: ['segwit']}]
);
console.log('Block Template (RPC):');
console.log(json);
}
(async () => {
const wdb = node.require('walletdb').wdb;
await node.open();
// API call: walletClient.createWallet('test')
const testWallet = await walletClient.request('PUT', '/wallet/test');
console.log('Wallet:');
console.log(testWallet);
// open socket to listen for events
await walletClient.open();
// subscribe to events from all wallets
walletClient.all();
// Fund default account.
// API call: walletClient.createAddress('test', 'default')
const receive = await walletClient.request(
'POST',
'/wallet/test/address',
{account: 'default'}
);
await fundWallet(wdb, receive.address);
// API call: walletClient.getBalance('test', 'default')
const balance = await walletClient.request(
'GET',
'/wallet/test/balance',
{account: 'default'}
);
console.log('Balance:');
console.log(balance);
// API call: walletClient.createAccount('test', 'foo')
const acct = await walletClient.request('PUT', '/wallet/test/account/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);
// API call: walletClient.getTX('test', hash)
const tx = await walletClient.request('GET', `/wallet/test/tx/${hash}`);
console.log('Sent TX details:');
console.log(tx);
await callNodeApi();
await walletClient.close();
await node.close();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,50 +0,0 @@
'use strict';
/*
* Usage:
* Run another Bitcoin node on local regtest network, for example
* $ ../../bin/bcoin --network=regtest
* Execute this script with the other node's address and port
* $ node connect-to-peer.js 127.0.0.1:48444
*/
const bcoin = require('../..');
const network = bcoin.Network.get('regtest');
const peer = bcoin.Peer.fromOptions({
network: 'regtest',
agent: 'my-subversion',
hasWitness: () => {
return false;
}
});
const addr = bcoin.net.NetAddress.fromHostname(process.argv[2], 'regtest');
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]);
});

View File

@ -1,117 +0,0 @@
'use strict';
const bcoin = require('../..').set('main');
const Logger = require('blgr');
// Setup logger to see what's Bcoin doing.
const logger = new Logger({
level: 'info'
});
// Create a blockchain and store it in memory.
const chain = new bcoin.Chain({
memory: true,
network: 'main',
logger: logger
});
const mempool = new bcoin.Mempool({
chain: chain,
logger: logger
});
// Create a network pool of peers with a limit of 8 peers.
const pool = new bcoin.Pool({
chain: chain,
mempool: mempool,
maxPeers: 8,
logger: logger
});
(async function() {
await logger.open();
await chain.open();
await pool.open();
// Connect, start retrieving and relaying txs
await pool.connect();
// Start the blockchain sync.
pool.startSync();
// Watch the action
const color = '\x1b[31m';
chain.on('block', (block) => {
console.log(color, 'Added mainnet block:');
console.log(block.rhash());
});
mempool.on('tx', (tx) => {
console.log(color, 'Added mainnet tx to mempool:');
console.log(tx.rhash);
});
pool.on('tx', (tx) => {
console.log(color, 'Saw mainnet transaction:');
console.log(tx.rhash);
});
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});;
// Start up a testnet sync in-memory
// while we're at it (because we can).
const tchain = new bcoin.Chain({
memory: true,
network: 'testnet',
logger: logger
});
const tmempool = new bcoin.Mempool({
network: 'testnet',
chain: tchain,
logger: logger
});
const tpool = new bcoin.Pool({
network: 'testnet',
chain: tchain,
mempool: tmempool,
size: 8,
logger: logger
});
(async function() {
await tchain.open();
await tpool.open();
// Connect, start retrieving and relaying txs
await tpool.connect();
// Start the blockchain sync.
tpool.startSync();
const color = '\x1b[32m';
tchain.on('block', (block) => {
console.log(color, 'Added testnet block:');
console.log(block.rhash());
});
tmempool.on('tx', (tx) => {
console.log(color, 'Added testnet tx to mempool:');
console.log(tx.rhash);
});
tpool.on('tx', (tx) => {
console.log(color, 'Saw testnet transaction:');
console.log(tx.rhash);
});
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,43 +0,0 @@
'use strict';
const bcoin = require('../..');
// 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 bcoin.Chain({ network: 'regtest', memory: true });
const mempool = new bcoin.Mempool({ chain: chain });
const miner = new bcoin.Miner({
chain: chain,
mempool: mempool,
// Make sure miner won't block the main thread.
useWorkers: true
});
(async () => {
// Open the chain
await chain.open();
// Open the miner (initialize the databases, etc).
// Miner will implicitly call `open` on 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);
});

View File

@ -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.wallet.WalletKey(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);
});

View File

@ -1,27 +0,0 @@
'use strict';
const bcoin = require('../..');
const node = new bcoin.FullNode({
memory: true,
network: 'testnet',
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);
});

View File

@ -1,81 +0,0 @@
'use strict';
const bcoin = require('../..');
const fs = require('bfile');
// Create chain for testnet, stored in memory by default.
// To store the chain on disk at the `prefix` location,
// set `memory: false`.
const chain = new bcoin.Chain({
network: 'testnet',
indexTX: true,
indexAddress: true,
db: 'leveldb',
prefix: '/tmp/bcoin-testnet-example',
memory: true
});
// Create a network pool of peers with a limit of 8 peers.
const pool = new bcoin.Pool({
chain: chain,
maxPeers: 8
});
(async () => {
// Ensure the directory exists if we are writing to disk
if (!chain.options.memory)
await fs.mkdirp(chain.options.prefix);
await chain.open();
// Connect the blockchain to the network
await pool.open();
await pool.connect();
pool.startSync();
// Monitor blockchain height and react when we hit the target
chain.on('connect', async (entry, block) => {
const height = entry.height;
console.log(
`Height: ${chain.height} ` +
`Block: ${entry.rhash()} ` +
`TXs: ${block.txs.length}`
);
if (height === 1000) {
const entry = await chain.getEntry(1000);
console.log('Block at height 1000:\n', entry);
// testnet tx at height 500
const txhash =
'fc407d7a3b819daa5cf1ecc2c2a4b103c3782104d1425d170993bd534779a0da';
const txhashBuffer = Buffer.from(txhash, 'hex').reverse();
const txmeta = await chain.db.getMeta(txhashBuffer);
const tx = txmeta.tx;
const coinview = await chain.db.getSpentView(tx);
console.log(`Tx with hash ${txhash}:\n`, txmeta);
console.log(
`\n Input value: ${tx.getInputValue(coinview)}` +
`\n Output value: ${tx.getOutputValue()}` +
`\n Fee: ${tx.getFee(coinview)}`
);
// testnet block at height 800
const hash =
Buffer.from(
'000000004df86f64cca38c6587df348e0c6849ebee628b3f840f552c707cc862',
'hex'
);
// chainDB indexes blocks by the REVERSE (little endian) hash
const block = await chain.getBlock(hash.reverse());
console.log(`Block with hash ${hash.toString('hex')}:`, block);
process.exit(1);
}
});
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,50 +0,0 @@
'use strict';
const bcoin = require('../..');
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 bcoin.FullNode({
memory: true,
network: 'testnet',
workers: true
});
node.use(MyPlugin);
(async () => {
const plugin = node.require('my-plugin');
await node.open();
await node.connect();
plugin.sayPeers();
await node.close();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,84 +0,0 @@
'use strict';
const bcoin = require('../..');
bcoin.set('regtest');
// SPV chains only store the chain headers.
const chain = new bcoin.Chain({
spv: true
});
const pool = new bcoin.Pool({
chain: chain,
maxOutbound: 1
});
const walletdb = new bcoin.wallet.WalletDB({ memory: true });
// Full node will provide tx data to SPV node
const full = {};
full.chain = new bcoin.Chain();
full.pool = new bcoin.Pool({
chain: full.chain,
port: 44444,
bip37: true,
listen: true
});
(async () => {
await pool.open();
await walletdb.open();
await chain.open();
await pool.connect();
await full.pool.open();
await full.chain.open();
await full.pool.connect();
const wallet = await walletdb.create();
const walletAddress = await wallet.receiveAddress();
console.log('Created wallet with address %s', walletAddress);
// Add our address to the SPV filter.
pool.watchAddress(walletAddress);
// Start the blockchain sync.
pool.startSync();
// Get ready to receive transactions!
pool.on('tx', (tx) => {
console.log('Received TX:\n', tx);
walletdb.addTX(tx);
console.log('TX added to wallet DB!');
});
wallet.on('balance', (balance) => {
console.log('Balance updated:\n', balance.toJSON());
});
// Connect the SPV node to the full node server
const netAddr = await pool.hosts.addNode('127.0.0.1:44444');
const peer = pool.createOutbound(netAddr);
pool.peers.add(peer);
full.pool.on('peer open', async () => {
console.log('SPV node peers:\n', pool.peers);
console.log('Full node peers:\n', full.pool.peers);
// Create a dummy transaction and send it from full to SPV node
const mtx = new bcoin.MTX();
mtx.addOutpoint(new bcoin.Outpoint(bcoin.consensus.ZERO_HASH, 0));
mtx.addOutput(walletAddress, 12000);
const tx = mtx.toTX();
// Give the node a few seconds to process connection before sending
console.log('Waiting for transaction...');
await new Promise(r => setTimeout(r, 3000));
await full.pool.broadcast(tx);
});
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,45 +0,0 @@
'use strict';
const bcoin = require('../..');
const random = require('bcrypto/lib/random');
function dummy() {
const hash = random.randomBytes(32);
return new bcoin.Outpoint(hash, 0);
}
const walletdb = new bcoin.wallet.WalletDB({
network: 'testnet',
memory: true
});
(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 bcoin.MTX();
mtx.addOutpoint(dummy());
mtx.addOutput(acct.receiveAddress(), 50460);
const tx = mtx.toTX();
wallet.on('tx', (tx) => {
console.log('Received transaciton:\n', tx);
});
await walletdb.addTX(tx);
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,70 +0,0 @@
'use strict';
const bcoin = require('../..');
(async () => {
// use well known test mnemonic
const phrase = [
'abandon', 'abandon', 'abandon', 'abandon',
'abandon', 'abandon', 'abandon', 'abandon',
'abandon', 'abandon', 'abandon', 'about'
].join(' ');
const network = bcoin.Network.get('regtest');
const mnemonic = bcoin.Mnemonic.fromPhrase(phrase);
// m'
const priv = bcoin.HDPrivateKey.fromMnemonic(mnemonic);
// m'/44'
const bip44Key = priv.derive(44, true);
// m'/44'/0'
const bitcoinKey = bip44Key.derive(0, true);
// m'/44'/0'/0'
const accountKey = bitcoinKey.derive(0, true);
// account extended public key
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format
const xpub = accountKey.xpubkey(network.type);
console.log('xpub to import:\n', xpub);
// recommended to use hardware wallet to derive keys
// see github.com/bcoin-org/bledger
// create watch only wallet
// the wallet will generate lookahead
// addresses from the account extended public key
// and can find spendable coins in the blockchain state
const wdb = new bcoin.wallet.WalletDB({
network: 'regtest',
memory: true
});
await wdb.open();
// new wallet still generates a master private key, but it will not be used
const wallet = await wdb.create({
name: 'my-watch-only-wallet',
accountKey: xpub,
watchOnly: true
});
// xpub account key placed at Account 0. Address 0 is already derived.
const acct0 = await wallet.getAccount(0);
// create new receive addresses through the deterministic chain
const key1 = await wallet.createReceive(0);
const addr1 = key1.getAddress('string', 'regtest');
const key2 = await wallet.createReceive(0);
const addr2 = key2.getAddress('string', 'regtest');
console.log('Wallet:\n', wallet);
console.log('Account:\n', acct0);
console.log('Address 1:\n', addr1);
console.log('Address 2:\n', addr2);
})();

View File

@ -1,218 +0,0 @@
# Getting started
## 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 >=v8.14.0
- npm >=v6.4.1
- 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 git for security purposes, as there
are security issues when installing via npm. 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 Git
``` bash
$ curl https://keybase.io/chjj/pgp_keys.asc | gpg --import
$ git clone git://github.com/bcoin-org/bcoin.git
$ cd bcoin
```
For a specific release:
```
$ git tag
$ git tag -v <version> # verify signature
$ git checkout <version>
```
Install dependencies:
```
$ npm install
$ npm install -g # link globally
```
**Note:** Dependencies are checked for integrity using `package-lock.json`.
However `npm` _will not_ make these checks with `npm install -g` and it
will link your installation globally so that `bcoin` is in your
path _(e.g. $ bcoin)_.
### Installing via Docker
Check [bcoin-docker](https://github.com/bcoin-org/bcoin-docker)
### Installing on Windows
Install OpenSSL v1.0.2L 64-Bit:
https://slproweb.com/download/Win64OpenSSL-1_0_2L.exe
As Administrator, open `cmd.exe` and run:
```console
C:\Users\bcoin\bcoin>npm install --global --production windows-build-tools
```
to install `VCBuild.exe` and `Python 2.7.x` both required by `node-gyp`
for building native modules.
Then continue [Installing via Git](#installing-via-git)
Note that you need a shell that supports bash scripts, like Git Bash to launch
bcoin.
### 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 randomly generated if no key was chosen, but not explicitly reported to
the user. 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/
```
[bclient](https://github.com/bcoin-org/bclient) is the prepackaged tool for
querying both the REST and RPC APIs. If bcoin is installed globally, both
`bcoin-cli` and `bwallet-cli` should be on your path.
``` bash
$ bcoin-cli info --api-key hunter2
$ bcoin-cli rpc getblockchaininfo --api-key hunter2
$ bwallet-cli balance
```
## 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, use `--only`
``` bash
$ bcoin --only foo.example.com,1.2.3.4,5.6.7.8
```
## 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
[configuration]: configuration.md

View File

@ -1,53 +0,0 @@
# 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 are based on 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 wallets, with many accounts, with many
addresses for each account. Bcoin should theoretically be able to scale to
hundreds of thousands of wallets/accounts/addresses.
## Deviation from BIP44
**It's important to backup the wallet database.** There are several deviations
from [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki)
that break the determinsitic algorithm, and therefore it's recommended to
backup the wallet database any time an account is created, as there are several
possible configurations of an account.
There is a command available via the wallet RPC called `backupwallet` that can
clone the database to a new destination. There are also the RPC calls
`dumpwallet` and `dumpprivkey` for exporting private keys. After shutting down
the wallet process, it's also possible to copy the LevelDB database from the
default location at `~/.bcoin/wallet` for main net or
`~/.bcoin/<network>/wallet` for others. Copying LevelDB while the process is
running can result in a corrupted copy. LevelDB is also prone to
[database corruption](https://en.wikipedia.org/wiki/LevelDB#Bugs_and_reliability).
Each account can be of a different type. You could have a pubkeyhash account,
a multisig account, and a witness pubkeyhash account all in the same wallet.
Accounts can be configured with or without Segregated Witness and both base58
(nested-in-P2SH) and bech32 (native) P2WPKH addresses can be derived from the
same account.
Bcoin adds a third branch to each account for nested SegWit addresses.
Branch `0` and `1` are for `receive` and `change` addresses respectively
(which is BIP44 standard) but branch `2` is used by bcoin to derive
[nested SegWit addresses.](https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH_nested_in_BIP16_P2SH)
Accounts in a bcoin wallet can be configured for multisig and import xpubs
from cosigners. Externally-generated Extended Private Keys (`xpriv`) and non-HD
single address private keys can all be imported into a bcoin wallet. Balances
of those addresses can be watched as well spent from (in the case of a private
key).
Unlike [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki),
bcoin does not limit account depth and a new account can be created
after an empty account. This can create issues with deterministic account
discovery from the master node (seed) as there are `2 ^ 31 - 1` _(worst case)_
possible accounts to search.

1
etc/authorized-peers Normal file
View File

@ -0,0 +1 @@
02b9f7499c4166e76d3a64326bbbe92dc02f0e07dc184f94995da61683c311cb0f

152
etc/certs.json Normal file
View File

@ -0,0 +1,152 @@
[
"ebd41040e4bb3ec742c9e381d31ef2a41a48b6685c96e7cef3c1df6cd4331c99",
"ca42dd41745fd0b81eb902362cf9d8bf719da1bd1b1efc946f5b4c99f42c1b9e",
"eb04cf5eb1f39afa762f2bb120f296cba520c1b97db1589565b81cb9a17b7244",
"6dc47172e01cbcb0bf62580d895fe2b8ac9ad4f873801e0c10b9c837d21eb177",
"16af57a9f676b0ab126095aa5ebadef22ab31119d644ac95cd4b93dbf3f26aeb",
"8c7209279ac04e275e16d07fd3b775e80154b5968046e31f52dd25766324e9a7",
"687fa451382278fff0c8b11f8d43d576671c6eb2bceab413fb83d965d06d2ff2",
"0791ca0749b20782aad3c7d7bd0cdfc9485835843eb2d7996009ce43ab6c6927",
"8095210805db4bbc355e4428d8fd6ec2cde3ab5fb97a9942988eb8f4dcd06016",
"73c176434f1bc6d5adf45b0e76e727287c8de57616c1e6e6141a2b2cbc7d8e4c",
"af8b6762a1e528228161a95d5c559ee266278f75d79e830189a503506abd6b4c",
"ff856a2d251dcd88d36656f450126798cfabaade40799c722de4d2b5db36a73a",
"ca2d82a08677072f8ab6764ff035676cfe3e5e325e012172df3f92096db79b85",
"a0459b9f63b22559f5fa5d4c6db3f9f72ff19342033578f073bf1d1b46cbb912",
"a0234f3bc8527ca5628eec81ad5d69895da5680dc91d1cb8477f33f878b95b0b",
"69fac9bd55fb0ac78d53bbee5cf1d597989fd0aaab20a25151bdf1733ee7d122",
"d8e0febc1db2e38d00940f37d27d41344d993e734b99d5656d9778d4d8143624",
"d7a7a0fb5d7e2731d771e9484ebcdef71d5f0c3e0a2948782bc83ee0ea699ef4",
"bd81ce3b4f6591d11a67b5fc7a47fdef25521bf9aa4e18b9e3df2e34a7803be8",
"3f06e55681d496f5be169eb5389f9f2b8ff61e1708df6881724849cd5d27cb69",
"a45ede3bbbf09c8ae15c72efc07268d693a21c996fd51e67ca079460fd6d8873",
"85a0dd7dd720adb7ff05f83d542b209dc7ff4528f7d677b18389fea5e5c49e86",
"18f1fc7f205df8adddeb7fe007dd57e3af375a9c4d8d73546bf4f1fed1e18d35",
"e75e72ed9f560eec6eb4800073a43fc3ad19195a392282017895974a99026b6c",
"7908b40314c138100b518d0735807ffbfcf8518a0095337105ba386b153dd927",
"6ea54741d004667eed1b4816634aa3a79e6e4b96950f8279dafc8d9bd8812137",
"0c258a12a5674aef25f28ba7dcfaeceea348e541e6f5cc4ee63b71b361606ac3",
"ef3cb417fc8ebf6f97876c9e4ece39de1ea5fe649141d1028b7d11c0b2298ced",
"cecddc905099d8dadfc5b1d209b737cbe2c18cfb2c10c0ff0bcf0d3286fc1aa2",
"c3846bf24b9e93ca64274c0ec67c1ecc5e024ffcacd2d74019350e81fe546ae4",
"1465fa205397b876faa6f0a9958e5590e40fcc7faa4fb7c2c8677521fb5fb658",
"c766a9bef2d4071c863a31aa4920e813b2d198608cb7b7cfe21143b836df09ea",
"7600295eefe85b9e1fd624db76062aaaae59818a54d2774cd4c0b2c01131e1b3",
"21db20123660bb2ed418205da11ee7a85a65e2bc6e55b5af7e7899c8a266d92e",
"3e9099b5015e8f486c00bcea9d111ee721faba355a89bcf1df69561e3dc6325c",
"4348a0e9444c78cb265e058d5e8944b4d84f9662bd26db257f8934a443c70161",
"7431e5f4c3c1ce4690774f0b61e05440883ba9a01ed00ba6abd7806ed3b118cf",
"0f993c8aef97baaf5687140ed59ad1821bb4afacf0aa9a58b5d57a338a3afbcb",
"0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739",
"767c955a76412c89af688e90a1c70f556cfd6b6025dbea10416d7eb6831f8c40",
"62dd0be9b9f50a163ea0f8e75c053b1eca57ea55c8688f647c6881f2c8357b95",
"be6c4da2bbb9ba59b6f3939768374246c3c005993fa98f020d1dedbed48a81d5",
"37d51006c512eaab626421f1ec8c92013fc5f82ae98ee533eb4619b8deb4d06c",
"8d722f81a9c113c0791df136a2966db26c950a971db46b4199f4ea54b78bfb9f",
"9acfab7e43c8d880d06b262a94deeee4b4659989c3d0caf19baf6405e41ab7df",
"f1c1b50ae5a20dd8030ec9f6bc24823dd367b5255759b4e71b61fce9f7375d73",
"4200f5043ac8590ebb527d209ed1503029fbcbd41ca1b506ec27f15ade7dac69",
"0c2cd63df7806fa399ede809116b575bf87989f06518f9808c860503178baf66",
"15f0ba00a3ac7af3ac884c072b1011a077bd77c097f40164b2f8598abd83860c",
"a71272aeaaa3cfe8727f7fb39f0fb3d1e5426e9060b06ee6f13e9a3c5833cd43",
"1793927a0614549789adce2f8f34f7f0b66d0f3ae3a3b84d21ec15dbba4fadc7",
"b9bea7860a962ea3611dab97ab6da3e21c1068b97d55575ed0e11279c11c8932",
"a22dba681e97376e2d397d728aae3a9b6296b9fdba60bc2e11f647f2c675fb37",
"41c923866ab4cad6b7ad578081582e020797a6cbdf4fff78ce8396b38937d7f5",
"327a3d761abadea034eb998406275cb1a4776efdae2fdf6d0168ea1c4f5567d0",
"e3b6a2db2ed7ce48842f7ac53241c7b71d54144bfb40c11f3f1d0b42f5eea12d",
"b6191a50d0c3977f7da99bcdaac86a227daeb9679ec70ba3b0c9d92271c170d3",
"960adf0063e96356750c2965dd0a0867da0b9cbd6e77714aeafb2349ab393da3",
"c0a6f4dc63a24bfdcf54ef2a6a082a0a72de35803e2ff5ff527ae5d87206dfd5",
"e4c73430d7a5b50925df43370a0d216e9a79b9d6db8373a0c69eb1cc31c7c52a",
"0f4e9cdd264b025550d170806340214fe94434c9b02f697ec710fc5feafb5e38",
"35ae5bddd8f7ae635cffba5682a8f00b95f48462c7108ee9a0e5292b074aafb2",
"eaa962c4fa4a6bafebe415196d351ccd888d4f53f3fa8ae6d7c466a94e6042bb",
"e28393773da845a679f2080cc7fb44a3b7a1c3792cb7eb7729fdcb6a8d99aea7",
"2d47437de17951215a12f3c58e51c729a58026ef1fcc0a5fb3d9dc012f600d19",
"b478b812250df878635c2aa7ec7d155eaa625ee82916e2cd294361886cd1fbd4",
"a4310d50af18a6447190372a86afaf8b951ffb431d837f1e5688b45971ed1557",
"4b03f45807ad70f21bfc2cae71c9fde4604c064cf5ffb686bae5dbaad7fdd34c",
"5edb7ac43b82a06a8761e8d7be4979ebf2611f7dd79bf91c1c6b566a219ed766",
"2399561127a57125de8cefea610ddf2fa078b5c8067f4e828290bfb860e84b3c",
"69ddd7ea90bb57c93e135dc85ea6fcd5480b603239bdc454fc758b2a26cf7f79",
"6c61dac3a2def031506be036d2a6fe401994fbd13df9c8d466599274c446ec98",
"668c83947da63b724bece1743c31a0e6aed0db8ec5b31be377bb784f91b6716f",
"ecc3e9c3407503bee091aa952f41348ff88baa863b2264befac807901574e939",
"f9e67d336c51002ac054c632022d66dda2e7e3fff10ad061ed31d8bbb410cfb2",
"bf0feefb9e3a581ad5f9e9db7589985743d261085c4d314f6f5d7259aa421612",
"03950fb49a531f3e1991942398dfa9e0ea32d7ba1cdd9bc85db57ed9400b434a",
"3c5f81fea5fab82c64bfa2eaecafcde8e077fc8620a7cae537163df36edbf378",
"cbb522d7b7f127ad6a0113865bdf1cd4102e7d0759af635a7cf4720dc963c53b",
"04048028bf1f2864d48f9ad4d83294366a828856553f3b14303f90147f5d40ef",
"2530cc8e98321502bad96f9b1fba1b099e2d299e0f4548bb914f363bc0d4531f",
"063e4afac491dfd332f3089b8542e94617d893d7fe944e10a7937ee29d9693c0",
"136335439334a7698016a0d324de72284e079d7b5220bb8fbd747816eebebaca",
"45140b3247eb9cc8c5b4f0d7b53091f73292089e6e5a63e2749dd3aca9198eda",
"2ce1cb0bf9d2f9e102993fbe215152c3b2dd0cabde1c68e5319b839154dbb7f5",
"568d6905a2c88708a4b3025190edcfedb1974a606a13c6e5290fcb2ae63edab5",
"0376ab1d54c5f9803ce4b2e201a0ee7eef7b57b636e8a93c9b8d4860c96f5fa7",
"0a81ec5a929777f145904af38d5d509f66b5e2c58fcdb531058b0e17f3f0b41b",
"70a73f7f376b60074248904534b11482d5bf0e698ecc498df52577ebf2e93b9a",
"bd71fdf6da97e4cf62d1647add2581b07d79adf8397eb4ecba9c5e8488821423",
"5c58468d55f58e497e743982d2b50010b6d165374acf83a7d4a32db768c4408e",
"fcbfe2886206f72b27593c8b070297e12d769ed10ed7930705a8098effc14d17",
"8c4edfd04348f322969e7e29a4cd4dca004655061c16e1b076422ef342ad630e",
"bfd88fe1101c41ae3e801bf8be56350ee9bad1a6b9bd515edc5c6d5b8711ac44",
"513b2cecb810d4cde5dd85391adfc6c2dd60d87bb736d2b521484aa47a0ebef6",
"88497f01602f3154246ae28c4d5aef10f1d87ebb76626f4ae0b7f95ba7968799",
"bc104f15a48be709dca542a7e1d4b9df6f054527e802eaa92d595444258afe71",
"55926084ec963a64b96e2abe01ce0ba86a64fbfebcc7aab5afc155b37fd76066",
"c1b48299aba5208fe9630ace55ca68a03eda5a519c8802a0d3a673be8f8e557d",
"e17890ee09a3fbf4f48b9c414a17d637b7a50647e9bc752322727fcc1742a911",
"c7ba6567de93a798ae1faa791e712d378fae1f93c4397fea441bb7cbe6fd5995",
"9a114025197c5bb95d94e63d55cd43790847b646b23cdf11ada4a00eff15fb48",
"edf7ebbca27a2a384d387b7d4010c666e2edb4843e4c29b4ae1d5b9332e6b24d",
"fd73dad31c644ff1b43bef0ccdda96710b9cd9875eca7e31707af3e96d522bbd",
"3e84ba4342908516e77573c0992f0979ca084e4685681ff195ccba8a229b8a76",
"978cd966f2faa07ba7aa9500d9c02e9d77f2cdada6ad6ba74af4b91c66593c50",
"49e7a442acf0ea6287050054b52564b650e4f49e42e348d6aa38e039e957b1c1",
"eec5496b988ce98625b934092eec2908bed0b0f316c2d4730c84eaf1f3d34881",
"3cfc3c14d1f684ff17e38c43ca440c00b967ec933e8bfe064ca1d72c90f2adb0",
"1c01c6f4dbb2fefc22558b2bca32563f49844acfc32b7be4b0ff599f9e8c7af7",
"f09b122c7114f4a09bd4ea4f4a99d558b46e4c25cd81140d29c05613914c3841",
"d95fea3ca4eedce74cd76e75fc6d1ff62c441f0fa8bc77f034b19e5db258015d",
"f96f23f4c3e79c077a46988d5af5900676a0f039cb645dd17549b216c82440ce",
"e23d4a036d7b70e9f595b1422079d2b91edfbb1fb651a0633eaa8a9dc5f80703",
"9a6ec012e1a7da9dbe34194d478ad7c0db1822fb071df12981496ed104384113",
"59769007f7685d0fcd50872f9f95d5755a5b2b457d81f3692b610a98672f0e1b",
"dd6936fe21f8f077c123a1a521c12224f72255b73e03a7260693e8a24b0fa389",
"b0bfd52bb0d7d9bd92bf5d4dc13da255c02c542f378365ea893911f55e55f23c",
"91e2f5788d5810eba7ba58737de1548a8ecacd014598bc0b143e041b17052552",
"f356bea244b7a91eb35d53ca9ad7864ace018e2d35d5f8f96ddf68a6f41aa474",
"8a866fd1b276b57e578e921c65828a2bed58e9f2f288054134b7f1f4bfc9cc74",
"8fe4fb0af93a4d0d67db0bebb23e37c71bf325dcbcdd240ea04daf58b47e1840",
"88ef81de202eb018452e43f864725cea5fbd1fc2d9d205730709c5d8b8690f46",
"7d05ebb682339f8c9451ee094eebfefa7953a114edb2f44949452fab7d2fc185",
"7e37cb8b4c47090cab36551ba6f45db840680fba166a952db100717f43053fc2",
"cb3ccbb76031e5e0138f8dd39a23f9de47ffc35e43c1144cea27d46a5ab1cb5f",
"31ad6648f8104138c738f39ea4320133393e3a18cc02296ef97c2ac9ef6731d0",
"552f7bdcf1a7af9e6ce672017f4f12abf77240c78e761ac203d1d9d20ac89988",
"4b22d5a6aec99f3cdb79aa5ec06838479cd5ecba7164f7f22dc1d65f63d85708",
"d6f034bd94aa233f0297eca4245b283973e447aa590f310c77f48fdf83112254",
"52f0e1c4e58ec629291b60317f074671b85d7ea80d5b07273463534b32b40234",
"e793c9b02fd8aa13e21c31228accb08119643b749c898964b1746d46c3d4cbd2",
"4ff460d54b9c86dabfbcfc5712e0400d2bed3fbc4d4fbdaa86e06adcd2a9ad7a",
"bec94911c2955676db6c0a550986d76e3ba005667c442c9762b4fbb773de228c",
"179fbc148a3dd00fd24ea13458cc43bfa7f59c8182d783a513f6ebec100c8924",
"3c4fb0b95ab8b30032f432b86f535fe172c185d0fd39865837cf36187fa6f428",
"4d2491414cfe956746ec4cefa6cf6f72e28a1329432f9d8a907ac4cb5dadc15a",
"5d56499be4d2e08bcfcad08a3e38723d50503bde706948e42f55603019e528ae",
"30d0895a9a448a262091635522d1f52010b5867acae12c78ef958fd4f4389f2f",
"43df5774b03e7fef5fe40d931a7bedf1bb2e6b42738c4e6d3841103d3aa7f339",
"02ed0eb28c14da45165c566791700d6451d7fb56f0b2ab1d3b8eb070e56edff5",
"5cc3d78e4e1d5e45547a04e6873e64f90cf9536d1ccc2ef800f355c4c5fd70fd",
"49351b903444c185ccdc5c693d24d8555cb208d6a8141307699f4af063199d78",
"8de78655e1be7f7847800b93f694d21d368cc06e033e7fab04bb5eb99da6b700",
"2a99f5bc1174b73cbb1d620884e01c34e51ccb3978da125f0e33268883bf4158",
"6b9c08e86eb0f767cfad65cd98b62149e5494a67f5845e7bd1ed019f27b86bd6",
"d487a56f83b07482e85e963394c1ecc2c9e51d0903ee946b02c301581ed99e16",
"8b45da1c06f791eb0cabf26be588f5fb23165c2e614bf885562d0dce50b29b02",
"a1339d33281a0b56e557d3d32b1ce7f9367eb094bd5fa72a7e5004c8ded7cafe",
"b676f2eddae8775cd36cb0f63cd1d4603961f49e6265ba013a2f0307b6d0b804"
]

1
etc/known-peers Normal file
View File

@ -0,0 +1 @@
node.bcoin.io,52.39.113.206 02b9f7499c4166e76d3a64326bbbe92dc02f0e07dc184f94995da61683c311cb0f

View File

@ -1,110 +1,64 @@
# Sample bcoin config file (~/.bcoin/bcoin.conf)
#
# Options
#
network: main
use-workers: true
# max-workers: 4
# worker-timeout: 5000
# sigcache-size: 50000
# network: main
#
# Node
#
prefix: ~/.bcoin
db: leveldb
max-files: 64
cache-size: 100
# fast: false
#
# Workers
#
workers: true
# workers-size: 4
# workers-timeout: 5000
#
# Logger
#
log-level: debug
log-console: true
log-file: true
#
# Chain
#
prune: false
checkpoints: true
entry-cache: 5000
# witness: true
# prune: false
use-checkpoints: true
coin-cache: true
index-tx: false
index-address: false
#
# Mempool
#
# limit-free: true
# limit-free-relay: 15
# reject-absurd-fees: true
# replace-by-fee: false
mempool-size: 100
limit-free: true
limit-free-relay: 15
reject-absurd-fees: true
replace-by-fee: false
persistent-mempool: false
#
# Pool
#
selfish: false
# selfish: false
headers: false
compact: true
bip37: false
listen: true
max-outbound: 8
max-inbound: 30
# Proxy Server (browser=websockets, node=socks)
# proxy: foo:bar@127.0.0.1:9050
# onion: true
# upnp: true
# Custom list of DNS seeds
# seeds: seed.bitcoin.sipa.be
# Local Host & Port (to listen on)
host: ::
bip151: true
# proxy-server: localhost
# preferred-seed: seed.bitcoin.sipa.be
# ignore-discovery: false
# port: 8333
listen: true
max-peers: 8
max-leeches: 30
bip150: false
identity-key: 74b4147957813b62cc8987f2b711ddb31f8cb46dcbf71502033da66053c8780a
auth-peers: ./authorized-peers
known-peers: ./known-peers
# Public Host & Port (to advertise to peers)
# public-host: 1.2.3.4
# public-port: 8444
# Always try to connect to these nodes.
# nodes: 127.0.0.1,127.0.0.2
# Only try to connect to these nodes.
# only: 127.0.0.1,127.0.0.2
#
# Miner
#
# payout-address: 1111111111111111111114oLvT2
# coinbase-flags: mined by bcoin
coinbase-flags: mined by bcoin
# coinbase-address: 1111111111111111111114oLvT2,1111111111111111111114oLvT2
preverify: false
max-block-weight: 4000000
reserved-block-weight: 4000
reserved-block-sigops: 400
#
# HTTP
#
http-host: ::
# http-port: 8332
# ssl: true
# ssl-cert: @/ssl/cert.crt
# ssl-key: @/ssl/priv.key
# http-port: 8332
# http-host: 0.0.0.0
# service-key: bikeshed
api-key: bikeshed
wallet-auth: false
# no-auth: false
# cors: false

View File

@ -1,28 +0,0 @@
# Sample bcoin wallet config file (~/.bcoin/wallet.conf)
#
# Options
#
# network: main
#
# HTTP
#
http-host: ::
# http-port: 8334
# ssl: true
# ssl-cert: @/ssl/cert.crt
# ssl-key: @/ssl/priv.key
api-key: bikeshed
# no-auth: false
# cors: false
#
# Wallet
#
witness: false
checkpoints: true
wallet-auth: false

View File

@ -16,7 +16,7 @@
"opts": {
"template": "templates/default",
"encoding": "utf8",
"destination": "./docs/reference",
"destination": "./docs/",
"recurse": true,
"private": true,
"pedantic": true

View File

@ -1,131 +0,0 @@
/*!
* bcoin.js - a javascript bitcoin library.
* Copyright (c) 2014-2015, Fedor Indutny (MIT License).
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* A bcoin "environment" which exposes all
* constructors for primitives, the blockchain,
* mempool, wallet, etc. It also exposes a
* global worker pool.
*
* @exports bcoin
* @type {Object}
*/
const bcoin = exports;
/**
* Set the default network.
* @param {String} network
*/
bcoin.set = function set(network) {
bcoin.Network.set(network);
return bcoin;
};
/*
* Expose
*/
// Blockchain
bcoin.blockchain = require('./blockchain');
bcoin.Chain = require('./blockchain/chain');
bcoin.ChainEntry = require('./blockchain/chainentry');
// BTC
bcoin.btc = require('./btc');
bcoin.Amount = require('./btc/amount');
bcoin.URI = require('./btc/uri');
// Coins
bcoin.coins = require('./coins');
bcoin.Coins = require('./coins/coins');
bcoin.CoinEntry = require('./coins/coinentry');
bcoin.CoinView = require('./coins/coinview');
// HD
bcoin.hd = require('./hd');
bcoin.HDPrivateKey = require('./hd/private');
bcoin.HDPublicKey = require('./hd/public');
bcoin.Mnemonic = require('./hd/mnemonic');
// Index
bcoin.indexer = require('./indexer');
bcoin.Indexer = require('./indexer/indexer');
bcoin.TXIndexer = require('./indexer/txindexer');
bcoin.AddrIndexer = require('./indexer/addrindexer');
// Mempool
bcoin.mempool = require('./mempool');
bcoin.Fees = require('./mempool/fees');
bcoin.Mempool = require('./mempool/mempool');
bcoin.MempoolEntry = require('./mempool/mempoolentry');
// Miner
bcoin.mining = require('./mining');
bcoin.Miner = require('./mining/miner');
// Net
bcoin.net = require('./net');
bcoin.packets = require('./net/packets');
bcoin.Peer = require('./net/peer');
bcoin.Pool = require('./net/pool');
// Node
bcoin.node = require('./node');
bcoin.Node = require('./node/node');
bcoin.FullNode = require('./node/fullnode');
bcoin.SPVNode = require('./node/spvnode');
// Primitives
bcoin.primitives = require('./primitives');
bcoin.Address = require('./primitives/address');
bcoin.Block = require('./primitives/block');
bcoin.Coin = require('./primitives/coin');
bcoin.Headers = require('./primitives/headers');
bcoin.Input = require('./primitives/input');
bcoin.InvItem = require('./primitives/invitem');
bcoin.KeyRing = require('./primitives/keyring');
bcoin.MerkleBlock = require('./primitives/merkleblock');
bcoin.MTX = require('./primitives/mtx');
bcoin.Outpoint = require('./primitives/outpoint');
bcoin.Output = require('./primitives/output');
bcoin.TX = require('./primitives/tx');
// Protocol
bcoin.protocol = require('./protocol');
bcoin.consensus = require('./protocol/consensus');
bcoin.Network = require('./protocol/network');
bcoin.networks = require('./protocol/networks');
bcoin.policy = require('./protocol/policy');
// Script
bcoin.script = require('./script');
bcoin.Opcode = require('./script/opcode');
bcoin.Program = require('./script/program');
bcoin.Script = require('./script/script');
bcoin.ScriptNum = require('./script/scriptnum');
bcoin.SigCache = require('./script/sigcache');
bcoin.Stack = require('./script/stack');
bcoin.Witness = require('./script/witness');
// Utils
bcoin.utils = require('./utils');
bcoin.util = require('./utils/util');
// Wallet
bcoin.wallet = require('./wallet');
bcoin.WalletDB = require('./wallet/walletdb');
// Workers
bcoin.workers = require('./workers');
bcoin.WorkerPool = require('./workers/workerpool');
// Package Info
bcoin.pkg = require('./pkg');

View File

@ -1,154 +1,25 @@
/*!
* bcoin.js - a javascript bitcoin library.
/**
* Javascript bitcoin library. Exposes the global environment.
* @module bcoin
* @see {Environment}
* @license
* Copyright (c) 2014-2015, Fedor Indutny (MIT License).
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin
*/
/* eslint prefer-arrow-callback: "off" */
'use strict';
/**
* A bcoin "environment" which exposes all
* constructors for primitives, the blockchain,
* mempool, wallet, etc. It also exposes a
* global worker pool.
*
* @exports bcoin
* @type {Object}
*/
const bcoin = exports;
/**
* Define a module for lazy loading.
* @param {String} name
* @param {String} path
*/
bcoin.define = function define(name, path) {
let cache = null;
Object.defineProperty(bcoin, name, {
enumerable: true,
get() {
if (!cache)
cache = require(path);
return cache;
}
});
};
/**
* Set the default network.
* @param {String} network
*/
bcoin.set = function set(network) {
bcoin.Network.set(network);
return bcoin;
};
var env = require('./env');
var utils = require('./utils/utils');
var global = utils.global;
/*
* Expose
* Expose bcoin globally in the
* browser. Necessary for workers.
*/
// Blockchain
bcoin.define('blockchain', './blockchain');
bcoin.define('blockstore', './blockstore');
bcoin.define('Chain', './blockchain/chain');
bcoin.define('ChainEntry', './blockchain/chainentry');
if (utils.isBrowser)
global.bcoin = env;
// BTC
bcoin.define('btc', './btc');
bcoin.define('Amount', './btc/amount');
bcoin.define('URI', './btc/uri');
// Coins
bcoin.define('coins', './coins');
bcoin.define('Coins', './coins/coins');
bcoin.define('CoinEntry', './coins/coinentry');
bcoin.define('CoinView', './coins/coinview');
// HD
bcoin.define('hd', './hd');
bcoin.define('HDPrivateKey', './hd/private');
bcoin.define('HDPublicKey', './hd/public');
bcoin.define('Mnemonic', './hd/mnemonic');
// Index
bcoin.define('indexer', './indexer');
bcoin.define('Indexer', './indexer/indexer');
bcoin.define('TXIndexer', './indexer/txindexer');
bcoin.define('AddrIndexer', './indexer/addrindexer');
// Mempool
bcoin.define('mempool', './mempool');
bcoin.define('Fees', './mempool/fees');
bcoin.define('Mempool', './mempool/mempool');
bcoin.define('MempoolEntry', './mempool/mempoolentry');
// Miner
bcoin.define('mining', './mining');
bcoin.define('Miner', './mining/miner');
// Net
bcoin.define('net', './net');
bcoin.define('packets', './net/packets');
bcoin.define('Peer', './net/peer');
bcoin.define('Pool', './net/pool');
// Node
bcoin.define('node', './node');
bcoin.define('Node', './node/node');
bcoin.define('FullNode', './node/fullnode');
bcoin.define('SPVNode', './node/spvnode');
// Primitives
bcoin.define('primitives', './primitives');
bcoin.define('Address', './primitives/address');
bcoin.define('Block', './primitives/block');
bcoin.define('Coin', './primitives/coin');
bcoin.define('Headers', './primitives/headers');
bcoin.define('Input', './primitives/input');
bcoin.define('InvItem', './primitives/invitem');
bcoin.define('KeyRing', './primitives/keyring');
bcoin.define('MerkleBlock', './primitives/merkleblock');
bcoin.define('MTX', './primitives/mtx');
bcoin.define('Outpoint', './primitives/outpoint');
bcoin.define('Output', './primitives/output');
bcoin.define('TX', './primitives/tx');
// Protocol
bcoin.define('protocol', './protocol');
bcoin.define('consensus', './protocol/consensus');
bcoin.define('Network', './protocol/network');
bcoin.define('networks', './protocol/networks');
bcoin.define('policy', './protocol/policy');
// Script
bcoin.define('script', './script');
bcoin.define('Opcode', './script/opcode');
bcoin.define('Program', './script/program');
bcoin.define('Script', './script/script');
bcoin.define('ScriptNum', './script/scriptnum');
bcoin.define('SigCache', './script/sigcache');
bcoin.define('Stack', './script/stack');
bcoin.define('Witness', './script/witness');
// Utils
bcoin.define('utils', './utils');
bcoin.define('util', './utils/util');
// Wallet
bcoin.define('wallet', './wallet');
bcoin.define('Path', './wallet/path');
bcoin.define('WalletKey', './wallet/walletkey');
bcoin.define('WalletDB', './wallet/walletdb');
// Workers
bcoin.define('workers', './workers');
bcoin.define('WorkerPool', './workers/workerpool');
// Package Info
bcoin.define('pkg', './pkg');
module.exports = env;

451
lib/bip70/asn1.js Normal file
View File

@ -0,0 +1,451 @@
/*!
* asn1.js - asn1 parsing for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*
* Parts of this software are based on asn1.js.
* https://github.com/indutny/asn1.js
*
* Copyright Fedor Indutny, 2013.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
'use strict';
var assert = require('assert');
var BufferReader = require('../utils/reader');
var asn1 = exports;
asn1.parseTag = function parseTag(p) {
var tag = p.readU8();
var primitive = (tag & 0x20) === 0;
var oct;
if ((tag & 0x1f) === 0x1f) {
oct = tag;
tag = 0;
while ((oct & 0x80) === 0x80) {
oct = p.readU8();
tag <<= 7;
tag |= oct & 0x7f;
}
} else {
tag &= 0x1f;
}
return {
primitive: primitive,
tag: tag,
len: asn1.parseLen(p, primitive)
};
};
asn1.parseLen = function parseLen(p, primitive) {
var len = p.readU8();
var num, i, j;
// Indefinite form
if (!primitive && len === 0x80)
return null;
// Definite form
if ((len & 0x80) === 0) {
// Short form
return len;
}
// Long form
num = len & 0x7f;
assert(num < 4, 'length octect is too long');
len = 0;
for (i = 0; i < num; i++) {
len <<= 8;
j = p.readU8();
len |= j;
}
return len;
};
asn1.parseCert = function parseCert(data) {
var d = BufferReader(data);
var p;
d.start();
p = BufferReader(asn1.parseSeq(d));
return {
tbs: asn1.parseTBS(p),
sigAlg: asn1.parseAlgIdent(p),
sig: asn1.parseBitstr(p),
raw: d.endData(true)
};
};
asn1.parseTBS = function parseTBS(data) {
var d = BufferReader(data);
var p;
d.start();
p = BufferReader(asn1.parseSeq(d));
return {
version: asn1.parseExplicitInt(p, 0, true),
serial: asn1.parseInt(p),
sig: asn1.parseAlgIdent(p),
issuer: asn1.parseName(p),
validity: asn1.parseValidity(p),
subject: asn1.parseName(p),
pubkey: asn1.parsePubkey(p),
raw: d.endData(true)
};
};
asn1.parseSeq = function parseSeq(data) {
var p = BufferReader(data);
var tag = asn1.parseTag(p);
assert.equal(tag.tag, 0x10); // seq
return p.readBytes(tag.len, true);
};
asn1.parseInt = function parseInt(data, readNum) {
var p = BufferReader(data);
var tag = asn1.parseTag(p);
var num;
assert.equal(tag.tag, 0x02); // int
num = p.readBytes(tag.len, true);
if (readNum)
return num.readUIntBE(0, num.length);
return num;
};
asn1.parseExplicitInt = function parseExplicitInt(data, i, readNum) {
var p = BufferReader(data);
var off = p.offset;
var tag = asn1.parseTag(p);
if (tag.tag !== i) {
p.seek(-(p.offset - off));
return -1;
}
return asn1.parseInt(p, readNum);
};
asn1.parseBitstr = function parseBitstr(data) {
var p = BufferReader(data);
var tag = asn1.parseTag(p);
assert.equal(tag.tag, 0x03); // bitstr
return asn1.alignBitstr(p.readBytes(tag.len, true));
};
asn1.parseString = function parseString(data) {
var p = BufferReader(data);
var tag = asn1.parseTag(p);
switch (tag.tag) {
case 0x03: // bitstr
return asn1.alignBitstr(p.readBytes(tag.len, true));
case 0x04: // octstr
case 0x12: // numstr
case 0x13: // prinstr
case 0x14: // t61str
case 0x15: // videostr
case 0x16: // ia5str
case 0x19: // graphstr
case 0x0c: // utf8str
case 0x1a: // iso646str
case 0x1b: // genstr
case 0x1c: // unistr
case 0x1d: // charstr
case 0x1e: // bmpstr
return p.readString('utf8', tag.len);
default:
assert(false, 'Bad string.');
}
};
asn1.alignBitstr = function(data) {
var padding = data[0];
var bits = (data.length - 1) * 8 - padding;
var buf = data.slice(1);
var shift = 8 - (bits % 8);
var i, out;
if (shift === 8 || buf.length === 0)
return buf;
out = new Buffer(buf.length);
out[0] = buf[0] >>> shift;
for (i = 1; i < buf.length; i++) {
out[i] = buf[i - 1] << (8 - shift);
out[i] |= buf[i] >>> shift;
}
return out;
};
asn1.parsePubkey = function parsePubkey(data) {
var p = BufferReader(data);
p = BufferReader(asn1.parseSeq(p));
return {
alg: asn1.parseAlgIdent(p),
pubkey: asn1.parseBitstr(p)
};
};
asn1.parseName = function parseName(data) {
var p = BufferReader(data);
var values = [];
var tag;
p = BufferReader(asn1.parseSeq(p));
while (p.left()) {
tag = asn1.parseTag(p);
assert.equal(tag.tag, 0x11); // set
tag = asn1.parseTag(p);
assert.equal(tag.tag, 0x10); // seq
values.push({
type: asn1.parseOID(p),
value: asn1.parseString(p)
});
}
return values;
};
asn1.parseValidity = function parseValidity(data) {
var p = BufferReader(data);
p = BufferReader(asn1.parseSeq(p));
return {
notBefore: asn1.parseTime(p),
notAfter: asn1.parseTime(p)
};
};
asn1.parseTime = function parseTime(data) {
var p = BufferReader(data);
var tag = asn1.parseTag(p);
var str = p.readString('ascii', tag.len);
var year, mon, day, hour, min, sec;
switch (tag.tag) {
case 0x17: // utctime
year = str.slice(0, 2) | 0;
mon = str.slice(2, 4) | 0;
day = str.slice(4, 6) | 0;
hour = str.slice(6, 8) | 0;
min = str.slice(8, 10) | 0;
sec = str.slice(10, 12) | 0;
if (year < 70)
year = 2000 + year;
else
year = 1900 + year;
break;
case 0x18: // gentime
year = str.slice(0, 4) | 0;
mon = str.slice(4, 6) | 0;
day = str.slice(6, 8) | 0;
hour = str.slice(8, 10) | 0;
min = str.slice(10, 12) | 0;
sec = str.slice(12, 14) | 0;
break;
default:
assert(false);
break;
}
return Date.UTC(year, mon - 1, day, hour, min, sec, 0) / 1000;
};
asn1.parseOID = function parseOID(data) {
var p = BufferReader(data);
var tag = asn1.parseTag(p);
var ids = [];
var ident = 0;
var subident = 0;
var objid, result, first, second;
assert.equal(tag.tag, 0x06); // objid
objid = p.readBytes(tag.len, true);
p = BufferReader(objid);
while (p.left()) {
subident = p.readU8();
ident <<= 7;
ident |= subident & 0x7f;
if ((subident & 0x80) === 0) {
ids.push(ident);
ident = 0;
}
}
if (subident & 0x80)
ids.push(ident);
first = (ids[0] / 40) | 0;
second = ids[0] % 40;
result = [first, second].concat(ids.slice(1));
return result.join('.');
};
asn1.parseAlgIdent = function parseAlgIdent(data) {
var p = BufferReader(data);
var params = null;
var alg;
p = BufferReader(asn1.parseSeq(p));
alg = asn1.parseOID(p);
if (p.left() > 0) {
params = p.readBytes(asn1.parseTag(p).len, true);
if (params.length === 0)
params = null;
}
return {
alg: alg,
params: params
};
};
asn1.parseRSAPublic = function parseRSAPublic(data) {
var p = BufferReader(data);
p = BufferReader(asn1.parseSeq(p));
return {
modulus: asn1.parseInt(p),
publicExponent: asn1.parseInt(p)
};
};
asn1.parseRSAPrivate = function parseRSAPrivate(data) {
var p = BufferReader(data);
p = BufferReader(asn1.parseSeq(p));
return {
version: asn1.parseInt(p, true),
modulus: asn1.parseInt(p),
publicExponent: asn1.parseInt(p),
privateExponent: asn1.parseInt(p),
prime1: asn1.parseInt(p),
prime2: asn1.parseInt(p),
exponent1: asn1.parseInt(p),
exponent2: asn1.parseInt(p),
coefficient: asn1.parseInt(p)
};
};
asn1.parsePEM = function parsePEM(pem) {
var buf = '';
var chunks = [];
var s, tag, type;
while (pem.length) {
if (s = /^-----BEGIN ([^\-]+)-----/.exec(pem)) {
pem = pem.substring(s[0].length);
tag = s[1];
continue;
}
if (s = /^-----END ([^\-]+)-----/.exec(pem)) {
pem = pem.substring(s[0].length);
assert(tag === s[1], 'Tag mismatch.');
buf = new Buffer(buf, 'base64');
type = tag.split(' ')[0].toLowerCase();
chunks.push({ tag: tag, type: type, data: buf });
buf = '';
tag = null;
continue;
}
if (s = /^[a-zA-Z0-9\+=\/]+/.exec(pem)) {
pem = pem.substring(s[0].length);
buf += s[0];
continue;
}
if (s = /^\s+/.exec(pem)) {
pem = pem.substring(s[0].length);
continue;
}
throw new Error('PEM parse error.');
}
assert(chunks.length !== 0, 'PEM parse error.');
assert(!tag, 'Un-ended tag.');
assert(buf.length === 0, 'Trailing data.');
return chunks;
};
asn1.fromPEM = function fromPEM(pem) {
var chunks = asn1.parsePEM(pem);
var body = chunks[0];
var extra = chunks[1];
var params, alg;
if (extra) {
if (extra.tag.indexOf('PARAMETERS') !== -1)
params = extra.data;
}
switch (body.type) {
case 'dsa':
alg = 'dsa';
break;
case 'rsa':
alg = 'rsa';
break;
case 'ec':
alg = 'ecdsa';
break;
}
return {
type: body.type,
alg: alg,
data: body.data,
params: params
};
};
asn1.toPEM = function toPEM(der, type, suffix) {
var pem = '';
var i;
if (suffix)
type += ' ' + suffix;
type = type.toUpperCase();
der = der.toString('base64');
for (i = 0; i < der.length; i += 64)
pem += der.slice(i, i + 64) + '\r\n';
return ''
+ '-----BEGIN ' + type + '-----\r\n'
+ pem
+ '-----END ' + type + '-----\r\n';
};

15
lib/bip70/index.js Normal file
View File

@ -0,0 +1,15 @@
/*!
* bip70.js - bip70 for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
exports.PaymentRequest = require('./paymentrequest');
exports.PaymentDetails = require('./paymentdetails');
exports.Payment = require('./payment');
exports.PaymentACK = require('./paymentack');
exports.asn1 = require('./asn1');
exports.x509 = require('./x509');
exports.pk = require('./pk');

127
lib/bip70/payment.js Normal file
View File

@ -0,0 +1,127 @@
/*!
* payment.js - bip70 payment for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var assert = require('assert');
var Output = require('../primitives/output');
var TX = require('../primitives/tx');
var Script = require('../script/script');
var protobuf = require('./protobuf');
var PaymentDetails = require('./paymentdetails');
var ProtoReader = protobuf.ProtoReader;
var ProtoWriter = protobuf.ProtoWriter;
function Payment(options) {
if (!(this instanceof Payment))
return new Payment(options);
this.merchantData = null;
this.transactions = [];
this.refundTo = [];
this.memo = null;
if (options)
this.fromOptions(options);
}
Payment.prototype.fromOptions = function fromOptions(options) {
var i, tx, output;
if (options.merchantData)
this.setData(options.merchantData);
if (options.transactions) {
assert(Array.isArray(options.transactions));
for (i = 0; i < options.transactions.length; i++) {
tx = new TX(options.transactions[i]);
this.transactions.push(tx);
}
}
if (options.refundTo) {
assert(Array.isArray(options.refundTo));
for (i = 0; i < options.refundTo.length; i++) {
output = new Output(options.refundTo[i]);
this.refundTo.push(output);
}
}
if (options.memo != null) {
assert(typeof options.memo === 'string');
this.memo = options.memo;
}
return this;
};
Payment.fromOptions = function fromOptions(options) {
return new Payment().fromOptions(options);
};
Payment.prototype.setData = PaymentDetails.prototype.setData;
Payment.prototype.getData = PaymentDetails.prototype.getData;
Payment.prototype.fromRaw = function fromRaw(data) {
var p = new ProtoReader(data);
var tx, op, output;
this.merchantData = p.readFieldBytes(1, true);
while (p.nextTag() === 2) {
tx = TX.fromRaw(p.readFieldBytes(2));
this.transactions.push(tx);
}
while (p.nextTag() === 3) {
op = new ProtoReader(p.readFieldBytes(3));
output = new Output();
output.value = op.readFieldU64(1, true);
output.script = Script.fromRaw(op.readFieldBytes(2, true));
this.refundTo.push(output);
}
this.memo = p.readFieldString(4, true);
return this;
};
Payment.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = new Buffer(data, enc);
return new Payment().fromRaw(data);
};
Payment.prototype.toRaw = function toRaw(writer) {
var p = new ProtoWriter(writer);
var i, tx, op, output;
if (this.merchantData)
p.writeFieldBytes(1, this.merchantData);
for (i = 0; i < this.transactions.length; i++) {
tx = this.transactions[i];
this.writeFieldBytes(2, tx.toRaw());
}
for (i = 0; i < this.refundTo.length; i++) {
op = new ProtoWriter();
output = this.refundTo[i];
op.writeFieldU64(1, output.value);
op.writeFieldBytes(2, output.script.toRaw());
p.writeFieldBytes(3, op.render());
}
if (this.memo != null)
p.writeFieldString(4, this.memo);
if (!writer)
p = p.render();
return p;
};
module.exports = Payment;

71
lib/bip70/paymentack.js Normal file
View File

@ -0,0 +1,71 @@
/*!
* paymentack.js - bip70 paymentack for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var assert = require('assert');
var protobuf = require('./protobuf');
var Payment = require('./payment');
var ProtoReader = protobuf.ProtoReader;
var ProtoWriter = protobuf.ProtoWriter;
function PaymentACK(options) {
if (!(this instanceof PaymentACK))
return new PaymentACK(options);
this.payment = new Payment();
this.memo = null;
if (options)
this.fromOptions(options);
}
PaymentACK.prototype.fromOptions = function fromOptions(options) {
if (options.payment)
this.payment.fromOptions(options.payment);
if (options.memo != null) {
assert(typeof options.memo === 'string');
this.memo = options.memo;
}
return this;
};
PaymentACK.fromOptions = function fromOptions(options) {
return new PaymentACK().fromOptions(options);
};
PaymentACK.prototype.fromRaw = function fromRaw(data) {
var p = new ProtoReader(data);
this.payment.fromRaw(p.readFieldBytes(1));
this.memo = p.readFieldString(2, true);
return this;
};
PaymentACK.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = new Buffer(data, enc);
return new PaymentACK().fromRaw(data);
};
PaymentACK.prototype.toRaw = function toRaw(writer) {
var p = new ProtoWriter(writer);
p.writeFieldBytes(1, this.payment.toRaw());
if (this.memo != null)
p.writeFieldString(2, this.memo);
if (!writer)
p = p.render();
return p;
};
module.exports = PaymentACK;

185
lib/bip70/paymentdetails.js Normal file
View File

@ -0,0 +1,185 @@
/*!
* paymentdetails.js - bip70 paymentdetails for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var assert = require('assert');
var utils = require('../utils/utils');
var Output = require('../primitives/output');
var protobuf = require('./protobuf');
var ProtoReader = protobuf.ProtoReader;
var ProtoWriter = protobuf.ProtoWriter;
function PaymentDetails(options) {
if (!(this instanceof PaymentDetails))
return new PaymentDetails(options);
this.network = null;
this.outputs = [];
this.time = utils.now();
this.expires = -1;
this.memo = null;
this.paymentUrl = null;
this.merchantData = null;
if (options)
this.fromOptions(options);
}
PaymentDetails.prototype.fromOptions = function fromOptions(options) {
var i, output;
if (options.network != null) {
assert(typeof options.network === 'string');
this.network = options.network;
}
if (options.outputs) {
assert(Array.isArray(options.outputs));
for (i = 0; i < options.outputs.length; i++) {
output = new Output(options.outputs[i]);
this.outputs.push(output);
}
}
if (options.time != null) {
assert(utils.isNumber(options.time));
this.time = options.time;
}
if (options.expires != null) {
assert(utils.isNumber(options.expires));
this.expires = options.expires;
}
if (options.memo != null) {
assert(typeof options.memo === 'string');
this.memo = options.memo;
}
if (options.paymentUrl != null) {
assert(typeof options.paymentUrl === 'string');
this.paymentUrl = options.paymentUrl;
}
if (options.merchantData)
this.setData(options.merchantData);
return this;
};
PaymentDetails.fromOptions = function fromOptions(options) {
return new PaymentDetails().fromOptions(options);
};
PaymentDetails.prototype.isExpired = function isExpired() {
if (this.expires === -1)
return false;
return utils.now() > this.expires;
};
PaymentDetails.prototype.setData = function setData(data, enc) {
if (data == null || Buffer.isBuffer(data)) {
this.merchantData = data;
return;
}
if (typeof data !== 'string') {
assert(!enc || enc === 'json');
this.merchantData = new Buffer(JSON.stringify(data), 'utf8');
return;
}
this.merchantData = new Buffer(data, enc);
};
PaymentDetails.prototype.getData = function getData(enc) {
var data = this.merchantData;
if (!data)
return;
if (!enc)
return data;
if (enc === 'json') {
data = data.toString('utf8');
try {
data = JSON.parse(data);
} catch (e) {
return;
}
return data;
}
return data.toString(enc);
};
PaymentDetails.prototype.fromRaw = function fromRaw(data) {
var p = new ProtoReader(data);
var op, output;
this.network = p.readFieldString(1, true);
while (p.nextTag() === 2) {
op = new ProtoReader(p.readFieldBytes(2));
output = new Output();
output.value = op.readFieldU64(1, true);
output.script.fromRaw(op.readFieldBytes(2, true));
this.outputs.push(output);
}
this.time = p.readFieldU64(3);
this.expires = p.readFieldU64(4, true);
this.memo = p.readFieldString(5, true);
this.paymentUrl = p.readFieldString(6, true);
this.merchantData = p.readFieldBytes(7, true);
return this;
};
PaymentDetails.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = new Buffer(data, enc);
return new PaymentDetails().fromRaw(data);
};
PaymentDetails.prototype.toRaw = function toRaw(writer) {
var p = new ProtoWriter(writer);
var i, op, output;
if (this.network != null)
p.writeFieldString(1, this.network);
for (i = 0; i < this.outputs.length; i++) {
output = this.outputs[i];
op = new ProtoWriter();
op.writeFieldU64(1, output.value);
op.writeFieldBytes(2, output.script.toRaw());
p.writeFieldBytes(2, op.render());
}
p.writeFieldU64(3, this.time);
if (this.expires !== -1)
p.writeFieldU64(4, this.expires);
if (this.memo != null)
p.writeFieldString(5, this.memo);
if (this.paymentUrl != null)
p.writeFieldString(6, this.paymentUrl);
if (this.merchantData)
p.writeFieldString(7, this.merchantData);
if (!writer)
p = p.render();
return p;
};
module.exports = PaymentDetails;

252
lib/bip70/paymentrequest.js Normal file
View File

@ -0,0 +1,252 @@
/*!
* paymentrequest.js - bip70 paymentrequest for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var assert = require('assert');
var utils = require('../utils/utils');
var crypto = require('../crypto/crypto');
var x509 = require('./x509');
var asn1 = require('./asn1');
var protobuf = require('./protobuf');
var PaymentDetails = require('./paymentdetails');
var ProtoReader = protobuf.ProtoReader;
var ProtoWriter = protobuf.ProtoWriter;
function PaymentRequest(options) {
if (!(this instanceof PaymentRequest))
return new PaymentRequest(options);
this.version = -1;
this.pkiType = null;
this.pkiData = null;
this.paymentDetails = new PaymentDetails();
this.signature = null;
if (options)
this.fromOptions(options);
}
PaymentRequest.prototype.fromOptions = function fromOptions(options) {
if (options.version != null) {
assert(utils.isNumber(options.version));
this.version = options.version;
}
if (options.pkiType != null) {
assert(typeof options.pkiType === 'string');
this.pkiType = options.pkiType;
}
if (options.pkiData) {
assert(Buffer.isBuffer(options.pkiData));
this.pkiData = options.pkiData;
}
if (options.paymentDetails)
this.paymentDetails.fromOptions(options.paymentDetails);
if (options.signature) {
assert(Buffer.isBuffer(options.signature));
this.signature = options.signature;
}
if (options.chain)
this.setChain(options.chain);
return this;
};
PaymentRequest.fromOptions = function fromOptions(options) {
return new PaymentRequest().fromOptions(options);
};
PaymentRequest.prototype.fromRaw = function fromRaw(data) {
var p = new ProtoReader(data);
this.version = p.readFieldU32(1, true);
this.pkiType = p.readFieldString(2, true);
this.pkiData = p.readFieldBytes(3, true);
this.paymentDetails.fromRaw(p.readFieldBytes(4));
this.signature = p.readFieldBytes(5, true);
return this;
};
PaymentRequest.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = new Buffer(data, enc);
return new PaymentRequest().fromRaw(data);
};
PaymentRequest.prototype.toRaw = function toRaw(writer) {
var p = new ProtoWriter(writer);
if (this.version !== -1)
p.writeFieldU32(1, this.version);
if (this.pkiType != null)
p.writeFieldString(2, this.pkiType);
if (this.pkiData)
p.writeFieldBytes(3, this.pkiData);
p.writeFieldBytes(4, this.paymentDetails.toRaw());
if (this.signature)
p.writeFieldBytes(5, this.signature);
if (!writer)
p = p.render();
return p;
};
PaymentRequest.prototype.getAlgorithm = function getAlgorithm() {
var parts;
if (!this.pkiType)
return;
parts = this.pkiType.split('+');
if (parts.length !== 2)
return;
if (parts[0] !== 'x509')
return;
if (parts[1] !== 'sha1' && parts[1] !== 'sha256')
return;
return { key: parts[0], hash: parts[1] };
};
PaymentRequest.prototype.signatureData = function signatureData() {
var signature = this.signature;
var data;
this.signature = new Buffer(0);
data = this.toRaw();
this.signature = signature;
return data;
};
PaymentRequest.prototype.signatureHash = function signatureHash() {
var alg = this.getAlgorithm();
assert(alg, 'No hash algorithm available.');
return crypto.hash(alg.hash, this.signatureData());
};
PaymentRequest.prototype.setChain = function setChain(chain) {
var p = new ProtoWriter();
var i, cert, pem;
if (!Array.isArray(chain))
chain = [chain];
for (i = 0; i < chain.length; i++) {
cert = chain[i];
if (typeof cert === 'string') {
pem = asn1.fromPEM(cert);
assert(pem.type === 'certificate', 'Bad certificate PEM.');
cert = pem.data;
}
assert(Buffer.isBuffer(cert), 'Certificates must be PEM or DER.');
p.writeFieldBytes(1, cert);
}
this.pkiData = p.render();
};
PaymentRequest.prototype.getChain = function getChain() {
var chain = [];
var p;
if (!this.pkiData)
return chain;
p = new ProtoReader(this.pkiData);
while (p.nextTag() === 1)
chain.push(p.readFieldBytes(1));
return chain;
};
PaymentRequest.prototype.sign = function sign(key, chain) {
var alg, msg;
if (chain)
this.setChain(chain);
if (!this.pkiType)
this.pkiType = 'x509+sha256';
alg = this.getAlgorithm();
assert(alg, 'No hash algorithm available.');
msg = this.signatureData();
chain = this.getChain();
this.signature = x509.signSubject(alg.hash, msg, key, chain);
};
PaymentRequest.prototype.verify = function verify() {
var alg, msg, sig, chain;
if (!this.pkiType || this.pkiType === 'none')
return true;
if (!this.signature)
return false;
alg = this.getAlgorithm();
if (!alg)
return false;
msg = this.signatureData();
sig = this.signature;
chain = this.getChain();
return x509.verifySubject(alg.hash, msg, sig, chain);
};
PaymentRequest.prototype.verifyChain = function verifyChain() {
if (!this.pkiType || this.pkiType === 'none')
return true;
return x509.verifyChain(this.getChain());
};
PaymentRequest.prototype.getCA = function getCA() {
var chain, root;
if (!this.pkiType || this.pkiType === 'none')
return;
chain = this.getChain();
if (chain.length === 0)
return;
root = x509.parse(chain[chain.length - 1]);
if (!root)
return;
return {
name: x509.getCAName(root),
trusted: x509.isTrusted(root),
cert: root
};
};
module.exports = PaymentRequest;

253
lib/bip70/pk.js Normal file
View File

@ -0,0 +1,253 @@
/*!
* x509.js - x509 handling for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var BN = require('bn.js');
var asn1 = require('./asn1');
var elliptic = require('elliptic');
var crypto = require('../crypto/crypto');
var nativeCrypto;
try {
nativeCrypto = require('crypto');
} catch (e) {
;
}
var pk = exports;
var rsa = {};
var ecdsa = {};
var native = {};
rsa.prefixes = {
md5: new Buffer('3020300c06082a864886f70d020505000410', 'hex'),
sha1: new Buffer('3021300906052b0e03021a05000414', 'hex'),
sha224: new Buffer('302d300d06096086480165030402040500041c', 'hex'),
sha256: new Buffer('3031300d060960864801650304020105000420', 'hex'),
sha384: new Buffer('3041300d060960864801650304020205000430', 'hex'),
sha512: new Buffer('3051300d060960864801650304020305000440', 'hex'),
md5sha1: new Buffer(0),
ripemd160: new Buffer('30203008060628cf060300310414', 'hex')
};
// Ported from:
// https://github.com/golang/go/blob/master/src/crypto/rsa/pkcs1v15.go
rsa.verify = function verify(hashAlg, msg, sig, key) {
var hash = crypto.hash(hashAlg, msg);
var prefix = rsa.prefixes[hashAlg];
var len = prefix.length + hash.length;
var pub = asn1.parseRSAPublic(key);
var N = new BN(pub.modulus);
var e = new BN(pub.publicExponent);
var k = Math.ceil(N.bitLength() / 8);
var m, em, ok, i;
if (k < len + 11)
throw new Error('Message too long.');
m = rsa.encrypt(N, e, sig);
em = leftpad(m, k);
ok = crypto.ceq(em[0], 0x00);
ok &= crypto.ceq(em[1], 0x01);
ok &= crypto.ccmp(em.slice(k - hash.length, k), hash);
ok &= crypto.ccmp(em.slice(k - len, k - hash.length), prefix);
ok &= crypto.ceq(em[k - len - 1], 0x00);
for (i = 2; i < k - len - 1; i++)
ok &= crypto.ceq(em[i], 0xff);
return ok === 1;
};
rsa.sign = function sign(hashAlg, msg, key) {
var hash = crypto.hash(hashAlg, msg);
var prefix = rsa.prefixes[hashAlg];
var len = prefix.length + hash.length;
var priv = asn1.parseRSAPrivate(key);
var N = new BN(priv.modulus);
var D = new BN(priv.privateExponent);
var k = Math.ceil(N.bitLength() / 8);
var i, em;
if (k < len + 11)
throw new Error('Message too long.');
em = new Buffer(k);
em.fill(0);
em[1] = 0x01;
for (i = 2; i < k - len - 1; i++)
em[i] = 0xff;
prefix.copy(em, k - len);
hash.copy(em, k - hash.length);
return rsa.decrypt(N, D, em);
};
rsa.decrypt = function decrypt(N, D, m) {
var c = new BN(m);
if (c.cmp(N) > 0)
throw new Error('Cannot decrypt.');
return c
.toRed(BN.red(N))
.redPow(D)
.fromRed()
.toArrayLike(Buffer, 'be');
};
rsa.encrypt = function encrypt(N, e, m) {
return new BN(m)
.toRed(BN.red(N))
.redPow(e)
.fromRed()
.toArrayLike(Buffer, 'be');
};
ecdsa.verify = function verify(curve, msg, hashAlg, key, sig) {
var hash = crypto.hash(hashAlg, msg);
var ec = elliptic.ec(curve);
return ec.verify(hash, sig, key);
};
ecdsa.sign = function sign(curve, msg, hashAlg, key) {
var hash = crypto.hash(hashAlg, msg);
var ec = elliptic.ec(curve);
return new Buffer(ec.sign(hash, key));
};
native.verify = function verify(alg, hash, msg, sig, key) {
var algo, verify;
if (!nativeCrypto)
return false;
algo = normalizeAlg(alg, hash);
verify = nativeCrypto.createVerify(algo);
verify.update(msg);
return verify.verify(key, sig);
};
native.sign = function _sign(alg, hash, msg, key) {
var algo, sig;
if (!nativeCrypto)
return false;
algo = normalizeAlg(alg, hash);
sig = nativeCrypto.createSign(algo);
sig.update(msg);
return sig.sign(key);
};
pk.pemTag = {
dsa: 'DSA',
rsa: 'RSA',
ecdsa: 'EC'
};
pk.toPEM = function toPEM(key, type) {
var tag = pk.pemTag[key.alg];
var pem = asn1.toPEM(key.data, tag, type);
// Key parameters, usually present
// if selecting an EC curve.
if (key.params)
pem += asn1.toPEM(key.params, tag, 'parameters');
return pem;
};
pk._verify = function verify(hash, msg, sig, key) {
var pem;
switch (key.alg) {
case 'dsa':
pem = pk.toPEM(key, 'public key');
return native.verify(key.alg, hash, msg, sig, pem);
case 'rsa':
if (nativeCrypto) {
pem = pk.toPEM(key, 'public key');
return native.verify(key.alg, hash, msg, sig, pem);
}
return rsa.verify(hash, msg, sig, key.data);
case 'ecdsa':
if (!key.curve)
throw new Error('No curve present.');
return ecdsa.verify(key.curve, hash, msg, sig, key.data);
default:
throw new Error('Unsupported algorithm.');
}
};
pk.verify = function verify(hash, msg, sig, key) {
try {
return pk._verify(hash, msg, sig, key);
} catch (e) {
return false;
}
};
pk.sign = function sign(hash, msg, key) {
var pem;
switch (key.alg) {
case 'dsa':
pem = pk.toPEM(key, 'private key');
return native.sign(key.alg, hash, msg, pem);
case 'rsa':
if (nativeCrypto) {
pem = pk.toPEM(key, 'private key');
return native.sign(key.alg, hash, msg, pem);
}
return rsa.sign(hash, msg, key.data);
case 'ecdsa':
if (!key.curve)
throw new Error('No curve present.');
return ecdsa.sign(key.curve, hash, msg, key.data);
default:
throw new Error('Unsupported algorithm.');
}
};
function leftpad(input, size) {
var n = input.length;
var out;
if (n > size)
n = size;
out = new Buffer(size);
out.fill(0);
input.copy(out, out.length - n);
return out;
}
function normalizeAlg(alg, hash) {
var name = alg.toUpperCase() + '-' + hash.toUpperCase();
switch (name) {
case 'ECDSA-SHA1':
name = 'ecdsa-with-SHA1';
break;
case 'ECDSA-SHA256':
name = 'ecdsa-with-SHA256';
break;
}
return name;
}
pk.rsa = rsa;
pk.ecdsa = ecdsa;
pk.native = native;

260
lib/bip70/protobuf.js Normal file
View File

@ -0,0 +1,260 @@
/*!
* protobuf.js - protobufs for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var utils = require('../utils/utils');
var assert = require('assert');
var BufferReader = require('../utils/reader');
var BufferWriter = require('../utils/writer');
var wireType = {
VARINT: 0,
FIXED64: 1,
DELIMITED: 2,
START_GROUP: 3,
END_GROUP: 4,
FIXED32: 5
};
function ProtoReader(data, zeroCopy) {
if (data instanceof ProtoReader)
return data;
if (!(this instanceof ProtoReader))
return new ProtoReader(data, zeroCopy);
BufferReader.call(this, data, zeroCopy);
}
utils.inherits(ProtoReader, BufferReader);
ProtoReader.prototype.readVarint = function readVarint() {
var result = exports.readVarint(this.data, this.offset);
this.offset += result.size;
return result.value;
};
ProtoReader.prototype.readFieldValue = function readFieldValue(tag, opt) {
var field = this.readField(tag, opt);
if (!field)
return -1;
assert(field.value != null);
return field.value;
};
ProtoReader.prototype.readFieldU64 = function readFieldU64(tag, opt) {
var field = this.readField(tag, opt);
if (!field)
return -1;
assert(field.type === wireType.VARINT || field.type === wireType.FIXED64);
return field.value;
};
ProtoReader.prototype.readFieldU32 = function readFieldU32(tag, opt) {
var field = this.readField(tag, opt);
if (!field)
return -1;
assert(field.type === wireType.VARINT || field.type === wireType.FIXED32);
return field.value;
};
ProtoReader.prototype.readFieldBytes = function readFieldBytes(tag, opt) {
var field = this.readField(tag, opt);
if (!field)
return null;
assert(field.data);
return field.data;
};
ProtoReader.prototype.readFieldString = function readFieldString(tag, opt, enc) {
var field = this.readField(tag, opt);
if (!field)
return null;
assert(field.data);
return field.data.toString(enc || 'utf8');
};
ProtoReader.prototype.nextTag = function nextTag() {
var field;
if (this.left() === 0)
return -1;
field = this.readField();
this.seek(-field.size);
return field.tag;
};
ProtoReader.prototype.readField = function readField(tag, opt) {
var offset = this.offset;
var header = this.readVarint();
var value, data, group, field;
if (tag != null && (header >>> 3) !== tag) {
assert(opt, 'Non-optional field not present.');
this.offset = offset;
return;
}
switch (header & 7) {
case wireType.VARINT:
value = this.readVarint();
break;
case wireType.FIXED64:
value = this.readU64N();
break;
case wireType.DELIMITED:
data = this.readVarBytes();
break;
case wireType.START_GROUP:
group = [];
for (;;) {
field = this.readField();
if (field.type === wireType.END_GROUP)
break;
group.push(field);
}
break;
case wireType.END_GROUP:
assert(false, 'Unexpected end group.');
break;
case wireType.FIXED32:
value = this.readU32();
break;
default:
assert(false, 'Bad wire type.');
break;
}
return {
size: this.offset - offset,
header: header,
tag: header >>> 3,
type: header & 7,
value: value,
data: data,
group: group
};
};
function ProtoWriter(options) {
if (options instanceof ProtoWriter)
return options;
if (!(this instanceof ProtoWriter))
return new ProtoWriter(options);
BufferWriter.call(this, options);
}
utils.inherits(ProtoWriter, BufferWriter);
ProtoWriter.prototype.writeVarint = function writeVarint(num) {
var size = exports.sizeVarint(num);
var buf = new Buffer(size);
exports.writeVarint(buf, num, 0);
this.writeBytes(buf);
};
ProtoWriter.prototype.writeFieldVarint = function writeFieldVarint(tag, value) {
var header = (tag << 3) | wireType.VARINT;
this.writeVarint(header);
this.writeVarint(value);
};
ProtoWriter.prototype.writeFieldU64 = function writeFieldU64(tag, value) {
assert(utils.isSafeInteger(value));
this.writeFieldVarint(tag, value);
};
ProtoWriter.prototype.writeFieldU32 = function writeFieldU32(tag, value) {
assert(value <= 0xffffffff);
this.writeFieldVarint(tag, value);
};
ProtoWriter.prototype.writeFieldBytes = function writeFieldBytes(tag, data) {
var header = (tag << 3) | wireType.DELIMITED;
this.writeVarint(header);
this.writeVarint(data.length);
this.writeBytes(data);
};
ProtoWriter.prototype.writeFieldString = function writeFieldString(tag, data, enc) {
if (typeof data === 'string')
data = new Buffer(data, enc || 'utf8');
this.writeFieldBytes(tag, data);
};
exports.readVarint = function readVarint(data, off) {
var num = 0;
var ch = 0x80;
var size = 0;
while (ch & 0x80) {
if (off >= data.length) {
num = 0;
break;
}
ch = data[off++];
// Optimization for javascript insanity.
switch (size) {
case 0:
case 1:
case 2:
case 3:
num += (ch & 0x7f) << (7 * size);
break;
case 4:
num += (ch & 0x7f) * (1 << (7 * size));
break;
default:
num += (ch & 0x7f) * Math.pow(2, 7 * size);
break;
}
size++;
}
assert(utils.isSafeInteger(num), 'Number exceeds 2^53-1.');
return { size: size, value: num };
};
exports.writeVarint = function writeVarint(data, num, off) {
var ch;
assert(utils.isSafeInteger(num), 'Number exceeds 2^53-1.');
do {
assert(off < data.length);
ch = num & 0x7f;
num -= num % 0x80;
num /= 0x80;
if (num !== 0)
ch |= 0x80;
data[off] = ch;
off++;
} while (num > 0);
return off;
};
exports.sizeVarint = function sizeVarint(num) {
var size = 0;
assert(utils.isSafeInteger(num), 'Number exceeds 2^53-1.');
do {
num -= num % 0x80;
num /= 0x80;
size++;
} while (num > 0);
return size;
};
exports.ProtoReader = ProtoReader;
exports.ProtoWriter = ProtoWriter;

306
lib/bip70/x509.js Normal file
View File

@ -0,0 +1,306 @@
/*!
* x509.js - x509 handling for bcoin
* Copyright (c) 2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var assert = require('assert');
var asn1 = require('./asn1');
var utils = require('../utils/utils');
var crypto = require('../crypto/crypto');
var pk = require('./pk');
var x509 = exports;
x509.getSubjectOID = function getSubjectOID(cert, oid) {
var subject = cert.tbs.subject;
var i, entry;
for (i = 0; i < subject.length; i++) {
entry = subject[i];
if (entry.type === oid)
return entry.value;
}
};
x509.getCAName = function getCAName(cert) {
// This seems to work the best in practice
// for getting a human-readable and
// descriptive name for the CA.
// See:
// http://oid-info.com/get/2.5.4
// Precedence:
// (3) commonName
// (11) organizationUnitName
// (10) organizationName
return x509.getSubjectOID(cert, '2.5.4.3')
|| x509.getSubjectOID(cert, '2.5.4.11')
|| x509.getSubjectOID(cert, '2.5.4.10')
|| 'Unknown';
};
x509.trusted = {};
x509.allowUntrusted = false;
x509.isTrusted = function isTrusted(cert) {
var fingerprint = crypto.sha256(cert.raw);
var hash = fingerprint.toString('hex');
return x509.trusted[hash] === true;
};
x509.setTrust = function setTrust(certs) {
var i, cert, pem, hash;
if (!Array.isArray(certs))
certs = [certs];
for (i = 0; i < certs.length; i++) {
cert = certs[i];
if (isHash(cert)) {
if (!Buffer.isBuffer(cert))
cert = new Buffer(cert, 'hex');
hash = cert.toString('hex');
x509.trusted[hash] = true;
continue;
}
if (typeof cert === 'string') {
pem = asn1.fromPEM(cert);
assert(pem.type === 'certificate', 'Must add certificates to trust.');
cert = pem.data;
}
assert(Buffer.isBuffer(cert), 'Certificates must be PEM or DER.');
cert = x509.parse(cert);
assert(cert, 'Could not parse certificate.');
hash = crypto.sha256(cert.raw).toString('hex');
x509.trusted[hash] = true;
}
};
/*
* https://www.ietf.org/rfc/rfc2459.txt
* https://tools.ietf.org/html/rfc3279
* http://oid-info.com/get/1.2.840.10040.4
* http://oid-info.com/get/1.2.840.113549.1.1
* http://oid-info.com/get/1.2.840.10045.4.3
*/
x509.oid = {
'1.2.840.10040.4.1' : { key: 'dsa', hash: null },
'1.2.840.10040.4.2' : { key: 'dsa', hash: null },
'1.2.840.10040.4.3' : { key: 'dsa', hash: 'sha1' },
'1.2.840.113549.1.1.1' : { key: 'rsa', hash: null },
'1.2.840.113549.1.1.2' : { key: 'rsa', hash: 'md2' },
'1.2.840.113549.1.1.3' : { key: 'rsa', hash: 'md4' },
'1.2.840.113549.1.1.4' : { key: 'rsa', hash: 'md5' },
'1.2.840.113549.1.1.5' : { key: 'rsa', hash: 'sha1' },
'1.2.840.113549.1.1.11': { key: 'rsa', hash: 'sha256' },
'1.2.840.113549.1.1.12': { key: 'rsa', hash: 'sha384' },
'1.2.840.113549.1.1.13': { key: 'rsa', hash: 'sha512' },
'1.2.840.113549.1.1.14': { key: 'rsa', hash: 'sha224' },
'1.2.840.10045.2.1' : { key: 'ecdsa', hash: null },
'1.2.840.10045.4.1' : { key: 'ecdsa', hash: 'sha1' },
'1.2.840.10045.4.3.1' : { key: 'ecdsa', hash: 'sha224' },
'1.2.840.10045.4.3.2' : { key: 'ecdsa', hash: 'sha256' },
'1.2.840.10045.4.3.3' : { key: 'ecdsa', hash: 'sha384' },
'1.2.840.10045.4.3.4' : { key: 'ecdsa', hash: 'sha512' }
};
x509.curves = {
'1.3.132.0.33': 'p224',
'1.2.840.10045.3.1.7': 'p256',
'1.3.132.0.34': 'p384',
'1.3.132.0.35': 'p521'
};
x509.getKeyAlgorithm = function getKeyAlgorithm(cert) {
var alg = cert.tbs.pubkey.alg.alg;
return x509.oid[alg];
};
x509.getSigAlgorithm = function getSigAlgorithm(cert) {
var alg = cert.sigAlg.alg;
return x509.oid[alg];
};
x509.getCurve = function getCurve(params) {
var oid;
if (!params)
return;
try {
oid = asn1.parseOID(params);
} catch (e) {
return;
}
return x509.curves[oid];
};
x509.parse = function parse(der) {
try {
return asn1.parseCert(der);
} catch (e) {
;
}
};
x509.getPublicKey = function getPublicKey(cert) {
var alg = x509.getKeyAlgorithm(cert);
var key, params, curve;
if (!alg)
return;
key = cert.tbs.pubkey.pubkey;
params = cert.tbs.pubkey.alg.params;
if (alg.key === 'ecdsa')
curve = x509.getCurve(params);
return {
alg: alg.key,
data: key,
params: params,
curve: curve
};
};
x509.verifyTime = function verifyTime(cert) {
var time = cert.tbs.validity;
var now = Math.floor(Date.now() / 1000);
return now > time.notBefore && now < time.notAfter;
};
x509.signSubject = function signSubject(hash, msg, key, chain) {
var cert, pub, curve;
assert(chain.length !== 0, 'No chain available.');
cert = x509.parse(chain[0]);
assert(cert, 'Could not parse certificate.');
if (typeof key === 'string') {
key = asn1.fromPEM(key);
if (key.alg === 'ecdsa')
curve = x509.getCurve(key.params);
key = {
alg: key.alg,
data: key.data,
params: key.params,
curve: curve
};
} else {
pub = x509.getPublicKey(cert);
assert(pub, 'Certificate uses an unknown algorithm.');
key = {
alg: pub.alg,
data: key,
params: pub.params,
curve: pub.curve
};
}
return pk.sign(hash, msg, key);
};
x509.verifySubject = function verifySubject(hash, msg, sig, chain) {
var cert, key;
if (chain.length === 0)
return false;
cert = x509.parse(chain[0]);
if (!cert)
return false;
key = x509.getPublicKey(cert);
if (!key)
return false;
return pk.verify(hash, msg, sig, key);
};
x509.verifyChain = function verifyChain(chain) {
var i, child, parent, alg, key, sig, msg;
chain = chain.slice();
// Parse certificates and
// check validity time.
for (i = 0; i < chain.length; i++) {
child = x509.parse(chain[i]);
if (!child)
return false;
chain[i] = child;
if (!x509.verifyTime(child))
return false;
}
// Verify signatures.
for (i = 1; i < chain.length; i++) {
child = chain[i - 1];
parent = chain[i];
alg = x509.getSigAlgorithm(child);
msg = child.tbs.raw;
sig = child.sig;
key = x509.getPublicKey(parent);
if (!alg || !alg.hash)
return false;
if (!key)
return false;
if (!pk.verify(alg.hash, msg, sig, key))
return false;
}
// If trust hasn't been
// setup, just return.
if (x509.allowUntrusted)
return true;
// Make sure we trust one
// of the certs in the chain.
for (i = 0; i < chain.length; i++) {
child = chain[i];
// If any certificate in the chain
// is trusted, assume we also trust
// the parent.
if (x509.isTrusted(child))
return true;
}
// No trusted certs present.
return false;
};
x509.asn1 = asn1;
function isHash(data) {
if (typeof data === 'string')
return utils.isHex(data) && data.length === 64;
if (Buffer.isBuffer(data))
return data.length === 32;
return false;
}
x509.setTrust(require('../../etc/certs.json'));

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,381 +0,0 @@
/*!
* chainentry.js - chainentry object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('bsert');
const bio = require('bufio');
const BN = require('bcrypto/lib/bn.js');
const consensus = require('../protocol/consensus');
const hash256 = require('bcrypto/lib/hash256');
const util = require('../utils/util');
const Headers = require('../primitives/headers');
const InvItem = require('../primitives/invitem');
const {inspectSymbol} = require('../utils');
/*
* Constants
*/
const ZERO = new BN(0);
/**
* Chain Entry
* Represents an entry in the chain. Unlike
* other bitcoin fullnodes, we store the
* chainwork _with_ the entry in order to
* avoid reading the entire chain index on
* boot and recalculating the chainworks.
* @alias module:blockchain.ChainEntry
* @property {Hash} hash
* @property {Number} version
* @property {Hash} prevBlock
* @property {Hash} merkleRoot
* @property {Number} time
* @property {Number} bits
* @property {Number} nonce
* @property {Number} height
* @property {BN} chainwork
* @property {Hash} rhash
*/
class ChainEntry {
/**
* Create a chain entry.
* @constructor
* @param {Object?} options
*/
constructor(options) {
this.hash = consensus.ZERO_HASH;
this.version = 1;
this.prevBlock = consensus.ZERO_HASH;
this.merkleRoot = consensus.ZERO_HASH;
this.time = 0;
this.bits = 0;
this.nonce = 0;
this.height = 0;
this.chainwork = ZERO;
if (options)
this.fromOptions(options);
}
/**
* Inject properties from options.
* @private
* @param {Object} options
*/
fromOptions(options) {
assert(options, 'Block data is required.');
assert(Buffer.isBuffer(options.hash));
assert((options.version >>> 0) === options.version);
assert(Buffer.isBuffer(options.prevBlock));
assert(Buffer.isBuffer(options.merkleRoot));
assert((options.time >>> 0) === options.time);
assert((options.bits >>> 0) === options.bits);
assert((options.nonce >>> 0) === options.nonce);
assert((options.height >>> 0) === options.height);
assert(!options.chainwork || BN.isBN(options.chainwork));
this.hash = options.hash;
this.version = options.version;
this.prevBlock = options.prevBlock;
this.merkleRoot = options.merkleRoot;
this.time = options.time;
this.bits = options.bits;
this.nonce = options.nonce;
this.height = options.height;
this.chainwork = options.chainwork || ZERO;
return this;
}
/**
* Instantiate chainentry from options.
* @param {Object} options
* @param {ChainEntry} prev - Previous entry.
* @returns {ChainEntry}
*/
static fromOptions(options, prev) {
return new this().fromOptions(options, prev);
}
/**
* Calculate the proof: (1 << 256) / (target + 1)
* @returns {BN} proof
*/
getProof() {
const target = consensus.fromCompact(this.bits);
if (target.isNeg() || target.isZero())
return new BN(0);
return ChainEntry.MAX_CHAINWORK.div(target.iaddn(1));
}
/**
* Calculate the chainwork by
* adding proof to previous chainwork.
* @returns {BN} chainwork
*/
getChainwork(prev) {
const proof = this.getProof();
if (!prev)
return proof;
return proof.iadd(prev.chainwork);
}
/**
* Test against the genesis block.
* @returns {Boolean}
*/
isGenesis() {
return this.height === 0;
}
/**
* Test whether the entry contains an unknown version bit.
* @param {Network} network
* @returns {Boolean}
*/
hasUnknown(network) {
const TOP_MASK = consensus.VERSION_TOP_MASK;
const TOP_BITS = consensus.VERSION_TOP_BITS;
const bits = (this.version & TOP_MASK) >>> 0;
if (bits !== TOP_BITS)
return false;
return (this.version & network.unknownBits) !== 0;
}
/**
* Test whether the entry contains a version bit.
* @param {Number} bit
* @returns {Boolean}
*/
hasBit(bit) {
return consensus.hasBit(this.version, bit);
}
/**
* Get little-endian block hash.
* @returns {Hash}
*/
rhash() {
return util.revHex(this.hash);
}
/**
* Inject properties from block.
* @private
* @param {Block|MerkleBlock} block
* @param {ChainEntry} prev - Previous entry.
*/
fromBlock(block, prev) {
this.hash = block.hash();
this.version = block.version;
this.prevBlock = block.prevBlock;
this.merkleRoot = block.merkleRoot;
this.time = block.time;
this.bits = block.bits;
this.nonce = block.nonce;
this.height = prev ? prev.height + 1: 0;
this.chainwork = this.getChainwork(prev);
return this;
}
/**
* Instantiate chainentry from block.
* @param {Block|MerkleBlock} block
* @param {ChainEntry} prev - Previous entry.
* @returns {ChainEntry}
*/
static fromBlock(block, prev) {
return new this().fromBlock(block, prev);
}
/**
* Serialize the entry to internal database format.
* @returns {Buffer}
*/
toRaw() {
const bw = bio.write(116);
bw.writeU32(this.version);
bw.writeHash(this.prevBlock);
bw.writeHash(this.merkleRoot);
bw.writeU32(this.time);
bw.writeU32(this.bits);
bw.writeU32(this.nonce);
bw.writeU32(this.height);
bw.writeBytes(this.chainwork.toArrayLike(Buffer, 'le', 32));
return bw.render();
}
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
*/
fromRaw(data) {
const br = bio.read(data, true);
const hash = hash256.digest(br.readBytes(80));
br.seek(-80);
this.hash = hash;
this.version = br.readU32();
this.prevBlock = br.readHash();
this.merkleRoot = br.readHash();
this.time = br.readU32();
this.bits = br.readU32();
this.nonce = br.readU32();
this.height = br.readU32();
this.chainwork = new BN(br.readBytes(32), 'le');
return this;
}
/**
* Deserialize the entry.
* @param {Buffer} data
* @returns {ChainEntry}
*/
static fromRaw(data) {
return new this().fromRaw(data);
}
/**
* Serialize the entry to an object more
* suitable for JSON serialization.
* @returns {Object}
*/
toJSON() {
return {
hash: util.revHex(this.hash),
version: this.version,
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
time: this.time,
bits: this.bits,
nonce: this.nonce,
height: this.height,
chainwork: this.chainwork.toString('hex', 64)
};
}
/**
* Inject properties from json object.
* @private
* @param {Object} json
*/
fromJSON(json) {
assert(json, 'Block data is required.');
assert(typeof json.hash === 'string');
assert((json.version >>> 0) === json.version);
assert(typeof json.prevBlock === 'string');
assert(typeof json.merkleRoot === 'string');
assert((json.time >>> 0) === json.time);
assert((json.bits >>> 0) === json.bits);
assert((json.nonce >>> 0) === json.nonce);
assert(typeof json.chainwork === 'string');
this.hash = util.fromRev(json.hash);
this.version = json.version;
this.prevBlock = util.fromRev(json.prevBlock);
this.merkleRoot = util.fromRev(json.merkleRoot);
this.time = json.time;
this.bits = json.bits;
this.nonce = json.nonce;
this.height = json.height;
this.chainwork = new BN(json.chainwork, 'hex');
return this;
}
/**
* Instantiate block from jsonified object.
* @param {Object} json
* @returns {ChainEntry}
*/
static fromJSON(json) {
return new this().fromJSON(json);
}
/**
* Convert the entry to a headers object.
* @returns {Headers}
*/
toHeaders() {
return Headers.fromEntry(this);
}
/**
* Convert the entry to an inv item.
* @returns {InvItem}
*/
toInv() {
return new InvItem(InvItem.types.BLOCK, this.hash);
}
/**
* Return a more user-friendly object.
* @returns {Object}
*/
[inspectSymbol]() {
const json = this.toJSON();
json.version = json.version.toString(16);
return json;
}
/**
* Test whether an object is a {@link ChainEntry}.
* @param {Object} obj
* @returns {Boolean}
*/
static isChainEntry(obj) {
return obj instanceof ChainEntry;
}
}
/**
* The max chainwork (1 << 256).
* @const {BN}
*/
ChainEntry.MAX_CHAINWORK = new BN(1).ushln(256);
/*
* Expose
*/
module.exports = ChainEntry;

View File

@ -1,76 +0,0 @@
/*!
* common.js - bitcoin constants for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module blockchain/common
*/
/**
* Locktime flags.
* @enum {Number}
*/
exports.lockFlags = {
VERIFY_SEQUENCE: 1 << 0,
MEDIAN_TIME_PAST: 1 << 1
};
/**
* Consensus locktime flags (used for block validation).
* @const {LockFlags}
* @default
*/
exports.lockFlags.MANDATORY_LOCKTIME_FLAGS = 0;
/**
* Standard locktime flags (used for mempool validation).
* @const {LockFlags}
* @default
*/
exports.lockFlags.STANDARD_LOCKTIME_FLAGS = 0
| exports.lockFlags.VERIFY_SEQUENCE
| exports.lockFlags.MEDIAN_TIME_PAST;
/**
* Threshold states for versionbits
* @enum {Number}
* @default
*/
exports.thresholdStates = {
DEFINED: 0,
STARTED: 1,
LOCKED_IN: 2,
ACTIVE: 3,
FAILED: 4
};
/**
* Verify flags for blocks.
* @enum {Number}
* @default
*/
exports.flags = {
VERIFY_NONE: 0,
VERIFY_POW: 1 << 0,
VERIFY_BODY: 1 << 1
};
/**
* Default block verify flags.
* @const {Number}
* @default
*/
exports.flags.DEFAULT_FLAGS = 0
| exports.flags.VERIFY_POW
| exports.flags.VERIFY_BODY;

View File

@ -1,17 +0,0 @@
/*!
* blockchain/index.js - blockchain for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module blockchain
*/
exports.ChainDB = require('./chaindb');
exports.ChainEntry = require('./chainentry');
exports.Chain = require('./chain');
exports.common = require('./common');
exports.layout = require('./layout');

View File

@ -1,54 +0,0 @@
/*!
* layout.js - blockchain data layout for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const bdb = require('bdb');
/*
* Database Layout:
* V -> db version
* O -> chain options
* R -> tip hash
* D -> versionbits deployments
* e[hash] -> entry
* h[hash] -> height
* H[height] -> hash
* n[hash] -> next hash
* p[hash] -> tip index
* b[hash] -> block (deprecated)
* t[hash] -> extended tx (deprecated)
* c[hash] -> coins
* u[hash] -> undo coins (deprecated)
* v[bit][hash] -> versionbits state
* T[addr-hash][hash] -> dummy (tx by address) (deprecated)
* C[addr-hash][hash][index] -> dummy (coin by address) (deprecated)
*/
const layout = {
V: bdb.key('V'),
O: bdb.key('O'),
R: bdb.key('R'),
D: bdb.key('D'),
e: bdb.key('e', ['hash256']),
h: bdb.key('h', ['hash256']),
H: bdb.key('H', ['uint32']),
n: bdb.key('n', ['hash256']),
p: bdb.key('p', ['hash256']),
b: bdb.key('b', ['hash256']),
t: bdb.key('t', ['hash256']),
c: bdb.key('c', ['hash256', 'uint32']),
u: bdb.key('u', ['hash256']),
v: bdb.key('v', ['uint8', 'hash256']),
T: bdb.key('T', ['hash', 'hash256']),
C: bdb.key('C', ['hash', 'hash256', 'uint32'])
};
/*
* Expose
*/
module.exports = layout;

View File

@ -1,148 +0,0 @@
# BlockStore
BlockStore `lib/blockstore` is a bcoin module intended to be used as a backend
for storing block and undo coin data. It includes a backend that uses flat
files for storage. Its key benefit is performance improvements across the
board in disk I/O, which is the major bottleneck for the initial block sync.
Blocks are stored in wire format directly to the disk, while some additional
metadata is stored in a key-value store, i.e. LevelDB, to help with the data
management. Both the flat files and the metadata db, are exposed through a
unified interace so that the users can simply read and write blocks without
having to worry about managing data layout on the disk.
In addition to blocks, undo coin data, which is used to revert the changes
applied by a block (in case of a re-org), is also stored on disk, in a similar
fashion.
## Interface
The `AbstractBlockStore` interface defines the following abstract methods to be
defined by concrete implementations:
### Basic housekeeping
* `ensure()`
* `open()`
* `close()`
### Block I/O
* `read(hash, offset, size)`
* `write(hash, data)`
* `prune(hash)`
* `has(hash)`
### Undo Coins I/O
* `readUndo(hash)`
* `writeUndo(hash, data)`
* `pruneUndo(hash)`
* `hasUndo(hash)`
The interface is implemented by `FileBlockStore` and `LevelBlockStore`, backed
by flat files and LevelDB respectively. We will focus here on the
`FileBlockStore`, which is the backend that implements a flat file based
storage.
## FileBlockStore
`FileBlockStore` implements the flat file backend for `AbstractBlockStore`. As
the name suggests, it uses flat files for block/undo data and LevelDB for
metadata.
Let's create a file blockstore, write a block and walk-through the disk storage:
```js
// nodejs
const store = blockstore.create({
network: 'regtest',
prefix: '/tmp/blockstore'
});
await store.ensure();
await store.open();
await store.write(hash, block);
```
```sh
// shell
tree /tmp/blockstore/
/tmp/blockstore/
└── blocks
├── blk00000.dat
└── index
├── LOG
...
```
As we can see, the store writes to the file `blk00000.dat` in
`/tmp/blockstore/blocks/`, and the metadata is written to
`/tmp/blockstore/index`.
Raw blocks are written to the disk in flat files named `blkXXXXX.dat`, where
`XXXXX` is the number of file being currently written, starting at
`blk00000.dat`. We store the file number as an integer in the metadata db,
expanding the digits to five places.
The metadata db key `layout.F` tracks the last file used for writing. Each
file in turn tracks the number of blocks in it, the number of bytes used and
its max length. This data is stored in the db key `layout.f`.
f['block'][0] => [1, 5, 128] // blk00000.dat: 1 block written, 5 bytes used, 128 bytes length
F['block'] => 0 // writing to file blk00000.dat
Each raw block data is preceded by a magic marker defined as follows, to help
identify data written by us:
magic (8 bytes) = network.magic (4 bytes) + block data length (4 bytes)
For raw undo block data, the hash of the block is also included:
magic (40 bytes) = network.magic (4 bytes) + length (4 bytes) + hash (32 bytes)
But a marker alone is not sufficient to track the data we write to the files.
For each block we write, we need to store a pointer to the position in the file
where to start reading, and the size of the data we need to seek. This data is
stored in the metadata db using the key `layout.b`:
b['block']['hash'] => [0, 8, 285] // 'hash' points to file blk00000.dat, position 8, size 285
Using this we know that our block is in `blk00000.dat`, bytes 8 through 293 and its size
is 285 bytes.
Note that the position indicates that the block data is preceded by 8 bytes of
the magic marker.
Examples:
> `store.write('hash', 'block')`
blk00000:
0xfabfb5da05000000 block
index:
b['block']['hash'] => [0, 8, 5]
f['block'][0] => [1, 13, 128]
F['block'] => 0
> `store.write('hash1', 'block1')`
blk00000:
0xfabfb5da05000000 block 0xfabfb5da06000000 block1
index:
b['block']['hash'] => [0, 8, 5]
b['block']['hash1'] => [0, 13, 6]
f['block'][0] => [2, 19, 128]
F['block'] => 0
> `store.prune('hash1', 'block1')`
blk00000:
0xfabfb5da05000000 block 0xfabfb5da06000000 block1
index:
b['block']['hash'] => [0, 8, 5]
f['block'][0] => [1, 19, 128]
F['block'] => 0

View File

@ -1,142 +0,0 @@
/*!
* blockstore/abstract.js - abstract blockstore for bcoin
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const Logger = require('blgr');
/**
* Abstract Block Store
*
* @alias module:blockstore.AbstractBlockStore
* @abstract
*/
class AbstractBlockStore {
/**
* Create an abstract blockstore.
* @constructor
*/
constructor(options) {
this.options = options || {};
if (this.options.logger != null)
this.logger = this.options.logger.context('blockstore');
else
this.logger = Logger.global.context('blockstore');
}
/**
* This method ensures that resources are available
* before opening.
* @returns {Promise}
*/
async ensure() {
throw new Error('Abstract method.');
}
/**
* This method opens any necessary resources and
* initializes the store to be ready to be queried.
* @returns {Promise}
*/
async open() {
throw new Error('Abstract method.');
}
/**
* This method closes resources and prepares
* the store to be closed.
* @returns {Promise}
*/
async close() {
throw new Error('Abstract method.');
}
/**
* This method stores block undo coin data.
* @returns {Promise}
*/
async writeUndo(hash, data) {
throw new Error('Abstract method.');
}
/**
* This method stores block data.
* @returns {Promise}
*/
async write(hash, data) {
throw new Error('Abstract method.');
}
/**
* This method will retrieve block undo coin data.
* @returns {Promise}
*/
async readUndo(hash) {
throw new Error('Abstract method.');
}
/**
* This method will retrieve block data. Smaller portions of
* the block can be read by using the offset and size arguments.
* @returns {Promise}
*/
async read(hash, offset, size) {
throw new Error('Abstract method.');
}
/**
* This will free resources for storing the block undo coin data.
* @returns {Promise}
*/
async pruneUndo(hash) {
throw new Error('Abstract method.');
}
/**
* This will free resources for storing the block data.
* @returns {Promise}
*/
async prune(hash) {
throw new Error('Abstract method.');
}
/**
* This will check if a block undo coin data has been stored
* and is available.
* @returns {Promise}
*/
async hasUndo(hash) {
throw new Error('Abstract method.');
}
/**
* This will check if a block has been stored and is available.
* @returns {Promise}
*/
async has(hash) {
throw new Error('Abstract method.');
}
}
/*
* Expose
*/
module.exports = AbstractBlockStore;

View File

@ -1,31 +0,0 @@
/*!
* common.js - blockstore constants for bcoin
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module blockstore/common
*/
/**
* Block data types.
* @enum {Number}
*/
exports.types = {
BLOCK: 1,
UNDO: 2
};
/**
* File prefixes for block data types.
* @enum {String}
*/
exports.prefixes = {
1: 'blk',
2: 'blu'
};

View File

@ -1,590 +0,0 @@
/*!
* blockstore/file.js - file blockstore for bcoin
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const {isAbsolute, resolve, join} = require('path');
const bdb = require('bdb');
const assert = require('bsert');
const fs = require('bfile');
const bio = require('bufio');
const hash256 = require('bcrypto/lib/hash256');
const Network = require('../protocol/network');
const AbstractBlockStore = require('./abstract');
const {BlockRecord, FileRecord} = require('./records');
const layout = require('./layout');
const {types, prefixes} = require('./common');
/**
* File Block Store
*
* @alias module:blockstore:FileBlockStore
* @abstract
*/
class FileBlockStore extends AbstractBlockStore {
/**
* Create a blockstore that stores blocks in files.
* @constructor
*/
constructor(options) {
super(options);
assert(isAbsolute(options.location), 'Location not absolute.');
this.location = options.location;
this.indexLocation = resolve(this.location, './index');
this.db = bdb.create({
location: this.indexLocation,
cacheSize: options.cacheSize,
compression: false
});
this.maxFileLength = options.maxFileLength || 128 * 1024 * 1024;
assert(Number.isSafeInteger(this.maxFileLength),
'Invalid max file length.');
this.network = Network.primary;
if (options.network != null)
this.network = Network.get(options.network);
this.writing = false;
}
/**
* Compares the number of files in the directory
* with the recorded number of files.
* @param {Number} type - The type of block data
* @private
* @returns {Promise}
*/
async check(type) {
const prefix = prefixes[type];
const regexp = new RegExp(`^${prefix}(\\d{5})\\.dat$`);
const all = await fs.readdir(this.location);
const dats = all.filter(f => regexp.test(f));
const filenos = dats.map(f => parseInt(f.match(regexp)[1]));
let missing = false;
for (const fileno of filenos) {
const rec = await this.db.get(layout.f.encode(type, fileno));
if (!rec) {
missing = true;
break;
}
}
return {missing, filenos};
}
/**
* Creates indexes from files for a block type. Reads the hash of
* the block data from the magic prefix, except for a block which
* the hash is read from the block header.
* @private
* @param {Number} type - The type of block data
* @returns {Promise}
*/
async _index(type) {
const {missing, filenos} = await this.check(type);
if (!missing)
return;
this.logger.info('Indexing block type %d...', type);
for (const fileno of filenos) {
const b = this.db.batch();
const filepath = this.filepath(type, fileno);
const data = await fs.readFile(filepath);
const reader = bio.read(data);
let magic = null;
let blocks = 0;
while (reader.left() >= 4) {
magic = reader.readU32();
// Move forward a byte from the last read
// if the magic doesn't match.
if (magic !== this.network.magic) {
reader.seek(-3);
continue;
}
let hash = null;
let position = 0;
let length = 0;
try {
length = reader.readU32();
if (type === types.BLOCK) {
position = reader.offset;
hash = hash256.digest(reader.readBytes(80, true));
reader.seek(length - 80);
} else {
hash = reader.readHash();
position = reader.offset;
reader.seek(length);
}
} catch (err) {
this.logger.warning(
'Unknown block in file: %s, reason: %s',
filepath, err.message);
continue;
}
const blockrecord = new BlockRecord({
file: fileno,
position: position,
length: length
});
blocks += 1;
b.put(layout.b.encode(type, hash), blockrecord.toRaw());
}
const filerecord = new FileRecord({
blocks: blocks,
used: reader.offset,
length: this.maxFileLength
});
b.put(layout.f.encode(type, fileno), filerecord.toRaw());
await b.write();
this.logger.info('Indexed %d blocks (file=%s).', blocks, filepath);
}
}
/**
* Compares the number of files in the directory
* with the recorded number of files. If there are any
* inconsistencies it will reindex all blocks.
* @private
* @returns {Promise}
*/
async index() {
await this._index(types.BLOCK);
await this._index(types.UNDO);
}
/**
* This method ensures that both the block storage directory
* and index directory exist.
* before opening.
* @returns {Promise}
*/
async ensure() {
return fs.mkdirp(this.indexLocation);
}
/**
* Opens the file block store. It will regenerate necessary block
* indexing if the index is missing or inconsistent.
* @returns {Promise}
*/
async open() {
this.logger.info('Opening FileBlockStore...');
await this.db.open();
await this.db.verify(layout.V.encode(), 'fileblockstore', 0);
await this.index();
}
/**
* This closes the file block store and underlying
* indexing databases.
*/
async close() {
this.logger.info('Closing FileBlockStore...');
await this.db.close();
}
/**
* This method will determine the file path based on the file number
* and the current block data location.
* @private
* @param {Number} type - The type of block data
* @param {Number} fileno - The number of the file.
* @returns {Promise}
*/
filepath(type, fileno) {
const pad = 5;
let num = fileno.toString(10);
if (num.length > pad)
throw new Error('File number too large.');
while (num.length < pad)
num = `0${num}`;
let filepath = null;
const prefix = prefixes[type];
if (!prefix)
throw new Error('Unknown file prefix.');
filepath = join(this.location, `${prefix}${num}.dat`);
return filepath;
}
/**
* This method will select and potentially allocate a file to
* write a block based on the size and type.
* @private
* @param {Number} type - The type of block data
* @param {Number} length - The number of bytes
* @returns {Promise}
*/
async allocate(type, length) {
if (length > this.maxFileLength)
throw new Error('Block length above max file length.');
let fileno = 0;
let filerecord = null;
let filepath = null;
const last = await this.db.get(layout.F.encode(type));
if (last)
fileno = bio.readU32(last, 0);
filepath = this.filepath(type, fileno);
const rec = await this.db.get(layout.f.encode(type, fileno));
let touch = false;
if (rec) {
filerecord = FileRecord.fromRaw(rec);
} else {
touch = true;
filerecord = new FileRecord({
blocks: 0,
used: 0,
length: this.maxFileLength
});
}
if (filerecord.used + length > filerecord.length) {
fileno += 1;
filepath = this.filepath(type, fileno);
touch = true;
filerecord = new FileRecord({
blocks: 0,
used: 0,
length: this.maxFileLength
});
}
if (touch) {
const fd = await fs.open(filepath, 'w');
await fs.close(fd);
}
return {fileno, filerecord, filepath};
}
/**
* This method stores block undo coin data in files.
* @param {Buffer} hash - The block hash
* @param {Buffer} data - The block data
* @returns {Promise}
*/
async writeUndo(hash, data) {
return this._write(types.UNDO, hash, data);
}
/**
* This method stores block data in files.
* @param {Buffer} hash - The block hash
* @param {Buffer} data - The block data
* @returns {Promise}
*/
async write(hash, data) {
return this._write(types.BLOCK, hash, data);
}
/**
* This method stores block data in files with by appending
* data to the last written file and updating indexes to point
* to the file and position.
* @private
* @param {Number} type - The type of block data
* @param {Buffer} hash - The block hash
* @param {Buffer} data - The block data
* @returns {Promise}
*/
async _write(type, hash, data) {
if (this.writing)
throw new Error('Already writing.');
this.writing = true;
if (await this.db.has(layout.b.encode(type, hash))) {
this.writing = false;
return false;
}
let mlength = 8;
// Hash for a block is not stored with
// the magic prefix as it's read from the header
// of the block data.
if (type !== types.BLOCK)
mlength += 32;
const blength = data.length;
const length = data.length + mlength;
const bwm = bio.write(mlength);
bwm.writeU32(this.network.magic);
bwm.writeU32(blength);
if (type !== types.BLOCK)
bwm.writeHash(hash);
const magic = bwm.render();
const {
fileno,
filerecord,
filepath
} = await this.allocate(type, length);
const mposition = filerecord.used;
const bposition = filerecord.used + mlength;
const fd = await fs.open(filepath, 'r+');
let mwritten = 0;
let bwritten = 0;
try {
mwritten = await fs.write(fd, magic, 0, mlength, mposition);
bwritten = await fs.write(fd, data, 0, blength, bposition);
} finally {
await fs.close(fd);
}
if (mwritten !== mlength) {
this.writing = false;
throw new Error('Could not write block magic.');
}
if (bwritten !== blength) {
this.writing = false;
throw new Error('Could not write block.');
}
filerecord.blocks += 1;
filerecord.used += length;
const b = this.db.batch();
const blockrecord = new BlockRecord({
file: fileno,
position: bposition,
length: blength
});
b.put(layout.b.encode(type, hash), blockrecord.toRaw());
b.put(layout.f.encode(type, fileno), filerecord.toRaw());
const last = bio.write(4).writeU32(fileno).render();
b.put(layout.F.encode(type), last);
await b.write();
this.writing = false;
return true;
}
/**
* This method will retrieve block undo coin data.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async readUndo(hash) {
return this._read(types.UNDO, hash);
}
/**
* This method will retrieve block data. Smaller portions of the
* block (e.g. transactions) can be read by using the offset and
* length arguments.
* @param {Buffer} hash - The block hash
* @param {Number} offset - The offset within the block
* @param {Number} length - The number of bytes of the data
* @returns {Promise}
*/
async read(hash, offset, length) {
return this._read(types.BLOCK, hash, offset, length);
}
/**
* This methods reads data from disk by retrieving the index of
* the data and reading from the corresponding file and location.
* @private
* @param {Number} type - The type of block data
* @param {Buffer} hash - The block hash
* @param {Number} offset - The offset within the block
* @param {Number} length - The number of bytes of the data
* @returns {Promise}
*/
async _read(type, hash, offset, length) {
const raw = await this.db.get(layout.b.encode(type, hash));
if (!raw)
return null;
const blockrecord = BlockRecord.fromRaw(raw);
const filepath = this.filepath(type, blockrecord.file);
let position = blockrecord.position;
if (offset)
position += offset;
if (!length)
length = blockrecord.length;
if (offset + length > blockrecord.length)
throw new Error('Out-of-bounds read.');
const data = Buffer.alloc(length);
const fd = await fs.open(filepath, 'r');
let bytes = 0;
try {
bytes = await fs.read(fd, data, 0, length, position);
} finally {
await fs.close(fd);
}
if (bytes !== length)
throw new Error('Wrong number of bytes read.');
return data;
}
/**
* This will free resources for storing the block undo coin data.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async pruneUndo(hash) {
return this._prune(types.UNDO, hash);
}
/**
* This will free resources for storing the block data.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async prune(hash) {
return this._prune(types.BLOCK, hash);
}
/**
* This will free resources for storing the block data. The block
* data may not be deleted from disk immediately, the index for the
* block is removed and will not be able to be read. The underlying
* file is unlinked when all blocks in a file have been pruned.
* @private
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async _prune(type, hash) {
const braw = await this.db.get(layout.b.encode(type, hash));
if (!braw)
return false;
const blockrecord = BlockRecord.fromRaw(braw);
const fraw = await this.db.get(layout.f.encode(type, blockrecord.file));
if (!fraw)
return false;
const filerecord = FileRecord.fromRaw(fraw);
filerecord.blocks -= 1;
const b = this.db.batch();
if (filerecord.blocks === 0)
b.del(layout.f.encode(type, blockrecord.file));
else
b.put(layout.f.encode(type, blockrecord.file), filerecord.toRaw());
b.del(layout.b.encode(type, hash));
await b.write();
if (filerecord.blocks === 0)
await fs.unlink(this.filepath(type, blockrecord.file));
return true;
}
/**
* This will check if a block undo coin has been stored
* and is available.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async hasUndo(hash) {
return await this.db.has(layout.b.encode(types.UNDO, hash));
}
/**
* This will check if a block has been stored and is available.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async has(hash) {
return await this.db.has(layout.b.encode(types.BLOCK, hash));
}
}
/*
* Expose
*/
module.exports = FileBlockStore;

View File

@ -1,42 +0,0 @@
/*!
* blockstore/index.js - bitcoin blockstore for bcoin
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const {join} = require('path');
const AbstractBlockStore = require('./abstract');
const LevelBlockStore = require('./level');
const FileBlockStore = require('./file');
/**
* @module blockstore
*/
exports.create = (options) => {
const location = join(options.prefix, 'blocks');
if (options.memory) {
return new LevelBlockStore({
network: options.network,
logger: options.logger,
location: location,
cacheSize: options.cacheSize,
memory: options.memory
});
}
return new FileBlockStore({
network: options.network,
logger: options.logger,
location: location,
cacheSize: options.cacheSize
});
};
exports.AbstractBlockStore = AbstractBlockStore;
exports.FileBlockStore = FileBlockStore;
exports.LevelBlockStore = LevelBlockStore;

View File

@ -1,30 +0,0 @@
/*!
* blockstore/layout.js - file blockstore data layout for bcoin
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const bdb = require('bdb');
/*
* Database Layout:
* V -> db version
* F[type] -> last file record by type
* f[type][fileno] -> file record by type and file number
* b[type][hash] -> block record by type and block hash
*/
const layout = {
V: bdb.key('V'),
F: bdb.key('F', ['uint32']),
f: bdb.key('f', ['uint32', 'uint32']),
b: bdb.key('b', ['uint32', 'hash256'])
};
/*
* Expose
*/
module.exports = layout;

View File

@ -1,189 +0,0 @@
/*!
* blockstore/level.js - leveldb blockstore for bcoin
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const bdb = require('bdb');
const fs = require('bfile');
const AbstractBlockStore = require('./abstract');
const layout = require('./layout');
const {types} = require('./common');
/**
* LevelDB Block Store
*
* @alias module:blockstore:LevelBlockStore
* @abstract
*/
class LevelBlockStore extends AbstractBlockStore {
/**
* Create a blockstore that stores blocks in LevelDB.
* @constructor
*/
constructor(options) {
super(options);
this.location = options.location;
this.db = bdb.create({
location: this.location,
cacheSize: options.cacheSize,
compression: false,
memory: options.memory
});
}
/**
* This method ensures that the storage directory exists
* before opening.
* @returns {Promise}
*/
async ensure() {
return fs.mkdirp(this.location);
}
/**
* Opens the block storage.
* @returns {Promise}
*/
async open() {
this.logger.info('Opening LevelBlockStore...');
await this.db.open();
await this.db.verify(layout.V.encode(), 'levelblockstore', 0);
}
/**
* Closes the block storage.
*/
async close() {
this.logger.info('Closing LevelBlockStore...');
await this.db.close();
}
/**
* This method stores block undo coin data in LevelDB.
* @param {Buffer} hash - The block hash
* @param {Buffer} data - The block data
* @returns {Promise}
*/
async writeUndo(hash, data) {
return this.db.put(layout.b.encode(types.UNDO, hash), data);
}
/**
* This method stores block data in LevelDB.
* @param {Buffer} hash - The block hash
* @param {Buffer} data - The block data
* @returns {Promise}
*/
async write(hash, data) {
return this.db.put(layout.b.encode(types.BLOCK, hash), data);
}
/**
* This method will retrieve block undo coin data.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async readUndo(hash) {
return this.db.get(layout.b.encode(types.UNDO, hash));
}
/**
* This method will retrieve block data. Smaller portions of the
* block (e.g. transactions) can be returned using the offset and
* length arguments. However, the entire block will be read as the
* data is stored in a key/value database.
* @param {Buffer} hash - The block hash
* @param {Number} offset - The offset within the block
* @param {Number} length - The number of bytes of the data
* @returns {Promise}
*/
async read(hash, offset, length) {
let raw = await this.db.get(layout.b.encode(types.BLOCK, hash));
if (offset) {
if (offset + length > raw.length)
throw new Error('Out-of-bounds read.');
raw = raw.slice(offset, offset + length);
}
return raw;
}
/**
* This will free resources for storing the block undo coin data.
* The block data may not be immediately removed from disk, and will
* be reclaimed during LevelDB compaction.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async pruneUndo(hash) {
if (!await this.hasUndo(hash))
return false;
await this.db.del(layout.b.encode(types.UNDO, hash));
return true;
}
/**
* This will free resources for storing the block data. The block
* data may not be immediately removed from disk, and will be reclaimed
* during LevelDB compaction.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async prune(hash) {
if (!await this.has(hash))
return false;
await this.db.del(layout.b.encode(types.BLOCK, hash));
return true;
}
/**
* This will check if a block undo coin data has been stored
* and is available.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async hasUndo(hash) {
return this.db.has(layout.b.encode(types.UNDO, hash));
}
/**
* This will check if a block has been stored and is available.
* @param {Buffer} hash - The block hash
* @returns {Promise}
*/
async has(hash) {
return this.db.has(layout.b.encode(types.BLOCK, hash));
}
}
/*
* Expose
*/
module.exports = LevelBlockStore;

View File

@ -1,149 +0,0 @@
/*!
* blockstore/records.js - blockstore records
* Copyright (c) 2019, Braydon Fuller (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('bsert');
const bio = require('bufio');
/**
* @module blockstore/records
*/
/**
* Block Record
*/
class BlockRecord {
/**
* Create a block record.
* @constructor
*/
constructor(options = {}) {
this.file = options.file || 0;
this.position = options.position || 0;
this.length = options.length || 0;
assert((this.file >>> 0) === this.file);
assert((this.position >>> 0) === this.position);
assert((this.length >>> 0) === this.length);
}
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
*/
fromRaw(data) {
const br = bio.read(data);
this.file = br.readU32();
this.position = br.readU32();
this.length = br.readU32();
return this;
}
/**
* Instantiate block record from serialized data.
* @param {Hash} hash
* @param {Buffer} data
* @returns {BlockRecord}
*/
static fromRaw(data) {
return new this().fromRaw(data);
}
/**
* Serialize the block record.
* @returns {Buffer}
*/
toRaw() {
const bw = bio.write(12);
bw.writeU32(this.file);
bw.writeU32(this.position);
bw.writeU32(this.length);
return bw.render();
}
}
/**
* File Record
*/
class FileRecord {
/**
* Create a file record.
* @constructor
*/
constructor(options = {}) {
this.blocks = options.blocks || 0;
this.used = options.used || 0;
this.length = options.length || 0;
assert((this.blocks >>> 0) === this.blocks);
assert((this.used >>> 0) === this.used);
assert((this.length >>> 0) === this.length);
}
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
*/
fromRaw(data) {
const br = bio.read(data);
this.blocks = br.readU32();
this.used = br.readU32();
this.length = br.readU32();
return this;
}
/**
* Instantiate file record from serialized data.
* @param {Hash} hash
* @param {Buffer} data
* @returns {ChainState}
*/
static fromRaw(data) {
return new this().fromRaw(data);
}
/**
* Serialize the file record.
* @returns {Buffer}
*/
toRaw() {
const bw = bio.write(12);
bw.writeU32(this.blocks);
bw.writeU32(this.used);
bw.writeU32(this.length);
return bw.render();
}
}
/*
* Expose
*/
exports.BlockRecord = BlockRecord;
exports.FileRecord = FileRecord;
module.exports = exports;

View File

@ -1,366 +0,0 @@
/*!
* amount.js - amount object for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('bsert');
const fixed = require('../utils/fixed');
const {inspectSymbol} = require('../utils');
/**
* Amount
* Represents a bitcoin amount (satoshis internally).
* @alias module:btc.Amount
* @property {Amount} value
*/
class Amount {
/**
* Create an amount.
* @constructor
* @param {(String|Number)?} value
* @param {String?} unit
*/
constructor(value, unit) {
this.value = 0;
if (value != null)
this.fromOptions(value, unit);
}
/**
* Inject properties from options.
* @private
* @param {(String|Number)?} value
* @param {String?} unit
* @returns {Amount}
*/
fromOptions(value, unit) {
if (typeof unit === 'string')
return this.from(unit, value);
if (typeof value === 'number')
return this.fromValue(value);
return this.fromBTC(value);
}
/**
* Get satoshi value.
* @returns {Amount}
*/
toValue() {
return this.value;
}
/**
* Get satoshi string or value.
* @param {Boolean?} num
* @returns {String|Amount}
*/
toSatoshis(num) {
if (num)
return this.value;
return this.value.toString(10);
}
/**
* Get bits string or value.
* @param {Boolean?} num
* @returns {String|Amount}
*/
toBits(num) {
return Amount.encode(this.value, 2, num);
}
/**
* Get mbtc string or value.
* @param {Boolean?} num
* @returns {String|Amount}
*/
toMBTC(num) {
return Amount.encode(this.value, 5, num);
}
/**
* Get btc string or value.
* @param {Boolean?} num
* @returns {String|Amount}
*/
toBTC(num) {
return Amount.encode(this.value, 8, num);
}
/**
* Get unit string or value.
* @param {String} unit - Can be `sat`,
* `ubtc`, `bits`, `mbtc`, or `btc`.
* @param {Boolean?} num
* @returns {String|Amount}
*/
to(unit, num) {
switch (unit) {
case 'sat':
return this.toSatoshis(num);
case 'ubtc':
case 'bits':
return this.toBits(num);
case 'mbtc':
return this.toMBTC(num);
case 'btc':
return this.toBTC(num);
}
throw new Error(`Unknown unit "${unit}".`);
}
/**
* Convert amount to bitcoin string.
* @returns {String}
*/
toString() {
return this.toBTC();
}
/**
* Inject properties from value.
* @private
* @param {Amount} value
* @returns {Amount}
*/
fromValue(value) {
assert(Number.isSafeInteger(value) && value >= 0,
'Value must be an int64.');
this.value = value;
return this;
}
/**
* Inject properties from satoshis.
* @private
* @param {Number|String} value
* @returns {Amount}
*/
fromSatoshis(value) {
this.value = Amount.decode(value, 0);
return this;
}
/**
* Inject properties from bits.
* @private
* @param {Number|String} value
* @returns {Amount}
*/
fromBits(value) {
this.value = Amount.decode(value, 2);
return this;
}
/**
* Inject properties from mbtc.
* @private
* @param {Number|String} value
* @returns {Amount}
*/
fromMBTC(value) {
this.value = Amount.decode(value, 5);
return this;
}
/**
* Inject properties from btc.
* @private
* @param {Number|String} value
* @returns {Amount}
*/
fromBTC(value) {
this.value = Amount.decode(value, 8);
return this;
}
/**
* Inject properties from unit.
* @private
* @param {String} unit
* @param {Number|String} value
* @returns {Amount}
*/
from(unit, value) {
switch (unit) {
case 'sat':
return this.fromSatoshis(value);
case 'ubtc':
case 'bits':
return this.fromBits(value);
case 'mbtc':
return this.fromMBTC(value);
case 'btc':
return this.fromBTC(value);
}
throw new Error(`Unknown unit "${unit}".`);
}
/**
* Instantiate amount from options.
* @param {(String|Number)?} value
* @param {String?} unit
* @returns {Amount}
*/
static fromOptions(value, unit) {
return new this().fromOptions(value, unit);
}
/**
* Instantiate amount from value.
* @private
* @param {Amount} value
* @returns {Amount}
*/
static fromValue(value) {
return new this().fromValue(value);
}
/**
* Instantiate amount from satoshis.
* @param {Number|String} value
* @returns {Amount}
*/
static fromSatoshis(value) {
return new this().fromSatoshis(value);
}
/**
* Instantiate amount from bits.
* @param {Number|String} value
* @returns {Amount}
*/
static fromBits(value) {
return new this().fromBits(value);
}
/**
* Instantiate amount from mbtc.
* @param {Number|String} value
* @returns {Amount}
*/
static fromMBTC(value) {
return new this().fromMBTC(value);
}
/**
* Instantiate amount from btc.
* @param {Number|String} value
* @returns {Amount}
*/
static fromBTC(value) {
return new this().fromBTC(value);
}
/**
* Instantiate amount from unit.
* @param {String} unit
* @param {Number|String} value
* @returns {Amount}
*/
static from(unit, value) {
return new this().from(unit, value);
}
/**
* Inspect amount.
* @returns {String}
*/
[inspectSymbol]() {
return `<Amount: ${this.toString()}>`;
}
/**
* Safely convert satoshis to a BTC string.
* This function explicitly avoids any
* floating point arithmetic.
* @param {Amount} value - Satoshis.
* @returns {String} BTC string.
*/
static btc(value, num) {
if (typeof value === 'string')
return value;
return Amount.encode(value, 8, num);
}
/**
* Safely convert a BTC string to satoshis.
* @param {String} str - BTC
* @returns {Amount} Satoshis.
* @throws on parse error
*/
static value(str) {
if (typeof str === 'number')
return str;
return Amount.decode(str, 8);
}
/**
* Safely convert satoshis to a BTC string.
* @param {Amount} value
* @param {Number} exp - Exponent.
* @param {Boolean} num - Return a number.
* @returns {String|Number}
*/
static encode(value, exp, num) {
if (num)
return fixed.toFloat(value, exp);
return fixed.encode(value, exp);
}
/**
* Safely convert a BTC string to satoshis.
* @param {String|Number} value - BTC
* @param {Number} exp - Exponent.
* @returns {Amount} Satoshis.
* @throws on parse error
*/
static decode(value, exp) {
if (typeof value === 'number')
return fixed.fromFloat(value, exp);
return fixed.decode(value, exp);
}
}
/*
* Expose
*/
module.exports = Amount;

View File

@ -1,14 +0,0 @@
/*!
* btc/index.js - high-level btc objects for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module btc
*/
exports.Amount = require('./amount');
exports.URI = require('./uri');

View File

@ -1,286 +0,0 @@
/**
* uri.js - bitcoin uri parsing for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('bsert');
const Address = require('../primitives/address');
const Amount = require('./amount');
const {inspectSymbol} = require('../utils');
/**
* URI
* Represents a bitcoin URI.
* @alias module:btc.URI
* @property {Address} address
* @property {Amount} amount
* @property {String|null} label
* @property {String|null} message
* @property {String|null} request
*/
class URI {
/**
* Create a bitcoin URI.
* @alias module:btc.URI
* @constructor
* @param {Object|String} options
*/
constructor(options) {
this.address = new Address();
this.amount = -1;
this.label = null;
this.message = null;
this.request = null;
if (options)
this.fromOptions(options);
}
/**
* Inject properties from options object.
* @private
* @param {Object|String} options
* @returns {URI}
*/
fromOptions(options) {
if (typeof options === 'string')
return this.fromString(options);
if (options.address)
this.address.fromOptions(options.address);
if (options.amount != null) {
assert(Number.isSafeInteger(options.amount) && options.amount >= 0,
'Amount must be a uint64.');
this.amount = options.amount;
}
if (options.label) {
assert(typeof options.label === 'string', 'Label must be a string.');
this.label = options.label;
}
if (options.message) {
assert(typeof options.message === 'string', 'Message must be a string.');
this.message = options.message;
}
if (options.request) {
assert(typeof options.request === 'string', 'Request must be a string.');
this.request = options.request;
}
return this;
}
/**
* Instantiate URI from options.
* @param {Object|String} options
* @returns {URI}
*/
static fromOptions(options) {
return new this().fromOptions(options);
}
/**
* Parse and inject properties from string.
* @private
* @param {String} str
* @param {Network?} network
* @returns {URI}
*/
fromString(str, network) {
assert(typeof str === 'string');
assert(str.length > 8, 'Not a bitcoin URI.');
const prefix = str.substring(0, 8);
str = str.substring(8);
const index = str.indexOf('?');
let addr, qs;
if (index === -1) {
addr = str;
} else {
addr = str.substring(0, index);
qs = str.substring(index + 1);
}
this.address.fromString(addr, network);
if (!qs)
return this;
const query = parsePairs(qs);
if (query.amount) {
assert(query.amount.length > 0, 'Value is empty.');
assert(query.amount[0] !== '-', 'Value is negative.');
this.amount = Amount.value(query.amount);
}
if (query.label)
this.label = query.label;
if (query.message)
this.message = query.message;
if (query.r)
this.request = query.r;
return this;
}
/**
* Instantiate uri from string.
* @param {String} str
* @param {Network?} network
* @returns {URI}
*/
static fromString(str, network) {
return new this().fromString(str, network);
}
/**
* Serialize uri to a string.
* @returns {String}
*/
toString() {
let str = 'flo:';
str += this.address.toString();
const query = [];
if (this.amount !== -1)
query.push(`amount=${Amount.btc(this.amount)}`);
if (this.label)
query.push(`label=${escape(this.label)}`);
if (this.message)
query.push(`message=${escape(this.message)}`);
if (this.request)
query.push(`r=${escape(this.request)}`);
if (query.length > 0)
str += '?' + query.join('&');
return str;
}
/**
* Inspect bitcoin uri.
* @returns {String}
*/
[inspectSymbol]() {
return `<URI: ${this.toString()}>`;
}
}
/*
* Helpers
*/
class BitcoinQuery {
constructor() {
this.amount = null;
this.label = null;
this.message = null;
this.r = null;
}
}
function parsePairs(str) {
const parts = str.split('&');
const data = new BitcoinQuery();
let size = 0;
for (const pair of parts) {
const index = pair.indexOf('=');
let key, value;
if (index === -1) {
key = pair;
value = '';
} else {
key = pair.substring(0, index);
value = pair.substring(index + 1);
}
if (key.length === 0) {
assert(value.length === 0, 'Empty key in querystring.');
continue;
}
assert(size < 4, 'Too many keys in querystring.');
switch (key) {
case 'amount':
assert(data.amount == null, 'Duplicate key in querystring (amount).');
data.amount = unescape(value);
break;
case 'label':
assert(data.label == null, 'Duplicate key in querystring (label).');
data.label = unescape(value);
break;
case 'message':
assert(data.message == null, 'Duplicate key in querystring (message).');
data.message = unescape(value);
break;
case 'r':
assert(data.r == null, 'Duplicate key in querystring (r).');
data.r = unescape(value);
break;
default:
assert(false, `Unknown querystring key: ${value}.`);
break;
}
size += 1;
}
return data;
}
function unescape(str) {
try {
str = decodeURIComponent(str);
str = str.replace(/\+/g, ' ');
} catch (e) {
throw new Error('Malformed URI.');
}
if (str.indexOf('\0') !== -1)
throw new Error('Malformed URI.');
return str;
}
function escape(str) {
str = encodeURIComponent(str);
str = str.replace(/%20/g, '+');
return str;
}
/*
* Expose
*/
module.exports = URI;

View File

@ -0,0 +1,63 @@
/*!
* blockdb.js - blockchain data management for bcoin
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* BlockDB
* @constructor
*/
function BlockDB(chaindb) {
this.chaindb = chaindb;
this.db = chaindb.db;
this.layout = chaindb.layout;
}
BlockDB.prototype.open = function open() {
return Promise.resolve();
};
BlockDB.prototype.close = function close() {
return Promise.resolve();
};
BlockDB.prototype.sync = function sync() {
return Promise.resolve();
};
BlockDB.prototype.saveBlock = function saveBlock(block) {
this.chaindb.put(this.layout.b(block.hash()), block.toRaw());
return Promise.resolve();
};
BlockDB.prototype.readBlock = function readBlock(hash) {
return this.db.get(this.layout.b(hash));
};
BlockDB.prototype.readBlockEntry = function readBlockEntry(entry) {
return this.readBlock(entry.hash);
};
BlockDB.prototype.removeBlock = function removeBlock(hash) {
this.chaindb.del(this.layout.b(hash));
return Promise.resolve();
};
BlockDB.prototype.pruneBlock = function pruneBlock(hash) {
this.chaindb.del(this.layout.b(hash));
return Promise.resolve();
};
BlockDB.prototype.pruneBlockEntry = function pruneBlockEntry(entry) {
return this.pruneBlock(entry.hash);
};
/*
* Expose
*/
module.exports = BlockDB;

196
lib/chain/blockdb.js Normal file
View File

@ -0,0 +1,196 @@
/*!
* blockdb.js - blockchain data management for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var assert = require('assert');
var co = require('../utils/co');
var Flat = require('../db/flat');
var LRU = require('../utils/lru');
var FileEntry = Flat.FileEntry;
/**
* BlockDB
* @constructor
*/
function BlockDB(chaindb) {
this.chaindb = chaindb;
this.db = chaindb.db;
this.layout = chaindb.layout;
this.flat = new Flat(this.db);
this.cache = new LRU(8192);
}
BlockDB.prototype.open = function open() {
return this.flat.open();
};
BlockDB.prototype.close = function close() {
return this.flat.close();
};
BlockDB.prototype.sync = co(function* sync() {
var entry = yield this.chaindb.getTip();
var block, rollback;
assert(entry);
for (;;) {
try {
block = yield this.readBlock(entry.hash);
} catch (e) {
if (e.type !== 'ChecksumMismatch')
throw e;
block = null;
}
if (block)
break;
this.cache.remove(entry.hash);
entry = yield entry.getPrevious();
assert(entry);
rollback = true;
}
if (!rollback)
return;
yield this.chaindb.reset(entry.hash, true);
});
BlockDB.prototype.getEntry = co(function* getEntry(hash) {
var key = hash;
var entry, data;
if (typeof key !== 'string')
key = key.toString('hex');
entry = this.cache.get(key);
if (entry)
return entry;
data = yield this.db.get(this.layout.b(hash));
if (!data)
return;
entry = FileEntry.fromRaw(data);
this.cache.set(key, entry);
return entry;
});
BlockDB.prototype.saveBlock = co(function* saveBlock(block) {
var hash = block.hash();
var hex = block.hash('hex');
var entry = yield this.flat.write(block.toRaw());
if (block.height === 0)
yield this.flat.sync();
this.cache.set(hex, entry);
this.chaindb.put(this.layout.b(hash), entry.toRaw());
});
BlockDB.prototype.readBlock = co(function* readBlock(hash) {
var entry = yield this.getEntry(hash);
if (!entry)
return;
return yield this.readBlockEntry(entry);
});
BlockDB.prototype.readBlockEntry = function readBlockEntry(entry) {
return this.flat.read(entry.index, entry.pos);
};
BlockDB.prototype.removeBlock = co(function* removeBlock(hash) {
var entry = yield this.getEntry(hash);
if (!entry)
return;
this.chaindb.del(this.layout.b(hash));
if (entry.pos === 0)
yield this.flat.remove(entry.index);
});
BlockDB.prototype.pruneBlock = co(function* pruneBlock(hash) {
var entry = yield this.getEntry(hash);
if (!entry)
return;
return yield this.pruneBlockEntry(hash, entry);
});
BlockDB.prototype.pruneBlockEntry = function pruneBlockEntry(hash, entry) {
var index = entry.index;
if (index === this.current.index)
index -= 1;
this.chaindb.del(this.layout.b(hash));
return this.flat.remove(index);
};
/**
* Batch
* @constructor
*/
function Batch(ffdb) {
this.ffdb = ffdb;
this.ops = [];
}
Batch.prototype.put = function put(block) {
this.ops.push(new BatchOp(0, block));
};
Batch.prototype.del = function del(hash) {
this.ops.push(new BatchOp(1, hash));
};
Batch.prototype.write = co(function* write() {
var i, op;
for (i = 0; i < this.ops.length; i++) {
op = this.ops[i];
switch (op.type) {
case 0:
yield this.ffdb.saveBlock(op.data);
break;
case 1:
yield this.ffdb.removeBlock(op.data);
break;
default:
assert(false);
}
}
});
/**
* BatchOp
* @constructor
*/
function BatchOp(type, data) {
this.type = type;
this.data = data;
}
/*
* Expose
*/
module.exports = BlockDB;

95
lib/chain/browser.js Normal file
View File

@ -0,0 +1,95 @@
/*!
* layout-browser.js - chaindb layout for browser.
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
var utils = require('../utils/utils');
var pad32 = utils.pad32;
var layout = {
R: 'R',
O: 'O',
e: function e(hash) {
return 'e' + hex(hash);
},
h: function h(hash) {
return 'h' + hex(hash);
},
H: function H(height) {
return 'H' + pad32(height);
},
n: function n(hash) {
return 'n' + hex(hash);
},
p: function p(hash) {
return 'p' + hex(hash);
},
b: function b(hash) {
return 'b' + hex(hash);
},
t: function t(hash) {
return 't' + hex(hash);
},
c: function c(hash) {
return 'c' + hex(hash);
},
u: function u(hash) {
return 'u' + hex(hash);
},
T: function T(address, hash) {
address = hex(address);
if (address.length === 64)
return 'W' + address + hex(hash);
return 'T' + address + hex(hash);
},
C: function C(address, hash, index) {
address = hex(address);
if (address.length === 64)
return 'X' + address + hex(hash) + pad32(index);
return 'C' + address + hex(hash) + pad32(index);
},
pp: function aa(key) {
return key.slice(1, 65);
},
Cc: function Cc(key) {
var hash, index;
if (key.length === 139) {
hash = key.slice(65, 129);
index = +key.slice(129);
} else {
hash = key.slice(41, 105);
index = +key.slice(105);
}
return [hash, index];
},
Tt: function Tt(key) {
return key.length === 129
? key.slice(64)
: key.slice(41);
}
};
/*
* Helpers
*/
function hex(hash) {
if (typeof hash !== 'string')
hash = hash.toString('hex');
return hash;
}
/*
* Expose
*/
module.exports = layout;

2305
lib/chain/chain.js Normal file

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More