Compare commits

...

23 Commits

Author SHA1 Message Date
Justin Langston
389e752096 Merge pull request #806 from SonicWizard/next
added proxy to pull data from proper url
2017-08-29 16:12:32 -04:00
Justin Langston
9e2a875027 Merge pull request #805 from tenthirtyone/next-merge
Next-merge API updates
2017-08-29 16:12:00 -04:00
tenthirtyone
2146ff290b index block on tx model 2017-08-28 12:49:46 -04:00
tenthirtyone
ee0d5595b3 move models into lib 2017-08-28 00:38:48 -04:00
tenthirtyone
1a18a369c1 Save logic moved to models. Parsers removed 2017-08-27 23:44:08 -04:00
tenthirtyone
b836390b22 remove sockets 2017-08-27 22:53:39 -04:00
tenthirtyone
56078e2487 move cors to middleware 2017-08-27 22:38:40 -04:00
tenthirtyone
5f7e2b7613 removed old audit code 2017-08-27 22:30:41 -04:00
tenthirtyone
4ba24bba25 input sanitization moved to middleware 2017-08-27 21:58:04 -04:00
tenthirtyone
e7fd05afe9 Merge remote-tracking branch 'upstream/next' into next-merge 2017-08-27 21:55:41 -04:00
Darren Nelsen
45a8c809a3 added proxy to pull data from proper url 2017-08-24 16:48:22 -04:00
Jason Dreyzehner
fbfd9ecb34 Merge pull request #804 from SonicWizard/next
Completed Latest Transactions
2017-08-23 13:43:56 -04:00
Darren Nelsen
ccf681dda7 added input parm for refresh timer seconds on latest-transactions component 2017-08-23 11:42:38 -04:00
Darren Nelsen
2ac2822257 removed console logs; added a seconds var for latest transactions refresh 2017-08-23 10:41:10 -04:00
Darren Nelsen
07cd0cbd8f added refresh timer to latest transactions; styled latest transactions grid 2017-08-22 17:17:13 -04:00
Justin Langston
421d0ef8f4 Merge pull request #801 from tenthirtyone/next-merge
Next merge
2017-08-22 15:50:21 -04:00
Darren Nelsen
9848b17fc1 added call to new txs endpoint; changed html to reflect txid and valueOut in transactions grid 2017-08-22 14:34:24 -04:00
Darren Nelsen
b9de71862d Merge branch 'next-merge' of https://github.com/tenthirtyone/insight into next 2017-08-22 14:11:10 -04:00
Darren Nelsen
b21e11b8fb Merge branch 'next-merge' of https://github.com/tenthirtyone/insight into next 2017-08-22 13:44:36 -04:00
Darren Nelsen
8a1d8e6df2 pull in transactions from new endpoint 2017-08-22 13:30:01 -04:00
Darren Nelsen
201a3871a0 Merge branch 'next-merge' of https://github.com/tenthirtyone/insight into next 2017-08-22 10:15:24 -04:00
Darren Nelsen
c6b0e66a42 Merge branch 'next' of https://github.com/bitpay/insight into next 2017-08-22 10:08:50 -04:00
Darren Nelsen
743c060463 added ion-grid to latest-transactions component 2017-08-21 18:00:39 -04:00
31 changed files with 377 additions and 430 deletions

View File

@ -4,5 +4,9 @@
"type": "ionic-angular",
"integrations": {
"cordova": {}
}
},
"proxies": [{
"path": "/api",
"proxyUrl": "http://localhost:3000/api"
}]
}

View File

@ -38,12 +38,10 @@
"devDependencies": {
"@angular/cli": "1.1.2",
"@ionic/app-scripts": "1.3.7",
"@ionic/cli-plugin-cordova": "1.6.2",
"@ionic/cli-plugin-ionic-angular": "1.4.1",
"@types/jasmine": "2.5.41",
"@types/node": "7.0.4",
"codecov": "2.2.0",
"ionic": "3.9.1",
"ionic": "3.9.2",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "3.2.0",
"karma": "1.4.1",

View File

@ -1,4 +1,27 @@
<!-- Generated template for the LatestTransactionsComponent component -->
<div>
{{text}}
<div *ngIf="loading">
<ion-spinner name="crescent"></ion-spinner>
</div>
<div *ngIf="!loading">
<ion-grid>
<ion-row>
<ion-col><b>Hash</b></ion-col>
<ion-col text-right><b>Value Out</b></ion-col>
</ion-row>
<ion-row *ngFor="let tx of transactions">
<ion-col col-9>
<div class="ellipsis">
<a (click)="goToTx(tx.txid)">{{ tx.txid }}</a>
</div>
</ion-col>
<ion-col col-3 text-right>
{{ currency.getConversion(tx.valueOut) }}
</ion-col>
</ion-row>
</ion-grid>
</div>
</div>

View File

@ -1,3 +1,23 @@
latest-transactions {
ion-grid {
// border: 2px solid green;
margin: 10px 0 20px;
ion-row {
border-top: 1px solid #ccc;
}
ion-row:nth-child(even) {
background-color: #f4f4f4;
}
ion-row:first-child {
background-color: white;
border-top: none;
}
ion-row:last-child {
background-color: white;
}
}
}

View File

@ -1,6 +1,8 @@
import { Component } from '@angular/core';
// import { Http } from '@angular/http';
// import { ApiProvider } from '../../providers/api/api';
import { Component, NgZone, Input } from '@angular/core';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { ApiProvider } from '../../providers/api/api';
import { CurrencyProvider } from '../../providers/currency/currency';
/**
* Generated class for the LatestTransactionsComponent component.
@ -14,14 +16,34 @@ import { Component } from '@angular/core';
})
export class LatestTransactionsComponent {
private text: string;
private loading: boolean = true;
private transactions: Array<any> = [];
@Input() public refreshSeconds: number = 10;
private timer: number;
constructor(/*private http: Http, private api: ApiProvider*/) {
console.log('Hello LatestTransactionsComponent Component');
this.text = 'Hello Latest Transactions';
constructor(private http: Http, private navCtrl: NavController, private api: ApiProvider, public currency: CurrencyProvider, private ngZone: NgZone) {
this.loadTransactions();
}
/*
let url: string = this.api.apiPrefix + 'txs?' + this.queryType + '=' + this.queryValue;
public ngOnChanges(): void {
if (this.timer) {
clearInterval(this.timer);
}
this.ngZone.runOutsideAngular(() => {
this.timer = setInterval(
function (): void {
this.ngZone.run(function (): void {
this.loadTransactions.call(this);
}.bind(this));
}.bind(this),
1000 * this.refreshSeconds
);
});
}
private loadTransactions(): void {
let url: string = this.api.apiPrefix + 'txs';
this.http.get(url).subscribe(
(data) => {
@ -33,20 +55,11 @@ export class LatestTransactionsComponent {
this.loading = false;
}
);
*/
/*
this.http.get(this.api.apiPrefix + 'tx/' + this.txId).subscribe(
(data) => {
this.tx = JSON.parse(data['_body']);
this.loading = false;
},
(err) => {
console.log('err is', err);
this.loading = false;
}
);
*/
}
public goToTx(txId: string): void {
this.navCtrl.push('transaction', {
'txId': txId
});
}
}

View File

@ -18,7 +18,7 @@
<div>
<h1>Latest Transactions</h1>
<latest-transactions></latest-transactions>
<latest-transactions [refreshSeconds]="8"></latest-transactions>
</div>
<div class="about">

View File

@ -20,8 +20,4 @@ export class HomePage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
public ionViewDidLoad(): void {
console.log('ionViewDidLoad HomePage');
}
}

View File

@ -13,7 +13,6 @@ import { ApiProvider } from '../../providers/api/api';
export class BlocksProvider {
constructor(public http: Http, private api: ApiProvider) {
console.log('Hello BlocksProvider Provider');
}
public getBlocks(): any {

View File

@ -159,50 +159,9 @@
ws "1.1.1"
xml2js "^0.4.17"
"@ionic/cli-plugin-cordova@1.6.2":
version "1.6.2"
resolved "https://registry.yarnpkg.com/@ionic/cli-plugin-cordova/-/cli-plugin-cordova-1.6.2.tgz#f71d10641df8b522f54f8274e0d5bc4dbb8b5208"
dependencies:
"@ionic/cli-utils" "1.7.0"
chalk "^2.0.0"
elementtree "^0.1.7"
tslib "^1.7.1"
"@ionic/cli-plugin-ionic-angular@1.4.1":
version "1.4.1"
resolved "https://registry.yarnpkg.com/@ionic/cli-plugin-ionic-angular/-/cli-plugin-ionic-angular-1.4.1.tgz#bb94b7ad61c2f79757b2dff041c0b7e2151777ec"
dependencies:
"@ionic/cli-utils" "1.7.0"
chalk "^2.0.0"
tslib "^1.7.1"
"@ionic/cli-utils@1.7.0":
version "1.7.0"
resolved "https://registry.yarnpkg.com/@ionic/cli-utils/-/cli-utils-1.7.0.tgz#05bdbf3e7533eeeee27d58f3adbfe26bf2bf0d1d"
dependencies:
archiver "^2.0.0"
chalk "^2.0.0"
ci-info "^1.0.0"
cross-spawn "^5.1.0"
dargs "^5.1.0"
dev-null "^0.1.1"
inquirer "^3.2.1"
leek "0.0.24"
lodash "^4.17.4"
minimist "^1.2.0"
ncp "^2.0.0"
semver "^5.4.1"
slice-ansi "^1.0.0"
string-width "^2.1.1"
strip-ansi "^4.0.0"
superagent "^3.5.2"
tslib "^1.7.1"
uuid "^3.0.1"
wrap-ansi "^3.0.1"
"@ionic/cli-utils@1.9.1":
version "1.9.1"
resolved "https://registry.yarnpkg.com/@ionic/cli-utils/-/cli-utils-1.9.1.tgz#a0118819cb8de1f3bc4bc5b401e5b61d7f41d5b5"
"@ionic/cli-utils@1.9.2":
version "1.9.2"
resolved "https://registry.yarnpkg.com/@ionic/cli-utils/-/cli-utils-1.9.2.tgz#9916d8bb6ec696b948b6be1c05fbec46c87ddc0b"
dependencies:
"@types/gulp" "^3.8.33"
archiver "^2.0.0"
@ -1973,10 +1932,6 @@ detect-node@^2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.0.3.tgz#a2033c09cc8e158d37748fbde7507832bd6ce127"
dev-null@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/dev-null/-/dev-null-0.1.1.tgz#5a205ce3c2b2ef77b6238d6ba179eb74c6a0e818"
di@^0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/di/-/di-0.0.1.tgz#806649326ceaa7caa3306d75d985ea2748ba913c"
@ -3223,11 +3178,11 @@ ionic-angular@3.4.2:
version "3.4.2"
resolved "https://registry.yarnpkg.com/ionic-angular/-/ionic-angular-3.4.2.tgz#762631f1af78a5ae1c0aa0f4d23b31435142abe1"
ionic@3.9.1:
version "3.9.1"
resolved "https://registry.yarnpkg.com/ionic/-/ionic-3.9.1.tgz#be50eea2f55bad40574772ecaeaf5a460fd16330"
ionic@3.9.2:
version "3.9.2"
resolved "https://registry.yarnpkg.com/ionic/-/ionic-3.9.2.tgz#d958069ce29d9dbb8b9c1638b59995ce005ce845"
dependencies:
"@ionic/cli-utils" "1.9.1"
"@ionic/cli-utils" "1.9.2"
chalk "^2.0.0"
opn "^5.1.0"
os-name "^2.0.1"

View File

@ -9,10 +9,8 @@ logger.log('debug',
db.connect(config.mongodb.uri, config.mongodb.options);
db.connection.once('open', () => {
// DB Audit returns best height to node
db.blocks.findMissingBlocks((err, bestBlockHeight) => {
db.blocks.getBestBlockHeight((err, bestBlockHeight) => {
// Pass height to node to start Sync
logger.log('debug',
`Starting Bcoin from best height: ${bestBlockHeight}`);

View File

@ -1,21 +1,14 @@
const logger = require('../logger');
const util = require('../util');
const db = require('../db');
module.exports = function AddressAPI(router) {
router.get('/addr/:addr', (req, res) => {
const addr = req.params.addr || '';
if (!util.isBitcoinAddress(addr)) {
return res.status(404).send({
error: 'Invalid bitcoin address',
});
}
return db.txs.getTxByAddress(addr, 0, 999999999, (error, txs) => {
if (error) {
return db.txs.getTxByAddress(addr, 0, 999999999, (err, txs) => {
if (err || txs.length === 0) {
logger.log('error',
`getTxByBlock ${error}`);
`getTxByBlock ${err}`);
return res.status(404).send();
}

View File

@ -1,17 +1,10 @@
const logger = require('../logger');
const db = require('../db');
const util = require('../util');
module.exports = function BlockAPI(router) {
router.get('/block/:blockHash', (req, res) => {
const blockHash = req.params.blockHash;
if (!util.isBlockHash(blockHash)) {
return res.status(404).send({
error: 'Invalid bitcoin address',
});
}
// Pass Mongo params, fields and limit to db api.
return db.blocks.getByHash(blockHash,
(err, block) => {
@ -70,12 +63,6 @@ module.exports = function BlockAPI(router) {
router.get('/rawblock/:blockHash', (req, res) => {
const blockHash = req.params.blockHash || '';
if (!util.isBlockHash(blockHash)) {
return res.status(400).send({
error: 'Invalid bitcoin address',
});
}
// Pass Mongo params, fields and limit to db api.
return db.blocks.getRawBlock(blockHash,
(err, block) => {

View File

@ -2,20 +2,19 @@ const express = require('express');
const config = require('../../config');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const sanitizer = require('./middleware/sanitizer');
const app = express();
const api = express.Router();
const cors = require('./cors');
const cors = require('./middleware/cors');
app.use(cors);
app.use(helmet());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(sanitizer);
// Serve insight ui front end from root dir public folder
app.use(express.static('../app/www', { maxage: '1w' }));
// Legacy UI - useful for 1:1 compares
// app.use(express.static('./public', { maxage: '1w' }));
app.set('json spaces', config.api.json_spaces);
@ -36,7 +35,6 @@ app.use((req, res) => res.status(404).send({
error: 'Not found',
}));
// Socket server
const server = require('http').Server(app);
module.exports = {

View File

@ -1,17 +1,10 @@
const Message = require('bitcore-message');
const util = require('../util');
// Copied from previous source
function verifyMessage(req, res) {
const address = req.body.address || req.query.address;
const signature = req.body.signature || req.query.signature;
const message = req.body.message || req.query.message;
if (!util.isBitcoinAddress(address)) {
return res.status(400).send({
error: 'Invalid bitcoin address',
});
}
if (!address || !signature || !message) {
return res.json({
message: 'Missing parameters (expected "address", "signature" and "message")',

View File

@ -0,0 +1,140 @@
const util = require('../../util');
// Strip the request, sanitize inputs, rebuild
module.exports = function sanitize(req, res, next) {
const params = req.params || null;
const body = req.body || null;
const query = req.query || null;
let cleanParams = null;
let cleanBody = null;
let cleanQuery = null;
// req.params
if (params) {
// Transaction Id
if (params.txid && !util.isTxid(params.txid)) {
return res.status(404).send({
error: 'Invalid Transaction Id',
});
}
// Address
if (params.addr && typeof (params.addr) !== 'string') {
return res.status(404).send({
error: 'Invalid Bitcoin Address',
});
}
// Block Hash
if (params.blockHash && typeof (params.blockHash) !== 'string') {
return res.status(404).send({
error: 'Invalid Block Hash',
});
}
// Height
if (params.height) {
if (typeof (params.height) !== 'number') {
return res.status(404).send({
error: 'Invalid Block Hash',
});
}
params.height = parseInt(params.height, 10);
}
cleanParams = {
txid: params.txid || null,
addr: params.addr || null,
blockHash: params.blockHash || null,
height: params.height || null,
};
}
// req.body
if (body) {
// Signature
if (body.signature && typeof (body.signature) !== 'string') {
return res.status(404).send({
error: 'Invalid Signature',
});
}
// Message
if (body.message && typeof (body.message) !== 'string') {
return res.status(404).send({
error: 'Invalid Message',
});
}
// Address
if (body.address && !util.isBitcoinAddress(body.address)) {
return res.status(404).send({
error: 'Invalid Bitcoin Address',
});
}
cleanBody = {
signature: body.signature || null,
message: body.message || null,
address: body.address || null,
};
}
if (query) {
// Address
if (query.address && !util.isBitcoinAddress(query.address)) {
return res.status(404).send({
error: 'Invalid Bitcoin Address',
});
}
// Signature
if (query.signature && typeof (query.signature) !== 'string') {
return res.status(404).send({
error: 'Invalid Signature',
});
}
// Message
if (query.message && typeof (query.message) !== 'string') {
return res.status(404).send({
error: 'Invalid Message',
});
}
// q
if (query.q && typeof (query.q) !== 'string') {
return res.status(404).send({
error: 'Invalid Q',
});
}
// Page Number
if (query.pageNum && typeof (query.pageNum) !== 'number') {
return res.status(404).send({
error: 'Invalid Page Number',
});
}
// Block (hash - implicit)
if (query.block && typeof (query.block) !== 'string') {
return res.status(404).send({
error: 'Invalid Block',
});
}
// Raw Tx
if (query.rawtx && typeof (query.rawtx) !== 'string') {
return res.status(404).send({
error: 'Invalid Bitcoin Address',
});
}
cleanQuery = {
address: query.address || null,
signature: query.signature || null,
message: query.message || null,
q: query.q || null,
pageNum: query.pageNum || null,
block: query.block || null,
rawtx: query.rawtx || null,
};
}
// Strip off unexpected params
req.params = cleanParams;
req.body = cleanBody;
req.query = cleanQuery;
return next();
};

View File

@ -1,68 +0,0 @@
const server = require('.');
const io = require('socket.io')(server);
let refreshBlocks = false;
const txInterval = 200;
let txCounter = 0;
// Not quite debouncing
setInterval(() => {
refreshBlocks = true;
}, 10000);
io.on('connection', (socket) => {
socket.on('subscribe', (data) => {
});
socket.on('message', (data) => {
});
socket.on('unsubscribe', (data) => {
});
socket.on('disconnect', (data) => {
});
});
// Emit block refresh and txs
function processBlock(entry, block) {
if (refreshBlocks) {
refreshBlocks = false;
emitBlock(entry);
}
block.txs.forEach((tx) => {
txCounter++;
if (txCounter % txInterval === 0) {
txCounter = 0;
emitTx(tx);
}
});
}
function emitBlock(block) {
io.sockets.emit('block', {
hash: block.toJSON().hash,
});
}
function emitTx(transaction) {
const txJSON = transaction.toJSON();
io.sockets.emit('tx', {
txid: txJSON.hash,
valueOut: transaction.outputs.reduce((sum, output) => {
output = output.toJSON();
const valB = (output.value || output.valueOut.value || 0) / 1e8;
return sum + valB;
}, 0),
});
}
module.exports = {
io,
processBlock,
emitBlock,
emitTx,
};

View File

@ -2,34 +2,24 @@ const logger = require('../logger');
const request = require('request');
const config = require('../../config');
const db = require('../db');
const util = require('../util');
const API_URL = `http://${config.bcoin_http}:${config.bcoin['http-port']}`;
const MAX_TXS = config.api.max_txs;
const TTL = config.api.request_ttl;
module.exports = function transactionAPI(router) {
// Txs by txid
router.get('/tx/:txid', (req, res) => {
if (!util.isTxid(req.params.txid)) {
return res.status(404).send({
error: 'Invalid transaction id',
});
}
// Get max block height for calculating confirmations
const height = db.blocks.bestHeight();
// Bcoin transaction data
const txid = req.params.txid || '';
db.txs.getTxById(txid, (err, transaction) => {
if (err || !transaction) {
return db.txs.getTxById(txid, (err, tx) => {
if (err || !tx) {
logger.log('error',
`/tx/:tid getTxById: ${err.err}`);
`/tx/:tid getTxById: ${err ? err.err : ''}`);
return res.status(404).send();
}
const tx = transaction;
return res.send({
txid: tx.hash,
version: tx.version,
@ -61,17 +51,9 @@ module.exports = function transactionAPI(router) {
// query by address
router.get('/txs', (req, res) => {
const pageNum = parseInt(req.query.pageNum, 10) || 0;
const rangeStart = pageNum * MAX_TXS;
const rangeEnd = rangeStart + MAX_TXS;
const height = db.blocks.bestHeight();
// get txs for blockhash, start with best height to calc confirmations
if (req.query.block) {
if (!util.isBlockHash(req.query.block)) {
return res.status(400).send({
error: 'Invalid block hash',
});
}
return db.txs.getTxCountByBlock(req.query.block, (err, count) => {
if (err) {
logger.log('error',
@ -115,16 +97,10 @@ module.exports = function transactionAPI(router) {
});
});
} else if (req.query.address) {
if (!util.isBitcoinAddress(req.query.address)) {
return res.status(400).send({
error: 'Invalid bitcoin address',
});
}
// Get txs by address, start with best height to calc confirmations
const addr = req.query.address || '';
db.txs.getTxCountByAddress(req.query.address, (err, count) => {
return db.txs.getTxCountByAddress(addr, (err, count) => {
if (err) {
logger.log('error',
`getTxByBlock ${err}`);
@ -132,7 +108,7 @@ module.exports = function transactionAPI(router) {
}
const totalPages = Math.ceil(count / MAX_TXS);
return db.txs.getTxByAddress(req.query.address, pageNum, MAX_TXS, (error, txs) => {
return db.txs.getTxByAddress(addr, pageNum, MAX_TXS, (error, txs) => {
if (error) {
logger.log('error',
`getTxByBlock ${error}`);
@ -165,39 +141,38 @@ module.exports = function transactionAPI(router) {
});
});
});
} else {
// Get last n txs
db.txs.getTopTransactions((err, txs) => {
if (err) {
logger.log('err',
`/txs getTopTransactions ${err}`);
return res.status(404).send(err);
}
return res.send(txs.map(tx => ({
txid: tx.hash,
fees: tx.fee / 1e8,
size: tx.size,
confirmations: (height - tx.height) + 1,
valueOut: tx.outputs.reduce((sum, output) => sum + output.value, 0) / 1e8,
vin: tx.inputs.map(input => ({
scriptSig: {
asm: input.script,
},
addr: input.address,
value: input.value / 1e8,
})),
vout: tx.outputs.map(output => ({
scriptPubKey: {
asm: output.script,
addresses: [output.address],
},
value: output.value / 1e8,
})),
isCoinBase: tx.inputs[0].prevout.hash === '0000000000000000000000000000000000000000000000000000000000000000',
})),
);
});
}
// Get last n txs
return db.txs.getTopTransactions((err, txs) => {
if (err) {
logger.log('err',
`/txs getTopTransactions ${err}`);
return res.status(404).send(err);
}
return res.send(txs.map(tx => ({
txid: tx.hash,
fees: tx.fee / 1e8,
size: tx.size,
confirmations: (height - tx.height) + 1,
valueOut: tx.outputs.reduce((sum, output) => sum + output.value, 0) / 1e8,
vin: tx.inputs.map(input => ({
scriptSig: {
asm: input.script,
},
addr: input.address,
value: input.value / 1e8,
})),
vout: tx.outputs.map(output => ({
scriptPubKey: {
asm: output.script,
addresses: [output.address],
},
value: output.value / 1e8,
})),
isCoinBase: tx.inputs[0].prevout.hash === '0000000000000000000000000000000000000000000000000000000000000000',
})),
);
});
});
router.get('/rawtx/:txid', (req, res) => res.send(req.params.txid));

View File

@ -1,4 +1,4 @@
const Block = require('../../models/block.js');
const Block = require('../models/block.js');
const logger = require('../logger');
const config = require('../../config');
@ -39,8 +39,12 @@ function getLastBlock(cb) {
.limit(1);
}
// Returns the missing block if it exists. Otherwise, return tip.
function findMissingBlocks(cb) {
function saveBcoinBlock(entry, block, cb) {
return Block.saveBcoinBlock(entry, block, cb);
}
// Returns highest consecutive block height
function getBestBlockHeight(cb) {
logger.log('debug',
'Verifying Mongo Blockchain');
return Block.getHeights((err, blocks) => {
@ -59,11 +63,12 @@ function findMissingBlocks(cb) {
}
module.exports = {
findMissingBlocks,
getBestBlockHeight,
getRawBlock,
getTopBlocks,
getLastBlock,
getByHash,
byHeight,
bestHeight,
saveBcoinBlock,
};

View File

@ -1,14 +1,9 @@
const Transactions = require('../../models/transaction.js');
const Transactions = require('../models/transaction.js');
const config = require('../../config');
const logger = require('../logger');
const MAX_PAGE_TXS = config.api.max_page_txs;
function getEmptyInputs(cb) {
return Transactions.getEmptyInputs(cb);
}
function getTopTransactions(cb) {
return Transactions.last(cb);
}
@ -36,45 +31,17 @@ function getTxCountByAddress(address, cb) {
return Transactions.countByAddress(address, cb);
}
function updateInput(txid, inputid, value, address) {
return Transactions.updateInput(txid, inputid, value, address);
function saveBcoinTransactions(entry, txs, cb) {
return Transactions.saveBcoinTransactions(entry, txs, cb);
}
// Updates empty inputs with prevout addr & value
function auditInputs() {
getEmptyInputs(
(err, txs) => {
if (err) {
return logger.log('warn',
`No Empty Inputs found: ${err.err}`);
}
// For each tx with unmarked inputs
return txs.forEach((inputTx) => {
inputTx.inputs.forEach((input) => {
const txHash = input.prevout.hash;
const outIdx = input.prevout.index;
return getTxById(txHash, (error, tx) => {
if (error || !tx) {
// Mongo save is async. Bcoin is kinda sync... Does not mean the tx will not be found
return logger.log('warn',
`No Tx found: ${txHash} ${error}`);
}
return updateInput(inputTx._id, input._id, tx.outputs[outIdx].value, tx.outputs[outIdx].address);
});
});
});
});
}
module.exports = {
auditInputs,
getEmptyInputs,
getTopTransactions,
getTxById,
getTxByBlock,
getTxCountByBlock,
getTxByAddress,
getTxCountByAddress,
updateInput,
saveBcoinTransactions,
};

View File

@ -1,5 +1,6 @@
const mongoose = require('mongoose');
const config = require('../config');
const config = require('../../config');
const util = require('../util');
const Schema = mongoose.Schema;
// These limits can be overriden higher up the stack
@ -66,4 +67,32 @@ BlockSchema.statics.getHeights = function findMissing(cb) {
.sort({ height: 1 });
};
BlockSchema.statics.saveBcoinBlock = function saveBcoinBlock(entry, block, cb) {
const Block = this.model('Block');
const rawBlock = block.toRaw().toString('hex');
const blockJSON = block.toJSON();
const reward = util.calcBlockReward(entry.height);
return new Block({
hash: blockJSON.hash,
height: entry.height,
size: block.getSize(),
version: blockJSON.version,
prevBlock: blockJSON.prevBlock,
merkleRoot: blockJSON.merkleRoot,
ts: blockJSON.ts,
bits: blockJSON.bits,
nonce: blockJSON.nonce,
txs: block.txs.map((tx) => {
const txJSON = tx.toJSON();
return txJSON.hash;
}),
chainwork: entry.chainwork,
reward,
network: config.bcoin.network,
poolInfo: {},
rawBlock,
}).save(cb);
};
module.exports = mongoose.model('Block', BlockSchema);

View File

@ -1,13 +1,13 @@
const mongoose = require('mongoose');
const Input = require('./input');
const Output = require('./output');
const logger = require('../lib/logger');
const config = require('../config');
const logger = require('../logger');
const config = require('../../config');
const util = require('../util');
const Schema = mongoose.Schema;
// These limits can be overriden higher up the stack
const MAX_TXS = config.api.max_txs;
const MAX_PAGE_TXS = config.api.max_page_txs;
const TransactionSchema = new Schema({
hash: { type: String, default: '' },
@ -28,6 +28,7 @@ const TransactionSchema = new Schema({
});
TransactionSchema.index({ hash: 1 });
TransactionSchema.index({ block: 1 });
TransactionSchema.index({ 'outputs.address': 1 });
TransactionSchema.index({ 'inputs.address': 1 });
@ -84,30 +85,44 @@ TransactionSchema.statics.last = function lastTx(cb) {
.sort({ height: -1 });
};
TransactionSchema.statics.getEmptyInputs = function getEmptyInputs(cb) {
return this.model('Transaction').find({
'inputs.prevout.hash': { $ne: '0000000000000000000000000000000000000000000000000000000000000000' },
'inputs.value': 0,
},
cb);
TransactionSchema.statics.saveBcoinTransactions = function saveBcoinTransactions(entry, txs, cb) {
txs.forEach((tx) => {
this.saveBcoinTransaction(entry, tx, cb);
});
};
TransactionSchema.statics.updateInput = function updateInput(txid, inputid, value, address) {
return this.model('Transaction').findOneAndUpdate(
{ _id: txid, 'inputs._id': inputid },
{
$set: {
'inputs.$.value': value,
'inputs.$.address': address,
},
},
(err, tx) => {
if (err) {
logger.log('error',
`updateInput: ${err}`);
}
},
);
TransactionSchema.statics.saveBcoinTransaction = function saveBcoinTransaction(entry, tx, cb) {
const Transaction = this.model('Transaction');
return new Transaction({
hash: tx.hash,
witnessHash: tx.witnessHash,
fee: tx.fee,
rate: tx.rate,
ps: tx.ps,
height: entry.height,
block: util.revHex(entry.hash),
ts: entry.ts,
date: entry.tx,
index: tx.index,
version: tx.version,
flag: tx.flag,
inputs: tx.inputs.map(input => new Input({
value: input.coin ? input.coin.value : 0,
prevout: input.prevout,
script: input.script,
witness: input.witness,
sequence: input.sequence,
address: input.coin ? input.coin.address : '',
})),
outputs: tx.outputs.map(output => new Output({
address: output.address,
script: output.script,
value: output.value,
})),
lockTime: tx.locktime,
chain: config.bcoin.network,
})
.save(cb);
};
module.exports = mongoose.model('Transaction', TransactionSchema);

View File

@ -1,9 +1,6 @@
const FullNode = require('bcoin/lib/node/fullnode');
const logger = require('../../lib/logger');
const BlockParser = require('../parser').Block;
const TxParser = require('../parser').Transaction;
const config = require('../../config');
const socket = require('../../lib/api/socket');
const db = require('../../lib/db');
const node = new FullNode(config.bcoin);
@ -20,12 +17,24 @@ function start(bestBlockHeight) {
node.chain.on('connect', (entry, block) => {
db.blocks.bestHeight(entry.height);
// Assemble Bcoin block data
node.chain.db.getBlockView(block)
.then((view) => {
const fullBlock = block.getJSON(node.network, view, entry.height);
BlockParser.parse(entry, block);
TxParser.parse(entry, fullBlock.txs);
// Save the block
db.blocks.saveBcoinBlock(entry, block, (err) => {
if (err) {
logger.log('error',
`Error saving block ${err}`);
}
});
// Save the Txs
db.txs.saveBcoinTransactions(entry, fullBlock.txs, (err) => {
if (err) {
logger.log('error',
`Error saving txs ${err}`);
}
});
});
});

View File

@ -1,42 +0,0 @@
const BlockModel = require('../../models/block');
const config = require('../../config');
const util = require('../../lib/util');
const logger = require('../logger');
function parse(entry, block) {
const rawBlock = block.toRaw().toString('hex');
const blockJSON = block.toJSON();
const reward = util.calcBlockReward(entry.height);
// Can probably use destructuring to build something nicer
const newBlock = new BlockModel({
hash: blockJSON.hash,
height: entry.height,
size: block.getSize(),
version: blockJSON.version,
prevBlock: blockJSON.prevBlock,
merkleRoot: blockJSON.merkleRoot,
ts: blockJSON.ts,
bits: blockJSON.bits,
nonce: blockJSON.nonce,
txs: block.txs.map((tx) => {
const txJSON = tx.toJSON();
return txJSON.hash;
}),
chainwork: entry.chainwork,
reward,
network: config.bcoin.network,
poolInfo: {},
rawBlock,
});
newBlock.save((err) => {
if (err) {
logger.log('error', err.message);
}
});
}
module.exports = {
parse,
};

View File

@ -1,7 +0,0 @@
const Block = require('./block');
const Transaction = require('./transaction');
module.exports = {
Block,
Transaction,
};

View File

@ -1,52 +0,0 @@
const TxModel = require('../../models/transaction');
const InputModel = require('../../models/input');
const OutputModel = require('../../models/output');
const config = require('../../config');
const util = require('../../lib/util');
const logger = require('../logger');
const db = require('../db');
function parse(entry, txs) {
txs.forEach((tx) => {
const t = new TxModel({
hash: tx.hash,
witnessHash: tx.witnessHash,
fee: tx.fee,
rate: tx.rate,
ps: tx.ps,
height: entry.height,
block: util.revHex(entry.hash),
ts: entry.ts,
date: entry.tx,
index: tx.index,
version: tx.version,
flag: tx.flag,
inputs: tx.inputs.map(input => new InputModel({
value: input.coin ? input.coin.value : 0,
prevout: input.prevout,
script: input.script,
witness: input.witness,
sequence: input.sequence,
address: input.coin ? input.coin.address : '',
})),
outputs: tx.outputs.map(output => new OutputModel({
address: output.address,
script: output.script,
value: output.value,
})),
lockTime: tx.locktime,
chain: config.bcoin.network,
});
t.save((err) => {
if (err) {
logger.log('error', err.message);
}
});
});
}
module.exports = {
parse,
};

View File

@ -20,7 +20,6 @@
"helmet": "^3.8.1",
"mongoose": "^4.11.5",
"request": "^2.81.0",
"socket.io": "^2.0.3",
"winston": "^2.3.1"
},
"devDependencies": {

View File

@ -1,5 +1,5 @@
const db = require('../lib/db');
const Block = require('../models/block.js');
const Block = require('../lib/models/block.js');
Block.findOne({}, (err, block) => {
console.log(err);