replaced jquery ajax

This commit is contained in:
sairaj mote 2022-07-29 00:09:46 +05:30
parent 7c0aeef420
commit 603312db4e
2 changed files with 217 additions and 200 deletions

View File

@ -13,7 +13,6 @@
href="https://fonts.googleapis.com/css2?family=Calistoga&family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap" href="https://fonts.googleapis.com/css2?family=Calistoga&family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap"
rel="stylesheet"> rel="stylesheet">
<script src="https://unpkg.com/uhtml@3.0.1/es.js"></script> <script src="https://unpkg.com/uhtml@3.0.1/es.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script> </script>
<script type="text/javascript" src="lib.js"></script> <script type="text/javascript" src="lib.js"></script>
<script type="text/javascript" src="lib_btc.js"></script> <script type="text/javascript" src="lib_btc.js"></script>
@ -1449,6 +1448,24 @@
}) })
} }
// replacement for jquery ajax
function ajax(options) {
const xhr = new XMLHttpRequest();
xhr.open(options.method, options.url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
options.success(JSON.parse(this.response));
} else {
options.error(this.statusText);
}
};
xhr.onerror = function () {
options.error(this.statusText);
};
xhr.send(JSON.stringify(options.data));
}
</script> </script>
</body> </body>

View File

@ -1,11 +1,11 @@
(function(GLOBAL) { //lib_btc v1.0.1 (function (GLOBAL) { //lib_btc v1.0.1
/* Utility Libraries required /* Utility Libraries required
* All credits for these codes belong to their respective creators, moderators and owners. * All credits for these codes belong to their respective creators, moderators and owners.
* For more info (including license and terms of use), please visit respective source. * For more info (including license and terms of use), please visit respective source.
*/ */
//sha512.js //sha512.js
(function() { (function () {
/* /*
A JavaScript implementation of the SHA family of hashes, as defined in FIPS A JavaScript implementation of the SHA family of hashes, as defined in FIPS
PUB 180-2 as well as the corresponding HMAC implementation as defined in PUB 180-2 as well as the corresponding HMAC implementation as defined in
@ -94,7 +94,7 @@
}; };
try { try {
a.hasOwnProperty("outputUpper") && (b.outputUpper = a.outputUpper), a.hasOwnProperty("b64Pad") && (b.b64Pad = a.b64Pad) a.hasOwnProperty("outputUpper") && (b.outputUpper = a.outputUpper), a.hasOwnProperty("b64Pad") && (b.b64Pad = a.b64Pad)
} catch (d) {} } catch (d) { }
"boolean" !== typeof b.outputUpper && n("Invalid outputUpper formatting option"); "boolean" !== typeof b.outputUpper && n("Invalid outputUpper formatting option");
"string" !== typeof b.b64Pad && n("Invalid b64Pad formatting option"); "string" !== typeof b.b64Pad && n("Invalid b64Pad formatting option");
return b return b
@ -216,7 +216,7 @@
] : n("Unexpected error in SHA-2 implementation"); ] : n("Unexpected error in SHA-2 implementation");
return D return D
} }
GLOBAL.jsSHA = function(a, b, d) { GLOBAL.jsSHA = function (a, b, d) {
var h = q, var h = q,
f = q, f = q,
g = 0, g = 0,
@ -226,7 +226,7 @@
m = "undefined" !== typeof d ? d : 8; m = "undefined" !== typeof d ? d : 8;
8 === m || 16 === m || n("charSize must be 8 or 16"); 8 === m || 16 === m || n("charSize must be 8 or 16");
"HEX" === b ? (0 !== a.length % 2 && n("srcString of HEX type must be in byte increments"), j = x(a), g = j.binLen, k = j.value) : "ASCII" === b || "TEXT" === b ? (j = u(a, m), g = j.binLen, k = j.value) : "B64" === b ? (j = B(a), g = j.binLen, k = j.value) : n("inputFormat must be HEX, TEXT, ASCII, or B64"); "HEX" === b ? (0 !== a.length % 2 && n("srcString of HEX type must be in byte increments"), j = x(a), g = j.binLen, k = j.value) : "ASCII" === b || "TEXT" === b ? (j = u(a, m), g = j.binLen, k = j.value) : "B64" === b ? (j = B(a), g = j.binLen, k = j.value) : n("inputFormat must be HEX, TEXT, ASCII, or B64");
this.getHash = function(a, b, d) { this.getHash = function (a, b, d) {
var e = q, var e = q,
m = k.slice(), m = k.slice(),
j = ""; j = "";
@ -244,7 +244,7 @@
a ? (q === h && (h = $(m, g, a)), j = e(h, G(d))) : "SHA-512" === a ? (q === f && (f = $(m, g, a)), j = e(f, G(d))) : n("Chosen SHA variant is not supported"); a ? (q === h && (h = $(m, g, a)), j = e(h, G(d))) : "SHA-512" === a ? (q === f && (f = $(m, g, a)), j = e(f, G(d))) : n("Chosen SHA variant is not supported");
return j return j
}; };
this.getHMAC = function(a, b, d, e, f) { this.getHMAC = function (a, b, d, e, f) {
var h, l, j, t, p, y = [], var h, l, j, t, p, y = [],
z = [], z = [],
r = q; r = q;
@ -272,13 +272,13 @@
})(); })();
//coin.js //coin.js
(function() { (function () {
/* /*
Coinjs 0.01 beta by OutCast3k{at}gmail.com Coinjs 0.01 beta by OutCast3k{at}gmail.com
A bitcoin framework. A bitcoin framework.
http://github.com/OutCast3k/coinjs or http://coinb.in/coinjs http://github.com/OutCast3k/coinjs or http://coinb.in/coinjs
*/ */
var coinjs = GLOBAL.coinjs = function() {}; var coinjs = GLOBAL.coinjs = function () { };
/* public vars */ /* public vars */
coinjs.pub = 0x00; coinjs.pub = 0x00;
@ -308,7 +308,7 @@
/* start of address functions */ /* start of address functions */
/* generate a private and public keypair, with address and WIF address */ /* generate a private and public keypair, with address and WIF address */
coinjs.newKeys = function(input) { coinjs.newKeys = function (input) {
var privkey = (input) ? Crypto.SHA256(input) : this.newPrivkey(); var privkey = (input) ? Crypto.SHA256(input) : this.newPrivkey();
var pubkey = this.newPubkey(privkey); var pubkey = this.newPubkey(privkey);
return { return {
@ -321,7 +321,7 @@
} }
/* generate a new random private key */ /* generate a new random private key */
coinjs.newPrivkey = function() { coinjs.newPrivkey = function () {
var x = GLOBAL.location; var x = GLOBAL.location;
x += (GLOBAL.screen.height * GLOBAL.screen.width * GLOBAL.screen.colorDepth); x += (GLOBAL.screen.height * GLOBAL.screen.width * GLOBAL.screen.colorDepth);
x += coinjs.random(64); x += coinjs.random(64);
@ -352,7 +352,7 @@
} }
/* generate a public key from a private key */ /* generate a public key from a private key */
coinjs.newPubkey = function(hash) { coinjs.newPubkey = function (hash) {
var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash)); var privateKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(hash));
var curve = EllipticCurve.getSECCurveByName("secp256k1"); var curve = EllipticCurve.getSECCurveByName("secp256k1");
@ -378,7 +378,7 @@
} }
/* provide a public key and return address */ /* provide a public key and return address */
coinjs.pubkey2address = function(h, byte) { coinjs.pubkey2address = function (h, byte) {
var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), { var r = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(h), {
asBytes: true asBytes: true
})); }));
@ -393,7 +393,7 @@
} }
/* provide a scripthash and return address */ /* provide a scripthash and return address */
coinjs.scripthash2address = function(h) { coinjs.scripthash2address = function (h) {
var x = Crypto.util.hexToBytes(h); var x = Crypto.util.hexToBytes(h);
x.unshift(coinjs.pub); x.unshift(coinjs.pub);
var r = x; var r = x;
@ -407,7 +407,7 @@
} }
/* new multisig address, provide the pubkeys AND required signatures to release the funds */ /* new multisig address, provide the pubkeys AND required signatures to release the funds */
coinjs.pubkeys2MultisigAddress = function(pubkeys, required) { coinjs.pubkeys2MultisigAddress = function (pubkeys, required) {
var s = coinjs.script(); var s = coinjs.script();
s.writeOp(81 + (required * 1) - 1); //OP_1 s.writeOp(81 + (required * 1) - 1); //OP_1
for (var i = 0; i < pubkeys.length; ++i) { for (var i = 0; i < pubkeys.length; ++i) {
@ -449,7 +449,7 @@
may throw a string on failure! may throw a string on failure!
*/ */
coinjs.simpleHodlAddress = function(pubkey, checklocktimeverify) { coinjs.simpleHodlAddress = function (pubkey, checklocktimeverify) {
if (checklocktimeverify < 0) { if (checklocktimeverify < 0) {
throw "Parameter for OP_CHECKLOCKTIMEVERIFY is negative."; throw "Parameter for OP_CHECKLOCKTIMEVERIFY is negative.";
@ -489,7 +489,7 @@
} }
/* create a new segwit address */ /* create a new segwit address */
coinjs.segwitAddress = function(pubkey) { coinjs.segwitAddress = function (pubkey) {
var keyhash = [0x00, 0x14].concat(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { var keyhash = [0x00, 0x14].concat(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), {
asBytes: true asBytes: true
}), { }), {
@ -518,7 +518,7 @@
} }
/* create a new segwit bech32 encoded address */ /* create a new segwit bech32 encoded address */
coinjs.bech32Address = function(pubkey) { coinjs.bech32Address = function (pubkey) {
var program = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), { var program = ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubkey), {
asBytes: true asBytes: true
}), { }), {
@ -533,7 +533,7 @@
} }
/* extract the redeemscript from a bech32 address */ /* extract the redeemscript from a bech32 address */
coinjs.bech32redeemscript = function(address) { coinjs.bech32redeemscript = function (address) {
var r = false; var r = false;
var decode = coinjs.bech32_decode(address); var decode = coinjs.bech32_decode(address);
if (decode) { if (decode) {
@ -544,7 +544,7 @@
} }
/* provide a privkey and return an WIF */ /* provide a privkey and return an WIF */
coinjs.privkey2wif = function(h) { coinjs.privkey2wif = function (h) {
var r = Crypto.util.hexToBytes(h); var r = Crypto.util.hexToBytes(h);
if (coinjs.compressed == true) { if (coinjs.compressed == true) {
@ -563,7 +563,7 @@
} }
/* convert a wif key back to a private key */ /* convert a wif key back to a private key */
coinjs.wif2privkey = function(wif) { coinjs.wif2privkey = function (wif) {
var compressed = false; var compressed = false;
var decode = coinjs.base58decode(wif); var decode = coinjs.base58decode(wif);
var key = decode.slice(0, decode.length - 4); var key = decode.slice(0, decode.length - 4);
@ -579,7 +579,7 @@
} }
/* convert a wif to a pubkey */ /* convert a wif to a pubkey */
coinjs.wif2pubkey = function(wif) { coinjs.wif2pubkey = function (wif) {
var compressed = coinjs.compressed; var compressed = coinjs.compressed;
var r = coinjs.wif2privkey(wif); var r = coinjs.wif2privkey(wif);
coinjs.compressed = r['compressed']; coinjs.compressed = r['compressed'];
@ -592,7 +592,7 @@
} }
/* convert a wif to a address */ /* convert a wif to a address */
coinjs.wif2address = function(wif) { coinjs.wif2address = function (wif) {
var r = coinjs.wif2pubkey(wif); var r = coinjs.wif2pubkey(wif);
return { return {
'address': coinjs.pubkey2address(r['pubkey']), 'address': coinjs.pubkey2address(r['pubkey']),
@ -601,7 +601,7 @@
} }
/* decode or validate an address and return the hash */ /* decode or validate an address and return the hash */
coinjs.addressDecode = function(addr) { coinjs.addressDecode = function (addr) {
try { try {
var bytes = coinjs.base58decode(addr); var bytes = coinjs.base58decode(addr);
var front = bytes.slice(0, bytes.length - 4); var front = bytes.slice(0, bytes.length - 4);
@ -675,13 +675,13 @@
} }
/* retreive the balance from a given address */ /* retreive the balance from a given address */
coinjs.addressBalance = function(address, callback) { coinjs.addressBalance = function (address, callback) {
coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + Math.random(), callback, "GET"); coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=bal&address=' + address + '&r=' + Math.random(), callback, "GET");
} }
/* decompress an compressed public key */ /* decompress an compressed public key */
coinjs.pubkeydecompress = function(pubkey) { coinjs.pubkeydecompress = function (pubkey) {
if ((typeof(pubkey) == 'string') && pubkey.match(/^[a-f0-9]+$/i)) { if ((typeof (pubkey) == 'string') && pubkey.match(/^[a-f0-9]+$/i)) {
var curve = EllipticCurve.getSECCurveByName("secp256k1"); var curve = EllipticCurve.getSECCurveByName("secp256k1");
try { try {
var pt = curve.curve.decodePointHex(pubkey); var pt = curve.curve.decodePointHex(pubkey);
@ -700,7 +700,7 @@
return false; return false;
} }
coinjs.bech32_polymod = function(values) { coinjs.bech32_polymod = function (values) {
var chk = 1; var chk = 1;
var BECH32_GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; var BECH32_GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
for (var p = 0; p < values.length; ++p) { for (var p = 0; p < values.length; ++p) {
@ -715,7 +715,7 @@
return chk; return chk;
} }
coinjs.bech32_hrpExpand = function(hrp) { coinjs.bech32_hrpExpand = function (hrp) {
var ret = []; var ret = [];
var p; var p;
for (p = 0; p < hrp.length; ++p) { for (p = 0; p < hrp.length; ++p) {
@ -728,11 +728,11 @@
return ret; return ret;
} }
coinjs.bech32_verifyChecksum = function(hrp, data) { coinjs.bech32_verifyChecksum = function (hrp, data) {
return coinjs.bech32_polymod(coinjs.bech32_hrpExpand(hrp).concat(data)) === 1; return coinjs.bech32_polymod(coinjs.bech32_hrpExpand(hrp).concat(data)) === 1;
} }
coinjs.bech32_createChecksum = function(hrp, data) { coinjs.bech32_createChecksum = function (hrp, data) {
var values = coinjs.bech32_hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]); var values = coinjs.bech32_hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
var mod = coinjs.bech32_polymod(values) ^ 1; var mod = coinjs.bech32_polymod(values) ^ 1;
var ret = []; var ret = [];
@ -742,7 +742,7 @@
return ret; return ret;
} }
coinjs.bech32_encode = function(hrp, data) { coinjs.bech32_encode = function (hrp, data) {
var combined = data.concat(coinjs.bech32_createChecksum(hrp, data)); var combined = data.concat(coinjs.bech32_createChecksum(hrp, data));
var ret = hrp + '1'; var ret = hrp + '1';
for (var p = 0; p < combined.length; ++p) { for (var p = 0; p < combined.length; ++p) {
@ -751,7 +751,7 @@
return ret; return ret;
} }
coinjs.bech32_decode = function(bechString) { coinjs.bech32_decode = function (bechString) {
var p; var p;
var has_lower = false; var has_lower = false;
var has_upper = false; var has_upper = false;
@ -792,7 +792,7 @@
}; };
} }
coinjs.bech32_convert = function(data, inBits, outBits, pad) { coinjs.bech32_convert = function (data, inBits, outBits, pad) {
var value = 0; var value = 0;
var bits = 0; var bits = 0;
var maxV = (1 << outBits) - 1; var maxV = (1 << outBits) - 1;
@ -820,7 +820,7 @@
return result; return result;
} }
coinjs.testdeterministicK = function() { coinjs.testdeterministicK = function () {
// https://github.com/bitpay/bitcore/blob/9a5193d8e94b0bd5b8e7f00038e7c0b935405a03/test/crypto/ecdsa.js // https://github.com/bitpay/bitcore/blob/9a5193d8e94b0bd5b8e7f00038e7c0b935405a03/test/crypto/ecdsa.js
// Line 21 and 22 specify digest hash and privkey for the first 2 test vectors. // Line 21 and 22 specify digest hash and privkey for the first 2 test vectors.
// Line 96-117 tells expected result. // Line 96-117 tells expected result.
@ -902,7 +902,7 @@
var result_txt = '\n----------------------\nResults\n----------------------\n\n'; var result_txt = '\n----------------------\nResults\n----------------------\n\n';
for (i = 0; i < test_vectors.length; i++) { for (i = 0; i < test_vectors.length; i++) {
var hash = Crypto.SHA256(test_vectors[i]['message'].split('').map(function(c) { var hash = Crypto.SHA256(test_vectors[i]['message'].split('').map(function (c) {
return c.charCodeAt(0); return c.charCodeAt(0);
}), { }), {
asBytes: true asBytes: true
@ -938,17 +938,17 @@
}; };
/* start of hd functions, thanks bip32.org */ /* start of hd functions, thanks bip32.org */
coinjs.hd = function(data) { coinjs.hd = function (data) {
var r = {}; var r = {};
/* some hd value parsing */ /* some hd value parsing */
r.parse = function() { r.parse = function () {
var bytes = []; var bytes = [];
// some quick validation // some quick validation
if (typeof(data) == 'string') { if (typeof (data) == 'string') {
var decoded = coinjs.base58decode(data); var decoded = coinjs.base58decode(data);
if (decoded.length == 82) { if (decoded.length == 82) {
var checksum = decoded.slice(78, 82); var checksum = decoded.slice(78, 82);
@ -1009,7 +1009,7 @@
} }
// extend prv/pub key // extend prv/pub key
r.extend = function() { r.extend = function () {
var hd = coinjs.hd(); var hd = coinjs.hd();
return hd.make({ return hd.make({
'depth': (this.depth * 1) + 1, 'depth': (this.depth * 1) + 1,
@ -1022,7 +1022,7 @@
} }
// derive from path // derive from path
r.derive_path = function(path) { r.derive_path = function (path) {
if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'') return this; if (path == 'm' || path == 'M' || path == 'm\'' || path == 'M\'') return this;
@ -1050,7 +1050,7 @@
} }
// derive key from index // derive key from index
r.derive = function(i) { r.derive = function (i) {
i = (i) ? i : 0; i = (i) ? i : 0;
var blob = (Crypto.util.hexToBytes(this.keys.pubkey)).concat(coinjs.numToBytes(i, 4).reverse()); var blob = (Crypto.util.hexToBytes(this.keys.pubkey)).concat(coinjs.numToBytes(i, 4).reverse());
@ -1118,7 +1118,7 @@
} }
// make a master hd xprv/xpub // make a master hd xprv/xpub
r.master = function(pass) { r.master = function (pass) {
var seed = (pass) ? Crypto.SHA256(pass) : coinjs.newPrivkey(); var seed = (pass) ? Crypto.SHA256(pass) : coinjs.newPrivkey();
var hasher = new jsSHA(seed, 'HEX'); var hasher = new jsSHA(seed, 'HEX');
var I = hasher.getHMAC("Bitcoin seed", "TEXT", "SHA-512", "HEX"); var I = hasher.getHMAC("Bitcoin seed", "TEXT", "SHA-512", "HEX");
@ -1138,7 +1138,7 @@
} }
// encode data to a base58 string // encode data to a base58 string
r.make = function(data) { // { (int) depth, (array) parent_fingerprint, (int) child_index, (byte array) chain_code, (hex str) privkey, (hex str) pubkey} r.make = function (data) { // { (int) depth, (array) parent_fingerprint, (int) child_index, (byte array) chain_code, (hex str) privkey, (hex str) pubkey}
var k = []; var k = [];
//depth //depth
@ -1193,7 +1193,7 @@
/* start of script functions */ /* start of script functions */
coinjs.script = function(data) { coinjs.script = function (data) {
var r = {}; var r = {};
if (!data) { if (!data) {
@ -1209,7 +1209,7 @@
} }
/* parse buffer array */ /* parse buffer array */
r.parse = function() { r.parse = function () {
var self = this; var self = this;
r.chunks = []; r.chunks = [];
@ -1251,7 +1251,7 @@
}; };
/* decode the redeemscript of a multisignature transaction */ /* decode the redeemscript of a multisignature transaction */
r.decodeRedeemScript = function(script) { r.decodeRedeemScript = function (script) {
var r = false; var r = false;
try { try {
var s = coinjs.script(Crypto.util.hexToBytes(script)); var s = coinjs.script(Crypto.util.hexToBytes(script));
@ -1294,7 +1294,7 @@
} }
/* create output script to spend */ /* create output script to spend */
r.spendToScript = function(address) { r.spendToScript = function (address) {
var addr = coinjs.addressDecode(address); var addr = coinjs.addressDecode(address);
var s = coinjs.script(); var s = coinjs.script();
if (addr.type == "bech32") { if (addr.type == "bech32") {
@ -1315,7 +1315,7 @@
} }
/* geneate a (script) pubkey hash of the address - used for when signing */ /* geneate a (script) pubkey hash of the address - used for when signing */
r.pubkeyHash = function(address) { r.pubkeyHash = function (address) {
var addr = coinjs.addressDecode(address); var addr = coinjs.addressDecode(address);
var s = coinjs.script(); var s = coinjs.script();
s.writeOp(118); //OP_DUP s.writeOp(118); //OP_DUP
@ -1327,14 +1327,14 @@
} }
/* write to buffer */ /* write to buffer */
r.writeOp = function(op) { r.writeOp = function (op) {
this.buffer.push(op); this.buffer.push(op);
this.chunks.push(op); this.chunks.push(op);
return true; return true;
} }
/* write bytes to buffer */ /* write bytes to buffer */
r.writeBytes = function(data) { r.writeBytes = function (data) {
if (data.length < 76) { //OP_PUSHDATA1 if (data.length < 76) { //OP_PUSHDATA1
this.buffer.push(data.length); this.buffer.push(data.length);
} else if (data.length <= 0xff) { } else if (data.length <= 0xff) {
@ -1363,7 +1363,7 @@
/* start of transaction functions */ /* start of transaction functions */
/* create a new transaction object */ /* create a new transaction object */
coinjs.transaction = function() { coinjs.transaction = function () {
var r = {}; var r = {};
r.version = 1; r.version = 1;
@ -1375,7 +1375,7 @@
r.block = null; r.block = null;
/* add an input to a transaction */ /* add an input to a transaction */
r.addinput = function(txid, index, script, sequence) { r.addinput = function (txid, index, script, sequence) {
var o = {}; var o = {};
o.outpoint = { o.outpoint = {
'hash': txid, 'hash': txid,
@ -1387,7 +1387,7 @@
} }
/* add an output to a transaction */ /* add an output to a transaction */
r.addoutput = function(address, value) { r.addoutput = function (address, value) {
var o = {}; var o = {};
o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10); o.value = new BigInteger('' + Math.round((value * 1) * 1e8), 10);
var s = coinjs.script(); var s = coinjs.script();
@ -1397,7 +1397,7 @@
} }
/* add two outputs for stealth addresses to a transaction */ /* add two outputs for stealth addresses to a transaction */
r.addstealth = function(stealth, value) { r.addstealth = function (stealth, value) {
var ephemeralKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(coinjs.newPrivkey())); var ephemeralKeyBigInt = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(coinjs.newPrivkey()));
var curve = EllipticCurve.getSECCurveByName("secp256k1"); var curve = EllipticCurve.getSECCurveByName("secp256k1");
@ -1439,7 +1439,7 @@
} }
/* add data to a transaction */ /* add data to a transaction */
r.adddata = function(data) { r.adddata = function (data) {
var r = false; var r = false;
if (((data.match(/^[a-f0-9]+$/gi)) && data.length < 160) && (data.length % 2) == 0) { if (((data.match(/^[a-f0-9]+$/gi)) && data.length < 160) && (data.length % 2) == 0) {
var s = coinjs.script(); var s = coinjs.script();
@ -1454,19 +1454,19 @@
} }
/* list unspent transactions */ /* list unspent transactions */
r.listUnspent = function(address, callback) { r.listUnspent = function (address, callback) {
coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + Math.random(), callback, "GET"); coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=addresses&request=unspent&address=' + address + '&r=' + Math.random(), callback, "GET");
} }
/* list transaction data */ /* list transaction data */
r.getTransaction = function(txid, callback) { r.getTransaction = function (txid, callback) {
coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + Math.random(), callback, "GET"); coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=gettransaction&txid=' + txid + '&r=' + Math.random(), callback, "GET");
} }
/* add unspent to transaction */ /* add unspent to transaction */
r.addUnspent = function(address, callback, script, segwit, sequence) { r.addUnspent = function (address, callback, script, segwit, sequence) {
var self = this; var self = this;
this.listUnspent(address, function(data) { this.listUnspent(address, function (data) {
var s = coinjs.script(); var s = coinjs.script();
var value = 0; var value = 0;
var total = 0; var total = 0;
@ -1519,23 +1519,23 @@
} }
/* add unspent and sign */ /* add unspent and sign */
r.addUnspentAndSign = function(wif, callback) { r.addUnspentAndSign = function (wif, callback) {
var self = this; var self = this;
var address = coinjs.wif2address(wif); var address = coinjs.wif2address(wif);
self.addUnspent(address['address'], function(data) { self.addUnspent(address['address'], function (data) {
self.sign(wif); self.sign(wif);
return callback(data); return callback(data);
}); });
} }
/* broadcast a transaction */ /* broadcast a transaction */
r.broadcast = function(callback, txhex) { r.broadcast = function (callback, txhex) {
var tx = txhex || this.serialize(); var tx = txhex || this.serialize();
coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=sendrawtransaction', callback, "POST", ["rawtx=" + tx]); coinjs.ajax(coinjs.host + '?uid=' + coinjs.uid + '&key=' + coinjs.key + '&setmodule=bitcoin&request=sendrawtransaction', callback, "POST", ["rawtx=" + tx]);
} }
/* generate the transaction hash to sign from a transaction input */ /* generate the transaction hash to sign from a transaction input */
r.transactionHash = function(index, sigHashType) { r.transactionHash = function (index, sigHashType) {
var clone = coinjs.clone(this); var clone = coinjs.clone(this);
var shType = sigHashType || 1; var shType = sigHashType || 1;
@ -1619,7 +1619,7 @@
} }
/* generate a segwit transaction hash to sign from a transaction input */ /* generate a segwit transaction hash to sign from a transaction input */
r.transactionHashSegWitV0 = function(index, sigHashType) { r.transactionHashSegWitV0 = function (index, sigHashType) {
/* /*
Notice: coinb.in by default, deals with segwit transactions in a non-standard way. Notice: coinb.in by default, deals with segwit transactions in a non-standard way.
Segwit transactions require that input values are included in the transaction hash. Segwit transactions require that input values are included in the transaction hash.
@ -1749,7 +1749,7 @@
} }
/* extract the scriptSig, used in the transactionHash() function */ /* extract the scriptSig, used in the transactionHash() function */
r.extractScriptKey = function(index) { r.extractScriptKey = function (index) {
if (this.ins[index]) { if (this.ins[index]) {
if ((this.ins[index].script.chunks.length == 5) && this.ins[index].script.chunks[4] == 172 && coinjs.isArray(this.ins[index].script.chunks[2])) { //OP_CHECKSIG if ((this.ins[index].script.chunks.length == 5) && this.ins[index].script.chunks[4] == 172 && coinjs.isArray(this.ins[index].script.chunks[2])) { //OP_CHECKSIG
// regular scriptPubkey (not signed) // regular scriptPubkey (not signed)
@ -1846,7 +1846,7 @@
} }
/* generate a signature from a transaction hash */ /* generate a signature from a transaction hash */
r.transactionSig = function(index, wif, sigHashType, txhash) { r.transactionSig = function (index, wif, sigHashType, txhash) {
function serializeSig(r, s) { function serializeSig(r, s) {
var rBa = r.toByteArraySigned(); var rBa = r.toByteArraySigned();
@ -1902,7 +1902,7 @@
} }
// https://tools.ietf.org/html/rfc6979#section-3.2 // https://tools.ietf.org/html/rfc6979#section-3.2
r.deterministicK = function(wif, hash, badrs) { r.deterministicK = function (wif, hash, badrs) {
// if r or s were invalid when this function was used in signing, // if r or s were invalid when this function was used in signing,
// we do not want to actually compute r, s here for efficiency, so, // we do not want to actually compute r, s here for efficiency, so,
// we can increment badrs. explained at end of RFC 6979 section 3.2 // we can increment badrs. explained at end of RFC 6979 section 3.2
@ -1980,7 +1980,7 @@
}; };
/* sign a "standard" input */ /* sign a "standard" input */
r.signinput = function(index, wif, sigHashType) { r.signinput = function (index, wif, sigHashType) {
var key = coinjs.wif2pubkey(wif); var key = coinjs.wif2pubkey(wif);
var shType = sigHashType || 1; var shType = sigHashType || 1;
var signature = this.transactionSig(index, wif, shType); var signature = this.transactionSig(index, wif, shType);
@ -1992,7 +1992,7 @@
} }
/* signs a time locked / hodl input */ /* signs a time locked / hodl input */
r.signhodl = function(index, wif, sigHashType) { r.signhodl = function (index, wif, sigHashType) {
var shType = sigHashType || 1; var shType = sigHashType || 1;
var signature = this.transactionSig(index, wif, shType); var signature = this.transactionSig(index, wif, shType);
var redeemScript = this.ins[index].script.buffer var redeemScript = this.ins[index].script.buffer
@ -2004,7 +2004,7 @@
} }
/* sign a multisig input */ /* sign a multisig input */
r.signmultisig = function(index, wif, sigHashType) { r.signmultisig = function (index, wif, sigHashType) {
function scriptListPubkey(redeemScript) { function scriptListPubkey(redeemScript) {
var r = {}; var r = {};
@ -2059,7 +2059,7 @@
} }
/* sign segwit input */ /* sign segwit input */
r.signsegwit = function(index, wif, sigHashType) { r.signsegwit = function (index, wif, sigHashType) {
var shType = sigHashType || 1; var shType = sigHashType || 1;
var wif2 = coinjs.wif2pubkey(wif); var wif2 = coinjs.wif2pubkey(wif);
@ -2134,7 +2134,7 @@
} }
/* sign inputs */ /* sign inputs */
r.sign = function(wif, sigHashType) { r.sign = function (wif, sigHashType) {
var shType = sigHashType || 1; var shType = sigHashType || 1;
for (var i = 0; i < this.ins.length; i++) { for (var i = 0; i < this.ins.length; i++) {
var d = this.extractScriptKey(i); var d = this.extractScriptKey(i);
@ -2163,7 +2163,7 @@
} }
/* serialize a transaction */ /* serialize a transaction */
r.serialize = function() { r.serialize = function () {
var buffer = []; var buffer = [];
buffer = buffer.concat(coinjs.numToBytes(parseInt(this.version), 4)); buffer = buffer.concat(coinjs.numToBytes(parseInt(this.version), 4));
@ -2206,7 +2206,7 @@
} }
/* deserialize a transaction */ /* deserialize a transaction */
r.deserialize = function(buffer) { r.deserialize = function (buffer) {
if (typeof buffer == "string") { if (typeof buffer == "string") {
buffer = Crypto.util.hexToBytes(buffer) buffer = Crypto.util.hexToBytes(buffer)
} }
@ -2214,13 +2214,13 @@
var pos = 0; var pos = 0;
var witness = false; var witness = false;
var readAsInt = function(bytes) { var readAsInt = function (bytes) {
if (bytes == 0) return 0; if (bytes == 0) return 0;
pos++; pos++;
return buffer[pos - 1] + readAsInt(bytes - 1) * 256; return buffer[pos - 1] + readAsInt(bytes - 1) * 256;
} }
var readVarInt = function() { var readVarInt = function () {
pos++; pos++;
if (buffer[pos - 1] < 253) { if (buffer[pos - 1] < 253) {
return buffer[pos - 1]; return buffer[pos - 1];
@ -2228,12 +2228,12 @@
return readAsInt(buffer[pos - 1] - 251); return readAsInt(buffer[pos - 1] - 251);
} }
var readBytes = function(bytes) { var readBytes = function (bytes) {
pos += bytes; pos += bytes;
return buffer.slice(pos - bytes, pos); return buffer.slice(pos - bytes, pos);
} }
var readVarString = function() { var readVarString = function () {
var size = readVarInt(); var size = readVarInt();
return readBytes(size); return readBytes(size);
} }
@ -2287,7 +2287,7 @@
return obj; return obj;
} }
r.size = function() { r.size = function () {
return ((this.serialize()).length / 2).toFixed(0); return ((this.serialize()).length / 2).toFixed(0);
} }
@ -2296,7 +2296,7 @@
/* start of signature vertification functions */ /* start of signature vertification functions */
coinjs.verifySignature = function(hash, sig, pubkey) { coinjs.verifySignature = function (hash, sig, pubkey) {
function parseSig(sig) { function parseSig(sig) {
var cursor; var cursor;
@ -2351,7 +2351,7 @@
return coinjs.verifySignatureRaw(e, r, s, Q); return coinjs.verifySignatureRaw(e, r, s, Q);
} }
coinjs.verifySignatureRaw = function(e, r, s, Q) { coinjs.verifySignatureRaw = function (e, r, s, Q) {
var ecparams = EllipticCurve.getSECCurveByName("secp256k1"); var ecparams = EllipticCurve.getSECCurveByName("secp256k1");
var n = ecparams.getN(); var n = ecparams.getN();
var G = ecparams.getG(); var G = ecparams.getG();
@ -2377,7 +2377,7 @@
/* start of privates functions */ /* start of privates functions */
/* base58 encode function */ /* base58 encode function */
coinjs.base58encode = function(buffer) { coinjs.base58encode = function (buffer) {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var base = BigInteger.valueOf(58); var base = BigInteger.valueOf(58);
@ -2400,7 +2400,7 @@
} }
/* base58 decode function */ /* base58 decode function */
coinjs.base58decode = function(buffer) { coinjs.base58decode = function (buffer) {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
var base = BigInteger.valueOf(58); var base = BigInteger.valueOf(58);
var validRegex = /^[1-9A-HJ-NP-Za-km-z]+$/; var validRegex = /^[1-9A-HJ-NP-Za-km-z]+$/;
@ -2424,7 +2424,7 @@
} }
/* raw ajax function to avoid needing bigger frame works like jquery, mootools etc */ /* raw ajax function to avoid needing bigger frame works like jquery, mootools etc */
coinjs.ajax = function(u, f, m, a) { coinjs.ajax = function (u, f, m, a) {
var x = false; var x = false;
try { try {
x = new ActiveXObject('Msxml2.XMLHTTP') x = new ActiveXObject('Msxml2.XMLHTTP')
@ -2441,7 +2441,7 @@
} }
x.open(m, u, true); x.open(m, u, true);
x.onreadystatechange = function() { x.onreadystatechange = function () {
if ((x.readyState == 4) && f) if ((x.readyState == 4) && f)
f(x.responseText); f(x.responseText);
}; };
@ -2454,8 +2454,8 @@
} }
/* clone an object */ /* clone an object */
coinjs.clone = function(obj) { coinjs.clone = function (obj) {
if (obj == null || typeof(obj) != 'object') return obj; if (obj == null || typeof (obj) != 'object') return obj;
var temp = new obj.constructor(); var temp = new obj.constructor();
for (var key in obj) { for (var key in obj) {
@ -2466,7 +2466,7 @@
return temp; return temp;
} }
coinjs.numToBytes = function(num, bytes) { coinjs.numToBytes = function (num, bytes) {
if (typeof bytes === "undefined") bytes = 8; if (typeof bytes === "undefined") bytes = 8;
if (bytes == 0) { if (bytes == 0) {
return []; return [];
@ -2486,7 +2486,7 @@
0; 0;
} }
coinjs.numToScriptNumBytes = function(_number) { coinjs.numToScriptNumBytes = function (_number) {
var value = Math.abs(_number); var value = Math.abs(_number);
var size = scriptNumSize(value); var size = scriptNumSize(value);
var result = []; var result = [];
@ -2504,7 +2504,7 @@
return result; return result;
} }
coinjs.numToVarInt = function(num) { coinjs.numToVarInt = function (num) {
if (num < 253) { if (num < 253) {
return [num]; return [num];
} else if (num < 65536) { } else if (num < 65536) {
@ -2516,12 +2516,12 @@
} }
} }
coinjs.bytesToNum = function(bytes) { coinjs.bytesToNum = function (bytes) {
if (bytes.length == 0) return 0; if (bytes.length == 0) return 0;
else return bytes[0] + 256 * coinjs.bytesToNum(bytes.slice(1)); else return bytes[0] + 256 * coinjs.bytesToNum(bytes.slice(1));
} }
coinjs.uint = function(f, size) { coinjs.uint = function (f, size) {
if (f.length < size) if (f.length < size)
throw new Error("not enough data"); throw new Error("not enough data");
var n = 0; var n = 0;
@ -2532,11 +2532,11 @@
return n; return n;
} }
coinjs.isArray = function(o) { coinjs.isArray = function (o) {
return Object.prototype.toString.call(o) === '[object Array]'; return Object.prototype.toString.call(o) === '[object Array]';
} }
coinjs.countObject = function(obj) { coinjs.countObject = function (obj) {
var count = 0; var count = 0;
var i; var i;
for (i in obj) { for (i in obj) {
@ -2547,7 +2547,7 @@
return count; return count;
} }
coinjs.random = function(length) { coinjs.random = function (length) {
var r = ""; var r = "";
var l = length || 25; var l = length || 25;
var chars = "!$%^&*()_+{}:@~?><|\./;'#][=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; var chars = "!$%^&*()_+{}:@~?><|\./;'#][=-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
@ -2560,13 +2560,13 @@
})(); })();
})(typeof global !== "undefined" ? global : window); })(typeof global !== "undefined" ? global : window);
(function(EXPORTS) { //btc_api v1.0.6 (function (EXPORTS) { //btc_api v1.0.6
const btc_api = EXPORTS; const btc_api = EXPORTS;
//This library uses API provided by chain.so (https://chain.so/) //This library uses API provided by chain.so (https://chain.so/)
const URL = "https://chain.so/api/v2/"; const URL = "https://chain.so/api/v2/";
const fetch_api = btc_api.fetch = function(api) { const fetch_api = btc_api.fetch = function (api) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.debug(URL + api); console.debug(URL + api);
fetch(URL + api).then(response => { fetch(URL + api).then(response => {
@ -2578,7 +2578,7 @@
}; };
const broadcast = btc_api.broadcast = rawtx => new Promise((resolve, reject) => { const broadcast = btc_api.broadcast = rawtx => new Promise((resolve, reject) => {
$.ajax({ ajax({
type: "POST", type: "POST",
url: URL + "send_tx/BTC/", url: URL + "send_tx/BTC/",
data: { data: {
@ -2615,7 +2615,7 @@
coinjs.compressed = true; coinjs.compressed = true;
const verifyKey = btc_api.verifyKey = function(addr, key) { const verifyKey = btc_api.verifyKey = function (addr, key) {
if (!addr || !key) if (!addr || !key)
return undefined; return undefined;
switch (coinjs.addressDecode(addr).type) { switch (coinjs.addressDecode(addr).type) {
@ -2630,7 +2630,7 @@
} }
} }
const validateAddress = btc_api.validateAddress = function(addr) { const validateAddress = btc_api.validateAddress = function (addr) {
if (!addr) if (!addr)
return undefined; return undefined;
let type = coinjs.addressDecode(addr).type; let type = coinjs.addressDecode(addr).type;
@ -2643,7 +2643,7 @@
//convert from one blockchain to another blockchain (target version) //convert from one blockchain to another blockchain (target version)
btc_api.convert = {}; btc_api.convert = {};
btc_api.convert.wif = function(source_wif, target_version = coinjs.priv) { btc_api.convert.wif = function (source_wif, target_version = coinjs.priv) {
let keyHex = decodeLegacy(source_wif).hex; let keyHex = decodeLegacy(source_wif).hex;
if (!keyHex || keyHex.length < 66 || !/01$/.test(keyHex)) if (!keyHex || keyHex.length < 66 || !/01$/.test(keyHex))
return null; return null;
@ -2651,7 +2651,7 @@
return encodeLegacy(keyHex, target_version); return encodeLegacy(keyHex, target_version);
} }
btc_api.convert.legacy2legacy = function(source_addr, target_version = coinjs.pub) { btc_api.convert.legacy2legacy = function (source_addr, target_version = coinjs.pub) {
let rawHex = decodeLegacy(source_addr).hex; let rawHex = decodeLegacy(source_addr).hex;
if (!rawHex) if (!rawHex)
return null; return null;
@ -2659,7 +2659,7 @@
return encodeLegacy(rawHex, target_version); return encodeLegacy(rawHex, target_version);
} }
btc_api.convert.legacy2bech = function(source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { btc_api.convert.legacy2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) {
let rawHex = decodeLegacy(source_addr).hex; let rawHex = decodeLegacy(source_addr).hex;
if (!rawHex) if (!rawHex)
return null; return null;
@ -2667,7 +2667,7 @@
return encodeBech32(rawHex, target_version, target_hrp); return encodeBech32(rawHex, target_version, target_hrp);
} }
btc_api.convert.bech2bech = function(source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) { btc_api.convert.bech2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) {
let rawHex = decodeBech32(source_addr).hex; let rawHex = decodeBech32(source_addr).hex;
if (!rawHex) if (!rawHex)
return null; return null;
@ -2675,7 +2675,7 @@
return encodeBech32(rawHex, target_version, target_hrp); return encodeBech32(rawHex, target_version, target_hrp);
} }
btc_api.convert.bech2legacy = function(source_addr, target_version = coinjs.pub) { btc_api.convert.bech2legacy = function (source_addr, target_version = coinjs.pub) {
let rawHex = decodeBech32(source_addr).hex; let rawHex = decodeBech32(source_addr).hex;
if (!rawHex) if (!rawHex)
return null; return null;
@ -2777,7 +2777,7 @@
script = Crypto.util.bytesToHex(s.buffer); script = Crypto.util.bytesToHex(s.buffer);
} else //legacy script } else //legacy script
script = utxos[i].script_hex; script = utxos[i].script_hex;
tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/ ); //0xfffffffd for Replace-by-fee tx.addinput(utxos[i].txid, utxos[i].output_no, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee
} }
addUTXOs(tx, senders, redeemScripts, required_amount, n + 1) addUTXOs(tx, senders, redeemScripts, required_amount, n + 1)
.then(result => resolve(result)) .then(result => resolve(result))
@ -2786,7 +2786,7 @@
}) })
} }
btc_api.sendTx = function(senders, privkeys, receivers, amounts, fee, change_addr = null) { btc_api.sendTx = function (senders, privkeys, receivers, amounts, fee, change_addr = null) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
//Add values into array (if single values are passed) //Add values into array (if single values are passed)
if (!Array.isArray(senders)) if (!Array.isArray(senders))
@ -2851,7 +2851,7 @@
tx.addoutput(change_addr || senders[0], change); tx.addoutput(change_addr || senders[0], change);
console.debug("amounts (total, fee, change):", total_amount, fee, change); console.debug("amounts (total, fee, change):", total_amount, fee, change);
console.debug("Unsigned:", tx.serialize()); console.debug("Unsigned:", tx.serialize());
new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/ ))); //Sign the tx using private key WIF new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/))); //Sign the tx using private key WIF
console.debug("Signed:", tx.serialize()); console.debug("Signed:", tx.serialize());
debugger; debugger;