Compare commits
No commits in common. "main" and "testing" have entirely different histories.
32
.github/workflows/push-dappbundle.yml
vendored
32
.github/workflows/push-dappbundle.yml
vendored
@ -1,32 +0,0 @@
|
||||
name: Workflow push to Dappbundle
|
||||
on: [push]
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Executing remote command
|
||||
uses: appleboy/ssh-action@v1.0.0
|
||||
with:
|
||||
host: ${{ secrets.R_HOST }}
|
||||
username: ${{ secrets.P_USERNAME }}
|
||||
password: ${{ secrets.P_PASSWORD }}
|
||||
port: ${{ secrets.SSH_PORT }}
|
||||
script: |
|
||||
if [ -d "${{ secrets.DEPLOYMENT_LOCATION}}/dappbundle" ]; then
|
||||
echo "Folder exists. Skipping Git clone."
|
||||
else
|
||||
echo "Folder does not exist. Cloning repository..."
|
||||
cd ${{ secrets.DEPLOYMENT_LOCATION}}/ && git clone https://github.com/ranchimall/dappbundle.git
|
||||
fi
|
||||
|
||||
if [ -d "${{ secrets.DEPLOYMENT_LOCATION}}/dappbundle/${{ github.event.repository.name }}" ]; then
|
||||
echo "Repository exists. Remove folder "
|
||||
rm -r "${{ secrets.DEPLOYMENT_LOCATION}}/dappbundle/${{ github.event.repository.name }}"
|
||||
fi
|
||||
|
||||
echo "Cloning repository..."
|
||||
cd ${{ secrets.DEPLOYMENT_LOCATION}}/dappbundle && git clone https://github.com/ranchimall/${{ github.event.repository.name }}
|
||||
|
||||
cd "${{ secrets.DEPLOYMENT_LOCATION}}/dappbundle/${{ github.event.repository.name }}" && rm -rf .gitattributes .git .github .gitignore
|
||||
cd ${{ secrets.DEPLOYMENT_LOCATION}}/dappbundle/ && git add . && git commit -m "Workflow updating files of ${{ github.event.repository.name }}" && git push "https://ranchimalldev:${{ secrets.RM_ACCESS_TOKEN }}@github.com/ranchimall/dappbundle.git"
|
||||
21
LICENCE
21
LICENCE
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Sai Raj
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
82
README.md
82
README.md
@ -1,82 +1,2 @@
|
||||
# BTC Wallet
|
||||
[](https://github.com/ranchimall/btcwallet/actions/workflows/push-dappbundle.yml)
|
||||
|
||||
BTC Wallet
|
||||
It is a web-based Bitcoin wallet and Bitcoin explorer that promotes self-custody by generating Bitcoin addresses and private keys locally on the user's device. If you are suspicious about internet monitoring, then open the URL, disconnect your computer from the internet, and then generate the Bitcoin address and private key.
|
||||
These are client-side scripts that can generate Bitcoin addresses, send Bitcoin transactions to the blockchain, and monitor Bitcoin data from the Bitcoin blockchain.
|
||||
|
||||
|
||||
### Live URL for BTC Wallet:
|
||||
*https://ranchimall.github.io/btcwallet/*
|
||||
|
||||
#### Do not forget to copy and save the private key in a safe place. This BTC wallet doesn't give a seed phrase but directly the original private key, which makes it more secure for the users to take full custody of their bitcoins.
|
||||
|
||||
#### Note:
|
||||
Seed phrases are English words and can be memorized by someone who is looking at your screen. Private keys are random characters that hide inside asterisk signs that make it difficult for anyone to look at them and memorize them.
|
||||
|
||||
|
||||
## Instructions to use
|
||||
|
||||
Note: BTC Wallet uses IndedxedDB for storing data, which means data is stored in the respective browser you used to open the web wallet. Data stored by one browser can't be accessed by other browsers.
|
||||
|
||||
## Functions:
|
||||
|
||||
### Generate BTC address
|
||||
Click on "Generate BTC address" to generate a new Bitcoin address with its private key. With the use of the "Copy" button, both the BTC address and private key can be copied to save it somewhere safe.
|
||||
|
||||
Note: Do not share your private key with anyone and keep it safe. Once lost a private key can't be recovered.
|
||||
|
||||
### Retrieve BTC address
|
||||
In case you have forgotten your Bitcoin address but still have the private key, you can retrieve the Bitcoin address. Simply enter the private key and click on the "Recover" button.
|
||||
|
||||
### Search BTC address or transaction ID (Bitcoin Explorer)
|
||||
Any Bitcoin address or a Bitcoin transaction id can be searched to fetch the blockchain data. Simply enter the Bitcoin address or the transaction id, press "Enter" or click on "Search" to fetch the blockchain transactions.
|
||||
|
||||
### Send
|
||||
i) The "Send" button can be used to send bitcoins to other Bitcoin addresses. <br>
|
||||
ii) Click on the "Send" button from the left menu bar <br>
|
||||
iii) Enter or paste the "Sender's Bitcoin address" <br>
|
||||
iv) Enter or paste the "Sender's Bitcoin private key" <br>
|
||||
v) Upon entering the private key, the balance of the address will reflect on the screen <br>
|
||||
vi) Enter the "Reciever's Bitcoin address" <br>
|
||||
vi) Enter the "amount" of bitcoin to be sent <br>
|
||||
vii) Amount can be entered in the form of BTC, USD, or INR <br>
|
||||
viii) Amount entered in USD or INR will automatically convert to the equivalent BTC amount <br>
|
||||
ix) Approximate fees will show up before making the transaction <br>
|
||||
x) Fees can be modified by the user. An increased fee increases the chance of transactions taking place faster <br>
|
||||
xi) Click on the "Send" button to initiate the transaction <br>
|
||||
xii) This will give the transaction id using which the transaction details and confirmation can be monitored <br>
|
||||
|
||||
#### Note: Multiple senders and multiple receiver addresses can be used to send Bitcoins to multiple receivers. For multiple senders, all their corresponding private keys will be required
|
||||
|
||||
#### Note: The fee is comparatively low than other Bitcoin wallets or other Exchange wallets because RanchiMall does not have any additional fees for any transaction.
|
||||
|
||||
|
||||
## Convert
|
||||
i) "Convert" is a special feature developed by RanchiMall which converts a FLO blockchain address to an equivalent Bitcoin address <br>
|
||||
ii) The same can be done with a Bitcoin address as well. A Bitcoin address can be converted to its equivalent FLO address <br>
|
||||
|
||||
### Why is "Converter" required
|
||||
i) RanchiMall has built all dapps on the FLO blockchain <br>
|
||||
ii) All the dapps require a FLO private key to be signed in <br>
|
||||
iii) Later RanchiMall developed a Bitcoin address sign-in architecture for its dapps <br>
|
||||
iv) If a user has a FLO address and he/she uses any of RanchiMall dapps, then using an equivalent Bitcoin address to sign in will also take the user to the same account which he/she signed into using their FLO private key.
|
||||
|
||||
### More about Converter
|
||||
i) Both the FLO or BTC address and the Private keys can be converted for each other <br>
|
||||
ii) This means a FLO address can have its equivalent BTC address and a BTC address can have its equivalent FLO address <br>
|
||||
iii) A FLO private key can be converted to its equivalent BTC address's private key <br>
|
||||
|
||||
#### Note: The pairing of this conversion will always remain the same. <br>
|
||||
a) A FLO blockchain address can have only one equivalent BTC address <br>
|
||||
b) A Bitcoin blockchain address can have only one equivalent FLO blockchain address <br>
|
||||
c) Along with the FLO or BTC address, their private keys can also be converted <br>
|
||||
|
||||
### How to use Converter
|
||||
i) Click on the "Convert" button on the homepage <br>
|
||||
ii) Click on "FLO" if you want to convert a FLO blockchain address or FLO private key to its equivalent BTC address or BTC private key <br>
|
||||
iii) Under the "Private key converter", enter the private key of the FLO address. This will convert the FLO private key to the equivalent BTC private key and BTC address <br>
|
||||
iv) Click on "BTC" if you want to convert a Bitcoin blockchain address or BTC private key to its equivalent FLO address or FLO private key <br>
|
||||
v) Under the "Address converter", enter the FLO address to get the equivalent BTC address and vice versa <br>
|
||||
|
||||
# btc-webwallet
|
||||
|
||||
|
||||
851
btcOperator.js
Normal file
851
btcOperator.js
Normal file
@ -0,0 +1,851 @@
|
||||
(function (EXPORTS) { //btcOperator v1.1.1
|
||||
/* BTC Crypto and API Operator */
|
||||
const btcOperator = EXPORTS;
|
||||
|
||||
//This library uses API provided by chain.so (https://chain.so/)
|
||||
const URL = "https://blockchain.info/";
|
||||
|
||||
const fetch_api = btcOperator.fetch = function (api, json_res = true) {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.debug(URL + api);
|
||||
fetch(URL + api).then(response => {
|
||||
if (response.ok) {
|
||||
(json_res ? response.json() : response.text())
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
} else {
|
||||
response.json()
|
||||
.then(result => reject(result))
|
||||
.catch(error => reject(error))
|
||||
}
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
};
|
||||
|
||||
const SATOSHI_IN_BTC = 1e8;
|
||||
|
||||
const util = btcOperator.util = {};
|
||||
|
||||
util.Sat_to_BTC = value => parseFloat((value / SATOSHI_IN_BTC).toFixed(8));
|
||||
util.BTC_to_Sat = value => parseInt(value * SATOSHI_IN_BTC);
|
||||
|
||||
function get_fee_rate() {
|
||||
return new Promise((resolve, reject) => {
|
||||
fetch('https://api.blockchain.info/mempool/fees').then(response => {
|
||||
if (response.ok)
|
||||
response.json()
|
||||
.then(result => resolve(util.Sat_to_BTC(result.regular)))
|
||||
.catch(error => reject(error));
|
||||
else
|
||||
reject(response);
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
const broadcastTx = btcOperator.broadcastTx = rawTxHex => new Promise((resolve, reject) => {
|
||||
let url = 'https://coinb.in/api/?uid=1&key=12345678901234567890123456789012&setmodule=bitcoin&request=sendrawtransaction';
|
||||
fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
body: "rawtx=" + rawTxHex
|
||||
}).then(response => {
|
||||
response.text().then(resultText => {
|
||||
let r = resultText.match(/<result>.*<\/result>/);
|
||||
if (!r)
|
||||
reject(resultText);
|
||||
else {
|
||||
r = r.pop().replace('<result>', '').replace('</result>', '');
|
||||
if (r == '1') {
|
||||
let txid = resultText.match(/<txid>.*<\/txid>/).pop().replace('<txid>', '').replace('</txid>', '');
|
||||
resolve(txid);
|
||||
} else if (r == '0') {
|
||||
let error = resultText.match(/<response>.*<\/response>/).pop().replace('<response>', '').replace('</response>', '');
|
||||
reject(decodeURIComponent(error.replace(/\+/g, " ")));
|
||||
} else reject(resultText);
|
||||
}
|
||||
}).catch(error => reject(error))
|
||||
}).catch(error => reject(error))
|
||||
});
|
||||
|
||||
Object.defineProperties(btcOperator, {
|
||||
newKeys: {
|
||||
get: () => {
|
||||
let r = coinjs.newKeys();
|
||||
r.segwitAddress = coinjs.segwitAddress(r.pubkey).address;
|
||||
r.bech32Address = coinjs.bech32Address(r.pubkey).address;
|
||||
return r;
|
||||
}
|
||||
},
|
||||
pubkey: {
|
||||
value: key => key.length >= 66 ? key : (key.length == 64 ? coinjs.newPubkey(key) : coinjs.wif2pubkey(key).pubkey)
|
||||
},
|
||||
address: {
|
||||
value: (key, prefix = undefined) => coinjs.pubkey2address(btcOperator.pubkey(key), prefix)
|
||||
},
|
||||
segwitAddress: {
|
||||
value: key => coinjs.segwitAddress(btcOperator.pubkey(key)).address
|
||||
},
|
||||
bech32Address: {
|
||||
value: key => coinjs.bech32Address(btcOperator.pubkey(key)).address
|
||||
}
|
||||
});
|
||||
|
||||
coinjs.compressed = true;
|
||||
|
||||
const verifyKey = btcOperator.verifyKey = function (addr, key) {
|
||||
if (!addr || !key)
|
||||
return undefined;
|
||||
switch (coinjs.addressDecode(addr).type) {
|
||||
case "standard":
|
||||
return btcOperator.address(key) === addr;
|
||||
case "multisig":
|
||||
return btcOperator.segwitAddress(key) === addr;
|
||||
case "bech32":
|
||||
return btcOperator.bech32Address(key) === addr;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const validateAddress = btcOperator.validateAddress = function (addr) {
|
||||
if (!addr)
|
||||
return undefined;
|
||||
let type = coinjs.addressDecode(addr).type;
|
||||
if (["standard", "multisig", "bech32", "multisigBech32"].includes(type))
|
||||
return type;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
btcOperator.multiSigAddress = function (pubKeys, minRequired, bech32 = true) {
|
||||
if (!Array.isArray(pubKeys))
|
||||
throw "pubKeys must be an array of public keys";
|
||||
else if (pubKeys.length < minRequired)
|
||||
throw "minimum required should be less than the number of pubKeys";
|
||||
if (bech32)
|
||||
return coinjs.pubkeys2MultisigAddressBech32(pubKeys, minRequired);
|
||||
else
|
||||
return coinjs.pubkeys2MultisigAddress(pubKeys, minRequired);
|
||||
}
|
||||
|
||||
//convert from one blockchain to another blockchain (target version)
|
||||
btcOperator.convert = {};
|
||||
|
||||
btcOperator.convert.wif = function (source_wif, target_version = coinjs.priv) {
|
||||
let keyHex = decodeLegacy(source_wif).hex;
|
||||
if (!keyHex || keyHex.length < 66 || !/01$/.test(keyHex))
|
||||
return null;
|
||||
else
|
||||
return encodeLegacy(keyHex, target_version);
|
||||
}
|
||||
|
||||
btcOperator.convert.legacy2legacy = function (source_addr, target_version = coinjs.pub) {
|
||||
let rawHex = decodeLegacy(source_addr).hex;
|
||||
if (!rawHex)
|
||||
return null;
|
||||
else
|
||||
return encodeLegacy(rawHex, target_version);
|
||||
}
|
||||
|
||||
btcOperator.convert.legacy2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) {
|
||||
let rawHex = decodeLegacy(source_addr).hex;
|
||||
if (!rawHex)
|
||||
return null;
|
||||
else
|
||||
return encodeBech32(rawHex, target_version, target_hrp);
|
||||
}
|
||||
|
||||
btcOperator.convert.bech2bech = function (source_addr, target_version = coinjs.bech32.version, target_hrp = coinjs.bech32.hrp) {
|
||||
let rawHex = decodeBech32(source_addr).hex;
|
||||
if (!rawHex)
|
||||
return null;
|
||||
else
|
||||
return encodeBech32(rawHex, target_version, target_hrp);
|
||||
}
|
||||
|
||||
btcOperator.convert.bech2legacy = function (source_addr, target_version = coinjs.pub) {
|
||||
let rawHex = decodeBech32(source_addr).hex;
|
||||
if (!rawHex)
|
||||
return null;
|
||||
else
|
||||
return encodeLegacy(rawHex, target_version);
|
||||
}
|
||||
|
||||
function decodeLegacy(source) {
|
||||
var decode = coinjs.base58decode(source);
|
||||
var raw = decode.slice(0, decode.length - 4),
|
||||
checksum = decode.slice(decode.length - 4);
|
||||
var hash = Crypto.SHA256(Crypto.SHA256(raw, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
if (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3])
|
||||
return null;
|
||||
let version = raw.shift();
|
||||
return {
|
||||
version: version,
|
||||
hex: Crypto.util.bytesToHex(raw)
|
||||
}
|
||||
}
|
||||
|
||||
function encodeLegacy(hex, version) {
|
||||
var bytes = Crypto.util.hexToBytes(hex);
|
||||
bytes.unshift(version);
|
||||
var hash = Crypto.SHA256(Crypto.SHA256(bytes, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
var checksum = hash.slice(0, 4);
|
||||
return coinjs.base58encode(bytes.concat(checksum));
|
||||
}
|
||||
|
||||
function decodeBech32(source) {
|
||||
let decode = coinjs.bech32_decode(source);
|
||||
if (!decode)
|
||||
return null;
|
||||
var raw = decode.data;
|
||||
let version = raw.shift();
|
||||
raw = coinjs.bech32_convert(raw, 5, 8, false);
|
||||
return {
|
||||
hrp: decode.hrp,
|
||||
version: version,
|
||||
hex: Crypto.util.bytesToHex(raw)
|
||||
}
|
||||
}
|
||||
|
||||
function encodeBech32(hex, version, hrp) {
|
||||
var bytes = Crypto.util.hexToBytes(hex);
|
||||
bytes = coinjs.bech32_convert(bytes, 8, 5, true);
|
||||
bytes.unshift(version)
|
||||
return coinjs.bech32_encode(hrp, bytes);
|
||||
}
|
||||
|
||||
//BTC blockchain APIs
|
||||
|
||||
btcOperator.getBalance = addr => new Promise((resolve, reject) => {
|
||||
fetch_api(`q/addressbalance/${addr}`)
|
||||
.then(result => resolve(util.Sat_to_BTC(result)))
|
||||
.catch(error => reject(error))
|
||||
});
|
||||
|
||||
const BASE_TX_SIZE = 12,
|
||||
BASE_INPUT_SIZE = 41,
|
||||
LEGACY_INPUT_SIZE = 107,
|
||||
BECH32_INPUT_SIZE = 27,
|
||||
BECH32_MULTISIG_INPUT_SIZE = 35,
|
||||
SEGWIT_INPUT_SIZE = 59,
|
||||
MULTISIG_INPUT_SIZE_ES = 351,
|
||||
BASE_OUTPUT_SIZE = 9,
|
||||
LEGACY_OUTPUT_SIZE = 25,
|
||||
BECH32_OUTPUT_SIZE = 23,
|
||||
BECH32_MULTISIG_OUTPUT_SIZE = 34,
|
||||
SEGWIT_OUTPUT_SIZE = 23;
|
||||
|
||||
function _redeemScript(addr, key) {
|
||||
let decode = coinjs.addressDecode(addr);
|
||||
switch (decode.type) {
|
||||
case "standard":
|
||||
return false;
|
||||
case "multisig":
|
||||
return key ? coinjs.segwitAddress(btcOperator.pubkey(key)).redeemscript : null;
|
||||
case "bech32":
|
||||
return decode.redeemscript;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function _sizePerInput(addr, rs) {
|
||||
switch (coinjs.addressDecode(addr).type) {
|
||||
case "standard":
|
||||
return BASE_INPUT_SIZE + LEGACY_INPUT_SIZE;
|
||||
case "bech32":
|
||||
return BASE_INPUT_SIZE + BECH32_INPUT_SIZE;
|
||||
case "multisigBech32":
|
||||
return BASE_INPUT_SIZE + BECH32_MULTISIG_INPUT_SIZE;
|
||||
case "multisig":
|
||||
switch (coinjs.script().decodeRedeemScript(rs).type) {
|
||||
case "segwit__":
|
||||
return BASE_INPUT_SIZE + SEGWIT_INPUT_SIZE;
|
||||
case "multisig__":
|
||||
return BASE_INPUT_SIZE + MULTISIG_INPUT_SIZE_ES;
|
||||
default:
|
||||
return null;
|
||||
};
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function _sizePerOutput(addr) {
|
||||
switch (coinjs.addressDecode(addr).type) {
|
||||
case "standard":
|
||||
return BASE_OUTPUT_SIZE + LEGACY_OUTPUT_SIZE;
|
||||
case "bech32":
|
||||
return BASE_OUTPUT_SIZE + BECH32_OUTPUT_SIZE;
|
||||
case "multisigBech32":
|
||||
return BASE_OUTPUT_SIZE + BECH32_MULTISIG_OUTPUT_SIZE;
|
||||
case "multisig":
|
||||
return BASE_OUTPUT_SIZE + SEGWIT_OUTPUT_SIZE;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function validateTxParameters(parameters) {
|
||||
let invalids = [];
|
||||
//sender-ids
|
||||
if (parameters.senders) {
|
||||
if (!Array.isArray(parameters.senders))
|
||||
parameters.senders = [parameters.senders];
|
||||
parameters.senders.forEach(id => !validateAddress(id) ? invalids.push(id) : null);
|
||||
if (invalids.length)
|
||||
throw "Invalid senders:" + invalids;
|
||||
}
|
||||
if (parameters.privkeys) {
|
||||
if (!Array.isArray(parameters.privkeys))
|
||||
parameters.privkeys = [parameters.privkeys];
|
||||
if (parameters.senders.length != parameters.privkeys.length)
|
||||
throw "Array length for senders and privkeys should be equal";
|
||||
parameters.senders.forEach((id, i) => {
|
||||
let key = parameters.privkeys[i];
|
||||
if (!verifyKey(id, key)) //verify private-key
|
||||
invalids.push(id);
|
||||
if (key.length === 64) //convert Hex to WIF if needed
|
||||
parameters.privkeys[i] = coinjs.privkey2wif(key);
|
||||
});
|
||||
if (invalids.length)
|
||||
throw "Invalid private key for address:" + invalids;
|
||||
}
|
||||
//receiver-ids (and change-id)
|
||||
if (!Array.isArray(parameters.receivers))
|
||||
parameters.receivers = [parameters.receivers];
|
||||
parameters.receivers.forEach(id => !validateAddress(id) ? invalids.push(id) : null);
|
||||
if (invalids.length)
|
||||
throw "Invalid receivers:" + invalids;
|
||||
if (parameters.change_address && !validateAddress(parameters.change_address))
|
||||
throw "Invalid change_address:" + parameters.change_address;
|
||||
//fee and amounts
|
||||
if ((typeof parameters.fee !== "number" || parameters.fee <= 0) && parameters.fee !== null) //fee = null (auto calc)
|
||||
throw "Invalid fee:" + parameters.fee;
|
||||
if (!Array.isArray(parameters.amounts))
|
||||
parameters.amounts = [parameters.amounts];
|
||||
if (parameters.receivers.length != parameters.amounts.length)
|
||||
throw "Array length for receivers and amounts should be equal";
|
||||
parameters.amounts.forEach(a => typeof a !== "number" || a <= 0 ? invalids.push(a) : null);
|
||||
if (invalids.length)
|
||||
throw "Invalid amounts:" + invalids;
|
||||
//return
|
||||
return parameters;
|
||||
}
|
||||
|
||||
function createTransaction(senders, redeemScripts, receivers, amounts, fee, change_address, fee_from_receiver) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let total_amount = parseFloat(amounts.reduce((t, a) => t + a, 0).toFixed(8));
|
||||
const tx = coinjs.transaction();
|
||||
let output_size = addOutputs(tx, receivers, amounts, change_address);
|
||||
addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver).then(result => {
|
||||
if (result.change_amount > 0 && result.change_amount > result.fee) //add change amount if any (ignore dust change)
|
||||
tx.outs[tx.outs.length - 1].value = util.BTC_to_Sat(result.change_amount); //values are in satoshi
|
||||
if (fee_from_receiver) { //deduce fee from receivers if fee_from_receiver
|
||||
let fee_remaining = util.BTC_to_Sat(result.fee);
|
||||
for (let i = 0; i < tx.outs.length - 1 && fee_remaining > 0; i++) {
|
||||
if (fee_remaining < tx.outs[i].value) {
|
||||
tx.outs[i].value -= fee_remaining;
|
||||
fee_remaining = 0;
|
||||
} else {
|
||||
fee_remaining -= tx.outs[i].value;
|
||||
tx.outs[i].value = 0;
|
||||
}
|
||||
}
|
||||
if (fee_remaining > 0)
|
||||
return reject("Send amount is less than fee");
|
||||
|
||||
}
|
||||
tx.outs = tx.outs.filter(o => o.value != 0); //remove all output with value 0
|
||||
result.output_size = output_size;
|
||||
result.output_amount = total_amount - (fee_from_receiver ? result.fee : 0);
|
||||
result.total_size = BASE_TX_SIZE + output_size + result.input_size;
|
||||
result.transaction = tx;
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
function addInputs(tx, senders, redeemScripts, total_amount, fee, output_size, fee_from_receiver) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (fee !== null) {
|
||||
addUTXOs(tx, senders, redeemScripts, fee_from_receiver ? total_amount : total_amount + fee, false).then(result => {
|
||||
result.fee = fee;
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
} else {
|
||||
get_fee_rate().then(fee_rate => {
|
||||
let net_fee = BASE_TX_SIZE * fee_rate;
|
||||
net_fee += (output_size * fee_rate);
|
||||
(fee_from_receiver ?
|
||||
addUTXOs(tx, senders, redeemScripts, total_amount, false) :
|
||||
addUTXOs(tx, senders, redeemScripts, total_amount + net_fee, fee_rate)
|
||||
).then(result => {
|
||||
result.fee = parseFloat((net_fee + (result.input_size * fee_rate)).toFixed(8));
|
||||
result.fee_rate = fee_rate;
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
}).catch(error => reject(error))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
required_amount = parseFloat(required_amount.toFixed(8));
|
||||
if (typeof rec_args.n === "undefined") {
|
||||
rec_args.n = 0;
|
||||
rec_args.input_size = 0;
|
||||
rec_args.input_amount = 0;
|
||||
}
|
||||
if (required_amount <= 0)
|
||||
return resolve({
|
||||
input_size: rec_args.input_size,
|
||||
input_amount: rec_args.input_amount,
|
||||
change_amount: required_amount * -1 //required_amount will be -ve of change_amount
|
||||
});
|
||||
else if (rec_args.n >= senders.length)
|
||||
return reject("Insufficient Balance");
|
||||
let addr = senders[rec_args.n],
|
||||
rs = redeemScripts[rec_args.n];
|
||||
let addr_type = coinjs.addressDecode(addr).type;
|
||||
let size_per_input = _sizePerInput(addr, rs);
|
||||
fetch_api(`unspent?active=${addr}`).then(result => {
|
||||
let utxos = result.unspent_outputs;
|
||||
console.debug("add-utxo", addr, rs, required_amount, utxos);
|
||||
for (let i = 0; i < utxos.length && required_amount > 0; i++) {
|
||||
if (!utxos[i].confirmations) //ignore unconfirmed utxo
|
||||
continue;
|
||||
var script;
|
||||
if (!rs || !rs.length) //legacy script
|
||||
script = utxos[i].script;
|
||||
else if (((rs.match(/^00/) && rs.length == 44)) || (rs.length == 40 && rs.match(/^[a-f0-9]+$/gi)) || addr_type === 'multisigBech32') {
|
||||
//redeemScript for segwit/bech32 and multisig (bech32)
|
||||
let s = coinjs.script();
|
||||
s.writeBytes(Crypto.util.hexToBytes(rs));
|
||||
s.writeOp(0);
|
||||
s.writeBytes(coinjs.numToBytes(utxos[i].value.toFixed(0), 8));
|
||||
script = Crypto.util.bytesToHex(s.buffer);
|
||||
} else //redeemScript for multisig (segwit)
|
||||
script = rs;
|
||||
tx.addinput(utxos[i].tx_hash_big_endian, utxos[i].tx_output_n, script, 0xfffffffd /*sequence*/); //0xfffffffd for Replace-by-fee
|
||||
//update track values
|
||||
rec_args.input_size += size_per_input;
|
||||
rec_args.input_amount += util.Sat_to_BTC(utxos[i].value);
|
||||
required_amount -= util.Sat_to_BTC(utxos[i].value);
|
||||
if (fee_rate) //automatic fee calculation (dynamic)
|
||||
required_amount += size_per_input * fee_rate;
|
||||
}
|
||||
rec_args.n += 1;
|
||||
addUTXOs(tx, senders, redeemScripts, required_amount, fee_rate, rec_args)
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
function addOutputs(tx, receivers, amounts, change_address) {
|
||||
let size = 0;
|
||||
for (let i in receivers) {
|
||||
tx.addoutput(receivers[i], amounts[i]);
|
||||
size += _sizePerOutput(receivers[i]);
|
||||
}
|
||||
tx.addoutput(change_address, 0);
|
||||
size += _sizePerOutput(change_address);
|
||||
return size;
|
||||
}
|
||||
|
||||
/*
|
||||
function autoFeeCalc(tx) {
|
||||
return new Promise((resolve, reject) => {
|
||||
get_fee_rate().then(fee_rate => {
|
||||
let tx_size = tx.size();
|
||||
for (var i = 0; i < this.ins.length; i++)
|
||||
switch (tx.extractScriptKey(i).type) {
|
||||
case 'scriptpubkey':
|
||||
tx_size += SIGN_SIZE;
|
||||
break;
|
||||
case 'segwit':
|
||||
case 'multisig':
|
||||
tx_size += SIGN_SIZE * 0.25;
|
||||
break;
|
||||
default:
|
||||
console.warn('Unknown script-type');
|
||||
tx_size += SIGN_SIZE;
|
||||
}
|
||||
resolve(tx_size * fee_rate);
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
function editFee(tx, current_fee, target_fee, index = -1) {
|
||||
//values are in satoshi
|
||||
index = parseInt(index >= 0 ? index : tx.outs.length - index);
|
||||
if (index < 0 || index >= tx.outs.length)
|
||||
throw "Invalid index";
|
||||
let edit_value = parseInt(current_fee - target_fee), //rip of any decimal places
|
||||
current_value = tx.outs[index].value; //could be BigInterger
|
||||
if (edit_value < 0 && edit_value > current_value)
|
||||
throw "Insufficient value at vout";
|
||||
tx.outs[index].value = current_value instanceof BigInteger ?
|
||||
current_value.add(new BigInteger('' + edit_value)) : parseInt(current_value + edit_value);
|
||||
}
|
||||
*/
|
||||
|
||||
btcOperator.sendTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
createSignedTx(senders, privkeys, receivers, amounts, fee, options).then(result => {
|
||||
debugger;
|
||||
broadcastTx(result.transaction.serialize())
|
||||
.then(txid => resolve(txid))
|
||||
.catch(error => reject(error));
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
const createSignedTx = btcOperator.createSignedTx = function (senders, privkeys, receivers, amounts, fee = null, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
({
|
||||
senders,
|
||||
privkeys,
|
||||
receivers,
|
||||
amounts
|
||||
} = validateTxParameters({
|
||||
senders,
|
||||
privkeys,
|
||||
receivers,
|
||||
amounts,
|
||||
fee,
|
||||
change_address: options.change_address
|
||||
}));
|
||||
} catch (e) {
|
||||
return reject(e)
|
||||
}
|
||||
let redeemScripts = [],
|
||||
wif_keys = [];
|
||||
for (let i in senders) {
|
||||
let rs = _redeemScript(senders[i], privkeys[i]); //get redeem-script (segwit/bech32)
|
||||
redeemScripts.push(rs);
|
||||
rs === false ? wif_keys.unshift(privkeys[i]) : wif_keys.push(privkeys[i]); //sorting private-keys (wif)
|
||||
}
|
||||
if (redeemScripts.includes(null)) //TODO: segwit
|
||||
return reject("Unable to get redeem-script");
|
||||
//create transaction
|
||||
createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => {
|
||||
let tx = result.transaction;
|
||||
console.debug("Unsigned:", tx.serialize());
|
||||
new Set(wif_keys).forEach(key => console.debug("Signing key:", key, tx.sign(key, 1 /*sighashtype*/))); //Sign the tx using private key WIF
|
||||
console.debug("Signed:", tx.serialize());
|
||||
resolve(result);
|
||||
}).catch(error => reject(error));
|
||||
})
|
||||
}
|
||||
|
||||
btcOperator.createTx = function (senders, receivers, amounts, fee = null, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
({
|
||||
senders,
|
||||
receivers,
|
||||
amounts
|
||||
} = validateTxParameters({
|
||||
senders,
|
||||
receivers,
|
||||
amounts,
|
||||
fee,
|
||||
change_address: options.change_address
|
||||
}));
|
||||
} catch (e) {
|
||||
return reject(e)
|
||||
}
|
||||
let redeemScripts = senders.map(id => _redeemScript(id));
|
||||
if (redeemScripts.includes(null)) //TODO: segwit
|
||||
return reject("Unable to get redeem-script");
|
||||
//create transaction
|
||||
createTransaction(senders, redeemScripts, receivers, amounts, fee, options.change_address || senders[0], options.fee_from_receiver).then(result => {
|
||||
result.tx_hex = result.transaction.serialize();
|
||||
delete result.transaction;
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
btcOperator.createMultiSigTx = function (sender, redeemScript, receivers, amounts, fee = null, options = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
//validate tx parameters
|
||||
let addr_type = validateAddress(sender);
|
||||
if (!(["multisig", "multisigBech32"].includes(addr_type)))
|
||||
return reject("Invalid sender (multisig):" + sender);
|
||||
else {
|
||||
let script = coinjs.script();
|
||||
let decode = (addr_type == "multisig") ?
|
||||
script.decodeRedeemScript(redeemScript) :
|
||||
script.decodeRedeemScriptBech32(redeemScript);
|
||||
if (!decode || decode.address !== sender)
|
||||
return reject("Invalid redeem-script");
|
||||
}
|
||||
try {
|
||||
({
|
||||
receivers,
|
||||
amounts
|
||||
} = validateTxParameters({
|
||||
receivers,
|
||||
amounts,
|
||||
fee,
|
||||
change_address: options.change_address
|
||||
}));
|
||||
} catch (e) {
|
||||
return reject(e)
|
||||
}
|
||||
//create transaction
|
||||
createTransaction([sender], [redeemScript], receivers, amounts, fee, options.change_address || sender, options.fee_from_receiver).then(result => {
|
||||
result.tx_hex = result.transaction.serialize();
|
||||
delete result.transaction;
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
function deserializeTx(tx) {
|
||||
if (typeof tx === 'string' || Array.isArray(tx)) {
|
||||
try {
|
||||
tx = coinjs.transaction().deserialize(tx);
|
||||
} catch {
|
||||
throw "Invalid transaction hex";
|
||||
}
|
||||
} else if (typeof tx !== 'object' || typeof tx.sign !== 'function')
|
||||
throw "Invalid transaction object";
|
||||
return tx;
|
||||
}
|
||||
|
||||
btcOperator.signTx = function (tx, privkeys, sighashtype = 1) {
|
||||
tx = deserializeTx(tx);
|
||||
if (!Array.isArray(privkeys))
|
||||
privkeys = [privkeys];
|
||||
for (let i in privkeys)
|
||||
if (privkeys[i].length === 64)
|
||||
privkeys[i] = coinjs.privkey2wif(privkeys[i]);
|
||||
new Set(privkeys).forEach(key => tx.sign(key, sighashtype)); //Sign the tx using private key WIF
|
||||
return tx.serialize();
|
||||
}
|
||||
|
||||
const checkSigned = btcOperator.checkSigned = function (tx, bool = true) {
|
||||
tx = deserializeTx(tx);
|
||||
let n = [];
|
||||
for (let i in tx.ins) {
|
||||
var s = tx.extractScriptKey(i);
|
||||
if (s['type'] !== 'multisig' && s['type'] !== 'multisig_bech32')
|
||||
n.push(s.signed == 'true' || (tx.witness[i] && tx.witness[i].length == 2))
|
||||
else {
|
||||
var rs = coinjs.script().decodeRedeemScript(s.script); //will work for bech32 too, as only address is diff
|
||||
let x = {
|
||||
s: s['signatures'],
|
||||
r: rs['signaturesRequired'],
|
||||
t: rs['pubkeys'].length
|
||||
};
|
||||
if (x.r > x.t)
|
||||
throw "signaturesRequired is more than publicKeys";
|
||||
else if (x.s < x.r)
|
||||
n.push(x);
|
||||
else
|
||||
n.push(true);
|
||||
}
|
||||
}
|
||||
return bool ? !(n.filter(x => x !== true).length) : n;
|
||||
}
|
||||
|
||||
btcOperator.checkIfSameTx = function (tx1, tx2) {
|
||||
tx1 = deserializeTx(tx1);
|
||||
tx2 = deserializeTx(tx2);
|
||||
if (tx1.ins.length !== tx2.ins.length || tx1.outs.length !== tx2.outs.length)
|
||||
return false;
|
||||
for (let i = 0; i < tx1.ins.length; i++)
|
||||
if (tx1.ins[i].outpoint.hash !== tx2.ins[i].outpoint.hash || tx1.ins[i].outpoint.index !== tx2.ins[i].outpoint.index)
|
||||
return false;
|
||||
for (let i = 0; i < tx2.ins.length; i++)
|
||||
if (tx1.outs[i].value !== tx2.outs[i].value || Crypto.util.bytesToHex(tx1.outs[i].script.buffer) !== Crypto.util.bytesToHex(tx2.outs[i].script.buffer))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
const getTxOutput = (txid, i) => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawtx/${txid}`)
|
||||
.then(result => resolve(result.out[i]))
|
||||
.catch(error => reject(error))
|
||||
});
|
||||
|
||||
btcOperator.parseTransaction = function (tx) {
|
||||
return new Promise((resolve, reject) => {
|
||||
tx = deserializeTx(tx);
|
||||
let result = {};
|
||||
let promises = [];
|
||||
//Parse Inputs
|
||||
for (let i = 0; i < tx.ins.length; i++)
|
||||
promises.push(getTxOutput(tx.ins[i].outpoint.hash, tx.ins[i].outpoint.index));
|
||||
Promise.all(promises).then(inputs => {
|
||||
result.inputs = inputs.map(inp => Object({
|
||||
address: inp.addr,
|
||||
value: util.Sat_to_BTC(inp.value)
|
||||
}));
|
||||
let signed = checkSigned(tx, false);
|
||||
result.inputs.forEach((inp, i) => inp.signed = signed[i]);
|
||||
//Parse Outputs
|
||||
result.outputs = tx.outs.map(out => {
|
||||
var address;
|
||||
switch (out.script.chunks[0]) {
|
||||
case 0: //bech32, multisig-bech32
|
||||
address = encodeBech32(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.bech32.version, coinjs.bech32.hrp);
|
||||
break;
|
||||
case 169: //segwit, multisig-segwit
|
||||
address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[1]), coinjs.multisig);
|
||||
break;
|
||||
case 118: //legacy
|
||||
address = encodeLegacy(Crypto.util.bytesToHex(out.script.chunks[2]), coinjs.pub);
|
||||
}
|
||||
return {
|
||||
address,
|
||||
value: util.Sat_to_BTC(out.value)
|
||||
}
|
||||
});
|
||||
//Parse Totals
|
||||
result.total_input = parseFloat(result.inputs.reduce((a, inp) => a += inp.value, 0).toFixed(8));
|
||||
result.total_output = parseFloat(result.outputs.reduce((a, out) => a += out.value, 0).toFixed(8));
|
||||
result.fee = parseFloat((result.total_input - result.total_output).toFixed(8));
|
||||
resolve(result);
|
||||
}).catch(error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
btcOperator.transactionID = function (tx) {
|
||||
tx = deserializeTx(tx);
|
||||
let clone = coinjs.clone(tx);
|
||||
clone.witness = null;
|
||||
let raw_bytes = Crypto.util.hexToBytes(clone.serialize());
|
||||
let txid = Crypto.SHA256(Crypto.SHA256(raw_bytes, { asBytes: true }), { asBytes: true }).reverse();
|
||||
return Crypto.util.bytesToHex(txid);
|
||||
}
|
||||
|
||||
const getLatestBlock = btcOperator.getLatestBlock = () => new Promise((resolve, reject) => {
|
||||
fetch_api(`q/getblockcount`)
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
})
|
||||
|
||||
btcOperator.getTx = txid => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawtx/${txid}`).then(result => {
|
||||
getLatestBlock().then(latest_block => resolve({
|
||||
block: result.block_height,
|
||||
txid: result.hash,
|
||||
time: result.time * 1000,
|
||||
confirmations: result.block_height === null ? 0 : latest_block - result.block_height, //calculate confirmations using latest block number as api doesnt relay it
|
||||
size: result.size,
|
||||
fee: util.Sat_to_BTC(result.fee),
|
||||
inputs: result.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })),
|
||||
total_input_value: util.Sat_to_BTC(result.inputs.reduce((a, i) => a + i.prev_out.value, 0)),
|
||||
outputs: result.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })),
|
||||
total_output_value: util.Sat_to_BTC(result.out.reduce((a, o) => a += o.value, 0)),
|
||||
}))
|
||||
}).catch(error => reject(error))
|
||||
});
|
||||
|
||||
btcOperator.getTx.hex = txid => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawtx/${txid}?format=hex`, false)
|
||||
.then(result => resolve(result))
|
||||
.catch(error => reject(error))
|
||||
})
|
||||
|
||||
btcOperator.getAddressData = address => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawaddr/${address}`).then(data => {
|
||||
let details = {};
|
||||
details.balance = util.Sat_to_BTC(data.final_balance);
|
||||
details.address = data.address;
|
||||
details.txs = data.txs.map(tx => {
|
||||
let d = {
|
||||
txid: tx.hash,
|
||||
time: tx.time * 1000, //s to ms
|
||||
block: tx.block_height,
|
||||
}
|
||||
//sender list
|
||||
d.tx_senders = {};
|
||||
tx.inputs.forEach(i => {
|
||||
if (i.prev_out.addr in d.tx_senders)
|
||||
d.tx_senders[i.prev_out.addr] += i.prev_out.value;
|
||||
else d.tx_senders[i.prev_out.addr] = i.prev_out.value;
|
||||
});
|
||||
d.tx_input_value = 0;
|
||||
for (let s in d.tx_senders) {
|
||||
let val = d.tx_senders[s];
|
||||
d.tx_senders[s] = util.Sat_to_BTC(val);
|
||||
d.tx_input_value += val;
|
||||
}
|
||||
d.tx_input_value = util.Sat_to_BTC(d.tx_input_value);
|
||||
//receiver list
|
||||
d.tx_receivers = {};
|
||||
tx.out.forEach(o => {
|
||||
if (o.addr in d.tx_receivers)
|
||||
d.tx_receivers[o.addr] += o.value;
|
||||
else d.tx_receivers[o.addr] = o.value;
|
||||
});
|
||||
d.tx_output_value = 0;
|
||||
for (let r in d.tx_receivers) {
|
||||
let val = d.tx_receivers[r];
|
||||
d.tx_receivers[r] = util.Sat_to_BTC(val);
|
||||
d.tx_output_value += val;
|
||||
}
|
||||
d.tx_output_value = util.Sat_to_BTC(d.tx_output_value);
|
||||
d.tx_fee = util.Sat_to_BTC(tx.fee);
|
||||
//tx type
|
||||
if (tx.result > 0) { //net > 0, balance inc => type=in
|
||||
d.type = "in";
|
||||
d.amount = util.Sat_to_BTC(tx.result);
|
||||
d.sender = Object.keys(d.tx_senders).filter(s => s !== address);
|
||||
} else if (Object.keys(d.tx_receivers).some(r => r !== address)) { //net < 0, balance dec & receiver present => type=out
|
||||
d.type = "out";
|
||||
d.amount = util.Sat_to_BTC(tx.result * -1);
|
||||
d.receiver = Object.keys(d.tx_receivers).filter(r => r !== address);
|
||||
d.fee = d.tx_fee;
|
||||
} else { //net < 0 (fee) & no other id in receiver list => type=self
|
||||
d.type = "self";
|
||||
d.amount = d.tx_receivers[address];
|
||||
d.address = address
|
||||
}
|
||||
return d;
|
||||
})
|
||||
resolve(details);
|
||||
}).catch(error => reject(error))
|
||||
});
|
||||
|
||||
btcOperator.getBlock = block => new Promise((resolve, reject) => {
|
||||
fetch_api(`rawblock/${block}`).then(result => resolve({
|
||||
height: result.height,
|
||||
hash: result.hash,
|
||||
merkle_root: result.mrkl_root,
|
||||
prev_block: result.prev_block,
|
||||
next_block: result.next_block[0],
|
||||
size: result.size,
|
||||
time: result.time * 1000, //s to ms
|
||||
txs: result.tx.map(t => Object({
|
||||
fee: t.fee,
|
||||
size: t.size,
|
||||
inputs: t.inputs.map(i => Object({ address: i.prev_out.addr, value: util.Sat_to_BTC(i.prev_out.value) })),
|
||||
total_input_value: util.Sat_to_BTC(t.inputs.reduce((a, i) => a + i.prev_out.value, 0)),
|
||||
outputs: t.out.map(o => Object({ address: o.addr, value: util.Sat_to_BTC(o.value) })),
|
||||
total_output_value: util.Sat_to_BTC(t.out.reduce((a, o) => a += o.value, 0)),
|
||||
}))
|
||||
|
||||
})).catch(error => reject(error))
|
||||
});
|
||||
|
||||
})('object' === typeof module ? module.exports : window.btcOperator = {});
|
||||
12
components.js
Normal file
12
components.js
Normal file
File diff suppressed because one or more lines are too long
396
css/main.css
396
css/main.css
@ -20,13 +20,14 @@ body {
|
||||
--text-color: 20, 20, 20;
|
||||
--foreground-color: 252, 253, 255;
|
||||
--background-color: 241, 243, 248;
|
||||
--danger-color: rgb(225, 58, 58);
|
||||
--danger-color: rgb(255, 75, 75);
|
||||
--green: #1cad59;
|
||||
--yellow: rgb(255, 207, 65);
|
||||
--yellow: rgb(220, 165, 0);
|
||||
scrollbar-width: thin;
|
||||
scrollbar-gutter: stable;
|
||||
color: rgba(var(--text-color), 1);
|
||||
background-color: rgba(var(--background-color), 1);
|
||||
transition: background-color 0.3s;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@ -46,6 +47,21 @@ body[data-theme=dark] sm-popup::part(popup) {
|
||||
background-color: rgba(var(--foreground-color), 1);
|
||||
}
|
||||
|
||||
h1, h1 > *,
|
||||
h2,
|
||||
h2 > *,
|
||||
h3,
|
||||
h3 > *,
|
||||
h4,
|
||||
h4 > *,
|
||||
h5,
|
||||
h5 > *,
|
||||
h6,
|
||||
h6 > * {
|
||||
font-weight: 400;
|
||||
font-family: "Calistoga", cursive;
|
||||
}
|
||||
|
||||
p,
|
||||
strong {
|
||||
font-size: 0.9rem;
|
||||
@ -71,8 +87,15 @@ a:focus-visible {
|
||||
box-shadow: 0 0 0 0.1rem rgba(var(--text-color), 1) inset;
|
||||
}
|
||||
|
||||
button,
|
||||
.button {
|
||||
a.button {
|
||||
padding: 0.4rem 0.6rem;
|
||||
border-radius: 0.3rem;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
user-select: none;
|
||||
@ -87,26 +110,22 @@ button,
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
padding: 0.8rem;
|
||||
border-radius: 0.5rem;
|
||||
border-radius: 0.3rem;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
button:focus-visible,
|
||||
.button:focus-visible {
|
||||
button:focus-visible {
|
||||
outline: var(--accent-color) solid medium;
|
||||
}
|
||||
button:not(:disabled),
|
||||
.button:not(:disabled) {
|
||||
button:not(:disabled) {
|
||||
color: var(--accent-color);
|
||||
cursor: pointer;
|
||||
}
|
||||
button .icon,
|
||||
.button .icon {
|
||||
button .icon {
|
||||
fill: var(--accent-color);
|
||||
}
|
||||
|
||||
.button {
|
||||
display: inline-flex;
|
||||
background-color: rgba(var(--text-color), 0.06);
|
||||
}
|
||||
.button--primary, .button--danger {
|
||||
@ -124,12 +143,6 @@ button .icon,
|
||||
.button--small {
|
||||
padding: 0.4rem 0.5rem;
|
||||
}
|
||||
.button--colored {
|
||||
color: var(--accent-color) !important;
|
||||
}
|
||||
.button--colored .icon {
|
||||
fill: var(--accent-color);
|
||||
}
|
||||
|
||||
.cta {
|
||||
text-transform: uppercase;
|
||||
@ -169,17 +182,14 @@ a:any-link:focus-visible {
|
||||
|
||||
details summary {
|
||||
display: flex;
|
||||
gap: 0.3rem;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
user-select: none;
|
||||
cursor: pointer;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
color: var(--accent-color);
|
||||
}
|
||||
details summary .down-arrow {
|
||||
fill: var(--accent-color);
|
||||
}
|
||||
|
||||
details[open] summary {
|
||||
margin-bottom: 1rem;
|
||||
@ -191,7 +201,7 @@ details[open] > summary .down-arrow {
|
||||
sm-input,
|
||||
sm-textarea {
|
||||
width: 100%;
|
||||
--border-radius: 0.5rem;
|
||||
--border-radius: 0.4rem;
|
||||
--background-color: rgba(var(--foreground-color), 1);
|
||||
}
|
||||
sm-input button .icon,
|
||||
@ -234,13 +244,13 @@ sm-option {
|
||||
sm-chips {
|
||||
--gap: 0;
|
||||
background-color: rgba(var(--text-color), 0.06);
|
||||
border-radius: 0.5rem;
|
||||
border-radius: 0.3rem;
|
||||
padding: 0.3rem;
|
||||
}
|
||||
|
||||
sm-chip {
|
||||
font-size: 0.9rem;
|
||||
--border-radius: 0.3rem;
|
||||
--border-radius: 0.2rem;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
user-select: none;
|
||||
@ -250,10 +260,6 @@ sm-chip[selected] {
|
||||
--background: var(--accent-color);
|
||||
}
|
||||
|
||||
sm-notifications {
|
||||
z-index: 100000;
|
||||
}
|
||||
|
||||
ul,
|
||||
ol {
|
||||
list-style: none;
|
||||
@ -310,6 +316,8 @@ ol li::before {
|
||||
overflow-wrap: break-word;
|
||||
word-wrap: break-word;
|
||||
word-break: break-word;
|
||||
-webkit-hyphens: auto;
|
||||
hyphens: auto;
|
||||
}
|
||||
|
||||
.full-bleed {
|
||||
@ -345,10 +353,6 @@ ol li::before {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.flex-direction-column {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
}
|
||||
@ -385,18 +389,10 @@ ol li::before {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.align-content-start {
|
||||
.align-start {
|
||||
align-content: flex-start;
|
||||
}
|
||||
|
||||
.align-items-start {
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.align-self-start {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.align-center {
|
||||
align-items: center;
|
||||
}
|
||||
@ -522,10 +518,6 @@ ol li::before {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.margin-right-auto {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.margin-left-0-5 {
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
@ -589,19 +581,19 @@ ol li::before {
|
||||
}
|
||||
#confirmation_popup h4,
|
||||
#prompt_popup h4 {
|
||||
margin-bottom: 1.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
#confirmation_popup sm-button,
|
||||
#prompt_popup sm-button {
|
||||
margin: 0;
|
||||
}
|
||||
#confirmation_popup > .flex:last-of-type,
|
||||
#prompt_popup > .flex:last-of-type {
|
||||
#confirmation_popup .flex,
|
||||
#prompt_popup .flex {
|
||||
padding: 0;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
#confirmation_popup > .flex:last-of-type sm-button:first-of-type,
|
||||
#prompt_popup > .flex:last-of-type sm-button:first-of-type {
|
||||
#confirmation_popup .flex sm-button:first-of-type,
|
||||
#prompt_popup .flex sm-button:first-of-type {
|
||||
margin-right: 0.6rem;
|
||||
margin-left: auto;
|
||||
}
|
||||
@ -623,6 +615,12 @@ ol li::before {
|
||||
margin-left: -0.5rem;
|
||||
}
|
||||
|
||||
.flo-icon {
|
||||
margin-right: 0.3rem;
|
||||
height: 1.5rem;
|
||||
width: 1.5rem;
|
||||
}
|
||||
|
||||
#secondary_pages {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@ -646,38 +644,8 @@ ol li::before {
|
||||
font-size: clamp(2rem, 5vw, 5rem);
|
||||
}
|
||||
|
||||
#loading_page {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 20;
|
||||
background-color: rgba(var(--foreground-color), 1);
|
||||
}
|
||||
|
||||
#main_header {
|
||||
padding: 1rem max(1rem, 4vw);
|
||||
}
|
||||
|
||||
.app-brand {
|
||||
display: flex;
|
||||
gap: 0.3rem;
|
||||
align-items: center;
|
||||
}
|
||||
.app-brand .icon {
|
||||
height: 1.7rem;
|
||||
width: 1.7rem;
|
||||
}
|
||||
|
||||
.app-name__company {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
color: rgba(var(--text-color), 0.8);
|
||||
padding: 1.5rem max(1rem, 4vw);
|
||||
}
|
||||
|
||||
#main_card {
|
||||
@ -686,6 +654,7 @@ ol li::before {
|
||||
grid-template-rows: auto 1fr;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
transition: background-color 0.3s;
|
||||
background-color: rgba(var(--foreground-color), 1);
|
||||
}
|
||||
|
||||
@ -768,14 +737,12 @@ ol li::before {
|
||||
display: grid;
|
||||
text-align: center;
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
}
|
||||
.multi-state-button > * {
|
||||
grid-area: 1/1/2/2;
|
||||
}
|
||||
.multi-state-button button {
|
||||
z-index: 1;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.scrolling-wrapper {
|
||||
@ -797,11 +764,13 @@ ol li::before {
|
||||
background-color: transparent;
|
||||
border: thin solid rgba(var(--text-color), 0.3);
|
||||
text-align: left;
|
||||
flex-shrink: 1;
|
||||
}
|
||||
.primary-action .icon {
|
||||
fill: var(--accent-color);
|
||||
}
|
||||
.primary-action:not(:last-of-type) {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
#flo_id_warning {
|
||||
padding-bottom: 1.5rem;
|
||||
@ -825,10 +794,6 @@ ol li::before {
|
||||
margin-bottom: 0.3rem;
|
||||
}
|
||||
|
||||
#search_query_input {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
#address_balance_card {
|
||||
padding: 1.5rem;
|
||||
border-radius: 0.5rem;
|
||||
@ -843,13 +808,6 @@ ol li::before {
|
||||
color: var(--accent-color);
|
||||
}
|
||||
|
||||
#filter_selector {
|
||||
--padding: 0.3rem 0.5rem;
|
||||
}
|
||||
#filter_selector sm-chip {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 0.5rem 0;
|
||||
border: none;
|
||||
@ -884,69 +842,50 @@ ol li::before {
|
||||
border-bottom: thin solid rgba(var(--text-color), 0.3);
|
||||
}
|
||||
|
||||
#tx_details__header:has(#tx_status) time {
|
||||
text-align: left;
|
||||
margin-right: auto;
|
||||
}
|
||||
#tx_details__header:has(:not(#tx_status)) time {
|
||||
text-align: right;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
#transactions_list {
|
||||
display: grid;
|
||||
gap: 2rem;
|
||||
padding-bottom: 4rem;
|
||||
padding-top: 2rem;
|
||||
}
|
||||
|
||||
transaction-card {
|
||||
position: relative;
|
||||
}
|
||||
transaction-card:not(:last-of-type) {
|
||||
padding-bottom: 2rem;
|
||||
}
|
||||
transaction-card:not(:last-of-type)::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
height: 1px;
|
||||
width: calc(100% - 3.5rem);
|
||||
background-color: rgba(var(--text-color), 0.2);
|
||||
}
|
||||
|
||||
.transaction {
|
||||
position: relative;
|
||||
grid-template-columns: auto 1fr;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
gap: 0.5rem 1rem;
|
||||
align-items: center;
|
||||
grid-template-areas: "icon time amount" "icon receiver receiver" "icon txid txid";
|
||||
}
|
||||
.transaction.in .transaction__amount {
|
||||
color: var(--green);
|
||||
.transaction:not(:last-of-type) {
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
.transaction.in .transaction__amount::before {
|
||||
content: "+";
|
||||
.transaction__amount {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.transaction.out .icon {
|
||||
fill: var(--danger-color);
|
||||
}
|
||||
.transaction.out .transaction__amount {
|
||||
color: var(--danger-color);
|
||||
}
|
||||
.transaction.out .transaction__amount::before {
|
||||
content: "-";
|
||||
content: "- ";
|
||||
}
|
||||
.transaction__amount {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.transaction.out .transaction__icon .icon {
|
||||
fill: var(--danger-color);
|
||||
}
|
||||
.transaction.in .transaction__icon .icon {
|
||||
.transaction.in .icon {
|
||||
fill: var(--green);
|
||||
}
|
||||
.transaction.unconfirmed-tx .transaction__icon .icon {
|
||||
.transaction.in .transaction__amount {
|
||||
color: var(--green);
|
||||
}
|
||||
.transaction.in .transaction__amount::before {
|
||||
content: "+ ";
|
||||
}
|
||||
.transaction.unconfirmed-tx {
|
||||
grid-template-areas: "icon time amount" "icon receiver receiver" "icon txid txid" "icon unconfirmed unconfirmed" "icon badge badge";
|
||||
}
|
||||
.transaction.unconfirmed-tx .icon {
|
||||
fill: var(--yellow);
|
||||
}
|
||||
.transaction__icon {
|
||||
grid-area: icon;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@ -956,32 +895,40 @@ transaction-card:not(:last-of-type)::after {
|
||||
border-radius: 2rem;
|
||||
}
|
||||
.transaction__receiver {
|
||||
grid-area: receiver;
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.3rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.transaction__time {
|
||||
grid-area: time;
|
||||
font-size: 0.9rem;
|
||||
color: rgba(var(--text-color), 0.8);
|
||||
text-wrap: balance;
|
||||
}
|
||||
.transaction__amount {
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.transaction__id {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.pending-badge {
|
||||
.transaction .pending-badge {
|
||||
grid-area: badge;
|
||||
font-size: 0.8rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 0.5rem;
|
||||
background-color: var(--yellow);
|
||||
color: rgba(0, 0, 0, 0.8);
|
||||
color: rgba(var(--foreground-color), 1);
|
||||
font-weight: 500;
|
||||
justify-self: flex-start;
|
||||
}
|
||||
.transaction__amount {
|
||||
grid-area: amount;
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.transaction__id {
|
||||
grid-area: txid;
|
||||
font-size: 0.9rem;
|
||||
color: rgba(var(--text-color), 0.8);
|
||||
}
|
||||
.transaction .unconfirmed-wrapper {
|
||||
grid-area: unconfirmed;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.tx-participant:not(:last-of-type) {
|
||||
margin-right: 0.5rem;
|
||||
@ -990,80 +937,15 @@ transaction-card:not(:last-of-type)::after {
|
||||
content: ",";
|
||||
}
|
||||
|
||||
#tx_details time {
|
||||
padding: 0.3rem 0.8rem;
|
||||
border-radius: 5rem;
|
||||
background-color: rgba(var(--text-color), 0.06);
|
||||
font-weight: 500;
|
||||
font-size: 0.9rem;
|
||||
text-wrap: balance;
|
||||
table tr {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
#tx_status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.6rem 0.8rem;
|
||||
border-radius: 0.5rem;
|
||||
background-color: rgba(var(--text-color), 0.03);
|
||||
color: var(--danger-color);
|
||||
width: -webkit-fit-content;
|
||||
width: -moz-fit-content;
|
||||
width: fit-content;
|
||||
table tr td,
|
||||
table tr th {
|
||||
padding: 0.8rem 0.5rem;
|
||||
}
|
||||
#tx_status .icon {
|
||||
fill: var(--danger-color);
|
||||
}
|
||||
|
||||
#tx_amount {
|
||||
font-size: max(2rem, 4vw);
|
||||
font-weight: 700;
|
||||
text-wrap: balance;
|
||||
}
|
||||
#tx_amount:has(+ *) {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
#tx_technicals .tx-detail:first-of-type {
|
||||
position: relative;
|
||||
}
|
||||
#tx_technicals .tx-detail:first-of-type::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 0;
|
||||
transform: translateY(-50%);
|
||||
width: 0.2rem;
|
||||
height: calc(100% - 2rem);
|
||||
background-color: var(--accent-color);
|
||||
border-radius: 0 1rem 1rem 0;
|
||||
}
|
||||
|
||||
.details-wrapper {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.tx-detail {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
align-content: flex-start;
|
||||
background-color: rgba(var(--text-color), 0.03);
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
flex: 1 1 8rem;
|
||||
}
|
||||
.tx-detail .flex div {
|
||||
color: rgba(var(--text-color), 0.8);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.tx-detail > div {
|
||||
font-weight: 700;
|
||||
font-size: 1rem;
|
||||
color: rgba(var(--text-color), 0.9);
|
||||
table tr:nth-child(even) {
|
||||
background-color: rgba(var(--text-color), 0.05);
|
||||
}
|
||||
|
||||
#in_out_wrapper {
|
||||
@ -1112,10 +994,6 @@ transaction-card:not(:last-of-type)::after {
|
||||
background-color: rgba(var(--foreground-color), 1);
|
||||
}
|
||||
|
||||
#txid {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.user-action-result__icon {
|
||||
justify-self: center;
|
||||
height: 4rem;
|
||||
@ -1173,55 +1051,6 @@ transaction-card:not(:last-of-type)::after {
|
||||
transform: scale(1) translateY(0);
|
||||
}
|
||||
}
|
||||
.increase-fee-sender,
|
||||
.increase-fee-receiver {
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
border: solid thin rgba(var(--text-color), 0.3);
|
||||
}
|
||||
|
||||
.input-action-wrapper {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
width: 100%;
|
||||
align-items: start;
|
||||
container: input-action/inline-size;
|
||||
}
|
||||
.input-action-wrapper sm-input {
|
||||
width: auto;
|
||||
flex: 1;
|
||||
min-width: 20rem;
|
||||
}
|
||||
.input-action-wrapper button {
|
||||
min-width: 7rem;
|
||||
min-height: 3.15rem;
|
||||
}
|
||||
|
||||
@container input-action (max-width: 28rem) {
|
||||
sm-input {
|
||||
width: 100%;
|
||||
min-width: 16rem !important;
|
||||
}
|
||||
button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
#conversion_view_selector {
|
||||
margin-right: auto;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.converted-card:not(:empty) {
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
background-color: rgba(var(--text-color), 0.03);
|
||||
}
|
||||
.converted-card:not(:empty) sm-copy {
|
||||
font-weight: 500;
|
||||
color: rgba(var(--text-color), 0.9);
|
||||
}
|
||||
|
||||
@media screen and (max-width: 40rem) {
|
||||
#main_navbar.hide-away {
|
||||
bottom: 0;
|
||||
@ -1254,7 +1083,6 @@ transaction-card:not(:last-of-type)::after {
|
||||
}
|
||||
#main_header {
|
||||
grid-area: header;
|
||||
padding: 1.5rem max(1rem, 4vw);
|
||||
}
|
||||
#main_navbar {
|
||||
grid-area: nav;
|
||||
@ -1280,24 +1108,13 @@ transaction-card:not(:last-of-type)::after {
|
||||
body[data-theme=dark] #main_navbar {
|
||||
background-color: rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
.page {
|
||||
width: min(60rem, 100%);
|
||||
margin: 0 auto;
|
||||
#pages_container {
|
||||
padding: 0 4vw;
|
||||
}
|
||||
#generate_btc_addr_popup,
|
||||
#retrieve_btc_addr_popup {
|
||||
--width: 28rem;
|
||||
}
|
||||
#convert {
|
||||
width: min(72rem, 100%);
|
||||
}
|
||||
#key_conversion_content {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
align-items: flex-start;
|
||||
}
|
||||
#increase_fee_popup {
|
||||
--width: 30rem;
|
||||
}
|
||||
}
|
||||
@media screen and (min-width: 48rem) {
|
||||
.sender-card,
|
||||
@ -1305,6 +1122,11 @@ transaction-card:not(:last-of-type)::after {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
@media screen and (min-width: 64rem) {
|
||||
#pages_container {
|
||||
padding: 0 12vw;
|
||||
}
|
||||
}
|
||||
@media (any-hover: hover) {
|
||||
::-webkit-scrollbar {
|
||||
width: 0.5rem;
|
||||
|
||||
2
css/main.min.css
vendored
2
css/main.min.css
vendored
File diff suppressed because one or more lines are too long
614
css/main.scss
614
css/main.scss
File diff suppressed because it is too large
Load Diff
86
docs/UI.md
86
docs/UI.md
@ -1,86 +0,0 @@
|
||||
## routeTo(targetPage, options = {}) explanation
|
||||
- routeTo handles routing and animation logic for our web applications. This function takes a targetPage and an optional options object as parameters.
|
||||
- Destructures options Object: firstLoad, hashChange, and isPreview are destructured from the options object.
|
||||
- Parsing targetPage:
|
||||
1. If targetPage is an empty string, pageId is set to 'check_details'.
|
||||
2. If targetPage contains a slash (/), it splits targetPage into parts. The first part is the pageId, and the second part (if any) is further split into subPageId1.
|
||||
Query parameters are parsed from the search parameters of the URL, if available.
|
||||
- Handling check_details Page:
|
||||
1. If the pageId is 'check_details', it checks for query parameters. If there are query parameters, it updates the search input value and renders query results.
|
||||
- Animating Navigation:
|
||||
1. Animates the transition of the navigation menu based on the current and previous active elements.
|
||||
2. Handles the indicator animation to show the active menu item.
|
||||
3. If the current page is not found in the navigation menu, it hides the navigation bar.
|
||||
- Showing/Hiding Pages:
|
||||
1. Hides all pages, then shows the target page and animates its opacity to make it visible.
|
||||
- Updating pagesData.lastPage:
|
||||
1. Updates the lastPage property of pagesData to keep track of the last visited page.
|
||||
|
||||
## UI Page Flow
|
||||
- Linking scripts are added first
|
||||
|
||||
- Create sm-notifications thereafter
|
||||
- Create sm-popup
|
||||
|
||||
- Then create `<div id="main_card">`
|
||||
|
||||
- Then create `<header></header>` inside the main card
|
||||
|
||||
- Then create `<main id="pages_container" class="grid">`
|
||||
|
||||
- Then the first page `<div id="check_details" class="page hidden">`
|
||||
- Then the second page `<div id="send" class="page">`
|
||||
- Then the third page `<div id="convert_key" class="page hidden flex flex-direction-column gap-1-5">`
|
||||
|
||||
|
||||
- Inside a page
|
||||
1. Fieldsets
|
||||
2. Input inside it
|
||||
3. Then button <button type="submit" onclick="convertBtcPrivateKey()" class="button button--primary cta" disabled="">Convert</button>
|
||||
|
||||
- Clicking a button will lead to action <button type="submit" onclick="convertBtcPrivateKey()"
|
||||
|
||||
- Everything happens through clicking
|
||||
|
||||
```javascript
|
||||
<button id="convert_to_flo" class="button--primary justify-self-center cta" type="submit" disabled="">
|
||||
Convert
|
||||
</button>
|
||||
|
||||
<div id="btc_address_converter_result"></div>
|
||||
|
||||
getRef('convert_to_flo').onclick = evt => {
|
||||
const btc_bech = getRef('convert_btc_input').value.trim();
|
||||
if (btc_bech === '') {
|
||||
getRef('convert_btc_input').focusIn()
|
||||
return notify('Please enter BTC address', 'error');
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
- Or we can add eventlisteners from Javascript side
|
||||
- We add eventListeners to any id
|
||||
```javascript
|
||||
getRef('convert_btc_private_key_form').addEventListener('invalid', e => {
|
||||
getRef('flo_private').value = '';
|
||||
getRef('converted_flo_address').value = '';
|
||||
})
|
||||
```
|
||||
|
||||
- Then the navbar
|
||||
` <nav id="main_navbar">`
|
||||
- Navbar goes into bottom of the page
|
||||
|
||||
- Then you place your popups
|
||||
```
|
||||
<sm-popup id="txid_popup">
|
||||
|
||||
getRef('txid_popup__resolved_txid').value = txid;
|
||||
openPopup('txid_popup', true);
|
||||
```
|
||||
|
||||
- Now there is <script id="ui_utils"> this is the script with UI Javascript logic
|
||||
|
||||
- And finally the <script></script> with actual business logic
|
||||
|
||||
- Attach eventlisteners to different buttons, and handle them as per the busines logic
|
||||
2289
index.html
2289
index.html
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
1
scripts/btcOperator.min.js
vendored
1
scripts/btcOperator.min.js
vendored
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
1
scripts/components.min.js
vendored
1
scripts/components.min.js
vendored
File diff suppressed because one or more lines are too long
@ -1,530 +0,0 @@
|
||||
(function (EXPORTS) { //floCrypto v2.3.6a
|
||||
/* FLO Crypto Operators */
|
||||
'use strict';
|
||||
const floCrypto = EXPORTS;
|
||||
|
||||
const p = BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16);
|
||||
const ecparams = EllipticCurve.getSECCurveByName("secp256k1");
|
||||
const ascii_alternatives = `‘ '\n’ '\n“ "\n” "\n– --\n— ---\n≥ >=\n≤ <=\n≠ !=\n× *\n÷ /\n← <-\n→ ->\n↔ <->\n⇒ =>\n⇐ <=\n⇔ <=>`;
|
||||
const exponent1 = () => p.add(BigInteger.ONE).divide(BigInteger("4"));
|
||||
coinjs.compressed = true; //defaulting coinjs compressed to true;
|
||||
|
||||
function calculateY(x) {
|
||||
let exp = exponent1();
|
||||
// x is x value of public key in BigInteger format without 02 or 03 or 04 prefix
|
||||
return x.modPow(BigInteger("3"), p).add(BigInteger("7")).mod(p).modPow(exp, p)
|
||||
}
|
||||
|
||||
function getUncompressedPublicKey(compressedPublicKey) {
|
||||
// Fetch x from compressedPublicKey
|
||||
let pubKeyBytes = Crypto.util.hexToBytes(compressedPublicKey);
|
||||
const prefix = pubKeyBytes.shift() // remove prefix
|
||||
let prefix_modulus = prefix % 2;
|
||||
pubKeyBytes.unshift(0) // add prefix 0
|
||||
let x = new BigInteger(pubKeyBytes)
|
||||
let xDecimalValue = x.toString()
|
||||
// Fetch y
|
||||
let y = calculateY(x);
|
||||
let yDecimalValue = y.toString();
|
||||
// verify y value
|
||||
let resultBigInt = y.mod(BigInteger("2"));
|
||||
let check = resultBigInt.toString() % 2;
|
||||
if (prefix_modulus !== check)
|
||||
yDecimalValue = y.negate().mod(p).toString();
|
||||
return {
|
||||
x: xDecimalValue,
|
||||
y: yDecimalValue
|
||||
};
|
||||
}
|
||||
|
||||
function getSenderPublicKeyString() {
|
||||
let privateKey = ellipticCurveEncryption.senderRandom();
|
||||
var senderPublicKeyString = ellipticCurveEncryption.senderPublicString(privateKey);
|
||||
return {
|
||||
privateKey: privateKey,
|
||||
senderPublicKeyString: senderPublicKeyString
|
||||
}
|
||||
}
|
||||
|
||||
function deriveSharedKeySender(receiverPublicKeyHex, senderPrivateKey) {
|
||||
let receiverPublicKeyString = getUncompressedPublicKey(receiverPublicKeyHex);
|
||||
var senderDerivedKey = ellipticCurveEncryption.senderSharedKeyDerivation(
|
||||
receiverPublicKeyString.x, receiverPublicKeyString.y, senderPrivateKey);
|
||||
return senderDerivedKey;
|
||||
}
|
||||
|
||||
function deriveSharedKeyReceiver(senderPublicKeyString, receiverPrivateKey) {
|
||||
return ellipticCurveEncryption.receiverSharedKeyDerivation(
|
||||
senderPublicKeyString.XValuePublicString, senderPublicKeyString.YValuePublicString, receiverPrivateKey);
|
||||
}
|
||||
|
||||
function getReceiverPublicKeyString(privateKey) {
|
||||
return ellipticCurveEncryption.receiverPublicString(privateKey);
|
||||
}
|
||||
|
||||
function wifToDecimal(pk_wif, isPubKeyCompressed = false) {
|
||||
let pk = Bitcoin.Base58.decode(pk_wif)
|
||||
pk.shift()
|
||||
pk.splice(-4, 4)
|
||||
//If the private key corresponded to a compressed public key, also drop the last byte (it should be 0x01).
|
||||
if (isPubKeyCompressed == true) pk.pop()
|
||||
pk.unshift(0)
|
||||
let privateKeyDecimal = BigInteger(pk).toString()
|
||||
let privateKeyHex = Crypto.util.bytesToHex(pk)
|
||||
return {
|
||||
privateKeyDecimal: privateKeyDecimal,
|
||||
privateKeyHex: privateKeyHex
|
||||
}
|
||||
}
|
||||
|
||||
//generate a random Interger within range
|
||||
floCrypto.randInt = function (min, max) {
|
||||
min = Math.ceil(min);
|
||||
max = Math.floor(max);
|
||||
return Math.floor(securedMathRandom() * (max - min + 1)) + min;
|
||||
}
|
||||
|
||||
//generate a random String within length (options : alphaNumeric chars only)
|
||||
floCrypto.randString = function (length, alphaNumeric = true) {
|
||||
var result = '';
|
||||
var characters = alphaNumeric ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' :
|
||||
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+-./*?@#&$<>=[]{}():';
|
||||
for (var i = 0; i < length; i++)
|
||||
result += characters.charAt(Math.floor(securedMathRandom() * characters.length));
|
||||
return result;
|
||||
}
|
||||
|
||||
//Encrypt Data using public-key
|
||||
floCrypto.encryptData = function (data, receiverPublicKeyHex) {
|
||||
var senderECKeyData = getSenderPublicKeyString();
|
||||
var senderDerivedKey = deriveSharedKeySender(receiverPublicKeyHex, senderECKeyData.privateKey);
|
||||
let senderKey = senderDerivedKey.XValue + senderDerivedKey.YValue;
|
||||
let secret = Crypto.AES.encrypt(data, senderKey);
|
||||
return {
|
||||
secret: secret,
|
||||
senderPublicKeyString: senderECKeyData.senderPublicKeyString
|
||||
};
|
||||
}
|
||||
|
||||
//Decrypt Data using private-key
|
||||
floCrypto.decryptData = function (data, privateKeyHex) {
|
||||
var receiverECKeyData = {};
|
||||
if (typeof privateKeyHex !== "string") throw new Error("No private key found.");
|
||||
let privateKey = wifToDecimal(privateKeyHex, true);
|
||||
if (typeof privateKey.privateKeyDecimal !== "string") throw new Error("Failed to detremine your private key.");
|
||||
receiverECKeyData.privateKey = privateKey.privateKeyDecimal;
|
||||
var receiverDerivedKey = deriveSharedKeyReceiver(data.senderPublicKeyString, receiverECKeyData.privateKey);
|
||||
let receiverKey = receiverDerivedKey.XValue + receiverDerivedKey.YValue;
|
||||
let decryptMsg = Crypto.AES.decrypt(data.secret, receiverKey);
|
||||
return decryptMsg;
|
||||
}
|
||||
|
||||
//Sign data using private-key
|
||||
floCrypto.signData = function (data, privateKeyHex) {
|
||||
var key = new Bitcoin.ECKey(privateKeyHex);
|
||||
var messageHash = Crypto.SHA256(data);
|
||||
var messageSign = Bitcoin.ECDSA.sign(messageHash, key.priv);
|
||||
var sighex = Crypto.util.bytesToHex(messageSign);
|
||||
return sighex;
|
||||
}
|
||||
|
||||
//Verify signatue of the data using public-key
|
||||
floCrypto.verifySign = function (data, signatureHex, publicKeyHex) {
|
||||
var msgHash = Crypto.SHA256(data);
|
||||
var sigBytes = Crypto.util.hexToBytes(signatureHex);
|
||||
var publicKeyPoint = ecparams.getCurve().decodePointHex(publicKeyHex);
|
||||
var verify = Bitcoin.ECDSA.verify(msgHash, sigBytes, publicKeyPoint);
|
||||
return verify;
|
||||
}
|
||||
|
||||
//Generates a new flo ID and returns private-key, public-key and floID
|
||||
const generateNewID = floCrypto.generateNewID = function () {
|
||||
var key = new Bitcoin.ECKey(false);
|
||||
key.setCompressed(true);
|
||||
return {
|
||||
floID: key.getBitcoinAddress(),
|
||||
pubKey: key.getPubKeyHex(),
|
||||
privKey: key.getBitcoinWalletImportFormat()
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperties(floCrypto, {
|
||||
newID: {
|
||||
get: () => generateNewID()
|
||||
},
|
||||
hashID: {
|
||||
value: (str) => {
|
||||
let bytes = ripemd160(Crypto.SHA256(str, { asBytes: true }), { asBytes: true });
|
||||
bytes.unshift(bitjs.pub);
|
||||
var hash = Crypto.SHA256(Crypto.SHA256(bytes, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
var checksum = hash.slice(0, 4);
|
||||
return bitjs.Base58.encode(bytes.concat(checksum));
|
||||
}
|
||||
},
|
||||
tmpID: {
|
||||
get: () => {
|
||||
let bytes = Crypto.util.randomBytes(20);
|
||||
bytes.unshift(bitjs.pub);
|
||||
var hash = Crypto.SHA256(Crypto.SHA256(bytes, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
var checksum = hash.slice(0, 4);
|
||||
return bitjs.Base58.encode(bytes.concat(checksum));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//Returns public-key from private-key
|
||||
floCrypto.getPubKeyHex = function (privateKeyHex) {
|
||||
if (!privateKeyHex)
|
||||
return null;
|
||||
var key = new Bitcoin.ECKey(privateKeyHex);
|
||||
if (key.priv == null)
|
||||
return null;
|
||||
key.setCompressed(true);
|
||||
return key.getPubKeyHex();
|
||||
}
|
||||
|
||||
//Returns flo-ID from public-key or private-key
|
||||
floCrypto.getFloID = function (keyHex) {
|
||||
if (!keyHex)
|
||||
return null;
|
||||
try {
|
||||
var key = new Bitcoin.ECKey(keyHex);
|
||||
if (key.priv == null)
|
||||
key.setPub(keyHex);
|
||||
return key.getBitcoinAddress();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
floCrypto.getAddress = function (privateKeyHex, strict = false) {
|
||||
if (!privateKeyHex)
|
||||
return;
|
||||
var key = new Bitcoin.ECKey(privateKeyHex);
|
||||
if (key.priv == null)
|
||||
return null;
|
||||
key.setCompressed(true);
|
||||
let pubKey = key.getPubKeyHex(),
|
||||
version = bitjs.Base58.decode(privateKeyHex)[0];
|
||||
switch (version) {
|
||||
case coinjs.priv: //BTC
|
||||
return coinjs.bech32Address(pubKey).address;
|
||||
case bitjs.priv: //FLO
|
||||
return bitjs.pubkey2address(pubKey);
|
||||
default:
|
||||
return strict ? false : bitjs.pubkey2address(pubKey); //default to FLO address (if strict=false)
|
||||
}
|
||||
}
|
||||
|
||||
//Verify the private-key for the given public-key or flo-ID
|
||||
floCrypto.verifyPrivKey = function (privateKeyHex, pubKey_floID, isfloID = true) {
|
||||
if (!privateKeyHex || !pubKey_floID)
|
||||
return false;
|
||||
try {
|
||||
var key = new Bitcoin.ECKey(privateKeyHex);
|
||||
if (key.priv == null)
|
||||
return false;
|
||||
key.setCompressed(true);
|
||||
if (isfloID && pubKey_floID == key.getBitcoinAddress())
|
||||
return true;
|
||||
else if (!isfloID && pubKey_floID.toUpperCase() == key.getPubKeyHex().toUpperCase())
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
floCrypto.getMultisigAddress = function (publicKeyList, requiredSignatures) {
|
||||
if (!Array.isArray(publicKeyList) || !publicKeyList.length)
|
||||
return null;
|
||||
if (!Number.isInteger(requiredSignatures) || requiredSignatures < 1 || requiredSignatures > publicKeyList.length)
|
||||
return null;
|
||||
try {
|
||||
var multisig = bitjs.pubkeys2multisig(publicKeyList, requiredSignatures);
|
||||
return multisig;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
floCrypto.decodeRedeemScript = function (redeemScript) {
|
||||
try {
|
||||
var decoded = bitjs.transaction().decodeRedeemScript(redeemScript);
|
||||
return decoded;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//Check if the given flo-id is valid or not
|
||||
floCrypto.validateFloID = function (floID, regularOnly = false) {
|
||||
if (!floID)
|
||||
return false;
|
||||
try {
|
||||
let addr = new Bitcoin.Address(floID);
|
||||
if (regularOnly && addr.version != Bitcoin.Address.standardVersion)
|
||||
return false;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//Check if the given address (any blockchain) is valid or not
|
||||
floCrypto.validateAddr = function (address, std = true, bech = true) {
|
||||
let raw = decodeAddress(address);
|
||||
if (!raw)
|
||||
return false;
|
||||
if (typeof raw.version !== 'undefined') { //legacy or segwit
|
||||
if (std == false)
|
||||
return false;
|
||||
else if (std === true || (!Array.isArray(std) && std === raw.version) || (Array.isArray(std) && std.includes(raw.version)))
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
} else if (typeof raw.bech_version !== 'undefined') { //bech32
|
||||
if (bech === false)
|
||||
return false;
|
||||
else if (bech === true || (!Array.isArray(bech) && bech === raw.bech_version) || (Array.isArray(bech) && bech.includes(raw.bech_version)))
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
} else //unknown
|
||||
return false;
|
||||
}
|
||||
|
||||
//Check the public-key (or redeem-script) for the address (any blockchain)
|
||||
floCrypto.verifyPubKey = function (pubKeyHex, address) {
|
||||
let raw = decodeAddress(address);
|
||||
if (!raw)
|
||||
return;
|
||||
let pub_hash = Crypto.util.bytesToHex(ripemd160(Crypto.SHA256(Crypto.util.hexToBytes(pubKeyHex), { asBytes: true })));
|
||||
if (typeof raw.bech_version !== 'undefined' && raw.bytes.length == 32) //bech32-multisig
|
||||
raw.hex = Crypto.util.bytesToHex(ripemd160(raw.bytes, { asBytes: true }));
|
||||
return pub_hash === raw.hex;
|
||||
}
|
||||
|
||||
//Convert the given address (any blockchain) to equivalent floID
|
||||
floCrypto.toFloID = function (address, options = null) {
|
||||
if (!address)
|
||||
return;
|
||||
let raw = decodeAddress(address);
|
||||
if (!raw)
|
||||
return;
|
||||
else if (options) { //if (optional) version check is passed
|
||||
if (typeof raw.version !== 'undefined' && (!options.std || !options.std.includes(raw.version)))
|
||||
return;
|
||||
if (typeof raw.bech_version !== 'undefined' && (!options.bech || !options.bech.includes(raw.bech_version)))
|
||||
return;
|
||||
}
|
||||
raw.bytes.unshift(bitjs.pub);
|
||||
let hash = Crypto.SHA256(Crypto.SHA256(raw.bytes, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
return bitjs.Base58.encode(raw.bytes.concat(hash.slice(0, 4)));
|
||||
}
|
||||
|
||||
//Convert raw address bytes to floID
|
||||
floCrypto.rawToFloID = function (raw_bytes) {
|
||||
if (typeof raw_bytes === 'string')
|
||||
raw_bytes = Crypto.util.hexToBytes(raw_bytes);
|
||||
if (raw_bytes.length != 20)
|
||||
return null;
|
||||
raw_bytes.unshift(bitjs.pub);
|
||||
let hash = Crypto.SHA256(Crypto.SHA256(raw_bytes, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
return bitjs.Base58.encode(raw_bytes.concat(hash.slice(0, 4)));
|
||||
}
|
||||
|
||||
//Convert the given multisig address (any blockchain) to equivalent multisig floID
|
||||
floCrypto.toMultisigFloID = function (address, options = null) {
|
||||
if (!address)
|
||||
return;
|
||||
let raw = decodeAddress(address);
|
||||
if (!raw)
|
||||
return;
|
||||
else if (options) { //if (optional) version check is passed
|
||||
if (typeof raw.version !== 'undefined' && (!options.std || !options.std.includes(raw.version)))
|
||||
return;
|
||||
if (typeof raw.bech_version !== 'undefined' && (!options.bech || !options.bech.includes(raw.bech_version)))
|
||||
return;
|
||||
}
|
||||
if (typeof raw.bech_version !== 'undefined') {
|
||||
if (raw.bytes.length != 32) return; //multisig bech address have 32 bytes
|
||||
//multisig-bech:hash=SHA256 whereas multisig:hash=r160(SHA265), thus ripemd160 the bytes from multisig-bech
|
||||
raw.bytes = ripemd160(raw.bytes, {
|
||||
asBytes: true
|
||||
});
|
||||
}
|
||||
raw.bytes.unshift(bitjs.multisig);
|
||||
let hash = Crypto.SHA256(Crypto.SHA256(raw.bytes, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
return bitjs.Base58.encode(raw.bytes.concat(hash.slice(0, 4)));
|
||||
}
|
||||
|
||||
//Checks if the given addresses (any blockchain) are same (w.r.t keys)
|
||||
floCrypto.isSameAddr = function (addr1, addr2) {
|
||||
if (!addr1 || !addr2)
|
||||
return;
|
||||
let raw1 = decodeAddress(addr1),
|
||||
raw2 = decodeAddress(addr2);
|
||||
if (!raw1 || !raw2)
|
||||
return false;
|
||||
else {
|
||||
if (typeof raw1.bech_version !== 'undefined' && raw1.bytes.length == 32) //bech32-multisig
|
||||
raw1.hex = Crypto.util.bytesToHex(ripemd160(raw1.bytes, { asBytes: true }));
|
||||
if (typeof raw2.bech_version !== 'undefined' && raw2.bytes.length == 32) //bech32-multisig
|
||||
raw2.hex = Crypto.util.bytesToHex(ripemd160(raw2.bytes, { asBytes: true }));
|
||||
return raw1.hex === raw2.hex;
|
||||
}
|
||||
}
|
||||
|
||||
const decodeAddress = floCrypto.decodeAddr = function (address) {
|
||||
if (!address)
|
||||
return;
|
||||
else if (address.length == 33 || address.length == 34) { //legacy encoding
|
||||
let decode = bitjs.Base58.decode(address);
|
||||
let bytes = decode.slice(0, decode.length - 4);
|
||||
let checksum = decode.slice(decode.length - 4),
|
||||
hash = Crypto.SHA256(Crypto.SHA256(bytes, {
|
||||
asBytes: true
|
||||
}), {
|
||||
asBytes: true
|
||||
});
|
||||
return (hash[0] != checksum[0] || hash[1] != checksum[1] || hash[2] != checksum[2] || hash[3] != checksum[3]) ? null : {
|
||||
version: bytes.shift(),
|
||||
hex: Crypto.util.bytesToHex(bytes),
|
||||
bytes
|
||||
}
|
||||
} else if (address.length == 42 || address.length == 62) { //bech encoding
|
||||
let decode = coinjs.bech32_decode(address);
|
||||
if (decode) {
|
||||
let bytes = decode.data;
|
||||
let bech_version = bytes.shift();
|
||||
bytes = coinjs.bech32_convert(bytes, 5, 8, false);
|
||||
return {
|
||||
bech_version,
|
||||
hrp: decode.hrp,
|
||||
hex: Crypto.util.bytesToHex(bytes),
|
||||
bytes
|
||||
}
|
||||
} else
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//Split the str using shamir's Secret and Returns the shares
|
||||
floCrypto.createShamirsSecretShares = function (str, total_shares, threshold_limit) {
|
||||
try {
|
||||
if (str.length > 0) {
|
||||
var strHex = shamirSecretShare.str2hex(str);
|
||||
var shares = shamirSecretShare.share(strHex, total_shares, threshold_limit);
|
||||
return shares;
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
//Returns the retrived secret by combining the shamirs shares
|
||||
const retrieveShamirSecret = floCrypto.retrieveShamirSecret = function (sharesArray) {
|
||||
try {
|
||||
if (sharesArray.length > 0) {
|
||||
var comb = shamirSecretShare.combine(sharesArray.slice(0, sharesArray.length));
|
||||
comb = shamirSecretShare.hex2str(comb);
|
||||
return comb;
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//Verifies the shares and str
|
||||
floCrypto.verifyShamirsSecret = function (sharesArray, str) {
|
||||
if (!str)
|
||||
return null;
|
||||
else if (retrieveShamirSecret(sharesArray) === str)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
const validateASCII = floCrypto.validateASCII = function (string, bool = true) {
|
||||
if (typeof string !== "string")
|
||||
return null;
|
||||
if (bool) {
|
||||
let x;
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
x = string.charCodeAt(i);
|
||||
if (x < 32 || x > 127)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
let x, invalids = {};
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
x = string.charCodeAt(i);
|
||||
if (x < 32 || x > 127)
|
||||
if (x in invalids)
|
||||
invalids[string[i]].push(i)
|
||||
else
|
||||
invalids[string[i]] = [i];
|
||||
}
|
||||
if (Object.keys(invalids).length)
|
||||
return invalids;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
floCrypto.convertToASCII = function (string, mode = 'soft-remove') {
|
||||
let chars = validateASCII(string, false);
|
||||
if (chars === true)
|
||||
return string;
|
||||
else if (chars === null)
|
||||
return null;
|
||||
let convertor, result = string,
|
||||
refAlt = {};
|
||||
ascii_alternatives.split('\n').forEach(a => refAlt[a[0]] = a.slice(2));
|
||||
mode = mode.toLowerCase();
|
||||
if (mode === "hard-unicode")
|
||||
convertor = (c) => `\\u${('000' + c.charCodeAt().toString(16)).slice(-4)}`;
|
||||
else if (mode === "soft-unicode")
|
||||
convertor = (c) => refAlt[c] || `\\u${('000' + c.charCodeAt().toString(16)).slice(-4)}`;
|
||||
else if (mode === "hard-remove")
|
||||
convertor = c => "";
|
||||
else if (mode === "soft-remove")
|
||||
convertor = c => refAlt[c] || "";
|
||||
else
|
||||
return null;
|
||||
for (let c in chars)
|
||||
result = result.replaceAll(c, convertor(c));
|
||||
return result;
|
||||
}
|
||||
|
||||
floCrypto.revertUnicode = function (string) {
|
||||
return string.replace(/\\u[\dA-F]{4}/gi,
|
||||
m => String.fromCharCode(parseInt(m.replace(/\\u/g, ''), 16)));
|
||||
}
|
||||
|
||||
})('object' === typeof module ? module.exports : window.floCrypto = {});
|
||||
@ -1,46 +0,0 @@
|
||||
(function (EXPORTS) { //floEthereum v1.0.1a
|
||||
/* FLO Ethereum Operators */
|
||||
/* Make sure you added Taproot, Keccak, FLO and BTC Libraries before */
|
||||
'use strict';
|
||||
const floEthereum = EXPORTS;
|
||||
|
||||
const ethPrivateKeyFromWif = floEthereum.ethPrivateKeyFromWif = function (privateKey,) {
|
||||
return coinjs.wif2privkey(privateKey).privkey;
|
||||
}
|
||||
|
||||
const ethAddressFromPrivateKey = floEthereum.ethAddressFromPrivateKey = function (privateKey, onlyEvenY = false) {
|
||||
var t1, t1_x, t1_y, t1_y_BigInt, t2, t3, t4;
|
||||
var groupOrder = BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
|
||||
|
||||
t1 = bitjs.newPubkey(privateKey);
|
||||
t1_x = t1.slice(2, 66); t1_y = t1.slice(-64);
|
||||
if (onlyEvenY) {
|
||||
t1_y_BigInt = BigInt("0x" + t1_y);
|
||||
if (t1_y_BigInt % 2n !== 0n) { t1_y_BigInt = (groupOrder - t1_y_BigInt) % groupOrder; t1_y = t1_y_BigInt.toString(16) }
|
||||
};
|
||||
|
||||
t2 = t1_x.toString(16) + t1_y.toString(16);
|
||||
t3 = keccak.keccak_256(Crypto.util.hexToBytes(t2));
|
||||
t4 = keccak.extractLast20Bytes(t3);
|
||||
return "0x" + t4;
|
||||
}
|
||||
|
||||
const ethAddressFromCompressedPublicKey = floEthereum.ethAddressFromCompressedPublicKey = function (compressedPublicKey) {
|
||||
var t1, t2, t3, t4;
|
||||
t1 = coinjs.compressedToUncompressed(compressedPublicKey);
|
||||
t2 = t1.slice(2);
|
||||
t3 = keccak.keccak_256(Crypto.util.hexToBytes(t2));
|
||||
t4 = keccak.extractLast20Bytes(t3);
|
||||
return "0x" + t4;
|
||||
}
|
||||
|
||||
const ethAddressFromUncompressedPublicKey = floEthereum.ethAddressFromUncompressedPublicKey = function (unCompressedPublicKey) {
|
||||
var t1, t2, t3, t4;
|
||||
t1 = unCompressedPublicKey;
|
||||
t2 = t1.slice(2);
|
||||
t3 = keccak.keccak_256(Crypto.util.hexToBytes(t2));
|
||||
t4 = keccak.extractLast20Bytes(t3);
|
||||
return "0x" + t4;
|
||||
}
|
||||
|
||||
})('object' === typeof module ? module.exports : window.floEthereum = {});
|
||||
1
scripts/floEthereum.min.js
vendored
1
scripts/floEthereum.min.js
vendored
@ -1 +0,0 @@
|
||||
!function(EXPORTS){"use strict";const floEthereum="object"===typeof module?module.exports:window.floEthereum={};floEthereum.ethPrivateKeyFromWif=function(privateKey){return coinjs.wif2privkey(privateKey).privkey},floEthereum.ethAddressFromPrivateKey=function(privateKey,onlyEvenY=!1){var t1,t1_x,t1_y,t1_y_BigInt,t2,t3,groupOrder=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");return t1_x=(t1=bitjs.newPubkey(privateKey)).slice(2,66),t1_y=t1.slice(-64),onlyEvenY&&(t1_y_BigInt=BigInt("0x"+t1_y))%2n!==0n&&(t1_y=(t1_y_BigInt=(groupOrder-t1_y_BigInt)%groupOrder).toString(16)),t2=t1_x.toString(16)+t1_y.toString(16),t3=keccak.keccak_256(Crypto.util.hexToBytes(t2)),"0x"+keccak.extractLast20Bytes(t3)},floEthereum.ethAddressFromCompressedPublicKey=function(compressedPublicKey){var t2,t3;return t2=coinjs.compressedToUncompressed(compressedPublicKey).slice(2),t3=keccak.keccak_256(Crypto.util.hexToBytes(t2)),"0x"+keccak.extractLast20Bytes(t3)},floEthereum.ethAddressFromUncompressedPublicKey=function(unCompressedPublicKey){var t2,t3;return t2=unCompressedPublicKey.slice(2),t3=keccak.keccak_256(Crypto.util.hexToBytes(t2)),"0x"+keccak.extractLast20Bytes(t3)}}();
|
||||
@ -1,673 +0,0 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var INPUT_ERROR = 'input is invalid type';
|
||||
var FINALIZE_ERROR = 'finalize already called';
|
||||
var WINDOW = typeof window === 'object';
|
||||
var root = WINDOW ? (window.keccak = window.keccak || {}) : {};
|
||||
if (root.JS_SHA3_NO_WINDOW) {
|
||||
WINDOW = false;
|
||||
}
|
||||
var WEB_WORKER = !WINDOW && typeof self === 'object';
|
||||
var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
|
||||
if (NODE_JS) {
|
||||
root = global;
|
||||
} else if (WEB_WORKER) {
|
||||
root = self;
|
||||
}
|
||||
var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;
|
||||
var AMD = typeof define === 'function' && define.amd;
|
||||
var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
|
||||
var HEX_CHARS = '0123456789abcdef'.split('');
|
||||
var SHAKE_PADDING = [31, 7936, 2031616, 520093696];
|
||||
var CSHAKE_PADDING = [4, 1024, 262144, 67108864];
|
||||
var KECCAK_PADDING = [1, 256, 65536, 16777216];
|
||||
var PADDING = [6, 1536, 393216, 100663296];
|
||||
var SHIFT = [0, 8, 16, 24];
|
||||
var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
|
||||
0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,
|
||||
2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,
|
||||
2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
|
||||
2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
|
||||
var BITS = [224, 256, 384, 512];
|
||||
var SHAKE_BITS = [128, 256];
|
||||
var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];
|
||||
var CSHAKE_BYTEPAD = {
|
||||
'128': 168,
|
||||
'256': 136
|
||||
};
|
||||
|
||||
|
||||
var isArray = root.JS_SHA3_NO_NODE_JS || !Array.isArray
|
||||
? function (obj) {
|
||||
return Object.prototype.toString.call(obj) === '[object Array]';
|
||||
}
|
||||
: Array.isArray;
|
||||
|
||||
var isView = (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView))
|
||||
? function (obj) {
|
||||
return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
|
||||
}
|
||||
: ArrayBuffer.isView;
|
||||
|
||||
// [message: string, isString: bool]
|
||||
var formatMessage = function (message) {
|
||||
var type = typeof message;
|
||||
if (type === 'string') {
|
||||
return [message, true];
|
||||
}
|
||||
if (type !== 'object' || message === null) {
|
||||
throw new Error(INPUT_ERROR);
|
||||
}
|
||||
if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {
|
||||
return [new Uint8Array(message), false];
|
||||
}
|
||||
if (!isArray(message) && !isView(message)) {
|
||||
throw new Error(INPUT_ERROR);
|
||||
}
|
||||
return [message, false];
|
||||
}
|
||||
|
||||
var empty = function (message) {
|
||||
return formatMessage(message)[0].length === 0;
|
||||
};
|
||||
|
||||
var createOutputMethod = function (bits, padding, outputType) {
|
||||
return function (message) {
|
||||
return new Keccak(bits, padding, bits).update(message)[outputType]();
|
||||
};
|
||||
};
|
||||
|
||||
var createShakeOutputMethod = function (bits, padding, outputType) {
|
||||
return function (message, outputBits) {
|
||||
return new Keccak(bits, padding, outputBits).update(message)[outputType]();
|
||||
};
|
||||
};
|
||||
|
||||
var createCshakeOutputMethod = function (bits, padding, outputType) {
|
||||
return function (message, outputBits, n, s) {
|
||||
return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();
|
||||
};
|
||||
};
|
||||
|
||||
var createKmacOutputMethod = function (bits, padding, outputType) {
|
||||
return function (key, message, outputBits, s) {
|
||||
return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();
|
||||
};
|
||||
};
|
||||
|
||||
var createOutputMethods = function (method, createMethod, bits, padding) {
|
||||
for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
|
||||
var type = OUTPUT_TYPES[i];
|
||||
method[type] = createMethod(bits, padding, type);
|
||||
}
|
||||
return method;
|
||||
};
|
||||
|
||||
var createMethod = function (bits, padding) {
|
||||
var method = createOutputMethod(bits, padding, 'hex');
|
||||
method.create = function () {
|
||||
return new Keccak(bits, padding, bits);
|
||||
};
|
||||
method.update = function (message) {
|
||||
return method.create().update(message);
|
||||
};
|
||||
return createOutputMethods(method, createOutputMethod, bits, padding);
|
||||
};
|
||||
|
||||
var createShakeMethod = function (bits, padding) {
|
||||
var method = createShakeOutputMethod(bits, padding, 'hex');
|
||||
method.create = function (outputBits) {
|
||||
return new Keccak(bits, padding, outputBits);
|
||||
};
|
||||
method.update = function (message, outputBits) {
|
||||
return method.create(outputBits).update(message);
|
||||
};
|
||||
return createOutputMethods(method, createShakeOutputMethod, bits, padding);
|
||||
};
|
||||
|
||||
var createCshakeMethod = function (bits, padding) {
|
||||
var w = CSHAKE_BYTEPAD[bits];
|
||||
var method = createCshakeOutputMethod(bits, padding, 'hex');
|
||||
method.create = function (outputBits, n, s) {
|
||||
if (empty(n) && empty(s)) {
|
||||
return methods['shake' + bits].create(outputBits);
|
||||
} else {
|
||||
return new Keccak(bits, padding, outputBits).bytepad([n, s], w);
|
||||
}
|
||||
};
|
||||
method.update = function (message, outputBits, n, s) {
|
||||
return method.create(outputBits, n, s).update(message);
|
||||
};
|
||||
return createOutputMethods(method, createCshakeOutputMethod, bits, padding);
|
||||
};
|
||||
|
||||
var createKmacMethod = function (bits, padding) {
|
||||
var w = CSHAKE_BYTEPAD[bits];
|
||||
var method = createKmacOutputMethod(bits, padding, 'hex');
|
||||
method.create = function (key, outputBits, s) {
|
||||
return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);
|
||||
};
|
||||
method.update = function (key, message, outputBits, s) {
|
||||
return method.create(key, outputBits, s).update(message);
|
||||
};
|
||||
return createOutputMethods(method, createKmacOutputMethod, bits, padding);
|
||||
};
|
||||
|
||||
var algorithms = [
|
||||
{ name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },
|
||||
{ name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },
|
||||
{ name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },
|
||||
{ name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },
|
||||
{ name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }
|
||||
];
|
||||
|
||||
var methods = {}, methodNames = [];
|
||||
|
||||
for (var i = 0; i < algorithms.length; ++i) {
|
||||
var algorithm = algorithms[i];
|
||||
var bits = algorithm.bits;
|
||||
for (var j = 0; j < bits.length; ++j) {
|
||||
var methodName = algorithm.name + '_' + bits[j];
|
||||
methodNames.push(methodName);
|
||||
methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);
|
||||
if (algorithm.name !== 'sha3') {
|
||||
var newMethodName = algorithm.name + bits[j];
|
||||
methodNames.push(newMethodName);
|
||||
methods[newMethodName] = methods[methodName];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
methodNames.push("extractLast20Bytes");
|
||||
methods["extractLast20Bytes"] = extractLast20Bytes;
|
||||
|
||||
|
||||
function Keccak(bits, padding, outputBits) {
|
||||
this.blocks = [];
|
||||
this.s = [];
|
||||
this.padding = padding;
|
||||
this.outputBits = outputBits;
|
||||
this.reset = true;
|
||||
this.finalized = false;
|
||||
this.block = 0;
|
||||
this.start = 0;
|
||||
this.blockCount = (1600 - (bits << 1)) >> 5;
|
||||
this.byteCount = this.blockCount << 2;
|
||||
this.outputBlocks = outputBits >> 5;
|
||||
this.extraBytes = (outputBits & 31) >> 3;
|
||||
|
||||
for (var i = 0; i < 50; ++i) {
|
||||
this.s[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
Keccak.prototype.update = function (message) {
|
||||
if (this.finalized) {
|
||||
throw new Error(FINALIZE_ERROR);
|
||||
}
|
||||
var result = formatMessage(message);
|
||||
message = result[0];
|
||||
var isString = result[1];
|
||||
var blocks = this.blocks, byteCount = this.byteCount, length = message.length,
|
||||
blockCount = this.blockCount, index = 0, s = this.s, i, code;
|
||||
|
||||
while (index < length) {
|
||||
if (this.reset) {
|
||||
this.reset = false;
|
||||
blocks[0] = this.block;
|
||||
for (i = 1; i < blockCount + 1; ++i) {
|
||||
blocks[i] = 0;
|
||||
}
|
||||
}
|
||||
if (isString) {
|
||||
for (i = this.start; index < length && i < byteCount; ++index) {
|
||||
code = message.charCodeAt(index);
|
||||
if (code < 0x80) {
|
||||
blocks[i >> 2] |= code << SHIFT[i++ & 3];
|
||||
} else if (code < 0x800) {
|
||||
blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
|
||||
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
|
||||
} else if (code < 0xd800 || code >= 0xe000) {
|
||||
blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
|
||||
blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
|
||||
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
|
||||
} else {
|
||||
code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
|
||||
blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
|
||||
blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
|
||||
blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
|
||||
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (i = this.start; index < length && i < byteCount; ++index) {
|
||||
blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
|
||||
}
|
||||
}
|
||||
this.lastByteIndex = i;
|
||||
if (i >= byteCount) {
|
||||
this.start = i - byteCount;
|
||||
this.block = blocks[blockCount];
|
||||
for (i = 0; i < blockCount; ++i) {
|
||||
s[i] ^= blocks[i];
|
||||
}
|
||||
f(s);
|
||||
this.reset = true;
|
||||
} else {
|
||||
this.start = i;
|
||||
}
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
Keccak.prototype.encode = function (x, right) {
|
||||
var o = x & 255, n = 1;
|
||||
var bytes = [o];
|
||||
x = x >> 8;
|
||||
o = x & 255;
|
||||
while (o > 0) {
|
||||
bytes.unshift(o);
|
||||
x = x >> 8;
|
||||
o = x & 255;
|
||||
++n;
|
||||
}
|
||||
if (right) {
|
||||
bytes.push(n);
|
||||
} else {
|
||||
bytes.unshift(n);
|
||||
}
|
||||
this.update(bytes);
|
||||
return bytes.length;
|
||||
};
|
||||
|
||||
Keccak.prototype.encodeString = function (str) {
|
||||
var result = formatMessage(str);
|
||||
str = result[0];
|
||||
var isString = result[1];
|
||||
var bytes = 0, length = str.length;
|
||||
if (isString) {
|
||||
for (var i = 0; i < str.length; ++i) {
|
||||
var code = str.charCodeAt(i);
|
||||
if (code < 0x80) {
|
||||
bytes += 1;
|
||||
} else if (code < 0x800) {
|
||||
bytes += 2;
|
||||
} else if (code < 0xd800 || code >= 0xe000) {
|
||||
bytes += 3;
|
||||
} else {
|
||||
code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));
|
||||
bytes += 4;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
bytes = length;
|
||||
}
|
||||
bytes += this.encode(bytes * 8);
|
||||
this.update(str);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
Keccak.prototype.bytepad = function (strs, w) {
|
||||
var bytes = this.encode(w);
|
||||
for (var i = 0; i < strs.length; ++i) {
|
||||
bytes += this.encodeString(strs[i]);
|
||||
}
|
||||
var paddingBytes = (w - bytes % w) % w;
|
||||
var zeros = [];
|
||||
zeros.length = paddingBytes;
|
||||
this.update(zeros);
|
||||
return this;
|
||||
};
|
||||
|
||||
Keccak.prototype.finalize = function () {
|
||||
if (this.finalized) {
|
||||
return;
|
||||
}
|
||||
this.finalized = true;
|
||||
var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
|
||||
blocks[i >> 2] |= this.padding[i & 3];
|
||||
if (this.lastByteIndex === this.byteCount) {
|
||||
blocks[0] = blocks[blockCount];
|
||||
for (i = 1; i < blockCount + 1; ++i) {
|
||||
blocks[i] = 0;
|
||||
}
|
||||
}
|
||||
blocks[blockCount - 1] |= 0x80000000;
|
||||
for (i = 0; i < blockCount; ++i) {
|
||||
s[i] ^= blocks[i];
|
||||
}
|
||||
f(s);
|
||||
};
|
||||
|
||||
Keccak.prototype.toString = Keccak.prototype.hex = function () {
|
||||
this.finalize();
|
||||
|
||||
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
|
||||
extraBytes = this.extraBytes, i = 0, j = 0;
|
||||
var hex = '', block;
|
||||
while (j < outputBlocks) {
|
||||
for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
|
||||
block = s[i];
|
||||
hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +
|
||||
HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +
|
||||
HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +
|
||||
HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
|
||||
}
|
||||
if (j % blockCount === 0) {
|
||||
f(s);
|
||||
i = 0;
|
||||
}
|
||||
}
|
||||
if (extraBytes) {
|
||||
block = s[i];
|
||||
hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
|
||||
if (extraBytes > 1) {
|
||||
hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
|
||||
}
|
||||
if (extraBytes > 2) {
|
||||
hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
|
||||
}
|
||||
}
|
||||
return hex;
|
||||
};
|
||||
|
||||
Keccak.prototype.arrayBuffer = function () {
|
||||
this.finalize();
|
||||
|
||||
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
|
||||
extraBytes = this.extraBytes, i = 0, j = 0;
|
||||
var bytes = this.outputBits >> 3;
|
||||
var buffer;
|
||||
if (extraBytes) {
|
||||
buffer = new ArrayBuffer((outputBlocks + 1) << 2);
|
||||
} else {
|
||||
buffer = new ArrayBuffer(bytes);
|
||||
}
|
||||
var array = new Uint32Array(buffer);
|
||||
while (j < outputBlocks) {
|
||||
for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
|
||||
array[j] = s[i];
|
||||
}
|
||||
if (j % blockCount === 0) {
|
||||
f(s);
|
||||
}
|
||||
}
|
||||
if (extraBytes) {
|
||||
array[i] = s[i];
|
||||
buffer = buffer.slice(0, bytes);
|
||||
}
|
||||
return buffer;
|
||||
};
|
||||
|
||||
Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
|
||||
|
||||
Keccak.prototype.digest = Keccak.prototype.array = function () {
|
||||
this.finalize();
|
||||
|
||||
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
|
||||
extraBytes = this.extraBytes, i = 0, j = 0;
|
||||
var array = [], offset, block;
|
||||
while (j < outputBlocks) {
|
||||
for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
|
||||
offset = j << 2;
|
||||
block = s[i];
|
||||
array[offset] = block & 0xFF;
|
||||
array[offset + 1] = (block >> 8) & 0xFF;
|
||||
array[offset + 2] = (block >> 16) & 0xFF;
|
||||
array[offset + 3] = (block >> 24) & 0xFF;
|
||||
}
|
||||
if (j % blockCount === 0) {
|
||||
f(s);
|
||||
}
|
||||
}
|
||||
if (extraBytes) {
|
||||
offset = j << 2;
|
||||
block = s[i];
|
||||
array[offset] = block & 0xFF;
|
||||
if (extraBytes > 1) {
|
||||
array[offset + 1] = (block >> 8) & 0xFF;
|
||||
}
|
||||
if (extraBytes > 2) {
|
||||
array[offset + 2] = (block >> 16) & 0xFF;
|
||||
}
|
||||
}
|
||||
return array;
|
||||
};
|
||||
|
||||
function Kmac(bits, padding, outputBits) {
|
||||
Keccak.call(this, bits, padding, outputBits);
|
||||
}
|
||||
|
||||
Kmac.prototype = new Keccak();
|
||||
|
||||
Kmac.prototype.finalize = function () {
|
||||
this.encode(this.outputBits, true);
|
||||
return Keccak.prototype.finalize.call(this);
|
||||
};
|
||||
|
||||
var f = function (s) {
|
||||
var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,
|
||||
b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,
|
||||
b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,
|
||||
b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
|
||||
for (n = 0; n < 48; n += 2) {
|
||||
c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
|
||||
c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
|
||||
c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
|
||||
c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
|
||||
c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
|
||||
c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
|
||||
c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
|
||||
c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
|
||||
c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
|
||||
c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
|
||||
|
||||
h = c8 ^ ((c2 << 1) | (c3 >>> 31));
|
||||
l = c9 ^ ((c3 << 1) | (c2 >>> 31));
|
||||
s[0] ^= h;
|
||||
s[1] ^= l;
|
||||
s[10] ^= h;
|
||||
s[11] ^= l;
|
||||
s[20] ^= h;
|
||||
s[21] ^= l;
|
||||
s[30] ^= h;
|
||||
s[31] ^= l;
|
||||
s[40] ^= h;
|
||||
s[41] ^= l;
|
||||
h = c0 ^ ((c4 << 1) | (c5 >>> 31));
|
||||
l = c1 ^ ((c5 << 1) | (c4 >>> 31));
|
||||
s[2] ^= h;
|
||||
s[3] ^= l;
|
||||
s[12] ^= h;
|
||||
s[13] ^= l;
|
||||
s[22] ^= h;
|
||||
s[23] ^= l;
|
||||
s[32] ^= h;
|
||||
s[33] ^= l;
|
||||
s[42] ^= h;
|
||||
s[43] ^= l;
|
||||
h = c2 ^ ((c6 << 1) | (c7 >>> 31));
|
||||
l = c3 ^ ((c7 << 1) | (c6 >>> 31));
|
||||
s[4] ^= h;
|
||||
s[5] ^= l;
|
||||
s[14] ^= h;
|
||||
s[15] ^= l;
|
||||
s[24] ^= h;
|
||||
s[25] ^= l;
|
||||
s[34] ^= h;
|
||||
s[35] ^= l;
|
||||
s[44] ^= h;
|
||||
s[45] ^= l;
|
||||
h = c4 ^ ((c8 << 1) | (c9 >>> 31));
|
||||
l = c5 ^ ((c9 << 1) | (c8 >>> 31));
|
||||
s[6] ^= h;
|
||||
s[7] ^= l;
|
||||
s[16] ^= h;
|
||||
s[17] ^= l;
|
||||
s[26] ^= h;
|
||||
s[27] ^= l;
|
||||
s[36] ^= h;
|
||||
s[37] ^= l;
|
||||
s[46] ^= h;
|
||||
s[47] ^= l;
|
||||
h = c6 ^ ((c0 << 1) | (c1 >>> 31));
|
||||
l = c7 ^ ((c1 << 1) | (c0 >>> 31));
|
||||
s[8] ^= h;
|
||||
s[9] ^= l;
|
||||
s[18] ^= h;
|
||||
s[19] ^= l;
|
||||
s[28] ^= h;
|
||||
s[29] ^= l;
|
||||
s[38] ^= h;
|
||||
s[39] ^= l;
|
||||
s[48] ^= h;
|
||||
s[49] ^= l;
|
||||
|
||||
b0 = s[0];
|
||||
b1 = s[1];
|
||||
b32 = (s[11] << 4) | (s[10] >>> 28);
|
||||
b33 = (s[10] << 4) | (s[11] >>> 28);
|
||||
b14 = (s[20] << 3) | (s[21] >>> 29);
|
||||
b15 = (s[21] << 3) | (s[20] >>> 29);
|
||||
b46 = (s[31] << 9) | (s[30] >>> 23);
|
||||
b47 = (s[30] << 9) | (s[31] >>> 23);
|
||||
b28 = (s[40] << 18) | (s[41] >>> 14);
|
||||
b29 = (s[41] << 18) | (s[40] >>> 14);
|
||||
b20 = (s[2] << 1) | (s[3] >>> 31);
|
||||
b21 = (s[3] << 1) | (s[2] >>> 31);
|
||||
b2 = (s[13] << 12) | (s[12] >>> 20);
|
||||
b3 = (s[12] << 12) | (s[13] >>> 20);
|
||||
b34 = (s[22] << 10) | (s[23] >>> 22);
|
||||
b35 = (s[23] << 10) | (s[22] >>> 22);
|
||||
b16 = (s[33] << 13) | (s[32] >>> 19);
|
||||
b17 = (s[32] << 13) | (s[33] >>> 19);
|
||||
b48 = (s[42] << 2) | (s[43] >>> 30);
|
||||
b49 = (s[43] << 2) | (s[42] >>> 30);
|
||||
b40 = (s[5] << 30) | (s[4] >>> 2);
|
||||
b41 = (s[4] << 30) | (s[5] >>> 2);
|
||||
b22 = (s[14] << 6) | (s[15] >>> 26);
|
||||
b23 = (s[15] << 6) | (s[14] >>> 26);
|
||||
b4 = (s[25] << 11) | (s[24] >>> 21);
|
||||
b5 = (s[24] << 11) | (s[25] >>> 21);
|
||||
b36 = (s[34] << 15) | (s[35] >>> 17);
|
||||
b37 = (s[35] << 15) | (s[34] >>> 17);
|
||||
b18 = (s[45] << 29) | (s[44] >>> 3);
|
||||
b19 = (s[44] << 29) | (s[45] >>> 3);
|
||||
b10 = (s[6] << 28) | (s[7] >>> 4);
|
||||
b11 = (s[7] << 28) | (s[6] >>> 4);
|
||||
b42 = (s[17] << 23) | (s[16] >>> 9);
|
||||
b43 = (s[16] << 23) | (s[17] >>> 9);
|
||||
b24 = (s[26] << 25) | (s[27] >>> 7);
|
||||
b25 = (s[27] << 25) | (s[26] >>> 7);
|
||||
b6 = (s[36] << 21) | (s[37] >>> 11);
|
||||
b7 = (s[37] << 21) | (s[36] >>> 11);
|
||||
b38 = (s[47] << 24) | (s[46] >>> 8);
|
||||
b39 = (s[46] << 24) | (s[47] >>> 8);
|
||||
b30 = (s[8] << 27) | (s[9] >>> 5);
|
||||
b31 = (s[9] << 27) | (s[8] >>> 5);
|
||||
b12 = (s[18] << 20) | (s[19] >>> 12);
|
||||
b13 = (s[19] << 20) | (s[18] >>> 12);
|
||||
b44 = (s[29] << 7) | (s[28] >>> 25);
|
||||
b45 = (s[28] << 7) | (s[29] >>> 25);
|
||||
b26 = (s[38] << 8) | (s[39] >>> 24);
|
||||
b27 = (s[39] << 8) | (s[38] >>> 24);
|
||||
b8 = (s[48] << 14) | (s[49] >>> 18);
|
||||
b9 = (s[49] << 14) | (s[48] >>> 18);
|
||||
|
||||
s[0] = b0 ^ (~b2 & b4);
|
||||
s[1] = b1 ^ (~b3 & b5);
|
||||
s[10] = b10 ^ (~b12 & b14);
|
||||
s[11] = b11 ^ (~b13 & b15);
|
||||
s[20] = b20 ^ (~b22 & b24);
|
||||
s[21] = b21 ^ (~b23 & b25);
|
||||
s[30] = b30 ^ (~b32 & b34);
|
||||
s[31] = b31 ^ (~b33 & b35);
|
||||
s[40] = b40 ^ (~b42 & b44);
|
||||
s[41] = b41 ^ (~b43 & b45);
|
||||
s[2] = b2 ^ (~b4 & b6);
|
||||
s[3] = b3 ^ (~b5 & b7);
|
||||
s[12] = b12 ^ (~b14 & b16);
|
||||
s[13] = b13 ^ (~b15 & b17);
|
||||
s[22] = b22 ^ (~b24 & b26);
|
||||
s[23] = b23 ^ (~b25 & b27);
|
||||
s[32] = b32 ^ (~b34 & b36);
|
||||
s[33] = b33 ^ (~b35 & b37);
|
||||
s[42] = b42 ^ (~b44 & b46);
|
||||
s[43] = b43 ^ (~b45 & b47);
|
||||
s[4] = b4 ^ (~b6 & b8);
|
||||
s[5] = b5 ^ (~b7 & b9);
|
||||
s[14] = b14 ^ (~b16 & b18);
|
||||
s[15] = b15 ^ (~b17 & b19);
|
||||
s[24] = b24 ^ (~b26 & b28);
|
||||
s[25] = b25 ^ (~b27 & b29);
|
||||
s[34] = b34 ^ (~b36 & b38);
|
||||
s[35] = b35 ^ (~b37 & b39);
|
||||
s[44] = b44 ^ (~b46 & b48);
|
||||
s[45] = b45 ^ (~b47 & b49);
|
||||
s[6] = b6 ^ (~b8 & b0);
|
||||
s[7] = b7 ^ (~b9 & b1);
|
||||
s[16] = b16 ^ (~b18 & b10);
|
||||
s[17] = b17 ^ (~b19 & b11);
|
||||
s[26] = b26 ^ (~b28 & b20);
|
||||
s[27] = b27 ^ (~b29 & b21);
|
||||
s[36] = b36 ^ (~b38 & b30);
|
||||
s[37] = b37 ^ (~b39 & b31);
|
||||
s[46] = b46 ^ (~b48 & b40);
|
||||
s[47] = b47 ^ (~b49 & b41);
|
||||
s[8] = b8 ^ (~b0 & b2);
|
||||
s[9] = b9 ^ (~b1 & b3);
|
||||
s[18] = b18 ^ (~b10 & b12);
|
||||
s[19] = b19 ^ (~b11 & b13);
|
||||
s[28] = b28 ^ (~b20 & b22);
|
||||
s[29] = b29 ^ (~b21 & b23);
|
||||
s[38] = b38 ^ (~b30 & b32);
|
||||
s[39] = b39 ^ (~b31 & b33);
|
||||
s[48] = b48 ^ (~b40 & b42);
|
||||
s[49] = b49 ^ (~b41 & b43);
|
||||
|
||||
s[0] ^= RC[n];
|
||||
s[1] ^= RC[n + 1];
|
||||
}
|
||||
};
|
||||
|
||||
function extractLast20Bytes(hexString, addPrefix) {
|
||||
// Ensure the input hexString has '0x' prefix
|
||||
if (!hexString.startsWith('0x')) {
|
||||
hexString = '0x' + hexString;
|
||||
}
|
||||
|
||||
// Remove '0x' prefix and parse the hex string to a BigInt
|
||||
var bigIntValue = BigInt(hexString);
|
||||
|
||||
// Extract the last 20 bytes (160 bits) from the BigInt
|
||||
var last20Bytes = bigIntValue & BigInt('0x' + 'f'.repeat(40)); // 0xf is 4 bits in hexadecimal, repeated 40 times for 160 bits
|
||||
|
||||
// Convert the result back to a hexadecimal string
|
||||
var result = last20Bytes.toString(16).padStart(40, '0'); // 40 characters for 160 bits
|
||||
|
||||
// Add '0x' prefix if addPrefix is truthy
|
||||
if (addPrefix) {
|
||||
result = '0x' + result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
if (typeof root.keccak === 'object') {
|
||||
Object.assign(root.keccak, methods);
|
||||
}
|
||||
|
||||
if (COMMON_JS) {
|
||||
module.exports = methods;
|
||||
} else {
|
||||
for (i = 0; i < methodNames.length; ++i) {
|
||||
root[methodNames[i]] = methods[methodNames[i]];
|
||||
}
|
||||
if (AMD) {
|
||||
define(function () {
|
||||
return methods;
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
Loading…
Reference in New Issue
Block a user