├── package.json ├── README.md ├── LICENSE ├── .gitignore ├── cache.js ├── connection.js ├── protocol.js └── index.js /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "minigate", 3 | "version": "0.4.1", 4 | "description": "A light weight metanet gateway.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node index.js test" 8 | }, 9 | "bin": { 10 | "minigate": "./index.js" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/monkeylord/MiniGate.git" 15 | }, 16 | "keywords": [ 17 | "metanet", 18 | "bitcoin", 19 | "gateway", 20 | "website", 21 | "electrum", 22 | "bsv" 23 | ], 24 | "author": "Monkeylord", 25 | "license": "MIT", 26 | "bugs": { 27 | "url": "https://github.com/monkeylord/MiniGate/issues" 28 | }, 29 | "homepage": "https://github.com/monkeylord/MiniGate#readme", 30 | "dependencies": { 31 | "bsv": "^1.5.3", 32 | "commander": "^2.19.0", 33 | "electrum-client": "0.0.6", 34 | "express": "^4.16.4", 35 | "mime-lookup": "0.0.2" 36 | }, 37 | "devDependencies": {} 38 | } 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MiniGate 2 | A light weight metanet gateway for bitcoin. 3 | 4 | ### Install 5 | 6 | #### Install Nodejs 7 | 8 | Download Nodejs [here](https://nodejs.org/). 9 | 10 | #### Install MiniGate 11 | 12 | 1. Open a command line. 13 | 2. `npm install -g minigate` 14 | 15 | ### Usage 16 | 17 | Use command 18 | 19 | ~~~shell 20 | minigate 21 | ~~~ 22 | 23 | You will see 24 | 25 | >MiniGate Listening on 8000 ... 26 | > Version: 0.0.1 27 | > Electrum Server: electrumx.bitcoinsv.io:50002 28 | 29 | Now you can browse metanet B protocol resources at http://127.0.0.1:8000/[txid] 30 | 31 | ### Advanced 32 | 33 | You can specify which ElectrumX server minigate should connect to, by `-e` option. 34 | 35 | like `minigate -e sv.satoshi.io`:50002 36 | 37 | To find ElectrumX server, just open your electrum wallet, `Tools` -> `Network` -> `Server`, then you can see a list of server. 38 | 39 | You can also specify which local port minigate should listen to, by `-p` option. 40 | 41 | like `minigate -p 8080` 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Monkeylord 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | -------------------------------------------------------------------------------- /cache.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const os = require('os') 3 | var Cache = {} 4 | 5 | var cacheDir = os.tmpdir()+"\/minigate" 6 | 7 | Cache.loadDTree = function (addr){ 8 | if(!fs.existsSync(`${cacheDir}\/${addr}.d.json`))return {} 9 | else return JSON.parse(fs.readFileSync(`${cacheDir}\/${addr}.d.json`).toString()) 10 | } 11 | 12 | Cache.saveDTree = function (addr, dTree){ 13 | fs.writeFileSync(`${cacheDir}\/${addr}.d.json`,JSON.stringify(dTree,null,2)) 14 | } 15 | 16 | Cache.updateDTree = function (dTree, dRecord){ 17 | // Update if D Record is newer 18 | if( !dTree[dRecord.key] || dTree[dRecord.key].sequence < dRecord.sequence ){ 19 | console.log(` - ${dRecord.key} Updated.`) 20 | dTree[dRecord.key] = dRecord 21 | } 22 | dTree.lastUpdate = new Date().getTime() 23 | } 24 | 25 | Cache.cleanCache = function (){ 26 | var count = 0 27 | if(fs.existsSync(cacheDir)){ 28 | var txFiles = fs.readdirSync(cacheDir) 29 | count = txFiles.length 30 | txFiles.forEach(function(file) { 31 | var cachedTXFile = cacheDir + "/" + file 32 | fs.unlinkSync(cachedTXFile) 33 | }) 34 | fs.rmdirSync(cacheDir); 35 | } 36 | console.log(`MiniGate: ${ count } cached TX(s) cleaned`) 37 | } 38 | 39 | Cache.getCache = function getCache(txid){ 40 | if(fs.existsSync(cacheDir)){ 41 | if(fs.existsSync(cacheDir+'\/'+txid))return fs.readFileSync(cacheDir+'\/'+txid).toString() 42 | else return null 43 | }else return null 44 | } 45 | 46 | Cache.setCache = function (txid, tx){ 47 | if(!fs.existsSync(cacheDir))fs.mkdirSync(cacheDir) 48 | fs.writeFileSync(cacheDir+"\/"+txid, tx) 49 | } 50 | 51 | 52 | module.exports = Cache -------------------------------------------------------------------------------- /connection.js: -------------------------------------------------------------------------------- 1 | const ElectrumCli = require('electrum-client') 2 | 3 | var eclreuse = null 4 | var curHost = "" 5 | var curPort = "" 6 | 7 | var serverpool = [ 8 | 'electrumx.bitcoinsv.io:50002', 9 | 'sv.satoshi.io:50002', 10 | 'sv2.satoshi.io:50002', 11 | //'sv.electrumx.cash:50002' 12 | ] 13 | 14 | function Connection(){} 15 | 16 | function getCliFromPool(){ 17 | if(eclreuse!=null)return (async()=>{return eclreuse})() 18 | // get the fastest server 19 | else return Promise.race(serverpool.map(server=>{ 20 | var esHost = server.split(':')[0] 21 | var esPort = parseInt(server.split(':')[1]) 22 | var ecl = new ElectrumCli(esPort, esHost, 'tls') 23 | return ecl.connect().then(()=>{ 24 | return ecl 25 | }) 26 | })).then((ecl)=>{ 27 | curHost = ecl.host 28 | curPort = ecl.port 29 | eclreuse = ecl 30 | ecl.onClose = ()=>{ 31 | console.log("Presisted Connection to ElectrumX Server Closed.") 32 | eclreuse = null 33 | } 34 | return ecl.server_version(`MiniGate v${version}`, "1.4").then(()=>{ 35 | return ecl.serverDonation_address().then(address=>{ 36 | console.log("Presisted Connection to ElectrumX Server Established.") 37 | console.log(` ElectrumX Server Connected: ${curHost + ":" + curPort}`) 38 | console.log(` ElectrumX Server Donations: ${ address }`) 39 | console.log(`You can help electrumX server staying alive by making a donation to it.\n`) 40 | }) 41 | }).then(()=>{ 42 | return ecl 43 | }) 44 | }) 45 | } 46 | 47 | async function fetchTX(txid){ 48 | var fetchedTX = null 49 | var ecl = null 50 | 51 | // check if tx cached 52 | if(program.cache){ 53 | var cachedTX = getCache(txid) 54 | if(cachedTX){ 55 | console.log(` - Cache matched ${txid}`) 56 | fetchedTX = (async()=>{return cachedTX})() 57 | } 58 | } 59 | 60 | // fetch TX from electrumX server 61 | if(fetchedTX == null){ 62 | fetchedTX = getCliFromPool().then(result=>{ 63 | ecl = result 64 | return ecl.connect() 65 | }).then(r=>{ 66 | console.log(` - Getting ${txid}`) 67 | return ecl.blockchainTransaction_get(txid, false).then(tx=>{ 68 | if(!tx.code){ 69 | tx = bsv.Transaction(tx) 70 | //console.log(tx.id) 71 | setCache(tx.id,tx.toString()) 72 | } 73 | return tx 74 | }) 75 | }) 76 | } 77 | return fetchedTX 78 | } 79 | 80 | 81 | module.exports = Connections -------------------------------------------------------------------------------- /protocol.js: -------------------------------------------------------------------------------- 1 | const bsv = require('bsv') 2 | 3 | var Protocol = {} 4 | 5 | Protocol.resolveD = function (tx){ 6 | var tx = bsv.Transaction(tx) 7 | var DataOut = tx.outputs.filter(output=>output.script.isDataOut()||output.script.isSafeDataOut())[0] 8 | // Not Data transaction 9 | if(!DataOut)return null 10 | var script = DataOut.script 11 | // Malformed 12 | if(script.chunks.length<6)return null 13 | if(script.chunks[1].buf && script.chunks[1].buf.toString() === '19iG3WTYSsbyos3uJ733yK4zEioi1FesNU'){ 14 | return { 15 | key: script.chunks[2].buf.toString('utf-8'), 16 | value: script.chunks[3].buf.toString('utf-8'), 17 | type: script.chunks[4].buf.toString(), 18 | sequence: parseInt(script.chunks[5].buf)||1 19 | } 20 | } else if(script.chunks[2].buf && script.chunks[2].buf.toString() === '19iG3WTYSsbyos3uJ733yK4zEioi1FesNU'){ 21 | return { 22 | key: script.chunks[3].buf.toString('utf-8'), 23 | value: script.chunks[4].buf.toString('utf-8'), 24 | type: script.chunks[5].buf.toString(), 25 | sequence: parseInt(script.chunks[6].buf)||1 26 | } 27 | } else { 28 | // Not D transaction 29 | return null 30 | } 31 | } 32 | 33 | Protocol.resolveB = function (tx){ 34 | var tx = bsv.Transaction(tx) 35 | var Bscript = tx.outputs.filter(output=>output.script.isDataOut()||output.script.isSafeDataOut())[0].script 36 | if(Bscript.chunks[1].buf && Bscript.chunks[1].buf.toString() === '19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut'){ 37 | return { 38 | data: Bscript.chunks[2].buf, 39 | media_type: Bscript.chunks[3].buf.toString(), 40 | encoding: (Bscript.chunks[4])?Bscript.chunks[4].buf.toString():"", 41 | filename: (Bscript.chunks[5])?Bscript.chunks[5].buf.toString():"" 42 | } 43 | } else if(Bscript.chunks[2].buf && Bscript.chunks[2].buf.toString() === '19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut'){ 44 | return { 45 | data: Bscript.chunks[3].buf, 46 | media_type: Bscript.chunks[4].buf.toString(), 47 | encoding: (Bscript.chunks[5])?Bscript.chunks[4].buf.toString():"", 48 | filename: (Bscript.chunks[6])?Bscript.chunks[5].buf.toString():"" 49 | } 50 | } else { 51 | // Not B transaction 52 | return null 53 | } 54 | } 55 | 56 | Protocol.resolveBcat = function (tx){ 57 | var tx = bsv.Transaction(tx) 58 | var Bscript = tx.outputs.filter(output=>output.script.isDataOut()||output.script.isSafeDataOut())[0].script 59 | if(Bscript.chunks[1].buf && Bscript.chunks[1].buf.toString() === '15DHFxWZJT58f9nhyGnsRBqrgwK4W6h4Up'){ 60 | return { 61 | info: Bscript.chunks[2].buf, 62 | media_type: Bscript.chunks[3].buf.toString(), 63 | encoding: (Bscript.chunks[4])?Bscript.chunks[4].buf.toString():"", 64 | filename: (Bscript.chunks[5])?Bscript.chunks[5].buf.toString():"", 65 | flag: (Bscript.chunks[6])?Bscript.chunks[6].buf.toString():"", 66 | data:Bscript.chunks.slice(7).map(chunk=>chunk.buf.toString('hex')) 67 | } 68 | } else if(Bscript.chunks[2].buf && Bscript.chunks[2].buf.toString() === '15DHFxWZJT58f9nhyGnsRBqrgwK4W6h4Up'){ 69 | return { 70 | info: Bscript.chunks[3].buf, 71 | media_type: Bscript.chunks[4].buf.toString(), 72 | encoding: (Bscript.chunks[5])?Bscript.chunks[5].buf.toString():"", 73 | filename: (Bscript.chunks[6])?Bscript.chunks[6].buf.toString():"", 74 | flag: (Bscript.chunks[6])?Bscript.chunks[7].buf.toString():"", 75 | data:Bscript.chunks.slice(8).map(chunk=>chunk.buf.toString('hex')) 76 | } 77 | } else { 78 | // Not Bcat transaction 79 | return null 80 | } 81 | } 82 | Protocol.resolveBcatPart = function (tx){ 83 | var tx = bsv.Transaction(tx) 84 | var Bscript = tx.outputs.filter(output=>output.script.isDataOut()||output.script.isSafeDataOut())[0].script 85 | if(Bscript.chunks[1].buf && Bscript.chunks[1].buf.toString() === '1ChDHzdd1H4wSjgGMHyndZm6qxEDGjqpJL'){ 86 | return { 87 | data: Bscript.chunks[2].buf 88 | } 89 | } else if(Bscript.chunks[2].buf && Bscript.chunks[2].buf.toString() === '1ChDHzdd1H4wSjgGMHyndZm6qxEDGjqpJL'){ 90 | return { 91 | data: Bscript.chunks[3].buf 92 | } 93 | } else { 94 | // Not BcatPart transaction, try B 95 | return Protocol.resolveB(tx) 96 | } 97 | } 98 | 99 | module.exports = Protocol 100 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const os = require('os') 4 | const fs = require('fs') 5 | const program = require('commander') 6 | const express = require('express') 7 | const https = require('https') 8 | const app = express() 9 | const bsv = require('bsv') 10 | const ElectrumCli = require('electrum-client') 11 | const MimeLookup = require('mime-lookup') 12 | const mime = new MimeLookup(require('mime-db')) 13 | const txidReg = new RegExp('^[0-9a-fA-F]{64}$') 14 | const version = require('./package.json').version 15 | const Protocol = require('./protocol') 16 | const Cache = require('./cache') 17 | 18 | global.debug = false 19 | const DTREE_UPDATE_INTERVAL = 120000 20 | 21 | var serverpool = [ 22 | 'electrumx.bitcoinsv.io:50002', 23 | 'sv.satoshi.io:50002', 24 | 'sv2.satoshi.io:50002', 25 | //'sv.electrumx.cash:50002' 26 | ] 27 | 28 | program 29 | .command('test') 30 | .description('Test if MiniGate is working on ElectrumX') 31 | .action(test) 32 | 33 | program 34 | .command('start') 35 | .description('Start MiniGate.') 36 | .action(test) 37 | 38 | program 39 | .command('clean') 40 | .description('Clean cache.') 41 | .action(Cache.cleanCache) 42 | 43 | program 44 | .version(version) 45 | .option('-e, --electrumX [electrumXServer]', 'Specify a ElectrumX Server') 46 | .option('-p, --port [port]', 'Specify port minigate should listen on', 8000) 47 | .option('-s, --sslport [port]', 'Specify ssl port minigate should listen on', 8443) 48 | .option('-c, --cache [true/false]', 'Enable local TX cache', true) 49 | 50 | program 51 | .parse(process.argv); 52 | 53 | var eclreuse = null 54 | var curHost = "" 55 | var curPort = "" 56 | 57 | function getCliFromPool(){ 58 | if(eclreuse!=null)return (async()=>{return eclreuse})() 59 | // get the fastest server 60 | else return Promise.race(serverpool.map(server=>{ 61 | var esHost = server.split(':')[0] 62 | var esPort = parseInt(server.split(':')[1]) 63 | var ecl = new ElectrumCli(esPort, esHost, 'tls') 64 | return ecl.connect().then(()=>{ 65 | return ecl 66 | }) 67 | })).then((ecl)=>{ 68 | curHost = ecl.host 69 | curPort = ecl.port 70 | eclreuse = ecl 71 | ecl.onClose = ()=>{ 72 | console.log("Presisted Connection to ElectrumX Server Closed.") 73 | eclreuse = null 74 | } 75 | return ecl.server_version(`MiniGate v${version}`, "1.4").then(()=>{ 76 | return ecl.serverDonation_address().then(address=>{ 77 | console.log("Presisted Connection to ElectrumX Server Established.") 78 | console.log(` ElectrumX Server Connected: ${curHost + ":" + curPort}`) 79 | console.log(` ElectrumX Server Donations: ${ address }`) 80 | console.log(`You can help electrumX server staying alive by making a donation to it.\n`) 81 | }) 82 | }).then(()=>{ 83 | return ecl 84 | }) 85 | }) 86 | } 87 | 88 | function test(){ 89 | if(program.electrumX){ 90 | serverpool = [ program.electrumX ] 91 | } 92 | console.log("Testing if minigate can connect to electrumX server...") 93 | var ecl = null 94 | getCliFromPool().then(result=>{ 95 | ecl = result 96 | return ecl.connect() 97 | }).then(()=>{ 98 | console.log(` ElectrumX Server Connected: ${curHost + ":" + curPort}`) 99 | console.log("Nice! MiniGate is working.") 100 | ecl.close() 101 | }).catch(e=>{ 102 | console.log(e) 103 | console.log("Cannot connect to electrumX server.") 104 | console.log("You should specify a electrumX server.") 105 | console.log(" minigate [start|test] -e [ElectrumX Server Address:Port]") 106 | if(ecl)ecl.close() 107 | }).then(()=>{ 108 | process.exit() 109 | }) 110 | } 111 | 112 | function start(){ 113 | if(program.electrumX){ 114 | serverpool = [ program.electrumX ] 115 | } 116 | app.get('/', (req, res) => res.send('MiniGate Online')) 117 | app.get('/:txid', (req, res) => { 118 | res.header("Access-Control-Allow-Origin", "*") 119 | var txid = req.params.txid.split('.')[0] 120 | console.log(`Handling ${txid}`) 121 | if(!txidReg.test(txid)) { 122 | res.status(404) 123 | return res.send("MiniGate Error: Not A Valid TXID") 124 | } 125 | 126 | var fetchedTX = fetchTX(txid) 127 | // handle tx 128 | fetchedTX.then(tx=>{ 129 | if(tx.code){ 130 | // If code is not undefined, something must be wrong. 131 | res.status(500) 132 | res.send(JSON.stringify(tx)) 133 | }else{ 134 | var bcatRecord = Protocol.resolveBcat(tx) 135 | if(bcatRecord!=null){ 136 | Promise.all(bcatRecord.data.map(txid=>fetchTX(txid))).then(txs=>{ 137 | var bPartRecords = txs.map(tx=>Protocol.resolveBcatPart(tx)) 138 | bcatRecord.media_type = correctMIME(bcatRecord.media_type, req.params.txid) 139 | if(global.debug)console.log(bcatRecord.media_type) 140 | res.set('Content-Type',bcatRecord.media_type); 141 | res.send(replaceURL(Buffer.concat(bPartRecords.map(bPart=>bPart.data)),bcatRecord.media_type)) 142 | }) 143 | }else{ 144 | var bRecord = Protocol.resolveB(tx) 145 | bRecord.media_type = correctMIME(bRecord.media_type, req.params.txid) 146 | if(global.debug)console.log(bRecord.media_type) 147 | res.set('Content-Type',bRecord.media_type); 148 | res.send(replaceURL(bRecord.data, bRecord.media_type)) 149 | } 150 | Cache.setCache(tx.id,tx.toString()) 151 | } 152 | }).catch(e=>{ 153 | console.log(`Failed to Get ${ txid } ...`) 154 | console.log(e) 155 | //if(ecl)ecl.close() 156 | res.status(500) 157 | res.send(e) 158 | }) 159 | }) 160 | app.get('/:addr/[a-zA-Z0-9%_~\/@!$&*+,\.:;=-]+', (req, res, next) => { 161 | res.header("Access-Control-Allow-Origin", "*") 162 | if(!isAddress(req.params.addr))next() 163 | else{ 164 | var key = req.url.replace(`/${req.params.addr}/`,'').replace(/\?.*$/,'') 165 | console.log(`Handling ${req.params.addr}/${key}`) 166 | var dTree = Cache.loadDTree(req.params.addr) 167 | var beforeHandleD = Promise.resolve() 168 | if(!dTree.lastUpdate || (new Date().getTime() - dTree.lastUpdate) > DTREE_UPDATE_INTERVAL){ 169 | // Should Update DTree 170 | console.log(`Updating DTree for ${req.params.addr}`) 171 | beforeHandleD = getCliFromPool().then(ecl=>{ 172 | return ecl.connect().then(()=>{ 173 | return ecl 174 | }) 175 | }).then(ecl=>{ 176 | return ecl.blockchainScripthash_getHistory(getScriptHash(req.params.addr)) 177 | }).catch(e=>{ 178 | console.log(`Fail to get ${req.params.addr}'s latest record.`) 179 | return [] 180 | }).then(txs=>{ 181 | //console.log(txs) 182 | return Promise.all(txs.map(txrecord=>{ 183 | return fetchTX(txrecord.tx_hash).then(tx=>{ 184 | var record = Protocol.resolveD(tx) 185 | if(record)Cache.updateDTree(dTree,record) 186 | //console.log(tx.id) 187 | Cache.setCache(tx.id,tx.toString()) 188 | }) 189 | })) 190 | }).then(()=>{ 191 | Cache.saveDTree(req.params.addr, dTree) 192 | console.log(`DTree for ${req.params.addr} updated`) 193 | }) 194 | } 195 | 196 | // We have latest DTree, handle D request now 197 | beforeHandleD.then(()=>{ 198 | if(global.debug)console.log(dTree) 199 | if(global.debug)console.log(dTree[key]) 200 | if(dTree[key]) 201 | console.log(` - DRecord ${req.params.addr}/${key} found.\n - Type: ${dTree[key].type}\n - Value: ${dTree[key].value}\n - Last update: ${Date(dTree[key].sequence)}`) 202 | else console.log("404: " + key) 203 | if(dTree[key] && dTree[key].type == 'b')return fetchTX(dTree[key].value).then(tx=>{ 204 | var bRecord = Protocol.resolveB(tx) 205 | if(bRecord){ 206 | bRecord.media_type = correctMIME(bRecord.media_type, key) 207 | res.set('Content-Type',bRecord.media_type) 208 | res.send(replaceURL(bRecord.data, bRecord.media_type)) 209 | }else if(bRecord = Protocol.resolveBcat(tx)){ 210 | Promise.all(bRecord.data.map(txid=>fetchTX(txid))).then(txs=>{ 211 | var bPartRecords = txs.map(tx=>Protocol.resolveBcatPart(tx)) 212 | bRecord.media_type = correctMIME(bRecord.media_type, key) 213 | if(global.debug)console.log(bRecord.media_type) 214 | res.set('Content-Type',bRecord.media_type); 215 | res.send(replaceURL(Buffer.concat(bPartRecords.map(bPart=>bPart.data)),bRecord.media_type)) 216 | }) 217 | }else res.status(404).send(`${key} not found`) 218 | }) 219 | else res.status(404).send(`${key} not found`) 220 | }) 221 | } 222 | }) 223 | if (fs.existsSync('privkey.pem') && fs.existsSync('fullchain.pem')) { 224 | const httpsServer = https.createServer({ 225 | key: fs.readFileSync('privkey.pem'), 226 | cert: fs.readFileSync('fullchain.pem'), 227 | }, app) 228 | httpsServer.listen(program.sslport, () => { 229 | console.log(`MiniGate Listening with SSL on ${ program.sslport } ...`) 230 | }) 231 | } else { 232 | console.log('no privkey.pem / fullchain.pem: HTTPS disabled. letsencrypt.org provides free') 233 | } 234 | app.listen(program.port, () => console.log(`MiniGate Listening on ${ program.port } ...\n Version: ${ version }`)) 235 | getCliFromPool() 236 | } 237 | 238 | async function fetchTX(txid){ 239 | var fetchedTX = null 240 | var ecl = null 241 | 242 | // check if tx cached 243 | if(program.cache){ 244 | var cachedTX = Cache.getCache(txid) 245 | if(cachedTX){ 246 | console.log("Cache matched " + txid) 247 | fetchedTX = (async()=>{return cachedTX})() 248 | } 249 | } 250 | 251 | // fetch TX from electrumX server 252 | if(fetchedTX == null){ 253 | fetchedTX = getCliFromPool().then(result=>{ 254 | ecl = result 255 | return ecl.connect() 256 | }).then(r=>{ 257 | console.log("Getting " + txid) 258 | return ecl.blockchainTransaction_get(txid, false).then(tx=>{ 259 | if(!tx.code){ 260 | tx = bsv.Transaction(tx) 261 | //console.log(tx.id) 262 | Cache.setCache(tx.id,tx.toString()) 263 | } 264 | return tx 265 | }) 266 | }) 267 | } 268 | return fetchedTX 269 | } 270 | 271 | function getScriptHash(address){ 272 | var script = bsv.Script.fromAddress(address) 273 | var scriptHash = bsv.crypto.Hash.sha256(script.toBuffer()).reverse() 274 | return scriptHash.toString('hex') 275 | } 276 | 277 | function isAddress(address){ 278 | return bsv.Address.isValid(address) 279 | } 280 | 281 | var replaceMIME = ['text'] 282 | function replaceURL(data, mime){ 283 | if(replaceMIME.find(type=>mime.indexOf(type)!=-1))return data.toString() 284 | .replace(new RegExp("b://",'g'),"/") 285 | .replace(new RegExp("bit://19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut",'g'),"") 286 | .replace(new RegExp("bit://15DHFxWZJT58f9nhyGnsRBqrgwK4W6h4Up",'g'),"") 287 | else return data 288 | } 289 | 290 | function correctMIME(org_mime, filename){ 291 | var res = org_mime 292 | if(res=='binary')res='application/binary' 293 | if(filename.split('.').length > 1)res = mime.lookup(filename) 294 | return res 295 | } 296 | 297 | if(program.args.length==0)start() 298 | --------------------------------------------------------------------------------