From 349fcae37ff01e8e9a023d7015f3103dbaeeeb15 Mon Sep 17 00:00:00 2001 From: sairajzero Date: Sun, 26 Jun 2022 19:13:53 +0530 Subject: [PATCH] cross-blockchain WIF conversion - convert compressed WIF from one blockchain to another (target privkey prefix needed) - btc_api.pubkey: return the same if pubkey is passed. (thus address, segwitAddress, bech32Address now accepts pubkey, privkey and wif) - btc_api.address: accepts optional parameter 'prefix' to generate address for respective blockchain (Default: 0x00 BTC) --- .gitignore | 1 + lib_btc.js | 40 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..168b657 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.tmp* \ No newline at end of file diff --git a/lib_btc.js b/lib_btc.js index 262f86a..92cfffd 100644 --- a/lib_btc.js +++ b/lib_btc.js @@ -2599,10 +2599,10 @@ } }, pubkey: { - value: key => key.length === 64 ? coinjs.newPubkey(key) : coinjs.wif2pubkey(key).pubkey + value: key => key.length === 66 ? key : (key.length === 64 ? coinjs.newPubkey(key) : coinjs.wif2pubkey(key).pubkey) }, address: { - value: key => coinjs.pubkey2address(btc_api.pubkey(key)) + value: (key, prefix = undefined) => coinjs.pubkey2address(btc_api.pubkey(key), prefix) }, segwitAddress: { value: key => coinjs.segwitAddress(btc_api.pubkey(key)).address @@ -2639,6 +2639,42 @@ return false; } + //convert WIF from one blockchain to another (target privkey-prefix needed) + btc_api.convert_wif = function(source_wif, target_prefix = coinjs.priv) { + //decode the wif + var decode = coinjs.base58decode(source_wif); + var key = decode.slice(0, decode.length - 4), + checksum = decode.slice(decode.length - 4); + //verify checksum of inpput wif + var hash = Crypto.SHA256(Crypto.SHA256(key, { + asBytes: true + }), { + asBytes: true + }); + if (hash[0] != checksum[0] || + hash[1] != checksum[1] || + hash[2] != checksum[2] || + hash[3] != checksum[3]) { + throw "Checksum validation failed!"; + } + //version of input wif + let version = key.shift(); + //check if wif is compressed + if (key.length < 33 || key[key.length - 1] != 0x01) + throw "Key is uncompressed"; + //add target prefix + key.unshift(target_prefix); + //concat checksum + var hash = Crypto.SHA256(Crypto.SHA256(key, { + asBytes: true + }), { + asBytes: true + }); + var checksum = hash.slice(0, 4); + key = key.concat(checksum); + return coinjs.base58encode(key); + } + btc_api.getBalance = addr => new Promise((resolve, reject) => { fetch_api(`get_address_balance/BTC/${addr}`) .then(result => resolve(parseFloat(result.data.confirmed_balance)))