mempool/frontend/src/app/components/block/block.component.ts

450 lines
16 KiB
TypeScript
Raw Normal View History

import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { ElectrsApiService } from '../../services/electrs-api.service';
2022-06-22 19:08:16 +00:00
import { switchMap, tap, throttleTime, catchError, map, shareReplay, startWith, pairwise } from 'rxjs/operators';
import { Transaction, Vout } from '../../interfaces/electrs.interface';
2022-11-01 14:01:50 -06:00
import { Observable, of, Subscription, asyncScheduler, EMPTY, Subject } from 'rxjs';
import { StateService } from '../../services/state.service';
2022-09-21 17:23:45 +02:00
import { SeoService } from '../../services/seo.service';
import { WebsocketService } from '../../services/websocket.service';
import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe';
import { BlockExtended, TransactionStripped } from '../../interfaces/node-api.interface';
import { ApiService } from '../../services/api.service';
import { BlockOverviewGraphComponent } from '../../components/block-overview-graph/block-overview-graph.component';
import { detectWebGL } from '../../shared/graphs.utils';
2019-11-06 15:35:02 +08:00
@Component({
selector: 'app-block',
templateUrl: './block.component.html',
styleUrls: ['./block.component.scss']
})
export class BlockComponent implements OnInit, OnDestroy {
network = '';
block: BlockExtended;
blockHeight: number;
2022-06-14 16:39:37 +00:00
lastBlockHeight: number;
nextBlockHeight: number;
blockHash: string;
2019-11-12 16:39:59 +08:00
isLoadingBlock = true;
latestBlock: BlockExtended;
latestBlocks: BlockExtended[] = [];
transactions: Transaction[];
2019-11-12 16:39:59 +08:00
isLoadingTransactions = true;
2022-06-14 16:39:37 +00:00
strippedTransactions: TransactionStripped[];
overviewTransitionDirection: string;
isLoadingOverview = true;
2019-11-13 14:51:44 +08:00
error: any;
blockSubsidy: number;
fees: number;
paginationMaxSize: number;
page = 1;
itemsPerPage: number;
txsLoadingStatus$: Observable<number>;
showDetails = false;
showPreviousBlocklink = true;
showNextBlocklink = true;
2022-05-21 02:30:38 +04:00
transactionsError: any = null;
2022-06-14 16:39:37 +00:00
overviewError: any = null;
webGlEnabled = true;
2022-10-28 10:31:55 -06:00
indexingAvailable = false;
2019-11-06 15:35:02 +08:00
2022-06-14 16:39:37 +00:00
transactionSubscription: Subscription;
overviewSubscription: Subscription;
keyNavigationSubscription: Subscription;
blocksSubscription: Subscription;
networkChangedSubscription: Subscription;
queryParamsSubscription: Subscription;
nextBlockSubscription: Subscription = undefined;
nextBlockSummarySubscription: Subscription = undefined;
nextBlockTxListSubscription: Subscription = undefined;
timeLtrSubscription: Subscription;
timeLtr: boolean;
2022-11-01 14:01:50 -06:00
fetchAuditScore$ = new Subject<string>();
fetchAuditScoreSubscription: Subscription;
2022-06-14 16:39:37 +00:00
@ViewChild('blockGraph') blockGraph: BlockOverviewGraphComponent;
2019-11-12 16:39:59 +08:00
constructor(
private route: ActivatedRoute,
private location: Location,
private router: Router,
private electrsApiService: ElectrsApiService,
public stateService: StateService,
2020-03-24 00:52:08 +07:00
private seoService: SeoService,
2020-09-26 22:46:26 +07:00
private websocketService: WebsocketService,
2021-12-31 02:21:12 +04:00
private relativeUrlPipe: RelativeUrlPipe,
private apiService: ApiService
2022-06-14 16:39:37 +00:00
) {
this.webGlEnabled = detectWebGL();
}
2019-11-06 15:35:02 +08:00
ngOnInit() {
2020-09-26 22:46:26 +07:00
this.websocketService.want(['blocks', 'mempool-blocks']);
this.paginationMaxSize = window.matchMedia('(max-width: 670px)').matches ? 3 : 5;
this.network = this.stateService.network;
this.itemsPerPage = this.stateService.env.ITEMS_PER_PAGE;
this.timeLtrSubscription = this.stateService.timeLtr.subscribe((ltr) => {
this.timeLtr = !!ltr;
});
2022-10-28 10:31:55 -06:00
this.indexingAvailable = (this.stateService.env.BASE_MODULE === 'mempool' &&
this.stateService.env.MINING_DASHBOARD === true);
this.txsLoadingStatus$ = this.route.paramMap
.pipe(
switchMap(() => this.stateService.loadingIndicators$),
map((indicators) => indicators['blocktxs-' + this.blockHash] !== undefined ? indicators['blocktxs-' + this.blockHash] : 0)
);
this.blocksSubscription = this.stateService.blocks$
.subscribe(([block]) => {
this.latestBlock = block;
this.latestBlocks.unshift(block);
this.latestBlocks = this.latestBlocks.slice(0, this.stateService.env.KEEP_BLOCKS_AMOUNT);
this.setNextAndPreviousBlockLink();
if (block.id === this.blockHash) {
this.block = block;
2022-11-01 14:01:50 -06:00
if (this.block.id && this.block?.extras?.matchRate == null) {
this.fetchAuditScore$.next(this.block.id);
}
2022-02-04 19:28:00 +09:00
if (block?.extras?.reward != undefined) {
this.fees = block.extras.reward / 100000000 - this.blockSubsidy;
}
}
});
2022-11-01 14:01:50 -06:00
if (this.indexingAvailable) {
this.fetchAuditScoreSubscription = this.fetchAuditScore$
.pipe(
switchMap((hash) => this.apiService.getBlockAuditScore$(hash)),
catchError(() => EMPTY),
)
.subscribe((score) => {
if (score && score.hash === this.block.id) {
this.block.extras.matchRate = score.matchRate || null;
} else {
this.block.extras.matchRate = null;
}
});
}
2022-06-14 16:39:37 +00:00
const block$ = this.route.paramMap.pipe(
2019-11-12 16:39:59 +08:00
switchMap((params: ParamMap) => {
const blockHash: string = params.get('id') || '';
this.block = undefined;
this.page = 1;
this.error = undefined;
this.fees = undefined;
this.stateService.markBlock$.next({});
if (history.state.data && history.state.data.blockHeight) {
this.blockHeight = history.state.data.blockHeight;
}
let isBlockHeight = false;
if (/^[0-9]+$/.test(blockHash)) {
isBlockHeight = true;
} else {
this.blockHash = blockHash;
}
2020-02-24 03:42:29 +07:00
document.body.scrollTo(0, 0);
if (history.state.data && history.state.data.block) {
2020-02-17 20:39:20 +07:00
this.blockHeight = history.state.data.block.height;
return of(history.state.data.block);
} else {
this.isLoadingBlock = true;
2022-06-22 19:08:16 +00:00
this.isLoadingOverview = true;
let blockInCache: BlockExtended;
if (isBlockHeight) {
blockInCache = this.latestBlocks.find((block) => block.height === parseInt(blockHash, 10));
if (blockInCache) {
return of(blockInCache);
}
return this.electrsApiService.getBlockHashFromHeight$(parseInt(blockHash, 10))
.pipe(
switchMap((hash) => {
this.blockHash = hash;
this.location.replaceState(
this.router.createUrlTree([(this.network ? '/' + this.network : '') + '/block/', hash]).toString()
);
2022-08-16 16:15:34 +00:00
return this.apiService.getBlock$(hash).pipe(
catchError((err) => {
this.error = err;
this.isLoadingBlock = false;
this.isLoadingOverview = false;
return EMPTY;
})
);
}),
catchError((err) => {
this.error = err;
this.isLoadingBlock = false;
this.isLoadingOverview = false;
return EMPTY;
}),
);
}
2021-08-11 00:17:25 +05:30
blockInCache = this.latestBlocks.find((block) => block.id === this.blockHash);
if (blockInCache) {
return of(blockInCache);
}
2022-08-16 16:15:34 +00:00
return this.apiService.getBlock$(blockHash).pipe(
catchError((err) => {
this.error = err;
this.isLoadingBlock = false;
this.isLoadingOverview = false;
return EMPTY;
})
);
}
}),
tap((block: BlockExtended) => {
if (block.height > 0) {
// Preload previous block summary (execute the http query so the response will be cached)
this.unsubscribeNextBlockSubscriptions();
setTimeout(() => {
this.nextBlockSubscription = this.apiService.getBlock$(block.previousblockhash).subscribe();
this.nextBlockTxListSubscription = this.electrsApiService.getBlockTransactions$(block.previousblockhash).subscribe();
this.nextBlockSummarySubscription = this.apiService.getStrippedBlockTransactions$(block.previousblockhash).subscribe();
}, 100);
}
this.block = block;
this.blockHeight = block.height;
2022-06-14 16:39:37 +00:00
this.lastBlockHeight = this.blockHeight;
this.nextBlockHeight = block.height + 1;
this.setNextAndPreviousBlockLink();
this.seoService.setTitle($localize`:@@block.component.browser-title:Block ${block.height}:BLOCK_HEIGHT:: ${block.id}:BLOCK_ID:`);
this.isLoadingBlock = false;
this.setBlockSubsidy();
2022-02-04 19:28:00 +09:00
if (block?.extras?.reward !== undefined) {
this.fees = block.extras.reward / 100000000 - this.blockSubsidy;
}
this.stateService.markBlock$.next({ blockHeight: this.blockHeight });
2022-11-01 14:01:50 -06:00
if (this.block.id && this.block?.extras?.matchRate == null) {
this.fetchAuditScore$.next(this.block.id);
}
this.isLoadingTransactions = true;
this.transactions = null;
2022-05-21 02:30:38 +04:00
this.transactionsError = null;
2022-06-14 16:39:37 +00:00
this.isLoadingOverview = true;
2022-06-22 19:08:16 +00:00
this.overviewError = null;
}),
2022-06-22 19:08:16 +00:00
throttleTime(300, asyncScheduler, { leading: true, trailing: true }),
2022-06-14 16:39:37 +00:00
shareReplay(1)
);
this.transactionSubscription = block$.pipe(
switchMap((block) => this.electrsApiService.getBlockTransactions$(block.id)
.pipe(
catchError((err) => {
2022-05-21 02:30:38 +04:00
this.transactionsError = err;
return of([]);
}))
),
2019-11-12 16:39:59 +08:00
)
.subscribe((transactions: Transaction[]) => {
if (this.fees === undefined && transactions[0]) {
this.fees = transactions[0].vout.reduce((acc: number, curr: Vout) => acc + curr.value, 0) / 100000000 - this.blockSubsidy;
}
this.transactions = transactions;
this.isLoadingTransactions = false;
2019-11-13 14:51:44 +08:00
},
(error) => {
this.error = error;
this.isLoadingBlock = false;
2022-06-14 16:39:37 +00:00
this.isLoadingOverview = false;
});
this.overviewSubscription = block$.pipe(
startWith(null),
pairwise(),
switchMap(([prevBlock, block]) => this.apiService.getStrippedBlockTransactions$(block.id)
.pipe(
catchError((err) => {
this.overviewError = err;
return of([]);
}),
switchMap((transactions) => {
if (prevBlock) {
return of({ transactions, direction: (prevBlock.height < block.height) ? 'right' : 'left' });
} else {
return of({ transactions, direction: 'down' });
}
})
)
),
)
.subscribe(({transactions, direction}: {transactions: TransactionStripped[], direction: string}) => {
this.strippedTransactions = transactions;
2022-06-22 19:08:16 +00:00
this.isLoadingOverview = false;
if (this.blockGraph) {
this.blockGraph.destroy();
this.blockGraph.setup(this.strippedTransactions);
2022-06-14 16:39:37 +00:00
}
},
(error) => {
this.error = error;
this.isLoadingOverview = false;
2022-06-22 19:08:16 +00:00
if (this.blockGraph) {
this.blockGraph.destroy();
}
2019-11-12 16:39:59 +08:00
});
this.networkChangedSubscription = this.stateService.networkChanged$
.subscribe((network) => this.network = network);
this.queryParamsSubscription = this.route.queryParams.subscribe((params) => {
if (params.showDetails === 'true') {
this.showDetails = true;
} else {
this.showDetails = false;
}
});
this.keyNavigationSubscription = this.stateService.keyNavigation$.subscribe((event) => {
const prevKey = this.timeLtr ? 'ArrowLeft' : 'ArrowRight';
const nextKey = this.timeLtr ? 'ArrowRight' : 'ArrowLeft';
if (this.showPreviousBlocklink && event.key === prevKey && this.nextBlockHeight - 2 >= 0) {
this.navigateToPreviousBlock();
}
if (event.key === nextKey) {
if (this.showNextBlocklink) {
this.navigateToNextBlock();
} else {
2021-12-31 02:21:12 +04:00
this.router.navigate([this.relativeUrlPipe.transform('/mempool-block'), '0']);
}
}
});
}
ngOnDestroy() {
this.stateService.markBlock$.next({});
2022-06-14 16:39:37 +00:00
this.transactionSubscription.unsubscribe();
this.overviewSubscription.unsubscribe();
this.keyNavigationSubscription.unsubscribe();
this.blocksSubscription.unsubscribe();
this.networkChangedSubscription.unsubscribe();
this.queryParamsSubscription.unsubscribe();
this.timeLtrSubscription.unsubscribe();
2022-11-01 14:01:50 -06:00
this.fetchAuditScoreSubscription?.unsubscribe();
this.unsubscribeNextBlockSubscriptions();
}
unsubscribeNextBlockSubscriptions() {
if (this.nextBlockSubscription !== undefined) {
this.nextBlockSubscription.unsubscribe();
}
if (this.nextBlockSummarySubscription !== undefined) {
this.nextBlockSummarySubscription.unsubscribe();
}
if (this.nextBlockTxListSubscription !== undefined) {
this.nextBlockTxListSubscription.unsubscribe();
}
}
// TODO - Refactor this.fees/this.reward for liquid because it is not
// used anymore on Bitcoin networks (we use block.extras directly)
setBlockSubsidy() {
this.blockSubsidy = 0;
2019-11-12 16:39:59 +08:00
}
pageChange(page: number, target: HTMLElement) {
const start = (page - 1) * this.itemsPerPage;
2019-11-12 16:39:59 +08:00
this.isLoadingTransactions = true;
this.transactions = null;
2022-05-21 02:30:38 +04:00
this.transactionsError = null;
target.scrollIntoView(); // works for chrome
this.electrsApiService.getBlockTransactions$(this.block.id, start)
2022-05-21 02:30:38 +04:00
.pipe(
catchError((err) => {
this.transactionsError = err;
return of([]);
})
)
.subscribe((transactions) => {
this.transactions = transactions;
2019-11-12 16:39:59 +08:00
this.isLoadingTransactions = false;
target.scrollIntoView(); // works for firefox
2019-11-12 16:39:59 +08:00
});
2019-11-06 15:35:02 +08:00
}
toggleShowDetails() {
if (this.showDetails) {
this.showDetails = false;
this.router.navigate([], {
relativeTo: this.route,
queryParams: { showDetails: false },
queryParamsHandling: 'merge',
fragment: 'block'
});
} else {
this.showDetails = true;
this.router.navigate([], {
relativeTo: this.route,
queryParams: { showDetails: true },
queryParamsHandling: 'merge',
fragment: 'details'
});
}
}
hasTaproot(version: number): boolean {
const versionBit = 2; // Taproot
return (Number(version) & (1 << versionBit)) === (1 << versionBit);
}
displayTaprootStatus(): boolean {
if (this.stateService.network !== '') {
return false;
}
return this.block && this.block.height > 681393 && (new Date().getTime() / 1000) < 1628640000;
}
onResize(event: any) {
this.paginationMaxSize = event.target.innerWidth < 670 ? 3 : 5;
}
navigateToPreviousBlock() {
if (!this.block) {
return;
}
const block = this.latestBlocks.find((b) => b.height === this.nextBlockHeight - 2);
2021-12-31 02:21:12 +04:00
this.router.navigate([this.relativeUrlPipe.transform('/block/'),
block ? block.id : this.block.previousblockhash], { state: { data: { block, blockHeight: this.nextBlockHeight - 2 } } });
}
navigateToNextBlock() {
const block = this.latestBlocks.find((b) => b.height === this.nextBlockHeight);
2021-12-31 02:21:12 +04:00
this.router.navigate([this.relativeUrlPipe.transform('/block/'),
block ? block.id : this.nextBlockHeight], { state: { data: { block, blockHeight: this.nextBlockHeight } } });
}
setNextAndPreviousBlockLink(){
if (this.latestBlock) {
if (!this.blockHeight){
this.showPreviousBlocklink = false;
} else {
this.showPreviousBlocklink = true;
}
if (this.latestBlock.height && this.latestBlock.height === this.blockHeight) {
this.showNextBlocklink = false;
} else {
this.showNextBlocklink = true;
}
}
}
onTxClick(event: TransactionStripped): void {
const url = new RelativeUrlPipe(this.stateService).transform(`/tx/${event.txid}`);
this.router.navigate([url]);
}
}