Fixed: floData with 16 char didnot sent on testnet

Adjusted max floData size to 1040
This commit is contained in:
Vivek Teega 2020-09-11 18:13:49 +05:30
parent 7e470d520f
commit e61be9f594
3 changed files with 11234 additions and 11149 deletions

File diff suppressed because one or more lines are too long

View File

@ -165,7 +165,7 @@
color: var(--accent-color); color: var(--accent-color);
} }
.text-area textarea{ .text-area textarea {
resize: none; resize: none;
} }
@ -193,11 +193,11 @@
transition: border 0.2s ease; transition: border 0.2s ease;
} }
textarea{ textarea {
margin-bottom: 2rem; margin-bottom: 2rem;
} }
#show_character_count{ #show_character_count {
position: absolute; position: absolute;
bottom: 0; bottom: 0;
right: 0; right: 0;
@ -1799,7 +1799,8 @@
</svg> </svg>
<span></span> <span></span>
</div> </div>
<div class="icons tabs activeButton" title='Generate or recover FLO address' id="addrGenBtn" onclick="showPage(this.id, 'addrGen')"> <div class="icons tabs activeButton" title='Generate or recover FLO address' id="addrGenBtn"
onclick="showPage(this.id, 'addrGen')">
<svg role="img" viewBox="0 0 20 16"> <svg role="img" viewBox="0 0 20 16">
<g> <g>
<circle cx="9" cy="9" r="3" /> <circle cx="9" cy="9" r="3" />
@ -1816,14 +1817,14 @@
<svg role="img" viewBox="0 0 20 16"> <svg role="img" viewBox="0 0 20 16">
<g> <g>
<path d="M0.3,9.1l6.2,2.2c0.2,0.1,0.4,0,0.5-0.1L19.1,0L0.3,8.2C-0.1,8.4-0.1,9,0.3,9.1z" /> <path d="M0.3,9.1l6.2,2.2c0.2,0.1,0.4,0,0.5-0.1L19.1,0L0.3,8.2C-0.1,8.4-0.1,9,0.3,9.1z" />
<path d="M10,18.8l-2.2-6.2c-0.1-0.2,0-0.4,0.1-0.5L19.1,0l-8.2,18.8C10.7,19.2,10.1,19.2,10,18.8z" /> <path
d="M10,18.8l-2.2-6.2c-0.1-0.2,0-0.4,0.1-0.5L19.1,0l-8.2,18.8C10.7,19.2,10.1,19.2,10,18.8z" />
</g> </g>
</svg> </svg>
<h6>Send</h6> <h6>Send</h6>
<span>Send FLO data</span> <span>Send FLO data</span>
</div> </div>
<div class="icons tabs" title='Monitor FLO data' id="getDataBtn" <div class="icons tabs" title='Monitor FLO data' id="getDataBtn" onclick="showPage(this.id, 'getData')">
onclick="showPage(this.id, 'getData')">
<svg role="img" viewBox="0 0 20 16"> <svg role="img" viewBox="0 0 20 16">
<path d="M18,0H2C0.9,0,0,0.9,0,2v14c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V2C20,0.9,19.1,0,18,0z M16.4,6.9l-4.2,4.2 <path d="M18,0H2C0.9,0,0,0.9,0,2v14c0,1.1,0.9,2,2,2h16c1.1,0,2-0.9,2-2V2C20,0.9,19.1,0,18,0z M16.4,6.9l-4.2,4.2
c-0.4,0.4-1,0.4-1.4,0L8.6,9l-3.5,3.5c-0.4,0.4-1,0.4-1.4,0c-0.4-0.4-0.4-1,0-1.4l4.2-4.2c0.4-0.4,1-0.4,1.4,0L11.4,9l3.5-3.5 c-0.4,0.4-1,0.4-1.4,0L8.6,9l-3.5,3.5c-0.4,0.4-1,0.4-1.4,0c-0.4-0.4-0.4-1,0-1.4l4.2-4.2c0.4-0.4,1-0.4,1.4,0L11.4,9l3.5-3.5
@ -1861,8 +1862,9 @@
<label>FLO Address</label> <label>FLO Address</label>
</div> </div>
<div class="input"> <div class="input">
<input autocomplete="off" aria-label="Label" type="text" onfocus="animateInput(this.parentNode)" <input autocomplete="off" aria-label="Label" type="text"
onblur="revertBack(this.parentNode)" id="addrLabel" /> onfocus="animateInput(this.parentNode)" onblur="revertBack(this.parentNode)"
id="addrLabel" />
<label>Label</label> <label>Label</label>
</div> </div>
<button onclick="closeAdd()">Cancel</button> <button onclick="closeAdd()">Cancel</button>
@ -1963,9 +1965,9 @@
<h5>To send FLO data, make sure you have enough balance.</h5> <h5>To send FLO data, make sure you have enough balance.</h5>
</div> </div>
<div class="input"> <div class="input">
<input autocomplete="off" aria-label="FLO address" <input autocomplete="off" aria-label="FLO address" onfocus="animateInput(this.parentNode)"
onfocus="animateInput(this.parentNode)" onblur="revertBack(this.parentNode)" type="text" onblur="revertBack(this.parentNode)" type="text" id="getBal_addr"
id="getBal_addr" oninput="checkBalAddress(this)" /> oninput="checkBalAddress(this)" />
<label>FLO address</label> <label>FLO address</label>
<button id="getBal_btn" onclick="getBal()" disabled>Check balance</button> <button id="getBal_btn" onclick="getBal()" disabled>Check balance</button>
</div> </div>
@ -2109,9 +2111,8 @@
<h4>Recover FLO address</h4> <h4>Recover FLO address</h4>
<h5>Please enter your private key.</h5> <h5>Please enter your private key.</h5>
<div class="input"> <div class="input">
<input autocomplete="off" aria-label="Private key" type="text" <input autocomplete="off" aria-label="Private key" type="text" onfocus="animateInput(this.parentNode)"
onfocus="animateInput(this.parentNode)" onblur="revertBack(this.parentNode)" id="pop" onblur="revertBack(this.parentNode)" id="pop" oninput="checkPrivateKey(this)" />
oninput="checkPrivateKey(this)" />
<label>Private key</label> <label>Private key</label>
</div> </div>
<button onclick="fadeout()">Cancel</button> <button onclick="fadeout()">Cancel</button>
@ -2446,7 +2447,7 @@
floatPart = parts[1], floatPart = parts[1],
intPart = parts[0]; intPart = parts[0];
intPartText.textContent = intPart; intPartText.textContent = intPart;
if(floatPart) if (floatPart)
floatPartText.textContent = `.${floatPart}`; floatPartText.textContent = `.${floatPart}`;
document.getElementById('sdright').setAttribute('style', 'pointer-events: all; opacity: 1') document.getElementById('sdright').setAttribute('style', 'pointer-events: all; opacity: 1')
loading.classList.remove('show', 'spin'); loading.classList.remove('show', 'spin');
@ -2797,8 +2798,8 @@
} }
let showCharacterCount = document.getElementById('show_character_count') let showCharacterCount = document.getElementById('show_character_count')
document.getElementById('flotextdata').addEventListener('input', function(){ document.getElementById('flotextdata').addEventListener('input', function () {
if(1040 - this.value.length){ if (1040 - this.value.length) {
showCharacterCount.textContent = `${1040 - this.value.length}/1040` showCharacterCount.textContent = `${1040 - this.value.length}/1040`
} }
else else
@ -2806,7 +2807,7 @@
}) })
</script> </script>
<script> <script>
//All util libraries required for Standard operations (DO NOT EDIT ANY) //All util libraries required for Standard operations (DO NOT EDIT ANY)
/*! /*!
@ -3474,7 +3475,7 @@
entropyStr += window.location; entropyStr += window.location;
var entropyBytes = Crypto.SHA256(entropyStr, { asBytes: true }); var entropyBytes = Crypto.SHA256(entropyStr, { 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]);
} }
} }
@ -5176,7 +5177,7 @@
// A "null" reducer // A "null" reducer
var NullExp = window.NullExp = function NullExp() {} var NullExp = window.NullExp = function NullExp() { }
NullExp.prototype.convert = function (x) { NullExp.prototype.convert = function (x) {
return x; return x;
}; };
@ -5267,7 +5268,7 @@
(function () { (function () {
// Constructor function of Global EllipticCurve object // Constructor function of Global EllipticCurve object
var ec = window.EllipticCurve = function () {}; var ec = window.EllipticCurve = function () { };
// ---------------- // ----------------
// ECFieldElementFp constructor // ECFieldElementFp constructor
@ -5946,7 +5947,7 @@
//bitTrx.js //bitTrx.js
(function () { (function () {
var bitjs = window.bitjs = function () {}; var bitjs = window.bitjs = function () { };
/* public vars */ /* public vars */
bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23 bitjs.pub = 0x23; // flochange - changed the prefix to FLO Mainnet PublicKey Prefix 0x23
@ -6382,26 +6383,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 <= 1040) { } else if (floDataCount <= 1040) {
floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd"); floDataCountAdjusted = (floDataCount - 253) + parseInt("0xfd00fd");
floDataCountStringAdjusted = floDataCountAdjusted.toString(16); floDataCountStringAdjusted = floDataCountAdjusted.toString(16);
floDataCountString = floDataCountStringAdjusted.substr(0,2)+ floDataCountStringAdjusted.substr(4,2)+ floDataCountStringAdjusted.substr(2,2); floDataCountString = floDataCountStringAdjusted.substr(0, 2) + floDataCountStringAdjusted.substr(4, 2) + floDataCountStringAdjusted.substr(2, 2);
} else { } else {
floDataCountString = "Character Limit Exceeded"; floDataCountString = "Character Limit Exceeded";
} }
return Crypto.util.bytesToHex(buffer)+floDataCountString+flohex; // flochange -- Addition of floDataCountString and floData in serialization return Crypto.util.bytesToHex(buffer) + floDataCountString + flohex; // flochange -- Addition of floDataCountString and floData in serialization
} }
@ -6621,12 +6622,12 @@
); );
//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;
}; };
@ -6656,7 +6657,7 @@
/** /**
* 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, { asBytes: true }), { asBytes: true }); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes: true }), { asBytes: true });
@ -6956,7 +6957,7 @@
if (pubkey.getBitcoinAddress().toString() == address) { if (pubkey.getBitcoinAddress().toString() == address) {
return i; return i;
} }
} catch (e) {} } catch (e) { }
} }
throw "Unable to find valid recovery factor"; throw "Unable to find valid recovery factor";
} }
@ -7056,14 +7057,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") && /^R[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{51}$/.test(input)) || if (((floGlobals.blockchain == "FLO") && /^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);
} }
@ -7114,9 +7115,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
/** /**
@ -7459,10 +7460,10 @@
return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true }); return Crypto.SHA256(Crypto.SHA256(data, { 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, methodName; var i = 1, methodName;
while((methodName = arguments[i++])){ while ((methodName = arguments[i++])) {
if(typeof obj[methodName] != 'function') { if (typeof obj[methodName] != 'function') {
return false; return false;
} }
} }
@ -7916,7 +7917,7 @@
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.max /* to make sure it's not negative */ ) % product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max /* to make sure it's not negative */) %
config.max; config.max;
} }
@ -8042,7 +8043,7 @@
exports.init(); exports.init();
})(typeof module !== 'undefined' && module['exports'] ? module['exports'] : (window['shamirSecretShare'] = {}), })(typeof module !== 'undefined' && module['exports'] ? module['exports'] : (window['shamirSecretShare'] = {}),
typeof global !== 'undefined' ? global : window); typeof global !== 'undefined' ? global : window);
</script> </script>
<script> <script>
/* FLO Crypto Operators*/ /* FLO Crypto Operators*/
@ -8064,7 +8065,7 @@
}, },
//generate a random Interger within range //generate a random Interger within range
randInt: function(min, max) { randInt: function (min, max) {
min = Math.ceil(min); min = Math.ceil(min);
max = Math.floor(max); max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; return Math.floor(Math.random() * (max - min + 1)) + min;
@ -8073,11 +8074,11 @@
//generate a random String within length (options : alphaNumeric chars only) //generate a random String within length (options : alphaNumeric chars only)
randString: function (length, alphaNumeric = false) { randString: function (length, alphaNumeric = false) {
var result = ''; var result = '';
if(alphaNumeric) if (alphaNumeric)
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
else else
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():'; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():';
for ( var i = 0; i < length; i++ ) for (var i = 0; i < length; i++)
result += characters.charAt(Math.floor(Math.random() * characters.length)); result += characters.charAt(Math.floor(Math.random() * characters.length));
return result; return result;
}, },
@ -8292,14 +8293,14 @@
}, },
createShamirsSecretShares: function (str, total_shares, threshold_limit) { createShamirsSecretShares: function (str, total_shares, threshold_limit) {
try{ try {
if (str.length > 0) { if (str.length > 0) {
var strHex = shamirSecretShare.str2hex(str); var strHex = shamirSecretShare.str2hex(str);
var shares = shamirSecretShare.share(strHex, total_shares, threshold_limit); var shares = shamirSecretShare.share(strHex, total_shares, threshold_limit);
return shares; return shares;
} }
return false; return false;
}catch{ } catch {
return false return false
} }
}, },
@ -8309,14 +8310,14 @@
}, },
retrieveShamirSecret: function (sharesArray) { retrieveShamirSecret: function (sharesArray) {
try{ try {
if (sharesArray.length > 0) { if (sharesArray.length > 0) {
var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length)); var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length));
comb = shamirSecretShare.hex2str(comb); comb = shamirSecretShare.hex2str(comb);
return comb; return comb;
} }
return false; return false;
}catch{ } catch {
return false return false
} }
} }
@ -8329,8 +8330,8 @@
util: { util: {
serverList: floGlobals.apiURL[floGlobals.blockchain].slice(0), serverList: floGlobals.apiURL[floGlobals.blockchain].slice(0),
curPos: floCrypto.randInt(0, floGlobals.apiURL[floGlobals.blockchain].length), curPos: floCrypto.randInt(0, floGlobals.apiURL[floGlobals.blockchain].length),
fetch_retry: function(apicall){ fetch_retry: function (apicall) {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
this.serverList.splice(this.curPos, 1); this.serverList.splice(this.curPos, 1);
this.curPos = floCrypto.randInt(0, this.serverList.length) this.curPos = floCrypto.randInt(0, this.serverList.length)
this.fetch_api(apicall) this.fetch_api(apicall)
@ -8338,15 +8339,15 @@
.catch(error => reject(error)); .catch(error => reject(error));
}) })
}, },
fetch_api: function(apicall){ fetch_api: function (apicall) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if(this.serverList.length === 0) if (this.serverList.length === 0)
reject("No floSight server working") reject("No floSight server working")
else{ else {
fetch(this.serverList[this.curPos] + apicall).then(response => { fetch(this.serverList[this.curPos] + apicall).then(response => {
if(response.ok) if (response.ok)
response.json().then(data => resolve(data)); response.json().then(data => resolve(data));
else{ else {
this.fetch_retry(apicall) this.fetch_retry(apicall)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
@ -8419,7 +8420,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))
@ -8451,7 +8452,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))
@ -8467,11 +8468,11 @@
* @param {float} sendAmt (optional) amount to be sent to receivers (default value: floGlobals.sendAmt) * @param {float} sendAmt (optional) amount to be sent to receivers (default value: floGlobals.sendAmt)
* @return {Promise} * @return {Promise}
*/ */
writeDataMultiple: function (senderPrivKeys, data, receivers, preserveRatio = true){ writeDataMultiple: function (senderPrivKeys, data, receivers, 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);
@ -8504,7 +8505,7 @@
let senders = {}, preserveRatio; let senders = {}, preserveRatio;
//check for argument validations //check for argument validations
try{ try {
let invalids = { let invalids = {
InvalidSenderPrivKeys: [], InvalidSenderPrivKeys: [],
InvalidSenderAmountFor: [], InvalidSenderAmountFor: [],
@ -8514,31 +8515,31 @@
let inputVal = 0, outputVal = 0; let inputVal = 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.getPubKeyHex(key)); let floID = floCrypto.getFloIDfromPubkeyHex(floCrypto.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] <= 0) if (typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[key] <= 0)
invalids.InvalidSenderAmountFor.push(key) invalids.InvalidSenderAmountFor.push(key)
else else
inputVal += senderPrivKeys[key]; inputVal += senderPrivKeys[key];
@ -8548,7 +8549,7 @@
coins: senderPrivKeys[key] coins: senderPrivKeys[key]
} }
} }
}catch(error){ } catch (error) {
invalids.InvalidSenderPrivKeys.push(key) invalids.InvalidSenderPrivKeys.push(key)
} }
} }
@ -8570,9 +8571,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(`Input Amount (${inputVal}) not equal to Output Amount (${outputVal})`) return reject(`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
@ -8584,7 +8585,7 @@
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 = [];
@ -8595,7 +8596,7 @@
totalBalance += balance[floID]; totalBalance += balance[floID];
} }
if (insufficient.length) if (insufficient.length)
return reject({InsufficientBalance: insufficient}) return reject({ 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)
@ -8612,7 +8613,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
@ -8636,7 +8637,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();
@ -8677,39 +8678,39 @@
}, },
//Get new Tx in blockchain since last sync using API //Get new Tx in blockchain since last sync using API
getNewTxs: function(addr, ignoreOld){ getNewTxs: function (addr, ignoreOld) {
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 - ignoreOld; var newItems = response.totalItems - ignoreOld;
if(newItems){ if (newItems) {
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(response => { this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems * 2}`).then(response => {
var filteredData = []; var filteredData = [];
for (i = response.totalItems - ignoreOld - 1; i >=0 ; i--){ for (i = response.totalItems - ignoreOld - 1; i >= 0; i--) {
if(response.items[i].isCoinBase){ if (response.items[i].isCoinBase) {
var item = { var item = {
time : response.items[i].time, time: response.items[i].time,
txid : response.items[i].txid, txid: response.items[i].txid,
sender : '(mined)'+response.items[i].vin[0].coinbase, sender: '(mined)' + response.items[i].vin[0].coinbase,
receiver : addr, receiver: addr,
floData : response.items[i].floData floData: response.items[i].floData
} }
}else{ } else {
var item = { var item = {
time : response.items[i].time, time: response.items[i].time,
txid : response.items[i].txid, txid: response.items[i].txid,
sender : response.items[i].vin[0].addr, sender: response.items[i].vin[0].addr,
receiver : response.items[i].vout[0].scriptPubKey.addresses[0], receiver: response.items[i].vout[0].scriptPubKey.addresses[0],
floData : response.items[i].floData floData: response.items[i].floData
} }
} }
filteredData.push(item); filteredData.push(item);
} }
resolve({totalItems:response.totalItems , items:filteredData}); resolve({ totalItems: response.totalItems, items: filteredData });
}).catch(error => { }).catch(error => {
reject(error); reject(error);
}); });
}else } else
resolve({totalItems:response.totalItems , items:[]}) resolve({ totalItems: response.totalItems, items: [] })
}).catch(error => { }).catch(error => {
reject(error); reject(error);
}); });
@ -8878,35 +8879,35 @@
floWebWallet = { floWebWallet = {
//generate a new Address triplet : resolves Object(floID,pubKey,privKey) //generate a new Address triplet : resolves Object(floID,pubKey,privKey)
generateNewAddr: function(){ generateNewAddr: function () {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
try{ try {
var triplet = floCrypto.generateNewID(); var triplet = floCrypto.generateNewID();
resolve(triplet); resolve(triplet);
}catch(error){ } catch (error) {
reject(error); reject(error);
} }
}) })
}, },
//recover triplet from given privKey : resolves Object(floID,pubKey,privKey) //recover triplet from given privKey : resolves Object(floID,pubKey,privKey)
recoverAddr: function(privKey){ recoverAddr: function (privKey) {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
try{ try {
var triplet = {} var triplet = {}
triplet.privKey = privKey; triplet.privKey = privKey;
triplet.pubKey = floCrypto.getPubKeyHex(triplet.privKey); triplet.pubKey = floCrypto.getPubKeyHex(triplet.privKey);
triplet.floID = floCrypto.getFloIDfromPubkeyHex(triplet.pubKey); triplet.floID = floCrypto.getFloIDfromPubkeyHex(triplet.pubKey);
resolve(triplet); resolve(triplet);
}catch(error){ } catch (error) {
reject(error); reject(error);
} }
}) })
}, },
//get balance of addr using API : resolves (balance) //get balance of addr using API : resolves (balance)
getBalance: function(addr){ getBalance: function (addr) {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
floBlockchainAPI.getBalance(addr) floBlockchainAPI.getBalance(addr)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)) .catch(error => reject(error))
@ -8914,27 +8915,27 @@
}, },
//send transaction to the blockchain using API : resolves (txid) //send transaction to the blockchain using API : resolves (txid)
sendTransaction: function(sender,receiver,amount,floData,privKey){ sendTransaction: function (sender, receiver, amount, floData, privKey) {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
floBlockchainAPI.sendTx(sender,receiver, amount, privKey, floData) floBlockchainAPI.sendTx(sender, receiver, amount, privKey, floData)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)) .catch(error => reject(error))
}) })
}, },
//sync new transactions from blockchain using API and stores in IDB : resolves Array(newItems) //sync new transactions from blockchain using API and stores in IDB : resolves Array(newItems)
syncTransactions: function(addr){ syncTransactions: function (addr) {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
compactIDB.readData('lastSync',addr).then(lastSync => { compactIDB.readData('lastSync', addr).then(lastSync => {
lastSync = lastSync|0; lastSync = lastSync | 0;
floBlockchainAPI.getNewTxs(addr,lastSync).then(APIresult => { floBlockchainAPI.getNewTxs(addr, lastSync).then(APIresult => {
compactIDB.readData('transactions',addr).then(IDBresult => { compactIDB.readData('transactions', addr).then(IDBresult => {
if (IDBresult === undefined) if (IDBresult === undefined)
var promise1 = compactIDB.addData('transactions',APIresult.items,addr) var promise1 = compactIDB.addData('transactions', APIresult.items, addr)
else else
var promise1 = compactIDB.writeData('transactions',IDBresult.concat(APIresult.items),addr) var promise1 = compactIDB.writeData('transactions', IDBresult.concat(APIresult.items), addr)
var promise2 = compactIDB.writeData('lastSync',APIresult.totalItems,addr) var promise2 = compactIDB.writeData('lastSync', APIresult.totalItems, addr)
Promise.all([promise1,promise2]).then(values => resolve(APIresult.items)) Promise.all([promise1, promise2]).then(values => resolve(APIresult.items))
}) })
}) })
}).catch(error => reject(error)) }).catch(error => reject(error))
@ -8942,17 +8943,17 @@
}, },
//read transactions stored in IDB : resolves Array(storedItems) //read transactions stored in IDB : resolves Array(storedItems)
readTransactions: function(addr){ readTransactions: function (addr) {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
compactIDB.readData('transactions',addr) compactIDB.readData('transactions', addr)
.then(IDBresult => resolve(IDBresult)) .then(IDBresult => resolve(IDBresult))
.catch(error => reject(error)) .catch(error => reject(error))
}) })
}, },
//get address-label pairs from IDB : resolves Object(addr:label) //get address-label pairs from IDB : resolves Object(addr:label)
getLabels: function(){ getLabels: function () {
return new Promise((resolve,reject) => { return new Promise((resolve, reject) => {
compactIDB.readAllData('labels') compactIDB.readAllData('labels')
.then(IDBresult => resolve(IDBresult)) .then(IDBresult => resolve(IDBresult))
.catch(error => reject(error)) .catch(error => reject(error))
@ -8960,13 +8961,13 @@
} }
} }
function onLoadStartUp(){ function onLoadStartUp() {
var IDBObjects = { var IDBObjects = {
lastSync:{}, lastSync: {},
labels:{}, labels: {},
transactions:{} transactions: {}
} }
compactIDB.initDB("FLOwebWallet",IDBObjects) compactIDB.initDB("FLOwebWallet", IDBObjects)
.then(result => console.log(result)) .then(result => console.log(result))
.catch(error => console.log(error)) .catch(error => console.log(error))

File diff suppressed because it is too large Load Diff