@exodus/bitcoinjs-lib-forks 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/LICENSE +21 -0
  3. package/README.md +207 -0
  4. package/package.json +67 -0
  5. package/src/address.js +97 -0
  6. package/src/block.js +177 -0
  7. package/src/bufferutils.js +56 -0
  8. package/src/crypto.js +29 -0
  9. package/src/ecdsa.js +161 -0
  10. package/src/ecpair.js +131 -0
  11. package/src/ecsignature.js +97 -0
  12. package/src/hdnode.js +316 -0
  13. package/src/index.js +23 -0
  14. package/src/networks.js +47 -0
  15. package/src/script.js +214 -0
  16. package/src/script_number.js +68 -0
  17. package/src/templates/index.js +74 -0
  18. package/src/templates/multisig/index.js +4 -0
  19. package/src/templates/multisig/input.js +71 -0
  20. package/src/templates/multisig/output.js +64 -0
  21. package/src/templates/nulldata.js +34 -0
  22. package/src/templates/pubkey/index.js +4 -0
  23. package/src/templates/pubkey/input.js +39 -0
  24. package/src/templates/pubkey/output.js +33 -0
  25. package/src/templates/pubkeyhash/index.js +4 -0
  26. package/src/templates/pubkeyhash/input.js +51 -0
  27. package/src/templates/pubkeyhash/output.js +42 -0
  28. package/src/templates/scripthash/index.js +4 -0
  29. package/src/templates/scripthash/input.js +84 -0
  30. package/src/templates/scripthash/output.js +34 -0
  31. package/src/templates/witnesscommitment/index.js +3 -0
  32. package/src/templates/witnesscommitment/output.js +42 -0
  33. package/src/templates/witnesspubkeyhash/index.js +4 -0
  34. package/src/templates/witnesspubkeyhash/input.js +44 -0
  35. package/src/templates/witnesspubkeyhash/output.js +33 -0
  36. package/src/templates/witnessscripthash/index.js +4 -0
  37. package/src/templates/witnessscripthash/input.js +63 -0
  38. package/src/templates/witnessscripthash/output.js +33 -0
  39. package/src/transaction.js +547 -0
  40. package/src/transaction_builder.js +825 -0
  41. package/src/types.js +53 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # 0.0.1 / 2018-11-14
2
+
3
+ Initial release, with 2018-11-15 BCH (BitcoinABC) HF support.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2011-2017 bitcoinjs-lib contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,207 @@
1
+ # BitcoinJS Forks (`@exodus/bitcoinjs-lib-forks`)
2
+
3
+ [![Build Status](https://travis-ci.com/ExodusMovement/bitcoinjs-lib-forks.svg?token=QTcVjCYzbYmjmHfQpsUB&branch=bcash-bgold)](https://travis-ci.com/ExodusMovement/bitcoinjs-lib-forks)
4
+
5
+ `bitcoinjs-lib` forked to support Bitcoin Cash & Bitcoin Gold. Based off of https://github.com/bitcoinjs/bitcoinjs-lib/pull/831. Original README below.
6
+
7
+ # BitcoinJS (bitcoinjs-lib)
8
+ [![Build Status](https://travis-ci.org/bitcoinjs/bitcoinjs-lib.png?branch=master)](https://travis-ci.org/bitcoinjs/bitcoinjs-lib)
9
+ [![NPM](https://img.shields.io/npm/v/bitcoinjs-lib.svg)](https://www.npmjs.org/package/bitcoinjs-lib)
10
+ [![tip for next commit](https://tip4commit.com/projects/735.svg)](http://tip4commit.com/projects/735)
11
+
12
+ [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
13
+
14
+ The pure JavaScript Bitcoin library for node.js and browsers.
15
+ Estimated to be in use by over 15 million wallet users and is the backbone for almost all Bitcoin web wallets in production today.
16
+
17
+
18
+ ## Features
19
+ - Clean: Pure JavaScript, concise code, easy to read.
20
+ - Tested: Coverage > 90%, third-party integration tests.
21
+ - Careful: Two person approval process for small, focused pull requests.
22
+ - Compatible: Works on Node.js and all modern browsers.
23
+ - Powerful: Support for advanced features, such as multi-sig, HD Wallets.
24
+ - Secure: Strong random number generation, PGP signed releases, trusted developers.
25
+ - Principled: No support for browsers with crap RNG (IE < 11)
26
+ - Standardized: Node community coding style, Browserify, Node's stdlib and Buffers.
27
+ - Fast: Optimized code, uses typed arrays instead of byte arrays for performance.
28
+ - Experiment-friendly: Bitcoin Mainnet and Testnet support.
29
+ - Altcoin-ready: Capable of working with bitcoin-derived cryptocurrencies (such as Dogecoin).
30
+
31
+
32
+ ## Should I use this in production?
33
+ If you are thinking of using the master branch of this library in production, **stop**.
34
+ Master is not stable; it is our development branch, and [only tagged releases may be classified as stable](https://github.com/bitcoinjs/bitcoinjs-lib/tags).
35
+
36
+
37
+ ## Installation
38
+ ``` bash
39
+ npm install bitcoinjs-lib
40
+ ```
41
+
42
+ ## Setup
43
+ ### Node.js
44
+ ``` javascript
45
+ var bitcoin = require('bitcoinjs-lib')
46
+ ```
47
+
48
+ ### Browser
49
+ If you're familiar with how to use browserify, ignore this and proceed normally.
50
+ These steps are advisory only, and may not be suitable for your application.
51
+
52
+ [Browserify](https://github.com/substack/node-browserify) is assumed to be installed for these steps.
53
+
54
+ For your project, create an `index.js` file
55
+ ``` javascript
56
+ let bitcoin = require('bitcoinjs-lib')
57
+
58
+ // your code here
59
+ function myFunction () {
60
+ return bitcoin.ECPair.makeRandom().toWIF()
61
+ }
62
+
63
+ module.exports = {
64
+ myFunction
65
+ }
66
+ ```
67
+
68
+ Now, to compile for the browser:
69
+ ``` bash
70
+ browserify index.js --standalone foo > app.js
71
+ ```
72
+
73
+ You can now put `<script src="app.js" />` in your web page, using `foo.myFunction` to create a new Bitcoin private key.
74
+
75
+ **NOTE**: If you uglify the javascript, you must exclude the following variable names from being mangled: `BigInteger`, `ECPair`, `Point`.
76
+ This is because of the function-name-duck-typing used in [typeforce](https://github.com/dcousens/typeforce).
77
+
78
+ Example:
79
+ ``` bash
80
+ uglifyjs ... --mangle --reserved 'BigInteger,ECPair,Point'
81
+ ```
82
+
83
+ **NOTE**: This library tracks Node LTS features, if you need strict ES5, use [`--transform babelify`](https://github.com/babel/babelify) in conjunction with your `browserify` step (using an [`es2015`](http://babeljs.io/docs/plugins/preset-es2015/) preset).
84
+
85
+ **NOTE**: If you expect this library to run on an iOS 10 device, ensure that you are using [buffer@5.0.5](https://github.com/feross/buffer/pull/155) or greater.
86
+
87
+
88
+ ### Typescript or VSCode users
89
+ Type declarations for Typescript are available for version `^3.0.0` of the library.
90
+ ``` bash
91
+ npm install @types/bitcoinjs-lib
92
+ ```
93
+
94
+ You can now use `bitcoinjs-lib` as a typescript compliant library.
95
+ ``` javascript
96
+ import { HDNode, Transaction } from 'bitcoinjs-lib'
97
+ ```
98
+
99
+ For VSCode (and other editors), users are advised to install the type declarations, as Intellisense uses that information to help you code (autocompletion, static analysis).
100
+
101
+ Report any typescript related bugs at [@dlebrecht DefinitelyTyped fork](https://github.com/dlebrecht/DefinitelyTyped), submit PRs to [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped)
102
+
103
+
104
+ ### Flow
105
+ Definitions for [Flow typechecker](https://flowtype.org/) are available in flow-typed repository.
106
+
107
+ [You can either download them directly](https://github.com/flowtype/flow-typed/blob/master/definitions/npm/bitcoinjs-lib_v2.x.x/flow_v0.17.x-/bitcoinjs-lib_v2.x.x.js) from the repo, or with the flow-typed CLI
108
+
109
+ # npm install -g flow-typed
110
+ $ flow-typed install -f 0.27 bitcoinjs-lib@2.2.0 # 0.27 for flow version, 2.2.0 for bitcoinjs-lib version
111
+
112
+ The definitions are complete and up to date with version 2.2.0. The definitions are maintained by [@runn1ng](https://github.com/runn1ng).
113
+
114
+ ## Examples
115
+ The below examples are implemented as integration tests, they should be very easy to understand.
116
+ Otherwise, pull requests are appreciated.
117
+ Some examples interact (via HTTPS) with a 3rd Party Blockchain Provider (3PBP).
118
+
119
+ - [Generate a random address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L12)
120
+ - [Generate an address from a SHA256 hash](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L19)
121
+ - [Import an address via WIF](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L29)
122
+ - [Generate a 2-of-3 P2SH multisig address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L36)
123
+ - [Generate a SegWit address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L50)
124
+ - [Generate a SegWit P2SH address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L60)
125
+ - [Generate a SegWit 3-of-4 multisig address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L71)
126
+ - [Generate a SegWit 2-of-2 P2SH multisig address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L86)
127
+ - [Support the retrieval of transactions for an address (3rd party blockchain)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L100)
128
+ - [Generate a Testnet address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L121)
129
+ - [Generate a Litecoin address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/addresses.js#L131)
130
+ - [Create a 1-to-1 Transaction](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.js#L14)
131
+ - [Create a 2-to-2 Transaction](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.js#L28)
132
+ - [Create (and broadcast via 3PBP) a typical Transaction](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.js#L46)
133
+ - [Create (and broadcast via 3PBP) a Transaction with an OP\_RETURN output](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.js#L88)
134
+ - [Create (and broadcast via 3PBP) a Transaction with a 2-of-4 P2SH(multisig) input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.js#L115)
135
+ - [Create (and broadcast via 3PBP) a Transaction with a SegWit P2SH(P2WPKH) input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.js#L151)
136
+ - [Create (and broadcast via 3PBP) a Transaction with a SegWit 3-of-4 P2SH(P2WSH(multisig)) input](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/transactions.js#L183)
137
+ - [Import a BIP32 testnet xpriv and export to WIF](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.js#L8)
138
+ - [Export a BIP32 xpriv, then import it](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.js#L15)
139
+ - [Export a BIP32 xpub](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.js#L26)
140
+ - [Create a BIP32, bitcoin, account 0, external address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.js#L35)
141
+ - [Create a BIP44, bitcoin, account 0, external address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.js#L50)
142
+ - [Create a BIP49, bitcoin testnet, account 0, external address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.js#L66)
143
+ - [Use BIP39 to generate BIP32 addresses](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/bip32.js#L83)
144
+ - [Create (and broadcast via 3PBP) a Transaction where Alice can redeem the output after the expiry](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/cltv.js#L37)
145
+ - [Create (and broadcast via 3PBP) a Transaction where Alice and Bob can redeem the output at any time](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/cltv.js#L71)
146
+ - [Create (but fail to broadcast via 3PBP) a Transaction where Alice attempts to redeem before the expiry](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/cltv.js#L104)
147
+ - [Recover a private key from duplicate R values](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/crypto.js#L14)
148
+ - [Recover a BIP32 parent private key from the parent public key, and a derived, non-hardened child private key](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/crypto.js#L115)
149
+ - [Generate a single-key stealth address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/stealth.js#L70:)
150
+ - [Generate a single-key stealth address (randomly)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/stealth.js#L89:)
151
+ - [Recover parent recipient.d, if a derived private key is leaked (and nonce was revealed)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/stealth.js#L105)
152
+ - [Generate a dual-key stealth address](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/stealth.js#L122)
153
+ - [Generate a dual-key stealth address (randomly)](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/stealth.js#L145)
154
+
155
+ If you have a use case that you feel could be listed here, please [ask for it](https://github.com/bitcoinjs/bitcoinjs-lib/issues/new)!
156
+
157
+
158
+ ## Projects utilizing BitcoinJS
159
+ - [BitAddress](https://www.bitaddress.org)
160
+ - [Blockchain.info](https://blockchain.info/wallet)
161
+ - [Blocktrail](https://www.blocktrail.com/)
162
+ - [Dark Wallet](https://www.darkwallet.is/)
163
+ - [DecentralBank](http://decentralbank.com/)
164
+ - [Dogechain Wallet](https://dogechain.info)
165
+ - [EI8HT Wallet](http://ei8.ht/)
166
+ - [GreenAddress](https://greenaddress.it)
167
+ - [Helperbit](https://helperbit.com)
168
+ - [Melis Wallet](https://melis.io)
169
+ - [Robocoin](https://wallet.robocoin.com)
170
+ - [Skyhook ATM](http://projectskyhook.com)
171
+
172
+
173
+ ## Contributing
174
+ We are always accepting of pull requests, but we do adhere to specific standards in regards to coding style, test driven development and commit messages.
175
+
176
+ Please make your best effort to adhere to these when contributing to save on trivial corrections.
177
+
178
+
179
+ ### Running the test suite
180
+
181
+ ``` bash
182
+ npm test
183
+ npm run-script coverage
184
+ ```
185
+
186
+ ## Complementing Libraries
187
+ - [BIP21](https://github.com/bitcoinjs/bip21) - A BIP21 compatible URL encoding utility library
188
+ - [BIP38](https://github.com/bitcoinjs/bip38) - Passphrase-protected private keys
189
+ - [BIP39](https://github.com/bitcoinjs/bip39) - Mnemonic generation for deterministic keys
190
+ - [BIP32-Utils](https://github.com/bitcoinjs/bip32-utils) - A set of utilities for working with BIP32
191
+ - [BIP66](https://github.com/bitcoinjs/bip66) - Strict DER signature decoding
192
+ - [BIP69](https://github.com/bitcoinjs/bip69) - Lexicographical Indexing of Transaction Inputs and Outputs
193
+ - [Base58](https://github.com/cryptocoinjs/bs58) - Base58 encoding/decoding
194
+ - [Base58 Check](https://github.com/bitcoinjs/bs58check) - Base58 check encoding/decoding
195
+ - [Bech32](https://github.com/bitcoinjs/bech32) - A BIP173 compliant Bech32 encoding library
196
+ - [coinselect](https://github.com/bitcoinjs/coinselect) - A fee-optimizing, transaction input selection module for bitcoinjs-lib.
197
+ - [merkle-lib](https://github.com/bitcoinjs/merkle-lib) - A performance conscious library for merkle root and tree calculations.
198
+ - [minimaldata](https://github.com/bitcoinjs/minimaldata) - A module to check bitcoin policy: SCRIPT_VERIFY_MINIMALDATA
199
+
200
+
201
+ ## Alternatives
202
+ - [BCoin](https://github.com/indutny/bcoin)
203
+ - [Bitcore](https://github.com/bitpay/bitcore)
204
+ - [Cryptocoin](https://github.com/cryptocoinjs/cryptocoin)
205
+
206
+
207
+ ## LICENSE [MIT](LICENSE)
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@exodus/bitcoinjs-lib-forks",
3
+ "version": "0.0.1",
4
+ "description": "Client-side Bitcoin Forks JavaScript library",
5
+ "main": "./src/index.js",
6
+ "engines": {
7
+ "node": ">=8.0.0"
8
+ },
9
+ "keywords": [
10
+ "bitcoinjs",
11
+ "bitcoin",
12
+ "browserify",
13
+ "javascript",
14
+ "bitcoinjs",
15
+ "forks",
16
+ "cash",
17
+ "gold"
18
+ ],
19
+ "scripts": {
20
+ "coverage-report": "nyc report --reporter=lcov",
21
+ "coverage-html": "nyc report --reporter=html",
22
+ "coverage": "nyc --check-coverage --branches 90 --functions 90 mocha",
23
+ "integration": "mocha test/integration/",
24
+ "standard": "standard",
25
+ "test": "npm run standard && npm run coverage",
26
+ "unit": "mocha"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/bitcoinjs/bitcoinjs-lib.git"
31
+ },
32
+ "files": [
33
+ "src"
34
+ ],
35
+ "dependencies": {
36
+ "bech32": "0.0.3",
37
+ "bigi": "^1.4.0",
38
+ "bip66": "^1.1.0",
39
+ "bitcoin-ops": "^1.3.0",
40
+ "bs58check": "^2.0.0",
41
+ "create-hash": "^1.1.0",
42
+ "create-hmac": "^1.1.3",
43
+ "ecurve": "^1.0.0",
44
+ "merkle-lib": "^2.0.10",
45
+ "pushdata-bitcoin": "^1.0.1",
46
+ "randombytes": "^2.0.1",
47
+ "safe-buffer": "^5.0.1",
48
+ "typeforce": "^1.11.3",
49
+ "varuint-bitcoin": "^1.0.4",
50
+ "wif": "^2.0.1"
51
+ },
52
+ "devDependencies": {
53
+ "async": "^2.0.1",
54
+ "bip39": "^2.3.0",
55
+ "bs58": "^4.0.0",
56
+ "cb-http-client": "^0.2.0",
57
+ "coinselect": "^3.1.1",
58
+ "dhttp": "^2.3.5",
59
+ "minimaldata": "^1.0.2",
60
+ "mocha": "^3.1.0",
61
+ "nyc": "^10.2.0",
62
+ "proxyquire": "^1.4.0",
63
+ "sinon": "^1.12.2",
64
+ "standard": "^9.0.2"
65
+ },
66
+ "license": "MIT"
67
+ }
package/src/address.js ADDED
@@ -0,0 +1,97 @@
1
+ var Buffer = require('safe-buffer').Buffer
2
+ var bech32 = require('bech32')
3
+ var bs58check = require('bs58check')
4
+ var bscript = require('./script')
5
+ var btemplates = require('./templates')
6
+ var networks = require('./networks')
7
+ var typeforce = require('typeforce')
8
+ var types = require('./types')
9
+
10
+ function fromBase58Check (address) {
11
+ var payload = bs58check.decode(address)
12
+
13
+ // TODO: 4.0.0, move to "toOutputScript"
14
+ if (payload.length < 21) throw new TypeError(address + ' is too short')
15
+ if (payload.length > 21) throw new TypeError(address + ' is too long')
16
+
17
+ var version = payload.readUInt8(0)
18
+ var hash = payload.slice(1)
19
+
20
+ return { version: version, hash: hash }
21
+ }
22
+
23
+ function fromBech32 (address) {
24
+ var result = bech32.decode(address)
25
+ var data = bech32.fromWords(result.words.slice(1))
26
+
27
+ return {
28
+ version: result.words[0],
29
+ prefix: result.prefix,
30
+ data: Buffer.from(data)
31
+ }
32
+ }
33
+
34
+ function toBase58Check (hash, version) {
35
+ typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments)
36
+
37
+ var payload = Buffer.allocUnsafe(21)
38
+ payload.writeUInt8(version, 0)
39
+ hash.copy(payload, 1)
40
+
41
+ return bs58check.encode(payload)
42
+ }
43
+
44
+ function toBech32 (data, version, prefix) {
45
+ var words = bech32.toWords(data)
46
+ words.unshift(version)
47
+
48
+ return bech32.encode(prefix, words)
49
+ }
50
+
51
+ function fromOutputScript (outputScript, network) {
52
+ network = network || networks.bitcoin
53
+
54
+ if (btemplates.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash)
55
+ if (btemplates.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash)
56
+ if (btemplates.witnessPubKeyHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 22), 0, network.bech32)
57
+ if (btemplates.witnessScriptHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 34), 0, network.bech32)
58
+
59
+ throw new Error(bscript.toASM(outputScript) + ' has no matching Address')
60
+ }
61
+
62
+ function toOutputScript (address, network) {
63
+ network = network || networks.bitcoin
64
+
65
+ var decode
66
+ try {
67
+ decode = fromBase58Check(address)
68
+ } catch (e) {}
69
+
70
+ if (decode) {
71
+ if (decode.version === network.pubKeyHash) return btemplates.pubKeyHash.output.encode(decode.hash)
72
+ if (decode.version === network.scriptHash) return btemplates.scriptHash.output.encode(decode.hash)
73
+ } else {
74
+ try {
75
+ decode = fromBech32(address)
76
+ } catch (e) {}
77
+
78
+ if (decode) {
79
+ if (decode.prefix !== network.bech32) throw new Error(address + ' has an invalid prefix')
80
+ if (decode.version === 0) {
81
+ if (decode.data.length === 20) return btemplates.witnessPubKeyHash.output.encode(decode.data)
82
+ if (decode.data.length === 32) return btemplates.witnessScriptHash.output.encode(decode.data)
83
+ }
84
+ }
85
+ }
86
+
87
+ throw new Error(address + ' has no matching Script')
88
+ }
89
+
90
+ module.exports = {
91
+ fromBase58Check: fromBase58Check,
92
+ fromBech32: fromBech32,
93
+ fromOutputScript: fromOutputScript,
94
+ toBase58Check: toBase58Check,
95
+ toBech32: toBech32,
96
+ toOutputScript: toOutputScript
97
+ }
package/src/block.js ADDED
@@ -0,0 +1,177 @@
1
+ var Buffer = require('safe-buffer').Buffer
2
+ var bcrypto = require('./crypto')
3
+ var fastMerkleRoot = require('merkle-lib/fastRoot')
4
+ var typeforce = require('typeforce')
5
+ var types = require('./types')
6
+ var varuint = require('varuint-bitcoin')
7
+
8
+ var Transaction = require('./transaction')
9
+
10
+ function Block () {
11
+ this.version = 1
12
+ this.prevHash = null
13
+ this.merkleRoot = null
14
+ this.timestamp = 0
15
+ this.bits = 0
16
+ this.nonce = 0
17
+ }
18
+
19
+ Block.fromBuffer = function (buffer) {
20
+ if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)')
21
+
22
+ var offset = 0
23
+ function readSlice (n) {
24
+ offset += n
25
+ return buffer.slice(offset - n, offset)
26
+ }
27
+
28
+ function readUInt32 () {
29
+ var i = buffer.readUInt32LE(offset)
30
+ offset += 4
31
+ return i
32
+ }
33
+
34
+ function readInt32 () {
35
+ var i = buffer.readInt32LE(offset)
36
+ offset += 4
37
+ return i
38
+ }
39
+
40
+ var block = new Block()
41
+ block.version = readInt32()
42
+ block.prevHash = readSlice(32)
43
+ block.merkleRoot = readSlice(32)
44
+ block.timestamp = readUInt32()
45
+ block.bits = readUInt32()
46
+ block.nonce = readUInt32()
47
+
48
+ if (buffer.length === 80) return block
49
+
50
+ function readVarInt () {
51
+ var vi = varuint.decode(buffer, offset)
52
+ offset += varuint.decode.bytes
53
+ return vi
54
+ }
55
+
56
+ function readTransaction () {
57
+ var tx = Transaction.fromBuffer(buffer.slice(offset), true)
58
+ offset += tx.byteLength()
59
+ return tx
60
+ }
61
+
62
+ var nTransactions = readVarInt()
63
+ block.transactions = []
64
+
65
+ for (var i = 0; i < nTransactions; ++i) {
66
+ var tx = readTransaction()
67
+ block.transactions.push(tx)
68
+ }
69
+
70
+ return block
71
+ }
72
+
73
+ Block.prototype.byteLength = function (headersOnly) {
74
+ if (headersOnly || !this.transactions) return 80
75
+
76
+ return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) {
77
+ return a + x.byteLength()
78
+ }, 0)
79
+ }
80
+
81
+ Block.fromHex = function (hex) {
82
+ return Block.fromBuffer(Buffer.from(hex, 'hex'))
83
+ }
84
+
85
+ Block.prototype.getHash = function () {
86
+ return bcrypto.hash256(this.toBuffer(true))
87
+ }
88
+
89
+ Block.prototype.getId = function () {
90
+ return this.getHash().reverse().toString('hex')
91
+ }
92
+
93
+ Block.prototype.getUTCDate = function () {
94
+ var date = new Date(0) // epoch
95
+ date.setUTCSeconds(this.timestamp)
96
+
97
+ return date
98
+ }
99
+
100
+ // TODO: buffer, offset compatibility
101
+ Block.prototype.toBuffer = function (headersOnly) {
102
+ var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly))
103
+
104
+ var offset = 0
105
+ function writeSlice (slice) {
106
+ slice.copy(buffer, offset)
107
+ offset += slice.length
108
+ }
109
+
110
+ function writeInt32 (i) {
111
+ buffer.writeInt32LE(i, offset)
112
+ offset += 4
113
+ }
114
+ function writeUInt32 (i) {
115
+ buffer.writeUInt32LE(i, offset)
116
+ offset += 4
117
+ }
118
+
119
+ writeInt32(this.version)
120
+ writeSlice(this.prevHash)
121
+ writeSlice(this.merkleRoot)
122
+ writeUInt32(this.timestamp)
123
+ writeUInt32(this.bits)
124
+ writeUInt32(this.nonce)
125
+
126
+ if (headersOnly || !this.transactions) return buffer
127
+
128
+ varuint.encode(this.transactions.length, buffer, offset)
129
+ offset += varuint.encode.bytes
130
+
131
+ this.transactions.forEach(function (tx) {
132
+ var txSize = tx.byteLength() // TODO: extract from toBuffer?
133
+ tx.toBuffer(buffer, offset)
134
+ offset += txSize
135
+ })
136
+
137
+ return buffer
138
+ }
139
+
140
+ Block.prototype.toHex = function (headersOnly) {
141
+ return this.toBuffer(headersOnly).toString('hex')
142
+ }
143
+
144
+ Block.calculateTarget = function (bits) {
145
+ var exponent = ((bits & 0xff000000) >> 24) - 3
146
+ var mantissa = bits & 0x007fffff
147
+ var target = Buffer.alloc(32, 0)
148
+ target.writeUInt32BE(mantissa, 28 - exponent)
149
+ return target
150
+ }
151
+
152
+ Block.calculateMerkleRoot = function (transactions) {
153
+ typeforce([{ getHash: types.Function }], transactions)
154
+ if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions')
155
+
156
+ var hashes = transactions.map(function (transaction) {
157
+ return transaction.getHash()
158
+ })
159
+
160
+ return fastMerkleRoot(hashes, bcrypto.hash256)
161
+ }
162
+
163
+ Block.prototype.checkMerkleRoot = function () {
164
+ if (!this.transactions) return false
165
+
166
+ var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
167
+ return this.merkleRoot.compare(actualMerkleRoot) === 0
168
+ }
169
+
170
+ Block.prototype.checkProofOfWork = function () {
171
+ var hash = this.getHash().reverse()
172
+ var target = Block.calculateTarget(this.bits)
173
+
174
+ return hash.compare(target) <= 0
175
+ }
176
+
177
+ module.exports = Block
@@ -0,0 +1,56 @@
1
+ var pushdata = require('pushdata-bitcoin')
2
+ var varuint = require('varuint-bitcoin')
3
+
4
+ // https://github.com/feross/buffer/blob/master/index.js#L1127
5
+ function verifuint (value, max) {
6
+ if (typeof value !== 'number') throw new Error('cannot write a non-number as a number')
7
+ if (value < 0) throw new Error('specified a negative value for writing an unsigned value')
8
+ if (value > max) throw new Error('RangeError: value out of range')
9
+ if (Math.floor(value) !== value) throw new Error('value has a fractional component')
10
+ }
11
+
12
+ function readUInt64LE (buffer, offset) {
13
+ var a = buffer.readUInt32LE(offset)
14
+ var b = buffer.readUInt32LE(offset + 4)
15
+ b *= 0x100000000
16
+
17
+ verifuint(b + a, 0x001fffffffffffff)
18
+
19
+ return b + a
20
+ }
21
+
22
+ function writeUInt64LE (buffer, value, offset) {
23
+ verifuint(value, 0x001fffffffffffff)
24
+
25
+ buffer.writeInt32LE(value & -1, offset)
26
+ buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
27
+ return offset + 8
28
+ }
29
+
30
+ // TODO: remove in 4.0.0?
31
+ function readVarInt (buffer, offset) {
32
+ var result = varuint.decode(buffer, offset)
33
+
34
+ return {
35
+ number: result,
36
+ size: varuint.decode.bytes
37
+ }
38
+ }
39
+
40
+ // TODO: remove in 4.0.0?
41
+ function writeVarInt (buffer, number, offset) {
42
+ varuint.encode(number, buffer, offset)
43
+ return varuint.encode.bytes
44
+ }
45
+
46
+ module.exports = {
47
+ pushDataSize: pushdata.encodingLength,
48
+ readPushDataInt: pushdata.decode,
49
+ readUInt64LE: readUInt64LE,
50
+ readVarInt: readVarInt,
51
+ varIntBuffer: varuint.encode,
52
+ varIntSize: varuint.encodingLength,
53
+ writePushDataInt: pushdata.encode,
54
+ writeUInt64LE: writeUInt64LE,
55
+ writeVarInt: writeVarInt
56
+ }
package/src/crypto.js ADDED
@@ -0,0 +1,29 @@
1
+ var createHash = require('create-hash')
2
+
3
+ function ripemd160 (buffer) {
4
+ return createHash('rmd160').update(buffer).digest()
5
+ }
6
+
7
+ function sha1 (buffer) {
8
+ return createHash('sha1').update(buffer).digest()
9
+ }
10
+
11
+ function sha256 (buffer) {
12
+ return createHash('sha256').update(buffer).digest()
13
+ }
14
+
15
+ function hash160 (buffer) {
16
+ return ripemd160(sha256(buffer))
17
+ }
18
+
19
+ function hash256 (buffer) {
20
+ return sha256(sha256(buffer))
21
+ }
22
+
23
+ module.exports = {
24
+ hash160: hash160,
25
+ hash256: hash256,
26
+ ripemd160: ripemd160,
27
+ sha1: sha1,
28
+ sha256: sha256
29
+ }