Compare commits

..
160 Commits
Author SHA1 Message Date
Niko Storni 70c04cca47 fully upgrade phpcake 2018-12-03 18:09:10 -05:00
Niko Storni ed508182b5 fix more deprecations 2018-12-03 17:55:33 -05:00
Niko Storni 3d28c44fde fix deprecations
change default statusCode to 200
2018-12-03 17:52:22 -05:00
Niko Storni 6c61179546 add caching to api
update deprecated methods
swap qr library
2018-12-03 17:27:41 -05:00
Akinwale Ariwodola 3eab838967 composer package updates 2018-12-03 17:26:01 +00:00
Akinwale Ariwodola e8d3ead2c7 update home page style to accommodate new difficulty values 2018-12-03 18:23:59 +01:00
Akinwale Ariwodola 5983c61820 Merge pull request #46 from lbryio/hot-wallet
add additional hot wallet
2018-11-28 16:04:09 +01:00
marcdeb1 d98e9a3fb2 Improve search (#40)
* Added search page results
* Added getContentTag and getAutoThumbText to Claims model
* Order in search results
2018-11-28 16:03:41 +01:00
Thomas Zarebczan c7c1e7299f add additional hot wallet 2018-11-26 17:27:36 -05:00
Thomas Zarebczan 9246952c08 Merge pull request #38 from preserveddarnell/newcopyedits
Update various typos, punctuations & errors.
2018-11-12 11:42:46 -05:00
Thomas Zarebczan 59d23dc2a7 Update LICENSE 2018-11-12 11:42:30 -05:00
Akinwale Ariwodola c58676cd69 only get the claim link if the claim object is not null 2018-11-01 07:08:27 +01:00
preserveddarnell b9917c89da Update various typos, punctuations & errors. 2018-10-22 17:49:46 -04:00
marcdeb1 26a79d8340 Lbry addresses (#35)
* Added logo to indicate addresses owned by LBRY
2018-10-19 16:00:50 +01:00
marcdeb1 f903235c24 Added mining inflation chart to stats page (#34) 2018-10-19 13:22:50 +01:00
Akinwale Ariwodola d8734c1b8e Merge fix for PR 33 (#37)
* Added claim link to transaction
* Added 'View' link next to Claim label
2018-10-19 12:54:54 +01:00
marcdeb1 c13c06f74f Claim LBRY link and Thumbnail (#32)
* Claim LBRY link and Thumbnail
* Added getLink function to Model
* Changed getLink function name
2018-10-19 12:49:22 +01:00
Akinwale Ariwodola ad82fc3975 Merge pull request #36 from marcdeb1/db_column_name
Changed LatestTransactionTime column name
2018-10-18 12:20:46 +01:00
marcdeb1 4d0efbaff8 Changed LatestTransactionTime column name 2018-10-11 07:42:46 +02:00
Akinwale Ariwodola c8462afdee Update README.md with installation instructions (#30) 2018-08-09 21:30:21 +01:00
Akinwale Ariwodola a8a956f2bc update confirmations calculation on block list page 2018-07-26 12:22:51 +01:00
Akinwale Ariwodola b91b3681d3 tweak confirmation calculation 2018-07-26 12:14:48 +01:00
Akinwale Ariwodola 190d998e4c Merge branch 'master' of https://github.com/lbryio/block-explorer 2018-07-26 12:08:56 +01:00
Akinwale Ariwodola 667097f35d better confirmations calculation 2018-07-26 12:08:15 +01:00
Akinwale Ariwodola 8d552afe8f removed unused cron file 2018-07-26 10:30:13 +00:00
Akinwale Ariwodola ad4615cc5a forevermempool reset cron 2018-07-26 07:59:20 +01:00
Akinwale Ariwodola 3ad5db032b fix p2pk hash index 2018-07-26 07:27:12 +01:00
Akinwale Ariwodola e25cd7807e Merge pull request #26 from lbryio/diff
show diff on address page when tx spends back into the same wallet
2018-07-21 01:26:13 +01:00
Akinwale Ariwodola 71c7834521 move RPC URL value to configuration file 2018-07-21 00:18:24 +00:00
Akinwale Ariwodola 27ff22ff5a Updated mdanter/ecc version. Some cron file updates based on new environment. 2018-07-19 19:19:59 +00:00
Alex Grintsvayg 70032020f5 show diff on address page when tx spends back into the same wallet 2018-06-08 13:44:40 -04:00
Akinwale Ariwodola c8ca48220f display verified tags 2018-05-28 21:09:16 +01:00
Akinwale Ariwodola c2a19d91c1 remove address tagging 2018-05-23 00:46:55 +01:00
akinwale d3e542dd91 Merge pull request #22 from lbryio/imgsrc-fix
strip tags from claim thumbnail url
2018-04-09 16:49:50 +01:00
Akinwale Ariwodola 5d23294dba strip tags from claim thumbnail url 2018-04-09 11:48:55 -04:00
akinwale a0cbc324b7 Merge pull request #16 from Smurphonomics/master
Cleaner Easier to Read Block Explorer
2018-04-09 16:38:27 +01:00
Akinwale Ariwodola f66101a9de small reconnect fix for forevermempool 2018-03-14 22:51:55 +01:00
Alex Grin 537dd85473 Merge pull request #14 from lbrydocs/patch-1
create LICENSE file
2018-02-28 09:39:41 -05:00
Smurphonomics 0adcf92cbb Simple Grammar Corrections
Simple grammar corrections - Every little help :p
2018-02-22 16:45:19 +10:00
Smurphonomics ade487848d Cleaner Easier to Read Block Explorer
Made a few changes to separate links from titles, reduced some text sizes to be a more uniform, readable size and allow for more content within the page view. Fixed the button `border-radius` error.

This style (not present on the style-sheet) needs to be as changed...

From

`.claims-body .claim-metadata {padding: 24px 36px 88px 36px;}`

To

`.claims-body .claim-metadata {padding: 24px}`
2018-02-22 16:08:17 +10:00
LBRY Docs 7706338460 create LICENSE file 2018-02-05 12:58:49 -08:00
akinwale c60b3946ce Merge pull request #13 from lbryio/add-addresses
add aux addresses
2018-01-16 15:50:22 +01:00
Thomas Zarebczan 6bf194c448 Update MainController.php
bMvUBo1h5WS46ThHtmfmXftz3z33VHL7wc - holding 6M comm coins
bMgqQqYfwzWWYBk5o5dBMXtCndVAoeqy6h - holding 4M dev fund coins
2018-01-14 12:11:29 -05:00
akinwale 7cd3e5322c Merge pull request #12 from lbryio/add-address
add additional cold storage address
2017-12-28 08:07:32 +01:00
Thomas Zarebczan c82fd1a982 add additional cold storage address 2017-12-20 22:26:10 -05:00
Akinwale Ariwodola efcce65004 changed Google Analytics tracker ID 2017-12-01 10:20:15 +01:00
Akinwale Ariwodola df6264f388 fixed closing div tag in header 2017-11-28 22:29:48 +01:00
Akinwale Ariwodola a99606ecbf Added Google Analytics code 2017-11-28 21:27:37 +01:00
Akinwale Ariwodola f2bf172997 Merge branch 'master' of https://github.com/lbryio/block-explorer into explorer.lbry.io 2017-11-26 13:07:19 +01:00
Akinwale Ariwodola 5db80ac0d4 fixed position of download app link 2017-11-26 13:03:07 +01:00
Josh Finer fe14cd88f0 Update index.ctp 2017-11-25 17:03:01 -05:00
Thomas Zarebczan a855ee3d94 Add more addresses (#7)
* Add more addresses
2017-11-10 09:02:37 -06:00
Akinwale Ariwodola 24d9f2fb08 removed extra array definition in utxosupply 2017-10-13 05:40:43 +00:00
Thomas Zarebczan c509ce9585 add supply endpoint (#6)
* Total and circulating coin supply endpoint
2017-10-13 06:36:26 +01:00
Akinwale Ariwodola 58620a6298 updated transaction time css 2017-10-09 13:35:18 +01:00
Akinwale Ariwodola 409a0a7da7 fixed getTimestamp error 2017-10-09 13:35:09 +01:00
Akinwale Ariwodola 6e6dcd0613 added created time and block time to transction details page 2017-10-09 13:35:01 +01:00
Akinwale Ariwodola ba995ed51f fix code merge issues 2017-10-09 13:33:39 +01:00
Akinwale Ariwodola e7e444f84a some updates from the explorer.lbry.io branch 2017-10-09 13:30:57 +01:00
Akinwale Ariwodola 1d9dbb802b fix zero price on homepage 2017-10-09 13:29:55 +01:00
Akinwale Ariwodola 85926e316f price changed to display N/A when the value is $0.00 2017-10-09 13:29:43 +01:00
Akinwale Ariwodola 7f701f87d5 removed some unused code 2017-10-09 09:07:38 +01:00
Akinwale Ariwodola 06a495d396 Merge branch 'master' of https://gitlab.com/aureolin/lbryexplorer 2017-09-05 09:46:49 +01:00
Akinwale Ariwodola a19e3abd07 forevermempool fix 2017-09-05 09:46:31 +01:00
Akinwale Ariwodola 66940ac02a cron script modification for lbrycrd blocknotify 2017-08-27 13:50:03 +00:00
Akinwale Ariwodola d531487eb0 updated transaction time css 2017-08-26 14:33:47 +01:00
Akinwale Ariwodola 04f0f68fe4 fixed getTimestamp error 2017-08-26 14:31:44 +01:00
Akinwale Ariwodola 836b7e15b3 added created time and block time to transction details page 2017-08-26 14:27:57 +01:00
Akinwale Ariwodola 5acd8f6039 reduced number of blocksync threads to 2 2017-08-25 16:16:39 +01:00
Akinwale Ariwodola df2bb0c960 reduced number of blocksync threads to 2 2017-08-25 16:15:23 +01:00
Akinwale Ariwodola 04802c3c00 removed unnecessary alert 2017-08-16 17:59:13 +01:00
Akinwale Ariwodola 96fac56e70 lbry app and Coinomi transaction URL handling 2017-08-16 17:56:46 +01:00
Akinwale Ariwodola f85b9982e2 fix zero price on homepage 2017-08-14 21:02:12 +01:00
Akinwale Ariwodola 32c7118cf8 price changed to display N/A when the value is $0.00 2017-08-14 20:58:13 +01:00
Akinwale Ariwodola 6f5acdbc19 changes for explorer.lbry.io 2017-08-14 20:39:55 +01:00
Akinwale Ariwodola 31bddb6394 added address balance API endpoint 2017-08-08 11:44:28 +01:00
Akinwale Ariwodola f3454d78a2 fix claims publisher name display 2017-07-31 19:41:43 +01:00
Akinwale Ariwodola 5941c102b9 display address balance before received / sent 2017-07-07 01:26:16 +01:00
Akinwale Ariwodola 70291f6260 excluded genesis block address from rich list 2017-07-04 03:26:56 +01:00
Akinwale Ariwodola f54b8366a0 script hash address fix 2017-07-04 03:15:43 +01:00
Akinwale Ariwodola d5f5c383a9 added commas for debit and credit amounts on the address transactions list 2017-07-03 21:54:21 +01:00
Akinwale Ariwodola 4343ea91d5 changed top 500 rich list percentage precision to 5 decimal places 2017-07-03 21:50:36 +01:00
Akinwale Ariwodola abf84407cc added rich list and stats page 2017-07-03 21:47:30 +01:00
Akinwale Ariwodola 6c2e6727a8 added distinct selector for ClaimId when selecting claims to prevent duplicates (due to joins which should be fixed) from showing 2017-06-25 09:14:59 +01:00
Akinwale Ariwodola 7a84b50254 prevent claim transaction link on home page from opening the claim itself 2017-06-23 15:20:56 +01:00
Akinwale Ariwodola df36f5322f fixed word break for claim metadata description 2017-06-19 05:08:46 +01:00
Akinwale Ariwodola 981bd7d6a0 more ambiguous fixes 2017-06-19 01:33:37 +01:00
Akinwale Ariwodola 20a818c866 added IsFiltered flag to identify actual NSFW items that are not tagged NSFW. 2017-06-19 01:32:03 +01:00
Akinwale Ariwodola 12ec6e1df4 fix ambiguous nsfw condition 2017-06-19 00:43:48 +01:00
Akinwale Ariwodola a2e9b8142e added nsfw flag to claims retrieval api 2017-06-19 00:42:29 +01:00
Akinwale Ariwodola 65924fdb3c claims api retrieval tweaks 2017-06-19 00:26:57 +01:00
Akinwale Ariwodola 74932d02a2 claims retrieval api modifications 2017-06-18 20:28:31 +01:00
Akinwale Ariwodola 7853701a75 changed claims api limit from 24 to 48 2017-06-18 16:09:46 +01:00
Akinwale Ariwodola 3a92dbc0fc preliminary claims api implementation 2017-06-18 11:08:50 +01:00
Akinwale Ariwodola 2d59ca30f1 temporary fix for titles with multibyte characters in the claims explorer 2017-06-17 19:22:39 +01:00
Akinwale Ariwodola 8e7b1f42bd temporary workaround for duplicate claim id 2017-06-17 18:47:16 +01:00
Akinwale Ariwodola fa555e77be tweaks to block size formatting in block size chart. 2017-06-17 18:17:35 +01:00
Akinwale Ariwodola 5730ccc3c7 default period fix 2017-06-17 17:12:07 +01:00
Akinwale Ariwodola 37976f3082 implemented block size chart period saving to local storage to persist for page reloads 2017-06-17 17:08:07 +01:00
Akinwale Ariwodola 051bf6d8d9 fix grammar 2017-06-17 16:53:47 +01:00
Akinwale Ariwodola f70f41c787 added pagination to claims explorer 2017-06-17 16:51:00 +01:00
Akinwale Ariwodola 4557e395fe added chart export 2017-06-17 10:56:37 +01:00
Akinwale Ariwodola bfc5c40449 added flag to track chart loading progress and preevent double loading 2017-06-17 10:24:55 +01:00
Akinwale Ariwodola 0d791a6b43 price history cron 2017-06-17 09:21:07 +00:00
Akinwale Ariwodola e9beaedeec updated position of the block size chart links 2017-06-17 10:20:40 +01:00
Akinwale Ariwodola 9b57b50f9e block size chart grid tweaks 2017-06-17 10:16:35 +01:00
Akinwale Ariwodola 1492e00318 block size chart scrollbar and display tweaks 2017-06-17 09:52:35 +01:00
Akinwale Ariwodola edc857c352 changed to zero-prefixed day of month in table data 2017-06-17 09:41:16 +01:00
Akinwale Ariwodola ff85546e3f block size chart formatting fixes 2017-06-17 09:14:12 +01:00
Akinwale Ariwodola 56e576ba39 added blocks index and block size chart 2017-06-17 08:40:39 +01:00
Akinwale Ariwodola d4cb27dca7 added all query parameter for address transactions 2017-06-16 18:35:56 +01:00
Akinwale Ariwodola c9c7197b0e pagination result display fix 2017-06-16 18:28:35 +01:00
Akinwale Ariwodola e196308fa0 fix pagination bug 2017-06-16 18:26:11 +01:00
Akinwale Ariwodola 09924dc667 implemented pagination for address transactions 2017-06-16 18:23:26 +01:00
Akinwale Ariwodola be2a458db7 added price history handling and storage 2017-06-16 16:47:12 +01:00
Akinwale Ariwodola e2480c65f3 changed NSFW label on claims detail page 2017-06-16 09:53:18 +01:00
Akinwale Ariwodola b53b71ebfc ordering by fee then random to more claims by publisher 2017-06-16 09:40:08 +01:00
Akinwale Ariwodola c2ff1a5ccf added random ordering to more claims by publisher 2017-06-16 09:38:15 +01:00
Akinwale Ariwodola 71ad171fb9 fixed titles in claim explorer 2017-06-16 09:32:17 +01:00
Akinwale Ariwodola ce2df654de fixed image onerror event handler 2017-06-16 09:19:55 +01:00
Akinwale Ariwodola bbebcac60c yet more fixes 2017-06-16 09:12:54 +01:00
Akinwale Ariwodola 7b540c0196 more fixes 2017-06-16 09:10:47 +01:00
Akinwale Ariwodola 3d11a783d7 fixed failed claims interrupting output insertion 2017-06-16 09:03:17 +01:00
Akinwale Ariwodola 9b2a76b5c0 changed character casing for content type label 2017-06-16 08:46:50 +01:00
Akinwale Ariwodola a2f092ddac fixed number format for address transactions 2017-06-16 08:42:42 +01:00
Akinwale Ariwodola e5bb7e470d fixed claims price display for LBC currency 2017-06-16 08:33:18 +01:00
Akinwale Ariwodola 10f271ce67 lbry url regex update 2017-06-16 08:17:58 +01:00
Akinwale Ariwodola 5e6d6b468c added lbry link parsing to claims description 2017-06-16 08:02:22 +01:00
Akinwale Ariwodola a74b794aaf fixed claim grid item titles and added tooltips 2017-06-16 08:00:32 +01:00
Akinwale Ariwodola 46938aa305 fixed cost conversion error 2017-06-16 07:44:21 +01:00
Akinwale Ariwodola 33064c7b5c added recent claims links 2017-06-16 07:21:28 +01:00
Akinwale Ariwodola c169075ff6 fixed claim creation display time to match transaction time 2017-06-16 07:06:35 +01:00
Akinwale Ariwodola 8161830d81 added target=_blank to all license urls 2017-06-16 07:00:23 +01:00
Akinwale Ariwodola 8e68307c18 added rel=nofollow for parsed links in claim description 2017-06-16 06:55:29 +01:00
Akinwale Ariwodola 5cd9b3ec0a added price tags 2017-06-16 06:46:06 +01:00
Akinwale Ariwodola 6472a7ca49 added more claims to identity claim page 2017-06-16 05:48:35 +01:00
Akinwale Ariwodola 5f98c38c39 done 2017-06-16 00:25:55 +01:00
Akinwale Ariwodola 3a860e873c missing address fixes 2017-06-16 00:19:42 +01:00
Akinwale Ariwodola cfb03164e0 yet more fixes 2017-06-16 00:04:13 +01:00
Akinwale Ariwodola 385cac5608 more fixes 2017-06-16 00:01:44 +01:00
Akinwale Ariwodola 0760f3f340 fix zero outputs 2017-06-15 23:58:33 +01:00
Akinwale Ariwodola ffb068bf53 updated parsetxs cron to go back up to 10000 blocks 2017-06-15 23:37:30 +01:00
Akinwale Ariwodola e5d40c7b8c change failed claim from preventing tx save 2017-06-15 23:34:50 +01:00
Akinwale Ariwodola 78f51e89b4 claim explorer implementation 2017-06-15 23:18:47 +01:00
Akinwale Ariwodola 6018338b87 added identity tag for claim box 2017-06-15 19:19:41 +01:00
Akinwale Ariwodola 5db1855424 added extra claim null check 2017-06-15 19:17:07 +01:00
Akinwale Ariwodola 385c6c9438 added upper limit for claim index 2017-06-15 18:35:04 +01:00
Akinwale Ariwodola 48493b7b2f implemented claims index and recent claims 2017-06-15 18:22:56 +01:00
Akinwale Ariwodola 3f5c671c05 AmountHelper fix 2017-06-14 23:26:55 +01:00
Akinwale Ariwodola a0bd169924 fixed AmountHelper bug where values without decimal points don't get properly formatted 2017-06-14 23:24:54 +01:00
Akinwale Ariwodola 3d5cfac462 Changed exchange rate refresh interval to 15 minutes 2017-06-14 20:18:52 +01:00
Akinwale Ariwodola 361a5ff2db fixed network hash rate calculation 2017-06-14 01:59:06 +01:00
Akinwale Ariwodola 05538f1b70 style fixes for debit and credit amounts on address page 2017-06-14 00:58:00 +00:00
Akinwale Ariwodola 5558a38106 fixed combined debit and credit display for addresses 2017-06-13 23:39:40 +01:00
Akinwale Ariwodola 63a3dfaac0 added debit and credit display for transactions that have outputs returning to the same address 2017-06-13 23:37:31 +01:00
Akinwale Ariwodola dacac5b8e4 changed forever mempool resolution to 1 second and added redis tx hash caching to prevent db hits 2017-06-13 21:20:41 +01:00
Akinwale Ariwodola a7ef82fd69 Changed default value for thousandsSeparator 2017-06-13 20:07:29 +01:00
Akinwale Ariwodola e2a383a064 added thousandsSeparator parameter to the AmountHelper methods 2017-06-13 20:05:48 +01:00
Akinwale Ariwodola f48e9f8b46 Local sync commit 2017-06-13 19:54:56 +01:00
root 1ebcd999a6 Initial commit 2017-06-13 18:33:31 +00:00
172 changed files with 11525 additions and 7716 deletions

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.bat]
end_of_line = crlf
[*.yml]
indent_style = space
indent_size = 2
+42
View File
@@ -0,0 +1,42 @@
# Define the line ending behavior of the different file extensions
# Set default behaviour, in case users don't have core.autocrlf set.
* text=auto
* text eol=lf
# Explicitly declare text files we want to always be normalized and converted
# to native line endings on checkout.
*.php text
*.default text
*.ctp text
*.sql text
*.md text
*.po text
*.js text
*.css text
*.ini text
*.properties text
*.txt text
*.xml text
*.svg text
*.yml text
.htaccess text
# Declare files that will always have CRLF line endings on checkout.
*.bat eol=crlf
# Declare files that will always have LF line endings on checkout.
*.pem eol=lf
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
*.gif binary
*.ico binary
*.mo binary
*.pdf binary
*.phar binary
*.woff binary
*.woff2 binary
*.ttf binary
*.otf binary
*.eot binary
+7 -6
View File
@@ -1,6 +1,7 @@
/var/
/explorer
.env
*.cnf
__pycache__/
/dist/
/vendor/*
/config/app.php
/config/lbry.php
/logs/*
lbryexplorer.zip
lbryexplorer.komodoproject
.komodotools
+11
View File
@@ -0,0 +1,11 @@
# Uncomment the following to prevent the httpoxy vulnerability
# See: https://httpoxy.org/
#<IfModule mod_headers.c>
# RequestHeader unset Proxy
#</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>
+30
View File
@@ -0,0 +1,30 @@
language: php
dist: trusty
sudo: false
php:
- 5.6
- 7.0
- 7.1
matrix:
fast_finish: true
include:
- php: 7.0
env: PHPCS=1
before_script:
- if [[ $PHPCS = 1 ]]; then composer require cakephp/cakephp-codesniffer:~2.1; fi
- if [[ $PHPCS != 1 ]]; then composer install; fi
- if [[ $PHPCS != 1 ]]; then composer require phpunit/phpunit:"^5.7|^6.0"; fi
- if [[ $PHPCS != 1 ]]; then composer run-script post-install-cmd --no-interaction; fi
script:
- if [[ $PHPCS != 1 ]]; then vendor/bin/phpunit; fi
- if [[ $PHPCS = 1 ]]; then vendor/bin/phpcs -p --extensions=php --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests ./config ./webroot; fi
notifications:
email: false
-19
View File
@@ -1,19 +0,0 @@
.PHONY: test verify release
test:
go test ./...
go vet ./...
verify: test
go test -race ./...
release:
mkdir -p dist/release
set -e; for target in darwin/arm64 linux/amd64; do \
os=$${target%/*}; arch=$${target#*/}; \
name=$$os; if [ "$$os" = darwin ]; then name=mac; fi; \
CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -trimpath \
-o dist/release/explorer-$$name-$$arch ./cmd/explorer; \
done
cp LICENSE THIRD-PARTY.md dist/release/
cp -a licenses dist/release/
+80 -56
View File
@@ -1,67 +1,91 @@
> This is a Go rewrite of the LBRY block explorer. The previous PHP implementation is preserved on the [`php-version`](https://github.com/lbryio/block-explorer/tree/php-version) branch of this repository.
# LBRY Block Explorer
# LBRY explorer
A simple PHP block explorer for browsing transactions and claims on the [LBRY](https://lbry.io) blockchain. The explorer was developed using CakePHP which is a model-view-controller (MVC) PHP framework.
A read-only block explorer for the LBRY blockchain.
## Installation
There are some prerequisites that need to be installed before the explorer can be accessed.
* Web server - Apache, caddy or nginx
* [lbrycrd](https://github.com/lbryio/lbrycrd) with txindex turned on
* [Python claims decoder](https://github.com/cryptodevorg/lbry-decoder)
* MariaDB 10.2 or higher
* Redis Server (optional, only required for the CakePHP redis cache engine, or to run `forevermempool`)
* PHP 7.2 or higher
* php-fpm
* [igbinary extension](https://github.com/igbinary/igbinary)
* [phpredis extension](https://github.com/phpredis/phpredis)
* composer (PHP package manager)
## Build and run
Requires Go 1.23 or newer. From this directory:
```sh
make verify
make release
### Installation steps
* Clone the Github repository. `git clone https://github.com/lbryio/block-explorer`
* Create a MariaDB database using the DDL found in `block-explorer/sql/lbryexplorer.ddl.sql`
* Change the working directory to the cloned directory and run composer.
```
Release executables are written to `dist/release/`:
| Executable | Platform |
| --- | --- |
| `explorer-mac-arm64` | macOS, Apple Silicon |
| `explorer-linux-amd64` | Linux, x86-64 |
Set `EXPLORER_MYSQL_DSN` using a private environment file or your service manager,
then run the executable for your platform. For example, on an Apple Silicon Mac:
```sh
./dist/release/explorer-mac-arm64
cd block-explorer
composer update
```
* Create the directories, `tmp` and `logs` in the `block-explorer` folder if they have not been created yet, and make sure that they are writable by the web server.
* Copy `config/app.default.php` to `config/app.php`. Edit the database connection values to correspond to your environment.
* Copy `config/lbry.default.php` to `config/lbry.php`. Update the values for LBRY RPC URL and the Redis URL to correspond to your environment.
* Configure your web server with the host root folder set to `<path to>/block-explorer/webroot` where `<path to>` is the absolute path to the configuration. Here is a sample nginx configuration. You can make changes to this configuration to correspond to your environment.
```
server {
listen 80;
server_name my.explorer.com;
Open <http://127.0.0.1:8080>. For development, use `go run ./cmd/explorer`.
The application reads its configuration from the process environment; it does
not automatically load `.env` files.
root /var/www/block-explorer/webroot;
index index.php;
## Configuration
location / {
try_files $uri $uri/ /index.php?$args;
}
| Variable | Default | Purpose |
| --- | --- | --- |
| `EXPLORER_MYSQL_DSN` | required | MySQL driver DSN, such as `USER:PASSWORD@tcp(HOST:3306)/chainquery` |
| `EXPLORER_LISTEN` | `127.0.0.1:8080` | HTTP listener |
| `EXPLORER_CACHE_DIR` | `var/cache/go` | Writable disk-cache directory, relative to the working directory |
Use a SELECT-only database account. Queries run in read-only transactions with
UTC connections, a five-second connection timeout and a pool of at most four
connections. Chainquery manages database population independently.
Cached blocked-content and inflation responses expire after ten minutes; supply
responses expire after one hour. Cache files persist across restarts.
Tests use local HTTP mocks and checked-in regression fixtures; no database access
or external services are required for `make verify`.
## Caddy
Set `EXPLORER_LISTEN=127.0.0.1:8001` to use port 8001. A Caddy configuration for
that listener is:
```caddyfile
explorer.lbry.com {
reverse_proxy 127.0.0.1:8001
}
explorer.lbry.io {
redir https://explorer.lbry.com{uri} permanent
# pass the PHP scripts to FastCGI server listening on the php-fpm socket
location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_ignore_client_abort on;
fastcgi_param PHP_AUTH_USER $remote_user;
fastcgi_param PHP_AUTH_PW $http_authorization;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
```
* Restart your web server.
See [TODO.md](TODO.md) for known issues and [THIRD-PARTY.md](THIRD-PARTY.md) for notices.
### Cron jobs
There are a few scripts which can be set up as cron jobs or scheduled tasks.
#### blocks.sh
Detect new LBRY blocks. Can also be configured to be triggered using the lbrycrd `blocknotify` flag. This cron will create new blocks obtained from lbrycrd starting from the highest block number in the database, and then create the corresponding block transactions. If there are pending transactions created by the forevermempool script, they will be automatically associated with the respective blocks.
#### claimindex.sh
Create claims found on the LBRY blockchain in the database. This requires the Python decoder to be running in the background.
#### pricehistory.sh
Get the current LBC price in USD and store the value in the `PriceHistory` table. This also caches the most recent price in Redis.
#### forever.sh
Run the `forevermempool` script, and restart if necessary. The `forevermempool` script checks the LBRY blockchain mempool every second and creates transactions found in the database. The script makes use of Redis for caching the pending transaction IDs.
## Usage
Launch the URL for the configured web server root in a browser.
## Contributing
Contributions to this project are welcome, encouraged, and compensated. For more details, see https://lbry.io/faq/contributing
## License
This project is MIT licensed. For the full license, see [LICENSE](LICENSE).
## Security
We take security seriously. Please contact security@lbry.io regarding any security issues. Our PGP key is [here](https://keybase.io/lbry/key.asc) if you need it.
## Contact
The primary contact for this project is [@akinwale](https://github.com/akinwale) (akinwale@lbry.io)
-18
View File
@@ -1,18 +0,0 @@
# Third-party notices
Frontend assets retain their bundled notices and licenses under `webroot/`.
| Component | Version / purpose | License text |
| --- | --- | --- |
| [filippo.io/edwards25519](https://filippo.io/edwards25519) | v1.1.0 | [license](licenses/filippo.io_edwards25519.txt) |
| [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql) | v1.9.3 | [license](licenses/github.com_go-sql-driver_mysql.txt) |
| [github.com/makiuchi-d/gozxing](https://github.com/makiuchi-d/gozxing) | v0.1.1 | [license](licenses/github.com_makiuchi-d_gozxing.txt) |
| [golang.org/x/text](https://golang.org/x/text) | v0.3.7 | [license](licenses/golang.org_x_text.txt) |
| [golang.org/x/xerrors](https://golang.org/x/xerrors) | v0.0.0-20200804184101-5ec99f83aff1 | [license](licenses/golang.org_x_xerrors.txt) |
| Go standard library/runtime | Build toolchain | [BSD license](licenses/Go.txt) |
| CakePHP | Error-layout compatibility | [MIT license](licenses/CakePHP.txt) |
| BaconQrCode | QR capacity/mask compatibility | [BSD license](licenses/BaconQrCode.txt) |
| Endroid QR | QR matrix/layout reference | [MIT license](licenses/Endroid.txt) |
| PHP Group | `rounding.go` algorithm adapted from [PHP 8.5 math.c](https://github.com/php/php-src/blob/PHP-8.5/ext/standard/math.c) | [PHP License 3.01](licenses/PHP-3.01.txt) |
PHP Group copyright and license apply to the adapted rounding algorithm. Other project code retains the project license. Unmodified Go module sources are identified by `go.mod`/`go.sum` and available with `go mod download`.
-11
View File
@@ -1,11 +0,0 @@
# Known issues and follow-up work
API behavior changes require a compatibility decision before implementation.
- [ ] Measure opportunities for additional query caching, especially address-history totals and block-size aggregation.
- [ ] Define and implement a JSON contract for `/api/v1/address/:addr/transactions`, which currently returns homepage HTML with HTTP 200.
- [ ] Review unknown API-path handling. Unmatched paths, including retired tag URLs, return homepage HTML. Paid tagging is absent.
- [ ] Fix the transaction fragment-link handler, which checks `txhash.trim` instead of calling `txhash.trim()`. Cover supported Coinomi/LBRY fragment formats.
- [ ] Review unconfirmed address-history timestamps: a datetime returned by `IFNULL(transaction_time, created_at)` can be interpreted as a Unix timestamp and cause HTTP 500.
- [ ] Review tiny monetary `DOUBLE` values and scientific notation. Decimal operations can reject these values; any repair needs an explicit decimal-contract decision.
- [ ] Review empty-database blocks-list failures and the empty block link shown for `MEMPOOL` transactions.
Executable
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env sh
################################################################################
#
# Cake is a shell script for invoking CakePHP shell commands
#
# CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
# Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
#
# Licensed under The MIT License
# For full copyright and license information, please see the LICENSE.txt
# Redistributions of files must retain the above copyright notice.
#
# @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
# @link http://cakephp.org CakePHP(tm) Project
# @since 1.2.0
# @license http://www.opensource.org/licenses/mit-license.php MIT License
#
################################################################################
# Canonicalize by following every symlink of the given name recursively
canonicalize() {
NAME="$1"
if [ -f "$NAME" ]
then
DIR=$(dirname -- "$NAME")
NAME=$(cd -P "$DIR" > /dev/null && pwd -P)/$(basename -- "$NAME")
fi
while [ -h "$NAME" ]; do
DIR=$(dirname -- "$NAME")
SYM=$(readlink "$NAME")
NAME=$(cd "$DIR" > /dev/null && cd $(dirname -- "$SYM") > /dev/null && pwd)/$(basename -- "$SYM")
done
echo "$NAME"
}
CONSOLE=$(dirname -- "$(canonicalize "$0")")
APP=$(dirname "$CONSOLE")
if [ $(basename $0) != 'cake' ]
then
exec php "$CONSOLE"/cake.php $(basename $0) "$@"
else
exec php "$CONSOLE"/cake.php "$@"
fi
exit
+27
View File
@@ -0,0 +1,27 @@
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: Cake is a Windows batch script for invoking CakePHP shell commands
::
:: CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
:: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
::
:: Licensed under The MIT License
:: Redistributions of files must retain the above copyright notice.
::
:: @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
:: @link http://cakephp.org CakePHP(tm) Project
:: @since 2.0.0
:: @license http://www.opensource.org/licenses/mit-license.php MIT License
::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@echo off
SET app=%0
SET lib=%~dp0
php "%lib%cake.php" %*
echo.
exit /B %ERRORLEVEL%
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/php -q
<?php
/**
* Command-line code generation utility to automate programmer chores.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 2.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
$minVersion = '5.6.0';
if (file_exists('composer.json')) {
$composer = json_decode(file_get_contents('composer.json'));
if (isset($composer->require->php)) {
$minVersion = preg_replace('/([^0-9\.])/', '', $composer->require->php);
}
}
if (version_compare(phpversion(), $minVersion, '<')) {
fwrite(STDERR, sprintf("Minimum PHP version: %s. You are using: %s.\n", $minVersion, phpversion()));
exit(-1);
}
require dirname(__DIR__) . '/vendor/autoload.php';
include dirname(__DIR__) . '/config/bootstrap.php';
exit(Cake\Console\ShellDispatcher::run($argv));
-70
View File
@@ -1,70 +0,0 @@
package main
import (
"context"
"explorer/internal/explorer"
"log"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
dsn := os.Getenv("EXPLORER_MYSQL_DSN")
if dsn == "" {
log.Fatal("EXPLORER_MYSQL_DSN is required")
}
store, e := explorer.Open(dsn)
if e != nil {
log.Fatal("invalid MySQL configuration")
}
defer store.DB.Close()
addr := os.Getenv("EXPLORER_LISTEN")
if addr == "" {
addr = "127.0.0.1:8080"
}
cache := os.Getenv("EXPLORER_CACHE_DIR")
if cache == "" {
cache = "var/cache/go"
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
observed := explorer.ObservedStore{Store: store, Logger: logger, Stats: store.DB.Stats}
app := &explorer.Server{Store: observed, Logger: logger, Cache: explorer.Cache{Dir: cache}}
server := &http.Server{Addr: addr, Handler: explorer.AccessLog(app, logger), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
listener, e := net.Listen("tcp", addr)
if e != nil {
log.Fatal(e)
}
log.Printf("listening on %s", listener.Addr())
if e = runServer(ctx, server, listener); e != nil {
log.Fatal(e)
}
}
// Wait for Shutdown to drain active requests before returning from main.
func runServer(ctx context.Context, server *http.Server, listener net.Listener) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer listener.Close()
stopped := make(chan error, 1)
go func() {
<-ctx.Done()
shutdownCtx, stop := context.WithTimeout(context.Background(), 10*time.Second)
defer stop()
err := server.Shutdown(shutdownCtx)
if err != nil {
server.Close()
}
stopped <- err
}()
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
return err
}
return <-stopped
}
-62
View File
@@ -1,62 +0,0 @@
package main
import (
"context"
"io"
"net"
"net/http"
"testing"
"time"
)
func TestShutdownDrainsActiveRequest(t *testing.T) {
listener, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
entered, release := make(chan struct{}), make(chan struct{})
server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(entered); <-release; io.WriteString(w, "complete") })}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stopped := make(chan error, 1)
go func() { stopped <- runServer(ctx, server, listener) }()
result := make(chan string, 1)
go func() {
resp, e := http.Get("http://" + listener.Addr().String())
if e != nil {
result <- e.Error()
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
result <- string(body)
}()
select {
case <-entered:
case <-time.After(time.Second):
t.Fatal("request did not start")
}
cancel()
select {
case e := <-stopped:
t.Fatal("shutdown returned before request drained", e)
case <-time.After(30 * time.Millisecond):
}
close(release)
select {
case body := <-result:
if body != "complete" {
t.Fatal(body)
}
case <-time.After(time.Second):
t.Fatal("request did not finish")
}
select {
case e := <-stopped:
if e != nil {
t.Fatal(e)
}
case <-time.After(time.Second):
t.Fatal("shutdown did not finish")
}
}
+53
View File
@@ -0,0 +1,53 @@
{
"name": "cakephp/app",
"description": "CakePHP skeleton app",
"homepage": "http://cakephp.org",
"type": "project",
"license": "MIT",
"require": {
"php": ">=5.6",
"cakephp/cakephp": "^3.6",
"mobiledetect/mobiledetectlib": "2.*",
"cakephp/migrations": "~1.0",
"cakephp/plugin-installer": "~1.0",
"mdanter/ecc": "^0.5.0",
"nesbot/carbon": "~1.18",
"predis/predis": "^1.1.1",
"endroid/qr-code": "^3.5"
},
"require-dev": {
"psy/psysh": "@stable",
"cakephp/debug_kit": "~3.2",
"cakephp/bake": "~1.1"
},
"suggest": {
"markstory/asset_compress": "An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.",
"dereuromark/cakephp-ide-helper": "After baking your code, this keeps your annotations in sync with the code evolving from there on for maximum IDE and PHPStan compatibility.",
"phpunit/phpunit": "Allows automated tests to be run without system-wide install.",
"cakephp/cakephp-codesniffer": "Allows to check the code against the coding standards used in CakePHP."
},
"autoload": {
"psr-4": {
"App\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"App\\Test\\": "tests",
"Cake\\Test\\": "./vendor/cakephp/cakephp/tests"
}
},
"scripts": {
"post-install-cmd": "App\\Console\\Installer::postInstall",
"post-create-project-cmd": "App\\Console\\Installer::postInstall",
"post-autoload-dump": "Cake\\Composer\\Installer\\PluginInstaller::postAutoloadDump",
"check": [
"@test",
"@cs-check"
],
"cs-check": "phpcs --colors -p --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests",
"cs-fix": "phpcbf --colors --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests",
"test": "phpunit --colors=always"
},
"prefer-stable": true
}
Generated
+3349
View File
File diff suppressed because it is too large. Load diff
+348
View File
@@ -0,0 +1,348 @@
<?php
namespace App\config;
return [
/**
* Debug Level:
*
* Production Mode:
* false: No error messages, errors, or warnings shown.
*
* Development Mode:
* true: Errors and warnings shown.
*/
'debug' => filter_var(env('DEBUG', true), FILTER_VALIDATE_BOOLEAN),
/**
* Configure basic information about the application.
*
* - namespace - The namespace to find app classes under.
* - defaultLocale - The default locale for translation, formatting currencies and numbers, date and time.
* - encoding - The encoding used for HTML + database connections.
* - base - The base directory the app resides in. If false this
* will be auto detected.
* - dir - Name of app directory.
* - webroot - The webroot directory.
* - wwwRoot - The file path to webroot.
* - baseUrl - To configure CakePHP to *not* use mod_rewrite and to
* use CakePHP pretty URLs, remove these .htaccess
* files:
* /.htaccess
* /webroot/.htaccess
* And uncomment the baseUrl key below.
* - fullBaseUrl - A base URL to use for absolute links.
* - imageBaseUrl - Web path to the public images directory under webroot.
* - cssBaseUrl - Web path to the public css directory under webroot.
* - jsBaseUrl - Web path to the public js directory under webroot.
* - paths - Configure paths for non class based resources. Supports the
* `plugins`, `templates`, `locales` subkeys, which allow the definition of
* paths for plugins, view templates and locale files respectively.
*/
'App' => [
'namespace' => 'App',
'encoding' => env('APP_ENCODING', 'UTF-8'),
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
'base' => false,
'dir' => 'src',
'webroot' => 'webroot',
'wwwRoot' => WWW_ROOT,
// 'baseUrl' => env('SCRIPT_NAME'),
'fullBaseUrl' => false,
'imageBaseUrl' => 'img/',
'cssBaseUrl' => 'css/',
'jsBaseUrl' => 'js/',
'paths' => [
'plugins' => [ROOT . DS . 'plugins' . DS],
'templates' => [APP . 'Template' . DS],
'locales' => [APP . 'Locale' . DS],
],
],
/**
* Security and encryption configuration
*
* - salt - A random string used in security hashing methods.
* The salt value is also used as the encryption key.
* You should treat it as extremely sensitive data.
*/
'Security' => [
'salt' => env('SECURITY_SALT', '__SALT__'),
],
/**
* Apply timestamps with the last modified time to static assets (js, css, images).
* Will append a querystring parameter containing the time the file was modified.
* This is useful for busting browser caches.
*
* Set to true to apply timestamps when debug is true. Set to 'force' to always
* enable timestamping regardless of debug value.
*/
'Asset' => [
// 'timestamp' => true,
],
/**
* Configure the cache adapters.
*/
'Cache' => [
'default' => [
'className' => 'File',
'path' => CACHE,
'url' => env('CACHE_DEFAULT_URL', null),
],
/**
* Configure the cache used for general framework caching.
* Translation cache files are stored with this configuration.
* Duration will be set to '+2 minutes' in bootstrap.php when debug = true
* If you set 'className' => 'Null' core cache will be disabled.
*/
'_cake_core_' => [
'className' => 'File',
'prefix' => 'myapp_cake_core_',
'path' => CACHE . 'persistent/',
'serialize' => true,
'duration' => '+1 years',
'url' => env('CACHE_CAKECORE_URL', null),
],
/**
* Configure the cache for model and datasource caches. This cache
* configuration is used to store schema descriptions, and table listings
* in connections.
* Duration will be set to '+2 minutes' in bootstrap.php when debug = true
*/
'_cake_model_' => [
'className' => 'File',
'prefix' => 'myapp_cake_model_',
'path' => CACHE . 'models/',
'serialize' => true,
'duration' => '+1 years',
'url' => env('CACHE_CAKEMODEL_URL', null),
],
],
/**
* Configure the Error and Exception handlers used by your application.
*
* By default errors are displayed using Debugger, when debug is true and logged
* by Cake\Log\Log when debug is false.
*
* In CLI environments exceptions will be printed to stderr with a backtrace.
* In web environments an HTML page will be displayed for the exception.
* With debug true, framework errors like Missing Controller will be displayed.
* When debug is false, framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `errorLevel` - int - The level of errors you are interested in capturing.
* - `trace` - boolean - Whether or not backtraces should be included in
* logged errors/exceptions.
* - `log` - boolean - Whether or not you want exceptions logged.
* - `exceptionRenderer` - string - The class responsible for rendering
* uncaught exceptions. If you choose a custom class you should place
* the file for that class in src/Error. This class needs to implement a
* render method.
* - `skipLog` - array - List of exceptions to skip for logging. Exceptions that
* extend one of the listed exceptions will also be skipped for logging.
* E.g.:
* `'skipLog' => ['Cake\Network\Exception\NotFoundException', 'Cake\Network\Exception\UnauthorizedException']`
* - `extraFatalErrorMemory` - int - The number of megabytes to increase
* the memory limit by when a fatal error is encountered. This allows
* breathing room to complete logging or error handling.
*/
'Error' => [
'errorLevel' => E_ALL,
'exceptionRenderer' => 'Cake\Error\ExceptionRenderer',
'skipLog' => [],
'log' => true,
'trace' => true,
],
/**
* Email configuration.
*
* By defining transports separately from delivery profiles you can easily
* re-use transport configuration across multiple profiles.
*
* You can specify multiple configurations for production, development and
* testing.
*
* Each transport needs a `className`. Valid options are as follows:
*
* Mail - Send using PHP mail function
* Smtp - Send using SMTP
* Debug - Do not send the email, just return the result
*
* You can add custom transports (or override existing transports) by adding the
* appropriate file to src/Mailer/Transport. Transports should be named
* 'YourTransport.php', where 'Your' is the name of the transport.
*/
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
/**
* Email delivery profiles
*
* Delivery profiles allow you to predefine various properties about email
* messages from your application and give the settings a name. This saves
* duplication across your application and makes maintenance and development
* easier. Each profile accepts a number of keys. See `Cake\Mailer\Email`
* for more information.
*/
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'you@localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],
/**
* Connection information used by the ORM to connect
* to your application's datastores.
* Do not use periods in database name - it may lead to error.
* See https://github.com/cakephp/cakephp/issues/6471 for details.
* Drivers include Mysql Postgres Sqlite Sqlserver
* See vendor\cakephp\cakephp\src\Database\Driver for complete list
*/
'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
/**
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
//'port' => 'non_standard_port_number',
'username' => 'my_app',
'password' => 'secret',
'database' => 'my_app',
'encoding' => 'utf8',
'timezone' => 'UTC',
'flags' => [],
'cacheMetadata' => true,
'log' => false,
/**
* Set identifier quoting to true if you are using reserved words or
* special characters in your table or column names. Enabling this
* setting will result in queries built using the Query Builder having
* identifiers quoted when creating SQL. It should be noted that this
* decreases performance because each query needs to be traversed and
* manipulated before being executed.
*/
'quoteIdentifiers' => false,
/**
* During development, if using MySQL < 5.6, uncommenting the
* following line could boost the speed at which schema metadata is
* fetched from the database. It can also be set directly with the
* mysql configuration directive 'innodb_stats_on_metadata = 0'
* which is the recommended value in production environments
*/
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
'url' => env('DATABASE_URL', null),
],
/**
* The test connection is used during the test suite.
*/
'test' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'non_standard_port_number',
'username' => 'my_app',
'password' => 'secret',
'database' => 'test_myapp',
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
'url' => env('DATABASE_TEST_URL', null),
],
],
/**
* Configures logging options
*/
'Log' => [
'debug' => [
'className' => 'Cake\Log\Engine\FileLog',
'path' => LOGS,
'file' => 'debug',
'levels' => ['notice', 'info', 'debug'],
'url' => env('LOG_DEBUG_URL', null),
],
'error' => [
'className' => 'Cake\Log\Engine\FileLog',
'path' => LOGS,
'file' => 'error',
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
'url' => env('LOG_ERROR_URL', null),
],
],
/**
* Session configuration.
*
* Contains an array of settings to use for session configuration. The
* `defaults` key is used to define a default preset to use for sessions, any
* settings declared here will override the settings of the default config.
*
* ## Options
*
* - `cookie` - The name of the cookie to use. Defaults to 'CAKEPHP'.
* - `cookiePath` - The url path for which session cookie is set. Maps to the
* `session.cookie_path` php.ini config. Defaults to base path of app.
* - `timeout` - The time in minutes the session should be valid for.
* Pass 0 to disable checking timeout.
* Please note that php.ini's session.gc_maxlifetime must be equal to or greater
* than the largest Session['timeout'] in all served websites for it to have the
* desired effect.
* - `defaults` - The default configuration set to use as a basis for your session.
* There are four built-in options: php, cake, cache, database.
* - `handler` - Can be used to enable a custom session handler. Expects an
* array with at least the `engine` key, being the name of the Session engine
* class to use for managing the session. CakePHP bundles the `CacheSession`
* and `DatabaseSession` engines.
* - `ini` - An associative array of additional ini values to set.
*
* The built-in `defaults` options are:
*
* - 'php' - Uses settings defined in your php.ini.
* - 'cake' - Saves session files in CakePHP's /tmp directory.
* - 'database' - Uses CakePHP's database sessions.
* - 'cache' - Use the Cache class to save sessions.
*
* To define a custom session handler, save it at src/Network/Session/<name>.php.
* Make sure the class implements PHP's `SessionHandlerInterface` and set
* Session.handler to <name>
*
* To use database sessions, load the SQL file located at config/Schema/sessions.sql
*/
'Session' => [
'defaults' => 'php',
],
];
+200
View File
@@ -0,0 +1,200 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 0.10.8
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
// You can remove this if you are confident that your PHP version is sufficient.
if (version_compare(PHP_VERSION, '5.6.0') < 0) {
trigger_error('Your PHP version must be equal or higher than 5.6.0 to}
/*
* You can remove this if you are confident you have intl installed.
*/
if (!extension_loaded('intl')) {
trigger_error('You must enable the intl extension to}
/*
* You can remove this if you are confident you have mbstring installed.
*/
if (!extension_loaded('mbstring')) {
trigger_error('You must enable the mbstring extension to}
/*
* Configure paths required to find CakePHP + general filepath
* constants
*/
require __DIR__ . '/paths.php';
/*
* Bootstrap CakePHP.
*
* Does the various bits of setup that CakePHP needs to do.
* This includes:
*
* - Registering the CakePHP autoloader.
* - Setting the default application paths.
*/
require CORE_PATH . 'config' . DS . 'bootstrap.php';
/*
* Read configuration file and inject configuration into various
* CakePHP classes.
*
* By default there is only one configuration file. It is often a good
* idea to create multiple configuration files, and separate the configuration
* that changes from configuration that does not. This makes deployment simpler.
*/
try {
Configure::config('default', new PhpConfig());
Configure::load('app', 'default', false);
} catch (\Exception $e) {
exit($e->getMessage() . "\n");
}
/*
* Load an environment local configuration file.
* You can use a file like app_local.php to provide local overrides to your
* shared configuration.
*/
//Configure::load('app_local', 'default');
/*
* When debug = true the metadata cache should only last
* for a short time.
*/
if (Configure::read('debug')) {
Configure::write('Cache._cake_model_.duration', '+2 minutes');
Configure::write('Cache._cake_core_.duration', '+2 minutes');
}
/*
* Set server timezone to UTC. You can change it to another timezone of your
* choice but using UTC makes time calculations / conversions easier.
*/
date_default_timezone_set('UTC');
/*
* Configure the mbstring extension to use the correct encoding.
*/
mb_internal_encoding(Configure::read('App.encoding'));
/*
* Set the default locale. This controls how dates, number and currency is
* formatted and sets the default language to use for translations.
*/
ini_set('intl.default_locale', Configure::read('App.defaultLocale'));
/*
* Register application error and exception handlers.
*/
$isCli = PHP_SAPI === 'cli';
if ($isCli) {
(new ConsoleErrorHandler(Configure::read('Error')))->register();
} else {
(new ErrorHandler(Configure::read('Error')))->register();
}
/*
* Include the CLI bootstrap overrides.
*/
if ($isCli) {
require __DIR__ . '/bootstrap_cli.php';
}
/*
* Set the full base URL.
* This URL is used as the base of all absolute links.
*
* If you define fullBaseUrl in your config file you can remove this.
*/
if (!Configure::read('App.fullBaseUrl')) {
$s = null;
if (env('HTTPS')) {
$s = 's';
}
$httpHost = env('HTTP_HOST');
if (isset($httpHost)) {
Configure::write('App.fullBaseUrl', 'http' . $s . '://' . $httpHost);
}
unset($httpHost, $s);
}
Cache::setConfig(Configure::consume('Cache'));
ConnectionManager::setConfig(Configure::consume('Datasources'));
Email::setConfigTransport(Configure::consume('EmailTransport'));
Email::setConfig(Configure::consume('Email'));
Log::setConfig(Configure::consume('Log'));
Security::setSalt(Configure::consume('Security.salt'));
/*
* The default crypto extension in 3.0 is OpenSSL.
* If you are migrating from 2.x uncomment this code to
* use a more compatible Mcrypt based implementation
*/
//Security::engine(new \Cake\Utility\Crypto\Mcrypt());
/*
* Setup detectors for mobile and tablet.
*/
Request::addDetector('mobile', function ($request) {
$detector = new \Detection\MobileDetect();
return $detector->isMobile();
});
Request::addDetector('tablet', function ($request) {
$detector = new \Detection\MobileDetect();
return $detector->isTablet();
});
/*
* Enable immutable time objects in the ORM.
*
* You can enable default locale format parsing by adding calls
* to `useLocaleParser()`. This enables the automatic conversion of
* locale specific date formats. For details see
* @link http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#parsing-localized-datetime-data
*/
Type::build('time')
->useImmutable();
Type::build('date')
->useImmutable();
Type::build('datetime')
->useImmutable();
Type::build('timestamp')
->useImmutable();
/*
* Custom Inflector rules, can be set to correctly pluralize or singularize
* table, model, controller names or whatever other string is passed to the
* inflection functions.
*/
//Inflector::rules('plural', ['/^(inflect)or$/i' => '\1ables']);
//Inflector::rules('irregular', ['red' => 'redlings']);
//Inflector::rules('uninflected', ['dontinflectme']);
//Inflector::rules('transliteration', ['/å/' => 'aa']);
/*
* Plugins need to be loaded manually, you can either load them one by one or all of them in a single call
* Uncomment one of the lines below, as you need. make sure you read the documentation on Plugin to use more
* advanced ways of loading plugins
*
* Plugin::loadAll(); // Loads all plugins at once
* Plugin::load('Migrations'); //Loads a single plugin named Migrations
*
*/
Configure::load('lbry');
+40
View File
@@ -0,0 +1,40 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace App\config;
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Core\Plugin;
/**
* Additional bootstrapping and configuration for CLI environments should
* be put here.
*/
// Set the fullBaseUrl to allow URLs to be generated in shell tasks.
// This is useful when sending email from shells.
//Configure::write('App.fullBaseUrl', php_uname('n'));
// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');
try {
Plugin::load('Bake');
} catch (MissingPluginException $e) {
// Do not halt if the plugin is missing
}
Plugin::load('Migrations');
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\config;
return [
'Lbry' => [
'RpcUrl' => 'http://user:password@127.0.0.1:9245',
],
'Redis' => [
'Url' => 'tcp://127.0.0.1:6379',
]
];
+87
View File
@@ -0,0 +1,87 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace App\config;
/**
* Use the DS to separate the directories in other defines
*/
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
/**
* These defines should only be edited if you have cake installed in
* a directory layout other than the way it is distributed.
* When using custom settings be sure to use the DS and do not add a trailing DS.
*/
/**
* The full path to the directory which holds "src", WITHOUT a trailing DS.
*/
define('ROOT', dirname(__DIR__));
/**
* The actual directory name for the application directory. Normally
* named 'src'.
*/
define('APP_DIR', 'src');
/**
* Path to the application's directory.
*/
define('APP', ROOT . DS . APP_DIR . DS);
/**
* Path to the config directory.
*/
define('CONFIG', ROOT . DS . 'config' . DS);
/**
* File path to the webroot directory.
*/
define('WWW_ROOT', ROOT . DS . 'webroot' . DS);
/**
* Path to the tests directory.
*/
define('TESTS', ROOT . DS . 'tests' . DS);
/**
* Path to the temporary files directory.
*/
define('TMP', ROOT . DS . 'tmp' . DS);
/**
* Path to the logs directory.
*/
define('LOGS', ROOT . DS . 'logs' . DS);
/**
* Path to the cache files directory. It can be shared between hosts in a multi-server setup.
*/
define('CACHE', TMP . 'cache' . DS);
/**
* The absolute path to the "cake" directory, WITHOUT a trailing DS.
*
* CakePHP should always be installed with composer, so look there.
*/
define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp');
/**
* Path to the cake directory.
*/
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
define('CAKE', CORE_PATH . 'src' . DS);
+39
View File
@@ -0,0 +1,39 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.5.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
/*
* You can empty out this file, if you are certain that you match all requirements.
*/
/*
* You can remove this if you are confident that your PHP version is sufficient.
*/
if (version_compare(PHP_VERSION, '5.6.0') < 0) {
trigger_error('Your PHP version must be equal or higher than 5.6.0 to use CakePHP.' . PHP_EOL, E_USER_ERROR);
}
/*
* You can remove this if you are confident you have intl installed.
*/
if (!extension_loaded('intl')) {
trigger_error('You must enable the intl extension to use CakePHP.' . PHP_EOL, E_USER_ERROR);
}
/*
* You can remove this if you are confident you have mbstring installed.
*/
if (!extension_loaded('mbstring')) {
trigger_error('You must enable the mbstring extension to use CakePHP.' . PHP_EOL, E_USER_ERROR);
}
+70
View File
@@ -0,0 +1,70 @@
<?php
/**
* Routes configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different URLs to chosen controllers and their actions (functions).
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* The default class to use for all routes
*
* The following route classes are supplied with CakePHP and are appropriate
* to set as the default:
*
* - Route
* - InflectedRoute
* - DashedRoute
*
* If no call is made to `Router::defaultRouteClass()`, the class used is
* `Route` (`Cake\Routing\Route\Route`)
*
* Note that `Route` does not do any inflections on URLs which will result in
* inconsistently cased URLs when used with `:plugin`, `:controller` and
* `:action` markers.
*
*/
Router::defaultRouteClass(DashedRoute::class);
Router::scope('/', function (RouteBuilder $routes) {
$routes->connect('/', ['controller' => 'Main', 'action' => 'index']);
$routes->connect('/address/*', ['controller' => 'Main', 'action' => 'address']);
$routes->connect('/blocks/*', ['controller' => 'Main', 'action' => 'blocks']);
$routes->connect('/claims/*', ['controller' => 'Main', 'action' => 'claims']);
$routes->connect('/find', ['controller' => 'Main', 'action' => 'find']);
$routes->connect('/realtime', ['controller' => 'Main', 'action' => 'realtime']);
$routes->connect('/stats', ['controller' => 'Main', 'action' => 'stats']);
$routes->connect('/tx/*', ['controller' => 'Main', 'action' => 'tx']);
$routes->connect('/qr/*', ['controller' => 'Main', 'action' => 'qr']);
$routes->connect('/*', ['controller' => 'Main', 'action' => 'index']);
$routes->connect('/api/v1/address/:addr/tag', ['controller' => 'Main', 'action' => 'apiaddrtag'], ['addr' => '[A-Za-z0-9,]+', 'pass' => ['addr']]);
$routes->connect('/api/v1/address/:addr/utxo', ['controller' => 'Main', 'action' => 'apiaddrutxo'], ['addr' => '[A-Za-z0-9,]+', 'pass' => ['addr']]);
$routes->connect('/api/v1/address/:addr/balance', ['controller' => 'Main', 'action' => 'apiaddrbalance'], ['addr' => '[A-Za-z0-9]+', 'pass' => ['addr']]);
$routes->connect('/api/v1/address/:addr/transactions', ['controller' => 'Main', 'action' => 'apiaddrtx'], ['addr' => '[A-Za-z0-9,]+', 'pass' => ['addr']]);
$routes->connect('/api/v1/charts/blocksize/:period', ['controller' => 'Main', 'action' => 'apiblocksize'], ['period' => '[012346789dhy]+', 'pass' => ['period']]);
$routes->connect('/api/v1/realtime/blocks', ['controller' => 'Main', 'action' => 'apirealtimeblocks']);
$routes->connect('/api/v1/realtime/tx', ['controller' => 'Main', 'action' => 'apirealtimetx']);
$routes->connect('/api/v1/recentblocks', ['controller' => 'Main', 'action' => 'apirecentblocks']);
$routes->connect('/api/v1/status', ['controller' => 'Main', 'action' => 'apistatus']);
$routes->connect('/api/v1/supply', ['controller' => 'Main', 'action' => 'apiutxosupply']);
//$routes->connect('/api/v1/recenttxs', ['controller' => 'Main', 'action' => 'apirecenttxs']);
$routes->connect('/api/v1/claims/browse', ['controller' => 'Claims', 'action' => 'apibrowse']);
//$routes->fallbacks(DashedRoute::class);
});
+18
View File
@@ -0,0 +1,18 @@
# Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
#
# Licensed under The MIT License
# For full copyright and license information, please see the LICENSE.txt
# Redistributions of files must retain the above copyright notice.
# MIT License (http://www.opensource.org/licenses/mit-license.php)
CREATE TABLE i18n (
id int NOT NULL auto_increment,
locale varchar(6) NOT NULL,
model varchar(255) NOT NULL,
foreign_key int(10) NOT NULL,
field varchar(255) NOT NULL,
content text,
PRIMARY KEY (id),
UNIQUE INDEX I18N_LOCALE_FIELD(locale, model, foreign_key, field),
INDEX I18N_FIELD(model, foreign_key, field)
);
+13
View File
@@ -0,0 +1,13 @@
# Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
#
# Licensed under The MIT License
# For full copyright and license information, please see the LICENSE.txt
# Redistributions of files must retain the above copyright notice.
# MIT License (http://www.opensource.org/licenses/mit-license.php)
CREATE TABLE sessions (
id char(40) NOT NULL,
data text,
expires INT(11) NOT NULL,
PRIMARY KEY (id)
);
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake block addrtxamounts
Executable
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake block parsenewblocks
rm tmp/lock/parsenewblocks 2>/dev/null
bin/cake block parsetxs
rm tmp/lock/parsetxs 2>/dev/null
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake block parsetxs
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake block buildclaimindex
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake block fixzerooutputs
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
pkill -f forevermempool
rm -f /home/lbry/explorer.lbry.io/tmp/lock/forevermempool 2>/dev/null
cd /home/lbry/explorer.lbry.io
bin/cake block forevermempool &
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake block parsemempool
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake aux pricehistory
Executable
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake block updatespends
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
cd /home/lbry/explorer.lbry.io
bin/cake aux verifytags
-3
View File
@@ -1,3 +0,0 @@
# Keep the real file outside the checkout, owned by root and mode 0600.
# Use an existing SELECT-only account. Never put actual credentials here.
EXPLORER_MYSQL_DSN=explorer_reader:REPLACE_ME@tcp(DB_HOST:3306)/chainquery
-28
View File
@@ -1,28 +0,0 @@
[Unit]
Description=LBRY explorer Go frontend
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=explorer
Group=explorer
WorkingDirectory=/opt/lbry-explorer/current
EnvironmentFile=/etc/lbry-explorer/explorer.env
Environment=EXPLORER_LISTEN=127.0.0.1:8080
Environment=EXPLORER_CACHE_DIR=/var/cache/lbry-explorer/go
ExecStart=/opt/lbry-explorer/current/explorer
Restart=on-failure
RestartSec=3
TimeoutStopSec=15
CacheDirectory=lbry-explorer/go
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
-11
View File
@@ -1,11 +0,0 @@
# Include in the explorer.lbry.com server block.
# Keep its TLS, intended cache headers and error handling.
# Proxy assets as well as pages: Go releases need no disk webroot.
# Adjust/remove any older static-file locations that take precedence over this.
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 300s;
}
-14
View File
@@ -1,14 +0,0 @@
module explorer
go 1.23
require (
github.com/go-sql-driver/mysql v1.9.3
github.com/makiuchi-d/gozxing v0.1.1
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
)
-10
View File
@@ -1,10 +0,0 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/makiuchi-d/gozxing v0.1.1 h1:xxqijhoedi+/lZlhINteGbywIrewVdVv2wl9r5O9S1I=
github.com/makiuchi-d/gozxing v0.1.1/go.mod h1:eRIHbOjX7QWxLIDJoQuMLhuXg9LAuw6znsUtRkNw9DU=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
require 'webroot' . DIRECTORY_SEPARATOR . 'index.php';
-124
View File
@@ -1,124 +0,0 @@
package explorer
import (
"html/template"
"math/big"
"net/http"
"net/url"
"regexp"
"strings"
)
var unixDigits = regexp.MustCompile(`^[+-]?[0-9]+$`)
func safeURL(v any) template.URL {
s := phpTrim(text(v))
u, e := url.Parse(s)
if e != nil {
return template.URL("#")
}
switch strings.ToLower(u.Scheme) {
case "", "http", "https", "ftp", "lbry", "mailto":
return template.URL(s)
}
return template.URL("#")
}
func (s *Server) addressPage(w http.ResponseWriter, r *http.Request) {
addr := firstArgument(r, "/address")
if addr == "" || addr == "0" {
redirect(w, r, "/", 302)
return
}
query := func(q string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), q, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
rows, ok := query("SELECT * FROM address WHERE address = ? LIMIT 1", addr)
if !ok {
return
}
data := pageData{Title: "Address " + addr, Address: Row{"address": addr}, NumPages: 1, PageLimit: 50, CurrentPage: queryInt(r, "page")}
if len(rows) == 0 {
if len(addr) != 34 {
redirect(w, r, "/", 302)
return
}
} else {
data.Address = rows[0]
tas, ok := query("SELECT * FROM transaction_address WHERE address_id = ?", data.Address["id"])
if !ok {
return
}
data.NumRecords = len(tas)
offset := 0
if queryString(r, "all") == "true" {
data.PageLimit = len(tas)
data.CurrentPage = 1
data.NumPages = 1
} else {
data.CurrentPage, data.NumPages, data.Pagination = paginate(len(tas), 50, data.CurrentPage)
offset = (data.CurrentPage - 1) * 50
}
data.RecentTxs, ok = query("SELECT T.id,T.hash,T.input_count,T.output_count,T.block_hash_id,TA.debit_amount,TA.credit_amount,B.height,B.confirmations,IFNULL(T.transaction_time,T.created_at) AS transaction_time FROM transaction T LEFT JOIN block B ON T.block_hash_id = B.hash RIGHT JOIN (SELECT transaction_id,debit_amount,credit_amount FROM transaction_address WHERE address_id = ?) TA ON TA.transaction_id = T.id ORDER BY transaction_time DESC LIMIT ?, ?", data.Address["id"], offset, data.PageLimit)
if !ok {
return
}
for _, tx := range data.RecentTxs {
if !unixDigits.MatchString(text(tx["transaction_time"])) {
internalError(w)
return
}
}
for _, ta := range tas {
data.TotalReceived += number(ta["credit_amount"])
data.TotalSent += number(ta["debit_amount"])
}
data.BalanceAmount = data.TotalReceived - data.TotalSent
}
data.Begin = (data.CurrentPage-1)*data.PageLimit + 1
data.End = min(data.NumRecords, data.Begin+data.PageLimit-1)
s.render(w, r, "address", data)
}
var ownedAddresses = map[string]bool{"rEqocTgdPdoD8NEbrECTUPfpquJ4zPVCJ8": true, "rKaAUDxr24hHNNTQuNtRvNt8SGYJMdLXo3": true, "r7hj61jdbGXcsccxw8UmEFCReZoCWLRr7t": true, "bRo4FEeqqxY7nWFANsZsuKEWByEgkvz8Qt": true, "bU2XUzckfpdEuQNemKvhPT1gexQ3GG3SC2": true, "bay3VA6YTQBL4WLobbG7CthmoGeUKXuXkD": true, "bLPbiXBp6Vr3NSnsHzDsLNzoy5o36re9Cz": true, "bVUrbCK8hcZ5XWti7b9eNxKEBxzc1rr393": true, "bZja2VyhAC84a9hMwT8dwTU6rDRXowrjxH": true, "bMgqQqYfwzWWYBk5o5dBMXtCndVAoeqy6h": true, "bMvUBo1h5WS46ThHtmfmXftz3z33VHL7wc": true, "bX6napXtY2nVTBRc8PwULBuGWn2i3SCtrN": true, "bG1fEEqDVepDy3AbvM8outQ3FQUu76aDot": true}
const inflationChartVersion = 1785112059
func (s *Server) statsPage(w http.ResponseWriter, r *http.Request) {
rows, e := s.Store.Query(r.Context(), "SELECT * FROM address WHERE address <> ? ORDER BY balance DESC LIMIT 500", "bHW58d37s1hBjj3wPBkn5zpCX3F8ZW3uWf")
if e != nil {
internalError(w)
return
}
total := new(big.Rat)
maxBalance := new(big.Rat)
for _, item := range rows {
if item["first_seen"] == nil {
internalError(w)
return
}
if !validBCString(phpString(item["balance"])) {
internalError(w)
return
}
balance := decimal(phpString(item["balance"]))
total = decimal(truncated(new(big.Rat).Add(total, balance), 8))
if balance.Cmp(maxBalance) > 0 {
maxBalance = balance
}
}
if len(rows) > 0 && (total.Sign() == 0 || maxBalance.Sign() == 0) {
internalError(w)
return
}
for _, item := range rows {
balance := decimal(phpString(item["balance"]))
item["Top500Percent"] = number(truncated(new(big.Rat).Quo(balance, total), 8)) * 100
item["MinMaxPercent"] = number(truncated(new(big.Rat).Quo(balance, maxBalance), 8)) * 100
}
s.render(w, r, "stats", pageData{Title: "Stats & Rich List", RichList: rows, InflationChartVersion: inflationChartVersion})
}
-275
View File
@@ -1,275 +0,0 @@
package explorer
import (
"encoding/json"
"fmt"
"math/big"
"math/rand/v2"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
func placeholders(n int) string { return strings.TrimSuffix(strings.Repeat("?,", n), ",") }
var bcNumber = regexp.MustCompile(`^(?:[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+))?$`)
func validBCString(s string) bool { return bcNumber.MatchString(s) }
func decimal(v any) *big.Rat {
r := new(big.Rat)
if _, ok := r.SetString(text(v)); !ok {
return new(big.Rat)
}
return r
}
func truncated(r *big.Rat, places int) string {
scale := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(places)), nil)
n := new(big.Int).Mul(r.Num(), scale)
n.Quo(n, r.Denom())
sign := ""
if n.Sign() < 0 {
sign = "-"
n.Abs(n)
}
s := n.String()
if places == 0 {
return sign + s
}
for len(s) <= places {
s = "0" + s
}
return sign + s[:len(s)-places] + "." + s[len(s)-places:]
}
func phpString(v any) string {
if v == nil {
return "0"
}
if f, ok := v.(float64); ok {
s := strconv.FormatFloat(f, 'G', 14, 64)
if i := strings.IndexByte(s, 'E'); i >= 0 {
mantissa := s[:i]
if !strings.Contains(mantissa, ".") {
mantissa += ".0"
}
exp, _ := strconv.Atoi(s[i+1:])
s = mantissa + fmt.Sprintf("E%+d", exp)
}
return s
}
return text(v)
}
func (s *Server) remainingAPI(w http.ResponseWriter, r *http.Request) bool {
path := r.URL.Path
q := func(sql string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), sql, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
if path == "/api/v1/charts/inflation" {
if r.Method != "GET" {
jsonError(w, 400, "Invalid HTTP request method.")
return true
}
if b, ok := s.cachedArray("inflation_chart"); ok {
sendJSON(w, 200, struct {
Success bool `json:"success"`
Data json.RawMessage `json:"data"`
}{true, b})
return true
}
highest, ok := q("SELECT height FROM block WHERE confirmations > 0 ORDER BY height DESC LIMIT 1")
if !ok {
return true
}
if len(highest) == 0 {
clientError(w, r, 404, "Not Found")
return true
}
h := int(number(highest[0]["height"]))
args := []any{}
for i := 0; i <= h; i += 1000 {
args = append(args, i)
}
if h%1000 != 0 {
args = append(args, h)
}
samples, ok := q("SELECT height,block_time FROM block WHERE height IN ("+placeholders(len(args))+") AND confirmations > 0 ORDER BY height ASC", args...)
if !ok {
return true
}
recent, ok := q("SELECT height,block_time FROM block WHERE confirmations > 0 ORDER BY height DESC LIMIT 101")
if !ok {
return true
}
for a, b := 0, len(recent)-1; a < b; a, b = a+1, b-1 {
recent[a], recent[b] = recent[b], recent[a]
}
data := struct {
Samples []Row `json:"samples"`
Recent []Row `json:"recent"`
Last int `json:"last_reward_block"`
Interval int `json:"future_sample_interval"`
}{orderedRows(samples, "height", "block_time"), orderedRows(recent, "height", "block_time"), 4071017, 1000}
b, e := phpJSON(data)
if e == nil {
s.Cache.Put("inflation_chart", b, 10*time.Minute)
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
Data any `json:"data"`
}{true, data})
return true
}
if path == "/api/v1/supply" {
if b, ok := s.cachedArray("utxo_supply"); ok {
sendJSON(w, 200, struct {
Success bool `json:"success"`
Supply json.RawMessage `json:"utxosupply"`
}{true, b})
return true
}
total, ok := q("SELECT SUM(balance) AS balance FROM address")
if !ok {
return true
}
addresses := []any{"rEqocTgdPdoD8NEbrECTUPfpquJ4zPVCJ8", "r7hj61jdbGXcsccxw8UmEFCReZoCWLRr7t", "rKaAUDxr24hHNNTQuNtRvNt8SGYJMdLXo3", "bRo4FEeqqxY7nWFANsZsuKEWByEgkvz8Qt", "bU2XUzckfpdEuQNemKvhPT1gexQ3GG3SC2", "bay3VA6YTQBL4WLobbG7CthmoGeUKXuXkD", "bLPbiXBp6Vr3NSnsHzDsLNzoy5o36re9Cz", "bMvUBo1h5WS46ThHtmfmXftz3z33VHL7wc", "bVUrbCK8hcZ5XWti7b9eNxKEBxzc1rr393", "bZja2VyhAC84a9hMwT8dwTU6rDRXowrjxH", "bCrboXVztuSbZzVToCWSsu1pEr2oxKHu9v", "bMgqQqYfwzWWYBk5o5dBMXtCndVAoeqy6h", "bX6napXtY2nVTBRc8PwULBuGWn2i3SCtrN"}
reserved, ok := q("SELECT SUM(balance) AS balance FROM address WHERE address IN ("+placeholders(len(addresses))+")", addresses...)
if !ok {
return true
}
t, rv := "0", "0"
if len(total) > 0 {
t = phpString(total[0]["balance"])
}
if len(reserved) > 0 {
rv = phpString(reserved[0]["balance"])
}
if !validBCString(t) || !validBCString(rv) {
internalError(w)
return true
}
data := struct {
Total string `json:"total"`
Circulating string `json:"circulating"`
}{t, truncated(new(big.Rat).Sub(decimal(t), decimal(rv)), 8)}
b, e := phpJSON(data)
if e == nil {
s.Cache.Put("utxo_supply", b, time.Hour)
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
Supply any `json:"utxosupply"`
}{true, data})
return true
}
if strings.HasPrefix(path, "/api/v1/address/") && strings.HasSuffix(path, "/utxo") {
addr := strings.TrimSuffix(strings.TrimPrefix(path, "/api/v1/address/"), "/utxo")
if addr == "" || strings.Contains(addr, "/") {
return false
}
parts := strings.Split(addr, ",")
args := make([]any, len(parts))
for i, p := range parts {
args[i] = p
}
addresses, ok := q("SELECT id,address FROM address WHERE address IN ("+placeholders(len(args))+")", args...)
if !ok {
return true
}
if len(addresses) == 0 {
jsonError(w, 404, "No base58 address matching the specified parameter was found.")
return true
}
args = nil
conditions := []string{}
for _, a := range addresses {
args = append(args, a["id"])
conditions = append(conditions, "JSON_CONTAINS(O.address_list, JSON_QUOTE(?))")
}
for _, a := range addresses {
args = append(args, a["address"])
}
rows, ok := q("SELECT T.hash AS transaction_hash,O.vout,O.value,O.address_list,O.script_pub_key_asm,O.script_pub_key_hex,O.type,O.required_signatures,B.confirmations FROM transaction T JOIN output O ON O.transaction_id = T.id JOIN block B ON B.hash = T.block_hash_id WHERE O.transaction_id IN (SELECT TA.transaction_id FROM transaction_address TA WHERE TA.address_id IN ("+placeholders(len(addresses))+")) AND ("+strings.Join(conditions, " OR ")+") AND O.is_spent <> 1 ORDER BY T.transaction_time ASC", args...)
if !ok {
return true
}
out := make([]Row, 0, len(rows))
for _, row := range rows {
if !validBCString(phpString(row["value"])) {
internalError(w)
return true
}
var list any
json.Unmarshal([]byte(text(row["address_list"])), &list)
atomic := new(big.Rat).Mul(decimal(phpString(row["value"])), big.NewRat(100000000, 1))
value, _ := strconv.ParseInt(truncated(atomic, 0), 10, 64)
out = append(out, Row{"transaction_hash": row["transaction_hash"], "output_index": row["vout"], "value": value, "addresses": list, "script": row["script_pub_key_asm"], "script_hex": row["script_pub_key_hex"], "script_type": row["type"], "required_signatures": int(number(row["required_signatures"])), "spent": false, "confirmations": int(number(row["confirmations"]))})
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
UTXO []Row `json:"utxo"`
}{true, orderedRows(out, "transaction_hash", "output_index", "value", "addresses", "script", "script_hex", "script_type", "required_signatures", "spent", "confirmations")})
return true
}
if path == "/api/v1/claims/browse" {
before, after := max(0, queryInt(r, "before")), queryInt(r, "after")
sort := phpTrim(queryString(r, "sort"))
order := "DESC"
var randomStart int
if sort == "oldest" || sort == "random" {
order = "ASC"
}
if sort == "random" {
last, ok := q("SELECT id FROM claim ORDER BY id DESC LIMIT 1")
if !ok {
return true
}
if len(last) > 0 {
maxID := int(number(last[0]["id"]))
if maxID > 0 {
randomStart = rand.IntN(maxID) + 1
if s.RandomInt != nil {
randomStart = s.RandomInt(maxID) + 1
}
}
}
}
where := "Claims.thumbnail_url IS NOT NULL AND Claims.thumbnail_url != '' AND Claims.is_filtered != 1"
args := []any{}
if after > 0 {
where += " AND Claims.id > ?"
args = append(args, after)
order = "ASC"
} else if before > 0 {
where += " AND Claims.id < ?"
args = append(args, before)
order = "DESC"
} else if randomStart > 0 {
where += " AND Claims.id >= ?"
args = append(args, randomStart)
}
if phpTrim(queryString(r, "nsfw")) != "true" {
where += " AND Claims.is_nsfw != 1"
}
rows, ok := q(fmt.Sprintf("SELECT Claims.*,Publisher.name AS publisher FROM claim Claims LEFT JOIN claim Publisher ON Publisher.claim_id = Claims.publisher_id WHERE %s ORDER BY Claims.id %s LIMIT 48", where, order), args...)
if !ok {
return true
}
if rows == nil {
rows = []Row{}
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
Claims []Row `json:"claims"`
Total int `json:"total"`
}{true, claimEntities(rows), 23000000})
return true
}
return false
}
-187
View File
@@ -1,187 +0,0 @@
package explorer
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type scriptedStore struct {
sets [][]Row
queries []string
args [][]any
}
func (f *scriptedStore) Query(_ context.Context, q string, a ...any) ([]Row, error) {
f.queries = append(f.queries, q)
f.args = append(f.args, a)
if len(f.sets) == 0 {
return []Row{}, nil
}
rows := f.sets[0]
f.sets = f.sets[1:]
return rows, nil
}
func TestInflationSamplingAndCache(t *testing.T) {
f := &scriptedStore{sets: [][]Row{{{"height": int64(2501)}}, {{"height": 0, "block_time": 1}, {"height": 2000, "block_time": 2}, {"height": 2501, "block_time": 3}}, {{"height": 2501, "block_time": 3}, {"height": 2500, "block_time": 2}}}}
s := Server{Store: f, Cache: Cache{Dir: t.TempDir()}}
var bodies []string
for i := 0; i < 2; i++ {
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/charts/inflation", nil))
if w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
bodies = append(bodies, w.Body.String())
}
if bodies[0] != bodies[1] {
t.Fatal("cache changed bytes")
}
if len(f.queries) != 3 {
t.Fatal(f.queries)
}
if len(f.args[1]) != 4 || f.args[1][3] != 2501 {
t.Fatal(f.args)
}
var result struct {
Data struct {
Recent []Row
Last int `json:"last_reward_block"`
}
}
if e := json.Unmarshal([]byte(bodies[0]), &result); e != nil {
t.Fatal(e)
}
if number(result.Data.Recent[0]["height"]) != 2500 || result.Data.Last != 4071017 {
t.Fatal(bodies[0])
}
}
func TestClaimsCursorPrecedence(t *testing.T) {
for _, query := range []string{"after=4&before=9&sort=oldest", "before=-2&sort=popular&nsfw=True", "before=7&sort=oldest&nsfw=true"} {
f := &scriptedStore{}
s := Server{Store: f}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/claims/browse?"+query, nil))
if w.Body.String() != `{"success":true,"claims":[],"total":23000000}` {
t.Fatal(w.Body.String())
}
q := f.queries[0]
switch {
case strings.Contains(query, "after="):
if !strings.Contains(q, "Claims.id > ?") || !strings.Contains(q, "ORDER BY Claims.id ASC") {
t.Fatal(q)
}
case strings.Contains(query, "before=-"):
if strings.Contains(q, "Claims.id <") {
t.Fatal(q)
}
default:
if !strings.Contains(q, "Claims.id < ?") || !strings.Contains(q, "ORDER BY Claims.id DESC") {
t.Fatal(q)
}
}
if strings.HasSuffix(query, "nsfw=true") && strings.Contains(q, "is_nsfw !=") {
t.Fatal(q)
}
}
}
func TestUTXOAtomicAndShape(t *testing.T) {
f := &scriptedStore{sets: [][]Row{{{"id": int64(2), "address": "addr"}}, {{"transaction_hash": "tx", "vout": int64(1), "value": 1.23456789, "address_list": "[\"addr\"]", "script_pub_key_asm": "op /", "script_pub_key_hex": "01", "type": "pubkeyhash", "required_signatures": int64(1), "confirmations": int64(7)}}}}
s := Server{Store: f}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/address/addr,unknown/utxo", nil))
want := `{"success":true,"utxo":[{"transaction_hash":"tx","output_index":1,"value":123456789,"addresses":["addr"],"script":"op \/","script_hex":"01","script_type":"pubkeyhash","required_signatures":1,"spent":false,"confirmations":7}]}`
if w.Body.String() != want {
t.Fatal(w.Body.String())
}
if !strings.Contains(f.queries[1], "JSON_CONTAINS(O.address_list, JSON_QUOTE(?))") || len(f.args[1]) != 2 {
t.Fatal(f.queries, f.args)
}
}
func TestSupplyDecimalAndCache(t *testing.T) {
f := &scriptedStore{sets: [][]Row{{{"balance": 10.12345678}}, {{"balance": 1.00000001}}}}
s := Server{Store: f, Cache: Cache{Dir: t.TempDir()}}
for i := 0; i < 2; i++ {
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/supply", nil))
if w.Body.String() != `{"success":true,"utxosupply":{"total":"10.12345678","circulating":"9.12345677"}}` {
t.Fatal(w.Body.String())
}
}
if len(f.queries) != 2 {
t.Fatal(f.queries)
}
if len(f.args[1]) != 13 {
t.Fatal(f.args)
}
}
type roundTrip func(*http.Request) (*http.Response, error)
func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestBlockedListRequestCachingAndPublisher(t *testing.T) {
calls := 0
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if r.URL.String() != blockedListURL || r.Method != "GET" {
t.Fatal(r.Method, r.URL.String())
}
return &http.Response{StatusCode: 503, Body: http.NoBody, Header: http.Header{}}, nil
})}
now := time.Unix(1, 0)
s := Server{Cache: Cache{Dir: t.TempDir(), Now: func() time.Time { return now }}, HTTPClient: client}
s.blocked(context.Background())
s.blocked(context.Background())
if calls != 1 {
t.Fatal("non-2xx response not cached", calls)
}
now = now.Add(10 * time.Minute)
client.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"data":[{"claim_id":"publisher"}]}`)), Header: http.Header{}}, nil
})
list := s.blocked(context.Background())
rows := []Row{{"claim_id": "claim", "publisher_id": "publisher", "thumbnail_url": "https://image"}}
markBlocked(rows, list)
if !truth(rows[0]["isBlocked"]) || rows[0]["thumbnail_url"] != nil {
t.Fatal(rows)
}
}
func TestPrimitiveAPICacheEntriesAreMisses(t *testing.T) {
for _, key := range []string{"inflation_chart", "utxo_supply"} {
for _, body := range []string{`null`, `false`, `"wrong type"`} {
c := Cache{Dir: t.TempDir()}
if e := c.Put(key, []byte(body), time.Hour); e != nil {
t.Fatal(e)
}
s := Server{Cache: c}
if _, hit := s.cachedArray(key); hit {
t.Fatalf("primitive cache body accepted: %s %s", key, body)
}
}
}
c := Cache{Dir: t.TempDir()}
c.Put("inflation_chart", []byte(`[]`), time.Hour)
s := Server{Cache: c}
if _, hit := s.cachedArray("inflation_chart"); !hit {
t.Fatal("empty array is a valid legacy cache hit")
}
}
func TestNullBlockedCacheEntryIsMiss(t *testing.T) {
calls := 0
s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"data":[]}`))}, nil
})}}
s.Cache.Put("list_blocked", []byte(`null`), time.Hour)
s.blocked(context.Background())
if calls != 1 {
t.Fatal("null blocked-list cache must fetch")
}
}
-79
View File
@@ -1,79 +0,0 @@
package explorer
import (
"bytes"
"explorer/webroot"
"io/fs"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestBundledAssetsEmbedded(t *testing.T) {
reference := filepath.Join("..", "..", "webroot")
count := 0
e := filepath.WalkDir(reference, func(path string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
if d.IsDir() {
return nil
}
name, _ := filepath.Rel(reference, path)
if name == "embed.go" {
return nil
}
want, e := os.ReadFile(path)
if e != nil {
return e
}
embedded, e := webroot.Files.ReadFile(filepath.ToSlash(name))
if e != nil {
return e
}
if !bytes.Equal(want, embedded) {
t.Errorf("embedded asset bytes changed: %s", name)
}
count++
return nil
})
if e != nil {
t.Fatal(e)
}
if count < 100 {
t.Fatal("incomplete asset inventory", count)
}
}
func TestEmbeddedAssetHTTP(t *testing.T) {
s := Server{}
for _, name := range []string{"css/main.css", "js/jquery.js", "img/lbry.png", "amcharts/serial.js", "amcharts/plugins/export/export.min.js"} {
t.Run(name, func(t *testing.T) {
want, e := webroot.Files.ReadFile(name)
if e != nil {
t.Fatal(e)
}
for _, method := range []string{"GET", "HEAD"} {
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest(method, "/"+name, nil))
if w.Code != 200 || w.Header().Get("Content-Type") == "" {
t.Fatalf("%s: status %d, headers %v", method, w.Code, w.Header())
}
if method == "GET" && !bytes.Equal(w.Body.Bytes(), want) {
t.Fatal("asset body differs")
}
if method == "HEAD" && w.Body.Len() != 0 {
t.Fatal("HEAD returned a body")
}
}
r := httptest.NewRequest("GET", "/"+name, nil)
r.Header.Set("Range", "bytes=0-9")
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
if w.Code != 206 || !bytes.Equal(w.Body.Bytes(), want[:10]) {
t.Fatal("range response differs", w.Code)
}
})
}
}
-251
View File
@@ -1,251 +0,0 @@
package explorer
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
)
const blockedListURL = "https://api.odysee.com/file/list_blocked?with_claim_id=true"
func blockedHTTPClient() *http.Client {
return &http.Client{CheckRedirect: func(req *http.Request, via []*http.Request) error {
req.Header.Del("Referer")
if len(via) > 20 {
return errors.New("maximum 20 redirects followed")
}
return nil
}, Timeout: 15 * time.Second, Transport: &http.Transport{ForceAttemptHTTP2: true, DisableCompression: true, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 5 * time.Second}}
}
func (s *Server) blocked(ctx context.Context) map[string]bool {
started := time.Now()
cacheHit := false
fetchFailed := false
status := 0
if s.Logger != nil {
defer func() {
s.Logger.InfoContext(ctx, "blocked_list", "cache_hit", cacheHit, "fetch_failed", fetchFailed, "http_status", status, "duration_ms", float64(time.Since(started))/float64(time.Millisecond))
}()
}
var body []byte
cached, hit := s.Cache.Get("list_blocked")
if hit {
var ok bool
body, ok = decodeBlockedCache(cached)
if ok {
cacheHit = true
} else {
hit = false
}
}
if !hit {
client := s.HTTPClient
if client == nil {
client = blockedHTTPClient()
defer client.CloseIdleConnections()
}
req, e := http.NewRequestWithContext(ctx, "GET", blockedListURL, nil)
if e != nil {
return nil
}
req.Header.Set("User-Agent", "")
req.Header.Set("Accept", "*/*")
req, finishConnectBudget := connectionBudget(req, 5*time.Second)
defer finishConnectBudget()
resp, e := client.Do(req)
if e != nil {
fetchFailed = true
return nil
}
status = resp.StatusCode
defer resp.Body.Close()
body, e = io.ReadAll(resp.Body)
if e != nil {
fetchFailed = true
return nil
}
var b []byte
if utf8.Valid(body) {
b, _ = json.Marshal(string(body))
} else {
b, _ = json.Marshal(struct {
Raw []byte `json:"raw_base64"`
}{body})
}
s.Cache.Put("list_blocked", b, 10*time.Minute)
}
return parseBlocked(body)
}
const blockedTrue = "\xfftrue"
const blockedFalse = "\xfffalse"
const blockedNull = "\xffnull"
func parseBlocked(body []byte) map[string]bool {
if !validProviderJSON(body) {
return nil
}
var root map[string]json.RawMessage
if json.Unmarshal(body, &root) != nil {
return nil
}
var entries []json.RawMessage
if json.Unmarshal(root["data"], &entries) != nil {
return nil
}
out := map[string]bool{}
for _, item := range entries {
var fields map[string]json.RawMessage
if json.Unmarshal(item, &fields) != nil {
out[blockedNull] = true
continue
}
raw := fields["claim_id"]
if len(raw) == 0 || string(raw) == "null" {
out[blockedNull] = true
continue
}
if string(raw) == "true" {
out[blockedTrue] = true
continue
}
if string(raw) == "false" {
out[blockedFalse] = true
continue
}
var id string
if json.Unmarshal(raw, &id) == nil {
out[id] = true
continue
}
var n json.Number
if json.Unmarshal(raw, &n) == nil {
out[string(n)] = true
}
}
return out
}
func isBlockedID(id string, list map[string]bool) bool {
if list[id] || list[blockedTrue] && truth(id) || list[blockedFalse] && !truth(id) || list[blockedNull] && id == "" {
return true
}
a := strings.Trim(id, " \t\n\r\f\v")
if !numericPattern.MatchString(a) {
return false
}
ai, ae := strconv.ParseInt(a, 10, 64)
af, _ := strconv.ParseFloat(a, 64)
for key := range list {
b := strings.Trim(key, " \t\n\r\f\v")
if !numericPattern.MatchString(b) {
continue
}
bi, be := strconv.ParseInt(b, 10, 64)
if ae == nil && be == nil {
if ai == bi {
return true
}
} else {
bf, _ := strconv.ParseFloat(b, 64)
if af == bf {
return true
}
}
}
return false
}
func markBlocked(rows []Row, list map[string]bool) {
for _, row := range rows {
blocked := isBlockedID(text(row["claim_id"]), list)
if publisher := text(row["publisher_id"]); truth(publisher) {
blocked = blocked || isBlockedID(publisher, list)
}
row["isBlocked"] = blocked
if blocked {
row["thumbnail_url"] = nil
}
}
}
func decodeBlockedCache(cached []byte) ([]byte, bool) {
trimmed := bytes.TrimSpace(cached)
if len(trimmed) > 0 && trimmed[0] == '"' {
var raw string
if json.Unmarshal(cached, &raw) == nil {
return []byte(raw), true
}
}
var wrapper map[string]json.RawMessage
if json.Unmarshal(cached, &wrapper) != nil {
return nil, false
}
var raw string
field := wrapper["raw_base64"]
if len(field) == 0 || field[0] != '"' || json.Unmarshal(field, &raw) != nil {
return nil, false
}
decoded, e := base64.StdEncoding.DecodeString(raw)
return decoded, e == nil
}
// PHP json_decode rejects malformed UTF-8 and unpaired UTF-16 escapes rather
// than replacing them. Validate these before the Go decoder sees the payload.
func validProviderJSON(body []byte) bool {
if !utf8.Valid(body) || !json.Valid(body) {
return false
}
quoted := false
depth := 0
for i := 0; i < len(body); i++ {
c := body[i]
if c == '"' {
quoted = !quoted
continue
}
if !quoted {
if c == '{' || c == '[' {
depth++
if depth >= 512 {
return false
}
} else if c == '}' || c == ']' {
depth--
}
continue
}
if c != '\\' {
continue
}
i++
if body[i] != 'u' {
continue
}
code, _ := strconv.ParseUint(string(body[i+1:i+5]), 16, 16)
i += 4
if code >= 0xdc00 && code <= 0xdfff {
return false
}
if code >= 0xd800 && code <= 0xdbff {
if i+6 >= len(body) || body[i+1] != '\\' || body[i+2] != 'u' {
return false
}
low, e := strconv.ParseUint(string(body[i+3:i+7]), 16, 16)
if e != nil || low < 0xdc00 || low > 0xdfff {
return false
}
i += 6
}
}
return true
}
-172
View File
@@ -1,172 +0,0 @@
package explorer
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestBlockedTransportFailureIsUncached(t *testing.T) {
calls := 0
s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) { calls++; return nil, errors.New("unavailable") })}}
for i := 0; i < 2; i++ {
if len(s.blocked(context.Background())) != 0 {
t.Fatal("failure should produce empty list")
}
}
if calls != 2 {
t.Fatal("transport failure was cached")
}
if _, ok := s.Cache.Get("list_blocked"); ok {
t.Fatal("failed request populated cache")
}
}
func TestBlockedMalformedBodyIsCached(t *testing.T) {
calls := 0
s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("not JSON")), Header: http.Header{}}, nil
})}}
s.blocked(context.Background())
s.blocked(context.Background())
if calls != 1 {
t.Fatal("successful malformed body must be cached")
}
}
func TestBlockedContextDeadline(t *testing.T) {
s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) { <-r.Context().Done(); return nil, r.Context().Err() })}}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
if len(s.blocked(ctx)) != 0 {
t.Fatal("deadline fallback")
}
if _, ok := s.Cache.Get("list_blocked"); ok {
t.Fatal("deadline was cached")
}
client := blockedHTTPClient()
if client.Timeout != 15*time.Second {
t.Fatal(client.Timeout)
}
transport := client.Transport.(*http.Transport)
if !transport.DisableCompression || transport.TLSHandshakeTimeout != 5*time.Second {
t.Fatal("transport compatibility")
}
}
func TestBlockedRedirectAndHeaders(t *testing.T) {
var paths []string
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.UserAgent() != "" || r.Header.Get("Accept-Encoding") != "" || r.Header.Get("Accept") != "*/*" || r.Header.Get("Referer") != "" {
t.Error("unexpected request headers/method", r.Method, r.Header)
}
paths = append(paths, r.URL.RequestURI())
if r.URL.Path == "/file/list_blocked" {
w.Header().Set("Location", "/final")
w.WriteHeader(302)
return
}
io.WriteString(w, `{"data":[{"claim_id":"blocked"}]}`)
}))
defer fixture.Close()
target, _ := url.Parse(fixture.URL)
client := blockedHTTPClient()
transport := client.Transport
client.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
copy := r.Clone(r.Context())
u := *r.URL
u.Host = target.Host
u.Scheme = target.Scheme
copy.URL = &u
return transport.RoundTrip(copy)
})
s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: client}
if !s.blocked(context.Background())["blocked"] {
t.Fatal("redirected body missing")
}
if len(paths) != 2 || paths[0] != "/file/list_blocked?with_claim_id=true" || paths[1] != "/final" {
t.Fatal(paths)
}
}
func TestBlockedRedirectLimit(t *testing.T) {
var calls atomic.Int64
fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.Header().Set("Location", "/loop")
w.WriteHeader(http.StatusFound)
}))
defer fixture.Close()
resp, err := blockedHTTPClient().Get(fixture.URL + "/loop")
if resp != nil {
resp.Body.Close()
}
if err == nil || calls.Load() != 21 {
t.Fatalf("expected initial request plus 20 redirects; got %d requests, error %v", calls.Load(), err)
}
}
func TestBlockedInvalidUTF8IsCachedWithoutRepair(t *testing.T) {
raw := append([]byte(`{"data":[{"claim_id":"blocked","junk":"`), 255)
raw = append(raw, []byte(`"}]}`)...)
calls := 0
s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(bytes.NewReader(raw))}, nil
})}}
for i := 0; i < 2; i++ {
if len(s.blocked(context.Background())) != 0 {
t.Fatal("malformed provider JSON was repaired")
}
}
if calls != 1 {
t.Fatal("successful binary response must remain cached", calls)
}
cached, ok := s.Cache.Get("list_blocked")
if !ok {
t.Fatal("missing raw response cache")
}
decoded, ok := decodeBlockedCache(cached)
if !ok || !bytes.Equal(decoded, raw) {
t.Fatal("cached bytes changed")
}
}
func TestProviderJSONDepthAndSurrogates(t *testing.T) {
for _, c := range []struct {
body string
valid bool
}{{`{"data":[],"junk":"\ud800"}`, false}, {`{"data":[],"junk":"\ud800\udc00"}`, true}, {`{"data":[],"junk":"\\ud800"}`, true}, {strings.Repeat("[", 511) + "0" + strings.Repeat("]", 511), true}, {strings.Repeat("[", 512) + "0" + strings.Repeat("]", 512), false}} {
if got := validProviderJSON([]byte(c.body)); got != c.valid {
t.Fatal("JSON validation mismatch", got, c.valid)
}
}
}
func TestConnectionBudgetSeparatesHandshakeAndTransfer(t *testing.T) {
req := httptest.NewRequest("GET", "https://example.invalid/", nil)
bounded, finish := connectionBudget(req, 10*time.Millisecond)
trace := httptrace.ContextClientTrace(bounded.Context())
trace.GetConn("example.invalid:443")
select {
case <-bounded.Context().Done():
case <-time.After(time.Second):
t.Fatal("connection budget did not cancel")
}
finish()
bounded, finish = connectionBudget(req, 5*time.Millisecond)
defer finish()
trace = httptrace.ContextClientTrace(bounded.Context())
trace.GetConn("example.invalid:443")
trace.GotConn(httptrace.GotConnInfo{})
select {
case <-bounded.Context().Done():
t.Fatal("successful connection timer cancelled response transfer")
case <-time.After(15 * time.Millisecond):
}
}
-101
View File
@@ -1,101 +0,0 @@
package explorer
import (
"net/http"
"regexp"
"strconv"
"strings"
)
var phpIntPrefix = regexp.MustCompile(`^[\t\n\r\f\v ]*([+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)`)
func phpInt(s string) int {
m := phpIntPrefix.FindStringSubmatch(s)
if len(m) < 2 {
return 0
}
if !strings.ContainsAny(m[1], ".eE") {
v, _ := strconv.ParseInt(m[1], 10, 64)
return int(v)
}
v, _ := strconv.ParseFloat(m[1], 64)
if v >= 9223372036854775807 {
return int(^uint(0) >> 1)
}
if v <= -9223372036854775808 {
return -int(^uint(0)>>1) - 1
}
return int(v)
}
func (s *Server) blocksPage(w http.ResponseWriter, r *http.Request) {
q := func(sql string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), sql, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
rest := strings.TrimPrefix(r.URL.Path, "/blocks")
rest = strings.TrimPrefix(rest, "/")
if rest != "" {
height := phpInt(firstArgument(r, "/blocks"))
if height < 0 {
redirect(w, r, "/", 302)
return
}
rows, ok := q("SELECT * FROM block WHERE height = ? LIMIT 1", height)
if !ok {
return
}
if len(rows) == 0 {
redirect(w, r, "/", 302)
return
}
block := rows[0]
txs, ok := q("SELECT id,value,input_count,output_count,hash,version FROM transaction WHERE block_hash_id = ?", block["hash"])
if !ok {
return
}
last, ok := q("SELECT height FROM block ORDER BY height DESC LIMIT 1")
if !ok {
return
}
confirmations := int64(0)
if len(last) > 0 {
confirmations = int64(number(last[0]["height"]) - number(block["height"]) + 1)
}
s.render(w, r, "block", pageData{Title: "Block Height " + text(block["height"]), Block: block, Txs: txs, Confirmations: confirmations})
return
}
count, ok := q("SELECT height AS Total FROM block ORDER BY id DESC LIMIT 1")
if !ok {
return
}
total := 0
if len(count) > 0 {
total = int(number(count[0]["Total"]))
}
if total == 0 {
internalError(w)
return
}
page, pages, pagination := paginate(total, 50, queryInt(r, "page"))
last, ok := q("SELECT height FROM block ORDER BY height DESC LIMIT 1")
if !ok {
return
}
highest := Row{"height": 0}
if len(last) > 0 {
highest = last[0]
}
blocks := []Row{}
if pages > 0 {
blocks, ok = q("SELECT height,difficulty,block_size,nonce,block_time,tx_count FROM block ORDER BY height DESC LIMIT 50 OFFSET ?", (page-1)*50)
if !ok {
return
}
}
begin := (page-1)*50 + 1
s.render(w, r, "blocks", pageData{Title: "Blocks", Blocks: blocks, Highest: highest, NumRecords: total, NumPages: pages, CurrentPage: page, PageLimit: 50, Pagination: pagination, Begin: begin, End: min(total, begin+49)})
}
-58
View File
@@ -1,58 +0,0 @@
package explorer
import (
"encoding/base64"
"encoding/json"
"net/http/httptest"
"os"
"testing"
)
func TestQueryAndBlockingBoundaries(t *testing.T) {
b, e := os.ReadFile("testdata/boundaries.json")
if e != nil {
t.Fatal(e)
}
var f struct {
Queries []struct {
Raw, Q string
Page int64
}
Blocked []struct {
Claim string
Publisher *string
Body string
BodyBase64 string `json:"body_base64"`
Expected bool
}
}
if e = json.Unmarshal(b, &f); e != nil {
t.Fatal(e)
}
for _, c := range f.Queries {
r := httptest.NewRequest("GET", "/?"+c.Raw, nil)
if q := queryString(r, "q"); q != c.Q {
t.Errorf("%s: q %q != expected %q", c.Raw, q, c.Q)
}
if page := queryInt(r, "page"); int64(page) != c.Page {
t.Errorf("%s: page %d != expected %d", c.Raw, page, c.Page)
}
}
for _, c := range f.Blocked {
row := Row{"claim_id": c.Claim}
if c.Publisher != nil {
row["publisher_id"] = *c.Publisher
}
body := []byte(c.Body)
if c.BodyBase64 != "" {
body, e = base64.StdEncoding.DecodeString(c.BodyBase64)
if e != nil {
t.Fatal(e)
}
}
markBlocked([]Row{row}, parseBlocked(body))
if got := truth(row["isBlocked"]); got != c.Expected {
t.Errorf("%s claim %q publisher %v: %v != expected %v", c.Body, c.Claim, c.Publisher, got, c.Expected)
}
}
}
-73
View File
@@ -1,73 +0,0 @@
package explorer
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"time"
)
type Cache struct {
Dir string
Now func() time.Time
}
type cacheEntry struct {
Expires time.Time `json:"expires"`
Body json.RawMessage `json:"body"`
}
func (c Cache) now() time.Time {
if c.Now != nil {
return c.Now()
}
return time.Now()
}
func (c Cache) Get(key string) ([]byte, bool) {
b, e := os.ReadFile(filepath.Join(c.Dir, key+".json"))
if e != nil {
return nil, false
}
var v cacheEntry
if json.Unmarshal(b, &v) != nil || !c.now().Before(v.Expires) {
return nil, false
}
return v.Body, true
}
func (c Cache) Put(key string, b []byte, ttl time.Duration) error {
if e := os.MkdirAll(c.Dir, 0700); e != nil {
return e
}
v, e := json.Marshal(cacheEntry{c.now().Add(ttl), b})
if e != nil {
return e
}
f, e := os.CreateTemp(c.Dir, ".cache-")
if e != nil {
return e
}
name := f.Name()
defer os.Remove(name)
if _, e = f.Write(v); e != nil {
f.Close()
return e
}
if e = f.Close(); e != nil {
return e
}
return os.Rename(name, filepath.Join(c.Dir, key+".json"))
}
// Cake accepts only PHP arrays for these API cache entries. JSON objects and
// arrays are their Go-cache representations; primitives/null remain misses.
func (s *Server) cachedArray(key string) ([]byte, bool) {
b, ok := s.Cache.Get(key)
if !ok {
return nil, false
}
trimmed := bytes.TrimSpace(b)
if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') {
return nil, false
}
return b, true
}
-167
View File
@@ -1,167 +0,0 @@
package explorer
import (
"net/http"
"regexp"
"strconv"
"strings"
)
type claimCard struct {
Claim Row
LastItem, LastRow bool
}
func cards(rows []Row) []claimCard {
out := make([]claimCard, 0, len(rows))
lastRow := (len(rows) + 2) / 3
for i, row := range rows {
out = append(out, claimCard{row, (i+1)%3 == 0, i/3+1 == lastRow})
}
return out
}
func claimCost(r Row) string {
if number(r["price"]) > 0 {
return currency(r["price"]) + " LBC"
}
if r["fee"] != nil && strings.ToLower(text(r["fee_currency"])) == "lbc" {
return currency(r["fee"]) + " LBC"
}
return ""
}
func (s *Server) claimsPage(w http.ResponseWriter, r *http.Request) {
rest := strings.TrimPrefix(strings.TrimPrefix(r.URL.Path, "/claims"), "/")
if rest != "" && rest != "0" {
s.claimPage(w, r, firstArgument(r, "/claims"))
return
}
rows, e := s.Store.Query(r.Context(), "SELECT MAX(id) AS MaxId FROM claim")
if e != nil {
internalError(w)
return
}
maxID := 0
if len(rows) > 0 {
maxID = int(number(rows[0]["MaxId"]))
}
page, pages, pagination := paginate(20000000, 96, queryInt(r, "page"))
start := maxID - page*96
end := min(maxID, start+96)
list := s.blocked(r.Context())
claims, e := s.Store.Query(r.Context(), "SELECT Claims.*,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id WHERE Claims.id > ? AND Claims.id <= ? ORDER BY Claims.id DESC", start, end)
if e != nil {
internalError(w)
return
}
markBlocked(claims, list)
s.render(w, r, "claims", pageData{Title: "Claims Explorer", Claims: claims, Cards: cards(claims), NumRecords: 20000000, PageLimit: 96, CurrentPage: page, NumPages: pages, Pagination: pagination})
}
var numericPattern = regexp.MustCompile(`^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`)
func (s *Server) findPage(w http.ResponseWriter, r *http.Request) {
criteria := phpTrim(queryString(r, "q"))
var claims []Row
query := func(q string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), q, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
redirect := func(path string) { redirect(w, r, path, 302) }
switch {
case numericPattern.MatchString(criteria):
n, _ := strconv.ParseFloat(criteria, 64)
height := int(n)
rows, ok := query("SELECT id FROM block WHERE height = ? LIMIT 1", height)
if !ok {
return
}
if len(rows) > 0 {
redirect("/blocks/" + strconv.Itoa(height))
return
}
case len(criteria) == 34:
rows, ok := query("SELECT id,address FROM address WHERE address = ? LIMIT 1", criteria)
if !ok {
return
}
if len(rows) > 0 {
redirect("/address/" + text(rows[0]["address"]))
return
}
case len(criteria) == 40:
rows, ok := query("SELECT claim_id FROM claim WHERE claim_id = ? LIMIT 1", criteria)
if !ok {
return
}
if len(rows) > 0 {
redirect("/claims/" + text(rows[0]["claim_id"]))
return
}
case len(criteria) == 64:
rows, ok := query("SELECT height FROM block WHERE hash = ? LIMIT 1", criteria)
if !ok {
return
}
if len(rows) > 0 {
redirect("/blocks/" + text(rows[0]["height"]))
return
}
rows, ok = query("SELECT hash FROM transaction WHERE hash = ? LIMIT 1", criteria)
if !ok {
return
}
if len(rows) > 0 {
redirect("/tx/" + text(rows[0]["hash"]))
return
}
default:
var ok bool
claims, ok = query("SELECT Claims.* FROM claim Claims WHERE name = ? GROUP BY claim_id ORDER BY FIELD(bid_state, 'Controlling') DESC LIMIT 10", criteria)
if !ok {
return
}
if len(claims) == 1 {
redirect("/claims/" + text(claims[0]["claim_id"]))
return
}
}
s.render(w, r, "find", pageData{Title: "Search Results", Claims: claims, Cards: cards(claims)})
}
func (s *Server) claimPage(w http.ResponseWriter, r *http.Request, id string) {
query := func(q string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), q, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
rows, ok := query("SELECT Claims.*,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id WHERE Claims.claim_id = ? ORDER BY Claims.created_at DESC LIMIT 1", id)
if !ok {
return
}
if len(rows) == 0 {
redirect(w, r, "/", 302)
return
}
claim := rows[0]
var more []Row
if claim["publisher"] != nil && text(claim["publisher_id"]) != "f2cf43b86b9d70175dc22dbb9ff7806241d90780" {
more, ok = query("SELECT Claims.claim_id,Claims.bid_state,Claims.fee,Claims.fee_currency,Claims.is_nsfw,Claims.claim_type,Claims.name,Claims.title,Claims.description,Claims.content_type,Claims.language,Claims.author,Claims.license,Claims.created_at,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id WHERE Claims.claim_type = 1 AND Claims.id <> ? AND Claims.publisher_id = ? ORDER BY Claims.fee DESC,RAND() DESC LIMIT 9", claim["id"], claim["publisher_id"])
if !ok {
return
}
}
blocked := s.blocked(r.Context())
markBlocked(rows, blocked)
isBlocked := truth(claim["isBlocked"])
if isBlocked {
more = nil
}
s.render(w, r, "claim", pageData{Title: "Claim • " + text(claim["name"]), Claim: claim, MoreClaims: more, Cards: cards(more), ClaimIsBlocked: isBlocked})
}
-36
View File
@@ -1,36 +0,0 @@
package explorer
import (
"context"
"net/http"
"net/http/httptrace"
"sync"
"time"
)
// CURLOPT_CONNECTTIMEOUT includes DNS, TCP, proxy CONNECT and TLS. A dial
// timeout alone leaves a second TLS timeout window, so bound GetConn..GotConn.
// The separate client timeout continues to cover response transfer.
func connectionBudget(req *http.Request, budget time.Duration) (*http.Request, func()) {
ctx, cancel := context.WithCancel(req.Context())
var mu sync.Mutex
var timer *time.Timer
closed := false
stopTimer := func() {
if timer != nil {
timer.Stop()
timer = nil
}
}
trace := &httptrace.ClientTrace{GetConn: func(string) {
mu.Lock()
defer mu.Unlock()
if closed {
return
}
stopTimer()
timer = time.AfterFunc(budget, cancel)
}, GotConn: func(httptrace.GotConnInfo) { mu.Lock(); defer mu.Unlock(); stopTimer() }}
finish := func() { mu.Lock(); closed = true; stopTimer(); mu.Unlock(); cancel() }
return req.WithContext(httptrace.WithClientTrace(ctx, trace)), finish
}
-124
View File
@@ -1,124 +0,0 @@
package explorer
import (
"context"
"database/sql"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"github.com/go-sql-driver/mysql"
)
// Store deliberately exposes only SELECT operations. Every query runs in a
// server-enforced read-only transaction, including queries on pooled connections.
type Store interface {
Query(context.Context, string, ...any) ([]Row, error)
}
type Row map[string]any
type MySQL struct{ DB *sql.DB }
func Open(dsn string) (*MySQL, error) {
c, err := mysql.ParseDSN(dsn)
if err != nil {
return nil, err
}
c.ParseTime = false
c.MultiStatements = false
c.Timeout = 5 * time.Second
if c.Params == nil {
c.Params = map[string]string{}
}
c.Params["time_zone"] = "'+00:00'"
db, err := sql.Open("mysql", c.FormatDSN())
if err != nil {
return nil, err
}
db.SetMaxOpenConns(4)
db.SetMaxIdleConns(2)
db.SetConnMaxLifetime(5 * time.Minute)
return &MySQL{db}, nil
}
func (s *MySQL) Query(ctx context.Context, q string, args ...any) ([]Row, error) {
if !strings.HasPrefix(strings.ToUpper(phpTrim(q)), "SELECT ") {
return nil, errors.New("only SELECT is permitted")
}
// Preserve the source query duration, including all=true address history.
// Caller deadlines and disconnect cancellation still propagate to MySQL.
tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
return nil, err
}
defer tx.Rollback()
rows, err := tx.QueryContext(ctx, q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
cols, err := rows.ColumnTypes()
if err != nil {
return nil, err
}
out := make([]Row, 0)
for rows.Next() {
values := make([]any, len(cols))
ptr := make([]any, len(cols))
for i := range values {
ptr[i] = &values[i]
}
if err = rows.Scan(ptr...); err != nil {
return nil, err
}
r := Row{}
columns := make([]string, len(cols))
for i, c := range cols {
columns[i] = c.Name()
}
r["__columns"] = columns
for i, c := range cols {
v := values[i]
if b, ok := v.([]byte); ok {
v = string(b)
}
if str, ok := v.(string); ok {
switch c.DatabaseTypeName() {
case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT":
v, err = strconv.ParseInt(str, 10, 64)
case "FLOAT", "DOUBLE":
v, err = strconv.ParseFloat(str, 64)
}
if err != nil {
return nil, err
}
}
r[c.Name()] = v
}
out = append(out, r)
}
return out, rows.Err()
}
func number(v any) float64 {
switch n := v.(type) {
case json.Number:
f, _ := n.Float64()
return f
case uint64:
return float64(n)
case int32:
return float64(n)
case uint32:
return float64(n)
case float64:
return n
case int64:
return float64(n)
case int:
return float64(n)
case string:
f, _ := strconv.ParseFloat(n, 64)
return f
}
return 0
}
-37
View File
@@ -1,37 +0,0 @@
package explorer
import (
"html"
"html/template"
"regexp"
"strings"
)
var descriptionURL = regexp.MustCompile(`(?i)((https?|ftp|lbry)://([A-Za-z0-9\-/]+|\S*?\.\S*?))([\s)\[\]{},;"':<]|\.\s|$)`)
var descriptionEmail = regexp.MustCompile(`[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$`)
func description(v any) template.HTML {
s := text(v)
if phpTrim(s) == "" {
return template.HTML("<em>No description available.</em>")
}
var b strings.Builder
end := 0
for _, m := range descriptionURL.FindAllStringSubmatchIndex(s, -1) {
b.WriteString(html.EscapeString(s[end:m[2]]))
url := s[m[2]:m[3]]
escaped := html.EscapeString(url)
b.WriteString(`<a href="` + escaped + `" target="_blank" rel="nofollow">` + escaped + `</a>`)
b.WriteString(html.EscapeString(s[m[8]:m[9]]))
end = m[1]
}
tail := s[end:]
if loc := descriptionEmail.FindStringIndex(tail); loc != nil {
b.WriteString(html.EscapeString(tail[:loc[0]]))
mail := html.EscapeString(tail[loc[0]:loc[1]])
b.WriteString(`<a href="mailto:` + mail + `" rel="nofollow">` + mail + `</a>`)
} else {
b.WriteString(html.EscapeString(tail))
}
return template.HTML(strings.ReplaceAll(b.String(), "\n", "<br />"))
}
-32
View File
@@ -1,32 +0,0 @@
package explorer
// Cake's schema-driven entity conversions apply to browse results, unlike
// raw PDO rows used by UTXO and chart queries.
func claimEntities(rows []Row) []Row {
if rows == nil {
return []Row{}
}
for _, r := range rows {
for _, field := range []string{"is_nsfw", "is_filtered", "is_cert_valid", "is_cert_processed", "has_claim_list"} {
if r[field] != nil {
r[field] = truth(r[field])
}
}
for _, field := range []string{"created_at", "modified_at"} {
if r[field] != nil {
r[field] = timestamp(r[field]).Format("2006-01-02T15:04:05-07:00")
}
}
for _, field := range []string{"value_as_json", "claim_id_list"} {
if str, ok := r[field].(string); ok {
value, e := decodeOrderedJSON(str)
if e == nil {
r[field] = cakeJSONArray(value)
} else {
r[field] = nil
}
}
}
}
return rows
}
-33
View File
@@ -1,33 +0,0 @@
package explorer
import (
"fmt"
"html/template"
"net/http"
"net/url"
"strings"
)
func internalError(w http.ResponseWriter) {
body, _ := templateFiles.ReadFile("templates/error500.html")
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
w.WriteHeader(500)
w.Write(body)
}
func clientError(w http.ResponseWriter, r *http.Request, status int, message string) {
body, _ := templateFiles.ReadFile("templates/error400.html")
t := template.Must(template.New("error").Parse(string(body)))
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
w.WriteHeader(status)
target := r.RequestURI
if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") {
if u, e := url.Parse(target); e == nil {
target = u.RequestURI()
}
}
t.Execute(w, struct{ Message, URL string }{message, target})
}
func badMethodError(w http.ResponseWriter, r *http.Request) {
clientError(w, r, 400, fmt.Sprintf("Invalid HTTP method received. `%s` is invalid.", strings.ToUpper(r.Method)))
}
-50
View File
@@ -1,50 +0,0 @@
package explorer
import (
"encoding/json"
"os"
"testing"
"time"
)
func TestFormatting(t *testing.T) {
b, e := os.ReadFile("testdata/formatting.json")
if e != nil {
t.Fatal(e)
}
var fixtures struct {
Now int64
Dates []struct {
Timestamp int64
Ago, Human string
}
Amounts []struct {
Value any
Amount, Plain, Currency string
}
}
if e = json.Unmarshal(b, &fixtures); e != nil {
t.Fatal(e)
}
now := time.Unix(fixtures.Now, 0).UTC()
for _, f := range fixtures.Dates {
tm := time.Unix(f.Timestamp, 0).UTC()
if got := cakeAgo(tm, now); got != f.Ago {
t.Errorf("ago %d: %q != expected %q", f.Timestamp, got, f.Ago)
}
if got := humanAgo(tm, now); got != f.Human {
t.Errorf("human %d: %q != expected %q", f.Timestamp, got, f.Human)
}
}
for _, f := range fixtures.Amounts {
if got := amount(f.Value, ","); got != f.Amount {
t.Errorf("amount %v: %q != expected %q", f.Value, got, f.Amount)
}
if got := amount(f.Value, ""); got != f.Plain {
t.Errorf("plain %v: %q != expected %q", f.Value, got, f.Plain)
}
if got := currency(f.Value); got != f.Currency {
t.Errorf("currency %v: %q != expected %q", f.Value, got, f.Currency)
}
}
}
-336
View File
@@ -1,336 +0,0 @@
package explorer
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"unicode/utf16"
"unicode/utf8"
)
// PHP defaults preserve insertion order, escape Unicode and slashes, reject
// malformed UTF-8, and switch float notation outside exponents [-4,16].
func phpJSON(v any) ([]byte, error) {
var out bytes.Buffer
if err := appendPHPJSON(&out, reflect.ValueOf(v)); err != nil {
return nil, err
}
return out.Bytes(), nil
}
func appendJSONString(out *bytes.Buffer, s string) error {
if !utf8.ValidString(s) {
return errors.New("malformed UTF-8 characters")
}
out.WriteByte('"')
for _, r := range s {
switch r {
case '"':
out.WriteString(`\"`)
case '\\':
out.WriteString(`\\`)
case '/':
out.WriteString(`\/`)
case '\b':
out.WriteString(`\b`)
case '\f':
out.WriteString(`\f`)
case '\n':
out.WriteString(`\n`)
case '\r':
out.WriteString(`\r`)
case '\t':
out.WriteString(`\t`)
default:
if r < 32 || r > 127 {
if r <= 0xffff {
fmt.Fprintf(out, `\u%04x`, r)
} else {
a, b := utf16.EncodeRune(r)
fmt.Fprintf(out, `\u%04x\u%04x`, a, b)
}
} else {
out.WriteRune(r)
}
}
}
out.WriteByte('"')
return nil
}
func phpFloat(f float64) (string, error) {
if math.IsNaN(f) || math.IsInf(f, 0) {
return "", errors.New("Inf and NaN cannot be JSON encoded")
}
e := strconv.FormatFloat(f, 'e', -1, 64)
i := strings.IndexByte(e, 'e')
exponent, _ := strconv.Atoi(e[i+1:])
if exponent < -4 || exponent >= 17 {
mantissa := e[:i]
if !strings.Contains(mantissa, ".") {
mantissa += ".0"
}
return mantissa + fmt.Sprintf("e%+d", exponent), nil
}
return strconv.FormatFloat(f, 'f', -1, 64), nil
}
type jsonField struct {
Key string
Value any
}
type jsonObject []jsonField
func appendObject(out *bytes.Buffer, fields []jsonField) error {
out.WriteByte('{')
for i, f := range fields {
if i > 0 {
out.WriteByte(',')
}
if e := appendJSONString(out, f.Key); e != nil {
return e
}
out.WriteByte(':')
if e := appendPHPJSON(out, reflect.ValueOf(f.Value)); e != nil {
return e
}
}
out.WriteByte('}')
return nil
}
func rowFields(r Row) []jsonField {
keys, ok := r["__columns"].([]string)
if !ok {
for key := range r {
if key != "__columns" {
keys = append(keys, key)
}
}
sort.Strings(keys)
}
fields := make([]jsonField, 0, len(keys))
for _, key := range keys {
fields = append(fields, jsonField{key, r[key]})
}
return fields
}
func appendPHPJSON(out *bytes.Buffer, v reflect.Value) error {
if !v.IsValid() {
out.WriteString("null")
return nil
}
if v.Kind() == reflect.Interface || v.Kind() == reflect.Pointer {
if v.IsNil() {
out.WriteString("null")
return nil
}
return appendPHPJSON(out, v.Elem())
}
if v.CanInterface() {
switch value := v.Interface().(type) {
case Row:
return appendObject(out, rowFields(value))
case jsonObject:
return appendObject(out, value)
case json.RawMessage:
if !json.Valid(value) {
return errors.New("invalid raw JSON")
}
out.Write(value)
return nil
case json.Number:
if i, e := value.Int64(); e == nil {
out.WriteString(strconv.FormatInt(i, 10))
return nil
}
f, e := value.Float64()
if e != nil {
return e
}
s, e := phpFloat(f)
if e != nil {
return e
}
out.WriteString(s)
return nil
}
}
switch v.Kind() {
case reflect.Bool:
out.WriteString(strconv.FormatBool(v.Bool()))
case reflect.String:
return appendJSONString(out, v.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
out.WriteString(strconv.FormatInt(v.Int(), 10))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
out.WriteString(strconv.FormatUint(v.Uint(), 10))
case reflect.Float32, reflect.Float64:
s, e := phpFloat(v.Float())
if e != nil {
return e
}
out.WriteString(s)
case reflect.Slice, reflect.Array:
if v.Kind() == reflect.Slice && v.IsNil() {
out.WriteString("null")
return nil
}
out.WriteByte('[')
for i := 0; i < v.Len(); i++ {
if i > 0 {
out.WriteByte(',')
}
if e := appendPHPJSON(out, v.Index(i)); e != nil {
return e
}
}
out.WriteByte(']')
case reflect.Map:
if v.IsNil() {
out.WriteString("null")
return nil
}
if v.Type().Key().Kind() != reflect.String {
return errors.New("nonstring JSON map key")
}
keys := v.MapKeys()
sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
fields := make([]jsonField, 0, len(keys))
for _, key := range keys {
fields = append(fields, jsonField{key.String(), v.MapIndex(key).Interface()})
}
return appendObject(out, fields)
case reflect.Struct:
fields := []jsonField{}
typ := v.Type()
for i := 0; i < v.NumField(); i++ {
field := typ.Field(i)
if !field.IsExported() {
continue
}
tag := strings.Split(field.Tag.Get("json"), ",")
if tag[0] == "-" {
continue
}
if len(tag) > 1 && tag[1] == "omitempty" && v.Field(i).IsZero() {
continue
}
key := tag[0]
if key == "" {
key = field.Name
}
fields = append(fields, jsonField{key, v.Field(i).Interface()})
}
return appendObject(out, fields)
default:
return fmt.Errorf("unsupported JSON type %s", v.Kind())
}
return nil
}
func sendJSON(w http.ResponseWriter, status int, v any) {
b, e := phpJSON(v)
if e != nil {
internalError(w)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(b)
}
func jsonError(w http.ResponseWriter, status int, message string) {
sendJSON(w, status, struct {
Error bool `json:"error"`
Message string `json:"message"`
}{true, message})
}
func (r Row) MarshalJSON() ([]byte, error) { return phpJSON(r) }
func orderedRows(rows []Row, keys ...string) []Row {
if rows == nil {
return []Row{}
}
for _, r := range rows {
r["__columns"] = keys
}
return rows
}
// Decode DB JSON in source order, retaining an empty object as {} rather than [].
func decodeOrderedJSON(s string) (any, error) {
d := json.NewDecoder(strings.NewReader(s))
d.UseNumber()
return readJSONValue(d)
}
func readJSONValue(d *json.Decoder) (any, error) {
token, e := d.Token()
if e != nil {
return nil, e
}
if delimiter, ok := token.(json.Delim); ok {
switch delimiter {
case '{':
obj := jsonObject{}
for d.More() {
key, e := d.Token()
if e != nil {
return nil, e
}
value, e := readJSONValue(d)
if e != nil {
return nil, e
}
obj = append(obj, jsonField{key.(string), value})
}
_, e = d.Token()
return obj, e
case '[':
arr := []any{}
for d.More() {
value, e := readJSONValue(d)
if e != nil {
return nil, e
}
arr = append(arr, value)
}
_, e = d.Token()
return arr, e
}
}
return token, nil
}
// Cake JsonType decodes JSON objects to PHP associative arrays. Empty objects
// and objects whose numeric keys form 0..n-1 consequently serialize as arrays.
func cakeJSONArray(v any) any {
switch value := v.(type) {
case jsonObject:
if len(value) == 0 {
return []any{}
}
sequential := true
for i, f := range value {
value[i].Value = cakeJSONArray(f.Value)
if f.Key != strconv.Itoa(i) {
sequential = false
}
}
if sequential {
arr := make([]any, len(value))
for i, f := range value {
arr[i] = f.Value
}
return arr
}
return value
case []any:
for i, item := range value {
value[i] = cakeJSONArray(item)
}
return value
}
return v
}
-54
View File
@@ -1,54 +0,0 @@
package explorer
import (
"encoding/json"
"math"
"os"
"testing"
)
func TestJSONNumbers(t *testing.T) {
b, e := os.ReadFile("testdata/formatting.json")
if e != nil {
t.Fatal(e)
}
var f struct {
JSON []struct {
Value json.Number
Encoded string
}
}
if e = json.Unmarshal(b, &f); e != nil {
t.Fatal(e)
}
if len(f.JSON) == 0 {
t.Fatal("no numeric fixtures")
}
for _, c := range f.JSON {
var value any = c.Value
if string(c.Value) == "-0" {
value = math.Copysign(0, -1)
}
b, e := phpJSON(value)
if e != nil || string(b) != c.Encoded {
t.Errorf("%s => %s != expected %s (%v)", c.Value, b, c.Encoded, e)
}
}
for _, v := range []any{string([]byte{0xff}), Row{"bad": string([]byte{0xc3})}} {
if _, e = phpJSON(v); e == nil {
t.Fatal("invalid UTF-8 accepted")
}
}
}
func TestCakeJSONAssociativeArrays(t *testing.T) {
for _, c := range []struct{ in, want string }{{`{}`, `[]`}, {`{"0":"a","1":"b"}`, `["a","b"]`}, {`{"long":{},"z":1.0}`, `{"long":[],"z":1}`}} {
v, e := decodeOrderedJSON(c.in)
if e != nil {
t.Fatal(e)
}
b, e := phpJSON(cakeJSONArray(v))
if e != nil || string(b) != c.want {
t.Fatal(string(b), c.want, e)
}
}
}
-79
View File
@@ -1,79 +0,0 @@
package explorer
import (
"context"
"database/sql"
"errors"
"log/slog"
"net/http"
"time"
"github.com/go-sql-driver/mysql"
)
// ObservedStore records query cost without logging SQL, arguments, credentials,
// claim metadata or database error messages. It introduces no DB operations.
type ObservedStore struct {
Store Store
Logger *slog.Logger
Stats func() sql.DBStats
}
func (s ObservedStore) Query(ctx context.Context, q string, args ...any) ([]Row, error) {
started := time.Now()
rows, err := s.Store.Query(ctx, q, args...)
if s.Logger != nil {
code := 0
var mysqlErr *mysql.MySQLError
if errors.As(err, &mysqlErr) {
code = int(mysqlErr.Number)
}
attrs := []any{"duration_ms", float64(time.Since(started)) / float64(time.Millisecond), "rows", len(rows), "success", err == nil, "mysql_error_code", code}
if s.Stats != nil {
stats := s.Stats()
attrs = append(attrs, "pool_open", stats.OpenConnections, "pool_in_use", stats.InUse, "pool_wait_count", stats.WaitCount, "pool_wait_ms", stats.WaitDuration.Milliseconds())
}
s.Logger.InfoContext(ctx, "db_query", attrs...)
}
return rows, err
}
type observedResponse struct {
http.ResponseWriter
status int
bytes int64
}
func (w *observedResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter }
func (w *observedResponse) WriteHeader(status int) {
if w.status != 0 {
return
}
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *observedResponse) Write(b []byte) (int, error) {
if w.status == 0 {
w.WriteHeader(200)
}
n, e := w.ResponseWriter.Write(b)
w.bytes += int64(n)
return n, e
}
// AccessLog uses the matched action instead of raw query parameters or paths.
// It adds no headers or public monitoring routes.
func AccessLog(next http.Handler, logger *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
response := &observedResponse{ResponseWriter: w}
next.ServeHTTP(response, r)
status := response.status
if status == 0 {
status = 200
}
if logger != nil {
logger.InfoContext(r.Context(), "http_request", "method", r.Method, "action", matchRoute(r.URL.EscapedPath(), r.Method).Action, "status", status, "bytes", response.bytes, "duration_ms", float64(time.Since(started))/float64(time.Millisecond))
}
})
}
-53
View File
@@ -1,53 +0,0 @@
package explorer
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
type failedStore struct{}
func (failedStore) Query(context.Context, string, ...any) ([]Row, error) {
return nil, errors.New("private-password-or-SQL-must-not-be-logged")
}
func TestObservabilityPreservesResponseAndRedactsInputs(t *testing.T) {
var log bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&log, nil))
observed := ObservedStore{Store: &fakeStore{rows: []Row{}}, Logger: logger, Stats: func() sql.DBStats { return sql.DBStats{OpenConnections: 1, WaitCount: 2} }}
app := &Server{Store: observed}
w := httptest.NewRecorder()
AccessLog(app, logger).ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/status?secret=do-not-log", nil))
if w.Code != 200 || w.Body.String() != `{"success":true,"status":{"height":0,"difficulty":"0.00","price":"N\/A","hashrate":"N\/A"}}` {
t.Fatal(w.Code, w.Body.String())
}
if strings.Contains(log.String(), "secret") || strings.Contains(log.String(), "SELECT") || strings.Contains(log.String(), "do-not-log") {
t.Fatal("private input in logs")
}
for _, line := range strings.Split(strings.TrimSpace(log.String()), "\n") {
var item map[string]any
if e := json.Unmarshal([]byte(line), &item); e != nil {
t.Fatal(e)
}
}
failed := ObservedStore{Store: failedStore{}, Logger: logger}
failed.Query(context.Background(), "SELECT private", "password")
if strings.Contains(log.String(), "private-password") || strings.Contains(log.String(), "SELECT private") {
t.Fatal("database error text or SQL leaked")
}
}
func TestAccessLogHeadResponse(t *testing.T) {
app := AccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Test", "kept"); w.WriteHeader(302) }), nil)
w := httptest.NewRecorder()
app.ServeHTTP(w, httptest.NewRequest("HEAD", "/", nil))
if w.Code != 302 || w.Header().Get("X-Test") != "kept" || w.Body.Len() != 0 {
t.Fatal(w.Code, w.Header(), w.Body.String())
}
}
-297
View File
@@ -1,297 +0,0 @@
package explorer
import (
"bytes"
"embed"
"encoding/json"
"fmt"
"html"
"html/template"
"math"
"math/rand/v2"
"net/http"
"strconv"
"strings"
"time"
)
//go:embed templates/*.html
var templateFiles embed.FS
type pageData struct {
Tx Row
Inputs, Outputs []ioView
Fee string
Address Row
RecentTxs, RichList []Row
BalanceAmount, TotalReceived, TotalSent float64
InflationChartVersion int64
Claim Row
MoreClaims []Row
ClaimIsBlocked bool
Title string
Analytics bool
RecentBlocks, RecentClaims, Blocks, Txs []Row
Highest, Block Row
Confirmations int64
NumRecords, NumPages, CurrentPage, PageLimit int
Begin, End int
Pagination pagination
Claims []Row
Cards []claimCard
}
func text(v any) string {
if v == nil {
return ""
}
if n, ok := v.(json.Number); ok {
if strings.ContainsAny(string(n), ".eE") {
return phpString(number(n))
}
return string(n)
}
if f, ok := v.(float64); ok {
return phpString(f)
}
return fmt.Sprint(v)
}
func truth(v any) bool {
if v == nil {
return false
}
if b, ok := v.(bool); ok {
return b
}
s := text(v)
return s != "" && s != "0"
}
func fixed(v any, places int) string {
return strconv.FormatFloat(roundPHP(number(v), places), 'f', places, 64)
}
func grouped(v any, places int) string {
s := fixed(v, places)
parts := strings.SplitN(s, ".", 2)
sign := ""
if strings.HasPrefix(parts[0], "-") {
sign = "-"
parts[0] = parts[0][1:]
}
n := parts[0]
for i := len(n) - 3; i > 0; i -= 3 {
n = n[:i] + "," + n[i:]
}
if len(parts) > 1 {
n += "." + parts[1]
}
return sign + n
}
func amount(v any, separator string) string {
s := fixed(v, 8)
if separator != "" {
s = strings.ReplaceAll(grouped(v, 8), ",", separator)
}
return strings.TrimSuffix(strings.TrimRight(s, "0"), ".")
}
func currency(v any) string {
s := text(v)
parts := strings.SplitN(s, ".", 2)
if len(parts) == 1 {
return grouped(v, 2)
}
left := grouped(parts[0], 0)
if number("0."+parts[1]) == 0 {
return left
}
right := parts[1] + "00"
return left + "." + right[:2]
}
func timestamp(v any) time.Time {
if str, ok := v.(string); ok {
for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339Nano} {
if t, e := time.ParseInLocation(layout, str, time.UTC); e == nil {
return t
}
}
}
return time.Unix(int64(number(v)), 0).UTC()
}
func contentTag(r Row) string {
ct := text(r["content_type"])
for _, prefix := range []string{"audio", "video", "image"} {
if strings.HasPrefix(ct, prefix) {
return strings.ToUpper(prefix)
}
}
if number(r["claim_type"]) == 2 {
return "IDENTITY"
}
return ""
}
func autoThumb(r Row) string {
name := text(r["name"])
n := 5
if number(r["claim_type"]) == 2 {
n = 10
if len(name) > 0 {
name = name[1:]
}
} else if title := phpTrim(text(r["title"])); title != "" {
name = title
}
if len(name) > n {
name = name[:n]
}
var b strings.Builder
for i := 0; i < len(name); i++ {
c := name[i]
if c >= 'a' && c <= 'z' {
c -= 32
}
b.WriteByte(c)
}
return b.String()
}
func claimTitle(r Row) string {
if number(r["claim_type"]) == 1 {
return text(r["name"])
}
if phpTrim(text(r["title"])) != "" {
return text(r["title"])
}
return ""
}
func lbryLink(r Row) template.URL {
name := text(r["name"])
if publisher := text(r["publisher"]); publisher != "" {
name = publisher + "/" + name
}
return template.URL("lbry://" + name)
}
func thumbColor() string {
return []string{"purple", "orange", "blue", "teal", "green", "yellow"}[rand.IntN(6)]
}
func (s *Server) functions() template.FuncMap {
return template.FuncMap{
"confirmationDelay": confirmationDelay, "safeURL": safeURL, "ownedAddress": func(v any) bool { return ownedAddresses[text(v)] }, "txClass": func(r Row) string {
if number(r["debit_amount"]) > 0 {
if number(r["credit_amount"]) > 0 {
return "diff"
}
return "debit"
}
return "credit"
}, "difference": func(a, b any) float64 { return number(a) - number(b) },
"isset": func(row Row, key string) bool { return row[key] != nil }, "trim": func(v any) string { return phpTrim(text(v)) }, "language": func(v any) string {
if text(v) == "en" {
return "English"
}
return text(v)
}, "claimCost": claimCost, "description": description, "publisherLink": func(v any) template.URL { return template.URL("lbry://" + text(v)) }, "claimDate": func(r Row) string {
v := r["created_at"]
if number(r["transaction_time"]) > 0 {
v = r["transaction_time"]
}
return timestamp(v).Format("2 Jan 2006 15:04:05")
},
"text": text, "truth": truth, "num": number, "fixed": fixed, "grouped": grouped, "amount": amount, "currency": currency, "contentTag": contentTag, "autoThumb": autoThumb, "claimTitle": claimTitle, "lbryLink": lbryLink, "lbryHref": func(r Row) template.HTMLAttr {
return template.HTMLAttr(`href="` + html.EscapeString(string(lbryLink(r))) + `"`)
}, "publisherHref": func(v any) template.HTMLAttr {
return template.HTMLAttr(`href="` + html.EscapeString("lbry://"+text(v)) + `"`)
}, "thumbColor": thumbColor,
"showThumbnail": func(r Row) bool { return !truth(r["is_nsfw"]) && phpTrim(text(r["thumbnail_url"])) != "" },
"thumbnail": func(v any) string {
return "https://thumbnails.odycdn.com/optimize/s:1280:720/quality:85/plain/" + text(v)
},
"kb": func(v any) string { return phpString(roundPHP(number(v)/1024, 2)) + "KB" },
"date": func(v any, layout string) string { return timestamp(v).Format(layout) },
"ago": func(v any) string { return cakeAgo(timestamp(v), s.now()) },
"humanAgo": func(v any) string { return humanAgo(timestamp(v), s.now()) },
"add": func(a, b any) int { return int(number(a) + number(b)) }, "sub": func(a, b any) int { return int(number(a) - number(b)) },
}
}
func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, data pageData) {
data.Analytics = r.Host == "explorer.lbry.com"
started := time.Now()
if value, ok := r.Context().Value(requestStartKey{}).(time.Time); ok {
started = value
}
functions := s.functions()
functions["elapsed"] = func() int64 { return int64(math.Round(float64(time.Since(started)) / float64(time.Millisecond))) }
t, e := template.New("layout").Funcs(functions).ParseFS(templateFiles, "templates/layout.html", "templates/header.html", "templates/pagination.html", "templates/claimbox.html", "templates/"+name+".html")
if e != nil {
http.Error(w, "Template error", 500)
return
}
var b bytes.Buffer
if e = t.ExecuteTemplate(&b, "layout", data); e != nil {
http.Error(w, "Template execution error", 500)
return
}
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
w.Write(b.Bytes())
}
func (s *Server) page(w http.ResponseWriter, r *http.Request) {
q := func(query string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), query, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
if r.URL.Path == "/qr" || strings.HasPrefix(r.URL.Path, "/qr/") {
s.qr(w, r)
return
}
if r.URL.Path == "/address" || strings.HasPrefix(r.URL.Path, "/address/") {
s.addressPage(w, r)
return
}
if r.URL.Path == "/stats" {
s.statsPage(w, r)
return
}
if r.URL.Path == "/tx" || strings.HasPrefix(r.URL.Path, "/tx/") {
s.transactionPage(w, r)
return
}
if r.URL.Path == "/find" {
s.findPage(w, r)
return
}
if r.URL.Path == "/claims" || strings.HasPrefix(r.URL.Path, "/claims/") {
s.claimsPage(w, r)
return
}
if r.URL.Path == "/realtime" {
blocks, ok := q("SELECT height,block_time,tx_count FROM block ORDER BY height DESC LIMIT 10")
if !ok {
return
}
txs, ok := q("SELECT id,value,hash,input_count,output_count,transaction_time,created_at FROM transaction ORDER BY created_at DESC LIMIT 10")
if !ok {
return
}
s.render(w, r, "realtime", pageData{Title: "Realtime Explorer", Blocks: blocks, Txs: txs})
return
}
if r.URL.Path == "/blocks" || strings.HasPrefix(r.URL.Path, "/blocks/") {
s.blocksPage(w, r)
return
}
blocks, ok := q("SELECT chainwork,confirmations,difficulty,hash,height,block_time,block_size,tx_count FROM block ORDER BY height DESC LIMIT 6")
if !ok {
return
}
claims, ok := q("SELECT Claims.*,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id ORDER BY Claims.created_at DESC LIMIT 5")
if !ok {
return
}
highest := Row{"height": nil, "difficulty": nil}
if len(blocks) > 0 {
highest = blocks[0]
}
s.render(w, r, "home", pageData{Title: "Home", RecentBlocks: blocks, RecentClaims: claims, Highest: highest})
}
-45
View File
@@ -1,45 +0,0 @@
package explorer
type pagination struct {
Visible bool
Previous, Next int
Pages []int
StartEllipsis, EndEllipsis bool
Last, Current int
}
func paginate(records, limit, page int) (int, int, pagination) {
total := (records + limit - 1) / limit
if page < 1 {
page = 1
}
if page > total {
page = total
}
p := pagination{Visible: total > 1, Last: total, Current: page}
if page > 1 {
p.Previous = page - 1
}
if page < total {
p.Next = page + 1
}
start, end := 1, min(total, 10)
if total > 10 && page > 5 {
if page >= 10 {
start = page - 5
}
if page > total-10 && start > 5 {
end = total
} else {
end = min(page+5, total)
}
}
if records > 0 {
for i := start; i <= end; i++ {
p.Pages = append(p.Pages, i)
}
p.StartEllipsis = start >= 5
p.EndEllipsis = end < total-1
}
return page, total, p
}
-148
View File
@@ -1,148 +0,0 @@
package explorer
import (
"fmt"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode/decoder"
"github.com/makiuchi-d/gozxing/qrcode/encoder"
"image"
"image/color"
"image/png"
"net/http"
"strings"
)
func qrImage(data string) (image.Image, error) {
first, e := encoder.Encoder_encode(data, decoder.ErrorCorrectionLevel_H, map[gozxing.EncodeHintType]interface{}{gozxing.EncodeHintType_CHARACTER_SET: "UTF-8", gozxing.EncodeHintType_QR_MASK_PATTERN: 0})
if e != nil {
return nil, e
}
version, versionErr := baconVersion(data, first.GetMode())
if versionErr != nil {
return nil, versionErr
}
var matrix *encoder.ByteMatrix
best := int(^uint(0) >> 1)
// Bacon 3.1 requires four white modules within the matrix for penalty
// rule 3; ZXing treats the outside border as white. Score all eight
// encodings with Bacon's rule to preserve Endroid's exact mask choice.
for mask := 0; mask < 8; mask++ {
code, e := encoder.Encoder_encode(data, decoder.ErrorCorrectionLevel_H, map[gozxing.EncodeHintType]interface{}{gozxing.EncodeHintType_CHARACTER_SET: "UTF-8", gozxing.EncodeHintType_QR_MASK_PATTERN: mask, gozxing.EncodeHintType_QR_VERSION: version})
if e != nil {
return nil, e
}
candidate := code.GetMatrix()
score := baconPenalty(candidate)
if score < best {
best = score
matrix = candidate
}
}
n := matrix.GetWidth()
block := 300 / n
margin := (320 - n*block) / 2
img := image.NewGray(image.Rect(0, 0, 320, 320))
for i := range img.Pix {
img.Pix[i] = 255
}
for y := 0; y < n; y++ {
for x := 0; x < n; x++ {
if matrix.Get(x, y) != 1 {
continue
}
for dy := 0; dy < block; dy++ {
for dx := 0; dx < block; dx++ {
img.SetGray(margin+x*block+dx, margin+y*block+dy, color.Gray{0})
}
}
}
}
return img, nil
}
func (s *Server) qr(w http.ResponseWriter, r *http.Request) {
data := firstArgument(r, "/qr")
trimmed := strings.Trim(data, " \t\n\r\x00\x0b")
if data == "0" || len(trimmed) == 0 || len(trimmed) > 50 {
jsonError(w, 400, "Invalid QR code data.")
return
}
img, e := qrImage(data)
if e != nil {
internalError(w)
return
}
w.Header().Set("Content-Type", "image/png")
png.Encode(w, img)
}
func baconPenalty(m *encoder.ByteMatrix) int {
score := encoder.MaskUtil_applyMaskPenaltyRule1(m) + encoder.MaskUtil_applyMaskPenaltyRule2(m) + encoder.MaskUtil_applyMaskPenaltyRule4(m)
n := m.GetWidth()
for axis := 0; axis < 2; axis++ {
for line := 0; line < n; line++ {
at := func(i int) int8 {
if axis == 0 {
return m.Get(i, line)
}
return m.Get(line, i)
}
white := func(a, b int) bool {
if a < 0 || b > n {
return false
}
for i := a; i < b; i++ {
if at(i) != 0 {
return false
}
}
return true
}
for i := 0; i+6 < n; i++ {
if at(i) == 1 && at(i+1) == 0 && at(i+2) == 1 && at(i+3) == 1 && at(i+4) == 1 && at(i+5) == 0 && at(i+6) == 1 && (white(i-4, i) || white(i+7, i+11)) {
score += 40
}
}
}
}
return score
}
func baconVersion(data string, mode *decoder.Mode) (int, error) {
header, bits := 4, 0
switch mode {
case decoder.Mode_BYTE:
header += 12
bits = len(data) * 8
case decoder.Mode_NUMERIC:
bits = len(data) / 3 * 10
if len(data)%3 == 1 {
bits += 4
} else if len(data)%3 == 2 {
bits += 7
}
case decoder.Mode_ALPHANUMERIC:
bits = len(data)/2*11 + len(data)%2*6
default:
return 0, fmt.Errorf("unsupported QR encoding mode")
}
choose := func(countBits int) (*decoder.Version, error) {
for n := 1; n <= 40; n++ {
v, _ := decoder.Version_GetVersionForNumber(n)
capacity := v.GetTotalCodewords() - v.GetECBlocksForLevel(decoder.ErrorCorrectionLevel_H).GetTotalECCodewords()
if capacity >= (header+countBits+bits+8)/8 {
return v, nil
}
}
return nil, fmt.Errorf("QR data too big")
}
v1, _ := decoder.Version_GetVersionForNumber(1)
provisional, e := choose(mode.GetCharacterCountBits(v1))
if e != nil {
return 0, e
}
version, e := choose(mode.GetCharacterCountBits(provisional))
if e != nil {
return 0, e
}
return version.GetVersionNumber(), nil
}
-88
View File
@@ -1,88 +0,0 @@
package explorer
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/makiuchi-d/gozxing"
"github.com/makiuchi-d/gozxing/qrcode"
"image/png"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
)
func TestQRRendering(t *testing.T) {
raw, err := os.ReadFile("testdata/qr.json")
if err != nil {
t.Fatal(err)
}
var cases []struct {
Data string
Width, Height int
SHA256 string
}
if err = json.Unmarshal(raw, &cases); err != nil {
t.Fatal(err)
}
if len(cases) < 50 {
t.Fatal("missing QR regression cases")
}
for _, c := range cases {
t.Run(c.Data, func(t *testing.T) {
img, err := qrImage(c.Data)
if err != nil {
t.Fatal(err)
}
if img.Bounds().Dx() != c.Width || img.Bounds().Dy() != c.Height {
t.Fatal("QR dimensions changed", img.Bounds())
}
pixels := make([]byte, 0, c.Width*c.Height*4)
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
r, g, b, a := img.At(x, y).RGBA()
pixels = append(pixels, byte(r>>8), byte(g>>8), byte(b>>8), byte(a>>8))
}
}
if got := fmt.Sprintf("%x", sha256.Sum256(pixels)); got != c.SHA256 {
t.Fatal("QR pixels changed", got, c.SHA256)
}
})
}
}
func TestQRPayloadAndRouting(t *testing.T) {
for _, data := range []string{"lbry://hello/path", " hello ", "éà😀", strings.Repeat("a", 50)} {
w := httptest.NewRecorder()
s := Server{}
s.ServeHTTP(w, httptest.NewRequest("GET", "/qr/"+url.PathEscape(data), nil))
if w.Code != 200 || w.Header().Get("Content-Type") != "image/png" {
t.Fatal(w.Code, w.Body.String())
}
img, e := png.Decode(bytes.NewReader(w.Body.Bytes()))
if e != nil {
t.Fatal(e)
}
bitmap, e := gozxing.NewBinaryBitmapFromImage(img)
if e != nil {
t.Fatal(e)
}
result, e := qrcode.NewQRCodeReader().Decode(bitmap, nil)
if e != nil || result.GetText() != data {
t.Fatal(data, result, e)
}
}
}
func TestQRInvalidBoundaries(t *testing.T) {
for _, data := range []string{"", "0", " \t\n", strings.Repeat("é", 26), strings.Repeat("a", 51)} {
w := httptest.NewRecorder()
s := Server{}
s.ServeHTTP(w, httptest.NewRequest("GET", "/qr/"+url.PathEscape(data), nil))
if w.Code != 400 || w.Body.String() != `{"error":true,"message":"Invalid QR code data."}` {
t.Fatal(data, w.Code, w.Body.String())
}
}
}
-81
View File
@@ -1,81 +0,0 @@
package explorer
import (
"net/http"
"strings"
)
func phpTrim(s string) string { return strings.Trim(s, " \t\n\r\x00\x0b") }
type queryParameter struct {
Value string
Array bool
Present bool
}
func queryParam(r *http.Request, key string) queryParameter {
var result queryParameter
for _, part := range strings.Split(r.URL.RawQuery, "&") {
pair := strings.SplitN(part, "=", 2)
name := phpQueryDecode(pair[0])
value := ""
if len(pair) > 1 {
value = phpQueryDecode(pair[1])
}
if name == key {
result = queryParameter{value, false, true}
continue
}
if strings.HasPrefix(name, key+"[") && strings.Contains(name[len(key)+1:], "]") {
result = queryParameter{"", true, true}
}
}
return result
}
func queryString(r *http.Request, key string) string {
v := queryParam(r, key)
if v.Array {
return "Array"
}
return v.Value
}
func queryInt(r *http.Request, key string) int {
v := queryParam(r, key)
if v.Array {
return 1
}
return phpInt(v.Value)
}
func queryScalar(r *http.Request, key string) string {
v := queryParam(r, key)
if v.Array {
return ""
}
return v.Value
}
func phpQueryDecode(s string) string {
var out strings.Builder
hex := func(b byte) int {
switch {
case b >= '0' && b <= '9':
return int(b - '0')
case b >= 'a' && b <= 'f':
return int(b-'a') + 10
case b >= 'A' && b <= 'F':
return int(b-'A') + 10
}
return -1
}
for i := 0; i < len(s); i++ {
if s[i] == '+' {
out.WriteByte(' ')
} else if s[i] == '%' && i+2 < len(s) && hex(s[i+1]) >= 0 && hex(s[i+2]) >= 0 {
out.WriteByte(byte(hex(s[i+1])*16 + hex(s[i+2])))
i += 2
} else {
out.WriteByte(s[i])
}
}
return out.String()
}
-18
View File
@@ -1,18 +0,0 @@
package explorer
import (
"net/http"
)
type headWriter struct{ http.ResponseWriter }
func (w headWriter) Write(b []byte) (int, error) { return len(b), nil }
func redirect(w http.ResponseWriter, r *http.Request, location string, status int) {
scheme := "http"
if r.TLS != nil || r.URL.Scheme == "https" || r.Header.Get("X-Forwarded-Proto") == "https" {
scheme = "https"
}
w.Header().Set("Location", scheme+"://"+r.Host+location)
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
w.WriteHeader(status)
}
-38
View File
@@ -1,38 +0,0 @@
package explorer
import "math"
// PHP 8.5 half-up rounding compares the unscaled number with a reconstructed
// half boundary. This avoids decimal-scaling errors such as 1.005*100 < 100.5.
// Algorithm adapted from PHP Group's _php_math_round, PHP License 3.01:
// https://github.com/php/php-src/blob/PHP-8.5/ext/standard/math.c
// Copyright (c) The PHP Group. See licenses/PHP-3.01.txt.
func roundPHP(value float64, places int) float64 {
if value == 0 {
return 0
}
if math.IsNaN(value) || math.IsInf(value, 0) {
return value
}
sign := 1.0
if value < 0 {
sign = -1
value = -value
}
scale := math.Pow10(places)
integral := math.Floor(value * scale)
if (integral+1)/scale == value {
integral++
}
if integral >= 1e16 {
return sign * value
}
if value >= (integral+.5)/scale {
integral++
}
result := integral / scale
if result == 0 {
return 0
}
return sign * result
}
-63
View File
@@ -1,63 +0,0 @@
package explorer
import (
"context"
"encoding/json"
"net/http/httptest"
"os"
"regexp"
"strconv"
"testing"
"time"
)
func TestRoundingBoundaries(t *testing.T) {
b, e := os.ReadFile("testdata/formatting.json")
if e != nil {
t.Fatal(e)
}
var f struct {
Rounds []struct {
Value float64
Places int
Expected string
}
}
if e = json.Unmarshal(b, &f); e != nil {
t.Fatal(e)
}
if len(f.Rounds) < 30 {
t.Fatal("missing rounding cases")
}
for _, c := range f.Rounds {
if got := fixed(c.Value, c.Places); got != c.Expected {
t.Errorf("%v precision %d: %s != expected %s", c.Value, c.Places, got, c.Expected)
}
}
s := Server{Store: &fakeStore{rows: []Row{{"height": 1, "difficulty": 1.005}}}}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/status", nil))
if w.Body.String() != `{"success":true,"status":{"height":1,"difficulty":"1.01","price":"N\/A","hashrate":"N\/A"}}` {
t.Fatal(w.Body.String())
}
}
type delayedStore struct{}
func (delayedStore) Query(context.Context, string, ...any) ([]Row, error) {
time.Sleep(3 * time.Millisecond)
return []Row{}, nil
}
func TestFooterMeasuresRequestWork(t *testing.T) {
w := httptest.NewRecorder()
s := Server{Store: delayedStore{}}
s.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
match := regexp.MustCompile(`Page took ([0-9]+)ms`).FindStringSubmatch(w.Body.String())
if len(match) != 2 {
t.Fatal("missing timing footer")
}
elapsed, _ := strconv.Atoi(match[1])
if elapsed < 5 {
t.Fatal("footer omitted database time", elapsed)
}
}
-105
View File
@@ -1,105 +0,0 @@
package explorer
import (
"context"
"net/http"
"net/url"
"regexp"
"strings"
)
type routeMatch struct {
Action, Canonical string
Args []string
}
type routeKey struct{}
var apiAddressPattern = regexp.MustCompile(`^/api/v1/address/([A-Za-z0-9,]+)/utxo/*$`)
var apiBalancePattern = regexp.MustCompile(`^/api/v1/address/([A-Za-z0-9]+)/balance/*$`)
var apiPeriodPattern = regexp.MustCompile(`^/api/v1/charts/blocksize/([012346789dhy]+)/*$`)
func matchRoute(path, method string) routeMatch {
path = "/" + strings.TrimLeft(path, "/")
valid := false
for _, m := range []string{"GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS", "HEAD"} {
if strings.ToUpper(method) == m {
valid = true
}
}
if !valid {
return routeMatch{Action: "badmethod"}
}
if strings.Contains(path, "%") {
parts := strings.Split(path, "/")
for i, p := range parts {
decoded, e := url.QueryUnescape(p)
if e == nil {
parts[i] = strings.ReplaceAll(decoded, "/", "%2f")
}
}
path = strings.Join(parts, "/")
}
trimmed := strings.TrimRight(path, "/")
if trimmed == "" {
trimmed = "/"
}
for _, rule := range []struct {
Pattern *regexp.Regexp
Action, Prefix, Suffix string
}{{apiAddressPattern, "apiaddrutxo", "/api/v1/address/", "/utxo"}, {apiBalancePattern, "apiaddrbalance", "/api/v1/address/", "/balance"}, {apiPeriodPattern, "apiblocksize", "/api/v1/charts/blocksize/", ""}} {
if m := rule.Pattern.FindStringSubmatch(path); m != nil {
return routeMatch{rule.Action, rule.Prefix + m[1] + rule.Suffix, []string{m[1]}}
}
}
static := map[string]string{"/api/v1/charts/inflation": "apiinflation", "/api/v1/realtime/blocks": "apirealtimeblocks", "/api/v1/realtime/tx": "apirealtimetx", "/api/v1/recentblocks": "apirecentblocks", "/api/v1/status": "apistatus", "/api/v1/supply": "apiutxosupply", "/api/v1/claims/browse": "apibrowse", "/": "index", "/find": "find", "/realtime": "realtime", "/stats": "stats"}
if action, ok := static[trimmed]; ok {
return routeMatch{action, trimmed, []string{}}
}
for _, action := range []string{"address", "blocks", "claims", "tx", "qr"} {
prefix := "/" + action
if path == prefix || strings.HasPrefix(path, prefix+"/") {
args := []string{}
for _, arg := range strings.Split(strings.TrimPrefix(path, prefix), "/") {
if arg != "" {
v, e := url.PathUnescape(arg)
if e == nil {
args = append(args, v)
}
}
}
canonical := prefix
if len(args) > 0 {
canonical += "/" + args[0]
}
return routeMatch{action, canonical, args}
}
}
return routeMatch{"index", "/", []string{}}
}
func routedRequest(r *http.Request, match routeMatch) *http.Request {
copy := r.Clone(context.WithValue(r.Context(), routeKey{}, match))
u := *r.URL
u.Path = match.Canonical
u.RawPath = ""
copy.URL = &u
return copy
}
func firstArgument(r *http.Request, prefix string) string {
if match, ok := r.Context().Value(routeKey{}).(routeMatch); ok {
if len(match.Args) > 0 {
return match.Args[0]
}
return ""
}
path := strings.TrimPrefix(r.URL.EscapedPath(), prefix)
path = strings.TrimPrefix(path, "/")
for _, part := range strings.Split(path, "/") {
if part != "" {
decoded, e := url.PathUnescape(part)
if e == nil {
return decoded
}
}
}
return ""
}
-35
View File
@@ -1,35 +0,0 @@
package explorer
import (
"encoding/json"
"os"
"reflect"
"testing"
)
func TestRoutes(t *testing.T) {
b, e := os.ReadFile("testdata/routes.json")
if e != nil {
t.Fatal(e)
}
var cases []struct {
Path, Method, Action string
Args []string
}
if e = json.Unmarshal(b, &cases); e != nil {
t.Fatal(e)
}
if len(cases) < 50 {
t.Fatal("missing route cases")
}
for _, c := range cases {
m := matchRoute(c.Path, c.Method)
if m.Action != c.Action {
t.Errorf("%s %s: %s != expected %s", c.Method, c.Path, m.Action, c.Action)
}
if c.Action != "index" && !reflect.DeepEqual(m.Args, c.Args) {
t.Errorf("%s arguments %v != expected %v", c.Path, m.Args, c.Args)
}
}
}
-192
View File
@@ -1,192 +0,0 @@
package explorer
import (
"context"
"explorer/webroot"
"fmt"
"io/fs"
"log/slog"
"net/http"
"path"
"strings"
"time"
)
type requestStartKey struct{}
type Server struct {
Logger *slog.Logger
RandomInt func(int) int
HTTPClient *http.Client
Store Store
Cache Cache
Now func() time.Time
}
func (s *Server) now() time.Time {
if s.Now != nil {
return s.Now().UTC()
}
return time.Now().UTC()
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), requestStartKey{}, time.Now()))
if r.Method == "HEAD" {
w = headWriter{w}
}
// Serve only real files under the production webroot. Missing files continue
// through application routing, as they do in the production front controller.
name := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
if info, e := fs.Stat(webroot.Files, name); e == nil && !info.IsDir() {
http.ServeFileFS(w, r, webroot.Files, name)
return
}
match := matchRoute(r.URL.EscapedPath(), r.Method)
if match.Action == "badmethod" {
badMethodError(w, r)
return
}
r = routedRequest(r, match)
if s.api(w, r) {
return
}
s.page(w, r)
}
func (s *Server) api(w http.ResponseWriter, r *http.Request) bool {
path := r.URL.Path
query := func(q string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), q, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
if s.remainingAPI(w, r) {
return true
}
switch path {
case "/api/v1/status":
rows, ok := query("SELECT height,difficulty FROM block ORDER BY height DESC LIMIT 1")
if !ok {
return true
}
var height any = 0
difficulty := 0.0
if len(rows) > 0 {
height = rows[0]["height"]
difficulty = number(rows[0]["difficulty"])
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
Status any `json:"status"`
}{true, struct {
Height any `json:"height"`
Difficulty string `json:"difficulty"`
Price string `json:"price"`
Hashrate string `json:"hashrate"`
}{height, fixed(difficulty, 2), "N/A", "N/A"}})
case "/api/v1/recentblocks", "/api/v1/realtime/blocks":
q := "SELECT height AS Height,block_time AS BlockTime,tx_count AS TransactionCount FROM block ORDER BY height DESC LIMIT 10"
if path == "/api/v1/recentblocks" {
q = "SELECT difficulty AS Difficulty,hash AS Hash,height AS Height,block_time AS BlockTime,block_size AS BlockSize,tx_count AS TransactionCount FROM block ORDER BY height DESC LIMIT 6"
}
rows, ok := query(q)
if !ok {
return true
}
if path == "/api/v1/recentblocks" {
for _, row := range rows {
row["Difficulty"] = fixed(row["Difficulty"], 2)
}
}
keys := []string{"Height", "BlockTime", "TransactionCount"}
if path == "/api/v1/recentblocks" {
keys = []string{"Difficulty", "Hash", "Height", "BlockTime", "BlockSize", "TransactionCount"}
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
Blocks []Row `json:"blocks"`
}{true, orderedRows(rows, keys...)})
case "/api/v1/realtime/tx":
rows, ok := query("SELECT id,value AS Value,hash AS Hash,input_count AS InputCount,output_count AS OutputCount,transaction_time AS TxTime FROM transaction ORDER BY transaction_time DESC LIMIT 10")
if ok {
sendJSON(w, 200, struct {
Success bool `json:"success"`
Txs []Row `json:"txs"`
}{true, orderedRows(rows, "id", "Value", "Hash", "InputCount", "OutputCount", "TxTime")})
}
default:
if strings.HasPrefix(path, "/api/v1/address/") && strings.HasSuffix(path, "/balance") {
addr := strings.TrimSuffix(strings.TrimPrefix(path, "/api/v1/address/"), "/balance")
if addr == "" || strings.Contains(addr, "/") {
return false
}
rows, ok := query("SELECT id,balance FROM address WHERE address = ? LIMIT 1", addr)
if !ok {
return true
}
if len(rows) == 0 {
jsonError(w, 400, "Could not find address.")
return true
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
Balance any `json:"balance"`
}{true, struct {
Confirmed any `json:"confirmed"`
Unconfirmed int `json:"unconfirmed"`
}{rows[0]["balance"], 0}})
return true
}
if strings.HasPrefix(path, "/api/v1/charts/blocksize/") {
period := strings.TrimPrefix(path, "/api/v1/charts/blocksize/")
if strings.Contains(period, "/") {
return false
}
if r.Method != "GET" {
jsonError(w, 400, "Invalid HTTP request method.")
return true
}
durations := map[string]time.Duration{"24h": 24 * time.Hour, "72h": 72 * time.Hour, "168h": 168 * time.Hour, "30d": 30 * 24 * time.Hour, "90d": 90 * 24 * time.Hour}
start := s.now()
d, valid := durations[period]
if period == "1y" {
start = start.AddDate(-1, 0, 0)
valid = true
} else {
start = start.Add(-d)
}
if !valid {
jsonError(w, 400, "Invalid time period specified.")
return true
}
format, layout := "%Y-%m-%d", "2006-01-02"
if strings.HasSuffix(period, "h") {
format, layout = "%Y-%m-%d %H:00:00", "2006-01-02 15:00:00"
}
q := fmt.Sprintf("SELECT AVG(block_size) AS AvgBlockSize, DATE_FORMAT(FROM_UNIXTIME(block_time), '%s') AS TimePeriod FROM block WHERE DATE_FORMAT(FROM_UNIXTIME(block_time), '%s') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", format, format)
rows, ok := query(q, start.Format(layout))
if !ok {
return true
}
var data any = []any{}
if len(rows) > 0 {
m := map[string]any{}
for _, row := range rows {
m[fmt.Sprint(row["TimePeriod"])] = struct {
Avg float64 `json:"AvgBlockSize"`
}{number(row["AvgBlockSize"])}
}
data = m
}
sendJSON(w, 200, struct {
Success bool `json:"success"`
Data any `json:"data"`
}{true, data})
return true
}
return false
}
return true
}
-163
View File
@@ -1,163 +0,0 @@
package explorer
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
)
type fakeStore struct {
rows []Row
calls []string
args [][]any
}
func (f *fakeStore) Query(_ context.Context, q string, a ...any) ([]Row, error) {
f.calls = append(f.calls, q)
f.args = append(f.args, a)
return f.rows, nil
}
func TestStatus(t *testing.T) {
f := &fakeStore{rows: []Row{{"height": int64(25), "difficulty": 1234.567}}}
s := Server{Store: f}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/status", nil))
want := `{"success":true,"status":{"height":25,"difficulty":"1234.57","price":"N\/A","hashrate":"N\/A"}}`
if w.Body.String() != want {
t.Fatal(w.Body.String())
}
if !strings.Contains(f.calls[0], "ORDER BY height DESC LIMIT 1") {
t.Fatal(f.calls)
}
}
func TestBalanceBoundParameters(t *testing.T) {
f := &fakeStore{rows: []Row{}}
s := Server{Store: f}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/address/abc/balance", nil))
if w.Code != 400 || w.Body.String() != `{"error":true,"message":"Could not find address."}` {
t.Fatal(w.Code, w.Body.String())
}
if f.args[0][0] != "abc" || strings.Contains(f.calls[0], "abc") {
t.Fatal("address must be bound")
}
}
func TestChartValidationAndEmptyShape(t *testing.T) {
for _, tc := range []struct {
method, path, want string
code int
}{{"POST", "24h", `{"error":true,"message":"Invalid HTTP request method."}`, 400}, {"GET", "2h", `{"error":true,"message":"Invalid time period specified."}`, 400}, {"GET", "24h", `{"success":true,"data":[]}`, 200}} {
f := &fakeStore{rows: []Row{}}
s := Server{Store: f, Now: func() time.Time { return time.Date(2026, 11, 2, 13, 45, 0, 0, time.UTC) }}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest(tc.method, "/api/v1/charts/blocksize/"+tc.path, nil))
if w.Code != tc.code || w.Body.String() != tc.want {
t.Fatal(w.Code, w.Body.String())
}
if tc.code == 400 && len(f.calls) != 0 {
t.Fatal("invalid request queried DB")
}
if tc.code == 200 && f.args[0][0] != "2026-11-01 13:00:00" {
t.Fatal(f.args)
}
}
}
func TestPHPJSON(t *testing.T) {
b, e := phpJSON(struct {
Text string `json:"text"`
}{"<é/😀>"})
if e != nil || string(b) != `{"text":"<\u00e9\/\ud83d\ude00>"}` {
t.Fatal(string(b), e)
}
}
func TestCacheExpiry(t *testing.T) {
now := time.Unix(1000, 0)
c := Cache{Dir: t.TempDir(), Now: func() time.Time { return now }}
if e := c.Put("inflation", []byte(`{"a":1}`), 10*time.Minute); e != nil {
t.Fatal(e)
}
if b, ok := c.Get("inflation"); !ok || string(b) != `{"a":1}` {
t.Fatal(string(b), ok)
}
now = now.Add(10 * time.Minute)
if _, ok := c.Get("inflation"); ok {
t.Fatal("expired hit")
}
}
func TestAllTemplatesExecute(t *testing.T) {
s := Server{Now: func() time.Time { return time.Unix(1700000100, 0) }}
data := pageData{Tx: Row{"hash": "abc", "created_at": "2026-11-02 11:00:00", "value": 1, "input_count": 1, "output_count": 1}, Address: Row{"address": "abc"}, Claim: Row{"name": "claim", "claim_type": 1, "created_at": "2026-11-02 11:00:00"}, Title: "fixture", Highest: Row{"height": 50, "difficulty": 2}, RecentBlocks: []Row{{"height": 50, "difficulty": 2, "block_time": 1700000000, "block_size": 123, "tx_count": 1}}, RecentClaims: []Row{{"name": "safe <name>", "claim_id": "123", "claim_type": 1, "is_nsfw": 0, "thumbnail_url": "", "transaction_hash_id": "abc", "vout": 0}}, Block: Row{"height": 50, "difficulty": 2, "block_time": 1700000000, "block_size": 123}, Txs: []Row{}, Blocks: []Row{}, NumRecords: 50, PageLimit: 50, CurrentPage: 1, NumPages: 1, Begin: 1, End: 50}
for _, name := range []string{"home", "realtime", "block", "blocks", "claims", "find", "claim", "address", "stats", "tx"} {
t.Run(name, func(t *testing.T) {
w := httptest.NewRecorder()
s.render(w, httptest.NewRequest("GET", "http://explorer.lbry.com/", nil), name, data)
if w.Code != 200 {
t.Fatal(w.Body.String())
}
if !strings.Contains(w.Body.String(), "/css/main.css") {
t.Fatal("missing layout")
}
if strings.Contains(w.Body.String(), "#ZgotmplZ") {
t.Fatal("template URL rejected")
}
if name == "home" && !strings.Contains(w.Body.String(), "safe &lt;name&gt;") {
t.Fatal("claim text not escaped")
}
})
}
}
func TestHomepageFallbackAndPageRedirects(t *testing.T) {
for _, path := range []string{"/unknown", "/api/v1/address/abc/transactions", "/tag/abc", "/api/v1/address/abc/tag", "/api/v1/status/extra", "/css/missing.css", "/css/", "/embed.go"} {
f := &fakeStore{rows: []Row{}}
s := Server{Store: f}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
if w.Code != 200 || !strings.Contains(w.Body.String(), "LBRY Block Explorer &bull; Home") {
t.Fatalf("%s: %d %s", path, w.Code, w.Body.String())
}
}
for _, path := range []string{"/tx", "/tx/missing", "/blocks/-1", "/claims/missing", "/address/short"} {
f := &fakeStore{rows: []Row{}}
s := Server{Store: f}
w := httptest.NewRecorder()
s.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
if w.Code != 302 || w.Header().Get("Location") != "http://example.com/" {
t.Fatalf("%s: %d %s", path, w.Code, w.Body.String())
}
}
}
func TestDescriptionEscapesAndLinks(t *testing.T) {
got := string(description("See https://example.com/page\n<script>alert(1)</script>"))
if !strings.Contains(got, `<a href="https://example.com/page" target="_blank" rel="nofollow">https://example.com/page</a><br />`) {
t.Fatal(got)
}
if strings.Contains(got, "<script>") || !strings.Contains(got, "&lt;script&gt;") {
t.Fatal(got)
}
if string(safeURL("javascript:alert(1)")) != "#" {
t.Fatal("unsafe scheme")
}
}
func TestClaimEntityJSONTypes(t *testing.T) {
rows := claimEntities([]Row{{"is_nsfw": int64(0), "is_cert_valid": int64(1), "has_claim_list": nil, "created_at": "2026-11-02 12:00:00", "value_as_json": `{"text":"é"}`, "claim_type": int64(2)}})
r := rows[0]
if r["is_nsfw"] != false || r["is_cert_valid"] != true || r["has_claim_list"] != nil || r["created_at"] != "2026-11-02T12:00:00+00:00" || r["claim_type"] != int64(2) {
t.Fatal(r)
}
if _, ok := r["value_as_json"].(jsonObject); !ok {
t.Fatal(r)
}
}
func TestCachedJSONDoesNotDoubleEscape(t *testing.T) {
b, e := phpJSON(struct {
Data json.RawMessage `json:"data"`
}{json.RawMessage(`{"url":"https:\/\/example.com"}`)})
if e != nil || string(b) != `{"data":{"url":"https:\/\/example.com"}}` {
t.Fatal(string(b), e)
}
}
-86
View File
@@ -1,86 +0,0 @@
{{define "script"}}{{end}}{{define "css"}}{{end}}{{define "content"}}
{{template "header" .}}
<div class="address-head">
<h3>LBRY Address</h3>
<h4>{{$.Address.address}}</h4>
{{if trim .Address.Tag}}
{{if trim .Address.TagUrl}}<a href="{{safeURL .Address.TagUrl}}" target="_blank" rel="nofollow">{{$.Address.Tag}}</a>{{else}}{{.Address.Tag}}{{end}}
{{end}}
</div>
<div class="address-subhead">
<div class="address-qr">
<img src="/qr/lbry%3A{{$.Address.address}}" alt="lbry:{{$.Address.address}}" />
</div>
<div class="address-summary">
<div class="box">
<div class="title">Balance (LBC)</div>
<div class="value">{{amount .BalanceAmount ","}}</div>
</div>
<div class="box">
<div class="title">Received (LBC)</div>
<div class="value">{{amount .TotalReceived ","}}</div>
</div>
<div class="box last">
<div class="title">Sent (LBC)</div>
<div class="value">{{amount .TotalSent ","}}</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="recent-transactions">
<h3>Transactions</h3>
<div class="results-meta">
{{if gt .NumRecords 0}}
Showing {{grouped .Begin 0}} - {{grouped .End 0}} of {{grouped .NumRecords 0}} transaction{{if ne .NumRecords 1}}s{{end}}
{{end}}
</div>
<table class="table tx-table">
<thead>
<tr>
<th class="w125 left">Height</th>
<th class="w250 left">Transaction Hash</th>
<th class="left">Timestamp</th>
<th class="w125 right">Confirmations</th>
<th class="w80 right">Inputs</th>
<th class="w80 right">Outputs</th>
<th class="w225 right">Amount</th>
</tr>
</thead>
<tbody>
{{if not .RecentTxs}}
<tr>
<td class="nodata" colspan="7">There are no recent transactions to display for this wallet.</td>
</tr>
{{end}}
{{range $tx := .RecentTxs}}
<tr>
<td class="w125">{{if eq $tx.height nil}}<em>Unconfirmed</em>{{else}}<a href="/blocks/{{$tx.height}}">{{$tx.height}}</a>{{end}}</td>
<td class="w250"><div><a href="/tx/{{$tx.hash}}?address={{$.Address.address}}#{{$.Address.address}}">{{$tx.hash}}</a></div></td>
<td>{{date $tx.transaction_time "02 Jan 2006 15:04:05"}} UTC</td>
<td class="right">{{grouped $tx.confirmations 0}}</td>
<td class="right">{{$tx.input_count}}</td>
<td class="right">{{$tx.output_count}}</td>
<td class="right {{txClass $tx}}">
{{grouped (difference $tx.credit_amount $tx.debit_amount) 8}} LBC
</td>
</tr>
{{end}}
</tbody>
</table>
</div>
{{template "pagination" .}}
{{end}}
-125
View File
@@ -1,125 +0,0 @@
{{define "content"}}{{template "header" .}}
<div class="block-head">
<h3>LBRY Block {{.Block.height}}</h3>
<h4>{{.Block.hash}}</h4>
</div>
<div class="block-nav">
{{if gt (num .Block.height) 0.0}}
<a class="btn btn-prev" href="/blocks/{{sub .Block.height 1}}">&laquo; Previous Block</a>
{{end}}
<a class="btn btn-next" href="/blocks/{{add .Block.height 1}}">Next Block &raquo;</a>
<div class="clear"></div>
</div>
<div class="block-info">
<div class="block-summary">
<h3>Overview</h3>
<div class="label half-width">Block Size (bytes)</div>
<div class="label half-width">Block Time</div>
<div class="value half-width">{{grouped .Block.block_size 0}}</div>
<div class="value half-width">{{date .Block.block_time "2 Jan 2006 15:04:05"}} UTC</div>
<div class="clear spacer"></div>
<div class="label half-width">Bits</div>
<div class="label half-width">Confirmations</div>
<div class="value half-width">{{.Block.bits}}</div>
<div class="value half-width">{{.Confirmations}}</div>
<div class="clear spacer"></div>
<div class="label half-width">Difficulty</div>
<div class="label half-width">Nonce</div>
<div class="value half-width">{{amount .Block.difficulty ""}}</div>
<div class="value half-width">{{.Block.nonce}}</div>
<div class="clear spacer"></div>
<div class="label">Chainwork</div> <div class="value">{{.Block.chainwork}}</div>
<div class="spacer"></div>
<div class="label">MerkleRoot</div> <div class="value">{{.Block.merkle_root}}</div>
<div class="spacer"></div>
<div class="label">NameClaimRoot</div> <div class="value">{{.Block.name_claim_root}}</div>
<!--
<div class="spacer"></div>
<div class="label">Target</div> <div class="value">{{.Block.Target}}</div>
-->
<div class="spacer"></div>
<div class="label">Version</div> <div class="value">{{.Block.version}}</div>
</div>
<div class="block-transactions">
<h3>{{len .Txs}} Transaction{{if ne (len .Txs) 1}}s{{end}}</h3>
<div class="transactions-list">
<table class="table">
<thead>
<tr>
<th>Hash</th>
<th class="w100 right">Inputs</th>
<th class="w100 right">Outputs</th>
<th class="w200 right">Value</th>
</tr>
</thead>
<tbody>
{{if not .Txs}}
<tr>
<td class="nodata" colspan="4">There are no transactions to display at this time.</td>
</tr>
{{end}}
{{range $tx := .Txs}}
<tr>
<td class="w300"><div><a href="/tx/{{$tx.hash}}">{{$tx.hash}}</a></div></td>
<td class="right">{{$tx.input_count}}</td>
<td class="right">{{$tx.output_count}}</td>
<td class="right"><div title="{{text $tx.value}} LBC">{{currency $tx.value}} LBC</div></td>
</tr>
{{end}}
</tbody>
</table>
</div>
</div>
</div>
<div class="clear"></div>
{{end}}{{define "script"}}
<script type="text/javascript">
var resizeCards = function() {
var bSummary = $('.block-summary');
var bTransactions = $('.block-transactions');
if (bTransactions.outerHeight() < bSummary.outerHeight()) {
bTransactions.outerHeight(bSummary.outerHeight());
}
};
$(document).ready(function() {
resizeCards();
});
window.onload = function() {
resizeCards();
};
</script>
{{end}}{{define "css"}}{{end}}
-63
View File
@@ -1,63 +0,0 @@
{{define "script"}}<script type="text/javascript" src="/amcharts/amcharts.js"></script>
<script type="text/javascript" src="/amcharts/serial.js"></script>
<script type="text/javascript" src="/amcharts/plugins/export/export.min.js"></script>
<script type="text/javascript" src="/js/block-size-chart.js"></script>
{{end}}{{define "content"}}{{template "header" .}}
<div class="block-head">
<h3>LBRY Blocks</h3>
</div>
<div class="block-size-chart-container">
<div class="load-progress inc"></div>
<h3>Block Size Chart</h3>
<div class="block-size-data-links">
<a href="#" title="24 hours" data-period="24h">24h</a>
<a href="#" title="72 hours" data-period="72h">72h</a>
<a href="#" title="1 week" data-period="168h">1w</a>
<a href="#" title="30 days" data-period="30d">30d</a>
<a href="#" title="90 days" data-period="90d">90d</a>
<a href="#" title="1 year" data-period="1y">1y</a>
</div>
<div id="block-size-chart" class="chart"></div>
<div id="chart-export" class="btn-chart-export"></div>
</div>
<div class="all-blocks">
<h3>All Blocks</h3>
<div class="results-meta">
{{if gt .NumRecords 0}}
Showing {{grouped .Begin 0}} - {{grouped .End 0}} of {{grouped .NumRecords 0}} block{{if ne .NumRecords 1}}s{{end}}
{{end}}
</div>
<table class="table">
<thead>
<tr>
<th class="w100">Height</th>
<th class="w150 left pad-left">Difficulty</th>
<th class="w100 right">Confirmations</th>
<th class="w100 right">TX Count</th>
<th class="w100 right">Block Size</th>
<th class="w100 right pad-left">Nonce</th>
<th class="w150 left pad-left">Block Time</th>
</tr>
</thead>
<tbody>
{{range $block := .Blocks}}
<tr>
<td class="right"><a href="/blocks/{{$block.height}}">{{$block.height}}</a></td>
<td class="pad-left">{{fixed $block.difficulty 8}}</td>
<td class="right">{{grouped (add (sub $.Highest.height $block.height) 1) 0}}</td>
<td class="right">{{$block.tx_count}}</td>
<td class="right">{{kb $block.block_size}}</td>
<td class="right pad-left">{{$block.nonce}}</td>
<td class="pad-left">{{date $block.block_time "02 Jan 2006 15:04:05"}} UTC</td>
</tr>
{{end}}
</tbody>
</table>
</div>
{{template "pagination" .}}
{{end}}{{define "css"}}<link rel="stylesheet" href="/amcharts/plugins/export/export.css">{{end}}
-140
View File
@@ -1,140 +0,0 @@
{{define "script"}}<script type="text/javascript">
var resizeCards = function() {
var claimInfo = $('.claim-info');
var claimMtdt = $('.claim-metadata');
if (claimMtdt.outerHeight() < claimInfo.outerHeight()) {
claimMtdt.outerHeight(claimInfo.outerHeight());
} else if (claimInfo.outerHeight() < claimMtdt.outerHeight()) {
claimInfo.outerHeight(claimMtdt.outerHeight());
}
};
window.onload = function() {
resizeCards();
};
$(document).ready(function() {
resizeCards();
$('.claim-grid-item img,.claim-info img').on('error', function() {
var img = $(this);
var parent = img.parent();
var text = parent.attr('data-autothumb');
img.remove();
parent.append(
$('<div></div>').attr({'class': 'autothumb' }).text(text)
);
});
$(document).on('click', '.claim-grid-item', function() {
var id = $(this).attr('data-id');
location.href = '/claims/' + id;
});
});
</script>
{{end}}{{define "css"}}{{end}}{{define "content"}}{{template "header" .}}{{$claim := .Claim}}<div class="claims-head">
<h3><a href="/claims">LBRY Claims</a> &bull; {{$claim.name}}</h3>
<h4>{{$claim.claim_id}}</h4>
</div>
<div class="claims-body">
{{if .ClaimIsBlocked}}
<div class="blocked-claim-info">
<div class="content">
In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications. For more information, please refer to <a href="https://lbry.com/faq/dmca" target="_blank">DMCA takedown requests</a>.
</div>
</div>
{{else}}
<div class="claim-info">
<div data-autothumb="{{autoThumb $claim}}" class="thumbnail {{thumbColor}}">
{{if showThumbnail $claim}}
<img src="{{thumbnail $claim.thumbnail_url}}" alt="" />
{{else}}
<div class="autothumb">{{autoThumb $claim}}</div>
{{end}}
</div>
<div class="content">
{{if eq (num $claim.claim_type) 1.0}}
<div class="label">Published By</div>
<div class="value">
{{if isset $claim "publisher"}}
<a {{publisherHref $claim.publisher}}>{{$claim.publisher}}</a>
{{else}}
<em>Anonymous</em>
{{end}}
</div>
{{end}}
<div class="label">Created On</div>
<div class="value">{{claimDate $claim}} UTC</div>
<div class="label">Transaction ID</div>
<div class="value"><a href="/tx/{{$claim.transaction_hash_id}}#output-{{$claim.vout}}">{{$claim.transaction_hash_id}}</a></div>
{{if eq (num $claim.claim_type) 1.0}}
<div class="label half-width">Cost</div>
<div class="label half-width">Safe for Work</div>
<div class="value half-width">{{if claimCost $claim}}{{claimCost $claim}}{{else}}Free{{end}}</div>
<div class="value half-width">{{if truth $claim.is_nsfw}}No{{else}}Yes{{end}}</div>
<div class="clear"></div>
{{end}}
</div>
</div>
<div class="claim-metadata">
{{if eq (num $claim.claim_type) 2.0}}
<div class="title">Identity Claim</div>
<div class="desc">This is an identity claim.</div>
{{else}}
<div class="title">{{$claim.title}}</div>
<div class="desc">{{description $claim.description}}</div>
<div class="details">
<div class="label half-width">Author</div>
<div class="label half-width">Content Type</div>
<div class="value half-width">{{if trim $claim.author}}{{$claim.author}}{{else}}<em>Unspecified</em>{{end}}</div>
<div class="value half-width">{{if trim $claim.content_type}}{{$claim.content_type}}{{else}}<em>Unspecified</em>{{end}}</div>
<!--
<div class="label half-width">License</div>
-->
<div class="label">Language</div>
<!--
<div class="value half-width"{{if trim $claim.license}} title="{{$claim.license}}"{{end}}>
{{if trim $claim.License}}{{$claim.License}}{{else}}<em>Unspecified</em>{{end}}
</div>
-->
<div class="value half-width">{{if trim $claim.language}}{{if eq $claim.language "en"}}English{{end}}{{else}}<em>Unspecified</em>{{end}}</div>
</div>
{{end}}
<a {{lbryHref $claim}} class="open-lbry-link">Open in LBRY</a>
</div>
<div class="clear"></div>
{{end}}
{{if .MoreClaims}}
<div class="more-claims">
<h4>{{if isset $claim "publisher"}}More from the publisher{{else}}Published by this identity{{end}}</h4>
<div class="claims-grid">
{{range .Cards}}{{template "claimbox" .}}{{end}}
<div class="clear"></div>
</div>
</div>
{{end}}
</div>
{{end}}
-61
View File
@@ -1,61 +0,0 @@
{{define "claimbox"}}{{$claim := .Claim}}<div data-id="{{$claim.claim_id}}" class="claim-grid-item{{if .LastItem}} last-item{{end}}{{if .LastRow}} last-row{{end}}">
{{if claimCost .Claim}}
<div class="price-tag">{{claimCost .Claim}}</div>
{{end}}
<div class="tags">
{{if eq $claim.bid_state "Controlling"}}
<div class="bid-state">Controlling</div>
{{end}}
{{if contentTag $claim}}
<div class="content-type">{{contentTag $claim}}</div>
{{end}}
{{if truth $claim.is_nsfw}}
<div class="nsfw">NSFW</div>
{{end}}
</div>
<div data-autothumb="{{autoThumb $claim}}" class="thumbnail {{thumbColor}}">
{{if showThumbnail $claim}}
<img src="{{thumbnail $claim.thumbnail_url}}" alt="" />
{{else}}
<div class="autothumb">{{autoThumb $claim}}</div>
{{end}}
</div>
{{if truth $claim.isBlocked}}
<div class="blocked-info">
In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications. For more information, please refer to <a href="https://lbry.com/faq/dmca" target="_blank">DMCA takedown requests</a>
</div>
{{else}}
<div class="metadata">
<div class="title" title="{{claimTitle $claim}}">{{if claimTitle $claim}}{{claimTitle $claim}}{{else}}<em>No Title</em>{{end}}</div>
<div class="link" title="{{lbryLink $claim}}"><a {{lbryHref $claim}} rel="nofollow">{{lbryLink $claim}}</a></div>
<div class="desc">{{if trim $claim.description}}{{$claim.description}}{{else}}<em>No description available</em>{{end}}</div>
<div class="label half-width">Transaction</div>
<div class="label half-width">Created</div>
<div class="value half-width"><a href="/tx/{{$claim.transaction_hash_id}}#output-{{$claim.vout}}" title="{{$claim.transaction_hash_id}}">{{$claim.transaction_hash_id}}</a></div>
<div class="value half-width" title="{{date $claim.created_at "2 Jan 2006 15:04:05"}} UTC">
{{ago $claim.created_at}}
</div>
<div class="clear spacer"></div>
{{if eq (num $claim.claim_type) 1.0}}
<div class="label half-width">Content Type</div>
<div class="label half-width">Language</div>
<div class="value half-width" title="{{$claim.content_type}}">{{$claim.content_type}}</div>
<div class="value half-width" title="{{language $claim.language}}">{{language $claim.language}}</div>
<div class="clear spacer"></div>
{{end}}
</div>
{{end}}
</div>
{{end}}
-47
View File
@@ -1,47 +0,0 @@
{{define "script"}}<script type="text/javascript">
var resizeCards = function() {
var claimInfo = $('.claim-info');
var claimMtdt = $('.claim-metadata');
if (claimMtdt.outerHeight() < claimInfo.outerHeight()) {
claimMtdt.outerHeight(claimInfo.outerHeight());
} else if (claimInfo.outerHeight() < claimMtdt.outerHeight()) {
claimInfo.outerHeight(claimMtdt.outerHeight());
}
};
window.onload = function() {
resizeCards();
};
$(document).ready(function() {
resizeCards();
$('.claim-grid-item img,.claim-info img').on('error', function() {
var img = $(this);
var parent = img.parent();
var text = parent.attr('data-autothumb');
img.remove();
parent.append(
$('<div></div>').attr({'class': 'autothumb' }).text(text)
);
});
$(document).on('click', '.claim-grid-item', function() {
var id = $(this).attr('data-id');
location.href = '/claims/' + id;
});
});
</script>
{{end}}{{define "css"}}{{end}}{{define "content"}}{{template "header" .}}<div class="claims-head">
<h2>Claims Explorer</h2>
</div>
<div class="claims-grid">
{{range .Cards}}{{template "claimbox" .}}{{end}}
<div class="clear"></div>
</div>
{{template "pagination" .}}
{{end}}
-25
View File
@@ -1,25 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <title>
Error </title>
<link href="/favicon.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" href="/css/base.css"> <link rel="stylesheet" href="/css/cake.css">
</head>
<body>
<div id="container">
<div id="header">
<h1>Error</h1>
</div>
<div id="content">
<h2>{{.Message}}</h2>
<p class="error">
<strong>Error: </strong>
The requested address <strong>'{{.URL}}'</strong> was not found on this server.</p>
</div>
<div id="footer">
<a href="javascript:history.back()">Back</a> </div>
</div>
</body>
</html>
-25
View File
@@ -1,25 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <title>
Error </title>
<link href="/favicon.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" href="/css/base.css"> <link rel="stylesheet" href="/css/cake.css">
</head>
<body>
<div id="container">
<div id="header">
<h1>Error</h1>
</div>
<div id="content">
<h2>An Internal Error Has Occurred</h2>
<p class="error">
<strong>Error: </strong>
An Internal Error Has Occurred.</p>
</div>
<div id="footer">
<a href="javascript:history.back()">Back</a> </div>
</div>
</body>
</html>
-49
View File
@@ -1,49 +0,0 @@
{{define "script"}}<script type="text/javascript">
var resizeCards = function() {
var claimInfo = $('.claim-info');
var claimMtdt = $('.claim-metadata');
if (claimMtdt.outerHeight() < claimInfo.outerHeight()) {
claimMtdt.outerHeight(claimInfo.outerHeight());
} else if (claimInfo.outerHeight() < claimMtdt.outerHeight()) {
claimInfo.outerHeight(claimMtdt.outerHeight());
}
};
window.onload = function() {
resizeCards();
};
$(document).ready(function() {
resizeCards();
$('.claim-grid-item img,.claim-info img').on('error', function() {
var img = $(this);
var parent = img.parent();
var text = parent.attr('data-autothumb');
img.remove();
parent.append(
$('<div></div>').attr({'class': 'autothumb' }).text(text)
);
});
$(document).on('click', '.claim-grid-item', function() {
var id = $(this).attr('data-id');
location.href = '/claims/' + id;
});
});
</script>
{{end}}{{define "css"}}{{end}}{{define "content"}}{{template "header" .}}<div class="claims-head">
<h3>Search results</h3>
</div>
<div class="claims-grid">
{{if .Claims}}
{{range .Cards}}{{template "claimbox" .}}{{end}}
{{else}}
<div class="no-results">No results were found.</div>
{{end}}
<div class="clear"></div>
</div>
{{template "pagination" .}}
{{end}}
@@ -1,25 +0,0 @@
{{define "pagination"}}{{with .Pagination}}{{if .Visible}}
<div class="pagination">
<div class="prev">
&nbsp;
{{if .Previous}}<a href="?page={{.Previous}}">Previous</a>{{end}}
</div>
<div class="pages">
{{if .StartEllipsis}}<div class="page-number"><a href="?page=1">1</a></div>
<div class="page-number">...</div>
{{end}}
{{range .Pages}}<div class="page-number">
{{if eq $.Pagination.Current .}}{{.}}{{else}}<a href="?page={{.}}">{{.}}</a>{{end}}
</div>
{{end}}
{{if .EndEllipsis}}<div class="page-number">...</div>
<div class="page-number"><a href="?page={{.Last}}">{{.Last}}</a></div>
{{end}}
</div>
<div class="next">
&nbsp;
{{if .Next}}<a href="?page={{.Next}}">Next</a>{{end}}
</div>
<div class="clear"></div>
</div>
{{end}}{{end}}{{end}}
-59
View File
@@ -1,59 +0,0 @@
{{define "script"}}<script src="/amcharts/amcharts.js"></script>
<script src="/amcharts/serial.js"></script>
<script src="/amcharts/plugins/export/export.min.js"></script>
<script src="/amcharts/plugins/responsive/responsive.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/js/mining-inflation-chart.js?v={{.InflationChartVersion}}"></script>
{{end}}{{define "css"}}<link rel="stylesheet" href="/css/mining-inflation-chart.css"><link rel="stylesheet" href="/amcharts/plugins/export/export.css">{{end}}{{define "content"}}{{template "header" .}}<div class="stats-head">
<h3>LBRY Stats</h3>
</div>
<div class="stats-main">
<div class="mining-inflation-chart-container">
<div class="load-progress inc"></div>
<h3>Mining Inflation Chart</h3>
<div id="mining-inflation-chart" class="chart"></div>
<div id="chart-export" class="btn-chart-export"></div>
</div>
<div class="richlist">
<h3>LBRY Rich List (Top 500)</h3>
<table class="table">
<thead>
<tr>
<th class="w50 right">Rank</th>
<th class="w300 left">Address</th>
<th class="w150 right">Balance (LBC)</th>
<th class="w150 right">Balance (USD)</th>
<th class="w200 left med-pad-left">First Seen</th>
<th class="w200 center">% Top 500</th>
</tr>
</thead>
<tbody>
{{range $i,$item := .RichList}}
<tr>
<td class="right topvalign">{{add $i 1}}</td>
<td class="topvalign"><a href="/address/{{$item.address}}" target="_blank">{{$item.address}}</a>
{{if ownedAddress $item.address}}
<span class="lbry-address">
<img src="/img/lbry.png" height="18px" width="18px" title="Address owned by LBRY Inc."/>
</span>
{{end}}
{{if trim $item.Tag}}
<div class="tag">
{{if trim $item.TagUrl}}<a href="{{safeURL $item.TagUrl}}" target="_blank" rel="nofollow">{{$item.Tag}}</a>{{else}}{{$item.Tag}}{{end}}
</div>
{{end}}</td>
<td class="right topvalign">{{grouped $item.balance 8}}</td>
<td class="right topvalign">$0.00</td>
<td class="med-pad-left topvalign">{{date $item.first_seen "02 Jan 2006 15:04:05"}} UTC</td>
<td class="w150 center top500-percent-cell"><div class="top500-percent" style="width: {{text $item.MinMaxPercent}}%"></div><div class="text">{{fixed $item.Top500Percent 5}}%</div></td>
</tr>
{{end}}
</tbody>
</table>
</div>
<div class="clear"></div>
</div>
{{end}}
-150
View File
@@ -1,150 +0,0 @@
{{define "script"}}
<script type="text/javascript">
$(document).ready(function() {
if (location.hash && (location.hash.indexOf('input-') > -1 || location.hash.indexOf('output-') > -1)) {
$(location.hash).addClass('highlighted');
}
});
</script>
{{end}}{{define "css"}}{{end}}{{define "content"}}
{{template "header" .}}
<div class="tx-head">
<h3>LBRY Transaction</h3>
<h4>{{.Tx.hash}}</h4>
</div>
<div class="tx-time">
<div class="created-time">
<h3 title="Represents the time this transaction was created on the explorer">Time Created</h3>
<div>{{date .Tx.created_at "2 Jan 2006 15:04:05"}} UTC </div>
</div>
<div class="conf-time">
<h3 title="The time the first confirmation of this transaction happened on the blockchain">Block Time</h3>
<div>{{if not (trim .Tx.transaction_time)}}<em>Not yet confirmed</em>{{else}}{{date .Tx.transaction_time "2 Jan 2006 15:04:05"}} UTC{{end}}
{{confirmationDelay .Tx}}
</div>
</div>
<div class="clear"></div>
</div>
<div class="tx-summary">
<div class="box p25">
<div class="title">Amount (LBC)</div>
<div class="value">{{amount .Tx.value ","}}</div>
</div>
<div class="box p15">
<div class="title">Block Height</div>
{{if not (trim .Tx.block_hash_id)}}
<div class="value" title="Unconfirmed">Unconf.</div>
{{else}}
<div class="value" title="{{.Tx.block_hash_id}}"><a href="/blocks/{{.Block.height}}">{{.Block.height}}</a></div>
{{end}}
</div>
<div class="box p15">
<div class="title">Confirmations</div>
<div class="value">{{.Confirmations}}</div>
</div>
<div class="box p15">
<div class="title">Size (bytes)</div>
<div class="value">{{grouped .Tx.transaction_size 0}}</div>
</div>
<div class="box p15">
<div class="title">Inputs</div>
<div class="value">{{.Tx.input_count}}</div>
</div>
<div class="box p15 last">
<div class="title">Outputs</div>
<div class="value">{{.Tx.output_count}}</div>
</div>
<div class="clear"></div>
</div>
<div class="tx-details">
<h3>Details</h3>
<div class="tx-details-layout">
<div class="inputs">
<div class="subtitle">{{.Tx.input_count}} input{{if ne (num .Tx.input_count) 1.0}}s{{end}}</div>
{{range $in := .Inputs}}
<div id="input-{{$in.Row.id}}" class="input {{if $in.Source}}is-source{{end}}">
{{if truth $in.Row.is_coinbase}}
<div>Block Reward (New Coins)</div>
{{else}}
{{if not (trim $in.Row.value)}}
<div>Incomplete data</div>
{{else}}{{if $in.Anchor}}
<a id="{{$in.Address.address}}"></a>
{{end}}
<div><span class="value">{{amount $in.Row.value ","}} LBC</span> from</div>
<div class="address"><a href="/address/{{$in.Address.address}}">{{$in.Address.address}}</a>
(<a class="output-link" href="/tx/{{$in.Row.prevout_hash}}#output-{{$in.Row.prevout_n}}">output</a>)
{{if trim $in.Address.Tag}}
<div class="tag">
{{if trim $in.Address.TagUrl}}<a href="{{safeURL $in.Address.TagUrl}}" target="_blank" rel="nofollow">{{$in.Address.Tag}}</a>{{else}}{{$in.Address.Tag}}{{end}}
</div>
{{end}}
</div>
{{end}}
{{end}}
</div>
{{end}}
</div>
<div class="divider">
<img src="/img/right-arrow.png" alt="" />
</div>
<div class="outputs">
<div class="subtitle">{{.Tx.output_count}} output{{if ne (num .Tx.output_count) 1.0}}s{{end}}
{{if gt (num .Fee) 0.0}}
<span class="fee"><span class="label">Fee</span> <span class="value">{{amount .Fee ","}} LBC</span></span>
{{end}}
</div>
{{range $out := .Outputs}}
<div id="output-{{$out.Row.vout}}" class="output {{if $out.Source}}is-source{{end}}">
<div class="labels">
{{if and $out.Row.Claim (or $out.Row.IsClaim $out.Row.IsSupportClaim $out.Row.IsUpdateClaim)}}<a class="view-claim" href="/claims/{{$out.Row.Claim.claim_id}}">View</a>{{end}}
{{if $out.Row.IsSupportClaim}}<div class="support">SUPPORT</div>{{end}}
{{if $out.Row.IsUpdateClaim}}<div class="update">UPDATE</div>{{end}}
{{if $out.Row.IsClaim}}<div class="claim">CLAIM</div>{{end}}
</div>
{{if not (trim $out.Row.value)}}
<div>Incomplete data</div>
{{else}}{{if $out.Anchor}}
<a id="{{$out.Address.address}}"></a>
{{end}}
<div><span class="value">{{amount $out.Row.value ","}} LBC</span> to</div>
<div class="address"><a href="/address/{{$out.Address.address}}">{{$out.Address.address}}</a>
{{if truth $out.Row.is_spent}}(<a href="/tx/{{if $out.Row.spend_input_id}}{{$out.Row.spend_input_hash}}{{end}}#input-{{if $out.Row.spend_input_id}}{{$out.Row.spend_input_id}}{{end}}">spent</a>){{else}}(unspent){{end}}
{{if trim $out.Address.Tag}}
<div class="tag">
{{if trim $out.Address.TagUrl}}<a href="{{safeURL $out.Address.TagUrl}}" target="_blank" rel="nofollow">{{$out.Address.Tag}}</a>{{else}}{{$out.Address.Tag}}{{end}}
</div>
{{end}}
</div>
{{end}}
</div>
{{end}}
</div>
</div>
</div>
{{end}}
-161
View File
@@ -1,161 +0,0 @@
{
"queries": [
{
"raw": "q=one&q=two",
"q": "two",
"page": 0
},
{
"raw": "q[]=hello",
"q": "Array",
"page": 0
},
{
"raw": "q=abc%ZZ",
"q": "abc%ZZ",
"page": 0
},
{
"raw": "q=%2B%20x",
"q": "+ x",
"page": 0
},
{
"raw": "page=9007199254740993",
"q": "",
"page": 9007199254740993
},
{
"raw": "page=9223372036854775807",
"q": "",
"page": 9223372036854775807
},
{
"raw": "page=9223372036854775808",
"q": "",
"page": 9223372036854775807
},
{
"raw": "page=-9223372036854775809",
"q": "",
"page": -9223372036854775808
},
{
"raw": "page=1e3",
"q": "",
"page": 1000
},
{
"raw": "page[]=2",
"q": "",
"page": 1
},
{
"raw": "page=3&page[x]=2",
"q": "",
"page": 1
},
{
"raw": "page[x]=2&page=3",
"q": "",
"page": 3
},
{
"raw": "page[broken=2",
"q": "",
"page": 0
}
],
"blocked": [
{
"claim": "blocked",
"publisher": null,
"body": "{\"data\":[{\"claim_id\":12},{\"claim_id\":\"blocked\"}]}",
"expected": true
},
{
"claim": "blocked",
"publisher": null,
"body": "{\"data\":[null,\"bad\",{}, {\"claim_id\":\"blocked\"}]}",
"expected": true
},
{
"claim": "blocked",
"publisher": null,
"body": "{\"data\":[{\"claim_id\":true}]}",
"expected": true
},
{
"claim": "blocked",
"publisher": null,
"body": "{\"data\":[{\"claim_id\":false}]}",
"expected": false
},
{
"claim": "",
"publisher": null,
"body": "{\"data\":[{}]}",
"expected": true
},
{
"claim": "0000000000000000000000000000000000000001",
"publisher": null,
"body": "{\"data\":[{\"claim_id\":1}]}",
"expected": true
},
{
"claim": "0000000000000000000000000000000000000001",
"publisher": null,
"body": "{\"data\":[{\"claim_id\":\"1\"}]}",
"expected": true
},
{
"claim": "not-blocked",
"publisher": "publisher",
"body": "{\"data\":[{\"claim_id\":\"publisher\"}]}",
"expected": true
},
{
"claim": "not-blocked",
"publisher": "0",
"body": "{\"data\":[{\"claim_id\":\"0\"}]}",
"expected": false
},
{
"claim": "blocked",
"publisher": null,
"body": "{\"data\":{\"0\":{\"claim_id\":\"blocked\"}}}",
"expected": false
},
{
"claim": "blocked",
"publisher": null,
"body": "not JSON",
"expected": false
},
{
"claim": "blocked",
"publisher": null,
"body": "{\"Data\":[{\"claim_id\":\"blocked\"}]}",
"expected": false
},
{
"claim": "blocked",
"publisher": null,
"body": "{\"data\":[{\"claim_id\":\"\\u0000true\"}]}",
"expected": false
},
{
"claim": "blocked",
"publisher": null,
"body": "{\"data\":[{\"claim_id\":\"blocked\",\"junk\":\"\\ud800\"}]}",
"expected": false
},
{
"claim": "blocked",
"publisher": null,
"body_base64": "eyJkYXRhIjpbeyJjbGFpbV9pZCI6ImJsb2NrZWQiLCJqdW5rIjoi\/yJ9XX0=",
"expected": false
}
]
}
-446
View File
@@ -1,446 +0,0 @@
{
"rounds": [
{
"value": 1.005,
"places": 0,
"expected": "1"
},
{
"value": 1.005,
"places": 2,
"expected": "1.01"
},
{
"value": 1.005,
"places": 5,
"expected": "1.00500"
},
{
"value": 1.005,
"places": 8,
"expected": "1.00500000"
},
{
"value": 1.0049999999999997,
"places": 0,
"expected": "1"
},
{
"value": 1.0049999999999997,
"places": 2,
"expected": "1.00"
},
{
"value": 1.0049999999999997,
"places": 5,
"expected": "1.00500"
},
{
"value": 1.0049999999999997,
"places": 8,
"expected": "1.00500000"
},
{
"value": 2.675,
"places": 0,
"expected": "3"
},
{
"value": 2.675,
"places": 2,
"expected": "2.68"
},
{
"value": 2.675,
"places": 5,
"expected": "2.67500"
},
{
"value": 2.675,
"places": 8,
"expected": "2.67500000"
},
{
"value": -1.005,
"places": 0,
"expected": "-1"
},
{
"value": -1.005,
"places": 2,
"expected": "-1.01"
},
{
"value": -1.005,
"places": 5,
"expected": "-1.00500"
},
{
"value": -1.005,
"places": 8,
"expected": "-1.00500000"
},
{
"value": -0,
"places": 0,
"expected": "0"
},
{
"value": -0,
"places": 2,
"expected": "0.00"
},
{
"value": -0,
"places": 5,
"expected": "0.00000"
},
{
"value": -0,
"places": 8,
"expected": "0.00000000"
},
{
"value": -1.0e-9,
"places": 0,
"expected": "0"
},
{
"value": -1.0e-9,
"places": 2,
"expected": "0.00"
},
{
"value": -1.0e-9,
"places": 5,
"expected": "0.00000"
},
{
"value": -1.0e-9,
"places": 8,
"expected": "0.00000000"
},
{
"value": 0.285,
"places": 0,
"expected": "0"
},
{
"value": 0.285,
"places": 2,
"expected": "0.29"
},
{
"value": 0.285,
"places": 5,
"expected": "0.28500"
},
{
"value": 0.285,
"places": 8,
"expected": "0.28500000"
},
{
"value": 1234567890.1234,
"places": 0,
"expected": "1234567890"
},
{
"value": 1234567890.1234,
"places": 2,
"expected": "1234567890.12"
},
{
"value": 1234567890.1234,
"places": 5,
"expected": "1234567890.12340"
},
{
"value": 1234567890.1234,
"places": 8,
"expected": "1234567890.12339997"
}
],
"json": [
{
"value": 1.0e-5,
"encoded": "1.0e-5"
},
{
"value": 0.0001,
"encoded": "0.0001"
},
{
"value": 1.0e-7,
"encoded": "1.0e-7"
},
{
"value": 10000000000000000,
"encoded": "10000000000000000"
},
{
"value": 1.0e+17,
"encoded": "1.0e+17"
},
{
"value": 1.0e+20,
"encoded": "1.0e+20"
},
{
"value": 1.0e+21,
"encoded": "1.0e+21"
},
{
"value": -0,
"encoded": "-0"
},
{
"value": 1.2345678901234567,
"encoded": "1.2345678901234567"
},
{
"value": 9223372036854775807,
"encoded": "9223372036854775807"
}
],
"now": 1793620800,
"dates": [
{
"timestamp": 1793620800,
"ago": "just now",
"human": "0 seconds ago"
},
{
"timestamp": 1793620799,
"ago": "1 second ago",
"human": "1 second ago"
},
{
"timestamp": 1793620798,
"ago": "2 seconds ago",
"human": "2 seconds ago"
},
{
"timestamp": 1793620741,
"ago": "59 seconds ago",
"human": "59 seconds ago"
},
{
"timestamp": 1793620740,
"ago": "1 minute ago",
"human": "1 minute ago"
},
{
"timestamp": 1793620739,
"ago": "1 minute ago",
"human": "1 minute ago"
},
{
"timestamp": 1793617201,
"ago": "59 minutes ago",
"human": "59 minutes ago"
},
{
"timestamp": 1793617200,
"ago": "1 hour ago",
"human": "1 hour ago"
},
{
"timestamp": 1793617199,
"ago": "1 hour ago",
"human": "1 hour ago"
},
{
"timestamp": 1793534401,
"ago": "23 hours, 59 minutes ago",
"human": "23 hours ago"
},
{
"timestamp": 1793534400,
"ago": "1 day ago",
"human": "1 day ago"
},
{
"timestamp": 1793016001,
"ago": "6 days, 23 hours ago",
"human": "6 days ago"
},
{
"timestamp": 1793016000,
"ago": "1 week ago",
"human": "1 week ago"
},
{
"timestamp": 1790942400,
"ago": "on 10\/2\/26",
"human": "1 month ago"
},
{
"timestamp": 1761998400,
"ago": "on 11\/1\/25",
"human": "1 year ago"
},
{
"timestamp": 1793620801,
"ago": "1 second",
"human": "1 second from now"
},
{
"timestamp": 1793620860,
"ago": "1 minute",
"human": "1 minute from now"
},
{
"timestamp": 1793624401,
"ago": "1 hour",
"human": "1 hour from now"
},
{
"timestamp": 1793534339,
"ago": "1 day ago",
"human": "1 day ago"
},
{
"timestamp": 1793530739,
"ago": "1 day, 1 hour ago",
"human": "1 day ago"
},
{
"timestamp": 1793447939,
"ago": "2 days ago",
"human": "2 days ago"
},
{
"timestamp": 1791120800,
"ago": "4 weeks, 1 day ago",
"human": "4 weeks ago"
},
{
"timestamp": 1793707261,
"ago": "1 day",
"human": "1 day from now"
},
{
"timestamp": 1796299200,
"ago": "on 12\/3\/26",
"human": "1 month from now"
},
{
"timestamp": 1788540800,
"ago": "on 9\/4\/26",
"human": "1 month ago"
},
{
"timestamp": 1785844800,
"ago": "on 8\/4\/26",
"human": "2 months ago"
},
{
"timestamp": 1778620800,
"ago": "on 5\/12\/26",
"human": "5 months ago"
},
{
"timestamp": 1730548800,
"ago": "on 11\/2\/24",
"human": "2 years ago"
},
{
"timestamp": 1856692800,
"ago": "on 11\/1\/28",
"human": "1 year from now"
}
],
"amounts": [
{
"value": -0,
"amount": "0",
"plain": "0",
"currency": "0.00"
},
{
"value": -1.0e-9,
"amount": "0",
"plain": "0",
"currency": "-1"
},
{
"value": -1.0e-8,
"amount": "-0.00000001",
"plain": "-0.00000001",
"currency": "-1"
},
{
"value": 1.005,
"amount": "1.005",
"plain": "1.005",
"currency": "1.00"
},
{
"value": 2.675,
"amount": "2.675",
"plain": "2.675",
"currency": "2.67"
},
{
"value": 0,
"amount": "0",
"plain": "0",
"currency": "0.00"
},
{
"value": 1,
"amount": "1",
"plain": "1",
"currency": "1.00"
},
{
"value": 1.01,
"amount": "1.01",
"plain": "1.01",
"currency": "1.01"
},
{
"value": 1234.567891235,
"amount": "1,234.56789124",
"plain": "1234.56789124",
"currency": "1,234.56"
},
{
"value": 5.0e-9,
"amount": "0.00000001",
"plain": "0.00000001",
"currency": "5"
},
{
"value": -1.234,
"amount": "-1.234",
"plain": "-1.234",
"currency": "-1.23"
},
{
"value": 1234567890.1234,
"amount": "1,234,567,890.12339997",
"plain": "1234567890.12339997",
"currency": "1,234,567,890.12"
},
{
"value": "1.0",
"amount": "1",
"plain": "1",
"currency": "1"
},
{
"value": "1.230",
"amount": "1.23",
"plain": "1.23",
"currency": "1.23"
},
{
"value": "123.00000001",
"amount": "123.00000001",
"plain": "123.00000001",
"currency": "123.00"
}
]
}
-344
View File
@@ -1,344 +0,0 @@
[
{
"data": "lbry:bHW58d37s1hBjj3wPBkn5zpCX3F8ZW3uWf",
"width": 320,
"height": 320,
"sha256": "cbee851be28252d6c21f0a6728b7e4998837d963c0118860a0ebc7ec95ef11bc"
},
{
"data": "HELLO WORLD",
"width": 320,
"height": 320,
"sha256": "0cb3d46135fb7f8206dbc38eb826bc82ebcda986c9d99a73ac85b65cdb911d65"
},
{
"data": "12345678901234567890",
"width": 320,
"height": 320,
"sha256": "c132e611b18b767097c13d5674cd3d5274b1c2a128f5b3a3c3ab6784cf34f45a"
},
{
"data": "éà😀",
"width": 320,
"height": 320,
"sha256": "7541fa7bb1c4cf4572bdd7b06d7347b68376517ff4eab8057a9d152655c0ea6d"
},
{
"data": " hello ",
"width": 320,
"height": 320,
"sha256": "33874446befe1bc452778a57fdce27bdc30dd553ec5c37221110662b36bffb65"
},
{
"data": "漢字",
"width": 320,
"height": 320,
"sha256": "6270e5b5102252e168482d18f31d46d5f55d1df9761649ac316ba263226cd5c3"
},
{
"data": "lbry:b111111111111111111111111111111111",
"width": 320,
"height": 320,
"sha256": "4679bf366ba578fbcbd8c9052a47e7b92dd56ab497d07f64f99317c8f38664c0"
},
{
"data": "a",
"width": 320,
"height": 320,
"sha256": "97403b9b99bff84d4124d0dc4a7a987f76145512a3adf4f1683bc5ea8c4ab366"
},
{
"data": "aa",
"width": 320,
"height": 320,
"sha256": "2da4c046154f8acb3d4e9f8028d5a54aa1e57f46e11438aa7119599fd3ed7870"
},
{
"data": "aaa",
"width": 320,
"height": 320,
"sha256": "426ac076a4fc037e4ab9ac5df0db48da2cccc4cd89bbafb9bae4796d6349543c"
},
{
"data": "aaaa",
"width": 320,
"height": 320,
"sha256": "fb3371adb262f8637a6b53c8fb95cdae04d48158c666112c31f2bbcec4594dea"
},
{
"data": "aaaaa",
"width": 320,
"height": 320,
"sha256": "5e155e39d06dcf87a1b95e09ffb8d3dd9fe8d5ad56c14bcc2365fdb1a653505a"
},
{
"data": "aaaaaa",
"width": 320,
"height": 320,
"sha256": "e5ef2d2c17c92baf377cc3cf4b9d689cdacfef66c0d80249f6b8dad62705b3f2"
},
{
"data": "aaaaaaa",
"width": 320,
"height": 320,
"sha256": "f177ffc257468dc7df8b0809d9089f030d68450026cb44eb8edb08fe2a8ca762"
},
{
"data": "aaaaaaaa",
"width": 320,
"height": 320,
"sha256": "1a1b8e2ea2c76c1a21589a2adcef5c21d4561471f879e1aff063e4662540d535"
},
{
"data": "aaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "534557007b8dbfe98ec5cb88f64852ee1bf4eda851e7c70562a48145ea7b4f89"
},
{
"data": "aaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "8bfc5d621939b39f42891ccd5a4c327db1d94a3e7d3a6f741074fcb2c868f5fb"
},
{
"data": "aaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "a632f1c886938df6d028f5f6dfac5342034172bb649cb897e3d0e6caaa80bae8"
},
{
"data": "aaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "aee804987d756b3607b48c7d7a4f58b9a26d2f21b12de016adcd81fbaef315d7"
},
{
"data": "aaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "39c904fb422b765ded32cfee09eee5c3cd29a56cbb09a3c4f2794060dbc8f8ad"
},
{
"data": "aaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "2bb59fe682c84c7063ca970c3a16787b3c7733a0ada91a93cf2000c54c4837ad"
},
{
"data": "aaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "5c9ed97eda9565478754318969b14262cc277fc67b84cfd553fed2ec54f683ff"
},
{
"data": "aaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "294d2649cecccf4e5c5013b2f3ca8e7c1e130345ea382f987130bd64f561819f"
},
{
"data": "aaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "7688288161fddbe5183db4ef746787487203544d7465ad544b9268a6807d6283"
},
{
"data": "aaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "d0ab31799eed3686c0b090d258c3f8b9e8253d24cd4989bf668c4c569f34efe2"
},
{
"data": "aaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "d975297f21eb66162ff46c0641fecc1de914f90ee42d5e3b3c8700a71778a59c"
},
{
"data": "aaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "25ebe63974078efe094a1397c36f903523db8bb067d7f8aca0643cc5824b7f57"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "1c578f3d9549c77e920cd34428e7310188a0f46a4df3ad632411f78fad91f344"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "f8e6b1a2c8d582707240a6ed4a8468e3522d2dd7ddcf0767ba2bb8c993fcc38e"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "ca230ec35d58478f0e93212b73ec61ecd82fb4e3b5c6a4ed356d3d02ad9221fa"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "8b0249237bba17863da93dc2c9aed2dfe4f4ff408169d083e385cd67fc397b46"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "0ac8e5b1b161f888d8080efd5b26ede0d72f581e750a89ce6d41f5f82f1f499a"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "556c9f4a82b51ffe1011aaeaafb25d1916f943ad73663b517c253740504ae8fc"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "4ba8ac6c007a2a2478f236de7c6618c5245408a164a451b9286556802a480301"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "6b55824c3289f4b9e0cbd346d8cfc2e405fed55b96ffa57ee42d4ac0800400c5"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "b5e5785ec55f16786c5c8014df9b869bad7096fe6bb1ed1ca95cebb036aaa074"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "c638d11ad35d9b02c6a11110e9453878c79eb4ac985b2383732da51dd534e18e"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "95e6282b563e39a9f44f6da621f36b5182f2f22e3023188c04276e6ec52d688f"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "9dcc61f8edaa61b38d82add67779a1417fc725288c8f77d69b8cbfa2b79ab669"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "8193c04c7c0e41df0e24a6bf0d70827ca0585459e5b7fb748406ff4bbde200f9"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "0808a9938c9e6d498d4e7e231765e5ec2446aeebf69fa86e35daa20879302c70"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "6949c9f3998f256e0456c149116907fc81f2910a7b93554217014d866b530d81"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "60c2192de14d4f3aadcf691652506923a9547ddff2e763ac6d0eac88d6646768"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "18e1c93fa5c24b52006ba33f62f4efe36400415f86425b66b367f6051b1191f9"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "c37d5242354a9dd1216089b1f8ee40c9bd8aa357ba233f338e306cf44367fb38"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "623bc8ce6e7b1ab4b72c944073f4a26bb66c435a60fddc68f3f812061fbbfcfe"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "8786c3b9c367a9ee8a1f01c4a7abf13eece24861aff9d078c0d1e05fc1e48f0a"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "e36be2bce2fb23540ccdd0b3162ecb5eda9ecfdd4c4bf8193c63a88c305b813b"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "892aebb3db4fa93574610f39a9e0667494199c072a88b9ee9d09215f9d7bcc65"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "576d515ebeb366c311c7433eb9c91112d0384b5a8c91efca1df3472e521d7ba5"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "2bce4f5094e8ecf7d1fd8e6fe7df6a54ed68a127a60515b197294a533c367181"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "05270729376899bdfbc88c97ee5fd6f5b23e0e939a0b18a79d6f0f8ecc267698"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "2deac4b041d151f824bd7a1be7ae66600feb47d0028483dc90c9321804ab1014"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "1934daf83d858a232fd9c3dc2fe98a1309d7188d9c2d7e966c8ad8a9bd0596f4"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "2cc1c66500bd9aaff4445bc66c9c3ce14e38aaa8ab74a15fe5082de20a62114b"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "b3ed2f2055813010b54aadae876fe5d03124ed46afd154ee938065e0bf365929"
},
{
"data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"width": 320,
"height": 320,
"sha256": "68d5d704aa0b1a6f1b464365ffcdf43f0a5a4b7b5073af302d184e8297db8ac2"
}
]
-458
View File
@@ -1,458 +0,0 @@
[
{
"path": "/",
"method": "GET",
"action": "index",
"args": []
},
{
"path": "/",
"method": "POST",
"action": "index",
"args": []
},
{
"path": "/",
"method": "HEAD",
"action": "index",
"args": []
},
{
"path": "/api/v1/status",
"method": "GET",
"action": "apistatus",
"args": []
},
{
"path": "/api/v1/status",
"method": "POST",
"action": "apistatus",
"args": []
},
{
"path": "/api/v1/status",
"method": "HEAD",
"action": "apistatus",
"args": []
},
{
"path": "/api/v1/status/",
"method": "GET",
"action": "apistatus",
"args": []
},
{
"path": "/api/v1/status/",
"method": "POST",
"action": "apistatus",
"args": []
},
{
"path": "/api/v1/status/",
"method": "HEAD",
"action": "apistatus",
"args": []
},
{
"path": "/api/v1/status/extra",
"method": "GET",
"action": "index",
"args": [
"api",
"v1",
"status",
"extra"
]
},
{
"path": "/api/v1/status/extra",
"method": "POST",
"action": "index",
"args": [
"api",
"v1",
"status",
"extra"
]
},
{
"path": "/api/v1/status/extra",
"method": "HEAD",
"action": "index",
"args": [
"api",
"v1",
"status",
"extra"
]
},
{
"path": "/blocks",
"method": "GET",
"action": "blocks",
"args": []
},
{
"path": "/blocks",
"method": "POST",
"action": "blocks",
"args": []
},
{
"path": "/blocks",
"method": "HEAD",
"action": "blocks",
"args": []
},
{
"path": "/blocks/",
"method": "GET",
"action": "blocks",
"args": []
},
{
"path": "/blocks/",
"method": "POST",
"action": "blocks",
"args": []
},
{
"path": "/blocks/",
"method": "HEAD",
"action": "blocks",
"args": []
},
{
"path": "/blocks/1/extra",
"method": "GET",
"action": "blocks",
"args": [
"1",
"extra"
]
},
{
"path": "/blocks/1/extra",
"method": "POST",
"action": "blocks",
"args": [
"1",
"extra"
]
},
{
"path": "/blocks/1/extra",
"method": "HEAD",
"action": "blocks",
"args": [
"1",
"extra"
]
},
{
"path": "/blocks/%31",
"method": "GET",
"action": "blocks",
"args": [
"1"
]
},
{
"path": "/blocks/%31",
"method": "POST",
"action": "blocks",
"args": [
"1"
]
},
{
"path": "/blocks/%31",
"method": "HEAD",
"action": "blocks",
"args": [
"1"
]
},
{
"path": "/blocks//",
"method": "GET",
"action": "blocks",
"args": []
},
{
"path": "/blocks//",
"method": "POST",
"action": "blocks",
"args": []
},
{
"path": "/blocks//",
"method": "HEAD",
"action": "blocks",
"args": []
},
{
"path": "/qr/lbry%3A%2F%2Fhello",
"method": "GET",
"action": "qr",
"args": [
"lbry://hello"
]
},
{
"path": "/qr/lbry%3A%2F%2Fhello",
"method": "POST",
"action": "qr",
"args": [
"lbry://hello"
]
},
{
"path": "/qr/lbry%3A%2F%2Fhello",
"method": "HEAD",
"action": "qr",
"args": [
"lbry://hello"
]
},
{
"path": "/qr/lbry://hello",
"method": "GET",
"action": "qr",
"args": [
"lbry:",
"hello"
]
},
{
"path": "/qr/lbry://hello",
"method": "POST",
"action": "qr",
"args": [
"lbry:",
"hello"
]
},
{
"path": "/qr/lbry://hello",
"method": "HEAD",
"action": "qr",
"args": [
"lbry:",
"hello"
]
},
{
"path": "/api/v1/address/abc!/balance",
"method": "GET",
"action": "index",
"args": [
"api",
"v1",
"address",
"abc!",
"balance"
]
},
{
"path": "/api/v1/address/abc!/balance",
"method": "POST",
"action": "index",
"args": [
"api",
"v1",
"address",
"abc!",
"balance"
]
},
{
"path": "/api/v1/address/abc!/balance",
"method": "HEAD",
"action": "index",
"args": [
"api",
"v1",
"address",
"abc!",
"balance"
]
},
{
"path": "/api/v1/address//balance",
"method": "GET",
"action": "index",
"args": [
"api",
"v1",
"address",
"balance"
]
},
{
"path": "/api/v1/address//balance",
"method": "POST",
"action": "index",
"args": [
"api",
"v1",
"address",
"balance"
]
},
{
"path": "/api/v1/address//balance",
"method": "HEAD",
"action": "index",
"args": [
"api",
"v1",
"address",
"balance"
]
},
{
"path": "/api/v1/charts/blocksize/2h",
"method": "GET",
"action": "apiblocksize",
"args": [
"2h"
]
},
{
"path": "/api/v1/charts/blocksize/2h",
"method": "POST",
"action": "apiblocksize",
"args": [
"2h"
]
},
{
"path": "/api/v1/charts/blocksize/2h",
"method": "HEAD",
"action": "apiblocksize",
"args": [
"2h"
]
},
{
"path": "/realtime/",
"method": "GET",
"action": "realtime",
"args": []
},
{
"path": "/realtime/",
"method": "POST",
"action": "realtime",
"args": []
},
{
"path": "/realtime/",
"method": "HEAD",
"action": "realtime",
"args": []
},
{
"path": "/find/",
"method": "GET",
"action": "find",
"args": []
},
{
"path": "/find/",
"method": "POST",
"action": "find",
"args": []
},
{
"path": "/find/",
"method": "HEAD",
"action": "find",
"args": []
},
{
"path": "/stats/",
"method": "GET",
"action": "stats",
"args": []
},
{
"path": "/stats/",
"method": "POST",
"action": "stats",
"args": []
},
{
"path": "/stats/",
"method": "HEAD",
"action": "stats",
"args": []
},
{
"path": "/tx/%2F",
"method": "GET",
"action": "tx",
"args": [
"/"
]
},
{
"path": "/tx/%2F",
"method": "POST",
"action": "tx",
"args": [
"/"
]
},
{
"path": "/tx/%2F",
"method": "HEAD",
"action": "tx",
"args": [
"/"
]
},
{
"path": "//stats",
"method": "GET",
"action": "stats",
"args": []
},
{
"path": "//stats",
"method": "POST",
"action": "stats",
"args": []
},
{
"path": "//stats",
"method": "HEAD",
"action": "stats",
"args": []
},
{
"path": "/claims/0",
"method": "GET",
"action": "claims",
"args": [
"0"
]
},
{
"path": "/claims/0",
"method": "POST",
"action": "claims",
"args": [
"0"
]
},
{
"path": "/claims/0",
"method": "HEAD",
"action": "claims",
"args": [
"0"
]
}
]
-154
View File
@@ -1,154 +0,0 @@
package explorer
import (
"fmt"
"strings"
"time"
)
func unitString(n int, u string) string {
if n != 1 {
u += "s"
}
return fmt.Sprintf("%d %s", n, u)
}
func cakeAgo(t, now time.Time) string {
diff := int64(now.Unix() - t.Unix())
future := diff < 0
if future {
diff = -diff
}
if diff == 0 {
return "just now"
}
if diff > int64(now.AddDate(0, 1, 0).Sub(now)/time.Second) {
return "on " + t.Format("1/2/06")
}
vals := []int{0, 0, 0, 0, 0, 0, 0}
units := []string{"year", "month", "week", "day", "hour", "minute", "second"}
if diff >= 604800 {
past, next := t, now
if future {
past, next = now, t
}
years := next.Year() - past.Year()
months := int(next.Month()) + 12*years - int(past.Month())
if months >= 12 {
years = months / 12
months -= years * 12
}
if next.Month() < past.Month() && next.Year()-past.Year() == 1 {
years--
}
days := next.Day() - past.Day()
if days < 0 {
daysInPast := time.Date(past.Year(), past.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
daysInFuture := time.Date(next.Year(), next.Month(), 0, 0, 0, 0, 0, time.UTC).Day()
if !future {
days = daysInPast - past.Day() + next.Day()
} else {
days = daysInFuture - past.Day() + next.Day()
}
if next.Month() != past.Month() {
months--
}
}
if months == 0 && years >= 1 && diff < int64(years)*31536000 {
months = 11
years--
}
if months >= 12 {
years++
months -= 12
}
vals[0], vals[1], vals[2], vals[3] = years, months, days/7, days%7
} else {
vals[3] = int(diff / 86400)
diff %= 86400
vals[4] = int(diff / 3600)
diff %= 3600
vals[5] = int(diff / 60)
vals[6] = int(diff % 60)
}
first := 6
for i, n := range vals {
if n > 0 {
first = i
break
}
}
end := 6
if first <= 2 {
end = 3
} else if first == 3 {
end = 4
} else if first <= 5 {
end = 5
}
pieces := []string{}
for i := 0; i <= end; i++ {
if vals[i] > 0 {
pieces = append(pieces, unitString(vals[i], units[i]))
}
}
out := strings.Join(pieces, ", ")
if out == "" {
article := "a"
if units[end] == "hour" {
article = "an"
}
if future {
return "in about " + article + " " + units[end]
}
return "about " + article + " " + units[end] + " ago"
}
if !future {
out += " ago"
}
return out
}
func humanAgo(t, now time.Time) string {
past, next := t, now
future := t.After(now)
if future {
past, next = now, t
}
years := next.Year() - past.Year()
months := int(next.Month()) - int(past.Month())
if months < 0 {
years--
months += 12
}
days := next.Day() - past.Day()
if next.Hour()*3600+next.Minute()*60+next.Second() < past.Hour()*3600+past.Minute()*60+past.Second() {
days--
}
if days < 0 {
months--
if months < 0 {
years--
months += 12
}
days += time.Date(past.Year(), past.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
seconds := int(next.Sub(past) / time.Second)
n, unit := seconds%60, "second"
if years > 0 {
n, unit = years, "year"
} else if months > 0 {
n, unit = months, "month"
} else if days >= 7 {
n, unit = days/7, "week"
} else if days > 0 {
n, unit = days, "day"
} else if seconds >= 3600 {
n, unit = seconds/3600, "hour"
} else if seconds >= 60 {
n, unit = seconds/60, "minute"
}
out := unitString(n, unit)
if future {
return out + " from now"
}
return out + " ago"
}
-156
View File
@@ -1,156 +0,0 @@
package explorer
import (
"encoding/json"
"fmt"
"math"
"math/big"
"net/http"
"strings"
)
type ioView struct {
Row, Address Row
Source, Anchor bool
}
func ioViews(rows []Row, addressKey, source string, seen map[string]bool) []ioView {
out := make([]ioView, 0, len(rows))
for _, row := range rows {
address := Row{}
if list, ok := row[addressKey].([]Row); ok && len(list) > 0 {
address = list[0]
}
name := text(address["address"])
anchor := false
if !seen[name] && phpTrim(text(row["value"])) != "" && !truth(row["is_coinbase"]) {
anchor = true
seen[name] = true
}
out = append(out, ioView{row, address, name != "" && name == source, anchor})
}
return out
}
func confirmationDelay(tx Row) string {
diff := int64(number(tx["transaction_time"])) - timestamp(tx["created_at"]).Unix()
if diff <= 0 {
return ""
}
n := int(diff)
unit := "second"
if diff > 60 {
n = int(math.Ceil(float64(diff) / 60))
unit = "minute"
}
return fmt.Sprintf(" (+%s)", unitString(n, unit))
}
func (s *Server) transactionPage(w http.ResponseWriter, r *http.Request) {
hash := firstArgument(r, "/tx")
if hash == "" {
redirect(w, r, "/", 302)
return
}
query := func(q string, args ...any) ([]Row, bool) {
rows, e := s.Store.Query(r.Context(), q, args...)
if e != nil {
internalError(w)
return nil, false
}
return rows, true
}
rows, ok := query("SELECT * FROM transaction WHERE hash = ? LIMIT 1", hash)
if !ok {
return
}
if len(rows) == 0 {
redirect(w, r, "/", 302)
return
}
tx := rows[0]
var block Row
confirmations := int64(0)
if tx["block_hash_id"] != nil && text(tx["block_hash_id"]) != "MEMPOOL" {
blocks, ok := query("SELECT confirmations,height FROM block WHERE hash = ? LIMIT 1", tx["block_hash_id"])
if !ok {
return
}
last, ok := query("SELECT height FROM block ORDER BY height DESC LIMIT 1")
if !ok {
return
}
if len(blocks) > 0 {
block = blocks[0]
if len(last) > 0 {
confirmations = int64(number(last[0]["height"]) - number(block["height"]) + 1)
}
}
}
inputs, ok := query("SELECT * FROM input WHERE transaction_id = ? ORDER BY prevout_n ASC", tx["id"])
if !ok {
return
}
for _, in := range inputs {
in["input_addresses"] = []Row{}
if in["input_address_id"] != nil {
addresses, ok := query("SELECT id,address FROM address WHERE id = ?", in["input_address_id"])
if !ok {
return
}
in["input_addresses"] = addresses
}
}
outputs, ok := query("SELECT Outputs.*,I.transaction_hash AS spend_input_hash,I.id AS spend_input_id FROM output Outputs LEFT JOIN input I ON I.id = Outputs.spent_by_input_id WHERE Outputs.transaction_id = ? ORDER BY Outputs.vout ASC", tx["id"])
if !ok {
return
}
for _, out := range outputs {
script := text(out["script_pub_key_asm"])
out["IsClaim"] = strings.Contains(script, "CLAIM")
out["IsSupportClaim"] = strings.Contains(script, "SUPPORT_CLAIM")
out["IsUpdateClaim"] = strings.Contains(script, "UPDATE_CLAIM")
claims, ok := query("SELECT id,claim_id,claim_address,vout,transaction_hash_id FROM claim WHERE transaction_hash_id = ? AND vout = ? LIMIT 1", tx["hash"], out["vout"])
if !ok {
return
}
var claim Row
if len(claims) > 0 {
claim = claims[0]
}
out["Claim"] = claim
var list []any
json.Unmarshal([]byte(text(out["address_list"])), &list)
if len(list) == 0 && text(claim["claim_address"]) != "" {
list = append(list, claim["claim_address"])
}
out["output_addresses"] = []Row{}
if len(list) > 0 {
addresses, ok := query("SELECT address FROM address WHERE address IN ("+placeholders(len(list))+")", list...)
if !ok {
return
}
out["output_addresses"] = addresses
}
}
totalIn, totalOut := new(big.Rat), new(big.Rat)
for _, in := range inputs {
if !validBCString(phpString(in["value"])) {
internalError(w)
return
}
totalIn = decimal(truncated(new(big.Rat).Add(totalIn, decimal(phpString(in["value"]))), 8))
}
for _, out := range outputs {
if !validBCString(phpString(out["value"])) {
internalError(w)
return
}
totalOut = decimal(truncated(new(big.Rat).Add(totalOut, decimal(phpString(out["value"]))), 8))
}
fee := truncated(new(big.Rat).Sub(totalIn, totalOut), 8)
seen := map[string]bool{}
source := queryScalar(r, "address")
data := pageData{Title: "Transaction ", Tx: tx, Block: block, Confirmations: confirmations, Fee: fee}
data.Inputs = ioViews(inputs, "input_addresses", source, seen)
data.Outputs = ioViews(outputs, "output_addresses", source, seen)
s.render(w, r, "tx", data)
}
-22
View File
@@ -1,22 +0,0 @@
Copyright (c) 2017-present, Ben Scholzen 'DASPRiD'
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-20
View File
@@ -1,20 +0,0 @@
Copyright (c) 2005-present, Cake Software Foundation, Inc. (https://cakefoundation.org)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-19
View File
@@ -1,19 +0,0 @@
Copyright 2025 (c) Jeroen van den Enden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-27
View File
@@ -1,27 +0,0 @@
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-68
View File
@@ -1,68 +0,0 @@
--------------------------------------------------------------------
The PHP License, version 3.01
Copyright (c) 1999 - 2024 The PHP Group. All rights reserved.
--------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, is permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The name "PHP" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact group@php.net.
4. Products derived from this software may not be called "PHP", nor
may "PHP" appear in their name, without prior written permission
from group@php.net. You may indicate that your software works in
conjunction with PHP by saying "Foo for PHP" instead of calling
it "PHP Foo" or "phpfoo"
5. The PHP Group may publish revised and/or new versions of the
license from time to time. Each version will be given a
distinguishing version number.
Once covered code has been published under a particular version
of the license, you may always continue to use it under the terms
of that version. You may also choose to use such covered code
under the terms of any subsequent version of the license
published by the PHP Group. No one other than the PHP Group has
the right to modify the terms applicable to covered code created
under this License.
6. Redistributions of any form whatsoever must retain the following
acknowledgment:
"This product includes PHP software, freely available from
<http://www.php.net/software/>".
THIS SOFTWARE IS PROVIDED BY THE PHP DEVELOPMENT TEAM ``AS IS'' AND
ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PHP
DEVELOPMENT TEAM OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------
This software consists of voluntary contributions made by many
individuals on behalf of the PHP Group.
The PHP Group can be contacted via Email at group@php.net.
For more information on the PHP Group and the PHP project,
please see <http://www.php.net>.
PHP includes the Zend Engine, freely available at
<http://www.zend.com>.
-27
View File
@@ -1,27 +0,0 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-373
View File
@@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
-230
View File
@@ -1,230 +0,0 @@
MIT License
Copyright (c) 2018 Daisuke MAKIUCHI (MakKi; makki_d)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
========================================================================
Original zxing License
Copyright 2007-2018 ZXing authors
========================================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-27
View File
@@ -1,27 +0,0 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more