Compare commits

..

2705 Commits

Author SHA1 Message Date
wiz
ead7613579 Merge pull request #4877 from mempool/nymkappa/truncate-hashrate-difficulty
[migration] re-index hashrates and difficulty_adjustments
2024-04-04 11:05:16 +09:00
wiz
ca0613ec17 Merge pull request #4876 from mempool/knorrium/change_default_replication_settings
Update default settings for Docker
2024-04-04 11:05:04 +09:00
nymkappa
727208ff84 [migration] re-index hashrates and difficulty_adjustments 2024-04-04 10:57:54 +09:00
Felipe Knorr Kuhn
53c3de2af5 Update default settings for Docker 2024-04-04 10:49:32 +09:00
softsimon
3f50d57ed1 Fix test broke due to i18n key change 2024-04-03 21:44:48 +09:00
softsimon
37cb9b0fe8 Merge pull request #4872 from mempool/natsoni/fix-fiat-selector-sorting
Sort currency by ticker in fiat selector
2024-04-03 18:57:24 +09:00
softsimon
a3b5f79094 Merge pull request #4871 from mempool/natsoni/fix-liquid-testnet
Fix Liquid testnet broken blocks
2024-04-03 18:55:55 +09:00
softsimon
1b1ffa7109 Transifex pull 04-03 2024-04-03 18:47:16 +09:00
softsimon
2b3021c8fe Merge pull request #4873 from mempool/simon/i18n-improvements-04-02
i18n corrections and merging
2024-04-03 18:18:29 +09:00
softsimon
0ccc47786d Merge pull request #4874 from mempool/knorrium/fix_docker_for_rust
Fix the Docker workflow for the new Rust steps
2024-04-03 18:17:06 +09:00
softsimon
24366b929e i18n corrections and merging 2024-04-03 18:13:42 +09:00
Felipe Knorr Kuhn
2cab2a7885 Read FD from the environment variables 2024-04-03 18:13:14 +09:00
Felipe Knorr Kuhn
4284038c4b Fix error when deleting the missing @napi-rs folder 2024-04-03 18:12:51 +09:00
Felipe Knorr Kuhn
425d158777 Update Dockerfile to work with the new Rust steps 2024-04-03 18:12:26 +09:00
Felipe Knorr Kuhn
1a11b1813f Add more build contexts for the backend and rust-gbt 2024-04-03 18:11:58 +09:00
wiz
85a86d4b06 ops: Add backend git hash check 2024-04-03 17:28:58 +09:00
natsoni
073578243c Fix fiat selector sorting 2024-04-03 16:34:56 +09:00
wiz
69578f8086 Merge pull request #4820 from mempool/nymkappa/polish-enterprise-logo
[enterprise] polish enterprise logo
2024-04-03 16:17:37 +09:00
wiz
ec92f83a58 Merge pull request #4865 from mempool/mononaut/public-acceleration-config
Public acceleration config
2024-04-03 16:16:36 +09:00
wiz
37c0adbbfa Merge pull request #4868 from mempool/natsoni/fix-global-footer
Fix footer position
2024-04-03 16:15:57 +09:00
natsoni
e9c40692a6 Fix network switch mechanism 2024-04-03 16:09:30 +09:00
softsimon
32383b0bc2 Merge pull request #4869 from mempool/knorrium/more_bisq_cleanup
Cleanup more bisq references
2024-04-03 14:01:53 +09:00
Felipe Knorr Kuhn
d2f912d15c Remove leftover Bisq references from the GH workflow 2024-04-03 12:31:41 +09:00
Felipe Knorr Kuhn
c35c08b17a Remove bisq references from the tests 2024-04-03 12:31:17 +09:00
natsoni
4efd0dda83 Push footer down when content is less than window height 2024-04-03 11:28:25 +09:00
wiz
e7f8bcf83b ops: Update check script for elements electrs hash 2024-04-02 22:24:00 +09:00
wiz
08fa6d55b5 Merge pull request #4832 from mempool/dependabot/npm_and_yarn/frontend/express-4.19.2
Bump express from 4.18.2 to 4.19.2 in /frontend
2024-04-02 22:03:05 +09:00
Felipe Knorr Kuhn
3a2aad645b Merge branch 'master' into mononaut/public-acceleration-config 2024-04-02 21:31:28 +09:00
Felipe Knorr Kuhn
2c655a08be Merge branch 'master' into dependabot/npm_and_yarn/frontend/express-4.19.2 2024-04-02 21:13:34 +09:00
softsimon
bd359fdd31 Merge pull request #4859 from mempool/nymkappa/accel-copy
[accelerator] deposit -> top up
2024-04-02 21:12:47 +09:00
Felipe Knorr Kuhn
13216687dc Merge branch 'master' into nymkappa/accel-copy 2024-04-02 21:03:41 +09:00
wiz
1bf4f9902e Merge pull request #4862 from mempool/knorrium/fix_liquid_tests
Re-enable and fix Liquid tests
2024-04-02 21:02:42 +09:00
Felipe Knorr Kuhn
9908ec01aa Merge branch 'master' into mononaut/public-acceleration-config 2024-04-02 20:53:01 +09:00
Felipe Knorr Kuhn
051533bb14 Merge branch 'master' into knorrium/fix_liquid_tests 2024-04-02 20:48:36 +09:00
Mononaut
3d900bdfe5 Enable PUBLIC_ACCELERATIONS in mainnet prod 2024-04-02 08:24:57 +00:00
Mononaut
b32cce1440 Restrict public acceleration APIs to mainnet 2024-04-02 08:23:38 +00:00
Mononaut
37aee77eb4 Add config for public acceleration data 2024-04-02 08:19:35 +00:00
softsimon
72b8ae2a55 Revert id change 2024-04-02 17:07:18 +09:00
Felipe Knorr Kuhn
3e3bed9aa4 Disable viewport tests for now 2024-04-02 16:54:02 +09:00
Felipe Knorr Kuhn
844a86f997 Merge branch 'master' into knorrium/fix_liquid_tests 2024-04-02 16:44:04 +09:00
Felipe Knorr Kuhn
468f17c76c Add a few more Liquid testnet tests 2024-04-02 16:18:52 +09:00
softsimon
68a7a89fd6 Merge pull request #4864 from mempool/simon/update-i18n-04-02
Simon/update i18n 04 02
2024-04-02 16:06:07 +09:00
softsimon
931551a17f New extract 2024-04-02 16:05:52 +09:00
softsimon
7b79384f27 Extracting i18n 2024-04-02 16:02:18 +09:00
softsimon
69568421f3 Merge pull request #4232 from mempool/hunicus/move-on-in-it
Fix mining dashboard meta description not showing
2024-04-02 15:58:07 +09:00
softsimon
7fab57193d Merge pull request #4863 from mempool/mononaut/fix-block-page
Fix block audit cache bug
2024-04-02 15:32:58 +09:00
Mononaut
49146e1402 Fix mainnet blocks loading bug 2024-04-02 06:29:43 +00:00
hunicus
f28abd68f4 Merge branch 'master' into hunicus/move-on-in-it 2024-04-02 15:26:11 +09:00
Felipe Knorr Kuhn
4bb1320563 Re-enable and fix Liquid tests 2024-04-02 15:14:02 +09:00
dependabot[bot]
0a848f25a4 Bump express from 4.18.2 to 4.19.2 in /frontend
Bumps [express](https://github.com/expressjs/express) from 4.18.2 to 4.19.2.
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.18.2...4.19.2)

---
updated-dependencies:
- dependency-name: express
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-02 06:07:47 +00:00
wiz
83dbae3a70 Merge pull request #4786 from mempool/simon/remove-bisq
Removing Bisq
2024-04-02 15:06:23 +09:00
wiz
ce057bad20 ops: Bump NodeJS to v20.12.0 in start script 2024-04-02 14:58:55 +09:00
wiz
8bec0cacdb ops: Remove bisq from start script 2024-04-02 14:58:21 +09:00
wiz
faa990a2c6 ops: Remove bisq from build script 2024-04-02 14:55:52 +09:00
wiz
872e4b4a17 Merge pull request #4855 from mempool/knorrium/fix_missing_assets
Run sync-assets-dev when building
2024-04-02 14:55:03 +09:00
softsimon
3e0c36e714 Merge pull request #4854 from mempool/natsoni/fix-network-errors
Fix frontend errors on block loading
2024-04-02 14:38:26 +09:00
softsimon
974eaeb02f Merge branch 'master' into natsoni/fix-network-errors 2024-04-02 14:31:32 +09:00
softsimon
f833904d7b Merge pull request #4858 from mempool/mononaut/better-audits
Betterer audits
2024-04-02 14:30:17 +09:00
nymkappa
1bba1cfeb1 [accelerator] deposit -> top up 2024-04-02 11:35:03 +08:00
Mononaut
4a6641f544 revert reverting better audits PR 2024-04-02 02:02:38 +00:00
softsimon
c51159d275 Merge pull request #4836 from mempool/mononaut/first-seen-tooltip
Display first seen time on block visualisation tooltips
2024-04-01 22:49:46 +09:00
softsimon
d279ea3278 Merge pull request #4857 from mempool/revert-4852-mononaut/better-audits
Revert "Better audits"
2024-04-01 22:49:05 +09:00
softsimon
102cb96483 Revert "Better audits" 2024-04-01 22:48:46 +09:00
softsimon
10d4e5a600 Merge pull request #4852 from mempool/mononaut/better-audits
Better audits
2024-04-01 22:47:46 +09:00
softsimon
2048816c23 Merge pull request #4847 from mempool/dependabot/github_actions/dtolnay/rust-toolchain-dc6353516c68da0f06325f42ad880f76a5e77ec9
Bump dtolnay/rust-toolchain from be73d7920c329f220ce78e0234b8f96b7ae60248 to dc6353516c68da0f06325f42ad880f76a5e77ec9
2024-04-01 22:04:15 +09:00
Felipe Knorr Kuhn
8d2efd4d10 Merge branch 'master' into dependabot/github_actions/dtolnay/rust-toolchain-dc6353516c68da0f06325f42ad880f76a5e77ec9 2024-04-01 21:59:31 +09:00
softsimon
ecf1db0716 Merge pull request #4848 from mempool/mononaut/esplora-only-address-graph
Add backend type flag, disable address graphs for non-esplora
2024-04-01 19:11:54 +09:00
softsimon
1a3b8580e7 Merge branch 'master' into mononaut/esplora-only-address-graph 2024-04-01 19:10:18 +09:00
Felipe Knorr Kuhn
7063d9e113 Merge branch 'master' into knorrium/fix_missing_assets 2024-04-01 19:04:06 +09:00
Felipe Knorr Kuhn
0445c150a2 Run sync-assets-dev when building 2024-04-01 19:01:08 +09:00
wiz
cfb1e1d908 ops: Remove nginx config for bisq 2024-04-01 19:00:37 +09:00
natsoni
3f80dbc5ce Fix random console errors on block loading 2024-04-01 18:53:50 +09:00
softsimon
0090d36514 Merge branch 'master' into simon/remove-bisq 2024-04-01 18:52:56 +09:00
softsimon
bf22f4515f Merge branch 'master' into mononaut/first-seen-tooltip 2024-04-01 18:44:52 +09:00
wiz
bf5d5b98cb ops: Update check script for config.js URL 2024-04-01 18:44:41 +09:00
softsimon
df491d050d Merge pull request #4851 from mempool/knorrium/docker_node_bump
Bump Docker images to node v20.12.0 LTS
2024-04-01 18:40:14 +09:00
softsimon
91267201bf Merge pull request #4853 from mempool/natsoni/fix-liquid-peg-crash
Fix Liquid crash
2024-04-01 18:30:33 +09:00
natsoni
061abaa148 Fix Liquid crash 2024-04-01 18:21:43 +09:00
wiz
4132765027 Merge pull request #4819 from mempool/simon/angular-17
Angular 17
2024-04-01 18:14:17 +09:00
wiz
e64d1be6f0 Merge branch 'master' into simon/angular-17 2024-04-01 17:48:55 +09:00
Mononaut
03255dd077 Improve marginal fee rate detection 2024-04-01 08:42:23 +00:00
Mononaut
bd4e223aed Add "prioritized" category to audits 2024-04-01 08:07:09 +00:00
wiz
964be2a6df Don't use PATH in sync-assets.js 2024-04-01 16:53:49 +09:00
softsimon
cf00fa73c6 Correcting esbuild target and module 2024-04-01 16:16:40 +09:00
Felipe Knorr Kuhn
8956ef4b43 Bump Docker images to node v20.12.0 LTS 2024-04-01 16:14:26 +09:00
softsimon
5c3f256229 Bumping TS build target 2024-04-01 16:11:08 +09:00
wiz
56b9715fc5 ops: Upgrade NodeJS to v20.12 for Debian in prod installer 2024-04-01 16:05:31 +09:00
wiz
e3f7f08fb4 ops: Follow redirects to download AppleColorEmoji.ttf 2024-04-01 16:01:16 +09:00
wiz
cc63f20708 ops: Upgrade NodeJS to v20.12.0 in prod installer 2024-04-01 16:01:13 +09:00
Mononaut
93956d0ed4 Refactor first seen tooltip labels 2024-04-01 07:00:46 +00:00
softsimon
4a3aceadbf Merge pull request #4849 from mempool/mononaut/backend-backend-info
Add backend mode to backend-info
2024-04-01 15:27:38 +09:00
Mononaut
9b456954b1 Change "first seen ... before" to "confirmed ... after" 2024-04-01 06:21:01 +00:00
Mononaut
855b20834e Display first seen time on block visualiation tooltips 2024-04-01 06:21:01 +00:00
Mononaut
df72829fd2 Add backend mode to backend-info 2024-04-01 04:00:29 +00:00
Mononaut
855e25ccd2 Add backend type flag, disable address graphs for non-esplora 2024-04-01 03:49:56 +00:00
dependabot[bot]
150a7d9eeb Bump dtolnay/rust-toolchain
Bumps [dtolnay/rust-toolchain](https://github.com/dtolnay/rust-toolchain) from be73d7920c329f220ce78e0234b8f96b7ae60248 to dc6353516c68da0f06325f42ad880f76a5e77ec9.
- [Release notes](https://github.com/dtolnay/rust-toolchain/releases)
- [Commits](be73d7920c...dc6353516c)

---
updated-dependencies:
- dependency-name: dtolnay/rust-toolchain
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-01 02:45:31 +00:00
softsimon
1630d71e7b Merge pull request #4840 from mempool/mononaut/multi-tx-tracking
Add track-txs websocket subscription
2024-03-31 18:51:00 +09:00
Mononaut
7deee5d5f2 Fix outspend tracking typo 2024-03-31 09:45:26 +00:00
softsimon
19dcc9d62d Merge pull request #4842 from mempool/mononaut/halving-widget-fixes
Fix next block subsidy calculation
2024-03-31 18:04:57 +09:00
Mononaut
9270298374 Fix next block subsidy calculation 2024-03-31 08:53:09 +00:00
softsimon
1c862d57ea Merge pull request #4841 from mempool/mononaut/fix-always-dirty
Clear cpfp dirty status
2024-03-31 17:16:36 +09:00
Mononaut
ac8fdd6405 Clear cpfp dirty status 2024-03-31 08:06:01 +00:00
Mononaut
c5300c950b Add track-txs websocket subscription 2024-03-31 07:55:43 +00:00
softsimon
92b9c8f370 Merge pull request #4838 from mempool/mononaut/stop-excluding-accelerations
Don't exclude accelerated txs from fee graph & fee statistics
2024-03-31 16:09:37 +09:00
softsimon
7969d069b2 Merge pull request #4835 from mempool/natsoni/add-data-lightning-world-graph
Add node data to lightning world channels graph
2024-03-31 16:05:58 +09:00
Mononaut
7367991df1 Don't exclude accelerated txs from fee graph & fee statistics 2024-03-31 05:40:51 +00:00
softsimon
8f19a376fa Merge pull request #4826 from mempool/mononaut/standardized-grid
Standardize the block visualization grid
2024-03-31 12:39:16 +09:00
softsimon
0b1296330b Merge pull request #4817 from mempool/natsoni/fix-unnecessary-block-load
Fix unnecessary request of blocks on dashboard load
2024-03-31 12:37:02 +09:00
softsimon
6bebc76633 Fix websocket init test support 2024-03-31 12:26:13 +09:00
natsoni
6b8f08c6d7 Add node data to lightning world channels graph 2024-03-29 21:57:11 +09:00
softsimon
ba8d4ccc02 Merge pull request #4555 from mempool/mononaut/limit-gbt-input-redux
Limited GBT
2024-03-29 21:26:33 +09:00
softsimon
e9fe50a4bb Merge pull request #4830 from mempool/dependabot/npm_and_yarn/unfurler/express-4.19.2
Bump express from 4.18.1 to 4.19.2 in /unfurler
2024-03-29 20:23:11 +09:00
softsimon
52a33d5a51 Merge pull request #4829 from mempool/natsoni/allow-show-block-fees-only
Add an option to always show the block fees on infinite blockchain
2024-03-29 17:04:11 +09:00
softsimon
66309813d5 Changing to async pipe 2024-03-29 16:30:55 +09:00
softsimon
5a57d220cb Merge pull request #4834 from mempool/mononaut/fix-audit-tx-row
hide empty audit row in tx page details panel
2024-03-29 16:19:36 +09:00
Mononaut
cbcb61d3fa hide empty audit row in tx page details panel 2024-03-29 06:51:56 +00:00
softsimon
3d0e16857a Merge pull request #4833 from mempool/dependabot/npm_and_yarn/backend/express-4.19.2
Bump express from 4.18.2 to 4.19.2 in /backend
2024-03-29 15:40:11 +09:00
Mononaut
3732406ce8 Sanity checks for mempool visualization deltas 2024-03-29 03:52:21 +00:00
Mononaut
8f2e1de578 Limit GBT: fix on-demand CPFP calculation 2024-03-29 03:52:18 +00:00
Mononaut
07c76d084e Limit GBT: handle accelerations beneath the purge rate 2024-03-29 03:51:48 +00:00
Mononaut
5411eb491f Limit GBT: fix candidate set inconsistency 2024-03-29 03:51:48 +00:00
Mononaut
b10bd05207 Move max cpfp graph size to named const 2024-03-29 03:51:47 +00:00
Mononaut
0533953f54 Add LIMIT_GBT config 2024-03-29 03:51:47 +00:00
Mononaut
b3e07e0c22 Retire "getSimonTemplate" GBT option 2024-03-29 03:51:46 +00:00
Mononaut
62653086e9 Limit GBT - calculate purged tx cpfp on demand 2024-03-29 03:49:57 +00:00
Mononaut
e2d3bb4cc5 Use minfee node to limit gbt input size 2024-03-29 03:49:54 +00:00
dependabot[bot]
70bf31c397 Bump express from 4.18.2 to 4.19.2 in /backend
Bumps [express](https://github.com/expressjs/express) from 4.18.2 to 4.19.2.
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.18.2...4.19.2)

---
updated-dependencies:
- dependency-name: express
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-28 17:18:10 +00:00
natsoni
22d9a1cb8b Keep block fees on infinite blockchain when leaving mining dashboard 2024-03-28 16:58:00 +09:00
Felipe Knorr Kuhn
6492aa6f4a Merge branch 'master' into simon/angular-17 2024-03-28 16:46:43 +09:00
dependabot[bot]
c0a9a8b07a Bump express from 4.18.1 to 4.19.2 in /unfurler
Bumps [express](https://github.com/expressjs/express) from 4.18.1 to 4.19.2.
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/master/History.md)
- [Commits](https://github.com/expressjs/express/compare/4.18.1...4.19.2)

---
updated-dependencies:
- dependency-name: express
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-28 07:42:18 +00:00
softsimon
5c430e57a4 Merge pull request #4828 from mempool/natsoni/fix-blockchain-doc
Fix truncated blockchain in FAQ
2024-03-28 14:40:20 +09:00
softsimon
27b48b1874 Updating eslib build target 2024-03-28 12:24:31 +09:00
softsimon
33cddc6fba Moving esbuild to dependency 2024-03-28 12:17:16 +09:00
natsoni
1e5b798af9 Fix for #4827 2024-03-27 19:00:24 +09:00
natsoni
f91fc6f026 Fix truncated blockchain in faq 2024-03-27 18:47:10 +09:00
Mononaut
82e115c009 Standardize the block visualization grid 2024-03-27 02:46:29 +00:00
softsimon
44cf63458f Correct sample mempool services api url 2024-03-26 18:54:31 +09:00
softsimon
53aea3dcf6 Fix eslint errors 2024-03-26 18:13:02 +09:00
softsimon
7408a6f331 Add esbuild as dev dependency 2024-03-26 18:04:20 +09:00
softsimon
6e62e93bf6 Updating eslint 2024-03-26 17:51:54 +09:00
softsimon
8861aedea1 Merge pull request #4824 from mempool/natsoni/fix-hashrate-graph-scale
Set coherent units for hashrate and difficulty units on hashrate graph
2024-03-26 17:37:16 +09:00
softsimon
16f9593d2e Merge pull request #4814 from mempool/natsoni/hide-featured-assets-testnet
Hide featured assets on Liquid testnet
2024-03-26 17:10:36 +09:00
softsimon
5537e79640 Merge branch 'master' into natsoni/hide-featured-assets-testnet 2024-03-26 17:07:36 +09:00
softsimon
1ea66595ea Merge pull request #4822 from mempool/natsoni/add-pool-dominance-to-graph
Add pool dominance data to mining pool page
2024-03-26 17:01:40 +09:00
natsoni
fa2dd3c7cb Set coherent units for hashrate and difficulty units on hashrate graph 2024-03-26 16:57:00 +09:00
softsimon
1e04afffa3 Update package.lock 2024-03-26 15:42:56 +09:00
softsimon
57cbf71915 Merge pull request #4821 from mempool/mononaut/accelerated-badge-fixes
Accelerated badge fixes
2024-03-26 14:46:52 +09:00
softsimon
78b1b1e561 Merge pull request #4823 from mempool/nymkappa/aggregated-acceleration-history-rounding
[accelerator] fix rounding issue
2024-03-26 14:40:37 +09:00
nymkappa
6fb2a3b39c [accelerator] fix rounding issue 2024-03-26 14:38:57 +09:00
natsoni
cb866d8fa2 Add pool dominance data to mining pool page 2024-03-26 14:11:08 +09:00
softsimon
365c89d98f Merge pull request #4818 from mempool/mononaut/halving-widget
Add halving countdown widget to main dashboard
2024-03-26 13:22:01 +09:00
nymkappa
f4b9301f55 [enterprise] polish enterprise logo 2024-03-26 11:36:20 +09:00
Mononaut
6afe12c1be Fix duplicate accelerated badge on transaction page 2024-03-26 02:33:51 +00:00
Mononaut
952a61f8f2 Fix accelerated badge in block overview tooltip 2024-03-26 02:33:33 +00:00
softsimon
0825c7a6d6 Fixing SSR 2024-03-25 18:33:58 +09:00
Mononaut
0ece8bb2a6 Add halving countdown widget to main dashboard 2024-03-25 08:32:50 +00:00
natsoni
8822c0972f Fix unnecessary request of blocks on dashboard load 2024-03-25 12:07:33 +09:00
softsimon
6310ef7f57 Upgrade to Angular 17 2024-03-24 16:22:05 +09:00
natsoni
d4749cfc82 Hide featured assets on liquid testnet 2024-03-24 15:41:18 +09:00
softsimon
60996a99f0 Removing Bisq 2024-03-23 18:03:49 +09:00
softsimon
1b21cd89a3 Merge pull request #4805 from mempool/mononaut/http-error-handling
http error handling
2024-03-23 18:03:24 +09:00
Mononaut
13fb75fec3 Extend http interceptor to normalize errors 2024-03-23 07:07:29 +00:00
Mononaut
484e032775 Reusable component & pipe for http error rendering 2024-03-23 07:07:24 +00:00
softsimon
21b3e4071c Merge pull request #4812 from mempool/mononaut/tx-page-tags
Add Goggles filter badges to the transaction page
2024-03-23 15:56:25 +09:00
Mononaut
48b82329cb Adjust transaction details table layout 2024-03-23 06:52:38 +00:00
Mononaut
00dcff50ee Add Goggles filters tags to the transaction page 2024-03-23 06:08:40 +00:00
wiz
abbc8a134b Merge pull request #4811 from mempool/nymkappa/hide-accel-subdomain
[accelerator] disable ui elements on subdomain
2024-03-23 14:43:18 +09:00
softsimon
4374e6e0eb Merge pull request #4810 from mempool/mononaut/tx-tags
Show goggles badges on block overview tooltip
2024-03-23 14:10:30 +09:00
softsimon
15062b80d1 Removing goggles icon 2024-03-23 14:08:43 +09:00
softsimon
b4d0b75557 Merge pull request #4321 from mempool/mononaut/ssr
Angular Universal SSR
2024-03-22 20:01:30 +09:00
Mononaut
d6f1b51fa6 Show goggles badges on block overview tooltip 2024-03-22 10:05:59 +00:00
nymkappa
0a24a9ea7c [accelerator] disable ui elements on subdomain 2024-03-22 17:51:13 +09:00
softsimon
e01df9ee32 Merge pull request #4809 from mempool/nymkappa/polish-menu
[menu] fix css
2024-03-22 17:37:08 +09:00
softsimon
3aa12c935b Merge pull request #4806 from mempool/mononaut/address-chart-navigation
Add click navigation to balance history chart
2024-03-22 15:44:53 +09:00
Mononaut
6e2f17b3d2 SSR: Fix more merge/version conflicts 2024-03-22 05:41:58 +00:00
Mononaut
50e656b259 SSR: fix merge/version conflicts 2024-03-22 05:35:22 +00:00
Mononaut
48af95d722 SSR: placeholder bowtie diagram while loading 2024-03-22 05:35:22 +00:00
Mononaut
c926088136 SSR: Fix block viz loading indicators 2024-03-22 05:35:22 +00:00
Mononaut
b167848b9b SSR: Fix initial state of lightning pages & graphs 2024-03-22 05:35:22 +00:00
Mononaut
99730d02ab SSR: fix graph loading indicators 2024-03-22 05:35:22 +00:00
Mononaut
ed73c1e94c SSR: fix clock page timeout 2024-03-22 05:35:22 +00:00
Mononaut
ab5ee5370a SSR: solve block page initial state 2024-03-22 05:35:21 +00:00
Mononaut
4fbbff6614 SSR: fix transferstate block ordering 2024-03-22 05:35:21 +00:00
Mononaut
9cd33825bf SSR: dirty hack to fix initial blockchain scroll 2024-03-22 05:35:21 +00:00
Mononaut
abd7f62b20 SSR: preserve transferstate api response headers 2024-03-22 05:35:21 +00:00
Mononaut
bcd337794a SSR: fix mining dashboard initial layout 2024-03-22 05:35:21 +00:00
Mononaut
1ae5f05316 SSR: init latest replacements on server side 2024-03-22 05:35:20 +00:00
Mononaut
c5822b11a0 SSR zone macrotask utilities, solve tx page initial state 2024-03-22 05:35:20 +00:00
Mononaut
5b4132b551 SSR: fix incoming tx graph init state 2024-03-22 05:35:20 +00:00
Mononaut
29aaeef47b Fix deprecated SSR state transfer imports 2024-03-22 05:35:20 +00:00
Mononaut
10e468d463 Fix hashrate difficulty SSR state dependency 2024-03-22 05:35:20 +00:00
Mononaut
6464f6d8bb Exclude webgl block viz from SSR rendering 2024-03-22 05:35:20 +00:00
Mononaut
cfdbd93695 Fix SSR matchMedia shim 2024-03-22 05:35:19 +00:00
Mononaut
a2b9b0c89d Exclude echarts from server-side rendering 2024-03-22 05:35:19 +00:00
Mononaut
e6fb93140c Fix default mining pool img fallback behavior 2024-03-22 05:35:19 +00:00
Mononaut
4e26e1f196 SSR ResizeObserver shim 2024-03-22 05:35:19 +00:00
Mononaut
1bb625f06b Cleaner SSR server routing 2024-03-22 05:35:19 +00:00
Mononaut
68b55db872 restore basic Angular Universal build 2024-03-22 05:35:19 +00:00
nymkappa
c47822cae7 [menu] fix css 2024-03-22 14:34:21 +09:00
softsimon
00a94f9e3c Merge pull request #4799 from mempool/natsoni/blocks-table-url-pagination
Add page number to URL in blocks table
2024-03-22 14:24:56 +09:00
natsoni
adda511869 Refactor key navigation on recent pegs table 2024-03-22 13:48:01 +09:00
softsimon
1b971bfb05 Merge pull request #4807 from mempool/nymkappa/cleanup-lightning-code
[refactor] cleanup dead code
2024-03-22 09:39:40 +09:00
nymkappa
ea94dfcd6b [refactor] cleanup dead code 2024-03-21 18:14:35 +09:00
Mononaut
3dd328475e Add click navigation to balance history chart 2024-03-21 09:02:17 +00:00
softsimon
c18779b4e3 Refactoring debounce mechanism 2024-03-21 17:58:34 +09:00
natsoni
5deb8c3149 Allow smooth key navigation in block table and pegs table 2024-03-21 16:24:16 +09:00
softsimon
78f03bd6d5 Merge pull request #4803 from mempool/mononaut/fix-address-chart-axis
Fix address chart y-axis labels
2024-03-21 15:47:50 +09:00
softsimon
5249fb1a8b Merge pull request #4790 from mempool/natsoni/account-menu-overlay
Account menu overlays UI instead of pushing it
2024-03-21 14:50:48 +09:00
softsimon
4ce0497048 Improve select truncated strings 2024-03-21 14:05:44 +09:00
natsoni
393181f753 Set absolute menu in sticky header by @mononaut 2024-03-21 13:47:28 +09:00
softsimon
7f2d77a73b Merge pull request #4793 from mempool/natsoni/fix-fiat-price-on-tesnet
Fix fiat price displayed on test networks
2024-03-21 12:08:18 +09:00
Mononaut
f8a1fc6aa2 Fix address chart y-axis labels 2024-03-21 02:56:20 +00:00
softsimon
7bf7d02a18 Merge pull request #4802 from mempool/natsoni/fix-bowtie-tooltip-bug
Fix bowtie tooltip bug
2024-03-21 11:31:18 +09:00
natsoni
7b6163cfee Fix bowtie tooltip bug 2024-03-20 21:25:00 +09:00
softsimon
19b0c4e410 Merge pull request #4792 from mempool/mononaut/address-balance-graph
Add balance graph to address page
2024-03-20 19:08:43 +09:00
Mononaut
2c16dda7c0 Address chart support p2pks 2024-03-20 10:03:19 +00:00
Mononaut
82f1fa5110 Add balance graph to address page 2024-03-20 10:03:19 +00:00
natsoni
524619f48e Add URL pagination and keyboard navigation to Liquid pegs list 2024-03-20 18:24:40 +09:00
natsoni
666165ebe9 Add key navigation support to blocks list 2024-03-20 15:10:51 +09:00
natsoni
6b9159b89c Add URL pagination to block transaction list 2024-03-20 14:08:44 +09:00
softsimon
48d852fd49 Merge pull request #4798 from mempool/simon/flex-justified-navbar
Flex justified navbar
2024-03-20 13:07:00 +09:00
natsoni
f6dbe1e17f Add page number to URL in blocks table 2024-03-20 13:02:56 +09:00
softsimon
fc5b2c050e Flex justified navbar 2024-03-19 15:12:28 +09:00
softsimon
92d960a9cc Merge pull request #4789 from mempool/hunicus/api-docs-unfurler
Add /docs/api unfurler image
2024-03-19 12:19:41 +09:00
softsimon
482493fef0 Merge pull request #4794 from mempool/natsoni/add-currency-frontend-config
Add missing ADDITIONAL_CURRENCIES flag in frontend config
2024-03-19 12:11:26 +09:00
natsoni
4e45993d41 Add missing additional currencies flag in frontend config 2024-03-19 12:07:25 +09:00
natsoni
8edd2b5802 Fix fiat price displayed on test networks 2024-03-19 11:58:50 +09:00
softsimon
e53254fb2d Merge pull request #4791 from mempool/natsoni/update-doc-historical-price
Update doc for historical price endpoint
2024-03-19 11:53:01 +09:00
nymkappa
40663c79c0 Merge branch 'master' into natsoni/account-menu-overlay 2024-03-19 09:04:07 +09:00
natsoni
cca7c7e8e2 Update doc for historical price endpoint 2024-03-18 17:41:13 +09:00
natsoni
2c6f210e8e Account menu overlays UI instead of pushing it 2024-03-18 16:49:33 +09:00
hunicus
82ba80dbb1 Add /docs/api unfurler image 2024-03-18 03:16:00 -04:00
softsimon
634b461bb5 Merge pull request #4787 from mempool/natsoni/fix-load-more-p2pk
Fix broken load more for P2PK address page
2024-03-18 15:27:39 +09:00
softsimon
f1b9a0f536 Merge pull request #4697 from mempool/dependabot/docker/docker/backend/node-20.11.1-buster-slim
Bump node from 20.8.0-buster-slim to 20.11.1-buster-slim in /docker/backend
2024-03-18 15:07:07 +09:00
softsimon
b7d9efebd1 Merge pull request #4785 from mempool/natsoni/bowtie-tooltip-price
Display more accurate price data on tx bowtie tooltip
2024-03-18 14:46:39 +09:00
softsimon
34d93abbf6 Merge pull request #4784 from mempool/simon/scss-flex-warning-fixes
Fixing scss flexbox warnings
2024-03-18 12:27:52 +09:00
softsimon
dbecb73f97 Merge pull request #4782 from mempool/nymkappa/no-block-accel-list
[accelerator] show ~ for pending accel in the block column
2024-03-18 11:47:24 +09:00
softsimon
9fa6d232d9 Merge pull request #4696 from mempool/dependabot/docker/docker/frontend/node-20.11.1-buster-slim
Bump node from 20.8.0-buster-slim to 20.11.1-buster-slim in /docker/frontend
2024-03-18 11:40:03 +09:00
softsimon
30c033b403 Merge pull request #4695 from mempool/dependabot/docker/docker/frontend/nginx-1.25.4-alpine
Bump nginx from 1.24.0-alpine to 1.25.4-alpine in /docker/frontend
2024-03-18 11:39:37 +09:00
softsimon
788d1de968 Merge pull request #4783 from mempool/mononaut/pool-acc-fees-mobile
Fix pool oob fees table mobile layout
2024-03-18 11:39:09 +09:00
natsoni
a04d685f1a Change tooltip text "ago" -> "earlier" 2024-03-17 22:23:46 +09:00
natsoni
43232b9d0a Fix broken load more for P2PK address page 2024-03-17 17:58:26 +09:00
softsimon
acd9c23180 Fixing scss flexbox warnings
fixes #4781
2024-03-17 17:08:07 +09:00
Mononaut
a8fa7dcb2a Fix pool oob fees table mobile layout 2024-03-17 08:00:51 +00:00
natsoni
2dc6f6ff5a Display more accurate price on prevout/spent outputs in bowtie tooltip 2024-03-17 16:25:36 +09:00
softsimon
df107d34b4 Fixing undefined error 2024-03-17 15:31:17 +09:00
nymkappa
2245109ae6 [accelerator] show ~ for pending accel in the block column 2024-03-17 10:12:17 +09:00
softsimon
1c76a6091a Merge pull request #4778 from mempool/dependabot/npm_and_yarn/frontend/follow-redirects-1.15.6
Bump follow-redirects from 1.15.5 to 1.15.6 in /frontend
2024-03-16 17:23:59 +07:00
softsimon
29c0131edf Merge pull request #4779 from mempool/dependabot/npm_and_yarn/backend/follow-redirects-1.15.6
Bump follow-redirects from 1.15.5 to 1.15.6 in /backend
2024-03-16 17:23:40 +07:00
wiz
c78a14c5fd Merge pull request #4780 from mempool/mononaut/fix-acc-pool-fees
Fix pool page accelerator fees
2024-03-16 18:21:23 +09:00
wiz
1dd72418c1 Merge branch 'master' into mononaut/fix-acc-pool-fees 2024-03-16 18:19:08 +09:00
Mononaut
f54bdace61 Fix pool page accelerator fees 2024-03-16 09:16:58 +00:00
dependabot[bot]
5ac87c095f Bump follow-redirects from 1.15.5 to 1.15.6 in /backend
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.5 to 1.15.6.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.5...v1.15.6)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-16 09:13:17 +00:00
dependabot[bot]
2d8111a6e7 Bump follow-redirects from 1.15.5 to 1.15.6 in /frontend
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.5 to 1.15.6.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.5...v1.15.6)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-16 09:13:14 +00:00
softsimon
d5cca2903c Merge pull request #4770 from mempool/dependabot/npm_and_yarn/frontend/cypress-13.7.0
Bump cypress from 13.6.2 to 13.7.0 in /frontend
2024-03-16 16:12:39 +07:00
wiz
d5e591c4af Merge pull request #4773 from mempool/mononaut/simplify-recent-txs
Simplify recent transactions observable
2024-03-16 17:27:07 +09:00
wiz
b5fa44955f Merge pull request #4775 from mempool/mononaut/oob-block-precision
Increase precision of out-of-band fees on the block page
2024-03-16 17:22:23 +09:00
wiz
9e1cf51e4a Merge pull request #4776 from mempool/mononaut/fix-new-unfurls
Fix tx push unfurl preview
2024-03-16 17:21:58 +09:00
wiz
fd41dfc152 Merge pull request #4774 from mempool/mononaut/accelerator-audit-pools
Show accelerator audit totals on pools page
2024-03-16 17:20:49 +09:00
wiz
d03e7b2d46 Merge branch 'master' into mononaut/accelerator-audit-pools 2024-03-16 17:19:56 +09:00
wiz
d3c5cbde7f Merge pull request #4771 from mempool/mononaut/update-bid-boost
Update acceleration audit to match latest bid boost version
2024-03-16 17:19:34 +09:00
wiz
dd7c8f2934 Merge pull request #4772 from mempool/mononaut/replacement-skeleton
Fix recent replacements skeleton loader
2024-03-16 17:19:18 +09:00
wiz
0b173296c4 Merge pull request #4768 from mempool/nymkappa/provisional-status
[accelerator] add provisional status
2024-03-16 17:17:54 +09:00
softsimon
81c8c8dafb Merge pull request #4747 from mempool/natsoni/more-fiat-currencies
Use fx rates to add more currencies support and improve fiat prices
2024-03-16 10:31:47 +07:00
Mononaut
31d3566ed5 Fix tx push unfurl preview 2024-03-15 09:35:08 +00:00
Mononaut
fb852b73e9 Increase precision of out-of-band fees on the block page 2024-03-15 08:28:50 +00:00
Mononaut
a44219a3c3 Add out of band fees to pools page 2024-03-15 07:44:57 +00:00
Mononaut
120ffdb0f4 Simplify pool details table 2024-03-15 07:40:44 +00:00
nymkappa
8dbfa1c73c Merge branch 'master' into nymkappa/provisional-status 2024-03-15 16:38:13 +09:00
Mononaut
8427127545 Simplify recent transactions observable 2024-03-15 06:05:52 +00:00
Mononaut
404892174d Fix recent replacements skeleton loader 2024-03-15 05:33:23 +00:00
Mononaut
e171c7694c Update acceleration audit to match latest bid boost version 2024-03-15 03:27:30 +00:00
natsoni
7bc6ef2516 Fix tx fee to display historical price 2024-03-14 13:08:15 +01:00
softsimon
0fcfc5e78d Merge branch 'master' into natsoni/more-fiat-currencies 2024-03-14 16:23:26 +07:00
softsimon
c12e664b9a Merge pull request #4769 from mempool/hunicus/the-the-preview
Move 'the' on the sponsor preview image
2024-03-14 16:09:50 +07:00
dependabot[bot]
8cb040eec6 Bump cypress from 13.6.2 to 13.7.0 in /frontend
Bumps [cypress](https://github.com/cypress-io/cypress) from 13.6.2 to 13.7.0.
- [Release notes](https://github.com/cypress-io/cypress/releases)
- [Changelog](https://github.com/cypress-io/cypress/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/cypress-io/cypress/compare/v13.6.2...v13.7.0)

---
updated-dependencies:
- dependency-name: cypress
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-14 02:32:54 +00:00
natsoni
5ecb915c60 Fix db version conflicts 2024-03-13 11:09:30 +01:00
hunicus
ab93a45853 Move the on the sponsor preview image 2024-03-13 18:15:06 +09:00
natsoni
a95d17950f Add fake entry for missing price data before 2010-07-19 2024-03-12 20:50:48 +01:00
nymkappa
860aac060c [accelerator] add provisional status 2024-03-12 17:04:37 +09:00
wiz
023b2f7ae2 Tweak CSS color for OOB fees on block component 2024-03-12 16:46:47 +09:00
wiz
9a531b0a00 Fix SQL query for /api/v1/accelerations/block/:height for older blocks 2024-03-12 15:05:05 +09:00
wiz
0c4631359d Merge pull request #4767 from mempool/hunicus/dot-space-previews
Add unfurler routes for /enterprise and /sponsor
2024-03-12 14:20:07 +09:00
wiz
fd04947ac0 Merge pull request #4766 from mempool/mononaut/past-acceleration-fees
Audit past acceleration fees
2024-03-12 14:19:18 +09:00
wiz
acdc5f92cd Merge pull request #4757 from russeree/add-aduit-blocks-param
Add audit=[bool] param to /block/[hash] url
2024-03-12 14:18:13 +09:00
wiz
f0f1eb06bb Remove stray console.log from #4757
Co-authored-by: mononaut <83316221+mononaut@users.noreply.github.com>
2024-03-12 14:17:57 +09:00
hunicus
fc1179f7bd Merge branch 'master' into hunicus/dot-space-previews 2024-03-12 11:35:09 +09:00
hunicus
cbc0e44d64 Add unfurler routes for /enterprise and /sponsor 2024-03-12 11:33:30 +09:00
softsimon
f851e821b4 Merge pull request #4760 from mempool/junderw/rust-gbt-build-final
Refactor rust-gbt and destroy all issues and be happy for all eternity
2024-03-12 09:12:02 +07:00
hunicus
df51018599 Reorder unfurler routes to be alphabetic 2024-03-12 10:22:42 +09:00
Mononaut
11a4f4e6d9 Audit past acceleration data 2024-03-11 21:35:01 +00:00
natsoni
b99e5c4160 Populate historical fiat prices from latest to oldest 2024-03-11 18:02:30 +01:00
natsoni
91ec0c8382 Merge branch 'origin/HEAD' into natsoni/more-fiat-currencies and fix db version conflicts 2024-03-11 15:32:35 +01:00
natsoni
669cf59269 Set monthly granulary for fx rates 2024-03-11 15:27:43 +01:00
natsoni
8e158e1786 Fix lastHistoricalRun variable to be in seconds 2024-03-11 14:28:06 +01:00
wiz
93f547e446 Merge pull request #4764 from mempool/nymkappa/fix-mysql-query
fix mysql query
2024-03-11 19:32:27 +09:00
nymkappa
ece40c5e74 fix mysql query 2024-03-11 19:01:39 +09:00
wiz
0dff902151 Add unfurler page for /blocks and /tx/push 2024-03-11 17:54:51 +09:00
wiz
5ea4ef80b9 Fix typo in fix for database migration fail 2024-03-11 16:07:47 +09:00
wiz
d83f483898 Fix database migration fail 2024-03-11 16:03:08 +09:00
wiz
c5d382c351 Fix typo build error in unfurler 2024-03-11 15:55:32 +09:00
wiz
b50d747440 Add missing unfurler routes, rename images to match 2024-03-11 15:38:09 +09:00
wiz
e7fde2f872 Merge pull request #4759 from mempool/hunicus/add-preview-imgs
Add page-specific preview images
2024-03-11 14:51:49 +09:00
wiz
c4b47e1f1c ops: Add mempool servers to elements.conf 2024-03-11 14:49:47 +09:00
wiz
3d61e57b00 Merge pull request #4761 from mempool/mononaut/fix-block-acc-fees
Fix block acceleration fees calculation & api bugs
2024-03-11 14:29:07 +09:00
junderw
92a5fc8159 Refactor rust-gbt 2024-03-11 02:09:37 +09:00
natsoni
a5099fed75 Add backend checks for enabling fiat prices and update config paths 2024-03-10 17:12:19 +01:00
natsoni
b11164005c Add FIAT_PRICE category to backend config 2024-03-10 16:34:43 +01:00
Mononaut
a2b0dd3a23 Fix block acceleration fees calculation & api 2024-03-10 15:08:44 +00:00
hunicus
553c2131d9 Remove mempool.space signup preview image 2024-03-10 20:46:12 +09:00
hunicus
c590a623f0 Merge branch 'master' into hunicus/add-preview-imgs 2024-03-10 17:47:23 +09:00
hunicus
a81c0a3b0f Add back old preview assets 2024-03-10 17:32:10 +09:00
hunicus
0f6b694fa9 Switch accelerator preview images 2024-03-10 17:28:14 +09:00
wiz
c55c298fb5 Merge pull request #4755 from mempool/nymkappa/sign-in-button
Update CTAs
2024-03-10 17:00:25 +09:00
wiz
ede3a121c7 Merge pull request #4758 from mempool/mononaut/accelerated-badge
Move accelerated badge into tx mining info field
2024-03-10 16:58:43 +09:00
softsimon
7bedb9488b Merge pull request #4749 from mempool/mononaut/fake-p2wsh-goggles
Add fake p2wsh goggles
2024-03-10 10:24:23 +07:00
softsimon
6d3c429bf4 Fixing database migration conflict. 2024-03-10 10:09:18 +07:00
Mononaut
9a730b51d4 Add fake p2wsh goggles 2024-03-10 10:07:33 +07:00
hunicus
a7c450895b Add preview assets for mempool.space 2024-03-10 11:11:40 +09:00
hunicus
a5f864fe35 Explicitly set mining and lightning preview images 2024-03-10 11:10:24 +09:00
hunicus
b41f196421 Add preview image: tos 2024-03-10 11:06:22 +09:00
hunicus
462c7f9c2c Add preview image: trademark policy 2024-03-10 11:04:39 +09:00
hunicus
869aa7fea5 Add preview image: recent blocks 2024-03-10 10:59:44 +09:00
hunicus
5b1f3d7cbe Add preview image: rbf 2024-03-10 10:59:44 +09:00
hunicus
60ad0b71c5 Add preview image: privacy policy 2024-03-10 10:59:43 +09:00
hunicus
68af577104 Update old preview images 2024-03-10 10:59:43 +09:00
hunicus
26be760692 Add preview image: faq 2024-03-10 10:27:10 +09:00
hunicus
a5b16cf129 Add preview image: broadcast tx 2024-03-10 10:26:57 +09:00
hunicus
a0e387efad Add preview image: accelerator dashboard 2024-03-10 10:08:21 +09:00
hunicus
e26e08b426 Add preview image: about page 2024-03-10 09:54:00 +09:00
hunicus
d9d92f1915 Add service function for fixed preview images 2024-03-10 09:52:28 +09:00
hunicus
79f0ea74c8 Compress existing preview images 2024-03-10 09:37:58 +09:00
hunicus
d1c12f9f6e Remove duplicate metadata tags
Some metadata was being set twice, because property and name
attributes for Twitter items were both being set.
2024-03-10 09:37:58 +09:00
hunicus
1b92c62353 Update default preview image location
Remove duplicate image, move to previews folder, and update
existing paths.
2024-03-10 08:23:16 +09:00
russeree
fffffffdb3 add audit=[bool] param to block hash url 2024-03-09 10:18:32 -08:00
Mononaut
2647e94bc8 Move accelerated badge into tx mining info field 2024-03-09 18:14:48 +00:00
natsoni
ccf1121f19 Fetch historical data based on timestamp and currency 2024-03-09 16:43:23 +01:00
natsoni
23076172e4 Merge branch 'master' into natsoni/more-fiat-currencies 2024-03-09 11:53:07 +01:00
nymkappa
52c4dd8bc3 [accelerator] preview cta points to mempool.space if not official build 2024-03-09 17:45:08 +09:00
softsimon
bfde456ca8 Only display docs enterprise upsell on official mempool 2024-03-09 15:38:16 +07:00
nymkappa
10819fda6d [ui] disable sign in button in global footer 2024-03-09 17:33:38 +09:00
wiz
c3d90d573f Merge pull request #4736 from mempool/mononaut/accelerator-audit-stats
Show accelerator audit total on block page
2024-03-09 13:52:39 +09:00
wiz
3c2ba74cb2 Merge pull request #4750 from mempool/nymkappa/fix-acceleration-apis
[accelerator] update dashboard and doc
2024-03-09 13:51:45 +09:00
wiz
0079e5d576 Merge pull request #4754 from mempool/nymkappa/min-accel-graph-bar-height
[accelerator] set accel graph bar min height
2024-03-09 13:51:23 +09:00
wiz
3f07026229 Merge pull request #4753 from mempool/mononaut/clockchain-pools
Hide mining pools on clock blockchain
2024-03-09 13:51:07 +09:00
wiz
ac971d17c7 Merge pull request #4748 from mempool/mononaut/transaction-mining-info
Display basic mining info on transaction page
2024-03-09 13:50:21 +09:00
wiz
00d8241dd7 Merge pull request #4752 from mempool/mononaut/loading-goggles
Fix stuck Goggles on websocket reconnect
2024-03-09 13:49:48 +09:00
wiz
d459e1fae3 Merge pull request #4746 from mempool/nymkappa/subdomain-cache-buster
[enterprise] implement subdomain logo cache buster
2024-03-09 13:49:17 +09:00
wiz
61b84e3957 Merge pull request #4751 from mempool/nymkappa/dynamic-timespan-selector-accel-graph
[accelerator] dynamically show timespan selector based on the oldest acceleration
2024-03-09 13:46:36 +09:00
softsimon
020194d37b Merge pull request #4723 from mempool/natsoni/federation-utxos-expiry
Liquid dashboard: Filter for expired UTXOs - Match layout with main dashboard
2024-03-09 10:20:08 +07:00
nymkappa
1665b0d915 [accelerator] set accel graph bar min height 2024-03-09 09:24:25 +09:00
Mononaut
b606282fb4 Hide mining pools on clock blockchain 2024-03-08 19:16:09 +00:00
Mononaut
dde6719306 Fix stuck Goggles on websocket reconnect 2024-03-08 16:47:15 +00:00
Mononaut
7af185a919 Tx audit tags handle coinbase 2024-03-08 15:22:48 +00:00
Mononaut
c17b77fe31 Display basic mining info on transaction page 2024-03-08 15:22:47 +00:00
nymkappa
faa5887c3b [accelerator] dynamically show timespan selector based on the oldest acceleration 2024-03-08 18:00:57 +09:00
softsimon
29bbb922c5 Merge pull request #4722 from mempool/dependabot/npm_and_yarn/frontend/es5-ext-0.10.64
Bump es5-ext from 0.10.53 to 0.10.64 in /frontend
2024-03-08 10:22:03 +07:00
dependabot[bot]
aac3b1aa5c Bump es5-ext from 0.10.53 to 0.10.64 in /frontend
Bumps [es5-ext](https://github.com/medikoo/es5-ext) from 0.10.53 to 0.10.64.
- [Release notes](https://github.com/medikoo/es5-ext/releases)
- [Changelog](https://github.com/medikoo/es5-ext/blob/main/CHANGELOG.md)
- [Commits](https://github.com/medikoo/es5-ext/compare/v0.10.53...v0.10.64)

---
updated-dependencies:
- dependency-name: es5-ext
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-08 03:21:24 +00:00
softsimon
e3bb7f73f9 Merge pull request #4702 from mempool/dependabot/npm_and_yarn/backend/ip-2.0.1
Bump ip from 2.0.0 to 2.0.1 in /backend
2024-03-08 10:20:09 +07:00
softsimon
c4ecc1626d Merge pull request #4701 from mempool/dependabot/npm_and_yarn/frontend/ip-2.0.1
Bump ip from 2.0.0 to 2.0.1 in /frontend
2024-03-08 10:19:54 +07:00
nymkappa
007f424d15 [accelerator] update doc, split public/authenticated 2024-03-08 10:52:02 +09:00
nymkappa
1d56bfa9b8 [accelerator] remove query params for acceleration list 2024-03-08 10:33:23 +09:00
Mononaut
e7788133fa Add missing null check in block accelerations subscription 2024-03-07 19:52:42 +00:00
Mononaut
7491fb512c Show accelerator audit total on block page 2024-03-07 19:46:24 +00:00
natsoni
b043d698ca Allow historical price api to return data of a single currency 2024-03-07 18:33:19 +01:00
natsoni
f121d16544 Add more fiat currencies using fx rates from FreeCurrencyAPI 2024-03-07 10:48:32 +01:00
natsoni
bfaddfc345 Add CURRENCY_API_KEY option to config files 2024-03-07 10:36:33 +01:00
nymkappa
f5e1e5f1a2 [enterprise] implement subdomain logo cache buster 2024-03-07 18:32:52 +09:00
natsoni
e8c5d478fa Merge branch 'master' into natsoni/federation-utxos-expiry 2024-03-07 10:27:44 +01:00
wiz
1d877a746f Merge pull request #4744 from mempool/mononaut/send-nodes
More status page polish
2024-03-07 18:06:05 +09:00
softsimon
82716b0037 Merge pull request #4745 from mempool/mononaut/missing-blocks
Fix missing mempool blocks
2024-03-07 12:15:19 +07:00
softsimon
b988f042cc Merge pull request #4743 from mempool/junderw/reload-icons
Fix: Refresh Liquid icons every 15 seconds to match electrs.
2024-03-07 11:09:33 +07:00
softsimon
1df5c5df6d Updating to match crontab update 2024-03-07 11:09:08 +07:00
Mononaut
3178d30f2a Fix missing mempool blocks bug 2024-03-06 22:25:58 +00:00
Mononaut
be52fd4e46 More status page polish 2024-03-06 19:34:12 +00:00
junderw
11a6d81a17 Fix: Refresh Liquid icons every 15 seconds to match electrs. 2024-03-07 02:21:38 +09:00
wiz
31e320b2e2 ops: Update check git/md5 hash script 2024-03-06 17:37:27 +09:00
wiz
7f18d73443 Merge pull request #4689 from mempool/mononaut/wallet-balance
Add embeddable wallet balance page
2024-03-06 16:38:00 +09:00
wiz
30485e7483 Merge pull request #4397 from mempool/mononaut/tomahawk-timeouts
Improve timeout handling in esplora api health monitoring & logs
2024-03-06 16:34:20 +09:00
wiz
a2fb16c84c Merge pull request #4144 from mempool/hunicus/enterprise-cta-docs
Add enterprise cta to docs
2024-03-06 16:33:38 +09:00
wiz
57a878403e Merge branch 'master' into mononaut/wallet-balance 2024-03-06 16:29:10 +09:00
wiz
faa5475ab7 Merge branch 'master' into mononaut/tomahawk-timeouts 2024-03-06 16:24:35 +09:00
wiz
28d23d4304 Merge branch 'master' into hunicus/enterprise-cta-docs 2024-03-06 16:23:48 +09:00
wiz
cef80a36a9 Merge pull request #4655 from jamesblacklock/macos-docker-init
modify docker/init.sh for macOS compatibility
2024-03-06 16:20:49 +09:00
wiz
e0e997a3d1 Merge pull request #4549 from mempool/nymkappa/increase-mysql-pool
[database] increase default pool size to 100 connections
2024-03-06 16:19:53 +09:00
wiz
c4a11309fa Merge pull request #4278 from mempool/knorrium/add_sync_check_script
ops: Add block height workflow
2024-03-06 16:18:46 +09:00
wiz
fa4caec73e Merge pull request #4628 from mempool/simon/dashboard-miner-tags
Display pool tags on dashboard
2024-03-06 16:17:25 +09:00
wiz
965a135390 Merge pull request #4740 from mempool/mononaut/polish-nodes
Polish /nodes and /network pages
2024-03-06 16:14:32 +09:00
wiz
9e5fdbb64a ops: Increase nginx proxy buffer sizes 2024-03-06 16:04:30 +09:00
Mononaut
71863e4f48 Polish /nodes and /network pages 2024-03-05 23:16:20 +00:00
dependabot[bot]
7cee1512a3 Bump ip from 2.0.0 to 2.0.1 in /backend
Bumps [ip](https://github.com/indutny/node-ip) from 2.0.0 to 2.0.1.
- [Commits](https://github.com/indutny/node-ip/compare/v2.0.0...v2.0.1)

---
updated-dependencies:
- dependency-name: ip
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-05 13:52:17 +00:00
wiz
c9b2ce3efb Merge pull request #4737 from mempool/junderw/bump-rust-deps
Bump rust-gbt deps
2024-03-05 22:50:35 +09:00
junderw
0f1434e32d Bump rust-gbt deps 2024-03-05 22:32:14 +09:00
wiz
acb60fa1bc ops: Add check script to production folder 2024-03-05 21:44:54 +09:00
wiz
9e1fe71dc8 ops: Add MAX_TRACKED_ADDRESSES to prod configs 2024-03-05 20:48:39 +09:00
wiz
62e0cb2e57 Merge pull request #4734 from mempool/mononaut/tomahawk-status-page
Tomahawk status page
2024-03-05 20:09:40 +09:00
natsoni
198939da81 Minor typo and displaying fixes 2024-03-04 20:45:45 +01:00
natsoni
847b90f167 Fix db version conflicts 2024-03-04 20:32:38 +01:00
Mononaut
73e9c85ff1 Separate tomahawk nodes & network pages, misc fixes 2024-03-04 18:47:26 +00:00
Mononaut
5f3ca3a321 Disable tomahawk status on non-official instances 2024-03-04 18:47:26 +00:00
Mononaut
1518b3ccfb Backend OFFICIAL config setting 2024-03-04 18:47:26 +00:00
Mononaut
5898143f66 Electrs server status page 2024-03-04 18:47:26 +00:00
Mononaut
f63f1b1773 Websocket subscription for fallback server health status 2024-03-04 18:47:24 +00:00
softsimon
8405e5ff07 Merge pull request #4718 from mempool/mononaut/accelerator-audit
Accelerator audit
2024-03-05 01:38:53 +07:00
Mononaut
f923ee4ede Accelerator audit use datetime for added column 2024-03-04 16:32:43 +00:00
Mononaut
bd0de745e2 Add local acceleration info APIs 2024-03-04 16:29:29 +00:00
Mononaut
130bdac58c Calculate & save acceleration bid boost rates 2024-03-04 16:29:28 +00:00
Mononaut
75578ac9fa Improve timeout handling in esplora api health monitoring & logs 2024-03-04 15:22:29 +00:00
wiz
b9d46003f8 Merge pull request #4733 from mempool/mononaut/tooltip-fee-rate
Hide effective rate on tooltip where irrelevant
2024-03-04 22:31:01 +09:00
wiz
1fd07f6c9f Merge pull request #4731 from mempool/nymkappa/accel-list-1y
[accelerator] acceleration list query 1y
2024-03-04 22:30:37 +09:00
wiz
5a5409fd1a Merge pull request #4732 from mempool/nymkappa/fix-accel-chart
[accelerator] fix accel graph tooltip and time axis
2024-03-04 22:30:18 +09:00
softsimon
4bddb52db1 Merge pull request #4712 from mempool/mononaut/the-goggles-nonstandard
Add non-standard Goggles filter
2024-03-04 12:25:49 +07:00
natsoni
dc9bddc6b2 Remove checkbox for expired UTXOs and add new tab 2024-03-03 18:31:39 +01:00
Mononaut
8626846264 Hide effective rate on tooltip where irrelevant 2024-03-03 16:48:04 +00:00
Mononaut
eadbc139fa Handle missing inner_redeemscript 2024-03-03 16:02:14 +00:00
Mononaut
882e8ec598 Check in missing script utility file 2024-03-03 16:02:14 +00:00
Mononaut
249c57f376 Add non-standard Goggles filter 2024-03-03 16:02:14 +00:00
nymkappa
f083aa37d6 [accelerator] fix xaxis type accel graph 2024-03-03 15:43:29 +01:00
nymkappa
c74ce7de83 [accelerator] fix tooltip timestamp accel graph 2024-03-03 15:40:31 +01:00
nymkappa
d4c01f6b1f [accelerator] acceleration list query 1y 2024-03-03 07:57:36 +01:00
wiz
1deacb9996 Merge pull request #4729 from mempool/nymkappa/accel-stats-3m
[accelerator] fix accel bid boost history chart
2024-03-03 12:27:15 +09:00
nymkappa
8bd939b374 [accelerator] show 3m stats, fix accel fee chart 2024-03-01 12:53:29 +01:00
nymkappa
cda5448f13 [accelerator] fix accel bid boost chart height 2024-03-01 11:04:40 +01:00
softsimon
af6af2748c Merge pull request #4715 from mempool/nymkappa/accel-dashboard-cleanup
[accelerator] improve acceleration list/dashboard
2024-03-01 10:17:22 +07:00
wiz
975588a862 Merge pull request #4725 from mempool/knorrium/tag_to_latest_again
Push the latest tag to Docker Hub again
2024-03-01 11:50:46 +09:00
Felipe Knorr Kuhn
093649136e Push the latest tag to Docker Hub again 2024-02-29 18:42:29 -08:00
natsoni
84e91b2c90 Merge remote-tracking branch 'origin/master' into natsoni/federation-utxos-expiry 2024-02-29 14:59:41 +01:00
natsoni
ef209da774 Add expiry filter to Federation UTXOs table
Unify Liquid dashboard with mempool dashboard
2024-02-29 14:57:15 +01:00
wiz
018d4230e2 ops: Remove node207-214.tk7 from prod cluster configs 2024-02-29 19:33:39 +09:00
softsimon
6c66da5426 Merge pull request #4720 from mempool/dependabot/npm_and_yarn/backend/babel/core-7.24.0
Bump @babel/core from 7.23.2 to 7.24.0 in /backend
2024-02-29 17:20:18 +07:00
dependabot[bot]
4a6231c93c Bump ip from 2.0.0 to 2.0.1 in /frontend
Bumps [ip](https://github.com/indutny/node-ip) from 2.0.0 to 2.0.1.
- [Commits](https://github.com/indutny/node-ip/compare/v2.0.0...v2.0.1)

---
updated-dependencies:
- dependency-name: ip
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-29 05:06:01 +00:00
softsimon
5b9b0d0968 Merge pull request #4694 from mempool/dependabot/npm_and_yarn/frontend/echarts-5.5.0
Bump echarts from 5.4.3 to 5.5.0 in /frontend
2024-02-29 12:05:10 +07:00
softsimon
ddf1bc0654 Merge pull request #4721 from mempool/simon/accel-tab-mainnet-only
Only display acceleration tab on mainnet
2024-02-29 11:55:08 +07:00
softsimon
419b40884a Only display acceleration tab on mainnet
fixes #4719
2024-02-29 11:49:12 +07:00
dependabot[bot]
1f05e7b366 Bump @babel/core from 7.23.2 to 7.24.0 in /backend
Bumps [@babel/core](https://github.com/babel/babel/tree/HEAD/packages/babel-core) from 7.23.2 to 7.24.0.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.24.0/packages/babel-core)

---
updated-dependencies:
- dependency-name: "@babel/core"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-29 02:32:53 +00:00
nymkappa
867e959430 [accelerator] /accelerator/stats -> /accelerator/accelerations/stats 2024-02-27 15:22:59 +01:00
nymkappa
3f8a4b5119 [accelerator] move accel stats into backend 2024-02-27 15:20:15 +01:00
nymkappa
cc06f85e73 Merge branch 'master' into nymkappa/accel-dashboard-cleanup 2024-02-27 12:42:19 +01:00
softsimon
a9d94bdafd Merge pull request #4685 from mempool/mononaut/v3-filter
Add Goggles filter for nVersion=3
2024-02-27 15:44:13 +07:00
wiz
18b1805ff3 Merge pull request #4706 from mempool/natsoni/fix-liquid-dashboard-safari
Fix liquid dashboard css
2024-02-27 12:22:18 +09:00
wiz
4044ca3877 Merge pull request #4708 from mempool/mononaut/acceleration-goggles
Add Acceleration Goggles
2024-02-27 12:21:55 +09:00
wiz
66386f2bcc Merge pull request #4709 from mempool/hunicus/txs-api-queryparam
Fix query parameter label in tx history api doc
2024-02-27 12:21:17 +09:00
wiz
d0bf26bcef Merge pull request #4711 from mempool/nymkappa/update-doc
[doc] remove "estimated_fee" from accelerator endpoints
2024-02-27 12:20:54 +09:00
wiz
e918e1fdab ops: Implement ACL for internal APIs 2024-02-27 11:46:14 +09:00
nymkappa
ab0c3eeab6 [accelerator] cap max width acceleration history list for now 2024-02-26 16:47:19 +01:00
nymkappa
e26fcff063 [accelerator] cleanup status 2024-02-26 16:40:22 +01:00
nymkappa
b3b65c59dc [accelerator] improve dashboard responsiveness a bit 2024-02-26 16:23:00 +01:00
nymkappa
fbebfdae04 [accelerator] add pagination support in acceleration list 2024-02-26 15:54:10 +01:00
nymkappa
968a26d2cd Merge branch 'master' into nymkappa/update-doc 2024-02-25 10:07:48 +01:00
wiz
43fde86e9d Merge pull request #4710 from mempool/knorrium/update_node_matrix_20_21
Update node matrix to v20 and v21
2024-02-25 16:48:27 +09:00
wiz
587c7f6d59 ops: Kill nginx cache heater script on shutdown 2024-02-25 16:47:40 +09:00
Felipe Knorr Kuhn
f431ca742f Update node matrix to v20 and v21 2024-02-24 23:40:36 -08:00
wiz
7e16c5e8c4 Tweak a few strings on Acceleration Summary screen 2024-02-25 16:18:43 +09:00
hunicus
8701ba8546 Fix query parameter label in tx history api doc 2024-02-25 01:17:46 -05:00
Mononaut
42912ff007 Add Acceleration Goggles 2024-02-24 20:37:41 +00:00
natsoni
6d8a72301c Fix recent pegs table css 2024-02-22 15:14:47 +01:00
natsoni
1cdbde680c Fix liquid dashboard on mobile view 2024-02-22 14:43:19 +01:00
wiz
ec21b3d06f Merge pull request #4678 from mempool/knorrium/skip_latest_tagging
Temporarily disable tagging images as latest
2024-02-22 19:18:55 +09:00
wiz
e8e43c074b Merge pull request #4704 from mempool/mononaut/matomo-events
matomo events
2024-02-22 19:18:27 +09:00
nymkappa
dc50b40b69 if matomo is undefined, don't try to use it 2024-02-22 11:07:50 +01:00
wiz
e41d6bc2e6 Merge pull request #4504 from mempool/orangesurf/trademark-updates-2
Move 3rd party licenses to footer
2024-02-22 17:45:27 +09:00
wiz
cb7938baa1 Merge branch 'master' into orangesurf/trademark-updates-2 2024-02-22 15:56:08 +09:00
wiz
4d6b62c7de Merge pull request #4205 from mempool/mononaut/unfurl-fallback-no-cache
Unfurl fallback no-cache
2024-02-22 15:52:10 +09:00
wiz
7bf053afe5 Merge branch 'master' into mononaut/unfurl-fallback-no-cache 2024-02-22 15:51:57 +09:00
wiz
d8900d40c7 Merge pull request #4204 from mempool/mononaut/unfurl-symlink-fallbacks
Use symlink to avoid duplicate unfurler fallback images
2024-02-22 15:51:47 +09:00
wiz
841f18f481 Merge pull request #4687 from mempool/mononaut/testnet-expiry
Restore mempoolexpiry on test networks
2024-02-22 15:43:24 +09:00
wiz
b0d34d4e48 Merge branch 'master' into mononaut/matomo-events 2024-02-22 15:27:57 +09:00
Mononaut
c684834c42 matomo tx events 2024-02-21 23:15:31 +00:00
softsimon
46e989ab27 Merge pull request #4692 from mempool/natsoni/fix-goggles-z-index
Fix block visualisation tooltip z-index
2024-02-21 12:17:43 +07:00
softsimon
2c19e44fbf Merge pull request #4690 from mempool/natsoni/fix-hardcoded-hashrate-unit
Fix hardcoded hashrate unit in pool ranking graph
2024-02-21 11:12:21 +07:00
softsimon
dab72f669d Merge pull request #4700 from mempool/natsoni/lightning-pagination
Add pagination to Lightning nodes list and fix table overflow
2024-02-21 11:07:35 +07:00
softsimon
16537e8018 Merge pull request #4703 from mempool/mononaut/revert-halving-countdown
Revert reverted halving countdown widget
2024-02-21 11:05:52 +07:00
Mononaut
a3b713cc74 Revert reverted halving countdown widget 2024-02-20 23:12:41 +00:00
natsoni
17697e669a Add pagination to Lightning nodes list and fix overflow 2024-02-19 17:08:07 +01:00
softsimon
035068a72e Merge pull request #4632 from mempool/mononaut/redis-error-handling
Handle Redis errors and disconnects
2024-02-19 22:18:24 +07:00
softsimon
086ae6978a Merge branch 'master' into mononaut/redis-error-handling 2024-02-19 21:21:05 +07:00
softsimon
951b946be9 Merge pull request #4699 from mempool/natsoni/fix-nodes-map-undefined-channels
Fix nodes map undefined channels count
2024-02-19 21:19:21 +07:00
natsoni
5fc2205b54 Fix nodes map undefined channels count 2024-02-19 11:57:43 +01:00
softsimon
18e412939d Merge pull request #4698 from mempool/mononaut/bg-goggles-indexing
Continue other indexing tasks while Goggles classification runs
2024-02-19 12:29:46 +08:00
Mononaut
69dc21d232 Continue other indexing tasks while Goggles classification runs 2024-02-19 04:11:03 +00:00
dependabot[bot]
dbe66fd4d9 Bump node in /docker/backend
Bumps node from 20.8.0-buster-slim to 20.11.1-buster-slim.

---
updated-dependencies:
- dependency-name: node
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-19 02:38:37 +00:00
dependabot[bot]
3041540283 Bump node in /docker/frontend
Bumps node from 20.8.0-buster-slim to 20.11.1-buster-slim.

---
updated-dependencies:
- dependency-name: node
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-19 02:30:33 +00:00
dependabot[bot]
d982938366 Bump nginx from 1.24.0-alpine to 1.25.4-alpine in /docker/frontend
Bumps nginx from 1.24.0-alpine to 1.25.4-alpine.

---
updated-dependencies:
- dependency-name: nginx
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-19 02:30:26 +00:00
dependabot[bot]
521d2fc650 Bump echarts from 5.4.3 to 5.5.0 in /frontend
Bumps [echarts](https://github.com/apache/echarts) from 5.4.3 to 5.5.0.
- [Release notes](https://github.com/apache/echarts/releases)
- [Commits](https://github.com/apache/echarts/compare/5.4.3...5.5.0)

---
updated-dependencies:
- dependency-name: echarts
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-19 02:25:26 +00:00
natsoni
ac250ebe6c Add z-index to block overview tooltip component 2024-02-17 18:08:22 +01:00
natsoni
596aada169 Fix hardcoded hashrate unit in pool ranking graph 2024-02-16 09:59:37 +01:00
Mononaut
1f14cbfcaa Fix websocket wallet balances, reposition logo 2024-02-16 06:07:04 +00:00
Mononaut
a7ce7121ee add mempool logo to wallet widget 2024-02-16 02:50:16 +00:00
Mononaut
96a17f09a5 Add embeddable wallet balance page 2024-02-16 02:41:22 +00:00
nymkappa
c4df05b581 [doc] remove "estimated_fee" from accelerator endpoints 2024-02-15 17:33:38 +01:00
softsimon
7fb699a02b Merge pull request #4680 from mempool/mononaut/sliding-difficulty
Project early difficulty adjustment with sliding window
2024-02-15 23:55:21 +08:00
Mononaut
e8fc1e8522 Always show estimated difficulty adjustment 2024-02-15 15:32:31 +00:00
softsimon
5f14b32a06 Merge branch 'master' into mononaut/sliding-difficulty 2024-02-15 22:57:21 +08:00
softsimon
e2d7c82553 Merge pull request #4673 from mempool/natsoni/liquid-dashboard-minor-fixes
Liquid Audit dashboard: requested changes
2024-02-15 17:13:20 +08:00
natsoni
7259a00c8d Polish pegometer for varying screen width 2024-02-14 18:22:04 +01:00
Mononaut
7c6c1187bb Restore mempoolexpiry on test networks 2024-02-14 15:13:00 +00:00
natsoni
9f4c351e3d Minor logic change in dashboard component 2024-02-13 16:55:02 +01:00
softsimon
329c1330f4 Merge pull request #4686 from mempool/move-sponsor-boxes
Move sponsor boxes to subscriptions account panel
2024-02-13 21:26:51 +08:00
natsoni
d55d5db01d Resolve conflicts in dashboard component 2024-02-13 09:47:45 +01:00
natsoni
55cd2f5678 Liquid dashboard: switch places of top graphs 2024-02-13 09:36:22 +01:00
natsoni
69747a0028 Migrate audit dashboard to main Liquid page 2024-02-13 00:59:28 +01:00
hunicus
45c1e05ebc Move sponsor boxes to subscriptions account panel 2024-02-12 17:43:34 -05:00
Mononaut
8713d33d1a Add Goggles filter for nVersion=3 2024-02-12 20:00:57 +00:00
softsimon
512f632475 Merge pull request #4676 from mempool/simon/log-mempool-on-new-blocks
Log mempool stats on new blocks
2024-02-12 23:07:49 +08:00
softsimon
6dedecad70 Merge pull request #4681 from mempool/mononaut/fix-log-stats-on-new-block
Fix statistics timespans
2024-02-12 18:55:48 +08:00
natsoni
99aa6c9ed3 Liquid: improve recent pegs pagination data query 2024-02-12 11:34:47 +01:00
Mononaut
d24d643d70 Fix statistics timespan for 2h and 24hr charts 2024-02-12 00:54:34 +00:00
Mononaut
000524691a Project early difficulty from sliding window 2024-02-11 23:11:19 +00:00
Felipe Knorr Kuhn
290de43df0 Temporarily disable tagging images as latest 2024-02-11 13:10:08 -08:00
softsimon
cc2f42e814 Merge pull request #4672 from mempool/nymkappa/fix-username-not-showing
[auth] properly refresh user when `auth` object changes
2024-02-11 20:13:51 +08:00
softsimon
a40727b194 Merge pull request #4624 from mempool/nymkappa/api-key-rest
[doc] add accelerator rest api documentation
2024-02-11 20:02:41 +08:00
nymkappa
6933d3c395 Merge branch 'master' into nymkappa/fix-username-not-showing 2024-02-11 12:03:04 +01:00
nymkappa
4fc5a6197a Merge branch 'master' into nymkappa/api-key-rest 2024-02-11 12:01:38 +01:00
nymkappa
fbabd93b5e Update frontend/src/app/docs/api-docs/api-docs-data.ts
Co-authored-by: hunicus <93150691+hunicus@users.noreply.github.com>
2024-02-11 12:01:09 +01:00
softsimon
2c22200820 Log mempool stats on new blocks 2024-02-10 20:45:58 +08:00
softsimon
d921c3fdc2 Merge pull request #4670 from mempool/mononaut/optimize-mempool-websocket
Reduce the network size of mempool block websocket updates
2024-02-10 20:10:42 +08:00
nymkappa
a1bd84ea6d [doc] separate private/public acceleration history endpoint title 2024-02-10 11:41:30 +01:00
nymkappa
740f9af9af [doc] additional rest api doc for accelerator 2024-02-10 11:40:19 +01:00
nymkappa
be183ada0a [doc] fix acceleration history endpoint detail 2024-02-10 10:56:19 +01:00
nymkappa
a2b01587b1 [auth] small refactor 2024-02-10 10:31:56 +01:00
nymkappa
5f698dfbbb Merge branch 'master' into nymkappa/api-key-rest 2024-02-10 10:23:17 +01:00
softsimon
46f2509ca0 Merge branch 'master' into mononaut/optimize-mempool-websocket 2024-02-10 15:27:15 +08:00
wiz
8bd4a8a9ee Merge pull request #4674 from mempool/mononaut/data-filter 2024-02-09 17:53:15 -05:00
wiz
e00bc86bd1 Merge pull request #4675 from mempool/mononaut/no-webgl 2024-02-09 17:52:54 -05:00
Mononaut
ade256efc7 Handle missing webgl on dashboards 2024-02-09 21:46:42 +00:00
natsoni
33ac4056d8 Display percent instead of ratio in stats 2024-02-09 18:59:24 +01:00
natsoni
4ef1df47a3 Fix addresses stat error 2024-02-09 18:46:34 +01:00
Mononaut
e23de97e0f 💩 => data 2024-02-09 17:42:20 +00:00
natsoni
346c024ddf Change federation wallet stats to include utxos count 2024-02-09 16:26:59 +01:00
nymkappa
bb43599493 [auth] remove debug log 2024-02-09 15:53:20 +01:00
nymkappa
e6266ecedc [auth] properly refresh user when auth object changes 2024-02-09 15:49:28 +01:00
softsimon
d4db628c3b Merge pull request #4666 from mempool/mononaut/persistent-filters
Make dashboard filters persistent, add disjunctive filter mode
2024-02-09 21:31:09 +08:00
softsimon
1e56ac094c Smaller mobile toggle buttons 2024-02-09 21:30:50 +08:00
Mononaut
ddee5f927c Make dashboard filters persistent, add disjunctive filter mode 2024-02-09 21:30:50 +08:00
natsoni
42bd08c744 Minor fixes on Liquid dashboards 2024-02-09 14:26:34 +01:00
softsimon
dfbec0ceef Merge pull request #4511 from mempool/nymkappa/fix-platinium-typo
[typo] platinium -> platinum
2024-02-09 20:46:19 +08:00
nymkappa
3b3081f884 Merge branch 'master' into nymkappa/api-key-rest 2024-02-09 12:51:30 +01:00
softsimon
925d51f40e Merge pull request #4669 from mempool/mononaut/fix-dashboard-sizes
Fix mining/liquid dashboard widget heights
2024-02-09 14:11:43 +08:00
softsimon
b3dbe1215c Adjusting Load more position to match other dashboards 2024-02-09 14:11:12 +08:00
softsimon
dd89c398cc Merge pull request #4665 from mempool/natsoni/fix-liquid-dashboard-mobile
Fix Liquid dashboard layout on mobile view
2024-02-09 14:01:29 +08:00
Mononaut
7de4a03f1b Fix mining/liquid dashboard widget heights 2024-02-08 22:50:47 +00:00
Mononaut
1121136a5e Reduce the network size of mempool block websocket updates 2024-02-08 22:40:22 +00:00
natsoni
e5f0544cc2 Fix Liquid dashboard layout for mobile view 2024-02-08 18:32:07 +01:00
nymkappa
3456d2737a Merge branch 'master' into nymkappa/fix-platinium-typo 2024-02-08 15:11:45 +01:00
softsimon
efdc83d4bb Enabling Accelerator 2024-02-08 21:25:34 +08:00
softsimon
d745bf3f9e Merge pull request #4664 from mempool/simon/liquid-mining-dashboard-heights
Fixed liquid and mining dashboard graph heights
2024-02-08 21:02:58 +08:00
softsimon
9d6231b6e5 New mining dashboard graph height 2024-02-08 21:01:24 +08:00
softsimon
fdad3d1fd5 Fixing new liquid dashboard height 2024-02-08 20:56:16 +08:00
wiz
1e3650594c Merge pull request #4509 from mempool/nymkappa/mega-branch
[Mega branch] Various fixes and improvements
2024-02-08 07:55:25 -05:00
nymkappa
2dc2a22edb Merge branch 'master' into nymkappa/mega-branch 2024-02-08 13:37:17 +01:00
softsimon
dcccc3c8a2 Merge pull request #4658 from mempool/natsoni/fix-undefined-block-fee
Blockchain component: display dash when feerate is undefined
2024-02-08 20:31:00 +08:00
wiz
49553b7bae Merge pull request #4653 from mempool/mononaut/healthier-checks
Staggered esplora fallback health checks
2024-02-08 07:23:39 -05:00
softsimon
01e019245b Merge pull request #4651 from mempool/natsoni/liquid-audit-improvements
Liquid audit dashboard: various improvements
2024-02-08 19:50:55 +08:00
softsimon
01066eae64 Merge pull request #4648 from mempool/natsoni/search-bar-confidential-addresses
Search bar: add Liquid confidential addresses to addresses regex
2024-02-08 19:45:08 +08:00
softsimon
b88d6bc7b7 Merge pull request #4659 from mempool/natsoni/fix-broken-blocks-skeleton
Fix broken skeleton loader of blocks-list
2024-02-08 18:34:00 +08:00
softsimon
a51d82bcfb Merge branch 'master' into natsoni/fix-broken-blocks-skeleton 2024-02-08 16:22:06 +08:00
softsimon
999994c701 Merge pull request #4652 from mempool/mononaut/fix-address-scroll
Fix infinite address scroll
2024-02-08 16:14:05 +08:00
softsimon
0a7c91a4e9 Merge pull request #4663 from mempool/mononaut/dashboard-concept
New dashboard concept
2024-02-08 14:57:44 +08:00
softsimon
510dd91328 Changed to toggle buttons. Changed filters. 2024-02-08 14:52:31 +08:00
Mononaut
3ceb583127 Fix Goggles title alignment 2024-02-08 04:18:05 +00:00
Mononaut
d7be5a4737 Simple Goggle Toggles 2024-02-08 04:17:54 +00:00
Mononaut
3039481686 Change titles, adjust padding 2024-02-08 02:47:46 +00:00
Mononaut
f14cd5ee2b Swap incoming vb chart and mempool stats 2024-02-08 00:37:16 +00:00
Mononaut
e268a6a033 Fix mining dashboard hashrate graph height 2024-02-08 00:03:34 +00:00
Mononaut
ca2c5d3628 Expand lightning dashboard widgets & improve responsiveness 2024-02-08 00:00:06 +00:00
Mononaut
ce7a007b62 Expand mining dashboard widgets & improve responsiveness 2024-02-07 23:26:06 +00:00
Mononaut
ba0a3d004d Expand acceleration dashboard widgets & improve responsiveness 2024-02-07 21:40:22 +00:00
Mononaut
29e4a581e7 Add next block visualization to main dashboard, expand widgets 2024-02-07 21:39:39 +00:00
Mononaut
4f98a413d1 address scroll handle different page sizes 2024-02-07 20:23:35 +00:00
nymkappa
0ab1183048 Merge branch 'master' into nymkappa/mega-branch 2024-02-07 17:01:55 +01:00
James Blacklock
b8d635f257 Merge branch 'master' into macos-docker-init 2024-02-07 09:15:32 -05:00
natsoni
03d4375b17 Clean up blocks-list skeleton 2024-02-07 14:51:23 +01:00
softsimon
e86d0dc868 Merge pull request #4573 from mempool/dependabot/npm_and_yarn/backend/follow-redirects-1.15.5
Bump follow-redirects from 1.15.2 to 1.15.5 in /backend
2024-02-07 21:47:56 +08:00
softsimon
e9a7ea3623 Merge pull request #4650 from mempool/natsoni/add-liquid-peg-out-label
Add P2WSH Liquid peg out to input label
2024-02-07 20:09:48 +08:00
dependabot[bot]
1e568e5b4c Bump follow-redirects from 1.15.2 to 1.15.5 in /backend
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.2 to 1.15.5.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.2...v1.15.5)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-02-07 11:53:08 +00:00
softsimon
b56350dca1 Merge pull request #4633 from mempool/dependabot/npm_and_yarn/backend/mysql2-3.9.1
Bump mysql2 from 3.7.0 to 3.9.1 in /backend
2024-02-07 19:52:24 +08:00
natsoni
20614213a7 Add skeleton to recent blocks on Liquid dashboard 2024-02-07 12:50:36 +01:00
softsimon
582eca1fdd Merge branch 'master' into dependabot/npm_and_yarn/backend/mysql2-3.9.1 2024-02-07 19:47:41 +08:00
natsoni
df7f1cc86b Blockchain component: display dash when feerate is undefined 2024-02-07 11:31:22 +01:00
softsimon
0acb797494 Merge pull request #4646 from mempool/knorrium/download_from_cdn
[sync-assets] More logging, add MEMPOOL_CDN and DRY_RUN options
2024-02-07 16:05:01 +08:00
Felipe Knorr Kuhn
195eeaa7b9 Merge branch 'master' into knorrium/download_from_cdn 2024-02-06 20:10:39 -08:00
James Blacklock
d04952b10b Merge branch 'master' into macos-docker-init 2024-02-06 23:06:20 -05:00
softsimon
48c2317e20 Merge pull request #4654 from jamesblacklock/docker-bugfix-2
fix syntax error in mempool-config.json
2024-02-07 12:06:04 +08:00
Felipe Knorr Kuhn
95233f0ef3 Merge branch 'master' into docker-bugfix-2 2024-02-06 19:56:22 -08:00
softsimon
29c6efa9ed Merge pull request #4657 from mempool/knorrium/validate_final_docker_json
Add a step to validate the JSON config generated for Docker
2024-02-07 11:55:42 +08:00
Felipe Knorr Kuhn
624cbf05c0 Add a step to validate the JSON config generated for Docker 2024-02-06 19:47:09 -08:00
James Blacklock
1547c2c477 fix syntax error in mempool-config.json 2024-02-06 22:13:10 -05:00
James Blacklock
df92f4d0aa modify docker/init.sh for macOS compatibility 2024-02-06 21:36:14 -05:00
Mononaut
3959f52d19 Staggered esplora fallback health checks 2024-02-06 23:42:14 +00:00
Mononaut
dfdd286f75 Fix infinite address scroll 2024-02-06 21:50:29 +00:00
wiz
fea115bcbc ops: Fix obvious bug in cache heater script 2024-02-06 14:03:44 -05:00
wiz
f004705896 ops: Add missing HTTP Expires header for fees API 2024-02-06 13:55:44 -05:00
wiz
87a613e4dc ops: Fix broken nginx cache configuration 2024-02-06 13:53:03 -05:00
natsoni
b561648082 Add peg ins/out volume to stats components 2024-02-06 17:35:02 +01:00
natsoni
602c87bea0 Update peg-in/out links to open new page on click 2024-02-06 17:34:24 +01:00
natsoni
b453898b1d Add glow effect to peg outs in progress 2024-02-06 17:34:04 +01:00
Felipe Knorr Kuhn
c4c886b584 Merge branch 'master' into knorrium/download_from_cdn 2024-02-06 07:44:00 -08:00
natsoni
517d36783f Add P2WSH Liquid peg out to input label 2024-02-06 11:37:51 +01:00
nymkappa
f964888c47 Merge branch 'master' into nymkappa/mega-branch 2024-02-05 17:10:07 +01:00
natsoni
c58115a96c Add confidential addresses in liquid address regex 2024-02-05 11:53:05 +01:00
natsoni
fc415372bf Fix P2SH / P2PKH detection on Liquid address page 2024-02-05 11:22:14 +01:00
softsimon
47d221fd3b Merge pull request #4647 from mempool/mononaut/better-coinjoin-goggles
Improve Goggles coinjoin detection
2024-02-05 18:13:12 +08:00
Mononaut
7e5e85c8b9 Improve Goggles coinjoin detection 2024-02-04 21:47:31 +00:00
Felipe Knorr Kuhn
9c72d1df3b Sync assets from the mempool CDN 2024-02-04 09:18:50 -08:00
Felipe Knorr Kuhn
933bc47b44 Add DRY_RUN and MEMPOOL_CDN options 2024-02-04 09:17:42 -08:00
softsimon
a15729c38f Merge pull request #4640 from mempool/fix-liquid-frontend-crash
Fix Liquid frontend crash
2024-02-04 23:38:32 +08:00
softsimon
229e122daf Merge branch 'master' into fix-liquid-frontend-crash 2024-02-04 23:14:35 +08:00
softsimon
16846d526c Merge pull request #4616 from mempool/natsee/liquid-audit-dashboard
Feature: Liquid Federation Audit Dashboard
2024-02-04 22:05:02 +08:00
natsoni
19a4c10860 Fix date alignment in utxos table 2024-02-04 14:57:04 +01:00
natsoni
ae38c3bf81 Update CLA for natsoni 2024-02-04 13:06:49 +01:00
natsoni
575c407098 Remove SQL transactions in federation utxos indexing 2024-02-04 13:03:41 +01:00
natsoni
03e4a21bce Fix styling issue in peg and utxo widgets 2024-02-04 13:01:07 +01:00
natsoni
7bfc649042 Add seo title to pegs and utxos tables 2024-02-04 12:34:40 +01:00
Felipe Knorr Kuhn
e478fb2279 Merge branch 'master' into fix-liquid-frontend-crash 2024-02-03 09:17:53 -08:00
softsimon
9494d2fb0b Merge pull request #4631 from mempool/mononaut/fix-null-err
Fix missing optional chain on bestDescendant access
2024-02-03 21:59:37 +08:00
softsimon
b44ec76130 Merge pull request #4637 from mempool/mononaut/summaries-indexing-error
More robust error handling and logging during summaries indexing
2024-02-03 20:39:09 +08:00
softsimon
dd7bd9e397 Merge pull request #4639 from mempool/mononaut/acc-data-catch
Fix error handling in acceleration data polling
2024-02-02 23:57:41 +08:00
Mononaut
0bf0d79ee4 Fix error handling in acceleration data polling 2024-02-02 15:31:10 +00:00
softsimon
788a8693ee Merge pull request #4523 from jamesblacklock/docker-bugfix
fix bug in backend Docker `start.sh` script
2024-02-02 11:40:45 +08:00
natsee
163c0b6d78 Liquid peg outs address indexing: support for duplicates and minor fixes 2024-02-01 19:29:31 +01:00
natsee
7ab5b2a2b7 Add check for mempoolBlocks length in mempool subscription 2024-02-01 12:13:34 +01:00
nymkappa
f3fd70a846 Merge branch 'master' into nymkappa/mega-branch 2024-01-30 23:17:26 +01:00
James Blacklock
770b6dfd19 Merge branch 'master' into docker-bugfix 2024-01-30 15:50:03 -05:00
Mononaut
db8ba7c938 More robust error handling and logging during summaries indexing 2024-01-30 16:42:55 +00:00
wiz
e4d92c8fe0 Merge pull request #4629 from mempool/wiz/add-new-prod-servers
ops: Add new prod servers for fallback/replication
2024-01-30 10:18:10 -05:00
natsee
1e15428a63 Liquid Audit: fix i18n 2024-01-30 15:11:51 +01:00
natsee
f4de3a44e0 Liquid: Add address column in recent pegs table 2024-01-30 14:25:08 +01:00
natsee
e69ba7e884 Liquid Federation indexing: clean up logging 2024-01-30 11:55:59 +01:00
softsimon
b4906a5e8a Merge pull request #4626 from mempool/mononaut/fix-pool-dominance
Fix pools dominance chart
2024-01-30 17:21:49 +07:00
natsee
73e6045549 Liquid: Add support for peg outs display 2024-01-30 11:11:30 +01:00
dependabot[bot]
5f3f483546 Bump mysql2 from 3.7.0 to 3.9.1 in /backend
Bumps [mysql2](https://github.com/sidorares/node-mysql2) from 3.7.0 to 3.9.1.
- [Release notes](https://github.com/sidorares/node-mysql2/releases)
- [Changelog](https://github.com/sidorares/node-mysql2/blob/master/Changelog.md)
- [Commits](https://github.com/sidorares/node-mysql2/compare/v3.7.0...v3.9.1)

---
updated-dependencies:
- dependency-name: mysql2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-30 02:07:07 +00:00
Mononaut
ba8ea7d0d1 Handle Redis errors and disconnects 2024-01-30 01:10:36 +00:00
Mononaut
e458196bff Fix missing optional chain on bestDescendant access 2024-01-29 23:15:21 +00:00
Mononaut
2637636f27 Fix pool dominance sorting 2024-01-29 16:59:13 +00:00
natsee
639fc3dd5f Liquid audit: Add recent pegs widget and table 2024-01-29 17:06:25 +01:00
natsee
451a61e5fc Reformat UTXOs widget to Peg Ins widget 2024-01-29 12:22:47 +01:00
nymkappa
b2a130bb17 [doc] fix copy, formatting and hide accelerator doc title if non official instance 2024-01-29 11:45:14 +01:00
natsee
c39ca0270e Fix elements_pegs bitcoinaddress field 2024-01-29 11:36:58 +01:00
natsee
b6e5a059c9 Liquid: minor changes on audit display 2024-01-29 11:06:51 +01:00
hunicus
a3055e20f4 Fix signet and testnet docs pages 2024-01-29 01:57:06 -05:00
wiz
3ac70b3860 ops: Add new prod servers for fallback/replication 2024-01-29 00:05:16 -05:00
natsee
71f73835da Liquid Federation: filter out change UTXOs from table 2024-01-28 21:46:31 +01:00
natsee
59128c8ca0 Audit dashboard: merge utxos and addresses tables in same page 2024-01-28 20:07:41 +01:00
softsimon
08272c7f87 Display pool tags on dashboard 2024-01-29 01:50:46 +07:00
natsee
36d3734d55 Liquid Federation dashboard: minor changes 2024-01-28 18:26:00 +01:00
softsimon
c9c477c88f Merge pull request #4622 from mempool/mononaut/beta-accelerator
Add beta tag to accelerator dashboard nav item
2024-01-28 17:39:51 +07:00
softsimon
8806b8332b Merge pull request #4621 from mempool/mononaut/acceleration-list
Fix acceleration list css, move to /acceleration/list
2024-01-28 17:37:24 +07:00
softsimon
c7a38c78d2 Merge pull request #4619 from mempool/nymkappa/halving-widget
[mining] update halving widget to be more human readable
2024-01-28 17:31:05 +07:00
nymkappa
2d189ca3f6 Merge branch 'master' into nymkappa/halving-widget 2024-01-28 09:50:39 +01:00
softsimon
4b798730b1 Merge pull request #4623 from mempool/mononaut/goggles-index-config
Goggles indexing config & rate limit
2024-01-28 15:24:45 +07:00
Mononaut
bbb0aea0d1 Fix pools dominance chart 2024-01-27 22:25:42 +00:00
nymkappa
57c7df4f1c Merge pull request #4625 from mempool/mononaut/double-time-units
dual-unit app-time halving countdown
2024-01-27 20:25:34 +01:00
Mononaut
87910a6eb7 Display halving countdown with double units 2024-01-27 19:11:43 +00:00
nymkappa
ea1b74dcef [doc] add accelerator rest api documentation 2024-01-27 19:35:16 +01:00
Mononaut
09e38ac177 Goggles indexing config & rate limit 2024-01-27 18:22:58 +00:00
natsee
5b93d39d73 Fix duplicate api call to audit status 2024-01-27 19:19:14 +01:00
Mononaut
4e5ebabc54 Add beta tag to accelerator dashboard tab 2024-01-27 18:03:53 +00:00
Mononaut
a79e1aec1c Fix acceleration list css, move to /acceleration/list 2024-01-27 16:45:18 +00:00
nymkappa
085d40a4e3 Merge branch 'master' into nymkappa/mega-branch 2024-01-27 16:27:25 +01:00
nymkappa
057abbb6c1 [mining] update halving widget to be more human readable 2024-01-27 16:16:32 +01:00
natsee
1a2844ffdf Liquid dashboard: Fix double api call 2024-01-26 20:49:48 +01:00
natsee
7102a72f84 Remove beta tag to Liquid Federation Audit 2024-01-26 19:11:38 +01:00
natsee
87e328504f Liquid: Fix audit updating conditions 2024-01-26 18:52:07 +01:00
softsimon
520e79aec4 Merge pull request #4615 from mempool/mononaut/halvenening
Fix halving fireworks
2024-01-26 23:56:18 +07:00
softsimon
ee6422c982 Merge pull request #4609 from afahrer/master
Channel search results showing up during TX search
2024-01-26 23:43:47 +07:00
wiz
e8ca8e7ec1 ops: Add redis to prod installer 2024-01-26 10:51:44 -05:00
wiz
b110f86b48 ops: Add new nginx hot cacher 2024-01-26 10:43:03 -05:00
wiz
5a7a78cddc ops: Add new nginx hot cacher 2024-01-26 10:40:21 -05:00
wiz
c7862e19c2 ops: Add /api/v1/fees/recommended to warm cache 2024-01-26 10:26:42 -05:00
softsimon
3610908171 Update rust-gbt package lock version 2024-01-26 21:48:21 +07:00
softsimon
87c336734d Merge pull request #4612 from mempool/mononaut/update-rust
Update rust-toolchain to 1.65
2024-01-26 21:45:40 +07:00
hunicus
89d805b500 Merge branch 'master' into hunicus/move-on-in-it 2024-01-26 08:40:40 -05:00
softsimon
bad3992397 Merge pull request #4505 from natsee/fix-overflow-pool-ranking
Fix overflow on mining pool ranking table
2024-01-26 16:13:29 +07:00
nymkappa
edb4c8d9ad Merge branch 'master' into fix-overflow-pool-ranking 2024-01-25 22:33:29 +01:00
nymkappa
565a881f3b Merge branch 'master' into nymkappa/mega-branch 2024-01-25 18:49:13 +01:00
natsee
d1d8f77b29 Fix eslint 2024-01-25 15:56:25 +01:00
natsee
c957692726 Merge branch 'natsee/liquid-federation-audit' into natsee/liquid-audit-dashboard 2024-01-25 15:22:47 +01:00
natsee
16f0830f2c Fix conflict in database-migration 2024-01-25 15:19:46 +01:00
natsee
b6d2008e97 Merge branch 'master' into natsee/liquid-federation-audit 2024-01-25 15:17:51 +01:00
natsee
a6b584d964 Liquid: Federation Audit Dashboard 2024-01-25 15:08:15 +01:00
softsimon
e81d1e273a Merge pull request #4550 from mempool/orangesurf/trademark0103
update trademarks
2024-01-25 15:46:12 +07:00
Mononaut
dbe7ebe530 Fix halving fireworks 2024-01-25 01:51:01 +00:00
Mononaut
4e007acd84 Update rust-toolchain to 1.65 2024-01-24 18:53:59 +00:00
softsimon
4fe745817c Merge pull request #4137 from mempool/mononaut/multi-address-tracking
Multi address tracking
2024-01-24 23:14:00 +07:00
softsimon
09ce1bd458 Merge pull request #4608 from mempool/mononaut/goggle-index-bugfix
Fix version update & error handling in Goggles indexing
2024-01-24 23:08:31 +07:00
Mononaut
09a727c00d Fix more Goggles indexing bugs 2024-01-24 12:18:42 +00:00
afahrer
f7f1eb067b $ match. fix transaction starting with number 2024-01-23 22:56:17 -05:00
afahrer
74d94579f9 Channel search results showing up during TX search 2024-01-23 20:48:49 -05:00
orangesurf
885331fe4a Remove space from footer 2024-01-23 18:34:43 +00:00
Mononaut
8ca2b2b5c0 Fix version update & error handling in Goggles indexing 2024-01-23 17:20:57 +00:00
softsimon
58f143f867 Merge pull request #4605 from mempool/mononaut/goggle-index
Goggle Indexing
2024-01-24 00:16:24 +07:00
softsimon
a19ffb884f Fixing broken info-link 2024-01-24 00:15:10 +07:00
softsimon
2faca121d3 Merge pull request #4526 from mempool/mononaut/mined-goggles
Mined Goggles
2024-01-24 00:13:43 +07:00
softsimon
8f99d2ba58 Merge pull request #4604 from mempool/simon/clear-tx-cache
Clear txCache when switching network
2024-01-23 23:47:40 +07:00
nymkappa
585732e438 Merge branch 'master' into orangesurf/trademark0103 2024-01-23 17:32:58 +01:00
Mononaut
0cddfcfa64 Fix missing quotes on multi-address-tracking error msg 2024-01-23 14:04:15 +00:00
Mononaut
aa0948a154 Add multi-address-tracking limit config 2024-01-23 13:36:42 +00:00
Mononaut
8f7895cb2e Track dropped txs in multi-address subscription 2024-01-23 13:36:42 +00:00
Mononaut
77a526b91c Normalize scriptpubkeys to lowercase 2024-01-23 13:36:42 +00:00
Mononaut
ccd9642a01 Deduplicate address validation code 2024-01-23 13:36:41 +00:00
Mononaut
8642956dc2 Add track-scriptpubkeys websocket subscription 2024-01-23 13:36:41 +00:00
Mononaut
57c3861ca6 Support multi address websocket subscriptions 2024-01-23 13:36:41 +00:00
Mononaut
82920f621f Fix Goggles indexing when summaries disabled 2024-01-23 13:33:59 +00:00
softsimon
de7db08ae3 Merge pull request #4601 from mempool/natsee/seach-bar-liquid-assets
Search bar: suggest Liquid assets
2024-01-23 20:07:06 +07:00
softsimon
431f60d9c0 Use current network name in search result 2024-01-23 18:56:32 +07:00
softsimon
da545dbcf1 Merge branch 'master' into natsee/seach-bar-liquid-assets 2024-01-23 17:14:26 +07:00
natsee
b7feb0d43d Merge branch 'natsee/liquid-federation-audit' into natsee/liquid-audit-dashboard 2024-01-23 09:48:36 +01:00
natsee
cef060be2d Only include count in federation address and UTXO queries 2024-01-23 09:46:15 +01:00
softsimon
c570cc1e73 Merge branch 'master' into simon/clear-tx-cache 2024-01-23 11:20:38 +07:00
softsimon
6339cc8d59 Merge pull request #4597 from mempool/knorrium/cache_assets_gha
Cache build assets to prevent rate limiting
2024-01-23 11:20:06 +07:00
Felipe Knorr Kuhn
fe079a72be Clean up action 2024-01-22 20:06:27 -08:00
Felipe Knorr Kuhn
c789797d2d Revert "Remove the download artifacts step"
This reverts commit 479007da55.
2024-01-22 20:05:20 -08:00
Felipe Knorr Kuhn
479007da55 Remove the download artifacts step 2024-01-22 19:56:45 -08:00
Mononaut
7405cf8336 Add block classification indexing 2024-01-23 01:44:19 +00:00
Felipe Knorr Kuhn
f955c1b0f4 Merge branch 'master' into knorrium/cache_assets_gha 2024-01-22 16:53:19 -08:00
Felipe Knorr Kuhn
99f7201ec5 Cache build assets to prevent rate limiting 2024-01-22 16:51:08 -08:00
Mononaut
0c9c79c86c Enable goggles on supported mined block visualizations 2024-01-22 22:32:19 +00:00
Mononaut
1507003c19 Save goggle flags in audit templates & block summaries 2024-01-22 22:32:18 +00:00
softsimon
5ecdf1988e Clear txCache when switching network
fixes #4603
2024-01-23 01:23:51 +07:00
softsimon
5b622c7786 Merge pull request #4589 from isghe/fix-copyright-2024
about: fix copyright 2024
2024-01-22 22:19:20 +07:00
natsee
392ea35d51 Skeleton audit dashboard 2024-01-22 16:03:55 +01:00
softsimon
552ba98de2 Pull from transifex 2024-01-22 21:30:03 +07:00
softsimon
7a2f8bcce2 Capitalizing title 2024-01-22 21:17:43 +07:00
softsimon
d53b5e4a68 Capitalizing title 2024-01-22 21:16:24 +07:00
softsimon
c2bd6419bb Acceleration i18n fixes 2024-01-22 21:13:41 +07:00
natsee
8f7cd70882 Add throttleTime to avoid too frequent calls to backend 2024-01-22 14:19:01 +01:00
natsee
fa90eb84fc Truncate elements_pegs and add primary key instead of drop/create 2024-01-22 13:59:11 +01:00
natsee
00613fe613 Liquid: suggest asset in search bar results 2024-01-22 11:45:07 +01:00
natsee
0663cc2cfa Fix search bar result overflow 2024-01-22 11:29:41 +01:00
natsee
81a09e9dba Add Liquid Peg-in column to Federation UTXOs list 2024-01-21 13:51:50 +01:00
natsee
cd713c61b3 Liquid: wip on Federation audit dashboard 2024-01-21 13:33:20 +01:00
natsee
752eba767a Liquid: add BTC reserves to L-BTC widget and make it dynamic 2024-01-21 13:19:02 +01:00
natsee
de2842b62a Add pegtxid and pegindex data to federation_txos table 2024-01-21 13:04:34 +01:00
orangesurf
a89af41c48 Update bisq-dashboard.component.ts
Switch from ® to &reg; for better compatibility
2024-01-21 11:20:11 +00:00
orangesurf
c751e10da8 Update seo.service.ts
Switch from ® to &reg; for better compatibility
2024-01-21 11:19:01 +00:00
orangesurf
2750f1789c Update index.ts
Switch from ® to &reg; for better compatibility
2024-01-21 11:17:50 +00:00
orangesurf
aaf378ed42 Update index.liquid.html
Switch from ® to &reg; for better compatibility
2024-01-21 11:15:11 +00:00
orangesurf
bc5e03deb5 Update index.bisq.html
Switch from ® to &reg; for better compatibility
2024-01-21 11:13:55 +00:00
orangesurf
8759d49daf Merge branch 'master' into orangesurf/trademark0103 2024-01-21 10:29:40 +00:00
natsee
4b10e32e73 Liquid: add indexing process of Federation utxos 2024-01-20 15:15:15 +01:00
softsimon
6671746fc5 Fixing i18n build error and extracting new i18n 2024-01-20 20:07:25 +07:00
wiz
10bb6caf97 ops: Fix elements crontab 2024-01-20 07:20:40 -05:00
wiz
b52946e6f5 ops: Fix bitcoin crontab 2024-01-20 07:20:18 -05:00
wiz
aac094b965 ops: Add VA1 nodes to bitcoin.conf peer list 2024-01-20 06:42:46 -05:00
softsimon
8ca14e7f19 Merge pull request #4488 from mempool/simon/acceleration-tab
Acceleration tab
2024-01-19 23:35:23 +07:00
softsimon
84182b2512 Merge pull request #4586 from mempool/mononaut/acceleration-tab-changes
Acceleration tab changes
2024-01-19 23:34:42 +07:00
softsimon
a45e4a6ec5 Merge pull request #4585 from mempool/mononaut/accelerator-dashboard-polish
Accelerator dashboard tweaks
2024-01-19 23:27:33 +07:00
Mononaut
a5eeaaa91a AccDash: label transactions -> request 2024-01-19 14:40:11 +00:00
nymkappa
59e30027a5 Merge branch 'master' into nymkappa/mega-branch 2024-01-19 09:49:00 +01:00
softsimon
7fd8ae375c Asset group title fix 2024-01-19 10:24:04 +07:00
softsimon
9e240e55ce Default Liquid asset child should be /featured 2024-01-19 00:15:51 +07:00
Isidoro Ghezzi
d82a5281fc about: fix copyright 2024
add contributors/isghe.txt

using contributors/wiz.txt as template
2024-01-18 16:56:08 +01:00
nymkappa
8054e2d79a [accelerator] fix success rate stat value 2024-01-18 15:54:04 +01:00
softsimon
af7d437d09 Merge pull request #4584 from mempool/nymkappa/add-internal-routes-to-bitcoin-core
[bitcoin core] Add internal routes to bitcoin core
2024-01-18 20:20:59 +07:00
nymkappa
f6d7790512 [sponsors] allow setting up custom host for the sponsor component 2024-01-18 12:13:52 +01:00
softsimon
e373f36765 Merge pull request #4460 from natsee/lightning-dashboard-ownership
Add % ownership in capacity table (LN dashboard)
2024-01-18 16:41:21 +07:00
nymkappa
8cb49ba8e3 Merge branch 'master' into lightning-dashboard-ownership 2024-01-17 17:42:53 +01:00
Mononaut
d2270ffc26 Move acceleration tab icon, fix responsive issues 2024-01-15 23:39:51 +00:00
Mononaut
5009ca909c AccDash: out-of-band fees -> bid boost 2024-01-15 22:52:42 +00:00
Mononaut
6a189c484a AccDash: accelerated -> pending 2024-01-15 22:34:12 +00:00
nymkappa
ed9826b2d8 [bitcoin core] internal core api from camel case to kebab case 2024-01-15 16:12:58 +01:00
nymkappa
0225455784 Fix merge conflict with 2013dc6d8b 2024-01-15 10:05:37 +01:00
nymkappa
ee721b3e1c Merge branch 'master' into nymkappa/mega-branch 2024-01-15 10:01:38 +01:00
nymkappa
f161f7e8e2 [bitcoin core] fix getMempoolAncestors verbose param 2024-01-15 10:00:01 +01:00
nymkappa
b38bbb9513 [bitcoin core] add missing verbose params to bitcoin core internal routes 2024-01-15 09:59:35 +01:00
nymkappa
f095913538 [bitcoin core] add internal routes to bitcoin core rpc 2024-01-15 09:59:32 +01:00
softsimon
91fad7ff65 Merge pull request #4583 from mempool/mononaut/goggles-inscription-bug
Fix goggles inscription detection bug
2024-01-15 10:25:31 +07:00
Mononaut
00b8f001b0 Fix goggles inscription detection bug 2024-01-15 02:47:29 +00:00
softsimon
73d4ea75de Merge pull request #4543 from natsee/cross-network-address-search
Search bar feature: network based regex and address matches
2024-01-14 18:38:50 +07:00
softsimon
0722c221c7 Minor adjustments 2024-01-14 18:27:30 +07:00
softsimon
693d8c4b3b Merge pull request #4577 from mempool/translations_frontend-src-locale-messages-xlf--master_nb
Updates for file frontend/src/locale/messages.xlf in nb
2024-01-14 10:37:22 +07:00
softsimon
2e5bb000ab Merge pull request #4579 from mempool/knorrium/add_seconds_to_block_list
Add seconds to block timestamp in the mining pool view and blocks list
2024-01-14 10:34:27 +07:00
softsimon
203e2040d7 Merge pull request #4572 from mempool/nymkappa/fix-footer
[footer] fix css
2024-01-14 10:32:49 +07:00
softsimon
a987983413 Merge pull request #4575 from mempool/simon/dashboard-more-skeleton-loaders
Adding dashboard skeleton loaders
2024-01-14 10:08:39 +07:00
softsimon
227c597cb6 Merge pull request #4578 from mempool/knorrium/add_seconds_to_block_view
Add seconds to the block view timestamp
2024-01-14 10:08:03 +07:00
Felipe Knorr Kuhn
a8442a3467 Add seconds to block timestamp in the mining pool view and blocks list 2024-01-13 18:11:13 -08:00
Felipe Knorr Kuhn
65236c7b08 Add seconds to the block view timestamp 2024-01-13 13:55:12 -08:00
transifex-integration[bot]
e4d7034d81 Translate frontend/src/locale/messages.xlf in nb
100% reviewed source file: 'frontend/src/locale/messages.xlf'
on 'nb'.
2024-01-13 16:57:03 +00:00
wiz
2ca6dc51da ops: Increase nginx proxy_read_timeout to 2m 2024-01-13 12:22:38 +09:00
wiz
fdd14fd6dc ops: Disable disk cache for production mainnet 2024-01-13 12:22:23 +09:00
softsimon
cafcb4f9a6 Merge pull request #4576 from mempool/knorrium/cypress_13_6_2
Update Cypress to v13.6.2
2024-01-13 09:08:45 +07:00
Felipe Knorr Kuhn
a06bf86b95 Update Cypress to v13.6.2 2024-01-12 13:06:11 -08:00
nymkappa
5c43c17261 Merge branch 'master' into lightning-dashboard-ownership 2024-01-12 18:45:45 +01:00
natsee
3b8de5057c Check env flags before cross network address search 2024-01-12 18:04:49 +01:00
natsee
0ec40eafb4 Remove hard-coded timestamp for regexes 2024-01-12 17:21:07 +01:00
natsee
9a7e22806d Merge branch 'master' into cross-network-address-search 2024-01-12 17:05:57 +01:00
softsimon
d546f2eba5 Merge pull request #4574 from mempool/dependabot/npm_and_yarn/frontend/follow-redirects-1.15.5
Bump follow-redirects from 1.15.3 to 1.15.5 in /frontend
2024-01-12 22:42:27 +07:00
softsimon
46fdb5b30d Adding dashboard skeleton loaders 2024-01-12 18:08:57 +07:00
dependabot[bot]
a23088458b Bump follow-redirects from 1.15.3 to 1.15.5 in /frontend
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.3 to 1.15.5.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.3...v1.15.5)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-12 10:21:43 +00:00
softsimon
b86b38398e Merge pull request #4558 from mempool/dependabot/npm_and_yarn/frontend/cypress-fail-on-console-error-5.1.0
Bump cypress-fail-on-console-error from 5.0.0 to 5.1.0 in /frontend
2024-01-12 17:20:43 +07:00
softsimon
600cbae739 Merge pull request #4557 from mempool/dependabot/npm_and_yarn/backend/mysql2-3.7.0
Bump mysql2 from 3.6.0 to 3.7.0 in /backend
2024-01-12 17:19:52 +07:00
nymkappa
7f62a0f9b5 [footer] fix css RTL issues 2024-01-12 10:50:41 +01:00
softsimon
978e0bff24 Merge pull request #4534 from natsee/fix-search-result-duplicate-address
Fix duplicate address in search results
2024-01-12 15:43:53 +07:00
softsimon
5291828e6a Merge branch 'master' into fix-search-result-duplicate-address 2024-01-12 15:39:38 +07:00
softsimon
ecb696661e Merge pull request #4570 from mempool/mononaut/sigop-faqs
Add sigop related FAQ entries
2024-01-12 09:54:20 +07:00
softsimon
e9a67adf4f Adding links to FAQ sections from TX page 2024-01-12 09:50:33 +07:00
nymkappa
5389d19850 [footer] fix css 2024-01-11 16:26:09 +01:00
Mononaut
439177a78f Add sigop related FAQ entries 2024-01-10 22:07:01 +00:00
dependabot[bot]
367f70c3b3 Bump mysql2 from 3.6.0 to 3.7.0 in /backend
Bumps [mysql2](https://github.com/sidorares/node-mysql2) from 3.6.0 to 3.7.0.
- [Release notes](https://github.com/sidorares/node-mysql2/releases)
- [Changelog](https://github.com/sidorares/node-mysql2/blob/master/Changelog.md)
- [Commits](https://github.com/sidorares/node-mysql2/compare/v3.6.0...v3.7.0)

---
updated-dependencies:
- dependency-name: mysql2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-10 14:40:20 +00:00
softsimon
6553de53b8 Merge pull request #4566 from mempool/mononaut/rust-clean
Clean rust-gbt directory before build
2024-01-10 21:39:34 +07:00
Mononaut
8336a00aea Clean rust-gbt directory before build 2024-01-10 14:32:37 +00:00
softsimon
f694d5333a Merge pull request #4561 from mempool/mononaut/fix-prices
Fix bad coinbase price url, switch to median prices
2024-01-10 11:21:11 +07:00
softsimon
aad288c0d9 Merge pull request #4554 from mempool/mononaut/unmineable-txs
Handle unmineable transactions in GBT implementations
2024-01-10 00:18:41 +07:00
Mononaut
30d58d9971 Restore GBT result size sanity check 2024-01-09 17:08:25 +00:00
Mononaut
89d37f0058 Fix unmineable tx handling 2024-01-09 16:26:05 +00:00
softsimon
7cd0c4f352 Merge pull request #4530 from natsee/update-docs-api
Add endpoints to docs api
2024-01-09 23:07:02 +07:00
softsimon
7de3d789b3 Merge branch 'master' into update-docs-api 2024-01-09 22:58:16 +07:00
softsimon
f9dfb3b2b1 Merge pull request #4556 from mempool/mononaut/smooth-mempool-blocks
Smooth out irregular mempool block updates
2024-01-09 11:16:25 +07:00
softsimon
17427b7970 Merge pull request #4560 from mempool/mononaut/fee-sanity
Additional fee recommendation sanity checks
2024-01-09 10:41:52 +07:00
softsimon
6da4f34656 Merge pull request #4542 from mempool/mononaut/unsub-track-block
unsubscribe from mempool block tracking
2024-01-09 08:46:15 +07:00
Mononaut
0230f95001 Fix bad coinbase price url, switch to median prices 2024-01-08 22:39:51 +00:00
Mononaut
d5c5ae0e09 Additional fee recommendation sanity checks 2024-01-08 16:33:19 +00:00
Mononaut
fc8eca4c26 Handle stale smoothed mempool block updates 2024-01-08 14:42:00 +00:00
dependabot[bot]
9485dfe2ce Bump cypress-fail-on-console-error from 5.0.0 to 5.1.0 in /frontend
Bumps [cypress-fail-on-console-error](https://github.com/nils-hoyer/cypress-fail-on-console-error) from 5.0.0 to 5.1.0.
- [Release notes](https://github.com/nils-hoyer/cypress-fail-on-console-error/releases)
- [Commits](https://github.com/nils-hoyer/cypress-fail-on-console-error/compare/5.0.0...5.1.0)

---
updated-dependencies:
- dependency-name: cypress-fail-on-console-error
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-08 02:48:43 +00:00
Mononaut
5f66a95402 Smooth out irregular mempool block updates 2024-01-07 18:02:11 +00:00
Mononaut
d665d2a12c Handle unmineable transactions in GBT implementations 2024-01-06 04:20:19 +00:00
James Blacklock
5f1180118a Merge branch 'master' into docker-bugfix 2024-01-04 12:10:31 -05:00
softsimon
f7e7072dbc Merge pull request #4548 from natsee/liquid-missing-featured-route
[Liquid] Fix missing assets/featured route
2024-01-04 17:14:12 +07:00
orangesurf
a0d0650e2a update trademarks 2024-01-03 19:09:59 +01:00
nymkappa
64f6775c68 [database] increase default pool size to 100 connections 2024-01-03 15:12:11 +01:00
natsee
f73350f7d6 [Liquid] Fix missing assets/featured route 2024-01-03 14:21:11 +01:00
natsee
bfdab0ac48 Merge branch 'master' into cross-network-address-search 2024-01-03 13:37:16 +01:00
natsee
b9776263dc Exclude date and timestamp results for non-bitcoin networks 2024-01-03 13:36:33 +01:00
softsimon
56dce6b28c Merge pull request #4527 from natsee/fix-faq-nav-bar-overflow
Fix faq nav bar overflow
2024-01-03 11:28:53 +07:00
Mononaut
c1785993a8 Fix websocket subscription logging 2024-01-02 16:26:57 +00:00
softsimon
0c956be136 Merge pull request #4545 from mempool/simon/block-view-accel-flag-check-fix
Acceleration flag check on block/tx view
2024-01-02 23:18:55 +07:00
softsimon
a498f9205b Fix error on transaction page when acceleration is disabled 2024-01-02 11:25:50 +07:00
softsimon
09041c50ef Acceleration flag check on block view 2024-01-02 10:35:52 +07:00
natsee
dd31d5a665 Fix E2E error: change regex address minimum length 2024-01-01 14:52:02 +01:00
natsee
3e1b85e32c Add search addresses from cross networks feature 2024-01-01 13:54:37 +01:00
Mononaut
51bfffbf0e unsubscribe from mempool block tracking 2024-01-01 12:01:53 +00:00
wiz
9b6e60bfba ops: Add production/redis.conf 2024-01-01 08:03:34 +09:00
wiz
8492007a48 Merge pull request #4541 from mempool/mononaut/optimize-new-block-ws
Optimize websocket updates on new block
2024-01-01 07:48:35 +09:00
natsee
bd34d71d8b Update regexes in regex.utils.ts 2023-12-31 23:46:06 +01:00
Mononaut
23ececca95 Optimize websocket updates on new block 2023-12-31 18:07:39 +00:00
wiz
fb61fddcc4 Merge pull request #4512 from mempool/simon/acceleration-sounds
Acceleration sounds
2023-12-31 04:22:33 +09:00
wiz
24ec12e7a1 Merge pull request #4517 from mempool/orangesurf/goggles
Mempool Goggles™
2023-12-31 04:22:17 +09:00
wiz
681f9a1c69 ops: Enable redis for production mainnet 2023-12-31 03:39:23 +09:00
wiz
fab82551cf Remove old GPLv3 license file, rename AGPLv3 license to COPYING 2023-12-31 03:22:14 +09:00
natsee
6cea6ceb7e Merge branch 'upstream/master' into search-bar-network-regex 2023-12-30 19:18:49 +01:00
softsimon
118eef6f0c Merge pull request #4537 from mempool/mononaut/acc-preview-highlight
Highlight accelerations in block previews & non-audit mode
2023-12-30 10:39:57 +07:00
softsimon
626f95d802 Merge pull request #4521 from mempool/mononaut/responsive-acceleration-dash
Fix widget responsiveness on acceleration dashboard
2023-12-29 23:29:56 +07:00
Mononaut
ab3ce5ece0 Highlight accelerations in blocks in previews & non-audit mode 2023-12-29 14:13:13 +00:00
natsee
d2a5adbd9d Fix duplicate address field in search results 2023-12-28 15:34:36 +01:00
natsee
93b074edf0 Add endpoints to docs api 2023-12-27 18:50:41 +01:00
softsimon
577b1a9f66 Merge pull request #4525 from mempool/mononaut/nogl-fee-chart
Fix missing mempool fee chart when webgl disabled
2023-12-27 13:15:35 +07:00
softsimon
d9c28643f4 Merge pull request #4091 from dni/dni-patch-1
Update liquid-master-page.component.html
2023-12-27 13:11:34 +07:00
James Blacklock
3f305207f9 Merge branch 'master' into docker-bugfix 2023-12-25 03:27:26 -05:00
softsimon
2fb3e4e4e5 Merge pull request #4516 from natsee/toggle-expand-rbf-history
Expand toggle for RBF history view
2023-12-23 15:19:19 +07:00
natsee
40f2d553e2 Fix faq nav bar overflow 2023-12-22 10:39:40 +01:00
James Blacklock
8e9a187a15 Merge branch 'master' into docker-bugfix 2023-12-21 13:02:25 -05:00
Mononaut
0370cc896c Fix missing mempool fee chart when webgl disabled 2023-12-21 13:06:52 +00:00
softsimon
d6291ecd52 Merge pull request #4519 from Start9Labs/update/start9
update startOS info
2023-12-21 15:22:49 +07:00
softsimon
9d82926d6f Merge pull request #4518 from pedromvpg/master
Dot the i's on liquid logo
2023-12-21 15:20:46 +07:00
James Blacklock
cd964d37e8 fix bug in backend Docker start.sh script 2023-12-20 17:03:06 -05:00
James Blacklock
ec4c418c22 sign contributor agreement 2023-12-20 17:02:12 -05:00
wiz
07f9410d45 ops: Fix elements unix socket path 2023-12-21 05:05:59 +09:00
Mononaut
c3675d5b1c Fix widget responsiveness on acceleration dashboard 2023-12-20 18:30:19 +00:00
natsee
f471541907 Fix fade out on RBF history 2023-12-20 16:30:15 +01:00
Matt Hill
4f3852bbba One more 2023-12-19 21:49:52 -07:00
Matt Hill
fc36e04dc0 update start9 os and icon 2023-12-19 08:20:21 -07:00
natsee
7f488f5b01 Fade out the bottom of collapsed rbf history 2023-12-19 14:40:37 +01:00
softsimon
1d74a99d2f Update frontend/src/app/components/transaction/transaction.component.ts
Co-authored-by: mononaut <83316221+mononaut@users.noreply.github.com>
2023-12-19 13:17:26 +07:00
Pedro
bd07773b8d Dot the i's on liquid logo 2023-12-18 12:05:05 +00:00
orangesurf
59f8a7199c Fix space 2023-12-18 09:35:14 +00:00
orangesurf
03b78015ba Remove redundant semicolons 2023-12-18 09:22:28 +00:00
orangesurf
f72683dc19 Add Mempool Goggles TM 2023-12-18 09:18:55 +00:00
natsee
75b3bc6249 Expand toggle for RBF history view 2023-12-17 20:26:34 +01:00
softsimon
f915ff3f91 Merge pull request #4487 from mempool/nymkappa/hashrate-indexing-message
[mining] show proper message when we have less than 2 weeks worth of mining pool hashrate data
2023-12-17 21:33:18 +07:00
softsimon
01131360c2 Merge branch 'master' into nymkappa/hashrate-indexing-message 2023-12-17 21:31:59 +07:00
softsimon
30da419fb4 Merge pull request #4515 from mempool/mononaut/faster-goggles
Faster goggles
2023-12-17 18:44:39 +07:00
softsimon
e8c48f6f23 Merge branch 'master' into mononaut/faster-goggles 2023-12-17 18:08:41 +07:00
softsimon
ca7167870a Merge pull request #4510 from mempool/mononaut/smooth-goggle-transition
Smoother goggles color change transition
2023-12-17 18:08:28 +07:00
softsimon
7bdb2f41a5 Merge branch 'master' into mononaut/smooth-goggle-transition 2023-12-17 18:06:54 +07:00
softsimon
3e505d37c9 Merge pull request #4506 from mempool/mononaut/goggles
Mempool Goggles icon, tooltip, FAQ
2023-12-17 18:06:26 +07:00
Mononaut
78857102f8 Move goggles icon inside generic svg-images component 2023-12-17 10:57:00 +00:00
Mononaut
8dbf879c37 Add Goggles FAQ entry 2023-12-17 10:56:42 +00:00
Mononaut
bc89fd5b7c Goggles icon, beta tag and info tooltip 2023-12-17 10:56:42 +00:00
Mononaut
a8fd2ac9dc Preserve tx replacement flag 2023-12-17 10:45:26 +00:00
Mononaut
c2f52ac1f3 Avoid repeated tx classification work 2023-12-17 09:57:15 +00:00
softsimon
472a86ffd4 Merge pull request #4391 from 0xBEEFCAF3/patch-1
fix: incorrect `HTTP_PORT` docker compose field in docker README.md
2023-12-17 16:55:13 +07:00
softsimon
21ad37dbec Merge pull request #4143 from mempool/hunicus/readme-enterprise
Add links to enterprise page in readmes
2023-12-17 11:37:36 +07:00
softsimon
10a50ac49f Merge pull request #3794 from mempool/mononaut/liquid-default-block-weight
Restore liquid max block weight to defaults
2023-12-17 11:36:36 +07:00
softsimon
b49e01bf64 Merge pull request #4502 from natsee/bugfix-search-block-number
Search result: do not offer "Go to" if block height > chain tip
2023-12-17 10:50:10 +07:00
softsimon
cc54538937 Merge pull request #4508 from natsee/show-clipboard-blockhash
Show blockhash copy button in block component
2023-12-17 10:22:45 +07:00
softsimon
6014469513 Acceleration sounds 2023-12-15 23:09:24 +07:00
nymkappa
9e88f5ecf8 [typo] platinium -> platinum 2023-12-15 16:58:10 +01:00
nymkappa
041f4f6695 Merge branch 'nymkappa/remove-services-version' into nymkappa/mega-branch 2023-12-15 16:16:12 +01:00
nymkappa
70ca75ac12 Merge branch 'nymkappa/subscription-tag' into nymkappa/mega-branch 2023-12-15 16:16:06 +01:00
Mononaut
b3a68a0db2 Smoother goggles color change transition 2023-12-15 15:05:43 +00:00
wiz
99b57bbec0 Merge pull request #4497 from mempool/simon/acceleration-preview-loader
Acceleration preview loader
2023-12-15 23:39:58 +09:00
natsee
eae044cf66 Show blockhash copy button in block component 2023-12-15 15:38:02 +01:00
nymkappa
8238edb721 [menu] show og rank and active subscription in menu 2023-12-15 14:48:17 +01:00
natsee
0ac0a56ae5 Fix overflow on mining pool ranking table 2023-12-15 12:22:08 +01:00
orangesurf
445d600633 Changes following feedback 2023-12-15 10:37:16 +00:00
wiz
e4751a8274 Merge pull request #4503 from mempool/orangesurf/trademark-updates-2 2023-12-15 19:16:46 +09:00
orangesurf
100936e551 Changes following feedback 2023-12-15 10:04:04 +00:00
softsimon
acff9782cb Merge pull request #4501 from takuabonn/bugfix/4475
update to use cachedRequest
2023-12-15 14:15:07 +07:00
softsimon
b9c60b0820 Merge pull request #4500 from mempool/mononaut/block-viz-filters
Projected block filters
2023-12-15 09:04:19 +07:00
Mononaut
2e531413fa Disable filter UI on mined blocks 2023-12-14 18:09:04 +00:00
natsee
3eb6241c98 Delete variables and use observables in top nodes components 2023-12-14 16:09:54 +01:00
Mononaut
16b9ca6c40 Fix CI unit test circular dependency 2023-12-14 13:30:19 +00:00
natsee
b0c02b16ff Search result: do not offer Go to block 2023-12-14 12:49:11 +01:00
Mononaut
512589dc79 Add fake pubkey filter 2023-12-14 11:29:44 +00:00
natsee
464cffb5c1 Add LN statistics interface 2023-12-14 12:22:00 +01:00
Mononaut
ce195c9133 Fix ECDSA DER signature detection 2023-12-13 16:15:55 +00:00
takuabonn
1fb3de9dc3 update contributors 2023-12-14 01:10:28 +09:00
takuabonn
7cb58ed988 update to use cachedRequest 2023-12-14 00:47:11 +09:00
natsee
97053ab5cf Update contributor agreement file 2023-12-13 15:13:01 +01:00
ncois
39c5792e6f Include % ownership in statistics table on LN dashboard and on ranking pages 2023-12-13 15:08:34 +01:00
Mononaut
c019355c9f Adapt block filter UI for small screens 2023-12-13 11:29:10 +00:00
Mononaut
5777561744 Tidy up block filter code, disable multisig flag 2023-12-13 11:04:45 +00:00
Mononaut
24dbe5d4ee Add block viz filter UI 2023-12-13 11:00:49 +00:00
Mononaut
e12f43e741 Add sighash filter flags 2023-12-13 10:59:56 +00:00
Mononaut
173bc127cb Block viz filters proof of concept 2023-12-13 10:59:56 +00:00
wiz
14e440da6b Merge pull request #4499 from mempool/wiz/license-change-agpl-only
Change dual-licensed GPLv3/AGPLv3 to AGPLv3 only
2023-12-13 19:36:52 +09:00
wiz
93c61f5ed3 Change dual-licensed GPLv3/AGPLv3 to AGPLv3 only 2023-12-13 17:46:51 +09:00
wiz
7a77e86ab2 Merge pull request #4485 from mempool/orangesurf/trademark-updates
Add latest registered trademark information
2023-12-13 17:42:01 +09:00
nymkappa
2013dc6d8b [refactoring] move servics related api calls to its own service 2023-12-12 17:24:58 +01:00
softsimon
d3f7190b7f Acceleration preview loader 2023-12-12 20:49:08 +07:00
nymkappa
590188fe6d [footer] remove services version number 2023-12-12 09:17:46 +01:00
nymkappa
38479db5ca Merge branch 'master' into nymkappa/twitter-handle 2023-12-12 09:10:38 +01:00
nymkappa
ed215aa4cd [menu] only add space after @ username if username already contains @ 2023-12-12 09:07:27 +01:00
wiz
df55497747 Merge branch 'master' into orangesurf/trademark-updates 2023-12-12 15:50:56 +09:00
softsimon
6d5a723ff4 Merge pull request #4491 from mempool/dependabot/github_actions/dtolnay/rust-toolchain-be73d7920c329f220ce78e0234b8f96b7ae60248
Bump dtolnay/rust-toolchain from f361669954a8ecfc00a3443f35f9ac8e610ffc06 to be73d7920c329f220ce78e0234b8f96b7ae60248
2023-12-12 09:11:58 +07:00
orangesurf
9f6f210c38 Merge branch 'master' into orangesurf/trademark-updates 2023-12-11 16:43:45 +00:00
orangesurf
cb1d9753c8 Changes following feedback 2023-12-11 15:26:17 +00:00
dependabot[bot]
05259e9f81 Bump dtolnay/rust-toolchain
Bumps [dtolnay/rust-toolchain](https://github.com/dtolnay/rust-toolchain) from f361669954a8ecfc00a3443f35f9ac8e610ffc06 to be73d7920c329f220ce78e0234b8f96b7ae60248.
- [Release notes](https://github.com/dtolnay/rust-toolchain/releases)
- [Commits](f361669954...be73d7920c)

---
updated-dependencies:
- dependency-name: dtolnay/rust-toolchain
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-11 02:42:17 +00:00
softsimon
e5df1571da Acceleration tab 2023-12-09 22:33:02 +07:00
Armin Sabouri
88d2a3a50d sign CLA for 0xBEEFCAF3 2023-12-08 17:25:02 -05:00
Armin Sabouri
a4810b8be0 fix: incorrect HTTP_PORT docker compose field in docker README.md
The override is [BACKEND_HTTP_PORT defined here](59c513f2a5/docker/backend/start.sh (L7))
2023-12-08 17:25:02 -05:00
nymkappa
5ac432556b [mining] show proper message when we have less than 2 weeks worth of mining pool hashrate data 2023-12-08 17:00:36 +01:00
softsimon
f03acce324 Merge pull request #4483 from TechMiX/hotfix/rtlIssues
fix: RTL issues related to sidenav and global footer
2023-12-08 21:21:57 +07:00
wiz
aff8f2c41f Merge branch 'master' into hotfix/rtlIssues 2023-12-08 23:16:59 +09:00
wiz
88f617611f Merge pull request #4220 from mempool/mononaut/accelerator-dashboard
Accelerator dashboard
2023-12-08 22:26:54 +09:00
Mononaut
2cddc5fdd8 accelerations: not yet 2023-12-08 13:23:51 +00:00
orangesurf
d38381af8b Changes following feedback 2023-12-08 13:08:43 +00:00
Mononaut
aff44d90d5 Rerefactor acceleration dashboard 2023-12-08 13:08:16 +00:00
Mononaut
42f6f0c122 Redesign accelerator dashboard 2023-12-08 13:08:16 +00:00
Mononaut
8599876b26 Refactor accelerator dashboard 2023-12-08 13:08:16 +00:00
Mononaut
e34ee3a34d Fix rebase issues 2023-12-08 13:08:15 +00:00
Mononaut
47de84f03a Accelerator dashboard widget titles: latest -> recent 2023-12-08 13:08:15 +00:00
Mononaut
f071d5e76a Accelerator dashboard fix success criteria 2023-12-08 13:08:15 +00:00
Mononaut
5a55ba2d28 Accelerator dashboard pending widget, fee delta fiat values 2023-12-08 13:08:15 +00:00
Mononaut
2efd474357 Fix accelerator dashboard widget page link css 2023-12-08 13:08:15 +00:00
Mononaut
472a76560f Tidy acceleration dashboard, add missing fields 2023-12-08 13:08:14 +00:00
Mononaut
f26b630aab Fix acceleration dashboard merge issues 2023-12-08 13:08:14 +00:00
Mononaut
b0e73466fa Show mining blockchain blocks on accelerator dashboard 2023-12-08 13:08:14 +00:00
Mononaut
7019e6ec03 Add acceleration fees graph 2023-12-08 13:08:14 +00:00
Mononaut
f409c67125 update acceleration dashboard to match actual API format 2023-12-08 13:08:13 +00:00
Mononaut
6cf40489e5 tidy up acceleration dashboard 2023-12-08 13:08:13 +00:00
Mononaut
14ad0c8ecb Add more acceleration stats 2023-12-08 13:08:13 +00:00
Mononaut
f86645b50c Add latest block accelerations list 2023-12-08 13:08:13 +00:00
Mononaut
f23bcec10d Add acceleration fees graph 2023-12-08 13:08:13 +00:00
Mononaut
6f97a2ef74 Add accelerator dashboard 2023-12-08 13:08:13 +00:00
Mononaut
42a3a380d5 widgetify block fee rates chart 2023-12-08 13:08:12 +00:00
TechMiX
bbcc683a3c fix: use empty sidenav when service is disabled 2023-12-08 14:06:34 +01:00
TechMiX
9406103ed1 fix: adjust the blockchain container with menu in rtl mode 2023-12-07 22:49:51 +01:00
TechMiX
dc06387347 fix: rtl issues related to sidenav and global footer 2023-12-07 20:52:11 +01:00
orangesurf
5a2da751fa Remove TM & R from logo names 2023-12-07 09:55:12 +00:00
orangesurf
83db6f6428 Update License, about page and trademark policy with new registered trademarks 2023-12-07 09:28:36 +00:00
wiz
4169e1053f Merge pull request #4482 from mempool/mononaut/fix-negative-accel-rate
Fix negative accelerated fee rate, simplify fee rate table
2023-12-07 01:50:12 +09:00
wiz
a46e779d0c Merge branch 'master' into mononaut/fix-negative-accel-rate 2023-12-06 23:56:12 +09:00
Mononaut
51102004bb Fix negative accelerated fee rate, simplify fee rate table 2023-12-06 14:50:26 +00:00
wiz
08e9142d57 Merge pull request #4481 from mempool/mononaut/improve-acceleration-tracking
Improve acceleration tracking
2023-12-06 22:42:00 +09:00
Mononaut
b7c4cd43fc Better error handling for accelerations update request 2023-12-06 12:09:46 +00:00
Mononaut
08a35b85a8 Fix current accelerations update race condition 2023-12-06 12:09:28 +00:00
wiz
51a28b2e01 Merge pull request #4480 from mempool/mononaut/mined-acceleration-info
Show accelerated fee rates for mined transactions
2023-12-05 23:00:15 +09:00
Mononaut
966adf5963 Show accelerated fee rates on mined tx pages 2023-12-05 13:48:38 +00:00
wiz
ae7b17c4fd Merge pull request #4478 from mempool/mononaut/accelerated-badge
Accelerated tx audit badge
2023-12-05 17:36:52 +09:00
Mononaut
5b4bc9fe19 Accelerated tx audit badge 2023-12-05 08:33:57 +00:00
wiz
89eb7ec90b ops: Enable accelerator in production config 2023-12-05 05:29:18 +09:00
wiz
a646c5f22f Merge pull request #4390 from ncois/tooltip-overflow-bug
Fix tooltip overflow by increasing width
2023-12-04 23:44:44 +09:00
wiz
c345f2164b Merge pull request #4462 from ncois/search-block-datetime
Search a block by date and timestamp
2023-12-04 23:44:19 +09:00
wiz
9791ee018d Merge pull request #4466 from ncois/pool-hashrate-format
Pool chart hashrate format in power of ten
2023-12-04 23:44:06 +09:00
wiz
7c83b85e3e Merge pull request #4476 from mempool/nymkappa/fix-waitlist-message
[accel preview] only show waitlist message if logged in
2023-12-04 23:43:50 +09:00
nymkappa
63942af720 wait list -> waitlist @softsimon 2023-12-04 23:30:22 +09:00
nymkappa
4da5910e0b [accel preview] only show waitlist message if logged in 2023-12-04 23:23:51 +09:00
wiz
025788e78c Merge pull request #4471 from mempool/nymkappa/fix-one-bug-add-two-more
Various fixes and improvements
2023-12-04 22:51:41 +09:00
nymkappa
88a9524064 Merge branch 'master' into pool-hashrate-format 2023-12-04 21:34:43 +09:00
ncois
c216e849e6 Add more precision to hashrate graphs 2023-12-04 09:56:56 +01:00
nymkappa
c86768edc9 [about] fix merge conflict #4425 2023-12-04 16:59:29 +09:00
nymkappa
4283d30ce0 Merge branch 'master' into search-block-datetime 2023-12-04 13:09:58 +09:00
nymkappa
e2eeaebfc7 Merge branch 'master' into nymkappa/fix-one-bug-add-two-more 2023-12-04 10:47:49 +09:00
softsimon
90d87aaaca Merge pull request #4472 from mempool/simon/upgrading-fontawesome
Upgrading fontawesome
2023-12-03 18:17:33 +09:00
softsimon
b2e9275ad9 Upgrading fontawesome 2023-12-03 17:34:31 +09:00
nymkappa
181e816c1a Merge branch 'nymkappa/about-page-empty-anchor' into nymkappa/fix-one-bug-add-two-more 2023-12-03 15:17:04 +09:00
softsimon
758ca4e93a Merge pull request #4233 from mempool/hunicus/enterprise-abs
Make enterprise links not relative
2023-12-03 14:09:25 +09:00
softsimon
a33f915c7a Merge pull request #4438 from mempool/mononaut/refactor-difficulty-reindexing
Refactor difficulty reindexing to process blocks in height order
2023-12-03 13:15:01 +09:00
softsimon
75c6d006ff Merge pull request #4433 from mempool/mononaut/dismiss-acceleration-preview
Make the acceleration preview dismissable
2023-12-02 18:19:46 +09:00
softsimon
1fe983a299 Merge pull request #4468 from mempool/mononaut/fix-liquid-fee-rounding
Fix liquid recommended fee rounding
2023-12-02 15:05:13 +09:00
Mononaut
cd8e3e2604 Fix liquid fee rounding 2023-12-02 03:20:09 +00:00
wiz
dfc4309d9e Merge pull request #4465 from mempool/mononaut/fix-liquid-minfee
Fix Liquid minfee defaults
2023-12-01 21:52:25 +09:00
ncois
0a70273456 Pool chart: show power of ten of hashrate on desktop 2023-12-01 12:57:30 +01:00
softsimon
62c9a88235 Merge pull request #4448 from mempool/nymkappa/accel-preview-logged-in
[accelerator] show wait list message in preview when logged in with no access
2023-12-01 18:37:05 +09:00
Mononaut
851e07b50b Fix liquid minfee defaults 2023-12-01 18:12:59 +09:00
wiz
e1bbec074b Merge pull request #4457 from mempool/mononaut/matomo-path
matomo path
2023-12-01 17:54:06 +09:00
Mononaut
9fcafeeeb0 Switch to toggle-style acceleration dismiss button 2023-12-01 14:55:19 +09:00
Mononaut
e986cfd30b Make the acceleration preview dismissable 2023-12-01 14:21:05 +09:00
ncois
2584a1f2b0 Add date and timestamp search option 2023-11-30 20:05:25 +01:00
softsimon
1c92394563 Merge pull request #4449 from mempool/nymkappa/translation-typo
Fix some SEO strings
2023-11-30 18:33:05 +09:00
softsimon
36398ca57a Updating messages.xlf 2023-11-30 18:29:06 +09:00
softsimon
6b978f9262 Merge pull request #3706 from mempool/mononaut/reconnect-dead-websocket
reconnect websocket after closed by server
2023-11-30 18:26:18 +09:00
softsimon
12cf130c00 Merge branch 'master' into mononaut/reconnect-dead-websocket 2023-11-30 17:57:19 +09:00
softsimon
ba933a81c3 Merge pull request #3704 from mempool/mononaut/handle-websocket-errors
Disconnect websocket clients on error
2023-11-30 17:56:58 +09:00
Mononaut
7de7081d67 matomo path 2023-11-30 17:35:26 +09:00
nymkappa
6b933c202f Update nodes-rankings-dashboard.component.ts 2023-11-30 17:22:22 +09:00
softsimon
f1525b7df5 Merge pull request #4445 from mempool/dependabot/npm_and_yarn/frontend/fortawesome/fontawesome-svg-core-6.5.0
Bump @fortawesome/fontawesome-svg-core from 6.4.0 to 6.5.0 in /frontend
2023-11-30 17:05:19 +09:00
wiz
62c4af1a0c Merge pull request #4455 from mempool/mononaut/fix-matomo-fix
Fix matomo again
2023-11-30 15:49:00 +09:00
Mononaut
4ac98bc483 Fix matomo again 2023-11-30 15:46:58 +09:00
softsimon
ed07daebca Merge branch 'master' into mononaut/handle-websocket-errors 2023-11-30 15:18:16 +09:00
wiz
f8bbf7783c Merge pull request #4443 from mempool/nymkappa/debug-add-context
[log] create more general error
2023-11-30 14:53:51 +09:00
softsimon
fac2fab16a Merge pull request #4437 from mempool/simon/remove-audit-beta
Remove block audit beta-tag
2023-11-30 14:50:57 +09:00
wiz
76de4e34d8 Merge pull request #4425 from mempool/mononaut/fix-matomo
fix matomo bug
2023-11-30 14:40:26 +09:00
softsimon
6109f25aa9 Merge pull request #4452 from ncois/tx-ui-overflow
Fix overflow on transaction page
2023-11-30 14:36:15 +09:00
softsimon
86303175e9 Merge pull request #4451 from ncois/format-difficulty-chart
Difficulty adjustment chart: format the hashrate and difficulty
2023-11-30 14:27:39 +09:00
nymkappa
a670131f40 Merge branch 'master' into tooltip-overflow-bug 2023-11-30 11:54:16 +09:00
ncois
c5ce3167f3 Fix overflow on transaction page 2023-11-29 15:27:45 +01:00
ncois
9913254a5c Difficulty value: remove rounding 2023-11-29 11:16:48 +01:00
ncois
fbb4ba39c2 Mining chart: show hashrate power of ten on desktop 2023-11-29 11:08:38 +01:00
nymkappa
22bf0fe928 Re-apply fix from https://github.com/mempool/mempool/pull/4419/files#diff-9daf43654b4e0bb2c925b6396c6e3a7e1b117bd854fe9c46290f025bfe0a762eR285 2023-11-29 18:03:23 +09:00
nymkappa
3b30765070 Revert unnecessary changes 2023-11-29 18:00:07 +09:00
nymkappa
63fde7d0b6 Merge branch 'master' into nymkappa/about-page-sponsors-component 2023-11-29 17:57:54 +09:00
softsimon
cf338970bf Merge pull request #4450 from mempool/translations_frontend-src-locale-messages-xlf--master_fr
Updates for file frontend/src/locale/messages.xlf in fr
2023-11-29 16:35:27 +09:00
Mononaut
08e046ea2a fix matomo bug 2023-11-29 16:17:07 +09:00
transifex-integration[bot]
5697710c23 Translate frontend/src/locale/messages.xlf in fr
100% reviewed source file: 'frontend/src/locale/messages.xlf'
on 'fr'.
2023-11-29 07:00:03 +00:00
nymkappa
b9e050e24b Fix small typo in lightning node ranking dashboard seo 2023-11-29 15:59:15 +09:00
nymkappa
ff819673e5 Fix "and" chain in lightning dashboard seo 2023-11-29 15:56:35 +09:00
nymkappa
2e2801a4ab Add missing txid in seo tx preview 2023-11-29 15:51:35 +09:00
nymkappa
f52b17ca7a Add missing space in seo address preview 2023-11-29 15:28:14 +09:00
softsimon
3d25235705 Merge pull request #4439 from mempool/mononaut/fix-ln-search-suggestions
Fix spurious ln channel typeahead matches
2023-11-29 15:24:34 +09:00
nymkappa
2cbc6783a4 [accelerator] show wait list message in preview when logged in with no access 2023-11-29 15:02:48 +09:00
dependabot[bot]
406bf5d3b7 Bump @fortawesome/fontawesome-svg-core from 6.4.0 to 6.5.0 in /frontend
Bumps [@fortawesome/fontawesome-svg-core](https://github.com/FortAwesome/Font-Awesome) from 6.4.0 to 6.5.0.
- [Release notes](https://github.com/FortAwesome/Font-Awesome/releases)
- [Changelog](https://github.com/FortAwesome/Font-Awesome/blob/6.x/CHANGELOG.md)
- [Commits](https://github.com/FortAwesome/Font-Awesome/compare/6.4.0...6.5.0)

---
updated-dependencies:
- dependency-name: "@fortawesome/fontawesome-svg-core"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-29 02:48:50 +00:00
nymkappa
f5bf883de9 [about] fix auto scroll to chad/whale 2023-11-28 18:05:18 +09:00
nymkappa
c06cade1ca [log] create more general error 2023-11-28 17:13:52 +09:00
softsimon
c23a872887 Updating german i18n 2023-11-28 14:42:25 +09:00
softsimon
cd5a51098b Merge pull request #4419 from mempool/nymkappa/fix-about-page-ctas
[about page] fix wrapping perk
2023-11-26 18:24:58 +09:00
Mononaut
0b449347c1 Fix spurious ln channel typeahead matches 2023-11-26 09:22:44 +00:00
softsimon
d3f8876818 Merge pull request #4424 from mempool/nymkappa/channel-map-larger
[lightning] enlarge channel map
2023-11-26 18:09:31 +09:00
softsimon
d2da81e039 Remove block audit beta-tag 2023-11-26 17:21:13 +09:00
Mononaut
66d88abdc5 Refactor difficulty reindexing to process blocks in height order 2023-11-26 08:17:30 +00:00
softsimon
be2b9a9c2e Merge pull request #4436 from mempool/simon/pull-from-transifex-11-25
Pull from transifex 11/25
2023-11-26 17:01:10 +09:00
softsimon
63ba273dbe Pull from transifex 11/25 2023-11-26 17:00:46 +09:00
softsimon
8ae4c75c1a Fixing one last i18n string 2023-11-26 16:59:45 +09:00
softsimon
1cece1037a Disclaimer i18n fix 2023-11-26 16:29:20 +09:00
softsimon
478873302c Merging another duplicate i18n string 2023-11-26 16:20:57 +09:00
softsimon
3cff01b21e Merging another duplicate i18n string 2023-11-26 16:20:46 +09:00
softsimon
f67848b043 Merging another duplicate i18n string 2023-11-26 16:10:18 +09:00
softsimon
f0c88ff6cc Fix duplicate recent block i18n 2023-11-26 16:03:53 +09:00
softsimon
da5adc3e4e Merge pull request #4435 from mempool/simon/more-i18n-fixes3
More i18n fixes (3)
2023-11-26 15:49:02 +09:00
softsimon
bebd2ea028 More i18n fixes (3) 2023-11-26 15:48:44 +09:00
softsimon
e7e25e1632 Merge pull request #4432 from mempool/simon/more-i18n-fixes-etc
RBF i18n fixes
2023-11-25 20:46:19 +09:00
softsimon
c4130fd5b9 RBF i18n fixes 2023-11-25 20:45:59 +09:00
softsimon
dcad18b297 Merge pull request #4431 from mempool/simon/seo-description-fixes
Fixing titles and merging more i18n duplicates
2023-11-25 20:31:56 +09:00
softsimon
d380aad98c Fixing titles and merging more i18n duplicates 2023-11-25 20:31:29 +09:00
Mononaut
85c9c79699 reconnect websocket after closed by server 2023-11-25 11:25:07 +00:00
softsimon
107e0be59f Merge pull request #4428 from mempool/simon/i18n-fixes-231125
Updating and correcting i18n strings
2023-11-25 18:12:17 +09:00
softsimon
e654170d0b Updating and correcting i18n strings 2023-11-25 18:05:08 +09:00
Mononaut
652100f774 More verbose websocket error logs 2023-11-25 09:02:27 +00:00
Mononaut
0f04f751e1 Disconnect websocket clients on error 2023-11-25 08:27:17 +00:00
wiz
d3055dab54 Merge pull request #4157 from mempool/hunicus/bimi-svg
Add bimi svg
2023-11-25 16:29:29 +09:00
ncois
643402c046 Merge branch 'mempool:master' into tooltip-overflow-bug 2023-11-24 13:28:42 +01:00
nymkappa
e95d5a7982 [lightning] enlarge channel map 2023-11-24 18:14:16 +09:00
nymkappa
3103ef15e5 [about page] move CTA sponsors box into a sub component 2023-11-24 11:13:12 +09:00
wiz
5d5e9e8219 Legal: update Privacy Policy 20231123 2023-11-23 22:23:06 +09:00
wiz
99fd4500e4 Fix broken sponsor links on About page 2023-11-23 21:50:27 +09:00
nymkappa
69081ed647 [about page] fix wrapping perk 2023-11-23 21:07:21 +09:00
softsimon
c8bcd4f04f Merge pull request #4415 from mempool/nymkappa/fix-css-testnet
[ui] only load empty sidebar in foss mainnet
2023-11-23 18:56:43 +09:00
nymkappa
7f4fd83ad2 [ui] fix testnets padding 2023-11-23 18:40:25 +09:00
softsimon
70722dfc9c Merge pull request #4414 from mempool/nymkappa/fix-waitlist-message-preview
[accelerator] fix preview UX on mobile when there is an error/warning
2023-11-23 17:42:19 +09:00
softsimon
407b4c53a6 Merge pull request #4403 from mempool/mononaut/empty-mempool-block-health
Fix health score when mempool was empty
2023-11-23 17:25:06 +09:00
nymkappa
c11551de7b [accelerator] fix preview UX on mobile when there is an error/warning 2023-11-23 17:00:57 +09:00
softsimon
2d5964b81e Merge pull request #4413 from mempool/nymkappa/polish-accel-preview
[accelerator] small align tweak
2023-11-23 15:51:07 +09:00
nymkappa
98e3c7b9cf [accelerator] small align tweak 2023-11-23 15:47:28 +09:00
softsimon
2de57a8074 Merge pull request #4412 from mempool/nymkappa/polish-accel-preview
[accelerator] fix preview text wrap not working on safari/firefox + polish accelerator preview
2023-11-23 15:39:24 +09:00
nymkappa
8badacf123 [accelerator] fix preview text wrap not working on safari/firefox
[accelerator] polish accelerator preview
2023-11-23 14:54:50 +09:00
softsimon
40b387a1e0 Merge pull request #4411 from mempool/nymkappa/fix-menu-css
[menu] force background color when menu is open
2023-11-23 13:31:11 +09:00
nymkappa
e5d2788736 [menu] force background color when menu is open 2023-11-23 10:45:16 +09:00
ncois
f57436f511 Merge branch 'master' into tooltip-overflow-bug 2023-11-22 12:14:03 +01:00
Mononaut
75cc844676 actually fix empty mempool health score 2023-11-22 19:53:22 +09:00
wiz
5d05dd7089 Merge pull request #4410 from mempool/simon/accelerate-button-height
Accelerate button height align fix
2023-11-22 19:51:49 +09:00
softsimon
35e108aa1c Accelerate button height fix 2023-11-22 19:37:44 +09:00
softsimon
3f06b38767 Merge pull request #4408 from mempool/mononaut/restore-calculator
Restore the calculator
2023-11-22 18:19:39 +09:00
Mononaut
9844c3d275 Restore the calculator 2023-11-22 18:13:41 +09:00
wiz
04eeb19bb9 Fix string in community sponsor CTA button box 2023-11-22 17:56:56 +09:00
wiz
671540af78 Merge pull request #4407 from mempool/mononaut/8chain
Standalone multi-block view page
2023-11-22 17:54:38 +09:00
Mononaut
1a732f18fc Remove font, update 8 block defaults, fix deprecated css 2023-11-22 17:47:51 +09:00
Mononaut
729fb3bb9d Move standalone blocks page to /view/blocks 2023-11-22 17:47:51 +09:00
Mononaut
fc56f273d4 Simplify 8chain block info 2023-11-22 17:47:51 +09:00
Mononaut
642be969a3 Add more block info, reduce font size 2023-11-22 17:47:50 +09:00
Mononaut
d69cdacd5e Add numBlocks param 2023-11-22 17:47:50 +09:00
Mononaut
ec8fc53dcb eight blocks 2023-11-22 17:47:49 +09:00
wiz
108d1762d6 Merge pull request #4404 from mempool/simon/truncate-text-link-fix
Fixes truncated links
2023-11-22 17:17:51 +09:00
wiz
879039ca8c Merge pull request #4406 from mempool/wiz/update-privacy-policy
Update our Privacy Policy for new backend
2023-11-22 17:16:38 +09:00
wiz
047d1463e7 Add missing <br> tag in privacy poilicy 2023-11-22 17:15:39 +09:00
wiz
8fc60fa086 Merge pull request #4405 from mempool/mononaut/simplify-acceleration-preview
simplify acceleration preview summary
2023-11-22 17:12:26 +09:00
wiz
bce68ee37f Merge branch 'master' into wiz/update-privacy-policy 2023-11-22 17:09:14 +09:00
wiz
2f25c128c1 Merge pull request #4395 from mempool/hunicus/about-sponsor-link
Change sponsor cta on about page
2023-11-22 17:06:55 +09:00
wiz
a76a600d3f Tweak community sponsor word 2023-11-22 17:06:02 +09:00
wiz
afdb419beb Update our Privacy Policy for new backend 2023-11-22 16:55:40 +09:00
Mononaut
8bd2aa3dd3 simplify acceleration preview summary 2023-11-22 16:38:58 +09:00
hunicus
a3f2c42b8e Replace vip events with early accelerator 2023-11-22 16:31:24 +09:00
softsimon
dbcd900056 Fixes truncated links 2023-11-22 16:22:41 +09:00
softsimon
5a6d6fae41 Merge pull request #4401 from mempool/mononaut/menu-footer-align-bug
Fix truncated hidden text layout flow bug
2023-11-22 15:35:26 +09:00
softsimon
6bb666ba5e Merge pull request #4402 from mempool/dependabot/npm_and_yarn/frontend/cypress-13.6.0
Bump cypress from 13.5.0 to 13.6.0 in /frontend
2023-11-22 14:47:49 +09:00
Mononaut
8dc80eadf3 Fix health score when mempool was empty 2023-11-22 13:10:53 +09:00
softsimon
505532f812 Merge pull request #4396 from mempool/mononaut/graph-tooltip-fixes
Fix mempool graph tooltip width & vb precision
2023-11-22 12:21:03 +09:00
dependabot[bot]
89eb02dad0 Bump cypress from 13.5.0 to 13.6.0 in /frontend
Bumps [cypress](https://github.com/cypress-io/cypress) from 13.5.0 to 13.6.0.
- [Release notes](https://github.com/cypress-io/cypress/releases)
- [Changelog](https://github.com/cypress-io/cypress/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/cypress-io/cypress/compare/v13.5.0...v13.6.0)

---
updated-dependencies:
- dependency-name: cypress
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-22 02:21:44 +00:00
Mononaut
94a7b710c5 Fix truncated hidden text layout flow bug 2023-11-22 11:15:00 +09:00
softsimon
1e01f88c15 Merge pull request #4398 from mempool/mononaut/fix-left-margin
Fix negative left margin on master page
2023-11-21 20:41:38 +09:00
Mononaut
d471616a24 Fix negative left margin on master page 2023-11-21 20:29:41 +09:00
hunicus
9b8f70a0ae Change alignment and copy 2023-11-21 18:00:22 +09:00
Mononaut
ab079e9372 Fix mempool graph tooltip width & vb precision 2023-11-21 16:36:46 +09:00
hunicus
b77a16233b Change sponsor cta on about page 2023-11-21 14:56:53 +09:00
wiz
894075493b ops: Fix mempool backend config for liquid socket paths 2023-11-20 23:28:37 +09:00
wiz
954512cd8e Merge pull request #4303 from mempool/nymkappa/mega-branch
[Accelerator] Mega branch
2023-11-20 22:41:23 +09:00
nymkappa
deaf6ad6a5 [enterprise] fix api endpoints urls 2023-11-20 19:12:56 +09:00
nymkappa
98443b48ba Merge remote-tracking branch 'origin/nymkappa/mega-branch' into nymkappa/mega-branch 2023-11-20 17:16:44 +09:00
nymkappa
a7dc8793c2 [about page] un-hide sponsors buttons 2023-11-20 17:16:27 +09:00
wiz
84b8e5d472 Merge branch 'master' into nymkappa/mega-branch 2023-11-20 17:15:01 +09:00
ncois
1eb425897e Adjust the width of the incoming tx tooltip for 2h timeframe 2023-11-19 16:42:09 +01:00
softsimon
e768072799 Merge pull request #4388 from mempool/mononaut/rbf-cache-load-logs
More verbose RBF cache check logs
2023-11-19 17:34:00 +09:00
nymkappa
206706180f [accelerator] fix confirmation message when accelerating 2023-11-19 17:23:46 +09:00
nymkappa
0e3b3a0e00 [accelerator] fix message when trying to accelerate 2023-11-19 17:16:05 +09:00
wiz
28733c1e97 Merge branch 'master' into nymkappa/mega-branch 2023-11-19 16:07:03 +09:00
softsimon
7e74a26de2 Merge pull request #4257 from mempool/nymkappa/sticky-header-non-bitcoin
Sticky header non bitcoin
2023-11-19 15:27:52 +09:00
nymkappa
6d920e0ed3 [accelerator] hide accelerate banner 2023-11-18 18:36:17 +09:00
nymkappa
88e5f8a6af remove upgrade link when feature not available 2023-11-18 17:15:04 +09:00
nymkappa
ae82ac8368 Merge remote-tracking branch 'origin/nymkappa/mega-branch' into nymkappa/mega-branch 2023-11-18 15:21:01 +09:00
nymkappa
15cba58144 /image -> /images 2023-11-18 15:20:53 +09:00
wiz
2c820f1cc0 ops: Rewrite nginx config for new services API endpoints 2023-11-18 15:09:02 +09:00
wiz
4070492584 ops: Set nginx to ignore Pragma header for no-cache endpoints 2023-11-18 13:22:17 +09:00
wiz
82a43e25e0 ops: Set nginx no-cache headers for /api/v1/services/auth 2023-11-18 12:40:39 +09:00
wiz
5e45d8f3bc ops: Set nginx no-cache headers for /api/v1/services/account 2023-11-18 12:20:18 +09:00
wiz
e5709235f3 Merge branch 'master' into nymkappa/mega-branch 2023-11-18 11:30:35 +09:00
ncois
9d0bfdfa88 Increase tooltip width in mempool graphs 2023-11-17 13:47:28 +01:00
softsimon
59c513f2a5 Merge pull request #4389 from ncois/fix-p2pk-balance
Fix P2PK balance display in address page (duplicate)
2023-11-17 20:49:02 +09:00
ncois
76a07315f3 Fix P2PK balance display in address page 2023-11-17 09:52:48 +01:00
softsimon
5723f167df Merge pull request #4386 from mempool/mononaut/fix-electrum-p2pk
Fix electrum p2pk/scripthash format
2023-11-17 17:31:22 +09:00
Mononaut
6ac328c979 More verbose RBF cache check logs 2023-11-17 07:06:44 +00:00
softsimon
85e52d24c3 Merge pull request #4382 from shubhamkmr04/shubham/Change-ZEUS-logo
Change ZEUS Logo
2023-11-17 15:29:13 +09:00
Mononaut
7717c15666 Fix electrum p2pk/scripthash format 2023-11-17 03:49:31 +00:00
softsimon
61d7fd490a Merge pull request #4385 from mempool/mononaut/memory-usage-precision
Round memory usage to 3 significant figures
2023-11-17 11:48:44 +09:00
Mononaut
ccf952983b Round memory usage to 3sf 2023-11-17 02:22:57 +00:00
Shubham Kumar
602d7ce207 Merge branch 'master' into shubham/Change-ZEUS-logo 2023-11-16 12:42:19 +05:30
nymkappa
64a51803c4 Merge branch 'master' into nymkappa/mega-branch 2023-11-16 16:10:55 +09:00
shubham
a63e68e9e3 Change ZEUS Logo 2023-11-16 12:38:54 +05:30
softsimon
d4d17fa167 Merge pull request #4371 from mempool/nymkappa/outliers-toggle
[graph] add toggle to show/hide outliers in transaction vBytes per second graph
2023-11-16 14:59:50 +09:00
nymkappa
4cd8d70de5 cleanup if/else 2023-11-15 18:47:56 +09:00
nymkappa
dc26c6f105 [graph] don't change yaxis scale if no outliers - save state in localstorage 2023-11-15 18:46:33 +09:00
nymkappa
365954f5b4 Merge pull request #4304 from mempool/nymkappa/new-enterprise-launch
Prepare enterprise only launch
2023-11-15 18:24:48 +09:00
nymkappa
ff38073280 Merge branch 'nymkappa/mega-branch' into nymkappa/new-enterprise-launch 2023-11-15 18:22:37 +09:00
nymkappa
eeebfde33c Merge branch 'master' into nymkappa/mega-branch 2023-11-15 18:22:27 +09:00
softsimon
fa12233667 Merge pull request #4381 from mempool/mononaut/acc-preview-min-height
Minimum acceleration preview bar height
2023-11-15 18:22:05 +09:00
nymkappa
19477c4ee3 Merge branch 'master' into mononaut/acc-preview-min-height 2023-11-15 18:18:42 +09:00
nymkappa
e4b56bac88 Merge branch 'nymkappa/mega-branch' into nymkappa/new-enterprise-launch 2023-11-15 18:18:01 +09:00
nymkappa
d390fa8671 Merge branch 'master' into nymkappa/mega-branch 2023-11-15 18:17:48 +09:00
softsimon
f9f9c62608 Merge pull request #4374 from mempool/nymkappa/fix-hybrid-build-routing
[frontend] export MasterPageComponent for re-use in hybrid build
2023-11-15 18:02:25 +09:00
Mononaut
d9966143c1 Minimum acceleration preview bar height 2023-11-15 08:49:22 +00:00
nymkappa
57ab82ae7a Merge branch 'nymkappa/mega-branch' into nymkappa/new-enterprise-launch 2023-11-15 17:23:42 +09:00
nymkappa
756f6d8abe [frontend] export MasterPageComponent for re-use in hybrid build 2023-11-15 17:09:54 +09:00
softsimon
f0840a51d9 Merge pull request #4379 from mempool/mononaut/reduce-batch-sizes
Configurable mempool/electrs batch sizes
2023-11-15 16:56:35 +09:00
softsimon
eac8f8c2c6 Merge pull request #4368 from mempool/simon/truncate-selection
Make search and select work for truncated text
2023-11-15 16:25:17 +09:00
Mononaut
20f61fc6a0 Round batch sizes up 2023-11-15 06:58:00 +00:00
Mononaut
6454892d48 Use mempool/txs max_txs parameter 2023-11-15 06:57:31 +00:00
Mononaut
35d7c55c1d Configurable esplora batch sizes 2023-11-15 06:12:15 +00:00
softsimon
86fe6a802b Fixing mobile overflow 2023-11-15 15:07:14 +09:00
softsimon
d4568b631d Make search and select work for truncated text
fixes #4367
2023-11-15 14:39:23 +09:00
nymkappa
2d30c0b588 [graph] use echart echart yaxis max property instead of modifying the data itself 2023-11-15 14:08:44 +09:00
wiz
1aea3fcac5 Merge pull request #4378 from mempool/mononaut/tomahawk-logs-fix
Set fallback server out-of-sync when unreachable
2023-11-14 19:27:13 +09:00
Mononaut
5cfd599018 Set fallback server out-of-symc when unreachable 2023-11-14 10:17:02 +00:00
wiz
d8f2462ff0 Merge pull request #4377 from mempool/mononaut/tomahawk-logs
🥩🙂🪵📝
2023-11-14 19:10:41 +09:00
Mononaut
85091e1f3a 🥩🙂🪵📝 2023-11-14 09:55:02 +00:00
softsimon
3a8d19062f Merge pull request #4271 from mempool/mononaut/refactor-task-scheduler
Refactor indexer scheduling to avoid accumulating identical tasks
2023-11-14 18:13:48 +09:00
wiz
6913946079 ops: Upgrade mariadb to 10.11.x 2023-11-14 17:46:52 +09:00
wiz
fdd18317f9 ops: Kill node before sh in stop script 2023-11-14 17:46:42 +09:00
softsimon
a7c64c0df3 Merge branch 'master' into mononaut/refactor-task-scheduler 2023-11-14 17:17:55 +09:00
softsimon
f2fb2f98f1 Merge pull request #4375 from mempool/mononaut/db-error-log-levels
Support different log levels for database query error messages
2023-11-14 17:17:31 +09:00
Mononaut
7aad664112 Support different log levels for database query error messages 2023-11-14 07:59:24 +00:00
nymkappa
fa040ca19f [frontend] export MasterPageComponent for re-use in hybrid build 2023-11-14 15:53:37 +09:00
Mononaut
00887bc24b Refactor indexer scheduling to avoid accumulating identical tasks 2023-11-14 06:30:22 +00:00
softsimon
ab8b557e73 Merge pull request #4373 from mempool/mononaut/fix-silent-db-exceptions
Fix silently unhandled database exceptions
2023-11-14 15:27:52 +09:00
Mononaut
5c0a59d2f6 handle unknown query types in db error log 2023-11-14 06:13:06 +00:00
Mononaut
29cbdf6cd5 handle null query in error log 2023-11-14 05:52:27 +00:00
Mononaut
08b68ef8ba handle exception in db transaction rollback 2023-11-14 05:33:48 +00:00
Mononaut
1ae34e069c Fix silently unhandled database exceptions 2023-11-14 05:11:51 +00:00
softsimon
5bad829afc Merge pull request #4316 from starius/taproot-channels
[lightning] add taproot-channels to node features
2023-11-14 13:54:31 +09:00
softsimon
562cd5683a Merge branch 'master' into taproot-channels 2023-11-14 13:41:44 +09:00
nymkappa
cbf2395009 Merge branch 'master' into nymkappa/mega-branch 2023-11-14 11:12:11 +09:00
nymkappa
c393483590 [graph] add toggle to show/hide outliers in transaction vBytes per second graph 2023-11-14 10:51:51 +09:00
wiz
cbe1ec4e72 Merge pull request #4356 from mempool/mononaut/fix-pid-lock
Recover from stale PID file
2023-11-13 22:19:43 +09:00
Mononaut
c6a92083a8 Fix pid parsing on release lock 2023-11-13 07:54:11 +00:00
Mononaut
8c4b488251 handle SIGHUP exit code 2023-11-13 07:54:11 +00:00
Mononaut
3639dcc92a Recover from stale PID file 2023-11-13 07:54:11 +00:00
wiz
28113d1141 Merge pull request #4163 from mempool/mononaut/fast-forensics
Fast lightning forensics
2023-11-13 14:54:20 +09:00
softsimon
12b49abfdd Merge pull request #4258 from mempool/mononaut/esplora-sigops
Sigops everywhere
2023-11-13 14:32:23 +09:00
wiz
68e0dfe736 Merge branch 'master' into mononaut/fast-forensics 2023-11-13 14:24:08 +09:00
Mononaut
29299e622e Calculate sigops in /api/v1/tx/:txid for mined txs 2023-11-13 03:44:35 +00:00
Mononaut
4ac0a6dad2 Display sigops on all transactions 2023-11-13 03:44:35 +00:00
Mononaut
a510b4992c Fix condition to add mempool data to loaded cache txs 2023-11-13 03:44:35 +00:00
Mononaut
72e19f674a Clear Liquid sigops 2023-11-13 03:44:34 +00:00
Mononaut
ea2a7e7505 Use sigops from mempool/electrs, fix the nodejs sigop calculation 2023-11-13 03:44:34 +00:00
wiz
74a2cedc7a Merge pull request #4101 from mempool/mononaut/faster-rbf-load
use bulk /txs endpoint to check cached rbf tx status
2023-11-12 19:10:53 +09:00
wiz
c0a481acbe Reduce /internal/txs RBF cache query chunk size to 250 2023-11-12 19:09:36 +09:00
Mononaut
5998b54fec more logs, reduce request chunk sizes 2023-11-12 09:23:37 +00:00
wiz
a2f6ea7b3a Merge branch 'master' into mononaut/faster-rbf-load 2023-11-12 17:41:30 +09:00
wiz
6a877c2a2e Merge pull request #4158 from mempool/junderw/fix-paths
Nginx: Ignore all internal-api paths
2023-11-12 17:40:34 +09:00
wiz
ee90a96d22 Merge branch 'master' into junderw/fix-paths 2023-11-12 17:22:39 +09:00
softsimon
4ea7989aec Merge pull request #4364 from mempool/mononaut/fix-incoming-tx-chart
restore incoming tx clearance line, smooth moving avg
2023-11-12 17:13:53 +09:00
Mononaut
fc52514c31 restore incoming tx clearance line, smooth moving avg 2023-11-12 07:59:06 +00:00
Mononaut
b9217da453 Change internal API prefix to "internal" 2023-11-12 07:08:21 +00:00
Mononaut
70badaf461 Speed up $scanForClosedChannels, use internal outspends apis 2023-11-12 07:08:20 +00:00
Mononaut
995acb238d Refactor forensics batching, speed up opened channel forensics 2023-11-12 07:08:20 +00:00
Mononaut
5bee54a2bf Use new bulk endpoints to speed up forensics 2023-11-12 07:08:19 +00:00
Mononaut
7ec7ae7b95 Remove old batched outspends API 2023-11-12 07:03:28 +00:00
Mononaut
09f208484a Add electrsApiService cachedRequest function, switch outspends 2023-11-12 07:03:28 +00:00
Mononaut
8aa51c4e80 Batch esplora outspends requests 2023-11-12 07:03:28 +00:00
Mononaut
823f06451c Send correct tx conf status in websocket msgs 2023-11-12 07:03:27 +00:00
Mononaut
9d60c39aeb Resolve rbf cache merge conflicts 2023-11-12 06:19:46 +00:00
Mononaut
031e14f302 Update internal getRawTransactions to use new prefix 2023-11-12 05:37:39 +00:00
Mononaut
156b5d0b3c Update bulk /txs to use new failover router, internal-api path 2023-11-12 05:37:39 +00:00
Mononaut
38909cfc42 use bulk /txs endpoint to check cached rbf tx status 2023-11-12 05:37:37 +00:00
softsimon
3de779ea13 Merge pull request #4255 from mempool/mononaut/confirmed-tx-status
Send correct tx conf status in websocket msgs
2023-11-12 14:34:12 +09:00
Mononaut
2339a0771e Use internal /block/:hash/txs endpoint 2023-11-12 05:04:41 +00:00
junderw
4972f00a96 Add internal endpoint blocking to all Nginx configs 2023-11-12 05:04:41 +00:00
Jonathan Underwood
502a1c021e Add suggestions from wiz
Co-authored-by: wiz <j@wiz.biz>
2023-11-12 05:04:41 +00:00
Mononaut
d16773bfa0 Switch backend to use internal-api paths 2023-11-12 05:04:41 +00:00
junderw
511b827bf5 Nginx: Ignore all internal-api paths 2023-11-12 05:04:40 +00:00
softsimon
90634c4343 Merge branch 'master' into mononaut/confirmed-tx-status 2023-11-12 13:48:35 +09:00
softsimon
1e69f3b331 Merge pull request #4246 from mempool/dependabot/npm_and_yarn/frontend/mock-socket-9.3.1
Bump mock-socket from 9.2.1 to 9.3.1 in /frontend
2023-11-11 18:42:53 +09:00
dependabot[bot]
4273276422 Bump mock-socket from 9.2.1 to 9.3.1 in /frontend
Bumps [mock-socket](https://github.com/thoov/mock-socket) from 9.2.1 to 9.3.1.
- [Release notes](https://github.com/thoov/mock-socket/releases)
- [Changelog](https://github.com/thoov/mock-socket/blob/master/CHANGELOG.md)
- [Commits](https://github.com/thoov/mock-socket/commits)

---
updated-dependencies:
- dependency-name: mock-socket
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-11 09:37:11 +00:00
softsimon
fd25713746 Merge pull request #4318 from mempool/mononaut/more-dp-fees
Improve precision of fee distribution chart labels
2023-11-11 18:36:26 +09:00
Mononaut
37605d5732 Improve fee distribution legibility on small screens 2023-11-11 08:57:55 +00:00
softsimon
df2967d576 Merge pull request #4353 from mempool/dependabot/npm_and_yarn/frontend/frontend-angular-dependencies-f2c2dc5ad6
Bump the frontend-angular-dependencies group in /frontend with 1 update
2023-11-11 17:57:32 +09:00
dependabot[bot]
9ab85ab799 Bump the frontend-angular-dependencies group in /frontend with 1 update
Bumps the frontend-angular-dependencies group in /frontend with 1 update: [ngx-echarts](https://github.com/xieziyu/ngx-echarts).

- [Release notes](https://github.com/xieziyu/ngx-echarts/releases)
- [Commits](https://github.com/xieziyu/ngx-echarts/commits)

---
updated-dependencies:
- dependency-name: ngx-echarts
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-11 08:39:56 +00:00
softsimon
1b6f039341 Merge pull request #4289 from mempool/dependabot/npm_and_yarn/frontend/get-func-name-2.0.2
Bump get-func-name from 2.0.0 to 2.0.2 in /frontend
2023-11-11 17:38:47 +09:00
dependabot[bot]
0abf4f415f Bump get-func-name from 2.0.0 to 2.0.2 in /frontend
Bumps [get-func-name](https://github.com/chaijs/get-func-name) from 2.0.0 to 2.0.2.
- [Release notes](https://github.com/chaijs/get-func-name/releases)
- [Commits](https://github.com/chaijs/get-func-name/commits/v2.0.2)

---
updated-dependencies:
- dependency-name: get-func-name
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-11 08:29:45 +00:00
Mononaut
b5a5f0f608 Add small margin above fee distribution graph 2023-11-11 08:24:58 +00:00
Mononaut
ffd2685922 Display fee distribution labels to 3 sig figs 2023-11-11 08:24:57 +00:00
softsimon
9845567c2f Merge pull request #4361 from mempool/mononaut/fix-double-outspend-request
ApiService caching layer
2023-11-11 17:07:31 +09:00
Mononaut
6740ab61f3 Reduce outspend API cache expiry to 250ms 2023-11-11 07:46:25 +00:00
Mononaut
3f0c3c1952 Add apiService cachedRequest function, apply to outspends requests 2023-11-11 07:16:59 +00:00
softsimon
7142d69dda Merge pull request #4319 from mempool/mononaut/fix-stale-rbf-cache
Fix rbf tree leak, clean up stale trees in Redis
2023-11-11 15:17:13 +09:00
Mononaut
e3e248d601 Convert RBF disk cache data to match new format 2023-11-11 05:52:37 +00:00
softsimon
a0a4ae611c Merge pull request #2846 from antonilol/cookie
Add Bitcoin Core RPC cookie authentication option
2023-11-11 13:16:35 +09:00
Mononaut
0e420d8196 Fix rbf tree leak, clean up stale trees in Redis 2023-11-11 04:05:56 +00:00
softsimon
06d1bbdf03 Merge branch 'master' into cookie 2023-11-11 12:57:49 +09:00
softsimon
87b034fa8c Merge pull request #4292 from mempool/mononaut/hide-arrow-on-replace
Hide the blockchain arrow when transaction is replaced
2023-11-11 12:17:54 +09:00
softsimon
874d2b371d Merge branch 'master' into mononaut/hide-arrow-on-replace 2023-11-11 11:57:03 +09:00
softsimon
6134376964 Merge pull request #4347 from mempool/dependabot/npm_and_yarn/frontend/cypress-13.5.0
Bump cypress from 13.3.0 to 13.5.0 in /frontend
2023-11-11 11:56:46 +09:00
softsimon
eba5560caa Merge pull request #4348 from mempool/dependabot/npm_and_yarn/backend/axios-1.6.1
Bump axios from 1.5.0 to 1.6.1 in /backend
2023-11-11 11:56:34 +09:00
dependabot[bot]
e08665dee5 Bump cypress from 13.3.0 to 13.5.0 in /frontend
Bumps [cypress](https://github.com/cypress-io/cypress) from 13.3.0 to 13.5.0.
- [Release notes](https://github.com/cypress-io/cypress/releases)
- [Changelog](https://github.com/cypress-io/cypress/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/cypress-io/cypress/compare/v13.3.0...v13.5.0)

---
updated-dependencies:
- dependency-name: cypress
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-11 02:47:53 +00:00
softsimon
b8b341431a Merge pull request #4354 from mempool/mononaut/rerebundle
Better code-splitting
2023-11-10 16:40:36 +09:00
softsimon
9e6072c371 Merge branch 'master' into mononaut/confirmed-tx-status 2023-11-10 14:49:24 +09:00
Mononaut
af7b9c0dc8 Adjust webpack chunk preloading strategy 2023-11-10 05:36:19 +00:00
softsimon
1e3babe714 Merge pull request #4254 from mempool/mononaut/failover-timeout-config
Add REQUEST_TIMEOUT and FALLBACK_TIMEOUT esplora config options
2023-11-10 14:27:25 +09:00
softsimon
a663cca3d0 Merge branch 'master' into mononaut/failover-timeout-config 2023-11-10 14:09:43 +09:00
softsimon
3580d060ce Merge pull request #4274 from mempool/mononaut/fix-faq-blockchain
Fix faq blockchain positioning
2023-11-10 13:53:15 +09:00
softsimon
31ead371dc Merge branch 'master' into mononaut/fix-faq-blockchain 2023-11-10 13:49:58 +09:00
softsimon
897cd7edeb Merge pull request #3571 from mempool/nymkappa/tx-overflow
Fix transaction amount overflow
2023-11-10 12:56:40 +09:00
softsimon
683b72387b Merge branch 'master' into nymkappa/tx-overflow 2023-11-10 12:47:52 +09:00
Mononaut
db8ed5b705 Split liquid, lightning & mainnet graphs 2023-11-10 03:21:25 +00:00
Mononaut
80bf2f9ebd Split master page components & deduplicate main routes 2023-11-10 03:20:59 +00:00
Mononaut
854a9dd057 Split legal page components into separate modules 2023-11-10 03:20:59 +00:00
Mononaut
ae02ff5b0d Split About component into separate module 2023-11-10 03:20:59 +00:00
Mononaut
0cf898a19f Split transaction components into separate module 2023-11-10 03:20:57 +00:00
Mononaut
b5a8687b6a Split Block component into separate module 2023-11-10 03:20:32 +00:00
wiz
27077dcd6c Merge pull request #4280 from mempool/mononaut/standalone-visualizations
Standalone block visualizations
2023-11-09 20:06:28 +09:00
wiz
80ecf77270 Merge branch 'master' into mononaut/standalone-visualizations 2023-11-09 19:52:32 +09:00
wiz
8d6225d6c5 Merge pull request #4309 from mempool/knorrium/unfurler_config
Configurable unfurler config
2023-11-09 19:50:58 +09:00
wiz
8dcd372b99 Merge pull request #4312 from mempool/mononaut/fix-group-channel-count
Fix node group map channel count
2023-11-09 19:26:08 +09:00
wiz
c4d37392dc Merge branch 'master' into mononaut/fix-group-channel-count 2023-11-09 18:46:41 +09:00
wiz
4ed3b65d12 Merge pull request #4323 from mempool/mononaut/hide-mempool-count-line
Hide mempool graph count line by default
2023-11-09 18:46:33 +09:00
wiz
86458927d6 Merge branch 'master' into mononaut/hide-mempool-count-line 2023-11-09 18:38:11 +09:00
wiz
49f189f257 Merge pull request #4343 from erikarvstedt/add-distro-nix-bitcoin
README: add `nix-bitcoin` to node distros
2023-11-09 18:37:20 +09:00
softsimon
9cc0aaeac2 Merge pull request #4345 from mempool/mononaut/rebundle
Shake the echarts tree
2023-11-09 18:25:26 +09:00
wiz
2df99ef7ed Merge branch 'master' into mononaut/rebundle 2023-11-09 18:06:19 +09:00
softsimon
450bda7d04 Merge pull request #4328 from mempool/mononaut/purging-min-fee
Enforce purging rate minimum on recommended fees
2023-11-09 14:58:48 +09:00
dependabot[bot]
d18b8881d0 Bump axios from 1.5.0 to 1.6.1 in /backend
Bumps [axios](https://github.com/axios/axios) from 1.5.0 to 1.6.1.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.5.0...v1.6.1)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-09 02:16:55 +00:00
wiz
1b3ceed707 Merge pull request #4325 from fanquake/bitcoin_core_25_1
Upgrade bitcoin core to v25.1
2023-11-09 01:39:01 +09:00
Mononaut
a33dc74c88 Shake the echarts tree 2023-11-07 23:35:33 +00:00
softsimon
79fb0a34dc Merge pull request #4331 from mempool/dependabot/npm_and_yarn/frontend/browserify-sign-4.2.2
Bump browserify-sign from 4.2.1 to 4.2.2 in /frontend
2023-11-07 11:46:35 +09:00
softsimon
40f79e64b3 Merge pull request #4329 from mempool/dependabot/npm_and_yarn/backend/crypto-js-4.2.0
Bump crypto-js from 4.1.1 to 4.2.0 in /backend
2023-11-07 11:46:17 +09:00
dependabot[bot]
5f034d34b3 Bump browserify-sign from 4.2.1 to 4.2.2 in /frontend
Bumps [browserify-sign](https://github.com/crypto-browserify/browserify-sign) from 4.2.1 to 4.2.2.
- [Changelog](https://github.com/browserify/browserify-sign/blob/main/CHANGELOG.md)
- [Commits](https://github.com/crypto-browserify/browserify-sign/compare/v4.2.1...v4.2.2)

---
updated-dependencies:
- dependency-name: browserify-sign
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-07 01:45:30 +00:00
softsimon
6d336c010c Merge pull request #4322 from mempool/dependabot/npm_and_yarn/frontend/babel/traverse-7.23.2
Bump @babel/traverse from 7.22.8 to 7.23.2 in /frontend
2023-11-07 10:44:36 +09:00
dependabot[bot]
14c87e2f03 Bump crypto-js from 4.1.1 to 4.2.0 in /backend
Bumps [crypto-js](https://github.com/brix/crypto-js) from 4.1.1 to 4.2.0.
- [Commits](https://github.com/brix/crypto-js/compare/4.1.1...4.2.0)

---
updated-dependencies:
- dependency-name: crypto-js
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-07 01:44:00 +00:00
softsimon
6ef15bddcd Merge pull request #4314 from mempool/dependabot/npm_and_yarn/backend/babel/core-7.23.2
Bump @babel/core from 7.21.4 to 7.23.2 in /backend
2023-11-07 10:43:03 +09:00
softsimon
fbc6c078ef Merge pull request #4302 from mempool/simon/liquid-blocks-api
Fix block pagination for liquid
2023-11-07 10:42:26 +09:00
softsimon
717601342f Merge pull request #4327 from mempool/orangesurf/primal-logo
Add primal.net logo to footer
2023-11-07 10:41:45 +09:00
Erik Arvstedt
939fe951d4 README: add nix-bitcoin to node distros 2023-11-05 13:47:23 +01:00
nymkappa
a9a3623539 Merge pull request #4341 from mempool/nymkappa/hide-accelerate-cta-loading
[accelerator] hide cta while the tx page is loading
2023-11-02 10:21:46 +09:00
nymkappa
27966ad8ec [accelerator] hide cta while the tx page is loading 2023-11-02 10:21:15 +09:00
nymkappa
5d1ebc6d31 Merge pull request #4340 from mempool/nymkappa/fix-search-align-issue
[CSS] fix search align issue when hamburger icon is showing
2023-11-01 17:49:26 +09:00
nymkappa
a68c2a2be6 [css] fix search bar align issue when hamburger icon is showing 2023-11-01 17:47:20 +09:00
softsimon
7145856d98 Merge pull request #4326 from TKone7/patch-1
Fix memory cache cleanup logic
2023-10-30 20:51:42 +08:00
softsimon
f305dba50c Merge pull request #4332 from mempool/mononaut/fix-docker-pid-config
Fix stray comma in docker backend config
2023-10-29 15:55:47 +08:00
Mononaut
5523c77a04 Fix stray , in docker backend config 2023-10-28 21:06:33 +00:00
Mononaut
83fde600f1 Enforce purging rate minimum on recommended fees 2023-10-25 17:46:04 +00:00
orangesurf
d7c60d9b11 Merge pull request #4324 from orangesurf/master
Add primal.net logo to footer
2023-10-23 19:14:08 +01:00
TKone7
4ca273c8c1 Agree to Contributor License Agreement 2023-10-23 15:56:07 +02:00
TKone7
59a92d0363 Fix cleanup logic
Keep only cache entries with an expiry in the future.
2023-10-23 15:49:34 +02:00
fanquake
26f5776d6d Upgrade bitcoin core to v25.1 2023-10-23 14:44:21 +01:00
fanquake
abee175f4f contrib: add fanquake CLA 2023-10-23 14:44:21 +01:00
orangesurf
9ca41a7608 Merge branch 'master' into master 2023-10-22 17:25:20 +01:00
Mononaut
6efeeb1d64 Hide mempool count line by default 2023-10-20 15:10:40 +00:00
Boris Nagaev
2bc3352785 [lightning] add taproot-channels to node features
Update from https://github.com/lightningnetwork/lnd/blob/master/lnwire/features.go
2023-10-20 04:49:14 +02:00
Boris Nagaev
50460d4025 contributer license 2023-10-20 04:48:34 +02:00
dependabot[bot]
1bc02fd216 Bump @babel/traverse from 7.22.8 to 7.23.2 in /frontend
Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.22.8 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse)

---
updated-dependencies:
- dependency-name: "@babel/traverse"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-19 11:23:40 +00:00
softsimon
413941f5ac Merge pull request #4154 from mempool/mononaut/record-purge-rates
Record purging rate in statistics
2023-10-15 00:25:10 +07:00
softsimon
68854d56cc Merge branch 'master' into mononaut/record-purge-rates 2023-10-14 15:07:03 +07:00
softsimon
a78376a1c5 Merge pull request #4217 from mempool/mononaut/pid-file
Implement pid file & checks
2023-10-14 15:06:14 +07:00
softsimon
a95f1e583d Merge pull request #3923 from pfoytik/pfoytik/incomingTxMA
added moving average to Transactions vBytes per second (vB/s)
2023-10-13 17:40:41 +07:00
dependabot[bot]
0783507821 Bump @babel/core from 7.21.4 to 7.23.2 in /backend
Bumps [@babel/core](https://github.com/babel/babel/tree/HEAD/packages/babel-core) from 7.21.4 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/@babel/core@7.23.2/packages/babel-core)

---
updated-dependencies:
- dependency-name: "@babel/core"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-12 02:38:59 +00:00
Peter
76621464f1 ma vbytes 2023-10-11 08:09:06 -04:00
Felipe Knorr Kuhn
e9e507af69 Fix default config path 2023-10-10 19:53:57 -07:00
Mononaut
af3d6eccfb Fix node group map channel count 2023-10-11 01:09:10 +00:00
orangesurf
21ede8671d Update global-footer.component.html 2023-10-09 19:01:48 +00:00
orangesurf
e27cf33981 Improve footer formatting for small screens 2023-10-08 17:52:03 +01:00
orangesurf
02c892aa07 Merge branch 'mempool:master' into master 2023-10-08 17:39:47 +01:00
Felipe Knorr Kuhn
a35c8be25c Configurable unfurler config 2023-10-08 09:03:22 -07:00
wiz
5302b27d55 Merge pull request #4307 from fubz/fubz/electrs-crontab 2023-10-07 09:22:36 +09:00
fubz
5b357eb6b5 fix: configure crontab for electrs single script 2023-10-06 12:48:46 -04:00
nymkappa
7d3f82eca0 [footer] remove "Sign-up" label 2023-10-05 11:16:01 +02:00
nymkappa
20026f974f Merge remote-tracking branch 'origin/nymkappa/accel-button' into nymkappa/mega-branch 2023-10-04 12:11:10 +02:00
nymkappa
3d964fcdfa Merge branch 'nymkappa/about-page-profile-image' into nymkappa/mega-branch 2023-10-04 12:11:05 +02:00
nymkappa
9e8b2957d0 Merge branch 'nymkappa/menu' into nymkappa/mega-branch 2023-10-04 12:10:58 +02:00
nymkappa
c04e92a686 Merge branch 'nymkappa/accelerate-preview-login-cta' into nymkappa/mega-branch 2023-10-04 12:10:46 +02:00
nymkappa
2dd6dd9233 Merge branch 'nymkappa/polish-accelerate-cta' into nymkappa/mega-branch 2023-10-04 12:10:39 +02:00
nymkappa
e9b72776ed Merge remote-tracking branch 'origin/nymkappa/fix-menu-scroll' into nymkappa/mega-branch 2023-10-04 12:10:28 +02:00
nymkappa
23df1f012c Merge remote-tracking branch 'origin/nymkappa/sticky-header-non-bitcoin' into nymkappa/mega-branch 2023-10-04 12:10:17 +02:00
softsimon
10be2c8176 Fix block pagination for liquid 2023-10-04 01:41:49 +04:00
softsimon
e25e99456c Merge pull request #4033 from mempool/nymkappa/no-db-blocks-list
[block list] improve block list when db = false
2023-10-03 20:59:53 +04:00
softsimon
e6236d8cfd Merge branch 'master' into nymkappa/no-db-blocks-list 2023-10-02 21:53:44 +04:00
Mononaut
75c50416f5 Fix PID docker config 2023-10-01 16:43:21 +01:00
Mononaut
0808640ec0 Check database enabled before releasing PID lock file 2023-10-01 16:38:45 +01:00
Mononaut
7dad00523f Implement pid file & checks 2023-10-01 16:37:28 +01:00
softsimon
63a4810b11 Merge pull request #4299 from mempool/knorrium/update_node_matrix
Reduce the test matrix to node v18 and v20
2023-10-01 12:24:22 +04:00
softsimon
0e69f28e58 Merge pull request #4290 from mempool/dependabot/npm_and_yarn/frontend/cypress-13.3.0
Bump cypress from 13.2.0 to 13.3.0 in /frontend
2023-10-01 12:24:09 +04:00
Felipe Knorr Kuhn
77f8999f1e Merge branch 'master' into knorrium/update_node_matrix 2023-09-30 08:59:25 -07:00
Felipe Knorr Kuhn
0e4e0bff78 Reduce the test matrix to node v18 and v20 2023-09-30 08:57:57 -07:00
Felipe Knorr Kuhn
504840c15a Merge branch 'master' into dependabot/npm_and_yarn/frontend/cypress-13.3.0 2023-09-30 08:48:00 -07:00
wiz
b7919afd2f Merge pull request #4294 from mempool/knorrium/docker_updates
Docker updates
2023-09-30 18:53:17 +09:00
Felipe Knorr Kuhn
7c09dd1b70 Set REDIS as disabled by default 2023-09-29 22:14:29 -07:00
Felipe Knorr Kuhn
679e967241 Add missing ACCELERATOR variable 2023-09-29 20:14:40 -07:00
Felipe Knorr Kuhn
f21a31ce86 Remove x86 2023-09-29 19:32:38 -07:00
Felipe Knorr Kuhn
003f3cf8b1 Replace armv7 with x86 2023-09-29 19:30:56 -07:00
Felipe Knorr Kuhn
3ec8a6955c Update Docker GHA 2023-09-29 19:23:38 -07:00
Felipe Knorr Kuhn
fba4759ba1 Update node base images to 20.8.0 2023-09-29 19:16:06 -07:00
Felipe Knorr Kuhn
ea2f39b18a Update mariadb base image 2023-09-29 19:04:54 -07:00
Felipe Knorr Kuhn
ad77b3a6c9 Update the frontend base and ngnix images 2023-09-29 19:04:37 -07:00
Felipe Knorr Kuhn
097db4edcd Update backend base images 2023-09-29 19:03:53 -07:00
Felipe Knorr Kuhn
e9e2c2f7b5 Remove unused files 2023-09-29 19:03:29 -07:00
Mononaut
420fbf3d6f Hide the blockchain arrow when transaction is replaced 2023-09-29 00:02:01 +01:00
dependabot[bot]
7a1cd0ff6a Bump cypress from 13.2.0 to 13.3.0 in /frontend
Bumps [cypress](https://github.com/cypress-io/cypress) from 13.2.0 to 13.3.0.
- [Release notes](https://github.com/cypress-io/cypress/releases)
- [Changelog](https://github.com/cypress-io/cypress/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/cypress-io/cypress/compare/v13.2.0...v13.3.0)

---
updated-dependencies:
- dependency-name: cypress
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-28 02:23:46 +00:00
wiz
f83fed62ce Merge pull request #4286 from mempool/wiz/bump-nodejs-v20.7.0
Bump NodeJS version to v20.7.0
2023-09-27 14:39:04 +09:00
wiz
72fdcb749f Bump NodeJS version to v20.7.0 2023-09-27 14:23:07 +09:00
wiz
21a78e37d1 Merge pull request #4112 from Emzy/ops/nginx-buffer-size
Fixing proxy_buffer_size error nginx.conf
2023-09-27 12:10:42 +09:00
wiz
feed25b641 Merge branch 'master' into ops/nginx-buffer-size 2023-09-27 12:10:25 +09:00
softsimon
5e95d8d6ce Merge pull request #4281 from mempool/nymkappa/fix-blockchain-width-liquid
[ui] don't add 120px to blockchain component on liquid
2023-09-26 00:28:48 +04:00
orangesurf
6de8cbe9b9 Add primal.net logo to footer 2023-09-25 19:57:52 +01:00
softsimon
9cf2db77b4 Merge pull request #4279 from mempool/knorrium/hardened_sync_assets
Fixes to sync-assets
2023-09-24 22:40:33 +04:00
Felipe Knorr Kuhn
372fb38722 Skip syncing Liquid assets if BASE_MODULE is not set to liquid 2023-09-24 10:31:14 -07:00
Felipe Knorr Kuhn
c35f8a3f08 Add SKIP_SYNC and verbosity from previous PR 2023-09-23 15:39:00 -07:00
Mononaut
6773af92ed Add standalone mempool block visualization page 2023-09-23 23:09:11 +01:00
Felipe Knorr Kuhn
4ed629a8ea Minor improvements to sync-assets 2023-09-23 14:43:54 -07:00
Felipe Knorr Kuhn
67b2aa2ff0 Add trailing slash to the sync-assets script 2023-09-23 14:42:54 -07:00
Mononaut
72750267d0 Enable navigation from standalone block page 2023-09-23 22:26:21 +01:00
Felipe Knorr Kuhn
24b3ca559d Add block delta to the logs 2023-09-23 13:32:12 -07:00
Felipe Knorr Kuhn
5edd83d496 Merge branch 'master' into knorrium/add_sync_check_script 2023-09-23 13:20:42 -07:00
softsimon
36dc5e9a9b Merge pull request #4215 from mempool/dependabot/npm_and_yarn/backend/axios-1.5.0
Bump axios from 1.4.0 to 1.5.0 in /backend
2023-09-24 00:02:02 +04:00
Felipe Knorr Kuhn
693b845c45 Add block height workflow 2023-09-23 11:57:20 -07:00
dependabot[bot]
928d3282a2 Bump axios from 1.4.0 to 1.5.0 in /backend
Bumps [axios](https://github.com/axios/axios) from 1.4.0 to 1.5.0.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.4.0...v1.5.0)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-23 15:20:54 +00:00
softsimon
a567f44b3c Merge pull request #4276 from mempool/knorrium/print_backend_sha_workflow
ops: Add workflow to print the backend info on all servers
2023-09-23 19:20:34 +04:00
softsimon
363b9f5be2 Merge pull request #4275 from mempool/knorrium/update_cypress_deps
Update Cypress to v13 and other test deps
2023-09-23 19:20:05 +04:00
Felipe Knorr Kuhn
52725df296 Add workflow to run the backend info script 2023-09-23 07:58:09 -07:00
Felipe Knorr Kuhn
e3cd7dbf34 Add script to print the backend info on all servers 2023-09-23 07:57:49 -07:00
Felipe Knorr Kuhn
593e72f905 Update Cypress to v13 and other test deps 2023-09-22 18:51:29 -07:00
Mononaut
80afcae645 Fix faq blockchain positioning 2023-09-23 00:40:47 +01:00
Mononaut
f3fc774c2d Add standalone block visualization page 2023-09-21 21:57:54 +01:00
softsimon
8c2d72ad58 Merge branch 'master' into nymkappa/no-db-blocks-list 2023-09-21 20:45:26 +04:00
softsimon
d0696628b2 Merge pull request #4200 from mempool/mononaut/canonical-blocks
Update canonical link with block hash
2023-09-21 12:45:21 +04:00
Mononaut
368ab1dc66 Update canonical link with block hash 2023-09-21 12:31:38 +04:00
softsimon
b6f66a6a28 Merge pull request #4236 from mempool/mononaut/mempool-count-graph
Add mempool transaction count line to graph
2023-09-20 20:26:25 +04:00
softsimon
bda361cf57 Merge pull request #4269 from mempool/mononaut/reduce-blockchain-jumping
Reduce blockchain jumping
2023-09-20 18:20:34 +04:00
Mononaut
1a6a0c12ec Fix blockchain scroll jumping 2023-09-20 03:55:06 +00:00
Mononaut
b645ad3fd8 Reduce thrashing while initializing blockchain scroll position 2023-09-19 22:55:57 +00:00
wiz
b979594a04 Merge pull request #4262 from mempool/wiz/add-va1-mempoolspace-lightning-nodes
Add VA1 mempool.space lightning node pubkeys
2023-09-18 17:43:40 -04:00
wiz
6aceb898df Merge pull request #4248 from orangesurf/master
Add orangesurf contributor declaration & update trademark to registered trademark
2023-09-18 17:27:50 -04:00
Mononaut
c80201e3db hide mempool count line before start of data 2023-09-18 21:13:11 +00:00
Mononaut
ef5d2606b7 Add missing count data to longer statistics timespans 2023-09-18 21:07:24 +00:00
softsimon
1e648a2dce Merge pull request #4265 from mempool/nymkappa/fix-js-error-when-no-geolocation
[lightning] fix js error when there is no geolocation available
2023-09-18 17:23:23 +04:00
softsimon
11058b469c Merge pull request #4209 from mempool/mononaut/address-page-rbf
Notify address page of removed transactions
2023-09-18 17:04:31 +04:00
nymkappa
e79c32010d [lightning] fix js error when there is no geolocation available 2023-09-18 09:44:22 +02:00
wiz
5e4742e51b Merge branch 'master' into master 2023-09-18 00:51:38 -04:00
wiz
38d30d23e5 Add VA1 mempool.space lightning node pubkeys 2023-09-17 20:57:47 -04:00
wiz
47dd2cbd5d ops: Add VA1 servers to prod config 2023-09-17 19:56:33 -04:00
nymkappa
6b8db33a9c [ui] don't add 120px to blockchain component on liquid 2023-09-15 17:11:52 +02:00
nymkappa
14a41b3108 [bisq] sticky header 2023-09-15 16:05:10 +02:00
nymkappa
81d1a809d2 [liquid] sticky header 2023-09-15 16:02:39 +02:00
Mononaut
441b505aa3 Send correct tx conf status in websocket msgs 2023-09-14 23:27:40 +00:00
Mononaut
9b17c16325 Notify address page of removed transactions 2023-09-14 23:25:21 +00:00
Mononaut
c1f0eac8f8 Add REQUEST_TIMEOUT and FALLBACK_TIMEOUT esplora config options 2023-09-14 22:57:37 +00:00
softsimon
83c285e17d Merge pull request #4199 from mempool/mononaut/fix-diff-skeleton-mouseover
Fix js error on mouseover on difficulty skeleton
2023-09-13 13:26:10 +04:00
softsimon
5fabf892ba Merge branch 'master' into mononaut/fix-diff-skeleton-mouseover 2023-09-13 13:22:19 +04:00
nymkappa
a000438277 [UI] menu username ellipsis 2023-09-13 09:30:11 +02:00
nymkappa
e3fffd8fb2 [UI] fix menu scroll issue 2023-09-13 09:21:31 +02:00
orangesurf
0ba4e98f52 Replace other instances of tm use for The Mempool Open Source Project 2023-09-12 19:55:00 +01:00
orangesurf
a1b75c3772 Update to reflect registered trademark 2023-09-12 19:45:18 +01:00
orangesurf
0712195de4 Add orangesurf contributor declaration 2023-09-12 19:29:33 +01:00
nymkappa
a133fa8d41 Merge branch 'master' into nymkappa/tx-overflow 2023-09-12 15:12:27 +02:00
nymkappa
4d6c5a7ce7 Merge branch 'master' into nymkappa/no-db-blocks-list 2023-09-12 15:11:59 +02:00
nymkappa
5dfd1a495e Merge branch 'master' into nymkappa/about-page-profile-image 2023-09-12 14:34:34 +02:00
nymkappa
a463fc289f Merge branch 'master' into nymkappa/menu 2023-09-12 14:34:28 +02:00
nymkappa
a8e6d9b4b9 Merge branch 'master' into nymkappa/accelerate-preview-login-cta 2023-09-12 14:34:22 +02:00
nymkappa
9ed7e80c44 fix typo post merge 2023-09-12 14:15:29 +02:00
nymkappa
596d55e413 Merge branch 'master' into nymkappa/accel-button 2023-09-12 14:05:56 +02:00
Mononaut
71d4aa9ddd Add mempool count line to graph 2023-09-08 01:35:02 +09:00
hunicus
fc2df35a42 Merge branch 'master' into hunicus/enterprise-cta-docs 2023-09-07 02:30:12 +09:00
hunicus
d02838fb59 Implement enterprise cta in docs [mobile] 2023-09-07 02:26:41 +09:00
hunicus
572f6bdbac Fix mining dashboard meta description not showing 2023-09-06 22:42:58 +09:00
hunicus
42a222338b Add missing meta descriptions 2023-09-06 22:42:33 +09:00
hunicus
d630e7217a Make enterprise links not relative 2023-09-06 01:42:19 +09:00
nymkappa
0e1a9d8619 [accelerator] blinking cta, polish accel preview 2023-09-03 16:05:12 +03:00
nymkappa
d09668aaa6 [accelerator] login CTA with redirection 2023-09-03 12:20:30 +03:00
wiz
827b0f6ad1 ops: Make install script wait longer for mysql to start 2023-08-31 16:52:56 +09:00
wiz
e8d85613b4 Merge pull request #4224 from mempool/mononaut/failover-timeout
Bump failover timeout to 5s
2023-08-31 02:38:10 +09:00
wiz
ce3b599bab ops: Add /api/v1/services route for new backend 2023-08-31 02:36:22 +09:00
Mononaut
47a7564cfc Bump failover timeout to 5s 2023-08-31 02:25:28 +09:00
wiz
93aa08b60d Merge branch 'master' into nymkappa/menu 2023-08-31 02:02:50 +09:00
nymkappa
4664e55513 [footer] fix positioning when menu component is not loaded 2023-08-30 18:58:21 +02:00
wiz
7744146ef7 Merge pull request #4188 from mempool/nymkappa/menu
User menu + integrated accelerator if available
2023-08-31 01:55:52 +09:00
wiz
9cb72cff31 Set apple-mobile-web-app-capable to yes 2023-08-31 01:35:10 +09:00
nymkappa
98119b3e54 Merge remote-tracking branch 'origin/nymkappa/menu' into nymkappa/menu 2023-08-30 18:32:56 +02:00
nymkappa
f5a3e78cbe [css] fix spacing at the top x2 2023-08-30 18:32:14 +02:00
wiz
515d2656e7 Set apple-mobile-web-app-status-bar-style to black 2023-08-31 01:23:07 +09:00
wiz
339a21caaa Merge branch 'master' into nymkappa/menu 2023-08-31 01:01:00 +09:00
wiz
a7c0d33de8 Merge pull request #4219 from mempool/mononaut/accelerator-preview-concept
Accelerator preview concept
2023-08-31 00:58:24 +09:00
Mononaut
d1ef1afc9c Fix default min/max/default userbid 2023-08-31 00:32:54 +09:00
wiz
bf4a1fcd7a Merge pull request #4221 from hunicus/add-meta-descriptions
Add meta descriptions
2023-08-31 00:29:46 +09:00
Mononaut
d6044331e1 Hide balance unless insufficient for max cost 2023-08-31 00:15:09 +09:00
wiz
9fdb164b64 Merge branch 'master' into add-meta-descriptions 2023-08-31 00:09:57 +09:00
hunicus
d691bf2714 Add meta titles+descriptions to pages missing them 2023-08-30 23:59:51 +09:00
hunicus
cd366177ba Add meta descriptions for mempool and liquid 2023-08-30 21:10:59 +09:00
hunicus
6312884234 Add meta descriptions for bisq 2023-08-30 20:47:57 +09:00
hunicus
d1f26f0491 Add meta descriptions to docs page
Also move all meta tag setting to ngDoCheck()
because page titles were not updating when
user switched docs tabs.
2023-08-30 20:47:57 +09:00
Mononaut
ed12e30517 Hide fee diagram on mobile 2023-08-30 17:16:39 +09:00
Mononaut
cb363aca23 Simplify acceleration quote 2023-08-30 16:55:24 +09:00
Mononaut
c753a8e92a Accelerator fee diagram concept 2023-08-30 16:55:24 +09:00
nymkappa
c44276027c [auto scroll] fix documention anchor scrolling 2023-08-29 15:51:17 +02:00
nymkappa
91fbd0864b [css] fix footer position 2023-08-29 14:34:56 +02:00
nymkappa
c2c4047ffd [css] fix spacing at the top 2023-08-29 14:19:02 +02:00
nymkappa
9427ba96a2 Merge branch 'master' into nymkappa/menu 2023-08-29 10:53:09 +02:00
nymkappa
7c11f0a3da [tx] fix eta css 2023-08-29 10:50:13 +02:00
softsimon
6780ba82d0 Merge pull request #4213 from mempool/mononaut/live-cpfp-updates
Send cpfp/effective fee rate changes to subscribed websocket clients
2023-08-29 10:17:33 +02:00
softsimon
6d643604d0 Merge branch 'master' into mononaut/live-cpfp-updates 2023-08-29 10:12:55 +02:00
nymkappa
7ae4b451e4 [auth] remove auto logout when imageMd5 no in localstorage 2023-08-29 09:31:18 +02:00
nymkappa
bbd1f088d1 [footer] only show cta if official && ACCELERATOR 2023-08-28 16:20:30 +02:00
nymkappa
3060aecddb [status badge] reposition a bit higher 2023-08-28 15:57:06 +02:00
nymkappa
7a765cecd9 [footer] only show cta if official 2023-08-28 15:41:45 +02:00
nymkappa
03e9592c79 Merge pull request #4216 from mempool/mononaut/fix-menu-blockchain-offset
Fix bad blockchain offset after services -> dash
2023-08-28 10:56:18 +02:00
Mononaut
c7b89f31dd Fix bad blockchain offset after services -> dash 2023-08-28 17:42:32 +09:00
nymkappa
899b230760 Merge remote-tracking branch 'origin/nymkappa/menu' into nymkappa/menu 2023-08-28 10:24:52 +02:00
nymkappa
d787ef99c4 [typo] the Mempool Accelerator -> Mempool Accelerator 2023-08-28 10:24:44 +02:00
wiz
043ab008db Merge branch 'master' into nymkappa/menu 2023-08-28 16:43:03 +09:00
nymkappa
4abc4e96a8 [typo] satss -> sats 2023-08-28 09:34:50 +02:00
nymkappa
7fd8790750 [auth] fix blinking profile picture 2023-08-28 09:29:13 +02:00
nymkappa
8ba4a7b421 [ui] polish x2 2023-08-27 19:17:03 +02:00
nymkappa
78ea9cbd16 [ui] polish x1 2023-08-27 12:52:58 +02:00
softsimon
727937b8ae Merge pull request #4135 from mempool/hunicus/citadel-link
Change citadel link on about page
2023-08-27 11:42:52 +02:00
nymkappa
5f4add3e22 [tx] fix css when accel not available 2023-08-27 09:07:47 +02:00
wiz
c4f8afbaf7 Merge pull request #4195 from mempool/junderw/rusttoolchain 2023-08-27 13:19:15 +09:00
Mononaut
528877f43f Send cpfp/effective fee rate changes to subscribed ws clients 2023-08-27 00:30:55 +09:00
nymkappa
a3d61fa525 [accelerator] show payment preview when not logged in 2023-08-26 15:07:05 +02:00
nymkappa
c0308fbc0d Merge branch 'master' into nymkappa/menu 2023-08-26 14:01:07 +02:00
softsimon
24696d0408 Merge pull request #4183 from mempool/mononaut/attitude-adjustment
Don't overload core with mempool tx requests
2023-08-26 12:28:26 +02:00
nymkappa
b9838fda8d Merge branch 'master' into mononaut/attitude-adjustment 2023-08-26 11:48:21 +02:00
nymkappa
726bd51abb [debug] update versioning print 2023-08-26 11:27:45 +02:00
nymkappa
1fe08d1234 [accelerator] fix overflow in tx page integrated accel 2023-08-26 10:05:04 +02:00
nymkappa
1ca136fa75 Merge pull request #4212 from mempool/nymkappa/accelerate-preview
Nymkappa/accelerate preview
2023-08-26 09:53:29 +02:00
nymkappa
fcecbe4967 [tx] integrated accelerator 2023-08-26 09:52:55 +02:00
hunicus
d42a3f74ec Add description to index html and seo service 2023-08-26 14:18:55 +09:00
wiz
dc44f1b618 ops: Fix WebGL for unfurler 2023-08-26 04:40:12 +09:00
wiz
0fde6dd908 ops: Bump prod NodeJS version to v20.5.1 2023-08-25 23:34:50 +09:00
wiz
4eb494baec ops: Increase FreeBSD bitcoin node shutdown timeout to 600 2023-08-25 23:29:03 +09:00
wiz
c1b2f1f2c7 ops: Disable tor in prod install script 2023-08-25 23:24:51 +09:00
wiz
a6d2887847 Merge branch 'master' into nymkappa/menu 2023-08-25 23:13:32 +09:00
nymkappa
f9895a492c Merge branch 'nymkappa/menu' into nymkappa/accelerate-preview 2023-08-24 18:23:30 +02:00
nymkappa
ac56f70f6f Merge pull request #4176 from mempool/nymkappa/fix-eta
[tx] fix eta css with accelerate button
2023-08-24 18:21:27 +02:00
Mononaut
f295392dca Record purging rate in statistics 2023-08-24 22:04:41 +09:00
nymkappa
c89e283c8e [tx] start adding acceleration preview 2023-08-24 14:17:31 +02:00
nymkappa
3aa938a94b Merge pull request #4202 from mempool/mononaut/dynamic-width-chain
Dynamic width chain
2023-08-24 10:42:46 +02:00
Mononaut
20fff97804 restore window resize listener 2023-08-24 17:28:21 +09:00
Mononaut
d1f7026804 hambuger 2023-08-24 17:28:19 +09:00
Mononaut
2da31c4d4a Slide blockchain to compensate for menu 2023-08-24 17:27:31 +09:00
Mononaut
975ba653a2 Dynamically resize blockchain to fit container 2023-08-24 17:27:31 +09:00
softsimon
f12fabe030 Merge pull request #4206 from mempool/dependabot/npm_and_yarn/frontend/frontend-angular-dependencies-f1c021e5b3
Bump the frontend-angular-dependencies group in /frontend with 12 updates
2023-08-24 10:17:12 +02:00
dependabot[bot]
25d75efa09 Bump the frontend-angular-dependencies group
Bumps the frontend-angular-dependencies group in /frontend with 12 updates:

| Package | From | To |
| --- | --- | --- |
| [@angular-devkit/build-angular](https://github.com/angular/angular-cli) | `16.1.4` | `16.2.0` |
| [@angular/animations](https://github.com/angular/angular/tree/HEAD/packages/animations) | `16.1.5` | `16.2.2` |
| [@angular/cli](https://github.com/angular/angular-cli) | `16.1.4` | `16.2.0` |
| [@angular/common](https://github.com/angular/angular/tree/HEAD/packages/common) | `16.1.5` | `16.2.2` |
| [@angular/compiler](https://github.com/angular/angular/tree/HEAD/packages/compiler) | `16.1.5` | `16.2.2` |
| [@angular/core](https://github.com/angular/angular/tree/HEAD/packages/core) | `16.1.5` | `16.2.2` |
| [@angular/forms](https://github.com/angular/angular/tree/HEAD/packages/forms) | `16.1.5` | `16.2.2` |
| [@angular/localize](https://github.com/angular/angular) | `16.1.5` | `16.2.2` |
| [@angular/platform-browser](https://github.com/angular/angular/tree/HEAD/packages/platform-browser) | `16.1.5` | `16.2.2` |
| [@angular/platform-browser-dynamic](https://github.com/angular/angular/tree/HEAD/packages/platform-browser-dynamic) | `16.1.5` | `16.2.2` |
| [@angular/platform-server](https://github.com/angular/angular/tree/HEAD/packages/platform-server) | `16.1.5` | `16.2.2` |
| [@angular/router](https://github.com/angular/angular/tree/HEAD/packages/router) | `16.1.5` | `16.2.2` |


Updates `@angular-devkit/build-angular` from 16.1.4 to 16.2.0
- [Release notes](https://github.com/angular/angular-cli/releases)
- [Changelog](https://github.com/angular/angular-cli/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular-cli/compare/16.1.4...16.2.0)

Updates `@angular/animations` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/animations)

Updates `@angular/cli` from 16.1.4 to 16.2.0
- [Release notes](https://github.com/angular/angular-cli/releases)
- [Changelog](https://github.com/angular/angular-cli/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular-cli/compare/16.1.4...16.2.0)

Updates `@angular/common` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/common)

Updates `@angular/compiler` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/compiler)

Updates `@angular/core` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/core)

Updates `@angular/forms` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/forms)

Updates `@angular/localize` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/compare/16.1.5...16.2.2)

Updates `@angular/platform-browser` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/platform-browser)

Updates `@angular/platform-browser-dynamic` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/platform-browser-dynamic)

Updates `@angular/platform-server` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/platform-server)

Updates `@angular/router` from 16.1.5 to 16.2.2
- [Release notes](https://github.com/angular/angular/releases)
- [Changelog](https://github.com/angular/angular/blob/main/CHANGELOG.md)
- [Commits](https://github.com/angular/angular/commits/16.2.2/packages/router)

---
updated-dependencies:
- dependency-name: "@angular-devkit/build-angular"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/animations"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/cli"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/common"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/compiler"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/core"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/forms"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/localize"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/platform-browser"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/platform-browser-dynamic"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/platform-server"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
- dependency-name: "@angular/router"
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: frontend-angular-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-24 02:53:59 +00:00
nymkappa
c8100712e8 [footer] polish breakpoints in /services/* 2023-08-23 16:17:07 +02:00
nymkappa
a7b2c39f51 [footer] re-add missing tagline 2023-08-23 15:02:36 +02:00
nymkappa
3d9fa5076b Merge remote-tracking branch 'origin/nymkappa/menu' into nymkappa/menu 2023-08-23 14:40:29 +02:00
nymkappa
9fa715e403 [footer] re-add main CTA with better design 2023-08-23 14:40:16 +02:00
nymkappa
9ee11b64e9 [menu] disable hamburger icon when not logged in 2023-08-23 14:39:58 +02:00
nymkappa
8c90d4ba98 Merge branch 'master' into nymkappa/menu 2023-08-23 12:21:23 +02:00
nymkappa
b333c211f7 [menu] fix non clickable hamburger when logged out 2023-08-23 11:50:47 +02:00
Mononaut
ab8386adea Set no-cache on unfurl failure fallback response 2023-08-23 02:10:57 +09:00
wiz
b180fe694f ops: Tweak nginx config for gone paths and render expires 2023-08-23 01:09:11 +09:00
Mononaut
b7474b29e4 Use symlink to avoid duplicate fallback images 2023-08-23 00:34:55 +09:00
wiz
6c7d33f681 Merge pull request #4203 from mempool/mononaut/fix-unfurl-fallbacks
Fix unfurl fallback img routes
2023-08-23 00:31:48 +09:00
Mononaut
6946bc9da9 Fix unfurl fallback img routes 2023-08-23 00:11:24 +09:00
nymkappa
8fb566858f [css] make sure <main> cannot be larger than viewport 2023-08-22 15:44:32 +02:00
nymkappa
379e1470fd [menu] fix menu close trigger, fix menu scroll on mobile safari 2023-08-22 14:59:23 +02:00
nymkappa
c5f0608b46 [debug] footer version same color, inline version in about page 2023-08-22 14:51:05 +02:00
wiz
063d7e96a1 Merge pull request #4198 from mempool/mononaut/unfurler-fixes
More unfurler fixes
2023-08-22 20:26:03 +09:00
nymkappa
7544357826 [ui] redesign UX for navbar using sticky 2023-08-22 08:35:10 +02:00
nymkappa
5005817529 [ui] tweak profile image 2023-08-21 23:18:55 +02:00
nymkappa
bfc3fbe397 [ui] hide the navbar on scroll 2023-08-21 22:19:05 +02:00
nymkappa
30be7e0f7a [ui] redesign UX for navbar 2023-08-21 22:08:25 +02:00
junderw
18eb6600b0 Fix README to include workaround for legacy versions of npm 2023-08-21 12:53:20 -07:00
junderw
88c0d04c18 Match CI toolchain with rust-toolchain 2023-08-21 12:53:20 -07:00
Mononaut
8ea7bb907c Fix js error on mouseover on difficulty skeleton 2023-08-22 02:40:00 +09:00
Mononaut
0d2df72621 Proxy unfurler resources to local instance 2023-08-22 02:16:46 +09:00
Mononaut
91c0a3e689 More unfurler logging 2023-08-22 02:16:36 +09:00
junderw
b595002c25 Revert "Add a missing [workspace] tag in rust-gbt Cargo to build in git"
This reverts commit fadc46f3b5.
2023-08-21 10:01:40 -07:00
Mononaut
9ba7ab9975 More robust webgl handling 2023-08-22 00:07:44 +09:00
softsimon
7674bee5ad Animating menu 2023-08-21 17:06:12 +02:00
nymkappa
0ee28a335f [header] show anon image if user did not set a picture (to improve later) 2023-08-21 17:04:17 +02:00
nymkappa
285485c69e [about page] /api/v1/about-page -> /api/v1/services/sponsors 2023-08-21 15:27:55 +02:00
nymkappa
b8222bff43 [auth] fix auth not being cleared after logout 2023-08-21 15:01:31 +02:00
nymkappa
3321ae0f1f [debug] always show git hashes in footer 2023-08-21 11:36:40 +02:00
nymkappa
4010047344 Merge remote-tracking branch 'origin/nymkappa/menu' into nymkappa/menu 2023-08-21 11:20:20 +02:00
nymkappa
ce290a449c [debug] show more git hashes in about and footer 2023-08-21 11:19:54 +02:00
Jonathan Underwood
b9c151f549 Update rust-toolchain 2023-08-21 17:47:58 +09:00
nymkappa
2ff3e4acb9 Merge branch 'master' into nymkappa/menu 2023-08-21 09:14:24 +02:00
wiz
ead32a4a65 Merge pull request #4194 from TheBlueMatt/msrv
Drop MSRV to 1.63
2023-08-21 16:06:13 +09:00
nymkappa
a1e2d2fd74 [debug] SERVICES -> GIT_COMMIT_HASH_MEMPOOL_SPACE in env 2023-08-21 08:57:27 +02:00
Matt Corallo
122a721d7a sign cla 2023-08-21 05:04:33 +00:00
Matt Corallo
6088fffc09 Drop MSRV to 1.63
Debian bookworm ships with 1.63, and since the change is trivial,
there's little reason to not support people running mempool on
Debian.
2023-08-21 04:03:37 +00:00
Matt Corallo
fadc46f3b5 Add a missing [workspace] tag in rust-gbt Cargo to build in git
If cargo detects its being run in a git tree, it looks for a
top-level `Cargo.toml`. When failing to find one, it errors out,
saying "current package believes it's in a workspace when it's not."

Instead, we add a `[workspace]` tag to let cargo know that rust-gbt
is not, in fact, in a rust workspace.
2023-08-21 04:00:52 +00:00
nymkappa
e82b43e340 [footer] fix footer sizing in /services 2023-08-20 22:54:12 +02:00
nymkappa
22886cb32d [debug] show services backend version in /services global footer, show services global frontend build in /about 2023-08-20 22:53:33 +02:00
nymkappa
ef554ad67b Merge branch 'master' into nymkappa/menu 2023-08-20 08:21:38 +02:00
nymkappa
b64b6fb3c7 [menu] fix json.parse on missing auth in localstorage 2023-08-20 08:11:55 +02:00
wiz
8e73e76312 ops: Tweak proxy_cache_valid time for unfurler/slurper cache 2023-08-20 02:36:34 +09:00
wiz
9d978ead6d ops: Set expires headers for unfurler/slurper responses 2023-08-20 00:01:22 +09:00
wiz
655eb31107 ops: Tweak nginx cache valid time for unfurler/slurper 2023-08-19 23:27:08 +09:00
wiz
15bd7bc068 Merge pull request #4187 from mempool/mononaut/unfurler-debugging
Unfurler debugging
2023-08-19 23:23:53 +09:00
wiz
65847547b9 ops: Tweak nginx cache for slurper 2023-08-19 23:23:28 +09:00
Mononaut
ed9d31686e Add cluster/tab to unfurler logs 2023-08-19 21:07:10 +09:00
Mononaut
7f2a459575 Fix SSR puppeteer page initialization 2023-08-19 21:05:28 +09:00
Mononaut
126e87a746 More more verbose unfurler logs 2023-08-19 19:35:52 +09:00
Mononaut
2819cea509 Reduce core mempool tx sync to 8 concurrent requests 2023-08-19 19:02:30 +09:00
junderw
2a8a403da7 Use p-limit to limit concurrent requests 2023-08-19 18:53:32 +09:00
Mononaut
3bda5537d7 More verbose unfurler logs 2023-08-19 18:50:57 +09:00
Mononaut
df8b6cd53c Fix unfurler resource proxying 2023-08-19 18:40:11 +09:00
Mononaut
e4fcadf39b More verbose comments on $getMempoolTransactionsExtended 2023-08-19 04:47:19 +09:00
nymkappa
c4f2f4ca66 [menu] handle logout without reload, show signin in sidebar when not logged in 2023-08-18 18:33:09 +02:00
nymkappa
0c1221dc07 [menu] only show on official mainnet with accelerator enabled 2023-08-18 18:12:45 +02:00
nymkappa
d1c9e8b56e [menu] show username at the top of the menu 2023-08-18 18:04:40 +02:00
Mononaut
1b2122cd35 Don't overload core with mempool tx requests 2023-08-19 01:02:27 +09:00
nymkappa
5aff2c74e6 [menu] show hamburger when logged out, fix menu scrolling on small screen 2023-08-18 17:56:07 +02:00
softsimon
f36ee36576 Merge pull request #4180 from mempool/junderw/fix-nbits-calculations
Fix: calcBitsDifference regtest fix
2023-08-18 17:27:25 +02:00
junderw
08a09bf371 Fix: calcBitsDifference regtest fix 2023-08-17 23:57:20 -07:00
nymkappa
1bdbb1b908 [menu] logout is a special item 2023-08-17 22:13:06 +02:00
wiz
f1f97320df ops: Fix install script crash for removed electrs-start-liquidtestnet 2023-08-18 03:51:09 +09:00
softsimon
52cc3022c6 Merge pull request #4146 from mempool/mononaut/fix-mempool-blocks-stacking
Fix stacked mempool blocks layout & width
2023-08-17 19:17:19 +02:00
nymkappa
91e3943a74 [menu] call services api to fetch user menu 2023-08-17 18:59:27 +02:00
nymkappa
23b871631a [menu] write menu component with hardcoded values 2023-08-17 18:51:39 +02:00
wiz
e975bacaa1 Merge branch 'master' into mononaut/fix-mempool-blocks-stacking 2023-08-17 23:21:00 +09:00
nymkappa
ab911d5c9e [tx] fix eta css with accelerate button 2023-08-17 14:28:33 +02:00
wiz
2c9e20dd87 ops: Always start xorg for unfurler even if no GPU detected 2023-08-17 18:38:17 +09:00
wiz
487d5de0ef Merge pull request #4152 from mempool/mononaut/unfurler-mode-headers
Select unfurl mode with route prefix
2023-08-17 16:48:26 +09:00
wiz
1653f003bc Merge branch 'master' into mononaut/unfurler-mode-headers 2023-08-17 16:39:30 +09:00
softsimon
21ea6f82fc Merge pull request #4134 from mempool/knorrium/dependabot_frontend_groups
Add frontend dependency groups to dependabot
2023-08-17 06:22:11 +02:00
softsimon
ca682d5879 Merge pull request #4164 from mempool/knorrium/fix_docker_start
Fix Docker start script and unit test
2023-08-17 06:20:39 +02:00
Felipe Knorr Kuhn
cd3b11407b Merge branch 'master' into knorrium/dependabot_frontend_groups 2023-08-16 21:15:28 -07:00
Felipe Knorr Kuhn
004208e9c8 Fix linting 2023-08-16 16:16:04 -07:00
Felipe Knorr Kuhn
44d2ea1263 Fix Docker config unit test to work with array values 2023-08-16 16:08:45 -07:00
Felipe Knorr Kuhn
27797b8f1d Add missing ESPLORA FALLBACK vars to the start script 2023-08-16 16:08:01 -07:00
Felipe Knorr Kuhn
9aedccdb32 Remove trailing comma on the Docker JSON 2023-08-16 16:07:27 -07:00
Mononaut
b1e1601ccf Switch unfurl proxy header to url prefix 2023-08-16 21:55:03 +09:00
hunicus
1dd66e6695 Add bimi svg 2023-08-16 12:43:36 +09:00
wiz
681d4bffd7 Merge branch 'master' into mononaut/unfurler-mode-headers 2023-08-16 04:07:35 +09:00
wiz
8f2a2d1c81 ops: Add delay before warm cache loop begins 2023-08-16 04:03:17 +09:00
wiz
0bfd01e732 ops: Add unfurl/slurp queries to nginx warm cache script 2023-08-16 03:51:10 +09:00
wiz
83a92a7e3a ops: Add nginx config for /unfurler and /slurper prefixes 2023-08-16 03:27:09 +09:00
softsimon
dbdbe29281 Merge pull request #4153 from mempool/hunicus/rm-luminex
Remove luminex from about page
2023-08-14 21:30:44 +01:00
hunicus
a2f67990b5 Remove luminex from about page 2023-08-15 04:24:34 +09:00
Mononaut
5511795fbb Fix mempool slide on page change 2023-08-14 19:34:31 +09:00
Mononaut
13f6f9f9e5 Select unfurl mode with X-Unfurl-Type header 2023-08-14 18:05:09 +09:00
Mononaut
8c21d106fc Fix stacked mempool blocks layout & width 2023-08-14 02:37:46 +09:00
wiz
e9165e5dd8 Merge pull request #4107 from mempool/mononaut/unfurler-fixes
Quick fixes for unfurler/seo renderer
2023-08-13 15:40:22 +09:00
hunicus
0a918b8fa8 Add enterprise note to backend readme 2023-08-13 13:04:58 +09:00
hunicus
102579baa9 Add enterprise note to production readme 2023-08-13 13:00:47 +09:00
hunicus
b3f90e2981 Add mempool enterprise note to top-level readme 2023-08-13 12:55:14 +09:00
wiz
2e8a9c75ee Merge pull request #4138 from mempool/mononaut/accelerate-mainnet-only
Hide accelerate CTA on non-mainnet networks
2023-08-12 17:19:46 +09:00
hunicus
a23881e62c Implement enterprise cta in docs [desktop] 2023-08-11 17:11:05 +09:00
Mononaut
e8e245cc75 Hide accelerate CTA on non-mainnet networks 2023-08-10 20:27:49 +09:00
nymkappa
6199216c54 use new services api to fetch chads profile image as well 2023-08-10 18:08:30 +09:00
nymkappa
b988a4c526 use new services api to fetch chad/whale profile image 2023-08-10 18:01:05 +09:00
hunicus
45ba50e82c Change citadel link on about page 2023-08-10 16:26:07 +09:00
wiz
b6da116dfc Merge branch 'master' into mononaut/unfurler-fixes 2023-08-10 16:02:48 +09:00
wiz
a9e92d0593 Merge pull request #4121 from mempool/hunicus/footer-refinement-exp
Refine footer design/layout
2023-08-10 16:02:20 +09:00
wiz
db90e77a32 Merge branch 'master' into hunicus/footer-refinement-exp 2023-08-10 15:51:07 +09:00
Felipe Knorr Kuhn
c2cad416e2 Add frontend dependency groups to dependabot 2023-08-09 22:33:59 -07:00
wiz
7191ca6915 Merge pull request #4133 from mempool/knorrium/dependabot_tweak 2023-08-10 13:59:19 +09:00
Felipe Knorr Kuhn
fb3cb127b0 Set dependabot to fix the package.json file in addition to the lock file 2023-08-09 21:51:11 -07:00
wiz
9f007d78f8 ops: Fix fonts config from installer 2023-08-09 23:44:03 +09:00
wiz
c5bdcec164 ops: Add delay before starting bitcoind/elementsd/electrs 2023-08-09 23:43:49 +09:00
hunicus
d4f9600ff1 Make footer refinements responsive 2023-08-09 16:42:16 +09:00
softsimon
8b260ce21c Merge pull request #4108 from mempool/simon/disable-historical-testnets
Handle historical price API calls when using any testnet
2023-08-09 10:51:58 +04:00
nymkappa
89be841e64 [accelerator] hide accelerate button if already accelerating 2023-08-08 17:10:59 +09:00
Stephan Oeste
fc73dcc344 Fixing proxy_buffer_size error nginx.conf 2023-08-07 20:08:30 +02:00
softsimon
8d7c04bcda Merge pull request #4111 from mempool/nymkappa/mining-pool-api
[mining] add /api/v1/pools API to list mining pools
2023-08-07 14:33:58 +09:00
nymkappa
e4c17e5011 [mining] add /api/v1/mining/pools API to list mining pools 2023-08-07 12:16:01 +09:00
softsimon
b03c3745a2 Merge pull request #4110 from mempool/knorrium/backend_unit_test_tweaks
Backend unit test tweaks
2023-08-07 12:14:01 +09:00
softsimon
41eecfa7df Merge pull request #4095 from mempool/mononaut/refactor-address-tracking
Refactor websocket address tracking
2023-08-07 12:13:07 +09:00
Mononaut
38e9021e8c simplify scriptpubkey tracking 2023-08-07 10:43:42 +09:00
Felipe Knorr Kuhn
adc46b6ae5 Update Github workflow to run with the CI flag 2023-08-06 08:01:28 -07:00
Felipe Knorr Kuhn
8912bac0ac Add test:ci task 2023-08-06 08:00:49 -07:00
Felipe Knorr Kuhn
e4fca3c2b7 Log verbose Docker checks only when running on CI 2023-08-06 08:00:30 -07:00
hunicus
2855fff702 Make basic footer refinement
TODO: responsiveness
2023-08-06 16:16:16 +09:00
Mononaut
8dbf9f29cf Send unfurler fallback imgs directly 2023-08-06 15:49:11 +09:00
softsimon
cbebbd40f1 Handle price API in the frontend when testnet 2023-08-06 15:41:57 +09:00
Mononaut
9aa778e44e reboot unfurler periodically 2023-08-06 13:47:38 +09:00
Mononaut
6fc645a454 Remove unfurler soft404 debug spam 2023-08-06 13:47:20 +09:00
softsimon
b977c4332f Merge pull request #4076 from mempool/knorrium/update_cypress_deps
Update Cypress deps
2023-08-06 13:06:46 +09:00
Felipe Knorr Kuhn
a79e214a6a Merge branch 'master' into knorrium/update_cypress_deps 2023-08-05 14:24:24 -07:00
wiz
6f11defea2 Merge pull request #4103 from mempool/ops/enable-prod-replication
Enable audit replication for production
2023-08-05 22:10:10 +09:00
wiz
53ba48de9f ops: Enable replication for production 2023-08-05 21:57:43 +09:00
wiz
3fb097bfff Merge pull request #4099 from mempool/mononaut/esplora-failover
new health-check based esplora failover mechanism
2023-08-05 20:59:30 +09:00
Mononaut
9138c3b676 always switch back to local if available 2023-08-05 20:39:02 +09:00
softsimon
2ceafcacc6 Disable historical prices on testnets 2023-08-05 20:29:00 +09:00
Mononaut
85935d8f90 allow protocol, port & path in fallback urls 2023-08-05 20:06:19 +09:00
Mononaut
ae5e1e6d29 Fix failover debug prints 2023-08-05 19:55:33 +09:00
softsimon
bcfc704f7a Merge pull request #4102 from mempool/hunicus/footer-space
Add space below logo in footer
2023-08-05 19:37:41 +09:00
Mononaut
e512feef74 Add debug prints, fix POST request 2023-08-05 19:25:00 +09:00
softsimon
b11e31e54b Merge branch 'master' into knorrium/update_cypress_deps 2023-08-05 19:13:19 +09:00
hunicus
b1ed05e95e Add space below logo in footer 2023-08-05 19:06:25 +09:00
Mononaut
2095f90262 new health-check based esplora failover mechanism 2023-08-05 19:02:46 +09:00
wiz
794a4ded9c Merge pull request #3169 from mempool/mononaut/seo-ssr
dynamically render search crawler requests
2023-08-05 18:34:45 +09:00
wiz
cf4f779e59 Merge remote-tracking branch 'origin/master' into mononaut/seo-ssr 2023-08-05 18:23:12 +09:00
softsimon
c1c69d7272 Merge pull request #4096 from mempool/mononaut/speed-up-rbf-detection
Speed up RBF detection
2023-08-05 17:37:50 +09:00
softsimon
a4e7219214 Adding RBF tests 2023-08-05 17:20:07 +09:00
softsimon
af8e5b60ee Merge pull request #4098 from mempool/fix/liquid-bits-calc
Fix: Difficulty calculations for Liquid networks must be NaN
2023-08-05 17:10:08 +09:00
Jonathan Underwood
6ff7a59bfb Merge branch 'master' into fix/liquid-bits-calc 2023-08-05 00:00:02 -07:00
softsimon
95341806c3 Merge pull request #4100 from mempool/feat/rust-build-revert
Feature: Build Rust during build script AND install
2023-08-05 15:58:16 +09:00
junderw
e994aac162 Feature: Build Rust during build script AND install 2023-08-04 23:40:10 -07:00
junderw
ea926660fe Fix: Difficulty calculations for Liquid networks must be NaN 2023-08-04 20:42:14 -07:00
nymkappa
223f6df371 fix 'large' class trigger 2023-08-05 10:52:11 +09:00
nymkappa
869a879676 Merge branch 'master' into nymkappa/tx-overflow 2023-08-05 10:10:01 +09:00
nymkappa
5959c426f3 Merge branch 'master' into nymkappa/tx-overflow 2023-08-05 10:09:22 +09:00
Felipe Knorr Kuhn
33a6f81265 Merge branch 'master' into knorrium/update_cypress_deps 2023-08-04 08:51:00 -07:00
Felipe Knorr Kuhn
367bcbda83 Update cypress action to node 18 2023-08-04 08:40:15 -07:00
Felipe Knorr Kuhn
e3114144e1 Tweak imports again 2023-08-04 08:36:05 -07:00
Felipe Knorr Kuhn
da4f891e2f Use full path for import 2023-08-04 08:23:29 -07:00
Felipe Knorr Kuhn
e4a43fcca5 Update tsconfig for the tests 2023-08-04 08:19:19 -07:00
Mononaut
3ec676ca90 Speed up RBF detection 2023-08-04 19:11:49 +09:00
softsimon
9da9c2750d Merge pull request #4064 from mempool/mononaut/better-mobile-difficulty-tooltip
Improve difficulty tooltip display on mobile
2023-08-04 18:41:07 +09:00
softsimon
d2641cc927 Merge pull request #4085 from mempool/mononaut/fast-mempool-sync
use bulk mempool post api to batch mempool update requests
2023-08-04 17:26:01 +09:00
softsimon
b026f5a481 Removing console log 2023-08-04 15:55:22 +09:00
softsimon
45ddab519d Merge pull request #4093 from mempool/fix/packaging-rust-gbt
Fix: Rust-GBT packaging needs fixing
2023-08-04 15:52:20 +09:00
junderw
0535e8c5f9 Fix: Rust-GBT packaging needs fixing 2023-08-04 15:45:34 +09:00
softsimon
b4ec69ce7a Merge pull request #4058 from mempool/mononaut/prices-api
Current fiat prices API
2023-08-04 15:39:35 +09:00
wiz
989e4832cc Merge pull request #3995 from mempool/mononaut/acceleration-viz
Acceleration visualization
2023-08-04 15:34:02 +09:00
softsimon
0d777c24c5 Merge pull request #4090 from mempool/mononaut/missing-latest-replacements
resume tracking subscriptions after websocket reconnect
2023-08-04 15:33:33 +09:00
mononaut
101de3bac7 Fix PRICE_UPDATES_PER_HOUR docker default
Co-authored-by: nymkappa <9780671+nymkappa@users.noreply.github.com>
2023-08-04 15:23:55 +09:00
wiz
c3f83f74ce Merge branch 'master' into mononaut/acceleration-viz 2023-08-04 15:10:02 +09:00
wiz
39e36936bc Merge pull request #3795 from mempool/nymkappa/accelerator-soft-launch
[accelerator] prepare soft launch
2023-08-04 14:31:39 +09:00
nymkappa
11248821c5 hide sponsor buttons 2023-08-04 14:30:40 +09:00
Mononaut
3074d814e7 precompute address transactions for websocket msg loop 2023-08-04 13:59:49 +09:00
softsimon
22aa45f055 Merge pull request #4094 from mempool/dependabot/npm_and_yarn/backend/mysql2-3.6.0
Bump mysql2 from 3.5.2 to 3.6.0 in /backend
2023-08-04 13:56:27 +09:00
softsimon
07f95acc29 Base expiry on update frequency 2023-08-04 13:26:19 +09:00
softsimon
2892bfa1d8 Fixing cycle reset at top of the hour 2023-08-04 13:23:09 +09:00
dependabot[bot]
356ab9c6ae Bump mysql2 from 3.5.2 to 3.6.0 in /backend
Bumps [mysql2](https://github.com/sidorares/node-mysql2) from 3.5.2 to 3.6.0.
- [Release notes](https://github.com/sidorares/node-mysql2/releases)
- [Changelog](https://github.com/sidorares/node-mysql2/blob/master/Changelog.md)
- [Commits](https://github.com/sidorares/node-mysql2/compare/v3.5.2...v3.6.0)

---
updated-dependencies:
- dependency-name: mysql2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-04 02:40:58 +00:00
nymkappa
851d030878 [about] re-enable two sponsor buttons 2023-08-04 10:23:15 +09:00
dni ⚡
f7ec5ca82e Update liquid-master-page.component.html
ngIf for BISQ_ENABLED was missing
2023-08-03 17:47:30 +02:00
softsimon
813f3dc09d Updating config sample 2023-08-03 18:26:24 +09:00
softsimon
172c77328b Changing setting to per hour 2023-08-03 18:22:52 +09:00
softsimon
b213f43a91 Erasing unused PRICE_DATA_SERVER from readme 2023-08-03 17:43:03 +09:00
softsimon
284d39baa8 Update price at least every hour 2023-08-03 17:43:02 +09:00
softsimon
af4d0b4d3f Allow priceUpdater to run without storing to database 2023-08-03 17:43:02 +09:00
softsimon
83a487ecae Setting fixture to fixed number 2023-08-03 17:43:02 +09:00
softsimon
bcb3b39bd8 Updating start.sh and README 2023-08-03 17:43:02 +09:00
softsimon
ae59f95ba9 Refactoring price update config. Fixing last price time. 2023-08-03 17:43:02 +09:00
softsimon
b2d4000b2d Update backend/src/api/prices/prices.routes.ts 2023-08-03 17:43:02 +09:00
softsimon
864d9239ce Update backend/src/__fixtures__/mempool-config.template.json 2023-08-03 17:43:02 +09:00
Mononaut
09c23b1241 configurable price update frequency 2023-08-03 17:43:02 +09:00
Mononaut
22665f149b add /prices api endpoint 2023-08-03 17:43:01 +09:00
nymkappa
683d775c7e Merge branch 'master' into nymkappa/no-db-blocks-list 2023-08-03 16:50:19 +09:00
Mononaut
cb5b96485c resume tracking subscriptions after websocket reconnect 2023-08-03 16:17:17 +09:00
nymkappa
4ee703325a [footer] polish cta using update footer with logo 2023-08-03 16:12:59 +09:00
Mononaut
3d6a8a501d limit mouse events to difficulty bar 2023-08-03 15:51:09 +09:00
nymkappa
0111d8806b Merge branch 'mononaut/acceleration-viz' into nymkappa/accelerator-soft-launch 2023-08-03 15:43:28 +09:00
Mononaut
d06fe83bd9 Improve difficulty tooltip display on mobile 2023-08-03 15:36:36 +09:00
nymkappa
8936273aeb Merge branch 'master' into mononaut/acceleration-viz 2023-08-03 15:28:56 +09:00
nymkappa
99a60ab22a add ACCELERATOR frontend setting 2023-08-03 15:20:48 +09:00
nymkappa
7ec5d8265f toggle header visibility in master page component 2023-08-03 15:20:48 +09:00
nymkappa
1458e89f3a [footer] main cta points to /accelerator 2023-08-03 15:20:48 +09:00
nymkappa
5846862d55 [footer] dynamic CTA button based on login status 2023-08-03 15:20:48 +09:00
nymkappa
727d170c9c [tx] add accel shortcut into transaction component 2023-08-03 15:20:47 +09:00
nymkappa
6c2c62ba2e [lightning] claim your node button 2023-08-03 15:20:47 +09:00
nymkappa
f2ae858097 [sponsors] show profile by tiers on about page 2023-08-03 15:20:19 +09:00
nymkappa
d236d89717 [mining] send pool unique id in /pools API 2023-08-03 15:08:14 +09:00
softsimon
cac2a984ab Merge pull request #4089 from andrewtoth/andrewtoth/sig
Accept CLA
2023-08-03 12:59:18 +09:00
andrewtoth
e0b2ffa527 Accept CLA 2023-08-03 03:46:15 +00:00
softsimon
2c7919ace6 Merge pull request #4065 from mempool/mononaut/log-scale-fee-graph
Use log10 scale for projected block fee graph
2023-08-02 18:35:46 +09:00
wiz
e9cd41722b Merge pull request #4081 from mempool/mononaut/fix-null-coinbase-fee
fix null coinbase fees in block summary
2023-08-02 16:05:09 +09:00
Mononaut
ca0c6b5e6e use bulk mempool/txs post api to batch mempool update requests 2023-08-02 15:05:27 +09:00
softsimon
b1d5ba890f Merge pull request #4084 from mempool/hunicus/30-footer-yacht
Show tool list when no other networks available in footer
2023-08-02 14:44:19 +09:00
softsimon
9373fb3dd1 Minor ngIf else template optimization 2023-08-02 14:34:59 +09:00
softsimon
f8ca53fdf0 Merge pull request #4078 from mempool/fix/difficulty-calc
Fix: Use bits to calculate difficulty instead of floating points
2023-08-02 13:08:55 +09:00
hunicus
ddd5baf44e Show tool list when no other networks available 2023-08-02 12:46:59 +09:00
mononaut
b365ad3ba4 Merge branch 'master' into fix/difficulty-calc 2023-08-02 11:00:32 +09:00
softsimon
63993b01aa Merge pull request #4083 from mempool/mononaut/fix-partial-index-difficulty
fix partially indexed difficulty bug
2023-08-01 18:49:45 +09:00
Mononaut
ab784cede2 fix partially indexed difficulty bug 2023-08-01 18:41:48 +09:00
wiz
648a732352 Merge pull request #3853 from mempool/hunicus/accelerate-disclaimer
Replace disclaimer text regarding tx acceleration
2023-08-01 18:36:41 +09:00
wiz
e5b8b73077 Merge pull request #4080 from mempool/hunicus/30-footer
Add graphic to footer + simplify left footer column
2023-08-01 18:34:17 +09:00
hunicus
8fe78fa12b Improve conditions for showing network links 2023-08-01 18:08:49 +09:00
hunicus
f166cb7974 Remove commented/inactive social links 2023-08-01 17:54:09 +09:00
hunicus
d3532eb734 Improve show conditions for explore links 2023-08-01 17:54:09 +09:00
hunicus
4cb379bb0f Change more networks to networks 2023-08-01 17:54:09 +09:00
hunicus
316028fe66 Add space below tagline 2023-08-01 17:54:09 +09:00
Mononaut
543357f1db fix null coinbase fees in block summary 2023-08-01 17:33:03 +09:00
wiz
c93f52f3a8 Merge branch 'master' into hunicus/30-footer 2023-08-01 16:54:48 +09:00
junderw
9bf334a22d Fix: Use bits to calculate difficulty instead of floating points 2023-08-01 00:52:45 -07:00
softsimon
22e57ae95c Merge pull request #4079 from mempool/simon/mempool-break-poll-limit
Base mempool break limit of current poll rate
2023-08-01 16:00:42 +09:00
hunicus
a1af41804a Implement wiz footer suggestions 2023-08-01 16:00:16 +09:00
softsimon
b0080a5859 Base mempool break limit of current poll rate 2023-08-01 15:55:03 +09:00
wiz
5c36692799 Merge pull request #3973 from mempool/ops/move-electrs-scripts-to-electrs-repo
ops: Move electrs scripts to mempool/electrs repo
2023-08-01 15:38:46 +09:00
wiz
97877053bf Merge pull request #4068 from mempool/mononaut/electrs-blocks
Get blocks from electrs again
2023-08-01 15:33:13 +09:00
softsimon
f9a44a5fbb Merge pull request #4074 from mempool/fix_rust_gbt_typo
Fix rust gbt docker  typo
2023-08-01 14:14:56 +09:00
softsimon
6b5bcaa279 Merge pull request #4077 from bguillaumat/patch-1
Add bguillaumat.txt to contributors
2023-08-01 14:07:18 +09:00
wiz
8c396978a8 Merge branch 'master' into mononaut/electrs-blocks 2023-08-01 13:54:05 +09:00
wiz
a51d2a6aec Merge pull request #4071 from mempool/mononaut/fast-indexing
Fast indexing
2023-08-01 13:53:56 +09:00
Mononaut
a863c17408 Fix difficulty indexing db queries to return bits 2023-08-01 13:28:56 +09:00
Mononaut
0924bb6ac0 Use bits to detect difficulty adjustments, not difficulty 2023-08-01 13:28:56 +09:00
Mononaut
910e67ff36 Get blocks from electrs again 2023-08-01 13:28:56 +09:00
Bastien Guillaumat
aa17f8203c Add bguillaumat.txt to contributors 2023-08-01 03:13:58 +02:00
Felipe Knorr Kuhn
a23cd5ad29 Update Cypress deps 2023-07-31 14:44:59 -07:00
Felipe Knorr Kuhn
b7b6548cce Fix RUST GBT Docker override 2023-07-31 14:11:31 -07:00
Felipe Knorr Kuhn
17f1cb8648 Fix config unit test that was returning early 2023-07-31 14:10:49 -07:00
softsimon
d5dca95fbe Merge pull request #4072 from mempool/simon/electrum-scripthash-fix
Fix scripthash lookup for Electrum*
2023-07-31 21:10:59 +09:00
softsimon
bed7c1b283 Fix scripthash lookup for Electrum* 2023-07-31 18:29:40 +09:00
Mononaut
0d25ef0b5b Get block txs from esplora, index CPFP together with summaries 2023-07-31 18:13:16 +09:00
Mononaut
6b7d8d95f7 reduce mempool poll rate while indexing 2023-07-31 18:13:16 +09:00
Mononaut
bafc0bd9cf fix indexing log prints 2023-07-31 18:13:11 +09:00
softsimon
7a87f74b22 Merge pull request #4070 from mempool/mononaut/redis-fixes
Misc Redis fixes
2023-07-31 17:28:54 +09:00
Mononaut
49db63d888 Faster Redis tx deletion, fix debug log level 2023-07-31 16:38:18 +09:00
Mononaut
363fc1b00b Get blocks from electrs again 2023-07-31 15:39:02 +09:00
wiz
36a26fc2ce Merge pull request #4063 from mempool/mononaut/simple-redis
Simple Redis
2023-07-31 15:34:08 +09:00
softsimon
73b71c4914 Fixing docker config and tests 2023-07-31 14:28:56 +09:00
Mononaut
dcfab218fb Improve Redis logging 2023-07-31 12:21:28 +09:00
Mononaut
c79a597c96 switch from redis-json to simple key-value redis entries 2023-07-31 12:16:37 +09:00
Mononaut
a393f42b5e strip non-essential data from redis cache txs 2023-07-31 12:16:36 +09:00
Mononaut
6ac58f2da7 store redis mempool in sharded json object 2023-07-31 12:16:36 +09:00
Mononaut
a9f8bbbcce Add network and schema versioning to redis cache 2023-07-31 12:16:34 +09:00
Mononaut
d65bddd30b Add transactions to Redis cache in manageable batches 2023-07-31 12:16:34 +09:00
Mononaut
b6cb539470 Fix redis feature merge conflicts 2023-07-31 12:16:34 +09:00
Mononaut
aea2b1ec6b Add RBF data to Redis cache 2023-07-31 12:16:33 +09:00
Mononaut
5138f9a254 Implement Redis cache for block and mempool data 2023-07-31 12:16:33 +09:00
wiz
8cfa4ef1a1 Merge pull request #4066 from mempool/wiz/update-preview-image
Remove text from mempool.space preview image
2023-07-31 11:24:17 +09:00
wiz
16401044f6 Remove text from mempool.space preview image 2023-07-31 11:16:43 +09:00
wiz
c88b7ddc77 ops: Use TK7 for unfurler 2023-07-31 11:12:54 +09:00
Mononaut
945a8ce92e Use log10 scale for projected block fee graph 2023-07-30 18:56:57 +09:00
softsimon
8b012a96f3 Merge pull request #4034 from mempool/mononaut/mobile-difficulty-tooltips
Fix difficulty tooltip position
2023-07-30 14:26:36 +09:00
softsimon
8b6bb54efb Merge pull request #4062 from fiatjaf/patch-1
Create fiatjaf.txt
2023-07-29 23:52:32 +09:00
fiatjaf_
2670589293 Create fiatjaf.txt 2023-07-29 09:27:12 -03:00
softsimon
91eef1c4d9 Merge pull request #4061 from rishkwal/master
rishkwal contributor license agreement added
2023-07-29 21:14:02 +09:00
Rishabh
562a5f6878 rishkwal contributor license agreement added 2023-07-29 15:54:34 +05:30
softsimon
5c20fd71e1 Merge pull request #3905 from mempool/hunicus/msop-r
Update mosp strings from tm to r
2023-07-29 18:34:31 +09:00
softsimon
adf093eca5 Merge pull request #4026 from mempool/nymkappa/charts-landscape-mobile
[graphs] fix min height in mobile landscape
2023-07-29 18:11:33 +09:00
softsimon
d14d286f24 Merge pull request #4057 from dni/patch-1
[BUG]: Update frontend entrypoint.sh
2023-07-29 17:50:58 +09:00
softsimon
ecd80aad6a Merge pull request #4056 from mempool/mononaut/compressed-p2pk
Add support for compressed p2pk addresses
2023-07-29 17:48:26 +09:00
softsimon
1b248c24f1 Merge pull request #4050 from mempool/mononaut/retry-block-txs
Handle failures while fetching block transactions
2023-07-29 17:12:34 +09:00
softsimon
f35f630695 Merge pull request #4060 from Czino/add-contributor-license-agreement
Add contributor license agreement
2023-07-29 17:09:30 +09:00
softsimon
8172ec9245 Merge pull request #4053 from mempool/nymkappa/pool-logo
[mining] use .slug to load pool logo
2023-07-29 17:07:06 +09:00
softsimon
14c86b84b8 Merge pull request #4059 from mempool/mononaut/connection-state
fix websocket connection state observable
2023-07-29 17:05:17 +09:00
Czino
1f8f40011a Update date 2023-07-29 09:57:40 +02:00
Czino
2719be9075 Add contributor license agreement 2023-07-29 09:53:47 +02:00
Mononaut
354c119e99 fix websocket connection state observable 2023-07-29 15:22:15 +09:00
nymkappa
f8faccd502 Merge branch 'master' into mononaut/acceleration-viz 2023-07-29 13:51:49 +09:00
dni ⚡
cc27c0159e [BUG]: Update frontend entrypoint.sh
Typo of variable LIQUID_ENABLED
2023-07-28 23:04:44 +02:00
wiz
b1bdb52851 ops: Fix a classic typo in mempool clear protection log print 2023-07-28 23:40:06 +09:00
softsimon
d52e2cd585 Merge pull request #4054 from mempool/mononaut/mined-address-txs
Show new mined transactions on the address page
2023-07-28 20:43:22 +09:00
Mononaut
2c613195cc Add support for compressed p2pk addresses 2023-07-28 19:17:52 +09:00
wiz
1ca99e9967 Merge branch 'master' into hunicus/msop-r 2023-07-28 17:29:25 +09:00
softsimon
f9ddc3cc5f Merge pull request #4049 from mempool/mononaut/p2pk-websocket-subscription
Support p2pk track-address websocket subscriptions
2023-07-28 17:03:24 +09:00
Mononaut
63ccecf410 remove unused calcScriptHash function 2023-07-28 16:14:28 +09:00
Mononaut
5b2470955d track p2pk addresses by scriptpubkey not scripthash 2023-07-28 16:09:39 +09:00
Mononaut
74b87b6006 Support p2pk track-address websocket subscriptions 2023-07-28 16:09:39 +09:00
Mononaut
9b65fbd98c Show new mined transactions on the address page 2023-07-28 15:56:55 +09:00
nymkappa
3f3f0db2f2 [mining] use .slug to load pool logo 2023-07-28 13:45:04 +09:00
nymkappa
48e3be875d Merge branch 'master' into nymkappa/no-db-blocks-list 2023-07-28 09:37:55 +09:00
nymkappa
c993ee51cc Merge branch 'master' into nymkappa/charts-landscape-mobile 2023-07-28 09:37:45 +09:00
softsimon
395f47516a Merge pull request #4048 from mempool/mononaut/fix-key-event-leak
Fix key navigation subscription leak
2023-07-27 17:20:30 +09:00
Mononaut
589adb95c3 remove stray debugging log 2023-07-27 14:49:21 +09:00
Mononaut
1fd5b975f1 Handle failures while fetching block transactions 2023-07-27 11:45:16 +09:00
nymkappa
67cff804a6 /accelerations -> /accelerator/accelerations 2023-07-26 15:08:35 +09:00
Mononaut
cde4af5930 fix mismatched use of gbt implementations 2023-07-26 15:08:35 +09:00
Mononaut
928a8be846 fix pool-dependent accelerated audit handling 2023-07-26 15:08:34 +09:00
Mononaut
7c641544b2 check in missing rust-gbt file 2023-07-26 15:08:34 +09:00
Mononaut
2a2aee21fb fix audit highlightning and fee ranges 2023-07-26 15:08:34 +09:00
Mononaut
3838d947b1 fix tests 2023-07-26 15:08:34 +09:00
Mononaut
ffc2b6c53c Add acceleration support to rust gbt 2023-07-26 15:08:34 +09:00
Mononaut
6494f890fe include per-tx pools in /accelerations endpoint 2023-07-26 15:08:34 +09:00
Mononaut
ba54bc9d15 support for acceleration mempool blocks animation 2023-07-26 15:08:33 +09:00
Mononaut
083bfdba06 Refactor accelerated audits 2023-07-26 15:08:33 +09:00
Mononaut
20b3ceab1e Implement accelerations API & config setting 2023-07-26 15:08:33 +09:00
Mononaut
c246db1cf9 Refactor acceleration tracking 2023-07-26 15:08:33 +09:00
Mononaut
aa24f6a84d use accelerated rates for block templates & show in viz 2023-07-26 15:08:33 +09:00
Mononaut
e489f713eb include accelerated tx data in block audits 2023-07-26 15:08:26 +09:00
softsimon
7edd40246c Merge branch 'master' into nymkappa/charts-landscape-mobile 2023-07-25 21:37:35 +09:00
Mononaut
e15c0c6c7a Fix key navigation subscription leak 2023-07-25 21:18:19 +09:00
softsimon
a13c424869 Merge pull request #4046 from mempool/mononaut/audit-exclude-conflicts
Exclude all conflicting transactions from audit score
2023-07-25 20:22:37 +09:00
softsimon
8ee9f52634 Merge pull request #4028 from mempool/nymkappa/search-autofocus
[search bar] only autofocus when in `/`, `/mining` and `/lightning`
2023-07-25 18:19:17 +09:00
softsimon
b58abe4779 Merge pull request #4045 from mempool/mononaut/fast-blocks
Faster blocks
2023-07-25 16:07:52 +09:00
nymkappa
6d5be78dd0 [search bar] use afterviewinit instead of afterviewchecked 2023-07-25 15:03:39 +09:00
softsimon
07b0f24cf1 Update frontend/src/app/shared/pipes/bytes-pipe/utils.ts 2023-07-25 14:26:43 +09:00
Mononaut
d7b874ac49 Exclude all conflicting transactions from audit score 2023-07-25 14:17:02 +09:00
nymkappa
0a0978f7d7 Merge branch 'master' into nymkappa/search-autofocus 2023-07-25 13:31:15 +09:00
Mononaut
25925751eb refactor $getTransactionsExtended to optimise API requests 2023-07-25 12:09:13 +09:00
Mononaut
0ebfd6f017 Fetch block txs from mempool/electrs in bulk 2023-07-25 10:27:43 +09:00
wiz
81d1c0a4d5 Merge pull request #4043 from mempool/mononaut/mempool-sync-status
Mempool inSync status
2023-07-24 19:39:17 +09:00
Mononaut
36fe5627c7 fix mempool sync skeleton loaders on Core backend 2023-07-24 17:49:34 +09:00
nymkappa
9e43dadad8 Merge branch 'master' into nymkappa/search-autofocus 2023-07-24 17:28:47 +09:00
Mononaut
2d463326e0 fix gbt mempool size mismatch bug 2023-07-24 17:22:38 +09:00
Mononaut
a6edfcc272 show mempool skeleton while not inSync 2023-07-24 16:22:35 +09:00
Mononaut
de4265a6d1 More conservative mempool inSync status 2023-07-24 16:22:22 +09:00
softsimon
dc43a81899 Merge pull request #4035 from mempool/mononaut/lightning-balance-bars
Lightning channel balance progress bars
2023-07-24 16:22:20 +09:00
Mononaut
e59c961f25 Add electrs sync progress updates 2023-07-24 14:59:51 +09:00
Mononaut
db715a1dba Switch to batch mempool/txs/:txid endpoint 2023-07-24 14:44:43 +09:00
Mononaut
202d4122b4 load mempool txs in bulk from esplora 2023-07-24 14:44:42 +09:00
nymkappa
f62f2341f4 Merge branch 'master' into nymkappa/search-autofocus 2023-07-24 13:39:17 +09:00
softsimon
e2fdacfddd Merge pull request #4041 from mempool/simon/sanitize-lightning-channel-id
Sanitize channel id search
2023-07-24 13:26:20 +09:00
softsimon
c84a444f79 Merge pull request #4039 from mempool/mononaut/fix-sigops
Fix missing sigops
2023-07-24 13:26:13 +09:00
softsimon
ee2d8f8c5a Sanitize channel id search 2023-07-24 13:21:06 +09:00
nymkappa
7db391d762 [search bar] add missing autofocus on lightning dashboard 2023-07-24 11:51:15 +09:00
nymkappa
da4a20cb85 [search bar] dont auto focus if touch screen 2023-07-24 11:35:46 +09:00
Mononaut
44f2217a68 Fix typo which skips sigop calculation 2023-07-24 10:49:29 +09:00
nymkappa
6ce3c1d75d [search bar] auto focus only in dashboards 2023-07-24 10:18:00 +09:00
wiz
caa8cfbc0e Another hotfix for CLN crash 2023-07-23 22:35:32 +09:00
wiz
02f361af73 Hotfix for CLN crash 2023-07-23 22:21:53 +09:00
Mononaut
a1e05c0c37 Lightning channel balance progress bars 2023-07-23 18:00:24 +09:00
Mononaut
05affa5ad4 Fix difficulty tooltip position 2023-07-23 16:19:48 +09:00
softsimon
5e91af168b Merge pull request #4027 from mempool/mononaut/p2pk
Support P2PK address types
2023-07-23 15:06:04 +09:00
softsimon
ae183210e0 Updating pubkey width on mobile and desktop 2023-07-23 14:43:43 +09:00
Mononaut
56127dce6a Add P2PK support to search bar 2023-07-23 14:05:04 +09:00
Mononaut
0376467e6c highlight matching P2PK inputs 2023-07-23 14:01:31 +09:00
Mononaut
48b55eed46 improve script hex parsing validation 2023-07-23 14:01:31 +09:00
Mononaut
0ce043cca9 Fix esplora error messages 2023-07-23 14:01:31 +09:00
Mononaut
65dbafd2ec Support P2PK address types 2023-07-23 14:01:31 +09:00
nymkappa
597073c9b6 [block list] re-enable block fee if !auditAvailable in widget 2023-07-23 12:18:21 +09:00
nymkappa
d7ac326f92 [block list] improve block list when db = false 2023-07-23 12:02:04 +09:00
softsimon
3f36a30d1d Merge pull request #4031 from knorrium/es2022_fixes
Es2022 fixes
2023-07-23 11:56:04 +09:00
softsimon
b021746e9e Merge pull request #4030 from mempool/fix/CI-Rust
Use more reliable Github Action for Rust toolchain install
2023-07-23 11:50:00 +09:00
junderw
975ec772fa Use more reliable Github Action for Rust toolchain install. 2023-07-22 19:41:36 -07:00
Felipe Knorr Kuhn
442a4ff6e0 Fix tsconfig settigns for ES2022 2023-07-23 11:06:21 +09:00
Felipe Knorr Kuhn
cea218b81a Reset the supported browsers list 2023-07-23 11:05:49 +09:00
nymkappa
7970df27ad [graphs] fix min height in mobile landscape 2023-07-22 17:42:02 +09:00
softsimon
a24d2ce547 Merge pull request #4021 from mempool/mononaut/blockchain-scroll
apply blockchain scroll offset as soon as element is ready
2023-07-22 14:32:42 +09:00
softsimon
95707de8ec Merge pull request #4013 from mempool/simon/css-fix-fa-icons
Fix some icon css color changes
2023-07-22 13:53:55 +09:00
softsimon
eb37066d5d Merge pull request #4024 from devinbileck/patch-1
Accept CLA
2023-07-22 13:53:45 +09:00
Devin Bileck
f0983844c1 Accept CLA 2023-07-21 15:13:10 -07:00
softsimon
a0bd4e0f63 Merge branch 'master' into mononaut/blockchain-scroll 2023-07-21 21:12:11 +09:00
softsimon
141ab8076f Merge pull request #4014 from mempool/mononaut/fix-blocks-list
Fix blocks list observable
2023-07-21 21:12:03 +09:00
softsimon
267f3d4877 Merge pull request #4020 from knorrium/fix_rate_limiting
Fix rate limiting when syncing assets on CI
2023-07-21 21:11:41 +09:00
softsimon
460a41644d Merge pull request #4015 from pedromvpg/patch-1
sign contributor agreement
2023-07-21 21:04:31 +09:00
Felipe Knorr Kuhn
ca69d19bf7 Use the GITHUB_SECRET to authenticate with the API
Fix the environment variable

Add extra logging when using the authentication

Use the GITHUB_TOKEN on the frontend build step
2023-07-21 18:14:32 +09:00
Mononaut
d91fa5c6ef null => of([]) 2023-07-21 18:10:13 +09:00
wiz
3610aa2e20 Merge pull request #3999 from mempool/mononaut/fix-liquid-fees
Fix fee handling on Liquid
2023-07-21 17:49:48 +09:00
wiz
7a6da07a61 Merge branch 'master' into mononaut/fix-liquid-fees 2023-07-21 17:38:47 +09:00
Mononaut
0f77fb88bf handle missing block.extras on liquid 2023-07-21 17:18:45 +09:00
Mononaut
1bd19e1d8d apply blockchain scroll offset when element is ready 2023-07-21 17:10:58 +09:00
Felipe Knorr Kuhn
61eeb82694 Expose the GITHUB_SECRET to the frontend build step 2023-07-21 17:09:57 +09:00
softsimon
135adfecbd Merge pull request #3934 from mempool/junderw/fix-armv7-docker
Fix backend docker build for armv7
2023-07-21 10:19:20 +09:00
softsimon
20b2017908 Merge pull request #4016 from knorrium/tweak_dependabot
Tweak dependabot settings
2023-07-21 10:18:58 +09:00
Felipe Knorr Kuhn
b1345038bd Tweak dependabot settings 2023-07-20 18:09:36 -07:00
Felipe Knorr Kuhn
7ba627e243 Merge branch 'master' into junderw/fix-armv7-docker 2023-07-20 17:31:17 -07:00
Pedro
6b453ef018 sign contributor agreement 2023-07-20 17:24:13 +01:00
Mononaut
943dc6f5e6 Fix blocks list observable 2023-07-20 17:30:26 +09:00
softsimon
4192869593 Fix some icon css color changes 2023-07-20 16:02:04 +09:00
softsimon
e066bb1e9d Merge pull request #4002 from mempool/nymkappa/mining-pool-summary
[mining] add missing empty td at the bottom of pool ranking
2023-07-20 15:10:32 +09:00
softsimon
6cdc97848f Merge pull request #3773 from mempool/nymkappa/search-bar-align
[search bar] fix alignment issue
2023-07-20 14:59:54 +09:00
nymkappa
ade7908229 [mining] add missing empty col at the bottom of pool ranking 2023-07-20 10:36:26 +09:00
nymkappa
9a2ab7fe21 [search bar] chrome - fix flex-auto 2023-07-20 09:57:04 +09:00
softsimon
213800f563 Merge error fix 2023-07-19 16:46:02 +09:00
junderw
2c59992d3f Fix E2E error 2023-07-19 16:28:06 +09:00
Mononaut
87e39b8389 Fix liquid blockchain bar 2023-07-19 16:24:05 +09:00
junderw
d825143b35 Search for full address in separate network if matches 2023-07-19 16:15:43 +09:00
junderw
3d900a3849 Fix: Prevent regex clash with channel IDs 2023-07-19 16:10:25 +09:00
junderw
0a51b752e6 Improve types and add liquidtestnet for regex 2023-07-19 16:10:25 +09:00
junderw
c0d3f295ee Finished Regex portion 2023-07-19 16:10:24 +09:00
junderw
1339b98281 Feature: Readable RegExp constructor 2023-07-19 16:09:15 +09:00
softsimon
bc508b6621 Merge pull request #3949 from knorrium/node_v20_to_matrix
Add node v20 to the test matrix
2023-07-19 15:56:31 +09:00
Mononaut
709783280a Fix liquid fees & remove minimum fee rate 2023-07-19 15:42:02 +09:00
softsimon
09b7c4021a Merge branch 'master' into nymkappa/tx-overflow 2023-07-19 15:18:23 +09:00
softsimon
f9aa1b5b35 Merge pull request #3194 from mempool/hunicus/manual-deployment-enterprise
Specify manual deployment support for enterprise sponsors
2023-07-19 14:25:02 +09:00
softsimon
2fffd8b43c Merge branch 'master' into hunicus/manual-deployment-enterprise 2023-07-19 14:19:03 +09:00
softsimon
741571a93a Merge pull request #3607 from mempool/nymkappa/clip-label-overflow
Clip overflowing labels in pool component on mobile
2023-07-19 14:05:31 +09:00
softsimon
07a424e6f1 Merge pull request #3997 from mempool/mononaut/liquid-latest-blocks
restore latest blocks on liquid
2023-07-19 14:03:58 +09:00
Mononaut
943d05f680 restore latest blocks on liquid 2023-07-19 12:09:46 +09:00
softsimon
57aa2c69ac Merge branch 'master' into nymkappa/clip-label-overflow 2023-07-19 11:31:01 +09:00
softsimon
61e28a33e0 Merge pull request #3996 from mempool/simon/zero-zat-minimum-fee-fix
Fix for 0 sat minimum fee
2023-07-19 11:15:53 +09:00
softsimon
4055128d7f Fix for 0 sat minimum fee 2023-07-19 11:06:28 +09:00
Felipe Knorr Kuhn
7c29e51bbb Merge branch 'master' into junderw/fix-armv7-docker 2023-07-18 14:30:20 -07:00
softsimon
fabd420586 Merge branch 'master' into node_v20_to_matrix 2023-07-18 18:56:00 +09:00
softsimon
a12316f4dc Updating default mining pool icon 2023-07-18 18:16:21 +09:00
softsimon
548611f13a Merge branch 'master' into nymkappa/search-bar-align 2023-07-18 18:02:44 +09:00
softsimon
3397edecb4 Merge pull request #3659 from nothing0012/zz/add-cla
Add cla
2023-07-18 17:42:00 +09:00
softsimon
b041a145b1 Merge pull request #3654 from learntheropes/patch-1
sign cla
2023-07-18 17:41:49 +09:00
softsimon
7046c3d6c3 Merge pull request #3935 from mempool/mononaut/lightning-justice
Add lightning justice page
2023-07-18 17:24:26 +09:00
softsimon
67f58a4491 Sorting by closing date descending 2023-07-18 17:19:14 +09:00
softsimon
d74e4b1876 Replacing loading text with spinner 2023-07-18 17:15:54 +09:00
softsimon
e757b74c87 Merge pull request #3990 from mempool/simon/removing-unused-fullrbf-code
Removing unused rbf frontend code
2023-07-18 17:06:01 +09:00
wiz
4b41730636 Merge branch 'master' into mononaut/lightning-justice 2023-07-18 16:49:49 +09:00
wiz
23ecf9cf41 Merge pull request #3993 from mempool/simon/backend-deps-18-07
Bumping backend deps
2023-07-18 16:19:28 +09:00
wiz
f8cfa35552 Merge pull request #3965 from mempool/nymkappa/network-switch-align
[network selection] fix some align issues
2023-07-18 15:53:41 +09:00
wiz
c1d0e802d9 Merge branch 'master' into nymkappa/network-switch-align 2023-07-18 15:40:57 +09:00
softsimon
bde7fad1c4 Bumping backend deps 2023-07-18 15:36:30 +09:00
softsimon
8007f5a3d3 Merge pull request #3992 from mempool/simon/angular-16
Angular 16
2023-07-18 15:10:49 +09:00
softsimon
83f955e469 Merge pull request #3969 from mempool/mononaut/ancestors-undefined
Fix tx.ancestors undefined bug
2023-07-18 15:10:17 +09:00
nymkappa
29c53a7852 [search bar] fix alignment issue 2023-07-18 15:01:30 +09:00
softsimon
3825a1c359 Trying downgrading cypress wait 2023-07-18 13:45:24 +09:00
softsimon
ac82a25fa2 Angular 16 2023-07-18 13:38:33 +09:00
softsimon
85e071049c Removing unused rbf frontend code 2023-07-18 11:42:13 +09:00
softsimon
ae22b7b444 Merge pull request #3989 from mempool/mononaut/fullrbf-list-toggle
Remove frontend FULL_RBF_ENABLED flag
2023-07-18 11:36:46 +09:00
softsimon
9aba4d4357 Merge pull request #3988 from mempool/mononaut/clock-width-fix
Fix clock horizontal scroll bug
2023-07-18 11:03:11 +09:00
Mononaut
17866f80bd Remove frontend FULL_RBF_ENABLED flag 2023-07-18 11:01:35 +09:00
Mononaut
5e46176c4e Fix clock horizontal scroll bug 2023-07-18 10:52:47 +09:00
wiz
fa48c6f025 ops: Use NodeJS v18 to build, v20 to run backend 2023-07-18 08:52:51 +09:00
Felipe Knorr Kuhn
69c54d7207 Merge branch 'master' into node_v20_to_matrix 2023-07-17 15:53:34 -07:00
wiz
7e06c97f51 ops: Bump NodeJS to v20.4.0 2023-07-18 07:50:14 +09:00
wiz
c02eef352b ops: Increase bitcoin.conf maxconnections 42 -> 100 2023-07-17 22:56:16 +09:00
wiz
924782a4d1 Merge pull request #3867 from mempool/simon/enable-mempoolfullrbf
It's time (Enable fullrbf)
2023-07-17 21:48:46 +09:00
softsimon
5c6e3dfd5c Merge pull request #3983 from mempool/mononaut/hide-unknown-conf-badge
Hide confirmations badge if height unknown
2023-07-17 21:48:08 +09:00
softsimon
89dac1a77c Merge pull request #3979 from mempool/mononaut/new-block-race-condition
get chain tip direct from Bitcoin Core to avoid race conditions
2023-07-17 21:38:35 +09:00
Mononaut
6a16759e20 Hide confirmations badge if height unknown 2023-07-17 19:23:09 +09:00
softsimon
c355602924 Merge pull request #3981 from mempool/mononaut/fix-websocket-null-data
Fix websocket null data for undefined rbfSummary
2023-07-17 19:10:05 +09:00
softsimon
08ad81f4b5 Merge pull request #3982 from mempool/mononaut/faster-mempoll
Fix mempool update poll delay
2023-07-17 18:59:07 +09:00
Mononaut
2c1b9b9095 Fix mempool update poll delay 2023-07-17 18:21:44 +09:00
softsimon
965270dc7f Merge pull request #3933 from mempool/nymkappa/feature-bits
Show raw and decoded lightning node features
2023-07-17 17:58:22 +09:00
Mononaut
4309bfd519 Fix websocket null data for undefined rbfSummary 2023-07-17 17:53:26 +09:00
softsimon
6ab3b89884 Change to a Details-button 2023-07-17 17:41:38 +09:00
Mononaut
7a059ba294 get chain tip direct from Bitcoin Core to avoid race conditions 2023-07-17 15:21:52 +09:00
wiz
8af64900d9 Merge pull request #3959 from mempool/simon/load-more-mempool-txs
Load more mempool transactions
2023-07-17 14:56:18 +09:00
wiz
a59a7fe25e Merge branch 'master' into simon/load-more-mempool-txs 2023-07-17 14:17:52 +09:00
softsimon
2fc8e2997d Merge pull request #3978 from mempool/mononaut/fix-pool-blocks
unbork mining pool blocks list
2023-07-17 14:03:01 +09:00
wiz
ede961a34a Merge branch 'master' into simon/load-more-mempool-txs 2023-07-17 14:02:32 +09:00
softsimon
77764e1c77 Merge pull request #3882 from mempool/mononaut/audit-replication
Audit data synchronization
2023-07-17 12:51:34 +09:00
softsimon
8e114917a1 Merge pull request #3976 from mempool/mononaut/six-latest-transactions
always send 6 latest transactions to websocket clients
2023-07-17 12:03:06 +09:00
softsimon
be599ca624 Merge pull request #3971 from mempool/mononaut/audit-recently-cpfpd
Add "recently cpfpd" exception to audits
2023-07-17 11:51:06 +09:00
Mononaut
2c39e1e203 unbork mining pool blocks list 2023-07-17 11:15:55 +09:00
Mononaut
bf5a16b043 always send 6 latest transactions to websocket clients 2023-07-17 11:02:28 +09:00
wiz
a7ec9138c3 ops: Bump elements tag to 22.1.1 2023-07-17 01:14:52 +09:00
wiz
c0f33e6b52 Merge pull request #3974 from mempool/mononaut/missing-socket-init-data
Set missing websocket init data
2023-07-16 19:55:12 +09:00
Mononaut
565336df21 Set missing websocket init data 2023-07-16 18:39:51 +09:00
nymkappa
6fe32cdd19 [lightning] fix issue during initial node.features indexing 2023-07-16 18:24:42 +09:00
nymkappa
8fb67a914c [lightning] fix node features binary conversion 2023-07-16 18:17:49 +09:00
nymkappa
6336c529ed [lightning] show decoded features in node page 2023-07-16 18:17:49 +09:00
nymkappa
556eb65320 [lightning] start integrating features bits in the node page 2023-07-16 18:17:49 +09:00
nymkappa
4d41d36fe7 [lightning] save feature bit number when using lnd describegraph 2023-07-16 18:17:49 +09:00
nymkappa
32d46ad7ac [lightning] save bit number when converting features from clightning 2023-07-16 18:17:48 +09:00
nymkappa
1f003cc292 [lightning] save node features as stringified json array in db 2023-07-16 18:17:48 +09:00
wiz
2d4bc9dbd6 ops: Move electrs scripts to mempool/electrs repo 2023-07-16 17:50:36 +09:00
Mononaut
b33ea4679d Add "recently cpfpd" exception to audits 2023-07-16 13:51:30 +09:00
Mononaut
b6a6fcd4e2 Fix tx.ancestors undefined bug 2023-07-16 12:53:55 +09:00
softsimon
b03f2185ce Merge pull request #3964 from mempool/simon/calculator-validation-improvements
Calculator validation improvements
2023-07-15 20:15:31 +09:00
softsimon
a52d5faf4f Merge pull request #3967 from mempool/nymkappa/update-price-timestamp-websocket
[price updater] update latestPrices timestamp before pushing to websocket
2023-07-15 20:15:10 +09:00
softsimon
b39f01471a Select all input box text on click 2023-07-15 17:47:36 +09:00
nymkappa
73d9b4ef28 [price updater] update latestPrices timestamp before pushing to websocket 2023-07-15 17:29:29 +09:00
nymkappa
cda6567c4c [network selector] fix rtl issue 2023-07-15 16:50:18 +09:00
nymkappa
a372b479b4 [network selector] improve align 2023-07-15 16:26:25 +09:00
softsimon
992196c91f Calculator validation improvements 2023-07-15 15:09:41 +09:00
softsimon
9ffd4cc38d Calculator mobile margin 2023-07-15 12:18:55 +09:00
softsimon
0bcaa5209c Merge pull request #3875 from mempool/simon/calculator
Bitcoin-Fiat calculator tool
2023-07-15 11:24:17 +09:00
softsimon
23dffb4ca2 Slight margin fix 2023-07-15 11:18:36 +09:00
softsimon
98be07f5ef Removing logos 2023-07-15 10:52:59 +09:00
softsimon
120c27d120 Calculator visual results 2023-07-15 10:52:59 +09:00
softsimon
67a998c69f Working fiat/btc calculator 2023-07-15 10:52:33 +09:00
wiz
e3ddde9c90 Merge branch 'master' into simon/load-more-mempool-txs 2023-07-14 19:30:15 +09:00
wiz
0ec98d03e5 Merge pull request #3621 from mempool/mononaut/sharper-blocks
Pixel-aligned grids for sharper block visualizations
2023-07-14 18:58:09 +09:00
wiz
8680e5f06e Merge branch 'master' into mononaut/sharper-blocks 2023-07-14 18:45:55 +09:00
wiz
23151ec3db Bump version to 3.0.0-dev
- Now requires mempool/electrs
- Mempool Accelerator integration
- Rust GBT integration
- And more!
2023-07-14 18:39:35 +09:00
Mononaut
7f0218e343 add margin between mobile audit tabs & visualization 2023-07-14 18:39:28 +09:00
softsimon
f8fc0439f8 Merge pull request #3962 from mempool/mononaut/latest-replacements
Switch "Latest blocks" to "Latest replacements"
2023-07-14 18:30:25 +09:00
Mononaut
1abd2a23cc Add audit replication success logging 2023-07-14 16:54:36 +09:00
Mononaut
e59a9d38ff fix audit replication merge conflicts 2023-07-14 16:54:32 +09:00
Mononaut
bccc6b3680 Add missing replication docker config 2023-07-14 16:43:07 +09:00
Mononaut
7f6d17fc0e Fix audit sync progress logging 2023-07-14 16:43:07 +09:00
Mononaut
736b997104 Add missing audit data to cached blocks 2023-07-14 16:43:07 +09:00
Mononaut
69e6b164b9 Add audit data replication service 2023-07-14 16:43:05 +09:00
Mononaut
fa48791c59 reduce latest rbf websocket data 2023-07-14 16:15:03 +09:00
Mononaut
9a6565cd92 tweak default sizes & resolutions 2023-07-14 15:35:52 +09:00
Mononaut
3cca6f6b8b Pixel-aligned grids for sharper block visualizations 2023-07-14 15:33:28 +09:00
softsimon
f15f0570d4 Merge pull request #3951 from mempool/mononaut/tx-highlight
Highlight searched transactions in the block visualizations
2023-07-14 15:10:12 +09:00
Mononaut
240afbed95 adjust latest replacements labels & layout 2023-07-14 12:25:45 +09:00
softsimon
548ea0f4b4 Merge pull request #3912 from bennyhodl/bennyhodl-contributor-agreement
bennyhodl contributor agreement
2023-07-14 12:20:49 +09:00
Mononaut
756fac7270 Switch "latest blocks" to "latest replacements" 2023-07-14 11:52:07 +09:00
softsimon
ba6f41fa1b Merge pull request #3961 from mempool/mononaut/fix-difficulty-chart
Fix difficulty chart off-by-one bug
2023-07-14 11:31:01 +09:00
Mononaut
d60709deff Fix scene null check on visualization load 2023-07-14 11:22:09 +09:00
Mononaut
e9c618849d Highlight matching transactions in the block visualizations 2023-07-14 11:22:09 +09:00
Mononaut
8477600859 Fix difficulty chart bug 2023-07-14 11:05:09 +09:00
softsimon
15a8c8d420 Support for romanz/electrs 2023-07-13 17:59:02 +09:00
softsimon
5ef592f53e Load more mempool transactions 2023-07-13 16:57:36 +09:00
wiz
cff2022baf Merge pull request #3952 from mempool/simon/connectivity-ranking-title-fix
Connectivity ranking title fix
2023-07-13 15:58:26 +09:00
wiz
a6dc4fa38c Merge branch 'master' into simon/connectivity-ranking-title-fix 2023-07-13 15:44:31 +09:00
wiz
8b681f3ba0 Merge pull request #3670 from mempool/junderw/pushtxantidos
Push TX: Include validation to prevent DoS
2023-07-13 15:44:18 +09:00
softsimon
5575a37f9b Merge pull request #3957 from mempool/mononaut/full-rbf-highlight
highlight & tag fullrbf replacements in RBF timeline
2023-07-13 15:34:19 +09:00
wiz
15e58035e5 ops: Remove 2 electrs patches from prod installer 2023-07-13 15:06:00 +09:00
wiz
da4f7a3aba Merge branch 'master' into junderw/pushtxantidos 2023-07-13 14:18:19 +09:00
wiz
7542d95bc5 Merge pull request #3940 from mempool/mononaut/null-miner-health
Unknown avg miner health
2023-07-13 14:17:39 +09:00
wiz
6a2a9bda06 Merge branch 'master' into mononaut/full-rbf-highlight 2023-07-13 14:16:33 +09:00
junderw
222b34993b Fix: Add new configs to all config instances properly. 2023-07-13 14:06:46 +09:00
junderw
df70ea05c6 Fix: Leaf version validation 2023-07-13 13:50:54 +09:00
junderw
43d41fca95 Fix: Allow detection of 1 byte annexes 2023-07-13 13:31:57 +09:00
junderw
95a8752a0a Fix: Tests for config 2023-07-13 13:26:18 +09:00
junderw
21a47a7b4b Push TX: Include validation to prevent DoS 2023-07-13 13:24:46 +09:00
softsimon
31336d47e2 Merge pull request #3948 from mempool/mononaut/loading-transaction
show "loading" message while checking for cached txs
2023-07-13 12:32:20 +09:00
Mononaut
3287c62f91 highlight & tag fullrbf replacements in RBF timeline 2023-07-13 12:28:33 +09:00
softsimon
cf13c43637 Merge pull request #3937 from mempool/mononaut/replace-stale-blocks
Replace client-side stale blocks
2023-07-13 12:08:24 +09:00
Mononaut
eccbcbe53b Add missing this.block null check 2023-07-13 11:58:29 +09:00
softsimon
04bc43e188 Merge pull request #3943 from mempool/mononaut/missing-fiat-alignment
Add spacer for missing fiat values
2023-07-13 11:10:46 +09:00
Mononaut
1e69ea2f1d Fix merge conflicts 2023-07-13 11:06:02 +09:00
Mononaut
886a099a2f Detect stale blocks from client blockchain cache 2023-07-13 10:45:48 +09:00
Mononaut
7230b65dc3 remove console.log, fix null blocks 2023-07-13 10:45:46 +09:00
Mononaut
842ac8ce39 Add stale block banner immediately on reorg 2023-07-13 10:43:18 +09:00
Mononaut
e8c703fdbc replace client recent blocks on reorg 2023-07-13 10:43:18 +09:00
wiz
9cf961c667 Merge pull request #3693 from mempool/mononaut/preview-table-overflows
prevent table overflow in unfurl previews
2023-07-12 18:32:47 +09:00
wiz
93b1c64482 Merge branch 'master' into mononaut/preview-table-overflows 2023-07-12 18:17:06 +09:00
wiz
faf85d0c82 Merge pull request #3620 from mempool/mononaut/fix-rtl-unfurls
Fix RTL locale unfurls
2023-07-12 18:17:01 +09:00
wiz
d01fa85927 Merge branch 'master' into mononaut/fix-rtl-unfurls 2023-07-12 17:54:21 +09:00
softsimon
7ad1ace8dc Merge pull request #3941 from mempool/mononaut/reset-latest-txs
reset blocks$ and transactions$ observables when network changes
2023-07-12 17:52:06 +09:00
Mononaut
132923e7db Show skeleton loader instead of "Loading transaction..." 2023-07-12 17:44:38 +09:00
Mononaut
55cc3a0c07 fix loading transaction i18n tag 2023-07-12 17:44:37 +09:00
Mononaut
415b70da14 show "loading" message while checking for cached txs 2023-07-12 17:44:37 +09:00
wiz
243fd5e9dd Merge pull request #3953 from mempool/mononaut/difficulty-updates
always show latest difficulty on hashrate chart
2023-07-12 17:33:22 +09:00
wiz
7c1c8e877e Merge pull request #3955 from mempool/wiz/fix-prod-rust-gbt-build
Fix production rust GBT build
2023-07-12 17:25:03 +09:00
wiz
95e50ddf02 Fix production rust GBT build 2023-07-12 17:16:40 +09:00
softsimon
b6b9ab1a87 Merge pull request #3945 from mempool/mononaut/fix-mined-rbf-conflicts
Fix mined rbf conflict prevention
2023-07-12 17:06:53 +09:00
wiz
4144746e14 Merge branch 'master' into mononaut/difficulty-updates 2023-07-12 16:45:03 +09:00
wiz
f871300bfb Merge branch 'master' into mononaut/fix-mined-rbf-conflicts 2023-07-12 16:17:47 +09:00
wiz
2b559ffcce Merge pull request #3598 from mempool/nymkappa/scan-closed-channel-no-mempool
Make sure to scan closed channels even if config.MEMPOOL.ENABLE = false
2023-07-12 16:17:38 +09:00
softsimon
ef771beb28 Merge pull request #3669 from TechMiX/hotfix/rtlIssue
Fix RTL issues
2023-07-12 16:06:35 +09:00
wiz
09b966e507 Merge branch 'master' into nymkappa/scan-closed-channel-no-mempool 2023-07-12 16:00:52 +09:00
wiz
4b9d0d1d31 Merge pull request #3947 from mempool/mononaut/fix-testnet-price-updater
fix price updater loop on testnet/signet
2023-07-12 16:00:39 +09:00
wiz
3ece5acd59 Merge branch 'master' into mononaut/fix-testnet-price-updater 2023-07-12 15:38:17 +09:00
Mononaut
0dd9867a1f always show latest difficulty on hashrate chart 2023-07-12 12:58:48 +09:00
softsimon
ffca2f174d Connectivity ranking title fix 2023-07-12 12:24:45 +09:00
softsimon
00282b79b8 Merge pull request #3862 from secondl1ght/patch-1
update frontend local instructions
2023-07-12 11:02:58 +09:00
softsimon
e66f14a5c3 Merge pull request #3870 from pfoytik/master
the last two docker-compose overrides need MEMPOOL_ in front
2023-07-12 11:02:36 +09:00
softsimon
05f85c5201 Merge branch 'master' into nymkappa/clip-label-overflow 2023-07-12 10:57:11 +09:00
Felipe Knorr Kuhn
2570357bec Add node v20 to the test matrix 2023-07-11 00:21:00 -07:00
Mononaut
ca2830d6d8 fix price updater loop on testnet/signet 2023-07-11 16:03:44 +09:00
wiz
795e6753eb Merge pull request #3879 from mempool/mononaut/audit-exclude-fullrbf
exclude fullrbf txs from audit and label in visualization
2023-07-11 15:29:32 +09:00
wiz
ad0a007e8c Merge pull request #3946 from mempool/mononaut/bitcoin-core-v25
Upgrade bitcoin core to v25.0
2023-07-11 15:28:36 +09:00
softsimon
168cc9c1bf Merge pull request #3932 from mempool/mononaut/stale-blocks
Stale blocks
2023-07-11 14:47:44 +09:00
Mononaut
11d1a68f78 Upgrade bitcoin core to v25.0 2023-07-11 14:36:42 +09:00
Mononaut
a01336d8ac Fix mined rbf conflict prevention 2023-07-11 11:44:30 +09:00
Mononaut
01bd9dd957 Add spacer for missing fiat values 2023-07-11 11:18:17 +09:00
Mononaut
94c0222efe reset blocks$ and transactions$ observables when network changes 2023-07-11 10:50:25 +09:00
softsimon
ad9d9c839b Merge pull request #3869 from mempool/mononaut/vb-wu-preference
Weight unit preference
2023-07-11 10:10:43 +09:00
Mononaut
5b9d43032c Switch remaining vb fields according to unit preference 2023-07-11 10:04:38 +09:00
Mononaut
bde8fbac98 Implement only-vsize and only-weight directives 2023-07-11 10:00:41 +09:00
Mononaut
013ad803d0 Switch all direct sat/vb fields to new rate component 2023-07-11 10:00:41 +09:00
Mononaut
c29558db20 Add fee rate display component 2023-07-11 10:00:40 +09:00
Mononaut
a45f1fde1c Add fee rate unit preference & dropdown 2023-07-11 10:00:40 +09:00
Mononaut
e81839e7ed Return null for avg of zero matching health scores 2023-07-11 09:54:03 +09:00
Mononaut
6942a6fd6a Show alert banner on stale blocks 2023-07-10 16:14:02 +09:00
Mononaut
385cb087d3 Replace cached blocks on reorg, serve stale blocks 2023-07-10 16:14:02 +09:00
Mononaut
f1966768a7 exclude fullrbf txs from audit and label in visualization 2023-07-10 15:34:22 +09:00
Mononaut
4ba552fe1b Add basic lightning justice page 2023-07-09 03:03:35 -04:00
junderw
ec918d57b2 Fix backend docker build for armv7 2023-07-08 23:03:03 -07:00
wiz
408c86963b Merge pull request #3889 from mempool/mononaut/rust-gbt
Rust GBT
2023-07-09 13:27:52 +09:00
Jonathan Underwood
f8e910f0a4 Merge branch 'master' into mononaut/rust-gbt 2023-07-07 18:56:04 -07:00
softsimon
8ad4b952ea Merge pull request #3915 from mempool/mononaut/block-time-precision
More precise relative block times
2023-07-07 19:06:08 +02:00
junderw
925ebf08d4 Fix Docker build for using napi-rs 2023-07-06 18:05:21 -07:00
junderw
eae5f6078e Move N-API CLI to dependencies 2023-07-06 15:49:54 -07:00
Jonathan Underwood
464587cec5 Add period 2023-07-05 19:35:36 -07:00
junderw
0c7c1dd0a8 Merge remote-tracking branch 'origin/master' into mononaut/rust-gbt 2023-07-05 08:39:48 -07:00
junderw
22d357c53c Faster txid to u32 parsing 2023-07-05 08:39:01 -07:00
Mononaut
cc695dc910 match higher precision time in block page details 2023-07-05 11:02:32 -04:00
Mononaut
850752e0ea More precise relative block times 2023-07-05 10:50:46 -04:00
softsimon
7b01f54fc6 Merge pull request #3919 from joostjager/pool-fees
Add average fee delta to pool ranking
2023-07-05 15:30:15 +02:00
wiz
9f2e94d9cd Merge pull request #3863 from mempool/mononaut/scrollable-mempool
scroll to see all mempool blocks
2023-07-05 09:57:17 +09:00
wiz
824c6f97e4 ops: Use mempool/electrs for liquid instances 2023-07-05 09:33:33 +09:00
junderw
390c4a7706 Use ManuallyDrop 2023-07-04 17:19:41 -07:00
wiz
efcb58a4a6 Merge branch 'master' into mononaut/scrollable-mempool 2023-07-05 07:58:50 +09:00
Joost Jager
9e5d10b15f Add average fee delta to pool ranking
Co-authored-by: mononaut <83316221+mononaut@users.noreply.github.com>
2023-07-04 11:25:39 +00:00
Mononaut
8fdc44aa89 replace audit_pool hashmap with a vec 2023-07-03 22:16:35 -04:00
Mononaut
cfa2363743 only return rates changed since last update 2023-07-03 12:01:49 -04:00
Mononaut
897c667f17 return sigop-adjusted effective fee rates 2023-07-03 12:01:06 -04:00
Mononaut
078bc1d914 fix and consolidate tx ordering logic 2023-07-03 11:57:12 -04:00
mononaut
d16d961cb2 Apply suggestions from code review
avoid regex in partial txid ordering conversion

Co-authored-by: Jonathan Underwood <jonathan.underwood4649@gmail.com>
2023-07-03 11:55:43 -04:00
Mononaut
23d487b904 Mimic Core's ordering for equal-score transactions 2023-07-03 10:28:32 -04:00
Mononaut
af6de9b72c more misc JS-side gbt performance optimizations 2023-07-03 10:20:08 -04:00
junderw
0ddfa94b59 Ran cargo fmt 2023-07-03 10:18:22 -04:00
Mononaut
ccbed8ec58 Use min(feerate,ancestor_feerate) for ancestor score 2023-07-03 10:18:22 -04:00
junderw
552818607a Better initial capacity 2023-07-03 10:18:22 -04:00
Mononaut
db8c34ae61 misc JS-side gbt performance optimizations 2023-07-03 10:18:22 -04:00
Mononaut
0886e850f9 Pass gbt mempool data directly without serialization 2023-07-03 10:18:21 -04:00
Mononaut
5065fa42d0 calculate total block weights inside rust gbt 2023-07-03 10:18:21 -04:00
junderw
2838b068f7 Increased performance 2023-07-03 10:18:21 -04:00
junderw
77c83a6a13 Fix CI for Rust test 2023-07-03 10:18:21 -04:00
Mononaut
79a10ee833 vsize -> sigop_adjusted_vsize 2023-07-03 10:18:21 -04:00
Mononaut
10beb76585 conform to core's gbt quirks 2023-07-03 10:18:21 -04:00
Mononaut
71f150b587 Add end-to-end test of rust gbt against results from Core 2023-07-03 10:18:21 -04:00
junderw
6650541b2d Added Logging and refactored a bit 2023-07-03 10:18:20 -04:00
Mononaut
702c4c123e remove unnecessary option wrapper from gbt return value 2023-07-03 10:18:20 -04:00
Mononaut
1688b7d24e fix handling of used txs at top of mempool stack 2023-07-03 10:18:20 -04:00
Mononaut
75fd4ff5e1 swap mempool_array deque for a mempool_stack vec 2023-07-03 10:18:20 -04:00
Mononaut
ac8f88da38 protect ancestor data from outside assignments 2023-07-03 10:18:20 -04:00
Mononaut
7873f1c26a fix rust gbt cpfp cluster construction 2023-07-03 10:18:20 -04:00
Mononaut
a66c0c88ce fix rust gbt priority queue handling 2023-07-03 10:18:20 -04:00
Mononaut
f5e0662517 Fix mempool-blocks linter issues 2023-07-03 10:18:19 -04:00
junderw
4334b9eac1 Fix README and publish = false in Cargo.toml 2023-07-03 10:18:19 -04:00
junderw
6e7a525d12 Fix: napi macro breaks rust-analyzer
See issue: https://github.com/napi-rs/napi-rs/issues/944#issuecomment-1013002760
This will ignore expanding the napi macro for rust-analyzer, letting auto-complete
work inside the napi impl blocks.
2023-07-03 10:18:19 -04:00
Mononaut
4a15cd7abe clearer uint32 uid overflow check 2023-07-03 10:18:19 -04:00
junderw
5d48ae1eec Use U32HasherState for HashSet 2023-07-03 10:18:19 -04:00
Mononaut
a71f931d9f Add sanity checks for GBT cache de-sync 2023-07-03 10:18:19 -04:00
Mononaut
6829e67e15 Add sanity check for uint32 uid overflow 2023-07-03 10:18:19 -04:00
Mononaut
fc504012d5 Enforce Rust GBT instance lifecycle 2023-07-03 10:18:18 -04:00
Mononaut
8f675c7062 Add Rust GBT config flag 2023-07-03 10:18:18 -04:00
junderw
1ed0f86ed9 calc_new_score can be private 2023-07-03 10:18:18 -04:00
junderw
2dfef5a003 Fix Rust version of compiler to prevent breakage 2023-07-03 10:18:18 -04:00
junderw
609df31e0c Fix clippy pedantic and nursery lints as well 2023-07-03 10:18:18 -04:00
junderw
e61ae59e53 Add safety comments 2023-07-03 10:18:18 -04:00
junderw
e3f4c33f03 Protect score from outside assignment and document the requirements 2023-07-03 10:18:17 -04:00
junderw
af4919a98b Use u32hasher with PriorityQueue as well 2023-07-03 10:18:17 -04:00
junderw
939d2230d2 Use bytemuck instead of unsafe Rust 2023-07-03 10:18:17 -04:00
junderw
59b19eefe3 Move u32hasher into its own module, don't expose the Hasher for use. 2023-07-03 10:18:17 -04:00
junderw
3c652bdcbc Optimize audit_pool key hashing as well. Use a const for starting capacity for tx related lists. 2023-07-03 10:18:17 -04:00
junderw
ded2352cf8 Use a class to hold state for Rust GbtGenerator 2023-07-03 10:18:17 -04:00
junderw
8cfda1a546 Use tokio async/await instead of callbacks 2023-07-03 10:18:17 -04:00
junderw
5f161e73c7 Check callback status in thread 2023-07-03 10:18:16 -04:00
junderw
dfe24ed9d7 Remove all unwrap() calls 2023-07-03 10:18:16 -04:00
junderw
4661bea2f0 Use N-API ThreadsafeFunction 2023-07-03 10:18:16 -04:00
junderw
152d2c364b Update TS side 2023-07-03 10:18:16 -04:00
junderw
2d4963c2df Feature: Use napi-rs instead of neon 2023-07-03 10:18:16 -04:00
junderw
0f1f151d65 Remove empty function 2023-07-03 10:18:16 -04:00
junderw
d2a47b92c8 Move conversion logic to struct file 2023-07-03 10:18:16 -04:00
junderw
920232be4c Use Cargo workspace
Cargo workspace in the root will help make the IDE experience universal.
Cargo.lock and the target directory for build artifacts will be in the root
of the mempool repository (with ./target ignored by git).
2023-07-03 10:18:15 -04:00
junderw
83bf9229e7 Fix: Some of the clippy pedantic lints 2023-07-03 10:18:15 -04:00
mononaut
178bb960e9 Remove redundant gbt function
Co-authored-by: Jonathan Underwood <jonathan.underwood4649@gmail.com>
2023-07-03 10:18:15 -04:00
Mononaut
891acf30bf Fix vscode rust-analyzer config 2023-07-03 10:18:15 -04:00
Mononaut
0e00881826 Refactor rust code for style 2023-07-03 10:18:15 -04:00
Mononaut
1d51b01bd1 Implement rust gbt updateBlockTemplates 2023-07-03 10:18:15 -04:00
Mononaut
52bb8b4a4d Rust GBT proof of concept 2023-07-03 10:18:14 -04:00
softsimon
3d33233e51 Merge pull request #3891 from 0xFlicker/master
sign contributor agreement
2023-07-03 10:11:51 +02:00
softsimon
4cd7561af8 Merge pull request #3906 from mempool/simon/mempool-break-limit
Lowering mempool loop break limit
2023-07-03 10:08:17 +02:00
softsimon
52c813bcc7 Merge branch 'master' into simon/mempool-break-limit 2023-07-03 09:59:21 +02:00
softsimon
c20c7ae11f Merge pull request #3917 from mempool/mononaut/effective-rate-templates
Save effective rates to templates & summaries
2023-07-02 18:40:40 +02:00
softsimon
5f582195ad Merge branch 'master' into mononaut/effective-rate-templates 2023-07-02 18:11:28 +02:00
softsimon
a567a28c5c Update backend/src/api/mempool.ts
Co-authored-by: mononaut <83316221+mononaut@users.noreply.github.com>
2023-07-02 18:10:14 +02:00
softsimon
59713e2132 Update backend/src/api/mempool.ts
Co-authored-by: mononaut <83316221+mononaut@users.noreply.github.com>
2023-07-02 18:10:08 +02:00
softsimon
1e83a99bae Update backend/src/api/mempool.ts
Co-authored-by: mononaut <83316221+mononaut@users.noreply.github.com>
2023-07-02 18:10:02 +02:00
softsimon
b5fdb6d64f Merge pull request #3843 from mempool/mononaut/projected-fee-graph
Better projected fee graph
2023-07-02 17:44:12 +02:00
softsimon
1411b701f9 Merge pull request #3887 from mempool/mononaut/atomic-cpfp
Atomic CPFP database operations
2023-07-02 17:29:42 +02:00
softsimon
f80257c5ea Merge branch 'master' into mononaut/atomic-cpfp 2023-07-01 22:04:14 +02:00
softsimon
23cd063402 Merge pull request #3883 from mempool/hunicus/ronindojo-link
Update ronindojo link on about page
2023-07-01 22:03:43 +02:00
softsimon
2bda12e5f9 Merge pull request #3881 from mempool/mononaut/separate-audit-api
Separate summary and audit-summary API endpoints
2023-07-01 19:43:20 +02:00
softsimon
2e285c8d86 Merge pull request #3878 from mempool/mononaut/full-mempool-graph
Add 'all time' option for mempool graph
2023-07-01 17:23:03 +02:00
softsimon
70854de6ec Merge pull request #3855 from mempool/mononaut/websocket-responses
Fix inconsistent websocket responses
2023-07-01 17:19:22 +02:00
softsimon
f5cf5c7cc3 Merge pull request #3916 from mempool/mononaut/fix-transaction-eta
Fix transaction component ETA
2023-07-01 16:21:18 +02:00
nymkappa
d939391e62 ALL -> all (no caps needed, match the url parameters as well) 2023-06-30 19:52:06 -04:00
nymkappa
85e33e689d break graph toggles into another line earlier 2023-06-30 19:52:05 -04:00
Mononaut
ca1a1228a9 break graph toggles into two rows on small screens 2023-06-30 19:52:05 -04:00
Mononaut
d4ed238ae1 Add statistics/all to cache warmer, change query keyword 2023-06-30 19:52:05 -04:00
Mononaut
22baf4186e Add 'all time' option for mempool graph 2023-06-30 19:52:05 -04:00
Mononaut
58b8052530 don't reset blockchain position on every mempool update 2023-06-30 19:45:53 -04:00
Mononaut
9d606d0006 scroll selected mempool block into view 2023-06-30 19:45:53 -04:00
Mononaut
d848ab4bef scroll to see all mempool blocks 2023-06-30 19:45:53 -04:00
Mononaut
eaad63a082 frontend resync recent blocks when necessary 2023-06-30 19:43:04 -04:00
Mononaut
ca6ddd609d clean up backend websocket logic 2023-06-30 19:43:04 -04:00
Mononaut
eca40f94c9 use power-of-ten formatting for large fee rates 2023-06-30 19:41:12 -04:00
Mononaut
86f51e3902 fix fee graph for underfilled blocks 2023-06-30 19:27:31 -04:00
Mononaut
9f2b98b246 Handle stack-of-N-blocks in new fee graph 2023-06-30 19:27:31 -04:00
Mononaut
e4f3642082 Redesign mempool block fee distribution graph 2023-06-30 19:27:30 -04:00
Mononaut
48d62a1396 Save effective fee rates to block templates & summaries 2023-06-29 19:24:19 -04:00
Mononaut
d9ed02a033 Fix transaction component ETA 2023-06-29 11:39:13 -04:00
bennyhodl
f87bf4df77 bennyhodl contributor agreement 2023-06-28 18:40:57 -04:00
softsimon
31ae382f75 Lowering mempool loop break limit 2023-06-27 18:46:28 +02:00
hunicus
c89b15fdbc Update mosp strings from tm to r 2023-06-27 12:37:04 -04:00
softsimon
5f787db30d Merge pull request #3762 from knorrium/update_node_matrix
Update node CI test matrix
2023-06-26 18:08:53 +02:00
softsimon
da3c39c7d0 Merge pull request #3861 from mempool/hunicus/add-luminex-sponsor
Add luminex as enterprise sponsor
2023-06-26 12:31:03 +02:00
0xflick
dbf759fc76 sign contributor agreement 2023-06-24 16:30:29 -05:00
wiz
e88cf70719 Merge pull request #3886 from mempool/mononaut/hotfix-undefined-cpfp-cluster
Hotfix for undefined cpfp cluster bug
2023-06-23 19:08:27 +09:00
Mononaut
1f442b9ea6 Make cpfp db save operations atomic 2023-06-22 12:08:47 -04:00
Mononaut
9ff5ce0d37 Change order of cpfp db operations 2023-06-21 19:57:18 -04:00
Mononaut
329c635da5 Fix getCpfpInfo error handling 2023-06-21 19:57:09 -04:00
Mononaut
e18f3800be Hotfix for undefined cpfp cluster bug 2023-06-21 19:07:00 -04:00
hunicus
9bfc2c9413 Update ronindojo link on about page 2023-06-20 22:36:29 -04:00
Mononaut
4fbab08586 Separate summary and audit-summary API endpoints 2023-06-20 15:13:52 -04:00
Peter Foytik
32490bfdb7 Merge branch 'mempool:master' into master 2023-06-20 13:09:08 -04:00
Antoni Spaanderman
0d69ad43ab fix config issues 2023-06-18 20:34:56 +02:00
Antoni Spaanderman
dc491a5984 change default cookie path to /bitcoin/.cookie 2023-06-18 19:16:09 +02:00
Antoni Spaanderman
e9386ec003 Add Bitcoin Core RPC cookie authentication option 2023-06-18 19:16:07 +02:00
softsimon
e5efc2957a Merge pull request #3871 from mempool/mononaut/rbf-removed-not-mined
Change RBF status badges
2023-06-17 15:05:12 +02:00
softsimon
20d7e56de2 Update i18n 2023-06-17 15:04:46 +02:00
softsimon
0586e04d67 Merge pull request #3873 from mempool/simon/sanitize-pubkey-search
Sanitize node pubkey search
2023-06-17 11:22:28 +02:00
wiz
39bde61538 ops: Set cache time for /api/v1 endpoints to 2 sec 2023-06-16 17:15:41 -07:00
softsimon
0fb92e6ebb Merge pull request #3872 from mempool/simon/mempool-loop-timeout
Reinstate the mempool loop time limit
2023-06-17 00:56:00 +02:00
softsimon
c8d3653ef3 Updating tests 2023-06-17 00:32:58 +02:00
softsimon
a5575c0876 Sanitize node pubkey search 2023-06-16 23:42:57 +02:00
Mononaut
1872e5d12f change "removed" and "replaced" badges to yellow 2023-06-16 17:35:07 -04:00
softsimon
176f5e1377 Reinstate the mempool loop time limit 2023-06-16 20:42:31 +02:00
Mononaut
c0e235c01a Mark RBF transactions as removed if earlier version is mined 2023-06-16 13:47:09 -04:00
softsimon
2faeb1071e Merge pull request #3864 from mempool/mononaut/blocks-api-calls
remove redundant audit score api calls from blocks list
2023-06-16 19:37:48 +02:00
Peter
e8aea38320 contributer license 2023-06-15 21:46:09 -04:00
Peter
5f3fd85834 the last two docker-compose overrides need MEMPOOL_ in front 2023-06-15 21:39:51 -04:00
Mononaut
618ba56c42 remove redundant audit score api calls from blocks list 2023-06-15 12:57:20 -04:00
softsimon
d955dbff55 Merge pull request #3842 from mempool/mononaut/consistent-fee-ranges
Fix fee range inconsistencies
2023-06-15 16:49:07 +02:00
Mononaut
ee39283241 precompute block fee spans 2023-06-15 09:54:08 -04:00
wiz
c42670259e ops: Fix crash while building electrs in install script 2023-06-15 02:37:30 -07:00
secondl1ght
fe6da62dab create secondl1ght.txt contributor file 2023-06-14 21:55:17 -06:00
secondl1ght
22a491717a update frontend local instructions 2023-06-14 21:48:36 -06:00
hunicus
816f410855 Make luminex css class unique 2023-06-14 22:17:05 -04:00
Mononaut
bb61ff97fa continue to skip first rate in simple fee ranges 2023-06-14 19:04:09 -04:00
hunicus
73d629d319 Add luminex as enterprise sponsor on about page 2023-06-14 18:58:49 -04:00
softsimon
c630d705df Merge pull request #3839 from mempool/mononaut/clean-up-legacy-cpfp
Clean up legacy CPFP calculations
2023-06-14 23:14:07 +02:00
softsimon
c5bf167e36 Merge pull request #3846 from mempool/mononaut/audit-details
Add expected vs actual audit details comparison table
2023-06-14 23:05:07 +02:00
softsimon
e8420853e2 Merge pull request #3838 from mempool/mononaut/dependent-rate-indexing
calculate & index ancestor-dependent effective rates
2023-06-14 23:02:25 +02:00
softsimon
a8a5b733e5 Merge pull request #3860 from mempool/simon/disable-liquid-tests
Disabling Liquid tests for now
2023-06-14 22:28:08 +02:00
Mononaut
30f8d5cf96 add missing markForChecks in blocks list 2023-06-14 16:23:57 -04:00
softsimon
f09939a201 Disabling Liquid tests for now 2023-06-14 22:20:18 +02:00
softsimon
a99515e94a Merge pull request #3834 from mempool/mononaut/fix-double-mined-rbf
Fix multiple mined RBF replacements of the same tx
2023-06-14 22:15:53 +02:00
Mononaut
c4f7b99978 add backfilled audit stats to cached blocks 2023-06-14 16:15:33 -04:00
softsimon
dcf73ec3f3 Merge pull request #3831 from mempool/mononaut/clock
Interactive clock
2023-06-14 22:14:26 +02:00
softsimon
bbe0579cdd Changing default clock to mempool 2023-06-14 21:53:51 +02:00
softsimon
4390ffe3b6 Merge pull request #3820 from mempool/nymkappa/reindexing-pools-update
Mining pool update / re-indexer improvment
2023-06-14 19:16:08 +02:00
Mononaut
6b93e61b56 minor audit details fixes 2023-06-14 11:28:39 -04:00
softsimon
c79d031c86 Merge pull request #3668 from mempool/simon/ignore-existing-mining-pools
Skip existing mining pool logos when syncing assets
2023-06-13 11:15:02 +02:00
Felipe Knorr Kuhn
048399574e Merge branch 'master' into update_node_matrix 2023-06-12 22:42:21 -07:00
Mononaut
ae5a0312be change audit detail labels 2023-06-12 12:40:19 -04:00
softsimon
0b2ffb3e91 Merge branch 'master' into nymkappa/reindexing-pools-update 2023-06-12 15:53:46 +02:00
softsimon
d009edbbf3 Merge pull request #3822 from mempool/nymkappa/fix-possible-crash
fix possible backend crash
2023-06-12 15:52:47 +02:00
softsimon
1fbdf97639 Merge branch 'master' into nymkappa/fix-possible-crash 2023-06-12 15:45:02 +02:00
softsimon
a36303e1fb Merge branch 'master' into simon/ignore-existing-mining-pools 2023-06-12 14:29:40 +02:00
hunicus
ce950d63cb Replace disclaimer text regarding tx acceleration 2023-06-12 07:07:15 -04:00
softsimon
27a3a1575d Merge pull request #3849 from mempool/mononaut/icon-reset-scroll
Reset blockchain scroll on logo click
2023-06-11 18:43:44 +02:00
Mononaut
93d24d1cf7 Add expected fee % diff to blocks list page 2023-06-10 12:35:15 -04:00
Mononaut
bfb842d7ea Add % difference to weight and tx count in audit details 2023-06-10 12:35:13 -04:00
Mononaut
5b62966863 Add indexer task to backfill audit fee/weight stats 2023-06-10 12:34:16 -04:00
Mononaut
3013386ca5 Add expected weight to audit table 2023-06-10 12:32:53 -04:00
Mononaut
aedaf53137 Merge branch 'master' into merged-expected-block-fees 2023-06-10 12:15:29 -04:00
Joost Jager
7157efcf79 Add CLA for joostjager
Signed-off-by: Joost Jager <joost.jager@gmail.com>
2023-06-10 11:10:05 +02:00
Mononaut
57ac1486a0 Reset blockchain scroll on logo click 2023-06-09 19:03:47 -04:00
softsimon
9a99ee6486 Merge pull request #3772 from mempool/nymkappa/dont-rethrow-block-summaries
[audit] warn if we cannot save templates and remove exception re-throw
2023-06-07 18:31:59 +02:00
nymkappa
fd30bff9c6 don't throw when BlocksAuditRepositories.$saveAudit fails 2023-06-07 18:04:21 +02:00
Mononaut
3c022ad755 Fix fee range inconsistencies 2023-06-07 11:59:31 -04:00
Mononaut
ca9b48283d calculate & index ancestor-dependent effective rates 2023-06-06 18:23:06 -04:00
Mononaut
c8fc416c88 Remove legacy mined block cpfp loop, reset stale ancestors 2023-06-06 14:19:30 -04:00
softsimon
804640216f Merge pull request #3830 from mempool/fix/p2tr-annex-parse
Fix: Annex parsing for p2tr on bitcoind/romanz backends
2023-06-06 20:27:03 +04:00
softsimon
2191bf2a22 Merge pull request #3826 from mempool/mononaut/fix-firstseen
fix firstSeen reset migration bug
2023-06-06 20:18:35 +04:00
softsimon
7d92cdf015 Merge pull request #3811 from mempool/mononaut/fix-median-fee-bug
Fix missing fees in $updateBlocks without esplora
2023-06-06 19:35:45 +04:00
Mononaut
386037d1db Fix missing fees in $updateBlocks without esplora 2023-06-06 17:34:22 +02:00
softsimon
f2e216b9ac Merge pull request #3804 from mempool/mononaut/split-summaries-table
Break block templates into their own db table
2023-06-06 19:30:28 +04:00
Mononaut
35d80eec1c Fix multiple mined RBF replacements of the same tx 2023-06-06 11:01:01 -04:00
softsimon
eb8c38e4e8 Merge pull request #3832 from mempool/mononaut/fix-graph-filter-colors
fix graph filter dropdown colors
2023-06-06 17:53:56 +04:00
Joost Jager
74b2014dff Show expected fees in blocks list 2023-06-06 08:52:29 +02:00
Mononaut
689319437a fix graph filter dropdown colors 2023-06-05 14:23:37 -04:00
Mononaut
9883e59f12 fix graph page links layout 2023-06-05 14:09:02 -04:00
Mononaut
30396c5dca Add link to clock from graph page 2023-06-05 13:28:00 -04:00
Mononaut
ec0d5e0c23 Polish clocks, fix urls, make interactive 2023-06-05 13:27:17 -04:00
junderw
9e1de656c1 Fix: Annex parsing for p2tr on bitcoind/romanz backends 2023-06-05 07:21:55 -07:00
Joost Jager
3c0bb11208 Add expected total fees audit 2023-06-05 14:19:16 +02:00
Mononaut
37dd95a4a0 fix firstSeen reset bug 2023-06-04 12:47:04 -04:00
softsimon
6076eeed46 Merge pull request #3825 from mempool/mononaut/fix-negative-confs
Fix negative confirmations
2023-06-04 20:23:35 +04:00
Mononaut
8b1dff6d15 fix txConfirmed type 2023-06-04 11:47:46 -04:00
softsimon
9d4b58604b Optimize change detection 2023-06-04 10:32:24 +04:00
Mononaut
c49626aefc Confirmation badge component, fix negative confirmations 2023-06-03 16:20:32 -04:00
softsimon
baeb200e8b Merge pull request #3815 from mempool/hunicus/unmute-promo
Unmute about promo video on click
2023-06-03 15:35:31 +04:00
softsimon
11669849ab Merge pull request #3818 from mempool/mononaut/calculate-sigops
Count sigops and use adjusted vsizes
2023-06-01 09:49:54 +07:00
Mononaut
b171ed6dd0 Break block templates into their own db table 2023-05-31 13:43:48 -04:00
nymkappa
0b74cf1d89 fix possible backend crash x2, remove dead code, improve log 2023-05-31 09:58:29 -07:00
nymkappa
c558c85f36 fix possible backend crash 2023-05-31 09:48:44 -07:00
Mononaut
0ac76e12c4 Fix frontend logic for displaying effective fee rate 2023-05-31 12:11:56 -04:00
Mononaut
ee1ec414ed use fractional base vsize in adjusted vsize 2023-05-31 11:45:47 -04:00
Mononaut
0e5dc21854 Fix mined rbf / calculate sigop merge conflicts 2023-05-31 11:37:13 -04:00
Mononaut
bf7df08305 Enforce block sigop limits in GBT algorithm 2023-05-31 11:29:58 -04:00
Mononaut
ec63c822db Display sigops & adjusted vsize in transaction page details 2023-05-31 11:29:58 -04:00
Mononaut
09e4e44e88 Count sigops & use adjusted vsizes in mempool projections 2023-05-31 11:29:56 -04:00
Mononaut
c5e6821ad4 show fee rating badge either on rate or effective rate 2023-05-31 11:27:04 -04:00
Mononaut
70fa78b987 Fix effective fee rates for non-cpfp dependents 2023-05-31 11:27:04 -04:00
softsimon
8c78e35063 Use native angular way of accessing HTML elements 2023-05-31 14:39:19 +07:00
nymkappa
ea51ab8d0b [indexer] show github sha when successufly updated pools json 2023-05-30 10:42:41 -07:00
nymkappa
62169cee3f [indexer] oldest known mining pool block per network 2023-05-30 10:25:41 -07:00
nymkappa
e7e7b30807 fix log 2023-05-30 10:16:56 -07:00
nymkappa
107bdbc209 [indexer] show indexer progress in /status component 2023-05-30 10:13:07 -07:00
nymkappa
0b4615cbf0 [indexer] reindex diff adjustments and hashrates upon mining pool update 2023-05-30 10:05:10 -07:00
wiz
126a75ed45 ops: Use mempool/electrs fork of blockstream/electrs 2023-05-30 12:53:38 -03:00
softsimon
0703690190 Merge pull request #3785 from mempool/mononaut/mined-block-rbf
Detect RBF by mined transactions
2023-05-30 14:50:07 +07:00
wiz
7f56f0295b Merge pull request #3817 from mempool/ops/add-backend-reindex-macros
ops: Add npm run scripts for backend reindexing
2023-05-29 14:21:01 -03:00
wiz
27154da191 ops: Add npm run scripts for backend reindexing 2023-05-29 14:09:28 -03:00
hunicus
0fb61fded3 Add touch event for touchscreens 2023-05-27 13:20:55 -04:00
hunicus
ce00814bbf Unmute about promo video on click 2023-05-28 01:40:30 +09:00
wiz
c758a3538b Merge pull request #3806 from mempool/dependabot/npm_and_yarn/backend/bitcoinjs-lib-6.1.1 2023-05-27 12:16:29 -03:00
Felipe Knorr Kuhn
60fd2df4e6 Merge branch 'master' into dependabot/npm_and_yarn/backend/bitcoinjs-lib-6.1.1 2023-05-27 08:13:46 -07:00
wiz
05e38b43b9 Merge pull request #3809 from mempool/hunicus/tm-r
Switch tm to r for registered trademarks
2023-05-26 23:50:35 -03:00
hunicus
9fa1eebc02 Switch tm to r for registered trademarks 2023-05-27 06:46:18 +09:00
wiz
79ea1ee257 Merge pull request #3797 from mempool/hunicus/add-bullbit
Add bull bitcoin as enterprise sponsor
2023-05-26 11:34:40 -03:00
wiz
add405481e Merge pull request #3776 from knorrium/docker_vars_test
Docker vars tests
2023-05-26 11:33:48 -03:00
Felipe Knorr Kuhn
c382e03e4a Merge branch 'master' into docker_vars_test 2023-05-26 07:16:29 -07:00
dependabot[bot]
ac73de31b5 Bump bitcoinjs-lib from 6.1.0 to 6.1.1 in /backend
Bumps [bitcoinjs-lib](https://github.com/bitcoinjs/bitcoinjs-lib) from 6.1.0 to 6.1.1.
- [Changelog](https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/CHANGELOG.md)
- [Commits](https://github.com/bitcoinjs/bitcoinjs-lib/compare/v6.1.0...v6.1.1)

---
updated-dependencies:
- dependency-name: bitcoinjs-lib
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-26 02:56:38 +00:00
wiz
ccd403b771 Merge branch 'master' into hunicus/add-bullbit 2023-05-25 19:18:00 -03:00
wiz
f28c460bb4 Merge pull request #3796 from mempool/hunicus/fka-embassyos
Change embassyos to startos
2023-05-25 19:17:53 -03:00
hunicus
5711c939d7 Make svg pretty 2023-05-25 15:58:48 -04:00
wiz
ef3ce6d187 Merge pull request #3799 from Emzy/ops/nginx-json-match 2023-05-25 14:58:45 -03:00
wiz
410e604dce Merge pull request #3801 from mempool/nymkappa/reindexing
Always re-indexing blocks when updating mining pools
2023-05-25 13:10:10 -03:00
nymkappa
8ffe2f3156 Always re-indexing blocks when updating mining pools 2023-05-25 09:08:51 -07:00
wiz
d27febf878 Merge pull request #3800 from mempool/simon/dont-wipe-mempool-cache
Don't wipe mempool cache in pools updater
2023-05-25 12:37:51 -03:00
softsimon
038f9659bb Save new disk cache after ignoring blocks 2023-05-25 19:19:14 +04:00
softsimon
aeb896e200 Don't wipe mempool cache in pools updater 2023-05-25 19:07:51 +04:00
softsimon
349ba613dd Revert "Don't wipe mempool cache in pools updater"
This reverts commit 714208a366.
2023-05-25 19:06:45 +04:00
softsimon
714208a366 Don't wipe mempool cache in pools updater 2023-05-25 19:05:29 +04:00
Stephan Oeste
ad4c7d7c0b Fix exact match of .js files. Was also matching .json before. 2023-05-25 16:50:56 +02:00
hunicus
264c02eca1 Add bull bitcoin as enterprise sponsor 2023-05-25 01:29:55 -04:00
hunicus
ea42077320 Change embassyos to startos 2023-05-25 00:31:44 -04:00
Mononaut
125b9e4525 Restore liquid max block weight to defaults 2023-05-24 15:49:35 -04:00
softsimon
92ffb441a1 Merge pull request #3791 from mempool/simon/pool-detection-addresses-fix
Fix for pool output address matching
2023-05-24 19:49:41 +04:00
wiz
725526d733 Merge pull request #3637 from mempool/ops/installer-fix-cln-folder-creation
ops: Fix installer creation of CLN folders
2023-05-23 18:34:28 -03:00
softsimon
31ea2e1d4b Fix for pool output address matching
fixes #3782
2023-05-24 01:22:01 +04:00
wiz
c81509d762 ops: Start mysql-server using onestart from install 2023-05-23 17:57:27 -03:00
wiz
07f16165ff ops: Disable buggy CLN crontab job in install 2023-05-23 17:23:51 -03:00
softsimon
536f29eb0d Merge pull request #3783 from mempool/mononaut/high-sigop-audit
Omit possible high-sigop txs from block health score
2023-05-21 19:32:26 -04:00
softsimon
e88e56421b Enable fullrbf 2023-05-20 18:00:22 -04:00
Mononaut
369db7a63c Detect RBF by mined transactions 2023-05-18 09:51:41 -04:00
Mononaut
81ec54fcb3 Omit possible high-sigop txs from block health score 2023-05-17 11:46:50 -04:00
softsimon
64d6bda728 Merge pull request #3780 from mempool/mononaut/fix-graph-filter
Fix mempool graph fee filtering
2023-05-16 23:37:12 -04:00
Mononaut
7ab05d815d Fix mempool graph fee filtering 2023-05-16 16:25:38 -06:00
Felipe Knorr Kuhn
50a865e54e Merge branch 'master' into docker_vars_test 2023-05-15 13:09:46 -07:00
softsimon
2156fb2a83 Merge pull request #3406 from mempool/nymkappa/block-health-history-i18n
Rename block prediction to block health
2023-05-14 16:39:43 -05:00
Felipe Knorr Kuhn
4e1087801a Merge branch 'master' into docker_vars_test 2023-05-14 14:34:47 -07:00
nymkappa
4dec152df0 Blocks Health -> Block Health 2023-05-14 16:32:11 -05:00
nymkappa
720c2b8807 Block prediction -> Block health - Fix wrong chart download name 2023-05-14 16:32:11 -05:00
Felipe Knorr Kuhn
b00e0b6a73 Fix Docker config file to use the correct types 2023-05-14 14:26:38 -07:00
Felipe Knorr Kuhn
6333f3aa47 Update the backend config fixture 2023-05-14 14:25:23 -07:00
softsimon
7b127ebe8b Merge pull request #3653 from mempool/mononaut/fix-mempool-block-skeleton
Fix mempool block skeleton loaders
2023-05-14 16:20:24 -05:00
softsimon
585309f9f0 Merge branch 'master' into mononaut/fix-mempool-block-skeleton 2023-05-14 16:18:37 -05:00
Felipe Knorr Kuhn
184ca3c662 Add a test to check that the docker json is in sync with the template 2023-05-14 14:17:53 -07:00
softsimon
bfea535df1 Merge pull request #3716 from mempool/mononaut/skeleton-fee
display fee box skeleton while mempool not in sync
2023-05-14 16:16:02 -05:00
softsimon
65189d6f3e Merge branch 'master' into mononaut/skeleton-fee 2023-05-14 16:10:39 -05:00
Felipe Knorr Kuhn
de434bb398 Add missing Lightning config 2023-05-14 13:26:35 -07:00
Felipe Knorr Kuhn
804485a526 Add missing DATABASE_TIMEOUT config 2023-05-14 13:20:18 -07:00
Felipe Knorr Kuhn
3f8fefcb0e Add a test to check if all the vars are on the Docker script 2023-05-14 13:14:44 -07:00
Felipe Knorr Kuhn
178da3df26 Use the same delimiter for all substitutions 2023-05-14 13:13:37 -07:00
softsimon
aa9fd845ef Path fix 2023-05-14 14:21:41 -05:00
softsimon
e41ce16bbb Merge branch 'master' into simon/ignore-existing-mining-pools 2023-05-14 13:19:22 -05:00
softsimon
f12403747d Adding video to sha1 check and chaining requests in promises. 2023-05-14 12:45:42 -05:00
Felipe Knorr Kuhn
68e9fb0882 Merge branch 'master' into update_node_matrix 2023-05-13 14:27:45 -07:00
softsimon
da3c3e8f5c Re-use variable fix 2023-05-13 13:24:44 -05:00
softsimon
a447887901 Adding missing slash 2023-05-13 13:23:27 -05:00
softsimon
02b5fadf44 Merge pull request #3774 from mempool/mononaut/fix-clock-fee
Remove clock fee debugging adjustment
2023-05-13 12:16:32 -05:00
Mononaut
ea52d40a10 Remove clock fee debugging adjustment 2023-05-13 09:33:15 -06:00
softsimon
cbd4ea1aa8 Merge pull request #3771 from mempool/mononaut/clock-mempool-subscription
Add missing clock websocket subscriptions
2023-05-13 08:35:05 -05:00
nymkappa
f95c16a78e [audit] warn if we cannot save templates and remove exception re-throw 2023-05-13 15:28:29 +02:00
softsimon
fa1cf7abb9 Merge pull request #3768 from mempool/hunicus/tm-symbol
Add trademark symbol to trademarks in footer
2023-05-13 08:04:55 -05:00
Mononaut
6a5afd7f95 Add missing clock websocket subscriptions 2023-05-12 21:08:12 -06:00
softsimon
d3bd434255 Use sha hashes to compare before downloading 2023-05-12 16:01:45 -05:00
hunicus
0ddd9b2487 Turn generic project text into trademark 2023-05-12 15:54:35 -04:00
hunicus
ee1e75f978 Add trademark symbol to trademarks in footer 2023-05-12 12:55:51 -04:00
wiz
6e83bee23f ops: Disable mempool loop for lightning backends 2023-05-12 11:38:28 -05:00
softsimon
49e057e726 Fixing trailing slash issue 2023-05-12 11:05:20 -05:00
softsimon
7f3e4eb534 Skip existing mining pool logos when syncing assets 2023-05-12 11:05:19 -05:00
softsimon
97c8ace8f7 Merge pull request #3749 from mempool/nymkappa/fix-3747
[mempool graph] show horizontal guide line
2023-05-12 10:54:05 -05:00
softsimon
a3ca79e995 Temporarily hide sign in 2023-05-12 10:53:42 -05:00
softsimon
50a96ce340 Merge branch 'master' into update_node_matrix 2023-05-12 10:37:23 -05:00
softsimon
962c9543d0 Merge pull request #3752 from mempool/simon/global-footer-fixes
Global footer fixes
2023-05-12 10:35:01 -05:00
softsimon
52bcef54be Only show sign in on mempool base module 2023-05-12 10:34:32 -05:00
softsimon
22030027b4 Merge pull request #3755 from mempool/mononaut/better-precise-durations
smarter time duration unit selection
2023-05-12 10:31:16 -05:00
hunicus
53a9093a70 Center left footer panel vertically 2023-05-12 11:29:17 -04:00
softsimon
6ef793f202 Merge pull request #3760 from knorrium/fix_rbf_test
Update mocks and fix RBF tests
2023-05-12 10:29:07 -05:00
softsimon
b227ff8e1b Update websocket RBF fixture 2023-05-12 10:14:21 -05:00
Felipe Knorr Kuhn
38162e1af2 Merge branch 'master' into update_node_matrix 2023-05-12 07:44:07 -07:00
Felipe Knorr Kuhn
db6b9ffa6e Merge branch 'master' into fix_rbf_test 2023-05-12 07:43:54 -07:00
softsimon
5a0c809fa7 Fix linting 2023-05-12 09:37:19 -05:00
softsimon
f6caed3ffd Hide sign in on non official 2023-05-12 09:31:12 -05:00
softsimon
6141516eb2 Merge pull request #3753 from mempool/mononaut/fix-difficulty-estimate
Fix difficulty estimate
2023-05-12 09:21:06 -05:00
Felipe Knorr Kuhn
b0478f6604 Remove node 19 and 20 due to Angular incompatibility 2023-05-11 22:15:29 -07:00
Felipe Knorr Kuhn
6cae3256a9 Update node CI test matrix 2023-05-11 21:42:19 -07:00
Felipe Knorr Kuhn
3b295b5482 Update mocks and fix RBF tests 2023-05-11 21:33:47 -07:00
softsimon
adc395fc3d Merge pull request #3743 from mempool/mononaut/full-stack-fee-stats
stack-of-n-blocks fee statistics
2023-05-11 19:48:02 -05:00
hunicus
0c52898010 Add spacing to compensate for links under button 2023-05-11 20:43:57 -04:00
hunicus
4fe6a74d20 Vary network urls according to base module 2023-05-11 20:37:11 -04:00
softsimon
7fca18d7be Merge pull request #3751 from mempool/mononaut/fix-rbf-times
Fix RBF timestamps to always use seconds
2023-05-11 19:35:29 -05:00
hunicus
208756bdd2 Show explorer links conditionally 2023-05-11 19:31:22 -04:00
hunicus
82a072bd87 Remove footer from bisq docs 2023-05-11 19:04:24 -04:00
softsimon
6d76d11837 Merge pull request #3742 from vostrnad/empty-witness-items
Display empty witness items
2023-05-11 17:51:44 -05:00
hunicus
982f1e007a Fix bisq quirks 2023-05-11 18:48:53 -04:00
hunicus
a4bf545993 Fix footer on bisq 2023-05-11 18:44:42 -04:00
softsimon
fe51f6a504 Merge pull request #3745 from mempool/mononaut/address-false-positive
Fix txids interpreted as addresses in search bar
2023-05-11 17:34:19 -05:00
softsimon
f5d311ca44 Fixes for Liquid 2023-05-11 17:14:16 -05:00
hunicus
b81dd99825 Remove social icons and version from about page 2023-05-11 17:57:04 -04:00
hunicus
f08457aba7 Improve responsiveness and add social icons 2023-05-11 17:46:38 -04:00
Mononaut
c601e5dcb4 smarter time duration unit selection 2023-05-11 13:33:38 -06:00
hunicus
11b82b3459 Remove third column on footer 2023-05-11 15:31:48 -04:00
Mononaut
d322665789 update difficulty tests 2023-05-11 11:39:18 -06:00
Mononaut
49529627f8 Fix difficulty adjustment calculation 2023-05-11 11:18:58 -06:00
softsimon
107746feec Global footer fixes 2023-05-11 11:38:57 -05:00
wiz
cb9d09a930 Merge branch 'master' into nymkappa/scan-closed-channel-no-mempool 2023-05-11 11:04:19 -05:00
Mononaut
e5bef55d47 Fix RBF timestamps to always use seconds 2023-05-11 09:21:48 -06:00
wiz
17dd02ed4e Merge pull request #3736 from mempool/mononaut/optimize-websocket-updates
Optimize websocket updates
2023-05-11 09:57:08 -05:00
nymkappa
7bb34fe090 [mempool graph] show horizontal guide line 2023-05-11 14:30:57 +02:00
Mononaut
abbaee0274 Fix txids interpreted as addresses in search 2023-05-10 19:57:58 -06:00
Mononaut
3d1cd3193a online calculation of stack-of-n-blocks fee statistics 2023-05-10 17:34:20 -06:00
Vojtěch Strnad
be53cd8b48 Display empty witness items 2023-05-11 00:11:23 +02:00
Vojtěch Strnad
4b20ea7232 Accept the CLA for @vostrnad 2023-05-11 00:10:57 +02:00
Mononaut
ffd7831efc optimize websocket init data 2023-05-10 08:05:39 -06:00
Mononaut
f8636d20c2 optimize batch client websocket updates 2023-05-10 08:05:39 -06:00
wiz
3b4dd7e633 Merge pull request #3724 from mempool/hunicus/big-footer
Add big footer
2023-05-09 13:45:43 -05:00
wiz
ea101e65bb Merge branch 'master' into hunicus/big-footer 2023-05-09 13:31:58 -05:00
wiz
8a713c3880 Merge pull request #3732 from mempool/mononaut/more-fee-bands
Increase displayed fee bands
2023-05-09 13:31:50 -05:00
wiz
42d5650bc0 Merge branch 'master' into mononaut/more-fee-bands 2023-05-09 13:20:04 -05:00
wiz
ee2bc2282a Merge pull request #3731 from mempool/mononaut/clocktower
Mempool clocks
2023-05-09 12:51:01 -05:00
wiz
34565dc675 Merge branch 'master' into mononaut/clocktower 2023-05-09 12:36:58 -05:00
wiz
6e57de3220 Merge pull request #3735 from mempool/mononaut/optimize-gbt-main-thread
Optimize main thread processing of GBT updates
2023-05-10 00:13:32 +09:00
Mononaut
033e78c0a7 Optimize main thread processing of GBT updates 2023-05-08 23:01:17 -06:00
Mononaut
5257716e1a Dynamic fee ranges & legend in mempool graph 2023-05-08 12:53:37 -06:00
Mononaut
47b95af8ae increase range of fee colors 2023-05-08 12:44:14 -06:00
Mononaut
f20bfb025b fix clock merge conflicts 2023-05-08 09:11:30 -06:00
Mononaut
9671259f5c clock selected block arrow 2023-05-08 08:48:56 -06:00
Mononaut
07dddd857b resize clock labels 2023-05-08 08:48:56 -06:00
Mononaut
19353fc1d0 rename clock components 2023-05-08 08:48:56 -06:00
Mononaut
1fccd70379 clock size query params 2023-05-08 08:48:55 -06:00
Mononaut
fdb0cf509d query param toggle for clock stats 2023-05-08 08:48:55 -06:00
Mononaut
056d61a28d clock i18n 2023-05-08 08:48:55 -06:00
Mononaut
d3a7950e78 Add clock statistics 2023-05-08 08:48:55 -06:00
Mononaut
3ddd51d4cb implement clock face & dial 2023-05-08 08:48:55 -06:00
Mononaut
f879a34021 responsive clock, fix blockchain 2023-05-08 08:48:55 -06:00
Mononaut
61531171c9 clocktower top blocks & layout adjustment 2023-05-08 08:48:53 -06:00
Mononaut
3b459b6857 hourly blocks clock faces 2023-05-08 08:46:18 -06:00
softsimon
be5882edb3 Merge pull request #3710 from mempool/mononaut/optimize-gbt-data
Mononaut/optimize gbt data
2023-05-07 23:55:27 +04:00
Mononaut
428d4fc6ab optimize data structures for advanced GBT algorithm 2023-05-07 11:54:23 -06:00
softsimon
07d9315bbe Merge pull request #3727 from mempool/simon/rapid-mempool-sync
Rapid mempool sync
2023-05-07 20:22:10 +04:00
softsimon
ee05a6852e Rapid mempool sync 2023-05-07 20:21:02 +04:00
softsimon
64b3e7ad50 Merge pull request #3655 from mempool/mononaut/mempool-delete-race-condition
Fix new block mempool eviction race condition
2023-05-07 20:18:36 +04:00
hunicus
822934828a Add initial content to big footer 2023-05-06 04:10:17 -04:00
softsimon
8866923efa Merge pull request #3721 from mempool/mononaut/fix-first-seen
Restore transaction first seen field
2023-05-06 03:05:35 +04:00
Mononaut
06ef114395 Restore transaction first seen field 2023-05-05 15:12:05 -07:00
softsimon
918a3ef115 Merge pull request #3677 from mempool/mononaut/duration-precision
More precise durations in difficulty components
2023-05-06 01:58:16 +04:00
softsimon
5e9e570b99 Merge branch 'master' into mononaut/duration-precision 2023-05-06 01:39:50 +04:00
softsimon
3e6c672a1e Merge pull request #3676 from mempool/mononaut/better-durations
Improve unit selection for duration formatting
2023-05-06 01:39:37 +04:00
Mononaut
387a38a1c8 Increase precision of some formatted durations 2023-05-05 14:35:57 -07:00
Mononaut
78e86c7c55 Improve unit selection for duration formatting 2023-05-05 14:30:03 -07:00
softsimon
de1e6d3b27 Merge pull request #3672 from mempool/hunicus/unchained-icon
Update unchained icon on about page
2023-05-06 01:18:53 +04:00
softsimon
9c9837d722 Merge pull request #3720 from mempool/simon/fix-global-footer-graph-pages
Fix height on graphs pages with footer
2023-05-06 00:55:56 +04:00
softsimon
494ceca44e Correcting graph widget bottom padding 2023-05-06 00:55:25 +04:00
softsimon
cb324733bf Removing weird bottom padding 2023-05-06 00:31:08 +04:00
softsimon
ad6d817f32 Adding bottom margin on some graph list pages 2023-05-06 00:20:56 +04:00
softsimon
e5ae2f6ef6 Fixing header margin and Lightning charts 2023-05-06 00:08:26 +04:00
softsimon
3425f2e390 Fix height on graphs pages with footer 2023-05-05 23:38:35 +04:00
Mononaut
3d0f7d6855 add missing rbf eviction 2023-05-05 10:20:17 -07:00
Mononaut
d322c6b5b5 Fix new block mempool deletion race condition 2023-05-05 10:19:11 -07:00
softsimon
a7dff0effe Merge pull request #3719 from mempool/mononaut/fix-rbf-cache-eviction
fix rbf cache eviction logic
2023-05-05 14:27:56 +04:00
Mononaut
f456912679 fix rbf cache eviction logic 2023-05-04 23:30:11 -04:00
softsimon
0d204426e6 Merge pull request #3564 from mempool/simon/global-footer
Global footer
2023-05-05 02:14:36 +04:00
softsimon
4c5ece8249 Fixing navbar overflowing footer 2023-05-05 02:06:48 +04:00
softsimon
e7ae9049bb Enabling footer on about page 2023-05-05 01:49:11 +04:00
softsimon
d40344aa92 Global footer component that fixes Liquid 2023-05-05 01:38:58 +04:00
softsimon
e3e273a688 Fixing position on mobile view 2023-05-05 00:53:21 +04:00
softsimon
e9a0be4941 Remove logger
Co-authored-by: Bufo <32884105+bufo24@users.noreply.github.com>
2023-05-05 00:53:21 +04:00
softsimon
9ca9ab63f5 Bottom padding for mobile 2023-05-05 00:53:20 +04:00
softsimon
261241fcc8 Global footer 2023-05-05 00:53:20 +04:00
softsimon
3c108a271d Merge pull request #3703 from mempool/mononaut/delayed-disk-cache
delay writing disk cache until block handler completes
2023-05-04 18:15:11 +04:00
Mononaut
e5f97ace8b delay writing disk cache until block handler completes 2023-05-03 15:53:47 -06:00
softsimon
e807b3ca74 Merge pull request #3705 from mempool/mononaut/increase-websocket-timeout
Increase client websocket timeout
2023-05-04 01:35:16 +04:00
softsimon
90154aec83 Merge pull request #3380 from mempool/mononaut/mempool-effective-rates
Use effective fee rates in mempool block visualizations & tooltips
2023-05-04 01:19:40 +04:00
Mononaut
d7333ec858 display fee box skeleton while mempool not in sync 2023-05-03 15:01:07 -06:00
softsimon
e6e90799ef Merge branch 'master' into mononaut/mempool-effective-rates 2023-05-04 00:58:49 +04:00
softsimon
8fd9c1a292 Merge pull request #3673 from mempool/mononaut/stable-mempool-positions
Improve stability of the mempool transaction marker arrow
2023-05-04 00:55:35 +04:00
Mononaut
489470639a remove mempool marker on tx confirmation 2023-05-03 14:18:07 -06:00
Mononaut
b79377d5a1 Use new mempool position data for transaction ETA 2023-05-03 14:18:07 -06:00
Mononaut
a22703d547 Add mempool position improvements to updateMempoolBlocks 2023-05-03 14:18:07 -06:00
Mononaut
3b8bcc4da5 Improve stability of mempool tx position arrow 2023-05-03 14:18:06 -06:00
softsimon
a5b764fb66 Merge pull request #3714 from mempool/mononaut/fix-tx-eta
Fix transaction ETA calculation
2023-05-04 00:17:09 +04:00
Mononaut
9bd968f6c3 fix tx page mempool blocks subscription leak 2023-05-03 13:58:08 -06:00
Mononaut
e3f1fced99 keep ETA relative time basis updated 2023-05-03 13:55:26 -06:00
softsimon
12ae940ed6 Merge pull request #2847 from mempool/mononaut/rbf-timeline
RBF Timelines
2023-05-03 23:48:57 +04:00
Mononaut
b325f8c524 Fix import path 2023-05-03 13:16:27 -06:00
Mononaut
ca7c8906a5 Fix missing null checks in tx component 2023-05-03 13:00:23 -06:00
Mononaut
a3b0c56182 Improve RBF diagram state visibility 2023-05-03 13:00:23 -06:00
Mononaut
f29a56f3fe Don't show RBF replaced alert banner after confirmation 2023-05-03 13:00:23 -06:00
Mononaut
36c7697c2b Update rbf disk caching for new method 2023-05-03 13:00:23 -06:00
Mononaut
3355419761 fix missing FULL_RBF_ENABLED config entries 2023-05-03 13:00:22 -06:00
Mononaut
3cb96b32a6 fix rbf e2e test 2023-05-03 13:00:22 -06:00
Mononaut
8d57aa1f06 scroll selected rbf node into view 2023-05-03 13:00:22 -06:00
Mononaut
f2749c67f3 change rbf subheading, fix interval alignment 2023-05-03 13:00:22 -06:00
Mononaut
f95da34fd1 change rbf tooltip to standard two-column table design 2023-05-03 13:00:22 -06:00
Mononaut
7e9cfa0858 Persist RBF cache to disk 2023-05-03 13:00:20 -06:00
Mononaut
6fb4adc27d fixes for non-dual-node rbf feature 2023-05-03 12:53:56 -06:00
Mononaut
723212c918 add mouseover tooltips to rbf timelines 2023-05-03 12:53:56 -06:00
Mononaut
086b41d958 support trees of RBF replacements 2023-05-03 12:53:56 -06:00
Mononaut
c064ef6ace remove 'replaces' alert on transaction page 2023-05-03 12:53:56 -06:00
Mononaut
f46296a2bb new page listing recent RBF events 2023-05-03 12:53:53 -06:00
Mononaut
7b2a1cfd10 update RBF timeline over websocket 2023-05-03 12:52:21 -06:00
Mononaut
1b843da785 Timeline of replacements for RBF-d transactions 2023-05-03 12:52:20 -06:00
softsimon
8db7326a5a Merge pull request #3709 from mempool/mononaut/optimize-new-block-gbt
skip unnecessary makeBlockTemplates call
2023-05-03 21:56:07 +04:00
Mononaut
3f49944c05 Fix transaction ETA calculation 2023-05-03 10:02:03 -06:00
softsimon
2f0d4d6068 Merge pull request #3712 from mempool/revert-3694-simon/revert-tcp-socket-fallback
Revert "Revert TCP socket fallback"
2023-05-03 10:12:59 +04:00
softsimon
dd68572603 Revert "Revert TCP socket fallback" 2023-05-03 10:11:44 +04:00
Mononaut
03ee5c7c31 skip unnecessary makeBlockTemplates 2023-05-02 18:47:34 -06:00
softsimon
4d5662fee4 Merge pull request #3708 from mempool/simon/change-forensics-logging-to-debug
Change forensic logging to debug
2023-05-02 18:08:26 +04:00
softsimon
565aa9616b Change forensic logging to debug 2023-05-02 17:39:02 +04:00
softsimon
62ef1768ec Merge pull request #3707 from mempool/simon/audit-optimization-dead-code
Removing dead code causing slowdown
2023-05-02 16:37:54 +04:00
softsimon
c659adb4be Removing dead code causing slowdown 2023-05-02 15:40:16 +04:00
Mononaut
3691ba8242 Increase client websocket timeout 2023-05-01 18:13:53 -06:00
softsimon
32c39f7af9 Merge pull request #3702 from mempool/mononaut/websocket-logs
Log websocket statistics
2023-05-02 00:55:13 +04:00
Mononaut
3748102bb0 Log websocket statistics 2023-05-01 13:08:29 -06:00
softsimon
a87b604153 Merge pull request #3700 from mempool/mononaut/fix-async-cache-load
await for mempool change handler after loading disk cache
2023-05-01 01:54:33 +04:00
Mononaut
4597bfa5d7 use $ naming convention for async function names 2023-04-30 15:52:44 -06:00
Mononaut
f30cf70226 await for mempool change handler after loading disk cache 2023-04-30 15:51:26 -06:00
softsimon
ba4253da79 Merge pull request #3689 from mempool/mononaut/debug-main-loop-stall
detect and log stalls in the main loop
2023-05-01 00:17:57 +04:00
softsimon
58b08f2c33 Add end quotes 2023-05-01 00:16:23 +04:00
softsimon
ac240398ef Merge branch 'master' into mononaut/debug-main-loop-stall 2023-04-30 22:53:06 +04:00
softsimon
1f2d05c5a4 Merge pull request #3696 from mempool/mononaut/mysql-timeout
Add explicit timeout to mysql DB queries
2023-04-30 22:09:02 +04:00
Mononaut
e05f2198d5 Add explicit timeout to mysql DB queries 2023-04-28 19:21:03 -06:00
Mononaut
95df317f56 detect and log stall in main loop 2023-04-28 19:17:58 -06:00
softsimon
f61f520a4b Merge pull request #3687 from mempool/simon/backend-block-tip-height-endpoint
Backend block tip height endpoint
2023-04-28 13:41:49 +04:00
wiz
864225a0dc Merge branch 'master' into simon/backend-block-tip-height-endpoint 2023-04-28 18:25:13 +09:00
softsimon
5628da2f80 Merge pull request #3694 from mempool/simon/revert-tcp-socket-fallback
Revert TCP socket fallback
2023-04-28 12:16:02 +04:00
softsimon
000c46bf57 Revert TCP socket fallback 2023-04-28 12:06:49 +04:00
softsimon
66919a1aba Backend block tip height endpoint 2023-04-26 13:49:01 +04:00
Mononaut
7b9fd8ac63 prevent table overflow in unfurl previews 2023-04-26 05:15:38 +09:00
nymkappa
6ac1a43d44 Merge branch 'master' into nymkappa/tx-overflow 2023-04-22 20:11:45 +02:00
nymkappa
99af881cdd Merge branch 'master' into nymkappa/clip-label-overflow 2023-04-22 20:10:27 +02:00
hunicus
008ec104b6 Fix clashing class in unchained svg 2023-04-19 22:52:53 -04:00
hunicus
b0859f91b2 Update unchained icon on about page 2023-04-19 22:00:09 -04:00
TechMiX
22ee9916dd fix change component and audit button position in RTL mode 2023-04-19 12:15:09 +02:00
softsimon
1df2c89cdb Merge branch 'master' into mononaut/fix-mempool-block-skeleton 2023-04-12 00:11:51 +08:00
softsimon
2fbe2b2fa6 Merge pull request #3652 from mempool/mononaut/fix-flying-mempool-blocks
Disable mempool block animations except when new block is mined
2023-04-08 23:09:53 +08:00
Giovanni La Perna
71935e29c8 Update and rename giovannilaperna.txt to learntheropes.txt
change github username
2023-04-08 11:19:04 +02:00
softsimon
d293d637b5 Merge pull request #3633 from mempool/mononaut/right-click-scroll
Disable blockchain drag for middle/right click
2023-04-08 17:00:25 +08:00
softsimon
04a8249883 Merge pull request #3644 from mempool/mononaut/full-mempool-cpfp
Perform full cpfp calculations for the entire mempool
2023-04-08 16:50:57 +08:00
Rex
123b853205 Add cla 2023-04-08 11:43:26 +08:00
softsimon
a196c276c9 Merge pull request #3656 from mempool/nymkappa/update-tests
[config] add missing RETRY_UNIX_SOCKET_AFTER
2023-04-08 10:22:08 +08:00
nymkappa
dfe2cf631f [config] fix docker esplora config and template 2023-04-08 10:42:08 +09:00
nymkappa
d6913b6439 [config] add missing RETRY_UNIX_SOCKET_AFTER 2023-04-07 13:28:32 +09:00
Giovanni La Perna
bad73c1805 Create giovannilaperna.txt 2023-04-07 01:04:23 +02:00
Mononaut
6602bddb2b Fit mempool block skeleton loaders to screen 2023-04-07 03:25:02 +09:00
Mononaut
32cd8bb3cb Prevent mempool block animations except when new block mined 2023-04-07 02:18:33 +09:00
Mononaut
5950034f53 Perform full cpfp calculations for the entire mempool 2023-04-07 00:25:45 +09:00
wiz
d18ebdfc59 ops: Update hard-coded path for liquid asset icons 2023-04-06 19:19:30 +09:00
wiz
604c3ba266 ops: Tweak boot-time delays for all daemons 2023-04-06 19:19:28 +09:00
wiz
b8d063a4f7 Merge pull request #3649 from mempool/nymkappa/indexing-error
Fix indexing error
2023-04-06 17:52:58 +09:00
wiz
3c30415982 ops: Add fallback TCP socket for esplora backends 2023-04-06 17:52:17 +09:00
nymkappa
c5252dc27d [indexing] delete dead code 2023-04-06 11:55:25 +09:00
nymkappa
6016db2533 [indexing] save missing fee_percentiles and median_fee_amt when indexing on the fly 2023-04-06 11:55:17 +09:00
nymkappa
b23f14b798 [indexing] fix typescript issue, reading invalid field 2023-04-06 11:54:22 +09:00
wiz
09d52f9fbe Merge pull request #3643 from mempool/nymkappa/esplora-socket-fallback
[esplora] fallback to tcp socket if unix socket fails
2023-04-05 22:58:34 +09:00
nymkappa
c23e529f0a [main loop] retry every seconds upon exception - warn after 5 attempts 2023-04-05 22:44:01 +09:00
nymkappa
ab7cb5f681 [esplora] reset timeout variable when retrying unix socket 2023-04-05 17:05:23 +09:00
nymkappa
db27e5a92c [esplora] print log when retrying unix socket - don't fallback to tcp socket on ETIMEDOUT 2023-04-05 17:00:53 +09:00
wiz
66109afb0d ops: Enable unix socket for esplora on mainnet-lightning 2023-04-05 16:48:26 +09:00
nymkappa
b6f1fd5a4a [esplora] initialize default socket config to axiosConfigWithUnixSocket 2023-04-05 16:38:37 +09:00
nymkappa
44a0913b81 [esplora] fallback to tcp socket if unix socket fails 2023-04-05 16:27:13 +09:00
Mononaut
4c569c0ded Send mempool effective fee rate changes to frontend & apply 2023-04-05 08:42:01 +09:00
Mononaut
3d5c156776 Use effective fee rates in mempool block visualizations & tooltips 2023-04-05 08:42:01 +09:00
wiz
6c81dcdc76 Merge pull request #3640 from mempool/ops/use-unix-sockets-for-mysql
ops: Use unix sockets for MySQL
2023-04-04 21:52:26 +09:00
wiz
906f24f0ee ops: Use unix sockets for MySQL 2023-04-04 21:48:42 +09:00
wiz
bca35600ff ops: Fix installer creation of CLN folders 2023-04-04 20:18:46 +09:00
wiz
a9dc5e9be4 Merge pull request #3634 from mempool/nymkappa/fiat-component-custom-color
Make fiat component color class customizable
2023-04-04 14:11:58 +09:00
nymkappa
90fa4a8f77 Make fiat component color class customizable 2023-04-04 11:42:06 +09:00
Mononaut
d325734c16 Disable blockchain drag for middle/right click 2023-04-04 08:25:40 +09:00
Mononaut
aa882aa36a Fix RTL locale unfurls 2023-04-04 07:55:55 +09:00
wiz
bdbb1dcf8e Merge pull request #3631 from mempool/simon/improved-warning-message
Redesigned testnet alert
2023-04-03 22:09:52 +09:00
wiz
2ada9dcd40 Merge branch 'master' into simon/improved-warning-message 2023-04-03 21:58:09 +09:00
wiz
95cc74c076 Merge pull request #3630 from mempool/hunicus/phx-dark-icon
Switch phoenix wallet logo to dark mode
2023-04-03 21:57:56 +09:00
softsimon
d59a31a65a Merge branch 'master' into simon/improved-warning-message 2023-04-03 20:03:04 +09:00
softsimon
38e4832b6a Restoring missing tx index attribute for cypress 2023-04-03 20:02:39 +09:00
softsimon
6b6dc9fb24 Merge pull request #3622 from mempool/mononaut/shift-click
Key modifiers to open transaction in new tab from visualization
2023-04-03 19:05:08 +09:00
softsimon
a1b6fc5a7b Redesigned testnet alert
fixes #3625
2023-04-03 18:30:06 +09:00
wiz
6ac0e887f7 Merge pull request #3247 from mempool/ops/esplora-unix-sockets
ops: Use unix sockets to query esplora from nginx
2023-04-03 16:07:05 +09:00
wiz
bdb7e62921 Merge branch 'master' into ops/esplora-unix-sockets 2023-04-03 15:34:47 +09:00
hunicus
445e376675 Switch phoenix wallet logo to dark mode 2023-04-03 02:07:56 -04:00
wiz
bedbd9c5d5 Merge pull request #3587 from mempool/hunicus/mynode-casing
Update mynode profile on about page
2023-04-03 15:00:13 +09:00
wiz
34236fca7c Remove unused mynodebtc.jpg 2023-04-03 14:59:39 +09:00
wiz
f74d651b85 Merge branch 'master' into hunicus/mynode-casing 2023-04-03 14:51:28 +09:00
softsimon
41a93af89e Merge pull request #3601 from mempool/mononaut/fix-liquid-asset-diagram
Fix broken tx diagram for non-LBTC liquid assets
2023-04-03 14:39:38 +09:00
wiz
e5b1615c61 Merge branch 'master' into mononaut/fix-liquid-asset-diagram 2023-04-03 12:27:32 +09:00
softsimon
2ef340712f Merge pull request #3442 from mempool/nymkappa/reorg-keep-templates
When a re-org happens, keep the block templates for audit
2023-04-03 12:24:05 +09:00
wiz
3841d1e7b8 Merge pull request #3600 from mempool/mononaut/fix-unfurl-cpfp-badge
Fix unfurl cpfp badge
2023-04-03 11:50:11 +09:00
wiz
675ecc608c Merge branch 'master' into mononaut/fix-unfurl-cpfp-badge 2023-04-03 11:40:47 +09:00
wiz
3625e41e97 Merge pull request #3599 from mempool/mononaut/fix-ln-node-unfurl
Fix node unfurl row overflow
2023-04-03 11:40:39 +09:00
wiz
ff8fecbd05 Merge branch 'master' into mononaut/fix-ln-node-unfurl 2023-04-03 11:31:20 +09:00
Mononaut
a91a8d2a4b Key modifiers to open tx in new tab from visualization 2023-04-02 07:46:32 +09:00
softsimon
83c03474a9 Merge pull request #3586 from mempool/nymkappa/fix-price-undefined
Add missing sanity check when fetching single price datapoint
2023-04-01 18:04:32 +09:00
softsimon
f55aac46f1 Merge pull request #3568 from mempool/hunicus/fix-memfaq-mobile
Fix anchor link expand on mobile for mempool faq
2023-04-01 18:03:17 +09:00
softsimon
f1b5ee2a5f Merge pull request #3404 from mempool/nymkappa/bugfix/wrong-percentage-heap-log
Fix % on heap limit warn
2023-04-01 16:56:50 +09:00
softsimon
97008b9caa Merge pull request #3326 from mempool/nymkappa/warning-testnet-signet
Show warning on testnet/signet
2023-04-01 16:53:17 +09:00
softsimon
b3038e557c Merge pull request #3618 from mempool/nymkappa/ln-stats-import-trycatch
Wrap lightning stats importer into try/catch
2023-04-01 15:21:55 +09:00
softsimon
61e29bcff9 Merge pull request #3608 from mempool/nymkappa/fix-default-graph-preference
Use window.location object instead of angular router for default graph window preference setting
2023-04-01 15:18:10 +09:00
nymkappa
a512884b65 Wrap lightning stats importer into try/catch 2023-04-01 14:56:18 +09:00
softsimon
46fbd6aa49 Merge pull request #3443 from mempool/simon/update-backend-libs-2023-03
Update backend NPM deps
2023-04-01 12:25:40 +09:00
softsimon
fc29943d0f Upgrading deps 2023-04-01 12:16:59 +09:00
softsimon
482a609d84 Update backend NPM libs 2023-04-01 12:15:32 +09:00
softsimon
b7d869ad23 Merge pull request #3375 from mempool/nymkappa/log-update
Update some logs
2023-04-01 12:07:53 +09:00
nymkappa
321161ede9 Cleanup some log 2023-04-01 12:00:54 +09:00
softsimon
b5ad0895ac Merge pull request #3610 from mempool/nymkappa/fix-search-wiz-test
Fix search 1wizS test
2023-03-31 22:32:40 +09:00
softsimon
427cef9f9d Merge pull request #3611 from mempool/nymkappa/fix-transaction-list-infinite-scroll
Fix infinite scroll transaction list component
2023-03-31 19:23:36 +09:00
nymkappa
816fb3bf01 Don't delete transactions when checking if the current chain is valid 2023-03-31 12:22:26 +09:00
nymkappa
44bbb472d3 Keep re-org'ed block summaries in the database 2023-03-31 12:08:05 +09:00
nymkappa
aba49897f9 Fix infinite scroll transaction list component 2023-03-30 17:07:34 +09:00
nymkappa
96121a86f8 Fix search 1wizS test 2023-03-29 17:35:49 +09:00
nymkappa
ea2193a42d Add missing sanity check when fetching single price datapoint 2023-03-29 17:33:07 +09:00
nymkappa
3db1486bfb Fix transaction amount overflow 2023-03-29 17:32:39 +09:00
nymkappa
9e4fe40ca3 When a re-org happens, keep the block templates for audit 2023-03-29 17:32:17 +09:00
nymkappa
d9b4ad64bb Fix % on heap limit warn 2023-03-29 17:30:32 +09:00
nymkappa
7562407a0c Show warning on testnet/signet 2023-03-29 17:27:33 +09:00
nymkappa
0bc244b9f1 Use window.location object instead of angular router for default graph window preference setting 2023-03-29 15:10:59 +09:00
nymkappa
7ab373ecac Clip overflowing labels in pool component on mobile 2023-03-29 15:09:38 +09:00
Mononaut
14e0d80042 Fix broken tx diagram for non-lBTC liquid assets 2023-03-29 07:54:58 +09:00
Mononaut
5555916de3 Fix unfurl cpfp badge 2023-03-29 05:45:49 +09:00
Mononaut
ef09912d1b Fix node unfurl row overflow 2023-03-29 03:15:01 +09:00
nymkappa
c675d1c498 Make sure to scan closed channels even if config.MEMPOOL.ENABLE = false 2023-03-28 23:07:50 +09:00
softsimon
5977251a20 Merge pull request #3316 from mempool/mononaut/projected-median-fee
New median fee calculation for mempool blocks
2023-03-28 17:22:20 +09:00
Mononaut
a4c027dc48 clean up unused vars in mempool-blocks.ts 2023-03-28 17:02:37 +09:00
Mononaut
9f40cba914 use new median fee calculation for mempool blocks 2023-03-28 17:02:37 +09:00
softsimon
5ba2c181b0 Merge pull request #3315 from mempool/mononaut/effective-fee-rates
Use effective fee rate heuristics for block fee span
2023-03-28 16:57:22 +09:00
Mononaut
2fc404a55c refactor effective rate calculation 2023-03-28 16:20:20 +09:00
Mononaut
2baa10dcef Use effective fee rate heuristics for block fee span 2023-03-28 16:19:06 +09:00
softsimon
d08a318a2c Merge pull request #3584 from mempool/release/v2.5.0
Release v2.5.0
2023-03-28 14:26:18 +09:00
wiz
96f3218ec6 Bump version to v2.6.0-dev 2023-03-28 14:25:05 +09:00
wiz
57eddac7f0 Release v2.5.0 2023-03-28 12:14:31 +09:00
wiz
af115b49aa Merge pull request #3585 from mempool/nymkappa/fix-db-state
Reset pools sha db state
2023-03-28 12:12:04 +09:00
softsimon
332f9a2f5e Pull from transifex (Vietnamese) 2023-03-28 12:11:27 +09:00
hunicus
2b3d132db6 Update mynode logo 2023-03-27 07:26:06 -04:00
hunicus
f1361a698d Switch mynode capitalization to match branding 2023-03-27 06:50:30 -04:00
nymkappa
34eef3553b Reset pools sha db state 2023-03-27 19:39:50 +09:00
softsimon
9e4ce42b6a Pull from transifex (Hebrew) 2023-03-27 16:31:02 +09:00
softsimon
4c4a91ae95 Merge pull request #3560 from mempool/mononaut/missing-tx-bug
Fix thread inconsistency / lazy deletion race condition bugs
2023-03-27 15:33:34 +09:00
softsimon
93d46d5c5b Pull from transifex 2023-03-27 15:12:23 +09:00
softsimon
8788d4f898 Pull from transifex 2023-03-27 15:10:17 +09:00
wiz
e28650c46c Merge pull request #3581 from mempool/simon/enable-lightning-mempool-prod 2023-03-27 14:53:46 +09:00
softsimon
855c11f02c Enabling mempool in lightning prod
fixes #3579
2023-03-27 14:51:34 +09:00
softsimon
3f8e91bd46 Merge pull request #3578 from mempool/nymkappa/revert-undocumented-fast-forward
Revert regression introduced in #1320
2023-03-26 22:10:23 +09:00
softsimon
6722e45109 Merge pull request #3576 from mempool/mononaut/fix-difficulty-adjustment
Fix difficulty adjustment bugs
2023-03-26 18:02:30 +09:00
nymkappa
414383638d Revert regression introduced in #1320 2023-03-26 17:54:24 +09:00
nymkappa
2575b79c05 Merge branch 'master' into mononaut/fix-difficulty-adjustment 2023-03-26 17:02:41 +09:00
nymkappa
c7cab4c877 Remove difficulty adjustment calculation lag in the backend 2023-03-26 17:01:04 +09:00
softsimon
85c2f0ba30 Pull from transifex 2023-03-26 16:46:20 +09:00
Mononaut
edfbede704 Don't send back difficulty adjustment info 2023-03-26 09:05:41 +09:00
Mononaut
5f60cb821a Fix difficulty adjustment start-of-epoch edge cases 2023-03-26 07:27:11 +09:00
Mononaut
8486c1117d log warnings for unexpectedly missing txs 2023-03-26 05:41:31 +09:00
hunicus
ad3785ff41 Fix anchor link expand on mobile for mempool faq 2023-03-24 21:22:49 -04:00
Mononaut
61f24562fd tighten sanity checks in block audit 2023-03-24 09:49:02 +09:00
Mononaut
28de93d0ff move lazy tx deletion into main loop 2023-03-24 09:48:08 +09:00
Mononaut
1fd85b729d handle stale transactions in block templates 2023-03-24 09:47:08 +09:00
softsimon
5681ae3f5c Pull from transifex 2023-03-23 22:45:07 +09:00
softsimon
9d9e0976ae Pull from transifex 2023-03-23 17:41:24 +09:00
wiz
6180837636 Merge pull request #3557 from mempool/nymkappa/hotfix-infinite-scroll
Hotfix infinite scroll (need to apply a real fix for 2.5.1)
2023-03-23 17:36:08 +09:00
wiz
17beaf7d4f Merge pull request #3555 from mempool/hunicus/raspiblitz-logo
Change raspibolt logo to raspiblitz logo
2023-03-23 17:34:01 +09:00
wiz
ce8f471b27 Merge pull request #3554 from mempool/simon/bumping-electrum-client
Bumping electrum-client
2023-03-23 17:27:31 +09:00
nymkappa
b3e36fdd99 Hotfix infinite scroll (need to apply a real fix) 2023-03-23 17:23:32 +09:00
wiz
f971ddf1fa Merge branch 'master' into hunicus/raspiblitz-logo 2023-03-23 17:22:18 +09:00
hunicus
c0c37922c3 Change raspibolt logo to raspiblitz logo 2023-03-23 03:12:44 -04:00
wiz
1eb9e58331 Merge branch 'master' into simon/bumping-electrum-client 2023-03-23 15:58:44 +09:00
wiz
f8a35a110c Merge pull request #3553 from mempool/nymkappa/electrum-retry
Reconnect to electrum an unlimited amount of times every 1 seconds upon disconnection
2023-03-23 15:58:37 +09:00
softsimon
c4d13fb5b7 Bumping electrum-client 2023-03-23 15:56:30 +09:00
nymkappa
53a44853b3 Reconnect to electrum an unlimited amount of times every 1 seconds up disconnection 2023-03-23 15:18:48 +09:00
softsimon
29aa3617d8 Crediting Lithuanian and Danish translator 2023-03-23 14:43:03 +09:00
wiz
addf3e2521 Merge pull request #3548 from mempool/simon/updating-node-map-loading
Update channels map indexing indicator
2023-03-23 13:46:34 +09:00
softsimon
5826f8fa1e Pull from transifex 2023-03-23 00:28:17 +09:00
wiz
965d89fd91 Merge branch 'master' into simon/updating-node-map-loading 2023-03-22 17:48:09 +09:00
nymkappa
ed69591bcf Show "No data to display yet" in "Fee distribution" chart on node page when there are no channels yet 2023-03-22 14:09:30 +09:00
nymkappa
f1f6c48128 Show "No data to display yet" until we have at least two points for node stats charts 2023-03-22 13:45:27 +09:00
softsimon
f8bd062aa2 Pull from transifex 2023-03-22 13:35:16 +09:00
softsimon
77835bcb9d Restoring Preview component behavior 2023-03-22 13:20:22 +09:00
softsimon
bf5821c8c8 Remove indexing indicator 2023-03-21 23:17:09 +09:00
softsimon
a2e23014f4 Update channels map indexing indicator 2023-03-21 23:14:45 +09:00
wiz
811c14a6bd Merge pull request #3547 from mempool/simon/node-fee-chart-loading-d
Removing "d" from node fee chart loading
2023-03-21 23:10:47 +09:00
wiz
a34d87148b Merge branch 'master' into simon/node-fee-chart-loading-d 2023-03-21 23:01:19 +09:00
wiz
a45a8db479 Merge pull request #3494 from mempool/simon/difficulty-mining-css-updates
Difficulty mining css updates
2023-03-21 23:00:54 +09:00
softsimon
672f71c515 Removing "d" from node fee chart loading 2023-03-21 22:48:40 +09:00
softsimon
2c16bbb0e9 Fixing sub text height 2023-03-21 22:26:18 +09:00
softsimon
63f7709e82 Restoring size of current change 2023-03-21 22:20:14 +09:00
wiz
15b13ef4a4 Merge branch 'master' into simon/difficulty-mining-css-updates 2023-03-21 22:03:46 +09:00
wiz
75303c7a34 docker: Minor tweak to frontend entrypoint LND detection 2023-03-21 21:50:46 +09:00
softsimon
1a6048f0ab Difficulty mining css updates 2023-03-21 21:25:37 +09:00
wiz
ae6a408c05 Merge pull request #3493 from mempool/simon/update-softsimon-profile
Update softsimon profile photo
2023-03-21 20:58:11 +09:00
wiz
1015cbfa94 Merge pull request #3492 from mempool/simon/lightning-indexing-status
Lightning indexing indicators
2023-03-21 20:56:47 +09:00
wiz
876feef53f Fix frontend docker entrypoint umbrel LND detection 2023-03-21 18:11:10 +09:00
softsimon
f5f0329d39 Update softsimon profile photo 2023-03-21 18:03:19 +09:00
wiz
80a7b6d8d5 Merge branch 'master' into simon/lightning-indexing-status 2023-03-21 18:02:28 +09:00
wiz
f72e17c12e Merge pull request #3491 from mempool/simon/audit-off-hide-health
Audit disabled related UX fixes
2023-03-21 18:02:24 +09:00
wiz
f570b2762f Merge branch 'master' into simon/audit-off-hide-health 2023-03-21 17:43:56 +09:00
wiz
e2fda99578 Merge pull request #3490 from mempool/simon/auto-disable-ln-on-macaroon-fail
Auto disable LN on macaroon fail
2023-03-21 17:43:12 +09:00
softsimon
d7d45146c8 Lightning indexing indicators
refs  #2647
2023-03-21 17:33:14 +09:00
softsimon
45dbc6c6f6 Update logger network after modifying config 2023-03-21 16:21:11 +09:00
softsimon
d76e3a5939 Audit disabled related UX fixes 2023-03-21 16:02:46 +09:00
wiz
ccab8b16bf Merge branch 'master' into ops/esplora-unix-sockets 2023-03-21 14:29:06 +09:00
wiz
7970f4ae88 ops: Use unix sockets to query esplora from nginx 2023-03-13 16:35:27 +09:00
Mononaut
96a41400f4 Add axios support for esplora unix sockets 2023-03-13 14:53:44 +09:00
hunicus
6cc2f20638 Use href for enterprise links 2023-03-12 04:39:57 -04:00
wiz
730c1ae2d7 Merge branch 'master' into hunicus/manual-deployment-enterprise 2023-03-12 16:57:49 +09:00
Mononaut
105cccf9b0 convert soft 404s to hard 404s in unfurler ssr 2023-03-09 02:34:21 -06:00
Mononaut
2f3e498906 fix canonical/meta tags in unfurler 2023-03-09 00:26:28 -06:00
Mononaut
82a808529b clean up unfurler meta html template 2023-03-08 01:47:35 -06:00
Mononaut
477f3bd70a add applebot & bingbot to seo user-agent detection 2023-03-08 01:11:54 -06:00
wiz
a874cdfb56 Merge branch 'master' into mononaut/seo-ssr 2023-03-08 15:29:18 +09:00
hunicus
f493da4eac Generalize faq from linux to any server 2023-03-04 18:24:02 +09:00
hunicus
e7ad857cc9 Specify manual deployment support for enterprise sponsors [readme] 2023-03-04 18:24:02 +09:00
hunicus
f968faeaf9 Specify manual deployment support for enterprise sponsors [faq] 2023-03-04 18:24:02 +09:00
Felipe Knorr Kuhn
c3c44713ef Merge branch 'master' into mononaut/seo-ssr 2023-03-02 23:53:40 -08:00
mononaut
f6cae729a7 revert capitalization in title tag
Co-authored-by: wiz <j@wiz.biz>
2023-02-28 18:40:59 -06:00
Mononaut
b1e32ed55f Fix googlebot user-agent detection 2023-02-27 10:48:13 -06:00
Mononaut
2f27d9279d extend unfurler to dynamically render search crawler requests 2023-02-26 10:56:32 -06:00
842 changed files with 222550 additions and 138263 deletions

View File

@@ -1,24 +1,42 @@
version: 2
updates:
- package-ecosystem: npm
versioning-strategy: increase
directory: "/backend"
schedule:
interval: daily
open-pull-requests-limit: 10
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major"]
update-types:
["version-update:semver-major", "version-update:semver-patch"]
allow:
- dependency-type: "production"
- package-ecosystem: npm
directory: "/frontend"
versioning-strategy: increase
groups:
frontend-angular-dependencies:
patterns:
- "@angular*"
- "@ng-*"
- "ngx-*"
frontend-jest-dependencies:
patterns:
- "@types/jest"
- "jest"
frontend-eslint-dependencies:
patterns:
- "@typescript-eslint*"
- "eslint"
schedule:
interval: daily
open-pull-requests-limit: 10
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major"]
update-types:
["version-update:semver-major", "version-update:semver-patch"]
allow:
- dependency-type: "production"
@@ -28,7 +46,8 @@ updates:
interval: weekly
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major"]
update-types:
["version-update:semver-major", "version-update:semver-patch"]
- package-ecosystem: docker
directory: "/docker/frontend"
@@ -36,7 +55,8 @@ updates:
interval: weekly
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major"]
update-types:
["version-update:semver-major", "version-update:semver-patch"]
- package-ecosystem: "github-actions"
directory: "/"
@@ -44,4 +64,5 @@ updates:
interval: weekly
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major"]
update-types:
["version-update:semver-major", "version-update:semver-patch"]

View File

@@ -9,7 +9,7 @@ jobs:
if: "!contains(github.event.pull_request.labels.*.name, 'ops') && !contains(github.head_ref, 'ops/')"
strategy:
matrix:
node: ["16.16.0", "18.14.1"]
node: ["20", "21"]
flavor: ["dev", "prod"]
fail-fast: false
runs-on: "ubuntu-latest"
@@ -27,6 +27,18 @@ jobs:
node-version: ${{ matrix.node }}
registry-url: "https://registry.npmjs.org"
- name: Read rust-toolchain file from repository
id: gettoolchain
run: echo "::set-output name=toolchain::$(cat ./rust/gbt/rust-toolchain)"
working-directory: ${{ matrix.node }}/${{ matrix.flavor }}
- 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@dc6353516c68da0f06325f42ad880f76a5e77ec9
with:
toolchain: ${{ steps.gettoolchain.outputs.toolchain }}
- name: Install
if: ${{ matrix.flavor == 'dev'}}
run: npm ci
@@ -44,18 +56,111 @@ jobs:
- name: Unit Tests
if: ${{ matrix.flavor == 'dev'}}
run: npm run test
run: npm run test:ci
working-directory: ${{ matrix.node }}/${{ matrix.flavor }}/backend
- name: Build
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.16.0", "18.14.1"]
node: ["20", "21"]
flavor: ["dev", "prod"]
fail-fast: false
runs-on: "ubuntu-latest"
@@ -91,6 +196,167 @@ 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"]
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
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

View File

@@ -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: 16.15.0
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 }}

View File

@@ -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

19
.github/workflows/get_backend_hash.yml vendored Normal file
View File

@@ -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

View File

@@ -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,8 +98,10 @@ 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 \
--build-context rustgbt=./rust \
--build-context backend=./backend \
--output "type=registry" ./${{ matrix.service }}/ \
--build-arg commitHash=$SHORT_SHA

2
.gitignore vendored
View File

@@ -5,3 +5,5 @@ backend/mempool-config.json
*.swp
frontend/src/resources/config.template.js
frontend/src/resources/config.js
target
docker/backend/start_ci.sh

2
.nvmrc
View File

@@ -1 +1 @@
v16.16.0
v20.8.0

View File

@@ -1,5 +1,6 @@
{
"editor.tabSize": 2,
"typescript.preferences.importModuleSpecifier": "relative",
"typescript.tsdk": "./backend/node_modules/typescript/lib"
"typescript.tsdk": "./backend/node_modules/typescript/lib",
"rust-analyzer.procMacro.ignored": { "napi-derive": ["napi"] }
}

View File

@@ -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

35
LICENSE
View File

@@ -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 <https://mempool.space/about>.
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 <https://mempool.space/about>; 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 <https://mempool.space/about>.
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 <https://mempool.space/trademark-policy>.
See our full Trademark Policy and Guidelines for more details, published on
<https://mempool.space/trademark-policy>.
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
<http://www.gnu.org/licenses/>.
along with this program. If not, see <http://www.gnu.org/licenses/>.

View File

@@ -1,675 +0,0 @@
### GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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 <https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -1 +0,0 @@
# For additional configs/scripting

View File

@@ -1,4 +1,4 @@
# The Mempool Open Source Project [![mempool](https://img.shields.io/endpoint?url=https://dashboard.cypress.io/badge/simple/ry4br7/master&style=flat-square)](https://dashboard.cypress.io/projects/ry4br7/runs)
# The Mempool Open Source Project® [![mempool](https://img.shields.io/endpoint?url=https://dashboard.cypress.io/badge/simple/ry4br7/master&style=flat-square)](https://dashboard.cypress.io/projects/ry4br7/runs)
https://user-images.githubusercontent.com/93150691/226236121-375ea64f-b4a1-4cc0-8fad-a6fb33226840.mp4
@@ -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 <a href="#one-click-installation">one-click install method</a>.
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 <a href="https://mempool.space/enterprise" target="_blank">Mempool Enterprise®</a>.
<a id="one-click-installation"></a>
## 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.

1
backend/.dockerignore Normal file
View File

@@ -0,0 +1 @@
Dockerfile

12
backend/.gitignore vendored
View File

@@ -7,6 +7,12 @@ mempool-config.json
pools.json
icons.json
# docker
Dockerfile
GeoIP
start.sh
wait-for-it.sh
# compiled output
/dist
/tmp
@@ -45,3 +51,9 @@ testem.log
#System Files
.DS_Store
Thumbs.db
# package folder (npm run package output)
/package
# Rust GBT folder (We build externally first)
/rust-gbt

View File

@@ -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 does not provide support for custom setups.
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).
@@ -79,11 +79,13 @@ Query OK, 0 rows affected (0.00 sec)
_Make sure to use Node.js 16.10 and npm 7._
_The build process requires [Rust](https://www.rust-lang.org/tools/install) to be installed._
Install dependencies with `npm` and build the backend:
```
cd backend
npm install
npm install --no-install-links # npm@9.4.2 and later can omit the --no-install-links
npm run build
```

View File

@@ -1,5 +1,6 @@
{
"MEMPOOL": {
"OFFICIAL": false,
"NETWORK": "mainnet",
"BACKEND": "electrum",
"ENABLED": true,
@@ -8,6 +9,7 @@
"API_URL_PREFIX": "/api/v1/",
"POLL_RATE_MS": 2000,
"CACHE_DIR": "./cache",
"CACHE_ENABLED": true,
"CLEAR_PROTECTION_MINUTES": 20,
"RECOMMENDED_FEE_PERCENTILE": 50,
"BLOCK_WEIGHT_UNITS": 4000000,
@@ -15,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,
@@ -25,17 +28,23 @@
"POOLS_JSON_URL": "https://raw.githubusercontent.com/mempool/mining-pools/master/pools-v2.json",
"POOLS_JSON_TREE_URL": "https://api.github.com/repos/mempool/mining-pools/git/trees/master",
"AUDIT": false,
"ADVANCED_GBT_AUDIT": false,
"ADVANCED_GBT_MEMPOOL": false,
"RUST_GBT": false,
"LIMIT_GBT": false,
"CPFP_INDEXING": false,
"DISK_CACHE_BLOCK_INTERVAL": 6
"DISK_CACHE_BLOCK_INTERVAL": 6,
"MAX_PUSH_TX_SIZE_WEIGHT": 4000000,
"ALLOW_UNREACHABLE": true,
"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",
@@ -43,14 +52,22 @@
"TLS_ENABLED": true
},
"ESPLORA": {
"REST_API_URL": "http://127.0.0.1:3000"
"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": {
"HOST": "127.0.0.1",
"PORT": 8332,
"USERNAME": "mempool",
"PASSWORD": "mempool",
"TIMEOUT": 60000
"TIMEOUT": 60000,
"COOKIE": false,
"COOKIE_PATH": "/path/to/bitcoin/.cookie"
},
"DATABASE": {
"ENABLED": true,
@@ -59,7 +76,9 @@
"SOCKET": "/var/run/mysql/mysql.sock",
"DATABASE": "mempool",
"USERNAME": "mempool",
"PASSWORD": "mempool"
"PASSWORD": "mempool",
"TIMEOUT": 180000,
"PID_DIR": ""
},
"SYSLOG": {
"ENABLED": true,
@@ -78,10 +97,6 @@
"GEOLITE2_ASN": "/usr/local/share/GeoIP/GeoLite2-ASN.mmdb",
"GEOIP2_ISP": "/usr/local/share/GeoIP/GeoIP2-ISP.mmdb"
},
"BISQ": {
"ENABLED": false,
"DATA_PATH": "/bisq/statsnode-data/btc_mainnet/db"
},
"LIGHTNING": {
"ENABLED": false,
"BACKEND": "lnd",
@@ -108,16 +123,34 @@
"USERNAME": "",
"PASSWORD": ""
},
"PRICE_DATA_SERVER": {
"TOR_URL": "http://wizpriceje6q5tdrxkyiazsgu7irquiqjy2dptezqhrtu7l2qelqktid.onion/getAllMarketPrices",
"CLEARNET_URL": "https://price.bisq.wiz.biz/getAllMarketPrices"
},
"EXTERNAL_DATA_SERVER": {
"MEMPOOL_API": "https://mempool.space/api/v1",
"MEMPOOL_ONION": "http://mempoolhqx4isw62xs7abwphsq7ldayuidyx2v2oethdhhj6mlo2r6ad.onion/api/v1",
"LIQUID_API": "https://liquid.network/api/v1",
"LIQUID_ONION": "http://liquidmom47f6s3m53ebfxn47p76a6tlnxib3wp6deux7wuzotdr6cyd.onion/api/v1",
"BISQ_URL": "https://bisq.markets/api",
"BISQ_ONION": "http://bisqmktse2cabavbr2xjq7xw3h6g5ottemo5rolfcwt6aly6tp5fdryd.onion/api"
"LIQUID_ONION": "http://liquidmom47f6s3m53ebfxn47p76a6tlnxib3wp6deux7wuzotdr6cyd.onion/api/v1"
},
"REDIS": {
"ENABLED": false,
"UNIX_SOCKET_PATH": "/tmp/redis.sock",
"BATCH_QUERY_BASE_SIZE": 5000
},
"REPLICATION": {
"ENABLED": false,
"AUDIT": false,
"AUDIT_START_HEIGHT": 774000,
"SERVERS": [
"list",
"of",
"trusted",
"servers"
]
},
"MEMPOOL_SERVICES": {
"API": "https://mempool.space/api/v1/services",
"ACCELERATIONS": false
},
"FIAT_PRICE": {
"ENABLED": true,
"API_KEY": "your-api-key-from-freecurrencyapi.com"
}
}

17
backend/npm_package.sh Executable file
View File

@@ -0,0 +1,17 @@
#/bin/sh
set -e
# Remove previous dist folder
rm -rf dist
# Build new dist folder
npm run build
# Remove previous package folder
rm -rf package
# Move JS and deps
mv dist package
cp -R node_modules package
# Remove symlink for rust-gbt and insert real folder
rm package/node_modules/rust-gbt
cp -R rust-gbt package/node_modules
# Clean up deps
npm run package-rm-build-deps

View File

@@ -0,0 +1,9 @@
#/bin/sh
set -e
# Cleaning up inside the node_modules folder
cd package/node_modules
rm -rf \
typescript \
@typescript-eslint \
@napi-rs

7804
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "mempool-backend",
"version": "2.5.0-dev",
"version": "3.0.0-dev",
"description": "Bitcoin mempool visualizer and blockchain explorer backend",
"license": "GNU Affero General Public License v3.0",
"homepage": "https://mempool.space",
@@ -23,46 +23,52 @@
"scripts": {
"tsc": "./node_modules/typescript/bin/tsc -p tsconfig.build.json",
"build": "npm run tsc && npm run create-resources",
"clean": "rm -rf ./dist/ ./node_modules/ ./package/ ./rust-gbt/",
"create-resources": "cp ./src/tasks/price-feeds/mtgox-weekly.json ./dist/tasks && node dist/api/fetch-version.js",
"package": "npm run build && rm -rf package && mv dist package && mv node_modules package && npm run package-rm-build-deps",
"package-rm-build-deps": "(cd package/node_modules; rm -r typescript @typescript-eslint)",
"package": "./npm_package.sh",
"package-rm-build-deps": "./npm_package_rm_build_deps.sh",
"preinstall": "cd ../rust/gbt && npm run build-release && npm run to-backend",
"start": "node --max-old-space-size=2048 dist/index.js",
"start-production": "node --max-old-space-size=16384 dist/index.js",
"reindex-updated-pools": "npm run start-production --update-pools",
"reindex-all-blocks": "npm run start-production --update-pools --reindex-blocks",
"test": "./node_modules/.bin/jest --coverage",
"test:ci": "CI=true ./node_modules/.bin/jest --coverage",
"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}\""
},
"dependencies": {
"@babel/core": "^7.20.12",
"@mempool/electrum-client": "^1.1.7",
"@types/node": "^16.18.11",
"axios": "~0.27.2",
"bitcoinjs-lib": "~6.1.0",
"crypto-js": "~4.1.1",
"express": "~4.18.2",
"maxmind": "~4.3.8",
"mysql2": "~2.3.3",
"node-worker-threads-pool": "~1.5.1",
"@babel/core": "^7.24.0",
"@mempool/electrum-client": "1.1.9",
"@types/node": "^18.15.3",
"axios": "~1.6.1",
"bitcoinjs-lib": "~6.1.3",
"crypto-js": "~4.2.0",
"express": "~4.19.2",
"maxmind": "~4.3.11",
"mysql2": "~3.9.1",
"rust-gbt": "file:./rust-gbt",
"redis": "^4.6.6",
"socks-proxy-agent": "~7.0.0",
"typescript": "~4.7.4",
"ws": "~8.11.0"
"typescript": "~4.9.3",
"ws": "~8.13.0"
},
"devDependencies": {
"@babel/core": "^7.20.7",
"@babel/code-frame": "^7.18.6",
"@babel/core": "^7.24.0",
"@types/compression": "^1.7.2",
"@types/crypto-js": "^4.1.1",
"@types/express": "^4.17.15",
"@types/jest": "^29.2.5",
"@types/ws": "~8.5.4",
"@typescript-eslint/eslint-plugin": "^5.48.1",
"@typescript-eslint/parser": "^5.48.1",
"eslint": "^8.31.0",
"eslint-config-prettier": "^8.5.0",
"jest": "^29.3.1",
"prettier": "^2.8.2",
"ts-jest": "^29.0.3",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.0",
"@types/ws": "~8.5.5",
"@typescript-eslint/eslint-plugin": "^5.55.0",
"@typescript-eslint/parser": "^5.55.0",
"eslint": "^8.36.0",
"eslint-config-prettier": "^8.8.0",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.1"
}
}

View File

@@ -1,42 +1,51 @@
{
"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__",
"AUTOMATIC_BLOCK_REINDEXING": false,
"POLL_RATE_MS": 3,
"CACHE_DIR": "__MEMPOOL_CACHE_DIR__",
"CACHE_ENABLED": true,
"CLEAR_PROTECTION_MINUTES": 4,
"RECOMMENDED_FEE_PERCENTILE": 5,
"BLOCK_WEIGHT_UNITS": 6,
"INITIAL_BLOCKS_AMOUNT": 7,
"MEMPOOL_BLOCKS_AMOUNT": 8,
"USE_SECOND_NODE_FOR_MINFEE": 10,
"EXTERNAL_ASSETS": 11,
"EXTERNAL_ASSETS": [],
"EXTERNAL_MAX_RETRY": 12,
"EXTERNAL_RETRY_INTERVAL": 13,
"USER_AGENT": "__MEMPOOL_USER_AGENT__",
"STDOUT_LOG_MIN_PRIORITY": "__MEMPOOL_STDOUT_LOG_MIN_PRIORITY__",
"INDEXING_BLOCKS_AMOUNT": 14,
"POOLS_JSON_TREE_URL": "__POOLS_JSON_TREE_URL__",
"POOLS_JSON_URL": "__POOLS_JSON_URL__",
"AUDIT": "__MEMPOOL_AUDIT__",
"ADVANCED_GBT_AUDIT": "__MEMPOOL_ADVANCED_GBT_AUDIT__",
"ADVANCED_GBT_MEMPOOL": "__MEMPOOL_ADVANCED_GBT_MEMPOOL__",
"CPFP_INDEXING": "__MEMPOOL_CPFP_INDEXING__",
"MAX_BLOCKS_BULK_QUERY": "__MEMPOOL_MAX_BLOCKS_BULK_QUERY__",
"DISK_CACHE_BLOCK_INTERVAL": "__MEMPOOL_DISK_CACHE_BLOCK_INTERVAL__"
"POOLS_JSON_TREE_URL": "__MEMPOOL_POOLS_JSON_TREE_URL__",
"POOLS_JSON_URL": "__MEMPOOL_POOLS_JSON_URL__",
"AUDIT": true,
"RUST_GBT": false,
"LIMIT_GBT": false,
"CPFP_INDEXING": true,
"MAX_BLOCKS_BULK_QUERY": 999,
"DISK_CACHE_BLOCK_INTERVAL": 999,
"MAX_PUSH_TX_SIZE_WEIGHT": 4000000,
"ALLOW_UNREACHABLE": true,
"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": "__CORE_RPC_TIMEOUT__"
"TIMEOUT": 1000,
"COOKIE": false,
"COOKIE_PATH": "__CORE_RPC_COOKIE_PATH__"
},
"ELECTRUM": {
"HOST": "__ELECTRUM_HOST__",
@@ -44,14 +53,22 @@
"TLS_ENABLED": true
},
"ESPLORA": {
"REST_API_URL": "__ESPLORA_REST_API_URL__"
"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": {
"HOST": "__SECOND_CORE_RPC_HOST__",
"PORT": 17,
"USERNAME": "__SECOND_CORE_RPC_USERNAME__",
"PASSWORD": "__SECOND_CORE_RPC_PASSWORD__",
"TIMEOUT": "__SECOND_CORE_RPC_TIMEOUT__"
"TIMEOUT": 2000,
"COOKIE": false,
"COOKIE_PATH": "__SECOND_CORE_RPC_COOKIE_PATH__"
},
"DATABASE": {
"ENABLED": false,
@@ -60,7 +77,10 @@
"PORT": 18,
"DATABASE": "__DATABASE_DATABASE__",
"USERNAME": "__DATABASE_USERNAME__",
"PASSWORD": "__DATABASE_PASSWORD__"
"PASSWORD": "__DATABASE_PASSWORD__",
"PID_DIR": "__DATABASE_PID_FILE__",
"TIMEOUT": 3000,
"POOL_SIZE": 100
},
"SYSLOG": {
"ENABLED": false,
@@ -73,10 +93,6 @@
"ENABLED": false,
"TX_PER_SECOND_SAMPLE_PERIOD": 20
},
"BISQ": {
"ENABLED": true,
"DATA_PATH": "__BISQ_DATA_PATH__"
},
"SOCKS5PROXY": {
"ENABLED": true,
"USE_ONION": true,
@@ -85,27 +101,21 @@
"USERNAME": "__SOCKS5PROXY_USERNAME__",
"PASSWORD": "__SOCKS5PROXY_PASSWORD__"
},
"PRICE_DATA_SERVER": {
"TOR_URL": "__PRICE_DATA_SERVER_TOR_URL__",
"CLEARNET_URL": "__PRICE_DATA_SERVER_CLEARNET_URL__"
},
"EXTERNAL_DATA_SERVER": {
"MEMPOOL_API": "__EXTERNAL_DATA_SERVER_MEMPOOL_API__",
"MEMPOOL_ONION": "__EXTERNAL_DATA_SERVER_MEMPOOL_ONION__",
"LIQUID_API": "__EXTERNAL_DATA_SERVER_LIQUID_API__",
"LIQUID_ONION": "__EXTERNAL_DATA_SERVER_LIQUID_ONION__",
"BISQ_URL": "__EXTERNAL_DATA_SERVER_BISQ_URL__",
"BISQ_ONION": "__EXTERNAL_DATA_SERVER_BISQ_ONION__"
"LIQUID_ONION": "__EXTERNAL_DATA_SERVER_LIQUID_ONION__"
},
"LIGHTNING": {
"ENABLED": "__LIGHTNING_ENABLED__",
"ENABLED": true,
"BACKEND": "__LIGHTNING_BACKEND__",
"TOPOLOGY_FOLDER": "__LIGHTNING_TOPOLOGY_FOLDER__",
"STATS_REFRESH_INTERVAL": 600,
"GRAPH_REFRESH_INTERVAL": 600,
"LOGGER_UPDATE_INTERVAL": 30,
"FORENSICS_INTERVAL": 43200,
"FORENSICS_RATE_LIMIT": "__FORENSICS_RATE_LIMIT__"
"FORENSICS_RATE_LIMIT": 1234
},
"LND": {
"TLS_CERT_PATH": "",
@@ -115,5 +125,24 @@
},
"CLIGHTNING": {
"SOCKET": "__CLIGHTNING_SOCKET__"
},
"REPLICATION": {
"ENABLED": false,
"AUDIT": false,
"AUDIT_START_HEIGHT": 774000,
"SERVERS": []
},
"MEMPOOL_SERVICES": {
"API": "",
"ACCELERATIONS": false
},
"REDIS": {
"ENABLED": false,
"UNIX_SOCKET_PATH": "/tmp/redis.sock",
"BATCH_QUERY_BASE_SIZE": 5000
},
"FIAT_PRICE": {
"ENABLED": true,
"API_KEY": "__MEMPOOL_CURRENCY_API_KEY__"
}
}

View File

@@ -0,0 +1,24 @@
import { Common } from '../../api/common';
import { MempoolTransactionExtended } from '../../mempool.interfaces';
const randomTransactions = require('./test-data/transactions-random.json');
const replacedTransactions = require('./test-data/transactions-replaced.json');
const rbfTransactions = require('./test-data/transactions-rbfs.json');
describe('Mempool Utils', () => {
test('should detect RBF transactions with fast method', () => {
const newTransactions = rbfTransactions.concat(randomTransactions);
const result: { [txid: string]: MempoolTransactionExtended[] } = Common.findRbfTransactions(newTransactions, replacedTransactions);
expect(Object.values(result).length).toEqual(2);
expect(result).toHaveProperty('7219d95161f3718335991ac6d967d24eedec370908c9879bb1e192e6d797d0a6');
expect(result).toHaveProperty('5387881d695d4564d397026dc5f740f816f8390b4b2c5ec8c20309122712a875');
});
test.only('should detect RBF transactions with scalable method', () => {
const newTransactions = rbfTransactions.concat(randomTransactions);
const result: { [txid: string]: MempoolTransactionExtended[] } = Common.findRbfTransactions(newTransactions, replacedTransactions, true);
expect(Object.values(result).length).toEqual(2);
expect(result).toHaveProperty('7219d95161f3718335991ac6d967d24eedec370908c9879bb1e192e6d797d0a6');
expect(result).toHaveProperty('5387881d695d4564d397026dc5f740f816f8390b4b2c5ec8c20309122712a875');
});
});

View File

@@ -1,4 +1,8 @@
import { calcDifficultyAdjustment, DifficultyAdjustment } from '../../api/difficulty-adjustment';
import {
calcBitsDifference,
calcDifficultyAdjustment,
DifficultyAdjustment,
} from '../../api/difficulty-adjustment';
describe('Mempool Difficulty Adjustment', () => {
test('should calculate Difficulty Adjustments properly', () => {
@@ -7,32 +11,60 @@ 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)
'mainnet', // Network (if testnet, next value is non-zero)
0, // If not testnet, not used
0, // Latest block timestamp in seconds (only used if difficulty already locked in)
],
{ // Expected Result
progressPercent: 9.027777777777777,
difficultyChange: 12.562233927411782,
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)
@@ -41,26 +73,94 @@ describe('Mempool Difficulty Adjustment', () => {
],
{ // Expected Result is same other than timeOffset
progressPercent: 9.027777777777777,
difficultyChange: 12.562233927411782,
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,
},
],
] as [[number, number, number, number, string, number], DifficultyAdjustment][];
[ // 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)
'mainnet', // Network (if testnet, next value is non-zero)
dt('2023-05-04T14:54:26.000Z'), // Latest block timestamp in seconds
],
{ // Expected Result
progressPercent: 99.95039682539682,
difficultyChange: -1.4512637555574193,
estimatedRetargetDate: 1683212658129,
remainingBlocks: 1,
remainingTime: 609129,
previousRetarget: 1.7220298879531821,
previousTime: 1681984653,
nextRetargetHeight: 788256,
timeAvg: 609129,
adjustedTimeAvg: 609129,
timeOffset: 0,
expectedBlocks: 2045.66,
},
],
] 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]);
}
});
test('should calculate Difficulty change from bits fields of two blocks', () => {
// Check same exponent + check min max for output
expect(calcBitsDifference(0x1d000200, 0x1d000100)).toEqual(100);
expect(calcBitsDifference(0x1d000400, 0x1d000100)).toEqual(300);
expect(calcBitsDifference(0x1d000800, 0x1d000100)).toEqual(300); // Actually 700
expect(calcBitsDifference(0x1d000100, 0x1d000200)).toEqual(-50);
expect(calcBitsDifference(0x1d000100, 0x1d000400)).toEqual(-75);
expect(calcBitsDifference(0x1d000100, 0x1d000800)).toEqual(-75); // Actually -87.5
// Check new higher exponent
expect(calcBitsDifference(0x1c000200, 0x1d000001)).toEqual(100);
expect(calcBitsDifference(0x1c000400, 0x1d000001)).toEqual(300);
expect(calcBitsDifference(0x1c000800, 0x1d000001)).toEqual(300);
expect(calcBitsDifference(0x1c000100, 0x1d000002)).toEqual(-50);
expect(calcBitsDifference(0x1c000100, 0x1d000004)).toEqual(-75);
expect(calcBitsDifference(0x1c000100, 0x1d000008)).toEqual(-75);
// Check new lower exponent
expect(calcBitsDifference(0x1d000002, 0x1c000100)).toEqual(100);
expect(calcBitsDifference(0x1d000004, 0x1c000100)).toEqual(300);
expect(calcBitsDifference(0x1d000008, 0x1c000100)).toEqual(300);
expect(calcBitsDifference(0x1d000001, 0x1c000200)).toEqual(-50);
expect(calcBitsDifference(0x1d000001, 0x1c000400)).toEqual(-75);
expect(calcBitsDifference(0x1d000001, 0x1c000800)).toEqual(-75);
// Check error when exponents are too far apart
expect(() => calcBitsDifference(0x1d000001, 0x1a000800)).toThrow(
/Impossible exponent difference/
);
// Check invalid inputs
expect(() => calcBitsDifference(0x7f000001, 0x1a000800)).toThrow(
/Invalid bits/
);
expect(() => calcBitsDifference(0, 0x1a000800)).toThrow(/Invalid bits/);
expect(() => calcBitsDifference(100.2783, 0x1a000800)).toThrow(
/Invalid bits/
);
expect(() => calcBitsDifference(0x00800000, 0x1a000800)).toThrow(
/Invalid bits/
);
expect(() => calcBitsDifference(0x1c000000, 0x1a000800)).toThrow(
/Invalid bits/
);
});
});

View File

@@ -0,0 +1,277 @@
[
{
"txid": "13f007241d78e8b0b4e57d2ae3fd37bcfe3226534d7cadeba5a549860d960db0",
"version": 2,
"locktime": 0,
"vin": [
{
"txid": "cb8f206f4e88bec97107089f3e9e61d50cde53d4541992ae19759b71103cf75c",
"vout": 0,
"prevout": {
"scriptpubkey": "0014fd6d15ff832c12f1ff04a5ccd5039f7227b260bd",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 fd6d15ff832c12f1ff04a5ccd5039f7227b260bd",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1ql4k3tlur9sf0rlcy5hxd2qulwgnmyc9akehvth",
"value": 610677
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"304302205c430b36ebd2bb327951d83440af1f58f127871b2baada4c4dde2bc0b6721f56021f3445099f1a40e35baeda32e8e3727b505ffba0d882b11f498c7762f4184e9901",
"0236b5edd4fbbcfb045960e42ec8a9968944084785932e32940e8cd2583b37da67"
],
"is_coinbase": false,
"sequence": 2147483648
}
],
"vout": [
{
"scriptpubkey": "76a9149d32ef812385f3811634e0c0117dd153a5de10a488ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 9d32ef812385f3811634e0c0117dd153a5de10a4 OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1FLC7Bag7okAkKPCyZbgZZg3Hh1EuGZ5Rd",
"value": 344697
},
{
"scriptpubkey": "00147dee8a7a38abbfb00dbfba365c8d6712934cc491",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 7dee8a7a38abbfb00dbfba365c8d6712934cc491",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q0hhg573c4wlmqrdlhgm9ert8z2f5e3y3lf9hvx",
"value": 265396
}
],
"size": 224,
"weight": 572,
"fee": 584,
"status": {
"confirmed": false
},
"order": 2953680397,
"vsize": 143,
"adjustedVsize": 143,
"sigops": 5,
"feePerVsize": 4.083916083916084,
"adjustedFeePerVsize": 4.083916083916084,
"effectiveFeePerVsize": 4.083916083916084,
"firstSeen": 1691222538,
"uid": 526973,
"inputs": [
526728
],
"position": {
"block": 7,
"vsize": 21429708.5
},
"bestDescendant": null,
"cpfpChecked": true
},
{
"txid": "8e89b20f8a7fadb0e4cdbe57a00eee224f5076bac5387fc276916724e7c4a16a",
"version": 2,
"locktime": 800571,
"vin": [
{
"txid": "35e16762459539f3a8e52c5dee6a9ccaa9e9268efed33aa2c6e1b7805e849f24",
"vout": 0,
"prevout": {
"scriptpubkey": "0014d4f16ef275b3e1c4a4ecbef55a164933e0f6460f",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 d4f16ef275b3e1c4a4ecbef55a164933e0f6460f",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q6nckaun4k0suff8vhm6459jfx0s0v3s0ff4ukl",
"value": 1528924
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"3044022019008b26e885bb43da25a11ffac147a057722072eedb68411f114f6e7eb82ebc02201b618264bb97756b88fc3bbc365b73044ac18b33b1067e31cfd5bcd0f50ed2c701",
"039b71145070bd3e8af28e27fa577f2e12ab6bb4e212d3eeaef08b4bc39e8cbc13"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "67c27ed0f767526234bcd5f795a31fab8ec4d0251bf12c68f2746951f4110d90",
"vout": 3,
"prevout": {
"scriptpubkey": "0014a7c3d613b321375054b2ac9b6114367bc034ad6f",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 a7c3d613b321375054b2ac9b6114367bc034ad6f",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q5lpavyanyym4q49j4jdkz9pk00qrftt0yqzvk3",
"value": 436523
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"304402204e67285fc656bc45ed082499b076d5dba2fa21d0d7e64a0ae52b19d69a11760002200f037d81ee540b74397844513b72b08ed92b06db76bd20b08f7a0a3b36ab13d501",
"02a3ebae85f0225b6fbb5ff060afce683a4683507a57544605a29ee7d287e591b4"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "21c38fb9a2521e438c614f53b19ddd7a5594bcc4b77480e762fd4b702fad3374",
"vout": 1,
"prevout": {
"scriptpubkey": "00149660e34ef88106536c816c037b5b28dd64a812e2",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 9660e34ef88106536c816c037b5b28dd64a812e2",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1qjeswxnhcsyr9xmypdsphkkegm4j2syhztgzxv4",
"value": 758149
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"3044022021b556f0aa99329076bcc435338aceaf534963efcab306931b1b2b0461e16e0c02203a78942a3745c4da656bddfd8cf16b85dc04d652904e88682127cdd9ca63339001",
"0298963be4a8f66aca9fcf1c6dc95547aeaa82347543190c91e094c2321142b9f0"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "aa998dbae65240a7386bf7d468459551d99c3de8e2f9057ff5f2d38e17daf788",
"vout": 0,
"prevout": {
"scriptpubkey": "00147bb7413a39943b21ded98ad5e6ad7a222d273e17",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 7bb7413a39943b21ded98ad5e6ad7a222d273e17",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q0wm5zw3ejsajrhke3t27dtt6ygkjw0sh9lltg6",
"value": 1067200
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"304402205e2269f7d4ee0513b34354c38e920aef2dabac6f4350afb2dd105ff3ee43ae7b02202870322f2cb85cb0b2b0e38152f018bfff271dc3ec5aed0515854d0b259aaf3d01",
"03b87320cf3263a644a0d3f89c1b4a7304d9dfda9eb8c891560716abcb73e88b99"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "230253d195d779d4688ba16993985cd27b2e7a687d8b889b3bc63f19ece36f20",
"vout": 0,
"prevout": {
"scriptpubkey": "001439647bd997819d12dfc72b0fb9ff9ffcb84946f8",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 39647bd997819d12dfc72b0fb9ff9ffcb84946f8",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q89j8hkvhsxw39h789v8mnlulljuyj3hc9zve97",
"value": 361950
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"304402204f7ca868bb9b92a07fecdc6b9dd56e4e1d007ca1405952f98ed6bc416345b5f2022055320a97791417abf6628fcf6513ac5785b06c630f854d8595e96ea06c3841d301",
"03a3ffe8e3ef2eea129b227e9658164bae0a6d21c17da6de9973ba34d9e04b21a0"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "670771e265a0b62dbd3c1fec2b865177eaf0bafd0ae49dd40a1c9fcd9a847a81",
"vout": 0,
"prevout": {
"scriptpubkey": "0014d45d1b0022c7387e42c5452ced561bdb8fd4b521",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 d45d1b0022c7387e42c5452ced561bdb8fd4b521",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q63w3kqpzcuu8usk9g5kw64smmw8afdfpxmc2m0",
"value": 453275
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"3044022071312921800441903b2099e723add8702dd0f92ec11526ff87acf6967ec64cbd02203deabe7ed56d5daaa9a95c5a607b1ab705ff1c46bc6984a6dca120e63a91768601",
"0257302ac8d9c4c8f9b1744f19bb432359326b9cc7bdddeeab9202749a6d92be58"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "0af82159eee2b69242f2ff032636e410b67ec1ace52e55fb0d20ed814cd64803",
"vout": 0,
"prevout": {
"scriptpubkey": "001459e4d6bfefc6b45f955a69c4aeca26348e9d54ed",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 59e4d6bfefc6b45f955a69c4aeca26348e9d54ed",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1qt8jdd0l0c669l926d8z2aj3xxj8f648dtyn7tc",
"value": 439961
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"3044022027540322e92c23c5513aa2587e7feb56a8ce82f879269d6b3cbd425634b44f8e022045572dee7262b02130bfe32d8aa8abbfaa64e101abfc819bba5380c78876692d01",
"03fe02262d87f4a5289d3dd66e3d9a74cd49fa1cad0249284a7451896a827249a5"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "68cf9c784870a4f888f044755f7ce318557f652461db8ef887d279672f186018",
"vout": 0,
"prevout": {
"scriptpubkey": "001454822b2d5d52597a78b630921cf439a41e32f2f9",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 54822b2d5d52597a78b630921cf439a41e32f2f9",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q2jpzkt2a2fvh579kxzfpeape5s0r9uhewhl5n4",
"value": 227639
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"304402203ad511d6a8730748b8828bc38897d360451adf620ebdc1d229c08c097c80bef202202f50c793d95b5200cf2258e03896a3be7720df0eb3b8c810c86db74341a7e83e01",
"0294992e9f4546e6e119741f908411ae531e9d1ff732d69b4dff8172aaf2a4b216"
],
"is_coinbase": false,
"sequence": 4294967293
},
{
"txid": "793f01dfdb19bf41f958fd917c16d9c4dd5d5e1a5c0434bfdb367212659d1b5b",
"vout": 0,
"prevout": {
"scriptpubkey": "0014f54edf8ae647b5300e2674523254e923d93d169f",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 f54edf8ae647b5300e2674523254e923d93d169f",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q748dlzhxg76nqr3xw3fry48fy0vn695lvhlkxv",
"value": 227070
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"304402206e807ab616f4f2887ba703ae744d856142d9aca8128698419bbb67fb4fad8177022060fc65c7cd66baa88ad1e1d317a6edd5f6cb52fe8bff6e5405ffa1acf9d945d901",
"02a0ad0167c6e9edf62677404d74d3b80ea276e47e758ffaa6ca17bd65ac79f7aa"
],
"is_coinbase": false,
"sequence": 4294967293
}
],
"vout": [
{
"scriptpubkey": "00148a5c45ccfc29d209940d94525e2edb7743a1ad8a",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 8a5c45ccfc29d209940d94525e2edb7743a1ad8a",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q3fwytn8u98fqn9qdj3f9utkmwap6rtv2ym33zm",
"value": 5500000
}
],
"size": 1375,
"weight": 2605,
"fee": 691,
"status": {
"confirmed": false
},
"order": 1788986599,
"vsize": 651,
"adjustedVsize": 651.25,
"sigops": 9,
"feePerVsize": 1.0610364683301343,
"adjustedFeePerVsize": 1.0610364683301343,
"effectiveFeePerVsize": 1.0610364683301343,
"firstSeen": 1691163298,
"uid": 120494,
"inputs": [],
"position": {
"block": 7,
"vsize": 93780091.5
},
"bestDescendant": null,
"cpfpChecked": true
}
]

View File

@@ -0,0 +1,121 @@
[
{
"txid": "7219d95161f3718335991ac6d967d24eedec370908c9879bb1e192e6d797d0a6",
"version": 1,
"locktime": 0,
"vin": [
{
"txid": "d863deb706de5a611028f7547e16ea81d7819e44beb640fb30a9ba30c585140f",
"vout": 0,
"prevout": {
"scriptpubkey": "76a914cd5b6566b455d043558829f6932edaae5d8f0ad388ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 cd5b6566b455d043558829f6932edaae5d8f0ad3 OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1Kiq1dyVBzYLWGrBPWjChvKyzB2H95x5RJ",
"value": 799995000
},
"scriptsig": "483045022100aeeddfb9785c5a4b70e90d0445785c68b7a44e28853441134a70ddc4da39527602203dfe1ec1a377aaacb64ae65c7c944caf1398d2dc063f712251b4cf696d44d3cb01210314338e3e191aea3ac9e9292611faeedf0379bbe62c30fd76c7450722a1ac47c6",
"scriptsig_asm": "OP_PUSHBYTES_72 3045022100aeeddfb9785c5a4b70e90d0445785c68b7a44e28853441134a70ddc4da39527602203dfe1ec1a377aaacb64ae65c7c944caf1398d2dc063f712251b4cf696d44d3cb01 OP_PUSHBYTES_33 0314338e3e191aea3ac9e9292611faeedf0379bbe62c30fd76c7450722a1ac47c6",
"is_coinbase": false,
"sequence": 4294967293
}
],
"vout": [
{
"scriptpubkey": "6a4c5058325b8669baa9259e082f064005bc92274b559337ac317798f5d76f2d0577ed5a96042fce8c33d841b6c47a99f9597000ab04a10b34cd419fc19784d9e36f1a33fd7b000c3bce00b6000c1d1e00614b",
"scriptpubkey_asm": "OP_RETURN OP_PUSHDATA1 58325b8669baa9259e082f064005bc92274b559337ac317798f5d76f2d0577ed5a96042fce8c33d841b6c47a99f9597000ab04a10b34cd419fc19784d9e36f1a33fd7b000c3bce00b6000c1d1e00614b",
"scriptpubkey_type": "op_return",
"value": 0
},
{
"scriptpubkey": "a9144890aae025c84cb72a9730b49ca12595d6f6088d87",
"scriptpubkey_asm": "OP_HASH160 OP_PUSHBYTES_20 4890aae025c84cb72a9730b49ca12595d6f6088d OP_EQUAL",
"scriptpubkey_type": "p2sh",
"scriptpubkey_address": "38Jht2bzmJL4EwoFvvyFzejhfEb4J7KxLb",
"value": 155000
},
{
"scriptpubkey": "76a91486e7dad6617303942a448b7f8afe9653e5624a5e88ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 86e7dad6617303942a448b7f8afe9653e5624a5e OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1DJKJGApgX4W8BSQ8FRPLqX78UaCskT4r2",
"value": 155000
},
{
"scriptpubkey": "76a914cd5b6566b455d043558829f6932edaae5d8f0ad388ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 cd5b6566b455d043558829f6932edaae5d8f0ad3 OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1Kiq1dyVBzYLWGrBPWjChvKyzB2H95x5RJ",
"value": 799675549
}
],
"size": 350,
"weight": 1400,
"fee": 9451,
"status": {
"confirmed": false
},
"order": 2798688215,
"vsize": 350,
"adjustedVsize": 350,
"sigops": 8,
"feePerVsize": 27.002857142857142,
"adjustedFeePerVsize": 27.002857142857142,
"effectiveFeePerVsize": 27.002857142857142,
"firstSeen": 1691218536,
"uid": 513598,
"inputs": [],
"position": {
"block": 0,
"vsize": 22166
},
"bestDescendant": null,
"cpfpChecked": true
},
{
"txid": "5387881d695d4564d397026dc5f740f816f8390b4b2c5ec8c20309122712a875",
"version": 2,
"locktime": 0,
"vin": [
{
"txid": "b50225a04a1d6fbbfa7a2122bc0580396f614027b3957f476229633576f06130",
"vout": 0,
"prevout": {
"scriptpubkey": "0014a24f913f8a9c30a4c302c2c78f2fd7addb08fd07",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 a24f913f8a9c30a4c302c2c78f2fd7addb08fd07",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q5f8ez0u2nsc2fsczctrc7t7h4hds3lg82ewqhz",
"value": 612917
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"3045022100a0c23953ace5d022b7a6d45d1ae1730bf20a4d594bb5d4fa7aa80e4881b44d320220008f9b144805bb91995fc0f452a56e09f4ad16fa149d71ae9b5d57c742e8e2cc01",
"03dc2c7b687019b40a68d713322675206cc266e34e5340ec982c13ff0222c3b2b6"
],
"is_coinbase": false,
"sequence": 2147483649
}
],
"vout": [
{
"scriptpubkey": "0014199a98f9589364ffe5ef5bbae45ce5dfcbb873bd",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 199a98f9589364ffe5ef5bbae45ce5dfcbb873bd",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1qrxdf372cjdj0le00twawgh89ml9msuaau62gk4",
"value": 611909
}
],
"size": 192,
"weight": 438,
"fee": 1008,
"status": {
"confirmed": false
},
"bestDescendant": null,
"descendants": null,
"adjustedFeePerVsize": 10.2283,
"sigops": 1,
"adjustedVsize": 109.5
}
]

View File

@@ -0,0 +1,139 @@
[
{
"txid": "008592364e21c1e3d62ba9538ac78a81779897b52100af5707ab063df98964f2",
"version": 1,
"locktime": 0,
"vin": [
{
"txid": "d863deb706de5a611028f7547e16ea81d7819e44beb640fb30a9ba30c585140f",
"vout": 0,
"prevout": {
"scriptpubkey": "76a914cd5b6566b455d043558829f6932edaae5d8f0ad388ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 cd5b6566b455d043558829f6932edaae5d8f0ad3 OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1Kiq1dyVBzYLWGrBPWjChvKyzB2H95x5RJ",
"value": 799995000
},
"scriptsig": "483045022100c1fb331d155a7d299a0451d14fa1122b328e0e239afc9ba8dc2aff449ddc5a3a02201c1e19030d1efa432f5069cd369d7ad09a67f68501345e4db35f7b799605f55601210314338e3e191aea3ac9e9292611faeedf0379bbe62c30fd76c7450722a1ac47c6",
"scriptsig_asm": "OP_PUSHBYTES_72 3045022100c1fb331d155a7d299a0451d14fa1122b328e0e239afc9ba8dc2aff449ddc5a3a02201c1e19030d1efa432f5069cd369d7ad09a67f68501345e4db35f7b799605f55601 OP_PUSHBYTES_33 0314338e3e191aea3ac9e9292611faeedf0379bbe62c30fd76c7450722a1ac47c6",
"is_coinbase": false,
"sequence": 4294967293
}
],
"vout": [
{
"scriptpubkey": "6a4c5058325b78064160b631b5a15d9078d99c0db066449fb4c59bbfa4d987ba906e2990088b2fce8c33d841b6c47a99f9597000ab04a10b34cd419fc19784d9e36f1a33fd7b000c3bce00b6000c1d1e00614b",
"scriptpubkey_asm": "OP_RETURN OP_PUSHDATA1 58325b78064160b631b5a15d9078d99c0db066449fb4c59bbfa4d987ba906e2990088b2fce8c33d841b6c47a99f9597000ab04a10b34cd419fc19784d9e36f1a33fd7b000c3bce00b6000c1d1e00614b",
"scriptpubkey_type": "op_return",
"value": 0
},
{
"scriptpubkey": "a9144890aae025c84cb72a9730b49ca12595d6f6088d87",
"scriptpubkey_asm": "OP_HASH160 OP_PUSHBYTES_20 4890aae025c84cb72a9730b49ca12595d6f6088d OP_EQUAL",
"scriptpubkey_type": "p2sh",
"scriptpubkey_address": "38Jht2bzmJL4EwoFvvyFzejhfEb4J7KxLb",
"value": 155000
},
{
"scriptpubkey": "76a91486e7dad6617303942a448b7f8afe9653e5624a5e88ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 86e7dad6617303942a448b7f8afe9653e5624a5e OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1DJKJGApgX4W8BSQ8FRPLqX78UaCskT4r2",
"value": 155000
},
{
"scriptpubkey": "76a914cd5b6566b455d043558829f6932edaae5d8f0ad388ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 cd5b6566b455d043558829f6932edaae5d8f0ad3 OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1Kiq1dyVBzYLWGrBPWjChvKyzB2H95x5RJ",
"value": 799676250
}
],
"size": 350,
"weight": 1400,
"fee": 8750,
"status": {
"confirmed": false
},
"order": 4066675193,
"vsize": 350,
"adjustedVsize": 350,
"sigops": 8,
"feePerVsize": 25,
"adjustedFeePerVsize": 25,
"effectiveFeePerVsize": 25,
"firstSeen": 1691218516,
"uid": 512584,
"inputs": [],
"position": {
"block": 0,
"vsize": 13846
},
"bestDescendant": null,
"cpfpChecked": true
},
{
"txid": "b7981a624e4261c11f1246314d41e74be56af82eb557bcd054a5e0f94c023668",
"version": 2,
"locktime": 0,
"vin": [
{
"txid": "b50225a04a1d6fbbfa7a2122bc0580396f614027b3957f476229633576f06130",
"vout": 0,
"prevout": {
"scriptpubkey": "0014a24f913f8a9c30a4c302c2c78f2fd7addb08fd07",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 a24f913f8a9c30a4c302c2c78f2fd7addb08fd07",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1q5f8ez0u2nsc2fsczctrc7t7h4hds3lg82ewqhz",
"value": 612917
},
"scriptsig": "",
"scriptsig_asm": "",
"witness": [
"304402204dd10f14afa41bc76d8278140ff1ec3d3f87f2c207bbb5418cc76dab30d7f6a402207877cc9c6a2c724b6ea7a1c24ac00022469f194fd1a4bd8030bbca1787d3f5f301",
"03dc2c7b687019b40a68d713322675206cc266e34e5340ec982c13ff0222c3b2b6"
],
"is_coinbase": false,
"sequence": 2147483648
}
],
"vout": [
{
"scriptpubkey": "76a9149d32ef812385f3811634e0c0117dd153a5de10a488ac",
"scriptpubkey_asm": "OP_DUP OP_HASH160 OP_PUSHBYTES_20 9d32ef812385f3811634e0c0117dd153a5de10a4 OP_EQUALVERIFY OP_CHECKSIG",
"scriptpubkey_type": "p2pkh",
"scriptpubkey_address": "1FLC7Bag7okAkKPCyZbgZZg3Hh1EuGZ5Rd",
"value": 344697
},
{
"scriptpubkey": "00144c2671336ca8761863b4c68d64d4672491fec1b9",
"scriptpubkey_asm": "OP_0 OP_PUSHBYTES_20 4c2671336ca8761863b4c68d64d4672491fec1b9",
"scriptpubkey_type": "v0_p2wpkh",
"scriptpubkey_address": "bc1qfsn8zvmv4pmpsca5c6xkf4r8yjglasdesrawcx",
"value": 267636
}
],
"size": 225,
"weight": 573,
"fee": 584,
"status": {
"confirmed": false
},
"order": 1748369996,
"vsize": 143,
"adjustedVsize": 143.25,
"sigops": 5,
"feePerVsize": 4.076788830715532,
"adjustedFeePerVsize": 4.076788830715532,
"effectiveFeePerVsize": 4.076788830715532,
"firstSeen": 1691222376,
"uid": 526515,
"inputs": [],
"position": {
"block": 7,
"vsize": 22021095.5
},
"bestDescendant": null,
"cpfpChecked": true
}
]

View File

@@ -14,15 +14,18 @@ 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/',
AUTOMATIC_BLOCK_REINDEXING: false,
POLL_RATE_MS: 2000,
CACHE_DIR: './cache',
CACHE_ENABLED: true,
CLEAR_PROTECTION_MINUTES: 20,
RECOMMENDED_FEE_PERCENTILE: 50,
BLOCK_WEIGHT_UNITS: 4000000,
@@ -38,23 +41,37 @@ describe('Mempool Backend Config', () => {
POOLS_JSON_TREE_URL: 'https://api.github.com/repos/mempool/mining-pools/git/trees/master',
POOLS_JSON_URL: 'https://raw.githubusercontent.com/mempool/mining-pools/master/pools-v2.json',
AUDIT: false,
ADVANCED_GBT_AUDIT: false,
ADVANCED_GBT_MEMPOOL: false,
RUST_GBT: false,
LIMIT_GBT: false,
CPFP_INDEXING: false,
MAX_BLOCKS_BULK_QUERY: 0,
DISK_CACHE_BLOCK_INTERVAL: 6,
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 });
expect(config.ESPLORA).toStrictEqual({ REST_API_URL: 'http://127.0.0.1:3000' });
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: [],
});
expect(config.CORE_RPC).toStrictEqual({
HOST: '127.0.0.1',
PORT: 8332,
USERNAME: 'mempool',
PASSWORD: 'mempool',
TIMEOUT: 60000
TIMEOUT: 60000,
COOKIE: false,
COOKIE_PATH: '/bitcoin/.cookie'
});
expect(config.SECOND_CORE_RPC).toStrictEqual({
@@ -62,7 +79,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({
@@ -72,7 +91,10 @@ describe('Mempool Backend Config', () => {
PORT: 3306,
DATABASE: 'mempool',
USERNAME: 'mempool',
PASSWORD: 'mempool'
PASSWORD: 'mempool',
TIMEOUT: 180000,
PID_DIR: '',
POOL_SIZE: 100,
});
expect(config.SYSLOG).toStrictEqual({
@@ -85,8 +107,6 @@ describe('Mempool Backend Config', () => {
expect(config.STATISTICS).toStrictEqual({ ENABLED: true, TX_PER_SECOND_SAMPLE_PERIOD: 150 });
expect(config.BISQ).toStrictEqual({ ENABLED: false, DATA_PATH: '/bisq/statsnode-data/btc_mainnet/db' });
expect(config.SOCKS5PROXY).toStrictEqual({
ENABLED: false,
USE_ONION: true,
@@ -96,18 +116,11 @@ describe('Mempool Backend Config', () => {
PASSWORD: ''
});
expect(config.PRICE_DATA_SERVER).toStrictEqual({
TOR_URL: 'http://wizpriceje6q5tdrxkyiazsgu7irquiqjy2dptezqhrtu7l2qelqktid.onion/getAllMarketPrices',
CLEARNET_URL: 'https://price.bisq.wiz.biz/getAllMarketPrices'
});
expect(config.EXTERNAL_DATA_SERVER).toStrictEqual({
MEMPOOL_API: 'https://mempool.space/api/v1',
MEMPOOL_ONION: 'http://mempoolhqx4isw62xs7abwphsq7ldayuidyx2v2oethdhhj6mlo2r6ad.onion/api/v1',
LIQUID_API: 'https://liquid.network/api/v1',
LIQUID_ONION: 'http://liquidmom47f6s3m53ebfxn47p76a6tlnxib3wp6deux7wuzotdr6cyd.onion/api/v1',
BISQ_URL: 'https://bisq.markets/api',
BISQ_ONION: 'http://bisqmktse2cabavbr2xjq7xw3h6g5ottemo5rolfcwt6aly6tp5fdryd.onion/api'
LIQUID_ONION: 'http://liquidmom47f6s3m53ebfxn47p76a6tlnxib3wp6deux7wuzotdr6cyd.onion/api/v1'
});
expect(config.MAXMIND).toStrictEqual({
@@ -116,6 +129,29 @@ describe('Mempool Backend Config', () => {
GEOLITE2_ASN: '/usr/local/share/GeoIP/GeoLite2-ASN.mmdb',
GEOIP2_ISP: '/usr/local/share/GeoIP/GeoIP2-ISP.mmdb'
});
expect(config.REPLICATION).toStrictEqual({
ENABLED: false,
AUDIT: false,
AUDIT_START_HEIGHT: 774000,
SERVERS: []
});
expect(config.MEMPOOL_SERVICES).toStrictEqual({
API: "",
ACCELERATIONS: false,
});
expect(config.REDIS).toStrictEqual({
ENABLED: false,
UNIX_SOCKET_PATH: '',
BATCH_QUERY_BASE_SIZE: 5000,
});
expect(config.FIAT_PRICE).toStrictEqual({
ENABLED: true,
API_KEY: '',
});
});
});
@@ -142,13 +178,112 @@ describe('Mempool Backend Config', () => {
expect(config.STATISTICS).toStrictEqual(fixture.STATISTICS);
expect(config.BISQ).toStrictEqual(fixture.BISQ);
expect(config.SOCKS5PROXY).toStrictEqual(fixture.SOCKS5PROXY);
expect(config.PRICE_DATA_SERVER).toStrictEqual(fixture.PRICE_DATA_SERVER);
expect(config.EXTERNAL_DATA_SERVER).toStrictEqual(fixture.EXTERNAL_DATA_SERVER);
expect(config.MEMPOOL_SERVICES).toStrictEqual(fixture.MEMPOOL_SERVICES);
expect(config.REDIS).toStrictEqual(fixture.REDIS);
});
});
test('should ensure the docker start.sh script has default values', () => {
jest.isolateModules(() => {
const startSh = fs.readFileSync(`${__dirname}/../../../docker/backend/start.sh`, 'utf-8');
const fixture = JSON.parse(fs.readFileSync(`${__dirname}/../__fixtures__/mempool-config.template.json`, 'utf8'));
function parseJson(jsonObj, root?) {
for (const [key, value] of Object.entries(jsonObj)) {
// We have a few cases where we can't follow the pattern
if (root === 'MEMPOOL' && key === 'HTTP_PORT') {
if (process.env.CI) {
console.log('skipping check for MEMPOOL_HTTP_PORT');
}
continue;
}
if (root) {
//The flattened string, i.e, __MEMPOOL_ENABLED__
const replaceStr = `${root ? '__' + root + '_' : '__'}${key}__`;
//The string used as the environment variable, i.e, MEMPOOL_ENABLED
const envVarStr = `${root ? root : ''}_${key}`;
let defaultEntry;
//The string used as the default value, to be checked as a regex, i.e, __MEMPOOL_ENABLED__=${MEMPOOL_ENABLED:=(.*)}
if (Array.isArray(value)) {
defaultEntry = `${replaceStr}=\${${envVarStr}:=[]}`;
if (process.env.CI) {
console.log(`looking for ${defaultEntry} in the start.sh script`);
}
//Regex matching does not work with the array values
expect(startSh).toContain(defaultEntry);
} else {
defaultEntry = replaceStr + '=' + '\\${' + envVarStr + ':=(.*)' + '}';
if (process.env.CI) {
console.log(`looking for ${defaultEntry} in the start.sh script`);
}
const re = new RegExp(defaultEntry);
expect(startSh).toMatch(re);
}
//The string that actually replaces the values in the config file
const sedStr = 'sed -i "s!' + replaceStr + '!${' + replaceStr + '}!g" mempool-config.json';
if (process.env.CI) {
console.log(`looking for ${sedStr} in the start.sh script`);
}
expect(startSh).toContain(sedStr);
}
else {
parseJson(value, key);
}
}
}
parseJson(fixture);
});
});
test('should ensure that the mempool-config.json Docker template has all the keys', () => {
jest.isolateModules(() => {
const fixture = JSON.parse(fs.readFileSync(`${__dirname}/../__fixtures__/mempool-config.template.json`, 'utf8'));
const dockerJson = fs.readFileSync(`${__dirname}/../../../docker/backend/mempool-config.json`, 'utf-8');
function parseJson(jsonObj, root?) {
for (const [key, value] of Object.entries(jsonObj)) {
switch (typeof value) {
case 'object': {
if (Array.isArray(value)) {
// numbers, arrays and booleans won't be enclosed by quotes
const replaceStr = `${root ? '__' + root + '_' : '__'}${key}__`;
expect(dockerJson).toContain(`"${key}": ${replaceStr}`);
break;
} else {
//Check for top level config keys
expect(dockerJson).toContain(`"${key}"`);
parseJson(value, key);
break;
}
}
case 'string': {
// strings should be enclosed by quotes
const replaceStr = `${root ? '__' + root + '_' : '__'}${key}__`;
expect(dockerJson).toContain(`"${key}": "${replaceStr}"`);
break;
}
default: {
// numbers, arrays and booleans won't be enclosed by quotes
const replaceStr = `${root ? '__' + root + '_' : '__'}${key}__`;
expect(dockerJson).toContain(`"${key}": ${replaceStr}`);
break;
}
}
};
}
parseJson(fixture);
});
});
});

View File

@@ -0,0 +1,68 @@
import fs from 'fs';
import { GbtGenerator, ThreadTransaction } from 'rust-gbt';
import path from 'path';
const baseline = require('./test-data/target-template.json');
const testVector = require('./test-data/test-data-ids.json');
const vectorUidMap: Map<number, string> = new Map(testVector.map(x => [x[0], x[1]]));
const vectorTxidMap: Map<string, number> = new Map(testVector.map(x => [x[1], x[0]]));
// Note that this test buffer is specially constructed
// such that uids are assigned in numerical txid order
// so that ties break the same way as in Core's implementation
const vectorBuffer: Buffer = fs.readFileSync(path.join(__dirname, './', './test-data/test-buffer.bin'));
describe('Rust GBT', () => {
test('should produce the same template as getBlockTemplate from Bitcoin Core', async () => {
const rustGbt = new GbtGenerator();
const { mempool, maxUid } = mempoolFromArrayBuffer(vectorBuffer.buffer);
const result = await rustGbt.make(mempool, [], maxUid);
const blocks: [string, number][][] = result.blocks.map(block => {
return block.map(uid => [vectorUidMap.get(uid) || 'missing', uid]);
});
const template = baseline.map(tx => [tx.txid, vectorTxidMap.get(tx.txid)]);
expect(blocks[0].length).toEqual(baseline.length);
expect(blocks[0]).toEqual(template);
});
});
function mempoolFromArrayBuffer(buf: ArrayBuffer): { mempool: ThreadTransaction[], maxUid: number } {
let maxUid = 0;
const view = new DataView(buf);
const count = view.getUint32(0, false);
const txs: ThreadTransaction[] = [];
let offset = 4;
for (let i = 0; i < count; i++) {
const uid = view.getUint32(offset, false);
maxUid = Math.max(maxUid, uid);
const tx: ThreadTransaction = {
uid,
order: txidToOrdering(vectorUidMap.get(uid) as string),
fee: view.getFloat64(offset + 4, false),
weight: view.getUint32(offset + 12, false),
sigops: view.getUint32(offset + 16, false),
// feePerVsize: view.getFloat64(offset + 20, false),
effectiveFeePerVsize: view.getFloat64(offset + 28, false),
inputs: [],
};
const numInputs = view.getUint32(offset + 36, false);
offset += 40;
for (let j = 0; j < numInputs; j++) {
tx.inputs.push(view.getUint32(offset, false));
offset += 4;
}
txs.push(tx);
}
return { mempool: txs, maxUid };
}
function txidToOrdering(txid: string): number {
return parseInt(
txid.substr(62, 2) +
txid.substr(60, 2) +
txid.substr(58, 2) +
txid.substr(56, 2),
16
);
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@@ -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; // in sats
};
depends: string[];
spentby: string[];
}
interface MempoolTx extends GraphTx {
ancestorcount: number;
ancestorsize: number;
fees: { // in sats
base: number;
ancestor: number;
};
ancestors: Map<string, MempoolTx>,
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 = 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<string, GraphTx> {
const blockTxs = new Map<string, MempoolTransactionExtended>(); // map of txs in this block
const spendMap = new Map<string, string>(); // 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<string, GraphTx> = 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: Math.ceil(tx.weight / 4),
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: Math.ceil(tx.weight / 4),
ancestors: new Map<string, MempoolTx>(),
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<string, MempoolTx>, 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<string, MempoolTx> | 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<string, MempoolTx>(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 = tx.fees.ancestor;
// 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;
});
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<string, MempoolTx>, visited: Map<string, Map<string, MempoolTx>>, depth: number = 0): Map<string, MempoolTx> {
// 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<string, MempoolTx>();
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<string, GraphTx>): Map<string, MempoolTx> {
const mempoolTxs = new Map<string, MempoolTx>();
all.forEach(entry => {
mempoolTxs.set(entry.txid, this.convertGraphToMempoolTx(entry));
});
const visited: Map<string, Map<string, MempoolTx>> = 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<string, MempoolTx>, all: Map<string, MempoolTx>): 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 / tx.vsize;
tx.ancestorRate = tx.fees.ancestor / 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<string, MinerTransaction>;
children: Set<MinerTransaction>;
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)
*/
export function makeBlockTemplate(candidates: IEsploraApi.Transaction[], accelerations: Acceleration[], maxBlocks: number = 8, weightLimit: number = BLOCK_WEIGHT_UNITS, sigopLimit: number = BLOCK_SIGOPS): TemplateTransaction[] {
const auditPool: Map<string, MinerTransaction> = 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<string, MinerTransaction>(),
children: new Set<MinerTransaction>(),
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<string, MinerTransaction>,
): 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<string, MinerTransaction>,
modified: MinerTransaction[],
clusterRate: number,
): MinerTransaction[] {
const descendantSet: Set<MinerTransaction> = 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
);
}

View File

@@ -1,18 +1,23 @@
import config from '../config';
import { TransactionExtended, MempoolBlockWithTransactions } from '../mempool.interfaces';
import logger from '../logger';
import { MempoolTransactionExtended, MempoolBlockWithTransactions } from '../mempool.interfaces';
import rbfCache from './rbf-cache';
const PROPAGATION_MARGIN = 180; // in seconds, time since a transaction is first seen after which it is assumed to have propagated to all miners
class Audit {
auditBlock(transactions: TransactionExtended[], projectedBlocks: MempoolBlockWithTransactions[], mempool: { [txId: string]: TransactionExtended })
: { censored: string[], added: string[], fresh: string[], score: number, similarity: number } {
auditBlock(transactions: MempoolTransactionExtended[], projectedBlocks: MempoolBlockWithTransactions[], mempool: { [txId: string]: MempoolTransactionExtended }, useAccelerations: boolean = false)
: { censored: string[], added: string[], prioritized: string[], fresh: string[], sigop: string[], fullrbf: string[], accelerated: string[], score: number, similarity: number } {
if (!projectedBlocks?.[0]?.transactionIds || !mempool) {
return { censored: [], added: [], fresh: [], score: 0, similarity: 1 };
return { censored: [], added: [], prioritized: [], fresh: [], sigop: [], fullrbf: [], accelerated: [], score: 1, similarity: 1 };
}
const matches: string[] = []; // present in both mined block and template
const added: string[] = []; // present in mined block, not in template
const fresh: string[] = []; // missing, but firstSeen within PROPAGATION_MARGIN
const prioritized: string[] = [] // present in the mined block, not in the template, but further down in the mempool
const fresh: string[] = []; // missing, but firstSeen or lastBoosted within PROPAGATION_MARGIN
const rbf: string[] = []; // either missing or present, and either part of a full-rbf replacement, or a conflict with the mined block
const accelerated: string[] = []; // prioritized by the mempool accelerator
const isCensored = {}; // missing, without excuse
const isDisplaced = {};
let displacedWeight = 0;
@@ -25,6 +30,9 @@ class Audit {
const now = Math.round((Date.now() / 1000));
for (const tx of transactions) {
inBlock[tx.txid] = tx;
if (mempool[tx.txid] && mempool[tx.txid].acceleration) {
accelerated.push(tx.txid);
}
}
// coinbase is always expected
if (transactions[0]) {
@@ -33,45 +41,65 @@ class Audit {
// look for transactions that were expected in the template, but missing from the mined block
for (const txid of projectedBlocks[0].transactionIds) {
if (!inBlock[txid]) {
// tx is recent, may have reached the miner too late for inclusion
if (mempool[txid]?.firstSeen != null && (now - (mempool[txid]?.firstSeen || 0)) <= PROPAGATION_MARGIN) {
// allow missing transactions which either belong to a full rbf tree, or conflict with any transaction in the mined block
if (rbfCache.has(txid) && (rbfCache.isFullRbf(txid) || rbfCache.anyInSameTree(txid, (tx) => inBlock[tx.txid]))) {
rbf.push(txid);
} else if (mempool[txid]?.firstSeen != null && (now - (mempool[txid]?.firstSeen || 0)) <= PROPAGATION_MARGIN) {
// tx is recent, may have reached the miner too late for inclusion
fresh.push(txid);
} else if (mempool[txid]?.lastBoosted != null && (now - (mempool[txid]?.lastBoosted || 0)) <= PROPAGATION_MARGIN) {
// tx was recently cpfp'd, miner may not have the latest effective rate
fresh.push(txid);
} else {
isCensored[txid] = true;
}
displacedWeight += mempool[txid].weight;
displacedWeight += mempool[txid]?.weight || 0;
} else {
matchedWeight += mempool[txid].weight;
matchedWeight += mempool[txid]?.weight || 0;
}
projectedWeight += mempool[txid].weight;
projectedWeight += mempool[txid]?.weight || 0;
inTemplate[txid] = true;
}
displacedWeight += (4000 - transactions[0].weight);
projectedWeight += transactions[0].weight;
matchedWeight += transactions[0].weight;
if (transactions[0]) {
displacedWeight += (4000 - transactions[0].weight);
projectedWeight += transactions[0].weight;
matchedWeight += transactions[0].weight;
}
// we can expect an honest miner to include 'displaced' transactions in place of recent arrivals and censored txs
// these displaced transactions should occupy the first N weight units of the next projected block
let displacedWeightRemaining = displacedWeight;
let displacedWeightRemaining = displacedWeight + 4000;
let index = 0;
let lastFeeRate = Infinity;
let failures = 0;
while (projectedBlocks[1] && index < projectedBlocks[1].transactionIds.length && failures < 500) {
const txid = projectedBlocks[1].transactionIds[index];
const fits = (mempool[txid].weight - displacedWeightRemaining) < 4000;
const feeMatches = mempool[txid].effectiveFeePerVsize >= lastFeeRate;
if (fits || feeMatches) {
isDisplaced[txid] = true;
if (fits) {
lastFeeRate = Math.min(lastFeeRate, mempool[txid].effectiveFeePerVsize);
let blockIndex = 1;
while (projectedBlocks[blockIndex] && failures < 500) {
if (index >= projectedBlocks[blockIndex].transactionIds.length) {
index = 0;
blockIndex++;
}
const txid = projectedBlocks[blockIndex].transactionIds[index];
const tx = mempool[txid];
if (tx) {
const fits = (tx.weight - displacedWeightRemaining) < 4000;
// 0.005 margin of error for any remaining vsize rounding issues
const feeMatches = tx.effectiveFeePerVsize >= (lastFeeRate - 0.005);
if (fits || feeMatches) {
isDisplaced[txid] = true;
if (fits) {
// (tx.effectiveFeePerVsize * tx.vsize) / Math.ceil(tx.vsize) attempts to correct for vsize rounding in the simple non-CPFP case
lastFeeRate = Math.min(lastFeeRate, (tx.effectiveFeePerVsize * tx.vsize) / Math.ceil(tx.vsize));
}
if (tx.firstSeen == null || (now - (tx?.firstSeen || 0)) > PROPAGATION_MARGIN) {
displacedWeightRemaining -= tx.weight;
}
failures = 0;
} else {
failures++;
}
if (mempool[txid].firstSeen == null || (now - (mempool[txid]?.firstSeen || 0)) > PROPAGATION_MARGIN) {
displacedWeightRemaining -= mempool[txid].weight;
}
failures = 0;
} else {
failures++;
logger.warn('projected transaction missing from mempool cache');
}
index++;
}
@@ -83,19 +111,15 @@ class Audit {
if (inTemplate[tx.txid]) {
matches.push(tx.txid);
} else {
if (!isDisplaced[tx.txid]) {
added.push(tx.txid);
} else {
}
let blockIndex = -1;
let index = -1;
projectedBlocks.forEach((block, bi) => {
const i = block.transactionIds.indexOf(tx.txid);
if (i >= 0) {
blockIndex = bi;
index = i;
if (rbfCache.has(tx.txid)) {
rbf.push(tx.txid);
} else if (!isDisplaced[tx.txid]) {
if (mempool[tx.txid]) {
prioritized.push(tx.txid);
} else {
added.push(tx.txid);
}
});
}
overflowWeight += tx.weight;
}
totalWeight += tx.weight;
@@ -108,32 +132,46 @@ class Audit {
index = projectedBlocks[0].transactionIds.length - 1;
while (index >= 0) {
const txid = projectedBlocks[0].transactionIds[index];
if (overflowWeightRemaining > 0) {
if (isCensored[txid]) {
delete isCensored[txid];
}
if (mempool[txid].effectiveFeePerVsize > maxOverflowRate) {
maxOverflowRate = mempool[txid].effectiveFeePerVsize;
rateThreshold = (Math.ceil(maxOverflowRate * 100) / 100) + 0.005;
}
} else if (mempool[txid].effectiveFeePerVsize <= rateThreshold) { // tolerance of 0.01 sat/vb + rounding
if (isCensored[txid]) {
delete isCensored[txid];
const tx = mempool[txid];
if (tx) {
if (overflowWeightRemaining > 0) {
if (isCensored[txid]) {
delete isCensored[txid];
}
if (tx.effectiveFeePerVsize > maxOverflowRate) {
maxOverflowRate = tx.effectiveFeePerVsize;
rateThreshold = (Math.ceil(maxOverflowRate * 100) / 100) + 0.005;
}
} else if (tx.effectiveFeePerVsize <= rateThreshold) { // tolerance of 0.01 sat/vb + rounding
if (isCensored[txid]) {
delete isCensored[txid];
}
}
overflowWeightRemaining -= (mempool[txid]?.weight || 0);
} else {
logger.warn('projected transaction missing from mempool cache');
}
overflowWeightRemaining -= (mempool[txid]?.weight || 0);
index--;
}
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 {
censored: Object.keys(isCensored),
added,
prioritized,
fresh,
sigop: [],
fullrbf: rbf,
accelerated,
score,
similarity,
};

View File

@@ -9,8 +9,8 @@ class BackendInfo {
constructor() {
// This file is created by ./fetch-version.ts during building
const versionFile = path.join(__dirname, 'version.json')
var versionInfo;
const versionFile = path.join(__dirname, 'version.json');
let versionInfo;
if (fs.existsSync(versionFile)) {
versionInfo = JSON.parse(fs.readFileSync(versionFile).toString());
} else {
@@ -24,7 +24,8 @@ class BackendInfo {
hostname: os.hostname(),
version: versionInfo.version,
gitCommit: versionInfo.gitCommit,
lightning: config.LIGHTNING.ENABLED
lightning: config.LIGHTNING.ENABLED,
backend: config.MEMPOOL.BACKEND,
};
}
@@ -32,7 +33,7 @@ class BackendInfo {
return this.backendInfo;
}
public getShortCommitHash() {
public getShortCommitHash(): string {
return this.backendInfo.gitCommit.slice(0, 7);
}
}

View File

@@ -1,381 +0,0 @@
import { Application, Request, Response } from 'express';
import config from '../../config';
import { RequiredSpec } from '../../mempool.interfaces';
import bisq from './bisq';
import { MarketsApiError } from './interfaces';
import marketsApi from './markets-api';
class BisqRoutes {
public initRoutes(app: Application) {
app
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/stats', this.getBisqStats)
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/tx/:txId', this.getBisqTransaction)
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/block/:hash', this.getBisqBlock)
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/blocks/tip/height', this.getBisqTip)
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/blocks/:index/:length', this.getBisqBlocks)
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/address/:address', this.getBisqAddress)
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/txs/:index/:length', this.getBisqTransactions)
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/currencies', this.getBisqMarketCurrencies.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/depth', this.getBisqMarketDepth.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/hloc', this.getBisqMarketHloc.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/markets', this.getBisqMarketMarkets.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/offers', this.getBisqMarketOffers.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/ticker', this.getBisqMarketTicker.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/trades', this.getBisqMarketTrades.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/volumes', this.getBisqMarketVolumes.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'bisq/markets/volumes/7d', this.getBisqMarketVolumes7d.bind(this))
;
}
private getBisqStats(req: Request, res: Response) {
const result = bisq.getStats();
res.json(result);
}
private getBisqTip(req: Request, res: Response) {
const result = bisq.getLatestBlockHeight();
res.type('text/plain');
res.send(result.toString());
}
private getBisqTransaction(req: Request, res: Response) {
const result = bisq.getTransaction(req.params.txId);
if (result) {
res.json(result);
} else {
res.status(404).send('Bisq transaction not found');
}
}
private getBisqTransactions(req: Request, res: Response) {
const types: string[] = [];
req.query.types = req.query.types || [];
if (!Array.isArray(req.query.types)) {
res.status(500).send('Types is not an array');
return;
}
for (const _type in req.query.types) {
if (typeof req.query.types[_type] === 'string') {
types.push(req.query.types[_type].toString());
}
}
const index = parseInt(req.params.index, 10) || 0;
const length = parseInt(req.params.length, 10) > 100 ? 100 : parseInt(req.params.length, 10) || 25;
const [transactions, count] = bisq.getTransactions(index, length, types);
res.header('X-Total-Count', count.toString());
res.json(transactions);
}
private getBisqBlock(req: Request, res: Response) {
const result = bisq.getBlock(req.params.hash);
if (result) {
res.json(result);
} else {
res.status(404).send('Bisq block not found');
}
}
private getBisqBlocks(req: Request, res: Response) {
const index = parseInt(req.params.index, 10) || 0;
const length = parseInt(req.params.length, 10) > 100 ? 100 : parseInt(req.params.length, 10) || 25;
const [transactions, count] = bisq.getBlocks(index, length);
res.header('X-Total-Count', count.toString());
res.json(transactions);
}
private getBisqAddress(req: Request, res: Response) {
const result = bisq.getAddress(req.params.address.substr(1));
if (result) {
res.json(result);
} else {
res.status(404).send('Bisq address not found');
}
}
private getBisqMarketCurrencies(req: Request, res: Response) {
const constraints: RequiredSpec = {
'type': {
required: false,
types: ['crypto', 'fiat', 'all']
},
};
const p = this.parseRequestParameters(req.query, constraints);
if (p.error) {
res.status(400).json(this.getBisqMarketErrorResponse(p.error));
return;
}
const result = marketsApi.getCurrencies(p.type);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketCurrencies error'));
}
}
private getBisqMarketDepth(req: Request, res: Response) {
const constraints: RequiredSpec = {
'market': {
required: true,
types: ['@string']
},
};
const p = this.parseRequestParameters(req.query, constraints);
if (p.error) {
res.status(400).json(this.getBisqMarketErrorResponse(p.error));
return;
}
const result = marketsApi.getDepth(p.market);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketDepth error'));
}
}
private getBisqMarketMarkets(req: Request, res: Response) {
const result = marketsApi.getMarkets();
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketMarkets error'));
}
}
private getBisqMarketTrades(req: Request, res: Response) {
const constraints: RequiredSpec = {
'market': {
required: true,
types: ['@string']
},
'timestamp_from': {
required: false,
types: ['@number']
},
'timestamp_to': {
required: false,
types: ['@number']
},
'trade_id_to': {
required: false,
types: ['@string']
},
'trade_id_from': {
required: false,
types: ['@string']
},
'direction': {
required: false,
types: ['buy', 'sell']
},
'limit': {
required: false,
types: ['@number']
},
'sort': {
required: false,
types: ['asc', 'desc']
}
};
const p = this.parseRequestParameters(req.query, constraints);
if (p.error) {
res.status(400).json(this.getBisqMarketErrorResponse(p.error));
return;
}
const result = marketsApi.getTrades(p.market, p.timestamp_from,
p.timestamp_to, p.trade_id_from, p.trade_id_to, p.direction, p.limit, p.sort);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketTrades error'));
}
}
private getBisqMarketOffers(req: Request, res: Response) {
const constraints: RequiredSpec = {
'market': {
required: true,
types: ['@string']
},
'direction': {
required: false,
types: ['buy', 'sell']
},
};
const p = this.parseRequestParameters(req.query, constraints);
if (p.error) {
res.status(400).json(this.getBisqMarketErrorResponse(p.error));
return;
}
const result = marketsApi.getOffers(p.market, p.direction);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketOffers error'));
}
}
private getBisqMarketVolumes(req: Request, res: Response) {
const constraints: RequiredSpec = {
'market': {
required: false,
types: ['@string']
},
'interval': {
required: false,
types: ['minute', 'half_hour', 'hour', 'half_day', 'day', 'week', 'month', 'year', 'auto']
},
'timestamp_from': {
required: false,
types: ['@number']
},
'timestamp_to': {
required: false,
types: ['@number']
},
'milliseconds': {
required: false,
types: ['@boolean']
},
'timestamp': {
required: false,
types: ['no', 'yes']
},
};
const p = this.parseRequestParameters(req.query, constraints);
if (p.error) {
res.status(400).json(this.getBisqMarketErrorResponse(p.error));
return;
}
const result = marketsApi.getVolumes(p.market, p.timestamp_from, p.timestamp_to, p.interval, p.milliseconds, p.timestamp);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketVolumes error'));
}
}
private getBisqMarketHloc(req: Request, res: Response) {
const constraints: RequiredSpec = {
'market': {
required: true,
types: ['@string']
},
'interval': {
required: false,
types: ['minute', 'half_hour', 'hour', 'half_day', 'day', 'week', 'month', 'year', 'auto']
},
'timestamp_from': {
required: false,
types: ['@number']
},
'timestamp_to': {
required: false,
types: ['@number']
},
'milliseconds': {
required: false,
types: ['@boolean']
},
'timestamp': {
required: false,
types: ['no', 'yes']
},
};
const p = this.parseRequestParameters(req.query, constraints);
if (p.error) {
res.status(400).json(this.getBisqMarketErrorResponse(p.error));
return;
}
const result = marketsApi.getHloc(p.market, p.interval, p.timestamp_from, p.timestamp_to, p.milliseconds, p.timestamp);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketHloc error'));
}
}
private getBisqMarketTicker(req: Request, res: Response) {
const constraints: RequiredSpec = {
'market': {
required: false,
types: ['@string']
},
};
const p = this.parseRequestParameters(req.query, constraints);
if (p.error) {
res.status(400).json(this.getBisqMarketErrorResponse(p.error));
return;
}
const result = marketsApi.getTicker(p.market);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketTicker error'));
}
}
private getBisqMarketVolumes7d(req: Request, res: Response) {
const result = marketsApi.getVolumesByTime(604800);
if (result) {
res.json(result);
} else {
res.status(500).json(this.getBisqMarketErrorResponse('getBisqMarketVolumes7d error'));
}
}
private parseRequestParameters(requestParams: object, params: RequiredSpec): { [name: string]: any; } {
const final = {};
for (const i in params) {
if (params.hasOwnProperty(i)) {
if (params[i].required && requestParams[i] === undefined) {
return { error: i + ' parameter missing'};
}
if (typeof requestParams[i] === 'string') {
const str = (requestParams[i] || '').toString().toLowerCase();
if (params[i].types.indexOf('@number') > -1) {
const number = parseInt((str).toString(), 10);
final[i] = number;
} else if (params[i].types.indexOf('@string') > -1) {
final[i] = str;
} else if (params[i].types.indexOf('@boolean') > -1) {
final[i] = str === 'true' || str === 'yes';
} else if (params[i].types.indexOf(str) > -1) {
final[i] = str;
} else {
return { error: i + ' parameter invalid'};
}
} else if (typeof requestParams[i] === 'number') {
final[i] = requestParams[i];
}
}
}
return final;
}
private getBisqMarketErrorResponse(message: string): MarketsApiError {
return {
'success': 0,
'error': message
};
}
}
export default new BisqRoutes;

View File

@@ -1,364 +0,0 @@
import config from '../../config';
import * as fs from 'fs';
import axios, { AxiosResponse } from 'axios';
import * as http from 'http';
import * as https from 'https';
import { SocksProxyAgent } from 'socks-proxy-agent';
import { BisqBlocks, BisqBlock, BisqTransaction, BisqStats, BisqTrade } from './interfaces';
import { Common } from '../common';
import { BlockExtended } from '../../mempool.interfaces';
import { StaticPool } from 'node-worker-threads-pool';
import backendInfo from '../backend-info';
import logger from '../../logger';
class Bisq {
private static BLOCKS_JSON_FILE_PATH = config.BISQ.DATA_PATH + '/json/all/blocks.json';
private latestBlockHeight = 0;
private blocks: BisqBlock[] = [];
private allBlocks: BisqBlock[] = [];
private transactions: BisqTransaction[] = [];
private transactionIndex: { [txId: string]: BisqTransaction } = {};
private blockIndex: { [hash: string]: BisqBlock } = {};
private addressIndex: { [address: string]: BisqTransaction[] } = {};
private stats: BisqStats = {
minted: 0,
burnt: 0,
addresses: 0,
unspent_txos: 0,
spent_txos: 0,
};
private price: number = 0;
private priceUpdateCallbackFunction: ((price: number) => void) | undefined;
private topDirectoryWatcher: fs.FSWatcher | undefined;
private subdirectoryWatcher: fs.FSWatcher | undefined;
private jsonParsePool = new StaticPool({
size: 4,
task: (blob: string) => JSON.parse(blob),
});
constructor() {}
startBisqService(): void {
try {
this.checkForBisqDataFolder();
} catch (e) {
logger.info('Retrying to start bisq service in 3 minutes');
setTimeout(this.startBisqService.bind(this), 180000);
return;
}
this.loadBisqDumpFile();
setInterval(this.updatePrice.bind(this), 1000 * 60 * 60);
this.updatePrice();
this.startTopDirectoryWatcher();
this.startSubDirectoryWatcher();
}
handleNewBitcoinBlock(block: BlockExtended): void {
if (block.height - 10 > this.latestBlockHeight && this.latestBlockHeight !== 0) {
logger.warn(`Bitcoin block height (#${block.height}) has diverged from the latest Bisq block height (#${this.latestBlockHeight}). Restarting watchers...`);
this.startTopDirectoryWatcher();
this.startSubDirectoryWatcher();
}
}
getTransaction(txId: string): BisqTransaction | undefined {
return this.transactionIndex[txId];
}
getTransactions(start: number, length: number, types: string[]): [BisqTransaction[], number] {
let transactions = this.transactions;
if (types.length) {
transactions = transactions.filter((tx) => types.indexOf(tx.txType) > -1);
}
return [transactions.slice(start, length + start), transactions.length];
}
getBlock(hash: string): BisqBlock | undefined {
return this.blockIndex[hash];
}
getAddress(hash: string): BisqTransaction[] {
return this.addressIndex[hash];
}
getBlocks(start: number, length: number): [BisqBlock[], number] {
return [this.blocks.slice(start, length + start), this.blocks.length];
}
getStats(): BisqStats {
return this.stats;
}
setPriceCallbackFunction(fn: (price: number) => void) {
this.priceUpdateCallbackFunction = fn;
}
getLatestBlockHeight(): number {
return this.latestBlockHeight;
}
private checkForBisqDataFolder() {
if (!fs.existsSync(Bisq.BLOCKS_JSON_FILE_PATH)) {
logger.warn(Bisq.BLOCKS_JSON_FILE_PATH + ` doesn't exist. Make sure Bisq is running and the config is correct before starting the server.`);
throw new Error(`Cannot load BISQ ${Bisq.BLOCKS_JSON_FILE_PATH} file`);
}
}
private startTopDirectoryWatcher() {
if (this.topDirectoryWatcher) {
this.topDirectoryWatcher.close();
}
let fsWait: NodeJS.Timeout | null = null;
this.topDirectoryWatcher = fs.watch(config.BISQ.DATA_PATH + '/json', () => {
if (fsWait) {
clearTimeout(fsWait);
}
if (this.subdirectoryWatcher) {
this.subdirectoryWatcher.close();
}
fsWait = setTimeout(() => {
logger.debug(`Bisq restart detected. Resetting both watchers in 3 minutes.`);
setTimeout(() => {
this.startTopDirectoryWatcher();
this.startSubDirectoryWatcher();
this.loadBisqDumpFile();
}, 180000);
}, 15000);
});
}
private startSubDirectoryWatcher() {
if (this.subdirectoryWatcher) {
this.subdirectoryWatcher.close();
}
if (!fs.existsSync(Bisq.BLOCKS_JSON_FILE_PATH)) {
logger.warn(Bisq.BLOCKS_JSON_FILE_PATH + ` doesn't exist. Trying to restart sub directory watcher again in 3 minutes.`);
setTimeout(() => this.startSubDirectoryWatcher(), 180000);
return;
}
let fsWait: NodeJS.Timeout | null = null;
this.subdirectoryWatcher = fs.watch(config.BISQ.DATA_PATH + '/json/all', () => {
if (fsWait) {
clearTimeout(fsWait);
}
fsWait = setTimeout(() => {
logger.debug(`Change detected in the Bisq data folder.`);
this.loadBisqDumpFile();
}, 2000);
});
}
private async updatePrice() {
type axiosOptions = {
headers: {
'User-Agent': string
};
timeout: number;
httpAgent?: http.Agent;
httpsAgent?: https.Agent;
}
const setDelay = (secs: number = 1): Promise<void> => new Promise(resolve => setTimeout(() => resolve(), secs * 1000));
const BISQ_URL = (config.SOCKS5PROXY.ENABLED === true) && (config.SOCKS5PROXY.USE_ONION === true) ? config.EXTERNAL_DATA_SERVER.BISQ_ONION : config.EXTERNAL_DATA_SERVER.BISQ_URL;
const isHTTP = (new URL(BISQ_URL).protocol.split(':')[0] === 'http') ? true : false;
const axiosOptions: axiosOptions = {
headers: {
'User-Agent': (config.MEMPOOL.USER_AGENT === 'mempool') ? `mempool/v${backendInfo.getBackendInfo().version}` : `${config.MEMPOOL.USER_AGENT}`
},
timeout: config.SOCKS5PROXY.ENABLED ? 30000 : 10000
};
let retry = 0;
while(retry < config.MEMPOOL.EXTERNAL_MAX_RETRY) {
try {
if (config.SOCKS5PROXY.ENABLED) {
const socksOptions: any = {
agentOptions: {
keepAlive: true,
},
hostname: config.SOCKS5PROXY.HOST,
port: config.SOCKS5PROXY.PORT
};
if (config.SOCKS5PROXY.USERNAME && config.SOCKS5PROXY.PASSWORD) {
socksOptions.username = config.SOCKS5PROXY.USERNAME;
socksOptions.password = config.SOCKS5PROXY.PASSWORD;
} else {
// Retry with different tor circuits https://stackoverflow.com/a/64960234
socksOptions.username = `circuit${retry}`;
}
// Handle proxy agent for onion addresses
if (isHTTP) {
axiosOptions.httpAgent = new SocksProxyAgent(socksOptions);
} else {
axiosOptions.httpsAgent = new SocksProxyAgent(socksOptions);
}
}
const data: AxiosResponse = await axios.get(`${BISQ_URL}/trades/?market=bsq_btc`, axiosOptions);
if (data.statusText === 'error' || !data.data) {
throw new Error(`Could not fetch data from Bisq market, Error: ${data.status}`);
}
const prices: number[] = [];
data.data.forEach((trade) => {
prices.push(parseFloat(trade.price) * 100000000);
});
prices.sort((a, b) => a - b);
this.price = Common.median(prices);
if (this.priceUpdateCallbackFunction) {
this.priceUpdateCallbackFunction(this.price);
}
logger.debug('Successfully updated Bisq market price');
break;
} catch (e) {
logger.err('Error updating Bisq market price: ' + (e instanceof Error ? e.message : e));
await setDelay(config.MEMPOOL.EXTERNAL_RETRY_INTERVAL);
retry++;
}
}
}
private async loadBisqDumpFile(): Promise<void> {
this.allBlocks = [];
try {
await this.loadData();
this.buildIndex();
this.calculateStats();
} catch (e) {
logger.info('Cannot load bisq dump file because: ' + (e instanceof Error ? e.message : e));
}
}
private buildIndex() {
const start = new Date().getTime();
this.transactions = [];
this.transactionIndex = {};
this.addressIndex = {};
this.allBlocks.forEach((block) => {
/* Build block index */
if (!this.blockIndex[block.hash]) {
this.blockIndex[block.hash] = block;
}
/* Build transactions index */
block.txs.forEach((tx) => {
this.transactions.push(tx);
this.transactionIndex[tx.id] = tx;
});
});
/* Build address index */
this.transactions.forEach((tx) => {
tx.inputs.forEach((input) => {
if (!this.addressIndex[input.address]) {
this.addressIndex[input.address] = [];
}
if (this.addressIndex[input.address].indexOf(tx) === -1) {
this.addressIndex[input.address].push(tx);
}
});
tx.outputs.forEach((output) => {
if (!this.addressIndex[output.address]) {
this.addressIndex[output.address] = [];
}
if (this.addressIndex[output.address].indexOf(tx) === -1) {
this.addressIndex[output.address].push(tx);
}
});
});
const time = new Date().getTime() - start;
logger.debug('Bisq data index rebuilt in ' + time + ' ms');
}
private calculateStats() {
let minted = 0;
let burned = 0;
let unspent = 0;
let spent = 0;
this.transactions.forEach((tx) => {
tx.outputs.forEach((output) => {
if (output.opReturn) {
return;
}
if (output.txOutputType === 'GENESIS_OUTPUT' || output.txOutputType === 'ISSUANCE_CANDIDATE_OUTPUT' && output.isVerified) {
minted += output.bsqAmount;
}
if (output.isUnspent) {
unspent++;
} else {
spent++;
}
});
burned += tx['burntFee'];
});
this.stats = {
addresses: Object.keys(this.addressIndex).length,
minted: minted / 100,
burnt: burned / 100,
spent_txos: spent,
unspent_txos: unspent,
};
}
private async loadData(): Promise<any> {
if (!fs.existsSync(Bisq.BLOCKS_JSON_FILE_PATH)) {
throw new Error(Bisq.BLOCKS_JSON_FILE_PATH + ` doesn't exist`);
}
const readline = require('readline');
const events = require('events');
const rl = readline.createInterface({
input: fs.createReadStream(Bisq.BLOCKS_JSON_FILE_PATH),
crlfDelay: Infinity
});
let blockBuffer = '';
let readingBlock = false;
let lineCount = 1;
const start = new Date().getTime();
logger.debug('Processing Bisq data dump...');
rl.on('line', (line) => {
if (lineCount === 2) {
line = line.replace(' "chainHeight": ', '');
this.latestBlockHeight = parseInt(line, 10);
}
if (line === ' {') {
readingBlock = true;
} else if (line === ' },') {
blockBuffer += '}';
try {
const block: BisqBlock = JSON.parse(blockBuffer);
this.allBlocks.push(block);
readingBlock = false;
blockBuffer = '';
} catch (e) {
logger.debug(blockBuffer);
throw Error(`Unable to parse Bisq data dump at line ${lineCount}` + (e instanceof Error ? e.message : e));
}
}
if (readingBlock === true) {
blockBuffer += line;
}
++lineCount;
});
await events.once(rl, 'close');
this.allBlocks.reverse();
this.blocks = this.allBlocks.filter((block) => block.txs.length > 0);
const time = new Date().getTime() - start;
logger.debug('Bisq dump processed in ' + time + ' ms');
}
}
export default new Bisq();

View File

@@ -1,258 +0,0 @@
export interface BisqBlocks {
chainHeight: number;
blocks: BisqBlock[];
}
export interface BisqBlock {
height: number;
time: number;
hash: string;
previousBlockHash: string;
txs: BisqTransaction[];
}
export interface BisqTransaction {
txVersion: string;
id: string;
blockHeight: number;
blockHash: string;
time: number;
inputs: BisqInput[];
outputs: BisqOutput[];
txType: string;
txTypeDisplayString: string;
burntFee: number;
invalidatedBsq: number;
unlockBlockHeight: number;
}
export interface BisqStats {
minted: number;
burnt: number;
addresses: number;
unspent_txos: number;
spent_txos: number;
}
interface BisqInput {
spendingTxOutputIndex: number;
spendingTxId: string;
bsqAmount: number;
isVerified: boolean;
address: string;
time: number;
}
interface BisqOutput {
txVersion: string;
txId: string;
index: number;
bsqAmount: number;
btcAmount: number;
height: number;
isVerified: boolean;
burntFee: number;
invalidatedBsq: number;
address: string;
scriptPubKey: BisqScriptPubKey;
time: any;
txType: string;
txTypeDisplayString: string;
txOutputType: string;
txOutputTypeDisplayString: string;
lockTime: number;
isUnspent: boolean;
spentInfo: SpentInfo;
opReturn?: string;
}
interface BisqScriptPubKey {
addresses: string[];
asm: string;
hex: string;
reqSigs?: number;
type: string;
}
interface SpentInfo {
height: number;
inputIndex: number;
txId: string;
}
export interface BisqTrade {
direction: string;
price: string;
amount: string;
volume: string;
payment_method: string;
trade_id: string;
trade_date: number;
market?: string;
}
export interface Currencies { [txid: string]: Currency; }
export interface Currency {
code: string;
name: string;
precision: number;
_type: string;
}
export interface Depth { [market: string]: Market; }
interface Market {
'buys': string[];
'sells': string[];
}
export interface HighLowOpenClose {
period_start: number | string;
open: string;
high: string;
low: string;
close: string;
volume_left: string;
volume_right: string;
avg: string;
}
export interface Markets { [txid: string]: Pair; }
interface Pair {
pair: string;
lname: string;
rname: string;
lsymbol: string;
rsymbol: string;
lprecision: number;
rprecision: number;
ltype: string;
rtype: string;
name: string;
}
export interface Offers { [market: string]: OffersMarket; }
interface OffersMarket {
buys: Offer[] | null;
sells: Offer[] | null;
}
export interface OffersData {
direction: string;
currencyCode: string;
minAmount: number;
amount: number;
price: number;
date: number;
useMarketBasedPrice: boolean;
marketPriceMargin: number;
paymentMethod: string;
id: string;
currencyPair: string;
primaryMarketDirection: string;
priceDisplayString: string;
primaryMarketAmountDisplayString: string;
primaryMarketMinAmountDisplayString: string;
primaryMarketVolumeDisplayString: string;
primaryMarketMinVolumeDisplayString: string;
primaryMarketPrice: number;
primaryMarketAmount: number;
primaryMarketMinAmount: number;
primaryMarketVolume: number;
primaryMarketMinVolume: number;
}
export interface Offer {
offer_id: string;
offer_date: number;
direction: string;
min_amount: string;
amount: string;
price: string;
volume: string;
payment_method: string;
offer_fee_txid: any;
}
export interface Tickers { [market: string]: Ticker | null; }
export interface Ticker {
last: string;
high: string;
low: string;
volume_left: string;
volume_right: string;
buy: string | null;
sell: string | null;
}
export interface Trade {
direction: string;
price: string;
amount: string;
volume: string;
payment_method: string;
trade_id: string;
trade_date: number;
}
export interface TradesData {
currency: string;
direction: string;
tradePrice: number;
tradeAmount: number;
tradeDate: number;
paymentMethod: string;
offerDate: number;
useMarketBasedPrice: boolean;
marketPriceMargin: number;
offerAmount: number;
offerMinAmount: number;
offerId: string;
depositTxId?: string;
currencyPair: string;
primaryMarketDirection: string;
primaryMarketTradePrice: number;
primaryMarketTradeAmount: number;
primaryMarketTradeVolume: number;
_market: string;
_tradePriceStr: string;
_tradeAmountStr: string;
_tradeVolumeStr: string;
_offerAmountStr: string;
_tradePrice: number;
_tradeAmount: number;
_tradeVolume: number;
_offerAmount: number;
}
export interface MarketVolume {
period_start: number;
num_trades: number;
volume: string;
}
export interface MarketsApiError {
success: number;
error: string;
}
export type Interval = 'minute' | 'half_hour' | 'hour' | 'half_day' | 'day' | 'week' | 'month' | 'year' | 'auto';
export interface SummarizedIntervals { [market: string]: SummarizedInterval; }
export interface SummarizedInterval {
'period_start': number;
'open': number;
'close': number;
'high': number;
'low': number;
'avg': number;
'volume_right': number;
'volume_left': number;
}

View File

@@ -1,679 +0,0 @@
import { Currencies, OffersData, TradesData, Depth, Currency, Interval, HighLowOpenClose,
Markets, Offers, Offer, BisqTrade, MarketVolume, Tickers, Ticker, SummarizedIntervals, SummarizedInterval } from './interfaces';
const strtotime = require('./strtotime');
class BisqMarketsApi {
private cryptoCurrencyData: Currency[] = [];
private fiatCurrencyData: Currency[] = [];
private activeCryptoCurrencyData: Currency[] = [];
private activeFiatCurrencyData: Currency[] = [];
private offersData: OffersData[] = [];
private tradesData: TradesData[] = [];
private fiatCurrenciesIndexed: { [code: string]: true } = {};
private allCurrenciesIndexed: { [code: string]: Currency } = {};
private tradeDataByMarket: { [market: string]: TradesData[] } = {};
private tickersCache: Ticker | Tickers | null = null;
constructor() { }
setOffersData(offers: OffersData[]) {
this.offersData = offers;
}
setTradesData(trades: TradesData[]) {
this.tradesData = trades;
this.tradeDataByMarket = {};
this.tradesData.forEach((trade) => {
trade._market = trade.currencyPair.toLowerCase().replace('/', '_');
if (!this.tradeDataByMarket[trade._market]) {
this.tradeDataByMarket[trade._market] = [];
}
this.tradeDataByMarket[trade._market].push(trade);
});
}
setCurrencyData(cryptoCurrency: Currency[], fiatCurrency: Currency[], activeCryptoCurrency: Currency[], activeFiatCurrency: Currency[]) {
this.cryptoCurrencyData = cryptoCurrency,
this.fiatCurrencyData = fiatCurrency,
this.activeCryptoCurrencyData = activeCryptoCurrency,
this.activeFiatCurrencyData = activeFiatCurrency;
this.fiatCurrenciesIndexed = {};
this.allCurrenciesIndexed = {};
this.fiatCurrencyData.forEach((currency) => {
currency._type = 'fiat';
this.fiatCurrenciesIndexed[currency.code] = true;
this.allCurrenciesIndexed[currency.code] = currency;
});
this.cryptoCurrencyData.forEach((currency) => {
currency._type = 'crypto';
this.allCurrenciesIndexed[currency.code] = currency;
});
}
updateCache() {
this.tickersCache = null;
this.tickersCache = this.getTicker();
}
getCurrencies(
type: 'crypto' | 'fiat' | 'active' | 'all' = 'all',
): Currencies {
let currencies: Currency[];
switch (type) {
case 'fiat':
currencies = this.fiatCurrencyData;
break;
case 'crypto':
currencies = this.cryptoCurrencyData;
break;
case 'active':
currencies = this.activeCryptoCurrencyData.concat(this.activeFiatCurrencyData);
break;
case 'all':
default:
currencies = this.cryptoCurrencyData.concat(this.fiatCurrencyData);
}
const result = {};
currencies.forEach((currency) => {
result[currency.code] = currency;
});
return result;
}
getDepth(
market: string,
): Depth {
const currencyPair = market.replace('_', '/').toUpperCase();
const buys = this.offersData
.filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'BUY')
.map((offer) => offer.price)
.sort((a, b) => b - a)
.map((price) => this.intToBtc(price));
const sells = this.offersData
.filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'SELL')
.map((offer) => offer.price)
.sort((a, b) => a - b)
.map((price) => this.intToBtc(price));
const result = {};
result[market] = {
'buys': buys,
'sells': sells,
};
return result;
}
getOffers(
market: string,
direction?: 'buy' | 'sell',
): Offers {
const currencyPair = market.replace('_', '/').toUpperCase();
let buys: Offer[] | null = null;
let sells: Offer[] | null = null;
if (!direction || direction === 'buy') {
buys = this.offersData
.filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'BUY')
.sort((a, b) => b.price - a.price)
.map((offer) => this.offerDataToOffer(offer, market));
}
if (!direction || direction === 'sell') {
sells = this.offersData
.filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'SELL')
.sort((a, b) => a.price - b.price)
.map((offer) => this.offerDataToOffer(offer, market));
}
const result: Offers = {};
result[market] = {
'buys': buys,
'sells': sells,
};
return result;
}
getMarkets(): Markets {
const allCurrencies = this.getCurrencies();
const activeCurrencies = this.getCurrencies('active');
const markets = {};
for (const currency of Object.keys(activeCurrencies)) {
if (allCurrencies[currency].code === 'BTC') {
continue;
}
const isFiat = allCurrencies[currency]._type === 'fiat';
const pmarketname = allCurrencies['BTC']['name'];
const lsymbol = isFiat ? 'BTC' : currency;
const rsymbol = isFiat ? currency : 'BTC';
const lname = isFiat ? pmarketname : allCurrencies[currency].name;
const rname = isFiat ? allCurrencies[currency].name : pmarketname;
const ltype = isFiat ? 'crypto' : allCurrencies[currency]._type;
const rtype = isFiat ? 'fiat' : 'crypto';
const lprecision = 8;
const rprecision = isFiat ? 2 : 8;
const pair = lsymbol.toLowerCase() + '_' + rsymbol.toLowerCase();
markets[pair] = {
'pair': pair,
'lname': lname,
'rname': rname,
'lsymbol': lsymbol,
'rsymbol': rsymbol,
'lprecision': lprecision,
'rprecision': rprecision,
'ltype': ltype,
'rtype': rtype,
'name': lname + '/' + rname,
};
}
return markets;
}
getTrades(
market: string,
timestamp_from?: number,
timestamp_to?: number,
trade_id_from?: string,
trade_id_to?: string,
direction?: 'buy' | 'sell',
limit: number = 100,
sort: 'asc' | 'desc' = 'desc',
): BisqTrade[] {
limit = Math.min(limit, 2000);
const _market = market === 'all' ? undefined : market;
if (!timestamp_from) {
timestamp_from = new Date('2016-01-01').getTime() / 1000;
}
if (!timestamp_to) {
timestamp_to = new Date().getTime() / 1000;
}
const matches = this.getTradesByCriteria(_market, timestamp_to, timestamp_from,
trade_id_to, trade_id_from, direction, sort, limit, false);
if (sort === 'asc') {
matches.sort((a, b) => a.tradeDate - b.tradeDate);
} else {
matches.sort((a, b) => b.tradeDate - a.tradeDate);
}
return matches.map((trade) => {
const bsqTrade: BisqTrade = {
direction: trade.primaryMarketDirection,
price: trade._tradePriceStr,
amount: trade._tradeAmountStr,
volume: trade._tradeVolumeStr,
payment_method: trade.paymentMethod,
trade_id: trade.offerId,
trade_date: trade.tradeDate,
};
if (market === 'all') {
bsqTrade.market = trade._market;
}
return bsqTrade;
});
}
getVolumes(
market?: string,
timestamp_from?: number,
timestamp_to?: number,
interval: Interval = 'auto',
milliseconds?: boolean,
timestamp: 'no' | 'yes' = 'yes',
): MarketVolume[] {
if (milliseconds) {
timestamp_from = timestamp_from ? timestamp_from / 1000 : timestamp_from;
timestamp_to = timestamp_to ? timestamp_to / 1000 : timestamp_to;
}
if (!timestamp_from) {
timestamp_from = new Date('2016-01-01').getTime() / 1000;
}
if (!timestamp_to) {
timestamp_to = new Date().getTime() / 1000;
}
const trades = this.getTradesByCriteria(market, timestamp_to, timestamp_from,
undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER);
if (interval === 'auto') {
const range = timestamp_to - timestamp_from;
interval = this.getIntervalFromRange(range);
}
const intervals: any = {};
const marketVolumes: MarketVolume[] = [];
for (const trade of trades) {
const traded_at = trade['tradeDate'] / 1000;
const interval_start = this.intervalStart(traded_at, interval);
if (!intervals[interval_start]) {
intervals[interval_start] = {
'volume': 0,
'num_trades': 0,
};
}
const period = intervals[interval_start];
period['period_start'] = interval_start;
period['volume'] += this.fiatCurrenciesIndexed[trade.currency] ? trade._tradeAmount : trade._tradeVolume;
period['num_trades']++;
}
for (const p in intervals) {
if (intervals.hasOwnProperty(p)) {
const period = intervals[p];
marketVolumes.push({
period_start: timestamp === 'no' ? new Date(period['period_start'] * 1000).toISOString() : period['period_start'],
num_trades: period['num_trades'],
volume: this.intToBtc(period['volume']),
});
}
}
return marketVolumes;
}
getTicker(
market?: string,
): Tickers | Ticker | null {
if (market) {
return this.getTickerFromMarket(market);
}
if (this.tickersCache) {
return this.tickersCache;
}
const allMarkets = this.getMarkets();
const tickers = {};
for (const m in allMarkets) {
if (allMarkets.hasOwnProperty(m)) {
tickers[allMarkets[m].pair] = this.getTickerFromMarket(allMarkets[m].pair);
}
}
return tickers;
}
getTickerFromMarket(market: string): Ticker | null {
let ticker: Ticker;
const timestamp_from = strtotime('-24 hour');
const timestamp_to = new Date().getTime() / 1000;
const trades = this.getTradesByCriteria(market, timestamp_to, timestamp_from,
undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER);
const periods: SummarizedInterval[] = Object.values(this.getTradesSummarized(trades, timestamp_from));
const allCurrencies = this.getCurrencies();
const currencyRight = allCurrencies[market.split('_')[1].toUpperCase()];
if (periods[0]) {
ticker = {
'last': this.intToBtc(periods[0].close),
'high': this.intToBtc(periods[0].high),
'low': this.intToBtc(periods[0].low),
'volume_left': this.intToBtc(periods[0].volume_left),
'volume_right': this.intToBtc(periods[0].volume_right),
'buy': null,
'sell': null,
};
} else {
const lastTrade = this.tradeDataByMarket[market];
if (!lastTrade) {
return null;
}
const tradePrice = lastTrade[0].primaryMarketTradePrice * Math.pow(10, 8 - currencyRight.precision);
const lastTradePrice = this.intToBtc(tradePrice);
ticker = {
'last': lastTradePrice,
'high': lastTradePrice,
'low': lastTradePrice,
'volume_left': '0',
'volume_right': '0',
'buy': null,
'sell': null,
};
}
const timestampFromMilli = timestamp_from * 1000;
const timestampToMilli = timestamp_to * 1000;
const currencyPair = market.replace('_', '/').toUpperCase();
const offersData = this.offersData.slice().sort((a, b) => a.price - b.price);
const buy = offersData.find((offer) => offer.currencyPair === currencyPair
&& offer.primaryMarketDirection === 'BUY'
&& offer.date >= timestampFromMilli
&& offer.date <= timestampToMilli
);
const sell = offersData.find((offer) => offer.currencyPair === currencyPair
&& offer.primaryMarketDirection === 'SELL'
&& offer.date >= timestampFromMilli
&& offer.date <= timestampToMilli
);
if (buy) {
ticker.buy = this.intToBtc(buy.primaryMarketPrice * Math.pow(10, 8 - currencyRight.precision));
}
if (sell) {
ticker.sell = this.intToBtc(sell.primaryMarketPrice * Math.pow(10, 8 - currencyRight.precision));
}
return ticker;
}
getHloc(
market: string,
interval: Interval = 'auto',
timestamp_from?: number,
timestamp_to?: number,
milliseconds?: boolean,
timestamp: 'no' | 'yes' = 'yes',
): HighLowOpenClose[] {
if (milliseconds) {
timestamp_from = timestamp_from ? timestamp_from / 1000 : timestamp_from;
timestamp_to = timestamp_to ? timestamp_to / 1000 : timestamp_to;
}
if (!timestamp_from) {
timestamp_from = new Date('2016-01-01').getTime() / 1000;
}
if (!timestamp_to) {
timestamp_to = new Date().getTime() / 1000;
}
const trades = this.getTradesByCriteria(market, timestamp_to, timestamp_from,
undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER);
if (interval === 'auto') {
const range = timestamp_to - timestamp_from;
interval = this.getIntervalFromRange(range);
}
const intervals = this.getTradesSummarized(trades, timestamp_from, interval);
const hloc: HighLowOpenClose[] = [];
for (const p in intervals) {
if (intervals.hasOwnProperty(p)) {
const period = intervals[p];
hloc.push({
period_start: timestamp === 'no' ? new Date(period['period_start'] * 1000).toISOString() : period['period_start'],
open: this.intToBtc(period['open']),
close: this.intToBtc(period['close']),
high: this.intToBtc(period['high']),
low: this.intToBtc(period['low']),
avg: this.intToBtc(period['avg']),
volume_right: this.intToBtc(period['volume_right']),
volume_left: this.intToBtc(period['volume_left']),
});
}
}
return hloc;
}
private getIntervalFromRange(range: number): Interval {
// two days range loads minute data
if (range <= 3600) {
// up to one hour range loads minutely data
return 'minute';
} else if (range <= 1 * 24 * 3600) {
// up to one day range loads half-hourly data
return 'half_hour';
} else if (range <= 3 * 24 * 3600) {
// up to 3 day range loads hourly data
return 'hour';
} else if (range <= 7 * 24 * 3600) {
// up to 7 day range loads half-daily data
return 'half_day';
} else if (range <= 60 * 24 * 3600) {
// up to 2 month range loads daily data
return 'day';
} else if (range <= 12 * 31 * 24 * 3600) {
// up to one year range loads weekly data
return 'week';
} else if (range <= 12 * 31 * 24 * 3600) {
// up to 5 year range loads monthly data
return 'month';
} else {
// greater range loads yearly data
return 'year';
}
}
getVolumesByTime(time: number): MarketVolume[] {
const timestamp_from = new Date().getTime() / 1000 - time;
const timestamp_to = new Date().getTime() / 1000;
const trades = this.getTradesByCriteria(undefined, timestamp_to, timestamp_from,
undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER);
const markets: any = {};
for (const trade of trades) {
if (!markets[trade._market]) {
markets[trade._market] = {
'volume': 0,
'num_trades': 0,
};
}
markets[trade._market]['volume'] += this.fiatCurrenciesIndexed[trade.currency] ? trade._tradeAmount : trade._tradeVolume;
markets[trade._market]['num_trades']++;
}
return markets;
}
private getTradesSummarized(trades: TradesData[], timestamp_from: number, interval?: string): SummarizedIntervals {
const intervals: any = {};
const intervals_prices: any = {};
for (const trade of trades) {
const traded_at = trade.tradeDate / 1000;
const interval_start = !interval ? timestamp_from : this.intervalStart(traded_at, interval);
if (!intervals[interval_start]) {
intervals[interval_start] = {
'open': 0,
'close': 0,
'high': 0,
'low': 0,
'avg': 0,
'volume_right': 0,
'volume_left': 0,
};
intervals_prices[interval_start] = [];
}
const period = intervals[interval_start];
const price = trade._tradePrice;
if (!intervals_prices[interval_start]['leftvol']) {
intervals_prices[interval_start]['leftvol'] = [];
}
if (!intervals_prices[interval_start]['rightvol']) {
intervals_prices[interval_start]['rightvol'] = [];
}
intervals_prices[interval_start]['leftvol'].push(trade._tradeAmount);
intervals_prices[interval_start]['rightvol'].push(trade._tradeVolume);
if (price) {
const plow = period['low'];
period['period_start'] = interval_start;
period['open'] = period['open'] || price;
period['close'] = price;
period['high'] = price > period['high'] ? price : period['high'];
period['low'] = (plow && price > plow) ? period['low'] : price;
period['avg'] = intervals_prices[interval_start]['rightvol'].reduce((p: number, c: number) => c + p, 0)
/ intervals_prices[interval_start]['leftvol'].reduce((c: number, p: number) => c + p, 0) * 100000000;
period['volume_left'] += trade._tradeAmount;
period['volume_right'] += trade._tradeVolume;
}
}
return intervals;
}
private getTradesByCriteria(
market: string | undefined,
timestamp_to: number,
timestamp_from: number,
trade_id_to: string | undefined,
trade_id_from: string | undefined,
direction: 'buy' | 'sell' | undefined,
sort: string,
limit: number,
integerAmounts: boolean = true,
): TradesData[] {
let trade_id_from_ts: number | null = null;
let trade_id_to_ts: number | null = null;
const allCurrencies = this.getCurrencies();
const timestampFromMilli = timestamp_from * 1000;
const timestampToMilli = timestamp_to * 1000;
// note: the offer_id_from/to depends on iterating over trades in
// descending chronological order.
const tradesDataSorted = this.tradesData.slice();
if (sort === 'asc') {
tradesDataSorted.reverse();
}
let matches: TradesData[] = [];
for (const trade of tradesDataSorted) {
if (trade_id_from === trade.offerId) {
trade_id_from_ts = trade.tradeDate;
}
if (trade_id_to === trade.offerId) {
trade_id_to_ts = trade.tradeDate;
}
if (trade_id_to && trade_id_to_ts === null) {
continue;
}
if (trade_id_from && trade_id_from_ts != null && trade_id_from_ts !== trade.tradeDate) {
continue;
}
if (market && market !== trade._market) {
continue;
}
if (timestampFromMilli && timestampFromMilli > trade.tradeDate) {
continue;
}
if (timestampToMilli && timestampToMilli < trade.tradeDate) {
continue;
}
if (direction && direction !== trade.direction.toLowerCase()) {
continue;
}
// Filter out bogus trades with BTC/BTC or XXX/XXX market.
// See github issue: https://github.com/bitsquare/bitsquare/issues/883
const currencyPairs = trade.currencyPair.split('/');
if (currencyPairs[0] === currencyPairs[1]) {
continue;
}
const currencyLeft = allCurrencies[currencyPairs[0]];
const currencyRight = allCurrencies[currencyPairs[1]];
if (!currencyLeft || !currencyRight) {
continue;
}
const tradePrice = trade.primaryMarketTradePrice * Math.pow(10, 8 - currencyRight.precision);
const tradeAmount = trade.primaryMarketTradeAmount * Math.pow(10, 8 - currencyLeft.precision);
const tradeVolume = trade.primaryMarketTradeVolume * Math.pow(10, 8 - currencyRight.precision);
if (integerAmounts) {
trade._tradePrice = tradePrice;
trade._tradeAmount = tradeAmount;
trade._tradeVolume = tradeVolume;
trade._offerAmount = trade.offerAmount;
} else {
trade._tradePriceStr = this.intToBtc(tradePrice);
trade._tradeAmountStr = this.intToBtc(tradeAmount);
trade._tradeVolumeStr = this.intToBtc(tradeVolume);
trade._offerAmountStr = this.intToBtc(trade.offerAmount);
}
matches.push(trade);
if (matches.length >= limit) {
break;
}
}
if ((trade_id_from && !trade_id_from_ts) || (trade_id_to && !trade_id_to_ts)) {
matches = [];
}
return matches;
}
private intervalStart(ts: number, interval: string): number {
switch (interval) {
case 'minute':
return (ts - (ts % 60));
case '10_minute':
return (ts - (ts % 600));
case 'half_hour':
return (ts - (ts % 1800));
case 'hour':
return (ts - (ts % 3600));
case 'half_day':
return (ts - (ts % (3600 * 12)));
case 'day':
return strtotime('midnight today', ts);
case 'week':
return strtotime('midnight sunday last week', ts);
case 'month':
return strtotime('midnight first day of this month', ts);
case 'year':
return strtotime('midnight first day of january', ts);
default:
throw new Error('Unsupported interval: ' + interval);
}
}
private offerDataToOffer(offer: OffersData, market: string): Offer {
const currencyPairs = market.split('_');
const currencyRight = this.allCurrenciesIndexed[currencyPairs[1].toUpperCase()];
const currencyLeft = this.allCurrenciesIndexed[currencyPairs[0].toUpperCase()];
const price = offer['primaryMarketPrice'] * Math.pow( 10, 8 - currencyRight['precision']);
const amount = offer['primaryMarketAmount'] * Math.pow( 10, 8 - currencyLeft['precision']);
const volume = offer['primaryMarketVolume'] * Math.pow( 10, 8 - currencyRight['precision']);
return {
offer_id: offer.id,
offer_date: offer.date,
direction: offer.primaryMarketDirection,
min_amount: this.intToBtc(offer.minAmount),
amount: this.intToBtc(amount),
price: this.intToBtc(price),
volume: this.intToBtc(volume),
payment_method: offer.paymentMethod,
offer_fee_txid: null,
};
}
private intToBtc(val: number): string {
return (val / 100000000).toFixed(8);
}
}
export default new BisqMarketsApi();

View File

@@ -1,137 +0,0 @@
import config from '../../config';
import * as fs from 'fs';
import { OffersData as OffersData, TradesData, Currency } from './interfaces';
import bisqMarket from './markets-api';
import logger from '../../logger';
class Bisq {
private static FOLDER_WATCH_CHANGE_DETECTION_DEBOUNCE = 4000;
private static MARKET_JSON_PATH = config.BISQ.DATA_PATH;
private static MARKET_JSON_FILE_PATHS = {
activeCryptoCurrency: '/active_crypto_currency_list.json',
activeFiatCurrency: '/active_fiat_currency_list.json',
cryptoCurrency: '/crypto_currency_list.json',
fiatCurrency: '/fiat_currency_list.json',
offers: '/offers_statistics.json',
trades: '/trade_statistics.json',
};
private cryptoCurrencyLastMtime = new Date('2016-01-01');
private fiatCurrencyLastMtime = new Date('2016-01-01');
private offersLastMtime = new Date('2016-01-01');
private tradesLastMtime = new Date('2016-01-01');
private subdirectoryWatcher: fs.FSWatcher | undefined;
constructor() {}
startBisqService(): void {
try {
this.checkForBisqDataFolder();
} catch (e) {
logger.info('Retrying to start bisq service (markets) in 3 minutes');
setTimeout(this.startBisqService.bind(this), 180000);
return;
}
this.loadBisqDumpFile();
this.startBisqDirectoryWatcher();
}
private checkForBisqDataFolder() {
if (!fs.existsSync(Bisq.MARKET_JSON_PATH + Bisq.MARKET_JSON_FILE_PATHS.cryptoCurrency)) {
logger.err(Bisq.MARKET_JSON_PATH + Bisq.MARKET_JSON_FILE_PATHS.cryptoCurrency + ` doesn't exist. Make sure Bisq is running and the config is correct before starting the server.`);
throw new Error(`Cannot load BISQ ${Bisq.MARKET_JSON_FILE_PATHS.cryptoCurrency} file`);
}
}
private startBisqDirectoryWatcher() {
if (this.subdirectoryWatcher) {
this.subdirectoryWatcher.close();
}
if (!fs.existsSync(Bisq.MARKET_JSON_PATH + Bisq.MARKET_JSON_FILE_PATHS.cryptoCurrency)) {
logger.warn(Bisq.MARKET_JSON_PATH + Bisq.MARKET_JSON_FILE_PATHS.cryptoCurrency + ` doesn't exist. Trying to restart sub directory watcher again in 3 minutes.`);
setTimeout(() => this.startBisqDirectoryWatcher(), 180000);
return;
}
let fsWait: NodeJS.Timeout | null = null;
this.subdirectoryWatcher = fs.watch(Bisq.MARKET_JSON_PATH, () => {
if (fsWait) {
clearTimeout(fsWait);
}
fsWait = setTimeout(() => {
logger.debug(`Change detected in the Bisq market data folder.`);
this.loadBisqDumpFile();
}, Bisq.FOLDER_WATCH_CHANGE_DETECTION_DEBOUNCE);
});
}
private async loadBisqDumpFile(): Promise<void> {
const start = new Date().getTime();
try {
let marketsDataUpdated = false;
const cryptoMtime = this.getFileMtime(Bisq.MARKET_JSON_FILE_PATHS.cryptoCurrency);
const fiatMtime = this.getFileMtime(Bisq.MARKET_JSON_FILE_PATHS.fiatCurrency);
if (cryptoMtime > this.cryptoCurrencyLastMtime || fiatMtime > this.fiatCurrencyLastMtime) {
const cryptoCurrencyData = await this.loadData<Currency[]>(Bisq.MARKET_JSON_FILE_PATHS.cryptoCurrency);
const fiatCurrencyData = await this.loadData<Currency[]>(Bisq.MARKET_JSON_FILE_PATHS.fiatCurrency);
const activeCryptoCurrencyData = await this.loadData<Currency[]>(Bisq.MARKET_JSON_FILE_PATHS.activeCryptoCurrency);
const activeFiatCurrencyData = await this.loadData<Currency[]>(Bisq.MARKET_JSON_FILE_PATHS.activeFiatCurrency);
logger.debug('Updating Bisq Market Currency Data');
bisqMarket.setCurrencyData(cryptoCurrencyData, fiatCurrencyData, activeCryptoCurrencyData, activeFiatCurrencyData);
if (cryptoMtime > this.cryptoCurrencyLastMtime) {
this.cryptoCurrencyLastMtime = cryptoMtime;
}
if (fiatMtime > this.fiatCurrencyLastMtime) {
this.fiatCurrencyLastMtime = fiatMtime;
}
marketsDataUpdated = true;
}
const offersMtime = this.getFileMtime(Bisq.MARKET_JSON_FILE_PATHS.offers);
if (offersMtime > this.offersLastMtime) {
const offersData = await this.loadData<OffersData[]>(Bisq.MARKET_JSON_FILE_PATHS.offers);
logger.debug('Updating Bisq Market Offers Data');
bisqMarket.setOffersData(offersData);
this.offersLastMtime = offersMtime;
marketsDataUpdated = true;
}
const tradesMtime = this.getFileMtime(Bisq.MARKET_JSON_FILE_PATHS.trades);
if (tradesMtime > this.tradesLastMtime) {
const tradesData = await this.loadData<TradesData[]>(Bisq.MARKET_JSON_FILE_PATHS.trades);
logger.debug('Updating Bisq Market Trades Data');
bisqMarket.setTradesData(tradesData);
this.tradesLastMtime = tradesMtime;
marketsDataUpdated = true;
}
if (marketsDataUpdated) {
bisqMarket.updateCache();
const time = new Date().getTime() - start;
logger.debug('Bisq market data updated in ' + time + ' ms');
}
} catch (e) {
logger.err('loadBisqMarketDataDumpFile() error.' + (e instanceof Error ? e.message : e));
}
}
private getFileMtime(path: string): Date {
const stats = fs.statSync(Bisq.MARKET_JSON_PATH + path);
return stats.mtime;
}
private loadData<T>(path: string): Promise<T> {
return new Promise((resolve, reject) => {
fs.readFile(Bisq.MARKET_JSON_PATH + path, 'utf8', (err, data) => {
if (err) {
reject(err);
}
try {
const parsedData = JSON.parse(data);
resolve(parsedData);
} catch (e) {
reject('JSON parse error (' + path + ')');
}
});
});
}
}
export default new Bisq();

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,17 @@
import { IBitcoinApi } from './bitcoin-api.interface';
import { IEsploraApi } from './esplora-api.interface';
export interface AbstractBitcoinApi {
$getRawMempool(): Promise<IEsploraApi.Transaction['txid'][]>;
$getRawTransaction(txId: string, skipConversion?: boolean, addPrevout?: boolean, lazyPrevouts?: boolean): Promise<IEsploraApi.Transaction>;
$getRawTransactions(txids: string[]): Promise<IEsploraApi.Transaction[]>;
$getMempoolTransactions(txids: string[]): Promise<IEsploraApi.Transaction[]>;
$getAllMempoolTransactions(lastTxid?: string, max_txs?: number);
$getTransactionHex(txId: string): Promise<string>;
$getBlockHeightTip(): Promise<number>;
$getBlockHashTip(): Promise<string>;
$getTxIdsForBlock(hash: string): Promise<string[]>;
$getTxsForBlock(hash: string): Promise<IEsploraApi.Transaction[]>;
$getBlockHash(height: number): Promise<string>;
$getBlockHeader(hash: string): Promise<string>;
$getBlock(hash: string): Promise<IEsploraApi.Block>;
@@ -14,10 +19,17 @@ export interface AbstractBitcoinApi {
$getAddress(address: string): Promise<IEsploraApi.Address>;
$getAddressTransactions(address: string, lastSeenTxId: string): Promise<IEsploraApi.Transaction[]>;
$getAddressPrefix(prefix: string): string[];
$getScriptHash(scripthash: string): Promise<IEsploraApi.ScriptHash>;
$getScriptHashTransactions(address: string, lastSeenTxId: string): Promise<IEsploraApi.Transaction[]>;
$sendRawTransaction(rawTransaction: string): Promise<string>;
$getOutspend(txId: string, vout: number): Promise<IEsploraApi.Outspend>;
$getOutspends(txId: string): Promise<IEsploraApi.Outspend[]>;
$getBatchedOutspends(txId: string[]): Promise<IEsploraApi.Outspend[][]>;
$getBatchedOutspendsInternal(txId: string[]): Promise<IEsploraApi.Outspend[][]>;
$getOutSpendsByOutpoint(outpoints: { txid: string, vout: number }[]): Promise<IEsploraApi.Outspend[]>;
startHealthChecks(): void;
getHealthStatus(): HealthCheckHost[];
}
export interface BitcoinRpcCredentials {
host: string;
@@ -25,4 +37,17 @@ 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;
lastChecked: number;
}

View File

@@ -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
};
}

View File

@@ -1,10 +1,11 @@
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';
import mempool from '../mempool';
import { TransactionExtended } from '../../mempool.interfaces';
import transactionUtils from '../transaction-utils';
class BitcoinApi implements AbstractBitcoinApi {
private rawMempoolCache: IBitcoinApi.RawMempool | null = null;
@@ -29,6 +30,7 @@ class BitcoinApi implements AbstractBitcoinApi {
weight: block.weight,
previousblockhash: block.previousblockhash,
mediantime: block.mediantime,
stale: block.confirmations === -1,
};
}
@@ -58,23 +60,46 @@ class BitcoinApi implements AbstractBitcoinApi {
});
}
$getTransactionHex(txId: string): Promise<string> {
return this.$getRawTransaction(txId, true)
.then((tx) => tx.hex || '');
async $getRawTransactions(txids: string[]): Promise<IEsploraApi.Transaction[]> {
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<IEsploraApi.Transaction[]> {
throw new Error('Method getMempoolTransactions not supported by the Bitcoin RPC API.');
}
$getAllMempoolTransactions(lastTxid?: string, max_txs?: number): Promise<IEsploraApi.Transaction[]> {
throw new Error('Method getAllMempoolTransactions not supported by the Bitcoin RPC API.');
}
async $getTransactionHex(txId: string): Promise<string> {
const txInMempool = mempool.getMempool()[txId];
if (txInMempool && txInMempool.hex) {
return txInMempool.hex;
}
return this.bitcoindClient.getRawTransaction(txId, true)
.then((transaction: IBitcoinApi.Transaction) => {
return transaction.hex;
});
}
$getBlockHeightTip(): Promise<number> {
return this.bitcoindClient.getChainTips()
.then((result: IBitcoinApi.ChainTips[]) => {
return result.find(tip => tip.status === 'active')!.height;
});
return this.bitcoindClient.getBlockCount();
}
$getBlockHashTip(): Promise<string> {
return this.bitcoindClient.getChainTips()
.then((result: IBitcoinApi.ChainTips[]) => {
return result.find(tip => tip.status === 'active')!.hash;
});
return this.bitcoindClient.getBestBlockHash();
}
$getTxIdsForBlock(hash: string): Promise<string[]> {
@@ -82,6 +107,10 @@ class BitcoinApi implements AbstractBitcoinApi {
.then((rpcBlock: IBitcoinApi.Block) => rpcBlock.tx);
}
$getTxsForBlock(hash: string): Promise<IEsploraApi.Transaction[]> {
throw new Error('Method getTxsForBlock not supported by the Bitcoin RPC API.');
}
$getRawBlock(hash: string): Promise<Buffer> {
return this.bitcoindClient.getBlock(hash, 0)
.then((raw: string) => Buffer.from(raw, "hex"));
@@ -113,6 +142,14 @@ class BitcoinApi implements AbstractBitcoinApi {
throw new Error('Method getAddressTransactions not supported by the Bitcoin RPC API.');
}
$getScriptHash(scripthash: string): Promise<IEsploraApi.ScriptHash> {
throw new Error('Method getScriptHash not supported by the Bitcoin RPC API.');
}
$getScriptHashTransactions(scripthash: string, lastSeenTxId: string): Promise<IEsploraApi.Transaction[]> {
throw new Error('Method getScriptHashTransactions not supported by the Bitcoin RPC API.');
}
$getRawMempool(): Promise<IEsploraApi.Transaction['txid'][]> {
return this.bitcoindClient.getRawMemPool();
}
@@ -174,6 +211,19 @@ class BitcoinApi implements AbstractBitcoinApi {
return outspends;
}
async $getBatchedOutspendsInternal(txId: string[]): Promise<IEsploraApi.Outspend[][]> {
return this.$getBatchedOutspends(txId);
}
async $getOutSpendsByOutpoint(outpoints: { txid: string, vout: number }[]): Promise<IEsploraApi.Outspend[]> {
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<number> {
// 120 is the default block span in Core
return this.bitcoindClient.getNetworkHashPs(120, blockHeight);
@@ -198,7 +248,7 @@ class BitcoinApi implements AbstractBitcoinApi {
scriptpubkey: vout.scriptPubKey.hex,
scriptpubkey_address: vout.scriptPubKey && vout.scriptPubKey.address ? vout.scriptPubKey.address
: vout.scriptPubKey.addresses ? vout.scriptPubKey.addresses[0] : '',
scriptpubkey_asm: vout.scriptPubKey.asm ? this.convertScriptSigAsm(vout.scriptPubKey.hex) : '',
scriptpubkey_asm: vout.scriptPubKey.asm ? transactionUtils.convertScriptSigAsm(vout.scriptPubKey.hex) : '',
scriptpubkey_type: this.translateScriptPubKeyType(vout.scriptPubKey.type),
};
});
@@ -208,7 +258,7 @@ class BitcoinApi implements AbstractBitcoinApi {
is_coinbase: !!vin.coinbase,
prevout: null,
scriptsig: vin.scriptSig && vin.scriptSig.hex || vin.coinbase || '',
scriptsig_asm: vin.scriptSig && this.convertScriptSigAsm(vin.scriptSig.hex) || '',
scriptsig_asm: vin.scriptSig && transactionUtils.convertScriptSigAsm(vin.scriptSig.hex) || '',
sequence: vin.sequence,
txid: vin.txid || '',
vout: vin.vout || 0,
@@ -280,7 +330,7 @@ class BitcoinApi implements AbstractBitcoinApi {
}
const innerTx = await this.$getRawTransaction(vin.txid, false, false);
vin.prevout = innerTx.vout[vin.vout];
this.addInnerScriptsToVin(vin);
transactionUtils.addInnerScriptsToVin(vin);
}
return transaction;
}
@@ -319,7 +369,7 @@ class BitcoinApi implements AbstractBitcoinApi {
}
const innerTx = await this.$getRawTransaction(transaction.vin[i].txid, false, false);
transaction.vin[i].prevout = innerTx.vout[transaction.vin[i].vout];
this.addInnerScriptsToVin(transaction.vin[i]);
transactionUtils.addInnerScriptsToVin(transaction.vin[i]);
totalIn += innerTx.vout[transaction.vin[i].vout].value;
}
if (lazyPrevouts && transaction.vin.length > 12) {
@@ -331,96 +381,11 @@ class BitcoinApi implements AbstractBitcoinApi {
return transaction;
}
private convertScriptSigAsm(hex: string): string {
const buf = Buffer.from(hex, 'hex');
public startHealthChecks(): void {};
const b: string[] = [];
let i = 0;
while (i < buf.length) {
const op = buf[i];
if (op >= 0x01 && op <= 0x4e) {
i++;
let push: number;
if (op === 0x4c) {
push = buf.readUInt8(i);
b.push('OP_PUSHDATA1');
i += 1;
} else if (op === 0x4d) {
push = buf.readUInt16LE(i);
b.push('OP_PUSHDATA2');
i += 2;
} else if (op === 0x4e) {
push = buf.readUInt32LE(i);
b.push('OP_PUSHDATA4');
i += 4;
} else {
push = op;
b.push('OP_PUSHBYTES_' + push);
}
const data = buf.slice(i, i + push);
if (data.length !== push) {
break;
}
b.push(data.toString('hex'));
i += data.length;
} else {
if (op === 0x00) {
b.push('OP_0');
} else if (op === 0x4f) {
b.push('OP_PUSHNUM_NEG1');
} else if (op === 0xb1) {
b.push('OP_CLTV');
} else if (op === 0xb2) {
b.push('OP_CSV');
} else if (op === 0xba) {
b.push('OP_CHECKSIGADD');
} else {
const opcode = bitcoinjs.script.toASM([ op ]);
if (opcode && op < 0xfd) {
if (/^OP_(\d+)$/.test(opcode)) {
b.push(opcode.replace(/^OP_(\d+)$/, 'OP_PUSHNUM_$1'));
} else {
b.push(opcode);
}
} else {
b.push('OP_RETURN_' + op);
}
}
i += 1;
}
}
return b.join(' ');
public getHealthStatus() {
return [];
}
private addInnerScriptsToVin(vin: IEsploraApi.Vin): void {
if (!vin.prevout) {
return;
}
if (vin.prevout.scriptpubkey_type === 'p2sh') {
const redeemScript = vin.scriptsig_asm.split(' ').reverse()[0];
vin.inner_redeemscript_asm = this.convertScriptSigAsm(redeemScript);
if (vin.witness && vin.witness.length > 2) {
const witnessScript = vin.witness[vin.witness.length - 1];
vin.inner_witnessscript_asm = this.convertScriptSigAsm(witnessScript);
}
}
if (vin.prevout.scriptpubkey_type === 'v0_p2wsh' && vin.witness) {
const witnessScript = vin.witness[vin.witness.length - 1];
vin.inner_witnessscript_asm = this.convertScriptSigAsm(witnessScript);
}
if (vin.prevout.scriptpubkey_type === 'v1_p2tr' && vin.witness && vin.witness.length > 1) {
const witnessScript = vin.witness[vin.witness.length - 2];
vin.inner_witnessscript_asm = this.convertScriptSigAsm(witnessScript);
}
}
}
export default BitcoinApi;

View File

@@ -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);

View File

@@ -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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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

View File

@@ -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);

View File

@@ -6,7 +6,7 @@ import websocketHandler from '../websocket-handler';
import mempool from '../mempool';
import feeApi from '../fee-api';
import mempoolBlocks from '../mempool-blocks';
import bitcoinApi, { bitcoinCoreApi } from './bitcoin-api-factory';
import bitcoinApi from './bitcoin-api-factory';
import { Common } from '../common';
import backendInfo from '../backend-info';
import transactionUtils from '../transaction-utils';
@@ -19,12 +19,12 @@ import bitcoinClient from './bitcoin-client';
import difficultyAdjustment from '../difficulty-adjustment';
import transactionRepository from '../../repositories/TransactionRepository';
import rbfCache from '../rbf-cache';
import { calculateCpfp } from '../cpfp';
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)
@@ -32,8 +32,10 @@ class BitcoinRoutes {
.get(config.MEMPOOL.API_URL_PREFIX + 'backend-info', this.getBackendInfo)
.get(config.MEMPOOL.API_URL_PREFIX + 'init-data', this.getInitData)
.get(config.MEMPOOL.API_URL_PREFIX + 'validate-address/:address', this.validateAddress)
.get(config.MEMPOOL.API_URL_PREFIX + 'tx/:txId/replaces', this.getRbfHistory)
.get(config.MEMPOOL.API_URL_PREFIX + 'tx/:txId/rbf', this.getRbfHistory)
.get(config.MEMPOOL.API_URL_PREFIX + 'tx/:txId/cached', this.getCachedTx)
.get(config.MEMPOOL.API_URL_PREFIX + 'replacements', this.getRbfReplacements)
.get(config.MEMPOOL.API_URL_PREFIX + 'fullrbf/replacements', this.getFullRbfReplacements)
.post(config.MEMPOOL.API_URL_PREFIX + 'tx/push', this.$postTransactionForm)
.get(config.MEMPOOL.API_URL_PREFIX + 'donations', async (req, res) => {
try {
@@ -94,6 +96,7 @@ class BitcoinRoutes {
.get(config.MEMPOOL.API_URL_PREFIX + 'block/:hash', this.getBlock)
.get(config.MEMPOOL.API_URL_PREFIX + 'block/:hash/summary', this.getStrippedBlockTransactions)
.get(config.MEMPOOL.API_URL_PREFIX + 'block/:hash/audit-summary', this.getBlockAuditSummary)
.get(config.MEMPOOL.API_URL_PREFIX + 'blocks/tip/height', this.getBlockTipHeight)
.post(config.MEMPOOL.API_URL_PREFIX + 'psbt/addparents', this.postPsbtCompletion)
.get(config.MEMPOOL.API_URL_PREFIX + 'blocks-bulk/:from', this.getBlocksByBulk.bind(this))
.get(config.MEMPOOL.API_URL_PREFIX + 'blocks-bulk/:from/:to', this.getBlocksByBulk.bind(this))
@@ -109,8 +112,8 @@ 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/height', this.getBlockTipHeight)
.get(config.MEMPOOL.API_URL_PREFIX + 'blocks/tip/hash', this.getBlockTipHash)
.get(config.MEMPOOL.API_URL_PREFIX + 'block/:hash/raw', this.getRawBlock)
.get(config.MEMPOOL.API_URL_PREFIX + 'block/:hash/txids', this.getTxIdsForBlock)
@@ -119,7 +122,10 @@ class BitcoinRoutes {
.get(config.MEMPOOL.API_URL_PREFIX + 'block-height/:height', this.getBlockHeight)
.get(config.MEMPOOL.API_URL_PREFIX + 'address/:address', this.getAddress)
.get(config.MEMPOOL.API_URL_PREFIX + 'address/:address/txs', this.getAddressTransactions)
.get(config.MEMPOOL.API_URL_PREFIX + 'address/:address/txs/chain/:txId', this.getAddressTransactions)
.get(config.MEMPOOL.API_URL_PREFIX + 'address/:address/txs/summary', this.getAddressTransactionSummary)
.get(config.MEMPOOL.API_URL_PREFIX + 'scripthash/:scripthash', this.getScriptHash)
.get(config.MEMPOOL.API_URL_PREFIX + 'scripthash/:scripthash/txs', this.getScriptHashTransactions)
.get(config.MEMPOOL.API_URL_PREFIX + 'scripthash/:scripthash/txs/summary', this.getScriptHashTransactionSummary)
.get(config.MEMPOOL.API_URL_PREFIX + 'address-prefix/:prefix', this.getAddressPrefix)
;
}
@@ -128,8 +134,9 @@ class BitcoinRoutes {
private getInitData(req: Request, res: Response) {
try {
const result = websocketHandler.getInitData();
res.json(result);
const result = websocketHandler.getSerializedInitData();
res.set('Content-Type', 'application/json');
res.send(result);
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
@@ -170,24 +177,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<IEsploraApi.Outspend[][] | void> {
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);
@@ -208,18 +211,26 @@ class BitcoinRoutes {
bestDescendant: tx.bestDescendant || null,
descendants: tx.descendants || null,
effectiveFeePerVsize: tx.effectiveFeePerVsize || null,
sigops: tx.sigops,
adjustedVsize: tx.adjustedVsize,
acceleration: tx.acceleration
});
return;
}
const cpfpInfo = Common.setRelativesAndGetCpfpInfo(tx, mempool.getMempool());
const cpfpInfo = calculateCpfp(tx, mempool.getMempool());
res.json(cpfpInfo);
return;
} else {
let cpfpInfo;
if (config.DATABASE.ENABLED) {
cpfpInfo = await transactionRepository.$getCpfpInfo(req.params.txId);
try {
cpfpInfo = await transactionRepository.$getCpfpInfo(req.params.txId);
} catch (e) {
res.status(500).send('failed to get CPFP info');
return;
}
}
if (cpfpInfo) {
res.json(cpfpInfo);
@@ -239,7 +250,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;
@@ -389,9 +400,13 @@ class BitcoinRoutes {
private async getBlockAuditSummary(req: Request, res: Response) {
try {
const transactions = await blocks.$getBlockAuditSummary(req.params.hash);
res.setHeader('Expires', new Date(Date.now() + 1000 * 3600 * 24 * 30).toUTCString());
res.json(transactions);
const auditSummary = await blocks.$getBlockAuditSummary(req.params.hash);
if (auditSummary) {
res.setHeader('Expires', new Date(Date.now() + 1000 * 3600 * 24 * 30).toUTCString());
res.json(auditSummary);
} else {
return res.status(404).send(`audit not available`);
}
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
@@ -403,7 +418,7 @@ class BitcoinRoutes {
const height = req.params.height === undefined ? undefined : parseInt(req.params.height, 10);
res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString());
res.json(await blocks.$getBlocks(height, 15));
} else { // Liquid, Bisq
} else { // Liquid
return await this.getLegacyBlocks(req, res);
}
} catch (e) {
@@ -413,7 +428,7 @@ class BitcoinRoutes {
private async getBlocksByBulk(req: Request, res: Response) {
try {
if (['mainnet', 'testnet', 'signet'].includes(config.MEMPOOL.NETWORK) === false) { // Liquid, Bisq - Not implemented
if (['mainnet', 'testnet', 'signet'].includes(config.MEMPOOL.NETWORK) === false) { // Liquid - Not implemented
return res.status(404).send(`This API is only available for Bitcoin networks`);
}
if (config.MEMPOOL.MAX_BLOCKS_BULK_QUERY <= 0) {
@@ -462,13 +477,13 @@ 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);
nextHash = localBlock.previousblockhash;
} else {
const block = await bitcoinCoreApi.$getBlock(nextHash);
const block = await bitcoinApi.$getBlock(nextHash);
returnBlocks.push(block);
nextHash = block.previousblockhash;
}
@@ -532,15 +547,46 @@ class BitcoinRoutes {
}
}
private async getAddressTransactions(req: Request, res: Response) {
private async getAddressTransactions(req: Request, res: Response): Promise<void> {
if (config.MEMPOOL.BACKEND === 'none') {
res.status(405).send('Address lookups cannot be used with bitcoind as backend.');
return;
}
try {
const transactions = await bitcoinApi.$getAddressTransactions(req.params.address, req.params.txId);
let lastTxId: string = '';
if (req.query.after_txid && typeof req.query.after_txid === 'string') {
lastTxId = req.query.after_txid;
}
const transactions = await bitcoinApi.$getAddressTransactions(req.params.address, lastTxId);
res.json(transactions);
} catch (e) {
if (e instanceof Error && e.message && (e.message.indexOf('too long') > 0 || e.message.indexOf('confirmed status') > 0)) {
res.status(413).send(e instanceof Error ? e.message : e);
return;
}
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async getAddressTransactionSummary(req: Request, res: Response): Promise<void> {
if (config.MEMPOOL.BACKEND !== 'esplora') {
res.status(405).send('Address summary lookups require mempool/electrs backend.');
return;
}
}
private async getScriptHash(req: Request, res: Response) {
if (config.MEMPOOL.BACKEND === 'none') {
res.status(405).send('Address lookups cannot be used with bitcoind as backend.');
return;
}
try {
// 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)) {
return res.status(413).send(e instanceof Error ? e.message : e);
@@ -549,8 +595,35 @@ class BitcoinRoutes {
}
}
private async getAdressTxChain(req: Request, res: Response) {
res.status(501).send('Not implemented');
private async getScriptHashTransactions(req: Request, res: Response): Promise<void> {
if (config.MEMPOOL.BACKEND === 'none') {
res.status(405).send('Address lookups cannot be used with bitcoind as backend.');
return;
}
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(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)) {
res.status(413).send(e instanceof Error ? e.message : e);
return;
}
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async getScriptHashTransactionSummary(req: Request, res: Response): Promise<void> {
if (config.MEMPOOL.BACKEND !== 'esplora') {
res.status(405).send('Scripthash summary lookups require mempool/electrs backend.');
return;
}
}
private async getAddressPrefix(req: Request, res: Response) {
@@ -589,10 +662,14 @@ class BitcoinRoutes {
}
}
private async getBlockTipHeight(req: Request, res: Response) {
private getBlockTipHeight(req: Request, res: Response) {
try {
const result = await bitcoinApi.$getBlockHeightTip();
res.json(result);
const result = blocks.getCurrentBlockHeight();
if (!result) {
return res.status(503).send(`Service Temporarily Unavailable`);
}
res.setHeader('content-type', 'text/plain');
res.send(result.toString());
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
@@ -638,8 +715,30 @@ class BitcoinRoutes {
private async getRbfHistory(req: Request, res: Response) {
try {
const result = rbfCache.getReplaces(req.params.txId);
res.json(result || []);
const replacements = rbfCache.getRbfTree(req.params.txId) || null;
const replaces = rbfCache.getReplaces(req.params.txId) || null;
res.json({
replacements,
replaces
});
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async getRbfReplacements(req: Request, res: Response) {
try {
const result = rbfCache.getRbfTrees(false);
res.json(result);
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async getFullRbfReplacements(req: Request, res: Response) {
try {
const result = rbfCache.getRbfTrees(true);
res.json(result);
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
@@ -683,12 +782,7 @@ class BitcoinRoutes {
private async $postTransaction(req: Request, res: Response) {
res.setHeader('content-type', 'text/plain');
try {
let rawTx;
if (typeof req.body === 'object') {
rawTx = Object.keys(req.body)[0];
} else {
rawTx = req.body;
}
const rawTx = Common.getTransactionFromRequest(req, false);
const txIdResult = await bitcoinApi.$sendRawTransaction(rawTx);
res.send(txIdResult);
} catch (e: any) {
@@ -699,12 +793,8 @@ class BitcoinRoutes {
private async $postTransactionForm(req: Request, res: Response) {
res.setHeader('content-type', 'text/plain');
const matches = /tx=([a-z0-9]+)/.exec(req.body);
let txHex = '';
if (matches && matches[1]) {
txHex = matches[1];
}
try {
const txHex = Common.getTransactionFromRequest(req, true);
const txIdResult = await bitcoinClient.sendRawTransaction(txHex);
res.send(txIdResult);
} catch (e: any) {

View File

@@ -16,7 +16,7 @@ class BitcoindElectrsApi extends BitcoinApi implements AbstractBitcoinApi {
super(bitcoinClient);
const electrumConfig = { client: 'mempool-v2', version: '1.4' };
const electrumPersistencePolicy = { retryPeriod: 10000, maxRetry: 1000, callback: null };
const electrumPersistencePolicy = { retryPeriod: 1000, maxRetry: Number.MAX_SAFE_INTEGER, callback: null };
const electrumCallbacks = {
onConnect: (client, versionInfo) => { logger.info(`Connected to Electrum Server at ${config.ELECTRUM.HOST}:${config.ELECTRUM.PORT} (${JSON.stringify(versionInfo)})`); },
@@ -126,6 +126,77 @@ class BitcoindElectrsApi extends BitcoinApi implements AbstractBitcoinApi {
}
}
async $getScriptHash(scripthash: string): Promise<IEsploraApi.ScriptHash> {
try {
const balance = await this.electrumClient.blockchainScripthash_getBalance(scripthash);
let history = memoryCache.get<IElectrumApi.ScriptHashHistory[]>('Scripthash_getHistory', scripthash);
if (!history) {
history = await this.electrumClient.blockchainScripthash_getHistory(scripthash);
memoryCache.set('Scripthash_getHistory', scripthash, history, 2);
}
const unconfirmed = history ? history.filter((h) => h.fee).length : 0;
return {
'scripthash': scripthash,
'chain_stats': {
'funded_txo_count': 0,
'funded_txo_sum': balance.confirmed ? balance.confirmed : 0,
'spent_txo_count': 0,
'spent_txo_sum': balance.confirmed < 0 ? balance.confirmed : 0,
'tx_count': (history?.length || 0) - unconfirmed,
},
'mempool_stats': {
'funded_txo_count': 0,
'funded_txo_sum': balance.unconfirmed > 0 ? balance.unconfirmed : 0,
'spent_txo_count': 0,
'spent_txo_sum': balance.unconfirmed < 0 ? -balance.unconfirmed : 0,
'tx_count': unconfirmed,
},
'electrum': true,
};
} catch (e: any) {
throw new Error(typeof e === 'string' ? e : e && e.message || e);
}
}
async $getScriptHashTransactions(scripthash: string, lastSeenTxId?: string): Promise<IEsploraApi.Transaction[]> {
try {
loadingIndicators.setProgress('address-' + scripthash, 0);
const transactions: IEsploraApi.Transaction[] = [];
let history = memoryCache.get<IElectrumApi.ScriptHashHistory[]>('Scripthash_getHistory', scripthash);
if (!history) {
history = await this.electrumClient.blockchainScripthash_getHistory(scripthash);
memoryCache.set('Scripthash_getHistory', scripthash, history, 2);
}
if (!history) {
throw new Error('failed to get scripthash history');
}
history.sort((a, b) => (b.height || 9999999) - (a.height || 9999999));
let startingIndex = 0;
if (lastSeenTxId) {
const pos = history.findIndex((historicalTx) => historicalTx.tx_hash === lastSeenTxId);
if (pos) {
startingIndex = pos + 1;
}
}
const endIndex = Math.min(startingIndex + 10, history.length);
for (let i = startingIndex; i < endIndex; i++) {
const tx = await this.$getRawTransaction(history[i].tx_hash, false, true);
transactions.push(tx);
loadingIndicators.setProgress('address-' + scripthash, (i + 1) / endIndex * 100);
}
return transactions;
} catch (e: any) {
loadingIndicators.setProgress('address-' + scripthash, 100);
throw new Error(typeof e === 'string' ? e : e && e.message || e);
}
}
private $getScriptHashBalance(scriptHash: string): Promise<IElectrumApi.ScriptHashBalance> {
return this.electrumClient.blockchainScripthash_getBalance(this.encodeScriptHash(scriptHash));
}

View File

@@ -6,6 +6,7 @@ export namespace IEsploraApi {
size: number;
weight: number;
fee: number;
sigops?: number;
vin: Vin[];
vout: Vout[];
status: Status;
@@ -89,6 +90,7 @@ export namespace IEsploraApi {
weight: number;
previousblockhash: string;
mediantime: number;
stale: boolean;
}
export interface Address {
@@ -98,6 +100,13 @@ export namespace IEsploraApi {
electrum?: boolean;
}
export interface ScriptHash {
scripthash: string;
chain_stats: ChainStats;
mempool_stats: MempoolStats;
electrum?: boolean;
}
export interface ChainStats {
funded_txo_count: number;
funded_txo_sum: number;

View File

@@ -1,67 +1,305 @@
import config from '../../config';
import axios, { AxiosRequestConfig } from 'axios';
import axios, { AxiosResponse, isAxiosError } 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';
const axiosConnection = axios.create({
httpAgent: new http.Agent({ keepAlive: true })
});
interface FailoverHost {
host: string,
rtts: number[],
rtt: number,
timedOut?: boolean,
failures: number,
latestHeight?: number,
socket?: boolean,
outOfSync?: boolean,
unreachable?: boolean,
preferred?: boolean,
checked: boolean,
lastChecked?: number,
}
class FailoverRouter {
activeHost: FailoverHost;
fallbackHost: FailoverHost;
maxHeight: number = 0;
hosts: FailoverHost[];
multihost: boolean;
pollInterval: number = 60000;
pollTimer: NodeJS.Timeout | null = null;
pollConnection = axios.create();
requestConnection = axios.create({
httpAgent: new http.Agent({ keepAlive: true })
});
constructor() {
// setup list of hosts
this.hosts = (config.ESPLORA.FALLBACK || []).map(domain => {
return {
host: domain,
checked: false,
rtts: [],
rtt: Infinity,
failures: 0,
};
});
this.activeHost = {
host: config.ESPLORA.UNIX_SOCKET_PATH || config.ESPLORA.REST_API_URL,
rtts: [],
rtt: 0,
failures: 0,
socket: !!config.ESPLORA.UNIX_SOCKET_PATH,
preferred: true,
checked: false,
};
this.fallbackHost = this.activeHost;
this.hosts.unshift(this.activeHost);
this.multihost = this.hosts.length > 1;
}
public startHealthChecks(): void {
// use axios interceptors to measure request rtt
this.pollConnection.interceptors.request.use((config) => {
config['meta'] = { startTime: Date.now() };
return config;
});
this.pollConnection.interceptors.response.use((response) => {
response.config['meta'].rtt = Date.now() - response.config['meta'].startTime;
return response;
});
if (this.multihost) {
this.pollHosts();
}
}
// start polling hosts to measure availability & rtt
private async pollHosts(): Promise<void> {
if (this.pollTimer) {
clearTimeout(this.pollTimer);
}
const start = Date.now();
// update rtts & sync status
for (const host of this.hosts) {
try {
const result = await (host.socket
? this.pollConnection.get<number>('/blocks/tip/height', { socketPath: host.host, timeout: config.ESPLORA.FALLBACK_TIMEOUT })
: this.pollConnection.get<number>(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 = true;
host.unreachable = true;
host.rtts = [];
host.rtt = Infinity;
}
host.timedOut = false;
} catch (e) {
host.outOfSync = true;
host.unreachable = true;
host.rtts = [];
host.rtt = Infinity;
if (isAxiosError(e) && (e.code === 'ECONNABORTED' || e.code === 'ETIMEDOUT')) {
host.timedOut = true;
} else {
host.timedOut = false;
}
}
host.checked = true;
host.lastChecked = Date.now();
// 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);
}
const rankOrder = this.updateFallback();
logger.debug(`Tomahawk ranking:\n${rankOrder.map((host, index) => this.formatRanking(index, host, this.activeHost, this.maxHeight)).join('\n')}`);
const elapsed = Date.now() - start;
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.timedOut ? ' ⌛️💥 ' : ' - ')} ${!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];
}
return rankOrder;
}
// sort hosts by connection quality, and update default fallback
public sortHosts(): FailoverHost[] {
// sort by connection quality
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
return a.rtt - b.rtt;
} else { // unless we have a preferred host
return a.preferred ? -1 : 1;
}
} else { // or the host is out of sync
return (a.unreachable || a.outOfSync) ? 1 : -1;
}
});
}
// depose the active host and choose the next best replacement
private electHost(): void {
this.activeHost.outOfSync = true;
this.activeHost.failures = 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 🚨🚨🚨`);
this.electHost();
return this.activeHost;
} else {
return this.fallbackHost;
}
}
private async $query<T>(method: 'get'| 'post', path, data: any, responseType = 'json', host = this.activeHost, retry: boolean = true): Promise<T> {
let axiosConfig;
let url;
if (host.socket) {
axiosConfig = { socketPath: host.host, timeout: config.ESPLORA.REQUEST_TIMEOUT, responseType };
url = path;
} else {
axiosConfig = { timeout: config.ESPLORA.REQUEST_TIMEOUT, responseType };
url = host.host + path;
}
if (data?.params) {
axiosConfig.params = data.params;
}
return (method === 'post'
? this.requestConnection.post<T>(url, data, axiosConfig)
: this.requestConnection.get<T>(url, axiosConfig)
).then((response) => { host.failures = Math.max(0, host.failures - 1); return response.data; })
.catch((e) => {
let fallbackHost = this.fallbackHost;
if (e?.response?.status !== 404) {
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) {
// Retry immediately
return this.$query(method, path, data, responseType, fallbackHost, false);
} else {
throw e;
}
});
}
public async $get<T>(path, responseType = 'json', params: any = null): Promise<T> {
return this.$query<T>('get', path, params ? { params } : null, responseType);
}
public async $post<T>(path, data: any, responseType = 'json'): Promise<T> {
return this.$query<T>('post', path, data, responseType);
}
}
class ElectrsApi implements AbstractBitcoinApi {
axiosConfig: AxiosRequestConfig = {
timeout: 10000,
};
constructor() { }
private failoverRouter = new FailoverRouter();
$getRawMempool(): Promise<IEsploraApi.Transaction['txid'][]> {
return axiosConnection.get<IEsploraApi.Transaction['txid'][]>(config.ESPLORA.REST_API_URL + '/mempool/txids', this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<IEsploraApi.Transaction['txid'][]>('/mempool/txids');
}
$getRawTransaction(txId: string): Promise<IEsploraApi.Transaction> {
return axiosConnection.get<IEsploraApi.Transaction>(config.ESPLORA.REST_API_URL + '/tx/' + txId, this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<IEsploraApi.Transaction>('/tx/' + txId);
}
async $getRawTransactions(txids: string[]): Promise<IEsploraApi.Transaction[]> {
return this.failoverRouter.$post<IEsploraApi.Transaction[]>('/internal/txs', txids, 'json');
}
async $getMempoolTransactions(txids: string[]): Promise<IEsploraApi.Transaction[]> {
return this.failoverRouter.$post<IEsploraApi.Transaction[]>('/internal/mempool/txs', txids, 'json');
}
async $getAllMempoolTransactions(lastSeenTxid?: string, max_txs?: number): Promise<IEsploraApi.Transaction[]> {
return this.failoverRouter.$get<IEsploraApi.Transaction[]>('/internal/mempool/txs' + (lastSeenTxid ? '/' + lastSeenTxid : ''), 'json', max_txs ? { max_txs } : null);
}
$getTransactionHex(txId: string): Promise<string> {
return axiosConnection.get<string>(config.ESPLORA.REST_API_URL + '/tx/' + txId + '/hex', this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<string>('/tx/' + txId + '/hex');
}
$getBlockHeightTip(): Promise<number> {
return axiosConnection.get<number>(config.ESPLORA.REST_API_URL + '/blocks/tip/height', this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<number>('/blocks/tip/height');
}
$getBlockHashTip(): Promise<string> {
return axiosConnection.get<string>(config.ESPLORA.REST_API_URL + '/blocks/tip/hash', this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<string>('/blocks/tip/hash');
}
$getTxIdsForBlock(hash: string): Promise<string[]> {
return axiosConnection.get<string[]>(config.ESPLORA.REST_API_URL + '/block/' + hash + '/txids', this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<string[]>('/block/' + hash + '/txids');
}
$getTxsForBlock(hash: string): Promise<IEsploraApi.Transaction[]> {
return this.failoverRouter.$get<IEsploraApi.Transaction[]>('/internal/block/' + hash + '/txs');
}
$getBlockHash(height: number): Promise<string> {
return axiosConnection.get<string>(config.ESPLORA.REST_API_URL + '/block-height/' + height, this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<string>('/block-height/' + height);
}
$getBlockHeader(hash: string): Promise<string> {
return axiosConnection.get<string>(config.ESPLORA.REST_API_URL + '/block/' + hash + '/header', this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<string>('/block/' + hash + '/header');
}
$getBlock(hash: string): Promise<IEsploraApi.Block> {
return axiosConnection.get<IEsploraApi.Block>(config.ESPLORA.REST_API_URL + '/block/' + hash, this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<IEsploraApi.Block>('/block/' + hash);
}
$getRawBlock(hash: string): Promise<Buffer> {
return axiosConnection.get<string>(config.ESPLORA.REST_API_URL + '/block/' + hash + "/raw", { ...this.axiosConfig, responseType: 'arraybuffer' })
return this.failoverRouter.$get<any>('/block/' + hash + '/raw', 'arraybuffer')
.then((response) => { return Buffer.from(response.data); });
}
@@ -73,6 +311,14 @@ class ElectrsApi implements AbstractBitcoinApi {
throw new Error('Method getAddressTransactions not implemented.');
}
$getScriptHash(scripthash: string): Promise<IEsploraApi.ScriptHash> {
throw new Error('Method getScriptHash not implemented.');
}
$getScriptHashTransactions(scripthash: string, txId?: string): Promise<IEsploraApi.Transaction[]> {
throw new Error('Method getScriptHashTransactions not implemented.');
}
$getAddressPrefix(prefix: string): string[] {
throw new Error('Method not implemented.');
}
@@ -82,22 +328,45 @@ class ElectrsApi implements AbstractBitcoinApi {
}
$getOutspend(txId: string, vout: number): Promise<IEsploraApi.Outspend> {
return axiosConnection.get<IEsploraApi.Outspend>(config.ESPLORA.REST_API_URL + '/tx/' + txId + '/outspend/' + vout, this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<IEsploraApi.Outspend>('/tx/' + txId + '/outspend/' + vout);
}
$getOutspends(txId: string): Promise<IEsploraApi.Outspend[]> {
return axiosConnection.get<IEsploraApi.Outspend[]>(config.ESPLORA.REST_API_URL + '/tx/' + txId + '/outspends', this.axiosConfig)
.then((response) => response.data);
return this.failoverRouter.$get<IEsploraApi.Outspend[]>('/tx/' + txId + '/outspends');
}
async $getBatchedOutspends(txId: string[]): Promise<IEsploraApi.Outspend[][]> {
const outspends: IEsploraApi.Outspend[][] = [];
for (const tx of txId) {
const outspend = await this.$getOutspends(tx);
outspends.push(outspend);
async $getBatchedOutspends(txids: string[]): Promise<IEsploraApi.Outspend[][]> {
throw new Error('Method not implemented.');
}
async $getBatchedOutspendsInternal(txids: string[]): Promise<IEsploraApi.Outspend[][]> {
return this.failoverRouter.$post<IEsploraApi.Outspend[][]>('/internal/txs/outspends/by-txid', txids, 'json');
}
async $getOutSpendsByOutpoint(outpoints: { txid: string, vout: number }[]): Promise<IEsploraApi.Outspend[]> {
return this.failoverRouter.$post<IEsploraApi.Outspend[]>('/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,
lastChecked: host.lastChecked || 0,
}));
} else {
return [];
}
return outspends;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,30 @@
import { CpfpInfo, MempoolBlockWithTransactions, TransactionExtended, TransactionStripped } from '../mempool.interfaces';
import * as bitcoinjs from 'bitcoinjs-lib';
import { Request } from 'express';
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'
@@ -57,35 +80,486 @@ export class Common {
return arr;
}
static findRbfTransactions(added: TransactionExtended[], deleted: TransactionExtended[]): { [txid: string]: TransactionExtended } {
const matches: { [txid: string]: TransactionExtended } = {};
deleted
.forEach((deletedTx) => {
const foundMatches = added.find((addedTx) => {
static findRbfTransactions(added: MempoolTransactionExtended[], deleted: MempoolTransactionExtended[], forceScalable = false): { [txid: string]: MempoolTransactionExtended[] } {
const matches: { [txid: string]: MempoolTransactionExtended[] } = {};
// For small N, a naive nested loop is extremely fast, but it doesn't scale
if (added.length < 1000 && deleted.length < 50 && !forceScalable) {
added.forEach((addedTx) => {
const foundMatches = deleted.filter((deletedTx) => {
// The new tx must, absolutely speaking, pay at least as much fee as the replaced tx.
return addedTx.fee > deletedTx.fee
// The new transaction must pay more fee per kB than the replaced tx.
&& addedTx.feePerVsize > deletedTx.feePerVsize
&& addedTx.adjustedFeePerVsize > deletedTx.adjustedFeePerVsize
// Spends one or more of the same inputs
&& deletedTx.vin.some((deletedVin) =>
addedTx.vin.some((vin) => vin.txid === deletedVin.txid && vin.vout === deletedVin.vout));
});
if (foundMatches) {
matches[deletedTx.txid] = foundMatches;
if (foundMatches?.length) {
matches[addedTx.txid] = [...new Set(foundMatches)];
}
});
} else {
// for large N, build a lookup table of prevouts we can check in ~constant time
const deletedSpendMap: { [txid: string]: { [vout: number]: MempoolTransactionExtended } } = {};
for (const tx of deleted) {
for (const vin of tx.vin) {
if (!deletedSpendMap[vin.txid]) {
deletedSpendMap[vin.txid] = {};
}
deletedSpendMap[vin.txid][vin.vout] = tx;
}
}
for (const addedTx of added) {
const foundMatches = new Set<MempoolTransactionExtended>();
for (const vin of addedTx.vin) {
const deletedTx = deletedSpendMap[vin.txid]?.[vin.vout];
if (deletedTx && deletedTx.txid !== addedTx.txid
// The new tx must, absolutely speaking, pay at least as much fee as the replaced tx.
&& addedTx.fee > deletedTx.fee
// The new transaction must pay more fee per kB than the replaced tx.
&& addedTx.adjustedFeePerVsize > deletedTx.adjustedFeePerVsize
) {
foundMatches.add(deletedTx);
}
if (foundMatches.size) {
matches[addedTx.txid] = [...foundMatches];
}
}
}
}
return matches;
}
static findMinedRbfTransactions(minedTransactions: TransactionExtended[], spendMap: Map<string, MempoolTransactionExtended>): { [txid: string]: { replaced: MempoolTransactionExtended[], replacedBy: TransactionExtended }} {
const matches: { [txid: string]: { replaced: MempoolTransactionExtended[], replacedBy: TransactionExtended }} = {};
for (const tx of minedTransactions) {
const replaced: Set<MempoolTransactionExtended> = new Set();
for (let i = 0; i < tx.vin.length; i++) {
const vin = tx.vin[i];
const match = spendMap.get(`${vin.txid}:${vin.vout}`);
if (match && match.txid !== tx.txid) {
replaced.add(match);
// remove this tx from the spendMap
// prevents the same tx being replaced more than once
for (const replacedVin of match.vin) {
const key = `${replacedVin.txid}:${replacedVin.vout}`;
spendMap.delete(key);
}
}
const key = `${vin.txid}:${vin.vout}`;
spendMap.delete(key);
}
if (replaced.size) {
matches[tx.txid] = { replaced: Array.from(replaced), replacedBy: tx };
}
}
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
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;
let P2WSHCount = 0;
let olgaSize = 0;
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;
}
if (vout.scriptpubkey_type === 'v0_p2wsh') {
if (!P2WSHCount) {
olgaSize = parseInt(vout.scriptpubkey.slice(4, 8), 16);
}
P2WSHCount++;
if (P2WSHCount === Math.ceil((olgaSize + 2) / 32)) {
const nullBytes = (P2WSHCount * 32) - olgaSize - 2;
if (vout.scriptpubkey.endsWith(''.padEnd(nullBytes * 2, '0'))) {
flags |= TransactionFlags.fake_scripthash;
}
}
} else {
P2WSHCount = 0;
}
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,
fee: tx.fee,
fee: tx.fee || 0,
vsize: tx.weight / 4,
value: tx.vout.reduce((acc, vout) => acc + (vout.value ? vout.value : 0), 0),
acc: tx.acceleration || undefined,
rate: tx.effectiveFeePerVsize,
time: tx.firstSeen || undefined,
};
}
static stripTransactions(txs: TransactionExtended[]): TransactionStripped[] {
return txs.map(Common.stripTransaction);
}
static sleep$(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
@@ -101,69 +575,6 @@ export class Common {
}
}
static setRelativesAndGetCpfpInfo(tx: TransactionExtended, memPool: { [txid: string]: TransactionExtended }): CpfpInfo {
const parents = this.findAllParents(tx, memPool);
const lowerFeeParents = parents.filter((parent) => parent.feePerVsize < tx.effectiveFeePerVsize);
let totalWeight = tx.weight + lowerFeeParents.reduce((prev, val) => prev + val.weight, 0);
let totalFees = tx.fee + lowerFeeParents.reduce((prev, val) => prev + val.fee, 0);
tx.ancestors = parents
.map((t) => {
return {
txid: t.txid,
weight: t.weight,
fee: t.fee,
};
});
// Add high (high fee) decendant weight and fees
if (tx.bestDescendant) {
totalWeight += tx.bestDescendant.weight;
totalFees += tx.bestDescendant.fee;
}
tx.effectiveFeePerVsize = Math.max(0, totalFees / (totalWeight / 4));
tx.cpfpChecked = true;
return {
ancestors: tx.ancestors,
bestDescendant: tx.bestDescendant || null,
};
}
private static findAllParents(tx: TransactionExtended, memPool: { [txid: string]: TransactionExtended }): TransactionExtended[] {
let parents: TransactionExtended[] = [];
tx.vin.forEach((parent) => {
if (parents.find((p) => p.txid === parent.txid)) {
return;
}
const parentTx = memPool[parent.txid];
if (parentTx) {
if (tx.bestDescendant && tx.bestDescendant.fee / (tx.bestDescendant.weight / 4) > parentTx.feePerVsize) {
if (parentTx.bestDescendant && parentTx.bestDescendant.fee < tx.fee + tx.bestDescendant.fee) {
parentTx.bestDescendant = {
weight: tx.weight + tx.bestDescendant.weight,
fee: tx.fee + tx.bestDescendant.fee,
txid: tx.txid,
};
}
} else if (tx.feePerVsize > parentTx.feePerVsize) {
parentTx.bestDescendant = {
weight: tx.weight,
fee: tx.fee,
txid: tx.txid
};
}
parents.push(parentTx);
parents = parents.concat(this.findAllParents(parentTx, memPool));
}
});
return parents;
}
// calculates the ratio of matched transactions to projected transactions by weight
static getSimilarity(projectedBlock: MempoolBlockWithTransactions, transactions: TransactionExtended[]): number {
let matchedWeight = 0;
@@ -219,6 +630,13 @@ export class Common {
);
}
static gogglesIndexingEnabled(): boolean {
return (
Common.blocksSummariesIndexingEnabled() &&
config.MEMPOOL.GOGGLES_INDEXING === true
);
}
static cpfpIndexingEnabled(): boolean {
return (
Common.indexingEnabled() &&
@@ -345,4 +763,373 @@ export class Common {
};
}
}
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: { [txid: string]: TransactionExtended } = {};
// initialize the txMap
for (const tx of transactions) {
txMap[tx.txid] = tx;
}
// reverse pass to identify CPFP clusters
for (let i = transactions.length - 1; i >= 0; i--) {
const tx = transactions[i];
if (!ancestors[tx.txid]) {
let totalFee = 0;
let totalVSize = 0;
clusterTxs.forEach(tx => {
totalFee += tx?.fee || 0;
totalVSize += (tx.weight / 4);
});
const effectiveFeePerVsize = totalFee / totalVSize;
let cluster: CpfpCluster;
if (clusterTxs.length > 1) {
cluster = {
root: clusterTxs[0].txid,
height,
txs: clusterTxs.map(tx => { return { txid: tx.txid, weight: tx.weight, fee: tx.fee || 0 }; }),
effectiveFeePerVsize,
};
clusters.push(cluster);
}
clusterTxs.forEach(tx => {
txMap[tx.txid].effectiveFeePerVsize = effectiveFeePerVsize;
if (cluster) {
clusterMap[tx.txid] = cluster;
}
});
// reset working vars
clusterTxs = [];
ancestors = {};
}
clusterTxs.push(tx);
tx.vin.forEach(vin => {
ancestors[vin.txid] = true;
});
}
// forward pass to enforce ancestor rate caps
for (const tx of transactions) {
let minAncestorRate = tx.effectiveFeePerVsize;
for (const vin of tx.vin) {
if (txMap[vin.txid]?.effectiveFeePerVsize) {
minAncestorRate = Math.min(minAncestorRate, txMap[vin.txid].effectiveFeePerVsize);
}
}
// check rounded values to skip cases with almost identical fees
const roundedMinAncestorRate = Math.ceil(minAncestorRate);
const roundedEffectiveFeeRate = Math.floor(tx.effectiveFeePerVsize);
if (roundedMinAncestorRate < roundedEffectiveFeeRate) {
tx.effectiveFeePerVsize = minAncestorRate;
if (!clusterMap[tx.txid]) {
// add a single-tx cluster to record the dependent rate
const cluster = {
root: tx.txid,
height,
txs: [{ txid: tx.txid, weight: tx.weight, fee: tx.fee || 0 }],
effectiveFeePerVsize: minAncestorRate,
};
clusterMap[tx.txid] = cluster;
clusters.push(cluster);
} else {
// update the existing cluster with the dependent rate
clusterMap[tx.txid].effectiveFeePerVsize = minAncestorRate;
}
}
}
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,
};
}
static calcEffectiveFeeStatistics(transactions: { weight: number, fee: number, effectiveFeePerVsize?: number, txid: string, acceleration?: boolean }[]): EffectiveFeeStats {
const sortedTxs = transactions.map(tx => { return { txid: tx.txid, weight: tx.weight, rate: tx.effectiveFeePerVsize || ((tx.fee || 0) / (tx.weight / 4)) }; }).sort((a, b) => a.rate - b.rate);
let weightCount = 0;
let medianFee = 0;
let medianWeight = 0;
// calculate the "medianFee" as the average fee rate of the middle 10000 weight units of transactions
const leftBound = 1995000;
const rightBound = 2005000;
for (let i = 0; i < sortedTxs.length && weightCount < rightBound; i++) {
const left = weightCount;
const right = weightCount + sortedTxs[i].weight;
if (right > leftBound) {
const weight = Math.min(right, rightBound) - Math.max(left, leftBound);
medianFee += (sortedTxs[i].rate * (weight / 4) );
medianWeight += weight;
}
weightCount += sortedTxs[i].weight;
}
const medianFeeRate = medianWeight ? (medianFee / (medianWeight / 4)) : 0;
// minimum effective fee heuristic:
// lowest of
// a) the 1st percentile of effective fee rates
// b) the minimum effective fee rate in the last 2% of transactions (in block order)
const minFee = Math.min(
Common.getNthPercentile(1, sortedTxs).rate,
transactions.slice(-transactions.length / 50).reduce((min, tx) => { return Math.min(min, tx.effectiveFeePerVsize || ((tx.fee || 0) / (tx.weight / 4))); }, Infinity)
);
// maximum effective fee heuristic:
// highest of
// a) the 99th percentile of effective fee rates
// b) the maximum effective fee rate in the first 2% of transactions (in block order)
const maxFee = Math.max(
Common.getNthPercentile(99, sortedTxs).rate,
transactions.slice(0, transactions.length / 50).reduce((max, tx) => { return Math.max(max, tx.effectiveFeePerVsize || ((tx.fee || 0) / (tx.weight / 4))); }, 0)
);
return {
medianFee: medianFeeRate,
feeRange: [
minFee,
[10,25,50,75,90].map(n => Common.getNthPercentile(n, sortedTxs).rate),
maxFee,
].flat(),
};
}
static getNthPercentile(n: number, sortedDistribution: any[]): any {
return sortedDistribution[Math.floor((sortedDistribution.length - 1) * (n / 100))];
}
static getTransactionFromRequest(req: Request, form: boolean): string {
let rawTx: any = typeof req.body === 'object' && form
? Object.values(req.body)[0] as any
: req.body;
if (typeof rawTx !== 'string') {
throw Object.assign(new Error('Non-string request body'), { code: -1 });
}
// Support both upper and lower case hex
// Support both txHash= Form and direct API POST
const reg = form ? /^txHash=((?:[a-fA-F0-9]{2})+)$/ : /^((?:[a-fA-F0-9]{2})+)$/;
const matches = reg.exec(rawTx);
if (!matches || !matches[1]) {
throw Object.assign(new Error('Non-hex request body'), { code: -2 });
}
// Guaranteed to be a hex string of multiple of 2
// Guaranteed to be lower case
// Guaranteed to pass validation (see function below)
return this.validateTransactionHex(matches[1].toLowerCase());
}
private static validateTransactionHex(txhex: string): string {
// Do not mutate txhex
// We assume txhex to be valid hex (output of getTransactionFromRequest above)
// Check 1: Valid transaction parse
let tx: bitcoinjs.Transaction;
try {
tx = bitcoinjs.Transaction.fromHex(txhex);
} catch(e) {
throw Object.assign(new Error('Invalid transaction (could not parse)'), { code: -4 });
}
// Check 2: Simple size check
if (tx.weight() > config.MEMPOOL.MAX_PUSH_TX_SIZE_WEIGHT) {
throw Object.assign(new Error(`Transaction too large (max ${config.MEMPOOL.MAX_PUSH_TX_SIZE_WEIGHT} weight units)`), { code: -3 });
}
// Check 3: Check unreachable script in taproot (if not allowed)
if (!config.MEMPOOL.ALLOW_UNREACHABLE) {
tx.ins.forEach(input => {
const witness = input.witness;
// See BIP 341: Script validation rules
const hasAnnex = witness.length >= 2 &&
witness[witness.length - 1][0] === 0x50;
const scriptSpendMinLength = hasAnnex ? 3 : 2;
const maybeScriptSpend = witness.length >= scriptSpendMinLength;
if (maybeScriptSpend) {
const controlBlock = witness[witness.length - scriptSpendMinLength + 1];
if (controlBlock.length === 0 || !this.isValidLeafVersion(controlBlock[0])) {
// Skip this input, it's not taproot
return;
}
// Definitely taproot. Get script
const script = witness[witness.length - scriptSpendMinLength];
const decompiled = bitcoinjs.script.decompile(script);
if (!decompiled || decompiled.length < 2) {
// Skip this input
return;
}
// Iterate up to second last (will look ahead 1 item)
for (let i = 0; i < decompiled.length - 1; i++) {
const first = decompiled[i];
const second = decompiled[i + 1];
if (
first === bitcoinjs.opcodes.OP_FALSE &&
second === bitcoinjs.opcodes.OP_IF
) {
throw Object.assign(new Error('Unreachable taproot scripts not allowed'), { code: -5 });
}
}
}
})
}
// Pass through the input string untouched
return txhex;
}
private static isValidLeafVersion(leafVersion: number): boolean {
// See Note 7 in BIP341
// https://github.com/bitcoin/bips/blob/66a1a8151021913047934ebab3f8883f2f8ca75b/bip-0341.mediawiki#cite_note-7
// "What constraints are there on the leaf version?"
// Must be an integer between 0 and 255
// Since we're parsing a byte
if (Math.floor(leafVersion) !== leafVersion || leafVersion < 0 || leafVersion > 255) {
return false;
}
// "the leaf version cannot be odd"
if ((leafVersion & 0x01) === 1) {
return false;
}
// "The values that comply to this rule are
// the 32 even values between 0xc0 and 0xfe
if (leafVersion >= 0xc0 && leafVersion <= 0xfe) {
return true;
}
// and also 0x66, 0x7e, 0x80, 0x84, 0x96, 0x98, 0xba, 0xbc, 0xbe."
if ([0x66, 0x7e, 0x80, 0x84, 0x96, 0x98, 0xba, 0xbc, 0xbe].includes(leafVersion)) {
return true;
}
// Otherwise, invalid
return false;
}
}
/**
* Class to calculate average fee rates of a list of transactions
* at certain weight percentiles, in a single pass
*
* init with:
* maxWeight - the total weight to measure percentiles relative to (e.g. 4MW for a single block)
* percentileBandWidth - how many weight units to average over for each percentile (as a % of maxWeight)
* percentiles - an array of weight percentiles to compute, in %
*
* then call .processNext(tx) for each transaction, in descending order
*
* retrieve the final results with .getFeeStats()
*/
export class OnlineFeeStatsCalculator {
private maxWeight: number;
private percentiles = [10,25,50,75,90];
private bandWidthPercent = 2;
private bandWidth: number = 0;
private bandIndex = 0;
private leftBound = 0;
private rightBound = 0;
private inBand = false;
private totalBandFee = 0;
private totalBandWeight = 0;
private minBandRate = Infinity;
private maxBandRate = 0;
private feeRange: { avg: number, min: number, max: number }[] = [];
private totalWeight: number = 0;
constructor (maxWeight: number, percentileBandWidth?: number, percentiles?: number[]) {
this.maxWeight = maxWeight;
if (percentiles && percentiles.length) {
this.percentiles = percentiles;
}
if (percentileBandWidth != null) {
this.bandWidthPercent = percentileBandWidth;
}
this.bandWidth = this.maxWeight * (this.bandWidthPercent / 100);
// add min/max percentiles aligned to the ends of the range
this.percentiles.unshift(this.bandWidthPercent / 2);
this.percentiles.push(100 - (this.bandWidthPercent / 2));
this.setNextBounds();
}
processNext(tx: { weight: number, fee: number, effectiveFeePerVsize?: number, feePerVsize?: number, rate?: number, txid: string }): void {
let left = this.totalWeight;
const right = this.totalWeight + tx.weight;
if (!this.inBand && right <= this.leftBound) {
this.totalWeight += tx.weight;
return;
}
while (left < right) {
if (right > this.leftBound) {
this.inBand = true;
const txRate = (tx.rate || tx.effectiveFeePerVsize || tx.feePerVsize || 0);
const weight = Math.min(right, this.rightBound) - Math.max(left, this.leftBound);
this.totalBandFee += (txRate * weight);
this.totalBandWeight += weight;
this.maxBandRate = Math.max(this.maxBandRate, txRate);
this.minBandRate = Math.min(this.minBandRate, txRate);
}
left = Math.min(right, this.rightBound);
if (left >= this.rightBound) {
this.inBand = false;
const avgBandFeeRate = this.totalBandWeight ? (this.totalBandFee / this.totalBandWeight) : 0;
this.feeRange.unshift({ avg: avgBandFeeRate, min: this.minBandRate, max: this.maxBandRate });
this.bandIndex++;
this.setNextBounds();
this.totalBandFee = 0;
this.totalBandWeight = 0;
this.minBandRate = Infinity;
this.maxBandRate = 0;
}
}
this.totalWeight += tx.weight;
}
private setNextBounds(): void {
const nextPercentile = this.percentiles[this.bandIndex];
if (nextPercentile != null) {
this.leftBound = ((nextPercentile / 100) * this.maxWeight) - (this.bandWidth / 2);
this.rightBound = this.leftBound + this.bandWidth;
} else {
this.leftBound = Infinity;
this.rightBound = Infinity;
}
}
getRawFeeStats(): WorkingEffectiveFeeStats {
if (this.totalBandWeight > 0) {
const avgBandFeeRate = this.totalBandWeight ? (this.totalBandFee / this.totalBandWeight) : 0;
this.feeRange.unshift({ avg: avgBandFeeRate, min: this.minBandRate, max: this.maxBandRate });
}
while (this.feeRange.length < this.percentiles.length) {
this.feeRange.unshift({ avg: 0, min: 0, max: 0 });
}
return {
minFee: this.feeRange[0].min,
medianFee: this.feeRange[Math.floor(this.feeRange.length / 2)].avg,
maxFee: this.feeRange[this.feeRange.length - 1].max,
feeRange: this.feeRange.map(f => f.avg),
};
}
getFeeStats(): EffectiveFeeStats {
const stats = this.getRawFeeStats();
stats.feeRange[0] = stats.minFee;
stats.feeRange[stats.feeRange.length - 1] = stats.maxFee;
return stats;
}
}

286
backend/src/api/cpfp.ts Normal file
View File

@@ -0,0 +1,286 @@
import { CpfpInfo, MempoolTransactionExtended } from '../mempool.interfaces';
import memPool from './mempool';
const CPFP_UPDATE_INTERVAL = 60_000; // update CPFP info at most once per 60s per transaction
const MAX_GRAPH_SIZE = 50; // the maximum number of in-mempool relatives to consider
interface GraphTx extends MempoolTransactionExtended {
depends: string[];
spentby: string[];
ancestorMap: Map<string, GraphTx>;
fees: {
base: number;
ancestor: number;
};
ancestorcount: number;
ancestorsize: number;
ancestorRate: number;
individualRate: number;
score: number;
}
/**
* Takes a mempool transaction and a copy of the current mempool, and calculates the CPFP data for
* that transaction (and all others in the same cluster)
*/
export function calculateCpfp(tx: MempoolTransactionExtended, mempool: { [txid: string]: MempoolTransactionExtended }): CpfpInfo {
if (tx.cpfpUpdated && Date.now() < (tx.cpfpUpdated + CPFP_UPDATE_INTERVAL)) {
tx.cpfpDirty = false;
return {
ancestors: tx.ancestors || [],
bestDescendant: tx.bestDescendant || null,
descendants: tx.descendants || [],
effectiveFeePerVsize: tx.effectiveFeePerVsize || tx.adjustedFeePerVsize || tx.feePerVsize,
sigops: tx.sigops,
adjustedVsize: tx.adjustedVsize,
acceleration: tx.acceleration
};
}
const ancestorMap = new Map<string, GraphTx>();
const graphTx = mempoolToGraphTx(tx);
ancestorMap.set(tx.txid, graphTx);
const allRelatives = expandRelativesGraph(mempool, ancestorMap);
const relativesMap = initializeRelatives(allRelatives);
const cluster = calculateCpfpCluster(tx.txid, relativesMap);
let totalVsize = 0;
let totalFee = 0;
for (const tx of cluster.values()) {
totalVsize += tx.adjustedVsize;
totalFee += tx.fee;
}
const effectiveFeePerVsize = totalFee / totalVsize;
for (const tx of cluster.values()) {
mempool[tx.txid].effectiveFeePerVsize = effectiveFeePerVsize;
mempool[tx.txid].ancestors = Array.from(tx.ancestorMap.values()).map(tx => ({ txid: tx.txid, weight: tx.weight, fee: tx.fee }));
mempool[tx.txid].descendants = Array.from(cluster.values()).filter(entry => entry.txid !== tx.txid && !tx.ancestorMap.has(entry.txid)).map(tx => ({ txid: tx.txid, weight: tx.weight, fee: tx.fee }));
mempool[tx.txid].bestDescendant = null;
mempool[tx.txid].cpfpChecked = true;
mempool[tx.txid].cpfpDirty = true;
mempool[tx.txid].cpfpUpdated = Date.now();
}
tx = mempool[tx.txid];
return {
ancestors: tx.ancestors || [],
bestDescendant: tx.bestDescendant || null,
descendants: tx.descendants || [],
effectiveFeePerVsize: tx.effectiveFeePerVsize || tx.adjustedFeePerVsize || tx.feePerVsize,
sigops: tx.sigops,
adjustedVsize: tx.adjustedVsize,
acceleration: tx.acceleration
};
}
function mempoolToGraphTx(tx: MempoolTransactionExtended): GraphTx {
return {
...tx,
depends: tx.vin.map(v => v.txid),
spentby: tx.vout.map((v, i) => memPool.getFromSpendMap(tx.txid, i)).map(tx => tx?.txid).filter(txid => txid != null) as string[],
ancestorMap: new Map(),
fees: {
base: tx.fee,
ancestor: tx.fee,
},
ancestorcount: 1,
ancestorsize: tx.adjustedVsize,
ancestorRate: 0,
individualRate: 0,
score: 0,
};
}
/**
* Takes a map of transaction ancestors, and expands it into a full graph of up to MAX_GRAPH_SIZE in-mempool relatives
*/
function expandRelativesGraph(mempool: { [txid: string]: MempoolTransactionExtended }, ancestors: Map<string, GraphTx>): Map<string, GraphTx> {
const relatives: Map<string, GraphTx> = new Map();
const stack: GraphTx[] = Array.from(ancestors.values());
while (stack.length > 0) {
if (relatives.size > MAX_GRAPH_SIZE) {
return relatives;
}
const nextTx = stack.pop();
if (!nextTx) {
continue;
}
relatives.set(nextTx.txid, nextTx);
for (const relativeTxid of [...nextTx.depends, ...nextTx.spentby]) {
if (relatives.has(relativeTxid)) {
// already processed this tx
continue;
}
let mempoolTx = ancestors.get(relativeTxid);
if (!mempoolTx && mempool[relativeTxid]) {
mempoolTx = mempoolToGraphTx(mempool[relativeTxid]);
}
if (mempoolTx) {
stack.push(mempoolTx);
}
}
}
return relatives;
}
/**
* 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
*/
function initializeRelatives(mempoolTxs: Map<string, GraphTx>): Map<string, GraphTx> {
const visited: Map<string, Map<string, GraphTx>> = new Map();
const leaves: GraphTx[] = Array.from(mempoolTxs.values()).filter(entry => entry.spentby.length === 0);
for (const leaf of leaves) {
setAncestors(leaf, mempoolTxs, visited);
}
mempoolTxs.forEach(entry => {
entry.ancestorMap?.forEach(ancestor => {
entry.ancestorcount++;
entry.ancestorsize += ancestor.adjustedVsize;
entry.fees.ancestor += ancestor.fees.base;
});
setAncestorScores(entry);
});
return mempoolTxs;
}
/**
* Given a root transaction and a list of in-mempool ancestors,
* Calculate the CPFP cluster
*
* @param tx
* @param ancestors
*/
function calculateCpfpCluster(txid: string, graph: Map<string, GraphTx>): Map<string, GraphTx> {
const tx = graph.get(txid);
if (!tx) {
return new Map<string, GraphTx>([]);
}
// Initialize individual & ancestor fee rates
graph.forEach(entry => setAncestorScores(entry));
// Sort by descending ancestor score
let sortedRelatives = Array.from(graph.values()).sort(mempoolComparator);
// Iterate until we reach a cluster that includes our target tx
let maxIterations = MAX_GRAPH_SIZE;
let best = sortedRelatives.shift();
let bestCluster = new Map<string, GraphTx>(best?.ancestorMap?.entries() || []);
while (sortedRelatives.length && best && (best.txid !== tx.txid && !best.ancestorMap.has(tx.txid)) && maxIterations > 0) {
maxIterations--;
if ((best && best.txid === tx.txid) || (bestCluster && bestCluster.has(tx.txid))) {
break;
} else {
// Remove this cluster (it doesn't include our target tx)
// and update scores, ancestor totals and dependencies for the survivors
removeAncestors(bestCluster, graph);
// re-sort
sortedRelatives = Array.from(graph.values()).sort(mempoolComparator);
// Grab the next highest scoring entry
best = sortedRelatives.shift();
if (best) {
bestCluster = new Map<string, GraphTx>(best?.ancestorMap?.entries() || []);
bestCluster.set(best?.txid, best);
}
}
}
bestCluster.set(tx.txid, tx);
return bestCluster;
}
/**
* Remove a cluster of transactions from an in-mempool dependency graph
* and update the survivors' scores and ancestors
*
* @param cluster
* @param ancestors
*/
function removeAncestors(cluster: Map<string, GraphTx>, all: Map<string, GraphTx>): void {
// remove
cluster.forEach(tx => {
all.delete(tx.txid);
});
// update survivors
all.forEach(tx => {
cluster.forEach(remove => {
if (tx.ancestorMap?.has(remove.txid)) {
// remove as dependency
tx.ancestorMap.delete(remove.txid);
tx.depends = tx.depends.filter(parent => parent !== remove.txid);
// update ancestor sizes and fees
tx.ancestorsize -= remove.adjustedVsize;
tx.fees.ancestor -= remove.fees.base;
}
});
// recalculate fee rates
setAncestorScores(tx);
});
}
/**
* Recursively traverses an in-mempool dependency graph, and sets a Map of in-mempool ancestors
* for each transaction.
*
* @param tx
* @param all
*/
function setAncestors(tx: GraphTx, all: Map<string, GraphTx>, visited: Map<string, Map<string, GraphTx>>, depth: number = 0): Map<string, GraphTx> {
// sanity check for infinite recursion / too many ancestors (should never happen)
if (depth > MAX_GRAPH_SIZE) {
return tx.ancestorMap;
}
// initialize the ancestor map for this tx
tx.ancestorMap = new Map<string, GraphTx>();
tx.depends.forEach(parentId => {
const parent = all.get(parentId);
if (parent) {
// add the parent
tx.ancestorMap?.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 = setAncestors(parent, all, visited, depth + 1);
}
// and add to this tx's map
ancestors.forEach((ancestor, ancestorId) => {
tx.ancestorMap?.set(ancestorId, ancestor);
});
}
});
visited.set(tx.txid, tx.ancestorMap);
return tx.ancestorMap;
}
/**
* Take a mempool transaction, and set the fee rates and ancestor score
*
* @param tx
*/
function setAncestorScores(tx: GraphTx): GraphTx {
tx.individualRate = (tx.fees.base * 100_000_000) / tx.adjustedVsize;
tx.ancestorRate = (tx.fees.ancestor * 100_000_000) / tx.ancestorsize;
tx.score = Math.min(tx.individualRate, tx.ancestorRate);
return tx;
}
// Sort by descending score
function mempoolComparator(a: GraphTx, b: GraphTx): number {
return b.score - a.score;
}

View File

@@ -7,7 +7,7 @@ import cpfpRepository from '../repositories/CpfpRepository';
import { RowDataPacket } from 'mysql2';
class DatabaseMigration {
private static currentVersion = 59;
private static currentVersion = 76;
private queryTimeout = 3600_000;
private statisticsAddedIndexed = false;
private uniqueLogs: string[] = [];
@@ -497,6 +497,7 @@ class DatabaseMigration {
this.uniqueLog(logger.notice, this.blocksTruncatedMessage);
await this.$executeQuery('DELETE FROM `pools`');
await this.$executeQuery('ALTER TABLE pools AUTO_INCREMENT = 1');
await this.$executeQuery(`UPDATE state SET string = NULL WHERE name = 'pools_json_sha'`);
this.uniqueLog(logger.notice, '`pools` table has been truncated`');
await this.updateToSchemaVersion(56);
}
@@ -515,6 +516,153 @@ class DatabaseMigration {
// https://github.com/mempool/mempool/issues/3360
await this.$executeQuery(`TRUNCATE prices`);
}
if (databaseSchemaVersion < 60 && isBitcoin === true) {
await this.$executeQuery('ALTER TABLE `blocks_audits` ADD sigop_txs JSON DEFAULT "[]"');
await this.updateToSchemaVersion(60);
}
if (databaseSchemaVersion < 61 && isBitcoin === true) {
// Break block templates into their own table
if (! await this.$checkIfTableExists('blocks_templates')) {
await this.$executeQuery('CREATE TABLE blocks_templates AS SELECT id, template FROM blocks_summaries WHERE template != "[]"');
}
await this.$executeQuery('ALTER TABLE blocks_templates MODIFY template JSON DEFAULT "[]"');
await this.$executeQuery('ALTER TABLE blocks_templates ADD PRIMARY KEY (id)');
await this.$executeQuery('ALTER TABLE blocks_summaries DROP COLUMN template');
await this.updateToSchemaVersion(61);
}
if (databaseSchemaVersion < 62 && isBitcoin === true) {
await this.$executeQuery('ALTER TABLE `blocks_audits` ADD expected_fees BIGINT UNSIGNED DEFAULT NULL');
await this.$executeQuery('ALTER TABLE `blocks_audits` ADD expected_weight BIGINT UNSIGNED DEFAULT NULL');
await this.updateToSchemaVersion(62);
}
if (databaseSchemaVersion < 63 && isBitcoin === true) {
await this.$executeQuery('ALTER TABLE `blocks_audits` ADD fullrbf_txs JSON DEFAULT "[]"');
await this.updateToSchemaVersion(63);
}
if (databaseSchemaVersion < 64 && isBitcoin === true) {
await this.$executeQuery('ALTER TABLE `nodes` ADD features text NULL');
await this.updateToSchemaVersion(64);
}
if (databaseSchemaVersion < 65 && isBitcoin === true) {
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);
}
if (databaseSchemaVersion < 71 && config.MEMPOOL.NETWORK === 'liquid') {
await this.$executeQuery('TRUNCATE TABLE elements_pegs');
await this.$executeQuery('TRUNCATE TABLE federation_txos');
await this.$executeQuery('SET FOREIGN_KEY_CHECKS = 0');
await this.$executeQuery('TRUNCATE TABLE federation_addresses');
await this.$executeQuery('SET FOREIGN_KEY_CHECKS = 1');
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
await this.$executeQuery(`UPDATE state SET number = 0 WHERE name = 'last_elements_block';`);
await this.$executeQuery(`UPDATE state SET number = 0 WHERE name = 'last_bitcoin_block_audit';`);
await this.$executeQuery('ALTER TABLE `federation_txos` ADD timelock INT NOT NULL DEFAULT 0');
await this.$executeQuery('ALTER TABLE `federation_txos` ADD expiredAt INT NOT NULL DEFAULT 0');
await this.$executeQuery('ALTER TABLE `federation_txos` ADD emergencyKey TINYINT NOT NULL DEFAULT 0');
await this.updateToSchemaVersion(71);
}
if (databaseSchemaVersion < 72 && isBitcoin === true) {
// reindex Goggles flags for mined block templates above height 832000
await this.$executeQuery('UPDATE blocks_summaries SET version = 0 WHERE height >= 832000;');
await this.updateToSchemaVersion(72);
}
if (databaseSchemaVersion < 73 && config.MEMPOOL.NETWORK === 'mainnet') {
// Clear bad data
await this.$executeQuery(`TRUNCATE accelerations`);
this.uniqueLog(logger.notice, `'accelerations' table has been truncated`);
await this.updateToSchemaVersion(73);
}
if (databaseSchemaVersion < 74 && config.MEMPOOL.NETWORK === 'mainnet') {
await this.$executeQuery(`INSERT INTO state(name, number) VALUE ('last_acceleration_block', 0);`);
await this.updateToSchemaVersion(74);
}
if (databaseSchemaVersion < 75) {
await this.$executeQuery('ALTER TABLE `prices` ADD `BGN` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `BRL` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `CNY` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `CZK` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `DKK` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `HKD` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `HRK` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `HUF` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `IDR` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `ILS` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `INR` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `ISK` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `KRW` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `MXN` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `MYR` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `NOK` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `NZD` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `PHP` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `PLN` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `RON` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `RUB` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `SEK` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `SGD` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `THB` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `TRY` float DEFAULT "-1"');
await this.$executeQuery('ALTER TABLE `prices` ADD `ZAR` float DEFAULT "-1"');
await this.$executeQuery('TRUNCATE hashrates');
await this.$executeQuery('TRUNCATE difficulty_adjustments');
await this.updateToSchemaVersion(75);
}
if (databaseSchemaVersion < 76 && isBitcoin === true) {
await this.$executeQuery('ALTER TABLE `blocks_audits` ADD prioritized_txs JSON DEFAULT "[]"');
await this.updateToSchemaVersion(76);
}
}
/**
@@ -762,6 +910,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,
@@ -1032,8 +1206,25 @@ 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<void> {
logger.warn(`Truncating pools, blocks and hashrates for re-indexing (using '--reindex-blocks'). You can cancel this command within 5 seconds`);
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);
await this.$executeQuery(`TRUNCATE blocks`);

View File

@@ -12,43 +12,117 @@ 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
}
/**
* Calculate the difficulty increase/decrease by using the `bits` integer contained in two
* block headers.
*
* Warning: Only compare `bits` from blocks in two adjacent difficulty periods. This code
* assumes the maximum difference is x4 or /4 (as per the protocol) and will throw an
* error if an exponent difference of 2 or more is seen.
*
* @param {number} oldBits The 32 bit `bits` integer from a block header.
* @param {number} newBits The 32 bit `bits` integer from a block header in the next difficulty period.
* @returns {number} A floating point decimal of the difficulty change from old to new.
* (ie. 21.3 means 21.3% increase in difficulty, -21.3 is a 21.3% decrease in difficulty)
*/
export function calcBitsDifference(oldBits: number, newBits: number): number {
// Must be
// - integer
// - highest exponent is 0x20, so max value (as integer) is 0x207fffff
// - min value is 1 (exponent = 0)
// - highest bit of the number-part is +- sign, it must not be 1
const verifyBits = (bits: number): void => {
if (
Math.floor(bits) !== bits ||
bits > 0x207fffff ||
bits < 1 ||
(bits & 0x00800000) !== 0 ||
(bits & 0x007fffff) === 0
) {
throw new Error('Invalid bits');
}
};
verifyBits(oldBits);
verifyBits(newBits);
// No need to mask exponents because we checked the bounds above
const oldExp = oldBits >> 24;
const newExp = newBits >> 24;
const oldNum = oldBits & 0x007fffff;
const newNum = newBits & 0x007fffff;
// The diff can only possibly be 1, 0, -1
// (because maximum difficulty change is x4 or /4 (2 bits up or down))
let result: number;
switch (newExp - oldExp) {
// New less than old, target lowered, difficulty increased
case -1:
result = ((oldNum << 8) * 100) / newNum - 100;
break;
// Same exponent, compare numbers as is.
case 0:
result = (oldNum * 100) / newNum - 100;
break;
// Old less than new, target raised, difficulty decreased
case 1:
result = (oldNum * 100) / (newNum << 8) - 100;
break;
default:
throw new Error('Impossible exponent difference');
}
// Min/Max values
return result > 300 ? 300 : result < -75 ? -75 : result;
}
export function calcDifficultyAdjustment(
DATime: number,
quarterEpochTime: number | null,
nowSeconds: number,
blockHeight: number,
previousRetarget: number,
network: string,
latestBlockTimestamp: number,
): DifficultyAdjustment {
const ESTIMATE_LAG_BLOCKS = 146; // For first 7.2% of epoch, don't estimate.
const EPOCH_BLOCK_LENGTH = 2016; // Bitcoin mainnet
const BLOCK_SECONDS_TARGET = 600; // Bitcoin mainnet
const TESTNET_MAX_BLOCK_SECONDS = 1200; // Bitcoin testnet
const diffSeconds = nowSeconds - DATime;
const diffSeconds = Math.max(0, nowSeconds - DATime);
const blocksInEpoch = (blockHeight >= 0) ? blockHeight % EPOCH_BLOCK_LENGTH : 0;
const progressPercent = (blockHeight >= 0) ? blocksInEpoch / EPOCH_BLOCK_LENGTH * 100 : 100;
const remainingBlocks = EPOCH_BLOCK_LENGTH - blocksInEpoch;
const nextRetargetHeight = (blockHeight >= 0) ? blockHeight + remainingBlocks : 0;
const expectedBlocks = diffSeconds / BLOCK_SECONDS_TARGET;
const actualTimespan = (blocksInEpoch === 2015 ? latestBlockTimestamp : nowSeconds) - DATime;
let difficultyChange = 0;
let timeAvgSecs = diffSeconds / blocksInEpoch;
// Only calculate the estimate once we have 7.2% of blocks in current epoch
if (blocksInEpoch >= ESTIMATE_LAG_BLOCKS) {
difficultyChange = (BLOCK_SECONDS_TARGET / timeAvgSecs - 1) * 100;
// Max increase is x4 (+300%)
if (difficultyChange > 300) {
difficultyChange = 300;
}
// Max decrease is /4 (-75%)
if (difficultyChange < -75) {
difficultyChange = -75;
}
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;
}
// Max increase is x4 (+300%)
if (difficultyChange > 300) {
difficultyChange = 300;
}
// Max decrease is /4 (-75%)
if (difficultyChange < -75) {
difficultyChange = -75;
}
// Testnet difficulty is set to 1 after 20 minutes of no blocks,
@@ -66,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 {
@@ -79,6 +154,7 @@ export function calcDifficultyAdjustment(
previousTime: DATime,
nextRetargetHeight,
timeAvg,
adjustedTimeAvg,
timeOffset,
expectedBlocks,
};
@@ -95,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
);
}

View File

@@ -7,19 +7,29 @@ import logger from '../logger';
import config from '../config';
import { TransactionExtended } from '../mempool.interfaces';
import { Common } from './common';
import rbfCache from './rbf-cache';
class DiskCache {
private cacheSchemaVersion = 3;
private rbfCacheSchemaVersion = 1;
private static TMP_FILE_NAME = config.MEMPOOL.CACHE_DIR + '/tmp-cache.json';
private static TMP_FILE_NAMES = config.MEMPOOL.CACHE_DIR + '/tmp-cache{number}.json';
private static FILE_NAME = config.MEMPOOL.CACHE_DIR + '/cache.json';
private static FILE_NAMES = config.MEMPOOL.CACHE_DIR + '/cache{number}.json';
private static TMP_RBF_FILE_NAME = config.MEMPOOL.CACHE_DIR + '/tmp-rbfcache.json';
private static RBF_FILE_NAME = config.MEMPOOL.CACHE_DIR + '/rbfcache.json';
private static CHUNK_FILES = 25;
private isWritingCache = false;
private ignoreBlocksCache = false;
private semaphore: { resume: (() => void)[], locks: number } = {
resume: [],
locks: 0,
};
constructor() {
if (!cluster.isPrimary) {
if (!cluster.isPrimary || !config.MEMPOOL.CACHE_ENABLED) {
return;
}
process.on('SIGINT', (e) => {
@@ -29,7 +39,7 @@ class DiskCache {
}
async $saveCacheToDisk(sync: boolean = false): Promise<void> {
if (!cluster.isPrimary) {
if (!cluster.isPrimary || !config.MEMPOOL.CACHE_ENABLED) {
return;
}
if (this.isWritingCache) {
@@ -43,7 +53,9 @@ class DiskCache {
const mempool = memPool.getMempool();
const mempoolArray: TransactionExtended[] = [];
for (const tx in mempool) {
mempoolArray.push(mempool[tx]);
if (mempool[tx]) {
mempoolArray.push(mempool[tx]);
}
}
Common.shuffleArray(mempoolArray);
@@ -71,6 +83,7 @@ class DiskCache {
fs.renameSync(DiskCache.TMP_FILE_NAMES.replace('{number}', i.toString()), DiskCache.FILE_NAMES.replace('{number}', i.toString()));
}
} else {
await this.$yield();
await fsPromises.writeFile(DiskCache.TMP_FILE_NAME, JSON.stringify({
network: config.MEMPOOL.NETWORK,
cacheSchemaVersion: this.cacheSchemaVersion,
@@ -80,6 +93,7 @@ class DiskCache {
mempoolArray: mempoolArray.splice(0, chunkSize),
}), { flag: 'w' });
for (let i = 1; i < DiskCache.CHUNK_FILES; i++) {
await this.$yield();
await fsPromises.writeFile(DiskCache.TMP_FILE_NAMES.replace('{number}', i.toString()), JSON.stringify({
mempool: {},
mempoolArray: mempoolArray.splice(0, chunkSize),
@@ -98,6 +112,32 @@ class DiskCache {
logger.warn('Error writing to cache file: ' + (e instanceof Error ? e.message : e));
this.isWritingCache = false;
}
try {
logger.debug('Writing rbf data to disk cache (async)...');
this.isWritingCache = true;
const rbfData = rbfCache.dump();
if (sync) {
fs.writeFileSync(DiskCache.TMP_RBF_FILE_NAME, JSON.stringify({
network: config.MEMPOOL.NETWORK,
rbfCacheSchemaVersion: this.rbfCacheSchemaVersion,
rbf: rbfData,
}), { flag: 'w' });
fs.renameSync(DiskCache.TMP_RBF_FILE_NAME, DiskCache.RBF_FILE_NAME);
} else {
await fsPromises.writeFile(DiskCache.TMP_RBF_FILE_NAME, JSON.stringify({
network: config.MEMPOOL.NETWORK,
rbfCacheSchemaVersion: this.rbfCacheSchemaVersion,
rbf: rbfData,
}), { flag: 'w' });
await fsPromises.rename(DiskCache.TMP_RBF_FILE_NAME, DiskCache.RBF_FILE_NAME);
}
logger.debug('Rbf data saved to disk cache');
this.isWritingCache = false;
} catch (e) {
logger.warn('Error writing rbf data to cache file: ' + (e instanceof Error ? e.message : e));
this.isWritingCache = false;
}
}
wipeCache(): void {
@@ -122,11 +162,24 @@ class DiskCache {
}
}
loadMempoolCache(): void {
if (!fs.existsSync(DiskCache.FILE_NAME)) {
wipeRbfCache() {
logger.notice(`Wipping nodejs backend cache/rbfcache.json file`);
try {
fs.unlinkSync(DiskCache.RBF_FILE_NAME);
} catch (e: any) {
if (e?.code !== 'ENOENT') {
logger.err(`Cannot wipe cache file ${DiskCache.RBF_FILE_NAME}. Exception ${JSON.stringify(e)}`);
}
}
}
async $loadMempoolCache(): Promise<void> {
if (!config.MEMPOOL.CACHE_ENABLED || !fs.existsSync(DiskCache.FILE_NAME)) {
return;
}
try {
const start = Date.now();
let data: any = {};
const cacheData = fs.readFileSync(DiskCache.FILE_NAME, 'utf8');
if (cacheData) {
@@ -143,6 +196,7 @@ class DiskCache {
if (data.mempoolArray) {
for (const tx of data.mempoolArray) {
delete tx.uid;
data.mempool[tx.txid] = tx;
}
}
@@ -155,6 +209,7 @@ class DiskCache {
const cacheData2 = JSON.parse(fs.readFileSync(fileName, 'utf8'));
if (cacheData2.mempoolArray) {
for (const tx of cacheData2.mempoolArray) {
delete tx.uid;
data.mempool[tx.txid] = tx;
}
} else {
@@ -162,16 +217,81 @@ class DiskCache {
}
}
} catch (e) {
logger.info('Error parsing ' + fileName + '. Skipping. Reason: ' + (e instanceof Error ? e.message : e));
logger.err('Error parsing ' + fileName + '. Skipping. Reason: ' + (e instanceof Error ? e.message : e));
}
}
memPool.setMempool(data.mempool);
blocks.setBlocks(data.blocks);
blocks.setBlockSummaries(data.blockSummaries || []);
logger.info(`Loaded mempool from disk cache in ${Date.now() - start} ms`);
await memPool.$setMempool(data.mempool);
if (!this.ignoreBlocksCache) {
blocks.setBlocks(data.blocks);
blocks.setBlockSummaries(data.blockSummaries || []);
} else {
logger.info('Re-saving cache with empty recent blocks data');
await this.$saveCacheToDisk(true);
}
} catch (e) {
logger.warn('Failed to parse mempoool and blocks cache. Skipping. Reason: ' + (e instanceof Error ? e.message : e));
}
try {
let rbfData: any = {};
const rbfCacheData = fs.readFileSync(DiskCache.RBF_FILE_NAME, 'utf8');
if (rbfCacheData) {
logger.info('Restoring rbf data from disk cache');
rbfData = JSON.parse(rbfCacheData);
if (rbfData.rbfCacheSchemaVersion === undefined || rbfData.rbfCacheSchemaVersion !== this.rbfCacheSchemaVersion) {
logger.notice('Rbf disk cache contains an outdated schema version. Clearing it and skipping the cache loading.');
return this.wipeRbfCache();
}
if (rbfData.network && rbfData.network !== config.MEMPOOL.NETWORK) {
logger.notice('Rbf disk cache contains data from a different network. Clearing it and skipping the cache loading.');
return this.wipeRbfCache();
}
}
if (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));
}
}
private $yield(): Promise<void> {
if (this.semaphore.locks) {
logger.debug('Pause writing mempool and blocks data to disk cache (async)');
return new Promise((resolve) => {
this.semaphore.resume.push(resolve);
});
} else {
return Promise.resolve();
}
}
public lock(): void {
this.semaphore.locks++;
}
public unlock(): void {
this.semaphore.locks = Math.max(0, this.semaphore.locks - 1);
if (!this.semaphore.locks && this.semaphore.resume.length) {
const nextResume = this.semaphore.resume.shift();
if (nextResume) {
logger.debug('Resume writing mempool and blocks data to disk cache (async)');
nextResume();
}
}
}
public setIgnoreBlocksCache(): void {
this.ignoreBlocksCache = true;
}
}

View File

@@ -80,7 +80,13 @@ class ChannelsApi {
public async $searchChannelsById(search: string): Promise<any[]> {
try {
const searchStripped = search.replace('%', '') + '%';
// 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;
@@ -117,6 +123,26 @@ class ChannelsApi {
}
}
public async $getPenaltyClosedChannels(): Promise<any[]> {
try {
const query = `
SELECT n1.alias AS alias_left,
n2.alias AS alias_right,
channels.*
FROM channels
LEFT JOIN nodes AS n1 ON n1.public_key = channels.node1_public_key
LEFT JOIN nodes AS n2 ON n2.public_key = channels.node2_public_key
WHERE channels.status = 2 AND channels.closing_reason = 3
ORDER BY closing_date DESC
`;
const [rows]: any = await DB.query(query);
return rows;
} catch (e) {
logger.err('$getPenaltyClosedChannels error: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
public async $getUnresolvedClosedChannels(): Promise<any[]> {
try {
const query = `SELECT * FROM channels WHERE status = 2 AND closing_reason = 2 AND closing_resolved = 0 AND closing_transaction_id != ''`;

View File

@@ -11,6 +11,7 @@ class ChannelsRoutes {
.get(config.MEMPOOL.API_URL_PREFIX + 'lightning/channels/search/:search', this.$searchChannelsById)
.get(config.MEMPOOL.API_URL_PREFIX + 'lightning/channels/:short_id', this.$getChannel)
.get(config.MEMPOOL.API_URL_PREFIX + 'lightning/channels', this.$getChannelsForNode)
.get(config.MEMPOOL.API_URL_PREFIX + 'lightning/penalties', this.$getPenaltyClosedChannels)
.get(config.MEMPOOL.API_URL_PREFIX + 'lightning/channels-geo', this.$getAllChannelsGeo)
.get(config.MEMPOOL.API_URL_PREFIX + 'lightning/channels-geo/:publicKey', this.$getAllChannelsGeo)
;
@@ -108,6 +109,18 @@ class ChannelsRoutes {
}
}
private async $getPenaltyClosedChannels(req: Request, res: Response): Promise<void> {
try {
const channels = await channelsApi.$getPenaltyClosedChannels();
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString());
res.json(channels);
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async $getAllChannelsGeo(req: Request, res: Response) {
try {
const style: string = typeof req.query.style === 'string' ? req.query.style : '';

View File

@@ -3,6 +3,7 @@ import DB from '../../database';
import { ResultSetHeader } from 'mysql2';
import { ILightningApi } from '../lightning/lightning-api.interface';
import { ITopNodesPerCapacity, ITopNodesPerChannels } from '../../mempool.interfaces';
import { bin2hex } from '../../utils/format';
class NodesApi {
public async $getWorldNodes(): Promise<any> {
@@ -56,7 +57,8 @@ class NodesApi {
UNIX_TIMESTAMP(updated_at) AS updated_at, color, sockets as sockets,
as_number, city_id, country_id, subdivision_id, longitude, latitude,
geo_names_iso.names as iso_code, geo_names_as.names as as_organization, geo_names_city.names as city,
geo_names_country.names as country, geo_names_subdivision.names as subdivision
geo_names_country.names as country, geo_names_subdivision.names as subdivision,
features
FROM nodes
LEFT JOIN geo_names geo_names_as on geo_names_as.id = as_number
LEFT JOIN geo_names geo_names_city on geo_names_city.id = city_id
@@ -76,6 +78,23 @@ class NodesApi {
node.city = JSON.parse(node.city);
node.country = JSON.parse(node.country);
// Features
node.features = JSON.parse(node.features);
node.featuresBits = null;
if (node.features) {
let maxBit = 0;
for (const feature of node.features) {
maxBit = Math.max(maxBit, feature.bit);
}
maxBit = Math.ceil(maxBit / 4) * 4 - 1;
node.featuresBits = new Array(maxBit + 1).fill(0);
for (const feature of node.features) {
node.featuresBits[feature.bit] = 1;
}
node.featuresBits = bin2hex(node.featuresBits.reverse().join(''));
}
// Active channels and capacity
const activeChannelsStats: any = await this.$getActiveChannelsStats(public_key);
node.active_channel_count = activeChannelsStats.active_channel_count ?? 0;
@@ -373,7 +392,7 @@ class NodesApi {
public async $searchNodeByPublicKeyOrAlias(search: string) {
try {
const publicKeySearch = search.replace('%', '') + '%';
const publicKeySearch = search.replace(/[^a-zA-Z0-9]/g, '') + '%';
const aliasSearch = search
.replace(/[-_.]/g, ' ') // Replace all -_. characters with empty space. Eg: "ln.nicehash" becomes "ln nicehash".
.replace(/[^a-zA-Z0-9 ]/g, '') // Remove all special characters and keep just A to Z, 0 to 9.
@@ -656,10 +675,19 @@ class NodesApi {
alias_search,
color,
sockets,
status
status,
features
)
VALUES (?, NOW(), FROM_UNIXTIME(?), ?, ?, ?, ?, 1)
ON DUPLICATE KEY UPDATE updated_at = FROM_UNIXTIME(?), alias = ?, alias_search = ?, color = ?, sockets = ?, status = 1`;
VALUES (?, NOW(), FROM_UNIXTIME(?), ?, ?, ?, ?, 1, ?)
ON DUPLICATE KEY UPDATE
updated_at = FROM_UNIXTIME(?),
alias = ?,
alias_search = ?,
color = ?,
sockets = ?,
status = 1,
features = ?
`;
await DB.query(query, [
node.pub_key,
@@ -668,11 +696,13 @@ class NodesApi {
this.aliasToSearchText(node.alias),
node.color,
sockets,
JSON.stringify(node.features),
node.last_update,
node.alias,
this.aliasToSearchText(node.alias),
node.color,
sockets,
JSON.stringify(node.features),
]);
} catch (e) {
logger.err('$saveNode() error: ' + (e instanceof Error ? e.message : e));

View File

@@ -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',

View File

@@ -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;
}
}

View File

@@ -2,8 +2,99 @@ import { ILightningApi } from '../lightning-api.interface';
import FundingTxFetcher from '../../../tasks/lightning/sync-tasks/funding-tx-fetcher';
import logger from '../../../logger';
import { Common } from '../../common';
import { hex2bin } from '../../../utils/format';
import config from '../../../config';
// https://github.com/lightningnetwork/lnd/blob/master/lnwire/features.go
export enum FeatureBits {
DataLossProtectRequired = 0,
DataLossProtectOptional = 1,
InitialRoutingSync = 3,
UpfrontShutdownScriptRequired = 4,
UpfrontShutdownScriptOptional = 5,
GossipQueriesRequired = 6,
GossipQueriesOptional = 7,
TLVOnionPayloadRequired = 8,
TLVOnionPayloadOptional = 9,
StaticRemoteKeyRequired = 12,
StaticRemoteKeyOptional = 13,
PaymentAddrRequired = 14,
PaymentAddrOptional = 15,
MPPRequired = 16,
MPPOptional = 17,
WumboChannelsRequired = 18,
WumboChannelsOptional = 19,
AnchorsRequired = 20,
AnchorsOptional = 21,
AnchorsZeroFeeHtlcTxRequired = 22,
AnchorsZeroFeeHtlcTxOptional = 23,
ShutdownAnySegwitRequired = 26,
ShutdownAnySegwitOptional = 27,
AMPRequired = 30,
AMPOptional = 31,
ExplicitChannelTypeRequired = 44,
ExplicitChannelTypeOptional = 45,
ScidAliasRequired = 46,
ScidAliasOptional = 47,
PaymentMetadataRequired = 48,
PaymentMetadataOptional = 49,
ZeroConfRequired = 50,
ZeroConfOptional = 51,
KeysendRequired = 54,
KeysendOptional = 55,
ScriptEnforcedLeaseRequired = 2022,
ScriptEnforcedLeaseOptional = 2023,
SimpleTaprootChannelsRequiredFinal = 80,
SimpleTaprootChannelsOptionalFinal = 81,
SimpleTaprootChannelsRequiredStaging = 180,
SimpleTaprootChannelsOptionalStaging = 181,
MaxBolt11Feature = 5114,
};
export const FeaturesMap = new Map<FeatureBits, string>([
[FeatureBits.DataLossProtectRequired, 'data-loss-protect'],
[FeatureBits.DataLossProtectOptional, 'data-loss-protect'],
[FeatureBits.InitialRoutingSync, 'initial-routing-sync'],
[FeatureBits.UpfrontShutdownScriptRequired, 'upfront-shutdown-script'],
[FeatureBits.UpfrontShutdownScriptOptional, 'upfront-shutdown-script'],
[FeatureBits.GossipQueriesRequired, 'gossip-queries'],
[FeatureBits.GossipQueriesOptional, 'gossip-queries'],
[FeatureBits.TLVOnionPayloadRequired, 'tlv-onion'],
[FeatureBits.TLVOnionPayloadOptional, 'tlv-onion'],
[FeatureBits.StaticRemoteKeyOptional, 'static-remote-key'],
[FeatureBits.StaticRemoteKeyRequired, 'static-remote-key'],
[FeatureBits.PaymentAddrOptional, 'payment-addr'],
[FeatureBits.PaymentAddrRequired, 'payment-addr'],
[FeatureBits.MPPOptional, 'multi-path-payments'],
[FeatureBits.MPPRequired, 'multi-path-payments'],
[FeatureBits.AnchorsRequired, 'anchor-commitments'],
[FeatureBits.AnchorsOptional, 'anchor-commitments'],
[FeatureBits.AnchorsZeroFeeHtlcTxRequired, 'anchors-zero-fee-htlc-tx'],
[FeatureBits.AnchorsZeroFeeHtlcTxOptional, 'anchors-zero-fee-htlc-tx'],
[FeatureBits.WumboChannelsRequired, 'wumbo-channels'],
[FeatureBits.WumboChannelsOptional, 'wumbo-channels'],
[FeatureBits.AMPRequired, 'amp'],
[FeatureBits.AMPOptional, 'amp'],
[FeatureBits.PaymentMetadataOptional, 'payment-metadata'],
[FeatureBits.PaymentMetadataRequired, 'payment-metadata'],
[FeatureBits.ExplicitChannelTypeOptional, 'explicit-commitment-type'],
[FeatureBits.ExplicitChannelTypeRequired, 'explicit-commitment-type'],
[FeatureBits.KeysendOptional, 'keysend'],
[FeatureBits.KeysendRequired, 'keysend'],
[FeatureBits.ScriptEnforcedLeaseRequired, 'script-enforced-lease'],
[FeatureBits.ScriptEnforcedLeaseOptional, 'script-enforced-lease'],
[FeatureBits.ScidAliasRequired, 'scid-alias'],
[FeatureBits.ScidAliasOptional, 'scid-alias'],
[FeatureBits.ZeroConfRequired, 'zero-conf'],
[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'],
]);
/**
* Convert a clightning "listnode" entry to a lnd node entry
*/
@@ -17,10 +108,36 @@ export function convertNode(clNode: any): ILightningApi.Node {
custom_records = undefined;
}
}
const nodeFeatures: ILightningApi.Feature[] = [];
const nodeFeaturesBinary = hex2bin(clNode.features).split('').reverse().join('');
for (let i = 0; i < nodeFeaturesBinary.length; i++) {
if (nodeFeaturesBinary[i] === '0') {
continue;
}
const feature = FeaturesMap.get(i);
if (!feature) {
nodeFeatures.push({
bit: i,
name: 'unknown',
is_required: i % 2 === 0,
is_known: false
});
} else {
nodeFeatures.push({
bit: i,
name: feature,
is_required: i % 2 === 0,
is_known: true
});
}
}
return {
alias: clNode.alias ?? '',
color: `#${clNode.color ?? ''}`,
features: [], // TODO parse and return clNode.feature
features: nodeFeatures,
pub_key: clNode.nodeid,
addresses: clNode.addresses?.map((addr) => {
let address = addr.address;
@@ -108,7 +225,7 @@ async function buildFullChannel(clChannelA: any, clChannelB: any): Promise<ILigh
return {
channel_id: Common.channelShortIdToIntegerId(clChannelA.short_channel_id),
capacity: clChannelA.satoshis,
capacity: (clChannelA.amount_msat / 1000).toString(),
last_update: lastUpdate,
node1_policy: convertPolicy(clChannelA),
node2_policy: convertPolicy(clChannelB),
@@ -132,7 +249,7 @@ async function buildIncompleteChannel(clChannel: any): Promise<ILightningApi.Cha
return {
channel_id: Common.channelShortIdToIntegerId(clChannel.short_channel_id),
capacity: clChannel.satoshis,
capacity: (clChannel.amount_msat / 1000).toString(),
last_update: clChannel.last_update ?? 0,
node1_policy: convertPolicy(clChannel),
node2_policy: null,
@@ -148,8 +265,8 @@ async function buildIncompleteChannel(clChannel: any): Promise<ILightningApi.Cha
function convertPolicy(clChannel: any): ILightningApi.RoutingPolicy {
return {
time_lock_delta: clChannel.delay,
min_htlc: clChannel.htlc_minimum_msat.slice(0, -4),
max_htlc_msat: clChannel.htlc_maximum_msat.slice(0, -4),
min_htlc: clChannel.htlc_minimum_msat.toString(),
max_htlc_msat: clChannel.htlc_maximum_msat.toString(),
fee_base_msat: clChannel.base_fee_millisatoshi,
fee_rate_milli_msat: clChannel.fee_per_millionth,
disabled: !clChannel.active,

View File

@@ -79,6 +79,7 @@ export namespace ILightningApi {
}
export interface Feature {
bit: number;
name: string;
is_required: boolean;
is_known: boolean;

View File

@@ -24,8 +24,9 @@ class LndApi implements AbstractLightningApi {
timeout: config.LND.TIMEOUT
};
} catch (e) {
logger.err(`Could not initialize LND Macaroon/TLS Cert. Disabling LIGHTNING. ` + (e instanceof Error ? e.message : e));
config.LIGHTNING.ENABLED = false;
logger.updateNetwork();
logger.err(`Could not initialize LND Macaroon/TLS Cert. Disabling LIGHTNING. ` + (e instanceof Error ? e.message : e));
}
}
@@ -40,8 +41,23 @@ class LndApi implements AbstractLightningApi {
}
async $getNetworkGraph(): Promise<ILightningApi.NetworkGraph> {
return axios.get<ILightningApi.NetworkGraph>(config.LND.REST_API_URL + '/v1/graph', this.axiosConfig)
const graph = await axios.get<ILightningApi.NetworkGraph>(config.LND.REST_API_URL + '/v1/graph', this.axiosConfig)
.then((response) => response.data);
for (const node of graph.nodes) {
const nodeFeatures: ILightningApi.Feature[] = [];
for (const bit in node.features) {
nodeFeatures.push({
bit: parseInt(bit, 10),
name: node.features[bit].name,
is_required: node.features[bit].is_required,
is_known: node.features[bit].is_known,
});
}
node.features = nodeFeatures;
}
return graph;
}
}

View File

@@ -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<any> {
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<void> {
const query = `INSERT INTO elements_pegs(
txindex: number, bitcoinaddress: string, bitcointxid: string, bitcoinindex: number, bitcoinblock: number, bitcoinBlockTime: number, final_tx: number): Promise<void> {
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, timelock, expiredAt, emergencyKey, pegtxid, pegindex, pegblocktime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
const params_utxos: (string | number)[] = [bitcointxid, bitcoinindex, bitcoinaddress, amount, bitcoinblock, bitcoinBlockTime, 1, bitcoinblock - 1, 0, 4032, 0, 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<number> {
@@ -98,6 +112,382 @@ 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, blocknumber, timelock, expiredAt 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<any> {
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;
// 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; // A Federation UTXO is spent in this block: we might find a peg-out address in the outputs
if (txo.expiredAt > 0 ) {
if (input.txinwitness?.length !== 13) { // Check if the witness data of the input contains the 11 signatures: if it doesn't, emergency keys are being used
await DB.query(`UPDATE federation_txos SET unspent = 0, lastblockupdate = ?, lasttimeupdate = ?, emergencyKey = 1 WHERE txid = ? AND txindex = ?`, [block.height, block.time, txo.txid, txo.txindex]);
logger.debug(`Expired Federation UTXO ${txo.txid}:${txo.txindex} (${txo.amount} sats) was spent in block ${block.height} using emergency keys!`);
} else {
await DB.query(`UPDATE federation_txos SET unspent = 0, lastblockupdate = ?, lasttimeupdate = ? WHERE txid = ? AND txindex = ?`, [block.height, block.time, txo.txid, txo.txindex]);
logger.debug(`Expired Federation UTXO ${txo.txid}:${txo.txindex} (${txo.amount} sats) was spent in block ${block.height} using regular 11-of-15 signatures`);
}
} else {
await DB.query(`UPDATE federation_txos SET unspent = 0, lastblockupdate = ?, lasttimeupdate = ? WHERE txid = ? AND txindex = ?`, [block.height, block.time, txo.txid, txo.txindex]);
logger.debug(`Federation UTXO ${txo.txid}:${txo.txindex} (${txo.amount} sats) was spent in block ${block.height}`);
}
// Remove the TXO from the utxo array
spentAsTip.splice(spentAsTip.indexOf(txo), 1);
}
}
// 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 timelock = output.scriptPubKey.address === federationChangeAddresses[0] ? 4032 : 2016; // P2WSH change address has a 4032 timelock, P2SH change address has a 2016 timelock
const query_utxos = `INSERT INTO federation_txos (txid, txindex, bitcoinaddress, amount, blocknumber, blocktime, unspent, lastblockupdate, lasttimeupdate, timelock, expiredAt, emergencyKey, 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, timelock, 0, 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,
blocknumber: block.height,
timelock: timelock,
expiredAt: 0,
});
logger.debug(`Added new Federation UTXO ${tx.txid}:${output.n} (${Math.round(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) {
if (utxo.expiredAt === 0 && block.height >= utxo.blocknumber + utxo.timelock) { // The UTXO is expiring in this block
await DB.query(`UPDATE federation_txos SET lastblockupdate = ?, expiredAt = ? WHERE txid = ? AND txindex = ?`, [block.height, block.time, utxo.txid, utxo.txindex]);
} else {
await DB.query(`UPDATE federation_txos SET lastblockupdate = ? WHERE txid = ? AND txindex = ?`, [block.height, utxo.txid, utxo.txindex]);
}
}
for (const utxo of unspentAsTip) {
if (utxo.expiredAt === 0 && block.height >= utxo.blocknumber + utxo.timelock) { // The UTXO is expiring in this block
await DB.query(`UPDATE federation_txos SET unspent = 0, lastblockupdate = ?, expiredAt = ? WHERE txid = ? AND txindex = ?`, [confirmedTip, block.time, utxo.txid, utxo.txindex]);
} else if (utxo.expiredAt === 0 && confirmedTip >= utxo.blocknumber + utxo.timelock) { // The UTXO is expiring before the tip: we need to keep track of it
await DB.query(`UPDATE federation_txos SET lastblockupdate = ? WHERE txid = ? AND txindex = ?`, [utxo.blocknumber + utxo.timelock - 1, utxo.txid, utxo.txindex]);
} else {
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<any> {
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<any> {
const result = await bitcoinSecondClient.getBlockchainInfo();
return {
bitcoinBlocks: result.blocks,
bitcoinHeaders: result.headers,
}
}
protected async $getLastBlockAudit(): Promise<number> {
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<any[]> {
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;
}
protected isDust(amount: number, feeRate: number): boolean {
return amount <= (450 * feeRate); // A P2WSH 11-of-15 multisig input is around 450 bytes
}
///////////// DATA QUERY //////////////
public async $getAuditStatus(): Promise<any> {
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<any> {
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<any> {
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)))
AND
(expiredAt = 0 OR expiredAt > 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<any> {
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<any> {
const [rows] = await DB.query(`SELECT SUM(amount) AS total_balance FROM federation_txos WHERE unspent = 1 AND expiredAt = 0;`);
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<any> {
const query = `SELECT bitcoinaddress, SUM(amount) AS balance FROM federation_txos WHERE unspent = 1 AND expiredAt = 0 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<any> {
const query = `SELECT txid, txindex, bitcoinaddress, amount, blocknumber, blocktime, pegtxid, pegindex, pegblocktime, timelock, expiredAt FROM federation_txos WHERE unspent = 1 AND expiredAt = 0 ORDER BY blocktime DESC;`;
const [rows] = await DB.query(query);
return rows;
}
// Get expired UTXOs, most recent first
public async $getExpiredUtxos(): Promise<any> {
const query = `SELECT txid, txindex, bitcoinaddress, amount, blocknumber, blocktime, pegtxid, pegindex, pegblocktime, timelock, expiredAt FROM federation_txos WHERE unspent = 1 AND expiredAt > 0 ORDER BY blocktime DESC;`;
const [rows]: any[] = await DB.query(query);
const feeRate = Math.round((await bitcoinSecondClient.estimateSmartFee(1)).feerate * 100000000 / 1000);
for (const row of rows) {
row.isDust = this.isDust(row.amount, feeRate);
}
return rows;
}
// Get utxos that were spent using emergency keys
public async $getEmergencySpentUtxos(): Promise<any> {
const query = `SELECT txid, txindex, bitcoinaddress, amount, blocknumber, blocktime, pegtxid, pegindex, pegblocktime, timelock, expiredAt FROM federation_txos WHERE emergencyKey = 1 ORDER BY blocktime DESC;`;
const [rows] = await DB.query(query);
return rows;
}
// Get the total number of federation addresses
public async $getFederationAddressesNumber(): Promise<any> {
const query = `SELECT COUNT(DISTINCT bitcoinaddress) AS address_count FROM federation_txos WHERE unspent = 1 AND expiredAt = 0;`;
const [rows] = await DB.query(query);
return rows[0];
}
// Get the total number of federation utxos
public async $getFederationUtxosNumber(): Promise<any> {
const query = `SELECT COUNT(*) AS utxo_count FROM federation_txos WHERE unspent = 1 AND expiredAt = 0;`;
const [rows] = await DB.query(query);
return rows[0];
}
// Get the total number of emergency spent utxos and their total amount
public async $getEmergencySpentUtxosStats(): Promise<any> {
const query = `SELECT COUNT(*) AS utxo_count, SUM(amount) AS total_amount FROM federation_txos WHERE emergencyKey = 1;`;
const [rows] = await DB.query(query);
return rows[0];
}
// Get recent pegs in / out
public async $getPegsList(count: number = 0): Promise<any> {
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<any> {
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<any> {
const [rows] = await DB.query(`SELECT COUNT(*) AS pegs_count FROM elements_pegs;`);
return rows[0];
}
}
export default new ElementsParser();

View File

@@ -2,7 +2,7 @@ import * as fs from 'fs';
import logger from '../../logger';
class Icons {
private static FILE_NAME = './icons.json';
private static FILE_NAME = '/elements/asset_registry_db/icons.json';
private iconIds: string[] = [];
private icons: { [assetId: string]: string; } = {};

View File

@@ -15,7 +15,21 @@ 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/utxos/expired', this.$getExpiredUtxos)
.get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/utxos/emergency-spent', this.$getEmergencySpentUtxos)
.get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/utxos/emergency-spent/stats', this.$getEmergencySpentUtxosStats)
.get(config.MEMPOOL.API_URL_PREFIX + 'liquid/reserves/status', this.$getFederationAuditStatus)
;
}
}
@@ -63,11 +77,183 @@ 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 $getExpiredUtxos(req: Request, res: Response) {
try {
const expiredUtxos = await elementsParser.$getExpiredUtxos();
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString());
res.json(expiredUtxos);
} 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 $getEmergencySpentUtxos(req: Request, res: Response) {
try {
const emergencySpentUtxos = await elementsParser.$getEmergencySpentUtxos();
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString());
res.json(emergencySpentUtxos);
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async $getEmergencySpentUtxosStats(req: Request, res: Response) {
try {
const emergencySpentUtxos = await elementsParser.$getEmergencySpentUtxosStats();
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString());
res.json(emergencySpentUtxos);
} 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();

View File

@@ -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()));
}
}

View File

@@ -1,16 +1,24 @@
import { GbtGenerator, GbtResult, ThreadTransaction as RustThreadTransaction, ThreadAcceleration as RustThreadAcceleration } from 'rust-gbt';
import logger from '../logger';
import { MempoolBlock, TransactionExtended, ThreadTransaction, TransactionStripped, MempoolBlockWithTransactions, MempoolBlockDelta, Ancestor } from '../mempool.interfaces';
import { Common } from './common';
import { MempoolBlock, MempoolTransactionExtended, MempoolBlockWithTransactions, MempoolBlockDelta, Ancestor, CompactThreadTransaction, EffectiveFeeStats, TransactionClassified, TransactionCompressed, MempoolDeltaChange, GbtCandidates } from '../mempool.interfaces';
import { Common, OnlineFeeStatsCalculator } from './common';
import config from '../config';
import { Worker } from 'worker_threads';
import path from 'path';
import mempool from './mempool';
const MAX_UINT32 = Math.pow(2, 32) - 1;
class MempoolBlocks {
private mempoolBlocks: MempoolBlockWithTransactions[] = [];
private mempoolBlockDeltas: MempoolBlockDelta[] = [];
private txSelectionWorker: Worker | null = null;
private rustInitialized: boolean = false;
private rustGbtGenerator: GbtGenerator = new GbtGenerator();
constructor() {}
private nextUid: number = 1;
private uidMap: Map<number, string> = new Map(); // map short numerical uids to full txids
private txidMap: Map<string, number> = new Map(); // map full txids back to short numerical uids
public getMempoolBlocks(): MempoolBlock[] {
return this.mempoolBlocks.map((block) => {
@@ -33,88 +41,12 @@ class MempoolBlocks {
return this.mempoolBlockDeltas;
}
public updateMempoolBlocks(memPool: { [txid: string]: TransactionExtended }, saveResults: boolean = false): MempoolBlockWithTransactions[] {
const latestMempool = memPool;
const memPoolArray: TransactionExtended[] = [];
for (const i in latestMempool) {
if (latestMempool.hasOwnProperty(i)) {
memPoolArray.push(latestMempool[i]);
}
}
const start = new Date().getTime();
// Clear bestDescendants & ancestors
memPoolArray.forEach((tx) => {
tx.bestDescendant = null;
tx.ancestors = [];
tx.cpfpChecked = false;
if (!tx.effectiveFeePerVsize) {
tx.effectiveFeePerVsize = tx.feePerVsize;
}
});
// First sort
memPoolArray.sort((a, b) => b.feePerVsize - a.feePerVsize);
// Loop through and traverse all ancestors and sum up all the sizes + fees
// Pass down size + fee to all unconfirmed children
let sizes = 0;
memPoolArray.forEach((tx, i) => {
sizes += tx.weight;
if (sizes > 4000000 * 8) {
return;
}
Common.setRelativesAndGetCpfpInfo(tx, memPool);
});
// Final sort, by effective fee
memPoolArray.sort((a, b) => b.effectiveFeePerVsize - a.effectiveFeePerVsize);
const end = new Date().getTime();
const time = end - start;
logger.debug('Mempool blocks calculated in ' + time / 1000 + ' seconds');
const blocks = this.calculateMempoolBlocks(memPoolArray, this.mempoolBlocks);
if (saveResults) {
const deltas = this.calculateMempoolDeltas(this.mempoolBlocks, blocks);
this.mempoolBlocks = blocks;
this.mempoolBlockDeltas = deltas;
}
return blocks;
}
private calculateMempoolBlocks(transactionsSorted: TransactionExtended[], prevBlocks: MempoolBlockWithTransactions[]): MempoolBlockWithTransactions[] {
const mempoolBlocks: MempoolBlockWithTransactions[] = [];
let blockWeight = 0;
let blockSize = 0;
let transactions: TransactionExtended[] = [];
transactionsSorted.forEach((tx) => {
if (blockWeight + tx.weight <= config.MEMPOOL.BLOCK_WEIGHT_UNITS
|| mempoolBlocks.length === config.MEMPOOL.MEMPOOL_BLOCKS_AMOUNT - 1) {
blockWeight += tx.weight;
blockSize += tx.size;
transactions.push(tx);
} else {
mempoolBlocks.push(this.dataToMempoolBlocks(transactions, mempoolBlocks.length));
blockWeight = tx.weight;
blockSize = tx.size;
transactions = [tx];
}
});
if (transactions.length) {
mempoolBlocks.push(this.dataToMempoolBlocks(transactions, mempoolBlocks.length));
}
return 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: TransactionClassified[] = [];
if (mempoolBlocks[i] && !prevBlocks[i]) {
added = mempoolBlocks[i].transactions;
} else if (!mempoolBlocks[i] && prevBlocks[i]) {
@@ -123,7 +55,7 @@ class MempoolBlocks {
const prevIds = {};
const newIds = {};
prevBlocks[i].transactions.forEach(tx => {
prevIds[tx.txid] = true;
prevIds[tx.txid] = tx;
});
mempoolBlocks[i].transactions.forEach(tx => {
newIds[tx.txid] = true;
@@ -136,31 +68,53 @@ class MempoolBlocks {
mempoolBlocks[i].transactions.forEach(tx => {
if (!prevIds[tx.txid]) {
added.push(tx);
} else if (tx.rate !== prevIds[tx.txid].rate || tx.acc !== prevIds[tx.txid].acc) {
changed.push(tx);
}
});
}
mempoolBlockDeltas.push({
added,
removed
added: added.map(this.compressTx),
removed,
changed: changed.map(this.compressDeltaChange),
});
}
return mempoolBlockDeltas;
}
public async makeBlockTemplates(newMempool: { [txid: string]: TransactionExtended }, saveResults: boolean = false): Promise<MempoolBlockWithTransactions[]> {
public async $makeBlockTemplates(transactions: string[], newMempool: { [txid: string]: MempoolTransactionExtended }, candidates: GbtCandidates | undefined, saveResults: boolean = false, useAccelerations: boolean = false, accelerationPool?: number): Promise<MempoolBlockWithTransactions[]> {
const start = Date.now();
// reset mempool short ids
if (saveResults) {
this.resetUids();
}
// set missing short ids
for (const txid of transactions) {
const tx = newMempool[txid];
this.setUid(tx, !saveResults);
}
const accelerations = useAccelerations ? mempool.getAccelerations() : {};
// prepare a stripped down version of the mempool with only the minimum necessary data
// to reduce the overhead of passing this data to the worker thread
const strippedMempool: { [txid: string]: ThreadTransaction } = {};
Object.values(newMempool).forEach(entry => {
strippedMempool[entry.txid] = {
txid: entry.txid,
fee: entry.fee,
weight: entry.weight,
feePerVsize: entry.fee / (entry.weight / 4),
effectiveFeePerVsize: entry.fee / (entry.weight / 4),
vin: entry.vin.map(v => v.txid),
};
});
const strippedMempool: Map<number, CompactThreadTransaction> = new Map();
for (const txid of transactions) {
const entry = newMempool[txid];
if (entry.uid !== null && entry.uid !== undefined) {
const stripped = {
uid: entry.uid,
fee: entry.fee + (useAccelerations && (!accelerationPool || accelerations[entry.txid]?.pools?.includes(accelerationPool)) ? (accelerations[entry.txid]?.feeDelta || 0) : 0),
weight: (entry.adjustedVsize * 4),
sigops: entry.sigops,
feePerVsize: entry.adjustedFeePerVsize || entry.feePerVsize,
effectiveFeePerVsize: entry.effectiveFeePerVsize || entry.adjustedFeePerVsize || entry.feePerVsize,
inputs: entry.vin.map(v => this.getUid(newMempool[v.txid])).filter(uid => (uid !== null && uid !== undefined)) as number[],
};
strippedMempool.set(entry.uid, stripped);
}
}
// (re)initialize tx selection worker thread
if (!this.txSelectionWorker) {
@@ -178,7 +132,7 @@ class MempoolBlocks {
// run the block construction algorithm in a separate thread, and wait for a result
let threadErrorListener;
try {
const workerResultPromise = new Promise<{ blocks: ThreadTransaction[][], clusters: { [root: string]: string[] } }>((resolve, reject) => {
const workerResultPromise = new Promise<{ blocks: number[][], rates: Map<number, number>, clusters: Map<number, number[]> }>((resolve, reject) => {
threadErrorListener = reject;
this.txSelectionWorker?.once('message', (result): void => {
resolve(result);
@@ -186,144 +140,488 @@ class MempoolBlocks {
this.txSelectionWorker?.once('error', reject);
});
this.txSelectionWorker.postMessage({ type: 'set', mempool: strippedMempool });
const { blocks, clusters } = await workerResultPromise;
const { blocks, rates, clusters } = this.convertResultTxids(await workerResultPromise);
// clean up thread error listener
this.txSelectionWorker?.removeListener('error', threadErrorListener);
return this.processBlockTemplates(newMempool, blocks, clusters, saveResults);
const processed = this.processBlockTemplates(newMempool, blocks, null, Object.entries(rates), Object.values(clusters), candidates, accelerations, accelerationPool, saveResults);
logger.debug(`makeBlockTemplates completed in ${(Date.now() - start)/1000} seconds`);
return processed;
} catch (e) {
logger.err('makeBlockTemplates failed. ' + (e instanceof Error ? e.message : e));
}
return this.mempoolBlocks;
}
public async updateBlockTemplates(newMempool: { [txid: string]: TransactionExtended }, added: TransactionExtended[], removed: string[], saveResults: boolean = false): Promise<void> {
public async $updateBlockTemplates(transactions: string[], newMempool: { [txid: string]: MempoolTransactionExtended }, added: MempoolTransactionExtended[], removed: MempoolTransactionExtended[], candidates: GbtCandidates | undefined, accelerationDelta: string[] = [], saveResults: boolean = false, useAccelerations: boolean = false): Promise<void> {
if (!this.txSelectionWorker) {
// need to reset the worker
this.makeBlockTemplates(newMempool, saveResults);
await this.$makeBlockTemplates(transactions, newMempool, candidates, saveResults, useAccelerations);
return;
}
const start = Date.now();
const accelerations = useAccelerations ? mempool.getAccelerations() : {};
const addedAndChanged: MempoolTransactionExtended[] = useAccelerations ? accelerationDelta.map(txid => newMempool[txid]).filter(tx => tx != null).concat(added) : added;
for (const tx of addedAndChanged) {
this.setUid(tx, false);
}
const removedTxs = removed.filter(tx => tx.uid != null) as MempoolTransactionExtended[];
// prepare a stripped down version of the mempool with only the minimum necessary data
// to reduce the overhead of passing this data to the worker thread
const addedStripped: ThreadTransaction[] = added.map(entry => {
const addedStripped: CompactThreadTransaction[] = addedAndChanged.filter(entry => entry.uid != null).map(entry => {
return {
txid: entry.txid,
fee: entry.fee,
weight: entry.weight,
feePerVsize: entry.fee / (entry.weight / 4),
effectiveFeePerVsize: entry.fee / (entry.weight / 4),
vin: entry.vin.map(v => v.txid),
uid: entry.uid || 0,
fee: entry.fee + (useAccelerations ? (accelerations[entry.txid]?.feeDelta || 0) : 0),
weight: (entry.adjustedVsize * 4),
sigops: entry.sigops,
feePerVsize: entry.adjustedFeePerVsize || entry.feePerVsize,
effectiveFeePerVsize: entry.effectiveFeePerVsize || entry.adjustedFeePerVsize || entry.feePerVsize,
inputs: entry.vin.map(v => this.getUid(newMempool[v.txid])).filter(uid => (uid !== null && uid !== undefined)) as number[],
};
});
// run the block construction algorithm in a separate thread, and wait for a result
let threadErrorListener;
try {
const workerResultPromise = new Promise<{ blocks: ThreadTransaction[][], clusters: { [root: string]: string[] } }>((resolve, reject) => {
const workerResultPromise = new Promise<{ blocks: number[][], rates: Map<number, number>, clusters: Map<number, number[]> }>((resolve, reject) => {
threadErrorListener = reject;
this.txSelectionWorker?.once('message', (result): void => {
resolve(result);
});
this.txSelectionWorker?.once('error', reject);
});
this.txSelectionWorker.postMessage({ type: 'update', added: addedStripped, removed });
const { blocks, clusters } = await workerResultPromise;
this.txSelectionWorker.postMessage({ type: 'update', added: addedStripped, removed: removedTxs.map(tx => tx.uid) as number[] });
const { blocks, rates, clusters } = this.convertResultTxids(await workerResultPromise);
this.removeUids(removedTxs);
// clean up thread error listener
this.txSelectionWorker?.removeListener('error', threadErrorListener);
this.processBlockTemplates(newMempool, blocks, clusters, saveResults);
this.processBlockTemplates(newMempool, blocks, null, Object.entries(rates), Object.values(clusters), candidates, accelerations, null, saveResults);
logger.debug(`updateBlockTemplates completed in ${(Date.now() - start) / 1000} seconds`);
} catch (e) {
logger.err('updateBlockTemplates failed. ' + (e instanceof Error ? e.message : e));
}
}
private processBlockTemplates(mempool, blocks, clusters, saveResults): MempoolBlockWithTransactions[] {
// update this thread's mempool with the results
blocks.forEach(block => {
block.forEach(tx => {
if (tx.txid in mempool) {
if (tx.effectiveFeePerVsize != null) {
mempool[tx.txid].effectiveFeePerVsize = tx.effectiveFeePerVsize;
}
if (tx.cpfpRoot && tx.cpfpRoot in clusters) {
const ancestors: Ancestor[] = [];
const descendants: Ancestor[] = [];
const cluster = clusters[tx.cpfpRoot];
let matched = false;
cluster.forEach(txid => {
if (txid === tx.txid) {
matched = true;
} else {
const relative = {
txid: txid,
fee: mempool[txid].fee,
weight: mempool[txid].weight,
};
if (matched) {
descendants.push(relative);
} else {
ancestors.push(relative);
}
}
});
mempool[tx.txid].ancestors = ancestors;
mempool[tx.txid].descendants = descendants;
mempool[tx.txid].bestDescendant = null;
}
mempool[tx.txid].cpfpChecked = tx.cpfpChecked;
}
});
private resetRustGbt(): void {
this.rustInitialized = false;
this.rustGbtGenerator = new GbtGenerator();
}
public async $rustMakeBlockTemplates(txids: string[], newMempool: { [txid: string]: MempoolTransactionExtended }, candidates: GbtCandidates | undefined, saveResults: boolean = false, useAccelerations: boolean = false, accelerationPool?: number): Promise<MempoolBlockWithTransactions[]> {
const start = Date.now();
// reset mempool short ids
if (saveResults) {
this.resetUids();
}
const transactions = txids.map(txid => newMempool[txid]).filter(tx => tx != null);
// set missing short ids
for (const tx of transactions) {
this.setUid(tx, !saveResults);
}
// set short ids for transaction inputs
for (const tx of transactions) {
tx.inputs = tx.vin.map(v => this.getUid(newMempool[v.txid])).filter(uid => (uid !== null && uid !== undefined)) as number[];
}
const accelerations = useAccelerations ? mempool.getAccelerations() : {};
const acceleratedList = accelerationPool ? Object.values(accelerations).filter(acc => newMempool[acc.txid] && acc.pools.includes(accelerationPool)) : Object.values(accelerations).filter(acc => newMempool[acc.txid]);
const convertedAccelerations = acceleratedList.map(acc => {
this.setUid(newMempool[acc.txid], true);
return {
uid: this.getUid(newMempool[acc.txid]),
delta: acc.feeDelta,
};
});
// unpack the condensed blocks into proper mempool blocks
const mempoolBlocks = blocks.map((transactions, blockIndex) => {
return this.dataToMempoolBlocks(transactions.map(tx => {
return mempool[tx.txid] || null;
}).filter(tx => !!tx), blockIndex);
// 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, overflow } = this.convertNapiResultTxids(
await rustGbt.make(transactions as RustThreadTransaction[], convertedAccelerations as RustThreadAcceleration[], this.nextUid),
);
if (saveResults) {
this.rustInitialized = true;
}
const expectedSize = transactions.length;
const resultMempoolSize = blocks.reduce((total, block) => total + block.length, 0) + overflow.length;
logger.debug(`RUST updateBlockTemplates returned ${resultMempoolSize} txs out of ${expectedSize} in the mempool, ${overflow.length} were unmineable`);
const processed = this.processBlockTemplates(newMempool, blocks, blockWeights, rates, clusters, candidates, accelerations, accelerationPool, saveResults);
logger.debug(`RUST makeBlockTemplates completed in ${(Date.now() - start)/1000} seconds`);
return processed;
} catch (e) {
logger.err('RUST makeBlockTemplates failed. ' + (e instanceof Error ? e.message : e));
if (saveResults) {
this.resetRustGbt();
}
}
return this.mempoolBlocks;
}
public async $oneOffRustBlockTemplates(transactions: string[], newMempool: { [txid: string]: MempoolTransactionExtended }, candidates: GbtCandidates | undefined, useAccelerations: boolean, accelerationPool?: number): Promise<MempoolBlockWithTransactions[]> {
return this.$rustMakeBlockTemplates(transactions, newMempool, candidates, false, useAccelerations, accelerationPool);
}
public async $rustUpdateBlockTemplates(transactions: string[], newMempool: { [txid: string]: MempoolTransactionExtended }, added: MempoolTransactionExtended[], removed: MempoolTransactionExtended[], candidates: GbtCandidates | undefined, useAccelerations: boolean, accelerationPool?: number): Promise<MempoolBlockWithTransactions[]> {
// GBT optimization requires that uids never get too sparse
// as a sanity check, we should also explicitly prevent uint32 uid overflow
if (this.nextUid + added.length >= Math.min(Math.max(262144, 2 * transactions.length), MAX_UINT32)) {
this.resetRustGbt();
}
if (!this.rustInitialized) {
// need to reset the worker
return this.$rustMakeBlockTemplates(transactions, newMempool, candidates, true, useAccelerations, accelerationPool);
}
const start = Date.now();
// set missing short ids
for (const tx of added) {
this.setUid(tx, false);
}
// set short ids for transaction inputs
for (const tx of added) {
tx.inputs = tx.vin.map(v => this.getUid(newMempool[v.txid])).filter(uid => (uid !== null && uid !== undefined)) as number[];
}
const removedTxs = removed.filter(tx => tx.uid != null) as MempoolTransactionExtended[];
const accelerations = useAccelerations ? mempool.getAccelerations() : {};
const acceleratedList = accelerationPool ? Object.values(accelerations).filter(acc => newMempool[acc.txid] && acc.pools.includes(accelerationPool)) : Object.values(accelerations).filter(acc => newMempool[acc.txid]);
const convertedAccelerations = acceleratedList.map(acc => {
this.setUid(newMempool[acc.txid], true);
return {
uid: this.getUid(newMempool[acc.txid]),
delta: acc.feeDelta,
};
});
// run the block construction algorithm in a separate thread, and wait for a result
try {
const { blocks, blockWeights, rates, clusters, overflow } = this.convertNapiResultTxids(
await this.rustGbtGenerator.update(
added as RustThreadTransaction[],
removedTxs.map(tx => tx.uid) as number[],
convertedAccelerations as RustThreadAcceleration[],
this.nextUid,
),
);
const resultMempoolSize = blocks.reduce((total, block) => total + block.length, 0) + overflow.length;
logger.debug(`RUST updateBlockTemplates returned ${resultMempoolSize} txs out of ${transactions.length} candidates, ${overflow.length} were unmineable`);
if (transactions.length !== resultMempoolSize) {
throw new Error(`GBT returned wrong number of transactions ${transactions.length} vs ${resultMempoolSize}, cache is probably out of sync`);
} else {
const processed = this.processBlockTemplates(newMempool, blocks, blockWeights, rates, clusters, candidates, accelerations, accelerationPool, true);
this.removeUids(removedTxs);
logger.debug(`RUST updateBlockTemplates completed in ${(Date.now() - start)/1000} seconds`);
return processed;
}
} catch (e) {
logger.err('RUST updateBlockTemplates failed. ' + (e instanceof Error ? e.message : e));
this.resetRustGbt();
return this.mempoolBlocks;
}
}
private processBlockTemplates(mempool: { [txid: string]: MempoolTransactionExtended }, blocks: string[][], blockWeights: number[] | null, rates: [string, number][], clusters: string[][], candidates: GbtCandidates | undefined, accelerations, accelerationPool, saveResults): MempoolBlockWithTransactions[] {
for (const txid of Object.keys(candidates?.txs ?? mempool)) {
if (txid in mempool) {
mempool[txid].cpfpDirty = false;
}
}
for (const [txid, rate] of rates) {
if (txid in mempool) {
mempool[txid].cpfpDirty = (rate !== mempool[txid].effectiveFeePerVsize);
mempool[txid].effectiveFeePerVsize = rate;
mempool[txid].cpfpChecked = false;
}
}
const lastBlockIndex = blocks.length - 1;
let hasBlockStack = blocks.length >= 8;
let stackWeight;
let feeStatsCalculator: OnlineFeeStatsCalculator | void;
if (hasBlockStack) {
if (blockWeights && blockWeights[7] !== null) {
stackWeight = blockWeights[7];
} else {
stackWeight = blocks[lastBlockIndex].reduce((total, tx) => total + (mempool[tx]?.weight || 0), 0);
}
hasBlockStack = stackWeight > config.MEMPOOL.BLOCK_WEIGHT_UNITS;
feeStatsCalculator = new OnlineFeeStatsCalculator(stackWeight, 0.5, [10, 20, 30, 40, 50, 60, 70, 80, 90]);
}
for (const cluster of clusters) {
for (const memberTxid of cluster) {
const mempoolTx = mempool[memberTxid];
if (mempoolTx) {
const ancestors: Ancestor[] = [];
const descendants: Ancestor[] = [];
let matched = false;
cluster.forEach(txid => {
if (txid === memberTxid) {
matched = true;
} else {
if (!mempool[txid]) {
console.log('txid missing from mempool! ', txid, candidates?.txs[txid]);
}
const relative = {
txid: txid,
fee: mempool[txid].fee,
weight: (mempool[txid].adjustedVsize * 4),
};
if (matched) {
descendants.push(relative);
mempoolTx.lastBoosted = Math.max(mempoolTx.lastBoosted || 0, mempool[txid].firstSeen || 0);
} else {
ancestors.push(relative);
}
}
});
if (mempoolTx.ancestors?.length !== ancestors.length || mempoolTx.descendants?.length !== descendants.length) {
mempoolTx.cpfpDirty = true;
}
Object.assign(mempoolTx, {ancestors, descendants, bestDescendant: null, cpfpChecked: true});
}
}
}
const isAccelerated : { [txid: string]: boolean } = {};
const sizeLimit = (config.MEMPOOL.BLOCK_WEIGHT_UNITS / 4) * 1.2;
// update this thread's mempool with the results
let mempoolTx: MempoolTransactionExtended;
const mempoolBlocks: MempoolBlockWithTransactions[] = blocks.map((block, blockIndex) => {
let totalSize = 0;
let totalVsize = 0;
let totalWeight = 0;
let totalFees = 0;
const transactions: MempoolTransactionExtended[] = [];
// backfill purged transactions
if (candidates?.txs && blockIndex === blocks.length - 1) {
for (const txid of Object.keys(mempool)) {
if (!candidates.txs[txid]) {
block.push(txid);
}
}
}
for (const txid of block) {
if (txid) {
mempoolTx = mempool[txid];
// save position in projected blocks
mempoolTx.position = {
block: blockIndex,
vsize: totalVsize + (mempoolTx.vsize / 2),
};
const acceleration = accelerations[txid];
if (isAccelerated[txid] || (acceleration && (!accelerationPool || acceleration.pools.includes(accelerationPool)))) {
if (!mempoolTx.acceleration) {
mempoolTx.cpfpDirty = true;
}
mempoolTx.acceleration = true;
for (const ancestor of mempoolTx.ancestors || []) {
if (!mempool[ancestor.txid].acceleration) {
mempool[ancestor.txid].cpfpDirty = true;
}
mempool[ancestor.txid].acceleration = true;
isAccelerated[ancestor.txid] = true;
}
} else {
if (mempoolTx.acceleration) {
mempoolTx.cpfpDirty = true;
}
delete mempoolTx.acceleration;
}
// online calculation of stack-of-blocks fee stats
if (hasBlockStack && blockIndex === lastBlockIndex && feeStatsCalculator) {
feeStatsCalculator.processNext(mempoolTx);
}
totalSize += mempoolTx.size;
totalVsize += mempoolTx.vsize;
totalWeight += mempoolTx.weight;
totalFees += mempoolTx.fee;
if (totalVsize <= sizeLimit) {
transactions.push(mempoolTx);
}
}
}
return this.dataToMempoolBlocks(
block,
transactions,
totalSize,
totalWeight,
totalFees,
(hasBlockStack && blockIndex === lastBlockIndex && feeStatsCalculator) ? feeStatsCalculator.getRawFeeStats() : undefined,
);
});
if (saveResults) {
const deltas = this.calculateMempoolDeltas(this.mempoolBlocks, mempoolBlocks);
this.mempoolBlocks = mempoolBlocks;
this.mempoolBlockDeltas = deltas;
}
return mempoolBlocks;
}
private dataToMempoolBlocks(transactions: TransactionExtended[], blocksIndex: number): MempoolBlockWithTransactions {
let totalSize = 0;
let totalWeight = 0;
const fitTransactions: TransactionExtended[] = [];
transactions.forEach(tx => {
totalSize += tx.size;
totalWeight += tx.weight;
if ((totalWeight + tx.weight) <= config.MEMPOOL.BLOCK_WEIGHT_UNITS * 1.2) {
fitTransactions.push(tx);
}
});
let rangeLength = 4;
if (blocksIndex === 0) {
rangeLength = 8;
}
if (transactions.length > 4000) {
rangeLength = 6;
} else if (transactions.length > 10000) {
rangeLength = 8;
private dataToMempoolBlocks(transactionIds: string[], transactions: MempoolTransactionExtended[], totalSize: number, totalWeight: number, totalFees: number, feeStats?: EffectiveFeeStats ): MempoolBlockWithTransactions {
if (!feeStats) {
feeStats = Common.calcEffectiveFeeStatistics(transactions);
}
return {
blockSize: totalSize,
blockVSize: totalWeight / 4,
nTx: transactions.length,
totalFees: transactions.reduce((acc, cur) => acc + cur.fee, 0),
medianFee: Common.percentile(transactions.map((tx) => tx.effectiveFeePerVsize), config.MEMPOOL.RECOMMENDED_FEE_PERCENTILE),
feeRange: Common.getFeesInRange(transactions, rangeLength),
transactionIds: transactions.map((tx) => tx.txid),
transactions: fitTransactions.map((tx) => Common.stripTransaction(tx)),
blockVSize: (totalWeight / 4), // fractional vsize to avoid rounding errors
nTx: transactionIds.length,
totalFees: totalFees,
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.classifyTransaction(tx)),
};
}
private resetUids(): void {
this.uidMap.clear();
this.txidMap.clear();
this.nextUid = 1;
}
private setUid(tx: MempoolTransactionExtended, skipSet = false): number {
if (!this.txidMap.has(tx.txid) || !skipSet) {
const uid = this.nextUid;
this.nextUid++;
this.uidMap.set(uid, tx.txid);
this.txidMap.set(tx.txid, uid);
tx.uid = uid;
return uid;
} else {
tx.uid = this.txidMap.get(tx.txid) as number;
return tx.uid;
}
}
private getUid(tx: MempoolTransactionExtended): number | void {
if (tx) {
return this.txidMap.get(tx.txid);
}
}
private removeUids(txs: MempoolTransactionExtended[]): void {
for (const tx of txs) {
const uid = this.txidMap.get(tx.txid);
if (uid != null) {
this.uidMap.delete(uid);
this.txidMap.delete(tx.txid);
}
tx.uid = undefined;
}
}
private convertResultTxids({ blocks, rates, clusters }: { blocks: number[][], rates: Map<number, number>, clusters: Map<number, number[]>})
: { blocks: string[][], rates: { [root: string]: number }, clusters: { [root: string]: string[] }} {
const convertedBlocks: string[][] = blocks.map(block => block.map(uid => {
return this.uidMap.get(uid) || '';
}));
const convertedRates = {};
for (const rateUid of rates.keys()) {
const rateTxid = this.uidMap.get(rateUid);
if (rateTxid) {
convertedRates[rateTxid] = rates.get(rateUid);
}
}
const convertedClusters = {};
for (const rootUid of clusters.keys()) {
const rootTxid = this.uidMap.get(rootUid);
if (rootTxid) {
const members = clusters.get(rootUid)?.map(uid => {
return this.uidMap.get(uid);
});
convertedClusters[rootTxid] = members;
}
}
return { blocks: convertedBlocks, rates: convertedRates, clusters: convertedClusters } as { blocks: string[][], rates: { [root: string]: number }, clusters: { [root: string]: 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) {
return txid;
} else {
throw new Error('GBT returned a block containing a transaction with unknown uid');
}
}));
const convertedRates: [string, number][] = [];
for (const [rateUid, rate] of rates) {
const rateTxid = this.uidMap.get(rateUid) as string;
convertedRates.push([rateTxid, rate]);
}
const convertedClusters: string[][] = [];
for (const cluster of clusters) {
convertedClusters.push(cluster.map(uid => this.uidMap.get(uid)) as string[]);
}
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,
tx.time || 0,
1,
];
} else {
return [
tx.txid,
tx.fee,
tx.vsize,
tx.value,
Math.round((tx.rate || (tx.fee / tx.vsize)) * 100) / 100,
tx.flags,
tx.time || 0,
];
}
}
public compressDeltaChange(tx: TransactionClassified): MempoolDeltaChange {
return [
tx.txid,
Math.round((tx.rate || (tx.fee / tx.vsize)) * 100) / 100,
tx.flags,
tx.acc ? 1 : 0,
];
}
}
export default new MempoolBlocks();

View File

@@ -1,6 +1,6 @@
import config from '../config';
import bitcoinApi from './bitcoin/bitcoin-api-factory';
import { TransactionExtended, VbytesPerSecond } from '../mempool.interfaces';
import { MempoolTransactionExtended, TransactionExtended, VbytesPerSecond, GbtCandidates } from '../mempool.interfaces';
import logger from '../logger';
import { Common } from './common';
import transactionUtils from './transaction-utils';
@@ -9,19 +9,24 @@ import loadingIndicators from './loading-indicators';
import bitcoinClient from './bitcoin/bitcoin-client';
import bitcoinSecondClient from './bitcoin/bitcoin-second-client';
import rbfCache from './rbf-cache';
import { Acceleration } from './services/acceleration';
import redisCache from './redis-cache';
import blocks from './blocks';
class Mempool {
private static WEBSOCKET_REFRESH_RATE_MS = 10000;
private static LAZY_DELETE_AFTER_SECONDS = 30;
private inSync: boolean = false;
private mempoolCacheDelta: number = -1;
private mempoolCache: { [txId: string]: TransactionExtended } = {};
private mempoolCache: { [txId: string]: MempoolTransactionExtended } = {};
private mempoolCandidates: { [txid: string ]: boolean } = {};
private spendMap = new Map<string, MempoolTransactionExtended>();
private mempoolInfo: IBitcoinApi.MempoolInfo = { loaded: false, size: 0, bytes: 0, usage: 0, total_fee: 0,
maxmempool: 300000000, mempoolminfee: 0.00001000, minrelaytxfee: 0.00001000 };
private mempoolChangedCallback: ((newMempool: {[txId: string]: TransactionExtended; }, newTransactions: TransactionExtended[],
deletedTransactions: TransactionExtended[]) => void) | undefined;
private asyncMempoolChangedCallback: ((newMempool: {[txId: string]: TransactionExtended; }, newTransactions: TransactionExtended[],
deletedTransactions: TransactionExtended[]) => Promise<void>) | undefined;
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[],
deletedTransactions: MempoolTransactionExtended[], accelerationDelta: string[], candidates?: GbtCandidates) => Promise<void>) | undefined;
private accelerations: { [txId: string]: Acceleration } = {};
private txPerSecondArray: number[] = [];
private txPerSecond: number = 0;
@@ -35,10 +40,12 @@ class Mempool {
private SAMPLE_TIME = 10000; // In ms
private timer = new Date().getTime();
private missingTxCount = 0;
private mainLoopTimeout: number = 120000;
public limitGBT = config.MEMPOOL.USE_SECOND_NODE_FOR_MINFEE && config.MEMPOOL.LIMIT_GBT;
constructor() {
setInterval(this.updateTxPerSecond.bind(this), 1000);
setInterval(this.deleteExpiredTransactions.bind(this), 20000);
}
/**
@@ -65,28 +72,108 @@ class Mempool {
return this.latestTransactions;
}
public setMempoolChangedCallback(fn: (newMempool: { [txId: string]: TransactionExtended; },
newTransactions: TransactionExtended[], deletedTransactions: TransactionExtended[]) => void) {
public setMempoolChangedCallback(fn: (newMempool: { [txId: string]: MempoolTransactionExtended; },
newTransactions: MempoolTransactionExtended[], deletedTransactions: MempoolTransactionExtended[], accelerationDelta: string[]) => void): void {
this.mempoolChangedCallback = fn;
}
public setAsyncMempoolChangedCallback(fn: (newMempool: { [txId: string]: TransactionExtended; },
newTransactions: TransactionExtended[], deletedTransactions: TransactionExtended[]) => Promise<void>) {
this.asyncMempoolChangedCallback = fn;
public setAsyncMempoolChangedCallback(fn: (newMempool: { [txId: string]: MempoolTransactionExtended; }, mempoolSize: number,
newTransactions: MempoolTransactionExtended[], deletedTransactions: MempoolTransactionExtended[], accelerationDelta: string[],
candidates?: GbtCandidates) => Promise<void>): void {
this.$asyncMempoolChangedCallback = fn;
}
public getMempool(): { [txid: string]: TransactionExtended } {
public getMempool(): { [txid: string]: MempoolTransactionExtended } {
return this.mempoolCache;
}
public setMempool(mempoolData: { [txId: string]: TransactionExtended }) {
public getSpendMap(): Map<string, MempoolTransactionExtended> {
return this.spendMap;
}
public getFromSpendMap(txid, index): MempoolTransactionExtended | void {
return this.spendMap.get(`${txid}:${index}`);
}
public async $setMempool(mempoolData: { [txId: string]: MempoolTransactionExtended }) {
this.mempoolCache = mempoolData;
let count = 0;
const redisTimer = Date.now();
if (config.MEMPOOL.CACHE_ENABLED && config.REDIS.ENABLED) {
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].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]);
}
this.mempoolCache[txid].flags = Common.getTransactionFlags(this.mempoolCache[txid]);
this.mempoolCache[txid].cpfpChecked = false;
this.mempoolCache[txid].cpfpDirty = true;
this.mempoolCache[txid].cpfpUpdated = undefined;
}
if (config.MEMPOOL.CACHE_ENABLED && config.REDIS.ENABLED) {
await redisCache.$flushTransactions();
logger.debug(`Finished migrating cache transactions in ${((Date.now() - redisTimer) / 1000).toFixed(2)} seconds`);
}
if (this.mempoolChangedCallback) {
this.mempoolChangedCallback(this.mempoolCache, [], []);
this.mempoolChangedCallback(this.mempoolCache, [], [], []);
}
if (this.asyncMempoolChangedCallback) {
this.asyncMempoolChangedCallback(this.mempoolCache, [], []);
if (this.$asyncMempoolChangedCallback) {
await this.$asyncMempoolChangedCallback(this.mempoolCache, count, [], [], [], this.limitGBT ? { txs: {}, added: [], removed: [] } : undefined);
}
this.addToSpendMap(Object.values(this.mempoolCache));
}
public async $reloadMempool(expectedCount: number): Promise<MempoolTransactionExtended[]> {
let count = 0;
let done = false;
let last_txid;
const newTransactions: MempoolTransactionExtended[] = [];
loadingIndicators.setProgress('mempool', count / expectedCount * 100);
while (!done) {
try {
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);
if (!this.mempoolCache[extendedTransaction.txid]) {
newTransactions.push(extendedTransaction);
this.mempoolCache[extendedTransaction.txid] = extendedTransaction;
}
count++;
}
logger.info(`Fetched ${count} of ${expectedCount} mempool transactions from esplora`);
if (result.length > 0) {
last_txid = result[result.length - 1].txid;
} else {
done = true;
}
if (Math.floor((count / expectedCount) * 100) < 100) {
loadingIndicators.setProgress('mempool', count / expectedCount * 100);
}
} else {
done = true;
}
} catch(err) {
logger.err('failed to fetch bulk mempool transactions from esplora');
}
}
logger.info(`Done inserting loaded mempool transactions into local cache`);
return newTransactions;
}
public getMempoolCandidates(): { [txid: string]: boolean } {
return this.mempoolCandidates;
}
public async $updateMemPoolInfo() {
@@ -118,19 +205,23 @@ class Mempool {
return txTimes;
}
public async $updateMempool(): Promise<void> {
public async $updateMempool(transactions: string[], accelerations: Acceleration[] | null, minFeeMempool: string[], minFeeTip: number, pollRate: number): Promise<void> {
logger.debug(`Updating mempool...`);
// warn if this run stalls the main loop for more than 2 minutes
const timer = this.startTimer();
const start = new Date().getTime();
let hasChange: boolean = false;
const currentMempoolSize = Object.keys(this.mempoolCache).length;
const transactions = await bitcoinApi.$getRawMempool();
this.updateTimerProgress(timer, 'got raw mempool');
const diff = transactions.length - currentMempoolSize;
const newTransactions: TransactionExtended[] = [];
let newTransactions: MempoolTransactionExtended[] = [];
this.mempoolCacheDelta = Math.abs(diff);
if (!this.inSync) {
loadingIndicators.setProgress('mempool', Object.keys(this.mempoolCache).length / transactions.length * 100);
loadingIndicators.setProgress('mempool', currentMempoolSize / transactions.length * 100);
}
// https://github.com/mempool/mempool/issues/3283
@@ -143,11 +234,36 @@ class Mempool {
}
};
for (const txid of transactions) {
if (!this.mempoolCache[txid]) {
try {
const transaction = await transactionUtils.$getTransactionExtended(txid);
this.mempoolCache[txid] = transaction;
let intervalTimer = Date.now();
let loaded = false;
if (config.MEMPOOL.BACKEND === 'esplora' && currentMempoolSize < transactions.length * 0.5 && transactions.length > 20_000) {
this.inSync = false;
logger.info(`Missing ${transactions.length - currentMempoolSize} mempool transactions, attempting to reload in bulk from esplora`);
try {
newTransactions = await this.$reloadMempool(transactions.length);
if (config.REDIS.ENABLED) {
for (const tx of newTransactions) {
await redisCache.$addTransaction(tx);
}
}
loaded = true;
} catch (e) {
logger.err('failed to load mempool in bulk from esplora, falling back to fetching individual transactions');
}
}
if (!loaded) {
const remainingTxids = transactions.filter(txid => !this.mempoolCache[txid]);
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);
logger.debug(`fetched ${txs.length} transactions`);
this.updateTimerProgress(timer, 'fetched new transactions');
for (const transaction of txs) {
this.mempoolCache[transaction.txid] = transaction;
if (this.inSync) {
this.txPerSecondArray.push(new Date().getTime());
this.vBytesPerSecondArray.push({
@@ -157,16 +273,35 @@ class Mempool {
}
hasChange = true;
newTransactions.push(transaction);
} catch (e: any) {
if (config.MEMPOOL.BACKEND === 'esplora' && e.response?.status === 404) {
this.missingTxCount++;
}
logger.debug(`Error finding transaction '${txid}' in the mempool: ` + (e instanceof Error ? e.message : e));
}
}
if ((new Date().getTime()) - start > Mempool.WEBSOCKET_REFRESH_RATE_MS) {
break;
if (config.REDIS.ENABLED) {
await redisCache.$addTransaction(transaction);
}
}
if (txs.length < slice.length) {
const missing = slice.length - txs.length;
if (config.MEMPOOL.BACKEND === 'esplora') {
this.missingTxCount += missing;
}
logger.debug(`Error finding ${missing} transactions in the mempool: `);
}
if (Date.now() - intervalTimer > Math.max(pollRate * 2, 5_000)) {
if (this.inSync) {
// Break and restart mempool loop if we spend too much time processing
// new transactions that may lead to falling behind on block height
logger.debug('Breaking mempool loop because the 5s time limit exceeded.');
break;
} else {
const progress = (currentMempoolSize + newTransactions.length) / transactions.length * 100;
logger.debug(`Mempool is synchronizing. Processed ${newTransactions.length}/${diff} txs (${Math.round(progress)}%)`);
if (Math.floor(progress) < 100) {
loadingIndicators.setProgress('mempool', progress);
}
intervalTimer = Date.now();
}
}
}
}
@@ -188,11 +323,11 @@ class Mempool {
logger.warn(`Mempool clear protection triggered because transactions.length: ${transactions.length} and currentMempoolSize: ${currentMempoolSize}.`);
setTimeout(() => {
this.mempoolProtection = 2;
logger.warn('Mempool clear protection resumed.');
logger.warn('Mempool clear protection ended, normal operation resumed.');
}, 1000 * 60 * config.MEMPOOL.CLEAR_PROTECTION_MINUTES);
}
const deletedTransactions: TransactionExtended[] = [];
const deletedTransactions: MempoolTransactionExtended[] = [];
if (this.mempoolProtection !== 1) {
this.mempoolProtection = 0;
@@ -200,45 +335,236 @@ class Mempool {
const transactionsObject = {};
transactions.forEach((txId) => transactionsObject[txId] = true);
// Flag transactions for lazy deletion
// Delete evicted transactions from mempool
for (const tx in this.mempoolCache) {
if (!transactionsObject[tx] && !this.mempoolCache[tx].deleteAfter) {
if (!transactionsObject[tx]) {
deletedTransactions.push(this.mempoolCache[tx]);
this.mempoolCache[tx].deleteAfter = new Date().getTime() + Mempool.LAZY_DELETE_AFTER_SECONDS * 1000;
}
}
for (const tx of deletedTransactions) {
delete this.mempoolCache[tx.txid];
}
}
const candidates = await this.getNextCandidates(minFeeMempool, minFeeTip, deletedTransactions);
const newMempoolSize = currentMempoolSize + newTransactions.length - deletedTransactions.length;
const newTransactionsStripped = newTransactions.map((tx) => Common.stripTransaction(tx));
this.latestTransactions = newTransactionsStripped.concat(this.latestTransactions).slice(0, 6);
if (!this.inSync && transactions.length === Object.keys(this.mempoolCache).length) {
const accelerationDelta = accelerations != null ? await this.$updateAccelerations(accelerations) : [];
if (accelerationDelta.length) {
hasChange = true;
}
this.mempoolCacheDelta = Math.abs(transactions.length - newMempoolSize);
const candidatesChanged = candidates?.added?.length || candidates?.removed?.length;
if (this.mempoolChangedCallback && (hasChange || deletedTransactions.length)) {
this.mempoolChangedCallback(this.mempoolCache, newTransactions, deletedTransactions, accelerationDelta);
}
if (this.$asyncMempoolChangedCallback && (hasChange || deletedTransactions.length || candidatesChanged)) {
this.updateTimerProgress(timer, 'running async mempool callback');
await this.$asyncMempoolChangedCallback(this.mempoolCache, newMempoolSize, newTransactions, deletedTransactions, accelerationDelta, candidates);
this.updateTimerProgress(timer, 'completed async mempool callback');
}
if (!this.inSync && transactions.length === newMempoolSize) {
this.inSync = true;
logger.notice('The mempool is now in sync!');
loadingIndicators.setProgress('mempool', 100);
}
this.mempoolCacheDelta = Math.abs(transactions.length - Object.keys(this.mempoolCache).length);
if (this.mempoolChangedCallback && (hasChange || deletedTransactions.length)) {
this.mempoolChangedCallback(this.mempoolCache, newTransactions, deletedTransactions);
}
if (this.asyncMempoolChangedCallback && (hasChange || deletedTransactions.length)) {
await this.asyncMempoolChangedCallback(this.mempoolCache, newTransactions, deletedTransactions);
// Update Redis cache
if (config.REDIS.ENABLED) {
await redisCache.$flushTransactions();
await redisCache.$removeTransactions(deletedTransactions.map(tx => tx.txid));
await rbfCache.updateCache();
}
const end = new Date().getTime();
const time = end - start;
logger.debug(`Mempool updated in ${time / 1000} seconds. New size: ${Object.keys(this.mempoolCache).length} (${diff > 0 ? '+' + diff : diff})`);
this.clearTimer(timer);
}
public handleRbfTransactions(rbfTransactions: { [txid: string]: TransactionExtended; }) {
public getAccelerations(): { [txid: string]: Acceleration } {
return this.accelerations;
}
public $updateAccelerations(newAccelerations: Acceleration[]): string[] {
if (!config.MEMPOOL_SERVICES.ACCELERATIONS) {
return [];
}
try {
const changed: string[] = [];
const newAccelerationMap: { [txid: string]: Acceleration } = {};
for (const acceleration of newAccelerations) {
newAccelerationMap[acceleration.txid] = acceleration;
if (this.accelerations[acceleration.txid] == null) {
// new acceleration
changed.push(acceleration.txid);
} else {
if (this.accelerations[acceleration.txid].feeDelta !== acceleration.feeDelta) {
// feeDelta changed
changed.push(acceleration.txid);
} else if (this.accelerations[acceleration.txid].pools?.length) {
let poolsChanged = false;
const pools = new Set();
this.accelerations[acceleration.txid].pools.forEach(pool => {
pools.add(pool);
});
acceleration.pools.forEach(pool => {
if (!pools.has(pool)) {
poolsChanged = true;
} else {
pools.delete(pool);
}
});
if (pools.size > 0) {
poolsChanged = true;
}
if (poolsChanged) {
// pools changed
changed.push(acceleration.txid);
}
}
}
}
for (const oldTxid of Object.keys(this.accelerations)) {
if (!newAccelerationMap[oldTxid]) {
// removed
changed.push(oldTxid);
}
}
this.accelerations = newAccelerationMap;
return changed;
} catch (e: any) {
logger.debug(`Failed to update accelerations: ` + (e instanceof Error ? e.message : e));
return [];
}
}
public async getNextCandidates(minFeeTransactions: string[], blockHeight: number, deletedTransactions: MempoolTransactionExtended[]): Promise<GbtCandidates | undefined> {
if (this.limitGBT) {
const deletedTxsMap = {};
for (const tx of deletedTransactions) {
deletedTxsMap[tx.txid] = tx;
}
const newCandidateTxMap = {};
for (const txid of minFeeTransactions) {
if (this.mempoolCache[txid]) {
newCandidateTxMap[txid] = true;
}
}
const accelerations = this.getAccelerations();
for (const txid of Object.keys(accelerations)) {
if (this.mempoolCache[txid]) {
newCandidateTxMap[txid] = true;
}
}
const removed: MempoolTransactionExtended[] = [];
const added: MempoolTransactionExtended[] = [];
// don't prematurely remove txs included in a new block
if (blockHeight > blocks.getCurrentBlockHeight()) {
for (const txid of Object.keys(this.mempoolCandidates)) {
newCandidateTxMap[txid] = true;
}
} else {
for (const txid of Object.keys(this.mempoolCandidates)) {
if (!newCandidateTxMap[txid]) {
if (this.mempoolCache[txid]) {
removed.push(this.mempoolCache[txid]);
this.mempoolCache[txid].effectiveFeePerVsize = this.mempoolCache[txid].adjustedFeePerVsize;
this.mempoolCache[txid].ancestors = [];
this.mempoolCache[txid].descendants = [];
this.mempoolCache[txid].bestDescendant = null;
this.mempoolCache[txid].cpfpChecked = false;
this.mempoolCache[txid].cpfpUpdated = undefined;
} else if (deletedTxsMap[txid]) {
removed.push(deletedTxsMap[txid]);
}
}
}
}
for (const txid of Object.keys(newCandidateTxMap)) {
if (!this.mempoolCandidates[txid]) {
added.push(this.mempoolCache[txid]);
}
}
this.mempoolCandidates = newCandidateTxMap;
return {
txs: this.mempoolCandidates,
added,
removed
};
}
}
private startTimer() {
const state: any = {
start: Date.now(),
progress: 'begin $updateMempool',
timer: null,
};
state.timer = setTimeout(() => {
logger.err(`$updateMempool stalled at "${state.progress}"`);
}, this.mainLoopTimeout);
return state;
}
private updateTimerProgress(state, msg) {
state.progress = msg;
}
private clearTimer(state) {
if (state.timer) {
clearTimeout(state.timer);
}
}
public handleRbfTransactions(rbfTransactions: { [txid: string]: MempoolTransactionExtended[]; }): void {
for (const rbfTransaction in rbfTransactions) {
if (this.mempoolCache[rbfTransaction]) {
if (this.mempoolCache[rbfTransaction] && rbfTransactions[rbfTransaction]?.length) {
// Store replaced transactions
rbfCache.add(this.mempoolCache[rbfTransaction], rbfTransactions[rbfTransaction].txid);
// Erase the replaced transactions from the local mempool
delete this.mempoolCache[rbfTransaction];
rbfCache.add(rbfTransactions[rbfTransaction], this.mempoolCache[rbfTransaction]);
}
}
}
public handleMinedRbfTransactions(rbfTransactions: { [txid: string]: { replaced: MempoolTransactionExtended[], replacedBy: TransactionExtended }}): void {
for (const rbfTransaction in rbfTransactions) {
if (rbfTransactions[rbfTransaction].replacedBy && rbfTransactions[rbfTransaction]?.replaced?.length) {
// Store replaced transactions
rbfCache.add(rbfTransactions[rbfTransaction].replaced, transactionUtils.extendMempoolTransaction(rbfTransactions[rbfTransaction].replacedBy));
}
}
}
public addToSpendMap(transactions: MempoolTransactionExtended[]): void {
for (const tx of transactions) {
for (const vin of tx.vin) {
this.spendMap.set(`${vin.txid}:${vin.vout}`, tx);
}
}
}
public removeFromSpendMap(transactions: TransactionExtended[]): void {
for (const tx of transactions) {
for (const vin of tx.vin) {
const key = `${vin.txid}:${vin.vout}`;
if (this.spendMap.get(key)?.txid === tx.txid) {
this.spendMap.delete(key);
}
}
}
}
@@ -256,17 +582,6 @@ class Mempool {
}
}
private deleteExpiredTransactions() {
const now = new Date().getTime();
for (const tx in this.mempoolCache) {
const lazyDeleteAt = this.mempoolCache[tx].deleteAfter;
if (lazyDeleteAt && lazyDeleteAt < now) {
delete this.mempoolCache[tx];
rbfCache.evict(tx);
}
}
}
private $getMempoolInfo() {
if (config.MEMPOOL.USE_SECOND_NODE_FOR_MINFEE) {
return Promise.all([

View File

@@ -8,10 +8,12 @@ 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) {
app
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pools', this.$listPools)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pools/:interval', this.$getPools)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:slug/hashrate', this.$getPoolHistoricalHashrate)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:slug/blocks', this.$getPoolBlocks)
@@ -26,13 +28,18 @@ class MiningRoutes {
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/fee-rates/:interval', this.$getHistoricalBlockFeeRates)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/sizes-weights/:interval', this.$getHistoricalBlockSizeAndWeight)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/difficulty-adjustments/:interval', this.$getDifficultyAdjustments)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/predictions/:interval', this.$getHistoricalBlockPrediction)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/predictions/:interval', this.$getHistoricalBlocksHealth)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/audit/scores', this.$getBlockAuditScores)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/audit/scores/:height', this.$getBlockAuditScores)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/blocks/audit/score/:hash', this.$getBlockAuditScore)
.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)
.get(config.MEMPOOL.API_URL_PREFIX + 'accelerations/total', this.$getAccelerationTotals)
;
}
@@ -41,13 +48,24 @@ class MiningRoutes {
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 300).toUTCString());
if (req.query.timestamp) {
res.status(200).send(await PricesRepository.$getNearestHistoricalPrice(
parseInt(<string>req.query.timestamp ?? 0, 10)
));
} else {
res.status(200).send(await PricesRepository.$getHistoricalPrices());
if (['testnet', 'signet', 'liquidtestnet'].includes(config.MEMPOOL.NETWORK)) {
res.status(400).send('Prices are not available on testnets.');
return;
}
const timestamp = parseInt(req.query.timestamp as string, 10) || 0;
const currency = req.query.currency as string;
let response;
if (timestamp && currency) {
response = await PricesRepository.$getNearestHistoricalPrice(timestamp, currency);
} else if (timestamp) {
response = await PricesRepository.$getNearestHistoricalPrice(timestamp);
} else if (currency) {
response = await PricesRepository.$getHistoricalPrices(currency);
} else {
response = await PricesRepository.$getHistoricalPrices();
}
res.status(200).send(response);
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
@@ -88,6 +106,29 @@ class MiningRoutes {
}
}
private async $listPools(req: Request, res: Response): Promise<void> {
try {
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString());
const pools = await mining.$listPools();
if (!pools) {
res.status(500).end();
return;
}
res.header('X-total-count', pools.length.toString());
if (pools.length === 0) {
res.status(204).send();
} else {
res.json(pools);
}
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async $getPools(req: Request, res: Response) {
try {
const stats = await mining.$getPoolsStats(req.params.interval);
@@ -244,15 +285,15 @@ class MiningRoutes {
}
}
private async $getHistoricalBlockPrediction(req: Request, res: Response) {
private async $getHistoricalBlocksHealth(req: Request, res: Response) {
try {
const blockPredictions = await mining.$getBlockPredictionsHistory(req.params.interval);
const blockCount = await BlocksAuditsRepository.$getPredictionsCount();
const blocksHealth = await mining.$getBlocksHealthHistory(req.params.interval);
const blockCount = await BlocksAuditsRepository.$getBlocksHealthCount();
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.header('X-total-count', blockCount.toString());
res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString());
res.json(blockPredictions.map(prediction => [prediction.time, prediction.height, prediction.match_rate]));
res.json(blocksHealth.map(health => [health.time, health.height, health.match_rate]));
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
@@ -324,6 +365,67 @@ class MiningRoutes {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
private async $getAccelerationsByPool(req: Request, res: Response): Promise<void> {
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<void> {
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<void> {
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);
}
}
private async $getAccelerationTotals(req: Request, res: Response): Promise<void> {
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.$getAccelerationTotals(<string>req.query.pool, <string>req.query.interval));
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
}
export default new MiningRoutes();

View File

@@ -11,20 +11,30 @@ import DifficultyAdjustmentsRepository from '../../repositories/DifficultyAdjust
import config from '../../config';
import BlocksAuditsRepository from '../../repositories/BlocksAuditsRepository';
import PricesRepository from '../../repositories/PricesRepository';
import { bitcoinCoreApi } from '../bitcoin/bitcoin-api-factory';
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;
public lastWeeklyHashrateIndexingDate: number | null = null;
public reindexHashrateRequested = false;
public reindexDifficultyAdjustmentRequested = false;
/**
* Get historical block predictions match rate
* Get historical blocks health
*/
public async $getBlockPredictionsHistory(interval: string | null = null): Promise<any> {
return await BlocksAuditsRepository.$getBlockPredictionsHistory(
public async $getBlocksHealthHistory(interval: string | null = null): Promise<any> {
return await BlocksAuditsRepository.$getBlocksHealthHistory(
this.getTimeRange(interval),
Common.getSqlInterval(interval)
);
@@ -53,7 +63,7 @@ class Mining {
/**
* Get historical block fee rates percentiles
*/
public async $getHistoricalBlockFeeRates(interval: string | null = null): Promise<any> {
public async $getHistoricalBlockFeeRates(interval: string | null = null): Promise<any> {
return await BlocksRepository.$getHistoricalBlockFeeRates(
this.getTimeRange(interval),
Common.getSqlInterval(interval)
@@ -63,7 +73,7 @@ class Mining {
/**
* Get historical block sizes
*/
public async $getHistoricalBlockSizes(interval: string | null = null): Promise<any> {
public async $getHistoricalBlockSizes(interval: string | null = null): Promise<any> {
return await BlocksRepository.$getHistoricalBlockSizes(
this.getTimeRange(interval),
Common.getSqlInterval(interval)
@@ -73,7 +83,7 @@ class Mining {
/**
* Get historical block weights
*/
public async $getHistoricalBlockWeights(interval: string | null = null): Promise<any> {
public async $getHistoricalBlockWeights(interval: string | null = null): Promise<any> {
return await BlocksRepository.$getHistoricalBlockWeights(
this.getTimeRange(interval),
Common.getSqlInterval(interval)
@@ -103,6 +113,8 @@ class Mining {
emptyBlocks: emptyBlocksCount.length > 0 ? emptyBlocksCount[0]['count'] : 0,
slug: poolInfo.slug,
avgMatchRate: poolInfo.avgMatchRate !== null ? Math.round(100 * poolInfo.avgMatchRate) / 100 : null,
avgFeeDelta: poolInfo.avgFeeDelta,
poolUniqueId: poolInfo.poolUniqueId
};
poolsStats.push(poolStat);
});
@@ -130,7 +142,7 @@ class Mining {
public async $getPoolStat(slug: string): Promise<object> {
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);
@@ -197,7 +209,7 @@ class Mining {
try {
const oldestConsecutiveBlockTimestamp = 1000 * (await BlocksRepository.$getOldestConsecutiveBlock()).timestamp;
const genesisBlock: IEsploraApi.Block = await bitcoinCoreApi.$getBlock(await bitcoinClient.getBlockHash(0));
const genesisBlock: IEsploraApi.Block = await bitcoinApi.$getBlock(await bitcoinApi.$getBlockHash(0));
const genesisTimestamp = genesisBlock.timestamp * 1000;
const indexedTimestamp = await HashratesRepository.$getWeeklyHashrateTimestamps();
@@ -290,6 +302,14 @@ class Mining {
* Generate daily hashrate data
*/
public async $generateNetworkHashrateHistory(): Promise<void> {
// If a re-index was requested, truncate first
if (this.reindexHashrateRequested === true) {
logger.notice(`hashrates will now be re-indexed`);
await database.query(`TRUNCATE hashrates`);
this.lastHashrateIndexingDate = 0;
this.reindexHashrateRequested = false;
}
// We only run this once a day around midnight
const today = new Date().getUTCDate();
if (today === this.lastHashrateIndexingDate) {
@@ -300,7 +320,7 @@ class Mining {
const oldestConsecutiveBlockTimestamp = 1000 * (await BlocksRepository.$getOldestConsecutiveBlock()).timestamp;
try {
const genesisBlock: IEsploraApi.Block = await bitcoinCoreApi.$getBlock(await bitcoinClient.getBlockHash(0));
const genesisBlock: IEsploraApi.Block = await bitcoinApi.$getBlock(await bitcoinApi.$getBlockHash(0));
const genesisTimestamp = genesisBlock.timestamp * 1000;
const indexedTimestamp = (await HashratesRepository.$getRawNetworkDailyHashrate(null)).map(hashrate => hashrate.timestamp);
const lastMidnight = this.getDateMidnight(new Date());
@@ -395,15 +415,24 @@ class Mining {
* Index difficulty adjustments
*/
public async $indexDifficultyAdjustments(): Promise<void> {
// If a re-index was requested, truncate first
if (this.reindexDifficultyAdjustmentRequested === true) {
logger.notice(`difficulty_adjustments will now be re-indexed`);
await database.query(`TRUNCATE difficulty_adjustments`);
this.reindexDifficultyAdjustmentRequested = false;
}
const indexedHeightsArray = await DifficultyAdjustmentsRepository.$getAdjustmentsHeights();
const indexedHeights = {};
for (const height of indexedHeightsArray) {
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 bitcoinCoreApi.$getBlock(await bitcoinClient.getBlockHash(0));
const genesisBlock: IEsploraApi.Block = await bitcoinApi.$getBlock(await bitcoinApi.$getBlockHash(0));
let currentDifficulty = genesisBlock.difficulty;
let currentBits = genesisBlock.bits;
let totalIndexed = 0;
if (config.MEMPOOL.INDEXING_BLOCKS_AMOUNT === -1 && indexedHeights[0] !== true) {
@@ -415,44 +444,51 @@ class Mining {
});
}
const oldestConsecutiveBlock = await BlocksRepository.$getOldestConsecutiveBlock();
if (config.MEMPOOL.INDEXING_BLOCKS_AMOUNT !== -1) {
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) {
if (block.difficulty !== currentDifficulty) {
if (indexedHeights[block.height] === true) { // Already indexed
if (block.height >= oldestConsecutiveBlock.height) {
currentDifficulty = block.difficulty;
}
continue;
// 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) {
// 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;
}
}
// update the current difficulty
currentDifficulty = block.difficulty;
currentBits = block.bits;
}
totalBlockChecked++;
const elapsedSeconds = Math.max(1, Math.round((new Date().getTime() / 1000) - timer));
if (elapsedSeconds > 5) {
const progress = Math.round(totalBlockChecked / blocks.length * 100);
logger.info(`Indexing difficulty adjustment at block #${block.height} | Progress: ${progress}%`, logger.tags.mining);
logger.debug(`Indexing difficulty adjustment at block #${block.height} | Progress: ${progress}%`, logger.tags.mining);
timer = new Date().getTime() / 1000;
}
}
@@ -473,11 +509,11 @@ class Mining {
}
this.blocksPriceIndexingRunning = true;
let totalInserted = 0;
try {
const prices: any[] = await PricesRepository.$getPricesTimesAndId();
const blocksWithoutPrices: any[] = await BlocksRepository.$getBlocksWithoutPrice();
let totalInserted = 0;
const blocksPrices: BlockPrice[] = [];
for (const block of blocksWithoutPrices) {
@@ -522,7 +558,13 @@ class Mining {
}
} catch (e) {
this.blocksPriceIndexingRunning = false;
throw e;
logger.err(`Cannot index block prices. ${e}`);
}
if (totalInserted > 0) {
logger.info(`Indexing blocks prices completed. Indexed ${totalInserted}`, logger.tags.mining);
} else {
logger.debug(`Indexing blocks prices completed. Indexed 0.`, logger.tags.mining);
}
this.blocksPriceIndexingRunning = false;
@@ -558,11 +600,27 @@ class Mining {
currentBlockHeight -= 10000;
}
if (totalIndexed) {
logger.info(`Indexing missing coinstatsindex data completed`, logger.tags.mining);
if (totalIndexed > 0) {
logger.info(`Indexing missing coinstatsindex data completed. Indexed ${totalIndexed}`, logger.tags.mining);
} else {
logger.debug(`Indexing missing coinstatsindex data completed. Indexed 0.`, logger.tags.mining);
}
}
/**
* List existing mining pools
*/
public async $listPools(): Promise<{name: string, slug: string, unique_id: number}[] | null> {
const [rows] = await database.query(`
SELECT
name,
slug,
unique_id
FROM pools`
);
return rows as {name: string, slug: string, unique_id: number}[];
}
private getDateMidnight(date: Date): Date {
date.setUTCHours(0);
date.setUTCMinutes(0);
@@ -587,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();

View File

@@ -4,6 +4,7 @@ import config from '../config';
import PoolsRepository from '../repositories/PoolsRepository';
import { PoolTag } from '../mempool.interfaces';
import diskCache from './disk-cache';
import mining from './mining/mining';
class PoolsParser {
miningPools: any[] = [];
@@ -41,7 +42,7 @@ class PoolsParser {
public async migratePoolsJson(): Promise<void> {
// We also need to wipe the backend cache to make sure we don't serve blocks with
// the wrong mining pool (usually happen with unknown blocks)
diskCache.wipeCache();
diskCache.setIgnoreBlocksCache();
await this.$insertUnknownPool();
@@ -73,14 +74,12 @@ class PoolsParser {
if (JSON.stringify(pool.addresses) !== poolDB.addresses ||
JSON.stringify(pool.regexes) !== poolDB.regexes) {
// Pool addresses changed or coinbase tags changed
logger.notice(`Updating addresses and/or coinbase tags for ${pool.name} mining pool. If 'AUTOMATIC_BLOCK_REINDEXING' is enabled, we will re-index its blocks and 'unknown' blocks`);
logger.notice(`Updating addresses and/or coinbase tags for ${pool.name} mining pool.`);
await PoolsRepository.$updateMiningPoolTags(poolDB.id, pool.addresses, pool.regexes);
await this.$deleteBlocksForPool(poolDB);
}
}
}
logger.info('Mining pools-v2.json import completed');
}
/**
@@ -118,10 +117,6 @@ class PoolsParser {
* @param pool
*/
private async $deleteBlocksForPool(pool: PoolTag): Promise<void> {
if (config.MEMPOOL.AUTOMATIC_BLOCK_REINDEXING === false) {
return;
}
// Get oldest blocks mined by the pool and assume pools-v2.json updates only concern most recent years
// Ignore early days of Bitcoin as there were no mining pool yet
const [oldestPoolBlock]: any[] = await DB.query(`
@@ -132,7 +127,15 @@ class PoolsParser {
LIMIT 1`,
[pool.id]
);
const oldestBlockHeight = oldestPoolBlock.length ?? 0 > 0 ? oldestPoolBlock[0].height : 130635;
let firstKnownBlockPool = 130635; // https://mempool.space/block/0000000000000a067d94ff753eec72830f1205ad3a4c216a08a80c832e551a52
if (config.MEMPOOL.NETWORK === 'testnet') {
firstKnownBlockPool = 21106; // https://mempool.space/testnet/block/0000000070b701a5b6a1b965f6a38e0472e70b2bb31b973e4638dec400877581
} else if (config.MEMPOOL.NETWORK === 'signet') {
firstKnownBlockPool = 0;
}
const oldestBlockHeight = oldestPoolBlock.length ?? 0 > 0 ? oldestPoolBlock[0].height : firstKnownBlockPool;
const [unknownPool] = await DB.query(`SELECT id from pools where slug = "unknown"`);
this.uniqueLog(logger.notice, `Deleting blocks with unknown mining pool from height ${oldestBlockHeight} for re-indexing`);
await DB.query(`
@@ -146,16 +149,31 @@ class PoolsParser {
WHERE pool_id = ?`,
[pool.id]
);
// Re-index hashrates and difficulty adjustments later
mining.reindexHashrateRequested = true;
mining.reindexDifficultyAdjustmentRequested = true;
}
private async $deleteUnknownBlocks(): Promise<void> {
let firstKnownBlockPool = 130635; // https://mempool.space/block/0000000000000a067d94ff753eec72830f1205ad3a4c216a08a80c832e551a52
if (config.MEMPOOL.NETWORK === 'testnet') {
firstKnownBlockPool = 21106; // https://mempool.space/testnet/block/0000000070b701a5b6a1b965f6a38e0472e70b2bb31b973e4638dec400877581
} else if (config.MEMPOOL.NETWORK === 'signet') {
firstKnownBlockPool = 0;
}
const [unknownPool] = await DB.query(`SELECT id from pools where slug = "unknown"`);
this.uniqueLog(logger.notice, `Deleting blocks with unknown mining pool from height 130635 for re-indexing`);
this.uniqueLog(logger.notice, `Deleting blocks with unknown mining pool from height ${firstKnownBlockPool} for re-indexing`);
await DB.query(`
DELETE FROM blocks
WHERE pool_id = ? AND height >= 130635`,
WHERE pool_id = ? AND height >= ${firstKnownBlockPool}`,
[unknownPool[0].id]
);
// Re-index hashrates and difficulty adjustments later
mining.reindexHashrateRequested = true;
mining.reindexDifficultyAdjustmentRequested = true;
}
}

View File

@@ -0,0 +1,19 @@
import { Application, Request, Response } from 'express';
import config from '../../config';
import pricesUpdater from '../../tasks/price-updater';
class PricesRoutes {
public initRoutes(app: Application): void {
app.get(config.MEMPOOL.API_URL_PREFIX + 'prices', this.$getCurrentPrices.bind(this));
}
private $getCurrentPrices(req: Request, res: Response): void {
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 360_0000 / config.MEMPOOL.PRICE_UPDATES_PER_HOUR).toUTCString());
res.json(pricesUpdater.getLatestPrices());
}
}
export default new PricesRoutes();

View File

@@ -1,65 +1,543 @@
import { TransactionExtended } from "../mempool.interfaces";
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";
export interface RbfTransaction extends TransactionStripped {
rbf?: boolean;
mined?: boolean;
fullRbf?: boolean;
}
export interface RbfTree {
tx: RbfTransaction;
time: number;
interval?: number;
mined?: boolean;
fullRbf: boolean;
replaces: RbfTree[];
}
export interface ReplacementInfo {
mined: boolean;
fullRbf: boolean;
txid: string;
oldFee: number;
oldVsize: number;
newFee: number;
newVsize: number;
}
enum CacheOp {
Remove = 0,
Add = 1,
Change = 2,
}
interface CacheEvent {
op: CacheOp;
type: 'tx' | 'tree' | 'exp';
txid: string,
value?: any,
}
class RbfCache {
private replacedBy: { [txid: string]: string; } = {};
private replaces: { [txid: string]: string[] } = {};
private txs: { [txid: string]: TransactionExtended } = {};
private expiring: { [txid: string]: Date } = {};
private replacedBy: Map<string, string> = new Map();
private replaces: Map<string, string[]> = new Map();
private rbfTrees: Map<string, RbfTree> = new Map(); // sequences of consecutive replacements
private dirtyTrees: Set<string> = new Set();
private treeMap: Map<string, string> = new Map(); // map of txids to sequence ids
private txs: Map<string, MempoolTransactionExtended> = new Map();
private expiring: Map<string, number> = new Map();
private cacheQueue: CacheEvent[] = [];
private evictionCount = 0;
private staleCount = 0;
constructor() {
setInterval(this.cleanup.bind(this), 1000 * 60 * 60);
setInterval(this.cleanup.bind(this), 1000 * 60 * 10);
}
public add(replacedTx: TransactionExtended, newTxId: string): void {
this.replacedBy[replacedTx.txid] = newTxId;
this.txs[replacedTx.txid] = replacedTx;
if (!this.replaces[newTxId]) {
this.replaces[newTxId] = [];
private addTx(txid: string, tx: MempoolTransactionExtended): void {
this.txs.set(txid, tx);
this.cacheQueue.push({ op: CacheOp.Add, type: 'tx', txid });
}
private addTree(txid: string, tree: RbfTree): void {
this.rbfTrees.set(txid, tree);
this.dirtyTrees.add(txid);
this.cacheQueue.push({ op: CacheOp.Add, type: 'tree', txid });
}
private addExpiration(txid: string, expiry: number): void {
this.expiring.set(txid, expiry);
this.cacheQueue.push({ op: CacheOp.Add, type: 'exp', txid, value: expiry });
}
private removeTx(txid: string): void {
this.txs.delete(txid);
this.cacheQueue.push({ op: CacheOp.Remove, type: 'tx', txid });
}
private removeTree(txid: string): void {
this.rbfTrees.delete(txid);
this.cacheQueue.push({ op: CacheOp.Remove, type: 'tree', txid });
}
private removeExpiration(txid: string): void {
this.expiring.delete(txid);
this.cacheQueue.push({ op: CacheOp.Remove, type: 'exp', txid });
}
public add(replaced: MempoolTransactionExtended[], newTxExtended: MempoolTransactionExtended): void {
if (!newTxExtended || !replaced?.length || this.txs.has(newTxExtended.txid)) {
return;
}
this.replaces[newTxId].push(replacedTx.txid);
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);
this.addTx(newTx.txid, newTxExtended);
// maintain rbf trees
let txFullRbf = false;
let treeFullRbf = false;
const replacedTrees: RbfTree[] = [];
for (const replacedTxExtended of replaced) {
const replacedTx = Common.stripTransaction(replacedTxExtended) as RbfTransaction;
replacedTx.rbf = replacedTxExtended.vin.some((v) => v.sequence < 0xfffffffe);
if (!replacedTx.rbf) {
txFullRbf = true;
}
this.replacedBy.set(replacedTx.txid, newTx.txid);
if (this.treeMap.has(replacedTx.txid)) {
const treeId = this.treeMap.get(replacedTx.txid);
if (treeId) {
const tree = this.rbfTrees.get(treeId);
this.removeTree(treeId);
if (tree) {
tree.interval = newTime - tree?.time;
replacedTrees.push(tree);
treeFullRbf = treeFullRbf || tree.fullRbf || !tree.tx.rbf;
}
}
} else {
const replacedTime = replacedTxExtended.firstSeen || (Date.now() / 1000);
replacedTrees.push({
tx: replacedTx,
time: replacedTime,
interval: newTime - replacedTime,
fullRbf: !replacedTx.rbf,
replaces: [],
});
treeFullRbf = treeFullRbf || !replacedTx.rbf;
this.addTx(replacedTx.txid, replacedTxExtended);
}
}
newTx.fullRbf = txFullRbf;
const treeId = replacedTrees[0].tx.txid;
const newTree = {
tx: newTx,
time: newTime,
fullRbf: treeFullRbf,
replaces: replacedTrees
};
this.addTree(treeId, newTree);
this.updateTreeMap(treeId, newTree);
this.replaces.set(newTx.txid, replacedTrees.map(tree => tree.tx.txid));
}
public has(txId: string): boolean {
return this.txs.has(txId);
}
public anyInSameTree(txId: string, predicate: (tx: RbfTransaction) => boolean): boolean {
const tree = this.getRbfTree(txId);
if (!tree) {
return false;
}
const txs = this.getTransactionsInTree(tree);
for (const tx of txs) {
if (predicate(tx)) {
return true;
}
}
return false;
}
public getReplacedBy(txId: string): string | undefined {
return this.replacedBy[txId];
return this.replacedBy.get(txId);
}
public getReplaces(txId: string): string[] | undefined {
return this.replaces[txId];
return this.replaces.get(txId);
}
public getTx(txId: string): TransactionExtended | undefined {
return this.txs[txId];
public getTx(txId: string): MempoolTransactionExtended | undefined {
return this.txs.get(txId);
}
public getRbfTree(txId: string): RbfTree | void {
return this.rbfTrees.get(this.treeMap.get(txId) || '');
}
// get a paginated list of RbfTrees
// ordered by most recent replacement time
public getRbfTrees(onlyFullRbf: boolean, after?: string): RbfTree[] {
const limit = 25;
const trees: RbfTree[] = [];
const used = new Set<string>();
const replacements: string[][] = Array.from(this.replacedBy).reverse();
const afterTree = after ? this.treeMap.get(after) : null;
let ready = !afterTree;
for (let i = 0; i < replacements.length && trees.length <= limit - 1; i++) {
const txid = replacements[i][1];
const treeId = this.treeMap.get(txid) || '';
if (treeId === afterTree) {
ready = true;
} else if (ready) {
if (!used.has(treeId)) {
const tree = this.rbfTrees.get(treeId);
used.add(treeId);
if (tree && (!onlyFullRbf || tree.fullRbf)) {
trees.push(tree);
}
}
}
}
return trees;
}
// get map of rbf trees that have been updated since the last call
public getRbfChanges(): { trees: {[id: string]: RbfTree }, map: { [txid: string]: string }} {
const changes: { trees: {[id: string]: RbfTree }, map: { [txid: string]: string }} = {
trees: {},
map: {},
};
this.dirtyTrees.forEach(id => {
const tree = this.rbfTrees.get(id);
if (tree) {
changes.trees[id] = tree;
this.getTransactionsInTree(tree).forEach(tx => {
changes.map[tx.txid] = id;
});
}
});
this.dirtyTrees = new Set();
return changes;
}
public mined(txid): void {
if (!this.txs.has(txid)) {
return;
}
const treeId = this.treeMap.get(txid);
if (treeId && this.rbfTrees.has(treeId)) {
const tree = this.rbfTrees.get(treeId);
if (tree) {
this.setTreeMined(tree, txid);
tree.mined = true;
this.dirtyTrees.add(treeId);
this.cacheQueue.push({ op: CacheOp.Change, type: 'tree', txid: treeId });
}
}
this.evict(txid);
}
// flag a transaction as removed from the mempool
public evict(txid): void {
this.expiring[txid] = new Date(Date.now() + 1000 * 86400); // 24 hours
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);
}
}
// is the transaction involved in a full rbf replacement?
public isFullRbf(txid: string): boolean {
const treeId = this.treeMap.get(txid);
if (!treeId) {
return false;
}
const tree = this.rbfTrees.get(treeId);
if (!tree) {
return false;
}
return tree?.fullRbf;
}
private cleanup(): void {
const currentDate = new Date();
for (const txid in this.expiring) {
if (this.expiring[txid] < currentDate) {
delete this.expiring[txid];
const now = Date.now();
for (const txid of this.expiring.keys()) {
if ((this.expiring.get(txid) || 0) < now) {
this.removeExpiration(txid);
this.remove(txid);
}
}
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 while a newer version remains in the mempool
if (this.replaces[txid] && !this.replacedBy[txid]) {
const replaces = this.replaces[txid];
delete this.replaces[txid];
for (const tx of replaces) {
// 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
delete this.replacedBy[tx];
delete this.txs[tx];
this.replacedBy.delete(tx);
// if this is the id of a tree, remove that too
if (this.treeMap.get(tx) === tx) {
this.removeTree(tx);
}
this.remove(tx);
}
}
}
private updateTreeMap(newId: string, tree: RbfTree): void {
this.treeMap.set(tree.tx.txid, newId);
tree.replaces.forEach(subtree => {
this.updateTreeMap(newId, subtree);
});
}
private getTransactionsInTree(tree: RbfTree, txs: RbfTransaction[] = []): RbfTransaction[] {
txs.push(tree.tx);
tree.replaces.forEach(subtree => {
this.getTransactionsInTree(subtree, txs);
});
return txs;
}
private setTreeMined(tree: RbfTree, txid: string): void {
if (tree.tx.txid === txid) {
tree.tx.mined = true;
} else {
tree.replaces.forEach(subtree => {
this.setTreeMined(subtree, txid);
});
}
}
public async updateCache(): Promise<void> {
if (!config.REDIS.ENABLED) {
return;
}
// Update the Redis cache by replaying queued events
for (const e of this.cacheQueue) {
if (e.op === CacheOp.Add || e.op === CacheOp.Change) {
let value = e.value;
switch(e.type) {
case 'tx': {
value = this.txs.get(e.txid);
} break;
case 'tree': {
const tree = this.rbfTrees.get(e.txid);
value = tree ? this.exportTree(tree) : null;
} break;
}
if (value != null) {
await redisCache.$setRbfEntry(e.type, e.txid, value);
}
} else if (e.op === CacheOp.Remove) {
await redisCache.$removeRbfEntry(e.type, e.txid);
}
}
this.cacheQueue = [];
}
public dump(): any {
const trees = Array.from(this.rbfTrees.values()).map((tree: RbfTree) => { return this.exportTree(tree); });
return {
txs: Array.from(this.txs.entries()),
trees,
expiring: Array.from(this.expiring.entries()),
};
}
public async load({ txs, trees, expiring, mempool }): Promise<void> {
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);
}
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) {
if (!deflated) {
deflated = {
root: tree.tx.txid,
};
}
deflated[tree.tx.txid] = {
tx: tree.tx.txid,
txMined: tree.tx.mined,
time: tree.time,
interval: tree.interval,
mined: tree.mined,
fullRbf: tree.fullRbf,
replaces: tree.replaces.map(child => child.tx.txid),
};
tree.replaces.forEach(child => {
this.exportTree(child, deflated);
});
return deflated;
}
async importTree(mempool, root, txid, deflated, txs: Map<string, MempoolTransactionExtended>, mined: boolean = false): Promise<RbfTree | void> {
const treeInfo = deflated[txid];
const replaces: RbfTree[] = [];
// 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(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;
}
}
}
this.replaces.set(txid, replaces.map(t => t.tx.txid));
const tx = txs.get(txid);
if (!tx) {
return;
}
const strippedTx = Common.stripTransaction(tx) as RbfTransaction;
strippedTx.rbf = tx.vin.some((v) => v.sequence < 0xfffffffe);
strippedTx.mined = treeInfo.txMined;
const tree = {
tx: strippedTx,
time: treeInfo.time,
interval: treeInfo.interval,
mined: mined,
fullRbf: treeInfo.fullRbf,
replaces,
};
this.treeMap.set(txid, root);
if (root === txid) {
this.addTree(root, tree);
}
return tree;
}
private async checkTrees(): Promise<void> {
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 => {
let oldFee = 0;
let oldVsize = 0;
for (const replaced of rbfTree.replaces) {
oldFee += replaced.tx.fee;
oldVsize += replaced.tx.vsize;
}
return {
txid: rbfTree.tx.txid,
mined: !!rbfTree.tx.mined,
fullRbf: !!rbfTree.tx.fullRbf,
oldFee,
oldVsize,
newFee: rbfTree.tx.fee,
newVsize: rbfTree.tx.vsize,
};
});
}
}
export default new RbfCache();

View File

@@ -0,0 +1,416 @@
import { createClient } from 'redis';
import memPool from './mempool';
import blocks from './blocks';
import logger from '../logger';
import config from '../config';
import { BlockExtended, BlockSummary, MempoolTransactionExtended } from '../mempool.interfaces';
import rbfCache from './rbf-cache';
import transactionUtils from './transaction-utils';
enum NetworkDB {
mainnet = 0,
testnet,
signet,
liquid,
liquidtestnet,
}
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) {
this.redisConfig = {
socket: {
path: config.REDIS.UNIX_SOCKET_PATH
},
database: NetworkDB[config.MEMPOOL.NETWORK],
};
this.$ensureConnected();
setInterval(() => { this.$ensureConnected(); }, 10000);
}
}
private async $ensureConnected(): Promise<boolean> {
if (!this.connected && config.REDIS.ENABLED) {
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;
}
}
}
private async $onConnected(): Promise<void> {
await this.$flushTransactions();
await this.$removeTransactions([]);
await this.$flushRbfQueues();
}
async $updateBlocks(blocks: BlockExtended[]): Promise<void> {
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.client.set('blocks', JSON.stringify(blocks));
logger.debug(`Saved latest blocks to Redis cache`);
} catch (e) {
logger.warn(`Failed to update blocks in Redis cache: ${e instanceof Error ? e.message : e}`);
}
}
async $updateBlockSummaries(summaries: BlockSummary[]): Promise<void> {
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.client.set('block-summaries', JSON.stringify(summaries));
logger.debug(`Saved latest block summaries to Redis cache`);
} catch (e) {
logger.warn(`Failed to update block summaries in Redis cache: ${e instanceof Error ? e.message : e}`);
}
}
async $addTransaction(tx: MempoolTransactionExtended): Promise<void> {
if (!config.REDIS.ENABLED) {
return;
}
this.cacheQueue.push(tx);
if (this.cacheQueue.length >= this.txFlushLimit) {
if (!this.pauseFlush) {
await this.$flushTransactions();
}
}
}
async $flushTransactions(): Promise<void> {
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;
}
this.pauseFlush = false;
const toAdd = this.cacheQueue.slice(0, this.txFlushLimit);
try {
const msetData = toAdd.map(tx => {
const minified: any = { ...tx };
delete minified.hex;
for (const vin of minified.vin) {
delete vin.inner_redeemscript_asm;
delete vin.inner_witnessscript_asm;
delete vin.scriptsig_asm;
}
for (const vout of minified.vout) {
delete vout.scriptpubkey_asm;
}
return [`mempool:tx:${tx.txid}`, JSON.stringify(minified)];
});
await this.client.MSET(msetData);
// 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 ${toAdd.length} transactions to Redis cache: ${e instanceof Error ? e.message : e}`);
this.pauseFlush = true;
}
}
async $removeTransactions(transactions: string[]): Promise<void> {
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);
}
}
// 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<void> {
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.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}`);
}
}
async $removeRbfEntry(type: string, txid: string): Promise<void> {
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.client.unlink(`rbf:${type}:${txid}`);
} catch (e) {
logger.warn(`Failed to remove RBF ${type} from Redis cache: ${e instanceof Error ? e.message : e}`);
}
}
private async $flushRbfQueues(): Promise<void> {
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<BlockExtended[]> {
if (!config.REDIS.ENABLED) {
return [];
}
if (!this.connected) {
logger.warn(`Failed to retrieve blocks from Redis cache: Redis is not connected`);
return [];
}
try {
const json = await this.client.get('blocks');
return JSON.parse(json);
} catch (e) {
logger.warn(`Failed to retrieve blocks from Redis cache: ${e instanceof Error ? e.message : e}`);
return [];
}
}
async $getBlockSummaries(): Promise<BlockSummary[]> {
if (!config.REDIS.ENABLED) {
return [];
}
if (!this.connected) {
logger.warn(`Failed to retrieve blocks from Redis cache: Redis is not connected`);
return [];
}
try {
const json = await this.client.get('block-summaries');
return JSON.parse(json);
} catch (e) {
logger.warn(`Failed to retrieve blocks from Redis cache: ${e instanceof Error ? e.message : e}`);
return [];
}
}
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 {
const mempoolList = await this.scanKeys<MempoolTransactionExtended>('mempool:tx:*');
for (const tx of mempoolList) {
mempool[tx.key] = tx.value;
}
logger.info(`Loaded mempool from Redis cache in ${Date.now() - start} ms`);
return mempool || {};
} catch (e) {
logger.warn(`Failed to retrieve mempool from Redis cache: ${e instanceof Error ? e.message : e}`);
}
return {};
}
async $getRbfEntries(type: string): Promise<any[]> {
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 {
const rbfEntries = await this.scanKeys<MempoolTransactionExtended[]>(`rbf:${type}:*`);
return rbfEntries;
} catch (e) {
logger.warn(`Failed to retrieve Rbf ${type}s from Redis cache: ${e instanceof Error ? e.message : e}`);
return [];
}
}
async $loadCache(): Promise<void> {
if (!config.REDIS.ENABLED) {
return;
}
logger.info('Restoring mempool and blocks data from Redis cache');
// Load block data
const loadedBlocks = await this.$getBlocks();
const loadedBlockSummaries = await this.$getBlockSummaries();
// Load mempool
const loadedMempool = await this.$getMempool();
this.inflateLoadedTxs(loadedMempool);
// Load rbf data
const rbfTxs = await this.$getRbfEntries('tx');
const rbfTrees = await this.$getRbfEntries('tree');
const rbfExpirations = await this.$getRbfEntries('exp');
// Set loaded data
blocks.setBlocks(loadedBlocks || []);
blocks.setBlockSummaries(loadedBlockSummaries || []);
await memPool.$setMempool(loadedMempool);
await rbfCache.load({
txs: rbfTxs,
trees: rbfTrees.map(loadedTree => { loadedTree.value.key = loadedTree.key; return loadedTree.value; }),
expiring: rbfExpirations,
mempool: memPool.getMempool(),
});
}
private inflateLoadedTxs(mempool: { [txid: string]: MempoolTransactionExtended }): void {
for (const tx of Object.values(mempool)) {
for (const vin of tx.vin) {
if (vin.scriptsig) {
vin.scriptsig_asm = transactionUtils.convertScriptSigAsm(vin.scriptsig);
transactionUtils.addInnerScriptsToVin(vin);
}
}
for (const vout of tx.vout) {
if (vout.scriptpubkey) {
vout.scriptpubkey_asm = transactionUtils.convertScriptSigAsm(vout.scriptpubkey);
}
}
}
}
private async scanKeys<T>(pattern): Promise<{ key: string, value: T }[]> {
logger.info(`loading Redis entries for ${pattern}`);
let keys: string[] = [];
const result: { key: string, value: T }[] = [];
const patternLength = pattern.length - 1;
let count = 0;
const processValues = async (keys): Promise<void> => {
const values = await this.client.MGET(keys);
for (let i = 0; i < values.length; i++) {
if (values[i]) {
result.push({ key: keys[i].slice(patternLength), value: JSON.parse(values[i]) });
count++;
}
}
logger.info(`loaded ${count} entries from Redis cache`);
};
for await (const key of this.client.scanIterator({
MATCH: pattern,
COUNT: 100
})) {
keys.push(key);
if (keys.length >= 10000) {
await processValues(keys);
keys = [];
}
}
if (keys.length) {
await processValues(keys);
}
return result;
}
}
export default new RedisCache();

View File

@@ -0,0 +1,76 @@
import config from '../../config';
import logger from '../../logger';
import { BlockExtended, PoolTag } from '../../mempool.interfaces';
import axios from 'axios';
export interface Acceleration {
txid: string,
feeDelta: number,
pools: number[],
};
export interface AccelerationHistory {
txid: string,
status: string,
feePaid: number,
added: number,
lastUpdated: number,
baseFee: number,
vsizeFee: number,
effectiveFee: number,
effectiveVsize: number,
feeDelta: number,
blockHash: string,
blockHeight: number,
pools: {
pool_unique_id: number,
username: string,
}[],
};
class AccelerationApi {
public async $fetchAccelerations(): Promise<Acceleration[] | null> {
if (config.MEMPOOL_SERVICES.ACCELERATIONS) {
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 [];
}
}
public async $fetchAccelerationHistory(page?: number, status?: string): Promise<AccelerationHistory[] | null> {
if (config.MEMPOOL_SERVICES.ACCELERATIONS) {
try {
const response = await axios.get(`${config.MEMPOOL_SERVICES.API}/accelerator/accelerations/history`, {
responseType: 'json',
timeout: 10000,
params: {
page,
status,
}
});
return response.data as AccelerationHistory[];
} catch (e) {
logger.warn('Failed to fetch acceleration history from the mempool services backend: ' + (e instanceof Error ? e.message : e));
return null;
}
} else {
return [];
}
}
public isAcceleratedBlock(block: BlockExtended, accelerations: Acceleration[]): boolean {
let anyAccelerated = false;
for (let i = 0; i < accelerations.length && !anyAccelerated; i++) {
anyAccelerated = anyAccelerated || accelerations[i].pools?.includes(block.extras.pool.id);
}
return anyAccelerated;
}
}
export default new AccelerationApi();

View File

@@ -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,
@@ -211,7 +216,7 @@ class StatisticsApi {
CAST(avg(vsize_1800) as DOUBLE) as vsize_1800,
CAST(avg(vsize_2000) as DOUBLE) as vsize_2000 \
FROM statistics \
WHERE added BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW() \
${interval === 'all' ? '' : `WHERE added BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`} \
GROUP BY UNIX_TIMESTAMP(added) DIV ${div} \
ORDER BY statistics.added DESC;`;
}
@@ -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,
@@ -259,7 +266,7 @@ class StatisticsApi {
vsize_1800,
vsize_2000 \
FROM statistics \
WHERE added BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW() \
${interval === 'all' ? '' : `WHERE added BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`} \
GROUP BY UNIX_TIMESTAMP(added) DIV ${div} \
ORDER BY statistics.added DESC;`;
}
@@ -278,7 +285,7 @@ class StatisticsApi {
public async $list2H(): Promise<OptimizedStatistic[]> {
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<OptimizedStatistic[]> {
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) {
@@ -386,13 +393,26 @@ class StatisticsApi {
}
}
public async $listAll(): Promise<OptimizedStatistic[]> {
try {
const query = this.getQueryForDays(43200, 'all'); // 12h interval
const [rows] = await DB.query({ sql: query, timeout: this.queryTimeout });
return this.mapStatisticToOptimizedStatistic(rows as Statistic[]);
} catch (e) {
logger.err('$listAll() error' + (e instanceof Error ? e.message : e));
return [];
}
}
private mapStatisticToOptimizedStatistic(statistic: Statistic[]): OptimizedStatistic[] {
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,

View File

@@ -15,10 +15,11 @@ class StatisticsRoutes {
.get(config.MEMPOOL.API_URL_PREFIX + 'statistics/2y', this.$getStatisticsByTime.bind(this, '2y'))
.get(config.MEMPOOL.API_URL_PREFIX + 'statistics/3y', this.$getStatisticsByTime.bind(this, '3y'))
.get(config.MEMPOOL.API_URL_PREFIX + 'statistics/4y', this.$getStatisticsByTime.bind(this, '4y'))
.get(config.MEMPOOL.API_URL_PREFIX + 'statistics/all', this.$getStatisticsByTime.bind(this, 'all'))
;
}
private async $getStatisticsByTime(time: '2h' | '24h' | '1w' | '1m' | '3m' | '6m' | '1y' | '2y' | '3y' | '4y', req: Request, res: Response) {
private async $getStatisticsByTime(time: '2h' | '24h' | '1w' | '1m' | '3m' | '6m' | '1y' | '2y' | '3y' | '4y' | 'all', req: Request, res: Response) {
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 300).toUTCString());
@@ -26,10 +27,6 @@ class StatisticsRoutes {
try {
let result;
switch (time as string) {
case '2h':
result = await statisticsApi.$list2H();
res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString());
break;
case '24h':
result = await statisticsApi.$list24H();
res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString());
@@ -58,8 +55,13 @@ class StatisticsRoutes {
case '4y':
result = await statisticsApi.$list4Y();
break;
case 'all':
result = await statisticsApi.$listAll();
break;
default:
result = await statisticsApi.$list2H();
res.setHeader('Expires', new Date(Date.now() + 1000 * 30).toUTCString());
break;
}
res.json(result);
} catch (e) {

View File

@@ -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<void> {
public async runStatistics(skipIfRecent = false): Promise<void> {
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,

View File

@@ -1,7 +1,11 @@
import { TransactionExtended, TransactionMinerInfo } from '../mempool.interfaces';
import { TransactionExtended, MempoolTransactionExtended, TransactionMinerInfo } from '../mempool.interfaces';
import { IEsploraApi } from './bitcoin/esplora-api.interface';
import { Common } from './common';
import bitcoinApi, { bitcoinCoreApi } from './bitcoin/bitcoin-api-factory';
import * as bitcoinjs from 'bitcoinjs-lib';
import logger from '../logger';
import config from '../config';
import pLimit from '../utils/p-limit';
class TransactionUtils {
constructor() { }
@@ -21,37 +25,113 @@ class TransactionUtils {
};
}
// Wrapper for $getTransactionExtended with an automatic retry direct to Core if the first API request fails.
// Propagates any error from the retry request.
public async $getTransactionExtendedRetry(txid: string, addPrevouts = false, lazyPrevouts = false, forceCore = false, addMempoolData = false): Promise<TransactionExtended> {
try {
const result = await this.$getTransactionExtended(txid, addPrevouts, lazyPrevouts, forceCore, addMempoolData);
if (result) {
return result;
} else {
logger.err(`Cannot fetch tx ${txid}. Reason: backend returned null data`);
}
} catch (e) {
logger.err(`Cannot fetch tx ${txid}. Reason: ` + (e instanceof Error ? e.message : e));
}
// retry direct from Core if first request failed
return this.$getTransactionExtended(txid, addPrevouts, lazyPrevouts, true, addMempoolData);
}
/**
* @param txId
* @param addPrevouts
* @param lazyPrevouts
* @param txId
* @param addPrevouts
* @param lazyPrevouts
* @param forceCore - See https://github.com/mempool/mempool/issues/2904
*/
public async $getTransactionExtended(txId: string, addPrevouts = false, lazyPrevouts = false, forceCore = false): Promise<TransactionExtended> {
public async $getTransactionExtended(txId: string, addPrevouts = false, lazyPrevouts = false, forceCore = false, addMempoolData = false): Promise<TransactionExtended> {
let transaction: IEsploraApi.Transaction;
if (forceCore === true) {
transaction = await bitcoinCoreApi.$getRawTransaction(txId, true);
transaction = await bitcoinCoreApi.$getRawTransaction(txId, false, addPrevouts, lazyPrevouts);
} else {
transaction = await bitcoinApi.$getRawTransaction(txId, false, addPrevouts, lazyPrevouts);
}
return this.extendTransaction(transaction);
if (Common.isLiquid()) {
if (!isFinite(Number(transaction.fee))) {
transaction.fee = Object.values(transaction.fee || {}).reduce((total, output) => total + output, 0);
}
}
if (addMempoolData || !transaction?.status?.confirmed) {
return this.extendMempoolTransaction(transaction);
} else {
return this.extendTransaction(transaction);
}
}
private extendTransaction(transaction: IEsploraApi.Transaction): TransactionExtended {
public async $getMempoolTransactionExtended(txId: string, addPrevouts = false, lazyPrevouts = false, forceCore = false): Promise<MempoolTransactionExtended> {
return (await this.$getTransactionExtended(txId, addPrevouts, lazyPrevouts, forceCore, true)) as MempoolTransactionExtended;
}
public async $getMempoolTransactionsExtended(txids: string[], addPrevouts = false, lazyPrevouts = false, forceCore = false): Promise<MempoolTransactionExtended[]> {
if (forceCore || config.MEMPOOL.BACKEND !== 'esplora') {
const limiter = pLimit(8); // Run 8 requests at a time
const results = await Promise.allSettled(txids.map(
txid => limiter(() => this.$getMempoolTransactionExtended(txid, addPrevouts, lazyPrevouts, forceCore))
));
return results.filter(reply => reply.status === 'fulfilled')
.map(r => (r as PromiseFulfilledResult<MempoolTransactionExtended>).value);
} else {
const transactions = await bitcoinApi.$getMempoolTransactions(txids);
return transactions.map(transaction => {
if (Common.isLiquid()) {
if (!isFinite(Number(transaction.fee))) {
transaction.fee = Object.values(transaction.fee || {}).reduce((total, output) => total + output, 0);
}
}
return this.extendMempoolTransaction(transaction);
});
}
}
public extendTransaction(transaction: IEsploraApi.Transaction): TransactionExtended {
// @ts-ignore
if (transaction.vsize) {
// @ts-ignore
return transaction;
}
const feePerVbytes = Math.max(Common.isLiquid() ? 0.1 : 1,
(transaction.fee || 0) / (transaction.weight / 4));
const feePerVbytes = (transaction.fee || 0) / (transaction.weight / 4);
const transactionExtended: TransactionExtended = Object.assign({
vsize: Math.round(transaction.weight / 4),
feePerVsize: feePerVbytes,
effectiveFeePerVsize: feePerVbytes,
}, transaction);
if (!transaction.status.confirmed) {
transactionExtended.firstSeen = Math.round((new Date().getTime() / 1000));
if (!transaction?.status?.confirmed && !transactionExtended.firstSeen) {
transactionExtended.firstSeen = Math.round((Date.now() / 1000));
}
return transactionExtended;
}
public extendMempoolTransaction(transaction: IEsploraApi.Transaction): MempoolTransactionExtended {
const vsize = Math.ceil(transaction.weight / 4);
const fractionalVsize = (transaction.weight / 4);
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;
const adjustedFeePerVsize = (transaction.fee || 0) / adjustedVsize;
const transactionExtended: MempoolTransactionExtended = Object.assign(transaction, {
order: this.txidToOrdering(transaction.txid),
vsize: Math.round(transaction.weight / 4),
adjustedVsize,
sigops,
feePerVsize: feePerVbytes,
adjustedFeePerVsize: adjustedFeePerVsize,
effectiveFeePerVsize: adjustedFeePerVsize,
});
if (!transactionExtended?.status?.confirmed && !transactionExtended.firstSeen) {
transactionExtended.firstSeen = Math.round((Date.now() / 1000));
}
return transactionExtended;
}
@@ -63,6 +143,201 @@ class TransactionUtils {
}
return str;
}
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);
// count OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY
if (isRawScript) {
// in scriptPubKey or scriptSig, always worth 20
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_(?:PUSHNUM_)?(\d+))? OP_CHECKMULTISIG/g);
for (const match of matches) {
const n = parseInt(match[1]);
if (Number.isInteger(n)) {
sigops += n;
} else {
sigops += 20;
}
}
}
return witness ? sigops : (sigops * 4);
}
public countSigops(transaction: IEsploraApi.Transaction): number {
let sigops = 0;
for (const input of transaction.vin) {
if (input.scriptsig_asm) {
sigops += this.countScriptSigops(input.scriptsig_asm, true);
}
if (input.prevout) {
switch (true) {
case input.prevout.scriptpubkey_type === 'p2sh' && input.witness?.length === 2 && input.scriptsig && input.scriptsig.startsWith('160014'):
case input.prevout.scriptpubkey_type === 'v0_p2wpkh':
sigops += 1;
break;
case input.prevout?.scriptpubkey_type === 'p2sh' && input.witness?.length && input.scriptsig && input.scriptsig.startsWith('220020'):
case input.prevout.scriptpubkey_type === 'v0_p2wsh':
if (input.witness?.length) {
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;
}
}
}
for (const output of transaction.vout) {
if (output.scriptpubkey_asm) {
sigops += this.countScriptSigops(output.scriptpubkey_asm, true);
}
}
return sigops;
}
// returns the most significant 4 bytes of the txid as an integer
public txidToOrdering(txid: string): number {
return parseInt(
txid.substr(62, 2) +
txid.substr(60, 2) +
txid.substr(58, 2) +
txid.substr(56, 2),
16
);
}
public addInnerScriptsToVin(vin: IEsploraApi.Vin): void {
if (!vin.prevout) {
return;
}
if (vin.prevout.scriptpubkey_type === 'p2sh') {
const redeemScript = vin.scriptsig_asm.split(' ').reverse()[0];
vin.inner_redeemscript_asm = this.convertScriptSigAsm(redeemScript);
if (vin.witness && vin.witness.length > 2) {
const witnessScript = vin.witness[vin.witness.length - 1];
vin.inner_witnessscript_asm = this.convertScriptSigAsm(witnessScript);
}
}
if (vin.prevout.scriptpubkey_type === 'v0_p2wsh' && vin.witness) {
const witnessScript = vin.witness[vin.witness.length - 1];
vin.inner_witnessscript_asm = this.convertScriptSigAsm(witnessScript);
}
if (vin.prevout.scriptpubkey_type === 'v1_p2tr' && vin.witness) {
const witnessScript = this.witnessToP2TRScript(vin.witness);
if (witnessScript !== null) {
vin.inner_witnessscript_asm = this.convertScriptSigAsm(witnessScript);
}
}
}
public convertScriptSigAsm(hex: string): string {
const buf = Buffer.from(hex, 'hex');
const b: string[] = [];
let i = 0;
while (i < buf.length) {
const op = buf[i];
if (op >= 0x01 && op <= 0x4e) {
i++;
let push: number;
if (op === 0x4c) {
push = buf.readUInt8(i);
b.push('OP_PUSHDATA1');
i += 1;
} else if (op === 0x4d) {
push = buf.readUInt16LE(i);
b.push('OP_PUSHDATA2');
i += 2;
} else if (op === 0x4e) {
push = buf.readUInt32LE(i);
b.push('OP_PUSHDATA4');
i += 4;
} else {
push = op;
b.push('OP_PUSHBYTES_' + push);
}
const data = buf.slice(i, i + push);
if (data.length !== push) {
break;
}
b.push(data.toString('hex'));
i += data.length;
} else {
if (op === 0x00) {
b.push('OP_0');
} else if (op === 0x4f) {
b.push('OP_PUSHNUM_NEG1');
} else if (op === 0xb1) {
b.push('OP_CLTV');
} else if (op === 0xb2) {
b.push('OP_CSV');
} else if (op === 0xba) {
b.push('OP_CHECKSIGADD');
} else {
const opcode = bitcoinjs.script.toASM([ op ]);
if (opcode && op < 0xfd) {
if (/^OP_(\d+)$/.test(opcode)) {
b.push(opcode.replace(/^OP_(\d+)$/, 'OP_PUSHNUM_$1'));
} else {
b.push(opcode);
}
} else {
b.push('OP_RETURN_' + op);
}
}
i += 1;
}
}
return b.join(' ');
}
/**
* This function must only be called when we know the witness we are parsing
* is a taproot witness.
* @param witness An array of hex strings that represents the witness stack of
* the input.
* @returns null if the witness is not a script spend, and the hex string of
* the script item if it is a script spend.
*/
public witnessToP2TRScript(witness: string[]): string | null {
if (witness.length < 2) return null;
// Note: see BIP341 for parsing details of witness stack
// If there are at least two witness elements, and the first byte of the
// last element is 0x50, this last element is called annex a and
// is removed from the witness stack.
const hasAnnex = witness[witness.length - 1].substring(0, 2) === '50';
// If there are at least two witness elements left, script path spending is used.
// Call the second-to-last stack element s, the script.
// (Note: this phrasing from BIP341 assumes we've *removed* the annex from the stack)
if (hasAnnex && witness.length < 3) return null;
const positionOfScript = hasAnnex ? witness.length - 3 : witness.length - 2;
return witness[positionOfScript];
}
}
export default new TransactionUtils();

View File

@@ -1,11 +1,10 @@
import config from '../config';
import logger from '../logger';
import { ThreadTransaction, MempoolBlockWithTransactions, AuditTransaction } from '../mempool.interfaces';
import { CompactThreadTransaction, AuditTransaction } from '../mempool.interfaces';
import { PairingHeap } from '../utils/pairing-heap';
import { Common } from './common';
import { parentPort } from 'worker_threads';
let mempool: { [txid: string]: ThreadTransaction } = {};
let mempool: Map<number, CompactThreadTransaction> = new Map();
if (parentPort) {
parentPort.on('message', (params) => {
@@ -13,18 +12,18 @@ if (parentPort) {
mempool = params.mempool;
} else if (params.type === 'update') {
params.added.forEach(tx => {
mempool[tx.txid] = tx;
mempool.set(tx.uid, tx);
});
params.removed.forEach(txid => {
delete mempool[txid];
params.removed.forEach(uid => {
mempool.delete(uid);
});
}
const { blocks, clusters } = makeBlockTemplates(mempool);
const { blocks, rates, clusters } = makeBlockTemplates(mempool);
// return the result to main thread.
if (parentPort) {
parentPort.postMessage({ blocks, clusters });
parentPort.postMessage({ blocks, rates, clusters });
}
});
}
@@ -33,35 +32,36 @@ if (parentPort) {
* Build projected mempool blocks 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 makeBlockTemplates(mempool: { [txid: string]: ThreadTransaction })
: { blocks: ThreadTransaction[][], clusters: { [root: string]: string[] } } {
function makeBlockTemplates(mempool: Map<number, CompactThreadTransaction>)
: { blocks: number[][], rates: Map<number, number>, clusters: Map<number, number[]> } {
const start = Date.now();
const auditPool: { [txid: string]: AuditTransaction } = {};
const auditPool: Map<number, AuditTransaction> = new Map();
const mempoolArray: AuditTransaction[] = [];
const restOfArray: ThreadTransaction[] = [];
const cpfpClusters: { [root: string]: string[] } = {};
const cpfpClusters: Map<number, number[]> = new Map();
// grab the top feerate txs up to maxWeight
Object.values(mempool).sort((a, b) => b.feePerVsize - a.feePerVsize).forEach(tx => {
mempool.forEach(tx => {
tx.dirty = false;
// initializing everything up front helps V8 optimize property access later
auditPool[tx.txid] = {
txid: tx.txid,
auditPool.set(tx.uid, {
uid: tx.uid,
fee: tx.fee,
weight: tx.weight,
feePerVsize: tx.feePerVsize,
effectiveFeePerVsize: tx.feePerVsize,
vin: tx.vin,
sigops: tx.sigops,
inputs: tx.inputs || [],
relativesSet: false,
ancestorMap: new Map<string, AuditTransaction>(),
ancestorMap: new Map<number, AuditTransaction>(),
children: new Set<AuditTransaction>(),
ancestorFee: 0,
ancestorWeight: 0,
ancestorSigops: 0,
score: 0,
used: false,
modified: false,
modifiedNode: null,
};
mempoolArray.push(auditPool[tx.txid]);
});
mempoolArray.push(auditPool.get(tx.uid) as AuditTransaction);
});
// Build relatives graph & calculate ancestor scores
@@ -72,15 +72,29 @@ function makeBlockTemplates(mempool: { [txid: string]: ThreadTransaction })
}
// Sort by descending ancestor score
mempoolArray.sort((a, b) => (b.score || 0) - (a.score || 0));
mempoolArray.sort((a, b) => {
if (b.score === a.score) {
// tie-break by uid for stability
return a.uid < b.uid ? -1 : 1;
} else {
return (b.score || 0) - (a.score || 0);
}
});
// Build blocks by greedily choosing the highest feerate package
// (i.e. the package rooted in the transaction with the best ancestor score)
const blocks: ThreadTransaction[][] = [];
const blocks: number[][] = [];
let blockWeight = 4000;
let blockSize = 0;
let blockSigops = 0;
let transactions: AuditTransaction[] = [];
const modified: PairingHeap<AuditTransaction> = new PairingHeap((a, b): boolean => (a.score || 0) > (b.score || 0));
const modified: PairingHeap<AuditTransaction> = new PairingHeap((a, b): boolean => {
if (a.score === b.score) {
// tie-break by uid for stability
return a.uid > b.uid;
} else {
return (a.score || 0) > (b.score || 0);
}
});
let overflow: AuditTransaction[] = [];
let failures = 0;
let top = 0;
@@ -107,30 +121,36 @@ function makeBlockTemplates(mempool: { [txid: string]: ThreadTransaction })
if (nextTx && !nextTx?.used) {
// Check if the package fits into this block
if (blockWeight + nextTx.ancestorWeight < config.MEMPOOL.BLOCK_WEIGHT_UNITS) {
if (blocks.length >= 7 || ((blockWeight + nextTx.ancestorWeight < config.MEMPOOL.BLOCK_WEIGHT_UNITS) && (blockSigops + nextTx.ancestorSigops <= 80000))) {
const ancestors: AuditTransaction[] = 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];
let isCluster = false;
if (sortedTxSet.length > 1) {
cpfpClusters[nextTx.txid] = sortedTxSet.map(tx => tx.txid);
cpfpClusters.set(nextTx.uid, sortedTxSet.map(tx => tx.uid));
isCluster = true;
}
const effectiveFeeRate = nextTx.ancestorFee / (nextTx.ancestorWeight / 4);
const effectiveFeeRate = Math.min(nextTx.dependencyRate || Infinity, nextTx.ancestorFee / (nextTx.ancestorWeight / 4));
const used: AuditTransaction[] = [];
while (sortedTxSet.length) {
const ancestor = sortedTxSet.pop();
const mempoolTx = mempool[ancestor.txid];
const mempoolTx = mempool.get(ancestor.uid);
if (!mempoolTx) {
continue;
}
ancestor.used = true;
ancestor.usedBy = nextTx.txid;
ancestor.usedBy = nextTx.uid;
// update original copy of this tx with effective fee rate & relatives data
mempoolTx.effectiveFeePerVsize = effectiveFeeRate;
if (isCluster) {
mempoolTx.cpfpRoot = nextTx.txid;
if (mempoolTx.effectiveFeePerVsize !== effectiveFeeRate) {
mempoolTx.effectiveFeePerVsize = effectiveFeeRate;
mempoolTx.dirty = true;
}
if (mempoolTx.cpfpRoot !== nextTx.uid) {
mempoolTx.cpfpRoot = isCluster ? nextTx.uid : null;
mempoolTx.dirty;
}
mempoolTx.cpfpChecked = true;
transactions.push(ancestor);
blockSize += ancestor.size;
blockWeight += ancestor.weight;
used.push(ancestor);
}
@@ -138,7 +158,7 @@ function makeBlockTemplates(mempool: { [txid: string]: ThreadTransaction })
// remove these as valid package ancestors for any descendants remaining in the mempool
if (used.length) {
used.forEach(tx => {
updateDescendants(tx, auditPool, modified);
updateDescendants(tx, auditPool, modified, effectiveFeeRate);
});
}
@@ -153,14 +173,16 @@ function makeBlockTemplates(mempool: { [txid: string]: ThreadTransaction })
// 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 => mempool[t.txid]));
blocks.push(transactions.map(t => t.uid));
} else {
break;
}
// reset for the next block
transactions = [];
blockSize = 0;
blockWeight = 4000;
// 'overflow' packages didn't fit in this block, but are valid candidates for the next
@@ -175,50 +197,38 @@ function makeBlockTemplates(mempool: { [txid: string]: ThreadTransaction })
overflow = [];
}
}
// pack any leftover transactions into the last block
for (const tx of overflow) {
if (!tx || tx?.used) {
continue;
}
blockWeight += tx.weight;
const mempoolTx = mempool[tx.txid];
// update original copy of this tx with effective fee rate & relatives data
mempoolTx.effectiveFeePerVsize = tx.score;
if (tx.ancestorMap.size > 0) {
cpfpClusters[tx.txid] = Array.from(tx.ancestorMap?.values()).map(a => a.txid);
mempoolTx.cpfpRoot = tx.txid;
}
mempoolTx.cpfpChecked = true;
transactions.push(tx);
tx.used = true;
if (overflow.length > 0) {
logger.warn('GBT overflow list unexpectedly non-empty after final block constructed');
}
const blockTransactions = transactions.map(t => mempool[t.txid]);
restOfArray.forEach(tx => {
blockWeight += tx.weight;
tx.effectiveFeePerVsize = tx.feePerVsize;
tx.cpfpChecked = false;
blockTransactions.push(tx);
});
if (blockTransactions.length) {
blocks.push(blockTransactions);
// add the final unbounded block if it contains any transactions
if (transactions.length > 0) {
blocks.push(transactions.map(t => t.uid));
}
// get map of dirty transactions
const rates = new Map<number, number>();
for (const tx of mempool.values()) {
if (tx?.dirty) {
rates.set(tx.uid, tx.effectiveFeePerVsize || tx.feePerVsize);
}
}
transactions = [];
const end = Date.now();
const time = end - start;
logger.debug('Mempool templates calculated in ' + time / 1000 + ' seconds');
return { blocks, clusters: cpfpClusters };
return { blocks, rates, clusters: cpfpClusters };
}
// traverse in-mempool ancestors
// recursion unavoidable, but should be limited to depth < 25 by mempool policy
function setRelatives(
tx: AuditTransaction,
mempool: { [txid: string]: AuditTransaction },
mempool: Map<number, AuditTransaction>,
): void {
for (const parent of tx.vin) {
const parentTx = mempool[parent];
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);
@@ -227,15 +237,17 @@ function setRelatives(
setRelatives(parentTx, mempool);
}
parentTx.ancestorMap.forEach((ancestor) => {
tx.ancestorMap.set(ancestor.txid, ancestor);
tx.ancestorMap.set(ancestor.uid, ancestor);
});
}
};
tx.ancestorFee = tx.fee || 0;
tx.ancestorWeight = tx.weight || 0;
tx.ancestorSigops = tx.sigops || 0;
tx.ancestorMap.forEach((ancestor) => {
tx.ancestorFee += ancestor.fee;
tx.ancestorWeight += ancestor.weight;
tx.ancestorSigops += ancestor.sigops;
});
tx.score = tx.ancestorFee / ((tx.ancestorWeight / 4) || 1);
tx.relativesSet = true;
@@ -245,8 +257,9 @@ function setRelatives(
// avoids recursion to limit call stack depth
function updateDescendants(
rootTx: AuditTransaction,
mempool: { [txid: string]: AuditTransaction },
mempool: Map<number, AuditTransaction>,
modified: PairingHeap<AuditTransaction>,
clusterRate: number,
): void {
const descendantSet: Set<AuditTransaction> = new Set();
// stack of nodes left to visit
@@ -261,13 +274,15 @@ function updateDescendants(
});
while (descendants.length) {
descendantTx = descendants.pop();
if (descendantTx && descendantTx.ancestorMap && descendantTx.ancestorMap.has(rootTx.txid)) {
if (descendantTx && descendantTx.ancestorMap && descendantTx.ancestorMap.has(rootTx.uid)) {
// remove tx as ancestor
descendantTx.ancestorMap.delete(rootTx.txid);
descendantTx.ancestorMap.delete(rootTx.uid);
descendantTx.ancestorFee -= rootTx.fee;
descendantTx.ancestorWeight -= rootTx.weight;
descendantTx.ancestorSigops -= rootTx.sigops;
tmpScore = descendantTx.score;
descendantTx.score = descendantTx.ancestorFee / (descendantTx.ancestorWeight / 4);
descendantTx.dependencyRate = descendantTx.dependencyRate ? Math.min(descendantTx.dependencyRate, clusterRate) : clusterRate;
if (!descendantTx.modifiedNode) {
descendantTx.modified = true;

File diff suppressed because it is too large Load Diff

View File

@@ -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;
@@ -12,6 +13,7 @@ interface IConfig {
API_URL_PREFIX: string;
POLL_RATE_MS: number;
CACHE_DIR: string;
CACHE_ENABLED: boolean;
CLEAR_PROTECTION_MINUTES: number;
RECOMMENDED_FEE_PERCENTILE: number;
BLOCK_WEIGHT_UNITS: number;
@@ -19,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;
@@ -29,14 +32,24 @@ interface IConfig {
POOLS_JSON_URL: string,
POOLS_JSON_TREE_URL: string,
AUDIT: boolean;
ADVANCED_GBT_AUDIT: boolean;
ADVANCED_GBT_MEMPOOL: boolean;
RUST_GBT: boolean;
LIMIT_GBT: boolean;
CPFP_INDEXING: boolean;
MAX_BLOCKS_BULK_QUERY: number;
DISK_CACHE_BLOCK_INTERVAL: number;
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: {
ENABLED: boolean;
@@ -68,6 +81,8 @@ interface IConfig {
USERNAME: string;
PASSWORD: string;
TIMEOUT: number;
COOKIE: boolean;
COOKIE_PATH: string;
};
SECOND_CORE_RPC: {
HOST: string;
@@ -75,6 +90,8 @@ interface IConfig {
USERNAME: string;
PASSWORD: string;
TIMEOUT: number;
COOKIE: boolean;
COOKIE_PATH: string;
};
DATABASE: {
ENABLED: boolean;
@@ -84,6 +101,9 @@ interface IConfig {
DATABASE: string;
USERNAME: string;
PASSWORD: string;
TIMEOUT: number;
PID_DIR: string;
POOL_SIZE: number;
};
SYSLOG: {
ENABLED: boolean;
@@ -96,10 +116,6 @@ interface IConfig {
ENABLED: boolean;
TX_PER_SECOND_SAMPLE_PERIOD: number;
};
BISQ: {
ENABLED: boolean;
DATA_PATH: string;
};
SOCKS5PROXY: {
ENABLED: boolean;
USE_ONION: boolean;
@@ -108,17 +124,11 @@ interface IConfig {
USERNAME: string;
PASSWORD: string;
};
PRICE_DATA_SERVER: {
TOR_URL: string;
CLEARNET_URL: string;
};
EXTERNAL_DATA_SERVER: {
MEMPOOL_API: string;
MEMPOOL_ONION: string;
LIQUID_API: string;
LIQUID_ONION: string;
BISQ_URL: string;
BISQ_ONION: string;
};
MAXMIND: {
ENABLED: boolean;
@@ -126,11 +136,31 @@ interface IConfig {
GEOLITE2_ASN: string;
GEOIP2_ISP: string;
},
REPLICATION: {
ENABLED: boolean;
AUDIT: boolean;
AUDIT_START_HEIGHT: number;
SERVERS: string[];
},
MEMPOOL_SERVICES: {
API: string;
ACCELERATIONS: boolean;
},
REDIS: {
ENABLED: boolean;
UNIX_SOCKET_PATH: string;
BATCH_QUERY_BASE_SIZE: number;
},
FIAT_PRICE: {
ENABLED: boolean;
API_KEY: string;
},
}
const defaults: IConfig = {
'MEMPOOL': {
'ENABLED': true,
'OFFICIAL': false,
'NETWORK': 'mainnet',
'BACKEND': 'none',
'HTTP_PORT': 8999,
@@ -138,6 +168,7 @@ const defaults: IConfig = {
'API_URL_PREFIX': '/api/v1/',
'POLL_RATE_MS': 2000,
'CACHE_DIR': './cache',
'CACHE_ENABLED': true,
'CLEAR_PROTECTION_MINUTES': 20,
'RECOMMENDED_FEE_PERCENTILE': 50,
'BLOCK_WEIGHT_UNITS': 4000000,
@@ -145,6 +176,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,
@@ -155,14 +187,24 @@ const defaults: IConfig = {
'POOLS_JSON_URL': 'https://raw.githubusercontent.com/mempool/mining-pools/master/pools-v2.json',
'POOLS_JSON_TREE_URL': 'https://api.github.com/repos/mempool/mining-pools/git/trees/master',
'AUDIT': false,
'ADVANCED_GBT_AUDIT': false,
'ADVANCED_GBT_MEMPOOL': false,
'RUST_GBT': false,
'LIMIT_GBT': false,
'CPFP_INDEXING': false,
'MAX_BLOCKS_BULK_QUERY': 0,
'DISK_CACHE_BLOCK_INTERVAL': 6,
'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': {
'HOST': '127.0.0.1',
@@ -175,6 +217,8 @@ const defaults: IConfig = {
'USERNAME': 'mempool',
'PASSWORD': 'mempool',
'TIMEOUT': 60000,
'COOKIE': false,
'COOKIE_PATH': '/bitcoin/.cookie'
},
'SECOND_CORE_RPC': {
'HOST': '127.0.0.1',
@@ -182,6 +226,8 @@ const defaults: IConfig = {
'USERNAME': 'mempool',
'PASSWORD': 'mempool',
'TIMEOUT': 60000,
'COOKIE': false,
'COOKIE_PATH': '/bitcoin/.cookie'
},
'DATABASE': {
'ENABLED': true,
@@ -190,7 +236,10 @@ const defaults: IConfig = {
'PORT': 3306,
'DATABASE': 'mempool',
'USERNAME': 'mempool',
'PASSWORD': 'mempool'
'PASSWORD': 'mempool',
'TIMEOUT': 180000,
'PID_DIR': '',
'POOL_SIZE': 100,
},
'SYSLOG': {
'ENABLED': true,
@@ -203,10 +252,6 @@ const defaults: IConfig = {
'ENABLED': true,
'TX_PER_SECOND_SAMPLE_PERIOD': 150
},
'BISQ': {
'ENABLED': false,
'DATA_PATH': '/bisq/statsnode-data/btc_mainnet/db'
},
'LIGHTNING': {
'ENABLED': false,
'BACKEND': 'lnd',
@@ -234,17 +279,11 @@ const defaults: IConfig = {
'USERNAME': '',
'PASSWORD': ''
},
'PRICE_DATA_SERVER': {
'TOR_URL': 'http://wizpriceje6q5tdrxkyiazsgu7irquiqjy2dptezqhrtu7l2qelqktid.onion/getAllMarketPrices',
'CLEARNET_URL': 'https://price.bisq.wiz.biz/getAllMarketPrices'
},
'EXTERNAL_DATA_SERVER': {
'MEMPOOL_API': 'https://mempool.space/api/v1',
'MEMPOOL_ONION': 'http://mempoolhqx4isw62xs7abwphsq7ldayuidyx2v2oethdhhj6mlo2r6ad.onion/api/v1',
'LIQUID_API': 'https://liquid.network/api/v1',
'LIQUID_ONION': 'http://liquidmom47f6s3m53ebfxn47p76a6tlnxib3wp6deux7wuzotdr6cyd.onion/api/v1',
'BISQ_URL': 'https://bisq.markets/api',
'BISQ_ONION': 'http://bisqmktse2cabavbr2xjq7xw3h6g5ottemo5rolfcwt6aly6tp5fdryd.onion/api'
'LIQUID_ONION': 'http://liquidmom47f6s3m53ebfxn47p76a6tlnxib3wp6deux7wuzotdr6cyd.onion/api/v1'
},
'MAXMIND': {
'ENABLED': false,
@@ -252,6 +291,25 @@ const defaults: IConfig = {
'GEOLITE2_ASN': '/usr/local/share/GeoIP/GeoLite2-ASN.mmdb',
'GEOIP2_ISP': '/usr/local/share/GeoIP/GeoIP2-ISP.mmdb'
},
'REPLICATION': {
'ENABLED': false,
'AUDIT': false,
'AUDIT_START_HEIGHT': 774000,
'SERVERS': [],
},
'MEMPOOL_SERVICES': {
'API': '',
'ACCELERATIONS': false,
},
'REDIS': {
'ENABLED': false,
'UNIX_SOCKET_PATH': '',
'BATCH_QUERY_BASE_SIZE': 5000,
},
'FIAT_PRICE': {
'ENABLED': true,
'API_KEY': '',
},
};
class Config implements IConfig {
@@ -263,14 +321,16 @@ class Config implements IConfig {
DATABASE: IConfig['DATABASE'];
SYSLOG: IConfig['SYSLOG'];
STATISTICS: IConfig['STATISTICS'];
BISQ: IConfig['BISQ'];
LIGHTNING: IConfig['LIGHTNING'];
LND: IConfig['LND'];
CLIGHTNING: IConfig['CLIGHTNING'];
SOCKS5PROXY: IConfig['SOCKS5PROXY'];
PRICE_DATA_SERVER: IConfig['PRICE_DATA_SERVER'];
EXTERNAL_DATA_SERVER: IConfig['EXTERNAL_DATA_SERVER'];
MAXMIND: IConfig['MAXMIND'];
REPLICATION: IConfig['REPLICATION'];
MEMPOOL_SERVICES: IConfig['MEMPOOL_SERVICES'];
REDIS: IConfig['REDIS'];
FIAT_PRICE: IConfig['FIAT_PRICE'];
constructor() {
const configs = this.merge(configFromFile, defaults);
@@ -282,14 +342,16 @@ class Config implements IConfig {
this.DATABASE = configs.DATABASE;
this.SYSLOG = configs.SYSLOG;
this.STATISTICS = configs.STATISTICS;
this.BISQ = configs.BISQ;
this.LIGHTNING = configs.LIGHTNING;
this.LND = configs.LND;
this.CLIGHTNING = configs.CLIGHTNING;
this.SOCKS5PROXY = configs.SOCKS5PROXY;
this.PRICE_DATA_SERVER = configs.PRICE_DATA_SERVER;
this.EXTERNAL_DATA_SERVER = configs.EXTERNAL_DATA_SERVER;
this.MAXMIND = configs.MAXMIND;
this.REPLICATION = configs.REPLICATION;
this.MEMPOOL_SERVICES = configs.MEMPOOL_SERVICES;
this.REDIS = configs.REDIS;
this.FIAT_PRICE = configs.FIAT_PRICE;
}
merge = (...objects: object[]): IConfig => {

View File

@@ -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,11 +34,82 @@ import { FieldPacket, OkPacket, PoolOptions, ResultSetHeader, RowDataPacket } fr
}
public async query<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket |
OkPacket[] | ResultSetHeader>(query, params?): Promise<[T, FieldPacket[]]>
OkPacket[] | ResultSetHeader>(query, params?, errorLogLevel: LogLevel | 'silent' = 'debug', connection?: PoolConnection): Promise<[T, FieldPacket[]]>
{
this.checkDBFlag();
let hardTimeout;
if (query?.timeout != null) {
hardTimeout = Math.floor(query.timeout * 1.1);
} else {
hardTimeout = config.DATABASE.TIMEOUT;
}
if (hardTimeout > 0) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`DB query failed to return, reject or time out within ${hardTimeout / 1000}s - ${query?.sql?.slice(0, 160) || (typeof(query) === 'string' || query instanceof String ? query?.slice(0, 160) : 'unknown query')}`));
}, hardTimeout);
// Use a specific connection if provided, otherwise delegate to the pool
const connectionPromise = connection ? Promise.resolve(connection) : this.getPool();
connectionPromise.then((pool: PoolConnection | Pool) => {
return pool.query(query, params) as Promise<[T, FieldPacket[]]>;
}).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 {
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<void> {
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<T extends RowDataPacket[][] | RowDataPacket[] | OkPacket |
OkPacket[] | ResultSetHeader>(queries: { query, params }[], errorLogLevel: LogLevel | 'silent' = 'debug'): Promise<[T, FieldPacket[]][]>
{
const pool = await this.getPool();
return pool.query(query, params);
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
const results: [T, FieldPacket[]][] = [];
for (const query of queries) {
const result = await this.query(query.query, query.params, errorLogLevel, connection) as [T, FieldPacket[]];
results.push(result);
}
await connection.commit();
return results;
} catch (e) {
logger.warn('Could not complete db transaction, rolling back: ' + (e instanceof Error ? e.message : e));
this.$rollbackAtomic(connection);
throw e;
} finally {
connection.release();
}
}
public async checkDbConnection() {
@@ -48,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<Pool> {
if (this.pool === null) {
this.pool = createPool(this.poolConfig);

View File

@@ -2,6 +2,7 @@ import express from 'express';
import { Application, Request, Response, NextFunction } from 'express';
import * as http from 'http';
import * as WebSocket from 'ws';
import bitcoinApi from './api/bitcoin/bitcoin-api-factory';
import cluster from 'cluster';
import DB from './database';
import config from './config';
@@ -10,8 +11,6 @@ import memPool from './api/mempool';
import diskCache from './api/disk-cache';
import statistics from './api/statistics/statistics';
import websocketHandler from './api/websocket-handler';
import bisq from './api/bisq/bisq';
import bisqMarkets from './api/bisq/markets';
import logger from './logger';
import backendInfo from './api/backend-info';
import loadingIndicators from './api/loading-indicators';
@@ -29,8 +28,8 @@ import generalLightningRoutes from './api/explorer/general.routes';
import lightningStatsUpdater from './tasks/lightning/stats-updater.service';
import networkSyncService from './tasks/lightning/network-sync.service';
import statisticsRoutes from './api/statistics/statistics.routes';
import pricesRoutes from './api/prices/prices.routes';
import miningRoutes from './api/mining/mining-routes';
import bisqRoutes from './api/bisq/bisq.routes';
import liquidRoutes from './api/liquid/liquid.routes';
import bitcoinRoutes from './api/bitcoin/bitcoin.routes';
import fundingTxFetcher from './tasks/lightning/sync-tasks/funding-tx-fetcher';
@@ -40,12 +39,17 @@ import chainTips from './api/chain-tips';
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';
import bitcoinSecondClient from './api/bitcoin/bitcoin-second-client';
class Server {
private wss: WebSocket.Server | undefined;
private server: http.Server | undefined;
private app: Application;
private currentBackendRetryInterval = 5;
private currentBackendRetryInterval = 1;
private backendRetryCount = 0;
private maxHeapSize: number = 0;
private heapLogInterval: number = 60;
@@ -87,7 +91,24 @@ class Server {
async startServer(worker = false): Promise<void> {
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
@@ -108,7 +129,7 @@ class Server {
.use(express.text({ type: ['text/plain', 'application/base64'] }))
;
if (config.DATABASE.ENABLED) {
if (config.DATABASE.ENABLED && config.FIAT_PRICE.ENABLED) {
await priceUpdater.$initializeLatestPriceWithDb();
}
@@ -120,7 +141,11 @@ class Server {
await poolsUpdater.updatePoolsJson(); // Needs to be done before loading the disk cache because we sometimes wipe it
await syncAssets.syncAssets$();
if (config.MEMPOOL.ENABLED) {
diskCache.loadMempoolCache();
if (config.MEMPOOL.CACHE_ENABLED) {
await diskCache.$loadMempoolCache();
} else if (config.REDIS.ENABLED) {
await redisCache.$loadCache();
}
}
if (config.STATISTICS.ENABLED && config.DATABASE.ENABLED && cluster.isPrimary) {
@@ -128,14 +153,22 @@ class Server {
}
if (Common.isLiquid()) {
try {
icons.loadIcons();
} catch (e) {
logger.err('Cannot load liquid icons. Ignoring. Reason: ' + (e instanceof Error ? e.message : e));
}
const refreshIcons = () => {
try {
icons.loadIcons();
} catch (e) {
logger.err('Cannot load liquid icons. Ignoring. Reason: ' + (e instanceof Error ? e.message : e));
}
};
// Run once on startup.
refreshIcons();
// Matches crontab refresh interval for asset db.
setInterval(refreshIcons, 3600_000);
}
priceUpdater.$run();
if (config.FIAT_PRICE.ENABLED) {
priceUpdater.$run();
}
await chainTips.updateOrphanedBlocks();
this.setUpHttpApiRoutes();
@@ -146,13 +179,6 @@ class Server {
setInterval(() => { this.healthCheck(); }, 2500);
if (config.BISQ.ENABLED) {
bisq.startBisqService();
bisq.setPriceCallbackFunction((price) => websocketHandler.setExtraInitProperties('bsq-price', price));
blocks.setNewBlockCallback(bisq.handleNewBitcoinBlock.bind(bisq));
bisqMarkets.startBisqService();
}
if (config.LIGHTNING.ENABLED) {
this.$runLightningBackend();
}
@@ -167,6 +193,7 @@ class Server {
}
async runMainUpdateLoop(): Promise<void> {
const start = Date.now();
try {
try {
await memPool.$updateMemPoolInfo();
@@ -178,22 +205,35 @@ class Server {
logger.debug(msg);
}
}
await blocks.$updateBlocks();
await memPool.$updateMempool();
const newMempool = await bitcoinApi.$getRawMempool();
const minFeeMempool = memPool.limitGBT ? await bitcoinSecondClient.getRawMemPool() : null;
const minFeeTip = memPool.limitGBT ? await bitcoinSecondClient.getBlockCount() : -1;
const newAccelerations = await accelerationApi.$fetchAccelerations();
const numHandledBlocks = await blocks.$updateBlocks();
const pollRate = config.MEMPOOL.POLL_RATE_MS * (indexer.indexerIsRunning() ? 10 : 1);
if (numHandledBlocks === 0) {
await memPool.$updateMempool(newMempool, newAccelerations, minFeeMempool, minFeeTip, pollRate);
}
indexer.$run();
if (config.FIAT_PRICE.ENABLED) {
priceUpdater.$run();
}
setTimeout(this.runMainUpdateLoop.bind(this), config.MEMPOOL.POLL_RATE_MS);
this.currentBackendRetryInterval = 5;
// rerun immediately if we skipped the mempool update, otherwise wait POLL_RATE_MS
const elapsed = Date.now() - start;
const remainingTime = Math.max(0, pollRate - elapsed);
setTimeout(this.runMainUpdateLoop.bind(this), numHandledBlocks > 0 ? 0 : remainingTime);
this.backendRetryCount = 0;
} catch (e: any) {
let loggerMsg = `Exception in runMainUpdateLoop(). Retrying in ${this.currentBackendRetryInterval} sec.`;
this.backendRetryCount++;
let loggerMsg = `Exception in runMainUpdateLoop() (count: ${this.backendRetryCount}). Retrying in ${this.currentBackendRetryInterval} sec.`;
loggerMsg += ` Reason: ${(e instanceof Error ? e.message : e)}.`;
if (e?.stack) {
loggerMsg += ` Stack trace: ${e.stack}`;
}
// When we get a first Exception, only `logger.debug` it and retry after 5 seconds
// From the second Exception, `logger.warn` the Exception and increase the retry delay
// Maximum retry delay is 60 seconds
if (this.currentBackendRetryInterval > 5) {
if (this.backendRetryCount >= 5) {
logger.warn(loggerMsg);
mempool.setOutOfSync();
} else {
@@ -203,8 +243,8 @@ class Server {
logger.debug(`AxiosError: ${e?.message}`);
}
setTimeout(this.runMainUpdateLoop.bind(this), 1000 * this.currentBackendRetryInterval);
this.currentBackendRetryInterval *= 2;
this.currentBackendRetryInterval = Math.min(this.currentBackendRetryInterval, 60);
} finally {
diskCache.unlock();
}
}
@@ -229,6 +269,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));
}
@@ -237,24 +278,25 @@ class Server {
websocketHandler.setupConnectionHandling();
if (config.MEMPOOL.ENABLED) {
statistics.setNewStatisticsEntryCallback(websocketHandler.handleNewStatistic.bind(websocketHandler));
memPool.setAsyncMempoolChangedCallback(websocketHandler.handleMempoolChange.bind(websocketHandler));
memPool.setAsyncMempoolChangedCallback(websocketHandler.$handleMempoolChange.bind(websocketHandler));
blocks.setNewAsyncBlockCallback(websocketHandler.handleNewBlock.bind(websocketHandler));
}
priceUpdater.setRatesChangedCallback(websocketHandler.handleNewConversionRates.bind(websocketHandler));
if (config.FIAT_PRICE.ENABLED) {
priceUpdater.setRatesChangedCallback(websocketHandler.handleNewConversionRates.bind(websocketHandler));
}
loadingIndicators.setProgressChangedCallback(websocketHandler.handleLoadingChanged.bind(websocketHandler));
}
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);
}
if (Common.indexingEnabled() && config.MEMPOOL.ENABLED) {
miningRoutes.initRoutes(this.app);
}
if (config.BISQ.ENABLED) {
bisqRoutes.initRoutes(this.app);
}
if (Common.isLiquid()) {
liquidRoutes.initRoutes(this.app);
}
@@ -275,7 +317,7 @@ class Server {
if (!this.warnedHeapCritical && this.maxHeapSize > warnThreshold) {
this.warnedHeapCritical = true;
logger.warn(`Used ${(this.maxHeapSize / stats.heap_size_limit).toFixed(2)}% of heap limit (${formatBytes(this.maxHeapSize, byteUnits, true)} / ${formatBytes(stats.heap_size_limit, byteUnits)})!`);
logger.warn(`Used ${(this.maxHeapSize / stats.heap_size_limit * 100).toFixed(2)}% of heap limit (${formatBytes(this.maxHeapSize, byteUnits, true)} / ${formatBytes(stats.heap_size_limit, byteUnits)})!`);
}
if (this.lastHeapLogTime === null || (now - this.lastHeapLogTime) > (this.heapLogInterval * 1000)) {
logger.debug(`Memory usage: ${formatBytes(this.maxHeapSize, byteUnits)} / ${formatBytes(stats.heap_size_limit, byteUnits)}`);
@@ -284,6 +326,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())();

View File

@@ -6,6 +6,9 @@ import logger from './logger';
import bitcoinClient from './api/bitcoin/bitcoin-client';
import priceUpdater from './tasks/price-updater';
import PricesRepository from './repositories/PricesRepository';
import config from './config';
import auditReplicator from './replication/AuditReplication';
import AccelerationRepository from './repositories/AccelerationRepository';
export interface CoreIndex {
name: string;
@@ -13,11 +16,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
@@ -67,33 +77,69 @@ class Indexer {
}
}
public async runSingleTask(task: 'blocksPrices' | 'coinStatsIndex'): Promise<void> {
if (!Common.indexingEnabled()) {
return;
}
if (task === 'blocksPrices' && !this.tasksRunning.includes(task)) {
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<void> {
if (!Common.indexingEnabled() || this.tasksRunning[task]) {
return;
}
this.tasksRunning[task] = true;
switch (task) {
case 'blocksPrices': {
if (!['testnet', 'signet'].includes(config.MEMPOOL.NETWORK) && config.FIAT_PRICE.ENABLED) {
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<void> {
@@ -103,6 +149,14 @@ class Indexer {
return;
}
if (config.FIAT_PRICE.ENABLED) {
try {
await priceUpdater.$run();
} catch (e) {
logger.err(`Running priceUpdater failed. Reason: ` + (e instanceof Error ? e.message : e));
}
}
// Do not attempt to index anything unless Bitcoin Core is fully synced
const blockchainInfo = await bitcoinClient.getBlockchainInfo();
if (blockchainInfo.blocks !== blockchainInfo.headers) {
@@ -117,8 +171,6 @@ class Indexer {
await this.checkAvailableCoreIndexes();
try {
await priceUpdater.$run();
const chainValid = await blocks.$generateBlockDatabase();
if (chainValid === false) {
// Chain of block hash was invalid, so we need to reindex. Stop here and continue at the next iteration
@@ -134,6 +186,11 @@ class Indexer {
await mining.$generatePoolHashrateHistory();
await blocks.$generateBlocksSummariesDatabase();
await blocks.$generateCPFPDatabase();
await blocks.$generateAuditStats();
await auditReplicator.$sync();
await AccelerationRepository.$indexPastAccelerations();
// 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));

View File

@@ -35,6 +35,7 @@ class Logger {
public tags = {
mining: 'Mining',
ln: 'Lightning',
goggles: 'Goggles',
};
// @ts-ignore
@@ -69,6 +70,10 @@ class Logger {
this.network = this.getNetwork();
}
public updateNetwork(): void {
this.network = this.getNetwork();
}
private addprio(prio): void {
this[prio] = (function(_this) {
return function(msg, tag?: string) {
@@ -81,9 +86,6 @@ class Logger {
if (config.LIGHTNING.ENABLED) {
return config.MEMPOOL.NETWORK === 'mainnet' ? 'lightning' : `${config.MEMPOOL.NETWORK}-lightning`;
}
if (config.BISQ.ENABLED) {
return 'bisq';
}
if (config.MEMPOOL.NETWORK && config.MEMPOOL.NETWORK !== 'mainnet') {
return config.MEMPOOL.NETWORK;
}
@@ -153,4 +155,6 @@ class Logger {
}
}
export type LogLevel = 'emerg' | 'alert' | 'crit' | 'err' | 'warn' | 'notice' | 'info' | 'debug';
export default new Logger();

View File

@@ -19,6 +19,8 @@ export interface PoolInfo {
blockCount: number;
slug: string;
avgMatchRate: number | null;
avgFeeDelta: number | null;
poolUniqueId: number;
}
export interface PoolStats extends PoolInfo {
@@ -32,13 +34,21 @@ export interface BlockAudit {
hash: string,
missingTxs: string[],
freshTxs: string[],
sigopTxs: string[],
fullrbfTxs: string[],
addedTxs: string[],
prioritizedTxs: string[],
acceleratedTxs: string[],
matchRate: number,
expectedFees?: number,
expectedWeight?: number,
}
export interface AuditScore {
hash: string,
matchRate?: number,
expectedFees?: number
expectedWeight?: number
}
export interface MempoolBlock {
@@ -52,12 +62,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: MempoolDeltaChange[];
}
interface VinStrippedToScriptsig {
@@ -79,25 +90,65 @@ export interface TransactionExtended extends IEsploraApi.Transaction {
descendants?: Ancestor[];
bestDescendant?: BestDescendant | null;
cpfpChecked?: boolean;
deleteAfter?: number;
position?: {
block: number,
vsize: number,
};
acceleration?: boolean;
replacement?: boolean;
uid?: number;
flags?: number;
}
export interface MempoolTransactionExtended extends TransactionExtended {
order: number;
sigops: number;
adjustedVsize: number;
adjustedFeePerVsize: number;
inputs?: number[];
lastBoosted?: number;
cpfpDirty?: boolean;
cpfpUpdated?: number;
}
export interface AuditTransaction {
txid: string;
uid: number;
fee: number;
weight: number;
feePerVsize: number;
effectiveFeePerVsize: number;
vin: string[];
sigops: number;
inputs: number[];
relativesSet: boolean;
ancestorMap: Map<string, AuditTransaction>;
ancestorMap: Map<number, AuditTransaction>;
children: Set<AuditTransaction>;
ancestorFee: number;
ancestorWeight: number;
ancestorSigops: number;
score: number;
used: boolean;
modified: boolean;
modifiedNode: HeapNode<AuditTransaction>;
dependencyRate?: number;
}
export interface CompactThreadTransaction {
uid: number;
fee: number;
weight: number;
sigops: number;
feePerVsize: number;
effectiveFeePerVsize: number;
inputs: number[];
cpfpRoot?: number;
cpfpChecked?: boolean;
dirty?: boolean;
}
export interface GbtCandidates {
txs: { [txid: string ]: boolean },
added: MempoolTransactionExtended[];
removed: MempoolTransactionExtended[];
}
export interface ThreadTransaction {
@@ -106,7 +157,7 @@ export interface ThreadTransaction {
weight: number;
feePerVsize: number;
effectiveFeePerVsize?: number;
vin: string[];
inputs: number[];
cpfpRoot?: string;
cpfpChecked?: boolean;
}
@@ -138,6 +189,9 @@ export interface CpfpInfo {
bestDescendant?: BestDescendant | null;
descendants?: Ancestor[];
effectiveFeePerVsize?: number;
sigops?: number;
adjustedVsize?: number,
acceleration?: boolean,
}
export interface TransactionStripped {
@@ -145,14 +199,66 @@ export interface TransactionStripped {
fee: number;
vsize: number;
value: number;
acc?: boolean;
rate?: number; // effective fee rate
time?: number;
}
export interface TransactionClassified extends TransactionStripped {
flags: number;
}
// [txid, fee, vsize, value, rate, flags, acceleration?]
export type TransactionCompressed = [string, number, 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,
fake_scripthash: 0b00001000_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
feeRange: number[]; // fee rate percentiles
reward: number;
matchRate: number | null;
expectedFees: number | null;
expectedWeight: number | null;
similarity?: number;
pool: {
id: number; // Note - This is the `unique_id`, not to mix with the auto increment `id`
@@ -189,11 +295,22 @@ export interface BlockExtension {
*/
export interface BlockExtended extends IEsploraApi.Block {
extras: BlockExtension;
canonical?: string;
}
export interface BlockSummary {
id: string;
transactions: TransactionStripped[];
transactions: TransactionClassified[];
version?: number;
}
export interface AuditSummary extends BlockAudit {
timestamp?: number,
size?: number,
weight?: number,
tx_count?: number,
transactions: TransactionClassified[];
template?: TransactionClassified[];
}
export interface BlockPrice {
@@ -214,6 +331,28 @@ export interface MempoolStats {
tx_count: number;
}
export interface EffectiveFeeStats {
medianFee: number; // median effective fee rate
feeRange: number[]; // 2nd, 10th, 25th, 50th, 75th, 90th, 98th percentiles
}
export interface WorkingEffectiveFeeStats extends EffectiveFeeStats {
minFee: number;
maxFee: number;
}
export interface CpfpCluster {
root: string,
height: number,
txs: Ancestor[],
effectiveFeePerVsize: number,
}
export interface CpfpSummary {
transactions: TransactionExtended[];
clusters: CpfpCluster[];
}
export interface Statistic {
id?: number;
added: string;
@@ -223,6 +362,7 @@ export interface Statistic {
total_fee: number;
mempool_byte_weight: number;
fee_data: string;
min_fee: number;
vsize_1: number;
vsize_2: number;
@@ -269,16 +409,32 @@ export interface OptimizedStatistic {
vbytes_per_second: number;
total_fee: number;
mempool_byte_weight: number;
min_fee: number;
vsizes: number[];
}
export interface TxTrackingInfo {
replacedBy?: string,
position?: { block: number, vsize: number, accelerated?: boolean },
cpfp?: {
ancestors?: Ancestor[],
bestDescendant?: Ancestor | null,
descendants?: Ancestor[] | null,
effectiveFeePerVsize?: number | null,
sigops: number,
adjustedVsize: number,
},
utxoSpent?: { [vout: number]: { vin: number, txid: string } },
accelerated?: boolean,
confirmed?: boolean
}
export interface WebsocketResponse {
action: string;
data: string[];
'track-tx': string;
'track-address': string;
'watch-mempool': boolean;
'track-bisq-market': string;
}
export interface VbytesPerSecond {
@@ -300,6 +456,7 @@ export interface IBackendInfo {
gitCommit: string;
version: string;
lightning: boolean;
backend: 'esplora' | 'electrum' | 'none';
}
export interface IDifficultyAdjustment {
@@ -309,9 +466,11 @@ export interface IDifficultyAdjustment {
remainingBlocks: number;
remainingTime: number;
previousRetarget: number;
previousTime: number;
nextRetargetHeight: number;
timeAvg: number;
timeOffset: number;
expectedBlocks: number;
}
export interface IndexedDifficultyAdjustment {

View File

@@ -0,0 +1,137 @@
import DB from '../database';
import logger from '../logger';
import { AuditSummary } from '../mempool.interfaces';
import blocksAuditsRepository from '../repositories/BlocksAuditsRepository';
import blocksSummariesRepository from '../repositories/BlocksSummariesRepository';
import { $sync } from './replicator';
import config from '../config';
import { Common } from '../api/common';
import blocks from '../api/blocks';
const BATCH_SIZE = 16;
/**
* Syncs missing block template and audit data from trusted servers
*/
class AuditReplication {
inProgress: boolean = false;
skip: Set<string> = new Set();
public async $sync(): Promise<void> {
if (!config.REPLICATION.ENABLED || !config.REPLICATION.AUDIT) {
// replication not enabled
return;
}
if (this.inProgress) {
logger.info(`AuditReplication sync already in progress`, 'Replication');
return;
}
this.inProgress = true;
const missingAudits = await this.$getMissingAuditBlocks();
logger.debug(`Fetching missing audit data for ${missingAudits.length} blocks from trusted servers`, 'Replication');
let totalSynced = 0;
let totalMissed = 0;
let loggerTimer = Date.now();
// process missing audits in batches of
for (let i = 0; i < missingAudits.length; i += BATCH_SIZE) {
const slice = missingAudits.slice(i, i + BATCH_SIZE);
const results = await Promise.all(slice.map(hash => this.$syncAudit(hash)));
const synced = results.reduce((total, status) => status ? total + 1 : total, 0);
totalSynced += synced;
totalMissed += (slice.length - synced);
if (Date.now() - loggerTimer > 10000) {
loggerTimer = Date.now();
logger.info(`Found ${totalSynced} / ${totalSynced + totalMissed} of ${missingAudits.length} missing audits`, 'Replication');
}
await Common.sleep$(1000);
}
logger.debug(`Fetched ${totalSynced} audits, ${totalMissed} still missing`, 'Replication');
this.inProgress = false;
}
private async $syncAudit(hash: string): Promise<boolean> {
if (this.skip.has(hash)) {
// we already know none of our trusted servers have this audit
return false;
}
let success = false;
// start with a random server so load is uniformly spread
const syncResult = await $sync(`/api/v1/block/${hash}/audit-summary`);
if (syncResult) {
if (syncResult.data?.template?.length) {
await this.$saveAuditData(hash, syncResult.data);
logger.info(`Imported audit data from ${syncResult.server} for block ${syncResult.data.height} (${hash})`);
success = true;
}
if (!syncResult.data && !syncResult.exists) {
this.skip.add(hash);
}
}
return success;
}
private async $getMissingAuditBlocks(): Promise<string[]> {
try {
const startHeight = config.REPLICATION.AUDIT_START_HEIGHT || 0;
const [rows]: any[] = await DB.query(`
SELECT auditable.hash, auditable.height
FROM (
SELECT hash, height
FROM blocks
WHERE height >= ?
) AS auditable
LEFT JOIN blocks_audits ON auditable.hash = blocks_audits.hash
WHERE blocks_audits.hash IS NULL
ORDER BY auditable.height DESC
`, [startHeight]);
return rows.map(row => row.hash);
} catch (e: any) {
logger.err(`Cannot fetch missing audit blocks from db. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
private async $saveAuditData(blockHash: string, auditSummary: AuditSummary): Promise<void> {
// save audit & template to DB
await blocksSummariesRepository.$saveTemplate({
height: auditSummary.height,
template: {
id: blockHash,
transactions: auditSummary.template || []
},
version: 1,
});
await blocksAuditsRepository.$saveAudit({
hash: blockHash,
height: auditSummary.height,
time: auditSummary.timestamp || auditSummary.time,
missingTxs: auditSummary.missingTxs || [],
addedTxs: auditSummary.addedTxs || [],
prioritizedTxs: auditSummary.prioritizedTxs || [],
freshTxs: auditSummary.freshTxs || [],
sigopTxs: auditSummary.sigopTxs || [],
fullrbfTxs: auditSummary.fullrbfTxs || [],
acceleratedTxs: auditSummary.acceleratedTxs || [],
matchRate: auditSummary.matchRate,
expectedFees: auditSummary.expectedFees,
expectedWeight: auditSummary.expectedWeight,
});
// add missing data to cached blocks
const cachedBlock = blocks.getBlocks().find(block => block.id === blockHash);
if (cachedBlock) {
cachedBlock.extras.matchRate = auditSummary.matchRate;
cachedBlock.extras.expectedFees = auditSummary.expectedFees || null;
cachedBlock.extras.expectedWeight = auditSummary.expectedWeight || null;
}
}
}
export default new AuditReplication();

View File

@@ -0,0 +1,70 @@
import config from '../config';
import backendInfo from '../api/backend-info';
import axios, { AxiosResponse } from 'axios';
import { SocksProxyAgent } from 'socks-proxy-agent';
import * as https from 'https';
export async function $sync(path): Promise<{ data?: any, exists: boolean, server?: string }> {
// start with a random server so load is uniformly spread
let allMissing = true;
const offset = Math.floor(Math.random() * config.REPLICATION.SERVERS.length);
for (let i = 0; i < config.REPLICATION.SERVERS.length; i++) {
const server = config.REPLICATION.SERVERS[(i + offset) % config.REPLICATION.SERVERS.length];
// don't query ourself
if (server === backendInfo.getBackendInfo().hostname) {
continue;
}
try {
const result = await query(`https://${server}${path}`);
if (result) {
return { data: result, exists: true, server };
}
} catch (e: any) {
if (e?.response?.status === 404) {
// this server is also missing this data
} else {
// something else went wrong
allMissing = false;
}
}
}
return { exists: !allMissing };
}
export async function query(path): Promise<object> {
type axiosOptions = {
headers: {
'User-Agent': string
};
timeout: number;
httpsAgent?: https.Agent;
};
const axiosOptions: axiosOptions = {
headers: {
'User-Agent': (config.MEMPOOL.USER_AGENT === 'mempool') ? `mempool/v${backendInfo.getBackendInfo().version}` : `${config.MEMPOOL.USER_AGENT}`
},
timeout: config.SOCKS5PROXY.ENABLED ? 30000 : 10000
};
if (config.SOCKS5PROXY.ENABLED) {
const socksOptions = {
agentOptions: {
keepAlive: true,
},
hostname: config.SOCKS5PROXY.HOST,
port: config.SOCKS5PROXY.PORT,
username: config.SOCKS5PROXY.USERNAME || 'circuit0',
password: config.SOCKS5PROXY.PASSWORD,
};
axiosOptions.httpsAgent = new SocksProxyAgent(socksOptions);
}
const data: AxiosResponse = await axios.get(path, axiosOptions);
if (data.statusText === 'error' || !data.data) {
throw new Error(`${data.status}`);
}
return data.data;
}

View File

@@ -0,0 +1,322 @@
import { AccelerationInfo, makeBlockTemplate } from '../api/acceleration';
import { 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';
import blocks from '../api/blocks';
import accelerationApi, { Acceleration } from '../api/services/acceleration';
import accelerationCosts from '../api/acceleration';
import bitcoinApi from '../api/bitcoin/bitcoin-api-factory';
import transactionUtils from '../api/transaction-utils';
import { BlockExtended, MempoolTransactionExtended } from '../mempool.interfaces';
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 {
private bidBoostV2Activated = 831580;
public async $saveAcceleration(acceleration: AccelerationInfo, block: IEsploraApi.Block, pool_id: number): Promise<void> {
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
height = ?
`, [
acceleration.txSummary.txid,
block.timestamp,
block.height,
pool_id,
acceleration.txSummary.effectiveVsize,
acceleration.txSummary.effectiveFee,
acceleration.targetFeeRate,
acceleration.cost,
block.height,
]);
} 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<PublicAcceleration[]> {
if (!interval || !['24h', '3d', '1w', '1m'].includes(interval)) {
interval = '1m';
}
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[] = [];
let hasFilter = false;
if (interval && height === null) {
query += ` WHERE accelerations.added BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW() `;
hasFilter = true;
}
if (height != null) {
if (hasFilter) {
query += ` AND accelerations.height = ? `;
} else {
query += ` WHERE accelerations.height = ? `;
}
params.push(height);
} else if (poolSlug != null) {
if (hasFilter) {
query += ` AND pools.slug = ? `;
} else {
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;
}
}
public async $getAccelerationTotals(poolSlug: string | null = null, interval: string | null = null): Promise<{ cost: number, count: number }> {
interval = Common.getSqlInterval(interval);
if (!config.MEMPOOL_SERVICES.ACCELERATIONS) {
return { cost: 0, count: 0 };
}
let query = `
SELECT SUM(boost_cost) as total_cost, COUNT(txid) as count FROM accelerations
JOIN pools on pools.unique_id = accelerations.pool
`;
let params: any[] = [];
let hasFilter = false;
if (interval) {
query += ` WHERE accelerations.added BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW() `;
hasFilter = true;
}
if (poolSlug != null) {
if (hasFilter) {
query += ` AND pools.slug = ? `;
} else {
query += ` WHERE pools.slug = ? `;
}
params.push(poolSlug);
}
try {
const [rows] = await DB.query(query, params) as RowDataPacket[][];
return {
cost: rows[0]?.total_cost || 0,
count: rows[0]?.count || 0,
};
} catch (e) {
logger.err(`Cannot query acceleration totals. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
public async $getLastSyncedHeight(): Promise<number> {
try {
const [rows] = await DB.query(`
SELECT * FROM state
WHERE name = 'last_acceleration_block'
`);
if (rows?.['length']) {
return rows[0].number;
}
} catch (e: any) {
logger.err(`Cannot find last acceleration sync height. Reason: ` + (e instanceof Error ? e.message : e));
}
return 0;
}
private async $setLastSyncedHeight(height: number): Promise<void> {
try {
await DB.query(`
UPDATE state
SET number = ?
WHERE name = 'last_acceleration_block'
`, [height]);
} catch (e: any) {
logger.err(`Cannot update last acceleration sync height. Reason: ` + (e instanceof Error ? e.message : e));
}
}
public async $indexAccelerationsForBlock(block: BlockExtended, accelerations: Acceleration[], transactions: MempoolTransactionExtended[]): Promise<void> {
const blockTxs: { [txid: string]: MempoolTransactionExtended } = {};
for (const tx of transactions) {
blockTxs[tx.txid] = tx;
}
const successfulAccelerations = accelerations.filter(acc => acc.pools.includes(block.extras.pool.id));
let boostRate: number | null = null;
for (const acc of successfulAccelerations) {
if (boostRate === null) {
boostRate = accelerationCosts.calculateBoostRate(
accelerations.map(acc => ({ txid: acc.txid, max_bid: acc.feeDelta })),
transactions
);
}
if (blockTxs[acc.txid]) {
const tx = blockTxs[acc.txid];
const accelerationInfo = accelerationCosts.getAccelerationInfo(tx, boostRate, transactions);
accelerationInfo.cost = Math.max(0, Math.min(acc.feeDelta, accelerationInfo.cost));
this.$saveAcceleration(accelerationInfo, block, block.extras.pool.id);
}
}
const lastSyncedHeight = await this.$getLastSyncedHeight();
// if we've missed any blocks, let the indexer catch up from the last synced height on the next run
if (block.height === lastSyncedHeight + 1) {
await this.$setLastSyncedHeight(block.height);
}
}
/**
* [INDEXING] Backfill missing acceleration data
*/
async $indexPastAccelerations(): Promise<void> {
if (config.MEMPOOL.NETWORK !== 'mainnet' || !config.MEMPOOL_SERVICES.ACCELERATIONS) {
// acceleration history disabled
return;
}
const lastSyncedHeight = await this.$getLastSyncedHeight();
const currentHeight = blocks.getCurrentBlockHeight();
if (currentHeight <= lastSyncedHeight) {
// already in sync
return;
}
logger.debug(`Fetching accelerations between block ${lastSyncedHeight} and ${currentHeight}`);
// Fetch accelerations from mempool.space since the last synced block;
const accelerationsByBlock = {};
const blockHashes = {};
let done = false;
let page = 1;
let count = 0;
try {
while (!done) {
const accelerations = await accelerationApi.$fetchAccelerationHistory(page);
page++;
if (!accelerations?.length) {
done = true;
break;
}
for (const acc of accelerations) {
if (acc.status !== 'completed_provisional' && acc.status !== 'completed') {
continue;
}
if (!lastSyncedHeight || acc.blockHeight > lastSyncedHeight) {
if (!accelerationsByBlock[acc.blockHeight]) {
accelerationsByBlock[acc.blockHeight] = [];
blockHashes[acc.blockHeight] = acc.blockHash;
}
accelerationsByBlock[acc.blockHeight].push(acc);
count++;
} else {
done = true;
}
}
}
} catch (e) {
logger.err(`Failed to fetch full acceleration history. Reason: ` + (e instanceof Error ? e.message : e));
}
logger.debug(`Indexing ${count} accelerations between block ${lastSyncedHeight} and ${currentHeight}`);
// process accelerated blocks in order
const heights = Object.keys(accelerationsByBlock).map(key => parseInt(key)).sort((a,b) => a - b);
for (const height of heights) {
const accelerations = accelerationsByBlock[height];
try {
const block = await blocks.$getBlock(blockHashes[height]) as BlockExtended;
const transactions = (await bitcoinApi.$getTxsForBlock(blockHashes[height])).map(tx => transactionUtils.extendMempoolTransaction(tx));
const blockTxs = {};
for (const tx of transactions) {
blockTxs[tx.txid] = tx;
}
let boostRate = 0;
// use Bid Boost V2 if active
if (height > this.bidBoostV2Activated) {
boostRate = accelerationCosts.calculateBoostRate(
accelerations.map(acc => ({ txid: acc.txid, max_bid: acc.feeDelta })),
transactions
);
} else {
// default to Bid Boost V1 (median block fee rate)
const template = makeBlockTemplate(
transactions,
accelerations.map(acc => ({ txid: acc.txid, max_bid: acc.feeDelta })),
1,
Infinity,
Infinity
);
const feeStats = Common.calcEffectiveFeeStatistics(template);
boostRate = feeStats.medianFee;
}
for (const acc of accelerations) {
if (blockTxs[acc.txid]) {
const tx = blockTxs[acc.txid];
const accelerationInfo = accelerationCosts.getAccelerationInfo(tx, boostRate, transactions);
accelerationInfo.cost = Math.max(0, Math.min(acc.feeDelta, accelerationInfo.cost));
await this.$saveAcceleration(accelerationInfo, block, block.extras.pool.id);
}
}
await this.$setLastSyncedHeight(height);
} catch (e) {
logger.err(`Failed to process accelerations for block ${height}. Reason: ` + (e instanceof Error ? e.message : e));
return;
}
logger.debug(`Indexed ${accelerations.length} accelerations in block ${height}`);
}
await this.$setLastSyncedHeight(currentHeight);
logger.debug(`Indexing accelerations completed`);
}
}
export default new AccelerationRepository();

View File

@@ -6,20 +6,32 @@ import { BlockAudit, AuditScore } from '../mempool.interfaces';
class BlocksAuditRepositories {
public async $saveAudit(audit: BlockAudit): Promise<void> {
try {
await DB.query(`INSERT INTO blocks_audits(time, height, hash, missing_txs, added_txs, fresh_txs, match_rate)
VALUE (FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?)`, [audit.time, audit.height, audit.hash, JSON.stringify(audit.missingTxs),
JSON.stringify(audit.addedTxs), JSON.stringify(audit.freshTxs), audit.matchRate]);
await DB.query(`INSERT INTO blocks_audits(time, height, hash, missing_txs, added_txs, prioritized_txs, fresh_txs, sigop_txs, fullrbf_txs, accelerated_txs, match_rate, expected_fees, expected_weight)
VALUE (FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [audit.time, audit.height, audit.hash, JSON.stringify(audit.missingTxs),
JSON.stringify(audit.addedTxs), JSON.stringify(audit.prioritizedTxs), JSON.stringify(audit.freshTxs), JSON.stringify(audit.sigopTxs), JSON.stringify(audit.fullrbfTxs), JSON.stringify(audit.acceleratedTxs), audit.matchRate, audit.expectedFees, audit.expectedWeight]);
} catch (e: any) {
if (e.errno === 1062) { // ER_DUP_ENTRY - This scenario is possible upon node backend restart
logger.debug(`Cannot save block audit for block ${audit.hash} because it has already been indexed, ignoring`);
} else {
logger.err(`Cannot save block audit into db. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
}
public async $getBlockPredictionsHistory(div: number, interval: string | null): Promise<any> {
public async $setSummary(hash: string, expectedFees: number, expectedWeight: number) {
try {
await DB.query(`
UPDATE blocks_audits SET
expected_fees = ?,
expected_weight = ?
WHERE hash = ?
`, [expectedFees, expectedWeight, hash]);
} catch (e: any) {
logger.err(`Cannot update block audit in db. Reason: ` + (e instanceof Error ? e.message : e));
}
}
public async $getBlocksHealthHistory(div: number, interval: string | null): Promise<any> {
try {
let query = `SELECT UNIX_TIMESTAMP(time) as time, height, match_rate FROM blocks_audits`;
@@ -32,43 +44,52 @@ class BlocksAuditRepositories {
const [rows] = await DB.query(query);
return rows;
} catch (e: any) {
logger.err(`Cannot fetch block prediction history. Reason: ` + (e instanceof Error ? e.message : e));
logger.err(`Cannot fetch blocks health history. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
public async $getPredictionsCount(): Promise<number> {
public async $getBlocksHealthCount(): Promise<number> {
try {
const [rows] = await DB.query(`SELECT count(hash) as count FROM blocks_audits`);
return rows[0].count;
} catch (e: any) {
logger.err(`Cannot fetch block prediction history. Reason: ` + (e instanceof Error ? e.message : e));
logger.err(`Cannot fetch blocks health count. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
public async $getBlockAudit(hash: string): Promise<any> {
public async $getBlockAudit(hash: string): Promise<BlockAudit | null> {
try {
const [rows]: any[] = await DB.query(
`SELECT blocks.height, blocks.hash as id, UNIX_TIMESTAMP(blocks.blockTimestamp) as timestamp, blocks.size,
blocks.weight, blocks.tx_count,
transactions, template, missing_txs as missingTxs, added_txs as addedTxs, fresh_txs as freshTxs, match_rate as matchRate
`SELECT blocks_audits.height, blocks_audits.hash as id, UNIX_TIMESTAMP(blocks_audits.time) as timestamp,
template,
missing_txs as missingTxs,
added_txs as addedTxs,
prioritized_txs as prioritizedTxs,
fresh_txs as freshTxs,
sigop_txs as sigopTxs,
fullrbf_txs as fullrbfTxs,
accelerated_txs as acceleratedTxs,
match_rate as matchRate,
expected_fees as expectedFees,
expected_weight as expectedWeight
FROM blocks_audits
JOIN blocks ON blocks.hash = blocks_audits.hash
JOIN blocks_summaries ON blocks_summaries.id = blocks_audits.hash
WHERE blocks_audits.hash = "${hash}"
`);
JOIN blocks_templates ON blocks_templates.id = blocks_audits.hash
WHERE blocks_audits.hash = ?
`, [hash]);
if (rows.length) {
rows[0].missingTxs = JSON.parse(rows[0].missingTxs);
rows[0].addedTxs = JSON.parse(rows[0].addedTxs);
rows[0].prioritizedTxs = JSON.parse(rows[0].prioritizedTxs);
rows[0].freshTxs = JSON.parse(rows[0].freshTxs);
rows[0].transactions = JSON.parse(rows[0].transactions);
rows[0].sigopTxs = JSON.parse(rows[0].sigopTxs);
rows[0].fullrbfTxs = JSON.parse(rows[0].fullrbfTxs);
rows[0].acceleratedTxs = JSON.parse(rows[0].acceleratedTxs);
rows[0].template = JSON.parse(rows[0].template);
if (rows[0].transactions.length) {
return rows[0];
}
return rows[0];
}
return null;
} catch (e: any) {
@@ -80,10 +101,10 @@ class BlocksAuditRepositories {
public async $getBlockAuditScore(hash: string): Promise<AuditScore> {
try {
const [rows]: any[] = await DB.query(
`SELECT hash, match_rate as matchRate
`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));
@@ -94,7 +115,7 @@ class BlocksAuditRepositories {
public async $getBlockAuditScores(maxHeight: number, minHeight: number): Promise<AuditScore[]> {
try {
const [rows]: any[] = await DB.query(
`SELECT hash, match_rate as matchRate
`SELECT hash, match_rate as matchRate, expected_fees as expectedFees, expected_weight as expectedWeight
FROM blocks_audits
WHERE blocks_audits.height BETWEEN ? AND ?
`, [minHeight, maxHeight]);
@@ -104,6 +125,32 @@ class BlocksAuditRepositories {
throw e;
}
}
public async $getBlocksWithoutSummaries(): Promise<string[]> {
try {
const [fromRows]: any[] = await DB.query(`
SELECT height
FROM blocks_audits
WHERE expected_fees IS NULL
ORDER BY height DESC
LIMIT 1
`);
if (!fromRows?.length) {
return [];
}
const fromHeight = fromRows[0].height;
const [idRows]: any[] = await DB.query(`
SELECT hash
FROM blocks_audits
WHERE height <= ?
ORDER BY height DESC
`, [fromHeight]);
return idRows.map(row => row.hash);
} catch (e: any) {
logger.err(`Cannot fetch block audit from db. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
}
export default new BlocksAuditRepositories();

View File

@@ -1,10 +1,11 @@
import { BlockExtended, BlockExtension, BlockPrice } from '../mempool.interfaces';
import bitcoinApi from '../api/bitcoin/bitcoin-api-factory';
import { BlockExtended, BlockExtension, BlockPrice, EffectiveFeeStats } from '../mempool.interfaces';
import DB from '../database';
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';
@@ -12,6 +13,49 @@ import config from '../config';
import chainTips from '../api/chain-tips';
import blocks from '../api/blocks';
import BlocksAuditsRepository from './BlocksAuditsRepository';
import transactionUtils from '../api/transaction-utils';
interface DatabaseBlock {
id: string;
height: number;
version: number;
timestamp: number;
bits: number;
nonce: number;
difficulty: number;
merkle_root: string;
tx_count: number;
size: number;
weight: number;
previousblockhash: string;
mediantime: number;
totalFees: number;
medianFee: number;
feeRange: string;
reward: number;
poolId: number;
poolName: string;
poolSlug: string;
avgFee: number;
avgFeeRate: number;
coinbaseRaw: string;
coinbaseAddress: string;
coinbaseSignature: string;
coinbaseSignatureAscii: string;
avgTxSize: number;
totalInputs: number;
totalOutputs: number;
totalOutputAmt: number;
medianFeeAmt: number;
feePercentiles: string;
segwitTotalTxs: number;
segwitTotalSize: number;
segwitTotalWeight: number;
header: string;
utxoSetChange: number;
utxoSetSize: number;
totalInputAmt: number;
}
const BLOCK_DB_FIELDS = `
blocks.hash AS id,
@@ -52,7 +96,7 @@ const BLOCK_DB_FIELDS = `
blocks.header,
blocks.utxoset_change AS utxoSetChange,
blocks.utxoset_size AS utxoSetSize,
blocks.total_input_amt AS totalInputAmts
blocks.total_input_amt AS totalInputAmt
`;
class BlocksRepository {
@@ -171,6 +215,32 @@ class BlocksRepository {
}
}
/**
* Update missing fee amounts fields
*
* @param blockHash
* @param feeAmtPercentiles
* @param medianFeeAmt
*/
public async $updateFeeAmounts(blockHash: string, feeAmtPercentiles, medianFeeAmt) : Promise<void> {
try {
const query = `
UPDATE blocks
SET fee_percentiles = ?, median_fee_amt = ?
WHERE hash = ?
`;
const params: any[] = [
JSON.stringify(feeAmtPercentiles),
medianFeeAmt,
blockHash
];
await DB.query(query, params);
} catch (e: any) {
logger.err(`Cannot update fee amounts for block ${blockHash}. Reason: ' + ${e instanceof Error ? e.message : e}`);
throw e;
}
}
/**
* Get all block height that have not been indexed between [startHeight, endHeight]
*/
@@ -333,7 +403,7 @@ class BlocksRepository {
/**
* Get average block health for all blocks for a single pool
*/
public async $getAvgBlockHealthPerPoolId(poolId: number): Promise<number> {
public async $getAvgBlockHealthPerPoolId(poolId: number): Promise<number | null> {
const params: any[] = [];
const query = `
SELECT AVG(blocks_audits.match_rate) AS avg_match_rate
@@ -345,8 +415,8 @@ class BlocksRepository {
try {
const [rows] = await DB.query(query, params);
if (!rows[0] || !rows[0].avg_match_rate) {
return 0;
if (!rows[0] || rows[0].avg_match_rate == null) {
return null;
}
return Math.round(rows[0].avg_match_rate * 100) / 100;
} catch (e) {
@@ -408,7 +478,7 @@ class BlocksRepository {
public async $getBlocksByPool(slug: string, startHeight?: number): Promise<BlockExtended[]> {
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[] = [];
@@ -432,7 +502,7 @@ class BlocksRepository {
const blocks: BlockExtended[] = [];
for (const block of rows) {
blocks.push(await this.formatDbBlockIntoExtendedBlock(block));
blocks.push(await this.formatDbBlockIntoExtendedBlock(block as DatabaseBlock));
}
return blocks;
@@ -459,43 +529,19 @@ class BlocksRepository {
return null;
}
return await this.formatDbBlockIntoExtendedBlock(rows[0]);
return await this.formatDbBlockIntoExtendedBlock(rows[0] as DatabaseBlock);
} catch (e) {
logger.err(`Cannot get indexed block ${height}. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get one block by hash
*/
public async $getBlockByHash(hash: string): Promise<object | null> {
try {
const query = `
SELECT ${BLOCK_DB_FIELDS}
FROM blocks
JOIN pools ON blocks.pool_id = pools.id
WHERE hash = ?;
`;
const [rows]: any[] = await DB.query(query, [hash]);
if (rows.length <= 0) {
return null;
}
return await this.formatDbBlockIntoExtendedBlock(rows[0]);
} catch (e) {
logger.err(`Cannot get indexed block ${hash}. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Return blocks difficulty
*/
public async $getBlocksDifficulty(): Promise<object[]> {
try {
const [rows]: any[] = await DB.query(`SELECT UNIX_TIMESTAMP(blockTimestamp) as time, height, difficulty 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));
@@ -533,19 +579,6 @@ class BlocksRepository {
}
}
/**
* Return blocks height
*/
public async $getBlocksHeightsAndTimestamp(): Promise<object[]> {
try {
const [rows]: any[] = await DB.query(`SELECT height, blockTimestamp as timestamp FROM blocks`);
return rows;
} catch (e) {
logger.err('Cannot get blocks height and timestamp from the db. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get general block stats
*/
@@ -599,7 +632,6 @@ class BlocksRepository {
if (blocks[idx].previous_block_hash !== blocks[idx - 1].hash) {
logger.warn(`Chain divergence detected at block ${blocks[idx - 1].height}`);
await this.$deleteBlocksFrom(blocks[idx - 1].height);
await BlocksSummariesRepository.$deleteBlocksFrom(blocks[idx - 1].height);
await HashratesRepository.$deleteHashratesFromTimestamp(blocks[idx - 1].timestamp - 604800);
await DifficultyAdjustmentsRepository.$deleteAdjustementsFromHeight(blocks[idx - 1].height);
return false;
@@ -619,7 +651,7 @@ class BlocksRepository {
* Delete blocks from the database from blockHeight
*/
public async $deleteBlocksFrom(blockHeight: number) {
logger.info(`Delete newer blocks from height ${blockHeight} from the database`);
logger.info(`Delete newer blocks from height ${blockHeight} from the database`, logger.tags.mining);
try {
await DB.query(`DELETE FROM blocks where height >= ${blockHeight}`);
@@ -770,10 +802,10 @@ class BlocksRepository {
/**
* Get a list of blocks that have been indexed
*/
public async $getIndexedBlocks(): Promise<any[]> {
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;
@@ -783,7 +815,7 @@ class BlocksRepository {
/**
* Get a list of blocks that have not had CPFP data indexed
*/
public async $getCPFPUnindexedBlocks(): Promise<any[]> {
public async $getCPFPUnindexedBlocks(): Promise<number[]> {
try {
const blockchainInfo = await bitcoinClient.getBlockchainInfo();
const currentBlockHeight = blockchainInfo.blocks;
@@ -793,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; });
@@ -818,7 +850,7 @@ class BlocksRepository {
*/
public async $getOldestConsecutiveBlock(): Promise<any> {
try {
const [rows]: any = await DB.query(`SELECT height, UNIX_TIMESTAMP(blockTimestamp) as timestamp, difficulty FROM blocks ORDER BY height DESC`);
const [rows]: any = await DB.query(`SELECT height, UNIX_TIMESTAMP(blockTimestamp) as timestamp, difficulty, bits FROM blocks ORDER BY height DESC`);
for (let i = 0; i < rows.length - 1; ++i) {
if (rows[i].height - rows[i + 1].height > 1) {
return rows[i];
@@ -834,7 +866,7 @@ class BlocksRepository {
/**
* Get all blocks which have not be linked to a price yet
*/
public async $getBlocksWithoutPrice(): Promise<object[]> {
public async $getBlocksWithoutPrice(): Promise<object[]> {
try {
const [rows]: any[] = await DB.query(`
SELECT UNIX_TIMESTAMP(blocks.blockTimestamp) as timestamp, blocks.height
@@ -846,7 +878,7 @@ class BlocksRepository {
return rows;
} catch (e) {
logger.err('Cannot get blocks height and timestamp from the db. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
return [];
}
}
@@ -866,7 +898,6 @@ class BlocksRepository {
logger.debug(`Cannot save blocks prices for blocks [${blockPrices[0].height} to ${blockPrices[blockPrices.length - 1].height}] because it has already been indexed, ignoring`);
} else {
logger.err(`Cannot save blocks prices for blocks [${blockPrices[0].height} to ${blockPrices[blockPrices.length - 1].height}] into db. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
}
@@ -885,7 +916,7 @@ class BlocksRepository {
return blocks;
} catch (e) {
logger.err(`Cannot get blocks with missing coinstatsindex. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
return [];
}
}
@@ -908,13 +939,32 @@ class BlocksRepository {
}
}
/**
* Save indexed effective fee statistics
*
* @param id
* @param feeStats
*/
public async $saveEffectiveFeeStats(id: string, feeStats: EffectiveFeeStats): Promise<void> {
try {
await DB.query(`
UPDATE blocks SET median_fee = ?, fee_span = ?
WHERE hash = ?`,
[feeStats.medianFee, JSON.stringify(feeStats.feeRange), id]
);
} catch (e) {
logger.err(`Cannot update block fee stats. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Convert a mysql row block into a BlockExtended. Note that you
* must provide the correct field into dbBlk object param
*
* @param dbBlk
*/
private async formatDbBlockIntoExtendedBlock(dbBlk: any): Promise<BlockExtended> {
private async formatDbBlockIntoExtendedBlock(dbBlk: DatabaseBlock): Promise<BlockExtended> {
const blk: Partial<BlockExtended> = {};
const extras: Partial<BlockExtension> = {};
@@ -970,26 +1020,43 @@ class BlocksRepository {
// Match rate is not part of the blocks table, but it is part of APIs so we must include it
extras.matchRate = null;
extras.expectedFees = null;
extras.expectedWeight = null;
if (config.MEMPOOL.AUDIT) {
const auditScore = await BlocksAuditsRepository.$getBlockAuditScore(dbBlk.id);
if (auditScore != null) {
extras.matchRate = auditScore.matchRate;
extras.expectedFees = auditScore.expectedFees;
extras.expectedWeight = auditScore.expectedWeight;
}
}
// If we're missing block summary related field, check if we can populate them on the fly now
// This is for example triggered upon re-org
if (Common.blocksSummariesIndexingEnabled() &&
(extras.medianFeeAmt === null || extras.feePercentiles === null))
{
extras.feePercentiles = await BlocksSummariesRepository.$getFeePercentilesByBlockId(dbBlk.id);
if (extras.feePercentiles === null) {
const block = await bitcoinClient.getBlock(dbBlk.id, 2);
const summary = blocks.summarizeBlock(block);
await BlocksSummariesRepository.$saveSummary({ height: block.height, mined: summary });
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, summaryVersion);
extras.feePercentiles = await BlocksSummariesRepository.$getFeePercentilesByBlockId(dbBlk.id);
}
if (extras.feePercentiles !== null) {
extras.medianFeeAmt = extras.feePercentiles[3];
await this.$updateFeeAmounts(dbBlk.id, extras.feePercentiles, extras.medianFeeAmt);
}
}

View File

@@ -1,6 +1,7 @@
import { RowDataPacket } from 'mysql2';
import DB from '../database';
import logger from '../logger';
import { BlockSummary } from '../mempool.interfaces';
import { BlockSummary, TransactionClassified } from '../mempool.interfaces';
class BlocksSummariesRepository {
public async $getByBlockId(id: string): Promise<BlockSummary | undefined> {
@@ -17,49 +18,59 @@ class BlocksSummariesRepository {
return undefined;
}
public async $saveSummary(params: { height: number, mined?: BlockSummary}) {
const blockId = params.mined?.id;
public async $saveTransactions(blockHeight: number, blockId: string, transactions: TransactionClassified[], version: number): Promise<void> {
try {
const transactions = JSON.stringify(params.mined?.transactions || []);
const transactionsStr = JSON.stringify(transactions);
await DB.query(`
INSERT INTO blocks_summaries (height, id, transactions, template)
VALUE (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
transactions = ?
`, [params.height, blockId, transactions, '[]', transactions]);
INSERT INTO blocks_summaries
SET height = ?, transactions = ?, id = ?, version = ?
ON DUPLICATE KEY UPDATE transactions = ?, version = ?`,
[blockHeight, transactionsStr, blockId, version, transactionsStr, version]);
} catch (e: any) {
if (e.errno === 1062) { // ER_DUP_ENTRY - This scenario is possible upon node backend restart
logger.debug(`Cannot save block summary for ${blockId} because it has already been indexed, ignoring`);
} else {
logger.debug(`Cannot save block summary for ${blockId}. Reason: ${e instanceof Error ? e.message : e}`);
throw e;
}
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<void> {
const blockId = params.template?.id;
try {
const transactions = JSON.stringify(params.template?.transactions || []);
await DB.query(`
INSERT INTO blocks_summaries (height, id, transactions, template)
VALUE (?, ?, ?, ?)
INSERT INTO blocks_templates (id, template, version)
VALUE (?, ?, ?)
ON DUPLICATE KEY UPDATE
template = ?
`, [params.height, 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`);
} else {
logger.debug(`Cannot save block template for ${blockId}. Reason: ${e instanceof Error ? e.message : e}`);
throw e;
logger.warn(`Cannot save block template for ${blockId}. Reason: ${e instanceof Error ? e.message : e}`);
}
}
}
public async $getTemplate(id: string): Promise<BlockSummary | undefined> {
try {
const [templates]: any[] = await DB.query(`SELECT * from blocks_templates WHERE id = ?`, [id]);
if (templates.length > 0) {
return {
id: templates[0].id,
transactions: JSON.parse(templates[0].template),
version: templates[0].version,
};
}
} catch (e) {
logger.err(`Cannot get block template for block id ${id}. Reason: ` + (e instanceof Error ? e.message : e));
}
return undefined;
}
public async $getIndexedSummariesId(): Promise<string[]> {
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));
@@ -68,17 +79,39 @@ class BlocksSummariesRepository {
return [];
}
/**
* Delete blocks from the database from blockHeight
*/
public async $deleteBlocksFrom(blockHeight: number) {
logger.info(`Delete newer blocks summary from height ${blockHeight} from the database`);
public async $getSummariesWithVersion(version: number): Promise<{ height: number, id: string }[]> {
try {
await DB.query(`DELETE FROM blocks_summaries where height >= ${blockHeight}`);
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 delete indexed blocks summaries. Reason: ' + (e instanceof Error ? e.message : 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 [];
}
/**

View File

@@ -1,62 +1,19 @@
import cluster, { Cluster } from 'cluster';
import { RowDataPacket } from 'mysql2';
import DB from '../database';
import logger from '../logger';
import { Ancestor } from '../mempool.interfaces';
import { Ancestor, CpfpCluster } from '../mempool.interfaces';
import transactionRepository from '../repositories/TransactionRepository';
class CpfpRepository {
public async $saveCluster(clusterRoot: string, height: number, txs: Ancestor[], effectiveFeePerVsize: number): Promise<boolean> {
if (!txs[0]) {
return false;
}
// skip clusters of transactions with the same fees
const roundedEffectiveFee = Math.round(effectiveFeePerVsize * 100) / 100;
const equalFee = txs.reduce((acc, tx) => {
return (acc && Math.round(((tx.fee || 0) / (tx.weight / 4)) * 100) / 100 === roundedEffectiveFee);
}, true);
if (equalFee) {
return false;
}
public async $batchSaveClusters(clusters: { root: string, height: number, txs: Ancestor[], effectiveFeePerVsize: number }[]): Promise<boolean> {
try {
const packedTxs = Buffer.from(this.pack(txs));
await DB.query(
`
INSERT INTO compact_cpfp_clusters(root, height, txs, fee_rate)
VALUE (UNHEX(?), ?, ?, ?)
ON DUPLICATE KEY UPDATE
height = ?,
txs = ?,
fee_rate = ?
`,
[clusterRoot, height, packedTxs, effectiveFeePerVsize, height, packedTxs, effectiveFeePerVsize]
);
const maxChunk = 10;
let chunkIndex = 0;
while (chunkIndex < txs.length) {
const chunk = txs.slice(chunkIndex, chunkIndex + maxChunk).map(tx => {
return { txid: tx.txid, cluster: clusterRoot };
});
await transactionRepository.$batchSetCluster(chunk);
chunkIndex += maxChunk;
}
return true;
} catch (e: any) {
logger.err(`Cannot save cpfp cluster into db. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
public async $batchSaveClusters(clusters: { root: string, height: number, txs: any, effectiveFeePerVsize: number}[]): Promise<boolean> {
try {
const clusterValues: any[] = [];
const txs: any[] = [];
const clusterValues: [string, number, Buffer, number][] = [];
const txs: { txid: string, cluster: string }[] = [];
for (const cluster of clusters) {
if (cluster.txs?.length > 1) {
if (cluster.txs?.length) {
const roundedEffectiveFee = Math.round(cluster.effectiveFeePerVsize * 100) / 100;
const equalFee = cluster.txs.reduce((acc, tx) => {
const equalFee = cluster.txs.length > 1 && cluster.txs.reduce((acc, tx) => {
return (acc && Math.round(((tx.fee || 0) / (tx.weight / 4)) * 100) / 100 === roundedEffectiveFee);
}, true);
if (!equalFee) {
@@ -77,16 +34,10 @@ class CpfpRepository {
return false;
}
const queries: { query, params }[] = [];
const maxChunk = 100;
let chunkIndex = 0;
// insert transactions in batches of up to 100 rows
while (chunkIndex < txs.length) {
const chunk = txs.slice(chunkIndex, chunkIndex + maxChunk);
await transactionRepository.$batchSetCluster(chunk);
chunkIndex += maxChunk;
}
chunkIndex = 0;
// insert clusters in batches of up to 100 rows
while (chunkIndex < clusterValues.length) {
const chunk = clusterValues.slice(chunkIndex, chunkIndex + maxChunk);
@@ -98,12 +49,23 @@ class CpfpRepository {
return (' (UNHEX(?), ?, ?, ?)');
}) + ';';
const values = chunk.flat();
await DB.query(
queries.push({
query,
values
);
params: values,
});
chunkIndex += maxChunk;
}
chunkIndex = 0;
// insert transactions in batches of up to 100 rows
while (chunkIndex < txs.length) {
const chunk = txs.slice(chunkIndex, chunkIndex + maxChunk);
queries.push(transactionRepository.buildBatchSetQuery(chunk));
chunkIndex += maxChunk;
}
await DB.$atomicQuery(queries);
return true;
} catch (e: any) {
logger.err(`Cannot save cpfp clusters into db. Reason: ` + (e instanceof Error ? e.message : e));
@@ -111,7 +73,7 @@ class CpfpRepository {
}
}
public async $getCluster(clusterRoot: string): Promise<Cluster | void> {
public async $getCluster(clusterRoot: string): Promise<CpfpCluster | void> {
const [clusterRows]: any = await DB.query(
`
SELECT *
@@ -122,6 +84,7 @@ class CpfpRepository {
);
const cluster = clusterRows[0];
if (cluster?.txs) {
cluster.effectiveFeePerVsize = cluster.fee_rate;
cluster.txs = this.unpack(cluster.txs);
return cluster;
}

View File

@@ -139,7 +139,7 @@ class HashratesRepository {
public async $getPoolWeeklyHashrate(slug: string): Promise<any[]> {
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
@@ -220,7 +220,7 @@ class HashratesRepository {
* Delete hashrates from the database from timestamp
*/
public async $deleteHashratesFromTimestamp(timestamp: number) {
logger.info(`Delete newer hashrates from timestamp ${new Date(timestamp * 1000).toUTCString()} from the database`);
logger.info(`Delete newer hashrates from timestamp ${new Date(timestamp * 1000).toUTCString()} from the database`, logger.tags.mining);
try {
await DB.query(`DELETE FROM hashrates WHERE hashrate_timestamp >= FROM_UNIXTIME(?)`, [timestamp]);

Some files were not shown because too many files have changed in this diff Show More