Skip to content

Commit

Permalink
Using bitdb.bitcoin.com endpoint for mainnet and testnet.* Bitdb clas…
Browse files Browse the repository at this point in the history
…s now requires instantiation to set network.* Bitdb methods can be accessed as a property of Bfp object* Unit tests updated to include bitdb response tests, including bitdb testnet* Fixed mistake in README file
  • Loading branch information
jcramer committed Jan 8, 2019
1 parent 1637e1c commit d1fcb33
Show file tree
Hide file tree
Showing 10 changed files with 129 additions and 89 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2018 Simple Ledger Protocol
Copyright (c) 2018 Simple Ledger, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ Other tools using the Bitcoin Files Protocol include:

# Example File Download
```javascript
const bfp = require('bitcoinfiles').bfp;
const Bfp = require('bitcoinfiles').bfp;
const bfp = new Bfp();

// 1 - download file using URI
let result;
Expand Down Expand Up @@ -70,7 +71,7 @@ let config = {
chunkData: null // chunk not needed for cost estimate stage
};
let uploadCost = Bfp.calculateFileUploadCost(fileSize, config);
console.log(uploadCost);
console.log('upload cost: ', uploadCost);

// 3 - create a funding transaction
let fundingAddress = 'bitcoincash:qqgvrkm0xpmwqgyhfm65qxv70tjtwma6lgk07ffv9u'
Expand All @@ -80,7 +81,7 @@ let fundingWif = 'KzcuA9xnDRrb9cPh29N7EQbBhQQLMWtcrDwKbEMoahmwBNACNRfa'
let fundingUtxo;

(async function(){
let txo = await network.getUtxoWithRetry(fundingAddress);
let txo = await network.getLastUtxoWithRetry(fundingAddress);

console.log('got funding Utxo.')
})();
Expand All @@ -91,7 +92,7 @@ let fundingUtxo;
let fileId;
(async function(){
fileId = await bfp.uploadFile(fundingUtxo, fundingAddress, fundingWif, someFileBuffer, fileName, fileExt);
console.log(fileId);
console.log('fileId: ', fileId);
})();

// wait for upload to complete resolve... Done.
Expand All @@ -107,7 +108,7 @@ const bfp = require('bitcoinfiles');
let metadata;
(async function(){
metadata = await bfp.bitdb.getFileMetadata("dc76c5bd116fd61713c5b454b393212e33a1b2a8c926dcc40261f955d59b8e90","qrg3fvfue463rc5genp2kyrj4mg6g2lpxst0y4wamw");
console.log(metadata);
console.log('metadata: ', metadata);
})

// metadata :
Expand Down
67 changes: 37 additions & 30 deletions dist/bitcoinfiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,18 @@ const BITBOXSDK = require('bitbox-sdk/lib/bitbox-sdk').default
let bfp = require('./lib/bfp');
let utils = require('./lib/utils');
let network = require('./lib/network');
let bitdb = require('./lib/bitdb');

module.exports = {
bfp: bfp,
utils: utils,
network: network,
bitdb: bitdb,
bitbox: BITBOX
}
},{"./lib/bfp":2,"./lib/bitdb":3,"./lib/network":4,"./lib/utils":5,"bitbox-sdk/lib/bitbox-sdk":96}],2:[function(require,module,exports){
},{"./lib/bfp":2,"./lib/network":4,"./lib/utils":5,"bitbox-sdk/lib/bitbox-sdk":96}],2:[function(require,module,exports){
(function (Buffer){
let utils = require('./utils');
let bitboxnetwork = require('./network');
let Network = require('./network');
let Bitdb = require('./bitdb');

const BITBOXSDK = require('bitbox-sdk/lib/bitbox-sdk').default
, BITBOX = new BITBOXSDK()
Expand All @@ -26,9 +25,10 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

class Bfp {

constructor(network = 'mainnet'){
constructor(network = 'mainnet') {
this.networkstring = network;
this.network = new bitboxnetwork(network);
this.network = new Network(network);
this.bitdb = new Bitdb(network);
}

static get lokadIdHex() { return "42465000" }
Expand Down Expand Up @@ -103,7 +103,7 @@ class Bfp {
if(uploadProgressCallback != null){
uploadProgressCallback(0);
}
console.log(transactions[0].toHex());
console.log('transaction: ', transactions[0].toHex());
var bfTxId = await this.network.sendTxWithRetry(transactions[0].toHex());

// progress
Expand Down Expand Up @@ -337,7 +337,7 @@ class Bfp {
uploadProgressCallback(0);
}
for (let nId = 0; nId < transactions.length; nId++) {
console.log(transactions[nId].toHex());
console.log('transaction: ', transactions[nId].toHex());
var bfTxId = await this.network.sendTxWithRetry(transactions[nId].toHex());
// progress
if(uploadProgressCallback != null){
Expand All @@ -361,8 +361,8 @@ class Bfp {
let chunks = [];
let size = 0;

let txid = bfpUri.replace('bitcoinfile:', '')
txid = txid.replace('bitcoinfiles:', '')
let txid = bfpUri.replace('bitcoinfile:', '');
txid = txid.replace('bitcoinfiles:', '');

let txn = await this.network.getTransactionDetailsWithRetry(txid);

Expand Down Expand Up @@ -410,7 +410,7 @@ class Bfp {
if(bfpMsg.sha256 != null){
let fileSha256 = BITBOX.Crypto.sha256(fileBuf);
let res = Buffer.compare(fileSha256, bfpMsg.sha256);
if(res == 0){
if(res === 0){
passesHashCheck = true;
}
}
Expand Down Expand Up @@ -502,7 +502,7 @@ class Bfp {
chunkData.forEach((item) => script.push(item));
}

// console.log(script);
//console.log('script: ', script);
let encodedScript = utils.encodeScript(script);

if (encodedScript.length > 223) {
Expand Down Expand Up @@ -850,18 +850,23 @@ class Bfp {

module.exports = Bfp;
}).call(this,require("buffer").Buffer)
},{"./network":4,"./utils":5,"bitbox-sdk/lib/bitbox-sdk":96,"buffer":174}],3:[function(require,module,exports){
},{"./bitdb":3,"./network":4,"./utils":5,"bitbox-sdk/lib/bitbox-sdk":96,"buffer":174}],3:[function(require,module,exports){
(function (Buffer){
const axios = require('axios');

const bitDbUrl = 'https://bitdb.network/q/';
module.exports = class BfpBitdb {

constructor(network) {
this.bitDbUrl = network === 'mainnet' ? 'https://bitdb.bitcoin.com/q/' : 'https://tbitdb.bitcoin.com/q/';
}

module.exports = class BitbdProxy {
async getFileMetadata(txid, apiKey=null) {

static async getFileMetadata(txid, apiKey) {
txid = txid.replace('bitcoinfile:', '');
txid = txid.replace('bitcoinfiles:', '');

if(!apiKey)
throw new Error('Missing BitDB key');
// if(!apiKey)
// throw new Error('Missing BitDB key');

let query = {
"v": 3,
Expand All @@ -883,10 +888,11 @@ module.exports = class BitbdProxy {
const data = Buffer.from(json_str).toString('base64');
const response = (await axios({
method: 'GET',
url: bitDbUrl + data,
headers: {
'key': apiKey,
},
url: this.bitDbUrl + data,
headers: null,
// {
// 'key': apiKey,
// },
json: true,
})).data;

Expand All @@ -906,7 +912,7 @@ module.exports = class BitbdProxy {
if(list.length === 0){
throw new Error('File not found');
}
console.log(list[0]);
console.log('bitdb response: ', list[0]);
return list[0];
}
}
Expand All @@ -928,11 +934,12 @@ class BfpNetwork {
this.isMonitoringPayment = false;
}

async getUtxoWithRetry(address, retries = 40) {
async getLastUtxoWithRetry(address, retries = 40) {
let result;
let count = 0;
while(result == undefined){
result = await this.getUtxo(address)
result = await this.getLastUtxo(address)
console.log(result);
count++;
if(count > retries)
throw new Error("BITBOX.Address.utxo endpoint experienced a problem");
Expand All @@ -955,13 +962,13 @@ class BfpNetwork {
return result;
}

async getUtxo(address, log=true) {
async getLastUtxo(address, log=true) {
// must be a cash or legacy addr
if(!this.BITBOX.Address.isCashAddress(address) && !this.BITBOX.Address.isLegacyAddress(address))
throw new Error("Not an a valid address format, must be cashAddr or Legacy address format.");
let res = await this.BITBOX.Address.utxo(address);
if(log)
console.log('getUtxo for ', address, ': ', res);
console.log('getLastUtxo for ', address, ': ', res);
return res[0];
}

Expand All @@ -970,7 +977,7 @@ class BfpNetwork {
if(res === "64: too-long-mempool-chain")
throw new Error("Mempool chain too long");
if(log)
console.log(res);
console.log('sendTx() res: ', res);
return res;
}

Expand Down Expand Up @@ -1003,12 +1010,12 @@ class BfpNetwork {

while (true) {
try {
var utxo = await this.getUtxo(paymentAddress);
var utxo = await this.getLastUtxo(paymentAddress);
if (utxo && utxo.satoshis >= fee && utxo.confirmations === 0) {
break;
}
} catch (ex) {
console.log(ex);
console.log('monitorForPayment() error: ', ex);
}

if(this.stopPayMonitor) {
Expand Down
2 changes: 1 addition & 1 deletion dist/bitcoinfiles.min.js

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@ const BITBOXSDK = require('bitbox-sdk/lib/bitbox-sdk').default
let bfp = require('./lib/bfp');
let utils = require('./lib/utils');
let network = require('./lib/network');
let bitdb = require('./lib/bitdb');

module.exports = {
bfp: bfp,
utils: utils,
network: network,
bitdb: bitdb,
bitbox: BITBOX
}
20 changes: 11 additions & 9 deletions lib/bfp.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
let utils = require('./utils');
let bitboxnetwork = require('./network');
let Network = require('./network');
let Bitdb = require('./bitdb');

const BITBOXSDK = require('bitbox-sdk/lib/bitbox-sdk').default
, BITBOX = new BITBOXSDK()
Expand All @@ -8,9 +9,10 @@ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

class Bfp {

constructor(network = 'mainnet'){
constructor(network = 'mainnet') {
this.networkstring = network;
this.network = new bitboxnetwork(network);
this.network = new Network(network);
this.bitdb = new Bitdb(network);
}

static get lokadIdHex() { return "42465000" }
Expand Down Expand Up @@ -85,7 +87,7 @@ class Bfp {
if(uploadProgressCallback != null){
uploadProgressCallback(0);
}
console.log(transactions[0].toHex());
console.log('transaction: ', transactions[0].toHex());
var bfTxId = await this.network.sendTxWithRetry(transactions[0].toHex());

// progress
Expand Down Expand Up @@ -319,7 +321,7 @@ class Bfp {
uploadProgressCallback(0);
}
for (let nId = 0; nId < transactions.length; nId++) {
console.log(transactions[nId].toHex());
console.log('transaction: ', transactions[nId].toHex());
var bfTxId = await this.network.sendTxWithRetry(transactions[nId].toHex());
// progress
if(uploadProgressCallback != null){
Expand All @@ -343,8 +345,8 @@ class Bfp {
let chunks = [];
let size = 0;

let txid = bfpUri.replace('bitcoinfile:', '')
txid = txid.replace('bitcoinfiles:', '')
let txid = bfpUri.replace('bitcoinfile:', '');
txid = txid.replace('bitcoinfiles:', '');

let txn = await this.network.getTransactionDetailsWithRetry(txid);

Expand Down Expand Up @@ -392,7 +394,7 @@ class Bfp {
if(bfpMsg.sha256 != null){
let fileSha256 = BITBOX.Crypto.sha256(fileBuf);
let res = Buffer.compare(fileSha256, bfpMsg.sha256);
if(res == 0){
if(res === 0){
passesHashCheck = true;
}
}
Expand Down Expand Up @@ -484,7 +486,7 @@ class Bfp {
chunkData.forEach((item) => script.push(item));
}

// console.log(script);
//console.log('script: ', script);
let encodedScript = utils.encodeScript(script);

if (encodedScript.length > 223) {
Expand Down
26 changes: 16 additions & 10 deletions lib/bitdb.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
const axios = require('axios');

const bitDbUrl = 'https://bitdb.network/q/';
module.exports = class BfpBitdb {

module.exports = class BitbdProxy {
constructor(network) {
this.bitDbUrl = network === 'mainnet' ? 'https://bitdb.bitcoin.com/q/' : 'https://tbitdb.bitcoin.com/q/';
}

async getFileMetadata(txid, apiKey=null) {

static async getFileMetadata(txid, apiKey) {
txid = txid.replace('bitcoinfile:', '');
txid = txid.replace('bitcoinfiles:', '');

if(!apiKey)
throw new Error('Missing BitDB key');
// if(!apiKey)
// throw new Error('Missing BitDB key');

let query = {
"v": 3,
Expand All @@ -29,10 +34,11 @@ module.exports = class BitbdProxy {
const data = Buffer.from(json_str).toString('base64');
const response = (await axios({
method: 'GET',
url: bitDbUrl + data,
headers: {
'key': apiKey,
},
url: this.bitDbUrl + data,
headers: null,
// {
// 'key': apiKey,
// },
json: true,
})).data;

Expand All @@ -52,7 +58,7 @@ module.exports = class BitbdProxy {
if(list.length === 0){
throw new Error('File not found');
}
console.log(list[0]);
console.log('bitdb response: ', list[0]);
return list[0];
}
}
Loading

0 comments on commit d1fcb33

Please sign in to comment.