diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 35b8d0011..51ddb7855 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ jobs: if: "!contains(github.event.pull_request.labels.*.name, 'ops') && !contains(github.head_ref, 'ops/')" strategy: matrix: - node: ["16", "17", "18", "20"] + node: ["20", "21"] flavor: ["dev", "prod"] fail-fast: false runs-on: "ubuntu-latest" @@ -35,7 +35,7 @@ jobs: - name: Install ${{ steps.gettoolchain.outputs.toolchain }} Rust toolchain # Latest version available on this commit is 1.71.1 # Commit date is Aug 3, 2023 - uses: dtolnay/rust-toolchain@f361669954a8ecfc00a3443f35f9ac8e610ffc06 + uses: dtolnay/rust-toolchain@be73d7920c329f220ce78e0234b8f96b7ae60248 with: toolchain: ${{ steps.gettoolchain.outputs.toolchain }} @@ -63,11 +63,104 @@ jobs: run: npm run build working-directory: ${{ matrix.node }}/${{ matrix.flavor }}/backend + + cache: + name: "Cache assets for builds" + runs-on: "ubuntu-latest" + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + path: assets + + - name: Setup Node + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node }} + registry-url: "https://registry.npmjs.org" + + - name: Install (Prod dependencies only) + run: npm ci --omit=dev --omit=optional + working-directory: assets/frontend + + - name: Restore cached mining pool assets + continue-on-error: true + id: cache-mining-pool-restore + uses: actions/cache/restore@v4 + with: + path: | + mining-pool-assets.zip + key: mining-pool-assets-cache + + - name: Restore promo video assets + continue-on-error: true + id: cache-promo-video-restore + uses: actions/cache/restore@v4 + with: + path: | + promo-video-assets.zip + key: promo-video-assets-cache + + - name: Unzip assets before building (src/resources) + continue-on-error: true + run: unzip -o mining-pool-assets.zip -d assets/frontend/src/resources/mining-pools + + - name: Unzip assets before building (src/resources) + continue-on-error: true + run: unzip -o promo-video-assets.zip -d assets/frontend/src/resources/promo-video + + # - name: Unzip assets before building (dist) + # continue-on-error: true + # run: unzip assets.zip -d assets/frontend/dist/mempool/browser/resources + + - name: Sync-assets + run: npm run sync-assets-dev + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + MEMPOOL_CDN: 1 + VERBOSE: 1 + working-directory: assets/frontend + + - name: Zip mining-pool assets + run: zip -jrq mining-pool-assets.zip assets/frontend/src/resources/mining-pools/* + + - name: Zip promo-video assets + run: zip -jrq promo-video-assets.zip assets/frontend/src/resources/promo-video/* + + - name: Upload mining pool assets as artifact + uses: actions/upload-artifact@v4 + with: + name: mining-pool-assets + path: mining-pool-assets.zip + + - name: Upload promo video assets as artifact + uses: actions/upload-artifact@v4 + with: + name: promo-video-assets + path: promo-video-assets.zip + + - name: Save mining pool assets cache + id: cache-mining-pool-save + uses: actions/cache/save@v4 + with: + path: | + mining-pool-assets.zip + key: mining-pool-assets-cache + + - name: Save promo video assets cache + id: cache-promo-video-save + uses: actions/cache/save@v4 + with: + path: | + promo-video-assets.zip + key: promo-video-assets-cache + frontend: + needs: cache if: "!contains(github.event.pull_request.labels.*.name, 'ops') && !contains(github.head_ref, 'ops/')" strategy: matrix: - node: ["16", "17", "18", "20"] + node: ["20", "21"] flavor: ["dev", "prod"] fail-fast: false runs-on: "ubuntu-latest" @@ -103,9 +196,171 @@ jobs: # - name: Test # run: npm run test + - name: Restore cached mining pool assets + continue-on-error: true + id: cache-mining-pool-restore + uses: actions/cache/restore@v4 + with: + path: | + mining-pool-assets.zip + key: mining-pool-assets-cache + + - name: Restore promo video assets + continue-on-error: true + id: cache-promo-video-restore + uses: actions/cache/restore@v4 + with: + path: | + promo-video-assets.zip + key: promo-video-assets-cache + + - name: Download artifact + uses: actions/download-artifact@v4 + with: + name: mining-pool-assets + + - name: Unzip assets before building (src/resources) + run: unzip -o mining-pool-assets.zip -d ${{ matrix.node }}/${{ matrix.flavor }}/frontend/src/resources/mining-pools + + - name: Download artifact + uses: actions/download-artifact@v4 + with: + name: promo-video-assets + + - name: Unzip assets before building (src/resources) + run: unzip -o promo-video-assets.zip -d ${{ matrix.node }}/${{ matrix.flavor }}/frontend/src/resources/promo-video + + # - name: Unzip assets before building (dist) + # run: unzip assets.zip -d ${{ matrix.node }}/${{ matrix.flavor }}/frontend/dist/mempool/browser/resources + + - name: Display resulting source tree + run: ls -R + - name: Build run: npm run build working-directory: ${{ matrix.node }}/${{ matrix.flavor }}/frontend env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + MEMPOOL_CDN: 1 + VERBOSE: 1 + + e2e: + if: "!contains(github.event.pull_request.labels.*.name, 'ops') && !contains(github.head_ref, 'ops/')" + runs-on: "ubuntu-latest" + needs: frontend + strategy: + fail-fast: false + matrix: + # module: ["mempool", "liquid", "bisq"] Disabling bisq support for now + module: ["mempool", "liquid"] + include: + - module: "mempool" + spec: | + cypress/e2e/mainnet/*.spec.ts + cypress/e2e/signet/*.spec.ts + cypress/e2e/testnet/*.spec.ts + - module: "liquid" + spec: | + cypress/e2e/liquid/liquid.spec.ts + cypress/e2e/liquidtestnet/liquidtestnet.spec.ts + # - module: "bisq" + # spec: | + # cypress/e2e/bisq/bisq.spec.ts + name: E2E tests for ${{ matrix.module }} + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + path: ${{ matrix.module }} + + - name: Setup node + uses: actions/setup-node@v3 + with: + node-version: 20 + cache: "npm" + cache-dependency-path: ${{ matrix.module }}/frontend/package-lock.json + + - name: Restore cached mining pool assets + continue-on-error: true + id: cache-mining-pool-restore + uses: actions/cache/restore@v4 + with: + path: | + mining-pool-assets.zip + key: mining-pool-assets-cache + + - name: Restore cached promo video assets + continue-on-error: true + id: cache-promo-video-restore + uses: actions/cache/restore@v4 + with: + path: | + promo-video-assets.zip + key: promo-video-assets-cache + + - name: Download artifact + uses: actions/download-artifact@v4 + with: + name: mining-pool-assets + + - name: Unzip assets before building (src/resources) + run: unzip -o mining-pool-assets.zip -d ${{ matrix.module }}/frontend/src/resources/mining-pools + + - name: Download artifact + uses: actions/download-artifact@v4 + with: + name: promo-video-assets + + - name: Unzip assets before building (src/resources) + run: unzip -o promo-video-assets.zip -d ${{ matrix.module }}/frontend/src/resources/promo-video + + - name: Chrome browser tests (${{ matrix.module }}) + uses: cypress-io/github-action@v5 + with: + tag: ${{ github.event_name }} + working-directory: ${{ matrix.module }}/frontend + build: npm run config:defaults:${{ matrix.module }} + start: npm run start:local-staging + wait-on: "http://localhost:4200" + wait-on-timeout: 120 + record: true + parallel: true + spec: ${{ matrix.spec }} + group: Tests on Chrome (${{ matrix.module }}) + browser: "chrome" + ci-build-id: "${{ github.sha }}-${{ github.workflow }}-${{ github.event_name }}" + env: + COMMIT_INFO_MESSAGE: ${{ github.event.pull_request.title }} + CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CYPRESS_PROJECT_ID: ${{ secrets.CYPRESS_PROJECT_ID }} + + validate_docker_json: + if: "!contains(github.event.pull_request.labels.*.name, 'ops') && !contains(github.head_ref, 'ops/')" + runs-on: "ubuntu-latest" + name: Validate generated backend Docker JSON + + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + path: docker + + - name: Install jq + run: sudo apt-get install jq -y + + - name: Create new start script to run on CI + run: | + sed '$d' start.sh > start_ci.sh + working-directory: docker/docker/backend + + - name: Run the script to generate the sample JSON + run: | + sh start_ci.sh + working-directory: docker/docker/backend + + - name: Validate JSON syntax + run: | + cat mempool-config.json | jq + working-directory: docker/docker/backend diff --git a/.github/workflows/cypress.yml b/.github/workflows/cypress.yml deleted file mode 100644 index d067136bf..000000000 --- a/.github/workflows/cypress.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: Cypress Tests - -on: - push: - branches: [master] - pull_request: - types: [opened, synchronize] - -jobs: - cypress: - if: "!contains(github.event.pull_request.labels.*.name, 'ops') && !contains(github.head_ref, 'ops/')" - runs-on: "ubuntu-latest" - strategy: - fail-fast: false - matrix: - module: ["mempool", "liquid", "bisq"] - include: - - module: "mempool" - spec: | - cypress/e2e/mainnet/*.spec.ts - cypress/e2e/signet/*.spec.ts - cypress/e2e/testnet/*.spec.ts - - module: "liquid" - spec: | - cypress/e2e/liquid/liquid.spec.ts - cypress/e2e/liquidtestnet/liquidtestnet.spec.ts - - module: "bisq" - spec: | - cypress/e2e/bisq/bisq.spec.ts - - name: E2E tests for ${{ matrix.module }} - steps: - - name: Checkout - uses: actions/checkout@v3 - with: - path: ${{ matrix.module }} - - - name: Setup node - uses: actions/setup-node@v3 - with: - node-version: 18 - cache: "npm" - cache-dependency-path: ${{ matrix.module }}/frontend/package-lock.json - - - name: Chrome browser tests (${{ matrix.module }}) - uses: cypress-io/github-action@v5 - with: - tag: ${{ github.event_name }} - working-directory: ${{ matrix.module }}/frontend - build: npm run config:defaults:${{ matrix.module }} - start: npm run start:local-staging - wait-on: "http://localhost:4200" - wait-on-timeout: 120 - record: true - parallel: true - spec: ${{ matrix.spec }} - group: Tests on Chrome (${{ matrix.module }}) - browser: "chrome" - ci-build-id: "${{ github.sha }}-${{ github.workflow }}-${{ github.event_name }}" - env: - COMMIT_INFO_MESSAGE: ${{ github.event.pull_request.title }} - CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - CYPRESS_PROJECT_ID: ${{ secrets.CYPRESS_PROJECT_ID }} diff --git a/.github/workflows/get_backend_block_height.yml b/.github/workflows/get_backend_block_height.yml new file mode 100644 index 000000000..52f3b038c --- /dev/null +++ b/.github/workflows/get_backend_block_height.yml @@ -0,0 +1,19 @@ +name: 'Check if servers are in sync' + +on: [workflow_dispatch] + +jobs: + print-backend-sha: + runs-on: 'ubuntu-latest' + name: Get block height + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + path: repo + + - name: Run script + working-directory: repo + run: | + chmod +x ./scripts/get_block_tip_height.sh + sh ./scripts/get_block_tip_height.sh diff --git a/.github/workflows/get_backend_hash.yml b/.github/workflows/get_backend_hash.yml new file mode 100644 index 000000000..57950dee4 --- /dev/null +++ b/.github/workflows/get_backend_hash.yml @@ -0,0 +1,19 @@ +name: 'Print backend hashes' + +on: [workflow_dispatch] + +jobs: + print-backend-sha: + runs-on: 'ubuntu-latest' + name: Print backend hashes + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + path: repo + + - name: Run script + working-directory: repo + run: | + chmod +x ./scripts/get_backend_hash.sh + sh ./scripts/get_backend_hash.sh diff --git a/.github/workflows/on-tag.yml b/.github/workflows/on-tag.yml index 5d8d71104..55a5585cc 100644 --- a/.github/workflows/on-tag.yml +++ b/.github/workflows/on-tag.yml @@ -68,17 +68,17 @@ jobs: run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin - name: Checkout project - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Init repo for Dockerization run: docker/init.sh "$TAG" - name: Set up QEMU - uses: docker/setup-qemu-action@v2 + uses: docker/setup-qemu-action@v3 id: qemu - name: Setup Docker buildx action - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 id: buildx - name: Available platforms @@ -98,7 +98,7 @@ jobs: docker buildx build \ --cache-from "type=local,src=/tmp/.buildx-cache" \ --cache-to "type=local,dest=/tmp/.buildx-cache" \ - --platform linux/amd64,linux/arm64,linux/arm/v7 \ + --platform linux/amd64,linux/arm64 \ --tag ${{ secrets.DOCKER_HUB_USER }}/${{ matrix.service }}:$TAG \ --tag ${{ secrets.DOCKER_HUB_USER }}/${{ matrix.service }}:latest \ --output "type=registry" ./${{ matrix.service }}/ \ diff --git a/.gitignore b/.gitignore index 4f19f2522..381f2187c 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ backend/mempool-config.json frontend/src/resources/config.template.js frontend/src/resources/config.js target +docker/backend/start_ci.sh \ No newline at end of file diff --git a/.nvmrc b/.nvmrc index f274881e5..a9b234d51 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v16.16.0 +v20.8.0 diff --git a/LICENSE.AGPL-3.md b/COPYING.md similarity index 100% rename from LICENSE.AGPL-3.md rename to COPYING.md diff --git a/Cargo.lock b/Cargo.lock index e03ab2531..0b51ea544 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,12 +57,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1586fa608b1dab41f667475b4a41faec5ba680aee428bfa5de4ea520fdc6e901" dependencies = [ "quote", - "syn 2.0.20", + "syn", ] +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + [[package]] name = "gbt" -version = "0.1.0" +version = "1.0.0" dependencies = [ "bytemuck", "bytes", @@ -71,15 +77,15 @@ dependencies = [ "napi-derive", "priority-queue", "tracing", - "tracing-log", + "tracing-log 0.2.0", "tracing-subscriber", ] [[package]] name = "hashbrown" -version = "0.12.3" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" [[package]] name = "hermit-abi" @@ -92,11 +98,11 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.9.3" +version = "2.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4" dependencies = [ - "autocfg", + "equivalent", "hashbrown", ] @@ -114,12 +120,12 @@ checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" [[package]] name = "libloading" -version = "0.7.4" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +checksum = "2caa5afb8bf9f3a2652760ce7d4f62d21c4d5a423e68466fca30df82f2330164" dependencies = [ "cfg-if", - "winapi", + "windows-targets", ] [[package]] @@ -145,9 +151,9 @@ checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "napi" -version = "2.13.2" +version = "2.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ede2d12cd6fce44da537a4be1f5510c73be2506c2e32dfaaafd1f36968f3a0e" +checksum = "54a63d0570e4c3e0daf7a8d380563610e159f538e20448d6c911337246f40e84" dependencies = [ "bitflags", "ctor", @@ -159,29 +165,29 @@ dependencies = [ [[package]] name = "napi-build" -version = "2.0.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "882a73d9ef23e8dc2ebbffb6a6ae2ef467c0f18ac10711e4cc59c5485d41df0e" +checksum = "2f9130fccc5f763cf2069b34a089a18f0d0883c66aceb81f2fad541a3d823c43" [[package]] name = "napi-derive" -version = "2.13.0" +version = "2.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da1c6a8fa84d549aa8708fcd062372bf8ec6e849de39016ab921067d21bde367" +checksum = "05bb7c37e3c1dda9312fdbe4a9fc7507fca72288ba154ec093e2d49114e727ce" dependencies = [ "cfg-if", "convert_case", "napi-derive-backend", "proc-macro2", "quote", - "syn 1.0.109", + "syn", ] [[package]] name = "napi-derive-backend" -version = "1.0.52" +version = "1.0.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20bbc7c69168d06a848f925ec5f0e0997f98e8c8d4f2cc30157f0da51c009e17" +checksum = "f785a8b8d7b83e925f5aa6d2ae3c159d17fe137ac368dc185bef410e7acdaeb4" dependencies = [ "convert_case", "once_cell", @@ -189,14 +195,14 @@ dependencies = [ "quote", "regex", "semver", - "syn 1.0.109", + "syn", ] [[package]] name = "napi-sys" -version = "2.2.3" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "166b5ef52a3ab5575047a9fe8d4a030cdd0f63c96f071cd6907674453b07bae3" +checksum = "2503fa6af34dc83fb74888df8b22afe933b58d37daf7d80424b1c60c68196b8b" dependencies = [ "libloading", ] @@ -223,9 +229,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "overload" @@ -241,11 +247,12 @@ checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" [[package]] name = "priority-queue" -version = "1.3.2" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fff39edfcaec0d64e8d0da38564fad195d2d51b680940295fcc307366e101e61" +checksum = "509354d8a769e8d0b567d6821b84495c60213162761a732d68ce87c964bd347f" dependencies = [ "autocfg", + "equivalent", "indexmap", ] @@ -320,17 +327,6 @@ version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - [[package]] name = "syn" version = "2.0.20" @@ -384,7 +380,7 @@ checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" dependencies = [ "proc-macro2", "quote", - "syn 2.0.20", + "syn", ] [[package]] @@ -408,6 +404,17 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.3.17" @@ -423,7 +430,7 @@ dependencies = [ "thread_local", "tracing", "tracing-core", - "tracing-log", + "tracing-log 0.1.3", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 59562297c..2f70699f4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [workspace] +resolver = "2" members = [ "./backend/rust-gbt", ] diff --git a/GNUmakefile b/GNUmakefile deleted file mode 100755 index de1144025..000000000 --- a/GNUmakefile +++ /dev/null @@ -1,47 +0,0 @@ -# If you see pwd_unknown showing up check permissions -PWD ?= pwd_unknown - -# DATABASE DEPLOY FOLDER CONFIG - default ./data -ifeq ($(data),) -DATA := data -export DATA -else -DATA := $(data) -export DATA -endif - -.PHONY: help -help: - @echo '' - @echo '' - @echo ' Usage: make [COMMAND]' - @echo '' - @echo ' make all # build init mempool and electrs' - @echo ' make init # setup some useful configs' - @echo ' make mempool # build q dockerized mempool.space' - @echo ' make electrs # build a docker electrs image' - @echo '' - -.PHONY: init -init: - @echo '' - mkdir -p $(DATA) $(DATA)/mysql $(DATA)/mysql/data - #REF: https://github.com/mempool/mempool/blob/master/docker/README.md - cat docker/docker-compose.yml > docker-compose.yml - cat backend/mempool-config.sample.json > backend/mempool-config.json -.PHONY: mempool -mempool: init - @echo '' - docker-compose up --force-recreate --always-recreate-deps - @echo '' -.PHONY: electrs -electrum: - #REF: https://hub.docker.com/r/beli/electrum - @echo '' - docker build -f docker/electrum/Dockerfile . - @echo '' -.PHONY: all -all: init - make mempool -####################### --include Makefile diff --git a/LICENSE b/LICENSE index 9f8592854..b6a09390a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,29 +1,28 @@ -The Mempool Open Source Project -Copyright (c) 2019-2023 The Mempool Open Source Project Developers +The Mempool Open Source Project® +Copyright (c) 2019-2023 Mempool Space K.K. and other shadowy super-coders This program is free software; you can redistribute it and/or modify it under -the terms of (at your option) either: +the terms of the GNU Affero General Public License as published by the Free +Software Foundation, either version 3 of the License or any later version +approved by a proxy statement published on . - 1) the GNU Affero General Public License as published by the Free Software - Foundation, either version 3 of the License or any later version approved by a - proxy statement published on ; or +However, this copyright license does not include an implied right or license +to use any trademarks, service marks, logos, or trade names of Mempool Space K.K. +or any other contributor to The Mempool Open Source Project. - 2) the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License or any later version approved by a - proxy statement published on . +The Mempool Open Source Project®, Mempool Accelerator™, Mempool Enterprise®, +Mempool Liquidity™, mempool.space®, Be your own explorer™, Explore the full +Bitcoin ecosystem™, Mempool Goggles™, the mempool Logo, the mempool Square logo, +the mempool Blocks logo, the mempool Blocks 3 | 2 logo, the mempool.space Vertical +Logo, and the mempool.space Horizontal logo are registered trademarks or trademarks +of Mempool Space K.K in Japan, the United States, and/or other countries. -However, this copyright license does not include an implied right or license to -use our trademarks: The Mempool Open Source Project®, mempool.space™, the -mempool Logo™, the mempool.space Vertical Logo™, the mempool.space Horizontal -Logo™, the mempool Square Logo™, and the mempool Blocks logo™ are registered -trademarks or trademarks of Mempool Space K.K in Japan, the United States, -and/or other countries. See our full Trademark Policy and Guidelines for more -details, published on . +See our full Trademark Policy and Guidelines for more details, published on +. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the full license terms for more details. You should have received a copy of both the GNU Affero General Public License -and the GNU General Public License along with this program. If not, see -. +along with this program. If not, see . diff --git a/LICENSE.GPL-3.md b/LICENSE.GPL-3.md deleted file mode 100644 index 2fb2e74d8..000000000 --- a/LICENSE.GPL-3.md +++ /dev/null @@ -1,675 +0,0 @@ -### GNU GENERAL PUBLIC LICENSE - -Version 3, 29 June 2007 - -Copyright (C) 2007 Free Software Foundation, Inc. - - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -### Preamble - -The GNU General Public License is a free, copyleft license for -software and other kinds of works. - -The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom -to share and change all versions of a program--to make sure it remains -free software for all its users. We, the Free Software Foundation, use -the GNU General Public License for most of our software; it applies -also to any other work released this way by its authors. You can apply -it to your programs, too. - -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you -have certain responsibilities if you distribute copies of the -software, or if you modify it: responsibilities to respect the freedom -of others. - -For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - -Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - -Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the -manufacturer can do so. This is fundamentally incompatible with the -aim of protecting users' freedom to change the software. The -systematic pattern of such abuse occurs in the area of products for -individuals to use, which is precisely where it is most unacceptable. -Therefore, we have designed this version of the GPL to prohibit the -practice for those products. If such problems arise substantially in -other domains, we stand ready to extend this provision to those -domains in future versions of the GPL, as needed to protect the -freedom of users. - -Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish -to avoid the special danger that patents applied to a free program -could make it effectively proprietary. To prevent this, the GPL -assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and -modification follow. - -### TERMS AND CONDITIONS - -#### 0. Definitions. - -"This License" refers to version 3 of the GNU General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds -of works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of -an exact copy. The resulting work is called a "modified version" of -the earlier work or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based -on the Program. - -To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - -To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user -through a computer network, with no transfer of a copy, is not -conveying. - -An interactive user interface displays "Appropriate Legal Notices" to -the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -#### 1. Source Code. - -The "source code" for a work means the preferred form of the work for -making modifications to it. "Object code" means any non-source form of -a work. - -A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - -The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can -regenerate automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same -work. - -#### 2. Basic Permissions. - -All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, -without conditions so long as your license otherwise remains in force. -You may convey covered works to others for the sole purpose of having -them make modifications exclusively for you, or provide you with -facilities for running those works, provided that you comply with the -terms of this License in conveying all material for which you do not -control copyright. Those thus making or running the covered works for -you must do so exclusively on your behalf, under your direction and -control, on terms that prohibit them from making any copies of your -copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the -conditions stated below. Sublicensing is not allowed; section 10 makes -it unnecessary. - -#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - -No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such -circumvention is effected by exercising rights under this License with -respect to the covered work, and you disclaim any intention to limit -operation or modification of the work as a means of enforcing, against -the work's users, your or third parties' legal rights to forbid -circumvention of technological measures. - -#### 4. Conveying Verbatim Copies. - -You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - -#### 5. Conveying Modified Source Versions. - -You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these -conditions: - -- a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. -- b) The work must carry prominent notices stating that it is - released under this License and any conditions added under - section 7. This requirement modifies the requirement in section 4 - to "keep intact all notices". -- c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. -- d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - -A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - -#### 6. Conveying Non-Source Forms. - -You may convey a covered work in object code form under the terms of -sections 4 and 5, provided that you also convey the machine-readable -Corresponding Source under the terms of this License, in one of these -ways: - -- a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. -- b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the Corresponding - Source from a network server at no charge. -- c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. -- d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. -- e) Convey the object code using peer-to-peer transmission, - provided you inform other peers where the object code and - Corresponding Source of the work are being offered to the general - public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, -family, or household purposes, or (2) anything designed or sold for -incorporation into a dwelling. In determining whether a product is a -consumer product, doubtful cases shall be resolved in favor of -coverage. For a particular product received by a particular user, -"normally used" refers to a typical or common use of that class of -product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected -to use, the product. A product is a consumer product regardless of -whether the product has substantial commercial, industrial or -non-consumer uses, unless such uses represent the only significant -mode of use of the product. - -"Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to -install and execute modified versions of a covered work in that User -Product from a modified version of its Corresponding Source. The -information must suffice to ensure that the continued functioning of -the modified object code is in no case prevented or interfered with -solely because modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or -updates for a work that has been modified or installed by the -recipient, or for the User Product in which it has been modified or -installed. Access to a network may be denied when the modification -itself materially and adversely affects the operation of the network -or violates the rules and protocols for communication across the -network. - -Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - -#### 7. Additional Terms. - -"Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders -of that material) supplement the terms of this License with terms: - -- a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or -- b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or -- c) Prohibiting misrepresentation of the origin of that material, - or requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or -- d) Limiting the use for publicity purposes of names of licensors - or authors of the material; or -- e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or -- f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions - of it) with contractual assumptions of liability to the recipient, - for any liability that these contractual assumptions directly - impose on those licensors and authors. - -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; the -above requirements apply either way. - -#### 8. Termination. - -You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - -However, if you cease all violation of this License, then your license -from a particular copyright holder is reinstated (a) provisionally, -unless and until the copyright holder explicitly and finally -terminates your license, and (b) permanently, if the copyright holder -fails to notify you of the violation by some reasonable means prior to -60 days after the cessation. - -Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - -#### 9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or run -a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - -#### 10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - -#### 11. Patents. - -A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims owned -or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - -If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - -A patent license is "discriminatory" if it does not include within the -scope of its coverage, prohibits the exercise of, or is conditioned on -the non-exercise of one or more of the rights that are specifically -granted under this License. You may not convey a covered work if you -are a party to an arrangement with a third party that is in the -business of distributing software, under which you make payment to the -third party based on the extent of your activity of conveying the -work, and under which the third party grants, to any of the parties -who would receive the covered work from you, a discriminatory patent -license (a) in connection with copies of the covered work conveyed by -you (or copies made from those copies), or (b) primarily for and in -connection with specific products or compilations that contain the -covered work, unless you entered into that arrangement, or that patent -license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - -#### 12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under -this License and any other pertinent obligations, then as a -consequence you may not convey it at all. For example, if you agree to -terms that obligate you to collect a royalty for further conveying -from those to whom you convey the Program, the only way you could -satisfy both those terms and this License would be to refrain entirely -from conveying the Program. - -#### 13. Use with the GNU Affero General Public License. - -Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - -#### 14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions -of the GNU General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in -detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies that a certain numbered version of the GNU General Public -License "or any later version" applies to it, you have the option of -following the terms and conditions either of that numbered version or -of any later version published by the Free Software Foundation. If the -Program does not specify a version number of the GNU General Public -License, you may choose any version ever published by the Free -Software Foundation. - -If the Program specifies that a proxy can decide which future versions -of the GNU General Public License can be used, that proxy's public -statement of acceptance of a version permanently authorizes you to -choose that version for the Program. - -Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - -#### 15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT -WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND -PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR -CORRECTION. - -#### 16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR -CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES -ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT -NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR -LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM -TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER -PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -#### 17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - -END OF TERMS AND CONDITIONS - -### How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these -terms. - -To do so, attach the following notices to the program. It is safest to -attach them to the start of each source file to most effectively state -the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper -mail. - -If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands \`show w' and \`show c' should show the -appropriate parts of the General Public License. Of course, your -program's commands might be different; for a GUI interface, you would -use an "about box". - -You should also get your employer (if you work as a programmer) or -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. For more information on this, and how to apply and follow -the GNU GPL, see . - -The GNU General Public License does not permit incorporating your -program into proprietary programs. If your program is a subroutine -library, you may consider it more useful to permit linking proprietary -applications with the library. If this is what you want to do, use the -GNU Lesser General Public License instead of this License. But first, -please read . diff --git a/Makefile b/Makefile deleted file mode 100644 index 53016c66f..000000000 --- a/Makefile +++ /dev/null @@ -1 +0,0 @@ -# For additional configs/scripting diff --git a/README.md b/README.md index dd2e62478..7e426f155 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,9 @@ It is an open-source project developed and operated for the benefit of the Bitco Mempool can be self-hosted on a wide variety of your own hardware, ranging from a simple one-click installation on a Raspberry Pi full-node distro all the way to a robust production instance on a powerful FreeBSD server. -**Most people should use a one-click install method.** Other install methods are meant for developers and others with experience managing servers. +Most people should use a one-click install method. + +Other install methods are meant for developers and others with experience managing servers. If you want support for your own production instance of Mempool, or if you'd like to have your own instance of Mempool run by the mempool.space team on their own global ISP infrastructure—check out Mempool Enterprise®. ## One-Click Installation @@ -22,7 +24,8 @@ Mempool can be conveniently installed on the following full-node distros: - [RaspiBlitz](https://github.com/rootzoll/raspiblitz) - [RoninDojo](https://code.samourai.io/ronindojo/RoninDojo) - [myNode](https://github.com/mynodebtc/mynode) -- [Start9](https://github.com/Start9Labs/embassy-os) +- [StartOS](https://github.com/Start9Labs/start-os) +- [nix-bitcoin](https://github.com/fort-nix/nix-bitcoin/blob/a1eacce6768ca4894f365af8f79be5bbd594e1c3/examples/configuration.nix#L129) **We highly recommend you deploy your own Mempool instance this way.** No matter which option you pick, you'll be able to get your own fully-sovereign instance of Mempool up quickly without needing to fiddle with any settings. diff --git a/backend/.gitignore b/backend/.gitignore index b4393c2f0..5cefd4bab 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -7,6 +7,12 @@ mempool-config.json pools.json icons.json +# docker +Dockerfile +GeoIP +start.sh +wait-for-it.sh + # compiled output /dist /tmp diff --git a/backend/README.md b/backend/README.md index e5d9dabdd..d0376408f 100644 --- a/backend/README.md +++ b/backend/README.md @@ -2,7 +2,7 @@ These instructions are mostly intended for developers. -If you choose to use these instructions for a production setup, be aware that you will still probably need to do additional configuration for your specific OS, environment, use-case, etc. We do our best here to provide a good starting point, but only proceed if you know what you're doing. Mempool only provides support for custom setups to [enterprise sponsors](https://mempool.space/enterprise). +If you choose to use these instructions for a production setup, be aware that you will still probably need to do additional configuration for your specific OS, environment, use-case, etc. We do our best here to provide a good starting point, but only proceed if you know what you're doing. Mempool only provides support for custom setups to project sponsors through [Mempool Enterprise®](https://mempool.space/enterprise). See other ways to set up Mempool on [the main README](/../../#installation-methods). diff --git a/backend/mempool-config.sample.json b/backend/mempool-config.sample.json index 00fe95cc5..5d2cf1fba 100644 --- a/backend/mempool-config.sample.json +++ b/backend/mempool-config.sample.json @@ -1,5 +1,6 @@ { "MEMPOOL": { + "OFFICIAL": false, "NETWORK": "mainnet", "BACKEND": "electrum", "ENABLED": true, @@ -16,6 +17,7 @@ "MEMPOOL_BLOCKS_AMOUNT": 8, "INDEXING_BLOCKS_AMOUNT": 11000, "BLOCKS_SUMMARIES_INDEXING": false, + "GOGGLES_INDEXING": false, "USE_SECOND_NODE_FOR_MINFEE": false, "EXTERNAL_ASSETS": [], "EXTERNAL_MAX_RETRY": 1, @@ -33,14 +35,17 @@ "DISK_CACHE_BLOCK_INTERVAL": 6, "MAX_PUSH_TX_SIZE_WEIGHT": 4000000, "ALLOW_UNREACHABLE": true, - "PRICE_UPDATES_PER_HOUR": 1 + "PRICE_UPDATES_PER_HOUR": 1, + "MAX_TRACKED_ADDRESSES": 100 }, "CORE_RPC": { "HOST": "127.0.0.1", "PORT": 8332, "USERNAME": "mempool", "PASSWORD": "mempool", - "TIMEOUT": 60000 + "TIMEOUT": 60000, + "COOKIE": false, + "COOKIE_PATH": "/path/to/bitcoin/.cookie" }, "ELECTRUM": { "HOST": "127.0.0.1", @@ -50,7 +55,10 @@ "ESPLORA": { "REST_API_URL": "http://127.0.0.1:3000", "UNIX_SOCKET_PATH": "/tmp/esplora-bitcoin-mainnet", + "BATCH_QUERY_BASE_SIZE": 1000, "RETRY_UNIX_SOCKET_AFTER": 30000, + "REQUEST_TIMEOUT": 10000, + "FALLBACK_TIMEOUT": 5000, "FALLBACK": [] }, "SECOND_CORE_RPC": { @@ -58,7 +66,9 @@ "PORT": 8332, "USERNAME": "mempool", "PASSWORD": "mempool", - "TIMEOUT": 60000 + "TIMEOUT": 60000, + "COOKIE": false, + "COOKIE_PATH": "/path/to/bitcoin/.cookie" }, "DATABASE": { "ENABLED": true, @@ -68,7 +78,8 @@ "DATABASE": "mempool", "USERNAME": "mempool", "PASSWORD": "mempool", - "TIMEOUT": 180000 + "TIMEOUT": 180000, + "PID_DIR": "" }, "SYSLOG": { "ENABLED": true, @@ -125,6 +136,11 @@ "BISQ_URL": "https://bisq.markets/api", "BISQ_ONION": "http://bisqmktse2cabavbr2xjq7xw3h6g5ottemo5rolfcwt6aly6tp5fdryd.onion/api" }, + "REDIS": { + "ENABLED": false, + "UNIX_SOCKET_PATH": "/tmp/redis.sock", + "BATCH_QUERY_BASE_SIZE": 5000 + }, "REPLICATION": { "ENABLED": false, "AUDIT": false, diff --git a/backend/package-lock.json b/backend/package-lock.json index f5452e908..95a949ef5 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -9,15 +9,15 @@ "version": "3.0.0-dev", "license": "GNU Affero General Public License v3.0", "dependencies": { - "@babel/core": "^7.21.3", + "@babel/core": "^7.24.0", "@mempool/electrum-client": "1.1.9", "@types/node": "^18.15.3", - "axios": "~1.4.0", + "axios": "~1.6.1", "bitcoinjs-lib": "~6.1.3", - "crypto-js": "~4.1.1", + "crypto-js": "~4.2.0", "express": "~4.18.2", "maxmind": "~4.3.11", - "mysql2": "~3.6.0", + "mysql2": "~3.9.1", "redis": "^4.6.6", "rust-gbt": "file:./rust-gbt", "socks-proxy-agent": "~7.0.0", @@ -26,7 +26,7 @@ }, "devDependencies": { "@babel/code-frame": "^7.18.6", - "@babel/core": "^7.21.3", + "@babel/core": "^7.24.0", "@types/compression": "^1.7.2", "@types/crypto-js": "^4.1.1", "@types/express": "^4.17.17", @@ -65,47 +65,48 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.21.4.tgz", - "integrity": "sha512-LYvhNKfwWSPpocw8GI7gpK2nq3HSDuEPC/uSYaALSJu9xjsalaaYFOq0Pwt5KmVqwEbZlDu81aLXwBOmD/Fv9g==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", + "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", "dev": true, "dependencies": { - "@babel/highlight": "^7.18.6" + "@babel/highlight": "^7.23.4", + "chalk": "^2.4.2" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/compat-data": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.21.4.tgz", - "integrity": "sha512-/DYyDpeCfaVinT40FPGdkkb+lYSKvsVuMjDAG7jPOWWiM1ibOaB9CXJAlc4d1QpP/U2q2P9jbrSlClKSErd55g==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz", + "integrity": "sha512-uU27kfDRlhfKl+w1U6vp16IuvSLtjAxdArVXPa9BvLkrr7CYIsxH5adpHObeAGY/41+syctUWOZ140a2Rvkgjw==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.21.4.tgz", - "integrity": "sha512-qt/YV149Jman/6AfmlxJ04LMIu8bMoyl3RB91yTFrxQmgbrSvQMy7cI8Q62FHx1t8wJ8B5fu0UDoLwHAhUo1QA==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.24.0.tgz", + "integrity": "sha512-fQfkg0Gjkza3nf0c7/w6Xf34BW4YvzNfACRLmmb7XRLa6XHdR+K9AlJlxneFfWYf6uhOzuzZVTjF/8KfndZANw==", "dev": true, "dependencies": { "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.21.4", - "@babel/generator": "^7.21.4", - "@babel/helper-compilation-targets": "^7.21.4", - "@babel/helper-module-transforms": "^7.21.2", - "@babel/helpers": "^7.21.0", - "@babel/parser": "^7.21.4", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.4", - "@babel/types": "^7.21.4", - "convert-source-map": "^1.7.0", + "@babel/code-frame": "^7.23.5", + "@babel/generator": "^7.23.6", + "@babel/helper-compilation-targets": "^7.23.6", + "@babel/helper-module-transforms": "^7.23.3", + "@babel/helpers": "^7.24.0", + "@babel/parser": "^7.24.0", + "@babel/template": "^7.24.0", + "@babel/traverse": "^7.24.0", + "@babel/types": "^7.24.0", + "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", - "json5": "^2.2.2", - "semver": "^6.3.0" + "json5": "^2.2.3", + "semver": "^6.3.1" }, "engines": { "node": ">=6.9.0" @@ -115,13 +116,19 @@ "url": "https://opencollective.com/babel" } }, + "node_modules/@babel/core/node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + }, "node_modules/@babel/generator": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.21.4.tgz", - "integrity": "sha512-NieM3pVIYW2SwGzKoqfPrQsf4xGs9M9AIG3ThppsSRmO+m7eQhmI6amajKMUeIO37wFfsvnvcxQFx6x6iqxDnA==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", + "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", "dev": true, "dependencies": { - "@babel/types": "^7.21.4", + "@babel/types": "^7.23.6", "@jridgewell/gen-mapping": "^0.3.2", "@jridgewell/trace-mapping": "^0.3.17", "jsesc": "^2.5.1" @@ -145,87 +152,84 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.21.4.tgz", - "integrity": "sha512-Fa0tTuOXZ1iL8IeDFUWCzjZcn+sJGd9RZdH9esYVjEejGmzf+FFYQpMi/kZUk2kPy/q1H3/GPw7np8qar/stfg==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz", + "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==", "dev": true, "dependencies": { - "@babel/compat-data": "^7.21.4", - "@babel/helper-validator-option": "^7.21.0", - "browserslist": "^4.21.3", + "@babel/compat-data": "^7.23.5", + "@babel/helper-validator-option": "^7.23.5", + "browserslist": "^4.22.2", "lru-cache": "^5.1.1", - "semver": "^6.3.0" + "semver": "^6.3.1" }, "engines": { "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" } }, "node_modules/@babel/helper-environment-visitor": { - "version": "7.18.9", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", - "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-function-name": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.21.0.tgz", - "integrity": "sha512-HfK1aMRanKHpxemaY2gqBmL04iAPOPRj7DxtNbiDOrJK+gdwkiNRVpCpUJYbUT+aZyemKN8brqTOxzCaG6ExRg==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dev": true, "dependencies": { - "@babel/template": "^7.20.7", - "@babel/types": "^7.21.0" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-hoist-variables": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", - "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", "dev": true, "dependencies": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-imports": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.21.4.tgz", - "integrity": "sha512-orajc5T2PsRYUN3ZryCEFeMDYwyw09c/pZeaQEZPH0MpKzSvn3e0uXsDBu3k03VI+9DBiRo+l22BfKTpKwa/Wg==", + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz", + "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==", "dev": true, "dependencies": { - "@babel/types": "^7.21.4" + "@babel/types": "^7.22.15" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.21.2", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.21.2.tgz", - "integrity": "sha512-79yj2AR4U/Oqq/WOV7Lx6hUjau1Zfo4cI+JLAVYeMV5XIlbOhmjEk5ulbTc9fMpmlojzZHkUUxAiK+UKn+hNQQ==", + "version": "7.23.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz", + "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==", "dev": true, "dependencies": { - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-module-imports": "^7.18.6", - "@babel/helper-simple-access": "^7.20.2", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/helper-validator-identifier": "^7.19.1", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.2", - "@babel/types": "^7.21.2" + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-module-imports": "^7.22.15", + "@babel/helper-simple-access": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/helper-validator-identifier": "^7.22.20" }, "engines": { "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" } }, "node_modules/@babel/helper-plugin-utils": { @@ -238,78 +242,78 @@ } }, "node_modules/@babel/helper-simple-access": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.20.2.tgz", - "integrity": "sha512-+0woI/WPq59IrqDYbVGfshjT5Dmk/nnbdpcF8SnMhhXObpTq2KNBdLFRFrkVdbDOyUmHBCxzm5FHV1rACIkIbA==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", + "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", "dev": true, "dependencies": { - "@babel/types": "^7.20.2" + "@babel/types": "^7.22.5" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-split-export-declaration": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", - "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", "dev": true, "dependencies": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-string-parser": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", - "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-option": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.21.0.tgz", - "integrity": "sha512-rmL/B8/f0mKS2baE9ZpyTcTavvEuWhTTW8amjzXNvYG4AwBsqTLikfXsEofsJEfKHf+HQVQbFOHy6o+4cnC/fQ==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz", + "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helpers": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.21.0.tgz", - "integrity": "sha512-XXve0CBtOW0pd7MRzzmoyuSj0e3SEzj8pgyFxnTT1NJZL38BD1MK7yYrm8yefRPIDvNNe14xR4FdbHwpInD4rA==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.24.0.tgz", + "integrity": "sha512-ulDZdc0Aj5uLc5nETsa7EPx2L7rM0YJM8r7ck7U73AXi7qOV44IHHRAYZHY6iU1rr3C5N4NtTmMRUJP6kwCWeA==", "dev": true, "dependencies": { - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.0", - "@babel/types": "^7.21.0" + "@babel/template": "^7.24.0", + "@babel/traverse": "^7.24.0", + "@babel/types": "^7.24.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", "dev": true, "dependencies": { - "@babel/helper-validator-identifier": "^7.18.6", - "chalk": "^2.0.0", + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", "js-tokens": "^4.0.0" }, "engines": { @@ -317,9 +321,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.21.4.tgz", - "integrity": "sha512-alVJj7k7zIxqBZ7BTRhz0IqJFxW1VJbm6N8JbcYhQ186df9ZBPbZBmWSqAMXwHGsCJdYks7z/voa3ibiS5bCIw==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.24.0.tgz", + "integrity": "sha512-QuP/FxEAzMSjXygs8v4N9dvdXzEHN4W1oF3PxuWAtPo08UdM17u89RDMgjLn/mlc56iM0HlLmVkO/wgR+rDgHg==", "dev": true, "bin": { "parser": "bin/babel-parser.js" @@ -506,34 +510,34 @@ } }, "node_modules/@babel/template": { - "version": "7.20.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz", - "integrity": "sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.24.0.tgz", + "integrity": "sha512-Bkf2q8lMB0AFpX0NFEqSbx1OkTHf0f+0j82mkw+ZpzBnkk7e9Ql0891vlfgi+kHwOk8tQjiQHpqh4LaSa0fKEA==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.18.6", - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7" + "@babel/code-frame": "^7.23.5", + "@babel/parser": "^7.24.0", + "@babel/types": "^7.24.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.21.4.tgz", - "integrity": "sha512-eyKrRHKdyZxqDm+fV1iqL9UAHMoIg0nDaGqfIOd8rKH17m5snv7Gn4qgjBoFfLz9APvjFU/ICT00NVCv1Epp8Q==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.24.0.tgz", + "integrity": "sha512-HfuJlI8qq3dEDmNU5ChzzpZRWq+oxCZQyMzIMEqLho+AQnhMnKQUzH6ydo3RBl/YjPCuk68Y6s0Gx0AeyULiWw==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.21.4", - "@babel/generator": "^7.21.4", - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-function-name": "^7.21.0", - "@babel/helper-hoist-variables": "^7.18.6", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/parser": "^7.21.4", - "@babel/types": "^7.21.4", - "debug": "^4.1.0", + "@babel/code-frame": "^7.23.5", + "@babel/generator": "^7.23.6", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.24.0", + "@babel/types": "^7.24.0", + "debug": "^4.3.1", "globals": "^11.1.0" }, "engines": { @@ -541,13 +545,13 @@ } }, "node_modules/@babel/types": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.21.4.tgz", - "integrity": "sha512-rU2oY501qDxE8Pyo7i/Orqma4ziCOrby0/9mvbDUGEfvZjb279Nk9k19e2fiCxHbRRpY2ZyrgW1eq22mvmOIzA==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.24.0.tgz", + "integrity": "sha512-+j7a5c253RfKh8iABBhywc8NSfP5LURe7Uh4qpsh6jc+aLJguvmIUBdjSdEMQv2bENrCR5MfRdjGo7vzS/ob7w==", "dev": true, "dependencies": { - "@babel/helper-string-parser": "^7.19.4", - "@babel/helper-validator-identifier": "^7.19.1", + "@babel/helper-string-parser": "^7.23.4", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" }, "engines": { @@ -1496,9 +1500,9 @@ } }, "node_modules/@napi-rs/cli": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-2.16.1.tgz", - "integrity": "sha512-L0Gr5iEQIDEbvWdDr1HUaBOxBSHL1VZhWSk1oryawoT8qJIY+KGfLFelU+Qma64ivCPbxYpkfPoKYVG3rcoGIA==", + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-2.18.0.tgz", + "integrity": "sha512-lfSRT7cs3iC4L+kv9suGYQEezn5Nii7Kpu+THsYVI0tA1Vh59LH45p4QADaD7hvIkmOz79eEGtoKQ9nAkAPkzA==", "bin": { "napi": "scripts/index.js" }, @@ -2321,9 +2325,9 @@ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, "node_modules/axios": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.4.0.tgz", - "integrity": "sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.1.tgz", + "integrity": "sha512-vfBmhDpKafglh0EldBEbVuoe7DyAavGSLWhuSm5ZSEKQnHhBf0xAAwybbNH1IkrJNGnS/VG4I5yxig1pCEXE4g==", "dependencies": { "follow-redirects": "^1.15.0", "form-data": "^4.0.0", @@ -2590,9 +2594,9 @@ } }, "node_modules/browserslist": { - "version": "4.21.5", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.5.tgz", - "integrity": "sha512-tUkiguQGW7S3IhB7N+c2MV/HZPSCPAAiYBZXLsBhFB/PCy6ZKKsZrmBayHV9fdGV/ARIfJ14NkxKzRDjvp7L6w==", + "version": "4.23.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", + "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", "dev": true, "funding": [ { @@ -2602,13 +2606,17 @@ { "type": "tidelift", "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" } ], "dependencies": { - "caniuse-lite": "^1.0.30001449", - "electron-to-chromium": "^1.4.284", - "node-releases": "^2.0.8", - "update-browserslist-db": "^1.0.10" + "caniuse-lite": "^1.0.30001587", + "electron-to-chromium": "^1.4.668", + "node-releases": "^2.0.14", + "update-browserslist-db": "^1.0.13" }, "bin": { "browserslist": "cli.js" @@ -2700,9 +2708,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001473", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001473.tgz", - "integrity": "sha512-ewDad7+D2vlyy+E4UJuVfiBsU69IL+8oVmTuZnH5Q6CIUbxNfI50uVpRHbUPDD6SUaN2o0Lh4DhTrvLG/Tn1yg==", + "version": "1.0.30001591", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001591.tgz", + "integrity": "sha512-PCzRMei/vXjJyL5mJtzNiUCKP59dm8Apqc3PH8gJkMnMXZGox93RbE76jHsmLwmIo6/3nsYIpJtx0O7u5PqFuQ==", "dev": true, "funding": [ { @@ -2892,9 +2900,9 @@ } }, "node_modules/crypto-js": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.1.1.tgz", - "integrity": "sha512-o2JlM7ydqd3Qk9CA0L4NL6mTzU2sdx96a+oOfPu8Mkl/PK51vSyoi8/rQ8NknZtk44vq15lmhAj9CIAGwgeWKw==" + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==" }, "node_modules/debug": { "version": "4.3.4", @@ -3023,9 +3031,9 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, "node_modules/electron-to-chromium": { - "version": "1.4.348", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.348.tgz", - "integrity": "sha512-gM7TdwuG3amns/1rlgxMbeeyNoBFPa+4Uu0c7FeROWh4qWmvSOnvcslKmWy51ggLKZ2n/F/4i2HJ+PVNxH9uCQ==", + "version": "1.4.686", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.686.tgz", + "integrity": "sha512-3avY1B+vUzNxEgkBDpKOP8WarvUAEwpRaiCL0He5OKWEFxzaOFiq4WoZEZe7qh0ReS7DiWoHMnYoQCKxNZNzSg==", "dev": true }, "node_modules/emittery": { @@ -3665,9 +3673,9 @@ "dev": true }, "node_modules/follow-redirects": { - "version": "1.15.2", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", - "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", "funding": [ { "type": "individual", @@ -6102,9 +6110,9 @@ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "node_modules/mysql2": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.6.0.tgz", - "integrity": "sha512-EWUGAhv6SphezurlfI2Fpt0uJEWLmirrtQR7SkbTHFC+4/mJBrPiSzHESHKAWKG7ALVD6xaG/NBjjd1DGJGQQQ==", + "version": "3.9.1", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.9.1.tgz", + "integrity": "sha512-3njoWAAhGBYy0tWBabqUQcLtczZUxrmmtc2vszQUekg3kTJyZ5/IeLC3Fo04u6y6Iy5Sba7pIIa2P/gs8D3ZeQ==", "dependencies": { "denque": "^2.1.0", "generate-function": "^2.3.1", @@ -6184,9 +6192,9 @@ "dev": true }, "node_modules/node-releases": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.10.tgz", - "integrity": "sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w==", + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", + "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", "dev": true }, "node_modules/normalize-path": { @@ -7399,9 +7407,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", - "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", + "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", "dev": true, "funding": [ { @@ -7411,6 +7419,10 @@ { "type": "tidelift", "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" } ], "dependencies": { @@ -7418,7 +7430,7 @@ "picocolors": "^1.0.0" }, "bin": { - "browserslist-lint": "cli.js" + "update-browserslist-db": "cli.js" }, "peerDependencies": { "browserslist": ">= 4.21.0" @@ -7655,10 +7667,10 @@ }, "rust-gbt": { "name": "gbt", - "version": "3.0.0-dev", + "version": "3.0.1", "hasInstallScript": true, "dependencies": { - "@napi-rs/cli": "^2.16.1" + "@napi-rs/cli": "2.18.0" }, "engines": { "node": ">= 12" @@ -7683,50 +7695,59 @@ } }, "@babel/code-frame": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.21.4.tgz", - "integrity": "sha512-LYvhNKfwWSPpocw8GI7gpK2nq3HSDuEPC/uSYaALSJu9xjsalaaYFOq0Pwt5KmVqwEbZlDu81aLXwBOmD/Fv9g==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", + "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", "dev": true, "requires": { - "@babel/highlight": "^7.18.6" + "@babel/highlight": "^7.23.4", + "chalk": "^2.4.2" } }, "@babel/compat-data": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.21.4.tgz", - "integrity": "sha512-/DYyDpeCfaVinT40FPGdkkb+lYSKvsVuMjDAG7jPOWWiM1ibOaB9CXJAlc4d1QpP/U2q2P9jbrSlClKSErd55g==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz", + "integrity": "sha512-uU27kfDRlhfKl+w1U6vp16IuvSLtjAxdArVXPa9BvLkrr7CYIsxH5adpHObeAGY/41+syctUWOZ140a2Rvkgjw==", "dev": true }, "@babel/core": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.21.4.tgz", - "integrity": "sha512-qt/YV149Jman/6AfmlxJ04LMIu8bMoyl3RB91yTFrxQmgbrSvQMy7cI8Q62FHx1t8wJ8B5fu0UDoLwHAhUo1QA==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.24.0.tgz", + "integrity": "sha512-fQfkg0Gjkza3nf0c7/w6Xf34BW4YvzNfACRLmmb7XRLa6XHdR+K9AlJlxneFfWYf6uhOzuzZVTjF/8KfndZANw==", "dev": true, "requires": { "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.21.4", - "@babel/generator": "^7.21.4", - "@babel/helper-compilation-targets": "^7.21.4", - "@babel/helper-module-transforms": "^7.21.2", - "@babel/helpers": "^7.21.0", - "@babel/parser": "^7.21.4", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.4", - "@babel/types": "^7.21.4", - "convert-source-map": "^1.7.0", + "@babel/code-frame": "^7.23.5", + "@babel/generator": "^7.23.6", + "@babel/helper-compilation-targets": "^7.23.6", + "@babel/helper-module-transforms": "^7.23.3", + "@babel/helpers": "^7.24.0", + "@babel/parser": "^7.24.0", + "@babel/template": "^7.24.0", + "@babel/traverse": "^7.24.0", + "@babel/types": "^7.24.0", + "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", - "json5": "^2.2.2", - "semver": "^6.3.0" + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "dependencies": { + "convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + } } }, "@babel/generator": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.21.4.tgz", - "integrity": "sha512-NieM3pVIYW2SwGzKoqfPrQsf4xGs9M9AIG3ThppsSRmO+m7eQhmI6amajKMUeIO37wFfsvnvcxQFx6x6iqxDnA==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", + "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", "dev": true, "requires": { - "@babel/types": "^7.21.4", + "@babel/types": "^7.23.6", "@jridgewell/gen-mapping": "^0.3.2", "@jridgewell/trace-mapping": "^0.3.17", "jsesc": "^2.5.1" @@ -7746,66 +7767,63 @@ } }, "@babel/helper-compilation-targets": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.21.4.tgz", - "integrity": "sha512-Fa0tTuOXZ1iL8IeDFUWCzjZcn+sJGd9RZdH9esYVjEejGmzf+FFYQpMi/kZUk2kPy/q1H3/GPw7np8qar/stfg==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz", + "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==", "dev": true, "requires": { - "@babel/compat-data": "^7.21.4", - "@babel/helper-validator-option": "^7.21.0", - "browserslist": "^4.21.3", + "@babel/compat-data": "^7.23.5", + "@babel/helper-validator-option": "^7.23.5", + "browserslist": "^4.22.2", "lru-cache": "^5.1.1", - "semver": "^6.3.0" + "semver": "^6.3.1" } }, "@babel/helper-environment-visitor": { - "version": "7.18.9", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", - "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", "dev": true }, "@babel/helper-function-name": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.21.0.tgz", - "integrity": "sha512-HfK1aMRanKHpxemaY2gqBmL04iAPOPRj7DxtNbiDOrJK+gdwkiNRVpCpUJYbUT+aZyemKN8brqTOxzCaG6ExRg==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dev": true, "requires": { - "@babel/template": "^7.20.7", - "@babel/types": "^7.21.0" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" } }, "@babel/helper-hoist-variables": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", - "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", + "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", "dev": true, "requires": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" } }, "@babel/helper-module-imports": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.21.4.tgz", - "integrity": "sha512-orajc5T2PsRYUN3ZryCEFeMDYwyw09c/pZeaQEZPH0MpKzSvn3e0uXsDBu3k03VI+9DBiRo+l22BfKTpKwa/Wg==", + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz", + "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==", "dev": true, "requires": { - "@babel/types": "^7.21.4" + "@babel/types": "^7.22.15" } }, "@babel/helper-module-transforms": { - "version": "7.21.2", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.21.2.tgz", - "integrity": "sha512-79yj2AR4U/Oqq/WOV7Lx6hUjau1Zfo4cI+JLAVYeMV5XIlbOhmjEk5ulbTc9fMpmlojzZHkUUxAiK+UKn+hNQQ==", + "version": "7.23.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz", + "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==", "dev": true, "requires": { - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-module-imports": "^7.18.6", - "@babel/helper-simple-access": "^7.20.2", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/helper-validator-identifier": "^7.19.1", - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.2", - "@babel/types": "^7.21.2" + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-module-imports": "^7.22.15", + "@babel/helper-simple-access": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/helper-validator-identifier": "^7.22.20" } }, "@babel/helper-plugin-utils": { @@ -7815,67 +7833,67 @@ "dev": true }, "@babel/helper-simple-access": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.20.2.tgz", - "integrity": "sha512-+0woI/WPq59IrqDYbVGfshjT5Dmk/nnbdpcF8SnMhhXObpTq2KNBdLFRFrkVdbDOyUmHBCxzm5FHV1rACIkIbA==", + "version": "7.22.5", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", + "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", "dev": true, "requires": { - "@babel/types": "^7.20.2" + "@babel/types": "^7.22.5" } }, "@babel/helper-split-export-declaration": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", - "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "version": "7.22.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", + "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", "dev": true, "requires": { - "@babel/types": "^7.18.6" + "@babel/types": "^7.22.5" } }, "@babel/helper-string-parser": { - "version": "7.19.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", - "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", "dev": true }, "@babel/helper-validator-identifier": { - "version": "7.19.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", - "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", "dev": true }, "@babel/helper-validator-option": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.21.0.tgz", - "integrity": "sha512-rmL/B8/f0mKS2baE9ZpyTcTavvEuWhTTW8amjzXNvYG4AwBsqTLikfXsEofsJEfKHf+HQVQbFOHy6o+4cnC/fQ==", + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz", + "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==", "dev": true }, "@babel/helpers": { - "version": "7.21.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.21.0.tgz", - "integrity": "sha512-XXve0CBtOW0pd7MRzzmoyuSj0e3SEzj8pgyFxnTT1NJZL38BD1MK7yYrm8yefRPIDvNNe14xR4FdbHwpInD4rA==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.24.0.tgz", + "integrity": "sha512-ulDZdc0Aj5uLc5nETsa7EPx2L7rM0YJM8r7ck7U73AXi7qOV44IHHRAYZHY6iU1rr3C5N4NtTmMRUJP6kwCWeA==", "dev": true, "requires": { - "@babel/template": "^7.20.7", - "@babel/traverse": "^7.21.0", - "@babel/types": "^7.21.0" + "@babel/template": "^7.24.0", + "@babel/traverse": "^7.24.0", + "@babel/types": "^7.24.0" } }, "@babel/highlight": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", - "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", "dev": true, "requires": { - "@babel/helper-validator-identifier": "^7.18.6", - "chalk": "^2.0.0", + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", "js-tokens": "^4.0.0" } }, "@babel/parser": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.21.4.tgz", - "integrity": "sha512-alVJj7k7zIxqBZ7BTRhz0IqJFxW1VJbm6N8JbcYhQ186df9ZBPbZBmWSqAMXwHGsCJdYks7z/voa3ibiS5bCIw==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.24.0.tgz", + "integrity": "sha512-QuP/FxEAzMSjXygs8v4N9dvdXzEHN4W1oF3PxuWAtPo08UdM17u89RDMgjLn/mlc56iM0HlLmVkO/wgR+rDgHg==", "dev": true }, "@babel/plugin-syntax-async-generators": { @@ -8005,42 +8023,42 @@ } }, "@babel/template": { - "version": "7.20.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz", - "integrity": "sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.24.0.tgz", + "integrity": "sha512-Bkf2q8lMB0AFpX0NFEqSbx1OkTHf0f+0j82mkw+ZpzBnkk7e9Ql0891vlfgi+kHwOk8tQjiQHpqh4LaSa0fKEA==", "dev": true, "requires": { - "@babel/code-frame": "^7.18.6", - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7" + "@babel/code-frame": "^7.23.5", + "@babel/parser": "^7.24.0", + "@babel/types": "^7.24.0" } }, "@babel/traverse": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.21.4.tgz", - "integrity": "sha512-eyKrRHKdyZxqDm+fV1iqL9UAHMoIg0nDaGqfIOd8rKH17m5snv7Gn4qgjBoFfLz9APvjFU/ICT00NVCv1Epp8Q==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.24.0.tgz", + "integrity": "sha512-HfuJlI8qq3dEDmNU5ChzzpZRWq+oxCZQyMzIMEqLho+AQnhMnKQUzH6ydo3RBl/YjPCuk68Y6s0Gx0AeyULiWw==", "dev": true, "requires": { - "@babel/code-frame": "^7.21.4", - "@babel/generator": "^7.21.4", - "@babel/helper-environment-visitor": "^7.18.9", - "@babel/helper-function-name": "^7.21.0", - "@babel/helper-hoist-variables": "^7.18.6", - "@babel/helper-split-export-declaration": "^7.18.6", - "@babel/parser": "^7.21.4", - "@babel/types": "^7.21.4", - "debug": "^4.1.0", + "@babel/code-frame": "^7.23.5", + "@babel/generator": "^7.23.6", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", + "@babel/helper-hoist-variables": "^7.22.5", + "@babel/helper-split-export-declaration": "^7.22.6", + "@babel/parser": "^7.24.0", + "@babel/types": "^7.24.0", + "debug": "^4.3.1", "globals": "^11.1.0" } }, "@babel/types": { - "version": "7.21.4", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.21.4.tgz", - "integrity": "sha512-rU2oY501qDxE8Pyo7i/Orqma4ziCOrby0/9mvbDUGEfvZjb279Nk9k19e2fiCxHbRRpY2ZyrgW1eq22mvmOIzA==", + "version": "7.24.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.24.0.tgz", + "integrity": "sha512-+j7a5c253RfKh8iABBhywc8NSfP5LURe7Uh4qpsh6jc+aLJguvmIUBdjSdEMQv2bENrCR5MfRdjGo7vzS/ob7w==", "dev": true, "requires": { - "@babel/helper-string-parser": "^7.19.4", - "@babel/helper-validator-identifier": "^7.19.1", + "@babel/helper-string-parser": "^7.23.4", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" } }, @@ -8757,9 +8775,9 @@ "integrity": "sha512-mlvPiCzUlaETpYW3i6V87A24jjMYgsebaXtUo3WQyyLnYUuxs0KiXQ2mnKh3h15j8Xg/hfxeGIi+5OC9u0nftQ==" }, "@napi-rs/cli": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-2.16.1.tgz", - "integrity": "sha512-L0Gr5iEQIDEbvWdDr1HUaBOxBSHL1VZhWSk1oryawoT8qJIY+KGfLFelU+Qma64ivCPbxYpkfPoKYVG3rcoGIA==" + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-2.18.0.tgz", + "integrity": "sha512-lfSRT7cs3iC4L+kv9suGYQEezn5Nii7Kpu+THsYVI0tA1Vh59LH45p4QADaD7hvIkmOz79eEGtoKQ9nAkAPkzA==" }, "@noble/hashes": { "version": "1.3.0", @@ -9397,9 +9415,9 @@ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" }, "axios": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.4.0.tgz", - "integrity": "sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.1.tgz", + "integrity": "sha512-vfBmhDpKafglh0EldBEbVuoe7DyAavGSLWhuSm5ZSEKQnHhBf0xAAwybbNH1IkrJNGnS/VG4I5yxig1pCEXE4g==", "requires": { "follow-redirects": "^1.15.0", "form-data": "^4.0.0", @@ -9615,15 +9633,15 @@ } }, "browserslist": { - "version": "4.21.5", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.5.tgz", - "integrity": "sha512-tUkiguQGW7S3IhB7N+c2MV/HZPSCPAAiYBZXLsBhFB/PCy6ZKKsZrmBayHV9fdGV/ARIfJ14NkxKzRDjvp7L6w==", + "version": "4.23.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", + "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", "dev": true, "requires": { - "caniuse-lite": "^1.0.30001449", - "electron-to-chromium": "^1.4.284", - "node-releases": "^2.0.8", - "update-browserslist-db": "^1.0.10" + "caniuse-lite": "^1.0.30001587", + "electron-to-chromium": "^1.4.668", + "node-releases": "^2.0.14", + "update-browserslist-db": "^1.0.13" } }, "bs-logger": { @@ -9694,9 +9712,9 @@ "dev": true }, "caniuse-lite": { - "version": "1.0.30001473", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001473.tgz", - "integrity": "sha512-ewDad7+D2vlyy+E4UJuVfiBsU69IL+8oVmTuZnH5Q6CIUbxNfI50uVpRHbUPDD6SUaN2o0Lh4DhTrvLG/Tn1yg==", + "version": "1.0.30001591", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001591.tgz", + "integrity": "sha512-PCzRMei/vXjJyL5mJtzNiUCKP59dm8Apqc3PH8gJkMnMXZGox93RbE76jHsmLwmIo6/3nsYIpJtx0O7u5PqFuQ==", "dev": true }, "chalk": { @@ -9832,9 +9850,9 @@ } }, "crypto-js": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.1.1.tgz", - "integrity": "sha512-o2JlM7ydqd3Qk9CA0L4NL6mTzU2sdx96a+oOfPu8Mkl/PK51vSyoi8/rQ8NknZtk44vq15lmhAj9CIAGwgeWKw==" + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==" }, "debug": { "version": "4.3.4", @@ -9924,9 +9942,9 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, "electron-to-chromium": { - "version": "1.4.348", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.348.tgz", - "integrity": "sha512-gM7TdwuG3amns/1rlgxMbeeyNoBFPa+4Uu0c7FeROWh4qWmvSOnvcslKmWy51ggLKZ2n/F/4i2HJ+PVNxH9uCQ==", + "version": "1.4.686", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.686.tgz", + "integrity": "sha512-3avY1B+vUzNxEgkBDpKOP8WarvUAEwpRaiCL0He5OKWEFxzaOFiq4WoZEZe7qh0ReS7DiWoHMnYoQCKxNZNzSg==", "dev": true }, "emittery": { @@ -10422,9 +10440,9 @@ "dev": true }, "follow-redirects": { - "version": "1.15.2", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", - "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==" + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==" }, "form-data": { "version": "4.0.0", @@ -12212,9 +12230,9 @@ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "mysql2": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.6.0.tgz", - "integrity": "sha512-EWUGAhv6SphezurlfI2Fpt0uJEWLmirrtQR7SkbTHFC+4/mJBrPiSzHESHKAWKG7ALVD6xaG/NBjjd1DGJGQQQ==", + "version": "3.9.1", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.9.1.tgz", + "integrity": "sha512-3njoWAAhGBYy0tWBabqUQcLtczZUxrmmtc2vszQUekg3kTJyZ5/IeLC3Fo04u6y6Iy5Sba7pIIa2P/gs8D3ZeQ==", "requires": { "denque": "^2.1.0", "generate-function": "^2.3.1", @@ -12280,9 +12298,9 @@ "dev": true }, "node-releases": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.10.tgz", - "integrity": "sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w==", + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", + "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", "dev": true }, "normalize-path": { @@ -12685,7 +12703,7 @@ "rust-gbt": { "version": "file:rust-gbt", "requires": { - "@napi-rs/cli": "^2.16.1" + "@napi-rs/cli": "2.18.0" } }, "safe-buffer": { @@ -13118,9 +13136,9 @@ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==" }, "update-browserslist-db": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", - "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", + "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", "dev": true, "requires": { "escalade": "^3.1.1", diff --git a/backend/package.json b/backend/package.json index 500cbf93c..640250a1f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -35,18 +35,19 @@ "lint": "./node_modules/.bin/eslint . --ext .ts", "lint:fix": "./node_modules/.bin/eslint . --ext .ts --fix", "prettier": "./node_modules/.bin/prettier --write \"src/**/*.{js,ts}\"", - "rust-build": "cd rust-gbt && npm run build-release" + "rust-clean": "cd rust-gbt && rm -f *.node index.d.ts index.js && rm -rf target && cd ../", + "rust-build": "npm run rust-clean && cd rust-gbt && npm run build-release" }, "dependencies": { - "@babel/core": "^7.21.3", + "@babel/core": "^7.24.0", "@mempool/electrum-client": "1.1.9", "@types/node": "^18.15.3", - "axios": "~1.4.0", + "axios": "~1.6.1", "bitcoinjs-lib": "~6.1.3", - "crypto-js": "~4.1.1", + "crypto-js": "~4.2.0", "express": "~4.18.2", "maxmind": "~4.3.11", - "mysql2": "~3.6.0", + "mysql2": "~3.9.1", "rust-gbt": "file:./rust-gbt", "redis": "^4.6.6", "socks-proxy-agent": "~7.0.0", @@ -55,7 +56,7 @@ }, "devDependencies": { "@babel/code-frame": "^7.18.6", - "@babel/core": "^7.21.3", + "@babel/core": "^7.24.0", "@types/compression": "^1.7.2", "@types/crypto-js": "^4.1.1", "@types/express": "^4.17.17", diff --git a/backend/rust-gbt/Cargo.toml b/backend/rust-gbt/Cargo.toml index 09fde52e2..10c572bf9 100644 --- a/backend/rust-gbt/Cargo.toml +++ b/backend/rust-gbt/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "gbt" -version = "0.1.0" -description = "An inefficient re-implementation of the getBlockTemplate algorithm in Rust" +version = "1.0.0" +description = "An efficient re-implementation of the getBlockTemplate algorithm in Rust" authors = ["mononaut"] edition = "2021" publish = false @@ -12,14 +12,14 @@ crate-type = ["cdylib"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -priority-queue = "1.3.2" +priority-queue = "2.0.2" bytes = "1.4.0" -napi = { version = "2.13.2", features = ["napi8", "tokio_rt"] } -napi-derive = "2.13.0" +napi = { version = "2.16.0", features = ["napi8", "tokio_rt"] } +napi-derive = "2.16.0" bytemuck = "1.13.1" tracing = "0.1.36" -tracing-log = "0.1.3" +tracing-log = "0.2.0" tracing-subscriber = { version = "0.3.15", features = ["env-filter"]} [build-dependencies] -napi-build = "2.0.1" +napi-build = "2.1.2" diff --git a/backend/rust-gbt/index.d.ts b/backend/rust-gbt/index.d.ts index 2bd8a620a..d1cb85b92 100644 --- a/backend/rust-gbt/index.d.ts +++ b/backend/rust-gbt/index.d.ts @@ -45,5 +45,6 @@ export class GbtResult { blockWeights: Array clusters: Array> rates: Array> - constructor(blocks: Array>, blockWeights: Array, clusters: Array>, rates: Array>) + overflow: Array + constructor(blocks: Array>, blockWeights: Array, clusters: Array>, rates: Array>, overflow: Array) } diff --git a/backend/rust-gbt/index.js b/backend/rust-gbt/index.js index 8680501d1..dd58a8b76 100644 --- a/backend/rust-gbt/index.js +++ b/backend/rust-gbt/index.js @@ -237,6 +237,49 @@ switch (platform) { loadError = e } break + case 'riscv64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'gbt.linux-riscv64-musl.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./gbt.linux-riscv64-musl.node') + } else { + nativeBinding = require('gbt-linux-riscv64-musl') + } + } catch (e) { + loadError = e + } + } else { + localFileExisted = existsSync( + join(__dirname, 'gbt.linux-riscv64-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./gbt.linux-riscv64-gnu.node') + } else { + nativeBinding = require('gbt-linux-riscv64-gnu') + } + } catch (e) { + loadError = e + } + } + break + case 's390x': + localFileExisted = existsSync( + join(__dirname, 'gbt.linux-s390x-gnu.node') + ) + try { + if (localFileExisted) { + nativeBinding = require('./gbt.linux-s390x-gnu.node') + } else { + nativeBinding = require('gbt-linux-s390x-gnu') + } + } catch (e) { + loadError = e + } + break default: throw new Error(`Unsupported architecture on Linux: ${arch}`) } diff --git a/backend/rust-gbt/package-lock.json b/backend/rust-gbt/package-lock.json index b7949b9ab..e351c82f8 100644 --- a/backend/rust-gbt/package-lock.json +++ b/backend/rust-gbt/package-lock.json @@ -1,24 +1,24 @@ { "name": "gbt", - "version": "3.0.0-dev", + "version": "3.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gbt", - "version": "3.0.0-dev", + "version": "3.0.1", "hasInstallScript": true, "dependencies": { - "@napi-rs/cli": "^2.16.1" + "@napi-rs/cli": "2.18.0" }, "engines": { "node": ">= 12" } }, "node_modules/@napi-rs/cli": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-2.16.1.tgz", - "integrity": "sha512-L0Gr5iEQIDEbvWdDr1HUaBOxBSHL1VZhWSk1oryawoT8qJIY+KGfLFelU+Qma64ivCPbxYpkfPoKYVG3rcoGIA==", + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-2.18.0.tgz", + "integrity": "sha512-lfSRT7cs3iC4L+kv9suGYQEezn5Nii7Kpu+THsYVI0tA1Vh59LH45p4QADaD7hvIkmOz79eEGtoKQ9nAkAPkzA==", "bin": { "napi": "scripts/index.js" }, diff --git a/backend/rust-gbt/package.json b/backend/rust-gbt/package.json index c95f36b06..b0dd96698 100644 --- a/backend/rust-gbt/package.json +++ b/backend/rust-gbt/package.json @@ -1,7 +1,7 @@ { "name": "gbt", - "version": "3.0.0-dev", - "description": "An inefficient re-implementation of the getBlockTemplate algorithm in Rust", + "version": "3.0.1", + "description": "An efficient re-implementation of the getBlockTemplate algorithm in Rust", "main": "index.js", "types": "index.d.ts", "scripts": { @@ -25,7 +25,7 @@ } }, "dependencies": { - "@napi-rs/cli": "^2.16.1" + "@napi-rs/cli": "2.18.0" }, "engines": { "node": ">= 12" diff --git a/backend/rust-gbt/src/gbt.rs b/backend/rust-gbt/src/gbt.rs index fb28dc299..38bf826a6 100644 --- a/backend/rust-gbt/src/gbt.rs +++ b/backend/rust-gbt/src/gbt.rs @@ -60,6 +60,7 @@ pub fn gbt(mempool: &mut ThreadTransactionsMap, accelerations: &[ThreadAccelerat indexed_accelerations[acceleration.uid as usize] = Some(acceleration); } + info!("Initializing working vecs with uid capacity for {}", max_uid + 1); let mempool_len = mempool.len(); let mut audit_pool: AuditPool = Vec::with_capacity(max_uid + 1); audit_pool.resize(max_uid + 1, None); @@ -127,74 +128,75 @@ pub fn gbt(mempool: &mut ThreadTransactionsMap, accelerations: &[ThreadAccelerat let next_from_stack = next_valid_from_stack(&mut mempool_stack, &audit_pool); let next_from_queue = next_valid_from_queue(&mut modified, &audit_pool); if next_from_stack.is_none() && next_from_queue.is_none() { - continue; - } - let (next_tx, from_stack) = match (next_from_stack, next_from_queue) { - (Some(stack_tx), Some(queue_tx)) => match queue_tx.cmp(stack_tx) { - std::cmp::Ordering::Less => (stack_tx, true), - _ => (queue_tx, false), - }, - (Some(stack_tx), None) => (stack_tx, true), - (None, Some(queue_tx)) => (queue_tx, false), - (None, None) => unreachable!(), - }; - - if from_stack { - mempool_stack.pop(); + info!("No transactions left! {:#?} in overflow", overflow.len()); } else { - modified.pop(); - } + let (next_tx, from_stack) = match (next_from_stack, next_from_queue) { + (Some(stack_tx), Some(queue_tx)) => match queue_tx.cmp(stack_tx) { + std::cmp::Ordering::Less => (stack_tx, true), + _ => (queue_tx, false), + }, + (Some(stack_tx), None) => (stack_tx, true), + (None, Some(queue_tx)) => (queue_tx, false), + (None, None) => unreachable!(), + }; - if blocks.len() < (MAX_BLOCKS - 1) - && ((block_weight + (4 * next_tx.ancestor_sigop_adjusted_vsize()) - >= MAX_BLOCK_WEIGHT_UNITS) - || (block_sigops + next_tx.ancestor_sigops() > BLOCK_SIGOPS)) - { - // hold this package in an overflow list while we check for smaller options - overflow.push(next_tx.uid); - failures += 1; - } else { - let mut package: Vec<(u32, u32, usize)> = Vec::new(); - let mut cluster: Vec = Vec::new(); - let is_cluster: bool = !next_tx.ancestors.is_empty(); - for ancestor_id in &next_tx.ancestors { - if let Some(Some(ancestor)) = audit_pool.get(*ancestor_id as usize) { - package.push((*ancestor_id, ancestor.order(), ancestor.ancestors.len())); - } - } - package.sort_unstable_by(|a, b| -> Ordering { - if a.2 != b.2 { - // order by ascending ancestor count - a.2.cmp(&b.2) - } else if a.1 != b.1 { - // tie-break by ascending partial txid - a.1.cmp(&b.1) - } else { - // tie-break partial txid collisions by ascending uid - a.0.cmp(&b.0) - } - }); - package.push((next_tx.uid, next_tx.order(), next_tx.ancestors.len())); - - let cluster_rate = next_tx.cluster_rate(); - - for (txid, _, _) in &package { - cluster.push(*txid); - if let Some(Some(tx)) = audit_pool.get_mut(*txid as usize) { - tx.used = true; - tx.set_dirty_if_different(cluster_rate); - transactions.push(tx.uid); - block_weight += tx.weight; - block_sigops += tx.sigops; - } - update_descendants(*txid, &mut audit_pool, &mut modified, cluster_rate); + if from_stack { + mempool_stack.pop(); + } else { + modified.pop(); } - if is_cluster { - clusters.push(cluster); - } + if blocks.len() < (MAX_BLOCKS - 1) + && ((block_weight + (4 * next_tx.ancestor_sigop_adjusted_vsize()) + >= MAX_BLOCK_WEIGHT_UNITS) + || (block_sigops + next_tx.ancestor_sigops() > BLOCK_SIGOPS)) + { + // hold this package in an overflow list while we check for smaller options + overflow.push(next_tx.uid); + failures += 1; + } else { + let mut package: Vec<(u32, u32, usize)> = Vec::new(); + let mut cluster: Vec = Vec::new(); + let is_cluster: bool = !next_tx.ancestors.is_empty(); + for ancestor_id in &next_tx.ancestors { + if let Some(Some(ancestor)) = audit_pool.get(*ancestor_id as usize) { + package.push((*ancestor_id, ancestor.order(), ancestor.ancestors.len())); + } + } + package.sort_unstable_by(|a, b| -> Ordering { + if a.2 != b.2 { + // order by ascending ancestor count + a.2.cmp(&b.2) + } else if a.1 != b.1 { + // tie-break by ascending partial txid + a.1.cmp(&b.1) + } else { + // tie-break partial txid collisions by ascending uid + a.0.cmp(&b.0) + } + }); + package.push((next_tx.uid, next_tx.order(), next_tx.ancestors.len())); - failures = 0; + let cluster_rate = next_tx.cluster_rate(); + + for (txid, _, _) in &package { + cluster.push(*txid); + if let Some(Some(tx)) = audit_pool.get_mut(*txid as usize) { + tx.used = true; + tx.set_dirty_if_different(cluster_rate); + transactions.push(tx.uid); + block_weight += tx.weight; + block_sigops += tx.sigops; + } + update_descendants(*txid, &mut audit_pool, &mut modified, cluster_rate); + } + + if is_cluster { + clusters.push(cluster); + } + + failures = 0; + } } // this block is full @@ -203,10 +205,14 @@ pub fn gbt(mempool: &mut ThreadTransactionsMap, accelerations: &[ThreadAccelerat let queue_is_empty = mempool_stack.is_empty() && modified.is_empty(); if (exceeded_package_tries || queue_is_empty) && blocks.len() < (MAX_BLOCKS - 1) { // finalize this block - if !transactions.is_empty() { - blocks.push(transactions); - block_weights.push(block_weight); + if transactions.is_empty() { + info!("trying to push an empty block! breaking loop! mempool {:#?} | modified {:#?} | overflow {:#?}", mempool_stack.len(), modified.len(), overflow.len()); + break; } + + blocks.push(transactions); + block_weights.push(block_weight); + // reset for the next block transactions = Vec::with_capacity(initial_txes_per_block); block_weight = BLOCK_RESERVED_WEIGHT; @@ -265,6 +271,7 @@ pub fn gbt(mempool: &mut ThreadTransactionsMap, accelerations: &[ThreadAccelerat block_weights, clusters, rates, + overflow, } } diff --git a/backend/rust-gbt/src/lib.rs b/backend/rust-gbt/src/lib.rs index 53db0ba21..edc9714ee 100644 --- a/backend/rust-gbt/src/lib.rs +++ b/backend/rust-gbt/src/lib.rs @@ -133,6 +133,7 @@ pub struct GbtResult { pub block_weights: Vec, pub clusters: Vec>, pub rates: Vec>, // Tuples not supported. u32 fits inside f64 + pub overflow: Vec, } /// All on another thread, this runs an arbitrary task in between diff --git a/backend/src/__fixtures__/mempool-config.template.json b/backend/src/__fixtures__/mempool-config.template.json index 1b6c8d411..26ae6fb28 100644 --- a/backend/src/__fixtures__/mempool-config.template.json +++ b/backend/src/__fixtures__/mempool-config.template.json @@ -1,9 +1,11 @@ { "MEMPOOL": { "ENABLED": true, + "OFFICIAL": false, "NETWORK": "__MEMPOOL_NETWORK__", "BACKEND": "__MEMPOOL_BACKEND__", "BLOCKS_SUMMARIES_INDEXING": true, + "GOGGLES_INDEXING": false, "HTTP_PORT": 1, "SPAWN_CLUSTER_PROCS": 2, "API_URL_PREFIX": "__MEMPOOL_API_URL_PREFIX__", @@ -34,14 +36,17 @@ "DISK_CACHE_BLOCK_INTERVAL": 999, "MAX_PUSH_TX_SIZE_WEIGHT": 4000000, "ALLOW_UNREACHABLE": true, - "PRICE_UPDATES_PER_HOUR": 1 + "PRICE_UPDATES_PER_HOUR": 1, + "MAX_TRACKED_ADDRESSES": 1 }, "CORE_RPC": { "HOST": "__CORE_RPC_HOST__", "PORT": 15, "USERNAME": "__CORE_RPC_USERNAME__", "PASSWORD": "__CORE_RPC_PASSWORD__", - "TIMEOUT": 1000 + "TIMEOUT": 1000, + "COOKIE": false, + "COOKIE_PATH": "__CORE_RPC_COOKIE_PATH__" }, "ELECTRUM": { "HOST": "__ELECTRUM_HOST__", @@ -51,7 +56,10 @@ "ESPLORA": { "REST_API_URL": "__ESPLORA_REST_API_URL__", "UNIX_SOCKET_PATH": "__ESPLORA_UNIX_SOCKET_PATH__", + "BATCH_QUERY_BASE_SIZE": 1000, "RETRY_UNIX_SOCKET_AFTER": 888, + "REQUEST_TIMEOUT": 10000, + "FALLBACK_TIMEOUT": 5000, "FALLBACK": [] }, "SECOND_CORE_RPC": { @@ -59,7 +67,9 @@ "PORT": 17, "USERNAME": "__SECOND_CORE_RPC_USERNAME__", "PASSWORD": "__SECOND_CORE_RPC_PASSWORD__", - "TIMEOUT": 2000 + "TIMEOUT": 2000, + "COOKIE": false, + "COOKIE_PATH": "__SECOND_CORE_RPC_COOKIE_PATH__" }, "DATABASE": { "ENABLED": false, @@ -69,7 +79,9 @@ "DATABASE": "__DATABASE_DATABASE__", "USERNAME": "__DATABASE_USERNAME__", "PASSWORD": "__DATABASE_PASSWORD__", - "TIMEOUT": 3000 + "PID_DIR": "__DATABASE_PID_FILE__", + "TIMEOUT": 3000, + "POOL_SIZE": 100 }, "SYSLOG": { "ENABLED": false, @@ -133,6 +145,7 @@ }, "REDIS": { "ENABLED": false, - "UNIX_SOCKET_PATH": "/tmp/redis.sock" + "UNIX_SOCKET_PATH": "/tmp/redis.sock", + "BATCH_QUERY_BASE_SIZE": 5000 } } diff --git a/backend/src/__tests__/api/difficulty-adjustment.test.ts b/backend/src/__tests__/api/difficulty-adjustment.test.ts index c3e8e1a88..a365d3429 100644 --- a/backend/src/__tests__/api/difficulty-adjustment.test.ts +++ b/backend/src/__tests__/api/difficulty-adjustment.test.ts @@ -11,9 +11,35 @@ describe('Mempool Difficulty Adjustment', () => { }; const vectors = [ - [ // Vector 1 + [ // Vector 1 (normal adjustment) + [ // Inputs + dt('2024-02-02T15:42:06.000Z'), // Last DA time (in seconds) + dt('2024-02-08T14:43:05.000Z'), // timestamp of 504 blocks ago (in seconds) + dt('2024-02-11T22:43:01.000Z'), // Current time (now) (in seconds) + 830027, // Current block height + 7.333505241141637, // Previous retarget % (Passed through) + 'mainnet', // Network (if testnet, next value is non-zero) + 0, // Latest block timestamp in seconds (only used if difficulty already locked in) + ], + { // Expected Result + progressPercent: 71.97420634920636, + difficultyChange: 8.512745140778843, + estimatedRetargetDate: 1708004001715, + remainingBlocks: 565, + remainingTime: 312620715, + previousRetarget: 7.333505241141637, + previousTime: 1706888526, + nextRetargetHeight: 830592, + timeAvg: 553311, + adjustedTimeAvg: 553311, + timeOffset: 0, + expectedBlocks: 1338.0916666666667, + }, + ], + [ // Vector 2 (within quarter-epoch overlap) [ // Inputs dt('2022-08-18T11:07:00.000Z'), // Last DA time (in seconds) + dt('2022-08-16T03:16:54.000Z'), // timestamp of 504 blocks ago (in seconds) dt('2022-08-19T14:03:53.000Z'), // Current time (now) (in seconds) 750134, // Current block height 0.6280047707459726, // Previous retarget % (Passed through) @@ -22,21 +48,23 @@ describe('Mempool Difficulty Adjustment', () => { ], { // Expected Result progressPercent: 9.027777777777777, - difficultyChange: 13.180707740199772, - estimatedRetargetDate: 1661895424692, + difficultyChange: 1.0420538959004633, + estimatedRetargetDate: 1662009048328, remainingBlocks: 1834, - remainingTime: 977591692, + remainingTime: 1091215328, previousRetarget: 0.6280047707459726, previousTime: 1660820820, nextRetargetHeight: 751968, timeAvg: 533038, + adjustedTimeAvg: 594992, timeOffset: 0, expectedBlocks: 161.68833333333333, }, ], - [ // Vector 2 (testnet) + [ // Vector 3 (testnet) [ // Inputs dt('2022-08-18T11:07:00.000Z'), // Last DA time (in seconds) + dt('2022-08-16T03:16:54.000Z'), // timestamp of 504 blocks ago (in seconds) dt('2022-08-19T14:03:53.000Z'), // Current time (now) (in seconds) 750134, // Current block height 0.6280047707459726, // Previous retarget % (Passed through) @@ -45,22 +73,24 @@ describe('Mempool Difficulty Adjustment', () => { ], { // Expected Result is same other than timeOffset progressPercent: 9.027777777777777, - difficultyChange: 13.180707740199772, - estimatedRetargetDate: 1661895424692, + difficultyChange: 1.0420538959004633, + estimatedRetargetDate: 1662009048328, remainingBlocks: 1834, - remainingTime: 977591692, + remainingTime: 1091215328, previousTime: 1660820820, previousRetarget: 0.6280047707459726, nextRetargetHeight: 751968, timeAvg: 533038, + adjustedTimeAvg: 594992, timeOffset: -667000, // 11 min 7 seconds since last block (testnet only) // If we add time avg to abs(timeOffset) it makes exactly 1200000 ms, or 20 minutes expectedBlocks: 161.68833333333333, }, ], - [ // Vector 3 (mainnet lock-in (epoch ending 788255)) + [ // Vector 4 (mainnet lock-in (epoch ending 788255)) [ // Inputs dt('2023-04-20T09:57:33.000Z'), // Last DA time (in seconds) + dt('2022-08-16T03:16:54.000Z'), // timestamp of 504 blocks ago (in seconds) dt('2023-05-04T14:54:09.000Z'), // Current time (now) (in seconds) 788255, // Current block height 1.7220298879531821, // Previous retarget % (Passed through) @@ -77,16 +107,17 @@ describe('Mempool Difficulty Adjustment', () => { previousTime: 1681984653, nextRetargetHeight: 788256, timeAvg: 609129, + adjustedTimeAvg: 609129, timeOffset: 0, expectedBlocks: 2045.66, }, ], - ] as [[number, number, number, number, string, number], DifficultyAdjustment][]; + ] as [[number, number, number, number, number, string, number], DifficultyAdjustment][]; for (const vector of vectors) { const result = calcDifficultyAdjustment(...vector[0]); // previousRetarget is passed through untouched - expect(result.previousRetarget).toStrictEqual(vector[0][3]); + expect(result.previousRetarget).toStrictEqual(vector[0][4]); expect(result).toStrictEqual(vector[1]); } }); diff --git a/backend/src/__tests__/config.test.ts b/backend/src/__tests__/config.test.ts index 8097a2465..5066e0ef7 100644 --- a/backend/src/__tests__/config.test.ts +++ b/backend/src/__tests__/config.test.ts @@ -14,9 +14,11 @@ describe('Mempool Backend Config', () => { expect(config.MEMPOOL).toStrictEqual({ ENABLED: true, + OFFICIAL: false, NETWORK: 'mainnet', BACKEND: 'none', BLOCKS_SUMMARIES_INDEXING: false, + GOGGLES_INDEXING: false, HTTP_PORT: 8999, SPAWN_CLUSTER_PROCS: 0, API_URL_PREFIX: '/api/v1/', @@ -48,6 +50,7 @@ describe('Mempool Backend Config', () => { MAX_PUSH_TX_SIZE_WEIGHT: 400000, ALLOW_UNREACHABLE: true, PRICE_UPDATES_PER_HOUR: 1, + MAX_TRACKED_ADDRESSES: 1, }); expect(config.ELECTRUM).toStrictEqual({ HOST: '127.0.0.1', PORT: 3306, TLS_ENABLED: true }); @@ -55,7 +58,10 @@ describe('Mempool Backend Config', () => { expect(config.ESPLORA).toStrictEqual({ REST_API_URL: 'http://127.0.0.1:3000', UNIX_SOCKET_PATH: null, + BATCH_QUERY_BASE_SIZE: 1000, RETRY_UNIX_SOCKET_AFTER: 30000, + REQUEST_TIMEOUT: 10000, + FALLBACK_TIMEOUT: 5000, FALLBACK: [], }); @@ -64,7 +70,9 @@ describe('Mempool Backend Config', () => { PORT: 8332, USERNAME: 'mempool', PASSWORD: 'mempool', - TIMEOUT: 60000 + TIMEOUT: 60000, + COOKIE: false, + COOKIE_PATH: '/bitcoin/.cookie' }); expect(config.SECOND_CORE_RPC).toStrictEqual({ @@ -72,7 +80,9 @@ describe('Mempool Backend Config', () => { PORT: 8332, USERNAME: 'mempool', PASSWORD: 'mempool', - TIMEOUT: 60000 + TIMEOUT: 60000, + COOKIE: false, + COOKIE_PATH: '/bitcoin/.cookie' }); expect(config.DATABASE).toStrictEqual({ @@ -84,6 +94,8 @@ describe('Mempool Backend Config', () => { USERNAME: 'mempool', PASSWORD: 'mempool', TIMEOUT: 180000, + PID_DIR: '', + POOL_SIZE: 100, }); expect(config.SYSLOG).toStrictEqual({ @@ -137,7 +149,8 @@ describe('Mempool Backend Config', () => { expect(config.REDIS).toStrictEqual({ ENABLED: false, - UNIX_SOCKET_PATH: '' + UNIX_SOCKET_PATH: '', + BATCH_QUERY_BASE_SIZE: 5000, }); }); }); diff --git a/backend/src/api/acceleration.ts b/backend/src/api/acceleration.ts new file mode 100644 index 000000000..2b032d09f --- /dev/null +++ b/backend/src/api/acceleration.ts @@ -0,0 +1,738 @@ +import logger from '../logger'; +import { MempoolTransactionExtended } from '../mempool.interfaces'; +import { IEsploraApi } from './bitcoin/esplora-api.interface'; + +const BLOCK_WEIGHT_UNITS = 4_000_000; +const BLOCK_SIGOPS = 80_000; +const MAX_RELATIVE_GRAPH_SIZE = 200; +const BID_BOOST_WINDOW = 40_000; +const BID_BOOST_MIN_OFFSET = 10_000; +const BID_BOOST_MAX_OFFSET = 400_000; + +type Acceleration = { + txid: string; + max_bid: number; +}; + +interface TxSummary { + txid: string; // txid of the current transaction + effectiveVsize: number; // Total vsize of the dependency tree + effectiveFee: number; // Total fee of the dependency tree in sats + ancestorCount: number; // Number of ancestors +} + +export interface AccelerationInfo { + txSummary: TxSummary; + targetFeeRate: number; // target fee rate (recommended next block fee, or median fee for mined block) + nextBlockFee: number; // fee in sats required to be in the next block (using recommended next block fee, or median fee for mined block) + cost: number; // additional cost to accelerate ((cost + txSummary.effectiveFee) / txSummary.effectiveVsize) >= targetFeeRate +} + +interface GraphTx { + txid: string; + vsize: number; + weight: number; + fees: { + base: number; + }; + depends: string[]; + spentby: string[]; +} + +interface MempoolTx extends GraphTx { + ancestorcount: number; + ancestorsize: number; + fees: { + base: number; + ancestor: number; + }; + + ancestors: Map, + ancestorRate: number; + individualRate: number; + score: number; +} + +class AccelerationCosts { + /** + * Takes a list of accelerations and verbose block data + * Returns the "fair" boost rate to charge accelerations + * + * @param accelerationsx + * @param verboseBlock + */ + public calculateBoostRate(accelerations: Acceleration[], blockTxs: IEsploraApi.Transaction[]): number { + // Run GBT ourselves to calculate accurate effective fee rates + // the list of transactions comes from a mined block, so we already know everything fits within consensus limits + const template = makeBlockTemplate(blockTxs, accelerations, 1, Infinity, Infinity); + + // initialize working maps for fast tx lookups + const accMap = {}; + const txMap = {}; + for (const acceleration of accelerations) { + accMap[acceleration.txid] = acceleration; + } + for (const tx of template) { + txMap[tx.txid] = tx; + } + + // Identify and exclude accelerated and otherwise prioritized transactions + const excludeMap = {}; + let totalWeight = 0; + let minAcceleratedPackage = Infinity; + let lastEffectiveRate = 0; + // Iterate over the mined template from bottom to top. + // Transactions should appear in ascending order of mining priority. + for (const blockTx of [...blockTxs].reverse()) { + const txid = blockTx.txid; + const tx = txMap[txid]; + totalWeight += tx.weight; + const isAccelerated = accMap[txid] != null; + // If a cluster has a in-band effective fee rate than the previous cluster, + // it must have been prioritized out-of-band (in order to have a higher mining priority) + // so exclude from the analysis. + const isPrioritized = tx.effectiveFeePerVsize < lastEffectiveRate; + if (isPrioritized || isAccelerated) { + let packageWeight = 0; + // exclude this whole CPFP cluster + for (const clusterTxid of tx.cluster) { + packageWeight += txMap[clusterTxid].weight; + if (!excludeMap[clusterTxid]) { + excludeMap[clusterTxid] = true; + } + } + // keep track of the smallest accelerated CPFP cluster for later + if (isAccelerated) { + minAcceleratedPackage = Math.min(minAcceleratedPackage, packageWeight); + } + } + if (!isPrioritized) { + if (!isAccelerated || !lastEffectiveRate) { + lastEffectiveRate = tx.effectiveFeePerVsize; + } + } + } + + // The Bid Boost Rate is calculated by disregarding the bottom X weight units of the block, + // where X is the larger of BID_BOOST_MIN_OFFSET or the smallest accelerated package weight (the "offset"), + // then taking the average fee rate of the following BID_BOOST_WINDOW weight units + // (ignoring accelerated transactions and their ancestors). + // + // Transactions within the offset might pay less than the fair rate due to bin-packing effects + // But the average rate paid by the next chunk of non-accelerated transactions provides a good + // upper bound on the "next best rate" of alternatives to including the accelerated transactions + // (since, if there were any better options, they would have been included instead) + const spareWeight = BLOCK_WEIGHT_UNITS - totalWeight; + const windowOffset = Math.min(Math.max(minAcceleratedPackage, BID_BOOST_MIN_OFFSET, spareWeight), BID_BOOST_MAX_OFFSET); + const leftBound = windowOffset; + const rightBound = windowOffset + BID_BOOST_WINDOW; + let totalFeeInWindow = 0; + let totalWeightInWindow = Math.max(0, spareWeight - leftBound); + let txIndex = blockTxs.length - 1; + for (let offset = spareWeight; offset < BLOCK_WEIGHT_UNITS && txIndex >= 0; txIndex--) { + const txid = blockTxs[txIndex].txid; + const tx = txMap[txid]; + if (excludeMap[txid]) { + // skip prioritized transactions and their ancestors + continue; + } + + const left = offset; + const right = offset + tx.weight; + offset += tx.weight; + if (right < leftBound) { + // not within window yet + continue; + } + if (left > rightBound) { + // past window + break; + } + // count fees for weight units within the window + const overlapLeft = Math.max(leftBound, left); + const overlapRight = Math.min(rightBound, right); + const overlapUnits = overlapRight - overlapLeft; + totalFeeInWindow += (tx.effectiveFeePerVsize * (overlapUnits / 4)); + totalWeightInWindow += overlapUnits; + } + + if (totalWeightInWindow < BID_BOOST_WINDOW) { + // not enough un-prioritized transactions to calculate a fair rate + // just charge everyone their max bids + return Infinity; + } + // Divide the total fee by the size of the BID_BOOST_WINDOW in vbytes + const averageRate = totalFeeInWindow / (BID_BOOST_WINDOW / 4); + return averageRate; + } + + + /** + * Takes an accelerated mined txid and a target rate + * Returns the total vsize, fees and acceleration cost (in sats) of the tx and all same-block ancestors + * + * @param txid + * @param medianFeeRate + */ + public getAccelerationInfo(tx: MempoolTransactionExtended, targetFeeRate: number, transactions: MempoolTransactionExtended[]): AccelerationInfo { + // Get same-block transaction ancestors + const allRelatives = this.getSameBlockRelatives(tx, transactions); + const relativesMap = this.initializeRelatives(allRelatives); + const rootTx = relativesMap.get(tx.txid) as MempoolTx; + + // Calculate cost to boost + return this.calculateAccelerationAncestors(rootTx, relativesMap, targetFeeRate); + } + + /** + * Takes a raw transaction, and builds a graph of same-block relatives, + * and returns as a MempoolTx + * + * @param tx + */ + private getSameBlockRelatives(tx: MempoolTransactionExtended, transactions: MempoolTransactionExtended[]): Map { + const blockTxs = new Map(); // map of txs in this block + const spendMap = new Map(); // map of outpoints to spending txids + for (const tx of transactions) { + blockTxs.set(tx.txid, tx); + for (const vin of tx.vin) { + spendMap.set(`${vin.txid}:${vin.vout}`, tx.txid); + } + } + + const relatives: Map = new Map(); + const stack: string[] = [tx.txid]; + + // build set of same-block ancestors + while (stack.length > 0) { + const nextTxid = stack.pop(); + const nextTx = nextTxid ? blockTxs.get(nextTxid) : null; + if (!nextTx || relatives.has(nextTx.txid)) { + continue; + } + + const mempoolTx = this.convertToGraphTx(nextTx); + + mempoolTx.fees.base = nextTx.fee || 0; + mempoolTx.depends = nextTx.vin.map(vin => vin.txid).filter(inTxid => inTxid && blockTxs.has(inTxid)) as string[]; + mempoolTx.spentby = nextTx.vout.map((vout, index) => spendMap.get(`${nextTx.txid}:${index}`)).filter(outTxid => outTxid && blockTxs.has(outTxid)) as string[]; + + for (const txid of [...mempoolTx.depends, ...mempoolTx.spentby]) { + if (txid) { + stack.push(txid); + } + } + + relatives.set(mempoolTx.txid, mempoolTx); + } + + return relatives; + } + + /** + * Takes a raw transaction and converts it to MempoolTx format + * fee and ancestor data is initialized with dummy/null values + * + * @param tx + */ + private convertToGraphTx(tx: MempoolTransactionExtended): GraphTx { + return { + txid: tx.txid, + vsize: tx.vsize, + weight: tx.weight, + fees: { + base: 0, // dummy + }, + depends: [], // dummy + spentby: [], //dummy + }; + } + + private convertGraphToMempoolTx(tx: GraphTx): MempoolTx { + return { + ...tx, + fees: { + base: tx.fees.base, + ancestor: tx.fees.base, + }, + ancestorcount: 1, + ancestorsize: tx.vsize, + ancestors: new Map(), + ancestorRate: 0, + individualRate: 0, + score: 0, + }; + } + + /** + * Given a root transaction, a list of in-mempool ancestors, and a target fee rate, + * Calculate the minimum set of transactions to fee-bump, their total vsize + fees + * + * @param tx + * @param ancestors + */ + private calculateAccelerationAncestors(tx: MempoolTx, relatives: Map, targetFeeRate: number): AccelerationInfo { + // add root tx to the ancestor map + relatives.set(tx.txid, tx); + + // Check for high-sigop transactions (not supported) + relatives.forEach(entry => { + if (entry.vsize > Math.ceil(entry.weight / 4)) { + throw new Error(`high_sigop_tx`); + } + }); + + // Initialize individual & ancestor fee rates + relatives.forEach(entry => this.setAncestorScores(entry)); + + // Sort by descending ancestor score + let sortedRelatives = Array.from(relatives.values()).sort(this.mempoolComparator); + + let includedInCluster: Map | null = null; + + // While highest score >= targetFeeRate + let maxIterations = MAX_RELATIVE_GRAPH_SIZE; + while (sortedRelatives.length && sortedRelatives[0].score && sortedRelatives[0].score >= targetFeeRate && maxIterations > 0) { + maxIterations--; + // Grab the highest scoring entry + const best = sortedRelatives.shift(); + if (best) { + const cluster = new Map(best.ancestors?.entries() || []); + if (best.ancestors.has(tx.txid)) { + includedInCluster = cluster; + } + cluster.set(best.txid, best); + // Remove this cluster (it already pays over the target rate, so doesn't need to be boosted) + // and update scores, ancestor totals and dependencies for the survivors + this.removeAncestors(cluster, relatives); + + // re-sort + sortedRelatives = Array.from(relatives.values()).sort(this.mempoolComparator); + } + } + + // sanity check for infinite loops / too many ancestors (should never happen) + if (maxIterations <= 0) { + logger.warn(`acceleration dependency calculation failed: calculateAccelerationAncestors loop exceeded ${MAX_RELATIVE_GRAPH_SIZE} iterations, unable to proceed`); + throw new Error('invalid_tx_dependencies'); + } + + let totalFee = Math.round(tx.fees.ancestor * 100_000_000); + + // transaction is already CPFP-d above the target rate by some descendant + if (includedInCluster) { + let clusterSize = 0; + let clusterFee = 0; + includedInCluster.forEach(entry => { + clusterSize += entry.vsize; + clusterFee += (entry.fees.base * 100_000_000); + }); + const clusterRate = clusterFee / clusterSize; + totalFee = Math.ceil(tx.ancestorsize * clusterRate); + } + + // Whatever remains in the accelerated tx's dependencies needs to be boosted to the targetFeeRate + // Cost = (totalVsize * targetFeeRate) - totalFee + return { + txSummary: { + txid: tx.txid, + effectiveVsize: tx.ancestorsize, + effectiveFee: totalFee, + ancestorCount: tx.ancestorcount, + }, + cost: Math.max(0, Math.ceil(tx.ancestorsize * targetFeeRate) - totalFee), + targetFeeRate, + nextBlockFee: Math.ceil(tx.ancestorsize * targetFeeRate), + }; + } + + /** + * Recursively traverses an in-mempool dependency graph, and sets a Map of in-mempool ancestors + * for each transaction. + * + * @param tx + * @param all + */ + private setAncestors(tx: MempoolTx, all: Map, visited: Map>, depth: number = 0): Map { + // sanity check for infinite recursion / too many ancestors (should never happen) + if (depth >= 100) { + logger.warn('acceleration dependency calculation failed: setAncestors reached depth of 100, unable to proceed', `Accelerator`); + throw new Error('invalid_tx_dependencies'); + } + + // initialize the ancestor map for this tx + tx.ancestors = new Map(); + tx.depends.forEach(parentId => { + const parent = all.get(parentId); + if (parent) { + // add the parent + tx.ancestors?.set(parentId, parent); + // check for a cached copy of this parent's ancestors + let ancestors = visited.get(parent.txid); + if (!ancestors) { + // recursively fetch the parent's ancestors + ancestors = this.setAncestors(parent, all, visited, depth + 1); + } + // and add to this tx's map + ancestors.forEach((ancestor, ancestorId) => { + tx.ancestors?.set(ancestorId, ancestor); + }); + } + }); + visited.set(tx.txid, tx.ancestors); + + return tx.ancestors; + } + + /** + * Efficiently sets a Map of in-mempool ancestors for each member of an expanded relative graph + * by running setAncestors on each leaf, and caching intermediate results. + * then initializes ancestor data for each transaction + * + * @param all + */ + private initializeRelatives(all: Map): Map { + const mempoolTxs = new Map(); + all.forEach(entry => { + mempoolTxs.set(entry.txid, this.convertGraphToMempoolTx(entry)); + }); + const visited: Map> = new Map(); + const leaves: MempoolTx[] = Array.from(mempoolTxs.values()).filter(entry => entry.spentby.length === 0); + for (const leaf of leaves) { + this.setAncestors(leaf, mempoolTxs, visited); + } + mempoolTxs.forEach(entry => { + entry.ancestors?.forEach(ancestor => { + entry.ancestorcount++; + entry.ancestorsize += ancestor.vsize; + entry.fees.ancestor += ancestor.fees.base; + }); + this.setAncestorScores(entry); + }); + return mempoolTxs; + } + + /** + * Remove a cluster of transactions from an in-mempool dependency graph + * and update the survivors' scores and ancestors + * + * @param cluster + * @param ancestors + */ + private removeAncestors(cluster: Map, all: Map): void { + // remove + cluster.forEach(tx => { + all.delete(tx.txid); + }); + + // update survivors + all.forEach(tx => { + cluster.forEach(remove => { + if (tx.ancestors?.has(remove.txid)) { + // remove as dependency + tx.ancestors.delete(remove.txid); + tx.depends = tx.depends.filter(parent => parent !== remove.txid); + // update ancestor sizes and fees + tx.ancestorsize -= remove.vsize; + tx.fees.ancestor -= remove.fees.base; + } + }); + // recalculate fee rates + this.setAncestorScores(tx); + }); + } + + /** + * Take a mempool transaction, and set the fee rates and ancestor score + * + * @param tx + */ + private setAncestorScores(tx: MempoolTx): void { + tx.individualRate = (tx.fees.base * 100_000_000) / tx.vsize; + tx.ancestorRate = (tx.fees.ancestor * 100_000_000) / tx.ancestorsize; + tx.score = Math.min(tx.individualRate, tx.ancestorRate); + } + + // Sort by descending score + private mempoolComparator(a, b): number { + return b.score - a.score; + } +} + +export default new AccelerationCosts; + +interface TemplateTransaction { + txid: string; + order: number; + weight: number; + adjustedVsize: number; // sigop-adjusted vsize, rounded up to the nearest integer + sigops: number; + fee: number; + feeDelta: number; + ancestors: string[]; + cluster: string[]; + effectiveFeePerVsize: number; +} + +interface MinerTransaction extends TemplateTransaction { + inputs: string[]; + feePerVsize: number; + relativesSet: boolean; + ancestorMap: Map; + children: Set; + ancestorFee: number; + ancestorVsize: number; + ancestorSigops: number; + score: number; + used: boolean; + modified: boolean; + dependencyRate: number; +} + +/* +* Build a block using an approximation of the transaction selection algorithm from Bitcoin Core +* (see BlockAssembler in https://github.com/bitcoin/bitcoin/blob/master/src/node/miner.cpp) +*/ +function makeBlockTemplate(candidates: IEsploraApi.Transaction[], accelerations: Acceleration[], maxBlocks: number = 8, weightLimit: number = BLOCK_WEIGHT_UNITS, sigopLimit: number = BLOCK_SIGOPS): TemplateTransaction[] { + const auditPool: Map = new Map(); + const mempoolArray: MinerTransaction[] = []; + + candidates.forEach(tx => { + // initializing everything up front helps V8 optimize property access later + const adjustedVsize = Math.ceil(Math.max(tx.weight / 4, 5 * (tx.sigops || 0))); + const feePerVsize = (tx.fee / adjustedVsize); + auditPool.set(tx.txid, { + txid: tx.txid, + order: txidToOrdering(tx.txid), + fee: tx.fee, + feeDelta: 0, + weight: tx.weight, + adjustedVsize, + feePerVsize: feePerVsize, + effectiveFeePerVsize: feePerVsize, + dependencyRate: feePerVsize, + sigops: tx.sigops || 0, + inputs: (tx.vin?.map(vin => vin.txid) || []) as string[], + relativesSet: false, + ancestors: [], + cluster: [], + ancestorMap: new Map(), + children: new Set(), + ancestorFee: 0, + ancestorVsize: 0, + ancestorSigops: 0, + score: 0, + used: false, + modified: false, + }); + mempoolArray.push(auditPool.get(tx.txid) as MinerTransaction); + }); + + // set accelerated effective fee + for (const acceleration of accelerations) { + const tx = auditPool.get(acceleration.txid); + if (tx) { + tx.feeDelta = acceleration.max_bid; + tx.feePerVsize = ((tx.fee + tx.feeDelta) / tx.adjustedVsize); + tx.effectiveFeePerVsize = tx.feePerVsize; + tx.dependencyRate = tx.feePerVsize; + } + } + + // Build relatives graph & calculate ancestor scores + for (const tx of mempoolArray) { + if (!tx.relativesSet) { + setRelatives(tx, auditPool); + } + } + + // Sort by descending ancestor score + mempoolArray.sort(priorityComparator); + + // Build blocks by greedily choosing the highest feerate package + // (i.e. the package rooted in the transaction with the best ancestor score) + const blocks: number[][] = []; + let blockWeight = 0; + let blockSigops = 0; + const transactions: MinerTransaction[] = []; + let modified: MinerTransaction[] = []; + const overflow: MinerTransaction[] = []; + let failures = 0; + while (mempoolArray.length || modified.length) { + // skip invalid transactions + while (mempoolArray[0].used || mempoolArray[0].modified) { + mempoolArray.shift(); + } + + // Select best next package + let nextTx; + const nextPoolTx = mempoolArray[0]; + const nextModifiedTx = modified[0]; + if (nextPoolTx && (!nextModifiedTx || (nextPoolTx.score || 0) > (nextModifiedTx.score || 0))) { + nextTx = nextPoolTx; + mempoolArray.shift(); + } else { + modified.shift(); + if (nextModifiedTx) { + nextTx = nextModifiedTx; + } + } + + if (nextTx && !nextTx?.used) { + // Check if the package fits into this block + if (blocks.length >= (maxBlocks - 1) || ((blockWeight + (4 * nextTx.ancestorVsize) < weightLimit) && (blockSigops + nextTx.ancestorSigops <= sigopLimit))) { + const ancestors: MinerTransaction[] = Array.from(nextTx.ancestorMap.values()); + // sort ancestors by dependency graph (equivalent to sorting by ascending ancestor count) + const sortedTxSet = [...ancestors.sort((a, b) => { return (a.ancestorMap.size || 0) - (b.ancestorMap.size || 0); }), nextTx]; + const clusterTxids = sortedTxSet.map(tx => tx.txid); + const effectiveFeeRate = Math.min(nextTx.dependencyRate || Infinity, nextTx.ancestorFee / nextTx.ancestorVsize); + const used: MinerTransaction[] = []; + while (sortedTxSet.length) { + const ancestor = sortedTxSet.pop(); + if (!ancestor) { + continue; + } + ancestor.used = true; + ancestor.usedBy = nextTx.txid; + // update this tx with effective fee rate & relatives data + if (ancestor.effectiveFeePerVsize !== effectiveFeeRate) { + ancestor.effectiveFeePerVsize = effectiveFeeRate; + } + ancestor.cluster = clusterTxids; + transactions.push(ancestor); + blockWeight += ancestor.weight; + blockSigops += ancestor.sigops; + used.push(ancestor); + } + + // remove these as valid package ancestors for any descendants remaining in the mempool + if (used.length) { + used.forEach(tx => { + modified = updateDescendants(tx, auditPool, modified, effectiveFeeRate); + }); + } + + failures = 0; + } else { + // hold this package in an overflow list while we check for smaller options + overflow.push(nextTx); + failures++; + } + } + + // this block is full + const exceededPackageTries = failures > 1000 && blockWeight > (weightLimit - 4000); + const queueEmpty = !mempoolArray.length && !modified.length; + + if (exceededPackageTries || queueEmpty) { + break; + } + } + + for (const tx of transactions) { + tx.ancestors = Object.values(tx.ancestorMap); + } + + return transactions; +} + +// traverse in-mempool ancestors +// recursion unavoidable, but should be limited to depth < 25 by mempool policy +function setRelatives( + tx: MinerTransaction, + mempool: Map, +): void { + for (const parent of tx.inputs) { + const parentTx = mempool.get(parent); + if (parentTx && !tx.ancestorMap?.has(parent)) { + tx.ancestorMap.set(parent, parentTx); + parentTx.children.add(tx); + // visit each node only once + if (!parentTx.relativesSet) { + setRelatives(parentTx, mempool); + } + parentTx.ancestorMap.forEach((ancestor) => { + tx.ancestorMap.set(ancestor.txid, ancestor); + }); + } + }; + tx.ancestorFee = (tx.fee + tx.feeDelta); + tx.ancestorVsize = tx.adjustedVsize || 0; + tx.ancestorSigops = tx.sigops || 0; + tx.ancestorMap.forEach((ancestor) => { + tx.ancestorFee += (ancestor.fee + ancestor.feeDelta); + tx.ancestorVsize += ancestor.adjustedVsize; + tx.ancestorSigops += ancestor.sigops; + }); + tx.score = tx.ancestorFee / tx.ancestorVsize; + tx.relativesSet = true; +} + +// iterate over remaining descendants, removing the root as a valid ancestor & updating the ancestor score +// avoids recursion to limit call stack depth +function updateDescendants( + rootTx: MinerTransaction, + mempool: Map, + modified: MinerTransaction[], + clusterRate: number, +): MinerTransaction[] { + const descendantSet: Set = new Set(); + // stack of nodes left to visit + const descendants: MinerTransaction[] = []; + let descendantTx: MinerTransaction | undefined; + rootTx.children.forEach(childTx => { + if (!descendantSet.has(childTx)) { + descendants.push(childTx); + descendantSet.add(childTx); + } + }); + while (descendants.length) { + descendantTx = descendants.pop(); + if (descendantTx && descendantTx.ancestorMap && descendantTx.ancestorMap.has(rootTx.txid)) { + // remove tx as ancestor + descendantTx.ancestorMap.delete(rootTx.txid); + descendantTx.ancestorFee -= (rootTx.fee + rootTx.feeDelta); + descendantTx.ancestorVsize -= rootTx.adjustedVsize; + descendantTx.ancestorSigops -= rootTx.sigops; + descendantTx.score = descendantTx.ancestorFee / descendantTx.ancestorVsize; + descendantTx.dependencyRate = descendantTx.dependencyRate ? Math.min(descendantTx.dependencyRate, clusterRate) : clusterRate; + + if (!descendantTx.modified) { + descendantTx.modified = true; + modified.push(descendantTx); + } + + // add this node's children to the stack + descendantTx.children.forEach(childTx => { + // visit each node only once + if (!descendantSet.has(childTx)) { + descendants.push(childTx); + descendantSet.add(childTx); + } + }); + } + } + // return new, resorted modified list + return modified.sort(priorityComparator); +} + +// Used to sort an array of MinerTransactions by descending ancestor score +function priorityComparator(a: MinerTransaction, b: MinerTransaction): number { + if (b.score === a.score) { + // tie-break by txid for stability + return a.order - b.order; + } else { + return b.score - a.score; + } +} + +// returns the most significant 4 bytes of the txid as an integer +function txidToOrdering(txid: string): number { + return parseInt( + txid.substring(62, 64) + + txid.substring(60, 62) + + txid.substring(58, 60) + + txid.substring(56, 58), + 16 + ); +} diff --git a/backend/src/api/audit.ts b/backend/src/api/audit.ts index e78b2796f..0ddfc2cc2 100644 --- a/backend/src/api/audit.ts +++ b/backend/src/api/audit.ts @@ -9,7 +9,7 @@ class Audit { auditBlock(transactions: MempoolTransactionExtended[], projectedBlocks: MempoolBlockWithTransactions[], mempool: { [txId: string]: MempoolTransactionExtended }, useAccelerations: boolean = false) : { censored: string[], added: string[], fresh: string[], sigop: string[], fullrbf: string[], accelerated: string[], score: number, similarity: number } { if (!projectedBlocks?.[0]?.transactionIds || !mempool) { - return { censored: [], added: [], fresh: [], sigop: [], fullrbf: [], accelerated: [], score: 0, similarity: 1 }; + return { censored: [], added: [], fresh: [], sigop: [], fullrbf: [], accelerated: [], score: 1, similarity: 1 }; } const matches: string[] = []; // present in both mined block and template @@ -144,7 +144,12 @@ class Audit { const numCensored = Object.keys(isCensored).length; const numMatches = matches.length - 1; // adjust for coinbase tx - const score = numMatches > 0 ? (numMatches / (numMatches + numCensored)) : 0; + let score = 0; + if (numMatches <= 0 && numCensored <= 0) { + score = 1; + } else if (numMatches > 0) { + score = (numMatches / (numMatches + numCensored)); + } const similarity = projectedWeight ? matchedWeight / projectedWeight : 1; return { diff --git a/backend/src/api/bisq/markets-api.ts b/backend/src/api/bisq/markets-api.ts index 54e0297b7..1b5b93059 100644 --- a/backend/src/api/bisq/markets-api.ts +++ b/backend/src/api/bisq/markets-api.ts @@ -646,7 +646,7 @@ class BisqMarketsApi { case 'year': return strtotime('midnight first day of january', ts); default: - throw new Error('Unsupported interval: ' + interval); + throw new Error('Unsupported interval'); } } diff --git a/backend/src/api/bitcoin/bitcoin-api-abstract-factory.ts b/backend/src/api/bitcoin/bitcoin-api-abstract-factory.ts index c44653a3d..abd4c47a5 100644 --- a/backend/src/api/bitcoin/bitcoin-api-abstract-factory.ts +++ b/backend/src/api/bitcoin/bitcoin-api-abstract-factory.ts @@ -1,10 +1,12 @@ +import { IBitcoinApi } from './bitcoin-api.interface'; import { IEsploraApi } from './esplora-api.interface'; export interface AbstractBitcoinApi { $getRawMempool(): Promise; $getRawTransaction(txId: string, skipConversion?: boolean, addPrevout?: boolean, lazyPrevouts?: boolean): Promise; + $getRawTransactions(txids: string[]): Promise; $getMempoolTransactions(txids: string[]): Promise; - $getAllMempoolTransactions(lastTxid: string); + $getAllMempoolTransactions(lastTxid?: string, max_txs?: number); $getTransactionHex(txId: string): Promise; $getBlockHeightTip(): Promise; $getBlockHashTip(): Promise; @@ -23,8 +25,11 @@ export interface AbstractBitcoinApi { $getOutspend(txId: string, vout: number): Promise; $getOutspends(txId: string): Promise; $getBatchedOutspends(txId: string[]): Promise; + $getBatchedOutspendsInternal(txId: string[]): Promise; + $getOutSpendsByOutpoint(outpoints: { txid: string, vout: number }[]): Promise; startHealthChecks(): void; + getHealthStatus(): HealthCheckHost[]; } export interface BitcoinRpcCredentials { host: string; @@ -32,4 +37,16 @@ export interface BitcoinRpcCredentials { user: string; pass: string; timeout: number; + cookie?: string; +} + +export interface HealthCheckHost { + host: string; + active: boolean; + rtt: number; + latestHeight: number; + socket: boolean; + outOfSync: boolean; + unreachable: boolean; + checked: boolean; } diff --git a/backend/src/api/bitcoin/bitcoin-api.interface.ts b/backend/src/api/bitcoin/bitcoin-api.interface.ts index 3afc22897..e176566d7 100644 --- a/backend/src/api/bitcoin/bitcoin-api.interface.ts +++ b/backend/src/api/bitcoin/bitcoin-api.interface.ts @@ -106,6 +106,7 @@ export namespace IBitcoinApi { address?: string; // (string) bitcoin address addresses?: string[]; // (string) bitcoin addresses pegout_chain?: string; // (string) Elements peg-out chain + pegout_address?: string; // (string) Elements peg-out address pegout_addresses?: string[]; // (string) Elements peg-out addresses }; } diff --git a/backend/src/api/bitcoin/bitcoin-api.ts b/backend/src/api/bitcoin/bitcoin-api.ts index 807baae2e..d19eb06ac 100644 --- a/backend/src/api/bitcoin/bitcoin-api.ts +++ b/backend/src/api/bitcoin/bitcoin-api.ts @@ -1,5 +1,5 @@ import * as bitcoinjs from 'bitcoinjs-lib'; -import { AbstractBitcoinApi } from './bitcoin-api-abstract-factory'; +import { AbstractBitcoinApi, HealthCheckHost } from './bitcoin-api-abstract-factory'; import { IBitcoinApi } from './bitcoin-api.interface'; import { IEsploraApi } from './esplora-api.interface'; import blocks from '../blocks'; @@ -60,11 +60,24 @@ class BitcoinApi implements AbstractBitcoinApi { }); } + async $getRawTransactions(txids: string[]): Promise { + const txs: IEsploraApi.Transaction[] = []; + for (const txid of txids) { + try { + const tx = await this.$getRawTransaction(txid, false, true); + txs.push(tx); + } catch (err) { + // skip failures + } + } + return txs; + } + $getMempoolTransactions(txids: string[]): Promise { throw new Error('Method getMempoolTransactions not supported by the Bitcoin RPC API.'); } - $getAllMempoolTransactions(lastTxid: string): Promise { + $getAllMempoolTransactions(lastTxid?: string, max_txs?: number): Promise { throw new Error('Method getAllMempoolTransactions not supported by the Bitcoin RPC API.'); } @@ -198,6 +211,19 @@ class BitcoinApi implements AbstractBitcoinApi { return outspends; } + async $getBatchedOutspendsInternal(txId: string[]): Promise { + return this.$getBatchedOutspends(txId); + } + + async $getOutSpendsByOutpoint(outpoints: { txid: string, vout: number }[]): Promise { + const outspends: IEsploraApi.Outspend[] = []; + for (const outpoint of outpoints) { + const outspend = await this.$getOutspend(outpoint.txid, outpoint.vout); + outspends.push(outspend); + } + return outspends; + } + $getEstimatedHashrate(blockHeight: number): Promise { // 120 is the default block span in Core return this.bitcoindClient.getNetworkHashPs(120, blockHeight); @@ -356,6 +382,10 @@ class BitcoinApi implements AbstractBitcoinApi { } public startHealthChecks(): void {}; + + public getHealthStatus() { + return []; + } } export default BitcoinApi; diff --git a/backend/src/api/bitcoin/bitcoin-client.ts b/backend/src/api/bitcoin/bitcoin-client.ts index 429638984..e8b30a888 100644 --- a/backend/src/api/bitcoin/bitcoin-client.ts +++ b/backend/src/api/bitcoin/bitcoin-client.ts @@ -8,6 +8,7 @@ const nodeRpcCredentials: BitcoinRpcCredentials = { user: config.CORE_RPC.USERNAME, pass: config.CORE_RPC.PASSWORD, timeout: config.CORE_RPC.TIMEOUT, + cookie: config.CORE_RPC.COOKIE ? config.CORE_RPC.COOKIE_PATH : undefined, }; export default new bitcoin.Client(nodeRpcCredentials); diff --git a/backend/src/api/bitcoin/bitcoin-core.routes.ts b/backend/src/api/bitcoin/bitcoin-core.routes.ts new file mode 100644 index 000000000..7933dc17b --- /dev/null +++ b/backend/src/api/bitcoin/bitcoin-core.routes.ts @@ -0,0 +1,249 @@ +import { Application, NextFunction, Request, Response } from 'express'; +import logger from '../../logger'; +import bitcoinClient from './bitcoin-client'; + +/** + * Define a set of routes used by the accelerator server + * Those routes are not designed to be public + */ +class BitcoinBackendRoutes { + private static tag = 'BitcoinBackendRoutes'; + + public initRoutes(app: Application) { + app + .get('/api/internal/bitcoin-core/' + 'get-mempool-entry', this.disableCache, this.$getMempoolEntry) + .post('/api/internal/bitcoin-core/' + 'decode-raw-transaction', this.disableCache, this.$decodeRawTransaction) + .get('/api/internal/bitcoin-core/' + 'get-raw-transaction', this.disableCache, this.$getRawTransaction) + .post('/api/internal/bitcoin-core/' + 'send-raw-transaction', this.disableCache, this.$sendRawTransaction) + .post('/api/internal/bitcoin-core/' + 'test-mempool-accept', this.disableCache, this.$testMempoolAccept) + .get('/api/internal/bitcoin-core/' + 'get-mempool-ancestors', this.disableCache, this.$getMempoolAncestors) + .get('/api/internal/bitcoin-core/' + 'get-block', this.disableCache, this.$getBlock) + .get('/api/internal/bitcoin-core/' + 'get-block-hash', this.disableCache, this.$getBlockHash) + .get('/api/internal/bitcoin-core/' + 'get-block-count', this.disableCache, this.$getBlockCount) + ; + } + + /** + * Disable caching for bitcoin core routes + * + * @param req + * @param res + * @param next + */ + private disableCache(req: Request, res: Response, next: NextFunction): void { + res.setHeader('Pragma', 'no-cache'); + res.setHeader('Cache-control', 'private, no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'); + res.setHeader('expires', -1); + next(); + } + + /** + * Exeption handler to return proper details to the accelerator server + * + * @param e + * @param fnName + * @param res + */ + private static handleException(e: any, fnName: string, res: Response): void { + if (typeof(e.code) === 'number') { + res.status(400).send(JSON.stringify(e, ['code', 'message'])); + } else { + const err = `exception in ${fnName}. ${e}. Details: ${JSON.stringify(e, ['code', 'message'])}`; + logger.err(err, BitcoinBackendRoutes.tag); + res.status(500).send(err); + } + } + + private async $getMempoolEntry(req: Request, res: Response): Promise { + const txid = req.query.txid; + try { + if (typeof(txid) !== 'string' || txid.length !== 64) { + res.status(400).send(`invalid param txid ${txid}. must be a string of 64 char`); + return; + } + const mempoolEntry = await bitcoinClient.getMempoolEntry(txid); + if (!mempoolEntry) { + res.status(404).send(`no mempool entry found for txid ${txid}`); + return; + } + res.status(200).send(mempoolEntry); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'getMempoolEntry', res); + } + } + + private async $decodeRawTransaction(req: Request, res: Response): Promise { + const rawTx = req.body.rawTx; + try { + if (typeof(rawTx) !== 'string') { + res.status(400).send(`invalid param rawTx ${rawTx}. must be a string`); + return; + } + const decodedTx = await bitcoinClient.decodeRawTransaction(rawTx); + if (!decodedTx) { + res.status(400).send(`unable to decode rawTx ${rawTx}`); + return; + } + res.status(200).send(decodedTx); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'decodeRawTransaction', res); + } + } + + private async $getRawTransaction(req: Request, res: Response): Promise { + const txid = req.query.txid; + const verbose = req.query.verbose; + try { + if (typeof(txid) !== 'string' || txid.length !== 64) { + res.status(400).send(`invalid param txid ${txid}. must be a string of 64 char`); + return; + } + if (typeof(verbose) !== 'string') { + res.status(400).send(`invalid param verbose ${verbose}. must be a string representing an integer`); + return; + } + const verboseNumber = parseInt(verbose, 10); + if (typeof(verboseNumber) !== 'number') { + res.status(400).send(`invalid param verbose ${verbose}. must be a valid integer`); + return; + } + + const decodedTx = await bitcoinClient.getRawTransaction(txid, verboseNumber); + if (!decodedTx) { + res.status(400).send(`unable to get raw transaction for txid ${txid}`); + return; + } + res.status(200).send(decodedTx); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'decodeRawTransaction', res); + } + } + + private async $sendRawTransaction(req: Request, res: Response): Promise { + const rawTx = req.body.rawTx; + try { + if (typeof(rawTx) !== 'string') { + res.status(400).send(`invalid param rawTx ${rawTx}. must be a string`); + return; + } + const txHex = await bitcoinClient.sendRawTransaction(rawTx); + if (!txHex) { + res.status(400).send(`unable to send rawTx ${rawTx}`); + return; + } + res.status(200).send(txHex); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'sendRawTransaction', res); + } + } + + private async $testMempoolAccept(req: Request, res: Response): Promise { + const rawTxs = req.body.rawTxs; + try { + if (typeof(rawTxs) !== 'object') { + res.status(400).send(`invalid param rawTxs ${JSON.stringify(rawTxs)}. must be an array of string`); + return; + } + const txHex = await bitcoinClient.testMempoolAccept(rawTxs); + if (typeof(txHex) !== 'object' || txHex.length === 0) { + res.status(400).send(`testmempoolaccept failed for raw txs ${JSON.stringify(rawTxs)}, got an empty result`); + return; + } + res.status(200).send(txHex); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'testMempoolAccept', res); + } + } + + private async $getMempoolAncestors(req: Request, res: Response): Promise { + const txid = req.query.txid; + const verbose = req.query.verbose; + try { + if (typeof(txid) !== 'string' || txid.length !== 64) { + res.status(400).send(`invalid param txid ${txid}. must be a string of 64 char`); + return; + } + if (typeof(verbose) !== 'string' || (verbose !== 'true' && verbose !== 'false')) { + res.status(400).send(`invalid param verbose ${verbose}. must be a string ('true' | 'false')`); + return; + } + + const ancestors = await bitcoinClient.getMempoolAncestors(txid, verbose === 'true' ? true : false); + if (!ancestors) { + res.status(400).send(`unable to get mempool ancestors for txid ${txid}`); + return; + } + res.status(200).send(ancestors); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'getMempoolAncestors', res); + } + } + + private async $getBlock(req: Request, res: Response): Promise { + const blockHash = req.query.hash; + const verbosity = req.query.verbosity; + try { + if (typeof(blockHash) !== 'string' || blockHash.length !== 64) { + res.status(400).send(`invalid param blockHash ${blockHash}. must be a string of 64 char`); + return; + } + if (typeof(verbosity) !== 'string') { + res.status(400).send(`invalid param verbosity ${verbosity}. must be a string representing an integer`); + return; + } + const verbosityNumber = parseInt(verbosity, 10); + if (typeof(verbosityNumber) !== 'number') { + res.status(400).send(`invalid param verbosity ${verbosity}. must be a valid integer`); + return; + } + + const block = await bitcoinClient.getBlock(blockHash, verbosityNumber); + if (!block) { + res.status(400).send(`unable to get block for block hash ${blockHash}`); + return; + } + res.status(200).send(block); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'getBlock', res); + } + } + + private async $getBlockHash(req: Request, res: Response): Promise { + const blockHeight = req.query.height; + try { + if (typeof(blockHeight) !== 'string') { + res.status(400).send(`invalid param blockHeight ${blockHeight}, must be a string representing an integer`); + return; + } + const blockHeightNumber = parseInt(blockHeight, 10); + if (typeof(blockHeightNumber) !== 'number') { + res.status(400).send(`invalid param blockHeight ${blockHeight}. must be a valid integer`); + return; + } + + const block = await bitcoinClient.getBlockHash(blockHeightNumber); + if (!block) { + res.status(400).send(`unable to get block hash for block height ${blockHeightNumber}`); + return; + } + res.status(200).send(block); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'getBlockHash', res); + } + } + + private async $getBlockCount(req: Request, res: Response): Promise { + try { + const count = await bitcoinClient.getBlockCount(); + if (!count) { + res.status(400).send(`unable to get block count`); + return; + } + res.status(200).send(`${count}`); + } catch (e: any) { + BitcoinBackendRoutes.handleException(e, 'getBlockCount', res); + } + } +} + +export default new BitcoinBackendRoutes \ No newline at end of file diff --git a/backend/src/api/bitcoin/bitcoin-second-client.ts b/backend/src/api/bitcoin/bitcoin-second-client.ts index 7f81a96a0..6ae9cefb0 100644 --- a/backend/src/api/bitcoin/bitcoin-second-client.ts +++ b/backend/src/api/bitcoin/bitcoin-second-client.ts @@ -8,6 +8,7 @@ const nodeRpcCredentials: BitcoinRpcCredentials = { user: config.SECOND_CORE_RPC.USERNAME, pass: config.SECOND_CORE_RPC.PASSWORD, timeout: config.SECOND_CORE_RPC.TIMEOUT, + cookie: config.SECOND_CORE_RPC.COOKIE ? config.SECOND_CORE_RPC.COOKIE_PATH : undefined, }; export default new bitcoin.Client(nodeRpcCredentials); diff --git a/backend/src/api/bitcoin/bitcoin.routes.ts b/backend/src/api/bitcoin/bitcoin.routes.ts index 90a31ecae..4e9a83d2c 100644 --- a/backend/src/api/bitcoin/bitcoin.routes.ts +++ b/backend/src/api/bitcoin/bitcoin.routes.ts @@ -24,7 +24,6 @@ class BitcoinRoutes { public initRoutes(app: Application) { app .get(config.MEMPOOL.API_URL_PREFIX + 'transaction-times', this.getTransactionTimes) - .get(config.MEMPOOL.API_URL_PREFIX + 'outspends', this.$getBatchedOutspends) .get(config.MEMPOOL.API_URL_PREFIX + 'cpfp/:txId', this.$getCpfpInfo) .get(config.MEMPOOL.API_URL_PREFIX + 'difficulty-adjustment', this.getDifficultyChange) .get(config.MEMPOOL.API_URL_PREFIX + 'fees/recommended', this.getRecommendedFees) @@ -112,6 +111,7 @@ class BitcoinRoutes { .get(config.MEMPOOL.API_URL_PREFIX + 'tx/:txId/hex', this.getRawTransaction) .get(config.MEMPOOL.API_URL_PREFIX + 'tx/:txId/status', this.getTransactionStatus) .get(config.MEMPOOL.API_URL_PREFIX + 'tx/:txId/outspends', this.getTransactionOutspends) + .get(config.MEMPOOL.API_URL_PREFIX + 'txs/outspends', this.$getBatchedOutspends) .get(config.MEMPOOL.API_URL_PREFIX + 'block/:hash/header', this.getBlockHeader) .get(config.MEMPOOL.API_URL_PREFIX + 'blocks/tip/hash', this.getBlockTipHash) .get(config.MEMPOOL.API_URL_PREFIX + 'block/:hash/raw', this.getRawBlock) @@ -174,24 +174,20 @@ class BitcoinRoutes { res.json(times); } - private async $getBatchedOutspends(req: Request, res: Response) { - if (!Array.isArray(req.query.txId)) { - res.status(500).send('Not an array'); + private async $getBatchedOutspends(req: Request, res: Response): Promise { + const txids_csv = req.query.txids; + if (!txids_csv || typeof txids_csv !== 'string') { + res.status(500).send('Invalid txids format'); return; } - if (req.query.txId.length > 50) { + const txids = txids_csv.split(','); + if (txids.length > 50) { res.status(400).send('Too many txids requested'); return; } - const txIds: string[] = []; - for (const _txId in req.query.txId) { - if (typeof req.query.txId[_txId] === 'string') { - txIds.push(req.query.txId[_txId].toString()); - } - } try { - const batchedOutspends = await bitcoinApi.$getBatchedOutspends(txIds); + const batchedOutspends = await bitcoinApi.$getBatchedOutspends(txids); res.json(batchedOutspends); } catch (e) { res.status(500).send(e instanceof Error ? e.message : e); @@ -251,7 +247,7 @@ class BitcoinRoutes { private async getTransaction(req: Request, res: Response) { try { - const transaction = await transactionUtils.$getTransactionExtended(req.params.txId, true); + const transaction = await transactionUtils.$getTransactionExtended(req.params.txId, true, false, false, true); res.json(transaction); } catch (e) { let statusCode = 500; @@ -478,7 +474,7 @@ class BitcoinRoutes { } let nextHash = startFromHash; - for (let i = 0; i < 10 && nextHash; i++) { + for (let i = 0; i < 15 && nextHash; i++) { const localBlock = blocks.getBlocks().find((b) => b.id === nextHash); if (localBlock) { returnBlocks.push(localBlock); @@ -577,7 +573,9 @@ class BitcoinRoutes { } try { - const addressData = await bitcoinApi.$getScriptHash(req.params.scripthash); + // electrum expects scripthashes in little-endian + const electrumScripthash = req.params.scripthash.match(/../g)?.reverse().join('') ?? ''; + const addressData = await bitcoinApi.$getScriptHash(electrumScripthash); res.json(addressData); } catch (e) { if (e instanceof Error && e.message && (e.message.indexOf('too long') > 0 || e.message.indexOf('confirmed status') > 0)) { @@ -594,11 +592,13 @@ class BitcoinRoutes { } try { + // electrum expects scripthashes in little-endian + const electrumScripthash = req.params.scripthash.match(/../g)?.reverse().join('') ?? ''; let lastTxId: string = ''; if (req.query.after_txid && typeof req.query.after_txid === 'string') { lastTxId = req.query.after_txid; } - const transactions = await bitcoinApi.$getScriptHashTransactions(req.params.scripthash, lastTxId); + const transactions = await bitcoinApi.$getScriptHashTransactions(electrumScripthash, lastTxId); res.json(transactions); } catch (e) { if (e instanceof Error && e.message && (e.message.indexOf('too long') > 0 || e.message.indexOf('confirmed status') > 0)) { diff --git a/backend/src/api/bitcoin/esplora-api.interface.ts b/backend/src/api/bitcoin/esplora-api.interface.ts index 55abe1d34..0a0960e46 100644 --- a/backend/src/api/bitcoin/esplora-api.interface.ts +++ b/backend/src/api/bitcoin/esplora-api.interface.ts @@ -6,6 +6,7 @@ export namespace IEsploraApi { size: number; weight: number; fee: number; + sigops?: number; vin: Vin[]; vout: Vout[]; status: Status; diff --git a/backend/src/api/bitcoin/esplora-api.ts b/backend/src/api/bitcoin/esplora-api.ts index d6d4327cb..c80a9e18f 100644 --- a/backend/src/api/bitcoin/esplora-api.ts +++ b/backend/src/api/bitcoin/esplora-api.ts @@ -1,24 +1,28 @@ import config from '../../config'; -import axios, { AxiosResponse } from 'axios'; +import axios from 'axios'; import http from 'http'; -import { AbstractBitcoinApi } from './bitcoin-api-abstract-factory'; +import { AbstractBitcoinApi, HealthCheckHost } from './bitcoin-api-abstract-factory'; import { IEsploraApi } from './esplora-api.interface'; import logger from '../../logger'; +import { Common } from '../common'; interface FailoverHost { host: string, rtts: number[], - rtt: number + rtt: number, failures: number, + latestHeight?: number, socket?: boolean, outOfSync?: boolean, unreachable?: boolean, preferred?: boolean, + checked: boolean, } class FailoverRouter { activeHost: FailoverHost; fallbackHost: FailoverHost; + maxHeight: number = 0; hosts: FailoverHost[]; multihost: boolean; pollInterval: number = 60000; @@ -33,6 +37,7 @@ class FailoverRouter { this.hosts = (config.ESPLORA.FALLBACK || []).map(domain => { return { host: domain, + checked: false, rtts: [], rtt: Infinity, failures: 0, @@ -45,6 +50,7 @@ class FailoverRouter { failures: 0, socket: !!config.ESPLORA.UNIX_SOCKET_PATH, preferred: true, + checked: false, }; this.fallbackHost = this.activeHost; this.hosts.unshift(this.activeHost); @@ -73,59 +79,87 @@ class FailoverRouter { clearTimeout(this.pollTimer); } - const results = await Promise.allSettled(this.hosts.map(async (host) => { - if (host.socket) { - return this.pollConnection.get('/blocks/tip/height', { socketPath: host.host, timeout: 5000 }); - } else { - return this.pollConnection.get(host.host + '/blocks/tip/height', { timeout: 5000 }); - } - })); - const maxHeight = results.reduce((max, result) => Math.max(max, result.status === 'fulfilled' ? result.value?.data || 0 : 0), 0); + const start = Date.now(); // update rtts & sync status - for (let i = 0; i < results.length; i++) { - const host = this.hosts[i]; - const result = results[i].status === 'fulfilled' ? (results[i] as PromiseFulfilledResult>).value : null; - if (result) { - const height = result.data; - const rtt = result.config['meta'].rtt; - host.rtts.unshift(rtt); - host.rtts.slice(0, 5); - host.rtt = host.rtts.reduce((acc, l) => acc + l, 0) / host.rtts.length; - if (height == null || isNaN(height) || (maxHeight - height > 2)) { - host.outOfSync = true; + for (const host of this.hosts) { + try { + const result = await (host.socket + ? this.pollConnection.get('/blocks/tip/height', { socketPath: host.host, timeout: config.ESPLORA.FALLBACK_TIMEOUT }) + : this.pollConnection.get(host.host + '/blocks/tip/height', { timeout: config.ESPLORA.FALLBACK_TIMEOUT }) + ); + if (result) { + const height = result.data; + this.maxHeight = Math.max(height, this.maxHeight); + const rtt = result.config['meta'].rtt; + host.rtts.unshift(rtt); + host.rtts.slice(0, 5); + host.rtt = host.rtts.reduce((acc, l) => acc + l, 0) / host.rtts.length; + host.latestHeight = height; + if (height == null || isNaN(height) || (this.maxHeight - height > 2)) { + host.outOfSync = true; + } else { + host.outOfSync = false; + } + host.unreachable = false; } else { - host.outOfSync = false; + host.outOfSync = true; + host.unreachable = true; + host.rtts = []; + host.rtt = Infinity; } - host.unreachable = false; - } else { + } catch (e) { + host.outOfSync = true; host.unreachable = true; + host.rtts = []; + host.rtt = Infinity; } + host.checked = true; + + + // switch if the current host is out of sync or significantly slower than the next best alternative + const rankOrder = this.sortHosts(); + // switch if the current host is out of sync or significantly slower than the next best alternative + if (this.activeHost.outOfSync || this.activeHost.unreachable || (this.activeHost !== rankOrder[0] && rankOrder[0].preferred) || (!this.activeHost.preferred && this.activeHost.rtt > (rankOrder[0].rtt * 2) + 50)) { + if (this.activeHost.unreachable) { + logger.warn(`🚨🚨🚨 Unable to reach ${this.activeHost.host}, failing over to next best alternative 🚨🚨🚨`); + } else if (this.activeHost.outOfSync) { + logger.warn(`🚨🚨🚨 ${this.activeHost.host} has fallen behind, failing over to next best alternative 🚨🚨🚨`); + } else { + logger.debug(`🛠️ ${this.activeHost.host} is no longer the best esplora host 🛠️`); + } + this.electHost(); + } + await Common.sleep$(50); } - this.sortHosts(); + const rankOrder = this.updateFallback(); + logger.debug(`Tomahawk ranking:\n${rankOrder.map((host, index) => this.formatRanking(index, host, this.activeHost, this.maxHeight)).join('\n')}`); - logger.debug(`Tomahawk ranking: ${this.hosts.map(host => '\navg rtt ' + Math.round(host.rtt).toString().padStart(5, ' ') + ' | reachable? ' + (!host.unreachable || false).toString().padStart(5, ' ') + ' | in sync? ' + (!host.outOfSync || false).toString().padStart(5, ' ') + ` | ${host.host}`).join('')}`); + const elapsed = Date.now() - start; - // switch if the current host is out of sync or significantly slower than the next best alternative - if (this.activeHost.outOfSync || this.activeHost.unreachable || (this.activeHost !== this.hosts[0] && this.hosts[0].preferred) || (!this.activeHost.preferred && this.activeHost.rtt > (this.hosts[0].rtt * 2) + 50)) { - if (this.activeHost.unreachable) { - logger.warn(`Unable to reach ${this.activeHost.host}, failing over to next best alternative`); - } else if (this.activeHost.outOfSync) { - logger.warn(`${this.activeHost.host} has fallen behind, failing over to next best alternative`); - } else { - logger.debug(`${this.activeHost.host} is no longer the best esplora host`); - } - this.electHost(); + this.pollTimer = setTimeout(() => { this.pollHosts(); }, Math.max(1, this.pollInterval - elapsed)); + } + + private formatRanking(index: number, host: FailoverHost, active: FailoverHost, maxHeight: number): string { + const heightStatus = !host.checked ? '⏳' : (host.outOfSync ? '🚫' : (host.latestHeight && host.latestHeight < maxHeight ? '🟧' : '✅')); + return `${host === active ? '⭐️' : ' '} ${host.rtt < Infinity ? Math.round(host.rtt).toString().padStart(5, ' ') + 'ms' : ' - '} ${!host.checked ? '⏳' : (host.unreachable ? '🔥' : '✅')} | block: ${host.latestHeight || '??????'} ${heightStatus} | ${host.host} ${host === active ? '⭐️' : ' '}`; + } + + private updateFallback(): FailoverHost[] { + const rankOrder = this.sortHosts(); + if (rankOrder.length > 1 && rankOrder[0] === this.activeHost) { + this.fallbackHost = rankOrder[1]; + } else { + this.fallbackHost = rankOrder[0]; } - - this.pollTimer = setTimeout(() => { this.pollHosts(); }, this.pollInterval); + return rankOrder; } // sort hosts by connection quality, and update default fallback - private sortHosts(): void { + public sortHosts(): FailoverHost[] { // sort by connection quality - this.hosts.sort((a, b) => { + return this.hosts.slice().sort((a, b) => { if ((a.unreachable || a.outOfSync) === (b.unreachable || b.outOfSync)) { if (a.preferred === b.preferred) { // lower rtt is best @@ -137,26 +171,21 @@ class FailoverRouter { return (a.unreachable || a.outOfSync) ? 1 : -1; } }); - if (this.hosts.length > 1 && this.hosts[0] === this.activeHost) { - this.fallbackHost = this.hosts[1]; - } else { - this.fallbackHost = this.hosts[0]; - } } // depose the active host and choose the next best replacement private electHost(): void { this.activeHost.outOfSync = true; this.activeHost.failures = 0; - this.sortHosts(); - this.activeHost = this.hosts[0]; + const rankOrder = this.sortHosts(); + this.activeHost = rankOrder[0]; logger.warn(`Switching esplora host to ${this.activeHost.host}`); } private addFailure(host: FailoverHost): FailoverHost { host.failures++; if (host.failures > 5 && this.multihost) { - logger.warn(`Too many esplora failures on ${this.activeHost.host}, falling back to next best alternative`); + logger.warn(`🚨🚨🚨 Too many esplora failures on ${this.activeHost.host}, falling back to next best alternative 🚨🚨🚨`); this.electHost(); return this.activeHost; } else { @@ -168,12 +197,15 @@ class FailoverRouter { let axiosConfig; let url; if (host.socket) { - axiosConfig = { socketPath: host.host, timeout: 10000, responseType }; + axiosConfig = { socketPath: host.host, timeout: config.ESPLORA.REQUEST_TIMEOUT, responseType }; url = path; } else { - axiosConfig = { timeout: 10000, responseType }; + axiosConfig = { timeout: config.ESPLORA.REQUEST_TIMEOUT, responseType }; url = host.host + path; } + if (data?.params) { + axiosConfig.params = data.params; + } return (method === 'post' ? this.requestConnection.post(url, data, axiosConfig) : this.requestConnection.get(url, axiosConfig) @@ -181,7 +213,8 @@ class FailoverRouter { .catch((e) => { let fallbackHost = this.fallbackHost; if (e?.response?.status !== 404) { - logger.warn(`esplora request failed ${e?.response?.status || 500} ${host.host}${path}`); + logger.warn(`esplora request failed ${e?.response?.status} ${host.host}${path}`); + logger.warn(e instanceof Error ? e.message : e); fallbackHost = this.addFailure(host); } if (retry && e?.code === 'ECONNREFUSED' && this.multihost) { @@ -193,8 +226,8 @@ class FailoverRouter { }); } - public async $get(path, responseType = 'json'): Promise { - return this.$query('get', path, null, responseType); + public async $get(path, responseType = 'json', params: any = null): Promise { + return this.$query('get', path, params ? { params } : null, responseType); } public async $post(path, data: any, responseType = 'json'): Promise { @@ -213,12 +246,16 @@ class ElectrsApi implements AbstractBitcoinApi { return this.failoverRouter.$get('/tx/' + txId); } - async $getMempoolTransactions(txids: string[]): Promise { - return this.failoverRouter.$post('/mempool/txs', txids, 'json'); + async $getRawTransactions(txids: string[]): Promise { + return this.failoverRouter.$post('/internal/txs', txids, 'json'); } - async $getAllMempoolTransactions(lastSeenTxid?: string): Promise { - return this.failoverRouter.$get('/mempool/txs' + (lastSeenTxid ? '/' + lastSeenTxid : '')); + async $getMempoolTransactions(txids: string[]): Promise { + return this.failoverRouter.$post('/internal/mempool/txs', txids, 'json'); + } + + async $getAllMempoolTransactions(lastSeenTxid?: string, max_txs?: number): Promise { + return this.failoverRouter.$get('/internal/mempool/txs' + (lastSeenTxid ? '/' + lastSeenTxid : ''), 'json', max_txs ? { max_txs } : null); } $getTransactionHex(txId: string): Promise { @@ -238,7 +275,7 @@ class ElectrsApi implements AbstractBitcoinApi { } $getTxsForBlock(hash: string): Promise { - return this.failoverRouter.$get('/block/' + hash + '/txs'); + return this.failoverRouter.$get('/internal/block/' + hash + '/txs'); } $getBlockHash(height: number): Promise { @@ -290,18 +327,38 @@ class ElectrsApi implements AbstractBitcoinApi { return this.failoverRouter.$get('/tx/' + txId + '/outspends'); } - async $getBatchedOutspends(txId: string[]): Promise { - const outspends: IEsploraApi.Outspend[][] = []; - for (const tx of txId) { - const outspend = await this.$getOutspends(tx); - outspends.push(outspend); - } - return outspends; + async $getBatchedOutspends(txids: string[]): Promise { + throw new Error('Method not implemented.'); + } + + async $getBatchedOutspendsInternal(txids: string[]): Promise { + return this.failoverRouter.$post('/internal/txs/outspends/by-txid', txids, 'json'); + } + + async $getOutSpendsByOutpoint(outpoints: { txid: string, vout: number }[]): Promise { + return this.failoverRouter.$post('/internal/txs/outspends/by-outpoint', outpoints.map(out => `${out.txid}:${out.vout}`), 'json'); } public startHealthChecks(): void { this.failoverRouter.startHealthChecks(); } + + public getHealthStatus(): HealthCheckHost[] { + if (config.MEMPOOL.OFFICIAL) { + return this.failoverRouter.sortHosts().map(host => ({ + host: host.host, + active: host === this.failoverRouter.activeHost, + rtt: host.rtt, + latestHeight: host.latestHeight || 0, + socket: !!host.socket, + outOfSync: !!host.outOfSync, + unreachable: !!host.unreachable, + checked: !!host.checked, + })); + } else { + return []; + } + } } export default ElectrsApi; diff --git a/backend/src/api/blocks.ts b/backend/src/api/blocks.ts index 73b010b91..28ca38152 100644 --- a/backend/src/api/blocks.ts +++ b/backend/src/api/blocks.ts @@ -2,7 +2,7 @@ import config from '../config'; import bitcoinApi, { bitcoinCoreApi } from './bitcoin/bitcoin-api-factory'; import logger from '../logger'; import memPool from './mempool'; -import { BlockExtended, BlockExtension, BlockSummary, PoolTag, TransactionExtended, TransactionStripped, TransactionMinerInfo, CpfpSummary, MempoolTransactionExtended } from '../mempool.interfaces'; +import { BlockExtended, BlockExtension, BlockSummary, PoolTag, TransactionExtended, TransactionMinerInfo, CpfpSummary, MempoolTransactionExtended, TransactionClassified, BlockAudit } from '../mempool.interfaces'; import { Common } from './common'; import diskCache from './disk-cache'; import transactionUtils from './transaction-utils'; @@ -37,8 +37,10 @@ class Blocks { private currentBits = 0; private lastDifficultyAdjustmentTime = 0; private previousDifficultyRetarget = 0; + private quarterEpochBlockTime: number | null = null; private newBlockCallbacks: ((block: BlockExtended, txIds: string[], transactions: TransactionExtended[]) => void)[] = []; private newAsyncBlockCallbacks: ((block: BlockExtended, txIds: string[], transactions: MempoolTransactionExtended[]) => Promise)[] = []; + private classifyingBlocks: boolean = false; private mainLoopTimeout: number = 120000; @@ -81,6 +83,7 @@ class Blocks { private async $getTransactionsExtended( blockHash: string, blockHeight: number, + blockTime: number, onlyCoinbase: boolean, txIds: string[] | null = null, quiet: boolean = false, @@ -101,6 +104,12 @@ class Blocks { if (!onlyCoinbase) { for (const txid of txIds) { if (mempool[txid]) { + mempool[txid].status = { + confirmed: true, + block_height: blockHeight, + block_hash: blockHash, + block_time: blockTime, + }; transactionMap[txid] = mempool[txid]; foundInMempool++; totalFound++; @@ -194,7 +203,8 @@ class Blocks { txid: tx.txid, vsize: tx.weight / 4, fee: tx.fee ? Math.round(tx.fee * 100000000) : 0, - value: Math.round(tx.vout.reduce((acc, vout) => acc + (vout.value ? vout.value : 0), 0) * 100000000) + value: Math.round(tx.vout.reduce((acc, vout) => acc + (vout.value ? vout.value : 0), 0) * 100000000), + flags: 0, }; }); @@ -207,7 +217,7 @@ class Blocks { public summarizeBlockTransactions(hash: string, transactions: TransactionExtended[]): BlockSummary { return { id: hash, - transactions: Common.stripTransactions(transactions), + transactions: Common.classifyTransactions(transactions), }; } @@ -443,7 +453,9 @@ class Blocks { if (config.MEMPOOL.BACKEND === 'esplora') { const txs = (await bitcoinApi.$getTxsForBlock(block.hash)).map(tx => transactionUtils.extendTransaction(tx)); const cpfpSummary = await this.$indexCPFP(block.hash, block.height, txs); - await this.$getStrippedBlockTransactions(block.hash, true, true, cpfpSummary, block.height); // This will index the block summary + if (cpfpSummary) { + await this.$getStrippedBlockTransactions(block.hash, true, true, cpfpSummary, block.height); // This will index the block summary + } } else { await this.$getStrippedBlockTransactions(block.hash, true, true); // This will index the block summary } @@ -553,6 +565,130 @@ class Blocks { logger.debug(`Indexing block audit details completed`); } + /** + * [INDEXING] Index transaction classification flags for Goggles + */ + public async $classifyBlocks(): Promise { + if (this.classifyingBlocks) { + return; + } + this.classifyingBlocks = true; + + // classification requires an esplora backend + if (!Common.gogglesIndexingEnabled() || config.MEMPOOL.BACKEND !== 'esplora') { + return; + } + + const blockchainInfo = await bitcoinClient.getBlockchainInfo(); + const currentBlockHeight = blockchainInfo.blocks; + + const unclassifiedBlocksList = await BlocksSummariesRepository.$getSummariesWithVersion(0); + const unclassifiedTemplatesList = await BlocksSummariesRepository.$getTemplatesWithVersion(0); + + // nothing to do + if (!unclassifiedBlocksList?.length && !unclassifiedTemplatesList?.length) { + return; + } + + let timer = Date.now(); + let indexedThisRun = 0; + let indexedTotal = 0; + + const minHeight = Math.min( + unclassifiedBlocksList[unclassifiedBlocksList.length - 1]?.height ?? Infinity, + unclassifiedTemplatesList[unclassifiedTemplatesList.length - 1]?.height ?? Infinity, + ); + const numToIndex = Math.max( + unclassifiedBlocksList.length, + unclassifiedTemplatesList.length, + ); + + const unclassifiedBlocks = {}; + const unclassifiedTemplates = {}; + for (const block of unclassifiedBlocksList) { + unclassifiedBlocks[block.height] = block.id; + } + for (const template of unclassifiedTemplatesList) { + unclassifiedTemplates[template.height] = template.id; + } + + logger.debug(`Classifying blocks and templates from #${currentBlockHeight} to #${minHeight}`, logger.tags.goggles); + + for (let height = currentBlockHeight; height >= 0; height--) { + try { + let txs: TransactionExtended[] | null = null; + if (unclassifiedBlocks[height]) { + const blockHash = unclassifiedBlocks[height]; + // fetch transactions + txs = (await bitcoinApi.$getTxsForBlock(blockHash)).map(tx => transactionUtils.extendTransaction(tx)) || []; + // add CPFP + const cpfpSummary = Common.calculateCpfp(height, txs, true); + // classify + const { transactions: classifiedTxs } = this.summarizeBlockTransactions(blockHash, cpfpSummary.transactions); + await BlocksSummariesRepository.$saveTransactions(height, blockHash, classifiedTxs, 1); + await Common.sleep$(250); + } + if (unclassifiedTemplates[height]) { + // classify template + const blockHash = unclassifiedTemplates[height]; + const template = await BlocksSummariesRepository.$getTemplate(blockHash); + const alreadyClassified = template?.transactions?.reduce((classified, tx) => (classified || tx.flags > 0), false); + let classifiedTemplate = template?.transactions || []; + if (!alreadyClassified) { + const templateTxs: (TransactionExtended | TransactionClassified)[] = []; + const blockTxMap: { [txid: string]: TransactionExtended } = {}; + for (const tx of (txs || [])) { + blockTxMap[tx.txid] = tx; + } + for (const templateTx of (template?.transactions || [])) { + let tx: TransactionExtended | null = blockTxMap[templateTx.txid]; + if (!tx) { + try { + tx = await transactionUtils.$getTransactionExtended(templateTx.txid, false, true, false); + } catch (e) { + // transaction probably not found + } + } + templateTxs.push(tx || templateTx); + } + const cpfpSummary = Common.calculateCpfp(height, templateTxs?.filter(tx => tx['effectiveFeePerVsize'] != null) as TransactionExtended[], true); + // classify + const { transactions: classifiedTxs } = this.summarizeBlockTransactions(blockHash, cpfpSummary.transactions); + const classifiedTxMap: { [txid: string]: TransactionClassified } = {}; + for (const tx of classifiedTxs) { + classifiedTxMap[tx.txid] = tx; + } + classifiedTemplate = classifiedTemplate.map(tx => { + if (classifiedTxMap[tx.txid]) { + tx.flags = classifiedTxMap[tx.txid].flags || 0; + } + return tx; + }); + } + await BlocksSummariesRepository.$saveTemplate({ height, template: { id: blockHash, transactions: classifiedTemplate }, version: 1 }); + await Common.sleep$(250); + } + } catch (e) { + logger.warn(`Failed to classify template or block summary at ${height}`, logger.tags.goggles); + } + + // timing & logging + if (unclassifiedBlocks[height] || unclassifiedTemplates[height]) { + indexedThisRun++; + indexedTotal++; + } + const elapsedSeconds = (Date.now() - timer) / 1000; + if (elapsedSeconds > 5) { + const perSecond = indexedThisRun / elapsedSeconds; + logger.debug(`Classified #${height}: ${indexedTotal} / ${numToIndex} blocks (${perSecond.toFixed(1)}/s)`); + timer = Date.now(); + indexedThisRun = 0; + } + } + + this.classifyingBlocks = false; + } + /** * [INDEXING] Index all blocks metadata for the mining dashboard */ @@ -608,7 +744,7 @@ class Blocks { } const blockHash = await bitcoinApi.$getBlockHash(blockHeight); const block: IEsploraApi.Block = await bitcoinApi.$getBlock(blockHash); - const transactions = await this.$getTransactionsExtended(blockHash, block.height, true, null, true); + const transactions = await this.$getTransactionsExtended(blockHash, block.height, block.timestamp, true, null, true); const blockExtended = await this.$getBlockExtended(block, transactions); newlyIndexed++; @@ -648,6 +784,16 @@ class Blocks { } else { this.currentBlockHeight = this.blocks[this.blocks.length - 1].height; } + if (this.currentBlockHeight >= 503) { + try { + const quarterEpochBlockHash = await bitcoinApi.$getBlockHash(this.currentBlockHeight - 503); + const quarterEpochBlock = await bitcoinApi.$getBlock(quarterEpochBlockHash); + this.quarterEpochBlockTime = quarterEpochBlock?.timestamp; + } catch (e) { + this.quarterEpochBlockTime = null; + logger.warn('failed to update last epoch block time: ' + (e instanceof Error ? e.message : e)); + } + } if (blockHeightTip - this.currentBlockHeight > config.MEMPOOL.INITIAL_BLOCKS_AMOUNT * 2) { logger.info(`${blockHeightTip - this.currentBlockHeight} blocks since tip. Fast forwarding to the ${config.MEMPOOL.INITIAL_BLOCKS_AMOUNT} recent blocks`); @@ -701,7 +847,7 @@ class Blocks { const verboseBlock = await bitcoinClient.getBlock(blockHash, 2); const block = BitcoinApi.convertBlock(verboseBlock); const txIds: string[] = verboseBlock.tx.map(tx => tx.txid); - const transactions = await this.$getTransactionsExtended(blockHash, block.height, false, txIds, false, true) as MempoolTransactionExtended[]; + const transactions = await this.$getTransactionsExtended(blockHash, block.height, block.timestamp, false, txIds, false, true) as MempoolTransactionExtended[]; // fill in missing transaction fee data from verboseBlock for (let i = 0; i < transactions.length; i++) { @@ -754,8 +900,13 @@ class Blocks { this.updateTimerProgress(timer, `saved ${this.currentBlockHeight} to database`); if (!fastForwarded) { - const lastestPriceId = await PricesRepository.$getLatestPriceId(); - this.updateTimerProgress(timer, `got latest price id ${this.currentBlockHeight}`); + let lastestPriceId; + try { + lastestPriceId = await PricesRepository.$getLatestPriceId(); + this.updateTimerProgress(timer, `got latest price id ${this.currentBlockHeight}`); + } catch (e) { + logger.debug('failed to fetch latest price id from db: ' + (e instanceof Error ? e.message : e)); + } if (priceUpdater.historyInserted === true && lastestPriceId !== null) { await blocksRepository.$saveBlockPrices([{ height: blockExtended.height, @@ -764,9 +915,7 @@ class Blocks { this.updateTimerProgress(timer, `saved prices for ${this.currentBlockHeight}`); } else { logger.debug(`Cannot save block price for ${blockExtended.height} because the price updater hasnt completed yet. Trying again in 10 seconds.`, logger.tags.mining); - setTimeout(() => { - indexer.runSingleTask('blocksPrices'); - }, 10000); + indexer.scheduleSingleTask('blocksPrices', 10000); } // Save blocks summary for visualization if it's enabled @@ -867,11 +1016,11 @@ class Blocks { return state; } - private updateTimerProgress(state, msg) { + private updateTimerProgress(state, msg): void { state.progress = msg; } - private clearTimer(state) { + private clearTimer(state): void { if (state.timer) { clearTimeout(state.timer); } @@ -890,7 +1039,7 @@ class Blocks { const blockHash = await bitcoinApi.$getBlockHash(height); const block: IEsploraApi.Block = await bitcoinApi.$getBlock(blockHash); - const transactions = await this.$getTransactionsExtended(blockHash, block.height, true); + const transactions = await this.$getTransactionsExtended(blockHash, block.height, block.timestamp, true); const blockExtended = await this.$getBlockExtended(block, transactions); if (Common.indexingEnabled()) { @@ -902,7 +1051,7 @@ class Blocks { public async $indexStaleBlock(hash: string): Promise { const block: IEsploraApi.Block = await bitcoinApi.$getBlock(hash); - const transactions = await this.$getTransactionsExtended(hash, block.height, true); + const transactions = await this.$getTransactionsExtended(hash, block.height, block.timestamp, true); const blockExtended = await this.$getBlockExtended(block, transactions); blockExtended.canonical = await bitcoinApi.$getBlockHash(block.height); @@ -935,7 +1084,7 @@ class Blocks { } public async $getStrippedBlockTransactions(hash: string, skipMemoryCache = false, - skipDBLookup = false, cpfpSummary?: CpfpSummary, blockHeight?: number): Promise + skipDBLookup = false, cpfpSummary?: CpfpSummary, blockHeight?: number): Promise { if (skipMemoryCache === false) { // Check the memory cache @@ -955,23 +1104,33 @@ class Blocks { let height = blockHeight; let summary: BlockSummary; + let summaryVersion = 0; if (cpfpSummary && !Common.isLiquid()) { summary = { id: hash, transactions: cpfpSummary.transactions.map(tx => { + let flags: number = 0; + try { + flags = tx.flags || Common.getTransactionFlags(tx); + } catch (e) { + logger.warn('Failed to classify transaction: ' + (e instanceof Error ? e.message : e)); + } return { txid: tx.txid, fee: tx.fee || 0, vsize: tx.vsize, value: Math.round(tx.vout.reduce((acc, vout) => acc + (vout.value ? vout.value : 0), 0)), - rate: tx.effectiveFeePerVsize + rate: tx.effectiveFeePerVsize, + flags: flags, }; }), }; + summaryVersion = 1; } else { if (config.MEMPOOL.BACKEND === 'esplora') { const txs = (await bitcoinApi.$getTxsForBlock(hash)).map(tx => transactionUtils.extendTransaction(tx)); summary = this.summarizeBlockTransactions(hash, txs); + summaryVersion = 1; } else { // Call Core RPC const block = await bitcoinClient.getBlock(hash, 2); @@ -986,7 +1145,7 @@ class Blocks { // Index the response if needed if (Common.blocksSummariesIndexingEnabled() === true) { - await BlocksSummariesRepository.$saveTransactions(height, hash, summary.transactions); + await BlocksSummariesRepository.$saveTransactions(height, hash, summary.transactions, summaryVersion); } return summary.transactions; @@ -1102,16 +1261,18 @@ class Blocks { if (cleanBlock.fee_amt_percentiles === null) { let summary; + let summaryVersion = 0; if (config.MEMPOOL.BACKEND === 'esplora') { const txs = (await bitcoinApi.$getTxsForBlock(cleanBlock.hash)).map(tx => transactionUtils.extendTransaction(tx)); summary = this.summarizeBlockTransactions(cleanBlock.hash, txs); + summaryVersion = 1; } else { // Call Core RPC const block = await bitcoinClient.getBlock(cleanBlock.hash, 2); summary = this.summarizeBlock(block); } - await BlocksSummariesRepository.$saveTransactions(cleanBlock.height, cleanBlock.hash, summary.transactions); + await BlocksSummariesRepository.$saveTransactions(cleanBlock.height, cleanBlock.hash, summary.transactions, summaryVersion); cleanBlock.fee_amt_percentiles = await BlocksSummariesRepository.$getFeePercentilesByBlockId(cleanBlock.hash); } if (cleanBlock.fee_amt_percentiles !== null) { @@ -1150,7 +1311,7 @@ class Blocks { return blocks; } - public async $getBlockAuditSummary(hash: string): Promise { + public async $getBlockAuditSummary(hash: string): Promise { if (['mainnet', 'testnet', 'signet'].includes(config.MEMPOOL.NETWORK)) { return BlocksAuditsRepository.$getBlockAudit(hash); } else { @@ -1166,11 +1327,15 @@ class Blocks { return this.previousDifficultyRetarget; } + public getQuarterEpochBlockTime(): number | null { + return this.quarterEpochBlockTime; + } + public getCurrentBlockHeight(): number { return this.currentBlockHeight; } - public async $indexCPFP(hash: string, height: number, txs?: TransactionExtended[]): Promise { + public async $indexCPFP(hash: string, height: number, txs?: TransactionExtended[]): Promise { let transactions = txs; if (!transactions) { if (config.MEMPOOL.BACKEND === 'esplora') { @@ -1185,14 +1350,19 @@ class Blocks { } } - const summary = Common.calculateCpfp(height, transactions as TransactionExtended[]); + if (transactions?.length != null) { + const summary = Common.calculateCpfp(height, transactions as TransactionExtended[]); - await this.$saveCpfp(hash, height, summary); + await this.$saveCpfp(hash, height, summary); - const effectiveFeeStats = Common.calcEffectiveFeeStatistics(summary.transactions); - await blocksRepository.$saveEffectiveFeeStats(hash, effectiveFeeStats); + const effectiveFeeStats = Common.calcEffectiveFeeStatistics(summary.transactions); + await blocksRepository.$saveEffectiveFeeStats(hash, effectiveFeeStats); - return summary; + return summary; + } else { + logger.err(`Cannot index CPFP for block ${height} - missing transaction data`); + return null; + } } public async $saveCpfp(hash: string, height: number, cpfpSummary: CpfpSummary): Promise { diff --git a/backend/src/api/common.ts b/backend/src/api/common.ts index b6f8ab657..72178df3e 100644 --- a/backend/src/api/common.ts +++ b/backend/src/api/common.ts @@ -1,9 +1,30 @@ import * as bitcoinjs from 'bitcoinjs-lib'; import { Request } from 'express'; -import { Ancestor, CpfpInfo, CpfpSummary, CpfpCluster, EffectiveFeeStats, MempoolBlockWithTransactions, TransactionExtended, MempoolTransactionExtended, TransactionStripped, WorkingEffectiveFeeStats } from '../mempool.interfaces'; +import { CpfpInfo, CpfpSummary, CpfpCluster, EffectiveFeeStats, MempoolBlockWithTransactions, TransactionExtended, MempoolTransactionExtended, TransactionStripped, WorkingEffectiveFeeStats, TransactionClassified, TransactionFlags } from '../mempool.interfaces'; import config from '../config'; import { NodeSocket } from '../repositories/NodesSocketsRepository'; import { isIP } from 'net'; +import transactionUtils from './transaction-utils'; +import { isPoint } from '../utils/secp256k1'; +import logger from '../logger'; +import { getVarIntLength, opcodes, parseMultisigScript } from '../utils/bitcoin-script'; + +// Bitcoin Core default policy settings +const TX_MAX_STANDARD_VERSION = 2; +const MAX_STANDARD_TX_WEIGHT = 400_000; +const MAX_BLOCK_SIGOPS_COST = 80_000; +const MAX_STANDARD_TX_SIGOPS_COST = (MAX_BLOCK_SIGOPS_COST / 5); +const MIN_STANDARD_TX_NONWITNESS_SIZE = 65; +const MAX_P2SH_SIGOPS = 15; +const MAX_STANDARD_P2WSH_STACK_ITEMS = 100; +const MAX_STANDARD_P2WSH_STACK_ITEM_SIZE = 80; +const MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE = 80; +const MAX_STANDARD_P2WSH_SCRIPT_SIZE = 3600; +const MAX_STANDARD_SCRIPTSIG_SIZE = 1650; +const DUST_RELAY_TX_FEE = 3; +const MAX_OP_RETURN_RELAY = 83; +const DEFAULT_PERMIT_BAREMULTISIG = true; + export class Common { static nativeAssetId = config.MEMPOOL.NETWORK === 'liquidtestnet' ? '144c654344aa716d6f3abcc1ca90e5641e4e2a7f633bc09fe3baf64585819a49' @@ -138,6 +159,376 @@ export class Common { return matches; } + static setSchnorrSighashFlags(flags: bigint, witness: string[]): bigint { + // no witness items + if (!witness?.length) { + return flags; + } + const hasAnnex = witness.length > 1 && witness[witness.length - 1].startsWith('50'); + if (witness?.length === (hasAnnex ? 2 : 1)) { + // keypath spend, signature is the only witness item + if (witness[0].length === 130) { + flags |= this.setSighashFlags(flags, witness[0]); + } else { + flags |= TransactionFlags.sighash_default; + } + } else { + // scriptpath spend, all items except for the script, control block and annex could be signatures + for (let i = 0; i < witness.length - (hasAnnex ? 3 : 2); i++) { + // handle probable signatures + if (witness[i].length === 130) { + flags |= this.setSighashFlags(flags, witness[i]); + } else if (witness[i].length === 128) { + flags |= TransactionFlags.sighash_default; + } + } + } + return flags; + } + + static isDERSig(w: string): boolean { + // heuristic to detect probable DER signatures + return (w.length >= 18 + && w.startsWith('30') // minimum DER signature length is 8 bytes + sighash flag (see https://mempool.space/testnet/tx/c6c232a36395fa338da458b86ff1327395a9afc28c5d2daa4273e410089fd433) + && ['01', '02', '03', '81', '82', '83'].includes(w.slice(-2)) // signature must end with a valid sighash flag + && (w.length === (2 * parseInt(w.slice(2, 4), 16)) + 6) // second byte encodes the combined length of the R and S components + ); + } + + /** + * Validates most standardness rules + * + * returns true early if any standardness rule is violated, otherwise false + * (except for non-mandatory-script-verify-flag and p2sh script evaluation rules which are *not* enforced) + */ + static isNonStandard(tx: TransactionExtended): boolean { + // version + if (tx.version > TX_MAX_STANDARD_VERSION) { + return true; + } + + // tx-size + if (tx.weight > MAX_STANDARD_TX_WEIGHT) { + return true; + } + + // tx-size-small + if (this.getNonWitnessSize(tx) < MIN_STANDARD_TX_NONWITNESS_SIZE) { + return true; + } + + // bad-txns-too-many-sigops + if (tx.sigops && tx.sigops > MAX_STANDARD_TX_SIGOPS_COST) { + return true; + } + + // input validation + for (const vin of tx.vin) { + if (vin.is_coinbase) { + // standardness rules don't apply to coinbase transactions + return false; + } + // scriptsig-size + if ((vin.scriptsig.length / 2) > MAX_STANDARD_SCRIPTSIG_SIZE) { + return true; + } + // scriptsig-not-pushonly + if (vin.scriptsig_asm) { + for (const op of vin.scriptsig_asm.split(' ')) { + if (opcodes[op] && opcodes[op] > opcodes['OP_16']) { + return true; + } + } + } + // bad-txns-nonstandard-inputs + if (vin.prevout?.scriptpubkey_type === 'p2sh') { + // TODO: evaluate script (https://github.com/bitcoin/bitcoin/blob/1ac627c485a43e50a9a49baddce186ee3ad4daad/src/policy/policy.cpp#L177) + // countScriptSigops returns the witness-scaled sigops, so divide by 4 before comparison with MAX_P2SH_SIGOPS + const sigops = (transactionUtils.countScriptSigops(vin.inner_redeemscript_asm) / 4); + if (sigops > MAX_P2SH_SIGOPS) { + return true; + } + } else if (['unknown', 'provably_unspendable', 'empty'].includes(vin.prevout?.scriptpubkey_type || '')) { + return true; + } + // TODO: bad-witness-nonstandard + } + + // output validation + let opreturnCount = 0; + for (const vout of tx.vout) { + // scriptpubkey + if (['unknown', 'provably_unspendable', 'empty'].includes(vout.scriptpubkey_type)) { + // (non-standard output type) + return true; + } else if (vout.scriptpubkey_type === 'multisig') { + if (!DEFAULT_PERMIT_BAREMULTISIG) { + // bare-multisig + return true; + } + const mOfN = parseMultisigScript(vout.scriptpubkey_asm); + if (!mOfN || mOfN.n < 1 || mOfN.n > 3 || mOfN.m < 1 || mOfN.m > mOfN.n) { + // (non-standard bare multisig threshold) + return true; + } + } else if (vout.scriptpubkey_type === 'op_return') { + opreturnCount++; + if ((vout.scriptpubkey.length / 2) > MAX_OP_RETURN_RELAY) { + // over default datacarrier limit + return true; + } + } + // dust + // (we could probably hardcode this for the different output types...) + if (vout.scriptpubkey_type !== 'op_return') { + let dustSize = (vout.scriptpubkey.length / 2); + // add varint length overhead + dustSize += getVarIntLength(dustSize); + // add value size + dustSize += 8; + if (['v0_p2wpkh', 'v0_p2wsh', 'v1_p2tr'].includes(vout.scriptpubkey_type)) { + dustSize += 67; + } else { + dustSize += 148; + } + if (vout.value < (dustSize * DUST_RELAY_TX_FEE)) { + // under minimum output size + console.log(`NON-STANDARD | dust | ${vout.value} | ${dustSize} ${dustSize * DUST_RELAY_TX_FEE} `, tx.txid); + return true; + } + } + } + + // multi-op-return + if (opreturnCount > 1) { + return true; + } + + // TODO: non-mandatory-script-verify-flag + + return false; + } + + static getNonWitnessSize(tx: TransactionExtended): number { + let weight = tx.weight; + let hasWitness = false; + for (const vin of tx.vin) { + if (vin.witness?.length) { + hasWitness = true; + // witness count + weight -= getVarIntLength(vin.witness.length); + for (const witness of vin.witness) { + // witness item size + content + weight -= getVarIntLength(witness.length / 2) + (witness.length / 2); + } + } + } + if (hasWitness) { + // marker & segwit flag + weight -= 2; + } + return Math.ceil(weight / 4); + } + + static setSegwitSighashFlags(flags: bigint, witness: string[]): bigint { + for (const w of witness) { + if (this.isDERSig(w)) { + flags |= this.setSighashFlags(flags, w); + } + } + return flags; + } + + static setLegacySighashFlags(flags: bigint, scriptsig_asm: string): bigint { + for (const item of scriptsig_asm.split(' ')) { + // skip op_codes + if (item.startsWith('OP_')) { + continue; + } + // check pushed data + if (this.isDERSig(item)) { + flags |= this.setSighashFlags(flags, item); + } + } + return flags; + } + + static setSighashFlags(flags: bigint, signature: string): bigint { + switch(signature.slice(-2)) { + case '01': return flags | TransactionFlags.sighash_all; + case '02': return flags | TransactionFlags.sighash_none; + case '03': return flags | TransactionFlags.sighash_single; + case '81': return flags | TransactionFlags.sighash_all | TransactionFlags.sighash_acp; + case '82': return flags | TransactionFlags.sighash_none | TransactionFlags.sighash_acp; + case '83': return flags | TransactionFlags.sighash_single | TransactionFlags.sighash_acp; + default: return flags | TransactionFlags.sighash_default; // taproot only + } + } + + static isBurnKey(pubkey: string): boolean { + return [ + '022222222222222222222222222222222222222222222222222222222222222222', + '033333333333333333333333333333333333333333333333333333333333333333', + '020202020202020202020202020202020202020202020202020202020202020202', + '030303030303030303030303030303030303030303030303030303030303030303', + ].includes(pubkey); + } + + static getTransactionFlags(tx: TransactionExtended): number { + let flags = tx.flags ? BigInt(tx.flags) : 0n; + + // Update variable flags (CPFP, RBF) + if (tx.ancestors?.length) { + flags |= TransactionFlags.cpfp_child; + } + if (tx.descendants?.length) { + flags |= TransactionFlags.cpfp_parent; + } + if (tx.replacement) { + flags |= TransactionFlags.replacement; + } + + // Already processed static flags, no need to do it again + if (tx.flags) { + return Number(flags); + } + + // Process static flags + if (tx.version === 1) { + flags |= TransactionFlags.v1; + } else if (tx.version === 2) { + flags |= TransactionFlags.v2; + } else if (tx.version === 3) { + flags |= TransactionFlags.v3; + } + const reusedInputAddresses: { [address: string ]: number } = {}; + const reusedOutputAddresses: { [address: string ]: number } = {}; + const inValues = {}; + const outValues = {}; + let rbf = false; + for (const vin of tx.vin) { + if (vin.sequence < 0xfffffffe) { + rbf = true; + } + switch (vin.prevout?.scriptpubkey_type) { + case 'p2pk': flags |= TransactionFlags.p2pk; break; + case 'multisig': flags |= TransactionFlags.p2ms; break; + case 'p2pkh': flags |= TransactionFlags.p2pkh; break; + case 'p2sh': flags |= TransactionFlags.p2sh; break; + case 'v0_p2wpkh': flags |= TransactionFlags.p2wpkh; break; + case 'v0_p2wsh': flags |= TransactionFlags.p2wsh; break; + case 'v1_p2tr': { + if (!vin.witness?.length) { + throw new Error('Taproot input missing witness data'); + } + flags |= TransactionFlags.p2tr; + // in taproot, if the last witness item begins with 0x50, it's an annex + const hasAnnex = vin.witness?.[vin.witness.length - 1].startsWith('50'); + // script spends have more than one witness item, not counting the annex (if present) + if (vin.witness.length > (hasAnnex ? 2 : 1)) { + // the script itself is the second-to-last witness item, not counting the annex + const asm = vin.inner_witnessscript_asm || transactionUtils.convertScriptSigAsm(vin.witness[vin.witness.length - (hasAnnex ? 3 : 2)]); + // inscriptions smuggle data within an 'OP_0 OP_IF ... OP_ENDIF' envelope + if (asm?.includes('OP_0 OP_IF')) { + flags |= TransactionFlags.inscription; + } + } + } break; + } + + // sighash flags + if (vin.prevout?.scriptpubkey_type === 'v1_p2tr') { + flags |= this.setSchnorrSighashFlags(flags, vin.witness); + } else if (vin.witness) { + flags |= this.setSegwitSighashFlags(flags, vin.witness); + } else if (vin.scriptsig?.length) { + flags |= this.setLegacySighashFlags(flags, vin.scriptsig_asm || transactionUtils.convertScriptSigAsm(vin.scriptsig)); + } + + if (vin.prevout?.scriptpubkey_address) { + reusedInputAddresses[vin.prevout?.scriptpubkey_address] = (reusedInputAddresses[vin.prevout?.scriptpubkey_address] || 0) + 1; + } + inValues[vin.prevout?.value || Math.random()] = (inValues[vin.prevout?.value || Math.random()] || 0) + 1; + } + if (rbf) { + flags |= TransactionFlags.rbf; + } else { + flags |= TransactionFlags.no_rbf; + } + let hasFakePubkey = false; + for (const vout of tx.vout) { + switch (vout.scriptpubkey_type) { + case 'p2pk': { + flags |= TransactionFlags.p2pk; + // detect fake pubkey (i.e. not a valid DER point on the secp256k1 curve) + hasFakePubkey = hasFakePubkey || !isPoint(vout.scriptpubkey?.slice(2, -2)); + } break; + case 'multisig': { + flags |= TransactionFlags.p2ms; + // detect fake pubkeys (i.e. not valid DER points on the secp256k1 curve) + const asm = vout.scriptpubkey_asm || transactionUtils.convertScriptSigAsm(vout.scriptpubkey); + for (const key of (asm?.split(' ') || [])) { + if (!hasFakePubkey && !key.startsWith('OP_')) { + hasFakePubkey = hasFakePubkey || this.isBurnKey(key) || !isPoint(key); + } + } + } break; + case 'p2pkh': flags |= TransactionFlags.p2pkh; break; + case 'p2sh': flags |= TransactionFlags.p2sh; break; + case 'v0_p2wpkh': flags |= TransactionFlags.p2wpkh; break; + case 'v0_p2wsh': flags |= TransactionFlags.p2wsh; break; + case 'v1_p2tr': flags |= TransactionFlags.p2tr; break; + case 'op_return': flags |= TransactionFlags.op_return; break; + } + if (vout.scriptpubkey_address) { + reusedOutputAddresses[vout.scriptpubkey_address] = (reusedOutputAddresses[vout.scriptpubkey_address] || 0) + 1; + } + outValues[vout.value || Math.random()] = (outValues[vout.value || Math.random()] || 0) + 1; + } + if (hasFakePubkey) { + flags |= TransactionFlags.fake_pubkey; + } + + // fast but bad heuristic to detect possible coinjoins + // (at least 5 inputs and 5 outputs, less than half of which are unique amounts, with no address reuse) + const addressReuse = Object.keys(reusedOutputAddresses).reduce((acc, key) => Math.max(acc, (reusedInputAddresses[key] || 0) + (reusedOutputAddresses[key] || 0)), 0) > 1; + if (!addressReuse && tx.vin.length >= 5 && tx.vout.length >= 5 && (Object.keys(inValues).length + Object.keys(outValues).length) <= (tx.vin.length + tx.vout.length) / 2 ) { + flags |= TransactionFlags.coinjoin; + } + // more than 5:1 input:output ratio + if (tx.vin.length / tx.vout.length >= 5) { + flags |= TransactionFlags.consolidation; + } + // less than 1:5 input:output ratio + if (tx.vin.length / tx.vout.length <= 0.2) { + flags |= TransactionFlags.batch_payout; + } + + if (this.isNonStandard(tx)) { + flags |= TransactionFlags.nonstandard; + } + + return Number(flags); + } + + static classifyTransaction(tx: TransactionExtended): TransactionClassified { + let flags = 0; + try { + flags = Common.getTransactionFlags(tx); + } catch (e) { + logger.warn('Failed to add classification flags to transaction: ' + (e instanceof Error ? e.message : e)); + } + tx.flags = flags; + return { + ...Common.stripTransaction(tx), + flags, + }; + } + + static classifyTransactions(txs: TransactionExtended[]): TransactionClassified[] { + return txs.map(Common.classifyTransaction); + } + static stripTransaction(tx: TransactionExtended): TransactionStripped { return { txid: tx.txid, @@ -150,7 +541,7 @@ export class Common { } static stripTransactions(txs: TransactionExtended[]): TransactionStripped[] { - return txs.map(this.stripTransaction); + return txs.map(Common.stripTransaction); } static sleep$(ms: number): Promise { @@ -286,6 +677,13 @@ export class Common { ); } + static gogglesIndexingEnabled(): boolean { + return ( + Common.blocksSummariesIndexingEnabled() && + config.MEMPOOL.GOGGLES_INDEXING === true + ); + } + static cpfpIndexingEnabled(): boolean { return ( Common.indexingEnabled() && @@ -413,12 +811,12 @@ export class Common { } } - static calculateCpfp(height: number, transactions: TransactionExtended[]): CpfpSummary { + static calculateCpfp(height: number, transactions: TransactionExtended[], saveRelatives: boolean = false): CpfpSummary { const clusters: CpfpCluster[] = []; // list of all cpfp clusters in this block const clusterMap: { [txid: string]: CpfpCluster } = {}; // map transactions to their cpfp cluster let clusterTxs: TransactionExtended[] = []; // working list of elements of the current cluster let ancestors: { [txid: string]: boolean } = {}; // working set of ancestors of the current cluster root - const txMap = {}; + const txMap: { [txid: string]: TransactionExtended } = {}; // initialize the txMap for (const tx of transactions) { txMap[tx.txid] = tx; @@ -488,6 +886,15 @@ export class Common { } } } + if (saveRelatives) { + for (const cluster of clusters) { + cluster.txs.forEach((member, index) => { + txMap[member.txid].descendants = cluster.txs.slice(0, index).reverse(); + txMap[member.txid].ancestors = cluster.txs.slice(index + 1).reverse(); + txMap[member.txid].effectiveFeePerVsize = cluster.effectiveFeePerVsize; + }); + } + } return { transactions, clusters, diff --git a/backend/src/api/database-migration.ts b/backend/src/api/database-migration.ts index b7dc39493..861830226 100644 --- a/backend/src/api/database-migration.ts +++ b/backend/src/api/database-migration.ts @@ -7,7 +7,7 @@ import cpfpRepository from '../repositories/CpfpRepository'; import { RowDataPacket } from 'mysql2'; class DatabaseMigration { - private static currentVersion = 65; + private static currentVersion = 70; private queryTimeout = 3600_000; private statisticsAddedIndexed = false; private uniqueLogs: string[] = []; @@ -553,6 +553,43 @@ class DatabaseMigration { await this.$executeQuery('ALTER TABLE `blocks_audits` ADD accelerated_txs JSON DEFAULT "[]"'); await this.updateToSchemaVersion(65); } + + if (databaseSchemaVersion < 66) { + await this.$executeQuery('ALTER TABLE `statistics` ADD min_fee FLOAT UNSIGNED DEFAULT NULL'); + await this.updateToSchemaVersion(66); + } + + if (databaseSchemaVersion < 67 && isBitcoin === true) { + await this.$executeQuery('ALTER TABLE `blocks_summaries` ADD version INT NOT NULL DEFAULT 0'); + await this.$executeQuery('ALTER TABLE `blocks_summaries` ADD INDEX `version` (`version`)'); + await this.$executeQuery('ALTER TABLE `blocks_templates` ADD version INT NOT NULL DEFAULT 0'); + await this.$executeQuery('ALTER TABLE `blocks_templates` ADD INDEX `version` (`version`)'); + await this.updateToSchemaVersion(67); + } + + if (databaseSchemaVersion < 68 && config.MEMPOOL.NETWORK === "liquid") { + await this.$executeQuery('TRUNCATE TABLE elements_pegs'); + await this.$executeQuery('ALTER TABLE elements_pegs ADD PRIMARY KEY (txid, txindex);'); + await this.$executeQuery(`UPDATE state SET number = 0 WHERE name = 'last_elements_block';`); + // Create the federation_addresses table and add the two Liquid Federation change addresses in + await this.$executeQuery(this.getCreateFederationAddressesTableQuery(), await this.$checkIfTableExists('federation_addresses')); + await this.$executeQuery(`INSERT INTO federation_addresses (bitcoinaddress) VALUES ('bc1qxvay4an52gcghxq5lavact7r6qe9l4laedsazz8fj2ee2cy47tlqff4aj4')`); // Federation change address + await this.$executeQuery(`INSERT INTO federation_addresses (bitcoinaddress) VALUES ('3EiAcrzq1cELXScc98KeCswGWZaPGceT1d')`); // Federation change address + // Create the federation_txos table that uses the federation_addresses table as a foreign key + await this.$executeQuery(this.getCreateFederationTxosTableQuery(), await this.$checkIfTableExists('federation_txos')); + await this.$executeQuery(`INSERT INTO state VALUES('last_bitcoin_block_audit', 0, NULL);`); + await this.updateToSchemaVersion(68); + } + + if (databaseSchemaVersion < 69 && config.MEMPOOL.NETWORK === 'mainnet') { + await this.$executeQuery(this.getCreateAccelerationsTableQuery(), await this.$checkIfTableExists('accelerations')); + await this.updateToSchemaVersion(69); + } + + if (databaseSchemaVersion < 70 && config.MEMPOOL.NETWORK === 'mainnet') { + await this.$executeQuery('ALTER TABLE accelerations MODIFY COLUMN added DATETIME;'); + await this.updateToSchemaVersion(70); + } } /** @@ -800,6 +837,32 @@ class DatabaseMigration { ) ENGINE=InnoDB DEFAULT CHARSET=utf8;`; } + private getCreateFederationAddressesTableQuery(): string { + return `CREATE TABLE IF NOT EXISTS federation_addresses ( + bitcoinaddress varchar(100) NOT NULL, + PRIMARY KEY (bitcoinaddress) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8;`; + } + + private getCreateFederationTxosTableQuery(): string { + return `CREATE TABLE IF NOT EXISTS federation_txos ( + txid varchar(65) NOT NULL, + txindex int(11) NOT NULL, + bitcoinaddress varchar(100) NOT NULL, + amount bigint(20) unsigned NOT NULL, + blocknumber int(11) unsigned NOT NULL, + blocktime int(11) unsigned NOT NULL, + unspent tinyint(1) NOT NULL, + lastblockupdate int(11) unsigned NOT NULL, + lasttimeupdate int(11) unsigned NOT NULL, + pegtxid varchar(65) NOT NULL, + pegindex int(11) NOT NULL, + pegblocktime int(11) unsigned NOT NULL, + PRIMARY KEY (txid, txindex), + FOREIGN KEY (bitcoinaddress) REFERENCES federation_addresses (bitcoinaddress) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8;`; + } + private getCreatePoolsTableQuery(): string { return `CREATE TABLE IF NOT EXISTS pools ( id int(11) NOT NULL AUTO_INCREMENT, @@ -1070,6 +1133,23 @@ class DatabaseMigration { ) ENGINE=InnoDB DEFAULT CHARSET=utf8;`; } + private getCreateAccelerationsTableQuery(): string { + return `CREATE TABLE IF NOT EXISTS accelerations ( + txid varchar(65) NOT NULL, + added datetime NOT NULL, + height int(10) NOT NULL, + pool smallint unsigned NULL, + effective_vsize int(10) NOT NULL, + effective_fee bigint(20) unsigned NOT NULL, + boost_rate float unsigned, + boost_cost bigint(20) unsigned NOT NULL, + PRIMARY KEY (txid), + INDEX (added), + INDEX (height), + INDEX (pool) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8;`; + } + public async $blocksReindexingTruncate(): Promise { logger.warn(`Truncating pools, blocks, hashrates and difficulty_adjustments tables for re-indexing (using '--reindex-blocks'). You can cancel this command within 5 seconds`); await Common.sleep$(5000); diff --git a/backend/src/api/difficulty-adjustment.ts b/backend/src/api/difficulty-adjustment.ts index d93a5f91a..2f3b21029 100644 --- a/backend/src/api/difficulty-adjustment.ts +++ b/backend/src/api/difficulty-adjustment.ts @@ -12,6 +12,7 @@ export interface DifficultyAdjustment { previousTime: number; // Unix time in ms nextRetargetHeight: number; // Block Height timeAvg: number; // Duration of time in ms + adjustedTimeAvg; // Expected block interval with hashrate implied over last 504 blocks timeOffset: number; // (Testnet) Time since last block (cap @ 20min) in ms expectedBlocks: number; // Block count } @@ -80,6 +81,7 @@ export function calcBitsDifference(oldBits: number, newBits: number): number { export function calcDifficultyAdjustment( DATime: number, + quarterEpochTime: number | null, nowSeconds: number, blockHeight: number, previousRetarget: number, @@ -100,8 +102,20 @@ export function calcDifficultyAdjustment( let difficultyChange = 0; let timeAvgSecs = blocksInEpoch ? diffSeconds / blocksInEpoch : BLOCK_SECONDS_TARGET; + let adjustedTimeAvgSecs = timeAvgSecs; + + // for the first 504 blocks of the epoch, calculate the expected avg block interval + // from a sliding window over the last 504 blocks + if (quarterEpochTime && blocksInEpoch < 503) { + const timeLastEpoch = DATime - quarterEpochTime; + const adjustedTimeLastEpoch = timeLastEpoch * (1 + (previousRetarget / 100)); + const adjustedTimeSpan = diffSeconds + adjustedTimeLastEpoch; + adjustedTimeAvgSecs = adjustedTimeSpan / 503; + difficultyChange = (BLOCK_SECONDS_TARGET / (adjustedTimeSpan / 504) - 1) * 100; + } else { + difficultyChange = (BLOCK_SECONDS_TARGET / (actualTimespan / (blocksInEpoch + 1)) - 1) * 100; + } - difficultyChange = (BLOCK_SECONDS_TARGET / (actualTimespan / (blocksInEpoch + 1)) - 1) * 100; // Max increase is x4 (+300%) if (difficultyChange > 300) { difficultyChange = 300; @@ -126,7 +140,8 @@ export function calcDifficultyAdjustment( } const timeAvg = Math.floor(timeAvgSecs * 1000); - const remainingTime = remainingBlocks * timeAvg; + const adjustedTimeAvg = Math.floor(adjustedTimeAvgSecs * 1000); + const remainingTime = remainingBlocks * adjustedTimeAvg; const estimatedRetargetDate = remainingTime + nowSeconds * 1000; return { @@ -139,6 +154,7 @@ export function calcDifficultyAdjustment( previousTime: DATime, nextRetargetHeight, timeAvg, + adjustedTimeAvg, timeOffset, expectedBlocks, }; @@ -155,9 +171,10 @@ class DifficultyAdjustmentApi { return null; } const nowSeconds = Math.floor(new Date().getTime() / 1000); + const quarterEpochBlockTime = blocks.getQuarterEpochBlockTime(); return calcDifficultyAdjustment( - DATime, nowSeconds, blockHeight, previousRetarget, + DATime, quarterEpochBlockTime, nowSeconds, blockHeight, previousRetarget, config.MEMPOOL.NETWORK, latestBlock.timestamp ); } diff --git a/backend/src/api/disk-cache.ts b/backend/src/api/disk-cache.ts index 6f603489a..202f8f4cb 100644 --- a/backend/src/api/disk-cache.ts +++ b/backend/src/api/disk-cache.ts @@ -252,7 +252,12 @@ class DiskCache { } if (rbfData?.rbf) { - rbfCache.load(rbfData.rbf); + rbfCache.load({ + txs: rbfData.rbf.txs.map(([txid, entry]) => ({ value: entry })), + trees: rbfData.rbf.trees, + expiring: rbfData.rbf.expiring.map(([txid, value]) => ({ key: txid, value })), + mempool: memPool.getMempool(), + }); } } catch (e) { logger.warn('Failed to parse rbf cache. Skipping. Reason: ' + (e instanceof Error ? e.message : e)); diff --git a/backend/src/api/explorer/channels.api.ts b/backend/src/api/explorer/channels.api.ts index 0b1b914fd..2faf06c33 100644 --- a/backend/src/api/explorer/channels.api.ts +++ b/backend/src/api/explorer/channels.api.ts @@ -80,7 +80,13 @@ class ChannelsApi { public async $searchChannelsById(search: string): Promise { try { - const searchStripped = search.replace(/[^0-9x]/g, '') + '%'; + // restrict search to valid id/short_id prefix formats + let searchStripped = search.match(/^[0-9]+[0-9x]*$/)?.[0] || ''; + if (!searchStripped.length) { + return []; + } + // add wildcard to search by prefix + searchStripped += '%'; const query = `SELECT id, short_id, capacity, status FROM channels WHERE id LIKE ? OR short_id LIKE ? LIMIT 10`; const [rows]: any = await DB.query(query, [searchStripped, searchStripped]); return rows; diff --git a/backend/src/api/explorer/nodes.routes.ts b/backend/src/api/explorer/nodes.routes.ts index e2dbcb0b6..3636abe2b 100644 --- a/backend/src/api/explorer/nodes.routes.ts +++ b/backend/src/api/explorer/nodes.routes.ts @@ -42,6 +42,12 @@ class NodesRoutes { switch (config.MEMPOOL.NETWORK) { case 'testnet': nodesList = [ + '0259db43b4e4ac0ff12a805f2d81e521253ba2317f6739bc611d8e2fa156d64256', + '0352b9944b9a52bd2116c91f1ba70c4ef851ac5ba27e1b20f1d92da3ade010dd10', + '03424f5a7601eaa47482cb17100b31a84a04d14fb44b83a57eeceffd8e299878e3', + '032850492ee61a5f7006a2fda6925e4b4ec3782f2b6de2ff0e439ef5a38c3b2470', + '022c80bace98831c44c32fb69755f2b353434e0ee9e7fbda29507f7ef8abea1421', + '02c3559c833e6f99f9ca05fe503e0b4e7524dea9121344edfd3e811101e0c28680', '032c7c7819276c4f706a04df1a0f1e10a5495994a7be4c1d3d28ca766e5a2b957b', '025a7e38c2834dd843591a4d23d5f09cdeb77ddca85f673c2d944a14220ff14cf7', '0395e2731a1673ef21d7a16a727c4fc4d4c35a861c428ce2c819c53d2b81c8bd55', @@ -64,6 +70,12 @@ class NodesRoutes { break; case 'signet': nodesList = [ + '029fe3621fc0c6e08056a14b868f8fb9acca1aa28a129512f6cea0f0d7654d9f92', + '02f60cd7a3a4f1c953dd9554a6ebd51a34f8b10b8124b7fc43a0b381139b55c883', + '03cbbf581774700865eebd1be42d022bc004ba30881274ab304e088a25d70e773d', + '0243348cb3741cfe2d8485fa8375c29c7bc7cbb67577c363cb6987a5e5fd0052cc', + '02cb73e631af44bee600d80f8488a9194c9dc5c7590e575c421a070d1be05bc8e9', + '0306f55ee631aa1e2cd4d9b2bfcbc14404faec5c541cef8b2e6f779061029d09c4', '03ddab321b760433cbf561b615ef62ac7d318630c5f51d523aaf5395b90b751956', '033d92c7bfd213ef1b34c90e985fb5dc77f9ec2409d391492484e57a44c4aca1de', '02ad010dda54253c1eb9efe38b0760657a3b43ecad62198c359c051c9d99d45781', @@ -86,6 +98,12 @@ class NodesRoutes { break; default: nodesList = [ + '02b12b889fe3c943cb05645921040ef13d6d397a2e7a4ad000e28500c505ff26d6', + '0302240ac9d71b39617cbde2764837ec3d6198bd6074b15b75d2ff33108e89d2e1', + '03364a8ace313376e5e4b68c954e287c6388e16df9e9fdbaf0363ecac41105cbf6', + '03229ab4b7f692753e094b93df90530150680f86b535b5183b0cffd75b3df583fc', + '03a696eb7acde991c1be97a58a9daef416659539ae462b897f5e9ae361f990228e', + '0248bf26cf3a63ab8870f34dc0ec9e6c8c6288cdba96ba3f026f34ec0f13ac4055', '03fbc17549ec667bccf397ababbcb4cdc0e3394345e4773079ab2774612ec9be61', '03da9a8623241ccf95f19cd645c6cecd4019ac91570e976eb0a128bebbc4d8a437', '03ca5340cf85cb2e7cf076e489f785410838de174e40be62723e8a60972ad75144', diff --git a/backend/src/api/fee-api.ts b/backend/src/api/fee-api.ts index 82778825e..24fd25a4b 100644 --- a/backend/src/api/fee-api.ts +++ b/backend/src/api/fee-api.ts @@ -1,23 +1,35 @@ import { MempoolBlock } from '../mempool.interfaces'; -import { Common } from './common'; +import config from '../config'; import mempool from './mempool'; import projectedBlocks from './mempool-blocks'; +const isLiquid = config.MEMPOOL.NETWORK === 'liquid' || config.MEMPOOL.NETWORK === 'liquidtestnet'; + +interface RecommendedFees { + fastestFee: number, + halfHourFee: number, + hourFee: number, + economyFee: number, + minimumFee: number, +} + class FeeApi { constructor() { } - defaultFee = Common.isLiquid() ? 0.1 : 1; + defaultFee = isLiquid ? 0.1 : 1; + minimumIncrement = isLiquid ? 0.1 : 1; - public getRecommendedFee() { + public getRecommendedFee(): RecommendedFees { const pBlocks = projectedBlocks.getMempoolBlocks(); const mPool = mempool.getMempoolInfo(); - const minimumFee = Math.ceil(mPool.mempoolminfee * 100000); + const minimumFee = this.roundUpToNearest(mPool.mempoolminfee * 100000, this.minimumIncrement); + const defaultMinFee = Math.max(minimumFee, this.defaultFee); if (!pBlocks.length) { return { - 'fastestFee': this.defaultFee, - 'halfHourFee': this.defaultFee, - 'hourFee': this.defaultFee, + 'fastestFee': defaultMinFee, + 'halfHourFee': defaultMinFee, + 'hourFee': defaultMinFee, 'economyFee': minimumFee, 'minimumFee': minimumFee, }; @@ -27,11 +39,25 @@ class FeeApi { const secondMedianFee = pBlocks[1] ? this.optimizeMedianFee(pBlocks[1], pBlocks[2], firstMedianFee) : this.defaultFee; const thirdMedianFee = pBlocks[2] ? this.optimizeMedianFee(pBlocks[2], pBlocks[3], secondMedianFee) : this.defaultFee; + let fastestFee = Math.max(minimumFee, firstMedianFee); + let halfHourFee = Math.max(minimumFee, secondMedianFee); + let hourFee = Math.max(minimumFee, thirdMedianFee); + const economyFee = Math.max(minimumFee, Math.min(2 * minimumFee, thirdMedianFee)); + + // ensure recommendations always increase w/ priority + fastestFee = Math.max(fastestFee, halfHourFee, hourFee, economyFee); + halfHourFee = Math.max(halfHourFee, hourFee, economyFee); + hourFee = Math.max(hourFee, economyFee); + + // explicitly enforce a minimum of ceil(mempoolminfee) on all recommendations. + // simply rounding up recommended rates is insufficient, as the purging rate + // can exceed the median rate of projected blocks in some extreme scenarios + // (see https://bitcoin.stackexchange.com/a/120024) return { - 'fastestFee': firstMedianFee, - 'halfHourFee': secondMedianFee, - 'hourFee': thirdMedianFee, - 'economyFee': Math.min(2 * minimumFee, thirdMedianFee), + 'fastestFee': fastestFee, + 'halfHourFee': halfHourFee, + 'hourFee': hourFee, + 'economyFee': economyFee, 'minimumFee': minimumFee, }; } @@ -45,7 +71,11 @@ class FeeApi { const multiplier = (pBlock.blockVSize - 500000) / 500000; return Math.max(Math.round(useFee * multiplier), this.defaultFee); } - return Math.ceil(useFee); + return this.roundUpToNearest(useFee, this.minimumIncrement); + } + + private roundUpToNearest(value: number, nearest: number): number { + return Math.ceil(value / nearest) * nearest; } } diff --git a/backend/src/api/lightning/clightning/clightning-convert.ts b/backend/src/api/lightning/clightning/clightning-convert.ts index 55e4bd213..0db60f649 100644 --- a/backend/src/api/lightning/clightning/clightning-convert.ts +++ b/backend/src/api/lightning/clightning/clightning-convert.ts @@ -44,9 +44,13 @@ export enum FeatureBits { KeysendOptional = 55, ScriptEnforcedLeaseRequired = 2022, ScriptEnforcedLeaseOptional = 2023, + SimpleTaprootChannelsRequiredFinal = 80, + SimpleTaprootChannelsOptionalFinal = 81, + SimpleTaprootChannelsRequiredStaging = 180, + SimpleTaprootChannelsOptionalStaging = 181, MaxBolt11Feature = 5114, }; - + export const FeaturesMap = new Map([ [FeatureBits.DataLossProtectRequired, 'data-loss-protect'], [FeatureBits.DataLossProtectOptional, 'data-loss-protect'], @@ -85,6 +89,10 @@ export const FeaturesMap = new Map([ [FeatureBits.ZeroConfOptional, 'zero-conf'], [FeatureBits.ShutdownAnySegwitRequired, 'shutdown-any-segwit'], [FeatureBits.ShutdownAnySegwitOptional, 'shutdown-any-segwit'], + [FeatureBits.SimpleTaprootChannelsRequiredFinal, 'taproot-channels'], + [FeatureBits.SimpleTaprootChannelsOptionalFinal, 'taproot-channels'], + [FeatureBits.SimpleTaprootChannelsRequiredStaging, 'taproot-channels-staging'], + [FeatureBits.SimpleTaprootChannelsOptionalStaging, 'taproot-channels-staging'], ]); /** diff --git a/backend/src/api/liquid/elements-parser.ts b/backend/src/api/liquid/elements-parser.ts index 12439e037..101a03aca 100644 --- a/backend/src/api/liquid/elements-parser.ts +++ b/backend/src/api/liquid/elements-parser.ts @@ -5,8 +5,12 @@ import { Common } from '../common'; import DB from '../../database'; import logger from '../../logger'; +const federationChangeAddresses = ['bc1qxvay4an52gcghxq5lavact7r6qe9l4laedsazz8fj2ee2cy47tlqff4aj4', '3EiAcrzq1cELXScc98KeCswGWZaPGceT1d']; +const auditBlockOffsetWithTip = 1; // Wait for 1 block confirmation before processing the block in the audit process to reduce the risk of reorgs + class ElementsParser { private isRunning = false; + private isUtxosUpdatingRunning = false; constructor() { } @@ -32,12 +36,6 @@ class ElementsParser { } } - public async $getPegDataByMonth(): Promise { - const query = `SELECT SUM(amount) AS amount, DATE_FORMAT(FROM_UNIXTIME(datetime), '%Y-%m-01') AS date FROM elements_pegs GROUP BY DATE_FORMAT(FROM_UNIXTIME(datetime), '%Y%m')`; - const [rows] = await DB.query(query); - return rows; - } - protected async $parseBlock(block: IBitcoinApi.Block) { for (const tx of block.tx) { await this.$parseInputs(tx, block); @@ -55,29 +53,30 @@ class ElementsParser { protected async $parsePegIn(input: IBitcoinApi.Vin, vindex: number, txid: string, block: IBitcoinApi.Block) { const bitcoinTx: IBitcoinApi.Transaction = await bitcoinSecondClient.getRawTransaction(input.txid, true); + const bitcoinBlock: IBitcoinApi.Block = await bitcoinSecondClient.getBlock(bitcoinTx.blockhash); const prevout = bitcoinTx.vout[input.vout || 0]; const outputAddress = prevout.scriptPubKey.address || (prevout.scriptPubKey.addresses && prevout.scriptPubKey.addresses[0]) || ''; await this.$savePegToDatabase(block.height, block.time, prevout.value * 100000000, txid, vindex, - outputAddress, bitcoinTx.txid, prevout.n, 1); + outputAddress, bitcoinTx.txid, prevout.n, bitcoinBlock.height, bitcoinBlock.time, 1); } protected async $parseOutputs(tx: IBitcoinApi.Transaction, block: IBitcoinApi.Block) { for (const output of tx.vout) { if (output.scriptPubKey.pegout_chain) { await this.$savePegToDatabase(block.height, block.time, 0 - output.value * 100000000, tx.txid, output.n, - (output.scriptPubKey.pegout_addresses && output.scriptPubKey.pegout_addresses[0] || ''), '', 0, 0); + (output.scriptPubKey.pegout_address || ''), '', 0, 0, 0, 0); } if (!output.scriptPubKey.pegout_chain && output.scriptPubKey.type === 'nulldata' && output.value && output.value > 0 && output.asset && output.asset === Common.nativeAssetId) { await this.$savePegToDatabase(block.height, block.time, 0 - output.value * 100000000, tx.txid, output.n, - (output.scriptPubKey.pegout_addresses && output.scriptPubKey.pegout_addresses[0] || ''), '', 0, 1); + (output.scriptPubKey.pegout_address || ''), '', 0, 0, 0, 1); } } } protected async $savePegToDatabase(height: number, blockTime: number, amount: number, txid: string, - txindex: number, bitcoinaddress: string, bitcointxid: string, bitcoinindex: number, final_tx: number): Promise { - const query = `INSERT INTO elements_pegs( + txindex: number, bitcoinaddress: string, bitcointxid: string, bitcoinindex: number, bitcoinblock: number, bitcoinBlockTime: number, final_tx: number): Promise { + const query = `INSERT IGNORE INTO elements_pegs( block, datetime, amount, txid, txindex, bitcoinaddress, bitcointxid, bitcoinindex, final_tx ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`; @@ -85,7 +84,22 @@ class ElementsParser { height, blockTime, amount, txid, txindex, bitcoinaddress, bitcointxid, bitcoinindex, final_tx ]; await DB.query(query, params); - logger.debug(`Saved L-BTC peg from block height #${height} with TXID ${txid}.`); + logger.debug(`Saved L-BTC peg from Liquid block height #${height} with TXID ${txid}.`); + + if (amount > 0) { // Peg-in + + // Add the address to the federation addresses table + await DB.query(`INSERT IGNORE INTO federation_addresses (bitcoinaddress) VALUES (?)`, [bitcoinaddress]); + + // Add the UTXO to the federation txos table + const query_utxos = `INSERT IGNORE INTO federation_txos (txid, txindex, bitcoinaddress, amount, blocknumber, blocktime, unspent, lastblockupdate, lasttimeupdate, pegtxid, pegindex, pegblocktime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; + const params_utxos: (string | number)[] = [bitcointxid, bitcoinindex, bitcoinaddress, amount, bitcoinblock, bitcoinBlockTime, 1, bitcoinblock - 1, 0, txid, txindex, blockTime]; + await DB.query(query_utxos, params_utxos); + const [minBlockUpdate] = await DB.query(`SELECT MIN(lastblockupdate) AS lastblockupdate FROM federation_txos WHERE unspent = 1`) + await this.$saveLastBlockAuditToDatabase(minBlockUpdate[0]['lastblockupdate']); + logger.debug(`Saved new Federation UTXO ${bitcointxid}:${bitcoinindex} belonging to ${bitcoinaddress} to federation txos`); + + } } protected async $getLatestBlockHeightFromDatabase(): Promise { @@ -98,6 +112,328 @@ class ElementsParser { const query = `UPDATE state SET number = ? WHERE name = 'last_elements_block'`; await DB.query(query, [blockHeight]); } + + ///////////// FEDERATION AUDIT ////////////// + + public async $updateFederationUtxos() { + if (this.isUtxosUpdatingRunning) { + return; + } + + this.isUtxosUpdatingRunning = true; + + try { + let auditProgress = await this.$getAuditProgress(); + // If no peg in transaction was found in the database, return + if (!auditProgress.lastBlockAudit) { + logger.debug(`No Federation UTXOs found in the database. Waiting for some to be confirmed before starting the Federation UTXOs audit`); + this.isUtxosUpdatingRunning = false; + return; + } + + const bitcoinBlocksToSync = await this.$getBitcoinBlockchainState(); + // If the bitcoin blockchain is not synced yet, return + if (bitcoinBlocksToSync.bitcoinHeaders > bitcoinBlocksToSync.bitcoinBlocks + 1) { + logger.debug(`Bitcoin client is not synced yet. ${bitcoinBlocksToSync.bitcoinHeaders - bitcoinBlocksToSync.bitcoinBlocks} blocks remaining to sync before the Federation audit process can start`); + this.isUtxosUpdatingRunning = false; + return; + } + + auditProgress.lastBlockAudit++; + + // Logging + let indexedThisRun = 0; + let timer = Date.now() / 1000; + const startedAt = Date.now() / 1000; + const indexingSpeeds: number[] = []; + + while (auditProgress.lastBlockAudit <= auditProgress.confirmedTip) { + + // First, get the current UTXOs that need to be scanned in the block + const utxos = await this.$getFederationUtxosToScan(auditProgress.lastBlockAudit); + + // Get the peg-out addresses that need to be scanned + const redeemAddresses = await this.$getRedeemAddressesToScan(); + + // The fast way: check if these UTXOs are still unspent as of the current block with gettxout + let spentAsTip: any[]; + let unspentAsTip: any[]; + if (auditProgress.confirmedTip - auditProgress.lastBlockAudit <= 150) { // If the audit status is not too far in the past, we can use gettxout (fast way) + const utxosToParse = await this.$getFederationUtxosToParse(utxos); + spentAsTip = utxosToParse.spentAsTip; + unspentAsTip = utxosToParse.unspentAsTip; + logger.debug(`Found ${utxos.length} Federation UTXOs and ${redeemAddresses.length} Peg-Out Addresses to scan in Bitcoin block height #${auditProgress.lastBlockAudit} / #${auditProgress.confirmedTip}`); + logger.debug(`${unspentAsTip.length} / ${utxos.length} Federation UTXOs are unspent as of tip`); + } else { // If the audit status is too far in the past, it is useless and wasteful to look for still unspent txos since they will all be spent as of the tip + spentAsTip = utxos; + unspentAsTip = []; + + // Logging + const elapsedSeconds = (Date.now() / 1000) - timer; + if (elapsedSeconds > 5) { + const runningFor = (Date.now() / 1000) - startedAt; + const blockPerSeconds = indexedThisRun / elapsedSeconds; + indexingSpeeds.push(blockPerSeconds); + if (indexingSpeeds.length > 100) indexingSpeeds.shift(); // Keep the length of the up to 100 last indexing speeds + const meanIndexingSpeed = indexingSpeeds.reduce((a, b) => a + b, 0) / indexingSpeeds.length; + const eta = (auditProgress.confirmedTip - auditProgress.lastBlockAudit) / meanIndexingSpeed; + logger.debug(`Scanning ${utxos.length} Federation UTXOs and ${redeemAddresses.length} Peg-Out Addresses at Bitcoin block height #${auditProgress.lastBlockAudit} / #${auditProgress.confirmedTip} | ~${meanIndexingSpeed.toFixed(2)} blocks/sec | elapsed: ${(runningFor / 60).toFixed(0)} minutes | ETA: ${(eta / 60).toFixed(0)} minutes`); + timer = Date.now() / 1000; + indexedThisRun = 0; + } + } + + // The slow way: parse the block to look for the spending tx + const blockHash: IBitcoinApi.ChainTips = await bitcoinSecondClient.getBlockHash(auditProgress.lastBlockAudit); + const block: IBitcoinApi.Block = await bitcoinSecondClient.getBlock(blockHash, 2); + await this.$parseBitcoinBlock(block, spentAsTip, unspentAsTip, auditProgress.confirmedTip, redeemAddresses); + + // Finally, update the lastblockupdate of the remaining UTXOs and save to the database + const [minBlockUpdate] = await DB.query(`SELECT MIN(lastblockupdate) AS lastblockupdate FROM federation_txos WHERE unspent = 1`) + await this.$saveLastBlockAuditToDatabase(minBlockUpdate[0]['lastblockupdate']); + + auditProgress = await this.$getAuditProgress(); + auditProgress.lastBlockAudit++; + indexedThisRun++; + } + + this.isUtxosUpdatingRunning = false; + } catch (e) { + this.isUtxosUpdatingRunning = false; + throw new Error(e instanceof Error ? e.message : 'Error'); + } + } + + // Get the UTXOs that need to be scanned in block height (UTXOs that were last updated in the block height - 1) + protected async $getFederationUtxosToScan(height: number) { + const query = `SELECT txid, txindex, bitcoinaddress, amount FROM federation_txos WHERE lastblockupdate = ? AND unspent = 1`; + const [rows] = await DB.query(query, [height - 1]); + return rows as any[]; + } + + // Returns the UTXOs that are spent as of tip and need to be scanned + protected async $getFederationUtxosToParse(utxos: any[]): Promise { + const spentAsTip: any[] = []; + const unspentAsTip: any[] = []; + + for (const utxo of utxos) { + const result = await bitcoinSecondClient.getTxOut(utxo.txid, utxo.txindex, false); + result ? unspentAsTip.push(utxo) : spentAsTip.push(utxo); + } + + return {spentAsTip, unspentAsTip}; + } + + protected async $parseBitcoinBlock(block: IBitcoinApi.Block, spentAsTip: any[], unspentAsTip: any[], confirmedTip: number, redeemAddressesData: any[] = []) { + const redeemAddresses: string[] = redeemAddressesData.map(redeemAddress => redeemAddress.bitcoinaddress); + for (const tx of block.tx) { + let mightRedeemInThisTx = false; // If a Federation UTXO is spent in this block, we might find a peg-out address in the outputs... + // Check if the Federation UTXOs that was spent as of tip are spent in this block + for (const input of tx.vin) { + const txo = spentAsTip.find(txo => txo.txid === input.txid && txo.txindex === input.vout); + if (txo) { + mightRedeemInThisTx = true; + await DB.query(`UPDATE federation_txos SET unspent = 0, lastblockupdate = ?, lasttimeupdate = ? WHERE txid = ? AND txindex = ?`, [block.height, block.time, txo.txid, txo.txindex]); + // Remove the TXO from the utxo array + spentAsTip.splice(spentAsTip.indexOf(txo), 1); + logger.debug(`Federation UTXO ${txo.txid}:${txo.txindex} (${txo.amount} sats) was spent in block ${block.height}`); + } + } + // Check if an output is sent to a change address of the federation + for (const output of tx.vout) { + if (output.scriptPubKey.address && federationChangeAddresses.includes(output.scriptPubKey.address)) { + // Check that the UTXO was not already added in the DB by previous scans + const [rows_check] = await DB.query(`SELECT txid FROM federation_txos WHERE txid = ? AND txindex = ?`, [tx.txid, output.n]) as any[]; + if (rows_check.length === 0) { + const query_utxos = `INSERT INTO federation_txos (txid, txindex, bitcoinaddress, amount, blocknumber, blocktime, unspent, lastblockupdate, lasttimeupdate, pegtxid, pegindex, pegblocktime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; + const params_utxos: (string | number)[] = [tx.txid, output.n, output.scriptPubKey.address, output.value * 100000000, block.height, block.time, 1, block.height, 0, '', 0, 0]; + await DB.query(query_utxos, params_utxos); + // Add the UTXO to the utxo array + spentAsTip.push({ + txid: tx.txid, + txindex: output.n, + bitcoinaddress: output.scriptPubKey.address, + amount: output.value * 100000000 + }); + logger.debug(`Added new Federation UTXO ${tx.txid}:${output.n} (${output.value * 100000000} sats), change address: ${output.scriptPubKey.address}`); + } + } + if (mightRedeemInThisTx && output.scriptPubKey.address && redeemAddresses.includes(output.scriptPubKey.address)) { + // Find the number of times output.scriptPubKey.address appears in redeemAddresses. There can be address reuse for peg-outs... + const matchingAddress: any[] = redeemAddressesData.filter(redeemAddress => redeemAddress.bitcoinaddress === output.scriptPubKey.address && -redeemAddress.amount === Math.round(output.value * 100000000)); + if (matchingAddress.length > 0) { + if (matchingAddress.length > 1) { + // If there are more than one peg out address with the same amount, we can't know which one redeemed the UTXO: we take the oldest one + matchingAddress.sort((a, b) => a.datetime - b.datetime); + logger.debug(`Found redeem txid ${tx.txid}:${output.n} to peg-out address ${matchingAddress[0].bitcoinaddress}, amount ${matchingAddress[0].amount}, datetime ${matchingAddress[0].datetime}`); + } else { + logger.debug(`Found redeem txid ${tx.txid}:${output.n} to peg-out address ${matchingAddress[0].bitcoinaddress}, amount ${matchingAddress[0].amount}`); + } + const query_add_redeem = `UPDATE elements_pegs SET bitcointxid = ?, bitcoinindex = ? WHERE bitcoinaddress = ? AND amount = ? AND datetime = ?`; + const params_add_redeem: (string | number)[] = [tx.txid, output.n, matchingAddress[0].bitcoinaddress, matchingAddress[0].amount, matchingAddress[0].datetime]; + await DB.query(query_add_redeem, params_add_redeem); + const index = redeemAddressesData.indexOf(matchingAddress[0]); + redeemAddressesData.splice(index, 1); + redeemAddresses.splice(index, 1); + } else { // The output amount does not match the peg-out amount... log it + logger.debug(`Found redeem txid ${tx.txid}:${output.n} to peg-out address ${output.scriptPubKey.address} but output amount ${Math.round(output.value * 100000000)} does not match the peg-out amount!`); + } + } + } + } + + + for (const utxo of spentAsTip) { + await DB.query(`UPDATE federation_txos SET lastblockupdate = ? WHERE txid = ? AND txindex = ?`, [block.height, utxo.txid, utxo.txindex]); + } + + for (const utxo of unspentAsTip) { + await DB.query(`UPDATE federation_txos SET lastblockupdate = ? WHERE txid = ? AND txindex = ?`, [confirmedTip, utxo.txid, utxo.txindex]); + } + } + + protected async $saveLastBlockAuditToDatabase(blockHeight: number) { + const query = `UPDATE state SET number = ? WHERE name = 'last_bitcoin_block_audit'`; + await DB.query(query, [blockHeight]); + } + + // Get the bitcoin block where the audit process was last updated + protected async $getAuditProgress(): Promise { + const lastblockaudit = await this.$getLastBlockAudit(); + const bitcoinBlocksToSync = await this.$getBitcoinBlockchainState(); + return { + lastBlockAudit: lastblockaudit, + confirmedTip: bitcoinBlocksToSync.bitcoinBlocks - auditBlockOffsetWithTip, + }; + } + + // Get the bitcoin blocks remaining to be synced + protected async $getBitcoinBlockchainState(): Promise { + const result = await bitcoinSecondClient.getBlockchainInfo(); + return { + bitcoinBlocks: result.blocks, + bitcoinHeaders: result.headers, + } + } + + protected async $getLastBlockAudit(): Promise { + const query = `SELECT number FROM state WHERE name = 'last_bitcoin_block_audit'`; + const [rows] = await DB.query(query); + return rows[0]['number']; + } + + protected async $getRedeemAddressesToScan(): Promise { + const query = `SELECT datetime, amount, bitcoinaddress FROM elements_pegs where amount < 0 AND bitcoinaddress != '' AND bitcointxid = '';`; + const [rows]: any[] = await DB.query(query); + return rows; + } + + ///////////// DATA QUERY ////////////// + + public async $getAuditStatus(): Promise { + const lastBlockAudit = await this.$getLastBlockAudit(); + const bitcoinBlocksToSync = await this.$getBitcoinBlockchainState(); + return { + bitcoinBlocks: bitcoinBlocksToSync.bitcoinBlocks, + bitcoinHeaders: bitcoinBlocksToSync.bitcoinHeaders, + lastBlockAudit: lastBlockAudit, + isAuditSynced: bitcoinBlocksToSync.bitcoinHeaders - bitcoinBlocksToSync.bitcoinBlocks <= 2 && bitcoinBlocksToSync.bitcoinBlocks - lastBlockAudit <= 3, + }; + } + + public async $getPegDataByMonth(): Promise { + const query = `SELECT SUM(amount) AS amount, DATE_FORMAT(FROM_UNIXTIME(datetime), '%Y-%m-01') AS date FROM elements_pegs GROUP BY DATE_FORMAT(FROM_UNIXTIME(datetime), '%Y%m')`; + const [rows] = await DB.query(query); + return rows; + } + + public async $getFederationReservesByMonth(): Promise { + const query = ` + SELECT SUM(amount) AS amount, DATE_FORMAT(FROM_UNIXTIME(blocktime), '%Y-%m-01') AS date FROM federation_txos + WHERE + (blocktime > UNIX_TIMESTAMP(LAST_DAY(FROM_UNIXTIME(blocktime) - INTERVAL 1 MONTH) + INTERVAL 1 DAY)) + AND + ((unspent = 1) OR (unspent = 0 AND lasttimeupdate > UNIX_TIMESTAMP(LAST_DAY(FROM_UNIXTIME(blocktime)) + INTERVAL 1 DAY))) + GROUP BY + date;`; + const [rows] = await DB.query(query); + return rows; + } + + // Get the current L-BTC pegs and the last Liquid block it was updated + public async $getCurrentLbtcSupply(): Promise { + const [rows] = await DB.query(`SELECT SUM(amount) AS LBTC_supply FROM elements_pegs;`); + const lastblockupdate = await this.$getLatestBlockHeightFromDatabase(); + const hash = await bitcoinClient.getBlockHash(lastblockupdate); + return { + amount: rows[0]['LBTC_supply'], + lastBlockUpdate: lastblockupdate, + hash: hash + }; + } + + // Get the current reserves of the federation and the last Bitcoin block it was updated + public async $getCurrentFederationReserves(): Promise { + const [rows] = await DB.query(`SELECT SUM(amount) AS total_balance FROM federation_txos WHERE unspent = 1;`); + const lastblockaudit = await this.$getLastBlockAudit(); + const hash = await bitcoinSecondClient.getBlockHash(lastblockaudit); + return { + amount: rows[0]['total_balance'], + lastBlockUpdate: lastblockaudit, + hash: hash + }; + } + + // Get all of the federation addresses, most balances first + public async $getFederationAddresses(): Promise { + const query = `SELECT bitcoinaddress, SUM(amount) AS balance FROM federation_txos WHERE unspent = 1 GROUP BY bitcoinaddress ORDER BY balance DESC;`; + const [rows] = await DB.query(query); + return rows; + } + + // Get all of the UTXOs held by the federation, most recent first + public async $getFederationUtxos(): Promise { + const query = `SELECT txid, txindex, bitcoinaddress, amount, blocknumber, blocktime, pegtxid, pegindex, pegblocktime FROM federation_txos WHERE unspent = 1 ORDER BY blocktime DESC;`; + const [rows] = await DB.query(query); + return rows; + } + + // Get the total number of federation addresses + public async $getFederationAddressesNumber(): Promise { + const query = `SELECT COUNT(DISTINCT bitcoinaddress) AS address_count FROM federation_txos WHERE unspent = 1;`; + const [rows] = await DB.query(query); + return rows[0]; + } + + // Get the total number of federation utxos + public async $getFederationUtxosNumber(): Promise { + const query = `SELECT COUNT(*) AS utxo_count FROM federation_txos WHERE unspent = 1;`; + const [rows] = await DB.query(query); + return rows[0]; + } + + // Get recent pegs in / out + public async $getPegsList(count: number = 0): Promise { + const query = `SELECT txid, txindex, amount, bitcoinaddress, bitcointxid, bitcoinindex, datetime AS blocktime FROM elements_pegs ORDER BY block DESC LIMIT 15 OFFSET ?;`; + const [rows] = await DB.query(query, [count]); + return rows; + } + + // Get all peg in / out from the last month + public async $getPegsVolumeDaily(): Promise { + const pegInQuery = await DB.query(`SELECT SUM(amount) AS volume, COUNT(*) AS number FROM elements_pegs WHERE amount > 0 and datetime > UNIX_TIMESTAMP(TIMESTAMPADD(DAY, -1, CURRENT_TIMESTAMP()));`); + const pegOutQuery = await DB.query(`SELECT SUM(amount) AS volume, COUNT(*) AS number FROM elements_pegs WHERE amount < 0 and datetime > UNIX_TIMESTAMP(TIMESTAMPADD(DAY, -1, CURRENT_TIMESTAMP()));`); + return [ + pegInQuery[0][0], + pegOutQuery[0][0] + ]; + } + + // Get the total pegs number + public async $getPegsCount(): Promise { + const [rows] = await DB.query(`SELECT COUNT(*) AS pegs_count FROM elements_pegs;`); + return rows[0]; + } } export default new ElementsParser(); diff --git a/backend/src/api/liquid/liquid.routes.ts b/backend/src/api/liquid/liquid.routes.ts index b130373e1..01d91e3b0 100644 --- a/backend/src/api/liquid/liquid.routes.ts +++ b/backend/src/api/liquid/liquid.routes.ts @@ -15,7 +15,18 @@ class LiquidRoutes { if (config.DATABASE.ENABLED) { app + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/pegs', this.$getElementsPegs) .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/pegs/month', this.$getElementsPegsByMonth) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/pegs/list/:count', this.$getPegsList) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/pegs/volume', this.$getPegsVolumeDaily) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/pegs/count', this.$getPegsCount) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves', this.$getFederationReserves) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/month', this.$getFederationReservesByMonth) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/addresses', this.$getFederationAddresses) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/addresses/total', this.$getFederationAddressesNumber) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/utxos', this.$getFederationUtxos) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/utxos/total', this.$getFederationUtxosNumber) + .get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/status', this.$getFederationAuditStatus) ; } } @@ -63,11 +74,147 @@ class LiquidRoutes { private async $getElementsPegsByMonth(req: Request, res: Response) { try { const pegs = await elementsParser.$getPegDataByMonth(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 60 * 60).toUTCString()); res.json(pegs); } catch (e) { res.status(500).send(e instanceof Error ? e.message : e); } } + + private async $getFederationReservesByMonth(req: Request, res: Response) { + try { + const reserves = await elementsParser.$getFederationReservesByMonth(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 60 * 60).toUTCString()); + res.json(reserves); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getElementsPegs(req: Request, res: Response) { + try { + const currentSupply = await elementsParser.$getCurrentLbtcSupply(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(currentSupply); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getFederationReserves(req: Request, res: Response) { + try { + const currentReserves = await elementsParser.$getCurrentFederationReserves(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(currentReserves); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getFederationAuditStatus(req: Request, res: Response) { + try { + const auditStatus = await elementsParser.$getAuditStatus(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(auditStatus); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getFederationAddresses(req: Request, res: Response) { + try { + const federationAddresses = await elementsParser.$getFederationAddresses(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(federationAddresses); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getFederationAddressesNumber(req: Request, res: Response) { + try { + const federationAddresses = await elementsParser.$getFederationAddressesNumber(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(federationAddresses); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getFederationUtxos(req: Request, res: Response) { + try { + const federationUtxos = await elementsParser.$getFederationUtxos(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(federationUtxos); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getFederationUtxosNumber(req: Request, res: Response) { + try { + const federationUtxos = await elementsParser.$getFederationUtxosNumber(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(federationUtxos); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getPegsList(req: Request, res: Response) { + try { + const recentPegs = await elementsParser.$getPegsList(parseInt(req.params?.count)); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(recentPegs); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getPegsVolumeDaily(req: Request, res: Response) { + try { + const pegsVolume = await elementsParser.$getPegsVolumeDaily(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(pegsVolume); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getPegsCount(req: Request, res: Response) { + try { + const pegsCount = await elementsParser.$getPegsCount(); + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString()); + res.json(pegsCount); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + } export default new LiquidRoutes(); diff --git a/backend/src/api/memory-cache.ts b/backend/src/api/memory-cache.ts index fe4162420..e71aaa6a2 100644 --- a/backend/src/api/memory-cache.ts +++ b/backend/src/api/memory-cache.ts @@ -31,7 +31,7 @@ class MemoryCache { } private cleanup() { - this.cache = this.cache.filter((cache) => cache.expires < (new Date())); + this.cache = this.cache.filter((cache) => cache.expires > (new Date())); } } diff --git a/backend/src/api/mempool-blocks.ts b/backend/src/api/mempool-blocks.ts index 15f9b6cf7..b9da7d4e8 100644 --- a/backend/src/api/mempool-blocks.ts +++ b/backend/src/api/mempool-blocks.ts @@ -1,6 +1,6 @@ import { GbtGenerator, GbtResult, ThreadTransaction as RustThreadTransaction, ThreadAcceleration as RustThreadAcceleration } from 'rust-gbt'; import logger from '../logger'; -import { MempoolBlock, MempoolTransactionExtended, TransactionStripped, MempoolBlockWithTransactions, MempoolBlockDelta, Ancestor, CompactThreadTransaction, EffectiveFeeStats, PoolTag } from '../mempool.interfaces'; +import { MempoolBlock, MempoolTransactionExtended, MempoolBlockWithTransactions, MempoolBlockDelta, Ancestor, CompactThreadTransaction, EffectiveFeeStats, PoolTag, TransactionClassified, TransactionCompressed, MempoolDeltaChange } from '../mempool.interfaces'; import { Common, OnlineFeeStatsCalculator } from './common'; import config from '../config'; import { Worker } from 'worker_threads'; @@ -169,9 +169,9 @@ class MempoolBlocks { private calculateMempoolDeltas(prevBlocks: MempoolBlockWithTransactions[], mempoolBlocks: MempoolBlockWithTransactions[]): MempoolBlockDelta[] { const mempoolBlockDeltas: MempoolBlockDelta[] = []; for (let i = 0; i < Math.max(mempoolBlocks.length, prevBlocks.length); i++) { - let added: TransactionStripped[] = []; + let added: TransactionClassified[] = []; let removed: string[] = []; - const changed: { txid: string, rate: number | undefined, acc: boolean | undefined }[] = []; + const changed: TransactionClassified[] = []; if (mempoolBlocks[i] && !prevBlocks[i]) { added = mempoolBlocks[i].transactions; } else if (!mempoolBlocks[i] && prevBlocks[i]) { @@ -194,14 +194,14 @@ class MempoolBlocks { if (!prevIds[tx.txid]) { added.push(tx); } else if (tx.rate !== prevIds[tx.txid].rate || tx.acc !== prevIds[tx.txid].acc) { - changed.push({ txid: tx.txid, rate: tx.rate, acc: tx.acc }); + changed.push(tx); } }); } mempoolBlockDeltas.push({ - added, + added: added.map(this.compressTx), removed, - changed, + changed: changed.map(this.compressDeltaChange), }); } return mempoolBlockDeltas; @@ -368,12 +368,15 @@ class MempoolBlocks { // run the block construction algorithm in a separate thread, and wait for a result const rustGbt = saveResults ? this.rustGbtGenerator : new GbtGenerator(); try { - const { blocks, blockWeights, rates, clusters } = this.convertNapiResultTxids( + const { blocks, blockWeights, rates, clusters, overflow } = this.convertNapiResultTxids( await rustGbt.make(Object.values(newMempool) as RustThreadTransaction[], convertedAccelerations as RustThreadAcceleration[], this.nextUid), ); if (saveResults) { this.rustInitialized = true; } + const mempoolSize = Object.keys(newMempool).length; + const resultMempoolSize = blocks.reduce((total, block) => total + block.length, 0) + overflow.length; + logger.debug(`RUST updateBlockTemplates returned ${resultMempoolSize} txs out of ${mempoolSize} in the mempool, ${overflow.length} were unmineable`); const processed = this.processBlockTemplates(newMempool, blocks, blockWeights, rates, clusters, accelerations, accelerationPool, saveResults); logger.debug(`RUST makeBlockTemplates completed in ${(Date.now() - start)/1000} seconds`); return processed; @@ -424,7 +427,7 @@ class MempoolBlocks { // run the block construction algorithm in a separate thread, and wait for a result try { - const { blocks, blockWeights, rates, clusters } = this.convertNapiResultTxids( + const { blocks, blockWeights, rates, clusters, overflow } = this.convertNapiResultTxids( await this.rustGbtGenerator.update( added as RustThreadTransaction[], removedUids, @@ -432,9 +435,10 @@ class MempoolBlocks { this.nextUid, ), ); - const resultMempoolSize = blocks.reduce((total, block) => total + block.length, 0); + const resultMempoolSize = blocks.reduce((total, block) => total + block.length, 0) + overflow.length; + logger.debug(`RUST updateBlockTemplates returned ${resultMempoolSize} txs out of ${mempoolSize} in the mempool, ${overflow.length} were unmineable`); if (mempoolSize !== resultMempoolSize) { - throw new Error('GBT returned wrong number of transactions, cache is probably out of sync'); + throw new Error('GBT returned wrong number of transactions , cache is probably out of sync'); } else { const processed = this.processBlockTemplates(newMempool, blocks, blockWeights, rates, clusters, accelerations, accelerationPool, true); this.removeUids(removedUids); @@ -582,6 +586,7 @@ class MempoolBlocks { const deltas = this.calculateMempoolDeltas(this.mempoolBlocks, mempoolBlocks); this.mempoolBlocks = mempoolBlocks; this.mempoolBlockDeltas = deltas; + } return mempoolBlocks; @@ -599,7 +604,7 @@ class MempoolBlocks { medianFee: feeStats.medianFee, // Common.percentile(transactions.map((tx) => tx.effectiveFeePerVsize), config.MEMPOOL.RECOMMENDED_FEE_PERCENTILE), feeRange: feeStats.feeRange, //Common.getFeesInRange(transactions, rangeLength), transactionIds: transactionIds, - transactions: transactions.map((tx) => Common.stripTransaction(tx)), + transactions: transactions.map((tx) => Common.classifyTransaction(tx)), }; } @@ -657,8 +662,8 @@ class MempoolBlocks { return { blocks: convertedBlocks, rates: convertedRates, clusters: convertedClusters } as { blocks: string[][], rates: { [root: string]: number }, clusters: { [root: string]: string[] }}; } - private convertNapiResultTxids({ blocks, blockWeights, rates, clusters }: GbtResult) - : { blocks: string[][], blockWeights: number[], rates: [string, number][], clusters: string[][] } { + private convertNapiResultTxids({ blocks, blockWeights, rates, clusters, overflow }: GbtResult) + : { blocks: string[][], blockWeights: number[], rates: [string, number][], clusters: string[][], overflow: string[] } { const convertedBlocks: string[][] = blocks.map(block => block.map(uid => { const txid = this.uidMap.get(uid); if (txid !== undefined) { @@ -676,7 +681,47 @@ class MempoolBlocks { for (const cluster of clusters) { convertedClusters.push(cluster.map(uid => this.uidMap.get(uid)) as string[]); } - return { blocks: convertedBlocks, blockWeights, rates: convertedRates, clusters: convertedClusters }; + const convertedOverflow: string[] = overflow.map(uid => { + const txid = this.uidMap.get(uid); + if (txid !== undefined) { + return txid; + } else { + throw new Error('GBT returned an unmineable transaction with unknown uid'); + } + }); + return { blocks: convertedBlocks, blockWeights, rates: convertedRates, clusters: convertedClusters, overflow: convertedOverflow }; + } + + public compressTx(tx: TransactionClassified): TransactionCompressed { + if (tx.acc) { + return [ + tx.txid, + tx.fee, + tx.vsize, + tx.value, + Math.round((tx.rate || (tx.fee / tx.vsize)) * 100) / 100, + tx.flags, + 1 + ]; + } else { + return [ + tx.txid, + tx.fee, + tx.vsize, + tx.value, + Math.round((tx.rate || (tx.fee / tx.vsize)) * 100) / 100, + tx.flags, + ]; + } + } + + public compressDeltaChange(tx: TransactionClassified): MempoolDeltaChange { + return [ + tx.txid, + Math.round((tx.rate || (tx.fee / tx.vsize)) * 100) / 100, + tx.flags, + tx.acc ? 1 : 0, + ]; } } diff --git a/backend/src/api/mempool.ts b/backend/src/api/mempool.ts index 73260dc9e..a5bc8407a 100644 --- a/backend/src/api/mempool.ts +++ b/backend/src/api/mempool.ts @@ -9,7 +9,7 @@ import loadingIndicators from './loading-indicators'; import bitcoinClient from './bitcoin/bitcoin-client'; import bitcoinSecondClient from './bitcoin/bitcoin-second-client'; import rbfCache from './rbf-cache'; -import accelerationApi, { Acceleration } from './services/acceleration'; +import { Acceleration } from './services/acceleration'; import redisCache from './redis-cache'; class Mempool { @@ -18,7 +18,7 @@ class Mempool { private mempoolCache: { [txId: string]: MempoolTransactionExtended } = {}; private spendMap = new Map(); private mempoolInfo: IBitcoinApi.MempoolInfo = { loaded: false, size: 0, bytes: 0, usage: 0, total_fee: 0, - maxmempool: 300000000, mempoolminfee: 0.00001000, minrelaytxfee: 0.00001000 }; + maxmempool: 300000000, mempoolminfee: Common.isLiquid() ? 0.00000100 : 0.00001000, minrelaytxfee: Common.isLiquid() ? 0.00000100 : 0.00001000 }; private mempoolChangedCallback: ((newMempool: {[txId: string]: MempoolTransactionExtended; }, newTransactions: MempoolTransactionExtended[], deletedTransactions: MempoolTransactionExtended[], accelerationDelta: string[]) => void) | undefined; private $asyncMempoolChangedCallback: ((newMempool: {[txId: string]: MempoolTransactionExtended; }, mempoolSize: number, newTransactions: MempoolTransactionExtended[], @@ -94,12 +94,15 @@ class Mempool { logger.debug(`Migrating ${Object.keys(this.mempoolCache).length} transactions from disk cache to Redis cache`); } for (const txid of Object.keys(this.mempoolCache)) { - if (!this.mempoolCache[txid].sigops || this.mempoolCache[txid].effectiveFeePerVsize == null) { + if (!this.mempoolCache[txid].adjustedVsize || this.mempoolCache[txid].sigops == null || this.mempoolCache[txid].effectiveFeePerVsize == null) { this.mempoolCache[txid] = transactionUtils.extendMempoolTransaction(this.mempoolCache[txid]); } if (this.mempoolCache[txid].order == null) { this.mempoolCache[txid].order = transactionUtils.txidToOrdering(txid); } + for (const vin of this.mempoolCache[txid].vin) { + transactionUtils.addInnerScriptsToVin(vin); + } count++; if (config.MEMPOOL.CACHE_ENABLED && config.REDIS.ENABLED) { await redisCache.$addTransaction(this.mempoolCache[txid]); @@ -126,7 +129,7 @@ class Mempool { loadingIndicators.setProgress('mempool', count / expectedCount * 100); while (!done) { try { - const result = await bitcoinApi.$getAllMempoolTransactions(last_txid); + const result = await bitcoinApi.$getAllMempoolTransactions(last_txid, config.ESPLORA.BATCH_QUERY_BASE_SIZE); if (result) { for (const tx of result) { const extendedTransaction = transactionUtils.extendMempoolTransaction(tx); @@ -185,7 +188,7 @@ class Mempool { return txTimes; } - public async $updateMempool(transactions: string[], pollRate: number): Promise { + public async $updateMempool(transactions: string[], accelerations: Acceleration[] | null, pollRate: number): Promise { logger.debug(`Updating mempool...`); // warn if this run stalls the main loop for more than 2 minutes @@ -235,7 +238,7 @@ class Mempool { if (!loaded) { const remainingTxids = transactions.filter(txid => !this.mempoolCache[txid]); - const sliceLength = 10000; + const sliceLength = config.ESPLORA.BATCH_QUERY_BASE_SIZE; for (let i = 0; i < Math.ceil(remainingTxids.length / sliceLength); i++) { const slice = remainingTxids.slice(i * sliceLength, (i + 1) * sliceLength); const txs = await transactionUtils.$getMempoolTransactionsExtended(slice, false, false, false); @@ -330,7 +333,7 @@ class Mempool { const newTransactionsStripped = newTransactions.map((tx) => Common.stripTransaction(tx)); this.latestTransactions = newTransactionsStripped.concat(this.latestTransactions).slice(0, 6); - const accelerationDelta = await this.$updateAccelerations(); + const accelerationDelta = accelerations != null ? await this.$updateAccelerations(accelerations) : []; if (accelerationDelta.length) { hasChange = true; } @@ -370,14 +373,12 @@ class Mempool { return this.accelerations; } - public async $updateAccelerations(): Promise { + public $updateAccelerations(newAccelerations: Acceleration[]): string[] { if (!config.MEMPOOL_SERVICES.ACCELERATIONS) { return []; } try { - const newAccelerations = await accelerationApi.$fetchAccelerations(); - const changed: string[] = []; const newAccelerationMap: { [txid: string]: Acceleration } = {}; diff --git a/backend/src/api/mining/mining-routes.ts b/backend/src/api/mining/mining-routes.ts index bb78de44a..6b9ef7b9f 100644 --- a/backend/src/api/mining/mining-routes.ts +++ b/backend/src/api/mining/mining-routes.ts @@ -8,6 +8,7 @@ import HashratesRepository from '../../repositories/HashratesRepository'; import bitcoinClient from '../bitcoin/bitcoin-client'; import mining from "./mining"; import PricesRepository from '../../repositories/PricesRepository'; +import AccelerationRepository from '../../repositories/AccelerationRepository'; class MiningRoutes { public initRoutes(app: Application) { @@ -34,6 +35,10 @@ class MiningRoutes { .get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/audit/:hash', this.$getBlockAudit) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/timestamp/:timestamp', this.$getHeightFromTimestamp) .get(config.MEMPOOL.API_URL_PREFIX + 'historical-price', this.$getHistoricalPrice) + + .get(config.MEMPOOL.API_URL_PREFIX + 'accelerations/pool/:slug', this.$getAccelerationsByPool) + .get(config.MEMPOOL.API_URL_PREFIX + 'accelerations/block/:height', this.$getAccelerationsByHeight) + .get(config.MEMPOOL.API_URL_PREFIX + 'accelerations/recent/:interval', this.$getRecentAccelerations) ; } @@ -352,6 +357,52 @@ class MiningRoutes { res.status(500).send(e instanceof Error ? e.message : e); } } + + private async $getAccelerationsByPool(req: Request, res: Response): Promise { + try { + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString()); + if (!config.MEMPOOL_SERVICES.ACCELERATIONS || ['testnet', 'signet', 'liquidtestnet', 'liquid'].includes(config.MEMPOOL.NETWORK)) { + res.status(400).send('Acceleration data is not available.'); + return; + } + res.status(200).send(await AccelerationRepository.$getAccelerationInfo(req.params.slug)); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getAccelerationsByHeight(req: Request, res: Response): Promise { + try { + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 3600 * 24).toUTCString()); + if (!config.MEMPOOL_SERVICES.ACCELERATIONS || ['testnet', 'signet', 'liquidtestnet', 'liquid'].includes(config.MEMPOOL.NETWORK)) { + res.status(400).send('Acceleration data is not available.'); + return; + } + const height = req.params.height === undefined ? undefined : parseInt(req.params.height, 10); + res.status(200).send(await AccelerationRepository.$getAccelerationInfo(null, height)); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } + + private async $getRecentAccelerations(req: Request, res: Response): Promise { + try { + res.header('Pragma', 'public'); + res.header('Cache-control', 'public'); + res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString()); + if (!config.MEMPOOL_SERVICES.ACCELERATIONS || ['testnet', 'signet', 'liquidtestnet', 'liquid'].includes(config.MEMPOOL.NETWORK)) { + res.status(400).send('Acceleration data is not available.'); + return; + } + res.status(200).send(await AccelerationRepository.$getAccelerationInfo(null, null, req.params.interval)); + } catch (e) { + res.status(500).send(e instanceof Error ? e.message : e); + } + } } export default new MiningRoutes(); diff --git a/backend/src/api/mining/mining.ts b/backend/src/api/mining/mining.ts index d9d5995da..85554db2d 100644 --- a/backend/src/api/mining/mining.ts +++ b/backend/src/api/mining/mining.ts @@ -15,6 +15,13 @@ import bitcoinApi from '../bitcoin/bitcoin-api-factory'; import { IEsploraApi } from '../bitcoin/esplora-api.interface'; import database from '../../database'; +interface DifficultyBlock { + timestamp: number, + height: number, + bits: number, + difficulty: number, +} + class Mining { private blocksPriceIndexingRunning = false; public lastHashrateIndexingDate: number | null = null; @@ -135,7 +142,7 @@ class Mining { public async $getPoolStat(slug: string): Promise { const pool = await PoolsRepository.$getPool(slug); if (!pool) { - throw new Error('This mining pool does not exist ' + escape(slug)); + throw new Error('This mining pool does not exist'); } const blockCount: number = await BlocksRepository.$blockCount(pool.id); @@ -421,6 +428,7 @@ class Mining { indexedHeights[height] = true; } + // gets {time, height, difficulty, bits} of blocks in ascending order of height const blocks: any = await BlocksRepository.$getBlocksDifficulty(); const genesisBlock: IEsploraApi.Block = await bitcoinApi.$getBlock(await bitcoinApi.$getBlockHash(0)); let currentDifficulty = genesisBlock.difficulty; @@ -436,41 +444,45 @@ class Mining { }); } - const oldestConsecutiveBlock = await BlocksRepository.$getOldestConsecutiveBlock(); - if (config.MEMPOOL.INDEXING_BLOCKS_AMOUNT !== -1) { - currentBits = oldestConsecutiveBlock.bits; - currentDifficulty = oldestConsecutiveBlock.difficulty; + if (!blocks?.length) { + // no blocks in database yet + return; } + const oldestConsecutiveBlock = this.getOldestConsecutiveBlock(blocks); + + currentBits = oldestConsecutiveBlock.bits; + currentDifficulty = oldestConsecutiveBlock.difficulty; + let totalBlockChecked = 0; let timer = new Date().getTime() / 1000; for (const block of blocks) { + // skip until the first block after the oldest consecutive block + if (block.height <= oldestConsecutiveBlock.height) { + continue; + } + + // difficulty has changed between two consecutive blocks! if (block.bits !== currentBits) { - if (indexedHeights[block.height] === true) { // Already indexed - if (block.height >= oldestConsecutiveBlock.height) { - currentDifficulty = block.difficulty; - currentBits = block.bits; - } - continue; + // skip if already indexed + if (indexedHeights[block.height] !== true) { + let adjustment = block.difficulty / currentDifficulty; + adjustment = Math.round(adjustment * 1000000) / 1000000; // Remove float point noise + + await DifficultyAdjustmentsRepository.$saveAdjustments({ + time: block.time, + height: block.height, + difficulty: block.difficulty, + adjustment: adjustment, + }); + + totalIndexed++; } - - let adjustment = block.difficulty / currentDifficulty; - adjustment = Math.round(adjustment * 1000000) / 1000000; // Remove float point noise - - await DifficultyAdjustmentsRepository.$saveAdjustments({ - time: block.time, - height: block.height, - difficulty: block.difficulty, - adjustment: adjustment, - }); - - totalIndexed++; - if (block.height >= oldestConsecutiveBlock.height) { - currentDifficulty = block.difficulty; - currentBits = block.bits; - } - } + // update the current difficulty + currentDifficulty = block.difficulty; + currentBits = block.bits; + } totalBlockChecked++; const elapsedSeconds = Math.max(1, Math.round((new Date().getTime() / 1000) - timer)); @@ -633,6 +645,17 @@ class Mining { default: return 86400 * scale; } } + + // Finds the oldest block in a consecutive chain back from the tip + // assumes `blocks` is sorted in ascending height order + private getOldestConsecutiveBlock(blocks: DifficultyBlock[]): DifficultyBlock { + for (let i = blocks.length - 1; i > 0; i--) { + if ((blocks[i].height - blocks[i - 1].height) > 1) { + return blocks[i]; + } + } + return blocks[0]; + } } export default new Mining(); diff --git a/backend/src/api/rbf-cache.ts b/backend/src/api/rbf-cache.ts index b5592252c..a087abbe0 100644 --- a/backend/src/api/rbf-cache.ts +++ b/backend/src/api/rbf-cache.ts @@ -2,6 +2,7 @@ import config from "../config"; import logger from "../logger"; import { MempoolTransactionExtended, TransactionStripped } from "../mempool.interfaces"; import bitcoinApi from './bitcoin/bitcoin-api-factory'; +import { IEsploraApi } from "./bitcoin/esplora-api.interface"; import { Common } from "./common"; import redisCache from "./redis-cache"; @@ -53,6 +54,9 @@ class RbfCache { private expiring: Map = new Map(); private cacheQueue: CacheEvent[] = []; + private evictionCount = 0; + private staleCount = 0; + constructor() { setInterval(this.cleanup.bind(this), 1000 * 60 * 10); } @@ -93,6 +97,8 @@ class RbfCache { return; } + newTxExtended.replacement = true; + const newTx = Common.stripTransaction(newTxExtended) as RbfTransaction; const newTime = newTxExtended.firstSeen || (Date.now() / 1000); newTx.rbf = newTxExtended.vin.some((v) => v.sequence < 0xfffffffe); @@ -245,6 +251,7 @@ class RbfCache { // flag a transaction as removed from the mempool public evict(txid: string, fast: boolean = false): void { + this.evictionCount++; if (this.txs.has(txid) && (fast || !this.expiring.has(txid))) { const expiryTime = fast ? Date.now() + (1000 * 60 * 10) : Date.now() + (1000 * 86400); // 24 hours this.addExpiration(txid, expiryTime); @@ -272,18 +279,23 @@ class RbfCache { this.remove(txid); } } - logger.debug(`rbf cache contains ${this.txs.size} txs, ${this.rbfTrees.size} trees, ${this.expiring.size} due to expire`); + logger.debug(`rbf cache contains ${this.txs.size} txs, ${this.rbfTrees.size} trees, ${this.expiring.size} due to expire (${this.evictionCount} newly expired)`); + this.evictionCount = 0; } // remove a transaction & all previous versions from the cache private remove(txid): void { // don't remove a transaction if a newer version remains in the mempool if (!this.replacedBy.has(txid)) { + const root = this.treeMap.get(txid); const replaces = this.replaces.get(txid); this.replaces.delete(txid); this.treeMap.delete(txid); this.removeTx(txid); this.removeExpiration(txid); + if (root === txid) { + this.removeTree(txid); + } for (const tx of (replaces || [])) { // recursively remove prior versions from the cache this.replacedBy.delete(tx); @@ -358,19 +370,28 @@ class RbfCache { }; } - public async load({ txs, trees, expiring }): Promise { - txs.forEach(txEntry => { - this.txs.set(txEntry.key, txEntry.value); - }); - for (const deflatedTree of trees) { - await this.importTree(deflatedTree.root, deflatedTree.root, deflatedTree, this.txs); - } - expiring.forEach(expiringEntry => { - if (this.txs.has(expiringEntry.key)) { - this.expiring.set(expiringEntry.key, new Date(expiringEntry.value).getTime()); + public async load({ txs, trees, expiring, mempool }): Promise { + try { + txs.forEach(txEntry => { + this.txs.set(txEntry.value.txid, txEntry.value); + }); + this.staleCount = 0; + for (const deflatedTree of trees) { + await this.importTree(mempool, deflatedTree.root, deflatedTree.root, deflatedTree, this.txs); } - }); - this.cleanup(); + expiring.forEach(expiringEntry => { + if (this.txs.has(expiringEntry.key)) { + this.expiring.set(expiringEntry.key, new Date(expiringEntry.value).getTime()); + } + }); + this.staleCount = 0; + await this.checkTrees(); + logger.debug(`loaded ${txs.length} txs, ${trees.length} trees into rbf cache, ${expiring.length} due to expire, ${this.staleCount} were stale`); + this.cleanup(); + + } catch (e) { + logger.err('failed to restore RBF cache: ' + (e instanceof Error ? e.message : e)); + } } exportTree(tree: RbfTree, deflated: any = null) { @@ -394,40 +415,25 @@ class RbfCache { return deflated; } - async importTree(root, txid, deflated, txs: Map, mined: boolean = false): Promise { + async importTree(mempool, root, txid, deflated, txs: Map, mined: boolean = false): Promise { const treeInfo = deflated[txid]; const replaces: RbfTree[] = []; - // check if any transactions in this tree have already been confirmed - mined = mined || treeInfo.mined; - let exists = mined; - if (!mined) { - try { - const apiTx = await bitcoinApi.$getRawTransaction(txid); - if (apiTx) { - exists = true; - } - if (apiTx?.status?.confirmed) { - mined = true; - treeInfo.txMined = true; - this.evict(txid, true); - } - } catch (e) { - // most transactions do not exist - } - } - - // if the root tx is not in the mempool or the blockchain - // evict this tree as soon as possible - if (root === txid && !exists) { - this.evict(txid, true); + // if the root tx is unknown, remove this tree and return early + if (root === txid && !txs.has(txid)) { + this.staleCount++; + this.removeTree(deflated.key); + return; } // recursively reconstruct child trees for (const childId of treeInfo.replaces) { - const replaced = await this.importTree(root, childId, deflated, txs, mined); + const replaced = await this.importTree(mempool, root, childId, deflated, txs, mined); if (replaced) { this.replacedBy.set(replaced.tx.txid, txid); + if (mempool[replaced.tx.txid]) { + mempool[replaced.tx.txid].replacement = true; + } replaces.push(replaced); if (replaced.mined) { mined = true; @@ -458,6 +464,60 @@ class RbfCache { return tree; } + private async checkTrees(): Promise { + const found: { [txid: string]: boolean } = {}; + const txids = Array.from(this.txs.values()).map(tx => tx.txid).filter(txid => { + return !this.expiring.has(txid) && !this.getRbfTree(txid)?.mined; + }); + + const processTxs = (txs: IEsploraApi.Transaction[]): void => { + for (const tx of txs) { + found[tx.txid] = true; + if (tx.status?.confirmed) { + const tree = this.getRbfTree(tx.txid); + if (tree) { + this.setTreeMined(tree, tx.txid); + tree.mined = true; + this.evict(tx.txid, false); + } + } + } + }; + + if (config.MEMPOOL.BACKEND === 'esplora') { + let processedCount = 0; + const sliceLength = Math.ceil(config.ESPLORA.BATCH_QUERY_BASE_SIZE / 40); + for (let i = 0; i < Math.ceil(txids.length / sliceLength); i++) { + const slice = txids.slice(i * sliceLength, (i + 1) * sliceLength); + processedCount += slice.length; + try { + const txs = await bitcoinApi.$getRawTransactions(slice); + processTxs(txs); + logger.debug(`fetched and processed ${processedCount} of ${txids.length} cached rbf transactions (${(processedCount / txids.length * 100).toFixed(2)}%)`); + } catch (err) { + logger.err(`failed to fetch or process ${slice.length} cached rbf transactions`); + } + } + } else { + const txs: IEsploraApi.Transaction[] = []; + for (const txid of txids) { + try { + const tx = await bitcoinApi.$getRawTransaction(txid, true, false); + txs.push(tx); + } catch (err) { + // some 404s are expected, so continue quietly + } + } + processTxs(txs); + } + + for (const txid of txids) { + if (!found[txid]) { + this.evict(txid, false); + } + } + } + public getLatestRbfSummary(): ReplacementInfo[] { const rbfList = this.getRbfTrees(false); return rbfList.slice(0, 6).map(rbfTree => { diff --git a/backend/src/api/redis-cache.ts b/backend/src/api/redis-cache.ts index fcde8013a..d19d73a7f 100644 --- a/backend/src/api/redis-cache.ts +++ b/backend/src/api/redis-cache.ts @@ -19,45 +19,90 @@ class RedisCache { private client; private connected = false; private schemaVersion = 1; + private redisConfig: any; + private pauseFlush: boolean = false; private cacheQueue: MempoolTransactionExtended[] = []; + private removeQueue: string[] = []; + private rbfCacheQueue: { type: string, txid: string, value: any }[] = []; + private rbfRemoveQueue: { type: string, txid: string }[] = []; private txFlushLimit: number = 10000; constructor() { if (config.REDIS.ENABLED) { - const redisConfig = { + this.redisConfig = { socket: { path: config.REDIS.UNIX_SOCKET_PATH }, database: NetworkDB[config.MEMPOOL.NETWORK], }; - this.client = createClient(redisConfig); - this.client.on('error', (e) => { - logger.err(`Error in Redis client: ${e instanceof Error ? e.message : e}`); - }); this.$ensureConnected(); + setInterval(() => { this.$ensureConnected(); }, 10000); } } - private async $ensureConnected(): Promise { + private async $ensureConnected(): Promise { if (!this.connected && config.REDIS.ENABLED) { - return this.client.connect().then(async () => { - this.connected = true; - logger.info(`Redis client connected`); - const version = await this.client.get('schema_version'); - if (version !== this.schemaVersion) { - // schema changed - // perform migrations or flush DB if necessary - logger.info(`Redis schema version changed from ${version} to ${this.schemaVersion}`); - await this.client.set('schema_version', this.schemaVersion); - } - }); + try { + this.client = createClient(this.redisConfig); + this.client.on('error', async (e) => { + logger.err(`Error in Redis client: ${e instanceof Error ? e.message : e}`); + this.connected = false; + await this.client.disconnect(); + }); + await this.client.connect().then(async () => { + try { + const version = await this.client.get('schema_version'); + this.connected = true; + if (version !== this.schemaVersion) { + // schema changed + // perform migrations or flush DB if necessary + logger.info(`Redis schema version changed from ${version} to ${this.schemaVersion}`); + await this.client.set('schema_version', this.schemaVersion); + } + logger.info(`Redis client connected`); + return true; + } catch (e) { + this.connected = false; + logger.warn('Failed to connect to Redis'); + return false; + } + }); + await this.$onConnected(); + return true; + } catch (e) { + logger.warn('Error connecting to Redis: ' + (e instanceof Error ? e.message : e)); + return false; + } + } else { + try { + // test connection + await this.client.get('schema_version'); + return true; + } catch (e) { + logger.warn('Lost connection to Redis: ' + (e instanceof Error ? e.message : e)); + logger.warn('Attempting to reconnect in 10 seconds'); + this.connected = false; + return false; + } } } - async $updateBlocks(blocks: BlockExtended[]) { + private async $onConnected(): Promise { + await this.$flushTransactions(); + await this.$removeTransactions([]); + await this.$flushRbfQueues(); + } + + async $updateBlocks(blocks: BlockExtended[]): Promise { + if (!config.REDIS.ENABLED) { + return; + } + if (!this.connected) { + logger.warn(`Failed to update blocks in Redis cache: Redis is not connected`); + return; + } try { - await this.$ensureConnected(); await this.client.set('blocks', JSON.stringify(blocks)); logger.debug(`Saved latest blocks to Redis cache`); } catch (e) { @@ -65,9 +110,15 @@ class RedisCache { } } - async $updateBlockSummaries(summaries: BlockSummary[]) { + async $updateBlockSummaries(summaries: BlockSummary[]): Promise { + if (!config.REDIS.ENABLED) { + return; + } + if (!this.connected) { + logger.warn(`Failed to update block summaries in Redis cache: Redis is not connected`); + return; + } try { - await this.$ensureConnected(); await this.client.set('block-summaries', JSON.stringify(summaries)); logger.debug(`Saved latest block summaries to Redis cache`); } catch (e) { @@ -75,30 +126,35 @@ class RedisCache { } } - async $addTransaction(tx: MempoolTransactionExtended) { + async $addTransaction(tx: MempoolTransactionExtended): Promise { + if (!config.REDIS.ENABLED) { + return; + } this.cacheQueue.push(tx); if (this.cacheQueue.length >= this.txFlushLimit) { - await this.$flushTransactions(); + if (!this.pauseFlush) { + await this.$flushTransactions(); + } } } - async $flushTransactions() { - const success = await this.$addTransactions(this.cacheQueue); - if (success) { - logger.debug(`Saved ${this.cacheQueue.length} transactions to Redis cache`); - this.cacheQueue = []; - } else { - logger.err(`Failed to save ${this.cacheQueue.length} transactions to Redis cache`); + async $flushTransactions(): Promise { + if (!config.REDIS.ENABLED) { + return; + } + if (!this.cacheQueue.length) { + return; + } + if (!this.connected) { + logger.warn(`Failed to add ${this.cacheQueue.length} transactions to Redis cache: Redis not connected`); + return; } - } - private async $addTransactions(newTransactions: MempoolTransactionExtended[]): Promise { - if (!newTransactions.length) { - return true; - } + this.pauseFlush = false; + + const toAdd = this.cacheQueue.slice(0, this.txFlushLimit); try { - await this.$ensureConnected(); - const msetData = newTransactions.map(tx => { + const msetData = toAdd.map(tx => { const minified: any = { ...tx }; delete minified.hex; for (const vin of minified.vin) { @@ -112,29 +168,53 @@ class RedisCache { return [`mempool:tx:${tx.txid}`, JSON.stringify(minified)]; }); await this.client.MSET(msetData); - return true; + // successful, remove transactions from cache queue + this.cacheQueue = this.cacheQueue.slice(toAdd.length); + logger.debug(`Saved ${toAdd.length} transactions to Redis cache, ${this.cacheQueue.length} left in queue`); } catch (e) { - logger.warn(`Failed to add ${newTransactions.length} transactions to Redis cache: ${e instanceof Error ? e.message : e}`); - return false; + logger.warn(`Failed to add ${toAdd.length} transactions to Redis cache: ${e instanceof Error ? e.message : e}`); + this.pauseFlush = true; } } - async $removeTransactions(transactions: string[]) { - try { - await this.$ensureConnected(); - for (let i = 0; i < Math.ceil(transactions.length / 10000); i++) { - const slice = transactions.slice(i * 10000, (i + 1) * 10000); - await this.client.unlink(slice.map(txid => `mempool:tx:${txid}`)); - logger.debug(`Deleted ${slice.length} transactions from the Redis cache`); + async $removeTransactions(transactions: string[]): Promise { + if (!config.REDIS.ENABLED) { + return; + } + const toRemove = this.removeQueue.concat(transactions); + this.removeQueue = []; + let failed: string[] = []; + let numRemoved = 0; + if (this.connected) { + const sliceLength = config.REDIS.BATCH_QUERY_BASE_SIZE; + for (let i = 0; i < Math.ceil(toRemove.length / sliceLength); i++) { + const slice = toRemove.slice(i * sliceLength, (i + 1) * sliceLength); + try { + await this.client.unlink(slice.map(txid => `mempool:tx:${txid}`)); + numRemoved+= sliceLength; + logger.debug(`Deleted ${slice.length} transactions from the Redis cache`); + } catch (e) { + logger.warn(`Failed to remove ${slice.length} transactions from Redis cache: ${e instanceof Error ? e.message : e}`); + failed = failed.concat(slice); + } } - } catch (e) { - logger.warn(`Failed to remove ${transactions.length} transactions from Redis cache: ${e instanceof Error ? e.message : e}`); + // concat instead of replace, in case more txs have been added in the meantime + this.removeQueue = this.removeQueue.concat(failed); + } else { + this.removeQueue = this.removeQueue.concat(toRemove); } } async $setRbfEntry(type: string, txid: string, value: any): Promise { + if (!config.REDIS.ENABLED) { + return; + } + if (!this.connected) { + this.rbfCacheQueue.push({ type, txid, value }); + logger.warn(`Failed to set RBF ${type} in Redis cache: Redis is not connected`); + return; + } try { - await this.$ensureConnected(); await this.client.set(`rbf:${type}:${txid}`, JSON.stringify(value)); } catch (e) { logger.warn(`Failed to set RBF ${type} in Redis cache: ${e instanceof Error ? e.message : e}`); @@ -142,17 +222,55 @@ class RedisCache { } async $removeRbfEntry(type: string, txid: string): Promise { + if (!config.REDIS.ENABLED) { + return; + } + if (!this.connected) { + this.rbfRemoveQueue.push({ type, txid }); + logger.warn(`Failed to remove RBF ${type} from Redis cache: Redis is not connected`); + return; + } try { - await this.$ensureConnected(); await this.client.unlink(`rbf:${type}:${txid}`); } catch (e) { logger.warn(`Failed to remove RBF ${type} from Redis cache: ${e instanceof Error ? e.message : e}`); } } - async $getBlocks(): Promise { + private async $flushRbfQueues(): Promise { + if (!config.REDIS.ENABLED) { + return; + } + if (!this.connected) { + return; + } + try { + const toAdd = this.rbfCacheQueue; + this.rbfCacheQueue = []; + for (const { type, txid, value } of toAdd) { + await this.$setRbfEntry(type, txid, value); + } + logger.debug(`Saved ${toAdd.length} queued RBF entries to the Redis cache`); + const toRemove = this.rbfRemoveQueue; + this.rbfRemoveQueue = []; + for (const { type, txid } of toRemove) { + await this.$removeRbfEntry(type, txid); + } + logger.debug(`Removed ${toRemove.length} queued RBF entries from the Redis cache`); + } catch (e) { + logger.warn(`Failed to flush RBF cache event queues after reconnecting to Redis: ${e instanceof Error ? e.message : e}`); + } + } + + async $getBlocks(): Promise { + if (!config.REDIS.ENABLED) { + return []; + } + if (!this.connected) { + logger.warn(`Failed to retrieve blocks from Redis cache: Redis is not connected`); + return []; + } try { - await this.$ensureConnected(); const json = await this.client.get('blocks'); return JSON.parse(json); } catch (e) { @@ -162,8 +280,14 @@ class RedisCache { } async $getBlockSummaries(): Promise { + if (!config.REDIS.ENABLED) { + return []; + } + if (!this.connected) { + logger.warn(`Failed to retrieve blocks from Redis cache: Redis is not connected`); + return []; + } try { - await this.$ensureConnected(); const json = await this.client.get('block-summaries'); return JSON.parse(json); } catch (e) { @@ -173,10 +297,16 @@ class RedisCache { } async $getMempool(): Promise<{ [txid: string]: MempoolTransactionExtended }> { + if (!config.REDIS.ENABLED) { + return {}; + } + if (!this.connected) { + logger.warn(`Failed to retrieve mempool from Redis cache: Redis is not connected`); + return {}; + } const start = Date.now(); const mempool = {}; try { - await this.$ensureConnected(); const mempoolList = await this.scanKeys('mempool:tx:*'); for (const tx of mempoolList) { mempool[tx.key] = tx.value; @@ -190,8 +320,14 @@ class RedisCache { } async $getRbfEntries(type: string): Promise { + if (!config.REDIS.ENABLED) { + return []; + } + if (!this.connected) { + logger.warn(`Failed to retrieve Rbf ${type}s from Redis cache: Redis is not connected`); + return []; + } try { - await this.$ensureConnected(); const rbfEntries = await this.scanKeys(`rbf:${type}:*`); return rbfEntries; } catch (e) { @@ -200,7 +336,10 @@ class RedisCache { } } - async $loadCache() { + async $loadCache(): Promise { + if (!config.REDIS.ENABLED) { + return; + } logger.info('Restoring mempool and blocks data from Redis cache'); // Load block data const loadedBlocks = await this.$getBlocks(); @@ -219,12 +358,13 @@ class RedisCache { await memPool.$setMempool(loadedMempool); await rbfCache.load({ txs: rbfTxs, - trees: rbfTrees.map(loadedTree => loadedTree.value), + trees: rbfTrees.map(loadedTree => { loadedTree.value.key = loadedTree.key; return loadedTree.value; }), expiring: rbfExpirations, + mempool: memPool.getMempool(), }); } - private inflateLoadedTxs(mempool: { [txid: string]: MempoolTransactionExtended }) { + private inflateLoadedTxs(mempool: { [txid: string]: MempoolTransactionExtended }): void { for (const tx of Object.values(mempool)) { for (const vin of tx.vin) { if (vin.scriptsig) { diff --git a/backend/src/api/services/acceleration.ts b/backend/src/api/services/acceleration.ts index 635dc8300..99bb963ee 100644 --- a/backend/src/api/services/acceleration.ts +++ b/backend/src/api/services/acceleration.ts @@ -1,6 +1,7 @@ -import { query } from '../../utils/axios-query'; import config from '../../config'; +import logger from '../../logger'; import { BlockExtended, PoolTag } from '../../mempool.interfaces'; +import axios from 'axios'; export interface Acceleration { txid: string, @@ -9,10 +10,15 @@ export interface Acceleration { } class AccelerationApi { - public async $fetchAccelerations(): Promise { + public async $fetchAccelerations(): Promise { if (config.MEMPOOL_SERVICES.ACCELERATIONS) { - const response = await query(`${config.MEMPOOL_SERVICES.API}/accelerator/accelerations`); - return (response as Acceleration[]) || []; + try { + const response = await axios.get(`${config.MEMPOOL_SERVICES.API}/accelerator/accelerations`, { responseType: 'json', timeout: 10000 }); + return response.data as Acceleration[]; + } catch (e) { + logger.warn('Failed to fetch current accelerations from the mempool services backend: ' + (e instanceof Error ? e.message : e)); + return null; + } } else { return []; } diff --git a/backend/src/api/statistics/statistics-api.ts b/backend/src/api/statistics/statistics-api.ts index 9df12d704..c7c3f37b0 100644 --- a/backend/src/api/statistics/statistics-api.ts +++ b/backend/src/api/statistics/statistics-api.ts @@ -15,6 +15,7 @@ class StatisticsApi { mempool_byte_weight, fee_data, total_fee, + min_fee, vsize_1, vsize_2, vsize_3, @@ -54,7 +55,7 @@ class StatisticsApi { vsize_1800, vsize_2000 ) - VALUES (NOW(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + VALUES (NOW(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)`; const [result]: any = await DB.query(query); return result.insertId; @@ -73,6 +74,7 @@ class StatisticsApi { mempool_byte_weight, fee_data, total_fee, + min_fee, vsize_1, vsize_2, vsize_3, @@ -112,7 +114,7 @@ class StatisticsApi { vsize_1800, vsize_2000 ) - VALUES (${statistics.added}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, + VALUES (${statistics.added}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`; const params: (string | number)[] = [ @@ -122,6 +124,7 @@ class StatisticsApi { statistics.mempool_byte_weight, statistics.fee_data, statistics.total_fee, + statistics.min_fee, statistics.vsize_1, statistics.vsize_2, statistics.vsize_3, @@ -171,7 +174,9 @@ class StatisticsApi { private getQueryForDaysAvg(div: number, interval: string) { return `SELECT UNIX_TIMESTAMP(added) as added, + CAST(avg(unconfirmed_transactions) as DOUBLE) as unconfirmed_transactions, CAST(avg(vbytes_per_second) as DOUBLE) as vbytes_per_second, + CAST(avg(min_fee) as DOUBLE) as min_fee, CAST(avg(vsize_1) as DOUBLE) as vsize_1, CAST(avg(vsize_2) as DOUBLE) as vsize_2, CAST(avg(vsize_3) as DOUBLE) as vsize_3, @@ -219,7 +224,9 @@ class StatisticsApi { private getQueryForDays(div: number, interval: string) { return `SELECT UNIX_TIMESTAMP(added) as added, + CAST(avg(unconfirmed_transactions) as DOUBLE) as unconfirmed_transactions, CAST(avg(vbytes_per_second) as DOUBLE) as vbytes_per_second, + CAST(avg(min_fee) as DOUBLE) as min_fee, vsize_1, vsize_2, vsize_3, @@ -278,7 +285,7 @@ class StatisticsApi { public async $list2H(): Promise { try { - const query = `SELECT *, UNIX_TIMESTAMP(added) as added FROM statistics ORDER BY statistics.added DESC LIMIT 120`; + const query = `SELECT *, UNIX_TIMESTAMP(added) as added FROM statistics WHERE added BETWEEN DATE_SUB(NOW(), INTERVAL 2 HOUR) AND NOW() ORDER BY statistics.added DESC`; const [rows] = await DB.query({ sql: query, timeout: this.queryTimeout }); return this.mapStatisticToOptimizedStatistic(rows as Statistic[]); } catch (e) { @@ -289,7 +296,7 @@ class StatisticsApi { public async $list24H(): Promise { try { - const query = `SELECT *, UNIX_TIMESTAMP(added) as added FROM statistics ORDER BY statistics.added DESC LIMIT 1440`; + const query = `SELECT *, UNIX_TIMESTAMP(added) as added FROM statistics WHERE added BETWEEN DATE_SUB(NOW(), INTERVAL 24 HOUR) AND NOW() ORDER BY statistics.added DESC`; const [rows] = await DB.query({ sql: query, timeout: this.queryTimeout }); return this.mapStatisticToOptimizedStatistic(rows as Statistic[]); } catch (e) { @@ -401,9 +408,11 @@ class StatisticsApi { return statistic.map((s) => { return { added: s.added, + count: s.unconfirmed_transactions, vbytes_per_second: s.vbytes_per_second, mempool_byte_weight: s.mempool_byte_weight, total_fee: s.total_fee, + min_fee: s.min_fee, vsizes: [ s.vsize_1, s.vsize_2, diff --git a/backend/src/api/statistics/statistics.ts b/backend/src/api/statistics/statistics.ts index 27554f36d..2926a4b17 100644 --- a/backend/src/api/statistics/statistics.ts +++ b/backend/src/api/statistics/statistics.ts @@ -6,6 +6,7 @@ import statisticsApi from './statistics-api'; class Statistics { protected intervalTimer: NodeJS.Timer | undefined; + protected lastRun: number = 0; protected newStatisticsEntryCallback: ((stats: OptimizedStatistic) => void) | undefined; public setNewStatisticsEntryCallback(fn: (stats: OptimizedStatistic) => void) { @@ -23,15 +24,21 @@ class Statistics { setTimeout(() => { this.runStatistics(); this.intervalTimer = setInterval(() => { - this.runStatistics(); + this.runStatistics(true); }, 1 * 60 * 1000); }, difference); } - private async runStatistics(): Promise { + public async runStatistics(skipIfRecent = false): Promise { if (!memPool.isInSync()) { return; } + + if (skipIfRecent && new Date().getTime() / 1000 - this.lastRun < 30) { + return; + } + + this.lastRun = new Date().getTime() / 1000; const currentMempool = memPool.getMempool(); const txPerSecond = memPool.getTxPerSecond(); const vBytesPerSecond = memPool.getVBytesPerSecond(); @@ -89,6 +96,9 @@ class Statistics { } }); + // get minFee and convert to sats/vb + const minFee = memPool.getMempoolInfo().mempoolminfee * 100000; + try { const insertId = await statisticsApi.$create({ added: 'NOW()', @@ -98,6 +108,7 @@ class Statistics { mempool_byte_weight: totalWeight, total_fee: totalFee, fee_data: '', + min_fee: minFee, vsize_1: weightVsizeFees['1'] || 0, vsize_2: weightVsizeFees['2'] || 0, vsize_3: weightVsizeFees['3'] || 0, diff --git a/backend/src/api/transaction-utils.ts b/backend/src/api/transaction-utils.ts index ef4a34012..9107f2ae7 100644 --- a/backend/src/api/transaction-utils.ts +++ b/backend/src/api/transaction-utils.ts @@ -116,7 +116,7 @@ class TransactionUtils { public extendMempoolTransaction(transaction: IEsploraApi.Transaction): MempoolTransactionExtended { const vsize = Math.ceil(transaction.weight / 4); const fractionalVsize = (transaction.weight / 4); - const sigops = !Common.isLiquid() ? this.countSigops(transaction) : 0; + let sigops = Common.isLiquid() ? 0 : (transaction.sigops != null ? transaction.sigops : this.countSigops(transaction)); // https://github.com/bitcoin/bitcoin/blob/e9262ea32a6e1d364fb7974844fadc36f931f8c6/src/policy/policy.cpp#L295-L298 const adjustedVsize = Math.max(fractionalVsize, sigops * 5); // adjusted vsize = Max(weight, sigops * bytes_per_sigop) / witness_scale_factor const feePerVbytes = (transaction.fee || 0) / fractionalVsize; @@ -145,6 +145,10 @@ class TransactionUtils { } public countScriptSigops(script: string, isRawScript: boolean = false, witness: boolean = false): number { + if (!script?.length) { + return 0; + } + let sigops = 0; // count OP_CHECKSIG and OP_CHECKSIGVERIFY sigops += (script.match(/OP_CHECKSIG/g)?.length || 0); @@ -155,7 +159,7 @@ class TransactionUtils { sigops += 20 * (script.match(/OP_CHECKMULTISIG/g)?.length || 0); } else { // in redeem scripts and witnesses, worth N if preceded by OP_N, 20 otherwise - const matches = script.matchAll(/(?:OP_(\d+))? OP_CHECKMULTISIG/g); + const matches = script.matchAll(/(?:OP_(?:PUSHNUM_)?(\d+))? OP_CHECKMULTISIG/g); for (const match of matches) { const n = parseInt(match[1]); if (Number.isInteger(n)) { @@ -189,6 +193,12 @@ class TransactionUtils { sigops += this.countScriptSigops(bitcoinjs.script.toASM(Buffer.from(input.witness[input.witness.length - 1], 'hex')), false, true); } break; + + case input.prevout.scriptpubkey_type === 'p2sh': + if (input.inner_redeemscript_asm) { + sigops += this.countScriptSigops(input.inner_redeemscript_asm); + } + break; } } } diff --git a/backend/src/api/tx-selection-worker.ts b/backend/src/api/tx-selection-worker.ts index 0acc2f65e..8ac7328fe 100644 --- a/backend/src/api/tx-selection-worker.ts +++ b/backend/src/api/tx-selection-worker.ts @@ -173,10 +173,13 @@ function makeBlockTemplates(mempool: Map) // this block is full const exceededPackageTries = failures > 1000 && blockWeight > (config.MEMPOOL.BLOCK_WEIGHT_UNITS - 4000); const queueEmpty = top >= mempoolArray.length && modified.isEmpty(); + if ((exceededPackageTries || queueEmpty) && blocks.length < 7) { // construct this block if (transactions.length) { blocks.push(transactions.map(t => t.uid)); + } else { + break; } // reset for the next block transactions = []; diff --git a/backend/src/api/websocket-handler.ts b/backend/src/api/websocket-handler.ts index 41cb6b99c..6711c88fb 100644 --- a/backend/src/api/websocket-handler.ts +++ b/backend/src/api/websocket-handler.ts @@ -23,6 +23,16 @@ import priceUpdater from '../tasks/price-updater'; import { ApiPrice } from '../repositories/PricesRepository'; import accelerationApi from './services/acceleration'; import mempool from './mempool'; +import statistics from './statistics/statistics'; +import accelerationCosts from './acceleration'; +import accelerationRepository from '../repositories/AccelerationRepository'; +import bitcoinApi from './bitcoin/bitcoin-api-factory'; + +interface AddressTransactions { + mempool: MempoolTransactionExtended[], + confirmed: MempoolTransactionExtended[], + removed: MempoolTransactionExtended[], +} // valid 'want' subscriptions const wantable = [ @@ -30,6 +40,7 @@ const wantable = [ 'mempool-blocks', 'live-2h-chart', 'stats', + 'tomahawk', ]; class WebsocketHandler { @@ -94,9 +105,13 @@ class WebsocketHandler { throw new Error('WebSocket.Server is not set'); } - this.wss.on('connection', (client: WebSocket) => { + this.wss.on('connection', (client: WebSocket, req) => { this.numConnected++; - client.on('error', logger.info); + client['remoteAddress'] = req.headers['x-forwarded-for'] || req.socket?.remoteAddress || 'unknown'; + client.on('error', (e) => { + logger.info(`websocket client error from ${client['remoteAddress']}: ` + (e instanceof Error ? e.message : e)); + client.close(); + }); client.on('close', () => { this.numDisconnected++; }); @@ -110,7 +125,7 @@ class WebsocketHandler { for (const sub of wantable) { const key = `want-${sub}`; const wants = parsedMessage.data.includes(sub); - if (wants && client['wants'] && !client[key]) { + if (wants && !client[key]) { wantNow[key] = true; } client[key] = wants; @@ -134,6 +149,10 @@ class WebsocketHandler { response['da'] = this.socketData['da']; } + if (wantNow['want-tomahawk']) { + response['tomahawk'] = JSON.stringify(bitcoinApi.getHealthStatus()); + } + if (parsedMessage && parsedMessage['track-tx']) { if (/^[a-fA-F0-9]{64}$/.test(parsedMessage['track-tx'])) { client['track-tx'] = parsedMessage['track-tx']; @@ -191,24 +210,49 @@ class WebsocketHandler { } if (parsedMessage && parsedMessage['track-address']) { - if (/^([a-km-zA-HJ-NP-Z1-9]{26,35}|[a-km-zA-HJ-NP-Z1-9]{80}|[a-z]{2,5}1[ac-hj-np-z02-9]{8,100}|[A-Z]{2,5}1[AC-HJ-NP-Z02-9]{8,100}|04[a-fA-F0-9]{128}|(02|03)[a-fA-F0-9]{64})$/ - .test(parsedMessage['track-address'])) { - let matchedAddress = parsedMessage['track-address']; - if (/^[A-Z]{2,5}1[AC-HJ-NP-Z02-9]{8,100}$/.test(parsedMessage['track-address'])) { - matchedAddress = matchedAddress.toLowerCase(); - } - if (/^04[a-fA-F0-9]{128}$/.test(parsedMessage['track-address'])) { - client['track-address'] = '41' + matchedAddress + 'ac'; - } else if (/^(02|03)[a-fA-F0-9]{64}$/.test(parsedMessage['track-address'])) { - client['track-address'] = '21' + matchedAddress + 'ac'; - } else { - client['track-address'] = matchedAddress; - } + const validAddress = this.testAddress(parsedMessage['track-address']); + if (validAddress) { + client['track-address'] = validAddress; } else { client['track-address'] = null; } } + if (parsedMessage && parsedMessage['track-addresses'] && Array.isArray(parsedMessage['track-addresses'])) { + const addressMap: { [address: string]: string } = {}; + for (const address of parsedMessage['track-addresses']) { + const validAddress = this.testAddress(address); + if (validAddress) { + addressMap[address] = validAddress; + } + } + if (Object.keys(addressMap).length > config.MEMPOOL.MAX_TRACKED_ADDRESSES) { + response['track-addresses-error'] = `"too many addresses requested, this connection supports tracking a maximum of ${config.MEMPOOL.MAX_TRACKED_ADDRESSES} addresses"`; + client['track-addresses'] = null; + } else if (Object.keys(addressMap).length > 0) { + client['track-addresses'] = addressMap; + } else { + client['track-addresses'] = null; + } + } + + if (parsedMessage && parsedMessage['track-scriptpubkeys'] && Array.isArray(parsedMessage['track-scriptpubkeys'])) { + const spks: string[] = []; + for (const spk of parsedMessage['track-scriptpubkeys']) { + if (/^[a-fA-F0-9]+$/.test(spk)) { + spks.push(spk.toLowerCase()); + } + } + if (spks.length > config.MEMPOOL.MAX_TRACKED_ADDRESSES) { + response['track-scriptpubkeys-error'] = `"too many scriptpubkeys requested, this connection supports tracking a maximum of ${config.MEMPOOL.MAX_TRACKED_ADDRESSES} scriptpubkeys"`; + client['track-scriptpubkeys'] = null; + } else if (spks.length) { + client['track-scriptpubkeys'] = spks; + } else { + client['track-scriptpubkeys'] = null; + } + } + if (parsedMessage && parsedMessage['track-asset']) { if (/^[a-fA-F0-9]{64}$/.test(parsedMessage['track-asset'])) { client['track-asset'] = parsedMessage['track-asset']; @@ -224,7 +268,7 @@ class WebsocketHandler { const mBlocksWithTransactions = mempoolBlocks.getMempoolBlocksWithTransactions(); response['projected-block-transactions'] = JSON.stringify({ index: index, - blockTransactions: mBlocksWithTransactions[index]?.transactions || [], + blockTransactions: (mBlocksWithTransactions[index]?.transactions || []).map(mempoolBlocks.compressTx), }); } else { client['track-mempool-block'] = null; @@ -278,11 +322,11 @@ class WebsocketHandler { } if (Object.keys(response).length) { - const serializedResponse = this.serializeResponse(response); - client.send(serializedResponse); + client.send(this.serializeResponse(response)); } } catch (e) { - logger.debug('Error parsing websocket message: ' + (e instanceof Error ? e.message : e)); + logger.debug(`Error parsing websocket message from ${client['remoteAddress']}: ` + (e instanceof Error ? e.message : e)); + client.close(); } }); }); @@ -387,8 +431,7 @@ class WebsocketHandler { } if (Object.keys(response).length) { - const serializedResponse = this.serializeResponse(response); - client.send(serializedResponse); + client.send(this.serializeResponse(response)); } }); } @@ -486,6 +529,7 @@ class WebsocketHandler { // pre-compute address transactions const addressCache = this.makeAddressCache(newTransactions); + const removedAddressCache = this.makeAddressCache(deletedTransactions); this.wss.clients.forEach(async (client) => { if (client.readyState !== WebSocket.OPEN) { @@ -508,6 +552,10 @@ class WebsocketHandler { response['mempool-blocks'] = getCachedResponse('mempool-blocks', mBlocks); } + if (client['want-tomahawk']) { + response['tomahawk'] = getCachedResponse('tomahawk', bitcoinApi.getHealthStatus()); + } + if (client['track-mempool-tx']) { const tx = newTransactions.find((t) => t.txid === client['track-mempool-tx']); if (tx) { @@ -526,16 +574,64 @@ class WebsocketHandler { } if (client['track-address']) { - const foundTransactions = Array.from(addressCache[client['track-address']]?.values() || []); + const newTransactions = Array.from(addressCache[client['track-address']]?.values() || []); + const removedTransactions = Array.from(removedAddressCache[client['track-address']]?.values() || []); // txs may be missing prevouts in non-esplora backends // so fetch the full transactions now - const fullTransactions = (config.MEMPOOL.BACKEND !== 'esplora') ? await this.getFullTransactions(foundTransactions) : foundTransactions; + const fullTransactions = (config.MEMPOOL.BACKEND !== 'esplora') ? await this.getFullTransactions(newTransactions) : newTransactions; + if (removedTransactions.length) { + response['address-removed-transactions'] = JSON.stringify(removedTransactions); + } if (fullTransactions.length) { response['address-transactions'] = JSON.stringify(fullTransactions); } } + if (client['track-addresses']) { + const addressMap: { [address: string]: AddressTransactions } = {}; + for (const [address, key] of Object.entries(client['track-addresses'] || {})) { + const newTransactions = Array.from(addressCache[key as string]?.values() || []); + const removedTransactions = Array.from(removedAddressCache[key as string]?.values() || []); + // txs may be missing prevouts in non-esplora backends + // so fetch the full transactions now + const fullTransactions = (config.MEMPOOL.BACKEND !== 'esplora') ? await this.getFullTransactions(newTransactions) : newTransactions; + if (fullTransactions?.length) { + addressMap[address] = { + mempool: fullTransactions, + confirmed: [], + removed: removedTransactions, + }; + } + } + + if (Object.keys(addressMap).length > 0) { + response['multi-address-transactions'] = JSON.stringify(addressMap); + } + } + + if (client['track-scriptpubkeys']) { + const spkMap: { [spk: string]: AddressTransactions } = {}; + for (const spk of client['track-scriptpubkeys'] || []) { + const newTransactions = Array.from(addressCache[spk as string]?.values() || []); + const removedTransactions = Array.from(removedAddressCache[spk as string]?.values() || []); + // txs may be missing prevouts in non-esplora backends + // so fetch the full transactions now + const fullTransactions = (config.MEMPOOL.BACKEND !== 'esplora') ? await this.getFullTransactions(newTransactions) : newTransactions; + if (fullTransactions?.length) { + spkMap[spk] = { + mempool: fullTransactions, + confirmed: [], + removed: removedTransactions, + }; + } + } + + if (Object.keys(spkMap).length > 0) { + response['multi-scriptpubkey-transactions'] = JSON.stringify(spkMap); + } + } + if (client['track-asset']) { const foundTransactions: TransactionExtended[] = []; @@ -572,7 +668,7 @@ class WebsocketHandler { response['utxoSpent'] = JSON.stringify(outspends); } - const rbfReplacedBy = rbfCache.getReplacedBy(client['track-tx']); + const rbfReplacedBy = rbfChanges.map[client['track-tx']] ? rbfCache.getReplacedBy(client['track-tx']) : false; if (rbfReplacedBy) { response['rbfTransaction'] = JSON.stringify({ txid: rbfReplacedBy, @@ -629,8 +725,7 @@ class WebsocketHandler { } if (Object.keys(response).length) { - const serializedResponse = this.serializeResponse(response); - client.send(serializedResponse); + client.send(this.serializeResponse(response)); } }); } @@ -641,9 +736,32 @@ class WebsocketHandler { } this.printLogs(); + await statistics.runStatistics(); const _memPool = memPool.getMempool(); + const isAccelerated = config.MEMPOOL_SERVICES.ACCELERATIONS && accelerationApi.isAcceleratedBlock(block, Object.values(mempool.getAccelerations())); + + + if (isAccelerated) { + const blockTxs: { [txid: string]: MempoolTransactionExtended } = {}; + for (const tx of transactions) { + blockTxs[tx.txid] = tx; + } + const accelerations = Object.values(mempool.getAccelerations()); + const boostRate = accelerationCosts.calculateBoostRate( + accelerations.map(acc => ({ txid: acc.txid, max_bid: acc.feeDelta })), + transactions + ); + for (const acc of accelerations) { + if (blockTxs[acc.txid]) { + const tx = blockTxs[acc.txid]; + const accelerationInfo = accelerationCosts.getAccelerationInfo(tx, boostRate, transactions); + accelerationRepository.$saveAcceleration(accelerationInfo, block, block.extras.pool.id); + } + } + } + const rbfTransactions = Common.findMinedRbfTransactions(transactions, memPool.getSpendMap()); memPool.handleMinedRbfTransactions(rbfTransactions); memPool.removeFromSpendMap(transactions); @@ -651,7 +769,6 @@ class WebsocketHandler { if (config.MEMPOOL.AUDIT && memPool.isInSync()) { let projectedBlocks; let auditMempool = _memPool; - const isAccelerated = config.MEMPOOL_SERVICES.ACCELERATIONS && accelerationApi.isAcceleratedBlock(block, Object.values(mempool.getAccelerations())); // template calculation functions have mempool side effects, so calculate audits using // a cloned copy of the mempool if we're running a different algorithm for mempool updates const separateAudit = config.MEMPOOL.ADVANCED_GBT_AUDIT !== config.MEMPOOL.ADVANCED_GBT_MEMPOOL; @@ -696,7 +813,8 @@ class WebsocketHandler { template: { id: block.id, transactions: stripped, - } + }, + version: 1, }); BlocksAuditsRepository.$saveAudit({ @@ -728,10 +846,13 @@ class WebsocketHandler { } } + const confirmedTxids: { [txid: string]: boolean } = {}; + // Update mempool to remove transactions included in the new block for (const txId of txIds) { delete _memPool[txId]; rbfCache.mined(txId); + confirmedTxids[txId] = true; } if (config.MEMPOOL.ADVANCED_GBT_MEMPOOL) { @@ -763,6 +884,8 @@ class WebsocketHandler { 'fees': fees, }); + const mBlocksWithTransactions = mempoolBlocks.getMempoolBlocksWithTransactions(); + const responseCache = { ...this.socketData }; function getCachedResponse(key, data): string { if (!responseCache[key]) { @@ -796,9 +919,13 @@ class WebsocketHandler { response['mempool-blocks'] = getCachedResponse('mempool-blocks', mBlocks); } + if (client['want-tomahawk']) { + response['tomahawk'] = getCachedResponse('tomahawk', bitcoinApi.getHealthStatus()); + } + if (client['track-tx']) { const trackTxid = client['track-tx']; - if (trackTxid && txIds.indexOf(trackTxid) > -1) { + if (trackTxid && confirmedTxids[trackTxid]) { response['txConfirmed'] = JSON.stringify(trackTxid); } else { const mempoolTx = _memPool[trackTxid]; @@ -831,6 +958,42 @@ class WebsocketHandler { } } + if (client['track-addresses']) { + const addressMap: { [address: string]: AddressTransactions } = {}; + for (const [address, key] of Object.entries(client['track-addresses'] || {})) { + const fullTransactions = Array.from(addressCache[key as string]?.values() || []); + if (fullTransactions?.length) { + addressMap[address] = { + mempool: [], + confirmed: fullTransactions, + removed: [], + }; + } + } + + if (Object.keys(addressMap).length > 0) { + response['multi-address-transactions'] = JSON.stringify(addressMap); + } + } + + if (client['track-scriptpubkeys']) { + const spkMap: { [spk: string]: AddressTransactions } = {}; + for (const spk of client['track-scriptpubkeys'] || []) { + const fullTransactions = Array.from(addressCache[spk as string]?.values() || []); + if (fullTransactions?.length) { + spkMap[spk] = { + mempool: [], + confirmed: fullTransactions, + removed: [], + }; + } + } + + if (Object.keys(spkMap).length > 0) { + response['multi-scriptpubkey-transactions'] = JSON.stringify(spkMap); + } + } + if (client['track-asset']) { const foundTransactions: TransactionExtended[] = []; @@ -870,19 +1033,28 @@ class WebsocketHandler { if (client['track-mempool-block'] >= 0 && memPool.isInSync()) { const index = client['track-mempool-block']; - if (mBlockDeltas && mBlockDeltas[index]) { - response['projected-block-transactions'] = getCachedResponse(`projected-block-transactions-${index}`, { - index: index, - delta: mBlockDeltas[index], - }); + + if (mBlockDeltas && mBlockDeltas[index] && mBlocksWithTransactions[index]?.transactions?.length) { + if (mBlockDeltas[index].added.length > (mBlocksWithTransactions[index]?.transactions.length / 2)) { + response['projected-block-transactions'] = getCachedResponse(`projected-block-transactions-full-${index}`, { + index: index, + blockTransactions: mBlocksWithTransactions[index].transactions.map(mempoolBlocks.compressTx), + }); + } else { + response['projected-block-transactions'] = getCachedResponse(`projected-block-transactions-delta-${index}`, { + index: index, + delta: mBlockDeltas[index], + }); + } } } if (Object.keys(response).length) { - const serializedResponse = this.serializeResponse(response); - client.send(serializedResponse); + client.send(this.serializeResponse(response)); } }); + + await statistics.runStatistics(); } // takes a dictionary of JSON serialized values @@ -893,6 +1065,28 @@ class WebsocketHandler { + '}'; } + // checks if an address conforms to a valid format + // returns the canonical form: + // - lowercase for bech32(m) + // - lowercase scriptpubkey for P2PK + // or false if invalid + private testAddress(address): string | false { + if (/^([a-km-zA-HJ-NP-Z1-9]{26,35}|[a-km-zA-HJ-NP-Z1-9]{80}|[a-z]{2,5}1[ac-hj-np-z02-9]{8,100}|[A-Z]{2,5}1[AC-HJ-NP-Z02-9]{8,100}|04[a-fA-F0-9]{128}|(02|03)[a-fA-F0-9]{64})$/.test(address)) { + if (/^[A-Z]{2,5}1[AC-HJ-NP-Z02-9]{8,100}|04[a-fA-F0-9]{128}|(02|03)[a-fA-F0-9]{64}$/.test(address)) { + address = address.toLowerCase(); + } + if (/^04[a-fA-F0-9]{128}$/.test(address)) { + return '41' + address + 'ac'; + } else if (/^(02|03)[a-fA-F0-9]{64}$/.test(address)) { + return '21' + address + 'ac'; + } else { + return address; + } + } else { + return false; + } + } + private makeAddressCache(transactions: MempoolTransactionExtended[]): { [address: string]: Set } { const addressCache: { [address: string]: Set } = {}; for (const tx of transactions) { @@ -941,10 +1135,27 @@ class WebsocketHandler { private printLogs(): void { if (this.wss) { + let numTxSubs = 0; + let numProjectedSubs = 0; + let numRbfSubs = 0; + + this.wss.clients.forEach((client) => { + if (client['track-tx']) { + numTxSubs++; + } + if (client['track-mempool-block'] != null && client['track-mempool-block'] >= 0) { + numProjectedSubs++; + } + if (client['track-rbf']) { + numRbfSubs++; + } + }) + const count = this.wss?.clients?.size || 0; const diff = count - this.numClients; this.numClients = count; logger.debug(`${count} websocket clients | ${this.numConnected} connected | ${this.numDisconnected} disconnected | (${diff >= 0 ? '+' : ''}${diff})`); + logger.debug(`websocket subscriptions: track-tx: ${numTxSubs}, track-mempool-block: ${numProjectedSubs} track-rbf: ${numRbfSubs}`); this.numConnected = 0; this.numDisconnected = 0; } diff --git a/backend/src/config.ts b/backend/src/config.ts index ed320d957..3330adca0 100644 --- a/backend/src/config.ts +++ b/backend/src/config.ts @@ -5,6 +5,7 @@ const configFromFile = require( interface IConfig { MEMPOOL: { ENABLED: boolean; + OFFICIAL: boolean; NETWORK: 'mainnet' | 'testnet' | 'signet' | 'liquid' | 'liquidtestnet'; BACKEND: 'esplora' | 'electrum' | 'none'; HTTP_PORT: number; @@ -20,6 +21,7 @@ interface IConfig { MEMPOOL_BLOCKS_AMOUNT: number; INDEXING_BLOCKS_AMOUNT: number; BLOCKS_SUMMARIES_INDEXING: boolean; + GOGGLES_INDEXING: boolean; USE_SECOND_NODE_FOR_MINFEE: boolean; EXTERNAL_ASSETS: string[]; EXTERNAL_MAX_RETRY: number; @@ -39,11 +41,15 @@ interface IConfig { MAX_PUSH_TX_SIZE_WEIGHT: number; ALLOW_UNREACHABLE: boolean; PRICE_UPDATES_PER_HOUR: number; + MAX_TRACKED_ADDRESSES: number; }; ESPLORA: { REST_API_URL: string; UNIX_SOCKET_PATH: string | void | null; + BATCH_QUERY_BASE_SIZE: number; RETRY_UNIX_SOCKET_AFTER: number; + REQUEST_TIMEOUT: number; + FALLBACK_TIMEOUT: number; FALLBACK: string[]; }; LIGHTNING: { @@ -76,6 +82,8 @@ interface IConfig { USERNAME: string; PASSWORD: string; TIMEOUT: number; + COOKIE: boolean; + COOKIE_PATH: string; }; SECOND_CORE_RPC: { HOST: string; @@ -83,6 +91,8 @@ interface IConfig { USERNAME: string; PASSWORD: string; TIMEOUT: number; + COOKIE: boolean; + COOKIE_PATH: string; }; DATABASE: { ENABLED: boolean; @@ -93,6 +103,8 @@ interface IConfig { USERNAME: string; PASSWORD: string; TIMEOUT: number; + PID_DIR: string; + POOL_SIZE: number; }; SYSLOG: { ENABLED: boolean; @@ -144,12 +156,14 @@ interface IConfig { REDIS: { ENABLED: boolean; UNIX_SOCKET_PATH: string; + BATCH_QUERY_BASE_SIZE: number; }, } const defaults: IConfig = { 'MEMPOOL': { 'ENABLED': true, + 'OFFICIAL': false, 'NETWORK': 'mainnet', 'BACKEND': 'none', 'HTTP_PORT': 8999, @@ -165,6 +179,7 @@ const defaults: IConfig = { 'MEMPOOL_BLOCKS_AMOUNT': 8, 'INDEXING_BLOCKS_AMOUNT': 11000, // 0 = disable indexing, -1 = index all blocks 'BLOCKS_SUMMARIES_INDEXING': false, + 'GOGGLES_INDEXING': false, 'USE_SECOND_NODE_FOR_MINFEE': false, 'EXTERNAL_ASSETS': [], 'EXTERNAL_MAX_RETRY': 1, @@ -184,11 +199,15 @@ const defaults: IConfig = { 'MAX_PUSH_TX_SIZE_WEIGHT': 400000, 'ALLOW_UNREACHABLE': true, 'PRICE_UPDATES_PER_HOUR': 1, + 'MAX_TRACKED_ADDRESSES': 1, }, 'ESPLORA': { 'REST_API_URL': 'http://127.0.0.1:3000', 'UNIX_SOCKET_PATH': null, + 'BATCH_QUERY_BASE_SIZE': 1000, 'RETRY_UNIX_SOCKET_AFTER': 30000, + 'REQUEST_TIMEOUT': 10000, + 'FALLBACK_TIMEOUT': 5000, 'FALLBACK': [], }, 'ELECTRUM': { @@ -202,6 +221,8 @@ const defaults: IConfig = { 'USERNAME': 'mempool', 'PASSWORD': 'mempool', 'TIMEOUT': 60000, + 'COOKIE': false, + 'COOKIE_PATH': '/bitcoin/.cookie' }, 'SECOND_CORE_RPC': { 'HOST': '127.0.0.1', @@ -209,6 +230,8 @@ const defaults: IConfig = { 'USERNAME': 'mempool', 'PASSWORD': 'mempool', 'TIMEOUT': 60000, + 'COOKIE': false, + 'COOKIE_PATH': '/bitcoin/.cookie' }, 'DATABASE': { 'ENABLED': true, @@ -219,6 +242,8 @@ const defaults: IConfig = { 'USERNAME': 'mempool', 'PASSWORD': 'mempool', 'TIMEOUT': 180000, + 'PID_DIR': '', + 'POOL_SIZE': 100, }, 'SYSLOG': { 'ENABLED': true, @@ -289,6 +314,7 @@ const defaults: IConfig = { 'REDIS': { 'ENABLED': false, 'UNIX_SOCKET_PATH': '', + 'BATCH_QUERY_BASE_SIZE': 5000, }, }; diff --git a/backend/src/database.ts b/backend/src/database.ts index 6ad545fda..05f624ff4 100644 --- a/backend/src/database.ts +++ b/backend/src/database.ts @@ -1,7 +1,11 @@ +import * as fs from 'fs'; +import path from 'path'; import config from './config'; import { createPool, Pool, PoolConnection } from 'mysql2/promise'; +import { LogLevel } from './logger'; import logger from './logger'; import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } from 'mysql2/typings/mysql'; +import { execSync } from 'child_process'; class DB { constructor() { @@ -17,7 +21,7 @@ import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } fr database: config.DATABASE.DATABASE, user: config.DATABASE.USERNAME, password: config.DATABASE.PASSWORD, - connectionLimit: 10, + connectionLimit: config.DATABASE.POOL_SIZE, supportBigNumbers: true, timezone: '+00:00', }; @@ -30,7 +34,7 @@ import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } fr } public async query(query, params?, connection?: PoolConnection): Promise<[T, FieldPacket[]]> + OkPacket[] | ResultSetHeader>(query, params?, errorLogLevel: LogLevel | 'silent' = 'debug', connection?: PoolConnection): Promise<[T, FieldPacket[]]> { this.checkDBFlag(); let hardTimeout; @@ -52,19 +56,38 @@ import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } fr }).then(result => { resolve(result); }).catch(error => { + if (errorLogLevel !== 'silent') { + logger[errorLogLevel](`database query "${query?.sql?.slice(0, 160) || (typeof(query) === 'string' || query instanceof String ? query?.slice(0, 160) : 'unknown query')}" failed!`); + } reject(error); }).finally(() => { clearTimeout(timer); }); }); } else { - const pool = await this.getPool(); - return pool.query(query, params); + try { + const pool = await this.getPool(); + return pool.query(query, params); + } catch (e) { + if (errorLogLevel !== 'silent') { + logger[errorLogLevel](`database query "${query?.sql?.slice(0, 160) || (typeof(query) === 'string' || query instanceof String ? query?.slice(0, 160) : 'unknown query')}" failed!`); + } + throw e; + } + } + } + + private async $rollbackAtomic(connection: PoolConnection): Promise { + try { + await connection.rollback(); + await connection.release(); + } catch (e) { + logger.warn('Failed to rollback incomplete db transaction: ' + (e instanceof Error ? e.message : e)); } } public async $atomicQuery(queries: { query, params }[]): Promise<[T, FieldPacket[]][]> + OkPacket[] | ResultSetHeader>(queries: { query, params }[], errorLogLevel: LogLevel | 'silent' = 'debug'): Promise<[T, FieldPacket[]][]> { const pool = await this.getPool(); const connection = await pool.getConnection(); @@ -73,7 +96,7 @@ import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } fr const results: [T, FieldPacket[]][] = []; for (const query of queries) { - const result = await this.query(query.query, query.params, connection) as [T, FieldPacket[]]; + const result = await this.query(query.query, query.params, errorLogLevel, connection) as [T, FieldPacket[]]; results.push(result); } @@ -81,9 +104,8 @@ import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } fr return results; } catch (e) { - logger.err('Could not complete db transaction, rolling back: ' + (e instanceof Error ? e.message : e)); - connection.rollback(); - connection.release(); + logger.warn('Could not complete db transaction, rolling back: ' + (e instanceof Error ? e.message : e)); + this.$rollbackAtomic(connection); throw e; } finally { connection.release(); @@ -101,6 +123,50 @@ import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } fr } } + public getPidLock(): boolean { + const filePath = path.join(config.DATABASE.PID_DIR || __dirname, `/mempool-${config.DATABASE.DATABASE}.pid`); + this.enforcePidLock(filePath); + fs.writeFileSync(filePath, `${process.pid}`); + return true; + } + + private enforcePidLock(filePath: string): void { + if (fs.existsSync(filePath)) { + const pid = parseInt(fs.readFileSync(filePath, 'utf-8')); + if (pid === process.pid) { + logger.warn('PID file already exists for this process'); + return; + } + + let cmd; + try { + cmd = execSync(`ps -p ${pid} -o args=`); + } catch (e) { + logger.warn(`Stale PID file at ${filePath}, but no process running on that PID ${pid}`); + return; + } + + if (cmd && cmd.toString()?.includes('node')) { + const msg = `Another mempool nodejs process is already running on PID ${pid}`; + logger.err(msg); + throw new Error(msg); + } else { + logger.warn(`Stale PID file at ${filePath}, but the PID ${pid} does not belong to a running mempool instance`); + } + } + } + + public releasePidLock(): void { + const filePath = path.join(config.DATABASE.PID_DIR || __dirname, `/mempool-${config.DATABASE.DATABASE}.pid`); + if (fs.existsSync(filePath)) { + const pid = parseInt(fs.readFileSync(filePath, 'utf-8')); + // only release our own pid file + if (pid === process.pid) { + fs.unlinkSync(filePath); + } + } + } + private async getPool(): Promise { if (this.pool === null) { this.pool = createPool(this.poolConfig); diff --git a/backend/src/index.ts b/backend/src/index.ts index 9d0fa07f5..3a8449131 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -43,6 +43,8 @@ import { AxiosError } from 'axios'; import v8 from 'v8'; import { formatBytes, getBytesUnit } from './utils/format'; import redisCache from './api/redis-cache'; +import accelerationApi from './api/services/acceleration'; +import bitcoinCoreRoutes from './api/bitcoin/bitcoin-core.routes'; class Server { private wss: WebSocket.Server | undefined; @@ -91,11 +93,24 @@ class Server { async startServer(worker = false): Promise { logger.notice(`Starting Mempool Server${worker ? ' (worker)' : ''}... (${backendInfo.getShortCommitHash()})`); + // Register cleanup listeners for exit events + ['exit', 'SIGHUP', 'SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(event => { + process.on(event, () => { this.onExit(event); }); + }); + process.on('uncaughtException', (error) => { + this.onUnhandledException('uncaughtException', error); + }); + process.on('unhandledRejection', (reason, promise) => { + this.onUnhandledException('unhandledRejection', reason); + }); + if (config.MEMPOOL.BACKEND === 'esplora') { bitcoinApi.startHealthChecks(); } if (config.DATABASE.ENABLED) { + DB.getPidLock(); + await DB.checkDbConnection(); try { if (process.env.npm_config_reindex_blocks === 'true') { // Re-index requests @@ -192,10 +207,11 @@ class Server { } } const newMempool = await bitcoinApi.$getRawMempool(); + const newAccelerations = await accelerationApi.$fetchAccelerations(); const numHandledBlocks = await blocks.$updateBlocks(); - const pollRate = config.MEMPOOL.POLL_RATE_MS * (indexer.indexerRunning ? 10 : 1); + const pollRate = config.MEMPOOL.POLL_RATE_MS * (indexer.indexerIsRunning() ? 10 : 1); if (numHandledBlocks === 0) { - await memPool.$updateMempool(newMempool, pollRate); + await memPool.$updateMempool(newMempool, newAccelerations, pollRate); } indexer.$run(); priceUpdater.$run(); @@ -250,6 +266,7 @@ class Server { blocks.setNewBlockCallback(async () => { try { await elementsParser.$parse(); + await elementsParser.$updateFederationUtxos(); } catch (e) { logger.warn('Elements parsing error: ' + (e instanceof Error ? e.message : e)); } @@ -267,6 +284,7 @@ class Server { setUpHttpApiRoutes(): void { bitcoinRoutes.initRoutes(this.app); + bitcoinCoreRoutes.initRoutes(this.app); pricesRoutes.initRoutes(this.app); if (config.STATISTICS.ENABLED && config.DATABASE.ENABLED && config.MEMPOOL.ENABLED) { statisticsRoutes.initRoutes(this.app); @@ -306,6 +324,19 @@ class Server { this.lastHeapLogTime = now; } } + + onExit(exitEvent, code = 0): void { + logger.debug(`onExit for signal: ${exitEvent}`); + if (config.DATABASE.ENABLED) { + DB.releasePidLock(); + } + process.exit(code); + } + + onUnhandledException(type, error): void { + console.error(`${type}:`, error); + this.onExit(type, 1); + } } ((): Server => new Server())(); diff --git a/backend/src/indexer.ts b/backend/src/indexer.ts index 7ec65d9c9..dcb91d010 100644 --- a/backend/src/indexer.ts +++ b/backend/src/indexer.ts @@ -15,11 +15,18 @@ export interface CoreIndex { best_block_height: number; } +type TaskName = 'blocksPrices' | 'coinStatsIndex'; + class Indexer { - runIndexer = true; - indexerRunning = false; - tasksRunning: string[] = []; - coreIndexes: CoreIndex[] = []; + private runIndexer = true; + private indexerRunning = false; + private tasksRunning: { [key in TaskName]?: boolean; } = {}; + private tasksScheduled: { [key in TaskName]?: NodeJS.Timeout; } = {}; + private coreIndexes: CoreIndex[] = []; + + public indexerIsRunning(): boolean { + return this.indexerRunning; + } /** * Check which core index is available for indexing @@ -69,33 +76,69 @@ class Indexer { } } - public async runSingleTask(task: 'blocksPrices' | 'coinStatsIndex'): Promise { - if (!Common.indexingEnabled()) { - return; - } - - if (task === 'blocksPrices' && !this.tasksRunning.includes(task) && !['testnet', 'signet'].includes(config.MEMPOOL.NETWORK)) { - this.tasksRunning.push(task); - const lastestPriceId = await PricesRepository.$getLatestPriceId(); - if (priceUpdater.historyInserted === false || lastestPriceId === null) { - logger.debug(`Blocks prices indexer is waiting for the price updater to complete`, logger.tags.mining); - setTimeout(() => { - this.tasksRunning = this.tasksRunning.filter(runningTask => runningTask !== task); - this.runSingleTask('blocksPrices'); - }, 10000); - } else { - logger.debug(`Blocks prices indexer will run now`, logger.tags.mining); - await mining.$indexBlockPrices(); - this.tasksRunning = this.tasksRunning.filter(runningTask => runningTask !== task); + /** + * schedules a single task to run in `timeout` ms + * only one task of each type may be scheduled + * + * @param {TaskName} task - the type of task + * @param {number} timeout - delay in ms + * @param {boolean} replace - `true` replaces any already scheduled task (works like a debounce), `false` ignores subsequent requests (works like a throttle) + */ + public scheduleSingleTask(task: TaskName, timeout: number = 10000, replace = false): void { + if (this.tasksScheduled[task]) { + if (!replace) { //throttle + return; + } else { // debounce + clearTimeout(this.tasksScheduled[task]); } } + this.tasksScheduled[task] = setTimeout(async () => { + try { + await this.runSingleTask(task); + } catch (e) { + logger.err(`Unexpected error in scheduled task ${task}: ` + (e instanceof Error ? e.message : e)); + } finally { + clearTimeout(this.tasksScheduled[task]); + } + }, timeout); + } - if (task === 'coinStatsIndex' && !this.tasksRunning.includes(task)) { - this.tasksRunning.push(task); - logger.debug(`Indexing coinStatsIndex now`); - await mining.$indexCoinStatsIndex(); - this.tasksRunning = this.tasksRunning.filter(runningTask => runningTask !== task); + /** + * Runs a single task immediately + * + * (use `scheduleSingleTask` instead to queue a task to run after some timeout) + */ + public async runSingleTask(task: TaskName): Promise { + if (!Common.indexingEnabled() || this.tasksRunning[task]) { + return; } + this.tasksRunning[task] = true; + + switch (task) { + case 'blocksPrices': { + if (!['testnet', 'signet'].includes(config.MEMPOOL.NETWORK)) { + let lastestPriceId; + try { + lastestPriceId = await PricesRepository.$getLatestPriceId(); + } catch (e) { + logger.debug('failed to fetch latest price id from db: ' + (e instanceof Error ? e.message : e)); + } if (priceUpdater.historyInserted === false || lastestPriceId === null) { + logger.debug(`Blocks prices indexer is waiting for the price updater to complete`, logger.tags.mining); + this.scheduleSingleTask(task, 10000); + } else { + logger.debug(`Blocks prices indexer will run now`, logger.tags.mining); + await mining.$indexBlockPrices(); + } + } + } break; + + case 'coinStatsIndex': { + logger.debug(`Indexing coinStatsIndex now`); + await mining.$indexCoinStatsIndex(); + } break; + } + + this.tasksRunning[task] = false; } public async $run(): Promise { @@ -142,6 +185,8 @@ class Indexer { await blocks.$generateCPFPDatabase(); await blocks.$generateAuditStats(); await auditReplicator.$sync(); + // do not wait for classify blocks to finish + blocks.$classifyBlocks(); } catch (e) { this.indexerRunning = false; logger.err(`Indexer failed, trying again in 10 seconds. Reason: ` + (e instanceof Error ? e.message : e)); diff --git a/backend/src/logger.ts b/backend/src/logger.ts index efafe894e..bbd781df6 100644 --- a/backend/src/logger.ts +++ b/backend/src/logger.ts @@ -35,6 +35,7 @@ class Logger { public tags = { mining: 'Mining', ln: 'Lightning', + goggles: 'Goggles', }; // @ts-ignore @@ -157,4 +158,6 @@ class Logger { } } +export type LogLevel = 'emerg' | 'alert' | 'crit' | 'err' | 'warn' | 'notice' | 'info' | 'debug'; + export default new Logger(); diff --git a/backend/src/mempool.interfaces.ts b/backend/src/mempool.interfaces.ts index b013f2f26..b68b137bb 100644 --- a/backend/src/mempool.interfaces.ts +++ b/backend/src/mempool.interfaces.ts @@ -61,13 +61,13 @@ export interface MempoolBlock { export interface MempoolBlockWithTransactions extends MempoolBlock { transactionIds: string[]; - transactions: TransactionStripped[]; + transactions: TransactionClassified[]; } export interface MempoolBlockDelta { - added: TransactionStripped[]; + added: TransactionCompressed[]; removed: string[]; - changed: { txid: string, rate: number | undefined }[]; + changed: MempoolDeltaChange[]; } interface VinStrippedToScriptsig { @@ -94,7 +94,9 @@ export interface TransactionExtended extends IEsploraApi.Transaction { vsize: number, }; acceleration?: boolean; + replacement?: boolean; uid?: number; + flags?: number; } export interface MempoolTransactionExtended extends TransactionExtended { @@ -190,6 +192,52 @@ export interface TransactionStripped { rate?: number; // effective fee rate } +export interface TransactionClassified extends TransactionStripped { + flags: number; +} + +// [txid, fee, vsize, value, rate, flags, acceleration?] +export type TransactionCompressed = [string, number, number, number, number, number, 1?]; +// [txid, rate, flags, acceleration?] +export type MempoolDeltaChange = [string, number, number, (1|0)]; + +// binary flags for transaction classification +export const TransactionFlags = { + // features + rbf: 0b00000001n, + no_rbf: 0b00000010n, + v1: 0b00000100n, + v2: 0b00001000n, + v3: 0b00010000n, + nonstandard: 0b00100000n, + // address types + p2pk: 0b00000001_00000000n, + p2ms: 0b00000010_00000000n, + p2pkh: 0b00000100_00000000n, + p2sh: 0b00001000_00000000n, + p2wpkh: 0b00010000_00000000n, + p2wsh: 0b00100000_00000000n, + p2tr: 0b01000000_00000000n, + // behavior + cpfp_parent: 0b00000001_00000000_00000000n, + cpfp_child: 0b00000010_00000000_00000000n, + replacement: 0b00000100_00000000_00000000n, + // data + op_return: 0b00000001_00000000_00000000_00000000n, + fake_pubkey: 0b00000010_00000000_00000000_00000000n, + inscription: 0b00000100_00000000_00000000_00000000n, + // heuristics + coinjoin: 0b00000001_00000000_00000000_00000000_00000000n, + consolidation: 0b00000010_00000000_00000000_00000000_00000000n, + batch_payout: 0b00000100_00000000_00000000_00000000_00000000n, + // sighash + sighash_all: 0b00000001_00000000_00000000_00000000_00000000_00000000n, + sighash_none: 0b00000010_00000000_00000000_00000000_00000000_00000000n, + sighash_single: 0b00000100_00000000_00000000_00000000_00000000_00000000n, + sighash_default:0b00001000_00000000_00000000_00000000_00000000_00000000n, + sighash_acp: 0b00010000_00000000_00000000_00000000_00000000_00000000n, +}; + export interface BlockExtension { totalFees: number; medianFee: number; // median fee rate @@ -239,7 +287,8 @@ export interface BlockExtended extends IEsploraApi.Block { export interface BlockSummary { id: string; - transactions: TransactionStripped[]; + transactions: TransactionClassified[]; + version?: number; } export interface AuditSummary extends BlockAudit { @@ -247,8 +296,8 @@ export interface AuditSummary extends BlockAudit { size?: number, weight?: number, tx_count?: number, - transactions: TransactionStripped[]; - template?: TransactionStripped[]; + transactions: TransactionClassified[]; + template?: TransactionClassified[]; } export interface BlockPrice { @@ -300,6 +349,7 @@ export interface Statistic { total_fee: number; mempool_byte_weight: number; fee_data: string; + min_fee: number; vsize_1: number; vsize_2: number; @@ -346,6 +396,7 @@ export interface OptimizedStatistic { vbytes_per_second: number; total_fee: number; mempool_byte_weight: number; + min_fee: number; vsizes: number[]; } diff --git a/backend/src/replication/AuditReplication.ts b/backend/src/replication/AuditReplication.ts index 5de9de0da..503c61613 100644 --- a/backend/src/replication/AuditReplication.ts +++ b/backend/src/replication/AuditReplication.ts @@ -105,7 +105,8 @@ class AuditReplication { template: { id: blockHash, transactions: auditSummary.template || [] - } + }, + version: 1, }); await blocksAuditsRepository.$saveAudit({ hash: blockHash, diff --git a/backend/src/repositories/AccelerationRepository.ts b/backend/src/repositories/AccelerationRepository.ts new file mode 100644 index 000000000..868f8526f --- /dev/null +++ b/backend/src/repositories/AccelerationRepository.ts @@ -0,0 +1,109 @@ +import { AccelerationInfo } from '../api/acceleration'; +import { ResultSetHeader, RowDataPacket } from 'mysql2'; +import DB from '../database'; +import logger from '../logger'; +import { IEsploraApi } from '../api/bitcoin/esplora-api.interface'; +import { Common } from '../api/common'; +import config from '../config'; + +export interface PublicAcceleration { + txid: string, + height: number, + pool: { + id: number, + slug: string, + name: string, + }, + effective_vsize: number, + effective_fee: number, + boost_rate: number, + boost_cost: number, +} + +class AccelerationRepository { + public async $saveAcceleration(acceleration: AccelerationInfo, block: IEsploraApi.Block, pool_id: number): Promise { + try { + await DB.query(` + INSERT INTO accelerations(txid, added, height, pool, effective_vsize, effective_fee, boost_rate, boost_cost) + VALUE (?, FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + added = FROM_UNIXTIME(?), + height = ?, + pool = ?, + effective_vsize = ?, + effective_fee = ?, + boost_rate = ?, + boost_cost = ? + `, [ + acceleration.txSummary.txid, + block.timestamp, + block.height, + pool_id, + acceleration.txSummary.effectiveVsize, + acceleration.txSummary.effectiveFee, + acceleration.targetFeeRate, acceleration.cost, + block.timestamp, + block.height, + pool_id, + acceleration.txSummary.effectiveVsize, + acceleration.txSummary.effectiveFee, + acceleration.targetFeeRate, acceleration.cost, + ]); + } catch (e: any) { + logger.err(`Cannot save acceleration (${acceleration.txSummary.txid}) into db. Reason: ` + (e instanceof Error ? e.message : e)); + // We don't throw, not a critical issue if we miss some accelerations + } + } + + public async $getAccelerationInfo(poolSlug: string | null = null, height: number | null = null, interval: string | null = null): Promise { + interval = Common.getSqlInterval(interval); + + if (!config.MEMPOOL_SERVICES.ACCELERATIONS || (interval == null && poolSlug == null && height == null)) { + return []; + } + + let query = ` + SELECT * FROM accelerations + JOIN pools on pools.unique_id = accelerations.pool + `; + let params: any[] = []; + + if (interval) { + query += ` WHERE accelerations.added BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW() `; + } else if (height != null) { + query += ` WHERE accelerations.height = ? `; + params.push(height); + } else if (poolSlug != null) { + query += ` WHERE pools.slug = ? `; + params.push(poolSlug); + } + + query += ` ORDER BY accelerations.added DESC `; + + try { + const [rows] = await DB.query(query, params) as RowDataPacket[][]; + if (rows?.length) { + return rows.map(row => ({ + txid: row.txid, + height: row.height, + pool: { + id: row.id, + slug: row.slug, + name: row.name, + }, + effective_vsize: row.effective_vsize, + effective_fee: row.effective_fee, + boost_rate: row.boost_rate, + boost_cost: row.boost_cost, + })); + } else { + return []; + } + } catch (e) { + logger.err(`Cannot query acceleration info. Reason: ` + (e instanceof Error ? e.message : e)); + throw e; + } + } +} + +export default new AccelerationRepository(); diff --git a/backend/src/repositories/BlocksAuditsRepository.ts b/backend/src/repositories/BlocksAuditsRepository.ts index c17958d2b..62f28c56f 100644 --- a/backend/src/repositories/BlocksAuditsRepository.ts +++ b/backend/src/repositories/BlocksAuditsRepository.ts @@ -59,7 +59,7 @@ class BlocksAuditRepositories { } } - public async $getBlockAudit(hash: string): Promise { + public async $getBlockAudit(hash: string): Promise { try { const [rows]: any[] = await DB.query( `SELECT blocks_audits.height, blocks_audits.hash as id, UNIX_TIMESTAMP(blocks_audits.time) as timestamp, @@ -75,8 +75,8 @@ class BlocksAuditRepositories { expected_weight as expectedWeight FROM blocks_audits JOIN blocks_templates ON blocks_templates.id = blocks_audits.hash - WHERE blocks_audits.hash = "${hash}" - `); + WHERE blocks_audits.hash = ? + `, [hash]); if (rows.length) { rows[0].missingTxs = JSON.parse(rows[0].missingTxs); @@ -101,8 +101,8 @@ class BlocksAuditRepositories { const [rows]: any[] = await DB.query( `SELECT hash, match_rate as matchRate, expected_fees as expectedFees, expected_weight as expectedWeight FROM blocks_audits - WHERE blocks_audits.hash = "${hash}" - `); + WHERE blocks_audits.hash = ? + `, [hash]); return rows[0]; } catch (e: any) { logger.err(`Cannot fetch block audit from db. Reason: ` + (e instanceof Error ? e.message : e)); diff --git a/backend/src/repositories/BlocksRepository.ts b/backend/src/repositories/BlocksRepository.ts index 0953f9b84..e6e92d60f 100644 --- a/backend/src/repositories/BlocksRepository.ts +++ b/backend/src/repositories/BlocksRepository.ts @@ -5,7 +5,7 @@ import logger from '../logger'; import { Common } from '../api/common'; import PoolsRepository from './PoolsRepository'; import HashratesRepository from './HashratesRepository'; -import { escape } from 'mysql2'; +import { RowDataPacket, escape } from 'mysql2'; import BlocksSummariesRepository from './BlocksSummariesRepository'; import DifficultyAdjustmentsRepository from './DifficultyAdjustmentsRepository'; import bitcoinClient from '../api/bitcoin/bitcoin-client'; @@ -478,7 +478,7 @@ class BlocksRepository { public async $getBlocksByPool(slug: string, startHeight?: number): Promise { const pool = await PoolsRepository.$getPool(slug); if (!pool) { - throw new Error('This mining pool does not exist ' + escape(slug)); + throw new Error('This mining pool does not exist'); } const params: any[] = []; @@ -541,7 +541,7 @@ class BlocksRepository { */ public async $getBlocksDifficulty(): Promise { try { - const [rows]: any[] = await DB.query(`SELECT UNIX_TIMESTAMP(blockTimestamp) as time, height, difficulty, bits FROM blocks`); + const [rows]: any[] = await DB.query(`SELECT UNIX_TIMESTAMP(blockTimestamp) as time, height, difficulty, bits FROM blocks ORDER BY height ASC`); return rows; } catch (e) { logger.err('Cannot get blocks difficulty list from the db. Reason: ' + (e instanceof Error ? e.message : e)); @@ -802,10 +802,10 @@ class BlocksRepository { /** * Get a list of blocks that have been indexed */ - public async $getIndexedBlocks(): Promise { + public async $getIndexedBlocks(): Promise<{ height: number, hash: string }[]> { try { - const [rows]: any = await DB.query(`SELECT height, hash FROM blocks ORDER BY height DESC`); - return rows; + const [rows] = await DB.query(`SELECT height, hash FROM blocks ORDER BY height DESC`) as RowDataPacket[][]; + return rows as { height: number, hash: string }[]; } catch (e) { logger.err('Cannot generate block size and weight history. Reason: ' + (e instanceof Error ? e.message : e)); throw e; @@ -815,7 +815,7 @@ class BlocksRepository { /** * Get a list of blocks that have not had CPFP data indexed */ - public async $getCPFPUnindexedBlocks(): Promise { + public async $getCPFPUnindexedBlocks(): Promise { try { const blockchainInfo = await bitcoinClient.getBlockchainInfo(); const currentBlockHeight = blockchainInfo.blocks; @@ -825,13 +825,13 @@ class BlocksRepository { } const minHeight = Math.max(0, currentBlockHeight - indexingBlockAmount + 1); - const [rows]: any[] = await DB.query(` + const [rows] = await DB.query(` SELECT height FROM compact_cpfp_clusters WHERE height <= ? AND height >= ? GROUP BY height ORDER BY height DESC; - `, [currentBlockHeight, minHeight]); + `, [currentBlockHeight, minHeight]) as RowDataPacket[][]; const indexedHeights = {}; rows.forEach((row) => { indexedHeights[row.height] = true; }); @@ -1040,16 +1040,18 @@ class BlocksRepository { if (extras.feePercentiles === null) { let summary; + let summaryVersion = 0; if (config.MEMPOOL.BACKEND === 'esplora') { const txs = (await bitcoinApi.$getTxsForBlock(dbBlk.id)).map(tx => transactionUtils.extendTransaction(tx)); summary = blocks.summarizeBlockTransactions(dbBlk.id, txs); + summaryVersion = 1; } else { // Call Core RPC const block = await bitcoinClient.getBlock(dbBlk.id, 2); summary = blocks.summarizeBlock(block); } - await BlocksSummariesRepository.$saveTransactions(dbBlk.height, dbBlk.id, summary.transactions); + await BlocksSummariesRepository.$saveTransactions(dbBlk.height, dbBlk.id, summary.transactions, summaryVersion); extras.feePercentiles = await BlocksSummariesRepository.$getFeePercentilesByBlockId(dbBlk.id); } if (extras.feePercentiles !== null) { diff --git a/backend/src/repositories/BlocksSummariesRepository.ts b/backend/src/repositories/BlocksSummariesRepository.ts index 09598db03..63ad5ddf2 100644 --- a/backend/src/repositories/BlocksSummariesRepository.ts +++ b/backend/src/repositories/BlocksSummariesRepository.ts @@ -1,6 +1,7 @@ +import { RowDataPacket } from 'mysql2'; import DB from '../database'; import logger from '../logger'; -import { BlockSummary, TransactionStripped } from '../mempool.interfaces'; +import { BlockSummary, TransactionClassified } from '../mempool.interfaces'; class BlocksSummariesRepository { public async $getByBlockId(id: string): Promise { @@ -17,30 +18,31 @@ class BlocksSummariesRepository { return undefined; } - public async $saveTransactions(blockHeight: number, blockId: string, transactions: TransactionStripped[]): Promise { + public async $saveTransactions(blockHeight: number, blockId: string, transactions: TransactionClassified[], version: number): Promise { try { const transactionsStr = JSON.stringify(transactions); await DB.query(` INSERT INTO blocks_summaries - SET height = ?, transactions = ?, id = ? - ON DUPLICATE KEY UPDATE transactions = ?`, - [blockHeight, transactionsStr, blockId, transactionsStr]); + SET height = ?, transactions = ?, id = ?, version = ? + ON DUPLICATE KEY UPDATE transactions = ?, version = ?`, + [blockHeight, transactionsStr, blockId, version, transactionsStr, version]); } catch (e: any) { logger.debug(`Cannot save block summary transactions for ${blockId}. Reason: ${e instanceof Error ? e.message : e}`); throw e; } } - public async $saveTemplate(params: { height: number, template: BlockSummary}) { + public async $saveTemplate(params: { height: number, template: BlockSummary, version: number}): Promise { const blockId = params.template?.id; try { const transactions = JSON.stringify(params.template?.transactions || []); await DB.query(` - INSERT INTO blocks_templates (id, template) - VALUE (?, ?) + INSERT INTO blocks_templates (id, template, version) + VALUE (?, ?, ?) ON DUPLICATE KEY UPDATE - template = ? - `, [blockId, transactions, transactions]); + template = ?, + version = ? + `, [blockId, transactions, params.version, transactions, params.version]); } catch (e: any) { if (e.errno === 1062) { // ER_DUP_ENTRY - This scenario is possible upon node backend restart logger.debug(`Cannot save block template for ${blockId} because it has already been indexed, ignoring`); @@ -57,6 +59,7 @@ class BlocksSummariesRepository { return { id: templates[0].id, transactions: JSON.parse(templates[0].template), + version: templates[0].version, }; } } catch (e) { @@ -67,7 +70,7 @@ class BlocksSummariesRepository { public async $getIndexedSummariesId(): Promise { try { - const [rows]: any[] = await DB.query(`SELECT id from blocks_summaries`); + const [rows] = await DB.query(`SELECT id from blocks_summaries`) as RowDataPacket[][]; return rows.map(row => row.id); } catch (e) { logger.err(`Cannot get block summaries id list. Reason: ` + (e instanceof Error ? e.message : e)); @@ -76,6 +79,41 @@ class BlocksSummariesRepository { return []; } + public async $getSummariesWithVersion(version: number): Promise<{ height: number, id: string }[]> { + try { + const [rows]: any[] = await DB.query(` + SELECT + height, + id + FROM blocks_summaries + WHERE version = ? + ORDER BY height DESC;`, [version]); + return rows; + } catch (e) { + logger.err(`Cannot get block summaries with version. Reason: ` + (e instanceof Error ? e.message : e)); + } + + return []; + } + + public async $getTemplatesWithVersion(version: number): Promise<{ height: number, id: string }[]> { + try { + const [rows]: any[] = await DB.query(` + SELECT + blocks_summaries.height as height, + blocks_templates.id as id + FROM blocks_templates + JOIN blocks_summaries ON blocks_templates.id = blocks_summaries.id + WHERE blocks_templates.version = ? + ORDER BY height DESC;`, [version]); + return rows; + } catch (e) { + logger.err(`Cannot get block summaries with version. Reason: ` + (e instanceof Error ? e.message : e)); + } + + return []; + } + /** * Get the fee percentiles if the block has already been indexed, [] otherwise * diff --git a/backend/src/repositories/HashratesRepository.ts b/backend/src/repositories/HashratesRepository.ts index 96cbf6f75..ec44afebe 100644 --- a/backend/src/repositories/HashratesRepository.ts +++ b/backend/src/repositories/HashratesRepository.ts @@ -139,7 +139,7 @@ class HashratesRepository { public async $getPoolWeeklyHashrate(slug: string): Promise { const pool = await PoolsRepository.$getPool(slug); if (!pool) { - throw new Error('This mining pool does not exist ' + escape(slug)); + throw new Error('This mining pool does not exist'); } // Find hashrate boundaries diff --git a/backend/src/repositories/NodesSocketsRepository.ts b/backend/src/repositories/NodesSocketsRepository.ts index af594e6e1..e85126de4 100644 --- a/backend/src/repositories/NodesSocketsRepository.ts +++ b/backend/src/repositories/NodesSocketsRepository.ts @@ -14,7 +14,7 @@ class NodesSocketsRepository { await DB.query(` INSERT INTO nodes_sockets(public_key, socket, type) VALUE (?, ?, ?) - `, [socket.publicKey, socket.addr, socket.network]); + `, [socket.publicKey, socket.addr, socket.network], 'silent'); } catch (e: any) { if (e.errno !== 1062) { // ER_DUP_ENTRY - Not an issue, just ignore this logger.err(`Cannot save node socket (${[socket.publicKey, socket.addr, socket.network]}) into db. Reason: ` + (e instanceof Error ? e.message : e)); diff --git a/backend/src/rpc-api/commands.ts b/backend/src/rpc-api/commands.ts index 78f5e12f4..ecfb2ed7c 100644 --- a/backend/src/rpc-api/commands.ts +++ b/backend/src/rpc-api/commands.ts @@ -91,4 +91,5 @@ module.exports = { walletPassphraseChange: 'walletpassphrasechange', getTxoutSetinfo: 'gettxoutsetinfo', getIndexInfo: 'getindexinfo', + testMempoolAccept: 'testmempoolaccept', }; diff --git a/backend/src/rpc-api/jsonrpc.ts b/backend/src/rpc-api/jsonrpc.ts index 4f7a38baa..0bcbdc16c 100644 --- a/backend/src/rpc-api/jsonrpc.ts +++ b/backend/src/rpc-api/jsonrpc.ts @@ -1,5 +1,6 @@ var http = require('http') var https = require('https') +import { readFileSync } from 'fs'; var JsonRPC = function (opts) { // @ts-ignore @@ -55,7 +56,13 @@ JsonRPC.prototype.call = function (method, params) { } // use HTTP auth if user and password set - if (this.opts.user && this.opts.pass) { + if (this.opts.cookie) { + if (!this.cachedCookie) { + this.cachedCookie = readFileSync(this.opts.cookie).toString(); + } + // @ts-ignore + requestOptions.auth = this.cachedCookie; + } else if (this.opts.user && this.opts.pass) { // @ts-ignore requestOptions.auth = this.opts.user + ':' + this.opts.pass } @@ -93,7 +100,7 @@ JsonRPC.prototype.call = function (method, params) { reject(err) }) - request.on('response', function (response) { + request.on('response', (response) => { clearTimeout(reqTimeout) // We need to buffer the response chunks in a nonblocking way. @@ -104,7 +111,7 @@ JsonRPC.prototype.call = function (method, params) { // When all the responses are finished, we decode the JSON and // depending on whether it's got a result or an error, we call // emitSuccess or emitError on the promise. - response.on('end', function () { + response.on('end', () => { var err if (cbCalled) return @@ -113,6 +120,14 @@ JsonRPC.prototype.call = function (method, params) { try { var decoded = JSON.parse(buffer) } catch (e) { + // if we authenticated using a cookie and it failed, read the cookie file again + if ( + response.statusCode === 401 /* Unauthorized */ && + this.opts.cookie + ) { + this.cachedCookie = undefined; + } + if (response.statusCode !== 200) { err = new Error('Invalid params, response status code: ' + response.statusCode) err.code = -32602 diff --git a/backend/src/tasks/lightning/forensics.service.ts b/backend/src/tasks/lightning/forensics.service.ts index 65ea61dc1..aa88f5bb4 100644 --- a/backend/src/tasks/lightning/forensics.service.ts +++ b/backend/src/tasks/lightning/forensics.service.ts @@ -15,8 +15,6 @@ class ForensicsService { txCache: { [txid: string]: IEsploraApi.Transaction } = {}; tempCached: string[] = []; - constructor() {} - public async $startService(): Promise { logger.info('Starting lightning network forensics service'); @@ -66,93 +64,138 @@ class ForensicsService { */ public async $runClosedChannelsForensics(onlyNewChannels: boolean = false): Promise { + // Only Esplora backend can retrieve spent transaction outputs if (config.MEMPOOL.BACKEND !== 'esplora') { return; } - let progress = 0; - try { logger.debug(`Started running closed channel forensics...`); - let channels; + let allChannels; if (onlyNewChannels) { - channels = await channelsApi.$getClosedChannelsWithoutReason(); + allChannels = await channelsApi.$getClosedChannelsWithoutReason(); } else { - channels = await channelsApi.$getUnresolvedClosedChannels(); + allChannels = await channelsApi.$getUnresolvedClosedChannels(); } - for (const channel of channels) { - let reason = 0; - let resolvedForceClose = false; - // Only Esplora backend can retrieve spent transaction outputs - const cached: string[] = []; + let progress = 0; + const sliceLength = Math.ceil(config.ESPLORA.BATCH_QUERY_BASE_SIZE / 10); + // process batches of 1000 channels + for (let i = 0; i < Math.ceil(allChannels.length / sliceLength); i++) { + const channels = allChannels.slice(i * sliceLength, (i + 1) * sliceLength); + + let allOutspends: IEsploraApi.Outspend[][] = []; + const forceClosedChannels: { channel: any, cachedSpends: string[] }[] = []; + + // fetch outspends in bulk try { - let outspends: IEsploraApi.Outspend[] | undefined; - try { - outspends = await bitcoinApi.$getOutspends(channel.closing_transaction_id); - await Common.sleep$(config.LIGHTNING.FORENSICS_RATE_LIMIT); - } catch (e) { - logger.err(`Failed to call ${config.ESPLORA.REST_API_URL + '/tx/' + channel.closing_transaction_id + '/outspends'}. Reason ${e instanceof Error ? e.message : e}`); - continue; - } - const lightningScriptReasons: number[] = []; + const outspendTxids = channels.map(channel => channel.closing_transaction_id); + allOutspends = await bitcoinApi.$getBatchedOutspendsInternal(outspendTxids); + logger.info(`Fetched outspends for ${allOutspends.length} txs from esplora for LN forensics`); + await Common.sleep$(config.LIGHTNING.FORENSICS_RATE_LIMIT); + } catch (e) { + logger.err(`Failed to call ${config.ESPLORA.REST_API_URL + '/internal/txs/outspends/by-txid'}. Reason ${e instanceof Error ? e.message : e}`); + } + // fetch spending transactions in bulk and load into txCache + const newSpendingTxids: { [txid: string]: boolean } = {}; + for (const outspends of allOutspends) { for (const outspend of outspends) { if (outspend.spent && outspend.txid) { - let spendingTx = await this.fetchTransaction(outspend.txid); - if (!spendingTx) { - continue; - } - cached.push(spendingTx.txid); - const lightningScript = this.findLightningScript(spendingTx.vin[outspend.vin || 0]); - lightningScriptReasons.push(lightningScript); + newSpendingTxids[outspend.txid] = true; } } - const filteredReasons = lightningScriptReasons.filter((r) => r !== 1); - if (filteredReasons.length) { - if (filteredReasons.some((r) => r === 2 || r === 4)) { - reason = 3; - } else { - reason = 2; - resolvedForceClose = true; - } - } else { - /* - We can detect a commitment transaction (force close) by reading Sequence and Locktime - https://github.com/lightning/bolts/blob/master/03-transactions.md#commitment-transaction - */ - let closingTx = await this.fetchTransaction(channel.closing_transaction_id, true); - if (!closingTx) { + } + const allOutspendTxs = await this.fetchTransactions( + allOutspends.flatMap(outspends => + outspends + .filter(outspend => outspend.spent && outspend.txid) + .map(outspend => outspend.txid) + ) + ); + logger.info(`Fetched ${allOutspendTxs.length} out-spending txs from esplora for LN forensics`); + + // process each outspend + for (const [index, channel] of channels.entries()) { + let reason = 0; + const cached: string[] = []; + try { + const outspends = allOutspends[index]; + if (!outspends || !outspends.length) { + // outspends are missing continue; } - cached.push(closingTx.txid); - const sequenceHex: string = closingTx.vin[0].sequence.toString(16); - const locktimeHex: string = closingTx.locktime.toString(16); - if (sequenceHex.substring(0, 2) === '80' && locktimeHex.substring(0, 2) === '20') { - reason = 2; // Here we can't be sure if it's a penalty or not - } else { - reason = 1; + const lightningScriptReasons: number[] = []; + for (const outspend of outspends) { + if (outspend.spent && outspend.txid) { + const spendingTx = this.txCache[outspend.txid]; + if (!spendingTx) { + continue; + } + cached.push(spendingTx.txid); + const lightningScript = this.findLightningScript(spendingTx.vin[outspend.vin || 0]); + lightningScriptReasons.push(lightningScript); + } } - } - if (reason) { - logger.debug('Setting closing reason ' + reason + ' for channel: ' + channel.id + '.'); - await DB.query(`UPDATE channels SET closing_reason = ? WHERE id = ?`, [reason, channel.id]); - if (reason === 2 && resolvedForceClose) { - await DB.query(`UPDATE channels SET closing_resolved = ? WHERE id = ?`, [true, channel.id]); - } - if (reason !== 2 || resolvedForceClose) { + const filteredReasons = lightningScriptReasons.filter((r) => r !== 1); + if (filteredReasons.length) { + if (filteredReasons.some((r) => r === 2 || r === 4)) { + // Force closed with penalty + reason = 3; + } else { + // Force closed without penalty + reason = 2; + await DB.query(`UPDATE channels SET closing_resolved = ? WHERE id = ?`, [true, channel.id]); + } + await DB.query(`UPDATE channels SET closing_reason = ? WHERE id = ?`, [reason, channel.id]); + // clean up cached transactions cached.forEach(txid => { delete this.txCache[txid]; }); + } else { + forceClosedChannels.push({ channel, cachedSpends: cached }); } + } catch (e) { + logger.err(`$runClosedChannelsForensics() failed for channel ${channel.short_id}. Reason: ${e instanceof Error ? e.message : e}`); } - } catch (e) { - logger.err(`$runClosedChannelsForensics() failed for channel ${channel.short_id}. Reason: ${e instanceof Error ? e.message : e}`); } - ++progress; + // fetch force-closing transactions in bulk + const closingTxs = await this.fetchTransactions(forceClosedChannels.map(x => x.channel.closing_transaction_id)); + logger.info(`Fetched ${closingTxs.length} closing txs from esplora for LN forensics`); + + // process channels with no lightning script reasons + for (const { channel, cachedSpends } of forceClosedChannels) { + const closingTx = this.txCache[channel.closing_transaction_id]; + if (!closingTx) { + // no channel close transaction found yet + continue; + } + /* + We can detect a commitment transaction (force close) by reading Sequence and Locktime + https://github.com/lightning/bolts/blob/master/03-transactions.md#commitment-transaction + */ + const sequenceHex: string = closingTx.vin[0].sequence.toString(16); + const locktimeHex: string = closingTx.locktime.toString(16); + let reason; + if (sequenceHex.substring(0, 2) === '80' && locktimeHex.substring(0, 2) === '20') { + // Force closed, but we can't be sure if it's a penalty or not + reason = 2; + } else { + // Mutually closed + reason = 1; + // clean up cached transactions + delete this.txCache[closingTx.txid]; + for (const txid of cachedSpends) { + delete this.txCache[txid]; + } + } + await DB.query(`UPDATE channels SET closing_reason = ? WHERE id = ?`, [reason, channel.id]); + } + + progress += channels.length; const elapsedSeconds = Math.round((new Date().getTime() / 1000) - this.loggerTimer); if (elapsedSeconds > 10) { - logger.debug(`Updating channel closed channel forensics ${progress}/${channels.length}`); + logger.debug(`Updating channel closed channel forensics ${progress}/${allChannels.length}`); this.loggerTimer = new Date().getTime() / 1000; } } @@ -220,8 +263,11 @@ class ForensicsService { logger.debug(`Started running open channel forensics...`); const channels = await channelsApi.$getChannelsWithoutSourceChecked(); + // preload open channel transactions + await this.fetchTransactions(channels.map(channel => channel.transaction_id), true); + for (const openChannel of channels) { - let openTx = await this.fetchTransaction(openChannel.transaction_id, true); + const openTx = this.txCache[openChannel.transaction_id]; if (!openTx) { continue; } @@ -276,7 +322,7 @@ class ForensicsService { // Check if a channel open tx input spends the result of a swept channel close output private async $attributeSweptChannelCloses(openChannel: ILightningApi.Channel, input: IEsploraApi.Vin): Promise { - let sweepTx = await this.fetchTransaction(input.txid, true); + const sweepTx = await this.fetchTransaction(input.txid, true); if (!sweepTx) { logger.err(`couldn't find input transaction for channel forensics ${openChannel.channel_id} ${input.txid}`); return; @@ -335,7 +381,7 @@ class ForensicsService { if (matched && !ambiguous) { // fetch closing channel transaction and perform forensics on the outputs - let prevChannelTx = await this.fetchTransaction(input.txid, true); + const prevChannelTx = await this.fetchTransaction(input.txid, true); let outspends: IEsploraApi.Outspend[] | undefined; try { outspends = await bitcoinApi.$getOutspends(input.txid); @@ -355,17 +401,17 @@ class ForensicsService { }; }); } + + // preload outspend transactions + await this.fetchTransactions(outspends.filter(o => o.spent && o.txid).map(o => o.txid), true); + for (let i = 0; i < outspends?.length; i++) { const outspend = outspends[i]; const output = prevChannel.outputs[i]; if (outspend.spent && outspend.txid) { - try { - const spendingTx = await this.fetchTransaction(outspend.txid, true); - if (spendingTx) { - output.type = this.findLightningScript(spendingTx.vin[outspend.vin || 0]); - } - } catch (e) { - logger.err(`Failed to call ${config.ESPLORA.REST_API_URL + '/tx/' + outspend.txid}. Reason ${e instanceof Error ? e.message : e}`); + const spendingTx = this.txCache[outspend.txid]; + if (spendingTx) { + output.type = this.findLightningScript(spendingTx.vin[outspend.vin || 0]); } } else { output.type = 0; @@ -430,13 +476,36 @@ class ForensicsService { } await Common.sleep$(config.LIGHTNING.FORENSICS_RATE_LIMIT); } catch (e) { - logger.err(`Failed to call ${config.ESPLORA.REST_API_URL + '/tx/' + txid + '/outspends'}. Reason ${e instanceof Error ? e.message : e}`); + logger.err(`Failed to call ${config.ESPLORA.REST_API_URL + '/tx/' + txid}. Reason ${e instanceof Error ? e.message : e}`); return null; } } return tx; } + // fetches a batch of transactions and adds them to the txCache + // the returned list of txs does *not* preserve ordering or number + async fetchTransactions(txids, temp: boolean = false): Promise<(IEsploraApi.Transaction | null)[]> { + // deduplicate txids + const uniqueTxids = [...new Set(txids)]; + // filter out any transactions we already have in the cache + const needToFetch: string[] = uniqueTxids.filter(txid => !this.txCache[txid]); + try { + const txs = await bitcoinApi.$getRawTransactions(needToFetch); + for (const tx of txs) { + this.txCache[tx.txid] = tx; + if (temp) { + this.tempCached.push(tx.txid); + } + } + await Common.sleep$(config.LIGHTNING.FORENSICS_RATE_LIMIT); + } catch (e) { + logger.err(`Failed to call ${config.ESPLORA.REST_API_URL + '/txs'}. Reason ${e instanceof Error ? e.message : e}`); + return []; + } + return txids.map(txid => this.txCache[txid]); + } + clearTempCache(): void { for (const txid of this.tempCached) { delete this.txCache[txid]; diff --git a/backend/src/tasks/lightning/network-sync.service.ts b/backend/src/tasks/lightning/network-sync.service.ts index 963b9e8c2..7d6a40571 100644 --- a/backend/src/tasks/lightning/network-sync.service.ts +++ b/backend/src/tasks/lightning/network-sync.service.ts @@ -288,22 +288,32 @@ class NetworkSyncService { } logger.debug(`${log}`, logger.tags.ln); - const channels = await channelsApi.$getChannelsByStatus([0, 1]); - for (const channel of channels) { - const spendingTx = await bitcoinApi.$getOutspend(channel.transaction_id, channel.transaction_vout); - if (spendingTx.spent === true && spendingTx.status?.confirmed === true) { - logger.debug(`Marking channel: ${channel.id} as closed.`, logger.tags.ln); - await DB.query(`UPDATE channels SET status = 2, closing_date = FROM_UNIXTIME(?) WHERE id = ?`, - [spendingTx.status.block_time, channel.id]); - if (spendingTx.txid && !channel.closing_transaction_id) { - await DB.query(`UPDATE channels SET closing_transaction_id = ? WHERE id = ?`, [spendingTx.txid, channel.id]); + const allChannels = await channelsApi.$getChannelsByStatus([0, 1]); + + const sliceLength = Math.ceil(config.ESPLORA.BATCH_QUERY_BASE_SIZE / 2); + // process batches of 5000 channels + for (let i = 0; i < Math.ceil(allChannels.length / sliceLength); i++) { + const channels = allChannels.slice(i * sliceLength, (i + 1) * sliceLength); + const outspends = await bitcoinApi.$getOutSpendsByOutpoint(channels.map(channel => { + return { txid: channel.transaction_id, vout: channel.transaction_vout }; + })); + + for (const [index, channel] of channels.entries()) { + const spendingTx = outspends[index]; + if (spendingTx.spent === true && spendingTx.status?.confirmed === true) { + // logger.debug(`Marking channel: ${channel.id} as closed.`, logger.tags.ln); + await DB.query(`UPDATE channels SET status = 2, closing_date = FROM_UNIXTIME(?) WHERE id = ?`, + [spendingTx.status.block_time, channel.id]); + if (spendingTx.txid && !channel.closing_transaction_id) { + await DB.query(`UPDATE channels SET closing_transaction_id = ? WHERE id = ?`, [spendingTx.txid, channel.id]); + } } } - ++progress; + progress += channels.length; const elapsedSeconds = Math.round((new Date().getTime() / 1000) - this.loggerTimer); if (elapsedSeconds > config.LIGHTNING.LOGGER_UPDATE_INTERVAL) { - logger.debug(`Checking if channel has been closed ${progress}/${channels.length}`, logger.tags.ln); + logger.debug(`Checking if channel has been closed ${progress}/${allChannels.length}`, logger.tags.ln); this.loggerTimer = new Date().getTime() / 1000; } } diff --git a/backend/src/tasks/price-feeds/coinbase-api.ts b/backend/src/tasks/price-feeds/coinbase-api.ts index 424ac8867..d2c6d063a 100644 --- a/backend/src/tasks/price-feeds/coinbase-api.ts +++ b/backend/src/tasks/price-feeds/coinbase-api.ts @@ -5,14 +5,14 @@ class CoinbaseApi implements PriceFeed { public name: string = 'Coinbase'; public currencies: string[] = ['USD', 'EUR', 'GBP']; - public url: string = 'https://api.coinbase.com/v2/prices/spot?currency='; + public url: string = 'https://api.coinbase.com/v2/prices/BTC-{CURRENCY}/spot'; public urlHist: string = 'https://api.exchange.coinbase.com/products/BTC-{CURRENCY}/candles?granularity={GRANULARITY}'; constructor() { } public async $fetchPrice(currency): Promise { - const response = await query(this.url + currency); + const response = await query(this.url.replace('{CURRENCY}', currency)); if (response && response['data'] && response['data']['amount']) { return parseInt(response['data']['amount'], 10); } else { diff --git a/backend/src/tasks/price-updater.ts b/backend/src/tasks/price-updater.ts index fd799fb87..0d5ca5958 100644 --- a/backend/src/tasks/price-updater.ts +++ b/backend/src/tasks/price-updater.ts @@ -23,6 +23,14 @@ export interface PriceHistory { [timestamp: number]: ApiPrice; } +function getMedian(arr: number[]): number { + const sortedArr = arr.slice().sort((a, b) => a - b); + const mid = Math.floor(sortedArr.length / 2); + return sortedArr.length % 2 !== 0 + ? sortedArr[mid] + : (sortedArr[mid - 1] + sortedArr[mid]) / 2; +} + class PriceUpdater { public historyInserted = false; private timeBetweenUpdatesMs = 360_0000 / config.MEMPOOL.PRICE_UPDATES_PER_HOUR; @@ -173,7 +181,7 @@ class PriceUpdater { if (prices.length === 0) { this.latestPrices[currency] = -1; } else { - this.latestPrices[currency] = Math.round((prices.reduce((partialSum, a) => partialSum + a, 0)) / prices.length); + this.latestPrices[currency] = Math.round(getMedian(prices)); } } @@ -300,9 +308,7 @@ class PriceUpdater { if (grouped[time][currency].length === 0) { continue; } - prices[currency] = Math.round((grouped[time][currency].reduce( - (partialSum, a) => partialSum + a, 0) - ) / grouped[time][currency].length); + prices[currency] = Math.round(getMedian(grouped[time][currency])); } await PricesRepository.$savePrices(parseInt(time, 10), prices); ++totalInserted; diff --git a/backend/src/utils/bitcoin-script.ts b/backend/src/utils/bitcoin-script.ts new file mode 100644 index 000000000..3414e8269 --- /dev/null +++ b/backend/src/utils/bitcoin-script.ts @@ -0,0 +1,203 @@ +const opcodes = { + OP_FALSE: 0, + OP_0: 0, + OP_PUSHDATA1: 76, + OP_PUSHDATA2: 77, + OP_PUSHDATA4: 78, + OP_1NEGATE: 79, + OP_PUSHNUM_NEG1: 79, + OP_RESERVED: 80, + OP_TRUE: 81, + OP_1: 81, + OP_2: 82, + OP_3: 83, + OP_4: 84, + OP_5: 85, + OP_6: 86, + OP_7: 87, + OP_8: 88, + OP_9: 89, + OP_10: 90, + OP_11: 91, + OP_12: 92, + OP_13: 93, + OP_14: 94, + OP_15: 95, + OP_16: 96, + OP_PUSHNUM_1: 81, + OP_PUSHNUM_2: 82, + OP_PUSHNUM_3: 83, + OP_PUSHNUM_4: 84, + OP_PUSHNUM_5: 85, + OP_PUSHNUM_6: 86, + OP_PUSHNUM_7: 87, + OP_PUSHNUM_8: 88, + OP_PUSHNUM_9: 89, + OP_PUSHNUM_10: 90, + OP_PUSHNUM_11: 91, + OP_PUSHNUM_12: 92, + OP_PUSHNUM_13: 93, + OP_PUSHNUM_14: 94, + OP_PUSHNUM_15: 95, + OP_PUSHNUM_16: 96, + OP_NOP: 97, + OP_VER: 98, + OP_IF: 99, + OP_NOTIF: 100, + OP_VERIF: 101, + OP_VERNOTIF: 102, + OP_ELSE: 103, + OP_ENDIF: 104, + OP_VERIFY: 105, + OP_RETURN: 106, + OP_TOALTSTACK: 107, + OP_FROMALTSTACK: 108, + OP_2DROP: 109, + OP_2DUP: 110, + OP_3DUP: 111, + OP_2OVER: 112, + OP_2ROT: 113, + OP_2SWAP: 114, + OP_IFDUP: 115, + OP_DEPTH: 116, + OP_DROP: 117, + OP_DUP: 118, + OP_NIP: 119, + OP_OVER: 120, + OP_PICK: 121, + OP_ROLL: 122, + OP_ROT: 123, + OP_SWAP: 124, + OP_TUCK: 125, + OP_CAT: 126, + OP_SUBSTR: 127, + OP_LEFT: 128, + OP_RIGHT: 129, + OP_SIZE: 130, + OP_INVERT: 131, + OP_AND: 132, + OP_OR: 133, + OP_XOR: 134, + OP_EQUAL: 135, + OP_EQUALVERIFY: 136, + OP_RESERVED1: 137, + OP_RESERVED2: 138, + OP_1ADD: 139, + OP_1SUB: 140, + OP_2MUL: 141, + OP_2DIV: 142, + OP_NEGATE: 143, + OP_ABS: 144, + OP_NOT: 145, + OP_0NOTEQUAL: 146, + OP_ADD: 147, + OP_SUB: 148, + OP_MUL: 149, + OP_DIV: 150, + OP_MOD: 151, + OP_LSHIFT: 152, + OP_RSHIFT: 153, + OP_BOOLAND: 154, + OP_BOOLOR: 155, + OP_NUMEQUAL: 156, + OP_NUMEQUALVERIFY: 157, + OP_NUMNOTEQUAL: 158, + OP_LESSTHAN: 159, + OP_GREATERTHAN: 160, + OP_LESSTHANOREQUAL: 161, + OP_GREATERTHANOREQUAL: 162, + OP_MIN: 163, + OP_MAX: 164, + OP_WITHIN: 165, + OP_RIPEMD160: 166, + OP_SHA1: 167, + OP_SHA256: 168, + OP_HASH160: 169, + OP_HASH256: 170, + OP_CODESEPARATOR: 171, + OP_CHECKSIG: 172, + OP_CHECKSIGVERIFY: 173, + OP_CHECKMULTISIG: 174, + OP_CHECKMULTISIGVERIFY: 175, + OP_NOP1: 176, + OP_NOP2: 177, + OP_CHECKLOCKTIMEVERIFY: 177, + OP_CLTV: 177, + OP_NOP3: 178, + OP_CHECKSEQUENCEVERIFY: 178, + OP_CSV: 178, + OP_NOP4: 179, + OP_NOP5: 180, + OP_NOP6: 181, + OP_NOP7: 182, + OP_NOP8: 183, + OP_NOP9: 184, + OP_NOP10: 185, + OP_CHECKSIGADD: 186, + OP_PUBKEYHASH: 253, + OP_PUBKEY: 254, + OP_INVALIDOPCODE: 255, +}; +// add unused opcodes +for (let i = 187; i <= 255; i++) { + opcodes[`OP_RETURN_${i}`] = i; +} + +export { opcodes }; + +/** extracts m and n from a multisig script (asm), returns nothing if it is not a multisig script */ +export function parseMultisigScript(script: string): void | { m: number, n: number } { + if (!script) { + return; + } + const ops = script.split(' '); + if (ops.length < 3 || ops.pop() !== 'OP_CHECKMULTISIG') { + return; + } + const opN = ops.pop(); + if (!opN) { + return; + } + if (!opN.startsWith('OP_PUSHNUM_')) { + return; + } + const n = parseInt(opN.match(/[0-9]+/)?.[0] || '', 10); + if (ops.length < n * 2 + 1) { + return; + } + // pop n public keys + for (let i = 0; i < n; i++) { + if (!/^0((2|3)\w{64}|4\w{128})$/.test(ops.pop() || '')) { + return; + } + if (!/^OP_PUSHBYTES_(33|65)$/.test(ops.pop() || '')) { + return; + } + } + const opM = ops.pop(); + if (!opM) { + return; + } + if (!opM.startsWith('OP_PUSHNUM_')) { + return; + } + const m = parseInt(opM.match(/[0-9]+/)?.[0] || '', 10); + + if (ops.length) { + return; + } + + return { m, n }; +} + +export function getVarIntLength(n: number): number { + if (n < 0xfd) { + return 1; + } else if (n <= 0xffff) { + return 3; + } else if (n <= 0xffffffff) { + return 5; + } else { + return 9; + } +} \ No newline at end of file diff --git a/backend/src/utils/secp256k1.ts b/backend/src/utils/secp256k1.ts new file mode 100644 index 000000000..9e0f6dc3b --- /dev/null +++ b/backend/src/utils/secp256k1.ts @@ -0,0 +1,77 @@ +function powMod(x: bigint, power: number, modulo: bigint): bigint { + for (let i = 0; i < power; i++) { + x = (x * x) % modulo; + } + return x; +} + +function sqrtMod(x: bigint, P: bigint): bigint { + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (powMod(b3, 3, P) * b3) % P; + const b9 = (powMod(b6, 3, P) * b3) % P; + const b11 = (powMod(b9, 2, P) * b2) % P; + const b22 = (powMod(b11, 11, P) * b11) % P; + const b44 = (powMod(b22, 22, P) * b22) % P; + const b88 = (powMod(b44, 44, P) * b44) % P; + const b176 = (powMod(b88, 88, P) * b88) % P; + const b220 = (powMod(b176, 44, P) * b44) % P; + const b223 = (powMod(b220, 3, P) * b3) % P; + const t1 = (powMod(b223, 23, P) * b22) % P; + const t2 = (powMod(t1, 6, P) * b2) % P; + const root = powMod(t2, 2, P); + return root; +} + +const curveP = BigInt(`0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F`); + +/** + * This function tells whether the point given is a DER encoded point on the ECDSA curve. + * @param {string} pointHex The point as a hex string (*must not* include a '0x' prefix) + * @returns {boolean} true if the point is on the SECP256K1 curve + */ +export function isPoint(pointHex: string): boolean { + if (!pointHex?.length) { + return false; + } + if ( + !( + // is uncompressed + ( + (pointHex.length === 130 && pointHex.startsWith('04')) || + // OR is compressed + (pointHex.length === 66 && + (pointHex.startsWith('02') || pointHex.startsWith('03'))) + ) + ) + ) { + return false; + } + + // Function modified slightly from noble-curves + + + // Now we know that pointHex is a 33 or 65 byte hex string. + const isCompressed = pointHex.length === 66; + + const x = BigInt(`0x${pointHex.slice(2, 66)}`); + if (x >= curveP) { + return false; + } + + if (!isCompressed) { + const y = BigInt(`0x${pointHex.slice(66, 130)}`); + if (y >= curveP) { + return false; + } + // Just check y^2 = x^3 + 7 (secp256k1 curve) + return (y * y) % curveP === (x * x * x + 7n) % curveP; + } else { + // Get unaltered y^2 (no mod p) + const ySquared = (x * x * x + 7n) % curveP; + // Try to sqrt it, it will round down if not perfect root + const y = sqrtMod(ySquared, curveP); + // If we square and it's equal, then it was a perfect root and valid point. + return (y * y) % curveP === ySquared; + } +} \ No newline at end of file diff --git a/contributors/0xBEEFCAF3.txt b/contributors/0xBEEFCAF3.txt new file mode 100644 index 000000000..e00999be1 --- /dev/null +++ b/contributors/0xBEEFCAF3.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of November 17, 2023. + +Signed: 0xBEEFCAF3 diff --git a/contributors/TKone7.txt b/contributors/TKone7.txt new file mode 100644 index 000000000..0112e34a3 --- /dev/null +++ b/contributors/TKone7.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of October 23, 2023. + +Signed: TKone7 diff --git a/contributors/afahrer.txt b/contributors/afahrer.txt new file mode 100644 index 000000000..1ce6dc8e5 --- /dev/null +++ b/contributors/afahrer.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of January 23, 2024. + +Signed: afahrer \ No newline at end of file diff --git a/contributors/fanquake.txt b/contributors/fanquake.txt new file mode 100644 index 000000000..3212bdcbf --- /dev/null +++ b/contributors/fanquake.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of October 23, 2023. + +Signed: fanquake diff --git a/contributors/fubz.txt b/contributors/fubz.txt new file mode 100644 index 000000000..e799d641d --- /dev/null +++ b/contributors/fubz.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of January 25, 2022. + +Signed: fubz diff --git a/contributors/isghe.txt b/contributors/isghe.txt new file mode 100644 index 000000000..5e556448a --- /dev/null +++ b/contributors/isghe.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of January 18, 2024. + +Signed: isghe diff --git a/contributors/jamesblacklock.txt b/contributors/jamesblacklock.txt new file mode 100644 index 000000000..11591f451 --- /dev/null +++ b/contributors/jamesblacklock.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of December 20, 2023. + +Signed: jamesblacklock diff --git a/contributors/natsoni.txt b/contributors/natsoni.txt new file mode 100644 index 000000000..ac1007ecf --- /dev/null +++ b/contributors/natsoni.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of November 16, 2023. + +Signed: natsoni diff --git a/contributors/orangesurf.txt b/contributors/orangesurf.txt new file mode 100644 index 000000000..c760a9125 --- /dev/null +++ b/contributors/orangesurf.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of September 12, 2023. + +Signed: orange surf diff --git a/contributors/shubhamkmr04.txt b/contributors/shubhamkmr04.txt new file mode 100644 index 000000000..ab7e49e0b --- /dev/null +++ b/contributors/shubhamkmr04.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of November 15, 2023. + +Signed: shubhamkmr04 \ No newline at end of file diff --git a/contributors/starius.txt b/contributors/starius.txt new file mode 100644 index 000000000..df9fdbe8d --- /dev/null +++ b/contributors/starius.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of Oct 13, 2023. + +Signed starius diff --git a/contributors/takuabonn.txt b/contributors/takuabonn.txt new file mode 100644 index 000000000..331019e91 --- /dev/null +++ b/contributors/takuabonn.txt @@ -0,0 +1,3 @@ +I hereby accept the terms of the Contributor License Agreement in the CONTRIBUTING.md file of the mempool/mempool git repository as of December 13, 2023. + +Signed: takuabonn \ No newline at end of file diff --git a/docker/README.md b/docker/README.md index 13bda7ec6..444324af8 100644 --- a/docker/README.md +++ b/docker/README.md @@ -124,7 +124,7 @@ Corresponding `docker-compose.yml` overrides: environment: MEMPOOL_NETWORK: "" MEMPOOL_BACKEND: "" - MEMPOOL_HTTP_PORT: "" + BACKEND_HTTP_PORT: "" MEMPOOL_SPAWN_CLUSTER_PROCS: "" MEMPOOL_API_URL_PREFIX: "" MEMPOOL_POLL_RATE_MS: "" @@ -164,7 +164,9 @@ Corresponding `docker-compose.yml` overrides: "PORT": 8332, "USERNAME": "mempool", "PASSWORD": "mempool", - "TIMEOUT": 60000 + "TIMEOUT": 60000, + "COOKIE": false, + "COOKIE_PATH": "" }, ``` @@ -177,6 +179,8 @@ Corresponding `docker-compose.yml` overrides: CORE_RPC_USERNAME: "" CORE_RPC_PASSWORD: "" CORE_RPC_TIMEOUT: 60000 + CORE_RPC_COOKIE: false + CORE_RPC_COOKIE_PATH: "" ... ``` @@ -231,7 +235,9 @@ Corresponding `docker-compose.yml` overrides: "PORT": 8332, "USERNAME": "mempool", "PASSWORD": "mempool", - "TIMEOUT": 60000 + "TIMEOUT": 60000, + "COOKIE": false, + "COOKIE_PATH": "" }, ``` @@ -244,6 +250,8 @@ Corresponding `docker-compose.yml` overrides: SECOND_CORE_RPC_USERNAME: "" SECOND_CORE_RPC_PASSWORD: "" SECOND_CORE_RPC_TIMEOUT: "" + SECOND_CORE_RPC_COOKIE: false + SECOND_CORE_RPC_COOKIE_PATH: "" ... ``` diff --git a/docker/backend/Dockerfile b/docker/backend/Dockerfile index bbe4df3d2..96b1a2d5b 100644 --- a/docker/backend/Dockerfile +++ b/docker/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM node:16.16.0-buster-slim AS builder +FROM node:20.8.0-buster-slim AS builder ARG commitHash ENV MEMPOOL_COMMIT_HASH=${commitHash} @@ -17,7 +17,7 @@ ENV PATH="/root/.cargo/bin:$PATH" RUN npm install --omit=dev --omit=optional RUN npm run package -FROM node:16.16.0-buster-slim +FROM node:20.8.0-buster-slim WORKDIR /backend diff --git a/docker/backend/mempool-config.json b/docker/backend/mempool-config.json index aa084133f..eca4cf14c 100644 --- a/docker/backend/mempool-config.json +++ b/docker/backend/mempool-config.json @@ -3,6 +3,7 @@ "NETWORK": "__MEMPOOL_NETWORK__", "BACKEND": "__MEMPOOL_BACKEND__", "ENABLED": __MEMPOOL_ENABLED__, + "OFFICIAL": __MEMPOOL_OFFICIAL__, "HTTP_PORT": __MEMPOOL_HTTP_PORT__, "SPAWN_CLUSTER_PROCS": __MEMPOOL_SPAWN_CLUSTER_PROCS__, "API_URL_PREFIX": "__MEMPOOL_API_URL_PREFIX__", @@ -22,6 +23,7 @@ "STDOUT_LOG_MIN_PRIORITY": "__MEMPOOL_STDOUT_LOG_MIN_PRIORITY__", "INDEXING_BLOCKS_AMOUNT": __MEMPOOL_INDEXING_BLOCKS_AMOUNT__, "BLOCKS_SUMMARIES_INDEXING": __MEMPOOL_BLOCKS_SUMMARIES_INDEXING__, + "GOGGLES_INDEXING": __MEMPOOL_GOGGLES_INDEXING__, "AUTOMATIC_BLOCK_REINDEXING": __MEMPOOL_AUTOMATIC_BLOCK_REINDEXING__, "AUDIT": __MEMPOOL_AUDIT__, "ADVANCED_GBT_AUDIT": __MEMPOOL_ADVANCED_GBT_AUDIT__, @@ -34,14 +36,17 @@ "ALLOW_UNREACHABLE": __MEMPOOL_ALLOW_UNREACHABLE__, "POOLS_JSON_TREE_URL": "__MEMPOOL_POOLS_JSON_TREE_URL__", "POOLS_JSON_URL": "__MEMPOOL_POOLS_JSON_URL__", - "PRICE_UPDATES_PER_HOUR": __MEMPOOL_PRICE_UPDATES_PER_HOUR__ + "PRICE_UPDATES_PER_HOUR": __MEMPOOL_PRICE_UPDATES_PER_HOUR__, + "MAX_TRACKED_ADDRESSES": __MEMPOOL_MAX_TRACKED_ADDRESSES__ }, "CORE_RPC": { "HOST": "__CORE_RPC_HOST__", "PORT": __CORE_RPC_PORT__, "USERNAME": "__CORE_RPC_USERNAME__", "PASSWORD": "__CORE_RPC_PASSWORD__", - "TIMEOUT": __CORE_RPC_TIMEOUT__ + "TIMEOUT": __CORE_RPC_TIMEOUT__, + "COOKIE": __CORE_RPC_COOKIE__, + "COOKIE_PATH": "__CORE_RPC_COOKIE_PATH__" }, "ELECTRUM": { "HOST": "__ELECTRUM_HOST__", @@ -51,7 +56,10 @@ "ESPLORA": { "REST_API_URL": "__ESPLORA_REST_API_URL__", "UNIX_SOCKET_PATH": "__ESPLORA_UNIX_SOCKET_PATH__", + "BATCH_QUERY_BASE_SIZE": __ESPLORA_BATCH_QUERY_BASE_SIZE__, "RETRY_UNIX_SOCKET_AFTER": __ESPLORA_RETRY_UNIX_SOCKET_AFTER__, + "REQUEST_TIMEOUT": __ESPLORA_REQUEST_TIMEOUT__, + "FALLBACK_TIMEOUT": __ESPLORA_FALLBACK_TIMEOUT__, "FALLBACK": __ESPLORA_FALLBACK__ }, "SECOND_CORE_RPC": { @@ -59,7 +67,9 @@ "PORT": __SECOND_CORE_RPC_PORT__, "USERNAME": "__SECOND_CORE_RPC_USERNAME__", "PASSWORD": "__SECOND_CORE_RPC_PASSWORD__", - "TIMEOUT": __SECOND_CORE_RPC_TIMEOUT__ + "TIMEOUT": __SECOND_CORE_RPC_TIMEOUT__, + "COOKIE": __SECOND_CORE_RPC_COOKIE__, + "COOKIE_PATH": "__SECOND_CORE_RPC_COOKIE_PATH__" }, "DATABASE": { "ENABLED": __DATABASE_ENABLED__, @@ -69,7 +79,9 @@ "DATABASE": "__DATABASE_DATABASE__", "USERNAME": "__DATABASE_USERNAME__", "PASSWORD": "__DATABASE_PASSWORD__", - "TIMEOUT": __DATABASE_TIMEOUT__ + "TIMEOUT": __DATABASE_TIMEOUT__, + "PID_DIR": "__DATABASE_PID_DIR__", + "POOL_SIZE": __DATABASE_POOL_SIZE__ }, "SYSLOG": { "ENABLED": __SYSLOG_ENABLED__, @@ -139,6 +151,7 @@ }, "REDIS": { "ENABLED": __REDIS_ENABLED__, - "UNIX_SOCKET_PATH": "__REDIS_UNIX_SOCKET_PATH__" + "UNIX_SOCKET_PATH": "__REDIS_UNIX_SOCKET_PATH__", + "BATCH_QUERY_BASE_SIZE": __REDIS_BATCH_QUERY_BASE_SIZE__ } } diff --git a/docker/backend/start.sh b/docker/backend/start.sh index 2e293ce34..b700bba32 100755 --- a/docker/backend/start.sh +++ b/docker/backend/start.sh @@ -4,6 +4,7 @@ __MEMPOOL_NETWORK__=${MEMPOOL_NETWORK:=mainnet} __MEMPOOL_BACKEND__=${MEMPOOL_BACKEND:=electrum} __MEMPOOL_ENABLED__=${MEMPOOL_ENABLED:=true} +__MEMPOOL_OFFICIAL__=${MEMPOOL_OFFICIAL:=false} __MEMPOOL_HTTP_PORT__=${BACKEND_HTTP_PORT:=8999} __MEMPOOL_SPAWN_CLUSTER_PROCS__=${MEMPOOL_SPAWN_CLUSTER_PROCS:=0} __MEMPOOL_API_URL_PREFIX__=${MEMPOOL_API_URL_PREFIX:=/api/v1/} @@ -17,6 +18,7 @@ __MEMPOOL_INITIAL_BLOCKS_AMOUNT__=${MEMPOOL_INITIAL_BLOCKS_AMOUNT:=8} __MEMPOOL_MEMPOOL_BLOCKS_AMOUNT__=${MEMPOOL_MEMPOOL_BLOCKS_AMOUNT:=8} __MEMPOOL_INDEXING_BLOCKS_AMOUNT__=${MEMPOOL_INDEXING_BLOCKS_AMOUNT:=11000} __MEMPOOL_BLOCKS_SUMMARIES_INDEXING__=${MEMPOOL_BLOCKS_SUMMARIES_INDEXING:=false} +__MEMPOOL_GOGGLES_INDEXING__=${MEMPOOL_GOGGLES_INDEXING:=false} __MEMPOOL_USE_SECOND_NODE_FOR_MINFEE__=${MEMPOOL_USE_SECOND_NODE_FOR_MINFEE:=false} __MEMPOOL_EXTERNAL_ASSETS__=${MEMPOOL_EXTERNAL_ASSETS:=[]} __MEMPOOL_EXTERNAL_MAX_RETRY__=${MEMPOOL_EXTERNAL_MAX_RETRY:=1} @@ -36,6 +38,7 @@ __MEMPOOL_DISK_CACHE_BLOCK_INTERVAL__=${MEMPOOL_DISK_CACHE_BLOCK_INTERVAL:=6} __MEMPOOL_MAX_PUSH_TX_SIZE_WEIGHT__=${MEMPOOL_MAX_PUSH_TX_SIZE_WEIGHT:=4000000} __MEMPOOL_ALLOW_UNREACHABLE__=${MEMPOOL_ALLOW_UNREACHABLE:=true} __MEMPOOL_PRICE_UPDATES_PER_HOUR__=${MEMPOOL_PRICE_UPDATES_PER_HOUR:=1} +__MEMPOOL_MAX_TRACKED_ADDRESSES__=${MEMPOOL_MAX_TRACKED_ADDRESSES:=1} # CORE_RPC __CORE_RPC_HOST__=${CORE_RPC_HOST:=127.0.0.1} @@ -43,6 +46,8 @@ __CORE_RPC_PORT__=${CORE_RPC_PORT:=8332} __CORE_RPC_USERNAME__=${CORE_RPC_USERNAME:=mempool} __CORE_RPC_PASSWORD__=${CORE_RPC_PASSWORD:=mempool} __CORE_RPC_TIMEOUT__=${CORE_RPC_TIMEOUT:=60000} +__CORE_RPC_COOKIE__=${CORE_RPC_COOKIE:=false} +__CORE_RPC_COOKIE_PATH__=${CORE_RPC_COOKIE_PATH:=""} # ELECTRUM __ELECTRUM_HOST__=${ELECTRUM_HOST:=127.0.0.1} @@ -51,8 +56,11 @@ __ELECTRUM_TLS_ENABLED__=${ELECTRUM_TLS_ENABLED:=false} # ESPLORA __ESPLORA_REST_API_URL__=${ESPLORA_REST_API_URL:=http://127.0.0.1:3000} -__ESPLORA_UNIX_SOCKET_PATH__=${ESPLORA_UNIX_SOCKET_PATH:="null"} +__ESPLORA_UNIX_SOCKET_PATH__=${ESPLORA_UNIX_SOCKET_PATH:=""} +__ESPLORA_BATCH_QUERY_BASE_SIZE__=${ESPLORA_BATCH_QUERY_BASE_SIZE:=1000} __ESPLORA_RETRY_UNIX_SOCKET_AFTER__=${ESPLORA_RETRY_UNIX_SOCKET_AFTER:=30000} +__ESPLORA_REQUEST_TIMEOUT__=${ESPLORA_REQUEST_TIMEOUT:=5000} +__ESPLORA_FALLBACK_TIMEOUT__=${ESPLORA_FALLBACK_TIMEOUT:=5000} __ESPLORA_FALLBACK__=${ESPLORA_FALLBACK:=[]} # SECOND_CORE_RPC @@ -61,6 +69,8 @@ __SECOND_CORE_RPC_PORT__=${SECOND_CORE_RPC_PORT:=8332} __SECOND_CORE_RPC_USERNAME__=${SECOND_CORE_RPC_USERNAME:=mempool} __SECOND_CORE_RPC_PASSWORD__=${SECOND_CORE_RPC_PASSWORD:=mempool} __SECOND_CORE_RPC_TIMEOUT__=${SECOND_CORE_RPC_TIMEOUT:=60000} +__SECOND_CORE_RPC_COOKIE__=${SECOND_CORE_RPC_COOKIE:=false} +__SECOND_CORE_RPC_COOKIE_PATH__=${SECOND_CORE_RPC_COOKIE_PATH:=""} # DATABASE __DATABASE_ENABLED__=${DATABASE_ENABLED:=true} @@ -71,6 +81,8 @@ __DATABASE_DATABASE__=${DATABASE_DATABASE:=mempool} __DATABASE_USERNAME__=${DATABASE_USERNAME:=mempool} __DATABASE_PASSWORD__=${DATABASE_PASSWORD:=mempool} __DATABASE_TIMEOUT__=${DATABASE_TIMEOUT:=180000} +__DATABASE_PID_DIR__=${DATABASE_PID_DIR:=""} +__DATABASE_POOL_SIZE__=${DATABASE_POOL_SIZE:=100} # SYSLOG __SYSLOG_ENABLED__=${SYSLOG_ENABLED:=false} @@ -139,14 +151,16 @@ __MEMPOOL_SERVICES_API__=${MEMPOOL_SERVICES_API:=""} __MEMPOOL_SERVICES_ACCELERATIONS__=${MEMPOOL_SERVICES_ACCELERATIONS:=false} # REDIS -__REDIS_ENABLED__=${REDIS_ENABLED:=true} +__REDIS_ENABLED__=${REDIS_ENABLED:=false} __REDIS_UNIX_SOCKET_PATH__=${REDIS_UNIX_SOCKET_PATH:=true} +__REDIS_BATCH_QUERY_BASE_SIZE__=${REDIS_BATCH_QUERY_BASE_SIZE:=5000} mkdir -p "${__MEMPOOL_CACHE_DIR__}" sed -i "s!__MEMPOOL_NETWORK__!${__MEMPOOL_NETWORK__}!g" mempool-config.json sed -i "s!__MEMPOOL_BACKEND__!${__MEMPOOL_BACKEND__}!g" mempool-config.json sed -i "s!__MEMPOOL_ENABLED__!${__MEMPOOL_ENABLED__}!g" mempool-config.json +sed -i "s!__MEMPOOL_OFFICIAL__!${__MEMPOOL_OFFICIAL__}!g" mempool-config.json sed -i "s!__MEMPOOL_HTTP_PORT__!${__MEMPOOL_HTTP_PORT__}!g" mempool-config.json sed -i "s!__MEMPOOL_SPAWN_CLUSTER_PROCS__!${__MEMPOOL_SPAWN_CLUSTER_PROCS__}!g" mempool-config.json sed -i "s!__MEMPOOL_API_URL_PREFIX__!${__MEMPOOL_API_URL_PREFIX__}!g" mempool-config.json @@ -160,6 +174,7 @@ sed -i "s!__MEMPOOL_INITIAL_BLOCKS_AMOUNT__!${__MEMPOOL_INITIAL_BLOCKS_AMOUNT__} sed -i "s!__MEMPOOL_MEMPOOL_BLOCKS_AMOUNT__!${__MEMPOOL_MEMPOOL_BLOCKS_AMOUNT__}!g" mempool-config.json sed -i "s!__MEMPOOL_INDEXING_BLOCKS_AMOUNT__!${__MEMPOOL_INDEXING_BLOCKS_AMOUNT__}!g" mempool-config.json sed -i "s!__MEMPOOL_BLOCKS_SUMMARIES_INDEXING__!${__MEMPOOL_BLOCKS_SUMMARIES_INDEXING__}!g" mempool-config.json +sed -i "s!__MEMPOOL_GOGGLES_INDEXING__!${__MEMPOOL_GOGGLES_INDEXING__}!g" mempool-config.json sed -i "s!__MEMPOOL_USE_SECOND_NODE_FOR_MINFEE__!${__MEMPOOL_USE_SECOND_NODE_FOR_MINFEE__}!g" mempool-config.json sed -i "s!__MEMPOOL_EXTERNAL_ASSETS__!${__MEMPOOL_EXTERNAL_ASSETS__}!g" mempool-config.json sed -i "s!__MEMPOOL_EXTERNAL_MAX_RETRY__!${__MEMPOOL_EXTERNAL_MAX_RETRY__}!g" mempool-config.json @@ -179,12 +194,15 @@ sed -i "s!__MEMPOOL_DISK_CACHE_BLOCK_INTERVAL__!${__MEMPOOL_DISK_CACHE_BLOCK_INT sed -i "s!__MEMPOOL_MAX_PUSH_TX_SIZE_WEIGHT__!${__MEMPOOL_MAX_PUSH_TX_SIZE_WEIGHT__}!g" mempool-config.json sed -i "s!__MEMPOOL_ALLOW_UNREACHABLE__!${__MEMPOOL_ALLOW_UNREACHABLE__}!g" mempool-config.json sed -i "s!__MEMPOOL_PRICE_UPDATES_PER_HOUR__!${__MEMPOOL_PRICE_UPDATES_PER_HOUR__}!g" mempool-config.json +sed -i "s!__MEMPOOL_MAX_TRACKED_ADDRESSES__!${__MEMPOOL_MAX_TRACKED_ADDRESSES__}!g" mempool-config.json sed -i "s!__CORE_RPC_HOST__!${__CORE_RPC_HOST__}!g" mempool-config.json sed -i "s!__CORE_RPC_PORT__!${__CORE_RPC_PORT__}!g" mempool-config.json sed -i "s!__CORE_RPC_USERNAME__!${__CORE_RPC_USERNAME__}!g" mempool-config.json sed -i "s!__CORE_RPC_PASSWORD__!${__CORE_RPC_PASSWORD__}!g" mempool-config.json sed -i "s!__CORE_RPC_TIMEOUT__!${__CORE_RPC_TIMEOUT__}!g" mempool-config.json +sed -i "s!__CORE_RPC_COOKIE__!${__CORE_RPC_COOKIE__}!g" mempool-config.json +sed -i "s!__CORE_RPC_COOKIE_PATH__!${__CORE_RPC_COOKIE_PATH__}!g" mempool-config.json sed -i "s!__ELECTRUM_HOST__!${__ELECTRUM_HOST__}!g" mempool-config.json sed -i "s!__ELECTRUM_PORT__!${__ELECTRUM_PORT__}!g" mempool-config.json @@ -192,7 +210,10 @@ sed -i "s!__ELECTRUM_TLS_ENABLED__!${__ELECTRUM_TLS_ENABLED__}!g" mempool-config sed -i "s!__ESPLORA_REST_API_URL__!${__ESPLORA_REST_API_URL__}!g" mempool-config.json sed -i "s!__ESPLORA_UNIX_SOCKET_PATH__!${__ESPLORA_UNIX_SOCKET_PATH__}!g" mempool-config.json +sed -i "s!__ESPLORA_BATCH_QUERY_BASE_SIZE__!${__ESPLORA_BATCH_QUERY_BASE_SIZE__}!g" mempool-config.json sed -i "s!__ESPLORA_RETRY_UNIX_SOCKET_AFTER__!${__ESPLORA_RETRY_UNIX_SOCKET_AFTER__}!g" mempool-config.json +sed -i "s!__ESPLORA_REQUEST_TIMEOUT__!${__ESPLORA_REQUEST_TIMEOUT__}!g" mempool-config.json +sed -i "s!__ESPLORA_FALLBACK_TIMEOUT__!${__ESPLORA_FALLBACK_TIMEOUT__}!g" mempool-config.json sed -i "s!__ESPLORA_FALLBACK__!${__ESPLORA_FALLBACK__}!g" mempool-config.json sed -i "s!__SECOND_CORE_RPC_HOST__!${__SECOND_CORE_RPC_HOST__}!g" mempool-config.json @@ -200,6 +221,8 @@ sed -i "s!__SECOND_CORE_RPC_PORT__!${__SECOND_CORE_RPC_PORT__}!g" mempool-config sed -i "s!__SECOND_CORE_RPC_USERNAME__!${__SECOND_CORE_RPC_USERNAME__}!g" mempool-config.json sed -i "s!__SECOND_CORE_RPC_PASSWORD__!${__SECOND_CORE_RPC_PASSWORD__}!g" mempool-config.json sed -i "s!__SECOND_CORE_RPC_TIMEOUT__!${__SECOND_CORE_RPC_TIMEOUT__}!g" mempool-config.json +sed -i "s!__SECOND_CORE_RPC_COOKIE__!${__SECOND_CORE_RPC_COOKIE__}!g" mempool-config.json +sed -i "s!__SECOND_CORE_RPC_COOKIE_PATH__!${__SECOND_CORE_RPC_COOKIE_PATH__}!g" mempool-config.json sed -i "s!__DATABASE_ENABLED__!${__DATABASE_ENABLED__}!g" mempool-config.json sed -i "s!__DATABASE_HOST__!${__DATABASE_HOST__}!g" mempool-config.json @@ -209,6 +232,8 @@ sed -i "s!__DATABASE_DATABASE__!${__DATABASE_DATABASE__}!g" mempool-config.json sed -i "s!__DATABASE_USERNAME__!${__DATABASE_USERNAME__}!g" mempool-config.json sed -i "s!__DATABASE_PASSWORD__!${__DATABASE_PASSWORD__}!g" mempool-config.json sed -i "s!__DATABASE_TIMEOUT__!${__DATABASE_TIMEOUT__}!g" mempool-config.json +sed -i "s!__DATABASE_PID_DIR__!${__DATABASE_PID_DIR__}!g" mempool-config.json +sed -i "s!__DATABASE_POOL_SIZE__!${__DATABASE_POOL_SIZE__}!g" mempool-config.json sed -i "s!__SYSLOG_ENABLED__!${__SYSLOG_ENABLED__}!g" mempool-config.json sed -i "s!__SYSLOG_HOST__!${__SYSLOG_HOST__}!g" mempool-config.json @@ -274,5 +299,6 @@ sed -i "s!__MEMPOOL_SERVICES_ACCELERATIONS__!${__MEMPOOL_SERVICES_ACCELERATIONS_ # REDIS sed -i "s!__REDIS_ENABLED__!${__REDIS_ENABLED__}!g" mempool-config.json sed -i "s!__REDIS_UNIX_SOCKET_PATH__!${__REDIS_UNIX_SOCKET_PATH__}!g" mempool-config.json +sed -i "s!__REDIS_BATCH_QUERY_BASE_SIZE__!${__REDIS_BATCH_QUERY_BASE_SIZE__}!g" mempool-config.json node /backend/package/index.js diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 68e73a1c8..4e1094306 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -38,7 +38,7 @@ services: MYSQL_USER: "mempool" MYSQL_PASSWORD: "mempool" MYSQL_ROOT_PASSWORD: "admin" - image: mariadb:10.5.8 + image: mariadb:10.5.21 user: "1000:1000" restart: on-failure stop_grace_period: 1m diff --git a/docker/electrum/Dockerfile b/docker/electrum/Dockerfile deleted file mode 100644 index b7af48989..000000000 --- a/docker/electrum/Dockerfile +++ /dev/null @@ -1,32 +0,0 @@ -FROM ubuntu:18.04 -MAINTAINER mempool.space developers -EXPOSE 50002 - -# runs as UID 1000 GID 1000 inside the container - -ENV VERSION 4.0.9 -RUN set -x \ - && apt-get update \ - && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends gpg gpg-agent dirmngr \ - && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends wget xpra python3-pyqt5 python3-wheel python3-pip python3-setuptools libsecp256k1-0 libsecp256k1-dev python3-numpy python3-dev build-essential \ - && wget -O /tmp/Electrum-${VERSION}.tar.gz https://download.electrum.org/${VERSION}/Electrum-${VERSION}.tar.gz \ - && wget -O /tmp/Electrum-${VERSION}.tar.gz.asc https://download.electrum.org/${VERSION}/Electrum-${VERSION}.tar.gz.asc \ - && gpg --keyserver keys.gnupg.net --recv-keys 6694D8DE7BE8EE5631BED9502BD5824B7F9470E6 \ - && gpg --verify /tmp/Electrum-${VERSION}.tar.gz.asc /tmp/Electrum-${VERSION}.tar.gz \ - && pip3 install /tmp/Electrum-${VERSION}.tar.gz \ - && test -f /usr/local/bin/electrum \ - && rm -vrf /tmp/Electrum-${VERSION}.tar.gz /tmp/Electrum-${VERSION}.tar.gz.asc ${HOME}/.gnupg \ - && apt-get purge --autoremove -y python3-wheel python3-pip python3-setuptools python3-dev build-essential libsecp256k1-dev curl gpg gpg-agent dirmngr \ - && apt-get clean && rm -rf /var/lib/apt/lists/* \ - && useradd -d /home/mempool -m mempool \ - && mkdir /electrum \ - && ln -s /electrum /home/mempool/.electrum \ - && chown mempool:mempool /electrum - -USER mempool -ENV HOME /home/mempool -WORKDIR /home/mempool -VOLUME /electrum - -CMD ["/usr/bin/xpra", "start", ":100", "--start-child=/usr/local/bin/electrum", "--bind-tcp=0.0.0.0:50002","--daemon=yes", "--notifications=no", "--mdns=no", "--pulseaudio=no", "--html=off", "--speaker=disabled", "--microphone=disabled", "--webcam=no", "--printing=no", "--dbus-launch=", "--exit-with-children"] -ENTRYPOINT ["electrum"] diff --git a/docker/frontend/Dockerfile b/docker/frontend/Dockerfile index b54612e3d..4d04ae88f 100644 --- a/docker/frontend/Dockerfile +++ b/docker/frontend/Dockerfile @@ -1,4 +1,4 @@ -FROM node:16.16.0-buster-slim AS builder +FROM node:20.8.0-buster-slim AS builder ARG commitHash ENV DOCKER_COMMIT_HASH=${commitHash} @@ -13,7 +13,7 @@ RUN npm install --omit=dev --omit=optional RUN npm run build -FROM nginx:1.17.8-alpine +FROM nginx:1.24.0-alpine WORKDIR /patch diff --git a/docker/frontend/entrypoint.sh b/docker/frontend/entrypoint.sh index 7d5ee313d..4e14aefac 100644 --- a/docker/frontend/entrypoint.sh +++ b/docker/frontend/entrypoint.sh @@ -39,6 +39,7 @@ __AUDIT__=${AUDIT:=false} __MAINNET_BLOCK_AUDIT_START_HEIGHT__=${MAINNET_BLOCK_AUDIT_START_HEIGHT:=0} __TESTNET_BLOCK_AUDIT_START_HEIGHT__=${TESTNET_BLOCK_AUDIT_START_HEIGHT:=0} __SIGNET_BLOCK_AUDIT_START_HEIGHT__=${SIGNET_BLOCK_AUDIT_START_HEIGHT:=0} +__ACCELERATOR__=${ACCELERATOR:=false} __HISTORICAL_PRICE__=${HISTORICAL_PRICE:=true} # Export as environment variables to be used by envsubst @@ -65,6 +66,7 @@ export __AUDIT__ export __MAINNET_BLOCK_AUDIT_START_HEIGHT__ export __TESTNET_BLOCK_AUDIT_START_HEIGHT__ export __SIGNET_BLOCK_AUDIT_START_HEIGHT__ +export __ACCELERATOR__ export __HISTORICAL_PRICE__ folder=$(find /var/www/mempool -name "config.js" | xargs dirname) diff --git a/docker/init.sh b/docker/init.sh index ee9ac9542..3c5ec6aa3 100755 --- a/docker/init.sh +++ b/docker/init.sh @@ -1,7 +1,7 @@ #!/bin/sh #backend -cp ./docker/backend/* ./backend/ +cp -r ./docker/backend/* ./backend/ #geoip-data mkdir -p ./backend/GeoIP/ @@ -13,8 +13,8 @@ localhostIP="127.0.0.1" cp ./docker/frontend/* ./frontend cp ./nginx.conf ./frontend/ cp ./nginx-mempool.conf ./frontend/ -sed -i "s/${localhostIP}:80/0.0.0.0:__MEMPOOL_FRONTEND_HTTP_PORT__/g" ./frontend/nginx.conf -sed -i "s/${localhostIP}/0.0.0.0/g" ./frontend/nginx.conf -sed -i "s/user nobody;//g" ./frontend/nginx.conf -sed -i "s!/etc/nginx/nginx-mempool.conf!/etc/nginx/conf.d/nginx-mempool.conf!g" ./frontend/nginx.conf -sed -i "s/${localhostIP}:8999/__MEMPOOL_BACKEND_MAINNET_HTTP_HOST__:__MEMPOOL_BACKEND_MAINNET_HTTP_PORT__/g" ./frontend/nginx-mempool.conf +sed -i"" -e "s/${localhostIP}:80/0.0.0.0:__MEMPOOL_FRONTEND_HTTP_PORT__/g" ./frontend/nginx.conf +sed -i"" -e "s/${localhostIP}/0.0.0.0/g" ./frontend/nginx.conf +sed -i"" -e "s/user nobody;//g" ./frontend/nginx.conf +sed -i"" -e "s!/etc/nginx/nginx-mempool.conf!/etc/nginx/conf.d/nginx-mempool.conf!g" ./frontend/nginx.conf +sed -i"" -e "s/${localhostIP}:8999/__MEMPOOL_BACKEND_MAINNET_HTTP_HOST__:__MEMPOOL_BACKEND_MAINNET_HTTP_PORT__/g" ./frontend/nginx-mempool.conf diff --git a/frontend/.gitignore b/frontend/.gitignore index 8159e7c7b..d2a765dda 100644 --- a/frontend/.gitignore +++ b/frontend/.gitignore @@ -6,6 +6,13 @@ /out-tsc server.run.js +# docker +Dockerfile +entrypoint.sh +nginx-mempool.conf +nginx.conf +wait-for + # Only exists if Bazel was run /bazel-out diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 666bfc33c..0fab7e887 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -22,9 +22,9 @@ "@angular/platform-server": "^16.2.2", "@angular/router": "^16.2.2", "@fortawesome/angular-fontawesome": "~0.13.0", - "@fortawesome/fontawesome-common-types": "~6.4.0", - "@fortawesome/fontawesome-svg-core": "~6.4.0", - "@fortawesome/free-solid-svg-icons": "~6.4.0", + "@fortawesome/fontawesome-common-types": "~6.5.1", + "@fortawesome/fontawesome-svg-core": "~6.5.1", + "@fortawesome/free-solid-svg-icons": "~6.5.1", "@mempool/mempool.js": "2.3.0", "@ng-bootstrap/ng-bootstrap": "^15.1.0", "@types/qrcode": "~1.5.0", @@ -32,14 +32,13 @@ "browserify": "^17.0.0", "clipboard": "^2.0.11", "domino": "^2.1.6", - "echarts": "~5.4.3", - "echarts-gl": "^2.0.9", + "echarts": "~5.5.0", "lightweight-charts": "~3.8.0", - "ngx-echarts": "~16.0.0", + "ngx-echarts": "~16.2.0", "ngx-infinite-scroll": "^16.0.0", "qrcode": "1.5.1", "rxjs": "~7.8.1", - "tinyify": "^4.0.0", + "tinyify": "^3.1.0", "tlite": "^0.1.9", "tslib": "~2.6.0", "zone.js": "~0.13.1" @@ -59,10 +58,10 @@ "optionalDependencies": { "@cypress/schematic": "^2.5.0", "@types/cypress": "^1.1.3", - "cypress": "^12.17.2", - "cypress-fail-on-console-error": "~4.0.3", - "cypress-wait-until": "^2.0.0", - "mock-socket": "~9.2.1", + "cypress": "^13.6.2", + "cypress-fail-on-console-error": "~5.1.0", + "cypress-wait-until": "^2.0.1", + "mock-socket": "~9.3.1", "start-server-and-test": "~2.0.0" } }, @@ -1250,11 +1249,12 @@ "integrity": "sha512-H71nDOOL8Y7kWRLqf6Sums+01Q5msqBW2KhDUTemh1tvY04eSkSXrK0uj/4mmY0Xr16/3zyZmsrxN7CKuRbNRg==" }, "node_modules/@babel/code-frame": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.5.tgz", - "integrity": "sha512-Xmwn266vad+6DAqEB2A6V/CcZVp62BbwVmcOJc2RPuwih1kw02TjQvWVWlcKGbBPd+8/0V5DEkOcizRGYsspYQ==", + "version": "7.22.13", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", + "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", "dependencies": { - "@babel/highlight": "^7.22.5" + "@babel/highlight": "^7.22.13", + "chalk": "^2.4.2" }, "engines": { "node": ">=6.9.0" @@ -1464,20 +1464,33 @@ } }, "node_modules/@babel/helper-environment-visitor": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.5.tgz", - "integrity": "sha512-XGmhECfVA/5sAt+H+xpSg0mfrHq6FzNr9Oxh7PSEBBRUb/mL7Kz3NICXb194rCqAEdxkhPT1a88teizAFyvk8Q==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-function-name": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.22.5.tgz", - "integrity": "sha512-wtHSq6jMRE3uF2otvfuD3DIvVhOsSNshQl0Qrd7qC9oQJzHvOL4qQXlQn2916+CXGywIjpGuIkoyZRRxHPiNQQ==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "dependencies": { - "@babel/template": "^7.22.5", - "@babel/types": "^7.22.5" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name/node_modules/@babel/template": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", + "dependencies": { + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" }, "engines": { "node": ">=6.9.0" @@ -1627,9 +1640,9 @@ } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.5.tgz", - "integrity": "sha512-aJXu+6lErq8ltp+JhkJUfk1MTGyuA4v7f3pA+BJ5HLfNC6nAQ0Cpi9uOquUj8Hehg0aUiHzWQbOVJGao6ztBAQ==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", "engines": { "node": ">=6.9.0" } @@ -1669,12 +1682,12 @@ } }, "node_modules/@babel/highlight": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.5.tgz", - "integrity": "sha512-BSKlD1hgnedS5XRnGOljZawtag7H1yPfQp0tdNJCHoH6AZ+Pcm9VvkrK59/Yy593Ypg0zMxH2BxD1VPYUQ7UIw==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", + "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", "dependencies": { - "@babel/helper-validator-identifier": "^7.22.5", - "chalk": "^2.0.0", + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", "js-tokens": "^4.0.0" }, "engines": { @@ -1682,9 +1695,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.22.7", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.22.7.tgz", - "integrity": "sha512-7NF8pOkHP5o2vpmGgNGcfAeCvOYhGLyA3Z4eBQkT1RJlWu47n63bCs93QfJ2hIAFCil7L5P2IWhs1oToVgrL0Q==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.0.tgz", + "integrity": "sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw==", "bin": { "parser": "bin/babel-parser.js" }, @@ -2879,18 +2892,18 @@ } }, "node_modules/@babel/traverse": { - "version": "7.22.8", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.22.8.tgz", - "integrity": "sha512-y6LPR+wpM2I3qJrsheCTwhIinzkETbplIgPBbwvqPKc+uljeA5gP+3nP8irdYt1mjQaDnlIcG+dw8OjAco4GXw==", + "version": "7.23.2", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.2.tgz", + "integrity": "sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw==", "dependencies": { - "@babel/code-frame": "^7.22.5", - "@babel/generator": "^7.22.7", - "@babel/helper-environment-visitor": "^7.22.5", - "@babel/helper-function-name": "^7.22.5", + "@babel/code-frame": "^7.22.13", + "@babel/generator": "^7.23.0", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", "@babel/helper-hoist-variables": "^7.22.5", "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.22.7", - "@babel/types": "^7.22.5", + "@babel/parser": "^7.23.0", + "@babel/types": "^7.23.0", "debug": "^4.1.0", "globals": "^11.1.0" }, @@ -2898,100 +2911,40 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/types": { - "version": "7.22.10", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.22.10.tgz", - "integrity": "sha512-obaoigiLrlDZ7TUQln/8m4mSqIW2QFeOrCQc9r+xsaHGNoplVNYlRVpsfE8Vj35GEm2ZH4ZhrNYogs/3fj85kg==", + "node_modules/@babel/traverse/node_modules/@babel/generator": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.0.tgz", + "integrity": "sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g==", "dependencies": { - "@babel/helper-string-parser": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.5", - "to-fast-properties": "^2.0.0" + "@babel/types": "^7.23.0", + "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", + "jsesc": "^2.5.1" }, "engines": { "node": ">=6.9.0" } }, - "node_modules/@browserify/envify": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@browserify/envify/-/envify-6.0.0.tgz", - "integrity": "sha512-ovxHR0KTsRCyMNwD7MGV0+VCU1sT6Ds+itC4DaQHM41eUId+w5Jd0qlhLVoDkkIVBnkY3BAAM8yb2QfpBlHkPw==", + "node_modules/@babel/traverse/node_modules/@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", "dependencies": { - "acorn-node": "^2.0.1", - "dash-ast": "^2.0.1", - "multisplice": "^1.0.0", - "through2": "^4.0.2" - }, - "bin": { - "envify": "bin/envify" + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@browserify/envify/node_modules/acorn-node": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-2.0.1.tgz", - "integrity": "sha512-VLR5sHqjk+8c5hrKeP2fWaIHb8eewsoxnZ8r2qpwRHXMHuC7KyOPflnOx9dLssVQUurzJ7rO0OzIFjHcndafWw==", + "node_modules/@babel/types": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.0.tgz", + "integrity": "sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg==", "dependencies": { - "acorn": "^7.0.0", - "acorn-walk": "^7.0.0", - "xtend": "^4.0.2" - } - }, - "node_modules/@browserify/envify/node_modules/dash-ast": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/dash-ast/-/dash-ast-2.0.1.tgz", - "integrity": "sha512-5TXltWJGc+RdnabUGzhRae1TRq6m4gr+3K2wQX0is5/F2yS6MJXJvLyI3ErAnsAXuJoGqvfVD5icRgim07DrxQ==" - }, - "node_modules/@browserify/envify/node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" + "@babel/helper-string-parser": "^7.22.5", + "@babel/helper-validator-identifier": "^7.22.20", + "to-fast-properties": "^2.0.0" }, "engines": { - "node": ">= 6" - } - }, - "node_modules/@browserify/envify/node_modules/through2": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", - "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", - "dependencies": { - "readable-stream": "3" - } - }, - "node_modules/@browserify/uglifyify": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@browserify/uglifyify/-/uglifyify-6.0.0.tgz", - "integrity": "sha512-48M2a3novsgKhUSo/B3ja10awc7unliK1HfW6aYBJdLFQj3wXDx9BBJVfj6MVYERSQVEVjNHQQ7IK89h4MpCLw==", - "dependencies": { - "convert-source-map": "^1.9.0", - "minimatch": "^3.0.2", - "terser": "^5.15.1", - "through2": "^4.0.2", - "xtend": "^4.0.1" - } - }, - "node_modules/@browserify/uglifyify/node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/@browserify/uglifyify/node_modules/through2": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", - "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", - "dependencies": { - "readable-stream": "3" + "node": ">=6.9.0" } }, "node_modules/@colors/colors": { @@ -3016,9 +2969,9 @@ } }, "node_modules/@cypress/request": { - "version": "2.88.11", - "resolved": "https://registry.npmjs.org/@cypress/request/-/request-2.88.11.tgz", - "integrity": "sha512-M83/wfQ1EkspjkE2lNWNV5ui2Cv7UCv1swW1DqljahbzLVWltcsexQh8jYtuS/vzFXP+HySntGM83ZXA9fn17w==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.1.tgz", + "integrity": "sha512-TWivJlJi8ZDx2wGOw1dbLuHJKUYX7bWySw377nlnGOW3hP9/MUKIsEdXT/YngWxVdgNCHRBmFlBipE+5/2ZZlQ==", "optional": true, "dependencies": { "aws-sign2": "~0.7.0", @@ -3034,9 +2987,9 @@ "json-stringify-safe": "~5.0.1", "mime-types": "~2.1.19", "performance-now": "^2.1.0", - "qs": "~6.10.3", + "qs": "6.10.4", "safe-buffer": "^5.1.2", - "tough-cookie": "~2.5.0", + "tough-cookie": "^4.1.3", "tunnel-agent": "^0.6.0", "uuid": "^8.3.2" }, @@ -3514,33 +3467,33 @@ } }, "node_modules/@fortawesome/fontawesome-common-types": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.4.0.tgz", - "integrity": "sha512-HNii132xfomg5QVZw0HwXXpN22s7VBHQBv9CeOu9tfJnhsWQNd2lmTNi8CSrnw5B+5YOmzu1UoPAyxaXsJ6RgQ==", + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.5.1.tgz", + "integrity": "sha512-GkWzv+L6d2bI5f/Vk6ikJ9xtl7dfXtoRu3YGE6nq0p/FFqA1ebMOAWg3XgRyb0I6LYyYkiAo+3/KrwuBp8xG7A==", "hasInstallScript": true, "engines": { "node": ">=6" } }, "node_modules/@fortawesome/fontawesome-svg-core": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.4.0.tgz", - "integrity": "sha512-Bertv8xOiVELz5raB2FlXDPKt+m94MQ3JgDfsVbrqNpLU9+UE2E18GKjLKw+d3XbeYPqg1pzyQKGsrzbw+pPaw==", + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.5.1.tgz", + "integrity": "sha512-MfRCYlQPXoLlpem+egxjfkEuP9UQswTrlCOsknus/NcMoblTH2g0jPrapbcIb04KGA7E2GZxbAccGZfWoYgsrQ==", "hasInstallScript": true, "dependencies": { - "@fortawesome/fontawesome-common-types": "6.4.0" + "@fortawesome/fontawesome-common-types": "6.5.1" }, "engines": { "node": ">=6" } }, "node_modules/@fortawesome/free-solid-svg-icons": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.4.0.tgz", - "integrity": "sha512-kutPeRGWm8V5dltFP1zGjQOEAzaLZj4StdQhWVZnfGFCvAPVvHh8qk5bRrU4KXnRRRNni5tKQI9PBAdI6MP8nQ==", + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.5.1.tgz", + "integrity": "sha512-S1PPfU3mIJa59biTtXJz1oI0+KAXW6bkAb31XKhxdxtuXDiUIFsih4JR1v5BbxY7hVHsD1RKq+jRkVRaf773NQ==", "hasInstallScript": true, "dependencies": { - "@fortawesome/fontawesome-common-types": "6.4.0" + "@fortawesome/fontawesome-common-types": "6.5.1" }, "engines": { "node": ">=6" @@ -3564,6 +3517,35 @@ "ms": "^2.1.1" } }, + "node_modules/@goto-bus-stop/envify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@goto-bus-stop/envify/-/envify-5.0.0.tgz", + "integrity": "sha512-xAnxuDWmwQxO8CgVuPTxKuNsKDfwyXXTyAabG4sNoK59H/ZMC7BHxTA/4ehtinsxbcH7/9L65F5VhyNdQfUyqA==", + "dependencies": { + "acorn-node": "^2.0.1", + "dash-ast": "^2.0.1", + "multisplice": "^1.0.0", + "through2": "^2.0.5" + }, + "bin": { + "envify": "bin/envify" + } + }, + "node_modules/@goto-bus-stop/envify/node_modules/acorn-node": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-2.0.1.tgz", + "integrity": "sha512-VLR5sHqjk+8c5hrKeP2fWaIHb8eewsoxnZ8r2qpwRHXMHuC7KyOPflnOx9dLssVQUurzJ7rO0OzIFjHcndafWw==", + "dependencies": { + "acorn": "^7.0.0", + "acorn-walk": "^7.0.0", + "xtend": "^4.0.2" + } + }, + "node_modules/@goto-bus-stop/envify/node_modules/dash-ast": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/dash-ast/-/dash-ast-2.0.1.tgz", + "integrity": "sha512-5TXltWJGc+RdnabUGzhRae1TRq6m4gr+3K2wQX0is5/F2yS6MJXJvLyI3ErAnsAXuJoGqvfVD5icRgim07DrxQ==" + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -3790,14 +3772,6 @@ "ws": "8.3.0" } }, - "node_modules/@mempool/mempool.js/node_modules/axios": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.24.0.tgz", - "integrity": "sha512-Q6cWsys88HoPgAaFAVUb0WpPk0O8iTeisR9IMqy9G8AbO4NlpVknrnQS03zzF9PGAWgO3cgletO3VjV/P7VztA==", - "dependencies": { - "follow-redirects": "^1.14.4" - } - }, "node_modules/@mempool/mempool.js/node_modules/ws": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.3.0.tgz", @@ -4094,9 +4068,9 @@ } }, "node_modules/@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-11.2.2.tgz", + "integrity": "sha512-G2piCSxQ7oWOxwGSAyFHfPIsyeJGXYtc6mFbnFA+kRXkiEnTl8c/8jul2S329iFBnDI9HGoeWWAZvuvOkZccgw==", "optional": true, "dependencies": { "@sinonjs/commons": "^3.0.0" @@ -4333,9 +4307,9 @@ "integrity": "sha512-Jus9s4CDbqwocc5pOAnh8ShfrnMcPHuJYzVcSUU7lrh8Ni5HuIqX3oilL86p3dlTrk0LzHRCgA/GQ7uNCw6l2Q==" }, "node_modules/@types/node": { - "version": "18.11.9", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.9.tgz", - "integrity": "sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==" + "version": "18.17.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.17.18.tgz", + "integrity": "sha512-/4QOuy3ZpV7Ya1GTRz5CYSz3DgkKpyUptXuQ5PPce7uuyJAOR7r9FhkmxJfvcNUXyklbC63a+YvB3jxy7s9ngw==" }, "node_modules/@types/qrcode": { "version": "1.5.0", @@ -5376,27 +5350,11 @@ "optional": true }, "node_modules/axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "optional": true, + "version": "0.24.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.24.0.tgz", + "integrity": "sha512-Q6cWsys88HoPgAaFAVUb0WpPk0O8iTeisR9IMqy9G8AbO4NlpVknrnQS03zzF9PGAWgO3cgletO3VjV/P7VztA==", "dependencies": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - } - }, - "node_modules/axios/node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "optional": true, - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" + "follow-redirects": "^1.14.4" } }, "node_modules/babel-loader": { @@ -5574,9 +5532,9 @@ "optional": true }, "node_modules/bn.js": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.0.tgz", - "integrity": "sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw==" + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.1.tgz", + "integrity": "sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ==" }, "node_modules/body-parser": { "version": "1.20.1", @@ -5871,25 +5829,28 @@ } }, "node_modules/browserify-sign": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.1.tgz", - "integrity": "sha512-/vrA5fguVAKKAVTNJjgSm1tRQDHUU6DbwO9IROu/0WAzC8PKhucDSh18J0RMvVeHAn5puMd+QHC2erPRNf8lmg==", + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.2.tgz", + "integrity": "sha512-1rudGyeYY42Dk6texmv7c4VcQ0EsvVbLwZkA+AQB7SxvXxmcD93jcHie8bzecJ+ChDlmAm2Qyu0+Ccg5uhZXCg==", "dependencies": { - "bn.js": "^5.1.1", - "browserify-rsa": "^4.0.1", + "bn.js": "^5.2.1", + "browserify-rsa": "^4.1.0", "create-hash": "^1.2.0", "create-hmac": "^1.1.7", - "elliptic": "^6.5.3", + "elliptic": "^6.5.4", "inherits": "^2.0.4", - "parse-asn1": "^5.1.5", - "readable-stream": "^3.6.0", - "safe-buffer": "^5.2.0" + "parse-asn1": "^5.1.6", + "readable-stream": "^3.6.2", + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">= 4" } }, "node_modules/browserify-sign/node_modules/readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -6229,6 +6190,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/call-matcher": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/call-matcher/-/call-matcher-2.0.0.tgz", + "integrity": "sha512-CIDC5wZZfZ2VjZu849WQckS58Z3pJXFfRaSjNjgo/q3in5zxkhTwVL83vttgtmvyLG7TuDlLlBya7SKP6CjDIA==", + "dependencies": { + "deep-equal": "^1.0.0", + "espurify": "^2.0.0", + "estraverse": "^4.0.0" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -6271,17 +6242,18 @@ "optional": true }, "node_modules/chai": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.4.tgz", - "integrity": "sha512-yS5H68VYOCtN1cjfwumDSuzn/9c+yza4f3reKXlE5rUg7SFcCEy90gJvydNgOYtblyf4Zi6jIWRnXOgErta0KA==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.0.tgz", + "integrity": "sha512-x9cHNq1uvkCdU+5xTkNh5WtgD4e4yDFCsp9jVc7N7qVeKeftv3gO/ZrviX5d+3ZfxdYnZXZYujjRInu1RogU6A==", "optional": true, "dependencies": { "assertion-error": "^1.1.0", - "check-error": "^1.0.2", - "deep-eql": "^3.0.1", - "get-func-name": "^2.0.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", "pathval": "^1.1.1", - "type-detect": "^4.0.5" + "type-detect": "^4.0.8" }, "engines": { "node": ">=4" @@ -6306,10 +6278,13 @@ "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==" }, "node_modules/check-error": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", - "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", "optional": true, + "dependencies": { + "get-func-name": "^2.0.2" + }, "engines": { "node": "*" } @@ -6389,11 +6364,6 @@ "safe-buffer": "^5.0.1" } }, - "node_modules/claygl": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/claygl/-/claygl-1.3.0.tgz", - "integrity": "sha512-+gGtJjT6SSHD2l2yC3MCubW/sCV40tZuSs5opdtn79vFSGUgp/lH139RNEQ6Jy078/L0aV8odCw8RSrUcMfLaQ==" - }, "node_modules/clean-stack": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", @@ -7113,15 +7083,15 @@ "peer": true }, "node_modules/cypress": { - "version": "12.17.2", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-12.17.2.tgz", - "integrity": "sha512-hxWAaWbqQBzzMuadSGSuQg5PDvIGOovm6xm0hIfpCVcORsCAj/gF2p0EvfnJ4f+jK2PCiDgP6D2eeE9/FK4Mjg==", + "version": "13.6.2", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.6.2.tgz", + "integrity": "sha512-TW3bGdPU4BrfvMQYv1z3oMqj71YI4AlgJgnrycicmPZAXtvywVFZW9DAToshO65D97rCWfG/kqMFsYB6Kp91gQ==", "hasInstallScript": true, "optional": true, "dependencies": { - "@cypress/request": "^2.88.11", + "@cypress/request": "^3.0.0", "@cypress/xvfb": "^1.2.4", - "@types/node": "^14.14.31", + "@types/node": "^18.17.5", "@types/sinonjs__fake-timers": "8.1.1", "@types/sizzle": "^2.3.2", "arch": "^2.2.0", @@ -7154,6 +7124,7 @@ "minimist": "^1.2.8", "ospath": "^1.2.2", "pretty-bytes": "^5.6.0", + "process": "^0.11.10", "proxy-from-env": "1.0.0", "request-progress": "^3.0.0", "semver": "^7.5.3", @@ -7166,35 +7137,25 @@ "cypress": "bin/cypress" }, "engines": { - "node": "^14.0.0 || ^16.0.0 || >=18.0.0" + "node": "^16.0.0 || ^18.0.0 || >=20.0.0" } }, "node_modules/cypress-fail-on-console-error": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/cypress-fail-on-console-error/-/cypress-fail-on-console-error-4.0.3.tgz", - "integrity": "sha512-v2nPupd2brtxKLkDQX58SbEPWRF/2nDbqPTnYyhPIYHqG7U3P2dGUZ3zraETKKoLhU3+C0otjgB6Vg/bHhocQw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cypress-fail-on-console-error/-/cypress-fail-on-console-error-5.1.0.tgz", + "integrity": "sha512-u/AXLE9obLd9KcGHkGJluJVZeOj1EEOFOs0URxxca4FrftUDJQ3u+IoNfjRUjsrBKmJxgM4vKd0G10D+ZT1uIA==", "optional": true, "dependencies": { - "chai": "^4.3.4", - "sinon": "^15.0.0", + "chai": "^4.3.10", + "sinon": "^17.0.0", "sinon-chai": "^3.7.0", "type-detect": "^4.0.8" } }, "node_modules/cypress-wait-until": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/cypress-wait-until/-/cypress-wait-until-2.0.0.tgz", - "integrity": "sha512-ulUZyrWBn+OuC8oiQuGKAScDYfpaWnE3dEE/raUo64w4RHQxZrQ/iMIWT4ZjGMMPr3P+BFEALCRnjQeRqzZj6g==", - "optional": true, - "engines": { - "node": ">=18.16.0", - "npm": ">=9.5.1" - } - }, - "node_modules/cypress/node_modules/@types/node": { - "version": "14.18.53", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.53.tgz", - "integrity": "sha512-soGmOpVBUq+gaBMwom1M+krC/NNbWlosh4AtGA03SyWNDiqSKtwp7OulO1M6+mg8YkHMvJ/y0AkCeO8d1hNb7A==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/cypress-wait-until/-/cypress-wait-until-2.0.1.tgz", + "integrity": "sha512-+IyVnYNiaX1+C+V/LazrJWAi/CqiwfNoRSrFviECQEyolW1gDRy765PZosL2alSSGK8V10Y7BGfOQyZUDgmnjQ==", "optional": true }, "node_modules/cypress/node_modules/ansi-styles": { @@ -7446,22 +7407,40 @@ "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=" }, "node_modules/deep-eql": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", - "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", "optional": true, "dependencies": { "type-detect": "^4.0.0" }, "engines": { - "node": ">=0.12" + "node": ">=6" + } + }, + "node_modules/deep-equal": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.2.tgz", + "integrity": "sha512-5tdhKF6DbU7iIzrIOa1AOUt39ZRm13cmL1cGEh//aqR8x9+tNfbywRf0n5FD/18OKMdo7DNEtrX2t22ZAkI+eg==", + "dependencies": { + "is-arguments": "^1.1.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.5.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", - "dev": true + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=" }, "node_modules/default-gateway": { "version": "6.0.3", @@ -7482,6 +7461,19 @@ "clone": "^1.0.2" } }, + "node_modules/define-data-property": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", + "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", + "dependencies": { + "get-intrinsic": "^1.2.1", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/define-lazy-prop": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", @@ -7491,14 +7483,19 @@ } }, "node_modules/define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", "dependencies": { - "object-keys": "^1.0.12" + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" }, "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/defined": { @@ -7786,24 +7783,12 @@ } }, "node_modules/echarts": { - "version": "5.4.3", - "resolved": "https://registry.npmjs.org/echarts/-/echarts-5.4.3.tgz", - "integrity": "sha512-mYKxLxhzy6zyTi/FaEbJMOZU1ULGEQHaeIeuMR5L+JnJTpz+YR03mnnpBhbR4+UYJAgiXgpyTVLffPAjOTLkZA==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/echarts/-/echarts-5.5.0.tgz", + "integrity": "sha512-rNYnNCzqDAPCr4m/fqyUFv7fD9qIsd50S6GDFgO1DxZhncCsNsG7IfUlAlvZe5oSEQxtsjnHiUuppzccry93Xw==", "dependencies": { "tslib": "2.3.0", - "zrender": "5.4.4" - } - }, - "node_modules/echarts-gl": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/echarts-gl/-/echarts-gl-2.0.9.tgz", - "integrity": "sha512-oKeMdkkkpJGWOzjgZUsF41DOh6cMsyrGGXimbjK2l6Xeq/dBQu4ShG2w2Dzrs/1bD27b2pLTGSaUzouY191gzA==", - "dependencies": { - "claygl": "^1.2.1", - "zrender": "^5.1.1" - }, - "peerDependencies": { - "echarts": "^5.1.2" + "zrender": "5.5.0" } }, "node_modules/echarts/node_modules/tslib": { @@ -8680,6 +8665,11 @@ "node": ">=4" } }, + "node_modules/espurify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/espurify/-/espurify-2.1.1.tgz", + "integrity": "sha512-zttWvnkhcDyGOhSH4vO2qCBILpdCMv/MX8lp4cqgRkQoDRGK2oZxi2GfWhlP2dIXmk7BaKeOTuzbHhyC68o8XQ==" + }, "node_modules/esquery": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", @@ -9114,8 +9104,7 @@ "node_modules/fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" }, "node_modules/fast-safe-stringify": { "version": "2.0.7", @@ -9283,9 +9272,9 @@ "devOptional": true }, "node_modules/follow-redirects": { - "version": "1.14.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", - "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==", + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", "funding": [ { "type": "individual", @@ -9456,9 +9445,20 @@ } }, "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/gauge": { "version": "4.0.4", @@ -9500,22 +9500,23 @@ } }, "node_modules/get-func-name": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", - "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", "optional": true, "engines": { "node": "*" } }, "node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", + "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -9651,6 +9652,17 @@ "delegate": "^3.1.2" } }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graceful-fs": { "version": "4.2.9", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", @@ -9724,10 +9736,46 @@ "node": ">=4" } }, + "node_modules/has-property-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", + "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", + "dependencies": { + "get-intrinsic": "^1.2.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", + "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dependencies": { + "has-symbols": "^1.0.2" + }, "engines": { "node": ">= 0.4" }, @@ -9794,6 +9842,17 @@ "minimalistic-assert": "^1.0.1" } }, + "node_modules/hasown": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", + "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hdr-histogram-js": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/hdr-histogram-js/-/hdr-histogram-js-2.0.3.tgz", @@ -10351,11 +10410,12 @@ } }, "node_modules/is-arguments": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.0.tgz", - "integrity": "sha512-1Ij4lOMPl/xB5kBDn7I+b2ttPMKa8szhEIrXDuXQD/oe3HJLTLhqhgGspwgyGd6MOywBUqVvYicF72lkgDnIHg==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", "dependencies": { - "call-bind": "^1.0.0" + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" @@ -10442,9 +10502,12 @@ } }, "node_modules/is-date-object": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", - "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, "engines": { "node": ">= 0.4" }, @@ -10600,12 +10663,12 @@ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==" }, "node_modules/is-regex": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz", - "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", "dependencies": { "call-bind": "^1.0.2", - "has-symbols": "^1.0.1" + "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" @@ -10830,9 +10893,9 @@ } }, "node_modules/joi": { - "version": "17.9.2", - "resolved": "https://registry.npmjs.org/joi/-/joi-17.9.2.tgz", - "integrity": "sha512-Itk/r+V4Dx0V3c7RLFdRh12IOjySm2/WGPMubBT92cQvRfYZhPM2W0hZlctjj72iES8jsRCwp7S/cRmWBnJ4nw==", + "version": "17.11.0", + "resolved": "https://registry.npmjs.org/joi/-/joi-17.11.0.tgz", + "integrity": "sha512-NgB+lZLNoqISVy1rZocE9PZI36bL/77ie924Ri43yEvi9GUUMPeyVIr8KdFTMUlby1p0PBYMk9spIxEUQYqrJQ==", "optional": true, "dependencies": { "@hapi/hoek": "^9.0.0", @@ -10976,28 +11039,6 @@ "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==" }, - "node_modules/jsdom/node_modules/tough-cookie": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz", - "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==", - "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/jsdom/node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", - "engines": { - "node": ">= 4.0.0" - } - }, "node_modules/jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", @@ -11380,6 +11421,18 @@ "node": ">=0.10.0" } }, + "node_modules/levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", + "dependencies": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/license-webpack-plugin": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/license-webpack-plugin/-/license-webpack-plugin-4.0.2.tgz", @@ -11710,6 +11763,15 @@ "node": ">=8.0" } }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "optional": true, + "dependencies": { + "get-func-name": "^2.0.1" + } + }, "node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -12200,9 +12262,9 @@ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" }, "node_modules/mock-socket": { - "version": "9.2.1", - "resolved": "https://registry.npmjs.org/mock-socket/-/mock-socket-9.2.1.tgz", - "integrity": "sha512-aw9F9T9G2zpGipLLhSNh6ZpgUyUl4frcVmRN08uE1NWPWg43Wx6+sGPDbQ7E5iFZZDJW5b5bypMeAEHqTbIFag==", + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/mock-socket/-/mock-socket-9.3.1.tgz", + "integrity": "sha512-qxBgB7Qa2sEQgHFjj0dSigq7fX4k6Saisd5Nelwp2q8mlbAFh5dHV9JTTlF8viYJLSSWgMCZFUom8PJcMNBoJw==", "optional": true, "engines": { "node": ">= 8" @@ -12250,9 +12312,9 @@ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "node_modules/multi-stage-sourcemap": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/multi-stage-sourcemap/-/multi-stage-sourcemap-0.3.1.tgz", - "integrity": "sha512-UiTLYjqeIoVnJHyWGskwMKIhtZKK9uXUjSTWuwatarrc0d2H/6MAVFdwvEA/aKOHamIn7z4tfvxjz+FYucFpNQ==", + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/multi-stage-sourcemap/-/multi-stage-sourcemap-0.2.1.tgz", + "integrity": "sha512-umaOM+8BZByZIB/ciD3dQLzTv50rEkkGJV78ta/tIVc/J/rfGZY5y1R+fBD3oTaolx41mK8rRcyGtYbDXlzx8Q==", "dependencies": { "source-map": "^0.1.34" } @@ -12451,9 +12513,9 @@ "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=" }, "node_modules/ngx-echarts": { - "version": "16.0.0", - "resolved": "https://registry.npmjs.org/ngx-echarts/-/ngx-echarts-16.0.0.tgz", - "integrity": "sha512-hdM7/CL29bY3sF3V5ihb7H1NeUsQlhijp8tVxT23+vkNTf9SJrUHPjs9oHOMkbTlr2Q8HB+eVpckYAL/tuK0CQ==", + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/ngx-echarts/-/ngx-echarts-16.2.0.tgz", + "integrity": "sha512-yhuDbp6qdkmR4kRVLS06Z0Iumod7xOj5n/Z++clRiKM24OQ4sM8WuOTicdfWy6eeYDNywdGSrri4Y5SUGRD8bg==", "dependencies": { "tslib": "^2.3.0" }, @@ -12488,9 +12550,9 @@ } }, "node_modules/nise": { - "version": "5.1.4", - "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.4.tgz", - "integrity": "sha512-8+Ib8rRJ4L0o3kfmyVCL7gzrohyDe0cMFTBa2d364yIrEGMEoetznKJx899YxjybU6bL9SQkYPSBBs1gyYs8Xg==", + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.5.tgz", + "integrity": "sha512-VJuPIfUFaXNRzETTQEEItTOP8Y171ijr+JLq42wHes3DiryR8vT+1TXQW/Rx8JNUhyYYWyIvjXTU6dOhJcs9Nw==", "optional": true, "dependencies": { "@sinonjs/commons": "^2.0.0", @@ -12509,6 +12571,24 @@ "type-detect": "4.0.8" } }, + "node_modules/nise/node_modules/@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "optional": true, + "dependencies": { + "@sinonjs/commons": "^3.0.0" + } + }, + "node_modules/nise/node_modules/@sinonjs/fake-timers/node_modules/@sinonjs/commons": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", + "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", + "optional": true, + "dependencies": { + "type-detect": "4.0.8" + } + }, "node_modules/nise/node_modules/isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", @@ -12765,6 +12845,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", @@ -12862,6 +12957,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "dependencies": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/ora": { "version": "5.4.1", "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", @@ -13569,6 +13680,14 @@ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" }, + "node_modules/prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==", + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/prettier": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.0.0.tgz", @@ -14034,6 +14153,22 @@ "resolved": "https://registry.npmjs.org/regex-parser/-/regex-parser-2.2.11.tgz", "integrity": "sha512-jbD/FT0+9MBU2XAZluI7w2OBs1RBi6p9M83nkoZayQXXU9e8Robt69FcZc7wU4eJD/YFTjn1JdCk3rbMJajz8Q==" }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.1.tgz", + "integrity": "sha512-sy6TXMN+hnP/wMy+ISxg3krXx7BAtWVO4UouuCN/ziM9UEne0euamVNafDfvC83bRNr95y0V5iijeDQFUNpvrg==", + "dependencies": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "set-function-name": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/regexpp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", @@ -14611,6 +14746,19 @@ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" }, + "node_modules/set-function-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.1.tgz", + "integrity": "sha512-tMNCiqYVkXIZgc2Hnoy2IvC/f8ezc5koaRFkCjrpWzGpCd3qbZXPzVy9MAZzK1ch/X0jvSkojys3oqJN0qCmdA==", + "dependencies": { + "define-data-property": "^1.0.1", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -14725,16 +14873,16 @@ ] }, "node_modules/sinon": { - "version": "15.2.0", - "resolved": "https://registry.npmjs.org/sinon/-/sinon-15.2.0.tgz", - "integrity": "sha512-nPS85arNqwBXaIsFCkolHjGIkFo+Oxu9vbgmBJizLAhqe6P2o3Qmj3KCUoRkfhHtvgDhZdWD3risLHAUJ8npjw==", + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/sinon/-/sinon-17.0.1.tgz", + "integrity": "sha512-wmwE19Lie0MLT+ZYNpDymasPHUKTaZHUH/pKEubRXIzySv9Atnlw+BUMGCzWgV7b7wO+Hw6f1TEOr0IUnmU8/g==", "optional": true, "dependencies": { "@sinonjs/commons": "^3.0.0", - "@sinonjs/fake-timers": "^10.3.0", + "@sinonjs/fake-timers": "^11.2.2", "@sinonjs/samsam": "^8.0.0", "diff": "^5.1.0", - "nise": "^5.1.4", + "nise": "^5.1.5", "supports-color": "^7.2.0" }, "funding": { @@ -15137,9 +15285,9 @@ } }, "node_modules/start-server-and-test": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/start-server-and-test/-/start-server-and-test-2.0.0.tgz", - "integrity": "sha512-UqKLw0mJbfrsG1jcRLTUlvuRi9sjNuUiDOLI42r7R5fA9dsFoywAy9DoLXNYys9B886E4RCKb+qM1Gzu96h7DQ==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/start-server-and-test/-/start-server-and-test-2.0.3.tgz", + "integrity": "sha512-QsVObjfjFZKJE6CS6bSKNwWZCKBG6975/jKRPPGFfFh+yOQglSeGXiNWjzgQNXdphcBI9nXbyso9tPfX4YAUhg==", "optional": true, "dependencies": { "arg": "^5.0.2", @@ -15149,7 +15297,7 @@ "execa": "5.1.1", "lazy-ass": "1.6.0", "ps-tree": "1.2.0", - "wait-on": "7.0.1" + "wait-on": "7.2.0" }, "bin": { "server-test": "src/bin/start.js", @@ -15157,7 +15305,7 @@ "start-test": "src/bin/start.js" }, "engines": { - "node": ">=6" + "node": ">=16" } }, "node_modules/start-server-and-test/node_modules/arg": { @@ -15572,70 +15720,30 @@ "integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==" }, "node_modules/tinyify": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/tinyify/-/tinyify-4.0.0.tgz", - "integrity": "sha512-jNDxImwUrJJAU2NyGG144J8aWx2ni39UuBo7ppCXFRmhSH0CbpWL4HgjNvrsAW05WQAgNZePwAlEemNuB+byaA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyify/-/tinyify-3.1.0.tgz", + "integrity": "sha512-r4tHoDkWhhoItWbxJ3KCHXask3hJN7gCUkR5PLfnQzQagTA6oDkzhCbiEDHkMqo7Ck7vVSA1pTP1gDc9p1AC1w==", "dependencies": { - "@browserify/envify": "^6.0.0", - "@browserify/uglifyify": "^6.0.0", + "@goto-bus-stop/envify": "^5.0.0", + "acorn-node": "^1.8.2", "browser-pack-flat": "^3.0.9", "bundle-collapser": "^1.3.0", "common-shakeify": "^1.1.1", + "dash-ast": "^1.0.0", "minify-stream": "^2.0.1", "multisplice": "^1.0.0", - "terser": "3.16.1", - "through2": "^4.0.2", - "unassertify": "^3.0.1" - } - }, - "node_modules/tinyify/node_modules/commander": { - "version": "2.17.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", - "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==" - }, - "node_modules/tinyify/node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/tinyify/node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tinyify/node_modules/terser": { - "version": "3.16.1", - "resolved": "https://registry.npmjs.org/terser/-/terser-3.16.1.tgz", - "integrity": "sha512-JDJjgleBROeek2iBcSNzOHLKsB/MdDf+E/BOAJ0Tk9r7p9/fVobfv7LMJ/g/k3v9SXdmjZnIlFd5nfn/Rt0Xow==", - "dependencies": { - "commander": "~2.17.1", - "source-map": "~0.6.1", - "source-map-support": "~0.5.9" - }, - "bin": { - "terser": "bin/uglifyjs" - }, - "engines": { - "node": ">=6.0.0" + "through2": "^3.0.1", + "uglifyify": "^5.0.0", + "unassertify": "^2.1.1" } }, "node_modules/tinyify/node_modules/through2": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", - "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-3.0.2.tgz", + "integrity": "sha512-enaDQ4MUyP2W6ZyT6EsMzqBPZaM/avg8iuo+l2d3QCs0J+6RaqkHV/2/lOwDTueBHeJ/2LG9lrLW3d5rWPucuQ==", "dependencies": { - "readable-stream": "3" + "inherits": "^2.0.4", + "readable-stream": "2 || 3" } }, "node_modules/tlite": { @@ -15682,16 +15790,25 @@ } }, "node_modules/tough-cookie": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", - "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", - "optional": true, + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz", + "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==", "dependencies": { - "psl": "^1.1.28", - "punycode": "^2.1.1" + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" }, "engines": { - "node": ">=0.8" + "node": ">=6" + } + }, + "node_modules/tough-cookie/node_modules/universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "engines": { + "node": ">= 4.0.0" } }, "node_modules/tr46": { @@ -15899,6 +16016,17 @@ "resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz", "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==" }, + "node_modules/type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", + "dependencies": { + "prelude-ls": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -15973,6 +16101,47 @@ "node": "*" } }, + "node_modules/uglifyify": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/uglifyify/-/uglifyify-5.0.2.tgz", + "integrity": "sha512-NcSk6pgoC+IgwZZ2tVLVHq+VNKSvLPlLkF5oUiHPVOJI0s/OlSVYEGXG9PCAH0hcyFZLyvt4KBdPAQBRlVDn1Q==", + "dependencies": { + "convert-source-map": "~1.1.0", + "minimatch": "^3.0.2", + "terser": "^3.7.5", + "through": "~2.3.4", + "xtend": "^4.0.1" + } + }, + "node_modules/uglifyify/node_modules/convert-source-map": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.1.3.tgz", + "integrity": "sha512-Y8L5rp6jo+g9VEPgvqNfEopjTR4OTYct8lXlS8iVQdmnjDvbdbzYe9rjtFCB9egC86JoNCU61WRY+ScjkZpnIg==" + }, + "node_modules/uglifyify/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/uglifyify/node_modules/terser": { + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-3.17.0.tgz", + "integrity": "sha512-/FQzzPJmCpjAH9Xvk2paiWrFq+5M6aVOf+2KRbwhByISDX/EujxsK+BAvrhb6H+2rtrLCHK9N01wO014vrIwVQ==", + "dependencies": { + "commander": "^2.19.0", + "source-map": "~0.6.1", + "source-map-support": "~0.5.10" + }, + "bin": { + "terser": "bin/uglifyjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/umd": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/umd/-/umd-3.0.3.tgz", @@ -15982,38 +16151,36 @@ } }, "node_modules/unassert": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/unassert/-/unassert-2.0.2.tgz", - "integrity": "sha512-P6OOg/aRdQmWH+b0g+T4U+9MgL+DG7w6oQPG+N3F2IMuvvd1WfZ5alT/Rjik2lMFVyhfACUxF7PGP1VCwSHlQA==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/unassert/-/unassert-1.6.0.tgz", + "integrity": "sha512-GoMtWTwGSxSFuRD0NKmbjlx3VJkgvSogzDzMPpJXYmBZv6MIWButsyMqEYhMx3NI4osXACcZA9mXiBteXyJtRw==", "dependencies": { - "estraverse": "^5.0.0" - } - }, - "node_modules/unassert/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "engines": { - "node": ">=4.0" + "acorn": "^7.0.0", + "call-matcher": "^2.0.0", + "deep-equal": "^1.0.0", + "espurify": "^2.0.1", + "estraverse": "^4.1.0", + "esutils": "^2.0.2", + "object-assign": "^4.1.0" } }, "node_modules/unassertify": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/unassertify/-/unassertify-3.0.1.tgz", - "integrity": "sha512-461ykSPY3oWU+39J5haiq7S/hcYy1oGJ2nHU92lqdL3jft+pSU6oAbb7o6VVmM7nZGLqppszgyzfpCnRBFgFtw==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/unassertify/-/unassertify-2.1.1.tgz", + "integrity": "sha512-YIAaIlc6/KC9Oib8cVZLlpDDhK1UTEuaDyx9BwD97xqxDZC0cJOqwFcs/Y6K3m73B5VzHsRTBLXNO0dxS/GkTw==", "dependencies": { - "acorn": "^8.0.0", + "acorn": "^5.1.0", "convert-source-map": "^1.1.1", - "escodegen": "^2.0.0", - "multi-stage-sourcemap": "^0.3.1", + "escodegen": "^1.6.1", + "multi-stage-sourcemap": "^0.2.1", "through": "^2.3.7", - "unassert": "^2.0.0" + "unassert": "^1.3.1" } }, "node_modules/unassertify/node_modules/acorn": { - "version": "8.10.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", - "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", + "version": "5.7.4", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.4.tgz", + "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", "bin": { "acorn": "bin/acorn" }, @@ -16021,6 +16188,36 @@ "node": ">=0.4.0" } }, + "node_modules/unassertify/node_modules/escodegen": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", + "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=4.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/unassertify/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/unbox-primitive": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", @@ -16353,16 +16550,16 @@ } }, "node_modules/wait-on": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-7.0.1.tgz", - "integrity": "sha512-9AnJE9qTjRQOlTZIldAaf/da2eW0eSRSgcqq85mXQja/DW3MriHxkpODDSUEg+Gri/rKEcXUZHe+cevvYItaog==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-7.2.0.tgz", + "integrity": "sha512-wCQcHkRazgjG5XoAq9jbTMLpNIjoSlZslrJ2+N9MxDsGEv1HnFoVjOCexL0ESva7Y9cu350j+DWADdk54s4AFQ==", "optional": true, "dependencies": { - "axios": "^0.27.2", - "joi": "^17.7.0", + "axios": "^1.6.1", + "joi": "^17.11.0", "lodash": "^4.17.21", - "minimist": "^1.2.7", - "rxjs": "^7.8.0" + "minimist": "^1.2.8", + "rxjs": "^7.8.1" }, "bin": { "wait-on": "bin/wait-on" @@ -16371,6 +16568,37 @@ "node": ">=12.0.0" } }, + "node_modules/wait-on/node_modules/axios": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", + "integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", + "optional": true, + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/wait-on/node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "optional": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/wait-on/node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "optional": true + }, "node_modules/watchpack": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz", @@ -16770,6 +16998,14 @@ "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.1.tgz", "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==" }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/wrap-ansi": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", @@ -17083,9 +17319,9 @@ } }, "node_modules/zrender": { - "version": "5.4.4", - "resolved": "https://registry.npmjs.org/zrender/-/zrender-5.4.4.tgz", - "integrity": "sha512-0VxCNJ7AGOMCWeHVyTrGzUgrK4asT4ml9PEkeGirAkKNYXYzoPJCLvmyfdoOXcjTHPs10OZVMfD1Rwg16AZyYw==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/zrender/-/zrender-5.5.0.tgz", + "integrity": "sha512-O3MilSi/9mwoovx77m6ROZM7sXShR/O/JIanvzTwjN3FORfLSr81PsUGd7jlaYOeds9d8tw82oP44+3YucVo+w==", "dependencies": { "tslib": "2.3.0" } @@ -17790,11 +18026,12 @@ "integrity": "sha512-H71nDOOL8Y7kWRLqf6Sums+01Q5msqBW2KhDUTemh1tvY04eSkSXrK0uj/4mmY0Xr16/3zyZmsrxN7CKuRbNRg==" }, "@babel/code-frame": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.5.tgz", - "integrity": "sha512-Xmwn266vad+6DAqEB2A6V/CcZVp62BbwVmcOJc2RPuwih1kw02TjQvWVWlcKGbBPd+8/0V5DEkOcizRGYsspYQ==", + "version": "7.22.13", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", + "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", "requires": { - "@babel/highlight": "^7.22.5" + "@babel/highlight": "^7.22.13", + "chalk": "^2.4.2" } }, "@babel/compat-data": { @@ -17959,17 +18196,29 @@ } }, "@babel/helper-environment-visitor": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.5.tgz", - "integrity": "sha512-XGmhECfVA/5sAt+H+xpSg0mfrHq6FzNr9Oxh7PSEBBRUb/mL7Kz3NICXb194rCqAEdxkhPT1a88teizAFyvk8Q==" + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", + "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==" }, "@babel/helper-function-name": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.22.5.tgz", - "integrity": "sha512-wtHSq6jMRE3uF2otvfuD3DIvVhOsSNshQl0Qrd7qC9oQJzHvOL4qQXlQn2916+CXGywIjpGuIkoyZRRxHPiNQQ==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", + "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", "requires": { - "@babel/template": "^7.22.5", - "@babel/types": "^7.22.5" + "@babel/template": "^7.22.15", + "@babel/types": "^7.23.0" + }, + "dependencies": { + "@babel/template": { + "version": "7.22.15", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", + "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", + "requires": { + "@babel/code-frame": "^7.22.13", + "@babel/parser": "^7.22.15", + "@babel/types": "^7.22.15" + } + } } }, "@babel/helper-hoist-variables": { @@ -18071,9 +18320,9 @@ "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==" }, "@babel/helper-validator-identifier": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.5.tgz", - "integrity": "sha512-aJXu+6lErq8ltp+JhkJUfk1MTGyuA4v7f3pA+BJ5HLfNC6nAQ0Cpi9uOquUj8Hehg0aUiHzWQbOVJGao6ztBAQ==" + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==" }, "@babel/helper-validator-option": { "version": "7.22.5", @@ -18101,19 +18350,19 @@ } }, "@babel/highlight": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.5.tgz", - "integrity": "sha512-BSKlD1hgnedS5XRnGOljZawtag7H1yPfQp0tdNJCHoH6AZ+Pcm9VvkrK59/Yy593Ypg0zMxH2BxD1VPYUQ7UIw==", + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", + "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", "requires": { - "@babel/helper-validator-identifier": "^7.22.5", - "chalk": "^2.0.0", + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", "js-tokens": "^4.0.0" } }, "@babel/parser": { - "version": "7.22.7", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.22.7.tgz", - "integrity": "sha512-7NF8pOkHP5o2vpmGgNGcfAeCvOYhGLyA3Z4eBQkT1RJlWu47n63bCs93QfJ2hIAFCil7L5P2IWhs1oToVgrL0Q==" + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.0.tgz", + "integrity": "sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw==" }, "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { "version": "7.22.5", @@ -18890,110 +19139,54 @@ } }, "@babel/traverse": { - "version": "7.22.8", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.22.8.tgz", - "integrity": "sha512-y6LPR+wpM2I3qJrsheCTwhIinzkETbplIgPBbwvqPKc+uljeA5gP+3nP8irdYt1mjQaDnlIcG+dw8OjAco4GXw==", + "version": "7.23.2", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.2.tgz", + "integrity": "sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw==", "requires": { - "@babel/code-frame": "^7.22.5", - "@babel/generator": "^7.22.7", - "@babel/helper-environment-visitor": "^7.22.5", - "@babel/helper-function-name": "^7.22.5", + "@babel/code-frame": "^7.22.13", + "@babel/generator": "^7.23.0", + "@babel/helper-environment-visitor": "^7.22.20", + "@babel/helper-function-name": "^7.23.0", "@babel/helper-hoist-variables": "^7.22.5", "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.22.7", - "@babel/types": "^7.22.5", + "@babel/parser": "^7.23.0", + "@babel/types": "^7.23.0", "debug": "^4.1.0", "globals": "^11.1.0" + }, + "dependencies": { + "@babel/generator": { + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.0.tgz", + "integrity": "sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g==", + "requires": { + "@babel/types": "^7.23.0", + "@jridgewell/gen-mapping": "^0.3.2", + "@jridgewell/trace-mapping": "^0.3.17", + "jsesc": "^2.5.1" + } + }, + "@jridgewell/trace-mapping": { + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "requires": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + } } }, "@babel/types": { - "version": "7.22.10", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.22.10.tgz", - "integrity": "sha512-obaoigiLrlDZ7TUQln/8m4mSqIW2QFeOrCQc9r+xsaHGNoplVNYlRVpsfE8Vj35GEm2ZH4ZhrNYogs/3fj85kg==", + "version": "7.23.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.0.tgz", + "integrity": "sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg==", "requires": { "@babel/helper-string-parser": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.5", + "@babel/helper-validator-identifier": "^7.22.20", "to-fast-properties": "^2.0.0" } }, - "@browserify/envify": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@browserify/envify/-/envify-6.0.0.tgz", - "integrity": "sha512-ovxHR0KTsRCyMNwD7MGV0+VCU1sT6Ds+itC4DaQHM41eUId+w5Jd0qlhLVoDkkIVBnkY3BAAM8yb2QfpBlHkPw==", - "requires": { - "acorn-node": "^2.0.1", - "dash-ast": "^2.0.1", - "multisplice": "^1.0.0", - "through2": "^4.0.2" - }, - "dependencies": { - "acorn-node": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-2.0.1.tgz", - "integrity": "sha512-VLR5sHqjk+8c5hrKeP2fWaIHb8eewsoxnZ8r2qpwRHXMHuC7KyOPflnOx9dLssVQUurzJ7rO0OzIFjHcndafWw==", - "requires": { - "acorn": "^7.0.0", - "acorn-walk": "^7.0.0", - "xtend": "^4.0.2" - } - }, - "dash-ast": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/dash-ast/-/dash-ast-2.0.1.tgz", - "integrity": "sha512-5TXltWJGc+RdnabUGzhRae1TRq6m4gr+3K2wQX0is5/F2yS6MJXJvLyI3ErAnsAXuJoGqvfVD5icRgim07DrxQ==" - }, - "readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "through2": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", - "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", - "requires": { - "readable-stream": "3" - } - } - } - }, - "@browserify/uglifyify": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@browserify/uglifyify/-/uglifyify-6.0.0.tgz", - "integrity": "sha512-48M2a3novsgKhUSo/B3ja10awc7unliK1HfW6aYBJdLFQj3wXDx9BBJVfj6MVYERSQVEVjNHQQ7IK89h4MpCLw==", - "requires": { - "convert-source-map": "^1.9.0", - "minimatch": "^3.0.2", - "terser": "^5.15.1", - "through2": "^4.0.2", - "xtend": "^4.0.1" - }, - "dependencies": { - "readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "through2": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", - "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", - "requires": { - "readable-stream": "3" - } - } - } - }, "@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -19010,9 +19203,9 @@ } }, "@cypress/request": { - "version": "2.88.11", - "resolved": "https://registry.npmjs.org/@cypress/request/-/request-2.88.11.tgz", - "integrity": "sha512-M83/wfQ1EkspjkE2lNWNV5ui2Cv7UCv1swW1DqljahbzLVWltcsexQh8jYtuS/vzFXP+HySntGM83ZXA9fn17w==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.1.tgz", + "integrity": "sha512-TWivJlJi8ZDx2wGOw1dbLuHJKUYX7bWySw377nlnGOW3hP9/MUKIsEdXT/YngWxVdgNCHRBmFlBipE+5/2ZZlQ==", "optional": true, "requires": { "aws-sign2": "~0.7.0", @@ -19028,9 +19221,9 @@ "json-stringify-safe": "~5.0.1", "mime-types": "~2.1.19", "performance-now": "^2.1.0", - "qs": "~6.10.3", + "qs": "6.10.4", "safe-buffer": "^5.1.2", - "tough-cookie": "~2.5.0", + "tough-cookie": "^4.1.3", "tunnel-agent": "^0.6.0", "uuid": "^8.3.2" } @@ -19278,24 +19471,24 @@ } }, "@fortawesome/fontawesome-common-types": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.4.0.tgz", - "integrity": "sha512-HNii132xfomg5QVZw0HwXXpN22s7VBHQBv9CeOu9tfJnhsWQNd2lmTNi8CSrnw5B+5YOmzu1UoPAyxaXsJ6RgQ==" + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.5.1.tgz", + "integrity": "sha512-GkWzv+L6d2bI5f/Vk6ikJ9xtl7dfXtoRu3YGE6nq0p/FFqA1ebMOAWg3XgRyb0I6LYyYkiAo+3/KrwuBp8xG7A==" }, "@fortawesome/fontawesome-svg-core": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.4.0.tgz", - "integrity": "sha512-Bertv8xOiVELz5raB2FlXDPKt+m94MQ3JgDfsVbrqNpLU9+UE2E18GKjLKw+d3XbeYPqg1pzyQKGsrzbw+pPaw==", + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.5.1.tgz", + "integrity": "sha512-MfRCYlQPXoLlpem+egxjfkEuP9UQswTrlCOsknus/NcMoblTH2g0jPrapbcIb04KGA7E2GZxbAccGZfWoYgsrQ==", "requires": { - "@fortawesome/fontawesome-common-types": "6.4.0" + "@fortawesome/fontawesome-common-types": "6.5.1" } }, "@fortawesome/free-solid-svg-icons": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.4.0.tgz", - "integrity": "sha512-kutPeRGWm8V5dltFP1zGjQOEAzaLZj4StdQhWVZnfGFCvAPVvHh8qk5bRrU4KXnRRRNni5tKQI9PBAdI6MP8nQ==", + "version": "6.5.1", + "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.5.1.tgz", + "integrity": "sha512-S1PPfU3mIJa59biTtXJz1oI0+KAXW6bkAb31XKhxdxtuXDiUIFsih4JR1v5BbxY7hVHsD1RKq+jRkVRaf773NQ==", "requires": { - "@fortawesome/fontawesome-common-types": "6.4.0" + "@fortawesome/fontawesome-common-types": "6.5.1" } }, "@goto-bus-stop/common-shake": { @@ -19318,6 +19511,34 @@ } } }, + "@goto-bus-stop/envify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@goto-bus-stop/envify/-/envify-5.0.0.tgz", + "integrity": "sha512-xAnxuDWmwQxO8CgVuPTxKuNsKDfwyXXTyAabG4sNoK59H/ZMC7BHxTA/4ehtinsxbcH7/9L65F5VhyNdQfUyqA==", + "requires": { + "acorn-node": "^2.0.1", + "dash-ast": "^2.0.1", + "multisplice": "^1.0.0", + "through2": "^2.0.5" + }, + "dependencies": { + "acorn-node": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/acorn-node/-/acorn-node-2.0.1.tgz", + "integrity": "sha512-VLR5sHqjk+8c5hrKeP2fWaIHb8eewsoxnZ8r2qpwRHXMHuC7KyOPflnOx9dLssVQUurzJ7rO0OzIFjHcndafWw==", + "requires": { + "acorn": "^7.0.0", + "acorn-walk": "^7.0.0", + "xtend": "^4.0.2" + } + }, + "dash-ast": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/dash-ast/-/dash-ast-2.0.1.tgz", + "integrity": "sha512-5TXltWJGc+RdnabUGzhRae1TRq6m4gr+3K2wQX0is5/F2yS6MJXJvLyI3ErAnsAXuJoGqvfVD5icRgim07DrxQ==" + } + } + }, "@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -19488,14 +19709,6 @@ "ws": "8.3.0" }, "dependencies": { - "axios": { - "version": "0.24.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.24.0.tgz", - "integrity": "sha512-Q6cWsys88HoPgAaFAVUb0WpPk0O8iTeisR9IMqy9G8AbO4NlpVknrnQS03zzF9PGAWgO3cgletO3VjV/P7VztA==", - "requires": { - "follow-redirects": "^1.14.4" - } - }, "ws": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.3.0.tgz", @@ -19700,9 +19913,9 @@ } }, "@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "version": "11.2.2", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-11.2.2.tgz", + "integrity": "sha512-G2piCSxQ7oWOxwGSAyFHfPIsyeJGXYtc6mFbnFA+kRXkiEnTl8c/8jul2S329iFBnDI9HGoeWWAZvuvOkZccgw==", "optional": true, "requires": { "@sinonjs/commons": "^3.0.0" @@ -19927,9 +20140,9 @@ "integrity": "sha512-Jus9s4CDbqwocc5pOAnh8ShfrnMcPHuJYzVcSUU7lrh8Ni5HuIqX3oilL86p3dlTrk0LzHRCgA/GQ7uNCw6l2Q==" }, "@types/node": { - "version": "18.11.9", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.9.tgz", - "integrity": "sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==" + "version": "18.17.18", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.17.18.tgz", + "integrity": "sha512-/4QOuy3ZpV7Ya1GTRz5CYSz3DgkKpyUptXuQ5PPce7uuyJAOR7r9FhkmxJfvcNUXyklbC63a+YvB3jxy7s9ngw==" }, "@types/qrcode": { "version": "1.5.0", @@ -20715,26 +20928,11 @@ "optional": true }, "axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "optional": true, + "version": "0.24.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.24.0.tgz", + "integrity": "sha512-Q6cWsys88HoPgAaFAVUb0WpPk0O8iTeisR9IMqy9G8AbO4NlpVknrnQS03zzF9PGAWgO3cgletO3VjV/P7VztA==", "requires": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - }, - "dependencies": { - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "optional": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - } + "follow-redirects": "^1.14.4" } }, "babel-loader": { @@ -20868,9 +21066,9 @@ "optional": true }, "bn.js": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.0.tgz", - "integrity": "sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw==" + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.1.tgz", + "integrity": "sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ==" }, "body-parser": { "version": "1.20.1", @@ -21214,25 +21412,25 @@ } }, "browserify-sign": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.1.tgz", - "integrity": "sha512-/vrA5fguVAKKAVTNJjgSm1tRQDHUU6DbwO9IROu/0WAzC8PKhucDSh18J0RMvVeHAn5puMd+QHC2erPRNf8lmg==", + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.2.tgz", + "integrity": "sha512-1rudGyeYY42Dk6texmv7c4VcQ0EsvVbLwZkA+AQB7SxvXxmcD93jcHie8bzecJ+ChDlmAm2Qyu0+Ccg5uhZXCg==", "requires": { - "bn.js": "^5.1.1", - "browserify-rsa": "^4.0.1", + "bn.js": "^5.2.1", + "browserify-rsa": "^4.1.0", "create-hash": "^1.2.0", "create-hmac": "^1.1.7", - "elliptic": "^6.5.3", + "elliptic": "^6.5.4", "inherits": "^2.0.4", - "parse-asn1": "^5.1.5", - "readable-stream": "^3.6.0", - "safe-buffer": "^5.2.0" + "parse-asn1": "^5.1.6", + "readable-stream": "^3.6.2", + "safe-buffer": "^5.2.1" }, "dependencies": { "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", "requires": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -21395,6 +21593,16 @@ "get-intrinsic": "^1.0.2" } }, + "call-matcher": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/call-matcher/-/call-matcher-2.0.0.tgz", + "integrity": "sha512-CIDC5wZZfZ2VjZu849WQckS58Z3pJXFfRaSjNjgo/q3in5zxkhTwVL83vttgtmvyLG7TuDlLlBya7SKP6CjDIA==", + "requires": { + "deep-equal": "^1.0.0", + "espurify": "^2.0.0", + "estraverse": "^4.0.0" + } + }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -21417,17 +21625,18 @@ "optional": true }, "chai": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.4.tgz", - "integrity": "sha512-yS5H68VYOCtN1cjfwumDSuzn/9c+yza4f3reKXlE5rUg7SFcCEy90gJvydNgOYtblyf4Zi6jIWRnXOgErta0KA==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.0.tgz", + "integrity": "sha512-x9cHNq1uvkCdU+5xTkNh5WtgD4e4yDFCsp9jVc7N7qVeKeftv3gO/ZrviX5d+3ZfxdYnZXZYujjRInu1RogU6A==", "optional": true, "requires": { "assertion-error": "^1.1.0", - "check-error": "^1.0.2", - "deep-eql": "^3.0.1", - "get-func-name": "^2.0.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", "pathval": "^1.1.1", - "type-detect": "^4.0.5" + "type-detect": "^4.0.8" } }, "chalk": { @@ -21446,10 +21655,13 @@ "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==" }, "check-error": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", - "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=", - "optional": true + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "optional": true, + "requires": { + "get-func-name": "^2.0.2" + } }, "check-more-types": { "version": "2.24.0", @@ -21497,11 +21709,6 @@ "safe-buffer": "^5.0.1" } }, - "claygl": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/claygl/-/claygl-1.3.0.tgz", - "integrity": "sha512-+gGtJjT6SSHD2l2yC3MCubW/sCV40tZuSs5opdtn79vFSGUgp/lH139RNEQ6Jy078/L0aV8odCw8RSrUcMfLaQ==" - }, "clean-stack": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", @@ -22065,14 +22272,14 @@ "peer": true }, "cypress": { - "version": "12.17.2", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-12.17.2.tgz", - "integrity": "sha512-hxWAaWbqQBzzMuadSGSuQg5PDvIGOovm6xm0hIfpCVcORsCAj/gF2p0EvfnJ4f+jK2PCiDgP6D2eeE9/FK4Mjg==", + "version": "13.6.2", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.6.2.tgz", + "integrity": "sha512-TW3bGdPU4BrfvMQYv1z3oMqj71YI4AlgJgnrycicmPZAXtvywVFZW9DAToshO65D97rCWfG/kqMFsYB6Kp91gQ==", "optional": true, "requires": { - "@cypress/request": "^2.88.11", + "@cypress/request": "^3.0.0", "@cypress/xvfb": "^1.2.4", - "@types/node": "^14.14.31", + "@types/node": "^18.17.5", "@types/sinonjs__fake-timers": "8.1.1", "@types/sizzle": "^2.3.2", "arch": "^2.2.0", @@ -22105,6 +22312,7 @@ "minimist": "^1.2.8", "ospath": "^1.2.2", "pretty-bytes": "^5.6.0", + "process": "^0.11.10", "proxy-from-env": "1.0.0", "request-progress": "^3.0.0", "semver": "^7.5.3", @@ -22114,12 +22322,6 @@ "yauzl": "^2.10.0" }, "dependencies": { - "@types/node": { - "version": "14.18.53", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.53.tgz", - "integrity": "sha512-soGmOpVBUq+gaBMwom1M+krC/NNbWlosh4AtGA03SyWNDiqSKtwp7OulO1M6+mg8YkHMvJ/y0AkCeO8d1hNb7A==", - "optional": true - }, "ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -22236,21 +22438,21 @@ } }, "cypress-fail-on-console-error": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/cypress-fail-on-console-error/-/cypress-fail-on-console-error-4.0.3.tgz", - "integrity": "sha512-v2nPupd2brtxKLkDQX58SbEPWRF/2nDbqPTnYyhPIYHqG7U3P2dGUZ3zraETKKoLhU3+C0otjgB6Vg/bHhocQw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/cypress-fail-on-console-error/-/cypress-fail-on-console-error-5.1.0.tgz", + "integrity": "sha512-u/AXLE9obLd9KcGHkGJluJVZeOj1EEOFOs0URxxca4FrftUDJQ3u+IoNfjRUjsrBKmJxgM4vKd0G10D+ZT1uIA==", "optional": true, "requires": { - "chai": "^4.3.4", - "sinon": "^15.0.0", + "chai": "^4.3.10", + "sinon": "^17.0.0", "sinon-chai": "^3.7.0", "type-detect": "^4.0.8" } }, "cypress-wait-until": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/cypress-wait-until/-/cypress-wait-until-2.0.0.tgz", - "integrity": "sha512-ulUZyrWBn+OuC8oiQuGKAScDYfpaWnE3dEE/raUo64w4RHQxZrQ/iMIWT4ZjGMMPr3P+BFEALCRnjQeRqzZj6g==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/cypress-wait-until/-/cypress-wait-until-2.0.1.tgz", + "integrity": "sha512-+IyVnYNiaX1+C+V/LazrJWAi/CqiwfNoRSrFviECQEyolW1gDRy765PZosL2alSSGK8V10Y7BGfOQyZUDgmnjQ==", "optional": true }, "d": { @@ -22323,19 +22525,31 @@ "integrity": "sha1-JJXduvbrh0q7Dhvp3yLS5aVEMmw=" }, "deep-eql": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", - "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", "optional": true, "requires": { "type-detect": "^4.0.0" } }, + "deep-equal": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.2.tgz", + "integrity": "sha512-5tdhKF6DbU7iIzrIOa1AOUt39ZRm13cmL1cGEh//aqR8x9+tNfbywRf0n5FD/18OKMdo7DNEtrX2t22ZAkI+eg==", + "requires": { + "is-arguments": "^1.1.1", + "is-date-object": "^1.0.5", + "is-regex": "^1.1.4", + "object-is": "^1.1.5", + "object-keys": "^1.1.1", + "regexp.prototype.flags": "^1.5.1" + } + }, "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", - "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", - "dev": true + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=" }, "default-gateway": { "version": "6.0.3", @@ -22353,17 +22567,29 @@ "clone": "^1.0.2" } }, + "define-data-property": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", + "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", + "requires": { + "get-intrinsic": "^1.2.1", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.0" + } + }, "define-lazy-prop": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==" }, "define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", "requires": { - "object-keys": "^1.0.12" + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" } }, "defined": { @@ -22596,12 +22822,12 @@ } }, "echarts": { - "version": "5.4.3", - "resolved": "https://registry.npmjs.org/echarts/-/echarts-5.4.3.tgz", - "integrity": "sha512-mYKxLxhzy6zyTi/FaEbJMOZU1ULGEQHaeIeuMR5L+JnJTpz+YR03mnnpBhbR4+UYJAgiXgpyTVLffPAjOTLkZA==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/echarts/-/echarts-5.5.0.tgz", + "integrity": "sha512-rNYnNCzqDAPCr4m/fqyUFv7fD9qIsd50S6GDFgO1DxZhncCsNsG7IfUlAlvZe5oSEQxtsjnHiUuppzccry93Xw==", "requires": { "tslib": "2.3.0", - "zrender": "5.4.4" + "zrender": "5.5.0" }, "dependencies": { "tslib": { @@ -22611,15 +22837,6 @@ } } }, - "echarts-gl": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/echarts-gl/-/echarts-gl-2.0.9.tgz", - "integrity": "sha512-oKeMdkkkpJGWOzjgZUsF41DOh6cMsyrGGXimbjK2l6Xeq/dBQu4ShG2w2Dzrs/1bD27b2pLTGSaUzouY191gzA==", - "requires": { - "claygl": "^1.2.1", - "zrender": "^5.1.1" - } - }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -23279,6 +23496,11 @@ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==" }, + "espurify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/espurify/-/espurify-2.1.1.tgz", + "integrity": "sha512-zttWvnkhcDyGOhSH4vO2qCBILpdCMv/MX8lp4cqgRkQoDRGK2oZxi2GfWhlP2dIXmk7BaKeOTuzbHhyC68o8XQ==" + }, "esquery": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.4.0.tgz", @@ -23636,8 +23858,7 @@ "fast-levenshtein": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", - "dev": true + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=" }, "fast-safe-stringify": { "version": "2.0.7", @@ -23771,9 +23992,9 @@ "devOptional": true }, "follow-redirects": { - "version": "1.14.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", - "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==" + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==" }, "foreach": { "version": "2.0.5", @@ -23888,9 +24109,14 @@ "optional": true }, "function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==" + }, + "functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==" }, "gauge": { "version": "4.0.4", @@ -23923,19 +24149,20 @@ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" }, "get-func-name": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", - "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", "optional": true }, "get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", + "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", "requires": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" } }, "get-package-type": { @@ -24034,6 +24261,14 @@ "delegate": "^3.1.2" } }, + "gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", + "requires": { + "get-intrinsic": "^1.1.3" + } + }, "graceful-fs": { "version": "4.2.9", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", @@ -24091,10 +24326,31 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==" }, + "has-property-descriptors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", + "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", + "requires": { + "get-intrinsic": "^1.2.2" + } + }, + "has-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", + "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==" + }, "has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" + }, + "has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "requires": { + "has-symbols": "^1.0.2" + } }, "has-unicode": { "version": "2.0.1", @@ -24137,6 +24393,14 @@ "minimalistic-assert": "^1.0.1" } }, + "hasown": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", + "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "requires": { + "function-bind": "^1.1.2" + } + }, "hdr-histogram-js": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/hdr-histogram-js/-/hdr-histogram-js-2.0.3.tgz", @@ -24548,11 +24812,12 @@ "integrity": "sha512-LlbxQ7xKzfBusov6UMi4MFpEg0m+mAm9xyNGEduwXMEDuf4WfzB/RZwMVYEd7IKGvh4IUkEXYxtAVu9T3OelJQ==" }, "is-arguments": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.0.tgz", - "integrity": "sha512-1Ij4lOMPl/xB5kBDn7I+b2ttPMKa8szhEIrXDuXQD/oe3HJLTLhqhgGspwgyGd6MOywBUqVvYicF72lkgDnIHg==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", + "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", "requires": { - "call-bind": "^1.0.0" + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" } }, "is-arrayish": { @@ -24609,9 +24874,12 @@ } }, "is-date-object": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", - "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==" + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", + "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", + "requires": { + "has-tostringtag": "^1.0.0" + } }, "is-docker": { "version": "2.2.1", @@ -24701,12 +24969,12 @@ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==" }, "is-regex": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.2.tgz", - "integrity": "sha512-axvdhb5pdhEVThqJzYXwMlVuZwC+FF2DpcOhTS+y/8jVq4trxyPgfcwIxIKiyeuLlSQYKkmUaPQJ8ZE4yNKXDg==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", + "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", "requires": { "call-bind": "^1.0.2", - "has-symbols": "^1.0.1" + "has-tostringtag": "^1.0.0" } }, "is-stream": { @@ -24855,9 +25123,9 @@ "integrity": "sha512-5eEbBDQT/jF1xg6l36P+mWGGoH9Spuy0PCdSr2dtWRDGC6ph/w9ZCL4lmESW8f8F7MwT3XKescfP0wnZWAKL9w==" }, "joi": { - "version": "17.9.2", - "resolved": "https://registry.npmjs.org/joi/-/joi-17.9.2.tgz", - "integrity": "sha512-Itk/r+V4Dx0V3c7RLFdRh12IOjySm2/WGPMubBT92cQvRfYZhPM2W0hZlctjj72iES8jsRCwp7S/cRmWBnJ4nw==", + "version": "17.11.0", + "resolved": "https://registry.npmjs.org/joi/-/joi-17.11.0.tgz", + "integrity": "sha512-NgB+lZLNoqISVy1rZocE9PZI36bL/77ie924Ri43yEvi9GUUMPeyVIr8KdFTMUlby1p0PBYMk9spIxEUQYqrJQ==", "optional": true, "requires": { "@hapi/hoek": "^9.0.0", @@ -24967,22 +25235,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/parse5/-/parse5-6.0.1.tgz", "integrity": "sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==" - }, - "tough-cookie": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz", - "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==", - "requires": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" - } - }, - "universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==" } } }, @@ -25286,6 +25538,15 @@ "klona": "^2.0.4" } }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA==", + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, "license-webpack-plugin": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/license-webpack-plugin/-/license-webpack-plugin-4.0.2.tgz", @@ -25528,6 +25789,15 @@ "streamroller": "^3.0.2" } }, + "loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "optional": true, + "requires": { + "get-func-name": "^2.0.1" + } + }, "lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -25913,9 +26183,9 @@ "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" }, "mock-socket": { - "version": "9.2.1", - "resolved": "https://registry.npmjs.org/mock-socket/-/mock-socket-9.2.1.tgz", - "integrity": "sha512-aw9F9T9G2zpGipLLhSNh6ZpgUyUl4frcVmRN08uE1NWPWg43Wx6+sGPDbQ7E5iFZZDJW5b5bypMeAEHqTbIFag==", + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/mock-socket/-/mock-socket-9.3.1.tgz", + "integrity": "sha512-qxBgB7Qa2sEQgHFjj0dSigq7fX4k6Saisd5Nelwp2q8mlbAFh5dHV9JTTlF8viYJLSSWgMCZFUom8PJcMNBoJw==", "optional": true }, "module-deps": { @@ -25951,9 +26221,9 @@ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, "multi-stage-sourcemap": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/multi-stage-sourcemap/-/multi-stage-sourcemap-0.3.1.tgz", - "integrity": "sha512-UiTLYjqeIoVnJHyWGskwMKIhtZKK9uXUjSTWuwatarrc0d2H/6MAVFdwvEA/aKOHamIn7z4tfvxjz+FYucFpNQ==", + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/multi-stage-sourcemap/-/multi-stage-sourcemap-0.2.1.tgz", + "integrity": "sha512-umaOM+8BZByZIB/ciD3dQLzTv50rEkkGJV78ta/tIVc/J/rfGZY5y1R+fBD3oTaolx41mK8rRcyGtYbDXlzx8Q==", "requires": { "source-map": "^0.1.34" }, @@ -26109,9 +26379,9 @@ "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=" }, "ngx-echarts": { - "version": "16.0.0", - "resolved": "https://registry.npmjs.org/ngx-echarts/-/ngx-echarts-16.0.0.tgz", - "integrity": "sha512-hdM7/CL29bY3sF3V5ihb7H1NeUsQlhijp8tVxT23+vkNTf9SJrUHPjs9oHOMkbTlr2Q8HB+eVpckYAL/tuK0CQ==", + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/ngx-echarts/-/ngx-echarts-16.2.0.tgz", + "integrity": "sha512-yhuDbp6qdkmR4kRVLS06Z0Iumod7xOj5n/Z++clRiKM24OQ4sM8WuOTicdfWy6eeYDNywdGSrri4Y5SUGRD8bg==", "requires": { "tslib": "^2.3.0" } @@ -26135,9 +26405,9 @@ } }, "nise": { - "version": "5.1.4", - "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.4.tgz", - "integrity": "sha512-8+Ib8rRJ4L0o3kfmyVCL7gzrohyDe0cMFTBa2d364yIrEGMEoetznKJx899YxjybU6bL9SQkYPSBBs1gyYs8Xg==", + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/nise/-/nise-5.1.5.tgz", + "integrity": "sha512-VJuPIfUFaXNRzETTQEEItTOP8Y171ijr+JLq42wHes3DiryR8vT+1TXQW/Rx8JNUhyYYWyIvjXTU6dOhJcs9Nw==", "optional": true, "requires": { "@sinonjs/commons": "^2.0.0", @@ -26156,6 +26426,26 @@ "type-detect": "4.0.8" } }, + "@sinonjs/fake-timers": { + "version": "10.3.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", + "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "optional": true, + "requires": { + "@sinonjs/commons": "^3.0.0" + }, + "dependencies": { + "@sinonjs/commons": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", + "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", + "optional": true, + "requires": { + "type-detect": "4.0.8" + } + } + } + }, "isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", @@ -26349,6 +26639,15 @@ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.9.0.tgz", "integrity": "sha512-i3Bp9iTqwhaLZBxGkRfo5ZbE07BQRT7MGu8+nNgwW9ItGp1TzCTw2DLEoWwjClxBjOFI/hWljTAmYGCEwmtnOw==" }, + "object-is": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", + "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.1.3" + } + }, "object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", @@ -26416,6 +26715,19 @@ "is-wsl": "^2.2.0" } }, + "optionator": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz", + "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==", + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.6", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "word-wrap": "~1.2.3" + } + }, "ora": { "version": "5.4.1", "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", @@ -26901,6 +27213,11 @@ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==" + }, "prettier": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.0.0.tgz", @@ -27258,6 +27575,16 @@ "resolved": "https://registry.npmjs.org/regex-parser/-/regex-parser-2.2.11.tgz", "integrity": "sha512-jbD/FT0+9MBU2XAZluI7w2OBs1RBi6p9M83nkoZayQXXU9e8Robt69FcZc7wU4eJD/YFTjn1JdCk3rbMJajz8Q==" }, + "regexp.prototype.flags": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.1.tgz", + "integrity": "sha512-sy6TXMN+hnP/wMy+ISxg3krXx7BAtWVO4UouuCN/ziM9UEne0euamVNafDfvC83bRNr95y0V5iijeDQFUNpvrg==", + "requires": { + "call-bind": "^1.0.2", + "define-properties": "^1.2.0", + "set-function-name": "^2.0.0" + } + }, "regexpp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-3.2.0.tgz", @@ -27684,6 +28011,16 @@ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" }, + "set-function-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.1.tgz", + "integrity": "sha512-tMNCiqYVkXIZgc2Hnoy2IvC/f8ezc5koaRFkCjrpWzGpCd3qbZXPzVy9MAZzK1ch/X0jvSkojys3oqJN0qCmdA==", + "requires": { + "define-data-property": "^1.0.1", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.0" + } + }, "setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -27763,16 +28100,16 @@ "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==" }, "sinon": { - "version": "15.2.0", - "resolved": "https://registry.npmjs.org/sinon/-/sinon-15.2.0.tgz", - "integrity": "sha512-nPS85arNqwBXaIsFCkolHjGIkFo+Oxu9vbgmBJizLAhqe6P2o3Qmj3KCUoRkfhHtvgDhZdWD3risLHAUJ8npjw==", + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/sinon/-/sinon-17.0.1.tgz", + "integrity": "sha512-wmwE19Lie0MLT+ZYNpDymasPHUKTaZHUH/pKEubRXIzySv9Atnlw+BUMGCzWgV7b7wO+Hw6f1TEOr0IUnmU8/g==", "optional": true, "requires": { "@sinonjs/commons": "^3.0.0", - "@sinonjs/fake-timers": "^10.3.0", + "@sinonjs/fake-timers": "^11.2.2", "@sinonjs/samsam": "^8.0.0", "diff": "^5.1.0", - "nise": "^5.1.4", + "nise": "^5.1.5", "supports-color": "^7.2.0" }, "dependencies": { @@ -28080,9 +28417,9 @@ } }, "start-server-and-test": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/start-server-and-test/-/start-server-and-test-2.0.0.tgz", - "integrity": "sha512-UqKLw0mJbfrsG1jcRLTUlvuRi9sjNuUiDOLI42r7R5fA9dsFoywAy9DoLXNYys9B886E4RCKb+qM1Gzu96h7DQ==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/start-server-and-test/-/start-server-and-test-2.0.3.tgz", + "integrity": "sha512-QsVObjfjFZKJE6CS6bSKNwWZCKBG6975/jKRPPGFfFh+yOQglSeGXiNWjzgQNXdphcBI9nXbyso9tPfX4YAUhg==", "optional": true, "requires": { "arg": "^5.0.2", @@ -28092,7 +28429,7 @@ "execa": "5.1.1", "lazy-ass": "1.6.0", "ps-tree": "1.2.0", - "wait-on": "7.0.1" + "wait-on": "7.2.0" }, "dependencies": { "arg": { @@ -28409,58 +28746,30 @@ "integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==" }, "tinyify": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/tinyify/-/tinyify-4.0.0.tgz", - "integrity": "sha512-jNDxImwUrJJAU2NyGG144J8aWx2ni39UuBo7ppCXFRmhSH0CbpWL4HgjNvrsAW05WQAgNZePwAlEemNuB+byaA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyify/-/tinyify-3.1.0.tgz", + "integrity": "sha512-r4tHoDkWhhoItWbxJ3KCHXask3hJN7gCUkR5PLfnQzQagTA6oDkzhCbiEDHkMqo7Ck7vVSA1pTP1gDc9p1AC1w==", "requires": { - "@browserify/envify": "^6.0.0", - "@browserify/uglifyify": "^6.0.0", + "@goto-bus-stop/envify": "^5.0.0", + "acorn-node": "^1.8.2", "browser-pack-flat": "^3.0.9", "bundle-collapser": "^1.3.0", "common-shakeify": "^1.1.1", + "dash-ast": "^1.0.0", "minify-stream": "^2.0.1", "multisplice": "^1.0.0", - "terser": "3.16.1", - "through2": "^4.0.2", - "unassertify": "^3.0.1" + "through2": "^3.0.1", + "uglifyify": "^5.0.0", + "unassertify": "^2.1.1" }, "dependencies": { - "commander": { - "version": "2.17.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", - "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==" - }, - "readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" - }, - "terser": { - "version": "3.16.1", - "resolved": "https://registry.npmjs.org/terser/-/terser-3.16.1.tgz", - "integrity": "sha512-JDJjgleBROeek2iBcSNzOHLKsB/MdDf+E/BOAJ0Tk9r7p9/fVobfv7LMJ/g/k3v9SXdmjZnIlFd5nfn/Rt0Xow==", - "requires": { - "commander": "~2.17.1", - "source-map": "~0.6.1", - "source-map-support": "~0.5.9" - } - }, "through2": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", - "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-3.0.2.tgz", + "integrity": "sha512-enaDQ4MUyP2W6ZyT6EsMzqBPZaM/avg8iuo+l2d3QCs0J+6RaqkHV/2/lOwDTueBHeJ/2LG9lrLW3d5rWPucuQ==", "requires": { - "readable-stream": "3" + "inherits": "^2.0.4", + "readable-stream": "2 || 3" } } } @@ -28497,13 +28806,21 @@ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" }, "tough-cookie": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", - "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", - "optional": true, + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz", + "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==", "requires": { - "psl": "^1.1.28", - "punycode": "^2.1.1" + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.2.0", + "url-parse": "^1.5.3" + }, + "dependencies": { + "universalify": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", + "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==" + } } }, "tr46": { @@ -28648,6 +28965,14 @@ "resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz", "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==" }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg==", + "requires": { + "prelude-ls": "~1.1.2" + } + }, "type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -28690,43 +29015,94 @@ "optional": true, "peer": true }, + "uglifyify": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/uglifyify/-/uglifyify-5.0.2.tgz", + "integrity": "sha512-NcSk6pgoC+IgwZZ2tVLVHq+VNKSvLPlLkF5oUiHPVOJI0s/OlSVYEGXG9PCAH0hcyFZLyvt4KBdPAQBRlVDn1Q==", + "requires": { + "convert-source-map": "~1.1.0", + "minimatch": "^3.0.2", + "terser": "^3.7.5", + "through": "~2.3.4", + "xtend": "^4.0.1" + }, + "dependencies": { + "convert-source-map": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.1.3.tgz", + "integrity": "sha512-Y8L5rp6jo+g9VEPgvqNfEopjTR4OTYct8lXlS8iVQdmnjDvbdbzYe9rjtFCB9egC86JoNCU61WRY+ScjkZpnIg==" + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" + }, + "terser": { + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-3.17.0.tgz", + "integrity": "sha512-/FQzzPJmCpjAH9Xvk2paiWrFq+5M6aVOf+2KRbwhByISDX/EujxsK+BAvrhb6H+2rtrLCHK9N01wO014vrIwVQ==", + "requires": { + "commander": "^2.19.0", + "source-map": "~0.6.1", + "source-map-support": "~0.5.10" + } + } + } + }, "umd": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/umd/-/umd-3.0.3.tgz", "integrity": "sha512-4IcGSufhFshvLNcMCV80UnQVlZ5pMOC8mvNPForqwA4+lzYQuetTESLDQkeLmihq8bRcnpbQa48Wb8Lh16/xow==" }, "unassert": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/unassert/-/unassert-2.0.2.tgz", - "integrity": "sha512-P6OOg/aRdQmWH+b0g+T4U+9MgL+DG7w6oQPG+N3F2IMuvvd1WfZ5alT/Rjik2lMFVyhfACUxF7PGP1VCwSHlQA==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/unassert/-/unassert-1.6.0.tgz", + "integrity": "sha512-GoMtWTwGSxSFuRD0NKmbjlx3VJkgvSogzDzMPpJXYmBZv6MIWButsyMqEYhMx3NI4osXACcZA9mXiBteXyJtRw==", "requires": { - "estraverse": "^5.0.0" - }, - "dependencies": { - "estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==" - } + "acorn": "^7.0.0", + "call-matcher": "^2.0.0", + "deep-equal": "^1.0.0", + "espurify": "^2.0.1", + "estraverse": "^4.1.0", + "esutils": "^2.0.2", + "object-assign": "^4.1.0" } }, "unassertify": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/unassertify/-/unassertify-3.0.1.tgz", - "integrity": "sha512-461ykSPY3oWU+39J5haiq7S/hcYy1oGJ2nHU92lqdL3jft+pSU6oAbb7o6VVmM7nZGLqppszgyzfpCnRBFgFtw==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/unassertify/-/unassertify-2.1.1.tgz", + "integrity": "sha512-YIAaIlc6/KC9Oib8cVZLlpDDhK1UTEuaDyx9BwD97xqxDZC0cJOqwFcs/Y6K3m73B5VzHsRTBLXNO0dxS/GkTw==", "requires": { - "acorn": "^8.0.0", + "acorn": "^5.1.0", "convert-source-map": "^1.1.1", - "escodegen": "^2.0.0", - "multi-stage-sourcemap": "^0.3.1", + "escodegen": "^1.6.1", + "multi-stage-sourcemap": "^0.2.1", "through": "^2.3.7", - "unassert": "^2.0.0" + "unassert": "^1.3.1" }, "dependencies": { "acorn": { - "version": "8.10.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", - "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==" + "version": "5.7.4", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.4.tgz", + "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==" + }, + "escodegen": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.14.3.tgz", + "integrity": "sha512-qFcX0XJkdg+PB3xjZZG/wKSuT1PnQWx57+TVSjIMmILd2yC/6ByYElPwJnslDsuWuSAp4AwJGumarAAmJch5Kw==", + "requires": { + "esprima": "^4.0.1", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.6.1" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "optional": true } } }, @@ -28946,16 +29322,46 @@ } }, "wait-on": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-7.0.1.tgz", - "integrity": "sha512-9AnJE9qTjRQOlTZIldAaf/da2eW0eSRSgcqq85mXQja/DW3MriHxkpODDSUEg+Gri/rKEcXUZHe+cevvYItaog==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/wait-on/-/wait-on-7.2.0.tgz", + "integrity": "sha512-wCQcHkRazgjG5XoAq9jbTMLpNIjoSlZslrJ2+N9MxDsGEv1HnFoVjOCexL0ESva7Y9cu350j+DWADdk54s4AFQ==", "optional": true, "requires": { - "axios": "^0.27.2", - "joi": "^17.7.0", + "axios": "^1.6.1", + "joi": "^17.11.0", "lodash": "^4.17.21", - "minimist": "^1.2.7", - "rxjs": "^7.8.0" + "minimist": "^1.2.8", + "rxjs": "^7.8.1" + }, + "dependencies": { + "axios": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", + "integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", + "optional": true, + "requires": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "optional": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + } + }, + "proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "optional": true + } } }, "watchpack": { @@ -29223,6 +29629,11 @@ "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.1.tgz", "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==" }, + "word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==" + }, "wrap-ansi": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", @@ -29458,9 +29869,9 @@ } }, "zrender": { - "version": "5.4.4", - "resolved": "https://registry.npmjs.org/zrender/-/zrender-5.4.4.tgz", - "integrity": "sha512-0VxCNJ7AGOMCWeHVyTrGzUgrK4asT4ml9PEkeGirAkKNYXYzoPJCLvmyfdoOXcjTHPs10OZVMfD1Rwg16AZyYw==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/zrender/-/zrender-5.5.0.tgz", + "integrity": "sha512-O3MilSi/9mwoovx77m6ROZM7sXShR/O/JIanvzTwjN3FORfLSr81PsUGd7jlaYOeds9d8tw82oP44+3YucVo+w==", "requires": { "tslib": "2.3.0" }, diff --git a/frontend/package.json b/frontend/package.json index 2bb2ab2cd..2a0de0977 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -35,7 +35,7 @@ "start:local-staging": "npm run generate-config && npm run sync-assets-dev && npm run ng -- serve -c local-staging", "start:mixed": "npm run generate-config && npm run sync-assets-dev && npm run ng -- serve -c mixed", "build": "npm run generate-config && npm run ng -- build --configuration production --localize && npm run sync-assets && npm run build-mempool.js", - "sync-assets": "rsync -av ./src/resources ./dist/mempool/browser && node sync-assets.js 'dist/mempool/browser/resources'", + "sync-assets": "rsync -av ./src/resources ./dist/mempool/browser && node sync-assets.js 'dist/mempool/browser/resources/'", "sync-assets-dev": "node sync-assets.js 'src/resources/'", "generate-config": "node generate-config.js", "build-mempool.js": "npm run build-mempool-js && npm run build-mempool-liquid-js && npm run build-mempool-bisq-js", @@ -74,9 +74,9 @@ "@angular/platform-server": "^16.2.2", "@angular/router": "^16.2.2", "@fortawesome/angular-fontawesome": "~0.13.0", - "@fortawesome/fontawesome-common-types": "~6.4.0", - "@fortawesome/fontawesome-svg-core": "~6.4.0", - "@fortawesome/free-solid-svg-icons": "~6.4.0", + "@fortawesome/fontawesome-common-types": "~6.5.1", + "@fortawesome/fontawesome-svg-core": "~6.5.1", + "@fortawesome/free-solid-svg-icons": "~6.5.1", "@mempool/mempool.js": "2.3.0", "@ng-bootstrap/ng-bootstrap": "^15.1.0", "@types/qrcode": "~1.5.0", @@ -84,14 +84,13 @@ "browserify": "^17.0.0", "clipboard": "^2.0.11", "domino": "^2.1.6", - "echarts": "~5.4.3", - "echarts-gl": "^2.0.9", + "echarts": "~5.5.0", "lightweight-charts": "~3.8.0", - "ngx-echarts": "~16.0.0", + "ngx-echarts": "~16.2.0", "ngx-infinite-scroll": "^16.0.0", "qrcode": "1.5.1", "rxjs": "~7.8.1", - "tinyify": "^4.0.0", + "tinyify": "^3.1.0", "tlite": "^0.1.9", "tslib": "~2.6.0", "zone.js": "~0.13.1" @@ -111,10 +110,10 @@ "optionalDependencies": { "@cypress/schematic": "^2.5.0", "@types/cypress": "^1.1.3", - "cypress": "^12.17.2", - "cypress-fail-on-console-error": "~4.0.3", - "cypress-wait-until": "^2.0.0", - "mock-socket": "~9.2.1", + "cypress": "^13.6.2", + "cypress-fail-on-console-error": "~5.1.0", + "cypress-wait-until": "^2.0.1", + "mock-socket": "~9.3.1", "start-server-and-test": "~2.0.0" }, "scarfSettings": { diff --git a/frontend/src/app/app-routing.module.ts b/frontend/src/app/app-routing.module.ts index 79a8e1c02..e123a1525 100644 --- a/frontend/src/app/app-routing.module.ts +++ b/frontend/src/app/app-routing.module.ts @@ -1,28 +1,11 @@ import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AppPreloadingStrategy } from './app.preloading-strategy' -import { StartComponent } from './components/start/start.component'; -import { TransactionComponent } from './components/transaction/transaction.component'; -import { BlockComponent } from './components/block/block.component'; +import { BlockViewComponent } from './components/block-view/block-view.component'; +import { EightBlocksComponent } from './components/eight-blocks/eight-blocks.component'; +import { MempoolBlockViewComponent } from './components/mempool-block-view/mempool-block-view.component'; import { ClockComponent } from './components/clock/clock.component'; -import { AddressComponent } from './components/address/address.component'; -import { MasterPageComponent } from './components/master-page/master-page.component'; -import { AboutComponent } from './components/about/about.component'; import { StatusViewComponent } from './components/status-view/status-view.component'; -import { TermsOfServiceComponent } from './components/terms-of-service/terms-of-service.component'; -import { PrivacyPolicyComponent } from './components/privacy-policy/privacy-policy.component'; -import { TrademarkPolicyComponent } from './components/trademark-policy/trademark-policy.component'; -import { BisqMasterPageComponent } from './components/bisq-master-page/bisq-master-page.component'; -import { PushTransactionComponent } from './components/push-transaction/push-transaction.component'; -import { BlocksList } from './components/blocks-list/blocks-list.component'; -import { RbfList } from './components/rbf-list/rbf-list.component'; -import { LiquidMasterPageComponent } from './components/liquid-master-page/liquid-master-page.component'; -import { AssetGroupComponent } from './components/assets/asset-group/asset-group.component'; -import { AssetsFeaturedComponent } from './components/assets/assets-featured/assets-featured.component'; -import { AssetsComponent } from './components/assets/assets.component'; -import { AssetComponent } from './components/asset/asset.component'; -import { AssetsNavComponent } from './components/assets/assets-nav/assets-nav.component'; -import { CalculatorComponent } from './components/calculator/calculator.component'; const browserWindow = window || {}; // @ts-ignore @@ -35,95 +18,13 @@ let routes: Routes = [ { path: '', pathMatch: 'full', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule), + loadChildren: () => import('./bitcoin-graphs.module').then(m => m.BitcoinGraphsModule), data: { preload: true }, }, { path: '', - component: MasterPageComponent, - children: [ - { - path: 'mining/blocks', - redirectTo: 'blocks', - pathMatch: 'full' - }, - { - path: 'tx/push', - component: PushTransactionComponent, - }, - { - path: 'about', - component: AboutComponent, - }, - { - path: 'blocks', - component: BlocksList, - }, - { - path: 'rbf', - component: RbfList, - }, - { - path: 'terms-of-service', - component: TermsOfServiceComponent - }, - { - path: 'privacy-policy', - component: PrivacyPolicyComponent - }, - { - path: 'trademark-policy', - component: TrademarkPolicyComponent - }, - { - path: 'address/:id', - children: [], - component: AddressComponent, - data: { - ogImage: true, - networkSpecific: true, - } - }, - { - path: 'tx', - component: StartComponent, - data: { networkSpecific: true }, - children: [ - { - path: ':id', - component: TransactionComponent - }, - ], - }, - { - path: 'block', - component: StartComponent, - data: { networkSpecific: true }, - children: [ - { - path: ':id', - component: BlockComponent, - data: { - ogImage: true - } - }, - ], - }, - { - path: 'docs', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule), - data: { preload: true }, - }, - { - path: 'api', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'lightning', - loadChildren: () => import('./lightning/lightning.module').then(m => m.LightningModule), - data: { preload: browserWindowEnv && browserWindowEnv.LIGHTNING === true, networks: ['bitcoin'] }, - }, - ], + loadChildren: () => import('./master-page.module').then(m => m.MasterPageModule), + data: { preload: true }, }, { path: 'status', @@ -132,7 +33,8 @@ let routes: Routes = [ }, { path: '', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./bitcoin-graphs.module').then(m => m.BitcoinGraphsModule), + data: { preload: true }, }, { path: '**', @@ -151,88 +53,13 @@ let routes: Routes = [ { path: '', pathMatch: 'full', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./bitcoin-graphs.module').then(m => m.BitcoinGraphsModule), + data: { preload: true }, }, { path: '', - component: MasterPageComponent, - children: [ - { - path: 'tx/push', - component: PushTransactionComponent, - }, - { - path: 'about', - component: AboutComponent, - }, - { - path: 'blocks', - component: BlocksList, - }, - { - path: 'rbf', - component: RbfList, - }, - { - path: 'terms-of-service', - component: TermsOfServiceComponent - }, - { - path: 'privacy-policy', - component: PrivacyPolicyComponent - }, - { - path: 'trademark-policy', - component: TrademarkPolicyComponent - }, - { - path: 'address/:id', - children: [], - component: AddressComponent, - data: { - ogImage: true, - networkSpecific: true, - } - }, - { - path: 'tx', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: TransactionComponent - }, - ], - }, - { - path: 'block', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: BlockComponent, - data: { - ogImage: true - } - }, - ], - }, - { - path: 'docs', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'api', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'lightning', - data: { networks: ['bitcoin'] }, - loadChildren: () => import('./lightning/lightning.module').then(m => m.LightningModule) - }, - ], + loadChildren: () => import('./master-page.module').then(m => m.MasterPageModule), + data: { preload: true }, }, { path: 'status', @@ -241,7 +68,8 @@ let routes: Routes = [ }, { path: '', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./bitcoin-graphs.module').then(m => m.BitcoinGraphsModule), + data: { preload: true }, }, { path: '**', @@ -252,97 +80,13 @@ let routes: Routes = [ { path: '', pathMatch: 'full', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./bitcoin-graphs.module').then(m => m.BitcoinGraphsModule), + data: { preload: true }, }, { path: '', - component: MasterPageComponent, - children: [ - { - path: 'mining/blocks', - redirectTo: 'blocks', - pathMatch: 'full' - }, - { - path: 'tx/push', - component: PushTransactionComponent, - }, - { - path: 'about', - component: AboutComponent, - }, - { - path: 'blocks', - component: BlocksList, - }, - { - path: 'rbf', - component: RbfList, - }, - { - path: 'tools/calculator', - component: CalculatorComponent - }, - { - path: 'terms-of-service', - component: TermsOfServiceComponent - }, - { - path: 'privacy-policy', - component: PrivacyPolicyComponent - }, - { - path: 'trademark-policy', - component: TrademarkPolicyComponent - }, - { - path: 'address/:id', - children: [], - component: AddressComponent, - data: { - ogImage: true, - networkSpecific: true, - } - }, - { - path: 'tx', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: TransactionComponent - }, - ], - }, - { - path: 'block', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: BlockComponent, - data: { - ogImage: true - } - }, - ], - }, - { - path: 'docs', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'api', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'lightning', - data: { networks: ['bitcoin'] }, - loadChildren: () => import('./lightning/lightning.module').then(m => m.LightningModule) - }, - ], + loadChildren: () => import('./master-page.module').then(m => m.MasterPageModule), + data: { preload: true }, }, { path: 'preview', @@ -373,6 +117,18 @@ let routes: Routes = [ path: 'clock/:mode/:index', component: ClockComponent, }, + { + path: 'view/block/:id', + component: BlockViewComponent, + }, + { + path: 'view/mempool-block/:index', + component: MempoolBlockViewComponent, + }, + { + path: 'view/blocks', + component: EightBlocksComponent, + }, { path: 'status', data: { networks: ['bitcoin', 'liquid'] }, @@ -380,7 +136,8 @@ let routes: Routes = [ }, { path: '', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./bitcoin-graphs.module').then(m => m.BitcoinGraphsModule), + data: { preload: true }, }, { path: '**', @@ -391,7 +148,6 @@ let routes: Routes = [ if (browserWindowEnv && browserWindowEnv.BASE_MODULE === 'bisq') { routes = [{ path: '', - component: BisqMasterPageComponent, loadChildren: () => import('./bisq/bisq.module').then(m => m.BisqModule) }]; } @@ -404,105 +160,13 @@ if (browserWindowEnv && browserWindowEnv.BASE_MODULE === 'liquid') { { path: '', pathMatch: 'full', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./liquid/liquid-graphs.module').then(m => m.LiquidGraphsModule), + data: { preload: true }, }, { path: '', - component: LiquidMasterPageComponent, - children: [ - { - path: 'tx/push', - component: PushTransactionComponent, - }, - { - path: 'about', - component: AboutComponent, - }, - { - path: 'blocks', - component: BlocksList, - }, - { - path: 'terms-of-service', - component: TermsOfServiceComponent - }, - { - path: 'privacy-policy', - component: PrivacyPolicyComponent - }, - { - path: 'trademark-policy', - component: TrademarkPolicyComponent - }, - { - path: 'address/:id', - children: [], - component: AddressComponent, - data: { - ogImage: true, - networkSpecific: true, - } - }, - { - path: 'tx', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: TransactionComponent - }, - ], - }, - { - path: 'block', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: BlockComponent, - data: { - ogImage: true - } - }, - ], - }, - { - path: 'assets', - data: { networks: ['liquid'] }, - component: AssetsNavComponent, - children: [ - { - path: 'all', - data: { networks: ['liquid'] }, - component: AssetsComponent, - }, - { - path: 'asset/:id', - data: { networkSpecific: true }, - component: AssetComponent - }, - { - path: 'group/:id', - data: { networkSpecific: true }, - component: AssetGroupComponent - }, - { - path: '**', - redirectTo: 'all' - } - ] - }, - { - path: 'docs', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'api', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - ], + loadChildren: () => import ('./liquid/liquid-master-page.module').then(m => m.LiquidMasterPageModule), + data: { preload: true }, }, { path: 'status', @@ -511,7 +175,8 @@ if (browserWindowEnv && browserWindowEnv.BASE_MODULE === 'liquid') { }, { path: '', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./liquid/liquid-graphs.module').then(m => m.LiquidGraphsModule), + data: { preload: true }, }, { path: '**', @@ -522,110 +187,13 @@ if (browserWindowEnv && browserWindowEnv.BASE_MODULE === 'liquid') { { path: '', pathMatch: 'full', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./liquid/liquid-graphs.module').then(m => m.LiquidGraphsModule), + data: { preload: true }, }, { path: '', - component: LiquidMasterPageComponent, - children: [ - { - path: 'tx/push', - component: PushTransactionComponent, - }, - { - path: 'about', - component: AboutComponent, - }, - { - path: 'blocks', - component: BlocksList, - }, - { - path: 'terms-of-service', - component: TermsOfServiceComponent - }, - { - path: 'privacy-policy', - component: PrivacyPolicyComponent - }, - { - path: 'trademark-policy', - component: TrademarkPolicyComponent - }, - { - path: 'address/:id', - children: [], - component: AddressComponent, - data: { - ogImage: true, - networkSpecific: true, - } - }, - { - path: 'tx', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: TransactionComponent - }, - ], - }, - { - path: 'block', - data: { networkSpecific: true }, - component: StartComponent, - children: [ - { - path: ':id', - component: BlockComponent, - data: { - ogImage: true - } - }, - ], - }, - { - path: 'assets', - data: { networks: ['liquid'] }, - component: AssetsNavComponent, - children: [ - { - path: 'featured', - data: { networkSpecific: true }, - component: AssetsFeaturedComponent, - }, - { - path: 'all', - data: { networks: ['liquid'] }, - component: AssetsComponent, - }, - { - path: 'asset/:id', - data: { networkSpecific: true }, - component: AssetComponent - }, - { - path: 'group/:id', - data: { networkSpecific: true }, - component: AssetGroupComponent - }, - { - path: '**', - redirectTo: 'featured' - } - ] - }, - { - path: 'docs', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'api', - loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) - }, - ], + loadChildren: () => import ('./liquid/liquid-master-page.module').then(m => m.LiquidMasterPageModule), + data: { preload: true }, }, { path: 'preview', @@ -647,7 +215,8 @@ if (browserWindowEnv && browserWindowEnv.BASE_MODULE === 'liquid') { }, { path: '', - loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule) + loadChildren: () => import('./liquid/liquid-graphs.module').then(m => m.LiquidGraphsModule), + data: { preload: true }, }, { path: '**', diff --git a/frontend/src/app/app.module.ts b/frontend/src/app/app.module.ts index 378ef11ed..6b7ec7f51 100644 --- a/frontend/src/app/app.module.ts +++ b/frontend/src/app/app.module.ts @@ -22,6 +22,7 @@ import { FiatCurrencyPipe } from './shared/pipes/fiat-currency.pipe'; import { ShortenStringPipe } from './shared/pipes/shorten-string-pipe/shorten-string.pipe'; import { CapAddressPipe } from './shared/pipes/cap-address-pipe/cap-address-pipe'; import { AppPreloadingStrategy } from './app.preloading-strategy'; +import { ServicesApiServices } from './services/services-api.service'; const providers = [ ElectrsApiService, @@ -40,6 +41,7 @@ const providers = [ FiatCurrencyPipe, CapAddressPipe, AppPreloadingStrategy, + ServicesApiServices, { provide: HTTP_INTERCEPTORS, useClass: HttpCacheInterceptor, multi: true } ]; diff --git a/frontend/src/app/bisq/bisq-block/bisq-block.component.ts b/frontend/src/app/bisq/bisq-block/bisq-block.component.ts index 42f62fbc0..59bb16a9e 100644 --- a/frontend/src/app/bisq/bisq-block/bisq-block.component.ts +++ b/frontend/src/app/bisq/bisq-block/bisq-block.component.ts @@ -69,6 +69,7 @@ export class BisqBlockComponent implements OnInit, OnDestroy { this.location.replaceState( this.router.createUrlTree(['/bisq/block/', hash]).toString() ); + this.seoService.updateCanonical(this.location.path()); return this.bisqApiService.getBlock$(this.blockHash) .pipe(catchError(this.caughtHttpError.bind(this))); }), diff --git a/frontend/src/app/bisq/bisq-dashboard/bisq-dashboard.component.ts b/frontend/src/app/bisq/bisq-dashboard/bisq-dashboard.component.ts index ebcb8a067..8834d09e9 100644 --- a/frontend/src/app/bisq/bisq-dashboard/bisq-dashboard.component.ts +++ b/frontend/src/app/bisq/bisq-dashboard/bisq-dashboard.component.ts @@ -30,7 +30,7 @@ export class BisqDashboardComponent implements OnInit { ngOnInit(): void { this.seoService.setTitle($localize`:@@meta.title.bisq.markets:Markets`); - this.seoService.setDescription($localize`:@@meta.description.bisq.markets:Explore the full Bitcoin ecosystem with The Mempool Open Project™. See Bisq market prices, trading activity, and more.`); + this.seoService.setDescription($localize`:@@meta.description.bisq.markets:Explore the full Bitcoin ecosystem with The Mempool Open Source Project®. See Bisq market prices, trading activity, and more.`); this.websocketService.want(['blocks']); this.volumes$ = this.bisqApiService.getAllVolumesDay$() diff --git a/frontend/src/app/bisq/bisq.module.ts b/frontend/src/app/bisq/bisq.module.ts index 93658d95a..f7f71156b 100644 --- a/frontend/src/app/bisq/bisq.module.ts +++ b/frontend/src/app/bisq/bisq.module.ts @@ -27,9 +27,11 @@ import { AutofocusDirective } from '../components/ngx-bootstrap-multiselect/auto import { MultiSelectSearchFilter } from '../components/ngx-bootstrap-multiselect/search-filter.pipe'; import { OffClickDirective } from '../components/ngx-bootstrap-multiselect/off-click.directive'; import { NgxDropdownMultiselectComponent } from '../components/ngx-bootstrap-multiselect/ngx-bootstrap-multiselect.component'; +import { BisqMasterPageComponent } from '../components/bisq-master-page/bisq-master-page.component'; @NgModule({ declarations: [ + BisqMasterPageComponent, BisqTransactionsComponent, BisqTransactionComponent, BisqBlockComponent, diff --git a/frontend/src/app/bisq/bisq.routing.module.ts b/frontend/src/app/bisq/bisq.routing.module.ts index 11acdca2a..7c6d2ee1b 100644 --- a/frontend/src/app/bisq/bisq.routing.module.ts +++ b/frontend/src/app/bisq/bisq.routing.module.ts @@ -1,6 +1,6 @@ import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; -import { AboutComponent } from '../components/about/about.component'; +import { BisqMasterPageComponent } from '../components/bisq-master-page/bisq-master-page.component'; import { BisqTransactionsComponent } from './bisq-transactions/bisq-transactions.component'; import { BisqTransactionComponent } from './bisq-transaction/bisq-transaction.component'; import { BisqBlockComponent } from './bisq-block/bisq-block.component'; @@ -10,78 +10,83 @@ import { BisqStatsComponent } from './bisq-stats/bisq-stats.component'; import { BisqDashboardComponent } from './bisq-dashboard/bisq-dashboard.component'; import { BisqMarketComponent } from './bisq-market/bisq-market.component'; import { BisqMainDashboardComponent } from './bisq-main-dashboard/bisq-main-dashboard.component'; -import { TermsOfServiceComponent } from '../components/terms-of-service/terms-of-service.component'; import { PushTransactionComponent } from '../components/push-transaction/push-transaction.component'; const routes: Routes = [ - { - path: '', - component: BisqMainDashboardComponent, - }, - { - path: 'markets', - data: { networks: ['bisq'] }, - component: BisqDashboardComponent, - }, - { - path: 'transactions', - data: { networks: ['bisq'] }, - component: BisqTransactionsComponent - }, - { - path: 'market/:pair', - data: { networkSpecific: true }, - component: BisqMarketComponent, - }, - { - path: 'tx/push', - component: PushTransactionComponent, - }, - { - path: 'tx/:id', - data: { networkSpecific: true }, - component: BisqTransactionComponent - }, - { - path: 'blocks', - children: [], - component: BisqBlocksComponent - }, - { - path: 'block/:id', - data: { networkSpecific: true }, - component: BisqBlockComponent, - }, - { - path: 'address/:id', - data: { networkSpecific: true }, - component: BisqAddressComponent, - }, - { - path: 'stats', - data: { networks: ['bisq'] }, - component: BisqStatsComponent, - }, - { - path: 'about', - component: AboutComponent, - }, - { - path: 'docs', - loadChildren: () => import('../docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'api', - loadChildren: () => import('../docs/docs.module').then(m => m.DocsModule) - }, - { - path: 'terms-of-service', - component: TermsOfServiceComponent - }, - { - path: '**', - redirectTo: '' - } + { + path: '', + component: BisqMasterPageComponent, + children: [ + { + path: '', + component: BisqMainDashboardComponent, + }, + { + path: 'markets', + data: { networks: ['bisq'] }, + component: BisqDashboardComponent, + }, + { + path: 'transactions', + data: { networks: ['bisq'] }, + component: BisqTransactionsComponent + }, + { + path: 'market/:pair', + data: { networkSpecific: true }, + component: BisqMarketComponent, + }, + { + path: 'tx/push', + component: PushTransactionComponent, + }, + { + path: 'tx/:id', + data: { networkSpecific: true }, + component: BisqTransactionComponent + }, + { + path: 'blocks', + children: [], + component: BisqBlocksComponent + }, + { + path: 'block/:id', + data: { networkSpecific: true }, + component: BisqBlockComponent, + }, + { + path: 'address/:id', + data: { networkSpecific: true }, + component: BisqAddressComponent, + }, + { + path: 'stats', + data: { networks: ['bisq'] }, + component: BisqStatsComponent, + }, + { + path: 'about', + loadChildren: () => import('../components/about/about.module').then(m => m.AboutModule), + }, + { + path: 'docs', + loadChildren: () => import('../docs/docs.module').then(m => m.DocsModule) + }, + { + path: 'api', + loadChildren: () => import('../docs/docs.module').then(m => m.DocsModule) + }, + { + path: 'terms-of-service', + loadChildren: () => import('../components/terms-of-service/terms-of-service.module').then(m => m.TermsOfServiceModule), + }, + { + path: '**', + redirectTo: '' + } + ] + } ]; @NgModule({ diff --git a/frontend/src/app/bitcoin-graphs.module.ts b/frontend/src/app/bitcoin-graphs.module.ts new file mode 100644 index 000000000..710743245 --- /dev/null +++ b/frontend/src/app/bitcoin-graphs.module.ts @@ -0,0 +1,37 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { MasterPageComponent } from './components/master-page/master-page.component'; + +const routes: Routes = [ + { + path: '', + component: MasterPageComponent, + loadChildren: () => import('./graphs/graphs.module').then(m => m.GraphsModule), + data: { preload: true }, + } +]; + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class BitcoinGraphsRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + BitcoinGraphsRoutingModule, + ], +}) +export class BitcoinGraphsModule { } + + + + + + diff --git a/frontend/src/app/bitcoin.utils.ts b/frontend/src/app/bitcoin.utils.ts index c4af730f6..d5b5122fa 100644 --- a/frontend/src/app/bitcoin.utils.ts +++ b/frontend/src/app/bitcoin.utils.ts @@ -225,7 +225,7 @@ const witnessSize = (vin: Vin) => vin.witness ? vin.witness.reduce((S, w) => S + const scriptSigSize = (vin: Vin) => vin.scriptsig ? vin.scriptsig.length / 2 : 0; // Power of ten wrapper -export function selectPowerOfTen(val: number): { divider: number, unit: string } { +export function selectPowerOfTen(val: number, multiplier = 1): { divider: number, unit: string } { const powerOfTen = { exa: Math.pow(10, 18), peta: Math.pow(10, 15), @@ -236,17 +236,17 @@ export function selectPowerOfTen(val: number): { divider: number, unit: string } }; let selectedPowerOfTen: { divider: number, unit: string }; - if (val < powerOfTen.kilo) { + if (val < powerOfTen.kilo * multiplier) { selectedPowerOfTen = { divider: 1, unit: '' }; // no scaling - } else if (val < powerOfTen.mega) { + } else if (val < powerOfTen.mega * multiplier) { selectedPowerOfTen = { divider: powerOfTen.kilo, unit: 'k' }; - } else if (val < powerOfTen.giga) { + } else if (val < powerOfTen.giga * multiplier) { selectedPowerOfTen = { divider: powerOfTen.mega, unit: 'M' }; - } else if (val < powerOfTen.tera) { + } else if (val < powerOfTen.tera * multiplier) { selectedPowerOfTen = { divider: powerOfTen.giga, unit: 'G' }; - } else if (val < powerOfTen.peta) { + } else if (val < powerOfTen.peta * multiplier) { selectedPowerOfTen = { divider: powerOfTen.tera, unit: 'T' }; - } else if (val < powerOfTen.exa) { + } else if (val < powerOfTen.exa * multiplier) { selectedPowerOfTen = { divider: powerOfTen.peta, unit: 'P' }; } else { selectedPowerOfTen = { divider: powerOfTen.exa, unit: 'E' }; diff --git a/frontend/src/app/components/about/about-sponsors.component.html b/frontend/src/app/components/about/about-sponsors.component.html new file mode 100644 index 000000000..9471fc78f --- /dev/null +++ b/frontend/src/app/components/about/about-sponsors.component.html @@ -0,0 +1,16 @@ +
+
+

If you're an individual...

+ Become a Community Sponsor + + + +
+
+

If you're a business...

+ Become an Enterprise Sponsor + + + +
+
diff --git a/frontend/src/app/components/about/about-sponsors.component.scss b/frontend/src/app/components/about/about-sponsors.component.scss new file mode 100644 index 000000000..7c01bb9a3 --- /dev/null +++ b/frontend/src/app/components/about/about-sponsors.component.scss @@ -0,0 +1,50 @@ +#become-sponsor-container { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: center; + align-items: center; + gap: 20px; + margin: 68px auto; + text-align: center; +} + +#become-sponsor-container.account { + margin: 20px auto; +} + +.become-sponsor { + background-color: #1d1f31; + border-radius: 16px; + padding: 12px 20px; + width: 400px; + padding: 40px 20px; +} + +.become-sponsor a { + margin-top: 10px; +} + +#become-sponsor-container .btn { + margin-bottom: 24px; +} + +#become-sponsor-container .ng-fa-icon { + color: #2ecc71; + margin-right: 5px; +} + +#become-sponsor-container .sponsor-feature { + text-align: left; + width: 250px; + margin: 12px auto; + white-space: nowrap; +} + +@media (max-width: 992px) { + + #become-sponsor-container { + flex-wrap: wrap; + } + +} diff --git a/frontend/src/app/components/about/about-sponsors.component.ts b/frontend/src/app/components/about/about-sponsors.component.ts new file mode 100644 index 000000000..6a47c3bd4 --- /dev/null +++ b/frontend/src/app/components/about/about-sponsors.component.ts @@ -0,0 +1,25 @@ +import { Component, Input } from '@angular/core'; +import { EnterpriseService } from '../../services/enterprise.service'; + +@Component({ + selector: 'app-about-sponsors', + templateUrl: './about-sponsors.component.html', + styleUrls: ['./about-sponsors.component.scss'], +}) +export class AboutSponsorsComponent { + @Input() host = 'https://mempool.space'; + @Input() context = 'about'; + + constructor(private enterpriseService: EnterpriseService) { + } + + onSponsorClick(e): boolean { + this.enterpriseService.goal(5); + return true; + } + + onEnterpriseClick(e): boolean { + this.enterpriseService.goal(6); + return true; + } +} diff --git a/frontend/src/app/components/about/about.component.html b/frontend/src/app/components/about/about.component.html index 6bff838aa..009040889 100644 --- a/frontend/src/app/components/about/about.component.html +++ b/frontend/src/app/components/about/about.component.html @@ -10,7 +10,7 @@
-
The Mempool Open Source Project
+
The Mempool Open Source Project ®

Our mempool and blockchain explorer for the Bitcoin community, focusing on the transaction fee market and multi-layer ecosystem, completely self-hosted without any trusted third-parties.

@@ -32,12 +32,8 @@ - -

Sponsor the project

- + +
@@ -186,14 +182,14 @@
-
+

Whale Sponsors

- + @@ -205,7 +201,7 @@ @@ -299,9 +295,9 @@ Blixt - + - Zeus + ZEUS @@ -409,38 +405,30 @@ - -
diff --git a/frontend/src/app/components/about/about.component.ts b/frontend/src/app/components/about/about.component.ts index 3cda0dc20..3fea849a1 100644 --- a/frontend/src/app/components/about/about.component.ts +++ b/frontend/src/app/components/about/about.component.ts @@ -9,6 +9,7 @@ import { Router, ActivatedRoute } from '@angular/router'; import { map, share, tap } from 'rxjs/operators'; import { ITranslators } from '../../interfaces/node-api.interface'; import { DOCUMENT } from '@angular/common'; +import { EnterpriseService } from '../../services/enterprise.service'; @Component({ selector: 'app-about', @@ -33,6 +34,7 @@ export class AboutComponent implements OnInit { private websocketService: WebsocketService, private seoService: SeoService, public stateService: StateService, + private enterpriseService: EnterpriseService, private apiService: ApiService, private router: Router, private route: ActivatedRoute, @@ -43,12 +45,17 @@ export class AboutComponent implements OnInit { ngOnInit() { this.backendInfo$ = this.stateService.backendInfo$; this.seoService.setTitle($localize`:@@004b222ff9ef9dd4771b777950ca1d0e4cd4348a:About`); - this.seoService.setDescription($localize`:@@meta.description.about:Learn more about The Mempool Open Source Project™\: enterprise sponsors, individual sponsors, integrations, who contributes, FOSS licensing, and more.`); + this.seoService.setDescription($localize`:@@meta.description.about:Learn more about The Mempool Open Source Project®\: enterprise sponsors, individual sponsors, integrations, who contributes, FOSS licensing, and more.`); this.websocketService.want(['blocks']); this.profiles$ = this.apiService.getAboutPageProfiles$().pipe( - tap(() => { - this.goToAnchor() + tap((profiles: any) => { + const scrollToSponsors = this.route.snapshot.fragment === 'community-sponsors'; + if (scrollToSponsors && !profiles?.whales?.length && !profiles?.chads?.length) { + return; + } else { + this.goToAnchor(scrollToSponsors) + } }), share(), ) @@ -83,11 +90,19 @@ export class AboutComponent implements OnInit { this.goToAnchor(); } - goToAnchor() { + goToAnchor(scrollToSponsor = false) { + if (!scrollToSponsor) { + return; + } setTimeout(() => { if (this.route.snapshot.fragment) { - if (this.document.getElementById(this.route.snapshot.fragment)) { - this.document.getElementById(this.route.snapshot.fragment).scrollIntoView({behavior: 'smooth'}); + const el = scrollToSponsor ? this.document.getElementById('community-sponsors-anchor') : this.document.getElementById(this.route.snapshot.fragment); + if (el) { + if (scrollToSponsor) { + el.scrollIntoView({behavior: 'smooth', block: 'center', inline: 'center'}); + } else { + el.scrollIntoView({behavior: 'smooth'}); + } } } }, 1); @@ -108,4 +123,14 @@ export class AboutComponent implements OnInit { unmutePromoVideo(): void { this.promoVideo.nativeElement.muted = false; } + + onSponsorClick(e): boolean { + this.enterpriseService.goal(5); + return true; + } + + onEnterpriseClick(e): boolean { + this.enterpriseService.goal(6); + return true; + } } diff --git a/frontend/src/app/components/about/about.module.ts b/frontend/src/app/components/about/about.module.ts new file mode 100644 index 000000000..7e8ed42d0 --- /dev/null +++ b/frontend/src/app/components/about/about.module.ts @@ -0,0 +1,45 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { AboutComponent } from './about.component'; +import { AboutSponsorsComponent } from './about-sponsors.component'; +import { SharedModule } from '../../shared/shared.module'; + +const routes: Routes = [ + { + path: '', + component: AboutComponent, + } +]; + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class AboutRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + AboutRoutingModule, + SharedModule, + ], + declarations: [ + AboutComponent, + AboutSponsorsComponent, + ], + exports: [ + AboutSponsorsComponent, + ] +}) +export class AboutModule { } + + + + + + diff --git a/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.scss b/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.scss index 6137b53ee..8d36387f3 100644 --- a/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.scss +++ b/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.scss @@ -2,7 +2,6 @@ height: 100%; min-width: 120px; width: 120px; - max-height: 90vh; margin-left: 4em; margin-right: 1.5em; padding-bottom: 63px; @@ -18,6 +17,7 @@ bottom: 0; left: 0; right: 0; + min-height: 30px; display: flex; flex-direction: column; justify-content: center; diff --git a/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.ts b/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.ts index 4d746a0d9..b5aebd35f 100644 --- a/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.ts +++ b/frontend/src/app/components/accelerate-preview/accelerate-fee-graph.component.ts @@ -58,13 +58,15 @@ export class AccelerateFeeGraphComponent implements OnInit, OnChanges { fee: option.fee, } }); - bars.push({ - rate: this.estimate.targetFeeRate, - style: this.getStyle(this.estimate.targetFeeRate, maxRate, baseHeight), - class: 'target', - label: 'next block', - fee: this.estimate.nextBlockFee - this.estimate.txSummary.effectiveFee - }); + if (this.estimate.nextBlockFee > this.estimate.txSummary.effectiveFee) { + bars.push({ + rate: this.estimate.targetFeeRate, + style: this.getStyle(this.estimate.targetFeeRate, maxRate, baseHeight), + class: 'target', + label: 'next block', + fee: this.estimate.nextBlockFee - this.estimate.txSummary.effectiveFee + }); + } bars.push({ rate: baseRate, style: this.getStyle(baseRate, maxRate, 0), diff --git a/frontend/src/app/components/accelerate-preview/accelerate-preview.component.html b/frontend/src/app/components/accelerate-preview/accelerate-preview.component.html index 9bb66eda1..b4488d33d 100644 --- a/frontend/src/app/components/accelerate-preview/accelerate-preview.component.html +++ b/frontend/src/app/components/accelerate-preview/accelerate-preview.component.html @@ -1,14 +1,16 @@ +
-
+
- Transaction has now been submitted to mining pools for acceleration. You can track the progress here. + Transaction has now been submitted to mining pools for acceleration.
+
-
- +
+
@@ -23,8 +25,13 @@ > - +
+ +
+
You are currently on the waitlist
+
+
Your transaction
@@ -37,10 +44,10 @@ Virtual size - + - + Size in vbytes of this transaction and its unconfirmed ancestors @@ -48,12 +55,12 @@ In-band fees - - {{ estimate.txSummary.effectiveFee | number : '1.0-0' }} sats + + {{ estimate.txSummary.effectiveFee | number : '1.0-0' }} sats - + Fees already paid by this transaction and its unconfirmed ancestors @@ -74,8 +81,8 @@
@@ -87,23 +94,15 @@
Acceleration summary
-
-
- Estimated cost -
-
- Maximum cost -
-
- + - @@ -116,34 +115,8 @@ {{ math.max(0, estimate.nextBlockFee - estimate.txSummary.effectiveFee) | number }} - - - - - - - - - - - - - @@ -156,32 +129,32 @@ - + - - + + @@ -191,19 +164,19 @@ - - + - + - - + + + + + + + + + +
Next block market rate + {{ estimate.targetFeeRate | number : '1.0-0' }} sat/vB - sats - -
- Your maximum - - ~{{ ((estimate.txSummary.effectiveFee + userBid) / estimate.txSummary.effectiveVsize) | number : '1.0-0' }} - sat/vB
- The maximum extra transaction fee you could pay - - - {{ userBid | number }} - - - sats - + sats +
- mempool.space fee + Accelerator Service Fee +{{ estimate.mempoolBaseFee | number }} - sats - + sats +
- Transaction vsize fee + Transaction Size Surcharge +{{ estimate.vsizeFee | number }} - sats - + sats +
Estimated acceleration cost - sats - + sats +
+
If your tx is accelerated to {{ estimate.targetFeeRate | number : '1.0-0' }} sat/vB
Maximum acceleration cost @@ -214,21 +187,21 @@ - sats - + sats +
+ If your tx is accelerated to ~{{ ((estimate.txSummary.effectiveFee + userBid) / estimate.txSummary.effectiveVsize) | number : '1.0-0' }} sat/vB
Available balance @@ -237,13 +210,24 @@ {{ estimate.userBalance | number }} - sats - + sats +
+ Login +
@@ -251,7 +235,7 @@
-
+
@@ -259,4 +243,9 @@
-
\ No newline at end of file +
+ + +
+
+
\ No newline at end of file diff --git a/frontend/src/app/components/accelerate-preview/accelerate-preview.component.scss b/frontend/src/app/components/accelerate-preview/accelerate-preview.component.scss index 433c05520..2e2b19ee8 100644 --- a/frontend/src/app/components/accelerate-preview/accelerate-preview.component.scss +++ b/frontend/src/app/components/accelerate-preview/accelerate-preview.component.scss @@ -8,9 +8,6 @@ align-items: center; justify-content: center; - .fee { - font-size: 1.2em; - } .rate { font-size: 0.9em; .symbol { @@ -28,7 +25,10 @@ .feerate.active { background-color: #105fb0 !important; opacity: 1; - border: 1px solid white !important; + border: 1px solid #007fff !important; +} +.feerate:focus { + box-shadow: none !important; } .estimateDisabled { @@ -41,10 +41,26 @@ margin-top: 0.5em; } +.tab { + &:first-child { + margin-right: 1px; + } + border: solid 1px black; + border-bottom: none; + background-color: #323655; + border-top-left-radius: 10px !important; + border-top-right-radius: 10px !important; +} +.tab.active { + background-color: #5d659d !important; + opacity: 1; +} +.tab:focus { + box-shadow: none !important; +} + .table-accelerator { tr { - text-wrap: wrap; - td { padding-top: 0; padding-bottom: 0; @@ -68,6 +84,7 @@ } &.info { color: #6c757d; + white-space: initial; } &.amt { text-align: right; @@ -76,6 +93,9 @@ &.units { padding-left: 0.2em; white-space: nowrap; + display: flex; + justify-content: space-between; + align-items: center; } } } @@ -85,4 +105,8 @@ flex-direction: row; align-items: stretch; margin-top: 1em; +} + +.item { + white-space: initial; } \ No newline at end of file diff --git a/frontend/src/app/components/accelerate-preview/accelerate-preview.component.ts b/frontend/src/app/components/accelerate-preview/accelerate-preview.component.ts index 1c356a80b..43ccce3b7 100644 --- a/frontend/src/app/components/accelerate-preview/accelerate-preview.component.ts +++ b/frontend/src/app/components/accelerate-preview/accelerate-preview.component.ts @@ -1,9 +1,11 @@ -import { Component, OnInit, Input, OnDestroy, OnChanges, SimpleChanges, HostListener } from '@angular/core'; +import { Component, OnInit, Input, OnDestroy, OnChanges, SimpleChanges, HostListener, ChangeDetectorRef } from '@angular/core'; import { ApiService } from '../../services/api.service'; import { Subscription, catchError, of, tap } from 'rxjs'; import { StorageService } from '../../services/storage.service'; import { Transaction } from '../../interfaces/electrs.interface'; import { nextRoundNumber } from '../../shared/common.utils'; +import { ServicesApiServices } from '../../services/services-api.service'; +import { AudioService } from '../../services/audio.service'; export type AccelerationEstimate = { txSummary: TxSummary; @@ -55,14 +57,16 @@ export class AcceleratePreviewComponent implements OnInit, OnDestroy, OnChanges maxCost = 0; userBid = 0; selectFeeRateIndex = 1; - showTable: 'estimated' | 'maximum' = 'maximum'; isMobile: boolean = window.innerWidth <= 767.98; + user: any = undefined; maxRateOptions: RateOption[] = []; constructor( - private apiService: ApiService, - private storageService: StorageService + private servicesApiService: ServicesApiServices, + private storageService: StorageService, + private audioService: AudioService, + private cd: ChangeDetectorRef ) { } ngOnDestroy(): void { @@ -73,12 +77,14 @@ export class AcceleratePreviewComponent implements OnInit, OnDestroy, OnChanges ngOnChanges(changes: SimpleChanges): void { if (changes.scrollEvent) { - this.scrollToPreview('acceleratePreviewAnchor', 'center'); + this.scrollToPreview('acceleratePreviewAnchor', 'start'); } } ngOnInit() { - this.estimateSubscription = this.apiService.estimate$(this.tx.txid).pipe( + this.user = this.storageService.getAuth()?.user ?? null; + + this.estimateSubscription = this.servicesApiService.estimate$(this.tx.txid).pipe( tap((response) => { if (response.status === 204) { this.estimate = undefined; @@ -93,7 +99,7 @@ export class AcceleratePreviewComponent implements OnInit, OnDestroy, OnChanges this.estimateSubscription.unsubscribe(); } - if (this.estimate.userBalance <= 0) { + if (this.estimate.hasAccess === true && this.estimate.userBalance <= 0) { if (this.isLoggedIn()) { this.error = `not_enough_balance`; this.scrollToPreviewWithTimeout('mempoolError', 'center'); @@ -126,7 +132,7 @@ export class AcceleratePreviewComponent implements OnInit, OnDestroy, OnChanges this.maxCost = this.userBid + this.estimate.mempoolBaseFee + this.estimate.vsizeFee; if (!this.error) { - this.scrollToPreview('acceleratePreviewAnchor', 'center'); + this.scrollToPreview('acceleratePreviewAnchor', 'start'); } } }), @@ -162,13 +168,14 @@ export class AcceleratePreviewComponent implements OnInit, OnDestroy, OnChanges scrollToPreview(id: string, position: ScrollLogicalPosition) { const acceleratePreviewAnchor = document.getElementById(id); if (acceleratePreviewAnchor) { + this.cd.markForCheck(); acceleratePreviewAnchor.scrollIntoView({ behavior: 'smooth', inline: position, block: position, }); } -} + } /** * Send acceleration request @@ -177,17 +184,22 @@ export class AcceleratePreviewComponent implements OnInit, OnDestroy, OnChanges if (this.accelerationSubscription) { this.accelerationSubscription.unsubscribe(); } - this.accelerationSubscription = this.apiService.accelerate$( + this.accelerationSubscription = this.servicesApiService.accelerate$( this.tx.txid, this.userBid ).subscribe({ next: () => { + this.audioService.playSound('ascend-chime-cartoon'); this.showSuccess = true; this.scrollToPreviewWithTimeout('successAlert', 'center'); this.estimateSubscription.unsubscribe(); }, error: (response) => { - this.error = response.error; + if (response.status === 403 && response.error === 'not_available') { + this.error = 'waitlisted'; + } else { + this.error = response.error; + } this.scrollToPreviewWithTimeout('mempoolError', 'center'); } }); @@ -202,4 +214,4 @@ export class AcceleratePreviewComponent implements OnInit, OnDestroy, OnChanges onResize(): void { this.isMobile = window.innerWidth <= 767.98; } -} \ No newline at end of file +} diff --git a/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.html b/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.html new file mode 100644 index 000000000..faf48eac7 --- /dev/null +++ b/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.html @@ -0,0 +1,39 @@ + + +
+
+
+ Acceleration Fees + +
+ +
+
+ + + + + +
+
+
+ +
+
+
+
+
+
diff --git a/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.scss b/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.scss new file mode 100644 index 000000000..11b468a24 --- /dev/null +++ b/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.scss @@ -0,0 +1,71 @@ +.card-header { + border-bottom: 0; + font-size: 18px; + @media (min-width: 465px) { + font-size: 20px; + } + @media (min-width: 992px) { + height: 40px; + } +} + +.main-title { + position: relative; + color: #ffffff91; + margin-top: -13px; + font-size: 10px; + text-transform: uppercase; + font-weight: 500; + text-align: center; + padding-bottom: 3px; +} + +.full-container { + display: flex; + flex-direction: column; + padding: 0px 15px; + width: 100%; + height: calc(100vh - 225px); + min-height: 400px; + @media (min-width: 992px) { + height: calc(100vh - 150px); + } +} + +.chart { + display: flex; + flex: 1; + width: 100%; + height: 100%; + padding-bottom: 20px; + padding-right: 10px; + @media (max-width: 992px) { + padding-bottom: 25px; + } + @media (max-width: 829px) { + padding-bottom: 50px; + } + @media (max-width: 767px) { + padding-bottom: 25px; + } + @media (max-width: 629px) { + padding-bottom: 55px; + } + @media (max-width: 567px) { + padding-bottom: 55px; + } +} + +h5 { + margin-bottom: 10px; +} + +.card-title { + font-size: 1rem; + color: #4a68b9; +} + +.disabled { + pointer-events: none; + opacity: 0.5; +} \ No newline at end of file diff --git a/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.ts b/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.ts new file mode 100644 index 000000000..001f005a1 --- /dev/null +++ b/frontend/src/app/components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component.ts @@ -0,0 +1,311 @@ +import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, Input, LOCALE_ID, OnDestroy, OnInit } from '@angular/core'; +import { EChartsOption } from 'echarts'; +import { Observable, Subscription, combineLatest, fromEvent } from 'rxjs'; +import { startWith, switchMap, tap } from 'rxjs/operators'; +import { SeoService } from '../../../services/seo.service'; +import { formatNumber } from '@angular/common'; +import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; +import { download, formatterXAxis, formatterXAxisLabel, formatterXAxisTimeCategory } from '../../../shared/graphs.utils'; +import { StorageService } from '../../../services/storage.service'; +import { MiningService } from '../../../services/mining.service'; +import { ActivatedRoute } from '@angular/router'; +import { Acceleration } from '../../../interfaces/node-api.interface'; +import { ServicesApiServices } from '../../../services/services-api.service'; + +@Component({ + selector: 'app-acceleration-fees-graph', + templateUrl: './acceleration-fees-graph.component.html', + styleUrls: ['./acceleration-fees-graph.component.scss'], + styles: [` + .loadingGraphs { + position: absolute; + top: 50%; + left: calc(50% - 15px); + z-index: 100; + } + `], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class AccelerationFeesGraphComponent implements OnInit, OnDestroy { + @Input() widget: boolean = false; + @Input() height: number = 300; + @Input() right: number | string = 45; + @Input() left: number | string = 75; + @Input() accelerations$: Observable; + + miningWindowPreference: string; + radioGroupForm: UntypedFormGroup; + + chartOptions: EChartsOption = {}; + chartInitOptions = { + renderer: 'svg', + }; + + hrStatsObservable$: Observable; + statsObservable$: Observable; + statsSubscription: Subscription; + isLoading = true; + formatNumber = formatNumber; + timespan = ''; + chartInstance: any = undefined; + + currency: string; + + constructor( + @Inject(LOCALE_ID) public locale: string, + private seoService: SeoService, + private servicesApiService: ServicesApiServices, + private formBuilder: UntypedFormBuilder, + private storageService: StorageService, + private miningService: MiningService, + private route: ActivatedRoute, + private cd: ChangeDetectorRef, + ) { + this.radioGroupForm = this.formBuilder.group({ dateSpan: '1y' }); + this.radioGroupForm.controls.dateSpan.setValue('1y'); + this.currency = 'USD'; + } + + ngOnInit(): void { + if (this.widget) { + this.miningWindowPreference = '3m'; + } else { + this.seoService.setTitle($localize`:@@bcf34abc2d9ed8f45a2f65dd464c46694e9a181e:Acceleration Fees`); + this.miningWindowPreference = this.miningService.getDefaultTimespan('3m'); + } + this.radioGroupForm = this.formBuilder.group({ dateSpan: this.miningWindowPreference }); + this.radioGroupForm.controls.dateSpan.setValue(this.miningWindowPreference); + + this.route.fragment.subscribe((fragment) => { + if (['24h', '3d', '1w', '1m', '3m'].indexOf(fragment) > -1) { + this.radioGroupForm.controls.dateSpan.setValue(fragment, { emitEvent: false }); + } + }); + this.statsObservable$ = combineLatest([ + this.radioGroupForm.get('dateSpan').valueChanges.pipe( + startWith(this.radioGroupForm.controls.dateSpan.value), + switchMap((timespan) => { + if (!this.widget) { + this.storageService.setValue('miningWindowPreference', timespan); + } + this.isLoading = true; + this.timespan = timespan; + return this.servicesApiService.getAggregatedAccelerationHistory$({timeframe: this.timespan}); + }) + ), + fromEvent(window, 'resize').pipe(startWith(null)), + ]).pipe( + tap(([history]) => { + this.isLoading = false; + this.prepareChartOptions(history); + this.cd.markForCheck(); + }) + ); + + this.statsObservable$.subscribe(); + } + + prepareChartOptions(data) { + let title: object; + if (data.length === 0) { + title = { + textStyle: { + color: 'grey', + fontSize: 15 + }, + text: $localize`No accelerated transaction for this timeframe`, + left: 'center', + top: 'center' + }; + } + + this.chartOptions = { + title: title, + color: [ + '#8F5FF6', + '#6b6b6b', + ], + animation: false, + grid: { + height: (this.widget && this.height) ? this.height - 30 : undefined, + top: this.widget ? 20 : 40, + bottom: this.widget ? 30 : 80, + right: this.right, + left: this.left, + }, + tooltip: { + show: !this.isMobile(), + trigger: 'axis', + axisPointer: { + type: 'line' + }, + backgroundColor: 'rgba(17, 19, 31, 1)', + borderRadius: 4, + shadowColor: 'rgba(0, 0, 0, 0.5)', + textStyle: { + color: '#b1b1b1', + align: 'left', + }, + borderColor: '#000', + formatter: (ticks) => { + let tooltip = `${formatterXAxis(this.locale, this.timespan, parseInt(ticks[0].axisValue, 10))}
`; + + if (ticks[0].data[1] > 10_000_000) { + tooltip += `${ticks[0].marker} ${ticks[0].seriesName}: ${formatNumber(ticks[0].data[1] / 100_000_000, this.locale, '1.0-0')} BTC
`; + } else { + tooltip += `${ticks[0].marker} ${ticks[0].seriesName}: ${formatNumber(ticks[0].data[1], this.locale, '1.0-0')} sats
`; + } + + if (['24h', '3d'].includes(this.timespan)) { + tooltip += `` + $localize`At block: ${ticks[0].data[2]}` + ``; + } else { + tooltip += `` + $localize`Around block: ${ticks[0].data[2]}` + ``; + } + + return tooltip; + } + }, + xAxis: data.length === 0 ? undefined : + { + name: this.widget ? undefined : formatterXAxisLabel(this.locale, this.timespan), + nameLocation: 'middle', + nameTextStyle: { + padding: [10, 0, 0, 0], + }, + type: 'time', + boundaryGap: false, + axisLine: { onZero: true }, + axisLabel: { + formatter: val => formatterXAxisTimeCategory(this.locale, this.timespan, parseInt(val, 10)), + align: 'center', + fontSize: 11, + lineHeight: 12, + hideOverlap: true, + padding: [0, 5], + }, + }, + legend: { + data: [ + { + name: 'Total bid boost', + inactiveColor: 'rgb(110, 112, 121)', + textStyle: { + color: 'white', + }, + icon: 'roundRect', + }, + ], + selected: { + 'Total bid boost': true, + }, + show: !this.widget, + }, + yAxis: data.length === 0 ? undefined : [ + { + type: 'value', + axisLabel: { + color: 'rgb(110, 112, 121)', + formatter: (val) => { + if (val >= 100_000) { + return `${(val / 100_000_000).toFixed(3)} BTC`; + } else { + return `${val} sats`; + } + } + }, + splitLine: { + lineStyle: { + type: 'dotted', + color: '#ffffff66', + opacity: 0.25, + } + }, + }, + { + type: 'value', + position: 'right', + axisLabel: { + color: 'rgb(110, 112, 121)', + formatter: function(val) { + return `${val}`; + }.bind(this) + }, + splitLine: { + show: false, + }, + }, + ], + series: data.length === 0 ? undefined : [ + { + legendHoverLink: false, + zlevel: 1, + name: 'Total bid boost', + data: data.map(h => { + return [h.timestamp * 1000, h.sumBidBoost, h.avgHeight] + }), + stack: 'Total', + type: 'bar', + barWidth: '90%', + large: true, + }, + ], + dataZoom: (this.widget || data.length === 0 )? undefined : [{ + type: 'inside', + realtime: true, + zoomLock: true, + maxSpan: 100, + minSpan: 5, + moveOnMouseMove: false, + }, { + showDetail: false, + show: true, + type: 'slider', + brushSelect: false, + realtime: true, + left: 20, + right: 15, + selectedDataBackground: { + lineStyle: { + color: '#fff', + opacity: 0.45, + }, + areaStyle: { + opacity: 0, + } + }, + }], + }; + } + + onChartInit(ec) { + this.chartInstance = ec; + } + + isMobile() { + return (window.innerWidth <= 767.98); + } + + onSaveChart() { + // @ts-ignore + const prevBottom = this.chartOptions.grid.bottom; + const now = new Date(); + // @ts-ignore + this.chartOptions.grid.bottom = 40; + this.chartOptions.backgroundColor = '#11131f'; + this.chartInstance.setOption(this.chartOptions); + download(this.chartInstance.getDataURL({ + pixelRatio: 2, + excludeComponents: ['dataZoom'], + }), `acceleration-fees-${this.timespan}-${Math.round(now.getTime() / 1000)}.svg`); + // @ts-ignore + this.chartOptions.grid.bottom = prevBottom; + this.chartOptions.backgroundColor = 'none'; + this.chartInstance.setOption(this.chartOptions); + } + + ngOnDestroy(): void { + if (this.statsSubscription) { + this.statsSubscription.unsubscribe(); + } + } +} diff --git a/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.html b/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.html new file mode 100644 index 000000000..fef91acc0 --- /dev/null +++ b/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.html @@ -0,0 +1,53 @@ +
+
+
+
Requests
+
+
{{ stats.totalRequested }}
+
accelerated
+
+
+
+
Total Bid Boost
+
+
{{ stats.totalBidBoost / 100_000_000 | amountShortener: 4 }} BTC
+ + + +
+
+
+
Success Rate
+
+
{{ stats.successRate.toFixed(2) }} %
+
mined
+
+
+
+
+ + +
+
+
Requests
+
+
+
+
+
+
+
Total Bid Boost
+
+
+
+
+
+
+
Success Rate
+
+
+
+
+
+
+
diff --git a/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.scss b/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.scss new file mode 100644 index 000000000..fcc5564a8 --- /dev/null +++ b/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.scss @@ -0,0 +1,88 @@ +.card-title { + color: #4a68b9; + font-size: 10px; + margin-bottom: 4px; + font-size: 1rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.card-text { + font-size: 22px; + span { + font-size: 11px; + position: relative; + top: -2px; + display: inline-flex; + } + .green-color { + display: block; + } +} + +.stats-container { + display: flex; + justify-content: space-between; + @media (min-width: 376px) { + flex-direction: row; + } + .item { + max-width: 150px; + margin: 0; + width: -webkit-fill-available; + @media (min-width: 376px) { + margin: 0 auto 0px; + } + &:first-child{ + display: none; + @media (min-width: 485px) { + display: block; + } + @media (min-width: 768px) { + display: none; + } + @media (min-width: 992px) { + display: block; + } + } + &:last-child { + margin-bottom: 0; + } + .card-text span { + color: #ffffff66; + font-size: 12px; + top: 0px; + } + .fee-text{ + border-bottom: 1px solid #ffffff1c; + width: fit-content; + margin: auto; + line-height: 1.45; + padding: 0px 2px; + } + .fiat { + display: block; + font-size: 14px !important; + } + } +} + +.loading-container{ + min-height: 76px; +} + +.card-text { + .skeleton-loader { + width: 100%; + display: block; + &:first-child { + max-width: 90px; + margin: 15px auto 3px; + } + &:last-child { + margin: 10px auto 3px; + max-width: 55px; + } + } +} \ No newline at end of file diff --git a/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.ts b/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.ts new file mode 100644 index 000000000..29909ff39 --- /dev/null +++ b/frontend/src/app/components/acceleration/acceleration-stats/acceleration-stats.component.ts @@ -0,0 +1,27 @@ +import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; +import { Observable } from 'rxjs'; +import { ServicesApiServices } from '../../../services/services-api.service'; + +export type AccelerationStats = { + totalRequested: number; + totalBidBoost: number; + successRate: number; +} + +@Component({ + selector: 'app-acceleration-stats', + templateUrl: './acceleration-stats.component.html', + styleUrls: ['./acceleration-stats.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class AccelerationStatsComponent implements OnInit { + accelerationStats$: Observable; + + constructor( + private servicesApiService: ServicesApiServices + ) { } + + ngOnInit(): void { + this.accelerationStats$ = this.servicesApiService.getAccelerationStats$(); + } +} diff --git a/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.html b/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.html new file mode 100644 index 000000000..177eee973 --- /dev/null +++ b/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.html @@ -0,0 +1,101 @@ +
+

Accelerations

+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TXIDFee RateAcceleration BidRequestedBid BoostBlockStatusRequested
+ + + + + + + {{ (acceleration.feeDelta) | number }} sat + + + + {{ (acceleration.boost) | number }} sat + + ~ + + {{ acceleration.blockHeight }} + + Pending + Mined + Completed + Canceled + + +
+ + + + + + + +
+ + + + + +
+
+
+
+ + +
+ There are no active accelerations + There are no recent accelerations +
+
+ +
diff --git a/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.scss b/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.scss new file mode 100644 index 000000000..85e655b25 --- /dev/null +++ b/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.scss @@ -0,0 +1,186 @@ +.spinner-border { + height: 25px; + width: 25px; + margin-top: 13px; +} + +.container-xl { + max-width: 1400px; +} +.container-xl.widget { + padding-left: 0px; + padding-bottom: 0px; +} +.container-xl.legacy { + max-width: 1140px; +} +.container-xl.widget-container { + min-height: 335px; + @media (max-width: 767px) { + min-height: auto; + } +} + +.container { + max-width: 100%; +} + +.acceleration-list { + min-height: 295px; + @media (max-width: 767px) { + min-height: auto; + } +} + +tr, td, th { + border: 0px; + padding-top: 0.65rem !important; + padding-bottom: 0.8rem !important; + + .difference { + margin-left: 0.5em; + + &.positive { + color: rgb(66, 183, 71); + } + &.negative { + color: rgb(183, 66, 66); + } + } +} + +.clear-link { + color: white; +} + +.disabled { + pointer-events: none; + opacity: 0.5; +} + +.progress { + background-color: #2d3348; +} + +.txid { + width: 20%; +} + +.fee { + width: 15%; +} + +.block { + width: 15%; + @media (max-width: 700px) { + display: none; + } +} + +.status { + width: 13%; +} + +.date { + width: 20%; + @media (max-width: 600px) { + display: none; + } +} + +.widget { + .txid { + width: 30%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 30%; + } + + .fee-rate { + width: 20%; + text-align: end !important; + @media (max-width: 975px) and (min-width: 768px) { + display: none; + } + @media (max-width: 410px) { + display: none; + } + } + + .bid { + text-align: end !important; + width: 30%; + min-width: 150px; + } + + .time { + width: 25%; + @media (max-width: 600px) { + display: none; + } + @media (max-width: 1200px) and (min-width: 768px) { + display: none; + } + } + + .fee { + width: 30%; + text-align: end !important; + } + + .block { + width: 20%; + @media (max-width: 1200px) and (min-width: 768px) { + display: none; + } + } + + .status { + width: 20% + } +} + +/* Tooltip text */ +.tooltip-custom { + position: relative; +} + +.tooltip-custom .tooltiptext { + visibility: hidden; + color: #fff; + text-align: center; + padding: 5px 0; + border-radius: 6px; + position: absolute; + z-index: 1; + top: -40px; + left: 0; +} + +/* Show the tooltip text when you mouse over the tooltip container */ +.tooltip-custom:hover .tooltiptext { + visibility: visible; +} + +.scriptmessage { + overflow: hidden; + display: inline-block; + text-overflow: ellipsis; + vertical-align: middle; + max-width: 50vw; + text-align: left; +} + +.no-data { + color: rgba(255, 255, 255, 0.4); + display: flex; + height: 280px; + width: 100%; + flex-direction: row; + align-items: center; + justify-content: center; + @media (max-width: 767px) { + height: 100px; + } +} diff --git a/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.ts b/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.ts new file mode 100644 index 000000000..974f9b71b --- /dev/null +++ b/frontend/src/app/components/acceleration/accelerations-list/accelerations-list.component.ts @@ -0,0 +1,88 @@ +import { Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef } from '@angular/core'; +import { combineLatest, BehaviorSubject, Observable, catchError, of, switchMap, tap } from 'rxjs'; +import { Acceleration, BlockExtended } from '../../../interfaces/node-api.interface'; +import { StateService } from '../../../services/state.service'; +import { WebsocketService } from '../../../services/websocket.service'; +import { ServicesApiServices } from '../../../services/services-api.service'; + +@Component({ + selector: 'app-accelerations-list', + templateUrl: './accelerations-list.component.html', + styleUrls: ['./accelerations-list.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class AccelerationsListComponent implements OnInit { + @Input() widget: boolean = false; + @Input() pending: boolean = false; + @Input() accelerations$: Observable; + + accelerationList$: Observable = undefined; + + isLoading = true; + paginationMaxSize: number; + page = 1; + accelerationCount: number; + maxSize = window.innerWidth <= 767.98 ? 3 : 5; + skeletonLines: number[] = []; + pageSubject: BehaviorSubject = new BehaviorSubject(this.page); + + constructor( + private servicesApiService: ServicesApiServices, + private websocketService: WebsocketService, + public stateService: StateService, + private cd: ChangeDetectorRef, + ) { + } + + ngOnInit(): void { + if (!this.widget) { + this.websocketService.want(['blocks']); + } + + this.skeletonLines = this.widget === true ? [...Array(6).keys()] : [...Array(15).keys()]; + this.paginationMaxSize = window.matchMedia('(max-width: 670px)').matches ? 3 : 5; + + this.accelerationList$ = this.pageSubject.pipe( + switchMap((page) => { + const accelerationObservable$ = this.accelerations$ || (this.pending ? this.servicesApiService.getAccelerations$() : this.servicesApiService.getAccelerationHistoryObserveResponse$({ timeframe: '1y', page: page })); + return accelerationObservable$.pipe( + switchMap(response => { + let accelerations = response; + if (response.body) { + accelerations = response.body; + this.accelerationCount = parseInt(response.headers.get('x-total-count'), 10); + } + if (this.pending) { + for (const acceleration of accelerations) { + acceleration.status = acceleration.status || 'accelerating'; + } + } + for (const acc of accelerations) { + acc.boost = acc.feePaid - acc.baseFee - acc.vsizeFee; + } + if (this.widget) { + return of(accelerations.slice(0, 6)); + } else { + return of(accelerations); + } + }), + catchError((err) => { + this.isLoading = false; + return of([]); + }), + tap(() => { + this.isLoading = false; + }) + ); + }) + ); + } + + pageChange(page: number): void { + this.pageSubject.next(page); + } + + trackByBlock(index: number, block: BlockExtended): number { + return block.height; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.html b/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.html new file mode 100644 index 000000000..5e049198a --- /dev/null +++ b/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.html @@ -0,0 +1,105 @@ + + +
+ +
+ + +
+
+ Active Accelerations +
+
+
+
+ +
+
+
+
+ + +
+
+ Acceleration stats  + (3 months) +
+
+
+
+ +
+
+
+
+ + + + + +
+
+
+
Total Bid Boost
+
+ +
+ +
+
+
+ + + + + +
+
+
+ + +
+
+
+ + + +
+
diff --git a/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.scss b/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.scss new file mode 100644 index 000000000..c8755c94e --- /dev/null +++ b/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.scss @@ -0,0 +1,175 @@ +.dashboard-container { + text-align: center; + margin-top: 0.5rem; + .col { + margin-bottom: 1.5rem; + } +} + +.card { + background-color: #1d1f31; +} + +.graph-card { + height: 100%; + @media (min-width: 992px) { + height: 385px; + } +} + +.mempool-graph { + height: 295px; + @media (min-width: 768px) { + height: 325px; + } + @media (min-width: 992px) { + height: 409px; + } +} + +.card-title { + font-size: 1rem; + color: #4a68b9; +} +.card-title > a { + color: #4a68b9; +} + +.card-body.pool-ranking { + padding: 1.25rem 0.25rem 0.75rem 0.25rem; +} +.card-text { + font-size: 22px; +} + +#blockchain-container { + position: relative; + overflow-x: scroll; + overflow-y: hidden; + scrollbar-width: none; + -ms-overflow-style: none; +} + +#blockchain-container::-webkit-scrollbar { + display: none; +} + +.fade-border { + -webkit-mask-image: linear-gradient(to right, transparent 0%, black 10%, black 80%, transparent 100%) +} + +.main-title { + position: relative; + color: #ffffff91; + margin-top: -13px; + font-size: 10px; + text-transform: uppercase; + font-weight: 500; + text-align: center; + padding-bottom: 3px; +} + +.more-padding { + padding: 24px 20px !important; +} + +.card-wrapper { + .card { + height: auto !important; + } + .card-body { + display: flex; + flex: inherit; + text-align: center; + flex-direction: column; + justify-content: space-around; + padding: 22px 20px; + } +} + +.skeleton-loader { + width: 100%; + display: block; + &:first-child { + max-width: 90px; + margin: 15px auto 3px; + } + &:last-child { + margin: 10px auto 3px; + max-width: 55px; + } +} + +.card-text { + font-size: 22px; +} + +.title-link, .title-link:hover, .title-link:focus, .title-link:active { + display: block; + margin-bottom: 10px; + text-decoration: none; + color: inherit; +} + +.lastest-blocks-table { + width: 100%; + text-align: left; + tr, td, th { + border: 0px; + padding-top: 0.65rem !important; + padding-bottom: 0.8rem !important; + } + .table-cell-height { + width: 25%; + } + .table-cell-fee { + width: 25%; + text-align: right; + } + .table-cell-pool { + text-align: left; + width: 30%; + + @media (max-width: 875px) { + display: none; + } + + .pool-name { + margin-left: 1em; + } + } + .table-cell-acceleration-count { + text-align: right; + width: 20%; + } +} + +.card { + @media (min-width: 768px) { + height: 420px; + } + @media (min-width: 992px) { + height: 510px; + } +} +.list-card { + height: 410px; + @media (max-width: 767px) { + height: auto; + } +} + +.mempool-block-wrapper { + max-height: 430px; + max-width: 430px; + margin: auto; + + @media (min-width: 768px) { + max-height: 344px; + max-width: 344px; + } + @media (min-width: 992px) { + max-height: 430px; + max-width: 430px; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.ts b/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.ts new file mode 100644 index 000000000..ba9240d1b --- /dev/null +++ b/frontend/src/app/components/acceleration/accelerator-dashboard/accelerator-dashboard.component.ts @@ -0,0 +1,138 @@ +import { ChangeDetectionStrategy, Component, HostListener, OnInit } from '@angular/core'; +import { SeoService } from '../../../services/seo.service'; +import { WebsocketService } from '../../../services/websocket.service'; +import { Acceleration, BlockExtended } from '../../../interfaces/node-api.interface'; +import { StateService } from '../../../services/state.service'; +import { Observable, catchError, combineLatest, distinctUntilChanged, interval, map, of, share, startWith, switchMap, tap } from 'rxjs'; +import { Color } from '../../block-overview-graph/sprite-types'; +import { hexToColor } from '../../block-overview-graph/utils'; +import TxView from '../../block-overview-graph/tx-view'; +import { feeLevels, mempoolFeeColors } from '../../../app.constants'; +import { ServicesApiServices } from '../../../services/services-api.service'; + +const acceleratedColor: Color = hexToColor('8F5FF6'); +const normalColors = mempoolFeeColors.map(hex => hexToColor(hex + '5F')); + +interface AccelerationBlock extends BlockExtended { + accelerationCount: number, +} + +@Component({ + selector: 'app-accelerator-dashboard', + templateUrl: './accelerator-dashboard.component.html', + styleUrls: ['./accelerator-dashboard.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class AcceleratorDashboardComponent implements OnInit { + blocks$: Observable; + accelerations$: Observable; + pendingAccelerations$: Observable; + minedAccelerations$: Observable; + loadingBlocks: boolean = true; + + graphHeight: number = 300; + + constructor( + private seoService: SeoService, + private websocketService: WebsocketService, + private serviceApiServices: ServicesApiServices, + private stateService: StateService, + ) { + this.seoService.setTitle($localize`:@@a681a4e2011bb28157689dbaa387de0dd0aa0c11:Accelerator Dashboard`); + } + + ngOnInit(): void { + this.onResize(); + this.websocketService.want(['blocks', 'mempool-blocks', 'stats']); + + this.pendingAccelerations$ = interval(30000).pipe( + startWith(true), + switchMap(() => { + return this.serviceApiServices.getAccelerations$().pipe( + catchError(() => { + return of([]); + }), + ); + }), + share(), + ); + + this.accelerations$ = this.stateService.chainTip$.pipe( + distinctUntilChanged(), + switchMap(() => { + return this.serviceApiServices.getAccelerationHistory$({ timeframe: '3m', page: 1, pageLength: 100}).pipe( + catchError(() => { + return of([]); + }), + ); + }), + share(), + ); + + this.minedAccelerations$ = this.accelerations$.pipe( + map(accelerations => { + return accelerations.filter(acc => ['mined', 'completed'].includes(acc.status)); + }) + ); + + this.blocks$ = combineLatest([ + this.accelerations$, + this.stateService.blocks$.pipe( + switchMap((blocks) => { + if (this.stateService.env.MINING_DASHBOARD === true) { + for (const block of blocks) { + // @ts-ignore: Need to add an extra field for the template + block.extras.pool.logo = `/resources/mining-pools/` + + block.extras.pool.name.toLowerCase().replace(' ', '').replace('.', '') + '.svg'; + } + } + return of(blocks as AccelerationBlock[]); + }), + tap(() => { + this.loadingBlocks = false; + }) + ) + ]).pipe( + switchMap(([accelerations, blocks]) => { + const blockMap = {}; + for (const block of blocks) { + blockMap[block.id] = block; + } + const accelerationsByBlock: { [ hash: string ]: Acceleration[] } = {}; + for (const acceleration of accelerations) { + if (['mined', 'completed'].includes(acceleration.status) && acceleration.pools.includes(blockMap[acceleration.blockHash]?.extras.pool.id)) { + if (!accelerationsByBlock[acceleration.blockHash]) { + accelerationsByBlock[acceleration.blockHash] = []; + } + accelerationsByBlock[acceleration.blockHash].push(acceleration); + } + } + return of(blocks.slice(0, 6).map(block => { + block.accelerationCount = (accelerationsByBlock[block.id] || []).length; + return block; + })); + }) + ); + } + + getAcceleratorColor(tx: TxView): Color { + if (tx.status === 'accelerated' || tx.acc) { + return acceleratedColor; + } else { + const rate = tx.fee / tx.vsize; // color by simple single-tx fee rate + const feeLevelIndex = feeLevels.findIndex((feeLvl) => Math.max(1, rate) < feeLvl) - 1; + return normalColors[feeLevelIndex] || normalColors[mempoolFeeColors.length - 1]; + } + } + + @HostListener('window:resize', ['$event']) + onResize(): void { + if (window.innerWidth >= 992) { + this.graphHeight = 380; + } else if (window.innerWidth >= 768) { + this.graphHeight = 300; + } else { + this.graphHeight = 270; + } + } +} diff --git a/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.html b/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.html new file mode 100644 index 000000000..377f8754a --- /dev/null +++ b/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.html @@ -0,0 +1,53 @@ +
+
+
+
Requests
+
+
{{ stats.count }}
+
pending
+
+
+
+
Avg Max Bid
+
+
{{ stats.avgFeeDelta / 100_000_000 | amountShortener: 4 }} BTC
+ + + +
+
+
+
Total Vsize
+
+
+
{{ (stats.totalVsize / 1_000_000 * 100).toFixed(2) }}% of next block
+
+
+
+
+ + +
+
+
Requests
+
+
+
+
+
+
+
Avg Max Bid
+
+
+
+
+
+
+
Total Vsize
+
+
+
+
+
+
+
diff --git a/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.scss b/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.scss new file mode 100644 index 000000000..fcc5564a8 --- /dev/null +++ b/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.scss @@ -0,0 +1,88 @@ +.card-title { + color: #4a68b9; + font-size: 10px; + margin-bottom: 4px; + font-size: 1rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.card-text { + font-size: 22px; + span { + font-size: 11px; + position: relative; + top: -2px; + display: inline-flex; + } + .green-color { + display: block; + } +} + +.stats-container { + display: flex; + justify-content: space-between; + @media (min-width: 376px) { + flex-direction: row; + } + .item { + max-width: 150px; + margin: 0; + width: -webkit-fill-available; + @media (min-width: 376px) { + margin: 0 auto 0px; + } + &:first-child{ + display: none; + @media (min-width: 485px) { + display: block; + } + @media (min-width: 768px) { + display: none; + } + @media (min-width: 992px) { + display: block; + } + } + &:last-child { + margin-bottom: 0; + } + .card-text span { + color: #ffffff66; + font-size: 12px; + top: 0px; + } + .fee-text{ + border-bottom: 1px solid #ffffff1c; + width: fit-content; + margin: auto; + line-height: 1.45; + padding: 0px 2px; + } + .fiat { + display: block; + font-size: 14px !important; + } + } +} + +.loading-container{ + min-height: 76px; +} + +.card-text { + .skeleton-loader { + width: 100%; + display: block; + &:first-child { + max-width: 90px; + margin: 15px auto 3px; + } + &:last-child { + margin: 10px auto 3px; + max-width: 55px; + } + } +} \ No newline at end of file diff --git a/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.ts b/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.ts new file mode 100644 index 000000000..ed7061156 --- /dev/null +++ b/frontend/src/app/components/acceleration/pending-stats/pending-stats.component.ts @@ -0,0 +1,41 @@ +import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; +import { Observable, of } from 'rxjs'; +import { switchMap } from 'rxjs/operators'; +import { Acceleration } from '../../../interfaces/node-api.interface'; +import { ServicesApiServices } from '../../../services/services-api.service'; + +@Component({ + selector: 'app-pending-stats', + templateUrl: './pending-stats.component.html', + styleUrls: ['./pending-stats.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class PendingStatsComponent implements OnInit { + @Input() accelerations$: Observable; + public accelerationStats$: Observable; + + constructor( + private servicesApiService: ServicesApiServices, + ) { } + + ngOnInit(): void { + this.accelerationStats$ = (this.accelerations$ || this.servicesApiService.getAccelerations$()).pipe( + switchMap(accelerations => { + let totalAccelerations = 0; + let totalFeeDelta = 0; + let totalVsize = 0; + for (const acceleration of accelerations) { + totalAccelerations++; + totalFeeDelta += acceleration.feeDelta || 0; + totalVsize += acceleration.effectiveVsize || 0; + } + return of({ + count: totalAccelerations, + totalFeeDelta, + avgFeeDelta: totalAccelerations ? totalFeeDelta / totalAccelerations : 0, + totalVsize, + }); + }) + ); + } +} diff --git a/frontend/src/app/components/address-labels/address-labels.component.ts b/frontend/src/app/components/address-labels/address-labels.component.ts index f4b3d0ca5..2365c167f 100644 --- a/frontend/src/app/components/address-labels/address-labels.component.ts +++ b/frontend/src/app/components/address-labels/address-labels.component.ts @@ -43,7 +43,7 @@ export class AddressLabelsComponent implements OnChanges { handleVin() { if (this.vin.inner_witnessscript_asm) { - if (this.vin.inner_witnessscript_asm.indexOf('OP_DEPTH OP_PUSHNUM_12 OP_EQUAL OP_IF OP_PUSHNUM_11') === 0) { + if (this.vin.inner_witnessscript_asm.indexOf('OP_DEPTH OP_PUSHNUM_12 OP_EQUAL OP_IF OP_PUSHNUM_11') === 0 || this.vin.inner_witnessscript_asm.indexOf('OP_PUSHNUM_15 OP_CHECKMULTISIG OP_IFDUP OP_NOTIF OP_PUSHBYTES_2') === 1259) { if (this.vin.witness.length > 11) { this.label = 'Liquid Peg Out'; } else { diff --git a/frontend/src/app/components/address/address-preview.component.ts b/frontend/src/app/components/address/address-preview.component.ts index 9bc6e967f..4ea857b37 100644 --- a/frontend/src/app/components/address/address-preview.component.ts +++ b/frontend/src/app/components/address/address-preview.component.ts @@ -69,7 +69,7 @@ export class AddressPreviewComponent implements OnInit, OnDestroy { this.addressString = this.addressString.toLowerCase(); } this.seoService.setTitle($localize`:@@address.component.browser-title:Address: ${this.addressString}:INTERPOLATION:`); - this.seoService.setDescription($localize`:@@meta.description.bitcoin.address:See mempool transactions, confirmed transactions, balance, and more for ${this.stateService.network==='liquid'||this.stateService.network==='liquidtestnet'?'Liquid':'Bitcoin'}${seoDescriptionNetwork(this.stateService.network)} address ${this.addressString}:INTERPOLATION:.`); + this.seoService.setDescription($localize`:@@meta.description.bitcoin.address:See mempool transactions, confirmed transactions, balance, and more for ${this.stateService.network==='liquid'||this.stateService.network==='liquidtestnet'?'Liquid':'Bitcoin'} ${seoDescriptionNetwork(this.stateService.network)} address ${this.addressString}:INTERPOLATION:.`); return (this.addressString.match(/04[a-fA-F0-9]{128}|(02|03)[a-fA-F0-9]{64}/) ? this.electrsApiService.getPubKeyAddress$(this.addressString) diff --git a/frontend/src/app/components/address/address.component.ts b/frontend/src/app/components/address/address.component.ts index e9cd0189b..7e613dba6 100644 --- a/frontend/src/app/components/address/address.component.ts +++ b/frontend/src/app/components/address/address.component.ts @@ -31,8 +31,7 @@ export class AddressComponent implements OnInit, OnDestroy { addressLoadingStatus$: Observable; addressInfo: null | AddressInformation = null; - totalConfirmedTxCount = 0; - loadedConfirmedTxCount = 0; + fullyLoaded = false; txCount = 0; received = 0; sent = 0; @@ -66,7 +65,7 @@ export class AddressComponent implements OnInit, OnDestroy { switchMap((params: ParamMap) => { this.error = undefined; this.isLoadingAddress = true; - this.loadedConfirmedTxCount = 0; + this.fullyLoaded = false; this.address = null; this.isLoadingTransactions = true; this.transactions = null; @@ -105,7 +104,7 @@ export class AddressComponent implements OnInit, OnDestroy { .pipe( filter((address) => !!address), tap((address: Address) => { - if ((this.stateService.network === 'liquid' || this.stateService.network === 'liquidtestnet') && /^([m-zA-HJ-NP-Z1-9]{26,35}|[a-z]{2,5}1[ac-hj-np-z02-9]{8,100}|[a-km-zA-HJ-NP-Z1-9]{80})$/.test(address.address)) { + if ((this.stateService.network === 'liquid' || this.stateService.network === 'liquidtestnet') && /^([a-zA-HJ-NP-Z1-9]{26,35}|[a-z]{2,5}1[ac-hj-np-z02-9]{8,100}|[a-km-zA-HJ-NP-Z1-9]{80})$/.test(address.address)) { this.apiService.validateAddress$(address.address) .subscribe((addressInfo) => { this.addressInfo = addressInfo; @@ -128,7 +127,6 @@ export class AddressComponent implements OnInit, OnDestroy { this.tempTransactions = transactions; if (transactions.length) { this.lastTransactionTxId = transactions[transactions.length - 1].txid; - this.loadedConfirmedTxCount += transactions.filter((tx) => tx.status.confirmed).length; } const fetchTxs: string[] = []; @@ -174,6 +172,11 @@ export class AddressComponent implements OnInit, OnDestroy { this.addTransaction(tx); }); + this.stateService.mempoolRemovedTransactions$ + .subscribe(tx => { + this.removeTransaction(tx); + }); + this.stateService.blockTransactions$ .subscribe((transaction) => { const tx = this.transactions.find((t) => t.txid === transaction.txid); @@ -186,8 +189,6 @@ export class AddressComponent implements OnInit, OnDestroy { this.audioService.playSound('magic'); } } - this.totalConfirmedTxCount++; - this.loadedConfirmedTxCount++; }); } @@ -222,17 +223,44 @@ export class AddressComponent implements OnInit, OnDestroy { return true; } + removeTransaction(transaction: Transaction): boolean { + const index = this.transactions.findIndex(((tx) => tx.txid === transaction.txid)); + if (index === -1) { + return false; + } + + this.transactions.splice(index, 1); + this.transactions = this.transactions.slice(); + this.txCount--; + + transaction.vin.forEach((vin) => { + if (vin?.prevout?.scriptpubkey_address === this.address.address) { + this.sent -= vin.prevout.value; + } + }); + transaction.vout.forEach((vout) => { + if (vout?.scriptpubkey_address === this.address.address) { + this.received -= vout.value; + } + }); + + return true; + } + loadMore() { - if (this.isLoadingTransactions || !this.totalConfirmedTxCount || this.loadedConfirmedTxCount >= this.totalConfirmedTxCount) { + if (this.isLoadingTransactions || this.fullyLoaded) { return; } this.isLoadingTransactions = true; this.retryLoadMore = false; this.electrsApiService.getAddressTransactions$(this.address.address, this.lastTransactionTxId) .subscribe((transactions: Transaction[]) => { - this.lastTransactionTxId = transactions[transactions.length - 1].txid; - this.loadedConfirmedTxCount += transactions.length; - this.transactions = this.transactions.concat(transactions); + if (transactions && transactions.length) { + this.lastTransactionTxId = transactions[transactions.length - 1].txid; + this.transactions = this.transactions.concat(transactions); + } else { + this.fullyLoaded = true; + } this.isLoadingTransactions = false; }, (error) => { @@ -249,7 +277,6 @@ export class AddressComponent implements OnInit, OnDestroy { this.received = this.address.chain_stats.funded_txo_sum + this.address.mempool_stats.funded_txo_sum; this.sent = this.address.chain_stats.spent_txo_sum + this.address.mempool_stats.spent_txo_sum; this.txCount = this.address.chain_stats.tx_count + this.address.mempool_stats.tx_count; - this.totalConfirmedTxCount = this.address.chain_stats.tx_count; } ngOnDestroy() { diff --git a/frontend/src/app/components/amount/amount.component.html b/frontend/src/app/components/amount/amount.component.html index 29f61ca41..34f9be8ae 100644 --- a/frontend/src/app/components/amount/amount.component.html +++ b/frontend/src/app/components/amount/amount.component.html @@ -19,7 +19,7 @@ ‎{{ addPlus && satoshis >= 0 ? '+' : '' }}{{ satoshis / 100000000 | number : digitsInfo }} - L- + L- tL- t sBTC diff --git a/frontend/src/app/components/amount/amount.component.ts b/frontend/src/app/components/amount/amount.component.ts index 479ae4791..9c779265c 100644 --- a/frontend/src/app/components/amount/amount.component.ts +++ b/frontend/src/app/components/amount/amount.component.ts @@ -23,6 +23,7 @@ export class AmountComponent implements OnInit, OnDestroy { @Input() noFiat = false; @Input() addPlus = false; @Input() blockConversion: Price; + @Input() forceBtc: boolean = false; constructor( private stateService: StateService, diff --git a/frontend/src/app/components/assets/asset-group/asset-group.component.html b/frontend/src/app/components/assets/asset-group/asset-group.component.html index a4c9e9da0..600a8a9bd 100644 --- a/frontend/src/app/components/assets/asset-group/asset-group.component.html +++ b/frontend/src/app/components/assets/asset-group/asset-group.component.html @@ -4,7 +4,7 @@
-

{{ group.name }}

+

{{ group['group'].name }}

Group of {{ group.assets.length | number }} assets
diff --git a/frontend/src/app/components/bisq-master-page/bisq-master-page.component.html b/frontend/src/app/components/bisq-master-page/bisq-master-page.component.html index 61597a2ed..19c5ab715 100644 --- a/frontend/src/app/components/bisq-master-page/bisq-master-page.component.html +++ b/frontend/src/app/components/bisq-master-page/bisq-master-page.component.html @@ -1,4 +1,4 @@ -
+
diff --git a/frontend/src/app/components/block-overview-graph/block-overview-graph.component.scss b/frontend/src/app/components/block-overview-graph/block-overview-graph.component.scss index d30dd3305..92964d948 100644 --- a/frontend/src/app/components/block-overview-graph/block-overview-graph.component.scss +++ b/frontend/src/app/components/block-overview-graph/block-overview-graph.component.scss @@ -7,6 +7,19 @@ justify-content: center; align-items: center; grid-column: 1/-1; + + .placeholder { + display: flex; + position: absolute; + left: 0; + right: 0; + top: 0; + bottom: 0; + height: 100%; + width: 100%; + align-items: center; + justify-content: center; + } } .grid-align { diff --git a/frontend/src/app/components/block-overview-graph/block-overview-graph.component.ts b/frontend/src/app/components/block-overview-graph/block-overview-graph.component.ts index c32216db9..95305d72f 100644 --- a/frontend/src/app/components/block-overview-graph/block-overview-graph.component.ts +++ b/frontend/src/app/components/block-overview-graph/block-overview-graph.component.ts @@ -4,10 +4,25 @@ import { FastVertexArray } from './fast-vertex-array'; import BlockScene from './block-scene'; import TxSprite from './tx-sprite'; import TxView from './tx-view'; -import { Position } from './sprite-types'; +import { Color, Position } from './sprite-types'; import { Price } from '../../services/price.service'; import { StateService } from '../../services/state.service'; import { Subscription } from 'rxjs'; +import { defaultColorFunction, setOpacity, defaultFeeColors, defaultAuditFeeColors, defaultMarginalFeeColors, defaultAuditColors } from './utils'; +import { ActiveFilter, FilterMode, toFlags } from '../../shared/filters.utils'; +import { detectWebGL } from '../../shared/graphs.utils'; + +const unmatchedOpacity = 0.2; +const unmatchedFeeColors = defaultFeeColors.map(c => setOpacity(c, unmatchedOpacity)); +const unmatchedAuditFeeColors = defaultAuditFeeColors.map(c => setOpacity(c, unmatchedOpacity)); +const unmatchedMarginalFeeColors = defaultMarginalFeeColors.map(c => setOpacity(c, unmatchedOpacity)); +const unmatchedAuditColors = { + censored: setOpacity(defaultAuditColors.censored, unmatchedOpacity), + missing: setOpacity(defaultAuditColors.missing, unmatchedOpacity), + added: setOpacity(defaultAuditColors.added, unmatchedOpacity), + selected: setOpacity(defaultAuditColors.selected, unmatchedOpacity), + accelerated: setOpacity(defaultAuditColors.accelerated, unmatchedOpacity), +}; @Component({ selector: 'app-block-overview-graph', @@ -20,11 +35,18 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On @Input() blockLimit: number; @Input() orientation = 'left'; @Input() flip = true; + @Input() animationDuration: number = 1000; + @Input() animationOffset: number | null = null; @Input() disableSpinner = false; @Input() mirrorTxid: string | void; @Input() unavailable: boolean = false; @Input() auditHighlighting: boolean = false; + @Input() showFilters: boolean = false; + @Input() excludeFilters: string[] = []; + @Input() filterFlags: bigint | null = null; + @Input() filterMode: FilterMode = 'and'; @Input() blockConversion: Price; + @Input() overrideColors: ((tx: TxView) => Color) | null = null; @Output() txClickEvent = new EventEmitter<{ tx: TransactionStripped, keyModifier: boolean}>(); @Output() txHoverEvent = new EventEmitter(); @Output() readyEvent = new EventEmitter(); @@ -53,12 +75,17 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On searchText: string; searchSubscription: Subscription; + filtersAvailable: boolean = true; + activeFilterFlags: bigint | null = null; + + webGlEnabled = true; constructor( readonly ngZone: NgZone, readonly elRef: ElementRef, private stateService: StateService, ) { + this.webGlEnabled = detectWebGL(); this.vertexArray = new FastVertexArray(512, TxSprite.dataSize); this.searchSubscription = this.stateService.searchText$.subscribe((text) => { this.searchText = text; @@ -89,6 +116,25 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On if (changes.auditHighlighting) { this.setHighlightingEnabled(this.auditHighlighting); } + if (changes.overrideColor && this.scene) { + this.scene.setColorFunction(this.overrideColors); + } + if ((changes.filterFlags || changes.showFilters || changes.filterMode)) { + this.setFilterFlags(); + } + } + + setFilterFlags(goggle?: ActiveFilter): void { + this.filterMode = goggle?.mode || this.filterMode; + this.activeFilterFlags = goggle?.filters ? toFlags(goggle.filters) : this.filterFlags; + if (this.scene) { + if (this.activeFilterFlags != null && this.filtersAvailable) { + this.scene.setColorFunction(this.getFilterColorFunction(this.activeFilterFlags)); + } else { + this.scene.setColorFunction(this.overrideColors); + } + } + this.start(); } ngOnDestroy(): void { @@ -117,6 +163,11 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On // initialize the scene without any entry transition setup(transactions: TransactionStripped[]): void { + const filtersAvailable = transactions.reduce((flagSet, tx) => flagSet || tx.flags > 0, false); + if (filtersAvailable !== this.filtersAvailable) { + this.setFilterFlags(); + } + this.filtersAvailable = filtersAvailable; if (this.scene) { this.scene.setup(transactions); this.readyNextFrame = true; @@ -141,9 +192,9 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On } } - replace(transactions: TransactionStripped[], direction: string, sort: boolean = true): void { + replace(transactions: TransactionStripped[], direction: string, sort: boolean = true, startTime?: number): void { if (this.scene) { - this.scene.replace(transactions || [], direction, sort); + this.scene.replace(transactions || [], direction, sort, startTime); this.start(); this.updateSearchHighlight(); } @@ -226,7 +277,8 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On } else { this.scene = new BlockScene({ width: this.displayWidth, height: this.displayHeight, resolution: this.resolution, blockLimit: this.blockLimit, orientation: this.orientation, flip: this.flip, vertexArray: this.vertexArray, - highlighting: this.auditHighlighting }); + highlighting: this.auditHighlighting, animationDuration: this.animationDuration, animationOffset: this.animationOffset, + colorFunction: this.getColorFunction() }); this.start(); } } @@ -367,6 +419,8 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On onPointerMove(event) { if (event.target === this.canvas.nativeElement) { this.setPreviewTx(event.offsetX, event.offsetY, false); + } else { + this.onPointerLeave(event); } } @@ -456,17 +510,45 @@ export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy, On } onTxClick(cssX: number, cssY: number, keyModifier: boolean = false) { - const x = cssX * window.devicePixelRatio; - const y = cssY * window.devicePixelRatio; - const selected = this.scene.getTxAt({ x, y }); - if (selected && selected.txid) { - this.txClickEvent.emit({ tx: selected, keyModifier }); + if (this.scene) { + const x = cssX * window.devicePixelRatio; + const y = cssY * window.devicePixelRatio; + const selected = this.scene.getTxAt({ x, y }); + if (selected && selected.txid) { + this.txClickEvent.emit({ tx: selected, keyModifier }); + } } } onTxHover(hoverId: string) { this.txHoverEvent.emit(hoverId); } + + getColorFunction(): ((tx: TxView) => Color) { + if (this.filterFlags) { + return this.getFilterColorFunction(this.filterFlags); + } else if (this.activeFilterFlags) { + return this.getFilterColorFunction(this.activeFilterFlags); + } else { + return this.overrideColors; + } + } + + getFilterColorFunction(flags: bigint): ((tx: TxView) => Color) { + return (tx: TxView) => { + if ((this.filterMode === 'and' && (tx.bigintFlags & flags) === flags) || (this.filterMode === 'or' && (flags === 0n || (tx.bigintFlags & flags) > 0n))) { + return defaultColorFunction(tx); + } else { + return defaultColorFunction( + tx, + unmatchedFeeColors, + unmatchedAuditFeeColors, + unmatchedMarginalFeeColors, + unmatchedAuditColors + ); + } + }; + } } // WebGL shader attributes diff --git a/frontend/src/app/components/block-overview-graph/block-scene.ts b/frontend/src/app/components/block-overview-graph/block-scene.ts index cb0537e2a..adcf736fc 100644 --- a/frontend/src/app/components/block-overview-graph/block-scene.ts +++ b/frontend/src/app/components/block-overview-graph/block-scene.ts @@ -1,15 +1,21 @@ import { FastVertexArray } from './fast-vertex-array'; import TxView from './tx-view'; import { TransactionStripped } from '../../interfaces/websocket.interface'; -import { Position, Square, ViewUpdateParams } from './sprite-types'; +import { Color, Position, Square, ViewUpdateParams } from './sprite-types'; +import { defaultColorFunction } from './utils'; export default class BlockScene { scene: { count: number, offset: { x: number, y: number}}; vertexArray: FastVertexArray; txs: { [key: string]: TxView }; + getColor: ((tx: TxView) => Color) = defaultColorFunction; orientation: string; flip: boolean; + animationDuration: number = 900; + configAnimationOffset: number | null; + animationOffset: number; highlightingEnabled: boolean; + filterFlags: bigint | null = 0b00000100_00000000_00000000_00000000n; width: number; height: number; gridWidth: number; @@ -23,11 +29,11 @@ export default class BlockScene { animateUntil = 0; dirty: boolean; - constructor({ width, height, resolution, blockLimit, orientation, flip, vertexArray, highlighting }: - { width: number, height: number, resolution: number, blockLimit: number, - orientation: string, flip: boolean, vertexArray: FastVertexArray, highlighting: boolean } + constructor({ width, height, resolution, blockLimit, animationDuration, animationOffset, orientation, flip, vertexArray, highlighting, colorFunction }: + { width: number, height: number, resolution: number, blockLimit: number, animationDuration: number, animationOffset: number, + orientation: string, flip: boolean, vertexArray: FastVertexArray, highlighting: boolean, colorFunction: ((tx: TxView) => Color) | null } ) { - this.init({ width, height, resolution, blockLimit, orientation, flip, vertexArray, highlighting }); + this.init({ width, height, resolution, blockLimit, animationDuration, animationOffset, orientation, flip, vertexArray, highlighting, colorFunction }); } resize({ width = this.width, height = this.height, animate = true }: { width?: number, height?: number, animate: boolean }): void { @@ -36,6 +42,7 @@ export default class BlockScene { this.gridSize = this.width / this.gridWidth; this.unitPadding = Math.max(1, Math.floor(this.gridSize / 5)); this.unitWidth = this.gridSize - (this.unitPadding * 2); + this.animationOffset = this.configAnimationOffset == null ? (this.width * 1.4) : this.configAnimationOffset; this.dirty = true; if (this.initialised && this.scene) { @@ -59,6 +66,14 @@ export default class BlockScene { } } + setColorFunction(colorFunction: ((tx: TxView) => Color) | null): void { + this.getColor = colorFunction || defaultColorFunction; + this.dirty = true; + if (this.initialised && this.scene) { + this.updateColors(performance.now(), 50); + } + } + // Destroy the current layout and clean up graphics sprites without any exit animation destroy(): void { Object.values(this.txs).forEach(tx => tx.destroy()); @@ -82,7 +97,7 @@ export default class BlockScene { this.applyTxUpdate(txView, { display: { position: txView.screenPosition, - color: txView.getColor() + color: this.getColor(txView) }, duration: 0 }); @@ -90,8 +105,8 @@ export default class BlockScene { } // Animate new block entering scene - enter(txs: TransactionStripped[], direction) { - this.replace(txs, direction); + enter(txs: TransactionStripped[], direction, startTime?: number) { + this.replace(txs, direction, false, startTime); } // Animate block leaving scene @@ -108,8 +123,7 @@ export default class BlockScene { } // Reset layout and replace with new set of transactions - replace(txs: TransactionStripped[], direction: string = 'left', sort: boolean = true): void { - const startTime = performance.now(); + replace(txs: TransactionStripped[], direction: string = 'left', sort: boolean = true, startTime: number = performance.now()): void { const nextIds = {}; const remove = []; txs.forEach(tx => { @@ -133,7 +147,7 @@ export default class BlockScene { removed.forEach(tx => { tx.destroy(); }); - }, 1000); + }, (startTime - performance.now()) + this.animationDuration + 1000); this.layout = new BlockLayout({ width: this.gridWidth, height: this.gridHeight }); @@ -147,7 +161,7 @@ export default class BlockScene { }); } - this.updateAll(startTime, 200, direction); + this.updateAll(startTime, 50, direction); } update(add: TransactionStripped[], remove: string[], change: { txid: string, rate: number | undefined, acc: boolean | undefined }[], direction: string = 'left', resetLayout: boolean = false): void { @@ -214,14 +228,18 @@ export default class BlockScene { this.animateUntil = Math.max(this.animateUntil, tx.setHighlight(value)); } - private init({ width, height, resolution, blockLimit, orientation, flip, vertexArray, highlighting }: - { width: number, height: number, resolution: number, blockLimit: number, - orientation: string, flip: boolean, vertexArray: FastVertexArray, highlighting: boolean } + private init({ width, height, resolution, blockLimit, animationDuration, animationOffset, orientation, flip, vertexArray, highlighting, colorFunction }: + { width: number, height: number, resolution: number, blockLimit: number, animationDuration: number, animationOffset: number, + orientation: string, flip: boolean, vertexArray: FastVertexArray, highlighting: boolean, colorFunction: ((tx: TxView) => Color) | null } ): void { + this.animationDuration = animationDuration || 1000; + this.configAnimationOffset = animationOffset; + this.animationOffset = this.configAnimationOffset == null ? (this.width * 1.4) : this.configAnimationOffset; this.orientation = orientation; this.flip = flip; this.vertexArray = vertexArray; this.highlightingEnabled = highlighting; + this.getColor = colorFunction || defaultColorFunction; this.scene = { count: 0, @@ -248,6 +266,20 @@ export default class BlockScene { this.animateUntil = Math.max(this.animateUntil, tx.update(update)); } + private updateTxColor(tx: TxView, startTime: number, delay: number, animate: boolean = true, duration?: number): void { + if (tx.dirty || this.dirty) { + const txColor = this.getColor(tx); + this.applyTxUpdate(tx, { + display: { + color: txColor + }, + duration: animate ? (duration || this.animationDuration) : 1, + start: startTime, + delay: animate ? delay : 0, + }); + } + } + private updateTx(tx: TxView, startTime: number, delay: number, direction: string = 'left', animate: boolean = true): void { if (tx.dirty || this.dirty) { this.saveGridToScreenPosition(tx); @@ -255,14 +287,28 @@ export default class BlockScene { } } + private updateColor(tx: TxView, startTime: number, delay: number, animate: boolean = true, duration: number = 500): void { + if (tx.dirty || this.dirty) { + const txColor = this.getColor(tx); + this.applyTxUpdate(tx, { + display: { + color: txColor, + }, + start: startTime, + delay, + duration: animate ? duration : 0, + }); + } + } + private setTxOnScreen(tx: TxView, startTime: number, delay: number = 50, direction: string = 'left', animate: boolean = true): void { if (!tx.initialised) { - const txColor = tx.getColor(); + const txColor = this.getColor(tx); this.applyTxUpdate(tx, { display: { position: { - x: tx.screenPosition.x + (direction === 'right' ? -this.width : (direction === 'left' ? this.width : 0)) * 1.4, - y: tx.screenPosition.y + (direction === 'up' ? -this.height : (direction === 'down' ? this.height : 0)) * 1.4, + x: tx.screenPosition.x + (direction === 'right' ? -this.width - this.animationOffset : (direction === 'left' ? this.width + this.animationOffset : 0)), + y: tx.screenPosition.y + (direction === 'up' ? -this.height - this.animationOffset : (direction === 'down' ? this.height + this.animationOffset : 0)), s: tx.screenPosition.s }, color: txColor, @@ -275,17 +321,17 @@ export default class BlockScene { position: tx.screenPosition, color: txColor }, - duration: animate ? 1000 : 1, + duration: animate ? this.animationDuration : 1, start: startTime, delay: animate ? delay : 0, }); } else { this.applyTxUpdate(tx, { display: { - position: tx.screenPosition + position: tx.screenPosition, }, - duration: animate ? 1000 : 0, - minDuration: animate ? 500 : 0, + duration: animate ? this.animationDuration : 0, + minDuration: animate ? (this.animationDuration / 2) : 0, start: startTime, delay: animate ? delay : 0, adjust: animate @@ -315,6 +361,15 @@ export default class BlockScene { this.dirty = false; } + private updateColors(startTime: number, delay: number = 50, animate: boolean = true, duration: number = 500): void { + const ids = this.getTxList(); + startTime = startTime || performance.now(); + for (const id of ids) { + this.updateColor(this.txs[id], startTime, delay, animate, duration); + } + this.dirty = false; + } + private remove(id: string, startTime: number, direction: string = 'left'): TxView | void { const tx = this.txs[id]; if (tx) { @@ -322,11 +377,11 @@ export default class BlockScene { this.applyTxUpdate(tx, { display: { position: { - x: tx.screenPosition.x + (direction === 'right' ? this.width : (direction === 'left' ? -this.width : 0)) * 1.4, - y: tx.screenPosition.y + (direction === 'up' ? this.height : (direction === 'down' ? -this.height : 0)) * 1.4, + x: tx.screenPosition.x + (direction === 'right' ? this.width + this.animationOffset : (direction === 'left' ? -this.width - this.animationOffset : 0)), + y: tx.screenPosition.y + (direction === 'up' ? this.height + this.animationOffset : (direction === 'down' ? -this.height - this.animationOffset : 0)), } }, - duration: 1000, + duration: this.animationDuration, start: startTime, delay: 50 }); @@ -851,4 +906,4 @@ class BlockLayout { function feeRateDescending(a: TxView, b: TxView) { return b.feerate - a.feerate; -} +} \ No newline at end of file diff --git a/frontend/src/app/components/block-overview-graph/tx-view.ts b/frontend/src/app/components/block-overview-graph/tx-view.ts index db2c4f6ae..b6008ef1d 100644 --- a/frontend/src/app/components/block-overview-graph/tx-view.ts +++ b/frontend/src/app/components/block-overview-graph/tx-view.ts @@ -1,25 +1,15 @@ import TxSprite from './tx-sprite'; import { FastVertexArray } from './fast-vertex-array'; -import { TransactionStripped } from '../../interfaces/websocket.interface'; import { SpriteUpdateParams, Square, Color, ViewUpdateParams } from './sprite-types'; -import { feeLevels, mempoolFeeColors } from '../../app.constants'; +import { hexToColor } from './utils'; import BlockScene from './block-scene'; +import { TransactionStripped } from '../../interfaces/node-api.interface'; +import { TransactionFlags } from '../../shared/filters.utils'; const hoverTransitionTime = 300; const defaultHoverColor = hexToColor('1bd8f4'); const defaultHighlightColor = hexToColor('800080'); -const feeColors = mempoolFeeColors.map(hexToColor); -const auditFeeColors = feeColors.map((color) => darken(desaturate(color, 0.3), 0.9)); -const marginalFeeColors = feeColors.map((color) => darken(desaturate(color, 0.8), 1.1)); -const auditColors = { - censored: hexToColor('f344df'), - missing: darken(desaturate(hexToColor('f344df'), 0.3), 0.7), - added: hexToColor('0099ff'), - selected: darken(desaturate(hexToColor('0099ff'), 0.3), 0.7), - accelerated: hexToColor('8F5FF6'), -}; - // convert from this class's update format to TxSprite's update format function toSpriteUpdate(params: ViewUpdateParams): SpriteUpdateParams { return { @@ -40,6 +30,7 @@ export default class TxView implements TransactionStripped { feerate: number; acc?: boolean; rate?: number; + bigintFlags?: bigint | null = 0b00000100_00000000_00000000_00000000n; status?: 'found' | 'missing' | 'sigop' | 'fresh' | 'freshcpfp' | 'added' | 'censored' | 'selected' | 'rbf' | 'accelerated'; context?: 'projected' | 'actual'; scene?: BlockScene; @@ -68,6 +59,7 @@ export default class TxView implements TransactionStripped { this.acc = tx.acc; this.rate = tx.rate; this.status = tx.status; + this.bigintFlags = tx.flags ? (BigInt(tx.flags) | (this.acc ? TransactionFlags.acceleration : 0n)): 0n; this.initialised = false; this.vertexArray = scene.vertexArray; @@ -195,77 +187,4 @@ export default class TxView implements TransactionStripped { this.dirty = false; return performance.now() + hoverTransitionTime; } - - getColor(): Color { - const rate = this.fee / this.vsize; // color by simple single-tx fee rate - const feeLevelIndex = feeLevels.findIndex((feeLvl) => Math.max(1, rate) < feeLvl) - 1; - const feeLevelColor = feeColors[feeLevelIndex] || feeColors[mempoolFeeColors.length - 1]; - // Normal mode - if (!this.scene?.highlightingEnabled) { - if (this.acc) { - return auditColors.accelerated; - } else { - return feeLevelColor; - } - return feeLevelColor; - } - // Block audit - switch(this.status) { - case 'censored': - return auditColors.censored; - case 'missing': - case 'sigop': - case 'rbf': - return marginalFeeColors[feeLevelIndex] || marginalFeeColors[mempoolFeeColors.length - 1]; - case 'fresh': - case 'freshcpfp': - return auditColors.missing; - case 'added': - return auditColors.added; - case 'selected': - return marginalFeeColors[feeLevelIndex] || marginalFeeColors[mempoolFeeColors.length - 1]; - case 'accelerated': - return auditColors.accelerated; - case 'found': - if (this.context === 'projected') { - return auditFeeColors[feeLevelIndex] || auditFeeColors[mempoolFeeColors.length - 1]; - } else { - return feeLevelColor; - } - default: - if (this.acc) { - return auditColors.accelerated; - } else { - return feeLevelColor; - } - } - } -} - -function hexToColor(hex: string): Color { - return { - r: parseInt(hex.slice(0, 2), 16) / 255, - g: parseInt(hex.slice(2, 4), 16) / 255, - b: parseInt(hex.slice(4, 6), 16) / 255, - a: 1 - }; -} - -function desaturate(color: Color, amount: number): Color { - const gray = (color.r + color.g + color.b) / 6; - return { - r: color.r + ((gray - color.r) * amount), - g: color.g + ((gray - color.g) * amount), - b: color.b + ((gray - color.b) * amount), - a: color.a, - }; -} - -function darken(color: Color, amount: number): Color { - return { - r: color.r * amount, - g: color.g * amount, - b: color.b * amount, - a: color.a, - } } diff --git a/frontend/src/app/components/block-overview-graph/utils.ts b/frontend/src/app/components/block-overview-graph/utils.ts new file mode 100644 index 000000000..9c800ad85 --- /dev/null +++ b/frontend/src/app/components/block-overview-graph/utils.ts @@ -0,0 +1,101 @@ +import { feeLevels, mempoolFeeColors } from '../../app.constants'; +import { Color } from './sprite-types'; +import TxView from './tx-view'; + +export function hexToColor(hex: string): Color { + return { + r: parseInt(hex.slice(0, 2), 16) / 255, + g: parseInt(hex.slice(2, 4), 16) / 255, + b: parseInt(hex.slice(4, 6), 16) / 255, + a: hex.length > 6 ? parseInt(hex.slice(6, 8), 16) / 255 : 1 + }; +} + +export function desaturate(color: Color, amount: number): Color { + const gray = (color.r + color.g + color.b) / 6; + return { + r: color.r + ((gray - color.r) * amount), + g: color.g + ((gray - color.g) * amount), + b: color.b + ((gray - color.b) * amount), + a: color.a, + }; +} + +export function darken(color: Color, amount: number): Color { + return { + r: color.r * amount, + g: color.g * amount, + b: color.b * amount, + a: color.a, + }; +} + +export function setOpacity(color: Color, opacity: number): Color { + return { + ...color, + a: opacity + }; +} + +// precomputed colors +export const defaultFeeColors = mempoolFeeColors.map(hexToColor); +export const defaultAuditFeeColors = defaultFeeColors.map((color) => darken(desaturate(color, 0.3), 0.9)); +export const defaultMarginalFeeColors = defaultFeeColors.map((color) => darken(desaturate(color, 0.8), 1.1)); +export const defaultAuditColors = { + censored: hexToColor('f344df'), + missing: darken(desaturate(hexToColor('f344df'), 0.3), 0.7), + added: hexToColor('0099ff'), + selected: darken(desaturate(hexToColor('0099ff'), 0.3), 0.7), + accelerated: hexToColor('8F5FF6'), +}; + +export function defaultColorFunction( + tx: TxView, + feeColors: Color[] = defaultFeeColors, + auditFeeColors: Color[] = defaultAuditFeeColors, + marginalFeeColors: Color[] = defaultMarginalFeeColors, + auditColors: { [status: string]: Color } = defaultAuditColors +): Color { + const rate = tx.fee / tx.vsize; // color by simple single-tx fee rate + const feeLevelIndex = feeLevels.findIndex((feeLvl) => Math.max(1, rate) < feeLvl) - 1; + const feeLevelColor = feeColors[feeLevelIndex] || feeColors[mempoolFeeColors.length - 1]; + // Normal mode + if (!tx.scene?.highlightingEnabled) { + if (tx.acc) { + return auditColors.accelerated; + } else { + return feeLevelColor; + } + return feeLevelColor; + } + // Block audit + switch(tx.status) { + case 'censored': + return auditColors.censored; + case 'missing': + case 'sigop': + case 'rbf': + return marginalFeeColors[feeLevelIndex] || marginalFeeColors[mempoolFeeColors.length - 1]; + case 'fresh': + case 'freshcpfp': + return auditColors.missing; + case 'added': + return auditColors.added; + case 'selected': + return marginalFeeColors[feeLevelIndex] || marginalFeeColors[mempoolFeeColors.length - 1]; + case 'accelerated': + return auditColors.accelerated; + case 'found': + if (tx.context === 'projected') { + return auditFeeColors[feeLevelIndex] || auditFeeColors[mempoolFeeColors.length - 1]; + } else { + return feeLevelColor; + } + default: + if (tx.acc) { + return auditColors.accelerated; + } else { + return feeLevelColor; + } + } +} \ No newline at end of file diff --git a/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.html b/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.html index a53cfdc9c..8fb687ebd 100644 --- a/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.html +++ b/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.html @@ -28,7 +28,7 @@ - + Effective fee rate Accelerated fee rate @@ -55,9 +55,13 @@ Added Marginal fee rate Conflicting - Accelerated + Accelerated + + + Accelerated +
diff --git a/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.scss b/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.scss index 00f6d94f7..81a79eb67 100644 --- a/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.scss +++ b/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.scss @@ -11,6 +11,7 @@ text-align: left; min-width: 320px; pointer-events: none; + z-index: 11; &.clickable { pointer-events: all; @@ -19,4 +20,17 @@ .td-width { padding-right: 10px; +} + +.badge.badge-accelerated { + background-color: #653b9c; + box-shadow: #ad7de57f 0px 0px 12px -2px; + color: white; + animation: acceleratePulse 1s infinite; +} + +@keyframes acceleratePulse { + 0% { background-color: #653b9c; box-shadow: #ad7de57f 0px 0px 12px -2px; } + 50% { background-color: #8457bb; box-shadow: #ad7de5 0px 0px 18px -2px;} + 100% { background-color: #653b9c; box-shadow: #ad7de57f 0px 0px 12px -2px; } } \ No newline at end of file diff --git a/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.ts b/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.ts index 65d0f984c..6b23276c8 100644 --- a/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.ts +++ b/frontend/src/app/components/block-overview-tooltip/block-overview-tooltip.component.ts @@ -1,7 +1,8 @@ import { Component, ElementRef, ViewChild, Input, OnChanges, ChangeDetectionStrategy } from '@angular/core'; -import { TransactionStripped } from '../../interfaces/websocket.interface'; import { Position } from '../../components/block-overview-graph/sprite-types.js'; import { Price } from '../../services/price.service'; +import { TransactionStripped } from '../../interfaces/node-api.interface.js'; +import { TransactionFlags } from '../../shared/filters.utils'; @Component({ selector: 'app-block-overview-tooltip', @@ -22,6 +23,7 @@ export class BlockOverviewTooltipComponent implements OnChanges { feeRate = 0; effectiveRate; acceleration; + hasEffectiveRate: boolean = false; tooltipPosition: Position = { x: 0, y: 0 }; @@ -55,6 +57,8 @@ export class BlockOverviewTooltipComponent implements OnChanges { this.feeRate = this.fee / this.vsize; this.effectiveRate = tx.rate; this.acceleration = tx.acc; + this.hasEffectiveRate = Math.abs((this.fee / this.vsize) - this.effectiveRate) > 0.05 + || (tx.bigintFlags && (tx.bigintFlags & (TransactionFlags.cpfp_child | TransactionFlags.cpfp_parent)) > 0n); } } } diff --git a/frontend/src/app/components/block-rewards-graph/block-rewards-graph.component.ts b/frontend/src/app/components/block-rewards-graph/block-rewards-graph.component.ts index 505da17a5..9c987fb57 100644 --- a/frontend/src/app/components/block-rewards-graph/block-rewards-graph.component.ts +++ b/frontend/src/app/components/block-rewards-graph/block-rewards-graph.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, OnInit } from '@angular/core'; -import { EChartsOption, graphic } from 'echarts'; +import { echarts, EChartsOption } from '../../graphs/echarts'; import { Observable } from 'rxjs'; import { map, share, startWith, switchMap, tap } from 'rxjs/operators'; import { ApiService } from '../../services/api.service'; @@ -123,11 +123,11 @@ export class BlockRewardsGraphComponent implements OnInit { title: title, animation: false, color: [ - new graphic.LinearGradient(0, 0, 0, 1, [ + new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: '#FDD835' }, { offset: 1, color: '#FB8C00' }, ]), - new graphic.LinearGradient(0, 0, 0, 1, [ + new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: '#C0CA33' }, { offset: 1, color: '#1B5E20' }, ]), diff --git a/frontend/src/app/components/block-sizes-weights-graph/block-sizes-weights-graph.component.ts b/frontend/src/app/components/block-sizes-weights-graph/block-sizes-weights-graph.component.ts index e42c6a8df..5d01e48e9 100644 --- a/frontend/src/app/components/block-sizes-weights-graph/block-sizes-weights-graph.component.ts +++ b/frontend/src/app/components/block-sizes-weights-graph/block-sizes-weights-graph.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, OnInit, HostBinding } from '@angular/core'; -import { EChartsOption} from 'echarts'; +import { EChartsOption} from '../../graphs/echarts'; import { Observable } from 'rxjs'; import { map, share, startWith, switchMap, tap } from 'rxjs/operators'; import { ApiService } from '../../services/api.service'; diff --git a/frontend/src/app/components/block-view/block-view.component.html b/frontend/src/app/components/block-view/block-view.component.html new file mode 100644 index 000000000..9a2ddf373 --- /dev/null +++ b/frontend/src/app/components/block-view/block-view.component.html @@ -0,0 +1,14 @@ +
+
+ +
+
diff --git a/frontend/src/app/components/block-view/block-view.component.scss b/frontend/src/app/components/block-view/block-view.component.scss new file mode 100644 index 000000000..782d416d8 --- /dev/null +++ b/frontend/src/app/components/block-view/block-view.component.scss @@ -0,0 +1,22 @@ +.block-wrapper { + width: 100vw; + height: 100vh; + background: #181b2d; +} + +.block-container { + flex-grow: 0; + flex-shrink: 0; + width: 100vw; + max-width: 100vh; + height: 100vh; + padding: 0; + margin: auto; + display: flex; + justify-content: center; + align-items: center; + + * { + flex-grow: 1; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/block-view/block-view.component.ts b/frontend/src/app/components/block-view/block-view.component.ts new file mode 100644 index 000000000..5c3b7719c --- /dev/null +++ b/frontend/src/app/components/block-view/block-view.component.ts @@ -0,0 +1,180 @@ +import { Component, OnInit, OnDestroy, ViewChild, HostListener } from '@angular/core'; +import { ActivatedRoute, ParamMap, Router } from '@angular/router'; +import { ElectrsApiService } from '../../services/electrs-api.service'; +import { switchMap, tap, catchError, shareReplay, filter } from 'rxjs/operators'; +import { of, Subscription } from 'rxjs'; +import { StateService } from '../../services/state.service'; +import { SeoService } from '../../services/seo.service'; +import { BlockExtended, TransactionStripped } from '../../interfaces/node-api.interface'; +import { ApiService } from '../../services/api.service'; +import { seoDescriptionNetwork } from '../../shared/common.utils'; +import { BlockOverviewGraphComponent } from '../block-overview-graph/block-overview-graph.component'; +import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe'; + +function bestFitResolution(min, max, n): number { + const target = (min + max) / 2; + let bestScore = Infinity; + let best = null; + for (let i = min; i <= max; i++) { + const remainder = (n % i); + if (remainder < bestScore || (remainder === bestScore && (Math.abs(i - target) < Math.abs(best - target)))) { + bestScore = remainder; + best = i; + } + } + return best; +} + +@Component({ + selector: 'app-block-view', + templateUrl: './block-view.component.html', + styleUrls: ['./block-view.component.scss'] +}) +export class BlockViewComponent implements OnInit, OnDestroy { + network = ''; + block: BlockExtended; + blockHeight: number; + blockHash: string; + rawId: string; + isLoadingBlock = true; + strippedTransactions: TransactionStripped[]; + isLoadingOverview = true; + autofit: boolean = false; + resolution: number = 80; + + overviewSubscription: Subscription; + networkChangedSubscription: Subscription; + queryParamsSubscription: Subscription; + + @ViewChild('blockGraph') blockGraph: BlockOverviewGraphComponent; + + constructor( + private route: ActivatedRoute, + private router: Router, + private electrsApiService: ElectrsApiService, + public stateService: StateService, + private seoService: SeoService, + private apiService: ApiService + ) { } + + ngOnInit(): void { + this.network = this.stateService.network; + + this.queryParamsSubscription = this.route.queryParams.subscribe((params) => { + this.autofit = params.autofit === 'true'; + if (this.autofit) { + this.onResize(); + } + }); + + const block$ = this.route.paramMap.pipe( + switchMap((params: ParamMap) => { + this.rawId = params.get('id') || ''; + + const blockHash: string = params.get('id') || ''; + this.block = undefined; + + let isBlockHeight = false; + if (/^[0-9]+$/.test(blockHash)) { + isBlockHeight = true; + } else { + this.blockHash = blockHash; + } + + this.isLoadingBlock = true; + this.isLoadingOverview = true; + + if (isBlockHeight) { + return this.electrsApiService.getBlockHashFromHeight$(parseInt(blockHash, 10)) + .pipe( + switchMap((hash) => { + if (hash) { + this.blockHash = hash; + return this.apiService.getBlock$(hash); + } else { + return null; + } + }), + catchError(() => { + return of(null); + }), + ); + } + return this.apiService.getBlock$(blockHash); + }), + filter((block: BlockExtended | void) => block != null), + tap((block: BlockExtended) => { + this.block = block; + this.blockHeight = block.height; + + this.seoService.setTitle($localize`:@@block.component.browser-title:Block ${block.height}:BLOCK_HEIGHT:: ${block.id}:BLOCK_ID:`); + if( this.stateService.network === 'liquid' || this.stateService.network === 'liquidtestnet' ) { + this.seoService.setDescription($localize`:@@meta.description.liquid.block:See size, weight, fee range, included transactions, and more for Liquid${seoDescriptionNetwork(this.stateService.network)} block ${block.height}:BLOCK_HEIGHT: (${block.id}:BLOCK_ID:).`); + } else { + this.seoService.setDescription($localize`:@@meta.description.bitcoin.block:See size, weight, fee range, included transactions, audit (expected v actual), and more for Bitcoin${seoDescriptionNetwork(this.stateService.network)} block ${block.height}:BLOCK_HEIGHT: (${block.id}:BLOCK_ID:).`); + } + this.isLoadingBlock = false; + this.isLoadingOverview = true; + }), + shareReplay(1) + ); + + this.overviewSubscription = block$.pipe( + switchMap((block) => this.apiService.getStrippedBlockTransactions$(block.id) + .pipe( + catchError(() => { + return of([]); + }), + switchMap((transactions) => { + return of(transactions); + }) + ) + ), + ) + .subscribe((transactions: TransactionStripped[]) => { + this.strippedTransactions = transactions; + this.isLoadingOverview = false; + if (this.blockGraph) { + this.blockGraph.destroy(); + this.blockGraph.setup(this.strippedTransactions); + } + }, + () => { + this.isLoadingOverview = false; + if (this.blockGraph) { + this.blockGraph.destroy(); + } + }); + + this.networkChangedSubscription = this.stateService.networkChanged$ + .subscribe((network) => this.network = network); + } + + onTxClick(event: { tx: TransactionStripped, keyModifier: boolean }): void { + const url = new RelativeUrlPipe(this.stateService).transform(`/tx/${event.tx.txid}`); + if (!event.keyModifier) { + this.router.navigate([url]); + } else { + window.open(url, '_blank'); + } + } + + @HostListener('window:resize', ['$event']) + onResize(): void { + if (this.autofit) { + this.resolution = bestFitResolution(64, 96, Math.min(window.innerWidth, window.innerHeight)); + } + } + + ngOnDestroy(): void { + if (this.overviewSubscription) { + this.overviewSubscription.unsubscribe(); + } + if (this.networkChangedSubscription) { + this.networkChangedSubscription.unsubscribe(); + } + if (this.queryParamsSubscription) { + this.queryParamsSubscription.unsubscribe(); + } + } +} diff --git a/frontend/src/app/components/block/block-preview.component.ts b/frontend/src/app/components/block/block-preview.component.ts index c4dfe40df..3e1d9b409 100644 --- a/frontend/src/app/components/block/block-preview.component.ts +++ b/frontend/src/app/components/block/block-preview.component.ts @@ -2,7 +2,7 @@ import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/co import { ActivatedRoute, ParamMap } from '@angular/router'; import { ElectrsApiService } from '../../services/electrs-api.service'; import { switchMap, tap, throttleTime, catchError, shareReplay, startWith, pairwise, filter } from 'rxjs/operators'; -import { of, Subscription, asyncScheduler } from 'rxjs'; +import { of, Subscription, asyncScheduler, forkJoin } from 'rxjs'; import { StateService } from '../../services/state.service'; import { SeoService } from '../../services/seo.service'; import { OpenGraphService } from '../../services/opengraph.service'; @@ -10,6 +10,7 @@ import { BlockExtended, TransactionStripped } from '../../interfaces/node-api.in import { ApiService } from '../../services/api.service'; import { seoDescriptionNetwork } from '../../shared/common.utils'; import { BlockOverviewGraphComponent } from '../../components/block-overview-graph/block-overview-graph.component'; +import { ServicesApiServices } from '../../services/services-api.service'; @Component({ selector: 'app-block-preview', @@ -42,7 +43,8 @@ export class BlockPreviewComponent implements OnInit, OnDestroy { public stateService: StateService, private seoService: SeoService, private openGraphService: OpenGraphService, - private apiService: ApiService + private apiService: ApiService, + private servicesApiService: ServicesApiServices, ) { } ngOnInit() { @@ -121,21 +123,37 @@ export class BlockPreviewComponent implements OnInit, OnDestroy { this.overviewSubscription = block$.pipe( startWith(null), pairwise(), - switchMap(([prevBlock, block]) => this.apiService.getStrippedBlockTransactions$(block.id) - .pipe( - catchError((err) => { - this.overviewError = err; - this.openGraphService.fail('block-viz-' + this.rawId); - return of([]); - }), - switchMap((transactions) => { - return of({ transactions, direction: 'down' }); - }) - ) + switchMap(([prevBlock, block]) => { + return forkJoin([ + this.apiService.getStrippedBlockTransactions$(block.id) + .pipe( + catchError((err) => { + this.overviewError = err; + this.openGraphService.fail('block-viz-' + this.rawId); + return of([]); + }), + switchMap((transactions) => { + return of(transactions); + }) + ), + this.stateService.env.ACCELERATOR === true && block.height > 819500 ? this.servicesApiService.getAccelerationHistory$({ blockHash: block.id }) : of([]) + ]); + } ), ) - .subscribe(({transactions, direction}: {transactions: TransactionStripped[], direction: string}) => { + .subscribe(([transactions, accelerations]) => { this.strippedTransactions = transactions; + + const acceleratedInBlock = {}; + for (const acc of accelerations) { + acceleratedInBlock[acc.txid] = acc; + } + for (const tx of transactions) { + if (acceleratedInBlock[tx.txid]) { + tx.acc = true; + } + } + this.isLoadingOverview = false; if (this.blockGraph) { this.blockGraph.destroy(); diff --git a/frontend/src/app/components/block/block.component.html b/frontend/src/app/components/block/block.component.html index e65905cd2..89699a68c 100644 --- a/frontend/src/app/components/block/block.component.html +++ b/frontend/src/app/components/block/block.component.html @@ -42,12 +42,12 @@ Hash - ‎{{ block.id | shortenString : 13 }} + ‎{{ block.id | shortenString : 13 }} Timestamp - + @@ -59,7 +59,7 @@ - Health + Health @@ -219,33 +221,39 @@
-

Expected Block beta

+

Expected Block

+ (txClickEvent)="onTxClick($event)" (txHoverEvent)="onTxHover($event)" [unavailable]="!isMobile && !showAudit" + [showFilters]="true" [excludeFilters]="['replacement']">
- + + +
-

Actual Block

+

Actual Block

+ (txClickEvent)="onTxClick($event)" (txHoverEvent)="onTxHover($event)" [unavailable]="isMobile && !showAudit" + [showFilters]="true" [excludeFilters]="['replacement']">
- + + +
@@ -262,7 +270,7 @@ Version - {{ block.version | decimal2hex }} Taproot + {{ block.version | decimal2hex }} Taproot Bits @@ -452,5 +460,24 @@ + + + + + + + + + + + + + + + + +
Total fees
Weight
Transactions
+
+

diff --git a/frontend/src/app/components/block/block.component.scss b/frontend/src/app/components/block/block.component.scss index c413b1fce..6deb2cb4b 100644 --- a/frontend/src/app/components/block/block.component.scss +++ b/frontend/src/app/components/block/block.component.scss @@ -57,11 +57,6 @@ text-align: left; } } - .info-link { - color: rgba(255, 255, 255, 0.4); - margin-left: 5px; - } - .difference { margin-left: 0.5em; diff --git a/frontend/src/app/components/block/block.component.ts b/frontend/src/app/components/block/block.component.ts index e226807e3..5bba24852 100644 --- a/frontend/src/app/components/block/block.component.ts +++ b/frontend/src/app/components/block/block.component.ts @@ -16,6 +16,7 @@ import { detectWebGL } from '../../shared/graphs.utils'; import { seoDescriptionNetwork } from '../../shared/common.utils'; import { PriceService, Price } from '../../services/price.service'; import { CacheService } from '../../services/cache.service'; +import { ServicesApiServices } from '../../services/services-api.service'; @Component({ selector: 'app-block', @@ -103,6 +104,7 @@ export class BlockComponent implements OnInit, OnDestroy { private apiService: ApiService, private priceService: PriceService, private cacheService: CacheService, + private servicesApiService: ServicesApiServices, ) { this.webGlEnabled = detectWebGL(); } @@ -166,7 +168,6 @@ export class BlockComponent implements OnInit, OnDestroy { 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; @@ -176,6 +177,7 @@ export class BlockComponent implements OnInit, OnDestroy { let isBlockHeight = false; if (/^[0-9]+$/.test(blockHash)) { isBlockHeight = true; + this.stateService.markBlock$.next({ blockHeight: parseInt(blockHash, 10)}); } else { this.blockHash = blockHash; } @@ -202,6 +204,7 @@ export class BlockComponent implements OnInit, OnDestroy { this.location.replaceState( this.router.createUrlTree([(this.network ? '/' + this.network : '') + '/block/', hash]).toString() ); + this.seoService.updateCanonical(this.location.path()); return this.apiService.getBlock$(hash).pipe( catchError((err) => { this.error = err; @@ -327,17 +330,28 @@ export class BlockComponent implements OnInit, OnDestroy { this.overviewError = err; return of(null); }) - ) + ), + this.stateService.env.ACCELERATOR === true && block.height > 819500 ? this.servicesApiService.getAccelerationHistory$({ blockHash: block.id }) : of([]) ]); }) ) - .subscribe(([transactions, blockAudit]) => { + .subscribe(([transactions, blockAudit, accelerations]) => { if (transactions) { this.strippedTransactions = transactions; } else { this.strippedTransactions = []; } + const acceleratedInBlock = {}; + for (const acc of accelerations) { + acceleratedInBlock[acc.txid] = acc; + } + for (const tx of transactions) { + if (acceleratedInBlock[tx.txid]) { + tx.acc = true; + } + } + this.blockAudit = null; if (transactions && blockAudit) { const inTemplate = {}; diff --git a/frontend/src/app/components/block/block.module.ts b/frontend/src/app/components/block/block.module.ts new file mode 100644 index 000000000..d6991c68a --- /dev/null +++ b/frontend/src/app/components/block/block.module.ts @@ -0,0 +1,43 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { BlockComponent } from './block.component'; +import { SharedModule } from '../../shared/shared.module'; + +const routes: Routes = [ + { + path: ':id', + component: BlockComponent, + data: { + ogImage: true + } + } +]; + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class BlockRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + BlockRoutingModule, + SharedModule, + ], + declarations: [ + BlockComponent, + ] +}) +export class BlockModule { } + + + + + + diff --git a/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.html b/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.html index 680beb006..e9f64b9b8 100644 --- a/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.html +++ b/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.html @@ -26,7 +26,7 @@
-   +
-   +
-
+
{{ block.extras.pool.name}} diff --git a/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.scss b/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.scss index 795e1f4df..c1cc6809d 100644 --- a/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.scss +++ b/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.scss @@ -166,7 +166,7 @@ opacity: 1; } .hide { - opacity: 0; + opacity: 0.4; pointer-events : none; } diff --git a/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.ts b/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.ts index ba066d10a..0da8ca7b5 100644 --- a/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.ts +++ b/frontend/src/app/components/blockchain-blocks/blockchain-blocks.component.ts @@ -79,7 +79,7 @@ export class BlockchainBlocksComponent implements OnInit, OnChanges, OnDestroy { } enabledMiningInfoIfNeeded(url) { - this.showMiningInfo = url.indexOf('/mining') !== -1; + this.showMiningInfo = url.includes('/mining') || url.includes('/acceleration'); this.cd.markForCheck(); // Need to update the view asap } diff --git a/frontend/src/app/components/blockchain/blockchain.component.html b/frontend/src/app/components/blockchain/blockchain.component.html index 2c3f1ad8c..5f625e4b3 100644 --- a/frontend/src/app/components/blockchain/blockchain.component.html +++ b/frontend/src/app/components/blockchain/blockchain.component.html @@ -1,5 +1,5 @@
-
+
diff --git a/frontend/src/app/components/blockchain/blockchain.component.scss b/frontend/src/app/components/blockchain/blockchain.component.scss index 135a8b842..eacd16118 100644 --- a/frontend/src/app/components/blockchain/blockchain.component.scss +++ b/frontend/src/app/components/blockchain/blockchain.component.scss @@ -26,15 +26,7 @@ position: absolute; left: 0; top: 75px; - --divider-offset: 50vw; - --mempool-offset: 0px; - transform: translateX(calc(var(--divider-offset) + var(--mempool-offset))); -} - -.blockchain-wrapper.time-ltr { - .position-container { - transform: translateX(calc(100vw - var(--divider-offset) - var(--mempool-offset))); - } + transform: translateX(1280px); } .black-background { diff --git a/frontend/src/app/components/blockchain/blockchain.component.ts b/frontend/src/app/components/blockchain/blockchain.component.ts index 56b7c39e6..2293b9479 100644 --- a/frontend/src/app/components/blockchain/blockchain.component.ts +++ b/frontend/src/app/components/blockchain/blockchain.component.ts @@ -1,4 +1,4 @@ -import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, Input, Output, EventEmitter, HostListener, ChangeDetectorRef, OnChanges, SimpleChanges } from '@angular/core'; +import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, Input, Output, EventEmitter, ChangeDetectorRef, OnChanges, SimpleChanges } from '@angular/core'; import { firstValueFrom, Subscription } from 'rxjs'; import { StateService } from '../../services/state.service'; @@ -27,8 +27,11 @@ export class BlockchainComponent implements OnInit, OnDestroy, OnChanges { loadingTip: boolean = true; connected: boolean = true; - dividerOffset: number = 0; - mempoolOffset: number = 0; + dividerOffset: number | null = null; + mempoolOffset: number | null = null; + positionStyle = { + transform: "translateX(1280px)", + }; constructor( public stateService: StateService, @@ -40,6 +43,7 @@ export class BlockchainComponent implements OnInit, OnDestroy, OnChanges { this.network = this.stateService.network; this.timeLtrSubscription = this.stateService.timeLtr.subscribe((ltr) => { this.timeLtr = !!ltr; + this.updateStyle(); }); this.connectionStateSubscription = this.stateService.connectionState$.subscribe(state => { this.connected = (state === 2); @@ -63,29 +67,47 @@ export class BlockchainComponent implements OnInit, OnDestroy, OnChanges { const prevOffset = this.mempoolOffset; this.mempoolOffset = 0; this.mempoolOffsetChange.emit(0); + this.updateStyle(); setTimeout(() => { this.ltrTransitionEnabled = true; this.flipping = true; this.stateService.timeLtr.next(!this.timeLtr); + this.cd.markForCheck(); setTimeout(() => { this.ltrTransitionEnabled = false; this.flipping = false; this.mempoolOffset = prevOffset; - this.mempoolOffsetChange.emit(this.mempoolOffset); + this.mempoolOffsetChange.emit((this.mempoolOffset || 0)); + this.updateStyle(); + this.cd.markForCheck(); }, 1000); }, 0); - this.cd.markForCheck(); } onMempoolWidthChange(width): void { if (this.flipping) { return; } - this.mempoolOffset = Math.max(0, width - this.dividerOffset); - this.cd.markForCheck(); + this.mempoolOffset = Math.max(0, width - (this.dividerOffset || 0)); + this.updateStyle(); this.mempoolOffsetChange.emit(this.mempoolOffset); } + updateStyle(): void { + if (this.dividerOffset == null || this.mempoolOffset == null) { + return; + } + const oldTransform = this.positionStyle.transform; + this.positionStyle = this.timeLtr ? { + transform: `translateX(calc(100vw - ${this.dividerOffset + this.mempoolOffset}px)`, + } : { + transform: `translateX(${this.dividerOffset + this.mempoolOffset}px)`, + }; + if (oldTransform !== this.positionStyle.transform) { + this.cd.detectChanges(); + } + } + ngOnChanges(changes: SimpleChanges): void { if (changes.containerWidth) { this.onResize(); @@ -107,6 +129,6 @@ export class BlockchainComponent implements OnInit, OnDestroy, OnChanges { this.dividerOffset = width * 0.95; } } - this.cd.markForCheck(); + this.updateStyle(); } } diff --git a/frontend/src/app/components/blocks-list/blocks-list.component.html b/frontend/src/app/components/blocks-list/blocks-list.component.html index 39fbb95e0..fd171720f 100644 --- a/frontend/src/app/components/blocks-list/blocks-list.component.html +++ b/frontend/src/app/components/blocks-list/blocks-list.component.html @@ -1,6 +1,6 @@ -
+

Blocks

@@ -9,28 +9,28 @@
- - + - - + - - - - + + - - + + - - - - - - - - - - - - - - - - - - diff --git a/frontend/src/app/components/blocks-list/blocks-list.component.ts b/frontend/src/app/components/blocks-list/blocks-list.component.ts index aa361d9dc..196a0341e 100644 --- a/frontend/src/app/components/blocks-list/blocks-list.component.ts +++ b/frontend/src/app/components/blocks-list/blocks-list.component.ts @@ -19,6 +19,7 @@ export class BlocksList implements OnInit { blocks$: Observable = undefined; + isMempoolModule = false; indexingAvailable = false; auditAvailable = false; isLoading = true; @@ -39,6 +40,7 @@ export class BlocksList implements OnInit { private cd: ChangeDetectorRef, private seoService: SeoService, ) { + this.isMempoolModule = this.stateService.env.BASE_MODULE === 'mempool'; } ngOnInit(): void { @@ -53,7 +55,9 @@ export class BlocksList implements OnInit { this.skeletonLines = this.widget === true ? [...Array(6).keys()] : [...Array(15).keys()]; this.paginationMaxSize = window.matchMedia('(max-width: 670px)').matches ? 3 : 5; - this.seoService.setTitle($localize`:@@meta.title.blocks-list:Blocks`); + if (!this.widget) { + this.seoService.setTitle($localize`:@@m8a7b4bd44c0ac71b2e72de0398b303257f7d2f54:Blocks`); + } if( this.stateService.network==='liquid'||this.stateService.network==='liquidtestnet' ) { this.seoService.setDescription($localize`:@@meta.description.liquid.blocks:See the most recent Liquid${seoDescriptionNetwork(this.stateService.network)} blocks along with basic stats such as block height, block size, and more.`); } else { @@ -75,11 +79,10 @@ export class BlocksList implements OnInit { this.lastBlockHeight = Math.max(...blocks.map(o => o.height)); }), map(blocks => { - if (this.indexingAvailable) { + if (this.stateService.env.BASE_MODULE === 'mempool') { for (const block of blocks) { // @ts-ignore: Need to add an extra field for the template - block.extras.pool.logo = `/resources/mining-pools/` + - block.extras.pool.slug + '.svg'; + block.extras.pool.logo = `/resources/mining-pools/` + block.extras.pool.slug + '.svg'; } } if (this.widget) { @@ -110,7 +113,7 @@ export class BlocksList implements OnInit { } if (blocks[1]) { this.blocksCount = Math.max(this.blocksCount, blocks[1][0].height) + 1; - if (this.stateService.env.MINING_DASHBOARD) { + if (this.isMempoolModule) { // @ts-ignore: Need to add an extra field for the template blocks[1][0].extras.pool.logo = `/resources/mining-pools/` + blocks[1][0].extras.pool.slug + '.svg'; @@ -121,9 +124,11 @@ export class BlocksList implements OnInit { return acc; }, []), switchMap((blocks) => { - blocks.forEach(block => { - block.extras.feeDelta = block.extras.expectedFees ? (block.extras.totalFees - block.extras.expectedFees) / block.extras.expectedFees : 0; - }); + if (this.isMempoolModule && this.auditAvailable) { + blocks.forEach(block => { + block.extras.feeDelta = block.extras.expectedFees ? (block.extras.totalFees - block.extras.expectedFees) / block.extras.expectedFees : 0; + }); + } return of(blocks); }) ); diff --git a/frontend/src/app/components/calculator/calculator.component.html b/frontend/src/app/components/calculator/calculator.component.html index bdbfdd0cd..e4ade67d2 100644 --- a/frontend/src/app/components/calculator/calculator.component.html +++ b/frontend/src/app/components/calculator/calculator.component.html @@ -1,6 +1,6 @@
-

Calculator

+

Calculator

@@ -26,7 +26,7 @@
- sats + sats
@@ -41,7 +41,7 @@
- sats + sats
diff --git a/frontend/src/app/components/clock/clock.component.html b/frontend/src/app/components/clock/clock.component.html index bdddef730..376d72bfc 100644 --- a/frontend/src/app/components/clock/clock.component.html +++ b/frontend/src/app/components/clock/clock.component.html @@ -38,36 +38,35 @@
-

fiat price

+

Price

-

priority rate

+

High Priority

-

block size

+

Size

- - {{ i }} transaction - {{ i }} transactions + {{ blocks[blockIndex].tx_count | number }} + Transactions

-

memory usage

+

Memory Usage

{{ mempoolInfo.size | number }}

-

unconfirmed

+

Unconfirmed

diff --git a/frontend/src/app/components/clock/clock.component.scss b/frontend/src/app/components/clock/clock.component.scss index 64929aa38..34aadcd74 100644 --- a/frontend/src/app/components/clock/clock.component.scss +++ b/frontend/src/app/components/clock/clock.component.scss @@ -63,6 +63,7 @@ .label { font-size: calc(0.04 * var(--clock-width)); line-height: calc(0.05 * var(--clock-width)); + text-transform: lowercase; } &.top { diff --git a/frontend/src/app/components/difficulty-mining/difficulty-mining.component.html b/frontend/src/app/components/difficulty-mining/difficulty-mining.component.html index 18e4830c7..1461b0c59 100644 --- a/frontend/src/app/components/difficulty-mining/difficulty-mining.component.html +++ b/frontend/src/app/components/difficulty-mining/difficulty-mining.component.html @@ -14,7 +14,7 @@
Estimate
-
+
@@ -24,9 +24,6 @@ {{ epochData.change | absolute | number: '1.2-2' }} %
- -
-
Previous: @@ -47,20 +44,30 @@
-
Next Halving
-
- - {{ i }} blocks - {{ i }} block +
Next Halving
+
+ {{ timeUntilHalving | date }} +
+ +
+ +
+ +
+
+
-
-
+ + + {{ i }} blocks + {{ i }} block + +
diff --git a/frontend/src/app/components/difficulty-mining/difficulty-mining.component.ts b/frontend/src/app/components/difficulty-mining/difficulty-mining.component.ts index c23d7d4b9..c650e2c02 100644 --- a/frontend/src/app/components/difficulty-mining/difficulty-mining.component.ts +++ b/frontend/src/app/components/difficulty-mining/difficulty-mining.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; -import { combineLatest, Observable, timer } from 'rxjs'; -import { map, switchMap } from 'rxjs/operators'; +import { combineLatest, Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; import { StateService } from '../../services/state.service'; interface EpochProgress { @@ -15,6 +15,8 @@ interface EpochProgress { previousRetarget: number; blocksUntilHalving: number; timeUntilHalving: number; + timeAvg: number; + adjustedTimeAvg: number; } @Component({ @@ -26,6 +28,9 @@ interface EpochProgress { export class DifficultyMiningComponent implements OnInit { isLoadingWebSocket$: Observable; difficultyEpoch$: Observable; + blocksUntilHalving: number | null = null; + timeUntilHalving = 0; + now = new Date().getTime(); @Input() showProgress = true; @Input() showHalving = false; @@ -64,8 +69,9 @@ export class DifficultyMiningComponent implements OnInit { colorPreviousAdjustments = '#ffffff66'; } - const blocksUntilHalving = 210000 - (maxHeight % 210000); - const timeUntilHalving = new Date().getTime() + (blocksUntilHalving * 600000); + this.blocksUntilHalving = 210000 - (maxHeight % 210000); + this.timeUntilHalving = new Date().getTime() + (this.blocksUntilHalving * 600000); + this.now = new Date().getTime(); const data = { base: `${da.progressPercent.toFixed(2)}%`, @@ -77,8 +83,10 @@ export class DifficultyMiningComponent implements OnInit { newDifficultyHeight: da.nextRetargetHeight, estimatedRetargetDate: da.estimatedRetargetDate, previousRetarget: da.previousRetarget, - blocksUntilHalving, - timeUntilHalving, + blocksUntilHalving: this.blocksUntilHalving, + timeUntilHalving: this.timeUntilHalving, + timeAvg: da.timeAvg, + adjustedTimeAvg: da.adjustedTimeAvg, }; return data; }) diff --git a/frontend/src/app/components/difficulty/difficulty.component.html b/frontend/src/app/components/difficulty/difficulty.component.html index f08ea06f5..8011c7e6f 100644 --- a/frontend/src/app/components/difficulty/difficulty.component.html +++ b/frontend/src/app/components/difficulty/difficulty.component.html @@ -42,7 +42,7 @@
Average block time
-
+
@@ -52,9 +52,6 @@ {{ epochData.change | absolute | number: '1.2-2' }} %
- -
-
Previous: diff --git a/frontend/src/app/components/difficulty/difficulty.component.ts b/frontend/src/app/components/difficulty/difficulty.component.ts index 7f305416f..d37667312 100644 --- a/frontend/src/app/components/difficulty/difficulty.component.ts +++ b/frontend/src/app/components/difficulty/difficulty.component.ts @@ -19,6 +19,7 @@ interface EpochProgress { blocksUntilHalving: number; timeUntilHalving: number; timeAvg: number; + adjustedTimeAvg: number; } type BlockStatus = 'mined' | 'behind' | 'ahead' | 'next' | 'remaining'; @@ -153,6 +154,7 @@ export class DifficultyComponent implements OnInit { blocksUntilHalving, timeUntilHalving, timeAvg: da.timeAvg, + adjustedTimeAvg: da.adjustedTimeAvg, }; return data; }) @@ -194,7 +196,7 @@ export class DifficultyComponent implements OnInit { @HostListener('pointerdown', ['$event']) onPointerDown(event): void { - if (this.epochSvgElement.nativeElement?.contains(event.target)) { + if (this.epochSvgElement?.nativeElement?.contains(event.target)) { this.onPointerMove(event); event.preventDefault(); } @@ -202,7 +204,7 @@ export class DifficultyComponent implements OnInit { @HostListener('pointermove', ['$event']) onPointerMove(event): void { - if (this.epochSvgElement.nativeElement?.contains(event.target)) { + if (this.epochSvgElement?.nativeElement?.contains(event.target)) { this.tooltipPosition = { x: event.clientX, y: event.clientY }; this.cd.markForCheck(); } diff --git a/frontend/src/app/components/eight-blocks/eight-blocks.component.html b/frontend/src/app/components/eight-blocks/eight-blocks.component.html new file mode 100644 index 000000000..59390c953 --- /dev/null +++ b/frontend/src/app/components/eight-blocks/eight-blocks.component.html @@ -0,0 +1,24 @@ +
+ +
+
+ +
+

{{ blockInfo[i].height }}

+

by {{ blockInfo[i].extras.pool.name || 'Unknown' }}

+
+
+
+
+
\ No newline at end of file diff --git a/frontend/src/app/components/eight-blocks/eight-blocks.component.scss b/frontend/src/app/components/eight-blocks/eight-blocks.component.scss new file mode 100644 index 000000000..6d2c9931c --- /dev/null +++ b/frontend/src/app/components/eight-blocks/eight-blocks.component.scss @@ -0,0 +1,69 @@ +.blocks { + width: 100%; + height: 100%; + min-width: 100vw; + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: flex-start; + align-items: flex-start; + align-content: flex-start; + + &.wrap { + flex-wrap: wrap; + } + + .block-wrapper { + flex-grow: 0; + flex-shrink: 0; + position: relative; + --block-width: 1080px; + + .info { + position: absolute; + left: 8%; + top: 8%; + right: 8%; + bottom: 8%; + height: 84%; + width: 84%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-weight: 700; + font-size: calc(var(--block-width) * 0.03); + text-shadow: 0 0 calc(var(--block-width) * 0.05) black; + + h1 { + font-size: 6em; + line-height: 1; + margin-bottom: calc(var(--block-width) * 0.03); + } + h2 { + font-size: 1.8em; + line-height: 1; + margin-bottom: calc(var(--block-width) * 0.03); + } + + .hash { + font-family: monospace; + word-wrap: break-word; + font-size: 1.4em; + line-height: 1; + margin-bottom: calc(var(--block-width) * 0.03); + } + + .mined-by { + position: absolute; + bottom: 0; + margin: auto; + text-align: center; + } + } + } + + .block-container { + overflow: hidden; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/eight-blocks/eight-blocks.component.ts b/frontend/src/app/components/eight-blocks/eight-blocks.component.ts new file mode 100644 index 000000000..96ab4dee9 --- /dev/null +++ b/frontend/src/app/components/eight-blocks/eight-blocks.component.ts @@ -0,0 +1,253 @@ +import { Component, OnInit, OnDestroy, ViewChildren, QueryList } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { catchError, startWith } from 'rxjs/operators'; +import { Subject, Subscription, of } from 'rxjs'; +import { StateService } from '../../services/state.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 '../block-overview-graph/block-overview-graph.component'; +import { detectWebGL } from '../../shared/graphs.utils'; +import { animate, style, transition, trigger } from '@angular/animations'; +import { BytesPipe } from '../../shared/pipes/bytes-pipe/bytes.pipe'; + +function bestFitResolution(min, max, n): number { + const target = (min + max) / 2; + let bestScore = Infinity; + let best = null; + for (let i = min; i <= max; i++) { + const remainder = (n % i); + if (remainder < bestScore || (remainder === bestScore && (Math.abs(i - target) < Math.abs(best - target)))) { + bestScore = remainder; + best = i; + } + } + return best; +} + +interface BlockInfo extends BlockExtended { + timeString: string; +} + +@Component({ + selector: 'app-eight-blocks', + templateUrl: './eight-blocks.component.html', + styleUrls: ['./eight-blocks.component.scss'], + animations: [ + trigger('infoChange', [ + transition(':enter', [ + style({ opacity: 0 }), + animate('1000ms', style({ opacity: 1 })), + ]), + transition(':leave', [ + animate('1000ms 500ms', style({ opacity: 0 })) + ]) + ]), + ], +}) +export class EightBlocksComponent implements OnInit, OnDestroy { + network = ''; + latestBlocks: BlockExtended[] = []; + isLoadingTransactions = true; + strippedTransactions: { [height: number]: TransactionStripped[] } = {}; + webGlEnabled = true; + hoverTx: string | null = null; + + blocksSubscription: Subscription; + cacheBlocksSubscription: Subscription; + networkChangedSubscription: Subscription; + queryParamsSubscription: Subscription; + graphChangeSubscription: Subscription; + + numBlocks: number = 8; + blockIndices: number[] = [...Array(8).keys()]; + autofit: boolean = false; + padding: number = 0; + wrapBlocks: boolean = false; + blockWidth: number = 1080; + animationDuration: number = 2000; + animationOffset: number = 0; + stagger: number = 0; + testing: boolean = true; + testHeight: number = 800000; + testShiftTimeout: number; + + showInfo: boolean = true; + blockInfo: BlockInfo[] = []; + + wrapperStyle = { + '--block-width': '1080px', + width: '1080px', + maxWidth: '1080px', + padding: '', + }; + containerStyle = {}; + resolution: number = 86; + + @ViewChildren('blockGraph') blockGraphs: QueryList; + + constructor( + private route: ActivatedRoute, + private router: Router, + public stateService: StateService, + private websocketService: WebsocketService, + private apiService: ApiService, + private bytesPipe: BytesPipe, + ) { + this.webGlEnabled = detectWebGL(); + } + + ngOnInit(): void { + this.websocketService.want(['blocks']); + this.network = this.stateService.network; + + this.queryParamsSubscription = this.route.queryParams.subscribe((params) => { + this.numBlocks = Number.isInteger(Number(params.numBlocks)) ? Number(params.numBlocks) : 8; + this.blockIndices = [...Array(this.numBlocks).keys()]; + this.autofit = params.autofit !== 'false'; + this.padding = Number.isInteger(Number(params.padding)) ? Number(params.padding) : 10; + this.blockWidth = Number.isInteger(Number(params.blockWidth)) ? Number(params.blockWidth) : 540; + this.wrapBlocks = params.wrap !== 'false'; + this.stagger = Number.isInteger(Number(params.stagger)) ? Number(params.stagger) : 0; + this.animationDuration = Number.isInteger(Number(params.animationDuration)) ? Number(params.animationDuration) : 2000; + this.animationOffset = this.padding * 2; + + if (this.autofit) { + this.resolution = bestFitResolution(76, 96, this.blockWidth - this.padding * 2); + } else { + this.resolution = 86; + } + + this.wrapperStyle = { + '--block-width': this.blockWidth + 'px', + width: this.blockWidth + 'px', + maxWidth: this.blockWidth + 'px', + padding: (this.padding || 0) +'px 0px', + }; + + if (params.test === 'true') { + if (this.blocksSubscription) { + this.blocksSubscription.unsubscribe(); + } + this.blocksSubscription = (new Subject()).subscribe((blocks) => { + this.handleNewBlock(blocks.slice(0, this.numBlocks)); + }); + this.shiftTestBlocks(); + } else if (!this.blocksSubscription) { + this.blocksSubscription = this.stateService.blocks$ + .subscribe((blocks) => { + this.handleNewBlock(blocks.slice(0, this.numBlocks)); + }); + } + }); + + this.setupBlockGraphs(); + + this.networkChangedSubscription = this.stateService.networkChanged$ + .subscribe((network) => this.network = network); + } + + ngAfterViewInit(): void { + this.graphChangeSubscription = this.blockGraphs.changes.pipe(startWith(null)).subscribe(() => { + this.setupBlockGraphs(); + }); + } + + ngOnDestroy(): void { + this.stateService.markBlock$.next({}); + if (this.blocksSubscription) { + this.blocksSubscription?.unsubscribe(); + } + this.cacheBlocksSubscription?.unsubscribe(); + this.networkChangedSubscription?.unsubscribe(); + this.queryParamsSubscription?.unsubscribe(); + } + + shiftTestBlocks(): void { + const sub = this.apiService.getBlocks$(this.testHeight).subscribe(result => { + sub.unsubscribe(); + this.handleNewBlock(result.slice(0, this.numBlocks)); + this.testHeight++; + clearTimeout(this.testShiftTimeout); + this.testShiftTimeout = window.setTimeout(() => { this.shiftTestBlocks(); }, 10000); + }); + } + + async handleNewBlock(blocks: BlockExtended[]): Promise { + const readyPromises: Promise[] = []; + const previousBlocks = this.latestBlocks; + const newHeights = {}; + this.latestBlocks = blocks; + for (const block of blocks) { + newHeights[block.height] = true; + if (!this.strippedTransactions[block.height]) { + readyPromises.push(new Promise((resolve) => { + const subscription = this.apiService.getStrippedBlockTransactions$(block.id).pipe( + catchError(() => { + return of([]); + }), + ).subscribe((transactions) => { + this.strippedTransactions[block.height] = transactions; + subscription.unsubscribe(); + resolve(transactions); + }); + })); + } + } + await Promise.allSettled(readyPromises); + this.updateBlockGraphs(blocks); + + // free up old transactions + previousBlocks.forEach(block => { + if (!newHeights[block.height]) { + delete this.strippedTransactions[block.height]; + } + }); + } + + updateBlockGraphs(blocks): void { + const startTime = performance.now() + 1000 - (this.stagger < 0 ? this.stagger * 8 : 0); + if (this.blockGraphs) { + this.blockGraphs.forEach((graph, index) => { + graph.replace(this.strippedTransactions[blocks?.[index]?.height] || [], 'right', false, startTime + (this.stagger * index)); + }); + } + this.showInfo = false; + setTimeout(() => { + this.blockInfo = blocks.map(block => { + return { + ...block, + timeString: (new Date(block.timestamp * 1000)).toLocaleTimeString(), + }; + }); + this.showInfo = true; + }, 1600); // Should match the animation time. + } + + setupBlockGraphs(): void { + if (this.blockGraphs) { + this.blockGraphs.forEach((graph, index) => { + graph.destroy(); + graph.setup(this.strippedTransactions[this.latestBlocks?.[index]?.height] || []); + }); + } + } + + onTxClick(event: { tx: TransactionStripped, keyModifier: boolean }): void { + const url = new RelativeUrlPipe(this.stateService).transform(`/tx/${event.tx.txid}`); + if (!event.keyModifier) { + this.router.navigate([url]); + } else { + window.open(url, '_blank'); + } + } + + onTxHover(txid: string): void { + if (txid && txid.length) { + this.hoverTx = txid; + } else { + this.hoverTx = null; + } + } +} diff --git a/frontend/src/app/components/fee-distribution-graph/fee-distribution-graph.component.scss b/frontend/src/app/components/fee-distribution-graph/fee-distribution-graph.component.scss new file mode 100644 index 000000000..e7150a720 --- /dev/null +++ b/frontend/src/app/components/fee-distribution-graph/fee-distribution-graph.component.scss @@ -0,0 +1,3 @@ +.fee-distribution-chart { + margin-top: 0.75rem; +} \ No newline at end of file diff --git a/frontend/src/app/components/fee-distribution-graph/fee-distribution-graph.component.ts b/frontend/src/app/components/fee-distribution-graph/fee-distribution-graph.component.ts index 010466952..178d87897 100644 --- a/frontend/src/app/components/fee-distribution-graph/fee-distribution-graph.component.ts +++ b/frontend/src/app/components/fee-distribution-graph/fee-distribution-graph.component.ts @@ -1,4 +1,4 @@ -import { OnChanges, OnDestroy } from '@angular/core'; +import { HostListener, OnChanges, OnDestroy } from '@angular/core'; import { Component, Input, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { TransactionStripped } from '../../interfaces/websocket.interface'; import { StateService } from '../../services/state.service'; @@ -9,6 +9,7 @@ import { Subscription } from 'rxjs'; @Component({ selector: 'app-fee-distribution-graph', templateUrl: './fee-distribution-graph.component.html', + styleUrls: ['./fee-distribution-graph.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class FeeDistributionGraphComponent implements OnInit, OnChanges, OnDestroy { @@ -25,6 +26,7 @@ export class FeeDistributionGraphComponent implements OnInit, OnChanges, OnDestr simple: boolean = false; data: number[][]; labelInterval: number = 50; + smallScreen: boolean = window.innerWidth < 450; rateUnitSub: Subscription; weightMode: boolean = false; @@ -95,9 +97,9 @@ export class FeeDistributionGraphComponent implements OnInit, OnChanges, OnDestr this.mempoolVsizeFeesOptions = { grid: { height: '210', - right: '20', + right: this.smallScreen ? '10' : '20', top: '22', - left: '40', + left: this.smallScreen ? '10' : '40', }, xAxis: { type: 'category', @@ -131,16 +133,17 @@ export class FeeDistributionGraphComponent implements OnInit, OnChanges, OnDestr } }, axisLabel: { - show: true, + show: !this.smallScreen, formatter: (value: number): string => { const unitValue = this.weightMode ? value / 4 : value; const selectedPowerOfTen = selectPowerOfTen(unitValue); - const newVal = Math.round(unitValue / selectedPowerOfTen.divider); + const scaledValue = unitValue / selectedPowerOfTen.divider; + const newVal = scaledValue >= 100 ? Math.round(scaledValue) : scaledValue.toPrecision(3); return `${newVal}${selectedPowerOfTen.unit}`; }, }, axisTick: { - show: true, + show: !this.smallScreen, } }, series: [{ @@ -151,11 +154,13 @@ export class FeeDistributionGraphComponent implements OnInit, OnChanges, OnDestr position: 'top', color: '#ffffff', textShadowBlur: 0, + fontSize: this.smallScreen ? 10 : 12, formatter: (label: { data: number[] }): string => { const value = label.data[1]; const unitValue = this.weightMode ? value / 4 : value; const selectedPowerOfTen = selectPowerOfTen(unitValue); - const newVal = Math.round(unitValue / selectedPowerOfTen.divider); + const scaledValue = unitValue / selectedPowerOfTen.divider; + const newVal = scaledValue >= 100 ? Math.round(scaledValue) : scaledValue.toPrecision(3); return `${newVal}${selectedPowerOfTen.unit}`; } }, @@ -179,6 +184,16 @@ export class FeeDistributionGraphComponent implements OnInit, OnChanges, OnDestr }; } + @HostListener('window:resize', ['$event']) + onResize(): void { + const isSmallScreen = window.innerWidth < 450; + if (this.smallScreen !== isSmallScreen) { + this.smallScreen = isSmallScreen; + this.prepareChart(); + this.mountChart(); + } + } + ngOnDestroy(): void { this.rateUnitSub.unsubscribe(); } diff --git a/frontend/src/app/components/footer/footer.component.html b/frontend/src/app/components/footer/footer.component.html index cc5d1f9b9..9c0369827 100644 --- a/frontend/src/app/components/footer/footer.component.html +++ b/frontend/src/app/components/footer/footer.component.html @@ -11,7 +11,7 @@
 
‎{{ mempoolInfoData.vBytesPerSecond | ceil | number }} vB/s
-
‎{{ mempoolInfoData.vBytesPerSecond * 4 | ceil | number }} WU/s
+
‎{{ mempoolInfoData.vBytesPerSecond * 4 | ceil | number }} WU/s
diff --git a/frontend/src/app/components/graphs/graphs.component.html b/frontend/src/app/components/graphs/graphs.component.html index 8468deb82..94241b825 100644 --- a/frontend/src/app/components/graphs/graphs.component.html +++ b/frontend/src/app/components/graphs/graphs.component.html @@ -22,7 +22,7 @@ Block Sizes and Weights Block Health + [routerLink]="['/graphs/mining/block-health' | relativeUrl]" i18n="mining.blocks-health">Block Health
diff --git a/frontend/src/app/components/hashrate-chart/hashrate-chart.component.html b/frontend/src/app/components/hashrate-chart/hashrate-chart.component.html index 83f8a3a4c..f3d340472 100644 --- a/frontend/src/app/components/hashrate-chart/hashrate-chart.component.html +++ b/frontend/src/app/components/hashrate-chart/hashrate-chart.component.html @@ -54,7 +54,7 @@
-
diff --git a/frontend/src/app/components/hashrate-chart/hashrate-chart.component.scss b/frontend/src/app/components/hashrate-chart/hashrate-chart.component.scss index 886608573..32885d5de 100644 --- a/frontend/src/app/components/hashrate-chart/hashrate-chart.component.scss +++ b/frontend/src/app/components/hashrate-chart/hashrate-chart.component.scss @@ -57,8 +57,6 @@ } .chart-widget { width: 100%; - height: 100%; - height: 240px; } .pool-distribution { diff --git a/frontend/src/app/components/hashrate-chart/hashrate-chart.component.ts b/frontend/src/app/components/hashrate-chart/hashrate-chart.component.ts index 592aba60b..2bda9a35a 100644 --- a/frontend/src/app/components/hashrate-chart/hashrate-chart.component.ts +++ b/frontend/src/app/components/hashrate-chart/hashrate-chart.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, OnInit, HostBinding } from '@angular/core'; -import { EChartsOption, graphic } from 'echarts'; -import { merge, Observable, of } from 'rxjs'; +import { echarts, EChartsOption } from '../../graphs/echarts'; +import { combineLatest, fromEvent, merge, Observable, of } from 'rxjs'; import { map, mergeMap, share, startWith, switchMap, tap } from 'rxjs/operators'; import { ApiService } from '../../services/api.service'; import { SeoService } from '../../services/seo.service'; @@ -31,6 +31,7 @@ import { seoDescriptionNetwork } from '../../shared/common.utils'; export class HashrateChartComponent implements OnInit { @Input() tableOnly = false; @Input() widget = false; + @Input() height: number = 300; @Input() right: number | string = 45; @Input() left: number | string = 75; @@ -86,28 +87,32 @@ export class HashrateChartComponent implements OnInit { } }); - this.hashrateObservable$ = merge( - this.radioGroupForm.get('dateSpan').valueChanges - .pipe( - startWith(this.radioGroupForm.controls.dateSpan.value), - switchMap((timespan) => { - if (!this.widget && !firstRun) { - this.storageService.setValue('miningWindowPreference', timespan); - } - this.timespan = timespan; - firstRun = false; - this.miningWindowPreference = timespan; - this.isLoading = true; - return this.apiService.getHistoricalHashrate$(this.timespan); - }) - ), - this.stateService.chainTip$ + this.hashrateObservable$ = combineLatest( + merge( + this.radioGroupForm.get('dateSpan').valueChanges .pipe( - switchMap(() => { + startWith(this.radioGroupForm.controls.dateSpan.value), + switchMap((timespan) => { + if (!this.widget && !firstRun) { + this.storageService.setValue('miningWindowPreference', timespan); + } + this.timespan = timespan; + firstRun = false; + this.miningWindowPreference = timespan; + this.isLoading = true; return this.apiService.getHistoricalHashrate$(this.timespan); }) - ) + ), + this.stateService.chainTip$ + .pipe( + switchMap(() => { + return this.apiService.getHistoricalHashrate$(this.timespan); + }) + ) + ), + fromEvent(window, 'resize').pipe(startWith(null)), ).pipe( + map(([response, _]) => response), tap((response: any) => { const data = response.body; @@ -204,7 +209,7 @@ export class HashrateChartComponent implements OnInit { title: title, animation: false, color: [ - new graphic.LinearGradient(0, 0, 0, 0.65, [ + new echarts.graphic.LinearGradient(0, 0, 0, 0.65, [ { offset: 0, color: '#F4511E99' }, { offset: 0.25, color: '#FB8C0099' }, { offset: 0.5, color: '#FFB30099' }, @@ -212,7 +217,7 @@ export class HashrateChartComponent implements OnInit { { offset: 1, color: '#7CB34299' } ]), '#D81B60', - new graphic.LinearGradient(0, 0, 0, 0.65, [ + new echarts.graphic.LinearGradient(0, 0, 0, 0.65, [ { offset: 0, color: '#F4511E' }, { offset: 0.25, color: '#FB8C00' }, { offset: 0.5, color: '#FFB300' }, @@ -221,6 +226,7 @@ export class HashrateChartComponent implements OnInit { ]), ], grid: { + height: (this.widget && this.height) ? this.height - 30 : undefined, top: this.widget ? 20 : 40, bottom: this.widget ? 30 : 70, right: this.right, @@ -249,10 +255,8 @@ export class HashrateChartComponent implements OnInit { for (const tick of ticks) { if (tick.seriesIndex === 0) { // Hashrate let hashrate = tick.data[1]; - if (this.isMobile()) { - hashratePowerOfTen = selectPowerOfTen(tick.data[1]); - hashrate = Math.round(tick.data[1] / hashratePowerOfTen.divider); - } + hashratePowerOfTen = selectPowerOfTen(tick.data[1], 10); + hashrate = tick.data[1] / hashratePowerOfTen.divider; hashrateString = `${tick.marker} ${tick.seriesName}: ${formatNumber(hashrate, this.locale, '1.0-0')} ${hashratePowerOfTen.unit}H/s
`; } else if (tick.seriesIndex === 1) { // Difficulty let difficultyPowerOfTen = hashratePowerOfTen; @@ -260,18 +264,14 @@ export class HashrateChartComponent implements OnInit { if (difficulty === null) { difficultyString = `${tick.marker} ${tick.seriesName}: No data
`; } else { - if (this.isMobile()) { - difficultyPowerOfTen = selectPowerOfTen(tick.data[1]); - difficulty = Math.round(tick.data[1] / difficultyPowerOfTen.divider); - } + difficultyPowerOfTen = selectPowerOfTen(tick.data[1]); + difficulty = tick.data[1] / difficultyPowerOfTen.divider; difficultyString = `${tick.marker} ${tick.seriesName}: ${formatNumber(difficulty, this.locale, '1.2-2')} ${difficultyPowerOfTen.unit}
`; } } else if (tick.seriesIndex === 2) { // Hashrate MA let hashrate = tick.data[1]; - if (this.isMobile()) { - hashratePowerOfTen = selectPowerOfTen(tick.data[1]); - hashrate = Math.round(tick.data[1] / hashratePowerOfTen.divider); - } + hashratePowerOfTen = selectPowerOfTen(tick.data[1], 10); + hashrate = tick.data[1] / hashratePowerOfTen.divider; hashrateStringMA = `${tick.marker} ${tick.seriesName}: ${formatNumber(hashrate, this.locale, '1.0-0')} ${hashratePowerOfTen.unit}H/s`; } } @@ -342,7 +342,7 @@ export class HashrateChartComponent implements OnInit { type: 'value', axisLabel: { color: 'rgb(110, 112, 121)', - formatter: (val) => { + formatter: (val): string => { const selectedPowerOfTen: any = selectPowerOfTen(val); const newVal = Math.round(val / selectedPowerOfTen.divider); return `${newVal} ${selectedPowerOfTen.unit}H/s`; @@ -364,9 +364,9 @@ export class HashrateChartComponent implements OnInit { position: 'right', axisLabel: { color: 'rgb(110, 112, 121)', - formatter: (val) => { + formatter: (val): string => { if (this.stateService.network === 'signet') { - return val; + return `${val}`; } const selectedPowerOfTen: any = selectPowerOfTen(val); const newVal = Math.round(val / selectedPowerOfTen.divider); diff --git a/frontend/src/app/components/hashrates-chart-pools/hashrate-chart-pools.component.ts b/frontend/src/app/components/hashrates-chart-pools/hashrate-chart-pools.component.ts index e7e3685d3..3f0e9258f 100644 --- a/frontend/src/app/components/hashrates-chart-pools/hashrate-chart-pools.component.ts +++ b/frontend/src/app/components/hashrates-chart-pools/hashrate-chart-pools.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, Input, LOCALE_ID, OnInit, HostBinding } from '@angular/core'; -import { EChartsOption } from 'echarts'; +import { EChartsOption } from '../../graphs/echarts'; import { Observable } from 'rxjs'; import { delay, map, retryWhen, share, startWith, switchMap, tap } from 'rxjs/operators'; import { ApiService } from '../../services/api.service'; @@ -11,6 +11,13 @@ import { MiningService } from '../../services/mining.service'; import { download } from '../../shared/graphs.utils'; import { ActivatedRoute } from '@angular/router'; +interface Hashrate { + timestamp: number; + avgHashRate: number; + share: number; + poolName: string; +} + @Component({ selector: 'app-hashrate-chart-pools', templateUrl: './hashrate-chart-pools.component.html', @@ -32,6 +39,7 @@ export class HashrateChartPoolsComponent implements OnInit { miningWindowPreference: string; radioGroupForm: UntypedFormGroup; + hashrates: Hashrate[]; chartOptions: EChartsOption = {}; chartInitOptions = { renderer: 'svg', @@ -87,56 +95,9 @@ export class HashrateChartPoolsComponent implements OnInit { return this.apiService.getHistoricalPoolsHashrate$(timespan) .pipe( tap((response) => { - const hashrates = response.body; + this.hashrates = response.body; // Prepare series (group all hashrates data point by pool) - const grouped = {}; - for (const hashrate of hashrates) { - if (!grouped.hasOwnProperty(hashrate.poolName)) { - grouped[hashrate.poolName] = []; - } - grouped[hashrate.poolName].push(hashrate); - } - - const series = []; - const legends = []; - for (const name in grouped) { - series.push({ - zlevel: 0, - stack: 'Total', - name: name, - showSymbol: false, - symbol: 'none', - data: grouped[name].map((val) => [val.timestamp * 1000, val.share * 100]), - type: 'line', - lineStyle: { width: 0 }, - areaStyle: { opacity: 1 }, - smooth: true, - color: poolsColor[name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()], - emphasis: { - disabled: true, - scale: false, - }, - }); - - legends.push({ - name: name, - inactiveColor: 'rgb(110, 112, 121)', - textStyle: { - color: 'white', - }, - icon: 'roundRect', - itemStyle: { - color: poolsColor[name.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()], - }, - }); - } - - this.prepareChartOptions({ - legends: legends, - series: series, - }); - this.isLoading = false; - + const series = this.applyHashrates(); if (series.length === 0) { this.cd.markForCheck(); throw new Error(); @@ -156,6 +117,77 @@ export class HashrateChartPoolsComponent implements OnInit { ); } + applyHashrates(): any[] { + const times: { [time: number]: { hashrates: { [pool: string]: Hashrate } } } = {}; + const pools = {}; + for (const hashrate of this.hashrates) { + if (!times[hashrate.timestamp]) { + times[hashrate.timestamp] = { hashrates: {} }; + } + times[hashrate.timestamp].hashrates[hashrate.poolName] = hashrate; + if (!pools[hashrate.poolName]) { + pools[hashrate.poolName] = true; + } + } + + const sortedTimes = Object.keys(times).sort((a,b) => parseInt(a) - parseInt(b)).map(time => ({ time: parseInt(time), hashrates: times[time].hashrates })); + const lastHashrates = sortedTimes[sortedTimes.length - 1].hashrates; + const sortedPools = Object.keys(pools).sort((a,b) => { + if (lastHashrates[b]?.share ?? lastHashrates[a]?.share ?? false) { + // sort by descending share of hashrate in latest period + return (lastHashrates[b]?.share || 0) - (lastHashrates[a]?.share || 0); + } else { + // tiebreak by pool name + b < a; + } + }); + + const series = []; + const legends = []; + for (const name of sortedPools) { + const data = sortedTimes.map(({ time, hashrates }) => { + return [time * 1000, (hashrates[name]?.share || 0) * 100]; + }); + series.push({ + zlevel: 0, + stack: 'Total', + name: name, + showSymbol: false, + symbol: 'none', + data, + type: 'line', + lineStyle: { width: 0 }, + areaStyle: { opacity: 1 }, + smooth: true, + color: poolsColor[name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()], + emphasis: { + disabled: true, + scale: false, + }, + }); + + legends.push({ + name: name, + inactiveColor: 'rgb(110, 112, 121)', + textStyle: { + color: 'white', + }, + icon: 'roundRect', + itemStyle: { + color: poolsColor[name.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()], + }, + }); + } + + this.prepareChartOptions({ + legends: legends, + series: series, + }); + this.isLoading = false; + + return series; + } + prepareChartOptions(data) { let title: object; if (data.series.length === 0) { @@ -256,6 +288,7 @@ export class HashrateChartPoolsComponent implements OnInit { }, }], }; + this.cd.markForCheck(); } onChartInit(ec) { diff --git a/frontend/src/app/components/incoming-transactions-graph/incoming-transactions-graph.component.ts b/frontend/src/app/components/incoming-transactions-graph/incoming-transactions-graph.component.ts index 219811e9c..703181eba 100644 --- a/frontend/src/app/components/incoming-transactions-graph/incoming-transactions-graph.component.ts +++ b/frontend/src/app/components/incoming-transactions-graph/incoming-transactions-graph.component.ts @@ -1,5 +1,5 @@ import { Component, Input, Inject, LOCALE_ID, ChangeDetectionStrategy, OnInit, OnDestroy } from '@angular/core'; -import { EChartsOption } from 'echarts'; +import { EChartsOption } from '../../graphs/echarts'; import { OnChanges } from '@angular/core'; import { StorageService } from '../../services/storage.service'; import { download, formatterXAxis, formatterXAxisLabel } from '../../shared/graphs.utils'; @@ -7,6 +7,8 @@ import { formatNumber } from '@angular/common'; import { StateService } from '../../services/state.service'; import { Subscription } from 'rxjs'; +const OUTLIERS_MEDIAN_MULTIPLIER = 4; + @Component({ selector: 'app-incoming-transactions-graph', templateUrl: './incoming-transactions-graph.component.html', @@ -29,6 +31,7 @@ export class IncomingTransactionsGraphComponent implements OnInit, OnChanges, On @Input() left: number | string = '0'; @Input() template: ('widget' | 'advanced') = 'widget'; @Input() windowPreferenceOverride: string; + @Input() outlierCappingEnabled: boolean = false; isLoading = true; mempoolStatsChartOption: EChartsOption = {}; @@ -37,8 +40,10 @@ export class IncomingTransactionsGraphComponent implements OnInit, OnChanges, On }; windowPreference: string; chartInstance: any = undefined; + MA: number[][] = []; weightMode: boolean = false; rateUnitSub: Subscription; + medianVbytesPerSecond: number | undefined; constructor( @Inject(LOCALE_ID) private locale: string, @@ -62,17 +67,107 @@ export class IncomingTransactionsGraphComponent implements OnInit, OnChanges, On return; } this.windowPreference = this.windowPreferenceOverride ? this.windowPreferenceOverride : this.storageService.getValue('graphWindowPreference'); + const windowSize = Math.max(10, Math.floor(this.data.series[0].length / 8)); + this.MA = this.calculateMA(this.data.series[0], windowSize); + if (this.outlierCappingEnabled === true) { + this.computeMedianVbytesPerSecond(this.data.series[0]); + } this.mountChart(); } rendered() { if (!this.data) { - return; + return; } this.isLoading = false; } + /** + * Calculate the median value of the vbytes per second chart to hide outliers + */ + computeMedianVbytesPerSecond(data: number[][]): void { + const vBytes: number[] = []; + for (const value of data) { + vBytes.push(value[1]); + } + const sorted = vBytes.slice().sort((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + this.medianVbytesPerSecond = sorted[middle]; + if (sorted.length % 2 === 0) { + this.medianVbytesPerSecond = (sorted[middle - 1] + sorted[middle]) / 2; + } + } + + /// calculate the moving average of the provided data based on windowSize + calculateMA(data: number[][], windowSize: number = 100): number[][] { + //update const variables that are not changed + const ma: number[][] = []; + let sum = 0; + let i = 0; + + //calculate the centered moving average + for (i = 0; i < data.length; i++) { + sum += data[i][1]; + if (i >= windowSize) { + sum -= data[i - windowSize][1]; + const midpoint = i - Math.floor(windowSize / 2); + const avg = sum / windowSize; + ma.push([data[midpoint][0], avg]); + } + } + + //return the moving average array + return ma; + } + mountChart(): void { + //create an array for the echart series + //similar to how it is done in mempool-graph.component.ts + const seriesGraph = []; + seriesGraph.push({ + zlevel: 0, + name: 'data', + data: this.data.series[0], + type: 'line', + smooth: false, + showSymbol: false, + symbol: 'none', + lineStyle: { + width: 3, + }, + markLine: { + silent: true, + symbol: 'none', + lineStyle: { + color: '#fff', + opacity: 1, + width: 2, + }, + data: [{ + yAxis: 1667, + label: { + show: false, + color: '#ffffff', + } + }], + } + }); + if (this.template !== 'widget') { + seriesGraph.push({ + zlevel: 0, + name: 'MA', + data: this.MA, + type: 'line', + smooth: false, + showSymbol: false, + symbol: 'none', + lineStyle: { + width: 2, + color: "white", + } + }); + } + this.mempoolStatsChartOption = { grid: { height: this.height, @@ -114,27 +209,31 @@ export class IncomingTransactionsGraphComponent implements OnInit, OnChanges, On obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 80; return obj; }, - extraCssText: `width: ${(['2h', '24h'].includes(this.windowPreference) || this.template === 'widget') ? '125px' : '135px'}; - background: transparent; + extraCssText: `background: transparent; border: none; box-shadow: none;`, axisPointer: { type: 'line', }, formatter: (params: any) => { - const axisValueLabel: string = formatterXAxis(this.locale, this.windowPreference, params[0].axisValue); + const axisValueLabel: string = formatterXAxis(this.locale, this.windowPreference, params[0].axisValue); const colorSpan = (color: string) => ``; let itemFormatted = '
' + axisValueLabel + '
'; params.map((item: any, index: number) => { - if (index < 26) { - itemFormatted += `
-
${colorSpan(item.color)}
-
-
${formatNumber(this.weightMode ? item.value[1] * 4 : item.value[1], this.locale, '1.0-0')} ${this.weightMode ? 'WU' : 'vB'}/s
-
`; + + //Do no include MA in tooltip legend! + if (item.seriesName !== 'MA') { + if (index < 26) { + itemFormatted += `
+
${colorSpan(item.color)}
+
+
${formatNumber(item.value[1], this.locale, '1.0-0')}vB/s
+
`; + } } }); - return `
${itemFormatted}
`; + return `
${itemFormatted}
`; } }, xAxis: [ @@ -156,6 +255,13 @@ export class IncomingTransactionsGraphComponent implements OnInit, OnChanges, On } ], yAxis: { + max: (value) => { + if (!this.outlierCappingEnabled || value.max < this.medianVbytesPerSecond * OUTLIERS_MEDIAN_MULTIPLIER) { + return undefined; + } else { + return Math.round(this.medianVbytesPerSecond * OUTLIERS_MEDIAN_MULTIPLIER); + } + }, type: 'value', axisLabel: { fontSize: 11, @@ -171,35 +277,7 @@ export class IncomingTransactionsGraphComponent implements OnInit, OnChanges, On } } }, - series: [ - { - zlevel: 0, - data: this.data.series[0], - type: 'line', - smooth: false, - showSymbol: false, - symbol: 'none', - lineStyle: { - width: 3, - }, - markLine: { - silent: true, - symbol: 'none', - lineStyle: { - color: '#fff', - opacity: 1, - width: 2, - }, - data: [{ - yAxis: 1667, - label: { - show: false, - color: '#ffffff', - } - }], - } - }, - ], + series: seriesGraph, visualMap: { show: false, top: 50, diff --git a/frontend/src/app/components/lbtc-pegs-graph/lbtc-pegs-graph.component.ts b/frontend/src/app/components/lbtc-pegs-graph/lbtc-pegs-graph.component.ts index e4aa95492..9931fb78a 100644 --- a/frontend/src/app/components/lbtc-pegs-graph/lbtc-pegs-graph.component.ts +++ b/frontend/src/app/components/lbtc-pegs-graph/lbtc-pegs-graph.component.ts @@ -1,6 +1,6 @@ import { Component, Inject, LOCALE_ID, ChangeDetectionStrategy, Input, OnChanges, OnInit } from '@angular/core'; import { formatDate, formatNumber } from '@angular/common'; -import { EChartsOption } from 'echarts'; +import { EChartsOption } from '../../graphs/echarts'; @Component({ selector: 'app-lbtc-pegs-graph', @@ -18,16 +18,15 @@ import { EChartsOption } from 'echarts'; }) export class LbtcPegsGraphComponent implements OnInit, OnChanges { @Input() data: any; + @Input() height: number | string = '320'; pegsChartOptions: EChartsOption; - height: number | string = '200'; right: number | string = '10'; top: number | string = '20'; left: number | string = '50'; template: ('widget' | 'advanced') = 'widget'; isLoading = true; - pegsChartOption: EChartsOption = {}; pegsChartInitOption = { renderer: 'svg' }; @@ -41,20 +40,24 @@ export class LbtcPegsGraphComponent implements OnInit, OnChanges { } ngOnChanges() { - if (!this.data) { + if (!this.data?.liquidPegs) { return; } - this.pegsChartOptions = this.createChartOptions(this.data.series, this.data.labels); + if (!this.data.liquidReserves) { + this.pegsChartOptions = this.createChartOptions(this.data.liquidPegs.series, this.data.liquidPegs.labels); + } else { + this.pegsChartOptions = this.createChartOptions(this.data.liquidPegs.series, this.data.liquidPegs.labels, this.data.liquidReserves.series); + } } rendered() { - if (!this.data) { + if (!this.data.liquidPegs) { return; } this.isLoading = false; } - createChartOptions(series: number[], labels: string[]): EChartsOption { + createChartOptions(pegSeries: number[], labels: string[], reservesSeries?: number[],): EChartsOption { return { grid: { height: this.height, @@ -99,17 +102,18 @@ export class LbtcPegsGraphComponent implements OnInit, OnChanges { type: 'line', }, formatter: (params: any) => { - const colorSpan = (color: string) => ``; + const colorSpan = (color: string) => ``; let itemFormatted = '
' + params[0].axisValue + '
'; - params.map((item: any, index: number) => { + for (let index = params.length - 1; index >= 0; index--) { + const item = params[index]; if (index < 26) { itemFormatted += `
${colorSpan(item.color)}
-
-
${formatNumber(item.value, this.locale, '1.2-2')} L-BTC
+
+
${formatNumber(item.value, this.locale, '1.2-2')} ${item.seriesName}
`; } - }); + } return `
${itemFormatted}
`; } }, @@ -138,20 +142,34 @@ export class LbtcPegsGraphComponent implements OnInit, OnChanges { }, series: [ { - data: series, + data: pegSeries, + name: 'L-BTC', + color: '#116761', type: 'line', stack: 'total', - smooth: false, + smooth: true, showSymbol: false, areaStyle: { opacity: 0.2, color: '#116761', }, lineStyle: { - width: 3, + width: 2, color: '#116761', }, }, + { + data: reservesSeries, + name: 'BTC', + color: '#EA983B', + type: 'line', + smooth: true, + showSymbol: false, + lineStyle: { + width: 2, + color: '#EA983B', + }, + }, ], }; } diff --git a/frontend/src/app/components/liquid-master-page/liquid-master-page.component.html b/frontend/src/app/components/liquid-master-page/liquid-master-page.component.html index 476c78622..dd07645bf 100644 --- a/frontend/src/app/components/liquid-master-page/liquid-master-page.component.html +++ b/frontend/src/app/components/liquid-master-page/liquid-master-page.component.html @@ -1,5 +1,5 @@ -
+
@@ -78,7 +78,7 @@ -
HeightHeightPoolTimestampTimestampHealthRewardFeesFeesTXsTransactionsSizeTransactionsSize
{{ block.height }} -
+
+
@@ -38,11 +38,17 @@ {{ block.extras.coinbaseRaw | hex2ascii }}
+
+ + {{ block.extras.pool.name }} + {{ block.extras.coinbaseRaw | hex2ascii }} +
- ‎{{ block.timestamp * 1000 | date:'yyyy-MM-dd HH:mm' }} + + ‎{{ block.timestamp * 1000 | date:'yyyy-MM-dd HH:mm:ss' }} + Unknown + + + {{ block.extras.feeDelta > 0 ? '+' : '' }}{{ (block.extras.feeDelta * 100) | amountShortener: 2 }}% + {{ block.tx_count | number }} +
@@ -82,34 +88,31 @@
+ - - + - + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AddressBalance
+ + + + + +
+ + + + + +
+ + + +
+ + + +
+ + + + + +
+
+
+
+ +
diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component.scss b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component.scss new file mode 100644 index 000000000..b711f659b --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component.scss @@ -0,0 +1,54 @@ +.spinner-border { + height: 25px; + width: 25px; + margin-top: 13px; +} + +.extra-margin-right { + @media (max-width: 380px) { + margin-left: -10px; + } +} + +tr, td, th { + border: 0px; + padding-top: 0.65rem; + padding-bottom: 0.6rem; + padding-right: 2rem; + .widget &.widget { + padding-right: 1rem; + @media (max-width: 510px) { + padding-right: 0.5rem; + } + } +} + +.clear-link { + color: white; +} + +.disabled { + pointer-events: none; + opacity: 0.5; +} + +.progress { + background-color: #2d3348; +} + +.address { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 160px; +} +.address.widget { + width: 60%; +} + +.amount { + width: 25%; +} +.amount.widget { + width: 40%; +} diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component.ts b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component.ts new file mode 100644 index 000000000..caeac1987 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component.ts @@ -0,0 +1,109 @@ +import { Component, OnInit, ChangeDetectionStrategy, Input } from '@angular/core'; +import { Observable, Subject, combineLatest, of, timer } from 'rxjs'; +import { delayWhen, filter, map, share, shareReplay, switchMap, takeUntil, tap, throttleTime } from 'rxjs/operators'; +import { ApiService } from '../../../services/api.service'; +import { Env, StateService } from '../../../services/state.service'; +import { AuditStatus, CurrentPegs, FederationAddress } from '../../../interfaces/node-api.interface'; +import { WebsocketService } from '../../../services/websocket.service'; + +@Component({ + selector: 'app-federation-addresses-list', + templateUrl: './federation-addresses-list.component.html', + styleUrls: ['./federation-addresses-list.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class FederationAddressesListComponent implements OnInit { + @Input() widget: boolean = false; + @Input() federationAddresses$: Observable; + + env: Env; + isLoading = true; + page = 1; + pageSize = 15; + maxSize = window.innerWidth <= 767.98 ? 3 : 5; + skeletonLines: number[] = []; + auditStatus$: Observable; + auditUpdated$: Observable; + lastReservesBlockUpdate: number = 0; + currentPeg$: Observable; + lastPegBlockUpdate: number = 0; + lastPegAmount: string = ''; + isLoad: boolean = true; + + private destroy$ = new Subject(); + + constructor( + private apiService: ApiService, + public stateService: StateService, + private websocketService: WebsocketService + ) { + } + + ngOnInit(): void { + this.isLoading = !this.widget; + this.env = this.stateService.env; + this.skeletonLines = this.widget === true ? [...Array(5).keys()] : [...Array(15).keys()]; + if (!this.widget) { + this.websocketService.want(['blocks']); + this.auditStatus$ = this.stateService.blocks$.pipe( + takeUntil(this.destroy$), + throttleTime(40000), + delayWhen(_ => this.isLoad ? timer(0) : timer(2000)), + tap(() => this.isLoad = false), + switchMap(() => this.apiService.federationAuditSynced$()), + shareReplay(1) + ); + + this.currentPeg$ = this.auditStatus$.pipe( + filter(auditStatus => auditStatus.isAuditSynced === true), + switchMap(_ => + this.apiService.liquidPegs$().pipe( + filter((currentPegs) => currentPegs.lastBlockUpdate >= this.lastPegBlockUpdate), + tap((currentPegs) => { + this.lastPegBlockUpdate = currentPegs.lastBlockUpdate; + }) + ) + ), + share() + ); + + this.auditUpdated$ = combineLatest([ + this.auditStatus$, + this.currentPeg$ + ]).pipe( + filter(([auditStatus, _]) => auditStatus.isAuditSynced === true), + map(([auditStatus, currentPeg]) => ({ + lastBlockAudit: auditStatus.lastBlockAudit, + currentPegAmount: currentPeg.amount + })), + switchMap(({ lastBlockAudit, currentPegAmount }) => { + const blockAuditCheck = lastBlockAudit > this.lastReservesBlockUpdate; + const amountCheck = currentPegAmount !== this.lastPegAmount; + this.lastReservesBlockUpdate = lastBlockAudit; + this.lastPegAmount = currentPegAmount; + return of(blockAuditCheck || amountCheck); + }), + share() + ); + + this.federationAddresses$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => this.apiService.federationAddresses$()), + tap(_ => this.isLoading = false), + share() + ); + } + + } + + ngOnDestroy(): void { + this.destroy$.next(1); + this.destroy$.complete(); + } + + pageChange(page: number): void { + this.page = page; + } + +} diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.html b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.html new file mode 100644 index 000000000..9240cf228 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.html @@ -0,0 +1,31 @@ +
+
+
+ +
Liquid Federation Wallet 
+
+
+
{{ federationWalletStats.address_count }} addresses
+
{{ federationWalletStats.utxo_count }} UTXOs
+
+
+
+
+ + + + + + +
+
diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.scss b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.scss new file mode 100644 index 000000000..4ddce6501 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.scss @@ -0,0 +1,73 @@ +.fee-estimation-container { + display: flex; + justify-content: space-between; + margin-bottom: 10px; + @media (min-width: 376px) { + flex-direction: row; + } + .item { + max-width: 300px; + margin: 0; + width: -webkit-fill-available; + @media (min-width: 376px) { + margin: 0 auto 0px; + } + + .card-title { + margin: 0; + color: #4a68b9; + font-size: 10px; + font-size: 1rem; + white-space: nowrap; + } + + .card-text { + padding-top: 9px; + font-size: 22px; + span { + font-size: 11px; + position: relative; + top: -2px; + } + } + + .card-text span { + color: #ffffff66; + font-size: 12px; + top: 0px; + } + .fee-text{ + border-bottom: 1px solid #ffffff1c; + width: fit-content; + margin: auto; + line-height: 1.45; + padding: 0px 2px; + } + .fiat { + display: block; + font-size: 14px !important; + } + } +} + +.card-text { + .skeleton-loader { + width: 100%; + display: block; + &:first-child { + max-width: 90px; + margin: 15px auto 3px; + } + &:last-child { + margin: 10px auto 3px; + max-width: 55px; + } + } +} + +.title-link, .title-link:hover, .title-link:focus, .title-link:active { + display: block; + margin-bottom: 4px; + text-decoration: none; + color: inherit; +} diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.ts b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.ts new file mode 100644 index 000000000..61650fdb4 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component.ts @@ -0,0 +1,31 @@ +import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; +import { Observable, combineLatest, map, of } from 'rxjs'; + +@Component({ + selector: 'app-federation-addresses-stats', + templateUrl: './federation-addresses-stats.component.html', + styleUrls: ['./federation-addresses-stats.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class FederationAddressesStatsComponent implements OnInit { + @Input() federationAddressesNumber$: Observable; + @Input() federationUtxosNumber$: Observable; + federationWalletStats$: Observable; + + constructor() { } + + ngOnInit(): void { + this.federationWalletStats$ = combineLatest([ + this.federationAddressesNumber$ ?? of(undefined), + this.federationUtxosNumber$ ?? of(undefined) + ]).pipe( + map(([address_count, utxo_count]) => { + if (address_count === undefined || utxo_count === undefined) { + return undefined; + } + return { address_count, utxo_count} + }) + ) + } + +} diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.html b/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.html new file mode 100644 index 000000000..ea52cd8d7 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.html @@ -0,0 +1,109 @@ +
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OutputAddressAmountRelated Peg-InDate
+ + + + + + + +
+ + + + + + + + + + + + + + + + + Change output + + + ‎{{ utxo.blocktime * 1000 | date:'yyyy-MM-dd HH:mm' }} +
()
+
+ + + + + +
+ + + + + + + + + +
+ + + + + +
+
+
+
+ +
diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.scss b/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.scss new file mode 100644 index 000000000..617edc869 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.scss @@ -0,0 +1,94 @@ +.spinner-border { + height: 25px; + width: 25px; + margin-top: 13px; +} + +tr, td, th { + border: 0px; + padding-top: 0.65rem !important; + padding-bottom: 0.6rem !important; + padding-right: 2rem !important; + .widget { + padding-right: 1rem !important; + } +} + +.clear-link { + color: white; +} + +.disabled { + pointer-events: none; + opacity: 0.5; +} + +.progress { + background-color: #2d3348; +} + +.txid { + width: 25%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 160px; +} +.txid.widget { + width: 40%; + +} + +.address { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 160px; + @media (max-width: 527px) { + display: none; + } +} + +.amount { + width: 12%; +} +.amount.widget { + width: 30%; +} + +.pegin { + width: 25%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 160px; + @media (max-width: 872px) { + display: none; + } +} + +.timestamp { + width: 18%; + @media (max-width: 800px) { + display: none; + } + @media (max-width: 1000px) { + .relative-time { + display: none; + } + } +} +.timestamp.widget { + width: 100%; + @media (min-width: 768px) AND (max-width: 1050px) { + display: none; + } + @media (max-width: 767px) { + display: block; + } + + @media (max-width: 500px) { + display: none; + } +} + diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.ts b/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.ts new file mode 100644 index 000000000..30f401abf --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component.ts @@ -0,0 +1,109 @@ +import { Component, OnInit, ChangeDetectionStrategy, Input } from '@angular/core'; +import { Observable, Subject, combineLatest, of, timer } from 'rxjs'; +import { delayWhen, filter, map, share, shareReplay, switchMap, takeUntil, tap, throttleTime } from 'rxjs/operators'; +import { ApiService } from '../../../services/api.service'; +import { Env, StateService } from '../../../services/state.service'; +import { AuditStatus, CurrentPegs, FederationUtxo } from '../../../interfaces/node-api.interface'; +import { WebsocketService } from '../../../services/websocket.service'; + +@Component({ + selector: 'app-federation-utxos-list', + templateUrl: './federation-utxos-list.component.html', + styleUrls: ['./federation-utxos-list.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class FederationUtxosListComponent implements OnInit { + @Input() widget: boolean = false; + @Input() federationUtxos$: Observable; + + env: Env; + isLoading = true; + page = 1; + pageSize = 15; + maxSize = window.innerWidth <= 767.98 ? 3 : 5; + skeletonLines: number[] = []; + auditStatus$: Observable; + auditUpdated$: Observable; + lastReservesBlockUpdate: number = 0; + currentPeg$: Observable; + lastPegBlockUpdate: number = 0; + lastPegAmount: string = ''; + isLoad: boolean = true; + + private destroy$ = new Subject(); + + constructor( + private apiService: ApiService, + public stateService: StateService, + private websocketService: WebsocketService, + ) { + } + + ngOnInit(): void { + this.isLoading = !this.widget; + this.env = this.stateService.env; + this.skeletonLines = this.widget === true ? [...Array(6).keys()] : [...Array(15).keys()]; + + if (!this.widget) { + this.websocketService.want(['blocks']); + this.auditStatus$ = this.stateService.blocks$.pipe( + takeUntil(this.destroy$), + throttleTime(40000), + delayWhen(_ => this.isLoad ? timer(0) : timer(2000)), + tap(() => this.isLoad = false), + switchMap(() => this.apiService.federationAuditSynced$()), + shareReplay(1) + ); + + this.currentPeg$ = this.auditStatus$.pipe( + filter(auditStatus => auditStatus.isAuditSynced === true), + switchMap(_ => + this.apiService.liquidPegs$().pipe( + filter((currentPegs) => currentPegs.lastBlockUpdate >= this.lastPegBlockUpdate), + tap((currentPegs) => { + this.lastPegBlockUpdate = currentPegs.lastBlockUpdate; + }) + ) + ), + share() + ); + + this.auditUpdated$ = combineLatest([ + this.auditStatus$, + this.currentPeg$ + ]).pipe( + filter(([auditStatus, _]) => auditStatus.isAuditSynced === true), + map(([auditStatus, currentPeg]) => ({ + lastBlockAudit: auditStatus.lastBlockAudit, + currentPegAmount: currentPeg.amount + })), + switchMap(({ lastBlockAudit, currentPegAmount }) => { + const blockAuditCheck = lastBlockAudit > this.lastReservesBlockUpdate; + const amountCheck = currentPegAmount !== this.lastPegAmount; + this.lastReservesBlockUpdate = lastBlockAudit; + this.lastPegAmount = currentPegAmount; + return of(blockAuditCheck || amountCheck); + }), + share() + ); + + this.federationUtxos$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => this.apiService.federationUtxos$()), + tap(_ => this.isLoading = false), + share() + ); + } + } + + ngOnDestroy(): void { + this.destroy$.next(1); + this.destroy$.complete(); + } + + pageChange(page: number): void { + this.page = page; + } + +} diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.html b/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.html new file mode 100644 index 000000000..1bb397533 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.html @@ -0,0 +1,24 @@ +
+
+

Liquid Federation Wallet

+
+ + + +
+ + + +
+ +
diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.scss b/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.scss new file mode 100644 index 000000000..4b07e45e3 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.scss @@ -0,0 +1,13 @@ +ul { + margin-bottom: 20px; +} + +@media (max-width: 767.98px) { + .nav-container { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + margin: auto; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.ts b/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.ts new file mode 100644 index 000000000..cbf931e28 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/federation-wallet/federation-wallet.component.ts @@ -0,0 +1,20 @@ +import { Component, OnInit } from '@angular/core'; +import { SeoService } from '../../../services/seo.service'; + +@Component({ + selector: 'app-federation-wallet', + templateUrl: './federation-wallet.component.html', + styleUrls: ['./federation-wallet.component.scss'] +}) +export class FederationWalletComponent implements OnInit { + + constructor( + private seoService: SeoService + ) { + this.seoService.setTitle($localize`:@@993e5bc509c26db81d93018e24a6afe6e50cae52:Liquid Federation Wallet`); + } + + ngOnInit(): void { + } + +} diff --git a/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.html b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.html new file mode 100644 index 000000000..2b0c49bd2 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.html @@ -0,0 +1,137 @@ +
+ +
+

Recent Peg-In / Out's

+
+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TransactionDateAmountFund / Redemption TxBTC Address
+ + + + + + + + + + + + + + +
+ + + + + + + + + + + + ‎{{ peg.blocktime * 1000 | date:'yyyy-MM-dd HH:mm' }} +
()
+
+ + + + + + + + + + Peg out in progress... + + + + + + + + +
+ + + + + +
+ + + + + + + + + +
+ + + + + +
+
+
+
+ +
+ +
+ + + - + \ No newline at end of file diff --git a/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.scss b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.scss new file mode 100644 index 000000000..7a3d9e49f --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.scss @@ -0,0 +1,123 @@ +.spinner-border { + height: 25px; + width: 25px; + margin-top: 13px; +} + +tr, td, th { + border: 0px; + padding-top: 0.65rem; + padding-bottom: 0.6rem; + padding-right: 2rem; + .widget &.widget { + padding-right: 1rem; + @media (max-width: 510px) { + padding-right: 0.5rem; + } + } +} + +.clear-link { + color: white; +} + +.disabled { + pointer-events: none; + opacity: 0.5; +} + +.progress { + background-color: #2d3348; +} + +.transaction { + width: 65%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 120px; +} +.transaction.widget { + width: 100%; + +} + +.address { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 160px; + @media (max-width: 527px) { + display: none; + } +} + +.amount { + width: 0%; +} + +.output { + width: 50%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 160px; + @media (max-width: 800px) { + display: none; + } +} + +.address { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 160px; + @media (max-width: 960px) { + display: none; + } +} + +.timestamp { + width: 0%; + @media (max-width: 650px) { + display: none; + } + @media (max-width: 1000px) { + .relative-time { + display: none; + } + } +} +.timestamp.widget { + @media (min-width: 768px) AND (max-width: 1050px) { + display: none; + } + @media (max-width: 767px) { + display: block; + } + + @media (max-width: 510px) { + display: none; + } +} + +.credit { + color: #7CB342; +} + +.debit { + color: #D81B60; +} + +.glow-effect { + animation: color-oscillation 1s ease-in-out infinite alternate; +} + +@keyframes color-oscillation { + 0% { + color: #777983; + } + 100% { + color: #D81B60; + } +} diff --git a/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.ts b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.ts new file mode 100644 index 000000000..d8c60113f --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component.ts @@ -0,0 +1,139 @@ +import { Component, OnInit, ChangeDetectionStrategy, Input } from '@angular/core'; +import { BehaviorSubject, Observable, Subject, combineLatest, of, timer } from 'rxjs'; +import { delayWhen, filter, map, share, shareReplay, switchMap, takeUntil, tap, throttleTime } from 'rxjs/operators'; +import { ApiService } from '../../../services/api.service'; +import { Env, StateService } from '../../../services/state.service'; +import { AuditStatus, CurrentPegs, RecentPeg } from '../../../interfaces/node-api.interface'; +import { WebsocketService } from '../../../services/websocket.service'; +import { SeoService } from '../../../services/seo.service'; + +@Component({ + selector: 'app-recent-pegs-list', + templateUrl: './recent-pegs-list.component.html', + styleUrls: ['./recent-pegs-list.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class RecentPegsListComponent implements OnInit { + @Input() widget: boolean = false; + @Input() recentPegsList$: Observable; + + env: Env; + isLoading = true; + isPegCountLoading = true; + page = 1; + pageSize = 15; + maxSize = window.innerWidth <= 767.98 ? 3 : 5; + skeletonLines: number[] = []; + auditStatus$: Observable; + auditUpdated$: Observable; + lastReservesBlockUpdate: number = 0; + currentPeg$: Observable; + pegsCount$: Observable; + startingIndexSubject: BehaviorSubject = new BehaviorSubject(0); + currentIndex: number = 0; + lastPegBlockUpdate: number = 0; + lastPegAmount: string = ''; + isLoad: boolean = true; + + private destroy$ = new Subject(); + + constructor( + private apiService: ApiService, + public stateService: StateService, + private websocketService: WebsocketService, + private seoService: SeoService + ) { + } + + ngOnInit(): void { + this.isLoading = !this.widget; + this.env = this.stateService.env; + this.skeletonLines = this.widget === true ? [...Array(5).keys()] : [...Array(15).keys()]; + + if (!this.widget) { + this.seoService.setTitle($localize`:@@a8b0889ea1b41888f1e247f2731cc9322198ca04:Recent Peg-In / Out's`); + this.websocketService.want(['blocks']); + this.auditStatus$ = this.stateService.blocks$.pipe( + takeUntil(this.destroy$), + throttleTime(40000), + delayWhen(_ => this.isLoad ? timer(0) : timer(2000)), + tap(() => this.isLoad = false), + switchMap(() => this.apiService.federationAuditSynced$()), + shareReplay(1) + ); + + this.currentPeg$ = this.auditStatus$.pipe( + filter(auditStatus => auditStatus.isAuditSynced === true), + switchMap(_ => + this.apiService.liquidPegs$().pipe( + filter((currentPegs) => currentPegs.lastBlockUpdate >= this.lastPegBlockUpdate), + tap((currentPegs) => { + this.lastPegBlockUpdate = currentPegs.lastBlockUpdate; + }) + ) + ), + share() + ); + + this.auditUpdated$ = combineLatest([ + this.auditStatus$, + this.currentPeg$ + ]).pipe( + filter(([auditStatus, _]) => auditStatus.isAuditSynced === true), + map(([auditStatus, currentPeg]) => ({ + lastBlockAudit: auditStatus.lastBlockAudit, + currentPegAmount: currentPeg.amount + })), + switchMap(({ lastBlockAudit, currentPegAmount }) => { + const blockAuditCheck = lastBlockAudit > this.lastReservesBlockUpdate; + const amountCheck = currentPegAmount !== this.lastPegAmount; + this.lastReservesBlockUpdate = lastBlockAudit; + this.lastPegAmount = currentPegAmount; + return of(blockAuditCheck || amountCheck); + }), + share() + ); + + this.pegsCount$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + tap(() => this.isPegCountLoading = true), + switchMap(_ => this.apiService.pegsCount$()), + map((data) => data.pegs_count), + tap(() => this.isPegCountLoading = false), + share() + ); + + this.recentPegsList$ = combineLatest([ + this.auditStatus$, + this.auditUpdated$, + this.startingIndexSubject + ]).pipe( + filter(([auditStatus, auditUpdated, startingIndex]) => { + const auditStatusCheck = auditStatus.isAuditSynced === true; + const auditUpdatedCheck = auditUpdated === true; + const startingIndexCheck = startingIndex !== this.currentIndex; + return auditStatusCheck && (auditUpdatedCheck || startingIndexCheck); + }), + tap(([_, __, startingIndex]) => { + this.currentIndex = startingIndex; + this.isLoading = true; + }), + switchMap(([_, __, startingIndex]) => this.apiService.recentPegsList$(startingIndex)), + tap(() => this.isLoading = false), + share() + ); + + } + } + + ngOnDestroy(): void { + this.destroy$.next(1); + this.destroy$.complete(); + } + + pageChange(page: number): void { + this.startingIndexSubject.next((page - 1) * 15); + this.page = page; + } + +} diff --git a/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.html b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.html new file mode 100644 index 000000000..2a853ff5d --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.html @@ -0,0 +1,47 @@ +
+ +
+
+
+
+{{ (+pegsVolume[0].volume) / 100000000 | number: '1.2-2' }} BTC
+
{{ (+pegsVolume[0].number) }} Peg-Ins
+
+
+
+
+
{{ (+pegsVolume[1].volume) / 100000000 | number: '1.2-2' }} BTC
+
{{ (+pegsVolume[1].number) }} Peg-Outs
+
+
+
+
+ + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.scss b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.scss new file mode 100644 index 000000000..4cfef8e7a --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.scss @@ -0,0 +1,80 @@ +.fee-estimation-container { + display: flex; + justify-content: space-between; + margin-bottom: 10px; + @media (min-width: 376px) { + flex-direction: row; + } + .item { + max-width: 300px; + margin: 0; + width: -webkit-fill-available; + @media (min-width: 376px) { + margin: 0 auto 0px; + } + + .card-title { + margin: 0; + color: #4a68b9; + font-size: 10px; + font-size: 1rem; + white-space: nowrap; + } + + .card-text { + font-size: 22px; + span { + font-size: 11px; + position: relative; + top: -2px; + } + } + + .card-text span { + color: #ffffff66; + font-size: 12px; + top: 0px; + } + .fee-text{ + border-bottom: 1px solid #ffffff1c; + width: fit-content; + margin: auto; + line-height: 1.45; + padding: 0px 2px; + } + .fiat { + display: block; + font-size: 14px !important; + } + } +} + +.card-text { + .skeleton-loader { + width: 100%; + display: block; + &:first-child { + max-width: 90px; + margin: 15px auto 3px; + } + &:last-child { + margin: 10px auto 3px; + max-width: 55px; + } + } +} + +.title-link, .title-link:hover, .title-link:focus, .title-link:active { + display: block; + margin-bottom: 4px; + text-decoration: none; + color: inherit; +} + +.credit { + color: #7CB342; +} + +.debit { + color: #D81B60; +} \ No newline at end of file diff --git a/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.ts b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.ts new file mode 100644 index 000000000..7bf8e6910 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component.ts @@ -0,0 +1,19 @@ +import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; +import { Observable } from 'rxjs'; +import { PegsVolume } from '../../../interfaces/node-api.interface'; + +@Component({ + selector: 'app-recent-pegs-stats', + templateUrl: './recent-pegs-stats.component.html', + styleUrls: ['./recent-pegs-stats.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class RecentPegsStatsComponent implements OnInit { + @Input() pegsVolume$: Observable; + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.html b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.html new file mode 100644 index 000000000..5758455de --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.html @@ -0,0 +1,42 @@ +
+ +
+
+
Unpeg
+
+
+ {{ unbackedMonths.total }} Unpeg Event +
+
+
+ +
+
Avg Peg Ratio
+
+
+ {{ (unbackedMonths.avg * 100).toFixed(3) }} % +
+
+
+
+
+
+ + +
+
+
Unpeg
+
+
+
+
+ +
+
Avg Peg Ratio
+
+
+
+
+
+
+ diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.scss b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.scss new file mode 100644 index 000000000..72aa390e4 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.scss @@ -0,0 +1,63 @@ +.fee-estimation-container { + display: flex; + justify-content: space-between; + @media (min-width: 376px) { + flex-direction: row; + } + .item { + max-width: 300px; + margin: 0; + width: -webkit-fill-available; + @media (min-width: 376px) { + margin: 0 auto 0px; + } + + .card-title { + margin-bottom: 4px; + color: #4a68b9; + font-size: 10px; + font-size: 1rem; + white-space: nowrap; + } + + .card-text { + font-size: 22px; + span { + font-size: 11px; + position: relative; + top: -2px; + } + .danger { + color: #D81B60; + } + .correct { + color: #7CB342; + } + } + + .card-text span { + color: #ffffff66; + font-size: 12px; + top: 0px; + } + .fee-text{ + width: fit-content; + margin: auto; + line-height: 1.45; + padding: 0px 2px; + } + } +} + +.loading-container{ + min-height: 76px; +} + +.card-text { + .skeleton-loader { + width: 100%; + display: block; + max-width: 90px; + margin: 15px auto 3px; + } +} diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.ts b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.ts new file mode 100644 index 000000000..45a114c1f --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component.ts @@ -0,0 +1,51 @@ +import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; +import { Observable, map } from 'rxjs'; + +@Component({ + selector: 'app-reserves-ratio-stats', + templateUrl: './reserves-ratio-stats.component.html', + styleUrls: ['./reserves-ratio-stats.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ReservesRatioStatsComponent implements OnInit { + @Input() fullHistory$: Observable; + unbackedMonths$: Observable + + constructor() { } + + ngOnInit(): void { + if (!this.fullHistory$) { + return; + } + this.unbackedMonths$ = this.fullHistory$ + .pipe( + map((fullHistory) => { + if (fullHistory.liquidPegs.series.length !== fullHistory.liquidReserves.series.length) { + return { + historyComplete: false, + total: null + }; + } + // Only check the last 3 years + let ratioSeries = fullHistory.liquidReserves.series.map((value: number, index: number) => value / fullHistory.liquidPegs.series[index]); + ratioSeries = ratioSeries.slice(Math.max(ratioSeries.length - 36, 0)); + let total = 0; + let avg = 0; + for (let i = 0; i < ratioSeries.length; i++) { + avg += ratioSeries[i]; + if (ratioSeries[i] < 1) { + total++; + } + } + avg = avg / ratioSeries.length; + return { + historyComplete: true, + total: total, + avg: avg, + }; + }) + ); + + } + +} diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.html b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.html new file mode 100644 index 000000000..64e68624b --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.html @@ -0,0 +1,4 @@ +
+
+
+
diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.scss b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.scss new file mode 100644 index 000000000..9881148fc --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.scss @@ -0,0 +1,6 @@ +.loadingGraphs { + position: absolute; + top: 50%; + left: calc(50% - 16px); + z-index: 100; +} \ No newline at end of file diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.ts b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.ts new file mode 100644 index 000000000..2289f5be1 --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component.ts @@ -0,0 +1,175 @@ +import { Component, ChangeDetectionStrategy, Input, OnChanges, OnInit, HostListener } from '@angular/core'; +import { EChartsOption } from '../../../graphs/echarts'; +import { CurrentPegs } from '../../../interfaces/node-api.interface'; + + +@Component({ + selector: 'app-reserves-ratio', + templateUrl: './reserves-ratio.component.html', + styleUrls: ['./reserves-ratio.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ReservesRatioComponent implements OnInit, OnChanges { + @Input() currentPeg: CurrentPegs; + @Input() currentReserves: CurrentPegs; + ratioChartOptions: EChartsOption; + + height: number | string = '200'; + right: number | string = '10'; + top: number | string = '20'; + left: number | string = '50'; + template: ('widget' | 'advanced') = 'widget'; + isLoading = true; + + ratioChartInitOptions = { + renderer: 'svg' + }; + + constructor() { } + + ngOnInit() { + this.isLoading = true; + } + + ngOnChanges() { + this.updateChartOptions(); + } + + updateChartOptions() { + if (!this.currentPeg || !this.currentReserves || this.currentPeg.amount === '0') { + return; + } + this.ratioChartOptions = this.createChartOptions(this.currentPeg, this.currentReserves); + } + + rendered() { + if (!this.currentPeg || !this.currentReserves) { + return; + } + this.isLoading = false; + } + + createChartOptions(currentPeg: CurrentPegs, currentReserves: CurrentPegs): EChartsOption { + const value = parseFloat(currentReserves.amount) / parseFloat(currentPeg.amount); + const hideMaxAxisLabels = value >= 1.001; + const hideMinAxisLabels = value <= 0.999; + + let axisFontSize = 14; + let pointerLength = '50%'; + let pointerWidth = 16; + let offsetCenter = ['0%', '-22%']; + if (window.innerWidth >= 992) { + axisFontSize = 14; + pointerLength = '50%'; + pointerWidth = 16; + offsetCenter = value >= 1.0007 || value <= 0.9993 ? ['0%', '-30%'] : ['0%', '-22%']; + } else if (window.innerWidth >= 768) { + axisFontSize = 10; + pointerLength = '35%'; + pointerWidth = 12; + offsetCenter = value >= 1.0007 || value <= 0.9993 ? ['0%', '-37%'] : ['0%', '-27%']; + } else if (window.innerWidth >= 450) { + axisFontSize = 14; + pointerLength = '45%'; + pointerWidth = 14; + offsetCenter = value >= 1.0007 || value <= 0.9993 ? ['0%', '-32%'] : ['0%', '-22%']; + } else { + axisFontSize = 10; + pointerLength = '35%'; + pointerWidth = 12; + offsetCenter = value >= 1.0007 || value <= 0.9993 ? ['0%', '-37%'] : ['0%', '-27%']; + } + + return { + series: [ + { + type: 'gauge', + startAngle: 180, + endAngle: 0, + center: ['50%', '75%'], + radius: '100%', + min: 0.999, + max: 1.001, + splitNumber: 2, + axisLine: { + lineStyle: { + width: 6, + color: [ + [0.49, '#D81B60'], + [1, '#7CB342'] + ] + } + }, + axisLabel: { + color: 'inherit', + fontFamily: 'inherit', + fontSize: axisFontSize, + formatter: function (value) { + if (value === 0.999) { + return hideMinAxisLabels ? '' : '99.9%'; + } else if (value === 1.001) { + return hideMaxAxisLabels ? '' : '100.1%'; + } else { + return '100%'; + } + }, + }, + pointer: { + icon: 'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z', + length: pointerLength, + width: pointerWidth, + offsetCenter: offsetCenter, + itemStyle: { + color: 'auto' + } + }, + axisTick: { + length: 12, + lineStyle: { + color: 'auto', + width: 2 + } + }, + splitLine: { + length: 20, + lineStyle: { + color: 'auto', + width: 5 + } + }, + title: { + show: true, + offsetCenter: [0, '-127%'], + fontSize: 18, + color: '#4a68b9', + fontFamily: 'inherit', + fontWeight: 500, + }, + detail: { + fontSize: 25, + offsetCenter: [0, '-0%'], + valueAnimation: true, + fontFamily: 'inherit', + fontWeight: 500, + formatter: function (value) { + return (value * 100).toFixed(3) + '%'; + }, + color: 'inherit' + }, + data: [ + { + value: value, + name: 'Assets vs Liabilities' + } + ] + } + ] + }; + } + + @HostListener('window:resize', ['$event']) + onResize(): void { + this.updateChartOptions(); + } +} + diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.html b/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.html new file mode 100644 index 000000000..65b40f39c --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.html @@ -0,0 +1,29 @@ +
+
+
L-BTC in circulation
+
+
{{ (+currentPeg.amount) / 100000000 | number: '1.2-2' }} L-BTC
+ + As of block {{ currentPeg.lastBlockUpdate }} + +
+
+
+
BTC Holdings
+
+
{{ (+currentReserves.amount) / 100000000 | number: '1.2-2' }} BTC
+ + As of block {{ currentReserves.lastBlockUpdate }} + +
+
+
+ + + +
+
+
+
+
+ diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.scss b/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.scss new file mode 100644 index 000000000..6ffb900ed --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.scss @@ -0,0 +1,74 @@ +.fee-estimation-container { + display: flex; + justify-content: space-between; + @media (min-width: 376px) { + flex-direction: row; + } + .item { + max-width: 150px; + margin: 0; + width: -webkit-fill-available; + @media (min-width: 376px) { + margin: 0 auto 0px; + } + + .card-title { + color: #4a68b9; + font-size: 10px; + margin-bottom: 4px; + font-size: 1rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .card-text { + font-size: 22px; + span { + font-size: 11px; + position: relative; + top: -2px; + } + } + + &:last-child { + margin-bottom: 0; + } + .card-text span { + color: #ffffff66; + font-size: 12px; + top: 0px; + } + .fee-text{ + border-bottom: 1px solid #ffffff1c; + color: #ffffff; + width: fit-content; + margin: auto; + line-height: 1.45; + padding: 0px 2px; + } + .fiat { + display: block; + font-size: 14px !important; + } + } +} + +.loading-container{ + min-height: 76px; +} + +.card-text { + .skeleton-loader { + width: 100%; + display: block; + &:first-child { + max-width: 90px; + margin: 15px auto 3px; + } + &:last-child { + margin: 10px auto 3px; + max-width: 55px; + } + } +} \ No newline at end of file diff --git a/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.ts b/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.ts new file mode 100644 index 000000000..61f2deb8c --- /dev/null +++ b/frontend/src/app/components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component.ts @@ -0,0 +1,24 @@ +import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; +import { Observable } from 'rxjs'; +import { Env, StateService } from '../../../services/state.service'; +import { CurrentPegs } from '../../../interfaces/node-api.interface'; + +@Component({ + selector: 'app-reserves-supply-stats', + templateUrl: './reserves-supply-stats.component.html', + styleUrls: ['./reserves-supply-stats.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ReservesSupplyStatsComponent implements OnInit { + @Input() currentReserves$: Observable; + @Input() currentPeg$: Observable; + + env: Env; + + constructor(private stateService: StateService) { } + + ngOnInit(): void { + this.env = this.stateService.env; + } + +} diff --git a/frontend/src/app/components/master-page/master-page.component.html b/frontend/src/app/components/master-page/master-page.component.html index 8863b335f..828ece1e5 100644 --- a/frontend/src/app/components/master-page/master-page.component.html +++ b/frontend/src/app/components/master-page/master-page.component.html @@ -5,7 +5,7 @@
- +
@@ -18,7 +18,7 @@
- +
@@ -48,9 +48,16 @@
+
diff --git a/frontend/src/app/components/master-page/master-page.component.scss b/frontend/src/app/components/master-page/master-page.component.scss index b82d973de..1d437cdaf 100644 --- a/frontend/src/app/components/master-page/master-page.component.scss +++ b/frontend/src/app/components/master-page/master-page.component.scss @@ -29,6 +29,16 @@ li.nav-item { padding-left: 8px; padding-right: 8px; } + @media (max-width: 429px) { + margin: auto 5px; + padding-left: 6px; + padding-right: 6px; + } + @media (max-width: 369px) { + margin: auto 3px; + padding-left: 4px; + padding-right: 4px; + } } @media (min-width: 992px) { @@ -64,7 +74,10 @@ li.nav-item { } a { font-size: 0.8em; - @media (min-width: 375px) { + @media (min-width: 370px) { + font-size: 0.9em; + } + @media (min-width: 430px) { font-size: 1em; } } @@ -198,7 +211,15 @@ nav { margin: 24px 0px 0px -15px; font-size: 8px; @media (max-width: 767.98px) { - margin: 33px 0px 0px -19px; + margin: 30px 0px 0px -19px; + font-size: 7px; + } + @media (max-width: 3429px) { + margin: 25px 0px 0px -19px; + font-size: 7px; + } + @media (max-width: 369px) { + margin: 20px 0px 0px -19px; font-size: 7px; } } @@ -238,4 +259,15 @@ nav { main { transition: 0.2s; transition-property: max-width; -} \ No newline at end of file +} + +// empty sidenav +.empty-sidenav { + z-index: 1; + background-color: transparent; + width: 0px; + height: calc(100vh - 65px); + position: sticky; + top: 65px; + padding-bottom: 20px; +} diff --git a/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.html b/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.html index 503f2e38d..6fb8dd4d6 100644 --- a/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.html +++ b/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.html @@ -1,9 +1,14 @@ diff --git a/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.ts b/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.ts index 226be5210..29825491c 100644 --- a/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.ts +++ b/frontend/src/app/components/mempool-block-overview/mempool-block-overview.component.ts @@ -3,11 +3,14 @@ import { Component, ComponentRef, ViewChild, HostListener, Input, Output, EventE import { StateService } from '../../services/state.service'; import { MempoolBlockDelta, TransactionStripped } from '../../interfaces/websocket.interface'; import { BlockOverviewGraphComponent } from '../../components/block-overview-graph/block-overview-graph.component'; -import { Subscription, BehaviorSubject, merge, of } from 'rxjs'; -import { switchMap, filter } from 'rxjs/operators'; +import { Subscription, BehaviorSubject, merge, of, timer } from 'rxjs'; +import { switchMap, filter, concatMap, map } from 'rxjs/operators'; import { WebsocketService } from '../../services/websocket.service'; import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe'; import { Router } from '@angular/router'; +import { Color } from '../block-overview-graph/sprite-types'; +import TxView from '../block-overview-graph/tx-view'; +import { FilterMode } from '../../shared/filters.utils'; @Component({ selector: 'app-mempool-block-overview', @@ -16,6 +19,11 @@ import { Router } from '@angular/router'; }) export class MempoolBlockOverviewComponent implements OnInit, OnDestroy, OnChanges, AfterViewInit { @Input() index: number; + @Input() resolution = 86; + @Input() showFilters: boolean = false; + @Input() overrideColors: ((tx: TxView) => Color) | null = null; + @Input() filterFlags: bigint | undefined = undefined; + @Input() filterMode: FilterMode = 'and'; @Output() txPreviewEvent = new EventEmitter(); @ViewChild('blockGraph') blockGraph: BlockOverviewGraphComponent; @@ -29,7 +37,11 @@ export class MempoolBlockOverviewComponent implements OnInit, OnDestroy, OnChang poolDirection: string = 'left'; blockSub: Subscription; - deltaSub: Subscription; + rateLimit = 1000; + private lastEventTime = Date.now() - this.rateLimit; + private subId = 0; + + firstLoad: boolean = true; constructor( public stateService: StateService, @@ -49,20 +61,82 @@ export class MempoolBlockOverviewComponent implements OnInit, OnDestroy, OnChang ngAfterViewInit(): void { this.blockSub = merge( - of(true), - this.stateService.connectionState$.pipe(filter((state) => state === 2)) - ) - .pipe(switchMap(() => this.stateService.mempoolBlockTransactions$)) - .subscribe((transactionsStripped) => { - this.replaceBlock(transactionsStripped); - }); - this.deltaSub = this.stateService.mempoolBlockDelta$.subscribe((delta) => { - this.updateBlock(delta); + this.stateService.mempoolBlockTransactions$, + this.stateService.mempoolBlockDelta$, + ).pipe( + concatMap(update => { + const now = Date.now(); + const timeSinceLastEvent = now - this.lastEventTime; + this.lastEventTime = Math.max(now, this.lastEventTime + this.rateLimit); + + const subId = this.subId; + + // If time since last event is less than X seconds, delay this event + if (timeSinceLastEvent < this.rateLimit) { + return timer(this.rateLimit - timeSinceLastEvent).pipe( + // Emit the event after the timer + map(() => ({ update, subId })) + ); + } else { + // If enough time has passed, emit the event immediately + return of({ update, subId }); + } + }) + ).subscribe(({ update, subId }) => { + // discard stale updates after a block transition + if (subId !== this.subId) { + return; + } + // process update + if (update['added']) { + // delta + this.updateBlock(update as MempoolBlockDelta); + } else { + const transactionsStripped = update as TransactionStripped[]; + // new transactions + if (this.firstLoad) { + this.replaceBlock(transactionsStripped); + } else { + const inOldBlock = {}; + const inNewBlock = {}; + const added: TransactionStripped[] = []; + const changed: { txid: string, rate: number | undefined, flags: number, acc: boolean | undefined }[] = []; + const removed: string[] = []; + for (const tx of transactionsStripped) { + inNewBlock[tx.txid] = true; + } + for (const txid of Object.keys(this.blockGraph?.scene?.txs || {})) { + inOldBlock[txid] = true; + if (!inNewBlock[txid]) { + removed.push(txid); + } + } + for (const tx of transactionsStripped) { + if (!inOldBlock[tx.txid]) { + added.push(tx); + } else { + changed.push({ + txid: tx.txid, + rate: tx.rate, + flags: tx.flags, + acc: tx.acc + }); + } + } + this.updateBlock({ + removed, + changed, + added + }); + } + } }); } ngOnChanges(changes): void { if (changes.index) { + this.subId++; + this.firstLoad = true; if (this.blockGraph) { this.blockGraph.clear(changes.index.currentValue > changes.index.previousValue ? this.chainDirection : this.poolDirection); } @@ -73,7 +147,6 @@ export class MempoolBlockOverviewComponent implements OnInit, OnDestroy, OnChang ngOnDestroy(): void { this.blockSub.unsubscribe(); - this.deltaSub.unsubscribe(); this.timeLtrSubscription.unsubscribe(); this.websocketService.stopTrackMempoolBlock(); } diff --git a/frontend/src/app/components/mempool-block-view/mempool-block-view.component.html b/frontend/src/app/components/mempool-block-view/mempool-block-view.component.html new file mode 100644 index 000000000..2fafb31cd --- /dev/null +++ b/frontend/src/app/components/mempool-block-view/mempool-block-view.component.html @@ -0,0 +1,5 @@ +
+
+ +
+
\ No newline at end of file diff --git a/frontend/src/app/components/mempool-block-view/mempool-block-view.component.scss b/frontend/src/app/components/mempool-block-view/mempool-block-view.component.scss new file mode 100644 index 000000000..782d416d8 --- /dev/null +++ b/frontend/src/app/components/mempool-block-view/mempool-block-view.component.scss @@ -0,0 +1,22 @@ +.block-wrapper { + width: 100vw; + height: 100vh; + background: #181b2d; +} + +.block-container { + flex-grow: 0; + flex-shrink: 0; + width: 100vw; + max-width: 100vh; + height: 100vh; + padding: 0; + margin: auto; + display: flex; + justify-content: center; + align-items: center; + + * { + flex-grow: 1; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/mempool-block-view/mempool-block-view.component.ts b/frontend/src/app/components/mempool-block-view/mempool-block-view.component.ts new file mode 100644 index 000000000..a671033cf --- /dev/null +++ b/frontend/src/app/components/mempool-block-view/mempool-block-view.component.ts @@ -0,0 +1,92 @@ +import { Component, OnInit, OnDestroy, HostListener } from '@angular/core'; +import { ActivatedRoute, ParamMap } from '@angular/router'; +import { Subscription, filter, map, switchMap, tap } from 'rxjs'; +import { StateService } from '../../services/state.service'; +import { WebsocketService } from '../../services/websocket.service'; + +function bestFitResolution(min, max, n): number { + const target = (min + max) / 2; + let bestScore = Infinity; + let best = null; + for (let i = min; i <= max; i++) { + const remainder = (n % i); + if (remainder < bestScore || (remainder === bestScore && (Math.abs(i - target) < Math.abs(best - target)))) { + bestScore = remainder; + best = i; + } + } + return best; +} + +@Component({ + selector: 'app-mempool-block-view', + templateUrl: './mempool-block-view.component.html', + styleUrls: ['./mempool-block-view.component.scss'] +}) +export class MempoolBlockViewComponent implements OnInit, OnDestroy { + autofit: boolean = false; + resolution: number = 80; + index: number = 0; + filterFlags: bigint | null = 0n; + + routeParamsSubscription: Subscription; + queryParamsSubscription: Subscription; + + constructor( + private route: ActivatedRoute, + private websocketService: WebsocketService, + public stateService: StateService, + ) { } + + ngOnInit(): void { + window['setFlags'] = this.setFilterFlags.bind(this); + + this.websocketService.want(['blocks', 'mempool-blocks']); + + this.routeParamsSubscription = this.route.paramMap + .pipe( + switchMap((params: ParamMap) => { + this.index = parseInt(params.get('index'), 10) || 0; + return this.stateService.mempoolBlocks$ + .pipe( + map((blocks) => { + if (!blocks.length) { + return [{ index: 0, blockSize: 0, blockVSize: 0, feeRange: [0, 0], medianFee: 0, nTx: 0, totalFees: 0 }]; + } + return blocks; + }), + filter((mempoolBlocks) => mempoolBlocks.length > 0), + tap((mempoolBlocks) => { + while (!mempoolBlocks[this.index]) { + this.index--; + } + }) + ); + }) + ).subscribe(); + + this.queryParamsSubscription = this.route.queryParams.subscribe((params) => { + this.autofit = params.autofit === 'true'; + if (this.autofit) { + this.onResize(); + } + }); + } + + + @HostListener('window:resize', ['$event']) + onResize(): void { + if (this.autofit) { + this.resolution = bestFitResolution(64, 96, Math.min(window.innerWidth, window.innerHeight)); + } + } + + ngOnDestroy(): void { + this.routeParamsSubscription.unsubscribe(); + this.queryParamsSubscription.unsubscribe(); + } + + setFilterFlags(flags: bigint | null) { + this.filterFlags = flags; + } +} diff --git a/frontend/src/app/components/mempool-block/mempool-block.component.html b/frontend/src/app/components/mempool-block/mempool-block.component.html index b089a6d74..d2aa1aed2 100644 --- a/frontend/src/app/components/mempool-block/mempool-block.component.html +++ b/frontend/src/app/components/mempool-block/mempool-block.component.html @@ -46,7 +46,9 @@
- +
+ +
diff --git a/frontend/src/app/components/mempool-block/mempool-block.component.ts b/frontend/src/app/components/mempool-block/mempool-block.component.ts index c11bedacd..89fb97dad 100644 --- a/frontend/src/app/components/mempool-block/mempool-block.component.ts +++ b/frontend/src/app/components/mempool-block/mempool-block.component.ts @@ -1,4 +1,4 @@ -import { Component, OnInit, OnDestroy, ChangeDetectionStrategy } from '@angular/core'; +import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { StateService } from '../../services/state.service'; import { ActivatedRoute, ParamMap } from '@angular/router'; import { switchMap, map, tap, filter } from 'rxjs/operators'; @@ -28,6 +28,7 @@ export class MempoolBlockComponent implements OnInit, OnDestroy { public stateService: StateService, private seoService: SeoService, private websocketService: WebsocketService, + private cd: ChangeDetectorRef, ) { this.webGlEnabled = detectWebGL(); } @@ -63,6 +64,7 @@ export class MempoolBlockComponent implements OnInit, OnDestroy { }), tap(() => { this.stateService.markBlock$.next({ mempoolBlockIndex: this.mempoolBlockIndex }); + this.websocketService.startTrackMempoolBlock(this.mempoolBlockIndex); }) ); @@ -73,6 +75,7 @@ export class MempoolBlockComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.stateService.markBlock$.next({}); + this.websocketService.stopTrackMempoolBlock(); } getOrdinal(mempoolBlock: MempoolBlock): string { diff --git a/frontend/src/app/components/mempool-blocks/mempool-blocks.component.html b/frontend/src/app/components/mempool-blocks/mempool-blocks.component.html index 59d35c91e..fca1ce215 100644 --- a/frontend/src/app/components/mempool-blocks/mempool-blocks.component.html +++ b/frontend/src/app/components/mempool-blocks/mempool-blocks.component.html @@ -34,7 +34,7 @@ - +
diff --git a/frontend/src/app/components/mempool-blocks/mempool-blocks.component.ts b/frontend/src/app/components/mempool-blocks/mempool-blocks.component.ts index 484389cd3..61e62f642 100644 --- a/frontend/src/app/components/mempool-blocks/mempool-blocks.component.ts +++ b/frontend/src/app/components/mempool-blocks/mempool-blocks.component.ts @@ -90,13 +90,17 @@ export class MempoolBlocksComponent implements OnInit, OnChanges, OnDestroy { ) { } enabledMiningInfoIfNeeded(url) { - this.showMiningInfo = url.indexOf('/mining') !== -1; + this.showMiningInfo = url.includes('/mining') || url.includes('/acceleration'); this.cd.markForCheck(); // Need to update the view asap } ngOnInit() { this.chainTip = this.stateService.latestBlockHeight; + const width = this.containerOffset + (this.stateService.env.MEMPOOL_BLOCKS_AMOUNT) * this.blockOffset; + this.mempoolWidth = width; + this.widthChange.emit(this.mempoolWidth); + if (['', 'testnet', 'signet'].includes(this.stateService.network)) { this.enabledMiningInfoIfNeeded(this.location.path()); this.location.onUrlChange((url) => this.enabledMiningInfoIfNeeded(url)); @@ -161,11 +165,11 @@ export class MempoolBlocksComponent implements OnInit, OnChanges, OnDestroy { return this.mempoolBlocks; }), tap(() => { - this.cd.markForCheck(); const width = this.containerOffset + this.mempoolBlocks.length * this.blockOffset; if (this.mempoolWidth !== width) { this.mempoolWidth = width; this.widthChange.emit(this.mempoolWidth); + this.cd.markForCheck(); } }) ); @@ -215,11 +219,13 @@ export class MempoolBlocksComponent implements OnInit, OnChanges, OnDestroy { if (isNewBlock && (block?.extras?.similarity == null || block?.extras?.similarity > 0.5) && !this.tabHidden) { this.blockIndex++; } + this.cd.markForCheck(); }); this.chainTipSubscription = this.stateService.chainTip$.subscribe((height) => { if (this.chainTip === -1) { this.chainTip = height; + this.cd.markForCheck(); } }); @@ -257,6 +263,7 @@ export class MempoolBlocksComponent implements OnInit, OnChanges, OnDestroy { this.blockPadding = 0.24 * this.blockWidth; this.containerOffset = 0.32 * this.blockWidth; this.blockOffset = this.blockWidth + this.blockPadding; + this.cd.markForCheck(); } } @@ -275,6 +282,7 @@ export class MempoolBlocksComponent implements OnInit, OnChanges, OnDestroy { onResize(): void { this.animateEntry = false; this.reduceEmptyBlocksToFitScreen(this.mempoolEmptyBlocks); + this.cd.markForCheck(); } trackByFn(index: number, block: MempoolBlock) { diff --git a/frontend/src/app/components/mempool-graph/mempool-graph.component.ts b/frontend/src/app/components/mempool-graph/mempool-graph.component.ts index 6c9795c89..79c426fd6 100644 --- a/frontend/src/app/components/mempool-graph/mempool-graph.component.ts +++ b/frontend/src/app/components/mempool-graph/mempool-graph.component.ts @@ -1,11 +1,12 @@ import { Component, OnInit, Input, Inject, LOCALE_ID, ChangeDetectionStrategy, OnChanges } from '@angular/core'; import { VbytesPipe } from '../../shared/pipes/bytes-pipe/vbytes.pipe'; import { WuBytesPipe } from '../../shared/pipes/bytes-pipe/wubytes.pipe'; +import { AmountShortenerPipe } from '../../shared/pipes/amount-shortener.pipe'; import { formatNumber } from '@angular/common'; import { OptimizedMempoolStats } from '../../interfaces/node-api.interface'; import { StateService } from '../../services/state.service'; import { StorageService } from '../../services/storage.service'; -import { EChartsOption } from 'echarts'; +import { EChartsOption } from '../../graphs/echarts'; import { feeLevels, chartColors } from '../../app.constants'; import { download, formatterXAxis, formatterXAxisLabel } from '../../shared/graphs.utils'; @@ -26,6 +27,7 @@ export class MempoolGraphComponent implements OnInit, OnChanges { @Input() data: any[]; @Input() filterSize = 100000; @Input() limitFilterFee = 1; + @Input() hideCount: boolean = true; @Input() height: number | string = 200; @Input() top: number | string = 20; @Input() right: number | string = 10; @@ -50,10 +52,13 @@ export class MempoolGraphComponent implements OnInit, OnChanges { inverted: boolean; chartInstance: any = undefined; weightMode: boolean = false; + isWidget: boolean = false; + showCount: boolean = false; constructor( private vbytesPipe: VbytesPipe, private wubytesPipe: WuBytesPipe, + private amountShortenerPipe: AmountShortenerPipe, private stateService: StateService, private storageService: StorageService, @Inject(LOCALE_ID) private locale: string, @@ -62,12 +67,16 @@ export class MempoolGraphComponent implements OnInit, OnChanges { ngOnInit(): void { this.isLoading = true; this.inverted = this.storageService.getValue('inverted-graph') === 'true'; + this.isWidget = this.template === 'widget'; + this.showCount = !this.isWidget && !this.hideCount; } - ngOnChanges() { + ngOnChanges(changes) { if (!this.data) { return; } + this.isWidget = this.template === 'widget'; + this.showCount = !this.isWidget && !this.hideCount; this.windowPreference = this.windowPreferenceOverride ? this.windowPreferenceOverride : this.storageService.getValue('graphWindowPreference'); this.mempoolVsizeFeesData = this.handleNewMempoolData(this.data.concat([])); this.mountFeeChart(); @@ -96,10 +105,12 @@ export class MempoolGraphComponent implements OnInit, OnChanges { mempoolStats.reverse(); const labels = mempoolStats.map(stats => stats.added); const finalArrayVByte = this.generateArray(mempoolStats); + const finalArrayCount = this.generateCountArray(mempoolStats); return { labels: labels, - series: finalArrayVByte + series: finalArrayVByte, + countSeries: finalArrayCount, }; } @@ -124,9 +135,13 @@ export class MempoolGraphComponent implements OnInit, OnChanges { return finalArray; } + generateCountArray(mempoolStats: OptimizedMempoolStats[]) { + return mempoolStats.filter(stats => stats.count > 0).map(stats => [stats.added * 1000, stats.count]); + } + mountFeeChart() { this.orderLevels(); - const { series } = this.mempoolVsizeFeesData; + const { series, countSeries } = this.mempoolVsizeFeesData; const seriesGraph = []; const newColors = []; @@ -178,6 +193,29 @@ export class MempoolGraphComponent implements OnInit, OnChanges { }); } } + if (this.showCount) { + newColors.push('white'); + seriesGraph.push({ + zlevel: 1, + yAxisIndex: 1, + name: 'count', + type: 'line', + stack: 'count', + smooth: false, + markPoint: false, + lineStyle: { + width: 2, + opacity: 1, + }, + symbol: 'none', + silent: true, + areaStyle: { + color: null, + opacity: 0, + }, + data: countSeries, + }); + } this.mempoolVsizeFeesOptions = { series: this.inverted ? [...seriesGraph].reverse() : seriesGraph, @@ -192,7 +230,7 @@ export class MempoolGraphComponent implements OnInit, OnChanges { positions[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 100; return positions; }, - extraCssText: `width: ${(this.template === 'advanced') ? '275px' : '200px'}; + extraCssText: `width: ${(this.template === 'advanced') ? '300px' : '200px'}; background: transparent; border: none; box-shadow: none;`, @@ -201,7 +239,11 @@ export class MempoolGraphComponent implements OnInit, OnChanges { label: { formatter: (params: any) => { if (params.axisDimension === 'y') { - return this.vbytesPipe.transform(params.value, 2, 'vB', 'MvB', true) + if (params.axisIndex === 0) { + return this.vbytesPipe.transform(params.value, 2, 'vB', 'MvB', true); + } else { + return this.amountShortenerPipe.transform(params.value, 2, undefined, true); + } } else { return formatterXAxis(this.locale, this.windowPreference, params.value); } @@ -212,11 +254,15 @@ export class MempoolGraphComponent implements OnInit, OnChanges { const axisValueLabel: string = formatterXAxis(this.locale, this.windowPreference, params[0].axisValue); const { totalValue, totalValueArray } = this.getTotalValues(params); const itemFormatted = []; - let totalParcial = 0; + let sum = 0; let progressPercentageText = ''; - const items = this.inverted ? [...params].reverse() : params; + let countItem; + let items = this.inverted ? [...params].reverse() : params; + if (items[items.length - 1].seriesName === 'count') { + countItem = items.pop(); + } items.map((item: any, index: number) => { - totalParcial += item.value[1]; + sum += item.value[1]; const progressPercentage = (item.value[1] / totalValue) * 100; const progressPercentageSum = (totalValueArray[index] / totalValue) * 100; let activeItemClass = ''; @@ -233,7 +279,7 @@ export class MempoolGraphComponent implements OnInit, OnChanges { % - ${this.vbytesPipe.transform(totalParcial, 2, 'vB', 'MvB', false)} + ${this.vbytesPipe.transform(sum, 2, 'vB', 'MvB', false)}
@@ -257,12 +303,12 @@ export class MempoolGraphComponent implements OnInit, OnChanges { - ${this.vbytesPipe.transform(item.value[1], 2, 'vB', 'MvB', false)} + ${(item.value[1] / 1_000_000).toFixed(2)} MvB - ${this.vbytesPipe.transform(totalValueArray[index], 2, 'vB', 'MvB', false)} + ${(totalValueArray[index] / 1_000_000).toFixed(2)} MvB @@ -276,6 +322,7 @@ export class MempoolGraphComponent implements OnInit, OnChanges { `); }); const classActive = (this.template === 'advanced') ? 'fees-wrapper-tooltip-chart-advanced' : ''; + const titleCount = $localize`Count`; const titleRange = $localize`Range`; const titleSize = $localize`:@@7faaaa08f56427999f3be41df1093ce4089bbd75:Size`; const titleSum = $localize`Sum`; @@ -286,6 +333,25 @@ export class MempoolGraphComponent implements OnInit, OnChanges { ${this.vbytesPipe.transform(totalValue, 2, 'vB', 'MvB', false)}
+ ` + + (this.showCount && countItem ? ` + + + + + + + +
+ + + ${titleCount} + + + ${this.amountShortenerPipe.transform(countItem.value[1], 2, undefined, true)} +
+ ` : '') + + ` @@ -305,12 +371,12 @@ export class MempoolGraphComponent implements OnInit, OnChanges { `; } }, - dataZoom: (this.template === 'widget' && this.isMobile()) ? null : [{ + dataZoom: (this.isWidget && this.isMobile()) ? null : [{ type: 'inside', realtime: true, - zoomLock: (this.template === 'widget') ? true : false, + zoomLock: (this.isWidget) ? true : false, zoomOnMouseWheel: (this.template === 'advanced') ? true : false, - moveOnMouseMove: (this.template === 'widget') ? true : false, + moveOnMouseMove: (this.isWidget) ? true : false, maxSpan: 100, minSpan: 10, }, { @@ -339,7 +405,7 @@ export class MempoolGraphComponent implements OnInit, OnChanges { }, xAxis: [ { - name: this.template === 'widget' ? '' : formatterXAxisLabel(this.locale, this.windowPreference), + name: this.isWidget ? '' : formatterXAxisLabel(this.locale, this.windowPreference), nameLocation: 'middle', nameTextStyle: { padding: [20, 0, 0, 0], @@ -357,7 +423,7 @@ export class MempoolGraphComponent implements OnInit, OnChanges { }, } ], - yAxis: { + yAxis: [{ type: 'value', axisLine: { onZero: false }, axisLabel: { @@ -371,7 +437,17 @@ export class MempoolGraphComponent implements OnInit, OnChanges { opacity: 0.25, } } - }, + }, this.showCount ? { + type: 'value', + position: 'right', + axisLine: { onZero: false }, + axisLabel: { + formatter: (value: number) => (`${this.amountShortenerPipe.transform(value, 2, undefined, true)}`), + }, + splitLine: { + show: false, + } + } : null], }; } diff --git a/frontend/src/app/components/menu/menu.component.html b/frontend/src/app/components/menu/menu.component.html index e89ace64a..c72016ef5 100644 --- a/frontend/src/app/components/menu/menu.component.html +++ b/frontend/src/app/components/menu/menu.component.html @@ -2,12 +2,23 @@ - - + @@ -104,13 +104,13 @@ - + - - + - - - + + + @@ -314,9 +324,13 @@ - - - + + + @@ -506,21 +520,27 @@   - + - - - + + + diff --git a/frontend/src/app/components/transaction/transaction.component.scss b/frontend/src/app/components/transaction/transaction.component.scss index 2e076600e..d78edf85b 100644 --- a/frontend/src/app/components/transaction/transaction.component.scss +++ b/frontend/src/app/components/transaction/transaction.component.scss @@ -60,8 +60,13 @@ top: -1px; } +.badge.badge-accelerated { + background-color: #653b9c; + color: white; +} + .btn-small-height { - line-height: 1.1; + line-height: 1; } .arrow-green { @@ -152,6 +157,16 @@ @media (min-width: 768px){ display: inline-block; } + @media (max-width: 425px){ + display: flex; + flex-direction: column; + } +} + +.effective-fee-rating { + @media (max-width: 767px){ + margin-right: 0px !important; + } } .title { @@ -169,7 +184,7 @@ } } -.details-button, .flow-toggle { +.details-button, .flow-toggle, .accelerator-toggle { margin-top: -5px; margin-left: 10px; @media (min-width: 768px){ @@ -218,8 +233,33 @@ } } -.link.accelerator { - cursor: pointer; +.alert-purple { + background-color: #5c3a88; + width: 100%; +} + +// Blinking block +@keyframes shadowyBackground { + 0% { + box-shadow: 0px 0px 20px rgba(#eba814, 1); + } + 50% { + box-shadow: 0px 0px 20px rgba(#eba814, .3); + } + 100% { + box-shadow: 0px 0px 20px rgba(#ffae00, 1); + } +} + +.blink-bg { + color: #fff; + background: repeating-linear-gradient(#daad0a 0%, #daad0a 5%, #987805 100%) !important; + animation: shadowyBackground 1s infinite; + box-shadow: 0px 0px 20px rgba(#eba814, 1); + transition: 100ms all ease-in; + margin-right: 8px; + font-size: 16px; + border: 1px solid gold; } .eta { @@ -234,7 +274,6 @@ .accelerate { display: flex !important; align-self: auto; - margin-top: 3px; margin-left: auto; background-color: #653b9c; @media (max-width: 849px) { diff --git a/frontend/src/app/components/transaction/transaction.component.ts b/frontend/src/app/components/transaction/transaction.component.ts index 505c4686d..60797a9a1 100644 --- a/frontend/src/app/components/transaction/transaction.component.ts +++ b/frontend/src/app/components/transaction/transaction.component.ts @@ -7,7 +7,6 @@ import { catchError, retryWhen, delay, - map, mergeMap, tap } from 'rxjs/operators'; @@ -21,11 +20,13 @@ import { ApiService } from '../../services/api.service'; import { SeoService } from '../../services/seo.service'; import { StorageService } from '../../services/storage.service'; import { seoDescriptionNetwork } from '../../shared/common.utils'; -import { BlockExtended, CpfpInfo, RbfTree, MempoolPosition, DifficultyAdjustment } from '../../interfaces/node-api.interface'; +import { BlockExtended, CpfpInfo, RbfTree, MempoolPosition, DifficultyAdjustment, Acceleration } from '../../interfaces/node-api.interface'; import { LiquidUnblinding } from './liquid-ublinding'; import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe'; import { Price, PriceService } from '../../services/price.service'; import { isFeatureActive } from '../../bitcoin.utils'; +import { ServicesApiServices } from '../../services/services-api.service'; +import { EnterpriseService } from '../../services/enterprise.service'; @Component({ selector: 'app-transaction', @@ -49,6 +50,7 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { fetchCpfpSubscription: Subscription; fetchRbfSubscription: Subscription; fetchCachedTxSubscription: Subscription; + fetchAccelerationSubscription: Subscription; txReplacedSubscription: Subscription; txRbfInfoSubscription: Subscription; mempoolPositionSubscription: Subscription; @@ -62,10 +64,14 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { rbfReplaces: string[]; rbfInfo: RbfTree; cpfpInfo: CpfpInfo | null; + accelerationInfo: Acceleration | null = null; + sigops: number | null; + adjustedVsize: number | null; showCpfpDetails = false; fetchCpfp$ = new Subject(); fetchRbfHistory$ = new Subject(); fetchCachedTx$ = new Subject(); + fetchAcceleration$ = new Subject(); isCached: boolean = false; now = Date.now(); da$: Observable; @@ -90,7 +96,7 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { rbfEnabled: boolean; taprootEnabled: boolean; hasEffectiveFeeRate: boolean; - accelerateCtaType: 'alert' | 'button' = 'alert'; + accelerateCtaType: 'alert' | 'button' = 'button'; acceleratorAvailable: boolean = this.stateService.env.OFFICIAL_MEMPOOL_SPACE && this.stateService.env.ACCELERATOR && this.stateService.network === ''; showAccelerationSummary = false; scrollIntoAccelPreview = false; @@ -108,14 +114,18 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { private websocketService: WebsocketService, private audioService: AudioService, private apiService: ApiService, + private servicesApiService: ServicesApiServices, private seoService: SeoService, private priceService: PriceService, - private storageService: StorageService + private storageService: StorageService, + private enterpriseService: EnterpriseService, ) {} ngOnInit() { this.acceleratorAvailable = this.stateService.env.OFFICIAL_MEMPOOL_SPACE && this.stateService.env.ACCELERATOR && this.stateService.network === ''; + this.enterpriseService.page(); + this.websocketService.want(['blocks', 'mempool-blocks']); this.stateService.networkChanged$.subscribe( (network) => { @@ -124,7 +134,7 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { } ); - this.accelerateCtaType = (this.storageService.getValue('accel-cta-type') as 'alert' | 'button') ?? 'alert'; + this.accelerateCtaType = (this.storageService.getValue('accel-cta-type') as 'alert' | 'button') ?? 'button'; this.setFlowEnabled(); this.flowPrefSubscription = this.stateService.hideFlow.subscribe((hide) => { @@ -236,6 +246,26 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { } }); + this.fetchAccelerationSubscription = this.fetchAcceleration$.pipe( + filter(() => this.stateService.env.ACCELERATOR === true), + tap(() => { + this.accelerationInfo = null; + }), + switchMap((blockHash: string) => { + return this.servicesApiService.getAccelerationHistory$({ blockHash }); + }), + catchError(() => { + return of(null); + }) + ).subscribe((accelerationHistory) => { + for (const acceleration of accelerationHistory) { + if (acceleration.txid === this.txId && (acceleration.status === 'completed' || acceleration.status === 'mined') && acceleration.feePaid > 0) { + acceleration.acceleratedFee = Math.max(acceleration.effectiveFee, acceleration.effectiveFee + acceleration.feePaid - acceleration.baseFee - acceleration.vsizeFee); + this.accelerationInfo = acceleration; + } + } + }); + this.mempoolPositionSubscription = this.stateService.mempoolTxPosition$.subscribe(txPosition => { this.now = Date.now(); if (txPosition && txPosition.txid === this.txId && txPosition.position) { @@ -288,7 +318,9 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { this.seoService.setTitle( $localize`:@@bisq.transaction.browser-title:Transaction: ${this.txId}:INTERPOLATION:` ); - this.seoService.setDescription($localize`:@@meta.description.bitcoin.transaction:Get real-time status, addresses, fees, script info, and more for ${this.stateService.network==='liquid'||this.stateService.network==='liquidtestnet'?'Liquid':'Bitcoin'}${seoDescriptionNetwork(this.stateService.network)} transaction with txid {txid}.`); + const network = this.stateService.network === 'liquid' || this.stateService.network === 'liquidtestnet' ? 'Liquid' : 'Bitcoin'; + const seoDescription = seoDescriptionNetwork(this.stateService.network); + this.seoService.setDescription($localize`:@@meta.description.bitcoin.transaction:Get real-time status, addresses, fees, script info, and more for ${network}${seoDescription} transaction with txid ${this.txId}.`); this.resetTransaction(); return merge( of(true), @@ -343,6 +375,10 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { if (tx.fee === undefined) { this.tx.fee = 0; } + if (this.tx.sigops != null) { + this.sigops = this.tx.sigops; + this.adjustedVsize = Math.max(this.tx.weight / 4, this.sigops * 5); + } this.tx.feePerVsize = tx.fee / (tx.weight / 4); this.isLoadingTx = false; this.error = undefined; @@ -359,6 +395,7 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { this.getTransactionTime(); } } else { + this.fetchAcceleration$.next(tx.status.block_hash); this.transactionTime = 0; } @@ -410,7 +447,12 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { block_time: block.timestamp, }; this.stateService.markBlock$.next({ blockHeight: block.height }); - this.audioService.playSound('magic'); + if (this.tx.acceleration || (this.accelerationInfo && ['accelerating', 'mined', 'completed'].includes(this.accelerationInfo.status))) { + this.audioService.playSound('wind-chimes-harp-ascend'); + } else { + this.audioService.playSound('magic'); + } + this.fetchAcceleration$.next(block.id); } }); @@ -422,6 +464,8 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { } this.rbfTransaction = rbfTransaction; this.replaced = true; + this.stateService.markBlock$.next({}); + if (rbfTransaction && !this.tx) { this.fetchCachedTx$.next(this.txId); } @@ -468,7 +512,7 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { } } } - if (!found && txFeePerVSize < mempoolBlocks[mempoolBlocks.length - 1].feeRange[0]) { + if (!found && mempoolBlocks.length && txFeePerVSize < mempoolBlocks[mempoolBlocks.length - 1].feeRange[0]) { this.txInBlockIndex = 7; } }); @@ -487,6 +531,7 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { if (!this.txId) { return; } + this.enterpriseService.goal(8); this.showAccelerationSummary = true && this.acceleratorAvailable; this.scrollIntoAccelPreview = !this.scrollIntoAccelPreview; return false; @@ -541,6 +586,10 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { } this.cpfpInfo = cpfpInfo; + if (this.cpfpInfo.adjustedVsize && this.cpfpInfo.sigops != null) { + this.sigops = this.cpfpInfo.sigops; + this.adjustedVsize = this.cpfpInfo.adjustedVsize; + } this.hasEffectiveFeeRate = hasRelatives || (this.tx.effectiveFeePerVsize && (Math.abs(this.tx.effectiveFeePerVsize - this.tx.feePerVsize) > 0.01)); } @@ -567,10 +616,13 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { this.replaced = false; this.transactionTime = -1; this.cpfpInfo = null; + this.adjustedVsize = null; + this.sigops = null; this.hasEffectiveFeeRate = false; this.rbfInfo = null; this.rbfReplaces = []; this.showCpfpDetails = false; + this.accelerationInfo = null; this.txInBlockIndex = null; this.mempoolPosition = null; document.body.scrollTo(0, 0); @@ -619,10 +671,14 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { // simulate normal anchor fragment behavior applyFragment(): void { const anchor = Array.from(this.fragmentParams.entries()).find(([frag, value]) => value === ''); - if (anchor) { - const anchorElement = document.getElementById(anchor[0]); - if (anchorElement) { - anchorElement.scrollIntoView(); + if (anchor?.length) { + if (anchor[0] === 'accelerate') { + setTimeout(this.onAccelerateClicked.bind(this), 100); + } else { + const anchorElement = document.getElementById(anchor[0]); + if (anchorElement) { + anchorElement.scrollIntoView(); + } } } } @@ -646,6 +702,7 @@ export class TransactionComponent implements OnInit, AfterViewInit, OnDestroy { this.fetchCpfpSubscription.unsubscribe(); this.fetchRbfSubscription.unsubscribe(); this.fetchCachedTxSubscription.unsubscribe(); + this.fetchAccelerationSubscription.unsubscribe(); this.txReplacedSubscription.unsubscribe(); this.txRbfInfoSubscription.unsubscribe(); this.queryParamsSubscription.unsubscribe(); diff --git a/frontend/src/app/components/transaction/transaction.module.ts b/frontend/src/app/components/transaction/transaction.module.ts new file mode 100644 index 000000000..d933cc350 --- /dev/null +++ b/frontend/src/app/components/transaction/transaction.module.ts @@ -0,0 +1,45 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { TransactionComponent } from './transaction.component'; +import { SharedModule } from '../../shared/shared.module'; +import { TxBowtieModule } from '../tx-bowtie-graph/tx-bowtie.module'; + +const routes: Routes = [ + { + path: ':id', + component: TransactionComponent, + data: { + ogImage: true + } + } +]; + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class TransactionRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + TransactionRoutingModule, + SharedModule, + TxBowtieModule, + ], + declarations: [ + TransactionComponent, + ] +}) +export class TransactionModule { } + + + + + + diff --git a/frontend/src/app/components/transactions-list/transactions-list.component.html b/frontend/src/app/components/transactions-list/transactions-list.component.html index 22486d320..625a7c70e 100644 --- a/frontend/src/app/components/transactions-list/transactions-list.component.html +++ b/frontend/src/app/components/transactions-list/transactions-list.component.html @@ -33,7 +33,7 @@ - + @@ -81,7 +81,7 @@ - - - - + + @@ -110,29 +95,21 @@
Pool Hashrate BlocksAvg Health Avg Block FeesEmpty blocksEmpty Blocks
{{ pool.name }}{{ pool.name }} {{ pool.lastEstimatedHashrate }} {{ miningStats.miningUnits.hashrateUnit }} {{ pool.blockCount }} ({{ pool.share }}%) +
-
Pools Luck (1w)
+
Pools Luck

-
Blocks (1w)
+
Pools Count

-
Pools Count (1w)
+
Blocks (1w)

diff --git a/frontend/src/app/components/pool-ranking/pool-ranking.component.scss b/frontend/src/app/components/pool-ranking/pool-ranking.component.scss index b82264503..f5a49678b 100644 --- a/frontend/src/app/components/pool-ranking/pool-ranking.component.scss +++ b/frontend/src/app/components/pool-ranking/pool-ranking.component.scss @@ -28,7 +28,9 @@ .chart-widget { width: 100%; height: 100%; - height: 240px; + @media (max-width: 767px) { + max-height: 240px; + } @media (max-width: 485px) { max-height: 200px; } @@ -41,6 +43,18 @@ } } +@media (max-width: 430px) { + .pool-name { + max-width: 110px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .health-column { + display: none; + } +} + .loadingGraphs { position: absolute; top: 50%; diff --git a/frontend/src/app/components/pool-ranking/pool-ranking.component.ts b/frontend/src/app/components/pool-ranking/pool-ranking.component.ts index 91475040c..a6f43909a 100644 --- a/frontend/src/app/components/pool-ranking/pool-ranking.component.ts +++ b/frontend/src/app/components/pool-ranking/pool-ranking.component.ts @@ -1,7 +1,7 @@ import { ChangeDetectionStrategy, Component, Input, NgZone, OnInit, HostBinding } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; -import { EChartsOption, PieSeriesOption } from 'echarts'; +import { EChartsOption, PieSeriesOption } from '../../graphs/echarts'; import { merge, Observable } from 'rxjs'; import { map, share, startWith, switchMap, tap } from 'rxjs/operators'; import { SeoService } from '../../services/seo.service'; @@ -20,6 +20,7 @@ import { isMobile } from '../../shared/common.utils'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class PoolRankingComponent implements OnInit { + @Input() height: number = 300; @Input() widget = false; miningWindowPreference: string; @@ -162,7 +163,7 @@ export class PoolRankingComponent implements OnInit { const i = pool.blockCount.toString(); if (this.miningWindowPreference === '24h') { return `${pool.name} (${pool.share}%)
` + - pool.lastEstimatedHashrate.toString() + ' PH/s' + + pool.lastEstimatedHashrate.toString() + ' ' + miningStats.miningUnits.hashrateUnit + `
` + $localize`${ i }:INTERPOLATION: blocks`; } else { return `${pool.name} (${pool.share}%)
` + @@ -200,7 +201,7 @@ export class PoolRankingComponent implements OnInit { const i = totalBlockOther.toString(); if (this.miningWindowPreference === '24h') { return `` + $localize`Other (${percentage})` + `
` + - totalEstimatedHashrateOther.toString() + ' PH/s' + + totalEstimatedHashrateOther.toString() + ' ' + miningStats.miningUnits.hashrateUnit + `
` + $localize`${ i }:INTERPOLATION: blocks`; } else { return `` + $localize`Other (${percentage})` + `
` + diff --git a/frontend/src/app/components/pool/pool-preview.component.ts b/frontend/src/app/components/pool/pool-preview.component.ts index b2302b9a7..e0c786082 100644 --- a/frontend/src/app/components/pool/pool-preview.component.ts +++ b/frontend/src/app/components/pool/pool-preview.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, Inject, LOCALE_ID, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; -import { EChartsOption, graphic } from 'echarts'; +import { echarts, EChartsOption } from '../../graphs/echarts'; import { Observable, of } from 'rxjs'; import { map, switchMap, catchError } from 'rxjs/operators'; import { PoolStat } from '../../interfaces/node-api.interface'; @@ -127,7 +127,7 @@ export class PoolPreviewComponent implements OnInit { title: title, animation: false, color: [ - new graphic.LinearGradient(0, 0, 0, 0.65, [ + new echarts.graphic.LinearGradient(0, 0, 0, 0.65, [ { offset: 0, color: '#F4511E' }, { offset: 0.25, color: '#FB8C00' }, { offset: 0.5, color: '#FFB300' }, diff --git a/frontend/src/app/components/pool/pool.component.html b/frontend/src/app/components/pool/pool.component.html index e1806086e..98d1d937b 100644 --- a/frontend/src/app/components/pool/pool.component.html +++ b/frontend/src/app/components/pool/pool.component.html @@ -143,7 +143,7 @@ - + @@ -165,7 +165,7 @@
Blocks 24hBlocks (24h) 1w All
- + @@ -224,7 +224,7 @@ {{ block.height }} + + + + + +
Blocks 24hBlocks (24h) 1w All
- ‎{{ block.timestamp * 1000 | date:'yyyy-MM-dd HH:mm' }} + ‎{{ block.timestamp * 1000 | date:'yyyy-MM-dd HH:mm:ss' }} @@ -433,7 +433,7 @@ - + @@ -458,7 +458,7 @@
Blocks 24hBlocks (24h) 1w All
- + diff --git a/frontend/src/app/components/pool/pool.component.ts b/frontend/src/app/components/pool/pool.component.ts index 0d465bc3c..4457814c3 100644 --- a/frontend/src/app/components/pool/pool.component.ts +++ b/frontend/src/app/components/pool/pool.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; -import { EChartsOption, graphic } from 'echarts'; +import { echarts, EChartsOption } from '../../graphs/echarts'; import { BehaviorSubject, Observable, of, timer } from 'rxjs'; import { catchError, distinctUntilChanged, map, share, switchMap, tap } from 'rxjs/operators'; import { BlockExtended, PoolStat } from '../../interfaces/node-api.interface'; @@ -115,13 +115,13 @@ export class PoolComponent implements OnInit { prepareChartOptions(data) { let title: object; - if (data.length === 0) { + if (data.length <= 1) { title = { textStyle: { color: 'grey', fontSize: 15 }, - text: $localize`:@@23555386d8af1ff73f297e89dd4af3f4689fb9dd:Indexing blocks`, + text: $localize`Not enough data yet`, left: 'center', top: 'center' }; @@ -131,7 +131,7 @@ export class PoolComponent implements OnInit { title: title, animation: false, color: [ - new graphic.LinearGradient(0, 0, 0, 0.65, [ + new echarts.graphic.LinearGradient(0, 0, 0, 0.65, [ { offset: 0, color: '#F4511E' }, { offset: 0.25, color: '#FB8C00' }, { offset: 0.5, color: '#FFB300' }, @@ -163,10 +163,8 @@ export class PoolComponent implements OnInit { let hashratePowerOfTen: any = selectPowerOfTen(1); let hashrate = ticks[0].data[1]; - if (this.isMobile()) { - hashratePowerOfTen = selectPowerOfTen(ticks[0].data[1]); - hashrate = Math.round(ticks[0].data[1] / hashratePowerOfTen.divider); - } + hashratePowerOfTen = selectPowerOfTen(ticks[0].data[1], 10); + hashrate = ticks[0].data[1] / hashratePowerOfTen.divider; return ` ${ticks[0].axisValueLabel}
@@ -174,14 +172,14 @@ export class PoolComponent implements OnInit { `; }.bind(this) }, - xAxis: data.length === 0 ? undefined : { + xAxis: data.length <= 1 ? undefined : { type: 'time', splitNumber: (this.isMobile()) ? 5 : 10, axisLabel: { hideOverlap: true, } }, - yAxis: data.length === 0 ? undefined : [ + yAxis: data.length <= 1 ? undefined : [ { min: (value) => { return value.min * 0.9; @@ -200,7 +198,7 @@ export class PoolComponent implements OnInit { } }, ], - series: data.length === 0 ? undefined : [ + series: data.length <= 1 ? undefined : [ { zlevel: 0, name: 'Hashrate', @@ -213,7 +211,7 @@ export class PoolComponent implements OnInit { }, }, ], - dataZoom: data.length === 0 ? undefined : [{ + dataZoom: data.length <= 1 ? undefined : [{ type: 'inside', realtime: true, zoomLock: true, diff --git a/frontend/src/app/components/privacy-policy/privacy-policy.component.html b/frontend/src/app/components/privacy-policy/privacy-policy.component.html index e0979ce24..d14b12bc3 100644 --- a/frontend/src/app/components/privacy-policy/privacy-policy.component.html +++ b/frontend/src/app/components/privacy-policy/privacy-policy.component.html @@ -5,7 +5,7 @@

Privacy Policy

-
Updated: November 18, 2021
+
Updated: November 23, 2023


@@ -53,6 +53,26 @@
+

SIGNING UP FOR AN ACCOUNT ON MEMPOOL.SPACE

+ +

If you sign up for an account on mempool.space, we may collect the following:

+ +
    + +
  1. If you provide your name, country, and/or e-mail address, we may use this information to manage your user account, for billing purposes, or to update you about our services. We will not share this with any third-party, except as detailed below if you sponsor The Mempool Open Source Project®, purchase a subscription to Mempool Enterprise®, or accelerate transactions using Mempool Accelerator™.
  2. + +
  3. If you connect your Twitter account, we may store your Twitter identity, e-mail address, and profile photo. We may publicly display your profile photo or link to your profile on our website, if you sponsor The Mempool Open Source Project, claim your Lightning node, or other such use cases.
  4. + +
  5. If you make a credit card payment, we will process your payment using Square (Block, Inc.), and we will store details about the transaction in our database. Please see "Information we collect about customers" on Square's website at https://squareup.com/us/en/legal/general/privacy
  6. + +
  7. If you make a Bitcoin or Liquid payment, we will process your payment using our self-hosted BTCPay Server instance and not share these details with any third-party.
  8. + +
  9. If you accelerate transactions using Mempool Accelerator™, we will store the TXID of your transactions you accelerate with us. We share this information with our mining pool partners, as well as publicly display accelerated transaction details on our website and APIs.
  10. + +
+ +
+

EOF

diff --git a/frontend/src/app/components/privacy-policy/privacy-policy.component.ts b/frontend/src/app/components/privacy-policy/privacy-policy.component.ts index 7a44070eb..b98390731 100644 --- a/frontend/src/app/components/privacy-policy/privacy-policy.component.ts +++ b/frontend/src/app/components/privacy-policy/privacy-policy.component.ts @@ -17,6 +17,6 @@ export class PrivacyPolicyComponent { ngOnInit(): void { this.seoService.setTitle('Privacy Policy'); - this.seoService.setDescription('Trusted third parties are security holes, as are trusted first parties...you should only trust your own self-hosted instance of The Mempool Open Source Project™.'); + this.seoService.setDescription('Trusted third parties are security holes, as are trusted first parties...you should only trust your own self-hosted instance of The Mempool Open Source Project®.'); } } diff --git a/frontend/src/app/components/privacy-policy/privacy-policy.module.ts b/frontend/src/app/components/privacy-policy/privacy-policy.module.ts new file mode 100644 index 000000000..6d279d80a --- /dev/null +++ b/frontend/src/app/components/privacy-policy/privacy-policy.module.ts @@ -0,0 +1,40 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { PrivacyPolicyComponent } from './privacy-policy.component'; +import { SharedModule } from '../../shared/shared.module'; + +const routes: Routes = [ + { + path: '', + component: PrivacyPolicyComponent, + } +]; + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class PrivacyPolicyRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + PrivacyPolicyRoutingModule, + SharedModule, + ], + declarations: [ + PrivacyPolicyComponent, + ] +}) +export class PrivacyPolicyModule { } + + + + + + diff --git a/frontend/src/app/components/rbf-list/rbf-list.component.html b/frontend/src/app/components/rbf-list/rbf-list.component.html index c3206d37a..78815544c 100644 --- a/frontend/src/app/components/rbf-list/rbf-list.component.html +++ b/frontend/src/app/components/rbf-list/rbf-list.component.html @@ -6,11 +6,9 @@
+ All + Full RBF
@@ -33,7 +31,7 @@
-

there are no replacements in the mempool yet!

+

There are no replacements in the mempool yet!

diff --git a/frontend/src/app/components/rbf-list/rbf-list.component.ts b/frontend/src/app/components/rbf-list/rbf-list.component.ts index 1ae14702b..0721c7fdf 100644 --- a/frontend/src/app/components/rbf-list/rbf-list.component.ts +++ b/frontend/src/app/components/rbf-list/rbf-list.component.ts @@ -55,7 +55,7 @@ export class RbfList implements OnInit, OnDestroy { }) ); - this.seoService.setTitle($localize`:@@meta.title.rbf-list:RBF Replacements`); + this.seoService.setTitle($localize`:@@5e3d5a82750902f159122fcca487b07f1af3141f:RBF Replacements`); this.seoService.setDescription($localize`:@@meta.description.rbf-list:See the most recent RBF replacements on the Bitcoin${seoDescriptionNetwork(this.stateService.network)} network, updated in real-time.`); } diff --git a/frontend/src/app/components/rbf-timeline/rbf-timeline-tooltip.component.html b/frontend/src/app/components/rbf-timeline/rbf-timeline-tooltip.component.html index 540da7480..84e20b75f 100644 --- a/frontend/src/app/components/rbf-timeline/rbf-timeline-tooltip.component.html +++ b/frontend/src/app/components/rbf-timeline/rbf-timeline-tooltip.component.html @@ -32,9 +32,9 @@ diff --git a/frontend/src/app/components/rbf-timeline/rbf-timeline.component.html b/frontend/src/app/components/rbf-timeline/rbf-timeline.component.html index a2012d45f..6f19537e1 100644 --- a/frontend/src/app/components/rbf-timeline/rbf-timeline.component.html +++ b/frontend/src/app/components/rbf-timeline/rbf-timeline.component.html @@ -1,7 +1,7 @@
-
-
+
+
@@ -13,7 +13,7 @@
-
+
-
+
@@ -51,6 +51,16 @@
+
+
+ + + + +
@@ -72,3 +82,5 @@ [isConnector]="hoverConnector" > -->
+ +{{ x }} remaining \ No newline at end of file diff --git a/frontend/src/app/components/rbf-timeline/rbf-timeline.component.scss b/frontend/src/app/components/rbf-timeline/rbf-timeline.component.scss index be7aef2d6..8962be63c 100644 --- a/frontend/src/app/components/rbf-timeline/rbf-timeline.component.scss +++ b/frontend/src/app/components/rbf-timeline/rbf-timeline.component.scss @@ -30,12 +30,32 @@ overflow-x: auto; -ms-overflow-style: none; scrollbar-width: none; - + &::-webkit-scrollbar { display: none; } } + .fade-out { + position: relative; + + &::before { + content: ''; + position: absolute; + width: 100%; + height: 70px; + top: -70px; + background: linear-gradient(to bottom, rgba(36, 39, 62, 0) 0%, rgba(36, 39, 62, 1) 100%); + z-index: 1; + } + } + + .toggle-wrapper { + width: 100%; + text-align: center; + margin: 1.25em 0 0; + } + .intervals, .nodes { min-width: 100%; display: flex; @@ -191,6 +211,10 @@ &.fullrbf { border-right: solid 10px #1bd8f4; } + &.last-pipe { + height: 150px; + bottom: -42px; + } } .corner { diff --git a/frontend/src/app/components/rbf-timeline/rbf-timeline.component.ts b/frontend/src/app/components/rbf-timeline/rbf-timeline.component.ts index 474da7326..687a7dbfd 100644 --- a/frontend/src/app/components/rbf-timeline/rbf-timeline.component.ts +++ b/frontend/src/app/components/rbf-timeline/rbf-timeline.component.ts @@ -25,7 +25,9 @@ function isTimelineCell(val: RbfTree | TimelineCell): boolean { export class RbfTimelineComponent implements OnInit, OnChanges { @Input() replacements: RbfTree; @Input() txid: string; + @Input() rowLimit: number = 5; // If explicitly set to 0, all timelines rows will be displayed by default rows: TimelineCell[][] = []; + timelineExpanded: boolean = this.rowLimit === 0; hoverInfo: RbfTree | null = null; tooltipPosition = null; @@ -191,6 +193,10 @@ export class RbfTimelineComponent implements OnInit, OnChanges { return rows; } + toggleTimeline(expand: boolean): void { + this.timelineExpanded = expand; + } + scrollToSelected() { const node = document.getElementById('node-' + this.txid); if (node) { diff --git a/frontend/src/app/components/search-form/search-form.component.html b/frontend/src/app/components/search-form/search-form.component.html index 3fc03c83a..73e9d0501 100644 --- a/frontend/src/app/components/search-form/search-form.component.html +++ b/frontend/src/app/components/search-form/search-form.component.html @@ -1,4 +1,4 @@ -
+
diff --git a/frontend/src/app/components/search-form/search-form.component.scss b/frontend/src/app/components/search-form/search-form.component.scss index 534bf0698..cec555a4f 100644 --- a/frontend/src/app/components/search-form/search-form.component.scss +++ b/frontend/src/app/components/search-form/search-form.component.scss @@ -1,15 +1,11 @@ :host ::ng-deep { .dropdown-item { white-space: nowrap; - width: calc(100% - 34px); } .dropdown-menu { width: calc(100% - 34px); } @media (min-width: 768px) { - .dropdown-item { - width: 410px; - } .dropdown-menu { width: 410px; } @@ -26,6 +22,13 @@ form { @media (min-width: 992px) { width: 100%; } + + &.hamburgerOpen { + @media (max-width: 613px) { + margin-left: 0px; + margin-right: 0px; + } + } } .btn-block { @@ -39,7 +42,7 @@ form { min-width: 400px; } @media (min-width: 992px) { - min-width: 200px; + min-width: 142px; } @media (min-width: 1200px) { min-width: 300px; diff --git a/frontend/src/app/components/search-form/search-form.component.ts b/frontend/src/app/components/search-form/search-form.component.ts index 0a794d1f5..3bbe5bccb 100644 --- a/frontend/src/app/components/search-form/search-form.component.ts +++ b/frontend/src/app/components/search-form/search-form.component.ts @@ -1,14 +1,15 @@ -import { Component, OnInit, ChangeDetectionStrategy, EventEmitter, Output, ViewChild, HostListener, ElementRef } from '@angular/core'; +import { Component, OnInit, ChangeDetectionStrategy, EventEmitter, Output, ViewChild, HostListener, ElementRef, Input } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { EventType, NavigationStart, Router } from '@angular/router'; import { AssetsService } from '../../services/assets.service'; -import { StateService } from '../../services/state.service'; +import { Env, StateService } from '../../services/state.service'; import { Observable, of, Subject, zip, BehaviorSubject, combineLatest } from 'rxjs'; import { debounceTime, distinctUntilChanged, switchMap, catchError, map, startWith, tap } from 'rxjs/operators'; import { ElectrsApiService } from '../../services/electrs-api.service'; import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe'; import { ApiService } from '../../services/api.service'; import { SearchResultsComponent } from './search-results/search-results.component'; +import { Network, findOtherNetworks, getRegex, getTargetUrl, needBaseModuleChange } from '../../shared/regex.utils'; @Component({ selector: 'app-search-form', @@ -17,6 +18,8 @@ import { SearchResultsComponent } from './search-results/search-results.componen changeDetection: ChangeDetectionStrategy.OnPush, }) export class SearchFormComponent implements OnInit { + @Input() hamburgerOpen = false; + env: Env; network = ''; assets: object = {}; isSearching = false; @@ -34,10 +37,13 @@ export class SearchFormComponent implements OnInit { } } - regexAddress = /^([a-km-zA-HJ-NP-Z1-9]{26,35}|[a-km-zA-HJ-NP-Z1-9]{80}|[A-z]{2,5}1[a-zA-HJ-NP-Z0-9]{39,59}|04[a-fA-F0-9]{128}|(02|03)[a-fA-F0-9]{64})$/; - regexBlockhash = /^[0]{8}[a-fA-F0-9]{56}$/; - regexTransaction = /^([a-fA-F0-9]{64})(:\d+)?$/; - regexBlockheight = /^[0-9]{1,9}$/; + regexAddress = getRegex('address', 'mainnet'); // Default to mainnet + regexBlockhash = getRegex('blockhash', 'mainnet'); + regexTransaction = getRegex('transaction'); + regexBlockheight = getRegex('blockheight'); + regexDate = getRegex('date'); + regexUnixTimestamp = getRegex('timestamp'); + focus$ = new Subject(); click$ = new Subject(); @@ -62,8 +68,14 @@ export class SearchFormComponent implements OnInit { } ngOnInit(): void { - this.stateService.networkChanged$.subscribe((network) => this.network = network); - + this.env = this.stateService.env; + this.stateService.networkChanged$.subscribe((network) => { + this.network = network; + // TODO: Eventually change network type here from string to enum of consts + this.regexAddress = getRegex('address', network as any || 'mainnet'); + this.regexBlockhash = getRegex('blockhash', network as any || 'mainnet'); + }); + this.router.events.subscribe((e: NavigationStart) => { // Reset search focus when changing page if (this.searchInput && e.type === EventType.NavigationStart) { this.searchInput.nativeElement.blur(); @@ -92,9 +104,6 @@ export class SearchFormComponent implements OnInit { const searchText$ = this.searchForm.get('searchText').valueChanges .pipe( map((text) => { - if (this.network === 'bisq' && text.match(/^(b)[^c]/i)) { - return text.substr(1); - } return text.trim(); }), tap((text) => { @@ -128,9 +137,6 @@ export class SearchFormComponent implements OnInit { ); }), map((result: any[]) => { - if (this.network === 'bisq') { - result[0] = result[0].map((address: string) => 'B' + address); - } return result; }), tap(() => { @@ -160,9 +166,11 @@ export class SearchFormComponent implements OnInit { blockHeight: false, txId: false, address: false, + otherNetworks: [], addresses: [], nodes: [], channels: [], + liquidAsset: [], }; } @@ -170,25 +178,42 @@ export class SearchFormComponent implements OnInit { const addressPrefixSearchResults = result[0]; const lightningResults = result[1]; - const matchesBlockHeight = this.regexBlockheight.test(searchText); + // Do not show date and timestamp results for liquid and bisq + const isNetworkBitcoin = this.network === '' || this.network === 'testnet' || this.network === 'signet'; + + const matchesBlockHeight = this.regexBlockheight.test(searchText) && parseInt(searchText) <= this.stateService.latestBlockHeight; + const matchesDateTime = this.regexDate.test(searchText) && new Date(searchText).toString() !== 'Invalid Date' && new Date(searchText).getTime() <= Date.now() && isNetworkBitcoin; + const matchesUnixTimestamp = this.regexUnixTimestamp.test(searchText) && parseInt(searchText) <= Math.floor(Date.now() / 1000) && isNetworkBitcoin; const matchesTxId = this.regexTransaction.test(searchText) && !this.regexBlockhash.test(searchText); const matchesBlockHash = this.regexBlockhash.test(searchText); - const matchesAddress = !matchesTxId && this.regexAddress.test(searchText); + let matchesAddress = !matchesTxId && this.regexAddress.test(searchText); + const otherNetworks = findOtherNetworks(searchText, this.network as any || 'mainnet', this.env); + const liquidAsset = this.assets ? (this.assets[searchText] || []) : []; - if (matchesAddress && this.network === 'bisq') { - searchText = 'B' + searchText; + // Add B prefix to addresses in Bisq network + if (!matchesAddress && this.network === 'bisq' && getRegex('address', 'mainnet').test(searchText)) { + searchText = 'B' + searchText; + matchesAddress = !matchesTxId && this.regexAddress.test(searchText); + } + + if (matchesDateTime && searchText.indexOf('/') !== -1) { + searchText = searchText.replace(/\//g, '-'); } return { searchText: searchText, - hashQuickMatch: +(matchesBlockHeight || matchesBlockHash || matchesTxId || matchesAddress), + hashQuickMatch: +(matchesBlockHeight || matchesBlockHash || matchesTxId || matchesAddress || matchesUnixTimestamp || matchesDateTime), blockHeight: matchesBlockHeight, + dateTime: matchesDateTime, + unixTimestamp: matchesUnixTimestamp, txId: matchesTxId, blockHash: matchesBlockHash, address: matchesAddress, - addresses: addressPrefixSearchResults, + addresses: matchesAddress && addressPrefixSearchResults.length === 1 && searchText === addressPrefixSearchResults[0] ? [] : addressPrefixSearchResults, // If there is only one address and it matches the search text, don't show it in the dropdown + otherNetworks: otherNetworks, nodes: lightningResults.nodes, channels: lightningResults.channels, + liquidAsset: liquidAsset, }; }) ); @@ -205,12 +230,21 @@ export class SearchFormComponent implements OnInit { selectedResult(result: any): void { if (typeof result === 'string') { this.search(result); - } else if (typeof result === 'number') { + } else if (typeof result === 'number' && result <= this.stateService.latestBlockHeight) { this.navigate('/block/', result.toString()); } else if (result.alias) { this.navigate('/lightning/node/', result.public_key); } else if (result.short_id) { this.navigate('/lightning/channel/', result.id); + } else if (result.network) { + if (result.isNetworkAvailable) { + this.navigate('/address/', result.address, undefined, result.network); + } else { + this.searchForm.setValue({ + searchText: '', + }); + this.isSearching = false; + } } } @@ -218,29 +252,44 @@ export class SearchFormComponent implements OnInit { const searchText = result || this.searchForm.value.searchText.trim(); if (searchText) { this.isSearching = true; + if (!this.regexTransaction.test(searchText) && this.regexAddress.test(searchText)) { this.navigate('/address/', searchText); - } else if (this.regexBlockhash.test(searchText) || this.regexBlockheight.test(searchText)) { + } else if (this.regexBlockhash.test(searchText)) { this.navigate('/block/', searchText); + } else if (this.regexBlockheight.test(searchText)) { + parseInt(searchText) <= this.stateService.latestBlockHeight ? this.navigate('/block/', searchText) : this.isSearching = false; } else if (this.regexTransaction.test(searchText)) { const matches = this.regexTransaction.exec(searchText); if (this.network === 'liquid' || this.network === 'liquidtestnet') { - if (this.assets[matches[1]]) { - this.navigate('/assets/asset/', matches[1]); + if (this.assets[matches[0]]) { + this.navigate('/assets/asset/', matches[0]); } - this.electrsApiService.getAsset$(matches[1]) + this.electrsApiService.getAsset$(matches[0]) .subscribe( - () => { this.navigate('/assets/asset/', matches[1]); }, + () => { this.navigate('/assets/asset/', matches[0]); }, () => { - this.electrsApiService.getBlock$(matches[1]) + this.electrsApiService.getBlock$(matches[0]) .subscribe( - (block) => { this.navigate('/block/', matches[1], { state: { data: { block } } }); }, + (block) => { this.navigate('/block/', matches[0], { state: { data: { block } } }); }, () => { this.navigate('/tx/', matches[0]); }); } ); } else { this.navigate('/tx/', matches[0]); } + } else if (this.regexDate.test(searchText) || this.regexUnixTimestamp.test(searchText)) { + let timestamp: number; + this.regexDate.test(searchText) ? timestamp = Math.floor(new Date(searchText).getTime() / 1000) : timestamp = searchText; + // Check if timestamp is too far in the future or before the genesis block + if (timestamp > Math.floor(Date.now() / 1000)) { + this.isSearching = false; + return; + } + this.apiService.getBlockDataFromTimestamp$(timestamp).subscribe( + (data) => { this.navigate('/block/', data.hash); }, + (error) => { console.log(error); this.isSearching = false; } + ); } else { this.searchResults.searchButtonClick(); this.isSearching = false; @@ -248,12 +297,17 @@ export class SearchFormComponent implements OnInit { } } - navigate(url: string, searchText: string, extras?: any): void { - this.router.navigate([this.relativeUrlPipe.transform(url), searchText], extras); - this.searchTriggered.emit(); - this.searchForm.setValue({ - searchText: '', - }); - this.isSearching = false; + + navigate(url: string, searchText: string, extras?: any, swapNetwork?: string) { + if (needBaseModuleChange(this.env.BASE_MODULE as 'liquid' | 'bisq' | 'mempool', swapNetwork as Network)) { + window.location.href = getTargetUrl(swapNetwork as Network, searchText, this.env); + } else { + this.router.navigate([this.relativeUrlPipe.transform(url, swapNetwork), searchText], extras); + this.searchTriggered.emit(); + this.searchForm.setValue({ + searchText: '', + }); + this.isSearching = false; + } } } diff --git a/frontend/src/app/components/search-form/search-results/search-results.component.html b/frontend/src/app/components/search-form/search-results/search-results.component.html index b0d043f53..f447d3837 100644 --- a/frontend/src/app/components/search-form/search-results/search-results.component.html +++ b/frontend/src/app/components/search-form/search-results/search-results.component.html @@ -1,32 +1,52 @@ -
Blocks 24hBlocks (24h) 1w All
Status - Full RBF + Full RBF RBF - RBF + RBF Mined
+ + + + + + + + + + + + + + + + + + +
HostRTTRTTHeight
{{ i + 1 }}{{ host.active ? '⭐️' : host.flag }}{{ host.link }}{{ (host.rtt / 1000) | number : '1.1-1' }} {{ host.rtt == null ? '' : 's'}} {{ !host.checked ? '⏳' : (host.unreachable ? '🔥' : '✅') }}{{ host.rtt | number : '1.0-0' }} {{ host.rtt == null ? '' : 'ms'}} {{ !host.checked ? '⏳' : (host.unreachable ? '🔥' : '✅') }}{{ host.latestHeight }} {{ !host.checked ? '⏳' : (host.outOfSync ? '🚫' : (host.latestHeight && host.latestHeight < tip ? '🟧' : '✅')) }}
+ + + diff --git a/frontend/src/app/components/server-health/server-health.component.scss b/frontend/src/app/components/server-health/server-health.component.scss new file mode 100644 index 000000000..572628a9d --- /dev/null +++ b/frontend/src/app/components/server-health/server-health.component.scss @@ -0,0 +1,72 @@ +.tomahawk { + .links { + float: right; + text-align: right; + margin-top: 1em; + + a, span { + margin-left: 1em; + } + } + + .dashboard-title { + text-align: left; + } + + .status-panel { + max-width: 720px; + margin: auto; + margin-top: 2em; + padding: 1em; + background: #24273e; + } + + .status-table { + width: 100%; + + td, th { + padding: 0.25em; + + &.rank, &.flag { + width: 28px; + text-align: right; + } + &.rtt, &.height { + width: 92px; + text-align: right; + } + &.only-small { + display: table-cell; + &.rtt { + width: 60px; + } + } + &.only-large { + display: none; + } + &.height { + padding-right: 0.5em; + } + &.host { + width: auto; + overflow: hidden; + text-overflow: ellipsis; + } + + @media (min-width: 576px) { + &.rank, &.flag { + width: 32px; + } + &.rtt, &.height { + width: 96px; + } + &.only-small { + display: none; + } + &.only-large { + display: table-cell; + } + } + } + } +} \ No newline at end of file diff --git a/frontend/src/app/components/server-health/server-health.component.ts b/frontend/src/app/components/server-health/server-health.component.ts new file mode 100644 index 000000000..363b28111 --- /dev/null +++ b/frontend/src/app/components/server-health/server-health.component.ts @@ -0,0 +1,67 @@ +import { Component, OnInit, ChangeDetectionStrategy, SecurityContext } from '@angular/core'; +import { WebsocketService } from '../../services/websocket.service'; +import { Observable, Subject, map } from 'rxjs'; +import { StateService } from '../../services/state.service'; +import { HealthCheckHost } from '../../interfaces/websocket.interface'; +import { DomSanitizer } from '@angular/platform-browser'; + +@Component({ + selector: 'app-server-health', + templateUrl: './server-health.component.html', + styleUrls: ['./server-health.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ServerHealthComponent implements OnInit { + hosts$: Observable; + tip$: Subject; + + constructor( + private websocketService: WebsocketService, + private stateService: StateService, + public sanitizer: DomSanitizer, + ) {} + + ngOnInit(): void { + this.hosts$ = this.stateService.serverHealth$.pipe( + map((hosts) => { + const subpath = window.location.pathname.slice(0, -6); + for (const host of hosts) { + let statusUrl = ''; + let linkHost = ''; + if (host.socket) { + statusUrl = 'https://' + window.location.hostname + subpath + '/status'; + linkHost = window.location.hostname + subpath; + } else { + const hostUrl = new URL(host.host); + statusUrl = 'https://' + hostUrl.hostname + subpath + '/status'; + linkHost = hostUrl.hostname + subpath; + } + host.statusPage = this.sanitizer.bypassSecurityTrustResourceUrl(this.sanitizer.sanitize(SecurityContext.URL, statusUrl)); + host.link = linkHost; + host.flag = this.parseFlag(host.host); + } + return hosts; + }) + ); + this.tip$ = this.stateService.chainTip$; + this.websocketService.want(['blocks', 'tomahawk']); + } + + trackByFn(index: number, host: HealthCheckHost): string { + return host.host; + } + + private parseFlag(host: string): string { + if (host.includes('.fra.')) { + return '🇩🇪'; + } else if (host.includes('.tk7.')) { + return '🇯🇵'; + } else if (host.includes('.fmt.')) { + return '🇺🇸'; + } else if (host.includes('.va1.')) { + return '🇺🇸'; + } else { + return ''; + } + } +} diff --git a/frontend/src/app/components/server-health/server-status.component.html b/frontend/src/app/components/server-health/server-status.component.html new file mode 100644 index 000000000..23ca16a61 --- /dev/null +++ b/frontend/src/app/components/server-health/server-status.component.html @@ -0,0 +1,16 @@ +
+
+ +

Live Network

+
+ + + + + +
diff --git a/frontend/src/app/components/server-health/server-status.component.scss b/frontend/src/app/components/server-health/server-status.component.scss new file mode 100644 index 000000000..09bebe040 --- /dev/null +++ b/frontend/src/app/components/server-health/server-status.component.scss @@ -0,0 +1,26 @@ +.tomahawk { + .links { + float: right; + text-align: right; + margin-top: 1em; + + a, span { + margin-left: 1em; + } + } + + .dashboard-title { + text-align: left; + } + + .mempoolStatus { + width: 100%; + height: 270px; + } + + .hostLink { + text-align: center; + margin: auto; + margin-top: 1em; + } +} \ No newline at end of file diff --git a/frontend/src/app/components/server-health/server-status.component.ts b/frontend/src/app/components/server-health/server-status.component.ts new file mode 100644 index 000000000..2e522b805 --- /dev/null +++ b/frontend/src/app/components/server-health/server-status.component.ts @@ -0,0 +1,80 @@ +import { Component, OnInit, ChangeDetectionStrategy, SecurityContext, OnDestroy, ChangeDetectorRef } from '@angular/core'; +import { WebsocketService } from '../../services/websocket.service'; +import { Observable, Subject, Subscription, map, tap } from 'rxjs'; +import { StateService } from '../../services/state.service'; +import { HealthCheckHost } from '../../interfaces/websocket.interface'; +import { DomSanitizer } from '@angular/platform-browser'; + +@Component({ + selector: 'app-server-status', + templateUrl: './server-status.component.html', + styleUrls: ['./server-status.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ServerStatusComponent implements OnInit, OnDestroy { + tip$: Subject; + hosts: HealthCheckHost[] = []; + hostSubscription: Subscription; + + constructor( + private websocketService: WebsocketService, + private stateService: StateService, + private cd: ChangeDetectorRef, + public sanitizer: DomSanitizer, + ) {} + + ngOnInit(): void { + this.hostSubscription = this.stateService.serverHealth$.pipe( + map((hosts) => { + const subpath = window.location.pathname.slice(0, -8); + for (const host of hosts) { + let statusUrl = ''; + let linkHost = ''; + if (host.socket) { + statusUrl = 'https://' + window.location.hostname + subpath + '/status'; + linkHost = window.location.hostname + subpath; + } else { + const hostUrl = new URL(host.host); + statusUrl = 'https://' + hostUrl.hostname + subpath + '/status'; + linkHost = hostUrl.hostname + subpath; + } + host.statusPage = this.sanitizer.bypassSecurityTrustResourceUrl(this.sanitizer.sanitize(SecurityContext.URL, statusUrl)); + host.link = linkHost; + } + return hosts; + }), + tap((hosts) => { + if (this.hosts.length !== hosts.length) { + this.hosts = hosts.sort((a,b) => { + const aParts = (a.host?.split('.') || []).reverse(); + const bParts = (b.host?.split('.') || []).reverse(); + let i = 0; + while (i < Math.max(aParts.length, bParts.length)) { + if (aParts[i] && !bParts[i]) { + return 1; + } else if (bParts[i] && !aParts[i]) { + return -1; + } else if (aParts[i] !== bParts[i]) { + return aParts[i].localeCompare(bParts[i]); + } + i++; + } + return 0; + }); + } + this.cd.markForCheck(); + }) + ).subscribe(); + this.tip$ = this.stateService.chainTip$; + this.websocketService.want(['blocks', 'tomahawk']); + } + + trackByFn(index: number, host: HealthCheckHost): string { + return host.host; + } + + ngOnDestroy(): void { + this.hosts = []; + this.hostSubscription.unsubscribe(); + } +} diff --git a/frontend/src/app/components/start/start.component.html b/frontend/src/app/components/start/start.component.html index 709a230d9..b61187ab4 100644 --- a/frontend/src/app/components/start/start.component.html +++ b/frontend/src/app/components/start/start.component.html @@ -2,8 +2,9 @@
-
-
+
+
+
{{ eventName }}
@@ -14,6 +15,7 @@
.before, .pyro > .after { +.pyro > .inner { z-index: 100; position: absolute; width: 5px; height: 5px; border-radius: 50%; - @include animation((1s bang ease-out infinite backwards, 1s gravity ease-in infinite backwards, 5s position linear infinite backwards)); + @include animation((1.25s ease-out infinite bang, 1.25s ease-in infinite gravity, 10s linear infinite position)); + + &.b { + @include animation-delay((-4.35s, -4.35s, -4.35s)); + @include animation-duration((1.45s, 1.45s, 11.6s)); + } + &.c { + @include animation-delay((-3.2s, -3.2s, -3.2s)); + @include animation-duration((1.6s, 1.6s, 12.8s)); + } } -.pyro > .after { - @include animation-delay((1.25s, 1.25s, 1.25s)); - @include animation-duration((1.25s, 1.25s, 6.25s)); -} - -@keyframes bang{ - to{ - box-shadow:-314.6666666667px -362.6666666667px red,-51.6666666667px 32.3333333333px #ff3700,-354.6666666667px -264.6666666667px #7b00ff,-319.6666666667px -73.6666666667px #00f7ff,-135.6666666667px -154.6666666667px #00ff48,57.3333333333px -402.6666666667px #0d00ff,-126.6666666667px -121.6666666667px #00ff7b,-335.6666666667px -5.6666666667px #00fff2,-291.6666666667px -.6666666667px #4f0,-126.6666666667px -187.6666666667px #7f0,-413.6666666667px -224.6666666667px #00ffbf,-283.6666666667px -391.6666666667px #00ff3c,-340.6666666667px -345.6666666667px #02f,-168.6666666667px -179.6666666667px #eaff00,7.3333333333px -153.6666666667px #26ff00,-175.6666666667px -234.6666666667px #8400ff,-324.6666666667px -254.6666666667px #0048ff,-335.6666666667px -9.6666666667px #00ff59,-304.6666666667px -8.6666666667px #001eff,-331.6666666667px -44.6666666667px #3f0,.3333333333px -49.6666666667px #0fc,-370.6666666667px -60.6666666667px #0015ff,29.3333333333px -13.6666666667px #8cff00,-168.6666666667px -281.6666666667px #f80,-48.6666666667px -61.6666666667px #f0b,33.3333333333px -113.6666666667px #ff00e1,-193.6666666667px -196.6666666667px #ff7b00,-14.6666666667px -24.6666666667px #ff0037,-149.6666666667px -273.6666666667px #0fa,-19.6666666667px -63.6666666667px #ff0004,13.3333333333px -227.6666666667px #7f0,-265.6666666667px -43.6666666667px #ff4800,-121.6666666667px -95.6666666667px #bfff00,-241.6666666667px -90.6666666667px #6200ff,-307.6666666667px -231.6666666667px #ff0062,78.3333333333px -128.6666666667px #ffbf00,27.3333333333px 44.3333333333px #95ff00,-81.6666666667px 6.3333333333px #ffc800,-343.6666666667px -247.6666666667px #2f0,-225.6666666667px -250.6666666667px #08f,-9.6666666667px -243.6666666667px #ff1a00,83.3333333333px -409.6666666667px #04f,-380.6666666667px -331.6666666667px #84ff00,-103.6666666667px -51.6666666667px #f02,-174.6666666667px -169.6666666667px #ffc800,20.3333333333px -191.6666666667px #ff0059,-40.6666666667px -55.6666666667px #0400ff,-199.6666666667px -66.6666666667px #ffd500,-358.6666666667px -5.6666666667px #0051ff,-84.6666666667px -289.6666666667px #f7ff00,-193.6666666667px -184.6666666667px #80f +@keyframes bang { + 0%, 15% { + box-sizing: none; + } + 84% { + box-shadow: -30.55vw -35.21vw red,-5.02vw 3.14vw #ff3700,-34.43vw -25.70vw #7b00ff,-31.04vw -7.15vw #00f7ff,-13.17vw -15.02vw #00ff48,5.57vw -39.09vw #0d00ff,-12.30vw -11.81vw #00ff7b,-32.59vw -0.55vw #00fff2,-28.32vw -.6666666667px #4f0,-12.30vw -18.22vw #7f0,-40.16vw -21.81vw #00ffbf,-27.54vw -38.03vw #00ff3c,-33.07vw -33.56vw #02f,-16.38vw -17.44vw #eaff00,0.71vw -14.92vw #26ff00,-17.06vw -22.78vw #8400ff,-31.52vw -24.72vw #0048ff,-32.59vw -0.94vw #00ff59,-29.58vw -0.84vw #001eff,-32.20vw -4.34vw #3f0,.3333333333px -4.82vw #0fc,-35.99vw -5.89vw #0015ff,2.85vw -1.33vw #8cff00,-16.38vw -27.35vw #f80,-4.72vw -5.99vw #f0b,3.24vw -11.04vw #ff00e1,-18.80vw -19.09vw #ff7b00,-1.42vw -2.39vw #ff0037,-14.53vw -26.57vw #0fa,-1.91vw -6.18vw #ff0004,1.29vw -22.10vw #7f0,-25.79vw -4.24vw #ff4800,-11.81vw -9.29vw #bfff00,-23.46vw -8.80vw #6200ff,-29.87vw -22.49vw #ff0062,7.61vw -12.49vw #ffbf00,2.65vw 4.30vw #95ff00,-7.93vw 0.61vw #ffc800,-33.37vw -24.05vw #2f0,-21.91vw -24.34vw #08f,-0.94vw -23.66vw #ff1a00,8.09vw -39.77vw #04f,-36.96vw -32.20vw #84ff00,-10.06vw -5.02vw #f02,-16.96vw -16.47vw #ffc800,1.97vw -18.61vw #ff0059,-3.95vw -5.40vw #0400ff,-19.39vw -6.47vw #ffd500,-34.82vw -0.55vw #0051ff,-8.22vw -28.12vw #f7ff00,-18.80vw -17.93vw #80f; + } + 85%, 100% { + box-sizing: none; } } @include keyframes(gravity) { - to { + 0% { + @include transform(translateY(0px)); + opacity: 0; + } + 15% { + @include transform(translateY(0px)); + opacity: 1; + } + 84% { + @include transform(translateY(400px)); + opacity: 0; + } + 85%, 100% { @include transform(translateY(200px)); opacity: 0; } } @include keyframes(position) { - 0%, 19.9% { - margin-top: 10%; - margin-left: 40%; + 0%, 12.4% { + margin-top: 10vw; + margin-left: 50%; } - 20%, 39.9% { - margin-top: 40%; - margin-left: 30%; + 12.5%, 24.9% { + margin-top: 22vw; + margin-left: 35%; } - 40%, 59.9% { - margin-top: 20%; - margin-left: 70% + 25%, 37.4% { + margin-top: 15vw; + margin-left: 80% } - 60%, 79.9% { - margin-top: 30%; - margin-left: 20%; + 37.5%, 49.9% { + margin-top: 28vw; + margin-left: 72%; } - 80%, 99.9% { - margin-top: 30%; - margin-left: 80%; + 50%, 62.4% { + margin-top: 22vw; + margin-left: 37%; + } + 62.5%, 74.9% { + margin-top: 10vw; + margin-left: 66%; + } + 75%, 87.4% { + margin-top: 25vw; + margin-left: 49%; + } + 87.5%, 99.9% { + margin-top: 18vw; + margin-left: 58%; } } diff --git a/frontend/src/app/components/start/start.component.ts b/frontend/src/app/components/start/start.component.ts index 18cd0ed30..b05d163e3 100644 --- a/frontend/src/app/components/start/start.component.ts +++ b/frontend/src/app/components/start/start.component.ts @@ -1,4 +1,4 @@ -import { Component, ElementRef, HostListener, OnInit, OnDestroy, ViewChild, Input, DoCheck } from '@angular/core'; +import { Component, ElementRef, HostListener, OnInit, OnDestroy, ViewChild, Input, ChangeDetectorRef, ChangeDetectionStrategy, AfterViewChecked } from '@angular/core'; import { Subscription } from 'rxjs'; import { MarkBlockState, StateService } from '../../services/state.service'; import { specialBlocks } from '../../app.constants'; @@ -8,8 +8,9 @@ import { BlockExtended } from '../../interfaces/node-api.interface'; selector: 'app-start', templateUrl: './start.component.html', styleUrls: ['./start.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush }) -export class StartComponent implements OnInit, OnDestroy, DoCheck { +export class StartComponent implements OnInit, AfterViewChecked, OnDestroy { @Input() showLoadingIndicator = false; interval = 60; @@ -23,7 +24,7 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { timeLtrSubscription: Subscription; timeLtr: boolean = this.stateService.timeLtr.value; chainTipSubscription: Subscription; - chainTip: number = -1; + chainTip: number = 100; tipIsSet: boolean = false; lastMark: MarkBlockState; markBlockSubscription: Subscription; @@ -41,7 +42,8 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { blocksPerPage: number = 1; pageWidth: number; firstPageWidth: number; - minScrollWidth: number; + minScrollWidth: number = 40 + (155 * (8 + (2 * Math.ceil(window.innerWidth / 155)))); + currentScrollWidth: number = null; pageIndex: number = 0; pages: any[] = []; pendingMark: number | null = null; @@ -49,25 +51,24 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { lastUpdate: number = 0; lastMouseX: number; velocity: number = 0; - mempoolOffset: number = 0; + mempoolOffset: number = null; + mempoolWidth: number = 0; + scrollLeft: number = null; - private resizeObserver: ResizeObserver; chainWidth: number = window.innerWidth; menuOpen: boolean = false; menuSliding: boolean = false; menuTimeout: number; + hasMenu = false; + constructor( private stateService: StateService, + private cd: ChangeDetectorRef, ) { this.isiOS = ['iPhone','iPod','iPad'].includes((navigator as any)?.userAgentData?.platform || navigator.platform); - } - - ngDoCheck(): void { - if (this.pendingOffset != null) { - const offset = this.pendingOffset; - this.pendingOffset = null; - this.addConvertedScrollOffset(offset); + if (this.stateService.network === '') { + this.hasMenu = true; } } @@ -77,6 +78,7 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { this.blockCount = blocks.length; this.dynamicBlocksAmount = Math.min(this.blockCount, this.stateService.env.KEEP_BLOCKS_AMOUNT, 8); this.firstPageWidth = 40 + (this.blockWidth * this.dynamicBlocksAmount); + this.minScrollWidth = 40 + (8 * this.blockWidth) + (this.pageWidth * 2); if (this.blockCount <= Math.min(8, this.stateService.env.KEEP_BLOCKS_AMOUNT)) { this.onResize(); } @@ -122,7 +124,7 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { this.scrollToBlock(scrollToHeight); } } - if (!this.tipIsSet || (blockHeight < 0 && !this.mempoolOffset)) { + if (!this.tipIsSet || (blockHeight < 0 && this.mempoolOffset == null)) { this.pendingMark = blockHeight; } } @@ -145,12 +147,15 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { } } } - if (specialBlocks[block.height] && specialBlocks[block.height].networks.includes(this.stateService.network || 'mainnet')) { - this.specialEvent = true; - this.eventName = specialBlocks[block.height].labelEventCompleted; - setTimeout(() => { + for (const block of blocks) { + if (specialBlocks[block.height] && specialBlocks[block.height].networks.includes(this.stateService.network || 'mainnet')) { + this.specialEvent = true; + this.eventName = specialBlocks[block.height].labelEventCompleted; + } + if (specialBlocks[block.height - 8] && specialBlocks[block.height - 8].networks.includes(this.stateService.network || 'mainnet')) { this.specialEvent = false; - }, 60 * 60 * 1000); + this.eventName = ''; + } } }); this.resetScrollSubscription = this.stateService.resetScroll$.subscribe(reset => { @@ -168,15 +173,47 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { }); } + ngAfterViewChecked(): void { + if (this.currentScrollWidth !== this.blockchainContainer?.nativeElement?.scrollWidth) { + this.currentScrollWidth = this.blockchainContainer?.nativeElement?.scrollWidth; + if (this.pendingOffset != null) { + const delta = this.pendingOffset - (this.mempoolOffset || 0); + this.mempoolOffset = this.pendingOffset; + this.currentScrollWidth = this.blockchainContainer?.nativeElement?.scrollWidth; + this.pendingOffset = null; + this.addConvertedScrollOffset(delta); + this.applyPendingMarkArrow(); + } else { + this.applyScrollLeft(); + } + } + } + onMempoolOffsetChange(offset): void { - const delta = offset - this.mempoolOffset; - this.addConvertedScrollOffset(delta); - this.mempoolOffset = offset; - this.applyPendingMarkArrow(); + if (offset !== this.mempoolOffset) { + this.pendingOffset = offset; + } + } + + applyScrollLeft(): void { + if (this.blockchainContainer?.nativeElement?.scrollWidth) { + let lastScrollLeft = null; + while (this.scrollLeft < 0 && this.shiftPagesForward() && lastScrollLeft !== this.scrollLeft) { + lastScrollLeft = this.scrollLeft; + this.scrollLeft += this.pageWidth; + } + lastScrollLeft = null; + while (this.scrollLeft > this.blockchainContainer.nativeElement.scrollWidth && this.shiftPagesBack() && lastScrollLeft !== this.scrollLeft) { + lastScrollLeft = this.scrollLeft; + this.scrollLeft -= this.pageWidth; + } + this.blockchainContainer.nativeElement.scrollLeft = this.scrollLeft; + } + this.cd.detectChanges(); } applyPendingMarkArrow(): void { - if (this.pendingMark != null) { + if (this.pendingMark != null && this.pendingMark <= this.chainTip) { if (this.pendingMark < 0) { this.scrollToBlock(this.chainTip - this.pendingMark); } else { @@ -191,6 +228,7 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { window.clearTimeout(this.menuTimeout); this.menuTimeout = window.setTimeout(() => { this.menuSliding = false; + this.cd.markForCheck(); }, 300); } @@ -200,34 +238,33 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { this.isMobile = this.chainWidth <= 767.98; let firstVisibleBlock; let offset; - if (this.blockchainContainer?.nativeElement != null) { - this.pages.forEach(page => { - const left = page.offset - this.getConvertedScrollOffset(); - const right = left + this.pageWidth; - if (left <= 0 && right > 0) { - const blockIndex = Math.max(0, Math.floor(left / -this.blockWidth)); - firstVisibleBlock = page.height - blockIndex; - offset = left + (blockIndex * this.blockWidth); - } - }); - } + this.pages.forEach(page => { + const left = page.offset - this.getConvertedScrollOffset(this.scrollLeft); + const right = left + this.pageWidth; + if (left <= 0 && right > 0) { + const blockIndex = Math.max(0, Math.floor(left / -this.blockWidth)); + firstVisibleBlock = page.height - blockIndex; + offset = left + (blockIndex * this.blockWidth); + } + }); this.blocksPerPage = Math.ceil(this.chainWidth / this.blockWidth); this.pageWidth = this.blocksPerPage * this.blockWidth; - this.minScrollWidth = this.firstPageWidth + (this.pageWidth * 2); + this.minScrollWidth = 40 + (8 * this.blockWidth) + (this.pageWidth * 2); if (firstVisibleBlock != null) { - this.scrollToBlock(firstVisibleBlock, offset + (this.isMobile ? this.blockWidth : 0)); + this.scrollToBlock(firstVisibleBlock, offset); } else { this.updatePages(); } + this.cd.markForCheck(); } onMouseDown(event: MouseEvent) { if (!(event.which > 1 || event.button > 0)) { this.mouseDragStartX = event.clientX; this.resetMomentum(event.clientX); - this.blockchainScrollLeftInit = this.blockchainContainer.nativeElement.scrollLeft; + this.blockchainScrollLeftInit = this.scrollLeft; } } onPointerDown(event: PointerEvent) { @@ -253,8 +290,8 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { if (this.mouseDragStartX != null) { this.updateVelocity(event.clientX); this.stateService.setBlockScrollingInProgress(true); - this.blockchainContainer.nativeElement.scrollLeft = - this.blockchainScrollLeftInit + this.mouseDragStartX - event.clientX; + this.scrollLeft = this.blockchainScrollLeftInit + this.mouseDragStartX - event.clientX; + this.applyScrollLeft(); } } @HostListener('document:mouseup', []) @@ -310,25 +347,31 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { } else { this.velocity += dv; } - this.blockchainContainer.nativeElement.scrollLeft -= displacement; + this.scrollLeft -= displacement; + this.applyScrollLeft(); this.animateMomentum(); } }); } onScroll(e) { + if (this.blockchainContainer?.nativeElement?.scrollLeft == null) { + return; + } + this.scrollLeft = this.blockchainContainer?.nativeElement?.scrollLeft; const middlePage = this.pageIndex === 0 ? this.pages[0] : this.pages[1]; // compensate for css transform const translation = (this.isMobile ? this.chainWidth * 0.95 : this.chainWidth * 0.5); const backThreshold = middlePage.offset + (this.pageWidth * 0.5) + translation; const forwardThreshold = middlePage.offset - (this.pageWidth * 0.5) + translation; - const scrollLeft = this.getConvertedScrollOffset(); - if (scrollLeft > backThreshold) { + this.scrollLeft = this.blockchainContainer.nativeElement.scrollLeft; + const offsetScroll = this.getConvertedScrollOffset(this.scrollLeft); + if (offsetScroll > backThreshold) { if (this.shiftPagesBack()) { this.addConvertedScrollOffset(-this.pageWidth); this.blockchainScrollLeftInit -= this.pageWidth; } - } else if (scrollLeft < forwardThreshold) { + } else if (offsetScroll < forwardThreshold) { if (this.shiftPagesForward()) { this.addConvertedScrollOffset(this.pageWidth); this.blockchainScrollLeftInit += this.pageWidth; @@ -337,10 +380,6 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { } scrollToBlock(height, blockOffset = 0) { - if (!this.blockchainContainer?.nativeElement) { - setTimeout(() => { this.scrollToBlock(height, blockOffset); }, 50); - return; - } if (this.isMobile) { blockOffset -= this.blockWidth; } @@ -348,15 +387,15 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { const pages = []; this.pageIndex = Math.max(viewingPageIndex - 1, 0); let viewingPage = this.getPageAt(viewingPageIndex); - const isLastPage = viewingPage.height < this.blocksPerPage; + const isLastPage = viewingPage.height <= 0; if (isLastPage) { this.pageIndex = Math.max(viewingPageIndex - 2, 0); viewingPage = this.getPageAt(viewingPageIndex); } - const left = viewingPage.offset - this.getConvertedScrollOffset(); + const left = viewingPage.offset - this.getConvertedScrollOffset(this.scrollLeft); const blockIndex = viewingPage.height - height; const targetOffset = (this.blockWidth * blockIndex) + left; - let deltaOffset = targetOffset - blockOffset; + const deltaOffset = targetOffset - blockOffset; if (isLastPage) { pages.push(this.getPageAt(viewingPageIndex - 2)); @@ -386,6 +425,7 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { pages.push(this.getPageAt(this.pageIndex + 1)); pages.push(this.getPageAt(this.pageIndex + 2)); this.pages = pages; + this.cd.markForCheck(); } shiftPagesBack(): boolean { @@ -439,44 +479,40 @@ export class StartComponent implements OnInit, OnDestroy, DoCheck { blockInViewport(height: number): boolean { const firstHeight = this.pages[0].height; const translation = (this.isMobile ? this.chainWidth * 0.95 : this.chainWidth * 0.5); - const firstX = this.pages[0].offset - this.getConvertedScrollOffset() + translation; + const firstX = this.pages[0].offset - this.getConvertedScrollOffset(this.scrollLeft) + translation; const xPos = firstX + ((firstHeight - height) * 155); return xPos > -55 && xPos < (this.chainWidth - 100); } - getConvertedScrollOffset(): number { + getConvertedScrollOffset(scrollLeft): number { if (this.timeLtr) { - return -(this.blockchainContainer?.nativeElement?.scrollLeft || 0) - this.mempoolOffset; + return -(scrollLeft || 0) - (this.mempoolOffset || 0); } else { - return (this.blockchainContainer?.nativeElement?.scrollLeft || 0) - this.mempoolOffset; + return (scrollLeft || 0) - (this.mempoolOffset || 0); } } setScrollLeft(offset: number): void { if (this.timeLtr) { - this.blockchainContainer.nativeElement.scrollLeft = offset - this.mempoolOffset; + this.scrollLeft = offset - (this.mempoolOffset || 0); } else { - this.blockchainContainer.nativeElement.scrollLeft = offset + this.mempoolOffset; + this.scrollLeft = offset + (this.mempoolOffset || 0); } + this.applyScrollLeft(); } addConvertedScrollOffset(offset: number): void { - if (!this.blockchainContainer?.nativeElement) { - this.pendingOffset = offset; - return; - } if (this.timeLtr) { - this.blockchainContainer.nativeElement.scrollLeft -= offset; + this.scrollLeft -= offset; } else { - this.blockchainContainer.nativeElement.scrollLeft += offset; + this.scrollLeft += offset; } + this.applyScrollLeft(); } ngOnDestroy() { - if (this.blockchainContainer?.nativeElement) { - // clean up scroll position to prevent caching wrong scroll in Firefox - this.setScrollLeft(0); - } + // clean up scroll position to prevent caching wrong scroll in Firefox + this.setScrollLeft(0); this.timeLtrSubscription.unsubscribe(); this.chainTipSubscription.unsubscribe(); this.markBlockSubscription.unsubscribe(); diff --git a/frontend/src/app/components/statistics/statistics.component.html b/frontend/src/app/components/statistics/statistics.component.html index 29089e43d..fa63590b0 100644 --- a/frontend/src/app/components/statistics/statistics.component.html +++ b/frontend/src/app/components/statistics/statistics.component.html @@ -14,7 +14,7 @@ [class]="(stateService.env.MINING_DASHBOARD || stateService.env.LIGHTNING) ? 'mining' : 'no-menu'" (click)="saveGraphPreference()">
- + @@ -69,6 +69,12 @@
Mempool Space K.K.
The Mempool Open Source Project
Mempool Accelerator
Mempool Enterprise
Mempool Liquidity
mempool.space
Be your own explorer
Explore the full Bitcoin ecosystem
Mempool Goggles
@@ -89,11 +95,16 @@

The mempool Square Logo



- +

The mempool Blocks Logo



+ +

+

The mempool Blocks 3 | 2 Logo

+

+

@@ -304,8 +315,7 @@

Also, if you are using our Marks in a way described in the sections "Uses for Which We Are Granting a License," you must include the following trademark attribution at the foot of the webpage where you have used the Mark (or, if in a book, on the credits page), on any packaging or labeling, and on advertising or marketing materials:

-

“The Mempool Space K.K.™, The Mempool Open Source Project®, mempool.space™, the mempool logo®, the mempool.space logos™, the mempool square logo®, and the mempool blocks logo™ are either registered trademarks or trademarks of Mempool Space K.K in Japan, the United States, and/or other countries, and are used with permission. Mempool Space K.K. has no affiliation with and does not sponsor or endorse the information provided herein.”

- +

"The Mempool Open Source Project®, Mempool Accelerator™, Mempool Enterprise®, Mempool Liquidity™, mempool.space®, Be your own explorer™, Explore the full Bitcoin ecosystem®, Mempool Goggles™, the mempool logo;, the mempool Square logo;, the mempool Blocks logo;, the mempool Blocks 3 | 2 logo;, the mempool.space Vertical Logo;, and the mempool.space Horizontal logo are either registered trademarks or trademarks of Mempool Space K.K in Japan, the United States, and/or other countries, and are used with permission. Mempool Space K.K. has no affiliation with and does not sponsor or endorse the information provided herein."

  • What to Do When You See Abuse

  • diff --git a/frontend/src/app/components/trademark-policy/trademark-policy.component.ts b/frontend/src/app/components/trademark-policy/trademark-policy.component.ts index 08f16264a..b8f53afcf 100644 --- a/frontend/src/app/components/trademark-policy/trademark-policy.component.ts +++ b/frontend/src/app/components/trademark-policy/trademark-policy.component.ts @@ -17,6 +17,6 @@ export class TrademarkPolicyComponent { ngOnInit(): void { this.seoService.setTitle('Trademark Policy'); - this.seoService.setDescription('An overview of the trademarks registered by Mempool Space K.K. and The Mempool Open Source Project™ and what we consider to be lawful usage of those trademarks.'); + this.seoService.setDescription('An overview of the trademarks registered by Mempool Space K.K. and The Mempool Open Source Project® and what we consider to be lawful usage of those trademarks.'); } } diff --git a/frontend/src/app/components/trademark-policy/trademark-policy.module.ts b/frontend/src/app/components/trademark-policy/trademark-policy.module.ts new file mode 100644 index 000000000..24f70be52 --- /dev/null +++ b/frontend/src/app/components/trademark-policy/trademark-policy.module.ts @@ -0,0 +1,40 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { TrademarkPolicyComponent } from './trademark-policy.component'; +import { SharedModule } from '../../shared/shared.module'; + +const routes: Routes = [ + { + path: '', + component: TrademarkPolicyComponent, + } +]; + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class TrademarkRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + TrademarkRoutingModule, + SharedModule, + ], + declarations: [ + TrademarkPolicyComponent, + ] +}) +export class TrademarkModule { } + + + + + + diff --git a/frontend/src/app/components/transaction/transaction-preview.component.html b/frontend/src/app/components/transaction/transaction-preview.component.html index 679138b14..63a11a8f0 100644 --- a/frontend/src/app/components/transaction/transaction-preview.component.html +++ b/frontend/src/app/components/transaction/transaction-preview.component.html @@ -40,7 +40,7 @@
    - Coinbase + Coinbase {{ tx.vin[0].scriptsig | hex2ascii }}
    diff --git a/frontend/src/app/components/transaction/transaction-preview.component.ts b/frontend/src/app/components/transaction/transaction-preview.component.ts index 153d9b22a..313442dbf 100644 --- a/frontend/src/app/components/transaction/transaction-preview.component.ts +++ b/frontend/src/app/components/transaction/transaction-preview.component.ts @@ -88,7 +88,9 @@ export class TransactionPreviewComponent implements OnInit, OnDestroy { this.seoService.setTitle( $localize`:@@bisq.transaction.browser-title:Transaction: ${this.txId}:INTERPOLATION:` ); - this.seoService.setDescription($localize`:@@meta.description.bitcoin.transaction:Get real-time status, addresses, fees, script info, and more for ${this.stateService.network==='liquid'||this.stateService.network==='liquidtestnet'?'Liquid':'Bitcoin'}${seoDescriptionNetwork(this.stateService.network)} transaction with txid {txid}.`); + const network = this.stateService.network === 'liquid' || this.stateService.network === 'liquidtestnet' ? 'Liquid' : 'Bitcoin'; + const seoDescription = seoDescriptionNetwork(this.stateService.network); + this.seoService.setDescription($localize`:@@meta.description.bitcoin.transaction:Get real-time status, addresses, fees, script info, and more for ${network}${seoDescription} transaction with txid ${this.txId}.`); this.resetTransaction(); return merge( of(true), diff --git a/frontend/src/app/components/transaction/transaction.component.html b/frontend/src/app/components/transaction/transaction.component.html index 006870864..2748b9ffc 100644 --- a/frontend/src/app/components/transaction/transaction.component.html +++ b/frontend/src/app/components/transaction/transaction.component.html @@ -6,12 +6,15 @@ -
    Features @@ -292,9 +298,13 @@ Virtual size
    Adjusted vsize
    Adjusted vsize + + + +
    WeightLocktime
    Sigops
    Sigops + + + +
    Transaction hex
    Accelerated fee rateEffective fee rate
    Accelerated fee rateEffective fee rate
    - - - + + + + + + +   + Accelerated +
    - +
    +
    @@ -204,7 +204,7 @@ Peg-out to - + @@ -222,7 +222,7 @@
    +
    diff --git a/frontend/src/app/components/transactions-list/transactions-list.component.scss b/frontend/src/app/components/transactions-list/transactions-list.component.scss index 14559089a..b80c4da4c 100644 --- a/frontend/src/app/components/transactions-list/transactions-list.component.scss +++ b/frontend/src/app/components/transactions-list/transactions-list.component.scss @@ -46,7 +46,16 @@ } td.amount { - width: 32.5%; + width: 36%; + @media (max-width: 576px) { + width: 50%; + } +} +td.amount.large { + width: 45%; + @media (max-width: 576px) { + width: 60%; + } } .extra-info { diff --git a/frontend/src/app/components/transactions-list/transactions-list.component.ts b/frontend/src/app/components/transactions-list/transactions-list.component.ts index c49ff0e3c..da9bdfe04 100644 --- a/frontend/src/app/components/transactions-list/transactions-list.component.ts +++ b/frontend/src/app/components/transactions-list/transactions-list.component.ts @@ -6,7 +6,7 @@ import { Outspend, Transaction, Vin, Vout } from '../../interfaces/electrs.inter import { ElectrsApiService } from '../../services/electrs-api.service'; import { environment } from '../../../environments/environment'; import { AssetsService } from '../../services/assets.service'; -import { filter, map, tap, switchMap, shareReplay } from 'rxjs/operators'; +import { filter, map, tap, switchMap, shareReplay, catchError } from 'rxjs/operators'; import { BlockExtended } from '../../interfaces/node-api.interface'; import { ApiService } from '../../services/api.service'; import { PriceService } from '../../services/price.service'; @@ -75,7 +75,7 @@ export class TransactionsListComponent implements OnInit, OnChanges { for (let i = 0; i < txIds.length; i += 50) { batches.push(txIds.slice(i, i + 50)); } - return forkJoin(batches.map(batch => this.apiService.getOutspendsBatched$(batch))); + return forkJoin(batches.map(batch => { return this.electrsApiService.cachedRequest(this.electrsApiService.getOutspendsBatched$, 250, batch); })); } else { return of([]); } @@ -90,6 +90,7 @@ export class TransactionsListComponent implements OnInit, OnChanges { outspends.forEach((outspend, i) => { transactions[i]._outspends = outspend; }); + this.ref.markForCheck(); }), ), this.stateService.utxoSpent$ @@ -108,6 +109,10 @@ export class TransactionsListComponent implements OnInit, OnChanges { .pipe( filter(() => this.stateService.env.LIGHTNING), switchMap((txIds) => this.apiService.getChannelByTxIds$(txIds)), + catchError((error) => { + // handle 404 + return of([]); + }), tap((channels) => { if (!this.transactions) { return; @@ -151,17 +156,45 @@ export class TransactionsListComponent implements OnInit, OnChanges { } if (this.address) { - const addressIn = tx.vout - .filter((v: Vout) => v.scriptpubkey_address === this.address) - .map((v: Vout) => v.value || 0) - .reduce((a: number, b: number) => a + b, 0); + const isP2PKUncompressed = this.address.length === 130; + const isP2PKCompressed = this.address.length === 66; + if (isP2PKCompressed) { + const addressIn = tx.vout + .filter((v: Vout) => v.scriptpubkey === '21' + this.address + 'ac') + .map((v: Vout) => v.value || 0) + .reduce((a: number, b: number) => a + b, 0); - const addressOut = tx.vin - .filter((v: Vin) => v.prevout && v.prevout.scriptpubkey_address === this.address) - .map((v: Vin) => v.prevout.value || 0) - .reduce((a: number, b: number) => a + b, 0); + const addressOut = tx.vin + .filter((v: Vin) => v.prevout && v.prevout.scriptpubkey === '21' + this.address + 'ac') + .map((v: Vin) => v.prevout.value || 0) + .reduce((a: number, b: number) => a + b, 0); - tx['addressValue'] = addressIn - addressOut; + tx['addressValue'] = addressIn - addressOut; + } else if (isP2PKUncompressed) { + const addressIn = tx.vout + .filter((v: Vout) => v.scriptpubkey === '41' + this.address + 'ac') + .map((v: Vout) => v.value || 0) + .reduce((a: number, b: number) => a + b, 0); + + const addressOut = tx.vin + .filter((v: Vin) => v.prevout && v.prevout.scriptpubkey === '41' + this.address + 'ac') + .map((v: Vin) => v.prevout.value || 0) + .reduce((a: number, b: number) => a + b, 0); + + tx['addressValue'] = addressIn - addressOut; + } else { + const addressIn = tx.vout + .filter((v: Vout) => v.scriptpubkey_address === this.address) + .map((v: Vout) => v.value || 0) + .reduce((a: number, b: number) => a + b, 0); + + const addressOut = tx.vin + .filter((v: Vin) => v.prevout && v.prevout.scriptpubkey_address === this.address) + .map((v: Vin) => v.prevout.value || 0) + .reduce((a: number, b: number) => a + b, 0); + + tx['addressValue'] = addressIn - addressOut; + } } this.priceService.getBlockPrice$(tx.status.block_time).pipe( diff --git a/frontend/src/app/components/tx-bowtie-graph-tooltip/tx-bowtie-graph-tooltip.component.html b/frontend/src/app/components/tx-bowtie-graph-tooltip/tx-bowtie-graph-tooltip.component.html index 9ebe36a87..1bc141f49 100644 --- a/frontend/src/app/components/tx-bowtie-graph-tooltip/tx-bowtie-graph-tooltip.component.html +++ b/frontend/src/app/components/tx-bowtie-graph-tooltip/tx-bowtie-graph-tooltip.component.html @@ -16,7 +16,7 @@ -

    Coinbase

    +

    Coinbase

    diff --git a/frontend/src/app/components/tx-bowtie-graph/tx-bowtie-graph.component.ts b/frontend/src/app/components/tx-bowtie-graph/tx-bowtie-graph.component.ts index 97e74957e..043c9ea3b 100644 --- a/frontend/src/app/components/tx-bowtie-graph/tx-bowtie-graph.component.ts +++ b/frontend/src/app/components/tx-bowtie-graph/tx-bowtie-graph.component.ts @@ -8,6 +8,7 @@ import { ApiService } from '../../services/api.service'; import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe'; import { AssetsService } from '../../services/assets.service'; import { environment } from '../../../environments/environment'; +import { ElectrsApiService } from '../../services/electrs-api.service'; interface SvgLine { path: string; @@ -100,7 +101,7 @@ export class TxBowtieGraphComponent implements OnInit, OnChanges { private router: Router, private relativeUrlPipe: RelativeUrlPipe, private stateService: StateService, - private apiService: ApiService, + private electrsApiService: ElectrsApiService, private assetsService: AssetsService, @Inject(LOCALE_ID) private locale: string, ) { @@ -123,7 +124,7 @@ export class TxBowtieGraphComponent implements OnInit, OnChanges { .pipe( switchMap((txid) => { if (!this.cached) { - return this.apiService.getOutspendsBatched$([txid]); + return this.electrsApiService.cachedRequest(this.electrsApiService.getOutspendsBatched$, 250, [txid]); } else { return of(null); } diff --git a/frontend/src/app/components/tx-bowtie-graph/tx-bowtie.module.ts b/frontend/src/app/components/tx-bowtie-graph/tx-bowtie.module.ts new file mode 100644 index 000000000..617425e7a --- /dev/null +++ b/frontend/src/app/components/tx-bowtie-graph/tx-bowtie.module.ts @@ -0,0 +1,28 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { SharedModule } from '../../shared/shared.module'; +import { TxBowtieGraphComponent } from '../tx-bowtie-graph/tx-bowtie-graph.component'; +import { TxBowtieGraphTooltipComponent } from '../tx-bowtie-graph-tooltip/tx-bowtie-graph-tooltip.component'; + + +@NgModule({ + imports: [ + CommonModule, + SharedModule, + ], + declarations: [ + TxBowtieGraphComponent, + TxBowtieGraphTooltipComponent, + ], + exports: [ + TxBowtieGraphComponent, + TxBowtieGraphTooltipComponent, + ] +}) +export class TxBowtieModule { } + + + + + + diff --git a/frontend/src/app/dashboard/dashboard.component.html b/frontend/src/app/dashboard/dashboard.component.html index fdd2131fe..4f7d5d2ff 100644 --- a/frontend/src/app/dashboard/dashboard.component.html +++ b/frontend/src/app/dashboard/dashboard.component.html @@ -1,7 +1,7 @@ -
    +
    - +
    Transaction Fees
    @@ -16,67 +16,52 @@
    -
    -
    - -
    +
    + +
    Mempool Goggles: {{ goggleCycle[goggleIndex].name }}
    +   + +
    +
    +
    + +
    +
    +
    +
    - - -
    - -
    -
    -
    - - -
    - -
    -
    - - - - - - - - -
    - - - - - {{ group.name }} -
    -
    - + +
    Incoming Transactions
    -
    New fee Status
    @@ -99,7 +84,7 @@ Mined Full RBF - RBF + RBF
    - - + - - + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -233,40 +268,67 @@

    -
    Memory usage
    +
    Memory Usage
     
    -
    /
    +
    /
    - -
    -
    -
    L-BTC in circulation
    - -

    {{ liquidPegsMonth.series.slice(-1)[0] | number: '1.2-2' }} L-BTC

    -
    + +
    + +
    + +
    +
    +
    + +
    +
    + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    - -
    Incoming transactions
    - - -  Backend is synchronizing ({{ mempoolLoadingStatus$ | async }}%) - - -
    -
     
    -
    ‎{{ mempoolInfoData.value.vBytesPerSecond | ceil | number }} vB/s
    -
    ‎{{ mempoolInfoData.value.vBytesPerSecond * 4 | ceil | number }} WU/s
    -
    -
    -
    -
    + + +
    + Audit in progress: Bitcoin block height #{{ auditStatus.lastBlockAudit }} / #{{ auditStatus.bitcoinHeaders }} +
    +
    +
    \ No newline at end of file diff --git a/frontend/src/app/dashboard/dashboard.component.scss b/frontend/src/app/dashboard/dashboard.component.scss index 884ba1027..b039e36f8 100644 --- a/frontend/src/app/dashboard/dashboard.component.scss +++ b/frontend/src/app/dashboard/dashboard.component.scss @@ -44,8 +44,11 @@ .graph-card { height: 100%; + @media (min-width: 768px) { + height: 415px; + } @media (min-width: 992px) { - height: 385px; + height: 510px; } } @@ -56,6 +59,10 @@ display: flex; flex-direction: row; } + &.lbtc-pegs-stats { + display: flex; + flex-direction: row; + } h5 { margin-bottom: 10px; } @@ -66,7 +73,7 @@ @media (min-width: 485px) { margin: 0px auto 10px; } - @media (min-width: 785px) { + @media (min-width: 768px) { margin: 0px auto 0px; } &:last-child { @@ -97,6 +104,9 @@ color: #ffffff66; font-size: 12px; } + .bitcoin-color { + color: #b86d12; + } } .progress { width: 90%; @@ -255,6 +265,12 @@ .mempool-graph { height: 255px; + @media (min-width: 768px) { + height: 285px; + } + @media (min-width: 992px) { + height: 370px; + } } .loadingGraphs{ height: 250px; @@ -361,3 +377,64 @@ text-decoration: none; color: inherit; } + +.mempool-block-wrapper { + max-height: 410px; + max-width: 410px; + margin: auto; + + @media (min-width: 768px) { + max-height: 344px; + max-width: 344px; + } + @media (min-width: 992px) { + max-height: 410px; + max-width: 410px; + } +} + +.goggle-badge { + margin: 6px 5px 8px; + background: none; + border: solid 2px #105fb0; + cursor: pointer; + + &.active { + background: #105fb0; + } +} + +.btn-xs { + padding: 0.35rem 0.5rem; + font-size: 12px; +} + +.quick-filter { + margin-top: 5px; + margin-bottom: 6px; +} + +.card-liquid { + background-color: #1d1f31; + height: 418px; + @media (min-width: 992px) { + height: 512px; + } + &.smaller { + height: 408px; + } +} + +.card-title-liquid { + padding-top: 20px; + margin-left: 10px; +} + +.in-progress-message { + position: relative; + color: #ffffff91; + margin-top: 20px; + text-align: center; + padding-bottom: 3px; + font-weight: 500; +} diff --git a/frontend/src/app/dashboard/dashboard.component.ts b/frontend/src/app/dashboard/dashboard.component.ts index 8a34bf768..1f380a99f 100644 --- a/frontend/src/app/dashboard/dashboard.component.ts +++ b/frontend/src/app/dashboard/dashboard.component.ts @@ -1,12 +1,13 @@ -import { AfterViewInit, ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core'; -import { combineLatest, merge, Observable, of, Subscription } from 'rxjs'; -import { catchError, filter, map, scan, share, switchMap, tap } from 'rxjs/operators'; -import { BlockExtended, OptimizedMempoolStats } from '../interfaces/node-api.interface'; +import { AfterViewInit, ChangeDetectionStrategy, Component, HostListener, OnDestroy, OnInit } from '@angular/core'; +import { combineLatest, EMPTY, fromEvent, interval, merge, Observable, of, Subject, Subscription, timer } from 'rxjs'; +import { catchError, delayWhen, distinctUntilChanged, filter, map, scan, share, shareReplay, startWith, switchMap, takeUntil, tap, throttleTime } from 'rxjs/operators'; +import { AuditStatus, BlockExtended, CurrentPegs, FederationAddress, OptimizedMempoolStats, PegsVolume, RecentPeg } from '../interfaces/node-api.interface'; import { MempoolInfo, TransactionStripped, ReplacementInfo } from '../interfaces/websocket.interface'; import { ApiService } from '../services/api.service'; import { StateService } from '../services/state.service'; import { WebsocketService } from '../services/websocket.service'; import { SeoService } from '../services/seo.service'; +import { ActiveFilter, FilterMode, toFlags } from '../shared/filters.utils'; interface MempoolBlocksData { blocks: number; @@ -32,7 +33,6 @@ interface MempoolStatsData { changeDetection: ChangeDetectionStrategy.OnPush }) export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { - featuredAssets$: Observable; network$: Observable; mempoolBlocksData$: Observable; mempoolInfoData$: Observable; @@ -47,8 +47,40 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { transactionsWeightPerSecondOptions: any; isLoadingWebSocket$: Observable; liquidPegsMonth$: Observable; + currentPeg$: Observable; + auditStatus$: Observable; + auditUpdated$: Observable; + liquidReservesMonth$: Observable; + currentReserves$: Observable; + recentPegsList$: Observable; + pegsVolume$: Observable; + federationAddresses$: Observable; + federationAddressesNumber$: Observable; + federationUtxosNumber$: Observable; + fullHistory$: Observable; + isLoad: boolean = true; + filterSubscription: Subscription; + mempoolInfoSubscription: Subscription; currencySubscription: Subscription; currency: string; + incomingGraphHeight: number = 300; + lbtcPegGraphHeight: number = 320; + private lastPegBlockUpdate: number = 0; + private lastPegAmount: string = ''; + private lastReservesBlockUpdate: number = 0; + + goggleResolution = 82; + goggleCycle: { index: number, name: string, mode: FilterMode, filters: string[] }[] = [ + { index: 0, name: 'All', mode: 'and', filters: [] }, + { index: 1, name: 'Consolidation', mode: 'and', filters: ['consolidation'] }, + { index: 2, name: 'Coinjoin', mode: 'and', filters: ['coinjoin'] }, + { index: 3, name: 'Data', mode: 'or', filters: ['inscription', 'fake_pubkey', 'op_return'] }, + ]; + goggleFlags = 0n; + goggleMode: FilterMode = 'and'; + goggleIndex = 0; + + private destroy$ = new Subject(); constructor( public stateService: StateService, @@ -62,11 +94,16 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { } ngOnDestroy(): void { + this.filterSubscription.unsubscribe(); + this.mempoolInfoSubscription.unsubscribe(); this.currencySubscription.unsubscribe(); this.websocketService.stopTrackRbfSummary(); + this.destroy$.next(1); + this.destroy$.complete(); } ngOnInit(): void { + this.onResize(); this.isLoadingWebSocket$ = this.stateService.isLoadingWebSocket$; this.seoService.resetTitle(); this.seoService.resetDescription(); @@ -78,11 +115,34 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { map((indicators) => indicators.mempool !== undefined ? indicators.mempool : 100) ); + this.filterSubscription = this.stateService.activeGoggles$.subscribe((active: ActiveFilter) => { + const activeFilters = active.filters.sort().join(','); + for (const goggle of this.goggleCycle) { + if (goggle.mode === active.mode) { + const goggleFilters = goggle.filters.sort().join(','); + if (goggleFilters === activeFilters) { + this.goggleIndex = goggle.index; + this.goggleFlags = toFlags(goggle.filters); + this.goggleMode = goggle.mode; + return; + } + } + } + this.goggleCycle.push({ + index: this.goggleCycle.length, + name: 'Custom', + mode: active.mode, + filters: active.filters, + }); + this.goggleIndex = this.goggleCycle.length - 1; + this.goggleFlags = toFlags(active.filters); + this.goggleMode = active.mode; + }); + this.mempoolInfoData$ = combineLatest([ this.stateService.mempoolInfo$, this.stateService.vbytesPerSecond$ - ]) - .pipe( + ]).pipe( map(([mempoolInfo, vbytesPerSecond]) => { const percent = Math.round((Math.min(vbytesPerSecond, this.vBytesPerSecondLimit) / this.vBytesPerSecondLimit) * 100); @@ -112,6 +172,8 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { }) ); + this.mempoolInfoSubscription = this.mempoolInfoData$.subscribe(); + this.mempoolBlocksData$ = this.stateService.mempoolBlocks$ .pipe( map((mempoolBlocks) => { @@ -125,19 +187,6 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { }) ); - this.featuredAssets$ = this.apiService.listFeaturedAssets$() - .pipe( - map((featured) => { - const newArray = []; - for (const feature of featured) { - if (feature.ticker !== 'L-BTC' && feature.asset) { - newArray.push(feature); - } - } - return newArray.slice(0, 4); - }), - ); - this.transactions$ = this.stateService.transactions$ .pipe( scan((acc, tx) => { @@ -203,9 +252,101 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { share(), ); - if (this.stateService.network === 'liquid' || this.stateService.network === 'liquidtestnet') { - this.liquidPegsMonth$ = this.apiService.listLiquidPegsMonth$() + if (this.stateService.network === 'liquid') { + this.auditStatus$ = this.stateService.blocks$.pipe( + takeUntil(this.destroy$), + throttleTime(40000), + delayWhen(_ => this.isLoad ? timer(0) : timer(2000)), + tap(() => this.isLoad = false), + switchMap(() => this.apiService.federationAuditSynced$()), + shareReplay(1) + ); + + this.currentPeg$ = this.auditStatus$.pipe( + switchMap(_ => + this.apiService.liquidPegs$().pipe( + filter((currentPegs) => currentPegs.lastBlockUpdate >= this.lastPegBlockUpdate), + tap((currentPegs) => { + this.lastPegBlockUpdate = currentPegs.lastBlockUpdate; + }) + ) + ), + share() + ); + + this.auditUpdated$ = combineLatest([ + this.auditStatus$, + this.currentPeg$ + ]).pipe( + filter(([auditStatus, _]) => auditStatus.isAuditSynced === true), + map(([auditStatus, currentPeg]) => ({ + lastBlockAudit: auditStatus.lastBlockAudit, + currentPegAmount: currentPeg.amount + })), + switchMap(({ lastBlockAudit, currentPegAmount }) => { + const blockAuditCheck = lastBlockAudit > this.lastReservesBlockUpdate; + const amountCheck = currentPegAmount !== this.lastPegAmount; + this.lastPegAmount = currentPegAmount; + return of(blockAuditCheck || amountCheck); + }), + share() + ); + + this.currentReserves$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => + this.apiService.liquidReserves$().pipe( + filter((currentReserves) => currentReserves.lastBlockUpdate >= this.lastReservesBlockUpdate), + tap((currentReserves) => { + this.lastReservesBlockUpdate = currentReserves.lastBlockUpdate; + }) + ) + ), + share() + ); + + this.recentPegsList$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => this.apiService.recentPegsList$()), + share() + ); + + this.pegsVolume$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => this.apiService.pegsVolume$()), + share() + ); + + this.federationAddresses$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => this.apiService.federationAddresses$()), + share() + ); + + this.federationAddressesNumber$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => this.apiService.federationAddressesNumber$()), + map(count => count.address_count), + share() + ); + + this.federationUtxosNumber$ = this.auditUpdated$.pipe( + filter(auditUpdated => auditUpdated === true), + throttleTime(40000), + switchMap(_ => this.apiService.federationUtxosNumber$()), + map(count => count.utxo_count), + share() + ); + + this.liquidPegsMonth$ = interval(60 * 60 * 1000) .pipe( + startWith(0), + switchMap(() => this.apiService.listLiquidPegsMonth$()), map((pegs) => { const labels = pegs.map(stats => stats.date); const series = pegs.map(stats => parseFloat(stats.amount) / 100000000); @@ -217,6 +358,45 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { }), share(), ); + + this.liquidReservesMonth$ = interval(60 * 60 * 1000).pipe( + startWith(0), + switchMap(() => this.apiService.listLiquidReservesMonth$()), + map(reserves => { + const labels = reserves.map(stats => stats.date); + const series = reserves.map(stats => parseFloat(stats.amount) / 100000000); + return { + series, + labels + }; + }), + share() + ); + + this.fullHistory$ = combineLatest([this.liquidPegsMonth$, this.currentPeg$, this.liquidReservesMonth$, this.currentReserves$]) + .pipe( + map(([liquidPegs, currentPeg, liquidReserves, currentReserves]) => { + liquidPegs.series[liquidPegs.series.length - 1] = parseFloat(currentPeg.amount) / 100000000; + + if (liquidPegs.series.length === liquidReserves?.series.length) { + liquidReserves.series[liquidReserves.series.length - 1] = parseFloat(currentReserves?.amount) / 100000000; + } else if (liquidPegs.series.length === liquidReserves?.series.length + 1) { + liquidReserves.series.push(parseFloat(currentReserves?.amount) / 100000000); + liquidReserves.labels.push(liquidPegs.labels[liquidPegs.labels.length - 1]); + } else { + liquidReserves = { + series: [], + labels: [] + }; + } + + return { + liquidPegs, + liquidReserves + }; + }), + share() + ); } this.currencySubscription = this.stateService.fiatCurrency$.subscribe((fiat) => { @@ -237,4 +417,30 @@ export class DashboardComponent implements OnInit, OnDestroy, AfterViewInit { trackByBlock(index: number, block: BlockExtended) { return block.height; } + + getArrayFromNumber(num: number): number[] { + return Array.from({ length: num }, (_, i) => i + 1); + } + + setFilter(index): void { + const selected = this.goggleCycle[index]; + this.stateService.activeGoggles$.next(selected); + } + + @HostListener('window:resize', ['$event']) + onResize(): void { + if (window.innerWidth >= 992) { + this.incomingGraphHeight = 300; + this.goggleResolution = 82; + this.lbtcPegGraphHeight = 320; + } else if (window.innerWidth >= 768) { + this.incomingGraphHeight = 215; + this.goggleResolution = 80; + this.lbtcPegGraphHeight = 230; + } else { + this.incomingGraphHeight = 180; + this.goggleResolution = 86; + this.lbtcPegGraphHeight = 220; + } + } } diff --git a/frontend/src/app/docs/api-docs/api-docs-data.ts b/frontend/src/app/docs/api-docs/api-docs-data.ts index 3a857fe6a..d79c23e4a 100644 --- a/frontend/src/app/docs/api-docs/api-docs-data.ts +++ b/frontend/src/app/docs/api-docs/api-docs-data.ts @@ -155,6 +155,7 @@ export const restApiDocsData = [ previousRetarget: -4.807005268478962, nextRetargetHeight: 741888, timeAvg: 302328, + adjustedTimeAvg: 302328, timeOffset: 0 }` }, @@ -171,6 +172,7 @@ export const restApiDocsData = [ previousRetarget: -4.807005268478962, nextRetargetHeight: 741888, timeAvg: 302328, + adjustedTimeAvg: 302328, timeOffset: 0 }` }, @@ -187,6 +189,7 @@ export const restApiDocsData = [ previousRetarget: -4.807005268478962, nextRetargetHeight: 741888, timeAvg: 302328, + adjustedTimeAvg: 302328, timeOffset: 0 }` }, @@ -203,12 +206,121 @@ export const restApiDocsData = [ previousRetarget: -4.807005268478962, nextRetargetHeight: 741888, timeAvg: 302328, + adjustedTimeAvg: 302328, timeOffset: 0 }` } } } }, + { + type: "endpoint", + category: "general", + httpRequestMethod: "GET", + fragment: "get-price", + title: "GET Price", + description: { + default: "Returns bitcoin latest price denominated in main currencies." + }, + urlString: "/v1/prices", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + commonJS: ``, + esModule: ``, + curl: `/api/v1/prices`, + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + response: `{ + time: 1703252411, + USD: 43753, + EUR: 40545, + GBP: 37528, + CAD: 58123, + CHF: 37438, + AUD: 64499, + JPY: 6218915 +}` + }, + codeSampleTestnet: emptyCodeSample, + codeSampleSignet: emptyCodeSample, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, + { + type: "endpoint", + category: "general", + httpRequestMethod: "GET", + fragment: "get-historical-price", + title: "GET Historical Price", + description: { + default: "Returns bitcoin historical price denominated in main currencies." + }, + urlString: "/v1/historical-price", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + commonJS: ``, + esModule: ``, + curl: `/api/v1/historical-price`, + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + response: `{ + prices: [ + { + time: 1703692800, + USD: 42972, + EUR: 39590, + GBP: 36803, + CAD: 56883, + CHF: 36486, + AUD: 63006, + JPY: 6124530 + }, + ... + { + time: 1279497600, + USD: 0.08584, + EUR: -1, + GBP: -1, + CAD: -1, + CHF: -1, + AUD: -1, + JPY: -1 + } + ], + exchangeRates: { + USDEUR: 0.92, + USDGBP: 0.86, + USDCAD: 1.32, + USDCHF: 0.85, + USDAUD: 1.47, + USDJPY: 142.52 + } +} +` + }, + codeSampleTestnet: emptyCodeSample, + codeSampleSignet: emptyCodeSample, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, { type: "endpoint", category: "general", @@ -905,7 +1017,7 @@ export const restApiDocsData = [ fragment: "get-address-transactions", title: "GET Address Transactions", description: { - default: "Get transaction history for the specified address/scripthash, sorted with newest first. Returns up to 50 mempool transactions plus the first 25 confirmed transactions. You can request more confirmed transactions using :last_seen_txid (see below)." + default: "Get transaction history for the specified address/scripthash, sorted with newest first. Returns up to 50 mempool transactions plus the first 25 confirmed transactions. You can request more confirmed transactions using an after_txid query parameter." }, urlString: "/address/:address/txs", showConditions: bitcoinNetworks.concat(liquidNetworks), @@ -1409,20 +1521,20 @@ export const restApiDocsData = [ ]` }, codeSampleSignet: { - esModule: [`1wiz18xYmhRX6xStj2b9t1rwWX4GKUgpv`], - commonJS: [`1wiz18xYmhRX6xStj2b9t1rwWX4GKUgpv`], - curl: [`1wiz18xYmhRX6xStj2b9t1rwWX4GKUgpv`], + esModule: [`tb1pu8ysre22dcl6qy5m5w7mjwutw73w4u24slcdh4myq06uhr6q29dqwc3ckt`], + commonJS: [`tb1pu8ysre22dcl6qy5m5w7mjwutw73w4u24slcdh4myq06uhr6q29dqwc3ckt`], + curl: [`tb1pu8ysre22dcl6qy5m5w7mjwutw73w4u24slcdh4myq06uhr6q29dqwc3ckt`], response: `[ { - txid: "e58b47f657b496a083ad9a4fb10c744d5e993028efd9cfba149885334d98bdf5", + txid: "c56a054302df8f8f80c5ac6b86b24ed52bf41d64de640659837c56bc33d10c9e", vout: 0, status: { confirmed: true, - block_height: 698571, - block_hash: "00000000000000000007536c0a664a7d2a01c31569623183eba0768d9a0c163d", - block_time: 1630520708 + block_height: 174923, + block_hash: "000000750e335ff355be2e3754fdada30d107d7d916aef07e2f5d014bec845e5", + block_time: 1703321003 }, - value: 642070789 + value: 546 }, ... ]` @@ -1470,6 +1582,65 @@ export const restApiDocsData = [ } } }, + { + type: "endpoint", + category: "addresses", + httpRequestMethod: "GET", + fragment: "get-address-validate", + title: "GET Address Validation", + description: { + default: "Returns whether an address is valid or not. Available fields: isvalid (boolean), address (string), scriptPubKey (string), isscript (boolean), iswitness (boolean), witness_version (numeric, optional), and witness_program (string, optional).", + }, + urlString: "/v1/validate-address/:address", + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/validate-address/%{1}`, + commonJS: ``, + esModule: ``, + }, + codeSampleMainnet: { + curl: [`1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY`], + response: `{ + isvalid: true, + address: "1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY", + scriptPubKey: "76a914c825a1ecf2a6830c4401620c3a16f1995057c2ab88ac", + isscript: false, + iswitness: false +}` + }, + codeSampleTestnet: { + curl: [`tb1q4kgratttzjvkxfmgd95z54qcq7y6hekdm3w56u`], + response: `{ + isvalid: true, + address: "tb1q4kgratttzjvkxfmgd95z54qcq7y6hekdm3w56u", + scriptPubKey: "0014ad903ead6b149963276869682a54180789abe6cd", + isscript: false, + iswitness: true, + witness_version: 0, + witness_program: "ad903ead6b149963276869682a54180789abe6cd" +}` + }, + codeSampleSignet: { + curl: [`tb1pu8ysre22dcl6qy5m5w7mjwutw73w4u24slcdh4myq06uhr6q29dqwc3ckt`], + response: `{ + isvalid: true, + address: "tb1pu8ysre22dcl6qy5m5w7mjwutw73w4u24slcdh4myq06uhr6q29dqwc3ckt", + scriptPubKey: "5120e1c901e54a6e3fa0129ba3bdb93b8b77a2eaf15587f0dbd76403f5cb8f40515a", + isscript: true, + iswitness: true, + witness_version: 1, + witness_program: "e1c901e54a6e3fa0129ba3bdb93b8b77a2eaf15587f0dbd76403f5cb8f40515a" +}` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, { type: "category", category: "assets", @@ -2109,6 +2280,61 @@ export const restApiDocsData = [ } } }, + { + type: "endpoint", + category: "blocks", + httpRequestMethod: "GET", + fragment: "get-block-timestamp", + title: "GET Block Timestamp", + description: { + default: "Returns the height and the hash of the block closest to the given :timestamp." + }, + urlString: "/v1/mining/blocks/timestamp/:timestamp", + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/mining/blocks/timestamp/%{1}`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: ['1672531200'], + response: `{ + height: 769786, + hash: "000000000000000000017f6405c2382de84944eb21be9cec0379a735813f137b", + timestamp: "2022-12-31T23:30:31.000Z" +}` + }, + codeSampleTestnet: { + esModule: [], + commonJS: [], + curl: ['1672531200'], + response: `{ + height: 2413838, + hash: "00000000000000082888e2353ea4baaea04d2e0e88f2ee054ad2bbcc1d6a5469", + timestamp: "2022-12-31T23:57:26.000Z" +}` + }, + codeSampleSignet: { + esModule: [], + commonJS: [], + curl: ['1672531200'], + response: `{ + height: 123713, + hash: "0000010c6df8ffe1684ab9d7cfac69836a4538c057fab4571b809120fe486c96", + timestamp: "2022-12-31T23:55:56.000Z" +}` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, { type: "endpoint", category: "blocks", @@ -2922,7 +3148,7 @@ export const restApiDocsData = [ fragment: "get-blocks-bulk", title: "GET Blocks (Bulk)", description: { - default: "

    Returns details on the range of blocks between :minHeight and :maxHeight, inclusive, up to 10 blocks. If :maxHeight is not specified, it defaults to the current tip.

    To return data for more than 10 blocks, consider becoming an enterprise sponsor.

    " + default: "

    Returns details on the range of blocks between :minHeight and :maxHeight, inclusive, up to 10 blocks. If :maxHeight is not specified, it defaults to the current tip.

    To return data for more than 10 blocks, consider becoming an enterprise sponsor.

    " }, urlString: "/v1/blocks-bulk/:minHeight[/:maxHeight]", showConditions: bitcoinNetworks, @@ -4042,6 +4268,101 @@ export const restApiDocsData = [ } } }, + { + type: "endpoint", + category: "mining", + httpRequestMethod: "GET", + fragment: "get-difficulty-adjustments", + title: "GET Difficulty Adjustments", + description: { + default: "

    Returns the record of difficulty adjustments over the specified trailing :interval:

    • Block timestamp
    • Block height
    • Difficulty
    • Difficulty change

    If no time interval is specified, all available data is returned." + }, + urlString: "/v1/mining/difficulty-adjustments/[:interval]", + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/mining/difficulty-adjustments/1m`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + response: `[ + [ + 1703311464, + 822528, + 72006146478567.1, + 1.06983 + ], + [ + 1702180644, + 820512, + 67305906902031.39, + 0.990408 + ], + [ + 1700957763, + 818496, + 67957790298897.88, + 1.0507 + ] +]` + }, + codeSampleTestnet: { + esModule: [], + commonJS: [], + curl: [], + response: `[ + [ + 1703429523, + 2544008, + 105074715.9955905, + 105075000 + ], + [ + 1703426009, + 2544005, + 1, + 0 + ], + [ + 1703422944, + 2544000, + 105074715.9955905, + 105075000 + ], + ... +]` + }, + codeSampleSignet: { + esModule: [], + commonJS: [], + curl: [], + response: `[ + [ + 1702402252, + 173376, + 0.002967416960321784, + 1.01893 + ], + [ + 1701214807, + 171360, + 0.002912289751655253, + 0.9652 + ] +]` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, { type: "endpoint", category: "mining", @@ -4559,6 +4880,407 @@ export const restApiDocsData = [ }, ... ] +}` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, + { + type: "endpoint", + category: "mining", + httpRequestMethod: "GET", + fragment: "get-block-predictions", + title: "GET Block Predictions", + description: { + default: "

    Returns average block health in the specified :timePeriod, ordered oldest to newest. :timePeriod can be any of the following: " + miningTimeIntervals + ".

    For 24h and 3d time periods, every block is included and figures are exact (not averages). For the 1w time period, figures may be averages depending on how fast blocks were found around a particular timestamp. For other time periods, figures are averages.

    " + }, + urlString: ["/v1/mining/blocks/predictions/:timePeriod"], + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/mining/blocks/predictions/%{1}`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [`3y`], + response: `[ + [ + 1687247274, + 777625, + 100 + ], + [ + 1687066238, + 788621, + 99.85 + ], + [ + 1687263518, + 795182, + 99.46 + ], + [ + 1687312271, + 795260, + 100 + ], + ... +]` + }, + codeSampleTestnet: { + esModule: [], + commonJS: [], + curl: [`3y`], + response: `[ + [ + 1687246773, + 2429248, + 100 + ], + [ + 1687285500, + 2438380, + 100 + ], + [ + 1687342820, + 2438467, + 100 + ], + [ + 1687372143, + 2438522, + 100 + ], + ... +]` + }, + codeSampleSignet: { + esModule: [], + commonJS: [], + curl: [`3y`], + response: `[ + [ + 1687246696, + 129639, + 0 + ], + [ + 1687303289, + 148191, + 0 + ], + [ + 1687315093, + 148218, + 0 + ], + [ + 1687368211, + 148312, + 0 + ], + ... +]` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, + { + type: "endpoint", + category: "mining", + httpRequestMethod: "GET", + fragment: "get-block-audit-score", + title: "GET Block Audit Score", + description: { + default: "Returns the block audit score for the specified :blockHash. Available fields: hash, matchRate, expectedFees, and expectedWeight." + }, + urlString: ["/v1/mining/blocks/audit/score/:blockHash"], + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/mining/blocks/audit/score/%{1}`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [`000000000000000000032535698c5b0c48283b792cf86c1c6e36ff84464de785`], + response: `{ + hash: "000000000000000000032535698c5b0c48283b792cf86c1c6e36ff84464de785", + matchRate: 99.66, + expectedFees: 12090955, + expectedWeight: 3991988 +}` + }, + codeSampleTestnet: { + esModule: [], + commonJS: [], + curl: [`000000000000025a66f30a181e438b9f65ef33cec3014b7a4ff4c7578289cd6e`], + response: `{ + hash: "000000000000025a66f30a181e438b9f65ef33cec3014b7a4ff4c7578289cd6e", + matchRate: 100, + expectedFees: 579169, + expectedWeight: 12997 +}` + }, + codeSampleSignet: { + esModule: [], + commonJS: [], + curl: [`000000c1491d7d4229d4bf07e0dcaa7e396767b45be388e1174c7439a9490121`], + response: `{ + hash: "000000c1491d7d4229d4bf07e0dcaa7e396767b45be388e1174c7439a9490121", + matchRate: 100, + expectedFees: 80520, + expectedWeight: 16487 +}` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, + { + type: "endpoint", + category: "mining", + httpRequestMethod: "GET", + fragment: "get-blocks-audit-scores", + title: "GET Blocks Audit Scores", + description: { + default: "Returns blocks audit score for the past 16 blocks. If :startHeight is specified, the past 15 blocks before (and including) :startHeight are returned. Available fields: hash, matchRate, expectedFees, and expectedWeight." + }, + urlString: ["/v1/mining/blocks/audit/scores/:startHeight"], + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/mining/blocks/audit/scores/%{1}`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [`820000`], + response: `[ + { + hash: "000000000000000000034cd3689507da0386d3d1790dd56f2e6945e650e02c74", + matchRate: 100, + expectedFees: 225828975, + expectedWeight: 3991756 + }, + { + hash: "00000000000000000000b3ad97907e99c54e6b9145a8f77842e59d9c0c8377cf", + matchRate: 100, + expectedFees: 295107022, + expectedWeight: 3991752 + }, + ... +]` + }, + codeSampleTestnet: { + esModule: [], + commonJS: [], + curl: [`2566570`], + response: `[ + { + hash: "00000000000002e7e96e7b5ee04a5fbb3ef9575a9f4a99effb32a8a89d9d2f19", + matchRate: 100, + expectedFees: 964677, + expectedWeight: 24959 + }, + { + hash: "00000000000003bd3962806d0e06d9982eb2e06aeba912687b2bac3668db32aa", + matchRate: 100, + expectedFees: 631200, + expectedWeight: 15516 + }, + ... +]` + }, + codeSampleSignet: { + esModule: [], + commonJS: [], + curl: [`175504`], + response: `[ + { + hash: "00000012d54289925efc151f2e111e0775e80c3b6bb4b0dcd3ff01dec4bbc5d0", + matchRate: 100, + expectedFees: 4767, + expectedWeight: 2524 + }, + { + hash: "00000031e269cf0b567260b01ae11453175f4598fdb4f1908c5e2f4265b9d93a", + matchRate: 100, + expectedFees: 9090, + expectedWeight: 1851 + }, + ... +]` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, + { + type: "endpoint", + category: "mining", + httpRequestMethod: "GET", + fragment: "get-block-audit-summary", + title: "GET Block Audit Summary", + description: { + default: "Returns the block audit summary for the specified :blockHash. Available fields: height, id, timestamp, template, missingTxs, addedTxs, freshTxs, sigopTxs, fullrbfTxs, acceleratedTxs, matchRate, expectedFees, and expectedWeight." + }, + urlString: ["/v1/block/:blockHash/audit-summary"], + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/block/%{1}/audit-summary`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [`00000000000000000000f218ceda7a5d9c289040b9c3f05ef9f7c2f4930e0123`], + response: `{ + height: 822418, + id: "00000000000000000000f218ceda7a5d9c289040b9c3f05ef9f7c2f4930e0123", + timestamp: 1703262962, + template: [ + { + txid: "1de119e4fe0fb92378de74a59fec337c39d505bbc0d04d20d151cc3fb7a91bf0", + fee: 92000, + vsize: 140.25, + value: 354245800, + rate: 655.9714795008913, + flags: 1099511631881 + }, + ... + ], + missingTxs: [], + addedTxs: [ + "3036565d1af6c5b14876a255cdf06214aa350e62154d1ce8619c8e933d0526f8", + "aaa9d8e8f1de712574182a618b4d608f96f39bfc55e296d2e5904561cdef2e77", + ... + ], + freshTxs: [ + "8ede292d8f0319cbe79fff9fd47564cd7f78fad74d7c506d2b157399ff41d904" + ], + sigopTxs: [], + fullrbfTxs: [ + "271e7792910a4ea134c02c03c9d7477b32a8531a5dd92fbc4dbf3ca70614fcce", + "634a5b2de393f0f5b4eeb335bee75c1779b1f2308a07e86cafb95894aa4734d0", + ... + ], + acceleratedTxs: [], + matchRate: 100, + expectedFees: 169464627, + expectedWeight: 3991702 +}` + }, + codeSampleTestnet: { + esModule: [], + commonJS: [], + curl: [`000000000000007cfba94e051326b3546c968a188a7e12e340a78cefc586bfe3`], + response: `{ + height: 2566708, + id: "000000000000007cfba94e051326b3546c968a188a7e12e340a78cefc586bfe3", + timestamp: 1703684826, + template: [ + { + txid: "6556caa3c6bff537f04837a6f7182dd7a253f31a46de4f21dec9584720156d35", + fee: 109707, + vsize: 264.75, + value: 456855, + rate: 414.37960339943345, + flags: 9895621445642 + }, + { + txid: "53b7743b8cfa0108dbcdc7c2f5e661b9d8f56216845a439449d7f9dfc466b147", + fee: 74640, + vsize: 215.5, + value: 19063915, + rate: 348.5338491295938, + flags: 1099528491017 + }, + ... + ], + missingTxs: [ + "8f2eae756119e43054ce1014a06e81d612113794d8b519e6ff393d7e0023396a", + "012b44b0fc0fddc549a056c85850f03a83446c843504c588cd5829873b30f5a9", + ... + ], + addedTxs: [], + freshTxs: [ + "af36a8b88f6c19f997614dfc8a41395190eaf496a49e8db393dacb770999abd5", + "fdfa272c8fe069573b964ddad605d748d8c737e94dfcd09bddaae0ee0a2445df", + ... + ], + sigopTxs: [], + fullrbfTxs: [], + acceleratedTxs: [], + matchRate: 86.96, + expectedFees: 1541639, + expectedWeight: 26425 +}` + }, + codeSampleSignet: { + esModule: [], + commonJS: [], + curl: [`0000008acf5177d07f1d648f4d54f26095936a5d29a0a6145dd75a0415e63c0f`], + response: `{ + height: 175519, + id: "0000008acf5177d07f1d648f4d54f26095936a5d29a0a6145dd75a0415e63c0f", + timestamp: 1703682844, + template: [ + { + txid: "f95b38742c483b81dc4ff49a803bae7625f1596ec5756c944d7586dfe8b38250", + fee: 3766, + vsize: 172.25, + value: 115117171776, + rate: 21.86357039187228, + flags: 1099528425481 + }, + { + txid: "8665c4d05732c930c2037bc0220e4ab9b1b64ce3302363ff7d118827c7347b52", + fee: 3766, + vsize: 172.25, + value: 115116509429, + rate: 21.86357039187228, + flags: 1099528425481 + }, + ... + ], + missingTxs: [], + addedTxs: [], + freshTxs: [], + sigopTxs: [], + fullrbfTxs: [], + acceleratedTxs: [], + matchRate: 100, + expectedFees: 10494, + expectedWeight: 6582 }` }, codeSampleLiquid: emptyCodeSample, @@ -5127,6 +5849,267 @@ export const restApiDocsData = [ } } }, + { + type: "endpoint", + category: "mempool", + httpRequestMethod: "GET", + fragment: "get-mempool-rbf", + title: "GET Mempool RBF Transactions", + description: { + default: "Returns the list of mempool transactions that are part of a RBF chain." + }, + urlString: "/v1/replacements", + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/replacements`, + commonJS: ``, + esModule: ``, + }, + codeSampleMainnet: { + curl: [], + response: `[ + { + tx: { + txid: "1ca4b22006e57b1b13f5cc89a41cf7c9e99fe225aabf407251e4fe0268f22d93", + fee: 14983, + vsize: 141.5, + value: 343934, + rate: 105.886925795053, + rbf: true, + fullRbf: false + }, + time: 1703331467, + fullRbf: false, + replaces: [ + { + tx: { + txid: "9f8e30674af641bb153a35254d539468e1d847b16bbdc13ce23b5a970b0b11cf", + fee: 13664, + vsize: 141.25, + value: 345253, + rate: 96.7362831858407, + rbf: true + }, + time: 1703331398, + interval: 69, + fullRbf: false, + replaces: [] + } + ] + }, + ... +]` + }, + codeSampleTestnet: { + curl: [], + response: `[ + { + tx: { + txid: "7766e3f008011b776905f96fcad9d4a7b75d1b368d1e77db2901254f1fa8357d", + fee: 9101, + vsize: 317, + value: 147706698, + rate: 28.709779179810724, + rbf: true, + fullRbf: false + }, + time: 1703331325, + fullRbf: false, + replaces: [ + { + tx: { + txid: "43055f6e5750c6aa0c2214e59e99f367398d96bde935e7666c3e648d249a4e40", + fee: 7000, + vsize: 317, + value: 147708799, + rate: 22.082018927444796, + rbf: true + }, + time: 1703331154, + interval: 171, + fullRbf: false, + replaces: [] + } + ] + }, + ... +]` + }, + codeSampleSignet: { + curl: [], + response: `[ + { + tx: { + txid: "13985a5717a1ea54ce720cd6b70421b1667061be491a6799acf6dea01c551248", + fee: 5040, + vsize: 215.5, + value: 762745, + rate: 23.387470997679813, + rbf: true, + fullRbf: false, + mined: true + }, + time: 1703316271, + fullRbf: false, + replaces: [ + { + tx: { + txid: "eac5ec8487414c955f4a5d3b2e516c351aec5299f1335f9019a00907962386ce", + fee: 4560, + vsize: 215.25, + value: 763225, + rate: 21.18466898954704, + rbf: true + }, + time: 1703316270, + interval: 1, + fullRbf: false, + replaces: [] + } + ], + mined: true + } +]` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, + { + type: "endpoint", + category: "mempool", + httpRequestMethod: "GET", + fragment: "get-mempool-fullrbf", + title: "GET Mempool Full RBF Transactions", + description: { + default: "Returns the list of mempool transactions that are part of a Full-RBF chain." + }, + urlString: "/v1/fullrbf/replacements", + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/fullrbf/replacements`, + commonJS: ``, + esModule: ``, + }, + codeSampleMainnet: { + curl: [], + response: `[ + { + tx: { + txid: "25e2bfaf0e0821e5cb71f11e460b2f71e1d5a3755015de42544afa5fbad6d443", + fee: 24436, + vsize: 297.75, + value: 273418, + rate: 82.0688497061293, + rbf: false, + fullRbf: true + }, + time: 1703409882, + fullRbf: true, + replaces: [ + { + tx: { + txid: "07d501e8ad4a25f07f3ced0a6102741720f710765e6fdb2eb966ba0df657997a", + fee: 24138, + vsize: 297.75, + value: 273716, + rate: 81.06801007556675, + rbf: false + }, + time: 1703409853, + interval: 29, + fullRbf: true, + replaces: [] + } + ] + }, + ... +]` + }, + codeSampleTestnet: { + curl: [], + response: `[ + { + tx: { + txid: "25e2bfaf0e0821e5cb71f11e460b2f71e1d5a3755015de42544afa5fbad6d443", + fee: 24436, + vsize: 297.75, + value: 273418, + rate: 82.0688497061293, + rbf: false, + fullRbf: true + }, + time: 1703409882, + fullRbf: true, + replaces: [ + { + tx: { + txid: "07d501e8ad4a25f07f3ced0a6102741720f710765e6fdb2eb966ba0df657997a", + fee: 24138, + vsize: 297.75, + value: 273716, + rate: 81.06801007556675, + rbf: false + }, + time: 1703409853, + interval: 29, + fullRbf: true, + replaces: [] + } + ] + }, + ... +]` + }, + codeSampleSignet: { + curl: [], + response: `[ + { + tx: { + txid: "25e2bfaf0e0821e5cb71f11e460b2f71e1d5a3755015de42544afa5fbad6d443", + fee: 24436, + vsize: 297.75, + value: 273418, + rate: 82.0688497061293, + rbf: false, + fullRbf: true + }, + time: 1703409882, + fullRbf: true, + replaces: [ + { + tx: { + txid: "07d501e8ad4a25f07f3ced0a6102741720f710765e6fdb2eb966ba0df657997a", + fee: 24138, + vsize: 297.75, + value: 273716, + rate: 81.06801007556675, + rbf: false + }, + time: 1703409853, + interval: 29, + fullRbf: true, + replaces: [] + } + ] + }, + ... +]` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, { type: "category", category: "transactions", @@ -5143,7 +6126,7 @@ export const restApiDocsData = [ description: { default: "Returns the ancestors and the best descendant fees for a transaction." }, - urlString: "/v1/fees/cpfp", + urlString: "/v1/cpfp", showConditions: bitcoinNetworks.concat(liquidNetworks), showJsExamples: showJsExamplesDefault, codeExample: { @@ -6000,6 +6983,148 @@ export const restApiDocsData = [ } } }, + { + type: "endpoint", + category: "transactions", + httpRequestMethod: "GET", + fragment: "get-transaction-rbf-history", + title: "GET Transaction RBF History", + description: { + default: "Returns the RBF tree history of a transaction." + }, + urlString: "v1/tx/:txId/rbf", + showConditions: bitcoinNetworks, + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/tx/%{1}/rbf`, + commonJS: ``, + esModule: ``, + }, + codeSampleMainnet: { + curl: [`2e95ff9094df9f3650e3f2abc189250760162be89a88f9f2f23301c7cb14b8b4`], + response: `{ + replacements: { + tx: { + txid: "2e95ff9094df9f3650e3f2abc189250760162be89a88f9f2f23301c7cb14b8b4", + fee: 1668, + vsize: 276.75, + value: 14849, + rate: 4.824207492795389, + rbf: false, + fullRbf: true + }, + time: 1703240261, + fullRbf: true, + replaces: [ + { + tx: { + txid: "3f4670463daadffed07d7a1060071b07f7e81a2566eca21d78bb513cbf21c82a", + fee: 420, + vsize: 208.25, + value: 4856, + rate: 2.0168067226890756, + rbf: false + }, + time: 1702870898, + interval: 369363, + fullRbf: true, + replaces: [] + } + ... + ] + }, + replaces: [ + "3f4670463daadffed07d7a1060071b07f7e81a2566eca21d78bb513cbf21c82a", + "92f9b4f719d0ffc9035d3a9767d80c940cecbc656df2243bafd33f52b583ee92" + ] +}` + }, + codeSampleTestnet: { + curl: [`5faaa30530bee55de8cc896bdf48f803c2274a94bffc2842386bec2a8bf7a813`], + response: `{ + replacements: { + tx: { + txid: "5faaa30530bee55de8cc896bdf48f803c2274a94bffc2842386bec2a8bf7a813", + fee: 9101, + vsize: 318, + value: 148022607, + rate: 28.61949685534591, + rbf: true, + fullRbf: false, + mined: true + }, + time: 1703322610, + fullRbf: false, + replaces: [ + { + tx: { + txid: "06e69641fa889fe9148669ac2904929004e7140087bedaec8c8e4e05aabded52", + fee: 7000, + vsize: 318, + value: 148024708, + rate: 22.0125786163522, + rbf: true + }, + time: 1703322602, + interval: 8, + fullRbf: false, + replaces: [] + } + ], + mined: true + }, + replaces: [ + "06e69641fa889fe9148669ac2904929004e7140087bedaec8c8e4e05aabded52" + ] +}` + }, + codeSampleSignet: { + curl: [`13985a5717a1ea54ce720cd6b70421b1667061be491a6799acf6dea01c551248`], + response: `{ + replacements: { + tx: { + txid: "13985a5717a1ea54ce720cd6b70421b1667061be491a6799acf6dea01c551248", + fee: 5040, + vsize: 215.5, + value: 762745, + rate: 23.387470997679813, + rbf: true, + fullRbf: false, + mined: true + }, + time: 1703316272, + fullRbf: false, + replaces: [ + { + tx: { + txid: "eac5ec8487414c955f4a5d3b2e516c351aec5299f1335f9019a00907962386ce", + fee: 4560, + vsize: 215.25, + value: 763225, + rate: 21.18466898954704, + rbf: true + }, + time: 1703316270, + interval: 2, + fullRbf: false, + replaces: [] + } + ], + mined: true + }, + replaces: [ + "eac5ec8487414c955f4a5d3b2e516c351aec5299f1335f9019a00907962386ce" + ] +}` + }, + codeSampleLiquid: emptyCodeSample, + codeSampleLiquidTestnet: emptyCodeSample, + codeSampleBisq: emptyCodeSample, + } + } + }, { type: "endpoint", category: "transactions", @@ -6098,6 +7223,48 @@ export const restApiDocsData = [ } } }, + { + type: "endpoint", + category: "transactions", + httpRequestMethod: "GET", + fragment: "get-transaction-times", + title: "GET Transaction Times", + description: { + default: "Returns the timestamps when a list of unconfirmed transactions was initially observed in the mempool. If a transaction is not found in the mempool or has been mined, the timestamp will be 0." + }, + urlString: "/v1/transaction-times", + showConditions: bitcoinNetworks.concat(liquidNetworks), + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/transaction-times?txId[]=%{1}&txId[]=%{2}`, + commonJS: ``, + esModule: ``, + }, + codeSampleMainnet: { + curl: ['51545ef0ec7f09196e60693b59369a134870985c8a90e5d42655b191de06285e', '6086089bd1c56a9c42a39d470cdfa7c12d4b52bf209608b390dfc4943f2d3851'], + response: `[1703082129,1702325558]` + }, + codeSampleTestnet: { + curl: ['25e7a95ebf10ed192ee91741653d8d970ac88f8e0cd6fb14cc6c7145116d3964', '1e158327e52acae35de94962e60e53fc70f6b175b0cfc3e2058bed4b895203b4'], + response: `[1703267563,1703267322]` + }, + codeSampleSignet: { + curl: ['8af0c5199acd89621244f2f61107fe5a9c7c7aad54928e8400651d03ca949aeb', '08f840f7b0c33c5b0fdadf1666e8a8c206836993d95fc1eeeef39b5ef9de03d0'], + response: `[1703267652,1703267696]` + }, + codeSampleLiquid: { + curl: ['6091498f06a3054f82a0c3e5be0a23030185c658dc3568684b0bccc4e759be11', '631212a073aa4ca392e3aeb469d1366ec2ee288988b106e4a6fc8dae8c4d7a9a'], + response: `[1703267652,1703267696]`, + }, + codeSampleLiquidTestnet: { + curl: ['fa8d43e47b2c4bbee12fd8bc1c7440028be2da6ac0f1df6ac77c983938c503fb', '26b12cd450f8fa8b6a527578db218bf212a60b2d5eb65c168f8eb3be6f5fd991'], + response: `[1703268185,1703268209]`, + }, + } + } + }, { type: "endpoint", category: "transactions", @@ -8708,7 +9875,400 @@ export const restApiDocsData = [ codeSampleBisq: emptyCodeSample, } } + }, + { + type: "category", + category: "accelerator", + fragment: "accelerator", + title: "Accelerator", + showConditions: [""], + options: { officialOnly: true }, + }, + { + options: { officialOnly: true }, + type: "endpoint", + category: "accelerator", + httpRequestMethod: "GET", + fragment: "accelerator-deposit-history", + title: "GET Deposit History", + description: { + default: "

    Returns a list of deposits the user has made as prepayment for the accelerator service.

    " + }, + urlString: "/v1/services/accelerator/deposit-history", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/services/accelerator/deposit-history`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + headers: "api_key: stacksats", + response: `[ + { + "type": "Bitcoin", + "invoiceId": "CCunucVyNw7jUiUz64mmHz", + "amount": 10311031, + "status": "pending", + "date": 1706372653000, + "link": "/payment/bitcoin/CCunucVyNw7jUiUz64mmHz" + }, + { + "type": "Bitcoin", + "invoiceId": "SG1U27R9PdWi3gH3jB9tm9", + "amount": 21000000, + "status": "paid", + "date": 1706372582000, + "link": null + }, + ... +]`, + }, + } + } + }, + { + options: { officialOnly: true }, + type: "endpoint", + category: "accelerator", + httpRequestMethod: "GET", + fragment: "accelerator-balance", + title: "GET Available Balance", + description: { + default: "

    Returns the user's currently available balance, currently locked funds, and total fees paid so far.

    " + }, + urlString: "/v1/services/accelerator/balance", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/services/accelerator/balance`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + headers: "api_key: stacksats", + response: `{ + "balance": 99900000, + "hold": 101829, + "feesPaid": 133721 +}`, + }, + } + } + }, + { + options: { officialOnly: true }, + type: "endpoint", + category: "accelerator", + httpRequestMethod: "POST", + fragment: "accelerator-estimate", + title: "POST Calculate Estimated Costs", + description: { + default: "

    Returns estimated costs to accelerate a transaction.

    " + }, + urlString: "/v1/services/accelerator/estimate", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `%{1}" "[[hostname]][[baseNetworkUrl]]/api/v1/services/accelerator/estimate`, //custom interpolation technique handled in replaceCurlPlaceholder() + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: ["txInput=ee13ebb99632377c15c94980357f674d285ac413452050031ea6dcd3e9b2dc29"], + headers: "api_key: stacksats", + response: `{ + "txSummary": { + "txid": "ee13ebb99632377c15c94980357f674d285ac413452050031ea6dcd3e9b2dc29", + "effectiveVsize": 154, + "effectiveFee": 154, + "ancestorCount": 1 + }, + "cost": 3850, + "targetFeeRate": 26, + "nextBlockFee": 4004, + "userBalance": 99900000, + "mempoolBaseFee": 40000, + "vsizeFee": 50000, + "hasAccess": true +}`, + }, + } + } + }, + { + options: { officialOnly: true }, + type: "endpoint", + category: "accelerator", + httpRequestMethod: "POST", + fragment: "accelerator-accelerate", + title: "POST Accelerate A Transaction", + description: { + default: "

    Sends a request to accelerate a transaction.

    " + }, + urlString: "/v1/services/accelerator/accelerate", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `%{1}" "[[hostname]][[baseNetworkUrl]]/api/v1/services/accelerator/accelerate`, //custom interpolation technique handled in replaceCurlPlaceholder() + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: ["txInput=ee13ebb99632377c15c94980357f674d285ac413452050031ea6dcd3e9b2dc29&userBid=21000000"], + headers: "api_key: stacksats", + response: `HTTP/1.1 200 OK`, + }, + } + } + }, + { + options: { officialOnly: true }, + type: "endpoint", + category: "accelerator", + httpRequestMethod: "GET", + fragment: "accelerator-history", + title: "GET Private Acceleration History", + description: { + default: "

    Returns the user's past acceleration requests.

    Pass one of the following for :status: all, requested, accelerating, mined, completed, failed. Pass true in :details to get a detailed history of the acceleration request.

    " + }, + urlString: "/v1/services/accelerator/history?status=:status&details=:details", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/services/accelerator/history?status=all&details=true`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + headers: "api_key: stacksats", + response: `[ + { + "id": 89, + "user_id": 1, + "txid": "ae2639469ec000ed1d14e2550cbb01794e1cd288a00cdc7cce18398ba3cc2ffe", + "status": "failed" + "fee_paid": 0, + "added": 1706378712, + "last_updated": 1706378712, + "confirmations": 4, + "base_fee": 0, + "vsize_fee": 0, + "max_bid": 7000, + "effective_vsize": 135, + "effective_fee": 3128, + "history": [ + { + "event": "user-requested-acceleration", + "timestamp": 1706378712 + }, + { + "event": "accepted_test-api-key", + "timestamp": 1706378712 + }, + { + "event": "failed-at-block-827672", + "timestamp": 1706380261 + } + ] + }, + { + "id": 88, + "user_id": 1, + "txid": "c5840e89173331760e959a190b24e2a289121277ed7f8a095fe289b37cee9fde", + "status": "completed" + "fee_paid": 140019, + "added": 1706378704, + "last_updated": 1706380231, + "confirmations": 6, + "base_fee": 40000, + "vsize_fee": 100000, + "max_bid": 14000, + "effective_vsize": 135, + "effective_fee": 3152, + "history": [ + { + "event": "user-requested-acceleration", + "timestamp": 1706378704 + }, + { + "event": "accepted_test-api-key", + "timestamp": 1706378704 + }, + { + "event": "complete-at-block-827670", + "timestamp": 1706380231 + } + ] + }, + { + "id": 87, + "user_id": 1, + "txid": "178b5b9b310f0d667d7ea563a2cdcc17bc8cd15261b58b1653860a724ca83458", + "status": "completed" + "fee_paid": 90062, + "added": 1706378684, + "last_updated": 1706380231, + "confirmations": 6, + "base_fee": 40000, + "vsize_fee": 50000, + "max_bid": 14000, + "effective_vsize": 135, + "effective_fee": 3260, + "history": [ + { + "event": "user-requested-acceleration", + "timestamp": 1706378684 + }, + { + "event": "accepted_test-api-key", + "timestamp": 1706378684 + }, + { + "event": "complete-at-block-827670", + "timestamp": 1706380231 + } + ] } +]`, + }, + } + } + }, + { + options: { officialOnly: true }, + type: "endpoint", + category: "accelerator", + httpRequestMethod: "GET", + fragment: "accelerator-pending", + title: "GET Pending Accelerations", + description: { + default: "

    Returns all transactions currently being accelerated.

    " + }, + urlString: "/v1/services/accelerator/accelerations", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/services/accelerator/accelerations`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + headers: '', + response: `[ + { + "txid": "8a183c8ae929a2afb857e7f2acd440aaefdf2797f8f7eab1c5f95ff8602abc81", + "added": 1707558316, + "feeDelta": 3500, + "effectiveVsize": 111, + "effectiveFee": 1671, + "pools": [ + 111 + ] + }, + { + "txid": "6097f295e21bdd8d725bd8d9ad4dd72b05bd795dc648bfef52150a9b2b7f7a45", + "added": 1707560464, + "feeDelta": 60000, + "effectiveVsize": 812, + "effectiveFee": 7790, + "pools": [ + 111 + ] + } +]`, + }, + } + } + }, + { + options: { officialOnly: true }, + type: "endpoint", + category: "accelerator", + httpRequestMethod: "GET", + fragment: "accelerator-public-history", + title: "GET Public Acceleration History", + description: { + default: `

    Returns all past accelerated transactions. + Filters can be applied:

      +
    • status: all, requested, accelerating, mined, completed, failed
    • +
    • timeframe: 24h, 3d, 1w, 1m, 3m, 6m, 1y, 2y, 3y, all
    • +
    • poolUniqueId: any id from https://github.com/mempool/mining-pools/blob/master/pools-v2.json +
    • blockHash: a block hash +
    • blockHeight: a block height +
    • page: the requested page number if using pagination +
    • pageLength: the page lenght if using pagination +

    ` + }, + urlString: "/v1/services/accelerator/accelerations/history", + showConditions: [""], + showJsExamples: showJsExamplesDefaultFalse, + codeExample: { + default: { + codeTemplate: { + curl: `/api/v1/services/accelerator/accelerations/history?blockHash=00000000000000000000482f0746d62141694b9210a813b97eb8445780a32003`, + commonJS: ``, + esModule: `` + }, + codeSampleMainnet: { + esModule: [], + commonJS: [], + curl: [], + headers: '', + response: `[ + { + "txid": "d7e1796d8eb4a09d4e6c174e36cfd852f1e6e6c9f7df4496339933cd32cbdd1d", + "status": "completed", + "feePaid": 53239, + "added": 1707421053, + "lastUpdated": 1707422952, + "baseFee": 50000, + "vsizeFee": 0, + "effectiveFee": 146, + "effectiveVsize": 141, + "feeDelta": 14000, + "blockHash": "00000000000000000000482f0746d62141694b9210a813b97eb8445780a32003", + "blockHeight": 829559, + "pools": [ + { + "pool_unique_id": 111, + "username": "foundryusa" + } + ] + } +]`, + }, + } + } + }, ]; export const faqData = [ @@ -8911,6 +10471,34 @@ export const faqData = [ fragment: "what-is-block-health", title: "What is block health?", }, + { + type: "endpoint", + category: "advanced", + showConditions: bitcoinNetworks, + fragment: "how-do-mempool-goggles-work", + title: "How do Mempool Goggles work?", + }, + { + type: "endpoint", + category: "advanced", + showConditions: bitcoinNetworks, + fragment: "what-are-sigops", + title: "What are sigops?", + }, + { + type: "endpoint", + category: "advanced", + showConditions: bitcoinNetworks, + fragment: "what-is-adjusted-vsize", + title: "What is adjusted vsize?", + }, + { + type: "endpoint", + category: "advanced", + showConditions: bitcoinNetworks, + fragment: "why-do-the-projected-block-fee-ranges-overlap", + title: "Why do the projected block fee ranges overlap?", + }, { type: "category", category: "self-hosting", diff --git a/frontend/src/app/docs/api-docs/api-docs-nav.component.html b/frontend/src/app/docs/api-docs/api-docs-nav.component.html index 6f4aedb5f..b2b34cb1e 100644 --- a/frontend/src/app/docs/api-docs/api-docs-nav.component.html +++ b/frontend/src/app/docs/api-docs/api-docs-nav.component.html @@ -3,6 +3,6 @@ More Info
    -

    {{ item.title }}

    +

    {{ item.title }}

    {{ item.title }}
    diff --git a/frontend/src/app/docs/api-docs/api-docs.component.html b/frontend/src/app/docs/api-docs/api-docs.component.html index 22fbec709..2a48157d9 100644 --- a/frontend/src/app/docs/api-docs/api-docs.component.html +++ b/frontend/src/app/docs/api-docs/api-docs.component.html @@ -10,9 +10,9 @@
    -
    HeightMinedPoolMined TXs Size
    {{ block.height }} - - - {{ block.extras.pool.name }} - - {{ block.tx_count | number }}
    @@ -150,7 +127,7 @@
    -
    Latest transactions
    +
    Recent Transactions
    @@ -158,14 +135,14 @@ - - + + - + @@ -178,25 +155,83 @@ - -
    TXID{{ currency }} Fee
    ConfidentialConfidential
    - - - - - - - - -
    -
    -
    -
    -
    -
    -
    -
    -
    + +
    + +
    + +
    +
    +
    + +
    +
    + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    + +
    +
    +
    + + +
    +
    +
    +
    +
    +
    + + +

    mempool.space merely provides data about the Bitcoin network. It cannot help you with retrieving funds, wallet issues, etc.

    For any such requests, you need to get in touch with the entity that helped make the transaction (wallet software, exchange company, etc).

    -

    mempool.space merely provides data about the Bitcoin network. It cannot help you with retrieving funds, wallet issues, etc.

    For any such requests, you need to get in touch with the entity that helped make the transaction (wallet software, exchange company, etc).

    - +
    +
    +

    mempool.space merely provides data about the Bitcoin network. It cannot help you with retrieving funds, wallet issues, etc.

    For any such requests, you need to get in touch with the entity that helped make the transaction (wallet software, exchange company, etc).

    @@ -48,57 +48,59 @@

    Below is a reference for the {{ network.val === '' ? 'Bitcoin' : network.val.charAt(0).toUpperCase() + network.val.slice(1) }} REST API service.

    -

    Note that we enforce rate limits. If you exceed these limits, you will get an HTTP 429 error. If you repeatedly exceed the limits, you may be banned from accessing the service altogether. Consider an enterprise sponsorship if you need higher API limits.

    +

    Note that we enforce rate limits. If you exceed these limits, you will get an HTTP 429 error. If you repeatedly exceed the limits, you may be banned from accessing the service altogether. Consider an enterprise sponsorship if you need higher API limits.

    -

    {{ item.title }}

    -
    - {{ item.title }} {{ item.category }} -
    -
    -
    Endpoint
    - - {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }} +
    +

    {{ item.title }}

    +
    + {{ item.title }} {{ item.category }} +
    +
    +
    Endpoint
    + + {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }} + + + + {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }} +

    {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }}

    +
    +
    + + + {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }} +

    {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }}

    +
    +
    +
    {{ item.httpRequestMethod }} {{ item.urlString }}
    +
    +
    +
    Description
    + +
    +
    + + +
    +
    +
    + +
    +
    +
    + + - - - {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }} -

    {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }}

    + + + - - - {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }} -

    {{ item.httpRequestMethod }} {{ baseNetworkUrl }}/api{{ item.urlString }}

    -
    -
    -
    {{ item.httpRequestMethod }} {{ item.urlString }}
    -
    -
    -
    Description
    - -
    -
    - - -
    -
    -
    - -
    + +
    - - - - - - - - - - -
    @@ -131,7 +133,7 @@

    {{electrsPort}}

    SSL

    Enabled

    -

    Electrum RPC interface for Bitcoin Signet is publicly available. Electrum RPC interface for all other networks is available to sponsors only—whitelisting is required.

    +

    Electrum RPC interface for Bitcoin Signet is publicly available. Electrum RPC interface for all other networks is available to sponsors only—whitelisting is required.

    @@ -145,8 +147,16 @@

    A mempool explorer is a tool that enables you to view real-time and historical information about a node's mempool, visualize its transactions, and search and view those transactions.

    The mempool.space website invented the concept of visualizing a Bitcoin node's mempool as projected blocks. These blocks are the inspiration for our half-filled block logo.

    Projected blocks are on the left of the dotted white line, and confirmed blocks are on the right.

    -
    - +
    +
    + +
    + + +
    +
    +
    +
    @@ -279,16 +289,127 @@

    Because of this feature's resource usage and availability requirements, it is only supported on official mempool.space instances.

    + +

    Mempool Goggles are a set of filters that can be applied to the mempool block visualizations to highlight different types of transactions.

    +

    There are currently 25 different Mempool Goggles filters, grouped into six categories:

    +
    +
    Features
    +
    +
    +
    RBF enabled
    +
    The transaction opts-in to BIP-125 replaceability.
    +
    RBF disabled
    +
    The transaction does not opt-in to BIP-125 replaceability.
    +
    Version 1
    +
    The default version for most transactions.
    +
    Version 2
    +
    Required for transactions which use OP_CHECKSEQUENCEVERIFY relative timelocks.
    +
    +
    + +
    Address Types
    +
    +
    +
    P2PK
    +
    Pay-to-public-key. A legacy output format most commonly found in old coinbase transactions.
    +
    Bare multisig
    +
    A legacy form of multisig, most commonly used for data embedding schemes (see also "Fake pubkey").
    +
    P2PKH
    +
    Pay-to-public-key-hash. A legacy address type that locks outputs to a public key.
    +
    P2SH
    +
    Pay-to-script-hash. A legacy address type that locks outputs to a redeem script.
    +
    P2WPKH
    +
    Pay-to-witness-public-key-hash. The SegWit version of P2PKH.
    +
    P2WSH
    +
    Pay-to-witness-script-hash. The SegWit version of P2SH.
    +
    Taproot
    +
    Addresses using the SegWit V1 format added in the Taproot upgrade.
    +
    +
    + +
    Behavior
    +
    +
    +
    Paid for by child
    +
    The transaction's effective fee rate has been increased by a higher rate CPFP child.
    +
    Pays for parent
    +
    The transaction bumps the effective fee rate of a lower rate CPFP ancestor.
    +
    Replacement
    +
    The transaction replaced a prior version via RBF.
    +
    +
    + +
    Data
    +
    + Different methods of embedding arbitrary data in a Bitcoin transaction. +
    +
    OP_RETURN
    +
    Fake pubkey
    +
    Data may be embedded in an invalid public key in a P2PK or Bare multisig output. This is a heuristic filter and can be prone to false positives and false negatives.
    +
    Inscription
    +
    Data is embedded in the witness script of a taproot input.
    +
    +
    + +
    Heuristics
    +
    + These filters match common types of transactions according to subjective criteria. +
    +
    Coinjoin
    +
    A type of collaborative privacy-improving transaction.
    +
    Consolidation
    +
    The transaction condenses many inputs into a few outputs.
    +
    Batch payment
    +
    The transaction sends coins from a few inputs to many outputs.
    +
    +
    + +
    Sighash Flags
    +
    + Different ways of signing inputs to Bitcoin transactions. Note that selecting multiple sighash filters will highlight transactions in which each sighash flag is used, but not necessarily in the same input. +
    +
    sighash_all
    +
    sighash_none
    +
    sighash_single
    +
    sighash_default
    +
    sighash_anyonecanpay
    +
    +
    +
    +
    + + +

    A "sigop" is a way of accounting for the cost of "signature operations" in Bitcoin script, like OP_CHECKSIG, OP_CHECKSIGVERIFY, OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY

    +

    These signature operations incur different costs depending on whether they are single or multi-sig operations, and on where they appear in a Bitcoin transaction.

    +

    By consensus, each Bitcoin block is permitted to include a maximum of 80,000 sigops.

    +
    + + +

    Bitcoin blocks have two independent consensus-enforced resource constraints - a 4MWU weight limit, and the 80,000 sigop limit.

    +

    Most transactions use a more of the weight limit than the sigop limit. However, some transactions use a disproportionate number of sigops compared to their weight.

    +

    To account for this, Bitcoin Core calculates and uses an "adjusted vsize" equal 5 times the number of sigops, or the unadjusted vsize, whichever is larger.

    +

    Then, during block template construction, Bitcoin Core selects transactions in descending order of fee rate measured in satoshis per adjusted vsize

    +

    On mempool.space, effective fee rates for unconfirmed transactions are also measured in terms of satoshis per adjusted vsize, after accounting for CPFP relationships and other dependencies.

    +
    + + +

    The projected mempool blocks represent what we expect the next blocks would look like if they were mined right now, and so each projected block follows all of the same rules and constraints as real mined blocks.

    +

    Those constraints can sometimes cause transactions with lower fee rates to be included "ahead" of transactions with higher rates.

    +

    For example, if one projected block has a very small amount of space left, it might be able to fit one more tiny low fee rate transaction, while larger higher fee rate transactions have to wait for the following block.

    +

    A similar effect can occur when there are a large number of transactions with very many sigops. In that scenario, each projected block can only include up to 80,000 sigops worth of transactions, after which the remaining space can only be filled by potentially much lower fee transactions with zero sigops.

    +

    In extreme cases this can produce several projected blocks in a row with overlapping fee ranges, as a result of each projected block containing both high-feerate high-sigop transactions and lower feerate zero-sigop transactions.

    +
    + The official mempool.space website is operated by The Mempool Open Source Project. See more information on our About page. There are also many unofficial instances of this website operated by individual members of the Bitcoin community. - We support one-click installation on a number of Raspberry Pi full-node distros including Umbrel, RaspiBlitz, MyNode, RoninDojo, and Start9's Embassy. + We support one-click installation on a number of Raspberry Pi full-node distros including Umbrel, RaspiBlitz, MyNode, RoninDojo, and StartOS. -

    You can manually install Mempool on your own server, but this requires advanced sysadmin skills since you will be manually configuring everything. You could also use our Docker images.

    In any case, we only provide support for manual deployments to enterprise sponsors.

    +

    You can manually install Mempool on your own server, but this requires advanced sysadmin skills since you will be manually configuring everything. You could also use our Docker images.

    In any case, we only provide support for manual deployments to enterprise sponsors.

    For casual users, we strongly suggest installing Mempool using one of the 1-click install methods.

    diff --git a/frontend/src/app/docs/api-docs/api-docs.component.scss b/frontend/src/app/docs/api-docs/api-docs.component.scss index 85a037118..046cf9a45 100644 --- a/frontend/src/app/docs/api-docs/api-docs.component.scss +++ b/frontend/src/app/docs/api-docs/api-docs.component.scss @@ -157,7 +157,7 @@ ul.no-bull.block-audit code{ position: fixed; top: 80px; overflow-y: auto; - height: calc(100vh - 50px); + height: calc(100vh - 75px); scrollbar-color: #2d3348 #11131f; scrollbar-width: thin; } @@ -259,13 +259,46 @@ h3 { } .blockchain-wrapper { - position: relative; + display: block; + height: 100%; width: 100%; - overflow: auto; - scrollbar-width: none; + min-height: 220px; + position: relative; + overflow: hidden; + + .position-container { + position: absolute; + left: 50%; + bottom: 150px; + } + + #divider { + width: 2px; + height: 175px; + left: 0; + top: -40px; + position: absolute; + } + + &.time-ltr { + .blocks-wrapper { + transform: scaleX(-1); + } + } } -.blockchain-wrapper::-webkit-scrollbar { - display: none; + +:host-context(.ltr-layout) { + .blockchain-wrapper.time-ltr .blocks-wrapper, + .blockchain-wrapper .blocks-wrapper { + direction: ltr; + } +} + +:host-context(.rtl-layout) { + .blockchain-wrapper.time-ltr .blocks-wrapper, + .blockchain-wrapper .blocks-wrapper { + direction: rtl; + } } #disclaimer { @@ -395,3 +428,44 @@ h3 { margin-bottom: 4rem; } } + +/* styles for nested definition lists */ +dl { + margin: 0; + padding: 0; +} + +dt { + font-weight: bold; + color: #4a68b9; + padding: 5px 0; +} + +dd { + padding: 2px 0; + + & > dl { + padding-left: 1em; + border-left: 2px solid #4a68b9; + margin-left: 1em; + margin-top: 5px; + } + + & > dl > dt { + display: inline; + font-weight: normal; + color: #e83e8c; + font-family: Consolas, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New; + text-transform: uppercase; + + &:before { + content: ""; + display: block; + } + } + + & > dl > dd { + display: inline; + margin-left: 1em; + } +} diff --git a/frontend/src/app/docs/api-docs/api-docs.component.ts b/frontend/src/app/docs/api-docs/api-docs.component.ts index 2cf639fb7..3f5ce75e5 100644 --- a/frontend/src/app/docs/api-docs/api-docs.component.ts +++ b/frontend/src/app/docs/api-docs/api-docs.component.ts @@ -1,6 +1,6 @@ import { Component, OnInit, Input, QueryList, AfterViewInit, ViewChildren } from '@angular/core'; import { Env, StateService } from '../../services/state.service'; -import { Observable, merge, of, Subject } from 'rxjs'; +import { Observable, merge, of, Subject, Subscription } from 'rxjs'; import { tap, takeUntil } from 'rxjs/operators'; import { ActivatedRoute } from "@angular/router"; import { faqData, restApiDocsData, wsApiDocsData } from './api-docs-data'; @@ -31,6 +31,8 @@ export class ApiDocsComponent implements OnInit, AfterViewInit { auditEnabled: boolean; mobileViewport: boolean = false; showMobileEnterpriseUpsell: boolean = true; + timeLtrSubscription: Subscription; + timeLtr: boolean = this.stateService.timeLtr.value; @ViewChildren(FaqTemplateDirective) faqTemplates: QueryList; dict = {}; @@ -105,12 +107,17 @@ export class ApiDocsComponent implements OnInit, AfterViewInit { this.electrsPort = 51302; break; } }); + + this.timeLtrSubscription = this.stateService.timeLtr.subscribe((ltr) => { + this.timeLtr = !!ltr; + }); } ngOnDestroy(): void { this.destroy$.next(true); this.destroy$.complete(); window.removeEventListener('scroll', this.onDocScroll); + this.timeLtrSubscription.unsubscribe(); } onDocScroll() { diff --git a/frontend/src/app/docs/code-template/code-template.component.ts b/frontend/src/app/docs/code-template/code-template.component.ts index 5ef8a64ba..6b91f5a9d 100644 --- a/frontend/src/app/docs/code-template/code-template.component.ts +++ b/frontend/src/app/docs/code-template/code-template.component.ts @@ -311,27 +311,29 @@ yarn add @mempool/liquid.js`; text = text.replace('%{' + indexNumber + '}', textReplace); } + const headersString = code.headers ? ` -H "${code.headers}"` : ``; + if (this.env.BASE_MODULE === 'mempool') { if (this.network === 'main' || this.network === '') { if (this.method === 'POST') { - return `curl -X POST -sSLd "${text}"`; + return `curl${headersString} -X POST -sSLd "${text}"`; } - return `curl -sSL "${this.hostname}${text}"`; + return `curl${headersString} -sSL "${this.hostname}${text}"`; } if (this.method === 'POST') { - return `curl -X POST -sSLd "${text}"`; + return `curl${headersString} -X POST -sSLd "${text}"`; } - return `curl -sSL "${this.hostname}/${this.network}${text}"`; + return `curl${headersString} -sSL "${this.hostname}/${this.network}${text}"`; } else if (this.env.BASE_MODULE === 'liquid') { if (this.method === 'POST') { if (this.network !== 'liquid') { text = text.replace('/api', `/${this.network}/api`); } - return `curl -X POST -sSLd "${text}"`; + return `curl${headersString} -X POST -sSLd "${text}"`; } - return ( this.network === 'liquid' ? `curl -sSL "${this.hostname}${text}"` : `curl -sSL "${this.hostname}/${this.network}${text}"` ); + return ( this.network === 'liquid' ? `curl${headersString} -sSL "${this.hostname}${text}"` : `curl${headersString} -sSL "${this.hostname}/${this.network}${text}"` ); } else { - return `curl -sSL "${this.hostname}${text}"`; + return `curl${headersString} -sSL "${this.hostname}${text}"`; } } diff --git a/frontend/src/app/docs/docs/docs.component.ts b/frontend/src/app/docs/docs/docs.component.ts index 2793fd70d..6d6c3b0c1 100644 --- a/frontend/src/app/docs/docs/docs.component.ts +++ b/frontend/src/app/docs/docs/docs.component.ts @@ -64,10 +64,9 @@ export class DocsComponent implements OnInit { } } else { this.activeTab = 3; - this.seoService.setTitle($localize`:@@meta.title.docs.websocket:Electrum RPC`); + this.seoService.setTitle($localize`:@@meta.title.docs.electrum:Electrum RPC`); this.seoService.setDescription($localize`:@@meta.description.docs.electrumrpc:Documentation for our Electrum RPC interface: get instant, convenient, and reliable access to an Esplora instance.`); } - } ngOnDestroy(): void { diff --git a/frontend/src/app/graphs/echarts.ts b/frontend/src/app/graphs/echarts.ts new file mode 100644 index 000000000..74fec1e71 --- /dev/null +++ b/frontend/src/app/graphs/echarts.ts @@ -0,0 +1,17 @@ +// Import tree-shakeable echarts +import * as echarts from 'echarts/core'; +import { LineChart, LinesChart, BarChart, TreemapChart, PieChart, ScatterChart, GaugeChart } from 'echarts/charts'; +import { TitleComponent, TooltipComponent, GridComponent, LegendComponent, GeoComponent, DataZoomComponent, VisualMapComponent, MarkLineComponent } from 'echarts/components'; +import { SVGRenderer, CanvasRenderer } from 'echarts/renderers'; +// Typescript interfaces +import { EChartsOption, TreemapSeriesOption, LineSeriesOption, PieSeriesOption } from 'echarts'; + + +echarts.use([ + SVGRenderer, CanvasRenderer, + TitleComponent, TooltipComponent, GridComponent, + LegendComponent, GeoComponent, DataZoomComponent, + VisualMapComponent, MarkLineComponent, + LineChart, LinesChart, BarChart, TreemapChart, PieChart, ScatterChart, GaugeChart +]); +export { echarts, EChartsOption, TreemapSeriesOption, LineSeriesOption, PieSeriesOption }; \ No newline at end of file diff --git a/frontend/src/app/graphs/graphs.module.ts b/frontend/src/app/graphs/graphs.module.ts index 87e8a620b..42aebe613 100644 --- a/frontend/src/app/graphs/graphs.module.ts +++ b/frontend/src/app/graphs/graphs.module.ts @@ -3,6 +3,7 @@ import { NgxEchartsModule } from 'ngx-echarts'; import { GraphsRoutingModule } from './graphs.routing.module'; import { SharedModule } from '../shared/shared.module'; +import { AccelerationFeesGraphComponent } from '../components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component'; import { BlockFeesGraphComponent } from '../components/block-fees-graph/block-fees-graph.component'; import { BlockRewardsGraphComponent } from '../components/block-rewards-graph/block-rewards-graph.component'; import { BlockFeeRatesGraphComponent } from '../components/block-fee-rates-graph/block-fee-rates-graph.component'; @@ -11,6 +12,13 @@ import { FeeDistributionGraphComponent } from '../components/fee-distribution-gr import { IncomingTransactionsGraphComponent } from '../components/incoming-transactions-graph/incoming-transactions-graph.component'; import { MempoolGraphComponent } from '../components/mempool-graph/mempool-graph.component'; import { LbtcPegsGraphComponent } from '../components/lbtc-pegs-graph/lbtc-pegs-graph.component'; +import { ReservesSupplyStatsComponent } from '../components/liquid-reserves-audit/reserves-supply-stats/reserves-supply-stats.component'; +import { ReservesRatioStatsComponent } from '../components/liquid-reserves-audit/reserves-ratio-stats/reserves-ratio-stats.component'; +import { ReservesRatioComponent } from '../components/liquid-reserves-audit/reserves-ratio/reserves-ratio.component'; +import { RecentPegsStatsComponent } from '../components/liquid-reserves-audit/recent-pegs-stats/recent-pegs-stats.component'; +import { RecentPegsListComponent } from '../components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component'; +import { FederationAddressesStatsComponent } from '../components/liquid-reserves-audit/federation-addresses-stats/federation-addresses-stats.component'; +import { FederationAddressesListComponent } from '../components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component'; import { GraphsComponent } from '../components/graphs/graphs.component'; import { StatisticsComponent } from '../components/statistics/statistics.component'; import { MempoolBlockComponent } from '../components/mempool-block/mempool-block.component'; @@ -19,6 +27,7 @@ import { PoolComponent } from '../components/pool/pool.component'; import { TelevisionComponent } from '../components/television/television.component'; import { DashboardComponent } from '../dashboard/dashboard.component'; import { MiningDashboardComponent } from '../components/mining-dashboard/mining-dashboard.component'; +import { AcceleratorDashboardComponent } from '../components/acceleration/accelerator-dashboard/accelerator-dashboard.component'; import { HashrateChartComponent } from '../components/hashrate-chart/hashrate-chart.component'; import { HashrateChartPoolsComponent } from '../components/hashrates-chart-pools/hashrate-chart-pools.component'; import { BlockHealthGraphComponent } from '../components/block-health-graph/block-health-graph.component'; @@ -30,12 +39,14 @@ import { CommonModule } from '@angular/common'; MempoolBlockComponent, MiningDashboardComponent, + AcceleratorDashboardComponent, PoolComponent, PoolRankingComponent, TelevisionComponent, StatisticsComponent, GraphsComponent, + AccelerationFeesGraphComponent, BlockFeesGraphComponent, BlockRewardsGraphComponent, BlockFeeRatesGraphComponent, @@ -44,6 +55,13 @@ import { CommonModule } from '@angular/common'; IncomingTransactionsGraphComponent, MempoolGraphComponent, LbtcPegsGraphComponent, + ReservesSupplyStatsComponent, + ReservesRatioStatsComponent, + ReservesRatioComponent, + RecentPegsStatsComponent, + RecentPegsListComponent, + FederationAddressesStatsComponent, + FederationAddressesListComponent, HashrateChartComponent, HashrateChartPoolsComponent, BlockHealthGraphComponent, @@ -53,7 +71,7 @@ import { CommonModule } from '@angular/common'; SharedModule, GraphsRoutingModule, NgxEchartsModule.forRoot({ - echarts: () => import('echarts') + echarts: () => import('./echarts').then(m => m.echarts), }) ], exports: [ diff --git a/frontend/src/app/graphs/graphs.routing.module.ts b/frontend/src/app/graphs/graphs.routing.module.ts index 03800dcfc..d3c7a1bce 100644 --- a/frontend/src/app/graphs/graphs.routing.module.ts +++ b/frontend/src/app/graphs/graphs.routing.module.ts @@ -8,32 +8,21 @@ import { BlockSizesWeightsGraphComponent } from '../components/block-sizes-weigh import { GraphsComponent } from '../components/graphs/graphs.component'; import { HashrateChartComponent } from '../components/hashrate-chart/hashrate-chart.component'; import { HashrateChartPoolsComponent } from '../components/hashrates-chart-pools/hashrate-chart-pools.component'; -import { LiquidMasterPageComponent } from '../components/liquid-master-page/liquid-master-page.component'; -import { MasterPageComponent } from '../components/master-page/master-page.component'; import { MempoolBlockComponent } from '../components/mempool-block/mempool-block.component'; import { MiningDashboardComponent } from '../components/mining-dashboard/mining-dashboard.component'; +import { AcceleratorDashboardComponent } from '../components/acceleration/accelerator-dashboard/accelerator-dashboard.component'; import { PoolRankingComponent } from '../components/pool-ranking/pool-ranking.component'; import { PoolComponent } from '../components/pool/pool.component'; import { StartComponent } from '../components/start/start.component'; import { StatisticsComponent } from '../components/statistics/statistics.component'; import { TelevisionComponent } from '../components/television/television.component'; import { DashboardComponent } from '../dashboard/dashboard.component'; -import { NodesNetworksChartComponent } from '../lightning/nodes-networks-chart/nodes-networks-chart.component'; -import { LightningStatisticsChartComponent } from '../lightning/statistics-chart/lightning-statistics-chart.component'; -import { NodesPerISPChartComponent } from '../lightning/nodes-per-isp-chart/nodes-per-isp-chart.component'; -import { NodesPerCountryChartComponent } from '../lightning/nodes-per-country-chart/nodes-per-country-chart.component'; -import { NodesMap } from '../lightning/nodes-map/nodes-map.component'; -import { NodesChannelsMap } from '../lightning/nodes-channels-map/nodes-channels-map.component'; - -const browserWindow = window || {}; -// @ts-ignore -const browserWindowEnv = browserWindow.__env || {}; -const isLiquid = browserWindowEnv && browserWindowEnv.BASE_MODULE === 'liquid'; +import { AccelerationFeesGraphComponent } from '../components/acceleration/acceleration-fees-graph/acceleration-fees-graph.component'; +import { AccelerationsListComponent } from '../components/acceleration/accelerations-list/accelerations-list.component'; const routes: Routes = [ { path: '', - component: isLiquid ? LiquidMasterPageComponent : MasterPageComponent, children: [ { path: 'mining/pool/:slug', @@ -51,6 +40,22 @@ const routes: Routes = [ }, ] }, + { + path: 'acceleration', + data: { networks: ['bitcoin'] }, + component: StartComponent, + children: [ + { + path: '', + component: AcceleratorDashboardComponent, + } + ] + }, + { + path: 'acceleration/list', + data: { networks: ['bitcoin'] }, + component: AccelerationsListComponent, + }, { path: 'mempool-block/:id', data: { networks: ['bitcoin', 'liquid'] }, @@ -108,34 +113,14 @@ const routes: Routes = [ component: BlockSizesWeightsGraphComponent, }, { - path: 'lightning/nodes-networks', + path: 'acceleration/fees', data: { networks: ['bitcoin'] }, - component: NodesNetworksChartComponent, + component: AccelerationFeesGraphComponent, }, { - path: 'lightning/capacity', - data: { networks: ['bitcoin'] }, - component: LightningStatisticsChartComponent, - }, - { - path: 'lightning/nodes-per-isp', - data: { networks: ['bitcoin'] }, - component: NodesPerISPChartComponent, - }, - { - path: 'lightning/nodes-per-country', - data: { networks: ['bitcoin'] }, - component: NodesPerCountryChartComponent, - }, - { - path: 'lightning/nodes-map', - data: { networks: ['bitcoin'] }, - component: NodesMap, - }, - { - path: 'lightning/nodes-channels-map', - data: { networks: ['bitcoin'] }, - component: NodesChannelsMap, + path: 'lightning', + data: { preload: true, networks: ['bitcoin'] }, + loadChildren: () => import ('./lightning-graphs.module').then(m => m.LightningGraphsModule), }, { path: '', diff --git a/frontend/src/app/graphs/lightning-graphs.module.ts b/frontend/src/app/graphs/lightning-graphs.module.ts new file mode 100644 index 000000000..ac123be33 --- /dev/null +++ b/frontend/src/app/graphs/lightning-graphs.module.ts @@ -0,0 +1,58 @@ +import { NgModule } from '@angular/core'; +import { SharedModule } from '../shared/shared.module'; +import { CommonModule } from '@angular/common'; +import { RouterModule, Routes } from '@angular/router'; +import { NodesNetworksChartComponent } from '../lightning/nodes-networks-chart/nodes-networks-chart.component'; +import { LightningStatisticsChartComponent } from '../lightning/statistics-chart/lightning-statistics-chart.component'; +import { NodesPerISPChartComponent } from '../lightning/nodes-per-isp-chart/nodes-per-isp-chart.component'; +import { NodesPerCountryChartComponent } from '../lightning/nodes-per-country-chart/nodes-per-country-chart.component'; +import { NodesMap } from '../lightning/nodes-map/nodes-map.component'; +import { NodesChannelsMap } from '../lightning/nodes-channels-map/nodes-channels-map.component'; + +const routes: Routes = [ + { + path: 'nodes-networks', + data: { networks: ['bitcoin'] }, + component: NodesNetworksChartComponent, + }, + { + path: 'capacity', + data: { networks: ['bitcoin'] }, + component: LightningStatisticsChartComponent, + }, + { + path: 'nodes-per-isp', + data: { networks: ['bitcoin'] }, + component: NodesPerISPChartComponent, + }, + { + path: 'nodes-per-country', + data: { networks: ['bitcoin'] }, + component: NodesPerCountryChartComponent, + }, + { + path: 'nodes-map', + data: { networks: ['bitcoin'] }, + component: NodesMap, + }, + { + path: 'nodes-channels-map', + data: { networks: ['bitcoin'] }, + component: NodesChannelsMap, + }, +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule], +}) +export class LightningGraphsRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + SharedModule, + LightningGraphsRoutingModule, + ], +}) +export class LightningGraphsModule { } diff --git a/frontend/src/app/interfaces/electrs.interface.ts b/frontend/src/app/interfaces/electrs.interface.ts index 2d604a9de..58a02ad79 100644 --- a/frontend/src/app/interfaces/electrs.interface.ts +++ b/frontend/src/app/interfaces/electrs.interface.ts @@ -26,6 +26,7 @@ export interface Transaction { _outspends?: Outspend[]; _channels?: TransactionChannels; price?: Price; + sigops?: number; } export interface TransactionChannels { diff --git a/frontend/src/app/interfaces/node-api.interface.ts b/frontend/src/app/interfaces/node-api.interface.ts index a9f069b56..e5764e785 100644 --- a/frontend/src/app/interfaces/node-api.interface.ts +++ b/frontend/src/app/interfaces/node-api.interface.ts @@ -2,6 +2,7 @@ import { Block, Transaction } from "./electrs.interface"; export interface OptimizedMempoolStats { added: number; + count: number; vbytes_per_second: number; total_fee: number; mempool_byte_weight: number; @@ -53,6 +54,7 @@ export interface DifficultyAdjustment { previousTime: number; nextRetargetHeight: number; timeAvg: number; + adjustedTimeAvg: number; timeOffset: number; expectedBlocks: number; } @@ -75,6 +77,51 @@ export interface LiquidPegs { date: string; } +export interface CurrentPegs { + amount: string; + lastBlockUpdate: number; + hash: string; +} + +export interface PegsVolume { + volume: string; + number: number; +} + +export interface FederationAddress { + bitcoinaddress: string; + balance: string; +} + +export interface FederationUtxo { + txid: string; + txindex: number; + bitcoinaddress: string; + amount: number; + blocknumber: number; + blocktime: number; + pegtxid: string; + pegindex: number; + pegblocktime: number; +} + +export interface RecentPeg { + txid: string; + txindex: number; + amount: number; + bitcoinaddress: string; + bitcointxid: string; + bitcoinindex: number; + blocktime: number; +} + +export interface AuditStatus { + bitcoinBlocks: number; + bitcoinHeaders: number; + lastBlockAudit: number; + isAuditSynced: boolean; +} + export interface ITranslators { [language: string]: string; } /** @@ -179,6 +226,7 @@ export interface TransactionStripped { value: number; rate?: number; // effective fee rate acc?: boolean; + flags?: number | null; status?: 'found' | 'missing' | 'sigop' | 'fresh' | 'freshcpfp' | 'added' | 'censored' | 'selected' | 'rbf' | 'accelerated'; context?: 'projected' | 'actual'; } @@ -253,6 +301,29 @@ export interface INodesRanking { topByChannels: ITopNodesPerChannels[]; } +export interface INodesStatisticsEntry { + added: string; + avg_base_fee_mtokens: number; + avg_capacity: number; + avg_fee_rate: number; + channel_count: number; + clearnet_nodes: number; + clearnet_tor_nodes: number; + id: number; + med_base_fee_mtokens: number; + med_capacity: number; + med_fee_rate: number; + node_count: number; + tor_nodes: number; + total_capacity: number; + unannounced_nodes: number; +} + +export interface INodesStatistics { + latest: INodesStatisticsEntry; + previous: INodesStatisticsEntry; +} + export interface IOldestNodes { publicKey: string, alias: string, @@ -301,3 +372,32 @@ export interface INode { funding_balance?: number; closing_balance?: number; } + +export interface Acceleration { + txid: string; + status: 'requested' | 'accelerating' | 'mined' | 'completed' | 'failed'; + pools: number[]; + feePaid: number; + added: number; // timestamp + lastUpdated: number; // timestamp + baseFee: number; + vsizeFee: number; + effectiveFee: number; + effectiveVsize: number; + feeDelta: number; + blockHash: string; + blockHeight: number; + + acceleratedFee?: number; + boost?: number; +} + +export interface AccelerationHistoryParams { + status?: string; + timeframe?: string; + poolUniqueId?: number; + blockHash?: string; + blockHeight?: number; + page?: number; + pageLength?: number; +} \ No newline at end of file diff --git a/frontend/src/app/interfaces/websocket.interface.ts b/frontend/src/app/interfaces/websocket.interface.ts index 1d0414de7..d085c22fa 100644 --- a/frontend/src/app/interfaces/websocket.interface.ts +++ b/frontend/src/app/interfaces/websocket.interface.ts @@ -1,3 +1,4 @@ +import { SafeResourceUrl } from '@angular/platform-browser'; import { ILoadingIndicators } from '../services/state.service'; import { Transaction } from './electrs.interface'; import { BlockExtended, DifficultyAdjustment, RbfTree } from './node-api.interface'; @@ -27,6 +28,8 @@ export interface WebsocketResponse { fees?: Recommendedfees; 'track-tx'?: string; 'track-address'?: string; + 'track-addresses'?: string[]; + 'track-scriptpubkeys'?: string[]; 'track-asset'?: string; 'track-mempool-block'?: number; 'track-rbf'?: string; @@ -68,9 +71,15 @@ export interface MempoolBlockWithTransactions extends MempoolBlock { } export interface MempoolBlockDelta { - added: TransactionStripped[], - removed: string[], - changed?: { txid: string, rate: number | undefined, acc: boolean | undefined }[]; + added: TransactionStripped[]; + removed: string[]; + changed: { txid: string, rate: number, flags: number, acc: boolean }[]; +} + +export interface MempoolBlockDeltaCompressed { + added: TransactionCompressed[]; + removed: string[]; + changed: MempoolDeltaChange[]; } export interface MempoolInfo { @@ -90,10 +99,16 @@ export interface TransactionStripped { value: number; acc?: boolean; // is accelerated? rate?: number; // effective fee rate + flags?: number; status?: 'found' | 'missing' | 'sigop' | 'fresh' | 'freshcpfp' | 'added' | 'censored' | 'selected' | 'rbf' | 'accelerated'; context?: 'projected' | 'actual'; } +// [txid, fee, vsize, value, rate, flags, acceleration?] +export type TransactionCompressed = [string, number, number, number, number, number, 1?]; +// [txid, rate, flags, acceleration?] +export type MempoolDeltaChange = [string, number, number, (1|0)]; + export interface IBackendInfo { hostname?: string; gitCommit: string; @@ -106,4 +121,18 @@ export interface Recommendedfees { hourFee: number; minimumFee: number; economyFee: number; +} + +export interface HealthCheckHost { + host: string; + active: boolean; + rtt: number; + latestHeight: number; + socket: boolean; + outOfSync: boolean; + unreachable: boolean; + checked: boolean; + link?: string; + statusPage?: SafeResourceUrl; + flag?: string; } \ No newline at end of file diff --git a/frontend/src/app/lightning/channels-list/channels-list.component.html b/frontend/src/app/lightning/channels-list/channels-list.component.html index b7b18892e..876551dc7 100644 --- a/frontend/src/app/lightning/channels-list/channels-list.component.html +++ b/frontend/src/app/lightning/channels-list/channels-list.component.html @@ -37,7 +37,7 @@ Alias   - Status + Status Fee rate Closing date Capacity diff --git a/frontend/src/app/lightning/channels-statistics/channels-statistics.component.ts b/frontend/src/app/lightning/channels-statistics/channels-statistics.component.ts index 4059e9420..f2b78f53c 100644 --- a/frontend/src/app/lightning/channels-statistics/channels-statistics.component.ts +++ b/frontend/src/app/lightning/channels-statistics/channels-statistics.component.ts @@ -1,5 +1,6 @@ import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; +import { INodesStatistics } from '../../interfaces/node-api.interface'; @Component({ selector: 'app-channels-statistics', @@ -8,7 +9,7 @@ import { Observable } from 'rxjs'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChannelsStatisticsComponent implements OnInit { - @Input() statistics$: Observable; + @Input() statistics$: Observable; mode: string = 'avg'; constructor() { } diff --git a/frontend/src/app/lightning/group/group-preview.component.ts b/frontend/src/app/lightning/group/group-preview.component.ts index fc81eab38..35bcb6e0f 100644 --- a/frontend/src/app/lightning/group/group-preview.component.ts +++ b/frontend/src/app/lightning/group/group-preview.component.ts @@ -57,7 +57,7 @@ export class GroupPreviewComponent implements OnInit { return of(null); } - return this.lightningApiService.getNodGroupNodes$(this.groupId); + return this.lightningApiService.getNodeGroup$(this.groupId); }), map((nodes) => { for (const node of nodes) { diff --git a/frontend/src/app/lightning/group/group.component.html b/frontend/src/app/lightning/group/group.component.html index de85b299e..c1ffe7f6d 100644 --- a/frontend/src/app/lightning/group/group.component.html +++ b/frontend/src/app/lightning/group/group.component.html @@ -14,7 +14,7 @@ - + @@ -70,7 +70,7 @@
    DescriptionDescription
    These are the Lightning nodes operated by The Mempool Open Source Project that provide data for the mempool.space website. Connect to us!
    - + diff --git a/frontend/src/app/lightning/group/group.component.ts b/frontend/src/app/lightning/group/group.component.ts index 0786076ed..4c2cd4dd9 100644 --- a/frontend/src/app/lightning/group/group.component.ts +++ b/frontend/src/app/lightning/group/group.component.ts @@ -41,7 +41,7 @@ export class GroupComponent implements OnInit { this.seoService.setTitle(`Mempool.space Lightning Nodes`); this.seoService.setDescription(`See all Lightning nodes run by mempool.space -- these are the nodes that provide the data on the mempool.space Lightning dashboard.`); - this.nodes$ = this.lightningApiService.getNodGroupNodes$('mempool.space') + this.nodes$ = this.lightningApiService.getNodeGroup$('mempool.space') .pipe( map((nodes) => { for (const node of nodes) { diff --git a/frontend/src/app/lightning/lightning-api.service.ts b/frontend/src/app/lightning/lightning-api.service.ts index bdcc78f3f..ee55fb75d 100644 --- a/frontend/src/app/lightning/lightning-api.service.ts +++ b/frontend/src/app/lightning/lightning-api.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; -import { Observable } from 'rxjs'; +import { BehaviorSubject, Observable, catchError, filter, of, shareReplay, take, tap } from 'rxjs'; import { StateService } from '../services/state.service'; import { IChannel, INodesRanking, IOldestNodes, ITopNodesPerCapacity, ITopNodesPerChannels } from '../interfaces/node-api.interface'; @@ -9,6 +9,8 @@ import { IChannel, INodesRanking, IOldestNodes, ITopNodesPerCapacity, ITopNodesP }) export class LightningApiService { private apiBasePath = ''; // network path is /testnet, etc. or '' for mainnet + + private requestCache = new Map, expiry: number }>; constructor( private httpClient: HttpClient, @@ -23,11 +25,51 @@ export class LightningApiService { }); } + private generateCacheKey(functionName: string, params: any[]): string { + return functionName + JSON.stringify(params); + } + + // delete expired cache entries + private cleanExpiredCache(): void { + this.requestCache.forEach((value, key) => { + if (value.expiry < Date.now()) { + this.requestCache.delete(key); + } + }); + } + + cachedRequest Observable>( + apiFunction: F, + expireAfter: number, // in ms + ...params: Parameters + ): Observable { + this.cleanExpiredCache(); + + const cacheKey = this.generateCacheKey(apiFunction.name, params); + if (!this.requestCache.has(cacheKey)) { + const subject = new BehaviorSubject(null); + this.requestCache.set(cacheKey, { subject, expiry: Date.now() + expireAfter }); + + apiFunction.bind(this)(...params).pipe( + tap(data => { + subject.next(data as T); + }), + catchError((error) => { + subject.error(error); + return of(null); + }), + shareReplay(1), + ).subscribe(); + } + + return this.requestCache.get(cacheKey).subject.asObservable().pipe(filter(val => val !== null), take(1)); + } + getNode$(publicKey: string): Observable { return this.httpClient.get(this.apiBasePath + '/api/v1/lightning/nodes/' + publicKey); } - getNodGroupNodes$(name: string): Observable { + getNodeGroup$(name: string): Observable { return this.httpClient.get(this.apiBasePath + '/api/v1/lightning/nodes/group/' + name); } diff --git a/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.html b/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.html index f7d318073..ec59b7432 100644 --- a/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.html +++ b/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.html @@ -34,9 +34,11 @@
    -
    +
    - +
    + +
    @@ -44,11 +46,13 @@
    -
    +
    -
    Lightning Network History
    - - +
    +
    Lightning Network History
    + + +
    @@ -63,7 +67,7 @@   - +
    @@ -77,7 +81,7 @@   - +
    diff --git a/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.scss b/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.scss index e91f7606a..e6da450df 100644 --- a/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.scss +++ b/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.scss @@ -20,6 +20,19 @@ } } +.fixed-mempool-graph { + height: 330px; +} + +.mempool-graph, .fixed-mempool-graph { + @media (min-width: 768px) { + height: 345px; + } + @media (min-width: 992px) { + height: 439px; + } +} + .card-title { font-size: 1rem; color: #4a68b9; diff --git a/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.ts b/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.ts index ba5ee3db2..63cdab42d 100644 --- a/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.ts +++ b/frontend/src/app/lightning/lightning-dashboard/lightning-dashboard.component.ts @@ -1,7 +1,7 @@ -import { AfterViewInit, ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; +import { AfterViewInit, ChangeDetectionStrategy, Component, HostListener, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { share } from 'rxjs/operators'; -import { INodesRanking } from '../../interfaces/node-api.interface'; +import { INodesRanking, INodesStatistics } from '../../interfaces/node-api.interface'; import { SeoService } from '../../services/seo.service'; import { StateService } from '../../services/state.service'; import { LightningApiService } from '../lightning-api.service'; @@ -13,9 +13,10 @@ import { LightningApiService } from '../lightning-api.service'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class LightningDashboardComponent implements OnInit, AfterViewInit { - statistics$: Observable; + statistics$: Observable; nodesRanking$: Observable; officialMempoolSpace = this.stateService.env.OFFICIAL_MEMPOOL_SPACE; + graphHeight: number = 300; constructor( private lightningApiService: LightningApiService, @@ -24,8 +25,10 @@ export class LightningDashboardComponent implements OnInit, AfterViewInit { ) { } ngOnInit(): void { + this.onResize(); + this.seoService.setTitle($localize`:@@142e923d3b04186ac6ba23387265d22a2fa404e0:Lightning Explorer`); - this.seoService.setDescription($localize`:@@meta.description.lightning.dashboard:Get stats on the Lightning network (aggregate capacity, connectivity, etc) and Lightning nodes (channels, liquidity, etc) and Lightning channels (status, fees, etc).`); + this.seoService.setDescription($localize`:@@meta.description.lightning.dashboard:Get stats on the Lightning network (aggregate capacity, connectivity, etc), Lightning nodes (channels, liquidity, etc) and Lightning channels (status, fees, etc).`); this.nodesRanking$ = this.lightningApiService.getNodesRanking$().pipe(share()); this.statistics$ = this.lightningApiService.getLatestStatistics$().pipe(share()); @@ -34,4 +37,15 @@ export class LightningDashboardComponent implements OnInit, AfterViewInit { ngAfterViewInit(): void { this.stateService.focusSearchInputDesktop(); } + + @HostListener('window:resize', ['$event']) + onResize(): void { + if (window.innerWidth >= 992) { + this.graphHeight = 340; + } else if (window.innerWidth >= 768) { + this.graphHeight = 245; + } else { + this.graphHeight = 210; + } + } } diff --git a/frontend/src/app/lightning/node-fee-chart/node-fee-chart.component.ts b/frontend/src/app/lightning/node-fee-chart/node-fee-chart.component.ts index f20142e47..ad667bcf6 100644 --- a/frontend/src/app/lightning/node-fee-chart/node-fee-chart.component.ts +++ b/frontend/src/app/lightning/node-fee-chart/node-fee-chart.component.ts @@ -1,5 +1,5 @@ import { Component, Inject, Input, LOCALE_ID, OnInit, HostBinding } from '@angular/core'; -import { EChartsOption } from 'echarts'; +import { EChartsOption } from '../../graphs/echarts'; import { switchMap } from 'rxjs/operators'; import { download } from '../../shared/graphs.utils'; import { LightningApiService } from '../lightning-api.service'; diff --git a/frontend/src/app/lightning/node-statistics-chart/node-statistics-chart.component.ts b/frontend/src/app/lightning/node-statistics-chart/node-statistics-chart.component.ts index 9b10152b5..a9308a887 100644 --- a/frontend/src/app/lightning/node-statistics-chart/node-statistics-chart.component.ts +++ b/frontend/src/app/lightning/node-statistics-chart/node-statistics-chart.component.ts @@ -1,5 +1,5 @@ import { Component, Inject, Input, LOCALE_ID, OnInit, HostBinding } from '@angular/core'; -import { EChartsOption } from 'echarts'; +import { EChartsOption } from '../../graphs/echarts'; import { Observable } from 'rxjs'; import { switchMap, tap } from 'rxjs/operators'; import { formatNumber } from '@angular/common'; diff --git a/frontend/src/app/lightning/node-statistics/node-statistics.component.ts b/frontend/src/app/lightning/node-statistics/node-statistics.component.ts index c42720427..338e17ab8 100644 --- a/frontend/src/app/lightning/node-statistics/node-statistics.component.ts +++ b/frontend/src/app/lightning/node-statistics/node-statistics.component.ts @@ -1,5 +1,6 @@ import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; +import { INodesStatistics } from '../../interfaces/node-api.interface'; @Component({ selector: 'app-node-statistics', @@ -8,7 +9,7 @@ import { Observable } from 'rxjs'; changeDetection: ChangeDetectionStrategy.OnPush, }) export class NodeStatisticsComponent implements OnInit { - @Input() statistics$: Observable; + @Input() statistics$: Observable; constructor() { } diff --git a/frontend/src/app/lightning/node/node-preview.component.html b/frontend/src/app/lightning/node/node-preview.component.html index eae076bf5..6eb5b7848 100644 --- a/frontend/src/app/lightning/node/node-preview.component.html +++ b/frontend/src/app/lightning/node/node-preview.component.html @@ -49,7 +49,7 @@
    diff --git a/frontend/src/app/lightning/node/node.component.html b/frontend/src/app/lightning/node/node.component.html index 11ddbc0eb..445eba1c2 100644 --- a/frontend/src/app/lightning/node/node.component.html +++ b/frontend/src/app/lightning/node/node.component.html @@ -119,7 +119,7 @@ - + - - + + @@ -113,5 +113,10 @@
    AliasConnectConnect Location
    Location - unknown + Unknown
    FeaturesFeatures {{ bits }} @@ -133,11 +133,11 @@
    Raw bits
    {{ node.featuresBits }} -
    Decoded
    +
    Decoded
    - + diff --git a/frontend/src/app/lightning/node/node.component.ts b/frontend/src/app/lightning/node/node.component.ts index 56f48bf65..cb465f0b2 100644 --- a/frontend/src/app/lightning/node/node.component.ts +++ b/frontend/src/app/lightning/node/node.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, OnInit, ChangeDetectorRef } from '@angular/core'; import { ActivatedRoute, ParamMap } from '@angular/router'; -import { Observable, of, EMPTY } from 'rxjs'; +import { Observable, of } from 'rxjs'; import { catchError, map, switchMap, tap, share } from 'rxjs/operators'; import { SeoService } from '../../services/seo.service'; import { ApiService } from '../../services/api.service'; @@ -8,6 +8,7 @@ import { LightningApiService } from '../lightning-api.service'; import { GeolocationData } from '../../shared/components/geolocation/geolocation.component'; import { ILiquidityAd, parseLiquidityAdHex } from './liquidity-ad'; import { haversineDistance, kmToMiles } from '../../../app/shared/common.utils'; +import { ServicesApiServices } from '../../services/services-api.service'; interface CustomRecord { type: string; @@ -43,6 +44,7 @@ export class NodeComponent implements OnInit { constructor( private apiService: ApiService, + private servicesApiService: ServicesApiServices, private lightningApiService: LightningApiService, private activatedRoute: ActivatedRoute, private seoService: SeoService, @@ -155,7 +157,7 @@ export class NodeComponent implements OnInit { this.nodeOwner$ = this.activatedRoute.paramMap .pipe( switchMap((params: ParamMap) => { - return this.apiService.getNodeOwner$(params.get('public_key')).pipe( + return this.servicesApiService.getNodeOwner$(params.get('public_key')).pipe( switchMap((response) => { if (response.status === 204) { return of(false); diff --git a/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.html b/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.html index 095ae6f8e..7237c709f 100644 --- a/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.html +++ b/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.html @@ -1,22 +1,28 @@ -
    +
    -
    -
    - Lightning Nodes Channels World Map -
    - (Tor nodes excluded) -
    -
    -
    -
    + +
    + +
    +
    + Lightning Nodes Channels World Map +
    + (Tor nodes excluded) +
    + +
    +
    + +
    diff --git a/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.scss b/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.scss index 6db0f27b0..558ad68a6 100644 --- a/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.scss +++ b/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.scss @@ -143,3 +143,55 @@ text-align: center; margin-top: 100px; } + +.full-container-graph { + display: flex; + flex-direction: column; + padding: 0px 15px; + width: 100%; + height: calc(100vh - 225px); + min-height: 400px; + @media (min-width: 992px) { + height: calc(100vh - 150px); + } +} +.full-container-graph.widget { + min-height: 240px; + height: 240px; + padding: 0px; +} +.full-container-graph.fit-container { + margin: 0; + padding: 0; + height: 100%; + min-height: 100px; + + .chart { + padding: 0; + min-height: 100px; + } +} + +.chart-graph { + display: flex; + flex: 1; + height: 100%; + padding-top: 30px; + padding-bottom: 20px; + padding-right: 10px; + @media (max-width: 992px) { + padding-bottom: 25px; + } + @media (max-width: 829px) { + padding-bottom: 50px; + } + @media (max-width: 767px) { + padding-bottom: 25px; + } + @media (max-width: 629px) { + padding-bottom: 55px; + } + @media (max-width: 567px) { + padding-bottom: 55px; + } +} diff --git a/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.ts b/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.ts index 3090a803c..296d60dec 100644 --- a/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.ts +++ b/frontend/src/app/lightning/nodes-channels-map/nodes-channels-map.component.ts @@ -6,8 +6,7 @@ import { AssetsService } from '../../services/assets.service'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe'; import { StateService } from '../../services/state.service'; -import { EChartsOption, registerMap } from 'echarts'; -import 'echarts-gl'; +import { EChartsOption, echarts } from '../../graphs/echarts'; import { isMobile } from '../../shared/common.utils'; @Component({ @@ -66,6 +65,7 @@ export class NodesChannelsMap implements OnInit { } if (this.style === 'graph') { + this.center = [0, 5]; this.seoService.setTitle($localize`Lightning Nodes Channels World Map`); this.seoService.setDescription($localize`:@@meta.description.lightning.node-map:See the channels of non-Tor Lightning network nodes visualized on a world map. Hover/tap on points on the map for node names and details.`); } @@ -88,7 +88,7 @@ export class NodesChannelsMap implements OnInit { this.style !== 'channelpage' ? this.apiService.getChannelsGeo$(params.get('public_key') ?? undefined, this.style) : [''], [params.get('public_key') ?? undefined] ).pipe(tap((data) => { - registerMap('world', data[0]); + echarts.registerMap('world', data[0]); const channelsLoc = []; const nodes = []; @@ -239,7 +239,6 @@ export class NodesChannelsMap implements OnInit { title: title ?? undefined, tooltip: {}, geo: { - top: 75, animation: false, silent: true, center: this.center, diff --git a/frontend/src/app/lightning/nodes-channels/node-channels.component.ts b/frontend/src/app/lightning/nodes-channels/node-channels.component.ts index 91d43f6ab..be596d8f9 100644 --- a/frontend/src/app/lightning/nodes-channels/node-channels.component.ts +++ b/frontend/src/app/lightning/nodes-channels/node-channels.component.ts @@ -1,7 +1,7 @@ import { formatNumber } from '@angular/common'; import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, NgZone, OnChanges } from '@angular/core'; import { Router } from '@angular/router'; -import { ECharts, EChartsOption, TreemapSeriesOption } from 'echarts'; +import { EChartsOption, TreemapSeriesOption } from '../../graphs/echarts'; import { Observable, share, switchMap, tap } from 'rxjs'; import { lerpColor } from '../../shared/graphs.utils'; import { AmountShortenerPipe } from '../../shared/pipes/amount-shortener.pipe'; @@ -18,7 +18,7 @@ import { StateService } from '../../services/state.service'; export class NodeChannels implements OnChanges { @Input() publicKey: string; - chartInstance: ECharts; + chartInstance: any; chartOptions: EChartsOption = {}; chartInitOptions = { renderer: 'svg', @@ -129,7 +129,7 @@ export class NodeChannels implements OnChanges { }; } - onChartInit(ec: ECharts): void { + onChartInit(ec: any): void { this.chartInstance = ec; this.chartInstance.on('click', (e) => { diff --git a/frontend/src/app/lightning/nodes-map/nodes-map.component.ts b/frontend/src/app/lightning/nodes-map/nodes-map.component.ts index 4f74723cc..bb9e21c4b 100644 --- a/frontend/src/app/lightning/nodes-map/nodes-map.component.ts +++ b/frontend/src/app/lightning/nodes-map/nodes-map.component.ts @@ -3,7 +3,7 @@ import { SeoService } from '../../services/seo.service'; import { ApiService } from '../../services/api.service'; import { Observable, BehaviorSubject, switchMap, tap, combineLatest } from 'rxjs'; import { AssetsService } from '../../services/assets.service'; -import { EChartsOption, registerMap } from 'echarts'; +import { EChartsOption, echarts } from '../../graphs/echarts'; import { lerpColor } from '../../shared/graphs.utils'; import { Router } from '@angular/router'; import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pipe'; @@ -63,7 +63,7 @@ export class NodesMap implements OnInit, OnChanges { this.assetsService.getWorldMapJson$, this.nodes$ ).pipe(tap((data) => { - registerMap('world', data[0]); + echarts.registerMap('world', data[0]); let maxLiquidity = data[1].maxLiquidity; let inputNodes: any[] = data[1].nodes; @@ -114,7 +114,7 @@ export class NodesMap implements OnInit, OnChanges { node[3], // Alias node[2], // Public key node[5], // Channels - node[6].en, // Country + node[6]?.en, // Country node[7], // ISO Code ]); } diff --git a/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.html b/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.html index 908b98fda..915f2f7ec 100644 --- a/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.html +++ b/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.html @@ -35,7 +35,7 @@
    -
    +
    diff --git a/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.scss b/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.scss index 0e6fb056d..aaea41265 100644 --- a/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.scss +++ b/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.scss @@ -56,7 +56,6 @@ } .chart-widget { width: 100%; - height: 145px; } .pool-distribution { diff --git a/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.ts b/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.ts index f62a6a244..82c74395b 100644 --- a/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.ts +++ b/frontend/src/app/lightning/nodes-networks-chart/nodes-networks-chart.component.ts @@ -1,5 +1,5 @@ -import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, OnInit, HostBinding } from '@angular/core'; -import { EChartsOption, graphic, LineSeriesOption} from 'echarts'; +import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, OnInit, HostBinding, OnChanges, SimpleChanges } from '@angular/core'; +import { echarts, EChartsOption, LineSeriesOption } from '../../graphs/echarts'; import { Observable } from 'rxjs'; import { map, share, startWith, switchMap, tap } from 'rxjs/operators'; import { formatNumber } from '@angular/common'; @@ -26,7 +26,8 @@ import { isMobile } from '../../shared/common.utils'; `], changeDetection: ChangeDetectionStrategy.OnPush, }) -export class NodesNetworksChartComponent implements OnInit { +export class NodesNetworksChartComponent implements OnInit, OnChanges { + @Input() height: number = 150; @Input() right: number | string = 45; @Input() left: number | string = 45; @Input() widget = false; @@ -47,6 +48,9 @@ export class NodesNetworksChartComponent implements OnInit { timespan = ''; chartInstance: any = undefined; + chartData: any; + maxYAxis: number; + constructor( @Inject(LOCALE_ID) public locale: string, private seoService: SeoService, @@ -71,44 +75,49 @@ export class NodesNetworksChartComponent implements OnInit { this.radioGroupForm = this.formBuilder.group({ dateSpan: this.miningWindowPreference }); this.radioGroupForm.controls.dateSpan.setValue(this.miningWindowPreference); - this.nodesNetworkObservable$ = this.radioGroupForm.get('dateSpan').valueChanges - .pipe( - startWith(this.miningWindowPreference), - switchMap((timespan) => { - this.timespan = timespan; - if (!this.widget && !firstRun) { - this.storageService.setValue('lightningWindowPreference', timespan); - } - firstRun = false; - this.miningWindowPreference = timespan; - this.isLoading = true; - return this.lightningApiService.listStatistics$(timespan) - .pipe( - tap((response) => { - const data = response.body; - const chartData = { - tor_nodes: data.map(val => [val.added * 1000, val.tor_nodes]), - clearnet_nodes: data.map(val => [val.added * 1000, val.clearnet_nodes]), - unannounced_nodes: data.map(val => [val.added * 1000, val.unannounced_nodes]), - clearnet_tor_nodes: data.map(val => [val.added * 1000, val.clearnet_tor_nodes]), - }; - let maxYAxis = 0; - for (const day of data) { - maxYAxis = Math.max(maxYAxis, day.tor_nodes + day.clearnet_nodes + day.unannounced_nodes + day.clearnet_tor_nodes); - } - maxYAxis = Math.ceil(maxYAxis / 3000) * 3000; - this.prepareChartOptions(chartData, maxYAxis); - this.isLoading = false; - }), - map((response) => { - return { - days: parseInt(response.headers.get('x-total-count'), 10), - }; - }), - ); - }), - share() - ); + this.nodesNetworkObservable$ = this.radioGroupForm.get('dateSpan').valueChanges.pipe( + startWith(this.miningWindowPreference), + switchMap((timespan) => { + this.timespan = timespan; + if (!this.widget && !firstRun) { + this.storageService.setValue('lightningWindowPreference', timespan); + } + firstRun = false; + this.miningWindowPreference = timespan; + this.isLoading = true; + return this.lightningApiService.cachedRequest(this.lightningApiService.listStatistics$, 250, timespan) + .pipe( + tap((response:any) => { + const data = response.body; + this.chartData = { + tor_nodes: data.map(val => [val.added * 1000, val.tor_nodes]), + clearnet_nodes: data.map(val => [val.added * 1000, val.clearnet_nodes]), + unannounced_nodes: data.map(val => [val.added * 1000, val.unannounced_nodes]), + clearnet_tor_nodes: data.map(val => [val.added * 1000, val.clearnet_tor_nodes]), + }; + this.maxYAxis = 0; + for (const day of data) { + this.maxYAxis = Math.max(this.maxYAxis, day.tor_nodes + day.clearnet_nodes + day.unannounced_nodes + day.clearnet_tor_nodes); + } + this.maxYAxis = Math.ceil(this.maxYAxis / 3000) * 3000; + this.prepareChartOptions(this.chartData, this.maxYAxis); + this.isLoading = false; + }), + map((response) => { + return { + days: parseInt(response.headers.get('x-total-count'), 10), + }; + }), + ); + }), + share() + ); + } + + ngOnChanges(changes: SimpleChanges): void { + if (changes.height && this.chartData && this.maxYAxis != null) { + this.prepareChartOptions(this.chartData, this.maxYAxis); + } } prepareChartOptions(data, maxYAxis): void { @@ -152,7 +161,7 @@ export class NodesNetworksChartComponent implements OnInit { opacity: 0.5, }, stack: 'Total', - color: new graphic.LinearGradient(0, 0.75, 0, 1, [ + color: new echarts.graphic.LinearGradient(0, 0.75, 0, 1, [ { offset: 0, color: '#D81B60' }, { offset: 1, color: '#D81B60AA' }, ]), @@ -174,7 +183,7 @@ export class NodesNetworksChartComponent implements OnInit { opacity: 0.5, }, stack: 'Total', - color: new graphic.LinearGradient(0, 0.75, 0, 1, [ + color: new echarts.graphic.LinearGradient(0, 0.75, 0, 1, [ { offset: 0, color: '#be7d4c' }, { offset: 1, color: '#be7d4cAA' }, ]), @@ -195,7 +204,7 @@ export class NodesNetworksChartComponent implements OnInit { opacity: 0.5, }, stack: 'Total', - color: new graphic.LinearGradient(0, 0.75, 0, 1, [ + color: new echarts.graphic.LinearGradient(0, 0.75, 0, 1, [ { offset: 0, color: '#FFB300' }, { offset: 1, color: '#FFB300AA' }, ]), @@ -216,7 +225,7 @@ export class NodesNetworksChartComponent implements OnInit { opacity: 0.5, }, stack: 'Total', - color: new graphic.LinearGradient(0, 0.75, 0, 1, [ + color: new echarts.graphic.LinearGradient(0, 0.75, 0, 1, [ { offset: 0, color: '#7D4698' }, { offset: 1, color: '#7D4698AA' }, ]), @@ -228,7 +237,7 @@ export class NodesNetworksChartComponent implements OnInit { title: title, animation: false, grid: { - height: this.widget ? 90 : undefined, + height: this.widget ? ((this.height || 120) - 60) : undefined, top: this.widget ? 20 : 40, bottom: this.widget ? 0 : 70, right: (isMobile() && this.widget) ? 35 : this.right, diff --git a/frontend/src/app/lightning/nodes-per-country-chart/nodes-per-country-chart.component.ts b/frontend/src/app/lightning/nodes-per-country-chart/nodes-per-country-chart.component.ts index 5bfa0fc2c..e305d8959 100644 --- a/frontend/src/app/lightning/nodes-per-country-chart/nodes-per-country-chart.component.ts +++ b/frontend/src/app/lightning/nodes-per-country-chart/nodes-per-country-chart.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, OnInit, HostBinding, NgZone } from '@angular/core'; import { Router } from '@angular/router'; -import { EChartsOption, PieSeriesOption } from 'echarts'; +import { EChartsOption, PieSeriesOption } from '../../graphs/echarts'; import { map, Observable, share, tap } from 'rxjs'; import { chartColors } from '../../app.constants'; import { ApiService } from '../../services/api.service'; diff --git a/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.html b/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.html index 9318e925b..be7737894 100644 --- a/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.html +++ b/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.html @@ -64,8 +64,8 @@ - - + + @@ -116,5 +116,10 @@
    BitNameName Required
    Channels Location
    {{ node.alias }}
    + + + diff --git a/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.scss b/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.scss index 25e4cf7f3..97d42298c 100644 --- a/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.scss +++ b/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.scss @@ -22,14 +22,14 @@ .timestamp-first { width: 20%; - @media (max-width: 576px) { + @media (max-width: 1060px) { display: none } } .timestamp-update { width: 16%; - @media (max-width: 576px) { + @media (max-width: 1060px) { display: none } } @@ -50,7 +50,7 @@ .city { max-width: 150px; - @media (max-width: 576px) { + @media (max-width: 675px) { display: none } } \ No newline at end of file diff --git a/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.ts b/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.ts index 19dd999ee..4035b62d4 100644 --- a/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.ts +++ b/frontend/src/app/lightning/nodes-per-country/nodes-per-country.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; -import { map, Observable, share } from 'rxjs'; +import { BehaviorSubject, combineLatest, map, Observable, share, tap } from 'rxjs'; import { ApiService } from '../../services/api.service'; import { SeoService } from '../../services/seo.service'; import { getFlagEmoji } from '../../shared/common.utils'; @@ -15,6 +15,12 @@ import { GeolocationData } from '../../shared/components/geolocation/geolocation export class NodesPerCountry implements OnInit { nodes$: Observable; country: {name: string, flag: string}; + nodesPagination$: Observable; + startingIndexSubject: BehaviorSubject = new BehaviorSubject(0); + page = 1; + pageSize = 15; + maxSize = window.innerWidth <= 767.98 ? 3 : 5; + isLoading = true; skeletonLines: number[] = []; @@ -23,7 +29,7 @@ export class NodesPerCountry implements OnInit { private seoService: SeoService, private route: ActivatedRoute, ) { - for (let i = 0; i < 20; ++i) { + for (let i = 0; i < this.pageSize; ++i) { this.skeletonLines.push(i); } } @@ -31,6 +37,7 @@ export class NodesPerCountry implements OnInit { ngOnInit(): void { this.nodes$ = this.apiService.getNodeForCountry$(this.route.snapshot.params.country) .pipe( + tap(() => this.isLoading = true), map(response => { this.seoService.setTitle($localize`Lightning nodes in ${response.country.en}`); this.seoService.setDescription($localize`:@@meta.description.lightning.nodes-country:Explore all the Lightning nodes hosted in ${response.country.en} and see an overview of each node's capacity, number of open channels, and more.`); @@ -87,11 +94,21 @@ export class NodesPerCountry implements OnInit { ispCount: Object.keys(isps).length }; }), + tap(() => this.isLoading = false), share() ); + + this.nodesPagination$ = combineLatest([this.nodes$, this.startingIndexSubject]).pipe( + map(([response, startingIndex]) => response.nodes.slice(startingIndex, startingIndex + this.pageSize)) + ); } trackByPublicKey(index: number, node: any): string { return node.public_key; } + + pageChange(page: number): void { + this.startingIndexSubject.next((page - 1) * this.pageSize); + this.page = page; + } } diff --git a/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.html b/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.html index 259c3503a..794ced684 100644 --- a/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.html +++ b/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.html @@ -39,7 +39,7 @@
    -
    diff --git a/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.ts b/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.ts index 67f393bc2..3d8a4b861 100644 --- a/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.ts +++ b/frontend/src/app/lightning/nodes-per-isp-chart/nodes-per-isp-chart.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, OnInit, HostBinding, NgZone, Input } from '@angular/core'; import { Router } from '@angular/router'; -import { EChartsOption, PieSeriesOption } from 'echarts'; +import { EChartsOption, PieSeriesOption } from '../../graphs/echarts'; import { combineLatest, map, Observable, share, startWith, Subject, switchMap, tap } from 'rxjs'; import { chartColors } from '../../app.constants'; import { ApiService } from '../../services/api.service'; @@ -18,6 +18,7 @@ import { RelativeUrlPipe } from '../../shared/pipes/relative-url/relative-url.pi changeDetection: ChangeDetectionStrategy.OnPush, }) export class NodesPerISPChartComponent implements OnInit { + @Input() height: number = 300; @Input() widget: boolean = false; isLoading = true; diff --git a/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.html b/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.html index 3daafe4db..865d2d2dd 100644 --- a/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.html +++ b/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.html @@ -61,8 +61,8 @@
    Channels Location
    {{ node.alias }}
    + + +
    diff --git a/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.scss b/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.scss index b829c5b59..b043d36f8 100644 --- a/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.scss +++ b/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.scss @@ -24,7 +24,7 @@ .timestamp-first { width: 20%; - @media (max-width: 576px) { + @media (max-width: 1060px) { display: none } } @@ -32,7 +32,7 @@ .timestamp-update { width: 16%; - @media (max-width: 576px) { + @media (max-width: 1060px) { display: none } } @@ -56,7 +56,7 @@ .city { max-width: 150px; - @media (max-width: 576px) { + @media (max-width: 675px) { display: none } } diff --git a/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.ts b/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.ts index d4f27975c..f6c61a9f6 100644 --- a/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.ts +++ b/frontend/src/app/lightning/nodes-per-isp/nodes-per-isp.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; -import { map, Observable, share } from 'rxjs'; +import { BehaviorSubject, combineLatest, map, Observable, share, tap } from 'rxjs'; import { ApiService } from '../../services/api.service'; import { SeoService } from '../../services/seo.service'; import { getFlagEmoji } from '../../shared/common.utils'; @@ -15,6 +15,12 @@ import { GeolocationData } from '../../shared/components/geolocation/geolocation export class NodesPerISP implements OnInit { nodes$: Observable; isp: {name: string, id: number}; + nodesPagination$: Observable; + startingIndexSubject: BehaviorSubject = new BehaviorSubject(0); + page = 1; + pageSize = 15; + maxSize = window.innerWidth <= 767.98 ? 3 : 5; + isLoading = true; skeletonLines: number[] = []; @@ -23,7 +29,7 @@ export class NodesPerISP implements OnInit { private seoService: SeoService, private route: ActivatedRoute, ) { - for (let i = 0; i < 20; ++i) { + for (let i = 0; i < this.pageSize; ++i) { this.skeletonLines.push(i); } } @@ -31,6 +37,7 @@ export class NodesPerISP implements OnInit { ngOnInit(): void { this.nodes$ = this.apiService.getNodeForISP$(this.route.snapshot.params.isp) .pipe( + tap(() => this.isLoading = true), map(response => { this.isp = { name: response.isp, @@ -77,11 +84,21 @@ export class NodesPerISP implements OnInit { topCountry: topCountry, }; }), + tap(() => this.isLoading = false), share() ); + + this.nodesPagination$ = combineLatest([this.nodes$, this.startingIndexSubject]).pipe( + map(([response, startingIndex]) => response.nodes.slice(startingIndex, startingIndex + this.pageSize)) + ); } trackByPublicKey(index: number, node: any): string { return node.public_key; } + + pageChange(page: number): void { + this.startingIndexSubject.next((page - 1) * this.pageSize); + this.page = page; + } } diff --git a/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.html b/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.html index 5bd03941e..51836880d 100644 --- a/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.html +++ b/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.html @@ -1,7 +1,7 @@ - + - + diff --git a/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.ts b/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.ts index 373751be9..8a1eae3dc 100644 --- a/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.ts +++ b/frontend/src/app/lightning/nodes-ranking/nodes-ranking.component.ts @@ -1,5 +1,9 @@ import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; +import { LightningApiService } from '../lightning-api.service'; +import { share } from 'rxjs/operators'; +import { Observable } from 'rxjs'; +import { INodesStatistics } from '../../interfaces/node-api.interface'; @Component({ selector: 'app-nodes-ranking', @@ -9,10 +13,15 @@ import { ActivatedRoute } from '@angular/router'; }) export class NodesRanking implements OnInit { type: string; + statistics$: Observable; - constructor(private route: ActivatedRoute) {} + constructor( + private route: ActivatedRoute, + private lightningApiService: LightningApiService, + ) {} ngOnInit(): void { + this.statistics$ = this.lightningApiService.getLatestStatistics$().pipe(share()); this.route.data.subscribe(data => { this.type = data.type; }); diff --git a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.html b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.html index 3efbc8594..27af80564 100644 --- a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.html +++ b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.html @@ -16,8 +16,8 @@ Last update Location - - + +
    @@ -27,12 +27,14 @@ +  ({{ (node?.capacity / data.statistics.totalCapacity * 100) | number:'1.1-1' }}%) {{ node.channels | number }} +  ({{ (node?.channels / data.statistics.totalChannels * 100) | number:'1.1-1' }}%) diff --git a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.scss b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.scss index 3547c447f..89f144135 100644 --- a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.scss +++ b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.scss @@ -41,6 +41,11 @@ tr, td, th { } } +.capacity-ratio { + font-size: 12px; + color: darkgrey; +} + .fiat { width: 15%; @media (min-width: 768px) and (max-width: 991px) { diff --git a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.ts b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.ts index 054fa2f3c..0b8c03bbd 100644 --- a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.ts +++ b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-capacity/top-nodes-per-capacity.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; -import { map, Observable } from 'rxjs'; -import { INodesRanking, ITopNodesPerCapacity } from '../../../interfaces/node-api.interface'; +import { combineLatest, map, Observable } from 'rxjs'; +import { INodesRanking, INodesStatistics, ITopNodesPerCapacity } from '../../../interfaces/node-api.interface'; import { SeoService } from '../../../services/seo.service'; import { StateService } from '../../../services/state.service'; import { GeolocationData } from '../../../shared/components/geolocation/geolocation.component'; @@ -14,9 +14,10 @@ import { LightningApiService } from '../../lightning-api.service'; }) export class TopNodesPerCapacity implements OnInit { @Input() nodes$: Observable; + @Input() statistics$: Observable; @Input() widget: boolean = false; - topNodesPerCapacity$: Observable; + topNodesPerCapacity$: Observable<{ nodes: ITopNodesPerCapacity[]; statistics: { totalCapacity: number; totalChannels?: number; } }>; skeletonRows: number[] = []; currency$: Observable; @@ -39,8 +40,12 @@ export class TopNodesPerCapacity implements OnInit { } if (this.widget === false) { - this.topNodesPerCapacity$ = this.apiService.getTopNodesByCapacity$().pipe( - map((ranking) => { + this.topNodesPerCapacity$ = combineLatest([ + this.apiService.getTopNodesByCapacity$(), + this.statistics$ + ]) + .pipe( + map(([ranking, statistics]) => { for (const i in ranking) { ranking[i].geolocation = { country: ranking[i].country?.en, @@ -49,13 +54,28 @@ export class TopNodesPerCapacity implements OnInit { iso: ranking[i].iso_code, }; } - return ranking; + return { + nodes: ranking, + statistics: { + totalCapacity: statistics.latest.total_capacity, + totalChannels: statistics.latest.channel_count, + } + } }) ); } else { - this.topNodesPerCapacity$ = this.nodes$.pipe( - map((ranking) => { - return ranking.topByCapacity.slice(0, 6); + this.topNodesPerCapacity$ = combineLatest([ + this.nodes$, + this.statistics$ + ]) + .pipe( + map(([ranking, statistics]) => { + return { + nodes: ranking.topByCapacity.slice(0, 6), + statistics: { + totalCapacity: statistics.latest.total_capacity, + } + } }) ); } diff --git a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.html b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.html index 94a887bb3..87f7f1ad2 100644 --- a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.html +++ b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.html @@ -16,8 +16,8 @@ Last update Location - - + +
    @@ -27,9 +27,11 @@ {{ node.channels ? (node.channels | number) : '~' }} +  ({{ (node?.channels / data.statistics.totalChannels * 100) | number:'1.1-1' }}%) +  ({{ (node.capacity / data.statistics.totalCapacity * 100) | number:'1.1-1' }}%) diff --git a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.scss b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.scss index a42599d69..63d65bcf8 100644 --- a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.scss +++ b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.scss @@ -44,6 +44,11 @@ tr, td, th { } } +.capacity-ratio { + font-size: 12px; + color: darkgrey; +} + .geolocation { @media (min-width: 768px) and (max-width: 991px) { display: none !important; diff --git a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.ts b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.ts index 3de177cc7..56d55a5d3 100644 --- a/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.ts +++ b/frontend/src/app/lightning/nodes-ranking/top-nodes-per-channels/top-nodes-per-channels.component.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; -import { map, Observable } from 'rxjs'; -import { INodesRanking, ITopNodesPerChannels } from '../../../interfaces/node-api.interface'; +import { combineLatest, map, Observable } from 'rxjs'; +import { INodesRanking, INodesStatistics, ITopNodesPerChannels } from '../../../interfaces/node-api.interface'; import { SeoService } from '../../../services/seo.service'; import { StateService } from '../../../services/state.service'; import { GeolocationData } from '../../../shared/components/geolocation/geolocation.component'; @@ -14,12 +14,13 @@ import { LightningApiService } from '../../lightning-api.service'; }) export class TopNodesPerChannels implements OnInit { @Input() nodes$: Observable; + @Input() statistics$: Observable; @Input() widget: boolean = false; - topNodesPerChannels$: Observable; + topNodesPerChannels$: Observable<{ nodes: ITopNodesPerChannels[]; statistics: { totalChannels: number; totalCapacity?: number; } }>; skeletonRows: number[] = []; currency$: Observable; - + constructor( private apiService: LightningApiService, private stateService: StateService, @@ -37,8 +38,12 @@ export class TopNodesPerChannels implements OnInit { this.seoService.setTitle($localize`:@@c50bf442cf99f6fc5f8b687c460f33234b879869:Connectivity Ranking`); this.seoService.setDescription($localize`:@@meta.description.lightning.ranking.channels:See Lightning nodes with the most channels open along with high-level stats like total node capacity, node age, and more.`); - this.topNodesPerChannels$ = this.apiService.getTopNodesByChannels$().pipe( - map((ranking) => { + this.topNodesPerChannels$ = combineLatest([ + this.apiService.getTopNodesByChannels$(), + this.statistics$ + ]) + .pipe( + map(([ranking, statistics]) => { for (const i in ranking) { ranking[i].geolocation = { country: ranking[i].country?.en, @@ -47,12 +52,22 @@ export class TopNodesPerChannels implements OnInit { iso: ranking[i].iso_code, }; } - return ranking; + return { + nodes: ranking, + statistics: { + totalChannels: statistics.latest.channel_count, + totalCapacity: statistics.latest.total_capacity, + } + } }) ); } else { - this.topNodesPerChannels$ = this.nodes$.pipe( - map((ranking) => { + this.topNodesPerChannels$ = combineLatest([ + this.nodes$, + this.statistics$ + ]) + .pipe( + map(([ranking, statistics]) => { for (const i in ranking.topByChannels) { ranking.topByChannels[i].geolocation = { country: ranking.topByChannels[i].country?.en, @@ -61,7 +76,12 @@ export class TopNodesPerChannels implements OnInit { iso: ranking.topByChannels[i].iso_code, }; } - return ranking.topByChannels.slice(0, 6); + return { + nodes: ranking.topByChannels.slice(0, 6), + statistics: { + totalChannels: statistics.latest.channel_count, + } + } }) ); } diff --git a/frontend/src/app/lightning/nodes-rankings-dashboard/nodes-rankings-dashboard.component.ts b/frontend/src/app/lightning/nodes-rankings-dashboard/nodes-rankings-dashboard.component.ts index 46becb793..178ca783c 100644 --- a/frontend/src/app/lightning/nodes-rankings-dashboard/nodes-rankings-dashboard.component.ts +++ b/frontend/src/app/lightning/nodes-rankings-dashboard/nodes-rankings-dashboard.component.ts @@ -20,7 +20,7 @@ export class NodesRankingsDashboard implements OnInit { ngOnInit(): void { this.seoService.setTitle($localize`Top lightning nodes`); - this.seoService.setDescription($localize`:@@meta.description.lightning.rankings-dashboard:See top the Lightning network nodes ranked by liquidity, connectivity, and age.`); + this.seoService.setDescription($localize`:@@meta.description.lightning.rankings-dashboard:See the top Lightning network nodes ranked by liquidity, connectivity, and age.`); this.nodesRanking$ = this.lightningApiService.getNodesRanking$().pipe(share()); } } diff --git a/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.html b/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.html index 68fe3ee64..9bb88ac59 100644 --- a/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.html +++ b/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.html @@ -42,7 +42,7 @@
    -
    diff --git a/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.scss b/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.scss index c885e4839..923a8a3e4 100644 --- a/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.scss +++ b/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.scss @@ -56,7 +56,6 @@ } .chart-widget { width: 100%; - height: 145px; } .pool-distribution { diff --git a/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.ts b/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.ts index 41e170de6..8bcf01015 100644 --- a/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.ts +++ b/frontend/src/app/lightning/statistics-chart/lightning-statistics-chart.component.ts @@ -1,6 +1,6 @@ -import { Component, Inject, Input, LOCALE_ID, OnInit, HostBinding } from '@angular/core'; -import { EChartsOption, graphic } from 'echarts'; -import { Observable } from 'rxjs'; +import { Component, Inject, Input, LOCALE_ID, OnInit, HostBinding, OnChanges, SimpleChanges } from '@angular/core'; +import { echarts, EChartsOption } from '../../graphs/echarts'; +import { Observable, combineLatest, fromEvent } from 'rxjs'; import { map, share, startWith, switchMap, tap } from 'rxjs/operators'; import { SeoService } from '../../services/seo.service'; import { formatNumber } from '@angular/common'; @@ -25,7 +25,8 @@ import { isMobile } from '../../shared/common.utils'; } `], }) -export class LightningStatisticsChartComponent implements OnInit { +export class LightningStatisticsChartComponent implements OnInit, OnChanges { + @Input() height: number = 150; @Input() right: number | string = 45; @Input() left: number | string = 45; @Input() widget = false; @@ -37,6 +38,7 @@ export class LightningStatisticsChartComponent implements OnInit { chartInitOptions = { renderer: 'svg', }; + chartData: any; @HostBinding('attr.dir') dir = 'ltr'; @@ -70,36 +72,42 @@ export class LightningStatisticsChartComponent implements OnInit { this.radioGroupForm = this.formBuilder.group({ dateSpan: this.miningWindowPreference }); this.radioGroupForm.controls.dateSpan.setValue(this.miningWindowPreference); - this.capacityObservable$ = this.radioGroupForm.get('dateSpan').valueChanges - .pipe( - startWith(this.miningWindowPreference), - switchMap((timespan) => { - this.timespan = timespan; - if (!this.widget && !firstRun) { - this.storageService.setValue('lightningWindowPreference', timespan); - } - firstRun = false; - this.miningWindowPreference = timespan; - this.isLoading = true; - return this.lightningApiService.listStatistics$(timespan) - .pipe( - tap((response) => { - const data = response.body; - this.prepareChartOptions({ - channel_count: data.map(val => [val.added * 1000, val.channel_count]), - capacity: data.map(val => [val.added * 1000, val.total_capacity]), - }); - this.isLoading = false; - }), - map((response) => { - return { - days: parseInt(response.headers.get('x-total-count'), 10), - }; - }), - ); - }), - share(), - ); + this.capacityObservable$ = this.radioGroupForm.get('dateSpan').valueChanges.pipe( + startWith(this.miningWindowPreference), + switchMap((timespan) => { + this.timespan = timespan; + if (!this.widget && !firstRun) { + this.storageService.setValue('lightningWindowPreference', timespan); + } + firstRun = false; + this.miningWindowPreference = timespan; + this.isLoading = true; + return this.lightningApiService.cachedRequest(this.lightningApiService.listStatistics$, 250, timespan) + .pipe( + tap((response:any) => { + const data = response.body; + this.chartData = { + channel_count: data.map(val => [val.added * 1000, val.channel_count]), + capacity: data.map(val => [val.added * 1000, val.total_capacity]), + }; + this.prepareChartOptions(this.chartData); + this.isLoading = false; + }), + map((response) => { + return { + days: parseInt(response.headers.get('x-total-count'), 10), + }; + }), + ); + }), + share(), + ); + } + + ngOnChanges(changes: SimpleChanges): void { + if (changes.height && this.chartData) { + this.prepareChartOptions(this.chartData); + } } prepareChartOptions(data): void { @@ -132,13 +140,13 @@ export class LightningStatisticsChartComponent implements OnInit { animation: false, color: [ '#FFB300', - new graphic.LinearGradient(0, 0.75, 0, 1, [ + new echarts.graphic.LinearGradient(0, 0.75, 0, 1, [ { offset: 0, color: '#D81B60' }, { offset: 1, color: '#D81B60AA' }, ]), ], grid: { - height: this.widget ? 90 : undefined, + height: this.widget ? ((this.height || 120) - 60) : undefined, top: this.widget ? 20 : 40, bottom: this.widget ? 0 : 70, right: (isMobile() && this.widget) ? 35 : this.right, diff --git a/frontend/src/app/liquid/liquid-graphs.module.ts b/frontend/src/app/liquid/liquid-graphs.module.ts new file mode 100644 index 000000000..3da93fc9d --- /dev/null +++ b/frontend/src/app/liquid/liquid-graphs.module.ts @@ -0,0 +1,37 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { LiquidMasterPageComponent } from '../components/liquid-master-page/liquid-master-page.component'; + +const routes: Routes = [ + { + path: '', + component: LiquidMasterPageComponent, + loadChildren: () => import('../graphs/graphs.module').then(m => m.GraphsModule), + data: { preload: true }, + } +]; + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class LiquidGraphsRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + LiquidGraphsRoutingModule, + ], +}) +export class LiquidGraphsModule { } + + + + + + diff --git a/frontend/src/app/liquid/liquid-master-page.module.ts b/frontend/src/app/liquid/liquid-master-page.module.ts new file mode 100644 index 000000000..4b8364ad5 --- /dev/null +++ b/frontend/src/app/liquid/liquid-master-page.module.ts @@ -0,0 +1,183 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { SharedModule } from '../shared/shared.module'; +import { NgxEchartsModule } from 'ngx-echarts'; +import { LiquidMasterPageComponent } from '../components/liquid-master-page/liquid-master-page.component'; + + +import { StartComponent } from '../components/start/start.component'; +import { AddressComponent } from '../components/address/address.component'; +import { PushTransactionComponent } from '../components/push-transaction/push-transaction.component'; +import { BlocksList } from '../components/blocks-list/blocks-list.component'; +import { AssetGroupComponent } from '../components/assets/asset-group/asset-group.component'; +import { AssetsComponent } from '../components/assets/assets.component'; +import { AssetsFeaturedComponent } from '../components/assets/assets-featured/assets-featured.component' +import { AssetComponent } from '../components/asset/asset.component'; +import { AssetsNavComponent } from '../components/assets/assets-nav/assets-nav.component'; +import { RecentPegsListComponent } from '../components/liquid-reserves-audit/recent-pegs-list/recent-pegs-list.component'; +import { FederationWalletComponent } from '../components/liquid-reserves-audit/federation-wallet/federation-wallet.component'; +import { FederationUtxosListComponent } from '../components/liquid-reserves-audit/federation-utxos-list/federation-utxos-list.component'; +import { FederationAddressesListComponent } from '../components/liquid-reserves-audit/federation-addresses-list/federation-addresses-list.component'; +import { ServerHealthComponent } from '../components/server-health/server-health.component'; +import { ServerStatusComponent } from '../components/server-health/server-status.component'; + +const routes: Routes = [ + { + path: '', + component: LiquidMasterPageComponent, + children: [ + { + path: 'tx/push', + component: PushTransactionComponent, + }, + { + path: 'about', + loadChildren: () => import('../components/about/about.module').then(m => m.AboutModule), + }, + { + path: 'blocks', + component: BlocksList, + }, + { + path: 'terms-of-service', + loadChildren: () => import('../components/terms-of-service/terms-of-service.module').then(m => m.TermsOfServiceModule), + }, + { + path: 'privacy-policy', + loadChildren: () => import('../components/privacy-policy/privacy-policy.module').then(m => m.PrivacyPolicyModule), + }, + { + path: 'trademark-policy', + loadChildren: () => import('../components/trademark-policy/trademark-policy.module').then(m => m.TrademarkModule), + }, + { + path: 'address/:id', + children: [], + component: AddressComponent, + data: { + ogImage: true, + networkSpecific: true, + } + }, + { + path: 'tx', + component: StartComponent, + data: { preload: true, networkSpecific: true }, + loadChildren: () => import('../components/transaction/transaction.module').then(m => m.TransactionModule), + }, + { + path: 'block', + component: StartComponent, + data: { preload: true, networkSpecific: true }, + loadChildren: () => import('../components/block/block.module').then(m => m.BlockModule), + }, + { + path: 'audit/wallet', + data: { networks: ['liquid'] }, + component: FederationWalletComponent, + children: [ + { + path: 'utxos', + data: { networks: ['liquid'] }, + component: FederationUtxosListComponent, + }, + { + path: 'addresses', + data: { networks: ['liquid'] }, + component: FederationAddressesListComponent, + }, + { + path: '**', + redirectTo: 'utxos' + } + ] + }, + { + path: 'audit/pegs', + data: { networks: ['liquid'] }, + component: RecentPegsListComponent, + }, + { + path: 'assets', + data: { networks: ['liquid'] }, + component: AssetsNavComponent, + children: [ + { + path: 'all', + data: { networks: ['liquid'] }, + component: AssetsComponent, + }, + { + path: 'featured', + data: { networks: ['liquid'] }, + component: AssetsFeaturedComponent, + }, + { + path: 'asset/:id', + data: { networkSpecific: true }, + component: AssetComponent + }, + { + path: 'group/:id', + data: { networkSpecific: true }, + component: AssetGroupComponent + }, + { + path: '**', + redirectTo: 'featured' + } + ] + }, + { + path: 'docs', + loadChildren: () => import('../docs/docs.module').then(m => m.DocsModule), + data: { preload: true }, + }, + { + path: 'api', + loadChildren: () => import('../docs/docs.module').then(m => m.DocsModule) + }, + ], + }, +]; + +if (window['__env']?.OFFICIAL_MEMPOOL_SPACE) { + routes[0].children.push({ + path: 'nodes', + data: { networks: ['bitcoin', 'liquid'] }, + component: ServerHealthComponent + }); + routes[0].children.push({ + path: 'network', + data: { networks: ['bitcoin', 'liquid'] }, + component: ServerStatusComponent + }); +} + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class LiquidRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + LiquidRoutingModule, + SharedModule, + NgxEchartsModule.forRoot({ + echarts: () => import('../graphs/echarts').then(m => m.echarts), + }) + ], + declarations: [ + LiquidMasterPageComponent, + FederationWalletComponent, + FederationUtxosListComponent, + ] +}) +export class LiquidMasterPageModule { } \ No newline at end of file diff --git a/frontend/src/app/master-page.module.ts b/frontend/src/app/master-page.module.ts new file mode 100644 index 000000000..ec3e08674 --- /dev/null +++ b/frontend/src/app/master-page.module.ts @@ -0,0 +1,137 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { Routes, RouterModule } from '@angular/router'; +import { MasterPageComponent } from './components/master-page/master-page.component'; +import { SharedModule } from './shared/shared.module'; + +import { StartComponent } from './components/start/start.component'; +import { AddressComponent } from './components/address/address.component'; +import { PushTransactionComponent } from './components/push-transaction/push-transaction.component'; +import { CalculatorComponent } from './components/calculator/calculator.component'; +import { BlocksList } from './components/blocks-list/blocks-list.component'; +import { RbfList } from './components/rbf-list/rbf-list.component'; +import { ServerHealthComponent } from './components/server-health/server-health.component'; +import { ServerStatusComponent } from './components/server-health/server-status.component'; + +const browserWindow = window || {}; +// @ts-ignore +const browserWindowEnv = browserWindow.__env || {}; + +const routes: Routes = [ + { + path: '', + component: MasterPageComponent, + children: [ + { + path: 'mining/blocks', + redirectTo: 'blocks', + pathMatch: 'full' + }, + { + path: 'tx/push', + component: PushTransactionComponent, + }, + { + path: 'about', + loadChildren: () => import('./components/about/about.module').then(m => m.AboutModule), + }, + { + path: 'blocks', + component: BlocksList, + }, + { + path: 'rbf', + component: RbfList, + }, + { + path: 'terms-of-service', + loadChildren: () => import('./components/terms-of-service/terms-of-service.module').then(m => m.TermsOfServiceModule), + }, + { + path: 'privacy-policy', + loadChildren: () => import('./components/privacy-policy/privacy-policy.module').then(m => m.PrivacyPolicyModule), + }, + { + path: 'trademark-policy', + loadChildren: () => import('./components/trademark-policy/trademark-policy.module').then(m => m.TrademarkModule), + }, + { + path: 'address/:id', + children: [], + component: AddressComponent, + data: { + ogImage: true, + networkSpecific: true, + } + }, + { + path: 'tx', + component: StartComponent, + data: { preload: true, networkSpecific: true }, + loadChildren: () => import('./components/transaction/transaction.module').then(m => m.TransactionModule), + }, + { + path: 'block', + component: StartComponent, + data: { preload: true, networkSpecific: true }, + loadChildren: () => import('./components/block/block.module').then(m => m.BlockModule), + }, + { + path: 'docs', + loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule), + data: { preload: true }, + }, + { + path: 'api', + loadChildren: () => import('./docs/docs.module').then(m => m.DocsModule) + }, + { + path: 'lightning', + loadChildren: () => import('./lightning/lightning.module').then(m => m.LightningModule), + data: { preload: browserWindowEnv && browserWindowEnv.LIGHTNING === true, networks: ['bitcoin'] }, + }, + { + path: 'tools/calculator', + component: CalculatorComponent + }, + ], + } +]; + +if (window['__env']?.OFFICIAL_MEMPOOL_SPACE) { + routes[0].children.push({ + path: 'nodes', + data: { networks: ['bitcoin', 'liquid'] }, + component: ServerHealthComponent + }); + routes[0].children.push({ + path: 'network', + data: { networks: ['bitcoin', 'liquid'] }, + component: ServerStatusComponent + }); +} + +@NgModule({ + imports: [ + RouterModule.forChild(routes) + ], + exports: [ + RouterModule + ] +}) +export class MasterPageRoutingModule { } + +@NgModule({ + imports: [ + CommonModule, + MasterPageRoutingModule, + SharedModule, + ], + declarations: [ + MasterPageComponent, + ], + exports: [ + MasterPageComponent, + ] +}) +export class MasterPageModule { } diff --git a/frontend/src/app/previews.module.ts b/frontend/src/app/previews.module.ts index 2e8dbdc75..95124f232 100644 --- a/frontend/src/app/previews.module.ts +++ b/frontend/src/app/previews.module.ts @@ -9,6 +9,7 @@ import { BlockPreviewComponent } from './components/block/block-preview.componen import { AddressPreviewComponent } from './components/address/address-preview.component'; import { PoolPreviewComponent } from './components/pool/pool-preview.component'; import { MasterPagePreviewComponent } from './components/master-page-preview/master-page-preview.component'; +import { TxBowtieModule } from './components/tx-bowtie-graph/tx-bowtie.module'; @NgModule({ declarations: [ TransactionPreviewComponent, @@ -23,6 +24,7 @@ import { MasterPagePreviewComponent } from './components/master-page-preview/mas RouterModule, PreviewsRoutingModule, GraphsModule, + TxBowtieModule, ], }) export class PreviewsModule { } diff --git a/frontend/src/app/previews.routing.module.ts b/frontend/src/app/previews.routing.module.ts index c2ad8db5f..6ac44a370 100644 --- a/frontend/src/app/previews.routing.module.ts +++ b/frontend/src/app/previews.routing.module.ts @@ -31,7 +31,8 @@ const routes: Routes = [ }, { path: 'lightning', - loadChildren: () => import('./lightning/lightning-previews.module').then(m => m.LightningPreviewsModule) + loadChildren: () => import('./lightning/lightning-previews.module').then(m => m.LightningPreviewsModule), + data: { preload: true }, }, ], } diff --git a/frontend/src/app/services/api.service.ts b/frontend/src/app/services/api.service.ts index 744474f9d..7bd41c8a0 100644 --- a/frontend/src/app/services/api.service.ts +++ b/frontend/src/app/services/api.service.ts @@ -1,17 +1,13 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http'; import { CpfpInfo, OptimizedMempoolStats, AddressInformation, LiquidPegs, ITranslators, - PoolStat, BlockExtended, TransactionStripped, RewardStats, AuditScore, BlockSizesAndWeights, RbfTree, BlockAudit } from '../interfaces/node-api.interface'; -import { Observable, of } from 'rxjs'; + PoolStat, BlockExtended, TransactionStripped, RewardStats, AuditScore, BlockSizesAndWeights, RbfTree, BlockAudit, Acceleration, AccelerationHistoryParams, CurrentPegs, AuditStatus, FederationAddress, FederationUtxo, RecentPeg, PegsVolume } from '../interfaces/node-api.interface'; +import { BehaviorSubject, Observable, catchError, filter, of, shareReplay, take, tap } from 'rxjs'; import { StateService } from './state.service'; -import { IBackendInfo, WebsocketResponse } from '../interfaces/websocket.interface'; -import { Outspend, Transaction } from '../interfaces/electrs.interface'; +import { Transaction } from '../interfaces/electrs.interface'; import { Conversion } from './price.service'; -import { MenuGroup } from '../interfaces/services.interface'; import { StorageService } from './storage.service'; - -// Todo - move to config.json -const SERVICES_API_PREFIX = `/api/v1/services`; +import { WebsocketResponse } from '../interfaces/websocket.interface'; @Injectable({ providedIn: 'root' @@ -20,6 +16,8 @@ export class ApiService { private apiBaseUrl: string; // base URL is protocol, hostname, and port private apiBasePath: string; // network path is /testnet, etc. or '' for mainnet + private requestCache = new Map, expiry: number }>; + constructor( private httpClient: HttpClient, private stateService: StateService, @@ -36,12 +34,46 @@ export class ApiService { } this.apiBasePath = network ? '/' + network : ''; }); + } - if (this.stateService.env.GIT_COMMIT_HASH_MEMPOOL_SPACE) { - this.getServicesBackendInfo$().subscribe(version => { - this.stateService.servicesBackendInfo$.next(version); - }) + private generateCacheKey(functionName: string, params: any[]): string { + return functionName + JSON.stringify(params); + } + + // delete expired cache entries + private cleanExpiredCache(): void { + this.requestCache.forEach((value, key) => { + if (value.expiry < Date.now()) { + this.requestCache.delete(key); + } + }); + } + + cachedRequest Observable>( + apiFunction: F, + expireAfter: number, // in ms + ...params: Parameters + ): Observable { + this.cleanExpiredCache(); + + const cacheKey = this.generateCacheKey(apiFunction.name, params); + if (!this.requestCache.has(cacheKey)) { + const subject = new BehaviorSubject(null); + this.requestCache.set(cacheKey, { subject, expiry: Date.now() + expireAfter }); + + apiFunction.bind(this)(...params).pipe( + tap(data => { + subject.next(data as T); + }), + catchError((error) => { + subject.error(error); + return of(null); + }), + shareReplay(1), + ).subscribe(); } + + return this.requestCache.get(cacheKey).subject.asObservable().pipe(filter(val => val !== null), take(1)); } list2HStatistics$(): Observable { @@ -96,14 +128,6 @@ export class ApiService { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/transaction-times', { params }); } - getOutspendsBatched$(txIds: string[]): Observable { - let params = new HttpParams(); - txIds.forEach((txId: string) => { - params = params.append('txId[]', txId); - }); - return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/outspends', { params }); - } - getAboutPageProfiles$(): Observable { return this.httpClient.get(this.apiBaseUrl + '/api/v1/services/sponsors'); } @@ -144,10 +168,54 @@ export class ApiService { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/' + (fullRbf ? 'fullrbf/' : '') + 'replacements/' + (after || '')); } + liquidPegs$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/pegs'); + } + + pegsVolume$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/pegs/volume'); + } + listLiquidPegsMonth$(): Observable { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/pegs/month'); } + liquidReserves$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/reserves'); + } + + listLiquidReservesMonth$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/reserves/month'); + } + + federationAuditSynced$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/reserves/status'); + } + + federationAddresses$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/reserves/addresses'); + } + + federationUtxos$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/reserves/utxos'); + } + + recentPegsList$(count: number = 0): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/pegs/list/' + count); + } + + pegsCount$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/pegs/count'); + } + + federationAddressesNumber$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/reserves/addresses/total'); + } + + federationUtxosNumber$(): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/liquid/reserves/utxos/total'); + } + listFeaturedAssets$(): Observable { return this.httpClient.get(this.apiBaseUrl + '/api/v1/assets/featured'); } @@ -193,6 +261,10 @@ export class ApiService { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/block/' + hash); } + getBlockDataFromTimestamp$(timestamp: number): Observable { + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/mining/blocks/timestamp/' + timestamp); + } + getStrippedBlockTransactions$(hash: string): Observable { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/v1/block/' + hash + '/summary'); } @@ -277,7 +349,7 @@ export class ApiService { } getEnterpriseInfo$(name: string): Observable { - return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + `/api/v1/enterprise/info/` + name); + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + `/api/v1/services/enterprise/info/` + name); } getChannelByTxIds$(txIds: string[]): Observable { @@ -340,54 +412,4 @@ export class ApiService { (timestamp ? `?timestamp=${timestamp}` : '') ); } - - /** - * Services - */ - - getNodeOwner$(publicKey: string): Observable { - let params = new HttpParams() - .set('node_public_key', publicKey); - return this.httpClient.get(`${SERVICES_API_PREFIX}/lightning/claim/current`, { params, observe: 'response' }); - } - - getUserMenuGroups$(): Observable { - const auth = this.storageService.getAuth(); - if (!auth) { - return of(null); - } - - return this.httpClient.get(`${SERVICES_API_PREFIX}/account/menu`); - } - - getUserInfo$(): Observable { - const auth = this.storageService.getAuth(); - if (!auth) { - return of(null); - } - - return this.httpClient.get(`${SERVICES_API_PREFIX}/account`); - } - - logout$(): Observable { - const auth = this.storageService.getAuth(); - if (!auth) { - return of(null); - } - - localStorage.removeItem('auth'); - return this.httpClient.post(`${SERVICES_API_PREFIX}/auth/logout`, {}); - } - - getServicesBackendInfo$(): Observable { - return this.httpClient.get(`${SERVICES_API_PREFIX}/version`); - } - - estimate$(txInput: string) { - return this.httpClient.post(`${SERVICES_API_PREFIX}/accelerator/estimate`, { txInput: txInput }, { observe: 'response' }); - } - - accelerate$(txInput: string, userBid: number) { - return this.httpClient.post(`${SERVICES_API_PREFIX}/accelerator/accelerate`, { txInput: txInput, userBid: userBid }); - } } diff --git a/frontend/src/app/services/audio.service.ts b/frontend/src/app/services/audio.service.ts index a0b27d168..5b5ffbf07 100644 --- a/frontend/src/app/services/audio.service.ts +++ b/frontend/src/app/services/audio.service.ts @@ -13,7 +13,7 @@ export class AudioService { } catch (e) {} } - public playSound(name: 'magic' | 'chime' | 'cha-ching' | 'bright-harmony') { + public playSound(name: 'magic' | 'chime' | 'cha-ching' | 'bright-harmony' | 'wind-chimes-harp-ascend' | 'ascend-chime-cartoon') { if (this.isPlaying || !this.audio) { return; } diff --git a/frontend/src/app/services/cache.service.ts b/frontend/src/app/services/cache.service.ts index 8c90dc210..993fcdfc6 100644 --- a/frontend/src/app/services/cache.service.ts +++ b/frontend/src/app/services/cache.service.ts @@ -40,6 +40,7 @@ export class CacheService { this.stateService.networkChanged$.subscribe((network) => { this.network = network; this.resetBlockCache(); + this.txCache = {}; }); } diff --git a/frontend/src/app/services/electrs-api.service.ts b/frontend/src/app/services/electrs-api.service.ts index d63d49f68..eaa1ab52d 100644 --- a/frontend/src/app/services/electrs-api.service.ts +++ b/frontend/src/app/services/electrs-api.service.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; -import { Observable, from, of, switchMap } from 'rxjs'; +import { BehaviorSubject, Observable, catchError, filter, from, of, shareReplay, switchMap, take, tap } from 'rxjs'; import { Transaction, Address, Outspend, Recent, Asset, ScriptHash } from '../interfaces/electrs.interface'; import { StateService } from './state.service'; import { BlockExtended } from '../interfaces/node-api.interface'; @@ -13,6 +13,8 @@ export class ElectrsApiService { private apiBaseUrl: string; // base URL is protocol, hostname, and port private apiBasePath: string; // network path is /testnet, etc. or '' for mainnet + private requestCache = new Map, expiry: number }>; + constructor( private httpClient: HttpClient, private stateService: StateService, @@ -30,6 +32,46 @@ export class ElectrsApiService { }); } + private generateCacheKey(functionName: string, params: any[]): string { + return functionName + JSON.stringify(params); + } + + // delete expired cache entries + private cleanExpiredCache(): void { + this.requestCache.forEach((value, key) => { + if (value.expiry < Date.now()) { + this.requestCache.delete(key); + } + }); + } + + cachedRequest Observable>( + apiFunction: F, + expireAfter: number, // in ms + ...params: Parameters + ): Observable { + this.cleanExpiredCache(); + + const cacheKey = this.generateCacheKey(apiFunction.name, params); + if (!this.requestCache.has(cacheKey)) { + const subject = new BehaviorSubject(null); + this.requestCache.set(cacheKey, { subject, expiry: Date.now() + expireAfter }); + + apiFunction.bind(this)(...params).pipe( + tap(data => { + subject.next(data as T); + }), + catchError((error) => { + subject.error(error); + return of(null); + }), + shareReplay(1), + ).subscribe(); + } + + return this.requestCache.get(cacheKey).subject.asObservable().pipe(filter(val => val !== null), take(1)); + } + getBlock$(hash: string): Observable { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/block/' + hash); } @@ -54,6 +96,12 @@ export class ElectrsApiService { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/tx/' + hash + '/outspends'); } + getOutspendsBatched$(txids: string[]): Observable { + let params = new HttpParams(); + params = params.append('txids', txids.join(',')); + return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/txs/outspends', { params }); + } + getBlockTransactions$(hash: string, index: number = 0): Observable { return this.httpClient.get(this.apiBaseUrl + this.apiBasePath + '/api/block/' + hash + '/txs/' + index); } diff --git a/frontend/src/app/services/enterprise.service.ts b/frontend/src/app/services/enterprise.service.ts index bc80f337d..d1e3624f9 100644 --- a/frontend/src/app/services/enterprise.service.ts +++ b/frontend/src/app/services/enterprise.service.ts @@ -3,6 +3,7 @@ import { Inject, Injectable } from '@angular/core'; import { ApiService } from './api.service'; import { SeoService } from './seo.service'; import { StateService } from './state.service'; +import { ActivatedRoute } from '@angular/router'; @Injectable({ providedIn: 'root' @@ -11,12 +12,15 @@ export class EnterpriseService { exclusiveHostName = '.mempool.space'; subdomain: string | null = null; info: object = {}; + statsUrl: string; + siteId: number; constructor( @Inject(DOCUMENT) private document: Document, private apiService: ApiService, private seoService: SeoService, private stateService: StateService, + private activatedRoute: ActivatedRoute, ) { const subdomain = this.document.location.hostname.indexOf(this.exclusiveHostName) > -1 && this.document.location.hostname.split(this.exclusiveHostName)[0] || false; @@ -56,7 +60,7 @@ export class EnterpriseService { insertMatomo(siteId?: number): void { let statsUrl = '//stats.mempool.space/'; - + if (!siteId) { switch (this.document.location.hostname) { case 'mempool.space': @@ -88,16 +92,71 @@ export class EnterpriseService { } } + this.statsUrl = statsUrl; + this.siteId = siteId; + // @ts-ignore - const _paq = window._paq = window._paq || []; - _paq.push(['disableCookies']); - _paq.push(['trackPageView']); - _paq.push(['enableLinkTracking']); - (function() { - _paq.push(['setTrackerUrl', statsUrl+'m.php']); - _paq.push(['setSiteId', siteId.toString()]); - const d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; - g.type='text/javascript'; g.async=true; g.src=statsUrl+'m.js'; s.parentNode.insertBefore(g,s); - })(); + if (window._paq && window['Matomo']) { + window['Matomo'].addTracker(statsUrl+'m.php', siteId.toString()); + const matomo = this.getMatomo(); + matomo.setDocumentTitle(this.seoService.getTitle()); + matomo.setCustomUrl(this.getCustomUrl()); + matomo.disableCookies(); + matomo.trackPageView(); + matomo.enableLinkTracking(); + } else { + // @ts-ignore + const alreadyInitialized = !!window._paq; + // @ts-ignore + const _paq = window._paq = window._paq || []; + _paq.push(['setDocumentTitle', this.seoService.getTitle()]); + _paq.push(['setCustomUrl', this.getCustomUrl()]); + _paq.push(['disableCookies']); + _paq.push(['trackPageView']); + _paq.push(['enableLinkTracking']); + if (alreadyInitialized) { + _paq.push(['addTracker', statsUrl+'m.php', siteId.toString()]); + } else { + (function() { + _paq.push(['setTrackerUrl', statsUrl+'m.php']); + _paq.push(['setSiteId', siteId.toString()]); + const d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + // @ts-ignore + g.type='text/javascript'; g.async=true; g.src=statsUrl+'m.js'; s.parentNode.insertBefore(g,s); + })(); + } + } + } + + private getMatomo() { + if (this.siteId != null) { + return window['Matomo']?.getTracker(this.statsUrl+'m.php', this.siteId); + } + } + + goal(id: number) { + // @ts-ignore + this.getMatomo()?.trackGoal(id); + } + + page() { + const matomo = this.getMatomo(); + if (matomo) { + matomo.setCustomUrl(this.getCustomUrl()); + matomo.trackPageView(); + } + } + + private getCustomUrl(): string { + let url = window.location.origin + '/'; + let route = this.activatedRoute; + while (route) { + const segment = route?.routeConfig?.path; + if (segment && segment.length) { + url += segment + '/'; + } + route = route.firstChild; + } + return url; } } diff --git a/frontend/src/app/services/seo.service.ts b/frontend/src/app/services/seo.service.ts index 2584cbaed..7830690ff 100644 --- a/frontend/src/app/services/seo.service.ts +++ b/frontend/src/app/services/seo.service.ts @@ -10,7 +10,9 @@ import { StateService } from './state.service'; export class SeoService { network = ''; baseTitle = 'mempool'; - baseDescription = 'Explore the full Bitcoin ecosystem with The Mempool Open Project™.'; + baseDescription = 'Explore the full Bitcoin ecosystem® with The Mempool Open Source Project®.'; + + canonicalLink: HTMLElement = document.getElementById('canonical'); constructor( private titleService: Title, @@ -65,6 +67,16 @@ export class SeoService { this.metaService.updateTag({ property: 'og:description', content: this.getDescription()}); } + updateCanonical(path) { + let domain = 'mempool.space'; + if (this.stateService.env.BASE_MODULE === 'liquid') { + domain = 'liquid.network'; + } else if (this.stateService.env.BASE_MODULE === 'bisq') { + domain = 'bisq.markets'; + } + this.canonicalLink.setAttribute('href', 'https://' + domain + path); + } + getTitle(): string { if (this.network === 'testnet') return this.baseTitle + ' - Bitcoin Testnet'; diff --git a/frontend/src/app/services/services-api.service.ts b/frontend/src/app/services/services-api.service.ts new file mode 100644 index 000000000..f41c5b42c --- /dev/null +++ b/frontend/src/app/services/services-api.service.ts @@ -0,0 +1,163 @@ +import { Router, NavigationStart } from '@angular/router'; +import { Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { StateService } from './state.service'; +import { StorageService } from './storage.service'; +import { MenuGroup } from '../interfaces/services.interface'; +import { Observable, of, ReplaySubject, tap, catchError, share, filter, switchMap } from 'rxjs'; +import { IBackendInfo } from '../interfaces/websocket.interface'; +import { Acceleration, AccelerationHistoryParams } from '../interfaces/node-api.interface'; +import { AccelerationStats } from '../components/acceleration/acceleration-stats/acceleration-stats.component'; + +export type ProductType = 'enterprise' | 'community' | 'mining_pool' | 'custom'; +export interface IUser { + username: string; + email: string | null; + passwordIsSet: boolean; + snsId: string; + type: ProductType; + subscription_tag: string; + status: 'pending' | 'verified' | 'disabled'; + features: string | null; + fullName: string | null; + countryCode: string | null; + imageMd5: string; + ogRank: number | null; +} + +// Todo - move to config.json +const SERVICES_API_PREFIX = `/api/v1/services`; + +@Injectable({ + providedIn: 'root' +}) +export class ServicesApiServices { + apiBaseUrl: string; // base URL is protocol, hostname, and port + apiBasePath: string; // network path is /testnet, etc. or '' for mainnet + + userSubject$ = new ReplaySubject(1); + currentAuth = null; + + constructor( + private httpClient: HttpClient, + private stateService: StateService, + private storageService: StorageService, + private router: Router, + ) { + this.currentAuth = localStorage.getItem('auth'); + + this.apiBaseUrl = ''; // use relative URL by default + if (!stateService.isBrowser) { // except when inside AU SSR process + this.apiBaseUrl = this.stateService.env.NGINX_PROTOCOL + '://' + this.stateService.env.NGINX_HOSTNAME + ':' + this.stateService.env.NGINX_PORT; + } + this.apiBasePath = ''; // assume mainnet by default + this.stateService.networkChanged$.subscribe((network) => { + if (network === 'bisq' && !this.stateService.env.BISQ_SEPARATE_BACKEND) { + network = ''; + } + this.apiBasePath = network ? '/' + network : ''; + }); + + if (this.stateService.env.GIT_COMMIT_HASH_MEMPOOL_SPACE) { + this.getServicesBackendInfo$().subscribe(version => { + this.stateService.servicesBackendInfo$.next(version); + }) + } + + this.getUserInfo$().subscribe(); + this.router.events.pipe( + filter((event) => event instanceof NavigationStart && this.currentAuth !== localStorage.getItem('auth')), + switchMap(() => this.getUserInfo$()), + ).subscribe(); + } + + /** + * Do not call directly, userSubject$ instead + */ + private getUserInfo$() { + return this.getUserInfoApi$().pipe( + tap((user) => { + this.userSubject$.next(user); + }), + catchError((e) => { + if (e.error === 'User does not exists') { + this.userSubject$.next(null); + this.logout$().subscribe(); + return of(null); + } + this.userSubject$.next(null); + return of(null); + }), + share(), + ) + } + + /** + * Do not call directly, userSubject$ instead + */ + private getUserInfoApi$(): Observable { + const auth = this.storageService.getAuth(); + if (!auth) { + return of(null); + } + + return this.httpClient.get(`${SERVICES_API_PREFIX}/account`); + } + + getNodeOwner$(publicKey: string): Observable { + let params = new HttpParams() + .set('node_public_key', publicKey); + return this.httpClient.get(`${SERVICES_API_PREFIX}/lightning/claim/current`, { params, observe: 'response' }); + } + + getUserMenuGroups$(): Observable { + const auth = this.storageService.getAuth(); + if (!auth) { + return of(null); + } + + return this.httpClient.get(`${SERVICES_API_PREFIX}/account/menu`); + } + + logout$(): Observable { + const auth = this.storageService.getAuth(); + if (!auth) { + return of(null); + } + + localStorage.removeItem('auth'); + return this.httpClient.post(`${SERVICES_API_PREFIX}/auth/logout`, {}); + } + + getServicesBackendInfo$(): Observable { + return this.httpClient.get(`${SERVICES_API_PREFIX}/version`); + } + + estimate$(txInput: string) { + return this.httpClient.post(`${SERVICES_API_PREFIX}/accelerator/estimate`, { txInput: txInput }, { observe: 'response' }); + } + + accelerate$(txInput: string, userBid: number) { + return this.httpClient.post(`${SERVICES_API_PREFIX}/accelerator/accelerate`, { txInput: txInput, userBid: userBid }); + } + + getAccelerations$(): Observable { + return this.httpClient.get(`${SERVICES_API_PREFIX}/accelerator/accelerations`); + } + + getAggregatedAccelerationHistory$(params: AccelerationHistoryParams): Observable { + return this.httpClient.get(`${SERVICES_API_PREFIX}/accelerator/accelerations/history/aggregated`, { params: { ...params } }); + } + + getAccelerationHistory$(params: AccelerationHistoryParams): Observable { + return this.httpClient.get(`${SERVICES_API_PREFIX}/accelerator/accelerations/history`, { params: { ...params } }); + } + + getAccelerationHistoryObserveResponse$(params: AccelerationHistoryParams): Observable { + return this.httpClient.get(`${SERVICES_API_PREFIX}/accelerator/accelerations/history`, { params: { ...params }, observe: 'response'}); + } + + getAccelerationStats$(): Observable { + return this.httpClient.get(`${SERVICES_API_PREFIX}/accelerator/accelerations/stats`); + } +} diff --git a/frontend/src/app/services/state.service.ts b/frontend/src/app/services/state.service.ts index 878edf359..83cd449c8 100644 --- a/frontend/src/app/services/state.service.ts +++ b/frontend/src/app/services/state.service.ts @@ -1,14 +1,14 @@ import { Inject, Injectable, PLATFORM_ID, LOCALE_ID } from '@angular/core'; import { ReplaySubject, BehaviorSubject, Subject, fromEvent, Observable, merge } from 'rxjs'; import { Transaction } from '../interfaces/electrs.interface'; -import { IBackendInfo, MempoolBlock, MempoolBlockDelta, MempoolInfo, Recommendedfees, ReplacedTransaction, ReplacementInfo, TransactionStripped } from '../interfaces/websocket.interface'; +import { HealthCheckHost, IBackendInfo, MempoolBlock, MempoolBlockDelta, MempoolInfo, Recommendedfees, ReplacedTransaction, ReplacementInfo, TransactionStripped } from '../interfaces/websocket.interface'; import { BlockExtended, CpfpInfo, DifficultyAdjustment, MempoolPosition, OptimizedMempoolStats, RbfTree } from '../interfaces/node-api.interface'; import { Router, NavigationStart } from '@angular/router'; import { isPlatformBrowser } from '@angular/common'; import { filter, map, scan, shareReplay } from 'rxjs/operators'; import { StorageService } from './storage.service'; import { hasTouchScreen } from '../shared/pipes/bytes-pipe/utils'; -import { ApiService } from './api.service'; +import { ActiveFilter } from '../shared/filters.utils'; export interface MarkBlockState { blockHeight?: number; @@ -117,6 +117,7 @@ export class StateService { difficultyAdjustment$ = new ReplaySubject(1); mempoolTransactions$ = new Subject(); mempoolTxPosition$ = new Subject<{ txid: string, position: MempoolPosition, cpfp: CpfpInfo | null}>(); + mempoolRemovedTransactions$ = new Subject(); blockTransactions$ = new Subject(); isLoadingWebSocket$ = new ReplaySubject(1); isLoadingMempool$ = new BehaviorSubject(true); @@ -127,6 +128,7 @@ export class StateService { loadingIndicators$ = new ReplaySubject(1); recommendedFees$ = new ReplaySubject(1); chainTip$ = new ReplaySubject(-1); + serverHealth$ = new Subject(); live2Chart$ = new Subject(); @@ -149,6 +151,8 @@ export class StateService { searchFocus$: Subject = new Subject(); menuOpen$: BehaviorSubject = new BehaviorSubject(false); + activeGoggles$: BehaviorSubject = new BehaviorSubject({ mode: 'and', filters: [] }); + constructor( @Inject(PLATFORM_ID) private platformId: any, @Inject(LOCALE_ID) private locale: string, diff --git a/frontend/src/app/services/websocket.service.ts b/frontend/src/app/services/websocket.service.ts index af2a15e8c..f4dcc4037 100644 --- a/frontend/src/app/services/websocket.service.ts +++ b/frontend/src/app/services/websocket.service.ts @@ -8,6 +8,7 @@ import { ApiService } from './api.service'; import { take } from 'rxjs/operators'; import { TransferState, makeStateKey } from '@angular/platform-browser'; import { CacheService } from './cache.service'; +import { uncompressDeltaChange, uncompressTx } from '../shared/common.utils'; const OFFLINE_RETRY_AFTER_MS = 2000; const OFFLINE_PING_CHECK_AFTER_MS = 30000; @@ -76,17 +77,22 @@ export class WebsocketService { this.stateService.resetChainTip(); - this.websocketSubject.complete(); - this.subscription.unsubscribe(); - this.websocketSubject = webSocket( - this.webSocketUrl.replace('{network}', this.network ? '/' + this.network : '') - ); - - this.startSubscription(); + this.reconnectWebsocket(); }); } } + reconnectWebsocket(retrying = false, hasInitData = false) { + console.log('reconnecting websocket'); + this.websocketSubject.complete(); + this.subscription.unsubscribe(); + this.websocketSubject = webSocket( + this.webSocketUrl.replace('{network}', this.network ? '/' + this.network : '') + ); + + this.startSubscription(retrying, hasInitData); + } + startSubscription(retrying = false, hasInitData = false) { if (!hasInitData) { this.stateService.isLoadingWebSocket$.next(true); @@ -178,14 +184,18 @@ export class WebsocketService { } startTrackMempoolBlock(block: number) { - this.websocketSubject.next({ 'track-mempool-block': block }); - this.isTrackingMempoolBlock = true - this.trackingMempoolBlock = block + // skip duplicate tracking requests + if (this.trackingMempoolBlock !== block) { + this.websocketSubject.next({ 'track-mempool-block': block }); + this.isTrackingMempoolBlock = true; + this.trackingMempoolBlock = block; + } } stopTrackMempoolBlock() { this.websocketSubject.next({ 'track-mempool-block': -1 }); - this.isTrackingMempoolBlock = false + this.isTrackingMempoolBlock = false; + this.trackingMempoolBlock = null; } startTrackRbf(mode: 'all' | 'fullRbf') { @@ -237,7 +247,7 @@ export class WebsocketService { this.goneOffline = true; this.stateService.connectionState$.next(0); window.setTimeout(() => { - this.startSubscription(true); + this.reconnectWebsocket(true); }, retryDelay); } @@ -358,6 +368,12 @@ export class WebsocketService { }); } + if (response['address-removed-transactions']) { + response['address-removed-transactions'].forEach((addressTransaction: Transaction) => { + this.stateService.mempoolRemovedTransactions$.next(addressTransaction); + }); + } + if (response['block-transactions']) { response['block-transactions'].forEach((addressTransaction: Transaction) => { this.stateService.blockTransactions$.next(addressTransaction); @@ -367,9 +383,9 @@ export class WebsocketService { if (response['projected-block-transactions']) { if (response['projected-block-transactions'].index == this.trackingMempoolBlock) { if (response['projected-block-transactions'].blockTransactions) { - this.stateService.mempoolBlockTransactions$.next(response['projected-block-transactions'].blockTransactions); + this.stateService.mempoolBlockTransactions$.next(response['projected-block-transactions'].blockTransactions.map(uncompressTx)); } else if (response['projected-block-transactions'].delta) { - this.stateService.mempoolBlockDelta$.next(response['projected-block-transactions'].delta); + this.stateService.mempoolBlockDelta$.next(uncompressDeltaChange(response['projected-block-transactions'].delta)); } } } @@ -399,6 +415,10 @@ export class WebsocketService { this.stateService.previousRetarget$.next(response.previousRetarget); } + if (response['tomahawk']) { + this.stateService.serverHealth$.next(response['tomahawk']); + } + if (response['git-commit']) { this.stateService.backendInfo$.next(response['git-commit']); } diff --git a/frontend/src/app/shared/common.utils.ts b/frontend/src/app/shared/common.utils.ts index a04fa1663..18a330fab 100644 --- a/frontend/src/app/shared/common.utils.ts +++ b/frontend/src/app/shared/common.utils.ts @@ -1,3 +1,5 @@ +import { MempoolBlockDelta, MempoolBlockDeltaCompressed, MempoolDeltaChange, TransactionCompressed, TransactionStripped } from "../interfaces/websocket.interface"; + export function isMobile(): boolean { return (window.innerWidth <= 767.98); } @@ -152,4 +154,29 @@ export function seoDescriptionNetwork(network: string): string { return ' ' + network.charAt(0).toUpperCase() + network.slice(1); } return ''; +} + +export function uncompressTx(tx: TransactionCompressed): TransactionStripped { + return { + txid: tx[0], + fee: tx[1], + vsize: tx[2], + value: tx[3], + rate: tx[4], + flags: tx[5], + acc: !!tx[6], + }; +} + +export function uncompressDeltaChange(delta: MempoolBlockDeltaCompressed): MempoolBlockDelta { + return { + added: delta.added.map(uncompressTx), + removed: delta.removed, + changed: delta.changed.map(tx => ({ + txid: tx[0], + rate: tx[1], + flags: tx[2], + acc: !!tx[3], + })) + }; } \ No newline at end of file diff --git a/frontend/src/app/shared/components/btc/btc.component.html b/frontend/src/app/shared/components/btc/btc.component.html new file mode 100644 index 000000000..c13a8ff31 --- /dev/null +++ b/frontend/src/app/shared/components/btc/btc.component.html @@ -0,0 +1,8 @@ +{{ valueOverride }} +‎{{ addPlus && satoshis >= 0 ? '+' : '' }}{{ value | number }} + + L- + tL- + t- + s-{{ unit }} + \ No newline at end of file diff --git a/frontend/src/app/shared/components/btc/btc.component.scss b/frontend/src/app/shared/components/btc/btc.component.scss new file mode 100644 index 000000000..e69de29bb diff --git a/frontend/src/app/shared/components/btc/btc.component.ts b/frontend/src/app/shared/components/btc/btc.component.ts new file mode 100644 index 000000000..4e62b07ff --- /dev/null +++ b/frontend/src/app/shared/components/btc/btc.component.ts @@ -0,0 +1,44 @@ +import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; +import { Subscription } from 'rxjs'; +import { StateService } from '../../../services/state.service'; + +@Component({ + selector: 'app-btc', + templateUrl: './btc.component.html', + styleUrls: ['./btc.component.scss'] +}) +export class BtcComponent implements OnInit, OnChanges { + @Input() satoshis: number; + @Input() addPlus = false; + @Input() valueOverride: string | undefined = undefined; + + value: number; + unit: string; + + network = ''; + stateSubscription: Subscription; + + constructor( + private stateService: StateService, + ) { } + + ngOnInit() { + this.stateSubscription = this.stateService.networkChanged$.subscribe((network) => this.network = network); + } + + ngOnDestroy() { + if (this.stateSubscription) { + this.stateSubscription.unsubscribe(); + } + } + + ngOnChanges(changes: SimpleChanges): void { + if (this.satoshis >= 1_000_000) { + this.value = (this.satoshis / 100_000_000); + this.unit = 'BTC' + } else { + this.value = Math.round(this.satoshis); + this.unit = 'sats' + } + } +} diff --git a/frontend/src/app/shared/components/fee-rate/fee-rate.component.html b/frontend/src/app/shared/components/fee-rate/fee-rate.component.html index bd684369c..f9e86cc2b 100644 --- a/frontend/src/app/shared/components/fee-rate/fee-rate.component.html +++ b/frontend/src/app/shared/components/fee-rate/fee-rate.component.html @@ -1,4 +1,10 @@ - {{ fee / (weight / 4) | feeRounding:rounding }} sat/vB - {{ fee / weight | feeRounding:rounding }} sat/WU + + {{ fee / (weight / 4) | feeRounding:rounding }} sat/vB + {{ fee / weight | feeRounding:rounding }} sat/WU + + + - sat/vB + - sat/WU + \ No newline at end of file diff --git a/frontend/src/app/shared/components/fee-rate/fee-rate.component.ts b/frontend/src/app/shared/components/fee-rate/fee-rate.component.ts index 4d65ef0c2..b1d143e7f 100644 --- a/frontend/src/app/shared/components/fee-rate/fee-rate.component.ts +++ b/frontend/src/app/shared/components/fee-rate/fee-rate.component.ts @@ -8,7 +8,7 @@ import { StateService } from '../../../services/state.service'; styleUrls: ['./fee-rate.component.scss'] }) export class FeeRateComponent implements OnInit { - @Input() fee: number; + @Input() fee: number | undefined; @Input() weight: number = 4; @Input() rounding: string = null; @Input() showUnit: boolean = true; diff --git a/frontend/src/app/shared/components/geolocation/geolocation.component.ts b/frontend/src/app/shared/components/geolocation/geolocation.component.ts index 9cce1ea08..1a498a1b2 100644 --- a/frontend/src/app/shared/components/geolocation/geolocation.component.ts +++ b/frontend/src/app/shared/components/geolocation/geolocation.component.ts @@ -20,6 +20,11 @@ export class GeolocationComponent implements OnChanges { formattedLocation: string = ''; ngOnChanges(): void { + if (!this.data) { + this.formattedLocation = '-'; + return; + } + const city = this.data.city ? this.data.city : ''; const subdivisionLikeCity = this.data.city === this.data.subdivision; let subdivision = this.data.subdivision; diff --git a/frontend/src/app/shared/components/global-footer/global-footer.component.html b/frontend/src/app/shared/components/global-footer/global-footer.component.html index 34d47379e..271279589 100644 --- a/frontend/src/app/shared/components/global-footer/global-footer.component.html +++ b/frontend/src/app/shared/components/global-footer/global-footer.component.html @@ -7,11 +7,11 @@
    -

    +

    Explore the full Bitcoin ecosystem - + ®

    -
    - -

    +

    Explore the full Bitcoin ecosystem - + ®