encoding: refactor. remove bip70.

This commit is contained in:
Christopher Jeffrey 2017-10-30 21:02:05 -07:00
parent 8ef82606e1
commit 658d3db928
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
47 changed files with 567 additions and 2399 deletions

View File

@ -41,9 +41,6 @@ bcoin.cache = function cache() {
* Expose
*/
// Horrible BIP
bcoin.bip70 = require('./bip70');
// Blockchain
bcoin.blockchain = require('./blockchain');
bcoin.chain = require('./blockchain/chain');

View File

@ -53,7 +53,6 @@ bcoin.set = function set(network) {
*/
bcoin.cache = function cache() {
bcoin.bip70;
bcoin.blockchain;
bcoin.btc;
bcoin.coins;
@ -77,9 +76,6 @@ bcoin.cache = function cache() {
* Expose
*/
// Horrible BIP
bcoin.define('bip70', './bip70');
// Blockchain
bcoin.define('blockchain', './blockchain');
bcoin.define('chain', './blockchain/chain');

View File

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

View File

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

View File

@ -1,179 +0,0 @@
/*!
* payment.js - bip70 payment for bcoin
* Copyright (c) 2016-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('assert');
const Output = require('../primitives/output');
const TX = require('../primitives/tx');
const Script = require('../script/script');
const ProtoReader = require('../utils/protoreader');
const ProtoWriter = require('../utils/protowriter');
const PaymentDetails = require('./paymentdetails');
/**
* Represents a BIP70 payment.
* @alias module:bip70.Payment
* @constructor
* @param {Object?} options
* @property {Buffer} merchantData
* @property {TX[]} transactions
* @property {Output[]} refundTo
* @property {String|null} memo
*/
function Payment(options) {
if (!(this instanceof Payment))
return new Payment(options);
this.merchantData = null;
this.transactions = [];
this.refundTo = [];
this.memo = null;
if (options)
this.fromOptions(options);
}
/**
* Inject properties from options.
* @private
* @param {Object} options
* @returns {Payment}
*/
Payment.prototype.fromOptions = function fromOptions(options) {
if (options.merchantData)
this.setData(options.merchantData);
if (options.transactions) {
assert(Array.isArray(options.transactions));
for (const item of options.transactions) {
const tx = new TX(item);
this.transactions.push(tx);
}
}
if (options.refundTo) {
assert(Array.isArray(options.refundTo));
for (const item of options.refundTo) {
const output = new Output(item);
this.refundTo.push(output);
}
}
if (options.memo != null) {
assert(typeof options.memo === 'string');
this.memo = options.memo;
}
return this;
};
/**
* Instantiate payment from options.
* @param {Object} options
* @returns {Payment}
*/
Payment.fromOptions = function fromOptions(options) {
return new Payment().fromOptions(options);
};
/**
* Set payment details.
* @method
* @alias Payment#setData
* @param {Object} data
* @param {String?} enc
*/
Payment.prototype.setData = PaymentDetails.prototype.setData;
/**
* Get payment details.
* @method
* @alias Payment#getData
* @param {String?} enc
* @returns {String|Object|null}
*/
Payment.prototype.getData = PaymentDetails.prototype.getData;
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
* @returns {Payment}
*/
Payment.prototype.fromRaw = function fromRaw(data) {
const br = new ProtoReader(data);
this.merchantData = br.readFieldBytes(1, true);
while (br.nextTag() === 2) {
const tx = TX.fromRaw(br.readFieldBytes(2));
this.transactions.push(tx);
}
while (br.nextTag() === 3) {
const op = new ProtoReader(br.readFieldBytes(3));
const output = new Output();
output.value = op.readFieldU64(1, true);
output.script = Script.fromRaw(op.readFieldBytes(2, true));
this.refundTo.push(output);
}
this.memo = br.readFieldString(4, true);
return this;
};
/**
* Instantiate payment from serialized data.
* @param {Buffer} data
* @returns {Payment}
*/
Payment.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = Buffer.from(data, enc);
return new Payment().fromRaw(data);
};
/**
* Serialize the payment (protobuf).
* @returns {Buffer}
*/
Payment.prototype.toRaw = function toRaw() {
const bw = new ProtoWriter();
if (this.merchantData)
bw.writeFieldBytes(1, this.merchantData);
for (const tx of this.transactions)
bw.writeFieldBytes(2, tx.toRaw());
for (const output of this.refundTo) {
const op = new ProtoWriter();
op.writeFieldU64(1, output.value);
op.writeFieldBytes(2, output.script.toRaw());
bw.writeFieldBytes(3, op.render());
}
if (this.memo != null)
bw.writeFieldString(4, this.memo);
return bw.render();
};
/*
* Expose
*/
module.exports = Payment;

View File

@ -1,111 +0,0 @@
/*!
* paymentack.js - bip70 paymentack for bcoin
* Copyright (c) 2016-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('assert');
const ProtoReader = require('../utils/protoreader');
const ProtoWriter = require('../utils/protowriter');
const Payment = require('./payment');
/**
* Represents a BIP70 payment ack.
* @alias module:bip70.PaymentACK
* @constructor
* @param {Object?} options
* @property {Payment} payment
* @property {String|null} memo
*/
function PaymentACK(options) {
if (!(this instanceof PaymentACK))
return new PaymentACK(options);
this.payment = new Payment();
this.memo = null;
if (options)
this.fromOptions(options);
}
/**
* Inject properties from options.
* @private
* @param {Object} options
* @returns {PaymentACK}
*/
PaymentACK.prototype.fromOptions = function fromOptions(options) {
if (options.payment)
this.payment.fromOptions(options.payment);
if (options.memo != null) {
assert(typeof options.memo === 'string');
this.memo = options.memo;
}
return this;
};
/**
* Instantiate payment ack from options.
* @param {Object} options
* @returns {PaymentACK}
*/
PaymentACK.fromOptions = function fromOptions(options) {
return new PaymentACK().fromOptions(options);
};
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
* @returns {PaymentACK}
*/
PaymentACK.prototype.fromRaw = function fromRaw(data) {
const br = new ProtoReader(data);
this.payment.fromRaw(br.readFieldBytes(1));
this.memo = br.readFieldString(2, true);
return this;
};
/**
* Instantiate payment ack from serialized data.
* @param {Buffer} data
* @returns {PaymentACK}
*/
PaymentACK.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = Buffer.from(data, enc);
return new PaymentACK().fromRaw(data);
};
/**
* Serialize the payment ack (protobuf).
* @returns {Buffer}
*/
PaymentACK.prototype.toRaw = function toRaw() {
const bw = new ProtoWriter();
bw.writeFieldBytes(1, this.payment.toRaw());
if (this.memo != null)
bw.writeFieldString(2, this.memo);
return bw.render();
};
/*
* Expose
*/
module.exports = PaymentACK;

View File

@ -1,242 +0,0 @@
/*!
* paymentdetails.js - bip70 paymentdetails for bcoin
* Copyright (c) 2016-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('assert');
const util = require('../utils/util');
const Output = require('../primitives/output');
const ProtoReader = require('../utils/protoreader');
const ProtoWriter = require('../utils/protowriter');
/**
* Represents BIP70 payment details.
* @alias module:bip70.PaymentDetails
* @constructor
* @param {Object?} options
* @property {String|null} network
* @property {Output[]} outputs
* @property {Number} time
* @property {Number} expires
* @property {String|null} memo
* @property {String|null} paymentUrl
* @property {Buffer|null} merchantData
*/
function PaymentDetails(options) {
if (!(this instanceof PaymentDetails))
return new PaymentDetails(options);
this.network = null;
this.outputs = [];
this.time = util.now();
this.expires = -1;
this.memo = null;
this.paymentUrl = null;
this.merchantData = null;
if (options)
this.fromOptions(options);
}
/**
* Inject properties from options.
* @private
* @param {Object} options
* @returns {PaymentDetails}
*/
PaymentDetails.prototype.fromOptions = function fromOptions(options) {
if (options.network != null) {
assert(typeof options.network === 'string');
this.network = options.network;
}
if (options.outputs) {
assert(Array.isArray(options.outputs));
for (const item of options.outputs) {
const output = new Output(item);
this.outputs.push(output);
}
}
if (options.time != null) {
assert(Number.isSafeInteger(options.time));
this.time = options.time;
}
if (options.expires != null) {
assert(Number.isSafeInteger(options.expires));
this.expires = options.expires;
}
if (options.memo != null) {
assert(typeof options.memo === 'string');
this.memo = options.memo;
}
if (options.paymentUrl != null) {
assert(typeof options.paymentUrl === 'string');
this.paymentUrl = options.paymentUrl;
}
if (options.merchantData)
this.setData(options.merchantData);
return this;
};
/**
* Instantiate payment details from options.
* @param {Object} options
* @returns {PaymentDetails}
*/
PaymentDetails.fromOptions = function fromOptions(options) {
return new PaymentDetails().fromOptions(options);
};
/**
* Test whether the payment is expired.
* @returns {Boolean}
*/
PaymentDetails.prototype.isExpired = function isExpired() {
if (this.expires === -1)
return false;
return util.now() > this.expires;
};
/**
* Set payment details.
* @param {Object} data
* @param {String?} enc
*/
PaymentDetails.prototype.setData = function setData(data, enc) {
if (data == null || Buffer.isBuffer(data)) {
this.merchantData = data;
return;
}
if (typeof data !== 'string') {
assert(!enc || enc === 'json');
this.merchantData = Buffer.from(JSON.stringify(data), 'utf8');
return;
}
this.merchantData = Buffer.from(data, enc);
};
/**
* Get payment details.
* @param {String?} enc
* @returns {String|Object|null}
*/
PaymentDetails.prototype.getData = function getData(enc) {
let data = this.merchantData;
if (!data)
return null;
if (!enc)
return data;
if (enc === 'json') {
data = data.toString('utf8');
try {
data = JSON.parse(data);
} catch (e) {
return null;
}
return data;
}
return data.toString(enc);
};
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
* @returns {PaymentDetails}
*/
PaymentDetails.prototype.fromRaw = function fromRaw(data) {
const br = new ProtoReader(data);
this.network = br.readFieldString(1, true);
while (br.nextTag() === 2) {
const op = new ProtoReader(br.readFieldBytes(2));
const output = new Output();
output.value = op.readFieldU64(1, true);
output.script.fromRaw(op.readFieldBytes(2, true));
this.outputs.push(output);
}
this.time = br.readFieldU64(3);
this.expires = br.readFieldU64(4, true);
this.memo = br.readFieldString(5, true);
this.paymentUrl = br.readFieldString(6, true);
this.merchantData = br.readFieldBytes(7, true);
return this;
};
/**
* Instantiate payment details from serialized data.
* @param {Buffer} data
* @returns {PaymentDetails}
*/
PaymentDetails.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = Buffer.from(data, enc);
return new PaymentDetails().fromRaw(data);
};
/**
* Serialize the payment details (protobuf).
* @returns {Buffer}
*/
PaymentDetails.prototype.toRaw = function toRaw() {
const bw = new ProtoWriter();
if (this.network != null)
bw.writeFieldString(1, this.network);
for (const output of this.outputs) {
const op = new ProtoWriter();
op.writeFieldU64(1, output.value);
op.writeFieldBytes(2, output.script.toRaw());
bw.writeFieldBytes(2, op.render());
}
bw.writeFieldU64(3, this.time);
if (this.expires !== -1)
bw.writeFieldU64(4, this.expires);
if (this.memo != null)
bw.writeFieldString(5, this.memo);
if (this.paymentUrl != null)
bw.writeFieldString(6, this.paymentUrl);
if (this.merchantData)
bw.writeFieldString(7, this.merchantData);
return bw.render();
};
/*
* Expose
*/
module.exports = PaymentDetails;

View File

@ -1,350 +0,0 @@
/*!
* paymentrequest.js - bip70 paymentrequest for bcoin
* Copyright (c) 2016-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('assert');
const digest = require('bcrypto/lib/digest');
const PEM = require('bcrypto/lib/utils/pem');
const x509 = require('./x509');
const ProtoReader = require('../utils/protoreader');
const ProtoWriter = require('../utils/protowriter');
const PaymentDetails = require('./paymentdetails');
/**
* Represents a BIP70 payment request.
* @alias module:bip70.PaymentRequest
* @constructor
* @param {Object?} options
* @property {Number} version
* @property {String|null} pkiType
* @property {Buffer|null} pkiData
* @property {PaymentDetails} paymentDetails
* @property {Buffer|null} signature
*/
function PaymentRequest(options) {
if (!(this instanceof PaymentRequest))
return new PaymentRequest(options);
this.version = -1;
this.pkiType = null;
this.pkiData = null;
this.paymentDetails = new PaymentDetails();
this.signature = null;
if (options)
this.fromOptions(options);
}
/**
* Inject properties from options.
* @private
* @param {Object} options
* @returns {PaymentRequest}
*/
PaymentRequest.prototype.fromOptions = function fromOptions(options) {
if (options.version != null) {
assert((options.version | 0) === options.version);
this.version = options.version;
}
if (options.pkiType != null) {
assert(typeof options.pkiType === 'string');
this.pkiType = options.pkiType;
}
if (options.pkiData) {
assert(Buffer.isBuffer(options.pkiData));
this.pkiData = options.pkiData;
}
if (options.paymentDetails)
this.paymentDetails.fromOptions(options.paymentDetails);
if (options.signature) {
assert(Buffer.isBuffer(options.signature));
this.signature = options.signature;
}
if (options.chain)
this.setChain(options.chain);
return this;
};
/**
* Instantiate payment request from options.
* @param {Object} options
* @returns {PaymentRequest}
*/
PaymentRequest.fromOptions = function fromOptions(options) {
return new PaymentRequest().fromOptions(options);
};
/**
* Inject properties from serialized data.
* @private
* @param {Buffer} data
* @returns {PaymentRequest}
*/
PaymentRequest.prototype.fromRaw = function fromRaw(data) {
const br = new ProtoReader(data);
this.version = br.readFieldU32(1, true);
this.pkiType = br.readFieldString(2, true);
this.pkiData = br.readFieldBytes(3, true);
this.paymentDetails.fromRaw(br.readFieldBytes(4));
this.signature = br.readFieldBytes(5, true);
return this;
};
/**
* Instantiate payment request from serialized data.
* @param {Buffer} data
* @returns {PaymentRequest}
*/
PaymentRequest.fromRaw = function fromRaw(data, enc) {
if (typeof data === 'string')
data = Buffer.from(data, enc);
return new PaymentRequest().fromRaw(data);
};
/**
* Serialize the payment request (protobuf).
* @returns {Buffer}
*/
PaymentRequest.prototype.toRaw = function toRaw() {
const bw = new ProtoWriter();
if (this.version !== -1)
bw.writeFieldU32(1, this.version);
if (this.pkiType != null)
bw.writeFieldString(2, this.pkiType);
if (this.pkiData)
bw.writeFieldBytes(3, this.pkiData);
bw.writeFieldBytes(4, this.paymentDetails.toRaw());
if (this.signature)
bw.writeFieldBytes(5, this.signature);
return bw.render();
};
/**
* Get payment request signature algorithm.
* @returns {Object|null}
*/
PaymentRequest.prototype.getAlgorithm = function getAlgorithm() {
if (!this.pkiType)
throw new Error('No PKI type available.');
const parts = this.pkiType.split('+');
if (parts.length !== 2)
throw new Error('Could not parse PKI algorithm.');
if (parts[0] !== 'x509')
throw new Error(`Unknown PKI type: ${parts[0]}.`);
if (parts[1] !== 'sha1' && parts[1] !== 'sha256')
throw new Error(`Unknown hash algorithm: ${parts[1]}.`);
return new Algorithm(parts[0], parts[1]);
};
/**
* Serialize payment request for sighash.
* @returns {Buffer}
*/
PaymentRequest.prototype.signatureData = function signatureData() {
const signature = this.signature;
this.signature = Buffer.alloc(0);
const data = this.toRaw();
this.signature = signature;
return data;
};
/**
* Get signature hash.
* @returns {Hash}
*/
PaymentRequest.prototype.signatureHash = function signatureHash() {
const alg = this.getAlgorithm();
return digest.hash(alg.hash, this.signatureData());
};
/**
* Set x509 certificate chain.
* @param {Buffer[]} chain
*/
PaymentRequest.prototype.setChain = function setChain(chain) {
const bw = new ProtoWriter();
assert(Array.isArray(chain), 'Chain must be an array.');
for (let cert of chain) {
if (typeof cert === 'string') {
const pem = PEM.decode(cert);
assert(pem.type === 'certificate', 'Bad certificate PEM.');
cert = pem.data;
}
assert(Buffer.isBuffer(cert), 'Certificates must be PEM or DER.');
bw.writeFieldBytes(1, cert);
}
this.pkiData = bw.render();
};
/**
* Get x509 certificate chain.
* @returns {Buffer[]}
*/
PaymentRequest.prototype.getChain = function getChain() {
const chain = [];
if (!this.pkiData)
return chain;
const br = new ProtoReader(this.pkiData);
while (br.nextTag() === 1)
chain.push(br.readFieldBytes(1));
return chain;
};
/**
* Sign payment request (chain must be set).
* @param {Buffer} key
* @param {Buffer[]?} certs
*/
PaymentRequest.prototype.sign = function sign(key, certs) {
if (certs)
this.setChain(certs);
if (!this.pkiType)
this.pkiType = 'x509+sha256';
const alg = this.getAlgorithm();
const msg = this.signatureData();
const chain = this.getChain();
this.signature = x509.signSubject(alg.hash, msg, key, chain);
};
/**
* Verify payment request signature.
* @returns {Boolean}
*/
PaymentRequest.prototype.verify = function verify() {
if (!this.pkiType || this.pkiType === 'none')
return false;
if (!this.signature)
return false;
let alg;
try {
alg = this.getAlgorithm();
} catch (e) {
return false;
}
const msg = this.signatureData();
const sig = this.signature;
const chain = this.getChain();
try {
return x509.verifySubject(alg.hash, msg, sig, chain);
} catch (e) {
return false;
}
};
/**
* Verify x509 certificate chain.
* @returns {Boolean}
*/
PaymentRequest.prototype.verifyChain = function verifyChain() {
if (!this.pkiType || this.pkiType === 'none')
return false;
try {
return x509.verifyChain(this.getChain());
} catch (e) {
return false;
}
};
/**
* Get root certificate authority.
* @returns {Object|null}
*/
PaymentRequest.prototype.getCA = function getCA() {
if (!this.pkiType || this.pkiType === 'none')
throw new Error('No CA found (pkiType).');
const chain = this.getChain();
if (chain.length === 0)
throw new Error('No CA found (chain).');
const root = x509.parse(chain[chain.length - 1]);
return new CA(root);
};
/**
* Algorithm
* @constructor
* @ignore
*/
function Algorithm(key, hash) {
this.key = key;
this.hash = hash;
}
/**
* CA
* @constructor
* @ignore
*/
function CA(root) {
this.name = x509.getCAName(root);
this.trusted = x509.isTrusted(root);
this.cert = root;
}
/*
* Expose
*/
module.exports = PaymentRequest;

View File

@ -1,56 +0,0 @@
/*!
* pk.js - public key algorithms for bcoin
* Copyright (c) 2016-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module bip70/pk
*/
const digest = require('bcrypto/lib/digest');
const rsa = require('bcrypto/lib/rsa');
const ecdsa = require('bcrypto/lib/ecdsa');
/**
* Verify signature with public key.
* @param {String} hash - Hash algorithm.
* @param {Buffer} msg
* @param {Buffer} sig
* @param {Object} key
* @returns {Boolean}
*/
exports.verify = function verify(hash, msg, sig, key) {
hash = digest.get(hash);
switch (key.alg) {
case 'rsa':
return rsa.verify(hash, msg, sig, key.data);
case 'ecdsa':
return ecdsa.verify(key.curve, hash, msg, sig, key.data);
default:
throw new Error('Unsupported algorithm.');
}
};
/**
* Sign message with private key.
* @param {String} hash - Hash algorithm.
* @param {Buffer} msg
* @param {Object} key
* @returns {Buffer}
*/
exports.sign = function sign(hash, msg, key) {
hash = digest.get(hash);
switch (key.alg) {
case 'rsa':
return rsa.sign(hash, msg, key.data);
case 'ecdsa':
return ecdsa.sign(key.curve, hash, msg, key.data);
default:
throw new Error('Unsupported algorithm.');
}
};

View File

@ -1,472 +0,0 @@
/*!
* x509.js - x509 handling for bcoin
* Copyright (c) 2016-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('assert');
const ASN1 = require('bcrypto/lib/utils/asn1');
const PEM = require('bcrypto/lib/utils/pem');
const util = require('../utils/util');
const digest = require('bcrypto/lib/digest');
const pk = require('./pk');
const certs = require('./certs');
/**
* @exports bip70/x509
*/
const x509 = exports;
/**
* Map of trusted root certs.
* @type {Set}
*/
x509.trusted = new Set();
/**
* Whether to allow untrusted root
* certs during verification.
* @type {Boolean}
*/
x509.allowUntrusted = false;
/**
* OID to algorithm map for PKI.
* @const {Object}
* @see https://www.ietf.org/rfc/rfc2459.txt
* @see https://tools.ietf.org/html/rfc3279
* @see http://oid-info.com/get/1.2.840.10040.4
* @see http://oid-info.com/get/1.2.840.113549.1.1
* @see http://oid-info.com/get/1.2.840.10045.4.3
*/
x509.oid = {
'1.2.840.10040.4.1' : { key: 'dsa', hash: null },
'1.2.840.10040.4.2' : { key: 'dsa', hash: null },
'1.2.840.10040.4.3' : { key: 'dsa', hash: 'sha1' },
'1.2.840.113549.1.1.1' : { key: 'rsa', hash: null },
'1.2.840.113549.1.1.2' : { key: 'rsa', hash: 'md2' },
'1.2.840.113549.1.1.3' : { key: 'rsa', hash: 'md4' },
'1.2.840.113549.1.1.4' : { key: 'rsa', hash: 'md5' },
'1.2.840.113549.1.1.5' : { key: 'rsa', hash: 'sha1' },
'1.2.840.113549.1.1.11': { key: 'rsa', hash: 'sha256' },
'1.2.840.113549.1.1.12': { key: 'rsa', hash: 'sha384' },
'1.2.840.113549.1.1.13': { key: 'rsa', hash: 'sha512' },
'1.2.840.113549.1.1.14': { key: 'rsa', hash: 'sha224' },
'1.2.840.10045.2.1' : { key: 'ecdsa', hash: null },
'1.2.840.10045.4.1' : { key: 'ecdsa', hash: 'sha1' },
'1.2.840.10045.4.3.1' : { key: 'ecdsa', hash: 'sha224' },
'1.2.840.10045.4.3.2' : { key: 'ecdsa', hash: 'sha256' },
'1.2.840.10045.4.3.3' : { key: 'ecdsa', hash: 'sha384' },
'1.2.840.10045.4.3.4' : { key: 'ecdsa', hash: 'sha512' }
};
/**
* OID to curve name map for ECDSA.
* @type {Object}
*/
x509.curves = {
'1.3.132.0.33': 'p224',
'1.2.840.10045.3.1.7': 'p256',
'1.3.132.0.34': 'p384',
'1.3.132.0.35': 'p521'
};
/**
* Retrieve cert value by OID.
* @param {Object} cert
* @param {String} oid
* @returns {String}
*/
x509.getSubjectOID = function getSubjectOID(cert, oid) {
const subject = cert.tbs.subject;
for (const entry of subject) {
if (entry.type === oid)
return entry.value;
}
return null;
};
/**
* Try to retrieve CA name by checking
* for a few different OIDs.
* @param {Object} cert
* @returns {String}
*/
x509.getCAName = function getCAName(cert) {
// This seems to work the best in practice
// for getting a human-readable and
// descriptive name for the CA.
// See:
// http://oid-info.com/get/2.5.4
// Precedence:
// (3) commonName
// (11) organizationUnitName
// (10) organizationName
return x509.getSubjectOID(cert, '2.5.4.3')
|| x509.getSubjectOID(cert, '2.5.4.11')
|| x509.getSubjectOID(cert, '2.5.4.10')
|| 'Unknown';
};
/**
* Test whether a cert is trusted by hashing
* and looking it up in the trusted map.
* @param {Object} cert
* @returns {Buffer}
*/
x509.isTrusted = function isTrusted(cert) {
const fingerprint = digest.sha256(cert.raw);
const hash = fingerprint.toString('hex');
return x509.trusted.has(hash);
};
/**
* Add root certificates to the trusted map.
* @param {Buffer[]} certs
*/
x509.setTrust = function setTrust(certs) {
assert(Array.isArray(certs), 'Certs must be an array.');
for (let cert of certs) {
if (typeof cert === 'string') {
const pem = PEM.decode(cert);
assert(pem.type === 'certificate', 'Must add certificates to trust.');
cert = pem.data;
}
assert(Buffer.isBuffer(cert), 'Certificates must be PEM or DER.');
cert = x509.parse(cert);
const hash = digest.sha256(cert.raw);
const fingerprint = hash.toString('hex');
x509.trusted.add(fingerprint);
}
};
/**
* Add root certificate fingerprints to the trusted map.
* @param {Hash[]} hashes
*/
x509.setFingerprints = function setFingerprints(hashes) {
assert(Array.isArray(hashes), 'Certs must be an array.');
for (let hash of hashes) {
if (typeof hash === 'string')
hash = Buffer.from(hash, 'hex');
assert(Buffer.isBuffer(hash), 'Fingerprint must be a buffer.');
assert(hash.length === 32, 'Fingerprint must be a sha256 hash.');
hash = hash.toString('hex');
x509.trusted.add(hash);
}
};
/**
* Retrieve key algorithm from cert.
* @param {Object} cert
* @returns {Object}
*/
x509.getKeyAlgorithm = function getKeyAlgorithm(cert) {
const oid = cert.tbs.pubkey.alg.alg;
const alg = x509.oid[oid];
if (!alg)
throw new Error(`Unknown key algorithm: ${oid}.`);
return alg;
};
/**
* Retrieve signature algorithm from cert.
* @param {Object} cert
* @returns {Object}
*/
x509.getSigAlgorithm = function getSigAlgorithm(cert) {
const oid = cert.sigAlg.alg;
const alg = x509.oid[oid];
if (!alg || !alg.hash)
throw new Error(`Unknown signature algorithm: ${oid}.`);
return alg;
};
/**
* Lookup curve based on key parameters.
* @param {Buffer} params
* @returns {Object}
*/
x509.getCurve = function getCurve(params) {
let oid;
try {
oid = ASN1.parseOID(params);
} catch (e) {
throw new Error('Could not parse curve OID.');
}
const curve = x509.curves[oid];
if (!curve)
throw new Error(`Unknown ECDSA curve: ${oid}.`);
return curve;
};
/**
* Parse a DER formatted cert.
* @param {Buffer} der
* @returns {Object|null}
*/
x509.parse = function parse(der) {
try {
return ASN1.parseCert(der);
} catch (e) {
throw new Error('Could not parse DER certificate.');
}
};
/**
* Get cert public key.
* @param {Object} cert
* @returns {Object|null}
*/
x509.getPublicKey = function getPublicKey(cert) {
const alg = x509.getKeyAlgorithm(cert);
const key = cert.tbs.pubkey.pubkey;
const params = cert.tbs.pubkey.alg.params;
let curve = null;
if (alg.key === 'ecdsa') {
if (!params)
throw new Error('No curve selected for ECDSA (cert).');
curve = x509.getCurve(params);
}
return {
alg: alg.key,
data: key,
params: params,
curve: curve
};
};
/**
* Verify cert expiration time.
* @param {Object} cert
* @returns {Boolean}
*/
x509.verifyTime = function verifyTime(cert) {
const time = cert.tbs.validity;
const now = util.now();
return now > time.notBefore && now < time.notAfter;
};
/**
* Get signature key info from cert chain.
* @param {Buffer} key
* @param {Buffer[]} chain
* @returns {Object}
*/
x509.getSigningKey = function getSigningKey(key, chain) {
assert(chain.length !== 0, 'No chain available.');
if (typeof key === 'string') {
let curve = null;
key = PEM.decode(key);
if (key.alg === 'ecdsa') {
if (!key.params)
throw new Error('No curve selected for ECDSA (key).');
curve = x509.getCurve(key.params);
}
key = {
alg: key.alg,
data: key.data,
params: key.params,
curve: curve
};
} else {
const cert = x509.parse(chain[0]);
const pub = x509.getPublicKey(cert);
key = {
alg: pub.alg,
data: key,
params: pub.params,
curve: pub.curve
};
}
return key;
};
/**
* Sign a hash with the chain signing key.
* @param {String} hash
* @param {Buffer} msg
* @param {Buffer} key
* @param {Buffer[]} chain
* @returns {Buffer}
*/
x509.signSubject = function signSubject(hash, msg, key, chain) {
const priv = x509.getSigningKey(key, chain);
return pk.sign(hash, msg, priv);
};
/**
* Get chain verification key.
* @param {Buffer[]} chain
* @returns {Object|null}
*/
x509.getVerifyKey = function getVerifyKey(chain) {
if (chain.length === 0)
throw new Error('No verify key available (cert chain).');
const cert = x509.parse(chain[0]);
return x509.getPublicKey(cert);
};
/**
* Verify a sighash against chain verification key.
* @param {String} hash
* @param {Buffer} msg
* @param {Buffer} sig
* @param {Buffer[]} chain
* @returns {Boolean}
*/
x509.verifySubject = function verifySubject(hash, msg, sig, chain) {
const key = x509.getVerifyKey(chain);
return pk.verify(hash, msg, sig, key);
};
/**
* Parse certificate chain.
* @param {Buffer[]} chain
* @returns {Object[]}
*/
x509.parseChain = function parseChain(chain) {
const certs = [];
for (const item of chain) {
const cert = x509.parse(item);
certs.push(cert);
}
return certs;
};
/**
* Verify all expiration times in a certificate chain.
* @param {Object[]} chain
* @returns {Boolean}
*/
x509.verifyTimes = function verifyTimes(chain) {
for (const cert of chain) {
if (!x509.verifyTime(cert))
return false;
}
return true;
};
/**
* Verify that at least one parent
* cert in the chain is trusted.
* @param {Object[]} chain
* @returns {Boolean}
*/
x509.verifyTrust = function verifyTrust(chain) {
// If trust hasn't been
// setup, just return.
if (x509.allowUntrusted)
return true;
// Make sure we trust one
// of the certs in the chain.
for (const cert of chain) {
// If any certificate in the chain
// is trusted, assume we also trust
// the parent.
if (x509.isTrusted(cert))
return true;
}
// No trusted certs present.
return false;
};
/**
* Verify certificate chain.
* @param {Object[]} certs
*/
x509.verifyChain = function verifyChain(certs) {
const chain = x509.parseChain(certs);
// Parse certificates and
// check validity time.
if (!x509.verifyTimes(chain))
throw new Error('Invalid certificate times.');
// Verify signatures.
for (let i = 1; i < chain.length; i++) {
const child = chain[i - 1];
const parent = chain[i];
const alg = x509.getSigAlgorithm(child);
const key = x509.getPublicKey(parent);
const msg = child.tbs.raw;
const sig = child.sig;
if (!pk.verify(alg.hash, msg, sig, key))
throw new Error(`${alg.key} verification failed for chain.`);
}
// Make sure we trust one
// of the certs in the chain.
if (!x509.verifyTrust(chain))
throw new Error('Certificate chain is untrusted.');
return true;
};
/*
* Load trusted certs.
*/
x509.setFingerprints(certs);

View File

@ -23,6 +23,7 @@ const CoinView = require('../coins/coinview');
const Script = require('../script/script');
const {VerifyError} = require('../protocol/errors');
const co = require('../utils/co');
const encoding = require('../utils/encoding');
const thresholdStates = common.thresholdStates;
/**
@ -1409,7 +1410,7 @@ Chain.prototype._add = async function _add(block, flags, id) {
*/
Chain.prototype.connect = async function connect(prev, block, flags) {
const start = util.hrtime();
const start = util.bench();
// Sanity check.
assert(block.prevBlock === prev.hash);
@ -1537,7 +1538,7 @@ Chain.prototype.logStatus = function logStatus(start, block, entry) {
// Report memory for debugging.
this.logger.memory();
const elapsed = util.hrtime(start);
const elapsed = util.bench(start);
this.logger.info(
'Block %s (%d) added to chain (size=%d txs=%d time=%d).',
@ -1573,7 +1574,7 @@ Chain.prototype.verifyCheckpoint = function verifyCheckpoint(prev, hash) {
if (hash === checkpoint) {
this.logger.debug('Hit checkpoint block %s (%d).',
util.revHex(hash), height);
encoding.revHex(hash), height);
this.emit('checkpoint', hash, height);
return true;
}
@ -1585,8 +1586,8 @@ Chain.prototype.verifyCheckpoint = function verifyCheckpoint(prev, hash) {
this.logger.warning(
'Checkpoint mismatch at height %d: expected=%s received=%s',
height,
util.revHex(checkpoint),
util.revHex(hash)
encoding.revHex(checkpoint),
encoding.revHex(hash)
);
this.purgeOrphans();

View File

@ -9,7 +9,6 @@
const assert = require('assert');
const BDB = require('bdb');
const util = require('../utils/util');
const BufferReader = require('../utils/reader');
const StaticWriter = require('../utils/staticwriter');
const Amount = require('../btc/amount');
@ -25,8 +24,8 @@ const Address = require('../primitives/address');
const ChainEntry = require('./chainentry');
const TXMeta = require('../primitives/txmeta');
const CoinEntry = require('../coins/coinentry');
const U8 = encoding.U8;
const U32 = encoding.U32;
const u8 = encoding.u8;
const u32 = encoding.u32;
/**
* The database backend for the {@link Chain} object.
@ -1291,7 +1290,7 @@ ChainDB.prototype.scan = async function scan(start, filter, iter) {
if (typeof start === 'number')
this.logger.info('Scanning from height %d.', start);
else
this.logger.info('Scanning from block %s.', util.revHex(start));
this.logger.info('Scanning from block %s.', encoding.revHex(start));
let entry = await this.getEntry(start);
@ -1398,7 +1397,7 @@ ChainDB.prototype._save = async function _save(entry, block, view) {
const hash = block.hash();
// Hash->height index.
this.put(layout.h(hash), U32(entry.height));
this.put(layout.h(hash), u32(entry.height));
// Entry data.
this.put(layout.e(hash), entry.toRaw());
@ -2135,7 +2134,7 @@ function ChainState() {
}
ChainState.prototype.rhash = function rhash() {
return util.revHex(this.tip);
return encoding.revHex(this.tip);
};
ChainState.prototype.clone = function clone() {
@ -2272,7 +2271,7 @@ function CacheUpdate(bit, hash, state) {
}
CacheUpdate.prototype.toRaw = function toRaw() {
return U8(this.state);
return u8(this.state);
};
/*

View File

@ -10,7 +10,6 @@
const assert = require('assert');
const BN = require('bcrypto/lib/bn');
const consensus = require('../protocol/consensus');
const util = require('../utils/util');
const digest = require('bcrypto/lib/digest');
const encoding = require('../utils/encoding');
const BufferReader = require('../utils/reader');
@ -180,7 +179,7 @@ ChainEntry.prototype.hasBit = function hasBit(bit) {
*/
ChainEntry.prototype.rhash = function rhash() {
return util.revHex(this.hash);
return encoding.revHex(this.hash);
};
/**
@ -277,10 +276,10 @@ ChainEntry.fromRaw = function fromRaw(data) {
ChainEntry.prototype.toJSON = function toJSON() {
return {
hash: util.revHex(this.hash),
hash: encoding.revHex(this.hash),
version: this.version,
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
prevBlock: encoding.revHex(this.prevBlock),
merkleRoot: encoding.revHex(this.merkleRoot),
time: this.time,
bits: this.bits,
nonce: this.nonce,
@ -306,10 +305,10 @@ ChainEntry.prototype.fromJSON = function fromJSON(json) {
assert((json.nonce >>> 0) === json.nonce);
assert(typeof json.chainwork === 'string');
this.hash = util.revHex(json.hash);
this.hash = encoding.revHex(json.hash);
this.version = json.version;
this.prevBlock = util.revHex(json.prevBlock);
this.merkleRoot = util.revHex(json.merkleRoot);
this.prevBlock = encoding.revHex(json.prevBlock);
this.merkleRoot = encoding.revHex(json.merkleRoot);
this.time = json.time;
this.bits = json.bits;
this.nonce = json.nonce;

1
lib/hd/udata.json Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -9,7 +9,6 @@
'use strict';
const assert = require('assert');
const util = require('../utils/util');
const binary = require('../utils/binary');
const consensus = require('../protocol/consensus');
const policy = require('../protocol/policy');
@ -492,7 +491,7 @@ PolicyEstimator.prototype.removeTX = function removeTX(hash) {
const item = this.map.get(hash);
if (!item) {
this.logger.spam('Mempool tx %s not found.', util.revHex(hash));
this.logger.spam('Mempool tx %s not found.', encoding.revHex(hash));
return;
}

View File

@ -419,7 +419,7 @@ Mempool.prototype.limitSize = function limitSize(added) {
const expiryTime = this.options.expiryTime;
const now = util.now();
let start = util.hrtime();
let start = util.bench();
const queue = new Heap(cmpRate);
for (const entry of this.map.values()) {
@ -443,9 +443,9 @@ Mempool.prototype.limitSize = function limitSize(added) {
this.logger.debug(
'(bench) Heap mempool traversal: %d.',
util.hrtime(start));
util.bench(start));
start = util.hrtime();
start = util.bench();
this.logger.debug(
'(bench) Heap mempool queue size: %d.',
@ -469,7 +469,7 @@ Mempool.prototype.limitSize = function limitSize(added) {
this.logger.debug(
'(bench) Heap mempool map removal: %d.',
util.hrtime(start));
util.bench(start));
return !this.hasEntry(added);
};
@ -1677,7 +1677,7 @@ Mempool.prototype.limitOrphans = function limitOrphans() {
assert(hash);
this.logger.debug('Removing orphan %s from mempool.', util.revHex(hash));
this.logger.debug('Removing orphan %s from mempool.', encoding.revHex(hash));
this.removeOrphan(hash);
@ -2491,7 +2491,7 @@ MempoolCache.prototype.flush = async function flush() {
MempoolCache.prototype.init = async function init(hash) {
const batch = this.db.batch();
batch.put(layout.V, encoding.U32(MempoolCache.VERSION));
batch.put(layout.V, encoding.u32(MempoolCache.VERSION));
batch.put(layout.R, Buffer.from(hash, 'hex'));
await batch.write();
};
@ -2506,7 +2506,7 @@ MempoolCache.prototype.verify = async function verify() {
this.logger.info(
'Mempool cache is empty. Writing tip %s.',
util.revHex(tip));
encoding.revHex(tip));
await this.init(tip);
}
@ -2526,7 +2526,7 @@ MempoolCache.prototype.verify = async function verify() {
if (tip !== this.chain.tip.hash) {
this.logger.warning(
'Mempool tip not consistent with chain tip (%s != %s)!',
util.revHex(tip),
encoding.revHex(tip),
this.chain.tip.rhash());
this.logger.warning('Invalidating mempool cache.');
await this.wipe();
@ -2543,7 +2543,7 @@ MempoolCache.prototype.wipe = async function wipe() {
for (const key of keys)
batch.del(key);
batch.put(layout.V, encoding.U32(MempoolCache.VERSION));
batch.put(layout.V, encoding.u32(MempoolCache.VERSION));
batch.put(layout.R, Buffer.from(this.chain.tip.hash, 'hex'));
batch.del(layout.F);

View File

@ -13,6 +13,7 @@ const co = require('../utils/co');
const AsyncObject = require('../utils/asyncobject');
const mine = require('./mine');
const Lock = require('../utils/lock');
const encoding = require('../utils/encoding');
/**
* CPU miner.
@ -411,7 +412,7 @@ CPUMiner.prototype.mineAsync = async function mineAsync(job) {
CPUMiner.prototype.sendStatus = function sendStatus(job, nonce) {
const attempt = job.attempt;
const tip = util.revHex(attempt.prevBlock);
const tip = encoding.revHex(attempt.prevBlock);
const hashes = job.getHashes(nonce);
const hashrate = job.getRate(nonce);

View File

@ -8,7 +8,6 @@
'use strict';
const assert = require('assert');
const util = require('../utils/util');
const hash256 = require('bcrypto/lib/hash256');
const merkle = require('bcrypto/lib/merkle');
const StaticWriter = require('../utils/staticwriter');
@ -664,7 +663,7 @@ function BlockProof(hash, root, nonce1, nonce2, time, nonce) {
}
BlockProof.prototype.rhash = function rhash() {
return util.revHex(this.hash.toString('hex'));
return encoding.revHex(this.hash.toString('hex'));
};
BlockProof.prototype.verify = function verify(target) {

View File

@ -1574,7 +1574,7 @@ RejectPacket.fromOptions = function fromOptions(options) {
*/
RejectPacket.prototype.rhash = function rhash() {
return this.hash ? util.revHex(this.hash) : null;
return this.hash ? encoding.revHex(this.hash) : null;
};
/**
@ -1758,7 +1758,7 @@ RejectPacket.fromError = function fromError(err, obj) {
RejectPacket.prototype.inspect = function inspect() {
const code = RejectPacket.codesByVal[this.code] || this.code;
const hash = this.hash ? util.revHex(this.hash) : null;
const hash = this.hash ? encoding.revHex(this.hash) : null;
return '<Reject:'
+ ` msg=${this.message}`
+ ` code=${code}`

View File

@ -10,7 +10,6 @@
const assert = require('assert');
const EventEmitter = require('events');
const {format} = require('util');
const util = require('../utils/util');
const co = require('../utils/co');
const Parser = require('./parser');
const Framer = require('./framer');
@ -1995,11 +1994,11 @@ Peer.prototype.sendGetHeaders = function sendGetHeaders(locator, stop) {
let hash = null;
if (packet.locator.length > 0)
hash = util.revHex(packet.locator[0]);
hash = encoding.revHex(packet.locator[0]);
let end = null;
if (stop)
end = util.revHex(stop);
end = encoding.revHex(stop);
this.logger.debug(
'Requesting headers packet from peer with getheaders (%s).',
@ -2023,11 +2022,11 @@ Peer.prototype.sendGetBlocks = function sendGetBlocks(locator, stop) {
let hash = null;
if (packet.locator.length > 0)
hash = util.revHex(packet.locator[0]);
hash = encoding.revHex(packet.locator[0]);
let end = null;
if (stop)
end = util.revHex(stop);
end = encoding.revHex(stop);
this.logger.debug(
'Requesting inv packet from peer with getblocks (%s).',
@ -2075,7 +2074,7 @@ Peer.prototype.sendReject = function sendReject(code, reason, msg, hash) {
if (msg) {
this.logger.debug('Rejecting %s %s (%s): code=%s reason=%s.',
msg, util.revHex(hash), this.hostname(), code, reason);
msg, encoding.revHex(hash), this.hostname(), code, reason);
} else {
this.logger.debug('Rejecting packet from %s: code=%s reason=%s.',
this.hostname(), code, reason);

View File

@ -33,6 +33,7 @@ const HostList = require('./hostlist');
const UPNP = require('./upnp');
const InvItem = require('../primitives/invitem');
const packets = require('./packets');
const encoding = require('../utils/encoding');
const services = common.services;
const invTypes = InvItem.types;
const packetTypes = packets.types;
@ -248,7 +249,7 @@ Pool.prototype.resetChain = function resetChain() {
this.headerChain.push(new HeaderEntry(tip.hash, tip.height));
this.logger.info(
'Initialized header chain to height %d (checkpoint=%s).',
tip.height, util.revHex(this.headerTip.hash));
tip.height, encoding.revHex(this.headerTip.hash));
}
};
@ -2304,8 +2305,8 @@ Pool.prototype.resolveChain = async function resolveChain(peer, hash) {
if (hash !== node.hash) {
this.logger.warning(
'Header hash mismatch %s != %s (%s).',
util.revHex(hash),
util.revHex(node.hash),
encoding.revHex(hash),
encoding.revHex(node.hash),
peer.hostname());
peer.destroy();
@ -2317,7 +2318,7 @@ Pool.prototype.resolveChain = async function resolveChain(peer, hash) {
if (node.height === this.headerTip.height) {
this.logger.info(
'Received checkpoint %s (%d).',
util.revHex(node.hash), node.height);
encoding.revHex(node.hash), node.height);
this.headerTip = this.getNextTip(node.height);
@ -2374,7 +2375,7 @@ Pool.prototype.handleBadOrphan = function handleBadOrphan(msg, err, id) {
if (!peer) {
this.logger.warning(
'Could not find offending peer for orphan: %s (%d).',
util.revHex(err.hash), id);
encoding.revHex(err.hash), id);
return;
}
@ -3462,7 +3463,7 @@ Pool.prototype.hasTX = function hasTX(hash) {
// If we recently rejected this item. Ignore.
if (this.mempool.hasReject(hash)) {
this.logger.spam('Saw known reject of %s.', util.revHex(hash));
this.logger.spam('Saw known reject of %s.', encoding.revHex(hash));
return true;
}
}
@ -4330,7 +4331,7 @@ BroadcastItem.prototype.handleReject = function handleReject(peer) {
BroadcastItem.prototype.inspect = function inspect() {
const type = this.type === invTypes.TX ? 'tx' : 'block';
const hash = util.revHex(this.hash);
const hash = encoding.revHex(this.hash);
return `<BroadcastItem: type=${type} hash=${hash}>`;
};

View File

@ -20,6 +20,7 @@ const random = require('bcrypto/lib/random');
const ccmp = require('bcrypto/lib/ccmp');
const Network = require('../protocol/network');
const Validator = require('../utils/validator');
const encoding = require('../utils/encoding');
const pkg = require('../pkg');
class HTTP extends Server {
@ -292,7 +293,7 @@ class HTTP extends Server {
const result = [];
for (const hash of hashes)
result.push(util.revHex(hash));
result.push(encoding.revHex(hash));
res.json(200, result);
});

View File

@ -464,7 +464,7 @@ class RPC extends RPCBase {
offset = 0;
for (const hash in peer.blockMap.keys()) {
const str = util.revHex(hash);
const str = encoding.revHex(hash);
hashes.push(str);
}
@ -490,7 +490,7 @@ class RPC extends RPCBase {
subver: peer.agent,
inbound: !peer.outbound,
startingheight: peer.height,
besthash: peer.bestHash ? util.revHex(peer.bestHash) : null,
besthash: peer.bestHash ? encoding.revHex(peer.bestHash) : null,
bestheight: peer.bestHeight,
banscore: peer.banScore,
inflight: hashes,
@ -694,7 +694,7 @@ class RPC extends RPCBase {
if (!hash)
throw new RPCError(errs.MISC_ERROR, 'Not found.');
return util.revHex(hash);
return encoding.revHex(hash);
}
async getBlockHeader(args, help) {
@ -878,7 +878,7 @@ class RPC extends RPCBase {
const hashes = this.mempool.getSnapshot();
return hashes.map(util.revHex);
return hashes.map(encoding.revHex);
}
async getTXOut(args, help) {
@ -1017,7 +1017,7 @@ class RPC extends RPCBase {
const out = [];
for (const hash of tree.matches)
out.push(util.revHex(hash.toString('hex')));
out.push(encoding.revHex(hash.toString('hex')));
return out;
}
@ -1461,8 +1461,8 @@ class RPC extends RPCBase {
vbavailable: vbavailable,
vbrequired: 0,
height: attempt.height,
previousblockhash: util.revHex(attempt.prevBlock),
target: util.revHex(attempt.target.toString('hex')),
previousblockhash: encoding.revHex(attempt.prevBlock),
target: encoding.revHex(attempt.target.toString('hex')),
bits: hex32(attempt.bits),
noncerange: '00000000ffffffff',
curtime: attempt.time,
@ -2286,7 +2286,7 @@ class RPC extends RPCBase {
if ((lastTX >>> 0) !== lastTX)
throw new RPCError(errs.INVALID_PARAMETER, 'Invalid longpoll ID.');
const hash = util.revHex(watched);
const hash = encoding.revHex(watched);
if (this.chain.tip.hash !== hash)
return;
@ -2699,16 +2699,16 @@ class RPC extends RPCBase {
height: entry.height,
version: entry.version,
versionHex: hex32(entry.version),
merkleroot: util.revHex(entry.merkleRoot),
merkleroot: encoding.revHex(entry.merkleRoot),
time: entry.time,
mediantime: mtp,
bits: entry.bits,
difficulty: toDifficulty(entry.bits),
chainwork: entry.chainwork.toString('hex', 64),
previousblockhash: entry.prevBlock !== encoding.NULL_HASH
? util.revHex(entry.prevBlock)
? encoding.revHex(entry.prevBlock)
: null,
nextblockhash: next ? util.revHex(next) : null
nextblockhash: next ? encoding.revHex(next) : null
};
}
@ -2735,7 +2735,7 @@ class RPC extends RPCBase {
height: entry.height,
version: entry.version,
versionHex: hex32(entry.version),
merkleroot: util.revHex(entry.merkleRoot),
merkleroot: encoding.revHex(entry.merkleRoot),
coinbase: block.txs[0].inputs[0].script.toJSON(),
tx: txs,
time: entry.time,
@ -2744,9 +2744,9 @@ class RPC extends RPCBase {
difficulty: toDifficulty(entry.bits),
chainwork: entry.chainwork.toString('hex', 64),
previousblockhash: entry.prevBlock !== encoding.NULL_HASH
? util.revHex(entry.prevBlock)
? encoding.revHex(entry.prevBlock)
: null,
nextblockhash: next ? util.revHex(next) : null
nextblockhash: next ? encoding.revHex(next) : null
};
}
@ -2765,7 +2765,7 @@ class RPC extends RPCBase {
ancestorcount: this.mempool.countAncestors(entry),
ancestorsize: 0,
ancestorfees: 0,
depends: this.mempool.getDepends(entry.tx).map(util.revHex)
depends: this.mempool.getDepends(entry.tx).map(encoding.revHex)
};
}
}

View File

@ -8,7 +8,6 @@
'use strict';
const assert = require('assert');
const util = require('../utils/util');
const digest = require('bcrypto/lib/digest');
const BufferReader = require('../utils/reader');
const StaticWriter = require('../utils/staticwriter');
@ -93,8 +92,8 @@ AbstractBlock.prototype.parseJSON = function parseJSON(json) {
assert((json.nonce >>> 0) === json.nonce);
this.version = json.version;
this.prevBlock = util.revHex(json.prevBlock);
this.merkleRoot = util.revHex(json.merkleRoot);
this.prevBlock = encoding.revHex(json.prevBlock);
this.merkleRoot = encoding.revHex(json.merkleRoot);
this.time = json.time;
this.bits = json.bits;
this.nonce = json.nonce;
@ -244,7 +243,7 @@ AbstractBlock.prototype.verifyBody = function verifyBody() {
*/
AbstractBlock.prototype.rhash = function rhash() {
return util.revHex(this.hash('hex'));
return encoding.revHex(this.hash('hex'));
};
/**

View File

@ -540,10 +540,10 @@ Block.prototype.format = function format(view, height) {
virtualSize: this.getVirtualSize(),
date: util.date(this.time),
version: this.version.toString(16),
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
prevBlock: encoding.revHex(this.prevBlock),
merkleRoot: encoding.revHex(this.merkleRoot),
commitmentHash: commitmentHash
? util.revHex(commitmentHash)
? encoding.revHex(commitmentHash)
: null,
time: this.time,
bits: this.bits,
@ -583,8 +583,8 @@ Block.prototype.getJSON = function getJSON(network, view, height, depth) {
height: height,
depth: depth,
version: this.version,
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
prevBlock: encoding.revHex(this.prevBlock),
merkleRoot: encoding.revHex(this.merkleRoot),
time: this.time,
bits: this.bits,
nonce: this.nonce,

View File

@ -8,7 +8,6 @@
'use strict';
const assert = require('assert');
const util = require('../utils/util');
const Amount = require('../btc/amount');
const Output = require('./output');
const Script = require('../script/script');
@ -186,7 +185,7 @@ Coin.fromKey = function fromKey(key) {
*/
Coin.prototype.rhash = function rhash() {
return util.revHex(this.hash);
return encoding.revHex(this.hash);
};
/**
@ -211,7 +210,7 @@ Coin.prototype.inspect = function inspect() {
value: Amount.btc(this.value),
script: this.script,
coinbase: this.coinbase,
hash: this.hash ? util.revHex(this.hash) : null,
hash: this.hash ? encoding.revHex(this.hash) : null,
index: this.index,
address: this.getAddress()
};
@ -282,7 +281,7 @@ Coin.prototype.fromJSON = function fromJSON(json) {
assert(typeof json.hash === 'string', 'Hash must be a string.');
assert(json.hash.length === 64, 'Hash must be a string.');
assert((json.index >>> 0) === json.index, 'Index must be a uint32.');
this.hash = util.revHex(json.hash);
this.hash = encoding.revHex(json.hash);
this.index = json.index;
}

View File

@ -11,6 +11,7 @@ const util = require('../utils/util');
const AbstractBlock = require('./abstractblock');
const StaticWriter = require('../utils/staticwriter');
const BufferReader = require('../utils/reader');
const encoding = require('../utils/encoding');
/**
* Represents block headers obtained from the network via `headers`.
@ -198,8 +199,8 @@ Headers.prototype.getJSON = function getJSON(network, view, height) {
hash: this.rhash(),
height: height,
version: this.version,
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
prevBlock: encoding.revHex(this.prevBlock),
merkleRoot: encoding.revHex(this.merkleRoot),
time: this.time,
bits: this.bits,
nonce: this.nonce
@ -251,8 +252,8 @@ Headers.prototype.format = function format(view, height) {
height: height != null ? height : -1,
date: util.date(this.time),
version: this.version.toString(16),
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
prevBlock: encoding.revHex(this.prevBlock),
merkleRoot: encoding.revHex(this.merkleRoot),
time: this.time,
bits: this.bits,
nonce: this.nonce

View File

@ -9,7 +9,7 @@
const BufferReader = require('../utils/reader');
const StaticWriter = require('../utils/staticwriter');
const util = require('../utils/util');
const encoding = require('../utils/encoding');
/**
* Inv Item
@ -191,7 +191,7 @@ InvItem.prototype.hasWitness = function hasWitness() {
*/
InvItem.prototype.rhash = function rhash() {
return util.revHex(this.hash);
return encoding.revHex(this.hash);
};
/*

View File

@ -303,8 +303,8 @@ MerkleBlock.prototype.format = function format(view, height) {
height: height != null ? height : -1,
date: util.date(this.time),
version: this.version.toString(16),
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
prevBlock: encoding.revHex(this.prevBlock),
merkleRoot: encoding.revHex(this.merkleRoot),
time: this.time,
bits: this.bits,
nonce: this.nonce,
@ -445,14 +445,14 @@ MerkleBlock.prototype.getJSON = function getJSON(network, view, height) {
hash: this.rhash(),
height: height,
version: this.version,
prevBlock: util.revHex(this.prevBlock),
merkleRoot: util.revHex(this.merkleRoot),
prevBlock: encoding.revHex(this.prevBlock),
merkleRoot: encoding.revHex(this.merkleRoot),
time: this.time,
bits: this.bits,
nonce: this.nonce,
totalTX: this.totalTX,
hashes: this.hashes.map((hash) => {
return util.revHex(hash.toString('hex'));
return encoding.revHex(hash.toString('hex'));
}),
flags: this.flags.toString('hex')
};
@ -473,7 +473,7 @@ MerkleBlock.prototype.fromJSON = function fromJSON(json) {
this.parseJSON(json);
for (let hash of json.hashes) {
hash = util.revHex(hash);
hash = encoding.revHex(hash);
this.hashes.push(Buffer.from(hash, 'hex'));
}

View File

@ -7,7 +7,6 @@
'use strict';
const assert = require('assert');
const util = require('../utils/util');
const StaticWriter = require('../utils/staticwriter');
const BufferReader = require('../utils/reader');
const encoding = require('../utils/encoding');
@ -119,7 +118,7 @@ Outpoint.prototype.isNull = function isNull() {
*/
Outpoint.prototype.rhash = function rhash() {
return util.revHex(this.hash);
return encoding.revHex(this.hash);
};
/**
@ -246,7 +245,7 @@ Outpoint.prototype.fromJSON = function fromJSON(json) {
assert(json, 'Outpoint data is required.');
assert(typeof json.hash === 'string', 'Hash must be a string.');
assert((json.index >>> 0) === json.index, 'Index must be a uint32.');
this.hash = util.revHex(json.hash);
this.hash = encoding.revHex(json.hash);
this.index = json.index;
return this;
};
@ -261,7 +260,7 @@ Outpoint.prototype.fromJSON = function fromJSON(json) {
Outpoint.prototype.toJSON = function toJSON() {
return {
hash: util.revHex(this.hash),
hash: encoding.revHex(this.hash),
index: this.index
};
};

View File

@ -2012,7 +2012,7 @@ TX.prototype.isWatched = function isWatched(filter) {
*/
TX.prototype.rhash = function rhash() {
return util.revHex(this.hash('hex'));
return encoding.revHex(this.hash('hex'));
};
/**
@ -2021,7 +2021,7 @@ TX.prototype.rhash = function rhash() {
*/
TX.prototype.rwhash = function rwhash() {
return util.revHex(this.witnessHash('hex'));
return encoding.revHex(this.witnessHash('hex'));
};
/**
@ -2089,7 +2089,7 @@ TX.prototype.format = function format(view, entry, index) {
if (entry) {
height = entry.height;
block = util.revHex(entry.hash);
block = encoding.revHex(entry.hash);
time = entry.time;
date = util.date(time);
}
@ -2157,7 +2157,7 @@ TX.prototype.getJSON = function getJSON(network, view, entry, index) {
if (entry) {
height = entry.height;
block = util.revHex(entry.hash);
block = encoding.revHex(entry.hash);
time = entry.time;
date = util.date(time);
}

View File

@ -11,6 +11,7 @@ const util = require('../utils/util');
const TX = require('./tx');
const StaticWriter = require('../utils/staticwriter');
const BufferReader = require('../utils/reader');
const encoding = require('../utils/encoding');
/**
* An extended transaction object.
@ -129,7 +130,7 @@ TXMeta.prototype.format = function format(view) {
const data = this.tx.format(view, null, this.index);
data.mtime = this.mtime;
data.height = this.height;
data.block = this.block ? util.revHex(this.block) : null;
data.block = this.block ? encoding.revHex(this.block) : null;
data.time = this.time;
return data;
};
@ -155,7 +156,7 @@ TXMeta.prototype.getJSON = function getJSON(network, view, chainHeight) {
const json = this.tx.getJSON(network, view, null, this.index);
json.mtime = this.mtime;
json.height = this.height;
json.block = this.block ? util.revHex(this.block) : null;
json.block = this.block ? encoding.revHex(this.block) : null;
json.time = this.time;
json.confirmations = 0;
@ -182,7 +183,7 @@ TXMeta.prototype.fromJSON = function fromJSON(json) {
this.mtime = json.mtime;
this.height = json.height;
this.block = util.revHex(json.block);
this.block = encoding.revHex(json.block);
this.index = json.index;
return this;

View File

@ -11,6 +11,7 @@
* @module utils/encoding
*/
const assert = require('assert');
const {U64, I64} = require('./int64');
const UINT128_MAX = U64.UINT64_MAX.shrn(7);
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
@ -383,24 +384,24 @@ encoding.writeI64BEN = function writeI64BEN(dst, num, off) {
encoding.readVarint = function readVarint(data, off) {
let value, size;
assert(off < data.length, off);
check(off < data.length, off);
switch (data[off]) {
case 0xff:
size = 9;
assert(off + size <= data.length, off);
check(off + size <= data.length, off);
value = encoding.readU64(data, off + 1);
enforce(value > 0xffffffff, off, 'Non-canonical varint');
break;
case 0xfe:
size = 5;
assert(off + size <= data.length, off);
check(off + size <= data.length, off);
value = data.readUInt32LE(off + 1, true);
enforce(value > 0xffff, off, 'Non-canonical varint');
break;
case 0xfd:
size = 3;
assert(off + size <= data.length, off);
check(off + size <= data.length, off);
value = data[off + 1] | (data[off + 2] << 8);
enforce(value >= 0xfd, off, 'Non-canonical varint');
break;
@ -475,11 +476,11 @@ encoding.sizeVarint = function sizeVarint(num) {
*/
encoding.readVarintN = function readVarintN(data, off) {
assert(off < data.length, off);
check(off < data.length, off);
if (data[off] === 0xff) {
const size = 9;
assert(off + size <= data.length, off);
check(off + size <= data.length, off);
const value = encoding.readU64N(data, off + 1);
enforce(value.hi !== 0, off, 'Non-canonical varint');
return new Varint(size, value);
@ -536,7 +537,7 @@ encoding.readVarint2 = function readVarint2(data, off) {
let size = 0;
for (;;) {
assert(off < data.length, off);
check(off < data.length, off);
const ch = data[off++];
size++;
@ -579,7 +580,7 @@ encoding.writeVarint2 = function writeVarint2(dst, num, off) {
len++;
}
assert(off + len + 1 <= dst.length, off);
check(off + len + 1 <= dst.length, off);
do {
dst[off++] = tmp[len];
@ -621,7 +622,7 @@ encoding.readVarint2N = function readVarint2N(data, off) {
let size = 0;
for (;;) {
assert(off < data.length, off);
check(off < data.length, off);
const ch = data[off++];
size++;
@ -709,7 +710,7 @@ encoding.sizeVarint2N = function sizeVarint2N(num) {
* @returns {Buffer}
*/
encoding.U8 = function U8(num) {
encoding.u8 = function u8(num) {
const data = Buffer.allocUnsafe(1);
data[0] = num >>> 0;
return data;
@ -721,24 +722,12 @@ encoding.U8 = function U8(num) {
* @returns {Buffer}
*/
encoding.U32 = function U32(num) {
encoding.u32 = function u32(num) {
const data = Buffer.allocUnsafe(4);
data.writeUInt32LE(num, 0, true);
return data;
};
/**
* Serialize number as a u32be.
* @param {Number} num
* @returns {Buffer}
*/
encoding.U32BE = function U32BE(num) {
const data = Buffer.allocUnsafe(4);
data.writeUInt32BE(num, 0, true);
return data;
};
/**
* Get size of varint-prefixed bytes.
* @param {Buffer} data
@ -774,6 +763,26 @@ encoding.sizeVarString = function sizeVarString(str, enc) {
return encoding.sizeVarint(len) + len;
};
/**
* Reverse a hex-string (used because of
* bitcoind's affinity for uint256le).
* @param {String} str - Hex string.
* @returns {String} Reversed hex string.
*/
encoding.revHex = function revHex(str) {
assert(typeof str === 'string');
assert(str.length > 0);
assert(str.length % 2 === 0);
let out = '';
for (let i = str.length - 2; i >= 0; i -= 2)
out += str[i] + str[i + 1];
return out;
};
/**
* EncodingError
* @constructor
@ -846,9 +855,9 @@ function Varint(size, value) {
this.value = value;
}
function assert(value, offset) {
function check(value, offset) {
if (!value)
throw new encoding.EncodingError(offset, 'Out of bounds read', assert);
throw new encoding.EncodingError(offset, 'Out of bounds read', check);
}
function enforce(value, offset, reason) {

View File

@ -7,8 +7,6 @@
'use strict';
const assert = require('assert');
/**
* @exports utils/util
*/
@ -21,7 +19,7 @@ const util = exports;
* @returns {Array} [seconds, nanoseconds]
*/
util.hrtime = function hrtime(time) {
util.bench = function bench(time) {
if (!process.hrtime) {
const now = Date.now();
@ -84,23 +82,3 @@ util.time = function time(date) {
return new Date(date) / 1000 | 0;
};
/**
* Reverse a hex-string (used because of
* bitcoind's affinity for uint256le).
* @param {String} data - Hex string.
* @returns {String} Reversed hex string.
*/
util.revHex = function revHex(data) {
assert(typeof data === 'string');
assert(data.length > 0);
assert(data.length % 2 === 0);
let out = '';
for (let i = 0; i < data.length; i += 2)
out = data.slice(i, i + 2) + out;
return out;
};

View File

@ -11,14 +11,14 @@ const assert = require('assert');
const {NodeClient} = require('bclient');
const TX = require('../primitives/tx');
const hash256 = require('bcrypto/lib/hash256');
const util = require('../utils/util');
const encoding = require('../utils/encoding');
const parsers = {
'block connect': (entry, txs) => parseBlock(entry, txs),
'block disconnect': entry => [parseEntry(entry)],
'block rescan': (entry, txs) => parseBlock(entry, txs),
'chain reset': entry => [parseEntry(entry)],
'tx': tx => [TX.fromRaw(tx)],
'tx': tx => [TX.fromRaw(tx)]
};
class WalletClient extends NodeClient {
@ -58,7 +58,7 @@ class WalletClient extends NodeClient {
async getEntry(block) {
if (typeof block === 'string')
block = util.revHex(block);
block = encoding.revHex(block);
return parseEntry(await super.getEntry(block));
}
@ -73,7 +73,7 @@ class WalletClient extends NodeClient {
async rescan(start) {
if (typeof start === 'string')
start = util.revHex(start);
start = encoding.revHex(start);
return super.rescan(start);
}

View File

@ -145,7 +145,7 @@ BlockMeta.prototype.fromEntry = function fromEntry(entry) {
*/
BlockMeta.prototype.fromJSON = function fromJSON(json) {
this.hash = util.revHex(json.hash);
this.hash = encoding.revHex(json.hash);
this.height = json.height;
this.time = json.time;
return this;
@ -216,7 +216,7 @@ BlockMeta.prototype.toRaw = function toRaw() {
BlockMeta.prototype.toJSON = function toJSON() {
return {
hash: util.revHex(this.hash),
hash: encoding.revHex(this.hash),
height: this.height,
time: this.time
};

View File

@ -316,7 +316,7 @@ class RPC extends RPCBase {
format('# Wallet Dump created by Bcoin %s', pkg.version),
format('# * Created on %s', time),
format('# * Best block at time of backup was %d (%s).',
tip.height, util.revHex(tip.hash)),
tip.height, encoding.revHex(tip.hash)),
format('# * File: %s', file),
''
];
@ -632,10 +632,10 @@ class RPC extends RPCBase {
return {
amount: Amount.btc(receive ? received : -sent, true),
confirmations: details.confirmations,
blockhash: details.block ? util.revHex(details.block) : null,
blockhash: details.block ? encoding.revHex(details.block) : null,
blockindex: details.index,
blocktime: details.time,
txid: util.revHex(details.hash),
txid: encoding.revHex(details.hash),
walletconflicts: [],
time: details.mtime,
timereceived: details.mtime,
@ -1057,7 +1057,7 @@ class RPC extends RPCBase {
return {
transactions: out,
lastblock: highest && highest.block
? util.revHex(highest.block)
? encoding.revHex(highest.block)
: encoding.NULL_HASH
};
}
@ -1123,10 +1123,10 @@ class RPC extends RPCBase {
label: member.path ? member.path.name : undefined,
vout: index,
confirmations: details.getDepth(),
blockhash: details.block ? util.revHex(details.block) : null,
blockhash: details.block ? encoding.revHex(details.block) : null,
blockindex: details.index,
blocktime: details.time,
txid: util.revHex(details.hash),
txid: encoding.revHex(details.hash),
walletconflicts: [],
time: details.mtime,
timereceived: details.mtime,

View File

@ -2509,9 +2509,9 @@ Details.prototype.toJSON = function toJSON(network, height) {
const rate = this.getRate(fee);
return {
hash: util.revHex(this.hash),
hash: encoding.revHex(this.hash),
height: this.height,
block: this.block ? util.revHex(this.block) : null,
block: this.block ? encoding.revHex(this.block) : null,
time: this.time,
mtime: this.mtime,
date: util.date(this.time),
@ -2702,10 +2702,10 @@ BlockRecord.prototype.toArray = function toArray() {
BlockRecord.prototype.toJSON = function toJSON() {
return {
hash: util.revHex(this.hash),
hash: encoding.revHex(this.hash),
height: this.height,
time: this.time,
hashes: this.toArray().map(util.revHex)
hashes: this.toArray().map(encoding.revHex)
};
};

View File

@ -11,7 +11,6 @@ const assert = require('assert');
const path = require('path');
const BDB = require('bdb');
const AsyncObject = require('../utils/asyncobject');
const util = require('../utils/util');
const Lock = require('../utils/lock');
const MappedLock = require('../utils/mappedlock');
const encoding = require('../utils/encoding');
@ -34,7 +33,7 @@ const ChainState = records.ChainState;
const BlockMeta = records.BlockMeta;
const TXRecord = records.TXRecord;
const MapRecord = records.MapRecord;
const U32 = encoding.U32;
const u32 = encoding.u32;
/**
* WalletDB
@ -723,7 +722,7 @@ WalletDB.prototype.save = function save(b, wallet) {
const id = wallet.id;
b.put(layout.w(wid), wallet.toRaw());
b.put(layout.l(id), U32(wid));
b.put(layout.l(id), u32(wid));
};
/**
@ -953,7 +952,7 @@ WalletDB.prototype.saveAccount = function saveAccount(b, account) {
b.put(layout.a(wid, index), account.toRaw());
// Name->Index lookups
b.put(layout.i(wid, name), U32(index));
b.put(layout.i(wid, name), u32(index));
// Index->Name lookups
b.put(layout.n(wid, index), Buffer.from(name, 'ascii'));
@ -1755,7 +1754,7 @@ WalletDB.prototype._addBlock = async function _addBlock(entry, txs) {
if (total > 0) {
this.logger.info('Connected WalletDB block %s (tx=%d).',
util.revHex(tip.hash), total);
encoding.revHex(tip.hash), total);
}
return total;
@ -1823,7 +1822,7 @@ WalletDB.prototype._removeBlock = async function _removeBlock(entry) {
await this.setTip(prev);
this.logger.warning('Disconnected wallet block %s (tx=%d).',
util.revHex(tip.hash), total);
encoding.revHex(tip.hash), total);
return total;
};

View File

@ -19,7 +19,6 @@ const assert = require('assert');
const BDB = require('bdb');
const encoding = require('../lib/utils/encoding');
const co = require('../lib/utils/co');
const util = require('../lib/utils/util');
const digest = require('bcrypto/lib/digest');
const BN = require('bcrypto/lib/bn');
const StaticWriter = require('../lib/utils/staticwriter');
@ -132,7 +131,8 @@ async function reserializeUndo(hash) {
if (hash !== encoding.NULL_HASH)
tip = await getEntry(hash);
console.log('Reserializing undo coins from tip %s.', util.revHex(tip.hash));
console.log('Reserializing undo coins from tip %s.',
encoding.revHex(tip.hash));
let batch = db.batch();
let pruning = false;
@ -143,7 +143,7 @@ async function reserializeUndo(hash) {
if (shouldPrune) {
if (tip.height < height - 288) {
console.log('Pruning block %s (%d).',
util.revHex(tip.hash), tip.height);
encoding.revHex(tip.hash), tip.height);
batch.del(pair('u', tip.hash));
batch.del(pair('b', tip.hash));
@ -186,7 +186,7 @@ async function reserializeUndo(hash) {
console.log(
'Reserializing coins for block %s (%d).',
util.revHex(tip.hash), tip.height);
encoding.revHex(tip.hash), tip.height);
for (let i = block.txs.length - 1; i >= 1; i--) {
const tx = block.txs[i];
@ -314,7 +314,7 @@ async function reserializeCoins(hash) {
start = false;
}
console.log('Reserializing coins from %s.', util.revHex(hash));
console.log('Reserializing coins from %s.', encoding.revHex(hash));
let batch = db.batch();
let total = 0;
@ -389,7 +389,7 @@ async function reserializeEntries(hash) {
assert(item.key.equals(pair('e', hash)));
}
console.log('Reserializing entries from %s.', util.revHex(hash));
console.log('Reserializing entries from %s.', encoding.revHex(hash));
const tip = await getTipHash();

View File

@ -5,7 +5,6 @@ const BDB = require('bdb');
const encoding = require('../lib/utils/encoding');
const BufferReader = require('../lib/utils/reader');
const digest = require('bcrypto/lib/digest');
const util = require('../lib/utils/util');
const BN = require('bcrypto/lib/bn');
const DUMMY = Buffer.from([0]);
@ -114,7 +113,7 @@ async function indexTips() {
for (let i = 0; i < tips.length; i++) {
const tip = tips[i];
console.log('Indexing chain tip: %s.', util.revHex(tip));
console.log('Indexing chain tip: %s.', encoding.revHex(tip));
batch.put(pair('p', tip), DUMMY);
}
}

View File

@ -1,215 +0,0 @@
/* eslint-env mocha */
/* eslint prefer-arrow-callback: "off" */
'use strict';
const assert = require('./util/assert');
const util = require('../lib/utils/util');
const bip70 = require('../lib/bip70');
const Address = require('../lib/primitives/address');
const x509 = bip70.x509;
const tests = require('./data/bip70.json');
tests.valid = Buffer.from(tests.valid, 'hex');
tests.invalid = Buffer.from(tests.invalid, 'hex');
tests.untrusted = Buffer.from(tests.untrusted, 'hex');
tests.ack = Buffer.from(tests.ack, 'hex');
tests.ca = {
crt: Buffer.from(tests.ca.crt, 'hex'),
priv: Buffer.from(tests.ca.priv, 'hex'),
pub: Buffer.from(tests.ca.pub, 'hex')
};
x509.allowUntrusted = true;
x509.trusted.clear();
x509.verifyTime = function() {
return true;
};
function testRequest(data) {
const req = bip70.PaymentRequest.fromRaw(data);
assert.strictEqual(req.pkiType, 'x509+sha256');
assert(req.pkiData);
assert(req.getChain());
assert(req.paymentDetails);
assert(req.paymentDetails.memo.length !== 0);
assert(req.paymentDetails.paymentUrl.length !== 0);
assert.bufferEqual(req.toRaw(), data);
assert(req.verify());
}
describe('BIP70', function() {
it('should parse and verify a payment request', () => {
testRequest(tests.valid);
testRequest(tests.invalid);
testRequest(tests.untrusted);
});
it('should verify cert chain', () => {
const req1 = bip70.PaymentRequest.fromRaw(tests.valid);
assert.strictEqual(req1.version, 1);
assert.strictEqual(req1.getChain().length, 4);
assert.strictEqual(req1.paymentDetails.paymentUrl,
'https://test.bitpay.com/i/CMWpuFsjgmQ2ZLiyGfcF1W');
assert.strictEqual(req1.paymentDetails.network, 'test');
assert.strictEqual(req1.paymentDetails.time, 1408645830);
assert.strictEqual(req1.paymentDetails.expires, 1408646730);
assert.strictEqual(req1.paymentDetails.outputs.length, 1);
assert(!req1.paymentDetails.merchantData);
assert(req1.paymentDetails.isExpired());
assert(req1.verifyChain());
const req2 = bip70.PaymentRequest.fromRaw(tests.invalid);
assert.strictEqual(req2.version, 1);
assert.strictEqual(req2.getChain().length, 3);
assert.strictEqual(req2.paymentDetails.paymentUrl,
'https://bitpay.com/i/PAQtNxX7KL8BtJBnfXyTaH');
assert.strictEqual(req2.paymentDetails.network, 'main');
assert.strictEqual(req2.paymentDetails.time, 1442409238);
assert.strictEqual(req2.paymentDetails.expires, 1442410138);
assert.strictEqual(req2.paymentDetails.outputs.length, 1);
assert.strictEqual(req2.paymentDetails.merchantData.length, 76);
assert(req2.paymentDetails.getData('json'));
assert(req2.paymentDetails.isExpired());
assert(req2.verifyChain());
req2.paymentDetails.setData({foo:1}, 'json');
assert.strictEqual(req2.paymentDetails.merchantData.length, 9);
assert.deepStrictEqual(req2.paymentDetails.getData('json'), {foo:1});
assert(!req2.verify());
const req3 = bip70.PaymentRequest.fromRaw(tests.untrusted);
assert.strictEqual(req3.version, -1);
assert.strictEqual(req3.getChain().length, 2);
assert.strictEqual(req3.paymentDetails.paymentUrl,
'https://www.coinbase.com/rp/55f9ca703d5d80008c0001f4');
assert.strictEqual(req3.paymentDetails.network, null);
assert.strictEqual(req3.paymentDetails.time, 1442433682);
assert.strictEqual(req3.paymentDetails.expires, 1442434548);
assert.strictEqual(req3.paymentDetails.outputs.length, 1);
assert.strictEqual(req3.paymentDetails.merchantData.length, 32);
assert.strictEqual(req3.paymentDetails.getData('utf8'),
'bb79b6f2310e321bd3b1d929edbeb358');
assert(req3.paymentDetails.isExpired());
assert(req3.verifyChain());
});
it('should fail to verify cert signatures when enforcing trust', () => {
x509.allowUntrusted = false;
const req1 = bip70.PaymentRequest.fromRaw(tests.valid);
assert(!req1.verifyChain());
const req2 = bip70.PaymentRequest.fromRaw(tests.invalid);
assert(!req2.verifyChain());
const req3 = bip70.PaymentRequest.fromRaw(tests.untrusted);
assert(!req3.verifyChain());
});
it('should verify cert signatures once root cert is added', () => {
const req1 = bip70.PaymentRequest.fromRaw(tests.valid);
x509.setTrust([req1.getChain().pop()]);
assert(req1.verifyChain());
const req2 = bip70.PaymentRequest.fromRaw(tests.untrusted);
assert(!req2.verifyChain());
});
it('should still fail to verify cert signatures for invalid', () => {
const req = bip70.PaymentRequest.fromRaw(tests.invalid);
assert(!req.verifyChain());
});
it('should get chain and ca for request', () => {
const req = bip70.PaymentRequest.fromRaw(tests.valid);
assert.strictEqual(req.getChain().length, 4);
assert.strictEqual(req.getCA().name,
'Go Daddy Class 2 Certification Authority');
});
it('should validate untrusted once again', () => {
const req1 = bip70.PaymentRequest.fromRaw(tests.untrusted);
x509.setTrust([req1.getChain().pop()]);
const req2 = bip70.PaymentRequest.fromRaw(tests.untrusted);
assert(req2.verifyChain());
assert.strictEqual(req2.getCA().name,
'DigiCert SHA2 Extended Validation Server CA');
});
it('should parse a payment ack', () => {
const ack = bip70.PaymentACK.fromRaw(tests.ack);
assert.strictEqual(ack.memo.length, 95);
assert.strictEqual(ack.memo, 'Transaction received by BitPay.'
+ ' Invoice will be marked as paid if the transaction is confirmed.');
assert.bufferEqual(ack.toRaw(), tests.ack);
});
it('should create a payment request, sign, and verify', () => {
const req = new bip70.PaymentRequest({
version: 25,
paymentDetails: {
network: 'testnet',
paymentUrl: 'http://bcoin.io/payment',
memo: 'foobar',
time: util.now(),
expires: util.now() + 3600,
outputs: [
{ value: 10000, address: new Address() },
{ value: 50000, address: new Address() }
],
merchantData: { foo: 'bar' }
}
});
assert.strictEqual(req.pkiType, null);
assert(!req.pkiData);
assert.strictEqual(req.getChain().length, 0);
assert(req.paymentDetails);
assert(req.paymentDetails.memo.length !== 0);
assert(req.paymentDetails.paymentUrl.length !== 0);
assert.deepStrictEqual(req.paymentDetails.getData('json'), {foo:'bar'});
assert.strictEqual(req.version, 25);
assert.strictEqual(req.paymentDetails.paymentUrl,
'http://bcoin.io/payment');
assert.strictEqual(req.paymentDetails.network, 'testnet');
assert(req.paymentDetails.time <= util.now());
assert.strictEqual(req.paymentDetails.expires,
req.paymentDetails.time + 3600);
assert.strictEqual(req.paymentDetails.outputs.length, 2);
assert(req.paymentDetails.merchantData);
assert(!req.paymentDetails.isExpired());
assert(!req.pkiData);
req.setChain([tests.ca.crt]);
req.sign(tests.ca.priv);
assert(req.pkiData);
assert.strictEqual(req.pkiType, 'x509+sha256');
assert.strictEqual(req.getChain().length, 1);
assert(req.verify());
assert(!req.verifyChain());
testRequest(req.toRaw());
x509.setTrust([tests.ca.crt]);
assert(req.verifyChain());
assert.strictEqual(req.getCA().name, 'JJs CA');
req.version = 24;
assert(!req.verify());
});
});

File diff suppressed because one or more lines are too long

View File

@ -4,10 +4,10 @@
'use strict';
const Input = require('../lib/primitives/input');
const util = require('../lib/utils/util');
const BufferReader = require('../lib/utils/reader');
const assert = require('./util/assert');
const common = require('./util/common');
const encoding = require('../lib/utils/encoding');
// Take input rawbytes from the raw data format
// p2pkh
@ -236,7 +236,7 @@ describe('Input', function() {
const inputs = test.inputs.map((prevout, i) => {
const input = Input.fromOptions({
prevout: {
hash: util.revHex(prevout.txId),
hash: encoding.revHex(prevout.txId),
index: prevout.vout
}
});

View File

@ -5,7 +5,6 @@
const {inspect} = require('util');
const assert = require('./util/assert');
const util = require('../lib/utils/util');
const encoding = require('../lib/utils/encoding');
const random = require('bcrypto/lib/random');
const consensus = require('../lib/protocol/consensus');
@ -66,7 +65,7 @@ function parseTXTest(data) {
const view = new CoinView();
for (const [txid, index, str, amount] of coins) {
const hash = util.revHex(txid);
const hash = encoding.revHex(txid);
const script = Script.fromString(str);
const value = parseInt(amount || '0', 10);
@ -103,7 +102,7 @@ function parseSighashTest(data) {
const tx = TX.fromRaw(txHex, 'hex');
const script = Script.fromRaw(scriptHex, 'hex');
const expected = util.revHex(hash);
const expected = encoding.revHex(hash);
let hex = type & 3;

View File

@ -19,7 +19,7 @@ const Input = require('../lib/primitives/input');
const Outpoint = require('../lib/primitives/outpoint');
const Script = require('../lib/script/script');
const HD = require('../lib/hd');
const U32 = encoding.U32;
const u32 = encoding.u32;
const KEY1 = 'xprv9s21ZrQH143K3Aj6xQBymM31Zb4BVc7wxqfUhMZrzewdDVCt'
+ 'qUP9iWfcHgJofs25xbaUpCps9GDXj83NiWvQCAkWQhVj5J4CorfnpKX94AZ';
@ -46,9 +46,9 @@ function nextBlock(wdb) {
}
function fakeBlock(height) {
const prev = digest.hash256(U32((height - 1) >>> 0));
const hash = digest.hash256(U32(height >>> 0));
const root = digest.hash256(U32((height | 0x80000000) >>> 0));
const prev = digest.hash256(u32((height - 1) >>> 0));
const hash = digest.hash256(u32(height >>> 0));
const root = digest.hash256(u32((height | 0x80000000) >>> 0));
return {
hash: hash.toString('hex'),