diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..7061901
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,18 @@
+; This file is for unifying the coding style for different editors and IDEs.
+; More information at http://editorconfig.org
+
+root = true
+
+[*]
+indent_style = space
+indent_size = 4
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.bat]
+end_of_line = crlf
+
+[*.yml]
+indent_style = space
+indent_size = 2
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..e16b4b4
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,42 @@
+# Define the line ending behavior of the different file extensions
+# Set default behaviour, in case users don't have core.autocrlf set.
+* text=auto
+* text eol=lf
+
+# Explicitly declare text files we want to always be normalized and converted
+# to native line endings on checkout.
+*.php text
+*.default text
+*.ctp text
+*.sql text
+*.md text
+*.po text
+*.js text
+*.css text
+*.ini text
+*.properties text
+*.txt text
+*.xml text
+*.svg text
+*.yml text
+.htaccess text
+
+# Declare files that will always have CRLF line endings on checkout.
+*.bat eol=crlf
+
+# Declare files that will always have LF line endings on checkout.
+*.pem eol=lf
+
+# Denote all files that are truly binary and should not be modified.
+*.png binary
+*.jpg binary
+*.gif binary
+*.ico binary
+*.mo binary
+*.pdf binary
+*.phar binary
+*.woff binary
+*.woff2 binary
+*.ttf binary
+*.otf binary
+*.eot binary
diff --git a/.gitignore b/.gitignore
index 4bde177..87b42b4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,7 @@
-/var/
-/explorer
-.env
-*.cnf
-__pycache__/
-/dist/
+/vendor/*
+/config/app.php
+/tmp/*
+/logs/*
+lbryexplorer.zip
+lbryexplorer.komodoproject
+.komodotools
diff --git a/.htaccess b/.htaccess
new file mode 100644
index 0000000..bc1dd9c
--- /dev/null
+++ b/.htaccess
@@ -0,0 +1,11 @@
+# Uncomment the following to prevent the httpoxy vulnerability
+# See: https://httpoxy.org/
+#
+# RequestHeader unset Proxy
+#
+
+
+ RewriteEngine on
+ RewriteRule ^$ webroot/ [L]
+ RewriteRule (.*) webroot/$1 [L]
+
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..befdb98
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,30 @@
+language: php
+
+dist: trusty
+
+sudo: false
+
+php:
+ - 5.6
+ - 7.0
+ - 7.1
+
+matrix:
+ fast_finish: true
+
+ include:
+ - php: 7.0
+ env: PHPCS=1
+
+before_script:
+ - if [[ $PHPCS = 1 ]]; then composer require cakephp/cakephp-codesniffer:~2.1; fi
+ - if [[ $PHPCS != 1 ]]; then composer install; fi
+ - if [[ $PHPCS != 1 ]]; then composer require phpunit/phpunit:"^5.7|^6.0"; fi
+ - if [[ $PHPCS != 1 ]]; then composer run-script post-install-cmd --no-interaction; fi
+
+script:
+ - if [[ $PHPCS != 1 ]]; then vendor/bin/phpunit; fi
+ - if [[ $PHPCS = 1 ]]; then vendor/bin/phpcs -p --extensions=php --standard=vendor/cakephp/cakephp-codesniffer/CakePHP ./src ./tests ./config ./webroot; fi
+
+notifications:
+ email: false
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 305136b..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,9 +0,0 @@
-The MIT License (MIT)
-
-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:
-
-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.
diff --git a/Makefile b/Makefile
deleted file mode 100644
index ea6dc80..0000000
--- a/Makefile
+++ /dev/null
@@ -1,19 +0,0 @@
-.PHONY: test verify release
-
-test:
- go test ./...
- go vet ./...
-
-verify: test
- go test -race ./...
-
-release:
- mkdir -p dist/release
- set -e; for target in darwin/arm64 linux/amd64; do \
- os=$${target%/*}; arch=$${target#*/}; \
- name=$$os; if [ "$$os" = darwin ]; then name=mac; fi; \
- CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -trimpath \
- -o dist/release/explorer-$$name-$$arch ./cmd/explorer; \
- done
- cp LICENSE THIRD-PARTY.md dist/release/
- cp -a licenses dist/release/
diff --git a/README.md b/README.md
index 57c5d60..e69de29 100644
--- a/README.md
+++ b/README.md
@@ -1,67 +0,0 @@
-> This is a Go rewrite of the LBRY block explorer. The previous PHP implementation is preserved on the [`php-version`](https://github.com/lbryio/block-explorer/tree/php-version) branch of this repository.
-
-# LBRY explorer
-
-A read-only block explorer for the LBRY blockchain.
-
-## Build and run
-
-Requires Go 1.23 or newer. From this directory:
-
-```sh
-make verify
-make release
-```
-
-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
-```
-
-Open . For development, use `go run ./cmd/explorer`.
-The application reads its configuration from the process environment; it does
-not automatically load `.env` files.
-
-## Configuration
-
-| 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
-}
-```
-
-See [TODO.md](TODO.md) for known issues and [THIRD-PARTY.md](THIRD-PARTY.md) for notices.
diff --git a/THIRD-PARTY.md b/THIRD-PARTY.md
deleted file mode 100644
index 8a15a63..0000000
--- a/THIRD-PARTY.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# Third-party notices
-
-Frontend assets retain their bundled notices and licenses under `webroot/`.
-
-| Component | Version / purpose | License text |
-| --- | --- | --- |
-| [filippo.io/edwards25519](https://filippo.io/edwards25519) | v1.1.0 | [license](licenses/filippo.io_edwards25519.txt) |
-| [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql) | v1.9.3 | [license](licenses/github.com_go-sql-driver_mysql.txt) |
-| [github.com/makiuchi-d/gozxing](https://github.com/makiuchi-d/gozxing) | v0.1.1 | [license](licenses/github.com_makiuchi-d_gozxing.txt) |
-| [golang.org/x/text](https://golang.org/x/text) | v0.3.7 | [license](licenses/golang.org_x_text.txt) |
-| [golang.org/x/xerrors](https://golang.org/x/xerrors) | v0.0.0-20200804184101-5ec99f83aff1 | [license](licenses/golang.org_x_xerrors.txt) |
-| Go standard library/runtime | Build toolchain | [BSD license](licenses/Go.txt) |
-| CakePHP | Error-layout compatibility | [MIT license](licenses/CakePHP.txt) |
-| BaconQrCode | QR capacity/mask compatibility | [BSD license](licenses/BaconQrCode.txt) |
-| Endroid QR | QR matrix/layout reference | [MIT license](licenses/Endroid.txt) |
-| PHP Group | `rounding.go` algorithm adapted from [PHP 8.5 math.c](https://github.com/php/php-src/blob/PHP-8.5/ext/standard/math.c) | [PHP License 3.01](licenses/PHP-3.01.txt) |
-
-PHP Group copyright and license apply to the adapted rounding algorithm. Other project code retains the project license. Unmodified Go module sources are identified by `go.mod`/`go.sum` and available with `go mod download`.
diff --git a/TODO.md b/TODO.md
deleted file mode 100644
index 4bf233f..0000000
--- a/TODO.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Known issues and follow-up work
-
-API behavior changes require a compatibility decision before implementation.
-
-- [ ] Measure opportunities for additional query caching, especially address-history totals and block-size aggregation.
-- [ ] Define and implement a JSON contract for `/api/v1/address/:addr/transactions`, which currently returns homepage HTML with HTTP 200.
-- [ ] Review unknown API-path handling. Unmatched paths, including retired tag URLs, return homepage HTML. Paid tagging is absent.
-- [ ] Fix the transaction fragment-link handler, which checks `txhash.trim` instead of calling `txhash.trim()`. Cover supported Coinomi/LBRY fragment formats.
-- [ ] Review unconfirmed address-history timestamps: a datetime returned by `IFNULL(transaction_time, created_at)` can be interpreted as a Unix timestamp and cause HTTP 500.
-- [ ] Review tiny monetary `DOUBLE` values and scientific notation. Decimal operations can reject these values; any repair needs an explicit decimal-contract decision.
-- [ ] Review empty-database blocks-list failures and the empty block link shown for `MEMPOOL` transactions.
diff --git a/bin/cake b/bin/cake
new file mode 100755
index 0000000..6801c45
--- /dev/null
+++ b/bin/cake
@@ -0,0 +1,46 @@
+#!/usr/bin/env sh
+################################################################################
+#
+# Cake is a shell script for invoking CakePHP shell commands
+#
+# CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
+# Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
+#
+# Licensed under The MIT License
+# For full copyright and license information, please see the LICENSE.txt
+# Redistributions of files must retain the above copyright notice.
+#
+# @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
+# @link http://cakephp.org CakePHP(tm) Project
+# @since 1.2.0
+# @license http://www.opensource.org/licenses/mit-license.php MIT License
+#
+################################################################################
+
+# Canonicalize by following every symlink of the given name recursively
+canonicalize() {
+ NAME="$1"
+ if [ -f "$NAME" ]
+ then
+ DIR=$(dirname -- "$NAME")
+ NAME=$(cd -P "$DIR" > /dev/null && pwd -P)/$(basename -- "$NAME")
+ fi
+ while [ -h "$NAME" ]; do
+ DIR=$(dirname -- "$NAME")
+ SYM=$(readlink "$NAME")
+ NAME=$(cd "$DIR" > /dev/null && cd $(dirname -- "$SYM") > /dev/null && pwd)/$(basename -- "$SYM")
+ done
+ echo "$NAME"
+}
+
+CONSOLE=$(dirname -- "$(canonicalize "$0")")
+APP=$(dirname "$CONSOLE")
+
+if [ $(basename $0) != 'cake' ]
+then
+ exec php "$CONSOLE"/cake.php $(basename $0) "$@"
+else
+ exec php "$CONSOLE"/cake.php "$@"
+fi
+
+exit
diff --git a/bin/cake.bat b/bin/cake.bat
new file mode 100644
index 0000000..d4512db
--- /dev/null
+++ b/bin/cake.bat
@@ -0,0 +1,27 @@
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+::
+:: Cake is a Windows batch script for invoking CakePHP shell commands
+::
+:: CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
+:: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
+::
+:: Licensed under The MIT License
+:: Redistributions of files must retain the above copyright notice.
+::
+:: @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
+:: @link http://cakephp.org CakePHP(tm) Project
+:: @since 2.0.0
+:: @license http://www.opensource.org/licenses/mit-license.php MIT License
+::
+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+
+@echo off
+
+SET app=%0
+SET lib=%~dp0
+
+php "%lib%cake.php" %*
+
+echo.
+
+exit /B %ERRORLEVEL%
diff --git a/bin/cake.php b/bin/cake.php
new file mode 100644
index 0000000..5ee314c
--- /dev/null
+++ b/bin/cake.php
@@ -0,0 +1,34 @@
+#!/usr/bin/php -q
+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));
diff --git a/cmd/explorer/main.go b/cmd/explorer/main.go
deleted file mode 100644
index 7bda42c..0000000
--- a/cmd/explorer/main.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package main
-
-import (
- "context"
- "explorer/internal/explorer"
- "log"
- "log/slog"
- "net"
- "net/http"
- "os"
- "os/signal"
- "syscall"
- "time"
-)
-
-func main() {
- dsn := os.Getenv("EXPLORER_MYSQL_DSN")
- if dsn == "" {
- log.Fatal("EXPLORER_MYSQL_DSN is required")
- }
- store, e := explorer.Open(dsn)
- if e != nil {
- log.Fatal("invalid MySQL configuration")
- }
- defer store.DB.Close()
- addr := os.Getenv("EXPLORER_LISTEN")
- if addr == "" {
- addr = "127.0.0.1:8080"
- }
- cache := os.Getenv("EXPLORER_CACHE_DIR")
- if cache == "" {
- cache = "var/cache/go"
- }
- logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
- observed := explorer.ObservedStore{Store: store, Logger: logger, Stats: store.DB.Stats}
- app := &explorer.Server{Store: observed, Logger: logger, Cache: explorer.Cache{Dir: cache}}
- server := &http.Server{Addr: addr, Handler: explorer.AccessLog(app, logger), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second}
- ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
- defer stop()
- listener, e := net.Listen("tcp", addr)
- if e != nil {
- log.Fatal(e)
- }
- log.Printf("listening on %s", listener.Addr())
- if e = runServer(ctx, server, listener); e != nil {
- log.Fatal(e)
- }
-}
-
-// Wait for Shutdown to drain active requests before returning from main.
-func runServer(ctx context.Context, server *http.Server, listener net.Listener) error {
- ctx, cancel := context.WithCancel(ctx)
- defer cancel()
- defer listener.Close()
- stopped := make(chan error, 1)
- go func() {
- <-ctx.Done()
- shutdownCtx, stop := context.WithTimeout(context.Background(), 10*time.Second)
- defer stop()
- err := server.Shutdown(shutdownCtx)
- if err != nil {
- server.Close()
- }
- stopped <- err
- }()
- if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
- return err
- }
- return <-stopped
-}
diff --git a/cmd/explorer/main_test.go b/cmd/explorer/main_test.go
deleted file mode 100644
index 52a5f61..0000000
--- a/cmd/explorer/main_test.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package main
-
-import (
- "context"
- "io"
- "net"
- "net/http"
- "testing"
- "time"
-)
-
-func TestShutdownDrainsActiveRequest(t *testing.T) {
- listener, e := net.Listen("tcp", "127.0.0.1:0")
- if e != nil {
- t.Fatal(e)
- }
- entered, release := make(chan struct{}), make(chan struct{})
- server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { close(entered); <-release; io.WriteString(w, "complete") })}
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- stopped := make(chan error, 1)
- go func() { stopped <- runServer(ctx, server, listener) }()
- result := make(chan string, 1)
- go func() {
- resp, e := http.Get("http://" + listener.Addr().String())
- if e != nil {
- result <- e.Error()
- return
- }
- defer resp.Body.Close()
- body, _ := io.ReadAll(resp.Body)
- result <- string(body)
- }()
- select {
- case <-entered:
- case <-time.After(time.Second):
- t.Fatal("request did not start")
- }
- cancel()
- select {
- case e := <-stopped:
- t.Fatal("shutdown returned before request drained", e)
- case <-time.After(30 * time.Millisecond):
- }
- close(release)
- select {
- case body := <-result:
- if body != "complete" {
- t.Fatal(body)
- }
- case <-time.After(time.Second):
- t.Fatal("request did not finish")
- }
- select {
- case e := <-stopped:
- if e != nil {
- t.Fatal(e)
- }
- case <-time.After(time.Second):
- t.Fatal("shutdown did not finish")
- }
-}
diff --git a/composer.json b/composer.json
new file mode 100644
index 0000000..79d60c9
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,53 @@
+{
+ "name": "cakephp/app",
+ "description": "CakePHP skeleton app",
+ "homepage": "http://cakephp.org",
+ "type": "project",
+ "license": "MIT",
+ "require": {
+ "php": ">=5.6",
+ "cakephp/cakephp": "3.4.*",
+ "mobiledetect/mobiledetectlib": "2.*",
+ "cakephp/migrations": "~1.0",
+ "cakephp/plugin-installer": "~1.0",
+ "mdanter/ecc": "^0.4.2",
+ "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
+}
diff --git a/composer.lock b/composer.lock
new file mode 100644
index 0000000..4634ac9
--- /dev/null
+++ b/composer.lock
@@ -0,0 +1,2737 @@
+{
+ "_readme": [
+ "This file locks the dependencies of your project to a known state",
+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
+ "This file is @generated automatically"
+ ],
+ "content-hash": "8508af8cab1d6513078a10e84e5a8833",
+ "packages": [
+ {
+ "name": "aura/intl",
+ "version": "3.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/auraphp/Aura.Intl.git",
+ "reference": "7fce228980b19bf4dee2d7bbd6202a69b0dde926"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/auraphp/Aura.Intl/zipball/7fce228980b19bf4dee2d7bbd6202a69b0dde926",
+ "reference": "7fce228980b19bf4dee2d7bbd6202a69b0dde926",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^5.6|^7.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Aura\\Intl\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Aura.Intl Contributors",
+ "homepage": "https://github.com/auraphp/Aura.Intl/contributors"
+ }
+ ],
+ "description": "The Aura Intl package provides internationalization tools, specifically message translation.",
+ "homepage": "https://github.com/auraphp/Aura.Intl",
+ "keywords": [
+ "g11n",
+ "globalization",
+ "i18n",
+ "internationalization",
+ "intl",
+ "l10n",
+ "localization"
+ ],
+ "time": "2017-01-20T05:00:11+00:00"
+ },
+ {
+ "name": "bacon/bacon-qr-code",
+ "version": "1.0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/Bacon/BaconQrCode.git",
+ "reference": "031a2ce68c5794064b49d11775b2daf45c96e21c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/031a2ce68c5794064b49d11775b2daf45c96e21c",
+ "reference": "031a2ce68c5794064b49d11775b2daf45c96e21c",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.3"
+ },
+ "suggest": {
+ "ext-gd": "to generate QR code images"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-0": {
+ "BaconQrCode": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-2-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Ben Scholzen 'DASPRiD'",
+ "email": "mail@dasprids.de",
+ "homepage": "http://www.dasprids.de",
+ "role": "Developer"
+ }
+ ],
+ "description": "BaconQrCode is a QR code generator for PHP.",
+ "homepage": "https://github.com/Bacon/BaconQrCode",
+ "time": "2016-01-09T22:55:35+00:00"
+ },
+ {
+ "name": "cakephp/cakephp",
+ "version": "3.4.7",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/cakephp/cakephp.git",
+ "reference": "b1aaa094894c020cd49d093bf5d6111fe26f5c45"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/cakephp/cakephp/zipball/b1aaa094894c020cd49d093bf5d6111fe26f5c45",
+ "reference": "b1aaa094894c020cd49d093bf5d6111fe26f5c45",
+ "shasum": ""
+ },
+ "require": {
+ "aura/intl": "^3.0.0",
+ "cakephp/chronos": "~1.0",
+ "ext-intl": "*",
+ "ext-mbstring": "*",
+ "php": ">=5.6.0",
+ "psr/log": "^1.0",
+ "zendframework/zend-diactoros": "^1.4"
+ },
+ "conflict": {
+ "phpunit/phpunit": "<5.7"
+ },
+ "replace": {
+ "cakephp/cache": "self.version",
+ "cakephp/collection": "self.version",
+ "cakephp/core": "self.version",
+ "cakephp/database": "self.version",
+ "cakephp/datasource": "self.version",
+ "cakephp/event": "self.version",
+ "cakephp/filesystem": "self.version",
+ "cakephp/form": "self.version",
+ "cakephp/i18n": "self.version",
+ "cakephp/log": "self.version",
+ "cakephp/orm": "self.version",
+ "cakephp/utility": "self.version",
+ "cakephp/validation": "self.version"
+ },
+ "require-dev": {
+ "cakephp/cakephp-codesniffer": "^3.0",
+ "phpunit/phpunit": "^5.7|^6.0"
+ },
+ "suggest": {
+ "ext-openssl": "To use Security::encrypt() or have secure CSRF token generation.",
+ "lib-ICU": "The intl PHP library, to use Text::transliterate() or Text::slug()"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Cake\\": "src"
+ },
+ "files": [
+ "src/Core/functions.php",
+ "src/Collection/functions.php",
+ "src/I18n/functions.php",
+ "src/Utility/bootstrap.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "CakePHP Community",
+ "homepage": "https://github.com/cakephp/cakephp/graphs/contributors"
+ }
+ ],
+ "description": "The CakePHP framework",
+ "homepage": "https://cakephp.org",
+ "keywords": [
+ "framework"
+ ],
+ "time": "2017-05-20T03:32:05+00:00"
+ },
+ {
+ "name": "cakephp/chronos",
+ "version": "1.1.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/cakephp/chronos.git",
+ "reference": "0621b191334d8dcb56907688986dd24eb8c38234"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/cakephp/chronos/zipball/0621b191334d8dcb56907688986dd24eb8c38234",
+ "reference": "0621b191334d8dcb56907688986dd24eb8c38234",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "require-dev": {
+ "athletic/athletic": "~0.1",
+ "cakephp/cakephp-codesniffer": "~2.3",
+ "phpbench/phpbench": "@dev",
+ "phpstan/phpstan": "^0.6.4",
+ "phpunit/phpunit": "<6.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Cake\\Chronos\\": "src"
+ },
+ "files": [
+ "src/carbon_compat.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Brian Nesbitt",
+ "email": "brian@nesbot.com",
+ "homepage": "http://nesbot.com"
+ },
+ {
+ "name": "The CakePHP Team",
+ "homepage": "http://cakephp.org"
+ }
+ ],
+ "description": "A simple API extension for DateTime.",
+ "homepage": "http://cakephp.org",
+ "keywords": [
+ "date",
+ "datetime",
+ "time"
+ ],
+ "time": "2017-04-27T01:27:49+00:00"
+ },
+ {
+ "name": "cakephp/migrations",
+ "version": "1.6.7",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/cakephp/migrations.git",
+ "reference": "f2a5e2915f8924bd36979a1001edeef7cd455f89"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/cakephp/migrations/zipball/f2a5e2915f8924bd36979a1001edeef7cd455f89",
+ "reference": "f2a5e2915f8924bd36979a1001edeef7cd455f89",
+ "shasum": ""
+ },
+ "require": {
+ "cakephp/cakephp": "~3.1",
+ "php": ">=5.4",
+ "robmorgan/phinx": "0.6.5"
+ },
+ "require-dev": {
+ "cakephp/bake": "@stable",
+ "phpunit/phpunit": "*"
+ },
+ "suggest": {
+ "cakephp/bake": "Required if you want to generate migrations."
+ },
+ "type": "cakephp-plugin",
+ "autoload": {
+ "psr-4": {
+ "Migrations\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "CakePHP Community",
+ "homepage": "https://github.com/cakephp/migrations/graphs/contributors"
+ }
+ ],
+ "description": "Database Migration plugin for CakePHP 3.0 based on Phinx",
+ "homepage": "https://github.com/cakephp/migrations",
+ "keywords": [
+ "cakephp",
+ "migrations"
+ ],
+ "time": "2017-01-07T16:45:31+00:00"
+ },
+ {
+ "name": "cakephp/plugin-installer",
+ "version": "1.0.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/cakephp/plugin-installer.git",
+ "reference": "3449cb3251e3e741b123237765e278005565d8de"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/cakephp/plugin-installer/zipball/3449cb3251e3e741b123237765e278005565d8de",
+ "reference": "3449cb3251e3e741b123237765e278005565d8de",
+ "shasum": ""
+ },
+ "require-dev": {
+ "cakephp/cakephp-codesniffer": "dev-master",
+ "composer/composer": "1.0.*@dev",
+ "phpunit/phpunit": "^4.8|^5.7|^6.0"
+ },
+ "type": "composer-installer",
+ "extra": {
+ "class": "Cake\\Composer\\Installer\\PluginInstaller"
+ },
+ "autoload": {
+ "psr-4": {
+ "Cake\\Composer\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "CakePHP Community",
+ "homepage": "http://cakephp.org"
+ }
+ ],
+ "description": "A composer installer for CakePHP 3.0+ plugins.",
+ "time": "2017-03-21T13:48:47+00:00"
+ },
+ {
+ "name": "endroid/qrcode",
+ "version": "2.2.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/endroid/QrCode.git",
+ "reference": "daa07e11249362e0fc0edf97f83719794d87726b"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/endroid/QrCode/zipball/daa07e11249362e0fc0edf97f83719794d87726b",
+ "reference": "daa07e11249362e0fc0edf97f83719794d87726b",
+ "shasum": ""
+ },
+ "require": {
+ "bacon/bacon-qr-code": "^1.0",
+ "ext-gd": "*",
+ "khanamiryan/qrcode-detector-decoder": "^0.0.1",
+ "myclabs/php-enum": "^1.5",
+ "php": ">=5.6",
+ "symfony/options-resolver": "^2.7|^3.0",
+ "symfony/property-access": "^2.7|^3.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^5.7|^6.0",
+ "sensio/framework-extra-bundle": "^3.0",
+ "symfony/asset": "^2.7|^3.0",
+ "symfony/browser-kit": "^2.7|^3.0",
+ "symfony/finder": "^2.7|^3.0",
+ "symfony/framework-bundle": "^2.7|^3.0",
+ "symfony/http-kernel": "^2.7|^3.0",
+ "symfony/templating": "^2.7|^3.0",
+ "symfony/twig-bundle": "^2.7|^3.0",
+ "symfony/yaml": "^2.7|^3.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "2.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Endroid\\QrCode\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jeroen van den Enden",
+ "email": "info@endroid.nl",
+ "homepage": "http://endroid.nl/"
+ }
+ ],
+ "description": "Endroid QR Code",
+ "homepage": "https://github.com/endroid/QrCode",
+ "keywords": [
+ "bundle",
+ "code",
+ "endroid",
+ "qr",
+ "qrcode",
+ "symfony"
+ ],
+ "time": "2017-05-30T13:53:47+00:00"
+ },
+ {
+ "name": "fgrosse/phpasn1",
+ "version": "1.5.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/fgrosse/PHPASN1.git",
+ "reference": "a18b162eca6aa70f8f15615f4ac8c852dffbc7dd"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/fgrosse/PHPASN1/zipball/a18b162eca6aa70f8f15615f4ac8c852dffbc7dd",
+ "reference": "a18b162eca6aa70f8f15615f4ac8c852dffbc7dd",
+ "shasum": ""
+ },
+ "require": {
+ "ext-gmp": "*",
+ "php": ">=5.6.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "~4.5",
+ "satooshi/php-coveralls": "dev-master"
+ },
+ "suggest": {
+ "php-curl": "For loading OID information from the web if they have not bee defined statically"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.5.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "FG\\": "lib/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Friedrich Große",
+ "email": "friedrich.grosse@gmail.com",
+ "homepage": "https://github.com/FGrosse",
+ "role": "Author"
+ },
+ {
+ "name": "All contributors",
+ "homepage": "https://github.com/FGrosse/PHPASN1/contributors"
+ }
+ ],
+ "description": "A PHP Framework that allows you to encode and decode arbitrary ASN.1 structures using the ITU-T X.690 Encoding Rules.",
+ "homepage": "https://github.com/FGrosse/PHPASN1",
+ "keywords": [
+ "DER",
+ "asn.1",
+ "asn1",
+ "ber",
+ "binary",
+ "decoding",
+ "encoding",
+ "x.509",
+ "x.690",
+ "x509",
+ "x690"
+ ],
+ "time": "2016-10-29T15:46:46+00:00"
+ },
+ {
+ "name": "khanamiryan/qrcode-detector-decoder",
+ "version": "0.0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/khanamiryan/php-qrcode-detector-decoder.git",
+ "reference": "96d5f80680b04803c4f1b69d6e01735e876b80c7"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/khanamiryan/php-qrcode-detector-decoder/zipball/96d5f80680b04803c4f1b69d6e01735e876b80c7",
+ "reference": "96d5f80680b04803c4f1b69d6e01735e876b80c7",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^5.6|^7.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^5.7"
+ },
+ "type": "library",
+ "autoload": {
+ "classmap": [
+ "lib/"
+ ],
+ "files": [
+ "lib/common/customFunctions.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Ashot Khanamiryan",
+ "email": "a.khanamiryan@gmail.com",
+ "homepage": "https://github.com/khanamiryan",
+ "role": "Developer"
+ }
+ ],
+ "description": "QR code decoder / reader",
+ "homepage": "https://github.com/khanamiryan/php-qrcode-detector-decoder",
+ "keywords": [
+ "barcode",
+ "qr",
+ "zxing"
+ ],
+ "time": "2017-01-13T09:11:46+00:00"
+ },
+ {
+ "name": "mdanter/ecc",
+ "version": "v0.4.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/phpecc/phpecc.git",
+ "reference": "fdd1fa9be8184c9f319433437cb1d9f9d4294164"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/phpecc/phpecc/zipball/fdd1fa9be8184c9f319433437cb1d9f9d4294164",
+ "reference": "fdd1fa9be8184c9f319433437cb1d9f9d4294164",
+ "shasum": ""
+ },
+ "require": {
+ "ext-gmp": "*",
+ "fgrosse/phpasn1": "~1.5",
+ "paragonie/random_compat": "^1|^2",
+ "php": ">=5.6.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "~4.1|~5.0",
+ "squizlabs/php_codesniffer": "~2",
+ "symfony/yaml": "~2.6|~3.0"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Mdanter\\Ecc\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Matyas Danter",
+ "homepage": "http://matejdanter.com/",
+ "role": "Author"
+ },
+ {
+ "name": "Thibaud Fabre",
+ "email": "thibaud@aztech.io",
+ "homepage": "http://aztech.io",
+ "role": "Maintainer"
+ }
+ ],
+ "description": "PHP Elliptic Curve Cryptography library",
+ "homepage": "https://github.com/phpecc/phpecc",
+ "keywords": [
+ "Diffie",
+ "ECDSA",
+ "Hellman",
+ "curve",
+ "ecdh",
+ "elliptic",
+ "nistp192",
+ "nistp224",
+ "nistp256",
+ "nistp521",
+ "phpecc",
+ "secp256k1"
+ ],
+ "time": "2017-01-04T12:13:24+00:00"
+ },
+ {
+ "name": "mobiledetect/mobiledetectlib",
+ "version": "2.8.25",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/serbanghita/Mobile-Detect.git",
+ "reference": "f0896b5c7274d1450023b0b376240be902c3251c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/serbanghita/Mobile-Detect/zipball/f0896b5c7274d1450023b0b376240be902c3251c",
+ "reference": "f0896b5c7274d1450023b0b376240be902c3251c",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.0.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "*"
+ },
+ "type": "library",
+ "autoload": {
+ "classmap": [
+ "Mobile_Detect.php"
+ ],
+ "psr-0": {
+ "Detection": "namespaced/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Serban Ghita",
+ "email": "serbanghita@gmail.com",
+ "homepage": "http://mobiledetect.net",
+ "role": "Developer"
+ }
+ ],
+ "description": "Mobile_Detect is a lightweight PHP class for detecting mobile devices. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.",
+ "homepage": "https://github.com/serbanghita/Mobile-Detect",
+ "keywords": [
+ "detect mobile devices",
+ "mobile",
+ "mobile detect",
+ "mobile detector",
+ "php mobile detect"
+ ],
+ "time": "2017-03-29T13:59:30+00:00"
+ },
+ {
+ "name": "myclabs/php-enum",
+ "version": "1.5.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/myclabs/php-enum.git",
+ "reference": "61f4a24da5be216301447f3278ea6562609d61f5"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/myclabs/php-enum/zipball/61f4a24da5be216301447f3278ea6562609d61f5",
+ "reference": "61f4a24da5be216301447f3278ea6562609d61f5",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "4.*",
+ "squizlabs/php_codesniffer": "1.*"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "MyCLabs\\Enum\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "PHP Enum contributors",
+ "homepage": "https://github.com/myclabs/php-enum/graphs/contributors"
+ }
+ ],
+ "description": "PHP Enum implementation",
+ "homepage": "http://github.com/myclabs/php-enum",
+ "keywords": [
+ "enum"
+ ],
+ "time": "2017-03-26T10:24:21+00:00"
+ },
+ {
+ "name": "nesbot/carbon",
+ "version": "1.22.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/briannesbitt/Carbon.git",
+ "reference": "7cdf42c0b1cc763ab7e4c33c47a24e27c66bfccc"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/briannesbitt/Carbon/zipball/7cdf42c0b1cc763ab7e4c33c47a24e27c66bfccc",
+ "reference": "7cdf42c0b1cc763ab7e4c33c47a24e27c66bfccc",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.0",
+ "symfony/translation": "~2.6 || ~3.0"
+ },
+ "require-dev": {
+ "friendsofphp/php-cs-fixer": "~2",
+ "phpunit/phpunit": "~4.0 || ~5.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.23-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Carbon\\": "src/Carbon/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Brian Nesbitt",
+ "email": "brian@nesbot.com",
+ "homepage": "http://nesbot.com"
+ }
+ ],
+ "description": "A simple API extension for DateTime.",
+ "homepage": "http://carbon.nesbot.com",
+ "keywords": [
+ "date",
+ "datetime",
+ "time"
+ ],
+ "time": "2017-01-16T07:55:07+00:00"
+ },
+ {
+ "name": "paragonie/random_compat",
+ "version": "v2.0.10",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/paragonie/random_compat.git",
+ "reference": "634bae8e911eefa89c1abfbf1b66da679ac8f54d"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/paragonie/random_compat/zipball/634bae8e911eefa89c1abfbf1b66da679ac8f54d",
+ "reference": "634bae8e911eefa89c1abfbf1b66da679ac8f54d",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.2.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "4.*|5.*"
+ },
+ "suggest": {
+ "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
+ },
+ "type": "library",
+ "autoload": {
+ "files": [
+ "lib/random.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Paragon Initiative Enterprises",
+ "email": "security@paragonie.com",
+ "homepage": "https://paragonie.com"
+ }
+ ],
+ "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
+ "keywords": [
+ "csprng",
+ "pseudorandom",
+ "random"
+ ],
+ "time": "2017-03-13T16:27:32+00:00"
+ },
+ {
+ "name": "predis/predis",
+ "version": "v1.1.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/nrk/predis.git",
+ "reference": "f0210e38881631afeafb56ab43405a92cafd9fd1"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/nrk/predis/zipball/f0210e38881631afeafb56ab43405a92cafd9fd1",
+ "reference": "f0210e38881631afeafb56ab43405a92cafd9fd1",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.9"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "~4.8"
+ },
+ "suggest": {
+ "ext-curl": "Allows access to Webdis when paired with phpiredis",
+ "ext-phpiredis": "Allows faster serialization and deserialization of the Redis protocol"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Predis\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Daniele Alessandri",
+ "email": "suppakilla@gmail.com",
+ "homepage": "http://clorophilla.net"
+ }
+ ],
+ "description": "Flexible and feature-complete Redis client for PHP and HHVM",
+ "homepage": "http://github.com/nrk/predis",
+ "keywords": [
+ "nosql",
+ "predis",
+ "redis"
+ ],
+ "time": "2016-06-16T16:22:20+00:00"
+ },
+ {
+ "name": "psr/http-message",
+ "version": "1.0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/php-fig/http-message.git",
+ "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
+ "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.0.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Psr\\Http\\Message\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "PHP-FIG",
+ "homepage": "http://www.php-fig.org/"
+ }
+ ],
+ "description": "Common interface for HTTP messages",
+ "homepage": "https://github.com/php-fig/http-message",
+ "keywords": [
+ "http",
+ "http-message",
+ "psr",
+ "psr-7",
+ "request",
+ "response"
+ ],
+ "time": "2016-08-06T14:39:51+00:00"
+ },
+ {
+ "name": "psr/log",
+ "version": "1.0.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/php-fig/log.git",
+ "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
+ "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.0.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Psr\\Log\\": "Psr/Log/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "PHP-FIG",
+ "homepage": "http://www.php-fig.org/"
+ }
+ ],
+ "description": "Common interface for logging libraries",
+ "homepage": "https://github.com/php-fig/log",
+ "keywords": [
+ "log",
+ "psr",
+ "psr-3"
+ ],
+ "time": "2016-10-10T12:19:37+00:00"
+ },
+ {
+ "name": "robmorgan/phinx",
+ "version": "v0.6.5",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/robmorgan/phinx.git",
+ "reference": "6943cb4bb78bf9d3964967a032220b7c793b97b7"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/robmorgan/phinx/zipball/6943cb4bb78bf9d3964967a032220b7c793b97b7",
+ "reference": "6943cb4bb78bf9d3964967a032220b7c793b97b7",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.4",
+ "symfony/config": "~2.8|~3.0",
+ "symfony/console": "~2.8|~3.0",
+ "symfony/yaml": "~2.8|~3.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.8.26|^5.0"
+ },
+ "bin": [
+ "bin/phinx"
+ ],
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Phinx\\": "src/Phinx"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Woody Gilk",
+ "email": "woody.gilk@gmail.com",
+ "homepage": "http://shadowhand.me",
+ "role": "Developer"
+ },
+ {
+ "name": "Rob Morgan",
+ "email": "robbym@gmail.com",
+ "homepage": "https://robmorgan.id.au",
+ "role": "Lead Developer"
+ },
+ {
+ "name": "Richard Quadling",
+ "email": "rquadling@gmail.com",
+ "role": "Developer"
+ }
+ ],
+ "description": "Phinx makes it ridiculously easy to manage the database migrations for your PHP app.",
+ "homepage": "https://phinx.org",
+ "keywords": [
+ "database",
+ "database migrations",
+ "db",
+ "migrations",
+ "phinx"
+ ],
+ "time": "2016-10-27T10:16:12+00:00"
+ },
+ {
+ "name": "symfony/config",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/config.git",
+ "reference": "35716d4904e0506a7a5a9bcf23f854aeb5719bca"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/config/zipball/35716d4904e0506a7a5a9bcf23f854aeb5719bca",
+ "reference": "35716d4904e0506a7a5a9bcf23f854aeb5719bca",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9",
+ "symfony/filesystem": "~2.8|~3.0"
+ },
+ "conflict": {
+ "symfony/dependency-injection": "<3.3"
+ },
+ "require-dev": {
+ "symfony/dependency-injection": "~3.3",
+ "symfony/yaml": "~3.0"
+ },
+ "suggest": {
+ "symfony/yaml": "To use the yaml reference dumper"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Config\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Config Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-06-02T18:07:20+00:00"
+ },
+ {
+ "name": "symfony/console",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/console.git",
+ "reference": "70d2a29b2911cbdc91a7e268046c395278238b2e"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/console/zipball/70d2a29b2911cbdc91a7e268046c395278238b2e",
+ "reference": "70d2a29b2911cbdc91a7e268046c395278238b2e",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9",
+ "symfony/debug": "~2.8|~3.0",
+ "symfony/polyfill-mbstring": "~1.0"
+ },
+ "conflict": {
+ "symfony/dependency-injection": "<3.3"
+ },
+ "require-dev": {
+ "psr/log": "~1.0",
+ "symfony/config": "~3.3",
+ "symfony/dependency-injection": "~3.3",
+ "symfony/event-dispatcher": "~2.8|~3.0",
+ "symfony/filesystem": "~2.8|~3.0",
+ "symfony/http-kernel": "~2.8|~3.0",
+ "symfony/process": "~2.8|~3.0"
+ },
+ "suggest": {
+ "psr/log": "For using the console logger",
+ "symfony/event-dispatcher": "",
+ "symfony/filesystem": "",
+ "symfony/process": ""
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Console\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Console Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-06-02T19:24:58+00:00"
+ },
+ {
+ "name": "symfony/debug",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/debug.git",
+ "reference": "e9c50482841ef696e8fa1470d950a79c8921f45d"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/debug/zipball/e9c50482841ef696e8fa1470d950a79c8921f45d",
+ "reference": "e9c50482841ef696e8fa1470d950a79c8921f45d",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9",
+ "psr/log": "~1.0"
+ },
+ "conflict": {
+ "symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2"
+ },
+ "require-dev": {
+ "symfony/http-kernel": "~2.8|~3.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Debug\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Debug Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-06-01T21:01:25+00:00"
+ },
+ {
+ "name": "symfony/filesystem",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/filesystem.git",
+ "reference": "c709670bf64721202ddbe4162846f250735842c0"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/filesystem/zipball/c709670bf64721202ddbe4162846f250735842c0",
+ "reference": "c709670bf64721202ddbe4162846f250735842c0",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Filesystem\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Filesystem Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-05-28T14:08:56+00:00"
+ },
+ {
+ "name": "symfony/inflector",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/inflector.git",
+ "reference": "aed5a0874a3bcfd8d0393a2d91b4cf828f29c7fb"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/inflector/zipball/aed5a0874a3bcfd8d0393a2d91b4cf828f29c7fb",
+ "reference": "aed5a0874a3bcfd8d0393a2d91b4cf828f29c7fb",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Inflector\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Bernhard Schussek",
+ "email": "bschussek@gmail.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Inflector Component",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "inflection",
+ "pluralize",
+ "singularize",
+ "string",
+ "symfony",
+ "words"
+ ],
+ "time": "2017-04-12T14:14:56+00:00"
+ },
+ {
+ "name": "symfony/options-resolver",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/options-resolver.git",
+ "reference": "ff48982d295bcac1fd861f934f041ebc73ae40f0"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/options-resolver/zipball/ff48982d295bcac1fd861f934f041ebc73ae40f0",
+ "reference": "ff48982d295bcac1fd861f934f041ebc73ae40f0",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\OptionsResolver\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony OptionsResolver Component",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "config",
+ "configuration",
+ "options"
+ ],
+ "time": "2017-04-12T14:14:56+00:00"
+ },
+ {
+ "name": "symfony/polyfill-mbstring",
+ "version": "v1.4.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-mbstring.git",
+ "reference": "f29dca382a6485c3cbe6379f0c61230167681937"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/f29dca382a6485c3cbe6379f0c61230167681937",
+ "reference": "f29dca382a6485c3cbe6379f0c61230167681937",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.3"
+ },
+ "suggest": {
+ "ext-mbstring": "For best performance"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.4-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Polyfill\\Mbstring\\": ""
+ },
+ "files": [
+ "bootstrap.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill for the Mbstring extension",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "mbstring",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "time": "2017-06-09T14:24:12+00:00"
+ },
+ {
+ "name": "symfony/polyfill-php70",
+ "version": "v1.4.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/polyfill-php70.git",
+ "reference": "032fd647d5c11a9ceab8ee8747e13b5448e93874"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/032fd647d5c11a9ceab8ee8747e13b5448e93874",
+ "reference": "032fd647d5c11a9ceab8ee8747e13b5448e93874",
+ "shasum": ""
+ },
+ "require": {
+ "paragonie/random_compat": "~1.0|~2.0",
+ "php": ">=5.3.3"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.4-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Polyfill\\Php70\\": ""
+ },
+ "files": [
+ "bootstrap.php"
+ ],
+ "classmap": [
+ "Resources/stubs"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "compatibility",
+ "polyfill",
+ "portable",
+ "shim"
+ ],
+ "time": "2017-06-09T14:24:12+00:00"
+ },
+ {
+ "name": "symfony/property-access",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/property-access.git",
+ "reference": "70bbfe28f77070d41957495bc6fed34f139fe6f7"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/property-access/zipball/70bbfe28f77070d41957495bc6fed34f139fe6f7",
+ "reference": "70bbfe28f77070d41957495bc6fed34f139fe6f7",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9",
+ "symfony/inflector": "~3.1",
+ "symfony/polyfill-php70": "~1.0"
+ },
+ "require-dev": {
+ "symfony/cache": "~3.1"
+ },
+ "suggest": {
+ "psr/cache-implementation": "To cache access methods."
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\PropertyAccess\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony PropertyAccess Component",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "access",
+ "array",
+ "extraction",
+ "index",
+ "injection",
+ "object",
+ "property",
+ "property path",
+ "reflection"
+ ],
+ "time": "2017-06-02T09:51:43+00:00"
+ },
+ {
+ "name": "symfony/translation",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/translation.git",
+ "reference": "dc3b2a0c6cfff60327ba1c043a82092735397543"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/translation/zipball/dc3b2a0c6cfff60327ba1c043a82092735397543",
+ "reference": "dc3b2a0c6cfff60327ba1c043a82092735397543",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9",
+ "symfony/polyfill-mbstring": "~1.0"
+ },
+ "conflict": {
+ "symfony/config": "<2.8",
+ "symfony/yaml": "<3.3"
+ },
+ "require-dev": {
+ "psr/log": "~1.0",
+ "symfony/config": "~2.8|~3.0",
+ "symfony/intl": "^2.8.18|^3.2.5",
+ "symfony/yaml": "~3.3"
+ },
+ "suggest": {
+ "psr/log": "To use logging capability in translator",
+ "symfony/config": "",
+ "symfony/yaml": ""
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Translation\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Translation Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-05-22T07:42:36+00:00"
+ },
+ {
+ "name": "symfony/yaml",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/yaml.git",
+ "reference": "9752a30000a8ca9f4b34b5227d15d0101b96b063"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/yaml/zipball/9752a30000a8ca9f4b34b5227d15d0101b96b063",
+ "reference": "9752a30000a8ca9f4b34b5227d15d0101b96b063",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "require-dev": {
+ "symfony/console": "~2.8|~3.0"
+ },
+ "suggest": {
+ "symfony/console": "For validating YAML files using the lint command"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Yaml\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Yaml Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-06-02T22:05:06+00:00"
+ },
+ {
+ "name": "zendframework/zend-diactoros",
+ "version": "1.4.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/zendframework/zend-diactoros.git",
+ "reference": "b03f285a333f51e58c95cce54109a4a9ed691436"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/zendframework/zend-diactoros/zipball/b03f285a333f51e58c95cce54109a4a9ed691436",
+ "reference": "b03f285a333f51e58c95cce54109a4a9ed691436",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^5.4 || ^7.0",
+ "psr/http-message": "~1.0"
+ },
+ "provide": {
+ "psr/http-message-implementation": "1.0"
+ },
+ "require-dev": {
+ "ext-dom": "*",
+ "ext-libxml": "*",
+ "phpunit/phpunit": "^4.6 || ^5.5",
+ "zendframework/zend-coding-standard": "~1.0.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.4-dev",
+ "dev-develop": "1.5-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Zend\\Diactoros\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-2-Clause"
+ ],
+ "description": "PSR HTTP Message implementations",
+ "homepage": "https://github.com/zendframework/zend-diactoros",
+ "keywords": [
+ "http",
+ "psr",
+ "psr-7"
+ ],
+ "time": "2017-04-06T16:18:34+00:00"
+ }
+ ],
+ "packages-dev": [
+ {
+ "name": "cakephp/bake",
+ "version": "1.3.5",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/cakephp/bake.git",
+ "reference": "6fe5dc1bcdd321ffc35e847ae0e0ab1effde2278"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/cakephp/bake/zipball/6fe5dc1bcdd321ffc35e847ae0e0ab1effde2278",
+ "reference": "6fe5dc1bcdd321ffc35e847ae0e0ab1effde2278",
+ "shasum": ""
+ },
+ "require": {
+ "cakephp/cakephp": ">=3.4.0 <4.0.0",
+ "cakephp/plugin-installer": "*",
+ "php": ">=5.6.0"
+ },
+ "require-dev": {
+ "cakephp/cakephp-codesniffer": "^3.0",
+ "phpunit/phpunit": "~5.7 | ~6.0"
+ },
+ "type": "cakephp-plugin",
+ "autoload": {
+ "psr-4": {
+ "Bake\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "CakePHP Community",
+ "homepage": "https://github.com/cakephp/bake/graphs/contributors"
+ }
+ ],
+ "description": "Bake plugin for CakePHP 3.0",
+ "homepage": "https://github.com/cakephp/bake",
+ "keywords": [
+ "bake",
+ "cakephp"
+ ],
+ "time": "2017-06-05T23:32:05+00:00"
+ },
+ {
+ "name": "cakephp/debug_kit",
+ "version": "3.10.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/cakephp/debug_kit.git",
+ "reference": "a0583e2cb58e80940fd4aeb026be48d5f0000ff2"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/cakephp/debug_kit/zipball/a0583e2cb58e80940fd4aeb026be48d5f0000ff2",
+ "reference": "a0583e2cb58e80940fd4aeb026be48d5f0000ff2",
+ "shasum": ""
+ },
+ "require": {
+ "cakephp/cakephp": "^3.4.0",
+ "cakephp/chronos": "^1.0.0",
+ "cakephp/plugin-installer": "^1.0.0",
+ "composer/composer": "^1.3.0",
+ "jdorn/sql-formatter": "^1.2.0"
+ },
+ "require-dev": {
+ "cakephp/cakephp-codesniffer": "^3.0",
+ "phpunit/phpunit": "<6.0"
+ },
+ "suggest": {
+ "ext-sqlite": "DebugKit needs to store panel data in a database. SQLite is simple and easy to use."
+ },
+ "type": "cakephp-plugin",
+ "autoload": {
+ "psr-4": {
+ "DebugKit\\": "src",
+ "DebugKit\\Test\\Fixture\\": "tests\\Fixture"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Mark Story",
+ "homepage": "http://mark-story.com",
+ "role": "Author"
+ },
+ {
+ "name": "CakePHP Community",
+ "homepage": "https://github.com/cakephp/debug_kit/graphs/contributors"
+ }
+ ],
+ "description": "CakePHP Debug Kit",
+ "homepage": "https://github.com/cakephp/debug_kit",
+ "keywords": [
+ "cakephp",
+ "debug",
+ "kit"
+ ],
+ "time": "2017-05-12T16:10:13+00:00"
+ },
+ {
+ "name": "composer/ca-bundle",
+ "version": "1.0.7",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/composer/ca-bundle.git",
+ "reference": "b17e6153cb7f33c7e44eb59578dc12eee5dc8e12"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/composer/ca-bundle/zipball/b17e6153cb7f33c7e44eb59578dc12eee5dc8e12",
+ "reference": "b17e6153cb7f33c7e44eb59578dc12eee5dc8e12",
+ "shasum": ""
+ },
+ "require": {
+ "ext-openssl": "*",
+ "ext-pcre": "*",
+ "php": "^5.3.2 || ^7.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.5",
+ "psr/log": "^1.0",
+ "symfony/process": "^2.5 || ^3.0"
+ },
+ "suggest": {
+ "symfony/process": "This is necessary to reliably check whether openssl_x509_parse is vulnerable on older php versions, but can be ignored on PHP 5.5.6+"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Composer\\CaBundle\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jordi Boggiano",
+ "email": "j.boggiano@seld.be",
+ "homepage": "http://seld.be"
+ }
+ ],
+ "description": "Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.",
+ "keywords": [
+ "cabundle",
+ "cacert",
+ "certificate",
+ "ssl",
+ "tls"
+ ],
+ "time": "2017-03-06T11:59:08+00:00"
+ },
+ {
+ "name": "composer/composer",
+ "version": "1.4.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/composer/composer.git",
+ "reference": "489e09ee6c3ba431fbeeef9147afdaeb6f91b647"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/composer/composer/zipball/489e09ee6c3ba431fbeeef9147afdaeb6f91b647",
+ "reference": "489e09ee6c3ba431fbeeef9147afdaeb6f91b647",
+ "shasum": ""
+ },
+ "require": {
+ "composer/ca-bundle": "^1.0",
+ "composer/semver": "^1.0",
+ "composer/spdx-licenses": "^1.0",
+ "justinrainbow/json-schema": "^3.0 || ^4.0 || ^5.0",
+ "php": "^5.3.2 || ^7.0",
+ "psr/log": "^1.0",
+ "seld/cli-prompt": "^1.0",
+ "seld/jsonlint": "^1.4",
+ "seld/phar-utils": "^1.0",
+ "symfony/console": "^2.7 || ^3.0",
+ "symfony/filesystem": "^2.7 || ^3.0",
+ "symfony/finder": "^2.7 || ^3.0",
+ "symfony/process": "^2.7 || ^3.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.5 || ^5.0.5",
+ "phpunit/phpunit-mock-objects": "^2.3 || ^3.0"
+ },
+ "suggest": {
+ "ext-openssl": "Enabling the openssl extension allows you to access https URLs for repositories and packages",
+ "ext-zip": "Enabling the zip extension allows you to unzip archives",
+ "ext-zlib": "Allow gzip compression of HTTP requests"
+ },
+ "bin": [
+ "bin/composer"
+ ],
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.4-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Composer\\": "src/Composer"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nils Adermann",
+ "email": "naderman@naderman.de",
+ "homepage": "http://www.naderman.de"
+ },
+ {
+ "name": "Jordi Boggiano",
+ "email": "j.boggiano@seld.be",
+ "homepage": "http://seld.be"
+ }
+ ],
+ "description": "Composer helps you declare, manage and install dependencies of PHP projects, ensuring you have the right stack everywhere.",
+ "homepage": "https://getcomposer.org/",
+ "keywords": [
+ "autoload",
+ "dependency",
+ "package"
+ ],
+ "time": "2017-05-17T06:17:53+00:00"
+ },
+ {
+ "name": "composer/semver",
+ "version": "1.4.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/composer/semver.git",
+ "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/composer/semver/zipball/c7cb9a2095a074d131b65a8a0cd294479d785573",
+ "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^5.3.2 || ^7.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.5 || ^5.0.5",
+ "phpunit/phpunit-mock-objects": "2.3.0 || ^3.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Composer\\Semver\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nils Adermann",
+ "email": "naderman@naderman.de",
+ "homepage": "http://www.naderman.de"
+ },
+ {
+ "name": "Jordi Boggiano",
+ "email": "j.boggiano@seld.be",
+ "homepage": "http://seld.be"
+ },
+ {
+ "name": "Rob Bast",
+ "email": "rob.bast@gmail.com",
+ "homepage": "http://robbast.nl"
+ }
+ ],
+ "description": "Semver library that offers utilities, version constraint parsing and validation.",
+ "keywords": [
+ "semantic",
+ "semver",
+ "validation",
+ "versioning"
+ ],
+ "time": "2016-08-30T16:08:34+00:00"
+ },
+ {
+ "name": "composer/spdx-licenses",
+ "version": "1.1.6",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/composer/spdx-licenses.git",
+ "reference": "2603a0d7ddc00a015deb576fa5297ca43dee6b1c"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/composer/spdx-licenses/zipball/2603a0d7ddc00a015deb576fa5297ca43dee6b1c",
+ "reference": "2603a0d7ddc00a015deb576fa5297ca43dee6b1c",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^5.3.2 || ^7.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.5 || ^5.0.5",
+ "phpunit/phpunit-mock-objects": "2.3.0 || ^3.0"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Composer\\Spdx\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nils Adermann",
+ "email": "naderman@naderman.de",
+ "homepage": "http://www.naderman.de"
+ },
+ {
+ "name": "Jordi Boggiano",
+ "email": "j.boggiano@seld.be",
+ "homepage": "http://seld.be"
+ },
+ {
+ "name": "Rob Bast",
+ "email": "rob.bast@gmail.com",
+ "homepage": "http://robbast.nl"
+ }
+ ],
+ "description": "SPDX licenses list and validation library.",
+ "keywords": [
+ "license",
+ "spdx",
+ "validator"
+ ],
+ "time": "2017-04-03T19:08:52+00:00"
+ },
+ {
+ "name": "dnoegel/php-xdg-base-dir",
+ "version": "0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/dnoegel/php-xdg-base-dir.git",
+ "reference": "265b8593498b997dc2d31e75b89f053b5cc9621a"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/dnoegel/php-xdg-base-dir/zipball/265b8593498b997dc2d31e75b89f053b5cc9621a",
+ "reference": "265b8593498b997dc2d31e75b89f053b5cc9621a",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.2"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "@stable"
+ },
+ "type": "project",
+ "autoload": {
+ "psr-4": {
+ "XdgBaseDir\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "implementation of xdg base directory specification for php",
+ "time": "2014-10-24T07:27:01+00:00"
+ },
+ {
+ "name": "jakub-onderka/php-console-color",
+ "version": "0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/JakubOnderka/PHP-Console-Color.git",
+ "reference": "e0b393dacf7703fc36a4efc3df1435485197e6c1"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/JakubOnderka/PHP-Console-Color/zipball/e0b393dacf7703fc36a4efc3df1435485197e6c1",
+ "reference": "e0b393dacf7703fc36a4efc3df1435485197e6c1",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.2"
+ },
+ "require-dev": {
+ "jakub-onderka/php-code-style": "1.0",
+ "jakub-onderka/php-parallel-lint": "0.*",
+ "jakub-onderka/php-var-dump-check": "0.*",
+ "phpunit/phpunit": "3.7.*",
+ "squizlabs/php_codesniffer": "1.*"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-0": {
+ "JakubOnderka\\PhpConsoleColor": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-2-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Jakub Onderka",
+ "email": "jakub.onderka@gmail.com",
+ "homepage": "http://www.acci.cz"
+ }
+ ],
+ "time": "2014-04-08T15:00:19+00:00"
+ },
+ {
+ "name": "jakub-onderka/php-console-highlighter",
+ "version": "v0.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/JakubOnderka/PHP-Console-Highlighter.git",
+ "reference": "7daa75df45242c8d5b75a22c00a201e7954e4fb5"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/JakubOnderka/PHP-Console-Highlighter/zipball/7daa75df45242c8d5b75a22c00a201e7954e4fb5",
+ "reference": "7daa75df45242c8d5b75a22c00a201e7954e4fb5",
+ "shasum": ""
+ },
+ "require": {
+ "jakub-onderka/php-console-color": "~0.1",
+ "php": ">=5.3.0"
+ },
+ "require-dev": {
+ "jakub-onderka/php-code-style": "~1.0",
+ "jakub-onderka/php-parallel-lint": "~0.5",
+ "jakub-onderka/php-var-dump-check": "~0.1",
+ "phpunit/phpunit": "~4.0",
+ "squizlabs/php_codesniffer": "~1.5"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-0": {
+ "JakubOnderka\\PhpConsoleHighlighter": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jakub Onderka",
+ "email": "acci@acci.cz",
+ "homepage": "http://www.acci.cz/"
+ }
+ ],
+ "time": "2015-04-20T18:58:01+00:00"
+ },
+ {
+ "name": "jdorn/sql-formatter",
+ "version": "v1.2.17",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/jdorn/sql-formatter.git",
+ "reference": "64990d96e0959dff8e059dfcdc1af130728d92bc"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/jdorn/sql-formatter/zipball/64990d96e0959dff8e059dfcdc1af130728d92bc",
+ "reference": "64990d96e0959dff8e059dfcdc1af130728d92bc",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.2.4"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "3.7.*"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.3.x-dev"
+ }
+ },
+ "autoload": {
+ "classmap": [
+ "lib"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jeremy Dorn",
+ "email": "jeremy@jeremydorn.com",
+ "homepage": "http://jeremydorn.com/"
+ }
+ ],
+ "description": "a PHP SQL highlighting library",
+ "homepage": "https://github.com/jdorn/sql-formatter/",
+ "keywords": [
+ "highlight",
+ "sql"
+ ],
+ "time": "2014-01-12T16:20:24+00:00"
+ },
+ {
+ "name": "justinrainbow/json-schema",
+ "version": "5.2.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/justinrainbow/json-schema.git",
+ "reference": "429be236f296ca249d61c65649cdf2652f4a5e80"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/justinrainbow/json-schema/zipball/429be236f296ca249d61c65649cdf2652f4a5e80",
+ "reference": "429be236f296ca249d61c65649cdf2652f4a5e80",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3.3"
+ },
+ "require-dev": {
+ "friendsofphp/php-cs-fixer": "^2.1",
+ "json-schema/json-schema-test-suite": "1.2.0",
+ "phpdocumentor/phpdocumentor": "^2.7",
+ "phpunit/phpunit": "^4.8.22"
+ },
+ "bin": [
+ "bin/validate-json"
+ ],
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "5.0.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "JsonSchema\\": "src/JsonSchema/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Bruno Prieto Reis",
+ "email": "bruno.p.reis@gmail.com"
+ },
+ {
+ "name": "Justin Rainbow",
+ "email": "justin.rainbow@gmail.com"
+ },
+ {
+ "name": "Igor Wiedler",
+ "email": "igor@wiedler.ch"
+ },
+ {
+ "name": "Robert Schönthal",
+ "email": "seroscho@googlemail.com"
+ }
+ ],
+ "description": "A library to validate a json schema.",
+ "homepage": "https://github.com/justinrainbow/json-schema",
+ "keywords": [
+ "json",
+ "schema"
+ ],
+ "time": "2017-05-16T21:06:09+00:00"
+ },
+ {
+ "name": "nikic/php-parser",
+ "version": "v3.0.5",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/nikic/PHP-Parser.git",
+ "reference": "2b9e2f71b722f7c53918ab0c25f7646c2013f17d"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/2b9e2f71b722f7c53918ab0c25f7646c2013f17d",
+ "reference": "2b9e2f71b722f7c53918ab0c25f7646c2013f17d",
+ "shasum": ""
+ },
+ "require": {
+ "ext-tokenizer": "*",
+ "php": ">=5.5"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "~4.0|~5.0"
+ },
+ "bin": [
+ "bin/php-parse"
+ ],
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.0-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "PhpParser\\": "lib/PhpParser"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "BSD-3-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Nikita Popov"
+ }
+ ],
+ "description": "A PHP parser written in PHP",
+ "keywords": [
+ "parser",
+ "php"
+ ],
+ "time": "2017-03-05T18:23:57+00:00"
+ },
+ {
+ "name": "psy/psysh",
+ "version": "v0.8.6",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/bobthecow/psysh.git",
+ "reference": "7028d6d525fb183d50b249b7c07598e3d386b27d"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/bobthecow/psysh/zipball/7028d6d525fb183d50b249b7c07598e3d386b27d",
+ "reference": "7028d6d525fb183d50b249b7c07598e3d386b27d",
+ "shasum": ""
+ },
+ "require": {
+ "dnoegel/php-xdg-base-dir": "0.1",
+ "jakub-onderka/php-console-highlighter": "0.3.*",
+ "nikic/php-parser": "~1.3|~2.0|~3.0",
+ "php": ">=5.3.9",
+ "symfony/console": "~2.3.10|^2.4.2|~3.0",
+ "symfony/var-dumper": "~2.7|~3.0"
+ },
+ "require-dev": {
+ "friendsofphp/php-cs-fixer": "~1.11",
+ "hoa/console": "~3.16|~1.14",
+ "phpunit/phpunit": "~4.4|~5.0",
+ "symfony/finder": "~2.1|~3.0"
+ },
+ "suggest": {
+ "ext-pcntl": "Enabling the PCNTL extension makes PsySH a lot happier :)",
+ "ext-pdo-sqlite": "The doc command requires SQLite to work.",
+ "ext-posix": "If you have PCNTL, you'll want the POSIX extension as well.",
+ "ext-readline": "Enables support for arrow-key history navigation, and showing and manipulating command history.",
+ "hoa/console": "A pure PHP readline implementation. You'll want this if your PHP install doesn't already support readline or libedit."
+ },
+ "bin": [
+ "bin/psysh"
+ ],
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-develop": "0.8.x-dev"
+ }
+ },
+ "autoload": {
+ "files": [
+ "src/Psy/functions.php"
+ ],
+ "psr-4": {
+ "Psy\\": "src/Psy/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Justin Hileman",
+ "email": "justin@justinhileman.info",
+ "homepage": "http://justinhileman.com"
+ }
+ ],
+ "description": "An interactive shell for modern PHP.",
+ "homepage": "http://psysh.org",
+ "keywords": [
+ "REPL",
+ "console",
+ "interactive",
+ "shell"
+ ],
+ "time": "2017-06-04T10:34:20+00:00"
+ },
+ {
+ "name": "seld/cli-prompt",
+ "version": "1.0.3",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/Seldaek/cli-prompt.git",
+ "reference": "a19a7376a4689d4d94cab66ab4f3c816019ba8dd"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/Seldaek/cli-prompt/zipball/a19a7376a4689d4d94cab66ab4f3c816019ba8dd",
+ "reference": "a19a7376a4689d4d94cab66ab4f3c816019ba8dd",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Seld\\CliPrompt\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jordi Boggiano",
+ "email": "j.boggiano@seld.be"
+ }
+ ],
+ "description": "Allows you to prompt for user input on the command line, and optionally hide the characters they type",
+ "keywords": [
+ "cli",
+ "console",
+ "hidden",
+ "input",
+ "prompt"
+ ],
+ "time": "2017-03-18T11:32:45+00:00"
+ },
+ {
+ "name": "seld/jsonlint",
+ "version": "1.6.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/Seldaek/jsonlint.git",
+ "reference": "791f8c594f300d246cdf01c6b3e1e19611e301d8"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/Seldaek/jsonlint/zipball/791f8c594f300d246cdf01c6b3e1e19611e301d8",
+ "reference": "791f8c594f300d246cdf01c6b3e1e19611e301d8",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^5.3 || ^7.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^4.5"
+ },
+ "bin": [
+ "bin/jsonlint"
+ ],
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Seld\\JsonLint\\": "src/Seld/JsonLint/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jordi Boggiano",
+ "email": "j.boggiano@seld.be",
+ "homepage": "http://seld.be"
+ }
+ ],
+ "description": "JSON Linter",
+ "keywords": [
+ "json",
+ "linter",
+ "parser",
+ "validator"
+ ],
+ "time": "2017-03-06T16:42:24+00:00"
+ },
+ {
+ "name": "seld/phar-utils",
+ "version": "1.0.1",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/Seldaek/phar-utils.git",
+ "reference": "7009b5139491975ef6486545a39f3e6dad5ac30a"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/Seldaek/phar-utils/zipball/7009b5139491975ef6486545a39f3e6dad5ac30a",
+ "reference": "7009b5139491975ef6486545a39f3e6dad5ac30a",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.3"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "1.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Seld\\PharUtils\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Jordi Boggiano",
+ "email": "j.boggiano@seld.be"
+ }
+ ],
+ "description": "PHAR file format utilities, for when PHP phars you up",
+ "keywords": [
+ "phra"
+ ],
+ "time": "2015-10-13T18:44:15+00:00"
+ },
+ {
+ "name": "symfony/finder",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/finder.git",
+ "reference": "baea7f66d30854ad32988c11a09d7ffd485810c4"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/finder/zipball/baea7f66d30854ad32988c11a09d7ffd485810c4",
+ "reference": "baea7f66d30854ad32988c11a09d7ffd485810c4",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Finder\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Finder Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-06-01T21:01:25+00:00"
+ },
+ {
+ "name": "symfony/process",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/process.git",
+ "reference": "8e30690c67aafb6c7992d6d8eb0d707807dd3eaf"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/process/zipball/8e30690c67aafb6c7992d6d8eb0d707807dd3eaf",
+ "reference": "8e30690c67aafb6c7992d6d8eb0d707807dd3eaf",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Symfony\\Component\\Process\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Fabien Potencier",
+ "email": "fabien@symfony.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony Process Component",
+ "homepage": "https://symfony.com",
+ "time": "2017-05-22T12:32:03+00:00"
+ },
+ {
+ "name": "symfony/var-dumper",
+ "version": "v3.3.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/symfony/var-dumper.git",
+ "reference": "347c4247a3e40018810b476fcd5dec36d46d08dc"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/symfony/var-dumper/zipball/347c4247a3e40018810b476fcd5dec36d46d08dc",
+ "reference": "347c4247a3e40018810b476fcd5dec36d46d08dc",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=5.5.9",
+ "symfony/polyfill-mbstring": "~1.0"
+ },
+ "conflict": {
+ "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0"
+ },
+ "require-dev": {
+ "ext-iconv": "*",
+ "twig/twig": "~1.34|~2.4"
+ },
+ "suggest": {
+ "ext-iconv": "To convert non-UTF-8 strings to UTF-8 (or symfony/polyfill-iconv in case ext-iconv cannot be used).",
+ "ext-symfony_debug": ""
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "3.3-dev"
+ }
+ },
+ "autoload": {
+ "files": [
+ "Resources/functions/dump.php"
+ ],
+ "psr-4": {
+ "Symfony\\Component\\VarDumper\\": ""
+ },
+ "exclude-from-classmap": [
+ "/Tests/"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Nicolas Grekas",
+ "email": "p@tchwork.com"
+ },
+ {
+ "name": "Symfony Community",
+ "homepage": "https://symfony.com/contributors"
+ }
+ ],
+ "description": "Symfony mechanism for exploring and dumping PHP variables",
+ "homepage": "https://symfony.com",
+ "keywords": [
+ "debug",
+ "dump"
+ ],
+ "time": "2017-06-02T09:10:29+00:00"
+ }
+ ],
+ "aliases": [],
+ "minimum-stability": "stable",
+ "stability-flags": {
+ "psy/psysh": 0
+ },
+ "prefer-stable": true,
+ "prefer-lowest": false,
+ "platform": {
+ "php": ">=5.6"
+ },
+ "platform-dev": []
+}
diff --git a/config/app.default.php b/config/app.default.php
new file mode 100644
index 0000000..c06599e
--- /dev/null
+++ b/config/app.default.php
@@ -0,0 +1,346 @@
+ 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/.php.
+ * Make sure the class implements PHP's `SessionHandlerInterface` and set
+ * Session.handler to
+ *
+ * To use database sessions, load the SQL file located at config/Schema/sessions.sql
+ */
+ 'Session' => [
+ 'defaults' => 'php',
+ ],
+];
diff --git a/config/bootstrap.php b/config/bootstrap.php
new file mode 100644
index 0000000..a3ac0d0
--- /dev/null
+++ b/config/bootstrap.php
@@ -0,0 +1,222 @@
+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]);
+}
diff --git a/config/bootstrap_cli.php b/config/bootstrap_cli.php
new file mode 100644
index 0000000..f822a55
--- /dev/null
+++ b/config/bootstrap_cli.php
@@ -0,0 +1,38 @@
+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();
diff --git a/config/schema/i18n.sql b/config/schema/i18n.sql
new file mode 100644
index 0000000..47cf171
--- /dev/null
+++ b/config/schema/i18n.sql
@@ -0,0 +1,18 @@
+# Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
+#
+# Licensed under The MIT License
+# For full copyright and license information, please see the LICENSE.txt
+# Redistributions of files must retain the above copyright notice.
+# MIT License (http://www.opensource.org/licenses/mit-license.php)
+
+CREATE TABLE i18n (
+ id int NOT NULL auto_increment,
+ locale varchar(6) NOT NULL,
+ model varchar(255) NOT NULL,
+ foreign_key int(10) NOT NULL,
+ field varchar(255) NOT NULL,
+ content text,
+ PRIMARY KEY (id),
+ UNIQUE INDEX I18N_LOCALE_FIELD(locale, model, foreign_key, field),
+ INDEX I18N_FIELD(model, foreign_key, field)
+);
diff --git a/config/schema/sessions.sql b/config/schema/sessions.sql
new file mode 100644
index 0000000..b5a5276
--- /dev/null
+++ b/config/schema/sessions.sql
@@ -0,0 +1,13 @@
+# Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
+#
+# Licensed under The MIT License
+# For full copyright and license information, please see the LICENSE.txt
+# Redistributions of files must retain the above copyright notice.
+# MIT License (http://www.opensource.org/licenses/mit-license.php)
+
+CREATE TABLE sessions (
+ id char(40) NOT NULL,
+ data text,
+ expires INT(11) NOT NULL,
+ PRIMARY KEY (id)
+);
diff --git a/cron/addrtx.sh b/cron/addrtx.sh
new file mode 100755
index 0000000..b3c02e9
--- /dev/null
+++ b/cron/addrtx.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block addrtxamounts
+
diff --git a/cron/blocks.sh b/cron/blocks.sh
new file mode 100755
index 0000000..dc5c788
--- /dev/null
+++ b/cron/blocks.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block parsenewblocks
+
diff --git a/cron/blockstuff.php b/cron/blockstuff.php
new file mode 100644
index 0000000..a2b9f38
--- /dev/null
+++ b/cron/blockstuff.php
@@ -0,0 +1,137 @@
+_startHeight = $startBlock;
+ $this->_endHeight = $endBlock;
+ $this->_maxHeight = $maxHeight;
+ }
+
+ public function run() {
+ $conn = new \PDO("mysql:host=localhost;dbname=lbry", 'lbry-admin', '46D861aX#!yQ');
+ $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+ $data_error = false;
+ $conn->beginTransaction();
+
+ // TODO: Batch block synchronisation from memory to DB
+
+ for ($curr_height = $this->_startHeight; $curr_height <= $this->_endHeight; $curr_height++) {
+ $idx_str = str_pad($curr_height, strlen($this->_maxHeight), '0', STR_PAD_LEFT);
+
+ // get the block hash
+ $req = ['method' => 'getblockhash', 'params' => [$curr_height]];
+ $response = BlockStuff::curl_json_post(BlockStuff::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $curr_block_hash = $json->result;
+
+ $req = ['method' => 'getblock', 'params' => [$curr_block_hash]];
+ $response = BlockStuff::curl_json_post(BlockStuff::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $curr_block = $json->result;
+
+ $stmt = $conn->prepare('UPDATE Blocks SET Confirmations = ? WHERE Height = ?');
+ try {
+ $stmt->execute([$curr_block->confirmations, $curr_height]);
+ echo "[$idx_str/$this->_maxHeight] Updated block height: $curr_height with confirmations $curr_block->confirmations.\n";
+ } catch (Exception $e) {
+ $data_error = true;
+ }
+ }
+
+ if ($data_error) {
+ echo "Rolling back changes.\n";
+ $conn->rollBack();
+ return;
+ }
+
+ echo "Committing data.\n";
+ $conn->commit();
+ }
+}
+
+class BlockStuff {
+ const rpcurl = 'http://lrpc:lrpc@127.0.0.1:9245';
+ public static function blocksync() {
+ self::lock('blocksync');
+
+ $conn = new \PDO("mysql:host=localhost;dbname=lbry", 'lbry-admin', '46D861aX#!yQ');
+
+ $stmt = $conn->prepare('SELECT Height FROM Blocks ORDER BY Height DESC LIMIT 1');
+ $stmt->execute([]);
+ $max_block = $stmt->fetch(PDO::FETCH_OBJ);
+ if ($max_block) {
+ $chunk_limit = 2;
+ $curr_height = 0;
+ $chunks = floor($max_block->Height / $chunk_limit);
+ $threads = [];
+ for ($i = 0; $i < $chunk_limit; $i++) {
+ $start = $curr_height;
+ $end = ($i == ($chunk_limit - 1)) ? $max_block->Height : $start + $chunks;
+ $curr_height += $chunks + 1;
+ $thread = new BlockSyncThread($start, $end, $max_block->Height);
+ $threads[] = $thread;
+
+ $thread->start();
+ }
+
+ for ($i = 0; $i < count($threads); $i++) {
+ $threads[$i]->join();
+ }
+ }
+
+ self::unlock('blocksync');
+ }
+
+ public static function curl_json_post($url, $data, $headers = []) {
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ $response = curl_exec($ch);
+ //Log::debug('Request execution completed.');
+ if ($response === false) {
+ $error = curl_error($ch);
+ $errno = curl_errno($ch);
+ curl_close($ch);
+
+ throw new \Exception(sprintf('The request failed: %s', $error), $errno);
+ } else {
+ curl_close($ch);
+ }
+
+ // Close any open file handle
+ return $response;
+ }
+
+ public static function lock($process_name) {
+ if (!is_dir(TMP . 'lock')) {
+ mkdir(TMP . 'lock');
+ }
+ $lock_file = TMP . 'lock' . DS . $process_name;
+ if (file_exists($lock_file)) {
+ echo "$process_name is already running.\n";
+ exit(0);
+ }
+ file_put_contents($lock_file, '1');
+ }
+
+ public static function unlock($process_name) {
+ $lock_file = TMP . 'lock' . DS . $process_name;
+ if (file_exists($lock_file)) {
+ unlink($lock_file);
+ }
+ return true;
+ }
+}
+
+BlockStuff::blocksync();
diff --git a/cron/blocktx.sh b/cron/blocktx.sh
new file mode 100755
index 0000000..0cead96
--- /dev/null
+++ b/cron/blocktx.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block parsetxs
+
diff --git a/cron/claimindex.sh b/cron/claimindex.sh
new file mode 100755
index 0000000..04b173f
--- /dev/null
+++ b/cron/claimindex.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block buildclaimindex
+
diff --git a/cron/confirmations.sh b/cron/confirmations.sh
new file mode 100755
index 0000000..7ff4ad4
--- /dev/null
+++ b/cron/confirmations.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng/cron
+php -d extension=pthreads.so blockstuff.php
diff --git a/cron/fixzero.sh b/cron/fixzero.sh
new file mode 100755
index 0000000..039fea1
--- /dev/null
+++ b/cron/fixzero.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block fixzerooutputs
+
diff --git a/cron/forevermempool.sh b/cron/forevermempool.sh
new file mode 100755
index 0000000..2eab3d7
--- /dev/null
+++ b/cron/forevermempool.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block forevermempool &
+
diff --git a/cron/livetx.sh b/cron/livetx.sh
new file mode 100755
index 0000000..18ac6bc
--- /dev/null
+++ b/cron/livetx.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block parsemempool
+
diff --git a/cron/pricehistory.sh b/cron/pricehistory.sh
new file mode 100755
index 0000000..7a06adf
--- /dev/null
+++ b/cron/pricehistory.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake aux pricehistory
+
diff --git a/cron/spends.sh b/cron/spends.sh
new file mode 100755
index 0000000..c5f5402
--- /dev/null
+++ b/cron/spends.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake block updatespends
+
diff --git a/cron/verifytags.sh b/cron/verifytags.sh
new file mode 100755
index 0000000..653c468
--- /dev/null
+++ b/cron/verifytags.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+cd /var/www/lbry.block.ng
+bin/cake aux verifytags
+
diff --git a/deploy/explorer.env.example b/deploy/explorer.env.example
deleted file mode 100644
index ce0c1fd..0000000
--- a/deploy/explorer.env.example
+++ /dev/null
@@ -1,3 +0,0 @@
-# Keep the real file outside the checkout, owned by root and mode 0600.
-# Use an existing SELECT-only account. Never put actual credentials here.
-EXPLORER_MYSQL_DSN=explorer_reader:REPLACE_ME@tcp(DB_HOST:3306)/chainquery
diff --git a/deploy/explorer.service b/deploy/explorer.service
deleted file mode 100644
index cf24366..0000000
--- a/deploy/explorer.service
+++ /dev/null
@@ -1,28 +0,0 @@
-[Unit]
-Description=LBRY explorer Go frontend
-After=network-online.target
-Wants=network-online.target
-
-[Service]
-Type=simple
-User=explorer
-Group=explorer
-WorkingDirectory=/opt/lbry-explorer/current
-EnvironmentFile=/etc/lbry-explorer/explorer.env
-Environment=EXPLORER_LISTEN=127.0.0.1:8080
-Environment=EXPLORER_CACHE_DIR=/var/cache/lbry-explorer/go
-ExecStart=/opt/lbry-explorer/current/explorer
-Restart=on-failure
-RestartSec=3
-TimeoutStopSec=15
-CacheDirectory=lbry-explorer/go
-UMask=0077
-NoNewPrivileges=true
-PrivateTmp=true
-ProtectSystem=strict
-ProtectHome=true
-StandardOutput=journal
-StandardError=journal
-
-[Install]
-WantedBy=multi-user.target
diff --git a/deploy/nginx-location.conf.example b/deploy/nginx-location.conf.example
deleted file mode 100644
index 5ab3545..0000000
--- a/deploy/nginx-location.conf.example
+++ /dev/null
@@ -1,11 +0,0 @@
-# Include in the explorer.lbry.com server block.
-# Keep its TLS, intended cache headers and error handling.
-# Proxy assets as well as pages: Go releases need no disk webroot.
-# Adjust/remove any older static-file locations that take precedence over this.
-location / {
- proxy_pass http://127.0.0.1:8080;
- proxy_set_header Host $http_host;
- proxy_set_header X-Forwarded-Proto $scheme;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_read_timeout 300s;
-}
diff --git a/go.mod b/go.mod
deleted file mode 100644
index b56c3ee..0000000
--- a/go.mod
+++ /dev/null
@@ -1,14 +0,0 @@
-module explorer
-
-go 1.23
-
-require (
- github.com/go-sql-driver/mysql v1.9.3
- github.com/makiuchi-d/gozxing v0.1.1
-)
-
-require (
- filippo.io/edwards25519 v1.1.0 // indirect
- golang.org/x/text v0.3.7 // indirect
- golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
-)
diff --git a/go.sum b/go.sum
deleted file mode 100644
index 9926f59..0000000
--- a/go.sum
+++ /dev/null
@@ -1,10 +0,0 @@
-filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
-filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
-github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
-github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
-github.com/makiuchi-d/gozxing v0.1.1 h1:xxqijhoedi+/lZlhINteGbywIrewVdVv2wl9r5O9S1I=
-github.com/makiuchi-d/gozxing v0.1.1/go.mod h1:eRIHbOjX7QWxLIDJoQuMLhuXg9LAuw6znsUtRkNw9DU=
-golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
-golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
-golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
-golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
diff --git a/index.php b/index.php
new file mode 100644
index 0000000..fc5e39c
--- /dev/null
+++ b/index.php
@@ -0,0 +1,16 @@
+ ? 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})
-}
diff --git a/internal/explorer/api_more.go b/internal/explorer/api_more.go
deleted file mode 100644
index 7c212e0..0000000
--- a/internal/explorer/api_more.go
+++ /dev/null
@@ -1,275 +0,0 @@
-package explorer
-
-import (
- "encoding/json"
- "fmt"
- "math/big"
- "math/rand/v2"
- "net/http"
- "regexp"
- "strconv"
- "strings"
- "time"
-)
-
-func placeholders(n int) string { return strings.TrimSuffix(strings.Repeat("?,", n), ",") }
-
-var bcNumber = regexp.MustCompile(`^(?:[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+))?$`)
-
-func validBCString(s string) bool { return bcNumber.MatchString(s) }
-
-func decimal(v any) *big.Rat {
- r := new(big.Rat)
- if _, ok := r.SetString(text(v)); !ok {
- return new(big.Rat)
- }
- return r
-}
-func truncated(r *big.Rat, places int) string {
- scale := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(places)), nil)
- n := new(big.Int).Mul(r.Num(), scale)
- n.Quo(n, r.Denom())
- sign := ""
- if n.Sign() < 0 {
- sign = "-"
- n.Abs(n)
- }
- s := n.String()
- if places == 0 {
- return sign + s
- }
- for len(s) <= places {
- s = "0" + s
- }
- return sign + s[:len(s)-places] + "." + s[len(s)-places:]
-}
-func phpString(v any) string {
- if v == nil {
- return "0"
- }
- if f, ok := v.(float64); ok {
- s := strconv.FormatFloat(f, 'G', 14, 64)
- if i := strings.IndexByte(s, 'E'); i >= 0 {
- mantissa := s[:i]
- if !strings.Contains(mantissa, ".") {
- mantissa += ".0"
- }
- exp, _ := strconv.Atoi(s[i+1:])
- s = mantissa + fmt.Sprintf("E%+d", exp)
- }
- return s
- }
- return text(v)
-}
-func (s *Server) remainingAPI(w http.ResponseWriter, r *http.Request) bool {
- path := r.URL.Path
- q := func(sql string, args ...any) ([]Row, bool) {
- rows, e := s.Store.Query(r.Context(), sql, args...)
- if e != nil {
- internalError(w)
- return nil, false
- }
- return rows, true
- }
- if path == "/api/v1/charts/inflation" {
- if r.Method != "GET" {
- jsonError(w, 400, "Invalid HTTP request method.")
- return true
- }
- if b, ok := s.cachedArray("inflation_chart"); ok {
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Data json.RawMessage `json:"data"`
- }{true, b})
- return true
- }
- highest, ok := q("SELECT height FROM block WHERE confirmations > 0 ORDER BY height DESC LIMIT 1")
- if !ok {
- return true
- }
- if len(highest) == 0 {
- clientError(w, r, 404, "Not Found")
- return true
- }
- h := int(number(highest[0]["height"]))
- args := []any{}
- for i := 0; i <= h; i += 1000 {
- args = append(args, i)
- }
- if h%1000 != 0 {
- args = append(args, h)
- }
- samples, ok := q("SELECT height,block_time FROM block WHERE height IN ("+placeholders(len(args))+") AND confirmations > 0 ORDER BY height ASC", args...)
- if !ok {
- return true
- }
- recent, ok := q("SELECT height,block_time FROM block WHERE confirmations > 0 ORDER BY height DESC LIMIT 101")
- if !ok {
- return true
- }
- for a, b := 0, len(recent)-1; a < b; a, b = a+1, b-1 {
- recent[a], recent[b] = recent[b], recent[a]
- }
- data := struct {
- Samples []Row `json:"samples"`
- Recent []Row `json:"recent"`
- Last int `json:"last_reward_block"`
- Interval int `json:"future_sample_interval"`
- }{orderedRows(samples, "height", "block_time"), orderedRows(recent, "height", "block_time"), 4071017, 1000}
- b, e := phpJSON(data)
- if e == nil {
- s.Cache.Put("inflation_chart", b, 10*time.Minute)
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Data any `json:"data"`
- }{true, data})
- return true
- }
- if path == "/api/v1/supply" {
- if b, ok := s.cachedArray("utxo_supply"); ok {
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Supply json.RawMessage `json:"utxosupply"`
- }{true, b})
- return true
- }
- total, ok := q("SELECT SUM(balance) AS balance FROM address")
- if !ok {
- return true
- }
- addresses := []any{"rEqocTgdPdoD8NEbrECTUPfpquJ4zPVCJ8", "r7hj61jdbGXcsccxw8UmEFCReZoCWLRr7t", "rKaAUDxr24hHNNTQuNtRvNt8SGYJMdLXo3", "bRo4FEeqqxY7nWFANsZsuKEWByEgkvz8Qt", "bU2XUzckfpdEuQNemKvhPT1gexQ3GG3SC2", "bay3VA6YTQBL4WLobbG7CthmoGeUKXuXkD", "bLPbiXBp6Vr3NSnsHzDsLNzoy5o36re9Cz", "bMvUBo1h5WS46ThHtmfmXftz3z33VHL7wc", "bVUrbCK8hcZ5XWti7b9eNxKEBxzc1rr393", "bZja2VyhAC84a9hMwT8dwTU6rDRXowrjxH", "bCrboXVztuSbZzVToCWSsu1pEr2oxKHu9v", "bMgqQqYfwzWWYBk5o5dBMXtCndVAoeqy6h", "bX6napXtY2nVTBRc8PwULBuGWn2i3SCtrN"}
- reserved, ok := q("SELECT SUM(balance) AS balance FROM address WHERE address IN ("+placeholders(len(addresses))+")", addresses...)
- if !ok {
- return true
- }
- t, rv := "0", "0"
- if len(total) > 0 {
- t = phpString(total[0]["balance"])
- }
- if len(reserved) > 0 {
- rv = phpString(reserved[0]["balance"])
- }
- if !validBCString(t) || !validBCString(rv) {
- internalError(w)
- return true
- }
- data := struct {
- Total string `json:"total"`
- Circulating string `json:"circulating"`
- }{t, truncated(new(big.Rat).Sub(decimal(t), decimal(rv)), 8)}
- b, e := phpJSON(data)
- if e == nil {
- s.Cache.Put("utxo_supply", b, time.Hour)
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Supply any `json:"utxosupply"`
- }{true, data})
- return true
- }
- if strings.HasPrefix(path, "/api/v1/address/") && strings.HasSuffix(path, "/utxo") {
- addr := strings.TrimSuffix(strings.TrimPrefix(path, "/api/v1/address/"), "/utxo")
- if addr == "" || strings.Contains(addr, "/") {
- return false
- }
- parts := strings.Split(addr, ",")
- args := make([]any, len(parts))
- for i, p := range parts {
- args[i] = p
- }
- addresses, ok := q("SELECT id,address FROM address WHERE address IN ("+placeholders(len(args))+")", args...)
- if !ok {
- return true
- }
- if len(addresses) == 0 {
- jsonError(w, 404, "No base58 address matching the specified parameter was found.")
- return true
- }
- args = nil
- conditions := []string{}
- for _, a := range addresses {
- args = append(args, a["id"])
- conditions = append(conditions, "JSON_CONTAINS(O.address_list, JSON_QUOTE(?))")
- }
- for _, a := range addresses {
- args = append(args, a["address"])
- }
- rows, ok := q("SELECT T.hash AS transaction_hash,O.vout,O.value,O.address_list,O.script_pub_key_asm,O.script_pub_key_hex,O.type,O.required_signatures,B.confirmations FROM transaction T JOIN output O ON O.transaction_id = T.id JOIN block B ON B.hash = T.block_hash_id WHERE O.transaction_id IN (SELECT TA.transaction_id FROM transaction_address TA WHERE TA.address_id IN ("+placeholders(len(addresses))+")) AND ("+strings.Join(conditions, " OR ")+") AND O.is_spent <> 1 ORDER BY T.transaction_time ASC", args...)
- if !ok {
- return true
- }
- out := make([]Row, 0, len(rows))
- for _, row := range rows {
- if !validBCString(phpString(row["value"])) {
- internalError(w)
- return true
- }
- var list any
- json.Unmarshal([]byte(text(row["address_list"])), &list)
- atomic := new(big.Rat).Mul(decimal(phpString(row["value"])), big.NewRat(100000000, 1))
- value, _ := strconv.ParseInt(truncated(atomic, 0), 10, 64)
- out = append(out, Row{"transaction_hash": row["transaction_hash"], "output_index": row["vout"], "value": value, "addresses": list, "script": row["script_pub_key_asm"], "script_hex": row["script_pub_key_hex"], "script_type": row["type"], "required_signatures": int(number(row["required_signatures"])), "spent": false, "confirmations": int(number(row["confirmations"]))})
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- UTXO []Row `json:"utxo"`
- }{true, orderedRows(out, "transaction_hash", "output_index", "value", "addresses", "script", "script_hex", "script_type", "required_signatures", "spent", "confirmations")})
- return true
- }
- if path == "/api/v1/claims/browse" {
- before, after := max(0, queryInt(r, "before")), queryInt(r, "after")
- sort := phpTrim(queryString(r, "sort"))
- order := "DESC"
- var randomStart int
- if sort == "oldest" || sort == "random" {
- order = "ASC"
- }
- if sort == "random" {
- last, ok := q("SELECT id FROM claim ORDER BY id DESC LIMIT 1")
- if !ok {
- return true
- }
- if len(last) > 0 {
- maxID := int(number(last[0]["id"]))
- if maxID > 0 {
- randomStart = rand.IntN(maxID) + 1
- if s.RandomInt != nil {
- randomStart = s.RandomInt(maxID) + 1
- }
- }
- }
- }
- where := "Claims.thumbnail_url IS NOT NULL AND Claims.thumbnail_url != '' AND Claims.is_filtered != 1"
- args := []any{}
- if after > 0 {
- where += " AND Claims.id > ?"
- args = append(args, after)
- order = "ASC"
- } else if before > 0 {
- where += " AND Claims.id < ?"
- args = append(args, before)
- order = "DESC"
- } else if randomStart > 0 {
- where += " AND Claims.id >= ?"
- args = append(args, randomStart)
- }
- if phpTrim(queryString(r, "nsfw")) != "true" {
- where += " AND Claims.is_nsfw != 1"
- }
- rows, ok := q(fmt.Sprintf("SELECT Claims.*,Publisher.name AS publisher FROM claim Claims LEFT JOIN claim Publisher ON Publisher.claim_id = Claims.publisher_id WHERE %s ORDER BY Claims.id %s LIMIT 48", where, order), args...)
- if !ok {
- return true
- }
- if rows == nil {
- rows = []Row{}
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Claims []Row `json:"claims"`
- Total int `json:"total"`
- }{true, claimEntities(rows), 23000000})
- return true
- }
- return false
-}
diff --git a/internal/explorer/api_test.go b/internal/explorer/api_test.go
deleted file mode 100644
index c833afa..0000000
--- a/internal/explorer/api_test.go
+++ /dev/null
@@ -1,187 +0,0 @@
-package explorer
-
-import (
- "context"
- "encoding/json"
- "io"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
- "time"
-)
-
-type scriptedStore struct {
- sets [][]Row
- queries []string
- args [][]any
-}
-
-func (f *scriptedStore) Query(_ context.Context, q string, a ...any) ([]Row, error) {
- f.queries = append(f.queries, q)
- f.args = append(f.args, a)
- if len(f.sets) == 0 {
- return []Row{}, nil
- }
- rows := f.sets[0]
- f.sets = f.sets[1:]
- return rows, nil
-}
-func TestInflationSamplingAndCache(t *testing.T) {
- f := &scriptedStore{sets: [][]Row{{{"height": int64(2501)}}, {{"height": 0, "block_time": 1}, {"height": 2000, "block_time": 2}, {"height": 2501, "block_time": 3}}, {{"height": 2501, "block_time": 3}, {"height": 2500, "block_time": 2}}}}
- s := Server{Store: f, Cache: Cache{Dir: t.TempDir()}}
- var bodies []string
- for i := 0; i < 2; i++ {
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/charts/inflation", nil))
- if w.Code != 200 {
- t.Fatal(w.Code, w.Body.String())
- }
- bodies = append(bodies, w.Body.String())
- }
- if bodies[0] != bodies[1] {
- t.Fatal("cache changed bytes")
- }
- if len(f.queries) != 3 {
- t.Fatal(f.queries)
- }
- if len(f.args[1]) != 4 || f.args[1][3] != 2501 {
- t.Fatal(f.args)
- }
- var result struct {
- Data struct {
- Recent []Row
- Last int `json:"last_reward_block"`
- }
- }
- if e := json.Unmarshal([]byte(bodies[0]), &result); e != nil {
- t.Fatal(e)
- }
- if number(result.Data.Recent[0]["height"]) != 2500 || result.Data.Last != 4071017 {
- t.Fatal(bodies[0])
- }
-}
-func TestClaimsCursorPrecedence(t *testing.T) {
- for _, query := range []string{"after=4&before=9&sort=oldest", "before=-2&sort=popular&nsfw=True", "before=7&sort=oldest&nsfw=true"} {
- f := &scriptedStore{}
- s := Server{Store: f}
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/claims/browse?"+query, nil))
- if w.Body.String() != `{"success":true,"claims":[],"total":23000000}` {
- t.Fatal(w.Body.String())
- }
- q := f.queries[0]
- switch {
- case strings.Contains(query, "after="):
- if !strings.Contains(q, "Claims.id > ?") || !strings.Contains(q, "ORDER BY Claims.id ASC") {
- t.Fatal(q)
- }
- case strings.Contains(query, "before=-"):
- if strings.Contains(q, "Claims.id <") {
- t.Fatal(q)
- }
- default:
- if !strings.Contains(q, "Claims.id < ?") || !strings.Contains(q, "ORDER BY Claims.id DESC") {
- t.Fatal(q)
- }
- }
- if strings.HasSuffix(query, "nsfw=true") && strings.Contains(q, "is_nsfw !=") {
- t.Fatal(q)
- }
- }
-}
-func TestUTXOAtomicAndShape(t *testing.T) {
- f := &scriptedStore{sets: [][]Row{{{"id": int64(2), "address": "addr"}}, {{"transaction_hash": "tx", "vout": int64(1), "value": 1.23456789, "address_list": "[\"addr\"]", "script_pub_key_asm": "op /", "script_pub_key_hex": "01", "type": "pubkeyhash", "required_signatures": int64(1), "confirmations": int64(7)}}}}
- s := Server{Store: f}
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/address/addr,unknown/utxo", nil))
- want := `{"success":true,"utxo":[{"transaction_hash":"tx","output_index":1,"value":123456789,"addresses":["addr"],"script":"op \/","script_hex":"01","script_type":"pubkeyhash","required_signatures":1,"spent":false,"confirmations":7}]}`
- if w.Body.String() != want {
- t.Fatal(w.Body.String())
- }
- if !strings.Contains(f.queries[1], "JSON_CONTAINS(O.address_list, JSON_QUOTE(?))") || len(f.args[1]) != 2 {
- t.Fatal(f.queries, f.args)
- }
-}
-func TestSupplyDecimalAndCache(t *testing.T) {
- f := &scriptedStore{sets: [][]Row{{{"balance": 10.12345678}}, {{"balance": 1.00000001}}}}
- s := Server{Store: f, Cache: Cache{Dir: t.TempDir()}}
- for i := 0; i < 2; i++ {
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/supply", nil))
- if w.Body.String() != `{"success":true,"utxosupply":{"total":"10.12345678","circulating":"9.12345677"}}` {
- t.Fatal(w.Body.String())
- }
- }
- if len(f.queries) != 2 {
- t.Fatal(f.queries)
- }
- if len(f.args[1]) != 13 {
- t.Fatal(f.args)
- }
-}
-
-type roundTrip func(*http.Request) (*http.Response, error)
-
-func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
-func TestBlockedListRequestCachingAndPublisher(t *testing.T) {
- calls := 0
- client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
- calls++
- if r.URL.String() != blockedListURL || r.Method != "GET" {
- t.Fatal(r.Method, r.URL.String())
- }
- return &http.Response{StatusCode: 503, Body: http.NoBody, Header: http.Header{}}, nil
- })}
- now := time.Unix(1, 0)
- s := Server{Cache: Cache{Dir: t.TempDir(), Now: func() time.Time { return now }}, HTTPClient: client}
- s.blocked(context.Background())
- s.blocked(context.Background())
- if calls != 1 {
- t.Fatal("non-2xx response not cached", calls)
- }
- now = now.Add(10 * time.Minute)
- client.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
- calls++
- return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"data":[{"claim_id":"publisher"}]}`)), Header: http.Header{}}, nil
- })
- list := s.blocked(context.Background())
- rows := []Row{{"claim_id": "claim", "publisher_id": "publisher", "thumbnail_url": "https://image"}}
- markBlocked(rows, list)
- if !truth(rows[0]["isBlocked"]) || rows[0]["thumbnail_url"] != nil {
- t.Fatal(rows)
- }
-}
-
-func TestPrimitiveAPICacheEntriesAreMisses(t *testing.T) {
- for _, key := range []string{"inflation_chart", "utxo_supply"} {
- for _, body := range []string{`null`, `false`, `"wrong type"`} {
- c := Cache{Dir: t.TempDir()}
- if e := c.Put(key, []byte(body), time.Hour); e != nil {
- t.Fatal(e)
- }
- s := Server{Cache: c}
- if _, hit := s.cachedArray(key); hit {
- t.Fatalf("primitive cache body accepted: %s %s", key, body)
- }
- }
- }
- c := Cache{Dir: t.TempDir()}
- c.Put("inflation_chart", []byte(`[]`), time.Hour)
- s := Server{Cache: c}
- if _, hit := s.cachedArray("inflation_chart"); !hit {
- t.Fatal("empty array is a valid legacy cache hit")
- }
-}
-func TestNullBlockedCacheEntryIsMiss(t *testing.T) {
- calls := 0
- s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
- calls++
- return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"data":[]}`))}, nil
- })}}
- s.Cache.Put("list_blocked", []byte(`null`), time.Hour)
- s.blocked(context.Background())
- if calls != 1 {
- t.Fatal("null blocked-list cache must fetch")
- }
-}
diff --git a/internal/explorer/assets_test.go b/internal/explorer/assets_test.go
deleted file mode 100644
index c14f30a..0000000
--- a/internal/explorer/assets_test.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "explorer/webroot"
- "io/fs"
- "net/http/httptest"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestBundledAssetsEmbedded(t *testing.T) {
- reference := filepath.Join("..", "..", "webroot")
- count := 0
- e := filepath.WalkDir(reference, func(path string, d fs.DirEntry, e error) error {
- if e != nil {
- return e
- }
- if d.IsDir() {
- return nil
- }
- name, _ := filepath.Rel(reference, path)
- if name == "embed.go" {
- return nil
- }
- want, e := os.ReadFile(path)
- if e != nil {
- return e
- }
- embedded, e := webroot.Files.ReadFile(filepath.ToSlash(name))
- if e != nil {
- return e
- }
- if !bytes.Equal(want, embedded) {
- t.Errorf("embedded asset bytes changed: %s", name)
- }
- count++
- return nil
- })
- if e != nil {
- t.Fatal(e)
- }
- if count < 100 {
- t.Fatal("incomplete asset inventory", count)
- }
-}
-
-func TestEmbeddedAssetHTTP(t *testing.T) {
- s := Server{}
- for _, name := range []string{"css/main.css", "js/jquery.js", "img/lbry.png", "amcharts/serial.js", "amcharts/plugins/export/export.min.js"} {
- t.Run(name, func(t *testing.T) {
- want, e := webroot.Files.ReadFile(name)
- if e != nil {
- t.Fatal(e)
- }
- for _, method := range []string{"GET", "HEAD"} {
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest(method, "/"+name, nil))
- if w.Code != 200 || w.Header().Get("Content-Type") == "" {
- t.Fatalf("%s: status %d, headers %v", method, w.Code, w.Header())
- }
- if method == "GET" && !bytes.Equal(w.Body.Bytes(), want) {
- t.Fatal("asset body differs")
- }
- if method == "HEAD" && w.Body.Len() != 0 {
- t.Fatal("HEAD returned a body")
- }
- }
- r := httptest.NewRequest("GET", "/"+name, nil)
- r.Header.Set("Range", "bytes=0-9")
- w := httptest.NewRecorder()
- s.ServeHTTP(w, r)
- if w.Code != 206 || !bytes.Equal(w.Body.Bytes(), want[:10]) {
- t.Fatal("range response differs", w.Code)
- }
- })
- }
-}
diff --git a/internal/explorer/blocked.go b/internal/explorer/blocked.go
deleted file mode 100644
index 8b3c2f6..0000000
--- a/internal/explorer/blocked.go
+++ /dev/null
@@ -1,251 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "context"
- "encoding/base64"
- "encoding/json"
- "errors"
- "io"
- "net"
- "net/http"
- "strconv"
- "strings"
- "time"
- "unicode/utf8"
-)
-
-const blockedListURL = "https://api.odysee.com/file/list_blocked?with_claim_id=true"
-
-func blockedHTTPClient() *http.Client {
- return &http.Client{CheckRedirect: func(req *http.Request, via []*http.Request) error {
- req.Header.Del("Referer")
- if len(via) > 20 {
- return errors.New("maximum 20 redirects followed")
- }
- return nil
- }, Timeout: 15 * time.Second, Transport: &http.Transport{ForceAttemptHTTP2: true, DisableCompression: true, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 5 * time.Second}}
-}
-func (s *Server) blocked(ctx context.Context) map[string]bool {
- started := time.Now()
- cacheHit := false
- fetchFailed := false
- status := 0
- if s.Logger != nil {
- defer func() {
- s.Logger.InfoContext(ctx, "blocked_list", "cache_hit", cacheHit, "fetch_failed", fetchFailed, "http_status", status, "duration_ms", float64(time.Since(started))/float64(time.Millisecond))
- }()
- }
- var body []byte
- cached, hit := s.Cache.Get("list_blocked")
- if hit {
- var ok bool
- body, ok = decodeBlockedCache(cached)
- if ok {
- cacheHit = true
- } else {
- hit = false
- }
- }
-
- if !hit {
- client := s.HTTPClient
- if client == nil {
- client = blockedHTTPClient()
- defer client.CloseIdleConnections()
- }
- req, e := http.NewRequestWithContext(ctx, "GET", blockedListURL, nil)
- if e != nil {
- return nil
- }
- req.Header.Set("User-Agent", "")
- req.Header.Set("Accept", "*/*")
- req, finishConnectBudget := connectionBudget(req, 5*time.Second)
- defer finishConnectBudget()
- resp, e := client.Do(req)
- if e != nil {
- fetchFailed = true
- return nil
- }
- status = resp.StatusCode
- defer resp.Body.Close()
- body, e = io.ReadAll(resp.Body)
- if e != nil {
- fetchFailed = true
- return nil
- }
- var b []byte
- if utf8.Valid(body) {
- b, _ = json.Marshal(string(body))
- } else {
- b, _ = json.Marshal(struct {
- Raw []byte `json:"raw_base64"`
- }{body})
- }
- s.Cache.Put("list_blocked", b, 10*time.Minute)
- }
- return parseBlocked(body)
-}
-
-const blockedTrue = "\xfftrue"
-const blockedFalse = "\xfffalse"
-const blockedNull = "\xffnull"
-
-func parseBlocked(body []byte) map[string]bool {
- if !validProviderJSON(body) {
- return nil
- }
- var root map[string]json.RawMessage
- if json.Unmarshal(body, &root) != nil {
- return nil
- }
- var entries []json.RawMessage
- if json.Unmarshal(root["data"], &entries) != nil {
- return nil
- }
- out := map[string]bool{}
- for _, item := range entries {
- var fields map[string]json.RawMessage
- if json.Unmarshal(item, &fields) != nil {
- out[blockedNull] = true
- continue
- }
- raw := fields["claim_id"]
- if len(raw) == 0 || string(raw) == "null" {
- out[blockedNull] = true
- continue
- }
- if string(raw) == "true" {
- out[blockedTrue] = true
- continue
- }
- if string(raw) == "false" {
- out[blockedFalse] = true
- continue
- }
- var id string
- if json.Unmarshal(raw, &id) == nil {
- out[id] = true
- continue
- }
- var n json.Number
- if json.Unmarshal(raw, &n) == nil {
- out[string(n)] = true
- }
- }
- return out
-}
-func isBlockedID(id string, list map[string]bool) bool {
- if list[id] || list[blockedTrue] && truth(id) || list[blockedFalse] && !truth(id) || list[blockedNull] && id == "" {
- return true
- }
- a := strings.Trim(id, " \t\n\r\f\v")
- if !numericPattern.MatchString(a) {
- return false
- }
- ai, ae := strconv.ParseInt(a, 10, 64)
- af, _ := strconv.ParseFloat(a, 64)
- for key := range list {
- b := strings.Trim(key, " \t\n\r\f\v")
- if !numericPattern.MatchString(b) {
- continue
- }
- bi, be := strconv.ParseInt(b, 10, 64)
- if ae == nil && be == nil {
- if ai == bi {
- return true
- }
- } else {
- bf, _ := strconv.ParseFloat(b, 64)
- if af == bf {
- return true
- }
- }
- }
- return false
-}
-
-func markBlocked(rows []Row, list map[string]bool) {
- for _, row := range rows {
- blocked := isBlockedID(text(row["claim_id"]), list)
- if publisher := text(row["publisher_id"]); truth(publisher) {
- blocked = blocked || isBlockedID(publisher, list)
- }
- row["isBlocked"] = blocked
- if blocked {
- row["thumbnail_url"] = nil
- }
- }
-}
-
-func decodeBlockedCache(cached []byte) ([]byte, bool) {
- trimmed := bytes.TrimSpace(cached)
- if len(trimmed) > 0 && trimmed[0] == '"' {
- var raw string
- if json.Unmarshal(cached, &raw) == nil {
- return []byte(raw), true
- }
- }
- var wrapper map[string]json.RawMessage
- if json.Unmarshal(cached, &wrapper) != nil {
- return nil, false
- }
- var raw string
- field := wrapper["raw_base64"]
- if len(field) == 0 || field[0] != '"' || json.Unmarshal(field, &raw) != nil {
- return nil, false
- }
- decoded, e := base64.StdEncoding.DecodeString(raw)
- return decoded, e == nil
-}
-
-// PHP json_decode rejects malformed UTF-8 and unpaired UTF-16 escapes rather
-// than replacing them. Validate these before the Go decoder sees the payload.
-func validProviderJSON(body []byte) bool {
- if !utf8.Valid(body) || !json.Valid(body) {
- return false
- }
- quoted := false
- depth := 0
- for i := 0; i < len(body); i++ {
- c := body[i]
- if c == '"' {
- quoted = !quoted
- continue
- }
- if !quoted {
- if c == '{' || c == '[' {
- depth++
- if depth >= 512 {
- return false
- }
- } else if c == '}' || c == ']' {
- depth--
- }
- continue
- }
- if c != '\\' {
- continue
- }
- i++
- if body[i] != 'u' {
- continue
- }
- code, _ := strconv.ParseUint(string(body[i+1:i+5]), 16, 16)
- i += 4
- if code >= 0xdc00 && code <= 0xdfff {
- return false
- }
- if code >= 0xd800 && code <= 0xdbff {
- if i+6 >= len(body) || body[i+1] != '\\' || body[i+2] != 'u' {
- return false
- }
- low, e := strconv.ParseUint(string(body[i+3:i+7]), 16, 16)
- if e != nil || low < 0xdc00 || low > 0xdfff {
- return false
- }
- i += 6
- }
- }
- return true
-}
diff --git a/internal/explorer/blocked_test.go b/internal/explorer/blocked_test.go
deleted file mode 100644
index f7d8158..0000000
--- a/internal/explorer/blocked_test.go
+++ /dev/null
@@ -1,172 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "context"
- "errors"
- "io"
- "net/http"
- "net/http/httptest"
- "net/http/httptrace"
- "net/url"
- "strings"
- "sync/atomic"
- "testing"
- "time"
-)
-
-func TestBlockedTransportFailureIsUncached(t *testing.T) {
- calls := 0
- s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) { calls++; return nil, errors.New("unavailable") })}}
- for i := 0; i < 2; i++ {
- if len(s.blocked(context.Background())) != 0 {
- t.Fatal("failure should produce empty list")
- }
- }
- if calls != 2 {
- t.Fatal("transport failure was cached")
- }
- if _, ok := s.Cache.Get("list_blocked"); ok {
- t.Fatal("failed request populated cache")
- }
-}
-func TestBlockedMalformedBodyIsCached(t *testing.T) {
- calls := 0
- s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
- calls++
- return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader("not JSON")), Header: http.Header{}}, nil
- })}}
- s.blocked(context.Background())
- s.blocked(context.Background())
- if calls != 1 {
- t.Fatal("successful malformed body must be cached")
- }
-}
-func TestBlockedContextDeadline(t *testing.T) {
- s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) { <-r.Context().Done(); return nil, r.Context().Err() })}}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
- defer cancel()
- if len(s.blocked(ctx)) != 0 {
- t.Fatal("deadline fallback")
- }
- if _, ok := s.Cache.Get("list_blocked"); ok {
- t.Fatal("deadline was cached")
- }
- client := blockedHTTPClient()
- if client.Timeout != 15*time.Second {
- t.Fatal(client.Timeout)
- }
- transport := client.Transport.(*http.Transport)
- if !transport.DisableCompression || transport.TLSHandshakeTimeout != 5*time.Second {
- t.Fatal("transport compatibility")
- }
-}
-func TestBlockedRedirectAndHeaders(t *testing.T) {
- var paths []string
- fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method != "GET" || r.UserAgent() != "" || r.Header.Get("Accept-Encoding") != "" || r.Header.Get("Accept") != "*/*" || r.Header.Get("Referer") != "" {
- t.Error("unexpected request headers/method", r.Method, r.Header)
- }
- paths = append(paths, r.URL.RequestURI())
- if r.URL.Path == "/file/list_blocked" {
- w.Header().Set("Location", "/final")
- w.WriteHeader(302)
- return
- }
- io.WriteString(w, `{"data":[{"claim_id":"blocked"}]}`)
- }))
- defer fixture.Close()
- target, _ := url.Parse(fixture.URL)
- client := blockedHTTPClient()
- transport := client.Transport
- client.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
- copy := r.Clone(r.Context())
- u := *r.URL
- u.Host = target.Host
- u.Scheme = target.Scheme
- copy.URL = &u
- return transport.RoundTrip(copy)
- })
- s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: client}
- if !s.blocked(context.Background())["blocked"] {
- t.Fatal("redirected body missing")
- }
- if len(paths) != 2 || paths[0] != "/file/list_blocked?with_claim_id=true" || paths[1] != "/final" {
- t.Fatal(paths)
- }
-}
-func TestBlockedRedirectLimit(t *testing.T) {
- var calls atomic.Int64
- fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- calls.Add(1)
- w.Header().Set("Location", "/loop")
- w.WriteHeader(http.StatusFound)
- }))
- defer fixture.Close()
- resp, err := blockedHTTPClient().Get(fixture.URL + "/loop")
- if resp != nil {
- resp.Body.Close()
- }
- if err == nil || calls.Load() != 21 {
- t.Fatalf("expected initial request plus 20 redirects; got %d requests, error %v", calls.Load(), err)
- }
-}
-
-func TestBlockedInvalidUTF8IsCachedWithoutRepair(t *testing.T) {
- raw := append([]byte(`{"data":[{"claim_id":"blocked","junk":"`), 255)
- raw = append(raw, []byte(`"}]}`)...)
- calls := 0
- s := Server{Cache: Cache{Dir: t.TempDir()}, HTTPClient: &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
- calls++
- return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(bytes.NewReader(raw))}, nil
- })}}
- for i := 0; i < 2; i++ {
- if len(s.blocked(context.Background())) != 0 {
- t.Fatal("malformed provider JSON was repaired")
- }
- }
- if calls != 1 {
- t.Fatal("successful binary response must remain cached", calls)
- }
- cached, ok := s.Cache.Get("list_blocked")
- if !ok {
- t.Fatal("missing raw response cache")
- }
- decoded, ok := decodeBlockedCache(cached)
- if !ok || !bytes.Equal(decoded, raw) {
- t.Fatal("cached bytes changed")
- }
-}
-func TestProviderJSONDepthAndSurrogates(t *testing.T) {
- for _, c := range []struct {
- body string
- valid bool
- }{{`{"data":[],"junk":"\ud800"}`, false}, {`{"data":[],"junk":"\ud800\udc00"}`, true}, {`{"data":[],"junk":"\\ud800"}`, true}, {strings.Repeat("[", 511) + "0" + strings.Repeat("]", 511), true}, {strings.Repeat("[", 512) + "0" + strings.Repeat("]", 512), false}} {
- if got := validProviderJSON([]byte(c.body)); got != c.valid {
- t.Fatal("JSON validation mismatch", got, c.valid)
- }
- }
-}
-
-func TestConnectionBudgetSeparatesHandshakeAndTransfer(t *testing.T) {
- req := httptest.NewRequest("GET", "https://example.invalid/", nil)
- bounded, finish := connectionBudget(req, 10*time.Millisecond)
- trace := httptrace.ContextClientTrace(bounded.Context())
- trace.GetConn("example.invalid:443")
- select {
- case <-bounded.Context().Done():
- case <-time.After(time.Second):
- t.Fatal("connection budget did not cancel")
- }
- finish()
- bounded, finish = connectionBudget(req, 5*time.Millisecond)
- defer finish()
- trace = httptrace.ContextClientTrace(bounded.Context())
- trace.GetConn("example.invalid:443")
- trace.GotConn(httptrace.GotConnInfo{})
- select {
- case <-bounded.Context().Done():
- t.Fatal("successful connection timer cancelled response transfer")
- case <-time.After(15 * time.Millisecond):
- }
-}
diff --git a/internal/explorer/blocks.go b/internal/explorer/blocks.go
deleted file mode 100644
index 046afbf..0000000
--- a/internal/explorer/blocks.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package explorer
-
-import (
- "net/http"
- "regexp"
- "strconv"
- "strings"
-)
-
-var phpIntPrefix = regexp.MustCompile(`^[\t\n\r\f\v ]*([+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)`)
-
-func phpInt(s string) int {
- m := phpIntPrefix.FindStringSubmatch(s)
- if len(m) < 2 {
- return 0
- }
- if !strings.ContainsAny(m[1], ".eE") {
- v, _ := strconv.ParseInt(m[1], 10, 64)
- return int(v)
- }
- v, _ := strconv.ParseFloat(m[1], 64)
- if v >= 9223372036854775807 {
- return int(^uint(0) >> 1)
- }
- if v <= -9223372036854775808 {
- return -int(^uint(0)>>1) - 1
- }
- return int(v)
-}
-func (s *Server) blocksPage(w http.ResponseWriter, r *http.Request) {
- q := func(sql string, args ...any) ([]Row, bool) {
- rows, e := s.Store.Query(r.Context(), sql, args...)
- if e != nil {
- internalError(w)
- return nil, false
- }
- return rows, true
- }
- rest := strings.TrimPrefix(r.URL.Path, "/blocks")
- rest = strings.TrimPrefix(rest, "/")
- if rest != "" {
- height := phpInt(firstArgument(r, "/blocks"))
- if height < 0 {
- redirect(w, r, "/", 302)
- return
- }
- rows, ok := q("SELECT * FROM block WHERE height = ? LIMIT 1", height)
- if !ok {
- return
- }
- if len(rows) == 0 {
- redirect(w, r, "/", 302)
- return
- }
- block := rows[0]
- txs, ok := q("SELECT id,value,input_count,output_count,hash,version FROM transaction WHERE block_hash_id = ?", block["hash"])
- if !ok {
- return
- }
- last, ok := q("SELECT height FROM block ORDER BY height DESC LIMIT 1")
- if !ok {
- return
- }
- confirmations := int64(0)
- if len(last) > 0 {
- confirmations = int64(number(last[0]["height"]) - number(block["height"]) + 1)
- }
- s.render(w, r, "block", pageData{Title: "Block Height " + text(block["height"]), Block: block, Txs: txs, Confirmations: confirmations})
- return
- }
- count, ok := q("SELECT height AS Total FROM block ORDER BY id DESC LIMIT 1")
- if !ok {
- return
- }
- total := 0
- if len(count) > 0 {
- total = int(number(count[0]["Total"]))
- }
- if total == 0 {
- internalError(w)
- return
- }
- page, pages, pagination := paginate(total, 50, queryInt(r, "page"))
- last, ok := q("SELECT height FROM block ORDER BY height DESC LIMIT 1")
- if !ok {
- return
- }
- highest := Row{"height": 0}
- if len(last) > 0 {
- highest = last[0]
- }
- blocks := []Row{}
- if pages > 0 {
- blocks, ok = q("SELECT height,difficulty,block_size,nonce,block_time,tx_count FROM block ORDER BY height DESC LIMIT 50 OFFSET ?", (page-1)*50)
- if !ok {
- return
- }
- }
- begin := (page-1)*50 + 1
- s.render(w, r, "blocks", pageData{Title: "Blocks", Blocks: blocks, Highest: highest, NumRecords: total, NumPages: pages, CurrentPage: page, PageLimit: 50, Pagination: pagination, Begin: begin, End: min(total, begin+49)})
-}
diff --git a/internal/explorer/boundary_test.go b/internal/explorer/boundary_test.go
deleted file mode 100644
index 641f97a..0000000
--- a/internal/explorer/boundary_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package explorer
-
-import (
- "encoding/base64"
- "encoding/json"
- "net/http/httptest"
- "os"
- "testing"
-)
-
-func TestQueryAndBlockingBoundaries(t *testing.T) {
- b, e := os.ReadFile("testdata/boundaries.json")
- if e != nil {
- t.Fatal(e)
- }
- var f struct {
- Queries []struct {
- Raw, Q string
- Page int64
- }
- Blocked []struct {
- Claim string
- Publisher *string
- Body string
- BodyBase64 string `json:"body_base64"`
- Expected bool
- }
- }
- if e = json.Unmarshal(b, &f); e != nil {
- t.Fatal(e)
- }
- for _, c := range f.Queries {
- r := httptest.NewRequest("GET", "/?"+c.Raw, nil)
- if q := queryString(r, "q"); q != c.Q {
- t.Errorf("%s: q %q != expected %q", c.Raw, q, c.Q)
- }
- if page := queryInt(r, "page"); int64(page) != c.Page {
- t.Errorf("%s: page %d != expected %d", c.Raw, page, c.Page)
- }
- }
- for _, c := range f.Blocked {
- row := Row{"claim_id": c.Claim}
- if c.Publisher != nil {
- row["publisher_id"] = *c.Publisher
- }
- body := []byte(c.Body)
- if c.BodyBase64 != "" {
- body, e = base64.StdEncoding.DecodeString(c.BodyBase64)
- if e != nil {
- t.Fatal(e)
- }
- }
- markBlocked([]Row{row}, parseBlocked(body))
- if got := truth(row["isBlocked"]); got != c.Expected {
- t.Errorf("%s claim %q publisher %v: %v != expected %v", c.Body, c.Claim, c.Publisher, got, c.Expected)
- }
- }
-}
diff --git a/internal/explorer/cache.go b/internal/explorer/cache.go
deleted file mode 100644
index 4a7630c..0000000
--- a/internal/explorer/cache.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "encoding/json"
- "os"
- "path/filepath"
- "time"
-)
-
-type Cache struct {
- Dir string
- Now func() time.Time
-}
-type cacheEntry struct {
- Expires time.Time `json:"expires"`
- Body json.RawMessage `json:"body"`
-}
-
-func (c Cache) now() time.Time {
- if c.Now != nil {
- return c.Now()
- }
- return time.Now()
-}
-func (c Cache) Get(key string) ([]byte, bool) {
- b, e := os.ReadFile(filepath.Join(c.Dir, key+".json"))
- if e != nil {
- return nil, false
- }
- var v cacheEntry
- if json.Unmarshal(b, &v) != nil || !c.now().Before(v.Expires) {
- return nil, false
- }
- return v.Body, true
-}
-func (c Cache) Put(key string, b []byte, ttl time.Duration) error {
- if e := os.MkdirAll(c.Dir, 0700); e != nil {
- return e
- }
- v, e := json.Marshal(cacheEntry{c.now().Add(ttl), b})
- if e != nil {
- return e
- }
- f, e := os.CreateTemp(c.Dir, ".cache-")
- if e != nil {
- return e
- }
- name := f.Name()
- defer os.Remove(name)
- if _, e = f.Write(v); e != nil {
- f.Close()
- return e
- }
- if e = f.Close(); e != nil {
- return e
- }
- return os.Rename(name, filepath.Join(c.Dir, key+".json"))
-}
-
-// Cake accepts only PHP arrays for these API cache entries. JSON objects and
-// arrays are their Go-cache representations; primitives/null remain misses.
-func (s *Server) cachedArray(key string) ([]byte, bool) {
- b, ok := s.Cache.Get(key)
- if !ok {
- return nil, false
- }
- trimmed := bytes.TrimSpace(b)
- if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') {
- return nil, false
- }
- return b, true
-}
diff --git a/internal/explorer/claims.go b/internal/explorer/claims.go
deleted file mode 100644
index 4bec989..0000000
--- a/internal/explorer/claims.go
+++ /dev/null
@@ -1,167 +0,0 @@
-package explorer
-
-import (
- "net/http"
- "regexp"
- "strconv"
- "strings"
-)
-
-type claimCard struct {
- Claim Row
- LastItem, LastRow bool
-}
-
-func cards(rows []Row) []claimCard {
- out := make([]claimCard, 0, len(rows))
- lastRow := (len(rows) + 2) / 3
- for i, row := range rows {
- out = append(out, claimCard{row, (i+1)%3 == 0, i/3+1 == lastRow})
- }
- return out
-}
-func claimCost(r Row) string {
- if number(r["price"]) > 0 {
- return currency(r["price"]) + " LBC"
- }
- if r["fee"] != nil && strings.ToLower(text(r["fee_currency"])) == "lbc" {
- return currency(r["fee"]) + " LBC"
- }
- return ""
-}
-func (s *Server) claimsPage(w http.ResponseWriter, r *http.Request) {
- rest := strings.TrimPrefix(strings.TrimPrefix(r.URL.Path, "/claims"), "/")
- if rest != "" && rest != "0" {
- s.claimPage(w, r, firstArgument(r, "/claims"))
- return
- }
- rows, e := s.Store.Query(r.Context(), "SELECT MAX(id) AS MaxId FROM claim")
- if e != nil {
- internalError(w)
- return
- }
- maxID := 0
- if len(rows) > 0 {
- maxID = int(number(rows[0]["MaxId"]))
- }
- page, pages, pagination := paginate(20000000, 96, queryInt(r, "page"))
- start := maxID - page*96
- end := min(maxID, start+96)
- list := s.blocked(r.Context())
- claims, e := s.Store.Query(r.Context(), "SELECT Claims.*,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id WHERE Claims.id > ? AND Claims.id <= ? ORDER BY Claims.id DESC", start, end)
- if e != nil {
- internalError(w)
- return
- }
- markBlocked(claims, list)
- s.render(w, r, "claims", pageData{Title: "Claims Explorer", Claims: claims, Cards: cards(claims), NumRecords: 20000000, PageLimit: 96, CurrentPage: page, NumPages: pages, Pagination: pagination})
-}
-
-var numericPattern = regexp.MustCompile(`^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`)
-
-func (s *Server) findPage(w http.ResponseWriter, r *http.Request) {
- criteria := phpTrim(queryString(r, "q"))
- var claims []Row
- query := func(q string, args ...any) ([]Row, bool) {
- rows, e := s.Store.Query(r.Context(), q, args...)
- if e != nil {
- internalError(w)
- return nil, false
- }
- return rows, true
- }
- redirect := func(path string) { redirect(w, r, path, 302) }
- switch {
- case numericPattern.MatchString(criteria):
- n, _ := strconv.ParseFloat(criteria, 64)
- height := int(n)
- rows, ok := query("SELECT id FROM block WHERE height = ? LIMIT 1", height)
- if !ok {
- return
- }
- if len(rows) > 0 {
- redirect("/blocks/" + strconv.Itoa(height))
- return
- }
- case len(criteria) == 34:
- rows, ok := query("SELECT id,address FROM address WHERE address = ? LIMIT 1", criteria)
- if !ok {
- return
- }
- if len(rows) > 0 {
- redirect("/address/" + text(rows[0]["address"]))
- return
- }
- case len(criteria) == 40:
- rows, ok := query("SELECT claim_id FROM claim WHERE claim_id = ? LIMIT 1", criteria)
- if !ok {
- return
- }
- if len(rows) > 0 {
- redirect("/claims/" + text(rows[0]["claim_id"]))
- return
- }
- case len(criteria) == 64:
- rows, ok := query("SELECT height FROM block WHERE hash = ? LIMIT 1", criteria)
- if !ok {
- return
- }
- if len(rows) > 0 {
- redirect("/blocks/" + text(rows[0]["height"]))
- return
- }
- rows, ok = query("SELECT hash FROM transaction WHERE hash = ? LIMIT 1", criteria)
- if !ok {
- return
- }
- if len(rows) > 0 {
- redirect("/tx/" + text(rows[0]["hash"]))
- return
- }
- default:
- var ok bool
- claims, ok = query("SELECT Claims.* FROM claim Claims WHERE name = ? GROUP BY claim_id ORDER BY FIELD(bid_state, 'Controlling') DESC LIMIT 10", criteria)
- if !ok {
- return
- }
- if len(claims) == 1 {
- redirect("/claims/" + text(claims[0]["claim_id"]))
- return
- }
- }
- s.render(w, r, "find", pageData{Title: "Search Results", Claims: claims, Cards: cards(claims)})
-}
-
-func (s *Server) claimPage(w http.ResponseWriter, r *http.Request, id string) {
- query := func(q string, args ...any) ([]Row, bool) {
- rows, e := s.Store.Query(r.Context(), q, args...)
- if e != nil {
- internalError(w)
- return nil, false
- }
- return rows, true
- }
- rows, ok := query("SELECT Claims.*,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id WHERE Claims.claim_id = ? ORDER BY Claims.created_at DESC LIMIT 1", id)
- if !ok {
- return
- }
- if len(rows) == 0 {
- redirect(w, r, "/", 302)
- return
- }
- claim := rows[0]
- var more []Row
- if claim["publisher"] != nil && text(claim["publisher_id"]) != "f2cf43b86b9d70175dc22dbb9ff7806241d90780" {
- more, ok = query("SELECT Claims.claim_id,Claims.bid_state,Claims.fee,Claims.fee_currency,Claims.is_nsfw,Claims.claim_type,Claims.name,Claims.title,Claims.description,Claims.content_type,Claims.language,Claims.author,Claims.license,Claims.created_at,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id WHERE Claims.claim_type = 1 AND Claims.id <> ? AND Claims.publisher_id = ? ORDER BY Claims.fee DESC,RAND() DESC LIMIT 9", claim["id"], claim["publisher_id"])
- if !ok {
- return
- }
- }
- blocked := s.blocked(r.Context())
- markBlocked(rows, blocked)
- isBlocked := truth(claim["isBlocked"])
- if isBlocked {
- more = nil
- }
- s.render(w, r, "claim", pageData{Title: "Claim • " + text(claim["name"]), Claim: claim, MoreClaims: more, Cards: cards(more), ClaimIsBlocked: isBlocked})
-}
diff --git a/internal/explorer/connect_budget.go b/internal/explorer/connect_budget.go
deleted file mode 100644
index a51535c..0000000
--- a/internal/explorer/connect_budget.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package explorer
-
-import (
- "context"
- "net/http"
- "net/http/httptrace"
- "sync"
- "time"
-)
-
-// CURLOPT_CONNECTTIMEOUT includes DNS, TCP, proxy CONNECT and TLS. A dial
-// timeout alone leaves a second TLS timeout window, so bound GetConn..GotConn.
-// The separate client timeout continues to cover response transfer.
-func connectionBudget(req *http.Request, budget time.Duration) (*http.Request, func()) {
- ctx, cancel := context.WithCancel(req.Context())
- var mu sync.Mutex
- var timer *time.Timer
- closed := false
- stopTimer := func() {
- if timer != nil {
- timer.Stop()
- timer = nil
- }
- }
- trace := &httptrace.ClientTrace{GetConn: func(string) {
- mu.Lock()
- defer mu.Unlock()
- if closed {
- return
- }
- stopTimer()
- timer = time.AfterFunc(budget, cancel)
- }, GotConn: func(httptrace.GotConnInfo) { mu.Lock(); defer mu.Unlock(); stopTimer() }}
- finish := func() { mu.Lock(); closed = true; stopTimer(); mu.Unlock(); cancel() }
- return req.WithContext(httptrace.WithClientTrace(ctx, trace)), finish
-}
diff --git a/internal/explorer/db.go b/internal/explorer/db.go
deleted file mode 100644
index 048e8c2..0000000
--- a/internal/explorer/db.go
+++ /dev/null
@@ -1,124 +0,0 @@
-package explorer
-
-import (
- "context"
- "database/sql"
- "encoding/json"
- "errors"
- "strconv"
- "strings"
- "time"
-
- "github.com/go-sql-driver/mysql"
-)
-
-// Store deliberately exposes only SELECT operations. Every query runs in a
-// server-enforced read-only transaction, including queries on pooled connections.
-type Store interface {
- Query(context.Context, string, ...any) ([]Row, error)
-}
-type Row map[string]any
-type MySQL struct{ DB *sql.DB }
-
-func Open(dsn string) (*MySQL, error) {
- c, err := mysql.ParseDSN(dsn)
- if err != nil {
- return nil, err
- }
- c.ParseTime = false
- c.MultiStatements = false
- c.Timeout = 5 * time.Second
- if c.Params == nil {
- c.Params = map[string]string{}
- }
- c.Params["time_zone"] = "'+00:00'"
- db, err := sql.Open("mysql", c.FormatDSN())
- if err != nil {
- return nil, err
- }
- db.SetMaxOpenConns(4)
- db.SetMaxIdleConns(2)
- db.SetConnMaxLifetime(5 * time.Minute)
- return &MySQL{db}, nil
-}
-func (s *MySQL) Query(ctx context.Context, q string, args ...any) ([]Row, error) {
- if !strings.HasPrefix(strings.ToUpper(phpTrim(q)), "SELECT ") {
- return nil, errors.New("only SELECT is permitted")
- }
- // Preserve the source query duration, including all=true address history.
- // Caller deadlines and disconnect cancellation still propagate to MySQL.
- tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
- if err != nil {
- return nil, err
- }
- defer tx.Rollback()
- rows, err := tx.QueryContext(ctx, q, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- cols, err := rows.ColumnTypes()
- if err != nil {
- return nil, err
- }
- out := make([]Row, 0)
- for rows.Next() {
- values := make([]any, len(cols))
- ptr := make([]any, len(cols))
- for i := range values {
- ptr[i] = &values[i]
- }
- if err = rows.Scan(ptr...); err != nil {
- return nil, err
- }
- r := Row{}
- columns := make([]string, len(cols))
- for i, c := range cols {
- columns[i] = c.Name()
- }
- r["__columns"] = columns
- for i, c := range cols {
- v := values[i]
- if b, ok := v.([]byte); ok {
- v = string(b)
- }
- if str, ok := v.(string); ok {
- switch c.DatabaseTypeName() {
- case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "BIGINT":
- v, err = strconv.ParseInt(str, 10, 64)
- case "FLOAT", "DOUBLE":
- v, err = strconv.ParseFloat(str, 64)
- }
- if err != nil {
- return nil, err
- }
- }
- r[c.Name()] = v
- }
- out = append(out, r)
- }
- return out, rows.Err()
-}
-func number(v any) float64 {
- switch n := v.(type) {
- case json.Number:
- f, _ := n.Float64()
- return f
- case uint64:
- return float64(n)
- case int32:
- return float64(n)
- case uint32:
- return float64(n)
- case float64:
- return n
- case int64:
- return float64(n)
- case int:
- return float64(n)
- case string:
- f, _ := strconv.ParseFloat(n, 64)
- return f
- }
- return 0
-}
diff --git a/internal/explorer/description.go b/internal/explorer/description.go
deleted file mode 100644
index d19e4f3..0000000
--- a/internal/explorer/description.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package explorer
-
-import (
- "html"
- "html/template"
- "regexp"
- "strings"
-)
-
-var descriptionURL = regexp.MustCompile(`(?i)((https?|ftp|lbry)://([A-Za-z0-9\-/]+|\S*?\.\S*?))([\s)\[\]{},;"':<]|\.\s|$)`)
-var descriptionEmail = regexp.MustCompile(`[a-zA-Z0-9.!#$%&'*+/=?^_` + "`" + `{|}~-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$`)
-
-func description(v any) template.HTML {
- s := text(v)
- if phpTrim(s) == "" {
- return template.HTML("No description available. ")
- }
- 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(`` + escaped + ` `)
- 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(`` + mail + ` `)
- } else {
- b.WriteString(html.EscapeString(tail))
- }
- return template.HTML(strings.ReplaceAll(b.String(), "\n", " "))
-}
diff --git a/internal/explorer/entity.go b/internal/explorer/entity.go
deleted file mode 100644
index 8c18461..0000000
--- a/internal/explorer/entity.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package explorer
-
-// Cake's schema-driven entity conversions apply to browse results, unlike
-// raw PDO rows used by UTXO and chart queries.
-func claimEntities(rows []Row) []Row {
- if rows == nil {
- return []Row{}
- }
- for _, r := range rows {
- for _, field := range []string{"is_nsfw", "is_filtered", "is_cert_valid", "is_cert_processed", "has_claim_list"} {
- if r[field] != nil {
- r[field] = truth(r[field])
- }
- }
- for _, field := range []string{"created_at", "modified_at"} {
- if r[field] != nil {
- r[field] = timestamp(r[field]).Format("2006-01-02T15:04:05-07:00")
- }
- }
- for _, field := range []string{"value_as_json", "claim_id_list"} {
- if str, ok := r[field].(string); ok {
- value, e := decodeOrderedJSON(str)
- if e == nil {
- r[field] = cakeJSONArray(value)
- } else {
- r[field] = nil
- }
- }
- }
- }
- return rows
-}
diff --git a/internal/explorer/errors.go b/internal/explorer/errors.go
deleted file mode 100644
index 0395edd..0000000
--- a/internal/explorer/errors.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package explorer
-
-import (
- "fmt"
- "html/template"
- "net/http"
- "net/url"
- "strings"
-)
-
-func internalError(w http.ResponseWriter) {
- body, _ := templateFiles.ReadFile("templates/error500.html")
- w.Header().Set("Content-Type", "text/html; charset=UTF-8")
- w.WriteHeader(500)
- w.Write(body)
-}
-
-func clientError(w http.ResponseWriter, r *http.Request, status int, message string) {
- body, _ := templateFiles.ReadFile("templates/error400.html")
- t := template.Must(template.New("error").Parse(string(body)))
- w.Header().Set("Content-Type", "text/html; charset=UTF-8")
- w.WriteHeader(status)
- target := r.RequestURI
- if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") {
- if u, e := url.Parse(target); e == nil {
- target = u.RequestURI()
- }
- }
- t.Execute(w, struct{ Message, URL string }{message, target})
-}
-func badMethodError(w http.ResponseWriter, r *http.Request) {
- clientError(w, r, 400, fmt.Sprintf("Invalid HTTP method received. `%s` is invalid.", strings.ToUpper(r.Method)))
-}
diff --git a/internal/explorer/formatting_test.go b/internal/explorer/formatting_test.go
deleted file mode 100644
index 664e608..0000000
--- a/internal/explorer/formatting_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package explorer
-
-import (
- "encoding/json"
- "os"
- "testing"
- "time"
-)
-
-func TestFormatting(t *testing.T) {
- b, e := os.ReadFile("testdata/formatting.json")
- if e != nil {
- t.Fatal(e)
- }
- var fixtures struct {
- Now int64
- Dates []struct {
- Timestamp int64
- Ago, Human string
- }
- Amounts []struct {
- Value any
- Amount, Plain, Currency string
- }
- }
- if e = json.Unmarshal(b, &fixtures); e != nil {
- t.Fatal(e)
- }
- now := time.Unix(fixtures.Now, 0).UTC()
- for _, f := range fixtures.Dates {
- tm := time.Unix(f.Timestamp, 0).UTC()
- if got := cakeAgo(tm, now); got != f.Ago {
- t.Errorf("ago %d: %q != expected %q", f.Timestamp, got, f.Ago)
- }
- if got := humanAgo(tm, now); got != f.Human {
- t.Errorf("human %d: %q != expected %q", f.Timestamp, got, f.Human)
- }
- }
- for _, f := range fixtures.Amounts {
- if got := amount(f.Value, ","); got != f.Amount {
- t.Errorf("amount %v: %q != expected %q", f.Value, got, f.Amount)
- }
- if got := amount(f.Value, ""); got != f.Plain {
- t.Errorf("plain %v: %q != expected %q", f.Value, got, f.Plain)
- }
- if got := currency(f.Value); got != f.Currency {
- t.Errorf("currency %v: %q != expected %q", f.Value, got, f.Currency)
- }
- }
-}
diff --git a/internal/explorer/json.go b/internal/explorer/json.go
deleted file mode 100644
index 80c40c9..0000000
--- a/internal/explorer/json.go
+++ /dev/null
@@ -1,336 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "math"
- "net/http"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "unicode/utf16"
- "unicode/utf8"
-)
-
-// PHP defaults preserve insertion order, escape Unicode and slashes, reject
-// malformed UTF-8, and switch float notation outside exponents [-4,16].
-func phpJSON(v any) ([]byte, error) {
- var out bytes.Buffer
- if err := appendPHPJSON(&out, reflect.ValueOf(v)); err != nil {
- return nil, err
- }
- return out.Bytes(), nil
-}
-func appendJSONString(out *bytes.Buffer, s string) error {
- if !utf8.ValidString(s) {
- return errors.New("malformed UTF-8 characters")
- }
- out.WriteByte('"')
- for _, r := range s {
- switch r {
- case '"':
- out.WriteString(`\"`)
- case '\\':
- out.WriteString(`\\`)
- case '/':
- out.WriteString(`\/`)
- case '\b':
- out.WriteString(`\b`)
- case '\f':
- out.WriteString(`\f`)
- case '\n':
- out.WriteString(`\n`)
- case '\r':
- out.WriteString(`\r`)
- case '\t':
- out.WriteString(`\t`)
- default:
- if r < 32 || r > 127 {
- if r <= 0xffff {
- fmt.Fprintf(out, `\u%04x`, r)
- } else {
- a, b := utf16.EncodeRune(r)
- fmt.Fprintf(out, `\u%04x\u%04x`, a, b)
- }
- } else {
- out.WriteRune(r)
- }
- }
- }
- out.WriteByte('"')
- return nil
-}
-func phpFloat(f float64) (string, error) {
- if math.IsNaN(f) || math.IsInf(f, 0) {
- return "", errors.New("Inf and NaN cannot be JSON encoded")
- }
- e := strconv.FormatFloat(f, 'e', -1, 64)
- i := strings.IndexByte(e, 'e')
- exponent, _ := strconv.Atoi(e[i+1:])
- if exponent < -4 || exponent >= 17 {
- mantissa := e[:i]
- if !strings.Contains(mantissa, ".") {
- mantissa += ".0"
- }
- return mantissa + fmt.Sprintf("e%+d", exponent), nil
- }
- return strconv.FormatFloat(f, 'f', -1, 64), nil
-}
-
-type jsonField struct {
- Key string
- Value any
-}
-type jsonObject []jsonField
-
-func appendObject(out *bytes.Buffer, fields []jsonField) error {
- out.WriteByte('{')
- for i, f := range fields {
- if i > 0 {
- out.WriteByte(',')
- }
- if e := appendJSONString(out, f.Key); e != nil {
- return e
- }
- out.WriteByte(':')
- if e := appendPHPJSON(out, reflect.ValueOf(f.Value)); e != nil {
- return e
- }
- }
- out.WriteByte('}')
- return nil
-}
-func rowFields(r Row) []jsonField {
- keys, ok := r["__columns"].([]string)
- if !ok {
- for key := range r {
- if key != "__columns" {
- keys = append(keys, key)
- }
- }
- sort.Strings(keys)
- }
- fields := make([]jsonField, 0, len(keys))
- for _, key := range keys {
- fields = append(fields, jsonField{key, r[key]})
- }
- return fields
-}
-func appendPHPJSON(out *bytes.Buffer, v reflect.Value) error {
- if !v.IsValid() {
- out.WriteString("null")
- return nil
- }
- if v.Kind() == reflect.Interface || v.Kind() == reflect.Pointer {
- if v.IsNil() {
- out.WriteString("null")
- return nil
- }
- return appendPHPJSON(out, v.Elem())
- }
- if v.CanInterface() {
- switch value := v.Interface().(type) {
- case Row:
- return appendObject(out, rowFields(value))
- case jsonObject:
- return appendObject(out, value)
- case json.RawMessage:
- if !json.Valid(value) {
- return errors.New("invalid raw JSON")
- }
- out.Write(value)
- return nil
- case json.Number:
- if i, e := value.Int64(); e == nil {
- out.WriteString(strconv.FormatInt(i, 10))
- return nil
- }
- f, e := value.Float64()
- if e != nil {
- return e
- }
- s, e := phpFloat(f)
- if e != nil {
- return e
- }
- out.WriteString(s)
- return nil
- }
- }
- switch v.Kind() {
- case reflect.Bool:
- out.WriteString(strconv.FormatBool(v.Bool()))
- case reflect.String:
- return appendJSONString(out, v.String())
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- out.WriteString(strconv.FormatInt(v.Int(), 10))
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- out.WriteString(strconv.FormatUint(v.Uint(), 10))
- case reflect.Float32, reflect.Float64:
- s, e := phpFloat(v.Float())
- if e != nil {
- return e
- }
- out.WriteString(s)
- case reflect.Slice, reflect.Array:
- if v.Kind() == reflect.Slice && v.IsNil() {
- out.WriteString("null")
- return nil
- }
- out.WriteByte('[')
- for i := 0; i < v.Len(); i++ {
- if i > 0 {
- out.WriteByte(',')
- }
- if e := appendPHPJSON(out, v.Index(i)); e != nil {
- return e
- }
- }
- out.WriteByte(']')
- case reflect.Map:
- if v.IsNil() {
- out.WriteString("null")
- return nil
- }
- if v.Type().Key().Kind() != reflect.String {
- return errors.New("nonstring JSON map key")
- }
- keys := v.MapKeys()
- sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
- fields := make([]jsonField, 0, len(keys))
- for _, key := range keys {
- fields = append(fields, jsonField{key.String(), v.MapIndex(key).Interface()})
- }
- return appendObject(out, fields)
- case reflect.Struct:
- fields := []jsonField{}
- typ := v.Type()
- for i := 0; i < v.NumField(); i++ {
- field := typ.Field(i)
- if !field.IsExported() {
- continue
- }
- tag := strings.Split(field.Tag.Get("json"), ",")
- if tag[0] == "-" {
- continue
- }
- if len(tag) > 1 && tag[1] == "omitempty" && v.Field(i).IsZero() {
- continue
- }
- key := tag[0]
- if key == "" {
- key = field.Name
- }
- fields = append(fields, jsonField{key, v.Field(i).Interface()})
- }
- return appendObject(out, fields)
- default:
- return fmt.Errorf("unsupported JSON type %s", v.Kind())
- }
- return nil
-}
-func sendJSON(w http.ResponseWriter, status int, v any) {
- b, e := phpJSON(v)
- if e != nil {
- internalError(w)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(status)
- w.Write(b)
-}
-func jsonError(w http.ResponseWriter, status int, message string) {
- sendJSON(w, status, struct {
- Error bool `json:"error"`
- Message string `json:"message"`
- }{true, message})
-}
-func (r Row) MarshalJSON() ([]byte, error) { return phpJSON(r) }
-func orderedRows(rows []Row, keys ...string) []Row {
- if rows == nil {
- return []Row{}
- }
- for _, r := range rows {
- r["__columns"] = keys
- }
- return rows
-}
-
-// Decode DB JSON in source order, retaining an empty object as {} rather than [].
-func decodeOrderedJSON(s string) (any, error) {
- d := json.NewDecoder(strings.NewReader(s))
- d.UseNumber()
- return readJSONValue(d)
-}
-func readJSONValue(d *json.Decoder) (any, error) {
- token, e := d.Token()
- if e != nil {
- return nil, e
- }
- if delimiter, ok := token.(json.Delim); ok {
- switch delimiter {
- case '{':
- obj := jsonObject{}
- for d.More() {
- key, e := d.Token()
- if e != nil {
- return nil, e
- }
- value, e := readJSONValue(d)
- if e != nil {
- return nil, e
- }
- obj = append(obj, jsonField{key.(string), value})
- }
- _, e = d.Token()
- return obj, e
- case '[':
- arr := []any{}
- for d.More() {
- value, e := readJSONValue(d)
- if e != nil {
- return nil, e
- }
- arr = append(arr, value)
- }
- _, e = d.Token()
- return arr, e
- }
- }
- return token, nil
-}
-
-// Cake JsonType decodes JSON objects to PHP associative arrays. Empty objects
-// and objects whose numeric keys form 0..n-1 consequently serialize as arrays.
-func cakeJSONArray(v any) any {
- switch value := v.(type) {
- case jsonObject:
- if len(value) == 0 {
- return []any{}
- }
- sequential := true
- for i, f := range value {
- value[i].Value = cakeJSONArray(f.Value)
- if f.Key != strconv.Itoa(i) {
- sequential = false
- }
- }
- if sequential {
- arr := make([]any, len(value))
- for i, f := range value {
- arr[i] = f.Value
- }
- return arr
- }
- return value
- case []any:
- for i, item := range value {
- value[i] = cakeJSONArray(item)
- }
- return value
- }
- return v
-}
diff --git a/internal/explorer/json_test.go b/internal/explorer/json_test.go
deleted file mode 100644
index 4e1538c..0000000
--- a/internal/explorer/json_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package explorer
-
-import (
- "encoding/json"
- "math"
- "os"
- "testing"
-)
-
-func TestJSONNumbers(t *testing.T) {
- b, e := os.ReadFile("testdata/formatting.json")
- if e != nil {
- t.Fatal(e)
- }
- var f struct {
- JSON []struct {
- Value json.Number
- Encoded string
- }
- }
- if e = json.Unmarshal(b, &f); e != nil {
- t.Fatal(e)
- }
- if len(f.JSON) == 0 {
- t.Fatal("no numeric fixtures")
- }
- for _, c := range f.JSON {
- var value any = c.Value
- if string(c.Value) == "-0" {
- value = math.Copysign(0, -1)
- }
- b, e := phpJSON(value)
- if e != nil || string(b) != c.Encoded {
- t.Errorf("%s => %s != expected %s (%v)", c.Value, b, c.Encoded, e)
- }
- }
- for _, v := range []any{string([]byte{0xff}), Row{"bad": string([]byte{0xc3})}} {
- if _, e = phpJSON(v); e == nil {
- t.Fatal("invalid UTF-8 accepted")
- }
- }
-}
-func TestCakeJSONAssociativeArrays(t *testing.T) {
- for _, c := range []struct{ in, want string }{{`{}`, `[]`}, {`{"0":"a","1":"b"}`, `["a","b"]`}, {`{"long":{},"z":1.0}`, `{"long":[],"z":1}`}} {
- v, e := decodeOrderedJSON(c.in)
- if e != nil {
- t.Fatal(e)
- }
- b, e := phpJSON(cakeJSONArray(v))
- if e != nil || string(b) != c.want {
- t.Fatal(string(b), c.want, e)
- }
- }
-}
diff --git a/internal/explorer/observe.go b/internal/explorer/observe.go
deleted file mode 100644
index 479dcff..0000000
--- a/internal/explorer/observe.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package explorer
-
-import (
- "context"
- "database/sql"
- "errors"
- "log/slog"
- "net/http"
- "time"
-
- "github.com/go-sql-driver/mysql"
-)
-
-// ObservedStore records query cost without logging SQL, arguments, credentials,
-// claim metadata or database error messages. It introduces no DB operations.
-type ObservedStore struct {
- Store Store
- Logger *slog.Logger
- Stats func() sql.DBStats
-}
-
-func (s ObservedStore) Query(ctx context.Context, q string, args ...any) ([]Row, error) {
- started := time.Now()
- rows, err := s.Store.Query(ctx, q, args...)
- if s.Logger != nil {
- code := 0
- var mysqlErr *mysql.MySQLError
- if errors.As(err, &mysqlErr) {
- code = int(mysqlErr.Number)
- }
- attrs := []any{"duration_ms", float64(time.Since(started)) / float64(time.Millisecond), "rows", len(rows), "success", err == nil, "mysql_error_code", code}
- if s.Stats != nil {
- stats := s.Stats()
- attrs = append(attrs, "pool_open", stats.OpenConnections, "pool_in_use", stats.InUse, "pool_wait_count", stats.WaitCount, "pool_wait_ms", stats.WaitDuration.Milliseconds())
- }
- s.Logger.InfoContext(ctx, "db_query", attrs...)
- }
- return rows, err
-}
-
-type observedResponse struct {
- http.ResponseWriter
- status int
- bytes int64
-}
-
-func (w *observedResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter }
-func (w *observedResponse) WriteHeader(status int) {
- if w.status != 0 {
- return
- }
- w.status = status
- w.ResponseWriter.WriteHeader(status)
-}
-func (w *observedResponse) Write(b []byte) (int, error) {
- if w.status == 0 {
- w.WriteHeader(200)
- }
- n, e := w.ResponseWriter.Write(b)
- w.bytes += int64(n)
- return n, e
-}
-
-// AccessLog uses the matched action instead of raw query parameters or paths.
-// It adds no headers or public monitoring routes.
-func AccessLog(next http.Handler, logger *slog.Logger) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- started := time.Now()
- response := &observedResponse{ResponseWriter: w}
- next.ServeHTTP(response, r)
- status := response.status
- if status == 0 {
- status = 200
- }
- if logger != nil {
- logger.InfoContext(r.Context(), "http_request", "method", r.Method, "action", matchRoute(r.URL.EscapedPath(), r.Method).Action, "status", status, "bytes", response.bytes, "duration_ms", float64(time.Since(started))/float64(time.Millisecond))
- }
- })
-}
diff --git a/internal/explorer/observe_test.go b/internal/explorer/observe_test.go
deleted file mode 100644
index 78d9eaa..0000000
--- a/internal/explorer/observe_test.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "context"
- "database/sql"
- "encoding/json"
- "errors"
- "log/slog"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
-)
-
-type failedStore struct{}
-
-func (failedStore) Query(context.Context, string, ...any) ([]Row, error) {
- return nil, errors.New("private-password-or-SQL-must-not-be-logged")
-}
-func TestObservabilityPreservesResponseAndRedactsInputs(t *testing.T) {
- var log bytes.Buffer
- logger := slog.New(slog.NewJSONHandler(&log, nil))
- observed := ObservedStore{Store: &fakeStore{rows: []Row{}}, Logger: logger, Stats: func() sql.DBStats { return sql.DBStats{OpenConnections: 1, WaitCount: 2} }}
- app := &Server{Store: observed}
- w := httptest.NewRecorder()
- AccessLog(app, logger).ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/status?secret=do-not-log", nil))
- if w.Code != 200 || w.Body.String() != `{"success":true,"status":{"height":0,"difficulty":"0.00","price":"N\/A","hashrate":"N\/A"}}` {
- t.Fatal(w.Code, w.Body.String())
- }
- if strings.Contains(log.String(), "secret") || strings.Contains(log.String(), "SELECT") || strings.Contains(log.String(), "do-not-log") {
- t.Fatal("private input in logs")
- }
- for _, line := range strings.Split(strings.TrimSpace(log.String()), "\n") {
- var item map[string]any
- if e := json.Unmarshal([]byte(line), &item); e != nil {
- t.Fatal(e)
- }
- }
- failed := ObservedStore{Store: failedStore{}, Logger: logger}
- failed.Query(context.Background(), "SELECT private", "password")
- if strings.Contains(log.String(), "private-password") || strings.Contains(log.String(), "SELECT private") {
- t.Fatal("database error text or SQL leaked")
- }
-}
-func TestAccessLogHeadResponse(t *testing.T) {
- app := AccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Test", "kept"); w.WriteHeader(302) }), nil)
- w := httptest.NewRecorder()
- app.ServeHTTP(w, httptest.NewRequest("HEAD", "/", nil))
- if w.Code != 302 || w.Header().Get("X-Test") != "kept" || w.Body.Len() != 0 {
- t.Fatal(w.Code, w.Header(), w.Body.String())
- }
-}
diff --git a/internal/explorer/pages.go b/internal/explorer/pages.go
deleted file mode 100644
index 08e66c1..0000000
--- a/internal/explorer/pages.go
+++ /dev/null
@@ -1,297 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "embed"
- "encoding/json"
- "fmt"
- "html"
- "html/template"
- "math"
- "math/rand/v2"
- "net/http"
- "strconv"
- "strings"
- "time"
-)
-
-//go:embed templates/*.html
-var templateFiles embed.FS
-
-type pageData struct {
- Tx Row
- Inputs, Outputs []ioView
- Fee string
- Address Row
- RecentTxs, RichList []Row
- BalanceAmount, TotalReceived, TotalSent float64
- InflationChartVersion int64
- Claim Row
- MoreClaims []Row
- ClaimIsBlocked bool
- Title string
- Analytics bool
- RecentBlocks, RecentClaims, Blocks, Txs []Row
- Highest, Block Row
- Confirmations int64
- NumRecords, NumPages, CurrentPage, PageLimit int
- Begin, End int
- Pagination pagination
- Claims []Row
- Cards []claimCard
-}
-
-func text(v any) string {
- if v == nil {
- return ""
- }
- if n, ok := v.(json.Number); ok {
- if strings.ContainsAny(string(n), ".eE") {
- return phpString(number(n))
- }
- return string(n)
- }
- if f, ok := v.(float64); ok {
- return phpString(f)
- }
- return fmt.Sprint(v)
-}
-func truth(v any) bool {
- if v == nil {
- return false
- }
- if b, ok := v.(bool); ok {
- return b
- }
- s := text(v)
- return s != "" && s != "0"
-}
-func fixed(v any, places int) string {
- return strconv.FormatFloat(roundPHP(number(v), places), 'f', places, 64)
-}
-func grouped(v any, places int) string {
- s := fixed(v, places)
- parts := strings.SplitN(s, ".", 2)
- sign := ""
- if strings.HasPrefix(parts[0], "-") {
- sign = "-"
- parts[0] = parts[0][1:]
- }
- n := parts[0]
- for i := len(n) - 3; i > 0; i -= 3 {
- n = n[:i] + "," + n[i:]
- }
- if len(parts) > 1 {
- n += "." + parts[1]
- }
- return sign + n
-}
-func amount(v any, separator string) string {
- s := fixed(v, 8)
- if separator != "" {
- s = strings.ReplaceAll(grouped(v, 8), ",", separator)
- }
- return strings.TrimSuffix(strings.TrimRight(s, "0"), ".")
-}
-func currency(v any) string {
- s := text(v)
- parts := strings.SplitN(s, ".", 2)
- if len(parts) == 1 {
- return grouped(v, 2)
- }
- left := grouped(parts[0], 0)
- if number("0."+parts[1]) == 0 {
- return left
- }
- right := parts[1] + "00"
- return left + "." + right[:2]
-}
-func timestamp(v any) time.Time {
- if str, ok := v.(string); ok {
- for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339Nano} {
- if t, e := time.ParseInLocation(layout, str, time.UTC); e == nil {
- return t
- }
- }
- }
- return time.Unix(int64(number(v)), 0).UTC()
-}
-func contentTag(r Row) string {
- ct := text(r["content_type"])
- for _, prefix := range []string{"audio", "video", "image"} {
- if strings.HasPrefix(ct, prefix) {
- return strings.ToUpper(prefix)
- }
- }
- if number(r["claim_type"]) == 2 {
- return "IDENTITY"
- }
- return ""
-}
-func autoThumb(r Row) string {
- name := text(r["name"])
- n := 5
- if number(r["claim_type"]) == 2 {
- n = 10
- if len(name) > 0 {
- name = name[1:]
- }
- } else if title := phpTrim(text(r["title"])); title != "" {
- name = title
- }
- if len(name) > n {
- name = name[:n]
- }
- var b strings.Builder
- for i := 0; i < len(name); i++ {
- c := name[i]
- if c >= 'a' && c <= 'z' {
- c -= 32
- }
- b.WriteByte(c)
- }
- return b.String()
-}
-func claimTitle(r Row) string {
- if number(r["claim_type"]) == 1 {
- return text(r["name"])
- }
- if phpTrim(text(r["title"])) != "" {
- return text(r["title"])
- }
- return ""
-}
-func lbryLink(r Row) template.URL {
- name := text(r["name"])
- if publisher := text(r["publisher"]); publisher != "" {
- name = publisher + "/" + name
- }
- return template.URL("lbry://" + name)
-}
-func thumbColor() string {
- return []string{"purple", "orange", "blue", "teal", "green", "yellow"}[rand.IntN(6)]
-}
-func (s *Server) functions() template.FuncMap {
- return template.FuncMap{
- "confirmationDelay": confirmationDelay, "safeURL": safeURL, "ownedAddress": func(v any) bool { return ownedAddresses[text(v)] }, "txClass": func(r Row) string {
- if number(r["debit_amount"]) > 0 {
- if number(r["credit_amount"]) > 0 {
- return "diff"
- }
- return "debit"
- }
- return "credit"
- }, "difference": func(a, b any) float64 { return number(a) - number(b) },
- "isset": func(row Row, key string) bool { return row[key] != nil }, "trim": func(v any) string { return phpTrim(text(v)) }, "language": func(v any) string {
- if text(v) == "en" {
- return "English"
- }
- return text(v)
- }, "claimCost": claimCost, "description": description, "publisherLink": func(v any) template.URL { return template.URL("lbry://" + text(v)) }, "claimDate": func(r Row) string {
- v := r["created_at"]
- if number(r["transaction_time"]) > 0 {
- v = r["transaction_time"]
- }
- return timestamp(v).Format("2 Jan 2006 15:04:05")
- },
- "text": text, "truth": truth, "num": number, "fixed": fixed, "grouped": grouped, "amount": amount, "currency": currency, "contentTag": contentTag, "autoThumb": autoThumb, "claimTitle": claimTitle, "lbryLink": lbryLink, "lbryHref": func(r Row) template.HTMLAttr {
- return template.HTMLAttr(`href="` + html.EscapeString(string(lbryLink(r))) + `"`)
- }, "publisherHref": func(v any) template.HTMLAttr {
- return template.HTMLAttr(`href="` + html.EscapeString("lbry://"+text(v)) + `"`)
- }, "thumbColor": thumbColor,
- "showThumbnail": func(r Row) bool { return !truth(r["is_nsfw"]) && phpTrim(text(r["thumbnail_url"])) != "" },
- "thumbnail": func(v any) string {
- return "https://thumbnails.odycdn.com/optimize/s:1280:720/quality:85/plain/" + text(v)
- },
- "kb": func(v any) string { return phpString(roundPHP(number(v)/1024, 2)) + "KB" },
- "date": func(v any, layout string) string { return timestamp(v).Format(layout) },
- "ago": func(v any) string { return cakeAgo(timestamp(v), s.now()) },
- "humanAgo": func(v any) string { return humanAgo(timestamp(v), s.now()) },
- "add": func(a, b any) int { return int(number(a) + number(b)) }, "sub": func(a, b any) int { return int(number(a) - number(b)) },
- }
-}
-
-func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, data pageData) {
- data.Analytics = r.Host == "explorer.lbry.com"
- started := time.Now()
- if value, ok := r.Context().Value(requestStartKey{}).(time.Time); ok {
- started = value
- }
- functions := s.functions()
- functions["elapsed"] = func() int64 { return int64(math.Round(float64(time.Since(started)) / float64(time.Millisecond))) }
- t, e := template.New("layout").Funcs(functions).ParseFS(templateFiles, "templates/layout.html", "templates/header.html", "templates/pagination.html", "templates/claimbox.html", "templates/"+name+".html")
- if e != nil {
- http.Error(w, "Template error", 500)
- return
- }
- var b bytes.Buffer
- if e = t.ExecuteTemplate(&b, "layout", data); e != nil {
- http.Error(w, "Template execution error", 500)
- return
- }
- w.Header().Set("Content-Type", "text/html; charset=UTF-8")
- w.Write(b.Bytes())
-}
-func (s *Server) page(w http.ResponseWriter, r *http.Request) {
- q := func(query string, args ...any) ([]Row, bool) {
- rows, e := s.Store.Query(r.Context(), query, args...)
- if e != nil {
- internalError(w)
- return nil, false
- }
- return rows, true
- }
- if r.URL.Path == "/qr" || strings.HasPrefix(r.URL.Path, "/qr/") {
- s.qr(w, r)
- return
- }
- if r.URL.Path == "/address" || strings.HasPrefix(r.URL.Path, "/address/") {
- s.addressPage(w, r)
- return
- }
- if r.URL.Path == "/stats" {
- s.statsPage(w, r)
- return
- }
- if r.URL.Path == "/tx" || strings.HasPrefix(r.URL.Path, "/tx/") {
- s.transactionPage(w, r)
- return
- }
- if r.URL.Path == "/find" {
- s.findPage(w, r)
- return
- }
- if r.URL.Path == "/claims" || strings.HasPrefix(r.URL.Path, "/claims/") {
- s.claimsPage(w, r)
- return
- }
- if r.URL.Path == "/realtime" {
- blocks, ok := q("SELECT height,block_time,tx_count FROM block ORDER BY height DESC LIMIT 10")
- if !ok {
- return
- }
- txs, ok := q("SELECT id,value,hash,input_count,output_count,transaction_time,created_at FROM transaction ORDER BY created_at DESC LIMIT 10")
- if !ok {
- return
- }
- s.render(w, r, "realtime", pageData{Title: "Realtime Explorer", Blocks: blocks, Txs: txs})
- return
- }
- if r.URL.Path == "/blocks" || strings.HasPrefix(r.URL.Path, "/blocks/") {
- s.blocksPage(w, r)
- return
- }
- blocks, ok := q("SELECT chainwork,confirmations,difficulty,hash,height,block_time,block_size,tx_count FROM block ORDER BY height DESC LIMIT 6")
- if !ok {
- return
- }
- claims, ok := q("SELECT Claims.*,C.name AS publisher FROM claim Claims LEFT JOIN claim C ON C.claim_id = Claims.publisher_id ORDER BY Claims.created_at DESC LIMIT 5")
- if !ok {
- return
- }
- highest := Row{"height": nil, "difficulty": nil}
- if len(blocks) > 0 {
- highest = blocks[0]
- }
- s.render(w, r, "home", pageData{Title: "Home", RecentBlocks: blocks, RecentClaims: claims, Highest: highest})
-}
diff --git a/internal/explorer/pagination.go b/internal/explorer/pagination.go
deleted file mode 100644
index 0f8c968..0000000
--- a/internal/explorer/pagination.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package explorer
-
-type pagination struct {
- Visible bool
- Previous, Next int
- Pages []int
- StartEllipsis, EndEllipsis bool
- Last, Current int
-}
-
-func paginate(records, limit, page int) (int, int, pagination) {
- total := (records + limit - 1) / limit
- if page < 1 {
- page = 1
- }
- if page > total {
- page = total
- }
- p := pagination{Visible: total > 1, Last: total, Current: page}
- if page > 1 {
- p.Previous = page - 1
- }
- if page < total {
- p.Next = page + 1
- }
- start, end := 1, min(total, 10)
- if total > 10 && page > 5 {
- if page >= 10 {
- start = page - 5
- }
- if page > total-10 && start > 5 {
- end = total
- } else {
- end = min(page+5, total)
- }
- }
- if records > 0 {
- for i := start; i <= end; i++ {
- p.Pages = append(p.Pages, i)
- }
- p.StartEllipsis = start >= 5
- p.EndEllipsis = end < total-1
- }
- return page, total, p
-}
diff --git a/internal/explorer/qr.go b/internal/explorer/qr.go
deleted file mode 100644
index 84aa3e1..0000000
--- a/internal/explorer/qr.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package explorer
-
-import (
- "fmt"
- "github.com/makiuchi-d/gozxing"
- "github.com/makiuchi-d/gozxing/qrcode/decoder"
- "github.com/makiuchi-d/gozxing/qrcode/encoder"
- "image"
- "image/color"
- "image/png"
- "net/http"
- "strings"
-)
-
-func qrImage(data string) (image.Image, error) {
- first, e := encoder.Encoder_encode(data, decoder.ErrorCorrectionLevel_H, map[gozxing.EncodeHintType]interface{}{gozxing.EncodeHintType_CHARACTER_SET: "UTF-8", gozxing.EncodeHintType_QR_MASK_PATTERN: 0})
- if e != nil {
- return nil, e
- }
- version, versionErr := baconVersion(data, first.GetMode())
- if versionErr != nil {
- return nil, versionErr
- }
- var matrix *encoder.ByteMatrix
- best := int(^uint(0) >> 1)
- // Bacon 3.1 requires four white modules within the matrix for penalty
- // rule 3; ZXing treats the outside border as white. Score all eight
- // encodings with Bacon's rule to preserve Endroid's exact mask choice.
- for mask := 0; mask < 8; mask++ {
- code, e := encoder.Encoder_encode(data, decoder.ErrorCorrectionLevel_H, map[gozxing.EncodeHintType]interface{}{gozxing.EncodeHintType_CHARACTER_SET: "UTF-8", gozxing.EncodeHintType_QR_MASK_PATTERN: mask, gozxing.EncodeHintType_QR_VERSION: version})
- if e != nil {
- return nil, e
- }
- candidate := code.GetMatrix()
- score := baconPenalty(candidate)
- if score < best {
- best = score
- matrix = candidate
- }
- }
- n := matrix.GetWidth()
- block := 300 / n
- margin := (320 - n*block) / 2
- img := image.NewGray(image.Rect(0, 0, 320, 320))
- for i := range img.Pix {
- img.Pix[i] = 255
- }
- for y := 0; y < n; y++ {
- for x := 0; x < n; x++ {
- if matrix.Get(x, y) != 1 {
- continue
- }
- for dy := 0; dy < block; dy++ {
- for dx := 0; dx < block; dx++ {
- img.SetGray(margin+x*block+dx, margin+y*block+dy, color.Gray{0})
- }
- }
- }
- }
- return img, nil
-}
-func (s *Server) qr(w http.ResponseWriter, r *http.Request) {
- data := firstArgument(r, "/qr")
- trimmed := strings.Trim(data, " \t\n\r\x00\x0b")
- if data == "0" || len(trimmed) == 0 || len(trimmed) > 50 {
- jsonError(w, 400, "Invalid QR code data.")
- return
- }
- img, e := qrImage(data)
- if e != nil {
- internalError(w)
- return
- }
- w.Header().Set("Content-Type", "image/png")
- png.Encode(w, img)
-}
-
-func baconPenalty(m *encoder.ByteMatrix) int {
- score := encoder.MaskUtil_applyMaskPenaltyRule1(m) + encoder.MaskUtil_applyMaskPenaltyRule2(m) + encoder.MaskUtil_applyMaskPenaltyRule4(m)
- n := m.GetWidth()
- for axis := 0; axis < 2; axis++ {
- for line := 0; line < n; line++ {
- at := func(i int) int8 {
- if axis == 0 {
- return m.Get(i, line)
- }
- return m.Get(line, i)
- }
- white := func(a, b int) bool {
- if a < 0 || b > n {
- return false
- }
- for i := a; i < b; i++ {
- if at(i) != 0 {
- return false
- }
- }
- return true
- }
- for i := 0; i+6 < n; i++ {
- if at(i) == 1 && at(i+1) == 0 && at(i+2) == 1 && at(i+3) == 1 && at(i+4) == 1 && at(i+5) == 0 && at(i+6) == 1 && (white(i-4, i) || white(i+7, i+11)) {
- score += 40
- }
- }
- }
- }
- return score
-}
-
-func baconVersion(data string, mode *decoder.Mode) (int, error) {
- header, bits := 4, 0
- switch mode {
- case decoder.Mode_BYTE:
- header += 12
- bits = len(data) * 8
- case decoder.Mode_NUMERIC:
- bits = len(data) / 3 * 10
- if len(data)%3 == 1 {
- bits += 4
- } else if len(data)%3 == 2 {
- bits += 7
- }
- case decoder.Mode_ALPHANUMERIC:
- bits = len(data)/2*11 + len(data)%2*6
- default:
- return 0, fmt.Errorf("unsupported QR encoding mode")
- }
- choose := func(countBits int) (*decoder.Version, error) {
- for n := 1; n <= 40; n++ {
- v, _ := decoder.Version_GetVersionForNumber(n)
- capacity := v.GetTotalCodewords() - v.GetECBlocksForLevel(decoder.ErrorCorrectionLevel_H).GetTotalECCodewords()
- if capacity >= (header+countBits+bits+8)/8 {
- return v, nil
- }
- }
- return nil, fmt.Errorf("QR data too big")
- }
- v1, _ := decoder.Version_GetVersionForNumber(1)
- provisional, e := choose(mode.GetCharacterCountBits(v1))
- if e != nil {
- return 0, e
- }
- version, e := choose(mode.GetCharacterCountBits(provisional))
- if e != nil {
- return 0, e
- }
- return version.GetVersionNumber(), nil
-}
diff --git a/internal/explorer/qr_test.go b/internal/explorer/qr_test.go
deleted file mode 100644
index e078257..0000000
--- a/internal/explorer/qr_test.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package explorer
-
-import (
- "bytes"
- "crypto/sha256"
- "encoding/json"
- "fmt"
- "github.com/makiuchi-d/gozxing"
- "github.com/makiuchi-d/gozxing/qrcode"
- "image/png"
- "net/http/httptest"
- "net/url"
- "os"
- "strings"
- "testing"
-)
-
-func TestQRRendering(t *testing.T) {
- raw, err := os.ReadFile("testdata/qr.json")
- if err != nil {
- t.Fatal(err)
- }
- var cases []struct {
- Data string
- Width, Height int
- SHA256 string
- }
- if err = json.Unmarshal(raw, &cases); err != nil {
- t.Fatal(err)
- }
- if len(cases) < 50 {
- t.Fatal("missing QR regression cases")
- }
- for _, c := range cases {
- t.Run(c.Data, func(t *testing.T) {
- img, err := qrImage(c.Data)
- if err != nil {
- t.Fatal(err)
- }
- if img.Bounds().Dx() != c.Width || img.Bounds().Dy() != c.Height {
- t.Fatal("QR dimensions changed", img.Bounds())
- }
- pixels := make([]byte, 0, c.Width*c.Height*4)
- for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
- for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
- r, g, b, a := img.At(x, y).RGBA()
- pixels = append(pixels, byte(r>>8), byte(g>>8), byte(b>>8), byte(a>>8))
- }
- }
- if got := fmt.Sprintf("%x", sha256.Sum256(pixels)); got != c.SHA256 {
- t.Fatal("QR pixels changed", got, c.SHA256)
- }
- })
- }
-}
-
-func TestQRPayloadAndRouting(t *testing.T) {
- for _, data := range []string{"lbry://hello/path", " hello ", "éà😀", strings.Repeat("a", 50)} {
- w := httptest.NewRecorder()
- s := Server{}
- s.ServeHTTP(w, httptest.NewRequest("GET", "/qr/"+url.PathEscape(data), nil))
- if w.Code != 200 || w.Header().Get("Content-Type") != "image/png" {
- t.Fatal(w.Code, w.Body.String())
- }
- img, e := png.Decode(bytes.NewReader(w.Body.Bytes()))
- if e != nil {
- t.Fatal(e)
- }
- bitmap, e := gozxing.NewBinaryBitmapFromImage(img)
- if e != nil {
- t.Fatal(e)
- }
- result, e := qrcode.NewQRCodeReader().Decode(bitmap, nil)
- if e != nil || result.GetText() != data {
- t.Fatal(data, result, e)
- }
- }
-}
-func TestQRInvalidBoundaries(t *testing.T) {
- for _, data := range []string{"", "0", " \t\n", strings.Repeat("é", 26), strings.Repeat("a", 51)} {
- w := httptest.NewRecorder()
- s := Server{}
- s.ServeHTTP(w, httptest.NewRequest("GET", "/qr/"+url.PathEscape(data), nil))
- if w.Code != 400 || w.Body.String() != `{"error":true,"message":"Invalid QR code data."}` {
- t.Fatal(data, w.Code, w.Body.String())
- }
- }
-}
diff --git a/internal/explorer/query.go b/internal/explorer/query.go
deleted file mode 100644
index 2f976a4..0000000
--- a/internal/explorer/query.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package explorer
-
-import (
- "net/http"
- "strings"
-)
-
-func phpTrim(s string) string { return strings.Trim(s, " \t\n\r\x00\x0b") }
-
-type queryParameter struct {
- Value string
- Array bool
- Present bool
-}
-
-func queryParam(r *http.Request, key string) queryParameter {
- var result queryParameter
- for _, part := range strings.Split(r.URL.RawQuery, "&") {
- pair := strings.SplitN(part, "=", 2)
- name := phpQueryDecode(pair[0])
- value := ""
- if len(pair) > 1 {
- value = phpQueryDecode(pair[1])
- }
- if name == key {
- result = queryParameter{value, false, true}
- continue
- }
- if strings.HasPrefix(name, key+"[") && strings.Contains(name[len(key)+1:], "]") {
- result = queryParameter{"", true, true}
- }
- }
- return result
-}
-func queryString(r *http.Request, key string) string {
- v := queryParam(r, key)
- if v.Array {
- return "Array"
- }
- return v.Value
-}
-func queryInt(r *http.Request, key string) int {
- v := queryParam(r, key)
- if v.Array {
- return 1
- }
- return phpInt(v.Value)
-}
-func queryScalar(r *http.Request, key string) string {
- v := queryParam(r, key)
- if v.Array {
- return ""
- }
- return v.Value
-}
-
-func phpQueryDecode(s string) string {
- var out strings.Builder
- hex := func(b byte) int {
- switch {
- case b >= '0' && b <= '9':
- return int(b - '0')
- case b >= 'a' && b <= 'f':
- return int(b-'a') + 10
- case b >= 'A' && b <= 'F':
- return int(b-'A') + 10
- }
- return -1
- }
- for i := 0; i < len(s); i++ {
- if s[i] == '+' {
- out.WriteByte(' ')
- } else if s[i] == '%' && i+2 < len(s) && hex(s[i+1]) >= 0 && hex(s[i+2]) >= 0 {
- out.WriteByte(byte(hex(s[i+1])*16 + hex(s[i+2])))
- i += 2
- } else {
- out.WriteByte(s[i])
- }
- }
- return out.String()
-}
diff --git a/internal/explorer/redirect.go b/internal/explorer/redirect.go
deleted file mode 100644
index 6f1759e..0000000
--- a/internal/explorer/redirect.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package explorer
-
-import (
- "net/http"
-)
-
-type headWriter struct{ http.ResponseWriter }
-
-func (w headWriter) Write(b []byte) (int, error) { return len(b), nil }
-func redirect(w http.ResponseWriter, r *http.Request, location string, status int) {
- scheme := "http"
- if r.TLS != nil || r.URL.Scheme == "https" || r.Header.Get("X-Forwarded-Proto") == "https" {
- scheme = "https"
- }
- w.Header().Set("Location", scheme+"://"+r.Host+location)
- w.Header().Set("Content-Type", "text/html; charset=UTF-8")
- w.WriteHeader(status)
-}
diff --git a/internal/explorer/rounding.go b/internal/explorer/rounding.go
deleted file mode 100644
index bef79d2..0000000
--- a/internal/explorer/rounding.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package explorer
-
-import "math"
-
-// PHP 8.5 half-up rounding compares the unscaled number with a reconstructed
-// half boundary. This avoids decimal-scaling errors such as 1.005*100 < 100.5.
-// Algorithm adapted from PHP Group's _php_math_round, PHP License 3.01:
-// https://github.com/php/php-src/blob/PHP-8.5/ext/standard/math.c
-// Copyright (c) The PHP Group. See licenses/PHP-3.01.txt.
-func roundPHP(value float64, places int) float64 {
- if value == 0 {
- return 0
- }
- if math.IsNaN(value) || math.IsInf(value, 0) {
- return value
- }
- sign := 1.0
- if value < 0 {
- sign = -1
- value = -value
- }
- scale := math.Pow10(places)
- integral := math.Floor(value * scale)
- if (integral+1)/scale == value {
- integral++
- }
- if integral >= 1e16 {
- return sign * value
- }
- if value >= (integral+.5)/scale {
- integral++
- }
- result := integral / scale
- if result == 0 {
- return 0
- }
- return sign * result
-}
diff --git a/internal/explorer/rounding_test.go b/internal/explorer/rounding_test.go
deleted file mode 100644
index b4b647d..0000000
--- a/internal/explorer/rounding_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package explorer
-
-import (
- "context"
- "encoding/json"
- "net/http/httptest"
- "os"
- "regexp"
- "strconv"
- "testing"
- "time"
-)
-
-func TestRoundingBoundaries(t *testing.T) {
- b, e := os.ReadFile("testdata/formatting.json")
- if e != nil {
- t.Fatal(e)
- }
- var f struct {
- Rounds []struct {
- Value float64
- Places int
- Expected string
- }
- }
- if e = json.Unmarshal(b, &f); e != nil {
- t.Fatal(e)
- }
- if len(f.Rounds) < 30 {
- t.Fatal("missing rounding cases")
- }
- for _, c := range f.Rounds {
- if got := fixed(c.Value, c.Places); got != c.Expected {
- t.Errorf("%v precision %d: %s != expected %s", c.Value, c.Places, got, c.Expected)
- }
- }
- s := Server{Store: &fakeStore{rows: []Row{{"height": 1, "difficulty": 1.005}}}}
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/status", nil))
- if w.Body.String() != `{"success":true,"status":{"height":1,"difficulty":"1.01","price":"N\/A","hashrate":"N\/A"}}` {
- t.Fatal(w.Body.String())
- }
-}
-
-type delayedStore struct{}
-
-func (delayedStore) Query(context.Context, string, ...any) ([]Row, error) {
- time.Sleep(3 * time.Millisecond)
- return []Row{}, nil
-}
-func TestFooterMeasuresRequestWork(t *testing.T) {
- w := httptest.NewRecorder()
- s := Server{Store: delayedStore{}}
- s.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
- match := regexp.MustCompile(`Page took ([0-9]+)ms`).FindStringSubmatch(w.Body.String())
- if len(match) != 2 {
- t.Fatal("missing timing footer")
- }
- elapsed, _ := strconv.Atoi(match[1])
- if elapsed < 5 {
- t.Fatal("footer omitted database time", elapsed)
- }
-}
diff --git a/internal/explorer/routes.go b/internal/explorer/routes.go
deleted file mode 100644
index 963a41e..0000000
--- a/internal/explorer/routes.go
+++ /dev/null
@@ -1,105 +0,0 @@
-package explorer
-
-import (
- "context"
- "net/http"
- "net/url"
- "regexp"
- "strings"
-)
-
-type routeMatch struct {
- Action, Canonical string
- Args []string
-}
-type routeKey struct{}
-
-var apiAddressPattern = regexp.MustCompile(`^/api/v1/address/([A-Za-z0-9,]+)/utxo/*$`)
-var apiBalancePattern = regexp.MustCompile(`^/api/v1/address/([A-Za-z0-9]+)/balance/*$`)
-var apiPeriodPattern = regexp.MustCompile(`^/api/v1/charts/blocksize/([012346789dhy]+)/*$`)
-
-func matchRoute(path, method string) routeMatch {
- path = "/" + strings.TrimLeft(path, "/")
- valid := false
- for _, m := range []string{"GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS", "HEAD"} {
- if strings.ToUpper(method) == m {
- valid = true
- }
- }
- if !valid {
- return routeMatch{Action: "badmethod"}
- }
- if strings.Contains(path, "%") {
- parts := strings.Split(path, "/")
- for i, p := range parts {
- decoded, e := url.QueryUnescape(p)
- if e == nil {
- parts[i] = strings.ReplaceAll(decoded, "/", "%2f")
- }
- }
- path = strings.Join(parts, "/")
- }
- trimmed := strings.TrimRight(path, "/")
- if trimmed == "" {
- trimmed = "/"
- }
- for _, rule := range []struct {
- Pattern *regexp.Regexp
- Action, Prefix, Suffix string
- }{{apiAddressPattern, "apiaddrutxo", "/api/v1/address/", "/utxo"}, {apiBalancePattern, "apiaddrbalance", "/api/v1/address/", "/balance"}, {apiPeriodPattern, "apiblocksize", "/api/v1/charts/blocksize/", ""}} {
- if m := rule.Pattern.FindStringSubmatch(path); m != nil {
- return routeMatch{rule.Action, rule.Prefix + m[1] + rule.Suffix, []string{m[1]}}
- }
- }
- static := map[string]string{"/api/v1/charts/inflation": "apiinflation", "/api/v1/realtime/blocks": "apirealtimeblocks", "/api/v1/realtime/tx": "apirealtimetx", "/api/v1/recentblocks": "apirecentblocks", "/api/v1/status": "apistatus", "/api/v1/supply": "apiutxosupply", "/api/v1/claims/browse": "apibrowse", "/": "index", "/find": "find", "/realtime": "realtime", "/stats": "stats"}
- if action, ok := static[trimmed]; ok {
- return routeMatch{action, trimmed, []string{}}
- }
- for _, action := range []string{"address", "blocks", "claims", "tx", "qr"} {
- prefix := "/" + action
- if path == prefix || strings.HasPrefix(path, prefix+"/") {
- args := []string{}
- for _, arg := range strings.Split(strings.TrimPrefix(path, prefix), "/") {
- if arg != "" {
- v, e := url.PathUnescape(arg)
- if e == nil {
- args = append(args, v)
- }
- }
- }
- canonical := prefix
- if len(args) > 0 {
- canonical += "/" + args[0]
- }
- return routeMatch{action, canonical, args}
- }
- }
- return routeMatch{"index", "/", []string{}}
-}
-func routedRequest(r *http.Request, match routeMatch) *http.Request {
- copy := r.Clone(context.WithValue(r.Context(), routeKey{}, match))
- u := *r.URL
- u.Path = match.Canonical
- u.RawPath = ""
- copy.URL = &u
- return copy
-}
-func firstArgument(r *http.Request, prefix string) string {
- if match, ok := r.Context().Value(routeKey{}).(routeMatch); ok {
- if len(match.Args) > 0 {
- return match.Args[0]
- }
- return ""
- }
- path := strings.TrimPrefix(r.URL.EscapedPath(), prefix)
- path = strings.TrimPrefix(path, "/")
- for _, part := range strings.Split(path, "/") {
- if part != "" {
- decoded, e := url.PathUnescape(part)
- if e == nil {
- return decoded
- }
- }
- }
- return ""
-}
diff --git a/internal/explorer/routes_test.go b/internal/explorer/routes_test.go
deleted file mode 100644
index 6df56db..0000000
--- a/internal/explorer/routes_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package explorer
-
-import (
- "encoding/json"
- "os"
- "reflect"
- "testing"
-)
-
-func TestRoutes(t *testing.T) {
- b, e := os.ReadFile("testdata/routes.json")
- if e != nil {
- t.Fatal(e)
- }
- var cases []struct {
- Path, Method, Action string
- Args []string
- }
-
- if e = json.Unmarshal(b, &cases); e != nil {
- t.Fatal(e)
- }
- if len(cases) < 50 {
- t.Fatal("missing route cases")
- }
- for _, c := range cases {
- m := matchRoute(c.Path, c.Method)
- if m.Action != c.Action {
- t.Errorf("%s %s: %s != expected %s", c.Method, c.Path, m.Action, c.Action)
- }
- if c.Action != "index" && !reflect.DeepEqual(m.Args, c.Args) {
- t.Errorf("%s arguments %v != expected %v", c.Path, m.Args, c.Args)
- }
- }
-}
diff --git a/internal/explorer/server.go b/internal/explorer/server.go
deleted file mode 100644
index d92f704..0000000
--- a/internal/explorer/server.go
+++ /dev/null
@@ -1,192 +0,0 @@
-package explorer
-
-import (
- "context"
- "explorer/webroot"
- "fmt"
- "io/fs"
- "log/slog"
- "net/http"
- "path"
- "strings"
- "time"
-)
-
-type requestStartKey struct{}
-
-type Server struct {
- Logger *slog.Logger
- RandomInt func(int) int
- HTTPClient *http.Client
- Store Store
- Cache Cache
- Now func() time.Time
-}
-
-func (s *Server) now() time.Time {
- if s.Now != nil {
- return s.Now().UTC()
- }
- return time.Now().UTC()
-}
-func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- r = r.WithContext(context.WithValue(r.Context(), requestStartKey{}, time.Now()))
- if r.Method == "HEAD" {
- w = headWriter{w}
- }
- // Serve only real files under the production webroot. Missing files continue
- // through application routing, as they do in the production front controller.
- name := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
- if info, e := fs.Stat(webroot.Files, name); e == nil && !info.IsDir() {
- http.ServeFileFS(w, r, webroot.Files, name)
- return
- }
- match := matchRoute(r.URL.EscapedPath(), r.Method)
- if match.Action == "badmethod" {
- badMethodError(w, r)
- return
- }
- r = routedRequest(r, match)
- if s.api(w, r) {
- return
- }
- s.page(w, r)
-}
-func (s *Server) api(w http.ResponseWriter, r *http.Request) bool {
- path := r.URL.Path
- query := func(q string, args ...any) ([]Row, bool) {
- rows, e := s.Store.Query(r.Context(), q, args...)
- if e != nil {
- internalError(w)
- return nil, false
- }
- return rows, true
- }
- if s.remainingAPI(w, r) {
- return true
- }
- switch path {
- case "/api/v1/status":
- rows, ok := query("SELECT height,difficulty FROM block ORDER BY height DESC LIMIT 1")
- if !ok {
- return true
- }
- var height any = 0
- difficulty := 0.0
- if len(rows) > 0 {
- height = rows[0]["height"]
- difficulty = number(rows[0]["difficulty"])
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Status any `json:"status"`
- }{true, struct {
- Height any `json:"height"`
- Difficulty string `json:"difficulty"`
- Price string `json:"price"`
- Hashrate string `json:"hashrate"`
- }{height, fixed(difficulty, 2), "N/A", "N/A"}})
- case "/api/v1/recentblocks", "/api/v1/realtime/blocks":
- q := "SELECT height AS Height,block_time AS BlockTime,tx_count AS TransactionCount FROM block ORDER BY height DESC LIMIT 10"
- if path == "/api/v1/recentblocks" {
- q = "SELECT difficulty AS Difficulty,hash AS Hash,height AS Height,block_time AS BlockTime,block_size AS BlockSize,tx_count AS TransactionCount FROM block ORDER BY height DESC LIMIT 6"
- }
- rows, ok := query(q)
- if !ok {
- return true
- }
- if path == "/api/v1/recentblocks" {
- for _, row := range rows {
- row["Difficulty"] = fixed(row["Difficulty"], 2)
- }
- }
- keys := []string{"Height", "BlockTime", "TransactionCount"}
- if path == "/api/v1/recentblocks" {
- keys = []string{"Difficulty", "Hash", "Height", "BlockTime", "BlockSize", "TransactionCount"}
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Blocks []Row `json:"blocks"`
- }{true, orderedRows(rows, keys...)})
- case "/api/v1/realtime/tx":
- rows, ok := query("SELECT id,value AS Value,hash AS Hash,input_count AS InputCount,output_count AS OutputCount,transaction_time AS TxTime FROM transaction ORDER BY transaction_time DESC LIMIT 10")
- if ok {
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Txs []Row `json:"txs"`
- }{true, orderedRows(rows, "id", "Value", "Hash", "InputCount", "OutputCount", "TxTime")})
- }
- default:
- if strings.HasPrefix(path, "/api/v1/address/") && strings.HasSuffix(path, "/balance") {
- addr := strings.TrimSuffix(strings.TrimPrefix(path, "/api/v1/address/"), "/balance")
- if addr == "" || strings.Contains(addr, "/") {
- return false
- }
- rows, ok := query("SELECT id,balance FROM address WHERE address = ? LIMIT 1", addr)
- if !ok {
- return true
- }
- if len(rows) == 0 {
- jsonError(w, 400, "Could not find address.")
- return true
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Balance any `json:"balance"`
- }{true, struct {
- Confirmed any `json:"confirmed"`
- Unconfirmed int `json:"unconfirmed"`
- }{rows[0]["balance"], 0}})
- return true
- }
- if strings.HasPrefix(path, "/api/v1/charts/blocksize/") {
- period := strings.TrimPrefix(path, "/api/v1/charts/blocksize/")
- if strings.Contains(period, "/") {
- return false
- }
- if r.Method != "GET" {
- jsonError(w, 400, "Invalid HTTP request method.")
- return true
- }
- durations := map[string]time.Duration{"24h": 24 * time.Hour, "72h": 72 * time.Hour, "168h": 168 * time.Hour, "30d": 30 * 24 * time.Hour, "90d": 90 * 24 * time.Hour}
- start := s.now()
- d, valid := durations[period]
- if period == "1y" {
- start = start.AddDate(-1, 0, 0)
- valid = true
- } else {
- start = start.Add(-d)
- }
- if !valid {
- jsonError(w, 400, "Invalid time period specified.")
- return true
- }
- format, layout := "%Y-%m-%d", "2006-01-02"
- if strings.HasSuffix(period, "h") {
- format, layout = "%Y-%m-%d %H:00:00", "2006-01-02 15:00:00"
- }
- q := fmt.Sprintf("SELECT AVG(block_size) AS AvgBlockSize, DATE_FORMAT(FROM_UNIXTIME(block_time), '%s') AS TimePeriod FROM block WHERE DATE_FORMAT(FROM_UNIXTIME(block_time), '%s') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", format, format)
- rows, ok := query(q, start.Format(layout))
- if !ok {
- return true
- }
- var data any = []any{}
- if len(rows) > 0 {
- m := map[string]any{}
- for _, row := range rows {
- m[fmt.Sprint(row["TimePeriod"])] = struct {
- Avg float64 `json:"AvgBlockSize"`
- }{number(row["AvgBlockSize"])}
- }
- data = m
- }
- sendJSON(w, 200, struct {
- Success bool `json:"success"`
- Data any `json:"data"`
- }{true, data})
- return true
- }
- return false
- }
- return true
-}
diff --git a/internal/explorer/server_test.go b/internal/explorer/server_test.go
deleted file mode 100644
index 08e2a3b..0000000
--- a/internal/explorer/server_test.go
+++ /dev/null
@@ -1,163 +0,0 @@
-package explorer
-
-import (
- "context"
- "encoding/json"
- "net/http/httptest"
- "strings"
- "testing"
- "time"
-)
-
-type fakeStore struct {
- rows []Row
- calls []string
- args [][]any
-}
-
-func (f *fakeStore) Query(_ context.Context, q string, a ...any) ([]Row, error) {
- f.calls = append(f.calls, q)
- f.args = append(f.args, a)
- return f.rows, nil
-}
-func TestStatus(t *testing.T) {
- f := &fakeStore{rows: []Row{{"height": int64(25), "difficulty": 1234.567}}}
- s := Server{Store: f}
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/status", nil))
- want := `{"success":true,"status":{"height":25,"difficulty":"1234.57","price":"N\/A","hashrate":"N\/A"}}`
- if w.Body.String() != want {
- t.Fatal(w.Body.String())
- }
- if !strings.Contains(f.calls[0], "ORDER BY height DESC LIMIT 1") {
- t.Fatal(f.calls)
- }
-}
-func TestBalanceBoundParameters(t *testing.T) {
- f := &fakeStore{rows: []Row{}}
- s := Server{Store: f}
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/address/abc/balance", nil))
- if w.Code != 400 || w.Body.String() != `{"error":true,"message":"Could not find address."}` {
- t.Fatal(w.Code, w.Body.String())
- }
- if f.args[0][0] != "abc" || strings.Contains(f.calls[0], "abc") {
- t.Fatal("address must be bound")
- }
-}
-func TestChartValidationAndEmptyShape(t *testing.T) {
- for _, tc := range []struct {
- method, path, want string
- code int
- }{{"POST", "24h", `{"error":true,"message":"Invalid HTTP request method."}`, 400}, {"GET", "2h", `{"error":true,"message":"Invalid time period specified."}`, 400}, {"GET", "24h", `{"success":true,"data":[]}`, 200}} {
- f := &fakeStore{rows: []Row{}}
- s := Server{Store: f, Now: func() time.Time { return time.Date(2026, 11, 2, 13, 45, 0, 0, time.UTC) }}
- w := httptest.NewRecorder()
- s.ServeHTTP(w, httptest.NewRequest(tc.method, "/api/v1/charts/blocksize/"+tc.path, nil))
- if w.Code != tc.code || w.Body.String() != tc.want {
- t.Fatal(w.Code, w.Body.String())
- }
- if tc.code == 400 && len(f.calls) != 0 {
- t.Fatal("invalid request queried DB")
- }
- if tc.code == 200 && f.args[0][0] != "2026-11-01 13:00:00" {
- t.Fatal(f.args)
- }
- }
-}
-func TestPHPJSON(t *testing.T) {
- b, e := phpJSON(struct {
- Text string `json:"text"`
- }{"<é/😀>"})
- if e != nil || string(b) != `{"text":"<\u00e9\/\ud83d\ude00>"}` {
- t.Fatal(string(b), e)
- }
-}
-func TestCacheExpiry(t *testing.T) {
- now := time.Unix(1000, 0)
- c := Cache{Dir: t.TempDir(), Now: func() time.Time { return now }}
- if e := c.Put("inflation", []byte(`{"a":1}`), 10*time.Minute); e != nil {
- t.Fatal(e)
- }
- if b, ok := c.Get("inflation"); !ok || string(b) != `{"a":1}` {
- t.Fatal(string(b), ok)
- }
- now = now.Add(10 * time.Minute)
- if _, ok := c.Get("inflation"); ok {
- t.Fatal("expired hit")
- }
-}
-
-func TestAllTemplatesExecute(t *testing.T) {
- s := Server{Now: func() time.Time { return time.Unix(1700000100, 0) }}
- data := pageData{Tx: Row{"hash": "abc", "created_at": "2026-11-02 11:00:00", "value": 1, "input_count": 1, "output_count": 1}, Address: Row{"address": "abc"}, Claim: Row{"name": "claim", "claim_type": 1, "created_at": "2026-11-02 11:00:00"}, Title: "fixture", Highest: Row{"height": 50, "difficulty": 2}, RecentBlocks: []Row{{"height": 50, "difficulty": 2, "block_time": 1700000000, "block_size": 123, "tx_count": 1}}, RecentClaims: []Row{{"name": "safe ", "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"))
- if !strings.Contains(got, `https://example.com/page `) {
- t.Fatal(got)
- }
- if strings.Contains(got, "
- {{end}}{{define "css"}}{{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/blocks.html b/internal/explorer/templates/blocks.html
deleted file mode 100644
index f2ae335..0000000
--- a/internal/explorer/templates/blocks.html
+++ /dev/null
@@ -1,63 +0,0 @@
-{{define "script"}}
-
-
-
-{{end}}{{define "content"}}{{template "header" .}}
-
-
-
LBRY Blocks
-
-
-
-
-
Block Size Chart
-
-
-
-
-
-
-
All Blocks
-
- {{if gt .NumRecords 0}}
- Showing {{grouped .Begin 0}} - {{grouped .End 0}} of {{grouped .NumRecords 0}} block{{if ne .NumRecords 1}}s{{end}}
- {{end}}
-
-
-
-
- Height
- Difficulty
- Confirmations
- TX Count
- Block Size
- Nonce
- Block Time
-
-
-
-
- {{range $block := .Blocks}}
-
- {{$block.height}}
- {{fixed $block.difficulty 8}}
- {{grouped (add (sub $.Highest.height $block.height) 1) 0}}
- {{$block.tx_count}}
- {{kb $block.block_size}}
- {{$block.nonce}}
- {{date $block.block_time "02 Jan 2006 15:04:05"}} UTC
-
- {{end}}
-
-
-
-
-{{template "pagination" .}}
-{{end}}{{define "css"}} {{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/claim.html b/internal/explorer/templates/claim.html
deleted file mode 100644
index 092f0fa..0000000
--- a/internal/explorer/templates/claim.html
+++ /dev/null
@@ -1,140 +0,0 @@
-{{define "script"}}
-{{end}}{{define "css"}}{{end}}{{define "content"}}{{template "header" .}}{{$claim := .Claim}}
-
-
{{$claim.claim_id}}
-
-
-
- {{if .ClaimIsBlocked}}
-
-
-
- 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
DMCA takedown requests .
-
-
-
- {{else}}
-
-
- {{if showThumbnail $claim}}
-
- {{else}}
-
{{autoThumb $claim}}
- {{end}}
-
-
-
- {{if eq (num $claim.claim_type) 1.0}}
-
Published By
-
- {{end}}
-
-
Created On
-
{{claimDate $claim}} UTC
-
-
Transaction ID
-
-
- {{if eq (num $claim.claim_type) 1.0}}
-
Cost
-
Safe for Work
-
-
{{if claimCost $claim}}{{claimCost $claim}}{{else}}Free{{end}}
-
{{if truth $claim.is_nsfw}}No{{else}}Yes{{end}}
-
-
- {{end}}
-
-
-
-
-
-
-
- {{end}}
-
- {{if .MoreClaims}}
-
-
-
{{if isset $claim "publisher"}}More from the publisher{{else}}Published by this identity{{end}}
-
-
- {{range .Cards}}{{template "claimbox" .}}{{end}}
-
-
-
-
- {{end}}
-
-
-
-{{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/claimbox.html b/internal/explorer/templates/claimbox.html
deleted file mode 100644
index a0b4655..0000000
--- a/internal/explorer/templates/claimbox.html
+++ /dev/null
@@ -1,61 +0,0 @@
-{{define "claimbox"}}{{$claim := .Claim}}
- {{if claimCost .Claim}}
-
{{claimCost .Claim}}
- {{end}}
-
-
-
-
- {{if showThumbnail $claim}}
-
- {{else}}
-
{{autoThumb $claim}}
- {{end}}
-
-
- {{if truth $claim.isBlocked}}
-
-
- 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
DMCA takedown requests
-
-
- {{else}}
-
-
- {{end}}
-
-{{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/claims.html b/internal/explorer/templates/claims.html
deleted file mode 100644
index 48a58ea..0000000
--- a/internal/explorer/templates/claims.html
+++ /dev/null
@@ -1,47 +0,0 @@
-{{define "script"}}
-{{end}}{{define "css"}}{{end}}{{define "content"}}{{template "header" .}}
-
Claims Explorer
-
-
-
- {{range .Cards}}{{template "claimbox" .}}{{end}}
-
-
-
-{{template "pagination" .}}
-
-
-{{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/error400.html b/internal/explorer/templates/error400.html
deleted file mode 100644
index 6a8a39b..0000000
--- a/internal/explorer/templates/error400.html
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
- Error
-
-
-
-
-
-
-
-
-
{{.Message}}
-
- Error:
- The requested address '{{.URL}}' was not found on this server.
-
-
-
-
-
diff --git a/internal/explorer/templates/error500.html b/internal/explorer/templates/error500.html
deleted file mode 100644
index 3793856..0000000
--- a/internal/explorer/templates/error500.html
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
- Error
-
-
-
-
-
-
-
-
-
An Internal Error Has Occurred
-
- Error:
- An Internal Error Has Occurred.
-
-
-
-
-
diff --git a/internal/explorer/templates/find.html b/internal/explorer/templates/find.html
deleted file mode 100644
index eb7bbc7..0000000
--- a/internal/explorer/templates/find.html
+++ /dev/null
@@ -1,49 +0,0 @@
-{{define "script"}}
-{{end}}{{define "css"}}{{end}}{{define "content"}}{{template "header" .}}
-
Search results
-
-
-
- {{if .Claims}}
- {{range .Cards}}{{template "claimbox" .}}{{end}}
- {{else}}
-
No results were found.
- {{end}}
-
-
-
-{{template "pagination" .}}
-{{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/layout.html b/internal/explorer/templates/layout.html
deleted file mode 100644
index c036196..0000000
--- a/internal/explorer/templates/layout.html
+++ /dev/null
@@ -1,67 +0,0 @@
-{{define "layout"}}
-
-
-
-
-
- LBRY Block Explorer • {{.Title}}
-
-
-
-
-
-
-
-
-
-
-
-
- {{if .Analytics}}
-
-
-
- {{end}}
-
-
-
-
- {{template "css" .}}
- {{template "script" .}}
-
-
- {{template "content" .}}
-
-
-
LBRY
-
-
Page took {{elapsed}}ms
-
-
-
-
-{{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/pagination.html b/internal/explorer/templates/pagination.html
deleted file mode 100644
index 8e3f21e..0000000
--- a/internal/explorer/templates/pagination.html
+++ /dev/null
@@ -1,25 +0,0 @@
-{{define "pagination"}}{{with .Pagination}}{{if .Visible}}
-
-{{end}}{{end}}{{end}}
diff --git a/internal/explorer/templates/stats.html b/internal/explorer/templates/stats.html
deleted file mode 100644
index e91a62a..0000000
--- a/internal/explorer/templates/stats.html
+++ /dev/null
@@ -1,59 +0,0 @@
-{{define "script"}}
-
-
-
-
-{{end}}{{define "css"}} {{end}}{{define "content"}}{{template "header" .}}
-
LBRY Stats
-
-
-
-
-
-
-
Mining Inflation Chart
-
-
-
-
-
-
LBRY Rich List (Top 500)
-
-
-
- Rank
- Address
- Balance (LBC)
- Balance (USD)
- First Seen
- % Top 500
-
-
-
-
- {{range $i,$item := .RichList}}
-
- {{add $i 1}}
- {{$item.address}}
- {{if ownedAddress $item.address}}
-
-
-
- {{end}}
- {{if trim $item.Tag}}
-
- {{if trim $item.TagUrl}}
{{$item.Tag}} {{else}}{{$item.Tag}}{{end}}
-
- {{end}}
- {{grouped $item.balance 8}}
- $0.00
- {{date $item.first_seen "02 Jan 2006 15:04:05"}} UTC
-
{{fixed $item.Top500Percent 5}}%
-
- {{end}}
-
-
-
-
-
-{{end}}
\ No newline at end of file
diff --git a/internal/explorer/templates/tx.html b/internal/explorer/templates/tx.html
deleted file mode 100644
index 0200081..0000000
--- a/internal/explorer/templates/tx.html
+++ /dev/null
@@ -1,150 +0,0 @@
-
-
-{{define "script"}}
-
-{{end}}{{define "css"}}{{end}}{{define "content"}}
-
-{{template "header" .}}
-
-
-
LBRY Transaction
- {{.Tx.hash}}
-
-
-
-
-
Time Created
-
{{date .Tx.created_at "2 Jan 2006 15:04:05"}} UTC
-
-
-
-
Block Time
-
{{if not (trim .Tx.transaction_time)}}Not yet confirmed {{else}}{{date .Tx.transaction_time "2 Jan 2006 15:04:05"}} UTC{{end}}
-
- {{confirmationDelay .Tx}}
-
-
-
-
-
-
-
-
-
Amount (LBC)
-
{{amount .Tx.value ","}}
-
-
-
-
Block Height
- {{if not (trim .Tx.block_hash_id)}}
-
Unconf.
- {{else}}
-
- {{end}}
-
-
-
-
Confirmations
-
{{.Confirmations}}
-
-
-
-
Size (bytes)
-
{{grouped .Tx.transaction_size 0}}
-
-
-
-
Inputs
-
{{.Tx.input_count}}
-
-
-
-
Outputs
-
{{.Tx.output_count}}
-
-
-
-
-
-
-
Details
-
-
-
-
-
-
-
-
-
{{.Tx.output_count}} output{{if ne (num .Tx.output_count) 1.0}}s{{end}}
-
- {{if gt (num .Fee) 0.0}}
- Fee {{amount .Fee ","}} LBC
- {{end}}
-
-
- {{range $out := .Outputs}}
-
-
- {{if and $out.Row.Claim (or $out.Row.IsClaim $out.Row.IsSupportClaim $out.Row.IsUpdateClaim)}}
View {{end}}
- {{if $out.Row.IsSupportClaim}}
SUPPORT
{{end}}
- {{if $out.Row.IsUpdateClaim}}
UPDATE
{{end}}
- {{if $out.Row.IsClaim}}
CLAIM
{{end}}
-
-
- {{if not (trim $out.Row.value)}}
-
Incomplete data
- {{else}}{{if $out.Anchor}}
-
- {{end}}
-
{{amount $out.Row.value ","}} LBC to
-
- {{end}}
-
- {{end}}
-
-
-
-{{end}}
\ No newline at end of file
diff --git a/internal/explorer/testdata/boundaries.json b/internal/explorer/testdata/boundaries.json
deleted file mode 100644
index 67d612e..0000000
--- a/internal/explorer/testdata/boundaries.json
+++ /dev/null
@@ -1,161 +0,0 @@
-{
- "queries": [
- {
- "raw": "q=one&q=two",
- "q": "two",
- "page": 0
- },
- {
- "raw": "q[]=hello",
- "q": "Array",
- "page": 0
- },
- {
- "raw": "q=abc%ZZ",
- "q": "abc%ZZ",
- "page": 0
- },
- {
- "raw": "q=%2B%20x",
- "q": "+ x",
- "page": 0
- },
- {
- "raw": "page=9007199254740993",
- "q": "",
- "page": 9007199254740993
- },
- {
- "raw": "page=9223372036854775807",
- "q": "",
- "page": 9223372036854775807
- },
- {
- "raw": "page=9223372036854775808",
- "q": "",
- "page": 9223372036854775807
- },
- {
- "raw": "page=-9223372036854775809",
- "q": "",
- "page": -9223372036854775808
- },
- {
- "raw": "page=1e3",
- "q": "",
- "page": 1000
- },
- {
- "raw": "page[]=2",
- "q": "",
- "page": 1
- },
- {
- "raw": "page=3&page[x]=2",
- "q": "",
- "page": 1
- },
- {
- "raw": "page[x]=2&page=3",
- "q": "",
- "page": 3
- },
- {
- "raw": "page[broken=2",
- "q": "",
- "page": 0
- }
- ],
- "blocked": [
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"data\":[{\"claim_id\":12},{\"claim_id\":\"blocked\"}]}",
- "expected": true
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"data\":[null,\"bad\",{}, {\"claim_id\":\"blocked\"}]}",
- "expected": true
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"data\":[{\"claim_id\":true}]}",
- "expected": true
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"data\":[{\"claim_id\":false}]}",
- "expected": false
- },
- {
- "claim": "",
- "publisher": null,
- "body": "{\"data\":[{}]}",
- "expected": true
- },
- {
- "claim": "0000000000000000000000000000000000000001",
- "publisher": null,
- "body": "{\"data\":[{\"claim_id\":1}]}",
- "expected": true
- },
- {
- "claim": "0000000000000000000000000000000000000001",
- "publisher": null,
- "body": "{\"data\":[{\"claim_id\":\"1\"}]}",
- "expected": true
- },
- {
- "claim": "not-blocked",
- "publisher": "publisher",
- "body": "{\"data\":[{\"claim_id\":\"publisher\"}]}",
- "expected": true
- },
- {
- "claim": "not-blocked",
- "publisher": "0",
- "body": "{\"data\":[{\"claim_id\":\"0\"}]}",
- "expected": false
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"data\":{\"0\":{\"claim_id\":\"blocked\"}}}",
- "expected": false
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "not JSON",
- "expected": false
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"Data\":[{\"claim_id\":\"blocked\"}]}",
- "expected": false
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"data\":[{\"claim_id\":\"\\u0000true\"}]}",
- "expected": false
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body": "{\"data\":[{\"claim_id\":\"blocked\",\"junk\":\"\\ud800\"}]}",
- "expected": false
- },
- {
- "claim": "blocked",
- "publisher": null,
- "body_base64": "eyJkYXRhIjpbeyJjbGFpbV9pZCI6ImJsb2NrZWQiLCJqdW5rIjoi\/yJ9XX0=",
- "expected": false
- }
- ]
-}
diff --git a/internal/explorer/testdata/formatting.json b/internal/explorer/testdata/formatting.json
deleted file mode 100644
index fa3c5a5..0000000
--- a/internal/explorer/testdata/formatting.json
+++ /dev/null
@@ -1,446 +0,0 @@
-{
- "rounds": [
- {
- "value": 1.005,
- "places": 0,
- "expected": "1"
- },
- {
- "value": 1.005,
- "places": 2,
- "expected": "1.01"
- },
- {
- "value": 1.005,
- "places": 5,
- "expected": "1.00500"
- },
- {
- "value": 1.005,
- "places": 8,
- "expected": "1.00500000"
- },
- {
- "value": 1.0049999999999997,
- "places": 0,
- "expected": "1"
- },
- {
- "value": 1.0049999999999997,
- "places": 2,
- "expected": "1.00"
- },
- {
- "value": 1.0049999999999997,
- "places": 5,
- "expected": "1.00500"
- },
- {
- "value": 1.0049999999999997,
- "places": 8,
- "expected": "1.00500000"
- },
- {
- "value": 2.675,
- "places": 0,
- "expected": "3"
- },
- {
- "value": 2.675,
- "places": 2,
- "expected": "2.68"
- },
- {
- "value": 2.675,
- "places": 5,
- "expected": "2.67500"
- },
- {
- "value": 2.675,
- "places": 8,
- "expected": "2.67500000"
- },
- {
- "value": -1.005,
- "places": 0,
- "expected": "-1"
- },
- {
- "value": -1.005,
- "places": 2,
- "expected": "-1.01"
- },
- {
- "value": -1.005,
- "places": 5,
- "expected": "-1.00500"
- },
- {
- "value": -1.005,
- "places": 8,
- "expected": "-1.00500000"
- },
- {
- "value": -0,
- "places": 0,
- "expected": "0"
- },
- {
- "value": -0,
- "places": 2,
- "expected": "0.00"
- },
- {
- "value": -0,
- "places": 5,
- "expected": "0.00000"
- },
- {
- "value": -0,
- "places": 8,
- "expected": "0.00000000"
- },
- {
- "value": -1.0e-9,
- "places": 0,
- "expected": "0"
- },
- {
- "value": -1.0e-9,
- "places": 2,
- "expected": "0.00"
- },
- {
- "value": -1.0e-9,
- "places": 5,
- "expected": "0.00000"
- },
- {
- "value": -1.0e-9,
- "places": 8,
- "expected": "0.00000000"
- },
- {
- "value": 0.285,
- "places": 0,
- "expected": "0"
- },
- {
- "value": 0.285,
- "places": 2,
- "expected": "0.29"
- },
- {
- "value": 0.285,
- "places": 5,
- "expected": "0.28500"
- },
- {
- "value": 0.285,
- "places": 8,
- "expected": "0.28500000"
- },
- {
- "value": 1234567890.1234,
- "places": 0,
- "expected": "1234567890"
- },
- {
- "value": 1234567890.1234,
- "places": 2,
- "expected": "1234567890.12"
- },
- {
- "value": 1234567890.1234,
- "places": 5,
- "expected": "1234567890.12340"
- },
- {
- "value": 1234567890.1234,
- "places": 8,
- "expected": "1234567890.12339997"
- }
- ],
- "json": [
- {
- "value": 1.0e-5,
- "encoded": "1.0e-5"
- },
- {
- "value": 0.0001,
- "encoded": "0.0001"
- },
- {
- "value": 1.0e-7,
- "encoded": "1.0e-7"
- },
- {
- "value": 10000000000000000,
- "encoded": "10000000000000000"
- },
- {
- "value": 1.0e+17,
- "encoded": "1.0e+17"
- },
- {
- "value": 1.0e+20,
- "encoded": "1.0e+20"
- },
- {
- "value": 1.0e+21,
- "encoded": "1.0e+21"
- },
- {
- "value": -0,
- "encoded": "-0"
- },
- {
- "value": 1.2345678901234567,
- "encoded": "1.2345678901234567"
- },
- {
- "value": 9223372036854775807,
- "encoded": "9223372036854775807"
- }
- ],
- "now": 1793620800,
- "dates": [
- {
- "timestamp": 1793620800,
- "ago": "just now",
- "human": "0 seconds ago"
- },
- {
- "timestamp": 1793620799,
- "ago": "1 second ago",
- "human": "1 second ago"
- },
- {
- "timestamp": 1793620798,
- "ago": "2 seconds ago",
- "human": "2 seconds ago"
- },
- {
- "timestamp": 1793620741,
- "ago": "59 seconds ago",
- "human": "59 seconds ago"
- },
- {
- "timestamp": 1793620740,
- "ago": "1 minute ago",
- "human": "1 minute ago"
- },
- {
- "timestamp": 1793620739,
- "ago": "1 minute ago",
- "human": "1 minute ago"
- },
- {
- "timestamp": 1793617201,
- "ago": "59 minutes ago",
- "human": "59 minutes ago"
- },
- {
- "timestamp": 1793617200,
- "ago": "1 hour ago",
- "human": "1 hour ago"
- },
- {
- "timestamp": 1793617199,
- "ago": "1 hour ago",
- "human": "1 hour ago"
- },
- {
- "timestamp": 1793534401,
- "ago": "23 hours, 59 minutes ago",
- "human": "23 hours ago"
- },
- {
- "timestamp": 1793534400,
- "ago": "1 day ago",
- "human": "1 day ago"
- },
- {
- "timestamp": 1793016001,
- "ago": "6 days, 23 hours ago",
- "human": "6 days ago"
- },
- {
- "timestamp": 1793016000,
- "ago": "1 week ago",
- "human": "1 week ago"
- },
- {
- "timestamp": 1790942400,
- "ago": "on 10\/2\/26",
- "human": "1 month ago"
- },
- {
- "timestamp": 1761998400,
- "ago": "on 11\/1\/25",
- "human": "1 year ago"
- },
- {
- "timestamp": 1793620801,
- "ago": "1 second",
- "human": "1 second from now"
- },
- {
- "timestamp": 1793620860,
- "ago": "1 minute",
- "human": "1 minute from now"
- },
- {
- "timestamp": 1793624401,
- "ago": "1 hour",
- "human": "1 hour from now"
- },
- {
- "timestamp": 1793534339,
- "ago": "1 day ago",
- "human": "1 day ago"
- },
- {
- "timestamp": 1793530739,
- "ago": "1 day, 1 hour ago",
- "human": "1 day ago"
- },
- {
- "timestamp": 1793447939,
- "ago": "2 days ago",
- "human": "2 days ago"
- },
- {
- "timestamp": 1791120800,
- "ago": "4 weeks, 1 day ago",
- "human": "4 weeks ago"
- },
- {
- "timestamp": 1793707261,
- "ago": "1 day",
- "human": "1 day from now"
- },
- {
- "timestamp": 1796299200,
- "ago": "on 12\/3\/26",
- "human": "1 month from now"
- },
- {
- "timestamp": 1788540800,
- "ago": "on 9\/4\/26",
- "human": "1 month ago"
- },
- {
- "timestamp": 1785844800,
- "ago": "on 8\/4\/26",
- "human": "2 months ago"
- },
- {
- "timestamp": 1778620800,
- "ago": "on 5\/12\/26",
- "human": "5 months ago"
- },
- {
- "timestamp": 1730548800,
- "ago": "on 11\/2\/24",
- "human": "2 years ago"
- },
- {
- "timestamp": 1856692800,
- "ago": "on 11\/1\/28",
- "human": "1 year from now"
- }
- ],
- "amounts": [
- {
- "value": -0,
- "amount": "0",
- "plain": "0",
- "currency": "0.00"
- },
- {
- "value": -1.0e-9,
- "amount": "0",
- "plain": "0",
- "currency": "-1"
- },
- {
- "value": -1.0e-8,
- "amount": "-0.00000001",
- "plain": "-0.00000001",
- "currency": "-1"
- },
- {
- "value": 1.005,
- "amount": "1.005",
- "plain": "1.005",
- "currency": "1.00"
- },
- {
- "value": 2.675,
- "amount": "2.675",
- "plain": "2.675",
- "currency": "2.67"
- },
- {
- "value": 0,
- "amount": "0",
- "plain": "0",
- "currency": "0.00"
- },
- {
- "value": 1,
- "amount": "1",
- "plain": "1",
- "currency": "1.00"
- },
- {
- "value": 1.01,
- "amount": "1.01",
- "plain": "1.01",
- "currency": "1.01"
- },
- {
- "value": 1234.567891235,
- "amount": "1,234.56789124",
- "plain": "1234.56789124",
- "currency": "1,234.56"
- },
- {
- "value": 5.0e-9,
- "amount": "0.00000001",
- "plain": "0.00000001",
- "currency": "5"
- },
- {
- "value": -1.234,
- "amount": "-1.234",
- "plain": "-1.234",
- "currency": "-1.23"
- },
- {
- "value": 1234567890.1234,
- "amount": "1,234,567,890.12339997",
- "plain": "1234567890.12339997",
- "currency": "1,234,567,890.12"
- },
- {
- "value": "1.0",
- "amount": "1",
- "plain": "1",
- "currency": "1"
- },
- {
- "value": "1.230",
- "amount": "1.23",
- "plain": "1.23",
- "currency": "1.23"
- },
- {
- "value": "123.00000001",
- "amount": "123.00000001",
- "plain": "123.00000001",
- "currency": "123.00"
- }
- ]
-}
diff --git a/internal/explorer/testdata/qr.json b/internal/explorer/testdata/qr.json
deleted file mode 100644
index 195dd1f..0000000
--- a/internal/explorer/testdata/qr.json
+++ /dev/null
@@ -1,344 +0,0 @@
-[
- {
- "data": "lbry:bHW58d37s1hBjj3wPBkn5zpCX3F8ZW3uWf",
- "width": 320,
- "height": 320,
- "sha256": "cbee851be28252d6c21f0a6728b7e4998837d963c0118860a0ebc7ec95ef11bc"
- },
- {
- "data": "HELLO WORLD",
- "width": 320,
- "height": 320,
- "sha256": "0cb3d46135fb7f8206dbc38eb826bc82ebcda986c9d99a73ac85b65cdb911d65"
- },
- {
- "data": "12345678901234567890",
- "width": 320,
- "height": 320,
- "sha256": "c132e611b18b767097c13d5674cd3d5274b1c2a128f5b3a3c3ab6784cf34f45a"
- },
- {
- "data": "éà😀",
- "width": 320,
- "height": 320,
- "sha256": "7541fa7bb1c4cf4572bdd7b06d7347b68376517ff4eab8057a9d152655c0ea6d"
- },
- {
- "data": " hello ",
- "width": 320,
- "height": 320,
- "sha256": "33874446befe1bc452778a57fdce27bdc30dd553ec5c37221110662b36bffb65"
- },
- {
- "data": "漢字",
- "width": 320,
- "height": 320,
- "sha256": "6270e5b5102252e168482d18f31d46d5f55d1df9761649ac316ba263226cd5c3"
- },
- {
- "data": "lbry:b111111111111111111111111111111111",
- "width": 320,
- "height": 320,
- "sha256": "4679bf366ba578fbcbd8c9052a47e7b92dd56ab497d07f64f99317c8f38664c0"
- },
- {
- "data": "a",
- "width": 320,
- "height": 320,
- "sha256": "97403b9b99bff84d4124d0dc4a7a987f76145512a3adf4f1683bc5ea8c4ab366"
- },
- {
- "data": "aa",
- "width": 320,
- "height": 320,
- "sha256": "2da4c046154f8acb3d4e9f8028d5a54aa1e57f46e11438aa7119599fd3ed7870"
- },
- {
- "data": "aaa",
- "width": 320,
- "height": 320,
- "sha256": "426ac076a4fc037e4ab9ac5df0db48da2cccc4cd89bbafb9bae4796d6349543c"
- },
- {
- "data": "aaaa",
- "width": 320,
- "height": 320,
- "sha256": "fb3371adb262f8637a6b53c8fb95cdae04d48158c666112c31f2bbcec4594dea"
- },
- {
- "data": "aaaaa",
- "width": 320,
- "height": 320,
- "sha256": "5e155e39d06dcf87a1b95e09ffb8d3dd9fe8d5ad56c14bcc2365fdb1a653505a"
- },
- {
- "data": "aaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "e5ef2d2c17c92baf377cc3cf4b9d689cdacfef66c0d80249f6b8dad62705b3f2"
- },
- {
- "data": "aaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "f177ffc257468dc7df8b0809d9089f030d68450026cb44eb8edb08fe2a8ca762"
- },
- {
- "data": "aaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "1a1b8e2ea2c76c1a21589a2adcef5c21d4561471f879e1aff063e4662540d535"
- },
- {
- "data": "aaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "534557007b8dbfe98ec5cb88f64852ee1bf4eda851e7c70562a48145ea7b4f89"
- },
- {
- "data": "aaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "8bfc5d621939b39f42891ccd5a4c327db1d94a3e7d3a6f741074fcb2c868f5fb"
- },
- {
- "data": "aaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "a632f1c886938df6d028f5f6dfac5342034172bb649cb897e3d0e6caaa80bae8"
- },
- {
- "data": "aaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "aee804987d756b3607b48c7d7a4f58b9a26d2f21b12de016adcd81fbaef315d7"
- },
- {
- "data": "aaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "39c904fb422b765ded32cfee09eee5c3cd29a56cbb09a3c4f2794060dbc8f8ad"
- },
- {
- "data": "aaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "2bb59fe682c84c7063ca970c3a16787b3c7733a0ada91a93cf2000c54c4837ad"
- },
- {
- "data": "aaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "5c9ed97eda9565478754318969b14262cc277fc67b84cfd553fed2ec54f683ff"
- },
- {
- "data": "aaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "294d2649cecccf4e5c5013b2f3ca8e7c1e130345ea382f987130bd64f561819f"
- },
- {
- "data": "aaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "7688288161fddbe5183db4ef746787487203544d7465ad544b9268a6807d6283"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "d0ab31799eed3686c0b090d258c3f8b9e8253d24cd4989bf668c4c569f34efe2"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "d975297f21eb66162ff46c0641fecc1de914f90ee42d5e3b3c8700a71778a59c"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "25ebe63974078efe094a1397c36f903523db8bb067d7f8aca0643cc5824b7f57"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "1c578f3d9549c77e920cd34428e7310188a0f46a4df3ad632411f78fad91f344"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "f8e6b1a2c8d582707240a6ed4a8468e3522d2dd7ddcf0767ba2bb8c993fcc38e"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "ca230ec35d58478f0e93212b73ec61ecd82fb4e3b5c6a4ed356d3d02ad9221fa"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "8b0249237bba17863da93dc2c9aed2dfe4f4ff408169d083e385cd67fc397b46"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "0ac8e5b1b161f888d8080efd5b26ede0d72f581e750a89ce6d41f5f82f1f499a"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "556c9f4a82b51ffe1011aaeaafb25d1916f943ad73663b517c253740504ae8fc"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "4ba8ac6c007a2a2478f236de7c6618c5245408a164a451b9286556802a480301"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "6b55824c3289f4b9e0cbd346d8cfc2e405fed55b96ffa57ee42d4ac0800400c5"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "b5e5785ec55f16786c5c8014df9b869bad7096fe6bb1ed1ca95cebb036aaa074"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "c638d11ad35d9b02c6a11110e9453878c79eb4ac985b2383732da51dd534e18e"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "95e6282b563e39a9f44f6da621f36b5182f2f22e3023188c04276e6ec52d688f"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "9dcc61f8edaa61b38d82add67779a1417fc725288c8f77d69b8cbfa2b79ab669"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "8193c04c7c0e41df0e24a6bf0d70827ca0585459e5b7fb748406ff4bbde200f9"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "0808a9938c9e6d498d4e7e231765e5ec2446aeebf69fa86e35daa20879302c70"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "6949c9f3998f256e0456c149116907fc81f2910a7b93554217014d866b530d81"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "60c2192de14d4f3aadcf691652506923a9547ddff2e763ac6d0eac88d6646768"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "18e1c93fa5c24b52006ba33f62f4efe36400415f86425b66b367f6051b1191f9"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "c37d5242354a9dd1216089b1f8ee40c9bd8aa357ba233f338e306cf44367fb38"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "623bc8ce6e7b1ab4b72c944073f4a26bb66c435a60fddc68f3f812061fbbfcfe"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "8786c3b9c367a9ee8a1f01c4a7abf13eece24861aff9d078c0d1e05fc1e48f0a"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "e36be2bce2fb23540ccdd0b3162ecb5eda9ecfdd4c4bf8193c63a88c305b813b"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "892aebb3db4fa93574610f39a9e0667494199c072a88b9ee9d09215f9d7bcc65"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "576d515ebeb366c311c7433eb9c91112d0384b5a8c91efca1df3472e521d7ba5"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "2bce4f5094e8ecf7d1fd8e6fe7df6a54ed68a127a60515b197294a533c367181"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "05270729376899bdfbc88c97ee5fd6f5b23e0e939a0b18a79d6f0f8ecc267698"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "2deac4b041d151f824bd7a1be7ae66600feb47d0028483dc90c9321804ab1014"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "1934daf83d858a232fd9c3dc2fe98a1309d7188d9c2d7e966c8ad8a9bd0596f4"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "2cc1c66500bd9aaff4445bc66c9c3ce14e38aaa8ab74a15fe5082de20a62114b"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "b3ed2f2055813010b54aadae876fe5d03124ed46afd154ee938065e0bf365929"
- },
- {
- "data": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
- "width": 320,
- "height": 320,
- "sha256": "68d5d704aa0b1a6f1b464365ffcdf43f0a5a4b7b5073af302d184e8297db8ac2"
- }
-]
diff --git a/internal/explorer/testdata/routes.json b/internal/explorer/testdata/routes.json
deleted file mode 100644
index ce7b67d..0000000
--- a/internal/explorer/testdata/routes.json
+++ /dev/null
@@ -1,458 +0,0 @@
-[
- {
- "path": "/",
- "method": "GET",
- "action": "index",
- "args": []
- },
- {
- "path": "/",
- "method": "POST",
- "action": "index",
- "args": []
- },
- {
- "path": "/",
- "method": "HEAD",
- "action": "index",
- "args": []
- },
- {
- "path": "/api/v1/status",
- "method": "GET",
- "action": "apistatus",
- "args": []
- },
- {
- "path": "/api/v1/status",
- "method": "POST",
- "action": "apistatus",
- "args": []
- },
- {
- "path": "/api/v1/status",
- "method": "HEAD",
- "action": "apistatus",
- "args": []
- },
- {
- "path": "/api/v1/status/",
- "method": "GET",
- "action": "apistatus",
- "args": []
- },
- {
- "path": "/api/v1/status/",
- "method": "POST",
- "action": "apistatus",
- "args": []
- },
- {
- "path": "/api/v1/status/",
- "method": "HEAD",
- "action": "apistatus",
- "args": []
- },
- {
- "path": "/api/v1/status/extra",
- "method": "GET",
- "action": "index",
- "args": [
- "api",
- "v1",
- "status",
- "extra"
- ]
- },
- {
- "path": "/api/v1/status/extra",
- "method": "POST",
- "action": "index",
- "args": [
- "api",
- "v1",
- "status",
- "extra"
- ]
- },
- {
- "path": "/api/v1/status/extra",
- "method": "HEAD",
- "action": "index",
- "args": [
- "api",
- "v1",
- "status",
- "extra"
- ]
- },
- {
- "path": "/blocks",
- "method": "GET",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks",
- "method": "POST",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks",
- "method": "HEAD",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks/",
- "method": "GET",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks/",
- "method": "POST",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks/",
- "method": "HEAD",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks/1/extra",
- "method": "GET",
- "action": "blocks",
- "args": [
- "1",
- "extra"
- ]
- },
- {
- "path": "/blocks/1/extra",
- "method": "POST",
- "action": "blocks",
- "args": [
- "1",
- "extra"
- ]
- },
- {
- "path": "/blocks/1/extra",
- "method": "HEAD",
- "action": "blocks",
- "args": [
- "1",
- "extra"
- ]
- },
- {
- "path": "/blocks/%31",
- "method": "GET",
- "action": "blocks",
- "args": [
- "1"
- ]
- },
- {
- "path": "/blocks/%31",
- "method": "POST",
- "action": "blocks",
- "args": [
- "1"
- ]
- },
- {
- "path": "/blocks/%31",
- "method": "HEAD",
- "action": "blocks",
- "args": [
- "1"
- ]
- },
- {
- "path": "/blocks//",
- "method": "GET",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks//",
- "method": "POST",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/blocks//",
- "method": "HEAD",
- "action": "blocks",
- "args": []
- },
- {
- "path": "/qr/lbry%3A%2F%2Fhello",
- "method": "GET",
- "action": "qr",
- "args": [
- "lbry://hello"
- ]
- },
- {
- "path": "/qr/lbry%3A%2F%2Fhello",
- "method": "POST",
- "action": "qr",
- "args": [
- "lbry://hello"
- ]
- },
- {
- "path": "/qr/lbry%3A%2F%2Fhello",
- "method": "HEAD",
- "action": "qr",
- "args": [
- "lbry://hello"
- ]
- },
- {
- "path": "/qr/lbry://hello",
- "method": "GET",
- "action": "qr",
- "args": [
- "lbry:",
- "hello"
- ]
- },
- {
- "path": "/qr/lbry://hello",
- "method": "POST",
- "action": "qr",
- "args": [
- "lbry:",
- "hello"
- ]
- },
- {
- "path": "/qr/lbry://hello",
- "method": "HEAD",
- "action": "qr",
- "args": [
- "lbry:",
- "hello"
- ]
- },
- {
- "path": "/api/v1/address/abc!/balance",
- "method": "GET",
- "action": "index",
- "args": [
- "api",
- "v1",
- "address",
- "abc!",
- "balance"
- ]
- },
- {
- "path": "/api/v1/address/abc!/balance",
- "method": "POST",
- "action": "index",
- "args": [
- "api",
- "v1",
- "address",
- "abc!",
- "balance"
- ]
- },
- {
- "path": "/api/v1/address/abc!/balance",
- "method": "HEAD",
- "action": "index",
- "args": [
- "api",
- "v1",
- "address",
- "abc!",
- "balance"
- ]
- },
- {
- "path": "/api/v1/address//balance",
- "method": "GET",
- "action": "index",
- "args": [
- "api",
- "v1",
- "address",
- "balance"
- ]
- },
- {
- "path": "/api/v1/address//balance",
- "method": "POST",
- "action": "index",
- "args": [
- "api",
- "v1",
- "address",
- "balance"
- ]
- },
- {
- "path": "/api/v1/address//balance",
- "method": "HEAD",
- "action": "index",
- "args": [
- "api",
- "v1",
- "address",
- "balance"
- ]
- },
- {
- "path": "/api/v1/charts/blocksize/2h",
- "method": "GET",
- "action": "apiblocksize",
- "args": [
- "2h"
- ]
- },
- {
- "path": "/api/v1/charts/blocksize/2h",
- "method": "POST",
- "action": "apiblocksize",
- "args": [
- "2h"
- ]
- },
- {
- "path": "/api/v1/charts/blocksize/2h",
- "method": "HEAD",
- "action": "apiblocksize",
- "args": [
- "2h"
- ]
- },
- {
- "path": "/realtime/",
- "method": "GET",
- "action": "realtime",
- "args": []
- },
- {
- "path": "/realtime/",
- "method": "POST",
- "action": "realtime",
- "args": []
- },
- {
- "path": "/realtime/",
- "method": "HEAD",
- "action": "realtime",
- "args": []
- },
- {
- "path": "/find/",
- "method": "GET",
- "action": "find",
- "args": []
- },
- {
- "path": "/find/",
- "method": "POST",
- "action": "find",
- "args": []
- },
- {
- "path": "/find/",
- "method": "HEAD",
- "action": "find",
- "args": []
- },
- {
- "path": "/stats/",
- "method": "GET",
- "action": "stats",
- "args": []
- },
- {
- "path": "/stats/",
- "method": "POST",
- "action": "stats",
- "args": []
- },
- {
- "path": "/stats/",
- "method": "HEAD",
- "action": "stats",
- "args": []
- },
- {
- "path": "/tx/%2F",
- "method": "GET",
- "action": "tx",
- "args": [
- "/"
- ]
- },
- {
- "path": "/tx/%2F",
- "method": "POST",
- "action": "tx",
- "args": [
- "/"
- ]
- },
- {
- "path": "/tx/%2F",
- "method": "HEAD",
- "action": "tx",
- "args": [
- "/"
- ]
- },
- {
- "path": "//stats",
- "method": "GET",
- "action": "stats",
- "args": []
- },
- {
- "path": "//stats",
- "method": "POST",
- "action": "stats",
- "args": []
- },
- {
- "path": "//stats",
- "method": "HEAD",
- "action": "stats",
- "args": []
- },
- {
- "path": "/claims/0",
- "method": "GET",
- "action": "claims",
- "args": [
- "0"
- ]
- },
- {
- "path": "/claims/0",
- "method": "POST",
- "action": "claims",
- "args": [
- "0"
- ]
- },
- {
- "path": "/claims/0",
- "method": "HEAD",
- "action": "claims",
- "args": [
- "0"
- ]
- }
-]
diff --git a/internal/explorer/time.go b/internal/explorer/time.go
deleted file mode 100644
index dccac4e..0000000
--- a/internal/explorer/time.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package explorer
-
-import (
- "fmt"
- "strings"
- "time"
-)
-
-func unitString(n int, u string) string {
- if n != 1 {
- u += "s"
- }
- return fmt.Sprintf("%d %s", n, u)
-}
-func cakeAgo(t, now time.Time) string {
- diff := int64(now.Unix() - t.Unix())
- future := diff < 0
- if future {
- diff = -diff
- }
- if diff == 0 {
- return "just now"
- }
- if diff > int64(now.AddDate(0, 1, 0).Sub(now)/time.Second) {
- return "on " + t.Format("1/2/06")
- }
- vals := []int{0, 0, 0, 0, 0, 0, 0}
- units := []string{"year", "month", "week", "day", "hour", "minute", "second"}
- if diff >= 604800 {
- past, next := t, now
- if future {
- past, next = now, t
- }
- years := next.Year() - past.Year()
- months := int(next.Month()) + 12*years - int(past.Month())
- if months >= 12 {
- years = months / 12
- months -= years * 12
- }
- if next.Month() < past.Month() && next.Year()-past.Year() == 1 {
- years--
- }
- days := next.Day() - past.Day()
- if days < 0 {
- daysInPast := time.Date(past.Year(), past.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
- daysInFuture := time.Date(next.Year(), next.Month(), 0, 0, 0, 0, 0, time.UTC).Day()
- if !future {
- days = daysInPast - past.Day() + next.Day()
- } else {
- days = daysInFuture - past.Day() + next.Day()
- }
- if next.Month() != past.Month() {
- months--
- }
- }
- if months == 0 && years >= 1 && diff < int64(years)*31536000 {
- months = 11
- years--
- }
- if months >= 12 {
- years++
- months -= 12
- }
- vals[0], vals[1], vals[2], vals[3] = years, months, days/7, days%7
- } else {
- vals[3] = int(diff / 86400)
- diff %= 86400
- vals[4] = int(diff / 3600)
- diff %= 3600
- vals[5] = int(diff / 60)
- vals[6] = int(diff % 60)
- }
- first := 6
- for i, n := range vals {
- if n > 0 {
- first = i
- break
- }
- }
- end := 6
- if first <= 2 {
- end = 3
- } else if first == 3 {
- end = 4
- } else if first <= 5 {
- end = 5
- }
- pieces := []string{}
- for i := 0; i <= end; i++ {
- if vals[i] > 0 {
- pieces = append(pieces, unitString(vals[i], units[i]))
- }
- }
- out := strings.Join(pieces, ", ")
- if out == "" {
- article := "a"
- if units[end] == "hour" {
- article = "an"
- }
- if future {
- return "in about " + article + " " + units[end]
- }
- return "about " + article + " " + units[end] + " ago"
- }
- if !future {
- out += " ago"
- }
- return out
-}
-func humanAgo(t, now time.Time) string {
- past, next := t, now
- future := t.After(now)
- if future {
- past, next = now, t
- }
- years := next.Year() - past.Year()
- months := int(next.Month()) - int(past.Month())
- if months < 0 {
- years--
- months += 12
- }
- days := next.Day() - past.Day()
- if next.Hour()*3600+next.Minute()*60+next.Second() < past.Hour()*3600+past.Minute()*60+past.Second() {
- days--
- }
- if days < 0 {
- months--
- if months < 0 {
- years--
- months += 12
- }
- days += time.Date(past.Year(), past.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
- }
- seconds := int(next.Sub(past) / time.Second)
- n, unit := seconds%60, "second"
- if years > 0 {
- n, unit = years, "year"
- } else if months > 0 {
- n, unit = months, "month"
- } else if days >= 7 {
- n, unit = days/7, "week"
- } else if days > 0 {
- n, unit = days, "day"
- } else if seconds >= 3600 {
- n, unit = seconds/3600, "hour"
- } else if seconds >= 60 {
- n, unit = seconds/60, "minute"
- }
- out := unitString(n, unit)
- if future {
- return out + " from now"
- }
- return out + " ago"
-}
diff --git a/internal/explorer/transaction.go b/internal/explorer/transaction.go
deleted file mode 100644
index ea72389..0000000
--- a/internal/explorer/transaction.go
+++ /dev/null
@@ -1,156 +0,0 @@
-package explorer
-
-import (
- "encoding/json"
- "fmt"
- "math"
- "math/big"
- "net/http"
- "strings"
-)
-
-type ioView struct {
- Row, Address Row
- Source, Anchor bool
-}
-
-func ioViews(rows []Row, addressKey, source string, seen map[string]bool) []ioView {
- out := make([]ioView, 0, len(rows))
- for _, row := range rows {
- address := Row{}
- if list, ok := row[addressKey].([]Row); ok && len(list) > 0 {
- address = list[0]
- }
- name := text(address["address"])
- anchor := false
- if !seen[name] && phpTrim(text(row["value"])) != "" && !truth(row["is_coinbase"]) {
- anchor = true
- seen[name] = true
- }
- out = append(out, ioView{row, address, name != "" && name == source, anchor})
- }
- return out
-}
-func confirmationDelay(tx Row) string {
- diff := int64(number(tx["transaction_time"])) - timestamp(tx["created_at"]).Unix()
- if diff <= 0 {
- return ""
- }
- n := int(diff)
- unit := "second"
- if diff > 60 {
- n = int(math.Ceil(float64(diff) / 60))
- unit = "minute"
- }
- return fmt.Sprintf(" (+%s)", unitString(n, unit))
-}
-func (s *Server) transactionPage(w http.ResponseWriter, r *http.Request) {
- hash := firstArgument(r, "/tx")
- if hash == "" {
- redirect(w, r, "/", 302)
- return
- }
- query := func(q string, args ...any) ([]Row, bool) {
- rows, e := s.Store.Query(r.Context(), q, args...)
- if e != nil {
- internalError(w)
- return nil, false
- }
- return rows, true
- }
- rows, ok := query("SELECT * FROM transaction WHERE hash = ? LIMIT 1", hash)
- if !ok {
- return
- }
- if len(rows) == 0 {
- redirect(w, r, "/", 302)
- return
- }
- tx := rows[0]
- var block Row
- confirmations := int64(0)
- if tx["block_hash_id"] != nil && text(tx["block_hash_id"]) != "MEMPOOL" {
- blocks, ok := query("SELECT confirmations,height FROM block WHERE hash = ? LIMIT 1", tx["block_hash_id"])
- if !ok {
- return
- }
- last, ok := query("SELECT height FROM block ORDER BY height DESC LIMIT 1")
- if !ok {
- return
- }
- if len(blocks) > 0 {
- block = blocks[0]
- if len(last) > 0 {
- confirmations = int64(number(last[0]["height"]) - number(block["height"]) + 1)
- }
- }
- }
- inputs, ok := query("SELECT * FROM input WHERE transaction_id = ? ORDER BY prevout_n ASC", tx["id"])
- if !ok {
- return
- }
- for _, in := range inputs {
- in["input_addresses"] = []Row{}
- if in["input_address_id"] != nil {
- addresses, ok := query("SELECT id,address FROM address WHERE id = ?", in["input_address_id"])
- if !ok {
- return
- }
- in["input_addresses"] = addresses
- }
- }
- outputs, ok := query("SELECT Outputs.*,I.transaction_hash AS spend_input_hash,I.id AS spend_input_id FROM output Outputs LEFT JOIN input I ON I.id = Outputs.spent_by_input_id WHERE Outputs.transaction_id = ? ORDER BY Outputs.vout ASC", tx["id"])
- if !ok {
- return
- }
- for _, out := range outputs {
- script := text(out["script_pub_key_asm"])
- out["IsClaim"] = strings.Contains(script, "CLAIM")
- out["IsSupportClaim"] = strings.Contains(script, "SUPPORT_CLAIM")
- out["IsUpdateClaim"] = strings.Contains(script, "UPDATE_CLAIM")
- claims, ok := query("SELECT id,claim_id,claim_address,vout,transaction_hash_id FROM claim WHERE transaction_hash_id = ? AND vout = ? LIMIT 1", tx["hash"], out["vout"])
- if !ok {
- return
- }
- var claim Row
- if len(claims) > 0 {
- claim = claims[0]
- }
- out["Claim"] = claim
- var list []any
- json.Unmarshal([]byte(text(out["address_list"])), &list)
- if len(list) == 0 && text(claim["claim_address"]) != "" {
- list = append(list, claim["claim_address"])
- }
- out["output_addresses"] = []Row{}
- if len(list) > 0 {
- addresses, ok := query("SELECT address FROM address WHERE address IN ("+placeholders(len(list))+")", list...)
- if !ok {
- return
- }
- out["output_addresses"] = addresses
- }
- }
- totalIn, totalOut := new(big.Rat), new(big.Rat)
- for _, in := range inputs {
- if !validBCString(phpString(in["value"])) {
- internalError(w)
- return
- }
- totalIn = decimal(truncated(new(big.Rat).Add(totalIn, decimal(phpString(in["value"]))), 8))
- }
- for _, out := range outputs {
- if !validBCString(phpString(out["value"])) {
- internalError(w)
- return
- }
- totalOut = decimal(truncated(new(big.Rat).Add(totalOut, decimal(phpString(out["value"]))), 8))
- }
- fee := truncated(new(big.Rat).Sub(totalIn, totalOut), 8)
- seen := map[string]bool{}
- source := queryScalar(r, "address")
- data := pageData{Title: "Transaction ", Tx: tx, Block: block, Confirmations: confirmations, Fee: fee}
- data.Inputs = ioViews(inputs, "input_addresses", source, seen)
- data.Outputs = ioViews(outputs, "output_addresses", source, seen)
- s.render(w, r, "tx", data)
-}
diff --git a/licenses/BaconQrCode.txt b/licenses/BaconQrCode.txt
deleted file mode 100644
index aa22018..0000000
--- a/licenses/BaconQrCode.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-Copyright (c) 2017-present, Ben Scholzen 'DASPRiD'
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/CakePHP.txt b/licenses/CakePHP.txt
deleted file mode 100644
index 291d80e..0000000
--- a/licenses/CakePHP.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2005-present, Cake Software Foundation, Inc. (https://cakefoundation.org)
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/licenses/Endroid.txt b/licenses/Endroid.txt
deleted file mode 100644
index 7f8b69a..0000000
--- a/licenses/Endroid.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright 2025 (c) Jeroen van den Enden
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is furnished
-to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/licenses/Go.txt b/licenses/Go.txt
deleted file mode 100644
index 2a7cf70..0000000
--- a/licenses/Go.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright 2009 The Go Authors.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google LLC nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/PHP-3.01.txt b/licenses/PHP-3.01.txt
deleted file mode 100644
index 0815d7e..0000000
--- a/licenses/PHP-3.01.txt
+++ /dev/null
@@ -1,68 +0,0 @@
---------------------------------------------------------------------
- The PHP License, version 3.01
-Copyright (c) 1999 - 2024 The PHP Group. All rights reserved.
---------------------------------------------------------------------
-
-Redistribution and use in source and binary forms, with or without
-modification, is permitted provided that the following conditions
-are met:
-
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- 2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in
- the documentation and/or other materials provided with the
- distribution.
-
- 3. The name "PHP" must not be used to endorse or promote products
- derived from this software without prior written permission. For
- written permission, please contact group@php.net.
-
- 4. Products derived from this software may not be called "PHP", nor
- may "PHP" appear in their name, without prior written permission
- from group@php.net. You may indicate that your software works in
- conjunction with PHP by saying "Foo for PHP" instead of calling
- it "PHP Foo" or "phpfoo"
-
- 5. The PHP Group may publish revised and/or new versions of the
- license from time to time. Each version will be given a
- distinguishing version number.
- Once covered code has been published under a particular version
- of the license, you may always continue to use it under the terms
- of that version. You may also choose to use such covered code
- under the terms of any subsequent version of the license
- published by the PHP Group. No one other than the PHP Group has
- the right to modify the terms applicable to covered code created
- under this License.
-
- 6. Redistributions of any form whatsoever must retain the following
- acknowledgment:
- "This product includes PHP software, freely available from
- ".
-
-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 .
-
-PHP includes the Zend Engine, freely available at
-.
diff --git a/licenses/filippo.io_edwards25519.txt b/licenses/filippo.io_edwards25519.txt
deleted file mode 100644
index 6a66aea..0000000
--- a/licenses/filippo.io_edwards25519.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2009 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/github.com_go-sql-driver_mysql.txt b/licenses/github.com_go-sql-driver_mysql.txt
deleted file mode 100644
index 14e2f77..0000000
--- a/licenses/github.com_go-sql-driver_mysql.txt
+++ /dev/null
@@ -1,373 +0,0 @@
-Mozilla Public License Version 2.0
-==================================
-
-1. Definitions
---------------
-
-1.1. "Contributor"
- means each individual or legal entity that creates, contributes to
- the creation of, or owns Covered Software.
-
-1.2. "Contributor Version"
- means the combination of the Contributions of others (if any) used
- by a Contributor and that particular Contributor's Contribution.
-
-1.3. "Contribution"
- means Covered Software of a particular Contributor.
-
-1.4. "Covered Software"
- means Source Code Form to which the initial Contributor has attached
- the notice in Exhibit A, the Executable Form of such Source Code
- Form, and Modifications of such Source Code Form, in each case
- including portions thereof.
-
-1.5. "Incompatible With Secondary Licenses"
- means
-
- (a) that the initial Contributor has attached the notice described
- in Exhibit B to the Covered Software; or
-
- (b) that the Covered Software was made available under the terms of
- version 1.1 or earlier of the License, but not also under the
- terms of a Secondary License.
-
-1.6. "Executable Form"
- means any form of the work other than Source Code Form.
-
-1.7. "Larger Work"
- means a work that combines Covered Software with other material, in
- a separate file or files, that is not Covered Software.
-
-1.8. "License"
- means this document.
-
-1.9. "Licensable"
- means having the right to grant, to the maximum extent possible,
- whether at the time of the initial grant or subsequently, any and
- all of the rights conveyed by this License.
-
-1.10. "Modifications"
- means any of the following:
-
- (a) any file in Source Code Form that results from an addition to,
- deletion from, or modification of the contents of Covered
- Software; or
-
- (b) any new file in Source Code Form that contains any Covered
- Software.
-
-1.11. "Patent Claims" of a Contributor
- means any patent claim(s), including without limitation, method,
- process, and apparatus claims, in any patent Licensable by such
- Contributor that would be infringed, but for the grant of the
- License, by the making, using, selling, offering for sale, having
- made, import, or transfer of either its Contributions or its
- Contributor Version.
-
-1.12. "Secondary License"
- means either the GNU General Public License, Version 2.0, the GNU
- Lesser General Public License, Version 2.1, the GNU Affero General
- Public License, Version 3.0, or any later versions of those
- licenses.
-
-1.13. "Source Code Form"
- means the form of the work preferred for making modifications.
-
-1.14. "You" (or "Your")
- means an individual or a legal entity exercising rights under this
- License. For legal entities, "You" includes any entity that
- controls, is controlled by, or is under common control with You. For
- purposes of this definition, "control" means (a) the power, direct
- or indirect, to cause the direction or management of such entity,
- whether by contract or otherwise, or (b) ownership of more than
- fifty percent (50%) of the outstanding shares or beneficial
- ownership of such entity.
-
-2. License Grants and Conditions
---------------------------------
-
-2.1. Grants
-
-Each Contributor hereby grants You a world-wide, royalty-free,
-non-exclusive license:
-
-(a) under intellectual property rights (other than patent or trademark)
- Licensable by such Contributor to use, reproduce, make available,
- modify, display, perform, distribute, and otherwise exploit its
- Contributions, either on an unmodified basis, with Modifications, or
- as part of a Larger Work; and
-
-(b) under Patent Claims of such Contributor to make, use, sell, offer
- for sale, have made, import, and otherwise transfer either its
- Contributions or its Contributor Version.
-
-2.2. Effective Date
-
-The licenses granted in Section 2.1 with respect to any Contribution
-become effective for each Contribution on the date the Contributor first
-distributes such Contribution.
-
-2.3. Limitations on Grant Scope
-
-The licenses granted in this Section 2 are the only rights granted under
-this License. No additional rights or licenses will be implied from the
-distribution or licensing of Covered Software under this License.
-Notwithstanding Section 2.1(b) above, no patent license is granted by a
-Contributor:
-
-(a) for any code that a Contributor has removed from Covered Software;
- or
-
-(b) for infringements caused by: (i) Your and any other third party's
- modifications of Covered Software, or (ii) the combination of its
- Contributions with other software (except as part of its Contributor
- Version); or
-
-(c) under Patent Claims infringed by Covered Software in the absence of
- its Contributions.
-
-This License does not grant any rights in the trademarks, service marks,
-or logos of any Contributor (except as may be necessary to comply with
-the notice requirements in Section 3.4).
-
-2.4. Subsequent Licenses
-
-No Contributor makes additional grants as a result of Your choice to
-distribute the Covered Software under a subsequent version of this
-License (see Section 10.2) or under the terms of a Secondary License (if
-permitted under the terms of Section 3.3).
-
-2.5. Representation
-
-Each Contributor represents that the Contributor believes its
-Contributions are its original creation(s) or it has sufficient rights
-to grant the rights to its Contributions conveyed by this License.
-
-2.6. Fair Use
-
-This License is not intended to limit any rights You have under
-applicable copyright doctrines of fair use, fair dealing, or other
-equivalents.
-
-2.7. Conditions
-
-Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
-in Section 2.1.
-
-3. Responsibilities
--------------------
-
-3.1. Distribution of Source Form
-
-All distribution of Covered Software in Source Code Form, including any
-Modifications that You create or to which You contribute, must be under
-the terms of this License. You must inform recipients that the Source
-Code Form of the Covered Software is governed by the terms of this
-License, and how they can obtain a copy of this License. You may not
-attempt to alter or restrict the recipients' rights in the Source Code
-Form.
-
-3.2. Distribution of Executable Form
-
-If You distribute Covered Software in Executable Form then:
-
-(a) such Covered Software must also be made available in Source Code
- Form, as described in Section 3.1, and You must inform recipients of
- the Executable Form how they can obtain a copy of such Source Code
- Form by reasonable means in a timely manner, at a charge no more
- than the cost of distribution to the recipient; and
-
-(b) You may distribute such Executable Form under the terms of this
- License, or sublicense it under different terms, provided that the
- license for the Executable Form does not attempt to limit or alter
- the recipients' rights in the Source Code Form under this License.
-
-3.3. Distribution of a Larger Work
-
-You may create and distribute a Larger Work under terms of Your choice,
-provided that You also comply with the requirements of this License for
-the Covered Software. If the Larger Work is a combination of Covered
-Software with a work governed by one or more Secondary Licenses, and the
-Covered Software is not Incompatible With Secondary Licenses, this
-License permits You to additionally distribute such Covered Software
-under the terms of such Secondary License(s), so that the recipient of
-the Larger Work may, at their option, further distribute the Covered
-Software under the terms of either this License or such Secondary
-License(s).
-
-3.4. Notices
-
-You may not remove or alter the substance of any license notices
-(including copyright notices, patent notices, disclaimers of warranty,
-or limitations of liability) contained within the Source Code Form of
-the Covered Software, except that You may alter any license notices to
-the extent required to remedy known factual inaccuracies.
-
-3.5. Application of Additional Terms
-
-You may choose to offer, and to charge a fee for, warranty, support,
-indemnity or liability obligations to one or more recipients of Covered
-Software. However, You may do so only on Your own behalf, and not on
-behalf of any Contributor. You must make it absolutely clear that any
-such warranty, support, indemnity, or liability obligation is offered by
-You alone, and You hereby agree to indemnify every Contributor for any
-liability incurred by such Contributor as a result of warranty, support,
-indemnity or liability terms You offer. You may include additional
-disclaimers of warranty and limitations of liability specific to any
-jurisdiction.
-
-4. Inability to Comply Due to Statute or Regulation
----------------------------------------------------
-
-If it is impossible for You to comply with any of the terms of this
-License with respect to some or all of the Covered Software due to
-statute, judicial order, or regulation then You must: (a) comply with
-the terms of this License to the maximum extent possible; and (b)
-describe the limitations and the code they affect. Such description must
-be placed in a text file included with all distributions of the Covered
-Software under this License. Except to the extent prohibited by statute
-or regulation, such description must be sufficiently detailed for a
-recipient of ordinary skill to be able to understand it.
-
-5. Termination
---------------
-
-5.1. The rights granted under this License will terminate automatically
-if You fail to comply with any of its terms. However, if You become
-compliant, then the rights granted under this License from a particular
-Contributor are reinstated (a) provisionally, unless and until such
-Contributor explicitly and finally terminates Your grants, and (b) on an
-ongoing basis, if such Contributor fails to notify You of the
-non-compliance by some reasonable means prior to 60 days after You have
-come back into compliance. Moreover, Your grants from a particular
-Contributor are reinstated on an ongoing basis if such Contributor
-notifies You of the non-compliance by some reasonable means, this is the
-first time You have received notice of non-compliance with this License
-from such Contributor, and You become compliant prior to 30 days after
-Your receipt of the notice.
-
-5.2. If You initiate litigation against any entity by asserting a patent
-infringement claim (excluding declaratory judgment actions,
-counter-claims, and cross-claims) alleging that a Contributor Version
-directly or indirectly infringes any patent, then the rights granted to
-You by any and all Contributors for the Covered Software under Section
-2.1 of this License shall terminate.
-
-5.3. In the event of termination under Sections 5.1 or 5.2 above, all
-end user license agreements (excluding distributors and resellers) which
-have been validly granted by You or Your distributors under this License
-prior to termination shall survive termination.
-
-************************************************************************
-* *
-* 6. Disclaimer of Warranty *
-* ------------------------- *
-* *
-* Covered Software is provided under this License on an "as is" *
-* basis, without warranty of any kind, either expressed, implied, or *
-* statutory, including, without limitation, warranties that the *
-* Covered Software is free of defects, merchantable, fit for a *
-* particular purpose or non-infringing. The entire risk as to the *
-* quality and performance of the Covered Software is with You. *
-* Should any Covered Software prove defective in any respect, You *
-* (not any Contributor) assume the cost of any necessary servicing, *
-* repair, or correction. This disclaimer of warranty constitutes an *
-* essential part of this License. No use of any Covered Software is *
-* authorized under this License except under this disclaimer. *
-* *
-************************************************************************
-
-************************************************************************
-* *
-* 7. Limitation of Liability *
-* -------------------------- *
-* *
-* Under no circumstances and under no legal theory, whether tort *
-* (including negligence), contract, or otherwise, shall any *
-* Contributor, or anyone who distributes Covered Software as *
-* permitted above, be liable to You for any direct, indirect, *
-* special, incidental, or consequential damages of any character *
-* including, without limitation, damages for lost profits, loss of *
-* goodwill, work stoppage, computer failure or malfunction, or any *
-* and all other commercial damages or losses, even if such party *
-* shall have been informed of the possibility of such damages. This *
-* limitation of liability shall not apply to liability for death or *
-* personal injury resulting from such party's negligence to the *
-* extent applicable law prohibits such limitation. Some *
-* jurisdictions do not allow the exclusion or limitation of *
-* incidental or consequential damages, so this exclusion and *
-* limitation may not apply to You. *
-* *
-************************************************************************
-
-8. Litigation
--------------
-
-Any litigation relating to this License may be brought only in the
-courts of a jurisdiction where the defendant maintains its principal
-place of business and such litigation shall be governed by laws of that
-jurisdiction, without reference to its conflict-of-law provisions.
-Nothing in this Section shall prevent a party's ability to bring
-cross-claims or counter-claims.
-
-9. Miscellaneous
-----------------
-
-This License represents the complete agreement concerning the subject
-matter hereof. If any provision of this License is held to be
-unenforceable, such provision shall be reformed only to the extent
-necessary to make it enforceable. Any law or regulation which provides
-that the language of a contract shall be construed against the drafter
-shall not be used to construe this License against a Contributor.
-
-10. Versions of the License
----------------------------
-
-10.1. New Versions
-
-Mozilla Foundation is the license steward. Except as provided in Section
-10.3, no one other than the license steward has the right to modify or
-publish new versions of this License. Each version will be given a
-distinguishing version number.
-
-10.2. Effect of New Versions
-
-You may distribute the Covered Software under the terms of the version
-of the License under which You originally received the Covered Software,
-or under the terms of any subsequent version published by the license
-steward.
-
-10.3. Modified Versions
-
-If you create software not governed by this License, and you want to
-create a new license for such software, you may create and use a
-modified version of this License if you rename the license and remove
-any references to the name of the license steward (except to note that
-such modified license differs from this License).
-
-10.4. Distributing Source Code Form that is Incompatible With Secondary
-Licenses
-
-If You choose to distribute Source Code Form that is Incompatible With
-Secondary Licenses under the terms of this version of the License, the
-notice described in Exhibit B of this License must be attached.
-
-Exhibit A - Source Code Form License Notice
--------------------------------------------
-
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-If it is not possible or desirable to put the notice in a particular
-file, then You may include the notice in a location (such as a LICENSE
-file in a relevant directory) where a recipient would be likely to look
-for such a notice.
-
-You may add additional accurate notices of copyright ownership.
-
-Exhibit B - "Incompatible With Secondary Licenses" Notice
----------------------------------------------------------
-
- This Source Code Form is "Incompatible With Secondary Licenses", as
- defined by the Mozilla Public License, v. 2.0.
diff --git a/licenses/github.com_makiuchi-d_gozxing.txt b/licenses/github.com_makiuchi-d_gozxing.txt
deleted file mode 100644
index 25fc076..0000000
--- a/licenses/github.com_makiuchi-d_gozxing.txt
+++ /dev/null
@@ -1,230 +0,0 @@
-MIT License
-
-Copyright (c) 2018 Daisuke MAKIUCHI (MakKi; makki_d)
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
-
-========================================================================
-Original zxing License
-Copyright 2007-2018 ZXing authors
-========================================================================
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
diff --git a/licenses/golang.org_x_text.txt b/licenses/golang.org_x_text.txt
deleted file mode 100644
index 6a66aea..0000000
--- a/licenses/golang.org_x_text.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2009 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/licenses/golang.org_x_xerrors.txt b/licenses/golang.org_x_xerrors.txt
deleted file mode 100644
index e4a47e1..0000000
--- a/licenses/golang.org_x_xerrors.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2019 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
new file mode 100644
index 0000000..77c784b
--- /dev/null
+++ b/phpunit.xml.dist
@@ -0,0 +1,40 @@
+
+
+
+
+
+
+
+
+
+
+ ./tests/TestCase
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ./src/
+ ./plugins/*/src/
+
+
+
diff --git a/sql/dbg.sql b/sql/dbg.sql
new file mode 100644
index 0000000..0039ded
--- /dev/null
+++ b/sql/dbg.sql
@@ -0,0 +1,52 @@
+DELIMITER //
+
+CREATE PROCEDURE DeleteBlock (
+ IN BlockId BIGINT
+)
+BEGIN
+ START TRANSACTION;
+
+ DELETE FROM InputsAddresses WHERE InputId IN (
+ SELECT Id FROM Inputs WHERE TransactionId IN (
+ SELECT Id FROM Transactions WHERE BlockHash IN (
+ SELECT Hash FROM Blocks WHERE Id = BlockId
+ )
+ )
+ );
+
+ DELETE FROM OutputsAddresses WHERE OutputId IN (
+ SELECT Id FROM Outputs WHERE TransactionId IN (
+ SELECT Id FROM Transactions WHERE BlockHash IN (
+ SELECT Hash FROM Blocks WHERE Id = BlockId
+ )
+ )
+ );
+
+ DELETE FROM Inputs WHERE TransactionId IN (
+ SELECT Id FROM Transactions WHERE BlockHash IN (
+ SELECT Hash FROM Blocks WHERE Id = BlockId
+ )
+ );
+
+ DELETE FROM Outputs WHERE TransactionId IN (
+ SELECT Id FROM Transactions WHERE BlockHash IN (
+ SELECT Hash FROM Blocks WHERE Id = BlockId
+ )
+ );
+
+ DELETE FROM TransactionsAddresses WHERE TransactionId IN (
+ SELECT Id FROM Transactions WHERE BlockHash IN (
+ SELECT Hash FROM Blocks WHERE Id = BlockId
+ )
+ );
+
+ DELETE FROM Transactions WHERE BlockHash IN (
+ SELECT Hash FROM Blocks WHERE Id = BlockId
+ );
+
+ DELETE FROM Blocks WHERE Id = BlockId;
+
+ COMMIT;
+END//
+
+DELIMITER ;
\ No newline at end of file
diff --git a/sql/lbryexplorer.aux.sql b/sql/lbryexplorer.aux.sql
new file mode 100644
index 0000000..f44f853
--- /dev/null
+++ b/sql/lbryexplorer.aux.sql
@@ -0,0 +1,18 @@
+-- Address Tagging TX tracking
+CREATE TABLE `TagAddressRequests`
+(
+ `Id` SERIAL,
+ `Address` VARCHAR(35) NOT NULL,
+ `VerificationAmount` DECIMAL(18,8) NOT NULL,
+ `Tag` VARCHAR(30) NOT NULL,
+ `TagUrl` VARCHAR(200) NULL,
+ `IsVerified` TINYINT(1) DEFAULT 0 NOT NULL,
+ `Created` DATETIME NOT NULL,
+ `Modified` DATETIME NOT NULL,
+ PRIMARY KEY `PK_TagAddressRequest` (`Id`),
+ UNIQUE KEY `Idx_TagAddressRequestId` (`Address`, `VerificationAmount`),
+ INDEX `Idx_TagAddressRequestVerificationAmount` (`VerificationAmount`),
+ INDEX `Idx_TagAddressRequestAddress` (`Address`),
+ INDEX `Idx_TagAddressRequestCreated` (`Created`),
+ INDEX `Idx_TagAddressRequestModified` (`Modified`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
\ No newline at end of file
diff --git a/sql/lbryexplorer.ddl.sql b/sql/lbryexplorer.ddl.sql
new file mode 100644
index 0000000..f624d4c
--- /dev/null
+++ b/sql/lbryexplorer.ddl.sql
@@ -0,0 +1,239 @@
+l--DROP DATABASE IF EXISTS lbry;
+CREATE DATABASE lbry DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
+USE lbry;
+
+CREATE TABLE `Blocks`
+(
+ `Id` SERIAL,
+
+ `Bits` VARCHAR(20) NOT NULL,
+ `Chainwork` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `Confirmations` INTEGER UNSIGNED NOT NULL,
+ `Difficulty` DECIMAL(18,8) NOT NULL,
+ `Hash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL ,
+ `Height` BIGINT UNSIGNED NOT NULL,
+ `MedianTime` BIGINT UNSIGNED NOT NULL,
+ `MerkleRoot` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `NameClaimRoot` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `Nonce` BIGINT UNSIGNED NOT NULL,
+ `PreviousBlockHash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `NextBlockHash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `BlockSize` BIGINT UNSIGNED NOT NULL,
+ `Target` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `BlockTime` BIGINT UNSIGNED NOT NULL,
+ `Version` BIGINT UNSIGNED NOT NULL,
+ `VersionHex` VARCHAR(10) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `TransactionHashes` TEXT,
+ `TransactionsProcessed` TINYINT(1) DEFAULT 0 NOT NULL,
+
+ `Created` DATETIME NOT NULL,
+ `Modified` DATETIME NOT NULL,
+
+ PRIMARY KEY `PK_Block` (`Id`),
+ UNIQUE KEY `Idx_BlockHash` (`Hash`),
+ CONSTRAINT `Cnt_TransactionHashesValidJson` CHECK(`TransactionHashes` IS NULL OR JSON_VALID(`TransactionHashes`)),
+ INDEX `Idx_BlockHeight` (`Height`),
+ INDEX `Idx_BlockTime` (`BlockTime`),
+ INDEX `Idx_MedianTime` (`MedianTime`),
+ INDEX `Idx_PreviousBlockHash` (`PreviousBlockHash`),
+ INDEX `Idx_BlockCreated` (`Created`),
+ INDEX `Idx_BlockModified` (`Modified`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `Transactions`
+(
+ `Id` SERIAL,
+ `BlockHash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `InputCount` INTEGER UNSIGNED NOT NULL,
+ `OutputCount` INTEGER UNSIGNED NOT NULL,
+ `Value` DECIMAL(18,8) NOT NULL,
+ `Fee` DECIMAL(18,8) DEFAULT 0 NOT NULL,
+ `TransactionTime` BIGINT UNSIGNED,
+ `TransactionSize` BIGINT UNSIGNED NOT NULL,
+ `Hash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `Version` INTEGER NOT NULL,
+ `LockTime` INTEGER UNSIGNED NOT NULL,
+ `Raw` TEXT,
+ `Created` DATETIME NOT NULL,
+ `Modified` DATETIME NOT NULL,
+ `CreatedTime` INTEGER UNSIGNED DEFAULT UNIX_TIMESTAMP() NOT NULL,
+ PRIMARY KEY `PK_Transaction` (`Id`),
+ FOREIGN KEY `FK_TransactionBlockHash` (`BlockHash`) REFERENCES `Blocks` (`Hash`),
+ UNIQUE KEY `Idx_TransactionHash` (`Hash`),
+ INDEX `Idx_TransactionTime` (`TransactionTime`),
+ INDEX `Idx_TransactionCreatedTime` (`CreatedTime`),
+ INDEX `Idx_TransactionCreated` (`Created`),
+ INDEX `Idx_TransactionModified` (`Modified`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `Addresses`
+(
+ `Id` SERIAL,
+ `Address` VARCHAR(40) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `FirstSeen` DATETIME,
+ `TotalReceived` DECIMAL(18,8) DEFAULT 0 NOT NULL,
+ `TotalSent` DECIMAL(18,8) DEFAULT 0 NOT NULL,
+ `Balance` DECIMAL(18,8) AS (`TotalReceived` - `TotalSent`) PERSISTENT,
+ `Tag` VARCHAR(30) NOT NULL,
+ `TagUrl` VARCHAR(200),
+ `Created` DATETIME NOT NULL,
+ `Modified` DATETIME NOT NULL,
+ PRIMARY KEY `PK_Address` (`Id`),
+ UNIQUE KEY `Idx_AddressAddress` (`Address`),
+ UNIQUE KEY `Idx_AddressTag` (`Tag`),
+ INDEX `Idx_AddressTotalReceived` (`TotalReceived`),
+ INDEX `Idx_AddressTotalSent` (`TotalSent`),
+ INDEX `Idx_AddressBalance` (`Balance`),
+ INDEX `Idx_AddressCreated` (`Created`),
+ INDEX `Idx_AddressModified` (`Modified`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `Inputs`
+(
+ `Id` SERIAL,
+ `TransactionId` BIGINT UNSIGNED NOT NULL,
+ `TransactionHash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `AddressId` BIGINT UNSIGNED,
+ `IsCoinbase` TINYINT(1) DEFAULT 0 NOT NULL,
+ `Coinbase` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `PrevoutHash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `PrevoutN` INTEGER UNSIGNED,
+ `PrevoutSpendUpdated` TINYINT(1) DEFAULT 0 NOT NULL,
+ `Sequence` INTEGER UNSIGNED,
+ `Value` DECIMAL(18,8),
+ `ScriptSigAsm` TEXT CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `ScriptSigHex` TEXT CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `Created` DATETIME NOT NULL,
+ `Modified` DATETIME NOT NULL,
+ PRIMARY KEY `PK_Input` (`Id`),
+ FOREIGN KEY `FK_InputAddress` (`AddressId`) REFERENCES `Addresses` (`Id`),
+ FOREIGN KEY `FK_InputTransaction` (`TransactionId`) REFERENCES `Transactions` (`Id`),
+ INDEX `Idx_InputValue` (`Value`),
+ INDEX `Idx_PrevoutHash` (`PrevoutHash`),
+ INDEX `Idx_InputCreated` (`Created`),
+ INDEX `Idx_InputModified` (`Modified`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `InputsAddresses`
+(
+ `InputId` BIGINT UNSIGNED NOT NULL,
+ `AddressId` BIGINT UNSIGNED NOT NULL,
+ PRIMARY KEY `PK_InputAddress` (`InputId`, `AddressId`),
+ FOREIGN KEY `Idx_InputsAddressesInput` (`InputId`) REFERENCES `Inputs` (`Id`),
+ FOREIGN KEY `Idx_InputsAddressesAddress` (`AddressId`) REFERENCES `Addresses` (`Id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `Outputs`
+(
+ `Id` SERIAL,
+ `TransactionId` BIGINT UNSIGNED NOT NULL,
+ `Value` DECIMAL(18,8),
+ `Vout` INTEGER UNSIGNED,
+ `Type` VARCHAR(20) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `ScriptPubKeyAsm` TEXT CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `ScriptPubKeyHex` TEXT CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `RequiredSignatures` INTEGER UNSIGNED,
+ `Hash160` VARCHAR(50) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `Addresses` TEXT CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `IsSpent` TINYINT(1) DEFAULT 0 NOT NULL,
+ `SpentByInputId` BIGINT UNSIGNED,
+ `Created` DATETIME NOT NULL,
+ `Modified` DATETIME NOT NULL,
+ PRIMARY KEY `PK_Output` (`Id`),
+ FOREIGN KEY `FK_OutputTransaction` (`TransactionId`) REFERENCES `Transactions` (`Id`),
+ FOREIGN KEY `FK_OutputSpentByInput` (`SpentByInputId`) REFERENCES `Inputs` (`Id`),
+ CONSTRAINT `Cnt_AddressesValidJson` CHECK(`Addresses` IS NULL OR JSON_VALID(`Addresses`)),
+ INDEX `Idx_OutputValue` (`Value`),
+ INDEX `Idx_OuptutCreated` (`Created`),
+ INDEX `Idx_OutputModified` (`Modified`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `OutputsAddresses`
+(
+ `OutputId` BIGINT UNSIGNED NOT NULL,
+ `AddressId` BIGINT UNSIGNED NOT NULL,
+ PRIMARY KEY `PK_OutputAddress` (`OutputId`, `AddressId`),
+ FOREIGN KEY `Idx_OutputsAddressesOutput` (`OutputId`) REFERENCES `Outputs` (`Id`),
+ FOREIGN KEY `Idx_OutputsAddressesAddress` (`AddressId`) REFERENCES `Addresses` (`Id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `TransactionsAddresses`
+(
+ `TransactionId` BIGINT UNSIGNED NOT NULL,
+ `AddressId` BIGINT UNSIGNED NOT NULL,
+ `DebitAmount` DECIMAL(18,8) DEFAULT 0 NOT NULL COMMENT 'Sum of the inputs to this address for the tx',
+ `CreditAmount` DECIMAL(18,8) DEFAULT 0 NOT NULL COMMENT 'Sum of the outputs to this address for the tx',
+ `LatestTransactionTime` DATETIME DEFAULT UTC_TIMESTAMP() NOT NULL,
+ PRIMARY KEY `PK_TransactionAddress` (`TransactionId`, `AddressId`),
+ FOREIGN KEY `Idx_TransactionsAddressesTransaction` (`TransactionId`) REFERENCES `Transactions` (`Id`),
+ FOREIGN KEY `Idx_TransactionsAddressesAddress` (`AddressId`) REFERENCES `Addresses` (`Id`),
+ INDEX `Idx_TransactionsAddressesLatestTransactionTime` (`LatestTransactionTime`),
+ INDEX `Idx_TransactionsAddressesDebit` (`DebitAmount`),
+ INDEX `Idx_TransactionsAddressesCredit` (`CreditAmount`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `Claims`
+(
+ `Id` SERIAL,
+ `TransactionHash` VARCHAR(70) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `Vout` INTEGER UNSIGNED NOT NULL,
+ `Name` VARCHAR(1024) NOT NULL,
+ `ClaimId` CHAR(40) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+ `ClaimType` TINYINT(1) NOT NULL, -- 1 - CertificateType, 2 - StreamType
+ `PublisherId` CHAR(40) CHARACTER SET latin1 COLLATE latin1_general_ci COMMENT 'references a ClaimId with CertificateType',
+ `PublisherSig` VARCHAR(200) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `Certificate` TEXT,
+ `TransactionTime` INTEGER UNSIGNED,
+ `Version` VARCHAR(10) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
+
+ -- Additional fields for easy indexing of stream types
+ `Author` VARCHAR(512),
+ `Description` MEDIUMTEXT,
+ `ContentType` VARCHAR(162) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `IsNSFW` TINYINT(1) DEFAULT 0 NOT NULL,
+ `Language` VARCHAR(20) CHARACTER SET latin1 COLLATE latin1_general_ci,
+ `ThumbnailUrl` TEXT,
+ `Title` TEXT,
+ `Fee` DECIMAL(18,8) DEFAULT 0 NOT NULL,
+ `FeeCurrency` CHAR(3),
+ `IsFiltered` TINYINT(1) DEFAULT 0 NOT NULL,
+
+ `Created` DATETIME NOT NULL,
+ `Modified` DATETIME NOT NULL,
+ PRIMARY KEY `PK_Claim` (`Id`),
+ FOREIGN KEY `FK_ClaimTransaction` (`TransactionHash`) REFERENCES `Transactions` (`Hash`),
+ FOREIGN KEY `FK_ClaimPublisher` (`PublisherId`) REFERENCES `Claims` (`ClaimId`),
+ UNIQUE KEY `Idx_ClaimUnique` (`TransactionHash`, `Vout`, `ClaimId`),
+ CONSTRAINT `Cnt_ClaimCertificate` CHECK(`Certificate` IS NULL OR JSON_VALID(`Certificate`)), -- certificate type
+ INDEX `Idx_Claim` (`ClaimId`),
+ INDEX `Idx_ClaimTransactionTime` (`TransactionTime`),
+ INDEX `Idx_ClaimCreated` (`Created`),
+ INDEX `Idx_ClaimModified` (`Modified`),
+
+ INDEX `Idx_ClaimAuthor` (`Author`(191)),
+ INDEX `Idx_ClaimContentType` (`ContentType`),
+ INDEX `Idx_ClaimLanguage` (`Language`),
+ INDEX `Idx_ClaimTitle` (`Title`(191))
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `ClaimStreams`
+(
+ `Id` BIGINT UNSIGNED NOT NULL,
+ `Stream` MEDIUMTEXT NOT NULL,
+ PRIMARY KEY `PK_ClaimStream` (`Id`),
+ FOREIGN KEY `PK_ClaimStreamClaim` (`Id`) REFERENCES `Claims` (`Id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+CREATE TABLE `PriceHistory`
+(
+ `Id` SERIAL,
+ `BTC` DECIMAL(18,8) DEFAULT 0 NOT NULL,
+ `USD` DECIMAL(18,2) DEFAULT 0 NOT NULL,
+ `Created` DATETIME NOT NULL,
+ PRIMARY KEY `PK_PriceHistory` (`Id`),
+ UNIQUE KEY `Idx_PriceHistoryCreated` (`Created`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;
+
+ALTER TABLE Claims ADD UNIQUE KEY `Idx_ClaimUnique` (`TransactionHash`, `Vout`, `ClaimId`);
+ALTER TABLE Addresses ADD COLUMN `Balance` DECIMAL(18,8) AS (`TotalReceived` - `TotalSent`) PERSISTENT AFTER `TotalSent`;
+ALTER TABLE Addresses ADD INDEX `Idx_AddressBalance` (`Balance`);
\ No newline at end of file
diff --git a/src/Application.php b/src/Application.php
new file mode 100644
index 0000000..9c5999b
--- /dev/null
+++ b/src/Application.php
@@ -0,0 +1,52 @@
+add(ErrorHandlerMiddleware::class)
+
+ // Handle plugin/theme assets like CakePHP normally does.
+ ->add(AssetMiddleware::class)
+
+ // Apply routing
+ ->add(RoutingMiddleware::class);
+
+ return $middleware;
+ }
+}
diff --git a/src/Console/Installer.php b/src/Console/Installer.php
new file mode 100644
index 0000000..0756096
--- /dev/null
+++ b/src/Console/Installer.php
@@ -0,0 +1,195 @@
+getIO();
+
+ $rootDir = dirname(dirname(__DIR__));
+
+ static::createAppConfig($rootDir, $io);
+ static::createWritableDirectories($rootDir, $io);
+
+ // ask if the permissions should be changed
+ if ($io->isInteractive()) {
+ $validator = function ($arg) {
+ if (in_array($arg, ['Y', 'y', 'N', 'n'])) {
+ return $arg;
+ }
+ throw new Exception('This is not a valid answer. Please choose Y or n.');
+ };
+ $setFolderPermissions = $io->askAndValidate(
+ 'Set Folder Permissions ? (Default to Y) [Y,n ]? ',
+ $validator,
+ 10,
+ 'Y'
+ );
+
+ if (in_array($setFolderPermissions, ['Y', 'y'])) {
+ static::setFolderPermissions($rootDir, $io);
+ }
+ } else {
+ static::setFolderPermissions($rootDir, $io);
+ }
+
+ static::setSecuritySalt($rootDir, $io);
+
+ if (class_exists('\Cake\Codeception\Console\Installer')) {
+ \Cake\Codeception\Console\Installer::customizeCodeceptionBinary($event);
+ }
+ }
+
+ /**
+ * Create the config/app.php file if it does not exist.
+ *
+ * @param string $dir The application's root directory.
+ * @param \Composer\IO\IOInterface $io IO interface to write to console.
+ * @return void
+ */
+ public static function createAppConfig($dir, $io)
+ {
+ $appConfig = $dir . '/config/app.php';
+ $defaultConfig = $dir . '/config/app.default.php';
+ if (!file_exists($appConfig)) {
+ copy($defaultConfig, $appConfig);
+ $io->write('Created `config/app.php` file');
+ }
+ }
+
+ /**
+ * Create the `logs` and `tmp` directories.
+ *
+ * @param string $dir The application's root directory.
+ * @param \Composer\IO\IOInterface $io IO interface to write to console.
+ * @return void
+ */
+ public static function createWritableDirectories($dir, $io)
+ {
+ $paths = [
+ 'logs',
+ 'tmp',
+ 'tmp/cache',
+ 'tmp/cache/models',
+ 'tmp/cache/persistent',
+ 'tmp/cache/views',
+ 'tmp/sessions',
+ 'tmp/tests'
+ ];
+
+ foreach ($paths as $path) {
+ $path = $dir . '/' . $path;
+ if (!file_exists($path)) {
+ mkdir($path);
+ $io->write('Created `' . $path . '` directory');
+ }
+ }
+ }
+
+ /**
+ * Set globally writable permissions on the "tmp" and "logs" directory.
+ *
+ * This is not the most secure default, but it gets people up and running quickly.
+ *
+ * @param string $dir The application's root directory.
+ * @param \Composer\IO\IOInterface $io IO interface to write to console.
+ * @return void
+ */
+ public static function setFolderPermissions($dir, $io)
+ {
+ // Change the permissions on a path and output the results.
+ $changePerms = function ($path, $perms, $io) {
+ // Get permission bits from stat(2) result.
+ $currentPerms = fileperms($path) & 0777;
+ if (($currentPerms & $perms) == $perms) {
+ return;
+ }
+
+ $res = chmod($path, $currentPerms | $perms);
+ if ($res) {
+ $io->write('Permissions set on ' . $path);
+ } else {
+ $io->write('Failed to set permissions on ' . $path);
+ }
+ };
+
+ $walker = function ($dir, $perms, $io) use (&$walker, $changePerms) {
+ $files = array_diff(scandir($dir), ['.', '..']);
+ foreach ($files as $file) {
+ $path = $dir . '/' . $file;
+
+ if (!is_dir($path)) {
+ continue;
+ }
+
+ $changePerms($path, $perms, $io);
+ $walker($path, $perms, $io);
+ }
+ };
+
+ $worldWritable = bindec('0000000111');
+ $walker($dir . '/tmp', $worldWritable, $io);
+ $changePerms($dir . '/tmp', $worldWritable, $io);
+ $changePerms($dir . '/logs', $worldWritable, $io);
+ }
+
+ /**
+ * Set the security.salt value in the application's config file.
+ *
+ * @param string $dir The application's root directory.
+ * @param \Composer\IO\IOInterface $io IO interface to write to console.
+ * @return void
+ */
+ public static function setSecuritySalt($dir, $io)
+ {
+ $config = $dir . '/config/app.php';
+ $content = file_get_contents($config);
+
+ $newKey = hash('sha256', Security::randomBytes(64));
+ $content = str_replace('__SALT__', $newKey, $content, $count);
+
+ if ($count == 0) {
+ $io->write('No Security.salt placeholder to replace.');
+
+ return;
+ }
+
+ $result = file_put_contents($config, $content);
+ if ($result) {
+ $io->write('Updated Security.salt value in config/app.php');
+
+ return;
+ }
+ $io->write('Unable to update Security.salt value.');
+ }
+}
diff --git a/src/Controller/AppController.php b/src/Controller/AppController.php
new file mode 100644
index 0000000..5cbfeca
--- /dev/null
+++ b/src/Controller/AppController.php
@@ -0,0 +1,80 @@
+loadComponent('Security');`
+ *
+ * @return void
+ */
+ public function initialize()
+ {
+ parent::initialize();
+
+ $this->loadComponent('RequestHandler');
+ $this->loadComponent('Flash');
+
+ /*
+ * Enable the following components for recommended CakePHP security settings.
+ * see http://book.cakephp.org/3.0/en/controllers/components/security.html
+ */
+ //$this->loadComponent('Security');
+ //$this->loadComponent('Csrf');
+ }
+
+ /**
+ * Before render callback.
+ *
+ * @param \Cake\Event\Event $event The beforeRender event.
+ * @return \Cake\Network\Response|null|void
+ */
+ public function beforeRender(Event $event)
+ {
+ if (!array_key_exists('_serialize', $this->viewVars) &&
+ in_array($this->response->type(), ['application/json', 'application/xml'])
+ ) {
+ $this->set('_serialize', true);
+ }
+ }
+
+ protected function _jsonResponse($object = [], $statusCode = null)
+ {
+ $this->response->statusCode($statusCode);
+ $this->response->type('json');
+ $this->response->body(json_encode($object));
+ }
+
+ protected function _jsonError($message, $statusCode = null) {
+ return $this->_jsonResponse(['error' => true, 'message' => $message], $statusCode);
+ }
+}
diff --git a/src/Controller/ClaimsController.php b/src/Controller/ClaimsController.php
new file mode 100644
index 0000000..aa3efc7
--- /dev/null
+++ b/src/Controller/ClaimsController.php
@@ -0,0 +1,61 @@
+autoRender = false;
+ $this->loadModel('Claims');
+
+ $pageLimit = 48;
+ $beforeId = intval($this->request->query('before'));
+ $afterId = intval($this->request->query('after'));
+ $sort = trim($this->request->query('sort'));
+ $nsfw = trim($this->request->query('nsfw'));
+ switch ($sort) {
+ case 'popular':
+ // TODO: sort by upvote/downvote score
+ break;
+ case 'random':
+ $order = ['RAND()' => 'ASC'];
+ break;
+ case 'oldest':
+ $order = ['Claims.Created' => 'ASC'];
+ break;
+ case 'newest':
+ default:
+ $order = ['Claims.Created' => 'DESC'];
+ break;
+ }
+
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute('SELECT COUNT(Id) AS Total FROM Claims WHERE ThumbnailUrl IS NOT NULL AND LENGTH(TRIM(ThumbnailUrl)) > 0');
+ $count = $stmt->fetch(\PDO::FETCH_OBJ);
+ $numClaims = $count->Total;
+
+ if ($beforeId < 0) {
+ $beforeId = 0;
+ }
+
+ $conditions = ['Claims.ThumbnailUrl IS NOT' => null, 'LENGTH(TRIM(Claims.ThumbnailUrl)) >' => 0, 'Claims.IsFiltered <>' => 1];
+ if ($afterId > 0) {
+ $conditions['Claims.Id >'] = $afterId;
+ } else if ($beforeId) {
+ $conditions['Claims.Id <'] = $beforeId;
+ }
+
+ if ($nsfw !== 'true') {
+ $conditions['Claims.IsNSFW <>'] = 1;
+ }
+
+ $claims = $this->Claims->find()->contain(['Stream', 'Publisher' => ['fields' => ['Name']]])->distinct(['Claims.ClaimId'])->where($conditions)->
+ limit($pageLimit)->order($order)->toArray();
+
+ return $this->_jsonResponse(['success' => true, 'claims' => $claims, 'total' => (int) $numClaims]);
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Controller/ErrorController.php b/src/Controller/ErrorController.php
new file mode 100644
index 0000000..cf0ebd5
--- /dev/null
+++ b/src/Controller/ErrorController.php
@@ -0,0 +1,68 @@
+loadComponent('RequestHandler');
+ }
+
+ /**
+ * beforeFilter callback.
+ *
+ * @param \Cake\Event\Event $event Event.
+ * @return \Cake\Network\Response|null|void
+ */
+ public function beforeFilter(Event $event)
+ {
+ }
+
+ /**
+ * beforeRender callback.
+ *
+ * @param \Cake\Event\Event $event Event.
+ * @return \Cake\Network\Response|null|void
+ */
+ public function beforeRender(Event $event)
+ {
+ parent::beforeRender($event);
+
+ $this->viewBuilder()->setTemplatePath('Error');
+ }
+
+ /**
+ * afterFilter callback.
+ *
+ * @param \Cake\Event\Event $event Event.
+ * @return \Cake\Network\Response|null|void
+ */
+ public function afterFilter(Event $event)
+ {
+ }
+}
diff --git a/src/Controller/MainController.php b/src/Controller/MainController.php
new file mode 100644
index 0000000..f68cd44
--- /dev/null
+++ b/src/Controller/MainController.php
@@ -0,0 +1,919 @@
+redis = new \Predis\Client('tcp://127.0.0.1:6379');
+ try {
+ $this->redis->info('mem');
+ } catch (\Predis\Connection\ConnectionException $e) {
+ $this->redis = null;
+ }
+ }
+
+ protected function _getLatestPrice() {
+ $now = new \DateTime('now', new \DateTimeZone('UTC'));
+ $priceInfo = new \stdClass();
+ $priceInfo->time = $now->format('c');
+
+ $shouldRefreshPrice = false;
+ if (!$this->redis) {
+ $shouldRefreshPrice = true;
+ } else {
+ if (!$this->redis->exists(self::lbcPriceKey)) {
+ $shouldRefreshPrice = true;
+ } else {
+ $priceInfo = json_decode($this->redis->get(self::lbcPriceKey));
+ $lastPriceDt = new \DateTime($priceInfo->time);
+ $diff = $now->diff($lastPriceDt);
+ $diffMinutes = $diff->i;
+ if ($diffMinutes >= 15 || $priceInfo->price == 0) { // 15 minutes (or if the price is 0)
+ $shouldRefreshPrice = true;
+ }
+ }
+ }
+
+ if ($shouldRefreshPrice) {
+ $btrxjson = json_decode(self::curl_get(self::bittrexMarketUrl));
+ $blckjson = json_decode(self::curl_get(self::blockchainTickerUrl));
+
+ if ($btrxjson->success) {
+ $onelbc = $btrxjson->result->Bid;
+ $lbcPrice = 0;
+ if (isset($blckjson->USD)) {
+ $lbcPrice = $onelbc * $blckjson->USD->buy;
+ if ($lbcPrice > 0) {
+ $priceInfo->price = number_format($lbcPrice, 2, '.', '');
+ $priceInfo->time = $now->format('c');
+ if ($this->redis) {
+ $this->redis->set(self::lbcPriceKey, json_encode($priceInfo));
+ }
+ }
+ }
+ }
+ }
+
+ $lbcUsdPrice = (isset($priceInfo->price) && ($priceInfo->price > 0)) ? '$' . $priceInfo->price : 'N/A';
+ return $lbcUsdPrice;
+ }
+
+ public function index() {
+ $this->loadModel('Blocks');
+ $this->loadModel('Claims');
+
+ $lbcUsdPrice = $this->_getLatestPrice();
+ $this->set('lbcUsdPrice', $lbcUsdPrice);
+
+ $blocks = $this->Blocks->find()->select(['Chainwork', 'Confirmations', 'Difficulty', 'Hash', 'Height', 'TransactionHashes', 'BlockTime', 'BlockSize'])->
+ order(['Height' => 'desc'])->limit(6)->toArray();
+ for ($i = 0; $i < count($blocks); $i++) {
+ $tx_hashes = json_decode($blocks[$i]->TransactionHashes);
+ $blocks[$i]->TransactionCount = count($tx_hashes);
+ }
+
+ // hash rate
+ $hashRate = $this->_formatHashRate($this->_gethashrate());
+
+ // recent claims
+ $claims = $this->Claims->find()->select(['TransactionHash', 'Name', 'Vout', 'ClaimId', 'ClaimType', 'Author', 'Title', 'Description', 'ContentType',
+ 'IsNSFW', 'Language', 'ThumbnailUrl', 'Created'])->
+ distinct(['Claims.ClaimId'])->
+ contain(['Publisher' => ['fields' => ['Name']]])->order(['Claims.Created' => 'DESC'])->limit(5)->toArray();
+
+ $this->set('recentBlocks', $blocks);
+ $this->set('recentClaims', $claims);
+ $this->set('hashRate', $hashRate);
+ }
+
+ public function claims($id = null) {
+ $this->loadModel('Claims');
+ $this->loadModel('Transactions');
+
+ $canConvert = false;
+ $priceInfo = json_decode($this->redis->get(self::lbcPriceKey));
+ if (isset($priceInfo->price)) {
+ $canConvert = true;
+ }
+
+ if (!$id) {
+ // paginate claims
+ $offset = 0;
+ $pageLimit = 96;
+ $page = intval($this->request->query('page'));
+
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute('SELECT COUNT(Id) AS Total FROM Claims');
+ $count = $stmt->fetch(\PDO::FETCH_OBJ);
+ $numClaims = $count->Total;
+
+ $numPages = ceil($numClaims / $pageLimit);
+ if ($page < 1) {
+ $page = 1;
+ }
+ if ($page > $numPages) {
+ $page = $numPages;
+ }
+
+ $offset = ($page - 1) * $pageLimit;
+ $claims = $this->Claims->find()->distinct(['Claims.ClaimId'])->contain(['Stream', 'Publisher' => ['fields' => ['Name']]])->order(['Claims.Created' => 'DESC'])->offset($offset)->limit($pageLimit)->toArray();
+ for ($i = 0; $i < count($claims); $i++) {
+ if ($canConvert && $claims[$i]->Fee > 0 && $claims[$i]->FeeCurrency == 'USD') {
+ $claims[$i]->Price = $claims[$i]->Fee / $priceInfo->price;
+ }
+
+ if (isset($claims[$i]->Stream)) {
+ $json = json_decode($claims[$i]->Stream->Stream);
+ if (isset($json->metadata->license)) {
+ $claims[$i]->License = $json->metadata->license;
+ }
+ if (isset($json->metadata->licenseUrl)) {
+ $claims[$i]->LicenseUrl = $json->metadata->licenseUrl;
+ }
+ }
+ }
+
+ $this->set('pageLimit', $pageLimit);
+ $this->set('numPages', $numPages);
+ $this->set('numRecords', $numClaims);
+ $this->set('currentPage', $page);
+ $this->set('claims', $claims);
+ } else {
+ $claim = $this->Claims->find()->contain(['Stream', 'Publisher' => ['fields' => ['ClaimId', 'Name']]])->where(['Claims.ClaimId' => $id])->order(['Claims.Created' => 'DESC'])->first();
+ if (!$claim) {
+ return $this->redirect('/');
+ }
+
+ if ($canConvert && $claim->Fee > 0 && $claim->FeeCurrency == 'USD') {
+ $claim->Price = $claim->Fee / $priceInfo->price;
+ }
+
+ if (isset($claim->Stream)) {
+ $json = json_decode($claim->Stream->Stream);
+ if (isset($json->metadata->license)) {
+ $claim->License = $json->metadata->license;
+ }
+ if (isset($json->metadata->licenseUrl)) {
+ $claim->LicenseUrl = $json->metadata->licenseUrl;
+ }
+ }
+
+ $moreClaims = [];
+ if (isset($claim->Publisher) || $claim->ClaimType == 1) {
+ // find more claims for the publisher
+ $moreClaims = $this->Claims->find()->contain(['Stream', 'Publisher' => ['fields' => ['Name']]])->
+ where(['Claims.ClaimType' => 2, 'Claims.Id <>' => $claim->Id, 'Claims.PublisherId' => isset($claim->Publisher) ? $claim->Publisher->ClaimId : $claim->ClaimId])->
+ limit(9)->order(['Claims.Fee' => 'DESC', 'RAND()' => 'DESC'])->toArray();
+ for ($i = 0; $i < count($moreClaims); $i++) {
+ if ($canConvert && $moreClaims[$i]->Fee > 0 && $moreClaims[$i]->FeeCurrency == 'USD') {
+ $moreClaims[$i]->Price = $moreClaims[$i]->Fee / $priceInfo->price;
+ }
+
+ if (isset($moreClaims[$i]->Stream)) {
+ $json = json_decode($moreClaims[$i]->Stream->Stream);
+ if (isset($json->metadata->license)) {
+ $moreClaims[$i]->License = $json->metadata->license;
+ }
+ if (isset($json->metadata->licenseUrl)) {
+ $moreClaims[$i]->LicenseUrl = $json->metadata->licenseUrl;
+ }
+ }
+ }
+ }
+
+ $this->set('claim', $claim);
+ $this->set('moreClaims', $moreClaims);
+ }
+ }
+
+ public function realtime() {
+ $this->loadModel('Blocks');
+ $this->loadModel('Transactions');
+
+ // load 10 blocks and transactions
+ $conn = ConnectionManager::get('default');
+ $blocks = $this->Blocks->find()->select(['Height', 'BlockTime', 'TransactionHashes'])->order(['Height' => 'desc'])->limit(10)->toArray();
+ for ($i = 0; $i < count($blocks); $i++) {
+ $tx_hashes = json_decode($blocks[$i]->TransactionHashes);
+ $blocks[$i]->TransactionCount = count($tx_hashes);
+ }
+
+ $stmt = $conn->execute('SELECT T.Hash, T.InputCount, T.OutputCount, T.Value, IFNULL(T.TransactionTime, T.CreatedTime) AS TxTime ' .
+ 'FROM Transactions T ORDER BY CreatedTime DESC LIMIT 10');
+ $txs = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ $this->set('blocks', $blocks);
+ $this->set('txs', $txs);
+ }
+
+ public function apiblocksize($timePeriod = '24h') {
+ $this->autoRender = false;
+
+ if (!$this->request->is('get')) {
+ return $this->_jsonError('Invalid HTTP request method.', 400);
+ }
+
+ $validPeriods = ['24h', '72h', '168h', '30d', '90d', '1y'];
+ if (!in_array($timePeriod, $validPeriods)) {
+ return $this->_jsonError('Invalid time period specified.', 400);
+ }
+
+ $isHourly = (strpos($timePeriod, 'h') !== false);
+ $now = new \DateTime('now', new \DateTimeZone('UTC'));
+ $dateFormat = $isHourly ? 'Y-m-d H:00:00' : 'Y-m-d';
+ $sqlDateFormat = $isHourly ? '%Y-%m-%d %H:00:00' : '%Y-%m-%d';
+ $intervalPrefix = $isHourly ? 'PT' : 'P';
+ $start = $now->sub(new \DateInterval($intervalPrefix . strtoupper($timePeriod)));
+
+ $resultSet = [];
+
+ $conn = ConnectionManager::get('default');
+
+ // get avg block sizes for the time period
+ $stmt = $conn->execute("SELECT AVG(BlockSize) AS AvgBlockSize, DATE_FORMAT(FROM_UNIXTIME(BlockTime), '$sqlDateFormat') AS TimePeriod " .
+ "FROM Blocks WHERE DATE_FORMAT(FROM_UNIXTIME(BlockTime), '$sqlDateFormat') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", [$start->format($dateFormat)]);
+ $avgBlockSizes = $stmt->fetchAll(\PDO::FETCH_OBJ);
+ foreach ($avgBlockSizes as $size) {
+ if (!isset($resultSet[$size->TimePeriod])) {
+ $resultSet[$size->TimePeriod] = [];
+ }
+ $resultSet[$size->TimePeriod]['AvgBlockSize'] = (float) $size->AvgBlockSize;
+ }
+
+ // get avg prices
+ $stmt = $conn->execute("SELECT AVG(USD) AS AvgUSD, DATE_FORMAT(Created, '$sqlDateFormat') AS TimePeriod " .
+ "FROM PriceHistory WHERE DATE_FORMAT(Created, '$sqlDateFormat') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", [$start->format($dateFormat)]);
+ $avgPrices = $stmt->fetchAll(\PDO::FETCH_OBJ);
+ foreach ($avgPrices as $price) {
+ if (!isset($resultSet[$price->TimePeriod])) {
+ $resultSet[$price->TimePeriod] = [];
+ }
+ $resultSet[$price->TimePeriod]['AvgUSD'] = (float) $price->AvgUSD;
+ }
+
+ return $this->_jsonResponse(['success' => true, 'data' => $resultSet]);
+ }
+
+ public function apirealtimeblocks() {
+ // load 10 blocks
+ $this->autoRender = false;
+ $this->loadModel('Blocks');
+ $blocks = $this->Blocks->find()->select(['Height', 'BlockTime', 'TransactionHashes'])->order(['Height' => 'desc'])->limit(10)->toArray();
+ for ($i = 0; $i < count($blocks); $i++) {
+ $tx_hashes = json_decode($blocks[$i]->TransactionHashes);
+ $blocks[$i]->TransactionCount = count($tx_hashes);
+ unset($blocks[$i]->TransactionHashes);
+ }
+
+ $this->_jsonResponse(['success' => true, 'blocks' => $blocks]);
+ }
+
+ public function apirealtimetx() {
+ // load 10 transactions
+ $this->autoRender = false;
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute('SELECT T.Hash, T.InputCount, T.OutputCount, T.Value, IFNULL(T.TransactionTime, T.CreatedTime) AS TxTime ' .
+ 'FROM Transactions T ORDER BY CreatedTime DESC LIMIT 10');
+ $txs = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ $this->_jsonResponse(['success' => true, 'txs' => $txs]);
+ }
+
+ protected function _formatHashRate($value) {
+ if ($value === 'N/A') {
+ return $value;
+ }
+
+ /*if ($value > 1000000000000) {
+ return number_format( $value / 1000000000000, 2, '.', '' ) . ' TH';
+ }*/
+ if ($value > 1000000000) {
+ return number_format( $value / 1000000000, 2, '.', '' ) . ' GH/s';
+ }
+ if ($value > 1000000) {
+ return number_format( $value / 1000000, 2, '.', '' ) . ' MH/s';
+ }
+ if ($value > 1000) {
+ return number_format( $value / 1000, 2, '.', '' ) . ' KH/s';
+ }
+
+ return number_format($value) . ' H/s';
+ }
+
+ public function find() {
+ $criteria = $this->request->query('q');
+ if ($criteria === null || strlen(trim($criteria)) == 0) {
+ return $this->redirect('/');
+ }
+
+ $this->loadModel('Blocks');
+ $this->loadModel('Claims');
+ $this->loadModel('Addresses');
+ $this->loadModel('Transactions');
+
+ if (is_numeric($criteria)) {
+ $height = (int) $criteria;
+ $block = $this->Blocks->find()->select(['Id'])->where(['Height' => $height])->first();
+ if ($block) {
+ return $this->redirect('/blocks/' . $height);
+ }
+ } else if (strlen(trim($criteria)) === 34) {
+ // Address
+ $address = $this->Addresses->find()->select(['Id', 'Address'])->where(['Address' => $criteria])->first();
+ if ($address) {
+ return $this->redirect('/address/' . $address->Address);
+ }
+ } else if (strlen(trim($criteria)) === 40) {
+ // Claim ID
+ $claim = $this->Claims->find()->select(['ClaimId'])->where(['ClaimId' => $criteria])->first();
+ if ($claim) {
+ return $this->redirect('/claim/' . $claim->ClaimId);
+ }
+ } else if (strlen(trim($criteria)) === 64) { // block or tx hash
+ // Try block hash first
+ $block = $this->Blocks->find()->select(['Height'])->where(['Hash' => $criteria])->first();
+ if ($block) {
+ return $this->redirect('/blocks/' . $block->Height);
+ } else {
+ $tx = $this->Transactions->find()->select(['Hash'])->where(['Hash' => $criteria])->first();
+ if ($tx) {
+ return $this->redirect('/tx/' . $tx->Hash);
+ }
+ }
+ } else {
+ // finally, try exact claim name match
+ $claim = $this->Claims->find()->select(['ClaimId'])->where(['Name' => $criteria])->first();
+ if ($claim) {
+ return $this->redirect('/claims/' . $claim->ClaimId);
+ }
+ }
+
+ // Not found, redirect to index
+ return $this->redirect('/');
+ }
+
+ public function blocks($height = null) {
+ $this->loadModel('Blocks');
+
+ if ($height === null) {
+ // paginate blocks
+ $offset = 0;
+ $pageLimit = 50;
+ $page = intval($this->request->query('page'));
+
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute('SELECT COUNT(Id) AS Total FROM Blocks');
+ $count = $stmt->fetch(\PDO::FETCH_OBJ);
+ $numBlocks = $count->Total;
+
+ $numPages = ceil($numBlocks / $pageLimit);
+ if ($page < 1) {
+ $page = 1;
+ }
+ if ($page > $numPages) {
+ $page = $numPages;
+ }
+
+ $offset = ($page - 1) * $pageLimit;
+ $blocks = $this->Blocks->find()->offset($offset)->limit($pageLimit)->order(['Height' => 'DESC'])->toArray();
+ $this->set('blocks', $blocks);
+ $this->set('pageLimit', $pageLimit);
+ $this->set('numPages', $numPages);
+ $this->set('numRecords', $numBlocks);
+ $this->set('currentPage', $page);
+ } else {
+ $this->loadModel('Transactions');
+ $height = intval($height);
+ if ($height < 0) {
+ return $this->redirect('/');
+ }
+
+ $block = $this->Blocks->find()->where(['Height' => $height])->first();
+ if (!$block) {
+ return $this->redirect('/');
+ }
+
+ try {
+ // update the block confirmations
+ $req = ['method' => 'getblock', 'params' => [$block->Hash]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $rpc_block = $json->result;
+ if (isset($rpc_block->confirmations)) {
+ $block->Confirmations = $rpc_block->confirmations;
+ $conn = ConnectionManager::get('default');
+ $conn->execute('UPDATE Blocks SET Confirmations = ? WHERE Id = ?', [$rpc_block->confirmations, $block->Id]);
+ }
+ } catch (\Exception $e) {
+ // try again next time
+ }
+
+ // Get the basic block transaction info
+ $txs = $this->Transactions->find()->select(['InputCount', 'OutputCount', 'Hash', 'Value', 'Version'])->where(['BlockHash' => $block->Hash])->toArray();
+
+ $this->set('block', $block);
+ $this->set('blockTxs', $txs);
+ }
+ }
+
+ public function tx($hash = null) {
+ $this->loadModel('Blocks');
+ $this->loadModel('Transactions');
+ $this->loadModel('Inputs');
+ $this->loadModel('Outputs');
+ $sourceAddress = $this->request->query('address');
+
+ $tx = $this->Transactions->find()->select(
+ ['Id', 'BlockHash', 'InputCount', 'OutputCount', 'Hash', 'Value', 'TransactionTime', 'TransactionSize', 'Created', 'Version', 'LockTime', 'Raw'])->where(['Hash' => $hash])->first();
+ if (!$tx) {
+ return $this->redirect('/');
+ }
+
+ if ($tx->TransactionSize == 0) {
+ $tx->TransactionSize = (strlen($tx->Raw) / 2);
+ $conn = ConnectionManager::get('default');
+ $conn->execute('UPDATE Transactions SET TransactionSize = ? WHERE Id = ?', [$tx->TransactionSize, $tx->Id]);
+ }
+
+ $block = $this->Blocks->find()->select(['Confirmations', 'Height'])->where(['Hash' => $tx->BlockHash])->first();
+ $inputs = $this->Inputs->find()->contain(['InputAddresses'])->where(['TransactionId' => $tx->Id])->order(['PrevoutN' => 'asc'])->toArray();
+ $outputs = $this->Outputs->find()->contain(['OutputAddresses', 'SpendInput' => ['fields' => ['Id', 'TransactionHash', 'PrevoutN', 'PrevoutHash']]])->where(['Outputs.TransactionId' => $tx->Id])->order(['Vout' => 'asc'])->toArray();
+ for ($i = 0; $i < count($outputs); $i++) {
+ $outputs[$i]->IsClaim = (strpos($outputs[$i]->ScriptPubKeyAsm, 'CLAIM') > -1);
+ $outputs[$i]->IsSupportClaim = (strpos($outputs[$i]->ScriptPubKeyAsm, 'SUPPORT_CLAIM') > -1);
+ $outputs[$i]->IsUpdateClaim = (strpos($outputs[$i]->ScriptPubKeyAsm, 'UPDATE_CLAIM') > -1);
+ }
+
+ $totalIn = 0;
+ $totalOut = 0;
+ $fee = 0;
+ foreach ($inputs as $in) {
+ $totalIn = bcadd($totalIn, $in->Value, 8);
+ }
+ foreach ($outputs as $out) {
+ $totalOut = bcadd($totalOut, $out->Value, 8);
+ }
+ $fee = bcsub($totalIn, $totalOut, 8);
+
+ $this->set('tx', $tx);
+ $this->set('block', $block);
+ $this->set('confirmations', $block ? number_format($block->Confirmations, 0, '', ',') : '0');
+ $this->set('fee', $fee);
+ $this->set('inputs', $inputs);
+ $this->set('outputs', $outputs);
+ $this->set('sourceAddress', $sourceAddress);
+ }
+
+ public function stats() {
+ $this->loadModel('Addresses');
+
+ // exclude bHW58d37s1hBjj3wPBkn5zpCX3F8ZW3uWf (genesis block)
+ $richList = $this->Addresses->find()->where(['Address <>' => 'bHW58d37s1hBjj3wPBkn5zpCX3F8ZW3uWf'])->order(['Balance' => 'DESC'])->limit(500)->toArray();
+
+ $priceRate = 0;
+ $priceInfo = json_decode($this->redis->get(self::lbcPriceKey));
+ if (isset($priceInfo->price)) {
+ $priceRate = $priceInfo->price;
+ }
+
+ // calculate percentages
+ $totalBalance = 0;
+ $maxBalance = 0;
+ $minBalance = 0;
+ foreach ($richList as $item) {
+ $totalBalance = bcadd($totalBalance, $item->Balance, 8);
+ $minBalance = $minBalance == 0 ? $item->Balance : min($minBalance, $item->Balance);
+ $maxBalance = max($maxBalance, $item->Balance);
+ }
+ for ($i = 0; $i < count($richList); $i++) {
+ $item = $richList[$i];
+ $percentage = bcdiv($item->Balance, $totalBalance, 8) * 100;
+ $richList[$i]->Top500Percent = $percentage;
+ $richList[$i]->MinMaxPercent = bcdiv($item->Balance, $maxBalance, 8) * 100;
+ }
+
+ $this->set('richList', $richList);
+ $this->set('rate', $priceRate);
+ }
+
+ public function address($addr = null) {
+ set_time_limit(0);
+
+ $this->loadModel('Addresses');
+ $this->loadModel('Transactions');
+ $this->loadModel('Inputs');
+ $this->loadModel('Outputs');
+
+ if (!$addr) {
+ return $this->redirect('/');
+ }
+
+ $offset = 0;
+ $pageLimit = 50;
+ $numTransactions = 0;
+ $page = intval($this->request->query('page'));
+
+ $canTag = false;
+ $totalRecvAmount = 0;
+ $totalSentAmount = 0;
+ $balanceAmount = 0;
+ $recentTxs = [];
+
+ $tagRequestAmount = 0;
+ // Check for pending tag request
+ $this->loadModel('TagAddressRequests');
+ $pending = $this->TagAddressRequests->find()->where(['Address' => $addr, 'IsVerified <>' => 1])->first();
+ if (!$pending) {
+ $tagRequestAmount = '25.' . rand(11111111, 99999999);
+ }
+
+
+ $address = $this->Addresses->find()->where(['Address' => $addr])->first();
+ if (!$address) {
+ if (strlen($addr) === 34) {
+ $address = new \stdClass();
+ $address->Address = $addr;
+ } else {
+ return $this->redirect('/');
+ }
+ } else {
+ $conn = ConnectionManager::get('default');
+
+ $canTag = true;
+ $addressId = $address->Id;
+
+ $stmt = $conn->execute('SELECT COUNT(TransactionId) AS Total FROM TransactionsAddresses WHERE AddressId = ?', [$addressId]);
+ $count = $stmt->fetch(\PDO::FETCH_OBJ);
+ $numTransactions = $count->Total;
+ $all = $this->request->query('all');
+ if ($all === 'true') {
+ $offset = 0;
+ $pageLimit = $numTransactions;
+ $numPages = 1;
+ $page = 1;
+ } else {
+ $numPages = ceil($numTransactions / $pageLimit);
+ if ($page < 1) {
+ $page = 1;
+ }
+ if ($page > $numPages) {
+ $page = $numPages;
+ }
+
+ $offset = ($page - 1) * $pageLimit;
+ }
+
+ $stmt = $conn->execute('SELECT A.TotalReceived, A.TotalSent, A.Balance FROM Addresses A WHERE A.Id = ?', [$address->Id]);
+ $totals = $stmt->fetch(\PDO::FETCH_OBJ);
+
+ $stmt = $conn->execute(sprintf('SELECT T.Id, T.Hash, T.InputCount, T.OutputCount, T.Value, ' .
+ 'TA.DebitAmount, TA.CreditAmount, ' .
+ 'B.Height, B.Confirmations, IFNULL(T.TransactionTime, T.CreatedTime) AS TxTime ' .
+ 'FROM Transactions T ' .
+ 'LEFT JOIN Blocks B ON T.BlockHash = B.Hash ' .
+ 'RIGHT JOIN (SELECT TransactionId, DebitAmount, CreditAmount FROM TransactionsAddresses ' .
+ ' WHERE AddressId = ? ORDER BY TransactionTime DESC LIMIT %d, %d) TA ON TA.TransactionId = T.Id', $offset, $pageLimit), [$addressId]);
+ $recentTxs = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ $totalRecvAmount = $totals->TotalReceived == 0 ? '0' : $totals->TotalReceived + 0;
+ $totalSentAmount = $totals->TotalSent == 0 ? '0' : $totals->TotalSent + 0;
+ $balanceAmount = $totals->Balance == 0 ? '0' : $totals->Balance + 0;
+ }
+
+ $this->set('offset', $offset);
+ $this->set('canTag', $canTag);
+ $this->set('pending', $pending);
+ $this->set('tagRequestAmount', $tagRequestAmount);
+ $this->set('address', $address);
+ $this->set('totalReceived', $totalRecvAmount);
+ $this->set('totalSent', $totalSentAmount);
+ $this->set('balanceAmount', $balanceAmount);
+ $this->set('recentTxs', $recentTxs);
+ $this->set('numRecords', $numTransactions);
+ $this->set('numPages', $numPages);
+ $this->set('currentPage', $page);
+ $this->set('pageLimit', $pageLimit);
+ }
+
+ public function qr($data = null) {
+ $this->autoRender = false;
+
+ if (!$data || strlen(trim($data)) == 0 || strlen(trim($data)) > 50) {
+ return;
+ }
+
+ $qrCode = new QrCode($data);
+ $qrCode->setSize(300);
+
+ // Set advanced options
+ $qrCode
+ ->setWriterByName('png')
+ ->setMargin(10)
+ ->setEncoding('UTF-8')
+ ->setErrorCorrectionLevel(ErrorCorrectionLevel::LOW)
+ ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0])
+ ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255])
+ ->setLogoWidth(150)
+ ->setValidateResult(false);
+
+ header('Content-Type: '.$qrCode->getContentType());
+ echo $qrCode->writeString();
+ exit(0);
+ }
+
+ public static function curl_get($url) {
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ $response = curl_exec($ch);
+ Log::debug('Request execution completed.');
+
+ if ($response === false) {
+ $error = curl_error($ch);
+ $errno = curl_errno($ch);
+ curl_close($ch);
+
+ throw new \Exception(sprintf('The request failed: %s', $error), $errno);
+ } else {
+ curl_close($ch);
+ }
+
+ return $response;
+ }
+
+ private function _gethashrate() {
+ $req = ['method' => 'getnetworkhashps', 'params' => []];
+ try {
+ $res = json_decode(self::curl_json_post(self::rpcurl, json_encode($req)));
+ if (!isset($res->result)) {
+ return 0;
+ }
+ return $res->result;
+ } catch (\Exception $e) {
+ return 'N/A';
+ }
+ }
+ private function _gettxoutsetinfo() {
+ $req = ['method' => 'gettxoutsetinfo', 'params' => []];
+ try {
+ $res = json_decode(self::curl_json_post(self::rpcurl, json_encode($req)));
+ if (!isset($res->result)) {
+ return 0;
+ }
+ return $res->result;
+ } catch (\Exception $e) {
+ return 'N/A';
+ }
+ }
+ public function apistatus() {
+ $this->autoRender = false;
+ $this->loadModel('Blocks');
+
+ // Get the max height block
+ $height = 0;
+ $difficulty = 0;
+ $highestBlock = $this->Blocks->find()->select(['Height', 'Difficulty'])->order(['Height' => 'desc'])->first();
+ $height = $highestBlock->Height;
+ $difficulty = $highestBlock->Difficulty;
+ $lbcUsdPrice = $this->_getLatestPrice();
+
+ // Calculate hash rate
+ $hashRate = $this->_formatHashRate($this->_gethashrate());
+
+ return $this->_jsonResponse(['success' => true, 'status' => [
+ 'height' => $height,
+ 'difficulty' => number_format($difficulty, 2, '.', ''),
+ 'price' => $lbcUsdPrice,
+ 'hashrate' => $hashRate
+ ]]);
+ }
+
+ public function apirecentblocks() {
+ $this->autoRender = false;
+ $this->loadModel('Blocks');
+ $blocks = $this->Blocks->find()->select(['Difficulty', 'Hash', 'Height', 'TransactionHashes', 'BlockTime', 'BlockSize'])->
+ order(['Height' => 'desc'])->limit(6)->toArray();
+ for ($i = 0; $i < count($blocks); $i++) {
+ $tx_hashes = json_decode($blocks[$i]->TransactionHashes);
+ $blocks[$i]->TransactionCount = count($tx_hashes);
+ $blocks[$i]->Difficulty = number_format($blocks[$i]->Difficulty, 2, '.', '');
+ unset($blocks[$i]->TransactionHashes);
+ }
+ return $this->_jsonResponse(['success' => true, 'blocks' => $blocks]);
+ }
+
+ public function apiaddrtag($base58address = null) {
+ $this->autoRender = false;
+ if (!isset($base58address) || strlen(trim($base58address)) !== 34) {
+ return $this->_jsonError('Invalid base58 address specified.', 400);
+ }
+ if (!$this->request->is('post')) {
+ return $this->_jsonError('Invalid HTTP request method.', 400);
+ }
+
+ if (trim($base58address) == self::tagReceiptAddress) {
+ return $this->_jsonError('You cannot submit a tag request for this address.', 400);
+ }
+
+ $this->loadModel('Addresses');
+ $this->loadModel('TagAddressRequests');
+ $data = [
+ 'Address' => $base58address,
+ 'Tag' => trim($this->request->data('tag')),
+ 'TagUrl' => trim($this->request->data('url')),
+ 'VerificationAmount' => $this->request->data('vamount')
+ ];
+
+ // verify
+ $entity = $this->TagAddressRequests->newEntity($data);
+ if (strlen($entity->Tag) === 0 || strlen($entity->Tag) > 30) {
+ return $this->_jsonError('Oops! Please specify a valid tag. It should be no more than 30 characters long.', 400);
+ }
+
+ if (strlen($entity->TagUrl) > 0) {
+ if (strlen($entity->TagUrl) > 200) {
+ return $this->_jsonError('Oops! The link should be no more than 200 characters long.', 400);
+ }
+ if (!filter_var($entity->TagUrl, FILTER_VALIDATE_URL)) {
+ return $this->_jsonError('Oops! The link should be a valid URL.', 400);
+ }
+ } else {
+ unset($entity->TagUrl);
+ }
+
+ if ($entity->VerificationAmount < 25.1 || $entity->VerificationAmount > 25.99999999) {
+ return $this->_jsonError('Oops! The verification amount is invalid. Please refresh the page and try again.', 400);
+ }
+
+ // check if the tag is taken
+ $addrTag = $this->Addresses->find()->select(['Id'])->where(['LOWER(Tag)' => strtolower($entity->Tag)])->first();
+ if ($addrTag) {
+ return $this->_jsonError('Oops! The tag is already taken. Please specify a different tag.', 400);
+ }
+
+ // check for existing verification
+ $exist = $this->TagAddressRequests->find()->select(['Id'])->where(['Address' => $base58address, 'IsVerified' => 0])->first();
+ if ($exist) {
+ return $this->_jsonError('Oops! There is a pending tag verification for this address.', 400);
+ }
+
+ // save the request
+ if (!$this->TagAddressRequests->save($entity)) {
+ return $this->_jsonError('Oops! The verification request could not be saved. If this problem persists, please send an email to hello@aureolin.co');
+ }
+
+ return $this->_jsonResponse(['success' => true, 'tag' => $entity->Tag]);
+ }
+
+ public function apiaddrbalance($base58address = null) {
+ $this->autoRender = false;
+ $this->loadModel('Addresses');
+
+ if (!isset($base58address)) {
+ return $this->_jsonError('Base58 address not specified.', 400);
+ }
+
+ // TODO: Add unconfirmed_balance to response
+ $result = $this->Addresses->find()->select(['Balance'])->where(['Address' => $base58address])->first();
+ if (!$result) {
+ // Return 0 for address that does not exist?
+ $result = new \stdClass();
+ $result->Balance = 0;
+ }
+
+ return $this->_jsonResponse(['success' => true, ['balance' => ['confirmed' => $result->Balance, 'unconfirmed' => 0]]]);
+ }
+
+ public function apiaddrutxo($base58address = null) {
+ $this->autoRender = false;
+ $this->loadModel('Addresses');
+
+ if (!isset($base58address)) {
+ return $this->_jsonError('Base58 address not specified.', 400);
+ }
+
+ $arr = explode(',', $base58address);
+ $addresses = $this->Addresses->find()->select(['Id'])->where(['Address IN' => $arr])->toArray();
+ if (count($addresses) == 0) {
+ return $this->_jsonError('No base58 address matching the specified parameter was found.', 404);
+ }
+
+ $addressIds = [];
+ $params = [];
+ foreach ($addresses as $address) {
+ $addressIds[] = $address->Id;
+ $params[] = '?';
+ }
+
+ // Get the unspent outputs for the address
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute(sprintf(
+ 'SELECT T.Hash AS TransactionHash, O.Vout, O.Value, O.Addresses, O.ScriptPubKeyAsm, O.ScriptPubKeyHex, O.Type, O.RequiredSignatures, B.Confirmations ' .
+ 'FROM Transactions T ' .
+ 'JOIN Outputs O ON O.TransactionId = T.Id ' .
+ 'JOIN Blocks B ON B.Hash = T.BlockHash ' .
+ 'WHERE O.Id IN (SELECT OutputId FROM OutputsAddresses WHERE AddressId IN (%s)) AND O.IsSpent <> 1 ORDER BY T.TransactionTime ASC', implode(',', $params)), $addressIds);
+ $outputs = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ $utxo = [];
+ foreach ($outputs as $out) {
+ $utxo[] = [
+ 'transaction_hash' => $out->TransactionHash,
+ 'output_index' => $out->Vout,
+ 'value' => (int) bcmul($out->Value, 100000000),
+ 'addresses' => json_decode($out->Addresses),
+ 'script' => $out->ScriptPubKeyAsm,
+ 'script_hex' => $out->ScriptPubKeyHex,
+ 'script_type' => $out->Type,
+ 'required_signatures' => (int) $out->RequiredSignatures,
+ 'spent' => false,
+ 'confirmations' => (int) $out->Confirmations
+ ];
+ }
+
+ return $this->_jsonResponse(['success' => true, 'utxo' => $utxo]);
+ }
+
+ public function apiutxosupply() {
+ $this->autoRender = false;
+ $this->loadModel('Addresses');
+
+ $circulating = 0;
+ $reservedcommunity = 0;
+ $reservedoperational = 0;
+ $reservedinstitutional = 0;
+ $reservedtotal = 0;
+ $circulating = 0;
+
+ $txoutsetinfo = $this->_gettxoutsetinfo();
+ $reservedcommunity = $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'rFLUohPG4tP3gZHYoyhvADCtrDMiaYb7Qd'])->first();
+ $reservedoperational = $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'r9PGXsejVJb9ZfMf3QVdDEJCzxkd9JLxzL'])->first();
+ $reservedinstitutional = $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'r9srwX7DEN7Mex3a8oR1mKSqQmLBizoJvi'])->first();
+ //aux is the address of hot wallets and where some of the LBRY operational fund are, but not sold on market.
+ $reservedaux = $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'bRo4FEeqqxY7nWFANsZsuKEWByEgkvz8Qt'])->first() +
+ $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'bU2XUzckfpdEuQNemKvhPT1gexQ3GG3SC2'])->first() +
+ $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'bay3VA6YTQBL4WLobbG7CthmoGeUKXuXkD'])->first() +
+ $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'bLPbiXBp6Vr3NSnsHzDsLNzoy5o36re9Cz'])->first() +
+ $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'bMvUBo1h5WS46ThHtmfmXftz3z33VHL7wc'])->first() +
+ $this->Addresses->find()->select(['Balance'])->where(['Address =' => 'bVUrbCK8hcZ5XWti7b9eNxKEBxzc1rr393'])->first();
+
+ $reservedtotal = $reservedcommunity->Balance + $reservedoperational->Balance + $reservedinstitutional->Balance + $reservedaux->Balance;
+
+
+ $circulating = $txoutsetinfo->total_amount - $reservedtotal;
+
+ return $this->_jsonResponse(['success' => true, 'utxosupply' => ['total' => $txoutsetinfo->total_amount, 'circulating' => $circulating]]);
+ }
+
+ private static function curl_json_post($url, $data, $headers = []) {
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ $response = curl_exec($ch);
+ if ($response === false) {
+ $error = curl_error($ch);
+ $errno = curl_errno($ch);
+ curl_close($ch);
+
+ throw new \Exception(sprintf('The request failed: %s', $error), $errno);
+ } else {
+ curl_close($ch);
+ }
+
+ // Close any open file handle
+ return $response;
+ }
+}
+
+?>
diff --git a/src/Controller/PagesController.php b/src/Controller/PagesController.php
new file mode 100644
index 0000000..55792c8
--- /dev/null
+++ b/src/Controller/PagesController.php
@@ -0,0 +1,69 @@
+redirect('/');
+ }
+ if (in_array('..', $path, true) || in_array('.', $path, true)) {
+ throw new ForbiddenException();
+ }
+ $page = $subpage = null;
+
+ if (!empty($path[0])) {
+ $page = $path[0];
+ }
+ if (!empty($path[1])) {
+ $subpage = $path[1];
+ }
+ $this->set(compact('page', 'subpage'));
+
+ try {
+ $this->render(implode('/', $path));
+ } catch (MissingTemplateException $e) {
+ if (Configure::read('debug')) {
+ throw $e;
+ }
+ throw new NotFoundException();
+ }
+ }
+}
diff --git a/src/Model/Behavior/SimpleAuditBehavior.php b/src/Model/Behavior/SimpleAuditBehavior.php
new file mode 100644
index 0000000..8d20b5b
--- /dev/null
+++ b/src/Model/Behavior/SimpleAuditBehavior.php
@@ -0,0 +1,67 @@
+ false,
+ 'implementedMethods' => ['audit' => 'audit'],
+ 'fieldMap' => [
+ 'CreatedOn' => 'Created',
+ 'ModifiedOn' => 'Modified',
+ 'CreatedBy' => 'CreatedBy',
+ 'ModifiedBy' => 'ModifiedBy'
+ ]
+ ];
+
+ public function audit(Entity $entity, $systemOperation = false) {
+ $time = $this->_currentUtcTime()->format('Y-m-d H:i:s');
+ $user = ($systemOperation) ? self::$DefaultUser : $this->_currentUser();
+
+ if (!$systemOperation
+ && $this->_config['abortOnUserInvalid']
+ && $user == self::$DefaultUser)
+ {
+ return false;
+ }
+
+ $fieldMap = $this->_config['fieldMap'];
+
+ if ($entity->isNew()) {
+ $entity->set($fieldMap['CreatedOn'], $time);
+ $entity->set($fieldMap['CreatedBy'], $user);
+ }
+
+ $entity->set($fieldMap['ModifiedOn'], $time);
+ $entity->set($fieldMap['ModifiedBy'], $user);
+ return true;
+ }
+
+ public function beforeSave(Event $event, Entity $entity) {
+ return $this->audit($entity);
+ }
+
+ private function _currentUtcTime() {
+ return new \DateTime('now', new \DateTimeZone('UTC'));
+ }
+
+ private function _currentUser() {
+ $request = Router::getRequest(true);
+ if ($request) {
+ $session = $request->session();
+ $fieldValue = $session->read(sprintf('Auth.User.' . $this->_userField));
+ return (intval($fieldValue) > 0) ? $fieldValue : self::$DefaultUser;
+ }
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Entity/Address.php b/src/Model/Entity/Address.php
new file mode 100644
index 0000000..fbae83e
--- /dev/null
+++ b/src/Model/Entity/Address.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/Block.php b/src/Model/Entity/Block.php
new file mode 100644
index 0000000..7858813
--- /dev/null
+++ b/src/Model/Entity/Block.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/Claim.php b/src/Model/Entity/Claim.php
new file mode 100644
index 0000000..8faa889
--- /dev/null
+++ b/src/Model/Entity/Claim.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/ClaimStream.php b/src/Model/Entity/ClaimStream.php
new file mode 100644
index 0000000..6a51882
--- /dev/null
+++ b/src/Model/Entity/ClaimStream.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/Input.php b/src/Model/Entity/Input.php
new file mode 100644
index 0000000..2cfebd1
--- /dev/null
+++ b/src/Model/Entity/Input.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/Output.php b/src/Model/Entity/Output.php
new file mode 100644
index 0000000..e1142a5
--- /dev/null
+++ b/src/Model/Entity/Output.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/PriceHistory.php b/src/Model/Entity/PriceHistory.php
new file mode 100644
index 0000000..2d0f333
--- /dev/null
+++ b/src/Model/Entity/PriceHistory.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/TagAddressRequest.php b/src/Model/Entity/TagAddressRequest.php
new file mode 100644
index 0000000..5f7977f
--- /dev/null
+++ b/src/Model/Entity/TagAddressRequest.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Entity/Transaction.php b/src/Model/Entity/Transaction.php
new file mode 100644
index 0000000..631f08c
--- /dev/null
+++ b/src/Model/Entity/Transaction.php
@@ -0,0 +1,11 @@
+
\ No newline at end of file
diff --git a/src/Model/Table/AddressesTable.php b/src/Model/Table/AddressesTable.php
new file mode 100644
index 0000000..1876136
--- /dev/null
+++ b/src/Model/Table/AddressesTable.php
@@ -0,0 +1,18 @@
+primaryKey('Id');
+ $this->table('Addresses');
+
+ $this->addBehavior('SimpleAudit');
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/BlocksTable.php b/src/Model/Table/BlocksTable.php
new file mode 100644
index 0000000..0b2a8ed
--- /dev/null
+++ b/src/Model/Table/BlocksTable.php
@@ -0,0 +1,18 @@
+primaryKey('Id');
+ $this->table('Blocks');
+
+ $this->addBehavior('SimpleAudit');
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/ClaimStreamsTable.php b/src/Model/Table/ClaimStreamsTable.php
new file mode 100644
index 0000000..eb77edf
--- /dev/null
+++ b/src/Model/Table/ClaimStreamsTable.php
@@ -0,0 +1,18 @@
+primaryKey('Id');
+ $this->table('ClaimStreams');
+
+ //$this->addBehavior('SimpleAudit');
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/ClaimsTable.php b/src/Model/Table/ClaimsTable.php
new file mode 100644
index 0000000..4177faa
--- /dev/null
+++ b/src/Model/Table/ClaimsTable.php
@@ -0,0 +1,36 @@
+primaryKey('Id');
+ $this->table('Claims');
+
+ //$this->addBehavior('SimpleAudit');
+ $this->addAssociations([
+ 'belongsTo' => [
+ 'Publisher' => [
+ 'className' => 'App\Model\Table\ClaimsTable',
+ 'foreignKey' => 'PublisherId',
+ 'bindingKey' => 'ClaimId',
+ 'propertyName' => 'Publisher'
+ ]
+ ],
+ 'hasOne' => [
+ 'Stream' => [
+ 'className' => 'App\Model\Table\ClaimStreamsTable',
+ 'foreignKey' => 'Id',
+ 'bindingKey' => 'Id',
+ 'propertyName' => 'Stream'
+ ]
+ ]
+ ]);
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/InputsTable.php b/src/Model/Table/InputsTable.php
new file mode 100644
index 0000000..c1c06e7
--- /dev/null
+++ b/src/Model/Table/InputsTable.php
@@ -0,0 +1,30 @@
+primaryKey('Id');
+ $this->table('Inputs');
+
+ $this->addBehavior('SimpleAudit');
+
+ $this->addAssociations([
+ 'belongsToMany' => [
+ 'InputAddresses' => [
+ 'className' => 'App\Model\Table\AddressesTable',
+ 'joinTable' => 'InputsAddresses',
+ 'foreignKey' => 'InputId',
+ 'targetForeignKey' => 'AddressId',
+ 'propertyName' => 'InputAddresses'
+ ]
+ ]
+ ]);
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/OutputsTable.php b/src/Model/Table/OutputsTable.php
new file mode 100644
index 0000000..1840aa7
--- /dev/null
+++ b/src/Model/Table/OutputsTable.php
@@ -0,0 +1,37 @@
+primaryKey('Id');
+ $this->table('Outputs');
+
+ $this->addBehavior('SimpleAudit');
+
+ $this->addAssociations([
+ 'belongsTo' => [
+ 'SpendInput' => [
+ 'className' => 'App\Model\Table\InputsTable',
+ 'foreignKey' => 'SpentByInputId',
+ 'propertyName' => 'SpendInput'
+ ]
+ ],
+ 'belongsToMany' => [
+ 'OutputAddresses' => [
+ 'className' => 'App\Model\Table\AddressesTable',
+ 'joinTable' => 'OutputsAddresses',
+ 'foreignKey' => 'OutputId',
+ 'targetForeignKey' => 'AddressId',
+ 'propertyName' => 'OutputAddresses'
+ ]
+ ]
+ ]);
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/PriceHistoryTable.php b/src/Model/Table/PriceHistoryTable.php
new file mode 100644
index 0000000..1b9fe02
--- /dev/null
+++ b/src/Model/Table/PriceHistoryTable.php
@@ -0,0 +1,16 @@
+primaryKey('Id');
+ $this->table('PriceHistory');
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/TagAddressRequestsTable.php b/src/Model/Table/TagAddressRequestsTable.php
new file mode 100644
index 0000000..51af76e
--- /dev/null
+++ b/src/Model/Table/TagAddressRequestsTable.php
@@ -0,0 +1,18 @@
+primaryKey('Id');
+ $this->table('TagAddressRequests');
+
+ $this->addBehavior('SimpleAudit');
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Model/Table/TransactionsTable.php b/src/Model/Table/TransactionsTable.php
new file mode 100644
index 0000000..613512d
--- /dev/null
+++ b/src/Model/Table/TransactionsTable.php
@@ -0,0 +1,18 @@
+primaryKey('Id');
+ $this->table('Transactions');
+
+ $this->addBehavior('SimpleAudit');
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/src/Shell/AuxShell.php b/src/Shell/AuxShell.php
new file mode 100644
index 0000000..692127f
--- /dev/null
+++ b/src/Shell/AuxShell.php
@@ -0,0 +1,222 @@
+loadModel('Addresses');
+ $this->loadModel('Inputs');
+ $this->loadModel('Outputs');
+ $this->loadModel('Transactions');
+ $this->loadModel('TagAddressRequests');
+ }
+
+ public function main() {
+ echo "No arguments specified.\n";
+ }
+
+ public function verifytags() {
+ self::lock('auxverify');
+
+ $conn = ConnectionManager::get('default');
+ $requests = $this->TagAddressRequests->find()->where(['IsVerified <>' => 1])->toArray();
+ foreach ($requests as $req) {
+ echo "Verifying tag for $req->Address, amount: $req->VerificationAmount... ";
+
+ $req_date = $req->Created;
+ $src_addr = $req->Address;
+ $dst_addr = self::tagrcptaddress;
+
+ // find a transaction with the corresponding inputs created on or after the date
+ // look for the address ids
+ $address = $this->Addresses->find()->select(['Id'])->where(['Address' => $src_addr])->first();
+ $veri_address = $this->Addresses->find()->select(['Id'])->where(['Address' => $dst_addr])->first(); // TODO: Redis cache?
+ if (!$address || !$veri_address) {
+ echo "could not find source nor verification addresses. Skipping.\n";
+ continue;
+ }
+
+ $src_addr_id = $address->Id;
+ $dst_addr_id = $veri_address->Id;
+
+ // find the inputs for the source address that were created after $req->Created - 1 hour
+ $req_date->sub(new \DateInterval('PT1H'));
+ $stmt = $conn->execute('SELECT DISTINCT I.TransactionId FROM Inputs I ' .
+ 'RIGHT JOIN (SELECT IIA.InputId FROM InputsAddresses IIA WHERE IIA.AddressId = ?) IA ON IA.InputId = I.Id ' .
+ 'JOIN Transactions T ON T.Id = I.TransactionId ' .
+ 'LEFT JOIN Blocks B ON B.Hash = T.BlockHash ' .
+ 'WHERE B.Confirmations > 0 AND DATE(I.Created) >= ?', [$src_addr_id, $req_date->format('Y-m-d')]);
+ $tx_inputs = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+
+ $param_values = [$dst_addr_id];
+ $params = [];
+ foreach ($tx_inputs as $in) {
+ $params[] = '?';
+ $param_values[] = $in->TransactionId;
+ }
+
+ $num_inputs = count($tx_inputs);
+ echo "***found $num_inputs inputs from address $src_addr.\n";
+
+ if ($num_inputs == 0) {
+ continue;
+ }
+
+ try {
+ // check the outputs with the dst address
+ $total_amount = 0;
+ $stmt = $conn->execute(sprintf('SELECT O.Value FROM Outputs O ' .
+ 'RIGHT JOIN (SELECT IOA.OutputId, IOA.AddressId FROM OutputsAddresses IOA WHERE IOA.AddressId = ?) OA ON OA.OutputId = O.Id ' .
+ 'WHERE O.TransactionId IN (%s)', implode(', ', $params)), $param_values);
+ $tx_outputs = $stmt->fetchAll(\PDO::FETCH_OBJ);
+ foreach ($tx_outputs as $out) {
+ echo "***found output to verification address with value " . $out->Value . "\n";
+ $total_amount = bcadd($total_amount, $out->Value, 8);
+ }
+
+ if ($total_amount >= $req->VerificationAmount) {
+ $conn->begin();
+ echo "***$total_amount is gte verification amount: $req->VerificationAmount.\n";
+
+ // Update the tag in the DB
+ $conn->execute('UPDATE Addresses SET Tag = ?, TagUrl = ? WHERE Address = ?', [$req->Tag, $req->TagUrl, $src_addr]);
+
+ // Set the request as verified
+ $conn->execute('UPDATE TagAddressRequests SET IsVerified = 1 WHERE Id = ?', [$req->Id]);
+
+ $conn->commit();
+ echo "Data committed.\n";
+ } else {
+ echo "***$total_amount is NOT up to verification amount: $req->VerificationAmount.\n";
+ }
+ } catch (\Exception $e) {
+ print_r($e);
+ echo "Rolling back.\n";
+ $conn->rollback();
+ }
+ }
+
+ self::unlock('auxverify');
+ }
+
+ public function pricehistory() {
+ self::lock('pricehistory');
+
+ $conn = ConnectionManager::get('default');
+ $redis = new \Predis\Client('tcp://127.0.0.1:6379');
+
+ try {
+ // Only allow 5-minute update intervals
+ $stmt = $conn->execute('SELECT MAX(Created) AS LastUpdate FROM PriceHistory');
+ $res = $stmt->fetch(\PDO::FETCH_OBJ);
+
+ $now = new \DateTime('now', new \DateTimeZone('UTC'));
+ if ($res && strlen(trim($res->LastUpdate)) > 0) {
+ $dt = new \DateTime($res->LastUpdate, new \DateTimeZone('UTC'));
+ $diff = $now->diff($dt);
+ $diffMinutes = $diff->i;
+ if ($diffMinutes < 5) {
+ echo "Last update is less than 5 minutes ago. Quitting.\n";
+ self::unlock('pricehistory');
+ return;
+ }
+ }
+
+ $btrxjson = json_decode(self::curl_get(self::bittrex));
+ $blckjson = json_decode(self::curl_get(self::blockchainticker));
+
+ if ($btrxjson->success) {
+ $btc = $btrxjson->result->Bid;
+ $usd = 0;
+ if (isset($blckjson->USD)) {
+ $usd = $btc * $blckjson->USD->buy;
+ $priceInfo = new \stdClass();
+ $priceInfo->price = number_format($usd, 2, '.', '');
+ $priceInfo->time = $now->format('c');
+ if ($redis) {
+ $redis->set(self::lbcpricekey, json_encode($priceInfo));
+ }
+
+ // save the price history if both prices are > 0
+ if ($usd > 0 && $btc > 0) {
+ $conn->execute('INSERT INTO PriceHistory (USD, BTC, Created) VALUES (?, ?, UTC_TIMESTAMP())', [$usd, $btc]);
+ echo "Inserted price history item. USD: $usd, BTC: $btc.\n";
+ } else {
+ echo "Could not insert price history item. USD: $usd, BTC: $btc.\n";
+ }
+ }
+ } else {
+ echo "bittrex requrest returned an invalid result.\n";
+ }
+ } catch (\Exception $e) {
+ print_r($e);
+ }
+
+ self::unlock('pricehistory');
+ }
+
+ public static function lock($process_name) {
+ if (!is_dir(TMP . 'lock')) {
+ mkdir(TMP . 'lock');
+ }
+ $lock_file = TMP . 'lock' . DS . $process_name;
+ if (file_exists($lock_file)) {
+ echo "$process_name is already running.\n";
+ exit(0);
+ }
+ file_put_contents($lock_file, '1');
+ }
+
+ public static function unlock($process_name) {
+ $lock_file = TMP . 'lock' . DS . $process_name;
+ if (file_exists($lock_file)) {
+ unlink($lock_file);
+ }
+ return true;
+ }
+
+ public static function curl_get($url) {
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ $response = curl_exec($ch);
+ if ($response === false) {
+ $error = curl_error($ch);
+ $errno = curl_errno($ch);
+ curl_close($ch);
+
+ throw new \Exception(sprintf('The request failed: %s', $error), $errno);
+ } else {
+ curl_close($ch);
+ }
+
+ return $response;
+ }
+}
+
+?>
diff --git a/src/Shell/BlockShell.php b/src/Shell/BlockShell.php
new file mode 100644
index 0000000..2c933de
--- /dev/null
+++ b/src/Shell/BlockShell.php
@@ -0,0 +1,2199 @@
+loadModel('Blocks');
+ $this->loadModel('Addresses');
+ $this->loadModel('Claims');
+ $this->loadModel('ClaimStreams');
+ $this->loadModel('Inputs');
+ $this->loadModel('Outputs');
+ $this->loadModel('Transactions');
+ }
+
+ public function main() {
+ $this->out('No arguments specified');
+ }
+
+ public function testtx() {
+ $raw = '0100000001e4801fa8c9621753410e6c576c73168cc551624e08e4cc56e9a9189e8ebabcc3010000006b483045022100dcc5ae5564353e05cd8415936cdb534a26049a80a9866dbcab5dbb6ab16abbc702203af681fb5fbba5c78af887778aa32f27bc653312322b44c2a78e883e322921790121031c38def6b103b58481818d7d8aba39f9f51798f686ec3332bac23726a23366adffffffff0200e1f50500000000fd3a01b512626c6f636b6578706c6f7265722d686f6d654d0801080110011aa3010801125c080410011a1c4c42525920426c6f636b204578706c6f72657220486f6d6570616765222c574950204c42525920426c6f636b204578706c6f72657220686f6d6520706167652073637265656e73686f742a00320038004a0052005a001a41080110011a3038c6bf4a310d5b172aaae03cffb93e5a27c47f3946f58af0a4b9f99d7be42998f7dcec9b0fb0c124a6477bdb4c5311db2209696d6167652f706e672a5c080110031a401eb69f65768ba2cc347067dfb1317131137f7d685a5e804a4aeedd2385332c70f3ec7632fcebfbc073e37a58dbfbf4e6641853bbfc188b0d8bf27435b540801d22146b2a1d378efcdb7db7a03baa7dfedb86b976bc4a6d7576a914b7182b0f7c896ab240d233f81cb891e3f25e739988ac8085e811000000001976a9146fde27b4dac0b79a9ea06756562a52b019da7a8e88ac00000000';
+ $decoded = self::decode_tx($raw);
+ }
+
+ public function fixscripthashtx() {
+ $conn = ConnectionManager::get('default');
+ $otxs = $this->Outputs->find()->select(['TransactionId'])->distinct(['TransactionId'])->where(['Type' => 'scripthash'])->toArray();
+ foreach ($otxs as $otx) {
+ $txid = $otx->TransactionId;
+ $tx = $this->Transactions->find()->select(['Hash'])->where(['Id' => $txid])->first();
+ $req = ['method' => 'getrawtransaction', 'params' => [$tx->Hash]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $tx_result = $json->result;
+ $raw_tx = $tx_result;
+ $tx_data = self::decode_tx($raw_tx);
+ $all_tx_data = $this->txdb_data_from_decoded($tx_data);
+
+ foreach ($all_tx_data['outputs'] as $out) {
+ if ($out['Type'] != 'scripthash') {
+ continue;
+ }
+
+ // get the old address
+ $old_output = $this->Outputs->find()->select(['Id', 'Addresses'])->where(['TransactionId' => $txid, 'Vout' => $out['Vout']])->first();
+ if ($old_output) {
+ $old_addresses = json_decode($old_output->Addresses);
+ $old_address = $old_addresses[0];
+ $new_addresses = json_decode($out['Addresses']);
+ $new_address = $new_addresses[0];
+
+ // update the output with new addresses array
+ $conn->begin();
+ $conn->execute('UPDATE Outputs SET Addresses = ? WHERE Id = ?', [$out['Addresses'], $old_output->Id]);
+
+ // update the old address with the new one
+ $conn->execute('UPDATE Addresses SET Address = ? WHERE Address = ?', [$new_address, $old_address]);
+ $conn->commit();
+
+ echo "$old_address => $new_address\n";
+ }
+ }
+ }
+ }
+
+ public static function hex2str($hex){
+ $string = '';
+ for ($i = 0; $i < strlen($hex)-1; $i+=2){
+ $string .= chr(hexdec($hex[$i].$hex[$i+1]));
+ }
+ return $string;
+ }
+
+ public function updateclaimfees() {
+ self::lock('claimfees');
+
+ $conn = ConnectionManager::get('default');
+ try {
+ $stmt = $conn->execute('SELECT CS.Id, CS.Stream FROM ClaimStreams CS JOIN Claims C ON C.Id = CS.Id WHERE C.Fee = 0 AND C.Id <= 11462 ORDER BY Id ASC');
+ $claims = $stmt->fetchAll(\PDO::FETCH_OBJ);
+ foreach ($claims as $claim) {
+ $stream = json_decode($claim->Stream);
+ if (isset($stream->metadata->fee) && $stream->metadata->fee->amount > 0) {
+ $fee = $stream->metadata->fee->amount;
+ $currency = $stream->metadata->fee->currency;
+
+ $conn->execute('UPDATE Claims SET Fee = ?, FeeCurrency = ? WHERE Id = ?', [$fee, $currency, $claim->Id]);
+ echo "Updated fee for claim ID: $claim->Id. Fee: $fee, Currency: $currency\n";
+ }
+ }
+ } catch (\Exception $e) {
+ print_r($e);
+ }
+
+ self::unlock('claimfees');
+ }
+
+ public function buildclaimindex() {
+ self::lock('buildindex');
+
+ // start with all txs
+ $decoder_url = 'http://127.0.0.1:5000';
+ $redis = self::_init_redis();
+ $conn = ConnectionManager::get('default');
+ $redis_key = 'claim.oid';
+ $last_claim_oid = $redis->exists($redis_key) ? $redis->get($redis_key) : 0;
+ try {
+ $stmt = $conn->execute('SELECT COUNT(Id) AS RecordCount FROM Outputs WHERE Id > ?', [$last_claim_oid]);
+ $count = min(500000, $stmt->fetch(\PDO::FETCH_OBJ)->RecordCount);
+
+ $idx = 0;
+ $stmt = $conn->execute('SELECT O.Id, O.TransactionId, O.Vout, O.ScriptPubKeyAsm, T.Hash, IFNULL(T.TransactionTime, T.CreatedTime) AS TxTime FROM Outputs O ' .
+ 'JOIN Transactions T ON T.Id = O.TransactionId WHERE O.Id > ? ORDER BY O.Id ASC LIMIT 500000',
+ [$last_claim_oid]);
+ while ($out = $stmt->fetch(\PDO::FETCH_OBJ)) {
+ $idx++;
+ $idx_str = str_pad($idx, strlen($count), '0', STR_PAD_LEFT);
+
+ $txid = $out->TransactionId;
+ $vout = $out->Vout;
+
+ if (strpos($out->ScriptPubKeyAsm, 'OP_CLAIM_NAME') !== false) {
+ // check if the claim already exists in the claims table
+ $stmt2 = $conn->execute('SELECT Id FROM Claims WHERE TransactionHash = ? AND Vout = ?', [$out->Hash, $out->Vout]);
+ $exist_claim = $stmt2->fetch(\PDO::FETCH_OBJ);
+ if ($exist_claim) {
+ echo "[$idx_str/$count] claim already exists for [$out->Hash:$vout]. Skipping.\n";
+ continue;
+ }
+
+ $asm_parts = explode(' ', $out->ScriptPubKeyAsm, 4);
+ $name_hex = $asm_parts[1];
+ $claim_name = @pack('H*', $name_hex);
+
+ // decode claim
+ $url = sprintf("%s/claim_decode/%s", $decoder_url, $claim_name);
+ $json = null;
+ try {
+ $json = self::curl_json_get($url);
+ } catch (\Exception $e) {
+ echo "[$idx_str/$count] claimdecode failed for [$out->Hash:$vout]. Skipping.\n";
+ continue;
+ }
+ $claim = json_decode($json);
+
+ if ($claim) {
+ $req = ['method' => 'getvalueforname', 'params' => [$claim_name]];
+ $json = null;
+ try {
+ $json = json_decode(self::curl_json_post(self::rpcurl, json_encode($req)));
+ if (!$json) {
+ echo "[$idx_str/$count] getvalueforname failed for [$out->Hash:$vout]. Skipping.\n";
+ continue;
+ }
+ } catch (\Exception $e) {
+ echo "[$idx_str/$count] getvalueforname failed for [$out->Hash:$vout]. Skipping.\n";
+ continue;
+ }
+
+ echo "[$idx_str/$count] claim found for [$out->Hash:$vout]. Processing claim... \n";
+ $claim_data = [];
+
+ $claim_id = $json->result->claimId;
+ $tx_dt = \DateTime::createFromFormat('U', $out->TxTime);
+
+ $claim_stream_data = null;
+ if ($claim->claimType === 'streamType') {
+ // Build claim object to save
+ $claim_data = [
+ 'ClaimId' => $claim_id,
+ 'TransactionHash' => $out->Hash,
+ 'Vout' => $out->Vout,
+ 'Name' => $claim_name,
+ 'Version' => $claim->version,
+ 'ClaimType' => 2, // streamType
+ 'ContentType' => isset($claim->stream->source->contentType) ? $claim->stream->source->contentType : null,
+ 'Title' => isset($claim->stream->metadata->title) ? $claim->stream->metadata->title : null,
+ 'Description' => isset($claim->stream->metadata->description) ? $claim->stream->metadata->description : null,
+ 'Language' => isset($claim->stream->metadata->language) ? $claim->stream->metadata->language : null,
+ 'Author' => isset($claim->stream->metadata->author) ? $claim->stream->metadata->author : null,
+ 'ThumbnailUrl' => isset($claim->stream->metadata->thumbnail) ? $claim->stream->metadata->thumbnail : null,
+ 'IsNSFW' => isset($claim->stream->metadata->nsfw) ? $claim->stream->metadata->nsfw : 0,
+ 'Fee' => isset($claim->stream->metadata->fee) ? $claim->stream->metadata->fee->amount : 0,
+ 'FeeCurrency' => isset($claim->stream->metadata->fee) ? $claim->stream->metadata->fee->currency : 0,
+ 'Created' => $tx_dt->format('Y-m-d H:i:s'),
+ 'Modified' => $tx_dt->format('Y-m-d H:i:s')
+ ];
+
+ $claim_stream_data = [
+ 'Stream' => json_encode($claim->stream)
+ ];
+
+ if (isset($claim->publisherSignature)) {
+ $sig_claim = $this->Claims->find()->select(['Id', 'ClaimId', 'Name'])->where(['ClaimId' => $claim->publisherSignature->certificateId])->first();
+ if ($sig_claim) {
+ $claim_data['PublisherId'] = $sig_claim->ClaimId;
+ $claim_data['PublisherName'] = $sig_claim->Name;
+ }
+ }
+ } else {
+ $claim_data = [
+ 'ClaimId' => $claim_id,
+ 'TransactionHash' => $out->Hash,
+ 'Vout' => $out->Vout,
+ 'Name' => $claim_name,
+ 'Version' => $claim->version,
+ 'ClaimType' => 1,
+ 'Certificate' => json_encode($claim->certificate),
+ 'Created' => $tx_dt->format('Y-m-d H:i:s'),
+ 'Modified' => $tx_dt->format('Y-m-d H:i:s')
+ ];
+ }
+
+ $conn->begin();
+ $data_error = false;
+
+ $claim_entity = $this->Claims->newEntity($claim_data);
+ $res = $this->Claims->save($claim_entity);
+
+ if (!$res) {
+ $data_error = true;
+ echo "[$idx_str/$count] claim for [$out->Hash:$vout] FAILED to save.\n";
+ }
+
+ if (!$data_error) {
+ if ($claim_stream_data) {
+ $claim_stream_data['Id'] = $claim_entity->Id;
+ $claim_stream_entity = $this->ClaimStreams->newEntity($claim_stream_data);
+
+ $res = $this->ClaimStreams->save($claim_stream_entity);
+ if (!$res) {
+ $data_error = true;
+ }
+ }
+ }
+
+ if (!$data_error) {
+ $conn->commit();
+ echo "[$idx_str/$count] claim for [$out->Hash:$vout] indexed.\n";
+ } else {
+ $conn->rollback();
+ echo "[$idx_str/$count] claim for [$out->Hash:$vout] NOT indexed. Rolled back.\n";
+ }
+ } else {
+ echo "[$idx_str/$count] claim for [$out->Hash:$vout] could not be decoded. Skipping.\n";
+ }
+ } else {
+ echo "[$idx_str/$count] no claim found for [$out->Hash:$vout]. Skipping.\n";
+ }
+
+ $redis->set($redis_key, $out->Id);
+ }
+ } catch (\Exception $e) {
+ // continue
+ print_r($e);
+ }
+
+ self::unlock('buildindex');
+ }
+
+ protected function _getclaimfortxout($pubkeyasm, $tx_hash, $vout, $tx_time = null) {
+ $claim_data = null;
+ $claim_stream_data = null;
+
+ $asm_parts = explode(' ', $pubkeyasm, 4);
+ $name_hex = $asm_parts[1];
+ $claim_name = @pack('H*', $name_hex);
+
+ // decode claim
+ $decoder_url = 'http://127.0.0.1:5000';
+ $url = sprintf("%s/claim_decode/%s", $decoder_url, $claim_name);
+ $json = null;
+ try {
+ $json = self::curl_json_get($url);
+ } catch (\Exception $e) {
+ echo "***claimdecode failed for [$tx_hash:$vout]. Skipping.\n";
+ }
+
+ if ($json) {
+ $claim = json_decode($json);
+ if ($claim) {
+ $req = ['method' => 'getvalueforname', 'params' => [$claim_name]];
+ $json = null;
+ try {
+ $json = json_decode(self::curl_json_post(self::rpcurl, json_encode($req)));
+ if ($json) {
+ $claim_data = [];
+ $claim_id = $json->result->claimId;
+ $now = new \DateTime('now', new \DateTimeZone('UTC'));
+ $tx_dt = ($tx_time != null) ? $tx_time : $now;
+ if ($claim->claimType === 'streamType') {
+ // Build claim object to save
+ $claim_data = [
+ 'ClaimId' => $claim_id,
+ 'TransactionHash' => $tx_hash,
+ 'Vout' => $vout,
+ 'Name' => $claim_name,
+ 'Version' => $claim->version,
+ 'ClaimType' => 2, // streamType
+ 'ContentType' => isset($claim->stream->source->contentType) ? $claim->stream->source->contentType : null,
+ 'Title' => isset($claim->stream->metadata->title) ? $claim->stream->metadata->title : null,
+ 'Description' => isset($claim->stream->metadata->description) ? $claim->stream->metadata->description : null,
+ 'Language' => isset($claim->stream->metadata->language) ? $claim->stream->metadata->language : null,
+ 'Author' => isset($claim->stream->metadata->author) ? $claim->stream->metadata->author : null,
+ 'ThumbnailUrl' => isset($claim->stream->metadata->thumbnail) ? $claim->stream->metadata->thumbnail : null,
+ 'IsNSFW' => isset($claim->stream->metadata->nsfw) ? $claim->stream->metadata->nsfw : 0,
+ 'Fee' => isset($claim->stream->metadata->fee) ? $claim->stream->metadata->fee->amount : 0,
+ 'FeeCurrency' => isset($claim->stream->metadata->fee) ? $claim->stream->metadata->fee->currency : 0,
+ 'Created' => $tx_dt->format('Y-m-d H:i:s'),
+ 'Modified' => $tx_dt->format('Y-m-d H:i:s')
+ ];
+
+ $claim_stream_data = [
+ 'Stream' => json_encode($claim->stream)
+ ];
+
+ if (isset($claim->publisherSignature)) {
+ $sig_claim = $this->Claims->find()->select(['Id', 'ClaimId', 'Name'])->where(['ClaimId' => $claim->publisherSignature->certificateId])->first();
+ if ($sig_claim) {
+ $claim_data['PublisherId'] = $sig_claim->ClaimId;
+ $claim_data['PublisherName'] = $sig_claim->Name;
+ }
+ }
+ } else {
+ $claim_data = [
+ 'ClaimId' => $claim_id,
+ 'TransactionHash' => $tx_hash,
+ 'Vout' => $vout,
+ 'Name' => $claim_name,
+ 'Version' => $claim->version,
+ 'ClaimType' => 1,
+ 'Certificate' => json_encode($claim->certificate),
+ 'Created' => $tx_dt->format('Y-m-d H:i:s'),
+ 'Modified' => $tx_dt->format('Y-m-d H:i:s')
+ ];
+ }
+ }
+ } catch (\Exception $e) {
+ echo "***getvalueforname failed for [$out->Hash:$vout]. Skipping.\n";
+ }
+ }
+ }
+
+ return ['claim_data' => $claim_data, 'claim_stream_data' => $claim_stream_data];
+ }
+
+ public function fixzerooutputs() {
+ self::lock('zerooutputs');
+
+ $redis = self::_init_redis();
+ $conn = ConnectionManager::get('default');
+
+ /** 2017-06-12 21:38:07 **/
+ //$last_fixed_txid = $redis->exists('fix.txid') ? $redis->get('fix.txid') : 0;
+ try {
+ $stmt = $conn->execute('SELECT Id FROM Transactions WHERE Created >= ? AND Created <= ? LIMIT 1000000', ['2017-06-15 20:44:50', '2017-06-16 08:02:09']);
+ $txids = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ $count = count($txids);
+ $idx = 0;
+ foreach ($txids as $distincttx) {
+ $idx++;
+ $idx_str = str_pad($idx, strlen($count), '0', STR_PAD_LEFT);
+ $txid = $distincttx->Id;
+ echo "[$idx_str/$count] Processing txid: $txid... ";
+ $total_diff = 0;
+
+ // findtx
+ $start_ms = round(microtime(true) * 1000);
+ $tx = $this->Transactions->find()->select(['Hash'])->where(['Id' => $txid])->first();
+ $diff_ms = (round(microtime(true) * 1000)) - $start_ms;
+ $total_diff += $diff_ms;
+ echo "findtx took {$diff_ms}ms. ";
+
+ // Get the inputs and outputs
+ // Get the raw transaction (Use getrawtx daemon instead (for speed!!!)
+
+ // getraw
+ $req = ['method' => 'getrawtransaction', 'params' => [$tx->Hash]];
+ $start_ms = round(microtime(true) * 1000);
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $diff_ms = (round(microtime(true) * 1000)) - $start_ms;
+ $total_diff += $diff_ms;
+ echo "getrawtx took {$diff_ms}ms. ";
+
+ $start_ms = round(microtime(true) * 1000);
+ $json = json_decode($response);
+ $tx_result = $json->result;
+ $raw_tx = $tx_result;
+ $tx_data = self::decode_tx($raw_tx);
+
+ $all_tx_data = $this->txdb_data_from_decoded($tx_data);
+
+ $inputs = $all_tx_data['inputs'];
+ $outputs = $all_tx_data['outputs'];
+
+ $addr_id_map = [];
+ $addr_id_drcr = []; // debits and credits grouped by address
+ $total_tx_value = 0;
+
+ $diff_ms = (round(microtime(true) * 1000)) - $start_ms;
+ $total_diff += $diff_ms;
+ echo "decodetx took {$diff_ms}ms. ";
+
+ // Create / update addresses
+ $addr_id_map = [];
+ $new_addr_map = [];
+ foreach($all_tx_data['addresses'] as $address => $addro) {
+ $prev_addr = $this->Addresses->find()->select(['Id'])->where(['Address' => $address])->first();
+ if (!$prev_addr) {
+ $new_addr = [
+ 'Address' => $address,
+ 'FirstSeen' => $block_ts->format('Y-m-d H:i:s')
+ ];
+ $entity = $this->Addresses->newEntity($new_addr);
+ $res = $this->Addresses->save($entity);
+ if (!$res) {
+ $data_error = true;
+ } else {
+ $addr_id_map[$address] = $entity->Id;
+ }
+ $new_addr_map[$address] = 1;
+ } else {
+ $addr_id_map[$address] = $prev_addr->Id;
+ }
+ }
+
+ $start_ms = round(microtime(true) * 1000);
+ $num_outputs = count($outputs);
+ foreach ($outputs as $out) {
+ $vout = $out['Vout'];
+ $total_tx_value = bcadd($total_tx_value, $out['Value'], 8);
+
+ // check if the output exists
+ $stmt = $conn->execute('SELECT Id FROM Outputs WHERE TransactionId = ? AND Vout = ?', [$txid, $vout]);
+ $exist_output = $stmt->fetch(\PDO::FETCH_OBJ);
+
+ if (!$exist_output) {
+ $out['TransactionId'] = $txid;
+ $out_entity = $this->Outputs->newEntity($out);
+
+ //$stmt->execute('INSERT INTO Outputs')
+ $conn->execute('INSERT INTO Outputs (TransactionId, Vout, Value, Type, ScriptPubKeyAsm, ScriptPubKeyHex, RequiredSignatures, Hash160, Addresses, Created, Modified) '.
+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(), UTC_TIMESTAMP())',
+ [$out['TransactionId'],
+ $out['Vout'],
+ $out['Value'],
+ $out['Type'],
+ $out['ScriptPubKeyAsm'],
+ $out['ScriptPubKeyHex'],
+ $out['RequiredSignatures'],
+ $out['Hash160'],
+ $out['Addresses']
+ ]);
+
+ // get the last insert id
+ $stmt = $conn->execute('SELECT LAST_INSERT_ID() AS outputId');
+ $linsert = $stmt->fetch(\PDO::FETCH_OBJ);
+ $out_entity->Id = $linsert->outputId;
+
+ if ($out_entity->Id === 0) {
+ $data_error = true;
+ break;
+ }
+
+ $json_addr = json_decode($out['Addresses']);
+ $address = $json_addr[0];
+
+ // Get the address ID
+ $addr_id = -1;
+ if (isset($addr_id_map[$address])) {
+ $addr_id = $addr_id_map[$address];
+ } else {
+ $src_addr = $this->Addresses->find()->select(['Id'])->where(['Address' => $address])->first();
+ if ($src_addr) {
+ $addr_id = $src_addr->Id;
+ $addr_id_map[$address] = $addr_id;
+ }
+ }
+
+ if ($addr_id > -1) {
+ $conn->execute('INSERT INTO OutputsAddresses (OutputId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE OutputId = OutputId', [$out_entity->Id, $addr_id]);
+ $conn->execute('INSERT INTO TransactionsAddresses (TransactionId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE TransactionId = TransactionId', [$txid, $addr_id]);
+ }
+
+ if ($addr_id > -1 && isset($new_addr_map[$address])) {
+ if (!isset($addr_id_drcr[$addr_id])) {
+ $addr_id_drcr[$addr_id] = ['debit' => 0, 'credit' => 0];
+ }
+ $addr_id_drcr[$addr_id]['credit'] = bcadd($addr_id_drcr[$addr_id]['credit'], $out['Value'], 8);
+
+ // Update the Received amount for the address based on the output
+ $conn->execute('UPDATE Addresses SET TotalReceived = TotalReceived + ? WHERE Id = ?', [$out['Value'], $addr_id]);
+ }
+ }
+ }
+ $diff_ms = (round(microtime(true) * 1000)) - $start_ms;
+ $total_diff += $diff_ms;
+ echo "$num_outputs output(s) took {$diff_ms}ms. ";
+
+ // Fix the input values
+ $start_ms = round(microtime(true) * 1000);
+ $num_inputs = count($inputs);
+ foreach ($inputs as $in) {
+ if (isset($in['PrevoutHash'])) {
+ $prevout_hash = $in['PrevoutHash'];
+ $in_prevout = $in['PrevoutN'];
+ $prevout_tx_id = -1;
+ $prevout_tx = $this->Transactions->find()->select(['Id'])->where(['Hash' => $prevout_hash])->first();
+ if (!$prevout_tx) {
+ continue;
+ }
+
+ $prevout_tx_id = $prevout_tx->Id;
+ $stmt = $conn->execute('SELECT Value, Addresses FROM Outputs WHERE TransactionId = ? AND Vout = ?', [$prevout_tx_id, $in_prevout]);
+ $src_output = $stmt->fetch(\PDO::FETCH_OBJ);
+ if ($src_output) {
+ $in['Value'] = $src_output->Value;
+ //$conn->execute('UPDATE Inputs SET Value = ? WHERE TransactionId = ? AND PrevoutHash = ? AND PrevoutN = ?', [$in['Value'], $txid, $prevout_hash, $in_prevout]);
+
+ // Check if the input exists
+ $stmt = $conn->execute('SELECT Id FROM Inputs WHERE TransactionId = ? AND PrevoutHash = ? AND PrevoutN = ?', [$txid, $prevout_hash, $in_prevout]);
+ $exist_input = $stmt->fetch(\PDO::FETCH_OBJ);
+
+ if (!$exist_input) {
+ $json_addr = json_decode($src_output->Addresses);
+ $address = $json_addr[0];
+
+ // Get the address ID
+ $addr_id = -1;
+ if (isset($addr_id_map[$address])) {
+ $addr_id = $addr_id_map[$address];
+ } else {
+ $src_addr = $this->Addresses->find()->select(['Id'])->where(['Address' => $address])->first();
+ if ($src_addr) {
+ $addr_id = $src_addr->Id;
+ $addr_id_map[$address] = $addr_id;
+ }
+ }
+
+ $in_entity = $this->Inputs->newEntity($in);
+ $in['TransactionId'] = $txid;
+ if ($addr_id > -1) {
+ $in['AddressId'] = $addr_id;
+ }
+ $conn->execute('INSERT INTO Inputs (TransactionId, TransactionHash, AddressId, PrevoutHash, PrevoutN, Sequence, Value, ScriptSigAsm, ScriptSigHex, Created, Modified) ' .
+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(), UTC_TIMESTAMP())',
+ [$in['TransactionId'],
+ $in['TransactionHash'],
+ isset($in['AddressId']) ? $in['AddressId'] : null,
+ $in['PrevoutHash'],
+ $in['PrevoutN'],
+ $in['Sequence'],
+ isset($in['Value']) ? $in['Value'] : 0,
+ $in['ScriptSigAsm'],
+ $in['ScriptSigHex']
+ ]);
+
+ // get last insert id
+ $stmt = $conn->execute('SELECT LAST_INSERT_ID() AS inputId');
+ $linsert = $stmt->fetch(\PDO::FETCH_OBJ);
+ $in_entity->Id = $linsert->inputId;
+
+ if ($in_entity->Id === 0) {
+ $data_error = true;
+ break;
+ }
+
+ if ($addr_id > -1) {
+ $conn->execute('INSERT INTO InputsAddresses (InputId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE InputId = InputId', [$in_entity->Id, $addr_id]);
+ $conn->execute('INSERT INTO TransactionsAddresses (TransactionId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE TransactionId = TransactionId', [$txid, $addr_id]);
+ }
+
+ if ($addr_id > -1 && isset($new_addr_map[$address])) {
+ if (!isset($addr_id_drcr[$addr_id])) {
+ $addr_id_drcr[$addr_id] = ['debit' => 0, 'credit' => 0];
+ }
+ $addr_id_drcr[$addr_id]['debit'] = bcadd($addr_id_drcr[$addr_id]['debit'], $in['Value'], 8);
+
+ // Update total sent
+ $conn->execute('UPDATE Addresses SET TotalSent = TotalSent + ? WHERE Id = ?', [$in['Value'], $addr_id]);
+ }
+ }
+ }
+ }
+ }
+ $diff_ms = (round(microtime(true) * 1000)) - $start_ms;
+ $total_diff += $diff_ms;
+ echo "$num_inputs input(s) took {$diff_ms}ms. ";
+
+ // update tx time
+ $start_ms = round(microtime(true) * 1000);
+ $upd_addr_ids = [];
+ //$conn->execute('UPDATE Transactions SET Value = ? WHERE Id = ?', [$total_tx_value, $txid]);
+ foreach ($addr_id_drcr as $addr_id => $drcr) {
+ try {
+ $conn->execute('UPDATE TransactionsAddresses SET DebitAmount = ?, CreditAmount = ? WHERE TransactionId = ? AND AddressId = ?',
+ [$drcr['debit'], $drcr['credit'], $txid, $addr_id]);
+ } catch (Exception $e) {
+ print_r($e);
+ $data_error = true;
+ break;
+ }
+ }
+
+ //$redis->set('fix.txid', $txid);
+ $diff_ms = (round(microtime(true) * 1000)) - $start_ms;
+ $total_diff += $diff_ms;
+ echo "update took {$diff_ms}ms. Total {$total_diff} ms.\n";
+ }
+ } catch (\Exception $e) {
+ print_r($e);
+ }
+
+ self::unlock('zerooutputs');
+ }
+
+ public function addrtxamounts() {
+ set_time_limit(0);
+
+ self::lock('addrtxamounts');
+
+ try {
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute('SELECT TransactionId, AddressId FROM TransactionsAddresses WHERE DebitAmount = 0 AND CreditAmount = 0 LIMIT 1000000');
+ $txaddresses = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ $count = count($txaddresses);
+ $idx = 0;
+
+ echo "Processing $count tx address combos...\n";
+ foreach ($txaddresses as $txaddr) {
+ $idx++;
+ $idx_str = str_pad($idx, strlen($count), '0', STR_PAD_LEFT);
+
+ // Check the inputs
+ $stmt = $conn->execute('SELECT SUM(I.Value) AS DebitAmount FROM Inputs I JOIN InputsAddresses IA ON IA.InputId = I.Id WHERE I.TransactionId = ? AND IA.AddressId = ?',
+ [$txaddr->TransactionId, $txaddr->AddressId]);
+ $res = $stmt->fetch(\PDO::FETCH_OBJ);
+ $debitamount = $res->DebitAmount ? $res->DebitAmount : 0;
+
+ $stmt = $conn->execute('SELECT SUM(O.Value) AS CreditAmount FROM Outputs O JOIN OutputsAddresses OA ON OA.OutputId = O.Id WHERE O.TransactionId = ? AND OA.AddressId = ?',
+ [$txaddr->TransactionId, $txaddr->AddressId]);
+ $res = $stmt->fetch(\PDO::FETCH_OBJ);
+ $creditamount = $res->CreditAmount ? $res->CreditAmount : 0;
+
+ echo "[$idx_str/$count] Updating tx $txaddr->TransactionId, address id $txaddr->AddressId with debit amount: $debitamount, credit amount: $creditamount... ";
+ $conn->execute('UPDATE TransactionsAddresses SET DebitAmount = ?, CreditAmount = ? WHERE TransactionId = ? AND AddressId = ?',
+ [$debitamount, $creditamount, $txaddr->TransactionId, $txaddr->AddressId]);
+ echo "Done.\n";
+ }
+ } catch (\Exception $e) {
+ // failed
+ print_r($e);
+ }
+
+ self::unlock('addrtxamounts');
+ }
+
+ private function processtx($tx_hash, $block_ts, $block_data, &$data_error) {
+ // Get the raw transaction (Use getrawtx daemon instead (for speed!!!)
+ $req = ['method' => 'getrawtransaction', 'params' => [$tx_hash]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $tx_result = $json->result;
+ $raw_tx = $tx_result;
+ $tx_data = self::decode_tx($raw_tx);
+
+ $all_tx_data = $this->txdb_data_from_decoded($tx_data);
+ $conn = ConnectionManager::get('default');
+
+ // Create / update addresses
+ $addr_id_map = [];
+ foreach($all_tx_data['addresses'] as $address => $addrss) {
+ $prev_addr = $this->Addresses->find()->select(['Id'])->where(['Address' => $address])->first();
+ if (!$prev_addr) {
+ $new_addr = [
+ 'Address' => $address,
+ 'FirstSeen' => $block_ts->format('Y-m-d H:i:s')
+ ];
+ $entity = $this->Addresses->newEntity($new_addr);
+ $res = $this->Addresses->save($entity);
+ if (!$res) {
+ $data_error = true;
+ } else {
+ $addr_id_map[$address] = $entity->Id;
+ }
+ } else {
+ $addr_id_map[$address] = $prev_addr->Id;
+ }
+ }
+
+ $addr_id_drcr = []; // debits and credits grouped by address
+ $numeric_tx_id = -1;
+ if (!$data_error) {
+ // Create transaction
+ $new_tx = $all_tx_data['tx'];
+
+ $total_tx_value = 0;
+ foreach ($all_tx_data['outputs'] as $out) {
+ $total_tx_value = bcadd($total_tx_value, $out['Value'], 8);
+ }
+
+ if ($block_data) {
+ $new_tx['BlockHash'] = $block_data['hash'];
+ $new_tx['TransactionTime'] = $block_data['time'];
+ }
+ $new_tx['TransactionSize'] = ((strlen($raw_tx)) / 2);
+ $new_tx['InputCount'] = count($all_tx_data['inputs']);
+ $new_tx['OutputCount'] = count($all_tx_data['outputs']);
+ $new_tx['Hash'] = $tx_hash;
+ $new_tx['Value'] = $total_tx_value;
+ $new_tx['Raw'] = $raw_tx;
+
+
+ $tx_entity = $this->Transactions->newEntity($new_tx);
+ $conn->execute('INSERT INTO Transactions (Version, LockTime, BlockHash, TransactionTime, InputCount, OutputCount, TransactionSize, Hash, Value, Raw, Created, Modified) VALUES ' .
+ '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(), UTC_TIMESTAMP())',
+ [
+ $new_tx['Version'],
+ $new_tx['LockTime'],
+ isset($new_tx['BlockHash']) ? $new_tx['BlockHash'] : null,
+ isset($new_tx['TransactionTime']) ? $new_tx['TransactionTime'] : null,
+ $new_tx['InputCount'],
+ $new_tx['OutputCount'],
+ $new_tx['TransactionSize'],
+ $new_tx['Hash'],
+ $new_tx['Value'],
+ $new_tx['Raw']
+ ]);
+ $stmt = $conn->execute('SELECT LAST_INSERT_ID() AS txnId');
+ $linsert = $stmt->fetch(\PDO::FETCH_OBJ);
+ $tx_entity->Id = $linsert->txnId;
+ if ($tx_entity->Id === 0) {
+ 3;
+ } else {
+ $numeric_tx_id = $tx_entity->Id;
+ }
+ }
+
+ if (!$data_error && $numeric_tx_id > 0) {
+ // Create the inputs
+ $inputs = $all_tx_data['inputs'];
+ $outputs = $all_tx_data['outputs'];
+
+ foreach ($inputs as $in) {
+ $in['TransactionId'] = $numeric_tx_id;
+ $in['TransactionHash'] = $tx_hash;
+
+ if (isset($in['IsCoinbase']) && $in['IsCoinbase'] === 1) {
+ $in_entity = $this->Inputs->newEntity($in);
+ $res = $this->Inputs->save($in_entity);
+ if (!$res) {
+ $data_error = true;
+ break;
+ }
+ } else {
+ $in_tx_hash = $in['PrevoutHash'];
+ $in_prevout = $in['PrevoutN'];
+
+ // Find the corresponding previous output
+ $in_tx = $this->Transactions->find()->select(['Id'])->where(['Hash' => $in_tx_hash])->first();
+ $src_output = null;
+ if ($in_tx) {
+ $stmt = $conn->execute('SELECT Id, Value, Addresses FROM Outputs WHERE TransactionId = ? AND Vout = ?', [$in_tx->Id, $in_prevout]);
+ $src_output = $stmt->fetch(\PDO::FETCH_OBJ);
+ if ($src_output) {
+ $in['Value'] = $src_output->Value;
+ $json_addr = json_decode($src_output->Addresses);
+ $in_addr_id = 0;
+ if (isset($addr_id_map[$json_addr[0]])) {
+ $in['AddressId'] = $addr_id_map[$json_addr[0]];
+ } else {
+ $in_addr = $this->Addresses->find()->select(['Id'])->where(['Address' => $json_addr[0]])->first();
+ if ($in_addr) {
+ $addr_id_map[$json_addr[0]] = $in_addr->Id;
+ $in['AddressId'] = $in_addr->Id;
+ }
+ }
+ }
+ }
+
+ $in_entity = $this->Inputs->newEntity($in);
+ $conn->execute('INSERT INTO Inputs (TransactionId, TransactionHash, AddressId, PrevoutHash, PrevoutN, Sequence, Value, ScriptSigAsm, ScriptSigHex, Created, Modified) ' .
+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(), UTC_TIMESTAMP())',
+ [$in['TransactionId'],
+ $in['TransactionHash'],
+ isset($in['AddressId']) ? $in['AddressId'] : null,
+ $in['PrevoutHash'],
+ $in['PrevoutN'],
+ $in['Sequence'],
+ isset($in['Value']) ? $in['Value'] : 0,
+ $in['ScriptSigAsm'],
+ $in['ScriptSigHex']
+ ]);
+
+ // get last insert id
+ $stmt = $conn->execute('SELECT LAST_INSERT_ID() AS inputId');
+ $linsert = $stmt->fetch(\PDO::FETCH_OBJ);
+ $in_entity->Id = $linsert->inputId;
+
+ if ($in_entity->Id === 0) {
+ $data_error = true;
+ break;
+ }
+
+ // Update the src_output spent if successful
+ if ($src_output) {
+ try {
+ $conn->execute('UPDATE Outputs SET IsSpent = 1, SpentByInputId = ? WHERE Id = ?', [$in_entity->Id, $src_output->Id]);
+ $conn->execute('UPDATE Inputs SET PrevoutSpendUpdated = 1 WHERE Id = ?', [$in_entity->Id]);
+ } catch (\Exception $e) {
+ $data_error = true;
+ break;
+ }
+ }
+
+ if (isset($in['AddressId']) && $in['AddressId'] > 0) {
+ $addr_id = $in['AddressId'];
+ if (!isset($addr_id_drcr[$addr_id])) {
+ $addr_id_drcr[$addr_id] = ['debit' => 0, 'credit' => 0];
+ }
+ $addr_id_drcr[$addr_id]['debit'] = bcadd($addr_id_drcr[$addr_id]['debit'], $in['Value'], 8);
+
+ try {
+ $conn->execute('INSERT INTO InputsAddresses (InputId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE InputId = InputId', [$in_entity->Id, $in['AddressId']]);
+ $conn->execute('UPDATE Addresses SET TotalSent = TotalSent + ? WHERE Id = ?', [$in['Value'], $in['AddressId']]);
+ $conn->execute('INSERT INTO TransactionsAddresses (TransactionId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE TransactionId = TransactionId', [$numeric_tx_id, $in['AddressId']]);
+ } catch (\Exception $e) {
+ $data_error = true;
+ break;
+ }
+ }
+ }
+ }
+
+ foreach ($outputs as $out) {
+ $out['TransactionId'] = $numeric_tx_id;
+ $out_entity = $this->Outputs->newEntity($out);
+
+ //$stmt->execute('INSERT INTO Outputs')
+ $conn->execute('INSERT INTO Outputs (TransactionId, Vout, Value, Type, ScriptPubKeyAsm, ScriptPubKeyHex, RequiredSignatures, Hash160, Addresses, Created, Modified) '.
+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(), UTC_TIMESTAMP())',
+ [$out['TransactionId'],
+ $out['Vout'],
+ $out['Value'],
+ $out['Type'],
+ $out['ScriptPubKeyAsm'],
+ $out['ScriptPubKeyHex'],
+ $out['RequiredSignatures'],
+ $out['Hash160'],
+ $out['Addresses']
+ ]);
+
+ // get the last insert id
+ $stmt = $conn->execute('SELECT LAST_INSERT_ID() AS outputId');
+ $linsert = $stmt->fetch(\PDO::FETCH_OBJ);
+ $out_entity->Id = $linsert->outputId;
+
+ if ($out_entity->Id === 0) {
+ $data_error = true;
+ break;
+ }
+
+ $json_addr = json_decode($out['Addresses']);
+ $out_addr_id = 0;
+ if (isset($addr_id_map[$json_addr[0]])) {
+ $out_addr_id = $addr_id_map[$json_addr[0]];
+ } else {
+ $out_addr = $this->Addresses->find()->select(['Id'])->where(['Address' => $json_addr[0]])->first();
+ if ($out_addr) {
+ $addr_id_map[$json_addr[0]] = $out_addr->Id;
+ $out_addr_id = $out_addr->Id;
+ }
+ }
+
+ if ($out_addr_id > 0) {
+ $addr_id = $out_addr_id;
+ if (!isset($addr_id_drcr[$addr_id])) {
+ $addr_id_drcr[$addr_id] = ['debit' => 0, 'credit' => 0];
+ }
+ $addr_id_drcr[$addr_id]['credit'] = bcadd($addr_id_drcr[$addr_id]['credit'], $out['Value'], 8);
+
+ try {
+ $conn->execute('INSERT INTO OutputsAddresses (OutputId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE OutputId = OutputId', [$out_entity->Id, $out_addr_id]);
+ $conn->execute('UPDATE Addresses SET TotalReceived = TotalReceived + ? WHERE Id = ?', [$out['Value'], $out_addr_id]);
+ $conn->execute('INSERT INTO TransactionsAddresses (TransactionId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE TransactionId = TransactionId', [$numeric_tx_id, $out_addr_id]);
+ } catch (\Exception $e) {
+ print_r($e);
+ $data_error = true;
+ break;
+ }
+ }
+
+ // create the claim if the asm pub key starts with OP_CLAIM_NAME
+ if (strpos($out['ScriptPubKeyAsm'], 'OP_CLAIM_NAME') !== false) {
+ $all_claim_data = $this->_getclaimfortxout($out['ScriptPubKeyAsm'], $tx_hash, $out['Vout'], $block_ts);
+ $claim = $all_claim_data['claim_data'];
+ $claim_stream_data = $all_claim_data['claim_stream_data'];
+
+ if (!$claim) {
+ continue;
+ }
+
+ if ($claim['ClaimType'] == 2 && !$claim_stream_data) {
+ echo "***claim stream data missing for streamType claim\n";
+ continue;
+ }
+
+ $claim_entity = $this->Claims->newEntity($claim);
+ $res = $this->Claims->save($claim_entity);
+
+ if (!$res) {
+ echo "***claim could not be saved.\n";
+ continue;
+ }
+
+ if (!$data_error && $claim_stream_data) {
+ $claim_stream_data['Id'] = $claim_entity->Id;
+ $claim_stream_entity = $this->ClaimStreams->newEntity($claim_stream_data);
+ $res = $this->ClaimStreams->save($claim_stream_entity);
+ if (!$res) {
+ echo "***claim stream could not be saved.\n";
+ }
+ }
+ }
+ }
+ }
+
+ // update tx amounts
+ if (!$data_error) {
+ foreach ($addr_id_drcr as $addr_id => $drcr) {
+ try {
+ $conn->execute('UPDATE TransactionsAddresses SET DebitAmount = ?, CreditAmount = ?, TransactionTime = UTC_TIMESTAMP() WHERE TransactionId = ? AND AddressId = ?',
+ [$drcr['debit'], $drcr['credit'], $numeric_tx_id, $addr_id]);
+ } catch (Exception $e) {
+ print_r($e);
+ $data_error = true;
+ break;
+ }
+ }
+ }
+ }
+
+ public function parsetxs() {
+ set_time_limit(0);
+
+ self::lock('parsetxs');
+
+ // Get the minimum block with no processed transactions
+ echo "Parsing transactions...\n";
+
+ $conn = ConnectionManager::get('default');
+ //$conn->execute('SET foreign_key_checks = 0');
+ //$conn->execute('SET unique_checks = 0');
+
+ $redis = self::_init_redis();
+ try {
+ $unproc_blocks = $this->Blocks->find()->select(['Id', 'Height', 'Hash', 'TransactionHashes', 'BlockTime'])->where(['TransactionsProcessed' => 0])->order(['Height' => 'asc'])->toArray();
+ foreach ($unproc_blocks as $min_block) {
+ $tx_hashes = json_decode($min_block->TransactionHashes);
+ if ($tx_hashes && is_array($tx_hashes)) {
+ $block_time = $min_block->BlockTime;
+ $block_ts = \DateTime::createFromFormat('U', $block_time);
+
+ $count = count($tx_hashes);
+ echo "Processing " . $count . " transaction(s) for block $min_block->Height ($min_block->Hash)...\n";
+
+ $data_error = false;
+ $conn->begin();
+
+ $idx = 0;
+ foreach ($tx_hashes as $tx_hash) {
+ $idx++;
+ $idx_str = str_pad($idx, strlen($count), '0', STR_PAD_LEFT);
+ echo "[$idx_str/$count] Processing tx hash: $tx_hash... ";
+
+ $total_diff = 0;
+ $start_ms = round(microtime(true) * 1000);
+ $exist_tx = $this->Transactions->find()->select(['Id'])->where(['Hash' => $tx_hash])->first();
+ $end_ms = round(microtime(true) * 1000);
+ $diff_ms = $end_ms - $start_ms;
+ $total_diff += $diff_ms;
+ echo "findtx took {$diff_ms}ms. ";
+
+ if ($exist_tx) {
+ echo "Exists. Skipping.\n";
+ continue;
+ }
+
+ $start_ms = round(microtime(true) * 1000);
+ $this->processtx($tx_hash, $block_ts, ['hash' => $min_block->Hash, 'time' => $min_block->BlockTime], $data_error);
+ $diff_ms = round(microtime(true) * 1000) - $start_ms;
+ $total_diff += $diff_ms;
+ echo "tx took {$diff_ms}ms. Total {$total_diff}ms. ";
+
+ if (!$data_error && $redis && $redis->sismember(self::mempooltxkey, $tx_hash)) {
+ $redis->srem(self::mempooltxkey, $tx_hash);
+ echo "Removed $tx_hash from redis mempooltx.\n";
+ }
+
+ echo "Done.\n";
+ }
+
+ if (!$data_error) {
+ $conn->execute('UPDATE Blocks SET TransactionsProcessed = 1 WHERE Id = ?', [$min_block->Id]);
+ }
+
+ if ($data_error) {
+ echo "Rolling back!\n";
+ $conn->rollback();
+ throw new \Exception('Data save failed!');
+ } else {
+ echo "Data committed.\n";
+ $conn->commit();
+ }
+ }
+ }
+
+ // Try to update txs with null BlockHash
+ $mempooltx = $this->Transactions->find()->select(['Id', 'Hash'])->where(['BlockHash IS' => null])->order(['Created' => 'asc'])->toArray();
+ $idx = 0;
+ $count = count($mempooltx);
+ foreach ($mempooltx as $tx) {
+ $idx++;
+ $tx_hash = $tx->Hash;
+ $idx_str = ($count > 10 && $idx < 10) ? '0' . $idx : $idx;
+ echo "[$idx_str/$count] Processing tx hash: $tx_hash... ";
+
+ $stmt = $conn->execute("SELECT Hash, BlockTime FROM Blocks WHERE TransactionHashes LIKE CONCAT('%', ?, '%') AND Height > ((SELECT MAX(Height) FROM Blocks) - 10000) ORDER BY Height ASC LIMIT 1", [$tx_hash]);
+ $block = $stmt->fetch(\PDO::FETCH_OBJ);
+ if ($block) {
+ $upd_tx = ['Id' => $tx->Id, 'BlockHash' => $block->Hash, 'TransactionTime' => $block->BlockTime];
+ $upd_entity = $this->Transactions->newEntity($upd_tx);
+ $this->Transactions->save($upd_entity);
+ echo "Done.\n";
+
+ if ($redis && $redis->sismember(self::mempooltxkey, $tx_hash)) {
+ $redis->srem(self::mempooltxkey, $tx_hash);
+ echo "Removed $tx_hash from redis mempooltx.\n";
+ }
+ } else {
+ echo "Block not found.\n";
+ }
+ }
+ } catch (\Exception $e) {
+ print_r($e);
+ }
+
+ //$conn->execute('SET foreign_key_checks = 1');
+ //$conn->execute('SET unique_checks = 1');
+
+ self::unlock('parsetxs');
+ }
+
+ public function parsenewblocks() {
+ set_time_limit(0);
+ self::lock('parsenewblocks');
+
+ echo "Parsing new blocks...\n";
+ $redis = self::_init_redis();
+ try {
+ // Get the best block hash
+ $req = ['method' => 'getbestblockhash', 'params' => []];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $best_hash = $json->result;
+
+ $req = ['method' => 'getblock', 'params' => [$best_hash]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $best_block = $json->result;
+
+ $max_block = $this->Blocks->find()->select(['Hash', 'Height'])->order(['Height' => 'desc'])->first();
+ if (!$max_block) {
+ self::unlock('parsenewblocks');
+ return;
+ }
+
+ $min_height = min($max_block->Height, $best_block->height);
+ $max_height = max($max_block->Height, $best_block->height);
+ $height_diff = $best_block->height - $max_block->Height;
+
+ if ($height_diff <= 0) {
+ self::unlock('parsenewblocks');
+ return;
+ }
+
+ $conn = ConnectionManager::get('default');
+ for ($curr_height = $min_height; $curr_height <= $max_height; $curr_height++) {
+ // get the block hash
+ $req = ['method' => 'getblockhash', 'params' => [$curr_height]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $curr_block_hash = $json->result;
+
+ $next_block_hash = null;
+ if ($curr_height < $max_height) {
+ $req = ['method' => 'getblockhash', 'params' => [$curr_height + 1]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $next_block_hash = $json->result;
+ }
+
+ $req = ['method' => 'getblock', 'params' => [$curr_block_hash]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $curr_block = $json->result;
+
+ if ($curr_block->confirmations < 0) {
+ continue;
+ }
+
+ $next_block = null;
+ if ($next_block_hash != null) {
+ $req = ['method' => 'getblock', 'params' => [$next_block_hash]];
+ $response = self::curl_json_post(self::rpcurl, json_encode($req));
+ $json = json_decode($response);
+ $next_block = $json->result;
+ }
+
+ if ($curr_block != null) {
+ $curr_block_ins = $this->blockdb_data_from_json($curr_block);
+ if ($next_block != null && $curr_block_ins['NextBlockHash'] == null) {
+ $curr_block_ins['NextBlockHash'] = $next_block->hash;
+ }
+
+ $block_data = $curr_block;
+ $block_id = -1;
+ // Make sure the block does not exist before inserting
+ $old_block = $this->Blocks->find()->select(['Id'])->where(['Hash' => $block_data->hash])->first();
+ if (!$old_block) {
+ echo "Inserting block $block_data->height ($block_data->hash)... ";
+ $curr_block_entity = $this->Blocks->newEntity($curr_block_ins);
+
+ $conn->execute('INSERT INTO Blocks (Bits, Chainwork, Confirmations, Difficulty, Hash, Height, MedianTime, MerkleRoot, NameClaimRoot, Nonce, PreviousBlockHash, NextBlockHash, BlockSize, Target, BlockTime, TransactionHashes, Version, VersionHex, Created, Modified) ' .
+ 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, UTC_TIMESTAMP(), UTC_TIMESTAMP())',
+ [
+ $curr_block_entity->Bits,
+ $curr_block_entity->Chainwork,
+ $curr_block_entity->Confirmations,
+ $curr_block_ins['Difficulty'], // cakephp 3 why?
+ $curr_block_entity->Hash,
+ $curr_block_entity->Height,
+ $curr_block_entity->MedianTime,
+ $curr_block_entity->MerkleRoot,
+ $curr_block_entity->NameClaimRoot,
+ $curr_block_entity->Nonce,
+ $curr_block_entity->PreviousBlockHash,
+ $curr_block_entity->NextBlockHash,
+ $curr_block_entity->BlockSize,
+ $curr_block_entity->Target,
+ $curr_block_entity->BlockTime,
+ $curr_block_entity->TransactionHashes,
+ $curr_block_entity->Version,
+ $curr_block_entity->VersionHex,
+ ]);
+
+ $stmt = $conn->execute('SELECT LAST_INSERT_ID() AS lBlockId');
+ $linsert = $stmt->fetch(\PDO::FETCH_OBJ);
+ $curr_block_entity->Id = $linsert->lBlockId;
+ $block_id = $curr_block_entity->Id;
+
+ echo "Done.\n";
+ } else {
+ echo "Updating block $block_data->height ($block_data->hash) with next block hash: " . $curr_block_ins['NextBlockHash'] . " and confirmations: " . $curr_block_ins['Confirmations'] . "... ";
+ $upd_block = ['Id' => $old_block->Id, 'NextBlockHash' => $curr_block_ins['NextBlockHash'], 'Confirmations' => $curr_block_ins['Confirmations']];
+ $upd_entity = $this->Blocks->newEntity($upd_block);
+ $block_id = $old_block->Id;
+ echo "Done.\n";
+ }
+
+ $txs = $block_data->tx;
+ $data_error = false;
+ foreach ($txs as $tx_hash) {
+ // Check if the transactions exist and then update the BlockHash and TxTime
+ $tx = $this->Transactions->find()->select(['Id'])->where(['Hash' => $tx_hash])->first();
+ if ($tx) {
+ $upd_tx_data = [
+ 'Id' => $tx->Id,
+ 'BlockHash' => $block_data->hash,
+ 'TransactionTime' => $block_data->time
+ ];
+ $upd_tx_entity = $this->Transactions->newEntity($upd_tx_data);
+ $this->Transactions->save($upd_tx_entity);
+ echo "Updated tx $tx_hash with block hash and time $block_data->time.\n";
+ } else {
+ // Doesn't exist, create a new transaction
+ echo "Inserting tx $tx_hash for block height $block_data->height... ";
+
+ $conn->begin();
+ $block_ts = \DateTime::createFromFormat('U', $block_data->time);
+ $this->processtx($tx_hash, $block_ts, ['hash' => $block_data->hash, 'time' => $block_data->time], $data_error);
+
+ if ($data_error) {
+ $conn->rollback();
+ echo "Insert failed.\n";
+ } else {
+ $conn->commit();
+ echo "Done.\n";
+ }
+ }
+
+ // Remove from redis if present
+ if (!$data_error && $redis && $redis->sismember(self::mempooltxkey, $tx_hash)) {
+ $redis->srem(self::mempooltxkey, $tx_hash);
+ echo "Removed $tx_hash from redis mempooltx.\n";
+ }
+ }
+
+ if (!$data_error && $block_id > -1) {
+ // set TransactionsProcessed to true
+ $conn->execute('UPDATE Blocks SET TransactionsProcessed = 1 WHERE Id = ?', [$block_id]);
+ }
+ }
+ }
+ } catch (\Exception $e) {
+ print_r($e);
+ }
+
+ self::unlock('parsenewblocks');
+ }
+
+ public function forevermempool() {
+ self::lock('forevermempool');
+
+ $conn = ConnectionManager::get('default');
+ $redis = self::_init_redis();
+
+ while (true) {
+ try {
+ $data = ['method' => 'getrawmempool', 'params' => []];
+ $res = self::curl_json_post(self::rpcurl, json_encode($data));
+ $json = json_decode($res);
+ $txs = $json->result;
+ $now = new \DateTime('now', new \DateTimeZone('UTC'));
+ $data_error = false;
+
+ if (count($txs) === 0) {
+ // If no transactions found, that means there's nothing in the mempool. Clear redis
+ if ($redis) {
+ $redis->del(self::mempooltxkey);
+ echo "Empty rawmempool. Cleared mempool txs from redis.\n";
+ }
+ }
+
+ foreach ($txs as $tx_hash) {
+ // Check redis mempool txs
+ if ($redis && $redis->exists(self::mempooltxkey)) {
+ if ($redis->sismember(self::mempooltxkey, $tx_hash)) {
+ echo "Found processed tx hash: $tx_hash. Skipping.\n";
+ continue;
+ }
+ }
+
+ echo "Processing tx hash: $tx_hash... ";
+ $exist_tx = $this->Transactions->find()->select(['Id'])->where(['Hash' => $tx_hash])->first();
+ if ($exist_tx) {
+ echo "Exists. Skipping.\n";
+ continue;
+ }
+
+ // Process the tx
+ $conn->begin();
+ $block_ts = new \DateTime('now', new \DateTimeZone('UTC'));
+ $this->processtx($tx_hash, $block_ts, null, $data_error);
+
+ if ($data_error) {
+ echo "Rolling back!\n";
+ $conn->rollback();
+ throw new \Exception('Data save failed!');
+ } else {
+ echo "Data committed.\n";
+ $conn->commit();
+
+ // Save to redis to prevent the DB from behing hit again
+ if ($redis) {
+ $redis->sadd(self::mempooltxkey, $tx_hash);
+ }
+ }
+ }
+ } catch (\Exception $e) {
+ echo "Error occurred processing mempool: " . $e->getMessage() . "\n";
+ }
+
+ echo "*******************\n";
+ sleep(1);
+ }
+
+ self::unlock('forevermempool');
+ }
+
+ private function txdb_data_from_decoded($decoded_tx) {
+ $tx = [
+ 'Version' => $decoded_tx['version'],
+ 'LockTime' => $decoded_tx['locktime']
+ ];
+
+ $addresses = [];
+ $inputs = [];
+ $outputs = [];
+
+ $vin = $decoded_tx['vin'];
+ $vout = $decoded_tx['vout'];
+ if (is_array($vin)) {
+ foreach ($vin as $in) {
+ if (isset($in['coinbase'])) {
+ $inputs[] = [
+ 'IsCoinbase' => 1,
+ 'Coinbase' => $in['coinbase']
+ ];
+ } else {
+ $inputs[] = [
+ 'PrevoutHash' => $in['txid'],
+ 'PrevoutN' => $in['vout'],
+ 'ScriptSigAsm' => $in['scriptSig']['asm'],
+ 'ScriptSigHex' => $in['scriptSig']['hex'],
+ 'Sequence' => $in['sequence']
+ ];
+ }
+ }
+
+ foreach ($vout as $out) {
+ $outputs[] = [
+ 'Vout' => $out['vout'],
+ 'Value' => bcdiv($out['value'], 100000000, 8),
+ 'Type' => isset($out['scriptPubKey']['type']) ? $out['scriptPubKey']['type'] : '',
+ 'ScriptPubKeyAsm' => isset($out['scriptPubKey']['asm']) ? $out['scriptPubKey']['asm'] : '',
+ 'ScriptPubKeyHex' => isset($out['scriptPubKey']['hex']) ? $out['scriptPubKey']['hex'] : '',
+ 'RequiredSignatures' => isset($out['scriptPubKey']['reqSigs']) ? $out['scriptPubKey']['reqSigs'] : '',
+ 'Hash160' => isset($out['scriptPubKey']['hash160']) ? $out['scriptPubKey']['hash160'] : '',
+ 'Addresses' => isset($out['scriptPubKey']['addresses']) ? json_encode($out['scriptPubKey']['addresses']) : null
+ ];
+
+ if (isset($out['scriptPubKey']['addresses'])) {
+ foreach ($out['scriptPubKey']['addresses'] as $address) {
+ $addresses[$address] = $address;
+ }
+ }
+ }
+ }
+
+ return ['tx' => $tx, 'addresses' => $addresses, 'inputs' => $inputs, 'outputs' => $outputs];
+ }
+
+ private function blockdb_data_from_json($json_block) {
+ return [
+ 'Bits' => $json_block->bits,
+ 'Chainwork' => $json_block->chainwork,
+ 'Confirmations' => $json_block->confirmations,
+ 'Difficulty' => $json_block->difficulty,
+ 'Hash' => $json_block->hash,
+ 'Height' => $json_block->height,
+ 'MedianTime' => $json_block->mediantime,
+ 'MerkleRoot' => $json_block->merkleroot,
+ 'NameClaimRoot' => $json_block->nameclaimroot,
+ 'Nonce' => $json_block->nonce,
+ 'PreviousBlockHash' => isset($json_block->previousblockhash) ? $json_block->previousblockhash : null,
+ 'NextBlockHash' => isset($json_block->nextblockhash) ? $json_block->nextblockhash : null,
+ 'BlockSize' => $json_block->size,
+ 'Target' => $json_block->target,
+ 'BlockTime' => $json_block->time,
+ 'TransactionHashes' => json_encode($json_block->tx),
+ 'Version' => $json_block->version,
+ 'VersionHex' => $json_block->versionHex
+ ];
+ }
+
+ private static function curl_json_post($url, $data, $headers = []) {
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ $response = curl_exec($ch);
+ //Log::debug('Request execution completed.');
+ if ($response === false) {
+ $error = curl_error($ch);
+ $errno = curl_errno($ch);
+ curl_close($ch);
+
+ throw new \Exception(sprintf('The request failed: %s', $error), $errno);
+ } else {
+ curl_close($ch);
+ }
+
+ // Close any open file handle
+ return $response;
+ }
+
+ private static function curl_json_get($url, $headers = []) {
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+ $response = curl_exec($ch);
+ //Log::debug('Request execution completed.');
+ if ($response === false) {
+ $error = curl_error($ch);
+ $errno = curl_errno($ch);
+ curl_close($ch);
+
+ throw new \Exception(sprintf('The request failed: %s', $error), $errno);
+ } else {
+ curl_close($ch);
+ }
+
+ // Close any open file handle
+ return $response;
+ }
+
+ private static $base58chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
+
+ public static $op_codes = [
+ ['OP_0', 0],
+ ['OP_PUSHDATA', 76],
+ 'OP_PUSHDATA2',
+ 'OP_PUSHDATA4',
+ 'OP_1NEGATE',
+ 'OP_RESERVED',
+ 'OP_1',
+ 'OP_2',
+ 'OP_3',
+ 'OP_4',
+ 'OP_5',
+ 'OP_6',
+ 'OP_7',
+ 'OP_8', 'OP_9', 'OP_10', 'OP_11', 'OP_12', 'OP_13', 'OP_14', 'OP_15', 'OP_16',
+ 'OP_NOP', 'OP_VER', 'OP_IF', 'OP_NOTIF', 'OP_VERIF', 'OP_VERNOTIF', 'OP_ELSE', 'OP_ENDIF', 'OP_VERIFY',
+ 'OP_RETURN', 'OP_TOALTSTACK', 'OP_FROMALTSTACK', 'OP_2DROP', 'OP_2DUP', 'OP_3DUP', 'OP_2OVER', 'OP_2ROT', 'OP_2SWAP',
+ 'OP_IFDUP', 'OP_DEPTH', 'OP_DROP', 'OP_DUP', 'OP_NIP', 'OP_OVER', 'OP_PICK', 'OP_ROLL', 'OP_ROT',
+ 'OP_SWAP', 'OP_TUCK', 'OP_CAT', 'OP_SUBSTR', 'OP_LEFT', 'OP_RIGHT', 'OP_SIZE', 'OP_INVERT', 'OP_AND',
+ 'OP_OR', 'OP_XOR', 'OP_EQUAL', 'OP_EQUALVERIFY', 'OP_RESERVED1', 'OP_RESERVED2', 'OP_1ADD', 'OP_1SUB', 'OP_2MUL',
+ 'OP_2DIV', 'OP_NEGATE', 'OP_ABS', 'OP_NOT', 'OP_0NOTEQUAL', 'OP_ADD', 'OP_SUB', 'OP_MUL', 'OP_DIV',
+ 'OP_MOD', 'OP_LSHIFT', 'OP_RSHIFT', 'OP_BOOLAND', 'OP_BOOLOR',
+ 'OP_NUMEQUAL', 'OP_NUMEQUALVERIFY', 'OP_NUMNOTEQUAL', 'OP_LESSTHAN',
+ 'OP_GREATERTHAN', 'OP_LESSTHANOREQUAL', 'OP_GREATERTHANOREQUAL', 'OP_MIN', 'OP_MAX',
+ 'OP_WITHIN', 'OP_RIPEMD160', 'OP_SHA1', 'OP_SHA256', 'OP_HASH160',
+ 'OP_HASH256', 'OP_CODESEPARATOR', 'OP_CHECKSIG', 'OP_CHECKSIGVERIFY', 'OP_CHECKMULTISIG',
+ 'OP_CHECKMULTISIGVERIFY', 'OP_NOP1', 'OP_NOP2', 'OP_NOP3', 'OP_NOP4', 'OP_NOP5', 'OP_CLAIM_NAME',
+ 'OP_SUPPORT_CLAIM', 'OP_UPDATE_CLAIM',
+ ['OP_SINGLEBYTE_END', 0xF0],
+ ['OP_DOUBLEBYTE_BEGIN', 0xF000],
+ 'OP_PUBKEY', 'OP_PUBKEYHASH',
+ ['OP_INVALIDOPCODE', 0xFFFF]
+ ];
+
+ public static $op_code = array(
+ '00' => 'OP_0', // or OP_FALSE
+ '51' => 'OP_1', // or OP_TRUE
+ '61' => 'OP_NOP',
+ '6a' => 'OP_RETURN',
+ '6d' => 'OP_2DROP',
+ '75' => 'OP_DROP',
+ '76' => 'OP_DUP',
+ '87' => 'OP_EQUAL',
+ '88' => 'OP_EQUALVERIFY',
+ 'a6' => 'OP_RIPEMD160',
+ 'a7' => 'OP_SHA1',
+ 'a8' => 'OP_SHA256',
+ 'a9' => 'OP_HASH160',
+ 'aa' => 'OP_HASH256',
+ 'ac' => 'OP_CHECKSIG',
+ 'ae' => 'OP_CHECKMULTISIG',
+ 'b5' => 'OP_CLAIM_NAME',
+ 'b6' => 'OP_SUPPORT_CLAIM',
+ 'b7' => 'OP_UPDATE_CLAIM'
+ );
+
+ /*protected static function hash160_to_bc_address($h160, $addrType = 0) {
+ $vh160 = $c . $h160;
+ $h = self::_dhash($vh160);
+
+ $addr = $vh160 . substr($h, 0, 4);
+ return $addr;
+ //return self::base58_encode($addr);
+ }*/
+
+ protected static function _dhash($str, $raw = false) {
+ return hash('sha256', hash('sha256', $str, true), $raw);
+ }
+
+ public static function _get_vint(&$string)
+ {
+ // Load the next byte, convert to decimal.
+ $decimal = hexdec(self::_return_bytes($string, 1));
+ // Less than 253: Not encoding extra bytes.
+ // More than 253, work out the $number of bytes using the 2^(offset)
+ $num_bytes = ($decimal < 253) ? 0 : 2 ^ ($decimal - 253);
+ // Num_bytes is 0: Just return the decimal
+ // Otherwise, return $num_bytes bytes (order flipped) and converted to decimal
+ return ($num_bytes == 0) ? $decimal : hexdec(self::_return_bytes($string, $num_bytes, true));
+ }
+
+ public static function hash160($string)
+ {
+ $bs = @pack("H*", $string);
+ return hash("ripemd160", hash("sha256", $bs, true));
+ }
+
+ public static function hash256($string)
+ {
+ $bs = @pack("H*", $string);
+ return hash("sha256", hash("sha256", $bs, true));
+ }
+
+ public static function hash160_to_address($hash160, $address_version = null)
+ {
+ $c = '';
+ if ($address_version == self::pubKeyAddress[0]) {
+ $c = dechex(self::pubKeyAddress[1]);
+ } else if ($address_version == self::scriptAddress[0]) {
+ $c = dechex(self::scriptAddress[1]);
+ }
+
+ $hash160 = $c . $hash160;
+ $addr = $hash160;
+ return self::base58_encode_checksum($addr);
+ }
+
+ public static function base58_encode_checksum($hex)
+ {
+ $checksum = self::hash256($hex);
+ $checksum = substr($checksum, 0, 8);
+ $hash = $hex . $checksum;
+ return self::base58_encode($hash);
+ }
+
+ public static function _decode_script($script)
+ {
+ $pos = 0;
+ $data = array();
+ while ($pos < strlen($script)) {
+ $code = hexdec(substr($script, $pos, 2)); // hex opcode.
+ $pos += 2;
+ if ($code < 1) {
+ // OP_FALSE
+ $push = '0';
+ } elseif ($code <= 75) {
+ // $code bytes will be pushed to the stack.
+ $push = substr($script, $pos, ($code * 2));
+ $pos += $code * 2;
+ } elseif ($code <= 78) {
+ // In this range, 2^($code-76) is the number of bytes to take for the *next* number onto the stack.
+ $szsz = pow(2, $code - 75); // decimal number of bytes.
+ $sz = hexdec(substr($script, $pos, ($szsz * 2))); // decimal number of bytes to load and push.
+ $pos += $szsz;
+ $push = substr($script, $pos, ($pos + $sz * 2)); // Load the data starting from the new position.
+ $pos += $sz * 2;
+ } elseif ($code <= 108/*96*/) {
+ // OP_x, where x = $code-80
+ $push = ($code - 80);
+ } else {
+ $push = $code;
+ }
+ $data[] = $push;
+ }
+
+ return implode(" ", $data);
+ }
+
+ /*public static function script_getopname($bytes_hex) {
+ $index = hexdec($bytes_hex) - 75;
+ $op = self::$op_codes[$index];
+ if (is_array($op)) {
+ if ($bytes_hex == dechex($op[1])) {
+ return $op[0];
+ }
+ }
+ if ()
+
+ return str_replace('OP_', '', $op);
+ }*/
+
+ public static function get_opcode($opname) {
+ $len = count(self::$op_codes);
+ for ($i = 0; $i < $len; $i++) {
+ $op = self::$op_codes[$i];
+ $op = is_array($op) ? $op[0] : $op;
+ if ($op === $opname) {
+ return $i;
+ }
+ }
+
+ return null;
+ }
+
+ public static function match_decoded($decoded, $to_match) {
+ if (strlen($decoded) != strlen($to_match)) {
+ return false;
+ }
+
+ for ($i = 0; $i < count($decoded); $i++) {
+ $pushdata4 = self::get_opcode('OP_PUSHDATA4');
+ if ($to_match[$i] == $pushdata4 && ($pushdata4 >= $decoded[$i][0]) > 0) {
+ continue;
+ }
+ if ($to_match[$i] != $decoded[$i][0]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public static function base58_encode($hex)
+ {
+ if (strlen($hex) == 0) {
+ return '';
+ }
+ // Convert the hex string to a base10 integer
+ $num = gmp_strval(gmp_init($hex, 16), 58);
+ // Check that number isn't just 0 - which would be all padding.
+ if ($num != '0') {
+ $num = strtr($num, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv', self::$base58chars);
+ } else {
+ $num = '';
+ }
+ // Pad the leading 1's
+ $pad = '';
+ $n = 0;
+ while (substr($hex, $n, 2) == '00') {
+ $pad .= '1';
+ $n += 2;
+ }
+ return $pad . $num;
+ }
+
+ public static function decode_tx($raw_transaction)
+ {
+ $math = EccFactory::getAdapter();
+ /*$magic_byte = BitcoinLib::magicByte($magic_byte);
+ $magic_p2sh_byte = BitcoinLib::magicP2SHByte($magic_p2sh_byte);*/
+ $raw_transaction = trim($raw_transaction);
+ if (((bool)preg_match('/^[0-9a-fA-F]{2,}$/i', $raw_transaction) !== true)
+ || (strlen($raw_transaction)) % 2 !== 0
+ ) {
+ throw new \InvalidArgumentException("Raw transaction is invalid hex");
+ }
+ $txHash = hash('sha256', hash('sha256', pack("H*", trim($raw_transaction)), true));
+ $txid = self::_flip_byte_order($txHash);
+ $info = array();
+ $info['txid'] = $txid;
+ $info['version'] = $math->hexDec(self::_return_bytes($raw_transaction, 4, true));
+ /*if (!in_array($info['version'], array('0', '1'))) {
+ throw new \InvalidArgumentException("Invalid transaction version");
+ }*/
+ $input_count = self::_get_vint($raw_transaction);
+ if (!($input_count >= 0 && $input_count <= 4294967296)) {
+ throw new \InvalidArgumentException("Invalid input count");
+ }
+ $info['vin'] = self::_decode_inputs($raw_transaction, $input_count);
+ if ($info['vin'] == false) {
+ throw new \InvalidArgumentException("No inputs in transaction");
+ }
+ $output_count = self::_get_vint($raw_transaction);
+ if (!($output_count >= 0 && $output_count <= 4294967296)) {
+ throw new \InvalidArgumentException("Invalid output count");
+ }
+ $info['vout'] = self::_decode_outputs($raw_transaction, $output_count);
+ $info['locktime'] = $math->hexDec(self::_return_bytes($raw_transaction, 4));
+ return $info;
+ }
+
+ public static function _decode_inputs(&$raw_transaction, $input_count)
+ {
+ $inputs = array();
+ // Loop until $input count is reached, sequentially removing the
+ // leading data from $raw_transaction reference.
+ for ($i = 0; $i < $input_count; $i++) {
+ // Load the TxID (32bytes) and vout (4bytes)
+ $txid = self::_return_bytes($raw_transaction, 32, true);
+ $vout = self::_return_bytes($raw_transaction, 4, true);
+ // Script is prefixed with a varint that must be decoded.
+ $script_length = self::_get_vint($raw_transaction); // decimal number of bytes.
+ $script = self::_return_bytes($raw_transaction, $script_length);
+
+ // Build input body depending on whether the TxIn is coinbase.
+ if ($txid == '0000000000000000000000000000000000000000000000000000000000000000') {
+ $input_body = array('coinbase' => $script);
+ } else {
+ $input_body = array('txid' => $txid,
+ 'vout' => hexdec($vout),
+ 'scriptSig' => array('asm' => self::_decode_script($script), 'hex' => $script));
+ }
+ // Append a sequence number, and finally add the input to the array.
+ $input_body['sequence'] = hexdec(self::_return_bytes($raw_transaction, 4));
+ $inputs[$i] = $input_body;
+ }
+ return $inputs;
+ }
+
+ public static function _decode_outputs(&$tx, $output_count)
+ {
+ $math = EccFactory::getAdapter();
+ /*$magic_byte = BitcoinLib::magicByte($magic_byte);
+ $magic_p2sh_byte = BitcoinLib::magicP2SHByte($magic_p2sh_byte);*/
+ $outputs = array();
+ for ($i = 0; $i < $output_count; $i++) {
+ // Pop 8 bytes (flipped) from the $tx string, convert to decimal,
+ // and then convert to Satoshis.
+ $satoshis = $math->hexDec(self::_return_bytes($tx, 8, true));
+ // Decode the varint for the length of the scriptPubKey
+ $script_length = self::_get_vint($tx); // decimal number of bytes
+ $script = self::_return_bytes($tx, $script_length);
+
+
+ try {
+ $asm = self::_decode_scriptPubKey($script);
+ } catch (\Exception $e) {
+ $asm = null;
+ }
+ // Begin building scriptPubKey
+ $scriptPubKey = array(
+ 'asm' => $asm,
+ 'hex' => $script
+ );
+
+ // Try to decode the scriptPubKey['asm'] to learn the transaction type.
+ $txn_info = self::_get_transaction_type($scriptPubKey['asm']);
+ if ($txn_info !== false) {
+ $scriptPubKey = array_merge($scriptPubKey, $txn_info);
+ }
+ $outputs[$i] = array(
+ 'value' => $satoshis,
+ 'vout' => $i,
+ 'scriptPubKey' => $scriptPubKey);
+ }
+ return $outputs;
+ }
+
+ public function fixoutputs() {
+ $sql = 'SELECT * FROM Outputs WHERE Id NOT IN (SELECT OutputId FROM OutputsAddresses)';
+
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute($sql);
+ $outs = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ foreach ($outs as $out) {
+ $txn_info = self::_get_transaction_type($out->ScriptPubKeyAsm);
+
+ $out_data = [
+ 'Id' => $out->Id,
+ 'Type' => $txn_info['type'],
+ 'RequiredSignatures' => $txn_info['reqSigs'],
+ 'Hash160' => $txn_info['hash160'],
+ 'Addresses' => json_encode($txn_info['addresses'])
+ ];
+ $out_entity = $this->Outputs->newEntity($out_data);
+ $this->Outputs->save($out_entity);
+
+ // Fix the addresses
+ foreach ($txn_info['addresses'] as $address) {
+ $prev_addr = $this->Addresses->find()->where(['Address' => $address])->first();
+ $addr_id = -1;
+ if ($prev_addr) {
+ $addr_id = $prev_addr->Id;
+ } else {
+ $dt = new \DateTime($out->Created, new \DateTimeZone('UTC'));
+ $new_addr = [
+ 'Address' => $address,
+ 'FirstSeen' => $dt->format('Y-m-d H:i:s')
+ ];
+ $new_addr_entity = $this->Addresses->newEntity($new_addr);
+ if ($this->Addresses->save($new_addr_entity)) {
+ $addr_id = $new_addr_entity->Id;
+ }
+ }
+
+ if ($addr_id > -1) {
+ $conn->execute('INSERT INTO OutputsAddresses (OutputId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE OutputId = OutputId', [$out->Id, $addr_id]);
+ }
+ }
+
+ echo "Fixed output $out->Id with new data: " . print_r($out_data, true);
+ }
+ }
+
+ public function fixinputs() {
+ $sql = 'SELECT * FROM Inputs WHERE IsCoinbase <> 1 AND Id NOT IN (SELECT InputId FROM InputsAddresses)';
+
+ $conn = ConnectionManager::get('default');
+ $stmt = $conn->execute($sql);
+ $ins = $stmt->fetchAll(\PDO::FETCH_OBJ);
+
+ foreach ($ins as $in) {
+ $prev_tx_hash = $in->PrevoutHash;
+ $prev_n = $in->PrevoutN;
+
+ // Get the previous transaction
+ $prev_tx = $this->Transactions->find()->select(['Id'])->where(['Hash' => $prev_tx_hash])->first();
+ if (!$prev_tx) {
+ echo "Previous tx for hash $prev_tx_hash not found.\n";
+ continue;
+ }
+
+ $prev_tx_id = $prev_tx->Id;
+ $src_output = $this->Outputs->find()->contain(['OutputAddresses'])->where(['TransactionId' => $prev_tx_id, 'Vout' => $prev_n])->first();
+ $in_data = ['Id' => $in->Id];
+ if ($src_output) {
+ $in_data['Value'] = $src_output->Value;
+ $in_data['AddressId'] = $src_output->OutputAddresses[0]->Id;
+
+ $in_entity = $this->Inputs->newEntity($in_data);
+ if ($this->Inputs->save($in_entity)) {
+ $conn->execute('INSERT INTO InputsAddresses (InputId, AddressId) VALUES (?, ?) ON DUPLICATE KEY UPDATE InputId = InputId', [$in->Id, $in_data['AddressId']]);
+ }
+ }
+
+ echo "Fixed input $in->Id with new data: " . print_r($in_data, true);
+ }
+ }
+
+ public static function _get_transaction_type($data)
+ {
+ //$magic_byte = BitcoinLib::magicByte($magic_byte);
+ //$magic_p2sh_byte = BitcoinLib::magicP2SHByte($magic_p2sh_byte);
+ $has_claim = (strpos($data, 'CLAIM') !== false);
+ $has_update_claim = (strpos($data, 'UPDATE_CLAIM') !== false);
+ $has_op_0 = (strpos($data, 'OP_0') !== false);
+ $data = explode(" ", trim($data));
+ // Define information about eventual transactions cases, and
+ // the position of the hash160 address in the stack.
+ $define = array();
+ $rule = array();
+
+ // Other standard: pay to pubkey hash
+ $define['p2pk'] = array('type' => 'pubkeyhash',
+ 'reqSigs' => 1,
+ 'data_index_for_hash' => 1);
+ $rule['p2pk'] = [
+ '0' => '/^[0-9a-f]+$/i',
+ '1' => '/^OP_CHECKSIG/'
+ ];
+
+ // Pay to script hash
+ $define['p2sh'] = array('type' => 'scripthash',
+ 'reqSigs' => 1,
+ 'data_index_for_hash' => 1);
+ $rule['p2sh'] = array(
+ '0' => '/^OP_HASH160/',
+ '1' => '/^[0-9a-f]{40}$/i', // pos 1
+ '2' => '/^OP_EQUAL/');
+
+ // Non-standard (claim_name and support_claim)
+ $define['p2c'] = array('type' => 'nonstandard',
+ 'reqSigs' => 1,
+ 'data_index_for_hash' => 7);
+ $rule['p2c'] = [
+ '0' => '/^OP_CLAIM_NAME|OP_SUPPORT_CLAIM/',
+ '1' => '/^[0-9a-f]+$/i',
+ '2' => '/^[0-9a-f]+$/i',
+ '3' => '/^OP_2DROP/',
+ '4' => '/^OP_DROP/',
+ '5' => '/^OP_DUP/',
+ '6' => '/^OP_HASH160/',
+ '7' => '/^[0-9a-f]{40}$/i', // pos 7
+ '8' => '/^OP_EQUALVERIFY/',
+ '9' => '/^OP_CHECKSIG/',
+ ];
+
+ // Non-standard (claim_name and support_claim)
+ $define['p2c2'] = array('type' => 'nonstandard',
+ 'reqSigs' => 1,
+ 'data_index_for_hash' => 7);
+ $rule['p2c2'] = [
+ '0' => '/^OP_CLAIM_NAME|OP_SUPPORT_CLAIM/',
+ '1' => '/^OP_0/',
+ '2' => '/^[0-9a-f]+$/i',
+ '3' => '/^OP_2DROP/',
+ '4' => '/^OP_DROP/',
+ '5' => '/^OP_DUP/',
+ '6' => '/^OP_HASH160/',
+ '7' => '/^[0-9a-f]{40}$/i', // pos 8
+ '8' => '/^OP_EQUALVERIFY/',
+ '9' => '/^OP_CHECKSIG/'
+ ];
+
+ // update_claim
+ $define['p2uc'] = array('type' => 'nonstandard',
+ 'reqSigs' => 1,
+ 'data_index_for_hash' => 8);
+ $rule['p2uc'] = [
+ '0' => '/^OP_UPDATE_CLAIM/',
+ '1' => '/^[0-9a-f]+$/i',
+ '2' => '/^[0-9a-f]+$/i',
+ '3' => '/^[0-9a-f]+$/i',
+ '4' => '/^OP_2DROP/',
+ '5' => '/^OP_2DROP/',
+ '6' => '/^OP_DUP/',
+ '7' => '/^OP_HASH160/',
+ '8' => '/^[0-9a-f]{40}$/i', // pos 8
+ '9' => '/^OP_EQUALVERIFY/',
+ '10' => '/^OP_CHECKSIG/'
+ ];
+
+ // Standard: pay to pubkey hash
+ $define['p2ph'] = array('type' => 'pubkeyhash',
+ 'reqSigs' => 1,
+ 'data_index_for_hash' => 2);
+ $rule['p2ph'] = array(
+ '0' => '/^OP_DUP/',
+ '1' => '/^OP_HASH160/',
+ '2' => '/^[0-9a-f]{40}$/i', // 2
+ '3' => '/^OP_EQUALVERIFY/',
+ '4' => '/^OP_CHECKSIG/');
+
+ if ($has_claim) {
+ unset($rule['p2ph']);
+ unset($rule['p2sh']);
+
+ if ($has_op_0) {
+ unset($rule['p2c']);
+ } else {
+ unset($rule['p2c2']);
+ }
+
+ if ($has_update_claim) {
+ unset($rule['p2c']);
+ } else {
+ unset($rule['p2uc']);
+ }
+ } else {
+ unset($rule['p2c']);
+ unset($rule['p2c2']);
+ unset($rule['p2uc']);
+ }
+
+ // Work out how many rules are applied in each case
+ $valid = array();
+ foreach ($rule as $tx_type => $def) {
+ $valid[$tx_type] = count($def);
+ }
+
+ // Attempt to validate against each of these rules.
+ $matches = [];
+ for ($index = 0; $index < count($data); $index++) {
+ $test = $data[$index];
+ foreach ($rule as $tx_type => $def) {
+ if (isset($def[$index])) {
+ preg_match($def[$index], $test, $matches[$tx_type]);
+ if (count($matches[$tx_type]) == 1) {
+ $valid[$tx_type]--;
+ break;
+ }
+ }
+ }
+ }
+
+ // Loop through rules, check if any transaction is a match.
+ foreach ($rule as $tx_type => $def) {
+ if ($valid[$tx_type] == 0) {
+ // Load predefined info for this transaction type if detected.
+ $return = $define[$tx_type];
+ if ($tx_type === 'p2pk') {
+ $return['hash160'] = self::hash160($data[$define[$tx_type]['data_index_for_hash']]);
+ $return['addresses'][0] = self::hash160_to_address($return['hash160'], self::pubKeyAddress[0]);
+ } else {
+ $return['hash160'] = $data[$define[$tx_type]['data_index_for_hash']];
+ $return['addresses'][0] = self::hash160_to_address($return['hash160'], ($tx_type === 'p2sh') ? self::scriptAddress[0] : self::pubKeyAddress[0]); // TODO: Pay to claim transaction?
+ }
+ unset($return['data_index_for_hash']);
+ }
+ }
+ return (!isset($return)) ? false : $return;
+ }
+
+ public static function _decode_scriptPubKey($script, $matchBitcoinCore = false)
+ {
+ $data = array();
+ while (strlen($script) !== 0) {
+ $byteHex = self::_return_bytes($script, 1);
+ $byteInt = hexdec($byteHex);
+
+ if (isset(self::$op_code[$byteHex])) {
+ // This checks if the OPCODE is defined from the list of constants.
+ if ($matchBitcoinCore && self::$op_code[$byteHex] == "OP_0") {
+ $data[] = '0';
+ } else if ($matchBitcoinCore && self::$op_code[$byteHex] == "OP_1") {
+ $data[] = '1';
+ } else {
+ $data[] = self::$op_code[$byteHex];
+ }
+ } elseif ($byteInt >= 0x01 && $byteInt <= 0x4e) {
+ // This checks if the OPCODE falls in the PUSHDATA range
+ if ($byteInt == 0x4d) {
+ // OP_PUSHDATA2
+ $byteInt = hexdec(self::_return_bytes($script, 2, true));
+ $data[] = self::_return_bytes($script, $byteInt);
+ } else if ($byteInt == 0x4e) {
+ // OP_PUSHDATA4
+ $byteInt = hexdec(self::_return_bytes($script, 4, true));
+ $data[] = self::_return_bytes($script, $byteInt);
+ } else if ($byteInt == 0x4c) {
+ $num_bytes = hexdec(self::_return_bytes($script, 1, true));
+ $data[] = self::_return_bytes($script, $num_bytes);
+ } else {
+ $data[] = self::_return_bytes($script, $byteInt);
+ }
+ } elseif ($byteInt >= 0x51 && $byteInt <= 0x60) {
+ // This checks if the CODE falls in the OP_X range
+ $data[] = $matchBitcoinCore ? ($byteInt - 0x50) : 'OP_' . ($byteInt - 0x50);
+ } else {
+ throw new \RuntimeException("Failed to decode scriptPubKey");
+ }
+ }
+
+ return implode(" ", $data);
+ }
+
+ public static function lock($process_name) {
+ if (!is_dir(TMP . 'lock')) {
+ mkdir(TMP . 'lock');
+ }
+ $lock_file = TMP . 'lock' . DS . $process_name;
+ if (file_exists($lock_file)) {
+ echo "$process_name is already running.\n";
+ exit(0);
+ }
+ file_put_contents($lock_file, '1');
+ }
+
+ public static function unlock($process_name) {
+ $lock_file = TMP . 'lock' . DS . $process_name;
+ if (file_exists($lock_file)) {
+ unlink($lock_file);
+ }
+ return true;
+ }
+
+ public static function _return_bytes(&$string, $byte_count, $reverse = false)
+ {
+ if (strlen($string) < $byte_count * 2) {
+ throw new \InvalidArgumentException("Could not read enough bytes");
+ }
+ $requested_bytes = substr($string, 0, $byte_count * 2);
+ // Overwrite $string, starting $byte_count bytes from the start.
+ $string = substr($string, $byte_count * 2);
+ // Flip byte order if requested.
+ return ($reverse == false) ? $requested_bytes : self::_flip_byte_order($requested_bytes);
+ }
+
+ public static function _flip_byte_order($bytes) {
+ return implode('', array_reverse(str_split($bytes, 2)));
+ }
+
+ public static function _init_redis() {
+ $redis = new \Predis\Client(self::redisurl);
+ try {
+ $redis->info('mem');
+ } catch (\Predis\Connection\ConnectionException $e) {
+ // redis not available
+ $redis = null;
+ }
+
+ return $redis;
+ }
+
+ /*public function parsehistoryblocks() {
+ set_time_limit(0);
+ header('Content-type: text/plain');
+
+ $block_hash = null;
+ // Get the minimum block hash first
+ $minBlock = $this->Blocks->find()->select(['Hash'])->order(['Height' => 'asc'])->first();
+ if (!$minBlock) {
+ // get the best block
+ $req = ['method' => 'status'];
+ $response = self::curl_json_post(self::lbryurl, json_encode($req));
+ $json = json_decode($response);
+ $block_hash = $json->result->blockchain_status->best_blockhash;
+ } else {
+ $block_hash = $minBlock->Hash;
+ }
+
+ echo "Processing block: $block_hash... ";
+ $req = ['method' => 'block_show', 'params' => ['blockhash' => $block_hash]];
+ $response = self::curl_json_post(self::lbryurl, json_encode($req));
+ $json = json_decode($response);
+ $block_data = $json->result;
+
+ // Check if the block exists
+ $oldBlock = $this->Blocks->find()->select(['Id'])->where(['Hash' => $block_hash])->first();
+ if (!$oldBlock) {
+ // Block does not exist, create the block
+ $newBlock = $this->blockdb_data_from_json($block_data);
+ $entity = $this->Blocks->newEntity($newBlock);
+ $this->Blocks->save($entity);
+ }
+ echo "Done.\n";
+
+ $prevBlockHash = isset($block_data->previousblockhash) ? $block_data->previousblockhash : null;
+ do {
+ $oldBlock = $this->Blocks->find()->select(['Id'])->where(['Hash' => $prevBlockHash])->first();
+ $req = ['method' => 'block_show', 'params' => ['blockhash' => $prevBlockHash]];
+ $response = self::curl_json_post(self::lbryurl, json_encode($req));
+ $json = json_decode($response);
+ $block_data = $json->result;
+ $prevBlockHash = isset($block_data->previousblockhash) ? $block_data->previousblockhash : null;
+
+ if (!$oldBlock) {
+ echo "Inserting block: $block_data->hash... ";
+ $newBlock = $this->blockdb_data_from_json($block_data);
+ $entity = $this->Blocks->newEntity($newBlock);
+ $this->Blocks->save($entity);
+ } else {
+ echo "Updating block: $block_data->hash with confirmations: $block_data->confirmations... ";
+ $updData = ['Id' => $oldBlock->Id, 'Confirmations' => $block_data->confirmations];
+ $entity = $this->Blocks->newEntity($newBlock);
+ $this->Blocks->save($entity);
+ }
+ echo "Done.\n";
+ } while($prevBlockHash != null && strlen(trim($prevBlockHash)) > 0);
+
+ exit(0);
+ }
+
+ public function updatespends() {
+ set_time_limit(0);
+
+ self::lock('updatespends');
+
+ try {
+ $conn = ConnectionManager::get('default');
+ $inputs = $this->Inputs->find()->select(['Id', 'PrevoutHash', 'PrevoutN'])->where(['PrevoutSpendUpdated' => 0, 'IsCoinbase <>' => 1])->limit(500000)->toArray();
+
+ $count = count($inputs);
+ $idx = 0;
+ echo sprintf("Processing %d inputs.\n", $count);
+ foreach ($inputs as $in) {
+ $idx++;
+ $idx_str = str_pad($idx, strlen($count), '0', STR_PAD_LEFT);
+
+ $tx = $this->Transactions->find()->select(['Id'])->where(['Hash' => $in->PrevoutHash])->first();
+ if ($tx) {
+ $data_error = false;
+
+ $conn->begin();
+
+ try {
+ // update the corresponding output and set it as spent
+ $conn->execute('UPDATE Outputs SET IsSpent = 1, SpentByInputId = ?, Modified = UTC_TIMESTAMP() WHERE TransactionId = ? AND Vout = ?', [$in->Id, $tx->Id, $in->PrevoutN]);
+ } catch (\Exception $e) {
+ $data_error = true;
+ }
+
+ if (!$data_error) {
+ // update the input
+ $in_data = ['Id' => $in->Id, 'PrevoutSpendUpdated' => 1];
+ $in_entity = $this->Inputs->newEntity($in_data);
+ $result = $this->Inputs->save($in_entity);
+
+ if (!$result) {
+ $data_error = true;
+ }
+ }
+
+ if ($data_error) {
+ echo sprintf("[$idx_str/$count] Could NOT update vout %s for transaction hash %s.\n", $in->PrevoutN, $in->PrevoutHash);
+ $conn->rollback();
+ } else {
+ echo sprintf("[$idx_str/$count] Updated vout %s for transaction hash %s.\n", $in->PrevoutN, $in->PrevoutHash);
+ $conn->commit();
+ }
+ } else {
+ echo sprintf("[$idx_str/$count] Transaction NOT found for tx hash %s.\n", $in->PrevoutHash);
+ }
+ }
+ } catch (\Exception $e) {
+ print_r($e);
+ }
+
+ self::unlock('updatespends');
+ }
+ */
+}
+
+?>
\ No newline at end of file
diff --git a/src/Shell/ConsoleShell.php b/src/Shell/ConsoleShell.php
new file mode 100644
index 0000000..c84bd97
--- /dev/null
+++ b/src/Shell/ConsoleShell.php
@@ -0,0 +1,81 @@
+err('Unable to load Psy\Shell. ');
+ $this->err('');
+ $this->err('Make sure you have installed psysh as a dependency,');
+ $this->err('and that Psy\Shell is registered in your autoloader.');
+ $this->err('');
+ $this->err('If you are using composer run');
+ $this->err('');
+ $this->err('$ php composer.phar require --dev psy/psysh ');
+ $this->err('');
+
+ return self::CODE_ERROR;
+ }
+
+ $this->out("You can exit with `CTRL-C` or `exit` ");
+ $this->out('');
+
+ Log::drop('debug');
+ Log::drop('error');
+ $this->_io->setLoggers(false);
+ restore_error_handler();
+ restore_exception_handler();
+
+ $psy = new PsyShell();
+ $psy->run();
+ }
+
+ /**
+ * Display help for this console.
+ *
+ * @return \Cake\Console\ConsoleOptionParser
+ */
+ public function getOptionParser()
+ {
+ $parser = new ConsoleOptionParser('console');
+ $parser->setDescription(
+ 'This shell provides a REPL that you can use to interact ' .
+ 'with your application in an interactive fashion. You can use ' .
+ 'it to run adhoc queries with your models, or experiment ' .
+ 'and explore the features of CakePHP and your application.' .
+ "\n\n" .
+ 'You will need to have psysh installed for this Shell to work.'
+ );
+
+ return $parser;
+ }
+}
diff --git a/src/Template/Element/Flash/default.ctp b/src/Template/Element/Flash/default.ctp
new file mode 100644
index 0000000..736b27d
--- /dev/null
+++ b/src/Template/Element/Flash/default.ctp
@@ -0,0 +1,10 @@
+
+= $message ?>
diff --git a/src/Template/Element/Flash/error.ctp b/src/Template/Element/Flash/error.ctp
new file mode 100644
index 0000000..e7c4af1
--- /dev/null
+++ b/src/Template/Element/Flash/error.ctp
@@ -0,0 +1,6 @@
+
+= $message ?>
diff --git a/src/Template/Element/Flash/success.ctp b/src/Template/Element/Flash/success.ctp
new file mode 100644
index 0000000..becd5a1
--- /dev/null
+++ b/src/Template/Element/Flash/success.ctp
@@ -0,0 +1,6 @@
+
+= $message ?>
diff --git a/internal/explorer/templates/header.html b/src/Template/Element/header.ctp
similarity index 87%
rename from internal/explorer/templates/header.html
rename to src/Template/Element/header.ctp
index 0531a7d..1a561f1 100644
--- a/internal/explorer/templates/header.html
+++ b/src/Template/Element/header.ctp
@@ -1,4 +1,4 @@
-{{define "header"}}
+
-{{end}}
\ No newline at end of file
+
\ No newline at end of file
diff --git a/src/Template/Element/pagination.ctp b/src/Template/Element/pagination.ctp
new file mode 100644
index 0000000..2d63203
--- /dev/null
+++ b/src/Template/Element/pagination.ctp
@@ -0,0 +1,58 @@
+ 1): ?>
+
+
\ No newline at end of file
diff --git a/src/Template/Email/html/default.ctp b/src/Template/Email/html/default.ctp
new file mode 100644
index 0000000..386674a
--- /dev/null
+++ b/src/Template/Email/html/default.ctp
@@ -0,0 +1,22 @@
+
+ ' . $line . " \n";
+endforeach;
+?>
diff --git a/src/Template/Email/text/default.ctp b/src/Template/Email/text/default.ctp
new file mode 100644
index 0000000..704b46f
--- /dev/null
+++ b/src/Template/Email/text/default.ctp
@@ -0,0 +1,16 @@
+
+= $content ?>
diff --git a/src/Template/Error/error400.ctp b/src/Template/Error/error400.ctp
new file mode 100644
index 0000000..2aebac6
--- /dev/null
+++ b/src/Template/Error/error400.ctp
@@ -0,0 +1,38 @@
+layout = 'error';
+
+if (Configure::read('debug')):
+ $this->layout = 'dev_error';
+
+ $this->assign('title', $message);
+ $this->assign('templateName', 'error400.ctp');
+
+ $this->start('file');
+?>
+queryString)) : ?>
+
+ SQL Query:
+ = h($error->queryString) ?>
+
+
+params)) : ?>
+ SQL Query Params:
+ params) ?>
+
+= $this->element('auto_table_warning') ?>
+end();
+endif;
+?>
+= h($message) ?>
+
+ = __d('cake', 'Error') ?>:
+ = __d('cake', 'The requested address {0} was not found on this server.', "'{$url}' ") ?>
+
diff --git a/src/Template/Error/error500.ctp b/src/Template/Error/error500.ctp
new file mode 100644
index 0000000..d8014f8
--- /dev/null
+++ b/src/Template/Error/error500.ctp
@@ -0,0 +1,43 @@
+layout = 'error';
+
+if (Configure::read('debug')):
+ $this->layout = 'dev_error';
+
+ $this->assign('title', $message);
+ $this->assign('templateName', 'error500.ctp');
+
+ $this->start('file');
+?>
+queryString)) : ?>
+
+ SQL Query:
+ = h($error->queryString) ?>
+
+
+params)) : ?>
+ SQL Query Params:
+ params) ?>
+
+
+ Error in:
+ = sprintf('%s, line %s', str_replace(ROOT, 'ROOT', $error->getFile()), $error->getLine()) ?>
+
+element('auto_table_warning');
+
+ if (extension_loaded('xdebug')):
+ xdebug_print_function_stack();
+ endif;
+
+ $this->end();
+endif;
+?>
+= __d('cake', 'An Internal Error Has Occurred') ?>
+
+ = __d('cake', 'Error') ?>:
+ = h($message) ?>
+
diff --git a/src/Template/Layout/Email/html/default.ctp b/src/Template/Layout/Email/html/default.ctp
new file mode 100644
index 0000000..2b43970
--- /dev/null
+++ b/src/Template/Layout/Email/html/default.ctp
@@ -0,0 +1,24 @@
+
+
+
+
+ = $this->fetch('title') ?>
+
+
+ = $this->fetch('content') ?>
+
+
diff --git a/src/Template/Layout/Email/text/default.ctp b/src/Template/Layout/Email/text/default.ctp
new file mode 100644
index 0000000..871dcfb
--- /dev/null
+++ b/src/Template/Layout/Email/text/default.ctp
@@ -0,0 +1,16 @@
+
+= $this->fetch('content') ?>
diff --git a/src/Template/Layout/ajax.ctp b/src/Template/Layout/ajax.ctp
new file mode 100644
index 0000000..871dcfb
--- /dev/null
+++ b/src/Template/Layout/ajax.ctp
@@ -0,0 +1,16 @@
+
+= $this->fetch('content') ?>
diff --git a/src/Template/Layout/default.ctp b/src/Template/Layout/default.ctp
new file mode 100644
index 0000000..9ee1ab7
--- /dev/null
+++ b/src/Template/Layout/default.ctp
@@ -0,0 +1,72 @@
+
+
+
+ = $this->Html->charset(); ?>
+
+
+ LBRY Block Explorer • = $this->fetch('title') ?>
+
+ Html->meta('icon') */?>
+
+ Html->script('jquery.js') ?>
+ Html->script('moment.js') ?>
+
+ Html->css('main.css') ?>
+
+
+
+
+
+
+
+
+
+
+
+
+ fetch('meta') ?>
+ fetch('css') ?>
+ fetch('script') ?>
+
+
+ fetch('content') ?>
+
+
+
LBRY
+
+
Page took ms
+
+
+
+
diff --git a/src/Template/Layout/error.ctp b/src/Template/Layout/error.ctp
new file mode 100644
index 0000000..5304ec4
--- /dev/null
+++ b/src/Template/Layout/error.ctp
@@ -0,0 +1,47 @@
+
+
+
+
+ = $this->Html->charset() ?>
+
+ = $this->fetch('title') ?>
+
+ = $this->Html->meta('icon') ?>
+
+ = $this->Html->css('base.css') ?>
+ = $this->Html->css('cake.css') ?>
+
+ = $this->fetch('meta') ?>
+ = $this->fetch('css') ?>
+ = $this->fetch('script') ?>
+
+
+
+
+
+ = $this->Flash->render() ?>
+
+ = $this->fetch('content') ?>
+
+
+
+
+
diff --git a/src/Template/Layout/rss/default.ctp b/src/Template/Layout/rss/default.ctp
new file mode 100644
index 0000000..5c15a19
--- /dev/null
+++ b/src/Template/Layout/rss/default.ctp
@@ -0,0 +1,14 @@
+fetch('title');
+endif;
+
+echo $this->Rss->document(
+ $this->Rss->channel(
+ [], $channel, $this->fetch('content')
+ )
+);
+?>
diff --git a/src/Template/Main/address.ctp b/src/Template/Main/address.ctp
new file mode 100644
index 0000000..08285c0
--- /dev/null
+++ b/src/Template/Main/address.ctp
@@ -0,0 +1,201 @@
+assign('title', 'Address ' . $address->Address) ?>
+
+start('script') ?>
+
+end() ?>
+
+element('header') ?>
+
+
+
LBRY Address
+
Address ?>
+
+
+
Tag adddress
+
+
This address has a pending tag request. If you made this request, please send exactly
VerificationAmount ?> LBC from
Address ?> to
bLockNgmfvnnnZw7bM6SPz6hk5BVzhevEp . Incomplete requests will be automatically deleted 7 days from the request creation date.
+
+
Label your public LBRY address with a name and an optional link. In order to tag this address, please send exactly
LBC
+ from
Address ?> to
bLockNgmfvnnnZw7bM6SPz6hk5BVzhevEp
+ and then specify the desired tag (maximum 30 characters) and link in the fields below. The transaction will be verified after at least 1 confirmation. The
LBC fee is a measure to prevent spam and low-effort submissions. Verification is an automatic process, but any tags or URLs that may be considered illegal when brought to attention will be removed.
+
+
+
+
+
+
+
+
+
+
+
+
+
Balance (LBC)
+
Amount->format($balanceAmount) ?>
+
+
+
+
Received (LBC)
+
Amount->format($totalReceived) ?>
+
+
+
+
Sent (LBC)
+
Amount->format($totalSent) ?>
+
+
+
+
+
+
+
+
+
+
Transactions
+
+ 0):
+ $begin = ($currentPage - 1) * $pageLimit + 1;
+ ?>
+ Showing - of transaction
+
+
+
+
+
+
+ Height
+ Transaction Hash
+ Timestamp
+ Confirmations
+ Inputs
+ Outputs
+ Amount
+
+
+
+
+
+
+ There are no recent transactions to display for this wallet.
+
+
+
+
+
+ Height === null): ?>Unconfirmed Height ?>
+
+ TxTime)->format('d M Y H:i:s') . ' UTC'; ?>
+ Confirmations, 0, '', ',') ?>
+ InputCount ?>
+ OutputCount ?>
+
+ DebitAmount > 0 && $tx->CreditAmount > 0): ?>
+ +CreditAmount, 8, '.', ',') ?> LBC
+ -DebitAmount, 8, '.', ',') ?> LBC
+
+ DebitAmount > 0) ? '-' : '+'); ?>DebitAmount > 0) ? $tx->DebitAmount : $tx->CreditAmount), 8, '.', ',') ?> LBC
+
+
+
+
+
+
+
+
+element('pagination') ?>
\ No newline at end of file
diff --git a/src/Template/Main/blocks.ctp b/src/Template/Main/blocks.ctp
new file mode 100644
index 0000000..a804c16
--- /dev/null
+++ b/src/Template/Main/blocks.ctp
@@ -0,0 +1,427 @@
+element('header') ?>
+
+
+ start('script'); ?>
+
+ end(); ?>
+
+ assign('title', 'Block Height ' . $block->Height) ?>
+
+
+
LBRY Block Height ?>
+ Hash ?>
+
+
+
+
+
+
+
Overview
+
+
Block Size (bytes)
+
Block Time
+
+
BlockSize, 0, '', ',') ?>
+
BlockTime)->format('j M Y H:i:s') . ' UTC' ?>
+
+
+
+
Bits
+
Confirmations
+
+
Bits ?>
+
Confirmations, 0, '', ',') ?>
+
+
+
+
Difficulty
+
Nonce
+
+
Amount->format($block->Difficulty, '') ?>
+
Nonce ?>
+
+
+
+
Chainwork
Chainwork ?>
+
+
+
+
MerkleRoot
MerkleRoot ?>
+
+
+
+
NameClaimRoot
NameClaimRoot ?>
+
+
+
+
Target
Target ?>
+
+
+
+
Version
Version ?>
+
+
+
+
Transaction
+
+
+
+
+
+ Hash
+ Inputs
+ Outputs
+ Value
+
+
+
+
+
+ There are no transactions to display at this time.
+
+
+
+
+
+
+ InputCount ?>
+ OutputCount ?>
+ Amount->formatCurrency($tx->Value) ?> LBC
+
+
+
+
+
+
+
+
+
+assign('title', 'Blocks');
+
+ $this->start('css');
+ echo $this->Html->css('/amcharts/plugins/export/export.css');
+ $this->end();
+
+ $this->start('script'); ?>
+
+
+
+
+end(); ?>
+
+
+
LBRY Blocks
+
+
+
+
+
Block Size Chart
+
+
+
+
+
+
+
All Blocks
+
+ 0):
+ $begin = ($currentPage - 1) * $pageLimit + 1;
+ ?>
+ Showing - of block
+
+
+
+
+
+ Height
+ Difficulty
+ Confirmations
+ TX Count
+ Block Size
+ Nonce
+ Block Time
+
+
+
+
+
+
+ Height ?>
+ Difficulty, 8, '.', '') ?>
+ Confirmations, 0, '', ',') ?>
+ TransactionHashes)) ?>
+ BlockSize / 1024, 2) . 'KB' ?>
+ Nonce ?>
+ BlockTime)->format('d M Y H:i:s') ?> UTC
+
+
+
+
+
+
+element('pagination') ?>
+
\ No newline at end of file
diff --git a/src/Template/Main/claims.ctp b/src/Template/Main/claims.ctp
new file mode 100644
index 0000000..67a3327
--- /dev/null
+++ b/src/Template/Main/claims.ctp
@@ -0,0 +1,395 @@
+start('script'); ?>
+
+end(); ?>
+element('header') ?>
+
+Name;
+$rawLink = $claim->Name;
+if (isset($claim->Publisher->Name)) {
+ $link = urlencode($claim->Publisher->Name) . '/' . $link;
+ $rawLink = $claim->Publisher->Name . '/' . $rawLink;
+}
+$link = 'lbry://' . $link;
+$rawLink = 'lbry://' . $rawLink;
+if ($claim->ClaimType == 1) { $autoThumbText = strtoupper(substr($claim->Name, 1, min( strlen($claim->Name), 10 ))); } else {
+ $str = str_replace(' ', '', (strlen(trim($claim->Title)) > 0) ? $claim->Title : $claim->Name);
+ $autoThumbText = strtoupper(mb_substr($str, 0, min( strlen($str), 10 )));
+}
+
+$cost = 'Free';
+if (isset($claim->Price) && $claim->Price > 0) {
+ $cost = $this->Amount->formatCurrency($claim->Price) . ' LBC';
+} else if (isset($claim->Fee) && strtolower($claim->FeeCurrency) === 'lbc') {
+ $cost = $this->Amount->formatCurrency($claim->Fee) . ' LBC';
+}
+
+$desc = $claim->Description;
+if (strlen(trim($desc)) == 0) {
+ $desc = 'No description available. ';
+} else {
+ $desc = preg_replace('#((https?|ftp|lbry)://([A-Za-z0-9\-\/]+|\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i','$1 $4', $desc);
+ $desc = preg_replace('/(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/is', '$0 ', $desc);
+}
+
+?>
+
+assign('title', 'Claim • ' . $claim->Name) ?>
+
+
+
+
+
+
+ IsNSFW && strlen(trim($claim->ThumbnailUrl)) > 0): ?>
+
+
+
+
+
+
+
+ ClaimType == 2): ?>
+
Published by
+
+
+
+
Created
+
TransactionTime > 0 ? $claim->TransactionTime : $claim->Created->format('U'))->format('j M Y H:i:s') ?> UTC
+
+
Transaction
+
+
+ ClaimType == 2): ?>
+
Cost
+
Safe for work
+
+
+
IsNSFW ? 'No' : 'Yes' ?>
+
+
+
+
+
+
+
+
+
+
+
+ 0): ?>
+
+
+
Publisher) ? 'More from the publisher' : 'Published by this identity' ?>
+
+
+ Name;
+ $rawLink = $claim->Name;
+ if (isset($claim->Publisher->Name)) {
+ $link = urlencode($claim->Publisher->Name) . '/' . $link;
+ $rawLink = $claim->Publisher->Name . '/' . $rawLink;
+ }
+ $link = 'lbry://' . $link;
+ $rawLink = 'lbry://' . $rawLink;
+ $cost = '';
+ if (isset($claim->Price) && $claim->Price > 0) {
+ $cost = $this->Amount->formatCurrency($claim->Price) . ' LBC';
+ } else if (isset($claim->Fee) && strtolower($claim->FeeCurrency) === 'lbc') {
+ $cost = $this->Amount->formatCurrency($claim->Fee) . ' LBC';
+ }
+
+ // 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), 10 ))); } else {
+ $str = str_replace(' ', '', (strlen(trim($claim->Title)) > 0) ? $claim->Title : $claim->Name);
+ $autoThumbText = strtoupper(mb_substr($str, 0, min( strlen($str), 10 )));
+ }
+
+ ?>
+
+ 0): ?>
+
+
+
+
+
+
+ IsNSFW && strlen(trim($claim->ThumbnailUrl)) > 0): ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+assign('title', 'Claims Explorer') ?>
+
+
+
Claims Explorer
+
+
+
+ Name;
+ $rawLink = $claim->Name;
+ if (isset($claim->Publisher->Name)) {
+ $link = urlencode($claim->Publisher->Name) . '/' . $link;
+ $rawLink = $claim->Publisher->Name . '/' . $rawLink;
+ }
+ $link = 'lbry://' . $link;
+ $rawLink = 'lbry://' . $rawLink;
+ $cost = '';
+ if (isset($claim->Price) && $claim->Price > 0) {
+ $cost = $this->Amount->formatCurrency($claim->Price) . ' LBC';
+ } else if (isset($claim->Fee) && strtolower($claim->FeeCurrency) === 'lbc') {
+ $cost = $this->Amount->formatCurrency($claim->Fee) . ' LBC';
+ }
+
+ // 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), 10 ))); } else {
+ $str = str_replace(' ', '', (strlen(trim($claim->Title)) > 0) ? $claim->Title : $claim->Name);
+ $autoThumbText = strtoupper(mb_substr($str, 0, min( strlen($str), 10 )));
+ }
+
+ ?>
+
+ 0): ?>
+
+
+
+
+
+
+ IsNSFW && strlen(trim($claim->ThumbnailUrl)) > 0): ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+element('pagination') ?>
+
+
\ No newline at end of file
diff --git a/internal/explorer/templates/home.html b/src/Template/Main/index.ctp
similarity index 57%
rename from internal/explorer/templates/home.html
rename to src/Template/Main/index.ctp
index 2739bbc..4f92bdd 100644
--- a/internal/explorer/templates/home.html
+++ b/src/Template/Main/index.ctp
@@ -1,6 +1,6 @@
+assign('title', 'Home') ?>
-
-{{define "script"}}
+start('script'); ?>
-{{end}}{{define "css"}}{{end}}{{define "content"}}
+end(); ?>
-
LBRY Block Explorer
+
LBRY Block Explorer
-
+
Block Height
-
{{.Highest.height}}
+
Height ?>
-
+
Difficulty
-
{{fixed .Highest.difficulty 2}}
+
Difficulty, 2, '.', '') ?>
-
+
-
+
@@ -166,16 +160,16 @@
- {{range $block := .RecentBlocks}}
-
- {{$block.height}}
- {{ago $block.block_time}}
- {{kb $block.block_size}}
- {{$block.tx_count}}
- {{fixed $block.difficulty 2}}
- {{date $block.block_time "02 Jan 2006 15:04:05"}} UTC
+
+
+ Height ?>
+ BlockTime)->diffForHumans(); ?>
+ BlockSize / 1024, 2) . 'KB' ?>
+ TransactionCount ?>
+ Difficulty, 2, '.', '') ?>
+ BlockTime)->format('d M Y H:i:s') . ' UTC' ?>
- {{end}}
+
@@ -183,42 +177,71 @@
Recent Claims
Claims Explorer
- {{range $i, $claim := .RecentClaims}}
-
+ 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 )));
+ }
+ ?>
+
-
- {{if showThumbnail $claim}}
-
- {{else}}
-
{{autoThumb $claim}}
- {{end}}
+
+ IsNSFW && strlen(trim($claim->ThumbnailUrl)) > 0): ?>
+
+
+
+
-
Transaction
+
Transaction
- {{end}}
+
-
-{{end}}
\ No newline at end of file
+
\ No newline at end of file
diff --git a/internal/explorer/templates/realtime.html b/src/Template/Main/realtime.ctp
similarity index 80%
rename from internal/explorer/templates/realtime.html
rename to src/Template/Main/realtime.ctp
index 7ae4e3b..3b29f04 100644
--- a/internal/explorer/templates/realtime.html
+++ b/src/Template/Main/realtime.ctp
@@ -1,6 +1,6 @@
+assign('title', 'Realtime Explorer') ?>
-
-{{define "script"}}
+start('script'); ?>
-{{end}}{{define "css"}}{{end}}{{define "content"}}
+end(); ?>
-{{template "header" .}}
+element('header') ?>
Realtime Explorer
@@ -127,13 +127,13 @@
- {{range $block := .Blocks}}
-
- {{$block.height}}
- {{ago $block.block_time}}
- {{$block.tx_count}}
+
+
+ Height ?>
+ BlockTime)->diffForHumans(); ?>
+ TransactionCount ?>
- {{end}}
+
@@ -152,15 +152,15 @@
- {{range $tx := .Txs}}
-
-
- {{humanAgo $tx.created_at}}
- {{$tx.input_count}}
- {{$tx.output_count}}
- {{fixed $tx.value 8}} LBC
+
+
+
+ TxTime)->diffForHumans(); ?>
+ InputCount ?>
+ OutputCount ?>
+ Value, 8, '.', '') ?> LBC
- {{end}}
+
@@ -168,4 +168,3 @@
-{{end}}
\ No newline at end of file
diff --git a/src/Template/Main/stats.ctp b/src/Template/Main/stats.ctp
new file mode 100644
index 0000000..36e056b
--- /dev/null
+++ b/src/Template/Main/stats.ctp
@@ -0,0 +1,53 @@
+assign('title', 'Stats & Rich List') ?>
+
+start('script'); ?>
+
+end(); ?>
+
+element('header') ?>
+
+
+
LBRY Stats
+
+
+
+
+
+
LBRY Rich List (Top 500)
+
+
+
+ Rank
+ Address
+ Balance (LBC)
+ Balance (USD)
+ First Seen
+ % Top 500
+
+
+
+
+
+
+
+ Address ?>
+ Tag) && strlen(trim($item->Tag)) > 0): ?>
+
+ TagUrl)) > 0): ?>
Tag ?> Tag; endif; ?>
+
+
+ Balance, 8, '.', ',') ?>
+ $Balance, $rate, 8), 2, '.', ',') ?>
+ FirstSeen->format('d M Y H:i:s') . ' UTC'; ?>
+
Top500Percent, 5, '.', '') ?>%
+
+
+
+
+
+
+
+
+
diff --git a/src/Template/Main/tx.ctp b/src/Template/Main/tx.ctp
new file mode 100644
index 0000000..59805b0
--- /dev/null
+++ b/src/Template/Main/tx.ctp
@@ -0,0 +1,169 @@
+assign('title', 'Transaction ' . $tx->Hash) ?>
+
+start('script'); ?>
+
+end(); ?>
+
+element('header') ?>
+
+
+
LBRY Transaction
+ Hash ?>
+
+
+
+
+
Time Created
+
Created->format('j M Y H:i:s') . ' UTC '; ?>
+
+
+
+
Block Time
+
TransactionTime == null || strlen(trim($tx->TransactionTime)) == 0) ? 'Not yet confirmed ' :
+ \DateTime::createFromFormat('U', $tx->TransactionTime)->format('j M Y H:i:s') . ' UTC' ?>
+
+ TransactionTime > $tx->Created->getTimestamp()):
+ $diffSeconds = $tx->TransactionTime - $tx->Created->getTimestamp();
+ if ($diffSeconds <= 60) {
+ echo sprintf(' (+%s second%s)', $diffSeconds, $diffSeconds == 1 ? '' : 's');
+ } else {
+ $diffMinutes = ceil($diffSeconds / 60);
+ echo sprintf(' (+%s minute%s)', $diffMinutes, $diffMinutes == 1 ? '' : 's');
+ }
+ ?>
+
+
+
+
+
+
+
+
+
+
Amount (LBC)
+
Amount->format($tx->Value) ?>
+
+
+
+
Block Height
+ BlockHash) || strlen(trim($tx->BlockHash)) === 0): ?>
+
Unconf.
+
+
+
+
+
+
+
+
+
Size (bytes)
+
TransactionSize, 0, '', ',') ?>
+
+
+
+
Inputs
+
InputCount ?>
+
+
+
+
Outputs
+
OutputCount ?>
+
+
+
+
+
+
+
Details
+
+
+
+
+
+
+
+
+
OutputCount ?> outputOutputCount === 1 ? '' : 's'; ?>
+
+ 0): ?>
+ Fee Amount->format($fee) ?> LBC
+
+
+
+
+
+
+ IsSupportClaim): ?>
SUPPORT
+ IsUpdateClaim): ?>
UPDATE
+ IsClaim): ?>
CLAIM
+
+
+
+
Incomplete data
+ Address])):
+ $setAddressIds[$addr->Address] = 1; ?>
+
+
+
Amount->format($out['Value']) ?> LBC to
+
Address ?>
+
+ IsSpent): ?>(
spent )(unspent)
+
+ Tag) && strlen(trim($addr->Tag)) > 0): ?>
+
+ TagUrl)) > 0): ?>
Tag ?> Tag; endif; ?>
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/Template/Pages/home.ctp b/src/Template/Pages/home.ctp
new file mode 100644
index 0000000..cae07dd
--- /dev/null
+++ b/src/Template/Pages/home.ctp
@@ -0,0 +1,276 @@
+layout = false;
+
+if (!Configure::read('debug')):
+ throw new NotFoundException('Please replace src/Template/Pages/home.ctp with your own version.');
+endif;
+
+$cakeDescription = 'CakePHP: the rapid development PHP framework';
+?>
+
+
+
+ = $this->Html->charset() ?>
+
+
+ = $cakeDescription ?>
+
+
+ = $this->Html->meta('icon') ?>
+ = $this->Html->css('base.css') ?>
+ = $this->Html->css('cake.css') ?>
+ = $this->Html->css('home.css') ?>
+
+
+
+
+
+
+
+
+
+
Please be aware that this page will not be shown if you turn off debug mode unless you replace src/Template/Pages/home.ctp with your own version.
+
+
+
+
+
+
+
+
+
Environment
+
+ =')): ?>
+ Your version of PHP is 5.6.0 or higher (detected = PHP_VERSION ?>).
+
+ Your version of PHP is too low. You need PHP 5.6.0 or higher to use CakePHP (detected = PHP_VERSION ?>).
+
+
+
+ Your version of PHP has the mbstring extension loaded.
+
+ Your version of PHP does NOT have the mbstring extension loaded. ;
+
+
+
+ Your version of PHP has the openssl extension loaded.
+
+ Your version of PHP has the mcrypt extension loaded.
+
+ Your version of PHP does NOT have the openssl or mcrypt extension loaded.
+
+
+
+ Your version of PHP has the intl extension loaded.
+
+ Your version of PHP does NOT have the intl extension loaded.
+
+
+
+
+
Filesystem
+
+
+ Your tmp directory is writable.
+
+ Your tmp directory is NOT writable.
+
+
+
+ Your logs directory is writable.
+
+ Your logs directory is NOT writable.
+
+
+
+
+ The = $settings['className'] ?>Engine is being used for core caching. To change the config edit config/app.php
+
+ Your cache is NOT working. Please check the settings in config/app.php
+
+
+
+
+
+
+
+
+
Database
+ connect();
+ } catch (Exception $connectionError) {
+ $connected = false;
+ $errorMsg = $connectionError->getMessage();
+ if (method_exists($connectionError, 'getAttributes')):
+ $attributes = $connectionError->getAttributes();
+ if (isset($errorMsg['message'])):
+ $errorMsg .= '
' . $attributes['message'];
+ endif;
+ endif;
+ }
+ ?>
+
+
+ CakePHP is able to connect to the database.
+
+ CakePHP is NOT able to connect to the database. = $errorMsg ?>
+
+
+
+
+
DebugKit
+
+
+ DebugKit is loaded.
+
+ DebugKit is NOT loaded. You need to either install pdo_sqlite, or define the "debug_kit" connection name.
+
+
+
+
+
+
+
+
+
Editing this Page
+
+ To change the content of this page, edit: src/Template/Pages/home.ctp.
+ You can also add some CSS styles for your pages at: webroot/css/.
+
+
+
+
+
+
+
+
More about Cake
+
+ CakePHP is a rapid development framework for PHP which uses commonly known design patterns like Front Controller and MVC.
+ Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility.
+
+
+
+
+
+
+
+
P
+
Help and Bug Reports
+
+
+
+
r
+
Docs and Downloads
+
+
+
+
s
+
Training and Certification
+
+
+
+
+
+
diff --git a/src/View/AjaxView.php b/src/View/AjaxView.php
new file mode 100644
index 0000000..594e2d8
--- /dev/null
+++ b/src/View/AjaxView.php
@@ -0,0 +1,49 @@
+response->type('ajax');
+ }
+}
diff --git a/src/View/AppView.php b/src/View/AppView.php
new file mode 100644
index 0000000..630ed93
--- /dev/null
+++ b/src/View/AppView.php
@@ -0,0 +1,42 @@
+loadHelper('Html');`
+ *
+ * @return void
+ */
+ public function initialize()
+ {
+ parent::initialize();
+ $this->loadHelper('Amount');
+ }
+}
diff --git a/src/View/Helper/AmountHelper.php b/src/View/Helper/AmountHelper.php
new file mode 100644
index 0000000..e830421
--- /dev/null
+++ b/src/View/Helper/AmountHelper.php
@@ -0,0 +1,46 @@
+ 0) {
+ $value .= '.' . rtrim($right, '0');
+ }
+ }
+
+ return $value;
+ }
+
+ public function formatCurrency($value, $thousandsSeparator = ',') {
+ $dotIdx = strpos($value, '.');
+ if ($dotIdx !== false) {
+ $left = substr($value, 0, $dotIdx);
+ $right = substr($value, $dotIdx + 1);
+
+ $value = number_format($left, 0, '', $thousandsSeparator);
+ if ((int) $right > 0) {
+ if (strlen($right) === 1) {
+ $value .= '.' . $right . '0';
+ } else {
+ $value .= '.' . substr($right, 0, 2);
+ }
+ }
+ } else {
+ $value = number_format($value, 2, '.', $thousandsSeparator);
+ }
+
+ return $value;
+ }
+}
+
+?>
\ No newline at end of file
diff --git a/tests/TestCase/ApplicationTest.php b/tests/TestCase/ApplicationTest.php
new file mode 100644
index 0000000..d397fa1
--- /dev/null
+++ b/tests/TestCase/ApplicationTest.php
@@ -0,0 +1,46 @@
+middleware($middleware);
+
+ $this->assertInstanceOf(ErrorHandlerMiddleware::class, $middleware->get(0));
+ $this->assertInstanceOf(AssetMiddleware::class, $middleware->get(1));
+ $this->assertInstanceOf(RoutingMiddleware::class, $middleware->get(2));
+ }
+}
diff --git a/tests/TestCase/Controller/PagesControllerTest.php b/tests/TestCase/Controller/PagesControllerTest.php
new file mode 100644
index 0000000..1b478a3
--- /dev/null
+++ b/tests/TestCase/Controller/PagesControllerTest.php
@@ -0,0 +1,97 @@
+get('/');
+ $this->assertResponseOk();
+ $this->get('/');
+ $this->assertResponseOk();
+ }
+
+ /**
+ * testDisplay method
+ *
+ * @return void
+ */
+ public function testDisplay()
+ {
+ $this->get('/pages/home');
+ $this->assertResponseOk();
+ $this->assertResponseContains('CakePHP');
+ $this->assertResponseContains('');
+ }
+
+ /**
+ * Test that missing template renders 404 page in production
+ *
+ * @return void
+ */
+ public function testMissingTemplate()
+ {
+ Configure::write('debug', false);
+ $this->get('/pages/not_existing');
+
+ $this->assertResponseError();
+ $this->assertResponseContains('Error');
+ }
+
+ /**
+ * Test that missing template in debug mode renders missing_template error page
+ *
+ * @return void
+ */
+ public function testMissingTemplateInDebug()
+ {
+ Configure::write('debug', true);
+ $this->get('/pages/not_existing');
+
+ $this->assertResponseFailure();
+ $this->assertResponseContains('Missing Template');
+ $this->assertResponseContains('Stacktrace');
+ $this->assertResponseContains('not_existing.ctp');
+ }
+
+ /**
+ * Test directory traversal protection
+ *
+ * @return void
+ */
+ public function testDirectoryTraversalProtection()
+ {
+ $this->get('/pages/../Layout/ajax');
+ $this->assertResponseCode(403);
+ $this->assertResponseContains('Forbidden');
+ }
+}
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
new file mode 100644
index 0000000..0ca191e
--- /dev/null
+++ b/tests/bootstrap.php
@@ -0,0 +1,12 @@
+
+ RewriteEngine On
+ RewriteCond %{REQUEST_FILENAME} !-f
+ RewriteRule ^ index.php [L]
+
diff --git a/webroot/amcharts/plugins/animate/README.md b/webroot/amcharts/plugins/animate/README.md
index 869043e..50ebf2f 100644
--- a/webroot/amcharts/plugins/animate/README.md
+++ b/webroot/amcharts/plugins/animate/README.md
@@ -5,7 +5,7 @@ Version: 1.1.2
## Description
-Smoothly animates the `dataProvider`.
+Smoothly animates the `dataProvider`
It works with serial, pie, XY, funnel, and radar.
@@ -96,13 +96,13 @@ http://www.apache.org/licenses/LICENSE-2.0
## Changelog
### 1.1.2
-* Fixing a bug with the minimum/maximum.
+* Fixing a bug with the minimum/maximum
### 1.1.1
-* It now automatically sets the minimum/maximum on the value axes while animating.
+* It now automatically sets the minimum/maximum on the value axes while animating
### 1.1.0
-* Adding in support for XY charts.
+* Adding in support for XY charts
### 1.0.0
-* Initial release.
+* Initial release
diff --git a/webroot/amcharts/plugins/dataloader/readme.md b/webroot/amcharts/plugins/dataloader/readme.md
index 4431de6..48c3919 100644
--- a/webroot/amcharts/plugins/dataloader/readme.md
+++ b/webroot/amcharts/plugins/dataloader/readme.md
@@ -5,28 +5,28 @@ Version: 1.0.16
## Description
-By default, all amCharts libraries accept data in JSON format. It needs to be
+By default all amCharts libraries accept data in JSON format. It needs to be
there when the web page loads, defined in-line or loaded via custom code.
-This plugin introduces our native wrapper that enables automatic loading of data
-from external data sources in CSV and JSON formats.
+This plugin introduces are native wrapper that enables automatic loading of data
+from external data data sources in CSV and JSON formats.
-Most of the time, you will just need to provide a URL of the external data
+Most of the times you will just need to provide a URL of the external data
source - static file or dynamically generated - and it will do the rest.
## Important notice
-Due to security measures implemented in most of the browsers, the external data
-loader will work only when the page with the chart or map is loaded via web
+Due to security measures implemented in most of the browsers, the external data
+loader will work only when the page with the chart or map is loaded via web
server.
So, any of the examples loaded locally (file:///) will not work.
The page needs to be loaded via web server (http://) in order to work properly.
-Loading data from another domain than the web page is loaded is possible, but is
-a subject for `Access-Control-Allow-Origin` policies defined by the web server
+Loading data from another domain than the web page is loaded is possible but is
+a subject for `Access-Control-Allow-Origin` policies defined by the web server
you are loading data from.
For more about loading data across domains use the following thread:
@@ -75,10 +75,10 @@ AmCharts.makeChart( "chartdiv", {
} );
```
-That's it. The plugin will make sure the files are loaded and dataProvider is
+That's it. The plugin will make sure the files are loaded and dataProvider is
populated with their content *before* the chart is built.
-Some formats like CSV, will require additional parameters needed to parse the
+Some formats, like CSV, will require additional parameters needed to parse the
data, such as "separator".
If the "format" is omitted, the plugin will assume JSON.
@@ -104,33 +104,33 @@ chart["dataLoader"] = {
Property | Default | Description
-------- | ------- | -----------
-async | true | If set to false (not recommended), everything will wait until data is fully loaded.
-complete | | Callback function to execute when loader is done.
-delimiter | , | [CSV only] a delimiter for columns (use \t for tab delimiters).
-emptyAs | undefined | [CSV only] replace empty columns with whatever is set here.
-error | | Callback function to execute if file load fails.
-init | | Callback function to execute when Data Loader is initialized, before any loading starts.
-format | json | Type of data: json, csv.
-headers | | An array of objects with two properties (key and value) to attach to HTTP request.
-load | | Callback function to execute when file is successfully loaded (might be invoked multiple times).
-noStyles | false | If set to true, no styles will be applied to "Data loading" curtain.
-numberFields | | [CSV only] An array of fields in data to treat as numbers.
-postProcess | | If set to function reference, that function will be called to "post-process" loaded data before passing it on to chart. The handler function will receive two parameters: loaded data, Data Loader options.
+async | true | If set to false (not recommended) everything will wait until data is fully loaded
+complete | | Callback function to execute when loader is done
+delimiter | , | [CSV only] a delimiter for columns (use \t for tab delimiters)
+emptyAs | undefined | [CSV only] replace empty columns with whatever is set here
+error | | Callback function to execute if file load fails
+init | | Callback function to execute when Data Loader is initialized, before any loading starts
+format | json | Type of data: json, csv
+headers | | An array of objects with two properties (key and value) to attach to HTTP request
+load | | Callback function to execute when file is successfully loaded (might be invoked multiple times)
+noStyles | false | If set to true no styles will be applied to "Data loading" curtain
+numberFields | | [CSV only] An array of fields in data to treat as numbers
+postProcess | | If set to function reference, that function will be called to "post-process" loaded data before passing it on to chart. The handler function will receive two parameters: loaded data, Data Loader options
progress | | Set this to function reference to track progress of the load. The function will be passed in three parameters: global progress, individual file progress, file URL.
-showErrors | true | Show loading errors in a chart curtain.
-showCurtain | true| Show curtain over the chart area when loading data.
-reload | 0 | Reload data every X seconds.
-reverse | false | [CSV only] add data points in revers order.
-skip | 0 | [CSV only] skip X first rows in data (includes first row if useColumnNames is used).
-skipEmpty | true | [CSV only] Ignore empty lines in data.
-timestamp | false | Add current timestamp to data URLs (to avoid caching).
-useColumnNames | false | [CSV only] Use first row in data as column names when parsing.
+showErrors | true | Show loading errors in a chart curtain
+showCurtain | true| Show curtain over the chart area when loading data
+reload | 0 | Reload data every X seconds
+reverse | false | [CSV only] add data points in revers order
+skip | 0 | [CSV only] skip X first rows in data (includes first row if useColumnNames is used)
+skipEmpty | true | [CSV only] Ignore empty lines in data
+timestamp | false | Add current timestamp to data URLs (to avoid caching)
+useColumnNames | false | [CSV only] Use first row in data as column names when parsing
## Using in JavaScript Stock Chart
-In JavaScript Stock Chart, it works exactly the same as in other chart types,
-with the exception that `dataLoader` is set as a property to the data set
+In JavaScript Stock Chart it works exactly the same as in other chart types,
+with the exception that `dataLoader` is set as a property to the data set
definition. I.e.:
```
@@ -174,7 +174,7 @@ var chart = AmCharts.makeChart("chartdiv", {
### Can I also load event data the same way?
-Sure. You just add a `eventDataLoader` object to your data set. All the same
+Sure. You just add a `eventDataLoader` object to your data set. All the same
settings apply.
@@ -251,9 +251,9 @@ The three available functions are as follows:
Function | Parameters | Description
-------- | ---------- | -----------
-AmCharts.loadFile() | url, options, callback | Loads the file and passes it into callback function (unparsed).
-AmCharts.parseCSV() | data, options | Parses data in string CSV format and returns JavaScript Array.
-AmCharts.parseJSON() | data | Parses data in string JSON format and returns JavaScript Array.
+AmCharts.loadFile() | url, options, callback | Loads the file and passes it into callback function (unparsed)
+AmCharts.parseCSV() | data, options | Parses data in string CSV format and returns JavaScript Array
+AmCharts.parseJSON() | data | Parses data in string JSON format and returns JavaScript Array
The options passed into standalone functions are the same as discussed in [Complete list of available dataLoader settings](#complete-list-of-available-dataloader-settings) chapter.
@@ -280,16 +280,16 @@ AmCharts.loadFile(dataset_url, {}, function(data) {
## Translating into other languages
-Depending on configuration options, the plugin will display a small number of
+Depending on configuration options the plugin will display a small number of
text prompts, like 'Data loading...'.
-Plugin will try matching chart's `language` property and display text prompts in
+Plugin will try matching chart's `language` property and display text prompts in
a corresponding language. For that the plugin needs to have the translations.
-Some of the plugin translations are in **lang** subdirectory. Simply include the
+Some of the plugin translations are in **lang** subdirectory. Simply include the
one you need.
-If there is no translation to your language readily available, just grab en.js,
+If there is no translation to your language readily available, just grab en.js,
copy it and translate.
The structure is simple:
@@ -302,7 +302,7 @@ The phrase in English must be left intact.
When you're done, you can include your language as a JavaScript file.
-P.S. send us your translation so we can include it for the benefits of other
+P.S. send us your translation so we can include it for the benefits of other
users. Thanks!
@@ -354,72 +354,72 @@ http://www.apache.org/licenses/LICENSE-2.0
## Changelog
### 1.0.16
-* Added "numberFields" config array.
+* Added "numberFields" config array
### 1.0.15
-* Added "emptyAs" config property. Empty CSV values will be set to this (default `undefined`).
+* Added "emptyAs" config property. Empty CSV values will be set to this (default `undefined`)
### 1.0.14
-* Added "init" event handler, which is called **before** loading starts.
+* Added "init" event handler, which is called **before** loading starts
### 1.0.13
-* Added "progress" handler, which can be used to monitor data load progress.
+* Added "progress" handler, which can be used to monitor data load progress
### 1.0.12
-* Better default options handling in external calls to AmCharts.loadFile.
-* Fixed the latest version of Stock Chart not resetting to default pre-defined period.
-* New example: Using Data Loader functions externally (map_json_external_function.html).
+* Better default options handling in external calls to AmCharts.loadFile
+* Fixed the latest version of Stock Chart not resetting to default pre-defined period
+* New example: Using Data Loader functions externally (map_json_external_function.html)
### 1.0.11
* New translation: Added French translation. Thanks Remy!
-* Tweaks to allow better animation after data load on Pie chart.
+* Tweaks to allow better animation after data load on Pie chart
### 1.0.10
-* Fixed error related to headers not being set when using standalone data load functions.
+* Fixed error related to headers not being set when using standalone data load functions
### 1.0.9
-* Plugin will now ignore empty CSV lines by default (configurable with `skipEmpty` property).
+* Plugin will now ignore empty CSV lines by default (configurable with `skipEmpty` property)
### 1.0.8
-* Added `headers` config variable which allows adding custom headers to HTTP requests.
+* Added `headers` config variable which allows adding custom headers to HTTP requests
### 1.0.7
-* Fixed an issue with the Pie chart when it is being loaded in inactive tab.
+* Fixed an issue with the Pie chart when it is being loaded in inactive tab
### 1.0.6
-* Added support for Gauge chart (loads `arrows` array).
+* Added support for Gauge chart (loads `arrows` array)
### 1.0.5
-* Fixed JS error if periodSelector was not defined in chart config.
-* Now all callback functions (complete, error, load) receive additional parameter: chart.
-* postProcess function will now have "this" context set to Data Loader object as well as receive chart reference as third parameter.
+* Fixed JS error if periodSelector was not defined in chart config
+* Now all callback functions (complete, error, load) receive additional parameter: chart
+* postProcess function will now have "this" context set to Data Loader object as well as receive chart reference as third paramater
### 1.0.4
-* Added `chart.dataLoader.loadData()` function which can be used to manually trigger all data reload.
+* Added `chart.dataLoader.loadData()` function which can be used to manually trigger all data reload
### 1.0.3
-* Fixed the bug where defaults were not being applied properly.
-* Fixed the bug with translations not being applied properly.
-* Cleaned up the code (to pass JSHint validation).
+* Fixed the bug where defaults were not being applied properly
+* Fixed the bug with translations not being applied properly
+* Cleaned up the code (to pass JSHint validation)
### 1.0.2
-* Fixed the issue with modified Array prototypes.
+* Fixed the issue with modified Array prototypes
### 1.0.1
-* Added `complete`, `load` and `error` properties that can be set with function handlers to be invoked on load completion, successful file load or failed load respectively.
-* Fixed language container initialization bug.
-* Fixed bug that was causing parse errors not be displayed.
+* Added `complete`, `load` and `error` properties that can be set with function handlers to be invoked on load completion, successful file load or failed load respectively
+* Fixed language container initialization bug
+* Fixed bug that was causing parse errors not be displayed
### 1.0
-* Added GANTT chart support.
+* Added GANTT chart support
### 0.9.2
-* Added global data load methods that can be used to load and parse data by code outside plugin.
-* Trim CSV column names.
-* Translation added: Lithuanian.
+* Added global data load methods that can be used to load and parse data by code outside plugin
+* Trim CSV column names
+* Translation added: Lithuanian
### 0.9.1
-* Fix chart animations not playing after asynchronous load.
+* Fix chart animations not playing after asynchronous load
### 0.9
-* Initial release.
+* Initial release
\ No newline at end of file
diff --git a/webroot/amcharts/plugins/export/README.md b/webroot/amcharts/plugins/export/README.md
index 6ed6a93..b5cdc53 100644
--- a/webroot/amcharts/plugins/export/README.md
+++ b/webroot/amcharts/plugins/export/README.md
@@ -77,7 +77,7 @@ AmCharts.makeChart( "chartdiv", {
## Loading external libraries needed for operation of this plugin
-The plugin relies on a number of different libraries to export images, draw
+The plugin relies on a number of different libraries, to export images, draw
annotations or generate download files.
Those libraries need to be loaded for the plugin to work properly.
@@ -86,15 +86,15 @@ There are two ways to load them. Choose the one that is right:
### 1) Automatic (preferred)
-All libraries required for plugin operation are included within plugins */libs*
+All libraries required for plugin operation are included withing plugins */libs*
subdirectory.
-The plugin will automatically try to look in the chart's [`path`](http://docs.amcharts.com/3/javascriptcharts/AmSerialChart#path)
+The plugin will automatically try to look in chart's [`path`](http://docs.amcharts.com/3/javascriptcharts/AmSerialChart#path)
property. If your plugin files are located within plugins folder under amcharts
(as is the case with the default distributions), you don't need to do anything -
the libraries will load on-demand.
-If you are using relative URL, note that it is relative to the web page you are
+If you are using relative url, note that it is relative to the web page you are
displaying your chart on, not the export.js library.
In case you've moved the libs folder you need to tell the plugin where it is
@@ -122,41 +122,41 @@ xlsx.js | libs/xlsx/ | Export to XLSX format
Property | Default | Description
-------- | ------- | -----------
-backgroundColor | #FFFFFF | RGB code of the color for the background of the exported image.
-enabled | true | Enables or disables export functionality.
+backgroundColor | #FFFFFF | RGB code of the color for the background of the exported image
+enabled | true | Enables or disables export functionality
divId | | ID or a reference to div object in case you want the menu in a separate container.
-fabric | {} | Overwrites the default drawing settings (fabricJS library).
-fallback | {} | Holds the messages to guide the user to copy the generated output; `false` will disable the fallback feature.
-fileName | amCharts | A file name to use for generated export files (an extension will be appended to it based on the export format).
-legend | {} | Places the legend in case it is within an external container ([skip to chapter](#adding-external-legend)).
-libs | | 3rd party required library settings (see the above section).
-menu | [] | A list of menu or submenu items (see the next chapter for details).
-pdfMake | {} | Overwrites the default settings for PDF export (pdfMake library).
-position | top-right | A position of export icon. Possible values: "top-left", "top-right" (default), "bottom-left", "bottom-right".
-removeImages | true | If true, export checks for and removes "tainted" images that area loaded from different domains.
-delay | | General setting to delay the capturing of the chart ([skip to chapter](#delay-the-capturing-before-export)).
-exportFields | [] | If set, only fields in this array will be exported (data export only).
-exportTitles | false | Exchanges the data field names with its dedicated title (data export only).
+fabric | {} | Overwrites the default drawing settings (fabricJS library)
+fallback | {} | Holds the messages to guide the user to copy the generated output; `false` will disable the fallback feature
+fileName | amCharts | A file name to use for generated export files (an extension will be appended to it based on the export format)
+legend | {} | Places the legend in case it is within an external container ([skip to chapter](#adding-external-legend))
+libs | | 3rd party required library settings (see the above section)
+menu | [] | A list of menu or submenu items (see the next chapter for details)
+pdfMake | {} | Overwrites the default settings for PDF export (pdfMake library)
+position | top-right | A position of export icon. Possible values: "top-left", "top-right" (default), "bottom-left", "bottom-right"
+removeImages | true | If true export checks for and removes "tainted" images that area lodead from different domains
+delay | | General setting to delay the capturing of the chart ([skip to chapter](#delay-the-capturing-before-export))
+exportFields | [] | If set, only fields in this array will be exported ( data export only )
+exportTitles | false | Exchanges the data field names with it's dedicated title ( data export only )
columnNames | {} | An object of key/value pairs to use as column names when exporting to data formats. `exportTitles` needs to be set for this to work as well.
-exportSelection | false | Exports the current data selection only ( data export only ).
-dataDateFormat | | Format to convert date strings to date objects, uses by default charts dataDateFormat (data export only).
-dateFormat | YYYY-MM-DD | Formats the category field in given date format (data export only).
-keyListener | false | If true, it observes the pressed keys to undo/redo the annotations.
-fileListener | false | If true, it observes the drag and drop feature and loads the dropped image file into the annotation.
-drawing | {} | Object which holds all possible settings for the annotation mode ([skip to chapter](#annotation-settings)).
-overflow | true | Flag to overwrite the CSS attribute 'overflow' of the chart container to avoid cropping the menu on small container.
-border | {} | An object of key/value pairs to define the overlaying border.
-processData | | A function which can be used to change the dataProvider when exporting to CSV, XLSX, or JSON.
-pageOrigin | true | A flag to show/hide the origin of the generated PDF (pdf export only).
-forceRemoveImages | false | If true, export removes all images.
+exportSelection | false | Exports the current data selection only ( data export only )
+dataDateFormat | | Format to convert date strings to date objects, uses by default charts dataDateFormat ( data export only )
+dateFormat | YYYY-MM-DD | Formats the category field in given date format ( data export only )
+keyListener | false | If true it observes the pressed keys to undo/redo the annotations
+fileListener | false | If true it observes the drag and drop feature and loads the dropped image file into the annotation
+drawing | {} | Object which holds all possible settings for the annotation mode ([skip to chapter](#annotation-settings))
+overflow | true | Flag to overwrite the css attribute 'overflow' of the chart container to avoid cropping the menu on small container
+border | {} | An object of key/value pairs to define the overlaying border
+processData | | A function which can be used to change the dataProvider when exporting to CSV, XLSX, or JSON
+pageOrigin | true | A flag to show / hide the origin of the generated PDF ( pdf export only )
+forceRemoveImages | false | If true export removes all images
debug | false | A flag which enables the plugin to write console logs (currently used by the dependency handler only).
## Configuring export menu
Plugin includes a way to completely control what is displayed on export menu.
-You can set up menus and sub-menus down to any level. You can even add custom
-items there that execute your arbitrary code on click. It's so configurable,
+You can set up menus, sub-menus, down to any level. You can even add custom
+items there that execute your arbitrary code on click. It's so configurable
it makes us sick with power ;)
The top-level menu is configured via `menu` property under `export`. It should
@@ -189,15 +189,15 @@ icon:
* JPG
* CSV
-When clicked, the plugin will trigger export to a respective format.
+When clicked the plugin will trigger export to a respective format.
-If that is all you need, then you're all set.
+If that is all you need, you're all set.
-Please note that we have wrapped our menu into another menu item, so that only
-the icon is displayed until we roll over the icon. This means that technically,
+Please note that we have wrapped out menu into another menu item, so that only
+the icon is displayed until we roll over the icon. This means that technically
we have a two-level hierarchical menu.
-If we omitted that first step, the chart would simply display a format list
+If we opmitted that first step, the chart would simply display a format list
right there on the chart.
### Advanced menu setup
@@ -273,7 +273,7 @@ This needs to be a function reference. I.e.:
### Adding external legend
In case you have an external legend you need to define the position where it should get placed in your export.
-By default, it obtains the dimensions from the container, but you can optionally overwrite those settings as shown below.
+By default it obtains the dimensions from the container but you can optionally overwrite those settings as shown below.
```
"export": {
@@ -299,7 +299,7 @@ If you want to change the dataProvider when exporting to CSV, XLSX, or JSON, you
### Adding overlaying border
-In case you need a more visible separation of your chart for further processing, you can add an overlaying border.
+In case you need a more visible separation of your chart for further processing you can add an overlaying border.
```
"export": {
@@ -313,8 +313,8 @@ In case you need a more visible separation of your chart for further processing,
### Menu item reviver
-By passing the `menuReviver` callback function, you can modify the resulting menu
-item or relative container before it gets appended to the list (`ul`). The
+By passing the `menuReviver` callback function you can modify the resulting menu
+item or relative container, before it gets appended to the list (`ul`). The
function takes two arguments and it needs to return a valid DOM element.
```
@@ -328,7 +328,7 @@ function takes two arguments and it needs to return a valid DOM element.
#### Format specific options that you can override using Menu item reviver
-Some formats such as CSV, have specific parameters that are used when exporting to this format. For example, default column separator for CSV is a comma. But what if you would like to be that a tab? You could use `menuReviver` for that like this:
+Some formats, such as CSV, have specific parameters that are used when exporting to this format. For example, default column separator for CSV is a comma. But what if you would like to be that a tab? You could use `menuReviver` for that like this:
```
"export": {
@@ -348,45 +348,45 @@ Below you will find a list of parameters that you can override for each format:
Property | Default | Available values | Description
--------- | ------- | ---------------- | -----------
-quality |1 | 0-1 | A quality of the resulting JPG image.
-multiplier | 1 | number | Set this to a non-1 number to resize the resulting image by.
+quality |1 | 0-1 | A quality of the resulting JPG image
+multiplier | 1 | number | Set this to non-1 number to resize the resulting image by
**PNG**
Property | Default | Available values | Description
--------- | ------- | ---------------- | -----------
-quality | 1 | 0-1 | A quality of the resulting JPG image.
-multiplier | 1 | number | Set this to a non-1 number to resize the resulting image by.
+quality | 1 | 0-1 | A quality of the resulting JPG image
+multiplier | 1 | number | Set this to non-1 number to resize the resulting image by
**PDF**
Property | Default | Available values | Description
--------- | ------- | ---------------- | -----------
-multiplier | 2 | number | Set this to a non-1 number to resize the resulting image by.
+multiplier | 2 | number | Set this to non-1 number to resize the resulting image by
**PRINT**
Property | Default | Available values | Description
--------- | ------- | ---------------- | -----------
-delay | 1 | number | Delay by number of seconds before triggering print.
-lossless | false | true/false | Enable or disable image optimization when printing.
+delay | 1 | number | Delay by number of seconds before triggering print
+lossless | false | true/false | Enable or disable image optimization when printing
**CSV**
Property | Default | Available values | Description
--------- | ------- | ---------------- | -----------
-delimiter | "," | string | A string to use as a column delimiter.
-quotes | true | true/false | Set whether to enclose strings in doublequotes.
-escape | true | true/false | Set whether to escape strings.
-withHeader | true | true/false | Add header row with column names.
+delimiter | "," | string | A string to use as a column delimiter
+quotes | true | true/false | Set whether to enclose strings in doublequotes
+escape | true | true/false | Set whether to escape strings
+withHeader | true | true/false | Add header row with column names
**XLSX**
Property | Default | Available values | Description
--------- | ------- | ---------------- | -----------
-dateFormat | "dateObject" | "dateObject"\|"string" | Whether to export dates as dates recognizable by Excel, or formatted as strings.
-withHeader | true | true/false | Add header row with column names.
-stringify | false | true/false | Convert all cell content to strings.
+dateFormat | "dateObject" | "dateObject"\|"string" | Whether to export dates as dates recognisable by Excel or formatted as strings
+withHeader | true | true/false | Add header row with column names
+stringify | false | true/false | Convert all cell content to strings
### Menu walker
@@ -436,7 +436,7 @@ Or if you want to change the label:
OK, this one is so cool, you'll need a class 700 insulation jacket.
-By default, each menu item triggers some kind of export. You can trigger an
+By default each menu item triggers some kind of export. You can trigger an
"annotation" mode instead by including `"action": "draw"` instead.
```
@@ -458,7 +458,7 @@ Now, when you click on the "Annotate" item in the menu, the chart will turn into
an image editor which you can actual draw on and the menu gets replaced by the
default annotation menu.
-If you don't like the default annotation menu, you can define your own:
+If you don't like the detault annotation menu, you can define your own:
```
"export": {
@@ -480,7 +480,7 @@ If you don't like the default annotation menu, you can define your own:
```
Now, when you turn on the annotation mode, your own submenu will display,
-allowing you to export the image into either PNG, JPG, SVG or PDF.
+allowing to export the image into either PNG, JPG, SVG or PDF.
And that's not even the end of it. You can add menu items to cancel, undo, redo
and still be able to reuse the choices by using the actions `draw.modes`,
@@ -517,7 +517,7 @@ and still be able to reuse the choices by using the actions `draw.modes`,
### Annotation settings
-Since 1.2.1, it's also possible to set some of the annotation options without the
+Since 1.2.1 it's also possible to set some of the annotation options without the
need to re-define the whole menu structure. You can easily adjust the choice of
modes, colors, widths or shapes, and set the defaults when entering the
annotation mode.
@@ -569,8 +569,8 @@ the following:
### Delay the capturing before export
-In some cases, you may want to delay the capturing of the current chart snapshot
-to highlight the current value. For this, you can simply define the 'delay'
+In some cases you may want to delay the capturing of the current chart snapshot
+to highlight the current value. For this you can simply define the 'delay'
property in your menu item:
```
@@ -589,7 +589,7 @@ property in your menu item:
### Events
-Since version 1.1.7, the plugin introduces some events you can use. For example,
+Since version 1.1.7 the plugin introduces some events you can use. For example
the `afterCapture` event allows you to add some texts or images which can't be
seen on the regular chart but only the generated export. Use it to watermark
your exported images.
@@ -623,7 +623,7 @@ your exported images.
}],
```
-Since version 1.4.29, we have added the `onReady` callback to get your stuff done
+Since version 1.4.29 we have added the `onReady` callback to get your stuff done
right after the plugin or specific dependency is ready to use. Ensure to check the
`timedout` flag to be sure the dependency got fully loaded.
@@ -653,42 +653,42 @@ right after the plugin or specific dependency is ready to use. Ensure to check t
Name | Arguments | Description
---- | --------- | -----------
-beforeCapture | [menu item setup](#a-list-of-menu-item-properties) | Called before the SVG element gets converted.
-afterCapture | [menu item setup](#a-list-of-menu-item-properties) | Called right before the passed callback of the capture method.
+beforeCapture | [menu item setup](#a-list-of-menu-item-properties) | Called before the SVG element gets converted
+afterCapture | [menu item setup](#a-list-of-menu-item-properties) | Called right before the passed callback of the capture method
### A list of menu item properties
Property | Description
-------- | -----------
-action | Set to "draw" if you want the item to trigger annotation mode.
-class | Class name applied to the tag.
-click | Function handler invoked upon click on menu item.
-format | A format to export chart/map to upon click (see below for a list of available formats).
-icon | Icon file (will use chart's [path](http://docs.amcharts.com/3/javascriptcharts/AmSerialChart#path) if the URL is not full).
-label | Text label to be displayed.
-menu | An array of submenu items.
-title | A title attribute of the link.
-backgroundColor | The background color of the canvas.
-fileName | A file name to use for generated export files (an extension will be appended to it based on the export format).
-extension | File extension for the generated export file (uses format default if not defined).
-mimeType | Internet media type to generate the export file (uses format default if not defined).
-pageSize | A string or { width: number, height: number } ([details](#exporting-to-pdf)).
-pageOrientation | By default we use portrait. You can change it to landscape if you wish ([details](#exporting-to-pdf)).
-pageMargins | [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins ([details](#exporting-to-pdf)).
-content | Array of elements which represents the content ([details](#exporting-to-pdf)).
-multiplier | Scale factor for the generated image.
-lossless | Flag to print the actual vector graphic instead of buffered bitmap (print option only, experimental).
-delay | A numeric value to delay the capturing in seconds ([details](#delay-the-capturing-before-export)).
-exportFields | [] | If set, only fields in this array will be exported (data export only).
-exportTitles | Exchanges the data field names with its dedicated title (data export only).
-columnNames | An object of key/value pairs to use as column names when exporting (data export only).
-exportSelection | Exports the current data selection only (data export only).
-dataDateFormat | Format to convert date strings to date objects, uses by default charts dataDateFormat (data export only).
-dateFormat | Formats the category field in given date format (data export only).
-border | An object of key/value pairs to define the overlaying border.
-pageOrigin | A flag to show/hide the origin of the generated PDF (pdf export only).
-compress | A flag to compress the generated output (svg only).
+action | Set to "draw" if you want the item to trigger annotation mode
+class | Class name applied to the tag
+click | Function handler invoked upon click on menu item
+format | A format to export chart/map to upon click (see below for a list of available formats)
+icon | Icon file (will use chart's [path](http://docs.amcharts.com/3/javascriptcharts/AmSerialChart#path) if the URL is not full)
+label | Text label to be displayed
+menu | An array of submenu items
+title | A title attribute of the link
+backgroundColor | The background color of the canvas
+fileName | A file name to use for generated export files (an extension will be appended to it based on the export format)
+extension | File extension for the generated export file (uses format default if not defined)
+mimeType | Internet media type to generate the export file (usses format default if not defined)
+pageSize | A string or { width: number, height: number } ([details](#exporting-to-pdf))
+pageOrientation | By default we use portrait, you can change it to landscape if you wish ([details](#exporting-to-pdf))
+pageMargins | [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins ([details](#exporting-to-pdf))
+content | Array of elements which represents the content ([details](#exporting-to-pdf))
+multiplier | Scale factor for the generated image
+lossless | Flag to print the actual vector graphic instead of buffered bitmap (print option only, experimental)
+delay | A numeric value to delay the capturing in seconds ([details](#delay-the-capturing-before-export))
+exportFields | [] | If set, only fields in this array will be exported ( data export only )
+exportTitles | Exchanges the data field names with it's dedicated title ( data export only )
+columnNames | An object of key/value pairs to use as column names when exporting ( data export only )
+exportSelection | Exports the current data selection only ( data export only )
+dataDateFormat | Format to convert date strings to date objects, uses by default charts dataDateFormat ( data export only )
+dateFormat | Formats the category field in given date format ( data export only )
+border | An object of key/value pairs to define the overlaying border
+pageOrigin | A flag to show / hide the origin of the generated PDF ( pdf export only )
+compress | A flag to compress the generated output ( svg only )
Available `format` values:
@@ -716,7 +716,7 @@ a function that returns a string.
To include exported image, use `image: "reference"`.
-Additionally, you can add `fit` property, which is an array of pixel dimensions
+Additionally, you can add `fit` property which is an array of pixel dimensions,
you want the image to be scaled to fit into.
Here's an example of such export menu item:
@@ -733,10 +733,10 @@ Here's an example of such export menu item:
Property | Description
-------- | -----------
-pageSize | A string or {width: number, height: number}.
-pageOrientation | By default, we use portrait. You can change it to landscape if you wish.
-pageMargins | [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins.
-content | Array of elements which represents the content ([full description](https://github.com/bpampuch/pdfmake/)).
+pageSize | a string or { width: number, height: number }
+pageOrientation | by default we use portrait, you can change it to landscape if you wish
+pageMargins | [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
+content | array of elements which represents the content ([full description](https://github.com/bpampuch/pdfmake/))
Pagesize | Dimensions in pixel
-------- | -----------
@@ -796,7 +796,7 @@ TABLOID | [792.00, 1224.00]
The plugin comes with a default CSS file `export.css`. You just need to include
it on your page.
-Feel free to override any styles defined in it. Create your own version and
+Feel free to override any styles defined in it, create your own version and
modify as you see fit.
If you choose to modify it, we suggest creating a copy so it does not get
@@ -808,7 +808,7 @@ overwritten when you update amCharts or plugin.
We explained how you can define custom functions to be executed on click on
export menu items.
-Those functions can tap into a plugin's methods to augment it with some custom
+Those functions can tap into plugin's methods to augment it with some custom
functionality.
Here's an example:
@@ -838,29 +838,29 @@ Here's a full list of API functions available for your consumption:
Function | Parameters | Description
-------- | ---------- | -----------
-toJPG | (object) options, (function) callback | Prepares a JPEG representation of the chart and passes the binary data to the callback function.
-toPNG | (object) options, (function) callback | Prepares a PNG representation of the chart and passes the binary data to the callback function.
-toSVG | (object) options, (function) callback | Prepares a SVG representation of the chart and passes the binary data to the callback function.
-toPDF | (object) options, (function) callback | Prepares a PDF representation of the chart and passes the binary data to the callback function.
-toJSON | (object) options, (function) callback | Prepares a JSON and passes the plain data to the callback function.
-toCSV | (object) options, (function) callback | Prepares a CSV and passes the plain data to the callback function.
-toXLSX | (object) options, (function) callback | Prepares a XLSX representation of the chart and passes the binary data to the callback function.
-toBlob | (object) options, (function) callback | Prepares a BLOB and passes the instance to the callback function.
-toCanvas | (object) options, (function) callback | Prepares a Canvas and passes the element to the callback function.
-toArray | (object) options, (function) callback | Prepares an Array and passes the data to the callback function.
-toImage | (object) options, (function) callback | Generates an image element which holds the output in an embedded base64 data URL.
+toJPG | (object) options, (function) callback | Prepares a JPEG representation of the chart and passes the binary data to the callback function
+toPNG | (object) options, (function) callback | Prepares a PNG representation of the chart and passes the binary data to the callback function
+toSVG | (object) options, (function) callback | Prepares a SVG representation of the chart and passes the binary data to the callback function
+toPDF | (object) options, (function) callback | Prepares a PDF representation of the chart and passes the binary data to the callback function
+toJSON | (object) options, (function) callback | Prepares a JSON and passes the plain data to the callback function
+toCSV | (object) options, (function) callback | Prepares a CSV and passes the plain data to the callback function
+toXLSX | (object) options, (function) callback | Prepares a XLSX representation of the chart and passes the binary data to the callback function
+toBlob | (object) options, (function) callback | Prepares a BLOB and passes the instance to the callback function
+toCanvas | (object) options, (function) callback | Prepares a Canvas and passes the element to the callback function
+toArray | (object) options, (function) callback | Prepares an Array and passes the data to the callback function
+toImage | (object) options, (function) callback | Generates an image element which holds the output in an embedded base64 data url
## Annotation API
-Since version 1.4.27, we've introduced the functionality to manage the annotations on the fly. The setter returns an array of objects, where each element represents an annotation.
-On the other hand, the setter processes the given annotations within options (options.data). Both methods support the reviver callback which allows you to modify the annotations if needed.
+Since version 1.4.27 we've introduced the functionality to manage the annotations on the fly. The setter returns an array of objects, where each element represents an annotation.
+On the other hand the setter processes the given annotations within options (options.data). Both methods support the reviver callback which allows you to modify the annotations if needed.
Function | Parameters | Description
-------- | ---------- | -----------
getAnnotations | (object) options, (function) callback | Returns an array of objects where each element represents an annotation.
setAnnotations | (object) options, (function) callback | Draws the given annotations (options.data).
-Here's an example how to insert annotations. Please ensure your chart is in annotation mode:
+Here's an example how to insert annotations, please ensure your chart is in annotation mode:
```
chart.export.setAnnotations({
@@ -880,7 +880,7 @@ chart.export.setAnnotations({
},function() {
- // Callback when finished
+ // Callback when finished
});
```
@@ -897,7 +897,7 @@ you may need to add following metatag in your `` of your HTML document.
```
-This feature will kick in by default. If you want to disable it, simply pass
+This feature will kick in by default. If you want to disable it simply pass
`false` to the `fallback` parameter.
```
@@ -906,7 +906,7 @@ This feature will kick in by default. If you want to disable it, simply pass
}
```
-In case you want to change our default messages, you can modify it like the
+In case you want to change our default messages you can modify it like
following.
```
@@ -942,7 +942,7 @@ They're all in subdirectory /examples.
You're encouraged to modify, extend and make derivative plugins out of this
plugin.
-You can modify files included in this archive, or better yet, fork this project
+You can modify files, included in this archive or, better yet, fork this project
on GitHub:
https://github.com/amcharts/export
@@ -958,7 +958,7 @@ This plugin is licensed under Apache License 2.0.
This basically means you're free to use or modify this plugin, even make your
own versions or completely different products out of it.
-Please see attached file "license.txt" for the complete license, or online here:
+Please see attached file "license.txt" for the complete license or online here:
http://www.apache.org/licenses/LICENSE-2.0
@@ -977,49 +977,49 @@ http://www.apache.org/licenses/LICENSE-2.0
* Fixed: Menu active state on mouseleave.
### 1.4.65
-* Fixed: Menu active state issue, menu kept its active when it hasn't been re-rendered.
+* Fixed: Menu active state issue, menu kept its active when it hasn't been rerendered.
### 1.4.64
-* Fixed: classList issue on IE11.
+* Fixed: classList issue on IE11
### 1.4.63
-* Fixed: Clip-path issue on graph lines.
+* Fixed: Clip-path issue on graph lines
### 1.4.62
-* Fixed: Gantt category issue..
+* Fixed: Gantt category issue
### 1.4.61
-* Fixed: SmoothCustomBullet plugin support, clip-path issue on curved corners.
+* Fixed: SmoothCustomBullet plugin support, clip-path issue on curved corners
### 1.4.60
-* Fixed: Empty print output in chrome version 57.
+* Fixed: Empty print output in chrome version 57
### 1.4.59
-* Fixed: Issue with blurred element when closing annotation mode.
+* Fixed: Issue with blurred element when closing annotation mode
### 1.4.58
-* Fixed: SVG clip-path export issue; injection control; wrap elements to support fill reference.
-* Fixed: Keyboard navigation disabled on touch devices.
+* Fixed: SVG clip-path export issue; injection control; wrap elements to support fill reference
+* Fixed: Keyboard navigation disabled on touch devices
### 1.4.57
* Added: Support for keyboard navigation (tabs and arrow keys).
-* Fixed: Merged pull request [#84](https://github.com/amcharts/export/pull/54) fixing an issue when "a" is undefined within deepMerge (thanks to [RahavLussato](https://github.com/RahavLussato)).
+* Fixed: Merged pull request [#84](https://github.com/amcharts/export/pull/54) fixing an issue when "a" is undefined within deepMerge (thanks to [RahavLussato](https://github.com/RahavLussato) )
### 1.4.56
* Added: Dependency handler on export methods, holds the actual call until the namespace shows up in current scope (uses libs.loadTimeout).
### 1.4.55
-* Added: Radial gradient issue on pie caused by the vertical gradient fix (v1.4.44).
+* Added: Radial gradient issue on pie caused by the vertical gradient fix (v1.4.44)
### 1.4.54
-* Fixed: Default text size on width changes.
+* Fixed: Default text size on width changes
### 1.4.53
-* Fixed: IOS print issue, captured the whole page instead of the single page.
+* Fixed: IOS print issue, captured the whole page instead of the single page
### 1.4.52
-* Fixed: Blank export issue specifically in chrome on IOS devices.
-* Updated: FileSaver.js due the chrome export issue on IOS.
+* Fixed: Blank export issue especifically in chrome on IOS devices.
+* Updated: FileSaver.js due the chrome export issue on IOS
### 1.4.51
* Fixed: Render issue on maps due half pixel position correction; simplified the positioning.
@@ -1037,118 +1037,118 @@ http://www.apache.org/licenses/LICENSE-2.0
* Fixed: `afterCapture` issue which removed injected elements.
### 1.4.46
-* Fixed: toSVG clipPath issue which exported multiple times the same clipPath.
+* Fixed: toSVG clipPath issue which exported multiple times the same clipPath
### 1.4.45
-* Fixed: Object selection issue on charts with heavy amount of datapoints.
-* Fixed: Line/Arrow drawing issue on vertical movement.
-* Changed: Pressing escape while an object has been selected will deselect first instead quitting the annotation mode.
+* Fixed: Object selection issue on charts with heavy amount of datapoints
+* Fixed: Line/Arrow drawing issue on vertical movement
+* Changed: Pressing escape while an object has been selected will deselect first instead quiting the annotation mode
### 1.4.44
-* Fixed: Vertical gradient issue.
+* Fixed: Vertical gradient issue
### 1.4.43
-* Fixed: Shown label in hidden valueAxis.
+* Fixed: Shown label in hidden valueAxis
### 1.4.42
-* Fixed: `exportFields` issue in combination with `columnNames` or `exportTitles`.
-* Added: `dataFieldsTitlesMap` into `processData` context to be able to trace back the translated keys against the data fields.
+* Fixed: `exportFields` issue in combination with `columnNames` or `exportTitles`
+* Added: `dataFieldsTitlesMap` into `processData` context to be able to trace back the translated keys against the data fields
### 1.4.41
-* Added: quote, escape option to `toArray` method.
-* Fixed: toArray method to respect `exportFields` order.
-* Fixed: toCSV, toXLSX to respect `exportFields` order.
+* Added: quote, escape option to `toArray` method
+* Fixed: toArray method to respect `exportFields` order
+* Fixed: toCSV, toXLSX to respect `exportFields` order
### 1.4.40
* Fixed: Infinite loop in Angular2 Zones
-* Fixed: `compress` option being obtained from the global config.
+* Fixed: `compress` option being obtained from the global config
### 1.4.39
* Added: New menu option `compress` to compress the generated output (svg only).
* Fixed: Strikethrough issue in SVG output.
### 1.4.38
-* Fixed: Support for external stock chart legends, overlapping issue with free licensed version of amcharts.
+* Fixed: Support for external stock chart legends, overlapping issue with free licensed version of amcharts
### 1.4.37
-* Fixed: Gradient issue which left the chart elements hidden after the export process.
-* Fixed: Typo in examples dropdown.
-* Added: Support for external stock chart legends.
+* Fixed: Gradient issue which left the chart elements hidden after the export process
+* Fixed: Typo in examples dropdown
+* Added: Support for external stock chart legends
### 1.4.36
-* Fixed: exportFields order being considered.
-* Fixed: Keep scroll position after printing.
-* Fixed: Namespace key issue with minified resource versions.
+* Fixed: exportFields order being considered
+* Fixed: Keep scroll position after printing
+* Fixed: Namespace key issue with minified resource versions
### 1.4.35
-* Fixed: Menu handling issue on touch devices, uses CSS classname to toggle menu items (updated CSS file, on devices only where the "Touch" object is within window scope).
+* Fixed: Menu handling issue on touch devices, uses css classname to toggle menu items (updated CSS file, on devices only where the "Touch" object is within window scope)
### 1.4.34
-* Fixed: Data shifting issue in data exports with compared graphs (stock only).
-* Fixed: Shallow copy of compared graphs in data exports (stock only).
+* Fixed: Data shifting issue in data exports with compared graphs (stock only)
+* Fixed: Shallow copy of compared graphs in data exports (stock only)
### 1.4.33
-* Fixed: fill/stroke polyfilling issue on svg elements with color validation/preparation for fabric.
+* Fixed: fill/stroke polyfilling issue on svg elements with color validation/preparation for fabric
### 1.4.32
-* Fixed: Issue polyfilling the color attributes with "rgba" color codes.
+* Fixed: Issue polyfilling the color attributes with "rgba" color codes
### 1.4.31
-* Changed: Included independent IE detection to handle specific IE10, IE11 svg image in canvas issue.
+* Changed: Included independent IE detection to handle specific IE10, IE11 svg image in canvas issue
### 1.4.30
-* Fixed: Pattern loading, positioning issue, supports x,y offset now.
+* Fixed: Pattern loading, positioning issue, supports x,y offset now
### 1.4.29
-* Added: `libs.loadTimeout` dependency namespace timeout used within onReady handler.
-* Added: `fabric.loadTimeout` loading image timeout to avoid blocking the export process.
-* Added: [onReady](#events) ready callback handler to get notified when the export or specific dependency is ready to use.
-* Fixed: fill/stroke issue on SVG elements which caused a crash within the export process.
-* Fixed: Image loader which froze occasionally and caused an unexpected behaviour.
+* Added: `libs.loadTimeout` dependency namespace timeout used within onReady handler
+* Added: `fabric.loadTimeout` loading image timeout to avoid blocking the export process
+* Added: [onReady](#events) ready callback handler to get notified when the export or specific dependency is ready to use
+* Fixed: fill/stroke issue on SVG elements which caused a crash within the export process
+* Fixed: Image loader which freezed occasionally and caused an unexpected behaviour
### 1.4.28
-* Fixed: Positioning / handling issue on multiline labels (injected modified fabricJS snippet to handle it).
-* Fixed: Cursor issue on regular exports which flashed the crosshair cursor for a moment.
+* Fixed: Positioning / handling issue on multiline labels (injected modifed fabricJS snippet to handle it)
+* Fixed: Cursor issue on regular exports which flashed the crosshair cursor for a moment
### 1.4.27
* Added: [Annotations API](#annotations-api) to get or set annotations within drawing mode.
### 1.4.26
-* Fixed: IE10 SVG image handing issue, caused by an internal bug of IE10 (removes SVGs automatically to avoid triggering the security policy).
+* Fixed: IE10 SVG image handing issue, caused by an internal bug of IE10 (removes SVGs automatically to avoid triggering the security policy)
### 1.4.25
-* Fixed: `export.config.advanced.js` sample config issue with drawing callbacks.
-* Fixed: `delay` property reset issue, did not get considered after first usage.
-* Fixed: `drawing.enabled` property issue after first usage, stayed on true.
-* Changed: Updated fabric.js source to `1.6.2`.
-* Added: Advanced sample using the advanced config.
+* Fixed: `export.config.advanced.js` sample config issue with drawing callbacks
+* Fixed: `delay` property reset issue, did not get considered after first usage
+* Fixed: `drawing.enabled` propery issue after first usage, stayed on true
+* Changed: Updated fabric.js source to `1.6.2`
+* Added: Advanced sample using the advanced config
### 1.4.24
-* Fixed: Issue with external legends in maps.
-* Fixed: Resource dependency issue of xlsx with jszip.
-* Fixed: Issue with `forceRemoveImages` in local environment (includes all ":\" and "file://" sources).
-* Changed: Resource loading order according to it's priority.
-* Changed: Loading minified resource versions by default to improve the payload significantly.
+* Fixed: Issue with external legends in maps
+* Fixed: Resource dependency issue of xlsx with jszip
+* Fixed: Issue with `forceRemoveImages` in local enviroment (includes all ":\" and "file://" sources)
+* Changed: Resource loading order according to it's priority
+* Changed: Loading minified resource versions by default to improve the payload significantly
### 1.4.23
-* Fixed: Issue with `forceRemoveImages` in local environment.
+* Fixed: Issue with `forceRemoveImages` in local enviroment
### 1.4.22
-* Fixed: Local time offset issue on XLSX exports.
-* Added: `forceRemoveImages` to remove images regardless if they are tainted or not.
-* Added: Used config ([processData](#changing-the-dataprovider-when-exporting)) as additional given parameter..
+* Fixed: Local time offset issue on XLSX exports
+* Added: `forceRemoveImages` to remove images regardless if they are tainted or not
+* Added: Used config ([processData](#changing-the-dataprovider-when-exporting)) as additional given parameter.
### 1.4.21
* Fixed: Issue with file:// image origin, forced removal as it does not fit to the CORS policy and blocks the image export.
### 1.4.20
-* Fixed: Issue with disappearing images in PDFs caused by exceeding boundary box for images.
+* Fixed: Issue with disappearing images in PDFs caused by exceeding boundary box for images
### 1.4.19
-* Fixed: Issue with radial gradient.
+* Fixed: Issue with radial gradient
### 1.4.18
-* Fixed: Issue with the legend positioning on the left side.
+* Fixed: Issue with the legend positioning on the left side
### 1.4.17
* Fixed: `clip-path` issue on XY serial charts which exposed the drawn line beyond the plotarea.
@@ -1163,219 +1163,219 @@ http://www.apache.org/licenses/LICENSE-2.0
* Added: ([border](#adding-overlaying-border)) config-property to add an overlaying border on the output image.
### 1.4.13
-* Fixed: Issue on balloons showing it's content as HTML added "textContent" as alternative getter.
+* Fixed: Issue on balloons showing it's content as HTML added "textContent" as alternative getter
### 1.4.12
-* Fixed: clipPath issue on SVG export (workaround until fabricJS handles that by themselves).
+* Fixed: clipPath issue on SVG export (workaround until fabricJS handles that by themselves)
### 1.4.11
-* Fixed: Depth issue on value labels on columns.
+* Fixed: Depth issue on value labels on columns
### 1.4.10
-* Fixed: potential vulnerability with anonymous function declaration.
+* Fixed: potential vulnerability with anonymous function declaration
### 1.4.9
-* Added: Radial gradient support on pie charts (new feature in amCharts v3.18.0).
+* Added: Radial gradient support on pie charts (new feature in amCharts v3.18.0)
### 1.4.8
-* Fixed: Clippath positioning issue.
-* Fixed: Issue removing tainted images.
-* Fixed: Hashbanged URL interpretation issue in IE (related to reusable svg nodes).
+* Fixed: Clippath positioning issue
+* Fixed: Issue removing tainted images
+* Fixed: Hashbanged url interpretation issue in IE (related to reusable svg nodes)
### 1.4.7
-* Fixed: Zeroes were being exported to data formats as empty strings rather than numbers.
+* Fixed: Zeroes were being exported to data formats as empty strings rather than numbers
### 1.4.6
-* Fixed: Loading issue with patterns in Firefox.
+* Fixed: Loading issue with patterns in firefox
### 1.4.5
-* Fixed: Issue with the "canvas-container" on chart revalidations.
+* Fixed: Issue with the "canvas-container" on chart revalidations
### 1.4.4
-* Added: Balloon text orientation.
-* Fixed: Issue with multiline label positioning.
+* Added: Balloon text orientation
+* Fixed: Issue with multiline label positioning
### 1.4.3
-* Added: `exportFields` option which is an array of fields to export in data formats (if you want to export just some fields as opposed to all fields).
+* Added: `exportFields` option which is an array of fields to export in data formats (if you want to export just some fields as opposed to all fields)
### 1.4.2
-* Added: `overflow` flag to overwrite the CSS attribute 'overflow' of the chart container.
+* Added: `overflow` flag to overwrite the css attribute 'overflow' of the chart container
### 1.4.1
-* Fixed: cropped bullets on XY charts.
+* Fixed: cropped bullets on XY charts
### 1.4.0
-* Fixed: beforeCapture issue on SVG document changes.
-* Added: Namespace check within globals for required third-party software.
+* Fixed: beforeCapture issue on SVG document changes
+* Added: Namespace check within globals for required third party software
### 1.3.9
-* Fixed: Base tag gradient drawing issue (includes embedded hotfix for fabricjs commit #c9745ff).
+* Fixed: Base tag gradient drawing issue (includes embedded hotfix for fabricjs commit #c9745ff)
### 1.3.8
-* Fixed: Base tag clip path issue which draw the lines outside the plotarea.
+* Fixed: Base tag clip path issue which draw the lines outside the plotarea
### 1.3.7
-* Added: `columnNames` property, which allows overriding column names when exporting chart data.
+* Added: `columnNames` property, which allows overriding column names when expoerting chart data
### 1.3.6
-* Fixed: Checking parseDates for category values for date interpretation.
+* Fixed: Checking parseDates for category values for date interpretation
### 1.3.5
-* Fixed: Scrollbar issue hiding the unselected scrollbar background area.
+* Fixed: Scrollbar issue hiding the unselected scrollbar background area
### 1.3.4
* Fixed: Absolute legend positioning issue.
### 1.3.3
-* Added: English as default language when define language does not exist.
+* Added: English as default language when define language does not exist
### 1.3.2
-* Added: ([drawing.autoClose](#annotation-settings)) new flag to automatically close the annotation mode after download.
-* Fixed: Internal pdfMake issue which prevented to generate PDFs in IE10, uses custom build until officially fixed.
+* Added: ([drawing.autoClose](#annotation-settings)) new flag to automatically close the annotation mode after download
+* Fixed: Internal pdfMake issue which prevented to generate PDFs in IE10, uses custom build until officially fixed
### 1.3.1
-* Added: Timestamp date fields get converted as dates.
-* Fixed: XLSX respects given dateFormat.
-* Changed: JSON exports date fields as date objects by default.
+* Added: Timestamp date fields get converted as dates
+* Fixed: XLSX respects given dateFormat
+* Changed: JSON exports date fields as date objects by default
### 1.3.0
-* Fixed: Issue hiding drawing container on "drawing.done".
-* Fixed: Legend positioning issue with charts created in a hidden container.
+* Fixed: Issue hiding drawing container on "drawing.done"
+* Fixed: Legend positioning issue with charts created in a hidden container
### 1.2.9
-* Fixed: Issue with missing `export.css` which showed the canvas.
-* Fixed: Issue with empty menu items; adds list only with childNodes > 1.
-* Fixed: Issue with hidden bullets; caused by wrong clip-paths.
-* Added: Polish language file (thanks to piernik).
+* Fixed: Issue with missing `export.css` which showed the canvas
+* Fixed: Issue with empty menu items; adds list only with childNodes > 1
+* Fixed: Issue with hidden bullets; caused by wrong clip-paths
+* Added: Polish language file ( thanks to piernik )
### 1.2.8
-* Fixed: Issue in `gatherClassName` checking element type.
+* Fixed: Issue in `gatherClassName` checking element type
### 1.2.7
-* Fixed: Generates true JPG file instead PNG with JPG extension.
-* Fixed: Drag & Drop feature does not activate automatically the annotation mode.
+* Fixed: Generates true JPG file instead PNG with JPG extension
+* Fixed: Drag&Drop feature does not activate automatically the annotation mode
### 1.2.6
-* Added: Native EXCEL date cell type for date fields, forced by default.
-* Fixed: Issue in `getChartData` which ignored given data array (affected API usage only).
+* Added: Native EXCEL date cell type for date fields, forced by default
+* Fixed: Issue in `getChartData` which ignored given data array ( affected API usage only )
### 1.2.5
-* Added: Illustrator support; `reviver` method to `toSVG`; converts by default RGBA to HEX colors codes and places it's dedicated opacity. property
-* Fixed: Multiline text positioning/line heights.
+* Added: Illustrator support; `reviver` method to `toSVG`; converts by default RGBA to HEX colors codes and places it's dedicated opacity property
+* Fixed: Multiline text positioning / line heights
### 1.2.4
-* Added: `exportSelection` exports the current data selection.
-* Added: `dataDateFormat` converts the date-strings to date objects with given format.
-* Added: `dateFormat` converts the date in given format.
-* Added: `processData` to format date fields and translate fields.
-* Changed: `gatherChartData` collects data, fields and titles only and uses `processData` to format.
+* Added: `exportSelection` exports the current data selection
+* Added: `dataDateFormat` converts the date-strings to date objects with given format
+* Added: `dateFormat` converts the date in given format
+* Added: `processData` to format date fields and translate fields
+* Changed: `gatherChartData` collects data, fields and titles only and uses `processData` to format
### 1.2.3
-* Fixed: Positioning issue on multiline labels.
+* Fixed: Positioning issue on multiline labels
### 1.2.2
-* Fixed: Issue with object changes which overwrite undo/redo object states.
-* Fixed: Issue with default fontSize.
+* Fixed: Issue with object changes which overwrite undo/redo object states
+* Fixed: Issue with default fontSize
### 1.2.1
-* Added: Possibility to add text, lines, shapes ([details](#annotation-settings)).
-* Added: Possibility to change drawing mode, color, opacity and size.
-* Added: Possibility to select move, scale, and drawn items.
-* Added: Possibility to define dedicated drawing menu `drawing.menu` individual menu items get prioritized.
-* Added: Dropbox feature which allows to drag images into the chart `fileListener: true`.
-* Added: Keylistener which allows to undo/redo/remove the drawn steps `keyListener: true`.
-* Added: Isolated plugin to be able to initiate manually regardless of the chart setup.
-* Fixed: Conflict with prototypeJS which caused tainted return value from `toArray`.
+* Added: Possibility to add text, lines, shapes ([details](#annotation-settings))
+* Added: Possibility to change drawing mode, color, opacity and size
+* Added: Possibility to select,move,scale drawn items
+* Added: Possibility to define dedicated drawing menu `drawing.menu` individual menu items get prioritised
+* Added: Dropbox feature which allows to drag images into the chart `fileListener: true`
+* Added: Keylistener which allows to undo/redo/remove the drawn steps `keyListener: true`
+* Added: Isolated plugin to be able to initiate manually regardless of the chart setup
+* Fixed: Conflict with prototypeJS which caused tainted return value from `toArray`
### 1.2.0
-* Fixed: Issue with deepMerge which did not allow modifying the pdfMake default settings.
-* Fixed: Menu issue which did not allow modifying the pdfMake settings.
-* Fixed: Undo issue which needed double attempts in the beginning.
-* Added: Drag/Scale feature in annotation mode; toggles automatically between drawing/dragging while hovering over the elements.
+* Fixed: Issue with deepMerge which did not allow to modfiy the pdfMake default settings
+* Fixed: Menu issue which did not allow to modify the pdfMake settings
+* Fixed: Undo issue which needed double attempts in the beginning
+* Added: Drag/Scale feature in annotation mode; toggles automatically between drawing/dragging while hovering over the elements
### 1.1.9
-* Added: `exportTitles` available in general or individual setup which exchanges the data field names with it's dedicated title.
-* Fix: Interpolates missing data fields across data provider.
+* Added: `exportTitles` available in general or individual setup which exchanges the data field names with it's dedicated title
+* Fix: Interpolates missing data fields across data provider
### 1.1.8
-* Added: Temporary workaround to bypass FileSaver check; issue prevented to open blob URLs in Safari browser.
+* Added: Temporary workaround to bypass FileSaver check; issue prevented to open blob urls in safari browser
### 1.1.7
-* Added: beforeCapture to be able to indicate the export process in some way.
-* Added: afterCapture to be able to modify the fabric instance if needed.
-* Added: SVG element as second argument within the "reviver" callback.
-* Added: Multiple arguments supported in "handleCallback" method.
+* Added: beforeCapture to be able to indicate the export process in some way
+* Added: afterCapture to be able to modify the fabric instance if needed
+* Added: SVG element as second argument within the "reviver" callback
+* Added: Multiple arguments supported in "handleCallback" method
### 1.1.6
* Fix: Pattern render issue in IE;
-* Added: Multiline support (workaround until fabricJS supports tspan).
-* Added: General delay property to delay the capturing of the chart ([details](#delay-the-capturing-before-export)).
+* Added: Multiline support (workaround until fabricJS supports tspan)
+* Added: General delay property to delay the capturing of the chart ([details](#delay-the-capturing-before-export))
### 1.1.5
-* Fix: Tainted check issue which failed if location.origin wasn't available.
-* Fix: Capture image check, triggers callback only if all images have been loaded.
-* Added: Multi language support; embedded English by default; overtakes chart language.
-* Added: Delay feature, which allows to delay the capturing ([details](#delay-the-capturing-before-export)).
+* Fix: Tainted check issue which failed if location.origin wasn't available
+* Fix: Capture image check, triggers callback only if all images have been loaded
+* Added: Multi language support; embedded english by default; overtakes chart language
+* Added: Delay feature, which allows to delay the capturing ([details](#delay-the-capturing-before-export))
### 1.1.4
-* Fix: Did not collect clip-path and pattern from legend.
-* Fix: External legend did not respect given width when positioned on left side.
-* Fix: Improved tainted image detection.
+* Fix: Did not collect clip-path and pattern from legend
+* Fix: External legend did not respect given width when positioned on left side
+* Fix: Improved tainted image detection
### 1.1.3
-* Added: Added reviver in capturing method to filter the drawn chart elements.
+* Added: Added reviver in capturing method to filter the drawn chart elements
### 1.1.2
-* Added: Generalized fallback; does a lookup on the Blob constructor.
-* Fix: Wait for lazy images, triggers capture callback only when all images have been fully loaded.
-* Discovered: [Safari 5 issue](https://github.com/kangax/fabric.js/issues/2241) please adapt fabric.js manually to solve it.
+* Added: Generalized fallback; does a lookup on the Blob constructor
+* Fix: Wait for lazy images, triggers capture callback only when all images have been fully loaded
+* Discovered: [Safari 5 issue](https://github.com/kangax/fabric.js/issues/2241) please adapt fabric.js manually to solve it
### 1.1.1
-* Fix: CSV export issue on date based charts.
-* Fix: Enhanced migration script to obtain more settings.
+* Fix: CSV export issue on date based charts
+* Fix: Enhanced migration script to obtain more settings
### 1.1.0
-* Fix: Print issue on safari which captured the actual page instead of the export.
-* Added: IE9 download fallback for `text/plain` and `image/*` mime types (CSS has been modified).
-* Added: `toImage` method; returns `img` element with embedded base64 imagery.
-* Added: `getBase64` option in `toSVG`.
+* Fix: Print issue on safari which captured the actual page instead of the export
+* Added: IE9 download fallback for `text/plain` and `image/*` mime types (CSS has been modified)
+* Added: `toImage` method; returns `img` element with embedded base64 imagery
+* Added: `getBase64` option in `toSVG`
* Added: `toImage` usage in `toPRINT` to be able to choose the image type + settings.
-* Added: `lossless` option in `toPRINT` (experimental).
+* Added: `lossless` option in `toPRINT` (experimental)
### 1.0.9
-* Added: IE9 base64 export.
-* Added: Third party updates + minified versions.
+* Added: IE9 base64 export
+* Added: Third party updates + minified versions
### 1.0.8
-* Fix: IE8 issue which prevents the chart from initiating.
+* Fix: IE8 issue which prevents the chart from initiating
### 1.0.7
-* Fix: issue on toCSV handling the header (first row).
+* Fix: issue on toCSV handling the header (first row)
### 1.0.6
* Fix: issue on revalidation the chart/map
-* Added: [path](http://docs.amcharts.com/3/javascriptcharts/AmSerialChart#path) to load the libraries by default.
+* Added: [path](http://docs.amcharts.com/3/javascriptcharts/AmSerialChart#path) to load the libaries by default
### 1.0.5
-* Added: divId to be able to place the menu within an external container.
-* Added: menuWalker to replace the whole menu generation.
-* Added: menuReviver to adapt menu items before being appended to the list.
-* Added: libs.async to load dependencies asynchronous (default true).
+* Added: divId to be able to place the menu within an external container
+* Added: menuWalker to replace the whole menu generation
+* Added: menuReviver to adapt menu items before being appended to the list
+* Added: libs.async to load dependencies asynchronous (default true)
### 1.0.4
-* Considering classNamePrefix (don't forget to adapt export.css).
-* Added: Safety delay on print restore to ensure capturing the canvas.
+* Considering classNamePrefix (dont't forget to adapt export.css)
+* Added: safety delay on print restore to ensure capturing the canvas
### 1.0.3
-* Fix: Flagged relative image paths as tainted.
+* Fix: flagged relative image paths as tainted
### 1.0.2
-* Fix: Compatibility on array method extension such as PrototypeJS.
+* Fix: compabitily on array method extension such as PrototypeJS
### 1.0.1
-* Added: libs.reload: false, script tag crawling to avoid multiple insertions.
-* Fix: IE10 bug on print.
-* Fix: migration bug, replaces menu instead of appending.
+* Added: libs.reload: false, script tag crawling to avoid multiple insertions
+* Fix: IE10 bug on print
+* Fix: migration bug, replaces menu instead of appending
### 1.0
-* Initial release.
+* Initial release
\ No newline at end of file
diff --git a/webroot/css/bids-chart.css b/webroot/css/bids-chart.css
deleted file mode 100644
index 48a41f4..0000000
--- a/webroot/css/bids-chart.css
+++ /dev/null
@@ -1,8 +0,0 @@
-.bids-chart-container { width: 1200px; margin: 0 auto 48px auto; box-shadow: 0 2px 6px rgba(0,0,0,.175); border: 1px solid rgba(0,0,0,.15); padding: 24px 36px; position: relative; overflow: hidden }
-.bids-chart-container .load-progress { position: absolute; top: 0; left: 0; width: 100%; height: 3px; background: #1e88e5; animation: indeterminate 4s linear infinite; }
-.bids-chart-container .chart { height: 414px }
-.bids-chart-container .btn-chart-export { position: absolute; right: 40px; bottom: 36px }
-@keyframes indeterminate {
- from { left: -70%; }
- to { left: 100% }
-}
\ No newline at end of file
diff --git a/webroot/css/main.css b/webroot/css/main.css
index b10df30..3f4b3b0 100644
--- a/webroot/css/main.css
+++ b/webroot/css/main.css
@@ -6,14 +6,14 @@
a:link, a:visited { color: #1e88e5; text-decoration: none }
a:hover { text-decoration: underline; color: #1976d2 }
-.header { width: 1200px; margin: 0 auto 24px auto; padding: 12px 0 50px 0; border-bottom: 1px solid #ddd }
+.header { width: 1200px; margin: 0 auto 24px auto; padding: 12px 0 64px 0; border-bottom: 1px solid #ddd }
.header a:link, .header a:visited { color: #333; text-decoration: none }
.header .title { font-family: 'adelle-sans', sans-serif; font-weight: bold; font-size: 140%; float: left; position: relative; top: 4px }
.header .search { float: right }
.header .search .input-group { border: 2px solid #1e88e5; position: relative; width: 525px; height: 36px; border-radius: 8px }
.header .search .input-group input { border: none; border-radius: 8px; padding: 8px 133px 8px 8px; width: 100%; height: 32px; width: 521px }
.header .search .input-group .btn-inline-search { border: none; cursor: pointer; position: absolute; right: -4px; top: 0; height: 100%; background: #1e88e5; color: #fff; width: 125px;
-border-radius: 0 8px 8px 0 }
+border-radius: 0 6px 8px 0 }
.header .search .input-group .btn-inline-search:hover { background: #1976d2 }
.home-container-cell > .main > .title { font-family: 'adelle-sans', sans-serif; font-weight: bold; font-size: 280%; margin: 24px auto 24px auto; width: 600px; text-align: center; color: #333; cursor: default }
@@ -21,8 +21,7 @@ border-radius: 0 8px 8px 0 }
.home-container-cell .ctls { width: 720px; text-align: center; margin: 24px auto; position: relative }
.home-container-cell .ctls .btn-search { font-size: 115%; display: inline-block; padding: 12px 48px; background: #1e88e5; color: #fff; border-radius: 8px; border: none; font-weight: 300; cursor: pointer }
.home-container-cell .ctls .btn-search:hover { background: #1976d2 }
-.home-container-cell .ctls .left-links { display: inline-block; font-weight: 300; position: absolute; left: 0; padding-top: 12px; }
-.home-container-cell .ctls .right-links { display: inline-block; font-weight: 300; position: absolute; right: 0; padding-top: 12px; }
+.home-container-cell .ctls .links { display: inline-block; font-weight: 300; position: absolute; right: 0; padding-top: 12px; }
.home-container-cell .ctls a { font-size: 115%; display: inline-block; margin-right: 12px }
.home-container-cell .ctls a.last { margin-left: 12px; margin-right: 0 }
.home-container-cell .ctls a:hover { text-decoration: none; color: #1976d2 }
@@ -60,7 +59,7 @@ border-radius: 0 8px 8px 0 }
.claims-head h2 { font-weight: 300; margin-bottom: 0; font-size: 220% }
.claims-head { width: 1200px; margin: 0 auto 24px auto; cursor: default }
.claims-head h3, h4 { font-weight: 300; margin: 0 }
-.claims-head h3 { font-size: 170%; margin-bottom: 3px }
+.claims-head h3 { font-size: 200%; margin-bottom: 3px }
.claims-head h4 { font-size: 125% }
.claims-grid { width: 1200px; margin: 0 auto 0 auto; cursor: default }
@@ -81,28 +80,23 @@ border-radius: 0 8px 8px 0 }
.claims-grid .claim-grid-item .thumbnail .autothumb { display: block; margin: 73px auto 0 auto; text-align: center; font-size: 240%; color: #fff; line-height: 54px }
.claims-grid .claim-grid-item .tags > div { display: inline-block; padding: 4px 12px; margin-left: 2px }
.claims-grid .claim-grid-item .tags .nsfw { background: #e53935; text-align: center; color: #fff; position: relative; left: 1px }
-.claims-grid .claim-grid-item .tags .bid-state { background: #551CA1; text-align: center; color: #fff; }
.claims-grid .claim-grid-item .tags .content-type { background: #880e4f; text-align: center; color: #fff; }
-.claims-grid .claim-grid-item .blocked-info { padding: 24px; font-size: 90%; }
.claims-grid .claim-grid-item .metadata { padding: 24px; font-size: 90% }
.claims-grid .claim-grid-item .title { font-size: 120%; height: 25px; line-height: 25px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
.claims-grid .claim-grid-item .desc { font-size: 90%; font-weight: 300; height: 72px; overflow: hidden; text-overflow: ellipsis; margin: 8px 0 20px 0; line-height: 24px }
.claims-grid .claim-grid-item .link { font-size: 95%; font-weight: 300; margin-top: 3px; overflow: hidden; text-overflow: ellipsis; line-height: 20px; height: 20px; margin-top: 6px }
.claims-grid .claim-grid-item .label { font-size: 80%; color: #1e88e5 }
-.claims-grid .no-results {font-style: italic; width: 100%; height: 300px; text-align: center; font-size: 90%; color: grey; }
.claims-grid .claim-grid-item .value { font-weight: 300; word-break: break-word; word-wrap: break-word; font-size: 95%; line-height: 24px; height: 24px }
.claims-grid .claim-grid-item .half-width { width: 155px; float: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding-right: 12px }
.claims-grid .claim-grid-item .spacer { height: 16px }
.claims-body { width: 1200px; margin: 0 auto 0 auto; cursor: default }
-.claims-body .blocked-claim-info { border: 1px solid rgba(0,0,0,.15); cursor: default }
-.claims-body .blocked-claim-info .content { padding: 48px }
-.claims-body .claim-info { width: 400px; float: left; /*box-shadow: 0 2px 4px rgba(0,0,0,.175);*/ border: 1px solid rgba(0,0,0,.15); cursor: default }
+.claims-body .claim-info { width: 400px; float: left; box-shadow: 0 2px 4px rgba(0,0,0,.175); border: 1px solid rgba(0,0,0,.15); cursor: default }
.claims-body .claim-info .thumbnail { width: 100%; height: 220px; background: #f0f0f0; display: block; position: relative; overflow: hidden }
.claims-body .claim-info .thumbnail img { width: 100% }
.claims-body .claim-info .content { padding: 24px }
-.claims-body .claim-info .content .label { font-size: inherit; text-decoration: underline; color: #666666 }
+.claims-body .claim-info .content .label { font-size: 90%; color: #1e88e5 }
.claims-body .claim-info .content .value { font-weight: 300; margin-bottom: 24px; word-break: break-word; word-wrap: break-word }
.claims-body .claim-info .content .value:last-child { margin-bottom: 0 }
.claims-body .claim-info .content .half-width { width: 50%; float: left }
@@ -114,12 +108,12 @@ border-radius: 0 8px 8px 0 }
.claims-body .claim-info .thumbnail.yellow { background: #fdd835 }
.claims-body .claim-info .thumbnail .autothumb { display: block; margin: 93px auto 0 auto; text-align: center; font-size: 240%; color: #fff; line-height: 54px }
-.claims-body .claim-metadata { width: 770px; margin-left: 30px; float: left; /*box-shadow: 0 2px 4px rgba(0,0,0,.175);*/ border: 1px solid rgba(0,0,0,.15); padding: 24px 36px 88px 36px; cursor: default; position: relative }
-.claims-body .claim-metadata .title { font-weight: bold; font-size: 120%; margin-bottom: 16px; color: #666666; padding: 0 8px }
-.claims-body .claim-metadata .desc { font-weight: 300; font-size: inherit; line-height: 1.8em; padding: 0 12px; word-break: break-word; word-wrap: break-word }
+.claims-body .claim-metadata { width: 750px; margin-left: 50px; float: left; box-shadow: 0 2px 4px rgba(0,0,0,.175); border: 1px solid rgba(0,0,0,.15); padding: 24px 36px 88px 36px; cursor: default; position: relative }
+.claims-body .claim-metadata .title { font-weight: 300; font-size: 170%; margin-bottom: 16px; color: #1e88e5; padding: 0 8px }
+.claims-body .claim-metadata .desc { font-weight: 300; font-size: 130%; line-height: 36px; padding: 0 12px; word-break: break-word; word-wrap: break-word }
.claims-body .claim-metadata .details { margin-top: 36px; border-top: 1px solid #ddd; padding: 36px 16px 0 16px }
-.claims-body .claim-metadata .details .label { font-size: inherit; color: #666666; text-decoration: underline }
-.claims-body .claim-metadata .details .value { font-size: inherit; font-weight: 300; margin-bottom: 24px }
+.claims-body .claim-metadata .details .label { font-size: 90%; color: #1e88e5 }
+.claims-body .claim-metadata .details .value { font-size: 110%; font-weight: 300; margin-bottom: 24px }
.claims-body .claim-metadata .details .half-width { width: 50%; padding-right: 36px; float: left; height: 25px; line-height: 25px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis }
.claims-body .claim-metadata .open-lbry-link { position: absolute; right: 36px; bottom: 36px; padding: 10px 24px; color: #fff; font-weight: 300; font-size: 90%; background: #1e88e5 }
.claims-body .claim-metadata .open-lbry-link:hover { text-decoration: none; background: #1976d2 }
@@ -224,9 +218,7 @@ footer .content .page-time { position: absolute; right: 12px; bottom: 0px; paddi
.stats-main h3 { font-weight: 300; margin: 0 0 12px 0 }
.stats { width: 1000px; margin: 0 auto 48px auto; box-shadow: 0 2px 6px rgba(0,0,0,.175); border: 1px solid rgba(0,0,0,.15); padding: 24px; cursor: default }
-.stats .box { padding: 24px 0; border-right: 1px solid #ccc; float: left; text-align: center }
-.stats .box-20 { width: 20% }
-.stats .box-30 { width: 30% }
+.stats .box { padding: 24px 0; border-right: 1px solid #ccc; float: left; text-align: center; width: 25% }
.stats .box .title { color: #1e88e5; font-size: 90% }
.stats .box .value { font-size: 180%; font-weight: 300; margin-top: 8px }
.stats .box.last { border-color: transparent }
@@ -259,7 +251,6 @@ footer .content .page-time { position: absolute; right: 12px; bottom: 0px; paddi
.tx-details-layout .outputs .output .labels .support { background: #ffeb3b }
.tx-details-layout .outputs .output .labels .update { background: #ea80fc }
.tx-details-layout .outputs .output .labels .claim { background: #76ff03 }
-.tx-details-layout .outputs .output .view-claim { font-size: 80%; }
.tx-details-layout .inputs .input .value, .tx-details-layout .outputs .output .value { font-weight: normal }
.tx-details-layout .inputs .input.is-source, .tx-details-layout .outputs .output.is-source { border-right-width: 18px; border-right-color: #1e88e5; background: #e3f2fd }
.tx-details-layout .inputs .input.highlighted, .tx-details-layout .outputs .output.highlighted { background: #f1f8e9 }
@@ -303,7 +294,6 @@ footer .content .page-time { position: absolute; right: 12px; bottom: 0px; paddi
.tx-table td { vertical-align: top; line-height: 24px }
.tx-table td.credit, .tx-table td div.credit { color: #00e676 }
.tx-table td.debit, .tx-table td div.debit { color: #ff0000 }
-.tx-table td.diff, .tx-table td div.diff{ color: #337ab7 }
.tx-table td div.debit { padding-top: 8px }
.pagination { width: 1200px; margin: 36px auto 0 auto; cursor: default }
@@ -317,4 +307,4 @@ footer .content .page-time { position: absolute; right: 12px; bottom: 0px; paddi
@keyframes indeterminate {
from { left: -25%; }
to { left: 100% }
-}
+}
\ No newline at end of file
diff --git a/webroot/css/mining-inflation-chart.css b/webroot/css/mining-inflation-chart.css
deleted file mode 100644
index 92f1b34..0000000
--- a/webroot/css/mining-inflation-chart.css
+++ /dev/null
@@ -1,8 +0,0 @@
-.mining-inflation-chart-container { width: 1200px; margin: 0 auto 48px auto; box-shadow: 0 2px 6px rgba(0,0,0,.175); border: 1px solid rgba(0,0,0,.15); padding: 24px 36px; position: relative; overflow: hidden }
-.mining-inflation-chart-container .load-progress { position: absolute; top: 0; left: 0; width: 100%; height: 3px; background: #1e88e5; animation: indeterminate 4s linear infinite; }
-.mining-inflation-chart-container .chart { height: 414px }
-.mining-inflation-chart-container .btn-chart-export { position: absolute; right: 40px; bottom: 36px }
-@keyframes indeterminate {
- from { left: -70%; }
- to { left: 100% }
-}
\ No newline at end of file
diff --git a/webroot/embed.go b/webroot/embed.go
deleted file mode 100644
index b47eabd..0000000
--- a/webroot/embed.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// Package webroot contains the unchanged frontend assets shipped in the binary.
-package webroot
-
-import "embed"
-
-// Files includes chart/export libraries and their nested resources as well as
-// the explorer's scripts, styles and images. Source files are not embedded.
-//
-//go:embed all:amcharts all:css all:img all:js
-var Files embed.FS
diff --git a/webroot/img/lbry.png b/webroot/img/lbry.png
deleted file mode 100644
index dc58a66..0000000
Binary files a/webroot/img/lbry.png and /dev/null differ
diff --git a/webroot/index.php b/webroot/index.php
new file mode 100644
index 0000000..6791f47
--- /dev/null
+++ b/webroot/index.php
@@ -0,0 +1,37 @@
+emit($server->run());
diff --git a/webroot/js/bids-chart.js b/webroot/js/bids-chart.js
deleted file mode 100644
index e84d2db..0000000
--- a/webroot/js/bids-chart.js
+++ /dev/null
@@ -1,170 +0,0 @@
-function buildChartData(claimsData) {
- var chartData = [];
- var lastDate = 0;
- var nbClaimsDay = 0;
- var nbClaimsTotal = 0;
- var bidClaimsDay = 0;
- var bidClaimsTotal = 0;
- var nbChannelsDay = 0;
- var nbChannelsTotal = 0;
- for(var i = 0; i < claimsData.length; i++) {
- if(claimsData[i].transaction_time == 0) {
- continue;
- }
- var transactionDate = new Date(claimsData[i].transaction_time * 1000);
- transactionDate.setHours(0,0,0,0)
- if(lastDate == 0) {
- lastDate = transactionDate;
- }
- if(transactionDate.toString() != lastDate.toString()) {
- nbClaimsTotal += nbClaimsDay;
- bidClaimsTotal += bidClaimsDay;
- var dateData = {
- date: lastDate,
- NumberClaims: nbClaimsTotal,
- BidsClaims: bidClaimsTotal,
- };
- chartData.push(dateData);
- nbClaimsDay = 0;
- bidClaimsDay = 0;
- lastDate = transactionDate;
- }
- if(claimsData[i].claim_type == 1) {
- nbClaimsDay += 1;
- bidClaimsDay += claimsData[i].effective_amount/100000000;
- }
- }
- return chartData;
-}
-
-function loadChartData() {
- var api_url = "https://chainquery.odysee.tv/api/sql?query=";
- var query = "SELECT c1.claim_type, c1.bid_state, c1.effective_amount, c1.transaction_time, o.transaction_time AS 'spent_time' FROM claim c1 LEFT JOIN (SELECT output.claim_id, tx.transaction_time FROM output INNER JOIN input ON input.prevout_hash = output.transaction_hash AND input.prevout_n = output.vout INNER JOIN transaction tx ON tx.id = input.transaction_id) o ON o.claim_id=c1.claim_id AND c1.bid_state='Spent' ORDER BY c1.transaction_time ASC";
- var url = api_url + query;
- var loadProgress = $('.bids-chart-container .load-progress');
- $.ajax({
- url: url,
- type: 'get',
- dataType: 'json',
- beforeSend: function() {
- chartLoadInProgress = true;
- loadProgress.css({ display: 'block' });
- },
- success: function(response) {
- if(response.success) {
- chartData = buildChartData(response.data);
- if(chart) {
- chart.dataProvider = chartData;
- chart.validateNow();
- chart.validateData();
- }
- }
- else {
- console.log("Could not fetch block data.");
- }
- },
- complete: function() {
- chartLoadInProgress = false;
- loadProgress.css({ display: 'none' });
- }
-});
-}
-
-var chart;
-var chartData = [];
-var chartLoadInProgress = false;
-AmCharts.ready(function() {
-chart = AmCharts.makeChart('bids-chart', {
-type: 'serial',
-theme: 'light',
-mouseWheelZoomEnabled: true,
-height: '100%',
-categoryField: 'date',
-synchronizeGrid: true,
-dataProvider: chartData,
-responsive: {
- enabled: true,
-},
-valueAxes: [
-{
- id: 'v-number-claims',
- axisColor: '#1e88e5',
- axisThickness: 2,
- position: 'left',
-},
-{
- id: 'v-bids-claims',
- axisColor: '#0b7a06',
- axisThickness: 2,
- position: 'left',
- offset: 75,
-},
-],
-categoryAxis: {
-parseDates: true,
-autoGridCount: false,
-minorGridEnabled: true,
-minorGridAlpha: 0.04,
-axisColor: '#dadada',
-twoLineMode: true
-},
-graphs: [
-{
- id: 'g-number-claims',
- valueAxis: 'v-number-claims',
- title: 'Number of claims',
- valueField: 'NumberClaims',
- bullet: 'round',
- bulletBorderThickness: 1,
- bulletBorderAlpha: 1,
- bulletColor: '#ffffff',
- bulletSize: 5,
- useLineColorForBulletBorder: true,
- lineColor: '#1e88e5',
- hideBulletsCount: 101,
- balloonText: '[[NumberClaims]]',
-},
-{
- id: 'g-bids-claims',
- valueAxis: 'v-bids-claims',
- title: 'Bids for claims (LBC)',
- valueField: 'BidsClaims',
- bullet: 'round',
- bulletBorderThickness: 1,
- bulletBorderAlpha: 1,
- bulletColor: '#ffffff',
- bulletSize: 5,
- useLineColorForBulletBorder: true,
- lineColor: '#0b7a06',
- balloonText: '[[BidsClaims]] LBC',
- hideBulletsCount: 101
-},
-],
-chartCursor: {
-cursorAlpha: 0.1,
-fullWidth: true,
-valueLineBalloonEnabled: true,
-categoryBalloonColor: '#333333',
-cursorColor: '#1e88e5'
-},
-chartScrollbar: {
-scrollbarHeight: 36,
-color: '#888888',
-gridColor: '#bbbbbb'
-},
-legend: {
-marginLeft: 110,
-useGraphSettings: true,
-valueText: "",
-spacing: 64,
-
-},
-export: {
-enabled: true,
-fileName: 'lbry-bids-chart',
-position: 'bottom-right',
-divId: 'chart-export'
-}
-});
-loadChartData();
-});
diff --git a/webroot/js/block-size-chart.js b/webroot/js/block-size-chart.js
deleted file mode 100644
index 24aba9a..0000000
--- a/webroot/js/block-size-chart.js
+++ /dev/null
@@ -1,228 +0,0 @@
-var chart;
-var chartData = [];
-var chartLoadInProgress = false;
-var minPeriod = 'hh';
-var validPeriods = ['24h', '72h', '168h', '30d', '90d', '1y'];
-var defaultPeriod = (validPeriods.indexOf(localStorage.getItem('chartPeriod')) > -1) ? localStorage.getItem('chartPeriod') : '24h';
-var periodGridCounts = {'24h': 24, '72h': 24, '168h': 14, '30d': 30, '90d': 45, '1y': 12 };
-AmCharts.ready(function() {
- chart = AmCharts.makeChart('block-size-chart', {
- type: 'serial',
- theme: 'light',
- mouseWheelZoomEnabled: true,
- categoryField: 'date',
- synchronizeGrid: true,
- dataProvider: chartData,
- valueAxes: [
- {
- id: 'v-block-size',
- axisColor: '#1e88e5',
- axisThickness: 2,
- labelFunction: function(value) {
- return (Math.round((value / 1000) * 100)/100).toFixed(2) + ' KB';
- }
- },
- {
- id: 'v-price',
- axisColor: '#00e676',
- offset: 75,
- gridAlpha: 0,
- axisThickness: 2,
- labelFunction: function(value) {
- return '$' + value.toFixed(2);
- }
- }
- ],
- categoryAxis: {
- parseDates: true,
- minPeriod: minPeriod, // DD for daily
- autoGridCount: false,
- minorGridEnabled: true,
- minorGridAlpha: 0.04,
- axisColor: '#dadada',
- twoLineMode: true,
- dateFormats: [{
- period: 'fff',
- format: 'JJ:NN:SS'
- }, {
- period: 'ss',
- format: 'JJ:NN:SS'
- }, {
- period: 'mm',
- format: 'JJ:NN'
- }, {
- period: 'hh',
- format: 'JJ:NN'
- }, {
- period: 'DD',
- format: 'DD'
- }, {
- period: 'WW',
- format: 'DD MMM'
- }, {
- period: 'MM',
- format: 'MMM'
- }, {
- period: 'YYYY',
- format: 'YYYY'
- }]
- },
- graphs: [
- {
- id: 'g-block-size',
- valueAxis: 'v-block-size', // we have to indicate which value axis should be used
- title: 'Avg Block Size',
- valueField: 'AvgBlockSize',
- bullet: 'round',
- bulletBorderThickness: 1,
- bulletBorderAlpha: 1,
- bulletColor: '#ffffff',
- bulletSize: 5,
- useLineColorForBulletBorder: true,
- lineColor: '#1e88e5',
- hideBulletsCount: 101,
- balloonText: '[[AvgBlockSize]] KB',
- switchable: false,
- balloonFunction: function(item, graph) {
- var result = graph.balloonText;
- return result.replace('[[AvgBlockSize]]', (Math.round((item.dataContext.AvgBlockSize / 1000) * 100)/100).toFixed(2));
- }
- },
- {
- id: 'g-price',
- valueAxis: 'v-price',
- title: 'Average Price',
- valueField: 'AvgUSD',
- bullet: 'round',
- bulletBorderThickness: 1,
- bulletBorderAlpha: 1,
- bulletColor: '#ffffff',
- bulletSize: 5,
- useLineColorForBulletBorder: true,
- lineColor: '#00e676',
- balloonText: '$[[AvgUSD]]',
- balloonFunction: function(item, graph) {
- var result = graph.balloonText;
- if (!item.dataContext.AvgUSD) {
- return '';
- }
- return result.replace('[[AvgUSD]]', item.dataContext.AvgUSD.toFixed(2));
- },
- hideBulletsCount: 101,
- labelFunction: function(value) {
- return '$' + value;
- },
- }
- ],
- chartCursor: {
- cursorAlpha: 0.1,
- fullWidth: true,
- valueLineBalloonEnabled: true,
- categoryBalloonColor: '#333333',
- cursorColor: '#1e88e5',
- categoryBalloonDateFormat: minPeriod === 'hh' ? 'D MMM HH:NN ' : 'D MMM'
- },
- chartScrollbar: {
- scrollbarHeight: 36,
- color: '#888888',
- gridColor: '#bbbbbb'
- },
- legend: {
- marginLeft: 110,
- useGraphSettings: true,
- valueAlign: 'right',
- valueWidth: 60,
- spacing: 64,
- valueFunction: function(item, formatted) {
- if (item.dataContext) {
- var g = item.graph;
- if (g.id === 'g-block-size' && item.dataContext.AvgBlockSize > 0) {
- return g.balloonText.replace('[[AvgBlockSize]]', (Math.round((item.dataContext.AvgBlockSize / 1000) * 100)/100).toFixed(2) );
- }
- if (g.id === 'g-price' && item.dataContext.AvgUSD) {
- return g.balloonText.replace('[[AvgUSD]]', item.dataContext.AvgUSD.toFixed(2));
- }
- }
-
- return formatted;
- }
- },
- export: {
- enabled: true,
- fileName: 'lbry-block-size-chart',
- position: 'bottom-right',
- divId: 'chart-export'
- }
- });
-
- loadChartData(defaultPeriod);
-});
-
-var loadChartData = function(dataPeriod) {
- var loadProgress = $('.block-size-chart-container .load-progress');
- // clear previous chart data
- $.ajax({
- url: '/api/v1/charts/blocksize/' + dataPeriod,
- type: 'get',
- dataType: 'json',
- beforeSend: function() {
- chartLoadInProgress = true;
- loadProgress.css({ display: 'block' });
- },
- success: function(response) {
- if (response.success) {
- chartData = [];
- var data = response.data;
- for (var period in data) {
- if (data.hasOwnProperty(period)) {
- chartData.push({
- date: Date.parse(period),
- AvgBlockSize: data[period].AvgBlockSize,
- AvgUSD: data[period].AvgUSD
- });
- }
- }
-
- // save selcted period to localStorage
- localStorage.setItem('chartPeriod', dataPeriod);
-
- if (chart) {
- var isHourly = (dataPeriod.indexOf('h') > -1);
- var gridCount = periodGridCounts[dataPeriod];
- chart.categoryAxis.minPeriod = isHourly ? 'hh' : 'DD';
- chart.categoryAxis.dateFormats[4].format = isHourly ? 'DD MMM' : 'DD';
- chart.chartCursor.categoryBalloonDateFormat = isHourly ? 'D MMM HH:NN ' : 'D MMM YYYY';
- chart.categoryAxis.gridCount = gridCount;
- chart.chartScrollbar.gridCount = gridCount;
- chart.dataProvider = chartData;
- chart.validateNow();
- chart.validateData();
- }
- }
- },
- complete: function() {
- chartLoadInProgress = false;
- loadProgress.css({ display: 'none' });
- }
- });
-};
-
-$(document).ready(function() {
- $('.block-size-data-links a').on('click', function(evt) {
- evt.preventDefault();
- if (chartLoadInProgress) {
- return;
- }
-
- var link = $(this);
- if (link.hasClass('active')) {
- return;
- }
-
- link.addClass('active').siblings().removeClass('active');
- var period = link.attr('data-period');
- loadChartData(period);
- });
-
- $('a[data-period="' + defaultPeriod + '"]').addClass('active').siblings().removeClass('active');
-});
\ No newline at end of file
diff --git a/webroot/js/mining-inflation-chart.js b/webroot/js/mining-inflation-chart.js
deleted file mode 100644
index fb03bf7..0000000
--- a/webroot/js/mining-inflation-chart.js
+++ /dev/null
@@ -1,318 +0,0 @@
-var PREMINE_REWARD = 400000000;
-var INITIAL_REWARD_END_HEIGHT = 5100;
-var REWARD_RAMP_END_HEIGHT = 55000;
-var REWARD_RAMP_GROUP_SIZE = 100;
-var REWARD_REDUCTION_GROUP_SIZE = 32;
-var MAX_STANDARD_REWARD = 500;
-var SECONDS_PER_YEAR = 60 * 60 * 24 * 365;
-var DEFAULT_BLOCK_TIME = 150;
-
-function getReward(blockHeight) {
- if (blockHeight == 0) {
- return PREMINE_REWARD;
- }
- else if (blockHeight <= INITIAL_REWARD_END_HEIGHT) {
- return 1;
- }
- else if (blockHeight <= REWARD_RAMP_END_HEIGHT) {
- return 1 + Math.floor((blockHeight - (INITIAL_REWARD_END_HEIGHT - REWARD_RAMP_GROUP_SIZE + 1)) / REWARD_RAMP_GROUP_SIZE);
- }
- else {
- var level = Math.floor((blockHeight - (REWARD_RAMP_END_HEIGHT + 1)) / REWARD_REDUCTION_GROUP_SIZE);
- var reduction = Math.floor((Math.floor(Math.sqrt((8 * level) + 1)) - 1) / 2);
- while(!(withinLevelBounds(reduction, level))) {
- if(Math.floor((reduction * reduction + reduction) / 2) > level) {
- reduction--;
- }
- else {
- reduction++;
- }
- }
- return Math.max(0, MAX_STANDARD_REWARD - reduction);
- }
-}
-
-function withinLevelBounds(reduction, level) {
- if(Math.floor((reduction * reduction + reduction) / 2) > level) {
- return false;
- }
- reduction += 1;
- if(Math.floor((reduction * reduction + reduction) / 2) <= level) {
- return false;
- }
- return true;
-}
-
-function getAverageBlockTime(blocks) {
- if (blocks.length < 2) {
- return DEFAULT_BLOCK_TIME;
- }
-
- var sum = 0;
- var intervals = 0;
- for(var i = 1; i < blocks.length; i++) {
- var blockTime = blocks[i].block_time - blocks[i - 1].block_time;
- if (blockTime > 0) {
- sum += blockTime;
- intervals++;
- }
- }
- return intervals > 0 ? sum / intervals : DEFAULT_BLOCK_TIME;
-}
-
-function getSupply(blockHeight) {
- if (blockHeight < 0) {
- return 0;
- }
-
- var supply = PREMINE_REWARD;
- supply += Math.min(blockHeight, INITIAL_REWARD_END_HEIGHT);
-
- if (blockHeight > INITIAL_REWARD_END_HEIGHT) {
- var rampBlocks = Math.min(blockHeight, REWARD_RAMP_END_HEIGHT) - INITIAL_REWARD_END_HEIGHT;
- var completeRampGroups = Math.floor(rampBlocks / REWARD_RAMP_GROUP_SIZE);
- var remainingRampBlocks = rampBlocks % REWARD_RAMP_GROUP_SIZE;
- supply += REWARD_RAMP_GROUP_SIZE * completeRampGroups * (completeRampGroups + 3) / 2;
- supply += remainingRampBlocks * (completeRampGroups + 2);
- }
-
- if (blockHeight > REWARD_RAMP_END_HEIGHT) {
- var reductionBlocks = blockHeight - REWARD_RAMP_END_HEIGHT;
- var completeReductionGroups = Math.floor((Math.sqrt(1 + (reductionBlocks / 4)) - 1) / 2);
- completeReductionGroups = Math.min(completeReductionGroups, MAX_STANDARD_REWARD);
- var completedReductionBlocks = REWARD_REDUCTION_GROUP_SIZE * completeReductionGroups * (completeReductionGroups + 1) / 2;
- var remainingReductionBlocks = reductionBlocks - completedReductionBlocks;
- var completedReductionSupply = REWARD_REDUCTION_GROUP_SIZE * (
- MAX_STANDARD_REWARD * completeReductionGroups * (completeReductionGroups + 1) / 2 -
- completeReductionGroups * (completeReductionGroups - 1) * (completeReductionGroups + 1) / 3
- );
- supply += completedReductionSupply;
- supply += remainingReductionBlocks * Math.max(0, MAX_STANDARD_REWARD - completeReductionGroups);
- }
-
- return supply;
-}
-
-function buildChartData(data) {
- var samples = data.samples || [];
- var recentBlocks = data.recent || [];
- if (samples.length === 0) {
- return [];
- }
-
- var chartData = [];
- var averageBlockTime = getAverageBlockTime(recentBlocks);
- var blocksPerYear = Math.max(1, Math.floor(SECONDS_PER_YEAR / averageBlockTime));
- var currentBlock = samples[samples.length - 1];
- var currentHeight = Number(currentBlock.height);
- var currentBlockTime = Number(currentBlock.block_time);
- var lastRewardBlock = Number(data.last_reward_block);
- var futureSampleInterval = Number(data.future_sample_interval);
- var points = [];
-
- for (var sampleIndex = 0; sampleIndex < samples.length; sampleIndex++) {
- points.push({
- height: Number(samples[sampleIndex].height),
- blockTime: Number(samples[sampleIndex].block_time)
- });
- }
-
- var nextFutureHeight = Math.ceil((currentHeight + 1) / futureSampleInterval) * futureSampleInterval;
- for (var futureHeight = nextFutureHeight; futureHeight <= lastRewardBlock; futureHeight += futureSampleInterval) {
- points.push({
- height: futureHeight,
- blockTime: currentBlockTime + ((futureHeight - currentHeight) * averageBlockTime)
- });
- }
- if (points[points.length - 1].height !== lastRewardBlock) {
- points.push({
- height: lastRewardBlock,
- blockTime: currentBlockTime + ((lastRewardBlock - currentHeight) * averageBlockTime)
- });
- }
-
- for (var pointIndex = 0; pointIndex < points.length; pointIndex++) {
- var point = points[pointIndex];
- var supply = getSupply(point.height);
- var lastYearHeight = Math.max(0, point.height - blocksPerYear);
- var lastYearSupply = getSupply(lastYearHeight);
- var inflationRate = lastYearSupply > 0 ? ((supply - lastYearSupply) / lastYearSupply) * 100 : 0;
-
- chartData.push({
- date: new Date(point.blockTime * 1000),
- AvailableSupply: supply,
- RewardLBC: point.height === 0 ? 0 : getReward(point.height),
- InflationRate: inflationRate,
- BlockId: point.height
- });
- }
-
- return chartData;
-}
-
-function loadChartData() {
- var loadProgress = $('.mining-inflation-chart-container .load-progress');
- $.ajax({
- url: '/api/v1/charts/inflation',
- type: 'get',
- dataType: 'json',
- beforeSend: function() {
- chartLoadInProgress = true;
- loadProgress.css({ display: 'block' });
- },
- success: function(response) {
- if(response.success) {
- chartData = buildChartData(response.data);
- if(chart) {
- chart.dataProvider = chartData;
- chart.validateNow();
- chart.validateData();
- }
- }
- else {
- $('#mining-inflation-chart').text('Unable to load inflation chart data.');
- }
- },
- error: function() {
- $('#mining-inflation-chart').text('Unable to load inflation chart data.');
- },
- complete: function() {
- chartLoadInProgress = false;
- loadProgress.css({ display: 'none' });
- }
- });
-}
-
-var chart;
-var chartData = [];
-var chartLoadInProgress = false;
-AmCharts.ready(function() {
-chart = AmCharts.makeChart('mining-inflation-chart', {
-type: 'serial',
-theme: 'light',
-mouseWheelZoomEnabled: true,
-height: '100%',
-categoryField: 'date',
-synchronizeGrid: true,
-dataProvider: chartData,
-responsive: {
- enabled: true,
-},
-valueAxes: [
-{
- id: 'v-supply',
- axisColor: '#1e88e5',
- axisThickness: 2,
- position: 'left',
- labelFunction: function(value) {
- return (Math.round((value / 1000000) * 1000000)/1000000).toFixed(2);
- }
-},
-{
- id: 'v-reward',
- axisColor: '#0b7a06',
- axisThickness: 2,
- position: 'left',
- offset: 75,
-},
-{
- id: 'v-inflation-rate',
- axisColor: '#ff9900',
- axisThickness: 2,
- position: 'right',
- labelFunction: function(value) {
- return value.toFixed(2);
- }
-},
-],
-categoryAxis: {
-parseDates: true,
-autoGridCount: false,
-minorGridEnabled: true,
-minorGridAlpha: 0.04,
-axisColor: '#dadada',
-twoLineMode: true
-},
-graphs: [
-{
- id: 'g-supply',
- valueAxis: 'v-supply', // we have to indicate which value axis should be used
- title: 'Available supply (millions LBC)',
- valueField: 'AvailableSupply',
- bullet: 'round',
- bulletBorderThickness: 1,
- bulletBorderAlpha: 1,
- bulletColor: '#ffffff',
- bulletSize: 5,
- useLineColorForBulletBorder: true,
- lineColor: '#1e88e5',
- hideBulletsCount: 101,
- balloonText: '[[AvailableSupply]]',
- balloonFunction: function(item, graph) {
- var result = graph.balloonText;
- return result.replace('[[AvailableSupply]]', (Math.round((item.dataContext.AvailableSupply / 1000000) * 1000000)/1000000).toFixed(2));
- }
-},
-{
- id: 'g-reward',
- valueAxis: 'v-reward',
- title: 'Block Reward (LBC)',
- valueField: 'RewardLBC',
- bullet: 'round',
- bulletBorderThickness: 1,
- bulletBorderAlpha: 1,
- bulletColor: '#ffffff',
- bulletSize: 5,
- useLineColorForBulletBorder: true,
- lineColor: '#0b7a06',
- balloonText: '[[RewardLBC]] LBC
Block [[BlockId]]',
- hideBulletsCount: 101
-},
-{
- id: 'g-inflation-rate',
- valueAxis: 'v-inflation-rate',
- title: 'Annualized Inflation Rate',
- valueField: 'InflationRate',
- bullet: 'round',
- bulletBorderThickness: 1,
- bulletBorderAlpha: 1,
- bulletColor: '#ffffff',
- bulletSize: 5,
- useLineColorForBulletBorder: true,
- lineColor: '#ff9900',
- balloonText: '[[InflationRate]]%',
- hideBulletsCount: 101,
- balloonFunction: function(item, graph) {
- var result = graph.balloonText;
- return result.replace('[[InflationRate]]', item.dataContext.InflationRate.toFixed(2));
- }
-}
-],
-chartCursor: {
-cursorAlpha: 0.1,
-fullWidth: true,
-valueLineBalloonEnabled: true,
-categoryBalloonColor: '#333333',
-cursorColor: '#1e88e5'
-},
-chartScrollbar: {
-scrollbarHeight: 36,
-color: '#888888',
-gridColor: '#bbbbbb'
-},
-legend: {
-marginLeft: 110,
-useGraphSettings: true,
-valueText: "",
-spacing: 64,
-
-},
-export: {
-enabled: true,
-fileName: 'lbry-supply-chart',
-position: 'bottom-right',
-divId: 'chart-export'
-}
-});
-loadChartData();
-});