Compare commits

..

No commits in common. "master" and "flosight" have entirely different histories.

5 changed files with 291 additions and 485 deletions

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //btcOperator v1.1.3c (function (EXPORTS) { //btcOperator v1.1.3b
/* BTC Crypto and API Operator */ /* BTC Crypto and API Operator */
const btcOperator = EXPORTS; const btcOperator = EXPORTS;
@ -92,9 +92,6 @@
}, },
bech32Address: { bech32Address: {
value: key => coinjs.bech32Address(btcOperator.pubkey(key)).address value: key => coinjs.bech32Address(btcOperator.pubkey(key)).address
},
bech32mAddress: {
value: key => segwit_addr.encode("bc", 1, key)
} }
}); });
@ -110,8 +107,6 @@
return btcOperator.segwitAddress(key) === addr; return btcOperator.segwitAddress(key) === addr;
case "bech32": case "bech32":
return btcOperator.bech32Address(key) === addr; return btcOperator.bech32Address(key) === addr;
case "bech32m":
return btcOperator.bech32mAddress(key) === addr; // Key is a byte array of 32 bytes
default: default:
return null; return null;
} }
@ -121,7 +116,7 @@
if (!addr) if (!addr)
return undefined; return undefined;
let type = coinjs.addressDecode(addr).type; let type = coinjs.addressDecode(addr).type;
if (["standard", "multisig", "bech32", "multisigBech32", "bech32m"].includes(type)) if (["standard", "multisig", "bech32", "multisigBech32"].includes(type))
return type; return type;
else else
return false; return false;
@ -286,7 +281,6 @@
BECH32_OUTPUT_SIZE = 23, BECH32_OUTPUT_SIZE = 23,
BECH32_MULTISIG_OUTPUT_SIZE = 34, BECH32_MULTISIG_OUTPUT_SIZE = 34,
SEGWIT_OUTPUT_SIZE = 23; SEGWIT_OUTPUT_SIZE = 23;
BECH32M_OUTPUT_SIZE = 35; // Check this later
function _redeemScript(addr, key) { function _redeemScript(addr, key) {
let decode = coinjs.addressDecode(addr); let decode = coinjs.addressDecode(addr);
@ -297,15 +291,10 @@
return key ? coinjs.segwitAddress(btcOperator.pubkey(key)).redeemscript : null; return key ? coinjs.segwitAddress(btcOperator.pubkey(key)).redeemscript : null;
case "bech32": case "bech32":
return decode.redeemscript; return decode.redeemscript;
case "'multisigBech32":
return decode.redeemscript; //Multisig-edit-fee-change1
case "bech32m":
return decode.outstring; //Maybe the redeemscript will come when input processing happens for bech32m
default: default:
return null; return null;
} }
} }
btcOperator._redeemScript = _redeemScript;
function _sizePerInput(addr, rs) { function _sizePerInput(addr, rs) {
switch (coinjs.addressDecode(addr).type) { switch (coinjs.addressDecode(addr).type) {
@ -339,8 +328,6 @@
return BASE_OUTPUT_SIZE + BECH32_MULTISIG_OUTPUT_SIZE; return BASE_OUTPUT_SIZE + BECH32_MULTISIG_OUTPUT_SIZE;
case "multisig": case "multisig":
return BASE_OUTPUT_SIZE + SEGWIT_OUTPUT_SIZE; return BASE_OUTPUT_SIZE + SEGWIT_OUTPUT_SIZE;
case "bech32m":
return BASE_OUTPUT_SIZE + BECH32M_OUTPUT_SIZE;
default: default:
return null; return null;
} }
@ -392,7 +379,6 @@
//return //return
return parameters; return parameters;
} }
btcOperator.validateTxParameters = validateTxParameters;
function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_address, fee_from_receiver) { function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_address, fee_from_receiver) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -431,7 +417,6 @@
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
} }
btcOperator.createTransaction = createTransaction;
function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver) { function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -456,7 +441,6 @@
} }
}) })
} }
btcOperator.addInputs = addInputs;
function addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args = {}) { function addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -511,7 +495,6 @@
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
} }
btcOperator.addUTXOs = addUTXOs;
function addOutputs(tx, receivers, amounts, change_address) { function addOutputs(tx, receivers, amounts, change_address) {
let size = 0; let size = 0;
@ -523,7 +506,6 @@
size += _sizePerOutput(change_address); size += _sizePerOutput(change_address);
return size; return size;
} }
btcOperator.addOutputs = addOutputs;
/* /*
function autoFeeCalc(tx) { function autoFeeCalc(tx) {
@ -571,19 +553,7 @@
} else resolve(deserializeTx(tx)); } else resolve(deserializeTx(tx));
}) })
} }
btcOperator.tx_fetch_for_editing = tx_fetch_for_editing;
const extractLastHexStrings = btcOperator.extractLastHexStrings = function (arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
const innerArray = arr[i];
if (innerArray.length > 0) {
const lastHexString = innerArray[innerArray.length - 1];
result.push(lastHexString);
}
}
return result;
}
btcOperator.editFee = function (tx_hex, new_fee, private_keys, change_only = true) { btcOperator.editFee = function (tx_hex, new_fee, private_keys, change_only = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -674,119 +644,10 @@
}) })
} }
btcOperator.editFee_corewallet = function(tx_hex, new_fee, private_keys, change_only = true) {
return new Promise((resolve, reject) => {
if (!Array.isArray(private_keys))
private_keys = [private_keys];
tx_fetch_for_editing(tx_hex).then(tx => {
parseTransaction(tx).then(tx_parsed => {
if (tx_parsed.fee >= new_fee)
return reject("Fees can only be increased");
//editable addresses in output values (for fee increase)
var edit_output_address = new Set();
if (change_only === true) //allow only change values (ie, sender address) to be edited to inc fee
tx_parsed.inputs.forEach(inp => edit_output_address.add(inp.address));
else if (change_only === false) //allow all output values to be edited
tx_parsed.outputs.forEach(out => edit_output_address.add(out.address));
else if (typeof change_only == 'string') // allow only given receiver id output to be edited
edit_output_address.add(change_only);
else if (Array.isArray(change_only)) //allow only given set of receiver id outputs to be edited
change_only.forEach(id => edit_output_address.add(id));
//edit output values to increase fee
let inc_fee = util.BTC_to_Sat(new_fee - tx_parsed.fee);
if (inc_fee < MIN_FEE_UPDATE)
return reject(`Insufficient additional fee. Minimum increment: ${MIN_FEE_UPDATE}`);
for (let i = tx.outs.length - 1; i >= 0 && inc_fee > 0; i--) //reduce in reverse order
if (edit_output_address.has(tx_parsed.outputs[i].address)) {
let current_value = tx.outs[i].value;
if (current_value instanceof BigInteger) //convert BigInteger class to inv value
current_value = current_value.intValue();
//edit the value as required
if (current_value > inc_fee) {
tx.outs[i].value = current_value - inc_fee;
inc_fee = 0;
} else {
inc_fee -= current_value;
tx.outs[i].value = 0;
}
}
if (inc_fee > 0) {
let max_possible_fee = util.BTC_to_Sat(new_fee) - inc_fee; //in satoshi
return reject(`Insufficient output values to increase fee. Maximum fee possible: ${util.Sat_to_BTC(max_possible_fee)}`);
}
tx.outs = tx.outs.filter(o => o.value >= DUST_AMT); //remove all output with value less than DUST amount
//remove existing signatures and reset the scripts
let wif_keys = [];
let witness_position = 0;
for (let i in tx.ins) {
var addr = tx_parsed.inputs[i].address,
value = util.BTC_to_Sat(tx_parsed.inputs[i].value);
let addr_decode = coinjs.addressDecode(addr);
//find the correct key for addr
var privKey = private_keys.find(pk => verifyKey(addr, pk));
if (!privKey)
return reject(`Private key missing for ${addr}`);
//find redeemScript (if any)
const rs = _redeemScript(addr, privKey);
rs === false ? wif_keys.unshift(privKey) : wif_keys.push(privKey); //sorting private-keys (wif)
//reset the script for re-signing
var script;
if (!rs || !rs.length) {
//legacy script (derive from address)
let s = coinjs.script();
s.writeOp(118); //OP_DUP
s.writeOp(169); //OP_HASH160
s.writeBytes(addr_decode.bytes);
s.writeOp(136); //OP_EQUALVERIFY
s.writeOp(172); //OP_CHECKSIG
script = Crypto.util.bytesToHex(s.buffer);
} else if (((rs.match(/^00/) && rs.length == 44)) || (rs.length == 40 && rs.match(/^[a-f0-9]+$/gi))) {
//redeemScript for segwit/bech32
let s = coinjs.script();
s.writeBytes(Crypto.util.hexToBytes(rs));
s.writeOp(0);
s.writeBytes(coinjs.numToBytes(value.toFixed(0), 8));
script = Crypto.util.bytesToHex(s.buffer);
if (addr_decode == "bech32") {witness_position = witness_position + 1;} //bech32 has witness
} else if (addr_decode.type === 'multisigBech32') {
var rs_array = [];
rs_array = btcOperator.extractLastHexStrings(tx.witness);
let redeemScript = rs_array[witness_position];
witness_position = witness_position + 1;
//redeemScript multisig (bech32)
let s = coinjs.script();
s.writeBytes(Crypto.util.hexToBytes(redeemScript));
s.writeOp(0);
s.writeBytes(coinjs.numToBytes(value.toFixed(0), 8));
script = Crypto.util.bytesToHex(s.buffer);
} else //redeemScript for multisig (segwit)
script = rs;
tx.ins[i].script = coinjs.script(script);
}
tx.witness = false; //remove all witness signatures
console.debug("Unsigned:", tx.serialize());
//re-sign the transaction
new Set(wif_keys).forEach(key => tx.sign(key, 1 /*sighashtype*/ )); //Sign the tx using private key WIF
if (btcOperator.checkSigned(tx)) {
resolve(tx.serialize());
} else {
reject("All private keys not present");
}
}).catch(error => reject(error))
}).catch(error => reject(error))
})
}
btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) { btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
createSignedTx(senders, privkeys, receivers, amounts, fee, options).then(result => { createSignedTx(senders, privkeys, receivers, amounts, fee, options).then(result => {
// debugger; debugger;
broadcastTx(result.transaction.serialize()) broadcastTx(result.transaction.serialize())
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)); .catch(error => reject(error));
@ -899,7 +760,7 @@
}) })
} }
const deserializeTx = btcOperator.deserializeTx = function (tx) { function deserializeTx(tx) {
if (typeof tx === 'string' || Array.isArray(tx)) { if (typeof tx === 'string' || Array.isArray(tx)) {
try { try {
tx = coinjs.transaction().deserialize(tx); tx = coinjs.transaction().deserialize(tx);
@ -1044,7 +905,7 @@
}).catch(error => reject(error)) }).catch(error => reject(error))
}); });
getTx.hex = btcOperator.getTx.hex = txid => new Promise((resolve, reject) => { getTx.hex = txid => new Promise((resolve, reject) => {
fetch_api(`rawtx/${txid}?format=hex`, false) fetch_api(`rawtx/${txid}?format=hex`, false)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)) .catch(error => reject(error))

View File

@ -1,13 +1,13 @@
(function (EXPORTS) { //floBlockchainAPI v3.0.1b (function (EXPORTS) { //floBlockchainAPI v2.5.6b
/* FLO Blockchain Operator to send/receive data from blockchain using API calls via FLO Blockbook*/ /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/
'use strict'; 'use strict';
const floBlockchainAPI = EXPORTS; const floBlockchainAPI = EXPORTS;
const DEFAULT = { const DEFAULT = {
blockchain: floGlobals.blockchain, blockchain: floGlobals.blockchain,
apiURL: { apiURL: {
FLO: ['https://blockbook.ranchimall.net/'], FLO: ['https://flosight.ranchimall.net/'],
FLO_TEST: ['https://blockbook-testnet.ranchimall.net/'] FLO_TEST: ['https://flosight-testnet.ranchimall.net/']
}, },
sendAmt: 0.0003, sendAmt: 0.0003,
fee: 0.0002, fee: 0.0002,
@ -61,9 +61,9 @@
var serverList = Array.from(allServerList); var serverList = Array.from(allServerList);
var curPos = floCrypto.randInt(0, serverList.length - 1); var curPos = floCrypto.randInt(0, serverList.length - 1);
function fetch_retry(apicall, rm_node) { function fetch_retry(apicall, rm_flosight) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let i = serverList.indexOf(rm_node) let i = serverList.indexOf(rm_flosight)
if (i != -1) serverList.splice(i, 1); if (i != -1) serverList.splice(i, 1);
curPos = floCrypto.randInt(0, serverList.length - 1); curPos = floCrypto.randInt(0, serverList.length - 1);
fetch_api(apicall, false) fetch_api(apicall, false)
@ -82,19 +82,19 @@
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
} else } else
reject("No FLO blockbook server working"); reject("No floSight server working");
} else { } else {
let serverURL = serverList[curPos]; let flosight = serverList[curPos];
fetch(serverURL + apicall).then(response => { fetch(flosight + apicall).then(response => {
if (response.ok) if (response.ok)
response.json().then(data => resolve(data)); response.json().then(data => resolve(data));
else { else {
fetch_retry(apicall, serverURL) fetch_retry(apicall, flosight)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
} }
}).catch(error => { }).catch(error => {
fetch_retry(apicall, serverURL) fetch_retry(apicall, flosight)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
}) })
@ -124,27 +124,43 @@
} }
//Get balance for the given Address //Get balance for the given Address
const getBalance = floBlockchainAPI.getBalance = function (addr) { const getBalance = floBlockchainAPI.getBalance = function (addr, after = null) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let api = `api/address/${addr}`; let api = `api/addr/${addr}/balance`, query_params = {};
promisedAPI(api, { details: "basic" }) if (after) {
.then(result => resolve(result["balance"])) if (typeof after === 'string' && /^[0-9a-z]{64}$/i.test(after))
.catch(error => reject(error)) query_params.after = after;
else return reject("Invalid 'after' parameter");
}
promisedAPI(api, query_params).then(result => {
if (typeof result === 'object' && result.lastItem) {
getBalance(addr, result.lastItem)
.then(r => resolve(util.toFixed(r + result.data)))
.catch(error => reject(error))
} else resolve(result);
}).catch(error => reject(error))
}); });
} }
function getScriptPubKey(address) {
var tx = bitjs.transaction();
tx.addoutput(address, 0);
let outputBuffer = tx.outputs.pop().script;
return Crypto.util.bytesToHex(outputBuffer)
}
const getUTXOs = address => new Promise((resolve, reject) => { const getUTXOs = address => new Promise((resolve, reject) => {
promisedAPI(`api/utxo/${address}`, { confirmed: true }).then(utxos => { promisedAPI(`api/addr/${address}/utxo`)
let scriptPubKey = getScriptPubKey(address); .then(utxo => resolve(utxo))
utxos.forEach(u => u.scriptPubKey = scriptPubKey); .catch(error => reject(error))
resolve(utxos); })
const getUnconfirmedSpent = address => new Promise((resolve, reject) => {
readTxs(address, { mempool: "only" }).then(result => {
let unconfirmedSpent = {};
for (let tx of result.items)
if (tx.confirmations == 0)
for (let vin of tx.vin)
if (vin.addr === address) {
if (Array.isArray(unconfirmedSpent[vin.txid]))
unconfirmedSpent[vin.txid].push(vin.vout);
else
unconfirmedSpent[vin.txid] = [vin.vout];
}
resolve(unconfirmedSpent);
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
@ -164,28 +180,32 @@
var fee = DEFAULT.fee; var fee = DEFAULT.fee;
if (balance < sendAmt + fee) if (balance < sendAmt + fee)
return reject("Insufficient FLO balance!"); return reject("Insufficient FLO balance!");
getUTXOs(senderAddr).then(utxos => { getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => {
//form/construct the transaction data getUTXOs(senderAddr).then(utxos => {
var trx = bitjs.transaction(); //form/construct the transaction data
var utxoAmt = 0.0; var trx = bitjs.transaction();
for (var i = utxos.length - 1; var utxoAmt = 0.0;
(i >= 0) && (utxoAmt < sendAmt + fee); i--) { for (var i = utxos.length - 1;
//use only utxos with confirmations (strict_utxo mode) (i >= 0) && (utxoAmt < sendAmt + fee); i--) {
if (utxos[i].confirmations || !strict_utxo) { //use only utxos with confirmations (strict_utxo mode)
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); if (utxos[i].confirmations || !strict_utxo) {
utxoAmt += utxos[i].amount; if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout))
}; continue; //A transaction has already used the utxo, but is unconfirmed.
} trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
if (utxoAmt < sendAmt + fee) utxoAmt += utxos[i].amount;
reject("Insufficient FLO: Some UTXOs are unconfirmed"); };
else { }
trx.addoutput(receiverAddr, sendAmt); if (utxoAmt < sendAmt + fee)
var change = utxoAmt - sendAmt - fee; reject("Insufficient FLO: Some UTXOs are unconfirmed");
if (change > DEFAULT.minChangeAmt) else {
trx.addoutput(senderAddr, change); trx.addoutput(receiverAddr, sendAmt);
trx.addflodata(floData.replace(/\n/g, ' ')); var change = utxoAmt - sendAmt - fee;
resolve(trx); if (change > DEFAULT.minChangeAmt)
} trx.addoutput(senderAddr, change);
trx.addflodata(floData.replace(/\n/g, ' '));
resolve(trx);
}
}).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
@ -273,30 +293,34 @@
if (balance < totalAmt + fee) if (balance < totalAmt + fee)
return reject("Insufficient FLO balance!"); return reject("Insufficient FLO balance!");
//get unconfirmed tx list //get unconfirmed tx list
getUTXOs(floID).then(utxos => { getUnconfirmedSpent(floID).then(unconfirmedSpent => {
var trx = bitjs.transaction(); getUTXOs(floID).then(utxos => {
var utxoAmt = 0.0; var trx = bitjs.transaction();
for (let i = utxos.length - 1; (i >= 0) && (utxoAmt < totalAmt + fee); i--) { var utxoAmt = 0.0;
//use only utxos with confirmations (strict_utxo mode) for (let i = utxos.length - 1; (i >= 0) && (utxoAmt < totalAmt + fee); i--) {
if (utxos[i].confirmations || !strict_utxo) { //use only utxos with confirmations (strict_utxo mode)
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); if (utxos[i].confirmations || !strict_utxo) {
utxoAmt += utxos[i].amount; if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout))
}; continue; //A transaction has already used the utxo, but is unconfirmed.
} trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
if (utxoAmt < totalAmt + fee) utxoAmt += utxos[i].amount;
reject("Insufficient FLO: Some UTXOs are unconfirmed"); };
else { }
for (let i = 0; i < count; i++) if (utxoAmt < totalAmt + fee)
trx.addoutput(floID, splitAmt); reject("Insufficient FLO: Some UTXOs are unconfirmed");
var change = utxoAmt - totalAmt - fee; else {
if (change > DEFAULT.minChangeAmt) for (let i = 0; i < count; i++)
trx.addoutput(floID, change); trx.addoutput(floID, splitAmt);
trx.addflodata(floData.replace(/\n/g, ' ')); var change = utxoAmt - totalAmt - fee;
var signedTxHash = trx.sign(privKey, 1); if (change > DEFAULT.minChangeAmt)
broadcastTx(signedTxHash) trx.addoutput(floID, change);
.then(txid => resolve(txid)) trx.addflodata(floData.replace(/\n/g, ' '));
.catch(error => reject(error)) var signedTxHash = trx.sign(privKey, 1);
} broadcastTx(signedTxHash)
.then(txid => resolve(txid))
.catch(error => reject(error))
}
}).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
@ -527,29 +551,33 @@
var fee = DEFAULT.fee; var fee = DEFAULT.fee;
if (balance < sendAmt + fee) if (balance < sendAmt + fee)
return reject("Insufficient FLO balance!"); return reject("Insufficient FLO balance!");
getUTXOs(senderAddr).then(utxos => { getUnconfirmedSpent(senderAddr).then(unconfirmedSpent => {
//form/construct the transaction data getUTXOs(senderAddr).then(utxos => {
var trx = bitjs.transaction(); //form/construct the transaction data
var utxoAmt = 0.0; var trx = bitjs.transaction();
for (var i = utxos.length - 1; var utxoAmt = 0.0;
(i >= 0) && (utxoAmt < sendAmt + fee); i--) { for (var i = utxos.length - 1;
//use only utxos with confirmations (strict_utxo mode) (i >= 0) && (utxoAmt < sendAmt + fee); i--) {
if (utxos[i].confirmations || !strict_utxo) { //use only utxos with confirmations (strict_utxo mode)
trx.addinput(utxos[i].txid, utxos[i].vout, redeemScript); //for multisig, script=redeemScript if (utxos[i].confirmations || !strict_utxo) {
utxoAmt += utxos[i].amount; if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout))
}; continue; //A transaction has already used the utxo, but is unconfirmed.
} trx.addinput(utxos[i].txid, utxos[i].vout, redeemScript); //for multisig, script=redeemScript
if (utxoAmt < sendAmt + fee) utxoAmt += utxos[i].amount;
reject("Insufficient FLO: Some UTXOs are unconfirmed"); };
else { }
for (let i in receivers) if (utxoAmt < sendAmt + fee)
trx.addoutput(receivers[i], amounts[i]); reject("Insufficient FLO: Some UTXOs are unconfirmed");
var change = utxoAmt - sendAmt - fee; else {
if (change > DEFAULT.minChangeAmt) for (let i in receivers)
trx.addoutput(senderAddr, change); trx.addoutput(receivers[i], amounts[i]);
trx.addflodata(floData.replace(/\n/g, ' ')); var change = utxoAmt - sendAmt - fee;
resolve(trx); if (change > DEFAULT.minChangeAmt)
} trx.addoutput(senderAddr, change);
trx.addflodata(floData.replace(/\n/g, ' '));
resolve(trx);
}
}).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}); });
@ -745,11 +773,20 @@
const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) { const broadcastTx = floBlockchainAPI.broadcastTx = function (signedTxHash) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (signedTxHash.length < 1) if (signedTxHash.length < 1)
return reject("Empty Transaction Data"); return reject("Empty Signature");
var url = serverList[curPos] + 'api/tx/send';
promisedAPI('/api/sendtx/' + signedTxHash) fetch(url, {
.then(response => resolve(response["result"])) method: "POST",
.catch(error => reject(error)) headers: {
'Content-Type': 'application/json'
},
body: `{"rawtx":"${signedTxHash}"}`
}).then(response => {
if (response.ok)
response.json().then(data => resolve(data.txid.result));
else
response.text().then(data => resolve(data));
}).catch(error => reject(error));
}) })
} }
@ -788,96 +825,61 @@
}) })
} }
//Read Txs of Address //Read Txs of Address between from and to
const readTxs = floBlockchainAPI.readTxs = function (addr, options = {}) { const readTxs = floBlockchainAPI.readTxs = function (addr, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let api = `api/addrs/${addr}/txs`;
//API options //API options
let query_params = { details: 'txs' }; let query_params = {};
//page options if (!isUndefined(options.after) || !isUndefined(options.before)) {
if (!isUndefined(options.page) && Number.isInteger(options.page)) if (!isUndefined(options.after))
query_params.page = options.page; query_params.after = options.after;
if (!isUndefined(options.pageSize) && Number.isInteger(options.pageSize)) if (!isUndefined(options.before))
query_params.pageSize = options.pageSize; query_params.before = options.before;
//only confirmed tx } else {
if (options.confirmed) //Default is false in server, so only add confirmed filter if confirmed has a true value if (!isUndefined(options.from))
query_params.confirmed = true; query_params.from = options.from;
if (!isUndefined(options.to))
promisedAPI(`api/address/${addr}`, query_params).then(response => { query_params.to = options.to;
if (!Array.isArray(response.txs)) //set empty array if address doesnt have any tx }
response.txs = []; if (!isUndefined(options.latest))
resolve(response) query_params.latest = options.latest;
}).catch(error => reject(error)) if (!isUndefined(options.mempool))
query_params.mempool = options.mempool;
promisedAPI(api, query_params)
.then(response => resolve(response))
.catch(error => reject(error))
}); });
} }
//backward support (floBlockchainAPI < v2.5.6)
function readAllTxs_oldSupport(addr, options, ignoreOld = 0, cacheTotal = 0) {
return new Promise((resolve, reject) => {
readTxs(addr, options).then(response => {
cacheTotal += response.txs.length;
let n_remaining = response.txApperances - cacheTotal
if (n_remaining < ignoreOld) { // must remove tx that would have been fetch during prev call
let n_remove = ignoreOld - n_remaining;
resolve(response.txs.slice(0, -n_remove));
} else if (response.page == response.totalPages) //last page reached
resolve(response.txs);
else {
options.page = response.page + 1;
readAllTxs_oldSupport(addr, options, ignoreOld, cacheTotal)
.then(result => resolve(response.txs.concat(result)))
.catch(error => reject(error))
}
}).catch(error => reject(error))
})
}
function readAllTxs_new(addr, options, lastItem) {
return new Promise((resolve, reject) => {
readTxs(addr, options).then(response => {
let i = response.txs.findIndex(t => t.txid === lastItem);
if (i != -1) //found lastItem
resolve(response.txs.slice(0, i))
else if (response.page == response.totalPages) //last page reached
resolve(response.txs);
else {
options.page = response.page + 1;
readAllTxs_new(addr, options, lastItem)
.then(result => resolve(response.txs.concat(result)))
.catch(error => reject(error))
}
}).catch(error => reject(error))
})
}
//Read All Txs of Address (newest first) //Read All Txs of Address (newest first)
const readAllTxs = floBlockchainAPI.readAllTxs = function (addr, options = {}) { const readAllTxs = floBlockchainAPI.readAllTxs = function (addr, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (Number.isInteger(options.ignoreOld)) //backward support: data from floBlockchainAPI < v2.5.6 readTxs(addr, options).then(response => {
readAllTxs_oldSupport(addr, options, options.ignoreOld).then(txs => { if (response.incomplete) {
let last_tx = txs.find(t => t.confirmations > 0); let next_options = Object.assign({}, options);
let new_lastItem = last_tx ? last_tx.txid : options.ignoreOld; if (options.latest)
next_options.before = response.initItem; //update before for chain query (latest 1st)
else
next_options.after = response.lastItem; //update after for chain query (oldest 1st)
readAllTxs(addr, next_options).then(r => {
r.items = r.items.concat(response.items); //latest tx are 1st in array
resolve(r);
}).catch(error => reject(error))
} else
resolve({ resolve({
lastItem: new_lastItem, lastItem: response.lastItem || options.after,
items: txs items: response.items
}) });
})
}).catch(error => reject(error)) });
else //New format for floBlockchainAPI >= v2.5.6
readAllTxs_new(addr, options, options.after).then(txs => {
let last_tx = txs.find(t => t.confirmations > 0);
let new_lastItem = last_tx ? last_tx.txid : options.after;
resolve({
lastItem: new_lastItem,
items: txs
})
}).catch(error => reject(error))
})
} }
/*Read flo Data from txs of given Address /*Read flo Data from txs of given Address
options can be used to filter data options can be used to filter data
after : query after the given txid after : query after the given txid
confirmed : query only confirmed tx or not (options same as readAllTx, DEFAULT=true: only_confirmed_tx) before : query before the given txid
mempool : query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx)
ignoreOld : ignore old txs (deprecated: support for backward compatibility only, cannot be used with 'after') ignoreOld : ignore old txs (deprecated: support for backward compatibility only, cannot be used with 'after')
sentOnly : filters only sent data sentOnly : filters only sent data
receivedOnly: filters only received data receivedOnly: filters only received data
@ -892,15 +894,19 @@
//fetch options //fetch options
let query_options = {}; let query_options = {};
query_options.confirmed = isUndefined(options.confirmed) ? true : options.confirmed; //DEFAULT: ignore unconfirmed tx query_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx
if (!isUndefined(options.after) || !isUndefined(options.before)) {
if (!isUndefined(options.after)) if (!isUndefined(options.ignoreOld)) //Backward support
return reject("Invalid options: cannot use after/before and ignoreOld in same query");
//use passed after and/or before options (options remain undefined if not passed)
query_options.after = options.after; query_options.after = options.after;
else if (!isUndefined(options.ignoreOld)) query_options.before = options.before;
query_options.ignoreOld = options.ignoreOld; }
readAllTxs(addr, query_options).then(response => { readAllTxs(addr, query_options).then(response => {
if (Number.isInteger(options.ignoreOld)) //backward support, cannot be used with options.after or options.before
response.items.splice(-options.ignoreOld); //negative to count from end of the array
if (typeof options.senders === "string") options.senders = [options.senders]; if (typeof options.senders === "string") options.senders = [options.senders];
if (typeof options.receivers === "string") options.receivers = [options.receivers]; if (typeof options.receivers === "string") options.receivers = [options.receivers];
@ -910,9 +916,9 @@
if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query
return false; return false;
if (options.sentOnly && !tx.vin.some(vin => vin.addresses[0] === addr)) if (options.sentOnly && !tx.vin.some(vin => vin.addr === addr))
return false; return false;
else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addresses[0]))) else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addr)))
return false; return false;
if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr)) if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr))
@ -938,7 +944,7 @@
txid: tx.txid, txid: tx.txid,
time: tx.time, time: tx.time,
blockheight: tx.blockheight, blockheight: tx.blockheight,
senders: new Set(tx.vin.map(v => v.addresses[0])), senders: new Set(tx.vin.map(v => v.addr)),
receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])), receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])),
data: tx.floData data: tx.floData
} : tx.floData); } : tx.floData);
@ -958,7 +964,8 @@
caseFn: (function) flodata => return bool value caseFn: (function) flodata => return bool value
options can be used to filter data options can be used to filter data
after : query after the given txid after : query after the given txid
confirmed : query only confirmed tx or not (options same as readAllTx, DEFAULT=true: only_confirmed_tx) before : query before the given txid
mempool : query mempool tx or not (options same as readAllTx, DEFAULT=false: ignore unconfirmed tx)
sentOnly : filters only sent data sentOnly : filters only sent data
receivedOnly: filters only received data receivedOnly: filters only received data
tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details) tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details)
@ -968,37 +975,23 @@
const getLatestData = floBlockchainAPI.getLatestData = function (addr, caseFn, options = {}) { const getLatestData = floBlockchainAPI.getLatestData = function (addr, caseFn, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
//fetch options //fetch options
let query_options = {}; let query_options = { latest: true };
query_options.confirmed = isUndefined(options.confirmed) ? true : options.confirmed; //DEFAULT: confirmed tx only query_options.mempool = isUndefined(options.mempool) ? false : options.mempool; //DEFAULT: ignore unconfirmed tx
if (!isUndefined(options.page)) if (!isUndefined(options.after)) query_options.after = options.after;
query_options.page = options.page; if (!isUndefined(options.before)) query_options.before = options.before;
//if (!isUndefined(options.after)) query_options.after = options.after;
let new_lastItem;
readTxs(addr, query_options).then(response => { readTxs(addr, query_options).then(response => {
//lastItem confirmed tx checked
if (!new_lastItem) {
let last_tx = response.items.find(t => t.confirmations > 0);
if (last_tx)
new_lastItem = last_tx.txid;
}
if (typeof options.senders === "string") options.senders = [options.senders]; if (typeof options.senders === "string") options.senders = [options.senders];
if (typeof options.receivers === "string") options.receivers = [options.receivers]; if (typeof options.receivers === "string") options.receivers = [options.receivers];
//check if `after` txid is in the response
let i_after = response.txs.findIndex(t => t.txid === options.after);
if (i_after != -1) //found lastItem, hence remove it and all txs before that
response.items.splice(i_after);
var item = response.items.find(tx => { var item = response.items.find(tx => {
if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query if (!tx.confirmations) //unconfirmed transactions: this should not happen as we send mempool=false in API query
return false; return false;
if (options.sentOnly && !tx.vin.some(vin => vin.addresses[0] === addr)) if (options.sentOnly && !tx.vin.some(vin => vin.addr === addr))
return false; return false;
else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addresses[0]))) else if (Array.isArray(options.senders) && !tx.vin.some(vin => options.senders.includes(vin.addr)))
return false; return false;
if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr)) if (options.receivedOnly && !tx.vout.some(vout => vout.scriptPubKey.addresses[0] === addr))
@ -1011,34 +1004,35 @@
//if item found, then resolve the result //if item found, then resolve the result
if (!isUndefined(item)) { if (!isUndefined(item)) {
const result = { lastItem: new_lastItem || item.txid }; const result = { lastItem: response.lastItem };
if (options.tx) { if (options.tx) {
result.item = { result.item = {
txid: item.txid, txid: tx.txid,
time: item.time, time: tx.time,
blockheight: item.blockheight, blockheight: tx.blockheight,
senders: new Set(item.vin.map(v => v.addresses[0])), senders: new Set(tx.vin.map(v => v.addr)),
receivers: new Set(item.vout.map(v => v.scriptPubKey.addresses[0])), receivers: new Set(tx.vout.map(v => v.scriptPubKey.addresses[0])),
data: item.floData data: tx.floData
} }
} else } else
result.data = item.floData; result.data = tx.floData;
return resolve(result); return resolve(result);
} }
if (response.page == response.totalPages || i_after != -1) //reached last page to check
resolve({ lastItem: new_lastItem || options.after }); //no data match the caseFn, resolve just the lastItem
//else if address needs chain query //else if address needs chain query
else { else if (response.incomplete) {
options.page = response.page + 1; let next_options = Object.assign({}, options);
getLatestData(addr, caseFn, options) options.before = response.initItem; //this fn uses latest option, so using before to chain query
.then(result => resolve(result)) getLatestData(addr, caseFn, next_options).then(r => {
.catch(error => reject(error)) r.lastItem = response.lastItem; //update last key as it should be the newest tx
resolve(r);
}).catch(error => reject(error))
} }
//no data match the caseFn, resolve just the lastItem
else
resolve({ lastItem: response.lastItem });
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })
} }
})('object' === typeof module ? module.exports : window.floBlockchainAPI = {}); })('object' === typeof module ? module.exports : window.floBlockchainAPI = {});

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //floCloudAPI v2.4.5 (function (EXPORTS) { //floCloudAPI v2.4.3a
/* FLO Cloud operations to send/request application data*/ /* FLO Cloud operations to send/request application data*/
'use strict'; 'use strict';
const floCloudAPI = EXPORTS; const floCloudAPI = EXPORTS;
@ -609,39 +609,49 @@
}) })
} }
*/ */
//edit comment of data in supernode cloud (sender only) /*(NEEDS UPDATE)
floCloudAPI.editApplicationData = function (vectorClock, comment_edit, options = {}) { //edit comment of data in supernode cloud (mutable comments only)
floCloudAPI.editApplicationData = function(vectorClock, newComment, oldData, options = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
//request the data from cloud for resigning let p0
let req_options = Object.assign({}, options); if (!oldData) {
req_options.atVectorClock = vectorClock; options.atVectorClock = vectorClock;
requestApplicationData(undefined, req_options).then(result => { options.callback = false;
if (!result.length) p0 = requestApplicationData(false, options)
return reject("Data not found"); } else
let data = result[0]; p0 = Promise.resolve({
if (data.senderID !== user.id) vectorClock: {
return reject("Only sender can edit comment"); ...oldData
data.comment = comment_edit; }
let hashcontent = ["receiverID", "time", "application", "type", "message", "comment"] })
.map(d => data[d]).join("|"); p0.then(d => {
let re_sign = user.sign(hashcontent); if (d.senderID != user.id)
var request = { return reject("Invalid requestorID")
receiverID: options.receiverID || DEFAULT.adminID, else if (!d.comment.startsWith("EDIT:"))
return reject("Data immutable")
let data = {
requestorID: user.id, requestorID: user.id,
pubKey: user.public, receiverID: d.receiverID,
time: Date.now(), time: Date.now(),
vectorClock: vectorClock, application: d.application,
edit: comment_edit, edit: {
re_sign: re_sign vectorClock: vectorClock,
comment: newComment
}
} }
let request_hash = ["time", "vectorClock", "edit", "re_sign"].map(d => request[d]).join("|"); d.comment = data.edit.comment;
request.sign = user.sign(request_hash); let hashcontent = ["receiverID", "time", "application", "type", "message",
singleRequest(request.receiverID, request) "comment"
.then(result => resolve(result)) ]
.map(x => d[x]).join("|")
data.edit.sign = user.sign(hashcontent)
singleRequest(data.receiverID, data)
.then(result => resolve("Data comment updated"))
.catch(error => reject(error)) .catch(error => reject(error))
}).catch(error => reject(error)) })
}) })
} }
*/
//tag data in supernode cloud (subAdmin access only) //tag data in supernode cloud (subAdmin access only)
floCloudAPI.tagApplicationData = function (vectorClock, tag, options = {}) { floCloudAPI.tagApplicationData = function (vectorClock, tag, options = {}) {
@ -801,67 +811,6 @@
}) })
} }
//upload file
floCloudAPI.uploadFile = function (fileBlob, type, options = {}) {
return new Promise((resolve, reject) => {
if (!(fileBlob instanceof File) && !(fileBlob instanceof Blob))
return reject("file must be instance of File/Blob");
fileBlob.arrayBuffer().then(arraybuf => {
let file_data = { type: fileBlob.type, name: fileBlob.name };
file_data.content = Crypto.util.bytesToBase64(new Uint8Array(arraybuf));
if (options.encrypt) {
let encryptionKey = options.encrypt === true ?
floGlobals.settings.encryptionKey : options.encrypt
file_data = floCrypto.encryptData(JSON.stringify(file_data), encryptionKey)
}
sendApplicationData(file_data, type, options)
.then(({ vectorClock, receiverID, type, application }) => resolve({ vectorClock, receiverID, type, application }))
.catch(error => reject(error))
}).catch(error => reject(error))
})
}
//download file
floCloudAPI.downloadFile = function (vectorClock, options = {}) {
return new Promise((resolve, reject) => {
options.atVectorClock = vectorClock;
requestApplicationData(options.type, options).then(result => {
if (!result.length)
return reject("File not found");
result = result[0];
try {
let file_data = decodeMessage(result.message);
//file is encrypted: decryption required
if (file_data instanceof Object && "secret" in file_data) {
if (!options.decrypt)
return reject("Data is encrypted");
let decryptionKey = (options.decrypt === true) ? Crypto.AES.decrypt(user_private, aes_key) : options.decrypt;
if (!Array.isArray(decryptionKey))
decryptionKey = [decryptionKey];
let flag = false;
for (let key of decryptionKey) {
try {
let tmp = floCrypto.decryptData(file_data, key);
file_data = JSON.parse(tmp);
flag = true;
break;
} catch (error) { }
}
if (!flag)
return reject("Unable to decrypt file: Invalid private key");
}
//reconstruct the file
let arraybuf = new Uint8Array(Crypto.util.base64ToBytes(file_data.content))
result.file = new File([arraybuf], file_data.name, { type: file_data.type });
resolve(result)
} catch (error) {
console.error(error);
reject("Data is not a file");
}
}).catch(error => reject(error))
})
}
/* /*
Functions: Functions:
findDiff(original, updatedObj) returns an object with the added, deleted and updated differences findDiff(original, updatedObj) returns an object with the added, deleted and updated differences

View File

@ -1,4 +1,4 @@
(function (EXPORTS) { //floDapps v2.4.1 (function (EXPORTS) { //floDapps v2.4.0
/* General functions for FLO Dapps*/ /* General functions for FLO Dapps*/
'use strict'; 'use strict';
const floDapps = EXPORTS; const floDapps = EXPORTS;
@ -172,7 +172,12 @@
//general //general
lastTx: {}, lastTx: {},
//supernode (cloud list) //supernode (cloud list)
supernodes: {} supernodes: {
indexes: {
uri: null,
pubKey: null
}
}
} }
var obs_a = { var obs_a = {
//login credentials //login credentials
@ -252,8 +257,7 @@
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!startUpOptions.cloud) if (!startUpOptions.cloud)
return resolve("No cloud for this app"); return resolve("No cloud for this app");
const CLOUD_KEY = "floCloudAPI#" + floCloudAPI.SNStorageID; compactIDB.readData("lastTx", floCloudAPI.SNStorageID, DEFAULT.root).then(lastTx => {
compactIDB.readData("lastTx", CLOUD_KEY, DEFAULT.root).then(lastTx => {
var query_options = { sentOnly: true, pattern: floCloudAPI.SNStorageName }; var query_options = { sentOnly: true, pattern: floCloudAPI.SNStorageName };
if (typeof lastTx == 'number') //lastTx is tx count (*backward support) if (typeof lastTx == 'number') //lastTx is tx count (*backward support)
query_options.ignoreOld = lastTx; query_options.ignoreOld = lastTx;
@ -261,27 +265,25 @@
query_options.after = lastTx; query_options.after = lastTx;
//fetch data from flosight //fetch data from flosight
floBlockchainAPI.readData(floCloudAPI.SNStorageID, query_options).then(result => { floBlockchainAPI.readData(floCloudAPI.SNStorageID, query_options).then(result => {
compactIDB.readData("supernodes", CLOUD_KEY, DEFAULT.root).then(nodes => { for (var i = result.data.length - 1; i >= 0; i--) {
nodes = nodes || {}; var content = JSON.parse(result.data[i])[floCloudAPI.SNStorageName];
for (var i = result.data.length - 1; i >= 0; i--) { for (let sn in content.removeNodes)
var content = JSON.parse(result.data[i])[floCloudAPI.SNStorageName]; compactIDB.removeData("supernodes", sn, DEFAULT.root);
for (let sn in content.removeNodes) for (let sn in content.newNodes)
delete nodes[sn]; compactIDB.writeData("supernodes", content.newNodes[sn], sn, DEFAULT.root);
for (let sn in content.newNodes) for (let sn in content.updateNodes)
nodes[sn] = content.newNodes[sn]; compactIDB.readData("supernodes", sn, DEFAULT.root).then(r => {
for (let sn in content.updateNodes) r = r || {}
if (sn in nodes) //check if node is listed r.uri = content.updateNodes[sn];
nodes[sn].uri = content.updateNodes[sn]; compactIDB.writeData("supernodes", r, sn, DEFAULT.root);
} });
Promise.all([ }
compactIDB.writeData("lastTx", result.lastItem, CLOUD_KEY, DEFAULT.root), compactIDB.writeData("lastTx", result.lastItem, floCloudAPI.SNStorageID, DEFAULT.root);
compactIDB.writeData("supernodes", nodes, CLOUD_KEY, DEFAULT.root) compactIDB.readAllData("supernodes", DEFAULT.root).then(nodes => {
]).then(_ => { floCloudAPI.init(nodes)
floCloudAPI.init(nodes) .then(result => resolve("Loaded Supernode list\n" + result))
.then(result => resolve("Loaded Supernode list\n" + result)) .catch(error => reject(error))
.catch(error => reject(error)) })
}).catch(error => reject(error))
}).catch(error => reject(error))
}) })
}).catch(error => reject(error)) }).catch(error => reject(error))
}) })

View File

@ -6,9 +6,9 @@
<script id="floGlobals"> <script id="floGlobals">
/* Constants for FLO blockchain operations !!Make sure to add this at beginning!! */ /* Constants for FLO blockchain operations !!Make sure to add this at beginning!! */
const floGlobals = { const floGlobals = {
blockchain: "FLO_TEST", blockchain: "FLO",
adminID: "oKKHdK5uYAJ52U91sYsWhnEaEAAhZP779B", adminID: "FKAEdnPfjXLHSYwrXQu377ugN4tXU7VGdf",
application: "TEST_MODE_testnet", application: "TEST_MODE",
} }
</script> </script>
<script> <script>
@ -54,4 +54,4 @@
(use console) (use console)
</body> </body>
</html> </html>