@onekeyfe/kaspa-core-lib 1.0.0-alpha.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 (53) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +59 -0
  3. package/index.d.ts +410 -0
  4. package/index.js +93 -0
  5. package/lib/address.js +792 -0
  6. package/lib/block/block.js +281 -0
  7. package/lib/block/blockheader.js +296 -0
  8. package/lib/block/index.js +4 -0
  9. package/lib/block/merkleblock.js +313 -0
  10. package/lib/crypto/bn.js +218 -0
  11. package/lib/crypto/ecdsa.js +296 -0
  12. package/lib/crypto/hash.js +85 -0
  13. package/lib/crypto/point.js +166 -0
  14. package/lib/crypto/random.js +57 -0
  15. package/lib/crypto/schnorr.js +287 -0
  16. package/lib/crypto/signature.js +441 -0
  17. package/lib/encoding/base58.js +70 -0
  18. package/lib/encoding/base58check.js +95 -0
  19. package/lib/encoding/bufferreader.js +202 -0
  20. package/lib/encoding/bufferwriter.js +155 -0
  21. package/lib/encoding/varint.js +72 -0
  22. package/lib/errors/index.js +61 -0
  23. package/lib/errors/spec.js +191 -0
  24. package/lib/hdprivatekey.js +646 -0
  25. package/lib/hdpublickey.js +496 -0
  26. package/lib/networks.js +277 -0
  27. package/lib/opcode.js +261 -0
  28. package/lib/privatekey.js +431 -0
  29. package/lib/publickey.js +375 -0
  30. package/lib/script/index.js +3 -0
  31. package/lib/script/interpreter.js +2107 -0
  32. package/lib/script/script.js +1163 -0
  33. package/lib/transaction/index.js +7 -0
  34. package/lib/transaction/input/index.js +6 -0
  35. package/lib/transaction/input/input.js +375 -0
  36. package/lib/transaction/input/multisig.js +221 -0
  37. package/lib/transaction/input/multisigscripthash.js +178 -0
  38. package/lib/transaction/input/publickey.js +91 -0
  39. package/lib/transaction/input/publickeyhash.js +100 -0
  40. package/lib/transaction/output.js +188 -0
  41. package/lib/transaction/sighash.js +534 -0
  42. package/lib/transaction/signature.js +89 -0
  43. package/lib/transaction/transaction.js +1384 -0
  44. package/lib/transaction/unspentoutput.js +109 -0
  45. package/lib/unit.js +238 -0
  46. package/lib/uri.js +223 -0
  47. package/lib/util/base32.js +63 -0
  48. package/lib/util/buffer.js +162 -0
  49. package/lib/util/convertBits.js +62 -0
  50. package/lib/util/js.js +110 -0
  51. package/lib/util/log.js +10 -0
  52. package/lib/util/preconditions.js +34 -0
  53. package/package.json +62 -0
package/lib/address.js ADDED
@@ -0,0 +1,792 @@
1
+ 'use strict';
2
+
3
+ var _ = require('lodash');
4
+ var $ = require('./util/preconditions');
5
+ var errors = require('./errors');
6
+ var Base58Check = require('./encoding/base58check');
7
+ var Networks = require('./networks');
8
+ var Hash = require('./crypto/hash');
9
+ var JSUtil = require('./util/js');
10
+ var PublicKey = require('./publickey');
11
+ var BN = require('./crypto/bn');
12
+
13
+ var base32 = require('./util/base32');
14
+ var convertBits = require('./util/convertBits');
15
+
16
+ /**
17
+ * Instantiate an address from an address String or Buffer, a public key or script hash Buffer,
18
+ * or an instance of {@link PublicKey} or {@link Script}.
19
+ *
20
+ * This is an immutable class, and if the first parameter provided to this constructor is an
21
+ * `Address` instance, the same argument will be returned.
22
+ *
23
+ * An address has two key properties: `network` and `type`. The type is either
24
+ * `Address.PayToPublicKey` (value is the `'pubkey'` string)
25
+ * or `Address.PayToScriptHash` (the string `'scripthash'`). The network is an instance of {@link Network}.
26
+ * You can quickly check whether an address is of a given kind by using the methods
27
+ * `isPayToPublicKey` and `isPayToScriptHash`
28
+ *
29
+ * @example
30
+ * ```javascript
31
+ * // validate that an input field is valid
32
+ * var error = Address.getValidationError(input, 'testnet');
33
+ * if (!error) {
34
+ * var address = Address(input, 'testnet');
35
+ * } else {
36
+ * // invalid network or checksum (typo?)
37
+ * var message = error.messsage;
38
+ * }
39
+ *
40
+ * // get an address from a public key
41
+ * var address = Address(publicKey, 'testnet').toString();
42
+ * ```
43
+ *
44
+ * @param {*} data - The encoded data in various formats
45
+ * @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
46
+ * @param {string=} type - The type of address: 'script' or 'pubkey'
47
+ * @returns {Address} A new valid and frozen instance of an Address
48
+ * @constructor
49
+ */
50
+ function Address(data, network, type) {
51
+ /* jshint maxcomplexity: 12 */
52
+ /* jshint maxstatements: 20 */
53
+
54
+ if (!(this instanceof Address)) {
55
+ return new Address(data, network, type);
56
+ }
57
+
58
+ if (_.isArray(data) && _.isNumber(network)) {
59
+ return Address.createMultisig(data, network, type);
60
+ }
61
+
62
+ if (data instanceof Address) {
63
+ // Immutable instance
64
+ return data;
65
+ }
66
+
67
+ $.checkArgument(data, 'First argument is required, please include address data.', 'guide/address.html');
68
+
69
+ if (network && !Networks.get(network)) {
70
+ throw new TypeError('Second argument must be "livenet", "testnet", or "regtest".');
71
+ }
72
+
73
+ if (type && (type !== Address.PayToPublicKey && type !== Address.PayToScriptHash)) {
74
+ throw new TypeError('Third argument must be "pubkey" or "scripthash".');
75
+ }
76
+
77
+ var info = this._classifyArguments(data, network, type);
78
+
79
+ // set defaults if not set
80
+ info.network = info.network || Networks.get(network) || Networks.defaultNetwork;
81
+ info.type = info.type || type || Address.PayToPublicKey;
82
+
83
+ JSUtil.defineImmutable(this, {
84
+ hashBuffer: info.hashBuffer,
85
+ network: info.network,
86
+ type: info.type
87
+ });
88
+
89
+ return this;
90
+ }
91
+
92
+ /**
93
+ * Internal function used to split different kinds of arguments of the constructor
94
+ * @param {*} data - The encoded data in various formats
95
+ * @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
96
+ * @param {string=} type - The type of address: 'script' or 'pubkey'
97
+ * @returns {Object} An "info" object with "type", "network", and "hashBuffer"
98
+ */
99
+ Address.prototype._classifyArguments = function(data, network, type) {
100
+ /* jshint maxcomplexity: 10 */
101
+ // transform and validate input data
102
+ if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 32) {
103
+ return Address._transformPublicKeyBuffer(data);
104
+ } else if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 21) {
105
+ return Address._transformBuffer(data, network, type);
106
+ } else if (data instanceof PublicKey) {
107
+ return Address._transformPublicKey(data);
108
+ } else if (data instanceof Script) {
109
+ return Address._transformScript(data, network);
110
+ } else if (typeof(data) === 'string') {
111
+ return Address._transformString(data, network, type);
112
+ } else if (_.isObject(data)) {
113
+ return Address._transformObject(data);
114
+ } else {
115
+ throw new TypeError('First argument is an unrecognized data format.');
116
+ }
117
+ };
118
+
119
+ /** @static */
120
+ Address.PayToPublicKey = 'pubkey';
121
+ /** @static */
122
+ Address.PayToScriptHash = 'scripthash';
123
+
124
+ /**
125
+ * @param {Buffer} hash - An instance of a hash Buffer
126
+ * @returns {Object} An object with keys: hashBuffer
127
+ * @private
128
+ */
129
+ Address._transformHash = function(hash) {
130
+ var info = {};
131
+ if (!(hash instanceof Buffer) && !(hash instanceof Uint8Array)) {
132
+ throw new TypeError('Address supplied is not a buffer.');
133
+ }
134
+ if (hash.length !== 20) {
135
+ throw new TypeError('Address hashbuffers must be exactly 20 bytes.');
136
+ }
137
+ info.hashBuffer = hash;
138
+ return info;
139
+ };
140
+
141
+ /**
142
+ * Deserializes an address serialized through `Address#toObject()`
143
+ * @param {Object} data
144
+ * @param {string} data.hash - the hash that this address encodes
145
+ * @param {string} data.type - either 'pubkey' or 'scripthash'
146
+ * @param {Network=} data.network - the name of the network associated
147
+ * @return {Address}
148
+ */
149
+ Address._transformObject = function(data) {
150
+ $.checkArgument(data.hash || data.hashBuffer, 'Must provide a `hash` or `hashBuffer` property');
151
+ $.checkArgument(data.type, 'Must provide a `type` property');
152
+ return {
153
+ hashBuffer: data.hash ? Buffer.from(data.hash, 'hex') : data.hashBuffer,
154
+ network: Networks.get(data.network) || Networks.defaultNetwork,
155
+ type: data.type
156
+ };
157
+ };
158
+
159
+ /**
160
+ * Internal function to discover the network and type based on the first data byte
161
+ *
162
+ * @param {Buffer} buffer - An instance of a hex encoded address Buffer
163
+ * @returns {Object} An object with keys: network and type
164
+ * @private
165
+ */
166
+ Address._classifyFromVersion = function(buffer) {
167
+ var version = {};
168
+
169
+ var pubkeyNetwork = Networks.get(buffer[0], 'pubkeyhash');
170
+ var scripthashNetwork = Networks.get(buffer[0], 'scripthash');
171
+
172
+ if (pubkeyNetwork) {
173
+ version.network = pubkeyNetwork;
174
+ version.type = Address.PayToPublicKey;
175
+ } else if (scripthashNetwork) {
176
+ version.network = scripthashNetwork;
177
+ version.type = Address.PayToScriptHash;
178
+ }
179
+
180
+ return version;
181
+ };
182
+
183
+ /**
184
+ * Internal function to transform a bitcoin address buffer
185
+ *
186
+ * @param {Buffer} buffer - An instance of a hex encoded address Buffer
187
+ * @param {string=} network - The network: 'livenet' or 'testnet'
188
+ * @param {string=} type - The type: 'pubkey' or 'scripthash'
189
+ * @returns {Object} An object with keys: hashBuffer, network and type
190
+ * @private
191
+ */
192
+ Address._transformBuffer = function(buffer, network, type) {
193
+ /* jshint maxcomplexity: 9 */
194
+ var info = {};
195
+ if (!(buffer instanceof Buffer) && !(buffer instanceof Uint8Array)) {
196
+ throw new TypeError('Address supplied is not a buffer.');
197
+ }
198
+ if (buffer.length !== 1 + 20) {
199
+ throw new TypeError('Address buffers must be exactly 21 bytes.');
200
+ }
201
+
202
+ var networkObj = Networks.get(network);
203
+ var bufferVersion = Address._classifyFromVersion(buffer);
204
+
205
+ if (network && !networkObj) {
206
+ throw new TypeError('Unknown network');
207
+ }
208
+
209
+ if (!bufferVersion.network || (networkObj && networkObj !== bufferVersion.network)) {
210
+ throw new TypeError('Address has mismatched network type.');
211
+ }
212
+
213
+ if (!bufferVersion.type || (type && type !== bufferVersion.type)) {
214
+ throw new TypeError('Address has mismatched type.');
215
+ }
216
+
217
+ info.hashBuffer = buffer.slice(1);
218
+ info.network = bufferVersion.network;
219
+ info.type = bufferVersion.type;
220
+ return info;
221
+ };
222
+
223
+ /**
224
+ * Internal function to transform a {@link PublicKey}
225
+ *
226
+ * @param {PublicKey} pubkey - An instance of PublicKey
227
+ * @returns {Object} An object with keys: hashBuffer, type
228
+ * @private
229
+ */
230
+ Address._transformPublicKey = function(pubkey) {
231
+ var info = {};
232
+ if (!(pubkey instanceof PublicKey)) {
233
+ throw new TypeError('Address must be an instance of PublicKey.');
234
+ }
235
+ info.hashBuffer = pubkey.toBuffer();
236
+ info.type = Address.PayToPublicKey;
237
+ return info;
238
+ };
239
+
240
+ /**
241
+ * Internal function to transform a {@link Buffer}
242
+ *
243
+ * @param {Buffer} pubkeyBuffer - A buffer of the public key
244
+ * @returns {Object} An object with keys: hashBuffer, type
245
+ * @private
246
+ */
247
+ Address._transformPublicKeyBuffer = function(pubkeyBuffer) {
248
+ var info = {};
249
+ if (!(pubkeyBuffer instanceof Buffer)) {
250
+ throw new TypeError('pubkeyBuffer must be a buffer');
251
+ }
252
+ info.hashBuffer = pubkeyBuffer;
253
+ info.type = Address.PayToPublicKey;
254
+ return info;
255
+ };
256
+
257
+ /**
258
+ * Internal function to transform a {@link Script} into a `info` object.
259
+ *
260
+ * @param {Script} script - An instance of Script
261
+ * @returns {Object} An object with keys: hashBuffer, type
262
+ * @private
263
+ */
264
+ Address._transformScript = function(script, network) {
265
+ $.checkArgument(script instanceof Script, 'script must be a Script instance');
266
+ var info = script.getAddressInfo(network);
267
+ if (!info) {
268
+ throw new errors.Script.CantDeriveAddress(script);
269
+ }
270
+ return info;
271
+ };
272
+
273
+ /**
274
+ * Creates a P2SH address from a set of public keys and a threshold.
275
+ *
276
+ * The addresses will be sorted lexicographically, as that is the trend in bitcoin.
277
+ * To create an address from unsorted public keys, use the {@link Script#buildMultisigOut}
278
+ * interface.
279
+ *
280
+ * @param {Array} publicKeys - a set of public keys to create an address
281
+ * @param {number} threshold - the number of signatures needed to release the funds
282
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
283
+ * @return {Address}
284
+ */
285
+ Address.createMultisig = function(publicKeys, threshold, network) {
286
+ network = network || publicKeys[0].network || Networks.defaultNetwork;
287
+ return Address.payingTo(Script.buildMultisigOut(publicKeys, threshold), network);
288
+ };
289
+
290
+ function decodeCashAddress(address) {
291
+
292
+
293
+ function hasSingleCase(string) {
294
+ var lowerCase = string.toLowerCase();
295
+ var upperCase = string.toUpperCase();
296
+ var hasSingleCase = string === lowerCase || string === upperCase;
297
+
298
+ return hasSingleCase;
299
+ }
300
+
301
+ function validChecksum(prefix, payload) {
302
+ function prefixToArray(prefix) {
303
+ var result = [];
304
+ for (var i=0; i<prefix.length; i++) {
305
+ result.push(prefix.charCodeAt(i) & 31);
306
+ }
307
+ return result;
308
+ }
309
+
310
+ var prefixData = prefixToArray(prefix).concat([0]);
311
+ return polymod(prefixData.concat(payload)) === 0;
312
+ }
313
+
314
+ $.checkArgument(hasSingleCase(address), 'Mixed case');
315
+ address = address.toLowerCase();
316
+
317
+ var pieces = address.split(':');
318
+ $.checkArgument(pieces.length <= 2, 'Invalid format:'+ address);
319
+
320
+ var prefix, encodedPayload;
321
+
322
+ if (pieces.length === 2) {
323
+ prefix = pieces[0];
324
+ encodedPayload = pieces[1];
325
+ } else {
326
+ prefix = null;
327
+ encodedPayload = pieces[0];
328
+ }
329
+
330
+
331
+
332
+ var payload = base32.decode(encodedPayload.toLowerCase());
333
+
334
+ if (prefix) {
335
+ $.checkArgument(validChecksum(prefix, payload), 'Invalid checksum:'+ address);
336
+ } else {
337
+
338
+ var netNames = ['livenet','testnet','regtest'];
339
+ var i;
340
+
341
+ while(!prefix && (i = netNames.shift())){
342
+ var p = Networks.get(i).prefix;
343
+ if(validChecksum(p, payload)) {
344
+ prefix = p;
345
+ }
346
+ }
347
+ $.checkArgument(prefix, 'Invalid checksum:'+ address);
348
+ }
349
+
350
+ var convertedBits = convertBits(payload.slice(0, -8), 5, 8, true);
351
+ var versionByte = convertedBits.shift();
352
+ var hashOrPublicKey = convertedBits;
353
+
354
+ if (versionByte == 1){
355
+ $.checkArgument(264 === hashOrPublicKey.length * 8, 'Invalid hash size:'+ address);
356
+ }else{
357
+ $.checkArgument(256 === hashOrPublicKey.length * 8, 'Invalid hash size:'+ address);
358
+ }
359
+
360
+ function getType(versionByte) {
361
+ switch (versionByte & 120) {
362
+ case 0:
363
+ return 'pubkey';
364
+ case 8:
365
+ return 'scripthash';
366
+ default:
367
+ throw new Error('Invalid address type in version byte:' + versionByte);
368
+ }
369
+ }
370
+
371
+
372
+ var type = getType(versionByte);
373
+ var network = Networks.get(prefix);
374
+ //console.log('[address.js.336:network:]',network); //TODO
375
+
376
+ var info = {};
377
+
378
+ //return { prefix, type, hash };
379
+ //console.log('[address.js.339]', hash); //TODO
380
+
381
+ if (type == 'pubkey'){
382
+ info.hashBuffer = Buffer.from(hashOrPublicKey);
383
+ }else{
384
+ info.hashBuffer = Buffer.from(hashOrPublicKey);
385
+ }
386
+ info.network = network;
387
+ info.type = type;
388
+ return info;
389
+ }
390
+
391
+ Address._decodeCashAddress = decodeCashAddress
392
+
393
+ /**
394
+ * Internal function to transform a bitcoin cash address string
395
+ *
396
+ * @param {string} data
397
+ * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet'
398
+ * @param {string=} type - The type: 'pubkey' or 'scripthash'
399
+ * @returns {Object} An object with keys: hashBuffer, network and type
400
+ * @private
401
+ */
402
+ Address._transformString = function(data, network, type) {
403
+ if (typeof(data) !== 'string') {
404
+ throw new TypeError('data parameter supplied is not a string.');
405
+ }
406
+ if (data.length < 34){
407
+ throw new Error('Invalid address');
408
+ }
409
+
410
+ if(data.length > 100) {
411
+ throw new TypeError('address string is too long');
412
+ }
413
+
414
+ data = data.trim();
415
+ var networkObj = Networks.get(network);
416
+
417
+ if (network && !networkObj) {
418
+ throw new TypeError('Unknown network');
419
+ }
420
+
421
+ if (data.length > 35){
422
+ var info = decodeCashAddress(data);
423
+ if (!info.network || (networkObj && networkObj.name !== info.network.name)) {
424
+ throw new TypeError('Address has mismatched network type.');
425
+ }
426
+ if (!info.type || (type && type !== info.type)) {
427
+ throw new TypeError('Address has mismatched type.');
428
+ }
429
+ return info;
430
+ } else {
431
+ var addressBuffer = Base58Check.decode(data);
432
+ // Legacy addr
433
+ return Address._transformBuffer(addressBuffer, network, type);
434
+ }
435
+ };
436
+
437
+
438
+ /**
439
+ * Instantiate an address from a PublicKey instance
440
+ *
441
+ * @param {PublicKey} data
442
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
443
+ * @returns {Address} A new valid and frozen instance of an Address
444
+ */
445
+ Address.fromPublicKey = function(data, network) {
446
+ var info = Address._transformPublicKey(data);
447
+ network = network || Networks.defaultNetwork;
448
+ return new Address(info.hashBuffer, network, info.type);
449
+ };
450
+
451
+ /**
452
+ * Instantiate an address from a public key
453
+ *
454
+ * @param {Buffer} data - A buffer of the public key
455
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
456
+ * @returns {Address} A new valid and frozen instance of an Address
457
+ */
458
+ Address.fromPublicKeyBuffer = function(data, network) {
459
+ var info = Address._transformPublicKeyBuffer(data);
460
+ return new Address(info.hashBuffer, network, Address.PayToPublicKeyHash);
461
+ };
462
+
463
+
464
+ /**
465
+ * Instantiate an address from a ripemd160 script hash
466
+ *
467
+ * @param {Buffer} hash - An instance of buffer of the hash
468
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
469
+ * @returns {Address} A new valid and frozen instance of an Address
470
+ */
471
+ Address.fromScriptHash = function(hash, network) {
472
+ $.checkArgument(hash, 'hash parameter is required');
473
+ var info = Address._transformHash(hash);
474
+ return new Address(info.hashBuffer, network, Address.PayToScriptHash);
475
+ };
476
+
477
+ /**
478
+ * Builds a p2sh address paying to script. This will hash the script and
479
+ * use that to create the address.
480
+ * If you want to extract an address associated with a script instead,
481
+ * see {{Address#fromScript}}
482
+ *
483
+ * @param {Script} script - An instance of Script
484
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
485
+ * @returns {Address} A new valid and frozen instance of an Address
486
+ */
487
+ Address.payingTo = function(script, network) {
488
+ $.checkArgument(script, 'script is required');
489
+ $.checkArgument(script instanceof Script, 'script must be instance of Script');
490
+
491
+ return Address.fromScriptHash(Hash.sha256ripemd160(script.toBuffer()), network);
492
+ };
493
+
494
+ /**
495
+ * Extract address from a Script. The script must be of one
496
+ * of the following types: p2pkh input, p2pkh output, p2sh input
497
+ * or p2sh output.
498
+ * This will analyze the script and extract address information from it.
499
+ * If you want to transform any script to a p2sh Address paying
500
+ * to that script's hash instead, use {{Address#payingTo}}
501
+ *
502
+ * @param {Script} script - An instance of Script
503
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
504
+ * @returns {Address} A new valid and frozen instance of an Address
505
+ */
506
+ Address.fromScript = function(script, network) {
507
+ $.checkArgument(script instanceof Script, 'script must be a Script instance');
508
+ var info = Address._transformScript(script, network);
509
+ return new Address(info.hashBuffer, network, info.type);
510
+ };
511
+
512
+ /**
513
+ * Instantiate an address from a buffer of the address
514
+ *
515
+ * @param {Buffer} buffer - An instance of buffer of the address
516
+ * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet'
517
+ * @param {string=} type - The type of address: 'script' or 'pubkey'
518
+ * @returns {Address} A new valid and frozen instance of an Address
519
+ */
520
+ Address.fromBuffer = function(buffer, network, type) {
521
+ var info = Address._transformBuffer(buffer, network, type);
522
+ return new Address(info.hashBuffer, info.network, info.type);
523
+ };
524
+
525
+ /**
526
+ * Instantiate an address from an address string
527
+ *
528
+ * @param {string} str - An string of the bitcoin address
529
+ * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet'
530
+ * @param {string=} type - The type of address: 'script' or 'pubkey'
531
+ * @returns {Address} A new valid and frozen instance of an Address
532
+ */
533
+ Address.fromString = function(str, network, type) {
534
+ var info = Address._transformString(str, network, type);
535
+ return new Address(info.hashBuffer, info.network, info.type);
536
+ };
537
+
538
+ /**
539
+ * Instantiate an address from an Object
540
+ *
541
+ * @param {string} json - An JSON string or Object with keys: hash, network and type
542
+ * @returns {Address} A new valid instance of an Address
543
+ */
544
+ Address.fromObject = function fromObject(obj) {
545
+ $.checkState(
546
+ JSUtil.isHexa(obj.hash),
547
+ 'Unexpected hash property, "' + obj.hash + '", expected to be hex.'
548
+ );
549
+ var hashBuffer = Buffer.from(obj.hash, 'hex');
550
+ return new Address(hashBuffer, obj.network, obj.type);
551
+ };
552
+
553
+ /**
554
+ * Will return a validation error if exists
555
+ *
556
+ * @example
557
+ * ```javascript
558
+ * // a network mismatch error
559
+ * var error = Address.getValidationError('15vkcKf7gB23wLAnZLmbVuMiiVDc1Nm4a2', 'testnet');
560
+ * ```
561
+ *
562
+ * @param {string} data - The encoded data
563
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
564
+ * @param {string} type - The type of address: 'script' or 'pubkey'
565
+ * @returns {null|Error} The corresponding error message
566
+ */
567
+ Address.getValidationError = function(data, network, type) {
568
+ var error;
569
+ try {
570
+ /* jshint nonew: false */
571
+ new Address(data, network, type);
572
+ } catch (e) {
573
+ error = e;
574
+ }
575
+ return error;
576
+ };
577
+
578
+ /**
579
+ * Will return a boolean if an address is valid
580
+ *
581
+ * @example
582
+ * ```javascript
583
+ * assert(Address.isValid('15vkcKf7gB23wLAnZLmbVuMiiVDc1Nm4a2', 'livenet'));
584
+ * ```
585
+ *
586
+ * @param {string} data - The encoded data
587
+ * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
588
+ * @param {string} type - The type of address: 'script' or 'pubkey'
589
+ * @returns {boolean} The corresponding error message
590
+ */
591
+ Address.isValid = function(data, network, type) {
592
+ return !Address.getValidationError(data, network, type);
593
+ };
594
+
595
+ /**
596
+ * Returns true if an address is of pay to public key hash type
597
+ * @return boolean
598
+ */
599
+ Address.prototype.isPayToPublicKey = function() {
600
+ return this.type === Address.PayToPublicKey;
601
+ };
602
+
603
+ /**
604
+ * Returns true if an address is of pay to script hash type
605
+ * @return boolean
606
+ */
607
+ Address.prototype.isPayToScriptHash = function() {
608
+ return this.type === Address.PayToScriptHash;
609
+ };
610
+
611
+ /**
612
+ * Will return a buffer representation of the address
613
+ *
614
+ * @returns {Buffer} Bitcoin address buffer
615
+ */
616
+ Address.prototype.toBuffer = function() {
617
+ var version = Buffer.from([this.network[this.type]]);
618
+ var buf = Buffer.concat([version, this.hashBuffer]);
619
+ return buf;
620
+ };
621
+
622
+ /**
623
+ * @returns {Object} A plain object with the address information
624
+ */
625
+ Address.prototype.toObject = Address.prototype.toJSON = function toObject() {
626
+ return {
627
+ hash: this.hashBuffer.toString('hex'),
628
+ type: this.type,
629
+ network: this.network.toString()
630
+ };
631
+ };
632
+
633
+ /**
634
+ * Will return a string formatted for the console
635
+ *
636
+ * @returns {string} Bitcoin address
637
+ */
638
+ Address.prototype.inspect = function() {
639
+ return '<Address: ' + this.toString() + ', type: ' + this.type + ', network: ' + this.network + '>';
640
+ };
641
+
642
+ /***
643
+ * @license
644
+ * https://github.com/bitcoincashjs/cashaddr
645
+ * Copyright (c) 2017 Emilio Almansi
646
+ * Distributed under the MIT software license, see the accompanying
647
+ * file LICENSE or http://www.opensource.org/licenses/mit-license.php.
648
+ */
649
+
650
+ Address.prototype.toCashBuffer = function() {
651
+ var version = Buffer.from([this.network[this.type]]);
652
+ var buf = Buffer.concat([version, this.hashBuffer]);
653
+ return buf;
654
+ };
655
+
656
+ /**
657
+ * Will return a the base58 (legacy) string representation of the address
658
+ *
659
+ * @returns {string} Bitcoin address
660
+ */
661
+ Address.prototype.toLegacyAddress = function () {
662
+ return Base58Check.encode(this.toBuffer());
663
+ };
664
+
665
+ /**
666
+ * Will return a cashaddr representation of the address. Always return lower case
667
+ * Can be converted by the caller to uppercase is needed (still valid).
668
+ *
669
+ * @returns {string} Bitcoin Cash address
670
+ */
671
+
672
+
673
+ Address.prototype.toCashAddress = function(stripPrefix) {
674
+ function getTypeBits(type) {
675
+ switch (type) {
676
+ case 'pubkey':
677
+ return 0;
678
+ case 'scripthash':
679
+ return 8;
680
+ default:
681
+ throw new Error('Invalid type:'+ type);
682
+ }
683
+ }
684
+
685
+ function getHashSizeBits(hash) {
686
+ switch (hash.length * 8) {
687
+ case 160:
688
+ return 0;
689
+ case 192:
690
+ return 1;
691
+ case 224:
692
+ return 2;
693
+ case 256:
694
+ return 3;
695
+ case 320:
696
+ return 4;
697
+ case 384:
698
+ return 5;
699
+ case 448:
700
+ return 6;
701
+ case 512:
702
+ return 7;
703
+ default:
704
+ throw new Error('Invalid hash size:'+ hash.length);
705
+ }
706
+ }
707
+
708
+ var eight0 = [0,0,0,0, 0,0,0,0];
709
+ var prefixData = this.network.prefixArray.concat([0]);
710
+ var versionByte = getTypeBits(this.type)
711
+ var arr = Array.prototype.slice.call(this.hashBuffer, 0);
712
+ var payloadData = convertBits([versionByte].concat(arr), 8, 5);
713
+ var checksumData = prefixData.concat(payloadData).concat(eight0);
714
+ var payload = payloadData.concat(checksumToArray(polymod(checksumData)));
715
+ if(stripPrefix === true) {
716
+ return base32.encode(payload);
717
+ } else {
718
+ return this.network.prefix+ ':' + base32.encode(payload);
719
+ }
720
+ };
721
+
722
+ /**
723
+ * Will return a string representation of the address (defaults to CashAddr format)
724
+ *
725
+ * @returns {string} address
726
+ */
727
+ Address.prototype.toString = Address.prototype.toCashAddress;
728
+
729
+
730
+ /***
731
+ * Returns an array representation of the given checksum to be encoded
732
+ * within the address' payload.
733
+ *
734
+ * @param {number} checksum Computed checksum.
735
+ */
736
+ function checksumToArray(checksum) {
737
+ var result = [];
738
+ for (var i = 0; i < 8; ++i) {
739
+ result.push(checksum & 31);
740
+ checksum /= 32;
741
+ }
742
+ return result.reverse();
743
+ }
744
+
745
+ /***
746
+ * Computes a checksum from the given input data as specified for the CashAddr
747
+ * format: https://github.com/Bitcoin-UAHF/spec/blob/master/cashaddr.md.
748
+ *
749
+ * @param {Array} data Array of 5-bit integers over which the checksum is to be computed.
750
+ */
751
+ var GENERATOR1 = [0x98, 0x79, 0xf3, 0xae, 0x1e];
752
+ var GENERATOR2 = [0xf2bc8e61, 0xb76d99e2, 0x3e5fb3c4, 0x2eabe2a8, 0x4f43e470];
753
+
754
+ function polymod(data) {
755
+ // Treat c as 8 bits + 32 bits
756
+ var c0 = 0, c1 = 1, C = 0;
757
+ for (var j = 0; j < data.length; j++) {
758
+ // Set C to c shifted by 35
759
+ C = c0 >>> 3;
760
+ // 0x[07]ffffffff
761
+ c0 &= 0x07;
762
+ // Shift as a whole number
763
+ c0 <<= 5;
764
+ c0 |= c1 >>> 27;
765
+ // 0xffffffff >>> 5
766
+ c1 &= 0x07ffffff;
767
+ c1 <<= 5;
768
+ // xor the last 5 bits
769
+ c1 ^= data[j];
770
+ for (var i = 0; i < GENERATOR1.length; ++i) {
771
+ if (C & (1 << i)) {
772
+ c0 ^= GENERATOR1[i];
773
+ c1 ^= GENERATOR2[i];
774
+ }
775
+ }
776
+ }
777
+ c1 ^= 1;
778
+ // Negative numbers -> large positive numbers
779
+ if (c1 < 0) {
780
+ c1 ^= 1 << 31;
781
+ c1 += (1 << 30) * 2;
782
+ }
783
+ // Unless bitwise operations are used,
784
+ // numbers are consisting of 52 bits, except
785
+ // the sign bit. The result is max 40 bits,
786
+ // so it fits perfectly in one number!
787
+ return c0 * (1 << 30) * 4 + c1;
788
+ }
789
+
790
+ module.exports = Address;
791
+
792
+ var Script = require('./script');