Created
August 28, 2018 03:13
-
-
Save akirattii/25b5fb2f7c5fc9b69432fa646785b4ed to your computer and use it in GitHub Desktop.
JS: How to parse Payments URI Scheme
This file contains hidden or 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
/** | |
* Payments URI Scheme Parser | |
* @param {String} - eg. "bitcoin:1XXX?amount=123&comment=%66%77" | |
* @see also: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki | |
*/ | |
function parsePaymentURIScheme(s) { | |
const tmp = s.match(/^(\w+)\:(\w+)\??(.+)?/); | |
const protocol = (tmp && tmp.length >= 1) ? tmp[1] : null; | |
const address = (tmp && tmp.length >= 2) ? tmp[2] : null; | |
const qstr = (tmp && tmp.length >= 3) ? tmp[3] : null; | |
const params = parseQS(qstr); | |
if (!protocol || !address) return null; | |
const ret = {}; | |
if (protocol) ret.protocol = protocol; | |
if (address) ret.address = address; | |
if (params) ret.params = params; | |
return ret | |
function parseQS(s) { | |
if (!s) return null; | |
const lines = s.split('&'); | |
if (!lines) return null; | |
const arr = []; | |
for (let len = lines.length, i = 0; i < len; i++) { | |
const line = lines[i]; | |
const [k, v] = line.split('='); | |
if (!k || !k.trim()) continue; | |
arr.push({ | |
key: k, | |
value: (v) ? decodeURIComponent(v) : null, | |
}); | |
} | |
return arr; | |
} | |
}; | |
// | |
// test | |
// | |
let ret = parsePaymentURIScheme("bitcoin:1XXXXX?amount=123&comment=%66%77"); | |
console.log(JSON.stringify(ret, null, 2)); | |
/* | |
{ | |
"protocol": "bitcoin", | |
"address": "1XXXXX", | |
"params": [ | |
{ | |
"key": "amount", | |
"value": "123" | |
}, | |
{ | |
"key": "comment", | |
"value": "fw" | |
} | |
] | |
} | |
*/ | |
ret = parsePaymentURIScheme("bitcoin:1XXXXX"); | |
console.log(JSON.stringify(ret, null, 2)); | |
/* | |
{ | |
"protocol": "bitcoin", | |
"address": "1XXXXX" | |
} | |
*/ | |
ret = parsePaymentURIScheme("bitcoin"); | |
console.log(JSON.stringify(ret, null, 2)); // null | |
ret = parsePaymentURIScheme(":1XXXX"); | |
console.log(JSON.stringify(ret, null, 2)); // null | |
ret = parsePaymentURIScheme(""); | |
console.log(JSON.stringify(ret, null, 2)); // null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment