forked from oipwg/oip-hdmw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.js.html
291 lines (222 loc) · 16.9 KB
/
util.js.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
util.js - Documentation
</title>
<link href="https://www.braintreepayments.com/images/favicon-ccda0b14.png" rel="icon" type="image/png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.7.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.3.0/highlightjs-line-numbers.min.js"></script>
<script>
hljs.initHighlightingOnLoad();
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
<link type="text/css" rel="stylesheet" href="styles/monokai-sublime.css">
<!-- start Mixpanel -->
<script type="text/javascript">(function(e,a){if(!a.__SV){var b=window;try{var c,l,i,j=b.location,g=j.hash;c=function(a,b){return(l=a.match(RegExp(b+"=([^&]*)")))?l[1]:null};g&&c(g,"state")&&(i=JSON.parse(decodeURIComponent(c(g,"state"))),"mpeditor"===i.action&&(b.sessionStorage.setItem("_mpcehash",g),history.replaceState(i.desiredHash||"",e.title,j.pathname+j.search)))}catch(m){}var k,h;window.mixpanel=a;a._i=[];a.init=function(b,c,f){function e(b,a){var c=a.split(".");2==c.length&&(b=b[c[0]],a=c[1]);b[a]=function(){b.push([a].concat(Array.prototype.slice.call(arguments,
0)))}}var d=a;"undefined"!==typeof f?d=a[f]=[]:f="mixpanel";d.people=d.people||[];d.toString=function(b){var a="mixpanel";"mixpanel"!==f&&(a+="."+f);b||(a+=" (stub)");return a};d.people.toString=function(){return d.toString(1)+".people (stub)"};k="disable time_event track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config reset people.set people.set_once people.increment people.append people.union people.track_charge people.clear_charges people.delete_user".split(" ");
for(h=0;h<k.length;h++)e(d,k[h]);a._i.push([b,c,f])};a.__SV=1.2;b=e.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?MIXPANEL_CUSTOM_LIB_URL:"file:"===e.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";c=e.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c)}})(document,window.mixpanel||[]);
mixpanel.init("1919205b2da72e4da3b9b6639b444d59");</script>
<!-- end Mixpanel -->
</head>
<body>
<svg style="display: none;">
<defs>
<symbol id="linkIcon" fill="#706d77" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/>
</symbol>
</defs>
</svg>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<div class="top-nav-wrapper">
<ul>
<li >
<a href="index.html">
<svg fill="#6D6D6D" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
<path d="M0 0h24v24H0z" fill="none"/>
</svg>
</a>
</li>
</ul>
</div>
<nav>
<h3 class="reference-title">
OIP HDMW
</h3>
<h3>Classes</h3><ul><li id="Account-nav"><a href="Account.html">Account</a><ul class='methods'><li data-type="method" id="Account-discoverChain-nav"><a href="Account.html#discoverChain">discoverChain</a></li><li data-type="method" id="Account-discoverChains-nav"><a href="Account.html#discoverChains">discoverChains</a></li><li data-type="method" id="Account-getAddress-nav"><a href="Account.html#getAddress">getAddress</a></li><li data-type="method" id="Account-getAddresses-nav"><a href="Account.html#getAddresses">getAddresses</a></li><li data-type="method" id="Account-getBalance-nav"><a href="Account.html#getBalance">getBalance</a></li><li data-type="method" id="Account-getChain-nav"><a href="Account.html#getChain">getChain</a></li><li data-type="method" id="Account-getExtendedPrivateKey-nav"><a href="Account.html#getExtendedPrivateKey">getExtendedPrivateKey</a></li><li data-type="method" id="Account-getExtendedPublicKey-nav"><a href="Account.html#getExtendedPublicKey">getExtendedPublicKey</a></li><li data-type="method" id="Account-getMainAddress-nav"><a href="Account.html#getMainAddress">getMainAddress</a></li><li data-type="method" id="Account-getNextChainAddress-nav"><a href="Account.html#getNextChainAddress">getNextChainAddress</a></li><li data-type="method" id="Account-getNextChangeAddress-nav"><a href="Account.html#getNextChangeAddress">getNextChangeAddress</a></li><li data-type="method" id="Account-getUsedAddresses-nav"><a href="Account.html#getUsedAddresses">getUsedAddresses</a></li><li data-type="method" id="Account-sendPayment-nav"><a href="Account.html#sendPayment">sendPayment</a></li></ul></li><li id="Address-nav"><a href="Address.html">Address</a><ul class='methods'><li data-type="method" id="Address-addSpentTransaction-nav"><a href="Address.html#addSpentTransaction">addSpentTransaction</a></li><li data-type="method" id="Address-deserialize-nav"><a href="Address.html#deserialize">deserialize</a></li><li data-type="method" id="Address-getBalance-nav"><a href="Address.html#getBalance">getBalance</a></li><li data-type="method" id="Address-getECPair-nav"><a href="Address.html#getECPair">getECPair</a></li><li data-type="method" id="Address-getPrivateAddress-nav"><a href="Address.html#getPrivateAddress">getPrivateAddress</a></li><li data-type="method" id="Address-getPublicAddress-nav"><a href="Address.html#getPublicAddress">getPublicAddress</a></li><li data-type="method" id="Address-getTotalReceived-nav"><a href="Address.html#getTotalReceived">getTotalReceived</a></li><li data-type="method" id="Address-getTotalSent-nav"><a href="Address.html#getTotalSent">getTotalSent</a></li><li data-type="method" id="Address-getUnconfirmedBalance-nav"><a href="Address.html#getUnconfirmedBalance">getUnconfirmedBalance</a></li><li data-type="method" id="Address-getUnspent-nav"><a href="Address.html#getUnspent">getUnspent</a></li><li data-type="method" id="Address-removeSpent-nav"><a href="Address.html#removeSpent">removeSpent</a></li><li data-type="method" id="Address-serialize-nav"><a href="Address.html#serialize">serialize</a></li><li data-type="method" id="Address-signMessage-nav"><a href="Address.html#signMessage">signMessage</a></li><li data-type="method" id="Address-updateState-nav"><a href="Address.html#updateState">updateState</a></li><li data-type="method" id="Address-verifySignature-nav"><a href="Address.html#verifySignature">verifySignature</a></li></ul></li><li id="Coin-nav"><a href="Coin.html">Coin</a><ul class='methods'><li data-type="method" id="Coin-addAccount-nav"><a href="Coin.html#addAccount">addAccount</a></li><li data-type="method" id="Coin-discoverAccounts-nav"><a href="Coin.html#discoverAccounts">discoverAccounts</a></li><li data-type="method" id="Coin-getAccount-nav"><a href="Coin.html#getAccount">getAccount</a></li><li data-type="method" id="Coin-getAccounts-nav"><a href="Coin.html#getAccounts">getAccounts</a></li><li data-type="method" id="Coin-getAddress-nav"><a href="Coin.html#getAddress">getAddress</a></li><li data-type="method" id="Coin-getBalance-nav"><a href="Coin.html#getBalance">getBalance</a></li><li data-type="method" id="Coin-getCoinInfo-nav"><a href="Coin.html#getCoinInfo">getCoinInfo</a></li><li data-type="method" id="Coin-getExtendedPrivateKey-nav"><a href="Coin.html#getExtendedPrivateKey">getExtendedPrivateKey</a></li><li data-type="method" id="Coin-getExtendedPublicKey-nav"><a href="Coin.html#getExtendedPublicKey">getExtendedPublicKey</a></li><li data-type="method" id="Coin-getMainAddress-nav"><a href="Coin.html#getMainAddress">getMainAddress</a></li><li data-type="method" id="Coin-sendPayment-nav"><a href="Coin.html#sendPayment">sendPayment</a></li></ul></li><li id="FloPsbt-nav"><a href="FloPsbt.html">FloPsbt</a></li><li id="FloPsbtTransaction-nav"><a href="FloPsbtTransaction.html">FloPsbtTransaction</a></li><li id="TransactionBuilder-nav"><a href="TransactionBuilder.html">TransactionBuilder</a><ul class='methods'><li data-type="method" id="TransactionBuilder-addFrom-nav"><a href="TransactionBuilder.html#addFrom">addFrom</a></li><li data-type="method" id="TransactionBuilder-addTo-nav"><a href="TransactionBuilder.html#addTo">addTo</a></li><li data-type="method" id="TransactionBuilder-buildInputsAndOutputs-nav"><a href="TransactionBuilder.html#buildInputsAndOutputs">buildInputsAndOutputs</a></li><li data-type="method" id="TransactionBuilder-buildTX-nav"><a href="TransactionBuilder.html#buildTX">buildTX</a></li><li data-type="method" id="TransactionBuilder-discoverChange-nav"><a href="TransactionBuilder.html#discoverChange">discoverChange</a></li><li data-type="method" id="TransactionBuilder-getUnspents-nav"><a href="TransactionBuilder.html#getUnspents">getUnspents</a></li><li data-type="method" id="TransactionBuilder-parseOptions-nav"><a href="TransactionBuilder.html#parseOptions">parseOptions</a></li><li data-type="method" id="TransactionBuilder-sendTX-nav"><a href="TransactionBuilder.html#sendTX">sendTX</a></li></ul></li><li id="Wallet-nav"><a href="Wallet.html">Wallet</a><ul class='methods'><li data-type="method" id="Wallet-addCoin-nav"><a href="Wallet.html#addCoin">addCoin</a></li><li data-type="method" id="Wallet-addTestnetCoins-nav"><a href="Wallet.html#addTestnetCoins">addTestnetCoins</a></li><li data-type="method" id="Wallet-fromEntropy-nav"><a href="Wallet.html#fromEntropy">fromEntropy</a></li><li data-type="method" id="Wallet-fromMnemonic-nav"><a href="Wallet.html#fromMnemonic">fromMnemonic</a></li><li data-type="method" id="Wallet-fromSeed-nav"><a href="Wallet.html#fromSeed">fromSeed</a></li><li data-type="method" id="Wallet-getCoin-nav"><a href="Wallet.html#getCoin">getCoin</a></li><li data-type="method" id="Wallet-getCoinBalances-nav"><a href="Wallet.html#getCoinBalances">getCoinBalances</a></li><li data-type="method" id="Wallet-getCoins-nav"><a href="Wallet.html#getCoins">getCoins</a></li><li data-type="method" id="Wallet-getEntropy-nav"><a href="Wallet.html#getEntropy">getEntropy</a></li><li data-type="method" id="Wallet-getExchangeRates-nav"><a href="Wallet.html#getExchangeRates">getExchangeRates</a></li><li data-type="method" id="Wallet-getExplorerUrls-nav"><a href="Wallet.html#getExplorerUrls">getExplorerUrls</a></li><li data-type="method" id="Wallet-getFiatBalances-nav"><a href="Wallet.html#getFiatBalances">getFiatBalances</a></li><li data-type="method" id="Wallet-getMnemonic-nav"><a href="Wallet.html#getMnemonic">getMnemonic</a></li><li data-type="method" id="Wallet-getNetworks-nav"><a href="Wallet.html#getNetworks">getNetworks</a></li><li data-type="method" id="Wallet-getSeed-nav"><a href="Wallet.html#getSeed">getSeed</a></li><li data-type="method" id="Wallet-sendPayment-nav"><a href="Wallet.html#sendPayment">sendPayment</a></li><li data-type="method" id="Wallet-setExplorerUrls-nav"><a href="Wallet.html#setExplorerUrls">setExplorerUrls</a></li></ul></li></ul><h3>Modules</h3><ul><li id="util-nav"><a href="module-util.html">util</a><ul class='methods'><li data-type="method" id="util-isEntropy-nav"><a href="module-util.html#~isEntropy">isEntropy</a></li><li data-type="method" id="util-isMnemonic-nav"><a href="module-util.html#~isMnemonic">isMnemonic</a></li><li data-type="method" id="util-isValidPublicAddress-nav"><a href="module-util.html#~isValidPublicAddress">isValidPublicAddress</a></li><li data-type="method" id="util-isValidWIF-nav"><a href="module-util.html#~isValidWIF">isValidWIF</a></li><li data-type="method" id="util-toBase58-nav"><a href="module-util.html#~toBase58">toBase58</a></li></ul></li></ul><h3 id="global-nav">Global</h3><ul><li><a href="global.html#DEFAULT_OPTS">DEFAULT_OPTS</a></li><li><a href="global.html#transactionFromBuffer">transactionFromBuffer</a></li></ul>
</nav>
<div id="main">
<h1 class="page-title">
util.js
</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import * as bitcoin from '@oipwg/bitcoinjs-lib'
import { Buffer } from 'safe-buffer'
import createHash from 'create-hash'
import bs58check from 'bs58check'
import wif from 'wif'
import varuint from 'varuint-bitcoin'
/** @module util */
function ripemd160 (buffer) {
return createHash('rmd160').update(buffer).digest()
}
function sha256 (buffer) {
return createHash('sha256').update(buffer).digest()
}
function hash256 (buffer) {
return sha256(sha256(buffer))
}
function hash160 (buffer) {
return ripemd160(sha256(buffer))
}
function toBase58Check (hash, version) {
const payload = Buffer.allocUnsafe(21)
payload.writeUInt8(version, 0)
hash.copy(payload, 1)
return bs58check.encode(payload)
}
/**
* @param {Buffer} key - The buffer for the Private/Public Key to encode
* @param {number} version - The specific "version" byte to prepend
* @return {string} Returns the Base58 encoded Key
*/
function toBase58 (key, version) {
if (!key) {
return console.log('KEY NULL!!!!')
}
return toBase58Check(hash160(key), version)
}
/**
* Check if a WIF is valid for a specific CoinNetwork
* @param {string} key - Base58 WIF Private Key
* @param {CoinNetwork} network
* @return {Boolean}
*/
function isValidWIF (key, network) {
try {
const dec = wif.decode(key)
if (network) {
return dec.version === network.wif
} else {
return true
}
} catch (e) {
console.error(e)
return false
}
}
/**
* Check if a Public Address is valid for a specific CoinNetwork
* @param {string} address - Base58 Public Address
* @param {CoinNetwork} network
* @return {Boolean}
*/
function isValidPublicAddress (address, network) {
try {
const dec = bitcoin.address.fromBase58Check(address)
if (network) {
return dec.version === network.pubKeyHash || dec.version === network.scriptHash
} else {
return true
}
} catch (e) {
return false
}
}
// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account-discovery
async function discovery (chain, gapLimit, queryPromise, i, coin) {
let gap = 0
let checked = 0
const allAddresses = []
const cycle = async (myCoin) => {
const batch = [chain.get()]
checked++
while (batch.length < gapLimit) {
chain.next()
batch.push(chain.get())
checked++
}
let queryResultSet
try {
queryResultSet = await queryPromise(batch, myCoin)
} catch (e) {
throw new Error('discovery failed! \n' + e)
}
for (const adr of queryResultSet.addresses) { allAddresses.push(adr) }
if (Array.isArray(queryResultSet.results)) { throw new TypeError('Expected query set, not Array') }
// iterate batch, guarantees order agnostic of queryPromise result ordering
batch.forEach(function (a) {
if (queryResultSet.results[toBase58(a.address.publicKey, a.network.pubKeyHash)]) {
gap = 0
} else {
gap += 1
}
})
if (gap >= gapLimit) {
const used = checked - gap
return { used: used, checked: checked, chainIndex: i, addresses: allAddresses }
} else {
chain.next()
}
try {
return await cycle(myCoin)
} catch (e) { throw new Error(e) }
}
try {
return await cycle(coin)
} catch (e) { throw new Error(e) }
}
/**
* Check if a given string is in a BIP39 Mnemonic format (is a string, and is at least 2 words long).
* Please note that this does not validate if the Mnemonic is a valid BIP39 Mnemonic
* (i.e. defined from Entropy vs a Brain Wallet)
* @param {string} mnemonic - BIP39 Mnemonic to check
* @return {Boolean}
*/
function isMnemonic (mnemonic) {
if (typeof mnemonic === 'string' && mnemonic.split(' ').length >= 2) { return true }
return false
}
/**
* Check if a given string is a BIP39 Entropy string.
* @param {string} entropy - The Entropy string to check
* @return {Boolean}
*/
function isEntropy (entropy) {
if (typeof entropy === 'string' && entropy.length >= 16 && entropy.length <= 32) { return true }
return false
}
module.exports = {
hash160,
hash256,
toBase58,
isValidPublicAddress,
isValidWIF,
isMnemonic,
isEntropy,
discovery,
varIntBuffer: varuint.encode
}
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.5</a>
</footer>
<script src="scripts/linenumber.js"></script>
<script src="scripts/pagelocation.js"></script>
</body>
</html>