mirror of
https://github.com/benjamin-wilson/public-pool.git
synced 2026-09-29 17:15:03 -07:00
Merge remote-tracking branch 'origin/master' into postgresql
This commit is contained in:
@@ -32,6 +32,4 @@ export class ClientStatisticsEntity extends TrackedEntity {
|
||||
acceptedCount: number;
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -19,7 +19,6 @@ export class ClientStatisticsService {
|
||||
}
|
||||
|
||||
public async save(clientStatistic: Partial<ClientStatisticsEntity>) {
|
||||
|
||||
// Attempt to update the existing record
|
||||
const updateResult = await this.clientStatisticsRepository
|
||||
.createQueryBuilder()
|
||||
|
||||
@@ -51,6 +51,37 @@ export class AppController {
|
||||
|
||||
}
|
||||
|
||||
@Get('pool')
|
||||
public async pool() {
|
||||
|
||||
const CACHE_KEY = 'POOL_INFO';
|
||||
const cachedResult = await this.cacheManager.get(CACHE_KEY);
|
||||
|
||||
if (cachedResult != null) {
|
||||
return cachedResult;
|
||||
}
|
||||
|
||||
|
||||
const userAgents = await this.clientService.getUserAgents();
|
||||
const totalHashRate = userAgents.reduce((acc, userAgent) => acc + parseFloat(userAgent.totalHashRate), 0);
|
||||
const totalMiners = userAgents.reduce((acc, userAgent) => acc + parseInt(userAgent.count), 0);
|
||||
const blockHeight = (await firstValueFrom(this.bitcoinRpcService.newBlock$)).blocks;
|
||||
const blocksFound = await this.blocksService.getFoundBlocks();
|
||||
|
||||
const data = {
|
||||
totalHashRate,
|
||||
blockHeight,
|
||||
totalMiners,
|
||||
blocksFound,
|
||||
fee: 0
|
||||
}
|
||||
|
||||
//5 min
|
||||
await this.cacheManager.set(CACHE_KEY, data, 5 * 60 * 1000);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@Get('network')
|
||||
public async network() {
|
||||
const miningInfo = await firstValueFrom(this.bitcoinRpcService.newBlock$);
|
||||
|
||||
@@ -27,9 +27,9 @@ export class MiningJob {
|
||||
jobTemplate: IJobTemplate
|
||||
) {
|
||||
|
||||
this.jobTemplateId = jobTemplate.blockData.id,
|
||||
this.jobTemplateId = jobTemplate.blockData.id;
|
||||
|
||||
this.coinbaseTransaction = this.createCoinbaseTransaction(payoutInformation, jobTemplate.blockData.coinbasevalue);
|
||||
this.coinbaseTransaction = this.createCoinbaseTransaction(payoutInformation, jobTemplate.blockData.coinbasevalue);
|
||||
|
||||
//The commitment is recorded in a scriptPubKey of the coinbase transaction. It must be at least 38 bytes, with the first 6-byte of 0x6a24aa21a9ed, that is:
|
||||
// 1-byte - OP_RETURN (0x6a)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { validate, ValidatorOptions } from 'class-validator';
|
||||
import * as crypto from 'crypto';
|
||||
import { Socket } from 'net';
|
||||
import { firstValueFrom, Subscription } from 'rxjs';
|
||||
import { clearInterval } from 'timers';
|
||||
|
||||
import { AddressSettingsService } from '../ORM/address-settings/address-settings.service';
|
||||
import { BlocksService } from '../ORM/blocks/blocks.service';
|
||||
@@ -35,7 +36,7 @@ export class StratumV1Client {
|
||||
private clientAuthorization: AuthorizationMessage;
|
||||
private clientSuggestedDifficulty: SuggestDifficulty;
|
||||
private stratumSubscription: Subscription;
|
||||
private backgroundWork: NodeJS.Timer;
|
||||
private backgroundWork: NodeJS.Timer[] = [];
|
||||
|
||||
private statistics: StratumV1ClientStatistics;
|
||||
private stratumInitialized = false;
|
||||
@@ -87,9 +88,10 @@ export class StratumV1Client {
|
||||
if (this.stratumSubscription != null) {
|
||||
this.stratumSubscription.unsubscribe();
|
||||
}
|
||||
if (this.backgroundWork != null) {
|
||||
clearInterval(this.backgroundWork);
|
||||
}
|
||||
|
||||
this.backgroundWork.forEach(work => {
|
||||
clearInterval(work);
|
||||
});
|
||||
}
|
||||
|
||||
private getRandomHexString() {
|
||||
@@ -333,46 +335,53 @@ export class StratumV1Client {
|
||||
&& this.clientAuthorization != null
|
||||
&& this.stratumInitialized == false) {
|
||||
|
||||
this.stratumInitialized = true;
|
||||
|
||||
switch (this.clientSubscription.userAgent) {
|
||||
case 'cpuminer': {
|
||||
this.sessionDifficulty = 0.1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (this.clientSuggestedDifficulty == null) {
|
||||
//console.log(`Setting difficulty to ${this.sessionDifficulty}`)
|
||||
const setDifficulty = JSON.stringify(new SuggestDifficulty().response(this.sessionDifficulty));
|
||||
const success = await this.write(setDifficulty + '\n');
|
||||
if (!success) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.stratumSubscription = this.stratumV1JobsService.newMiningJob$.subscribe(async (jobTemplate) => {
|
||||
try {
|
||||
await this.sendNewMiningJob(jobTemplate);
|
||||
} catch (e) {
|
||||
await this.socket.end();
|
||||
console.error(e);
|
||||
}
|
||||
});
|
||||
|
||||
this.backgroundWork = setInterval(async () => {
|
||||
await this.checkDifficulty();
|
||||
await this.statistics.saveShares(this.entity);
|
||||
}, 60 * 1000);
|
||||
this.initStratum();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private async initStratum() {
|
||||
this.stratumInitialized = true;
|
||||
|
||||
switch (this.clientSubscription.userAgent) {
|
||||
case 'cpuminer': {
|
||||
this.sessionDifficulty = 0.1;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.clientSuggestedDifficulty == null) {
|
||||
//console.log(`Setting difficulty to ${this.sessionDifficulty}`)
|
||||
const setDifficulty = JSON.stringify(new SuggestDifficulty().response(this.sessionDifficulty));
|
||||
const success = await this.write(setDifficulty + '\n');
|
||||
if (!success) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.stratumSubscription = this.stratumV1JobsService.newMiningJob$.subscribe(async (jobTemplate) => {
|
||||
try {
|
||||
await this.sendNewMiningJob(jobTemplate);
|
||||
} catch (e) {
|
||||
await this.socket.end();
|
||||
console.error(e);
|
||||
}
|
||||
});
|
||||
|
||||
this.backgroundWork.push(
|
||||
setInterval(async () => {
|
||||
await this.checkDifficulty();
|
||||
}, 60 * 1000)
|
||||
);
|
||||
|
||||
this.backgroundWork.push(
|
||||
setInterval(async () => {
|
||||
await this.statistics.saveShares(this.entity);
|
||||
}, 60 * 1000)
|
||||
);
|
||||
}
|
||||
|
||||
private async sendNewMiningJob(jobTemplate: IJobTemplate) {
|
||||
|
||||
|
||||
|
||||
let payoutInformation;
|
||||
const devFeeAddress = this.configService.get('DEV_FEE_ADDRESS');
|
||||
//50Th/s
|
||||
@@ -480,7 +489,7 @@ export class StratumV1Client {
|
||||
parseInt(submission.ntime, 16)
|
||||
);
|
||||
const header = updatedJobBlock.toBuffer(true);
|
||||
const { submissionDifficulty, submissionHash } = this.calculateDifficulty(header);
|
||||
const { submissionDifficulty } = this.calculateDifficulty(header);
|
||||
|
||||
//console.log(`DIFF: ${submissionDifficulty} of ${this.sessionDifficulty} from ${this.clientAuthorization.worker + '.' + this.extraNonceAndSessionId}`);
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ export class AppService implements OnModuleInit {
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
|
||||
}
|
||||
|
||||
@Interval(1000 * 60 * 60)
|
||||
|
||||
@@ -3,12 +3,11 @@ import { ConfigService } from '@nestjs/config';
|
||||
import { RPCClient } from 'rpc-bitcoin';
|
||||
import { BehaviorSubject, filter, shareReplay } from 'rxjs';
|
||||
import { RpcBlockService } from 'src/ORM/rpc-block/rpc-block.service';
|
||||
import * as zmq from 'zeromq/v5-compat';
|
||||
|
||||
import { IBlockTemplate } from '../models/bitcoin-rpc/IBlockTemplate';
|
||||
import { IMiningInfo } from '../models/bitcoin-rpc/IMiningInfo';
|
||||
|
||||
// import * as zmq from 'zeromq';
|
||||
|
||||
@Injectable()
|
||||
export class BitcoinRpcService {
|
||||
|
||||
@@ -30,17 +29,21 @@ export class BitcoinRpcService {
|
||||
|
||||
this.client = new RPCClient({ url, port, timeout, user, pass });
|
||||
|
||||
console.log('Bitcoin RPC connected');
|
||||
this.client.getrpcinfo().then((res) => {
|
||||
console.log('Bitcoin RPC connected');
|
||||
}, () => {
|
||||
console.error('Could not reach RPC host');
|
||||
});
|
||||
|
||||
if (this.configService.get('BITCOIN_ZMQ_HOST')) {
|
||||
// const sock = zmq.socket("sub");
|
||||
// sock.connect(this.configService.get('BITCOIN_ZMQ_HOST'));
|
||||
// sock.subscribe("rawblock");
|
||||
// sock.on("message", async (topic: Buffer, message: Buffer) => {
|
||||
// console.log("new block zmq");
|
||||
// this.pollMiningInfo();
|
||||
// });
|
||||
this.pollMiningInfo();
|
||||
const sock = zmq.socket("sub");
|
||||
sock.connect(this.configService.get('BITCOIN_ZMQ_HOST'));
|
||||
sock.subscribe("rawblock");
|
||||
sock.on("message", async (topic: Buffer, message: Buffer) => {
|
||||
console.log("new block zmq");
|
||||
await this.pollMiningInfo();
|
||||
});
|
||||
this.pollMiningInfo().then(() => { });
|
||||
} else {
|
||||
setInterval(this.pollMiningInfo.bind(this), 500);
|
||||
}
|
||||
@@ -77,11 +80,14 @@ export class BitcoinRpcService {
|
||||
if (block != null && block.data != null) {
|
||||
return Promise.resolve(JSON.parse(block.data));
|
||||
} else if (block == null) {
|
||||
// There is a unique constraint on the block height so if another process tries to lock, it'll throw
|
||||
try {
|
||||
await this.rpcBlockService.lockBlock(blockHeight, process.env.NODE_APP_INSTANCE);
|
||||
} catch (e) {
|
||||
result = await this.waitForBlock(blockHeight);
|
||||
|
||||
if (process.env.NODE_APP_INSTANCE != null) {
|
||||
// There is a unique constraint on the block height so if another process tries to lock, it'll throw
|
||||
try {
|
||||
await this.rpcBlockService.lockBlock(blockHeight, process.env.NODE_APP_INSTANCE);
|
||||
} catch (e) {
|
||||
result = await this.waitForBlock(blockHeight);
|
||||
}
|
||||
}
|
||||
|
||||
result = await this.client.getblocktemplate({
|
||||
|
||||
Reference in New Issue
Block a user