Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d536a49f9f |
No files matched your search
@@ -1,18 +0,0 @@
|
||||
; 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
|
||||
@@ -1,42 +0,0 @@
|
||||
# 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
|
||||
+6
-7
@@ -1,7 +1,6 @@
|
||||
/vendor/*
|
||||
/config/app.php
|
||||
/config/lbry.php
|
||||
/logs/*
|
||||
lbryexplorer.zip
|
||||
lbryexplorer.komodoproject
|
||||
.komodotools
|
||||
/var/
|
||||
/explorer
|
||||
.env
|
||||
*.cnf
|
||||
__pycache__/
|
||||
/dist/
|
||||
@@ -1,11 +0,0 @@
|
||||
# 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
@@ -1,30 +0,0 @@
|
||||
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
|
||||
@@ -1,10 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2018 LBRY Inc
|
||||
Copyright (c) 2017-2018 LBRY Inc.
|
||||
|
||||
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:
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
.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/
|
||||
@@ -1,91 +1,67 @@
|
||||
# LBRY Block Explorer
|
||||
> 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.
|
||||
|
||||
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.
|
||||
# LBRY explorer
|
||||
|
||||
## 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)
|
||||
A read-only block explorer for the LBRY blockchain.
|
||||
|
||||
### 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.
|
||||
## Build and run
|
||||
|
||||
Requires Go 1.23 or newer. From this directory:
|
||||
|
||||
```sh
|
||||
make verify
|
||||
make release
|
||||
```
|
||||
cd block-explorer
|
||||
composer update
|
||||
|
||||
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
|
||||
```
|
||||
* 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 configuraiton. 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;
|
||||
|
||||
root /var/www/block-explorer/webroot;
|
||||
index index.php;
|
||||
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.
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.php?$args;
|
||||
}
|
||||
## Configuration
|
||||
|
||||
# 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;
|
||||
}
|
||||
| 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
|
||||
}
|
||||
```
|
||||
* Restart your web server.
|
||||
|
||||
|
||||
### 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 transation 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)
|
||||
See [TODO.md](TODO.md) for known issues and [THIRD-PARTY.md](THIRD-PARTY.md) for notices.
|
||||
@@ -0,0 +1,18 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,11 @@
|
||||
# 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.
|
||||
@@ -1,46 +0,0 @@
|
||||
#!/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
|
||||
@@ -1,27 +0,0 @@
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::
|
||||
:: 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%
|
||||
@@ -1,34 +0,0 @@
|
||||
#!/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));
|
||||
@@ -0,0 +1,70 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
{
|
||||
"name": "cakephp/app",
|
||||
"description": "CakePHP skeleton app",
|
||||
"homepage": "http://cakephp.org",
|
||||
"type": "project",
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=5.6",
|
||||
"cakephp/cakephp": "3.4.*",
|
||||
"mobiledetect/mobiledetectlib": "2.*",
|
||||
"cakephp/migrations": "~1.0",
|
||||
"cakephp/plugin-installer": "~1.0",
|
||||
"mdanter/ecc": "^0.5.0",
|
||||
"nesbot/carbon": "~1.18",
|
||||
"endroid/qrcode": "^2.2.2",
|
||||
"predis/predis": "^1.1.1"
|
||||
},
|
||||
"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
-2733
File diff suppressed because it is too large.
Load diff
@@ -1,346 +0,0 @@
|
||||
<?php
|
||||
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',
|
||||
],
|
||||
];
|
||||
@@ -1,225 +0,0 @@
|
||||
<?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 use CakePHP.', 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.', 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.', E_USER_ERROR);
|
||||
}
|
||||
|
||||
/*
|
||||
* 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';
|
||||
|
||||
use Cake\Cache\Cache;
|
||||
use Cake\Console\ConsoleErrorHandler;
|
||||
use Cake\Core\App;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\Configure\Engine\PhpConfig;
|
||||
use Cake\Core\Plugin;
|
||||
use Cake\Database\Type;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\Error\ErrorHandler;
|
||||
use Cake\Log\Log;
|
||||
use Cake\Mailer\Email;
|
||||
use Cake\Network\Request;
|
||||
use Cake\Utility\Inflector;
|
||||
use Cake\Utility\Security;
|
||||
|
||||
/*
|
||||
* 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::salt(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
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
* Only try to load DebugKit in development mode
|
||||
* Debug Kit should not be installed on a production system
|
||||
*/
|
||||
if (Configure::read('debug')) {
|
||||
Plugin::load('DebugKit', ['bootstrap' => true]);
|
||||
}
|
||||
|
||||
Configure::load('lbry');
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
<?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
|
||||
*/
|
||||
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');
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'Lbry' => [
|
||||
'RpcUrl' => 'http://user:password@127.0.0.1:9245',
|
||||
],
|
||||
|
||||
'Redis' => [
|
||||
'Url' => 'tcp://127.0.0.1:6379',
|
||||
]
|
||||
];
|
||||
@@ -1,85 +0,0 @@
|
||||
<?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)
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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);
|
||||
@@ -1,80 +0,0 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
use Cake\Core\Plugin;
|
||||
use Cake\Routing\RouteBuilder;
|
||||
use Cake\Routing\Router;
|
||||
use Cake\Routing\Route\DashedRoute;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
});
|
||||
|
||||
/**
|
||||
* Load all plugin routes. See the Plugin documentation on
|
||||
* how to customize the loading of plugin routes.
|
||||
*/
|
||||
Plugin::routes();
|
||||
@@ -1,18 +0,0 @@
|
||||
# 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)
|
||||
);
|
||||
@@ -1,13 +0,0 @@
|
||||
# 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)
|
||||
);
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake block addrtxamounts
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/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
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake block parsetxs
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake block buildclaimindex
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake block fixzerooutputs
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
#!/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 &
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake block parsemempool
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake aux pricehistory
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake block updatespends
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd /home/lbry/explorer.lbry.io
|
||||
bin/cake aux verifytags
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# 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
|
||||
@@ -0,0 +1,28 @@
|
||||
[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
|
||||
@@ -0,0 +1,11 @@
|
||||
# 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;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
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=
|
||||
@@ -1,16 +0,0 @@
|
||||
<?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';
|
||||
@@ -0,0 +1,124 @@
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
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):
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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)})
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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 />"))
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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)))
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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))
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
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 ""
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
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 <name>") {
|
||||
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 • 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, "<script>") {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{{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}}
|
||||
@@ -0,0 +1,125 @@
|
||||
{{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}}">« Previous Block</a>
|
||||
{{end}}
|
||||
|
||||
<a class="btn btn-next" href="/blocks/{{add .Block.height 1}}">Next Block »</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}}
|
||||
@@ -0,0 +1,63 @@
|
||||
{{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}}
|
||||
@@ -0,0 +1,140 @@
|
||||
{{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> • {{$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}}
|
||||
@@ -0,0 +1,61 @@
|
||||
{{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}}
|
||||
@@ -0,0 +1,47 @@
|
||||
{{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}}
|
||||
@@ -0,0 +1,25 @@
|
||||
<!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>
|
||||
@@ -0,0 +1,25 @@
|
||||
<!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>
|
||||
@@ -0,0 +1,49 @@
|
||||
{{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,4 +1,4 @@
|
||||
<div class="header">
|
||||
{{define "header"}}<div class="header">
|
||||
<div class="title">
|
||||
<a href="/">LBRY Block Explorer</a>
|
||||
</div>
|
||||
@@ -11,4 +11,4 @@
|
||||
</form>
|
||||
</div>
|
||||
<div class="clear"></div>
|
||||
</div>
|
||||
</div>{{end}}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php $this->assign('title', 'Home') ?>
|
||||
|
||||
<?php $this->start('script'); ?>
|
||||
|
||||
{{define "script"}}
|
||||
<script type="text/javascript">
|
||||
var updateInterval = 120000;
|
||||
|
||||
@@ -108,7 +108,7 @@
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<?php $this->end(); ?>
|
||||
{{end}}{{define "css"}}{{end}}{{define "content"}}
|
||||
|
||||
<div class="home-container">
|
||||
<div class="home-container-cell">
|
||||
@@ -127,24 +127,24 @@
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="box">
|
||||
<div class="box box-20">
|
||||
<div class="title">Block Height</div>
|
||||
<div class="value"><?php echo $recentBlocks[0]->Height ?></div>
|
||||
<div class="value">{{.Highest.height}}</div>
|
||||
</div>
|
||||
|
||||
<div class="box">
|
||||
<div class="box box-30">
|
||||
<div class="title">Difficulty</div>
|
||||
<div class="value" title="<?php echo $recentBlocks[0]->Difficulty ?>"><?php echo number_format($recentBlocks[0]->Difficulty, 2, '.', '') ?></div>
|
||||
<div class="value" title="{{text .Highest.difficulty}}">{{fixed .Highest.difficulty 2}}</div>
|
||||
</div>
|
||||
|
||||
<div class="box">
|
||||
<div class="box box-30">
|
||||
<div class="title">Network</div>
|
||||
<div class="value"><?php echo $hashRate ?></div>
|
||||
<div class="value">N/A</div>
|
||||
</div>
|
||||
|
||||
<div class="box last">
|
||||
<div class="box box-20 last">
|
||||
<div class="title">Price</div>
|
||||
<div class="value"><?php echo $lbcUsdPrice ?></div>
|
||||
<div class="value">N/A</div>
|
||||
</div>
|
||||
|
||||
<div class="clear"></div>
|
||||
@@ -166,16 +166,16 @@
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<?php foreach ($recentBlocks as $block): ?>
|
||||
<tr data-height="<?php echo $block->Height ?>" data-time="<?php echo $block->BlockTime ?>">
|
||||
<td><a href="/blocks/<?php echo $block->Height ?>"><?php echo $block->Height ?></a></td>
|
||||
<td><?php echo \Carbon\Carbon::createFromTimestamp($block->BlockTime)->diffForHumans(); ?></td>
|
||||
<td class="right"><?php echo round($block->BlockSize / 1024, 2) . 'KB' ?></td>
|
||||
<td class="right"><?php echo $block->TransactionCount ?></td>
|
||||
<td class="right"><?php echo number_format($block->Difficulty, 2, '.', '') ?></td>
|
||||
<td class="last-cell"><?php echo DateTime::createFromFormat('U', $block->BlockTime)->format('d M Y H:i:s') . ' UTC' ?></td>
|
||||
{{range $block := .RecentBlocks}}
|
||||
<tr data-height="{{$block.height}}" data-time="{{$block.block_time}}">
|
||||
<td><a href="/blocks/{{$block.height}}">{{$block.height}}</a></td>
|
||||
<td>{{ago $block.block_time}}</td>
|
||||
<td class="right">{{kb $block.block_size}}</td>
|
||||
<td class="right">{{$block.tx_count}}</td>
|
||||
<td class="right">{{fixed $block.difficulty 2}}</td>
|
||||
<td class="last-cell">{{date $block.block_time "02 Jan 2006 15:04:05"}} UTC</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -183,71 +183,42 @@
|
||||
<div class="recent-claims">
|
||||
<h3>Recent Claims</h3>
|
||||
<a class="claim-explorer-link" href="/claims">Claims Explorer</a>
|
||||
<?php $idx = 0; $a = ['purple', 'orange', 'blue', 'teal', 'green', 'yellow']; foreach ($recentClaims as $claim):
|
||||
$idx++;
|
||||
$autoThumbText = '';
|
||||
$link = $claim->Name;
|
||||
$rawLink = $claim->Name;
|
||||
if (isset($claim->Publisher->Name)) {
|
||||
$link = urlencode($claim->Publisher->Name) . '/' . $link;
|
||||
$rawLink = $claim->Publisher->Name . '/' . $link;
|
||||
}
|
||||
$link = 'lbry://' . $link;
|
||||
$rawLink = 'lbry://' . $rawLink;
|
||||
|
||||
// content type
|
||||
$ctTag = null;
|
||||
if (substr($claim->ContentType, 0, 5) === 'audio') {
|
||||
$ctTag = 'audio';
|
||||
} else if (substr($claim->ContentType, 0, 5) === 'video') {
|
||||
$ctTag = 'video';
|
||||
} else if (substr($claim->ContentType, 0, 5) === 'image') {
|
||||
$ctTag = 'image';
|
||||
}
|
||||
|
||||
if (!$ctTag && $claim->ClaimType == 1) {
|
||||
$ctTag = 'identity';
|
||||
}
|
||||
|
||||
if ($claim->ClaimType == 1) { $autoThumbText = strtoupper(substr($claim->Name, 1, min( strlen($claim->Name), 3 ))); } else {
|
||||
$str = (strlen(trim($claim->Title)) > 0) ? $claim->Title : $claim->Name;
|
||||
$autoThumbText = strtoupper(substr($str, 0, min (strlen($str), 2 )));
|
||||
}
|
||||
?>
|
||||
<div data-id="<?php echo $claim->ClaimId ?>" class="claim-box<?php if ($idx == 5): ?> last<?php endif; ?>">
|
||||
{{range $i, $claim := .RecentClaims}}
|
||||
<div data-id="{{$claim.claim_id}}" class="claim-box{{if eq $i 4}} last{{end}}">
|
||||
<div class="tags">
|
||||
<?php if ($ctTag): ?>
|
||||
<div class="content-type"><?php echo strtoupper($ctTag) ?></div>
|
||||
<?php endif; ?>
|
||||
<?php if ($claim->IsNSFW): ?>
|
||||
{{if contentTag $claim}}
|
||||
<div class="content-type">{{contentTag $claim}}</div>
|
||||
{{end}}
|
||||
{{if truth $claim.is_nsfw}}
|
||||
<div class="nsfw">NSFW</div>
|
||||
<?php endif; ?>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<div data-autothumb="<?php echo $autoThumbText ?>" class="thumbnail <?php echo $a[mt_rand(0, count($a) - 1)] ?>">
|
||||
<?php if (!$claim->IsNSFW && strlen(trim($claim->ThumbnailUrl)) > 0): ?>
|
||||
<img src="<?php echo strip_tags($claim->ThumbnailUrl) ?>" alt="" />
|
||||
<?php else: ?>
|
||||
<div class="autothumb"><?php echo $autoThumbText ?></div>
|
||||
<?php endif; ?>
|
||||
<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="metadata">
|
||||
<div class="title" title="<?php echo $claim->ClaimType == 1 ? $claim->Name : ((strlen(trim($claim->Title)) > 0) ? $claim->Title : ''); ?>"><?php echo $claim->ClaimType == 1 ? $claim->Name : ((strlen(trim($claim->Title)) > 0) ? $claim->Title : '<em>No Title</em>') ?></div>
|
||||
<div class="link" title="<?php echo $rawLink ?>"><a href="<?php echo $link ?>"><?php echo $rawLink ?></a></div>
|
||||
<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}}>{{lbryLink $claim}}</a></div>
|
||||
|
||||
<div class="clear"></div>
|
||||
<?php if ($claim->ClaimType == 2 && strlen(trim($claim->Description)) > 0): ?>
|
||||
<div class="desc"><?php echo $claim->Description ?></div>
|
||||
<?php endif; ?>
|
||||
{{if and (eq (num $claim.claim_type) 2.0) (text $claim.description)}}
|
||||
<div class="desc">{{$claim.description}}</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<a class="tx-link" href="/tx/<?php echo $claim->TransactionHash ?>#output-<?php echo $claim->Vout ?>" target="_blank">Transaction</a>
|
||||
<a class="tx-link" href="/tx/{{$claim.transaction_hash_id}}#output-{{$claim.vout}}" target="_blank">Transaction</a>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
{{end}}
|
||||
|
||||
<div class="clear"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -1,23 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
{{define "layout"}}<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<?= $this->Html->charset(); ?>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>
|
||||
LBRY Block Explorer • <?= $this->fetch('title') ?>
|
||||
LBRY Block Explorer • {{.Title}}
|
||||
</title>
|
||||
<?php echo ''; /* $this->Html->meta('icon') */?>
|
||||
|
||||
|
||||
<?php echo $this->Html->script('jquery.js') ?>
|
||||
<?php echo $this->Html->script('moment.js') ?>
|
||||
<script src="/js/jquery.js"></script>
|
||||
<script src="/js/moment.js"></script>
|
||||
|
||||
<?php echo $this->Html->css('main.css') ?>
|
||||
<link rel="stylesheet" href="/css/main.css">
|
||||
|
||||
<script src="https://use.typekit.net/yst3vhs.js"></script>
|
||||
<script>try{Typekit.load({ async: true });}catch(e){}</script>
|
||||
|
||||
<!-- Analytics -->
|
||||
<?php if ($_SERVER['HTTP_HOST'] === 'explorer.lbry.io'): ?>
|
||||
{{if .Analytics}}
|
||||
<!-- Global site tag (gtag.js) - Google Analytics -->
|
||||
<script async src="//www.googletagmanager.com/gtag/js?id=UA-60403362-1"></script>
|
||||
<script>
|
||||
@@ -26,7 +26,7 @@
|
||||
gtag('js', new Date());
|
||||
gtag('config', 'UA-60403362-4');
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
{{end}}
|
||||
|
||||
<script type="text/javascript">
|
||||
// handle coinomi and lbry app urls
|
||||
@@ -49,18 +49,19 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<?php echo $this->fetch('meta') ?>
|
||||
<?php echo $this->fetch('css') ?>
|
||||
<?php echo $this->fetch('script') ?>
|
||||
|
||||
{{template "css" .}}
|
||||
{{template "script" .}}
|
||||
</head>
|
||||
<body>
|
||||
<?php echo $this->fetch('content') ?>
|
||||
{{template "content" .}}
|
||||
<footer>
|
||||
<div class="content">
|
||||
<a href="https://lbry.io">LBRY</a>
|
||||
<a href="https://lbry.com">LBRY</a>
|
||||
|
||||
<div class="page-time">Page took <?php echo round((microtime(true) - TIME_START) * 1000, 0) ?>ms</div>
|
||||
<div class="page-time">Page took {{elapsed}}ms</div>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
@@ -0,0 +1,25 @@
|
||||
{{define "pagination"}}{{with .Pagination}}{{if .Visible}}
|
||||
<div class="pagination">
|
||||
<div class="prev">
|
||||
|
||||
{{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">
|
||||
|
||||
{{if .Next}}<a href="?page={{.Next}}">Next</a>{{end}}
|
||||
</div>
|
||||
<div class="clear"></div>
|
||||
</div>
|
||||
{{end}}{{end}}{{end}}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php $this->assign('title', 'Realtime Explorer') ?>
|
||||
|
||||
<?php $this->start('script'); ?>
|
||||
|
||||
{{define "script"}}
|
||||
<script type="text/javascript">
|
||||
var updateBlocksInterval = 120000;
|
||||
var updateTxInterval = 30000;
|
||||
@@ -106,9 +106,9 @@
|
||||
setInterval(updateRealtimeTransactions, updateTxInterval);
|
||||
});
|
||||
</script>
|
||||
<?php $this->end(); ?>
|
||||
{{end}}{{define "css"}}{{end}}{{define "content"}}
|
||||
|
||||
<?php echo $this->element('header') ?>
|
||||
{{template "header" .}}
|
||||
|
||||
<div class="realtime-head">
|
||||
<h3>Realtime Explorer</h3>
|
||||
@@ -127,13 +127,13 @@
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<?php foreach ($blocks as $block): ?>
|
||||
<tr data-height="<?php echo $block->Height ?>" data-time="<?php echo $block->BlockTime ?>">
|
||||
<td><a href="/blocks/<?php echo $block->Height ?>" target="_blank"><?php echo $block->Height ?></a></td>
|
||||
<td><?php echo \Carbon\Carbon::createFromTimestamp($block->BlockTime)->diffForHumans(); ?></td>
|
||||
<td class="right"><?php echo $block->TransactionCount ?></td>
|
||||
{{range $block := .Blocks}}
|
||||
<tr data-height="{{$block.height}}" data-time="{{$block.block_time}}">
|
||||
<td><a href="/blocks/{{$block.height}}" target="_blank">{{$block.height}}</a></td>
|
||||
<td>{{ago $block.block_time}}</td>
|
||||
<td class="right">{{$block.tx_count}}</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -152,15 +152,15 @@
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<?php foreach ($txs as $tx): ?>
|
||||
<tr data-hash="<?php echo $tx->Hash ?>" data-time="<?php echo $tx->TxTime ?>">
|
||||
<td class="w200"><div><a href="/tx/<?php echo $tx->Hash ?>" target="_blank"><?php echo $tx->Hash ?></a></div></td>
|
||||
<td><?php echo \Carbon\Carbon::createFromTimestamp($tx->TxTime)->diffForHumans(); ?></td>
|
||||
<td class="right"><?php echo $tx->InputCount ?></td>
|
||||
<td class="right"><?php echo $tx->OutputCount ?></td>
|
||||
<td class="right"><?php echo number_format($tx->Value, 8, '.', '') ?> LBC</td>
|
||||
{{range $tx := .Txs}}
|
||||
<tr data-hash="{{$tx.hash}}" data-time="{{$tx.transaction_time}}">
|
||||
<td class="w200"><div><a href="/tx/{{$tx.hash}}" target="_blank">{{$tx.hash}}</a></div></td>
|
||||
<td>{{humanAgo $tx.created_at}}</td>
|
||||
<td class="right">{{$tx.input_count}}</td>
|
||||
<td class="right">{{$tx.output_count}}</td>
|
||||
<td class="right">{{fixed $tx.value 8}} LBC</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -168,3 +168,4 @@
|
||||
<div class="clear"></div>
|
||||
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -0,0 +1,59 @@
|
||||
{{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}}
|
||||
@@ -0,0 +1,150 @@
|
||||
|
||||
|
||||
{{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
@@ -0,0 +1,161 @@
|
||||
{
|
||||
"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
@@ -0,0 +1,446 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+344
@@ -0,0 +1,344 @@
|
||||
[
|
||||
{
|
||||
"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
@@ -0,0 +1,458 @@
|
||||
[
|
||||
{
|
||||
"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"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,154 @@
|
||||
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"
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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.
|
||||
@@ -0,0 +1,20 @@
|
||||
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.
|
||||
@@ -0,0 +1,19 @@
|
||||
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.
|
||||
@@ -0,0 +1,27 @@
|
||||
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.
|
||||
@@ -0,0 +1,68 @@
|
||||
--------------------------------------------------------------------
|
||||
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>.
|
||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user