Updating standard ops

This commit is contained in:
Vivek Teega 2020-08-20 17:12:45 +05:30
parent 801c08f2de
commit f6b5ef6c81

View File

@ -717,8 +717,7 @@
for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) {
if (imod4 == 0) continue; if (imod4 == 0) continue;
bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - bytes.push(((base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) |
1)) << (imod4 * 2)) |
(base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
} }
@ -1114,7 +1113,7 @@
(function () { (function () {
// Constructor function of Global SecureRandom object // Constructor function of Global SecureRandom object
var sr = window.SecureRandom = function () {}; var sr = window.SecureRandom = function () { };
// Properties // Properties
sr.state; sr.state;
@ -1242,9 +1241,7 @@
window.crypto.getRandomValues(ua); window.crypto.getRandomValues(ua);
for (t = 0; t < sr.poolSize; ++t) for (t = 0; t < sr.poolSize; ++t)
sr.pool[sr.pptr++] = ua[t]; sr.pool[sr.pptr++] = ua[t];
} catch (e) { } catch (e) { alert(e); }
alert(e);
}
} }
while (sr.pptr < sr.poolSize) { // extract some randomness from Math.random() while (sr.pptr < sr.poolSize) { // extract some randomness from Math.random()
t = Math.floor(65536 * Math.random()); t = Math.floor(65536 * Math.random());
@ -1267,13 +1264,11 @@
// browser plugin details: ~16.2 to ~21.8 bits // browser plugin details: ~16.2 to ~21.8 bits
var pluginsStr = ""; var pluginsStr = "";
for (var i = 0; i < navigator.plugins.length; i++) { for (var i = 0; i < navigator.plugins.length; i++) {
pluginsStr += navigator.plugins[i].name + " " + navigator.plugins[i].filename + " " + navigator pluginsStr += navigator.plugins[i].name + " " + navigator.plugins[i].filename + " " + navigator.plugins[i].description + " " + navigator.plugins[i].version + ", ";
.plugins[i].description + " " + navigator.plugins[i].version + ", ";
} }
var mimeTypesStr = ""; var mimeTypesStr = "";
for (var i = 0; i < navigator.mimeTypes.length; i++) { for (var i = 0; i < navigator.mimeTypes.length; i++) {
mimeTypesStr += navigator.mimeTypes[i].description + " " + navigator.mimeTypes[i].type + " " + mimeTypesStr += navigator.mimeTypes[i].description + " " + navigator.mimeTypes[i].type + " " + navigator.mimeTypes[i].suffixes + ", ";
navigator.mimeTypes[i].suffixes + ", ";
} }
entropyStr += pluginsStr + mimeTypesStr; entropyStr += pluginsStr + mimeTypesStr;
// cookies and storage: 1 bit // cookies and storage: 1 bit
@ -1285,10 +1280,8 @@
// location // location
entropyStr += window.location; entropyStr += window.location;
var entropyBytes = Crypto.SHA256(entropyStr, { var entropyBytes = Crypto.SHA256(entropyStr, { asBytes: true });
asBytes: true for (var i = 0 ; i < entropyBytes.length ; i++) {
});
for (var i = 0; i < entropyBytes.length; i++) {
sr.seedInt8(entropyBytes[i]); sr.seedInt8(entropyBytes[i]);
} }
} }
@ -4589,8 +4582,7 @@
// x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q);
// y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)) var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(
.multiply(
b.z).add(u.multiply(v3)).mod(this.curve.q); b.z).add(u.multiply(v3)).mod(this.curve.q);
// z3 = v^3 * z1 * z2 // z3 = v^3 * z1 * z2
var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q);
@ -4693,8 +4685,7 @@
ec.PointFp.prototype.getEncoded = function (compressed) { ec.PointFp.prototype.getEncoded = function (compressed) {
var x = this.getX().toBigInteger(); var x = this.getX().toBigInteger();
var y = this.getY().toBigInteger(); var y = this.getY().toBigInteger();
var len = var len = 32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol.
32; // integerToBytes will zero pad if integer is less than 32 bytes. 32 bytes length is required by the Bitcoin protocol.
var enc = ec.integerToBytes(x, len); var enc = ec.integerToBytes(x, len);
// when compressed prepend byte depending if y point is even or odd // when compressed prepend byte depending if y point is even or odd
@ -4706,8 +4697,7 @@
} }
} else { } else {
enc.unshift(0x04); enc.unshift(0x04);
enc = enc.concat(ec.integerToBytes(y, enc = enc.concat(ec.integerToBytes(y, len)); // uncompressed public key appends the bytes of the y point
len)); // uncompressed public key appends the bytes of the y point
} }
return enc; return enc;
}; };
@ -5171,8 +5161,7 @@
btrx.addflodata = function (txcomments) { // flochange - this whole function needs to be done btrx.addflodata = function (txcomments) { // flochange - this whole function needs to be done
this.floData = txcomments; this.floData = txcomments;
return this return this.floData; //flochange .. returning the txcomments -- check if the function return will assign
.floData; //flochange .. returning the txcomments -- check if the function return will assign
} }
@ -5464,28 +5453,26 @@
buffer = buffer.concat(scriptBytes); buffer = buffer.concat(scriptBytes);
} }
buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime), 4)); buffer = buffer.concat(bitjs.numToBytes(parseInt(this.locktime),4));
flohex = ascii_to_hexa(this.floData); flohex = ascii_to_hexa(this.floData);
floDataCount = this.floData.length; floDataCount = this.floData.length;
//flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction //flochange -- creating unique data character count logic for floData. This string is prefixed before actual floData string in Raw Transaction
if (floDataCount <= 16) { if (floDataCount <= 16) {
floDataCountString = floDataCount.toString(16); floDataCountString = floDataCount.toString(16);
floDataCountString = "0" + floDataCountString; floDataCountString = "0"+ floDataCountString;
} else if (floDataCount < 253) { } else if (floDataCount < 253) {
floDataCountString = floDataCount.toString(16); floDataCountString = floDataCount.toString(16);
} else if (floDataCount <= 1023) { } else if (floDataCount <= 1023) {
floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd");
floDataCountStringAdjusted = floDataCountAdjusted.toString(16); floDataCountStringAdjusted = floDataCountAdjusted.toString(16);
floDataCountString = floDataCountStringAdjusted.substr(0, 2) + floDataCountStringAdjusted floDataCountString = floDataCountStringAdjusted.substr(0,2)+ floDataCountStringAdjusted.substr(4,2)+ floDataCountStringAdjusted.substr(2,2);
.substr(4, 2) + floDataCountStringAdjusted.substr(2, 2);
} else { } else {
floDataCountString = "Character Limit Exceeded"; floDataCountString = "Character Limit Exceeded";
} }
return Crypto.util.bytesToHex(buffer) + floDataCountString + return Crypto.util.bytesToHex(buffer)+floDataCountString+flohex; // flochange -- Addition of floDataCountString and floData in serialization
flohex; // flochange -- Addition of floDataCountString and floData in serialization
} }
@ -5705,18 +5692,17 @@
); );
//https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js //https://raw.github.com/bitcoinjs/bitcoinjs-lib/09e8c6e184d6501a0c2c59d73ca64db5c0d3eb95/src/address.js
Bitcoin.Address = function (bytes) { Bitcoin.Address = function (bytes) {
if (floGlobals.blockchain == "FLO") if(floGlobals.blockchain == "FLO")
this.version = 0x23; // FLO mainnet public address this.version = 0x23; // FLO mainnet public address
else if (floGlobals.blockchain == "FLO_TEST") else if(floGlobals.blockchain == "FLO_TEST")
this.version = 0x73; // FLO testnet public address this.version = 0x73; // FLO testnet public address
if ("string" == typeof bytes) { if ("string" == typeof bytes) {
bytes = Bitcoin.Address.decodeString(bytes, this.version); bytes = Bitcoin.Address.decodeString(bytes,this.version);
} }
this.hash = bytes; this.hash = bytes;
}; };
Bitcoin.Address.networkVersion = Bitcoin.Address.networkVersion = 0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) // *this has no effect *
0x23; // (FLO mainnet 0x23, 35D), (Bitcoin Mainnet, 0x00, 0D) // *this has no effect *
/** /**
* Serialize this object as a standard Bitcoin address. * Serialize this object as a standard Bitcoin address.
@ -5729,11 +5715,7 @@
// Version // Version
hash.unshift(this.version); hash.unshift(this.version);
var checksum = Crypto.SHA256(Crypto.SHA256(hash, { var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true });
asBytes: true
}), {
asBytes: true
});
var bytes = hash.concat(checksum.slice(0, 4)); var bytes = hash.concat(checksum.slice(0, 4));
return Bitcoin.Base58.encode(bytes); return Bitcoin.Base58.encode(bytes);
}; };
@ -5745,14 +5727,10 @@
/** /**
* Parse a Bitcoin address contained in a string. * Parse a Bitcoin address contained in a string.
*/ */
Bitcoin.Address.decodeString = function (string, version) { Bitcoin.Address.decodeString = function (string,version) {
var bytes = Bitcoin.Base58.decode(string); var bytes = Bitcoin.Base58.decode(string);
var hash = bytes.slice(0, 21); var hash = bytes.slice(0, 21);
var checksum = Crypto.SHA256(Crypto.SHA256(hash, { var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true });
asBytes: true
}), {
asBytes: true
});
if (checksum[0] != bytes[21] || if (checksum[0] != bytes[21] ||
checksum[1] != bytes[22] || checksum[1] != bytes[22] ||
@ -6067,8 +6045,7 @@
// prevent duplicates from being added to the array // prevent duplicates from being added to the array
for (var index in this.keyArray) { for (var index in this.keyArray) {
var currentItem = this.keyArray[index]; var currentItem = this.keyArray[index];
if (currentItem != null && currentItem.priv != null && item.getBitcoinAddress() == if (currentItem != null && currentItem.priv != null && item.getBitcoinAddress() == currentItem.getBitcoinAddress()) {
currentItem.getBitcoinAddress()) {
doAdd = false; doAdd = false;
break; break;
} }
@ -6100,8 +6077,7 @@
var item = pool[index]; var item = pool[index];
if (Bitcoin.Util.hasMethods(item, 'getBitcoinAddress', 'toString')) { if (Bitcoin.Util.hasMethods(item, 'getBitcoinAddress', 'toString')) {
if (item != null) { if (item != null) {
keyPoolString += "\"" + item.getBitcoinAddress() + "\"" + ", \"" + item keyPoolString += "\"" + item.getBitcoinAddress() + "\"" + ", \"" + item.toString("wif") + "\"\n";
.toString("wif") + "\"\n";
} }
} }
} }
@ -6151,18 +6127,14 @@
this.priv = BigInteger.fromByteArrayUnsigned(input); this.priv = BigInteger.fromByteArrayUnsigned(input);
} else if ("string" == typeof input) { } else if ("string" == typeof input) {
var bytes = null; var bytes = null;
try { try{
// This part is edited for FLO. FLO WIF are always compressed WIF. FLO WIF (private key) starts with R for mainnet and c for testnet. // This part is edited for FLO. FLO WIF are always compressed WIF. FLO WIF (private key) starts with R for mainnet and c for testnet.
if (((floGlobals.blockchain == "FLO") && if(((floGlobals.blockchain == "FLO") && /^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input)) ||
/^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input) ((floGlobals.blockchain == "FLO_TEST") && /^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input))) {
) ||
((floGlobals.blockchain == "FLO_TEST") &&
/^c[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input))
) {
bytes = ECKey.decodeCompressedWalletImportFormat(input); bytes = ECKey.decodeCompressedWalletImportFormat(input);
this.compressed = true; this.compressed = true;
} else if (ECKey.isHexFormat(input)) { }else if (ECKey.isHexFormat(input)) {
bytes = Crypto.util.hexToBytes(input); bytes = Crypto.util.hexToBytes(input);
} }
@ -6198,14 +6170,12 @@
this.compressed = (this.compressed == undefined) ? !!ECKey.compressByDefault : this.compressed; this.compressed = (this.compressed == undefined) ? !!ECKey.compressByDefault : this.compressed;
try { try {
// check not zero // check not zero
if (this.priv != null && BigInteger.ZERO.compareTo(this.priv) == 0) this.setError( if (this.priv != null && BigInteger.ZERO.compareTo(this.priv) == 0) this.setError("Error: BigInteger equal to zero.");
"Error: BigInteger equal to zero.");
// valid range [0x1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140]) // valid range [0x1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140])
var hexKeyRangeLimit = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140"; var hexKeyRangeLimit = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140";
var rangeLimitBytes = Crypto.util.hexToBytes(hexKeyRangeLimit); var rangeLimitBytes = Crypto.util.hexToBytes(hexKeyRangeLimit);
var limitBigInt = BigInteger.fromByteArrayUnsigned(rangeLimitBytes); var limitBigInt = BigInteger.fromByteArrayUnsigned(rangeLimitBytes);
if (this.priv != null && limitBigInt.compareTo(this.priv) < 0) this.setError( if (this.priv != null && limitBigInt.compareTo(this.priv) < 0) this.setError("Error: BigInteger outside of curve range.")
"Error: BigInteger outside of curve range.")
if (this.priv != null) { if (this.priv != null) {
KeyPool.push(this); KeyPool.push(this);
@ -6215,9 +6185,9 @@
} }
}; };
if (floGlobals.blockchain == "FLO") if(floGlobals.blockchain == "FLO")
ECKey.privateKeyPrefix = 0xA3; //(Bitcoin mainnet 0x80 testnet 0xEF) (FLO mainnet 0xA3 163 D) ECKey.privateKeyPrefix = 0xA3; //(Bitcoin mainnet 0x80 testnet 0xEF) (FLO mainnet 0xA3 163 D)
else if (floGlobals.blockchain == "FLO_TEST") else if(floGlobals.blockchain == "FLO_TEST")
ECKey.privateKeyPrefix = 0xEF; //FLO testnet ECKey.privateKeyPrefix = 0xEF; //FLO testnet
/** /**
@ -6319,11 +6289,7 @@
if (bytes == null) return ""; if (bytes == null) return "";
bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte bytes.unshift(ECKey.privateKeyPrefix); // prepend 0x80 byte
if (this.compressed) bytes.push(0x01); // append 0x01 byte for compressed format if (this.compressed) bytes.push(0x01); // append 0x01 byte for compressed format
var checksum = Crypto.SHA256(Crypto.SHA256(bytes, { var checksum = Crypto.SHA256(Crypto.SHA256(bytes, { asBytes: true }), { asBytes: true });
asBytes: true
}), {
asBytes: true
});
bytes = bytes.concat(checksum.slice(0, 4)); bytes = bytes.concat(checksum.slice(0, 4));
var privWif = Bitcoin.Base58.encode(bytes); var privWif = Bitcoin.Base58.encode(bytes);
return privWif; return privWif;
@ -6356,7 +6322,8 @@
// Wallet Import Format // Wallet Import Format
else if (format.toString().toLowerCase() == "wif") { else if (format.toString().toLowerCase() == "wif") {
return this.getBitcoinWalletImportFormat(); return this.getBitcoinWalletImportFormat();
} else { }
else {
return this.getBitcoinHexFormat(); return this.getBitcoinHexFormat();
} }
}; };
@ -6375,11 +6342,7 @@
ECKey.decodeWalletImportFormat = function (privStr) { ECKey.decodeWalletImportFormat = function (privStr) {
var bytes = Bitcoin.Base58.decode(privStr); var bytes = Bitcoin.Base58.decode(privStr);
var hash = bytes.slice(0, 33); var hash = bytes.slice(0, 33);
var checksum = Crypto.SHA256(Crypto.SHA256(hash, { var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true });
asBytes: true
}), {
asBytes: true
});
if (checksum[0] != bytes[33] || if (checksum[0] != bytes[33] ||
checksum[1] != bytes[34] || checksum[1] != bytes[34] ||
checksum[2] != bytes[35] || checksum[2] != bytes[35] ||
@ -6400,11 +6363,7 @@
ECKey.decodeCompressedWalletImportFormat = function (privStr) { ECKey.decodeCompressedWalletImportFormat = function (privStr) {
var bytes = Bitcoin.Base58.decode(privStr); var bytes = Bitcoin.Base58.decode(privStr);
var hash = bytes.slice(0, 34); var hash = bytes.slice(0, 34);
var checksum = Crypto.SHA256(Crypto.SHA256(hash, { var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true });
asBytes: true
}), {
asBytes: true
});
if (checksum[0] != bytes[34] || if (checksum[0] != bytes[34] ||
checksum[1] != bytes[35] || checksum[1] != bytes[35] ||
checksum[2] != bytes[36] || checksum[2] != bytes[36] ||
@ -6456,18 +6415,12 @@
// 22, 26 or 30 characters, always starts with an 'S' // 22, 26 or 30 characters, always starts with an 'S'
ECKey.isMiniFormat = function (key) { ECKey.isMiniFormat = function (key) {
key = key.toString(); key = key.toString();
var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test( var validChars22 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{21}$/.test(key);
key); var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test(key);
var validChars26 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{25}$/.test( var validChars30 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{29}$/.test(key);
key); var testBytes = Crypto.SHA256(key + "?", { asBytes: true });
var validChars30 = /^S[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{29}$/.test(
key);
var testBytes = Crypto.SHA256(key + "?", {
asBytes: true
});
return ((testBytes[0] === 0x00 || testBytes[0] === 0x01) && (validChars22 || validChars26 || return ((testBytes[0] === 0x00 || testBytes[0] === 0x01) && (validChars22 || validChars26 || validChars30));
validChars30));
}; };
return ECKey; return ECKey;
@ -6570,26 +6523,17 @@
* array. * array.
*/ */
sha256ripe160: function (data) { sha256ripe160: function (data) {
return ripemd160(Crypto.SHA256(data, { return ripemd160(Crypto.SHA256(data, { asBytes: true }), { asBytes: true });
asBytes: true
}), {
asBytes: true
});
}, },
// double sha256 // double sha256
dsha256: function (data) { dsha256: function (data) {
return Crypto.SHA256(Crypto.SHA256(data, { return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true });
asBytes: true
}), {
asBytes: true
});
}, },
// duck typing method // duck typing method
hasMethods: function (obj /*, method list as strings */ ) { hasMethods: function(obj /*, method list as strings */){
var i = 1, var i = 1, methodName;
methodName; while((methodName = arguments[i++])){
while ((methodName = arguments[i++])) { if(typeof obj[methodName] != 'function') {
if (typeof obj[methodName] != 'function') {
return false; return false;
} }
} }
@ -6989,8 +6933,7 @@
warn(); warn();
} }
secret = '1' + hex2bin( secret = '1' + hex2bin(secret); // append a 1 so that we can preserve the correct number of leading zeros in our secret
secret); // append a 1 so that we can preserve the correct number of leading zeros in our secret
secret = split(secret, padLength); secret = split(secret, padLength);
var x = new Array(numShares), var x = new Array(numShares),
y = new Array(numShares); y = new Array(numShares);
@ -7184,20 +7127,15 @@
if (i === j) { if (i === j) {
continue; continue;
} }
if (at === x[ if (at === x[j]) { // happens when computing a share that is in the list of shares used to compute it
j]) { // happens when computing a share that is in the list of shares used to compute it product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
product = -
1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
break; break;
} }
product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max /* to make sure it's not negative */ ) %
.max /* to make sure it's not negative */ ) %
config.max; config.max;
} }
sum = product === -1 ? sum : sum ^ config.exps[ sum = product === -1 ? sum : sum ^ config.exps[product]; // though exps[-1]= undefined and undefined ^ anything = anything in chrome, this behavior may not hold everywhere, so do the check
product
]; // though exps[-1]= undefined and undefined ^ anything = anything in chrome, this behavior may not hold everywhere, so do the check
} }
return sum; return sum;
}; };
@ -7268,8 +7206,7 @@
if (typeof bytesPerChar !== 'number' || bytesPerChar % 1 !== 0 || bytesPerChar < 1 || if (typeof bytesPerChar !== 'number' || bytesPerChar % 1 !== 0 || bytesPerChar < 1 ||
bytesPerChar > defaults.maxBytesPerChar) { bytesPerChar > defaults.maxBytesPerChar) {
throw new Error('Bytes per character must be an integer between 1 and ' + defaults throw new Error('Bytes per character must be an integer between 1 and ' + defaults.maxBytesPerChar +
.maxBytesPerChar +
', inclusive.') ', inclusive.')
} }
@ -7303,8 +7240,7 @@
if (typeof bytesPerChar !== 'number' || bytesPerChar % 1 !== 0 || bytesPerChar < 1 || if (typeof bytesPerChar !== 'number' || bytesPerChar % 1 !== 0 || bytesPerChar < 1 ||
bytesPerChar > defaults.maxBytesPerChar) { bytesPerChar > defaults.maxBytesPerChar) {
throw new Error('Bytes per character must be an integer between 1 and ' + defaults throw new Error('Bytes per character must be an integer between 1 and ' + defaults.maxBytesPerChar +
.maxBytesPerChar +
', inclusive.') ', inclusive.')
} }
@ -7332,13 +7268,11 @@
findDifference(original, updatedObj) returns an object with the added, deleted and updated differences findDifference(original, updatedObj) returns an object with the added, deleted and updated differences
mergeRecurcive(original, diff) this will get you a new object that will merge all the changes between the old object and the new object mergeRecurcive(original, diff) this will get you a new object that will merge all the changes between the old object and the new object
*/ */
(function () { (function(){
const isDate = d => d instanceof Date; const isDate = d => d instanceof Date;
const isEmpty = o => Object.keys(o).length === 0; const isEmpty = o => Object.keys(o).length === 0;
const isObject = o => o != null && typeof o === 'object'; const isObject = o => o != null && typeof o === 'object';
const properObject = o => isObject(o) && !o.hasOwnProperty ? { const properObject = o => isObject(o) && !o.hasOwnProperty ? { ...o } : o;
...o
} : o;
const getLargerArray = (l, r) => l.length > r.length ? l : r; const getLargerArray = (l, r) => l.length > r.length ? l : r;
@ -7358,9 +7292,7 @@
...acc, ...acc,
[key]: array.reduce((acc2, item, index) => { [key]: array.reduce((acc2, item, index) => {
if (diff[key].hasOwnProperty(index)) { if (diff[key].hasOwnProperty(index)) {
acc2[index] = preserve(diff[key][index], leftArray[index], acc2[index] = preserve(diff[key][index], leftArray[index], rightArray[index]); // diff recurse and check for nested arrays
rightArray[index]
); // diff recurse and check for nested arrays
return acc2; return acc2;
} }
@ -7399,10 +7331,7 @@
if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc;
return { return { ...acc, [key]: difference };
...acc,
[key]: difference
};
} }
return acc; return acc;
@ -7419,10 +7348,7 @@
const r = properObject(rhs); const r = properObject(rhs);
const deletedValues = Object.keys(l).reduce((acc, key) => { const deletedValues = Object.keys(l).reduce((acc, key) => {
return r.hasOwnProperty(key) ? acc : { return r.hasOwnProperty(key) ? acc : { ...acc, [key]: null };
...acc,
[key]: null
};
}, {}); }, {});
if (isDate(l) || isDate(r)) { if (isDate(l) || isDate(r)) {
@ -7431,20 +7357,13 @@
} }
return Object.keys(r).reduce((acc, key) => { return Object.keys(r).reduce((acc, key) => {
if (!l.hasOwnProperty(key)) return { if (!l.hasOwnProperty(key)) return { ...acc, [key]: r[key] }; // return added r key
...acc,
[key]: r[key]
}; // return added r key
const difference = diff(l[key], r[key]); const difference = diff(l[key], r[key]);
if (isObject(difference) && isEmpty(difference) && !isDate(difference)) if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff
return acc; // return no diff
return { return { ...acc, [key]: difference }; // return updated key
...acc,
[key]: difference
}; // return updated key
}, deletedValues); }, deletedValues);
}; };
@ -7461,16 +7380,10 @@
if (isObject(difference) && isEmpty(difference)) return acc; if (isObject(difference) && isEmpty(difference)) return acc;
return { return { ...acc, [key]: difference };
...acc,
[key]: difference
};
} }
return { return { ...acc, [key]: r[key] };
...acc,
[key]: r[key]
};
}, {}); }, {});
}; };
@ -7484,10 +7397,7 @@
const r = properObject(rhs); const r = properObject(rhs);
const deletedValues = Object.keys(l).reduce((acc, key) => { const deletedValues = Object.keys(l).reduce((acc, key) => {
return r.hasOwnProperty(key) ? acc : { return r.hasOwnProperty(key) ? acc : { ...acc, [key]: null };
...acc,
[key]: null
};
}, {}); }, {});
if (isDate(l) || isDate(r)) { if (isDate(l) || isDate(r)) {
@ -7513,26 +7423,18 @@
return acc; // return no diff return acc; // return no diff
} }
return acc.slice(0, index).concat(rightItem).concat(acc.slice(index + return acc.slice(0, index).concat(rightItem).concat(acc.slice(index + 1)); // return updated key
1)); // return updated key
}, deletedValues); }, deletedValues);
} }
return Object.keys(r).reduce((acc, key) => { return Object.keys(r).reduce((acc, key) => {
if (!l.hasOwnProperty(key)) return { if (!l.hasOwnProperty(key)) return { ...acc, [key]: r[key] }; // return added r key
...acc,
[key]: r[key]
}; // return added r key
const difference = diff(l[key], r[key]); const difference = diff(l[key], r[key]);
if (isObject(difference) && isEmpty(difference) && !isDate(difference)) if (isObject(difference) && isEmpty(difference) && !isDate(difference)) return acc; // return no diff
return acc; // return no diff
return { return { ...acc, [key]: difference }; // return updated key
...acc,
[key]: difference
}; // return updated key
}, deletedValues); }, deletedValues);
}; };
@ -7548,16 +7450,10 @@
if (isObject(difference) && isEmpty(difference)) return acc; if (isObject(difference) && isEmpty(difference)) return acc;
return { return { ...acc, [key]: difference };
...acc,
[key]: difference
};
} }
return { return { ...acc, [key]: null };
...acc,
[key]: null
};
}, {}); }, {});
}; };
@ -7570,7 +7466,7 @@
const mergeRecursive = (obj1, obj2) => { const mergeRecursive = (obj1, obj2) => {
for (var p in obj2) { for (var p in obj2) {
try { try {
if (obj2[p].constructor == Object) { if(obj2[p].constructor == Object) {
obj1[p] = mergeRecursive(obj1[p], obj2[p]); obj1[p] = mergeRecursive(obj1[p], obj2[p]);
} }
// Property in destination object set; update its value. // Property in destination object set; update its value.
@ -7578,11 +7474,12 @@
// obj1[p] = []; // obj1[p] = [];
if (obj2[p].length < 1) { if (obj2[p].length < 1) {
obj1[p] = obj2[p]; obj1[p] = obj2[p];
} else { }
else {
obj1[p] = mergeRecursive(obj1[p], obj2[p]); obj1[p] = mergeRecursive(obj1[p], obj2[p]);
} }
} else { }else{
obj1[p] = obj2[p]; obj1[p] = obj2[p];
} }
} catch (e) { } catch (e) {
@ -7616,32 +7513,31 @@
if (!Object.keys(value).length) { if (!Object.keys(value).length) {
delete obj[key] delete obj[key]
} }
} else if (value === null) { }
else if (value === null) {
// null, remove it // null, remove it
delete obj[key]; delete obj[key];
} }
}); });
if (obj.constructor.toString().indexOf("Array") != -1) { if(obj.constructor.toString().indexOf("Array") != -1) {obj = obj.filter(function (el) {
obj = obj.filter(function (el) {
return el != null; return el != null;
}); });}
}
return obj; return obj;
} }
/*obj is original object or array, diff is the output of findDifference */ /*obj is original object or array, diff is the output of findDifference */
window.mergeDifference = (obj, diff) => { window.mergeDifference = (obj,diff) => {
if (Object.keys(diff.updated).length !== 0) if(Object.keys(diff.updated).length !== 0)
obj = mergeRecursive(obj, diff.updated) obj = mergeRecursive(obj,diff.updated)
if (Object.keys(diff.deleted).length !== 0) { if(Object.keys(diff.deleted).length !== 0){
obj = mergeRecursive(obj, diff.deleted) obj = mergeRecursive(obj,diff.deleted)
obj = cleanse(obj) obj = cleanse(obj)
} }
if (Object.keys(diff.added).length !== 0) if(Object.keys(diff.added).length !== 0)
obj = mergeRecursive(obj, diff.added) obj = mergeRecursive(obj,diff.added)
return obj return obj
} }
})(); })();
@ -7847,7 +7743,7 @@
//Returns public-key from private-key //Returns public-key from private-key
getPubKeyHex: function (privateKeyHex) { getPubKeyHex: function (privateKeyHex) {
if (!privateKeyHex) if(!privateKeyHex)
return null; return null;
var key = new Bitcoin.ECKey(privateKeyHex); var key = new Bitcoin.ECKey(privateKeyHex);
if (key.priv == null) if (key.priv == null)
@ -8030,7 +7926,7 @@
var change = utxoAmt - sendAmt - fee; var change = utxoAmt - sendAmt - fee;
if (change > 0) if (change > 0)
trx.addoutput(senderAddr, change); trx.addoutput(senderAddr, change);
trx.addflodata(floData.replace(/\n/g, ' ')); trx.addflodata(floData.replace(/\n/g,' '));
var signedTxHash = trx.sign(privKey, 1); var signedTxHash = trx.sign(privKey, 1);
this.broadcastTx(signedTxHash) this.broadcastTx(signedTxHash)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
@ -8061,7 +7957,7 @@
} }
} }
trx.addoutput(floID, utxoAmt - fee); trx.addoutput(floID, utxoAmt - fee);
trx.addflodata(floData.replace(/\n/g, ' ')); trx.addflodata(floData.replace(/\n/g,' '));
var signedTxHash = trx.sign(privKey, 1); var signedTxHash = trx.sign(privKey, 1);
this.broadcastTx(signedTxHash) this.broadcastTx(signedTxHash)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
@ -8077,11 +7973,11 @@
* @param {boolean} preserveRatio (optional) preserve ratio or equal contribution * @param {boolean} preserveRatio (optional) preserve ratio or equal contribution
* @return {Promise} * @return {Promise}
*/ */
writeDataMultiple: function (senderPrivKeys, data, receivers = [floGlobals.adminID], preserveRatio = true) { writeDataMultiple: function (senderPrivKeys, data, receivers = [floGlobals.adminID], preserveRatio = true){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!Array.isArray(senderPrivKeys)) if (!Array.isArray(senderPrivKeys))
return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array") return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array")
if (!preserveRatio) { if(!preserveRatio){
let tmp = {}; let tmp = {};
let amount = (floGlobals.sendAmt * receivers.length) / senderPrivKeys.length; let amount = (floGlobals.sendAmt * receivers.length) / senderPrivKeys.length;
senderPrivKeys.forEach(key => tmp[key] = amount); senderPrivKeys.forEach(key => tmp[key] = amount);
@ -8112,58 +8008,53 @@
sendTxMultiple: function (senderPrivKeys, receivers, floData = '') { sendTxMultiple: function (senderPrivKeys, receivers, floData = '') {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let senders = {}, let senders = {}, preserveRatio;
preserveRatio;
//check for argument validations //check for argument validations
try { try{
let invalids = { let invalids = {
InvalidSenderPrivKeys: [], InvalidSenderPrivKeys: [],
InvalidSenderAmountFor: [], InvalidSenderAmountFor: [],
InvalidReceiverIDs: [], InvalidReceiverIDs: [],
InvalidReceiveAmountFor: [] InvalidReceiveAmountFor: []
} }
let inputVal = 0, let inputVal = 0, outputVal = 0;
outputVal = 0;
//Validate sender privatekeys (and send amount if passed) //Validate sender privatekeys (and send amount if passed)
//conversion when only privateKeys are passed (preserveRatio mode) //conversion when only privateKeys are passed (preserveRatio mode)
if (Array.isArray(senderPrivKeys)) { if(Array.isArray(senderPrivKeys)){
senderPrivKeys.forEach(key => { senderPrivKeys.forEach(key => {
try { try{
if (!key) if(!key)
invalids.InvalidSenderPrivKeys.push(key); invalids.InvalidSenderPrivKeys.push(key);
else { else{
let floID = floCrypto.getFloIDfromPubkeyHex(floCrypto let floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(key));
.getPubKeyHex(key));
senders[floID] = { senders[floID] = {
wif: key wif: key
} }
} }
} catch (error) { }catch(error){
invalids.InvalidSenderPrivKeys.push(key) invalids.InvalidSenderPrivKeys.push(key)
} }
}) })
preserveRatio = true; preserveRatio = true;
} }
//conversion when privatekeys are passed with send amount //conversion when privatekeys are passed with send amount
else { else{
for (let key in senderPrivKeys) { for(let key in senderPrivKeys){
try { try{
if (!key) if(!key)
invalids.InvalidSenderPrivKeys.push(key); invalids.InvalidSenderPrivKeys.push(key);
else { else{
if (typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[key] <= if(typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[key] <= 0)
0)
invalids.InvalidSenderAmountFor.push(key) invalids.InvalidSenderAmountFor.push(key)
else else
inputVal += senderPrivKeys[key]; inputVal += senderPrivKeys[key];
let floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex( let floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.getPubKeyHex(key));
key));
senders[floID] = { senders[floID] = {
wif: key, wif: key,
coins: senderPrivKeys[key] coins: senderPrivKeys[key]
} }
} }
} catch (error) { }catch(error){
invalids.InvalidSenderPrivKeys.push(key) invalids.InvalidSenderPrivKeys.push(key)
} }
} }
@ -8185,10 +8076,9 @@
if (Object.keys(invalids).length) if (Object.keys(invalids).length)
return reject(invalids); return reject(invalids);
//Reject if given inputVal and outputVal are not equal //Reject if given inputVal and outputVal are not equal
if (!preserveRatio && inputVal != outputVal) if(!preserveRatio && inputVal != outputVal)
return reject( return reject(`Input Amount (${inputVal}) not equal to Output Amount (${outputVal})`)
`Input Amount (${inputVal}) not equal to Output Amount (${outputVal})`) }catch(error){
} catch (error) {
return reject(error) return reject(error)
} }
//Get balance of senders //Get balance of senders
@ -8200,22 +8090,18 @@
totalFee = floGlobals.fee, totalFee = floGlobals.fee,
balance = {}; balance = {};
//Divide fee among sender if not for preserveRatio //Divide fee among sender if not for preserveRatio
if (!preserveRatio) if(!preserveRatio)
var dividedFee = totalFee / Object.keys(senders).length; var dividedFee = totalFee / Object.keys(senders).length;
//Check if balance of each sender is sufficient enough //Check if balance of each sender is sufficient enough
let insufficient = []; let insufficient = [];
for (let floID in senders) { for (let floID in senders) {
balance[floID] = parseFloat(results.shift()); balance[floID] = parseFloat(results.shift());
if (isNaN(balance[floID]) || (preserveRatio && balance[floID] <= if (isNaN(balance[floID]) || (preserveRatio && balance[floID] <= totalFee) || (!preserveRatio && balance[floID] < senders[floID].coins + dividedFee))
totalFee) || (!preserveRatio && balance[floID] < senders[floID]
.coins + dividedFee))
insufficient.push(floID) insufficient.push(floID)
totalBalance += balance[floID]; totalBalance += balance[floID];
} }
if (insufficient.length) if (insufficient.length)
return reject({ return reject({InsufficientBalance: insufficient})
InsufficientBalance: insufficient
})
//Calculate totalSentAmount and check if totalBalance is sufficient //Calculate totalSentAmount and check if totalBalance is sufficient
let totalSendAmt = totalFee; let totalSendAmt = totalFee;
for (floID in receivers) for (floID in receivers)
@ -8232,7 +8118,7 @@
for (floID in senders) { for (floID in senders) {
let utxos = results.shift(); let utxos = results.shift();
let sendAmt; let sendAmt;
if (preserveRatio) { if(preserveRatio){
let ratio = (balance[floID] / totalBalance); let ratio = (balance[floID] / totalBalance);
sendAmt = totalSendAmt * ratio; sendAmt = totalSendAmt * ratio;
} else } else
@ -8256,7 +8142,7 @@
} }
for (floID in receivers) for (floID in receivers)
trx.addoutput(floID, receivers[floID]); trx.addoutput(floID, receivers[floID]);
trx.addflodata(floData.replace(/\n/g, ' ')); trx.addflodata(floData.replace(/\n/g,' '));
for (let i = 0; i < wifSeq.length; i++) for (let i = 0; i < wifSeq.length; i++)
trx.signinput(i, wifSeq[i], 1); trx.signinput(i, wifSeq[i], 1);
var signedTxHash = trx.serialize(); var signedTxHash = trx.serialize();
@ -8328,7 +8214,7 @@
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => {
var newItems = response.totalItems - options.ignoreOld; var newItems = response.totalItems - options.ignoreOld;
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems * 2}`).then( this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(
response => { response => {
if (options.limit <= 0) if (options.limit <= 0)
options.limit = response.items.length; options.limit = response.items.length;
@ -9027,7 +8913,8 @@
idb.onupgradeneeded = (event) => { idb.onupgradeneeded = (event) => {
var db = event.target.result; var db = event.target.result;
for (let obs in objectStores) { for (let obs in objectStores) {
var objectStore = db.createObjectStore(obs, objectStores[obs].options || {}); var objectStore = db.createObjectStore(obs, objectStores[obs].options ||
{});
if (objectStores[obs].indexes && typeof objectStores[obs].indexes === if (objectStores[obs].indexes && typeof objectStores[obs].indexes ===
'object') 'object')
for (let i in objectStores[obs].indexes) for (let i in objectStores[obs].indexes)
@ -9603,16 +9490,16 @@
}) })
} }
const checkIfPinRequired = function (key) { const checkIfPinRequired = function(key){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (key.length == 52) if(key.length == 52)
resolve(key) resolve(key)
else { else {
inputFn("PIN/Password").then(pwd => { inputFn("PIN/Password").then(pwd => {
try { try{
let privKey = Crypto.AES.decrypt(key, pwd); let privKey = Crypto.AES.decrypt(key, pwd);
resolve(privKey) resolve(privKey)
} catch (error) { }catch(error){
reject("Access Denied: Incorrect PIN/Password") reject("Access Denied: Incorrect PIN/Password")
} }
}).catch(error => reject("Access Denied: PIN/Password required")) }).catch(error => reject("Access Denied: PIN/Password required"))
@ -9623,12 +9510,12 @@
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
getPrivateKeyCredentials().then(key => { getPrivateKeyCredentials().then(key => {
checkIfPinRequired(key).then(privKey => { checkIfPinRequired(key).then(privKey => {
try { try{
myPrivKey = privKey myPrivKey = privKey
myPubKey = floCrypto.getPubKeyHex(myPrivKey) myPubKey = floCrypto.getPubKeyHex(myPrivKey)
myFloID = floCrypto.getFloIDfromPubkeyHex(myPubKey) myFloID = floCrypto.getFloIDfromPubkeyHex(myPubKey)
resolve('Login Credentials loaded successful') resolve('Login Credentials loaded successful')
} catch (error) { }catch(error){
reject("Corrupted Private Key") reject("Corrupted Private Key")
} }
}).catch(error => reject(error)) }).catch(error => reject(error))
@ -9727,19 +9614,18 @@
}) })
}, },
securePrivKey: function (pwd) { securePrivKey: function(pwd){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let indexArr = localStorage.getItem(`${floGlobals.application}#privKey`) let indexArr = localStorage.getItem(`${floGlobals.application}#privKey`)
if (!indexArr) if(!indexArr)
return reject("PrivKey not found"); return reject("PrivKey not found");
indexArr = JSON.parse(indexArr) indexArr = JSON.parse(indexArr)
let encryptedKey = Crypto.AES.encrypt(myPrivKey, pwd); let encryptedKey = Crypto.AES.encrypt(myPrivKey, pwd);
let threshold = indexArr.length; let threshold = indexArr.length;
let shares = floCrypto.createShamirsSecretShares(encryptedKey, threshold, threshold) let shares = floCrypto.createShamirsSecretShares(encryptedKey, threshold, threshold)
let promises = []; let promises = [];
for (var i = 0; i < threshold; i++) for(var i=0; i<threshold;i++)
promises.push(compactIDB.writeData("credentials", shares[i], indexArr[i], floGlobals promises.push(compactIDB.writeData("credentials", shares[i], indexArr[i], floGlobals.application));
.application));
Promise.all(promises) Promise.all(promises)
.then(results => resolve("Private Key Secured")) .then(results => resolve("Private Key Secured"))
.catch(error => reject(error)) .catch(error => reject(error))