Last active
January 15, 2018 23:00
-
-
Save throughnothing/453a5cc9b6e76c77c4f240ce995c10c1 to your computer and use it in GitHub Desktop.
Parse all 3 Bitcoin Cash Address formats into a bitcore Address object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cashaddrjs = require('cashaddrjs'); | |
var bitcore = require('bitcore-lib'); | |
var bitcoreCash = require('bitcore-lib-cash'); | |
// Get a bitcore.Address object for any address type | |
// - Legacy (BTC-style) | |
// - Copay (BitPay, probably will be deprecated?) | |
// - Cashaddr (new BCH format) | |
var getAddressObj = function(addressStr) { | |
try { | |
return new bitcore.Address(addressStr); | |
} catch (e) { | |
try { | |
return new bitcoreCash.Address(addressStr); | |
} catch (e2) { | |
try { | |
return bitcore.Address(new Buffer(cashaddrjs.decode(addressStr).hash)) | |
} catch (e3) { | |
return null; | |
} | |
} | |
} | |
}; | |
var toCashAddress = function(AddressObj) { | |
var type = AddressObj.type === bitcore.Address.PayToPublicKeyHash ? 'P2PKH' : 'P2SH'; | |
var hash = new Uint8Array(AddressObj.hashBuffer); | |
return cashaddrjs.encode('bitcoincash', type, hash); | |
} | |
var addressStrs = [ | |
'bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a', | |
'1HXmMKvXyUNcNkT276fMyLbvDUn7GyrFsM', | |
'CPWg6JjEJd9nwn4mcyDuPZGRWfmqxNwTXz', | |
] | |
addressStrs | |
.map(getAddressObj) | |
.map(function(a){ console.log(a); return a; }) | |
.map(toCashAddress) | |
.map(function(a){ console.log(a); return a; }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment