mirror of
https://github.com/Permissionless-Software-Foundation/bch-js.git
synced 2026-09-21 16:51:59 -07:00
Forked from christroutner/bch-js
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"root": true,
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2018,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": ["prettier"],
|
||||
"rules": {
|
||||
"no-debugger": ["warn"],
|
||||
"no-regex-spaces": ["error"],
|
||||
"no-unsafe-negation": ["error"],
|
||||
"curly": ["error", "multi-or-nest", "consistent"],
|
||||
"dot-location": ["error", "property"],
|
||||
"dot-notation": ["error"],
|
||||
"eqeqeq": ["error", "smart"],
|
||||
"no-else-return": ["error"],
|
||||
"no-extra-bind": ["error"],
|
||||
"no-extra-label": ["error"],
|
||||
"no-floating-decimal": ["error"],
|
||||
"no-implicit-coercion": ["error", { "allow": ["!!"] }],
|
||||
"wrap-iife": ["error", "inside"],
|
||||
"strict": ["error", "global"],
|
||||
"func-call-spacing": ["error", "never"],
|
||||
"comma-style": ["error", "last"],
|
||||
"keyword-spacing": ["error"],
|
||||
"linebreak-style": ["error", "unix"],
|
||||
"new-parens": ["error"],
|
||||
"no-lonely-if": ["error"],
|
||||
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1 }],
|
||||
"no-whitespace-before-property": ["error"],
|
||||
"semi": ["error", "never"],
|
||||
"arrow-body-style": ["error", "as-needed"],
|
||||
"arrow-parens": ["error", "as-needed"],
|
||||
"arrow-spacing": ["error"],
|
||||
"no-useless-computed-key": ["error"],
|
||||
"no-useless-rename": ["error"],
|
||||
"no-var": ["off"],
|
||||
"prefer-spread": ["off"],
|
||||
"prefer-template": ["error"],
|
||||
"rest-spread-spacing": ["error", "never"],
|
||||
"prefer-const": ["warn", { "destructuring": "all" }],
|
||||
"no-unreachable": ["warn"],
|
||||
"no-unused-vars": ["warn", { "args": "none" }],
|
||||
|
||||
"prettier/prettier": [
|
||||
"warn",
|
||||
{
|
||||
"printWidth": 80,
|
||||
"trailingComma": "none",
|
||||
"singleQuote": false,
|
||||
"semi": false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
node_modules/*
|
||||
.nyc_output/*
|
||||
wallet-info.txt
|
||||
wallet.json
|
||||
|
||||
docs/
|
||||
coverage/
|
||||
|
||||
# This paragraph comes last. Force includes specific files.
|
||||
!docs/README.md
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# This is a node.js v8+ JavaScript project
|
||||
language: node_js
|
||||
node_js:
|
||||
- "10"
|
||||
|
||||
# Build on Ubuntu Xenial (16.04)
|
||||
# https://docs.travis-ci.com/user/reference/trusty/#javascript-and-nodejs-images
|
||||
dist: xenial
|
||||
sudo: required
|
||||
|
||||
# Use Docker
|
||||
services:
|
||||
- docker
|
||||
|
||||
before_install:
|
||||
#- ./install-mongo
|
||||
#- npm install -g mocha
|
||||
|
||||
# https://github.com/greenkeeperio/greenkeeper-lockfile/issues/156
|
||||
install: case $TRAVIS_BRANCH in greenkeeper*) npm i;; *) npm ci;; esac;
|
||||
|
||||
# Send coverage data to Coveralls
|
||||
after_success:
|
||||
- npm run coverage
|
||||
|
||||
deploy:
|
||||
provider: script
|
||||
skip_cleanup: true
|
||||
script:
|
||||
- npx semantic-release
|
||||
@@ -0,0 +1,93 @@
|
||||
# Permissionless Software Foundation Community Contributing Guide 1.0
|
||||
|
||||
This document describes a very simple process suitable for most projects under
|
||||
the PSF umbrella. It is based on [this Medium article](https://medium.com/the-node-js-collection/healthy-open-source-967fa8be7951) and the [Node.js Community Contribution Guide](https://github.com/nodejs/TSC/blob/master/BasePolicies/CONTRIBUTING.md).
|
||||
Projects are encouraged to adopt this whether they
|
||||
are hosted under the PSF or not.
|
||||
|
||||
The goal of this document is to create a contribution process that:
|
||||
|
||||
* Encourages new contributions.
|
||||
* Encourages contributors to remain involved.
|
||||
* Avoids unnecessary processes and bureaucracy whenever possible.
|
||||
* Creates a transparent decision making process which makes it clear how
|
||||
contributors can be involved in decision making.
|
||||
|
||||
This document is based on much prior art in the Node.js community, io.js,
|
||||
and the Node.js project.
|
||||
|
||||
Additional guidance can be found at the [Permissionless Software Foundation Telegram Channel](https://t.me/permissionless_software).
|
||||
|
||||
## Vocabulary
|
||||
|
||||
* A **Contributor** is any individual creating or commenting on an issue or pull request.
|
||||
* A **Committer** is a subset of contributors who have been given write access to the repository.
|
||||
* A **TC (Technical Committee)** is a group of committers representing the required technical
|
||||
expertise to resolve rare disputes.
|
||||
|
||||
# Logging Issues
|
||||
|
||||
Log an issue for any question or problem you might have. When in doubt, log an issue,
|
||||
any additional policies about what to include will be provided in the responses. The only
|
||||
exception is security disclosures which should be sent privately.
|
||||
|
||||
Committers may direct you to another repository, ask for additional clarifications, and
|
||||
add appropriate metadata before the issue is addressed.
|
||||
|
||||
Please be courteous, respectful, and every participant is expected to follow the
|
||||
project's Code of Conduct.
|
||||
|
||||
# Contributions
|
||||
|
||||
Any change to resources in this repository must be through pull requests. This applies to all changes
|
||||
to documentation, code, binary files, etc. Even long term committers and TC members must use
|
||||
pull requests.
|
||||
|
||||
No pull request can be merged without being reviewed.
|
||||
|
||||
For non-trivial contributions, pull requests should sit for at least 36 hours to ensure that
|
||||
contributors in other timezones have time to review. Consideration should also be given to
|
||||
weekends and other holiday periods to ensure active committers all have reasonable time to
|
||||
become involved in the discussion and review process if they wish.
|
||||
|
||||
The default for each contribution is that it is accepted once no committer has an objection.
|
||||
During review committers may also request that a specific contributor who is most versed in a
|
||||
particular area gives a "LGTM" before the PR can be merged. There is no additional "sign off"
|
||||
process for contributions to land. Once all issues brought by committers are addressed it can
|
||||
be landed by any committer.
|
||||
|
||||
In the case of an objection being raised in a pull request by another committer, all involved
|
||||
committers should seek to arrive at a consensus by way of addressing concerns being expressed
|
||||
by discussion, compromise on the proposed change, or withdrawal of the proposed change.
|
||||
|
||||
If a contribution is controversial and committers cannot agree about how to get it to land
|
||||
or if it should land then it should be escalated to the TC. TC members should regularly
|
||||
discuss pending contributions in order to find a resolution. It is expected that only a
|
||||
small minority of issues be brought to the TC for resolution and that discussion and
|
||||
compromise among committers be the default resolution mechanism.
|
||||
|
||||
# Becoming a Committer
|
||||
|
||||
All contributors who land a non-trivial contribution should be on-boarded in a timely manner,
|
||||
and added as a committer, and be given write access to the repository.
|
||||
|
||||
Committers are expected to follow this policy and continue to send pull requests, go through
|
||||
proper review, and have other committers merge their pull requests.
|
||||
|
||||
# TC Process
|
||||
|
||||
The TC uses a "consensus seeking" process for issues that are escalated to the TC.
|
||||
The group tries to find a resolution that has no open objections among TC members.
|
||||
If a consensus cannot be reached that has no objections then a majority wins vote
|
||||
is called. It is also expected that the majority of decisions made by the TC are via
|
||||
a consensus seeking process and that voting is only used as a last-resort.
|
||||
|
||||
Resolution may involve returning the issue to committers with suggestions on how to
|
||||
move forward towards a consensus. It is not expected that a meeting of the TC
|
||||
will resolve all issues on its agenda during that meeting and may prefer to continue
|
||||
the discussion happening among the committers.
|
||||
|
||||
Members can be added to the TC at any time. Any committer can nominate another committer
|
||||
to the TC and the TC uses its standard consensus seeking process to evaluate whether or
|
||||
not to add this new member. Members who do not participate consistently at the level of
|
||||
a majority of the other members are expected to resign.
|
||||
@@ -0,0 +1,7 @@
|
||||
Copyright 2020 Chris Troutner
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,134 @@
|
||||
# bch-js
|
||||
|
||||
[](https://travis-ci.org/christroutner/bch-js)
|
||||
[](https://www.npmjs.com/package/@chris.troutner/bch-js)
|
||||
[](https://npmjs.org/package/@chris.troutner/bch-js)
|
||||
[](https://github.com/christroutner/bch-js/blob/master/LICENSE.md)
|
||||
|
||||
[bch-js](https://www.npmjs.com/package/@chris.troutner/bch-js) is a JavaScript npm library for creating web and mobile apps for interacting with the Bitcoin Cash (BCH) blockchain. It can be used for free, but requires an account on [FullStack.cash](https://fullstack.cash) for increased rate limits. Find out more from [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
|
||||
|
||||
### Quick Start Videos:
|
||||
Here are two YouTube walk-through videos to help you get started:
|
||||
- [Introduction to bch-js and the bch-js-examples repository](https://youtu.be/GD2i1ZUiyrk)
|
||||
- [Working with the FullStack.cash JWT token](https://youtu.be/GD2i1ZUiyrk)
|
||||
|
||||
### Quick Links
|
||||
- [npm Library](https://www.npmjs.com/package/@chris.troutner/bch-js)
|
||||
- [Documentation](https://bchjs.fullstack.cash/)
|
||||
- [Examples](https://github.com/Permissionless-Software-Foundation/bch-js-examples)
|
||||
- [api.fullstack.cash](https://api.fullstack.cash) - The REST API this library talks to by default.
|
||||
- [FullStack.cash Account](https://fullstack.cash/login) - Get your API key to unlock increased rate limits.
|
||||
- [FullStack.cash](https://fullstack.cash) - cloud-based infrastructure for application
|
||||
developers.
|
||||
- [Permissionless Software Foundation](https://psfoundation.cash) - The organization that maintains this library.
|
||||
|
||||
|
||||
### Quick Notes
|
||||
|
||||
- Install library: `npm install @chris.troutner/bch-js`
|
||||
|
||||
- Instantiate the library in your code:
|
||||
```
|
||||
const BCHJS = require("@chris.troutner/bch-js")
|
||||
let bchjs = new BCHJS()
|
||||
|
||||
// testnet
|
||||
bchjs = new BCHJS({ restURL: 'https://tapi.fullstack.cash/v3/' })
|
||||
```
|
||||
|
||||
This is a fork of the [BITBOX SDK](https://github.com/Bitcoin-com/bitbox-sdk) (which is maintained by Bitcoin.com). This library is intended to be paired with
|
||||
the [bch-api](https://github.com/christroutner/bch-api) REST API.
|
||||
|
||||
If you need a backward-compatible instance of this library, you can use a
|
||||
'shim'. Do it like this:
|
||||
```
|
||||
const BCHJS = require("@chris.troutner/bch-js")
|
||||
const bitbox = BCHJS.BitboxShim({ restURL: 'https://api.fullstack.cash/v3/' })
|
||||
```
|
||||
|
||||
### API Key
|
||||
The [bch-api](https://github.com/christroutner/bch-api) REST API hosted by [FullStack.cash](https://fullstack.cash) uses JWT tokens to pay for increased
|
||||
rate limits when interacting with the back end server. See [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) if you want to understand the system-as-a-whole. The JWT token can be fed to bch-js *implicitly* or *explicitly*.
|
||||
|
||||
- Implicitly: bch-js will detect your JWT token by setting the `BCHJSTOKEN` environment variable.
|
||||
- Explicitly: You can directly feed in the JWT token with the `apiToken` property when instantiating the library. Here is an example:
|
||||
|
||||
```
|
||||
const BCHJS = require("@chris.troutner/bch-js")
|
||||
let bchjs = new BCHJS({
|
||||
restURL: 'https://api.fullstack.cash/v3/',
|
||||
apiToken: 'eyJhbGciO...' // Your JWT token here.
|
||||
})
|
||||
```
|
||||
|
||||
### Gatsby
|
||||
bch-js is included in this [gatsby-ipfs-template](https://github.com/Permissionless-Software-Foundation/gatsby-ipfs-template) for building uncensorable web apps that can interact with the blockchain. When building a Gatsby (or other front-end app that uses Webpack), you'll need to add these lines to your `gatsby-node.js` file, as per [this issue](https://github.com/gatsbyjs/gatsby/issues/564):
|
||||
```
|
||||
exports.onCreateWebpackConfig = ({ actions }) => {
|
||||
actions.setWebpackConfig({
|
||||
node: {
|
||||
fs: 'empty'
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
This is because the new IPFS class in bch-js uses the fs library for uploading files, which is not supported by Gatsby.
|
||||
|
||||
## Features
|
||||
This library sets itself apart from BITBOX with the following features:
|
||||
|
||||
- [ECMAScript 2017 standard JavaScript](https://en.wikipedia.org/wiki/ECMAScript#8th_Edition_-_ECMAScript_2017) used instead of TypeScript. Works
|
||||
natively with node.js v10 or higher.
|
||||
|
||||
- Full SLP tokens support: bch-js has full support for all SLP token functionality, including send, mint, and genesis transactions. It also fully support all aspects of [non-fugible tokans (NFTs)](https://www.youtube.com/watch?v=vvlpYUx6HRs).
|
||||
|
||||
- [Semantic Release](https://github.com/semantic-release/semantic-release) for
|
||||
continuous delivery using semantic versioning.
|
||||
|
||||
- [Greenkeeper](https://greenkeeper.io/) automatic dependency management for
|
||||
automatically maintaining the latest, most secure dependencies.
|
||||
|
||||
- [IPFS uploads](https://ipfs.io) of all files and dependencies, to backup
|
||||
dependencies in case they are ever inaccessible from GitHub or npm.
|
||||
|
||||
|
||||
|
||||
## Documentation:
|
||||
|
||||
Full documentation for this library can be found here:
|
||||
- [Documentation](https://bchjs.fullstack.cash/)
|
||||
|
||||
Original documentation on BITBOX is available at:
|
||||
|
||||
- [General docs](https://developer.bitcoin.com)
|
||||
- [BITBOX Introduction](https://developer.bitcoin.com/bitbox)
|
||||
- [BITBOX API Reference](https://developer.bitcoin.com/bitbox/docs/getting-started)
|
||||
|
||||
|
||||
bch-js uses [APIDOC](http://apidocjs.com/) so that documentation and working code
|
||||
live in the same repository. To generate the documentation:
|
||||
- `npm run docs`
|
||||
- Open the generated `docs/index.html` file in a web browser.
|
||||
|
||||
## Support
|
||||
Have questions? Need help? Join our community support
|
||||
[Telegram channel](https://t.me/bch_js_toolkit)
|
||||
|
||||
## IPFS Releases
|
||||
|
||||
I will periodically publish IPFS releases of this repository, including all
|
||||
dependencies in the `node_modules` folder. This ensures working copies of this
|
||||
repository can be retrieved in case there is any drift in dependency files, or
|
||||
if dependencies are pulled from npm or GitHub.
|
||||
|
||||
- Initial fork on 5/9/2019:
|
||||
- without node_modules folder: QmQFHfbBQdEHfhtiRLbXtX1NcgnfL45hZb7TbQimTXAuzG (4 MB)
|
||||
- with node_modules folder: QmXq9Ds6Qdkg9xbRhcF8pay9KabA6QN2y7bx3wvSqiXifk (107 MB)
|
||||
|
||||
- v1.0.0 - refactored to pure JavaScript:
|
||||
- without node_modules folder: QmNjFsiTZRMAUa9rZpXqZqivv9JLaNicwLSPHjyLB7PVDk (1 MB)
|
||||
- with node_modules folder: Qma9ScApwBtuL7dpdSk7jpBFTxbqRdiR921WjyP75SU7bT (100 MB)
|
||||
|
||||
## License
|
||||
[MIT](LICENSE.md)
|
||||
@@ -0,0 +1,4 @@
|
||||
**Note:** This directory is being deprecated. Examples have been moved to this
|
||||
repository:
|
||||
|
||||
https://github.com/Permissionless-Software-Foundation/bch-js-examples
|
||||
Generated
+12111
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"name": "@chris.troutner/bch-js",
|
||||
"version": "3.0.0",
|
||||
"description": "Bitcoin Cash JavaScript Library based on BITBOX",
|
||||
"author": "Chris Troutner <chris.troutner@gmail.com>",
|
||||
"contributors": [
|
||||
"Gabriel Cardona <gabriel@bitcoin.com>"
|
||||
],
|
||||
"main": "src/bch-js",
|
||||
"scripts": {
|
||||
"test": "nyc mocha --timeout 30000 test/unit/",
|
||||
"test:integration": "mocha --timeout 30000 test/integration/",
|
||||
"test:integration:testnet": "mocha --timeout 30000 test/integration/testnet/",
|
||||
"test:integration:local": "RESTURL=http://localhost:3000/v3/ mocha --timeout 30000 test/integration",
|
||||
"test:integration:testnet:local": "RESTURL=http://localhost:4000/v3/ mocha --timeout 30000 test/integration/testnet",
|
||||
"test:integration:free": "bash test/integration/test-free-tier.sh",
|
||||
"test:integration:free:testnet": "bash test/integration/testnet/test-free-tier.sh",
|
||||
"test:temp": "nyc mocha --timeout 30000 test/unit/ipfs.js",
|
||||
"test:integration:api": "RESTURL=https://api.fullstack.cash/v3/ mocha --timeout 30000 test/integration",
|
||||
"coverage": "nyc report --reporter=text-lcov | coveralls",
|
||||
"coverage:report": "nyc --reporter=html mocha --timeout 25000 test/unit/",
|
||||
"docs": "./node_modules/.bin/apidoc -i src/ -o docs"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/christroutner/bch-js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/christroutner/bch-js.git"
|
||||
},
|
||||
"dependencies": {
|
||||
"@uppy/core": "^1.10.4",
|
||||
"@uppy/tus": "^1.5.12",
|
||||
"apidoc": "^0.17.7",
|
||||
"assert": "^2.0.0",
|
||||
"axios": "^0.19.0",
|
||||
"bc-bip68": "^1.0.5",
|
||||
"bch-wallet-bridge.js": "github:web3bch/bch-wallet-bridge.js#master",
|
||||
"bchaddrjs-slp": "^0.2.5",
|
||||
"bigi": "^1.4.2",
|
||||
"bignumber.js": "^9.0.0",
|
||||
"bip-schnorr": "^0.3.0",
|
||||
"bip21": "Bitcoin-com/bip21",
|
||||
"bip32-utils": "Bitcoin-com/bip32-utils#0.13.1",
|
||||
"bip38": "^2.0.2",
|
||||
"bip39": "^3.0.2",
|
||||
"bip66": "^1.1.5",
|
||||
"bitcoincash-ops": "christroutner/bitcoincash-ops",
|
||||
"bitcoincashjs-lib": "christroutner/bitcoincashjs-lib#master",
|
||||
"bitcoinjs-message": "^2.0.0",
|
||||
"bs58": "^4.0.1",
|
||||
"buffer": "^5.1.0",
|
||||
"cashaddrjs": "^0.3.3",
|
||||
"chalk": "^2.3.0",
|
||||
"clear": "0.1.0",
|
||||
"coininfo": "Bitcoin-com/coininfo",
|
||||
"commander": "^3.0.0",
|
||||
"cp-file": "^7.0.0",
|
||||
"ecurve": "^1.0.6",
|
||||
"figlet": "^1.2.0",
|
||||
"git-clone": "^0.1.0",
|
||||
"ini": "^1.3.5",
|
||||
"mkdirp": "^0.5.1",
|
||||
"node-cmd": "^3.0.0",
|
||||
"node-emoji": "^1.8.1",
|
||||
"qrcode": "^1.4.1",
|
||||
"randombytes": "^2.0.6",
|
||||
"repl.history": "^0.1.4",
|
||||
"safe-buffer": "^5.1.2",
|
||||
"satoshi-bitcoin": "^1.0.4",
|
||||
"slp-mdm": "0.0.6",
|
||||
"slp-parser": "0.0.4",
|
||||
"socket.io": "^2.1.1",
|
||||
"socket.io-client": "^2.1.1",
|
||||
"touch": "^3.1.0",
|
||||
"wif": "^2.0.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"chai": "^4.1.2",
|
||||
"coveralls": "^3.0.2",
|
||||
"eslint": "5.16.0",
|
||||
"eslint-config-prettier": "^6.0.0",
|
||||
"eslint-plugin-node": "^9.1.0",
|
||||
"eslint-plugin-prettier": "^3.1.0",
|
||||
"mocha": "^6.1.4",
|
||||
"nock": "^10.0.6",
|
||||
"node-mocks-http": "^1.7.0",
|
||||
"nyc": "^14.1.0",
|
||||
"prettier": "^1.18.2",
|
||||
"semantic-release": "^15.13.19",
|
||||
"sinon": "^7.3.2"
|
||||
},
|
||||
"apidoc": {
|
||||
"title": "bch-js",
|
||||
"url": "bchjs."
|
||||
}
|
||||
}
|
||||
+739
@@ -0,0 +1,739 @@
|
||||
//const axios = require("axios")
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
const cashaddr = require("cashaddrjs")
|
||||
const coininfo = require("coininfo")
|
||||
|
||||
class Address {
|
||||
constructor(config) {
|
||||
const tmp = {}
|
||||
if (!config || !config.restURL) tmp.restURL = `https://api.bchjs.cash/v3/`
|
||||
else tmp.restURL = config.restURL
|
||||
|
||||
this.restURL = tmp.restURL
|
||||
this.apiToken = tmp.apiToken
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.toLegacyAddress() toLegacyAddress() - Convert to Legacy Address
|
||||
* @apiName toLegacyAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Convert cashaddr to legacy address format
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet w/ prefix
|
||||
* bchjs.Address.toLegacyAddress('bitcoincash:qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
|
||||
* // 1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN
|
||||
*
|
||||
* // mainnet w/ no prefix
|
||||
* bchjs.Address.toLegacyAddress('qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
|
||||
* // 1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN
|
||||
*
|
||||
* // testnet w/ prefix
|
||||
* bchjs.Address.toLegacyAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // mqc1tmwY2368LLGktnePzEyPAsgADxbksi
|
||||
*
|
||||
* // testnet w/ no prefix
|
||||
* bchjs.Address.toLegacyAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // mqc1tmwY2368LLGktnePzEyPAsgADxbksi
|
||||
*/
|
||||
// Translate address from any address format into a specific format.
|
||||
toLegacyAddress(address) {
|
||||
const { prefix, type, hash } = this._decode(address)
|
||||
|
||||
let bitcoincash
|
||||
switch (prefix) {
|
||||
case "bitcoincash":
|
||||
bitcoincash = coininfo.bitcoincash.main
|
||||
break
|
||||
case "bchtest":
|
||||
bitcoincash = coininfo.bitcoincash.test
|
||||
break
|
||||
case "bchreg":
|
||||
bitcoincash = coininfo.bitcoincash.regtest
|
||||
break
|
||||
default:
|
||||
throw `unsupported prefix : ${prefix}`
|
||||
}
|
||||
|
||||
let version
|
||||
switch (type) {
|
||||
case "P2PKH":
|
||||
version = bitcoincash.versions.public
|
||||
break
|
||||
case "P2SH":
|
||||
version = bitcoincash.versions.scripthash
|
||||
break
|
||||
default:
|
||||
throw `unsupported address type : ${type}`
|
||||
}
|
||||
|
||||
const hashBuf = Buffer.from(hash)
|
||||
|
||||
return Bitcoin.address.toBase58Check(hashBuf, version)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.toCashAddress() toCashAddress() - Convert to bitcoincash: format
|
||||
* @apiName toCashAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Convert legacy to cashAddress format
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet
|
||||
* bchjs.Address.toCashAddress('1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN')
|
||||
* // bitcoincash:qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl
|
||||
*
|
||||
* // mainnet no prefix
|
||||
* bchjs.Address.toCashAddress('1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN', false)
|
||||
* // qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl
|
||||
*
|
||||
* // tesnet
|
||||
* bchjs.Address.toCashAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx')
|
||||
* // bchtest:qzq9je6pntpva3wf6scr7mlnycr54sjgeqxgrr9ku3
|
||||
*
|
||||
* // testnet no prefix
|
||||
* bchjs.Address.toCashAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx', false)
|
||||
* // qzq9je6pntpva3wf6scr7mlnycr54sjgeqxgrr9ku3
|
||||
*/
|
||||
toCashAddress(address, prefix = true, regtest = false) {
|
||||
const decoded = this._decode(address)
|
||||
|
||||
let prefixString
|
||||
if (regtest) prefixString = "bchreg"
|
||||
else prefixString = decoded.prefix
|
||||
|
||||
const cashAddress = cashaddr.encode(
|
||||
prefixString,
|
||||
decoded.type,
|
||||
decoded.hash
|
||||
)
|
||||
|
||||
if (prefix) return cashAddress
|
||||
return cashAddress.split(":")[1]
|
||||
}
|
||||
|
||||
// Converts any address format to hash160
|
||||
toHash160(address) {
|
||||
const legacyAddress = this.toLegacyAddress(address)
|
||||
const bytes = Bitcoin.address.fromBase58Check(legacyAddress)
|
||||
return bytes.hash.toString("hex")
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.hash160ToLegacy() hash160ToLegacy() - Convert hash160 to legacy address.
|
||||
* @apiName hash160ToLegacy
|
||||
* @apiGroup Address
|
||||
* @apiDescription Convert hash160 to legacy address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // legacy mainnet p2pkh
|
||||
* bchjs.Address.hash160ToLegacy("573d93b475be4f1925f3b74ed951201b0147eac1")
|
||||
* // 18xHZ8g2feo4ceejGpvzHkvXT79fi2ZdTG
|
||||
*
|
||||
* // legacy mainnet p2sh
|
||||
* bchjs.Address.hash160ToLegacy("7dc85da64d1d93ef01ef62e0221c02f512e3942f", 0x05)
|
||||
* // 3DA6RBcFgLwLTpnF6BRAee8w6a9H6JQLCm
|
||||
*
|
||||
* // legacy testnet p2pkh
|
||||
* bchjs.Address.hash160ToLegacy("155187a3283b08b30519db50bc23bbba9f4b6657", 0x6f)
|
||||
* // mhTg9sgNgvAGfmJs192oUzQWqAXHH5nqLE
|
||||
*/
|
||||
// Converts hash160 to Legacy Address
|
||||
hash160ToLegacy(hash160, network = Bitcoin.networks.bitcoin.pubKeyHash) {
|
||||
const buffer = Buffer.from(hash160, "hex")
|
||||
const legacyAddress = Bitcoin.address.toBase58Check(buffer, network)
|
||||
return legacyAddress
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.hash160ToCash() hash160ToCash() - Convert hash160 to cash address.
|
||||
* @apiName hash160ToCash
|
||||
* @apiGroup Address
|
||||
* @apiDescription Convert hash160 to cash address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* bchjs.Address.hash160ToCash("573d93b475be4f1925f3b74ed951201b0147eac1")
|
||||
* 'bitcoincash:qptnmya5wkly7xf97wm5ak23yqdsz3l2cyj7k9vyyh'
|
||||
* bchjs.Address.hash160ToCash("7dc85da64d1d93ef01ef62e0221c02f512e3942f", 0x05)
|
||||
* 'bitcoincash:pp7ushdxf5we8mcpaa3wqgsuqt639cu59ur5xu5fug'
|
||||
* bchjs.Address.hash160ToCash("155187a3283b08b30519db50bc23bbba9f4b6657", 0x6f)
|
||||
* 'bchtest:qq24rpar9qas3vc9r8d4p0prhwaf7jmx2u22nzt946'
|
||||
*/
|
||||
// Converts hash160 to Cash Address
|
||||
hash160ToCash(
|
||||
hash160,
|
||||
network = Bitcoin.networks.bitcoin.pubKeyHash,
|
||||
regtest = false
|
||||
) {
|
||||
const legacyAddress = this.hash160ToLegacy(hash160, network)
|
||||
return this.toCashAddress(legacyAddress, true, regtest)
|
||||
}
|
||||
|
||||
_decode(address) {
|
||||
try {
|
||||
return this._decodeLegacyAddress(address)
|
||||
} catch (error) {}
|
||||
|
||||
try {
|
||||
return this._decodeCashAddress(address)
|
||||
} catch (error) {}
|
||||
|
||||
try {
|
||||
return this._encodeAddressFromHash160(address)
|
||||
} catch (error) {}
|
||||
|
||||
throw new Error(`Unsupported address format : ${address}`)
|
||||
}
|
||||
|
||||
_decodeLegacyAddress(address) {
|
||||
const { version, hash } = Bitcoin.address.fromBase58Check(address)
|
||||
const info = coininfo.bitcoincash
|
||||
|
||||
switch (version) {
|
||||
case info.main.versions.public:
|
||||
return {
|
||||
prefix: "bitcoincash",
|
||||
type: "P2PKH",
|
||||
hash: hash,
|
||||
format: "legacy"
|
||||
}
|
||||
case info.main.versions.scripthash:
|
||||
return {
|
||||
prefix: "bitcoincash",
|
||||
type: "P2SH",
|
||||
hash: hash,
|
||||
format: "legacy"
|
||||
}
|
||||
case info.test.versions.public:
|
||||
return {
|
||||
prefix: "bchtest",
|
||||
type: "P2PKH",
|
||||
hash: hash,
|
||||
format: "legacy"
|
||||
}
|
||||
case info.test.versions.scripthash:
|
||||
return {
|
||||
prefix: "bchtest",
|
||||
type: "P2SH",
|
||||
hash: hash,
|
||||
format: "legacy"
|
||||
}
|
||||
default:
|
||||
throw new Error(`Invalid format : ${address}`)
|
||||
}
|
||||
}
|
||||
|
||||
_decodeCashAddress(address) {
|
||||
if (address.indexOf(":") !== -1) {
|
||||
const decoded = cashaddr.decode(address)
|
||||
decoded.format = "cashaddr"
|
||||
return decoded
|
||||
}
|
||||
|
||||
const prefixes = ["bitcoincash", "bchtest", "bchreg"]
|
||||
for (let i = 0; i < prefixes.length; ++i) {
|
||||
try {
|
||||
const decoded = cashaddr.decode(`${prefixes[i]}:${address}`)
|
||||
decoded.format = "cashaddr"
|
||||
return decoded
|
||||
} catch (error) {}
|
||||
}
|
||||
|
||||
throw new Error(`Invalid format : ${address}`)
|
||||
}
|
||||
|
||||
_encodeAddressFromHash160(address) {
|
||||
try {
|
||||
return {
|
||||
legacyAddress: this.hash160ToLegacy(address),
|
||||
cashAddress: this.hash160ToCash(address),
|
||||
format: "hash160"
|
||||
}
|
||||
} catch (error) {}
|
||||
|
||||
throw new Error(`Invalid format : ${address}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isLegacyAddress() isLegacyAddress() - Detect if legacy address.
|
||||
* @apiName isLegacyAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if legacy base58check encoded address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr
|
||||
* bchjs.Address.isLegacyAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // w/ no cashaddr prefix
|
||||
* bchjs.Address.isLegacyAddress('qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
|
||||
* // false
|
||||
*
|
||||
* // legacy
|
||||
* bchjs.Address.isLegacyAddress('1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ cashaddr prefix
|
||||
* bchjs.Address.isLegacyAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.Address.isLegacyAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.Address.isLegacyAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // true
|
||||
*/
|
||||
// Test for address format.
|
||||
isLegacyAddress(address) {
|
||||
return this.detectAddressFormat(address) === "legacy"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isCashAddress() isCashAddress() - Detect if cashAddr address.
|
||||
* @apiName isCashAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if cashAddr encoded address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet cashaddr
|
||||
* bchjs.Address.isCashAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet w/ no cashaddr prefix
|
||||
* bchjs.Address.isCashAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet legacy
|
||||
* bchjs.Address.isCashAddress('18HEMuar5ZhXDFep1gEiY1eoPPcBLxfDxj')
|
||||
* // false
|
||||
*
|
||||
* // testnet w/ cashaddr prefix
|
||||
* bchjs.Address.isCashAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.Address.isCashAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // testnet legacy
|
||||
* bchjs.Address.isCashAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // false
|
||||
*/
|
||||
isCashAddress(address) {
|
||||
return this.detectAddressFormat(address) === "cashaddr"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isHash160() isHash160() - Detect if an addess is a hash160.
|
||||
* @apiName isHash160
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if an addess is a hash160.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let hash160Address = '428df38e23fc879a25819427995c3e6355b12d33';
|
||||
* bchjs.Address.isHash160(hash160Address);
|
||||
* // true
|
||||
*
|
||||
* let notHash160Address = 'bitcoincash:pz8a837lttkvjksg0jjmmulqvfkgpqrcdgufy8ns5s';
|
||||
* bchjs.Address.isHash160(notHash160Address);
|
||||
* // false
|
||||
*/
|
||||
isHash160(address) {
|
||||
return this.detectAddressFormat(address) === "hash160"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isMainnetAddress() isMainnetAddress() - Detect if mainnet address.
|
||||
* @apiName isMainnetAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if mainnet address .
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet cashaddr
|
||||
* bchjs.Address.isMainnetAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet cashaddr w/ no prefix
|
||||
* bchjs.Address.isMainnetAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet legacy
|
||||
* bchjs.Address.isMainnetAddress('14krEkSaKoTkbFT9iUCfUYARo4EXA8co6M')
|
||||
* // true
|
||||
*
|
||||
* // testnet cashaddr
|
||||
* bchjs.Address.isMainnetAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.Address.isMainnetAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // testnet legacy
|
||||
* bchjs.Address.isMainnetAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // false
|
||||
*/
|
||||
// Test for address network.
|
||||
isMainnetAddress(address) {
|
||||
if (address[0] === "x") return true
|
||||
else if (address[0] === "t") return false
|
||||
|
||||
return this.detectAddressNetwork(address) === "mainnet"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isTestnetAddress() isTestnetAddress() - Detect if testnet address.
|
||||
* @apiName isTestnetAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if testnet address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr mainnet
|
||||
* bchjs.Address.isTestnetAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* //false
|
||||
*
|
||||
* // w/ no cashaddr prefix
|
||||
* bchjs.Address.isTestnetAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // legacy mainnet
|
||||
* bchjs.Address.isTestnetAddress('14krEkSaKoTkbFT9iUCfUYARo4EXA8co6M')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.Address.isTestnetAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.Address.isTestnetAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // testnet legacy
|
||||
* bchjs.Address.isTestnetAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // true
|
||||
*/
|
||||
isTestnetAddress(address) {
|
||||
if (address[0] === "x") return false
|
||||
else if (address[0] === "t") return true
|
||||
|
||||
return this.detectAddressNetwork(address) === "testnet"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isRegTestAddress() isRegTestAddress() - Detect if regtest address.
|
||||
* @apiName isRegTestAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if regtest address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // regtest
|
||||
* bchjs.Address.isRegTestAddress('bchreg:qzq9je6pntpva3wf6scr7mlnycr54sjgequ54zx9lh')
|
||||
* // true
|
||||
*
|
||||
* // regtest w/ no prefix
|
||||
* bchjs.Address.isRegTestAddress('qzq9je6pntpva3wf6scr7mlnycr54sjgequ54zx9lh')
|
||||
* // true
|
||||
*
|
||||
* // cashaddr mainnet
|
||||
* bchjs.Address.isRegTestAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* //false
|
||||
*
|
||||
* // w/ no cashaddr prefix
|
||||
* bchjs.Address.isRegTestAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // legacy mainnet
|
||||
* bchjs.Address.isRegTestAddress('14krEkSaKoTkbFT9iUCfUYARo4EXA8co6M')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.Address.isRegTestAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.Address.isRegTestAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*/
|
||||
isRegTestAddress(address) {
|
||||
return this.detectAddressNetwork(address) === "regtest"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isP2PKHAddress() isP2PKHAddress() - Detect if p2pkh address.
|
||||
* @apiName isP2PKHAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if p2pkh address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr
|
||||
* bchjs.Address.isP2PKHAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // w/ no cashaddr prefix
|
||||
* bchjs.Address.isP2PKHAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // legacy
|
||||
* bchjs.Address.isP2PKHAddress('14krEkSaKoTkbFT9iUCfUYARo4EXA8co6M')
|
||||
* // true
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.Address.isP2PKHAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.Address.isP2PKHAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.Address.isP2PKHAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // true
|
||||
*/
|
||||
|
||||
// Test for address type.
|
||||
isP2PKHAddress(address) {
|
||||
return this.detectAddressType(address) === "p2pkh"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.isP2SHAddress() isP2SHAddress() - Detect if p2sh address.
|
||||
* @apiName isP2SHAddress
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect if p2sh address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr
|
||||
* bchjs.Address.isP2SHAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr w/ no prefix
|
||||
* bchjs.Address.isP2SHAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // legacy
|
||||
* bchjs.Address.isP2SHAddress('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.Address.isP2SHAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.Address.isP2SHAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.Address.isP2SHAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // false
|
||||
*/
|
||||
|
||||
isP2SHAddress(address) {
|
||||
return this.detectAddressType(address) === "p2sh"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.detectAddressFormat() detectAddressFormat() - Detect address format.
|
||||
* @apiName detectAddressFormat
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect address format.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr
|
||||
* bchjs.Address.detectAddressFormat('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // cashaddr
|
||||
*
|
||||
* // cashaddr w/ no prefix
|
||||
* bchjs.Address.detectAddressFormat('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // cashaddr
|
||||
*
|
||||
* // legacy
|
||||
* bchjs.Address.detectAddressFormat('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74')
|
||||
* // legacy
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.Address.detectAddressFormat('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // cashaddr
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.Address.detectAddressFormat('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // cashaddr
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.Address.detectAddressFormat('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // legacy
|
||||
*/
|
||||
// Detect address format.
|
||||
detectAddressFormat(address) {
|
||||
const decoded = this._decode(address)
|
||||
|
||||
return decoded.format
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.detectAddressNetwork() detectAddressNetwork() - Detect address network.
|
||||
* @apiName detectAddressNetwork
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect address network.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr
|
||||
* bchjs.Address.detectAddressNetwork('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // mainnet
|
||||
*
|
||||
* // cashaddr w/ no prefix
|
||||
* bchjs.Address.detectAddressNetwork('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // mainnet
|
||||
*
|
||||
* // legacy
|
||||
* bchjs.Address.detectAddressNetwork('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74')
|
||||
* // mainnet
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.Address.detectAddressNetwork('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // testnet
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.Address.detectAddressNetwork('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // testnet
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.Address.detectAddressNetwork('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // testnet
|
||||
*/
|
||||
// Detect address network.
|
||||
detectAddressNetwork(address) {
|
||||
if (address[0] === "x") return "mainnet"
|
||||
else if (address[0] === "t") return "testnet"
|
||||
|
||||
const decoded = this._decode(address)
|
||||
|
||||
switch (decoded.prefix) {
|
||||
case "bitcoincash":
|
||||
return "mainnet"
|
||||
case "bchtest":
|
||||
return "testnet"
|
||||
case "bchreg":
|
||||
return "regtest"
|
||||
default:
|
||||
throw new Error(`Invalid prefix : ${decoded.prefix}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.detectAddressType() detectAddressType() - Detect address type.
|
||||
* @apiName detectAddressType
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect address type.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr
|
||||
* bchjs.Address.detectAddressType('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s');
|
||||
* // p2pkh
|
||||
*
|
||||
* // cashaddr w/ no prefix
|
||||
* bchjs.Address.detectAddressType('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s');
|
||||
* // p2pkh
|
||||
*
|
||||
* // legacy
|
||||
* bchjs.Address.detectAddressType('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74');
|
||||
* // p2pkh
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.Address.detectAddressType('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy');
|
||||
* // p2pkh
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.Address.detectAddressType('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy');
|
||||
* // p2pkh
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.Address.detectAddressType('mqc1tmwY2368LLGktnePzEyPAsgADxbksi');
|
||||
* // p2pkh
|
||||
*/
|
||||
// Detect address type.
|
||||
detectAddressType(address) {
|
||||
const decoded = this._decode(address)
|
||||
|
||||
return decoded.type.toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.fromXPub() fromXPub() - Generates an address (xpub).
|
||||
* @apiName fromXPub
|
||||
* @apiGroup Address
|
||||
* @apiDescription Generates an address for an extended public key (xpub).
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // generate 5 mainnet external change addresses for xpub6DTNmB7gWa8RtQAfmy8wSDikM5mky4fhsnqQd9AqoCaLcekqNgRZW5JCSXwXkLDkABHTD1qx7kqrbGzT6xBGfAvCJSj2rwvKWP8eZBR2EVA
|
||||
* let xpub = 'xpub6DTNmB7gWa8RtQAfmy8wSDikM5mky4fhsnqQd9AqoCaLcekqNgRZW5JCSXwXkLDkABHTD1qx7kqrbGzT6xBGfAvCJSj2rwvKWP8eZBR2EVA';
|
||||
* for(let i = 0; i <= 4; i++) {
|
||||
* console.log(bchjs.Address.fromXPub(xpub, "0/" + i))
|
||||
* }
|
||||
* // bitcoincash:qptnmya5wkly7xf97wm5ak23yqdsz3l2cyj7k9vyyh
|
||||
* // bitcoincash:qrr2suh9yjsrkl2qp3p967uhfg6u0r6xxsn9h5vuvr
|
||||
* // bitcoincash:qpkfg4kck99wksyss6nvaqtafeahfnyrpsj0ed372t
|
||||
* // bitcoincash:qppgmuuwy07g0x39sx2z0x2u8e34tvfdxvy0c2jvx7
|
||||
* // bitcoincash:qryj8x4s7vfsc864jm0xaak9qfe8qgk245y9ska57l
|
||||
*
|
||||
* // generate 5 testnet external change addresses for tpubDCrnMSKwDMAbxg82yqDt97peMvftCXk3EfBb9WgZh27mPbHGkysU3TW7qX5AwydmnVQfaGeNhUR6okQ3dS5AJTP9gEP7jk2Wcj6Xntc6gNh
|
||||
* let xpub = 'tpubDCrnMSKwDMAbxg82yqDt97peMvftCXk3EfBb9WgZh27mPbHGkysU3TW7qX5AwydmnVQfaGeNhUR6okQ3dS5AJTP9gEP7jk2Wcj6Xntc6gNh';
|
||||
* for(let i = 0; i <= 4; i++) {
|
||||
* console.log(bchjs.Address.fromXPub(xpub, "0/" + i))
|
||||
* }
|
||||
* // bchtest:qrth8470sc9scek9u0jj2d0349t62gxzdstw2jukl8
|
||||
* // bchtest:qpm56zc5re0nhms96r7p985aajthp0vxvg6e4ux3kc
|
||||
* // bchtest:qqtu3tf6yyd73ejhk3a2ylqynpl3mzzhwuzt299jfd
|
||||
* // bchtest:qzd7dvlnfukggjqsf5ju0qqwwltakfumjsck33js6m
|
||||
* // bchtest:qq322ataqeas4n0pdn4gz2sdereh5ae43ylk4qdvus
|
||||
*/
|
||||
fromXPub(xpub, path = "0/0") {
|
||||
const HDNode = Bitcoin.HDNode.fromBase58(
|
||||
xpub,
|
||||
Bitcoin.networks[this.detectAddressNetwork(xpub)]
|
||||
)
|
||||
const address = HDNode.derivePath(path)
|
||||
return this.toCashAddress(address.getAddress())
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Address.fromOutputScript() fromOutputScript() - Detect an addess from an OutputScript..
|
||||
* @apiName fromOutputScript
|
||||
* @apiGroup Address
|
||||
* @apiDescription Detect an addess from an OutputScript..
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* const script = bchjs.Script.encode([
|
||||
* Buffer.from("BOX", "ascii"),
|
||||
* bchjs.Script.opcodes.OP_CAT,
|
||||
* Buffer.from("BITBOX", "ascii"),
|
||||
* bchjs.Script.opcodes.OP_EQUAL
|
||||
* ]);
|
||||
* const p2sh_hash160 = bchjs.Crypto.hash160(script);
|
||||
* const scriptPubKey = bchjs.Script.scriptHash.output.encode(p2sh_hash160);
|
||||
*
|
||||
* // mainnet address from output script
|
||||
* bchjs.Address.fromOutputScript(scriptPubKey);
|
||||
* // bitcoincash:pz0qcslrqn7hr44hsszwl4lw5r6udkg6zqncnufkrl
|
||||
*
|
||||
* // testnet address from output script
|
||||
* bchjs.Address.fromOutputScript(scriptPubKey, 'testnet');
|
||||
* // bchtest:pz0qcslrqn7hr44hsszwl4lw5r6udkg6zqh2hmtpyr
|
||||
*/
|
||||
fromOutputScript(scriptPubKey, network = "mainnet") {
|
||||
let netParam
|
||||
if (network !== "bitcoincash" && network !== "mainnet")
|
||||
netParam = Bitcoin.networks.testnet
|
||||
|
||||
const regtest = network === "bchreg"
|
||||
|
||||
return this.toCashAddress(
|
||||
Bitcoin.address.fromOutputScript(scriptPubKey, netParam),
|
||||
true,
|
||||
regtest
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Address
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
This is the primary library file for bch-js. This file combines all the other
|
||||
libraries in order to create the BCHJS class.
|
||||
|
||||
The primary server used has switched to fullstack.cash. Go there to sign up
|
||||
for an account that gives you increased rate limits.
|
||||
*/
|
||||
|
||||
// bch-api mainnet.
|
||||
// const DEFAULT_REST_API = "https://api.bchjs.cash/v3/"
|
||||
const DEFAULT_REST_API = "https://api.fullstack.cash/v3/"
|
||||
|
||||
// local deps
|
||||
const BitcoinCash = require("./bitcoincash")
|
||||
const Crypto = require("./crypto")
|
||||
const Util = require("./util")
|
||||
const Blockchain = require("./blockchain")
|
||||
const Control = require("./control")
|
||||
const Generating = require("./generating")
|
||||
const Mining = require("./mining")
|
||||
const RawTransactions = require("./raw-transactions")
|
||||
const Mnemonic = require("./mnemonic")
|
||||
const Address = require("./address")
|
||||
const HDNode = require("./hdnode")
|
||||
const TransactionBuilder = require("./transaction-builder")
|
||||
const ECPair = require("./ecpair")
|
||||
const Script = require("./script")
|
||||
const Price = require("./price")
|
||||
const Socket = require("./socket")
|
||||
const Wallet = require("./wallet")
|
||||
const Schnorr = require("./schnorr")
|
||||
const SLP = require("./slp/slp")
|
||||
const IPFS = require("./ipfs")
|
||||
const Encryption = require("./encryption")
|
||||
|
||||
// Indexers
|
||||
const Blockbook = require("./blockbook")
|
||||
const OpenBazaar = require("./openbazaar")
|
||||
const Ninsight = require("./ninsight")
|
||||
const Electrumx = require("./electrumx")
|
||||
|
||||
class BCHJS {
|
||||
constructor(config) {
|
||||
// Try to retrieve the REST API URL from different sources.
|
||||
if (config && config.restURL && config.restURL !== "")
|
||||
this.restURL = config.restURL
|
||||
else if (process.env.RESTURL && process.env.RESTURL !== "")
|
||||
this.restURL = process.env.RESTURL
|
||||
else this.restURL = DEFAULT_REST_API
|
||||
|
||||
// Retrieve the apiToken
|
||||
this.apiToken = "" // default value.
|
||||
if (config && config.apiToken && config.apiToken !== "")
|
||||
this.apiToken = config.apiToken
|
||||
else if (process.env.BCHJSTOKEN && process.env.BCHJSTOKEN !== "")
|
||||
this.apiToken = process.env.BCHJSTOKEN
|
||||
|
||||
const libConfig = {
|
||||
restURL: this.restURL,
|
||||
apiToken: this.apiToken
|
||||
}
|
||||
|
||||
// console.log(`apiToken: ${this.apiToken}`)
|
||||
|
||||
// Populate Blockbook endpoints.
|
||||
this.Blockbook = new Blockbook(libConfig)
|
||||
|
||||
// Populate OpenBazaar endpoints
|
||||
this.OpenBazaar = new OpenBazaar(libConfig)
|
||||
|
||||
// Bitcoin.com Ninsight indexer
|
||||
this.Ninsight = new Ninsight()
|
||||
|
||||
// ElectrumX indexer
|
||||
this.Electrumx = new Electrumx(libConfig)
|
||||
|
||||
// Populate Full Node
|
||||
this.Control = new Control(libConfig)
|
||||
this.Mining = new Mining(libConfig)
|
||||
this.RawTransactions = new RawTransactions(libConfig)
|
||||
|
||||
// Populate utility functions
|
||||
this.Address = new Address(libConfig)
|
||||
this.BitcoinCash = new BitcoinCash(this.Address)
|
||||
this.Blockchain = new Blockchain(libConfig)
|
||||
this.Crypto = Crypto
|
||||
this.ECPair = ECPair
|
||||
this.ECPair.setAddress(this.Address)
|
||||
this.encryption = new Encryption(libConfig)
|
||||
this.Generating = new Generating(libConfig)
|
||||
this.HDNode = new HDNode(this.Address)
|
||||
this.Mnemonic = new Mnemonic(this.Address)
|
||||
this.Price = new Price()
|
||||
this.Script = new Script()
|
||||
this.TransactionBuilder = TransactionBuilder
|
||||
this.TransactionBuilder.setAddress(this.Address)
|
||||
this.Util = new Util(libConfig)
|
||||
this.Socket = Socket
|
||||
this.Wallet = Wallet
|
||||
this.Schnorr = new Schnorr(libConfig)
|
||||
|
||||
this.SLP = new SLP(libConfig)
|
||||
this.SLP.HDNode = this.HDNode
|
||||
|
||||
this.IPFS = new IPFS()
|
||||
}
|
||||
|
||||
static BitboxShim() {
|
||||
return BitboxShim
|
||||
}
|
||||
}
|
||||
|
||||
// Creat a shim so that all the endpoints match BITBOX SDK and this library
|
||||
// can be used as a drop-in replacement for BITBOX.
|
||||
class BitboxShim {
|
||||
constructor(config) {
|
||||
// Try to retrieve the REST API URL from different sources.
|
||||
if (config && config.restURL && config.restURL !== "")
|
||||
this.restURL = config.restURL
|
||||
else if (process.env.RESTURL && process.env.RESTURL !== "")
|
||||
this.restURL = process.env.RESTURL
|
||||
else this.restURL = DEFAULT_REST_API
|
||||
|
||||
// Retrieve the apiToken
|
||||
this.apiToken = "" // default value.
|
||||
if (config && config.apiToken && config.apiToken !== "")
|
||||
this.apiToken = config.apiToken
|
||||
else if (process.env.BCHJSTOKEN && process.env.BCHJSTOKEN !== "")
|
||||
this.apiToken = process.env.BCHJSTOKEN
|
||||
|
||||
const libConfig = {
|
||||
restURL: this.restURL,
|
||||
apiToken: this.apiToken
|
||||
}
|
||||
|
||||
// Populate utility functions
|
||||
this.Address = new Address(libConfig)
|
||||
this.BitcoinCash = new BitcoinCash(this.Address)
|
||||
this.Blockchain = new Blockchain(libConfig)
|
||||
this.Crypto = Crypto
|
||||
this.ECPair = ECPair
|
||||
this.ECPair.setAddress(this.Address)
|
||||
this.Generating = new Generating(libConfig)
|
||||
this.HDNode = new HDNode(this.Address)
|
||||
this.Mnemonic = new Mnemonic(this.Address)
|
||||
this.Price = new Price()
|
||||
this.Script = new Script()
|
||||
this.TransactionBuilder = TransactionBuilder
|
||||
this.TransactionBuilder.setAddress(this.Address)
|
||||
this.Util = new Util(libConfig)
|
||||
this.Socket = Socket
|
||||
this.Wallet = Wallet
|
||||
this.Schnorr = new Schnorr(libConfig)
|
||||
|
||||
// Populate the SLP endpoints.
|
||||
this.SLP = new SLP(libConfig)
|
||||
this.Address = this.SLP.Address
|
||||
|
||||
this.ECPair.toSLPAddress = this.SLP.ECPair.toSLPAddress
|
||||
|
||||
this.Util.list = this.SLP.Utils.list
|
||||
this.Util.balancesForAddress = this.SLP.Utils.balancesForAddress
|
||||
this.Util.balancesForToken = this.SLP.Utils.balancesForToken
|
||||
this.Util.balance = this.SLP.Utils.balance
|
||||
this.Util.validateTxid = this.SLP.Utils.validateTxid
|
||||
this.Util.tokenStats = this.SLP.Utils.tokenStats
|
||||
this.Util.transactions = this.SLP.Utils.transactions
|
||||
this.Util.burnTotal = this.SLP.Utils.burnTotal
|
||||
this.Util.decodeOpReturn = this.SLP.Utils.decodeOpReturn
|
||||
this.Util.isTokenUtxo = this.SLP.Utils.isTokenUtxo
|
||||
this.Util.tokenUtxoDetails = this.SLP.Utils.tokenUtxoDetails
|
||||
this.Util.txDetails = this.SLP.Utils.txDetails
|
||||
|
||||
// Populate Full Node
|
||||
this.Control = new Control(libConfig)
|
||||
this.Mining = new Mining(libConfig)
|
||||
this.RawTransactions = new RawTransactions(libConfig)
|
||||
|
||||
// Populate Blockbook endpoints.
|
||||
this.Blockbook = new Blockbook(libConfig)
|
||||
|
||||
// Populate OpenBazaar endpoints
|
||||
this.OpenBazaar = new OpenBazaar(libConfig)
|
||||
|
||||
// Bitcoin.com Ninsight indexer
|
||||
this.Ninsight = new Ninsight()
|
||||
this.Electrumx = new Electrumx(libConfig)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BCHJS
|
||||
@@ -0,0 +1,522 @@
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
const sb = require("satoshi-bitcoin")
|
||||
const bitcoinMessage = require("bitcoinjs-message")
|
||||
const bs58 = require("bs58")
|
||||
const bip21 = require("bip21")
|
||||
const coininfo = require("coininfo")
|
||||
const bip38 = require("bip38")
|
||||
const wif = require("wif")
|
||||
|
||||
const Buffer = require("safe-buffer").Buffer
|
||||
|
||||
class BitcoinCash {
|
||||
constructor(address) {
|
||||
this._address = address
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.toSatoshi() toSatoshi() - Converting Bitcoin Cash units to satoshi units.
|
||||
* @apiName toSatoshi
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Converting Bitcoin Cash units to satoshi units.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // convert 9 $BCH to satoshis
|
||||
* bchjs.BitcoinCash.toSatoshi(9)
|
||||
* // 900000000
|
||||
*
|
||||
* // convert 1 $BCH to satoshis
|
||||
* bchjs.BitcoinCash.toSatoshi(1)
|
||||
* // 100000000
|
||||
*
|
||||
* // convert 100 $BCH to satoshis
|
||||
* bchjs.BitcoinCash.toSatoshi(100)
|
||||
* // 10000000000
|
||||
*
|
||||
* // convert 42 $BCH to satoshis
|
||||
* bchjs.BitcoinCash.toSatoshi(42)
|
||||
* // 4200000000
|
||||
*
|
||||
* // convert 507 $BCH to satoshis
|
||||
* bchjs.BitcoinCash.toSatoshi(507)
|
||||
* // 50700000000
|
||||
*/
|
||||
// Translate coins to satoshi value
|
||||
toSatoshi(coins) {
|
||||
return sb.toSatoshi(coins)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.toBitcoinCash() toBitcoinCash() - Converting satoshi units to Bitcoin Cash units.
|
||||
* @apiName toBitcoinCash
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Converting satoshi units to Bitcoin Cash units.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // convert 900000000 satoshis to $BCH
|
||||
* bchjs.BitcoinCash.toBitcoinCash(900000000)
|
||||
* // 9
|
||||
*
|
||||
* // convert 100000000 satoshis to $BCH
|
||||
* bchjs.BitcoinCash.toBitcoinCash(100000000)
|
||||
* // 1
|
||||
*
|
||||
* // convert 10000000000 satoshis to $BCH
|
||||
* bchjs.BitcoinCash.toBitcoinCash(10000000000)
|
||||
* // 100
|
||||
*
|
||||
* // convert 4200000000 satoshis to $BCH
|
||||
* bchjs.BitcoinCash.toBitcoinCash(4200000000)
|
||||
* // 42
|
||||
*
|
||||
* // convert 50700000000 satoshis to $BCH
|
||||
* bchjs.BitcoinCash.toBitcoinCash(50700000000)
|
||||
* // 507
|
||||
*/
|
||||
// Translate satoshi to coin value
|
||||
toBitcoinCash(satoshis) {
|
||||
return sb.toBitcoin(satoshis)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.toBits() toBits() - Converting satoshi units to Bits denomination.
|
||||
* @apiName toBits
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Converting satoshi units to Bits denomination.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // convert 4242323400 satoshis to 42423.234 bits
|
||||
* bchjs.BitcoinCash.toBits(4242323400)
|
||||
* // 42423.234
|
||||
* // convert 100000000 satoshis to 1000 bits
|
||||
* bchjs.BitcoinCash.toBits(100000000)
|
||||
* // 1000
|
||||
* // convert 314000000 satoshis to 3140 bits
|
||||
* bchjs.BitcoinCash.toBits(314000000)
|
||||
* // 3140
|
||||
* // convert 987600000000 satoshis to 9876000 bits
|
||||
* bchjs.BitcoinCash.toBits(987600000000)
|
||||
* // 9876000
|
||||
* // convert 12300 satoshis to 0.123 bits
|
||||
* bchjs.BitcoinCash.toBits(12300)
|
||||
* // 0.123
|
||||
*/
|
||||
// Translate satoshi to bits denomination
|
||||
toBits(satoshis) {
|
||||
return parseFloat(satoshis) / 100
|
||||
}
|
||||
|
||||
// Translate satoshi to bits denomination
|
||||
// TODO remove in 2.0
|
||||
satsToBits(satoshis) {
|
||||
return parseFloat(satoshis) / 100
|
||||
}
|
||||
|
||||
// Translate bits to satoshi denomination
|
||||
// TODO remove in 2.0
|
||||
// fromBits(bits) {
|
||||
// return this.toInteger(bits * 100);
|
||||
// }
|
||||
//
|
||||
// // Translate bits to satoshi denomination
|
||||
// satsFromBits(bits) {
|
||||
// return this.toInteger(bits * 100);
|
||||
// }
|
||||
//
|
||||
// toInteger(number){
|
||||
// return Math.round( // round to nearest integer
|
||||
// Number(number) // type cast your input
|
||||
// );
|
||||
// }
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.signMessageWithPrivKey() signMessageWithPrivKey() - Sign message with private key.
|
||||
* @apiName signMessageWithPrivKey
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Sign message with private key.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* bchjs.BitcoinCash.signMessageWithPrivKey(
|
||||
* 'KxtpRDUJDiutLaTV8Vuavhb6h7zq9YV9ZKA3dU79PCgYmNVmkkvS',
|
||||
* 'EARTH'
|
||||
* )
|
||||
* // IIYVhlo2Z6TWFjYX1+YM+7vQKz0m+zYdSe4eYpFLuAQDEZXqll7lZC8Au22VI2LLP5x+IerZckVk3QQPsA3e8/8=
|
||||
*/
|
||||
// sign message
|
||||
signMessageWithPrivKey(privateKeyWIF, message) {
|
||||
const network = privateKeyWIF.charAt(0) === "c" ? "testnet" : "mainnet"
|
||||
let bitcoincash
|
||||
if (network === "mainnet") bitcoincash = coininfo.bitcoincash.main
|
||||
else bitcoincash = coininfo.bitcoincash.test
|
||||
|
||||
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
|
||||
const keyPair = Bitcoin.ECPair.fromWIF(
|
||||
privateKeyWIF,
|
||||
bitcoincashBitcoinJSLib
|
||||
)
|
||||
const privateKey = keyPair.d.toBuffer(32)
|
||||
return bitcoinMessage
|
||||
.sign(message, privateKey, keyPair.compressed)
|
||||
.toString("base64")
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.verifyMessage() verifyMessage() - Verify message.
|
||||
* @apiName verifyMessage
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Verify message.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* bchjs.BitcoinCash.verifyMessage(
|
||||
* 'bitcoincash:qp2zvw3zpk5xx43w4tve7mtekd9kaxwj4uenq9eupv',
|
||||
* 'IIYVhlo2Z6TWFjYX1+YM+7vQKz0m+zYdSe4eYpFLuAQDEZXqll7lZC8Au22VI2LLP5x+IerZckVk3QQPsA3e8/8=',
|
||||
* 'EARTH'
|
||||
* )
|
||||
* // true
|
||||
*/
|
||||
// verify message
|
||||
verifyMessage(address, signature, message) {
|
||||
return bitcoinMessage.verify(
|
||||
message,
|
||||
this._address.toLegacyAddress(address),
|
||||
signature
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.encodeBase58Check() encodeBase58Check() - Encodes hex string as base58Check.
|
||||
* @apiName encodeBase58Check
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Encodes hex string as base58Check.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // encode 0079bd35d306f648350818470c9f18903df6e06902a026f2a7 as base58check
|
||||
* let hex = '0079bd35d306f648350818470c9f18903df6e06902a026f2a7'
|
||||
* bchjs.BitcoinCash.encodeBase58Check(hex)
|
||||
* // 1C6hRmfzvWst5WA7bFRCVAqHt5gE2g7Qar
|
||||
*
|
||||
* // encode 006da742680accf2282df5fade8e9b7a01a517e779289b52cc as base58check
|
||||
* let hex = '006da742680accf2282df5fade8e9b7a01a517e779289b52cc'
|
||||
* bchjs.BitcoinCash.encodeBase58Check(hex)
|
||||
* // 1Azo2JBz2JswboeY9xSMcp14BAfhjnD9SK
|
||||
*
|
||||
* // encode 00c68a6a07ccdaf1669cfd8d244d80ff36b713551c6208f672 as base58check
|
||||
* let hex = '00c68a6a07ccdaf1669cfd8d244d80ff36b713551c6208f672'
|
||||
* bchjs.BitcoinCash.encodeBase58Check(hex)
|
||||
* // 1K6ncAmMEyQrKUYosZRD9swyZNXECu2aKs
|
||||
*
|
||||
* // encode 00d0a6b5e3dd43d0fb895b3b3df565bb8266c5ab00a25dbeb5 as base58check
|
||||
* let hex = '00d0a6b5e3dd43d0fb895b3b3df565bb8266c5ab00a25dbeb5'
|
||||
* bchjs.BitcoinCash.encodeBase58Check(hex)
|
||||
* // 1L2FG9hH3bwchhxHaCs5cg1QNbhmbaeAs6
|
||||
*
|
||||
* // encode 00db04c2e6f104997cb04c956bf25da6078e559d303127f08b as base58check
|
||||
* let hex = '00db04c2e6f104997cb04c956bf25da6078e559d303127f08b'
|
||||
* bchjs.BitcoinCash.encodeBase58Check(hex)
|
||||
* // 1Ly4gqPddveYHMNkfjoXHanVszXpD3duKg
|
||||
*/
|
||||
// encode base58Check
|
||||
encodeBase58Check(hex) {
|
||||
return bs58.encode(Buffer.from(hex, "hex"))
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.decodeBase58Check() decodeBase58Check() - Decodes base58Check encoded string to hex.
|
||||
* @apiName decodeBase58Check
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Decodes base58Check encoded string to hex.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // decode 1C6hRmfzvWst5WA7bFRCVAqHt5gE2g7Qar to hex
|
||||
* let base58check = '1C6hRmfzvWst5WA7bFRCVAqHt5gE2g7Qar'
|
||||
* bchjs.BitcoinCash.decodeBase58Check(base58check)
|
||||
* // 0079bd35d306f648350818470c9f18903df6e06902a026f2a7
|
||||
*
|
||||
* // decode 1Azo2JBz2JswboeY9xSMcp14BAfhjnD9SK to hex
|
||||
* let base58check = '1Azo2JBz2JswboeY9xSMcp14BAfhjnD9SK'
|
||||
* bchjs.BitcoinCash.decodeBase58Check(base58check)
|
||||
* // 006da742680accf2282df5fade8e9b7a01a517e779289b52cc
|
||||
*
|
||||
* // decode 1K6ncAmMEyQrKUYosZRD9swyZNXECu2aKs to hex
|
||||
* let base58check = '1K6ncAmMEyQrKUYosZRD9swyZNXECu2aKs'
|
||||
* bchjs.BitcoinCash.decodeBase58Check(base58check)
|
||||
* // 00c68a6a07ccdaf1669cfd8d244d80ff36b713551c6208f672
|
||||
*
|
||||
* // decode 1L2FG9hH3bwchhxHaCs5cg1QNbhmbaeAs6 to hex
|
||||
* let base58check = '1L2FG9hH3bwchhxHaCs5cg1QNbhmbaeAs6'
|
||||
* bchjs.BitcoinCash.decodeBase58Check(base58check)
|
||||
* // 00d0a6b5e3dd43d0fb895b3b3df565bb8266c5ab00a25dbeb5
|
||||
*
|
||||
* // decode 1Ly4gqPddveYHMNkfjoXHanVszXpD3duKg to hex
|
||||
* let base58check = '1Ly4gqPddveYHMNkfjoXHanVszXpD3duKg'
|
||||
* bchjs.BitcoinCash.decodeBase58Check(base58check)
|
||||
* // 00db04c2e6f104997cb04c956bf25da6078e559d303127f08b
|
||||
*/
|
||||
// decode base58Check
|
||||
decodeBase58Check(address) {
|
||||
return bs58.decode(address).toString("hex")
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.encodeBIP21() encodeBIP21() - Encodes address and options as BIP21 uri.
|
||||
* @apiName encodeBIP21
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Encodes address and options as BIP21 uri.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let address = 'bitcoincash:qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqrt2qkz5s'
|
||||
* let options = {
|
||||
* amount: 1,
|
||||
* label: '#BCHForEveryone',
|
||||
* }
|
||||
* bchjs.BitcoinCash.encodeBIP21(address, options)
|
||||
* // bitcoincash:qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqrt2qkz5s?amount=1&label=%23BCHForEveryone
|
||||
*
|
||||
* let address = '1C6hRmfzvWst5WA7bFRCVAqHt5gE2g7Qar'
|
||||
* let options = {
|
||||
* amount: 12.5,
|
||||
* label: 'coinbase donation',
|
||||
* message: "and ya don't stop",
|
||||
* }
|
||||
* bchjs.BitcoinCash.encodeBIP21(address, options)
|
||||
* // bitcoincash:qpum6dwnqmmysdggrprse8ccjq7ldcrfqgmmtgcmny?amount=12.5&label=coinbase%20donation&message=and%20ya%20don%27t%20stop
|
||||
*
|
||||
* let address = 'qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qw0e54u03'
|
||||
* let options = {
|
||||
* amount: 42,
|
||||
* label: 'no prefix',
|
||||
* }
|
||||
* bchjs.BitcoinCash.encodeBIP21(address, options)
|
||||
* // bitcoincash:qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qw0e54u03?amount=42&label=no%20prefix
|
||||
*/
|
||||
// encode bip21 url
|
||||
encodeBIP21(address, options, regtest = false) {
|
||||
return bip21.encode(
|
||||
this._address.toCashAddress(address, true, regtest),
|
||||
options
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.decodeBIP21() decodeBIP21() - Decodes BIP21 uri.
|
||||
* @apiName decodeBIP21
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Decodes BIP21 uri.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let bip21 =
|
||||
* 'bitcoincash:qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqrt2qkz5s?amount=1&label=%23BCHForEveryone'
|
||||
* bchjs.BitcoinCash.decodeBIP21(bip21)
|
||||
* // { address: 'qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqrt2qkz5s', options: { amount: 1, label: '#BCHForEveryone' } }
|
||||
*
|
||||
* let bip21 =
|
||||
* 'bitcoincash:qpum6dwnqmmysdggrprse8ccjq7ldcrfqgmmtgcmny?amount=12.5&label=coinbase%20donation&message=and%20ya%20don%27t%20stop'
|
||||
* bchjs.BitcoinCash.decodeBIP21(bip21)
|
||||
* // { address: 'qpum6dwnqmmysdggrprse8ccjq7ldcrfqgmmtgcmny',
|
||||
* // options:
|
||||
* // { amount: 12.5,
|
||||
* // label: 'coinbase donation',
|
||||
* // message: 'and ya don\'t stop'
|
||||
* // }
|
||||
* // }
|
||||
*
|
||||
* let bip21 =
|
||||
* 'bitcoincash:qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qw0e54u03?amount=42&label=no%20prefix'
|
||||
* bchjs.BitcoinCash.decodeBIP21(bip21)
|
||||
* // { address: 'qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qw0e54u03', options: { amount: 42, label: 'no prefix' } }
|
||||
*/
|
||||
// decode bip21 url
|
||||
decodeBIP21(url) {
|
||||
return bip21.decode(url)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.getByteCount() getByteCount() - Get byte count of transaction.
|
||||
* @apiName getByteCount
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* Get byte count of transaction.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // 1 P2PKH input
|
||||
* let inputs = {
|
||||
* P2PKH: 1,
|
||||
* }
|
||||
* // 1 P2SH output
|
||||
* let outputs = {
|
||||
* P2SH: 1,
|
||||
* }
|
||||
* bchjs.BitcoinCash.getByteCount(inputs, outputs)
|
||||
* // 190
|
||||
*
|
||||
* // 4 MULTISIG-P2SH 2-of-4 and 10 P2PKH inputs
|
||||
* let inputs = {
|
||||
* 'MULTISIG-P2SH:2-4': 4,
|
||||
* P2PKH: 10,
|
||||
* }
|
||||
* // 23 P2PKH outputs
|
||||
* let outputs = {
|
||||
* P2PKH: 23,
|
||||
* }
|
||||
* bchjs.BitcoinCash.getByteCount(inputs, outputs)
|
||||
* // 2750
|
||||
*
|
||||
* // 2 MULTISIG-P2SH 3-of-5 inputs
|
||||
* let inputs = {
|
||||
* 'MULTISIG-P2SH:3-5': 2,
|
||||
* }
|
||||
* // 2 P2PKH outputs
|
||||
* let outputs = {
|
||||
* P2PKH: 2,
|
||||
* }
|
||||
* bchjs.BitcoinCash.getByteCount(inputs, outputs)
|
||||
* // 565
|
||||
*
|
||||
* // 111 P2PKH inputs
|
||||
* let inputs = {
|
||||
* P2PKH: 111,
|
||||
* }
|
||||
* // 2 P2PKH outputs
|
||||
* let outputs = {
|
||||
* P2PKH: 2,
|
||||
* }
|
||||
* bchjs.BitcoinCash.getByteCount(inputs, outputs)
|
||||
* // 16506
|
||||
*
|
||||
* // 10 P2PKH and 1 MULTISIG-P2SH 1-of-2 input
|
||||
* let inputs = {
|
||||
* P2PKH: 10,
|
||||
* 'MULTISIG-P2SH:1-2': 1,
|
||||
* }
|
||||
* // 2 P2PKH and 1 P2SH outputs
|
||||
* let outputs = {
|
||||
* P2PKH: 2,
|
||||
* P2SH: 1,
|
||||
* }
|
||||
* bchjs.BitcoinCash.getByteCount(inputs, outputs)
|
||||
* // 1780
|
||||
*/
|
||||
getByteCount(inputs, outputs) {
|
||||
// from https://github.com/bitcoinjs/bitcoinjs-lib/issues/921#issuecomment-354394004
|
||||
let totalWeight = 0
|
||||
let hasWitness = false
|
||||
// assumes compressed pubkeys in all cases.
|
||||
const types = {
|
||||
inputs: {
|
||||
"MULTISIG-P2SH": 49 * 4,
|
||||
"MULTISIG-P2WSH": 6 + 41 * 4,
|
||||
"MULTISIG-P2SH-P2WSH": 6 + 76 * 4,
|
||||
P2PKH: 148 * 4,
|
||||
P2WPKH: 108 + 41 * 4,
|
||||
"P2SH-P2WPKH": 108 + 64 * 4
|
||||
},
|
||||
outputs: {
|
||||
P2SH: 32 * 4,
|
||||
P2PKH: 34 * 4,
|
||||
P2WPKH: 31 * 4,
|
||||
P2WSH: 43 * 4
|
||||
}
|
||||
}
|
||||
|
||||
Object.keys(inputs).forEach(function(key) {
|
||||
if (key.slice(0, 8) === "MULTISIG") {
|
||||
// ex. "MULTISIG-P2SH:2-3" would mean 2 of 3 P2SH MULTISIG
|
||||
const keyParts = key.split(":")
|
||||
if (keyParts.length !== 2) throw new Error(`invalid input: ${key}`)
|
||||
const newKey = keyParts[0]
|
||||
const mAndN = keyParts[1].split("-").map(function(item) {
|
||||
return parseInt(item)
|
||||
})
|
||||
|
||||
totalWeight += types.inputs[newKey] * inputs[key]
|
||||
const multiplyer = newKey === "MULTISIG-P2SH" ? 4 : 1
|
||||
totalWeight += (73 * mAndN[0] + 34 * mAndN[1]) * multiplyer
|
||||
} else {
|
||||
totalWeight += types.inputs[key] * inputs[key]
|
||||
}
|
||||
if (key.indexOf("W") >= 0) hasWitness = true
|
||||
})
|
||||
|
||||
Object.keys(outputs).forEach(function(key) {
|
||||
totalWeight += types.outputs[key] * outputs[key]
|
||||
})
|
||||
|
||||
if (hasWitness) totalWeight += 2
|
||||
|
||||
totalWeight += 10 * 4
|
||||
|
||||
return Math.ceil(totalWeight / 4)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.encryptBIP38() encryptBIP38() - BIP38 encrypt privkey WIFs.
|
||||
* @apiName encryptBIP38
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* BIP38 encrypt privkey WIFs.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet
|
||||
* bchjs.BitcoinCash.encryptBIP38(
|
||||
* 'L1phBREbhL4vb1uHHHCAse8bdGE5c7ic2PFjRxMawLzQCsiFVbvu',
|
||||
* '9GKVkabAHBMyAf'
|
||||
* )
|
||||
* // 6PYU2fDHRVF2194gKDGkbFbeu4mFgkWtVvg2RPd2Sp6KmZx3RCHFpgBB2G
|
||||
*
|
||||
* // testnet
|
||||
* bchjs.BitcoinCash.encryptBIP38(
|
||||
* 'cSx7KzdH9EcvDEireu2WYpGnXdFYpta7sJUNt5kVCJgA7kcAU8Gm',
|
||||
* '1EBPIyj55eR8bVUov9'
|
||||
* )
|
||||
* // 6PYUAPLwLSEjWSAfoe9NTSPkMZXnJA8j8EFJtKaeSnP18RCouutBrS2735
|
||||
*/
|
||||
encryptBIP38(privKeyWIF, passphrase) {
|
||||
const decoded = wif.decode(privKeyWIF)
|
||||
|
||||
return bip38.encrypt(decoded.privateKey, decoded.compressed, passphrase)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api BitcoinCash.decryptBIP38() decryptBIP38() - BIP38 encrypt privkey WIFs.
|
||||
* @apiName decryptBIP38
|
||||
* @apiGroup BitcoinCash
|
||||
* @apiDescription
|
||||
* BIP38 encrypt privkey WIFs.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet
|
||||
* bchjs.BitcoinCash.decryptBIP38(
|
||||
* '6PYU2fDHRVF2194gKDGkbFbeu4mFgkWtVvg2RPd2Sp6KmZx3RCHFpgBB2G',
|
||||
* '9GKVkabAHBMyAf',
|
||||
* 'mainnet'
|
||||
* )
|
||||
* // L1phBREbhL4vb1uHHHCAse8bdGE5c7ic2PFjRxMawLzQCsiFVbvu
|
||||
*
|
||||
* // testnet
|
||||
* bchjs.BitcoinCash.decryptBIP38(
|
||||
* '6PYUAPLwLSEjWSAfoe9NTSPkMZXnJA8j8EFJtKaeSnP18RCouutBrS2735',
|
||||
* '1EBPIyj55eR8bVUov9',
|
||||
* 'testnet'
|
||||
* )
|
||||
* // cSx7KzdH9EcvDEireu2WYpGnXdFYpta7sJUNt5kVCJgA7kcAU8Gm
|
||||
*/
|
||||
decryptBIP38(encryptedKey, passphrase, network = "mainnet") {
|
||||
const decryptedKey = bip38.decrypt(encryptedKey, passphrase)
|
||||
let prefix
|
||||
if (network === "testnet") prefix = 0xef
|
||||
else prefix = 0x80
|
||||
|
||||
return wif.encode(prefix, decryptedKey.privateKey, decryptedKey.compressed)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BitcoinCash
|
||||
@@ -0,0 +1,357 @@
|
||||
/*
|
||||
This library interacts with the REST API endpoints in bch-api that communicate
|
||||
with the Blockbook API.
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class Blockbook {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
// console.log(`Blockbook apiToken: ${this.apiToken}`)
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockbook.balance() balance() - Balance about an address.
|
||||
* @apiName Blockbook Balance
|
||||
* @apiGroup Blockbook
|
||||
* @apiDescription Return Balance about an address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let balance = await bchjs.Blockbook.balance('bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c');
|
||||
* console.log(balance)
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* //{
|
||||
* // "page": 1,
|
||||
* // "totalPages": 1,
|
||||
* // "itemsOnPage": 1000,
|
||||
* // "address": "bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c",
|
||||
* // "balance": "6000000",
|
||||
* // "totalReceived": "10185868",
|
||||
* // "totalSent": "4185868",
|
||||
* // "unconfirmedBalance": "0",
|
||||
* // "unconfirmedTxs": 0,
|
||||
* // "txs": 41,
|
||||
* // "txids": [
|
||||
* // "d31dc2cf66fe4d3d3ae18e1065def58a64920746b1702b52f060e5edeea9883b",
|
||||
* // "41e9a118765ecf7a1ba4487c0863e23dba343cc5880381a72f0365ac2546c5fa",
|
||||
* // "2f902dec880568511cefa87b9dd761563edeba9c8ba784dc9fca2f7c8c4e6f97",
|
||||
* // "eea57285462dd70dadcd431fc814857b3f81fe4d0a059a8c02c12fd7d33c02d1",
|
||||
* // "282b3b296b6aed7122586ed69f7a57d35584eaf94a4d1b1ad7d1b05d36cb79d1",
|
||||
* // "ac444896b3e32d17824fa6573eed3b89768c5c9085b7a71f3ba88e9d5ba67355",
|
||||
* // "a5f972572ee1753e2fd2457dd61ce5f40fa2f8a30173d417e49feef7542c96a1",
|
||||
* // "5165dc531aad05d1149bb0f0d9b7bda99c73e2f05e314bcfb5b4bb9ca5e1af5e",
|
||||
* // "54edaa42ff3d6559884a84ebb9bf5ef255635902f5f23b4854245d6b093d41d4",
|
||||
* // "2b0825188e909410a20a6fbdc58ff5ccf368844273f93f551222c91e6d0fa888",
|
||||
* // "7a12ea2c83d0c8a5d0f643974b0f04bc19be185c9011ed8fc33255a61d3198bb",
|
||||
* // "bd6aeeb0748251bb5dba7252ac766fb208c9909d7663c099568225d3bc998a7f",
|
||||
* // "7898bb1a8c5d933f9c2b24270522e8705b897c2f8d5b1c3477a6b952f2fe22ae",
|
||||
* // "8d35668a6838de8faa8dff5d8dedeb114bd8ffe6ae73d926264bc8328b2c46b5",
|
||||
* // "741b4692a14088438ab142cf0865fcbf3977aa7dbd2aafa9bf5f45e75e5e199a",
|
||||
* // "15f6a584080b04911121fbaca7bfcf3dd64ef2bfa5a01daf31e05a296c3e5e9e",
|
||||
* // "376de807f63253584c3edb80f92832ea90e8fdd7d8e68b2602e230d1b015e311",
|
||||
* // "eb5d0902e4a303f38223ecebb06bbf14da8a07d1ebb2d77a89dfb9e00e286c10",
|
||||
* // "11205c557af139f382c43f1f09f223cf28c64d939951fd569e5a30eee6178ccd",
|
||||
* // "ae05a78086b8d64db26d3047de3d6959a68f2a1ed3017ddf927e2c3b20a80b31",
|
||||
* // "7e0fc3cac7504d45b0f2ce68e807e592f0edf17914ab618a4cb4d93403d11c98",
|
||||
* // "1cafaacdfb85b0c33f496bf2c03c4f2ede508479bbad56ae99164dfd823a823f",
|
||||
* // "788add6a5cd961bdf7ca6145a3112462e0e51523d84a4a48047407a795433947",
|
||||
* // "49f09b616824a05eb14ae50c9fbc5d6a0c414d66a7d0b217aa75340c00ed8b85",
|
||||
* // "00f075805adf2a34563ecca33071d660a4c1e91d7d7045282c54554ee4844739",
|
||||
* // "8d048fd00cf375ba9bbea43730da1ce86fc3cb4026e1dd0e751c07fa50a652c6",
|
||||
* // "ac0e82ea84f93444602a99199dd80793f79a8ece5ac86156d2fff34f0bad44b2",
|
||||
* // "342f6815845797e0748f4716c923a0dc9b87de649b69925b36422f6d2dc23b7f",
|
||||
* // "0839a16b2411a1220c64c4d32a4c9b1e77ac5f47558921cf7c0a2adf25e0eb41",
|
||||
* // "62f42995711cb0308dac4203c5deaa2985f120559131e66aebc5164426fb6cee",
|
||||
* // "2ada093fe13c9c04da9582bb304923ce08312eaec92560b9128cdb9e93c5f52f",
|
||||
* // "e0aadd861a06993e39af932bb0b9ad69e7b37ef5843a13c6724789e1c94f3513",
|
||||
* // "925490ce60334aca204d82a61b634d89fe4cc9de429c7b6cb5ec420df3e3be5e",
|
||||
* // "60cb69f29c150378abe21d157858713f82c4e2122867597a2573474763a9e94e",
|
||||
* // "369a589173969c1c882cfb2d82b1e0ec90076ec827ff9d0f32ffc115690c93c3",
|
||||
* // "43324ef3f5fdd55b645ba14de8c0667be9b223d60b3d1dcd76cf8fdeb0fd32e4",
|
||||
* // "d2985c9b1c5c18fc2f6a963b7cb850606c4a18fcb85619057211ce3c8bcec696",
|
||||
* // "dded59fe377517e52918deae8912a096658ebf5ae61992d39953c8bc3932a11b",
|
||||
* // "2dc053f55a666a3d2a08b1c680b704d62a55506d14ad884add87edcc56b9277d",
|
||||
* // "544c15ce35c0f2e808d28f29d6587f1ec9276233e29856b7f2938cf0daef0026",
|
||||
* // "81039b1d7b855b133f359f9dc65f776bd105650153a941675fedc504228ddbd3"
|
||||
* // ]
|
||||
* //}
|
||||
*
|
||||
*(async () => {
|
||||
* try {
|
||||
* let balance = await bchjs.Blockbook.balance(['bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c','1BFHGm4HzqgXXyNX8n7DsQno5DAC4iLMRA']);
|
||||
* console.log(balance)
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* //[
|
||||
* // {
|
||||
* // "page": 1,
|
||||
* // "totalPages": 1,
|
||||
* // "itemsOnPage": 1000,
|
||||
* // "address": "bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c",
|
||||
* // "balance": "6000000",
|
||||
* // "totalReceived": "10185868",
|
||||
* // "totalSent": "4185868",
|
||||
* // "unconfirmedBalance": "0",
|
||||
* // "unconfirmedTxs": 0,
|
||||
* // "txs": 41,
|
||||
* // "txids": [
|
||||
* // "d31dc2cf66fe4d3d3ae18e1065def58a64920746b1702b52f060e5edeea9883b",
|
||||
* // "41e9a118765ecf7a1ba4487c0863e23dba343cc5880381a72f0365ac2546c5fa",
|
||||
* // "2f902dec880568511cefa87b9dd761563edeba9c8ba784dc9fca2f7c8c4e6f97",
|
||||
* // "eea57285462dd70dadcd431fc814857b3f81fe4d0a059a8c02c12fd7d33c02d1",
|
||||
* // "282b3b296b6aed7122586ed69f7a57d35584eaf94a4d1b1ad7d1b05d36cb79d1",
|
||||
* // "ac444896b3e32d17824fa6573eed3b89768c5c9085b7a71f3ba88e9d5ba67355",
|
||||
* // "a5f972572ee1753e2fd2457dd61ce5f40fa2f8a30173d417e49feef7542c96a1",
|
||||
* // "5165dc531aad05d1149bb0f0d9b7bda99c73e2f05e314bcfb5b4bb9ca5e1af5e",
|
||||
* // "54edaa42ff3d6559884a84ebb9bf5ef255635902f5f23b4854245d6b093d41d4",
|
||||
* // "2b0825188e909410a20a6fbdc58ff5ccf368844273f93f551222c91e6d0fa888",
|
||||
* // "7a12ea2c83d0c8a5d0f643974b0f04bc19be185c9011ed8fc33255a61d3198bb",
|
||||
* // "bd6aeeb0748251bb5dba7252ac766fb208c9909d7663c099568225d3bc998a7f",
|
||||
* // "7898bb1a8c5d933f9c2b24270522e8705b897c2f8d5b1c3477a6b952f2fe22ae",
|
||||
* // "8d35668a6838de8faa8dff5d8dedeb114bd8ffe6ae73d926264bc8328b2c46b5",
|
||||
* // "741b4692a14088438ab142cf0865fcbf3977aa7dbd2aafa9bf5f45e75e5e199a",
|
||||
* // "15f6a584080b04911121fbaca7bfcf3dd64ef2bfa5a01daf31e05a296c3e5e9e",
|
||||
* // "376de807f63253584c3edb80f92832ea90e8fdd7d8e68b2602e230d1b015e311",
|
||||
* // "eb5d0902e4a303f38223ecebb06bbf14da8a07d1ebb2d77a89dfb9e00e286c10",
|
||||
* // "11205c557af139f382c43f1f09f223cf28c64d939951fd569e5a30eee6178ccd",
|
||||
* // "ae05a78086b8d64db26d3047de3d6959a68f2a1ed3017ddf927e2c3b20a80b31",
|
||||
* // "7e0fc3cac7504d45b0f2ce68e807e592f0edf17914ab618a4cb4d93403d11c98",
|
||||
* // "1cafaacdfb85b0c33f496bf2c03c4f2ede508479bbad56ae99164dfd823a823f",
|
||||
* // "788add6a5cd961bdf7ca6145a3112462e0e51523d84a4a48047407a795433947",
|
||||
* // "49f09b616824a05eb14ae50c9fbc5d6a0c414d66a7d0b217aa75340c00ed8b85",
|
||||
* // "00f075805adf2a34563ecca33071d660a4c1e91d7d7045282c54554ee4844739",
|
||||
* // "8d048fd00cf375ba9bbea43730da1ce86fc3cb4026e1dd0e751c07fa50a652c6",
|
||||
* // "ac0e82ea84f93444602a99199dd80793f79a8ece5ac86156d2fff34f0bad44b2",
|
||||
* // "342f6815845797e0748f4716c923a0dc9b87de649b69925b36422f6d2dc23b7f",
|
||||
* // "0839a16b2411a1220c64c4d32a4c9b1e77ac5f47558921cf7c0a2adf25e0eb41",
|
||||
* // "62f42995711cb0308dac4203c5deaa2985f120559131e66aebc5164426fb6cee",
|
||||
* // "2ada093fe13c9c04da9582bb304923ce08312eaec92560b9128cdb9e93c5f52f",
|
||||
* // "e0aadd861a06993e39af932bb0b9ad69e7b37ef5843a13c6724789e1c94f3513",
|
||||
* // "925490ce60334aca204d82a61b634d89fe4cc9de429c7b6cb5ec420df3e3be5e",
|
||||
* // "60cb69f29c150378abe21d157858713f82c4e2122867597a2573474763a9e94e",
|
||||
* // "369a589173969c1c882cfb2d82b1e0ec90076ec827ff9d0f32ffc115690c93c3",
|
||||
* // "43324ef3f5fdd55b645ba14de8c0667be9b223d60b3d1dcd76cf8fdeb0fd32e4",
|
||||
* // "d2985c9b1c5c18fc2f6a963b7cb850606c4a18fcb85619057211ce3c8bcec696",
|
||||
* // "dded59fe377517e52918deae8912a096658ebf5ae61992d39953c8bc3932a11b",
|
||||
* // "2dc053f55a666a3d2a08b1c680b704d62a55506d14ad884add87edcc56b9277d",
|
||||
* // "544c15ce35c0f2e808d28f29d6587f1ec9276233e29856b7f2938cf0daef0026",
|
||||
* // "81039b1d7b855b133f359f9dc65f776bd105650153a941675fedc504228ddbd3"
|
||||
* // ]
|
||||
* // },
|
||||
* // {
|
||||
* // "page": 1,
|
||||
* // "totalPages": 1,
|
||||
* // "itemsOnPage": 1000,
|
||||
* // "address": "bitcoincash:qpcxf2sv9hjw08nvpgffpamfus9nmksm3chv5zqtnz",
|
||||
* // "balance": "0",
|
||||
* // "totalReceived": "36781097",
|
||||
* // "totalSent": "36781097",
|
||||
* // "unconfirmedBalance": "0",
|
||||
* // "unconfirmedTxs": 0,
|
||||
* // "txs": 11,
|
||||
* // "txids": [
|
||||
* // "11205c557af139f382c43f1f09f223cf28c64d939951fd569e5a30eee6178ccd",
|
||||
* // "ae05a78086b8d64db26d3047de3d6959a68f2a1ed3017ddf927e2c3b20a80b31",
|
||||
* // "7e0fc3cac7504d45b0f2ce68e807e592f0edf17914ab618a4cb4d93403d11c98",
|
||||
* // "60cb69f29c150378abe21d157858713f82c4e2122867597a2573474763a9e94e",
|
||||
* // "f737485aaee3c10b13013fa109bb6294b099246134ca9885f4cc332dbc6c9bb4",
|
||||
* // "decd5b9c0c959e4e543182093e8f7f8bc7a6ecd96a8a062daaeff3667f8feca7",
|
||||
* // "94e69a627a34ae27fca81d15fff4323a7ce1f7c275c7485762ce018221017632",
|
||||
* // "e67c70787af7f3506263c9eda007f3d2d24bd750ff95b5c50a120d9118dfd807",
|
||||
* // "8e5e00704a147d54028f94d52df7730e821b9c6cd4bd29494e5636f49c199d6a",
|
||||
* // "15102827c108566ea5daf725c09079c1a3f42ef99d1eb68ea8c584f7b16ab87a",
|
||||
* // "cc27be8846276612dfce5924b7be96556212f0f0e62bd17641732175edb9911e"
|
||||
* // ]
|
||||
* // }
|
||||
* //
|
||||
*
|
||||
*/
|
||||
|
||||
async balance(address) {
|
||||
try {
|
||||
// Handle single address.
|
||||
if (typeof address === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockbook/balance/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
|
||||
// Handle array of addresses.
|
||||
} else if (Array.isArray(address)) {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockbook/balance`,
|
||||
{
|
||||
addresses: address
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input address must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockbook.utxo() utxo() - Get list of uxto for address.
|
||||
* @apiName Blockbook Utxo
|
||||
* @apiGroup Blockbook
|
||||
* @apiDescription Return list of uxto for address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let utxo = await bchjs.Blockbook.utxo('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf');
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* [{
|
||||
* "txid": "7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41",
|
||||
* "vout": 0,
|
||||
* "value": "1000",
|
||||
* "height": 604392,
|
||||
* "confirmations": 25530,
|
||||
* "satoshis": 1000
|
||||
* }]
|
||||
*
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let utxo = await bchjs.Blockbook.utxo([
|
||||
* "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
* "bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c"
|
||||
* ]);
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* [
|
||||
* [{
|
||||
* "txid": "7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41",
|
||||
* "vout": 0,
|
||||
* "value": "1000",
|
||||
* "height": 604392,
|
||||
* "confirmations": 25530,
|
||||
* "satoshis": 1000
|
||||
* }],
|
||||
* [{
|
||||
* "txid": "d5228d2cdc77fbe5a9aa79f19b0933b6802f9f0067f42847fc4fe343664723e5",
|
||||
* "vout": 0,
|
||||
* "value": "6000",
|
||||
* "confirmations": 0,
|
||||
* "satoshis": 6000
|
||||
* }]
|
||||
* ]
|
||||
*/
|
||||
async utxo(address) {
|
||||
try {
|
||||
// Handle single address.
|
||||
if (typeof address === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockbook/utxos/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
|
||||
// Handle array of addresses.
|
||||
} else if (Array.isArray(address)) {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockbook/utxos`,
|
||||
{
|
||||
addresses: address
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input address must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockbook.tx() tx() - Get details on a transaction.
|
||||
* @apiName Blockbook Tx
|
||||
* @apiGroup Blockbook
|
||||
* @apiDescription Get details on a transaction.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let txDetails = await bchjs.Blockbook.tx(`5fe9b74056319a8c87f45cc745030715a6180758b94938dbf90d639d55652392`);
|
||||
* console.log(txDetails);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
*/
|
||||
async tx(txid) {
|
||||
try {
|
||||
// Handle single txid.
|
||||
if (typeof txid === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockbook/tx/${txid}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
|
||||
// Handle array of addresses.
|
||||
} else if (Array.isArray(txid)) {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockbook/tx`,
|
||||
{
|
||||
txids: txid
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input txid must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Blockbook
|
||||
@@ -0,0 +1,811 @@
|
||||
/*
|
||||
TODO
|
||||
- Add blockhash functionality back into getTxOutProof
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class Blockchain {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getBestBlockHash() getBestBlockHash() - Returns the hash of the best (tip) block in the longest blockchain.
|
||||
* @apiName getBestBlockHash
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns the hash of the best (tip) block in the longest blockchain.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getBestBlockHash = await bchjs.Blockchain.getBestBlockHash();
|
||||
* console.log(getBestBlockHash);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
* // 241decef88889efac8e6ce428a8ac696fdde5972eceed97e1fb58d6106af31d5
|
||||
*/
|
||||
async getBestBlockHash() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getBestBlockHash`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getBlock() getBlock() - Return information about block hash.
|
||||
* @apiName getBlock
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* If verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'. If verbose is true, returns an Object with information about block hash.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getBlock = await bchjs.Blockchain.getBlock("00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09");
|
||||
* console.log(getBlock);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // { hash: '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',
|
||||
* // confirmations: 528236,
|
||||
* // size: 216,
|
||||
* // height: 1000,
|
||||
* // version: 1,
|
||||
* // versionHex: '00000001',
|
||||
* // merkleroot: 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
|
||||
* // tx:
|
||||
* // [ 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33' ],
|
||||
* // time: 1232346882,
|
||||
* // mediantime: 1232344831,
|
||||
* // nonce: 2595206198,
|
||||
* // bits: '1d00ffff',
|
||||
* // difficulty: 1,
|
||||
* // chainwork: '000000000000000000000000000000000000000000000000000003e903e903e9',
|
||||
* // previousblockhash: '0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d',
|
||||
* // nextblockhash: '00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6' }
|
||||
*/
|
||||
async getBlock(blockhash, verbose = true) {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getBlock/${blockhash}?verbose=${verbose}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getBlockchainInfo() getBlockchainInfo() - Returns an object containing various state info regarding blockchain processing.
|
||||
* @apiName getBlockchainInfo
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns an object containing various state info regarding blockchain processing.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getBlockchainInfo = await bchjs.Blockchain.getBlockchainInfo();
|
||||
* console.log(getBlockchainInfo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // { chain: 'main',
|
||||
* // blocks: 529235,
|
||||
* // headers: 529235,
|
||||
* // bestblockhash: '00000000000000000108641af52e01a447b1f9d801571f93a0f20a8cbf80c236',
|
||||
* // difficulty: 702784497476.8376,
|
||||
* // mediantime: 1525727823,
|
||||
* // verificationprogress: 0.9999892037620548,
|
||||
* // chainwork: '00000000000000000000000000000000000000000099f5e1cf7d4e462a493a51',
|
||||
* // pruned: false,
|
||||
* // softforks:
|
||||
* // [ { id: 'bip34', version: 2, reject: [Object] },
|
||||
* // { id: 'bip66', version: 3, reject: [Object] },
|
||||
* // { id: 'bip65', version: 4, reject: [Object] } ],
|
||||
* // bip9_softforks:
|
||||
* // { csv:
|
||||
* // { status: 'active',
|
||||
* // startTime: 1462060800,
|
||||
* // timeout: 1493596800,
|
||||
* // since: 419328 } } }
|
||||
*/
|
||||
async getBlockchainInfo() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getBlockchainInfo`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getBlockCount() getBlockCount() - Returns the number of blocks in the longest blockchain.
|
||||
* @apiName getBlockCount
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns the number of blocks in the longest blockchain.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getBlockCount = await bchjs.Blockchain.getBlockCount();
|
||||
* console.log(getBlockCount);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
* // 529235
|
||||
*/
|
||||
async getBlockCount() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getBlockCount`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getBlockHash() getBlockHash() - Returns hash of block in best-block-chain at height provided.
|
||||
* @apiName getBlockHash
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns hash of block in best-block-chain at height provided.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getBlockHash = await bchjs.Blockchain.getBlockHash([0]);
|
||||
* console.log(getBlockHash);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
* // [ '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ]
|
||||
*/
|
||||
async getBlockHash(height = 1) {
|
||||
if (typeof height !== "string") height = JSON.stringify(height)
|
||||
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getBlockHash/${height}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getBlockHeader() getBlockHeader() - Return information about blockheader hash.
|
||||
* @apiName getBlockHeader
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* If verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'. If verbose is true, returns an Object with information about blockheader hash.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getBlockHeader = await bchjs.Blockchain.getBlockHeader(["00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"]);
|
||||
* console.log(getBlockHeader);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [{ hash: '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',
|
||||
* // confirmations: 528236,
|
||||
* // height: 1000,
|
||||
* // version: 1,
|
||||
* // versionHex: '00000001',
|
||||
* // merkleroot: 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
|
||||
* // time: 1232346882,
|
||||
* // mediantime: 1232344831,
|
||||
* // nonce: 2595206198,
|
||||
* // bits: '1d00ffff',
|
||||
* // difficulty: 1,
|
||||
* // chainwork: '000000000000000000000000000000000000000000000000000003e903e903e9',
|
||||
* // previousblockhash: '0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d',
|
||||
* // nextblockhash: '00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6' }]
|
||||
*/
|
||||
async getBlockHeader(hash, verbose = true) {
|
||||
try {
|
||||
// Handle single hash.
|
||||
if (typeof hash === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getBlockHeader/${hash}?verbose=${verbose}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
|
||||
// Handle array of hashes.
|
||||
} else if (Array.isArray(hash)) {
|
||||
// Dev note: must use axios.post for unit test stubbing.
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockchain/getBlockHeader`,
|
||||
{
|
||||
hashes: hash,
|
||||
verbose: verbose
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input hash must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getChainTips() getChainTips() - Return information about all known tips in the block tree.
|
||||
* @apiName getChainTips
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Return information about all known tips in the block tree, including the main chain as well as orphaned branches.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getChainTips = await bchjs.Blockchain.getChainTips();
|
||||
* console.log(getChainTips);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [ { height: 529235,
|
||||
* // hash: '00000000000000000108641af52e01a447b1f9d801571f93a0f20a8cbf80c236',
|
||||
* // branchlen: 0,
|
||||
* // status: 'active' },
|
||||
* // { height: 527442,
|
||||
* // hash: '0000000000000000014cbf7b7aa12e52dd97db4b1ba5f39dccae37773af9272e',
|
||||
* // branchlen: 1,
|
||||
* // status: 'invalid' },
|
||||
* // { height: 526861,
|
||||
* // hash: '00000000000000000225b070818bbafd95842ecbd25edf39bff54a7aa5c8fd10',
|
||||
* // branchlen: 1,
|
||||
* // status: 'valid-headers' } ]
|
||||
*/
|
||||
async getChainTips() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getChainTips`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getDifficulty() getDifficulty() - Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
|
||||
* @apiName getDifficulty
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns the proof-of-work difficulty as a multiple of the minimum difficulty.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getDifficulty = await bchjs.Blockchain.getDifficulty();
|
||||
* console.log(getDifficulty);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // 702784497476.8376
|
||||
*/
|
||||
async getDifficulty() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getDifficulty`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
// getMempoolAncestors
|
||||
async getMempoolAncestors(txid, verbose = false) {
|
||||
if (typeof txid !== "string") txid = JSON.stringify(txid)
|
||||
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getMempoolAncestors/${txid}?verbose=${verbose}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getMempoolDescendants(txid, verbose = false) {
|
||||
if (typeof txid !== "string") txid = JSON.stringify(txid)
|
||||
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getMempoolDescendants/${txid}?verbose=${verbose}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getMempoolEntry() getMempoolEntry() - Returns mempool data for given transaction.
|
||||
* @apiName getMempoolEntry
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns mempool data for given transaction.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getMempoolEntry = await bchjs.Blockchain.getMempoolEntry("fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33");
|
||||
* console.log(getMempoolEntry);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // {
|
||||
* // "size": 372,
|
||||
* // "fee": 0.00000374,
|
||||
* // "modifiedfee": 0.00000374,
|
||||
* // "time": 1547738850,
|
||||
* // "height": 565716,
|
||||
* // "startingpriority": 26524545.3974359,
|
||||
* // "currentpriority": 26524545.3974359,
|
||||
* // "descendantcount": 1,
|
||||
* // "descendantsize": 372,
|
||||
* // "descendantfees": 374,
|
||||
* // "ancestorcount": 1,
|
||||
* // "ancestorsize": 372,
|
||||
* // "ancestorfees": 374,
|
||||
* // "depends": []
|
||||
* // }
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getMempoolEntry = await bchjs.Blockchain.getMempoolEntry([
|
||||
* "fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33",
|
||||
* "defea04c38ee00cf73ad402984714ed22dc0dd99b2ae5cb50d791d94343ba79b"
|
||||
* ]);
|
||||
* console.log(getMempoolEntry);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [
|
||||
* // {
|
||||
* // "size": 372,
|
||||
* // "fee": 0.00000374,
|
||||
* // "modifiedfee": 0.00000374,
|
||||
* // "time": 1547738850,
|
||||
* // "height": 565716,
|
||||
* // "startingpriority": 26524545.3974359,
|
||||
* // "currentpriority": 26524545.3974359,
|
||||
* // "descendantcount": 1,
|
||||
* // "descendantsize": 372,
|
||||
* // "descendantfees": 374,
|
||||
* // "ancestorcount": 1,
|
||||
* // "ancestorsize": 372,
|
||||
* // "ancestorfees": 374,
|
||||
* // "depends": []
|
||||
* // },
|
||||
* // {
|
||||
* // "size": 372,
|
||||
* // "fee": 0.00000374,
|
||||
* // "modifiedfee": 0.00000374,
|
||||
* // "time": 1547738850,
|
||||
* // "height": 565716,
|
||||
* // "startingpriority": 26524545.3974359,
|
||||
* // "currentpriority": 26524545.3974359,
|
||||
* // "descendantcount": 1,
|
||||
* // "descendantsize": 372,
|
||||
* // "descendantfees": 374,
|
||||
* // "ancestorcount": 1,
|
||||
* // "ancestorsize": 372,
|
||||
* // "ancestorfees": 374,
|
||||
* // "depends": []
|
||||
* // }
|
||||
* // ]
|
||||
*/
|
||||
async getMempoolEntry(txid) {
|
||||
//if (typeof txid !== "string") txid = JSON.stringify(txid)
|
||||
|
||||
try {
|
||||
if (typeof txid === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getMempoolEntry/${txid}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
} else if (Array.isArray(txid)) {
|
||||
// Dev note: must use axios.post for unit test stubbing.
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockchain/getMempoolEntry`,
|
||||
{
|
||||
txids: txid
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getMempoolInfo() getMempoolInfo() - Returns details on the active state of the TX memory pool.
|
||||
* @apiName getMempoolInfo
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns details on the active state of the TX memory pool.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getMempoolInfo = await bchjs.Blockchain.getMempoolInfo();
|
||||
* console.log(getMempoolInfo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // { size: 257,
|
||||
* // bytes: 98257,
|
||||
* // usage: 365840,
|
||||
* // maxmempool: 300000000,
|
||||
* // mempoolminfee: 0 }
|
||||
*/
|
||||
async getMempoolInfo() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getMempoolInfo`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getRawMempool() getRawMempool() - Returns all transaction ids in memory pool as a json array of string transaction ids.
|
||||
* @apiName getRawMempool
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns all transaction ids in memory pool as a json array of string transaction ids.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getRawMempool = await bchjs.Blockchain.getRawMempool(true);
|
||||
* console.log(getRawMempool);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [ {'2ae541af20db6f2b50410f418af56e349d08877d685f6cf54df54658e892db7a':
|
||||
* // { size: 237,
|
||||
* // fee: 0.00000238,
|
||||
* // modifiedfee: 0.00000238,
|
||||
* // time: 1525732015,
|
||||
* // height: 529235,
|
||||
* // startingpriority: 0,
|
||||
* // currentpriority: 0,
|
||||
* // descendantcount: 10,
|
||||
* // descendantsize: 2376,
|
||||
* // descendantfees: 2380,
|
||||
* // ancestorcount: 3,
|
||||
* // ancestorsize: 712,
|
||||
* // ancestorfees: 714,
|
||||
* // depends:
|
||||
* // [ 'e25682caafc7000645d59f4c11d8d594b2943979b9d8fafb9f946e2b35c21b7e' ] },]
|
||||
*/
|
||||
async getRawMempool(verbose = false) {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/getRawMempool?vebose=${verbose}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getTxOut() getTxOut() - Returns details about an unspent transaction output.
|
||||
* @apiName getTxOut
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns details about an unspent transaction output.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getTxOut = await bchjs.Blockchain.getTxOut("e25682caafc7000645d59f4c11d8d594b2943979b9d8fafb9f946e2b35c21b7e", 1);
|
||||
* console.log(getTxOut);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // null
|
||||
*/
|
||||
async getTxOut(txid, n, include_mempool = true) {
|
||||
try {
|
||||
// Input validation
|
||||
if (typeof txid !== "string" || txid.length !== 64)
|
||||
throw new Error(`txid needs to be a proper transaction ID`)
|
||||
|
||||
if (isNaN(n)) throw new Error(`n must be an integer`)
|
||||
|
||||
if (typeof include_mempool !== "boolean")
|
||||
throw new Error(`include_mempool input must be of type boolean`)
|
||||
|
||||
// Send the request to the REST API.
|
||||
// const response = await axios.get(
|
||||
// `${this.restURL}blockchain/getTxOut/${txid}/${n}?include_mempool=${include_mempool}`,
|
||||
// _this.axiosOptions
|
||||
// )
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockchain/getTxOut`,
|
||||
{
|
||||
txid: txid,
|
||||
vout: n,
|
||||
mempool: include_mempool
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.getTxOutProof() getTxOutProof() - Returns a hex-encoded proof that "txid" was included in a block.
|
||||
* @apiName getTxOutProof
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Returns a hex-encoded proof that "txid" was included in a block.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getTxOutProof = await bchjs.Blockchain.getTxOutProof("e25682caafc7000645d59f4c11d8d594b2943979b9d8fafb9f946e2b35c21b7e");
|
||||
* console.log(getTxOutProof);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // "0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01"
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getTxOutProof = await bchjs.Blockchain.getTxOutProof([
|
||||
* "e25682caafc7000645d59f4c11d8d594b2943979b9d8fafb9f946e2b35c21b7e",
|
||||
* "d16662463fd98eb96c8f6898d58a4461ac3d0120f4d0aea601d72b37759f261c"
|
||||
* ]);
|
||||
* console.log(getTxOutProof);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [
|
||||
* // "010000007de867cc8adc5cc8fb6b898ca4462cf9fd667d7830a275277447e60800000000338f121232e169d3100edd82004dc2a1f0e1f030c6c488fa61eafa930b0528fe021f7449ffff001d36b4af9a0100000001338f121232e169d3100edd82004dc2a1f0e1f030c6c488fa61eafa930b0528fe0101",
|
||||
* // "010000007de867cc8adc5cc8fb6b898ca4462cf9fd667d7830a275277447e60800000000338f121232e169d3100edd82004dc2a1f0e1f030c6c488fa61eafa930b0528fe021f7449ffff001d36b4af9a0100000001338f121232e169d3100edd82004dc2a1f0e1f030c6c488fa61eafa930b0528fe0101"
|
||||
* // ]
|
||||
*/
|
||||
async getTxOutProof(txids) {
|
||||
try {
|
||||
// Single txid.
|
||||
if (typeof txids === "string") {
|
||||
const path = `${this.restURL}blockchain/getTxOutProof/${txids}`
|
||||
//if (blockhash) path = `${path}?blockhash=${blockhash}`
|
||||
|
||||
const response = await axios.get(path, _this.axiosOptions)
|
||||
return response.data
|
||||
|
||||
// Array of txids.
|
||||
} else if (Array.isArray(txids)) {
|
||||
// Dev note: must use axios.post for unit test stubbing.
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockchain/getTxOutProof`,
|
||||
{
|
||||
txids: txids
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async preciousBlock(blockhash) {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/preciousBlock/${blockhash}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async pruneBlockchain(height) {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockchain/pruneBlockchain/${height}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async verifyChain(checklevel = 3, nblocks = 6) {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/verifyChain?checklevel=${checklevel}&nblocks=${nblocks}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Blockchain.verifyTxOutProof() verifyTxOutProof() - Verifies that a proof points to a transaction in a block.
|
||||
* @apiName verifyTxOutProof
|
||||
* @apiGroup Blockchain
|
||||
* @apiDescription
|
||||
* Verifies that a proof points to a transaction in a block, returning the transaction it commits to and throwing an RPC error if the block is not in our best chain.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* const proof = "0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01"
|
||||
* let verifyTxOutProof = await bchjs.Blockchain.verifyTxOutProof(proof);
|
||||
* console.log(verifyTxOutProof);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [
|
||||
* // "03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
|
||||
* // ]
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* const proof = "0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01"
|
||||
* let verifyTxOutProof = await bchjs.Blockchain.verifyTxOutProof([proof, proof]);
|
||||
* console.log(verifyTxOutProof);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [
|
||||
* // "03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7",
|
||||
* // "03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
|
||||
* // ]
|
||||
*/
|
||||
async verifyTxOutProof(proof) {
|
||||
try {
|
||||
// Single block
|
||||
if (typeof proof === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}blockchain/verifyTxOutProof/${proof}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
|
||||
// Array of hashes.
|
||||
} else if (Array.isArray(proof)) {
|
||||
// Dev note: must use axios.post for unit test stubbing.
|
||||
const response = await axios.post(
|
||||
`${this.restURL}blockchain/verifyTxOutProof`,
|
||||
{
|
||||
proofs: proof
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Blockchain
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
API endpoints for basic control and information of the full node.
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
|
||||
let _this // Global reference to the instance of this class.
|
||||
|
||||
class Control {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Control.getNetworkInfo() getNetworkInfo() - Get Network info
|
||||
* @apiName getNetworkInfo
|
||||
* @apiGroup Control
|
||||
* @apiDescription Returns an object containing various network info.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getInfo = await bchjs.Control.getNetworkInfo();
|
||||
* console.log(getInfo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // returns
|
||||
* { version: 190500,
|
||||
* subversion: '/Bitcoin ABC:0.19.5(EB32.0)/',
|
||||
* protocolversion: 70015,
|
||||
* localservices: '0000000000000425',
|
||||
* localrelay: true,
|
||||
* timeoffset: 0,
|
||||
* networkactive: true,
|
||||
* connections: 17,
|
||||
* networks:
|
||||
* [ { name: 'ipv4',
|
||||
* limited: false,
|
||||
* reachable: true,
|
||||
* proxy: '',
|
||||
* proxy_randomize_credentials: false },
|
||||
* { name: 'ipv6',
|
||||
* limited: false,
|
||||
* reachable: true,
|
||||
* proxy: '',
|
||||
* proxy_randomize_credentials: false },
|
||||
* { name: 'onion',
|
||||
* limited: true,
|
||||
* reachable: false,
|
||||
* proxy: '',
|
||||
* proxy_randomize_credentials: false } ],
|
||||
* relayfee: 0.00001,
|
||||
* excessutxocharge: 0,
|
||||
* warnings:
|
||||
* 'Warning: Unknown block versions being mined! It\'s possible unknown rules are in effect' }}
|
||||
*/
|
||||
async getNetworkInfo() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}control/getNetworkInfo`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getMemoryInfo() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}control/getMemoryInfo`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
//
|
||||
// stop() {
|
||||
// // Stop Bitcoin Cash server.
|
||||
// return axios.post(`${this.restURL}control/stop`)
|
||||
// .then((response) => {
|
||||
// return response.data;
|
||||
// })
|
||||
// .catch((error) => {
|
||||
// return JSON.stringify(error.response.data.error.message);
|
||||
// });
|
||||
// }
|
||||
}
|
||||
|
||||
module.exports = Control
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
const randomBytes = require("randombytes")
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
|
||||
class Crypto {
|
||||
/**
|
||||
* @api Crypto.sha256() sha256() - Utility for creating sha256 hash.
|
||||
* @apiName sha256
|
||||
* @apiGroup Crypto
|
||||
* @apiDescription Utility for creating sha256 hash digests of data
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('0101010101010101', 'hex')
|
||||
* bchjs.Crypto.sha256(buffer)
|
||||
* // <Buffer c0 35 7a 32 ed 1f 6a 03 be 92 dd 09 44 76 f7 f1 a2 e2 14 ec>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('031ad329b3117e1d1e2974406868e575d48cff88e8128ba0eedb10da053785033b', 'hex')
|
||||
* bchjs.Crypto.sha256(buffer)
|
||||
* // <Buffer 98 ee ed 79 8e e9 58 d1 65 3e df 2d 85 7d 4a ea ba 97 19 32>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('03123464075c7a5fa6b8680afa2c962a02e7bf071c6b2395b0ac711d462cac9354', 'hex')
|
||||
* bchjs.Crypto.sha256(buffer)
|
||||
* // <Buffer 26 b0 78 0a 68 3a 1e 09 8e 9c b8 cf a1 b0 92 42 28 25 00 97>
|
||||
*
|
||||
* */
|
||||
// Translate address from any address format into a specific format.
|
||||
static sha256(buffer) {
|
||||
return Bitcoin.crypto.sha256(buffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Crypto.ripemd160() ripemd160()-Utility for creating ripemd160 hash.
|
||||
* @apiName ripemd160
|
||||
* @apiGroup Crypto
|
||||
* @apiDescription Utility for creating ripemd160 hash digests of data
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('0101010101010101', 'hex')
|
||||
* bchjs.Crypto.ripemd160(buffer)
|
||||
* // <Buffer 58 25 70 1b 4b 97 67 fd 35 06 3b 28 6d ca 35 82 85 3e 06 30>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('75618d82d1f6251f2ef1f42f5f0d5040330948a707ff6d69720dbdcb00b48aab', 'hex')
|
||||
* bchjs.Crypto.ripemd160(buffer)
|
||||
* // <Buffer 88 74 ef 88 8a 9b cb d8 3b 87 d0 6f f7 bc 21 3c 51 49 73 62>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('978c09dd46091d1922fa01e9f4a975b91a371f26ba8399de27d53801152121de', 'hex')
|
||||
* bchjs.Crypto.ripemd160(buffer)
|
||||
* // <Buffer 5f 95 6a 88 86 30 51 ea 52 15 d8 97 0c ed 8e 21 8e b6 15 cf>
|
||||
* */
|
||||
static ripemd160(buffer) {
|
||||
return Bitcoin.crypto.ripemd160(buffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Crypto.hash256() hash256() - Utility for creating double sha256 hash.
|
||||
* @apiName hash256
|
||||
* @apiGroup Crypto
|
||||
* @apiDescription Utility for creating double sha256 hash digests of data.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('0101010101010101', 'hex')
|
||||
* bchjs.Crypto.hash256(buffer)
|
||||
* // <Buffer 72 83 38 d9 9f 35 61 75 c4 94 5e f5 cc cf a6 1b 7b 56 14 3c bb f4 26 dd d0 e0 fc 7c fe 8c 3c 23>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('031ad329b3117e1d1e2974406868e575d48cff88e8128ba0eedb10da053785033b', 'hex')
|
||||
* bchjs.Crypto.hash256(buffer)
|
||||
* // <Buffer 7a d2 a7 4b d5 96 98 71 4a 29 91 a8 2b 71 73 6f 35 42 b2 82 8b 6a c2 4d e4 27 c4 40 da 89 d0 1a>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('03123464075c7a5fa6b8680afa2c962a02e7bf071c6b2395b0ac711d462cac9354', 'hex')
|
||||
* bchjs.Crypto.hash256(buffer)
|
||||
* // <Buffer 68 8f 1d 02 9e d5 4c 34 d0 32 0b 83 8b f6 fc 64 f6 2f 38 a6 e9 30 a0 af 5b db 4e 27 d1 a6 84 cd>
|
||||
* */
|
||||
static hash256(buffer) {
|
||||
return Bitcoin.crypto.hash256(buffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Crypto.hash160() hash160() - Utility for creating ripemd160(sha256()) hash.
|
||||
* @apiName hash160
|
||||
* @apiGroup Crypto
|
||||
* @apiDescription Utility for creating ripemd160(sha256()) hash digests of data.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('0101010101010101', 'hex')
|
||||
* bchjs.Crypto.hash160(buffer)
|
||||
* // <Buffer ab af 11 19 f8 3e 38 42 10 fe 8e 22 2e ac 76 e2 f0 da 39 dc>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('031ad329b3117e1d1e2974406868e575d48cff88e8128ba0eedb10da053785033b', 'hex')
|
||||
* bchjs.Crypto.hash160(buffer)
|
||||
* // <Buffer 88 74 ef 88 8a 9b cb d8 3b 87 d0 6f f7 bc 21 3c 51 49 73 62>
|
||||
*
|
||||
* // buffer from hex
|
||||
* let buffer = Buffer.from('03123464075c7a5fa6b8680afa2c962a02e7bf071c6b2395b0ac711d462cac9354', 'hex')
|
||||
* bchjs.Crypto.hash160(buffer)
|
||||
*
|
||||
* */
|
||||
static hash160(buffer) {
|
||||
return Bitcoin.crypto.hash160(buffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Crypto.randomBytes() randomBytes() - Generates cryptographically strong pseudo-random data.
|
||||
* @apiName randomBytes
|
||||
* @apiGroup Crypto
|
||||
* @apiDescription Generates cryptographically strong pseudo-random data. The size argument is a number indicating the number of bytes to generate.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* bchjs.Crypto.randomBytes(16)
|
||||
* // <Buffer 0e 87 d2 7b c4 c3 d0 06 ef bb f3 a4 e5 ea 87 02>
|
||||
*
|
||||
* bchjs.Crypto.randomBytes(20)
|
||||
* // <Buffer 8b 42 7d ca 52 c0 77 69 a3 f2 32 90 6b a5 a8 50 56 e2 47 0f>
|
||||
*
|
||||
* bchjs.Crypto.randomBytes(24)
|
||||
* // <Buffer 28 69 fc 81 f7 a8 dd 5e 25 92 c4 7b 87 31 02 e8 b3 4c 92 fa c4 c9 1a e2>
|
||||
*
|
||||
* bchjs.Crypto.randomBytes(28)
|
||||
* // <Buffer 80 53 dd 21 b6 02 a9 c7 8f 1c 1d 64 1b 6e 21 3e 3f 01 e1 0f aa 6c 59 50 3a b3 41 a6>
|
||||
*
|
||||
* bchjs.Crypto.randomBytes(32)
|
||||
* // <Buffer ec 44 73 72 ea 48 3e 08 a5 0a 62 b8 40 0f 69 64 a7 75 35 af 20 3d e1 6d ce 3b f9 37 11 19 2b c6>
|
||||
* */
|
||||
static randomBytes(size = 16) {
|
||||
return randomBytes(size)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Crypto
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
const coininfo = require("coininfo")
|
||||
|
||||
class ECPair {
|
||||
static setAddress(address) {
|
||||
ECPair._address = address
|
||||
}
|
||||
/**
|
||||
* @api Ecpair.fromWIF() fromWIF() - Generates an ECPair from a private key in wallet import format (WIF).
|
||||
* @apiName fromWIF
|
||||
* @apiGroup ECPair
|
||||
* @apiDescription Generates an ECPair from a private key in wallet import format (WIF). Follow these steps to go from a private key to a WIF. This method only works with a compressed private key.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet WIF
|
||||
* let wif = 'L4vmKsStbQaCvaKPnCzdRArZgdAxTqVx8vjMGLW5nHtWdRguiRi1';
|
||||
* bchjs.ECPair.fromWIF(wif);
|
||||
*
|
||||
* // testnet WIF
|
||||
* let wif = 'cSNLj6xeg3Yg2rfcgKoWNx4MiAgn9ugCUUro37UDEhn6CzeYqjWW'
|
||||
* bchjs.ECPair.fromWIF(wif)
|
||||
* */
|
||||
static fromWIF(privateKeyWIF) {
|
||||
let network
|
||||
if (privateKeyWIF[0] === "L" || privateKeyWIF[0] === "K")
|
||||
network = "mainnet"
|
||||
else if (privateKeyWIF[0] === "c") network = "testnet"
|
||||
|
||||
let bitcoincash
|
||||
if (network === "mainnet") bitcoincash = coininfo.bitcoincash.main
|
||||
else bitcoincash = coininfo.bitcoincash.test
|
||||
|
||||
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
|
||||
|
||||
return Bitcoin.ECPair.fromWIF(privateKeyWIF, bitcoincashBitcoinJSLib)
|
||||
}
|
||||
/**
|
||||
* @api Ecpair.toWIF() toWIF() - Gets a private key in wallet import format from an ECPair.
|
||||
* @apiName toWIF
|
||||
* @apiGroup ECPair
|
||||
* @apiDescription Gets a private key in wallet import format from an ECPair.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet wif
|
||||
* let wif = 'L4vmKsStbQaCvaKPnCzdRArZgdAxTqVx8vjMGLW5nHtWdRguiRi1';
|
||||
* // ecpair from wif
|
||||
* let ecpair = bchjs.ECPair.fromWIF(wif);
|
||||
* // wif from ecpair
|
||||
* bchjs.ECPair.toWIF(ecpair);
|
||||
* // L4vmKsStbQaCvaKPnCzdRArZgdAxTqVx8vjMGLW5nHtWdRguiRi1
|
||||
*
|
||||
* // testnet wif
|
||||
* let wif = 'cT3tJP7BnjFJSAHbooMXrY8E9t2AFj37amSBAYFMeHfqPqPgD4ZA';
|
||||
* // ecpair from wif
|
||||
* let ecpair = bchjs.ECPair.fromWIF(wif);
|
||||
* // wif from ecpair
|
||||
* bchjs.ECPair.toWIF(ecpair);
|
||||
* // cT3tJP7BnjFJSAHbooMXrY8E9t2AFj37amSBAYFMeHfqPqPgD4ZA
|
||||
* */
|
||||
static toWIF(ecpair) {
|
||||
return ecpair.toWIF()
|
||||
}
|
||||
|
||||
static sign(ecpair, buffer) {
|
||||
return ecpair.sign(buffer)
|
||||
}
|
||||
|
||||
static verify(ecpair, buffer, signature) {
|
||||
return ecpair.verify(buffer, signature)
|
||||
}
|
||||
/**
|
||||
* @api Ecpair.fromPublicKey() fromPublicKey() - Generates an ECPair from a public key buffer.
|
||||
* @apiName fromPublicKey
|
||||
* @apiGroup ECPair
|
||||
* @apiDescription Generates an ECPair from a public key buffer.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create ECPair from mainnet pubkeyBuffer
|
||||
* let pubkeyBuffer = Buffer.from("02fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb", 'hex');
|
||||
* bchjs.ECPair.fromPublicKey(pubkeyBuffer);
|
||||
*
|
||||
* // create ECPair from testnet pubkeyBuffer
|
||||
* let pubkeyBuffer = Buffer.from("024a6d0737a23c472d078d78c1cbc3c2bbf8767b48e72684ff03a911b463da7fa6", 'hex');
|
||||
* bchjs.ECPair.fromPublicKey(pubkeyBuffer);
|
||||
* */
|
||||
static fromPublicKey(pubkeyBuffer) {
|
||||
return Bitcoin.ECPair.fromPublicKeyBuffer(pubkeyBuffer)
|
||||
}
|
||||
/**
|
||||
* @api Ecpair.toPublicKey() toPublicKey() - Get the public key of an ECPair as a buffer.
|
||||
* @apiName toPublicKey
|
||||
* @apiGroup ECPair
|
||||
* @apiDescription Get the public key of an ECPair as a buffer.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create ecpair from mainnet public key buffer
|
||||
* let ecpair = bchjs.ECPair.fromPublicKey(Buffer.from('02d305772e0873fba6c1c7ff353ce374233316eb5820acd7ff3d7d9b82d514126b', 'hex'));
|
||||
* // create public key buffer
|
||||
* bchjs.ECPair.toPublicKey(ecpair);
|
||||
* //
|
||||
*
|
||||
* // create ecpair from testnet public key buffer
|
||||
* let ecpair = bchjs.ECPair.fromPublicKey(Buffer.from('024a6d0737a23c472d078d78c1cbc3c2bbf8767b48e72684ff03a911b463da7fa6', 'hex'));
|
||||
* // create public key buffer
|
||||
* bchjs.ECPair.toPublicKey(ecpair);
|
||||
* //
|
||||
* */
|
||||
static toPublicKey(ecpair) {
|
||||
return ecpair.getPublicKeyBuffer()
|
||||
}
|
||||
/**
|
||||
* @api Ecpair.toLegacyAddress() toLegacyAddress() - Get legacy address of ECPair.
|
||||
* @apiName toLegacyAddress
|
||||
* @apiGroup ECPair
|
||||
* @apiDescription Get legacy address of ECPair.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet wif
|
||||
* let wif = 'L5GPEGxCmojgzFoBLUUqT2GegLGqobiYhTZzfLtpkLTfTb9E9NRn';
|
||||
* // ecpair from wif
|
||||
* let ecpair = bchjs.ECPair.fromWIF(wif);
|
||||
* // to legacy address
|
||||
* bchjs.ECPair.toLegacyAddress(ecpair);
|
||||
* // 1DgxdA5bbMcCNWg3yB2MgKqFazV92BXgxK
|
||||
*
|
||||
* // testnet wif
|
||||
* let wif = 'cSNLj6xeg3Yg2rfcgKoWNx4MiAgn9ugCUUro37UDEhn6CzeYqjWW';
|
||||
* // ecpair from wif
|
||||
* let ecpair = bchjs.ECPair.fromWIF(wif);
|
||||
* // to legacy address
|
||||
* bchjs.ECPair.toLegacyAddress(ecpair);
|
||||
* // mg4PygFcXoyNJGJkM2Dcpe25av9wXzz1My
|
||||
* */
|
||||
static toLegacyAddress(ecpair) {
|
||||
return ecpair.getAddress()
|
||||
}
|
||||
/**
|
||||
* @api Ecpair.toCashAddress() toCashAddress() - Get cash address of ECPair.
|
||||
* @apiName toCashAddress
|
||||
* @apiGroup ECPair
|
||||
* @apiDescription Get cash address of ECPair.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet wif
|
||||
* let wif = 'L5GPEGxCmojgzFoBLUUqT2GegLGqobiYhTZzfLtpkLTfTb9E9NRn';
|
||||
* // ecpair from wif
|
||||
* let ecpair = bchjs.ECPair.fromWIF(wif);
|
||||
* // to legacy address
|
||||
* bchjs.ECPair.toCashAddress(ecpair);
|
||||
* // bitcoincash:qz9nq206kteyv2t7trhdr4vzzkej60kqtytn7sxkxm
|
||||
*
|
||||
* // testnet wif
|
||||
* let wif = 'cSNLj6xeg3Yg2rfcgKoWNx4MiAgn9ugCUUro37UDEhn6CzeYqjWW';
|
||||
* // ecpair from wif
|
||||
* let ecpair = bchjs.ECPair.fromWIF(wif);
|
||||
* // to legacy address
|
||||
* bchjs.ECPair.toCashAddress(ecpair);
|
||||
* // bchtest:qqzly4vrcxcjw62u4yq4nv86ltk2mc9v0yvq8mvj6m
|
||||
* */
|
||||
static toCashAddress(ecpair, regtest = false) {
|
||||
return ECPair._address.toCashAddress(ecpair.getAddress(), true, regtest)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ECPair
|
||||
@@ -0,0 +1,304 @@
|
||||
/*
|
||||
This library interacts with the ElectrumX bch-api REST API endpoints operated
|
||||
by FullStack.cash
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class ElectrumX {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`,
|
||||
timeout: 15000
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Electrumx.utxo() utxo() - Get a list of uxto for an address.
|
||||
* @apiName ElectrumX Utxo
|
||||
* @apiGroup ElectrumX
|
||||
* @apiDescription Return a list of uxtos for an address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let utxo = await bchjs.Electrumx.utxo('bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9');
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* utxo = {
|
||||
* "success": true,
|
||||
* "utxos": [
|
||||
* {
|
||||
* "height": 602405,
|
||||
* "tx_hash": "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7",
|
||||
* "tx_pos": 0,
|
||||
* "value": 1000
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let utxo = await bchjs.Electrumx.utxo(['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf', 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v']);
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* utxos = {
|
||||
* "success": true,
|
||||
* "utxos": [
|
||||
* {
|
||||
* "utxos": [
|
||||
* {
|
||||
* "height": 604392,
|
||||
* "tx_hash": "7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41",
|
||||
* "tx_pos": 0,
|
||||
* "value": 1000
|
||||
* },
|
||||
* {
|
||||
* "height": 630834,
|
||||
* "tx_hash": "4fe60a51e0d8f5134bfd8e5f872d6e502d7f01b28a6afebb27f4438a4f638d53",
|
||||
* "tx_pos": 0,
|
||||
* "value": 6000
|
||||
* }
|
||||
* ],
|
||||
* "address": "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
* },
|
||||
* {
|
||||
* "utxos": [],
|
||||
* "address": "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
*/
|
||||
async utxo(address) {
|
||||
try {
|
||||
// Handle single address.
|
||||
if (typeof address === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}electrumx/utxos/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
|
||||
// Handle array of addresses.
|
||||
} else if (Array.isArray(address)) {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}electrumx/utxos`,
|
||||
{
|
||||
addresses: address
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input address must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Electrumx.balance() balance() - Get the balance for an address.
|
||||
* @apiName ElectrumX Balance
|
||||
* @apiGroup ElectrumX
|
||||
* @apiDescription Return a list of balances for an address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let balance = await bchjs.Electrumx.balance('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf');
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* balance = {
|
||||
* "success": true,
|
||||
* "balance": {
|
||||
* "confirmed": 1000,
|
||||
* "unconfirmed": 0
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let balance = await bchjs.Electrumx.balance(['bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf', 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v']);
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* balance = {
|
||||
* "success": true,
|
||||
* "balances": [
|
||||
* {
|
||||
* "balance": {
|
||||
* "confirmed": 7000,
|
||||
* "unconfirmed": 0
|
||||
* },
|
||||
* "address": "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
* },
|
||||
* {
|
||||
* "balance": {
|
||||
* "confirmed": 0,
|
||||
* "unconfirmed": 0
|
||||
* },
|
||||
* "address": "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
*/
|
||||
async balance(address) {
|
||||
try {
|
||||
// Handle single address.
|
||||
if (typeof address === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}electrumx/balance/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
|
||||
// Handle array of addresses.
|
||||
} else if (Array.isArray(address)) {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}electrumx/balance`,
|
||||
{
|
||||
addresses: address
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input address must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Electrumx.transactions() transactions() - Get the transaction history for an address.
|
||||
* @apiName ElectrumX Transactions
|
||||
* @apiGroup ElectrumX
|
||||
* @apiDescription Return a transaction history for an address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let transactions = await bchjs.Electrumx.transactions('bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v');
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* {
|
||||
* "success": true,
|
||||
* "transactions": [
|
||||
* {
|
||||
* "height": 560430,
|
||||
* "tx_hash": "3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851"
|
||||
* },
|
||||
* {
|
||||
* "height": 560534,
|
||||
* "tx_hash": "4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let transactions = await bchjs.Electrumx.transactions(['bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj', 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v']);
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* transactions = {
|
||||
* "success": true,
|
||||
* "transactions": [
|
||||
* {
|
||||
* "transactions": [
|
||||
* {
|
||||
* "height": 631219,
|
||||
* "tx_hash": "ae2daa01c8172545b5edd205ea438706bcb74e63d4084a26b9ff2a46d46dc97f"
|
||||
* }
|
||||
* ],
|
||||
* "address": "bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj"
|
||||
* },
|
||||
* {
|
||||
* "transactions": [
|
||||
* {
|
||||
* "height": 560430,
|
||||
* "tx_hash": "3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851"
|
||||
* },
|
||||
* {
|
||||
* "height": 560534,
|
||||
* "tx_hash": "4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280"
|
||||
* }
|
||||
* ],
|
||||
* "address": "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
* }
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
*/
|
||||
async transactions(address) {
|
||||
try {
|
||||
// Handle single address.
|
||||
if (typeof address === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}electrumx/transactions/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
|
||||
// Handle array of addresses.
|
||||
} else if (Array.isArray(address)) {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}electrumx/transactions`,
|
||||
{
|
||||
addresses: address
|
||||
},
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input address must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ElectrumX
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
This library contains useful functions that deal with encryption.
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class Encryption {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
this.axios = axios
|
||||
// console.log(`Blockbook apiToken: ${this.apiToken}`)
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
// Search the blockchain for a public key associated with a BCH address.
|
||||
async getPubKey(addr) {
|
||||
try {
|
||||
if (!addr || typeof addr !== "string")
|
||||
throw new Error(`Input must be a valid Bitcoin Cash address.`)
|
||||
|
||||
const response = await _this.axios.get(
|
||||
`${this.restURL}encryption/publickey/${addr}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Encryption
|
||||
@@ -0,0 +1,34 @@
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class Generating {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
async generateToAddress(blocks, address, maxtries = 1000000) {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${this.restURL}generating/generateToAddress/${blocks}/${address}?maxtries=${maxtries}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Generating
|
||||
+640
@@ -0,0 +1,640 @@
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
const coininfo = require("coininfo")
|
||||
const bip32utils = require("bip32-utils")
|
||||
const bchaddrjs = require("bchaddrjs-slp")
|
||||
|
||||
class HDNode {
|
||||
constructor(address) {
|
||||
this._address = address
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.fromSeed() fromSeed() - Create HDNode from Seed Buffer.
|
||||
* @apiName fromSeed
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* HDNode stands for Hierarchically Deterministic node which can be used to create a HD wallet.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* bchjs.HDNode.fromSeed(seedBuffer);
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* bchjs.HDNode.fromSeed(seedBuffer);
|
||||
*/
|
||||
fromSeed(rootSeedBuffer, network = "mainnet") {
|
||||
let bitcoincash
|
||||
if (network === "bitcoincash" || network === "mainnet")
|
||||
bitcoincash = coininfo.bitcoincash.main
|
||||
else bitcoincash = coininfo.bitcoincash.test
|
||||
|
||||
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
|
||||
return Bitcoin.HDNode.fromSeedBuffer(
|
||||
rootSeedBuffer,
|
||||
bitcoincashBitcoinJSLib
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toLegacyAddress() toLegacyAddress() - Get legacy address of HDNode.
|
||||
* @apiName toLegacyAddress
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Get legacy address of HDNode
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to legacy address
|
||||
* bchjs.HDNode.toLegacyAddress(hdNode);
|
||||
* // 14apxtw2LDQmXWsS5k4JEhG93Jzjswhvma
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to cash address
|
||||
* bchjs.HDNode.toLegacyAddress(hdNode);
|
||||
* // 14mVsq3H5Ep2Jb6AqoKsmY1BFHKCBGPDLi
|
||||
*/
|
||||
toLegacyAddress(hdNode) {
|
||||
return hdNode.getAddress()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toCashAddress() toCashAddress() - Get cash address of HDNode
|
||||
* @apiName toCashAddress
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Get cash address of HDNode.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to cash address
|
||||
* bchjs.HDNode.toCashAddress(hdNode);
|
||||
* // bitcoincash:qqrz6kqw6nvhwgwrt4g7fggepvewtkr7nukkeqf4rw
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to cash address
|
||||
* bchjs.HDNode.toCashAddress(hdNode);
|
||||
* // bitcoincash:qq549jxsjv66kw0smdju4es2axnk7hhe9cquhjg4gt
|
||||
*/
|
||||
toCashAddress(hdNode, regtest = false) {
|
||||
return this._address.toCashAddress(hdNode.getAddress(), true, regtest)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.HDNode.toSLPAddress() toSLPAddress() - Get slp address of HDNode.
|
||||
* @apiName toSLPAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Get slp address of HDNode.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.SLP.HDNode.fromSeed(seedBuffer);
|
||||
* // to cash address
|
||||
* bchjs.SLP.HDNode.toSLPAddress(hdNode);
|
||||
* // simpleledger:qpst7ganm0ucmj3yl7jxvdqrm7tg3zhveg89xjh25d
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.SLP.HDNode.fromSeed(seedBuffer);
|
||||
* // to cash address
|
||||
* bchjs.SLP.HDNode.toSLPAddress(hdNode);
|
||||
* // simpleledger:qqxh2z2z397m4c6u9s5x6wjtku742q8rpvm6al2nrf
|
||||
*/
|
||||
toSLPAddress(hdNode) {
|
||||
const cashAddr = this.toCashAddress(hdNode)
|
||||
return bchaddrjs.toSlpAddress(cashAddr)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toWIF() toWIF() - Get private key in wallet import format (WIF) of HDNode.
|
||||
* @apiName toWIF
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Get private key in wallet import format (WIF) of HDNode.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to WIF
|
||||
* bchjs.HDNode.toWIF(hdNode);
|
||||
* // L5E8QjFnLukp8BuF4uu9gmvvSrbafioURGdBve5tA3Eq5ptzbMCJ
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to WIF
|
||||
* bchjs.HDNode.toWIF(hdNode);
|
||||
* // KwobPFhv3AuXc3ps6YtWfMVRpLBDBA7jnJddurfELTyTNcFhZYpJ
|
||||
*/
|
||||
toWIF(hdNode) {
|
||||
return hdNode.keyPair.toWIF()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toXPub() toXPub() - Get extended public key of HDNode.
|
||||
* @apiName toXPub
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Get extended public key of HDNode.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to extended public key
|
||||
* bchjs.HDNode.toXPub(hdNode);
|
||||
* // xpub661MyMwAqRbcG4CnhNYoK1r1TKLwQQ1UdC3LHoWFK61rsnzh7Hx35qQ9Z53ucYcE5WvA7GEDXhqqKjSY2e6Y8n7WNVLYHpXCuuX945VPuYn
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to extended public key
|
||||
* bchjs.HDNode.toXPub(hdNode);
|
||||
* // xpub661MyMwAqRbcFuMLeHkSbTNwNHG9MQyrAZqV1Q4MEAsmj9MYa5sxg8WC2LKqW6EHviHVucBjWi1n38juZpDDeX3U6YrsMeACdcNSTHkM8BQ
|
||||
*/
|
||||
toXPub(hdNode) {
|
||||
return hdNode.neutered().toBase58()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toXPriv() toXPriv() - Get extended private key of HDNode.
|
||||
* @apiName toXPriv
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Get extended private key of HDNode.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to extended private key
|
||||
* bchjs.HDNode.toXPriv(hdNode);
|
||||
* // xprv9s21ZrQH143K2eMCcbT4qwwRhw6qZaPaEDWB792bnrxQZPoP2JUk4kfEx9eeV1uGTAWAfCqYr4wDWo52qALiukizKwQzvEyNR1fWZJi97Kv
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // to extended private key
|
||||
* bchjs.HDNode.toXPriv(hdNode);
|
||||
* // xprv9s21ZrQH143K2b5GPP6zHz22E6LeCgQXJtwNbC3MA3Kz7Se7tveKo96EhqwFtSkYWkyenVcMqM7uq35PcUNG8cUdpsJEgwKG3dvfP7TmL3v
|
||||
*/
|
||||
toXPriv(hdNode) {
|
||||
return hdNode.toBase58()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toKeyPair() toKeyPair() - Get the ECPair of an HDNode.
|
||||
* @apiName toKeyPair
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Get the ECPair of an HDNode.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create root seed buffer from mnemonic
|
||||
* let rootSeed= bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from root seed
|
||||
* let hdNode = bchjs.HDNode.fromSeed(rootSeed);
|
||||
* // create public key buffer from HDNode
|
||||
* bchjs.HDNode.toKeyPair(hdNode);
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // create public key buffer from HDNode
|
||||
* bchjs.HDNode.toKeyPair(hdNode);
|
||||
*/
|
||||
toKeyPair(hdNode) {
|
||||
return hdNode.keyPair
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toPublicKey() toPublicKey() - Get the public key of an HDNode as a buffer.
|
||||
* @apiName toPublicKey
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Get the public key of an HDNode as a buffer.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create root seed buffer from mnemonic
|
||||
* let rootSeed= bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from root seed
|
||||
* let hdNode = bchjs.HDNode.fromSeed(rootSeed);
|
||||
* // create public key buffer from HDNode
|
||||
* bchjs.HDNode.toPublicKey(hdNode);
|
||||
* // <Buffer 03 86 d6 d3 db ec 1a 93 8c 2c a2 63 c9 79 8f eb e9 16 09 c5 a2 9b 07 65 c4 79 1f d9 0f fa 4d 27 20>
|
||||
*
|
||||
* // generate entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // create mnemonic from entropy
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // create public key buffer from HDNode
|
||||
* bchjs.HDNode.toPublicKey(hdNode);
|
||||
* // <Buffer 02 d2 26 74 6e 78 03 ac 11 e0 96 c6 24 de e8 dd 62 52 e7 8e 51 56 8a c1 18 62 aa 2a 72 50 1d ea 7d>
|
||||
*/
|
||||
toPublicKey(hdNode) {
|
||||
return hdNode.getPublicKeyBuffer()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.fromXPriv() fromXPriv() - Generate HDNode from extended private key.
|
||||
* @apiName fromXPriv
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Generate HDNode from extended private key.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet xpriv
|
||||
* bchjs.HDNode.fromXPriv('xprv9s21ZrQH143K2b5GPP6zHz22E6LeCgQXJtwNbC3MA3Kz7Se7tveKo96EhqwFtSkYWkyenVcMqM7uq35PcUNG8cUdpsJEgwKG3dvfP7TmL3v');
|
||||
*
|
||||
* // testnet xpriv
|
||||
* bchjs.HDNode.fromXPriv('tprv8gQ3zr1F5pRHMebqqhorrorYNvUG3XkcZjSWVs2cEtRwwJy1TRhgRx4XcF8dYHM2eyTbTCcdKYNhqgyBQphxwRoVyVKr9zuyoA8WxNDRvom');
|
||||
*/
|
||||
fromXPriv(xpriv) {
|
||||
let bitcoincash
|
||||
if (xpriv[0] === "x") bitcoincash = coininfo.bitcoincash.main
|
||||
else if (xpriv[0] === "t") bitcoincash = coininfo.bitcoincash.test
|
||||
|
||||
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
|
||||
return Bitcoin.HDNode.fromBase58(xpriv, bitcoincashBitcoinJSLib)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.fromXPub() fromXPub() - Generate HDNode from extended public key.
|
||||
* @apiName fromXPub
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Generate HDNode from extended public key.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet xpub
|
||||
* bchjs.HDNode.fromXPub('xpub661MyMwAqRbcFuMLeHkSbTNwNHG9MQyrAZqV1Q4MEAsmj9MYa5sxg8WC2LKqW6EHviHVucBjWi1n38juZpDDeX3U6YrsMeACdcNSTHkM8BQ');
|
||||
*
|
||||
* // testnet xpub
|
||||
* bchjs.HDNode.fromXPub('tpubDD669G3VEC6xF7ddjMUTGDWewwzCCrwX933HnP4ufAELmoDn5pXGcSgPnLodjFvWQwRXkG94f77BatEDA8dfQ99yy97kRYynUpNLENEqTBo');
|
||||
*/
|
||||
fromXPub(xpub) {
|
||||
let bitcoincash
|
||||
if (xpub[0] === "x") bitcoincash = coininfo.bitcoincash.main
|
||||
else if (xpub[0] === "t") bitcoincash = coininfo.bitcoincash.test
|
||||
|
||||
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
|
||||
return Bitcoin.HDNode.fromBase58(xpub, bitcoincashBitcoinJSLib)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.derivePath() derivePath() - Derive child HDNode from path.
|
||||
* @apiName derivePath
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Derive child HDNode from path
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // derive hardened child HDNode
|
||||
* bchjs.HDNode.derivePath(hdNode, "m/44'/145'/0'");
|
||||
*/
|
||||
derivePath(hdnode, path) {
|
||||
return hdnode.derivePath(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.derive() derive() - Derive non hardened child HDNode.
|
||||
* @apiName derive
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Derive non hardened child HDNode
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // derive unhardened child HDNode
|
||||
* bchjs.HDNode.derive(hdNode, 0);
|
||||
*/
|
||||
derive(hdnode, path) {
|
||||
return hdnode.derive(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.deriveHardened() deriveHardened() - Derive hardened child HDNode.
|
||||
* @apiName deriveHardened
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Derive hardened child HDNode
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create seed buffer from mnemonic
|
||||
* let seedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create HDNode from seed buffer
|
||||
* let hdNode = bchjs.HDNode.fromSeed(seedBuffer);
|
||||
* // derive hardened child HDNode
|
||||
* bchjs.HDNode.deriveHardened(hdNode, 0);
|
||||
*/
|
||||
deriveHardened(hdnode, path) {
|
||||
return hdnode.deriveHardened(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.sign() sign() - Sign 32 byte hash encoded as a buffer.
|
||||
* @apiName sign
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Sign 32 byte hash encoded as a buffer.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet xpriv
|
||||
* let xpriv = 'xprv9z2uWrGjbYPxc728rvtMi4jt4SudRiSfYn6Tdif5XN17pJ1NTbHoHK6JePkPLY1NHXLaQcA6sWudpZDm7DwKhbsGQieAp9wx46Wbio4iXg9';
|
||||
* // hdnode from xpriv
|
||||
* let hdnode = bchjs.HDNode.fromXPriv(xpriv);
|
||||
* // 32 byte buffer
|
||||
* let buf = Buffer.from(bchjs.Crypto.sha256('EARTH'), 'hex');
|
||||
* // sign
|
||||
* bchjs.HDNode.sign(hdnode, buf);
|
||||
*
|
||||
* // testnet xpriv
|
||||
* let xpriv = 'tprv8ggxJ8SG5EdqakzVUeLa9Gr7sqCdEcJPUNDmtdJscNxfmxoXvU36ZguiUWukJVEWEixAUr8pJabJkCt33wzxFQA587gqN51Lxdxx97zAzuG';
|
||||
* // hdnode from xpriv
|
||||
* let hdnode = bchjs.HDNode.fromXPriv(xpriv);
|
||||
* // 32 byte buffer
|
||||
* let buf = Buffer.from(bchjs.Crypto.sha256('EARTH'), 'hex');
|
||||
* // sign
|
||||
* bchjs.HDNode.sign(hdnode, buf);
|
||||
*/
|
||||
sign(hdnode, buffer) {
|
||||
return hdnode.sign(buffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.verify() verify() - Verify signed 32 byte hash encoded as a buffer.
|
||||
* @apiName verify
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Verify signed 32 byte hash encoded as a buffer.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet xprivs
|
||||
* let xpriv1 = 'xprv9ys4cvcoU8RoqvzxGj886r4Ey3w1WfVNYH8sMnVPVzyQtaPPM6Q8pHm3D9WPWvEupGEgcJ1xLaGaZDcvKfoAurE2AzHRRRup5FuHzDr8n15';
|
||||
* let xpriv2 = 'xprv9ys4cvcoU8RoxqkZ7Fgt33te4LPHgcsKwyoZYVorkzp9uonWxWgP9wiSQhPeBUqVHbdAyov4Yi55RywBkDfZKdJFRqA51Anz6v72zGaMGZp';
|
||||
* // hdnodes from xprivs
|
||||
* let hdnode1 = bchjs.HDNode.fromXPriv(xpriv1);
|
||||
* let hdnode2 = bchjs.HDNode.fromXPriv(xpriv2);
|
||||
* // 32 byte buffer
|
||||
* let buf = Buffer.from(bchjs.Crypto.sha256('EARTH'), 'hex');
|
||||
* // sign
|
||||
* let signature = bchjs.HDNode.sign(hdnode1, buf);
|
||||
* // verify
|
||||
* bchjs.HDNode.verify(hdnode1, buf, signature);
|
||||
* // true
|
||||
* bchjs.HDNode.verify(hdnode2, buf, signature);
|
||||
* // false
|
||||
*
|
||||
* // testnet xprivs
|
||||
* let xpriv1 = 'tprv8ggxJ8SG5EdqakzVUeLa9Gr7sqCdEcJPUNDmtdJscNxfmxoXvU36ZguiUWukJVEWEixAUr8pJabJkCt33wzxFQA587gqN51Lxdxx97zAzuG';
|
||||
* let xpriv2 = 'tprv8ggxJ8SG5EdqiM6Dn63QwHScQ7HS5hXqUMxSD1NEbDyPw6VtoUMFZBAohpTMsPz9cYbpHELmA4Zm79NKRvEvFdhWRX2bSmu7V7PiNb364nv';
|
||||
* // hdnodes from xprivs
|
||||
* let hdnode1 = bchjs.HDNode.fromXPriv(xpriv1);
|
||||
* let hdnode2 = bchjs.HDNode.fromXPriv(xpriv2);
|
||||
* // 32 byte buffer
|
||||
* let buf = Buffer.from(bchjs.Crypto.sha256('EARTH'), 'hex');
|
||||
* // sign
|
||||
* let signature = bchjs.ECPair.sign(hdnode1, buf);
|
||||
* // verify
|
||||
* bchjs.HDNode.verify(hdnode1, buf, signature);
|
||||
* // true
|
||||
* bchjs.HDNode.verify(hdnode2, buf, signature);
|
||||
* // false
|
||||
*/
|
||||
verify(hdnode, buffer, signature) {
|
||||
return hdnode.verify(buffer, signature)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.isPublic() isPublic() - Check if an HDNode can only derive public keys and children.
|
||||
* @apiName isPublic
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Check if an HDNode can only derive public keys and children
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet xpub
|
||||
* let xpub = 'xpub6DWfGUo4cjC8oWmgZdpyFMH6v3oeyADfdUPhsehzn5jX44zpazivha3JxUtkcCvBEB1c6DGaiUmpyz2m1DRfGDEVZ5VxLLW2UNEbZ5iTRvi';
|
||||
* let node = bchjs.HDNode.fromXPub(xpub);
|
||||
* bchjs.HDNode.isPublic(node);
|
||||
* // true
|
||||
*
|
||||
* // mainnet xpriv
|
||||
* let xpriv = 'xprv9ys4cvcoU8RoxqkZ7Fgt33te4LPHgcsKwyoZYVorkzp9uonWxWgP9wiSQhPeBUqVHbdAyov4Yi55RywBkDfZKdJFRqA51Anz6v72zGaMGZp';
|
||||
* let node = bchjs.HDNode.fromXPriv(xpriv);
|
||||
* bchjs.HDNode.isPublic(node);
|
||||
* // false
|
||||
*
|
||||
* // testnet xpub
|
||||
* let xpub = 'tpubDCxmZ3qLVVphg6NpsnAjQFqDPwr9HYqSgoAcUYAfqSgo32dL6NA8QXqWsS6XTjoGggohZKvujsAv2F2ugej9qfUYau2jSUB4JaYnfMsx3MJ';
|
||||
* let node = bchjs.HDNode.fromXPub(xpub);
|
||||
* bchjs.HDNode.isPublic(node);
|
||||
* // true
|
||||
*
|
||||
* // testnet xpriv
|
||||
* let xpriv = 'tprv8ggxJ8SG5EdqakzVUeLa9Gr7sqCdEcJPUNDmtdJscNxfmxoXvU36ZguiUWukJVEWEixAUr8pJabJkCt33wzxFQA587gqN51Lxdxx97zAzuG';
|
||||
* let node = bchjs.HDNode.fromXPriv(xpriv);
|
||||
* bchjs.HDNode.isPublic(node);
|
||||
* // false
|
||||
*/
|
||||
isPublic(hdnode) {
|
||||
return hdnode.isNeutered()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.isPrivate() isPrivate() - Check if an HDNode can derive both public and private keys and children.
|
||||
* @apiName isPrivate
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Check if an HDNode can derive both public and private keys and children
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet xpub
|
||||
* let xpub = 'xpub6DWfGUo4cjC8oWmgZdpyFMH6v3oeyADfdUPhsehzn5jX44zpazivha3JxUtkcCvBEB1c6DGaiUmpyz2m1DRfGDEVZ5VxLLW2UNEbZ5iTRvi';
|
||||
* let node = bchjs.HDNode.fromXPub(xpub);
|
||||
* bchjs.HDNode.isPrivate(node);
|
||||
* // false
|
||||
*
|
||||
* // mainnet xpriv
|
||||
* let xpriv = 'xprv9ys4cvcoU8RoxqkZ7Fgt33te4LPHgcsKwyoZYVorkzp9uonWxWgP9wiSQhPeBUqVHbdAyov4Yi55RywBkDfZKdJFRqA51Anz6v72zGaMGZp';
|
||||
* let node = bchjs.HDNode.fromXPriv(xpriv);
|
||||
* bchjs.HDNode.isPrivate(node);
|
||||
* // true
|
||||
*
|
||||
* // testnet xpub
|
||||
* let xpub = 'tpubDCxmZ3qLVVphg6NpsnAjQFqDPwr9HYqSgoAcUYAfqSgo32dL6NA8QXqWsS6XTjoGggohZKvujsAv2F2ugej9qfUYau2jSUB4JaYnfMsx3MJ';
|
||||
* let node = bchjs.HDNode.fromXPub(xpub);
|
||||
* bchjs.HDNode.isPrivate(node);
|
||||
* // false
|
||||
*
|
||||
* // testnet xpriv
|
||||
* let xpriv = 'tprv8ggxJ8SG5EdqakzVUeLa9Gr7sqCdEcJPUNDmtdJscNxfmxoXvU36ZguiUWukJVEWEixAUr8pJabJkCt33wzxFQA587gqN51Lxdxx97zAzuG';
|
||||
* let node = bchjs.HDNode.fromXPriv(xpriv);
|
||||
* bchjs.HDNode.isPrivate(node);
|
||||
* // true
|
||||
*/
|
||||
isPrivate(hdnode) {
|
||||
return !hdnode.isNeutered()
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.toIdentifier() toIdentifier() - hash160 of Node’s public key.
|
||||
* @apiName toIdentifier
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* hash160 of Node’s public key. The same value you would see in a scriptPubKey.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet
|
||||
* let xpub = 'xpub6DWfGUo4cjC8oWmgZdpyFMH6v3oeyADfdUPhsehzn5jX44zpazivha3JxUtkcCvBEB1c6DGaiUmpyz2m1DRfGDEVZ5VxLLW2UNEbZ5iTRvi';
|
||||
* let node = bchjs.HDNode.fromXPub(xpub);
|
||||
* bchjs.HDNode.toIdentifier(node);
|
||||
* // <Buffer cd d4 84 1d 2e 96 bf bf f7 9c d1 f4 a6 75 22 1c 7f 67 88 9c>
|
||||
* // the same as if we hash160ed it's publicKey
|
||||
* let publicKeyBuffer = bchjs.HDNode.toPublicKey(node);
|
||||
* bchjs.Crypto.hash160(publicKeyBuffer);
|
||||
* // <Buffer cd d4 84 1d 2e 96 bf bf f7 9c d1 f4 a6 75 22 1c 7f 67 88 9c>
|
||||
*
|
||||
* // testnet
|
||||
* let xpub = 'tpubDCxmZ3qLVVphg6NpsnAjQFqDPwr9HYqSgoAcUYAfqSgo32dL6NA8QXqWsS6XTjoGggohZKvujsAv2F2ugej9qfUYau2jSUB4JaYnfMsx3MJ';
|
||||
* let node = bchjs.HDNode.fromXPub(xpub);
|
||||
* bchjs.HDNode.toIdentifier(node);
|
||||
* // <Buffer e1 8e 20 e3 f8 f1 c0 53 e6 1f 9e 3a 58 8e 71 f5 0b 8d 2d c4>
|
||||
* // the same as if we hash160ed it's publicKey
|
||||
* let publicKeyBuffer = bchjs.HDNode.toPublicKey(node);
|
||||
* bchjs.Crypto.hash160(publicKeyBuffer);
|
||||
* // <Buffer e1 8e 20 e3 f8 f1 c0 53 e6 1f 9e 3a 58 8e 71 f5 0b 8d 2d c4>
|
||||
*/
|
||||
toIdentifier(hdnode) {
|
||||
return hdnode.getIdentifier()
|
||||
}
|
||||
|
||||
fromBase58(base58, network) {
|
||||
return Bitcoin.HDNode.fromBase58(base58, network)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api HDNode.createAccount() createAccount() - Create BIP32 account.
|
||||
* @apiName createAccount
|
||||
* @apiGroup HDNode
|
||||
* @apiDescription
|
||||
* Has getChainAddress and nextChainAddress helper methods.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create mnemonic
|
||||
* let mnemonic = bchjs.Mnemonic.generate(128);
|
||||
* // create root seed buffer
|
||||
* let rootSeedBuffer = bchjs.Mnemonic.toSeed(mnemonic);
|
||||
* // create master hd node
|
||||
* let masterHDNode = bchjs.HDNode.fromSeed(rootSeedBuffer);
|
||||
* // derive child node
|
||||
* let childNode = masterHDNode.derivePath("m/44'/145'/0'/0");
|
||||
* // create account
|
||||
* let account = bchjs.HDNode.createAccount([childNode]);
|
||||
*/
|
||||
createAccount(hdNodes) {
|
||||
const arr = hdNodes.map(
|
||||
(item, index) => new bip32utils.Chain(item.neutered())
|
||||
)
|
||||
return new bip32utils.Account(arr)
|
||||
}
|
||||
|
||||
createChain(hdNode) {
|
||||
return new bip32utils.Chain(hdNode)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = HDNode
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
/*
|
||||
This library interacts with the IPFS REST API at FullStack.cash for uploading
|
||||
and downloading data from the IPFS network.
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
const Uppy = require("@uppy/core")
|
||||
const Tus = require("@uppy/tus")
|
||||
const fs = require("fs")
|
||||
|
||||
let _this
|
||||
|
||||
class IPFS {
|
||||
constructor(config) {
|
||||
this.IPFS_API = process.env.IPFS_API
|
||||
? process.env.IPFS_API
|
||||
: // : `http://localhost:5001`
|
||||
`https://ipfs-api.fullstack.cash`
|
||||
|
||||
// Default options when calling axios.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
// authorization: `Token ${this.apiToken}`,
|
||||
timeout: 15000 // Timeout if the server does not respond in time.
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
|
||||
_this.axios = axios
|
||||
_this.fs = fs
|
||||
|
||||
// Initialize Uppy
|
||||
_this.uppy = _this.initUppy()
|
||||
}
|
||||
|
||||
// Initializes Uppy, which is used for file uploads.
|
||||
initUppy() {
|
||||
const uppy = Uppy({
|
||||
allowMultipleUploads: false,
|
||||
meta: { test: "avatar" },
|
||||
debug: false,
|
||||
restrictions: {
|
||||
maxFileSize: null,
|
||||
maxNumberOfFiles: 1,
|
||||
minNumberOfFiles: 1,
|
||||
allowedFileTypes: null //type of files allowed to load
|
||||
}
|
||||
})
|
||||
uppy.use(Tus, { endpoint: `${_this.IPFS_API}/uppy-files` })
|
||||
|
||||
return uppy
|
||||
}
|
||||
|
||||
/**
|
||||
* @api IPFS.createFileModel() createFileModel() - Create a file model
|
||||
* @apiName createFileModel()
|
||||
* @apiGroup IPFS
|
||||
* @apiDescription Creates a new model on the server. If successful, will
|
||||
* return an object with file data. That object contains a BCH address,
|
||||
* payment amount, and _id required to be able to upload a file.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* const path = `${__dirname}/ipfs.js`
|
||||
* let fileData = await bchjs.IPFS.uploadFile(path);
|
||||
* console.log(fileData);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* {
|
||||
* "success": true,
|
||||
* "hostingCostBCH": 0.00004197,
|
||||
* "hostingCostUSD": 0.01,
|
||||
* "file": {
|
||||
* "payloadLink": "",
|
||||
* "hasBeenPaid": false,
|
||||
* "_id": "5ec562319bfacc745e8d8a52",
|
||||
* "schemaVersion": 1,
|
||||
* "size": 4458,
|
||||
* "fileName": "ipfs.js",
|
||||
* "fileExtension": "js",
|
||||
* "createdTimestamp": "1589994033.655",
|
||||
* "hostingCost": 4196,
|
||||
* "walletIndex": 49,
|
||||
* "bchAddr": "bchtest:qzrpkevu7h2ayfa4rjx08r5elvpfu72dg567x3mh3c",
|
||||
* "__v": 0
|
||||
* }
|
||||
*/
|
||||
async createFileModel(path) {
|
||||
try {
|
||||
// Ensure the file exists.
|
||||
if (!_this.fs.existsSync(path))
|
||||
throw new Error(`Could not find this file: ${path}`)
|
||||
|
||||
// Read in the file.
|
||||
const fileBuf = _this.fs.readFileSync(path)
|
||||
// console.log(`fileBuf: `, fileBuf)
|
||||
|
||||
// console.log(`Buffer length: ${fileBuf.length}`)
|
||||
|
||||
// Get the file name from the path.
|
||||
const splitPath = path.split("/")
|
||||
const fileName = splitPath[splitPath.length - 1]
|
||||
|
||||
// Get the file extension.
|
||||
const splitExt = fileName.split(".")
|
||||
const fileExt = splitExt[splitExt.length - 1]
|
||||
|
||||
const fileObj = {
|
||||
schemaVersion: 1,
|
||||
size: fileBuf.length,
|
||||
fileName: fileName,
|
||||
fileExtension: fileExt
|
||||
}
|
||||
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)
|
||||
|
||||
const fileData = await _this.axios.post(`${this.IPFS_API}/files`, {
|
||||
file: fileObj
|
||||
})
|
||||
// console.log(`fileData.data: ${JSON.stringify(fileData.data, null, 2)}`)
|
||||
|
||||
return fileData.data
|
||||
} catch (err) {
|
||||
console.error(`Error in createFileModel()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api IPFS.uploadFile() uploadFile() - Upload a file to IPFS
|
||||
* @apiName uploadFile()
|
||||
* @apiGroup IPFS
|
||||
* @apiDescription Upload a file to the FullStack.cash IPFS server. If
|
||||
* successful, it will return an object with an ID, a BCH address, and an
|
||||
* amount of BCH to pay.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* const path = `${__dirname}/ipfs.js`
|
||||
* let fileData = await bchjs.IPFS.uploadFile(path, "5ec562319bfacc745e8d8a52");
|
||||
* console.log(fileData);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* {
|
||||
* "schemaVersion": 1,
|
||||
* "size": 2374,
|
||||
* "fileId": "5ec562319bfacc745e8d8a52",
|
||||
* "fileName": "ipfs.js",
|
||||
* "fileExtension": "js"
|
||||
* }
|
||||
*/
|
||||
async uploadFile(path, modelId) {
|
||||
try {
|
||||
// Ensure the file exists.
|
||||
if (!_this.fs.existsSync(path))
|
||||
throw new Error(`Could not find this file: ${path}`)
|
||||
|
||||
if (!modelId) {
|
||||
throw new Error(
|
||||
`Must include a file model ID in order to upload a file.`
|
||||
)
|
||||
}
|
||||
|
||||
// Read in the file.
|
||||
const fileBuf = _this.fs.readFileSync(path)
|
||||
|
||||
// Get the file name from the path.
|
||||
const splitPath = path.split("/")
|
||||
const fileName = splitPath[splitPath.length - 1]
|
||||
|
||||
// Prepare the upload object. Get a file ID from Uppy.
|
||||
const id = _this.uppy.addFile({
|
||||
name: fileName,
|
||||
data: fileBuf,
|
||||
source: "Local",
|
||||
isRemote: false
|
||||
})
|
||||
// console.log(`id: ${JSON.stringify(id, null, 2)}`)
|
||||
|
||||
// Add the model ID, required to be allowed to upload the file.
|
||||
_this.uppy.setFileMeta(id, { fileModelId: modelId })
|
||||
|
||||
// Upload the file to the server.
|
||||
const upData = await _this.uppy.upload()
|
||||
|
||||
if (upData.failed.length)
|
||||
throw new Error("The file could not be uploaded")
|
||||
|
||||
if (upData.successful.length) {
|
||||
delete upData.successful[0].data
|
||||
// console.log(`upData: ${JSON.stringify(upData, null, 2)}`)
|
||||
|
||||
const fileObj = {
|
||||
schemaVersion: 1,
|
||||
size: upData.successful[0].progress.bytesTotal,
|
||||
fileId: upData.successful[0].meta.fileModelId,
|
||||
fileName: upData.successful[0].name,
|
||||
fileExtension: upData.successful[0].extension
|
||||
}
|
||||
// console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)
|
||||
|
||||
return fileObj
|
||||
// return true
|
||||
}
|
||||
|
||||
return false
|
||||
} catch (err) {
|
||||
console.error(`Error in bch-js/src/ipfs.js/upload(): `)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api IPFS.getStatus() getStatus() - Check status of file upload
|
||||
* @apiName getStatus()
|
||||
* @apiGroup IPFS
|
||||
* @apiDescription Gets the status of the uploaded file. Will return an object
|
||||
* that indicates the payment status. If the file is paid, it should contain
|
||||
* an IPFS hash.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* const modelId = "5ec7392c2acfe57aa62e945a"
|
||||
* let fileData = await bchjs.IPFS.getStatus(modelId)
|
||||
* console.log(fileData)
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* {
|
||||
* "hasBeenPaid": true,
|
||||
* "satCost": 4403,
|
||||
* "bchAddr": "bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk",
|
||||
* "ipfsHash": "QmRDHPhY5hCNVRMVQvS2H9uty8P1skdwgLaHpUAkEvsjcE",
|
||||
* "fileId": "5ec7392c2acfe57aa62e945a",
|
||||
* "fileName": "ipfs-e2e.js"
|
||||
* }
|
||||
*/
|
||||
async getStatus(modelId) {
|
||||
try {
|
||||
if (!modelId) throw new Error(`Must include a file model ID.`)
|
||||
|
||||
const fileData = await _this.axios.get(
|
||||
`${this.IPFS_API}/files/${modelId}`
|
||||
)
|
||||
// console.log(`fileData.data: ${JSON.stringify(fileData.data, null, 2)}`)
|
||||
|
||||
const fileObj = {
|
||||
hasBeenPaid: fileData.data.file.hasBeenPaid,
|
||||
satCost: fileData.data.file.hostingCost,
|
||||
bchAddr: fileData.data.file.bchAddr,
|
||||
ipfsHash: fileData.data.file.payloadLink,
|
||||
fileId: fileData.data.file._id,
|
||||
fileName: fileData.data.file.fileName
|
||||
}
|
||||
|
||||
return fileObj
|
||||
} catch (err) {
|
||||
console.error(`Error in getStatus()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = IPFS
|
||||
@@ -0,0 +1,73 @@
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class Mining {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
async getBlockTemplate(template_request) {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}mining/getBlockTemplate/${template_request}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getMiningInfo() {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}mining/getMiningInfo`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getNetworkHashps(nblocks = 120, height = 1) {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}mining/getNetworkHashps?nblocks=${nblocks}&height=${height}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
async submitBlock(hex, parameters) {
|
||||
let path = `${this.restURL}mining/submitBlock/${hex}`
|
||||
if (parameters) path = `${path}?parameters=${parameters}`
|
||||
|
||||
try {
|
||||
const response = await axios.post(path, _this.axiosOptions)
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Mining
|
||||
+516
@@ -0,0 +1,516 @@
|
||||
const BIP39 = require("bip39")
|
||||
const randomBytes = require("randombytes")
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
const Buffer = require("safe-buffer").Buffer
|
||||
const wif = require("wif")
|
||||
|
||||
class Mnemonic {
|
||||
constructor(address) {
|
||||
this._address = address
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.generate() generate() - Generate BIP39 mnemonic from entropy.
|
||||
* @apiName generate
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Generate BIP39 mnemonic from entropy.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // generate 12 word mnemonic
|
||||
* bchjs.Mnemonic.generate(128);
|
||||
* // boil lonely casino manage habit where total glory muffin name limit mansion
|
||||
*
|
||||
* // generate 15 word mnemonic
|
||||
* bchjs.Mnemonic.generate(160);
|
||||
* // steak prevent estate save dance design close noise cheap season among train sleep ketchup gas
|
||||
*
|
||||
* // generate 18 word mnemonic
|
||||
* bchjs.Mnemonic.generate(192);
|
||||
* // fever endorse purpose normal fashion desert blood robust prevent clean guard display raise virtual again unit banana rich
|
||||
*
|
||||
* // generate 21 word mnemonic
|
||||
* bchjs.Mnemonic.generate(224);
|
||||
* // scan pink shock describe chicken edit budget exit camera morning awesome silk inner pair sea few flock walnut write mountain surface
|
||||
*
|
||||
* // generate 24 word mnemonic
|
||||
* bchjs.Mnemonic.generate(256);
|
||||
* // disagree tide elbow citizen jazz cinnamon bridge certain april settle pact film always inmate border inform solution that submit produce cloth balcony upper maid
|
||||
*
|
||||
* // generate 12 french word mnemonic
|
||||
* bchjs.Mnemonic.generate(128, bitbox.Mnemonic.wordLists().french);
|
||||
* // annonce ampleur sanglier peser acheter cultiver abroger embellir résoudre dialogue grappin lanterne
|
||||
*
|
||||
* // generate 256 bit korean word mnemonic
|
||||
* bchjs.Mnemonic.generate(256, bitbox.Mnemonic.wordLists().korean)
|
||||
* // 기능 단추 교육 비난 시집 근육 운동 코미디 숟가락 과목 한동안 유적 시리즈 삼월 앞날 유난히 흰색 사실 논문 장사 어른 논문 의논 장차
|
||||
*/
|
||||
generate(bits = 128, wordlist) {
|
||||
return BIP39.generateMnemonic(bits, randomBytes, wordlist)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.fromEntropy() fromEntropy() - Create mnemonic from entropy.
|
||||
* @apiName fromEntropy
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Create mnemonic from entropy.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // generate 16 bytes of entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(16);
|
||||
* //
|
||||
* // turn entropy to 12 word mnemonic
|
||||
* bchjs.Mnemonic.fromEntropy(entropy)
|
||||
* // security question relief cruel nephew jump chest copper axis assist gift correct
|
||||
*
|
||||
* // generate 20 bytes of entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(20);
|
||||
* //
|
||||
* // turn entropy to 15 word mnemonic
|
||||
* bchjs.Mnemonic.fromEntropy(entropy)
|
||||
* // impact hub pattern turkey cruel adult short moment make toe one actress roast yellow hurt
|
||||
*
|
||||
* // generate 24 bytes of entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(24);
|
||||
* //
|
||||
* // turn entropy to 18 word mnemonic
|
||||
* bchjs.Mnemonic.fromEntropy(entropy)
|
||||
* // bid quantum chronic marriage swing affair record amateur enhance heart object mind spoon speak toast piece chef real
|
||||
*
|
||||
* // generate 28 bytes of entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(28);
|
||||
* //
|
||||
* // turn entropy to 21 word mnemonic
|
||||
* bchjs.Mnemonic.fromEntropy(entropy)
|
||||
* // orchard rural giant okay tape pipe luggage clap bring wear ticket slot fiscal seminar crazy robot distance current dizzy swarm barrel
|
||||
*
|
||||
* // generate 32 bytes of entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* //
|
||||
* // turn entropy to 24 word mnemonic
|
||||
* bchjs.Mnemonic.fromEntropy(entropy)
|
||||
* // vibrant solution level obtain cheap damage october giant chalk cushion assist fossil spawn artist rice edit proof hotel process survey gas sausage mouse property
|
||||
*
|
||||
* // generate 16 bytes of entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(16);
|
||||
* //
|
||||
* // turn entropy to 12 japanese word mnemonic
|
||||
* bchjs.Mnemonic.fromEntropy(entropy.toString('hex'), bchjs.Mnemonic.wordLists().japanese)
|
||||
* // ぱそこん にあう にんめい きどく ちそう せんきょ かいが きおく いれる いねむり しいく きかんしゃ
|
||||
*/
|
||||
fromEntropy(bytes, wordlist) {
|
||||
return BIP39.entropyToMnemonic(bytes, wordlist)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.toEntropy() toEntropy() - Turn mnemonic to entropy.
|
||||
* @apiName toEntropy
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Turn mnemonic to entropy.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // turn 12 word mnemonic to entropy
|
||||
* let mnemonic = 'security question relief cruel nephew jump chest copper axis assist gift correct';
|
||||
* bchjs.Mnemonic.toEntropy(mnemonic)
|
||||
* // <Buffer c2 d5 f2 d5 1a 49 44 f1 c9 e1 7f 10 e1 b9 87 18>
|
||||
*
|
||||
* // turn 15 word mnemonic to entropy
|
||||
* let mnemonic = 'impact hub pattern turkey cruel adult short moment make toe one actress roast yellow hurt';
|
||||
* bchjs.Mnemonic.toEntropy(mnemonic)
|
||||
* // <Buffer 71 cd d2 85 75 53 48 07 b1 b4 77 86 9c 72 6a 81 6b b1 fe 1b>
|
||||
*
|
||||
* // turn 18 word mnemonic to entropy
|
||||
* let mnemonic = 'bid quantum chronic marriage swing affair record amateur enhance heart object mind spoon speak toast piece chef real';
|
||||
* bchjs.Mnemonic.toEntropy(mnemonic)
|
||||
* // <Buffer 16 15 e8 a1 c4 2d c0 08 ac f0 3d 4a 8d 4a 60 46 7d 29 a1 b8 c5 23 27 56>
|
||||
*
|
||||
* // turn 21 word mnemonic to entropy
|
||||
* let mnemonic = 'orchard rural giant okay tape pipe luggage clap bring wear ticket slot fiscal seminar crazy robot distance current dizzy swarm barrel';
|
||||
* bchjs.Mnemonic.toEntropy(mnemonic)
|
||||
* // <Buffer 9c 17 b1 86 cc fd dd 4a a1 31 4e 1c 3f 0f 86 e6 05 79 87 0c b5 d9 3f a6 c1 00 ed b1>
|
||||
*
|
||||
* // turn 24 word mnemonic to entropy
|
||||
* let mnemonic = 'vibrant solution level obtain cheap damage october giant chalk cushion assist fossil spawn artist rice edit proof hotel process survey gas sausage mouse property';
|
||||
* bchjs.Mnemonic.toEntropy(mnemonic)
|
||||
* // <Buffer f3 79 da 02 cc 42 6e 6e 26 43 0d 25 e6 cc 37 2d fd 0a 1a 2e 4a 33 ac 4d c6 ae 6d 56 01 7f 64 2d>
|
||||
*/
|
||||
toEntropy(mnemonic, wordlist) {
|
||||
return Buffer.from(BIP39.mnemonicToEntropy(mnemonic, wordlist), "hex")
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.validate() validate() - Validate mnemonic.
|
||||
* @apiName validate
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Validate mnemonic.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* bchjs.Mnemonic.validate('ca', bchjs.Mnemonic.wordLists().english)
|
||||
* // ca is not in wordlist, did you mean cabbage?
|
||||
*
|
||||
* bchjs.Mnemonic.validate('boil lonely casino manage habit where total glory muffin name limit mansion', bitbox.Mnemonic.wordLists().english)
|
||||
* // Valid mnemonic
|
||||
*
|
||||
* bchjs.Mnemonic.validate('boil lonely casino manage habit where total glory muffin name limit mansion boil lonely casino manage habit where total glory muffin name limit mansion', bitbox.Mnemonic.wordLists().english)
|
||||
* // Invalid mnemonic
|
||||
*/
|
||||
validate(mnemonic, wordlist) {
|
||||
// Preprocess the words
|
||||
const words = mnemonic.split(" ")
|
||||
// Detect blank phrase
|
||||
if (words.length === 0) return "Blank mnemonic"
|
||||
|
||||
// Check each word
|
||||
for (let i = 0; i < words.length; i++) {
|
||||
const word = words[i]
|
||||
if (wordlist.indexOf(word) === -1) {
|
||||
// Finding closest match to word
|
||||
const nearestWord = this.findNearestWord(word, wordlist)
|
||||
return `${word} is not in wordlist, did you mean ${nearestWord}?`
|
||||
}
|
||||
}
|
||||
// Check the words are valid
|
||||
//const properPhrase = words.join()
|
||||
const isValid = BIP39.validateMnemonic(mnemonic, wordlist)
|
||||
if (!isValid) return "Invalid mnemonic"
|
||||
|
||||
return "Valid mnemonic"
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.toSeed() toSeed() - Create root seed from mnemonic
|
||||
* @apiName toSeed
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Create root seed from mnemonic. Returns a Promise.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* await bchjs.Mnemonic.toSeed('enable stem left method one submit coach bid inspire cluster armed bracket')
|
||||
* // <Buffer 0a fa b7 46 8f 0c df 79 0f 0e 44 37 45 0c 33 c3 c8 27 17 42 75 d6 13 02 c3 55 de ef 2e 69 57 e4 f5 dd 55 b6 a8 73 78 6d b8 09 36 75 af 4f 6b 2c 52 63 ... >
|
||||
*
|
||||
* await bchjs.Mnemonic.toSeed('vendor talk alone sick balance tissue number armor frequent plug transfer chest', 'password');
|
||||
* // <Buffer 2d a5 46 52 36 a4 1c 90 bf c5 38 c9 78 16 03 26 1f 70 7c 67 44 aa e0 97 fa 96 1b a1 23 16 a0 e2 0c f6 ac b6 09 cc 2f af 9a 99 50 b3 f9 a9 be c9 f4 19 ... >
|
||||
*
|
||||
* await bchjs.Mnemonic.toSeed('idea relax weird defense body bronze champion ancient vocal peanut similar dose grit company peasant gate sunset deal library act include penalty annual main', '');
|
||||
* // <Buffer c1 56 36 5b 0f 2a 16 04 dd 6f 53 ad 7d 0a 4c 14 ba 38 f9 81 fb 18 0f df c3 14 6e 6a fc d8 af 2f 1f c4 2c b2 d3 65 8a 31 2e a8 48 59 12 bd f0 f1 8d e4 ... >
|
||||
*
|
||||
* await bchjs.Mnemonic.toSeed('bus aware census desk orphan zebra fashion host try muscle pig close jealous slice elegant prison reject ship great program trumpet syrup tray remove', '');
|
||||
* // <Buffer f4 2c e8 e1 88 d1 5a 66 5c 18 c0 cf ae df 09 3c 75 d2 4c 47 9d 52 87 f4 be c0 6b 13 e7 da 04 01 a3 50 36 87 22 1f ee cf c8 57 e8 6e ae bb 17 4b 83 60 ... >
|
||||
*
|
||||
* await bchjs.Mnemonic.toSeed('frost deliver coin clutch upon round scene wonder various wise luggage country', 'yayayayay');
|
||||
* // <Buffer 1d 00 9f a3 a8 86 51 a4 04 d5 03 3d eb 6d b1 01 e2 f1 3b c3 c8 6d 1f b9 93 b4 d1 33 dc 84 21 12 2c 9b 52 10 ba d8 96 15 e0 b0 9a 34 33 52 f8 07 c8 c4 ... >
|
||||
*/
|
||||
toSeed(mnemonic, password = "") {
|
||||
return BIP39.mnemonicToSeed(mnemonic, password)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.wordLists() wordLists() - Return mnemonic word lists.
|
||||
* @apiName wordLists
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Return mnemonic word lists.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* bchjs.Mnemonic.wordLists();
|
||||
* // {
|
||||
* // EN: [],
|
||||
* // JA: [],
|
||||
* // chinese_simplified: [],
|
||||
* // chinese_traditional: [],
|
||||
* // english: [],
|
||||
* // french: [],
|
||||
* // italian: [],
|
||||
* // japanese: [],
|
||||
* // korean: [],
|
||||
* // spanish: []
|
||||
* // }
|
||||
*/
|
||||
wordLists() {
|
||||
return BIP39.wordlists
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.toKeypairs() toKeypairs() - Returns an array of privateKeyWIF/publicAddress pairs.
|
||||
* @apiName toKeypairs
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Returns an array of privateKeyWIF/publicAddress pairs. It generates the addresses as the nth external change address of the first account from that mnemonic w/ this derivation path: m/44’/145’/0’/0/n
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // First create a mnemonic from 32 bytes of random entropy
|
||||
* let entropy = bchjs.Crypto.randomBytes(32);
|
||||
* // <Buffer bd 94 ad 86 be 19 5e 6c 51 b1 aa 52 b3 61 0b f8 9a 5d db 43 ac ee 8a ea 3a 38 6c ac 75 9e b5 42>
|
||||
* let mnemonic = bchjs.Mnemonic.fromEntropy(entropy);
|
||||
* // rural pistol giant label nominee curtain egg crystal famous only drill van place unit attitude oven memory fade mix sun shrug soon steak easily
|
||||
*
|
||||
* // Then call toKeypairs and pass in your mnemonic and how many keypairs you'd like
|
||||
* bchjs.Mnemonic.toKeypairs(mnemonic, 5)
|
||||
* // [ { privateKeyWIF: 'KwuSgSuV6m3U1oahRQEhSQ6e4gRE6LZXNGDTETGPGotKQJdH7ADd',
|
||||
* // address: 'bitcoincash:qqvk7aculs8r6t29pj23de35t43tupks2ua6wmc2hy' },
|
||||
* // { privateKeyWIF: 'L34pfoBm2swLBX5vAx1ReeYbSnpsvu7DRVaiLW8e9wNEJw5p3mV5',
|
||||
* // address: 'bitcoincash:qzt8ju6au2075cpzrhzwe5n96ycqnurarur5k92nd5' },
|
||||
* // { privateKeyWIF: 'L2nCRgDzmTRrQzSssFvVA7xiYHBJyfj62jdDwu1bTjHKVoLGxsqs',
|
||||
* // address: 'bitcoincash:qpdjwtyvqqaapykxr3pr6cty4gpww30aucam9l0qzn' },
|
||||
* // { privateKeyWIF: 'KyDLLa4RZKhnBP78Ue6557B55Jmffu1y8mH8p8WKA12knJUjiq4u',
|
||||
* // address: 'bitcoincash:qq8kee4k4h9fn22xya9p5u203vg69aat3usqdvkdkn' },
|
||||
* // { privateKeyWIF: 'L5gB66JqhfouEtZG5aRMQ9JaVS2ggkK3YozGfzZegBupaPXqdfaz',
|
||||
* // address: 'bitcoincash:qphwlpu2wzjxrjts94pn4wh778fwsu2afg2aj5her9' } ]
|
||||
*/
|
||||
async toKeypairs(mnemonic, numberOfKeypairs = 1, regtest = false) {
|
||||
const rootSeedBuffer = await this.toSeed(mnemonic, "")
|
||||
const hdNode = Bitcoin.HDNode.fromSeedBuffer(rootSeedBuffer)
|
||||
const HDPath = `44'/145'/0'/0/`
|
||||
|
||||
const accounts = []
|
||||
|
||||
for (let i = 0; i < numberOfKeypairs; i++) {
|
||||
const childHDNode = hdNode.derivePath(`${HDPath}${i}`)
|
||||
|
||||
let prefix = 128
|
||||
if (regtest === true) prefix = 239
|
||||
|
||||
accounts.push({
|
||||
privateKeyWIF: wif.encode(
|
||||
prefix,
|
||||
childHDNode.keyPair.d.toBuffer(32),
|
||||
true
|
||||
),
|
||||
address: this._address.toCashAddress(
|
||||
childHDNode.getAddress(),
|
||||
true,
|
||||
regtest
|
||||
)
|
||||
})
|
||||
}
|
||||
return accounts
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Mnemonic.findNearestWord() findNearestWord() - Returns nearest matching word from provided word list.
|
||||
* @apiName findNearestWord
|
||||
* @apiGroup Mnemonic
|
||||
* @apiDescription
|
||||
* Returns nearest matching word from provided word list.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // english
|
||||
* let word = 'ab';
|
||||
* let wordlist = bchjs.Mnemonic.wordLists().english;
|
||||
* bchjs.Mnemonic.findNearestWord(word, wordlist);
|
||||
* // abandon
|
||||
*
|
||||
* // french
|
||||
* let word = 'octu';
|
||||
* let wordlist = bchjs.Mnemonic.wordLists().french;
|
||||
* bchjs.Mnemonic.findNearestWord(word, wordlist);
|
||||
* // octupler
|
||||
*
|
||||
* // spanish
|
||||
* let word = 'foobaro';
|
||||
* let wordlist = bchjs.Mnemonic.wordLists().spanish;
|
||||
* bchjs.Mnemonic.findNearestWord(word, wordlist);
|
||||
* // forro
|
||||
*
|
||||
* // italian
|
||||
* let word = 'nv';
|
||||
* let wordlist = bchjs.Mnemonic.wordLists().italian;
|
||||
* bchjs.Mnemonic.findNearestWord(word, wordlist);
|
||||
* // neve
|
||||
*/
|
||||
findNearestWord(word, wordlist) {
|
||||
let minDistance = 99
|
||||
let closestWord = wordlist[0]
|
||||
for (let i = 0; i < wordlist.length; i++) {
|
||||
const comparedTo = wordlist[i]
|
||||
if (comparedTo.indexOf(word) === 0) return comparedTo
|
||||
|
||||
const distance = Levenshtein.get(word, comparedTo)
|
||||
if (distance < minDistance) {
|
||||
closestWord = comparedTo
|
||||
minDistance = distance
|
||||
}
|
||||
}
|
||||
return closestWord
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Mnemonic
|
||||
|
||||
// The following code is from: https://raw.githubusercontent.com/iancoleman/bip39/7ff86d4c983f1e8c80b87b31acfd69fcf98c1b82/src/js/levenshtein.js
|
||||
|
||||
/**
|
||||
* Extend an Object with another Object's properties.
|
||||
*
|
||||
* The source objects are specified as additional arguments.
|
||||
*
|
||||
* @param dst Object the object to extend.
|
||||
*
|
||||
* @return Object the final object.
|
||||
*/
|
||||
|
||||
const _extend = function(dst) {
|
||||
const sources = Array.prototype.slice.call(arguments, 1)
|
||||
for (let i = 0; i < sources.length; ++i) {
|
||||
const src = sources[i]
|
||||
for (const p in src) if (src.hasOwnProperty(p)) dst[p] = src[p]
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
/**
|
||||
* Defer execution of given function.
|
||||
* @param {Function} func
|
||||
*/
|
||||
const _defer = function(func) {
|
||||
if (typeof setImmediate === "function") return setImmediate(func)
|
||||
|
||||
return setTimeout(func, 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance.
|
||||
*/
|
||||
var Levenshtein = {
|
||||
/**
|
||||
* Calculate levenshtein distance of the two strings.
|
||||
*
|
||||
* @param str1 String the first string.
|
||||
* @param str2 String the second string.
|
||||
* @return Integer the levenshtein distance (0 and above).
|
||||
*/
|
||||
get: function(str1, str2) {
|
||||
// base cases
|
||||
if (str1 === str2) return 0
|
||||
if (str1.length === 0) return str2.length
|
||||
if (str2.length === 0) return str1.length
|
||||
|
||||
// two rows
|
||||
const prevRow = new Array(str2.length + 1)
|
||||
let curCol, nextCol, i, j, tmp
|
||||
|
||||
// initialise previous row
|
||||
for (i = 0; i < prevRow.length; ++i) prevRow[i] = i
|
||||
|
||||
// calculate current row distance from previous row
|
||||
for (i = 0; i < str1.length; ++i) {
|
||||
nextCol = i + 1
|
||||
|
||||
for (j = 0; j < str2.length; ++j) {
|
||||
curCol = nextCol
|
||||
|
||||
// substution
|
||||
nextCol = prevRow[j] + (str1.charAt(i) === str2.charAt(j) ? 0 : 1)
|
||||
// insertion
|
||||
tmp = curCol + 1
|
||||
if (nextCol > tmp) nextCol = tmp
|
||||
|
||||
// deletion
|
||||
tmp = prevRow[j + 1] + 1
|
||||
if (nextCol > tmp) nextCol = tmp
|
||||
|
||||
// copy current col value into previous (in preparation for next iteration)
|
||||
prevRow[j] = curCol
|
||||
}
|
||||
|
||||
// copy last col value into previous (in preparation for next iteration)
|
||||
prevRow[j] = nextCol
|
||||
}
|
||||
|
||||
return nextCol
|
||||
},
|
||||
|
||||
/**
|
||||
* Asynchronously calculate levenshtein distance of the two strings.
|
||||
*
|
||||
* @param str1 String the first string.
|
||||
* @param str2 String the second string.
|
||||
* @param cb Function callback function with signature: function(Error err, int distance)
|
||||
* @param [options] Object additional options.
|
||||
* @param [options.progress] Function progress callback with signature: function(percentComplete)
|
||||
*/
|
||||
getAsync: function(str1, str2, cb, options) {
|
||||
options = _extend(
|
||||
{},
|
||||
{
|
||||
progress: null
|
||||
},
|
||||
options
|
||||
)
|
||||
|
||||
// base cases
|
||||
if (str1 === str2) return cb(null, 0)
|
||||
if (str1.length === 0) return cb(null, str2.length)
|
||||
if (str2.length === 0) return cb(null, str1.length)
|
||||
|
||||
// two rows
|
||||
const prevRow = new Array(str2.length + 1)
|
||||
let curCol, nextCol, i, j, tmp, startTime, currentTime
|
||||
|
||||
// initialise previous row
|
||||
for (i = 0; i < prevRow.length; ++i) prevRow[i] = i
|
||||
|
||||
nextCol = 1
|
||||
i = 0
|
||||
j = -1
|
||||
|
||||
var __calculate = function() {
|
||||
// reset timer
|
||||
startTime = new Date().valueOf()
|
||||
currentTime = startTime
|
||||
|
||||
// keep going until one second has elapsed
|
||||
while (currentTime - startTime < 1000) {
|
||||
// reached end of current row?
|
||||
if (str2.length <= ++j) {
|
||||
// copy current into previous (in preparation for next iteration)
|
||||
prevRow[j] = nextCol
|
||||
|
||||
// if already done all chars
|
||||
if (str1.length <= ++i) return cb(null, nextCol)
|
||||
|
||||
// else if we have more left to do
|
||||
|
||||
nextCol = i + 1
|
||||
j = 0
|
||||
}
|
||||
|
||||
// calculation
|
||||
curCol = nextCol
|
||||
|
||||
// substution
|
||||
nextCol = prevRow[j] + (str1.charAt(i) === str2.charAt(j) ? 0 : 1)
|
||||
// insertion
|
||||
tmp = curCol + 1
|
||||
if (nextCol > tmp) nextCol = tmp
|
||||
|
||||
// deletion
|
||||
tmp = prevRow[j + 1] + 1
|
||||
if (nextCol > tmp) nextCol = tmp
|
||||
|
||||
// copy current into previous (in preparation for next iteration)
|
||||
prevRow[j] = curCol
|
||||
|
||||
// get current time
|
||||
currentTime = new Date().valueOf()
|
||||
}
|
||||
|
||||
// send a progress update?
|
||||
if (null !== options.progress) {
|
||||
try {
|
||||
options.progress.call(null, (i * 100.0) / str1.length)
|
||||
} catch (err) {
|
||||
return cb(`Progress callback: ${err.toString()}`)
|
||||
}
|
||||
}
|
||||
|
||||
// next iteration
|
||||
_defer(__calculate)
|
||||
}
|
||||
|
||||
__calculate()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
This library interacts with the ninsight REST API endpoints operated by
|
||||
Bitcoin.com
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class Ninsight {
|
||||
constructor(config) {
|
||||
// this.restURL = config.restURL
|
||||
// this.apiToken = config.apiToken
|
||||
|
||||
// this.ninsightURL = `https://bch-explorer.api.bitcoin.com/v1/`
|
||||
this.ninsightURL = `https://rest.bitcoin.com/v2`
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`,
|
||||
timeout: 15000
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Ninsight.utxo() utxo() - Get list of uxto for address.
|
||||
* @apiName Ninsight Utxo
|
||||
* @apiGroup Ninsight
|
||||
* @apiDescription Return list of uxto for address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let utxo = await bchjs.Ninsight.utxo('bitcoincash:qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c');
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [
|
||||
* // {
|
||||
* // "txid": "d31dc2cf66fe4d3d3ae18e1065def58a64920746b1702b52f060e5edeea9883b",
|
||||
* // "vout": 1,
|
||||
* // "value": "1000000",
|
||||
* // "height": 585570,
|
||||
* // "confirmations": 10392
|
||||
* // },
|
||||
* // {
|
||||
* // "txid": "41e9a118765ecf7a1ba4487c0863e23dba343cc5880381a72f0365ac2546c5fa",
|
||||
* // "vout": 0,
|
||||
* // "value": "1000000",
|
||||
* // "height": 577125,
|
||||
* // "confirmations": 18837
|
||||
* // }
|
||||
* // ]
|
||||
*
|
||||
*/
|
||||
async utxo(address) {
|
||||
try {
|
||||
if (typeof address !== "string")
|
||||
throw new Error(`address needs to be a string.`)
|
||||
|
||||
const response = await axios.get(
|
||||
`${this.ninsightURL}/address/utxo/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Ninsight
|
||||
@@ -0,0 +1,229 @@
|
||||
/*
|
||||
This library interacts with the public REST API endpoints that OpenBazaar
|
||||
provides for their application.
|
||||
*/
|
||||
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class OpenBazaar {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api OpenBazaar.balance() balance() - Balance about an address.
|
||||
* @apiName OpenBazaar Balance
|
||||
* @apiGroup OpenBazaar
|
||||
* @apiDescription Return Balance about an address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let balance = await bchjs.OpenBazaar.balance('bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9');
|
||||
* console.log(balance)
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* {
|
||||
* page: 1,
|
||||
* totalPages: 1,
|
||||
* itemsOnPage: 1000,
|
||||
* addrStr: "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9",
|
||||
* balance: "0.00001",
|
||||
* totalReceived: "0.00001",
|
||||
* totalSent: "0",
|
||||
* unconfirmedBalance: "0",
|
||||
* unconfirmedTxApperances: 0,
|
||||
* txApperances: 1,
|
||||
* transactions: [
|
||||
* "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7"
|
||||
* ]
|
||||
* }
|
||||
*
|
||||
*/
|
||||
async balance(address) {
|
||||
try {
|
||||
// Handle single address.
|
||||
if (typeof address === "string") {
|
||||
let response
|
||||
if (process.env.NETWORK === "testnet") {
|
||||
response = await axios.get(
|
||||
`https://tbch.blockbook.api.openbazaar.org/api/address/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
} else {
|
||||
response = await axios.get(
|
||||
`https://bch.blockbook.api.openbazaar.org/api/address/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
}
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input address must be a string.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api OpenBazaar.utxo() utxo() - Get list of uxto for address.
|
||||
* @apiName OpenBazaar Utxo
|
||||
* @apiGroup OpenBazaar
|
||||
* @apiDescription Return list of uxto for address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let utxo = await bchjs.OpenBazaar.utxo('bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9');
|
||||
* console.log(utxo);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* [
|
||||
* {
|
||||
* txid: "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7",
|
||||
* vout: 0,
|
||||
* amount: "0.00001",
|
||||
* satoshis: 1000,
|
||||
* height: 602405,
|
||||
* confirmations: 11
|
||||
* }
|
||||
* ]
|
||||
*/
|
||||
async utxo(address) {
|
||||
try {
|
||||
// Handle single address.
|
||||
if (typeof address === "string") {
|
||||
let response
|
||||
if (process.env.NETWORK === "testnet") {
|
||||
response = await axios.get(
|
||||
`https://tbch.blockbook.api.openbazaar.org/api/utxo/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
} else {
|
||||
response = await axios.get(
|
||||
`https://bch.blockbook.api.openbazaar.org/api/utxo/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
}
|
||||
return response.data
|
||||
}
|
||||
throw new Error(`Input address must be a string.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api OpenBazaar.tx() tx() - Get details on a transaction.
|
||||
* @apiName OpenBazaar Tx
|
||||
* @apiGroup OpenBazaar
|
||||
* @apiDescription Get details on a transaction.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let txDetails = await bchjs.OpenBazaar.tx(`2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7`);
|
||||
* console.log(txDetails);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
*{
|
||||
* txid: "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7",
|
||||
* version: 2,
|
||||
* vin: [
|
||||
* {
|
||||
* txid: "5f09d317e24c5d376f737a2711f3bd1d381abdb41743fff3819b4f76382e1eac",
|
||||
* vout: 1,
|
||||
* sequence: 4294967295,
|
||||
* n: 0,
|
||||
* scriptSig: {
|
||||
* hex:
|
||||
* "473044022000dd11c41a472f2e54348db996e60864d489429f12d1e044d49ff600b880c9590220715a926404bb0e2731a3795afb341ec1dad3f84ead7d27cd31fcc59abb14738c4121038476128287ac37c7a3cf7e8625fd5f024db1bc3d8e37395abe7bf42fda78d0d9"
|
||||
* },
|
||||
* addresses: ["bitcoincash:qqxy8hycqe89j7wa79gnggq6z3gaqu2uvqy26xehfe"],
|
||||
* value: "0.00047504"
|
||||
* }
|
||||
* ],
|
||||
* vout: [
|
||||
* {
|
||||
* value: "0.00001",
|
||||
* n: 0,
|
||||
* scriptPubKey: {
|
||||
* hex: "76a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788ac",
|
||||
* addresses: ["bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"]
|
||||
* },
|
||||
* spent: false
|
||||
* },
|
||||
* {
|
||||
* value: "0.00046256",
|
||||
* n: 1,
|
||||
* scriptPubKey: {
|
||||
* hex: "76a9142dbf5e1804c39a497b908c876097d63210c8490288ac",
|
||||
* addresses: ["bitcoincash:qqkm7hscqnpe5jtmjzxgwcyh6ceppjzfqg3jdn422e"]
|
||||
* },
|
||||
* spent: false
|
||||
* }
|
||||
* ],
|
||||
* blockhash: "0000000000000000010903a1fc4274499037c9339be9ec7338ee980331c20ce5",
|
||||
* blockheight: 602405,
|
||||
* confirmations: 11,
|
||||
* blocktime: 1569792892,
|
||||
* valueOut: "0.00047256",
|
||||
* valueIn: "0.00047504",
|
||||
* fees: "0.00000248",
|
||||
* hex:
|
||||
* "0200000001ac1e2e38764f9b81f3ff4317b4bd1a381dbdf311277a736f375d4ce217d3095f010000006a473044022000dd11c41a472f2e54348db996e60864d489429f12d1e044d49ff600b880c9590220715a926404bb0e2731a3795afb341ec1dad3f84ead7d27cd31fcc59abb14738c4121038476128287ac37c7a3cf7e8625fd5f024db1bc3d8e37395abe7bf42fda78d0d9ffffffff02e8030000000000001976a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788acb0b40000000000001976a9142dbf5e1804c39a497b908c876097d63210c8490288ac00000000"
|
||||
* }
|
||||
*
|
||||
*/
|
||||
async tx(txid) {
|
||||
try {
|
||||
// Handle single txid.
|
||||
if (typeof txid === "string") {
|
||||
let response
|
||||
if (process.env.NETWORK === "testnet") {
|
||||
response = await axios.get(
|
||||
`https://tbch.blockbook.api.openbazaar.org/api/tx/${txid}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
} else {
|
||||
response = await axios.get(
|
||||
`https://bch.blockbook.api.openbazaar.org/api/tx/${txid}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
}
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input txid must be a string.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenBazaar
|
||||
@@ -0,0 +1,34 @@
|
||||
const axios = require("axios")
|
||||
/**
|
||||
* @api price.current() current() - Get current price.
|
||||
* @apiName Price.
|
||||
* @apiGroup Price
|
||||
* @apiDescription Return current price of BCH in multiple currencies.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*(async () => {
|
||||
* try {
|
||||
* let current = await bchjs.Price.current('usd');
|
||||
* console.log(current);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
*})()
|
||||
*
|
||||
* // 26681
|
||||
*/
|
||||
class Price {
|
||||
async current(currency = "usd") {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`https://index-api.bitcoin.com/api/v0/cash/price/${currency.toLowerCase()}`
|
||||
)
|
||||
return response.data.price
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Price
|
||||
@@ -0,0 +1,357 @@
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class RawTransactions {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api RawTransactions.decodeRawTransaction() decodeRawTransaction() - Return an Array of JSON objects representing the serialized, hex-encoded transactions.
|
||||
* @apiName decodeRawTransaction
|
||||
* @apiGroup RawTransactions
|
||||
* @apiDescription
|
||||
* Return an Array of JSON objects representing the serialized, hex-encoded transactions.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let decodeRawTransaction = await bchjs.RawTransactions.decodeRawTransaction('01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000');
|
||||
* console.log(decodeRawTransaction);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // { txid: 'd86c34adaeae19171fd98fe0ffd89bfb92a1e6f0339f5e4f18d837715fd25758',
|
||||
* // hash:
|
||||
* // 'd86c34adaeae19171fd98fe0ffd89bfb92a1e6f0339f5e4f18d837715fd25758',
|
||||
* // size: 191,
|
||||
* // version: 1,
|
||||
* // locktime: 0,
|
||||
* // vin:
|
||||
* // [ { txid:
|
||||
* // '4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b',
|
||||
* // vout: 0,
|
||||
* // scriptSig: [Object],
|
||||
* // sequence: 4294967295 } ],
|
||||
* // vout: [ { value: 12.5, n: 0, scriptPubKey: [Object] } ] }
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let decodeRawTransaction = await bchjs.RawTransactions.decodeRawTransaction([
|
||||
* '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
|
||||
* '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
|
||||
* ]);
|
||||
* console.log(decodeRawTransaction);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [ { txid:
|
||||
* // 'd86c34adaeae19171fd98fe0ffd89bfb92a1e6f0339f5e4f18d837715fd25758',
|
||||
* // hash:
|
||||
* // 'd86c34adaeae19171fd98fe0ffd89bfb92a1e6f0339f5e4f18d837715fd25758',
|
||||
* // size: 191,
|
||||
* // version: 1,
|
||||
* // locktime: 0,
|
||||
* // vin: [ [Object] ],
|
||||
* // vout: [ [Object] ] },
|
||||
* // { txid:
|
||||
* // 'd86c34adaeae19171fd98fe0ffd89bfb92a1e6f0339f5e4f18d837715fd25758',
|
||||
* // hash:
|
||||
* // 'd86c34adaeae19171fd98fe0ffd89bfb92a1e6f0339f5e4f18d837715fd25758',
|
||||
* // size: 191,
|
||||
* // version: 1,
|
||||
* // locktime: 0,
|
||||
* // vin: [ [Object] ],
|
||||
* // vout: [ [Object] ] } ]
|
||||
*/
|
||||
async decodeRawTransaction(hex) {
|
||||
try {
|
||||
// Single hex
|
||||
if (typeof hex === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}rawtransactions/decodeRawTransaction/${hex}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
|
||||
// Array of hexes
|
||||
} else if (Array.isArray(hex)) {
|
||||
const options = {
|
||||
method: "POST",
|
||||
url: `${this.restURL}rawtransactions/decodeRawTransaction`,
|
||||
data: {
|
||||
hexes: hex
|
||||
},
|
||||
headers: {
|
||||
authorization: `Token ${_this.apiToken}`
|
||||
}
|
||||
}
|
||||
const response = await axios(options)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api RawTransactions.decodeScript() decodeScript() - Decode hex-encoded scripts.
|
||||
* @apiName decodeScript
|
||||
* @apiGroup RawTransactions
|
||||
* @apiDescription
|
||||
* Decode hex-encoded scripts.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let decodeScript = await bchjs.RawTransactions.decodeScript('4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16');
|
||||
* console.log(decodeScript);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // { asm: '30450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed59201 02e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16', type: 'nonstandard', p2sh: 'bitcoincash:pqwndulzwft8dlmqrteqyc9hf823xr3lcc7ypt74ts' }
|
||||
*
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let decodeScript = await bchjs.RawTransactions.decodeScript(['4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16']);
|
||||
* console.log(decodeScript);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [{ asm: '30450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed59201 02e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16',
|
||||
* // type: 'nonstandard',
|
||||
* // p2sh: 'bitcoincash:pqwndulzwft8dlmqrteqyc9hf823xr3lcc7ypt74ts' }]
|
||||
*/
|
||||
async decodeScript(script) {
|
||||
//if (typeof script !== "string") script = JSON.stringify(script)
|
||||
|
||||
try {
|
||||
if (typeof script === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}rawtransactions/decodeScript/${script}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
} else if (Array.isArray(script)) {
|
||||
const options = {
|
||||
method: "POST",
|
||||
url: `${this.restURL}rawtransactions/decodeScript`,
|
||||
data: {
|
||||
hexes: script
|
||||
},
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
const response = await axios(options)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api RawTransactions.getRawTransaction() getRawTransaction() - Return the raw transaction data.
|
||||
* @apiName getRawTransaction
|
||||
* @apiGroup RawTransactions
|
||||
* @apiDescription
|
||||
* Return the raw transaction data. If verbose is 'true', returns an Object with information about 'txid'. If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getRawTransaction = await bchjs.RawTransactions.getRawTransaction("0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098");
|
||||
* console.log(getRawTransaction);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // 01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let getRawTransaction = await bchjs.RawTransactions.getRawTransaction([
|
||||
* "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
|
||||
* "b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f"
|
||||
* ], true);
|
||||
* console.log(getRawTransaction);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [ { hex:
|
||||
* // '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000',
|
||||
* // txid:
|
||||
* // '0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098',
|
||||
* // hash:
|
||||
* // '0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098',
|
||||
* // size: 134,
|
||||
* // version: 1,
|
||||
* // locktime: 0,
|
||||
* // vin: [ [Object] ],
|
||||
* // vout: [ [Object] ],
|
||||
* // blockhash:
|
||||
* // '00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048',
|
||||
* // confirmations: 581882,
|
||||
* // time: 1231469665,
|
||||
* // blocktime: 1231469665 },
|
||||
* // { hex:
|
||||
* // '01000000010f3cb469bc82f931ee77d80b3dd495d02f9ed7cdc455cea3e7baa4bdeea6a78d000000006a47304402205ce3e1dfe4b5207818ce27035bc7cc03a5631f806d351535b32ce77c8d136aed02204e66e1fa4c2e12feab0d41a5593aff9629cdbc6ccb6126bc3d1a20404be7760c412103d44946d17e00179bbfc3b723aedc1831d8604e6a04bbd91170f1d894d04657bbffffffff02e6ec8500000000001976a914b5befddad83d9180fd4082c5528cf5a779b0fa6688acdf220000000000001976a9142c21a1be4239eeed678a456627a08d5f813d5c9288ac00000000',
|
||||
* // txid:
|
||||
* // 'b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f',
|
||||
* // hash:
|
||||
* // 'b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f',
|
||||
* // size: 225,
|
||||
* // version: 1,
|
||||
* // locktime: 0,
|
||||
* // vin: [ [Object] ],
|
||||
* // vout: [ [Object], [Object] ],
|
||||
* // blockhash:
|
||||
* // '000000000000000003a09a7d68a0d62fd0ab51c368372e46bac84277e2df47e2',
|
||||
* // confirmations: 16151,
|
||||
* // time: 1547752564,
|
||||
* // blocktime: 1547752564 } ]
|
||||
*/
|
||||
async getRawTransaction(txid, verbose = false) {
|
||||
try {
|
||||
if (typeof txid === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}rawtransactions/getRawTransaction/${txid}?verbose=${verbose}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
return response.data
|
||||
} else if (Array.isArray(txid)) {
|
||||
const options = {
|
||||
method: "POST",
|
||||
url: `${this.restURL}rawtransactions/getRawTransaction`,
|
||||
data: {
|
||||
txids: txid,
|
||||
verbose: verbose
|
||||
},
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
const response = await axios(options)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api RawTransactions.sendRawTransaction() sendRawTransaction() - Submits raw transaction (serialized, hex-encoded) to local node and network.
|
||||
* @apiName sendRawTransaction
|
||||
* @apiGroup RawTransactions
|
||||
* @apiDescription
|
||||
* Submits raw transaction (serialized, hex-encoded) to local node and network. Also see createrawtransaction and signrawtransaction calls.
|
||||
*
|
||||
* For bulk uploads, transactions must use different UTXOs.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // single tx
|
||||
* (async () => {
|
||||
* try {
|
||||
* let sendRawTransaction = await bchjs.RawTransactions.sendRawTransaction("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000");
|
||||
* console.log(sendRawTransaction);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
* // 0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098
|
||||
*
|
||||
* // single tx as array
|
||||
* (async () => {
|
||||
* try {
|
||||
* let sendRawTransaction = await bchjs.RawTransactions.sendRawTransaction(["01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000"]);
|
||||
* console.log(sendRawTransaction);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
* // ['0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098']
|
||||
*/
|
||||
async sendRawTransaction(hex, allowhighfees = false) {
|
||||
try {
|
||||
// Single tx hex.
|
||||
if (typeof hex === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}rawtransactions/sendRawTransaction/${hex}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
if (response.data === "66: insufficient priority") {
|
||||
console.warn(
|
||||
`WARN: Insufficient Priority! This is likely due to a fee that is too low, or insufficient funds.
|
||||
Please ensure that there is BCH in the given wallet. If you are running on the testnet, get some
|
||||
BCH from the testnet faucet at https://developer.bitcoin.com/faucets/bch`
|
||||
)
|
||||
}
|
||||
|
||||
return response.data
|
||||
|
||||
// Array input
|
||||
} else if (Array.isArray(hex)) {
|
||||
const options = {
|
||||
method: "POST",
|
||||
url: `${this.restURL}rawtransactions/sendRawTransaction`,
|
||||
data: {
|
||||
hexes: hex
|
||||
},
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
const response = await axios(options)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input hex must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = RawTransactions
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
const schnorr = require("bip-schnorr")
|
||||
|
||||
class Schnorr {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.sign() sign() - Sign a 32-byte message with the private key, returning a 64-byte signature.
|
||||
* @apiName sign
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Sign a 32-byte message with the private key, returning a 64-byte signature.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* const Buffer = require("safe-buffer").Buffer
|
||||
* const BigInteger = require("bigi")
|
||||
*
|
||||
* // signing
|
||||
* const privateKey = BigInteger.fromHex(
|
||||
* "B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF"
|
||||
* )
|
||||
* const message = Buffer.from(
|
||||
* "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
|
||||
* "hex"
|
||||
* )
|
||||
* const createdSignature = bchjs.Schnorr.sign(privateKey, message)
|
||||
* console.log("The signature is: " + createdSignature.toString("hex"))
|
||||
* // The signature is: 2a298dacae57395a15d0795ddbfd1dcb564da82b0f269bc70a74f8220429ba1d1e51a22ccec35599b8f266912281f8365ffc2d035a230434a1a64dc59f7013fd
|
||||
*/
|
||||
sign(privateKey, message) {
|
||||
return schnorr.sign(privateKey, message)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.verify() verify() - Verify a 64-byte signature of a 32-byte message against the public key.
|
||||
* @apiName verify
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Verify a 64-byte signature of a 32-byte message against the public key. Throws an Error if verification fails.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* const Buffer = require("safe-buffer").Buffer
|
||||
* const publicKey = Buffer.from(
|
||||
* "02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659",
|
||||
* "hex"
|
||||
* )
|
||||
* const message = Buffer.from(
|
||||
* "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
|
||||
* "hex"
|
||||
* )
|
||||
* const signatureToVerify = Buffer.from(
|
||||
* "2A298DACAE57395A15D0795DDBFD1DCB564DA82B0F269BC70A74F8220429BA1D1E51A22CCEC35599B8F266912281F8365FFC2D035A230434A1A64DC59F7013FD",
|
||||
* "hex"
|
||||
* )
|
||||
* try {
|
||||
* bchjs.Schnorr.verify(publicKey, message, signatureToVerify)
|
||||
* console.log("The signature is valid.")
|
||||
* } catch (e) {
|
||||
* console.error("The signature verification failed: " + e)
|
||||
* }
|
||||
*/
|
||||
verify(publicKey, message, signatureToVerify) {
|
||||
return schnorr.verify(publicKey, message, signatureToVerify)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.batchVerify() batchVerify() - Verify a list of 64-byte signatures as a batch operation.
|
||||
* @apiName batchVerify
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Verify a list of 64-byte signatures as a batch operation. Throws an Error if verification fails.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* const Buffer = require("safe-buffer").Buffer
|
||||
* const publicKeys = [
|
||||
* Buffer.from(
|
||||
* "02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "03FAC2114C2FBB091527EB7C64ECB11F8021CB45E8E7809D3C0938E4B8C0E5F84B",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "026D7F1D87AB3BBC8BC01F95D9AECE1E659D6E33C880F8EFA65FACF83E698BBBF7",
|
||||
* "hex"
|
||||
* )
|
||||
* ]
|
||||
* const messages = [
|
||||
* Buffer.from(
|
||||
* "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "5E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "B2F0CD8ECB23C1710903F872C31B0FD37E15224AF457722A87C5E0C7F50FFFB3",
|
||||
* "hex"
|
||||
* )
|
||||
* ]
|
||||
* const signatures = [
|
||||
* Buffer.from(
|
||||
* "2A298DACAE57395A15D0795DDBFD1DCB564DA82B0F269BC70A74F8220429BA1D1E51A22CCEC35599B8F266912281F8365FFC2D035A230434A1A64DC59F7013FD",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "00DA9B08172A9B6F0466A2DEFD817F2D7AB437E0D253CB5395A963866B3574BE00880371D01766935B92D2AB4CD5C8A2A5837EC57FED7660773A05F0DE142380",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "68CA1CC46F291A385E7C255562068357F964532300BEADFFB72DD93668C0C1CAC8D26132EB3200B86D66DE9C661A464C6B2293BB9A9F5B966E53CA736C7E504F",
|
||||
* "hex"
|
||||
* )
|
||||
* ]
|
||||
* try {
|
||||
* bchjs.Schnorr.batchVerify(publicKeys, messages, signatures)
|
||||
* console.log("The signatures are valid.")
|
||||
* } catch (e) {
|
||||
* console.error("The signature verification failed: " + e)
|
||||
* }
|
||||
*/
|
||||
batchVerify(publicKeys, messages, signaturesToVerify) {
|
||||
return schnorr.batchVerify(publicKeys, messages, signaturesToVerify)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.nonInteractive() nonInteractive() - Aggregates multiple signatures of different private keys
|
||||
* @apiName nonInteractive
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Aggregates multiple signatures of different private keys over the same message into a single 64-byte signature using a scheme that is safe from rogue-key attacks.
|
||||
*
|
||||
* This non-interactive scheme requires the knowledge of all private keys that are participating in the multi-signature creation.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* const Buffer = require("safe-buffer").Buffer
|
||||
* const BigInteger = require("bigi")
|
||||
*
|
||||
* const privateKey1 = BigInteger.fromHex(
|
||||
* "B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF"
|
||||
* )
|
||||
* const privateKey2 = BigInteger.fromHex(
|
||||
* "C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C7"
|
||||
* )
|
||||
* const message = Buffer.from(
|
||||
* "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89",
|
||||
* "hex"
|
||||
* )
|
||||
* const aggregatedSignature = bchjs.Schnorr.nonInteractive(
|
||||
* [privateKey1, privateKey2],
|
||||
* message
|
||||
* )
|
||||
*
|
||||
* // verifying an aggregated signature
|
||||
* const publicKey1 = Buffer.from(
|
||||
* "02DFF1D77F2A671C5F36183726DB2341BE58FEAE1DA2DECED843240F7B502BA659",
|
||||
* "hex"
|
||||
* )
|
||||
* const publicKey2 = Buffer.from(
|
||||
* "03FAC2114C2FBB091527EB7C64ECB11F8021CB45E8E7809D3C0938E4B8C0E5F84B",
|
||||
* "hex"
|
||||
* )
|
||||
* const X = bchjs.Schnorr.publicKeyCombine([publicKey1, publicKey2])
|
||||
* try {
|
||||
* bchjs.Schnorr.verify(X, message, aggregatedSignature)
|
||||
* console.log("The signature is valid.")
|
||||
* } catch (e) {
|
||||
* console.error("The signature verification failed: " + e)
|
||||
* }
|
||||
*/
|
||||
nonInteractive(privateKeys, message) {
|
||||
return schnorr.muSig.nonInteractive(privateKeys, message)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.computeEll() computeEll() - Generate ell which is the hash over all public keys participating in a session.
|
||||
* @apiName computeEll
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Generate ell which is the hash over all public keys participating in a session.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* const Buffer = require("safe-buffer").Buffer
|
||||
* const BigInteger = require("bigi")
|
||||
*
|
||||
* const publicData = {
|
||||
* pubKeys: [
|
||||
* Buffer.from(
|
||||
* "03846f34fdb2345f4bf932cb4b7d278fb3af24f44224fb52ae551781c3a3cad68a",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "02cd836b1d42c51d80cef695a14502c21d2c3c644bc82f6a7052eb29247cf61f4f",
|
||||
* "hex"
|
||||
* ),
|
||||
* Buffer.from(
|
||||
* "03b8c1765111002f09ba35c468fab273798a9058d1f8a4e276f45a1f1481dd0bdb",
|
||||
* "hex"
|
||||
* )
|
||||
* ],
|
||||
* message: bchjs.Schnorr.hash(Buffer.from("muSig is awesome!", "utf8")),
|
||||
* pubKeyHash: null,
|
||||
* pubKeyCombined: null,
|
||||
* commitments: [],
|
||||
* nonces: [],
|
||||
* nonceCombined: null,
|
||||
* partialSignatures: [],
|
||||
* signature: null
|
||||
* }
|
||||
*
|
||||
* // data only known by the individual party, these values are never shared
|
||||
* // between the signers!
|
||||
* const signerPrivateData = [
|
||||
* // signer 1
|
||||
* {
|
||||
* privateKey: BigInteger.fromHex(
|
||||
* "add2b25e2d356bec3770305391cbc80cab3a40057ad836bcb49ef3eed74a3fee"
|
||||
* ),
|
||||
* session: null
|
||||
* },
|
||||
* // signer 2
|
||||
* {
|
||||
* privateKey: BigInteger.fromHex(
|
||||
* "0a1645eef5a10e1f5011269abba9fd85c4f0cc70820d6f102fb7137f2988ad78"
|
||||
* ),
|
||||
* session: null
|
||||
* },
|
||||
* // signer 3
|
||||
* {
|
||||
* privateKey: BigInteger.fromHex(
|
||||
* "2031e7fed15c770519707bb092a6337215530e921ccea42030c15d86e8eaf0b8"
|
||||
* ),
|
||||
* session: null
|
||||
* }
|
||||
* ]
|
||||
*
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 1: Combine the public keys
|
||||
* // The public keys P_i are combined into the combined public key P.
|
||||
* // This can be done by every signer individually or by the initializing
|
||||
* // party and then be distributed to every participant.
|
||||
* // -----------------------------------------------------------------------
|
||||
* publicData.pubKeyHash = bchjs.Schnorr.computeEll(publicData.pubKeys)
|
||||
*/
|
||||
computeEll(publicKeys) {
|
||||
return schnorr.muSig.computeEll(publicKeys)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.publicKeyCombine() publicKeyCombine() - Creates a special rogue-key-resistant.
|
||||
* @apiName publicKeyCombine
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Creates the special rogue-key-resistant combined public key P by applying the MuSig coefficient to each public key P_i before adding them together.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // continued from above
|
||||
* publicData.pubKeyCombined = bchjs.Schnorr.publicKeyCombine(
|
||||
* publicData.pubKeys,
|
||||
* publicData.pubKeyHash
|
||||
* )
|
||||
*/
|
||||
publicKeyCombine(publicKeys, publicKeyHash) {
|
||||
return schnorr.muSig.pubKeyCombine(publicKeys, publicKeyHash)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.sessionInitialize() sessionInitialize() - Creates a signing session.
|
||||
* @apiName sessionInitialize
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Creates a signing session. Each participant must create a session and must not share the content of the session apart from the commitment and later the nonce.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // continued from above
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 2: Create the private signing session
|
||||
* // Each signing party does this in private. The session ID *must* be
|
||||
* // unique for every call to sessionInitialize, otherwise it's trivial for
|
||||
* // an attacker to extract the secret key!
|
||||
* // -----------------------------------------------------------------------
|
||||
* signerPrivateData.forEach((data, idx) => {
|
||||
* const sessionId = bchjs.Crypto.randomBytes(32) // must never be reused between sessions!
|
||||
* data.session = bchjs.Schnorr.sessionInitialize(
|
||||
* sessionId,
|
||||
* data.privateKey,
|
||||
* publicData.message,
|
||||
* publicData.pubKeyCombined,
|
||||
* publicData.pubKeyHash,
|
||||
* idx
|
||||
* )
|
||||
* })
|
||||
* const signerSession = signerPrivateData[0].session
|
||||
*/
|
||||
sessionInitialize(sessionId, privateKey, message, pubKeyCombined, ell, idx) {
|
||||
return schnorr.muSig.sessionInitialize(
|
||||
sessionId,
|
||||
privateKey,
|
||||
message,
|
||||
pubKeyCombined,
|
||||
ell,
|
||||
idx
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.sessionNonceCombine() sessionNonceCombine() - Combines multiple nonces R_i into the combined nonce R.
|
||||
* @apiName sessionNonceCombine
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Combines multiple nonces R_i into the combined nonce R.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // continued from above
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 3: Exchange commitments (communication round 1)
|
||||
* // The signers now exchange the commitments H(R_i). This is simulated here
|
||||
* // by copying the values from the private data to public data array.
|
||||
* // -----------------------------------------------------------------------
|
||||
* for (let i = 0; i < publicData.pubKeys.length; i++) {
|
||||
* publicData.commitments[i] = signerPrivateData[i].session.commitment
|
||||
* }
|
||||
*
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 4: Get nonces (communication round 2)
|
||||
* // Now that everybody has commited to the session, the nonces (R_i) can be
|
||||
* // exchanged. Again, this is simulated by copying.
|
||||
* // -----------------------------------------------------------------------
|
||||
* for (let i = 0; i < publicData.pubKeys.length; i++) {
|
||||
* publicData.nonces[i] = signerPrivateData[i].session.nonce
|
||||
* }
|
||||
*
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 5: Combine nonces
|
||||
* // The nonces can now be combined into R. Each participant should do this
|
||||
* // and keep track of whether the nonce was negated or not. This is needed
|
||||
* // for the later steps.
|
||||
* // -----------------------------------------------------------------------
|
||||
* publicData.nonceCombined = bchjs.Schnorr.sessionNonceCombine(
|
||||
* signerSession,
|
||||
* publicData.nonces
|
||||
* )
|
||||
* signerPrivateData.forEach(
|
||||
* data => (data.session.nonceIsNegated = signerSession.nonceIsNegated)
|
||||
* )
|
||||
*/
|
||||
sessionNonceCombine(session, nonces) {
|
||||
return schnorr.muSig.sessionNonceCombine(session, nonces)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.partialSign() partialSign() - Creates a partial signature s_i for a participant.
|
||||
* @apiName partialSign
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Creates a partial signature s_i for a participant.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // continued from above
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 6: Generate partial signatures
|
||||
* // Every participant can now create their partial signature s_i over the
|
||||
* // given message.
|
||||
* // -----------------------------------------------------------------------
|
||||
* signerPrivateData.forEach(data => {
|
||||
* data.session.partialSignature = bchjs.Schnorr.partialSign(
|
||||
* data.session,
|
||||
* publicData.message,
|
||||
* publicData.nonceCombined,
|
||||
* publicData.pubKeyCombined
|
||||
* )
|
||||
* })
|
||||
*/
|
||||
partialSign(session, message, nonceCombined, pubKeyCombined) {
|
||||
return schnorr.muSig.partialSign(
|
||||
session,
|
||||
message,
|
||||
nonceCombined,
|
||||
pubKeyCombined
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.partialSignatureVerify() partialSignatureVerify() - Verifies a partial signature s_i against the participant's public key P_i.
|
||||
* @apiName partialSignatureVerify
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Verifies a partial signature s_i against the participant's public key P_i. Throws an Error if verification fails.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // continued from above
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 7: Exchange partial signatures (communication round 3)
|
||||
* // The partial signature of each signer is exchanged with the other
|
||||
* // participants. Simulated here by copying.
|
||||
* // -----------------------------------------------------------------------
|
||||
* for (let i = 0; i < publicData.pubKeys.length; i++) {
|
||||
* publicData.partialSignatures[i] =
|
||||
* signerPrivateData[i].session.partialSignature
|
||||
* }
|
||||
*
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 8: Verify individual partial signatures
|
||||
* // Every participant should verify the partial signatures received by the
|
||||
* // other participants.
|
||||
* // -----------------------------------------------------------------------
|
||||
* for (let i = 0; i < publicData.pubKeys.length; i++) {
|
||||
* bchjs.Schnorr.partialSignatureVerify(
|
||||
* signerSession,
|
||||
* publicData.partialSignatures[i],
|
||||
* publicData.nonceCombined,
|
||||
* i,
|
||||
* publicData.pubKeys[i],
|
||||
* publicData.nonces[i]
|
||||
* )
|
||||
* }
|
||||
*/
|
||||
partialSignatureVerify(
|
||||
session,
|
||||
partialSignature,
|
||||
nonceCombined,
|
||||
idx,
|
||||
pubKey,
|
||||
nonce
|
||||
) {
|
||||
return schnorr.muSig.partialSigVerify(
|
||||
session,
|
||||
partialSignature,
|
||||
nonceCombined,
|
||||
idx,
|
||||
pubKey,
|
||||
nonce
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Schnorr.partialSignaturesCombine() partialSignaturesCombine() - Combines multiple partial signatures into a Schnorr signature.
|
||||
* @apiName partialSignaturesCombine
|
||||
* @apiGroup Schnorr
|
||||
* @apiDescription
|
||||
* Combines multiple partial signatures into a Schnorr signature (s, R) that can be verified against the combined public key P.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // continued from above
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 9: Combine partial signatures
|
||||
* // Finally, the partial signatures can be combined into the full signature
|
||||
* // (s, R) that can be verified against combined public key P.
|
||||
* // -----------------------------------------------------------------------
|
||||
* publicData.signature = bchjs.Schnorr.partialSignaturesCombine(
|
||||
* publicData.nonceCombined,
|
||||
* publicData.partialSignatures
|
||||
* )
|
||||
*
|
||||
* // -----------------------------------------------------------------------
|
||||
* // Step 10: Verify signature
|
||||
* // The resulting signature can now be verified as a normal Schnorr
|
||||
* // signature (s, R) over the message m and public key P.
|
||||
* // -----------------------------------------------------------------------
|
||||
* bchjs.Schnorr.verify(
|
||||
* publicData.pubKeyCombined,
|
||||
* publicData.message,
|
||||
* publicData.signature
|
||||
* )
|
||||
*/
|
||||
partialSignaturesCombine(nonceCombined, partialSignatures) {
|
||||
return schnorr.muSig.partialSigCombine(nonceCombined, partialSignatures)
|
||||
}
|
||||
|
||||
bufferToInt(buffer) {
|
||||
return schnorr.convert.bufferToInt(buffer)
|
||||
}
|
||||
|
||||
intToBuffer(bigInteger) {
|
||||
return schnorr.convert.intToBuffer(bigInteger)
|
||||
}
|
||||
|
||||
hash(buffer) {
|
||||
return schnorr.convert.hash(buffer)
|
||||
}
|
||||
|
||||
pointToBuffer(point) {
|
||||
return schnorr.convert.pointToBuffer(point)
|
||||
}
|
||||
|
||||
pubKeyToPoint(publicKey) {
|
||||
return schnorr.convert.pubKeyToPoint(publicKey)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Schnorr
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
const opcodes = require("bitcoincash-ops")
|
||||
|
||||
class Script {
|
||||
constructor() {
|
||||
this.opcodes = opcodes
|
||||
this.nullData = Bitcoin.script.nullData
|
||||
this.multisig = {
|
||||
input: {
|
||||
encode: signatures => {
|
||||
const sigs = []
|
||||
signatures.forEach(sig => {
|
||||
sigs.push(sig)
|
||||
})
|
||||
return Bitcoin.script.multisig.input.encode(sigs)
|
||||
},
|
||||
decode: Bitcoin.script.multisig.input.decode,
|
||||
check: Bitcoin.script.multisig.input.check
|
||||
},
|
||||
output: {
|
||||
encode: (m, pubKeys) => {
|
||||
const pks = []
|
||||
pubKeys.forEach(pubKey => {
|
||||
pks.push(pubKey)
|
||||
})
|
||||
return Bitcoin.script.multisig.output.encode(m, pks)
|
||||
},
|
||||
decode: Bitcoin.script.multisig.output.decode,
|
||||
check: Bitcoin.script.multisig.output.check
|
||||
}
|
||||
}
|
||||
this.pubKey = Bitcoin.script.pubKey
|
||||
this.pubKeyHash = Bitcoin.script.pubKeyHash
|
||||
this.scriptHash = Bitcoin.script.scriptHash
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Script.classifyInput() classifyInput()
|
||||
* @apiName classifyInput
|
||||
* @apiGroup Script
|
||||
* @apiDescription
|
||||
* Classify transaction input.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let pubkeyInput = "3045022100ba2c3b717e023966cb16df65ca83f77029e2a5b80c47c47b6956474ac9ff281302201d48ee3292439e284a6654a0e79ac2b8f7fff5c6b0d715260aa296501a239c6441";
|
||||
* bchjs.Script.classifyInput(bchjs.Script.fromASM(pubkeyInput));
|
||||
* // pubkey
|
||||
*
|
||||
* let pubkeyhashInput = "30440220280d4a9954c5afe24089bdd545466bd7a8caad8b295e30de9d3cb5e56fccf64e022036663b2c53b5fac674b4b935b53e2a4ea88dfc71c9b879870976d82887542ab441 02969479fa9bea3082697dce683ac05b13ae63016b41d5ca1a450ad40f6c543751";
|
||||
* bchjs.Script.classifyInput(bchjs.Script.fromASM(pubkeyhashInput));
|
||||
* // pubkeyhash
|
||||
*
|
||||
* let multisigInput = "OP_0 3045022100fe324541215798b2df68cbd44039615e23c506d4ec1a05572064392a98196b82022068c849fa6699206da2fc6d7848efc1d3804a5816d6293615fe34c1a7f34e1c2f01 3044022001ab168e80b863fdec694350b587339bb72a37108ac3c989849251444d13ebba02201811272023e3c1038478eb972a82d3ad431bfc2408e88e4da990f1a7ecbb263901 3045022100aaeb7204c17eee2f2c4ff1c9f8b39b79e75e7fbf33e92cc67ac51be8f15b75f90220659eee314a4943a6384d2b154fa5821ef7a084814d7ee2c6f9f7f0ffb53be34b01";
|
||||
* bchjs.Script.classifyInput(bchjs.Script.fromASM(multisigInput));
|
||||
* // multisig
|
||||
*
|
||||
* let scripthashInput = "OP_0 304402207515cf147d201f411092e6be5a64a6006f9308fad7b2a8fdaab22cd86ce764c202200974b8aca7bf51dbf54150d3884e1ae04f675637b926ec33bf75939446f6ca2801 3045022100ef253c1faa39e65115872519e5f0a33bbecf430c0f35cf562beabbad4da24d8d02201742be8ee49812a73adea3007c9641ce6725c32cd44ddb8e3a3af460015d140501 522102359c6e3f04cefbf089cf1d6670dc47c3fb4df68e2bad1fa5a369f9ce4b42bbd1210395a9d84d47d524548f79f435758c01faec5da2b7e551d3b8c995b7e06326ae4a52ae";
|
||||
* bchjs.Script.classifyInput(bchjs.Script.fromASM(scripthashInput));
|
||||
* // scripthash
|
||||
*/
|
||||
classifyInput(script) {
|
||||
return Bitcoin.script.classifyInput(script)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Script.classifyOutput() classifyOutput()
|
||||
* @apiName classifyOutput
|
||||
* @apiGroup Script
|
||||
* @apiDescription
|
||||
* Classify transaction output.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let nullDataOutput = "OP_RETURN 424348466f7245766572796f6e65";
|
||||
* bchjs.Script.classifyOutput(bchjs.Script.fromASM(nullDataOutput));
|
||||
* // nulldata
|
||||
*
|
||||
* let pubkeyOutput = "02359c6e3f04cefbf089cf1d6670dc47c3fb4df68e2bad1fa5a369f9ce4b42bbd1 OP_CHECKSIG";
|
||||
* bchjs.Script.classifyOutput(bchjs.Script.fromASM(pubkeyOutput));
|
||||
* // pubkey
|
||||
*
|
||||
* let pubkeyhashOutput = "OP_DUP OP_HASH160 aa4d7985c57e011a8b3dd8e0e5a73aaef41629c5 OP_EQUALVERIFY OP_CHECKSIG";
|
||||
* bchjs.Script.classifyOutput(bchjs.Script.fromASM(pubkeyhashOutput));
|
||||
* // pubkeyhash
|
||||
*
|
||||
* let multisigOutput = "OP_2 02359c6e3f04cefbf089cf1d6670dc47c3fb4df68e2bad1fa5a369f9ce4b42bbd1 0395a9d84d47d524548f79f435758c01faec5da2b7e551d3b8c995b7e06326ae4a OP_2 OP_CHECKMULTISIG";
|
||||
* bchjs.Script.classifyOutput(bchjs.Script.fromASM(multisigOutput));
|
||||
* // multisig
|
||||
*
|
||||
* let scripthashOutput = "OP_HASH160 722ff0bc2c3f47b35c20df646c395594da24e90e OP_EQUAL";
|
||||
* bchjs.Script.classifyOutput(bchjs.Script.fromASM(scripthashOutput));
|
||||
* // scripthash
|
||||
*/
|
||||
classifyOutput(script) {
|
||||
return Bitcoin.script.classifyOutput(script)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Script.decode() decode()
|
||||
* @apiName decode
|
||||
* @apiGroup Script
|
||||
* @apiDescription
|
||||
* Decode a Script buffer.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // decode P2PKH scriptSig buffer
|
||||
* let scriptSigBuffer = Buffer.from("483045022100877e2f9c28421f0a850cc8ff66ba1d0f6c8dbe9e63e199c2c2600c9c15bf9d4402204d35b13d3cc202aa25722b2b1791442ebc5c39d898b609515260ad08f0e766a6012102fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb", 'hex');
|
||||
* bchjs.Script.decode(scriptSigBuffer);
|
||||
* // [ <Buffer 30 45 02 21 00 87 7e 2f 9c 28 42 1f 0a 85 0c c8 ff 66 ba 1d 0f 6c 8d be 9e 63 e1 99 c2 c2 60 0c 9c 15 bf 9d 44 02 20 4d 35 b1 3d 3c c2 02 aa 25 72 2b ... >, <Buffer 02 fb 72 1b 92 02 5e 77 5b 1b 84 77 4e 65 d5 68 d2 46 45 cb 63 32 75 f5 c2 6f 5c 31 01 b2 14 a8 fb> ]
|
||||
*
|
||||
* // decode P2PKH scriptPubKey buffer
|
||||
* let scriptPubKeyBuffer = Buffer.from("76a91424e9c07804d0ee7e5bda934e0a3ae8710fc007dd88ac", 'hex');
|
||||
* bchjs.Script.decode(scriptPubKeyBuffer);
|
||||
* // [ 118,
|
||||
* // 169,
|
||||
* // <Buffer 24 e9 c0 78 04 d0 ee 7e 5b da 93 4e 0a 3a e8 71 0f c0 07 dd>,
|
||||
* // 136,
|
||||
* // 172 ]
|
||||
*/
|
||||
decode(scriptBuffer) {
|
||||
return Bitcoin.script.decompile(scriptBuffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Script.encode() encode()
|
||||
* @apiName encode
|
||||
* @apiGroup Script
|
||||
* @apiDescription
|
||||
* Encode a Script buffer with minimal push data. This function is used for
|
||||
* Script files like CashScript. However, it will mangle the OP_RETURN of
|
||||
* an SLP token transaction and will burn the tokens as a result. Use encode2()
|
||||
* instead for that.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // encode P2PKH scriptSig to buffer
|
||||
* let scriptSig = [
|
||||
* Buffer.from('3045022100877e2f9c28421f0a850cc8ff66ba1d0f6c8dbe9e63e199c2c2600c9c15bf9d4402204d35b13d3cc202aa25722b2b1791442ebc5c39d898b609515260ad08f0e766a601', 'hex'),
|
||||
* Buffer.from('02fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb', 'hex')
|
||||
* ]
|
||||
* bchjs.Script.encode(scriptSig);
|
||||
* // <Buffer 48 30 45 02 21 00 87 7e 2f 9c 28 42 1f 0a 85 0c c8 ff 66 ba 1d 0f 6c 8d be 9e 63 e1 99 c2 c2 60 0c 9c 15 bf 9d 44 02 20 4d 35 b1 3d 3c c2 02 aa 25 72 ... >
|
||||
*
|
||||
* // encode P2PKH scriptPubKey to buffer
|
||||
* let scriptPubKey = [
|
||||
* 118,
|
||||
* 169,
|
||||
* Buffer.from('24e9c07804d0ee7e5bda934e0a3ae8710fc007dd', 'hex'),
|
||||
* 136,
|
||||
* 172
|
||||
* ];
|
||||
* bchjs.Script.encode(scriptPubKey);
|
||||
* // <Buffer 76 a9 14 24 e9 c0 78 04 d0 ee 7e 5b da 93 4e 0a 3a e8 71 0f c0 07 dd 88 ac>
|
||||
*/
|
||||
encode(scriptChunks) {
|
||||
const arr = []
|
||||
scriptChunks.forEach(chunk => {
|
||||
arr.push(chunk)
|
||||
})
|
||||
return Bitcoin.script.compile(arr)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Script.encode2() encode2()
|
||||
* @apiName encode2
|
||||
* @apiGroup Script
|
||||
* @apiDescription
|
||||
* Encode a Script buffer without minimal push data. This should be used if
|
||||
* encode() does not produce the desired results. This should be used for compiling
|
||||
* SLP OP_RETURNs.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // encode P2PKH scriptSig to buffer
|
||||
* let scriptSig = [
|
||||
* Buffer.from('3045022100877e2f9c28421f0a850cc8ff66ba1d0f6c8dbe9e63e199c2c2600c9c15bf9d4402204d35b13d3cc202aa25722b2b1791442ebc5c39d898b609515260ad08f0e766a601', 'hex'),
|
||||
* Buffer.from('02fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb', 'hex')
|
||||
* ]
|
||||
* bchjs.Script.encode2(scriptSig);
|
||||
* // <Buffer 48 30 45 02 21 00 87 7e 2f 9c 28 42 1f 0a 85 0c c8 ff 66 ba 1d 0f 6c 8d be 9e 63 e1 99 c2 c2 60 0c 9c 15 bf 9d 44 02 20 4d 35 b1 3d 3c c2 02 aa 25 72 ... >
|
||||
*
|
||||
* // encode P2PKH scriptPubKey to buffer
|
||||
* let scriptPubKey = [
|
||||
* 118,
|
||||
* 169,
|
||||
* Buffer.from('24e9c07804d0ee7e5bda934e0a3ae8710fc007dd', 'hex'),
|
||||
* 136,
|
||||
* 172
|
||||
* ];
|
||||
* bchjs.Script.encode2(scriptPubKey);
|
||||
* // <Buffer 76 a9 14 24 e9 c0 78 04 d0 ee 7e 5b da 93 4e 0a 3a e8 71 0f c0 07 dd 88 ac>
|
||||
*/
|
||||
encode2(scriptChunks) {
|
||||
const arr = []
|
||||
scriptChunks.forEach(chunk => {
|
||||
arr.push(chunk)
|
||||
})
|
||||
return Bitcoin.script.compile2(arr)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Script.toASM() toASM()
|
||||
* @apiName toASM
|
||||
* @apiGroup Script
|
||||
* @apiDescription
|
||||
* Script buffer to ASM.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // P2PKH scriptSig
|
||||
* let scriptSigBuffer = Buffer.from('483045022100877e2f9c28421f0a850cc8ff66ba1d0f6c8dbe9e63e199c2c2600c9c15bf9d4402204d35b13d3cc202aa25722b2b1791442ebc5c39d898b609515260ad08f0e766a6012102fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb', 'hex');
|
||||
* bchjs.Script.toASM(scriptSigBuffer);
|
||||
* // 3045022100877e2f9c28421f0a850cc8ff66ba1d0f6c8dbe9e63e199c2c2600c9c15bf9d4402204d35b13d3cc202aa25722b2b1791442ebc5c39d898b609515260ad08f0e766a601 02fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb
|
||||
*
|
||||
* // P2PKH scriptPubKey
|
||||
* let scriptBuffer = Buffer.from("76a914bee4182d9fbc8931a728410a0cd3e0f340f2995a88ac", 'hex');
|
||||
* bchjs.Script.toASM(scriptBuffer);
|
||||
* // OP_DUP OP_HASH160 bee4182d9fbc8931a728410a0cd3e0f340f2995a OP_EQUALVERIFY OP_CHECKSIG
|
||||
*/
|
||||
toASM(buffer) {
|
||||
return Bitcoin.script.toASM(buffer)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Script.fromASM() fromASM()
|
||||
* @apiName fromASM
|
||||
* @apiGroup Script
|
||||
* @apiDescription
|
||||
* Script ASM to buffer.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // P2PKH scriptSig
|
||||
* let scriptSigASM = "3045022100877e2f9c28421f0a850cc8ff66ba1d0f6c8dbe9e63e199c2c2600c9c15bf9d4402204d35b13d3cc202aa25722b2b1791442ebc5c39d898b609515260ad08f0e766a601 02fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb";
|
||||
* bchjs.Script.fromASM(scriptSigASM);
|
||||
* // <Buffer 48 30 45 02 21 00 87 7e 2f 9c 28 42 1f 0a 85 0c c8 ff 66 ba 1d 0f 6c 8d be 9e 63 e1 99 c2 c2 60 0c 9c 15 bf 9d 44 02 20 4d 35 b1 3d 3c c2 02 aa 25 72 ... >
|
||||
*
|
||||
* // P2PKH scriptPubKey
|
||||
* let scriptPubKeyASM = "OP_DUP OP_HASH160 bee4182d9fbc8931a728410a0cd3e0f340f2995a OP_EQUALVERIFY OP_CHECKSIG";
|
||||
* bchjs.Script.fromASM(scriptPubKeyASM);
|
||||
* // <Buffer 76 a9 14 be e4 18 2d 9f bc 89 31 a7 28 41 0a 0c d3 e0 f3 40 f2 99 5a 88 ac>
|
||||
*/
|
||||
fromASM(asm) {
|
||||
return Bitcoin.script.fromASM(asm)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Script
|
||||
@@ -0,0 +1,658 @@
|
||||
const BCHJSAddress = require("../address")
|
||||
// const bchAddress = new BCHJSAddress()
|
||||
let bchAddress
|
||||
|
||||
const bchaddrjs = require("bchaddrjs-slp")
|
||||
|
||||
class Address extends BCHJSAddress {
|
||||
constructor(config) {
|
||||
super(config)
|
||||
|
||||
this.restURL = config.restURL
|
||||
|
||||
bchAddress = new BCHJSAddress(config)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Address.toSLPAddress() toSLPAddress() - Converting to slpAddress format.
|
||||
* @apiName toSLPAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Converting legacy or cashaddr to slpAddress format.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet legacy
|
||||
* bchjs.SLP.Address.toSLPAddress('1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN')
|
||||
* // simpleledger:qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzd
|
||||
*
|
||||
* // mainnet legacy return no prefix
|
||||
* bchjs.SLP.Address.toSLPAddress('1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN', false)
|
||||
* // qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl
|
||||
*
|
||||
* // mainnet cashaddr
|
||||
* bchjs.SLP.Address.toSLPAddress('bitcoincash:qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
|
||||
* // simpleledger:qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzdp
|
||||
*
|
||||
* // mainnet slpaddr no prefix
|
||||
* bchjs.SLP.Address.toSLPAddress('qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
|
||||
* // simpleledger:qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzdp
|
||||
*
|
||||
* // tesnet legacy
|
||||
* bchjs.SLP.Address.toSLPAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx')
|
||||
* // slptest:qzq9je6pntpva3wf6scr7mlnycr54sjgeqauyclpwv
|
||||
*
|
||||
* // testnet legacy return no prefix
|
||||
* bchjs.SLP.Address.toSLPAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx', false)
|
||||
* // qzq9je6pntpva3wf6scr7mlnycr54sjgeqauyclpwv
|
||||
*
|
||||
* // tesnet cashaddr
|
||||
* bchjs.SLP.Address.toSLPAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx')
|
||||
* // slptest:qzq9je6pntpva3wf6scr7mlnycr54sjgeqauyclpwv
|
||||
*
|
||||
* // testnet cashaddr no prefix
|
||||
* bchjs.SLP.Address.toSLPAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx', false)
|
||||
* // qzq9je6pntpva3wf6scr7mlnycr54sjgeqauyclpwv
|
||||
*/
|
||||
toSLPAddress(address, prefix = true, regtest = false) {
|
||||
this._ensureValidAddress(address)
|
||||
const slpAddress = bchaddrjs.toSlpAddress(address)
|
||||
if (prefix) return slpAddress
|
||||
return slpAddress.split(":")[1]
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Address.toCashAddress() toCashAddress() - Converting to cashAddress format.
|
||||
* @apiName toCashAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Converting legacy or slpaddr to cashAddress format.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet legacy
|
||||
* bchjs.SLP.Address.toCashAddress('1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN')
|
||||
* // bitcoincash:qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl
|
||||
*
|
||||
* // mainnet legacy return no prefix
|
||||
* bchjs.SLP.Address.toCashAddress('1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN', false)
|
||||
* // qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl
|
||||
*
|
||||
* // mainnet slpaddr
|
||||
* bchjs.SLP.Address.toCashAddress('simpleledger:qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzdp')
|
||||
* // bitcoincash:qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl
|
||||
*
|
||||
* // mainnet slpaddr no prefix
|
||||
* bchjs.SLP.Address.toCashAddress('qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzdp')
|
||||
* // qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl
|
||||
*
|
||||
* // tesnet legacy
|
||||
* bchjs.SLP.Address.toCashAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx')
|
||||
* // bchtest:qzq9je6pntpva3wf6scr7mlnycr54sjgeqxgrr9ku3
|
||||
*
|
||||
* // testnet legacy return no prefix
|
||||
* bchjs.SLP.Address.toCashAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx', false)
|
||||
* // qzq9je6pntpva3wf6scr7mlnycr54sjgeqxgrr9ku3
|
||||
*
|
||||
* // tesnet cashaddr
|
||||
* bchjs.SLP.Address.toCashAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx')
|
||||
* // bchtest:qzq9je6pntpva3wf6scr7mlnycr54sjgeqxgrr9ku3
|
||||
*
|
||||
* // testnet cashaddr no prefix
|
||||
* bchjs.SLP.Address.toCashAddress('msDbtTj7kWXPpYaR7PQmMK84i66fJqQMLx', false)
|
||||
* // qzq9je6pntpva3wf6scr7mlnycr54sjgeqxgrr9ku3
|
||||
*/
|
||||
toCashAddress(address, prefix = true, regtest = false) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashAddress = bchaddrjs.toCashAddress(address)
|
||||
if (prefix) return cashAddress
|
||||
return cashAddress.split(":")[1]
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Address.toLegacyAddress() toLegacyAddress() - Converting to legacy address format.
|
||||
* @apiName toLegacyAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Converting cashaddr or slpaddr to legacy address format.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* // mainnet cashaddr w/ prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('bitcoincash:qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
|
||||
* // 1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN
|
||||
*
|
||||
* // mainnet cashaddr w/ no prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('qzm47qz5ue99y9yl4aca7jnz7dwgdenl85jkfx3znl')
|
||||
* // 1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN
|
||||
*
|
||||
* // mainnet slpaddr w/ prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('simpleledger:qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzdp')
|
||||
* // 1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN
|
||||
*
|
||||
* // mainnet slpaddr w/ no prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('qzm47qz5ue99y9yl4aca7jnz7dwgdenl857dzayzdp')
|
||||
* // 1HiaTupadqQN66Tvgt7QSE5Wg13BUy25eN
|
||||
*
|
||||
* // testnet cashaddr w/ prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // mqc1tmwY2368LLGktnePzEyPAsgADxbksi
|
||||
*
|
||||
* // testnet cashaddr w/ no prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // mqc1tmwY2368LLGktnePzEyPAsgADxbksi
|
||||
*
|
||||
* // testnet slpaddr w/ prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // mqc1tmwY2368LLGktnePzEyPAsgADxbksi
|
||||
*
|
||||
* // testnet slpaddr w/ no prefix
|
||||
* bchjs.SLP.Address.toLegacyAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // mqc1tmwY2368LLGktnePzEyPAsgADxbksi
|
||||
*/
|
||||
toLegacyAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return bchAddress.toLegacyAddress(cashAddr)
|
||||
}
|
||||
|
||||
isLegacyAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
return bchAddress.isLegacyAddress(address)
|
||||
}
|
||||
|
||||
isCashAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
if (bchaddrjs.isSlpAddress(address)) return false
|
||||
|
||||
return bchAddress.isCashAddress(address)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Address.isSLPAddress() isSLPAddress() - Detect if slpAddr encoded address.
|
||||
* @apiName isSLPAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect if slpAddr encoded address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* // mainnet slpaddr
|
||||
* bchjs.SLP.Address.isSLPAddress('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // true
|
||||
*
|
||||
* // mainnet w/ no slpaddr prefix
|
||||
* bchjs.SLP.Address.isSLPAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // true
|
||||
*
|
||||
* // mainnet legacy
|
||||
* bchjs.SLP.Address.isSLPAddress('18HEMuar5ZhXDFep1gEiY1eoPPcBLxfDxj')
|
||||
* // false
|
||||
*
|
||||
* // testnet w/ slpaddr prefix
|
||||
* bchjs.SLP.Address.isSLPAddress('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no slpaddr prefix
|
||||
* bchjs.SLP.Address.isSLPAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // true
|
||||
*
|
||||
* // testnet legacy
|
||||
* bchjs.SLP.Address.isSLPAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // false
|
||||
*/
|
||||
isSLPAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
return bchaddrjs.isSlpAddress(address)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Address.isMainnetAddress() isMainnetAddress() - Detect if mainnet address.
|
||||
* @apiName isMainnetAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect if mainnet address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* // mainnet cashaddr
|
||||
* bchjs.SLP.Address.isMainnetAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet cashaddr w/ no prefix
|
||||
* bchjs.SLP.Address.isMainnetAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet slpaddr
|
||||
* bchjs.SLP.Address.isMainnetAddress('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // true
|
||||
*
|
||||
* // mainnet slpaddr w/ no prefix
|
||||
* bchjs.SLP.Address.isMainnetAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // true
|
||||
*
|
||||
* // mainnet legacy
|
||||
* bchjs.SLP.Address.isMainnetAddress('14krEkSaKoTkbFT9iUCfUYARo4EXA8co6M')
|
||||
* // true
|
||||
*
|
||||
* // testnet cashaddr
|
||||
* bchjs.SLP.Address.isMainnetAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.SLP.Address.isMainnetAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // testnet slpaddr
|
||||
* bchjs.SLP.Address.isMainnetAddress('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // false
|
||||
*
|
||||
* // testnet w/ no slpaddr prefix
|
||||
* bchjs.SLP.Address.isMainnetAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // false
|
||||
*
|
||||
* // testnet legacy
|
||||
* bchjs.SLP.Address.isMainnetAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // false
|
||||
*/
|
||||
isMainnetAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashaddr = bchaddrjs.toCashAddress(address)
|
||||
return bchAddress.isMainnetAddress(cashaddr)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.Address.isTestnetAddress() isTestnetAddress() - Detect if testnet address.
|
||||
* @apiName isTestnetAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect if testnet address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // cashaddr mainnet
|
||||
* bchjs.SLP.Address.isTestnetAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* //false
|
||||
*
|
||||
* // w/ no cashaddr prefix
|
||||
* bchjs.SLP.Address.isTestnetAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // slpaddr mainnet
|
||||
* bchjs.SLP.Address.isTestnetAddress('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* //false
|
||||
*
|
||||
* // w/ no slpaddr prefix
|
||||
* bchjs.SLP.Address.isTestnetAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // false
|
||||
*
|
||||
* // legacy mainnet
|
||||
* bchjs.SLP.Address.isTestnetAddress('14krEkSaKoTkbFT9iUCfUYARo4EXA8co6M')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.SLP.Address.isTestnetAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.SLP.Address.isTestnetAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // slpaddr testnet
|
||||
* bchjs.SLP.Address.isTestnetAddress('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no slpaddr prefix
|
||||
* bchjs.SLP.Address.isTestnetAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // true
|
||||
*
|
||||
* // testnet legacy
|
||||
* bchjs.SLP.Address.isTestnetAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // true
|
||||
*/
|
||||
isTestnetAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return bchAddress.isTestnetAddress(cashAddr)
|
||||
}
|
||||
/**
|
||||
* @api SLP.Address.isP2PKHAddress() isP2PKHAddress() - Detect if p2pkh address.
|
||||
* @apiName isP2PKHAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect if p2pkh address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet cashaddr
|
||||
* bchjs.SLP.Address.isP2PKHAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet w/ no cashaddr prefix
|
||||
* bchjs.SLP.Address.isP2PKHAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // true
|
||||
*
|
||||
* // mainnet slpaddr
|
||||
* bchjs.SLP.Address.isP2PKHAddress('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // true
|
||||
*
|
||||
* // mainnet w/ no slpaddr prefix
|
||||
* bchjs.SLP.Address.isP2PKHAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // true
|
||||
*
|
||||
* // legacy
|
||||
* bchjs.SLP.Address.isP2PKHAddress('14krEkSaKoTkbFT9iUCfUYARo4EXA8co6M')
|
||||
* // true
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.SLP.Address.isP2PKHAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no cashaddr prefix
|
||||
* bchjs.SLP.Address.isP2PKHAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // true
|
||||
*
|
||||
* // slpaddr testnet
|
||||
* bchjs.SLP.Address.isP2PKHAddress('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // true
|
||||
*
|
||||
* // testnet w/ no slpaddr prefix
|
||||
* bchjs.SLP.Address.isP2PKHAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // true
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.SLP.Address.isP2PKHAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // true
|
||||
*/
|
||||
isP2PKHAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return bchAddress.isP2PKHAddress(cashAddr)
|
||||
}
|
||||
/**
|
||||
* @api SLP.Address.isP2SHAddress() isP2SHAddress() - Detect if p2sh address.
|
||||
* @apiName isP2SHAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect if p2sh address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet cashaddr
|
||||
* bchjs.SLP.Address.isP2SHAddress('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // mainnet cashaddr w/ no prefix
|
||||
* bchjs.SLP.Address.isP2SHAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // false
|
||||
*
|
||||
* // mainnet slpaddr
|
||||
* bchjs.SLP.Address.isP2SHAddress('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // false
|
||||
*
|
||||
* // mainnet slpaddr w/ no prefix
|
||||
* bchjs.SLP.Address.isP2SHAddress('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // false
|
||||
*
|
||||
* // mainnet legacy
|
||||
* bchjs.SLP.Address.isP2SHAddress('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.SLP.Address.isP2SHAddress('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.isP2SHAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // false
|
||||
*
|
||||
* // slpaddr testnet
|
||||
* bchjs.SLP.Address.isP2SHAddress('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // false
|
||||
*
|
||||
* // slpaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.isP2SHAddress('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // false
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.SLP.Address.isP2SHAddress('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // false
|
||||
*/
|
||||
isP2SHAddress(address) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return bchAddress.isP2SHAddress(cashAddr)
|
||||
}
|
||||
/**
|
||||
* @api SLP.Address.detectAddressFormat() detectAddressFormat() - Detect address format.
|
||||
* @apiName detectAddressFormat
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect address format.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet cashaddr
|
||||
* bchjs.SLP.Address.detectAddressFormat('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // cashaddr
|
||||
*
|
||||
* // mainnet cashaddr w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressFormat('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // cashaddr
|
||||
*
|
||||
* // mainnet slpaddr
|
||||
* bchjs.SLP.Address.detectAddressFormat('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // slpaddr
|
||||
*
|
||||
* // mainnet slpaddr w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressFormat('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // slpaddr
|
||||
*
|
||||
* // mainnet legacy
|
||||
* bchjs.SLP.Address.detectAddressFormat('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74')
|
||||
* // legacy
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.SLP.Address.detectAddressFormat('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // cashaddr
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressFormat('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // cashaddr
|
||||
*
|
||||
* // slpaddr testnet
|
||||
* bchjs.SLP.Address.detectAddressFormat('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // slpaddr
|
||||
*
|
||||
* // slpaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressFormat('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // slpaddr
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.SLP.Address.detectAddressFormat('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // legacy
|
||||
*/
|
||||
detectAddressFormat(address) {
|
||||
this._ensureValidAddress(address)
|
||||
if (bchaddrjs.isSlpAddress(address)) return "slpaddr"
|
||||
|
||||
return bchAddress.detectAddressFormat(address)
|
||||
}
|
||||
/**
|
||||
* @api SLP.Address.detectAddressNetwork() detectAddressNetwork() - Detect address network.
|
||||
* @apiName detectAddressNetwork
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect address network.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainnet cashaddr
|
||||
* bchjs.SLP.Address.detectAddressNetwork('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // mainnet
|
||||
*
|
||||
* // mainnet cashaddr w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressNetwork('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s')
|
||||
* // mainnet
|
||||
*
|
||||
* // mainnet slpaddr
|
||||
* bchjs.SLP.Address.detectAddressNetwork('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // mainnet
|
||||
*
|
||||
* // mainnet slpaddr w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressNetwork('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w')
|
||||
* // mainnet
|
||||
*
|
||||
* // mainnet legacy
|
||||
* bchjs.SLP.Address.detectAddressNetwork('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74')
|
||||
* // mainnet
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.SLP.Address.detectAddressNetwork('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // testnet
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressNetwork('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy')
|
||||
* // testnet
|
||||
*
|
||||
* // slpaddr testnet
|
||||
* bchjs.SLP.Address.detectAddressNetwork('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // testnet
|
||||
*
|
||||
* // slpaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressNetwork('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse')
|
||||
* // testnet
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.SLP.Address.detectAddressNetwork('mqc1tmwY2368LLGktnePzEyPAsgADxbksi')
|
||||
* // testnet
|
||||
*/
|
||||
detectAddressNetwork(address) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return bchAddress.detectAddressNetwork(cashAddr)
|
||||
}
|
||||
/**
|
||||
* @api SLP.Address.detectAddressType() detectAddressType() - Detect address type.
|
||||
* @apiName detectAddressType
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Detect address type.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // mainet cashaddr
|
||||
* bchjs.SLP.Address.detectAddressType('bitcoincash:qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s');
|
||||
* // p2pkh
|
||||
*
|
||||
* // mainet cashaddr w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressType('qqfx3wcg8ts09mt5l3zey06wenapyfqq2qrcyj5x0s');
|
||||
* // p2pkh
|
||||
*
|
||||
* // mainet slpaddr
|
||||
* bchjs.SLP.Address.detectAddressType('simpleledger:qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w');
|
||||
* // p2pkh
|
||||
*
|
||||
* // mainet slpaddr w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressType('qqfx3wcg8ts09mt5l3zey06wenapyfqq2q0r0fpx3w');
|
||||
* // p2pkh
|
||||
*
|
||||
* // mainet legacy
|
||||
* bchjs.SLP.Address.detectAddressType('1NoYQso5UF6XqC4NbjKAp2EnjJ59yLNn74');
|
||||
* // p2pkh
|
||||
*
|
||||
* // cashaddr testnet
|
||||
* bchjs.SLP.Address.detectAddressType('bchtest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy');
|
||||
* // p2pkh
|
||||
*
|
||||
* // cashaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressType('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggt9t0a6zy');
|
||||
* // p2pkh
|
||||
*
|
||||
* // slpaddr testnet
|
||||
* bchjs.SLP.Address.detectAddressType('slptest:qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse');
|
||||
* // p2pkh
|
||||
*
|
||||
* // slpaddr testnet w/ no prefix
|
||||
* bchjs.SLP.Address.detectAddressType('qph2v4mkxjgdqgmlyjx6njmey0ftrxlnggs3v58dse');
|
||||
* // p2pkh
|
||||
*
|
||||
* // legacy testnet
|
||||
* bchjs.SLP.Address.detectAddressType('mqc1tmwY2368LLGktnePzEyPAsgADxbksi');
|
||||
* // p2pkh
|
||||
*/
|
||||
detectAddressType(address) {
|
||||
this._ensureValidAddress(address)
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return bchAddress.detectAddressType(cashAddr)
|
||||
}
|
||||
/*
|
||||
async details(address) {
|
||||
let tmpBITBOX
|
||||
let network
|
||||
if (typeof address === "string")
|
||||
network = this.detectAddressNetwork(address)
|
||||
else network = this.detectAddressNetwork(address[0])
|
||||
|
||||
if (network === "mainnet")
|
||||
tmpBITBOX = new BITBOX({ restURL: "https://rest.bitcoin.com/v2/" })
|
||||
else tmpBITBOX = new BITBOX({ restURL: "https://trest.bitcoin.com/v2/" })
|
||||
|
||||
if (typeof address === "string") {
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return tmpBITBOX.Address.details(cashAddr)
|
||||
}
|
||||
address = address.map(address => bchaddrjs.toCashAddress(address))
|
||||
return tmpBITBOX.Address.details(address)
|
||||
}
|
||||
|
||||
async utxo(address) {
|
||||
let tmpBITBOX
|
||||
let network
|
||||
if (typeof address === "string")
|
||||
network = this.detectAddressNetwork(address)
|
||||
else network = this.detectAddressNetwork(address[0])
|
||||
|
||||
if (network === "mainnet")
|
||||
tmpBITBOX = new BITBOX({ restURL: "https://rest.bitcoin.com/v2/" })
|
||||
else tmpBITBOX = new BITBOX({ restURL: "https://trest.bitcoin.com/v2/" })
|
||||
|
||||
if (typeof address === "string") {
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return tmpBITBOX.Address.utxo(cashAddr)
|
||||
}
|
||||
address = address.map(address => bchaddrjs.toCashAddress(address))
|
||||
return tmpBITBOX.Address.utxo(address)
|
||||
}
|
||||
|
||||
async unconfirmed(address) {
|
||||
let tmpBITBOX
|
||||
let network
|
||||
if (typeof address === "string")
|
||||
network = this.detectAddressNetwork(address)
|
||||
else network = this.detectAddressNetwork(address[0])
|
||||
|
||||
if (network === "mainnet")
|
||||
tmpBITBOX = new BITBOX({ restURL: "https://rest.bitcoin.com/v2/" })
|
||||
else tmpBITBOX = new BITBOX({ restURL: "https://trest.bitcoin.com/v2/" })
|
||||
|
||||
if (typeof address === "string") {
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return tmpBITBOX.Address.unconfirmed(cashAddr)
|
||||
}
|
||||
address = address.map(address => bchaddrjs.toCashAddress(address))
|
||||
return tmpBITBOX.Address.unconfirmed(address)
|
||||
}
|
||||
|
||||
async transactions(address) {
|
||||
let tmpBITBOX
|
||||
let network
|
||||
if (typeof address === "string")
|
||||
network = this.detectAddressNetwork(address)
|
||||
else network = this.detectAddressNetwork(address[0])
|
||||
|
||||
if (network === "mainnet")
|
||||
tmpBITBOX = new BITBOX({ restURL: "https://rest.bitcoin.com/v2/" })
|
||||
else tmpBITBOX = new BITBOX({ restURL: "https://trest.bitcoin.com/v2/" })
|
||||
|
||||
if (typeof address === "string") {
|
||||
const cashAddr = bchaddrjs.toCashAddress(address)
|
||||
return tmpBITBOX.Address.transactions(cashAddr)
|
||||
}
|
||||
address = address.map(address => bchaddrjs.toCashAddress(address))
|
||||
return tmpBITBOX.Address.transactions(address)
|
||||
}
|
||||
*/
|
||||
_ensureValidAddress(address) {
|
||||
try {
|
||||
bchaddrjs.toCashAddress(address)
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Invalid BCH address. Double check your address is valid: ${address}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Address
|
||||
@@ -0,0 +1,34 @@
|
||||
//const BCHJS = require("../bch-js")
|
||||
//const bchjs = new BCHJS()
|
||||
|
||||
const BCHJSECPair = require("../ecpair")
|
||||
|
||||
const bchaddrjs = require("bchaddrjs-slp")
|
||||
|
||||
class ECPair extends BCHJSECPair {
|
||||
/*
|
||||
constructor(restURL) {
|
||||
super(restURL)
|
||||
this.restURL = restURL
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* @api SLP.ECPair.toSLPAddress() toSLPAddress() - Get slp address of ECPair.
|
||||
* @apiName toSLPAddress
|
||||
* @apiGroup SLP
|
||||
* @apiDescription Get slp address of ECPair.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // create ecpair from wif
|
||||
* let ecpair = bchjs.SLP.ECPair.fromWIF('cUCSrdhu7mCzx4sWqL6irqzprkofxPmLHYgkSnG2WaWVqJDXtWRS')
|
||||
* // to slp address
|
||||
* bchjs.SLP.ECPair.toSLPAddress(ecpair);
|
||||
* // slptest:qq835u5srlcqwrtwt6xm4efwan30fxg9hcqag6fk03
|
||||
*/
|
||||
static toSLPAddress(ecpair) {
|
||||
const slpAddress = bchaddrjs.toSlpAddress(this.toCashAddress(ecpair))
|
||||
return slpAddress
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ECPair
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
/*
|
||||
This library wraps the slp-mdm library to generate the OP_RETURN for NFT1 tokens.
|
||||
|
||||
NFT Group tokens (Parents) are generated and minted. They are like amorphous
|
||||
NFTs; like stem cells that haven't specialized yet.
|
||||
|
||||
NFT 'Children' are the 'real' NFTs. They are created by burning an NFT Group
|
||||
(Parent) token.
|
||||
*/
|
||||
|
||||
const Address = require("./address")
|
||||
|
||||
const BigNumber = require("bignumber.js")
|
||||
const slpMdm = require("slp-mdm")
|
||||
|
||||
// const addy = new Address()
|
||||
let addy
|
||||
const TransactionBuilder = require("../transaction-builder")
|
||||
|
||||
class TokenType1 {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
|
||||
addy = new Address(config)
|
||||
|
||||
// Instantiate the transaction builder.
|
||||
TransactionBuilder.setAddress(addy)
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.NFT1.newNFTGroupOpReturn() newNFTGroupOpReturn()
|
||||
* @apiName newNFTGroupOpReturn
|
||||
* @apiGroup SLP NFT1
|
||||
* @apiDescription Generate the OP_RETURN value needed to create an SLP
|
||||
* NFT Group token.
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const configObj = {
|
||||
* name: "SLP Test Token",
|
||||
* ticker: "SLPTEST",
|
||||
* documentUrl: "https://FullStack.cash",
|
||||
* initialQty: 1
|
||||
* }
|
||||
*
|
||||
* const result = await bchjs.SLP.NFT1.newNFTGroupOpReturn(
|
||||
* configObj
|
||||
* )
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/tree/master/applications/slp/nft
|
||||
*
|
||||
*/
|
||||
newNFTGroupOpReturn(configObj) {
|
||||
try {
|
||||
// TODO: Add input validation.
|
||||
|
||||
// Prevent error if user fails to add the document hash.
|
||||
if (!configObj.documentHash) configObj.documentHash = ""
|
||||
|
||||
// If mint baton is not specified, then replace it with null.
|
||||
if (!configObj.mintBatonVout) configObj.mintBatonVout = null
|
||||
|
||||
const script = slpMdm.NFT1.Group.genesis(
|
||||
configObj.ticker,
|
||||
configObj.name,
|
||||
configObj.documentUrl,
|
||||
configObj.documentHash,
|
||||
0,
|
||||
configObj.mintBatonVout,
|
||||
new slpMdm.BN(configObj.initialQty)
|
||||
)
|
||||
|
||||
return script
|
||||
} catch (err) {
|
||||
console.log(`Error in generateNFTParentOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Mint additional NFT Group 'Parent' tokens.
|
||||
/**
|
||||
* @api SLP.NFT1.mintNFTGroupOpReturn() mintNFTGroupOpReturn()
|
||||
* @apiName mintNFTGroupOpReturn
|
||||
* @apiGroup SLP NFT1
|
||||
* @apiDescription Generate the OP_RETURN value needed to create an SLP Mint
|
||||
* transaction for an NFT Group token.
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const addr = "bitcoincash:qq6xz6wwcy78uh79vgjvfyahj4arq269w5an8pcjak"
|
||||
* const utxos = await bchjs.Blockbook.utxos(addr)
|
||||
*
|
||||
* // Identify the SLP token UTXOs.
|
||||
* let tokenUtxos = await bchjs.SLP.Utils.tokenUtxoDetails(utxos);
|
||||
*
|
||||
* // Filter out the minting baton.
|
||||
* tokenUtxos = tokenUtxos.filter((utxo, index) => {
|
||||
* if (
|
||||
* utxo && // UTXO is associated with a token.
|
||||
* utxo.tokenId === TOKENID && // UTXO matches the token ID.
|
||||
* utxo.utxoType === "minting-baton" && // UTXO is not a minting baton.
|
||||
* utxo.tokenType === 129 // UTXO is for NFT Group
|
||||
* )
|
||||
* return true;
|
||||
* });
|
||||
*
|
||||
* // Generate the SLP OP_RETURN
|
||||
* const slpData = bchjs.SLP.NFT1.mintNFTGroupOpReturn(
|
||||
* tokenUtxos,
|
||||
* 1 // Mint 1 new token.
|
||||
* );
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/tree/master/applications/slp/nft
|
||||
*/
|
||||
mintNFTGroupOpReturn(tokenUtxos, mintQty, destroyBaton = false) {
|
||||
try {
|
||||
// Throw error if input is not an array.
|
||||
if (!Array.isArray(tokenUtxos))
|
||||
throw new Error(`tokenUtxos must be an array.`)
|
||||
|
||||
// Loop through the tokenUtxos array and find the minting baton.
|
||||
let mintBatonUtxo
|
||||
for (let i = 0; i < tokenUtxos.length; i++) {
|
||||
if (tokenUtxos[i].utxoType === "minting-baton")
|
||||
mintBatonUtxo = tokenUtxos[i]
|
||||
}
|
||||
|
||||
// Throw an error if the minting baton could not be found.
|
||||
if (!mintBatonUtxo)
|
||||
throw new Error(`Minting baton could not be found in tokenUtxos array.`)
|
||||
|
||||
const tokenId = mintBatonUtxo.tokenId
|
||||
|
||||
if (!tokenId)
|
||||
throw new Error(`tokenId property not found in mint-baton UTXO.`)
|
||||
|
||||
// Signal that the baton should be passed or detroyed.
|
||||
let batonVout = 2
|
||||
if (destroyBaton) batonVout = null
|
||||
|
||||
const script = slpMdm.NFT1.Group.mint(
|
||||
tokenId,
|
||||
batonVout,
|
||||
new slpMdm.BN(mintQty)
|
||||
)
|
||||
|
||||
return script
|
||||
} catch (err) {
|
||||
// console.log(`Error in generateMintOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.NFT1.generateNFTChildGenesisOpReturn() generateNFTChildGenesisOpReturn()
|
||||
* @apiName generateNFTChildGenesisOpReturn
|
||||
* @apiGroup SLP NFT1
|
||||
* @apiDescription Generate the OP_RETURN value needed to create an SLP
|
||||
* NFT Child token.
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const configObj = {
|
||||
* name: "NFT Child",
|
||||
* ticker: "NFTC",
|
||||
* documentUrl: "https://FullStack.cash",
|
||||
* }
|
||||
*
|
||||
* const result = await bchjs.SLP.NFT1.generateNFTChildGenesisOpReturn(
|
||||
* configObj
|
||||
* )
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/tree/master/applications/slp/nft
|
||||
*
|
||||
*/
|
||||
generateNFTChildGenesisOpReturn(configObj) {
|
||||
try {
|
||||
// TODO: Add input validation.
|
||||
|
||||
// Prevent error if user fails to add the document hash.
|
||||
if (!configObj.documentHash) configObj.documentHash = ""
|
||||
|
||||
// If mint baton is not specified, then replace it with null.
|
||||
if (!configObj.mintBatonVout) configObj.mintBatonVout = null
|
||||
|
||||
const script = slpMdm.NFT1.Child.genesis(
|
||||
configObj.ticker,
|
||||
configObj.name,
|
||||
configObj.documentUrl,
|
||||
configObj.documentHash,
|
||||
0,
|
||||
configObj.mintBatonVout,
|
||||
new slpMdm.BN("1")
|
||||
)
|
||||
|
||||
return script
|
||||
} catch (err) {
|
||||
console.log(`Error in generateNFTChildGenesisOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.NFT1.generateNFTChildSendOpReturn() generateNFTChildSendOpReturn()
|
||||
* @apiName generateNFTChildSendOpReturn
|
||||
* @apiGroup SLP NFT1
|
||||
* @apiDescription Generate the OP_RETURN value needed to send an SLP NFT
|
||||
* Child token to another address.
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const addr = "bitcoincash:qq6xz6wwcy78uh79vgjvfyahj4arq269w5an8pcjak"
|
||||
* const utxos = await bchjs.Blockbook.utxos(addr)
|
||||
*
|
||||
* // Identify the SLP token UTXOs.
|
||||
* let tokenUtxos = await bchjs.SLP.Utils.tokenUtxoDetails(utxos);
|
||||
*
|
||||
* // Filter out the token UTXOs that match the user-provided token ID.
|
||||
* tokenUtxos = tokenUtxos.filter((utxo, index) => {
|
||||
* if (
|
||||
* utxo && // UTXO is associated with a token.
|
||||
* utxo.tokenId === TOKENID && // UTXO matches the token ID.
|
||||
* utxo.tokenType === "token" && // UTXO is not a minting baton.
|
||||
* utxo.tokenType === 65 // UTXO is for an NFT Child
|
||||
* )
|
||||
* return true;
|
||||
* });
|
||||
*
|
||||
* // Generate the SEND OP_RETURN
|
||||
* const slpData = bchjs.SLP.NFT1.generateNFTChildSendOpReturn(
|
||||
* tokenUtxos,
|
||||
* TOKENQTY
|
||||
* );
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/tree/master/applications/slp/nft
|
||||
*/
|
||||
generateNFTChildSendOpReturn(tokenUtxos, sendQty) {
|
||||
try {
|
||||
// TODO: Add input validation.
|
||||
|
||||
const tokenId = tokenUtxos[0].tokenId
|
||||
|
||||
// Calculate the total amount of tokens owned by the wallet.
|
||||
let totalTokens = 0
|
||||
for (let i = 0; i < tokenUtxos.length; i++)
|
||||
totalTokens += tokenUtxos[i].tokenQty
|
||||
|
||||
const change = totalTokens - sendQty
|
||||
|
||||
let script
|
||||
let outputs = 1
|
||||
|
||||
// The normal case, when there is token change to return to sender.
|
||||
if (change > 0) {
|
||||
outputs = 2
|
||||
|
||||
// Convert to integer string.
|
||||
const sendStr = Math.floor(sendQty).toString()
|
||||
const changeStr = Math.floor(change).toString()
|
||||
|
||||
// Generate the OP_RETURN as a Buffer.
|
||||
script = slpMdm.NFT1.Child.send(tokenId, [
|
||||
new slpMdm.BN(sendStr),
|
||||
new slpMdm.BN(changeStr)
|
||||
])
|
||||
//
|
||||
|
||||
// Corner case, when there is no token change to send back.
|
||||
} else {
|
||||
// Convert to integer string.
|
||||
const sendStr = Math.floor(sendQty).toString()
|
||||
|
||||
// Generate the OP_RETURN as a Buffer.
|
||||
script = slpMdm.NFT1.Child.send(tokenId, [new slpMdm.BN(sendStr)])
|
||||
}
|
||||
|
||||
return { script, outputs }
|
||||
} catch (err) {
|
||||
console.log(`Error in generateNFTChildSendOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.NFT1.generateNFTGroupSendOpReturn() generateNFTGroupSendOpReturn()
|
||||
* @apiName generateNFTGroupSendOpReturn
|
||||
* @apiGroup SLP NFT1
|
||||
* @apiDescription Generate the OP_RETURN value needed to send an SLP NFT
|
||||
* Group token to another address.
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const addr = "bitcoincash:qq6xz6wwcy78uh79vgjvfyahj4arq269w5an8pcjak"
|
||||
* const utxos = await bchjs.Blockbook.utxos(addr)
|
||||
*
|
||||
* // Identify the SLP token UTXOs.
|
||||
* let tokenUtxos = await bchjs.SLP.Utils.tokenUtxoDetails(utxos);
|
||||
*
|
||||
* // Filter out the token UTXOs that match the user-provided token ID.
|
||||
* tokenUtxos = tokenUtxos.filter((utxo, index) => {
|
||||
* if (
|
||||
* utxo && // UTXO is associated with a token.
|
||||
* utxo.tokenId === TOKENID && // UTXO matches the token ID.
|
||||
* utxo.tokenType === "token" && // UTXO is not a minting baton.
|
||||
* utxo.tokenType === 129 // UTXO is for an NFT Group
|
||||
* )
|
||||
* return true;
|
||||
* });
|
||||
*
|
||||
* // Generate the SEND OP_RETURN
|
||||
* const slpData = bchjs.SLP.NFT1.generateNFTGroupSendOpReturn(
|
||||
* tokenUtxos,
|
||||
* TOKENQTY
|
||||
* );
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/tree/master/applications/slp/nft
|
||||
*/
|
||||
generateNFTGroupSendOpReturn(tokenUtxos, sendQty) {
|
||||
try {
|
||||
// TODO: Add input validation.
|
||||
|
||||
const tokenId = tokenUtxos[0].tokenId
|
||||
|
||||
// Calculate the total amount of tokens owned by the wallet.
|
||||
let totalTokens = 0
|
||||
for (let i = 0; i < tokenUtxos.length; i++)
|
||||
totalTokens += tokenUtxos[i].tokenQty
|
||||
|
||||
const change = totalTokens - sendQty
|
||||
|
||||
let script
|
||||
let outputs = 1
|
||||
|
||||
// The normal case, when there is token change to return to sender.
|
||||
if (change > 0) {
|
||||
outputs = 2
|
||||
|
||||
// Convert to integer string.
|
||||
const sendStr = Math.floor(sendQty).toString()
|
||||
const changeStr = Math.floor(change).toString()
|
||||
|
||||
// Generate the OP_RETURN as a Buffer.
|
||||
script = slpMdm.NFT1.Group.send(tokenId, [
|
||||
new slpMdm.BN(sendStr),
|
||||
new slpMdm.BN(changeStr)
|
||||
])
|
||||
//
|
||||
|
||||
// Corner case, when there is no token change to send back.
|
||||
} else {
|
||||
// Convert to integer string.
|
||||
const sendStr = Math.floor(sendQty).toString()
|
||||
|
||||
// Generate the OP_RETURN as a Buffer.
|
||||
script = slpMdm.NFT1.Group.send(tokenId, [new slpMdm.BN(sendStr)])
|
||||
}
|
||||
|
||||
return { script, outputs }
|
||||
} catch (err) {
|
||||
console.log(`Error in generateNFTGroupSendOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TokenType1
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
This is the parent library for the SLP class. It was originally forked from slp-sdk.
|
||||
|
||||
TODO: Create an SLP fee calculator like slpjs:
|
||||
https://github.com/simpleledger/slpjs/blob/master/lib/slp.ts#L921
|
||||
*/
|
||||
|
||||
// imports
|
||||
// require deps
|
||||
//const BCHJS = require("../bch-js")
|
||||
const Address = require("./address")
|
||||
const ECPair = require("./ecpair")
|
||||
// const HDNode = require("./hdnode")
|
||||
const TokenType1 = require("./tokentype1")
|
||||
const NFT1 = require("./nft1")
|
||||
const Utils = require("./utils")
|
||||
|
||||
// SLP is a superset of BITBOX
|
||||
class SLP {
|
||||
constructor(config) {
|
||||
const tmp = {}
|
||||
if (!config || !config.restURL) {
|
||||
tmp.restURL = `https://api.fullstack.cash/v3/`
|
||||
} else {
|
||||
tmp.restURL = config.restURL
|
||||
tmp.apiToken = config.apiToken
|
||||
}
|
||||
|
||||
this.restURL = tmp.restURL
|
||||
this.apiToken = tmp.apiToken
|
||||
|
||||
this.Address = new Address(tmp)
|
||||
this.ECPair = ECPair
|
||||
this.TokenType1 = new TokenType1(tmp)
|
||||
this.NFT1 = new NFT1(this.restURL)
|
||||
this.Utils = new Utils(tmp)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SLP
|
||||
@@ -0,0 +1,435 @@
|
||||
//const BCHJS = require("../bch-js")
|
||||
//const bchjs = new BCHJS()
|
||||
|
||||
const Address = require("./address")
|
||||
const Script = require("../script")
|
||||
|
||||
const BigNumber = require("bignumber.js")
|
||||
const slpMdm = require("slp-mdm")
|
||||
const axios = require("axios")
|
||||
|
||||
// const addy = new Address()
|
||||
let addy
|
||||
const TransactionBuilder = require("../transaction-builder")
|
||||
|
||||
let _this // local global
|
||||
|
||||
class TokenType1 {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
addy = new Address(config)
|
||||
this.Script = new Script()
|
||||
|
||||
this.axios = axios
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
// Instantiate the transaction builder.
|
||||
TransactionBuilder.setAddress(addy)
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.TokenType1.generateSendOpReturn() generateSendOpReturn()
|
||||
* @apiName generateSendOpReturn
|
||||
* @apiGroup SLP TokenType1
|
||||
* @apiDescription Generate the OP_RETURN value needed to create an SLP Send transaction.
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const addr = "bitcoincash:qq6xz6wwcy78uh79vgjvfyahj4arq269w5an8pcjak"
|
||||
* const utxos = await bchjs.Blockbook.utxos(addr)
|
||||
*
|
||||
* // Identify the SLP token UTXOs.
|
||||
* let tokenUtxos = await bchjs.SLP.Utils.tokenUtxoDetails(utxos);
|
||||
*
|
||||
* // Filter out the token UTXOs that match the user-provided token ID.
|
||||
* tokenUtxos = tokenUtxos.filter((utxo, index) => {
|
||||
* if (
|
||||
* utxo && // UTXO is associated with a token.
|
||||
* utxo.tokenId === TOKENID && // UTXO matches the token ID.
|
||||
* utxo.tokenType === "token" // UTXO is not a minting baton.
|
||||
* )
|
||||
* return true;
|
||||
* });
|
||||
*
|
||||
* // Generate the SEND OP_RETURN
|
||||
* const slpData = bchjs.SLP.TokenType1.generateSendOpReturn(
|
||||
* tokenUtxos,
|
||||
* TOKENQTY
|
||||
* );
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/blob/master/applications/slp/send-token/send-token.js
|
||||
*/
|
||||
generateSendOpReturn(tokenUtxos, sendQty) {
|
||||
try {
|
||||
const tokenId = tokenUtxos[0].tokenId
|
||||
const decimals = tokenUtxos[0].decimals
|
||||
|
||||
// Calculate the total amount of tokens owned by the wallet.
|
||||
let totalTokens = 0
|
||||
for (let i = 0; i < tokenUtxos.length; i++)
|
||||
totalTokens += tokenUtxos[i].tokenQty
|
||||
|
||||
const change = totalTokens - sendQty
|
||||
// console.log(`change: ${change}`)
|
||||
|
||||
let script
|
||||
let outputs = 1
|
||||
|
||||
// The normal case, when there is token change to return to sender.
|
||||
if (change > 0) {
|
||||
outputs = 2
|
||||
|
||||
// Convert the send quantity to the format expected by slp-mdm.
|
||||
let baseQty = new BigNumber(sendQty).times(10 ** decimals)
|
||||
baseQty = baseQty.absoluteValue()
|
||||
baseQty = Math.floor(baseQty)
|
||||
baseQty = baseQty.toString()
|
||||
// console.log(`baseQty: `, baseQty)
|
||||
|
||||
// Convert the change quantity to the format expected by slp-mdm.
|
||||
let baseChange = new BigNumber(change).times(10 ** decimals)
|
||||
baseChange = baseChange.absoluteValue()
|
||||
baseChange = Math.floor(baseChange)
|
||||
baseChange = baseChange.toString()
|
||||
// console.log(`baseChange: `, baseChange)
|
||||
|
||||
// Generate the OP_RETURN as a Buffer.
|
||||
script = slpMdm.TokenType1.send(tokenId, [
|
||||
new slpMdm.BN(baseQty),
|
||||
new slpMdm.BN(baseChange)
|
||||
])
|
||||
//
|
||||
|
||||
// Corner case, when there is no token change to send back.
|
||||
} else {
|
||||
let baseQty = new BigNumber(sendQty).times(10 ** decimals)
|
||||
baseQty = baseQty.absoluteValue()
|
||||
baseQty = Math.floor(baseQty)
|
||||
baseQty = baseQty.toString()
|
||||
// console.log(`baseQty: `, baseQty)
|
||||
|
||||
// console.log(`baseQty: ${baseQty.toString()}`)
|
||||
|
||||
// Generate the OP_RETURN as a Buffer.
|
||||
script = slpMdm.TokenType1.send(tokenId, [new slpMdm.BN(baseQty)])
|
||||
}
|
||||
|
||||
return { script, outputs }
|
||||
} catch (err) {
|
||||
console.log(`Error in generateSendOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.TokenType1.generateBurnOpReturn() generateBurnOpReturn()
|
||||
* @apiName generateBurnOpReturn
|
||||
* @apiGroup SLP TokenType1
|
||||
* @apiDescription Generate the OP_RETURN value needed to create a SLP Send
|
||||
* transaction that burns tokens.
|
||||
* This is a slight variation of generateSendOpReturn(). It generates a SLP
|
||||
* SEND transaction designed to burn a select quantity of tokens.
|
||||
*
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const addr = "bitcoincash:qq6xz6wwcy78uh79vgjvfyahj4arq269w5an8pcjak"
|
||||
* const utxos = await bchjs.Blockbook.utxos(addr)
|
||||
*
|
||||
* // Identify the SLP token UTXOs.
|
||||
* let tokenUtxos = await bchjs.SLP.Utils.tokenUtxoDetails(utxos);
|
||||
*
|
||||
* // Filter out the token UTXOs that match the user-provided token ID.
|
||||
* tokenUtxos = tokenUtxos.filter((utxo, index) => {
|
||||
* if (
|
||||
* utxo && // UTXO is associated with a token.
|
||||
* utxo.tokenId === TOKENID && // UTXO matches the token ID.
|
||||
* utxo.tokenType === "token" // UTXO is not a minting baton.
|
||||
* )
|
||||
* return true;
|
||||
* });
|
||||
*
|
||||
* // Generate the SEND OP_RETURN
|
||||
* const slpData = bchjs.SLP.TokenType1.generateBurnOpReturn(
|
||||
* tokenUtxos,
|
||||
* 10 // Burn 10 tokens
|
||||
* );
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/blob/master/applications/slp/burn-tokens/burn-tokens.js
|
||||
*
|
||||
*/
|
||||
generateBurnOpReturn(tokenUtxos, burnQty) {
|
||||
try {
|
||||
const tokenId = tokenUtxos[0].tokenId
|
||||
const decimals = tokenUtxos[0].decimals
|
||||
|
||||
// Calculate the total amount of tokens owned by the wallet.
|
||||
let totalTokens = 0
|
||||
for (let i = 0; i < tokenUtxos.length; i++)
|
||||
totalTokens += tokenUtxos[i].tokenQty
|
||||
|
||||
const remainder = totalTokens - burnQty
|
||||
|
||||
let baseQty = new BigNumber(remainder).times(10 ** decimals)
|
||||
baseQty = baseQty.absoluteValue()
|
||||
baseQty = Math.floor(baseQty)
|
||||
baseQty = baseQty.toString()
|
||||
|
||||
// console.log(`baseQty: ${baseQty.toString()}`)
|
||||
|
||||
// Generate the OP_RETURN as a Buffer.
|
||||
const script = slpMdm.TokenType1.send(tokenId, [new slpMdm.BN(baseQty)])
|
||||
|
||||
return script
|
||||
} catch (err) {
|
||||
console.log(`Error in generateBurnOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.TokenType1.generateGenesisOpReturn() generateGenesisOpReturn()
|
||||
* @apiName generateGenesisOpReturn
|
||||
* @apiGroup SLP TokenType1
|
||||
* @apiDescription Generate the OP_RETURN value needed to create a new SLP token class.
|
||||
*
|
||||
* Expects a config object as input, see the example for properties.:
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const configObj = {
|
||||
* name: "SLP Test Token",
|
||||
* ticker: "SLPTEST",
|
||||
* documentUrl: "https://FullStack.cash",
|
||||
* documentHash: "",
|
||||
* decimals: 8,
|
||||
* initialQty: 10
|
||||
* }
|
||||
*
|
||||
* const result = await bchjs.SLP.TokenType1.generateGenesisOpReturn(
|
||||
* configObj
|
||||
* )
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/blob/master/applications/slp/create-token/create-token.js
|
||||
*
|
||||
*/
|
||||
generateGenesisOpReturn(configObj) {
|
||||
try {
|
||||
// TODO: Add input validation.
|
||||
|
||||
let baseQty = new BigNumber(configObj.initialQty).times(
|
||||
10 ** configObj.decimals
|
||||
)
|
||||
baseQty = baseQty.absoluteValue()
|
||||
baseQty = Math.floor(baseQty)
|
||||
baseQty = baseQty.toString()
|
||||
|
||||
// Prevent error if user fails to add the document hash.
|
||||
if (!configObj.documentHash) configObj.documentHash = ""
|
||||
|
||||
// If mint baton is not specified, then replace it with null.
|
||||
if (!configObj.mintBatonVout) configObj.mintBatonVout = null
|
||||
|
||||
const script = slpMdm.TokenType1.genesis(
|
||||
configObj.ticker,
|
||||
configObj.name,
|
||||
configObj.documentUrl,
|
||||
configObj.documentHash,
|
||||
configObj.decimals,
|
||||
configObj.mintBatonVout,
|
||||
new slpMdm.BN(baseQty)
|
||||
)
|
||||
|
||||
return script
|
||||
} catch (err) {
|
||||
console.log(`Error in generateGenesisOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Expects tokenUtxos to be an array of UTXOs. Must contain a UTXO with the
|
||||
// minting baton.
|
||||
// mintQty is the number of new coins to mint.
|
||||
// destroyBaton is an option Boolean. If true, will destroy the baton. By
|
||||
// default it is false and will pass the baton.
|
||||
/**
|
||||
* @api SLP.TokenType1.generateMintOpReturn() generateMintOpReturn()
|
||||
* @apiName generateMintOpReturn
|
||||
* @apiGroup SLP TokenType1
|
||||
* @apiDescription Generate the OP_RETURN value needed to create an SLP Mint transaction.
|
||||
* It's assumed all elements in the tokenUtxos array belong to the same token.
|
||||
*
|
||||
* Returns a Buffer representing a transaction output, ready to be added to
|
||||
* the Transaction Builder.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const addr = "bitcoincash:qq6xz6wwcy78uh79vgjvfyahj4arq269w5an8pcjak"
|
||||
* const utxos = await bchjs.Blockbook.utxos(addr)
|
||||
*
|
||||
* // Identify the SLP token UTXOs.
|
||||
* let tokenUtxos = await bchjs.SLP.Utils.tokenUtxoDetails(utxos);
|
||||
*
|
||||
* // Filter out the minting baton.
|
||||
* tokenUtxos = tokenUtxos.filter((utxo, index) => {
|
||||
* if (
|
||||
* utxo && // UTXO is associated with a token.
|
||||
* utxo.tokenId === TOKENID && // UTXO matches the token ID.
|
||||
* utxo.utxoType === "minting-baton" // UTXO is not a minting baton.
|
||||
* )
|
||||
* return true;
|
||||
* });
|
||||
*
|
||||
* // Generate the SLP OP_RETURN
|
||||
* const slpData = bchjs.SLP.TokenType1.generateMintOpReturn(
|
||||
* tokenUtxos,
|
||||
* 100 // Mint 100 new tokens.
|
||||
* );
|
||||
*
|
||||
* ...
|
||||
* // Add OP_RETURN as first output.
|
||||
* transactionBuilder.addOutput(slpData, 0);
|
||||
*
|
||||
* // See additional code here:
|
||||
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/blob/master/applications/slp/mint-token/mint-token.js
|
||||
*/
|
||||
generateMintOpReturn(tokenUtxos, mintQty, destroyBaton = false) {
|
||||
try {
|
||||
// Throw error if input is not an array.
|
||||
if (!Array.isArray(tokenUtxos))
|
||||
throw new Error(`tokenUtxos must be an array.`)
|
||||
|
||||
// Loop through the tokenUtxos array and find the minting baton.
|
||||
let mintBatonUtxo
|
||||
for (let i = 0; i < tokenUtxos.length; i++) {
|
||||
if (tokenUtxos[i].utxoType === "minting-baton")
|
||||
mintBatonUtxo = tokenUtxos[i]
|
||||
}
|
||||
|
||||
// Throw an error if the minting baton could not be found.
|
||||
if (!mintBatonUtxo)
|
||||
throw new Error(`Minting baton could not be found in tokenUtxos array.`)
|
||||
|
||||
const tokenId = mintBatonUtxo.tokenId
|
||||
const decimals = mintBatonUtxo.decimals
|
||||
|
||||
if (!tokenId)
|
||||
throw new Error(`tokenId property not found in mint-baton UTXO.`)
|
||||
if (!decimals)
|
||||
throw new Error(`decimals property not found in mint-baton UTXO.`)
|
||||
|
||||
let baseQty = new BigNumber(mintQty).times(10 ** decimals)
|
||||
baseQty = baseQty.absoluteValue()
|
||||
baseQty = Math.floor(baseQty)
|
||||
baseQty = baseQty.toString()
|
||||
|
||||
// Signal that the baton should be passed or detroyed.
|
||||
let batonVout = 2
|
||||
if (destroyBaton) batonVout = null
|
||||
|
||||
const script = slpMdm.TokenType1.mint(
|
||||
tokenId,
|
||||
batonVout,
|
||||
new slpMdm.BN(baseQty)
|
||||
)
|
||||
|
||||
return script
|
||||
} catch (err) {
|
||||
// console.log(`Error in generateMintOpReturn()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api SLP.TokenType1.getHexOpReturn() getHexOpReturn()
|
||||
* @apiName getHexOpReturn
|
||||
* @apiGroup SLP TokenType1
|
||||
* @apiDescription Get hex representation of an SLP OP_RETURN
|
||||
* This command returns a hex encoded OP_RETURN for SLP Send (Token Type 1)
|
||||
* transactions. Rather than computing it directly, it calls bch-api to do
|
||||
* the heavy lifting. This is easier and lighter weight for web apps.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
*
|
||||
* const tokenUtxos = [{
|
||||
* tokenId: "0a321bff9761f28e06a268b14711274bb77617410a16807bd0437ef234a072b1",
|
||||
* decimals: 0,
|
||||
* tokenQty: 2
|
||||
* }]
|
||||
*
|
||||
* const sendQty = 1.5
|
||||
*
|
||||
* const result = await bchjs.SLP.TokenType1.getHexOpReturn(tokenUtxos, sendQty)
|
||||
*
|
||||
* // result:
|
||||
* {
|
||||
* "script": "6a04534c500001010453454e44200a321bff9761f28e06a268b14711274bb77617410a16807bd0437ef234a072b1080000000000000001080000000000000000",
|
||||
* "outputs": 2
|
||||
* }
|
||||
*/
|
||||
async getHexOpReturn(tokenUtxos, sendQty) {
|
||||
try {
|
||||
// TODO: Add input filtering.
|
||||
|
||||
const data = {
|
||||
tokenUtxos,
|
||||
sendQty
|
||||
}
|
||||
|
||||
const result = await _this.axios.post(
|
||||
`${this.restURL}slp/generatesendopreturn`,
|
||||
data,
|
||||
_this.axiosOptions
|
||||
)
|
||||
|
||||
const slpSendObj = result.data
|
||||
|
||||
// const script = _this.Buffer.from(slpSendObj.script)
|
||||
//
|
||||
// slpSendObj.script = script
|
||||
// return slpSendObj
|
||||
|
||||
return slpSendObj
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TokenType1
|
||||
+1106
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
const io = require("socket.io-client")
|
||||
|
||||
class Socket {
|
||||
constructor(config = {}) {
|
||||
if (typeof config === "string") {
|
||||
// TODO remove this check in v2.0
|
||||
this.socket = io(`${config}`)
|
||||
} else {
|
||||
if (config.restURL) {
|
||||
this.socket = io(`${config.restURL}`)
|
||||
} else {
|
||||
const restURL = "https://rest.bitcoin.com"
|
||||
this.socket = io(`${restURL}`)
|
||||
}
|
||||
|
||||
if (config.callback) config.callback()
|
||||
}
|
||||
}
|
||||
|
||||
listen(endpoint, cb) {
|
||||
this.socket.emit(endpoint)
|
||||
|
||||
if (endpoint === "blocks") this.socket.on("blocks", msg => cb(msg))
|
||||
else if (endpoint === "transactions")
|
||||
this.socket.on("transactions", msg => cb(msg))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Socket
|
||||
@@ -0,0 +1,164 @@
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
const coininfo = require("coininfo")
|
||||
const bip66 = require("bip66")
|
||||
const bip68 = require("bc-bip68")
|
||||
|
||||
class TransactionBuilder {
|
||||
static setAddress(address) {
|
||||
TransactionBuilder._address = address
|
||||
}
|
||||
|
||||
constructor(network = "mainnet") {
|
||||
let bitcoincash
|
||||
if (network === "bitcoincash" || network === "mainnet")
|
||||
bitcoincash = coininfo.bitcoincash.main
|
||||
else bitcoincash = coininfo.bitcoincash.test
|
||||
|
||||
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
|
||||
this.transaction = new Bitcoin.TransactionBuilder(bitcoincashBitcoinJSLib)
|
||||
this.DEFAULT_SEQUENCE = 0xffffffff
|
||||
this.hashTypes = {
|
||||
SIGHASH_ALL: 0x01,
|
||||
SIGHASH_NONE: 0x02,
|
||||
SIGHASH_SINGLE: 0x03,
|
||||
SIGHASH_ANYONECANPAY: 0x80,
|
||||
SIGHASH_BITCOINCASH_BIP143: 0x40,
|
||||
ADVANCED_TRANSACTION_MARKER: 0x00,
|
||||
ADVANCED_TRANSACTION_FLAG: 0x01
|
||||
}
|
||||
this.signatureAlgorithms = {
|
||||
ECDSA: Bitcoin.ECSignature.ECDSA,
|
||||
SCHNORR: Bitcoin.ECSignature.SCHNORR
|
||||
}
|
||||
this.bip66 = bip66
|
||||
this.bip68 = bip68
|
||||
this.p2shInput = false
|
||||
this.tx
|
||||
}
|
||||
|
||||
/**
|
||||
* @api Transaction-Builder.addInput() addInput() - Add input to transaction.
|
||||
* @apiName AddInput
|
||||
* @apiGroup TransactionBuilder
|
||||
* @apiDescription Add input to transaction.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // txid of vout
|
||||
* let txid = 'f7890915febe580920df2681d2bac0909ae89bd0cc1d3ed763e5eeba7f337f0e';
|
||||
* // add input with txid and index of vout
|
||||
* transactionBuilder.addInput(txid, 0);
|
||||
*/
|
||||
addInput(txHash, vout, sequence = this.DEFAULT_SEQUENCE, prevOutScript) {
|
||||
this.transaction.addInput(txHash, vout, sequence, prevOutScript)
|
||||
}
|
||||
|
||||
addInputScript(vout, script) {
|
||||
this.tx = this.transaction.buildIncomplete()
|
||||
this.tx.setInputScript(vout, script)
|
||||
this.p2shInput = true
|
||||
}
|
||||
|
||||
addInputScripts(scripts) {
|
||||
this.tx = this.transaction.buildIncomplete()
|
||||
scripts.forEach(script => {
|
||||
this.tx.setInputScript(script.vout, script.script)
|
||||
})
|
||||
this.p2shInput = true
|
||||
}
|
||||
/**
|
||||
* @api Transaction-Builder.addOutput() addOutput() - Add output to transaction.
|
||||
* @apiName AddOutput
|
||||
* @apiGroup TransactionBuilder
|
||||
* @apiDescription Add output to transaction.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let originalAmount = 100000;
|
||||
* let byteCount = bchjs.BitcoinCash.getByteCount({ P2PKH: 1 }, { P2PKH: 1 });
|
||||
* // amount to send to receiver. It's the original amount - 1 sat/byte for tx size
|
||||
* let sendAmount = originalAmount - byteCount;
|
||||
* // add output w/ address and amount to send
|
||||
* transactionBuilder.addOutput('bitcoincash:qpuax2tarq33f86wccwlx8ge7tad2wgvqgjqlwshpw', sendAmount);
|
||||
*/
|
||||
addOutput(scriptPubKey, amount) {
|
||||
try {
|
||||
this.transaction.addOutput(
|
||||
TransactionBuilder._address.toLegacyAddress(scriptPubKey),
|
||||
amount
|
||||
)
|
||||
} catch (error) {
|
||||
this.transaction.addOutput(scriptPubKey, amount)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @api Transaction-Builder.setLockTime() setLockTime() - Set locktime.
|
||||
* @apiName SetLockTime
|
||||
* @apiGroup TransactionBuilder
|
||||
* @apiDescription Set locktime.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let originalAmount = 100000;
|
||||
* let byteCount = bchjs.BitcoinCash.getByteCount({ P2PKH: 1 }, { P2PKH: 1 });
|
||||
* // amount to send to receiver. It's the original amount - 1 sat/byte for tx size
|
||||
* let sendAmount = originalAmount - byteCount;
|
||||
* // add output w/ address and amount to send
|
||||
* transactionBuilder.addOutput('bitcoincash:qpuax2tarq33f86wccwlx8ge7tad2wgvqgjqlwshpw', sendAmount);
|
||||
* transactionBuilder.setLockTime(50000)
|
||||
*/
|
||||
setLockTime(locktime) {
|
||||
this.transaction.setLockTime(locktime)
|
||||
}
|
||||
/**
|
||||
* @api Transaction-Builder.sign() sign() - Sign transaction..
|
||||
* @apiName Sign.
|
||||
* @apiGroup TransactionBuilder
|
||||
* @apiDescription Sign transaction. It creates the unlocking script needed to spend an input. Each input has its own script and thus 'sign' must be called for each input even if the keyPair is the same..
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* let originalAmount = 100000;
|
||||
* // node of address which is going to spend utxo
|
||||
* let hdnode = bchjs.HDNode.fromXPriv("xprvA3eaDg64MwDr72PVGJ7CkvshNAzCDRz7rn98sYrZVAtDSWCAmNGQhEQeCLDcnmcpSkfjhHevXmu4ZL8ZcT9D4vEbG8LpiToZETrHZttw9Yw");
|
||||
* // keypair
|
||||
* let keyPair = bchjs.HDNode.toKeyPair(hdnode);
|
||||
* // empty redeemScript variable
|
||||
* let redeemScript;
|
||||
* // sign w/ keyPair
|
||||
* transactionBuilder.sign(0, keyPair, redeemScript, transactionBuilder.hashTypes.SIGHASH_ALL, originalAmount, transactionBuilder.signatureAlgorithms.SCHNORR);
|
||||
*/
|
||||
sign(
|
||||
vin,
|
||||
keyPair,
|
||||
redeemScript,
|
||||
hashType = this.hashTypes.SIGHASH_ALL,
|
||||
value,
|
||||
signatureAlgorithm
|
||||
) {
|
||||
let witnessScript
|
||||
|
||||
this.transaction.sign(
|
||||
vin,
|
||||
keyPair,
|
||||
redeemScript,
|
||||
hashType,
|
||||
value,
|
||||
witnessScript,
|
||||
signatureAlgorithm
|
||||
)
|
||||
}
|
||||
/**
|
||||
* @api Transaction-Builder.build() build() - Build transaction.
|
||||
* @apiName Build.
|
||||
* @apiGroup TransactionBuilder
|
||||
* @apiDescription Build transaction.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* // build tx
|
||||
* let tx = bchjs.transactionBuilder.build();
|
||||
*/
|
||||
build() {
|
||||
if (this.p2shInput === true) return this.tx
|
||||
|
||||
return this.transaction.build()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TransactionBuilder
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
const axios = require("axios")
|
||||
|
||||
let _this
|
||||
|
||||
class Util {
|
||||
constructor(config) {
|
||||
this.restURL = config.restURL
|
||||
this.apiToken = config.apiToken
|
||||
|
||||
// Add JWT token to the authorization header.
|
||||
this.axiosOptions = {
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
|
||||
_this = this
|
||||
}
|
||||
|
||||
/**
|
||||
* @api util.validateAddress() validateAddress() - Get information about the given bitcoin address.
|
||||
* @apiName Validate Address.
|
||||
* @apiGroup Util
|
||||
* @apiDescription Return information about the given bitcoin address.
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* (async () => {
|
||||
* try {
|
||||
* let validateAddress = await bchjs.Util.validateAddress("bitcoincash:qzc86hrdufhcwlyzk7k82x77kfs2myekn57nv9cw5f");
|
||||
* console.log(validateAddress);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // { isvalid: true,
|
||||
* // address: '17fshh33qUze2yifiJ2sXgijSMzJ2KNEwu',
|
||||
* // scriptPubKey: '76a914492ae280d70af33acf0ae7cd329b961e65e9cbd888ac',
|
||||
* // ismine: true,
|
||||
* // iswatchonly: false,
|
||||
* // isscript: false,
|
||||
* // pubkey: '0312eeb9ae5f14c3cf43cece11134af860c2ef7d775060e3a578ceec888acada31',
|
||||
* // iscompressed: true,
|
||||
* // account: 'Test' }
|
||||
*
|
||||
* (async () => {
|
||||
* try {
|
||||
* let validateAddress = await bchjs.Util.validateAddress(["bitcoincash:qzc86hrdufhcwlyzk7k82x77kfs2myekn57nv9cw5f"]);
|
||||
* console.log(validateAddress);
|
||||
* } catch(error) {
|
||||
* console.error(error)
|
||||
* }
|
||||
* })()
|
||||
*
|
||||
* // [{ isvalid: true,
|
||||
* // address: '17fshh33qUze2yifiJ2sXgijSMzJ2KNEwu',
|
||||
* // scriptPubKey: '76a914492ae280d70af33acf0ae7cd329b961e65e9cbd888ac',
|
||||
* // ismine: true,
|
||||
* // iswatchonly: false,
|
||||
* // isscript: false,
|
||||
* // pubkey: '0312eeb9ae5f14c3cf43cece11134af860c2ef7d775060e3a578ceec888acada31',
|
||||
* // iscompressed: true,
|
||||
* // account: 'Test' }]
|
||||
*/
|
||||
async validateAddress(address) {
|
||||
try {
|
||||
// Single block
|
||||
if (typeof address === "string") {
|
||||
const response = await axios.get(
|
||||
`${this.restURL}util/validateAddress/${address}`,
|
||||
_this.axiosOptions
|
||||
)
|
||||
return response.data
|
||||
|
||||
// Array of blocks.
|
||||
} else if (Array.isArray(address)) {
|
||||
const options = {
|
||||
method: "POST",
|
||||
url: `${this.restURL}util/validateAddress`,
|
||||
data: {
|
||||
addresses: address
|
||||
},
|
||||
headers: {
|
||||
authorization: `Token ${this.apiToken}`
|
||||
}
|
||||
}
|
||||
const response = await axios(options)
|
||||
|
||||
return response.data
|
||||
}
|
||||
|
||||
throw new Error(`Input must be a string or array of strings.`)
|
||||
} catch (error) {
|
||||
if (error.response && error.response.data) throw error.response.data
|
||||
else throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Util
|
||||
@@ -0,0 +1,77 @@
|
||||
// import BCHWalletBridge from "bch-wallet-bridge.js"
|
||||
class Wallet {
|
||||
constructor(walletProvider) {
|
||||
// this.bchWalletBridge = new BCHWalletBridge(walletProvider)
|
||||
}
|
||||
|
||||
setWalletProvider(walletProvider) {
|
||||
this.bchWalletBridge.walletProvider = walletProvider
|
||||
}
|
||||
|
||||
getAddress(changeType, index, dAppId) {
|
||||
return this.bchWalletBridge.getAddress(changeType, index, dAppId)
|
||||
}
|
||||
|
||||
getAddressIndex(changeType, dAppId) {
|
||||
return this.bchWalletBridge.getAddressIndex(changeType, dAppId)
|
||||
}
|
||||
|
||||
getAddresses(changeType, startIndex, size, dAppId) {
|
||||
return this.bchWalletBridge.getAddresses(
|
||||
changeType,
|
||||
startIndex,
|
||||
size,
|
||||
dAppId
|
||||
)
|
||||
}
|
||||
|
||||
getRedeemScript(p2shAddress, dAppId) {
|
||||
return this.bchWalletBridge.getRedeemScript(p2shAddress, dAppId)
|
||||
}
|
||||
|
||||
getRedeemScripts(dAppId) {
|
||||
return this.bchWalletBridge.getRedeemScripts(dAppId)
|
||||
}
|
||||
|
||||
addRedeemScript(redeemScript, dAppId) {
|
||||
return this.bchWalletBridge.addRedeemScript(redeemScript, dAppId)
|
||||
}
|
||||
|
||||
getUtxos(dAppId) {
|
||||
return this.bchWalletBridge.getUtxos(dAppId)
|
||||
}
|
||||
|
||||
getBalance(dAppId) {
|
||||
return this.bchWalletBridge.getBalance(dAppId)
|
||||
}
|
||||
|
||||
sign(address, dataToSign) {
|
||||
return this.bchWalletBridge.sign(address, dataToSign)
|
||||
}
|
||||
|
||||
buildTransaction(outputs, dAppId) {
|
||||
return this.bchWalletBridge.buildTransaction(outputs, dAppId)
|
||||
}
|
||||
|
||||
getProtocolVersion() {
|
||||
return this.bchWalletBridge.getProtocolVersion()
|
||||
}
|
||||
|
||||
getNetwork() {
|
||||
return this.bchWalletBridge.getNetwork()
|
||||
}
|
||||
|
||||
getFeePerByte() {
|
||||
return this.bchWalletBridge.getFeePerByte()
|
||||
}
|
||||
|
||||
getDefaultDAppId() {
|
||||
return this.bchWalletBridge.getDefaultDAppId()
|
||||
}
|
||||
|
||||
setDefaultDAppId(dAppId) {
|
||||
return this.bchWalletBridge.setDefaultDAppId(dAppId)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Wallet
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
A Mocha test file for running end-to-end (e2e) tests.
|
||||
*/
|
||||
|
||||
//const mocha = require("mocha")
|
||||
const assert = require("chai").assert
|
||||
|
||||
const sendToken = require("./send-token/send-token")
|
||||
|
||||
describe("#end-to-end tests", () => {
|
||||
describe("#send-tokens", () => {
|
||||
it("SLPDB should update balances in less than 10 seconds", async () => {
|
||||
const result = await sendToken.sendTokenTest()
|
||||
|
||||
assert(result, true, "True expected if test passed successfully.")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
An end-to-end test for testing the functionality of uploading a file to
|
||||
IPFS is working.
|
||||
*/
|
||||
|
||||
process.env.IPFS_API = `http://localhost:5001`
|
||||
// process.env.IPFS_API = `https://ipfs-api.fullstack.cash`
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
describe(`#IPFS`, () => {
|
||||
it("should upload a file to the server", async () => {
|
||||
const path = `${__dirname}/ipfs-e2e.js`
|
||||
|
||||
const fileModel = await bchjs.IPFS.createFileModel(path)
|
||||
console.log(`fileModel: ${JSON.stringify(fileModel, null, 2)}`)
|
||||
|
||||
const fileId = fileModel.file._id
|
||||
|
||||
const fileObj = await bchjs.IPFS.uploadFile(path, fileId)
|
||||
console.log(`fileObj: ${JSON.stringify(fileObj, null, 2)}`)
|
||||
}).timeout(30000)
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
Mocha test that verifies that the bch-api server is enforcing its
|
||||
anonymous access rules
|
||||
|
||||
To Run Test:
|
||||
- Update the RESTURL for bch-api you want to test against.
|
||||
*/
|
||||
|
||||
const assert = require("chai").assert
|
||||
|
||||
const RESTURL = `https://api.fullstack.cash/v3/`
|
||||
// const RESTURL = `http://localhost:3000/v3/`
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS({ restURL: RESTURL })
|
||||
|
||||
describe("#anonymous rate limits", () => {
|
||||
it("should allow an anonymous call to a full node endpoint", async () => {
|
||||
const result = await bchjs.Control.getNetworkInfo()
|
||||
|
||||
assert.property(result, "version")
|
||||
}).timeout(5000)
|
||||
|
||||
it("should allow an anonymous call to an indexer", async () => {
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "balance")
|
||||
}).timeout(5000)
|
||||
|
||||
it("should throw error when rate limit exceeded", async () => {
|
||||
try {
|
||||
for (let i = 0; i < 5; i++) await bchjs.Control.getNetworkInfo()
|
||||
|
||||
assert.equal(true, false, "unexpected result")
|
||||
} catch (err) {
|
||||
assert.include(err.error, "Too many requests")
|
||||
}
|
||||
}).timeout(5000)
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
Mocha test that verifies that the bch-api server is enforcing its
|
||||
FREE access rules
|
||||
|
||||
To Run Test:
|
||||
- Update the restURL for bch-api you want to test against.
|
||||
- Update the JWT_TOKEN value with a current free-level JWT token.
|
||||
*/
|
||||
|
||||
const assert = require("chai").assert
|
||||
|
||||
const JWT_TOKEN =
|
||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2YyMDIyMWMxMDAxMmFkOTQwMSIsImVtYWlsIjoiZGVtb0BkZW1vLmNvbSIsImFwaUxldmVsIjoxMCwicmF0ZUxpbWl0IjozLCJpYXQiOjE1OTA1Mjk2NzgsImV4cCI6MTU5MzEyMTY3OH0.4q5MFDCcVx0FusivJPiEIj3w8nhFG7ZV5IhJS7faUlc"
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS({
|
||||
restURL: `https://api.fullstack.cash/v3/`,
|
||||
// restURL: `http://localhost:3000/v3/`,
|
||||
apiToken: JWT_TOKEN
|
||||
})
|
||||
|
||||
describe("#free rate limits", () => {
|
||||
it("should allow an free call to an indexer", async () => {
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "balance")
|
||||
}).timeout(5000)
|
||||
|
||||
// it("should throw error when rate limit exceeded 3 RPM for indexer endpoints", async () => {
|
||||
// const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
//
|
||||
// try {
|
||||
// for (let i = 0; i < 5; i++) await bchjs.Blockbook.balance(addr)
|
||||
//
|
||||
// assert.equal(true, false, "unexpected result")
|
||||
// } catch (err) {
|
||||
// // console.log(`err: `, err)
|
||||
// assert.include(err.error, "Too many requests")
|
||||
// }
|
||||
// }).timeout(10000)
|
||||
|
||||
it("should allow up to 10 RPM to indexer, then throw error", async () => {
|
||||
try {
|
||||
const addr = "bitcoincash:qrehqueqhw629p6e57994436w730t4rzasnly00ht0"
|
||||
|
||||
for (let i = 0; i < 15; i++) {
|
||||
const result = await await bchjs.Blockbook.balance(addr)
|
||||
|
||||
if (i === 5) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "address", "more than 3 calls allowed")
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.error,
|
||||
"currently 10 requests",
|
||||
"more than 10 not allowed"
|
||||
)
|
||||
assert.include(err.error, 10)
|
||||
assert.notInclude(err.error, 3)
|
||||
}
|
||||
}).timeout(20000)
|
||||
|
||||
it("should allow up to 10 RPM to full node, then throw error", async () => {
|
||||
try {
|
||||
for (let i = 0; i < 15; i++) {
|
||||
const result = await bchjs.Control.getNetworkInfo()
|
||||
|
||||
if (i === 5) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "version", "more than 3 calls allowed")
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// console.log(`validating after 10th call`)
|
||||
// console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.error,
|
||||
"currently 10 requests",
|
||||
"more than 10 not allowed"
|
||||
)
|
||||
assert.include(err.error, 10)
|
||||
assert.notInclude(err.error, 3)
|
||||
}
|
||||
}).timeout(20000)
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
Mocha test that verifies that the bch-api server is enforcing its
|
||||
full-node access rules
|
||||
|
||||
To Run Test:
|
||||
- Update the restURL for bch-api you want to test against.
|
||||
- Update the JWT_TOKEN value with a current full-node-level JWT token.
|
||||
*/
|
||||
|
||||
const assert = require("chai").assert
|
||||
|
||||
const JWT_TOKEN =
|
||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkYmY4MjA1YTYwODliMjliYTlhZjc1OSIsImlhdCI6MTU3MjgzMTgzOSwiZXhwIjoxNTc1NDIzODM5fQ.sFFS4AF04U2aUwmKkBIfnMQIUoygzV9UMVzzQuwctpY"
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS({
|
||||
restURL: `https://api.bchjs.cash/v3/`,
|
||||
// restURL: `http://localhost:3000/v3/`,
|
||||
apiToken: JWT_TOKEN
|
||||
})
|
||||
|
||||
describe("#full node rate limits", () => {
|
||||
it("should allow an free call to an indexer", async () => {
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "balance")
|
||||
}).timeout(5000)
|
||||
|
||||
it("should throw error when rate limit exceeded 3 RPM for indexer endpoints", async () => {
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
|
||||
try {
|
||||
for (let i = 0; i < 5; i++) await bchjs.Blockbook.balance(addr)
|
||||
|
||||
assert.equal(true, false, "unexpected result")
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(err.error, "Too many requests")
|
||||
}
|
||||
}).timeout(10000)
|
||||
|
||||
it("should allow more than 10 RPM to full node", async () => {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const result = await bchjs.Control.getNetworkInfo()
|
||||
|
||||
if (i === 5) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "version", "more than 3 calls allowed")
|
||||
}
|
||||
|
||||
if (i === 15) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "version", "more than 10 calls allowed")
|
||||
}
|
||||
}
|
||||
}).timeout(10000)
|
||||
|
||||
it("should throw error for more than 100 RPM to fullnode", async () => {
|
||||
try {
|
||||
for (let i = 0; i < 100; i++) await bchjs.Control.getNetworkInfo()
|
||||
} catch (err) {
|
||||
// console.log(`validating after 10th call`)
|
||||
// console.log(`err: `, err)
|
||||
assert.include(err.error, "Too many requests")
|
||||
assert.include(err.error, 100)
|
||||
}
|
||||
}).timeout(30000)
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Mocha test that verifies that the bch-api server is enforcing its
|
||||
indexer access rules
|
||||
|
||||
To Run Test:
|
||||
- Update the restURL for bch-api you want to test against.
|
||||
- Update the JWT_TOKEN value with a current indexer-level JWT token.
|
||||
*/
|
||||
|
||||
const assert = require("chai").assert
|
||||
|
||||
const JWT_TOKEN =
|
||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTU5MDQzMjIxNywiZXhwIjoxNTkzMDI0MjE3fQ.R0Euhutd5FHCxLlSzjq1TYsGjI6iua_AguWIeLK2xCU"
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS({
|
||||
restURL: `https://api.fullstack.cash/v3/`,
|
||||
// restURL: `http://localhost:3000/v3/`,
|
||||
apiToken: JWT_TOKEN
|
||||
})
|
||||
|
||||
describe("#full node rate limits", () => {
|
||||
it("should allow more than 10 RPM to full node", async () => {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const result = await bchjs.Control.getNetworkInfo()
|
||||
|
||||
if (i === 5) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "version", "more than 3 calls allowed")
|
||||
}
|
||||
|
||||
if (i === 15) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "version", "more than 10 calls allowed")
|
||||
}
|
||||
}
|
||||
}).timeout(30000)
|
||||
|
||||
it("should allow more than 10 RPM to an indexer", async () => {
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
|
||||
if (i === 5) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "balance", "more than 3 calls allowed")
|
||||
}
|
||||
|
||||
if (i === 15) {
|
||||
// console.log(`validating 5th call: ${i}`)
|
||||
assert.property(result, "balance", "more than 10 calls allowed")
|
||||
}
|
||||
}
|
||||
}).timeout(30000)
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "sendrawtransaction",
|
||||
"version": "1.0.0",
|
||||
"description": "e2e test - Send two transactions in parallel.",
|
||||
"main": "sendrawtransaction.js",
|
||||
"scripts": {
|
||||
"test": "echo no tests yet",
|
||||
"start": "node sendrawtransaction.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Bitcoin-com/bitbox-javascript-sdk.git"
|
||||
},
|
||||
"keywords": [
|
||||
"bitbox",
|
||||
"bch",
|
||||
"bitcoin",
|
||||
"bitcoin cash",
|
||||
"bitcoin.com",
|
||||
"javascript"
|
||||
],
|
||||
"author": "Chris Troutner <chris.troutner@gmail.com>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Bitcoin-com/bitbox-javascript-sdk/issues"
|
||||
},
|
||||
"homepage": "https://github.com/Bitcoin-com/bitbox-javascript-sdk/blob/master/README.md"
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
This is an end-to-end test adapted from the send-bch example. It's purpose
|
||||
is to test the sendRawTransaction endpoint. Since the single call is tested
|
||||
all the time, this test focuses on testing the bulk endpoint by sending
|
||||
two transactions at once.
|
||||
|
||||
Instructions:
|
||||
- Ensure the address in the wallet.json file has some tBCH.
|
||||
- Ensure the address in the wallet.json file has two UTXOs between 0.1 and
|
||||
0.001 tBCH
|
||||
- This test will generate two transactions from two UTXOs and broadcast them
|
||||
using the sendrawtransaction bulk endpoint.
|
||||
*/
|
||||
|
||||
// Replace the address below with the address you want to send the BCH to.
|
||||
const RECV_ADDR1 = `bchtest:qzfn2mly05t6fjsh5kjj0dqq0jjtct27ng089dgg05`
|
||||
const RECV_ADDR2 = `bchtest:qz6yw0kqgfkknfy6jh2jvlfnkzmre3lt2u0pgcckdk`
|
||||
const SATOSHIS_TO_SEND = 1000
|
||||
|
||||
// Instantiate BITBOX.
|
||||
const bitboxLib = "../../../lib/BITBOX"
|
||||
const BITBOXSDK = require(bitboxLib)
|
||||
const BITBOX = new BITBOXSDK({ restURL: "https://trest.bitcoin.com/v2/" })
|
||||
//const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
|
||||
|
||||
const util = require("util")
|
||||
|
||||
// Open the wallet generated with create-wallet.
|
||||
try {
|
||||
var walletInfo = require(`./wallet.json`)
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Could not open wallet.json. Generate a wallet with create-wallet first.`
|
||||
)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const SEND_ADDR = walletInfo.cashAddress
|
||||
const SEND_MNEMONIC = walletInfo.mnemonic
|
||||
|
||||
async function testSend() {
|
||||
try {
|
||||
const hex1 = await buildTx1(RECV_ADDR1)
|
||||
const hex2 = await buildTx2(RECV_ADDR2)
|
||||
|
||||
console.log(`hex1: ${hex1}\n\n`)
|
||||
console.log(`hex2: ${hex2}\n\n`)
|
||||
|
||||
const broadcast = await BITBOX.RawTransactions.sendRawTransaction([
|
||||
hex1,
|
||||
hex2
|
||||
])
|
||||
console.log(`Transaction IDs: ${JSON.stringify(broadcast, null, 2)}`)
|
||||
console.log(`Should return an array of TXID strings.`)
|
||||
} catch (err) {
|
||||
console.log(`Error in testSend: `, err)
|
||||
}
|
||||
}
|
||||
testSend()
|
||||
|
||||
// Build a TX hex with the largest UTXO.
|
||||
async function buildTx1(recAddr) {
|
||||
try {
|
||||
// Get the balance of the sending address.
|
||||
const balance = await getBCHBalance(SEND_ADDR, false)
|
||||
console.log(`balance: ${JSON.stringify(balance, null, 2)}`)
|
||||
console.log(`Balance of sending address ${SEND_ADDR} is ${balance} BCH.`)
|
||||
|
||||
// Exit if the balance is zero.
|
||||
if (balance <= 0.0) {
|
||||
console.log(`Balance of sending address is zero. Exiting.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const SEND_ADDR_LEGACY = BITBOX.Address.toLegacyAddress(SEND_ADDR)
|
||||
const RECV_ADDR_LEGACY = BITBOX.Address.toLegacyAddress(recAddr)
|
||||
console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`)
|
||||
console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`)
|
||||
|
||||
const balance2 = await getBCHBalance(recAddr, false)
|
||||
//console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`)
|
||||
|
||||
const u = await BITBOX.Address.utxo(SEND_ADDR)
|
||||
//console.log(`u: ${JSON.stringify(u, null, 2)}`)
|
||||
const utxo = findBiggestUtxo(u.utxos)
|
||||
console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
|
||||
|
||||
// instance of transaction builder
|
||||
const transactionBuilder = new BITBOX.TransactionBuilder("testnet")
|
||||
|
||||
const satoshisToSend = SATOSHIS_TO_SEND
|
||||
const originalAmount = utxo.satoshis
|
||||
const vout = utxo.vout
|
||||
const txid = utxo.txid
|
||||
|
||||
// add input with txid and index of vout
|
||||
transactionBuilder.addInput(txid, vout)
|
||||
|
||||
// get byte count to calculate fee. paying 1.2 sat/byte
|
||||
const byteCount = BITBOX.BitcoinCash.getByteCount(
|
||||
{ P2PKH: 1 },
|
||||
{ P2PKH: 2 }
|
||||
)
|
||||
console.log(`byteCount: ${byteCount}`)
|
||||
const satoshisPerByte = 1.0
|
||||
const txFee = Math.floor(satoshisPerByte * byteCount)
|
||||
console.log(`txFee: ${txFee}`)
|
||||
|
||||
// amount to send back to the sending address.
|
||||
// It's the original amount - 1 sat/byte for tx size
|
||||
const remainder = originalAmount - satoshisToSend - txFee
|
||||
|
||||
// add output w/ address and amount to send
|
||||
transactionBuilder.addOutput(recAddr, satoshisToSend)
|
||||
transactionBuilder.addOutput(SEND_ADDR, remainder)
|
||||
|
||||
// Generate a change address from a Mnemonic of a private key.
|
||||
const change = changeAddrFromMnemonic(SEND_MNEMONIC)
|
||||
|
||||
// Generate a keypair from the change address.
|
||||
const keyPair = BITBOX.HDNode.toKeyPair(change)
|
||||
|
||||
// Sign the transaction with the HD node.
|
||||
let redeemScript
|
||||
transactionBuilder.sign(
|
||||
0,
|
||||
keyPair,
|
||||
redeemScript,
|
||||
transactionBuilder.hashTypes.SIGHASH_ALL,
|
||||
originalAmount
|
||||
)
|
||||
|
||||
// build tx
|
||||
const tx = transactionBuilder.build()
|
||||
// output rawhex
|
||||
const hex = tx.toHex()
|
||||
|
||||
return hex
|
||||
} catch (err) {
|
||||
console.log(`Error in buildTx().`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Build a TX hex with the SECOND largest UTXO.
|
||||
async function buildTx2(recAddr) {
|
||||
try {
|
||||
// Get the balance of the sending address.
|
||||
const balance = await getBCHBalance(SEND_ADDR, false)
|
||||
console.log(`balance: ${JSON.stringify(balance, null, 2)}`)
|
||||
console.log(`Balance of sending address ${SEND_ADDR} is ${balance} BCH.`)
|
||||
|
||||
// Exit if the balance is zero.
|
||||
if (balance <= 0.0) {
|
||||
console.log(`Balance of sending address is zero. Exiting.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const SEND_ADDR_LEGACY = BITBOX.Address.toLegacyAddress(SEND_ADDR)
|
||||
const RECV_ADDR_LEGACY = BITBOX.Address.toLegacyAddress(recAddr)
|
||||
console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`)
|
||||
console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`)
|
||||
|
||||
const balance2 = await getBCHBalance(recAddr, false)
|
||||
//console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`)
|
||||
|
||||
const u = await BITBOX.Address.utxo(SEND_ADDR)
|
||||
//console.log(`u: ${JSON.stringify(u, null, 2)}`)
|
||||
const utxo = findNextBiggestUtxo(u.utxos)
|
||||
console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
|
||||
|
||||
// instance of transaction builder
|
||||
const transactionBuilder = new BITBOX.TransactionBuilder("testnet")
|
||||
|
||||
const satoshisToSend = SATOSHIS_TO_SEND
|
||||
const originalAmount = utxo.satoshis
|
||||
const vout = utxo.vout
|
||||
const txid = utxo.txid
|
||||
|
||||
// add input with txid and index of vout
|
||||
transactionBuilder.addInput(txid, vout)
|
||||
|
||||
// get byte count to calculate fee. paying 1.2 sat/byte
|
||||
const byteCount = BITBOX.BitcoinCash.getByteCount(
|
||||
{ P2PKH: 1 },
|
||||
{ P2PKH: 2 }
|
||||
)
|
||||
console.log(`byteCount: ${byteCount}`)
|
||||
const satoshisPerByte = 1.0
|
||||
const txFee = Math.floor(satoshisPerByte * byteCount)
|
||||
console.log(`txFee: ${txFee}`)
|
||||
|
||||
// amount to send back to the sending address.
|
||||
// It's the original amount - 1 sat/byte for tx size
|
||||
const remainder = originalAmount - satoshisToSend - txFee
|
||||
|
||||
// add output w/ address and amount to send
|
||||
transactionBuilder.addOutput(recAddr, satoshisToSend)
|
||||
transactionBuilder.addOutput(SEND_ADDR, remainder)
|
||||
|
||||
// Generate a change address from a Mnemonic of a private key.
|
||||
const change = changeAddrFromMnemonic(SEND_MNEMONIC)
|
||||
|
||||
// Generate a keypair from the change address.
|
||||
const keyPair = BITBOX.HDNode.toKeyPair(change)
|
||||
|
||||
// Sign the transaction with the HD node.
|
||||
let redeemScript
|
||||
transactionBuilder.sign(
|
||||
0,
|
||||
keyPair,
|
||||
redeemScript,
|
||||
transactionBuilder.hashTypes.SIGHASH_ALL,
|
||||
originalAmount
|
||||
)
|
||||
|
||||
// build tx
|
||||
const tx = transactionBuilder.build()
|
||||
// output rawhex
|
||||
const hex = tx.toHex()
|
||||
|
||||
return hex
|
||||
} catch (err) {
|
||||
console.log(`Error in buildTx().`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a change address from a Mnemonic of a private key.
|
||||
function changeAddrFromMnemonic(mnemonic) {
|
||||
// root seed buffer
|
||||
const rootSeed = BITBOX.Mnemonic.toSeed(mnemonic)
|
||||
|
||||
// master HDNode
|
||||
const masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, "testnet")
|
||||
|
||||
// HDNode of BIP44 account
|
||||
const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
|
||||
|
||||
// derive the first external change address HDNode which is going to spend utxo
|
||||
const change = BITBOX.HDNode.derivePath(account, "0/0")
|
||||
|
||||
return change
|
||||
}
|
||||
|
||||
// Get the balance in BCH of a BCH address.
|
||||
async function getBCHBalance(addr, verbose) {
|
||||
try {
|
||||
const result = await BITBOX.Address.details(addr)
|
||||
|
||||
if (verbose) console.log(result)
|
||||
|
||||
const bchBalance = result
|
||||
|
||||
return bchBalance.balance
|
||||
} catch (err) {
|
||||
console.error(`Error in getBCHBalance: `, err)
|
||||
console.log(`addr: ${addr}`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the utxo with the biggest balance from an array of utxos.
|
||||
function findBiggestUtxo(utxos) {
|
||||
// Sort the utxos by the amount of satoshis, largest first.
|
||||
utxos.sort(function(a, b) {
|
||||
return b.satoshis - a.satoshis
|
||||
})
|
||||
|
||||
return utxos[0]
|
||||
}
|
||||
|
||||
// Returns the utxo with the 2nd biggest balance from an array of utxos.
|
||||
function findNextBiggestUtxo(utxos) {
|
||||
// Sort the utxos by the amount of satoshis, largest first.
|
||||
utxos.sort(function(a, b) {
|
||||
return b.satoshis - a.satoshis
|
||||
})
|
||||
|
||||
return utxos[1]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "sendrawtransaction",
|
||||
"version": "1.0.0",
|
||||
"description": "e2e test - Send two transactions in parallel.",
|
||||
"main": "sendrawtransaction.js",
|
||||
"scripts": {
|
||||
"test": "echo no tests yet",
|
||||
"start": "node sendrawtransaction.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Bitcoin-com/bitbox-javascript-sdk.git"
|
||||
},
|
||||
"keywords": [
|
||||
"bitbox",
|
||||
"bch",
|
||||
"bitcoin",
|
||||
"bitcoin cash",
|
||||
"bitcoin.com",
|
||||
"javascript"
|
||||
],
|
||||
"author": "Chris Troutner <chris.troutner@gmail.com>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/Bitcoin-com/bitbox-javascript-sdk/issues"
|
||||
},
|
||||
"homepage": "https://github.com/Bitcoin-com/bitbox-javascript-sdk/blob/master/README.md"
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
This is an end-to-end test adapted from the send-bch example. It's purpose
|
||||
is to test the sendRawTransaction endpoint.
|
||||
|
||||
This version tests the single send call.
|
||||
|
||||
Instructions:
|
||||
- Ensure the address in the wallet.json file has some tBCH.
|
||||
- Ensure the address in the wallet.json file has a UTXOs between 0.1 and
|
||||
0.001 tBCH
|
||||
- This test will generate a single transaction from a UTXOs and broadcast it
|
||||
using the sendrawtransaction single GET endpoint.
|
||||
*/
|
||||
|
||||
// Replace the address below with the address you want to send the BCH to.
|
||||
const RECV_ADDR1 = `bchtest:qzfn2mly05t6fjsh5kjj0dqq0jjtct27ng089dgg05`
|
||||
const SATOSHIS_TO_SEND = 1000
|
||||
|
||||
// Instantiate BITBOX.
|
||||
const bitboxLib = "../../../lib/BITBOX"
|
||||
const BITBOXSDK = require(bitboxLib)
|
||||
const BITBOX = new BITBOXSDK({ restURL: "https://trest.bitcoin.com/v2/" })
|
||||
//const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
|
||||
|
||||
const util = require("util")
|
||||
|
||||
// Open the wallet generated with create-wallet.
|
||||
try {
|
||||
var walletInfo = require(`./wallet.json`)
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Could not open wallet.json. Generate a wallet with create-wallet first.`
|
||||
)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const SEND_ADDR = walletInfo.cashAddress
|
||||
const SEND_MNEMONIC = walletInfo.mnemonic
|
||||
|
||||
async function testSend() {
|
||||
try {
|
||||
const hex1 = await buildTx1(RECV_ADDR1)
|
||||
//const hex2 = await buildTx2(RECV_ADDR2)
|
||||
|
||||
console.log(`hex1: ${hex1}\n\n`)
|
||||
//console.log(`hex2: ${hex2}\n\n`)
|
||||
|
||||
const broadcast = await BITBOX.RawTransactions.sendRawTransaction(hex1)
|
||||
|
||||
console.log(`Transaction IDs: ${JSON.stringify(broadcast, null, 2)}`)
|
||||
console.log(`Should return a TXID string.`)
|
||||
} catch (err) {
|
||||
console.log(`Error in testSend: `, err)
|
||||
}
|
||||
}
|
||||
testSend()
|
||||
|
||||
// Build a TX hex with the largest UTXO.
|
||||
async function buildTx1(recAddr) {
|
||||
try {
|
||||
// Get the balance of the sending address.
|
||||
const balance = await getBCHBalance(SEND_ADDR, false)
|
||||
console.log(`balance: ${JSON.stringify(balance, null, 2)}`)
|
||||
console.log(`Balance of sending address ${SEND_ADDR} is ${balance} BCH.`)
|
||||
|
||||
// Exit if the balance is zero.
|
||||
if (balance <= 0.0) {
|
||||
console.log(`Balance of sending address is zero. Exiting.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const SEND_ADDR_LEGACY = BITBOX.Address.toLegacyAddress(SEND_ADDR)
|
||||
const RECV_ADDR_LEGACY = BITBOX.Address.toLegacyAddress(recAddr)
|
||||
console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`)
|
||||
console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`)
|
||||
|
||||
const balance2 = await getBCHBalance(recAddr, false)
|
||||
//console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`)
|
||||
|
||||
const u = await BITBOX.Address.utxo(SEND_ADDR)
|
||||
//console.log(`u: ${JSON.stringify(u, null, 2)}`)
|
||||
const utxo = findBiggestUtxo(u.utxos)
|
||||
console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
|
||||
|
||||
// instance of transaction builder
|
||||
const transactionBuilder = new BITBOX.TransactionBuilder("testnet")
|
||||
|
||||
const satoshisToSend = SATOSHIS_TO_SEND
|
||||
const originalAmount = utxo.satoshis
|
||||
const vout = utxo.vout
|
||||
const txid = utxo.txid
|
||||
|
||||
// add input with txid and index of vout
|
||||
transactionBuilder.addInput(txid, vout)
|
||||
|
||||
// get byte count to calculate fee. paying 1.2 sat/byte
|
||||
const byteCount = BITBOX.BitcoinCash.getByteCount(
|
||||
{ P2PKH: 1 },
|
||||
{ P2PKH: 2 }
|
||||
)
|
||||
console.log(`byteCount: ${byteCount}`)
|
||||
const satoshisPerByte = 1.0
|
||||
const txFee = Math.floor(satoshisPerByte * byteCount)
|
||||
console.log(`txFee: ${txFee}`)
|
||||
|
||||
// amount to send back to the sending address.
|
||||
// It's the original amount - 1 sat/byte for tx size
|
||||
const remainder = originalAmount - satoshisToSend - txFee
|
||||
|
||||
// add output w/ address and amount to send
|
||||
transactionBuilder.addOutput(recAddr, satoshisToSend)
|
||||
transactionBuilder.addOutput(SEND_ADDR, remainder)
|
||||
|
||||
// Generate a change address from a Mnemonic of a private key.
|
||||
const change = changeAddrFromMnemonic(SEND_MNEMONIC)
|
||||
|
||||
// Generate a keypair from the change address.
|
||||
const keyPair = BITBOX.HDNode.toKeyPair(change)
|
||||
|
||||
// Sign the transaction with the HD node.
|
||||
let redeemScript
|
||||
transactionBuilder.sign(
|
||||
0,
|
||||
keyPair,
|
||||
redeemScript,
|
||||
transactionBuilder.hashTypes.SIGHASH_ALL,
|
||||
originalAmount
|
||||
)
|
||||
|
||||
// build tx
|
||||
const tx = transactionBuilder.build()
|
||||
// output rawhex
|
||||
const hex = tx.toHex()
|
||||
|
||||
return hex
|
||||
} catch (err) {
|
||||
console.log(`Error in buildTx().`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a change address from a Mnemonic of a private key.
|
||||
function changeAddrFromMnemonic(mnemonic) {
|
||||
// root seed buffer
|
||||
const rootSeed = BITBOX.Mnemonic.toSeed(mnemonic)
|
||||
|
||||
// master HDNode
|
||||
const masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, "testnet")
|
||||
|
||||
// HDNode of BIP44 account
|
||||
const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
|
||||
|
||||
// derive the first external change address HDNode which is going to spend utxo
|
||||
const change = BITBOX.HDNode.derivePath(account, "0/0")
|
||||
|
||||
return change
|
||||
}
|
||||
|
||||
// Get the balance in BCH of a BCH address.
|
||||
async function getBCHBalance(addr, verbose) {
|
||||
try {
|
||||
const result = await BITBOX.Address.details(addr)
|
||||
|
||||
if (verbose) console.log(result)
|
||||
|
||||
const bchBalance = result
|
||||
|
||||
return bchBalance.balance
|
||||
} catch (err) {
|
||||
console.error(`Error in getBCHBalance: `, err)
|
||||
console.log(`addr: ${addr}`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the utxo with the biggest balance from an array of utxos.
|
||||
function findBiggestUtxo(utxos) {
|
||||
// Sort the utxos by the amount of satoshis, largest first.
|
||||
utxos.sort(function(a, b) {
|
||||
return b.satoshis - a.satoshis
|
||||
})
|
||||
|
||||
return utxos[0]
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
This is an end-to-end test which verified the happy-path of sending an SLP
|
||||
token. It's really a test of the speed of SLPDB to process new token
|
||||
transactions.
|
||||
|
||||
This program expects two wallets. Wallet 1 must have a small amount of BCH
|
||||
and an inventory of SLP test tokens. Wallet 2 is the reieving wallet.
|
||||
*/
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 1
|
||||
}
|
||||
|
||||
// const SLPSDK = require("../../../lib/SLP")
|
||||
// const slpsdk = new SLPSDK()
|
||||
|
||||
const WALLET1 = `../wallet1.json`
|
||||
const WALLET2 = `../wallet2.json`
|
||||
|
||||
const lib = require("../util/e2e-util")
|
||||
|
||||
// The main test function.
|
||||
// Sends a token and reports on how long it takes to show up in SLPDB production.
|
||||
async function sendTokenTest() {
|
||||
try {
|
||||
// Open the sending wallet.
|
||||
const sendWallet = await lib.openWallet(WALLET1)
|
||||
//console.log(`sendWallet: ${JSON.stringify(walletInfo, null, 2)}`)
|
||||
|
||||
// Open the recieving wallet.
|
||||
const recvWallet = await lib.openWallet(WALLET2)
|
||||
//console.log(`recvWallet: ${JSON.stringify(walletInfo, null, 2)}`)
|
||||
|
||||
// Get the balance of the recieving wallet.
|
||||
// const testTokens = recvWallet.tokenBalance.filter(
|
||||
// x => testTokenId === x.tokenId
|
||||
// )
|
||||
// const startBalance = testTokens[0].balance
|
||||
const startBalance = await lib.getTestTokenBalance(recvWallet)
|
||||
console.log(`Starting balance: ${startBalance} test tokens.`)
|
||||
let newBalance = startBalance
|
||||
|
||||
// Send a token to the recieving wallet.
|
||||
await lib.sendToken(sendWallet, recvWallet)
|
||||
console.log(`Sent test token.`)
|
||||
|
||||
// Track the time until the balance for the recieving wallet has been updated.
|
||||
const startTime = new Date()
|
||||
const waitTime = 10000 // time in milliseconds
|
||||
|
||||
// Loop with a definite exit point, so we don't loop forever.
|
||||
for (let i = 0; i < 50; i++) {
|
||||
await sleep(waitTime) // Wait for a while before checking
|
||||
|
||||
console.log(`Checking token balance...`)
|
||||
newBalance = await lib.getTestTokenBalance(recvWallet)
|
||||
|
||||
// Break out of the loop once a new balance is detected.
|
||||
if (newBalance > startBalance) break
|
||||
|
||||
// Provide high-level warnings.
|
||||
const secondsPassed = (i * waitTime) / 1000
|
||||
if (secondsPassed > 60 * 10) {
|
||||
console.log(`More than 10 minutes passed.`)
|
||||
return false // Fail the test.
|
||||
} else if (secondsPassed > 60 * 5) {
|
||||
console.log(`More than 5 minutes passed.`)
|
||||
} else if (secondsPassed > 60) {
|
||||
console.log(`More than 1 minute passed.`)
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the amount of time that has passed.
|
||||
const endTime = new Date()
|
||||
let deltaTime = (endTime.getTime() - startTime.getTime()) / 60000
|
||||
deltaTime = lib.threeDecimals(deltaTime)
|
||||
console.log(`SLPDB updated token balance in ${deltaTime} minutes.`)
|
||||
|
||||
// Consolidate the SLP UTXOs on the recieve wallet.
|
||||
await lib.sendToken(recvWallet, recvWallet)
|
||||
|
||||
return deltaTime // Return the time in minutes it took for SLPDB to update.
|
||||
} catch (err) {
|
||||
console.log(`Error in e2e/send-token.js/sendTokenTest(): `, err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Promise based sleep function.
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sendTokenTest
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
This is a utility library for common SLP and BCH actions needed by the e2e
|
||||
tests.
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
openWallet,
|
||||
sendToken,
|
||||
getTestTokenBalance,
|
||||
threeDecimals
|
||||
}
|
||||
|
||||
const SLPSDK = require("../../../lib/SLP")
|
||||
const slpsdk = new SLPSDK()
|
||||
|
||||
const testTokenId =
|
||||
"cc1b2084a9c43bb5a633df7f38201adde5c5f5cef2fed945d12f8dcd4e505c67"
|
||||
|
||||
// Open a wallet and return an object with its address, BCH balance, and SLP
|
||||
// token balance.
|
||||
async function openWallet(filename) {
|
||||
try {
|
||||
walletInfo = require(filename)
|
||||
|
||||
//const walletBalance = await getBalance(walletInfo)
|
||||
// const walletBalance = await slpsdk.Utils.balancesForAddress(
|
||||
// walletInfo.slpAddress
|
||||
// )
|
||||
// // console.log(`walletBalance: ${JSON.stringify(walletBalance, null, 2)}`)
|
||||
// walletInfo.tokenBalance = walletBalance
|
||||
|
||||
return walletInfo
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Could not open ${filename}. Generate a wallet with create-wallet first.`,
|
||||
err
|
||||
)
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Send a token from wallet1 to wallet2.
|
||||
async function sendToken(wallet1, wallet2) {
|
||||
try {
|
||||
const mnemonic = wallet1.mnemonic
|
||||
|
||||
// root seed buffer
|
||||
const rootSeed = slpsdk.Mnemonic.toSeed(mnemonic)
|
||||
|
||||
// master HDNode
|
||||
const masterHDNode = slpsdk.HDNode.fromSeed(rootSeed)
|
||||
|
||||
// HDNode of BIP44 account
|
||||
const account = slpsdk.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
|
||||
|
||||
const change = slpsdk.HDNode.derivePath(account, "0/0")
|
||||
|
||||
// get the cash address
|
||||
//const cashAddress = slpsdk.HDNode.toCashAddress(change)
|
||||
//const slpAddress = slpsdk.HDNode.toSLPAddress(change)
|
||||
|
||||
const fundingAddress = wallet1.slpAddress
|
||||
const fundingWif = slpsdk.HDNode.toWIF(change) // <-- compressed WIF format
|
||||
const tokenReceiverAddress = wallet2.slpAddress
|
||||
const bchChangeReceiverAddress = wallet1.cashAddress
|
||||
|
||||
// Create a config object for minting
|
||||
const sendConfig = {
|
||||
fundingAddress,
|
||||
fundingWif,
|
||||
tokenReceiverAddress,
|
||||
bchChangeReceiverAddress,
|
||||
tokenId:
|
||||
"cc1b2084a9c43bb5a633df7f38201adde5c5f5cef2fed945d12f8dcd4e505c67",
|
||||
amount: 1
|
||||
}
|
||||
|
||||
//console.log(`createConfig: ${util.inspect(createConfig)}`)
|
||||
|
||||
// Generate, sign, and broadcast a hex-encoded transaction for sending
|
||||
// the tokens.
|
||||
const sendTxId = await slpsdk.TokenType1.send(sendConfig)
|
||||
|
||||
//console.log(`sendTxId: ${sendTxId}`)
|
||||
} catch (err) {
|
||||
console.log(`Error in e2e-util.js/sendToken()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Returns just the test token balance for a wallet.
|
||||
async function getTestTokenBalance(walletData) {
|
||||
try {
|
||||
const tokenBalance = await slpsdk.Util.balancesForAddress(
|
||||
walletData.slpAddress
|
||||
)
|
||||
// console.log(`tokenBalance: ${JSON.stringify(tokenBalance, null, 2)}`)
|
||||
|
||||
const testTokens = tokenBalance.filter(x => testTokenId === x.tokenId)
|
||||
|
||||
return testTokens[0].balance
|
||||
} catch (err) {
|
||||
console.log(`Error in e2e-util.js/getTestTokenBalance()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Round a number to three decimal places.
|
||||
function threeDecimals(inNum) {
|
||||
try {
|
||||
let tempNum = inNum * 1000
|
||||
tempNum = Math.round(tempNum)
|
||||
tempNum = tempNum / 1000
|
||||
return tempNum
|
||||
} catch (err) {
|
||||
console.log(`Error in e2e-util.js/threeDecimals()`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"mnemonic": "capital cushion ostrich later educate rubber thank resist alter hollow way dragon",
|
||||
"cashAddress": "bitcoincash:qrjnvnvsukcvc59a7v28pzmtue6aes4qgy5zmp72sr",
|
||||
"slpAddress": "simpleledger:qrjnvnvsukcvc59a7v28pzmtue6aes4qgyces6t2wa",
|
||||
"legacyAddress": "1Mtxny6hMUifjE9hNFoVbUYPS3wDkroLzH"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"mnemonic": "obscure volume zone abstract humor wisdom panther economy upset nation choose latin",
|
||||
"cashAddress": "bitcoincash:qpqv8cqlgkzzh2ed372g9l5vxur7f39y6vq7hac00m",
|
||||
"slpAddress": "simpleledger:qpqv8cqlgkzzh2ed372g9l5vxur7f39y6vv9uxd039",
|
||||
"legacyAddress": "16uStwkG1nGC1HB2tSWGqLQN2bDjXeeeRk"
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
Integration tests for the Blockbook library.
|
||||
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
//const axios = require("axios")
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe(`#Blockbook`, () => {
|
||||
describe(`#Balance`, () => {
|
||||
it(`should GET balance for a single address`, async () => {
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"page",
|
||||
"totalPages",
|
||||
"itemsOnPage",
|
||||
"address",
|
||||
"balance",
|
||||
"totalReceived",
|
||||
"totalSent",
|
||||
"unconfirmedBalance",
|
||||
"unconfirmedTxs",
|
||||
"txs",
|
||||
"txids"
|
||||
])
|
||||
assert.isArray(result.txids)
|
||||
})
|
||||
|
||||
it(`should POST request balances for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"page",
|
||||
"totalPages",
|
||||
"itemsOnPage",
|
||||
"address",
|
||||
"balance",
|
||||
"totalReceived",
|
||||
"totalSent",
|
||||
"unconfirmedBalance",
|
||||
"unconfirmedTxs",
|
||||
"txs",
|
||||
"txids"
|
||||
])
|
||||
assert.isArray(result[0].txids)
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Blockbook.balance(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
const addr = "bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7"
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"value",
|
||||
"height",
|
||||
"confirmations"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should POST utxo details for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7",
|
||||
"bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isArray(result[0])
|
||||
assert.hasAnyKeys(result[0][0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"value",
|
||||
"height",
|
||||
"confirmations"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Blockbook.utxo(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr")
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,331 @@
|
||||
/*
|
||||
Integration tests for the bchjs. Only covers calls made to
|
||||
rest.bitcoin.com.
|
||||
|
||||
TODO
|
||||
- getMempoolEntry() only works on TXs in the mempool, so it needs to be part
|
||||
of an e2e test to be properly tested.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe(`#blockchain`, () => {
|
||||
describe(`#getBestBlockHash`, () => {
|
||||
it(`should GET best block hash`, async () => {
|
||||
const result = await bchjs.Blockchain.getBestBlockHash()
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.isString(result)
|
||||
assert.equal(result.length, 64, "Specific hash length")
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getBlockHeader", () => {
|
||||
it(`should GET block header for a single hash`, async () => {
|
||||
const hash =
|
||||
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201"
|
||||
|
||||
const result = await bchjs.Blockchain.getBlockHeader(hash)
|
||||
|
||||
assert.hasAllKeys(result, [
|
||||
"hash",
|
||||
"confirmations",
|
||||
"height",
|
||||
"version",
|
||||
"versionHex",
|
||||
"merkleroot",
|
||||
"time",
|
||||
"mediantime",
|
||||
"nonce",
|
||||
"bits",
|
||||
"difficulty",
|
||||
"chainwork",
|
||||
"previousblockhash",
|
||||
"nextblockhash",
|
||||
"nTx"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should GET block headers for an array of hashes`, async () => {
|
||||
const hash = [
|
||||
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201",
|
||||
"00000000000000000568f0a96bf4348847bc84e455cbfec389f27311037a20f3"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockchain.getBlockHeader(hash)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAllKeys(result[0], [
|
||||
"hash",
|
||||
"confirmations",
|
||||
"height",
|
||||
"version",
|
||||
"versionHex",
|
||||
"merkleroot",
|
||||
"time",
|
||||
"mediantime",
|
||||
"nonce",
|
||||
"bits",
|
||||
"difficulty",
|
||||
"chainwork",
|
||||
"previousblockhash",
|
||||
"nextblockhash",
|
||||
"nTx"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const hash = 12345
|
||||
|
||||
await bchjs.Blockchain.getBlockHeader(hash)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input hash must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) {
|
||||
data.push(
|
||||
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201"
|
||||
)
|
||||
}
|
||||
|
||||
const result = await bchjs.Blockchain.getBlockHeader(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getMempoolEntry", () => {
|
||||
/*
|
||||
// To run this test, the txid must be unconfirmed.
|
||||
const txid =
|
||||
"defea04c38ee00cf73ad402984714ed22dc0dd99b2ae5cb50d791d94343ba79b"
|
||||
|
||||
it(`should GET single mempool entry`, async () => {
|
||||
const result = await bchjs.Blockchain.getMempoolEntry(txid)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"size",
|
||||
"fee",
|
||||
"modifiedfee",
|
||||
"time",
|
||||
"height",
|
||||
"startingpriority",
|
||||
"currentpriority",
|
||||
"descendantcount",
|
||||
"descendantsize",
|
||||
"descendantfees",
|
||||
"ancestorcount",
|
||||
"ancestorsize",
|
||||
"ancestorfees",
|
||||
"depends"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should get an array of mempool entries`, async () => {
|
||||
const result = await bchjs.Blockchain.getMempoolEntry([txid, txid])
|
||||
console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"size",
|
||||
"fee",
|
||||
"modifiedfee",
|
||||
"time",
|
||||
"height",
|
||||
"startingpriority",
|
||||
"currentpriority",
|
||||
"descendantcount",
|
||||
"descendantsize",
|
||||
"descendantfees",
|
||||
"ancestorcount",
|
||||
"ancestorsize",
|
||||
"ancestorfees",
|
||||
"depends"
|
||||
])
|
||||
})
|
||||
*/
|
||||
|
||||
it(`should throw an error if txid is not in mempool`, async () => {
|
||||
try {
|
||||
const txid =
|
||||
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
|
||||
|
||||
await bchjs.Blockchain.getMempoolEntry(txid)
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: ${util.inspect(err)}`)
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, `Transaction not in mempool`)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const txid = 12345
|
||||
|
||||
await bchjs.Blockchain.getMempoolEntry(txid)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#getTxOutProof`, () => {
|
||||
it(`should get single tx out proof`, async () => {
|
||||
const txid =
|
||||
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
|
||||
|
||||
const result = await bchjs.Blockchain.getTxOutProof(txid)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isString(result)
|
||||
})
|
||||
|
||||
it(`should get an array of tx out proofs`, async () => {
|
||||
const txid = [
|
||||
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7",
|
||||
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockchain.getTxOutProof(txid)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const txid = 12345
|
||||
|
||||
await bchjs.Blockchain.getTxOutProof(txid)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#verifyTxOutProof`, () => {
|
||||
const mockTxOutProof =
|
||||
"0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01"
|
||||
|
||||
it(`should verify a single proof`, async () => {
|
||||
const result = await bchjs.Blockchain.verifyTxOutProof(mockTxOutProof)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
assert.equal(
|
||||
result[0],
|
||||
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
|
||||
)
|
||||
})
|
||||
|
||||
it(`should verify an array of proofs`, async () => {
|
||||
const proofs = [mockTxOutProof, mockTxOutProof]
|
||||
const result = await bchjs.Blockchain.verifyTxOutProof(proofs)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
assert.equal(
|
||||
result[0],
|
||||
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
|
||||
)
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const txid = 12345
|
||||
|
||||
await bchjs.Blockchain.verifyTxOutProof(txid)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(mockTxOutProof)
|
||||
|
||||
const result = await bchjs.Blockchain.verifyTxOutProof(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getTxOut", () => {
|
||||
it("should get information on an unspent tx", async () => {
|
||||
const result = await bchjs.Blockchain.getTxOut(
|
||||
"62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8",
|
||||
0,
|
||||
true
|
||||
)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, [
|
||||
"bestblock",
|
||||
"confirmations",
|
||||
"value",
|
||||
"scriptPubKey",
|
||||
"coinbase"
|
||||
])
|
||||
})
|
||||
|
||||
it("should get information on a spent tx", async () => {
|
||||
const result = await bchjs.Blockchain.getTxOut(
|
||||
"87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871",
|
||||
0,
|
||||
true
|
||||
)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.equal(result, null)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
Integration tests for bchjs control library.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
describe(`#control`, () => {
|
||||
describe(`#getNetworkInfo`, () => {
|
||||
it("should get info on the full node", async () => {
|
||||
const result = await bchjs.Control.getNetworkInfo()
|
||||
console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "version")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const sinon = require("sinon")
|
||||
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
describe(`#ElectrumX`, () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "utxos")
|
||||
assert.isArray(result.utxos)
|
||||
|
||||
assert.property(result.utxos[0], "height")
|
||||
assert.property(result.utxos[0], "tx_hash")
|
||||
assert.property(result.utxos[0], "tx_pos")
|
||||
assert.property(result.utxos[0], "value")
|
||||
})
|
||||
|
||||
it(`should POST request for UTXOs for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "utxos")
|
||||
assert.isArray(result.utxos)
|
||||
|
||||
assert.property(result.utxos[0], "utxos")
|
||||
assert.isArray(result.utxos[0].utxos)
|
||||
assert.property(result.utxos[0], "address")
|
||||
|
||||
assert.property(result.utxos[0].utxos[0], "height")
|
||||
assert.property(result.utxos[0].utxos[0], "tx_hash")
|
||||
assert.property(result.utxos[0].utxos[0], "tx_pos")
|
||||
assert.property(result.utxos[0].utxos[0], "value")
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#balance`, () => {
|
||||
it(`should GET balance for a single address`, async () => {
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "balance")
|
||||
assert.property(result.balance, "confirmed")
|
||||
assert.property(result.balance, "unconfirmed")
|
||||
})
|
||||
|
||||
it(`should POST request for balances for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "balances")
|
||||
assert.isArray(result.balances)
|
||||
|
||||
assert.property(result.balances[0], "address")
|
||||
assert.property(result.balances[0], "balance")
|
||||
assert.property(result.balances[0].balance, "confirmed")
|
||||
assert.property(result.balances[0].balance, "unconfirmed")
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#transactions`, () => {
|
||||
it(`should GET transaction history for a single address`, async () => {
|
||||
const addr = "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "transactions")
|
||||
assert.isArray(result.transactions)
|
||||
assert.property(result.transactions[0], "height")
|
||||
assert.property(result.transactions[0], "tx_hash")
|
||||
})
|
||||
|
||||
it(`should POST request for transaction history for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "transactions")
|
||||
assert.isArray(result.transactions)
|
||||
|
||||
assert.property(result.transactions[0], "address")
|
||||
assert.property(result.transactions[0], "transactions")
|
||||
assert.isArray(result.transactions[0].transactions)
|
||||
assert.property(result.transactions[0].transactions[0], "height")
|
||||
assert.property(result.transactions[0].transactions[0], "tx_hash")
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qrehqueqhw629p6e57994436w730t4rzasnly00ht0")
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
const assert = require("chai").assert
|
||||
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
describe("#Encryption", () => {
|
||||
describe("#getPubKey", () => {
|
||||
it("should get a public key", async () => {
|
||||
const addr = "bitcoincash:qpf8jv9hmqcda0502gjp7nm3g24y5h5s4unutghsxq"
|
||||
|
||||
const result = await bchjs.encryption.getPubKey(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
assert.property(result, "publicKey")
|
||||
})
|
||||
|
||||
it("should report when public key can not be found", async () => {
|
||||
const addr = "bitcoincash:qrgqqkky28jdkv3w0ctrah0mz3jcsnsklc34gtukrh"
|
||||
|
||||
const result = await bchjs.encryption.getPubKey(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, false)
|
||||
assert.property(result, "publicKey")
|
||||
assert.equal(result.publicKey, "not found")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const sinon = require("sinon")
|
||||
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
describe(`#Ninsight`, () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.Ninsight.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "utxos")
|
||||
assert.property(result, "legacyAddress")
|
||||
assert.property(result, "cashAddress")
|
||||
assert.property(result, "slpAddress")
|
||||
assert.property(result, "scriptPubKey")
|
||||
assert.property(result, "asm")
|
||||
|
||||
assert.isArray(result.utxos)
|
||||
|
||||
assert.property(result.utxos[0], "txid")
|
||||
assert.property(result.utxos[0], "vout")
|
||||
assert.property(result.utxos[0], "amount")
|
||||
assert.property(result.utxos[0], "satoshis")
|
||||
assert.property(result.utxos[0], "height")
|
||||
assert.property(result.utxos[0], "confirmations")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
tests for OpenBazaar library.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
describe(`#OpenBazaar`, () => {
|
||||
describe(`#Balance`, () => {
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.OpenBazaar.balance(addr)
|
||||
// assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(err.message, `Input address must be a string`)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should GET balance for a single address`, async () => {
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.OpenBazaar.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, [
|
||||
"page",
|
||||
"totalPages",
|
||||
"itemsOnPage",
|
||||
"addrStr",
|
||||
"balance",
|
||||
"totalReceived",
|
||||
"totalSent",
|
||||
"unconfirmedBalance",
|
||||
"unconfirmedTxApperances",
|
||||
"txApperances",
|
||||
"transactions"
|
||||
])
|
||||
assert.isArray(result.transactions)
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.OpenBazaar.utxo(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(err.message, `Input address must be a string`)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.OpenBazaar.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAllKeys(result[0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"amount",
|
||||
"height",
|
||||
"confirmations",
|
||||
"satoshis"
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#tx`, () => {
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.OpenBazaar.tx(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(err.message, `Input txid must be a string`)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should GET transactions for a single address`, async () => {
|
||||
const addr =
|
||||
"2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7"
|
||||
|
||||
const result = await bchjs.OpenBazaar.tx(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, [
|
||||
"txid",
|
||||
"version",
|
||||
"vin",
|
||||
"vout",
|
||||
"blockhash",
|
||||
"blockheight",
|
||||
"confirmations",
|
||||
"blocktime",
|
||||
"valueOut",
|
||||
"valueIn",
|
||||
"fees",
|
||||
"hex",
|
||||
"time"
|
||||
])
|
||||
assert.isArray(result.vin)
|
||||
assert.isArray(result.vout)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
const assert = require("assert")
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
describe("#price", () => {
|
||||
describe("#current", () => {
|
||||
describe("#single currency", () => {
|
||||
it("should get current price for single currency", async () => {
|
||||
const result = await bchjs.Price.current("usd")
|
||||
assert.notEqual(0, result)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
Integration tests for the bchjs. Only covers calls made to
|
||||
rest.bitcoin.com.
|
||||
|
||||
TODO
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe("#rawtransaction", () => {
|
||||
describe("#decodeRawTransaction", () => {
|
||||
it("should decode tx for a single hex", async () => {
|
||||
const hex =
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeRawTransaction(hex)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout"
|
||||
])
|
||||
assert.isArray(result.vin)
|
||||
assert.isArray(result.vout)
|
||||
})
|
||||
|
||||
it("should decode an array of tx hexes", async () => {
|
||||
const hexes = [
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000",
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
|
||||
]
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeRawTransaction(hexes)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout"
|
||||
])
|
||||
assert.isArray(result[0].vin)
|
||||
assert.isArray(result[0].vout)
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.RawTransactions.decodeRawTransaction(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings.`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) {
|
||||
data.push(
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
|
||||
)
|
||||
}
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeRawTransaction(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getRawTransaction", () => {
|
||||
it("should decode a single txid, with concise output", async () => {
|
||||
const txid =
|
||||
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1"
|
||||
const verbose = false
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isString(result)
|
||||
})
|
||||
|
||||
it("should decode a single txid, with verbose output", async () => {
|
||||
const txid =
|
||||
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1"
|
||||
const verbose = true
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"hex",
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout",
|
||||
"blockhash",
|
||||
"confirmations",
|
||||
"time",
|
||||
"blocktime"
|
||||
])
|
||||
assert.isArray(result.vin)
|
||||
assert.isArray(result.vout)
|
||||
})
|
||||
|
||||
it("should decode an array of txids, with a concise output", async () => {
|
||||
const txid = [
|
||||
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1",
|
||||
"b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f"
|
||||
]
|
||||
const verbose = false
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
})
|
||||
|
||||
it("should decode an array of txids, with a verbose output", async () => {
|
||||
const txid = [
|
||||
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1",
|
||||
"b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f"
|
||||
]
|
||||
const verbose = true
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"hex",
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout",
|
||||
"blockhash",
|
||||
"confirmations",
|
||||
"time",
|
||||
"blocktime"
|
||||
])
|
||||
assert.isArray(result[0].vin)
|
||||
assert.isArray(result[0].vout)
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const dataMock =
|
||||
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1"
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(dataMock)
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#decodeScript", () => {
|
||||
it("should decode script for a single hex", async () => {
|
||||
const hex =
|
||||
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16"
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeScript(hex)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["asm", "type", "p2sh"])
|
||||
})
|
||||
|
||||
// CT 2/20/19 - Waiting for this PR to be merged complete the test:
|
||||
// https://github.com/Bitcoin-com/rest.bitcoin.com/pull/312
|
||||
/*
|
||||
it("should decode an array of tx hexes", async () => {
|
||||
const hexes = [
|
||||
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16",
|
||||
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16"
|
||||
]
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeScript(hexes)
|
||||
console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
})
|
||||
*/
|
||||
/*
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.RawTransactions.decodeRawTransaction(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings.`
|
||||
)
|
||||
}
|
||||
})
|
||||
*/
|
||||
})
|
||||
|
||||
/*
|
||||
Testing sentRawTransaction isn't really possible with an integration test,
|
||||
as the endpoint really needs an e2e test to be properly tested. The tests
|
||||
below expect error messages returned from the server, but at least test
|
||||
that the server is responding on those endpoints, and responds consistently.
|
||||
*/
|
||||
describe("sendRawTransaction", () => {
|
||||
it("should send a single transaction hex", async () => {
|
||||
try {
|
||||
const hex =
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
|
||||
|
||||
await bchjs.RawTransactions.sendRawTransaction(hex)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: ${util.inspect(err)}`)
|
||||
|
||||
assert.hasAllKeys(err, ["error"])
|
||||
assert.include(err.error, "Missing inputs")
|
||||
}
|
||||
})
|
||||
|
||||
it("should send an array of tx hexes", async () => {
|
||||
try {
|
||||
const hexes = [
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000",
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
|
||||
]
|
||||
|
||||
const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
|
||||
console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
} catch (err) {
|
||||
// console.log(`err: ${util.inspect(err)}`)
|
||||
|
||||
assert.hasAllKeys(err, ["error"])
|
||||
assert.include(err.error, "Missing inputs")
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.RawTransactions.sendRawTransaction(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input hex must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const dataMock =
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(dataMock)
|
||||
|
||||
const result = await bchjs.RawTransactions.sendRawTransaction(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,529 @@
|
||||
/*
|
||||
Integration tests for the bchjs covering SLP tokens.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 1
|
||||
}
|
||||
|
||||
describe(`#SLP`, () => {
|
||||
// before(() => {
|
||||
// console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`)
|
||||
// console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`)
|
||||
// })
|
||||
|
||||
beforeEach(async () => {
|
||||
// Introduce a delay so that the BVT doesn't trip the rate limits.
|
||||
await sleep(1000)
|
||||
})
|
||||
|
||||
describe("#util", () => {
|
||||
describe("#list", () => {
|
||||
it(`should get information on the Spice token`, async () => {
|
||||
const tokenId = `4de69e374a8ed21cbddd47f2338cc0f479dc58daa2bbe11cd604ca488eca0ddf`
|
||||
|
||||
const result = await bchjs.SLP.Utils.list(tokenId)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"decimals",
|
||||
"timestamp",
|
||||
"timestamp_unix",
|
||||
"versionType",
|
||||
"documentUri",
|
||||
"symbol",
|
||||
"name",
|
||||
"containsBaton",
|
||||
"id",
|
||||
"documentHash",
|
||||
"initialTokenQty",
|
||||
"blockCreated",
|
||||
"blockLastActiveSend",
|
||||
"blockLastActiveMint",
|
||||
"txnsSinceGenesis",
|
||||
"validAddress",
|
||||
"totalMinted",
|
||||
"totalBurned",
|
||||
"circulatingSupply",
|
||||
"mintingBatonStatus"
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
// describe("#decodeOpReturn", () => {
|
||||
// it("should decode the OP_RETURN for a SEND txid", async () => {
|
||||
// const txid =
|
||||
// "266844d53e46bbd7dd37134688dffea6e54d944edff27a0add63dd0908839bc1"
|
||||
//
|
||||
// const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
//
|
||||
// assert.hasAllKeys(result, [
|
||||
// "tokenType",
|
||||
// "transactionType",
|
||||
// "tokenId",
|
||||
// "spendData"
|
||||
// ])
|
||||
// })
|
||||
//
|
||||
// it("should decode the OP_RETURN for a GENESIS txid", async () => {
|
||||
// const txid =
|
||||
// "497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7"
|
||||
//
|
||||
// const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
//
|
||||
// assert.hasAllKeys(result, [
|
||||
// "tokenType",
|
||||
// "transactionType",
|
||||
// "ticker",
|
||||
// "name",
|
||||
// "documentUrl",
|
||||
// "documentHash",
|
||||
// "decimals",
|
||||
// "mintBatonVout",
|
||||
// "initialQty",
|
||||
// "tokensSentTo",
|
||||
// "batonHolder"
|
||||
// ])
|
||||
// })
|
||||
//
|
||||
// it("should decode the OP_RETURN for a MINT txid", async () => {
|
||||
// const txid =
|
||||
// "65f21bbfcd545e5eb515e38e861a9dfe2378aaa2c4e458eb9e59e4d40e38f3a4"
|
||||
//
|
||||
// const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
//
|
||||
// assert.hasAllKeys(result, [
|
||||
// "tokenType",
|
||||
// "transactionType",
|
||||
// "tokenId",
|
||||
// "mintBatonVout",
|
||||
// "batonStillExists",
|
||||
// "quantity",
|
||||
// "tokensSentTo",
|
||||
// "batonHolder"
|
||||
// ])
|
||||
// })
|
||||
//
|
||||
// it("should throw an error for a non-SLP transaction", async () => {
|
||||
// try {
|
||||
// const txid =
|
||||
// "3793d4906654f648e659f384c0f40b19c8f10c1e9fb72232a9b8edd61abaa1ec"
|
||||
//
|
||||
// await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
//
|
||||
// assert.equal(true, false, "Unexpected result")
|
||||
// } catch (err) {
|
||||
// // console.log(`err: `, err)
|
||||
// assert.include(err.message, "Not an OP_RETURN")
|
||||
// }
|
||||
// })
|
||||
// })
|
||||
|
||||
describe("#decodeOpReturn", () => {
|
||||
it("should decode the OP_RETURN for a SEND txid", async () => {
|
||||
const txid =
|
||||
"266844d53e46bbd7dd37134688dffea6e54d944edff27a0add63dd0908839bc1"
|
||||
|
||||
const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["tokenType", "txType", "tokenId", "amounts"])
|
||||
assert.equal(
|
||||
result.tokenId,
|
||||
"497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7"
|
||||
)
|
||||
|
||||
// Verify outputs
|
||||
assert.equal(result.amounts.length, 2)
|
||||
assert.equal(result.amounts[0], "100000000")
|
||||
assert.equal(result.amounts[1], "99883300000000")
|
||||
})
|
||||
|
||||
it("should decode the OP_RETURN for a GENESIS txid", async () => {
|
||||
const txid =
|
||||
"497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7"
|
||||
|
||||
const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, [
|
||||
"tokenType",
|
||||
"txType",
|
||||
"tokenId",
|
||||
"ticker",
|
||||
"name",
|
||||
"documentUri",
|
||||
"documentHash",
|
||||
"decimals",
|
||||
"mintBatonVout",
|
||||
"qty"
|
||||
])
|
||||
assert.equal(
|
||||
result.tokenId,
|
||||
"497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7"
|
||||
)
|
||||
assert.equal(result.txType, "GENESIS")
|
||||
assert.equal(result.ticker, "TOK-CH")
|
||||
assert.equal(result.name, "TokyoCash")
|
||||
})
|
||||
|
||||
it("should decode the OP_RETURN for a MINT txid", async () => {
|
||||
const txid =
|
||||
"65f21bbfcd545e5eb515e38e861a9dfe2378aaa2c4e458eb9e59e4d40e38f3a4"
|
||||
|
||||
const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, [
|
||||
"tokenType",
|
||||
"txType",
|
||||
"tokenId",
|
||||
"mintBatonVout",
|
||||
"qty"
|
||||
])
|
||||
})
|
||||
|
||||
it("should throw an error for a non-SLP transaction", async () => {
|
||||
try {
|
||||
const txid =
|
||||
"3793d4906654f648e659f384c0f40b19c8f10c1e9fb72232a9b8edd61abaa1ec"
|
||||
|
||||
await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
|
||||
assert.equal(true, false, "Unexpected result")
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(err.message, "scriptpubkey not op_return")
|
||||
}
|
||||
})
|
||||
|
||||
// Note: This TX is interpreted as valid by the original decodeOpReturn().
|
||||
// Fixing this issue and related issues was the reason for creating the
|
||||
// decodeOpReturn2() method using the slp-parser library.
|
||||
it("should throw error for invalid SLP transaction", async () => {
|
||||
try {
|
||||
const txid =
|
||||
"a60a522cc11ad7011b74e57fbabbd99296e4b9346bcb175dcf84efb737030415"
|
||||
|
||||
await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(err.message, "amount string size not 8 bytes")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#tokenUtxoDetails", () => {
|
||||
// // This captures an important corner-case. When an SLP token is created, the
|
||||
// // change UTXO will contain the same SLP txid, but it is not an SLP UTXO.
|
||||
it("should return details on minting baton from genesis transaction", async () => {
|
||||
const utxos = [
|
||||
{
|
||||
txid:
|
||||
"bd158c564dd4ef54305b14f44f8e94c44b649f246dab14bcb42fb0d0078b8a90",
|
||||
vout: 3,
|
||||
amount: 0.00002015,
|
||||
satoshis: 2015,
|
||||
height: 594892,
|
||||
confirmations: 5
|
||||
},
|
||||
{
|
||||
txid:
|
||||
"bd158c564dd4ef54305b14f44f8e94c44b649f246dab14bcb42fb0d0078b8a90",
|
||||
vout: 2,
|
||||
amount: 0.00000546,
|
||||
satoshis: 546,
|
||||
height: 594892,
|
||||
confirmations: 5
|
||||
}
|
||||
]
|
||||
|
||||
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
|
||||
// console.log(`data: ${JSON.stringify(data, null, 2)}`)
|
||||
|
||||
assert.equal(data[0].isValid, false, "Change UTXO marked as false.")
|
||||
|
||||
assert.property(data[1], "txid")
|
||||
assert.property(data[1], "vout")
|
||||
assert.property(data[1], "amount")
|
||||
assert.property(data[1], "satoshis")
|
||||
assert.property(data[1], "height")
|
||||
assert.property(data[1], "confirmations")
|
||||
assert.property(data[1], "utxoType")
|
||||
assert.property(data[1], "tokenId")
|
||||
assert.property(data[1], "tokenTicker")
|
||||
assert.property(data[1], "tokenName")
|
||||
assert.property(data[1], "tokenDocumentUrl")
|
||||
assert.property(data[1], "tokenDocumentHash")
|
||||
assert.property(data[1], "decimals")
|
||||
assert.property(data[1], "isValid")
|
||||
assert.equal(data[1].isValid, true)
|
||||
})
|
||||
|
||||
it("should return details for a MINT token utxo", async () => {
|
||||
// Mock the call to REST API
|
||||
|
||||
const utxos = [
|
||||
{
|
||||
txid:
|
||||
"cf4b922d1e1aa56b52d752d4206e1448ea76c3ebe69b3b97d8f8f65413bd5c76",
|
||||
vout: 1,
|
||||
amount: 0.00000546,
|
||||
satoshis: 546,
|
||||
height: 600297,
|
||||
confirmations: 76
|
||||
}
|
||||
]
|
||||
|
||||
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
|
||||
// console.log(`data: ${JSON.stringify(data, null, 2)}`)
|
||||
|
||||
assert.property(data[0], "txid")
|
||||
assert.property(data[0], "vout")
|
||||
assert.property(data[0], "amount")
|
||||
assert.property(data[0], "satoshis")
|
||||
assert.property(data[0], "height")
|
||||
assert.property(data[0], "confirmations")
|
||||
assert.property(data[0], "utxoType")
|
||||
assert.property(data[0], "transactionType")
|
||||
assert.property(data[0], "tokenId")
|
||||
assert.property(data[0], "tokenTicker")
|
||||
assert.property(data[0], "tokenName")
|
||||
assert.property(data[0], "tokenDocumentUrl")
|
||||
assert.property(data[0], "tokenDocumentHash")
|
||||
assert.property(data[0], "decimals")
|
||||
assert.property(data[0], "mintBatonVout")
|
||||
assert.property(data[0], "tokenQty")
|
||||
assert.property(data[0], "isValid")
|
||||
assert.equal(data[0].isValid, true)
|
||||
})
|
||||
|
||||
it("should return details for a simple SEND SLP token utxo", async () => {
|
||||
const utxos = [
|
||||
{
|
||||
txid:
|
||||
"fde117b1f176b231e2fa9a6cb022e0f7c31c288221df6bcb05f8b7d040ca87cb",
|
||||
vout: 1,
|
||||
amount: 0.00000546,
|
||||
satoshis: 546,
|
||||
height: 596089,
|
||||
confirmations: 748
|
||||
}
|
||||
]
|
||||
|
||||
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
|
||||
// console.log(`data: ${JSON.stringify(data, null, 2)}`)
|
||||
|
||||
assert.property(data[0], "txid")
|
||||
assert.property(data[0], "vout")
|
||||
assert.property(data[0], "amount")
|
||||
assert.property(data[0], "satoshis")
|
||||
assert.property(data[0], "height")
|
||||
assert.property(data[0], "confirmations")
|
||||
assert.property(data[0], "utxoType")
|
||||
assert.property(data[0], "tokenId")
|
||||
assert.property(data[0], "tokenTicker")
|
||||
assert.property(data[0], "tokenName")
|
||||
assert.property(data[0], "tokenDocumentUrl")
|
||||
assert.property(data[0], "tokenDocumentHash")
|
||||
assert.property(data[0], "decimals")
|
||||
assert.property(data[0], "tokenQty")
|
||||
assert.property(data[0], "isValid")
|
||||
assert.equal(data[0].isValid, true)
|
||||
})
|
||||
|
||||
it("should handle BCH and SLP utxos in the same TX", async () => {
|
||||
const utxos = [
|
||||
{
|
||||
txid:
|
||||
"d56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56",
|
||||
vout: 3,
|
||||
value: "6816",
|
||||
height: 606848,
|
||||
confirmations: 13,
|
||||
satoshis: 6816
|
||||
},
|
||||
{
|
||||
txid:
|
||||
"d56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56",
|
||||
vout: 2,
|
||||
value: "546",
|
||||
height: 606848,
|
||||
confirmations: 13,
|
||||
satoshis: 546
|
||||
}
|
||||
]
|
||||
|
||||
const result = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.equal(result.length, 2)
|
||||
assert.equal(result[0].isValid, false)
|
||||
assert.equal(result[1].isValid, true)
|
||||
})
|
||||
|
||||
it("should handle problematic utxos", async () => {
|
||||
const utxos = [
|
||||
{
|
||||
txid:
|
||||
"0e3a217fc22612002031d317b4cecd9b692b66b52951a67b23c43041aefa3959",
|
||||
vout: 0,
|
||||
amount: 0.00018362,
|
||||
satoshis: 18362,
|
||||
height: 613483,
|
||||
confirmations: 124
|
||||
},
|
||||
{
|
||||
txid:
|
||||
"67fd3c7c3a6eb0fea9ab311b91039545086220f7eeeefa367fa28e6e43009f19",
|
||||
vout: 1,
|
||||
amount: 0.00000546,
|
||||
satoshis: 546,
|
||||
height: 612075,
|
||||
confirmations: 1532
|
||||
}
|
||||
]
|
||||
|
||||
const result = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.equal(result.length, 2)
|
||||
assert.equal(result[0].isValid, false)
|
||||
assert.equal(result[1].isValid, true)
|
||||
})
|
||||
|
||||
it("should return false for BCH-only UTXOs", async () => {
|
||||
const utxos = [
|
||||
{
|
||||
txid:
|
||||
"a937f792c7c9eb23b4f344ce5c233d1ac0909217d0a504d71e6b1e4efb864a3b",
|
||||
vout: 0,
|
||||
amount: 0.00001,
|
||||
satoshis: 1000,
|
||||
confirmations: 0,
|
||||
ts: 1578424704
|
||||
},
|
||||
{
|
||||
txid:
|
||||
"53fd141c2e999e080a5860887441a2c45e9cbe262027e2bd2ac998fc76e43c44",
|
||||
vout: 0,
|
||||
amount: 0.00001,
|
||||
satoshis: 1000,
|
||||
confirmations: 0,
|
||||
ts: 1578424634
|
||||
}
|
||||
]
|
||||
|
||||
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
|
||||
// console.log(`data: ${JSON.stringify(data, null, 2)}`)
|
||||
|
||||
assert.isArray(data)
|
||||
assert.equal(data[0].isValid, false)
|
||||
assert.equal(data[1].isValid, false)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#balancesForAddress", () => {
|
||||
it(`should throw an error if input is not a string or array of strings`, async () => {
|
||||
try {
|
||||
const address = 1234
|
||||
|
||||
await bchjs.SLP.Utils.balancesForAddress(address)
|
||||
|
||||
assert.equal(true, false, "Uh oh. Code path should not end here.")
|
||||
} catch (err) {
|
||||
//console.log(`Error: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should fetch all balances for address: simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9`, async () => {
|
||||
const balances = await bchjs.SLP.Utils.balancesForAddress(
|
||||
"simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9"
|
||||
)
|
||||
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
|
||||
|
||||
assert.isArray(balances)
|
||||
assert.hasAllKeys(balances[0], [
|
||||
"tokenId",
|
||||
"balanceString",
|
||||
"balance",
|
||||
"decimalCount",
|
||||
"slpAddress"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should fetch balances for multiple addresses`, async () => {
|
||||
const addresses = [
|
||||
"simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9",
|
||||
"simpleledger:qqss4zp80hn6szsa4jg2s9fupe7g5tcg5ucdyl3r57"
|
||||
]
|
||||
|
||||
const balances = await bchjs.SLP.Utils.balancesForAddress(addresses)
|
||||
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
|
||||
|
||||
assert.isArray(balances)
|
||||
assert.isArray(balances[0])
|
||||
assert.hasAllKeys(balances[0][0], [
|
||||
"tokenId",
|
||||
"balanceString",
|
||||
"balance",
|
||||
"decimalCount",
|
||||
"slpAddress"
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#tokentype1", () => {
|
||||
describe("#getHexOpReturn", () => {
|
||||
it("should return OP_RETURN object ", async () => {
|
||||
const tokenUtxos = [
|
||||
{
|
||||
tokenId:
|
||||
"0a321bff9761f28e06a268b14711274bb77617410a16807bd0437ef234a072b1",
|
||||
decimals: 0,
|
||||
tokenQty: 2
|
||||
}
|
||||
]
|
||||
const sendQty = 1.5
|
||||
|
||||
const result = await bchjs.SLP.TokenType1.getHexOpReturn(
|
||||
tokenUtxos,
|
||||
sendQty
|
||||
)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "script")
|
||||
assert.isString(result.script)
|
||||
|
||||
assert.property(result, "outputs")
|
||||
assert.isNumber(result.outputs)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Promise-based sleep function
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms))
|
||||
}
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
export RESTURL=https://free-main.fullstack.cash/v3/
|
||||
#export RESTURL=http://localhost:3000/v3/
|
||||
|
||||
cd test/integration/
|
||||
mocha --timeout 30000 blockchain.js control.js electrumx.js ninsight.js openbazaar.js price.js rawtransaction.js slp.js util.js
|
||||
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
Integration tests for the Blockbook library.
|
||||
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v3/` })
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
// const bchjs = new BCHJS({ restURL: RESTURL })
|
||||
//const axios = require("axios")
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe(`#Blockbook`, () => {
|
||||
describe(`#Balance`, () => {
|
||||
it(`should GET balance for a single address`, async () => {
|
||||
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
// console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"page",
|
||||
"totalPages",
|
||||
"itemsOnPage",
|
||||
"address",
|
||||
"balance",
|
||||
"totalReceived",
|
||||
"totalSent",
|
||||
"unconfirmedBalance",
|
||||
"unconfirmedTxs",
|
||||
"txs",
|
||||
"txids"
|
||||
])
|
||||
assert.isArray(result.txids)
|
||||
})
|
||||
|
||||
it(`should POST request balances for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2",
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"page",
|
||||
"totalPages",
|
||||
"itemsOnPage",
|
||||
"address",
|
||||
"balance",
|
||||
"totalReceived",
|
||||
"totalSent",
|
||||
"unconfirmedBalance",
|
||||
"unconfirmedTxs",
|
||||
"txs",
|
||||
"txids"
|
||||
])
|
||||
assert.isArray(result[0].txids)
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Blockbook.balance(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"value",
|
||||
"height",
|
||||
"confirmations"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should POST utxo details for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2",
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isArray(result[0])
|
||||
assert.hasAnyKeys(result[0][0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"value",
|
||||
"height",
|
||||
"confirmations"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Blockbook.utxo(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,308 @@
|
||||
/*
|
||||
Integration tests for the bchjs. Only covers calls made to
|
||||
rest.bitcoin.com.
|
||||
|
||||
TODO
|
||||
- getMempoolEntry() only works on TXs in the mempool, so it needs to be part
|
||||
of an e2e test to be properly tested.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v3/` })
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe(`#blockchain`, () => {
|
||||
describe(`#getBestBlockHash`, () => {
|
||||
it(`should GET best block hash`, async () => {
|
||||
const result = await bchjs.Blockchain.getBestBlockHash()
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.isString(result)
|
||||
assert.equal(result.length, 64, "Specific hash length")
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getBlockHeader", () => {
|
||||
it(`should GET block header for a single hash`, async () => {
|
||||
const hash =
|
||||
"000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf"
|
||||
|
||||
const result = await bchjs.Blockchain.getBlockHeader(hash)
|
||||
|
||||
assert.hasAllKeys(result, [
|
||||
"hash",
|
||||
"confirmations",
|
||||
"height",
|
||||
"version",
|
||||
"versionHex",
|
||||
"merkleroot",
|
||||
"time",
|
||||
"mediantime",
|
||||
"nonce",
|
||||
"bits",
|
||||
"difficulty",
|
||||
"chainwork",
|
||||
"previousblockhash",
|
||||
"nextblockhash",
|
||||
"nTx"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should GET block headers for an array of hashes`, async () => {
|
||||
const hash = [
|
||||
"000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf",
|
||||
"00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockchain.getBlockHeader(hash)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAllKeys(result[0], [
|
||||
"hash",
|
||||
"confirmations",
|
||||
"height",
|
||||
"version",
|
||||
"versionHex",
|
||||
"merkleroot",
|
||||
"time",
|
||||
"mediantime",
|
||||
"nonce",
|
||||
"bits",
|
||||
"difficulty",
|
||||
"chainwork",
|
||||
"previousblockhash",
|
||||
"nextblockhash",
|
||||
"nTx"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const hash = 12345
|
||||
|
||||
await bchjs.Blockchain.getBlockHeader(hash)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input hash must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) {
|
||||
data.push(
|
||||
"00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2"
|
||||
)
|
||||
}
|
||||
|
||||
const result = await bchjs.Blockchain.getBlockHeader(data)
|
||||
|
||||
// console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getMempoolEntry", () => {
|
||||
/*
|
||||
// To run this test, the txid must be unconfirmed.
|
||||
const txid =
|
||||
"defea04c38ee00cf73ad402984714ed22dc0dd99b2ae5cb50d791d94343ba79b"
|
||||
|
||||
it(`should GET single mempool entry`, async () => {
|
||||
const result = await bchjs.Blockchain.getMempoolEntry(txid)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"size",
|
||||
"fee",
|
||||
"modifiedfee",
|
||||
"time",
|
||||
"height",
|
||||
"startingpriority",
|
||||
"currentpriority",
|
||||
"descendantcount",
|
||||
"descendantsize",
|
||||
"descendantfees",
|
||||
"ancestorcount",
|
||||
"ancestorsize",
|
||||
"ancestorfees",
|
||||
"depends"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should get an array of mempool entries`, async () => {
|
||||
const result = await bchjs.Blockchain.getMempoolEntry([txid, txid])
|
||||
console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"size",
|
||||
"fee",
|
||||
"modifiedfee",
|
||||
"time",
|
||||
"height",
|
||||
"startingpriority",
|
||||
"currentpriority",
|
||||
"descendantcount",
|
||||
"descendantsize",
|
||||
"descendantfees",
|
||||
"ancestorcount",
|
||||
"ancestorsize",
|
||||
"ancestorfees",
|
||||
"depends"
|
||||
])
|
||||
})
|
||||
*/
|
||||
|
||||
it(`should throw an error if txid is not in mempool`, async () => {
|
||||
try {
|
||||
const txid =
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04"
|
||||
|
||||
await bchjs.Blockchain.getMempoolEntry(txid)
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: ${util.inspect(err)}`)
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, `Transaction not in mempool`)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const txid = 12345
|
||||
|
||||
await bchjs.Blockchain.getMempoolEntry(txid)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#getTxOutProof`, () => {
|
||||
it(`should get single tx out proof`, async () => {
|
||||
const txid =
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04"
|
||||
|
||||
const result = await bchjs.Blockchain.getTxOutProof(txid)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isString(result)
|
||||
})
|
||||
|
||||
it(`should get an array of tx out proofs`, async () => {
|
||||
const txid = [
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04",
|
||||
"fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockchain.getTxOutProof(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const txid = 12345
|
||||
|
||||
await bchjs.Blockchain.getTxOutProof(txid)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#verifyTxOutProof`, () => {
|
||||
const mockTxOutProof =
|
||||
"00000020ac86ce8f2bda235c0dc135d18f6a777c44b121e8f41db8a51ca65000000000000cd4de3c49337712f3a1092c47c3bf73ec2f9b1cfd289ee991ede0b6eab4df229d5b8c5dffff001d82ce005b0700000003ec55d9142eac2c1d2229e5af24898b2590c111b62e2787fa1998d3d713fd432fd557124ed758fa156a6cdc6d317d5575aec2b86dfb159c62ecb4743f28bef1cb52e7a32fbec31e367ec152fdb952f75ee75bd8575f97b394093dbb0e6c694ffc0135"
|
||||
|
||||
it(`should verify a single proof`, async () => {
|
||||
const result = await bchjs.Blockchain.verifyTxOutProof(mockTxOutProof)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
assert.equal(
|
||||
result[0],
|
||||
"fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752"
|
||||
)
|
||||
})
|
||||
|
||||
it(`should verify an array of proofs`, async () => {
|
||||
const proofs = [mockTxOutProof, mockTxOutProof]
|
||||
const result = await bchjs.Blockchain.verifyTxOutProof(proofs)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
assert.equal(
|
||||
result[0],
|
||||
"fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752"
|
||||
)
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const txid = 12345
|
||||
|
||||
await bchjs.Blockchain.verifyTxOutProof(txid)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(mockTxOutProof)
|
||||
|
||||
const result = await bchjs.Blockchain.verifyTxOutProof(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
Integration tests for bchjs control library.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
|
||||
describe(`#control`, () => {
|
||||
describe(`#getNetworkInfo`, () => {
|
||||
it("should get info on the full node", async () => {
|
||||
const result = await bchjs.Control.getNetworkInfo()
|
||||
console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "version")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,185 @@
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const sinon = require("sinon")
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
|
||||
describe(`#ElectrumX`, () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "utxos")
|
||||
assert.isArray(result.utxos)
|
||||
|
||||
assert.property(result.utxos[0], "height")
|
||||
assert.property(result.utxos[0], "tx_hash")
|
||||
assert.property(result.utxos[0], "tx_pos")
|
||||
assert.property(result.utxos[0], "value")
|
||||
})
|
||||
|
||||
it(`should POST utxo details for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2",
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "utxos")
|
||||
assert.isArray(result.utxos)
|
||||
|
||||
assert.property(result.utxos[0], "utxos")
|
||||
assert.isArray(result.utxos[0].utxos)
|
||||
assert.property(result.utxos[0], "address")
|
||||
|
||||
assert.property(result.utxos[0].utxos[0], "height")
|
||||
assert.property(result.utxos[0].utxos[0], "tx_hash")
|
||||
assert.property(result.utxos[0].utxos[0], "tx_pos")
|
||||
assert.property(result.utxos[0].utxos[0], "value")
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#balance`, () => {
|
||||
it(`should GET balance for a single address`, async () => {
|
||||
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "balance")
|
||||
assert.property(result.balance, "confirmed")
|
||||
assert.property(result.balance, "unconfirmed")
|
||||
})
|
||||
|
||||
it(`should POST request for balances for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2",
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "balances")
|
||||
assert.isArray(result.balances)
|
||||
|
||||
assert.property(result.balances[0], "address")
|
||||
assert.property(result.balances[0], "balance")
|
||||
assert.property(result.balances[0].balance, "confirmed")
|
||||
assert.property(result.balances[0].balance, "unconfirmed")
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#transactions`, () => {
|
||||
it(`should GET transaction history for a single address`, async () => {
|
||||
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "transactions")
|
||||
assert.isArray(result.transactions)
|
||||
assert.property(result.transactions[0], "height")
|
||||
assert.property(result.transactions[0], "tx_hash")
|
||||
})
|
||||
|
||||
it(`should POST request for transaction history for an array of addresses`, async () => {
|
||||
const addr = [
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2",
|
||||
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "transactions")
|
||||
assert.isArray(result.transactions)
|
||||
|
||||
assert.property(result.transactions[0], "address")
|
||||
assert.property(result.transactions[0], "transactions")
|
||||
assert.isArray(result.transactions[0].transactions)
|
||||
assert.property(result.transactions[0].transactions[0], "height")
|
||||
assert.property(result.transactions[0].transactions[0], "tx_hash")
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
tests for OpenBazaar library.
|
||||
*/
|
||||
|
||||
// Force testnet call to OB1 servers.
|
||||
process.env.NETWORK = "testnet"
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
|
||||
describe(`#OpenBazaar`, () => {
|
||||
describe(`#Balance`, () => {
|
||||
// it(`should GET balance for a single address`, async () => {
|
||||
// const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
//
|
||||
// const result = await bchjs.OpenBazaar.balance(addr)
|
||||
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
//
|
||||
// assert.hasAllKeys(result, [
|
||||
// "page",
|
||||
// "totalPages",
|
||||
// "itemsOnPage",
|
||||
// "addrStr",
|
||||
// "balance",
|
||||
// "totalReceived",
|
||||
// "totalSent",
|
||||
// "unconfirmedBalance",
|
||||
// "unconfirmedTxApperances",
|
||||
// "txApperances",
|
||||
// "transactions"
|
||||
// ])
|
||||
// assert.isArray(result.transactions)
|
||||
// })
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.OpenBazaar.balance(addr)
|
||||
// assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(err.message, `Input address must be a string`)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
// it(`should GET utxos for a single address`, async () => {
|
||||
// const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2"
|
||||
//
|
||||
// const result = await bchjs.OpenBazaar.utxo(addr)
|
||||
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
//
|
||||
// assert.isArray(result)
|
||||
// assert.hasAllKeys(result[0], [
|
||||
// "txid",
|
||||
// "vout",
|
||||
// "amount",
|
||||
// "height",
|
||||
// "confirmations",
|
||||
// "satoshis"
|
||||
// ])
|
||||
// })
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.OpenBazaar.utxo(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(err.message, `Input address must be a string`)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#tx`, () => {
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.OpenBazaar.tx(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(err.message, `Input txid must be a string`)
|
||||
}
|
||||
})
|
||||
|
||||
// it(`should GET transactions for a single address`, async () => {
|
||||
// const addr =
|
||||
// "ed4692f50a4553527dd26cd8674ca06a0ab2d366f3135ca3668310467ead3cbf"
|
||||
//
|
||||
// const result = await bchjs.OpenBazaar.tx(addr)
|
||||
// // console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
//
|
||||
// assert.hasAnyKeys(result, [
|
||||
// "txid",
|
||||
// "version",
|
||||
// "vin",
|
||||
// "vout",
|
||||
// "blockhash",
|
||||
// "blockheight",
|
||||
// "confirmations",
|
||||
// "blocktime",
|
||||
// "valueOut",
|
||||
// "valueIn",
|
||||
// "fees",
|
||||
// "hex"
|
||||
// ])
|
||||
// assert.isArray(result.vin)
|
||||
// assert.isArray(result.vout)
|
||||
// })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,334 @@
|
||||
/*
|
||||
Integration tests for the bchjs. Only covers calls made to
|
||||
rest.bitcoin.com.
|
||||
|
||||
TODO
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v3/` })
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe("#rawtransaction", () => {
|
||||
describe("#decodeRawTransaction", () => {
|
||||
it("should decode tx for a single hex", async () => {
|
||||
const hex =
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeRawTransaction(hex)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout"
|
||||
])
|
||||
assert.isArray(result.vin)
|
||||
assert.isArray(result.vout)
|
||||
})
|
||||
|
||||
it("should decode an array of tx hexes", async () => {
|
||||
const hexes = [
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000",
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
|
||||
]
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeRawTransaction(hexes)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout"
|
||||
])
|
||||
assert.isArray(result[0].vin)
|
||||
assert.isArray(result[0].vout)
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.RawTransactions.decodeRawTransaction(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings.`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) {
|
||||
data.push(
|
||||
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000"
|
||||
)
|
||||
}
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeRawTransaction(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getRawTransaction", () => {
|
||||
it("should decode a single txid, with concise output", async () => {
|
||||
const txid =
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04"
|
||||
const verbose = false
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isString(result)
|
||||
})
|
||||
|
||||
it("should decode a single txid, with verbose output", async () => {
|
||||
const txid =
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04"
|
||||
const verbose = true
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"hex",
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout",
|
||||
"blockhash",
|
||||
"confirmations",
|
||||
"time",
|
||||
"blocktime"
|
||||
])
|
||||
assert.isArray(result.vin)
|
||||
assert.isArray(result.vout)
|
||||
})
|
||||
|
||||
it("should decode an array of txids, with a concise output", async () => {
|
||||
const txid = [
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04",
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04"
|
||||
]
|
||||
const verbose = false
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isString(result[0])
|
||||
})
|
||||
|
||||
it("should decode an array of txids, with a verbose output", async () => {
|
||||
const txid = [
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04",
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04"
|
||||
]
|
||||
const verbose = true
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(
|
||||
txid,
|
||||
verbose
|
||||
)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"hex",
|
||||
"txid",
|
||||
"hash",
|
||||
"size",
|
||||
"version",
|
||||
"locktime",
|
||||
"vin",
|
||||
"vout",
|
||||
"blockhash",
|
||||
"confirmations",
|
||||
"time",
|
||||
"blocktime"
|
||||
])
|
||||
assert.isArray(result[0].vin)
|
||||
assert.isArray(result[0].vout)
|
||||
})
|
||||
|
||||
it(`should throw error on array size limit`, async () => {
|
||||
try {
|
||||
const dataMock =
|
||||
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04"
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(dataMock)
|
||||
|
||||
const result = await bchjs.RawTransactions.getRawTransaction(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#decodeScript", () => {
|
||||
it("should decode script for a single hex", async () => {
|
||||
const hex =
|
||||
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16"
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeScript(hex)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["asm", "type", "p2sh"])
|
||||
})
|
||||
|
||||
// CT 2/20/19 - Waiting for this PR to be merged complete the test:
|
||||
// https://github.com/Bitcoin-com/rest.bitcoin.com/pull/312
|
||||
/*
|
||||
it("should decode an array of tx hexes", async () => {
|
||||
const hexes = [
|
||||
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16",
|
||||
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16"
|
||||
]
|
||||
|
||||
const result = await bchjs.RawTransactions.decodeScript(hexes)
|
||||
console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
})
|
||||
*/
|
||||
/*
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.RawTransactions.decodeRawTransaction(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings.`
|
||||
)
|
||||
}
|
||||
})
|
||||
*/
|
||||
})
|
||||
|
||||
/*
|
||||
Testing sentRawTransaction isn't really possible with an integration test,
|
||||
as the endpoint really needs an e2e test to be properly tested. The tests
|
||||
below expect error messages returned from the server, but at least test
|
||||
that the server is responding on those endpoints, and responds consistently.
|
||||
*/
|
||||
describe("sendRawTransaction", () => {
|
||||
it("should send a single transaction hex", async () => {
|
||||
try {
|
||||
const hex =
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
|
||||
|
||||
await bchjs.RawTransactions.sendRawTransaction(hex)
|
||||
//console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: ${util.inspect(err)}`)
|
||||
|
||||
assert.hasAllKeys(err, ["error"])
|
||||
assert.include(err.error, "Missing inputs")
|
||||
}
|
||||
})
|
||||
|
||||
it("should send an array of tx hexes", async () => {
|
||||
try {
|
||||
const hexes = [
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000",
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
|
||||
]
|
||||
|
||||
const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
|
||||
console.log(`result ${JSON.stringify(result, null, 2)}`)
|
||||
} catch (err) {
|
||||
// console.log(`err: ${util.inspect(err)}`)
|
||||
|
||||
assert.hasAllKeys(err, ["error"])
|
||||
assert.include(err.error, "Missing inputs")
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.RawTransactions.sendRawTransaction(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input hex must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const dataMock =
|
||||
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000"
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(dataMock)
|
||||
|
||||
const result = await bchjs.RawTransactions.sendRawTransaction(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
Integration tests for the bchjs covering SLP tokens.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v3/` })
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 1
|
||||
}
|
||||
|
||||
describe(`#SLP`, () => {
|
||||
beforeEach(async () => {
|
||||
// Introduce a delay so that the BVT doesn't trip the rate limits.
|
||||
await sleep(1000)
|
||||
})
|
||||
|
||||
describe("#util", () => {
|
||||
it(`should get information on the Oasis token`, async () => {
|
||||
const tokenId = `a371e9934c7695d08a5eb7f31d3bceb4f3644860cc67520cda1e149423b9ec39`
|
||||
|
||||
const result = await bchjs.SLP.Utils.list(tokenId)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"decimals",
|
||||
"timestamp",
|
||||
"timestamp_unix",
|
||||
"versionType",
|
||||
"documentUri",
|
||||
"symbol",
|
||||
"name",
|
||||
"containsBaton",
|
||||
"id",
|
||||
"documentHash",
|
||||
"initialTokenQty",
|
||||
"blockCreated",
|
||||
"blockLastActiveSend",
|
||||
"blockLastActiveMint",
|
||||
"txnsSinceGenesis",
|
||||
"validAddress",
|
||||
"totalMinted",
|
||||
"totalBurned",
|
||||
"circulatingSupply",
|
||||
"mintingBatonStatus"
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("#decodeOpReturn", () => {
|
||||
it("should decode the OP_RETURN for a SEND txid", async () => {
|
||||
const txid =
|
||||
"ad28116e0818339342dddfc5f58ca8a5379ceb9679b4e4cbd72f4de905415ec1"
|
||||
|
||||
const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["amounts", "tokenType", "tokenId", "txType"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("#balancesForAddress", () => {
|
||||
it(`should throw an error if input is not a string or array of strings`, async () => {
|
||||
try {
|
||||
const address = 1234
|
||||
|
||||
await bchjs.SLP.Utils.balancesForAddress(address)
|
||||
|
||||
assert.equal(true, false, "Uh oh. Code path should not end here.")
|
||||
} catch (err) {
|
||||
//console.log(`Error: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should fetch all balances for address: simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9`, async () => {
|
||||
// Mock the call to rest.bitcoin.com
|
||||
if (process.env.TEST === "unit") {
|
||||
sandbox
|
||||
.stub(axios, "get")
|
||||
.resolves({ data: mockData.balancesForAddress })
|
||||
}
|
||||
|
||||
const balances = await bchjs.SLP.Utils.balancesForAddress(
|
||||
"slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9"
|
||||
)
|
||||
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
|
||||
|
||||
assert.isArray(balances)
|
||||
assert.hasAllKeys(balances[0], [
|
||||
"tokenId",
|
||||
"balanceString",
|
||||
"balance",
|
||||
"decimalCount",
|
||||
"slpAddress"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should fetch balances for multiple addresses`, async () => {
|
||||
const addresses = [
|
||||
"slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9",
|
||||
"slptest:qr5uy4h8ysyhwkp9s245scckdnc7teyjqc5ft2z43h"
|
||||
]
|
||||
|
||||
// Mock the call to rest.bitcoin.com
|
||||
if (process.env.TEST === "unit") {
|
||||
sandbox
|
||||
.stub(axios, "post")
|
||||
.resolves({ data: mockData.balancesForAddresses })
|
||||
}
|
||||
|
||||
const balances = await bchjs.SLP.Utils.balancesForAddress(addresses)
|
||||
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
|
||||
|
||||
assert.isArray(balances)
|
||||
assert.isArray(balances[0])
|
||||
assert.hasAllKeys(balances[0][0], [
|
||||
"tokenId",
|
||||
"balanceString",
|
||||
"balance",
|
||||
"decimalCount",
|
||||
"slpAddress"
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Promise-based sleep function
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms))
|
||||
}
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/bash
|
||||
|
||||
export RESTURL=https://free-test.fullstack.cash/v3/
|
||||
export NETWORK=testnet
|
||||
#export RESTURL=http://localhost:3000/v3/
|
||||
|
||||
cd test/integration/testnet/
|
||||
mocha --timeout 30000 blockchain.js control.js electrumx.js openbazaar.js rawtransaction.js slp.js util.js
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
Integration tests for the bchjs. Only covers calls made to
|
||||
rest.bitcoin.com.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
|
||||
const RESTURL = process.env.RESTURL
|
||||
? process.env.RESTURL
|
||||
: `https://tapi.fullstack.cash/v3/`
|
||||
// if (process.env.RESTURL) RESTURL = process.env.RESTURL
|
||||
|
||||
const BCHJS = require("../../../src/bch-js")
|
||||
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v3/` })
|
||||
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe(`#util`, () => {
|
||||
describe(`#validateAddress`, () => {
|
||||
it(`should return false for testnet addr on mainnet`, async () => {
|
||||
const address = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peu`
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["isvalid"])
|
||||
assert.equal(result.isvalid, false)
|
||||
})
|
||||
|
||||
it(`should return false for bad address`, async () => {
|
||||
const address = `bchtest:qqqk4y6lsl5da64sg53xezmplyu5kmpyz2ysaa5y`
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["isvalid"])
|
||||
assert.equal(result.isvalid, false)
|
||||
})
|
||||
|
||||
it(`should validate valid address`, async () => {
|
||||
const address = `bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y`
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"isvalid",
|
||||
"address",
|
||||
"scriptPubKey",
|
||||
//"ismine",
|
||||
//"iswatchonly",
|
||||
"isscript"
|
||||
])
|
||||
assert.equal(result.isvalid, true)
|
||||
})
|
||||
|
||||
it(`should validate an array of addresses`, async () => {
|
||||
const address = [
|
||||
`bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y`,
|
||||
`bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh`
|
||||
]
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"isvalid",
|
||||
"address",
|
||||
"scriptPubKey",
|
||||
//"ismine",
|
||||
//"iswatchonly",
|
||||
"isscript"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const address = 15432
|
||||
|
||||
await bchjs.Util.validateAddress(address)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings.`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const dataMock = `bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh`
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(dataMock)
|
||||
|
||||
const result = await bchjs.Util.validateAddress(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
Integration tests for the bchjs. Only covers calls made to
|
||||
rest.bitcoin.com.
|
||||
*/
|
||||
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
// Inspect utility used for debugging.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = {
|
||||
showHidden: true,
|
||||
colors: true,
|
||||
depth: 3
|
||||
}
|
||||
|
||||
describe(`#util`, () => {
|
||||
describe(`#validateAddress`, () => {
|
||||
it(`should return false for testnet addr on mainnet`, async () => {
|
||||
const address = `bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y`
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["isvalid"])
|
||||
assert.equal(result.isvalid, false)
|
||||
})
|
||||
|
||||
it(`should return false for bad address`, async () => {
|
||||
const address = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peu`
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAllKeys(result, ["isvalid"])
|
||||
assert.equal(result.isvalid, false)
|
||||
})
|
||||
|
||||
it(`should validate valid address`, async () => {
|
||||
const address = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z`
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"isvalid",
|
||||
"address",
|
||||
"scriptPubKey",
|
||||
//"ismine",
|
||||
//"iswatchonly",
|
||||
"isscript"
|
||||
])
|
||||
assert.equal(result.isvalid, true)
|
||||
})
|
||||
|
||||
it(`should validate an array of addresses`, async () => {
|
||||
const address = [
|
||||
`bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z`,
|
||||
`bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z`
|
||||
]
|
||||
|
||||
const result = await bchjs.Util.validateAddress(address)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"isvalid",
|
||||
"address",
|
||||
"scriptPubKey",
|
||||
//"ismine",
|
||||
//"iswatchonly",
|
||||
"isscript"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper single input`, async () => {
|
||||
try {
|
||||
const address = 15432
|
||||
|
||||
await bchjs.Util.validateAddress(address)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input must be a string or array of strings.`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const dataMock = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z`
|
||||
const data = []
|
||||
for (let i = 0; i < 25; i++) data.push(dataMock)
|
||||
|
||||
const result = await bchjs.Util.validateAddress(data)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,905 @@
|
||||
const fixtures = require("./fixtures/address.json")
|
||||
const assert = require("assert")
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
const Bitcoin = require("bitcoincashjs-lib")
|
||||
|
||||
function flatten(arrays) {
|
||||
return [].concat.apply([], arrays)
|
||||
}
|
||||
|
||||
const XPUBS = flatten([fixtures.mainnetXPub, fixtures.testnetXPub])
|
||||
|
||||
const LEGACY_ADDRESSES = flatten([
|
||||
fixtures.legacyMainnetP2PKH,
|
||||
fixtures.legacyMainnetP2SH,
|
||||
fixtures.legacyTestnetP2PKH
|
||||
])
|
||||
|
||||
const mainnet_xpubs = []
|
||||
fixtures.mainnetXPub.forEach((f, i) => {
|
||||
mainnet_xpubs.push(f.xpub)
|
||||
})
|
||||
const MAINNET_ADDRESSES = flatten([
|
||||
mainnet_xpubs,
|
||||
fixtures.legacyMainnetP2PKH,
|
||||
fixtures.legacyMainnetP2SH,
|
||||
fixtures.cashaddrMainnetP2PKH
|
||||
])
|
||||
|
||||
const testnet_xpubs = []
|
||||
fixtures.testnetXPub.forEach((f, i) => {
|
||||
testnet_xpubs.push(f.xpub)
|
||||
})
|
||||
const TESTNET_ADDRESSES = flatten([
|
||||
testnet_xpubs,
|
||||
fixtures.legacyTestnetP2PKH,
|
||||
fixtures.cashaddrTestnetP2PKH
|
||||
])
|
||||
|
||||
const CASHADDR_ADDRESSES = flatten([
|
||||
fixtures.cashaddrMainnetP2PKH,
|
||||
fixtures.cashaddrMainnetP2SH,
|
||||
fixtures.cashaddrTestnetP2PKH
|
||||
])
|
||||
|
||||
const CASHADDR_ADDRESSES_NO_PREFIX = CASHADDR_ADDRESSES.map(address => {
|
||||
const parts = address.split(":")
|
||||
return parts[1]
|
||||
})
|
||||
|
||||
const REGTEST_ADDRESSES = fixtures.cashaddrRegTestP2PKH
|
||||
|
||||
const REGTEST_ADDRESSES_NO_PREFIX = REGTEST_ADDRESSES.map(address => {
|
||||
const parts = address.split(":")
|
||||
return parts[1]
|
||||
})
|
||||
|
||||
const HASH160_HASHES = flatten([
|
||||
fixtures.hash160MainnetP2PKH,
|
||||
fixtures.hash160MainnetP2SH,
|
||||
fixtures.hash160TestnetP2PKH
|
||||
])
|
||||
|
||||
const P2PKH_ADDRESSES = flatten([
|
||||
fixtures.legacyMainnetP2PKH,
|
||||
fixtures.legacyTestnetP2PKH,
|
||||
fixtures.cashaddrMainnetP2PKH,
|
||||
fixtures.cashaddrTestnetP2PKH,
|
||||
fixtures.cashaddrRegTestP2PKH
|
||||
])
|
||||
|
||||
const P2SH_ADDRESSES = flatten([
|
||||
fixtures.legacyMainnetP2SH,
|
||||
fixtures.cashaddrMainnetP2SH
|
||||
])
|
||||
|
||||
describe("#addressConversion", () => {
|
||||
describe("#toLegacyAddress", () => {
|
||||
it("should translate legacy address format to itself correctly", () => {
|
||||
assert.deepEqual(
|
||||
LEGACY_ADDRESSES.map(address => bchjs.Address.toLegacyAddress(address)),
|
||||
LEGACY_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert cashaddr address to legacy base58Check", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES.map(address =>
|
||||
bchjs.Address.toLegacyAddress(address)
|
||||
),
|
||||
LEGACY_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert cashaddr regtest address to legacy base58Check", () => {
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES.map(address =>
|
||||
bchjs.Address.toLegacyAddress(address)
|
||||
),
|
||||
fixtures.legacyTestnetP2PKH
|
||||
)
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.toLegacyAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.toLegacyAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#toCashAddress", () => {
|
||||
it("should convert legacy base58Check address to cashaddr", () => {
|
||||
assert.deepEqual(
|
||||
LEGACY_ADDRESSES.map(address =>
|
||||
bchjs.Address.toCashAddress(address, true)
|
||||
),
|
||||
CASHADDR_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert legacy base58Check address to regtest cashaddr", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.legacyTestnetP2PKH.map(address =>
|
||||
bchjs.Address.toCashAddress(address, true, true)
|
||||
),
|
||||
REGTEST_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should translate cashaddr address format to itself correctly", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES.map(address =>
|
||||
bchjs.Address.toCashAddress(address, true)
|
||||
),
|
||||
CASHADDR_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should translate regtest cashaddr address format to itself correctly", () => {
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES.map(address =>
|
||||
bchjs.Address.toCashAddress(address, true, true)
|
||||
),
|
||||
REGTEST_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should translate no-prefix cashaddr address format to itself correctly", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.toCashAddress(address, true)
|
||||
),
|
||||
CASHADDR_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should translate no-prefix regtest cashaddr address format to itself correctly", () => {
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.toCashAddress(address, true, true)
|
||||
),
|
||||
REGTEST_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
it("should translate cashaddr address format to itself of no-prefix correctly", () => {
|
||||
CASHADDR_ADDRESSES.forEach(address => {
|
||||
const noPrefix = bchjs.Address.toCashAddress(address, false)
|
||||
assert.equal(address.split(":")[1], noPrefix)
|
||||
})
|
||||
})
|
||||
|
||||
it("should translate regtest cashaddr address format to itself of no-prefix correctly", () => {
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
const noPrefix = bchjs.Address.toCashAddress(address, false, true)
|
||||
assert.equal(address.split(":")[1], noPrefix)
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.BitcoinCash.Address.toCashAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.BitcoinCash.Address.toCashAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
describe("#toHash160", () => {
|
||||
it("should convert legacy base58check address to hash160", () => {
|
||||
assert.deepEqual(
|
||||
LEGACY_ADDRESSES.map(address => bchjs.Address.toHash160(address)),
|
||||
HASH160_HASHES
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert cashaddr address to hash160", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.toHash160(address)),
|
||||
HASH160_HASHES
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert regtest cashaddr address to hash160", () => {
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.toHash160(address)),
|
||||
fixtures.hash160TestnetP2PKH
|
||||
)
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.toHash160()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.toHash160("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
describe("#fromHash160", () => {
|
||||
it("should convert hash160 to mainnet P2PKH legacy base58check address", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.hash160MainnetP2PKH.map(hash160 =>
|
||||
bchjs.Address.hash160ToLegacy(hash160)
|
||||
),
|
||||
fixtures.legacyMainnetP2PKH
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert hash160 to mainnet P2SH legacy base58check address", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.hash160MainnetP2SH.map(hash160 =>
|
||||
bchjs.Address.hash160ToLegacy(
|
||||
hash160,
|
||||
Bitcoin.networks.bitcoin.scriptHash
|
||||
)
|
||||
),
|
||||
fixtures.legacyMainnetP2SH
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert hash160 to testnet P2PKH legacy base58check address", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.hash160TestnetP2PKH.map(hash160 =>
|
||||
bchjs.Address.hash160ToLegacy(
|
||||
hash160,
|
||||
Bitcoin.networks.testnet.pubKeyHash
|
||||
)
|
||||
),
|
||||
fixtures.legacyTestnetP2PKH
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert hash160 to mainnet P2PKH cash address", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.hash160MainnetP2PKH.map(hash160 =>
|
||||
bchjs.Address.hash160ToCash(hash160)
|
||||
),
|
||||
fixtures.cashaddrMainnetP2PKH
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert hash160 to mainnet P2SH cash address", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.hash160MainnetP2SH.map(hash160 =>
|
||||
bchjs.Address.hash160ToCash(
|
||||
hash160,
|
||||
Bitcoin.networks.bitcoin.scriptHash
|
||||
)
|
||||
),
|
||||
fixtures.cashaddrMainnetP2SH
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert hash160 to testnet P2PKH cash address", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.hash160TestnetP2PKH.map(hash160 =>
|
||||
bchjs.Address.hash160ToCash(
|
||||
hash160,
|
||||
Bitcoin.networks.testnet.pubKeyHash
|
||||
)
|
||||
),
|
||||
fixtures.cashaddrTestnetP2PKH
|
||||
)
|
||||
})
|
||||
|
||||
it("should convert hash160 to regtest P2PKH cash address", () => {
|
||||
assert.deepEqual(
|
||||
fixtures.hash160TestnetP2PKH.map(hash160 =>
|
||||
bchjs.Address.hash160ToCash(
|
||||
hash160,
|
||||
Bitcoin.networks.testnet.pubKeyHash,
|
||||
true
|
||||
)
|
||||
),
|
||||
REGTEST_ADDRESSES
|
||||
)
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.hash160ToLegacy()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.hash160ToLegacy("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.hash160ToCash()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.hash160ToCash("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("address format detection", () => {
|
||||
describe("#isLegacyAddress", () => {
|
||||
describe("is legacy", () => {
|
||||
LEGACY_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a legacy base58Check address`, () => {
|
||||
const isBase58Check = bchjs.Address.isLegacyAddress(address)
|
||||
assert.equal(isBase58Check, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
describe("is not legacy", () => {
|
||||
CASHADDR_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a legacy address`, () => {
|
||||
const isBase58Check = bchjs.Address.isLegacyAddress(address)
|
||||
assert.equal(isBase58Check, false)
|
||||
})
|
||||
})
|
||||
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a legacy address`, () => {
|
||||
const isBase58Check = bchjs.Address.isLegacyAddress(address)
|
||||
assert.equal(isBase58Check, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isLegacyAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isLegacyAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#isCashAddress", () => {
|
||||
describe("is cashaddr", () => {
|
||||
CASHADDR_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a cashaddr address`, () => {
|
||||
const isCashaddr = bchjs.Address.isCashAddress(address)
|
||||
assert.equal(isCashaddr, true)
|
||||
})
|
||||
})
|
||||
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a cashaddr address`, () => {
|
||||
const isCashaddr = bchjs.Address.isCashAddress(address)
|
||||
assert.equal(isCashaddr, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("is not cashaddr", () => {
|
||||
LEGACY_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a cashaddr address`, () => {
|
||||
const isCashaddr = bchjs.Address.isCashAddress(address)
|
||||
assert.equal(isCashaddr, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isCashAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isCashAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
describe("#isHash160", () => {
|
||||
describe("is hash160", () => {
|
||||
HASH160_HASHES.forEach(address => {
|
||||
it(`should detect ${address} is a hash160 hash`, () => {
|
||||
const isHash160 = bchjs.Address.isHash160(address)
|
||||
assert.equal(isHash160, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
describe("is not hash160", () => {
|
||||
LEGACY_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a hash160 hash`, () => {
|
||||
const isHash160 = bchjs.Address.isHash160(address)
|
||||
assert.equal(isHash160, false)
|
||||
})
|
||||
})
|
||||
|
||||
CASHADDR_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a hash160 hash`, () => {
|
||||
const isHash160 = bchjs.Address.isHash160(address)
|
||||
assert.equal(isHash160, false)
|
||||
})
|
||||
})
|
||||
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a legacy address`, () => {
|
||||
const isHash160 = bchjs.Address.isHash160(address)
|
||||
assert.equal(isHash160, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isHash160()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isHash160("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("network detection", () => {
|
||||
describe("#isMainnetAddress", () => {
|
||||
describe("is mainnet", () => {
|
||||
MAINNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a mainnet address`, () => {
|
||||
const isMainnet = bchjs.Address.isMainnetAddress(address)
|
||||
assert.equal(isMainnet, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("is not mainnet", () => {
|
||||
TESTNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a mainnet address`, () => {
|
||||
const isMainnet = bchjs.Address.isMainnetAddress(address)
|
||||
assert.equal(isMainnet, false)
|
||||
})
|
||||
})
|
||||
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a mainnet address`, () => {
|
||||
const isMainnet = bchjs.Address.isMainnetAddress(address)
|
||||
assert.equal(isMainnet, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isMainnetAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isMainnetAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#isTestnetAddress", () => {
|
||||
describe("is testnet", () => {
|
||||
TESTNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a testnet address`, () => {
|
||||
const isTestnet = bchjs.Address.isTestnetAddress(address)
|
||||
assert.equal(isTestnet, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("is not testnet", () => {
|
||||
MAINNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a testnet address`, () => {
|
||||
const isTestnet = bchjs.Address.isTestnetAddress(address)
|
||||
assert.equal(isTestnet, false)
|
||||
})
|
||||
})
|
||||
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a testnet address`, () => {
|
||||
const isTestnet = bchjs.Address.isTestnetAddress(address)
|
||||
assert.equal(isTestnet, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isTestnetAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isTestnetAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#isRegTestAddress", () => {
|
||||
describe("is testnet", () => {
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a regtest address`, () => {
|
||||
const isRegTest = bchjs.Address.isRegTestAddress(address)
|
||||
assert.equal(isRegTest, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("is not testnet", () => {
|
||||
MAINNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a regtest address`, () => {
|
||||
const isRegTest = bchjs.Address.isRegTestAddress(address)
|
||||
assert.equal(isRegTest, false)
|
||||
})
|
||||
})
|
||||
|
||||
TESTNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a regtest address`, () => {
|
||||
const isRegTest = bchjs.Address.isRegTestAddress(address)
|
||||
assert.equal(isRegTest, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isRegTestAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isRegTestAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("address type detection", () => {
|
||||
describe("#isP2PKHAddress", () => {
|
||||
describe("is P2PKH", () => {
|
||||
P2PKH_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a P2PKH address`, () => {
|
||||
const isP2PKH = bchjs.Address.isP2PKHAddress(address)
|
||||
assert.equal(isP2PKH, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("is not P2PKH", () => {
|
||||
P2SH_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a P2PKH address`, () => {
|
||||
const isP2PKH = bchjs.Address.isP2PKHAddress(address)
|
||||
assert.equal(isP2PKH, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isP2PKHAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isP2PKHAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#isP2SHAddress", () => {
|
||||
describe("is P2SH", () => {
|
||||
P2SH_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a P2SH address`, () => {
|
||||
const isP2SH = bchjs.Address.isP2SHAddress(address)
|
||||
assert.equal(isP2SH, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("is not P2SH", () => {
|
||||
P2PKH_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is not a P2SH address`, () => {
|
||||
const isP2SH = bchjs.Address.isP2SHAddress(address)
|
||||
assert.equal(isP2SH, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isP2SHAddress()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.isP2SHAddress("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("cashaddr prefix detection", () => {
|
||||
it("should return the same result for detectAddressFormat", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.detectAddressFormat(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address =>
|
||||
bchjs.Address.detectAddressFormat(address)
|
||||
)
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.detectAddressFormat(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address =>
|
||||
bchjs.Address.detectAddressFormat(address)
|
||||
)
|
||||
)
|
||||
})
|
||||
it("should return the same result for detectAddressNetwork", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.detectAddressNetwork(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address =>
|
||||
bchjs.Address.detectAddressNetwork(address)
|
||||
)
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.detectAddressNetwork(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address =>
|
||||
bchjs.Address.detectAddressNetwork(address)
|
||||
)
|
||||
)
|
||||
})
|
||||
it("should return the same result for detectAddressType", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.detectAddressType(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address =>
|
||||
bchjs.Address.detectAddressType(address)
|
||||
)
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.detectAddressType(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.detectAddressType(address))
|
||||
)
|
||||
})
|
||||
it("should return the same result for toLegacyAddress", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.toLegacyAddress(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.toLegacyAddress(address))
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.toLegacyAddress(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.toLegacyAddress(address))
|
||||
)
|
||||
})
|
||||
it("should return the same result for isLegacyAddress", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isLegacyAddress(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.isLegacyAddress(address))
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isLegacyAddress(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.isLegacyAddress(address))
|
||||
)
|
||||
})
|
||||
it("should return the same result for isCashAddress", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isCashAddress(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.isCashAddress(address))
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isCashAddress(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.isCashAddress(address))
|
||||
)
|
||||
})
|
||||
it("should return the same result for isMainnetAddress", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isMainnetAddress(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.isMainnetAddress(address))
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isMainnetAddress(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.isMainnetAddress(address))
|
||||
)
|
||||
})
|
||||
it("should return the same result for isTestnetAddress", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isTestnetAddress(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.isTestnetAddress(address))
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isTestnetAddress(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.isTestnetAddress(address))
|
||||
)
|
||||
})
|
||||
it("should return the same result for isP2PKHAddress", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isP2PKHAddress(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.isP2PKHAddress(address))
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isP2PKHAddress(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.isP2PKHAddress(address))
|
||||
)
|
||||
})
|
||||
it("should return the same result for isP2SHAddress", () => {
|
||||
assert.deepEqual(
|
||||
CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isP2SHAddress(address)
|
||||
),
|
||||
CASHADDR_ADDRESSES.map(address => bchjs.Address.isP2SHAddress(address))
|
||||
)
|
||||
assert.deepEqual(
|
||||
REGTEST_ADDRESSES_NO_PREFIX.map(address =>
|
||||
bchjs.Address.isP2SHAddress(address)
|
||||
),
|
||||
REGTEST_ADDRESSES.map(address => bchjs.Address.isP2SHAddress(address))
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#detectAddressFormat", () => {
|
||||
LEGACY_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a legacy base58Check address`, () => {
|
||||
const isBase58Check = bchjs.Address.detectAddressFormat(address)
|
||||
assert.equal(isBase58Check, "legacy")
|
||||
})
|
||||
})
|
||||
|
||||
CASHADDR_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a legacy cashaddr address`, () => {
|
||||
const isCashaddr = bchjs.Address.detectAddressFormat(address)
|
||||
assert.equal(isCashaddr, "cashaddr")
|
||||
})
|
||||
})
|
||||
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a legacy cashaddr address`, () => {
|
||||
const isCashaddr = bchjs.Address.detectAddressFormat(address)
|
||||
assert.equal(isCashaddr, "cashaddr")
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.detectAddressFormat()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.detectAddressFormat("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#detectAddressNetwork", () => {
|
||||
MAINNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a mainnet address`, () => {
|
||||
const isMainnet = bchjs.Address.detectAddressNetwork(address)
|
||||
assert.equal(isMainnet, "mainnet")
|
||||
})
|
||||
})
|
||||
|
||||
TESTNET_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a testnet address`, () => {
|
||||
const isTestnet = bchjs.Address.detectAddressNetwork(address)
|
||||
assert.equal(isTestnet, "testnet")
|
||||
})
|
||||
})
|
||||
|
||||
REGTEST_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a testnet address`, () => {
|
||||
const isTestnet = bchjs.Address.detectAddressNetwork(address)
|
||||
assert.equal(isTestnet, "regtest")
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.detectAddressNetwork()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.detectAddressNetwork("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#detectAddressType", () => {
|
||||
P2PKH_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a P2PKH address`, () => {
|
||||
const isP2PKH = bchjs.Address.detectAddressType(address)
|
||||
assert.equal(isP2PKH, "p2pkh")
|
||||
})
|
||||
})
|
||||
|
||||
P2SH_ADDRESSES.forEach(address => {
|
||||
it(`should detect ${address} is a P2SH address`, () => {
|
||||
const isP2SH = bchjs.Address.detectAddressType(address)
|
||||
assert.equal(isP2SH, "p2sh")
|
||||
})
|
||||
})
|
||||
|
||||
describe("errors", () => {
|
||||
it("should fail when called with an invalid address", () => {
|
||||
assert.throws(() => {
|
||||
bchjs.Address.detectAddressType()
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
assert.throws(() => {
|
||||
bchjs.Address.detectAddressType("some invalid address")
|
||||
}, bchjs.BitcoinCash.InvalidAddressError)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#fromXPub", () => {
|
||||
XPUBS.forEach((xpub, i) => {
|
||||
xpub.addresses.forEach((address, j) => {
|
||||
it(`generate public external change address ${j} for ${xpub.xpub}`, () => {
|
||||
assert.equal(bchjs.Address.fromXPub(xpub.xpub, `0/${j}`), address)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#fromOutputScript", () => {
|
||||
const script = bchjs.Script.encode([
|
||||
Buffer.from("BOX", "ascii"),
|
||||
bchjs.Script.opcodes.OP_CAT,
|
||||
Buffer.from("BITBOX", "ascii"),
|
||||
bchjs.Script.opcodes.OP_EQUAL
|
||||
])
|
||||
|
||||
// hash160 script buffer
|
||||
const p2sh_hash160 = bchjs.Crypto.hash160(script)
|
||||
|
||||
// encode hash160 as P2SH output
|
||||
const scriptPubKey = bchjs.Script.scriptHash.output.encode(p2sh_hash160)
|
||||
const p2shAddress = bchjs.Address.fromOutputScript(scriptPubKey)
|
||||
fixtures.p2shMainnet.forEach((address, i) => {
|
||||
it(`generate address from output script`, () => {
|
||||
assert.equal(p2shAddress, address)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
|
||||
// Used for debugging and iterrogating JS objects.
|
||||
const util = require("util")
|
||||
util.inspect.defaultOptions = { depth: 1 }
|
||||
|
||||
describe(`#BitboxShim`, () => {
|
||||
it("should create the shim library", () => {
|
||||
const BitboxShim = BCHJS.BitboxShim()
|
||||
const bitbox = new BitboxShim()
|
||||
|
||||
//console.log(`bitbox.Address: ${util.inspect(bitbox.Address)}`)
|
||||
|
||||
assert.hasAnyKeys(bitbox.Address, [
|
||||
// "details",
|
||||
// "utxo",
|
||||
// "unconfirmed",
|
||||
// "transactions",
|
||||
// "toLegacyAddress"
|
||||
"restURL"
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,314 @@
|
||||
const fixtures = require("./fixtures/bitcoincash.json")
|
||||
const assert = require("assert")
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
// TODO
|
||||
// 1. generate testnet p2sh
|
||||
// 2. generate cashaddr mainnet p2sh
|
||||
// 3. generate cashaddr testnet p2sh
|
||||
// 4. create bchjs fromBase58 method
|
||||
// * confirm xpub cannot generate WIF
|
||||
// * confirm xpriv can generate WIF
|
||||
// 5. create fromXPriv method w/ tests and docs
|
||||
// 1. mainnet
|
||||
// * confirm xpriv generates address
|
||||
// * confirm xpriv generates WIF
|
||||
// 2. testnet
|
||||
// * confirm xpriv generates address
|
||||
// * confirm xpriv generates WIF
|
||||
// 6. More error test cases.
|
||||
|
||||
describe("#BitcoinCash", () => {
|
||||
describe("price conversion", () => {
|
||||
describe("#toBitcoinCash", () => {
|
||||
fixtures.conversion.toBCH.satoshis.forEach(satoshi => {
|
||||
it(`should convert ${satoshi[0]} Satoshis to ${
|
||||
satoshi[1]
|
||||
} $BCH`, () => {
|
||||
assert.equal(bchjs.BitcoinCash.toBitcoinCash(satoshi[0]), satoshi[1])
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.conversion.toBCH.strings.forEach(satoshi => {
|
||||
it(`should convert "${satoshi[0]}" Satoshis as a string to ${
|
||||
satoshi[1]
|
||||
} $BCH`, () => {
|
||||
assert.equal(bchjs.BitcoinCash.toBitcoinCash(satoshi[0]), satoshi[1])
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.conversion.toBCH.not.forEach(bch => {
|
||||
it(`converts ${bch[0]} to Bitcoin Cash, not to ${
|
||||
bch[1]
|
||||
} Satoshi`, () => {
|
||||
assert.notEqual(bchjs.BitcoinCash.toBitcoinCash(bch[0]), bch[1])
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.conversion.toBCH.rounding.forEach(satoshi => {
|
||||
it(`rounding ${satoshi[0]} to ${satoshi[1]} $BCH`, () => {
|
||||
assert.equal(bchjs.BitcoinCash.toBitcoinCash(satoshi[0]), satoshi[1])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#toSatoshi", () => {
|
||||
fixtures.conversion.toSatoshi.bch.forEach(bch => {
|
||||
it(`should convert ${bch[0]} $BCH to ${bch[1]} Satoshis`, () => {
|
||||
assert.equal(bchjs.BitcoinCash.toSatoshi(bch[0]), bch[1])
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.conversion.toSatoshi.strings.forEach(bch => {
|
||||
it(`should convert "${bch[0]}" $BCH as a string to ${
|
||||
bch[1]
|
||||
} Satoshis`, () => {
|
||||
assert.equal(bchjs.BitcoinCash.toSatoshi(bch[0]), bch[1])
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.conversion.toSatoshi.not.forEach(satoshi => {
|
||||
it(`converts ${satoshi[0]} to Satoshi, not to ${
|
||||
satoshi[1]
|
||||
} Bitcoin Cash`, () => {
|
||||
assert.notEqual(bchjs.BitcoinCash.toSatoshi(satoshi[0]), satoshi[1])
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.conversion.toSatoshi.rounding.forEach(bch => {
|
||||
it(`rounding ${bch[0]} to ${bch[1]} Satoshi`, () => {
|
||||
assert.equal(bchjs.BitcoinCash.toSatoshi(bch[0]), bch[1])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#satsToBits", () => {
|
||||
fixtures.conversion.satsToBits.bch.forEach(bch => {
|
||||
it(`should convert ${bch[0]} BCH to ${bch[1]} bits`, () => {
|
||||
assert.equal(
|
||||
bchjs.BitcoinCash.satsToBits(bchjs.BitcoinCash.toSatoshi(bch[0])),
|
||||
bch[1]
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.conversion.satsToBits.strings.forEach(bch => {
|
||||
it(`should convert "${bch[0]}" BCH as a string to ${
|
||||
bch[1]
|
||||
} bits`, () => {
|
||||
assert.equal(
|
||||
bchjs.BitcoinCash.satsToBits(bchjs.BitcoinCash.toSatoshi(bch[0])),
|
||||
bch[1]
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
//
|
||||
// describe('#satsFromBits', () => {
|
||||
// fixtures.conversion.satsFromBits.bch.forEach((bch) => {
|
||||
// it(`should convert ${bch[1]} bits to ${bch[0]} satoshis`, () => {
|
||||
// assert.equal(bchjs.BitcoinCash.satsFromBits(bch[1]), bch[0]);
|
||||
// });
|
||||
// });
|
||||
//
|
||||
// fixtures.conversion.satsFromBits.strings.forEach((bch) => {
|
||||
// it(`should convert "${bch[1]}" bits as a string to ${bch[0]} satoshis`, () => {
|
||||
// assert.equal(bchjs.BitcoinCash.satsFromBits(bch[1]), bch[0]);
|
||||
// });
|
||||
// });
|
||||
// });
|
||||
})
|
||||
|
||||
describe("sign and verify messages", () => {
|
||||
describe("#signMessageWithPrivKey", () => {
|
||||
fixtures.signatures.sign.forEach(sign => {
|
||||
it(`should sign a message w/ ${sign.network} ${sign.privateKeyWIF}`, () => {
|
||||
const privateKeyWIF = sign.privateKeyWIF
|
||||
const message = sign.message
|
||||
const signature = bchjs.BitcoinCash.signMessageWithPrivKey(
|
||||
privateKeyWIF,
|
||||
message
|
||||
)
|
||||
assert.equal(signature, sign.signature)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#verifyMessage", () => {
|
||||
fixtures.signatures.verify.forEach(sign => {
|
||||
it(`should verify a valid signed message from ${sign.network} cashaddr address ${sign.address}`, () => {
|
||||
assert.equal(
|
||||
bchjs.BitcoinCash.verifyMessage(
|
||||
sign.address,
|
||||
sign.signature,
|
||||
sign.message
|
||||
),
|
||||
true
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.signatures.verify.forEach(sign => {
|
||||
const legacyAddress = bchjs.Address.toLegacyAddress(sign.address)
|
||||
it(`should verify a valid signed message from ${sign.network} legacy address ${legacyAddress}`, () => {
|
||||
assert.equal(
|
||||
bchjs.BitcoinCash.verifyMessage(
|
||||
legacyAddress,
|
||||
sign.signature,
|
||||
sign.message
|
||||
),
|
||||
true
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.signatures.verify.forEach(sign => {
|
||||
const legacyAddress = bchjs.Address.toLegacyAddress(sign.address)
|
||||
it(`should not verify an invalid signed message from ${sign.network} cashaddr address ${sign.address}`, () => {
|
||||
assert.equal(
|
||||
bchjs.BitcoinCash.verifyMessage(
|
||||
sign.address,
|
||||
sign.signature,
|
||||
"nope"
|
||||
),
|
||||
false
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("encode and decode to base58Check", () => {
|
||||
describe("#encodeBase58Check", () => {
|
||||
fixtures.encodeBase58Check.forEach((base58Check, i) => {
|
||||
it(`encode ${base58Check.hex} as base58Check ${base58Check.base58Check}`, () => {
|
||||
assert.equal(
|
||||
bchjs.BitcoinCash.encodeBase58Check(base58Check.hex),
|
||||
base58Check.base58Check
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#decodeBase58Check", () => {
|
||||
fixtures.encodeBase58Check.forEach((base58Check, i) => {
|
||||
it(`decode ${base58Check.base58Check} as ${base58Check.hex}`, () => {
|
||||
assert.equal(
|
||||
bchjs.BitcoinCash.decodeBase58Check(base58Check.base58Check),
|
||||
base58Check.hex
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("encode and decode BIP21 urls", () => {
|
||||
describe("#encodeBIP21", () => {
|
||||
fixtures.bip21.valid.forEach((bip21, i) => {
|
||||
it(`encode ${bip21.address} as url`, () => {
|
||||
const url = bchjs.BitcoinCash.encodeBIP21(
|
||||
bip21.address,
|
||||
bip21.options
|
||||
)
|
||||
assert.equal(url, bip21.url)
|
||||
})
|
||||
})
|
||||
fixtures.bip21.valid_regtest.forEach((bip21, i) => {
|
||||
it(`encode ${bip21.address} as url`, () => {
|
||||
const url = bchjs.BitcoinCash.encodeBIP21(
|
||||
bip21.address,
|
||||
bip21.options,
|
||||
true
|
||||
)
|
||||
assert.equal(url, bip21.url)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#decodeBIP21", () => {
|
||||
fixtures.bip21.valid.forEach((bip21, i) => {
|
||||
it(`decodes ${bip21.url}`, () => {
|
||||
const decoded = bchjs.BitcoinCash.decodeBIP21(bip21.url)
|
||||
assert.equal(decoded.options.amount, bip21.options.amount)
|
||||
assert.equal(decoded.options.label, bip21.options.label)
|
||||
assert.equal(
|
||||
bchjs.Address.toCashAddress(decoded.address),
|
||||
bchjs.Address.toCashAddress(bip21.address)
|
||||
)
|
||||
})
|
||||
})
|
||||
// fixtures.bip21.valid_regtest.forEach((bip21, i) => {
|
||||
// it(`decodes ${bip21.url}`, () => {
|
||||
// const decoded = bchjs.BitcoinCash.decodeBIP21(bip21.url)
|
||||
// assert.equal(decoded.options.amount, bip21.options.amount)
|
||||
// assert.equal(decoded.options.label, bip21.options.label)
|
||||
// assert.equal(
|
||||
// bchjs.Address.toCashAddress(decoded.address, true, true),
|
||||
// bchjs.Address.toCashAddress(bip21.address, true, true)
|
||||
// )
|
||||
// })
|
||||
// })
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getByteCount", () => {
|
||||
fixtures.getByteCount.forEach(fixture => {
|
||||
it(`get byte count`, () => {
|
||||
const byteCount = bchjs.BitcoinCash.getByteCount(
|
||||
fixture.inputs,
|
||||
fixture.outputs
|
||||
)
|
||||
assert.equal(byteCount, fixture.byteCount)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#bip38", () => {
|
||||
describe("#encryptBIP38", () => {
|
||||
fixtures.bip38.encrypt.mainnet.forEach(fixture => {
|
||||
it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on mainnet`, () => {
|
||||
const encryptedKey = bchjs.BitcoinCash.encryptBIP38(
|
||||
fixture.wif,
|
||||
fixture.password
|
||||
)
|
||||
assert.equal(encryptedKey, fixture.encryptedKey)
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.bip38.encrypt.testnet.forEach(fixture => {
|
||||
it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on testnet`, () => {
|
||||
const encryptedKey = bchjs.BitcoinCash.encryptBIP38(
|
||||
fixture.wif,
|
||||
fixture.password
|
||||
)
|
||||
assert.equal(encryptedKey, fixture.encryptedKey)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#decryptBIP38", () => {
|
||||
fixtures.bip38.decrypt.mainnet.forEach(fixture => {
|
||||
it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on mainnet`, () => {
|
||||
const wif = bchjs.BitcoinCash.decryptBIP38(
|
||||
fixture.encryptedKey,
|
||||
fixture.password,
|
||||
"mainnet"
|
||||
)
|
||||
assert.equal(wif, fixture.wif)
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.bip38.decrypt.testnet.forEach(fixture => {
|
||||
it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on testnet`, () => {
|
||||
const wif = bchjs.BitcoinCash.decryptBIP38(
|
||||
fixture.encryptedKey,
|
||||
fixture.password,
|
||||
"testnet"
|
||||
)
|
||||
assert.equal(wif, fixture.wif)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,275 @@
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
const axios = require("axios")
|
||||
const sinon = require("sinon")
|
||||
|
||||
const mockData = require("./fixtures/blockbook-mock")
|
||||
|
||||
describe(`#Blockbook`, () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
describe(`#Balance`, () => {
|
||||
it(`should GET balance for a single address`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "get").resolves({ data: mockData.balance })
|
||||
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.hasAnyKeys(result, [
|
||||
"page",
|
||||
"totalPages",
|
||||
"itemsOnPage",
|
||||
"address",
|
||||
"balance",
|
||||
"totalReceived",
|
||||
"totalSent",
|
||||
"unconfirmedBalance",
|
||||
"unconfirmedTxs",
|
||||
"txs",
|
||||
"txids"
|
||||
])
|
||||
assert.isArray(result.txids)
|
||||
})
|
||||
|
||||
it(`should POST request balances for an array of addresses`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox
|
||||
.stub(axios, "post")
|
||||
.resolves({ data: [mockData.balance, mockData.balance] })
|
||||
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
//console.log(`result: ${util.inspect(result)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"page",
|
||||
"totalPages",
|
||||
"itemsOnPage",
|
||||
"address",
|
||||
"balance",
|
||||
"totalReceived",
|
||||
"totalSent",
|
||||
"unconfirmedBalance",
|
||||
"unconfirmedTxs",
|
||||
"txs",
|
||||
"txids"
|
||||
])
|
||||
assert.isArray(result[0].txids)
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
// Stub the network call.
|
||||
sandbox
|
||||
.stub(axios, "post")
|
||||
.throws(`Input address must be a string or array of strings`)
|
||||
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Blockbook.balance(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
/*
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "post").throws(`Array too large`)
|
||||
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
|
||||
|
||||
const result = await bchjs.Blockbook.balance(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
*/
|
||||
})
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "get").resolves({ data: mockData.utxo })
|
||||
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"value",
|
||||
"height",
|
||||
"confirmations"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should POST utxo details for an array of addresses`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "post").resolves({ data: mockData.utxos })
|
||||
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.isArray(result[0])
|
||||
assert.hasAnyKeys(result[0][0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"value",
|
||||
"height",
|
||||
"confirmations"
|
||||
])
|
||||
})
|
||||
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
// Stub the network call.
|
||||
sandbox
|
||||
.stub(axios, "post")
|
||||
.throws(`Input address must be a string or array of strings`)
|
||||
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Blockbook.utxo(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
//console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
/*
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
*/
|
||||
})
|
||||
|
||||
describe(`#tx`, () => {
|
||||
it(`should GET tx details for a single txid`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "get").resolves({ data: mockData.utxo })
|
||||
|
||||
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.isArray(result)
|
||||
assert.hasAnyKeys(result[0], [
|
||||
"txid",
|
||||
"vout",
|
||||
"value",
|
||||
"height",
|
||||
"confirmations"
|
||||
])
|
||||
})
|
||||
|
||||
// it(`should POST utxo details for an array of addresses`, async () => {
|
||||
// // Stub the network call.
|
||||
// sandbox.stub(axios, "post").resolves({ data: mockData.utxos })
|
||||
//
|
||||
// const addr = [
|
||||
// "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
// "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
// ]
|
||||
//
|
||||
// const result = await bchjs.Blockbook.utxo(addr)
|
||||
// //console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
//
|
||||
// assert.isArray(result)
|
||||
// assert.isArray(result[0])
|
||||
// assert.hasAnyKeys(result[0][0], [
|
||||
// "txid",
|
||||
// "vout",
|
||||
// "value",
|
||||
// "height",
|
||||
// "confirmations"
|
||||
// ])
|
||||
// })
|
||||
|
||||
// it(`should throw an error for improper input`, async () => {
|
||||
// try {
|
||||
// // Stub the network call.
|
||||
// sandbox
|
||||
// .stub(axios, "post")
|
||||
// .throws(`Input address must be a string or array of strings`)
|
||||
//
|
||||
// const addr = 12345
|
||||
//
|
||||
// await bchjs.Blockbook.utxo(addr)
|
||||
// assert.equal(true, false, "Unexpected result!")
|
||||
// } catch (err) {
|
||||
// //console.log(`err: `, err)
|
||||
// assert.include(
|
||||
// err.message,
|
||||
// `Input address must be a string or array of strings`
|
||||
// )
|
||||
// }
|
||||
// })
|
||||
|
||||
/*
|
||||
it(`should throw error on array size rate limit`, async () => {
|
||||
try {
|
||||
const addr = []
|
||||
for (let i = 0; i < 25; i++)
|
||||
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
|
||||
|
||||
const result = await bchjs.Blockbook.utxo(addr)
|
||||
|
||||
console.log(`result: ${util.inspect(result)}`)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
assert.hasAnyKeys(err, ["error"])
|
||||
assert.include(err.error, "Array too large")
|
||||
}
|
||||
})
|
||||
*/
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,494 @@
|
||||
const assert = require("assert")
|
||||
const assert2 = require("chai").assert
|
||||
const axios = require("axios")
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
const sinon = require("sinon")
|
||||
|
||||
const mockData = require("./fixtures/blockchain-mock")
|
||||
|
||||
describe("#Blockchain", () => {
|
||||
describe("#getBestBlockHash", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
it("should get best block hash", done => {
|
||||
const resolved = new Promise(r =>
|
||||
r({
|
||||
data:
|
||||
"0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d"
|
||||
})
|
||||
)
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getBestBlockHash()
|
||||
.then(result => {
|
||||
const hash =
|
||||
"0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d"
|
||||
assert.equal(hash, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getBlock", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
hash: "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09",
|
||||
confirmations: 526807,
|
||||
size: 216,
|
||||
height: 1000,
|
||||
version: 1,
|
||||
versionHex: "00000001",
|
||||
merkleroot:
|
||||
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33",
|
||||
tx: ["fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33"],
|
||||
time: 1232346882,
|
||||
mediantime: 1232344831,
|
||||
nonce: 2595206198,
|
||||
bits: "1d00ffff",
|
||||
difficulty: 1,
|
||||
chainwork:
|
||||
"000000000000000000000000000000000000000000000000000003e903e903e9",
|
||||
previousblockhash:
|
||||
"0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d",
|
||||
nextblockhash:
|
||||
"00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6"
|
||||
}
|
||||
|
||||
it("should get block by hash", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getBlock(
|
||||
"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"
|
||||
)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getBlockchainInfo", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
chain: "main",
|
||||
blocks: 527810,
|
||||
headers: 527810,
|
||||
bestblockhash:
|
||||
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0",
|
||||
difficulty: 576023394804.6666,
|
||||
mediantime: 1524878499,
|
||||
verificationprogress: 0.9999990106793685,
|
||||
chainwork:
|
||||
"00000000000000000000000000000000000000000096da5b040913fa09249b4e",
|
||||
pruned: false,
|
||||
softforks: [
|
||||
{ id: "bip34", version: 2, reject: [Object] },
|
||||
{ id: "bip66", version: 3, reject: [Object] },
|
||||
{ id: "bip65", version: 4, reject: [Object] }
|
||||
],
|
||||
bip9_softforks: {
|
||||
csv: {
|
||||
status: "active",
|
||||
startTime: 1462060800,
|
||||
timeout: 1493596800,
|
||||
since: 419328
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it("should get blockchain info", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getBlockchainInfo()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getBlockCount", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = 527810
|
||||
|
||||
it("should get block count", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getBlockCount()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getBlockHash", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data =
|
||||
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0"
|
||||
|
||||
it("should get block hash by height", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getBlockHash(527810)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getBlockHeader", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
hash: "000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0",
|
||||
confirmations: 1,
|
||||
height: 527810,
|
||||
version: 536870912,
|
||||
versionHex: "20000000",
|
||||
merkleroot:
|
||||
"9298432bbebe4638456aa19cb7ef91639da87668a285d88d0ecd6080424d223b",
|
||||
time: 1524881438,
|
||||
mediantime: 1524878499,
|
||||
nonce: 3326843941,
|
||||
bits: "1801e8a5",
|
||||
difficulty: 576023394804.6666,
|
||||
chainwork:
|
||||
"00000000000000000000000000000000000000000096da5b040913fa09249b4e",
|
||||
previousblockhash:
|
||||
"000000000000000000b33251708bc7a7b4540e61880d8c376e8e2db6a19a4789"
|
||||
}
|
||||
|
||||
it("should get block header by hash", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getBlockHeader(
|
||||
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0",
|
||||
true
|
||||
)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getDifficulty", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = "577528469277.1339"
|
||||
|
||||
it("should get difficulty", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getDifficulty()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getMempoolAncestors", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = "Transaction not in mempool"
|
||||
|
||||
it("should get mempool ancestors", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getMempoolAncestors(
|
||||
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88",
|
||||
true
|
||||
)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getMempoolDescendants", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
result: "Transaction not in mempool"
|
||||
}
|
||||
|
||||
it("should get mempool descendants", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getMempoolDescendants(
|
||||
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88",
|
||||
true
|
||||
)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getMempoolEntry", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
result: "Transaction not in mempool"
|
||||
}
|
||||
|
||||
it("should get mempool entry", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getMempoolEntry(
|
||||
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88"
|
||||
)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getMempoolInfo", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
result: {
|
||||
size: 317,
|
||||
bytes: 208583,
|
||||
usage: 554944,
|
||||
maxmempool: 300000000,
|
||||
mempoolminfee: 0
|
||||
}
|
||||
}
|
||||
|
||||
it("should get mempool info", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getMempoolInfo()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getRawMempool", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
result: {
|
||||
transactions: [
|
||||
{
|
||||
txid:
|
||||
"ab36d68dd0a618592fe34e4a898e8beeeb4049133547dbb16f9338384084af96",
|
||||
size: 191,
|
||||
fee: 0.00047703,
|
||||
modifiedfee: 0.00047703,
|
||||
time: 1524883317,
|
||||
height: 527811,
|
||||
startingpriority: 5287822727.272727,
|
||||
currentpriority: 5287822727.272727,
|
||||
descendantcount: 1,
|
||||
descendantsize: 191,
|
||||
descendantfees: 47703,
|
||||
ancestorcount: 1,
|
||||
ancestorsize: 191,
|
||||
ancestorfees: 47703,
|
||||
depends: []
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
it("should get mempool info", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.getRawMempool()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getTxOut", () => {
|
||||
// TODO finish this test
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
// const data = {
|
||||
// result: {}
|
||||
// }
|
||||
|
||||
it("should throw an error for improper txid.", async () => {
|
||||
try {
|
||||
await bchjs.Blockchain.getTxOut("badtxid")
|
||||
} catch (err) {
|
||||
assert2.include(err.message, "txid needs to be a proper transaction ID")
|
||||
}
|
||||
})
|
||||
|
||||
it("should throw an error if no vout value is provided.", async () => {
|
||||
try {
|
||||
await bchjs.Blockchain.getTxOut(
|
||||
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88"
|
||||
)
|
||||
} catch (err) {
|
||||
assert2.include(err.message, "n must be an integer")
|
||||
}
|
||||
})
|
||||
|
||||
it("should throw an error if include_mempool is not a boolean", async () => {
|
||||
try {
|
||||
await bchjs.Blockchain.getTxOut(
|
||||
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88",
|
||||
0,
|
||||
"bad value"
|
||||
)
|
||||
} catch (err) {
|
||||
assert2.include(
|
||||
err.message,
|
||||
"include_mempool input must be of type boolean"
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it("should get information on an unspent tx", async () => {
|
||||
sandbox.stub(axios, "post").resolves({ data: mockData.txOutUnspent })
|
||||
|
||||
const result = await bchjs.Blockchain.getTxOut(
|
||||
"62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8",
|
||||
0,
|
||||
true
|
||||
)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert2.hasAllKeys(result, [
|
||||
"bestblock",
|
||||
"confirmations",
|
||||
"value",
|
||||
"scriptPubKey",
|
||||
"coinbase"
|
||||
])
|
||||
})
|
||||
|
||||
it("should get information on a spent tx", async () => {
|
||||
sandbox.stub(axios, "post").resolves({ data: null })
|
||||
|
||||
const result = await bchjs.Blockchain.getTxOut(
|
||||
"87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871",
|
||||
0,
|
||||
true
|
||||
)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert2.equal(result, null)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#preciousBlock", () => {
|
||||
// TODO finish this test
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = {
|
||||
result: {}
|
||||
}
|
||||
|
||||
it("should get TODO", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.preciousBlock()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#pruneBlockchain", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = "Cannot prune blocks because node is not in prune mode."
|
||||
|
||||
it("should prune blockchain", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "post").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.pruneBlockchain(507)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#verifyChain", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = true
|
||||
|
||||
it("should verify blockchain", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.verifyChain(3, 6)
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#verifyTxOutProof", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
const data = "proof must be hexadecimal string (not '')"
|
||||
|
||||
it("should verify utxo proof", done => {
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Blockchain.verifyTxOutProof("3")
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
const assert = require("assert")
|
||||
const axios = require("axios")
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
const sinon = require("sinon")
|
||||
|
||||
describe("#Control", () => {
|
||||
describe("#getNetworkInfo", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
it("should get info", done => {
|
||||
const data = {
|
||||
version: 170000,
|
||||
protocolversion: 70015,
|
||||
blocks: 527813,
|
||||
timeoffset: 0,
|
||||
connections: 21,
|
||||
proxy: "",
|
||||
difficulty: 581086703759.5878,
|
||||
testnet: false,
|
||||
paytxfee: 0,
|
||||
relayfee: 0.00001,
|
||||
errors: ""
|
||||
}
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Control.getNetworkInfo()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
|
||||
describe("#getMemoryInfo", () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
it("should get memory info", done => {
|
||||
const data = {
|
||||
locked: {
|
||||
used: 0,
|
||||
free: 65536,
|
||||
total: 65536,
|
||||
locked: 65536,
|
||||
chunks_used: 0,
|
||||
chunks_free: 1
|
||||
}
|
||||
}
|
||||
const resolved = new Promise(r => r({ data: data }))
|
||||
sandbox.stub(axios, "get").returns(resolved)
|
||||
|
||||
bchjs.Control.getMemoryInfo()
|
||||
.then(result => {
|
||||
assert.deepEqual(data, result)
|
||||
})
|
||||
.then(done, done)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
const fixtures = require("./fixtures/crypto.json")
|
||||
const assert = require("assert")
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
const Buffer = require("safe-buffer").Buffer
|
||||
|
||||
describe("#Crypto", () => {
|
||||
describe("#sha256", () => {
|
||||
fixtures.sha256.forEach(fixture => {
|
||||
it(`should create SHA256Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const sha256Hash = bchjs.Crypto.sha256(data).toString("hex")
|
||||
assert.equal(sha256Hash, fixture.hash)
|
||||
})
|
||||
|
||||
it(`should create 64 character SHA256Hash hex encoded`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const sha256Hash = bchjs.Crypto.sha256(data).toString("hex")
|
||||
assert.equal(sha256Hash.length, 64)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#ripemd160", () => {
|
||||
fixtures.ripemd160.forEach(fixture => {
|
||||
it(`should create RIPEMD160Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const ripemd160 = bchjs.Crypto.ripemd160(data).toString("hex")
|
||||
assert.equal(ripemd160, fixture.hash)
|
||||
})
|
||||
|
||||
it(`should create 64 character RIPEMD160Hash hex encoded`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const ripemd160 = bchjs.Crypto.ripemd160(data).toString("hex")
|
||||
assert.equal(ripemd160.length, 40)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#hash256", () => {
|
||||
fixtures.hash256.forEach(fixture => {
|
||||
it(`should create double SHA256 Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const hash256 = bchjs.Crypto.hash256(data).toString("hex")
|
||||
assert.equal(hash256, fixture.hash)
|
||||
})
|
||||
|
||||
it(`should create 64 character SHA256 Hash hex encoded`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const hash256 = bchjs.Crypto.hash256(data).toString("hex")
|
||||
assert.equal(hash256.length, 64)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#hash160", () => {
|
||||
fixtures.hash160.forEach(fixture => {
|
||||
it(`should create RIPEMD160(SHA256()) hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const hash160 = bchjs.Crypto.hash160(data).toString("hex")
|
||||
assert.equal(hash160, fixture.hash)
|
||||
})
|
||||
|
||||
it(`should create 64 character SHA256Hash hex encoded`, () => {
|
||||
const data = Buffer.from(fixture.hex, "hex")
|
||||
const hash160 = bchjs.Crypto.hash160(data).toString("hex")
|
||||
assert.equal(hash160.length, 40)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#randomBytes", () => {
|
||||
for (let i = 0; i < 6; i++) {
|
||||
it("should return 16 bytes of entropy hex encoded", () => {
|
||||
const entropy = bchjs.Crypto.randomBytes(16)
|
||||
assert.equal(Buffer.byteLength(entropy), 16)
|
||||
})
|
||||
|
||||
it("should return 20 bytes of entropy hex encoded", () => {
|
||||
const entropy = bchjs.Crypto.randomBytes(20)
|
||||
assert.equal(Buffer.byteLength(entropy), 20)
|
||||
})
|
||||
|
||||
it("should return 24 bytes of entropy hex encoded", () => {
|
||||
const entropy = bchjs.Crypto.randomBytes(24)
|
||||
assert.equal(Buffer.byteLength(entropy), 24)
|
||||
})
|
||||
|
||||
it("should return 28 bytes of entropy hex encoded", () => {
|
||||
const entropy = bchjs.Crypto.randomBytes(28)
|
||||
assert.equal(Buffer.byteLength(entropy), 28)
|
||||
})
|
||||
|
||||
it("should return 32 bytes of entropy hex encoded", () => {
|
||||
const entropy = bchjs.Crypto.randomBytes(32)
|
||||
assert.equal(Buffer.byteLength(entropy), 32)
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
const assert = require("assert")
|
||||
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
const Buffer = require("safe-buffer").Buffer
|
||||
|
||||
const fixtures = require("./fixtures/ecpair.json")
|
||||
|
||||
describe("#ECPair", () => {
|
||||
describe("#fromWIF", () => {
|
||||
fixtures.fromWIF.forEach(fixture => {
|
||||
it(`should create ECPair from WIF ${fixture.privateKeyWIF}`, () => {
|
||||
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
assert.equal(typeof ecpair, "object")
|
||||
})
|
||||
|
||||
it(`should get ${fixture.legacy} legacy address`, () => {
|
||||
const legacy = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
assert.equal(bchjs.HDNode.toLegacyAddress(legacy), fixture.legacy)
|
||||
})
|
||||
|
||||
it(`should get ${fixture.cashAddr} cash address`, () => {
|
||||
const cashAddr = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
assert.equal(bchjs.HDNode.toCashAddress(cashAddr), fixture.cashAddr)
|
||||
})
|
||||
|
||||
it(`should get ${fixture.regtestAddr} cash address`, () => {
|
||||
const cashAddr = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
assert.equal(
|
||||
bchjs.HDNode.toCashAddress(cashAddr, true),
|
||||
fixture.regtestAddr
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#toWIF", () => {
|
||||
fixtures.toWIF.forEach(fixture => {
|
||||
it(`should get WIF ${fixture.privateKeyWIF} from ECPair`, () => {
|
||||
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
const wif = bchjs.ECPair.toWIF(ecpair)
|
||||
assert.equal(wif, fixture.privateKeyWIF)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#fromPublicKey", () => {
|
||||
fixtures.fromPublicKey.forEach(fixture => {
|
||||
it(`should create ECPair from public key buffer`, () => {
|
||||
const ecpair = bchjs.ECPair.fromPublicKey(
|
||||
Buffer.from(fixture.pubkeyHex, "hex")
|
||||
)
|
||||
assert.equal(typeof ecpair, "object")
|
||||
})
|
||||
|
||||
it(`should get ${fixture.legacy} legacy address`, () => {
|
||||
const ecpair = bchjs.ECPair.fromPublicKey(
|
||||
Buffer.from(fixture.pubkeyHex, "hex")
|
||||
)
|
||||
assert.equal(bchjs.HDNode.toLegacyAddress(ecpair), fixture.legacy)
|
||||
})
|
||||
|
||||
it(`should get ${fixture.cashAddr} cash address`, () => {
|
||||
const ecpair = bchjs.ECPair.fromPublicKey(
|
||||
Buffer.from(fixture.pubkeyHex, "hex")
|
||||
)
|
||||
assert.equal(bchjs.HDNode.toCashAddress(ecpair), fixture.cashAddr)
|
||||
})
|
||||
|
||||
it(`should get ${fixture.regtestAddr} cash address`, () => {
|
||||
const ecpair = bchjs.ECPair.fromPublicKey(
|
||||
Buffer.from(fixture.pubkeyHex, "hex")
|
||||
)
|
||||
assert.equal(
|
||||
bchjs.HDNode.toCashAddress(ecpair, true),
|
||||
fixture.regtestAddr
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#toPublicKey", () => {
|
||||
fixtures.toPublicKey.forEach(fixture => {
|
||||
it(`should create a public key buffer from an ECPair`, () => {
|
||||
const ecpair = bchjs.ECPair.fromPublicKey(
|
||||
Buffer.from(fixture.pubkeyHex, "hex")
|
||||
)
|
||||
const pubkeyBuffer = bchjs.ECPair.toPublicKey(ecpair)
|
||||
assert.equal(typeof pubkeyBuffer, "object")
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#toLegacyAddress", () => {
|
||||
fixtures.toLegacyAddress.forEach(fixture => {
|
||||
it(`should create legacy address ${fixture.legacy} from an ECPair`, () => {
|
||||
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
const legacyAddress = bchjs.ECPair.toLegacyAddress(ecpair)
|
||||
assert.equal(legacyAddress, fixture.legacy)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#toCashAddress", () => {
|
||||
fixtures.toCashAddress.forEach(fixture => {
|
||||
it(`should create cash address ${fixture.cashAddr} from an ECPair`, () => {
|
||||
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
const cashAddr = bchjs.ECPair.toCashAddress(ecpair)
|
||||
assert.equal(cashAddr, fixture.cashAddr)
|
||||
})
|
||||
})
|
||||
|
||||
fixtures.toCashAddress.forEach(fixture => {
|
||||
it(`should create regtest cash address ${fixture.regtestAddr} from an ECPair`, () => {
|
||||
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
const regtestAddr = bchjs.ECPair.toCashAddress(ecpair, true)
|
||||
assert.equal(regtestAddr, fixture.regtestAddr)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#sign", () => {
|
||||
fixtures.sign.forEach(fixture => {
|
||||
it(`should sign 32 byte hash buffer`, () => {
|
||||
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
|
||||
const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), "hex")
|
||||
const signatureBuf = bchjs.ECPair.sign(ecpair, buf)
|
||||
assert.equal(typeof signatureBuf, "object")
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("#verify", () => {
|
||||
fixtures.verify.forEach(fixture => {
|
||||
it(`should verify signed 32 byte hash buffer`, () => {
|
||||
const ecpair1 = bchjs.ECPair.fromWIF(fixture.privateKeyWIF1)
|
||||
//const ecpair2 = bchjs.ECPair.fromWIF(fixture.privateKeyWIF2)
|
||||
const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), "hex")
|
||||
const signature = bchjs.ECPair.sign(ecpair1, buf)
|
||||
const verify = bchjs.ECPair.verify(ecpair1, buf, signature)
|
||||
assert.equal(verify, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,199 @@
|
||||
const chai = require("chai")
|
||||
const assert = chai.assert
|
||||
const axios = require("axios")
|
||||
const sinon = require("sinon")
|
||||
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
const bchjs = new BCHJS()
|
||||
|
||||
const mockData = require("./fixtures/electrumx-mock")
|
||||
|
||||
describe(`#ElectrumX`, () => {
|
||||
let sandbox
|
||||
beforeEach(() => (sandbox = sinon.createSandbox()))
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
describe(`#utxo`, () => {
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Electrumx.utxo(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should GET utxos for a single address`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "get").resolves({ data: mockData.utxo })
|
||||
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "utxos")
|
||||
assert.isArray(result.utxos)
|
||||
|
||||
assert.property(result.utxos[0], "height")
|
||||
assert.property(result.utxos[0], "tx_hash")
|
||||
assert.property(result.utxos[0], "tx_pos")
|
||||
assert.property(result.utxos[0], "value")
|
||||
})
|
||||
|
||||
it(`should POST utxo details for an array of addresses`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "post").resolves({ data: mockData.utxos })
|
||||
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.utxo(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "utxos")
|
||||
assert.isArray(result.utxos)
|
||||
|
||||
assert.property(result.utxos[0], "utxos")
|
||||
assert.isArray(result.utxos[0].utxos)
|
||||
assert.property(result.utxos[0], "address")
|
||||
|
||||
assert.property(result.utxos[0].utxos[0], "height")
|
||||
assert.property(result.utxos[0].utxos[0], "tx_hash")
|
||||
assert.property(result.utxos[0].utxos[0], "tx_pos")
|
||||
assert.property(result.utxos[0].utxos[0], "value")
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#balance`, () => {
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Electrumx.balance(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should GET balance for a single address`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "get").resolves({ data: mockData.balance })
|
||||
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "balance")
|
||||
assert.property(result.balance, "confirmed")
|
||||
assert.property(result.balance, "unconfirmed")
|
||||
})
|
||||
|
||||
it(`should POST balance for an array of addresses`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "post").resolves({ data: mockData.balances })
|
||||
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.balance(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "balances")
|
||||
assert.isArray(result.balances)
|
||||
|
||||
assert.property(result.balances[0], "address")
|
||||
assert.property(result.balances[0], "balance")
|
||||
assert.property(result.balances[0].balance, "confirmed")
|
||||
assert.property(result.balances[0].balance, "unconfirmed")
|
||||
})
|
||||
})
|
||||
|
||||
describe(`#transactions`, () => {
|
||||
it(`should throw an error for improper input`, async () => {
|
||||
try {
|
||||
const addr = 12345
|
||||
|
||||
await bchjs.Electrumx.transactions(addr)
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
`Input address must be a string or array of strings`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it(`should GET transactions for a single address`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "get").resolves({ data: mockData.transaction })
|
||||
|
||||
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "transactions")
|
||||
assert.isArray(result.transactions)
|
||||
assert.property(result.transactions[0], "height")
|
||||
assert.property(result.transactions[0], "tx_hash")
|
||||
})
|
||||
|
||||
it(`should POST transaction history for an array of addresses`, async () => {
|
||||
// Stub the network call.
|
||||
sandbox.stub(axios, "post").resolves({ data: mockData.transactions })
|
||||
|
||||
const addr = [
|
||||
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
]
|
||||
|
||||
const result = await bchjs.Electrumx.transactions(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
|
||||
assert.property(result, "transactions")
|
||||
assert.isArray(result.transactions)
|
||||
|
||||
assert.property(result.transactions[0], "address")
|
||||
assert.property(result.transactions[0], "transactions")
|
||||
assert.isArray(result.transactions[0].transactions)
|
||||
assert.property(result.transactions[0].transactions[0], "height")
|
||||
assert.property(result.transactions[0].transactions[0], "tx_hash")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
const assert = require("chai").assert
|
||||
const sinon = require("sinon")
|
||||
|
||||
const BCHJS = require("../../src/bch-js")
|
||||
// const bchjs = new BCHJS()
|
||||
let bchjs
|
||||
|
||||
const mockData = require("./fixtures/encryption-mock")
|
||||
|
||||
describe("#Encryption", () => {
|
||||
let sandbox
|
||||
|
||||
beforeEach(() => {
|
||||
bchjs = new BCHJS()
|
||||
sandbox = sinon.createSandbox()
|
||||
})
|
||||
|
||||
afterEach(() => sandbox.restore())
|
||||
|
||||
describe("#getPubKey", () => {
|
||||
it("should throw error if BCH address is not provided.", async () => {
|
||||
try {
|
||||
await bchjs.encryption.getPubKey()
|
||||
|
||||
assert.equal(true, false, "Unexpected result!")
|
||||
} catch (err) {
|
||||
// console.log(`err: `, err)
|
||||
assert.include(
|
||||
err.message,
|
||||
"Input must be a valid Bitcoin Cash address"
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it("should report when public key can not be found", async () => {
|
||||
// Stub the network call.
|
||||
sandbox
|
||||
.stub(bchjs.encryption.axios, "get")
|
||||
.resolves({ data: mockData.failureMock })
|
||||
|
||||
const addr = "bitcoincash:qpxqr2pmcverj4vukgjqssvk2zju8tp9xsgz2nqagx"
|
||||
|
||||
const result = await bchjs.encryption.getPubKey(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, false)
|
||||
assert.property(result, "publicKey")
|
||||
assert.equal(result.publicKey, "not found")
|
||||
})
|
||||
|
||||
it("should get a public key", async () => {
|
||||
// Stub the network call.
|
||||
sandbox
|
||||
.stub(bchjs.encryption.axios, "get")
|
||||
.resolves({ data: mockData.successMock })
|
||||
|
||||
const addr = "bitcoincash:qpf8jv9hmqcda0502gjp7nm3g24y5h5s4unutghsxq"
|
||||
|
||||
const result = await bchjs.encryption.getPubKey(addr)
|
||||
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
|
||||
|
||||
assert.property(result, "success")
|
||||
assert.equal(result.success, true)
|
||||
assert.property(result, "publicKey")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,187 @@
|
||||
{
|
||||
"legacyMainnetP2PKH": [
|
||||
"18xHZ8g2feo4ceejGpvzHkvXT79fi2ZdTG",
|
||||
"1K7Qb1dWkiYwPrZhLws3uUKhxKEU7dRnbQ",
|
||||
"1Au7gWXS2zAgFSdWwT5QnTNeasye16kxoG",
|
||||
"174uecjfRgh1XkVBYFzZymkV1JwmFQ91s9",
|
||||
"1KLXUPMdq4vaU3VoQzSvLUx2mub5qzFkTc",
|
||||
"12AqNsGTyL6RDR8SDEtW9EyfYruFNZ9Sjs",
|
||||
"1P3Lq89iP27S76ZMKonty4mpJMDHp3a9NE",
|
||||
"14A8F8jHiipwnKLd2JEWqPvbGiS6FA7VoG",
|
||||
"1KgRZzxLUvZqL8EuufmdxqSjh3tgURwD6d",
|
||||
"1GMApiWJoTfQ21jbtVX3Qz8YtnGUuZAJtS"
|
||||
],
|
||||
"legacyMainnetP2SH": [
|
||||
"3DA6RBcFgLwLTpnF6BRAee8w6a9H6JQLCm",
|
||||
"3AbtU1JSaiQijyGT21stxpBRZj1hixWcGB",
|
||||
"3KfgmLeczB525pV2tJLQ6RM5qFMLaB2Kn1",
|
||||
"3Bsr5dvAJ2Q8CpHxJSZkNdgD12Tkb9TaR7",
|
||||
"3J78iYD4i4ht8Btp8pyRx71jg5yrRTkQaM",
|
||||
"3EGxduodZm6a9FLN1jdVxN8pT5orCmFdUK",
|
||||
"3DWvzGWYJCY19Gc4LcN8noHGpxdjRbJeYe",
|
||||
"3Aw9ePtWrH8EEJoF5HW8swW9VXxpF4dP54",
|
||||
"3QTQE5rt7TZg7hXZ4DsTQ6mUUZCbFY2RiL",
|
||||
"3EoWFm3GcTzDFBQ9KGVevhH1nuSxa14eFM"
|
||||
],
|
||||
"legacyTestnetP2PKH": [
|
||||
"mhTg9sgNgvAGfmJs192oUzQWqAXHH5nqLE",
|
||||
"mmpjQ24UyGGfJ39k44prH6W2A7y1qVaQti",
|
||||
"muEnSveRwu8cEJSvXzDTJZQWrr7y9i331i",
|
||||
"n3jZn7rb3Bjepap4TWo8pyqcwuxAw439HW",
|
||||
"mqHUen3SUNjQkAPjMxZfSnuyd8cmcbL6fq",
|
||||
"n4g3swxSebC9cDHXTjYQcx3tRAe4EPrZrZ",
|
||||
"n2yNUahmfBFLLzrpcXpMh8Votw7zbKVHtX",
|
||||
"mqYM6bu8Vw6xFTTPhbtxWPPmFN8BwpVQeE",
|
||||
"mrVbyCMyB3vhDya4rYSxdM8qivEGfn7JSP",
|
||||
"mnqGaf1SbPFh1tdXdeXd7pWhJUY2ite6SY"
|
||||
],
|
||||
"cashaddrMainnetP2PKH": [
|
||||
"bitcoincash:qptnmya5wkly7xf97wm5ak23yqdsz3l2cyj7k9vyyh",
|
||||
"bitcoincash:qrr2suh9yjsrkl2qp3p967uhfg6u0r6xxsn9h5vuvr",
|
||||
"bitcoincash:qpkfg4kck99wksyss6nvaqtafeahfnyrpsj0ed372t",
|
||||
"bitcoincash:qppgmuuwy07g0x39sx2z0x2u8e34tvfdxvy0c2jvx7",
|
||||
"bitcoincash:qryj8x4s7vfsc864jm0xaak9qfe8qgk245y9ska57l",
|
||||
"bitcoincash:qqxdgs9x9rx4v7g4ea5kxyprj2k9wnv695578lwmt8",
|
||||
"bitcoincash:qrcugfh4prxzl8qzqazyth7ytuc6k4qqcg50etp609",
|
||||
"bitcoincash:qq32y2h0ljtyyv4xkk07gtyrclv2xwq5sq3pqrzjes",
|
||||
"bitcoincash:qrxwdlhfx5f4xsfnl0g887e5ccs5puy8sgj0z0md6k",
|
||||
"bitcoincash:qz595e7jwa3q4vw26whn6zcz6x074669lgnnvjkz5m"
|
||||
],
|
||||
"cashaddrMainnetP2SH": [
|
||||
"bitcoincash:pp7ushdxf5we8mcpaa3wqgsuqt639cu59ur5xu5fug",
|
||||
"bitcoincash:ppsup5akyvql5w46q9eszd9fxpx970acpyqkw79vq2",
|
||||
"bitcoincash:prznrkhnf6zqsap6l664ayzu2xue67ue4gv686sjyu",
|
||||
"bitcoincash:pphmm80pznl6pnkmzakz3ahafydmvhwzcslea4v5mz",
|
||||
"bitcoincash:pz6pr25g6mulp0kes9xnmsda0u4rf442ase2un89pl",
|
||||
"bitcoincash:pz9qe6ys8x0l98zegf0a9rae4zenk95yp5dv5xjnk5",
|
||||
"bitcoincash:pzqmjwk8929jtqt7ac7szjuawtswmxhtu5xxm64upf",
|
||||
"bitcoincash:ppjk2e4nz47n50hpg8z6nt5hfjeajy4cyyp0p2tvnp",
|
||||
"bitcoincash:prum0t7tqczlyaw2d30tmpj3je9q2xlzwcqk9wx83u",
|
||||
"bitcoincash:pz8a837lttkvjksg0jjmmulqvfkgpqrcdgufy8ns5s"
|
||||
],
|
||||
"cashaddrTestnetP2PKH": [
|
||||
"bchtest:qq24rpar9qas3vc9r8d4p0prhwaf7jmx2u22nzt946",
|
||||
"bchtest:qpzj67wmlsq8uttddddapjjawyusureca59ug9cak8",
|
||||
"bchtest:qztg9c4u3ldhg68mqgzrple6ae92hwnfe5m6kyejfd",
|
||||
"bchtest:qrem2cg43ksmvlampheur8gfgdhhk57mygy26y7f2e",
|
||||
"bchtest:qp4jf3n740kffkladul96xnq5dtrflg4x5w5rfy22r",
|
||||
"bchtest:qrlqxnzuu6hvvg9qer0m093ywkjnu7wm7ypj7unqzc",
|
||||
"bchtest:qr44nfr9egxt7h7lxdktf9kajds9fwdxxcved7827j",
|
||||
"bchtest:qpklfd26u70ta4j7p4twxv2k5apx95p0qqgm8cf2sd",
|
||||
"bchtest:qpuxsqzgq3j0a58tnmwpgcrwwyrkenalevaeknklfg",
|
||||
"bchtest:qpgrlg0yqmdf4y8q980e57tx6v7vrvds2ug89n8w8q"
|
||||
],
|
||||
"cashaddrRegTestP2PKH": [
|
||||
"bchreg:qq24rpar9qas3vc9r8d4p0prhwaf7jmx2usk9rgkku",
|
||||
"bchreg:qpzj67wmlsq8uttddddapjjawyusureca5lq7ymw4p",
|
||||
"bchreg:qztg9c4u3ldhg68mqgzrple6ae92hwnfe5pxq96p2t",
|
||||
"bchreg:qrem2cg43ksmvlampheur8gfgdhhk57myg7kv9a6fl",
|
||||
"bchreg:qp4jf3n740kffkladul96xnq5dtrflg4x55g4g8ef9",
|
||||
"bchreg:qrlqxnzuu6hvvg9qer0m093ywkjnu7wm7ymwgasnp7",
|
||||
"bchreg:qr44nfr9egxt7h7lxdktf9kajds9fwdxxck9mlyea5",
|
||||
"bchreg:qpklfd26u70ta4j7p4twxv2k5apx95p0qqj83e2ent",
|
||||
"bchreg:qpuxsqzgq3j0a58tnmwpgcrwwyrkenalev89qj4v2w",
|
||||
"bchreg:qpgrlg0yqmdf4y8q980e57tx6v7vrvds2ujmnjyayx"
|
||||
],
|
||||
"hash160MainnetP2PKH": [
|
||||
"573d93b475be4f1925f3b74ed951201b0147eac1",
|
||||
"c6a872e524a03b7d400c425d7b974a35c78f4634",
|
||||
"6c9456d8b14aeb409086a6ce817d4e7b74cc830c",
|
||||
"428df38e23fc879a25819427995c3e6355b12d33",
|
||||
"c9239ab0f3130c1f5596de6ef6c502727022caad",
|
||||
"0cd440a628cd567915cf6963102392ac574d9a2d",
|
||||
"f1c426f508cc2f9c02074445dfc45f31ab5400c2",
|
||||
"22a22aeffc964232a6b59fe42c83c7d8a3381480",
|
||||
"cce6fee93513534133fbd073fb34c62140f08782",
|
||||
"a85a67d277620ab1cad3af3d0b02d19feaeb45fa"
|
||||
],
|
||||
"hash160MainnetP2SH": [
|
||||
"7dc85da64d1d93ef01ef62e0221c02f512e3942f",
|
||||
"61c0d3b62301fa3aba01730134a9304c5f3fb809",
|
||||
"c531daf34e8408743afeb55e905c51b99d7b99aa",
|
||||
"6fbd9de114ffa0cedb176c28f6fd491bb65dc2c4",
|
||||
"b411aa88d6f9f0bed9814d3dc1bd7f2a34d6aaec",
|
||||
"8a0ce890399ff29c59425fd28fb9a8b33b16840d",
|
||||
"81b93ac72a8b25817eee3d014b9d72e0ed9aebe5",
|
||||
"656566b3157d3a3ee141c5a9ae974cb3d912b821",
|
||||
"f9b7afcb0605f275ca6c5ebd8651964a051be276",
|
||||
"8fd3c7df5aecc95a087ca5bdf3e0626c8080786a"
|
||||
],
|
||||
"hash160TestnetP2PKH": [
|
||||
"155187a3283b08b30519db50bc23bbba9f4b6657",
|
||||
"452d79dbfc007e2d6d6b5bd0ca5d71390e0f38ed",
|
||||
"9682e2bc8fdb7468fb020430ff3aee4aabba69cd",
|
||||
"f3b561158da1b67fbb0df3c19d09436f7b53db22",
|
||||
"6b24c67eabec94dbfd6f3e5d1a60a35634fd1535",
|
||||
"fe034c5ce6aec620a0c8dfb7962475a53e79dbf1",
|
||||
"eb59a465ca0cbf5fdf336cb496dd936054b9a636",
|
||||
"6df4b55ae79ebed65e0d56e33156a74262d02f00",
|
||||
"786800480464fed0eb9edc14606e71076ccfbfcb",
|
||||
"503fa1e406da9a90e029df9a7966d33cc1b1b057"
|
||||
],
|
||||
"mainnetXPub": [
|
||||
{
|
||||
"xpub": "xpub6CVcpZVmPNjuniVYu1mLnLjDBfxWpx7LS25uxwRm5BLbXMCJmRaQgAxuqZDoYDeidJUh5QUatLJPWpeCkEK648hExyKFezqxJz4CMfEoYAc",
|
||||
"addresses": [
|
||||
"bitcoincash:qp3c2e0ehq5lqgnf2v8kqk0qemkatnknmga3mwqkms",
|
||||
"bitcoincash:qznkqj05zsx8uszyjfdyvfn55ecwltfsrq93jhwchv",
|
||||
"bitcoincash:qpkvr2gs84g6nltzcs9d9ef7qerh7qqenca2zddlpz",
|
||||
"bitcoincash:qpuchd6als5yc3fs55aktwylr20u0antyu5f99jt8k",
|
||||
"bitcoincash:qq670p9knuarh75ae7er4c246w909nd0z5gx6h60vv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"xpub": "xpub6CVcpZVmPNjuqYFnvSYoD9hE89PKmsWewFWGKeaCcVNSfDTgQgMuhm8Q2zreBsNQVMSJrBmQ3C95fi3SiRXYRQckQJMZuPXTJm9TcQejW13",
|
||||
"addresses": [
|
||||
"bitcoincash:qqhkcs5fnchh99p68mcszcz68cecef5jfyeugnyysl",
|
||||
"bitcoincash:qqxj4w8lgctdhpvl9um9w7tvgmc9se3ttcfkdfcv5e",
|
||||
"bitcoincash:qp30m7fu27vljfqvqq26kwn8f4zp4g7wngqdzn40xh",
|
||||
"bitcoincash:qrvtu7nw8x5343c9jgc5a58zw5vw3susful9x9yhrv",
|
||||
"bitcoincash:qrjcyuxunxzt2w35ney2hzrvgynrcqg5qqj9366m6a"
|
||||
]
|
||||
},
|
||||
{
|
||||
"xpub": "xpub6CVcpZVmPNjuu1zjt9joxDzDrP9UNs6GVS5K1jSopnq76RBZswLsxy75qvJTVcSS6V9Y4Df6L7GDsbns99WrLrfmBNwocEdQm5CXFGExAgq",
|
||||
"addresses": [
|
||||
"bitcoincash:qp3d5t96fdvjkurpt2h0t8nw5u4hr294q5q4dw6g9r",
|
||||
"bitcoincash:qpusevag7l73543hs2lw69aqx4kzlsxamyg785mnsa",
|
||||
"bitcoincash:qp48wzx62956wqux569mhm7dzyykya35aghd0y6qxf",
|
||||
"bitcoincash:qqxd6u4lap7s9zcm8jdkd44uakyghcw8hqawurftc6",
|
||||
"bitcoincash:qrn4gf9ufqp3ze4refp6yqh60s47crcwksqp20txs7"
|
||||
]
|
||||
}
|
||||
],
|
||||
"testnetXPub": [
|
||||
{
|
||||
"xpub": "tpubDCrnMSKwDMAbxg82yqDt97peMvftCXk3EfBb9WgZh27mPbHGkysU3TW7qX5AwydmnVQfaGeNhUR6okQ3dS5AJTP9gEP7jk2Wcj6Xntc6gNh",
|
||||
"addresses": [
|
||||
"bchtest:qrth8470sc9scek9u0jj2d0349t62gxzdstw2jukl8",
|
||||
"bchtest:qpm56zc5re0nhms96r7p985aajthp0vxvg6e4ux3kc",
|
||||
"bchtest:qqtu3tf6yyd73ejhk3a2ylqynpl3mzzhwuzt299jfd",
|
||||
"bchtest:qzd7dvlnfukggjqsf5ju0qqwwltakfumjsck33js6m",
|
||||
"bchtest:qq322ataqeas4n0pdn4gz2sdereh5ae43ylk4qdvus"
|
||||
]
|
||||
},
|
||||
{
|
||||
"xpub": "tpubDCrnMSKwDMAbzuN7eQDcFh9c6BsUvHHiL7j1AE9f9mE2ertgK6DwAZ6xmqtM3G5ifPkVynnjhMMMS87R1x4DTPrCbp4VjBttqMc4KmQEMRv",
|
||||
"addresses": [
|
||||
"bchtest:qq2lnfskh8herq7hhj067uzfmhg2cf6arvc8eld50k",
|
||||
"bchtest:qrjqt3vw8us9nc4d3h8j5fn6cxa0h5485ydd5zhq8y",
|
||||
"bchtest:qze485w97jjhpucgk9dmh7h4fx56z8tmvgv4c3esmm",
|
||||
"bchtest:qp6dvdwfu02z6d8cp6uqkpnjde66m89t9cexm00fmd",
|
||||
"bchtest:qz266xueu99z6mh8af66gwnsv48jxva6aslmju2wat"
|
||||
]
|
||||
},
|
||||
{
|
||||
"xpub": "tpubDCrnMSKwDMAc4zKRDfxDqmzzxwLd85MFYF3cHzmdGDchnS7Sz2UiHD6HqaJR5Lefq6BhApPvGsdp3smjE1KRNkWHZ4wWogt7UYrgVznGfs1",
|
||||
"addresses": [
|
||||
"bchtest:qqzkac72c0dygl92ru74zmwkkhdq7sc845n43ulmlw",
|
||||
"bchtest:qzsm0ymr035a5eg0r8k4hxvyaxqyd0e8msd7f79v2z",
|
||||
"bchtest:qqg6yea05gkqyxwdce6k5sjun8k9drgzn54d63cq5n",
|
||||
"bchtest:qrfumvznl5ck903vq3sp3gfsrjt22tqa85lxzjv4p9",
|
||||
"bchtest:qrd88na4869phkr0h44kzfakwc52w2jwmqjl6vlynn"
|
||||
]
|
||||
}
|
||||
],
|
||||
"p2shMainnet": ["bitcoincash:pz0qcslrqn7hr44hsszwl4lw5r6udkg6zqncnufkrl"]
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
{
|
||||
"conversion": {
|
||||
"toBCH": {
|
||||
"satoshis": [
|
||||
[100000000, 1],
|
||||
[123456789012345, 1234567.89012345],
|
||||
[314159265359, 3141.59265359],
|
||||
[9876765, 0.09876765],
|
||||
[507, 0.00000507]
|
||||
],
|
||||
"strings": [
|
||||
["100000000", 1],
|
||||
["123456789012345", "1234567.89012345"],
|
||||
["314159265359", "3141.59265359"],
|
||||
["9876765", "0.09876765"],
|
||||
["507", "0.00000507"]
|
||||
],
|
||||
"not": [
|
||||
[100000000, 10000000000000000],
|
||||
[12345, 1234500000000],
|
||||
[314159, 31415900000000],
|
||||
[9876765, 987676500000000],
|
||||
[507, 50700000000]
|
||||
],
|
||||
"rounding": [
|
||||
[1, 0.00000001],
|
||||
[42, 0.00000042],
|
||||
[507, 0.00000507],
|
||||
[1234, 0.00001234],
|
||||
[65432, 0.00065432]
|
||||
]
|
||||
},
|
||||
"toSatoshi": {
|
||||
"bch": [
|
||||
[1, 100000000],
|
||||
[1234567.89012345, 123456789012345],
|
||||
[3141.59265359, 314159265359],
|
||||
[0.09876765, 9876765],
|
||||
[0.00000507, 507]
|
||||
],
|
||||
"strings": [
|
||||
["1", "100000000"],
|
||||
["1234567.89012345", "123456789012345"],
|
||||
["3141.59265359", "314159265359"],
|
||||
["0.09876765", "9876765"],
|
||||
["0.00000507", "507"]
|
||||
],
|
||||
"not": [
|
||||
[10000000000000000, 100000000],
|
||||
[1234500000000, 12345],
|
||||
[31415900000000, 314159],
|
||||
[987676500000000, 9876765],
|
||||
[50700000000, 507]
|
||||
],
|
||||
"rounding": [
|
||||
[0.00000001, 1],
|
||||
[0.00000042, 42],
|
||||
[0.00000507, 507],
|
||||
[0.00001234, 1234],
|
||||
[0.00065432, 65432]
|
||||
]
|
||||
},
|
||||
"satsToBits": {
|
||||
"bch": [
|
||||
[42.423234, 42423234],
|
||||
[1, 1000000],
|
||||
[3.14, 3140000],
|
||||
[9876, 9876000000],
|
||||
[0.000123, 123]
|
||||
],
|
||||
"strings": [
|
||||
["42.423234", "42423234"],
|
||||
["1", "1000000"],
|
||||
["3.14", "3140000"],
|
||||
["9876", "9876000000"],
|
||||
["0.000123", "123"]
|
||||
]
|
||||
},
|
||||
"satsFromBits": {
|
||||
"bch": [
|
||||
[4242324, 42423.2340],
|
||||
[100000, 1000.0000],
|
||||
[314000, 3140.0000],
|
||||
[987600000, 9876000.0000],
|
||||
[12.3, 0.1230]
|
||||
],
|
||||
"strings": [
|
||||
["4242324", "42423.2340"],
|
||||
["100000", "1000.0000"],
|
||||
["314000", "3140.0000"],
|
||||
["987600000", "9876000.0000"],
|
||||
["12.3", "0.1230"]
|
||||
]
|
||||
}
|
||||
},
|
||||
"signatures": {
|
||||
"sign": [
|
||||
{
|
||||
"network": "mainnet",
|
||||
"privateKeyWIF": "Ky54Y7sxkGovqTi5ogipFUToqsz4NCepLn3bitzHyiF3JaYULMbP",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "IMx84IyWWbygyT5MnN1RWykh9B4lHMxght69emBCqmGfSGaYozaXeVZNzmKVGMxjSqqGZZ0aGPf08GtahLAjWXk="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"privateKeyWIF": "KzkgRUDjAofdLvwHFGEyhtiULPYpKDozgfkz5yWR1S39isWHWPrz",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "H8X9FFIbyD4zAC/Hr57m5qTA2IDgbYTbdBpm/FEIhJVYMsG5xiuZxPrt2OA0zS7Uon1fwGLvLr0rdi+aD+JSl4w="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"privateKeyWIF": "Kyb6tWZUfppAyQMRX9b1yAKahFDn8Xr2dY26tk7nM9s5cLvvFuqS",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "IFRV4fhdbJdKIABCkKQWezJTjUqw1aEZZc0k+pX5mQseG5e7UyGKG6r6REU1hSwahA0NHfOeNP2dZGzo9uYv+VU="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"privateKeyWIF": "KzoVcYVG1dqVPa8AASR9tjXQHqs8KDx9Ex3WrwaEYPPxJ76gTZC2",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "IAaBJA09iOlyfQkCsWSlFC82YdE3leIKOCLfiJA0FTaDM30xvQrVb38L5sF6eD2zUUPpc0wMbxeqC7Rj8lRroHk="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"privateKeyWIF": "KwEYU8cuczmym3KXUcVqmQS2R4zcKgzQ8ba2R54LHuSsY2wKXXkF",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "H+enm4Bb938z433Q7TBeFIMGNXrV8B1ui4SuLgkKqdYRDQgdaT1OHt5sk54CrjTQHGYOhpQW7DrRJLsIJffjJqs="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"privateKeyWIF": "cN4Uy1GrEG2nLEiwB4pcGe7DuVDhX3aRoc6EMbLTYUGiunEgY5aZ",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "H58Em7Eehv1pEIBHf3qmQTrGHbk7RaShpUIWZcYyjq4FHiKaVrzk4ZB2pThQe/+JmzM9tG/om9R90/LyN2YCVV8="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"privateKeyWIF": "cVsp354pynjPN7Z6aeiHHkwEiwb6YpxymmEAYGGKxDumHxF6JHuQ",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "IIFdTtIjnRzxQ07Yx8PKRjCNvDKjgiyujDzWUkFiSMV7Z8EM84DYIvFYslL00N4QDec6YFoSSmHAYi9IbJ8MRoQ="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"privateKeyWIF": "cSbWcRrNdTwSafDci88gVMPrrHpTV7ew3aqnTEDrKd8EsU6cg3zL",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "INB4Mv4YGwFZZl72ZW4Z+iNWcWgfl4mVhkrA9do+47MZJ+x5NcOylfzK++8BkzaQA08DeTsGw3zpOzbwJ/B+uZE="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"privateKeyWIF": "cTUU8gWrGvxArHUzRjibHfCDGpbhfUsYQxbnS5hurtQPUDfFuouo",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "IIoQBpSKymzH2Tg75bPXcZSxPyHPJU3Q/AcxwURmKWrDdWhSsKlv0dVXL0js28JD505Js8r/mkbe6MPV5PdVbCk="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"privateKeyWIF": "cS8T5umEVPMFpjvMViqPqnTBN5Zqs1HNCxKpVPoNbFCGaUxRzMz4",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "H1gOF88XX/tfH7pa50CfRXoD6h8pzi+Ceg3SG9E4UsJnat90Nw4nxbLJBTMDNTHbTfCD1Upe1IlbYLZEaVsIXrY="
|
||||
}
|
||||
],
|
||||
"verify": [
|
||||
{
|
||||
"network": "mainnet",
|
||||
"address": "bitcoincash:qzq53zlu48a00h0a8ay8gq3wnkvfxc50cv6fj5qm9d",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "IMx84IyWWbygyT5MnN1RWykh9B4lHMxght69emBCqmGfSGaYozaXeVZNzmKVGMxjSqqGZZ0aGPf08GtahLAjWXk="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"address": "bitcoincash:qrpuxwzerdfm5plxzxekya3js9wn2f4wa5lcgnat7c",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "H8X9FFIbyD4zAC/Hr57m5qTA2IDgbYTbdBpm/FEIhJVYMsG5xiuZxPrt2OA0zS7Uon1fwGLvLr0rdi+aD+JSl4w="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"address": "bitcoincash:qpq7zz6ax7lun9ks92g5qwye206xkenc655y4x7rfn",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "IFRV4fhdbJdKIABCkKQWezJTjUqw1aEZZc0k+pX5mQseG5e7UyGKG6r6REU1hSwahA0NHfOeNP2dZGzo9uYv+VU="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"address": "bitcoincash:qp22q7vt79qp724zvk0qkj59ec4h9ghx9yscnl3mpw",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "IAaBJA09iOlyfQkCsWSlFC82YdE3leIKOCLfiJA0FTaDM30xvQrVb38L5sF6eD2zUUPpc0wMbxeqC7Rj8lRroHk="
|
||||
},
|
||||
{
|
||||
"network": "mainnet",
|
||||
"address": "bitcoincash:qzul5ttllyky9tcdmc458tw0fymtc2mkvc75542prl",
|
||||
"message": "BCHForEveryone",
|
||||
"signature": "H+enm4Bb938z433Q7TBeFIMGNXrV8B1ui4SuLgkKqdYRDQgdaT1OHt5sk54CrjTQHGYOhpQW7DrRJLsIJffjJqs="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"address": "bchtest:qrhxjj4zxr342rpetm5hgmlxgrkkf9yhxspquuzpvf",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "H58Em7Eehv1pEIBHf3qmQTrGHbk7RaShpUIWZcYyjq4FHiKaVrzk4ZB2pThQe/+JmzM9tG/om9R90/LyN2YCVV8="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"address": "bchtest:qr8qhm92wf070lsd9xegmhnx8lt74tx0svc9yg3g0m",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "IIFdTtIjnRzxQ07Yx8PKRjCNvDKjgiyujDzWUkFiSMV7Z8EM84DYIvFYslL00N4QDec6YFoSSmHAYi9IbJ8MRoQ="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"address": "bchtest:qpgke00rhhl2w4a9jxzrdalaw0vz383j7uah86pv7f",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "INB4Mv4YGwFZZl72ZW4Z+iNWcWgfl4mVhkrA9do+47MZJ+x5NcOylfzK++8BkzaQA08DeTsGw3zpOzbwJ/B+uZE="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"address": "bchtest:qpnvzdzxshnvz8k28jrql4qr8qg6mc6mzc498c68c0",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "IIoQBpSKymzH2Tg75bPXcZSxPyHPJU3Q/AcxwURmKWrDdWhSsKlv0dVXL0js28JD505Js8r/mkbe6MPV5PdVbCk="
|
||||
},
|
||||
{
|
||||
"network": "testnet",
|
||||
"address": "bchtest:qqs5j90clt5v2rw824xnlta4q2exv76uvsfrrmar7z",
|
||||
"message": "#BCHForEveryone",
|
||||
"signature": "H1gOF88XX/tfH7pa50CfRXoD6h8pzi+Ceg3SG9E4UsJnat90Nw4nxbLJBTMDNTHbTfCD1Upe1IlbYLZEaVsIXrY="
|
||||
}
|
||||
]
|
||||
},
|
||||
"encodeBase58Check": [
|
||||
{
|
||||
"base58Check": "1C6hRmfzvWst5WA7bFRCVAqHt5gE2g7Qar",
|
||||
"hex": "0079bd35d306f648350818470c9f18903df6e06902a026f2a7"
|
||||
},
|
||||
{
|
||||
"base58Check": "1Azo2JBz2JswboeY9xSMcp14BAfhjnD9SK",
|
||||
"hex": "006da742680accf2282df5fade8e9b7a01a517e779289b52cc"
|
||||
},
|
||||
{
|
||||
"base58Check": "1K6ncAmMEyQrKUYosZRD9swyZNXECu2aKs",
|
||||
"hex": "00c68a6a07ccdaf1669cfd8d244d80ff36b713551c6208f672"
|
||||
},
|
||||
{
|
||||
"base58Check": "1L2FG9hH3bwchhxHaCs5cg1QNbhmbaeAs6",
|
||||
"hex": "00d0a6b5e3dd43d0fb895b3b3df565bb8266c5ab00a25dbeb5"
|
||||
},
|
||||
{
|
||||
"base58Check": "1Ly4gqPddveYHMNkfjoXHanVszXpD3duKg",
|
||||
"hex": "00db04c2e6f104997cb04c956bf25da6078e559d303127f08b"
|
||||
}
|
||||
],
|
||||
"bip21": {
|
||||
"invalid": [
|
||||
{
|
||||
"address": "bitcoincash:qpk6wsngptx0y2pd7hadar5m0gq629l80y2tcp5ktd",
|
||||
"url": "satoshi:qpk6wsngptx0y2pd7hadar5m0gq629l80y2tcp5ktd"
|
||||
}
|
||||
],
|
||||
"valid": [
|
||||
{
|
||||
"address": "1C6hRmfzvWst5WA7bFRCVAqHt5gE2g7Qar",
|
||||
"options": {
|
||||
"amount": 12.5,
|
||||
"label": "coinbase donation",
|
||||
"message": "and ya don't stop"
|
||||
},
|
||||
"url": "bitcoincash:qpum6dwnqmmysdggrprse8ccjq7ldcrfqgmmtgcmny?amount=12.5&label=coinbase%20donation&message=and%20ya%20don%27t%20stop"
|
||||
},
|
||||
{
|
||||
"address": "1Azo2JBz2JswboeY9xSMcp14BAfhjnD9SK",
|
||||
"options": {
|
||||
"label": "Foobar"
|
||||
},
|
||||
"url": "bitcoincash:qpk6wsngptx0y2pd7hadar5m0gq629l80y2tcp5ktd?label=Foobar"
|
||||
},
|
||||
{
|
||||
"address": "bitcoincash:qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqrt2qkz5s",
|
||||
"options": {
|
||||
"amount": 1,
|
||||
"label": "test"
|
||||
},
|
||||
"url": "bitcoincash:qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqrt2qkz5s?amount=1&label=test"
|
||||
},
|
||||
{
|
||||
"address": "bitcoincash:qzc5fxdm6lnwzgeju4jaemngtxkkkgt78ucn6vkjz5",
|
||||
"options": {
|
||||
"amount": 3,
|
||||
"label": "hhhhhhh"
|
||||
},
|
||||
"url": "bitcoincash:qzc5fxdm6lnwzgeju4jaemngtxkkkgt78ucn6vkjz5?amount=3&label=hhhhhhh"
|
||||
},
|
||||
{
|
||||
"address": "qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qw0e54u03",
|
||||
"options": {
|
||||
"amount": 23,
|
||||
"label": "no prefix"
|
||||
},
|
||||
"url": "bitcoincash:qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qw0e54u03?amount=23&label=no%20prefix"
|
||||
},
|
||||
{
|
||||
"address": "qphgz6ut3uu9xu8sly2zj7n5jkg5eyes5vjv3juf0x",
|
||||
"options": {
|
||||
"amount": 20.3,
|
||||
"label": "Foobar"
|
||||
},
|
||||
"url": "bitcoincash:qphgz6ut3uu9xu8sly2zj7n5jkg5eyes5vjv3juf0x?amount=20.3&label=Foobar"
|
||||
}
|
||||
],
|
||||
"valid_regtest": [
|
||||
{
|
||||
"address": "1C6hRmfzvWst5WA7bFRCVAqHt5gE2g7Qar",
|
||||
"options": {
|
||||
"amount": 12.5,
|
||||
"label": "coinbase donation",
|
||||
"message": "and ya don't stop"
|
||||
},
|
||||
"url": "bchreg:qpum6dwnqmmysdggrprse8ccjq7ldcrfqg94ewelh7?amount=12.5&label=coinbase%20donation&message=and%20ya%20don%27t%20stop"
|
||||
},
|
||||
{
|
||||
"address": "1Azo2JBz2JswboeY9xSMcp14BAfhjnD9SK",
|
||||
"options": {
|
||||
"label": "Foobar"
|
||||
},
|
||||
"url": "bchreg:qpk6wsngptx0y2pd7hadar5m0gq629l80y59284j0h?label=Foobar"
|
||||
},
|
||||
{
|
||||
"address": "bchreg:qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqa9cxhxs2",
|
||||
"options": {
|
||||
"amount": 1,
|
||||
"label": "test"
|
||||
},
|
||||
"url": "bchreg:qrdsfshx7yzfjl9sfj2khuja5crcu4vaxqa9cxhxs2?amount=1&label=test"
|
||||
},
|
||||
{
|
||||
"address": "bchreg:qzc5fxdm6lnwzgeju4jaemngtxkkkgt78uxag2hkxw",
|
||||
"options": {
|
||||
"amount": 3,
|
||||
"label": "hhhhhhh"
|
||||
},
|
||||
"url": "bchreg:qzc5fxdm6lnwzgeju4jaemngtxkkkgt78uxag2hkxw?amount=3&label=hhhhhhh"
|
||||
},
|
||||
{
|
||||
"address": "qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qsptj5ctt",
|
||||
"options": {
|
||||
"amount": 23,
|
||||
"label": "no prefix"
|
||||
},
|
||||
"url": "bchreg:qzw6tfrh8p0jh834uf9rhg77pjg5rgnt3qsptj5ctt?amount=23&label=no%20prefix"
|
||||
},
|
||||
{
|
||||
"address": "qphgz6ut3uu9xu8sly2zj7n5jkg5eyes5vvzr5adtu",
|
||||
"options": {
|
||||
"amount": 20.3,
|
||||
"label": "Foobar"
|
||||
},
|
||||
"url": "bchreg:qphgz6ut3uu9xu8sly2zj7n5jkg5eyes5vvzr5adtu?amount=20.3&label=Foobar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"getByteCount": [
|
||||
{
|
||||
"byteCount": 190,
|
||||
"inputs": {
|
||||
"P2PKH":1
|
||||
},
|
||||
"outputs": {
|
||||
"P2SH":1
|
||||
}
|
||||
},
|
||||
{
|
||||
"byteCount": 2750,
|
||||
"inputs": {
|
||||
"MULTISIG-P2SH:2-4":4,
|
||||
"P2PKH":10
|
||||
},
|
||||
"outputs": {
|
||||
"P2PKH":23
|
||||
}
|
||||
},
|
||||
{
|
||||
"byteCount": 565,
|
||||
"inputs": {
|
||||
"MULTISIG-P2SH:3-5":2
|
||||
},
|
||||
"outputs": {
|
||||
"P2PKH":2
|
||||
}
|
||||
},
|
||||
{
|
||||
"byteCount": 16506,
|
||||
"inputs": {
|
||||
"P2PKH":111
|
||||
},
|
||||
"outputs": {
|
||||
"P2PKH":2
|
||||
}
|
||||
},
|
||||
{
|
||||
"byteCount": 1780,
|
||||
"inputs": {
|
||||
"P2PKH":10,
|
||||
"MULTISIG-P2SH:1-2":1
|
||||
},
|
||||
"outputs": {
|
||||
"P2PKH":2,
|
||||
"P2SH":1
|
||||
}
|
||||
}
|
||||
],
|
||||
"bip38": {
|
||||
"encrypt": {
|
||||
"mainnet": [
|
||||
{
|
||||
"wif": "L1XHKhaBAfkr2FJQn3pTfCMxz652WYfmvKj8xDCHCEDV9tWGcbYj",
|
||||
"password": "1EBPIyj55eR8bVUov9",
|
||||
"encryptedKey": "6PYWWnBNfNpSqEJZKcfwbrYgTTdb9PNiGjQJ8r9V6cvsZNKLfcZD8YefQc"
|
||||
},
|
||||
{
|
||||
"wif": "L1phBREbhL4vb1uHHHCAse8bdGE5c7ic2PFjRxMawLzQCsiFVbvu",
|
||||
"password": "9GKVkabAHBMyAf",
|
||||
"encryptedKey": "6PYU2fDHRVF2194gKDGkbFbeu4mFgkWtVvg2RPd2Sp6KmZx3RCHFpgBB2G"
|
||||
}
|
||||
],
|
||||
"testnet": [
|
||||
{
|
||||
"wif": "cSx7KzdH9EcvDEireu2WYpGnXdFYpta7sJUNt5kVCJgA7kcAU8Gm",
|
||||
"password": "1EBPIyj55eR8bVUov9",
|
||||
"encryptedKey": "6PYUAPLwLSEjWSAfoe9NTSPkMZXnJA8j8EFJtKaeSnP18RCouutBrS2735"
|
||||
},
|
||||
{
|
||||
"wif": "cRgunCa2z1gCN6nNapTwKLdo58FdgTeAiJSaXx6RZeWSabQHkQKG",
|
||||
"password": "9GKVkabAHBMyAf",
|
||||
"encryptedKey": "6PYTNQJ1dYhLg6X1Xqm62ceuyfxCUYvV4LfhFfzzBaTuV4cFhgS5Xe8t1Y"
|
||||
}
|
||||
]
|
||||
},
|
||||
"decrypt": {
|
||||
"mainnet": [
|
||||
{
|
||||
"wif": "L1XHKhaBAfkr2FJQn3pTfCMxz652WYfmvKj8xDCHCEDV9tWGcbYj",
|
||||
"password": "1EBPIyj55eR8bVUov9",
|
||||
"encryptedKey": "6PYWWnBNfNpSqEJZKcfwbrYgTTdb9PNiGjQJ8r9V6cvsZNKLfcZD8YefQc"
|
||||
},
|
||||
{
|
||||
"wif": "L1phBREbhL4vb1uHHHCAse8bdGE5c7ic2PFjRxMawLzQCsiFVbvu",
|
||||
"password": "9GKVkabAHBMyAf",
|
||||
"encryptedKey": "6PYU2fDHRVF2194gKDGkbFbeu4mFgkWtVvg2RPd2Sp6KmZx3RCHFpgBB2G"
|
||||
}
|
||||
],
|
||||
"testnet": [
|
||||
{
|
||||
"wif": "cSx7KzdH9EcvDEireu2WYpGnXdFYpta7sJUNt5kVCJgA7kcAU8Gm",
|
||||
"password": "1EBPIyj55eR8bVUov9",
|
||||
"encryptedKey": "6PYUAPLwLSEjWSAfoe9NTSPkMZXnJA8j8EFJtKaeSnP18RCouutBrS2735"
|
||||
},
|
||||
{
|
||||
"wif": "cRgunCa2z1gCN6nNapTwKLdo58FdgTeAiJSaXx6RZeWSabQHkQKG",
|
||||
"password": "9GKVkabAHBMyAf",
|
||||
"encryptedKey": "6PYTNQJ1dYhLg6X1Xqm62ceuyfxCUYvV4LfhFfzzBaTuV4cFhgS5Xe8t1Y"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
Unit test mocks for bitcore endpoints.
|
||||
*/
|
||||
|
||||
const balance = { confirmed: 230000, unconfirmed: 0, balance: 230000 }
|
||||
|
||||
const utxo = [
|
||||
{
|
||||
_id: "5cecdd39a9f1235e2a3d409a",
|
||||
chain: "BCH",
|
||||
network: "mainnet",
|
||||
coinbase: false,
|
||||
mintIndex: 0,
|
||||
spentTxid: "",
|
||||
mintTxid:
|
||||
"27ec8512c1a9ee9e9ae9b98eb60375f1d2bd60e2e76a1eff5a45afdbc517cf9c",
|
||||
mintHeight: 560430,
|
||||
spentHeight: -2,
|
||||
address: "qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
script: "76a914db6ea94fa26b7272dc5e1487c35f258391e0f38788ac",
|
||||
value: 100000,
|
||||
confirmations: -1
|
||||
},
|
||||
{
|
||||
_id: "5cecdd1ca9f1235e2a3b6349",
|
||||
chain: "BCH",
|
||||
network: "mainnet",
|
||||
coinbase: false,
|
||||
mintIndex: 0,
|
||||
spentTxid: "",
|
||||
mintTxid:
|
||||
"6e1ae1bf7db6de799ec1c05ab2816ac65549bd80141567af088e6f291385b07d",
|
||||
mintHeight: 560039,
|
||||
spentHeight: -2,
|
||||
address: "qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
script: "76a914db6ea94fa26b7272dc5e1487c35f258391e0f38788ac",
|
||||
value: 130000,
|
||||
confirmations: -1
|
||||
}
|
||||
]
|
||||
|
||||
module.exports = {
|
||||
balance,
|
||||
utxo
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
Mock data used for unit testing.
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
details: {
|
||||
hash: "000000001c6aeec19265e9cc3ded8ba5ef5e63fae7747f30bf9c02c7bc8883f0",
|
||||
size: 216,
|
||||
height: 507,
|
||||
version: 1,
|
||||
merkleroot:
|
||||
"a85fa3d831ab6b0305e7ff88d2d4941e25a810d4461635df51490653822071a8",
|
||||
tx: ["a85fa3d831ab6b0305e7ff88d2d4941e25a810d4461635df51490653822071a8"],
|
||||
time: 1231973656,
|
||||
nonce: 330467862,
|
||||
bits: "1d00ffff",
|
||||
difficulty: 1,
|
||||
chainwork:
|
||||
"000000000000000000000000000000000000000000000000000001fc01fc01fc",
|
||||
confirmations: 585104,
|
||||
previousblockhash:
|
||||
"00000000a99525c043fd7e323414b60add43c254c44860094048f9c01e9a5fdd",
|
||||
nextblockhash:
|
||||
"000000000d550f4161f2702165fdd782ec72ff9c541f864ebb8256b662b7e51a",
|
||||
reward: 50,
|
||||
isMainChain: true,
|
||||
poolInfo: {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
Unit test mocks for Blockbook endpoints.
|
||||
*/
|
||||
|
||||
const balance = {
|
||||
page: 1,
|
||||
totalPages: 1,
|
||||
itemsOnPage: 1000,
|
||||
address: "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf",
|
||||
balance: "230000",
|
||||
totalReceived: "6194528752",
|
||||
totalSent: "6194298752",
|
||||
unconfirmedBalance: "0",
|
||||
unconfirmedTxs: 0,
|
||||
txs: 3,
|
||||
txids: [
|
||||
"27ec8512c1a9ee9e9ae9b98eb60375f1d2bd60e2e76a1eff5a45afdbc517cf9c",
|
||||
"6e1ae1bf7db6de799ec1c05ab2816ac65549bd80141567af088e6f291385b07d",
|
||||
"5d95f4e6047901fc1502a9758bbdb14ce73f24662b1784d13e0217b3d37bb7a2"
|
||||
]
|
||||
}
|
||||
|
||||
const utxo = [
|
||||
{
|
||||
txid: "27ec8512c1a9ee9e9ae9b98eb60375f1d2bd60e2e76a1eff5a45afdbc517cf9c",
|
||||
vout: 0,
|
||||
value: "100000",
|
||||
height: 560430,
|
||||
confirmations: 29321
|
||||
},
|
||||
{
|
||||
txid: "6e1ae1bf7db6de799ec1c05ab2816ac65549bd80141567af088e6f291385b07d",
|
||||
vout: 0,
|
||||
value: "130000",
|
||||
height: 560039,
|
||||
confirmations: 29712
|
||||
}
|
||||
]
|
||||
|
||||
const utxos = [
|
||||
[
|
||||
{
|
||||
txid: "27ec8512c1a9ee9e9ae9b98eb60375f1d2bd60e2e76a1eff5a45afdbc517cf9c",
|
||||
vout: 0,
|
||||
value: "100000",
|
||||
height: 560430,
|
||||
confirmations: 29868
|
||||
},
|
||||
{
|
||||
txid: "6e1ae1bf7db6de799ec1c05ab2816ac65549bd80141567af088e6f291385b07d",
|
||||
vout: 0,
|
||||
value: "130000",
|
||||
height: 560039,
|
||||
confirmations: 30259
|
||||
}
|
||||
],
|
||||
[]
|
||||
]
|
||||
|
||||
module.exports = {
|
||||
balance,
|
||||
utxo,
|
||||
utxos
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
Mock data used for unit testing.
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
bestBlockHash:
|
||||
"0000000000000000008e1f65f875703872544aa888c7ca6587f055f8f5fbd4bf",
|
||||
|
||||
blockHeader: {
|
||||
hash: "000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201",
|
||||
confirmations: 85727,
|
||||
height: 500000,
|
||||
version: 536870912,
|
||||
versionHex: "20000000",
|
||||
merkleroot:
|
||||
"4af279645e1b337e655ae3286fc2ca09f58eb01efa6ab27adedd1e9e6ec19091",
|
||||
time: 1509343584,
|
||||
mediantime: 1509336533,
|
||||
nonce: 3604508752,
|
||||
bits: "1809b91a",
|
||||
difficulty: 113081236211.4533,
|
||||
chainwork:
|
||||
"0000000000000000000000000000000000000000007ae48aca46e3b449ad9714",
|
||||
previousblockhash:
|
||||
"0000000000000000043831d6ebb013716f0580287ee5e5687e27d0ed72e6e523",
|
||||
nextblockhash:
|
||||
"00000000000000000568f0a96bf4348847bc84e455cbfec389f27311037a20f3"
|
||||
},
|
||||
|
||||
txOutProof:
|
||||
"0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01",
|
||||
|
||||
verifiedProof:
|
||||
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7",
|
||||
|
||||
txOutUnspent: {
|
||||
bestblock:
|
||||
"000000000000000000b441e02f5b1b9f5b3def961047afcc6f2f5636c952705e",
|
||||
confirmations: 2,
|
||||
value: 0.00006,
|
||||
scriptPubKey: {
|
||||
asm:
|
||||
"OP_DUP OP_HASH160 d19fae66b685f5c3633c0db0600313918347225f OP_EQUALVERIFY OP_CHECKSIG",
|
||||
hex: "76a914d19fae66b685f5c3633c0db0600313918347225f88ac",
|
||||
reqSigs: 1,
|
||||
type: "pubkeyhash",
|
||||
addresses: ["bitcoincash:qrgeltnxk6zltsmr8sxmqcqrzwgcx3eztusrwgf0x3"]
|
||||
},
|
||||
coinbase: false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"getBestBlockHash": [
|
||||
{ "data":
|
||||
{ "result": "0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d"}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"sha256": [
|
||||
{
|
||||
"hash": "04abc8821a06e5a30937967d11ad10221cb5ac3b5273e434f1284ee87129a061",
|
||||
"hex": "0101010101010101"
|
||||
},
|
||||
{
|
||||
"hash": "75618d82d1f6251f2ef1f42f5f0d5040330948a707ff6d69720dbdcb00b48aab",
|
||||
"hex": "031ad329b3117e1d1e2974406868e575d48cff88e8128ba0eedb10da053785033b"
|
||||
},
|
||||
{
|
||||
"hash": "978c09dd46091d1922fa01e9f4a975b91a371f26ba8399de27d53801152121de",
|
||||
"hex": "03123464075c7a5fa6b8680afa2c962a02e7bf071c6b2395b0ac711d462cac9354"
|
||||
},
|
||||
{
|
||||
"hash": "243e5ec9798d6ac435b30661528d8d83745543f517b8adac421a76fbe7f08105",
|
||||
"hex": "03ea9277ebf3d6edd26847fb109494def7d458f05e6e4fba381c094ce703c62248"
|
||||
},
|
||||
{
|
||||
"hash": "1304a815512047082dba9a9414ff0db643dbbf9eeb68527195f79cc26b021e10",
|
||||
"hex": "020379254cc10ef94976192ab42cab25f65ba4438e4b2b4610debd145d2bdb8d53"
|
||||
}
|
||||
],
|
||||
"ripemd160": [
|
||||
{
|
||||
"hash": "5825701b4b9767fd35063b286dca3582853e0630",
|
||||
"hex": "0101010101010101"
|
||||
},
|
||||
{
|
||||
"hash": "8874ef888a9bcbd83b87d06ff7bc213c51497362",
|
||||
"hex": "75618d82d1f6251f2ef1f42f5f0d5040330948a707ff6d69720dbdcb00b48aab"
|
||||
},
|
||||
{
|
||||
"hash": "5f956a88863051ea5215d8970ced8e218eb615cf",
|
||||
"hex": "978c09dd46091d1922fa01e9f4a975b91a371f26ba8399de27d53801152121de"
|
||||
},
|
||||
{
|
||||
"hash": "1fc790f399d3064cdf917c6b22bb0ef534fe35c9",
|
||||
"hex": "243e5ec9798d6ac435b30661528d8d83745543f517b8adac421a76fbe7f08105"
|
||||
},
|
||||
{
|
||||
"hash": "abd7091d8c4bd1e2c074f125870427f3dc0c0ce9",
|
||||
"hex": "1304a815512047082dba9a9414ff0db643dbbf9eeb68527195f79cc26b021e10"
|
||||
}
|
||||
],
|
||||
"hash256": [
|
||||
{
|
||||
"hash": "728338d99f356175c4945ef5cccfa61b7b56143cbbf426ddd0e0fc7cfe8c3c23",
|
||||
"hex": "0101010101010101"
|
||||
},
|
||||
{
|
||||
"hash": "7ad2a74bd59698714a2991a82b71736f3542b2828b6ac24de427c440da89d01a",
|
||||
"hex": "031ad329b3117e1d1e2974406868e575d48cff88e8128ba0eedb10da053785033b"
|
||||
},
|
||||
{
|
||||
"hash": "688f1d029ed54c34d0320b838bf6fc64f62f38a6e930a0af5bdb4e27d1a684cd",
|
||||
"hex": "03123464075c7a5fa6b8680afa2c962a02e7bf071c6b2395b0ac711d462cac9354"
|
||||
},
|
||||
{
|
||||
"hash": "46f3c4ddfa908cf8a3cda8ce3a676d98fec149d97db834a6e8f071790d839c52",
|
||||
"hex": "03ea9277ebf3d6edd26847fb109494def7d458f05e6e4fba381c094ce703c62248"
|
||||
},
|
||||
{
|
||||
"hash": "72cfe7b6b9402a4463dfc8bc1c08080578b1b82a2e3e632062e2cce2c9327c1f",
|
||||
"hex": "020379254cc10ef94976192ab42cab25f65ba4438e4b2b4610debd145d2bdb8d53"
|
||||
}
|
||||
],
|
||||
"hash160": [
|
||||
{
|
||||
"hash": "abaf1119f83e384210fe8e222eac76e2f0da39dc",
|
||||
"hex": "0101010101010101"
|
||||
},
|
||||
{
|
||||
"hash": "8874ef888a9bcbd83b87d06ff7bc213c51497362",
|
||||
"hex": "031ad329b3117e1d1e2974406868e575d48cff88e8128ba0eedb10da053785033b"
|
||||
},
|
||||
{
|
||||
"hash": "5f956a88863051ea5215d8970ced8e218eb615cf",
|
||||
"hex": "03123464075c7a5fa6b8680afa2c962a02e7bf071c6b2395b0ac711d462cac9354"
|
||||
},
|
||||
{
|
||||
"hash": "1fc790f399d3064cdf917c6b22bb0ef534fe35c9",
|
||||
"hex": "03ea9277ebf3d6edd26847fb109494def7d458f05e6e4fba381c094ce703c62248"
|
||||
},
|
||||
{
|
||||
"hash": "abd7091d8c4bd1e2c074f125870427f3dc0c0ce9",
|
||||
"hex": "020379254cc10ef94976192ab42cab25f65ba4438e4b2b4610debd145d2bdb8d53"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
{
|
||||
"fromWIF": [
|
||||
{
|
||||
"privateKeyWIF": "L5PKiCuwwgmVN1GQNg8CdR6Rmg7tg1Npw7GyL5ULRPZ5EVPhtSrz",
|
||||
"legacy": "1P23VhvFLH18qP7YRCPDWPwA9TCJjmp9B5",
|
||||
"cashAddr": "bitcoincash:qrcc23q0w7wgld690kduxvhetu0am523c5ufq5pes4",
|
||||
"regtestAddr": "bchreg:qrcc23q0w7wgld690kduxvhetu0am523c5z8jjqa50"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"legacy": "14tqru6iL3KX2m4nKg36tfLFe13J1d1uwu",
|
||||
"cashAddr": "bitcoincash:qq4tvcxq5z35pkfj65a2elyy8xpn0r55r59r5he7nz",
|
||||
"regtestAddr": "bchreg:qq4tvcxq5z35pkfj65a2elyy8xpn0r55r5mdx3c6hc"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L57L3Xtu3j1Z2B2RuQzc59JLQXJQ86TH8To1hM348URbC2iCZqLe",
|
||||
"legacy": "135cNoFyxcwJ88BQsJd7c6qKfSBgRK7cCT",
|
||||
"cashAddr": "bitcoincash:qqtv7uskar0nd8hyflesg7wq4uuqwdmtyg4hsx9kge",
|
||||
"regtestAddr": "bchreg:qqtv7uskar0nd8hyflesg7wq4uuqwdmtygtezqyjvr"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzTm29RBrSgUbMyeJL9sCNUnc7LQEuDeT6Upq1iUwx78qWRdRzyW",
|
||||
"legacy": "1NbRysVu1cy8A8mjrLh4z649HqG6DrX9Z",
|
||||
"cashAddr": "bitcoincash:qqzp270mhkglttfaysmt985aykwjhndw0ulmgr5g5d",
|
||||
"regtestAddr": "bchreg:qqzp270mhkglttfaysmt985aykwjhndw0up4694vsh"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L4BwXDmjzEyzKHbAfGruhieUDPs8KTx7DMgqPk4aF9GefzgqPENV",
|
||||
"legacy": "1FoZGWj8rgrimR7W383LNSLUfdPCjKAXLK",
|
||||
"cashAddr": "bitcoincash:qz39l492msv9zz838t8ltx2w4zmycnqhwck4fnnyym",
|
||||
"regtestAddr": "bchreg:qz39l492msv9zz838t8ltx2w4zmycnqhwcgmm4jqqp"
|
||||
}
|
||||
],
|
||||
"toWIF": [
|
||||
{
|
||||
"privateKeyWIF": "L5PKiCuwwgmVN1GQNg8CdR6Rmg7tg1Npw7GyL5ULRPZ5EVPhtSrz"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L57L3Xtu3j1Z2B2RuQzc59JLQXJQ86TH8To1hM348URbC2iCZqLe"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzTm29RBrSgUbMyeJL9sCNUnc7LQEuDeT6Upq1iUwx78qWRdRzyW"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L4BwXDmjzEyzKHbAfGruhieUDPs8KTx7DMgqPk4aF9GefzgqPENV"
|
||||
}
|
||||
],
|
||||
"fromPublicKey": [
|
||||
{
|
||||
"pubkeyHex": "02fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb",
|
||||
"legacy": "1SeP7kmdWTwjFmWiRMpqtSkDpW39zrVLK",
|
||||
"cashAddr": "bitcoincash:qqzdnxncgm3v247u5v0gqnglr2vpdhe0hu4wl0rmwt",
|
||||
"regtestAddr": "bchreg:qqzdnxncgm3v247u5v0gqnglr2vpdhe0hutqdfzl23"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "02d305772e0873fba6c1c7ff353ce374233316eb5820acd7ff3d7d9b82d514126b",
|
||||
"legacy": "1GpugKfjEycPRhk8A8ALPh1zAJmTQGdJPp",
|
||||
"cashAddr": "bitcoincash:qzkej6g2zr9c9k83chyqh5pllzv6pkw62ckf2m82ks",
|
||||
"regtestAddr": "bchreg:qzkej6g2zr9c9k83chyqh5pllzv6pkw62cg8caxwj2"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "02d305772e0873fba6c1c7ff353ce374233316eb5820acd7ff3d7d9b82d514126b",
|
||||
"legacy": "1GpugKfjEycPRhk8A8ALPh1zAJmTQGdJPp",
|
||||
"cashAddr": "bitcoincash:qzkej6g2zr9c9k83chyqh5pllzv6pkw62ckf2m82ks",
|
||||
"regtestAddr": "bchreg:qzkej6g2zr9c9k83chyqh5pllzv6pkw62cg8caxwj2"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "033c071f19057f11140f80308031fa58b6e7d8f9e889252805cae6a29c1248f843",
|
||||
"legacy": "15NQKRj7rAVsFL5rWMmhkAgx2K1dYoHoDW",
|
||||
"cashAddr": "bitcoincash:qqh7evl4w7h6lsu7uvakvadm0z5hj535lqk098l670",
|
||||
"regtestAddr": "bchreg:qqh7evl4w7h6lsu7uvakvadm0z5hj535lqgphp7764"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "024933d7cc962415fda8249d6ee6820009fb6f0cf592385d91f8d9f39de507b7e1",
|
||||
"legacy": "14sq5dL1TeFdQJpj3vVMQvjrdmQoqVoM6m",
|
||||
"cashAddr": "bitcoincash:qq4g2nmk64wt7a2mx85cl07n45nkh2p7lcytfgmqdl",
|
||||
"regtestAddr": "bchreg:qq4g2nmk64wt7a2mx85cl07n45nkh2p7lc69mw6yf9"
|
||||
}
|
||||
],
|
||||
"toPublicKey": [
|
||||
{
|
||||
"pubkeyHex": "02fb721b92025e775b1b84774e65d568d24645cb633275f5c26f5c3101b214a8fb"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "02d305772e0873fba6c1c7ff353ce374233316eb5820acd7ff3d7d9b82d514126b"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "02d305772e0873fba6c1c7ff353ce374233316eb5820acd7ff3d7d9b82d514126b"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "033c071f19057f11140f80308031fa58b6e7d8f9e889252805cae6a29c1248f843"
|
||||
},
|
||||
{
|
||||
"pubkeyHex": "024933d7cc962415fda8249d6ee6820009fb6f0cf592385d91f8d9f39de507b7e1"
|
||||
}
|
||||
],
|
||||
"toLegacyAddress": [
|
||||
{
|
||||
"privateKeyWIF": "L5PKiCuwwgmVN1GQNg8CdR6Rmg7tg1Npw7GyL5ULRPZ5EVPhtSrz",
|
||||
"legacy": "1P23VhvFLH18qP7YRCPDWPwA9TCJjmp9B5"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"legacy": "14tqru6iL3KX2m4nKg36tfLFe13J1d1uwu"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L57L3Xtu3j1Z2B2RuQzc59JLQXJQ86TH8To1hM348URbC2iCZqLe",
|
||||
"legacy": "135cNoFyxcwJ88BQsJd7c6qKfSBgRK7cCT"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzTm29RBrSgUbMyeJL9sCNUnc7LQEuDeT6Upq1iUwx78qWRdRzyW",
|
||||
"legacy": "1NbRysVu1cy8A8mjrLh4z649HqG6DrX9Z"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L4BwXDmjzEyzKHbAfGruhieUDPs8KTx7DMgqPk4aF9GefzgqPENV",
|
||||
"legacy": "1FoZGWj8rgrimR7W383LNSLUfdPCjKAXLK"
|
||||
}
|
||||
],
|
||||
"toCashAddress": [
|
||||
{
|
||||
"privateKeyWIF": "L5PKiCuwwgmVN1GQNg8CdR6Rmg7tg1Npw7GyL5ULRPZ5EVPhtSrz",
|
||||
"cashAddr": "bitcoincash:qrcc23q0w7wgld690kduxvhetu0am523c5ufq5pes4",
|
||||
"regtestAddr": "bchreg:qrcc23q0w7wgld690kduxvhetu0am523c5z8jjqa50"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"cashAddr": "bitcoincash:qq4tvcxq5z35pkfj65a2elyy8xpn0r55r59r5he7nz",
|
||||
"regtestAddr": "bchreg:qq4tvcxq5z35pkfj65a2elyy8xpn0r55r5mdx3c6hc"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L57L3Xtu3j1Z2B2RuQzc59JLQXJQ86TH8To1hM348URbC2iCZqLe",
|
||||
"cashAddr": "bitcoincash:qqtv7uskar0nd8hyflesg7wq4uuqwdmtyg4hsx9kge",
|
||||
"regtestAddr": "bchreg:qqtv7uskar0nd8hyflesg7wq4uuqwdmtygtezqyjvr"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzTm29RBrSgUbMyeJL9sCNUnc7LQEuDeT6Upq1iUwx78qWRdRzyW",
|
||||
"cashAddr": "bitcoincash:qqzp270mhkglttfaysmt985aykwjhndw0ulmgr5g5d",
|
||||
"regtestAddr": "bchreg:qqzp270mhkglttfaysmt985aykwjhndw0up4694vsh"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L4BwXDmjzEyzKHbAfGruhieUDPs8KTx7DMgqPk4aF9GefzgqPENV",
|
||||
"cashAddr": "bitcoincash:qz39l492msv9zz838t8ltx2w4zmycnqhwck4fnnyym",
|
||||
"regtestAddr": "bchreg:qz39l492msv9zz838t8ltx2w4zmycnqhwcgmm4jqqp"
|
||||
}
|
||||
],
|
||||
"sign": [
|
||||
{
|
||||
"privateKeyWIF": "L5PKiCuwwgmVN1GQNg8CdR6Rmg7tg1Npw7GyL5ULRPZ5EVPhtSrz",
|
||||
"data": "EARTH"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"data": "foobar"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L57L3Xtu3j1Z2B2RuQzc59JLQXJQ86TH8To1hM348URbC2iCZqLe",
|
||||
"data": "12334567890"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzTm29RBrSgUbMyeJL9sCNUnc7LQEuDeT6Upq1iUwx78qWRdRzyW",
|
||||
"data": "Be excellent to each other"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L4BwXDmjzEyzKHbAfGruhieUDPs8KTx7DMgqPk4aF9GefzgqPENV",
|
||||
"data": "satoshi"
|
||||
}
|
||||
],
|
||||
"verify": [
|
||||
{
|
||||
"privateKeyWIF1": "L5PKiCuwwgmVN1GQNg8CdR6Rmg7tg1Npw7GyL5ULRPZ5EVPhtSrz",
|
||||
"privateKeyWIF2": "L4BwXDmjzEyzKHbAfGruhieUDPs8KTx7DMgqPk4aF9GefzgqPENV",
|
||||
"data": "EARTH"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"privateKeyWIF2": "L5PKiCuwwgmVN1GQNg8CdR6Rmg7tg1Npw7GyL5ULRPZ5EVPhtSrz",
|
||||
"data": "foobar"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "L57L3Xtu3j1Z2B2RuQzc59JLQXJQ86TH8To1hM348URbC2iCZqLe",
|
||||
"privateKeyWIF2": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"data": "12334567890"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "KzTm29RBrSgUbMyeJL9sCNUnc7LQEuDeT6Upq1iUwx78qWRdRzyW",
|
||||
"privateKeyWIF2": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"data": "Be excellent to each other"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "L4BwXDmjzEyzKHbAfGruhieUDPs8KTx7DMgqPk4aF9GefzgqPENV",
|
||||
"privateKeyWIF2": "L1SD3NYLMcoqpUzn2hwJ7c1Vb4pPiqMToSMyGMTcbcvRBDh9U9SP",
|
||||
"data": "satoshi"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
Mocking data for unit tests for the ElectrumX library.
|
||||
*/
|
||||
|
||||
const utxo = {
|
||||
success: true,
|
||||
utxos: [
|
||||
{
|
||||
height: 602405,
|
||||
tx_hash:
|
||||
"2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7",
|
||||
tx_pos: 0,
|
||||
value: 1000
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const utxos = {
|
||||
success: true,
|
||||
utxos: [
|
||||
{
|
||||
utxos: [
|
||||
{
|
||||
height: 604392,
|
||||
tx_hash:
|
||||
"7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41",
|
||||
tx_pos: 0,
|
||||
value: 1000
|
||||
},
|
||||
{
|
||||
height: 630834,
|
||||
tx_hash:
|
||||
"4fe60a51e0d8f5134bfd8e5f872d6e502d7f01b28a6afebb27f4438a4f638d53",
|
||||
tx_pos: 0,
|
||||
value: 6000
|
||||
}
|
||||
],
|
||||
address: "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
},
|
||||
{
|
||||
utxos: [],
|
||||
address: "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const balance = {
|
||||
success: true,
|
||||
balance: {
|
||||
confirmed: 1000,
|
||||
unconfirmed: 0
|
||||
}
|
||||
}
|
||||
|
||||
const balances = {
|
||||
success: true,
|
||||
balances: [
|
||||
{
|
||||
balance: {
|
||||
confirmed: 7000,
|
||||
unconfirmed: 0
|
||||
},
|
||||
address: "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"
|
||||
},
|
||||
{
|
||||
balance: {
|
||||
confirmed: 0,
|
||||
unconfirmed: 0
|
||||
},
|
||||
address: "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const transaction = {
|
||||
success: true,
|
||||
transactions: [
|
||||
{
|
||||
height: 560430,
|
||||
tx_hash:
|
||||
"3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851"
|
||||
},
|
||||
{
|
||||
height: 560534,
|
||||
tx_hash:
|
||||
"4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const transactions = {
|
||||
success: true,
|
||||
transactions: [
|
||||
{
|
||||
transactions: [
|
||||
{
|
||||
height: 631219,
|
||||
tx_hash:
|
||||
"ae2daa01c8172545b5edd205ea438706bcb74e63d4084a26b9ff2a46d46dc97f"
|
||||
}
|
||||
],
|
||||
address: "bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj"
|
||||
},
|
||||
{
|
||||
transactions: [
|
||||
{
|
||||
height: 560430,
|
||||
tx_hash:
|
||||
"3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851"
|
||||
},
|
||||
{
|
||||
height: 560534,
|
||||
tx_hash:
|
||||
"4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280"
|
||||
}
|
||||
],
|
||||
address: "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
utxo,
|
||||
utxos,
|
||||
balance,
|
||||
balances,
|
||||
transaction,
|
||||
transactions
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
Mock data used for unit tests against the Encryption library.
|
||||
*/
|
||||
|
||||
const successMock = {
|
||||
success: true,
|
||||
publicKey:
|
||||
"03fcc37586d93af1e146238217989924e0ab1f011c34e1a23aec529354d5b28eb4"
|
||||
}
|
||||
|
||||
const failureMock = {
|
||||
success: false,
|
||||
publicKey: "not found"
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
successMock,
|
||||
failureMock
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
{
|
||||
"toXPub": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"xpub": "xpub661MyMwAqRbcGedwRJEC3DjCdtR3aQChzBzrGuLs1ou9ynjKoMBivmYEmQP3Acfg1azWxBmzSmQi7rLPMFbqtus8LZQngeVkSSqU63UabpZ"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"xpub": "xpub661MyMwAqRbcEchwVMh1yv3z9qDniozsh9niTRpwh12zG1FvGxTjRbMXMLYx2AszH2eQDSxNnq1TUzcGZFWPZt9qLRracrs3Hc2vZNmJHyj"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"xpub": "xpub661MyMwAqRbcGSmyx3bRW9NhjR3F1Agh9c1d4Hbu8SfdoiC23LXoA2n6T6sZQZybp8ZyjpxN9we9LXwKraVARdwsVMuL8BYFYC3TP3FX2Jx"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"xpub": "xpub661MyMwAqRbcGkg9gnqwWnxq5KsvMkFsGrjoSYUZKmS19rwiUXGYzZ8wRYXXwxrTpNFN9tiqrB6nDEFEGmaQfz9jfBqio3YsBW8asrh5d2r"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"xpub": "xpub661MyMwAqRbcFVDUv6gAfL63Z55XDyT1mNePiUKktmVcL426ZHWz5GRssSZ5PHCrKQgPKui7rRGiiNMSfvt3vJ6V4NqbSsNqgoEeimsyHrJ"
|
||||
}
|
||||
],
|
||||
"toXPriv": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"xpriv": "xprv9s21ZrQH143K4AZUKGhBg5nU5raZAwUrcy5FUWwFTUNB6zQBFosUNyDkv8EmFd1V4ASGt7d8sJ8sBem1DB8asw38K4cccN6azVCssnyfb4t"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"xpriv": "xprv9s21ZrQH143K28dUPLA1cn7FboPJKMH2Kvs7f3RL8fW1PCvmjR9Uso33W5M1PvysLBcnhhj9DvW5CUviWa6iswxv9QBYnmcsNKjonHwEZpj"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"xpriv": "xprv9s21ZrQH143K3xhWr24R91RyBPCkbhxqnP62FuCHa78evursVoDYcETcbprrDaiaoxhqieMCzM48THvTGM3b9hTb4FKHUoJrrMsX1cWw2G1"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"xpriv": "xprv9s21ZrQH143K4GbgamJw9f26XJ3RxHY1udpCeA4wmRu2H4cZvyxJSkpTaHReJUj5sjRWAfm8WkNChP29GdmkZcwjvWxVrWTe7vmXsx3XZHv"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"xpriv": "xprv9s21ZrQH143K3191p59AJC9K13F2pWjAQ9inv5v9LRxdTFgx1kCjXU7Q2ACdAm7P432XP8MjAoTHW9dDxjbFpfRqv7cu3hkn9u5ZtBQs3Vi"
|
||||
}
|
||||
],
|
||||
"toKeyPair": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe"
|
||||
}
|
||||
],
|
||||
"toPublicKey": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe"
|
||||
}
|
||||
],
|
||||
"derive": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"xpub": "xpub68gU3eZPcTu8CCNt5rky8yvMxD4VAmUujkprpEAQj7MtYX7JziPNfGjvmtnmdk6HKD2XUdSTHq3cTk1QafQsgUcUsHcPdCJ8pud8dvDo2Vb",
|
||||
"xpriv": "xprv9uh7e92Vn6LpyiJQyqDxmqydQBDzmJm4NXuG1qkoAmpufinATB587URSvepj7Leu2Qg6EZwwrmYZqD64M3C7izCWaaGkzMPwknFgbmjLAfP"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"xpub": "xpub698V4vD7nYSXEeVd8a4txiscubcaQBUSB9ZjhRSdbzCXmD81UG6P3AidHwudaUatfuX5nsB7iwUnn6M4Q21pX1nkB5G4X1zb4dCxNm7DG54",
|
||||
"xpriv": "xprv9v98fQgDxAtE2ARA2YXtbavtMZn5zikaove8u3323efYtQnrvin8VNQ9SeNJkJNxRhGGG3Eavc8edbGiiS6nr6MSdNCexgv8uYp5Ee6ctmH"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"xpub": "xpub69hicEP7JPwB9241jVA1ZGBhRfyhUXrxF25gpfN532wL8H6weGE7kwjLoyHvHFQPoeGk7MVsAq7129eFQBHhhc4Zpa64RvLpL8u6uMV6ywG",
|
||||
"xpriv": "xprv9viNCirDU2NsvXyYdTd1C8Exse9D5596soA62GxTUhQMFUmo6iusD9QrxiLPcLF2TUrxPPZLife9ubNCxpa378FLrUbGb8wqN7vtN1zZ8Jg"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"xpub": "xpub69eRZ9j2Qu22pbQDzPNNcRJHZZu5wwMpJCsaHWbGUs28fjf9rCxN2UhcnrgbRpbaK9m1hj6qXnUHUb8C4pHFsyqhqhLMXdi2wRmUWXpJRpE",
|
||||
"xpriv": "xprv9vf59eC8aXTjc7KktMqNFHMZ1Y4bYUdxvywyV8BevXV9nwL1Jfe7UgP8wYxkmGAL1qC9dRUS67HCMagx8pH566LkVFcen7DJDoCCtEbGB5g"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"xpub": "xpub69f9C5sYoihLrxJX4ixujbortnFkuXXW7xY5A5G5X6Ho4MhWzzKRjkgDbt1zRVeSD5tj91yFQ4p8qg6oCjr1HwFsMpSZBzUjm5nUo1eRwwA",
|
||||
"xpriv": "xprv9vfnnaLeyM93eUE3xhRuNTs8LkRGW4oekjcUMgrTxkkpBZNNTT1BBxMjkd6yNH5trjDw3wnYoXUZLCUs6xhs9sUfgNi1ufBkLJoCFXWsL3R"
|
||||
}
|
||||
],
|
||||
"deriveHardened": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"xpub": "xpub68gU3eZXx8S6MyhU1WTL8TyeaNYQ8yqutgPernats3dwvpqDMYv6VJbEi5Eqa6cPYe58wTWJjzSbbTMmVVpJxmwAfLs6BQoAxS1YpggMCrV",
|
||||
"xpriv": "xprv9uh7e92e7kso9VczuUvKmL2v2LhujX84XTU44QBHJi6y42W4p1bqwWGkrqdmPoJHAKNSXA399Unq9DRbJ5KkHLFUsSa7NMGjE2r3A98nd97"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"xpub": "xpub698V4vDG8CyVRafuqQjpVoqLr6NFUUwJFC4sgfj27RtP7Y2EGw1hwS3EUTzvDrDFZYMp5riwMJrhWKUv8HuNS2M5PVjzkDjFxbuboVNA39h",
|
||||
"xpriv": "xprv9v98fQgNHqRCD6bSjPCp8ftcJ4Xm52DSsy9GtHKQZ6MQEjh5jPhTPdikdE1MW1A8RGjv77qqqNYnGZHdDYEjMXgNU6mxHkLGLaePduedXWm"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"xpub": "xpub69hicEPFe4U9M3iKudDvQUcJEiuTXnjVpP3r7QfFMtXmwvBqFdq654QBjFkdb6K3RXinFySyQxPZTsyP7Nu56xqUMfiksCLaaU4o7j2TN5e",
|
||||
"xpriv": "xprv9viNCirMogur8Zdrobgv3LfZgh4y8L1eTA8FK2FdoYzo57rgi6WqXG5hszQufNumyFzLsiXYbZRWj35qcDQHQNP4BFtriHD6Z3J9KtkqSwY"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"xpub": "xpub69eRZ9jAkZZ128YH5uj3qkat4iUu7vogszErxHPdpFSbKhtQMkhSaGGr7nqQnV7pn2M9TR4bhfFMuPv8t3m9aAzrXLTucyfYKubKHsVV7a1",
|
||||
"xpriv": "xprv9vf59eCGvBzhoeToytC3Uce9WgeQiU5qWmKG9tz2FuucSuZFpDPC2TxNGY1gAqAmWyyq1Z9DKhyXiEgDYVt4Q3eptWdbASYm82ohkDyBjQo"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"xpub": "xpub69f9C5sh9PEK1QpikAfEcqvJtn9SoPFDieM91SPDczSb5zBBn5MmZ4wRCsKyeDJBHnavxzqZ2hwDBDdVnyBZuppPVXxH3LUrXsHB6Lx9nLe",
|
||||
"xpriv": "xprv9vfnnaLoK1g1nvkFe98EFhyaLkJxPvXNMRRYD3yc4eucDBr3EY3X1GcwMbfUHssRHAYnvHonMbQP5Dm9s56N4Moj32fwCSC6kGU6SbHTm3D"
|
||||
}
|
||||
],
|
||||
"derivePath": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"xpub": "xpub68gU3eZPcTu8CCNt5rky8yvMxD4VAmUujkprpEAQj7MtYX7JziPNfGjvmtnmdk6HKD2XUdSTHq3cTk1QafQsgUcUsHcPdCJ8pud8dvDo2Vb",
|
||||
"xpriv": "xprv9uh7e92Vn6LpyiJQyqDxmqydQBDzmJm4NXuG1qkoAmpufinATB587URSvepj7Leu2Qg6EZwwrmYZqD64M3C7izCWaaGkzMPwknFgbmjLAfP"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"xpub": "xpub698V4vD7nYSXEeVd8a4txiscubcaQBUSB9ZjhRSdbzCXmD81UG6P3AidHwudaUatfuX5nsB7iwUnn6M4Q21pX1nkB5G4X1zb4dCxNm7DG54",
|
||||
"xpriv": "xprv9v98fQgDxAtE2ARA2YXtbavtMZn5zikaove8u3323efYtQnrvin8VNQ9SeNJkJNxRhGGG3Eavc8edbGiiS6nr6MSdNCexgv8uYp5Ee6ctmH"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"xpub": "xpub69hicEP7JPwB9241jVA1ZGBhRfyhUXrxF25gpfN532wL8H6weGE7kwjLoyHvHFQPoeGk7MVsAq7129eFQBHhhc4Zpa64RvLpL8u6uMV6ywG",
|
||||
"xpriv": "xprv9viNCirDU2NsvXyYdTd1C8Exse9D5596soA62GxTUhQMFUmo6iusD9QrxiLPcLF2TUrxPPZLife9ubNCxpa378FLrUbGb8wqN7vtN1zZ8Jg"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"xpub": "xpub69eRZ9j2Qu22pbQDzPNNcRJHZZu5wwMpJCsaHWbGUs28fjf9rCxN2UhcnrgbRpbaK9m1hj6qXnUHUb8C4pHFsyqhqhLMXdi2wRmUWXpJRpE",
|
||||
"xpriv": "xprv9vf59eC8aXTjc7KktMqNFHMZ1Y4bYUdxvywyV8BevXV9nwL1Jfe7UgP8wYxkmGAL1qC9dRUS67HCMagx8pH566LkVFcen7DJDoCCtEbGB5g"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"xpub": "xpub69f9C5sYoihLrxJX4ixujbortnFkuXXW7xY5A5G5X6Ho4MhWzzKRjkgDbt1zRVeSD5tj91yFQ4p8qg6oCjr1HwFsMpSZBzUjm5nUo1eRwwA",
|
||||
"xpriv": "xprv9vfnnaLeyM93eUE3xhRuNTs8LkRGW4oekjcUMgrTxkkpBZNNTT1BBxMjkd6yNH5trjDw3wnYoXUZLCUs6xhs9sUfgNi1ufBkLJoCFXWsL3R"
|
||||
}
|
||||
],
|
||||
"deriveHardenedPath": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"xpub": "xpub68gU3eZXx8S6MyhU1WTL8TyeaNYQ8yqutgPernats3dwvpqDMYv6VJbEi5Eqa6cPYe58wTWJjzSbbTMmVVpJxmwAfLs6BQoAxS1YpggMCrV",
|
||||
"xpriv": "xprv9uh7e92e7kso9VczuUvKmL2v2LhujX84XTU44QBHJi6y42W4p1bqwWGkrqdmPoJHAKNSXA399Unq9DRbJ5KkHLFUsSa7NMGjE2r3A98nd97"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"xpub": "xpub698V4vDG8CyVRafuqQjpVoqLr6NFUUwJFC4sgfj27RtP7Y2EGw1hwS3EUTzvDrDFZYMp5riwMJrhWKUv8HuNS2M5PVjzkDjFxbuboVNA39h",
|
||||
"xpriv": "xprv9v98fQgNHqRCD6bSjPCp8ftcJ4Xm52DSsy9GtHKQZ6MQEjh5jPhTPdikdE1MW1A8RGjv77qqqNYnGZHdDYEjMXgNU6mxHkLGLaePduedXWm"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"xpub": "xpub69hicEPFe4U9M3iKudDvQUcJEiuTXnjVpP3r7QfFMtXmwvBqFdq654QBjFkdb6K3RXinFySyQxPZTsyP7Nu56xqUMfiksCLaaU4o7j2TN5e",
|
||||
"xpriv": "xprv9viNCirMogur8Zdrobgv3LfZgh4y8L1eTA8FK2FdoYzo57rgi6WqXG5hszQufNumyFzLsiXYbZRWj35qcDQHQNP4BFtriHD6Z3J9KtkqSwY"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"xpub": "xpub69eRZ9jAkZZ128YH5uj3qkat4iUu7vogszErxHPdpFSbKhtQMkhSaGGr7nqQnV7pn2M9TR4bhfFMuPv8t3m9aAzrXLTucyfYKubKHsVV7a1",
|
||||
"xpriv": "xprv9vf59eCGvBzhoeToytC3Uce9WgeQiU5qWmKG9tz2FuucSuZFpDPC2TxNGY1gAqAmWyyq1Z9DKhyXiEgDYVt4Q3eptWdbASYm82ohkDyBjQo"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"xpub": "xpub69f9C5sh9PEK1QpikAfEcqvJtn9SoPFDieM91SPDczSb5zBBn5MmZ4wRCsKyeDJBHnavxzqZ2hwDBDdVnyBZuppPVXxH3LUrXsHB6Lx9nLe",
|
||||
"xpriv": "xprv9vfnnaLoK1g1nvkFe98EFhyaLkJxPvXNMRRYD3yc4eucDBr3EY3X1GcwMbfUHssRHAYnvHonMbQP5Dm9s56N4Moj32fwCSC6kGU6SbHTm3D"
|
||||
}
|
||||
],
|
||||
"deriveBIP44": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"xpub": "xpub6CUjAgu7fDFsW63QGEe8T6XMfjh8PA2dHP7GQBwpRQSniWEY5VmA1CjQJ93s3BqT9VkML8qytP6rgJSf5jvP3bqzN7CTiwTxPo2ZpEuhQ6N",
|
||||
"xpriv": "xprv9yVNmBNDpqhaHbxwAD785xad7hrdyhJmvABfboYCs4uoqhuPXxSuTQQvSrRUXpN8it1sZvhKpxQ7pbHJb5aQ8Vghc51SCpWijdHZmWGMKp1"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"xpub": "xpub6CTS16pXaVuu7Uj6D7AcMhomMJ45DqaKCdUY8TYmkAuwDCaarsBhLRzHrVcLooPgTPnRF1mQSbUmfPWg3bVu2tWHuB7zzNbsDGbUHWZ6FCZ",
|
||||
"xpriv": "xprv9yU5bbHdk8Mbtzed75dbzZs2oGDapNrTqQYwL59ABqNxLQFSKKsSndfp1DkQNF1JiCDZfN3JLGdUtn5tBZ9V9i3uhjX1ymBVdsCt3kqAtXb"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"xpub": "xpub6CjWtuhSaU64a1vhqxT81EbcTw5GksMTgtNwU1uXGayxyP2DW12V6MvTfrvWXrCDp55z6d87iSwGfxENcgDuu3QpuzFzWXtfbcoBLzDySQo",
|
||||
"xpriv": "xprv9ykAVQAYk6XmMXrEjvv7e6esuuEnMQdcKfTLfdVuiFSz6ah4xTiEYZbypbXxvNzY5ZN3wkrBWnSAGAvsiZVDXuyB6qyxprJfDb6yxYj1ZhP"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"xpub": "xpub6CFoRnxxMJa9gbVBNMh3VS9Zb6mkaHiWzFGEm3gkzmQ7H8b45nGj2fffGRR5Requ4wAwhEQjkArSaqv7HHvLK3y9wJcJRY6x1PuVWcKvXpn",
|
||||
"xpriv": "xprv9yGT2HS4Ww1rU7QiGLA38JCq34wGApzfd2LdxfH9SRs8QLFuYExUUsMBR8UShsuRfYr3X57gmbtdz9BsC4gxEkESSdBxdmiuLULfVq4A8Vw"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"xpub": "xpub6CmhKTZY8gxFWcZRLyUUncSuXmWiifSSEdXxY7GbSA5oigKpxEjTCosSVaFFMMnq3ymUuLNaoe8b4SQUYmXPqYX8CUwMh1N9Sge7RBuvEsB",
|
||||
"xpriv": "xprv9ynLux2eJKPxJ8UxEwwURUWAyjgEKCiasQcMjiryspYpqszgQhRCf1YxeHWjM9v9rpLZW1DUEQRFNH9XmXTXL3zmxEvFV6JUe2N2yYVdpJK"
|
||||
}
|
||||
],
|
||||
"toLegacyAddress": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"address": "1HFrMyKqduYaStXuwwKJo4U6LYd8ygFfJP"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"address": "16PcBknwp8vdT8RH3iV9rFW8Us8JKws2jp"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"address": "18gWYq4bf8hiS5hPDurPrxEs3wikdzskXH"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"address": "14HyYKA6dgn1DVTLnvEFfh1jNFBATyragw"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"address": "1AFWhEY61yrTgsW1bbAfNM6LnrTZ77oMc6"
|
||||
}
|
||||
],
|
||||
"toCashAddress": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"address": "bitcoincash:qze9zznaqzdne2awnlnygt0p74dkc3e4svm9ty58nx",
|
||||
"regtestAddress": "bchreg:qze9zznaqzdne2awnlnygt0p74dkc3e4sv9tez4rhu"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"address": "bitcoincash:qqa37fkpl3g90ydgas3t3ev0xes24du2aqfdxaz85s",
|
||||
"regtestAddress": "bchreg:qqa37fkpl3g90ydgas3t3ev0xes24du2aqhr5mrrs2"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"address": "bitcoincash:qp2yr38pjeqdtsqw9pfwjs6ng3ya4lqlpu46wkzsh5",
|
||||
"regtestAddress": "bchreg:qp2yr38pjeqdtsqw9pfwjs6ng3ya4lqlput5usr5nw"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"address": "bitcoincash:qqjpuwkhepkgxylfg8tq59sqm8zwf32dxqdchcnge7",
|
||||
"regtestAddress": "bchreg:qqjpuwkhepkgxylfg8tq59sqm8zwf32dxqnk97jvay"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"address": "bitcoincash:qpjh00scq3ratsytmttle5cml6yyk9stvc5lfd6pck",
|
||||
"regtestAddress": "bchreg:qpjh00scq3ratsytmttle5cml6yyk9stvc23mtm9uv"
|
||||
}
|
||||
],
|
||||
"toWIF": [
|
||||
{
|
||||
"privateKeyWIF": "L3nMAFHGojwdTajZAjEfSsqyP8TmQgqpxmhKNdwpLiNw4EBuhUcg",
|
||||
"xpriv": "xprv9ysdmq3FsEdR2byz2KdNuGNd1dY181zpe5jBpydatj49DaxVnrTGNkM4S28WgBzNSFQA5SSnT34XcqcoS6opVGebrhXAef3rGpXPPb7yHPi"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KxWMGJMHMhB4f8aTwpmqags7gNvcrc7gs76SJHaXbAc4Me2DKP3L",
|
||||
"xpriv": "xprv9ysdmq3FsEdQyzSTsENJdmQPvXWDArRWG118RzwPTGoYmwUDGoeHoBjr1hxgGrLP9XpEXg9roQhSBFrwjb934bnu8yQzdHi6MmcPUXniGrP"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzYUskkRuJrhDYLgP1JAywmUx3MPh2UZNQa299iZgGS9cNKytzy4",
|
||||
"xpriv": "xprv9ysdmq3FsEdR71JPPhVFP2DwwQCUksByZA7kg6y5qTjDvkX8GQH1WwJDc2epCeCL416qnVHJYNQvaFjkrM1CkGwaHy1w9oVAUAe4V6cYiyq"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L54oL29DdWDiPtHDW1kr3fzTWdm2f34V1tWhrFxnJoVafadwx6aS",
|
||||
"xpriv": "xprv9ysdmq3FsEdR8Zka7LWxKXaW2bsS3fjmusdBq5GnnDVMSAZ2LqhsoydPr6gD4CS9Ww8vWfnKtGe1rTqbw5NBvuqJwhebogWGbmkGhV9xa69"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L5UtYZibxTiHYefBQNvTRHYp75V3EeoqzRdv8KwqzYBtvzewaUME",
|
||||
"xpriv": "xprv9ysdmq3FsEdRD3iBKzw3f8HwpR1TbZNbySfxvXFZ6ZnmiMQGPfcnfCuDoLcnGT27p8DTvsqVubj8tv6yQp5siqUoPmT4WRLpjZXauriLnZB"
|
||||
}
|
||||
],
|
||||
"fromSeed": [
|
||||
"rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe"
|
||||
],
|
||||
"fromXPriv": [
|
||||
{
|
||||
"xpriv": "xprv9ysdmq3FsEdR2byz2KdNuGNd1dY181zpe5jBpydatj49DaxVnrTGNkM4S28WgBzNSFQA5SSnT34XcqcoS6opVGebrhXAef3rGpXPPb7yHPi",
|
||||
"legacy": "1CtdPZHebT5QTdknNvEBjGSgACHbriUmLV",
|
||||
"cashaddress": "bitcoincash:qzpxe7f7zc3rwckjmtled2wfssvv5gkvw52e35pc9q",
|
||||
"regtestaddress": "bchreg:qzpxe7f7zc3rwckjmtled2wfssvv5gkvw55hrjqup6",
|
||||
"xpub": "xpub6CrzBLa9hcBiF64T8MAPGQKMZfNVXUig1JendN3CT4b86PHeLPmWvYfYHK2NNYrEBj1GwfWqWF1xYjn6aD1Y7RYDNajKSKbSi1CW2hzeDA5",
|
||||
"privateKeyWIF": "L3nMAFHGojwdTajZAjEfSsqyP8TmQgqpxmhKNdwpLiNw4EBuhUcg"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ysdmq3FsEdQyzSTsENJdmQPvXWDArRWG118RzwPTGoYmwUDGoeHoBjr1hxgGrLP9XpEXg9roQhSBFrwjb934bnu8yQzdHi6MmcPUXniGrP",
|
||||
"legacy": "1J1nGBW8rWeV1VEETii5nKhKHT7qshuQYw",
|
||||
"cashaddress": "bitcoincash:qzafl67pkxgmmzfp5jj4937jv6rlfs7zxy6gurw0xh",
|
||||
"regtestaddress": "bchreg:qzafl67pkxgmmzfp5jj4937jv6rlfs7zxyyxw90tzd",
|
||||
"xpub": "xpub6CrzBLa9hcBiCUWvyFuJzuM8UZLhaK9MdDvjEPM11cLXejoMpLxYLz4KrxjRV9cd44EacgeaWU4E3GT6HfkDwjEup3Hw9inf9opWxxCZUa6",
|
||||
"privateKeyWIF": "KxWMGJMHMhB4f8aTwpmqags7gNvcrc7gs76SJHaXbAc4Me2DKP3L"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ysdmq3FsEdR71JPPhVFP2DwwQCUksByZA7kg6y5qTjDvkX8GQH1WwJDc2epCeCL416qnVHJYNQvaFjkrM1CkGwaHy1w9oVAUAe4V6cYiyq",
|
||||
"legacy": "1CrwnAN3p4Y5h7511F49VgwUvbEq314BM9",
|
||||
"cashaddress": "bitcoincash:qzppkls7al33d0w2dd07776d0fu2jwvtxsnw8nyum4",
|
||||
"regtestaddress": "bchreg:qzppkls7al33d0w2dd07776d0fu2jwvtxsdq449cl0",
|
||||
"xpub": "xpub6CrzBLa9hcBiKVNrVj2FkAAgVS2yAKupvP3MUVNhPoGCoYrGowbG4jchTLccFRbah2Kw7VNbP11G6mXYAkur47EZJcsXkvwTqCekjrpBYaS",
|
||||
"privateKeyWIF": "KzYUskkRuJrhDYLgP1JAywmUx3MPh2UZNQa299iZgGS9cNKytzy4"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ysdmq3FsEdR8Zka7LWxKXaW2bsS3fjmusdBq5GnnDVMSAZ2LqhsoydPr6gD4CS9Ww8vWfnKtGe1rTqbw5NBvuqJwhebogWGbmkGhV9xa69",
|
||||
"legacy": "1HbccrsbZjyPewX6vaHBFyuhE2NtP3BJYp",
|
||||
"cashaddress": "bitcoincash:qzmqmc6vq4hrdwtjrluwk9uvyj6nt4h4aqe24qxnqr",
|
||||
"regtestaddress": "bchreg:qzmqmc6vq4hrdwtjrluwk9uvyj6nt4h4aq8y8x8hye",
|
||||
"xpub": "xpub6CrzBLa9hcBiM3q3DN3xgfXEadhvT8TdH6YndTgQLZ2LJxtAtP28MmwshM34EtFhPDLorNocunk1E2KBvBbsGVJ5NorsvxW1yDWxsuLZF8Y",
|
||||
"privateKeyWIF": "L54oL29DdWDiPtHDW1kr3fzTWdm2f34V1tWhrFxnJoVafadwx6aS"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ysdmq3FsEdRD3iBKzw3f8HwpR1TbZNbySfxvXFZ6ZnmiMQGPfcnfCuDoLcnGT27p8DTvsqVubj8tv6yQp5siqUoPmT4WRLpjZXauriLnZB",
|
||||
"legacy": "1CmRFZjxL6auhVooc9sd3d8oKwL8mKwfFQ",
|
||||
"cashaddress": "bitcoincash:qzqslmsyprdfzwu3hk4sa237c7lpm44kesvkl2vtnq",
|
||||
"regtestaddress": "bchreg:qzqslmsyprdfzwu3hk4sa237c7lpm44kesjcdvd0h6",
|
||||
"xpub": "xpub6CrzBLa9hcBiRXneS2U42GEgNSqx126TLfbZiufAeuKkb9jQwCw3D1Dhec4bNzwm9JkunejrxWcviV5NmoQTkb5eMGqJrVby2L7p6Mtee75",
|
||||
"privateKeyWIF": "L5UtYZibxTiHYefBQNvTRHYp75V3EeoqzRdv8KwqzYBtvzewaUME"
|
||||
}
|
||||
],
|
||||
"fromXPub": [
|
||||
{
|
||||
"legacy": "1CtdPZHebT5QTdknNvEBjGSgACHbriUmLV",
|
||||
"cashaddress": "bitcoincash:qzpxe7f7zc3rwckjmtled2wfssvv5gkvw52e35pc9q",
|
||||
"regtestaddress": "bchreg:qzpxe7f7zc3rwckjmtled2wfssvv5gkvw55hrjqup6",
|
||||
"xpub": "xpub6CrzBLa9hcBiF64T8MAPGQKMZfNVXUig1JendN3CT4b86PHeLPmWvYfYHK2NNYrEBj1GwfWqWF1xYjn6aD1Y7RYDNajKSKbSi1CW2hzeDA5"
|
||||
},
|
||||
{
|
||||
"legacy": "1J1nGBW8rWeV1VEETii5nKhKHT7qshuQYw",
|
||||
"cashaddress": "bitcoincash:qzafl67pkxgmmzfp5jj4937jv6rlfs7zxy6gurw0xh",
|
||||
"regtestaddress": "bchreg:qzafl67pkxgmmzfp5jj4937jv6rlfs7zxyyxw90tzd",
|
||||
"xpub": "xpub6CrzBLa9hcBiCUWvyFuJzuM8UZLhaK9MdDvjEPM11cLXejoMpLxYLz4KrxjRV9cd44EacgeaWU4E3GT6HfkDwjEup3Hw9inf9opWxxCZUa6"
|
||||
},
|
||||
{
|
||||
"legacy": "1CrwnAN3p4Y5h7511F49VgwUvbEq314BM9",
|
||||
"cashaddress": "bitcoincash:qzppkls7al33d0w2dd07776d0fu2jwvtxsnw8nyum4",
|
||||
"regtestaddress": "bchreg:qzppkls7al33d0w2dd07776d0fu2jwvtxsdq449cl0",
|
||||
"xpub": "xpub6CrzBLa9hcBiKVNrVj2FkAAgVS2yAKupvP3MUVNhPoGCoYrGowbG4jchTLccFRbah2Kw7VNbP11G6mXYAkur47EZJcsXkvwTqCekjrpBYaS"
|
||||
},
|
||||
{
|
||||
"legacy": "1HbccrsbZjyPewX6vaHBFyuhE2NtP3BJYp",
|
||||
"cashaddress": "bitcoincash:qzmqmc6vq4hrdwtjrluwk9uvyj6nt4h4aqe24qxnqr",
|
||||
"regtestaddress": "bchreg:qzmqmc6vq4hrdwtjrluwk9uvyj6nt4h4aq8y8x8hye",
|
||||
"xpub": "xpub6CrzBLa9hcBiM3q3DN3xgfXEadhvT8TdH6YndTgQLZ2LJxtAtP28MmwshM34EtFhPDLorNocunk1E2KBvBbsGVJ5NorsvxW1yDWxsuLZF8Y"
|
||||
},
|
||||
{
|
||||
"legacy": "1CmRFZjxL6auhVooc9sd3d8oKwL8mKwfFQ",
|
||||
"cashaddress": "bitcoincash:qzqslmsyprdfzwu3hk4sa237c7lpm44kesvkl2vtnq",
|
||||
"regtestaddress": "bchreg:qzqslmsyprdfzwu3hk4sa237c7lpm44kesjcdvd0h6",
|
||||
"xpub": "xpub6CrzBLa9hcBiRXneS2U42GEgNSqx126TLfbZiufAeuKkb9jQwCw3D1Dhec4bNzwm9JkunejrxWcviV5NmoQTkb5eMGqJrVby2L7p6Mtee75"
|
||||
}
|
||||
],
|
||||
"accounts": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"externals": [
|
||||
"bitcoincash:qr2xjcqfmpl8thetzssxm32s2fnpvsfplvm37gh72u",
|
||||
"bitcoincash:qzxuj7cxg4t8vwd2q9ktl354zxga3csgqg7rmxtuv2",
|
||||
"bitcoincash:qp9uznqurj0kpu2zd25cg2nth3tht9cj5u9v7wwnyc",
|
||||
"bitcoincash:qq6g7j7m6sr22rpun5m4jz9v57698nfevc640rhqjm",
|
||||
"bitcoincash:qzxwx6z6hkr9eu3sekn5cvl7d0p26t42ns6kxn4004"
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"externals": [
|
||||
"bitcoincash:qr92mpxs2p4swnn5segxnvx654gj9k5f3udnpmdp6e",
|
||||
"bitcoincash:qqfgdzjzyhzvlfkv6g06pshq8ddm6mdc9q8l4n5d87",
|
||||
"bitcoincash:qpnk7c29fst9c339cv2cd2d5qh5t6y6ypu7ma9nysd",
|
||||
"bitcoincash:qz49d0m0sdvucs9z7gg0p34jzc8qk9qlpc4ggzkc0v",
|
||||
"bitcoincash:qqap24wa7uu9nskcxfsc2t4mtx6sf5sh6ye43grqne"
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"externals": [
|
||||
"bitcoincash:qqf38us2wju8n4kakdd9pkm20h4pd7tt3u4tm6wval",
|
||||
"bitcoincash:qp57af8qltwk90kkj8gm60k0m6dkgcuzc57kraaswg",
|
||||
"bitcoincash:qzxfrmcjkr4l2zdy05ghxcqh2z2jr62n8qpdskq6u9",
|
||||
"bitcoincash:qpj5yyzafyek7hw0pawmys0xqkm4pgf2h5u3v0ndpw",
|
||||
"bitcoincash:qr84wwrp5yvre58qq6mk323y0pmmzmdgxs9vukesmj"
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"externals": [
|
||||
"bitcoincash:qzzd8g4l4rum2txra2jkw5mqe29e8ac6vsjrkruedp",
|
||||
"bitcoincash:qq0su63j07y7vcts6etld9q3c57jhav4pc867t4927",
|
||||
"bitcoincash:qrfxkf0dgqrzwl0dkkt5tde77l758lzepyelpt5qkr",
|
||||
"bitcoincash:qq2hwe79eugk3fpx7n6f5nfqkeh4eygq7v9ay8dxrf",
|
||||
"bitcoincash:qprcxg6tkm0hq3773a2v66ue379fdh49mcdgg7fscr"
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"externals": [
|
||||
"bitcoincash:qqqqwccu8c2j2twsh3qp6wdyfnzdvxa2qqqdqst9eq",
|
||||
"bitcoincash:qr53v0r6djuu0jnpkphtl53kgptvv6x67yt7djky59",
|
||||
"bitcoincash:qzm4awn03edhskc6rtzytud35x84njlkls63ur3ffa",
|
||||
"bitcoincash:qqsyhnfcxv4g4e8sn3xlkx99urrzfqlw7u8y5eukdz",
|
||||
"bitcoincash:qqrlf0qszjwrrsh0d8cz3anvusu6q37xvynms533gt"
|
||||
]
|
||||
}
|
||||
],
|
||||
"sign": [
|
||||
{
|
||||
"privateKeyWIF": "tprv8gSiosqMhzpP3XaTadTEcFe57vcwxWbxNPvcwesb262wbzcFzKtqH8KAZApTBDJipJuAu3Dqzj3MZmLTz1mSeXP7Kn9uZeNXFpHBDQHr4hW",
|
||||
"data": "EARTH"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "xprv9yFjArUhvYMNZGr63oZK2TptuZDLMfBSz2c5mnFwSCmQeCMNTgJyZwkhjAumNgfsDsRJEn7pYmLQM7o8u5P2dWk6tG6TndWoVBPQi3DvmpY",
|
||||
"data": "foobar"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "tprv8gSiosqMhzpPMPbutrLEoyEea5DetcC5oorjaqY5qUFVwdPves2vkdYxR3PpXj67hBC6EUH9DTCDzReR6UWAjgF69bsrJTudWqNHe5LbNTU",
|
||||
"data": "12334567890"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "xprv9yFjArUhvYMNciVULCdXz7D6xAevAHgWXmsioewMAiuaAzBgkyVqxkqDcyg8KTeJedKRyxaNWLYSwAUts41vGoWCkWiEtcrRMo7y1gCfCZe",
|
||||
"data": "Be excellent to each other"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "xprv9yFjArUhvYMNmSjZ8k77PA6B6wsJUAq7sm6cKuZhkcVe85jkdpwbWgcMmXq4SDZZ7dg9GaoJCCaFSnRSVhFTQh2LJdH3pzMwaTQANk78PFA",
|
||||
"data": "satoshi"
|
||||
}
|
||||
],
|
||||
"verify": [
|
||||
{
|
||||
"privateKeyWIF1": "xprv9yFjArUhvYMNZGr63oZK2TptuZDLMfBSz2c5mnFwSCmQeCMNTgJyZwkhjAumNgfsDsRJEn7pYmLQM7o8u5P2dWk6tG6TndWoVBPQi3DvmpY",
|
||||
"privateKeyWIF2": "xprv9yFjArUhvYMNmSjZ8k77PA6B6wsJUAq7sm6cKuZhkcVe85jkdpwbWgcMmXq4SDZZ7dg9GaoJCCaFSnRSVhFTQh2LJdH3pzMwaTQANk78PFA",
|
||||
"data": "EARTH"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "tprv8gSiosqMhzpPMPbutrLEoyEea5DetcC5oorjaqY5qUFVwdPves2vkdYxR3PpXj67hBC6EUH9DTCDzReR6UWAjgF69bsrJTudWqNHe5LbNTU",
|
||||
"privateKeyWIF2": "tprv8gSiosqMhzpP3XaTadTEcFe57vcwxWbxNPvcwesb262wbzcFzKtqH8KAZApTBDJipJuAu3Dqzj3MZmLTz1mSeXP7Kn9uZeNXFpHBDQHr4hW",
|
||||
"data": "foobar"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "xprv9yFjArUhvYMNmSjZ8k77PA6B6wsJUAq7sm6cKuZhkcVe85jkdpwbWgcMmXq4SDZZ7dg9GaoJCCaFSnRSVhFTQh2LJdH3pzMwaTQANk78PFA",
|
||||
"privateKeyWIF2": "xprv9yFjArUhvYMNZGr63oZK2TptuZDLMfBSz2c5mnFwSCmQeCMNTgJyZwkhjAumNgfsDsRJEn7pYmLQM7o8u5P2dWk6tG6TndWoVBPQi3DvmpY",
|
||||
"data": "12334567890"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "xprv9yFjArUhvYMNu32qRztSu86QozxDQjcUqFQ2YKxEaZ3Ww8m5CkfXXJMQxNLGQysS8uDnf7NGyboab2Rn4YskRh97jxFXNPgpqxVinM3vMki",
|
||||
"privateKeyWIF2": "xprv9yFjArUhvYMNZGr63oZK2TptuZDLMfBSz2c5mnFwSCmQeCMNTgJyZwkhjAumNgfsDsRJEn7pYmLQM7o8u5P2dWk6tG6TndWoVBPQi3DvmpY",
|
||||
"data": "Be excellent to each other"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF1": "xprv9yFjArUhvYMNyhQ3AsdJ6r8NH4NWwyXDg91twPN3hqdWZw6GJSz2JDLxfhJf46PCbs2K73239jzvNxRXqg62aV9M5ytN4kuSpi6JyGxm7eZ",
|
||||
"privateKeyWIF2": "xprv9yFjArUhvYMNu32qRztSu86QozxDQjcUqFQ2YKxEaZ3Ww8m5CkfXXJMQxNLGQysS8uDnf7NGyboab2Rn4YskRh97jxFXNPgpqxVinM3vMki",
|
||||
"data": "satoshi"
|
||||
}
|
||||
],
|
||||
"isPublic": [
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoxqkZ7Fgt33te4LPHgcsKwyoZYVorkzp9uonWxWgP9wiSQhPeBUqVHbdAyov4Yi55RywBkDfZKdJFRqA51Anz6v72zGaMGZp",
|
||||
"xpub": "xpub6CrR2S9hJVz7BKq2DHDtQBqNcNDn65bBKCjALtDUKLM8nc7fW3zdhk2vFwgAKyFx1VNfQrXTZyKz9sAHZp8rHUEq6n8aWLSaDHxBcsHUPr8"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoqvzxGj886r4Ey3w1WfVNYH8sMnVPVzyQtaPPM6Q8pHm3D9WPWvEupGEgcJ1xLaGaZDcvKfoAurE2AzHRRRup5FuHzDr8n15",
|
||||
"xpub": "xpub6CrR2S9hJVz74R5RNkf8TyzyX5mVv8DDuW4UAAu14LWPmNiXtdiPN65X4RFeCDjdgMQsFYBGVFV3gtscV3Caa1jkZMccuMSUchy6193GqoA"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoskNxLPn5ia9NLq5o2KS2H5aPXAp8yrXZCtDETASDjp1dbj4fDKHFzJD3T7xZgZRUeD1wi498xLtJcEEaqQty7xhQ8eYP2jv",
|
||||
"xpub": "xpub6CrR2S9hJVz76ETRSRK65i66trvHRn9seJVzKZDkYC4Y5gYNzhkUHcL7SzB5fZ8Dcbv19bzMqKR3W3XRKfMoJ8Us8QVkhAowV3KTVjibTjj"
|
||||
},
|
||||
{
|
||||
"xpriv": "tprv8gHe7RzeBHKRs7RNjmrcwaBeupsSMj6pJ5Fc9VyoWgHSQNQS2MuSv66VunfCVDGDuDUPj1T5CyXkmUyEZULcntcfc5TdQfpNWni9UU8QTkC",
|
||||
"xpub": "tpubDCygFr2tKf16kaTAdRXDLyqmUrPNX4HisNrPS226vx5qErfCekj36aiN5x2EDBBefiewYnLHKnRyUMLHN1X2A7212XEzoQqnTbdi5xGSu3X"
|
||||
},
|
||||
{
|
||||
"xpriv": "tprv8gHe7RzeBHKRz5dTMj3kbdpZUhSoEbx9dKgeTMf1Krcv4Vad4ESDpChSb2Dd1te4URYFp47aa7Ps6HYgz7UEPs9r438n9iST7LEJyDsLjXB",
|
||||
"xpub": "tpubDCygFr2tKf16sYfFFNiM13Ug3ixjPw94CdHRjshJk8RJtyqPgdFozhKJm8snjzRrAqSho3f3K4AT9XeP6xYN1sx58dPRfBsJ5FxTB5weFLL"
|
||||
}
|
||||
],
|
||||
"isPrivate": [
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoxqkZ7Fgt33te4LPHgcsKwyoZYVorkzp9uonWxWgP9wiSQhPeBUqVHbdAyov4Yi55RywBkDfZKdJFRqA51Anz6v72zGaMGZp",
|
||||
"xpub": "xpub6CrR2S9hJVz7BKq2DHDtQBqNcNDn65bBKCjALtDUKLM8nc7fW3zdhk2vFwgAKyFx1VNfQrXTZyKz9sAHZp8rHUEq6n8aWLSaDHxBcsHUPr8"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoqvzxGj886r4Ey3w1WfVNYH8sMnVPVzyQtaPPM6Q8pHm3D9WPWvEupGEgcJ1xLaGaZDcvKfoAurE2AzHRRRup5FuHzDr8n15",
|
||||
"xpub": "xpub6CrR2S9hJVz74R5RNkf8TyzyX5mVv8DDuW4UAAu14LWPmNiXtdiPN65X4RFeCDjdgMQsFYBGVFV3gtscV3Caa1jkZMccuMSUchy6193GqoA"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoskNxLPn5ia9NLq5o2KS2H5aPXAp8yrXZCtDETASDjp1dbj4fDKHFzJD3T7xZgZRUeD1wi498xLtJcEEaqQty7xhQ8eYP2jv",
|
||||
"xpub": "xpub6CrR2S9hJVz76ETRSRK65i66trvHRn9seJVzKZDkYC4Y5gYNzhkUHcL7SzB5fZ8Dcbv19bzMqKR3W3XRKfMoJ8Us8QVkhAowV3KTVjibTjj"
|
||||
},
|
||||
{
|
||||
"xpriv": "tprv8gHe7RzeBHKRs7RNjmrcwaBeupsSMj6pJ5Fc9VyoWgHSQNQS2MuSv66VunfCVDGDuDUPj1T5CyXkmUyEZULcntcfc5TdQfpNWni9UU8QTkC",
|
||||
"xpub": "tpubDCygFr2tKf16kaTAdRXDLyqmUrPNX4HisNrPS226vx5qErfCekj36aiN5x2EDBBefiewYnLHKnRyUMLHN1X2A7212XEzoQqnTbdi5xGSu3X"
|
||||
},
|
||||
{
|
||||
"xpriv": "tprv8gHe7RzeBHKRz5dTMj3kbdpZUhSoEbx9dKgeTMf1Krcv4Vad4ESDpChSb2Dd1te4URYFp47aa7Ps6HYgz7UEPs9r438n9iST7LEJyDsLjXB",
|
||||
"xpub": "tpubDCygFr2tKf16sYfFFNiM13Ug3ixjPw94CdHRjshJk8RJtyqPgdFozhKJm8snjzRrAqSho3f3K4AT9XeP6xYN1sx58dPRfBsJ5FxTB5weFLL"
|
||||
}
|
||||
],
|
||||
"toIdentifier": [
|
||||
{
|
||||
"xpriv": "tprv8ggxJ8SG5EdqakzVUeLa9Gr7sqCdEcJPUNDmtdJscNxfmxoXvU36ZguiUWukJVEWEixAUr8pJabJkCt33wzxFQA587gqN51Lxdxx97zAzuG"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoqvzxGj886r4Ey3w1WfVNYH8sMnVPVzyQtaPPM6Q8pHm3D9WPWvEupGEgcJ1xLaGaZDcvKfoAurE2AzHRRRup5FuHzDr8n15"
|
||||
},
|
||||
{
|
||||
"xpriv": "xprv9ys4cvcoU8RoskNxLPn5ia9NLq5o2KS2H5aPXAp8yrXZCtDETASDjp1dbj4fDKHFzJD3T7xZgZRUeD1wi498xLtJcEEaqQty7xhQ8eYP2jv"
|
||||
},
|
||||
{
|
||||
"xpriv": "tprv8gHe7RzeBHKRs7RNjmrcwaBeupsSMj6pJ5Fc9VyoWgHSQNQS2MuSv66VunfCVDGDuDUPj1T5CyXkmUyEZULcntcfc5TdQfpNWni9UU8QTkC"
|
||||
},
|
||||
{
|
||||
"xpriv": "tprv8gHe7RzeBHKRz5dTMj3kbdpZUhSoEbx9dKgeTMf1Krcv4Vad4ESDpChSb2Dd1te4URYFp47aa7Ps6HYgz7UEPs9r438n9iST7LEJyDsLjXB"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
Mock data for IPFS unit tests.
|
||||
*/
|
||||
|
||||
const uploadData = {
|
||||
successful: [
|
||||
{
|
||||
source: "Local",
|
||||
id: "uppy-ipfs/js-1e-application/octet-stream",
|
||||
name: "ipfs.js",
|
||||
extension: "js",
|
||||
meta: {
|
||||
test: "avatar",
|
||||
name: "ipfs.js",
|
||||
type: "application/octet-stream",
|
||||
fileModelId: "5ec562319bfacc745e8d8a52"
|
||||
},
|
||||
type: "application/octet-stream",
|
||||
progress: {
|
||||
uploadStarted: 1589596706524,
|
||||
uploadComplete: true,
|
||||
percentage: 100,
|
||||
bytesUploaded: 2374,
|
||||
bytesTotal: 2374
|
||||
},
|
||||
size: null,
|
||||
isRemote: false,
|
||||
remote: "",
|
||||
tus: {
|
||||
uploadUrl:
|
||||
"http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33"
|
||||
},
|
||||
response: {
|
||||
uploadURL:
|
||||
"http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33"
|
||||
},
|
||||
uploadURL:
|
||||
"http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33",
|
||||
isPaused: false
|
||||
}
|
||||
],
|
||||
failed: [],
|
||||
uploadID: "cka90u4m300000fi0cldg6lrf"
|
||||
}
|
||||
|
||||
const paymentInfo = {
|
||||
success: true,
|
||||
hostingCostBCH: 0.00004201,
|
||||
hostingCostUSD: 0.01,
|
||||
file: {
|
||||
payloadLink: "",
|
||||
hasBeenPaid: false,
|
||||
_id: "5ebf5d04cba8b038394e0d62",
|
||||
schemaVersion: 1,
|
||||
size: 2374,
|
||||
fileId: "uppy-ipfs/js-1e-application/octet-stream",
|
||||
fileName: "ipfs.js",
|
||||
fileExtension: "js",
|
||||
createdTimestamp: "1589599492.952",
|
||||
hostingCost: 4201,
|
||||
walletIndex: 36,
|
||||
bchAddr: "bchtest:qqymyk4zfvnw8rh6hcvl922ewudkyrn9jvk6gtuae6",
|
||||
__v: 0
|
||||
}
|
||||
}
|
||||
|
||||
mockNewFileModel = {
|
||||
success: true,
|
||||
hostingCostBCH: 0.00004197,
|
||||
hostingCostUSD: 0.01,
|
||||
file: {
|
||||
payloadLink: "",
|
||||
hasBeenPaid: false,
|
||||
_id: "5ec562319bfacc745e8d8a52",
|
||||
schemaVersion: 1,
|
||||
size: 4458,
|
||||
fileName: "ipfs.js",
|
||||
fileExtension: "js",
|
||||
createdTimestamp: "1589994033.655",
|
||||
hostingCost: 4196,
|
||||
walletIndex: 49,
|
||||
bchAddr: "bchtest:qzrpkevu7h2ayfa4rjx08r5elvpfu72dg567x3mh3c",
|
||||
__v: 0
|
||||
}
|
||||
}
|
||||
|
||||
const unpaidFileData = {
|
||||
file: {
|
||||
payloadLink: "",
|
||||
hasBeenPaid: false,
|
||||
_id: "5ec7392c2acfe57aa62e945a",
|
||||
schemaVersion: 1,
|
||||
size: 726,
|
||||
fileName: "ipfs-e2e.js",
|
||||
fileExtension: "js",
|
||||
createdTimestamp: "1590114604.986",
|
||||
hostingCost: 4403,
|
||||
walletIndex: 56,
|
||||
bchAddr: "bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk",
|
||||
__v: 0
|
||||
}
|
||||
}
|
||||
|
||||
const paidFileData = {
|
||||
file: {
|
||||
payloadLink: "QmRDHPhY5hCNVRMVQvS2H9uty8P1skdwgLaHpUAkEvsjcE",
|
||||
hasBeenPaid: true,
|
||||
_id: "5ec7392c2acfe57aa62e945a",
|
||||
schemaVersion: 1,
|
||||
size: 726,
|
||||
fileName: "ipfs-e2e.js",
|
||||
fileExtension: "js",
|
||||
createdTimestamp: "1590114604.986",
|
||||
hostingCost: 4403,
|
||||
walletIndex: 56,
|
||||
bchAddr: "bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk",
|
||||
__v: 0
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
uploadData,
|
||||
paymentInfo,
|
||||
mockNewFileModel,
|
||||
unpaidFileData,
|
||||
paidFileData
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
{
|
||||
"fromEntropy": [
|
||||
{
|
||||
"mnemonic": "rare dinosaur army fat spend average design order ritual town brave spike",
|
||||
"entropy": "b207cc3029bd141f8ef4e1ba9cc86d68"
|
||||
},
|
||||
{
|
||||
"mnemonic": "rabbit track ahead moral either upper tiger paper echo snow multiply trial kind two cram",
|
||||
"entropy": "b03cd014c7d471de387cff45f9b245f417a9d74c"
|
||||
},
|
||||
{
|
||||
"mnemonic": "shadow steak gospel heart life wedding loud jar marriage during lecture stove exclude price worry story art relief",
|
||||
"entropy": "c4daa193352815f1e10bba884885fc6b54ef54ff76b40cd6"
|
||||
},
|
||||
{
|
||||
"mnemonic": "supply salute they blood coyote century envelope circle baby armed comfort sport jazz clarify museum portion wolf hour donkey frog juice",
|
||||
"entropy": "d9d7db820bf31a4ad2f149110178b8e9577653e46d42fccdc904ae97"
|
||||
},
|
||||
{
|
||||
"mnemonic": "tunnel ugly degree bid merry world pupil tornado ski rent casino rent security length wet twice luxury rookie invite destroy busy leopard escape shoe",
|
||||
"entropy": "ea9d80e70b08bbfb6b7f2bca56c88ddb2c2d003e675a855779d81e11f3009346"
|
||||
}
|
||||
],
|
||||
"toKeypairs": [
|
||||
{
|
||||
"mnemonic": "curve quiz lesson bone wave endless rigid symbol plug shift access dragon",
|
||||
"output": [
|
||||
{
|
||||
"privateKeyWIF": "L5NHWZusDiBVi5eMc6mBGufDMewTqnN9fzi6zyCQSVp39iKPqH7v",
|
||||
"privateKeyWIFRegTest": "cVjGyUuiemsksX7czWaJeEAGytEsWETqk2ra7PeuwcU3QTKYFYX7",
|
||||
"address": "bitcoincash:qr3r0yazu6s4ed0ckgpv96zcwx3wt9jy6vv56ywm2w"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L3nGc7sEDQ6CQV7LPzyLwec8uWwQFWhXKcYdPC6dmx8xZuq4mmDM",
|
||||
"privateKeyWIFRegTest": "cU9G52s5eTnTZvabnQnUJy7CXkEouxoDPeh6VcZ9H4nxpeqnn4y7",
|
||||
"address": "bitcoincash:qqzc32v777yz4qprp0tk443j5j35q5q0xgzuvprgv0"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KxD3i4YUdzEdDggNbNjRbYqta85KPGko9mRxcZH1Dh7MYQ5PFjcq",
|
||||
"privateKeyWIFRegTest": "cNa3AyYL53vtP89dynYYxsLxCMNj3irVDoaRiyjWiomMo9AginKE",
|
||||
"address": "bitcoincash:qre988ur4gp5k2ph3lmxltqtg4q2zgw6eye0l6k6eg"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1emnG2hYd3VKGVRHpZS3qHXQHMBgvDy4he4UtFu747wVyT5sQGT",
|
||||
"privateKeyWIFRegTest": "cS1mFB2YygjkUhxggENZR9nb2WebMNKf8jnXbJiQcAmwkiSwiEsC",
|
||||
"address": "bitcoincash:qzrjsum46ecex9qs28eyhw27ltydu37wzcq3v80ld8"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L28uLVU1Kt8fPJtbK7HUB436atC4dSN1WQPJLde1w6dtyhNmLMyt",
|
||||
"privateKeyWIFRegTest": "cSVtoQTrkwpvYkMrhX6bYNYAD7VUHtThaSXmT46XSDHuESQ7LCaQ",
|
||||
"address": "bitcoincash:qqqnmqmpy9vz899ctv4chtx5n857pv9l4ykuea44xz"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "weapon undo scatter empty ride cement team protect ugly sudden mom zebra nurse label leopard",
|
||||
"output": [
|
||||
{
|
||||
"privateKeyWIF": "KxGbR7jBWA7jm7GVz9SQvUghX4cYyf1WoP7oGjVXgzbeCDBFy5Qi",
|
||||
"privateKeyWIFRegTest": "cNdat2j2wDozvYjmNZFYHoBm9Huxe77CsRGGP9x3C7FeSxGV9GtJ",
|
||||
"address": "bitcoincash:qr3r0yazu6s4ed0ckgpv96zcwx3wt9jy6vv56ywm2w"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L2Er6iZ87yeQVDREKQWw8xr7Uj2ZTmdF4fzfG2MYP3TYHHgXBphK",
|
||||
"privateKeyWIFRegTest": "cSbqZdYyZ3LfeetVhpL4WHMB6xKy8Diw8i98NSp3tA7YY2o3PGAC",
|
||||
"address": "bitcoincash:qqzc32v777yz4qprp0tk443j5j35q5q0xgzuvprgv0"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KwQW5F2oFfeqaB9H8AEWX6e8SFyw7qdNcVc3i9RBY6o1oDWYLuM3",
|
||||
"privateKeyWIFRegTest": "cMmVYA2egjM6jccYWa3dtR9C4VHLnHj4gXkWpZsh3DT23xZ7Zhgx",
|
||||
"address": "bitcoincash:qre988ur4gp5k2ph3lmxltqtg4q2zgw6eye0l6k6eg"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1wrABy4xHXNct68ZkBsNUfRN3MHvSW4KJPPDbusUCTjPq3zm3AB",
|
||||
"privateKeyWIFRegTest": "cSJqd6xvPMDdnKZPx9zzjoAUzGehatbkPLXrL2NNyK7jea72uxB7",
|
||||
"address": "bitcoincash:qzrjsum46ecex9qs28eyhw27ltydu37wzcq3v80ld8"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L5fQnDhGNYH6qFjh4pgtxYtZ6SSa6PNvqsvXL3Xxc3UTckwo35WU",
|
||||
"privateKeyWIFRegTest": "cW2QF8h7obyMzhCxTEW2KsPcifjykqUcuv4zSTzU7A8TsW2nQGUh",
|
||||
"address": "bitcoincash:qqqnmqmpy9vz899ctv4chtx5n857pv9l4ykuea44xz"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "energy special regular coin crop auto acquire clinic high liberty educate pride wage grace spoil ugly cable trust",
|
||||
"output": [
|
||||
{
|
||||
"privateKeyWIF": "Kwv3n87vwRrMbxa4vTWKY9gaAZtthe3NR1iebRTraaVSAwY5ty8Q",
|
||||
"privateKeyWIFRegTest": "cNH3F37nNVYcmQ3LJsKSuUBdnoCJN694V3s7hqvN5h9SRgYiXW9A",
|
||||
"address": "bitcoincash:qr3r0yazu6s4ed0ckgpv96zcwx3wt9jy6vv56ywm2w"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzucDPxzkExCHTzzJBXo17V7LwRtKj6movuYWmbGW2HjVsFTSBdk",
|
||||
"privateKeyWIFRegTest": "cRGbgJxrBJeTSuUFgbLvNRzAyAjHzBCTsy41dC3n18wjkcGHbiRX",
|
||||
"address": "bitcoincash:qqzc32v777yz4qprp0tk443j5j35q5q0xgzuvprgv0"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "Kye3NjRtM2NYtS4kfQgSNK2RvtzUM9mXzy6szZTVii33ETd5jNrU",
|
||||
"privateKeyWIFRegTest": "cQ12qeRjn64p3sY23pVZjdXVZ8Ht1bsE51FM6yv1Dph3VCj31tVz",
|
||||
"address": "bitcoincash:qre988ur4gp5k2ph3lmxltqtg4q2zgw6eye0l6k6eg"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KzZWMxZGgu8cZF2aEaP1sYnh3E4vtCHEKVzY2fWaHG44MFosYmq1",
|
||||
"privateKeyWIFRegTest": "cQvVpsZ87xpsigVqczC9EsHkfTNLYeNvPY9195y5nNi4bzvNh7Zt",
|
||||
"address": "bitcoincash:qzrjsum46ecex9qs28eyhw27ltydu37wzcq3v80ld8"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L4iVLdaMkKvwtZKeD1ishayo2XHGWLm37imjpQFyV4XSkv1XTkGk",
|
||||
"privateKeyWIFRegTest": "cV5UoYaDBPdD3znubRY14uUrekagAnrjBkvCvpiUzBBT1f5bgdjT",
|
||||
"address": "bitcoincash:qqqnmqmpy9vz899ctv4chtx5n857pv9l4ykuea44xz"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "dwarf all expect planet margin glare tribe hard hybrid cable fish key ordinary equip foil trash surprise carry account shove later",
|
||||
"output": [
|
||||
{
|
||||
"privateKeyWIF": "KwZ38dBpAk1BY53mmo6tSkt5we3FEAw8nvPE5m3L8iGJvfgCtM1r",
|
||||
"privateKeyWIFRegTest": "cMv2bYBfbohShWX3ACv1p5P9ZsLetd2prxXhCBVqdpvKBQpZYKBJ",
|
||||
"address": "bitcoincash:qr3r0yazu6s4ed0ckgpv96zcwx3wt9jy6vv56ywm2w"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L1VCKD5oq7s5iaWC2ZY79KuRxDJrQ6tjRiB3VaScYsxYD8TxsSan",
|
||||
"privateKeyWIFRegTest": "cRrBn85fGBZLt1yTQyMEWeQVaScG4YzRVkKWbzu83zcYTsVYovue",
|
||||
"address": "bitcoincash:qqzc32v777yz4qprp0tk443j5j35q5q0xgzuvprgv0"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KxojM7WKQqxS1FNKGVWowDPtzMXaXQ7UUsdwhxJFUwE7HxSofqUK",
|
||||
"privateKeyWIFRegTest": "cPAip2WAquehAgqaeuKwJXtxcapzBrDAYunQpNkkz3t7YhTkSbJy",
|
||||
"address": "bitcoincash:qre988ur4gp5k2ph3lmxltqtg4q2zgw6eye0l6k6eg"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "KyWdb9m9TJpxqGHkZjHLipQiLUVmhvZT8p49N761RUc2Nq23FBxd",
|
||||
"privateKeyWIFRegTest": "cPsd44kztNXDzhm1x96U68umxhoBNNf9CrCcUXYWvbG2daC2pDgL",
|
||||
"address": "bitcoincash:qzrjsum46ecex9qs28eyhw27ltydu37wzcq3v80ld8"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L33wzMLV6m6DLHPnzuf27ZSjLv8HGG3DCjMdxDDTieDt7P1ih1ic",
|
||||
"privateKeyWIFRegTest": "cTQwTGLLXpnUVis4PKU9Uswny9Rgvi8uGmW74dfyDkstN874DDMJ",
|
||||
"address": "bitcoincash:qqqnmqmpy9vz899ctv4chtx5n857pv9l4ykuea44xz"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"mnemonic": "sibling parent owner rack velvet head boy bicycle exchange gossip despair supply brain office blanket topic slot baby hire rebuild apology radar strike age",
|
||||
"output": [
|
||||
{
|
||||
"privateKeyWIF": "KyapaU8zwrHxLoqVfwRrF9e5a35DoXhV6C7zTkVnneuLQhMHBd7G",
|
||||
"privateKeyWIFRegTest": "cPwp3P8rNuzDWFJm4MEycU99CGNdTyoBAEGTaAxJHmZLfSTUM32i",
|
||||
"address": "bitcoincash:qr3r0yazu6s4ed0ckgpv96zcwx3wt9jy6vv56ywm2w"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L2WCL7KEJT415BPYBhW3vUp89x1AwFrLfMyjMrbC444N1tFKBhXY",
|
||||
"privateKeyWIFRegTest": "cSsBo2K5jWkGEcroa7KBHoKBnBJabhx2jQ8CUH3hZAiNGdPAbR1L",
|
||||
"address": "bitcoincash:qqzc32v777yz4qprp0tk443j5j35q5q0xgzuvprgv0"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L3Dz8kbwNf6EShtjnpZ65k8RuyD2reMcbZAnFY4GvQjy7CtvtmZX",
|
||||
"privateKeyWIFRegTest": "cTaybfbnoinVc9N1BENDT4dVYCWSX6TJfbKFMxWnRXPyMwwVTigN",
|
||||
"address": "bitcoincash:qre988ur4gp5k2ph3lmxltqtg4q2zgw6eye0l6k6eg"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L3Dy5sJB31JBnRtFZq6QJaKEaijo3wCnvJpjRvr8hYov7LUu8E13",
|
||||
"privateKeyWIFRegTest": "cTaxYnJ2U4zSwsMWxEuXftpJCx3CiPJUzLyCYMJeCfTvN5VU9AG6",
|
||||
"address": "bitcoincash:qzrjsum46ecex9qs28eyhw27ltydu37wzcq3v80ld8"
|
||||
},
|
||||
{
|
||||
"privateKeyWIF": "L4DTuvT3XWFW7vs6gvS88v4vYBMuJK3GjzMBTjD8XkpfJwoeqewD",
|
||||
"privateKeyWIFRegTest": "cUaTNqStxZwmHNLN5LFFWEZzAQfJxm8xp2Vea9fe2sUfZgtqShVL",
|
||||
"address": "bitcoincash:qqqnmqmpy9vz899ctv4chtx5n857pv9l4ykuea44xz"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"findNearestWord": [
|
||||
{
|
||||
"word": "ab",
|
||||
"foundWord": "abandon",
|
||||
"language": "english"
|
||||
},
|
||||
{
|
||||
"word": "octu",
|
||||
"foundWord": "octupler",
|
||||
"language": "french"
|
||||
},
|
||||
{
|
||||
"word": "reda",
|
||||
"foundWord": "area",
|
||||
"language": "english"
|
||||
},
|
||||
{
|
||||
"word": "foobaro",
|
||||
"foundWord": "forro",
|
||||
"language": "spanish"
|
||||
},
|
||||
{
|
||||
"word": "nv",
|
||||
"foundWord": "neve",
|
||||
"language": "italian"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
Mocking data for unit tests for the Ninsight library.
|
||||
*/
|
||||
|
||||
const utxo = {
|
||||
utxos: [
|
||||
{
|
||||
txid: "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7",
|
||||
vout: 0,
|
||||
amount: 0.00001,
|
||||
satoshis: 1000,
|
||||
height: 602405,
|
||||
confirmations: 36459
|
||||
}
|
||||
],
|
||||
legacyAddress: "15NCRBJsHaJy8As5bX1oh2YauRejnZ1MKF",
|
||||
cashAddress: "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9",
|
||||
slpAddress: "simpleledger:qqh793x9au6ehvh7r2zflzguanlme760wuwzunhjfm",
|
||||
scriptPubKey: "76a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788ac",
|
||||
asm:
|
||||
"OP_DUP OP_HASH160 2fe2c4c5ef359bb2fe1a849f891cecffbcfb4f77 OP_EQUALVERIFY OP_CHECKSIG"
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
utxo
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user